Module_OcppBackend.c 31 KB

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