Module_OcppBackend20.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. #include "Module_OcppBackend20.h"
  2. typedef enum boolean { FALSE, TRUE } BOOL;
  3. struct lws *wsi_client;
  4. struct lws_context *context;
  5. static int req_SendQueue = 0;
  6. pthread_t tid_connectServer;
  7. pthread_t tid_ProcQueue;
  8. pthread_t tid_Watchdog;
  9. struct StartTime
  10. {
  11. struct timespec connect;
  12. struct timespec bootNotification;
  13. struct timespec reConnect;
  14. struct timespec startTimeDog;
  15. struct timespec startTimeQueue;
  16. }startTime;
  17. //==========================================
  18. // Function prototype
  19. //==========================================
  20. void ReceivedMessage(void *in, size_t len);
  21. int SendBufLen=0;//(1024*4);//(1024*3);
  22. unsigned char SendBuffer[WEBSOCKET_BUFFER_SIZE]={0};
  23. static int ConnectionEstablished=0;
  24. static int TransactionMessageResend = 1; // the number of retry to submit a transaction-related message when the Central System fails to process it.
  25. static int TransactionQueueNum = 0;
  26. static int OfflineTransactionQueueNum = 0; // Number of offline transactions
  27. static int OfflineTransaction = 0;
  28. static int IsUsing = FALSE;
  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 counterLwsRestart = 0;;
  36. uint8_t counterQueueSent = 0;
  37. uint8_t counterConnect = 0;
  38. //=================================
  39. // Common routine
  40. //=================================
  41. int GetTransactionQueueNum(void)
  42. {
  43. return 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 + (1024*20) + 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, "\"TransactionEven\"") != 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. static int OCPP20Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
  68. {
  69. char buf[256]={0}, hash[20]={0}, key_b64[40]={0}, tempin[WEBSOCKET_BUFFER_SIZE]={0}, sstr[WEBSOCKET_BUFFER_SIZE]={0};
  70. uint8_t auth_b64[256]={0}, boxId[128]={0}, password[64]={0};
  71. int c = 0;
  72. char *loc;
  73. switch (reason)
  74. {
  75. case LWS_CALLBACK_PROTOCOL_INIT:
  76. DEBUG_INFO("LWS_CALLBACK_PROTOCOL_INIT\n");
  77. break;
  78. case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH:
  79. DEBUG_INFO("LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH\n");
  80. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Client Request START -----\n");
  81. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_URI);
  82. DEBUG_OCPPMESSAGE_INFO("GET %s HTTP/1.1 \n", buf);
  83. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_HOST);
  84. DEBUG_OCPPMESSAGE_INFO("Host: %s\n", buf);
  85. DEBUG_OCPPMESSAGE_INFO("Upgrade: websocket\n");
  86. DEBUG_OCPPMESSAGE_INFO("Connection: Upgrade\n");
  87. lws_b64_encode_string(hash, 16, key_b64, ARRAY_SIZE(key_b64));// Sec-WebSocket-Key
  88. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Key: %s\n", key_b64);
  89. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
  90. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  91. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Version: %d\n", SPEC_LATEST_SUPPORTED);
  92. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Client Request END -----\n");
  93. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Server response START -----\n");
  94. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_HTTP);
  95. DEBUG_OCPPMESSAGE_INFO("HTTP/1.1 %s\n", buf);
  96. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_UPGRADE);
  97. DEBUG_OCPPMESSAGE_INFO("Upgrade: %s\n", buf);
  98. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_CONNECTION);
  99. DEBUG_OCPPMESSAGE_INFO("Connection: %s\n", buf);
  100. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_ACCEPT);
  101. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Accept: %s\n", buf);
  102. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_PROTOCOL);
  103. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  104. DEBUG_OCPPMESSAGE_INFO("----- Handshake: Server response END -----\n");
  105. break;
  106. case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
  107. DEBUG_INFO("LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION\n");
  108. break;
  109. case LWS_CALLBACK_WSI_DESTROY:
  110. DEBUG_INFO("LWS_CALLBACK_WSI_DESTROY\n");
  111. pthread_detach(tid_connectServer);
  112. SetServerSign(FALSE);
  113. ConnectionEstablished = 0;
  114. context = NULL;
  115. break;
  116. case LWS_CALLBACK_LOCK_POLL:
  117. break;
  118. case LWS_CALLBACK_ADD_POLL_FD:
  119. DEBUG_INFO("LWS_CALLBACK_ADD_POLL_FD\n");
  120. break;
  121. case LWS_CALLBACK_DEL_POLL_FD:
  122. DEBUG_INFO("LWS_CALLBACK_DEL_POLL_FD\n");
  123. break;
  124. case LWS_CALLBACK_UNLOCK_POLL:
  125. break;
  126. case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
  127. break;
  128. case LWS_CALLBACK_WSI_CREATE:
  129. DEBUG_INFO("LWS_CALLBACK_WSI_CREATE\n");
  130. break;
  131. case LWS_CALLBACK_GET_THREAD_ID:
  132. break;
  133. case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
  134. DEBUG_INFO("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
  135. unsigned char** pos = (unsigned char**)in;
  136. unsigned char* end = (*pos) + len;
  137. switch(GetOcppSecurityProfile())
  138. {
  139. case 1:
  140. case 2:
  141. case 3:
  142. GetOcppChargerBoxId(boxId);
  143. GetOcppSecurityPassword(password);
  144. sprintf(buf, "%s:%s", boxId, password);
  145. lws_b64_encode_string(buf, strlen(buf), (char*)auth_b64, ARRAY_SIZE(auth_b64));
  146. sprintf(buf, "Basic %s", auth_b64);
  147. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_AUTHORIZATION, (uint8_t *)buf, strlen(buf), pos, end))
  148. {
  149. DEBUG_ERROR("lws_add_http_header_by_token : WSI_TOKEN_HTTP_AUTHORIZATION\n");
  150. return -1;
  151. }
  152. DEBUG_OCPPMESSAGE_INFO("Authorization: %s\n", buf);
  153. break;
  154. case 0:
  155. default:
  156. break;
  157. }
  158. break;
  159. case LWS_CALLBACK_CLIENT_ESTABLISHED: //3
  160. DEBUG_INFO("LWS_CALLBACK_CLIENT_ESTABLISHED\n");
  161. char frontUUID[100] ={0};
  162. char frontData[QUEUE_MESSAGE_LENGTH] ={0};
  163. int queueNotEmpty = FALSE;
  164. //connected
  165. ConnectionEstablished=1;
  166. SetOcppConnStatus(TRUE);
  167. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);
  168. if(queueNotEmpty == TRUE)
  169. {
  170. OfflineTransaction = 1; // 0: no packets in queue. 1: There are packets in queue.
  171. }
  172. TransactionMessageResend = 1;
  173. //get offline number
  174. queue_operation(QUEUE_OPERATION_SHOWQUEUE,"","");
  175. OfflineTransactionQueueNum =TransactionQueueNum ;
  176. break;
  177. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR://1
  178. DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR %s\n", (char *)in );
  179. //disconnected
  180. ConnectionEstablished=0;
  181. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Client START =====\n");
  182. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_URI);
  183. DEBUG_OCPPMESSAGE_INFO("GET %s HTTP/1.1 \n", buf);
  184. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_HOST);
  185. DEBUG_OCPPMESSAGE_INFO("Host: %s\n", buf);
  186. DEBUG_OCPPMESSAGE_INFO("Upgrade: websocket\n");
  187. DEBUG_OCPPMESSAGE_INFO("Connection: Upgrade\n");
  188. lws_b64_encode_string(hash, 16, key_b64, ARRAY_SIZE(key_b64));// Sec-WebSocket-Key
  189. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Key: %s\n", key_b64);
  190. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
  191. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  192. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Version: %d\n", SPEC_LATEST_SUPPORTED);
  193. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Client END =====\n");
  194. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Server response START =====\n");
  195. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_HTTP);
  196. DEBUG_OCPPMESSAGE_INFO("HTTP/1.1 %s\n", buf);
  197. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_UPGRADE);
  198. DEBUG_OCPPMESSAGE_INFO("Upgrade: %s\n", buf);
  199. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_CONNECTION);
  200. DEBUG_OCPPMESSAGE_INFO("Connection: %s\n", buf);
  201. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_ACCEPT);
  202. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Accept: %s\n", buf);
  203. lws_hdr_copy(wsi, buf, ARRAY_SIZE(buf) - 1, WSI_TOKEN_PROTOCOL);
  204. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  205. DEBUG_OCPPMESSAGE_INFO("===== Handshake: Server response END =====\n");
  206. break;
  207. case LWS_CALLBACK_CLOSED://4
  208. DEBUG_INFO("LWS_CALLBACK_CLOSED\n");
  209. //disconnected
  210. ConnectionEstablished=0;
  211. break;
  212. case LWS_CALLBACK_CLIENT_WRITEABLE://10
  213. //if(need to send message and its relevant data already store into SendBuffer)
  214. SendData(wsi);
  215. //lws_rx_flow_control( wsi, 1 );
  216. break;
  217. case LWS_CALLBACK_CLIENT_RECEIVE://8
  218. ((char *)in)[len] = '\0';
  219. DEBUG_OCPPMESSAGE_INFO("<==== %s\n", (char *)in);
  220. //**********Receive Message**********/
  221. c = 0;
  222. loc = strstr((const char *)in, "][2,");
  223. if(loc == NULL)
  224. {
  225. loc = strstr((const char *)in, "][3,");
  226. if(loc == NULL)
  227. {
  228. loc = strstr((const char *)in, "][4,");
  229. }
  230. }
  231. memset(sstr, 0, ARRAY_SIZE(sstr) );
  232. if(loc != NULL)
  233. {
  234. DEBUG_INFO("There are continuous second packet []\n");
  235. while (loc[1+c] != '\0')
  236. {
  237. sstr[c] = loc[1+c];
  238. c++;
  239. }
  240. sstr[c] = '\0';
  241. strcpy(tempin, sstr);
  242. DEBUG_INFO("Final Receive: %s\n", tempin);
  243. }
  244. else
  245. {
  246. strcpy(tempin,(char *)in);
  247. }
  248. ReceivedMessage((void *)strtrim(tempin), strlen(tempin));
  249. isWebsocketSendable = 1;
  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. 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. TransactionQueueNum = TransactionQueueNum + 1;
  555. if(OfflineTransaction == 1) // 0: no offline Transaction 1: offline Transaction
  556. {
  557. OfflineTransactionQueueNum = OfflineTransactionQueueNum + 1;
  558. }
  559. DEBUG_INFO("add queue end\n");
  560. system("/bin/fsync -d /dev/mtdblock13;/bin/sync &");
  561. return FALSE;
  562. }
  563. int delq()
  564. {
  565. char tempfile[] = "/Storage/OCPP/delqtemp.json";
  566. FILE *infile;
  567. FILE *outfile;
  568. int resultRename=0;
  569. char filename[60]={0};
  570. char rmFileCmd[100]={0};
  571. struct stat stats;
  572. stat("/Storage/OCPP", &stats);
  573. DEBUG_INFO("delq()\n");
  574. // Check for directory existence
  575. if (S_ISDIR(stats.st_mode) == 1)
  576. {
  577. //DEBUG_INFO("\n OCPP directory exist \n");
  578. }
  579. else
  580. {
  581. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  582. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  583. system(rmFileCmd);
  584. }
  585. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  586. if((access("/Storage/OCPP/TransactionRelatedQueue20",F_OK))!=-1)
  587. {
  588. //DEBUG_INFO("TransactionRelatedQueue20 exist.\n");
  589. }
  590. else
  591. {
  592. //DEBUG_INFO("TransactionRelatedQueue20 not exist\n");
  593. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue20", "w+");
  594. if(log == NULL)
  595. {
  596. //DEBUG_INFO("log is NULL\n");
  597. return 0;
  598. }
  599. else
  600. {
  601. fclose(log);
  602. }
  603. }
  604. // open file for writing
  605. strcpy(filename, "/Storage/OCPP/TransactionRelatedQueue20");
  606. infile = fopen ("/Storage/OCPP/TransactionRelatedQueue20", "r");
  607. outfile = fopen (tempfile, "w");
  608. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  609. int c;
  610. c = fgetc(infile);
  611. //printf("file c:%d\n",c);
  612. rewind(infile);
  613. if(c == EOF)
  614. {
  615. //DEBUG_INFO("TransactionRelatedQueue20 is NULL\n");
  616. fclose(infile);
  617. fclose(outfile);
  618. sprintf(rmFileCmd,"rm -f %s",tempfile);
  619. system(rmFileCmd);
  620. }
  621. else
  622. {
  623. char buf[QUEUE_MESSAGE_LENGTH]={0};
  624. int i = 0;
  625. //DEBUG_INFO("Orignal File is not NULL\n");
  626. while (fgets(buf, sizeof(buf), infile) != NULL)
  627. {
  628. //printf("Orignal File get strings \n");
  629. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  630. if(i==0)
  631. {
  632. TransactionQueueNum = TransactionQueueNum - 1;
  633. TransactionMessageResend = 1;
  634. DEBUG_INFO("delete the item\n");
  635. }
  636. if(i != 0)
  637. {
  638. fprintf(outfile,"%s\n", buf);
  639. }
  640. i = i + 1;
  641. }
  642. fclose(infile);
  643. fclose(outfile);
  644. sprintf(rmFileCmd,"rm -f %s",filename);
  645. system(rmFileCmd);
  646. resultRename = rename(tempfile, filename);
  647. if(resultRename == 0)
  648. {
  649. //DEBUG_INFO("TransactionRelatedQueue20 file renamed successfully");
  650. }
  651. else
  652. {
  653. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue20 file");
  654. }
  655. DEBUG_INFO("delq() end\n");
  656. }
  657. system("/bin/fsync -d /dev/mtdblock13;/bin/sync &");
  658. return 0;
  659. }
  660. int showqueue()
  661. {
  662. char rmFileCmd[100]={0};
  663. struct stat stats;
  664. stat("/Storage/OCPP", &stats);
  665. // Check for directory existence
  666. if (S_ISDIR(stats.st_mode) == 1)
  667. {
  668. //DEBUG_INFO("\n OCPP directory exist \n");
  669. }
  670. else
  671. {
  672. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  673. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  674. system(rmFileCmd);
  675. }
  676. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  677. if((access("/Storage/OCPP/TransactionRelatedQueue20",F_OK))!=-1)
  678. {
  679. //DEBUG_INFO("TransactionRelatedQueue20 exist.\n");
  680. }
  681. else
  682. {
  683. //DEBUG_INFO("TransactionRelatedQueue20 not exist\n");
  684. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue20", "w+");
  685. if(log == NULL)
  686. {
  687. DEBUG_INFO("log is NULL\n");
  688. return FALSE;
  689. }
  690. else
  691. {
  692. fclose(log);
  693. }
  694. }
  695. FILE *fp = fopen("/Storage/OCPP/TransactionRelatedQueue20", "r");
  696. char line[QUEUE_MESSAGE_LENGTH]={0};
  697. // check if file exist (and you can open it) or not
  698. if (fp == NULL) {
  699. DEBUG_INFO("can open file TransactionRelatedQueue20!");
  700. return FALSE;
  701. }
  702. TransactionQueueNum = 0; // the number of packets in queue
  703. while(fgets(line, sizeof line, fp) != NULL) {
  704. //DEBUG_INFO("%s\n", line);
  705. TransactionQueueNum = TransactionQueueNum + 1; //the number of packets in queue
  706. }
  707. fclose(fp);
  708. return TRUE;
  709. }
  710. int sentqueue(){
  711. FILE *fp;
  712. int result = FALSE; // 1: TRUE 0:FALSE
  713. char str[QUEUE_MESSAGE_LENGTH]={0};
  714. char cmdBuf[100]={0};
  715. struct stat stats;
  716. json_object *queueJson;
  717. DEBUG_INFO("Sent queue.\n");
  718. stat("/Storage/OCPP", &stats);
  719. // Check for directory existence
  720. if (S_ISDIR(stats.st_mode) == 1)
  721. {
  722. //DEBUG_INFO("\n OCPP directory exist \n");
  723. }
  724. else
  725. {
  726. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  727. sprintf(cmdBuf,"mkdir -p %s","/Storage/OCPP");
  728. system(cmdBuf);
  729. }
  730. /* opening file for reading */
  731. fp = fopen("/Storage/OCPP/TransactionRelatedQueue20" , "r");
  732. if(fp == NULL)
  733. {
  734. DEBUG_ERROR("Error opening file");
  735. return FALSE;
  736. }
  737. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL )
  738. {
  739. queueJson = json_tokener_parse(str);
  740. if(!is_error(queueJson))
  741. {
  742. LWS_Send(str);
  743. }
  744. json_object_put(queueJson);
  745. result = TRUE;
  746. }
  747. else
  748. {
  749. result = FALSE;
  750. }
  751. fclose(fp);
  752. return result;
  753. }
  754. void* processTransactionQueue(void* data)
  755. {
  756. char frontUUID[100] ={0};
  757. char frontData[QUEUE_MESSAGE_LENGTH/*1024*4*/] ={0};
  758. int queueNotEmpty = FALSE;
  759. while(1)
  760. {
  761. if(!req_SendQueue && ((getDiffSecNow(startTime.startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10)) || (isWebsocketSendable && isQueueSendable && (getDiffSecNow(startTime.startTimeQueue) >= ((counterQueueSent>=20)?5:0)))))
  762. {
  763. if(FirstHeartBeatResponse() == 1)
  764. {
  765. memset(frontUUID, 0, ARRAY_SIZE(frontUUID));
  766. memset(frontData, 0, ARRAY_SIZE(frontData));
  767. queueNotEmpty = FALSE;
  768. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  769. if((queueNotEmpty == TRUE) && (GetOcppConnStatus() == 1)) //OcppConnStatus 0: disconnected, 1: connected
  770. {
  771. if(isWebsocketSendable)
  772. DEBUG_INFO("isWebsocketSendable on.\n");
  773. if(isQueueSendable)
  774. DEBUG_INFO("isQueueSendable on.\n");
  775. if(((getDiffSecNow(startTime.startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))))
  776. DEBUG_INFO("Queue timer(%d) over spec(%d).\n", getDiffSecNow(startTime.startTimeQueue), TransactionMessageRetryIntervalGet());
  777. if((OfflineTransaction == 1) && (OfflineTransactionQueueNum != 0)) //OfflineTransaction 0: no offline Transaction 1: offline Transaction
  778. {
  779. DEBUG_INFO("Sent message from queue request off-line first.\n");
  780. req_SendQueue = 1; // 0: no packets to send 1: send the top packet in queue
  781. OfflineTransactionQueueNum = OfflineTransactionQueueNum - 1;
  782. if(OfflineTransactionQueueNum == 0)
  783. {
  784. OfflineTransaction = 0;
  785. }
  786. }
  787. else
  788. {
  789. if(TransactionMessageResend <= TransactionMessageAttemptsGet()) //
  790. {
  791. DEBUG_INFO("Sent message from queue request.\n");
  792. DEBUG_INFO("TransactionMessageResend = %d\n",TransactionMessageResend);
  793. req_SendQueue = 1;
  794. TransactionMessageResend += 1;
  795. }
  796. else
  797. {
  798. DEBUG_INFO("Transaction message resend(%d) over spec(%d) message abandon.\n", TransactionMessageResend, TransactionMessageAttemptsGet());
  799. queue_operation(QUEUE_OPERATION_DEL,"",""); //// delete item
  800. TransactionMessageResend = 1;
  801. }
  802. }
  803. }
  804. }
  805. if(GetOcppConnStatus() == 0)
  806. {
  807. if(queueNotEmpty == TRUE)
  808. {
  809. OfflineTransaction = 1; // 0: no offline Transaction 1: offline Transaction
  810. }
  811. }
  812. // Refresh queue timer
  813. refreshStartTimer(&startTime.startTimeQueue);
  814. if((counterQueueSent >= 10) || (queueNotEmpty == FALSE))
  815. {
  816. counterQueueSent = 0;
  817. }
  818. else
  819. {
  820. counterQueueSent += 1;
  821. }
  822. }
  823. usleep(500000);
  824. }
  825. pthread_exit(NULL); //
  826. return 0;
  827. }
  828. void* processWatchdog()
  829. {
  830. for(;;)
  831. {
  832. if((getDiffSecNow(startTime.startTimeDog) > 10) && (context != NULL))
  833. {
  834. DEBUG_INFO("LWS watch dog timeout.\n");
  835. lws_cancel_service(context);
  836. lws_cancel_service_pt(wsi_client);
  837. if(counterLwsRestart >= 2)
  838. {
  839. DEBUG_INFO("LWS watch dog timeout over 3 count.\n");
  840. system("pkill OcppBackend");
  841. }
  842. else
  843. counterLwsRestart++;
  844. refreshStartTimer(&startTime.startTimeDog);
  845. }
  846. if(counterConnect >= 2)
  847. {
  848. DEBUG_INFO("Connect OCPP server timeout over 3 count.\n");
  849. system("pkill OcppBackend");
  850. }
  851. /*
  852. if(system("pidof -s Module_PhBackend > /dev/null") != 0)
  853. {
  854. DEBUG_INFO("Module_PhBackend not running, restart it.\r\n");
  855. system("/root/Module_PhBackend &");
  856. }*/
  857. sleep(1);
  858. }
  859. pthread_exit(NULL); //
  860. }
  861. void CheckTransactionPacket(char *uuid)
  862. {
  863. char frontUUID[100]={0};
  864. char frontData[QUEUE_MESSAGE_LENGTH]={0};
  865. int queueNotEmpty = FALSE;
  866. int cmpResult = 0;
  867. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  868. if(queueNotEmpty == TRUE)
  869. {
  870. cmpResult = strcmp(frontUUID, uuid);
  871. if (cmpResult == 0)
  872. {
  873. DEBUG_INFO("Receive queue response match.\n");
  874. queue_operation(QUEUE_OPERATION_DEL,"","");//delq(); ---> remove temporally
  875. TransactionMessageResend = 1;
  876. }
  877. else
  878. DEBUG_INFO("Receive queue response mismatch.\n");
  879. }
  880. }
  881. int queue_operation(int type, char *frontUUID, char *frontData)
  882. {
  883. int result=0;
  884. while(1)
  885. {
  886. if (!IsUsing )
  887. {
  888. IsUsing = TRUE;
  889. if(type == QUEUE_OPERATION_SHOWQUEUE) // show items in queue
  890. {
  891. result = showqueue();
  892. }
  893. else if(type == QUEUE_OPERATION_SHOWFRONT) // show first item
  894. {
  895. result = showfront(frontUUID, frontData);
  896. }
  897. else if(type == QUEUE_OPERATION_DEL) // delete item
  898. {
  899. result = delq();
  900. }
  901. else if(type == QUEUE_OPERATION_SENT) // sent items in queue
  902. {
  903. result = sentqueue();
  904. }
  905. else if(type == QUEUE_OPERATION_ADD) // add items to the queue
  906. {
  907. // If queue file over size only add start * stop transaction message
  908. if(!isQueueOverSize() || (strstr(frontData, "MeterValues") == NULL))
  909. {
  910. result = addq(frontUUID, frontData);
  911. }
  912. }
  913. IsUsing = FALSE;
  914. break;
  915. }
  916. usleep(100000);
  917. }
  918. return result;
  919. }
  920. int removeMessageSentFile(void)
  921. {
  922. char rmFileCmd[100]={0};
  923. struct stat stats;
  924. stat("/Storage/OCPP", &stats);
  925. // Check for directory existence
  926. if(S_ISDIR(stats.st_mode) == 1)
  927. {
  928. //DEBUG_INFO("\n OCPP directory exist \n");
  929. }
  930. else
  931. {
  932. DEBUG_INFO("\n directory not exist, create dir \n");
  933. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  934. system(rmFileCmd);
  935. }
  936. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  937. if((access("/Storage/OCPP/MessageSent",F_OK))!=-1)
  938. {
  939. DEBUG_INFO("MessageSent file exist.\n");
  940. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/MessageSent");
  941. system(rmFileCmd);
  942. }
  943. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  944. return 0;
  945. }
  946. static int changeChageWebSocketPingInterval = FALSE;
  947. void ChageWebSocketPingInterval(int WebSocketPingInterval)
  948. {
  949. changeChageWebSocketPingInterval = TRUE;
  950. }
  951. //================================================
  952. // Main process
  953. //================================================
  954. int main(void)
  955. {
  956. char rmFileCmd[100]={0};
  957. struct stat stats;
  958. DEBUG_INFO("Module_OcppBackend20 task initialization...\n");
  959. //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);
  960. if(ProcessShareMemory()== FAIL)
  961. {
  962. return FAIL;
  963. }
  964. // Check & create OCPP dir
  965. stat("/Storage/OCPP", &stats);
  966. if(S_ISDIR(stats.st_mode) != 1)
  967. {
  968. DEBUG_INFO("OCPP directory not exist, create dir \n");
  969. sprintf(rmFileCmd,"mkdir -p /Storage/OCPP");
  970. system(rmFileCmd);
  971. }
  972. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  973. // Create Process: Resend Transaction
  974. pthread_create(&tid_ProcQueue, NULL, processTransactionQueue, NULL);
  975. pthread_create(&tid_Watchdog, NULL, processWatchdog, NULL);
  976. // Sqlite3 initial
  977. if(DB_Initial() != PASS)
  978. {
  979. DEBUG_ERROR("OCPP 2.0 local database initial fail.\n");
  980. return 0;
  981. }
  982. initialConfigurationTable();
  983. removeMessageSentFile();
  984. for(;;)
  985. {
  986. refreshStartTimer(&startTime.startTimeDog);
  987. counterLwsRestart = 0;
  988. // Connect server
  989. if(ConnectionEstablished==0) // Check InternetConn 0: disconnected, 1: connected
  990. {
  991. isWebsocketSendable = 1;
  992. isQueueSendable = 1;
  993. SetOcppConnStatus(FALSE);
  994. SetServerSign(FALSE);
  995. InitialSystemValue();
  996. if(getDiffSecNow(startTime.connect) >= 30)
  997. {
  998. DEBUG_INFO("Server connecting...\n");
  999. pthread_create(&tid_connectServer, NULL, ConnectWsServer, NULL);
  1000. refreshStartTimer(&startTime.connect);
  1001. }
  1002. CheckSystemValue();
  1003. }
  1004. else
  1005. {
  1006. // Sign in
  1007. if((GetServerSign() == FALSE) &&
  1008. (isConnectorInitMode(0) != TRUE) &&
  1009. ( (GetBootNotificationInterval()>0) ? (getDiffSecNow(startTime.bootNotification) >= GetBootNotificationInterval()) : (getDiffSecNow(startTime.bootNotification) >= 10) )
  1010. )
  1011. {
  1012. sendBootNotificationRequest();
  1013. refreshStartTimer(&startTime.bootNotification);
  1014. }
  1015. // On line operation
  1016. if(GetServerSign() == TRUE)
  1017. {
  1018. // Send message from queue
  1019. if((req_SendQueue == 1) && isWebsocketSendable)
  1020. {
  1021. queue_operation(QUEUE_OPERATION_SENT, "", "");
  1022. req_SendQueue = 0;
  1023. }
  1024. // Check System Value
  1025. CheckSystemValue();
  1026. if(GetHeartBeatWithNOResponse() >= 3)
  1027. {
  1028. lws_context_destroy(context);
  1029. ConnectionEstablished = 0;
  1030. context = NULL;
  1031. SetHeartBeatWithNOResponse();
  1032. }
  1033. if((changeChageWebSocketPingInterval == TRUE) || (GetOcppConnStatus() == 0))
  1034. {
  1035. if(getDiffSecNow(startTime.reConnect) >= 3)
  1036. {
  1037. DEBUG_INFO("GetOcppConnStatus() = %d\n", GetOcppConnStatus());
  1038. changeChageWebSocketPingInterval = FALSE;
  1039. lws_context_destroy(context);
  1040. ConnectionEstablished = 0;
  1041. context = NULL;
  1042. }
  1043. }
  1044. else
  1045. {
  1046. refreshStartTimer(&startTime.reConnect);
  1047. }
  1048. }
  1049. }
  1050. do
  1051. {
  1052. lws_service(context, 0);//timeout_ms
  1053. }while((SendBufLen>0) && (context!=NULL) && GetInternetConn());
  1054. refreshProcDogTimer();
  1055. usleep(100000);
  1056. }
  1057. pthread_join(tid_ProcQueue, NULL);
  1058. pthread_join(tid_Watchdog, NULL);
  1059. return FAIL;
  1060. }