Module_OcppBackend20.c 32 KB

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