Module_OcppBackend20.c 34 KB

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