Module_OcppBackend20.c 33 KB

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