Module_OcppBackend.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  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. DEBUG_OCPPMESSAGE_INFO("LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH Receive %s\n", (char *)in);
  332. break;
  333. case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
  334. #ifdef SystemLogMessage
  335. DEBUG_INFO("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
  336. #endif
  337. break;
  338. case LWS_CALLBACK_WSI_DESTROY:
  339. #ifdef SystemLogMessage
  340. DEBUG_INFO("LWS_CALLBACK_WSI_DESTROY\n");
  341. #endif
  342. server_sign = FALSE;
  343. break;
  344. case LWS_CALLBACK_LOCK_POLL:
  345. break;
  346. case LWS_CALLBACK_ADD_POLL_FD:
  347. #ifdef SystemLogMessage
  348. DEBUG_INFO("LWS_CALLBACK_ADD_POLL_FD\n");
  349. #endif
  350. break;
  351. case LWS_CALLBACK_DEL_POLL_FD:
  352. #ifdef SystemLogMessage
  353. DEBUG_INFO("LWS_CALLBACK_DEL_POLL_FD\n");
  354. #endif
  355. break;
  356. case LWS_CALLBACK_UNLOCK_POLL:
  357. break;
  358. case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
  359. break;
  360. case LWS_CALLBACK_WSI_CREATE:
  361. #ifdef SystemLogMessage
  362. DEBUG_INFO("LWS_CALLBACK_WSI_CREATE\n");
  363. #endif
  364. break;
  365. case LWS_CALLBACK_GET_THREAD_ID:
  366. break;
  367. case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
  368. #ifdef SystemLogMessage
  369. DEBUG_INFO("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
  370. #endif
  371. DEBUG_OCPPMESSAGE_INFO("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER Receive %s\n", (char *)in);
  372. break;
  373. case LWS_CALLBACK_CLIENT_ESTABLISHED://3
  374. #ifdef SystemLogMessage
  375. DEBUG_INFO("LWS_CALLBACK_CLIENT_ESTABLISHED\n");
  376. #endif
  377. //connected
  378. ConnectionEstablished=1;
  379. DEBUG_OCPPMESSAGE_INFO("LWS_CALLBACK_CLIENT_ESTABLISHED Receive %s\n", (char *)in);
  380. break;
  381. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR://1
  382. #ifdef Debug
  383. DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR:%s\n",in);
  384. #endif
  385. #ifdef SystemLogMessage
  386. DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
  387. #endif
  388. //disconnected
  389. ConnectionEstablished=0;
  390. break;
  391. case LWS_CALLBACK_CLOSED://4
  392. #ifdef SystemLogMessage
  393. DEBUG_INFO("LWS_CALLBACK_CLOSED\n");
  394. ConnectionEstablished=0;
  395. #endif
  396. //disconnected
  397. break;
  398. case LWS_CALLBACK_CLIENT_WRITEABLE://10
  399. //if(need to send message and its relevant data already store into SendBuffer)
  400. #ifdef SystemLogMessage
  401. //DEBUG_INFO("LWS_CALLBACK_CLIENT_WRITEABLE\n");
  402. #endif
  403. SendData(wsi);
  404. break;
  405. case LWS_CALLBACK_CLIENT_RECEIVE://8
  406. ((char *)in)[len] = '\0';
  407. //Print Out Adjudgement
  408. {
  409. char *ret, *ret1;
  410. ret = strstr((const char *)in, "currentTime");
  411. ret1 = strstr((const char *)in, "interval");
  412. if(!((ret != NULL)&&(ret1 == NULL)))
  413. {
  414. DEBUG_OCPPMESSAGE_INFO("Original Receive %s\n", (char *)in);
  415. }
  416. }
  417. char tempin[1024*4]={0};
  418. int c = 0;
  419. char *loc;
  420. char sstr[600]={ 0 };
  421. //**********Receive Message**********/
  422. c = 0;
  423. loc = strstr((const char *)in, "][2,");
  424. if(loc == NULL)
  425. {
  426. loc = strstr((const char *)in, "][3,");
  427. if(loc == NULL)
  428. {
  429. loc = strstr((const char *)in, "][4,");
  430. }
  431. }
  432. memset(sstr ,0, sizeof(sstr) );
  433. if(loc != NULL)
  434. {
  435. DEBUG_INFO("there are continuous second packet []\n");
  436. while (loc[1+c] != '\0')
  437. {
  438. sstr[c] = loc[1+c];
  439. c++;
  440. }
  441. sstr[c] = '\0';
  442. strcpy(tempin, sstr);
  443. DEBUG_INFO("Final Receive: %s\n", tempin);
  444. }
  445. else
  446. {
  447. strcpy(tempin,(char *)in);
  448. }
  449. ReceivedMessage((void *)tempin, len);
  450. break;
  451. default:
  452. #ifdef Debug
  453. DEBUG_INFO("OCPP16Callback:reason=%d\n", reason);
  454. #endif
  455. break;
  456. }
  457. return 0;
  458. }
  459. static struct lws_protocols protocols[] = {
  460. {
  461. "ocpp1.6",
  462. OCPP16Callback,
  463. 10240,
  464. 10240,
  465. },
  466. {
  467. "ocpp1.6",
  468. OCPP16Callback,
  469. 10240,
  470. 10240,
  471. },
  472. {
  473. NULL, NULL, 0 /* End of list */
  474. }
  475. };
  476. int ConnectWsServer()
  477. {
  478. int result = PASS;
  479. struct lws_context_creation_info ContextInfo;
  480. struct lws_client_connect_info ConnInfo;
  481. int use_ssl=0;
  482. //lws_set_log_level(LLL_PARSER | LLL_HEADER | LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_INFO | LLL_DEBUG | LLL_EXT | LLL_CLIENT | LLL_LATENCY , NULL);
  483. if(context!=NULL)
  484. lws_context_destroy(context);
  485. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  486. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  487. ContextInfo.iface = NULL;
  488. ContextInfo.ssl_private_key_password = NULL;
  489. ContextInfo.ssl_cert_filepath = NULL;
  490. ContextInfo.ssl_private_key_filepath = NULL;
  491. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";
  492. ContextInfo.ssl_cipher_list = NULL; //use default one
  493. ContextInfo.gid = -1;
  494. ContextInfo.uid = -1;
  495. if(use_ssl)
  496. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
  497. ContextInfo.protocols = protocols;
  498. ContextInfo.timeout_secs = 9999;//30;
  499. //if(ping pong enabled)
  500. ContextInfo.ws_ping_pong_interval = 30;//0 for none, else interval in seconds
  501. context = lws_create_context(&ContextInfo);
  502. if (context == NULL)
  503. {
  504. #ifdef SystemLogMessage
  505. DEBUG_ERROR("lws_create_context NG");
  506. #endif
  507. result = FAIL;
  508. }
  509. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  510. // fill up below information
  511. ConnInfo.context = context;
  512. if((GetOcppServerURL()==0) || (GetOcppPort() == 0) || (GetOcppPath()==0) )
  513. {
  514. result = FAIL;
  515. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  516. return result;
  517. }
  518. ConnInfo.address=(const char *)OcppHost;
  519. ConnInfo.port = GetOcppPort();
  520. ConnInfo.path=(const char *)OcppPath;
  521. ConnInfo.host=lws_canonical_hostname(context);
  522. ConnInfo.origin="origin";
  523. ConnInfo.protocol = protocols[1].name;
  524. ConnInfo.ietf_version_or_minus_one = -1;
  525. if(use_ssl)
  526. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;;
  527. wsi_client = lws_client_connect_via_info(&ConnInfo);
  528. if (!wsi_client)
  529. {
  530. #ifdef SystemLogMessage
  531. DEBUG_ERROR("lws_client_connect_via_info NG");
  532. #endif
  533. result = FAIL;
  534. }
  535. return result;
  536. }
  537. //void createq();
  538. int showfront(char *uuid, char *data);
  539. int addq(char *uuid, char *data) ;
  540. int delq();
  541. int sentqueue();
  542. void CheckTransactionPacket(char *uuid);
  543. int queue_operation(int type, char *frontUUID, char *frontData);
  544. int showfront(char *uuid, char *data) {
  545. FILE *fp;
  546. int result = FALSE; // 1: TRUE 0:FALSE
  547. char str[1200]={0};
  548. char sstr[50]={ 0 };//sstr[200]={ 0 };
  549. int c = 0;
  550. char *loc;
  551. char rmFileCmd[100]={0};
  552. struct stat stats;
  553. stat("../Storage/OCPP", &stats);
  554. // Check for directory existence
  555. if (S_ISDIR(stats.st_mode) == 1)
  556. {
  557. //DEBUG_INFO("\n OCPP directory exist \n");
  558. }
  559. else
  560. {
  561. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  562. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  563. system(rmFileCmd);
  564. }
  565. memset(rmFileCmd, 0, sizeof rmFileCmd);
  566. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  567. {
  568. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  569. }
  570. else
  571. {
  572. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  573. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  574. if(log == NULL)
  575. {
  576. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  577. return 0;
  578. }
  579. else
  580. {
  581. fclose(log);
  582. }
  583. }
  584. /* opening file for reading */
  585. fp = fopen("../Storage/OCPP/TransactionRelatedQueue" , "r");
  586. if(fp == NULL) {
  587. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  588. return FALSE;
  589. }
  590. if(fgetc(fp)==EOF)
  591. {
  592. //DEBUG_INFO("It is end of file");
  593. fclose(fp);
  594. memset(rmFileCmd, 0, sizeof rmFileCmd);
  595. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  596. {
  597. sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/TransactionRelatedQueue");
  598. system(rmFileCmd);
  599. }
  600. result = FALSE;
  601. return result;
  602. }
  603. if( fgets (str, 1200, fp)!=NULL ) {
  604. /* writing content to stdout */
  605. //DEBUG_INFO("str=%s",str);
  606. if ((str[0] == '\n')||(strcmp(str,"")==0))
  607. {
  608. DEBUG_INFO("It is a blank line");
  609. fclose(fp);
  610. memset(rmFileCmd, 0, sizeof rmFileCmd);
  611. sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/TransactionRelatedQueue");
  612. system(rmFileCmd);
  613. result = FALSE;
  614. return result;
  615. }
  616. else
  617. {
  618. //puts(str);
  619. /*********************uuid***************/
  620. loc = strstr(str, "\"");
  621. memset(sstr ,0, sizeof(sstr) );
  622. c = 0;
  623. while (loc[1+c] != '\"')
  624. {
  625. sstr[c] = loc[1+c];
  626. c++;
  627. }
  628. sstr[c] = '\0';
  629. //DEBUG_INFO("\n uuid:%s", sstr);
  630. //DEBUG_INFO("\n data:%s", str);
  631. strcpy(uuid,sstr);
  632. strcpy(data,str);
  633. result = TRUE;
  634. }
  635. //return 1;
  636. }
  637. else
  638. {
  639. //DEBUG_INFO("queue is null\n");
  640. strcpy(uuid,"");
  641. strcpy(data,"");
  642. result = FALSE;
  643. //return 0;
  644. }
  645. fclose(fp);
  646. return result;
  647. }
  648. int addq(char *uuid, char *data) {
  649. FILE *outfile;
  650. char rmFileCmd[100]={0};
  651. struct stat stats;
  652. stat("../Storage/OCPP", &stats);
  653. //DEBUG_INFO("addq\n");
  654. // Check for directory existence
  655. if (S_ISDIR(stats.st_mode) == 1)
  656. {
  657. //DEBUG_INFO("\n OCPP directory exist \n");
  658. }
  659. else
  660. {
  661. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  662. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  663. system(rmFileCmd);
  664. }
  665. memset(rmFileCmd, 0, sizeof rmFileCmd);
  666. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  667. {
  668. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  669. }
  670. else
  671. {
  672. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  673. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  674. if(log == NULL)
  675. {
  676. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  677. return 0;
  678. }
  679. else
  680. {
  681. fclose(log);
  682. }
  683. }
  684. // open file for writing
  685. outfile = fopen ("../Storage/OCPP/TransactionRelatedQueue", "a");
  686. //DEBUG_INFO("data=%s\n",data);
  687. fputs(data, outfile);
  688. fputs("\n", outfile);
  689. fclose (outfile);
  690. TransactionQueueNum = TransactionQueueNum + 1;
  691. return 0;
  692. }
  693. int delq() {
  694. char tempfile[] = "../Storage/OCPP/temp.json";
  695. FILE *infile;
  696. FILE *outfile;
  697. int resultRename=0;
  698. char filename[60]={0};
  699. char rmFileCmd[100]={0};
  700. struct stat stats;
  701. stat("../Storage/OCPP", &stats);
  702. DEBUG_INFO("delq()\n");
  703. // Check for directory existence
  704. if (S_ISDIR(stats.st_mode) == 1)
  705. {
  706. //DEBUG_INFO("\n OCPP directory exist \n");
  707. }
  708. else
  709. {
  710. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  711. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  712. system(rmFileCmd);
  713. }
  714. memset(rmFileCmd, 0, sizeof rmFileCmd);
  715. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  716. {
  717. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  718. }
  719. else
  720. {
  721. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  722. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  723. if(log == NULL)
  724. {
  725. DEBUG_INFO("log is NULL\n");
  726. return 0;
  727. }
  728. else
  729. {
  730. fclose(log);
  731. }
  732. }
  733. // open file for writing
  734. strcpy(filename, "../Storage/OCPP/TransactionRelatedQueue");
  735. infile = fopen ("../Storage/OCPP/TransactionRelatedQueue", "r");
  736. outfile = fopen (tempfile, "w");
  737. /*检测到文件结束标识返回1,否则返回0。*/
  738. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  739. int c;
  740. c = fgetc(infile);
  741. //printf("file c:%d\n",c);
  742. rewind(infile);
  743. if(c == EOF)
  744. {
  745. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  746. fclose(infile);
  747. fclose(outfile);
  748. sprintf(rmFileCmd,"rm -f %s",tempfile);
  749. system(rmFileCmd);
  750. }
  751. else
  752. {
  753. char buf[1200]={0};
  754. int i = 0;
  755. //DEBUG_INFO("Orignal File is not NULL\n");
  756. while (fgets(buf, sizeof(buf), infile) != NULL)
  757. {
  758. //printf("Orignal File get strings \n");
  759. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  760. if(i==0)
  761. {
  762. TransactionQueueNum = TransactionQueueNum - 1;
  763. TransactionQueueInterval = 0;
  764. TransactionMessageResend = 1;
  765. }
  766. if(i != 0)
  767. fprintf(outfile,"%s\n", buf);
  768. i = i + 1;
  769. }
  770. fclose(infile);
  771. fclose(outfile);
  772. sprintf(rmFileCmd,"rm -f %s",filename);
  773. system(rmFileCmd);
  774. resultRename = rename(tempfile, filename);
  775. if(resultRename == 0)
  776. {
  777. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  778. }
  779. else
  780. {
  781. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  782. }
  783. }
  784. return 0;
  785. }
  786. int showqueue() {
  787. char rmFileCmd[100]={0};
  788. struct stat stats;
  789. stat("../Storage/OCPP", &stats);
  790. // Check for directory existence
  791. if (S_ISDIR(stats.st_mode) == 1)
  792. {
  793. //DEBUG_INFO("\n OCPP directory exist \n");
  794. }
  795. else
  796. {
  797. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  798. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  799. system(rmFileCmd);
  800. }
  801. memset(rmFileCmd, 0, sizeof rmFileCmd);
  802. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  803. {
  804. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  805. }
  806. else
  807. {
  808. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  809. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  810. if(log == NULL)
  811. {
  812. DEBUG_INFO("log is NULL\n");
  813. return 0;
  814. }
  815. else
  816. {
  817. fclose(log);
  818. }
  819. }
  820. FILE *fp = fopen("../Storage/OCPP/TransactionRelatedQueue", "r");
  821. char line[1200]={0};
  822. // check if file exist (and you can open it) or not
  823. if (fp == NULL) {
  824. DEBUG_INFO("can open file TransactionRelatedQueue!");
  825. return 0;
  826. }
  827. while(fgets(line, sizeof line, fp) != NULL) {
  828. DEBUG_INFO("%s\n", line);
  829. }
  830. fclose(fp);
  831. return 0;
  832. }
  833. int sentqueue(){
  834. FILE *fp;
  835. int result = FALSE; // 1: TRUE 0:FALSE
  836. int temptransactionId = 0;
  837. int tempconnectorId = 0;
  838. int gunIndex = 0;
  839. char guid[37]={0};
  840. char tempdata[65]={0};
  841. char key_value[65]={0};
  842. int IsStopTransaction = FALSE;
  843. char str[1200]={0};
  844. char strcomposite[1200]={0};
  845. char rmFileCmd[100]={0};
  846. struct stat stats;
  847. char sstr[28]={ 0 };
  848. int c = 0;
  849. char *loc;
  850. DEBUG_INFO("sentqueue\n");
  851. stat("../Storage/OCPP", &stats);
  852. // Check for directory existence
  853. if (S_ISDIR(stats.st_mode) == 1)
  854. {
  855. //DEBUG_INFO("\n OCPP directory exist \n");
  856. }
  857. else
  858. {
  859. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  860. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  861. system(rmFileCmd);
  862. }
  863. memset(rmFileCmd, 0, sizeof rmFileCmd);
  864. /* opening file for reading */
  865. fp = fopen("../Storage/OCPP/TransactionRelatedQueue" , "r");
  866. if(fp == NULL) {
  867. DEBUG_INFO("Error opening file");
  868. return FALSE;
  869. }
  870. if( fgets (str, 1200, fp)!=NULL ) {
  871. /* writing content to stdout */
  872. //*********************StopTransaction***************************/
  873. loc = strstr(str, "StopTransaction");
  874. c = 0;
  875. memset(sstr ,0, sizeof(sstr) );
  876. if(loc != NULL)
  877. {
  878. IsStopTransaction = TRUE;
  879. }
  880. //*********************connectorId***************************/
  881. loc = strstr(str, "connectorId");
  882. c = 0;
  883. memset(sstr ,0, sizeof(sstr) );
  884. if(loc != NULL)
  885. {
  886. while (loc[strlen("connectorId")+2+c] != ',')
  887. {
  888. sstr[c] = loc[strlen("connectorId")+2+c];
  889. c++;
  890. }
  891. sstr[c] = '\0';
  892. tempconnectorId = atoi(sstr);
  893. //DEBUG_INFO("\n tempconnectorId:%d\n", tempconnectorId);
  894. }
  895. //*********************StartTransaction***************************/
  896. loc = strstr(str, "StartTransaction");
  897. c = 0;
  898. memset(sstr ,0, sizeof(sstr) );
  899. if(loc != NULL)
  900. {
  901. //DEBUG_INFO("\n sent queue StartTransaction\n");
  902. if(tempconnectorId > 0)
  903. {
  904. sprintf(tempdata, "StartTransaction,%d", (tempconnectorId-1));
  905. }
  906. else if(tempconnectorId == 0)
  907. {
  908. sprintf(tempdata, "StartTransaction,%d", 0);
  909. }
  910. memset(sstr ,0, sizeof(sstr) );
  911. //DEBUG_INFO("\n 0-0. sent queue str=%s\n",str);
  912. c=0;
  913. while (str[4+c] != '\"')
  914. {
  915. sstr[c] = str[4+c];
  916. c++;
  917. }
  918. sstr[c] = '\0';
  919. strcpy(guid, sstr);
  920. //DEBUG_INFO("\n 0. sent queue sstr=%s\n",sstr);
  921. if(hashmap_operation(1, guid, key_value) == TRUE)
  922. {
  923. //DEBUG_INFO("\n 1. sent queue guid=%s\n",guid);
  924. }
  925. else
  926. {
  927. hashmap_operation(0, guid, tempdata);
  928. //DEBUG_INFO("\n 2. sent queue guid=%s\n",guid);
  929. }
  930. }
  931. //****************transactionId********************/
  932. c=0;
  933. loc = strstr(str, "transactionId");
  934. memset(sstr ,0, sizeof(sstr) );
  935. if(loc != NULL)
  936. {
  937. while ((loc[strlen("transactionId")+2+c] != '}') && (loc[strlen("transactionId")+2+c] != ','))
  938. {
  939. sstr[c] = loc[strlen("transactionId")+2+c];
  940. c++;
  941. }
  942. sstr[c] = '\0';
  943. temptransactionId = atoi(sstr);
  944. //puts(str);
  945. //DEBUG_INFO("\n uuid:%s", "");
  946. //DEBUG_INFO("\n data:%s", str);
  947. if(IsStopTransaction == TRUE)
  948. {
  949. for(int i=0; i <10; i++)
  950. {
  951. //DEBUG_INFO("\n StopTransaction i:%d\n", i);
  952. //DEBUG_INFO("\n StopTransaction SentQueueTransactionId[i]:%d\n", SentQueueTransactionId[i]);
  953. //DEBUG_INFO("\n sStopTransaction temptransactionId:%d\n", temptransactionId);
  954. if(SentQueueTransactionId[i] == temptransactionId)
  955. {
  956. tempconnectorId = i;
  957. gunIndex = i;
  958. break;
  959. }
  960. }
  961. }
  962. else
  963. {
  964. if(tempconnectorId > 0)
  965. {
  966. SentQueueTransactionId[tempconnectorId-1] = temptransactionId;
  967. gunIndex = tempconnectorId-1;
  968. }
  969. }
  970. //DEBUG_INFO("\n gunIndex=%d \n",gunIndex);
  971. //DEBUG_INFO("\n temptransactionId=%d \n",temptransactionId);
  972. //DEBUG_INFO("\n GetTransactionId(gunIndex)=%d \n",GetTransactionId(gunIndex));
  973. if((GetTransactionId(gunIndex) != 0)&&(temptransactionId != GetTransactionId(gunIndex)))
  974. {
  975. strncpy(strcomposite,str, (loc-str)+2+strlen("transactionId"));
  976. sprintf(strcomposite+((loc-str)+2+strlen("transactionId")),"%d",GetTransactionId(gunIndex));
  977. strcat(strcomposite, loc+strlen("transactionId")+2+c);
  978. LWS_Send(strcomposite);
  979. }
  980. else
  981. {
  982. LWS_Send(str);
  983. }
  984. if((IsStopTransaction == TRUE)&&(GetTransactionId(gunIndex) != 0))
  985. {
  986. SetTransactionIdZero(gunIndex);
  987. }
  988. }
  989. else
  990. {
  991. LWS_Send(str);
  992. }
  993. result = TRUE;
  994. //return 1;
  995. }
  996. else
  997. {
  998. //DEBUG_INFO("queue is null\n");
  999. result = FALSE;
  1000. //return 0;
  1001. }
  1002. fclose(fp);
  1003. //DEBUG_INFO("sentqueue end\n");
  1004. return result;
  1005. }
  1006. //
  1007. void* processTransactionQueue(void* data) {
  1008. char frontUUID[100] ={0};
  1009. char frontData[1200/*1024*4*/] ={0};
  1010. int queueNotEmpty = 0;
  1011. while(1)
  1012. {
  1013. if(FirstHeartBeatResponse() == 1)
  1014. {
  1015. memset(frontUUID, 0, sizeof(frontUUID));
  1016. memset(frontData, 0, sizeof(frontData));
  1017. queueNotEmpty = 0;
  1018. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1019. if((queueNotEmpty == 1) && (GetOcppConnStatus() == 1))
  1020. {
  1021. if((OfflineTransaction == 1) && (TransactionQueueNum != 0))
  1022. {
  1023. TransactionQueueInterval = 10;//2;
  1024. sleep(TransactionQueueInterval);
  1025. sendbuffer = 1;
  1026. DEBUG_INFO("test 1\n");
  1027. }
  1028. else
  1029. {
  1030. OfflineTransaction = 0;
  1031. if(TransactionMessageResend < TransactionMessageAttemptsGet()) //
  1032. {
  1033. DEBUG_INFO("TransactionMessageResend=%d\n",TransactionMessageResend);
  1034. DEBUG_INFO("TransactionMessageAttemptsGet=%d\n",TransactionMessageAttemptsGet());
  1035. DEBUG_INFO("processTransactionQueue queue is not empty!\n");
  1036. TransactionQueueInterval= TransactionMessageRetryIntervalGet()* TransactionMessageResend;
  1037. DEBUG_INFO("TransactionQueueInterval =%d\n",TransactionQueueInterval);
  1038. sendbuffer = 1;
  1039. TransactionMessageResend = TransactionMessageResend + 1;
  1040. DEBUG_INFO("After ADD,TransactionMessageResend=%d\n",TransactionMessageResend);
  1041. sleep(TransactionQueueInterval);
  1042. }
  1043. else
  1044. {
  1045. queue_operation(2,"",""); //// delete item
  1046. TransactionQueueInterval = 0;
  1047. TransactionMessageResend = 1;
  1048. sleep(TransactionQueueInterval);
  1049. }
  1050. }
  1051. }
  1052. else if((queueNotEmpty == 1) && (GetOcppConnStatus() == 0))
  1053. {
  1054. OfflineTransaction = 1;
  1055. }
  1056. else
  1057. {
  1058. TransactionQueueInterval = 0;//10;
  1059. sleep(TransactionQueueInterval);
  1060. }
  1061. }
  1062. usleep(5000);
  1063. }
  1064. pthread_exit(NULL); //
  1065. return 0;
  1066. }
  1067. void CheckTransactionPacket(char *uuid)
  1068. {
  1069. char frontUUID[100]={0};
  1070. char frontData[1200]={0};
  1071. int queueNotEmpty = 0;
  1072. int cmpResult = 0;
  1073. //queue_operation(0,"","");//showqueue(); ---> remove temporally
  1074. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1075. if(queueNotEmpty == 1)
  1076. {
  1077. cmpResult = strcmp(frontUUID, uuid);
  1078. //cmpResult = strcmp(frontData, uuid);
  1079. if (cmpResult == 0)
  1080. {
  1081. DEBUG_INFO("TransactionPacket Compare All right!\n");
  1082. DEBUG_INFO("frontUUID=%s\n",frontUUID);
  1083. DEBUG_INFO("uuid=%s\n",uuid);
  1084. queue_operation(2,"","");//delq(); ---> remove temporally
  1085. TransactionQueueInterval = 0;
  1086. TransactionMessageResend = 1;
  1087. }
  1088. }
  1089. }
  1090. /* type: 0 (showqueue ); type: 1(showfront); type: 2(delq) type: 3 (sentqueue) type: 4 (addq) type: 5(store queue to /Storage/OCPP/ )*/
  1091. int queue_operation(int type, char *frontUUID, char *frontData)
  1092. {
  1093. pthread_mutex_unlock(&lock_sentData);
  1094. pthread_mutex_lock(&lock_sentData);
  1095. int result=0;
  1096. if(type == 0) // show items in queue
  1097. result = showqueue();
  1098. else if(type == 1) // show first item
  1099. result = showfront(frontUUID, frontData);
  1100. else if(type == 2) // delete item
  1101. result = delq();
  1102. else if(type == 3) // sent items in queue
  1103. result = sentqueue();
  1104. else if(type == 4) // add items to the queue
  1105. result = addq(frontUUID, frontData);
  1106. pthread_mutex_unlock(&lock_sentData);
  1107. return result;
  1108. }
  1109. char * strchr(const char *p, int ch)
  1110. {
  1111. char c;
  1112. c = ch;
  1113. for (;; ++p) {
  1114. if (*p == c)
  1115. return ((char *)p);
  1116. if (*p == '\0')
  1117. return (NULL);
  1118. }
  1119. /* NOTREACHED */
  1120. return NULL;
  1121. }
  1122. int removeMessageSentFile(void)
  1123. {
  1124. char rmFileCmd[100]={0};
  1125. struct stat stats;
  1126. //
  1127. stat("../Storage/OCPP", &stats);
  1128. // Check for directory existence
  1129. if (S_ISDIR(stats.st_mode) == 1)
  1130. {
  1131. //DEBUG_INFO("\n OCPP directory exist \n");
  1132. }
  1133. else
  1134. {
  1135. DEBUG_INFO("\n directory not exist, create dir \n");
  1136. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  1137. system(rmFileCmd);
  1138. }
  1139. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1140. if((access("../Storage/OCPP/MessageSent",F_OK))!=-1)
  1141. {
  1142. DEBUG_INFO("MessageSent file exist.\n");
  1143. sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/MessageSent");
  1144. system(rmFileCmd);
  1145. }
  1146. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1147. return 0;
  1148. }
  1149. #define SystemLogMessage
  1150. //================================================
  1151. // Main process
  1152. //================================================
  1153. int main(void)
  1154. {
  1155. char rmFileCmd[100]={0};
  1156. struct stat stats;
  1157. pthread_t t;
  1158. #ifdef SystemLogMessage
  1159. DEBUG_INFO("Initialization...\n");
  1160. #endif
  1161. if(ProcessShareMemory()== FAIL)
  1162. {
  1163. return FAIL;
  1164. }
  1165. //Create OCPP dir
  1166. stat("../Storage/OCPP", &stats);
  1167. // Check for directory existence
  1168. if (S_ISDIR(stats.st_mode) == 1)
  1169. {
  1170. //DEBUG_INFO("\n OCPP directory exist \n");
  1171. }
  1172. else
  1173. {
  1174. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  1175. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  1176. system(rmFileCmd);
  1177. }
  1178. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1179. //Create Process: Resend Transaction
  1180. pthread_create(&t, NULL, processTransactionQueue, NULL); //
  1181. sqlite3_config(SQLITE_CONFIG_URI,1);
  1182. if(sqlite3_open("file:/../Storage/OCPP/charger.db", &db))
  1183. {
  1184. #ifdef Debug
  1185. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1186. #endif
  1187. sqlite3_close( db );
  1188. exit(0);
  1189. }
  1190. else
  1191. {
  1192. #ifdef Debug
  1193. DEBUG_INFO( "Opened database successfully\n");
  1194. #endif
  1195. }
  1196. //Create Table log buffer
  1197. int rc =sqlite3_exec(db, createsql, 0, 0, &errMsg);
  1198. if (SQLITE_OK != rc)
  1199. {
  1200. #ifdef Debug
  1201. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1202. #endif
  1203. return 0;
  1204. }
  1205. else
  1206. {
  1207. #ifdef Debug
  1208. DEBUG_INFO( "Opened log buffer table successfully\n");
  1209. #endif
  1210. }
  1211. // Create Table OcppAuthCache
  1212. rc =sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg);
  1213. if (SQLITE_OK != rc)
  1214. {
  1215. #ifdef Debug
  1216. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1217. #endif
  1218. return 0;
  1219. }
  1220. else
  1221. {
  1222. #ifdef Debug
  1223. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1224. #endif
  1225. }
  1226. // Create Table OcppAuthLocal
  1227. rc =sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg);
  1228. if (SQLITE_OK != rc)
  1229. {
  1230. #ifdef Debug
  1231. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1232. #endif
  1233. return 0;
  1234. }
  1235. else
  1236. {
  1237. #ifdef Debug
  1238. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1239. #endif
  1240. }
  1241. initialConfigurationTable();
  1242. removeMessageSentFile();
  1243. //queryAllData();
  1244. OCPP_get_TableAuthlocalAllData();
  1245. for(;;)
  1246. {
  1247. while(ConnectionEstablished==0)
  1248. {
  1249. SetOcppConnStatus(FALSE);
  1250. if((time((time_t*)NULL)-startTime.connect)>=60)
  1251. {
  1252. #ifdef Debug
  1253. DEBUG_INFO("Execute ConnectWsServer\n");
  1254. #endif
  1255. ConnectWsServer();
  1256. startTime.connect=time((time_t*)NULL);
  1257. }
  1258. // Check System Value, process offline Transaction
  1259. CheckSystemValue();
  1260. lws_service(context, 10000);//timeout_ms
  1261. }
  1262. if(( (BootNotificationInterval != 0 && ((time((time_t*)NULL)-startTime.bootNotification)>=BootNotificationInterval) ) || ((time((time_t*)NULL)-startTime.bootNotification)>=defaultWaitingTime) ) && ((server_sign == FALSE)/*|| (server_pending == TRUE)*/))
  1263. {
  1264. //hashmapForMessageNew();
  1265. sendBootNotificationRequest();
  1266. startTime.bootNotification=time((time_t*)NULL);
  1267. }
  1268. if(server_sign == TRUE)
  1269. {
  1270. if(sendbuffer == 1)
  1271. {
  1272. queue_operation(3, "", "");//sentqueue()
  1273. sendbuffer = 0;
  1274. }
  1275. SetOcppConnStatus(TRUE);
  1276. // Check System Value
  1277. CheckSystemValue();
  1278. if(GetHeartBeatWithNOResponse() >= 3)
  1279. {
  1280. lws_context_destroy(context);
  1281. ConnectionEstablished=0;
  1282. context = NULL;
  1283. SetHeartBeatWithNOResponse();
  1284. }
  1285. }
  1286. lws_service(context, 100);//timeout_ms
  1287. }
  1288. pthread_join(t, NULL); //
  1289. //hashmapForMessageFree();
  1290. return FAIL;
  1291. }