Module_OcppBackend20.c 32 KB

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