Module_OcppBackend.c 40 KB

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