Module_OcppBackend.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. #include "Module_OcppBackend.h"
  2. typedef enum boolean { FALSE, TRUE } BOOL;
  3. struct lws *wsi_client;
  4. struct lws_context *context;
  5. static int req_SendQueue = 0;
  6. pthread_t tid_connectServer;
  7. pthread_t tid_ProcQueue;
  8. pthread_t tid_Watchdog;
  9. struct StartTime
  10. {
  11. struct timespec connect;
  12. struct timespec bootNotification;
  13. struct timespec reConnect;
  14. struct timespec startTimeDog;
  15. struct timespec startTimeQueue;
  16. struct timespec pingOn;
  17. }startTime;
  18. struct QueueOpInfo queueOpInfo;
  19. //==========================================
  20. // Function prototype
  21. //==========================================
  22. void ReceivedMessage(void *in, size_t len);
  23. int SendBufLen=0;//(1024*4);//(1024*3);
  24. unsigned char SendBuffer[WEBSOCKET_BUFFER_SIZE]={0};
  25. static int ConnectionEstablished=0;
  26. int defaultWaitingTime = 10; //10 second
  27. char OcppPath[384]={0};
  28. char OcppProtocol[10]={0},OcppHost[128]={0}, OcppTempPath[256]={0};
  29. int OcppPort=0;
  30. unsigned char StartTransactionIdTagTemp[20]={0};
  31. uint8_t isWebsocketSendable = 1;
  32. uint8_t isQueueSendable = 1;
  33. uint8_t counterLwsRestart = 0;
  34. uint8_t counterQueueSent = 0;
  35. uint8_t counterConnect = 0;
  36. uint8_t counterPingSend = 0;
  37. sqlite3 *db;
  38. char *errMsg = NULL;
  39. static char *createsql = "CREATE TABLE IF NOT EXISTS log_buffer("
  40. "idx integer primary key,"
  41. "user_id text,"
  42. "cmd_sn text,"
  43. "charger_id text,"
  44. "gun_type text,"
  45. "gun_no text,"
  46. "rfid_no text,"
  47. "stime text,"
  48. "etime text,"
  49. "time_len text,"
  50. "s_soc text,"
  51. "e_soc text,"
  52. "stop_reason text,"
  53. "power text,"
  54. "meter_before text,"
  55. "meter_after text,"
  56. "charge_price text,"
  57. "reserve text,"
  58. "surplus_before text,"
  59. "surplus_after text,"
  60. "service_price text,"
  61. "is_pay text,"
  62. "charge_strategy text,"
  63. "charge_parameter text,"
  64. "vin text,"
  65. "vehicle_no text,"
  66. "start_method text,"
  67. "card_type text,"
  68. "is_upload text,"
  69. "guid text UNIQUE,"
  70. "is_buf2OK text);";
  71. static char *sqlOcppAuthCache = "create table if not exists ocpp_auth_cache (idx integer primary key,"
  72. "idtag text UNIQUE,"
  73. "parent_idtag text,"
  74. "expir_date text,"
  75. "status text);";
  76. static char *sqlOcppAuthLocal = "create table if not exists ocpp_auth_local (idx integer primary key,"
  77. "idtag text UNIQUE,"
  78. "parent_idtag text,"
  79. "expir_date text,"
  80. "status text,"
  81. "version text);";
  82. static char *sqlTransaction = "create table if not exists ocpp_transaction_record (idx integer primary key,"
  83. "occurDatetime text,"
  84. "message_type text,"
  85. "message_content text);";
  86. static char *sqlPeriodEnergy = "create table if not exists ocpp_period_energy ( transactionId integer primary key UNIQUE,"
  87. "connectorId integer,"
  88. "occurDatetime text,"
  89. "periodEnergy text);";
  90. //=================================
  91. // Common routine
  92. //=================================
  93. int GetTransactionQueueNum(void)
  94. {
  95. return queueOpInfo.TransactionQueueNum;
  96. }
  97. //==========================================
  98. // Web socket tranceive routine
  99. //==========================================
  100. int SendData(struct lws *wsi)
  101. {
  102. int n;
  103. int len;
  104. unsigned char out[LWS_SEND_BUFFER_PRE_PADDING + ARRAY_SIZE(SendBuffer) + LWS_SEND_BUFFER_POST_PADDING] = {0};
  105. len = strlen((char *)SendBuffer);
  106. if(len == 0)return 0;
  107. if((strstr((char*)SendBuffer, "\"MeterValues\"") != NULL)
  108. || (strstr((char*)SendBuffer, "\"StartTransaction\"") != NULL)
  109. || (strstr((char*)SendBuffer, "\"StopTransaction\"") != NULL))
  110. {
  111. isQueueSendable = 0;
  112. }
  113. memcpy (out + LWS_SEND_BUFFER_PRE_PADDING, SendBuffer, len );
  114. DEBUG_OCPPMESSAGE_INFO("===========> %s\n", out + LWS_SEND_BUFFER_PRE_PADDING);
  115. n = lws_write(wsi, out + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
  116. memset(SendBuffer, 0, len);
  117. SendBufLen = 0;
  118. return n;
  119. }
  120. int SendPing(struct lws *wsi)
  121. {
  122. uint8_t ping[LWS_PRE + 125];
  123. DEBUG_OCPPMESSAGE_INFO("===========> Set PING packet.\n");
  124. return lws_write(wsi, ping + LWS_PRE, 0, LWS_WRITE_PING);
  125. }
  126. static int OCPP16Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
  127. {
  128. char buf[256]={0}, hash[20]={0}, key_b64[40]={0}, tempin[WEBSOCKET_BUFFER_SIZE]={0}, sstr[WEBSOCKET_BUFFER_SIZE]={0};
  129. uint8_t auth_b64[256]={0}, boxId[128]={0}, password[64]={0};
  130. int c = 0;
  131. char *loc;
  132. switch (reason)
  133. {
  134. case LWS_CALLBACK_PROTOCOL_INIT:
  135. DEBUG_INFO("LWS_CALLBACK_PROTOCOL_INIT\n");
  136. break;
  137. case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH:
  138. DEBUG_INFO("LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH\n");
  139. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Client Request START -----\n");
  140. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_URI);
  141. DEBUG_OCPPMESSAGE_INFO("GET %s HTTP/1.1 \n", buf);
  142. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_HOST);
  143. DEBUG_OCPPMESSAGE_INFO("Host: %s\n", buf);
  144. DEBUG_OCPPMESSAGE_INFO("Upgrade: websocket\n");
  145. DEBUG_OCPPMESSAGE_INFO("Connection: Upgrade\n");
  146. lws_b64_encode_string(hash, 16, key_b64, ARRAY_SIZE(key_b64));// Sec-WebSocket-Key
  147. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Key: %s\n", key_b64);
  148. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
  149. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  150. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Version: %d\n", SPEC_LATEST_SUPPORTED);
  151. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Client Request END -----\n");
  152. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Server response START -----\n");
  153. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_HTTP);
  154. DEBUG_OCPPMESSAGE_INFO("HTTP/1.1 %s\n", buf);
  155. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_UPGRADE);
  156. DEBUG_OCPPMESSAGE_INFO("Upgrade: %s\n", buf);
  157. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_CONNECTION);
  158. DEBUG_OCPPMESSAGE_INFO("Connection: %s\n", buf);
  159. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_ACCEPT);
  160. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Accept: %s\n", buf);
  161. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_PROTOCOL);
  162. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  163. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Server response END -----\n");
  164. SetOcppVersion((uint8_t*)buf);
  165. break;
  166. case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
  167. DEBUG_INFO("LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION\n");
  168. break;
  169. case LWS_CALLBACK_WSI_DESTROY:
  170. DEBUG_INFO("LWS_CALLBACK_WSI_DESTROY\n");
  171. pthread_detach(tid_connectServer);
  172. SetServerSign(FALSE);
  173. ConnectionEstablished = 0;
  174. context = NULL;
  175. break;
  176. case LWS_CALLBACK_LOCK_POLL:
  177. break;
  178. case LWS_CALLBACK_ADD_POLL_FD:
  179. DEBUG_INFO("LWS_CALLBACK_ADD_POLL_FD\n");
  180. break;
  181. case LWS_CALLBACK_DEL_POLL_FD:
  182. DEBUG_INFO("LWS_CALLBACK_DEL_POLL_FD\n");
  183. break;
  184. case LWS_CALLBACK_UNLOCK_POLL:
  185. break;
  186. case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
  187. break;
  188. case LWS_CALLBACK_WSI_CREATE:
  189. DEBUG_INFO("LWS_CALLBACK_WSI_CREATE\n");
  190. break;
  191. case LWS_CALLBACK_GET_THREAD_ID:
  192. break;
  193. case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
  194. DEBUG_INFO("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
  195. unsigned char** pos = (unsigned char**)in;
  196. unsigned char* end = (*pos) + len;
  197. switch(GetOcppSecurityProfile())
  198. {
  199. case 1:
  200. case 2:
  201. case 3:
  202. GetOcppChargerBoxId(boxId);
  203. GetOcppSecurityPassword(password);
  204. sprintf(buf, "%s:%s", boxId, password);
  205. lws_b64_encode_string(buf, strlen(buf), (char*)auth_b64, ARRAY_SIZE(auth_b64));
  206. sprintf(buf, "Basic %s", auth_b64);
  207. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_AUTHORIZATION, (uint8_t *)buf, strlen(buf), pos, end))
  208. {
  209. DEBUG_ERROR("lws_add_http_header_by_token : WSI_TOKEN_HTTP_AUTHORIZATION\n");
  210. return -1;
  211. }
  212. DEBUG_OCPPMESSAGE_INFO("Authorization: %s\n", buf);
  213. break;
  214. case 0:
  215. default:
  216. break;
  217. }
  218. break;
  219. case LWS_CALLBACK_CLIENT_ESTABLISHED: //3
  220. DEBUG_INFO("LWS_CALLBACK_CLIENT_ESTABLISHED\n");
  221. //connected
  222. ConnectionEstablished=1;
  223. SetOcppConnStatus(TRUE);
  224. refreshStartTimer(&startTime.pingOn);
  225. queueOpInfo.TransactionMessageResend = 0;
  226. break;
  227. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR://1
  228. DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR %s\n", (char *)in );
  229. //disconnected
  230. ConnectionEstablished=0;
  231. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Client START =====\n");
  232. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_URI);
  233. DEBUG_OCPPMESSAGE_INFO("GET %s HTTP/1.1 \n", buf);
  234. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_HOST);
  235. DEBUG_OCPPMESSAGE_INFO("Host: %s\n", buf);
  236. DEBUG_OCPPMESSAGE_INFO("Upgrade: websocket\n");
  237. DEBUG_OCPPMESSAGE_INFO("Connection: Upgrade\n");
  238. lws_b64_encode_string(hash, 16, key_b64, ARRAY_SIZE(key_b64));// Sec-WebSocket-Key
  239. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Key: %s\n", key_b64);
  240. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
  241. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  242. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Version: %d\n", SPEC_LATEST_SUPPORTED);
  243. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Client END =====\n");
  244. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Server response START =====\n");
  245. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_HTTP);
  246. DEBUG_OCPPMESSAGE_INFO("HTTP/1.1 %s\n", buf);
  247. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_UPGRADE);
  248. DEBUG_OCPPMESSAGE_INFO("Upgrade: %s\n", buf);
  249. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_CONNECTION);
  250. DEBUG_OCPPMESSAGE_INFO("Connection: %s\n", buf);
  251. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_ACCEPT);
  252. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Accept: %s\n", buf);
  253. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_PROTOCOL);
  254. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  255. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Server response END =====\n");
  256. break;
  257. case LWS_CALLBACK_CLOSED://4
  258. DEBUG_INFO("LWS_CALLBACK_CLOSED\n");
  259. //disconnected
  260. ConnectionEstablished=0;
  261. break;
  262. case LWS_CALLBACK_CLIENT_WRITEABLE://10
  263. if(isWebsocketSendable && (0 < GetWebSocketPingInterval()) && (GetWebSocketPingInterval() <= getDiffSecNow(startTime.pingOn)) && (GetServerSign() == TRUE))
  264. SendPing(wsi);
  265. else
  266. SendData(wsi);
  267. break;
  268. case LWS_CALLBACK_CLIENT_RECEIVE://8
  269. ((char *)in)[len] = '\0';
  270. DEBUG_OCPPMESSAGE_INFO("<===== %s\n", (char *)in);
  271. //**********Receive Message**********/
  272. c = 0;
  273. loc = strstr((const char *)in, "][2,");
  274. if(loc == NULL)
  275. {
  276. loc = strstr((const char *)in, "][3,");
  277. if(loc == NULL)
  278. {
  279. loc = strstr((const char *)in, "][4,");
  280. }
  281. }
  282. memset(sstr, 0, ARRAY_SIZE(sstr) );
  283. if(loc != NULL)
  284. {
  285. DEBUG_INFO("There are continuous second packet []\n");
  286. while (loc[1+c] != '\0')
  287. {
  288. sstr[c] = loc[1+c];
  289. c++;
  290. }
  291. sstr[c] = '\0';
  292. strcpy(tempin, sstr);
  293. DEBUG_INFO("Final Receive: %s\n", tempin);
  294. }
  295. else
  296. {
  297. strcpy(tempin,(char *)in);
  298. }
  299. ReceivedMessage((void *)strtrim(tempin), strlen(tempin));
  300. isWebsocketSendable = 1;
  301. refreshStartTimer(&startTime.pingOn);
  302. break;
  303. case LWS_CALLBACK_CLIENT_RECEIVE_PONG:
  304. DEBUG_INFO("LWS_CALLBACK_CLIENT_RECEIVE_PONG\n");
  305. DEBUG_OCPPMESSAGE_INFO("<===== Get PONG packet.\n");
  306. refreshStartTimer(&startTime.pingOn);
  307. isWebsocketSendable = 1;
  308. counterPingSend = 0;
  309. break;
  310. case LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION:
  311. DEBUG_INFO("LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION\n");
  312. break;
  313. case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS:
  314. DEBUG_INFO("LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS\n");
  315. break;
  316. case LWS_CALLBACK_PROTOCOL_DESTROY:
  317. DEBUG_INFO("LWS_CALLBACK_PROTOCOL_DESTROY\n");
  318. break;
  319. case LWS_CALLBACK_RECEIVE_PONG:
  320. DEBUG_INFO("LWS_CALLBACK_RECEIVE_PONG\n");
  321. break;
  322. case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE:
  323. DEBUG_INFO("LWS_CALLBACK_WS_PEER_INITIATED_CLOSE\n");
  324. break;
  325. case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
  326. DEBUG_INFO("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
  327. if(GetInternetConn() == 1)
  328. {
  329. DEBUG_INFO("Download new CA certification.\n", system("wget --no-check-certificate -O /root/cacert.pem http://curl.haxx.se/ca/cacert.pem &"));
  330. }
  331. break;
  332. default:
  333. DEBUG_INFO("Reason = %d\n", reason);
  334. break;
  335. }
  336. return 0;
  337. }
  338. static struct lws_protocols protocols[] =
  339. {
  340. {
  341. "ocpp1.6",
  342. OCPP16Callback,
  343. WEBSOCKET_BUFFER_SIZE,
  344. WEBSOCKET_BUFFER_SIZE,
  345. },
  346. {
  347. "ocpp2.0",
  348. OCPP16Callback,
  349. WEBSOCKET_BUFFER_SIZE,
  350. WEBSOCKET_BUFFER_SIZE,
  351. },
  352. {
  353. "ocpp1.6,ocpp2.0",
  354. OCPP16Callback,
  355. WEBSOCKET_BUFFER_SIZE,
  356. WEBSOCKET_BUFFER_SIZE,
  357. },
  358. {
  359. NULL, NULL, 0 /* End of list */
  360. }
  361. };
  362. void* ConnectWsServer(void* data) //int ConnectWsServer()
  363. {
  364. struct lws_context_creation_info ContextInfo;
  365. struct lws_client_connect_info ConnInfo;
  366. int use_ssl=0;
  367. counterConnect += 1;
  368. // If internet available synchronize datetime with ntp server
  369. if(GetInternetConn() == 1)
  370. {
  371. system("pkill ntpd");
  372. DEBUG_INFO("NTP synchronize with Microsoft\n", system("/usr/sbin/ntpd -nqp time.windows.com &"));
  373. DEBUG_INFO("NTP synchronize with China\n", system("/usr/sbin/ntpd -nqp cn.ntp.org.cn &"));
  374. DEBUG_INFO("NTP synchronize with Taiwan\n", system("/usr/sbin/ntpd -nqp tock.stdtime.gov.tw &"));
  375. DEBUG_INFO("NTP synchronize with Europe\n", system("/usr/sbin/ntpd -nqp 0.europe.pool.ntp.org &"));
  376. }
  377. if(context!=NULL)
  378. {
  379. pthread_detach(pthread_self());
  380. lws_context_destroy(context);
  381. ConnectionEstablished=0;
  382. context = NULL;
  383. }
  384. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  385. if((GetOcppServerURL()==0) || (GetOcppPort() == 0) || (GetOcppPath()==0))
  386. {
  387. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  388. goto end;
  389. }
  390. if((strcmp(OcppProtocol,"ws")==0)&&(strlen(OcppProtocol)== 2))
  391. {
  392. DEBUG_INFO("Web socket is non-security mode.\n");
  393. use_ssl=0;
  394. }
  395. else if((strcmp(OcppProtocol,"wss")==0)&&(strlen(OcppProtocol)== 3))
  396. {
  397. DEBUG_INFO("Web socket is security mode.\n");
  398. use_ssl=1;
  399. }
  400. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  401. ContextInfo.iface = NULL;
  402. ContextInfo.ssl_private_key_password = NULL;
  403. ContextInfo.ssl_cert_filepath = NULL;//"./ssl_key/client_cert.pem";
  404. ContextInfo.ssl_private_key_filepath = NULL;//"./ssl_key/client_key.pem";
  405. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";//"./cacert.pem";
  406. ContextInfo.ssl_cipher_list = NULL; //use default one
  407. ContextInfo.gid = -1;
  408. ContextInfo.uid = -1;
  409. if(use_ssl)
  410. {
  411. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT ;
  412. }
  413. ContextInfo.protocols = protocols;
  414. ContextInfo.timeout_secs = GetBackendConnectionTimeout();
  415. //ContextInfo.ws_ping_pong_interval = GetWebSocketPingInterval();
  416. ContextInfo.ka_time = 20;
  417. ContextInfo.keepalive_timeout = 5;
  418. ContextInfo.ka_probes = 2;
  419. ContextInfo.ka_interval = 5;
  420. context = lws_create_context(&ContextInfo);
  421. if (context == NULL)
  422. {
  423. DEBUG_ERROR("lws_create_context NG");
  424. goto end;
  425. }
  426. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  427. // fill up below information
  428. ConnInfo.context = context;
  429. ConnInfo.address=(const char *)OcppHost;
  430. DEBUG_INFO("ConnInfo.address: %s\n", ConnInfo.address);
  431. ConnInfo.port = GetOcppPort();
  432. DEBUG_INFO("ConnInfo.port: %d\n", ConnInfo.port);
  433. ConnInfo.path=(const char *)OcppPath;
  434. DEBUG_INFO("ConnInfo.path: %s\n", ConnInfo.path);
  435. char addr_port[256] = { 0 };
  436. sprintf(addr_port, "%s:%u", ConnInfo.address, (ConnInfo.port & 65535) );
  437. ConnInfo.host= addr_port; // ConnInfo.address;//lws_canonical_hostname(context);
  438. //ConnInfo.origin="origin";
  439. ConnInfo.protocol = protocols[0].name;
  440. ConnInfo.ietf_version_or_minus_one = -1;
  441. if(use_ssl)
  442. {
  443. #ifdef TLS_VALID_CERT_EXPIRED
  444. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
  445. DEBUG_INFO("TLS does not allow expired certification.\n");
  446. #else
  447. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK | LCCSCF_ALLOW_EXPIRED;
  448. DEBUG_INFO("TLS allow expired certification.\n");
  449. #endif
  450. }
  451. wsi_client = lws_client_connect_via_info(&ConnInfo);
  452. if (!wsi_client)
  453. {
  454. DEBUG_ERROR("lws_client_connect_via_info NG\n");
  455. goto end;
  456. }
  457. counterConnect=0;
  458. DEBUG_INFO("counterConnect: %d\n", counterConnect);
  459. end:
  460. pthread_exit(NULL/*(void *) fname*/);
  461. }
  462. int isQueueOverSize()
  463. {
  464. FILE *fp;
  465. uint32_t file_size;
  466. uint8_t result = FALSE;
  467. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  468. if(fp != NULL)
  469. {
  470. fseek(fp, 0L, SEEK_END);
  471. file_size = ftell(fp);
  472. if(file_size > (500*1024*1024))
  473. {
  474. result = TRUE;
  475. DEBUG_WARN("Queue file over size.\n");
  476. }
  477. fclose(fp);
  478. }
  479. return result;
  480. }
  481. int showfront(char *uuid, char *data)
  482. {
  483. FILE *fp;
  484. int result = FALSE; // 1: TRUE 0:FALSE
  485. char str[QUEUE_MESSAGE_LENGTH]={0};
  486. char sstr[50]={ 0 };//sstr[200]={ 0 };
  487. int c = 0;
  488. char *loc;
  489. char rmFileCmd[100]={0};
  490. struct stat stats;
  491. stat("/Storage/OCPP", &stats);
  492. // Check for directory existence
  493. if (S_ISDIR(stats.st_mode) == 1)
  494. {
  495. //DEBUG_INFO("\n OCPP directory exist \n");
  496. }
  497. else
  498. {
  499. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  500. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  501. system(rmFileCmd);
  502. }
  503. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  504. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  505. {
  506. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  507. }
  508. else
  509. {
  510. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  511. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  512. if(log == NULL)
  513. {
  514. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  515. return FALSE;
  516. }
  517. else
  518. {
  519. fclose(log);
  520. }
  521. }
  522. /* opening file for reading */
  523. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  524. if(fp == NULL) {
  525. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  526. return FALSE;
  527. }
  528. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL ) {
  529. /* writing content to stdout */
  530. //DEBUG_INFO("str=%s",str);
  531. if ((str[0] == '\n')||(strcmp(str,"")==0))
  532. {
  533. DEBUG_INFO("It is a blank line");
  534. fclose(fp);
  535. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  536. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/TransactionRelatedQueue");
  537. system(rmFileCmd);
  538. result = FALSE;
  539. return result;
  540. }
  541. else
  542. {
  543. //puts(str);
  544. //----------------uuid--------------//
  545. loc = strstr(str, "\"");
  546. memset(sstr ,0, ARRAY_SIZE(sstr) );
  547. c = 0;
  548. while (loc[1+c] != '\"')
  549. {
  550. sstr[c] = loc[1+c];
  551. c++;
  552. }
  553. sstr[c] = '\0';
  554. //DEBUG_INFO("\n uuid:%s", sstr);
  555. //DEBUG_INFO("\n data:%s", str);
  556. strcpy(uuid,sstr);
  557. strcpy(data,str);
  558. result = TRUE;
  559. }
  560. }
  561. else
  562. {
  563. //DEBUG_INFO("queue is null\n");
  564. strcpy(uuid,"");
  565. strcpy(data,"");
  566. result = FALSE;
  567. }
  568. fclose(fp);
  569. return result;
  570. }
  571. int addq(char *uuid, char *data)
  572. {
  573. FILE *outfile;
  574. char rmFileCmd[100]={0};
  575. struct stat stats;
  576. stat("/Storage/OCPP", &stats);
  577. DEBUG_INFO("addq\n");
  578. // Check for directory existence
  579. if (S_ISDIR(stats.st_mode) == 1)
  580. {
  581. //DEBUG_INFO("\n OCPP directory exist \n");
  582. }
  583. else
  584. {
  585. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  586. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  587. system(rmFileCmd);
  588. }
  589. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  590. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  591. {
  592. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  593. }
  594. else
  595. {
  596. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  597. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  598. if(log == NULL)
  599. {
  600. //DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  601. return FALSE;
  602. }
  603. else
  604. {
  605. fclose(log);
  606. }
  607. }
  608. // open file for writing
  609. outfile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "a");
  610. DEBUG_INFO("data = %s\n",data);
  611. fputs(data, outfile);
  612. fputs("\n", outfile);
  613. fclose (outfile);
  614. queueOpInfo.TransactionQueueNum += 1;
  615. DEBUG_INFO("add queue end\n");
  616. system("/bin/fsync -d /dev/mtdblock13;/bin/sync &");
  617. return FALSE;
  618. }
  619. //---------------- delq(): delete the top item --------------//
  620. int delq()
  621. {
  622. char tempfile[] = "/Storage/OCPP/delqtemp.json";
  623. FILE *infile;
  624. FILE *outfile;
  625. int resultRename=0;
  626. char filename[60]={0};
  627. char rmFileCmd[100]={0};
  628. struct stat stats;
  629. stat("/Storage/OCPP", &stats);
  630. DEBUG_INFO("delq()\n");
  631. // Check for directory existence
  632. if (S_ISDIR(stats.st_mode) == 1)
  633. {
  634. //DEBUG_INFO("\n OCPP directory exist \n");
  635. }
  636. else
  637. {
  638. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  639. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  640. system(rmFileCmd);
  641. }
  642. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  643. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  644. {
  645. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  646. }
  647. else
  648. {
  649. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  650. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  651. if(log == NULL)
  652. {
  653. //DEBUG_INFO("log is NULL\n");
  654. return 0;
  655. }
  656. else
  657. {
  658. fclose(log);
  659. }
  660. }
  661. // open file for writing
  662. strcpy(filename, "/Storage/OCPP/TransactionRelatedQueue");
  663. infile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "r");
  664. outfile = fopen (tempfile, "w");
  665. /*检测到文件结束标识返回1,否则返回0。*/
  666. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  667. int c;
  668. c = fgetc(infile);
  669. //printf("file c:%d\n",c);
  670. rewind(infile);
  671. if(c == EOF)
  672. {
  673. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  674. fclose(infile);
  675. fclose(outfile);
  676. sprintf(rmFileCmd,"rm -f %s",tempfile);
  677. system(rmFileCmd);
  678. }
  679. else
  680. {
  681. char buf[QUEUE_MESSAGE_LENGTH]={0};
  682. int i = 0;
  683. //DEBUG_INFO("Orignal File is not NULL\n");
  684. while (fgets(buf, sizeof(buf), infile) != NULL)
  685. {
  686. //printf("Orignal File get strings \n");
  687. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  688. if(i==0)
  689. {
  690. queueOpInfo.TransactionQueueNum -= 1;
  691. queueOpInfo.TransactionMessageResend = 0;
  692. DEBUG_INFO("delete the item\n");
  693. }
  694. if(i != 0)
  695. {
  696. fprintf(outfile,"%s\n", buf);
  697. }
  698. i = i + 1;
  699. }
  700. fclose(infile);
  701. fclose(outfile);
  702. sprintf(rmFileCmd,"rm -f %s",filename);
  703. system(rmFileCmd);
  704. resultRename = rename(tempfile, filename);
  705. if(resultRename == 0)
  706. {
  707. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  708. }
  709. else
  710. {
  711. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  712. }
  713. DEBUG_INFO("delq() end\n");
  714. }
  715. system("/bin/fsync -d /dev/mtdblock13;/bin/sync &");
  716. return 0;
  717. }
  718. int showqueue()
  719. {
  720. char rmFileCmd[100]={0};
  721. struct stat stats;
  722. stat("/Storage/OCPP", &stats);
  723. // Check for directory existence
  724. if (S_ISDIR(stats.st_mode) == 1)
  725. {
  726. //DEBUG_INFO("\n OCPP directory exist \n");
  727. }
  728. else
  729. {
  730. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  731. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  732. system(rmFileCmd);
  733. }
  734. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  735. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  736. {
  737. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  738. }
  739. else
  740. {
  741. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  742. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  743. if(log == NULL)
  744. {
  745. DEBUG_INFO("log is NULL\n");
  746. return FALSE;
  747. }
  748. else
  749. {
  750. fclose(log);
  751. }
  752. }
  753. FILE *fp = fopen("/Storage/OCPP/TransactionRelatedQueue", "r");
  754. char line[QUEUE_MESSAGE_LENGTH]={0};
  755. // check if file exist (and you can open it) or not
  756. if (fp == NULL) {
  757. DEBUG_INFO("can open file TransactionRelatedQueue!");
  758. return FALSE;
  759. }
  760. queueOpInfo.TransactionQueueNum = 0; // the number of packets in queue
  761. while(fgets(line, sizeof line, fp) != NULL) {
  762. //DEBUG_INFO("%s\n", line);
  763. queueOpInfo.TransactionQueueNum += 1; //the number of packets in queue
  764. }
  765. fclose(fp);
  766. return TRUE;
  767. }
  768. int sentqueue(){
  769. FILE *fp;
  770. int result = FALSE; // 1: TRUE 0:FALSE
  771. int temptransactionId = 0, gettransactionId = 0;
  772. int tempconnectorId = 0;
  773. //int gunIndex = 0;
  774. char guid[37]={0};
  775. char tempdata[65]={0};
  776. char key_value[65]={0};
  777. int IsStopTransaction = FALSE;
  778. //int IsconnectorIdNULL = FALSE;
  779. //int IsIdtagNULL = FALSE;
  780. char str[QUEUE_MESSAGE_LENGTH]={0};
  781. char strcomposite[QUEUE_MESSAGE_LENGTH]={0};
  782. char rmFileCmd[100]={0};
  783. char connectorStr[2]={0};
  784. struct stat stats;
  785. char sstr[28]={0};
  786. unsigned char IdtagStr[20]={0};
  787. unsigned char timestampStr[30]={0};
  788. int tempmeterStart = 0;
  789. int tempreservationId = 0;
  790. int c = 0;
  791. char *loc;
  792. DEBUG_INFO("Sent queue.\n");
  793. stat("/Storage/OCPP", &stats);
  794. // Check for directory existence
  795. if (S_ISDIR(stats.st_mode) == 1)
  796. {
  797. //DEBUG_INFO("\n OCPP directory exist \n");
  798. }
  799. else
  800. {
  801. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  802. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  803. system(rmFileCmd);
  804. }
  805. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  806. /* opening file for reading */
  807. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  808. if(fp == NULL) {
  809. DEBUG_INFO("Error opening file");
  810. return FALSE;
  811. }
  812. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL ) {
  813. //---- writing content to stdout ---//
  814. //*********************Start: StopTransaction***************************/
  815. loc = strstr(str, "StopTransaction");
  816. c = 0;
  817. memset(sstr ,0, ARRAY_SIZE(sstr) );
  818. if(loc != NULL)
  819. {
  820. IsStopTransaction = TRUE;
  821. }
  822. memset(connectorStr,0,ARRAY_SIZE(connectorStr));
  823. strncpy(connectorStr, str, 1);
  824. tempconnectorId = atoi(connectorStr);
  825. //*********************End: StopTransaction***************************/
  826. #if 0
  827. //*********************Start:connectorId***************************/
  828. loc = strstr(str, "connectorId");
  829. c = 0;
  830. memset(sstr ,0, ARRAY_SIZE(sstr) );
  831. if(loc != NULL)
  832. {
  833. while (loc[strlen("connectorId")+2+c] != ',')
  834. {
  835. sstr[c] = loc[strlen("connectorId")+2+c];
  836. c++;
  837. }
  838. sstr[c] = '\0';
  839. tempconnectorId = atoi(sstr);
  840. }
  841. // else
  842. // {
  843. // IsconnectorIdNULL = TRUE;
  844. // }
  845. //*********************End:connectorId***************************/
  846. #endif
  847. //*********************Start:idTag***************************/
  848. loc = strstr(str, "idTag");
  849. c = 0;
  850. memset(sstr ,0, ARRAY_SIZE(sstr) );
  851. if(loc != NULL)
  852. {
  853. while (loc[3+strlen("idTag")+c] != '\"')
  854. {
  855. sstr[c] = loc[3+strlen("idTag")+c];
  856. c++;
  857. }
  858. sstr[c] = '\0';
  859. strcpy((char*)IdtagStr, sstr);
  860. }
  861. // else
  862. // {
  863. // IsIdtagNULL = TRUE;
  864. // }
  865. //*********************End:idTag***************************/
  866. //*********************Start: StartTransaction***************************/
  867. loc = strstr(str, "StartTransaction");
  868. c = 0;
  869. memset(sstr ,0, ARRAY_SIZE(sstr) );
  870. if(loc != NULL)
  871. {
  872. // [2,0200000000000000000000000001584415776,StartTransaction,{connectorId:1,idTag:123,meterStart:100,reservationId:0,timestamp:2020-03-17T03:29:36Z}]
  873. //DEBUG_INFO("\n sent queue StartTransaction\n");
  874. if(tempconnectorId > 0)
  875. {
  876. sprintf(tempdata, "StartTransaction,%d", (tempconnectorId-1));
  877. }
  878. //GUID
  879. memset(sstr ,0, ARRAY_SIZE(sstr) );
  880. c=0;
  881. while (str[6+c] != '\"')
  882. {
  883. sstr[c] = str[6+c];
  884. c++;
  885. }
  886. sstr[c] = '\0';
  887. strcpy(guid, sstr);
  888. //Idtag
  889. loc = strstr(str, "idTag");
  890. memset(sstr ,0, ARRAY_SIZE(sstr) );
  891. c=0;
  892. while (loc[3+strlen("idTag")+c] != '\"')
  893. {
  894. sstr[c] = loc[3+strlen("idTag")+c];
  895. c++;
  896. }
  897. sstr[c] = '\0';
  898. strcpy((char*)IdtagStr, sstr);
  899. //meterStart
  900. loc = strstr(str, "meterStart");
  901. c = 0;
  902. memset(sstr ,0, ARRAY_SIZE(sstr) );
  903. if(loc != NULL)
  904. {
  905. while (loc[strlen("meterStart")+2+c] != ',')
  906. {
  907. sstr[c] = loc[strlen("meterStart")+2+c];
  908. c++;
  909. }
  910. sstr[c] = '\0';
  911. tempmeterStart = atoi(sstr);
  912. }
  913. //reservationId
  914. loc = strstr(str, "reservationId");
  915. c = 0;
  916. memset(sstr ,0, ARRAY_SIZE(sstr) );
  917. if(loc != NULL)
  918. {
  919. while (loc[strlen("reservationId")+2+c] != ',')
  920. {
  921. sstr[c] = loc[strlen("reservationId")+2+c];
  922. c++;
  923. }
  924. sstr[c] = '\0';
  925. tempreservationId = atoi(sstr);
  926. }
  927. //timestamp
  928. loc = strstr(str, "timestamp");
  929. memset(sstr ,0, ARRAY_SIZE(sstr) );
  930. c=0;
  931. while (loc[3+strlen("timestamp")+c] != '\"')
  932. {
  933. sstr[c] = loc[3+strlen("timestamp")+c];
  934. c++;
  935. }
  936. sstr[c] = '\0';
  937. strcpy((char*)timestampStr, sstr);
  938. if(hashmap_operation(HASH_OP_GET, guid, key_value) == TRUE)
  939. {
  940. //DEBUG_INFO("\n 1. sent queue guid=%s\n",guid);
  941. }
  942. else
  943. {
  944. hashmap_operation(HASH_OP_ADD, guid, tempdata);
  945. FillStartTransaction(tempconnectorId, IdtagStr, tempmeterStart, tempreservationId, timestampStr);
  946. //DEBUG_INFO("\n 2. sent queue guid=%s\n",guid);
  947. }
  948. }
  949. //*********************End: StartTransaction***************************/
  950. //****************transactionId********************/
  951. c=0;
  952. loc = strstr(str, "transactionId");
  953. memset(sstr ,0, ARRAY_SIZE(sstr) );
  954. if(loc != NULL)
  955. {
  956. // Only MeterValue with transactionId & StopTransaction will arrive here
  957. while ((loc[strlen("transactionId")+2+c] != '}') && (loc[strlen("transactionId")+2+c] != ','))
  958. {
  959. sstr[c] = loc[strlen("transactionId")+2+c];
  960. c++;
  961. }
  962. sstr[c] = '\0';
  963. temptransactionId = atoi(sstr);
  964. //Get IdTag from StartTransaction , store to StartTransactionIdTagTemp, For StopTransaction usage in Queue (StartTransaction. StopTransaction user id different), get actual TransactionId
  965. GetStartTransactionIdTag(tempconnectorId-1);
  966. gettransactionId = GetTransactionId(tempconnectorId, IdtagStr, IsStopTransaction);
  967. DEBUG_INFO("queue map transactionId = %d\n", gettransactionId);
  968. DEBUG_INFO("original connectorId = %d\n", tempconnectorId);
  969. DEBUG_INFO("original transactionId = %d\n", temptransactionId);
  970. DEBUG_INFO("original IdtagStr = %s\n", IdtagStr);
  971. if((gettransactionId != 0)&&(temptransactionId != gettransactionId))
  972. {
  973. //replace transactionId of metervalue or stopTransaction
  974. strncpy(strcomposite,str, (loc-str)+2+strlen("transactionId"));
  975. sprintf(strcomposite+((loc-str)+2+strlen("transactionId")),"%d",gettransactionId);
  976. strcat(strcomposite, loc+strlen("transactionId")+2+c); // 把 字串中transactionId後面的字串串接到 strcomposite後面
  977. LWS_Send(strcomposite+2); // skip 2 bytes String -> Connector ID,
  978. }
  979. else
  980. {
  981. LWS_Send(str+2); // skip 2 bytes String -> Connector ID
  982. gettransactionId = temptransactionId;
  983. }
  984. DEBUG_INFO("Final transactionId = %d\n", gettransactionId);
  985. if(IsStopTransaction == TRUE)//if((IsStopTransaction == TRUE)&&(gettransactionId != 0))
  986. {
  987. queueOpInfo.stopTransactionId = gettransactionId;
  988. //SetTransactionIdZero(gettransactionId);
  989. }
  990. }
  991. else
  992. {
  993. // MeterValue without transactionId & StartTransaction arrive here
  994. LWS_Send(str+2);
  995. }
  996. result = TRUE;
  997. }
  998. else
  999. {
  1000. result = FALSE;
  1001. }
  1002. fclose(fp);
  1003. return result;
  1004. }
  1005. void* processTransactionQueue(void* data)
  1006. {
  1007. char frontUUID[100] ={0};
  1008. char frontData[QUEUE_MESSAGE_LENGTH] ={0};
  1009. int queueNotEmpty = FALSE;
  1010. while(1)
  1011. {
  1012. if(!req_SendQueue && ((getDiffSecNow(startTime.startTimeQueue) >= ((TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10)*(queueOpInfo.TransactionMessageResend>1?2:1))) || (isWebsocketSendable && isQueueSendable && (getDiffSecNow(startTime.startTimeQueue) >= ((counterQueueSent>=20)?5:0)))))
  1013. {
  1014. if(FirstHeartBeatResponse() == 1)
  1015. {
  1016. memset(frontUUID, 0, ARRAY_SIZE(frontUUID));
  1017. memset(frontData, 0, ARRAY_SIZE(frontData));
  1018. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);
  1019. if((queueNotEmpty == TRUE) && (GetOcppConnStatus() == 1))
  1020. {
  1021. if(isWebsocketSendable)
  1022. DEBUG_INFO("isWebsocketSendable on.\n");
  1023. if(isQueueSendable)
  1024. DEBUG_INFO("isQueueSendable on.\n");
  1025. if(((getDiffSecNow(startTime.startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))))
  1026. DEBUG_INFO("Queue timer(%d) over spec(%d).\n", getDiffSecNow(startTime.startTimeQueue), TransactionMessageRetryIntervalGet());
  1027. if(queueOpInfo.TransactionMessageResend < TransactionMessageAttemptsGet())
  1028. {
  1029. DEBUG_INFO("Sent message from queue request.\n");
  1030. DEBUG_INFO("TransactionMessageResend time: %d\n", queueOpInfo.TransactionMessageResend);
  1031. req_SendQueue = 1;
  1032. queueOpInfo.TransactionMessageResend += 1;
  1033. }
  1034. else
  1035. {
  1036. DEBUG_INFO("Transaction message resend(%d) over spec(%d) message abandon.\n", queueOpInfo.TransactionMessageResend, TransactionMessageAttemptsGet());
  1037. queue_operation(QUEUE_OPERATION_DEL,"","");
  1038. queueOpInfo.TransactionMessageResend = 0;
  1039. req_SendQueue = 0;
  1040. }
  1041. }
  1042. }
  1043. // Refresh queue timer
  1044. refreshStartTimer(&startTime.startTimeQueue);
  1045. if((counterQueueSent >= 10) || (queueNotEmpty == FALSE))
  1046. {
  1047. counterQueueSent = 0;
  1048. }
  1049. else
  1050. {
  1051. counterQueueSent += 1;
  1052. }
  1053. }
  1054. usleep(500000);
  1055. }
  1056. pthread_exit(NULL);
  1057. return 0;
  1058. }
  1059. void* processWatchdog()
  1060. {
  1061. for(;;)
  1062. {
  1063. if((getDiffSecNow(startTime.startTimeDog) > 10) && (context != NULL))
  1064. {
  1065. DEBUG_INFO("LWS watch dog timeout.\n");
  1066. lws_cancel_service(context);
  1067. lws_cancel_service_pt(wsi_client);
  1068. if(counterLwsRestart >= 2)
  1069. {
  1070. DEBUG_INFO("LWS watch dog timeout over 3 count.\n");
  1071. system("pkill OcppBackend");
  1072. }
  1073. else
  1074. counterLwsRestart++;
  1075. refreshStartTimer(&startTime.startTimeDog);
  1076. }
  1077. if(counterConnect >= 2)
  1078. {
  1079. DEBUG_INFO("Connect OCPP server timeout over 3 count.\n");
  1080. system("pkill OcppBackend");
  1081. }
  1082. if((0 < GetWebSocketPingInterval()) && ((GetWebSocketPingInterval()+5) <= getDiffSecNow(startTime.pingOn)) && (wsi_client != NULL) && (GetServerSign() == TRUE))
  1083. {
  1084. DEBUG_WARN("Pong packet receive timeout.\n");
  1085. system("pkill OcppBackend");
  1086. }
  1087. usleep(500000);
  1088. }
  1089. pthread_exit(NULL); //
  1090. }
  1091. void CheckTransactionPacket(char *uuid)
  1092. {
  1093. char frontUUID[100]={0};
  1094. char frontData[QUEUE_MESSAGE_LENGTH]={0};
  1095. int queueNotEmpty = FALSE;
  1096. int cmpResult = 0;
  1097. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1098. if(queueNotEmpty == TRUE)
  1099. {
  1100. cmpResult = strcmp(frontUUID, uuid);
  1101. if (cmpResult == 0)
  1102. {
  1103. DEBUG_INFO("Receive queue response match.\n");
  1104. queue_operation(QUEUE_OPERATION_DEL,"","");//delq(); ---> remove temporally
  1105. queueOpInfo.TransactionMessageResend = 0;
  1106. }
  1107. else
  1108. DEBUG_INFO("Receive queue response mismatch.\n");
  1109. }
  1110. }
  1111. int queue_operation(int type, char *frontUUID, char *frontData)
  1112. {
  1113. int result=0;
  1114. while(1)
  1115. {
  1116. if (!queueOpInfo.IsUsing )
  1117. {
  1118. queueOpInfo.IsUsing = TRUE;
  1119. if(type == QUEUE_OPERATION_SHOWQUEUE) // show items in queue
  1120. {
  1121. result = showqueue();
  1122. }
  1123. else if(type == QUEUE_OPERATION_SHOWFRONT) // show first item
  1124. {
  1125. result = showfront(frontUUID, frontData);
  1126. }
  1127. else if(type == QUEUE_OPERATION_DEL) // delete item
  1128. {
  1129. result = delq();
  1130. }
  1131. else if(type == QUEUE_OPERATION_SENT) // sent items in queue
  1132. {
  1133. result = sentqueue();
  1134. }
  1135. else if(type == QUEUE_OPERATION_ADD) // add items to the queue
  1136. {
  1137. // If queue file over size only add start * stop transaction message
  1138. if(!isQueueOverSize() || (strstr(frontData, "MeterValues") == NULL))
  1139. {
  1140. result = addq(frontUUID, frontData);
  1141. }
  1142. }
  1143. queueOpInfo.IsUsing = FALSE;
  1144. break;
  1145. }
  1146. usleep(100000);
  1147. }
  1148. return result;
  1149. }
  1150. int removeMessageSentFile(void)
  1151. {
  1152. char rmFileCmd[100]={0};
  1153. struct stat stats;
  1154. stat("/Storage/OCPP", &stats);
  1155. // Check for directory existence
  1156. if(S_ISDIR(stats.st_mode) == 1)
  1157. {
  1158. //DEBUG_INFO("\n OCPP directory exist \n");
  1159. }
  1160. else
  1161. {
  1162. DEBUG_INFO("\n directory not exist, create dir \n");
  1163. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  1164. system(rmFileCmd);
  1165. }
  1166. stat("/Storage/OCPP/TransactionRelatedQueue", &stats);
  1167. if(stats.st_size < 10)
  1168. {
  1169. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1170. if((access("/Storage/OCPP/MessageSent",F_OK))!=-1)
  1171. {
  1172. DEBUG_INFO("MessageSent file exist.\n");
  1173. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/MessageSent");
  1174. system(rmFileCmd);
  1175. }
  1176. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1177. }
  1178. return 0;
  1179. }
  1180. //================================================
  1181. // Main process
  1182. //================================================
  1183. int main(void)
  1184. {
  1185. char rmFileCmd[100]={0};
  1186. struct stat stats;
  1187. queueOpInfo.IsUsing = FALSE;
  1188. queueOpInfo.TransactionMessageResend = 0;
  1189. DEBUG_INFO("Module_OcppBackend task initialization...\n");
  1190. //lws_set_log_level(LLL_PARSER | LLL_HEADER | LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_INFO | LLL_DEBUG | LLL_EXT | LLL_CLIENT | LLL_LATENCY , NULL);
  1191. if(ProcessShareMemory()== FAIL)
  1192. {
  1193. return FAIL;
  1194. }
  1195. // Check & create OCPP dir
  1196. stat("/Storage/OCPP", &stats);
  1197. if(S_ISDIR(stats.st_mode) != 1)
  1198. {
  1199. DEBUG_INFO("OCPP directory not exist, create dir \n");
  1200. sprintf(rmFileCmd,"mkdir -p /Storage/OCPP");
  1201. system(rmFileCmd);
  1202. }
  1203. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1204. // Create Process: Resend Transaction
  1205. pthread_create(&tid_ProcQueue, NULL, processTransactionQueue, NULL);
  1206. pthread_create(&tid_Watchdog, NULL, processWatchdog, NULL);
  1207. // Sqlite3 initial
  1208. sqlite3_config(SQLITE_CONFIG_URI,1);
  1209. if(sqlite3_open("file:/Storage/OCPP/charger.db", &db))
  1210. {
  1211. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1212. sqlite3_close( db );
  1213. exit(0);
  1214. }
  1215. else
  1216. {
  1217. DEBUG_INFO( "Opened database successfully\n");
  1218. }
  1219. //Create Table log buffer
  1220. if(sqlite3_exec(db, createsql, 0, 0, &errMsg) != SQLITE_OK)
  1221. {
  1222. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1223. return 0;
  1224. }
  1225. else
  1226. {
  1227. DEBUG_INFO( "Opened log buffer table successfully\n");
  1228. }
  1229. // Create Table OcppAuthCache
  1230. if(sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg) != SQLITE_OK)
  1231. {
  1232. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1233. return 0;
  1234. }
  1235. else
  1236. {
  1237. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1238. }
  1239. // Create Table OcppAuthLocal
  1240. if(sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg) != SQLITE_OK)
  1241. {
  1242. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1243. return 0;
  1244. }
  1245. else
  1246. {
  1247. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1248. }
  1249. // Create Table Transaction
  1250. if(sqlite3_exec(db, sqlTransaction, 0, 0, &errMsg) != SQLITE_OK)
  1251. {
  1252. DEBUG_INFO( "Create Table ocpp_transaction_record error %s\n",errMsg);
  1253. return 0;
  1254. }
  1255. else
  1256. {
  1257. DEBUG_INFO( "Opened ocpp_transaction_record table successfully\n");
  1258. }
  1259. // Create transaction period energy
  1260. if(sqlite3_exec(db, sqlPeriodEnergy, 0, 0, &errMsg) != SQLITE_OK)
  1261. {
  1262. DEBUG_INFO( "Create Table ocpp_period_energy error %s\n",errMsg);
  1263. return 0;
  1264. }
  1265. else
  1266. {
  1267. DEBUG_INFO( "Opened ocpp_period_energy table successfully\n");
  1268. }
  1269. if(initialConfigurationTable() != PASS)
  1270. {
  1271. DEBUG_WARN("OCPPConfiguration version mismatch, upgrade it.\n");
  1272. system("rm -f /Storage/OCPP/OCPPConfiguration");
  1273. initialConfigurationTable();
  1274. }
  1275. removeMessageSentFile();
  1276. for(;;)
  1277. {
  1278. refreshStartTimer(&startTime.startTimeDog);
  1279. counterLwsRestart = 0;
  1280. // Connect server
  1281. if(ConnectionEstablished==0) // Check InternetConn 0: disconnected, 1: connected
  1282. {
  1283. isWebsocketSendable = 1;
  1284. isQueueSendable = 1;
  1285. SetOcppConnStatus(FALSE);
  1286. SetServerSign(FALSE);
  1287. InitialSystemValue();
  1288. if(getDiffSecNow(startTime.connect) >= 30)
  1289. {
  1290. DEBUG_INFO("Server connecting...\n");
  1291. pthread_create(&tid_connectServer, NULL, ConnectWsServer, NULL);
  1292. refreshStartTimer(&startTime.connect);
  1293. }
  1294. CheckSystemValue();
  1295. }
  1296. else
  1297. {
  1298. // Sign in
  1299. if((GetServerSign() == FALSE) &&
  1300. (isConnectorInitMode(0) != TRUE) &&
  1301. ( (GetBootNotificationInterval()>0) ? (getDiffSecNow(startTime.bootNotification) >= GetBootNotificationInterval()) : (getDiffSecNow(startTime.bootNotification) >= defaultWaitingTime) )
  1302. )
  1303. {
  1304. sendBootNotificationRequest();
  1305. refreshStartTimer(&startTime.bootNotification);
  1306. }
  1307. // Check System Value
  1308. CheckSystemValue();
  1309. // On line operation
  1310. if(GetServerSign() == TRUE)
  1311. {
  1312. // Send message from queue
  1313. if((req_SendQueue == 1) && (isWebsocketSendable || ((queueOpInfo.TransactionMessageResend > 1) && (queueOpInfo.PreTransactionMessageResend != queueOpInfo.TransactionMessageResend))))
  1314. {
  1315. queue_operation(QUEUE_OPERATION_SENT, "", "");
  1316. req_SendQueue = 0;
  1317. queueOpInfo.PreTransactionMessageResend = queueOpInfo.TransactionMessageResend;
  1318. }
  1319. // PING packet
  1320. if(isWebsocketSendable && (0 < GetWebSocketPingInterval()) && ((GetWebSocketPingInterval()+counterPingSend) <= getDiffSecNow(startTime.pingOn)))
  1321. {
  1322. lws_callback_on_writable(wsi_client);
  1323. counterPingSend++;
  1324. }
  1325. if(GetHeartBeatWithNOResponse() >= 30)
  1326. {
  1327. lws_context_destroy(context);
  1328. ConnectionEstablished = 0;
  1329. context = NULL;
  1330. SetHeartBeatWithNOResponse();
  1331. DEBUG_WARN("Heartbeat re-send over 30 count.\n");
  1332. }
  1333. if((GetOcppConnStatus() == 0))
  1334. {
  1335. if(getDiffSecNow(startTime.reConnect) >= 3)
  1336. {
  1337. DEBUG_INFO("GetOcppConnStatus() = %d\n", GetOcppConnStatus());
  1338. lws_context_destroy(context);
  1339. ConnectionEstablished = 0;
  1340. context = NULL;
  1341. }
  1342. }
  1343. else
  1344. {
  1345. refreshStartTimer(&startTime.reConnect);
  1346. }
  1347. }
  1348. }
  1349. do
  1350. {
  1351. lws_service(context, 0);//timeout_ms
  1352. }while((SendBufLen>0) && (context!=NULL) && GetOcppConnStatus());
  1353. refreshProcDogTimer();
  1354. usleep(100000);
  1355. }
  1356. pthread_join(tid_ProcQueue, NULL);
  1357. pthread_join(tid_Watchdog, NULL);
  1358. return FAIL;
  1359. }