Module_OcppBackend.c 42 KB

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