Module_OcppBackend20.c 32 KB

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