Module_OcppBackend.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  1. #include <sys/time.h>
  2. #include <sys/timeb.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <sys/ioctl.h>
  6. #include <sys/socket.h>
  7. #include <sys/ipc.h>
  8. #include <sys/shm.h>
  9. #include <sys/shm.h>
  10. #include <sys/mman.h>
  11. #include <linux/wireless.h>
  12. #include <linux/sockios.h>
  13. #include <linux/socket.h>
  14. #include <arpa/inet.h>
  15. #include <netinet/in.h>
  16. #include <unistd.h>
  17. #include <stdarg.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <unistd.h>
  21. #include <fcntl.h>
  22. #include <termios.h>
  23. #include <errno.h>
  24. #include <errno.h>
  25. #include <string.h>
  26. #include <time.h>
  27. #include <ctype.h>
  28. #include <ifaddrs.h>
  29. #include "libwebsockets.h"
  30. #include <lws_config.h>
  31. #include "hashmap.h"
  32. #include "SystemLogMessage.h"
  33. #include "ShareMemory.h"
  34. #include <pthread.h>
  35. #include "MessageHandler.h"
  36. #include "sqlite3.h"
  37. #if 0
  38. #define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
  39. #define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
  40. #define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
  41. #endif
  42. #define Debug
  43. //#define ARRAY_SIZE(A) (sizeof(A) / sizeof(A[0]))
  44. #define PASS 1
  45. #define FAIL -1
  46. typedef enum boolean { FALSE, TRUE } BOOL;
  47. struct lws *wsi_client;
  48. struct lws_context *context;
  49. static int sendbuffer = 0;
  50. extern int server_sign;
  51. //extern int TransactionMessageAttemptsValue;
  52. //extern int TransactionMessageRetryIntervalValue;
  53. //extern int server_pending;
  54. //extern struct OCPP16Data *ShmOCPP16Data;
  55. extern void CheckSystemValue(void);
  56. //extern int TransactionMessageAttemptsGet(void);
  57. extern int FirstHeartBeatResponse(void);
  58. extern void OCPP_get_TableAuthlocalAllData(void);
  59. extern int TransactionMessageAttemptsGet(void);
  60. extern int TransactionMessageRetryIntervalGet(void);
  61. extern int GetOcppConnStatus(void);
  62. extern void SetOcppConnStatus(uint8_t status);
  63. extern int GetHeartBeatWithNOResponse(void);
  64. extern void SetHeartBeatWithNOResponse(void);
  65. //extern int InternetDisconnect(void);
  66. pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
  67. pthread_mutex_t lock_sentData = PTHREAD_MUTEX_INITIALIZER;
  68. pthread_mutex_t receiveData = PTHREAD_MUTEX_INITIALIZER;
  69. //struct json_object *parsed_json;
  70. //extern struct node Node;
  71. //==========================================
  72. // Function prototype
  73. //==========================================
  74. void trim(char *s);
  75. int mystrcmp(char *p1,char *p2);
  76. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
  77. void getSubStr(char *dest, char* src, char *split, int idx);
  78. void split(char **arr, char *str, const char *del);
  79. int strpos(char *source, char *substr, int skip);
  80. int strposs(char *source, char *substr, int idx);
  81. char *random_uuid( char buf[37] );
  82. static int OCPP16Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len);
  83. char * strchr(const char *p, int ch);
  84. void ReceivedMessage(void *in, size_t len);
  85. struct StartTime
  86. {
  87. unsigned int connect;
  88. unsigned int bootNotification;
  89. }startTime;
  90. #if 0
  91. unsigned char *SendBuffer;
  92. int SendBufLen=(1024*4);//(1024*3);
  93. #endif
  94. int SendBufLen=(1024*4);//(1024*3);
  95. unsigned char SendBuffer[1024*4]={0};
  96. static int ConnectionEstablished=0;
  97. static int TransactionMessageResend = 1;
  98. static int TransactionQueueInterval = 10;//3; // TransactionMessageAttempts
  99. static int TransactionQueueNum = 0;
  100. static int OfflineTransaction = 0;
  101. int defaultWaitingTime = 10; //10 second
  102. //===============================
  103. // OCPP SentQueue TransactionId
  104. //===============================
  105. static int SentQueueTransactionId[10]={0};
  106. extern int BootNotificationInterval;
  107. //char guid[37];
  108. //map_t hashMap;
  109. //data_struct_t* mapItem; --- remove for temporally
  110. //data_struct_t mapItem[0]={0};
  111. sqlite3 *db;
  112. char *errMsg = NULL;
  113. static char *createsql = "CREATE TABLE IF NOT EXISTS log_buffer("
  114. "idx integer primary key,"
  115. "user_id text,"
  116. "cmd_sn text,"
  117. "charger_id text,"
  118. "gun_type text,"
  119. "gun_no text,"
  120. "rfid_no text,"
  121. "stime text,"
  122. "etime text,"
  123. "time_len text,"
  124. "s_soc text,"
  125. "e_soc text,"
  126. "stop_reason text,"
  127. "power text,"
  128. "meter_before text,"
  129. "meter_after text,"
  130. "charge_price text,"
  131. "reserve text,"
  132. "surplus_before text,"
  133. "surplus_after text,"
  134. "service_price text,"
  135. "is_pay text,"
  136. "charge_strategy text,"
  137. "charge_parameter text,"
  138. "vin text,"
  139. "vehicle_no text,"
  140. "start_method text,"
  141. "card_type text,"
  142. "is_upload text,"
  143. "guid text UNIQUE,"
  144. "is_buf2OK text);";
  145. #if 0
  146. static char *createsChargingRecordsql = "CREATE TABLE IF NOT EXISTS ChargingRecord("
  147. "idx integer primary key,"
  148. "gun_type text,"
  149. "connectorId text,"
  150. "idTag text,"
  151. "transactionId text,"
  152. "stime text,"
  153. "etime text,"
  154. "time_len text,"
  155. "s_soc text,"
  156. "e_soc text,"
  157. "stop_reason text,"
  158. "power text,"
  159. "meter_before text,"
  160. "meter_after text,"
  161. "reservationId text,"
  162. "guid text UNIQUE);";
  163. //"is_buf2OK text);";
  164. #endif
  165. static char *sqlOcppAuthCache = "create table if not exists ocpp_auth_cache (idx integer primary key,"
  166. "idtag text UNIQUE,"
  167. "parent_idtag text,"
  168. "expir_date text,"
  169. "status text);";
  170. static char *sqlOcppAuthLocal = "create table if not exists ocpp_auth_local (idx integer primary key,"
  171. "idtag text UNIQUE,"
  172. "parent_idtag text,"
  173. "expir_date text,"
  174. "status text,"
  175. "version text);";
  176. #if 0
  177. static char *sqlInitialOcppAuthLocal = "insert or replace into ocpp_auth_local(idtag, parent_idtag, expir_date, status, version) values('PaHdImHiOnNG','none','2099-12-31T23:59:59.999Z','Accepted','0')";
  178. #endif
  179. int DiffTimeb(struct timeb ST, struct timeb ET)
  180. {
  181. //return milli-second
  182. unsigned int StartTime,StopTime;
  183. StartTime=(unsigned int)ST.time;
  184. StopTime=(unsigned int)ET.time;
  185. return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
  186. }
  187. //=================================
  188. // Common routine
  189. //=================================
  190. void trim(char *s)
  191. {
  192. int i=0, j, k, l=0;
  193. while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
  194. i++;
  195. j = strlen(s)-1;
  196. while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
  197. j--;
  198. if(i==0 && j==strlen(s)-1) { }
  199. else if(i==0) s[j+1] = '\0';
  200. else {
  201. for(k=i; k<=j; k++) s[l++] = s[k];
  202. s[l] = '\0';
  203. }
  204. }
  205. int mystrcmp(char *p1,char *p2)
  206. {
  207. while(*p1==*p2)
  208. {
  209. if(*p1=='\0' || *p2=='\0')
  210. break;
  211. p1++;
  212. p2++;
  213. }
  214. if(*p1=='\0' && *p2=='\0')
  215. return(PASS);
  216. else
  217. return(FAIL);
  218. }
  219. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
  220. {
  221. strncpy(dest, src + start, cnt);
  222. dest[cnt] = 0;
  223. }
  224. void getSubStr(char *dest, char* src, char *split, int idx)
  225. {
  226. int start = (strposs(src,",",idx)+1);
  227. int cnt = (strposs(src,",",idx+1)-2)-(strposs(src,",",idx)+1);
  228. strncpy(dest, src + start, cnt);
  229. dest[cnt] = 0;
  230. }
  231. void split(char **arr, char *str, const char *del)
  232. {
  233. char *s = strtok(str, del);
  234. while(s != NULL)
  235. {
  236. *arr++ = s;
  237. s = strtok(NULL, del);
  238. }
  239. }
  240. int strpos(char *source, char *substr, int skip)
  241. {
  242. char stack[strlen(source)];
  243. strncpy(stack, source+skip, strlen(source)-skip);
  244. char *p = strstr(stack, substr);
  245. if (p)
  246. return p - stack+skip;
  247. return -1;
  248. }
  249. int strposs(char *source, char *substr, int idx)
  250. {
  251. char stack[strlen(source)];
  252. int result=0;
  253. int count=0;
  254. while(count<=idx)
  255. {
  256. memset(stack,0,sizeof stack);
  257. strncpy(stack, source+result, strlen(source)-result);
  258. int loc = strcspn(stack, substr);
  259. if(loc>0)
  260. result += (loc+1);
  261. else
  262. result = -1;
  263. count++;
  264. }
  265. return result;
  266. }
  267. char *random_uuid( char buf[37] )
  268. {
  269. const char *c = "89ab";
  270. char *p = buf;
  271. int n;
  272. for( n = 0; n < 16; ++n )
  273. {
  274. int b = rand()%255;
  275. switch( n )
  276. {
  277. case 6:
  278. sprintf(p, "4%x", b%15 );
  279. break;
  280. case 8:
  281. sprintf(p, "%c%x", c[rand()%strlen(c)], b%15 );
  282. break;
  283. default:
  284. sprintf(p, "%02x", b);
  285. break;
  286. }
  287. p += 2;
  288. switch( n )
  289. {
  290. case 3:
  291. case 5:
  292. case 7:
  293. case 9:
  294. *p++ = '-';
  295. break;
  296. }
  297. }
  298. *p = 0;
  299. return buf;
  300. }
  301. //==========================================
  302. // Web socket tranceive routine
  303. //==========================================
  304. int SendData(struct lws *wsi)
  305. {
  306. int n;
  307. int len;
  308. char *ret;
  309. unsigned char out[LWS_SEND_BUFFER_PRE_PADDING + 4096 + LWS_SEND_BUFFER_POST_PADDING] = {0};
  310. len = strlen((char *)SendBuffer);
  311. if(len == 0)
  312. return 0;
  313. memcpy (out + LWS_SEND_BUFFER_PRE_PADDING, SendBuffer, len );
  314. ret = strstr((const char *)(out + LWS_SEND_BUFFER_PRE_PADDING), "Heartbeat");
  315. if(ret == NULL)
  316. {
  317. DEBUG_OCPPMESSAGE_INFO(" SendData= %s\n", out + LWS_SEND_BUFFER_PRE_PADDING);
  318. }
  319. n = lws_write(wsi, out + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
  320. memset(SendBuffer, 0, len);
  321. return n;
  322. }
  323. static int OCPP16Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
  324. {
  325. switch (reason)
  326. {
  327. case LWS_CALLBACK_PROTOCOL_INIT:
  328. #ifdef SystemLogMessage
  329. DEBUG_INFO("LWS_CALLBACK_PROTOCOL_INIT\n");
  330. #endif
  331. break;
  332. case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH:
  333. #ifdef SystemLogMessage
  334. DEBUG_INFO("LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH\n");
  335. #endif
  336. break;
  337. case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
  338. #ifdef SystemLogMessage
  339. DEBUG_INFO("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
  340. #endif
  341. break;
  342. case LWS_CALLBACK_WSI_DESTROY:
  343. #ifdef SystemLogMessage
  344. DEBUG_INFO("LWS_CALLBACK_WSI_DESTROY\n");
  345. #endif
  346. server_sign = FALSE;
  347. break;
  348. case LWS_CALLBACK_LOCK_POLL:
  349. break;
  350. case LWS_CALLBACK_ADD_POLL_FD:
  351. #ifdef SystemLogMessage
  352. DEBUG_INFO("LWS_CALLBACK_ADD_POLL_FD\n");
  353. #endif
  354. break;
  355. case LWS_CALLBACK_DEL_POLL_FD:
  356. #ifdef SystemLogMessage
  357. DEBUG_INFO("LWS_CALLBACK_DEL_POLL_FD\n");
  358. #endif
  359. break;
  360. case LWS_CALLBACK_UNLOCK_POLL:
  361. break;
  362. case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
  363. break;
  364. case LWS_CALLBACK_WSI_CREATE:
  365. #ifdef SystemLogMessage
  366. DEBUG_INFO("LWS_CALLBACK_WSI_CREATE\n");
  367. #endif
  368. break;
  369. case LWS_CALLBACK_GET_THREAD_ID:
  370. break;
  371. case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
  372. #ifdef SystemLogMessage
  373. DEBUG_INFO("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
  374. #endif
  375. break;
  376. case LWS_CALLBACK_CLIENT_ESTABLISHED://3
  377. #ifdef SystemLogMessage
  378. DEBUG_INFO("LWS_CALLBACK_CLIENT_ESTABLISHED\n");
  379. #endif
  380. //connected
  381. ConnectionEstablished=1;
  382. break;
  383. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR://1
  384. #ifdef Debug
  385. DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR:%s\n",in);
  386. #endif
  387. #ifdef SystemLogMessage
  388. DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
  389. #endif
  390. //disconnected
  391. ConnectionEstablished=0;
  392. break;
  393. case LWS_CALLBACK_CLOSED://4
  394. #ifdef SystemLogMessage
  395. DEBUG_INFO("LWS_CALLBACK_CLOSED\n");
  396. ConnectionEstablished=0;
  397. #endif
  398. //disconnected
  399. break;
  400. case LWS_CALLBACK_CLIENT_WRITEABLE://10
  401. //if(need to send message and its relevant data already store into SendBuffer)
  402. #ifdef SystemLogMessage
  403. //DEBUG_INFO("LWS_CALLBACK_CLIENT_WRITEABLE\n");
  404. #endif
  405. SendData(wsi);
  406. break;
  407. case LWS_CALLBACK_CLIENT_RECEIVE://8
  408. ((char *)in)[len] = '\0';
  409. //Print Out Adjudgement
  410. {
  411. char *ret, *ret1;
  412. ret = strstr((const char *)in, "currentTime");
  413. ret1 = strstr((const char *)in, "interval");
  414. if(!((ret != NULL)&&(ret1 == NULL)))
  415. {
  416. DEBUG_OCPPMESSAGE_INFO("Original Receive %s\n", (char *)in);
  417. }
  418. }
  419. char tempin[1024*4]={0};
  420. int c = 0;
  421. char *loc;
  422. char sstr[600]={ 0 };
  423. //**********Receive Message**********/
  424. c = 0;
  425. loc = strstr((const char *)in, "][2,");
  426. if(loc == NULL)
  427. {
  428. loc = strstr((const char *)in, "][3,");
  429. if(loc == NULL)
  430. {
  431. loc = strstr((const char *)in, "][4,");
  432. }
  433. }
  434. memset(sstr ,0, sizeof(sstr) );
  435. if(loc != NULL)
  436. {
  437. DEBUG_INFO("there are continuous second packet []\n");
  438. while (loc[1+c] != '\0')
  439. {
  440. sstr[c] = loc[1+c];
  441. c++;
  442. }
  443. sstr[c] = '\0';
  444. strcpy(tempin, sstr);
  445. DEBUG_INFO("Final Receive: %s\n", tempin);
  446. }
  447. else
  448. {
  449. strcpy(tempin,(char *)in);
  450. }
  451. ReceivedMessage((void *)tempin, len);
  452. break;
  453. default:
  454. #ifdef Debug
  455. DEBUG_INFO("OCPP16Callback:reason=%d\n", reason);
  456. #endif
  457. break;
  458. }
  459. return 0;
  460. }
  461. static struct lws_protocols protocols[] = {
  462. {
  463. "ocpp1.6",
  464. OCPP16Callback,
  465. 10240,
  466. 10240,
  467. },
  468. {
  469. "ocpp1.6",
  470. OCPP16Callback,
  471. 10240,
  472. 10240,
  473. },
  474. {
  475. NULL, NULL, 0 /* End of list */
  476. }
  477. };
  478. int ConnectWsServer()
  479. {
  480. int result = PASS;
  481. struct lws_context_creation_info ContextInfo;
  482. struct lws_client_connect_info ConnInfo;
  483. int use_ssl=0;
  484. //lws_set_log_level(LLL_PARSER | LLL_HEADER, NULL);
  485. if(context!=NULL)
  486. lws_context_destroy(context);
  487. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  488. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  489. ContextInfo.iface = NULL;
  490. ContextInfo.ssl_private_key_password = NULL;
  491. ContextInfo.ssl_cert_filepath = NULL;
  492. ContextInfo.ssl_private_key_filepath = NULL;
  493. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";
  494. ContextInfo.ssl_cipher_list = NULL; //use default one
  495. ContextInfo.gid = -1;
  496. ContextInfo.uid = -1;
  497. if(use_ssl)
  498. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
  499. ContextInfo.protocols = protocols;
  500. ContextInfo.timeout_secs = 9999;//30;
  501. //if(ping pong enabled)
  502. ContextInfo.ws_ping_pong_interval = 30;//0 for none, else interval in seconds
  503. context = lws_create_context(&ContextInfo);
  504. if (context == NULL)
  505. {
  506. #ifdef SystemLogMessage
  507. DEBUG_ERROR("lws_create_context NG");
  508. #endif
  509. result = FAIL;
  510. }
  511. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  512. // fill up below information
  513. ConnInfo.context = context;
  514. if((strcmp((const char *)GetOcppServerURL(),"")==0) || (GetOcppPort() == 0) || (strcmp((const char *)GetOcppPath(),"")==0) )
  515. {
  516. result = FAIL;
  517. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  518. return result;
  519. }
  520. ConnInfo.address=(const char *)GetOcppServerURL();
  521. ConnInfo.port = GetOcppPort();
  522. ConnInfo.path=(const char *)GetOcppPath();
  523. ConnInfo.host=lws_canonical_hostname(context);
  524. ConnInfo.origin="origin";
  525. ConnInfo.protocol = protocols[1].name;
  526. ConnInfo.ietf_version_or_minus_one = -1;
  527. if(use_ssl)
  528. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;;
  529. wsi_client = lws_client_connect_via_info(&ConnInfo);
  530. if (!wsi_client)
  531. {
  532. #ifdef SystemLogMessage
  533. DEBUG_ERROR("lws_client_connect_via_info NG");
  534. #endif
  535. result = FAIL;
  536. }
  537. return result;
  538. }
  539. //void createq();
  540. int showfront(char *uuid, char *data);
  541. int addq(char *uuid, char *data) ;
  542. int delq();
  543. int sentqueue();
  544. void CheckTransactionPacket(char *uuid);
  545. int queue_operation(int type, char *frontUUID, char *frontData);
  546. int showfront(char *uuid, char *data) {
  547. FILE *fp;
  548. int result = FALSE; // 1: TRUE 0:FALSE
  549. char str[1200]={0};
  550. char sstr[50]={ 0 };//sstr[200]={ 0 };
  551. int c = 0;
  552. char *loc;
  553. char rmFileCmd[100]={0};
  554. struct stat stats;
  555. stat("../Storage/OCPP", &stats);
  556. // Check for directory existence
  557. if (S_ISDIR(stats.st_mode) == 1)
  558. {
  559. //DEBUG_INFO("\n OCPP directory exist \n");
  560. }
  561. else
  562. {
  563. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  564. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  565. system(rmFileCmd);
  566. }
  567. memset(rmFileCmd, 0, sizeof rmFileCmd);
  568. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  569. {
  570. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  571. }
  572. else
  573. {
  574. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  575. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  576. if(log == NULL)
  577. {
  578. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  579. return 0;
  580. }
  581. else
  582. {
  583. fclose(log);
  584. }
  585. }
  586. /* opening file for reading */
  587. fp = fopen("../Storage/OCPP/TransactionRelatedQueue" , "r");
  588. if(fp == NULL) {
  589. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  590. return FALSE;
  591. }
  592. if(fgetc(fp)==EOF)
  593. {
  594. //DEBUG_INFO("It is end of file");
  595. fclose(fp);
  596. memset(rmFileCmd, 0, sizeof rmFileCmd);
  597. sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/TransactionRelatedQueue");
  598. system(rmFileCmd);
  599. result = FALSE;
  600. return result;
  601. }
  602. if( fgets (str, 1200, fp)!=NULL ) {
  603. /* writing content to stdout */
  604. //DEBUG_INFO("str=%s",str);
  605. if ((str[0] == '\n')||(strcmp(str,"")==0))
  606. {
  607. DEBUG_INFO("It is a blank line");
  608. fclose(fp);
  609. memset(rmFileCmd, 0, sizeof rmFileCmd);
  610. sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/TransactionRelatedQueue");
  611. system(rmFileCmd);
  612. result = FALSE;
  613. return result;
  614. }
  615. else
  616. {
  617. //puts(str);
  618. /*********************uuid***************/
  619. loc = strstr(str, "\"");
  620. memset(sstr ,0, sizeof(sstr) );
  621. c = 0;
  622. while (loc[1+c] != '\"')
  623. {
  624. sstr[c] = loc[1+c];
  625. c++;
  626. }
  627. sstr[c] = '\0';
  628. //DEBUG_INFO("\n uuid:%s", sstr);
  629. //DEBUG_INFO("\n data:%s", str);
  630. strcpy(uuid,sstr);
  631. strcpy(data,str);
  632. result = TRUE;
  633. }
  634. //return 1;
  635. }
  636. else
  637. {
  638. //DEBUG_INFO("queue is null\n");
  639. strcpy(uuid,"");
  640. strcpy(data,"");
  641. result = FALSE;
  642. //return 0;
  643. }
  644. fclose(fp);
  645. return result;
  646. }
  647. int addq(char *uuid, char *data) {
  648. FILE *outfile;
  649. char rmFileCmd[100]={0};
  650. struct stat stats;
  651. stat("../Storage/OCPP", &stats);
  652. //DEBUG_INFO("addq\n");
  653. // Check for directory existence
  654. if (S_ISDIR(stats.st_mode) == 1)
  655. {
  656. //DEBUG_INFO("\n OCPP directory exist \n");
  657. }
  658. else
  659. {
  660. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  661. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  662. system(rmFileCmd);
  663. }
  664. memset(rmFileCmd, 0, sizeof rmFileCmd);
  665. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  666. {
  667. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  668. }
  669. else
  670. {
  671. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  672. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  673. if(log == NULL)
  674. {
  675. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  676. return 0;
  677. }
  678. else
  679. {
  680. fclose(log);
  681. }
  682. }
  683. // open file for writing
  684. outfile = fopen ("../Storage/OCPP/TransactionRelatedQueue", "a");
  685. //DEBUG_INFO("data=%s\n",data);
  686. fputs(data, outfile);
  687. fputs("\n", outfile);
  688. fclose (outfile);
  689. TransactionQueueNum = TransactionQueueNum + 1;
  690. return 0;
  691. }
  692. int delq() {
  693. char tempfile[] = "../Storage/OCPP/temp.json";
  694. FILE *infile;
  695. FILE *outfile;
  696. int resultRename=0;
  697. char filename[60]={0};
  698. char rmFileCmd[100]={0};
  699. struct stat stats;
  700. stat("../Storage/OCPP", &stats);
  701. DEBUG_INFO("delq()\n");
  702. // Check for directory existence
  703. if (S_ISDIR(stats.st_mode) == 1)
  704. {
  705. //DEBUG_INFO("\n OCPP directory exist \n");
  706. }
  707. else
  708. {
  709. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  710. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  711. system(rmFileCmd);
  712. }
  713. memset(rmFileCmd, 0, sizeof rmFileCmd);
  714. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  715. {
  716. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  717. }
  718. else
  719. {
  720. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  721. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  722. if(log == NULL)
  723. {
  724. DEBUG_INFO("log is NULL\n");
  725. return 0;
  726. }
  727. else
  728. {
  729. fclose(log);
  730. }
  731. }
  732. // open file for writing
  733. strcpy(filename, "../Storage/OCPP/TransactionRelatedQueue");
  734. infile = fopen ("../Storage/OCPP/TransactionRelatedQueue", "r");
  735. outfile = fopen (tempfile, "w");
  736. /*检测到文件结束标识返回1,否则返回0。*/
  737. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  738. int c;
  739. c = fgetc(infile);
  740. //printf("file c:%d\n",c);
  741. rewind(infile);
  742. if(c == EOF)
  743. {
  744. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  745. fclose(infile);
  746. fclose(outfile);
  747. sprintf(rmFileCmd,"rm -f %s",tempfile);
  748. system(rmFileCmd);
  749. }
  750. else
  751. {
  752. char buf[1200]={0};
  753. int i = 0;
  754. //DEBUG_INFO("Orignal File is not NULL\n");
  755. while (fgets(buf, sizeof(buf), infile) != NULL)
  756. {
  757. //printf("Orignal File get strings \n");
  758. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  759. if(i==0)
  760. {
  761. TransactionQueueNum = TransactionQueueNum - 1;
  762. TransactionQueueInterval = 0;
  763. TransactionMessageResend = 1;
  764. }
  765. if(i != 0)
  766. fprintf(outfile,"%s\n", buf);
  767. i = i + 1;
  768. }
  769. fclose(infile);
  770. fclose(outfile);
  771. sprintf(rmFileCmd,"rm -f %s",filename);
  772. system(rmFileCmd);
  773. resultRename = rename(tempfile, filename);
  774. if(resultRename == 0)
  775. {
  776. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  777. }
  778. else
  779. {
  780. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  781. }
  782. }
  783. return 0;
  784. }
  785. int showqueue() {
  786. char rmFileCmd[100]={0};
  787. struct stat stats;
  788. stat("../Storage/OCPP", &stats);
  789. // Check for directory existence
  790. if (S_ISDIR(stats.st_mode) == 1)
  791. {
  792. //DEBUG_INFO("\n OCPP directory exist \n");
  793. }
  794. else
  795. {
  796. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  797. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  798. system(rmFileCmd);
  799. }
  800. memset(rmFileCmd, 0, sizeof rmFileCmd);
  801. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  802. {
  803. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  804. }
  805. else
  806. {
  807. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  808. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  809. if(log == NULL)
  810. {
  811. DEBUG_INFO("log is NULL\n");
  812. return 0;
  813. }
  814. else
  815. {
  816. fclose(log);
  817. }
  818. }
  819. FILE *fp = fopen("../Storage/OCPP/TransactionRelatedQueue", "r");
  820. char line[1200]={0};
  821. // check if file exist (and you can open it) or not
  822. if (fp == NULL) {
  823. DEBUG_INFO("can open file TransactionRelatedQueue!");
  824. return 0;
  825. }
  826. while(fgets(line, sizeof line, fp) != NULL) {
  827. DEBUG_INFO("%s\n", line);
  828. }
  829. fclose(fp);
  830. return 0;
  831. }
  832. int sentqueue(){
  833. FILE *fp;
  834. int result = FALSE; // 1: TRUE 0:FALSE
  835. int temptransactionId = 0;
  836. int tempconnectorId = 0;
  837. int gunIndex = 0;
  838. char guid[37]={0};
  839. char tempdata[65]={0};
  840. char key_value[65]={0};
  841. int IsStopTransaction = FALSE;
  842. char str[1200]={0};
  843. char strcomposite[1200]={0};
  844. char rmFileCmd[100]={0};
  845. struct stat stats;
  846. char sstr[28]={ 0 };
  847. int c = 0;
  848. char *loc;
  849. DEBUG_INFO("sentqueue\n");
  850. stat("../Storage/OCPP", &stats);
  851. // Check for directory existence
  852. if (S_ISDIR(stats.st_mode) == 1)
  853. {
  854. //DEBUG_INFO("\n OCPP directory exist \n");
  855. }
  856. else
  857. {
  858. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  859. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  860. system(rmFileCmd);
  861. }
  862. memset(rmFileCmd, 0, sizeof rmFileCmd);
  863. /* opening file for reading */
  864. fp = fopen("../Storage/OCPP/TransactionRelatedQueue" , "r");
  865. if(fp == NULL) {
  866. DEBUG_INFO("Error opening file");
  867. return FALSE;
  868. }
  869. if( fgets (str, 1200, fp)!=NULL ) {
  870. /* writing content to stdout */
  871. //*********************StopTransaction***************************/
  872. loc = strstr(str, "StopTransaction");
  873. c = 0;
  874. memset(sstr ,0, sizeof(sstr) );
  875. if(loc != NULL)
  876. {
  877. IsStopTransaction = TRUE;
  878. }
  879. //*********************connectorId***************************/
  880. loc = strstr(str, "connectorId");
  881. c = 0;
  882. memset(sstr ,0, sizeof(sstr) );
  883. if(loc != NULL)
  884. {
  885. while (loc[strlen("connectorId")+2+c] != ',')
  886. {
  887. sstr[c] = loc[strlen("connectorId")+2+c];
  888. c++;
  889. }
  890. sstr[c] = '\0';
  891. tempconnectorId = atoi(sstr);
  892. //DEBUG_INFO("\n tempconnectorId:%d\n", tempconnectorId);
  893. }
  894. //*********************StartTransaction***************************/
  895. loc = strstr(str, "StartTransaction");
  896. c = 0;
  897. memset(sstr ,0, sizeof(sstr) );
  898. if(loc != NULL)
  899. {
  900. //DEBUG_INFO("\n sent queue StartTransaction\n");
  901. if(tempconnectorId > 0)
  902. {
  903. sprintf(tempdata, "StartTransaction,%d", (tempconnectorId-1));
  904. }
  905. else if(tempconnectorId == 0)
  906. {
  907. sprintf(tempdata, "StartTransaction,%d", 0);
  908. }
  909. memset(sstr ,0, sizeof(sstr) );
  910. //DEBUG_INFO("\n 0-0. sent queue str=%s\n",str);
  911. c=0;
  912. while (str[4+c] != '\"')
  913. {
  914. sstr[c] = str[4+c];
  915. c++;
  916. }
  917. sstr[c] = '\0';
  918. strcpy(guid, sstr);
  919. //DEBUG_INFO("\n 0. sent queue sstr=%s\n",sstr);
  920. if(hashmap_operation(1, guid, key_value) == TRUE)
  921. {
  922. //DEBUG_INFO("\n 1. sent queue guid=%s\n",guid);
  923. }
  924. else
  925. {
  926. hashmap_operation(0, guid, tempdata);
  927. //DEBUG_INFO("\n 2. sent queue guid=%s\n",guid);
  928. }
  929. }
  930. //****************transactionId********************/
  931. c=0;
  932. loc = strstr(str, "transactionId");
  933. memset(sstr ,0, sizeof(sstr) );
  934. if(loc != NULL)
  935. {
  936. while ((loc[strlen("transactionId")+2+c] != '}') && (loc[strlen("transactionId")+2+c] != ','))
  937. {
  938. sstr[c] = loc[strlen("transactionId")+2+c];
  939. c++;
  940. }
  941. sstr[c] = '\0';
  942. temptransactionId = atoi(sstr);
  943. //puts(str);
  944. //DEBUG_INFO("\n uuid:%s", "");
  945. //DEBUG_INFO("\n data:%s", str);
  946. if(IsStopTransaction == TRUE)
  947. {
  948. for(int i=0; i <10; i++)
  949. {
  950. //DEBUG_INFO("\n StopTransaction i:%d\n", i);
  951. //DEBUG_INFO("\n StopTransaction SentQueueTransactionId[i]:%d\n", SentQueueTransactionId[i]);
  952. //DEBUG_INFO("\n sStopTransaction temptransactionId:%d\n", temptransactionId);
  953. if(SentQueueTransactionId[i] == temptransactionId)
  954. {
  955. tempconnectorId = i;
  956. gunIndex = i;
  957. break;
  958. }
  959. }
  960. }
  961. else
  962. {
  963. if(tempconnectorId > 0)
  964. {
  965. SentQueueTransactionId[tempconnectorId-1] = temptransactionId;
  966. gunIndex = tempconnectorId-1;
  967. }
  968. }
  969. //DEBUG_INFO("\n gunIndex=%d \n",gunIndex);
  970. //DEBUG_INFO("\n temptransactionId=%d \n",temptransactionId);
  971. //DEBUG_INFO("\n GetTransactionId(gunIndex)=%d \n",GetTransactionId(gunIndex));
  972. if((GetTransactionId(gunIndex) != 0)&&(temptransactionId != GetTransactionId(gunIndex)))
  973. {
  974. strncpy(strcomposite,str, (loc-str)+2+strlen("transactionId"));
  975. sprintf(strcomposite+((loc-str)+2+strlen("transactionId")),"%d",GetTransactionId(gunIndex));
  976. strcat(strcomposite, loc+strlen("transactionId")+2+c);
  977. LWS_Send(strcomposite);
  978. }
  979. else
  980. {
  981. LWS_Send(str);
  982. }
  983. if((IsStopTransaction == TRUE)&&(GetTransactionId(gunIndex) != 0))
  984. {
  985. SetTransactionIdZero(gunIndex);
  986. }
  987. }
  988. else
  989. {
  990. LWS_Send(str);
  991. }
  992. result = TRUE;
  993. //return 1;
  994. }
  995. else
  996. {
  997. //DEBUG_INFO("queue is null\n");
  998. result = FALSE;
  999. //return 0;
  1000. }
  1001. fclose(fp);
  1002. //DEBUG_INFO("sentqueue end\n");
  1003. return result;
  1004. }
  1005. //
  1006. void* processTransactionQueue(void* data) {
  1007. char frontUUID[100] ={0};
  1008. char frontData[1200/*1024*4*/] ={0};
  1009. int queueNotEmpty = 0;
  1010. while(1)
  1011. {
  1012. if(FirstHeartBeatResponse() == 1)
  1013. {
  1014. memset(frontUUID, 0, sizeof(frontUUID));
  1015. memset(frontData, 0, sizeof(frontData));
  1016. queueNotEmpty = 0;
  1017. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1018. if((queueNotEmpty == 1) && (GetOcppConnStatus() == 1))
  1019. {
  1020. if((OfflineTransaction == 1) && (TransactionQueueNum != 0))
  1021. {
  1022. TransactionQueueInterval = 10;//2;
  1023. sleep(TransactionQueueInterval);
  1024. sendbuffer = 1;
  1025. DEBUG_INFO("test 1\n");
  1026. }
  1027. else
  1028. {
  1029. OfflineTransaction = 0;
  1030. if(TransactionMessageResend < TransactionMessageAttemptsGet()) //
  1031. {
  1032. DEBUG_INFO("TransactionMessageResend=%d\n",TransactionMessageResend);
  1033. DEBUG_INFO("TransactionMessageAttemptsGet=%d\n",TransactionMessageAttemptsGet());
  1034. DEBUG_INFO("processTransactionQueue queue is not empty!\n");
  1035. TransactionQueueInterval= TransactionMessageRetryIntervalGet()* TransactionMessageResend;
  1036. DEBUG_INFO("TransactionQueueInterval =%d\n",TransactionQueueInterval);
  1037. sendbuffer = 1;
  1038. TransactionMessageResend = TransactionMessageResend + 1;
  1039. DEBUG_INFO("After ADD,TransactionMessageResend=%d\n",TransactionMessageResend);
  1040. sleep(TransactionQueueInterval);
  1041. }
  1042. else
  1043. {
  1044. queue_operation(2,"",""); //// delete item
  1045. TransactionQueueInterval = 0;
  1046. TransactionMessageResend = 1;
  1047. sleep(TransactionQueueInterval);
  1048. }
  1049. }
  1050. }
  1051. else if((queueNotEmpty == 1) && (GetOcppConnStatus() == 0))
  1052. {
  1053. OfflineTransaction = 1;
  1054. }
  1055. else
  1056. {
  1057. TransactionQueueInterval = 0;//10;
  1058. sleep(TransactionQueueInterval);
  1059. }
  1060. }
  1061. usleep(5000);
  1062. }
  1063. pthread_exit(NULL); //
  1064. return 0;
  1065. }
  1066. void CheckTransactionPacket(char *uuid)
  1067. {
  1068. char frontUUID[100]={0};
  1069. char frontData[1200]={0};
  1070. int queueNotEmpty = 0;
  1071. int cmpResult = 0;
  1072. //queue_operation(0,"","");//showqueue(); ---> remove temporally
  1073. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1074. if(queueNotEmpty == 1)
  1075. {
  1076. cmpResult = strcmp(frontUUID, uuid);
  1077. //cmpResult = strcmp(frontData, uuid);
  1078. if (cmpResult == 0)
  1079. {
  1080. DEBUG_INFO("TransactionPacket Compare All right!\n");
  1081. DEBUG_INFO("frontUUID=%s\n",frontUUID);
  1082. DEBUG_INFO("uuid=%s\n",uuid);
  1083. queue_operation(2,"","");//delq(); ---> remove temporally
  1084. TransactionQueueInterval = 0;
  1085. TransactionMessageResend = 1;
  1086. }
  1087. }
  1088. }
  1089. /* type: 0 (showqueue ); type: 1(showfront); type: 2(delq) type: 3 (sentqueue) type: 4 (addq) type: 5(store queue to /Storage/OCPP/ )*/
  1090. int queue_operation(int type, char *frontUUID, char *frontData)
  1091. {
  1092. pthread_mutex_unlock(&lock_sentData);
  1093. pthread_mutex_lock(&lock_sentData);
  1094. int result=0;
  1095. if(type == 0) // show items in queue
  1096. result = showqueue();
  1097. else if(type == 1) // show first item
  1098. result = showfront(frontUUID, frontData);
  1099. else if(type == 2) // delete item
  1100. result = delq();
  1101. else if(type == 3) // sent items in queue
  1102. result = sentqueue();
  1103. else if(type == 4) // add items to the queue
  1104. result = addq(frontUUID, frontData);
  1105. pthread_mutex_unlock(&lock_sentData);
  1106. return result;
  1107. }
  1108. char * strchr(const char *p, int ch)
  1109. {
  1110. char c;
  1111. c = ch;
  1112. for (;; ++p) {
  1113. if (*p == c)
  1114. return ((char *)p);
  1115. if (*p == '\0')
  1116. return (NULL);
  1117. }
  1118. /* NOTREACHED */
  1119. return NULL;
  1120. }
  1121. int removeMessageSentFile(void)
  1122. {
  1123. char rmFileCmd[100]={0};
  1124. struct stat stats;
  1125. //
  1126. stat("../Storage/OCPP", &stats);
  1127. // Check for directory existence
  1128. if (S_ISDIR(stats.st_mode) == 1)
  1129. {
  1130. //DEBUG_INFO("\n OCPP directory exist \n");
  1131. }
  1132. else
  1133. {
  1134. DEBUG_INFO("\n directory not exist, create dir \n");
  1135. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  1136. system(rmFileCmd);
  1137. }
  1138. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1139. if((access("../Storage/OCPP/MessageSent",F_OK))!=-1)
  1140. {
  1141. DEBUG_INFO("MessageSent file exist.\n");
  1142. sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/MessageSent");
  1143. system(rmFileCmd);
  1144. }
  1145. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1146. return 0;
  1147. }
  1148. #define SystemLogMessage
  1149. //================================================
  1150. // Main process
  1151. //================================================
  1152. int main(void)
  1153. {
  1154. char rmFileCmd[100]={0};
  1155. struct stat stats;
  1156. pthread_t t;
  1157. #ifdef SystemLogMessage
  1158. DEBUG_INFO("Initialization...\n");
  1159. #endif
  1160. if(ProcessShareMemory()== FAIL)
  1161. {
  1162. return FAIL;
  1163. }
  1164. //Create OCPP dir
  1165. stat("../Storage/OCPP", &stats);
  1166. // Check for directory existence
  1167. if (S_ISDIR(stats.st_mode) == 1)
  1168. {
  1169. //DEBUG_INFO("\n OCPP directory exist \n");
  1170. }
  1171. else
  1172. {
  1173. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  1174. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  1175. system(rmFileCmd);
  1176. }
  1177. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1178. //Create Process: Resend Transaction
  1179. pthread_create(&t, NULL, processTransactionQueue, NULL); //
  1180. sqlite3_config(SQLITE_CONFIG_URI,1);
  1181. if(sqlite3_open("file:/../Storage/OCPP/charger.db", &db))
  1182. {
  1183. #ifdef Debug
  1184. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1185. #endif
  1186. sqlite3_close( db );
  1187. exit(0);
  1188. }
  1189. else
  1190. {
  1191. #ifdef Debug
  1192. DEBUG_INFO( "Opened database successfully\n");
  1193. #endif
  1194. }
  1195. //Create Table log buffer
  1196. int rc =sqlite3_exec(db, createsql, 0, 0, &errMsg);
  1197. if (SQLITE_OK != rc)
  1198. {
  1199. #ifdef Debug
  1200. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1201. #endif
  1202. return 0;
  1203. }
  1204. else
  1205. {
  1206. #ifdef Debug
  1207. DEBUG_INFO( "Opened log buffer table successfully\n");
  1208. #endif
  1209. }
  1210. // Create Table OcppAuthCache
  1211. rc =sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg);
  1212. if (SQLITE_OK != rc)
  1213. {
  1214. #ifdef Debug
  1215. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1216. #endif
  1217. return 0;
  1218. }
  1219. else
  1220. {
  1221. #ifdef Debug
  1222. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1223. #endif
  1224. }
  1225. // Create Table OcppAuthLocal
  1226. rc =sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg);
  1227. if (SQLITE_OK != rc)
  1228. {
  1229. #ifdef Debug
  1230. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1231. #endif
  1232. return 0;
  1233. }
  1234. else
  1235. {
  1236. #ifdef Debug
  1237. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1238. #endif
  1239. }
  1240. initialConfigurationTable();
  1241. removeMessageSentFile();
  1242. //queryAllData();
  1243. OCPP_get_TableAuthlocalAllData();
  1244. for(;;)
  1245. {
  1246. while(ConnectionEstablished==0)
  1247. {
  1248. SetOcppConnStatus(FALSE);
  1249. if((time((time_t*)NULL)-startTime.connect)>=60)
  1250. {
  1251. #ifdef Debug
  1252. DEBUG_INFO("Execute ConnectWsServer\n");
  1253. #endif
  1254. ConnectWsServer();
  1255. startTime.connect=time((time_t*)NULL);
  1256. }
  1257. // Check System Value, process offline Transaction
  1258. CheckSystemValue();
  1259. lws_service(context, 10000);//timeout_ms
  1260. }
  1261. if(( (BootNotificationInterval != 0 && ((time((time_t*)NULL)-startTime.bootNotification)>=BootNotificationInterval) ) || ((time((time_t*)NULL)-startTime.bootNotification)>=defaultWaitingTime) ) && ((server_sign == FALSE)/*|| (server_pending == TRUE)*/))
  1262. {
  1263. //hashmapForMessageNew();
  1264. sendBootNotificationRequest();
  1265. startTime.bootNotification=time((time_t*)NULL);
  1266. }
  1267. if(server_sign == TRUE)
  1268. {
  1269. if(sendbuffer == 1)
  1270. {
  1271. queue_operation(3, "", "");//sentqueue()
  1272. sendbuffer = 0;
  1273. }
  1274. SetOcppConnStatus(TRUE);
  1275. // Check System Value
  1276. CheckSystemValue();
  1277. if(GetHeartBeatWithNOResponse() >= 3)
  1278. {
  1279. lws_context_destroy(context);
  1280. ConnectionEstablished=0;
  1281. context = NULL;
  1282. SetHeartBeatWithNOResponse();
  1283. }
  1284. }
  1285. lws_service(context, 100);//timeout_ms
  1286. }
  1287. pthread_join(t, NULL); //
  1288. //hashmapForMessageFree();
  1289. return FAIL;
  1290. }