Module_OcppBackend20.c 32 KB

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