Module_OcppBackend.c 41 KB

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