Module_OcppBackend.c 38 KB

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