Module_OcppBackend.c 45 KB

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