Module_OcppBackend.c 43 KB

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