Module_OcppBackend.c 42 KB

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