Module_OcppBackend.c 43 KB

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