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