Module_OcppBackend20.c 32 KB

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