Module_OcppBackend.c 34 KB

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