Module_OcppBackend.c 43 KB

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