Module_OcppBackend.c 42 KB

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