Module_OcppBackend.c 42 KB

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