Module_OcppBackend20.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. #include "Module_OcppBackend20.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. unsigned int connect;
  12. unsigned int bootNotification;
  13. }startTime;
  14. //==========================================
  15. // Function prototype
  16. //==========================================
  17. void ReceivedMessage(void *in, size_t len);
  18. int SendBufLen=0;//(1024*4);//(1024*3);
  19. unsigned char SendBuffer[1024*20]={0};
  20. static int ConnectionEstablished=0;
  21. static int TransactionMessageResend = 1; // the number of retry to submit a transaction-related message when the Central System fails to process it.
  22. static int TransactionQueueNum = 0;
  23. static int OfflineTransactionQueueNum = 0; // Number of offline transactions
  24. static int OfflineTransaction = 0;
  25. static int IsUsing = FALSE;
  26. char OcppPath[384]={0};
  27. char OcppProtocol[10]={0},OcppHost[128]={0}, OcppTempPath[256]={0};
  28. int OcppPort=0;
  29. unsigned char StartTransactionIdTagTemp[20]={0};
  30. uint32_t startTimeDog;
  31. uint32_t startTimeQueue;
  32. uint8_t isWebsocketSendable = 1;
  33. uint8_t counterLwsRestart = 0;;
  34. uint8_t counterQueueSent = 0;
  35. uint8_t counterConnect = 0;
  36. //=================================
  37. // Common routine
  38. //=================================
  39. int GetTransactionQueueNum(void)
  40. {
  41. return TransactionQueueNum;
  42. }
  43. //==========================================
  44. // Web socket tranceive routine
  45. //==========================================
  46. int SendData(struct lws *wsi)
  47. {
  48. int n;
  49. int len;
  50. unsigned char out[LWS_SEND_BUFFER_PRE_PADDING + (1024*20) + LWS_SEND_BUFFER_POST_PADDING] = {0};
  51. // Only disable isWebsocketSendable operation initiated by charger
  52. if((strstr((char*)SendBuffer, "\"Authorize\"") != NULL)
  53. || (strstr((char*)SendBuffer, "\"BootNotification\"") != NULL)
  54. || (strstr((char*)SendBuffer, "\"ClearedChargingLimit\"") != NULL)
  55. || (strstr((char*)SendBuffer, "\"DataTransfer\"") != NULL)
  56. || (strstr((char*)SendBuffer, "\"FirmwareStatusNotification\"") != NULL)
  57. || (strstr((char*)SendBuffer, "\"Get15118EVCertificate\"") != NULL)
  58. || (strstr((char*)SendBuffer, "\"GetCertificateStatus\"") != NULL)
  59. || (strstr((char*)SendBuffer, "\"Heartbeat\"") != NULL)
  60. || (strstr((char*)SendBuffer, "\"LogStatusNotification\"") != NULL)
  61. || (strstr((char*)SendBuffer, "\"MeterValues\"") != NULL)
  62. || (strstr((char*)SendBuffer, "\"NotifyChargingLimit\"") != NULL)
  63. || (strstr((char*)SendBuffer, "\"NotifyCustomerInformation\"") != NULL)
  64. || (strstr((char*)SendBuffer, "\"NotifyDisplayMessages\"") != NULL)
  65. || (strstr((char*)SendBuffer, "\"NotifyEVChargingNeeds\"") != NULL)
  66. || (strstr((char*)SendBuffer, "\"NotifyEVChargingSchedule\"") != NULL)
  67. || (strstr((char*)SendBuffer, "\"NotifyEvent\"") != NULL)
  68. || (strstr((char*)SendBuffer, "\"NotifyMonitoringReport\"") != NULL)
  69. || (strstr((char*)SendBuffer, "\"NotifyReport\"") != NULL)
  70. || (strstr((char*)SendBuffer, "\"PublishFirmwareStatusNotification\"") != NULL)
  71. || (strstr((char*)SendBuffer, "\"ReportChargingProfiles\"") != NULL)
  72. || (strstr((char*)SendBuffer, "\"ReservationStatusUpdate\"") != NULL)
  73. || (strstr((char*)SendBuffer, "\"SecurityEventNotification\"") != NULL)
  74. || (strstr((char*)SendBuffer, "\"SignCertificate\"") != NULL)
  75. || (strstr((char*)SendBuffer, "\"StatusNotification\"") != NULL)
  76. || (strstr((char*)SendBuffer, "\"TransactionEven\"") != NULL))
  77. {
  78. isWebsocketSendable = 0;
  79. }
  80. len = strlen((char *)SendBuffer);
  81. if(len == 0)
  82. return 0;
  83. memcpy (out + LWS_SEND_BUFFER_PRE_PADDING, SendBuffer, len );
  84. DEBUG_OCPPMESSAGE_INFO("===========> %s\n", out + LWS_SEND_BUFFER_PRE_PADDING);
  85. n = lws_write(wsi, out + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
  86. memset(SendBuffer, 0, len);
  87. SendBufLen = 0;
  88. return n;
  89. }
  90. static int OCPP20Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
  91. {
  92. char buf[256]={0}, hash[20]={0}, key_b64[40]={0}, tempin[65536]={0}, sstr[65536]={0};
  93. uint8_t auth_b64[256]={0}, boxId[128]={0}, password[64]={0};
  94. int c = 0;
  95. char *loc;
  96. switch (reason)
  97. {
  98. case LWS_CALLBACK_PROTOCOL_INIT:
  99. DEBUG_INFO("LWS_CALLBACK_PROTOCOL_INIT\n");
  100. break;
  101. case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH:
  102. DEBUG_INFO("LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH\n");
  103. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Client Request START -----\n");
  104. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_URI);
  105. DEBUG_OCPPMESSAGE_INFO("GET %s HTTP/1.1 \n", buf);
  106. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_HOST);
  107. DEBUG_OCPPMESSAGE_INFO("Host: %s\n", buf);
  108. DEBUG_OCPPMESSAGE_INFO("Upgrade: websocket\n");
  109. DEBUG_OCPPMESSAGE_INFO("Connection: Upgrade\n");
  110. lws_b64_encode_string(hash, 16, key_b64, ARRAY_SIZE(key_b64));// Sec-WebSocket-Key
  111. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Key: %s\n", key_b64);
  112. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
  113. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  114. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Version: %d\n", SPEC_LATEST_SUPPORTED);
  115. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Client Request END -----\n");
  116. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Server response START -----\n");
  117. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_HTTP);
  118. DEBUG_OCPPMESSAGE_INFO("HTTP/1.1 %s\n", buf);
  119. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_UPGRADE);
  120. DEBUG_OCPPMESSAGE_INFO("Upgrade: %s\n", buf);
  121. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_CONNECTION);
  122. DEBUG_OCPPMESSAGE_INFO("Connection: %s\n", buf);
  123. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_ACCEPT);
  124. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Accept: %s\n", buf);
  125. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_PROTOCOL);
  126. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  127. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Server response END -----\n");
  128. break;
  129. case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
  130. DEBUG_INFO("LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION\n");
  131. break;
  132. case LWS_CALLBACK_WSI_DESTROY:
  133. DEBUG_INFO("LWS_CALLBACK_WSI_DESTROY\n");
  134. pthread_detach(tid_connectServer);
  135. SetServerSign(FALSE);
  136. ConnectionEstablished = 0;
  137. context = NULL;
  138. break;
  139. case LWS_CALLBACK_LOCK_POLL:
  140. break;
  141. case LWS_CALLBACK_ADD_POLL_FD:
  142. DEBUG_INFO("LWS_CALLBACK_ADD_POLL_FD\n");
  143. break;
  144. case LWS_CALLBACK_DEL_POLL_FD:
  145. DEBUG_INFO("LWS_CALLBACK_DEL_POLL_FD\n");
  146. break;
  147. case LWS_CALLBACK_UNLOCK_POLL:
  148. break;
  149. case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
  150. break;
  151. case LWS_CALLBACK_WSI_CREATE:
  152. DEBUG_INFO("LWS_CALLBACK_WSI_CREATE\n");
  153. break;
  154. case LWS_CALLBACK_GET_THREAD_ID:
  155. break;
  156. case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
  157. DEBUG_INFO("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
  158. unsigned char** pos = (unsigned char**)in;
  159. unsigned char* end = (*pos) + len;
  160. switch(GetOcppSecurityProfile())
  161. {
  162. case 1:
  163. case 2:
  164. case 3:
  165. GetOcppChargerBoxId(boxId);
  166. GetOcppSecurityPassword(password);
  167. sprintf(buf, "%s:%s", boxId, password);
  168. lws_b64_encode_string(buf, strlen(buf), (char*)auth_b64, ARRAY_SIZE(auth_b64));
  169. sprintf(buf, "Basic %s", auth_b64);
  170. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_AUTHORIZATION, (uint8_t *)buf, strlen(buf), pos, end))
  171. {
  172. DEBUG_ERROR("lws_add_http_header_by_token : WSI_TOKEN_HTTP_AUTHORIZATION\n");
  173. return -1;
  174. }
  175. DEBUG_OCPPMESSAGE_INFO("Authorization: %s\n", buf);
  176. break;
  177. case 0:
  178. default:
  179. break;
  180. }
  181. break;
  182. case LWS_CALLBACK_CLIENT_ESTABLISHED: //3
  183. DEBUG_INFO("LWS_CALLBACK_CLIENT_ESTABLISHED\n");
  184. char frontUUID[100] ={0};
  185. char frontData[QUEUE_MESSAGE_LENGTH] ={0};
  186. int queueNotEmpty = FALSE;
  187. //connected
  188. ConnectionEstablished=1;
  189. SetOcppConnStatus(TRUE);
  190. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);
  191. if(queueNotEmpty == TRUE)
  192. {
  193. OfflineTransaction = 1; // 0: no packets in queue. 1: There are packets in queue.
  194. }
  195. TransactionMessageResend = 1;
  196. //get offline number
  197. queue_operation(QUEUE_OPERATION_SHOWQUEUE,"","");
  198. OfflineTransactionQueueNum =TransactionQueueNum ;
  199. break;
  200. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR://1
  201. DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR %s\n", (char *)in );
  202. //disconnected
  203. ConnectionEstablished=0;
  204. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Client START =====\n");
  205. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_URI);
  206. DEBUG_OCPPMESSAGE_INFO("GET %s HTTP/1.1 \n", buf);
  207. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_HOST);
  208. DEBUG_OCPPMESSAGE_INFO("Host: %s\n", buf);
  209. DEBUG_OCPPMESSAGE_INFO("Upgrade: websocket\n");
  210. DEBUG_OCPPMESSAGE_INFO("Connection: Upgrade\n");
  211. lws_b64_encode_string(hash, 16, key_b64, ARRAY_SIZE(key_b64));// Sec-WebSocket-Key
  212. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Key: %s\n", key_b64);
  213. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
  214. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  215. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Version: %d\n", SPEC_LATEST_SUPPORTED);
  216. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Client END =====\n");
  217. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Server response START =====\n");
  218. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_HTTP);
  219. DEBUG_OCPPMESSAGE_INFO("HTTP/1.1 %s\n", buf);
  220. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_UPGRADE);
  221. DEBUG_OCPPMESSAGE_INFO("Upgrade: %s\n", buf);
  222. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_CONNECTION);
  223. DEBUG_OCPPMESSAGE_INFO("Connection: %s\n", buf);
  224. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_ACCEPT);
  225. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Accept: %s\n", buf);
  226. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_PROTOCOL);
  227. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  228. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Server response END =====\n");
  229. break;
  230. case LWS_CALLBACK_CLOSED://4
  231. DEBUG_INFO("LWS_CALLBACK_CLOSED\n");
  232. //disconnected
  233. ConnectionEstablished=0;
  234. break;
  235. case LWS_CALLBACK_CLIENT_WRITEABLE://10
  236. //if(need to send message and its relevant data already store into SendBuffer)
  237. SendData(wsi);
  238. //lws_rx_flow_control( wsi, 1 );
  239. break;
  240. case LWS_CALLBACK_CLIENT_RECEIVE://8
  241. ((char *)in)[len] = '\0';
  242. DEBUG_OCPPMESSAGE_INFO("<==== %s\n", (char *)in);
  243. //**********Receive Message**********/
  244. c = 0;
  245. loc = strstr((const char *)in, "][2,");
  246. if(loc == NULL)
  247. {
  248. loc = strstr((const char *)in, "][3,");
  249. if(loc == NULL)
  250. {
  251. loc = strstr((const char *)in, "][4,");
  252. }
  253. }
  254. memset(sstr, 0, ARRAY_SIZE(sstr) );
  255. if(loc != NULL)
  256. {
  257. DEBUG_INFO("There are continuous second packet []\n");
  258. while (loc[1+c] != '\0')
  259. {
  260. sstr[c] = loc[1+c];
  261. c++;
  262. }
  263. sstr[c] = '\0';
  264. strcpy(tempin, sstr);
  265. DEBUG_INFO("Final Receive: %s\n", tempin);
  266. }
  267. else
  268. {
  269. strcpy(tempin,(char *)in);
  270. }
  271. ReceivedMessage((void *)strtrim(tempin), strlen(tempin));
  272. isWebsocketSendable = 1;
  273. break;
  274. case LWS_CALLBACK_CLIENT_RECEIVE_PONG:
  275. DEBUG_INFO("LWS_CALLBACK_CLIENT_RECEIVE_PONG\n");
  276. DEBUG_OCPPMESSAGE_INFO("<==== Get PONG packet.\n");
  277. break;
  278. case LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION:
  279. DEBUG_INFO("LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION\n");
  280. break;
  281. case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS:
  282. DEBUG_INFO("LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS\n");
  283. break;
  284. case LWS_CALLBACK_PROTOCOL_DESTROY:
  285. DEBUG_INFO("LWS_CALLBACK_PROTOCOL_DESTROY\n");
  286. break;
  287. case LWS_CALLBACK_RECEIVE_PONG:
  288. DEBUG_INFO("LWS_CALLBACK_RECEIVE_PONG\n");
  289. break;
  290. default:
  291. DEBUG_INFO("Reason = %d\n", reason);
  292. break;
  293. }
  294. return 0;
  295. }
  296. static struct lws_protocols protocols[] =
  297. {
  298. {
  299. "ocpp2.0",
  300. OCPP20Callback,
  301. 65536,//65536,//10240,
  302. 65536,//65536,//10240,
  303. },
  304. {
  305. "ocpp2.0",
  306. OCPP20Callback,
  307. 65536,//65536,//10240,
  308. 65536,//65536,//10240,
  309. },
  310. {
  311. NULL, NULL, 0 /* End of list */
  312. }
  313. };
  314. void* ConnectWsServer(void* data) //int ConnectWsServer()
  315. {
  316. struct lws_context_creation_info ContextInfo;
  317. struct lws_client_connect_info ConnInfo;
  318. int use_ssl=0;
  319. counterConnect += 1;
  320. // If internet available synchronize datetime with ntp server
  321. if(GetInternetConn() == 1)
  322. {
  323. system("pkill ntpd");
  324. DEBUG_INFO("NTP synchronize with Microsoft\n", system("/usr/sbin/ntpd -nqp time.windows.com &"));
  325. DEBUG_INFO("NTP synchronize with China\n", system("/usr/sbin/ntpd -nqp cn.ntp.org.cn &"));
  326. DEBUG_INFO("NTP synchronize with Taiwan\n", system("/usr/sbin/ntpd -nqp tock.stdtime.gov.tw &"));
  327. DEBUG_INFO("NTP synchronize with Europe\n", system("/usr/sbin/ntpd -nqp 0.europe.pool.ntp.org &"));
  328. }
  329. if(context!=NULL)
  330. {
  331. pthread_detach(pthread_self());
  332. lws_context_destroy(context);
  333. ConnectionEstablished=0;
  334. context = NULL;
  335. }
  336. checkNetworkProfile();
  337. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  338. if((GetOcppServerURL()==0) || (GetOcppPort() == 0) || (GetOcppPath()==0))
  339. {
  340. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  341. goto end;
  342. }
  343. if((strcmp(OcppProtocol,"ws")==0)&&(strlen(OcppProtocol)== 2))
  344. {
  345. DEBUG_INFO("Web socket is non-security mode.\n");
  346. use_ssl=0;
  347. }
  348. else if((strcmp(OcppProtocol,"wss")==0)&&(strlen(OcppProtocol)== 3))
  349. {
  350. DEBUG_INFO("Web socket is security mode.\n");
  351. use_ssl=1;
  352. }
  353. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  354. ContextInfo.iface = NULL;
  355. ContextInfo.ssl_private_key_password = NULL;
  356. ContextInfo.ssl_cert_filepath = NULL;//"./ssl_key/client_cert.pem";
  357. ContextInfo.ssl_private_key_filepath = NULL;//"./ssl_key/client_key.pem";
  358. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";//"./cacert.pem";
  359. ContextInfo.ssl_cipher_list = NULL; //use default one
  360. ContextInfo.gid = -1;
  361. ContextInfo.uid = -1;
  362. if(use_ssl)
  363. {
  364. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT ;
  365. }
  366. ContextInfo.protocols = protocols;
  367. ContextInfo.timeout_secs = GetWebSocketPingInterval();//WebSocketPingInterval;//30;//9999;//30;
  368. ContextInfo.ws_ping_pong_interval = GetWebSocketPingInterval();//WebSocketPingInterval;//30;//0 for none, else interval in seconds
  369. ContextInfo.ka_time = 20;
  370. ContextInfo.keepalive_timeout = 5;
  371. ContextInfo.ka_probes = 2;
  372. ContextInfo.ka_interval = 5;
  373. context = lws_create_context(&ContextInfo);
  374. if (context == NULL)
  375. {
  376. DEBUG_ERROR("lws_create_context NG");
  377. goto end;
  378. }
  379. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  380. // fill up below information
  381. ConnInfo.context = context;
  382. ConnInfo.address=(const char *)OcppHost;
  383. DEBUG_INFO("ConnInfo.address: %s\n", ConnInfo.address);
  384. ConnInfo.port = GetOcppPort();
  385. DEBUG_INFO("ConnInfo.port: %d\n", ConnInfo.port);
  386. ConnInfo.path=(const char *)OcppPath;
  387. DEBUG_INFO("ConnInfo.path: %s\n", ConnInfo.path);
  388. char addr_port[256] = { 0 };
  389. sprintf(addr_port, "%s:%u", ConnInfo.address, (ConnInfo.port & 65535) );
  390. ConnInfo.host= addr_port; // ConnInfo.address;//lws_canonical_hostname(context);
  391. //ConnInfo.origin="origin";
  392. ConnInfo.protocol = protocols[1].name;
  393. ConnInfo.ietf_version_or_minus_one = -1;
  394. if(use_ssl)
  395. {
  396. #ifdef TLS_VALID_CERT_EXPIRED
  397. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
  398. DEBUG_INFO("TLS does not allow expired certification.\n");
  399. #else
  400. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK | LCCSCF_ALLOW_EXPIRED;
  401. DEBUG_INFO("TLS allow expired certification.\n");
  402. #endif
  403. }
  404. wsi_client = lws_client_connect_via_info(&ConnInfo);
  405. if (!wsi_client)
  406. {
  407. DEBUG_ERROR("lws_client_connect_via_info NG\n");
  408. goto end;
  409. }
  410. counterConnect=0;
  411. DEBUG_INFO("counterConnect: %d\n", counterConnect);
  412. end:
  413. pthread_exit(NULL/*(void *) fname*/);
  414. }
  415. int isQueueOverSize()
  416. {
  417. FILE *fp;
  418. uint32_t file_size;
  419. uint8_t result = FALSE;
  420. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  421. if(fp != NULL)
  422. {
  423. fseek(fp, 0L, SEEK_END);
  424. file_size = ftell(fp);
  425. if(file_size > (100*1024*1024))
  426. {
  427. result = TRUE;
  428. DEBUG_WARN("Queue file over size.\n");
  429. }
  430. fclose(fp);
  431. }
  432. return result;
  433. }
  434. int showfront(char *uuid, char *data)
  435. {
  436. FILE *fp;
  437. int result = FALSE; // 1: TRUE 0:FALSE
  438. char str[QUEUE_MESSAGE_LENGTH]={0};
  439. char sstr[50]={ 0 };//sstr[200]={ 0 };
  440. int c = 0;
  441. char *loc;
  442. char rmFileCmd[100]={0};
  443. struct stat stats;
  444. stat("/Storage/OCPP", &stats);
  445. // Check for directory existence
  446. if (S_ISDIR(stats.st_mode) == 1)
  447. {
  448. //DEBUG_INFO("\n OCPP directory exist \n");
  449. }
  450. else
  451. {
  452. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  453. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  454. system(rmFileCmd);
  455. }
  456. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  457. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  458. {
  459. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  460. }
  461. else
  462. {
  463. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  464. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  465. if(log == NULL)
  466. {
  467. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  468. return FALSE;
  469. }
  470. else
  471. {
  472. fclose(log);
  473. }
  474. }
  475. /* opening file for reading */
  476. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  477. if(fp == NULL) {
  478. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  479. return FALSE;
  480. }
  481. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL ) {
  482. /* writing content to stdout */
  483. //DEBUG_INFO("str=%s",str);
  484. if ((str[0] == '\n')||(strcmp(str,"")==0))
  485. {
  486. DEBUG_INFO("It is a blank line");
  487. fclose(fp);
  488. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  489. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/TransactionRelatedQueue");
  490. system(rmFileCmd);
  491. result = FALSE;
  492. return result;
  493. }
  494. else
  495. {
  496. //puts(str);
  497. //----------------uuid--------------//
  498. loc = strstr(str, "\"");
  499. memset(sstr ,0, ARRAY_SIZE(sstr) );
  500. c = 0;
  501. while (loc[1+c] != '\"')
  502. {
  503. sstr[c] = loc[1+c];
  504. c++;
  505. }
  506. sstr[c] = '\0';
  507. //DEBUG_INFO("\n uuid:%s", sstr);
  508. //DEBUG_INFO("\n data:%s", str);
  509. strcpy(uuid,sstr);
  510. strcpy(data,str);
  511. result = TRUE;
  512. }
  513. }
  514. else
  515. {
  516. //DEBUG_INFO("queue is null\n");
  517. strcpy(uuid,"");
  518. strcpy(data,"");
  519. result = FALSE;
  520. }
  521. fclose(fp);
  522. return result;
  523. }
  524. int addq(char *uuid, char *data)
  525. {
  526. FILE *outfile;
  527. char rmFileCmd[100]={0};
  528. struct stat stats;
  529. stat("/Storage/OCPP", &stats);
  530. DEBUG_INFO("addq\n");
  531. // Check for directory existence
  532. if (S_ISDIR(stats.st_mode) == 1)
  533. {
  534. //DEBUG_INFO("\n OCPP directory exist \n");
  535. }
  536. else
  537. {
  538. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  539. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  540. system(rmFileCmd);
  541. }
  542. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  543. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  544. {
  545. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  546. }
  547. else
  548. {
  549. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  550. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  551. if(log == NULL)
  552. {
  553. //DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  554. return FALSE;
  555. }
  556. else
  557. {
  558. fclose(log);
  559. }
  560. }
  561. // open file for writing
  562. outfile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "a");
  563. DEBUG_INFO("data = %s\n",data);
  564. fputs(data, outfile);
  565. fputs("\n", outfile);
  566. fclose (outfile);
  567. TransactionQueueNum = TransactionQueueNum + 1;
  568. if(OfflineTransaction == 1) // 0: no offline Transaction 1: offline Transaction
  569. {
  570. OfflineTransactionQueueNum = OfflineTransactionQueueNum + 1;
  571. }
  572. DEBUG_INFO("add queue end\n");
  573. system("/bin/fsync -d /dev/mtdblock13;/bin/sync &");
  574. return FALSE;
  575. }
  576. int delq()
  577. {
  578. char tempfile[] = "/Storage/OCPP/delqtemp.json";
  579. FILE *infile;
  580. FILE *outfile;
  581. int resultRename=0;
  582. char filename[60]={0};
  583. char rmFileCmd[100]={0};
  584. struct stat stats;
  585. stat("/Storage/OCPP", &stats);
  586. DEBUG_INFO("delq()\n");
  587. // Check for directory existence
  588. if (S_ISDIR(stats.st_mode) == 1)
  589. {
  590. //DEBUG_INFO("\n OCPP directory exist \n");
  591. }
  592. else
  593. {
  594. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  595. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  596. system(rmFileCmd);
  597. }
  598. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  599. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  600. {
  601. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  602. }
  603. else
  604. {
  605. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  606. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  607. if(log == NULL)
  608. {
  609. //DEBUG_INFO("log is NULL\n");
  610. return 0;
  611. }
  612. else
  613. {
  614. fclose(log);
  615. }
  616. }
  617. // open file for writing
  618. strcpy(filename, "/Storage/OCPP/TransactionRelatedQueue");
  619. infile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "r");
  620. outfile = fopen (tempfile, "w");
  621. /*检测到文件结束标识返回1,否则返回0。*/
  622. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  623. int c;
  624. c = fgetc(infile);
  625. //printf("file c:%d\n",c);
  626. rewind(infile);
  627. if(c == EOF)
  628. {
  629. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  630. fclose(infile);
  631. fclose(outfile);
  632. sprintf(rmFileCmd,"rm -f %s",tempfile);
  633. system(rmFileCmd);
  634. }
  635. else
  636. {
  637. char buf[QUEUE_MESSAGE_LENGTH]={0};
  638. int i = 0;
  639. //DEBUG_INFO("Orignal File is not NULL\n");
  640. while (fgets(buf, sizeof(buf), infile) != NULL)
  641. {
  642. //printf("Orignal File get strings \n");
  643. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  644. if(i==0)
  645. {
  646. TransactionQueueNum = TransactionQueueNum - 1;
  647. TransactionMessageResend = 1;
  648. DEBUG_INFO("delete the item\n");
  649. }
  650. if(i != 0)
  651. {
  652. fprintf(outfile,"%s\n", buf);
  653. }
  654. i = i + 1;
  655. }
  656. fclose(infile);
  657. fclose(outfile);
  658. sprintf(rmFileCmd,"rm -f %s",filename);
  659. system(rmFileCmd);
  660. resultRename = rename(tempfile, filename);
  661. if(resultRename == 0)
  662. {
  663. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  664. }
  665. else
  666. {
  667. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  668. }
  669. DEBUG_INFO("delq() end\n");
  670. }
  671. system("/bin/fsync -d /dev/mtdblock13;/bin/sync &");
  672. return 0;
  673. }
  674. int showqueue()
  675. {
  676. char rmFileCmd[100]={0};
  677. struct stat stats;
  678. stat("/Storage/OCPP", &stats);
  679. // Check for directory existence
  680. if (S_ISDIR(stats.st_mode) == 1)
  681. {
  682. //DEBUG_INFO("\n OCPP directory exist \n");
  683. }
  684. else
  685. {
  686. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  687. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  688. system(rmFileCmd);
  689. }
  690. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  691. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  692. {
  693. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  694. }
  695. else
  696. {
  697. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  698. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  699. if(log == NULL)
  700. {
  701. DEBUG_INFO("log is NULL\n");
  702. return FALSE;
  703. }
  704. else
  705. {
  706. fclose(log);
  707. }
  708. }
  709. FILE *fp = fopen("/Storage/OCPP/TransactionRelatedQueue", "r");
  710. char line[QUEUE_MESSAGE_LENGTH]={0};
  711. // check if file exist (and you can open it) or not
  712. if (fp == NULL) {
  713. DEBUG_INFO("can open file TransactionRelatedQueue!");
  714. return FALSE;
  715. }
  716. TransactionQueueNum = 0; // the number of packets in queue
  717. while(fgets(line, sizeof line, fp) != NULL) {
  718. //DEBUG_INFO("%s\n", line);
  719. TransactionQueueNum = TransactionQueueNum + 1; //the number of packets in queue
  720. }
  721. fclose(fp);
  722. return TRUE;
  723. }
  724. int sentqueue(){
  725. FILE *fp;
  726. int result = FALSE; // 1: TRUE 0:FALSE
  727. char str[QUEUE_MESSAGE_LENGTH]={0};
  728. char cmdBuf[100]={0};
  729. struct stat stats;
  730. json_object *queueJson;
  731. DEBUG_INFO("Sent queue.\n");
  732. stat("/Storage/OCPP", &stats);
  733. // Check for directory existence
  734. if (S_ISDIR(stats.st_mode) == 1)
  735. {
  736. //DEBUG_INFO("\n OCPP directory exist \n");
  737. }
  738. else
  739. {
  740. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  741. sprintf(cmdBuf,"mkdir -p %s","/Storage/OCPP");
  742. system(cmdBuf);
  743. }
  744. /* opening file for reading */
  745. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  746. if(fp == NULL)
  747. {
  748. DEBUG_ERROR("Error opening file");
  749. return FALSE;
  750. }
  751. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL )
  752. {
  753. queueJson = json_tokener_parse(str);
  754. if(!is_error(queueJson))
  755. {
  756. LWS_Send(str);
  757. }
  758. json_object_put(queueJson);
  759. result = TRUE;
  760. }
  761. else
  762. {
  763. result = FALSE;
  764. }
  765. fclose(fp);
  766. return result;
  767. }
  768. void* processTransactionQueue(void* data)
  769. {
  770. char frontUUID[100] ={0};
  771. char frontData[QUEUE_MESSAGE_LENGTH/*1024*4*/] ={0};
  772. int queueNotEmpty = FALSE;
  773. while(1)
  774. {
  775. if(!req_SendQueue && ((((time((time_t*)NULL) - startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))) || (isWebsocketSendable && ((time((time_t*)NULL) - startTimeQueue) >= ((counterQueueSent>=20)?5:1)))))
  776. {
  777. if(FirstHeartBeatResponse() == 1)
  778. {
  779. memset(frontUUID, 0, ARRAY_SIZE(frontUUID));
  780. memset(frontData, 0, ARRAY_SIZE(frontData));
  781. queueNotEmpty = FALSE;
  782. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  783. if((queueNotEmpty == TRUE) && (GetOcppConnStatus() == 1)) //OcppConnStatus 0: disconnected, 1: connected
  784. {
  785. if(isWebsocketSendable)
  786. DEBUG_INFO("isWebsocketSendable on.\n");
  787. if((((time((time_t*)NULL) - startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))))
  788. DEBUG_INFO("Queue timer(%d) over spec(%d).\n", (time((time_t*)NULL) - startTimeQueue), TransactionMessageRetryIntervalGet());
  789. if((OfflineTransaction == 1) && (OfflineTransactionQueueNum != 0)) //OfflineTransaction 0: no offline Transaction 1: offline Transaction
  790. {
  791. DEBUG_INFO("Sent message from queue request off-line first.\n");
  792. req_SendQueue = 1; // 0: no packets to send 1: send the top packet in queue
  793. OfflineTransactionQueueNum = OfflineTransactionQueueNum - 1;
  794. if(OfflineTransactionQueueNum == 0)
  795. {
  796. OfflineTransaction = 0;
  797. }
  798. }
  799. else
  800. {
  801. if(TransactionMessageResend <= TransactionMessageAttemptsGet()) //
  802. {
  803. DEBUG_INFO("Sent message from queue request.\n");
  804. DEBUG_INFO("TransactionMessageResend = %d\n",TransactionMessageResend);
  805. req_SendQueue = 1;
  806. TransactionMessageResend += 1;
  807. }
  808. else
  809. {
  810. DEBUG_INFO("Transaction message resend(%d) over spec(%d) message abandon.\n", TransactionMessageResend, TransactionMessageAttemptsGet());
  811. queue_operation(QUEUE_OPERATION_DEL,"",""); //// delete item
  812. TransactionMessageResend = 1;
  813. }
  814. }
  815. }
  816. }
  817. if(GetOcppConnStatus() == 0)
  818. {
  819. if(queueNotEmpty == TRUE)
  820. {
  821. OfflineTransaction = 1; // 0: no offline Transaction 1: offline Transaction
  822. }
  823. }
  824. // Refresh queue timer
  825. startTimeQueue = time((time_t*)NULL);
  826. if((counterQueueSent >= 10) || (queueNotEmpty == FALSE))
  827. {
  828. counterQueueSent = 0;
  829. }
  830. else
  831. {
  832. counterQueueSent += 1;
  833. }
  834. }
  835. usleep(500000);
  836. }
  837. pthread_exit(NULL); //
  838. return 0;
  839. }
  840. void* processWatchdog()
  841. {
  842. for(;;)
  843. {
  844. if(((time((time_t*)NULL) - startTimeDog) > 10) && (context != NULL))
  845. {
  846. DEBUG_INFO("LWS watch dog timeout.\n");
  847. lws_cancel_service(context);
  848. lws_cancel_service_pt(wsi_client);
  849. if(counterLwsRestart >= 2)
  850. {
  851. DEBUG_INFO("LWS watch dog timeout over 3 count.\n");
  852. system("pkill OcppBackend");
  853. }
  854. else
  855. counterLwsRestart++;
  856. startTimeDog = time((time_t*)NULL);
  857. }
  858. if(counterConnect >= 2)
  859. {
  860. DEBUG_INFO("Connect OCPP server timeout over 3 count.\n");
  861. system("pkill OcppBackend");
  862. }
  863. /*
  864. if(system("pidof -s Module_PhBackend > /dev/null") != 0)
  865. {
  866. DEBUG_INFO("Module_PhBackend not running, restart it.\r\n");
  867. system("/root/Module_PhBackend &");
  868. }*/
  869. sleep(1);
  870. }
  871. pthread_exit(NULL); //
  872. }
  873. void CheckTransactionPacket(char *uuid)
  874. {
  875. char frontUUID[100]={0};
  876. char frontData[QUEUE_MESSAGE_LENGTH]={0};
  877. int queueNotEmpty = FALSE;
  878. int cmpResult = 0;
  879. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  880. if(queueNotEmpty == TRUE)
  881. {
  882. cmpResult = strcmp(frontUUID, uuid);
  883. if (cmpResult == 0)
  884. {
  885. DEBUG_INFO("Receive queue response match.\n");
  886. queue_operation(QUEUE_OPERATION_DEL,"","");//delq(); ---> remove temporally
  887. TransactionMessageResend = 1;
  888. }
  889. else
  890. DEBUG_INFO("Receive queue response mismatch.\n");
  891. }
  892. }
  893. int queue_operation(int type, char *frontUUID, char *frontData)
  894. {
  895. int result=0;
  896. while(1)
  897. {
  898. if (!IsUsing )
  899. {
  900. IsUsing = TRUE;
  901. if(type == QUEUE_OPERATION_SHOWQUEUE) // show items in queue
  902. {
  903. result = showqueue();
  904. }
  905. else if(type == QUEUE_OPERATION_SHOWFRONT) // show first item
  906. {
  907. result = showfront(frontUUID, frontData);
  908. }
  909. else if(type == QUEUE_OPERATION_DEL) // delete item
  910. {
  911. result = delq();
  912. }
  913. else if(type == QUEUE_OPERATION_SENT) // sent items in queue
  914. {
  915. result = sentqueue();
  916. }
  917. else if(type == QUEUE_OPERATION_ADD) // add items to the queue
  918. {
  919. // If queue file over size only add start * stop transaction message
  920. if(!isQueueOverSize() || (strstr(frontData, "MeterValues") == NULL))
  921. {
  922. result = addq(frontUUID, frontData);
  923. }
  924. }
  925. IsUsing = FALSE;
  926. break;
  927. }
  928. usleep(100000);
  929. }
  930. return result;
  931. }
  932. int removeMessageSentFile(void)
  933. {
  934. char rmFileCmd[100]={0};
  935. struct stat stats;
  936. stat("/Storage/OCPP", &stats);
  937. // Check for directory existence
  938. if(S_ISDIR(stats.st_mode) == 1)
  939. {
  940. //DEBUG_INFO("\n OCPP directory exist \n");
  941. }
  942. else
  943. {
  944. DEBUG_INFO("\n directory not exist, create dir \n");
  945. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  946. system(rmFileCmd);
  947. }
  948. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  949. if((access("/Storage/OCPP/MessageSent",F_OK))!=-1)
  950. {
  951. DEBUG_INFO("MessageSent file exist.\n");
  952. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/MessageSent");
  953. system(rmFileCmd);
  954. }
  955. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  956. return 0;
  957. }
  958. static int changeChageWebSocketPingInterval = FALSE;
  959. void ChageWebSocketPingInterval(int WebSocketPingInterval)
  960. {
  961. changeChageWebSocketPingInterval = TRUE;
  962. }
  963. //================================================
  964. // Main process
  965. //================================================
  966. int main(void)
  967. {
  968. char rmFileCmd[100]={0};
  969. struct stat stats;
  970. DEBUG_INFO("Module_OcppBackend20 task initialization...\n");
  971. //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);
  972. if(ProcessShareMemory()== FAIL)
  973. {
  974. return FAIL;
  975. }
  976. // Check & create OCPP dir
  977. stat("/Storage/OCPP", &stats);
  978. if(S_ISDIR(stats.st_mode) != 1)
  979. {
  980. DEBUG_INFO("OCPP directory not exist, create dir \n");
  981. sprintf(rmFileCmd,"mkdir -p /Storage/OCPP");
  982. system(rmFileCmd);
  983. }
  984. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  985. // Create Process: Resend Transaction
  986. pthread_create(&tid_ProcQueue, NULL, processTransactionQueue, NULL);
  987. pthread_create(&tid_Watchdog, NULL, processWatchdog, NULL);
  988. // Sqlite3 initial
  989. if(DB_Initial() != PASS)
  990. {
  991. DEBUG_ERROR("OCPP 2.0 local database initial fail.\n");
  992. return 0;
  993. }
  994. initialConfigurationTable();
  995. removeMessageSentFile();
  996. for(;;)
  997. {
  998. startTimeDog = time((time_t*)NULL);
  999. counterLwsRestart = 0;
  1000. // Connect server
  1001. if(ConnectionEstablished==0) // Check InternetConn 0: disconnected, 1: connected
  1002. {
  1003. isWebsocketSendable = 1;
  1004. SetOcppConnStatus(FALSE);
  1005. SetServerSign(FALSE);
  1006. InitialSystemValue();
  1007. if((time((time_t*)NULL)-startTime.connect) >= (GetWebSocketPingInterval()>=30?GetWebSocketPingInterval()+5:30))
  1008. {
  1009. DEBUG_INFO("Server connecting...\n");
  1010. pthread_create(&tid_connectServer, NULL, ConnectWsServer, NULL);
  1011. startTime.connect=time((time_t*)NULL);
  1012. }
  1013. CheckSystemValue();
  1014. }
  1015. else
  1016. {
  1017. // Sign in
  1018. if((GetServerSign() == FALSE) &&
  1019. (isConnectorInitMode(0) != TRUE) &&
  1020. ( (GetBootNotificationInterval()>0) ? ((time((time_t*)NULL)-startTime.bootNotification) >= GetBootNotificationInterval()) : ((time((time_t*)NULL)-startTime.bootNotification) >= 10) )
  1021. )
  1022. {
  1023. sendBootNotificationRequest();
  1024. startTime.bootNotification=time((time_t*)NULL);
  1025. }
  1026. // On line operation
  1027. if(GetServerSign() == TRUE)
  1028. {
  1029. // Send message from queue
  1030. if((req_SendQueue == 1) && isWebsocketSendable)
  1031. {
  1032. queue_operation(QUEUE_OPERATION_SENT, "", "");
  1033. req_SendQueue = 0;
  1034. }
  1035. // Check System Value
  1036. CheckSystemValue();
  1037. if(GetHeartBeatWithNOResponse() >= 3)
  1038. {
  1039. lws_context_destroy(context);
  1040. ConnectionEstablished = 0;
  1041. context = NULL;
  1042. SetHeartBeatWithNOResponse();
  1043. }
  1044. if((changeChageWebSocketPingInterval == TRUE) || (GetOcppConnStatus() == 0))
  1045. {
  1046. DEBUG_INFO("GetOcppConnStatus() = %d\n", GetOcppConnStatus());
  1047. changeChageWebSocketPingInterval = FALSE;
  1048. lws_context_destroy(context);
  1049. ConnectionEstablished = 0;
  1050. context = NULL;
  1051. }
  1052. }
  1053. }
  1054. do
  1055. {
  1056. lws_service(context, 0);//timeout_ms
  1057. }while((SendBufLen>0) && (context!=NULL) && GetInternetConn());
  1058. refreshProcDogTimer();
  1059. usleep(100000);
  1060. }
  1061. pthread_join(tid_ProcQueue, NULL);
  1062. pthread_join(tid_Watchdog, NULL);
  1063. return FAIL;
  1064. }