Module_OcppBackend.c 43 KB

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