Module_OcppBackend20.c 33 KB

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