Module_OcppBackend.c 35 KB

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