Module_OcppBackend.c 37 KB

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