Module_OcppBackend20.c 38 KB

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