Module_OcppBackend20.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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. system("pkill ntpd");
  305. DEBUG_INFO("NTP synchronize with Microsoft\n", system("/usr/sbin/ntpd -nqp time.windows.com &"));
  306. DEBUG_INFO("NTP synchronize with China\n", system("/usr/sbin/ntpd -nqp cn.ntp.org.cn &"));
  307. DEBUG_INFO("NTP synchronize with Taiwan\n", system("/usr/sbin/ntpd -nqp tock.stdtime.gov.tw &"));
  308. DEBUG_INFO("NTP synchronize with Europe\n", system("/usr/sbin/ntpd -nqp 0.europe.pool.ntp.org &"));
  309. }
  310. if(context!=NULL)
  311. {
  312. pthread_detach(pthread_self());
  313. lws_context_destroy(context);
  314. ConnectionEstablished=0;
  315. context = NULL;
  316. }
  317. checkNetworkProfile();
  318. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  319. if((GetOcppServerURL()==0) || (GetOcppPort() == 0) || (GetOcppPath()==0))
  320. {
  321. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  322. goto end;
  323. }
  324. if((strcmp(OcppProtocol,"ws")==0)&&(strlen(OcppProtocol)== 2))
  325. {
  326. DEBUG_INFO("Web socket is non-security mode.\n");
  327. use_ssl=0;
  328. }
  329. else if((strcmp(OcppProtocol,"wss")==0)&&(strlen(OcppProtocol)== 3))
  330. {
  331. DEBUG_INFO("Web socket is security mode.\n");
  332. use_ssl=1;
  333. }
  334. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  335. ContextInfo.iface = NULL;
  336. ContextInfo.ssl_private_key_password = NULL;
  337. ContextInfo.ssl_cert_filepath = NULL;//"./ssl_key/client_cert.pem";
  338. ContextInfo.ssl_private_key_filepath = NULL;//"./ssl_key/client_key.pem";
  339. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";//"./cacert.pem";
  340. ContextInfo.ssl_cipher_list = NULL; //use default one
  341. ContextInfo.gid = -1;
  342. ContextInfo.uid = -1;
  343. if(use_ssl)
  344. {
  345. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT ;
  346. }
  347. ContextInfo.protocols = protocols;
  348. ContextInfo.timeout_secs = GetWebSocketPingInterval();//WebSocketPingInterval;//30;//9999;//30;
  349. ContextInfo.ws_ping_pong_interval = GetWebSocketPingInterval();//WebSocketPingInterval;//30;//0 for none, else interval in seconds
  350. context = lws_create_context(&ContextInfo);
  351. if (context == NULL)
  352. {
  353. DEBUG_ERROR("lws_create_context NG");
  354. goto end;
  355. }
  356. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  357. // fill up below information
  358. ConnInfo.context = context;
  359. ConnInfo.address=(const char *)OcppHost;
  360. DEBUG_INFO("ConnInfo.address: %s\n", ConnInfo.address);
  361. ConnInfo.port = GetOcppPort();
  362. DEBUG_INFO("ConnInfo.port: %d\n", ConnInfo.port);
  363. ConnInfo.path=(const char *)OcppPath;
  364. DEBUG_INFO("ConnInfo.path: %s\n", ConnInfo.path);
  365. char addr_port[256] = { 0 };
  366. sprintf(addr_port, "%s:%u", ConnInfo.address, (ConnInfo.port & 65535) );
  367. ConnInfo.host= addr_port; // ConnInfo.address;//lws_canonical_hostname(context);
  368. //ConnInfo.origin="origin";
  369. ConnInfo.protocol = protocols[1].name;
  370. ConnInfo.ietf_version_or_minus_one = -1;
  371. if(use_ssl)
  372. {
  373. #ifdef TLS_VALID_CERT_EXPIRED
  374. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
  375. DEBUG_INFO("TLS does not allow expired certification.\n");
  376. #else
  377. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK | LCCSCF_ALLOW_EXPIRED;
  378. DEBUG_INFO("TLS allow expired certification.\n");
  379. #endif
  380. }
  381. wsi_client = lws_client_connect_via_info(&ConnInfo);
  382. if (!wsi_client)
  383. {
  384. DEBUG_ERROR("lws_client_connect_via_info NG\n");
  385. goto end;
  386. }
  387. end:
  388. pthread_exit(NULL/*(void *) fname*/);
  389. }
  390. int isQueueOverSize()
  391. {
  392. FILE *fp;
  393. uint32_t file_size;
  394. uint8_t result = FALSE;
  395. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  396. if(fp != NULL)
  397. {
  398. fseek(fp, 0L, SEEK_END);
  399. file_size = ftell(fp);
  400. if(file_size > (500*1024*1024))
  401. {
  402. result = TRUE;
  403. DEBUG_WARN("Queue file over size.\n");
  404. }
  405. fclose(fp);
  406. }
  407. return result;
  408. }
  409. int showfront(char *uuid, char *data)
  410. {
  411. FILE *fp;
  412. int result = FALSE; // 1: TRUE 0:FALSE
  413. char str[QUEUE_MESSAGE_LENGTH]={0};
  414. char sstr[50]={ 0 };//sstr[200]={ 0 };
  415. int c = 0;
  416. char *loc;
  417. char rmFileCmd[100]={0};
  418. struct stat stats;
  419. stat("/Storage/OCPP", &stats);
  420. // Check for directory existence
  421. if (S_ISDIR(stats.st_mode) == 1)
  422. {
  423. //DEBUG_INFO("\n OCPP directory exist \n");
  424. }
  425. else
  426. {
  427. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  428. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  429. system(rmFileCmd);
  430. }
  431. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  432. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  433. {
  434. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  435. }
  436. else
  437. {
  438. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  439. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  440. if(log == NULL)
  441. {
  442. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  443. return FALSE;
  444. }
  445. else
  446. {
  447. fclose(log);
  448. }
  449. }
  450. /* opening file for reading */
  451. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  452. if(fp == NULL) {
  453. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  454. return FALSE;
  455. }
  456. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL ) {
  457. /* writing content to stdout */
  458. //DEBUG_INFO("str=%s",str);
  459. if ((str[0] == '\n')||(strcmp(str,"")==0))
  460. {
  461. DEBUG_INFO("It is a blank line");
  462. fclose(fp);
  463. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  464. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/TransactionRelatedQueue");
  465. system(rmFileCmd);
  466. result = FALSE;
  467. return result;
  468. }
  469. else
  470. {
  471. //puts(str);
  472. //----------------uuid--------------//
  473. loc = strstr(str, "\"");
  474. memset(sstr ,0, ARRAY_SIZE(sstr) );
  475. c = 0;
  476. while (loc[1+c] != '\"')
  477. {
  478. sstr[c] = loc[1+c];
  479. c++;
  480. }
  481. sstr[c] = '\0';
  482. //DEBUG_INFO("\n uuid:%s", sstr);
  483. //DEBUG_INFO("\n data:%s", str);
  484. strcpy(uuid,sstr);
  485. strcpy(data,str);
  486. result = TRUE;
  487. }
  488. }
  489. else
  490. {
  491. //DEBUG_INFO("queue is null\n");
  492. strcpy(uuid,"");
  493. strcpy(data,"");
  494. result = FALSE;
  495. }
  496. fclose(fp);
  497. return result;
  498. }
  499. int addq(char *uuid, char *data)
  500. {
  501. FILE *outfile;
  502. char rmFileCmd[100]={0};
  503. struct stat stats;
  504. stat("/Storage/OCPP", &stats);
  505. DEBUG_INFO("addq\n");
  506. // Check for directory existence
  507. if (S_ISDIR(stats.st_mode) == 1)
  508. {
  509. //DEBUG_INFO("\n OCPP directory exist \n");
  510. }
  511. else
  512. {
  513. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  514. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  515. system(rmFileCmd);
  516. }
  517. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  518. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  519. {
  520. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  521. }
  522. else
  523. {
  524. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  525. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  526. if(log == NULL)
  527. {
  528. //DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  529. return FALSE;
  530. }
  531. else
  532. {
  533. fclose(log);
  534. }
  535. }
  536. // open file for writing
  537. outfile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "a");
  538. DEBUG_INFO("data = %s\n",data);
  539. fputs(data, outfile);
  540. fputs("\n", outfile);
  541. fclose (outfile);
  542. TransactionQueueNum = TransactionQueueNum + 1;
  543. if(OfflineTransaction == 1) // 0: no offline Transaction 1: offline Transaction
  544. {
  545. OfflineTransactionQueueNum = OfflineTransactionQueueNum + 1;
  546. }
  547. DEBUG_INFO("add queue end\n");
  548. return FALSE;
  549. }
  550. int delq()
  551. {
  552. char tempfile[] = "/Storage/OCPP/delqtemp.json";
  553. FILE *infile;
  554. FILE *outfile;
  555. int resultRename=0;
  556. char filename[60]={0};
  557. char rmFileCmd[100]={0};
  558. struct stat stats;
  559. stat("/Storage/OCPP", &stats);
  560. DEBUG_INFO("delq()\n");
  561. // Check for directory existence
  562. if (S_ISDIR(stats.st_mode) == 1)
  563. {
  564. //DEBUG_INFO("\n OCPP directory exist \n");
  565. }
  566. else
  567. {
  568. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  569. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  570. system(rmFileCmd);
  571. }
  572. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  573. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  574. {
  575. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  576. }
  577. else
  578. {
  579. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  580. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  581. if(log == NULL)
  582. {
  583. //DEBUG_INFO("log is NULL\n");
  584. return 0;
  585. }
  586. else
  587. {
  588. fclose(log);
  589. }
  590. }
  591. // open file for writing
  592. strcpy(filename, "/Storage/OCPP/TransactionRelatedQueue");
  593. infile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "r");
  594. outfile = fopen (tempfile, "w");
  595. /*检测到文件结束标识返回1,否则返回0。*/
  596. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  597. int c;
  598. c = fgetc(infile);
  599. //printf("file c:%d\n",c);
  600. rewind(infile);
  601. if(c == EOF)
  602. {
  603. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  604. fclose(infile);
  605. fclose(outfile);
  606. sprintf(rmFileCmd,"rm -f %s",tempfile);
  607. system(rmFileCmd);
  608. }
  609. else
  610. {
  611. char buf[QUEUE_MESSAGE_LENGTH]={0};
  612. int i = 0;
  613. //DEBUG_INFO("Orignal File is not NULL\n");
  614. while (fgets(buf, sizeof(buf), infile) != NULL)
  615. {
  616. //printf("Orignal File get strings \n");
  617. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  618. if(i==0)
  619. {
  620. TransactionQueueNum = TransactionQueueNum - 1;
  621. TransactionMessageResend = 1;
  622. DEBUG_INFO("delete the item\n");
  623. }
  624. if(i != 0)
  625. {
  626. fprintf(outfile,"%s\n", buf);
  627. }
  628. i = i + 1;
  629. }
  630. fclose(infile);
  631. fclose(outfile);
  632. sprintf(rmFileCmd,"rm -f %s",filename);
  633. system(rmFileCmd);
  634. resultRename = rename(tempfile, filename);
  635. if(resultRename == 0)
  636. {
  637. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  638. }
  639. else
  640. {
  641. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  642. }
  643. DEBUG_INFO("delq() end\n");
  644. }
  645. return 0;
  646. }
  647. int showqueue()
  648. {
  649. char rmFileCmd[100]={0};
  650. struct stat stats;
  651. stat("/Storage/OCPP", &stats);
  652. // Check for directory existence
  653. if (S_ISDIR(stats.st_mode) == 1)
  654. {
  655. //DEBUG_INFO("\n OCPP directory exist \n");
  656. }
  657. else
  658. {
  659. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  660. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  661. system(rmFileCmd);
  662. }
  663. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  664. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  665. {
  666. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  667. }
  668. else
  669. {
  670. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  671. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  672. if(log == NULL)
  673. {
  674. DEBUG_INFO("log is NULL\n");
  675. return FALSE;
  676. }
  677. else
  678. {
  679. fclose(log);
  680. }
  681. }
  682. FILE *fp = fopen("/Storage/OCPP/TransactionRelatedQueue", "r");
  683. char line[QUEUE_MESSAGE_LENGTH]={0};
  684. // check if file exist (and you can open it) or not
  685. if (fp == NULL) {
  686. DEBUG_INFO("can open file TransactionRelatedQueue!");
  687. return FALSE;
  688. }
  689. TransactionQueueNum = 0; // the number of packets in queue
  690. while(fgets(line, sizeof line, fp) != NULL) {
  691. //DEBUG_INFO("%s\n", line);
  692. TransactionQueueNum = TransactionQueueNum + 1; //the number of packets in queue
  693. }
  694. fclose(fp);
  695. return TRUE;
  696. }
  697. int sentqueue(){
  698. FILE *fp;
  699. int result = FALSE; // 1: TRUE 0:FALSE
  700. char str[QUEUE_MESSAGE_LENGTH]={0};
  701. char rmFileCmd[100]={0};
  702. struct stat stats;
  703. json_object *queueJson;
  704. DEBUG_INFO("Sent queue.\n");
  705. stat("/Storage/OCPP", &stats);
  706. // Check for directory existence
  707. if (S_ISDIR(stats.st_mode) == 1)
  708. {
  709. //DEBUG_INFO("\n OCPP directory exist \n");
  710. }
  711. else
  712. {
  713. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  714. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  715. system(rmFileCmd);
  716. }
  717. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  718. /* opening file for reading */
  719. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  720. if(fp == NULL) {
  721. DEBUG_INFO("Error opening file");
  722. return FALSE;
  723. }
  724. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL )
  725. {
  726. queueJson = json_tokener_parse(str+2);
  727. if(!is_error(queueJson))
  728. {
  729. LWS_Send(str+2);
  730. }
  731. json_object_put(queueJson);
  732. result = TRUE;
  733. }
  734. else
  735. {
  736. result = FALSE;
  737. }
  738. fclose(fp);
  739. return result;
  740. }
  741. void* processTransactionQueue(void* data)
  742. {
  743. char frontUUID[100] ={0};
  744. char frontData[QUEUE_MESSAGE_LENGTH/*1024*4*/] ={0};
  745. int queueNotEmpty = FALSE;
  746. while(1)
  747. {
  748. if(!req_SendQueue && ((((time((time_t*)NULL) - startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))) || (isWebsocketSendable && ((time((time_t*)NULL) - startTimeQueue) >= ((counterQueueSent>=20)?5:1)))))
  749. {
  750. if(FirstHeartBeatResponse() == 1)
  751. {
  752. memset(frontUUID, 0, ARRAY_SIZE(frontUUID));
  753. memset(frontData, 0, ARRAY_SIZE(frontData));
  754. queueNotEmpty = FALSE;
  755. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  756. if((queueNotEmpty == TRUE) && (GetOcppConnStatus() == 1)) //OcppConnStatus 0: disconnected, 1: connected
  757. {
  758. if(isWebsocketSendable)
  759. DEBUG_INFO("isWebsocketSendable on.\n");
  760. if((((time((time_t*)NULL) - startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))))
  761. DEBUG_INFO("Queue timer(%d) over spec(%d).\n", (time((time_t*)NULL) - startTimeQueue), TransactionMessageRetryIntervalGet());
  762. if((OfflineTransaction == 1) && (OfflineTransactionQueueNum != 0)) //OfflineTransaction 0: no offline Transaction 1: offline Transaction
  763. {
  764. DEBUG_INFO("Sent message from queue request off-line first.\n");
  765. req_SendQueue = 1; // 0: no packets to send 1: send the top packet in queue
  766. OfflineTransactionQueueNum = OfflineTransactionQueueNum - 1;
  767. if(OfflineTransactionQueueNum == 0)
  768. {
  769. OfflineTransaction = 0;
  770. }
  771. }
  772. else
  773. {
  774. if(TransactionMessageResend <= TransactionMessageAttemptsGet()) //
  775. {
  776. DEBUG_INFO("Sent message from queue request.\n");
  777. DEBUG_INFO("TransactionMessageResend = %d\n",TransactionMessageResend);
  778. req_SendQueue = 1;
  779. TransactionMessageResend += 1;
  780. }
  781. else
  782. {
  783. DEBUG_INFO("Transaction message resend(%d) over spec(%d) message abandon.\n", TransactionMessageResend, TransactionMessageAttemptsGet());
  784. queue_operation(QUEUE_OPERATION_DEL,"",""); //// delete item
  785. TransactionMessageResend = 1;
  786. }
  787. }
  788. }
  789. }
  790. if(GetOcppConnStatus() == 0)
  791. {
  792. if(queueNotEmpty == TRUE)
  793. {
  794. OfflineTransaction = 1; // 0: no offline Transaction 1: offline Transaction
  795. }
  796. }
  797. // Refresh queue timer
  798. startTimeQueue = time((time_t*)NULL);
  799. if((counterQueueSent >= 10) || (queueNotEmpty == FALSE))
  800. {
  801. counterQueueSent = 0;
  802. }
  803. else
  804. {
  805. counterQueueSent += 1;
  806. }
  807. }
  808. usleep(500000);
  809. }
  810. pthread_exit(NULL); //
  811. return 0;
  812. }
  813. void* processWatchdog()
  814. {
  815. for(;;)
  816. {
  817. if(((time((time_t*)NULL) - startTimeDog) > 10) && (context != NULL))
  818. {
  819. DEBUG_INFO("LWS watch dog timeout.\n");
  820. lws_cancel_service(context);
  821. lws_cancel_service_pt(wsi_client);
  822. if(counterLwsRestart >= 2)
  823. {
  824. DEBUG_INFO("LWS watch dog timeout over 3 count.\n");
  825. system("pkill OcppBackend");
  826. }
  827. else
  828. counterLwsRestart++;
  829. startTimeDog = time((time_t*)NULL);
  830. }
  831. /*
  832. if(system("pidof -s Module_PhBackend > /dev/null") != 0)
  833. {
  834. DEBUG_INFO("Module_PhBackend not running, restart it.\r\n");
  835. system("/root/Module_PhBackend &");
  836. }*/
  837. sleep(1);
  838. }
  839. pthread_exit(NULL); //
  840. }
  841. void CheckTransactionPacket(char *uuid)
  842. {
  843. char frontUUID[100]={0};
  844. char frontData[QUEUE_MESSAGE_LENGTH]={0};
  845. int queueNotEmpty = FALSE;
  846. int cmpResult = 0;
  847. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  848. if(queueNotEmpty == TRUE)
  849. {
  850. cmpResult = strcmp(frontUUID, uuid);
  851. if (cmpResult == 0)
  852. {
  853. DEBUG_INFO("Receive queue response match.\n");
  854. queue_operation(QUEUE_OPERATION_DEL,"","");//delq(); ---> remove temporally
  855. TransactionMessageResend = 1;
  856. }
  857. else
  858. DEBUG_INFO("Receive queue response mismatch.\n");
  859. }
  860. }
  861. int queue_operation(int type, char *frontUUID, char *frontData)
  862. {
  863. int result=0;
  864. while(1)
  865. {
  866. if (!IsUsing )
  867. {
  868. IsUsing = TRUE;
  869. if(type == QUEUE_OPERATION_SHOWQUEUE) // show items in queue
  870. {
  871. result = showqueue();
  872. }
  873. else if(type == QUEUE_OPERATION_SHOWFRONT) // show first item
  874. {
  875. result = showfront(frontUUID, frontData);
  876. }
  877. else if(type == QUEUE_OPERATION_DEL) // delete item
  878. {
  879. result = delq();
  880. }
  881. else if(type == QUEUE_OPERATION_SENT) // sent items in queue
  882. {
  883. result = sentqueue();
  884. }
  885. else if(type == QUEUE_OPERATION_ADD) // add items to the queue
  886. {
  887. // If queue file over size only add start * stop transaction message
  888. if(!isQueueOverSize() || (strstr(frontData, "MeterValues") == NULL))
  889. {
  890. result = addq(frontUUID, frontData);
  891. }
  892. }
  893. IsUsing = FALSE;
  894. break;
  895. }
  896. usleep(100000);
  897. }
  898. return result;
  899. }
  900. int removeMessageSentFile(void)
  901. {
  902. char rmFileCmd[100]={0};
  903. struct stat stats;
  904. stat("/Storage/OCPP", &stats);
  905. // Check for directory existence
  906. if(S_ISDIR(stats.st_mode) == 1)
  907. {
  908. //DEBUG_INFO("\n OCPP directory exist \n");
  909. }
  910. else
  911. {
  912. DEBUG_INFO("\n directory not exist, create dir \n");
  913. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  914. system(rmFileCmd);
  915. }
  916. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  917. if((access("/Storage/OCPP/MessageSent",F_OK))!=-1)
  918. {
  919. DEBUG_INFO("MessageSent file exist.\n");
  920. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/MessageSent");
  921. system(rmFileCmd);
  922. }
  923. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  924. return 0;
  925. }
  926. static int changeChageWebSocketPingInterval = FALSE;
  927. void ChageWebSocketPingInterval(int WebSocketPingInterval)
  928. {
  929. changeChageWebSocketPingInterval = TRUE;
  930. }
  931. //================================================
  932. // Main process
  933. //================================================
  934. int main(void)
  935. {
  936. char rmFileCmd[100]={0};
  937. struct stat stats;
  938. DEBUG_INFO("Module_OcppBackend task initialization...\n");
  939. //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);
  940. if(ProcessShareMemory()== FAIL)
  941. {
  942. return FAIL;
  943. }
  944. // Check & create OCPP dir
  945. stat("/Storage/OCPP", &stats);
  946. if(S_ISDIR(stats.st_mode) != 1)
  947. {
  948. DEBUG_INFO("OCPP directory not exist, create dir \n");
  949. sprintf(rmFileCmd,"mkdir -p /Storage/OCPP");
  950. system(rmFileCmd);
  951. }
  952. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  953. // Create Process: Resend Transaction
  954. pthread_create(&tid_ProcQueue, NULL, processTransactionQueue, NULL);
  955. pthread_create(&tid_Watchdog, NULL, processWatchdog, NULL);
  956. // Sqlite3 initial
  957. if(DB_Initial() != PASS)
  958. {
  959. DEBUG_ERROR("OCPP 2.0 local database initial fail.\n");
  960. return 0;
  961. }
  962. initialConfigurationTable();
  963. removeMessageSentFile();
  964. for(;;)
  965. {
  966. startTimeDog = time((time_t*)NULL);
  967. counterLwsRestart = 0;
  968. // Connect server
  969. if(ConnectionEstablished==0) // Check InternetConn 0: disconnected, 1: connected
  970. {
  971. isWebsocketSendable = 1;
  972. SetOcppConnStatus(FALSE);
  973. SetServerSign(FALSE);
  974. InitialSystemValue();
  975. if((time((time_t*)NULL)-startTime.connect) >= (GetWebSocketPingInterval()>=30?GetWebSocketPingInterval()+5:30))
  976. {
  977. DEBUG_INFO("Server connecting...\n");
  978. pthread_create(&tid_connectServer, NULL, ConnectWsServer, NULL);
  979. startTime.connect=time((time_t*)NULL);
  980. }
  981. CheckSystemValue();
  982. }
  983. else
  984. {
  985. // Sign in
  986. if((GetServerSign() == FALSE) &&
  987. ((GetBootNotificationInterval() >= 0) && ((time((time_t*)NULL)-startTime.bootNotification)>= GetBootNotificationInterval())))
  988. {
  989. sendBootNotificationRequest();
  990. startTime.bootNotification=time((time_t*)NULL);
  991. }
  992. // On line operation
  993. if(GetServerSign() == TRUE)
  994. {
  995. // Send message from queue
  996. if((req_SendQueue == 1) && isWebsocketSendable)
  997. {
  998. queue_operation(QUEUE_OPERATION_SENT, "", "");
  999. req_SendQueue = 0;
  1000. }
  1001. // Check System Value
  1002. CheckSystemValue();
  1003. if(GetHeartBeatWithNOResponse() >= 3)
  1004. {
  1005. lws_context_destroy(context);
  1006. ConnectionEstablished = 0;
  1007. context = NULL;
  1008. SetHeartBeatWithNOResponse();
  1009. }
  1010. if((changeChageWebSocketPingInterval == TRUE) || (GetOcppConnStatus() == 0))
  1011. {
  1012. DEBUG_INFO("GetOcppConnStatus() = %d\n", GetOcppConnStatus());
  1013. changeChageWebSocketPingInterval = FALSE;
  1014. lws_context_destroy(context);
  1015. ConnectionEstablished = 0;
  1016. context = NULL;
  1017. }
  1018. }
  1019. }
  1020. do
  1021. {
  1022. lws_service(context, 0);//timeout_ms
  1023. }while((SendBufLen>0) && (context!=NULL) && GetInternetConn());
  1024. usleep(100000);
  1025. }
  1026. pthread_join(tid_ProcQueue, NULL);
  1027. pthread_join(tid_Watchdog, NULL);
  1028. return FAIL;
  1029. }