Module_OcppBackend20.c 33 KB

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