Module_OcppBackend20.c 33 KB

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