Module_OcppBackend.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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(" SendData= %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("Original Receive %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. //void createq();
  540. int showfront(char *uuid, char *data);
  541. int addq(char *uuid, char *data) ;
  542. int delq();
  543. int sentqueue();
  544. void CheckTransactionPacket(char *uuid);
  545. int queue_operation(int type, char *frontUUID, char *frontData);
  546. int showfront(char *uuid, char *data) {
  547. FILE *fp;
  548. int result = FALSE; // 1: TRUE 0:FALSE
  549. char str[1200]={0};
  550. char sstr[50]={ 0 };//sstr[200]={ 0 };
  551. int c = 0;
  552. char *loc;
  553. char rmFileCmd[100]={0};
  554. struct stat stats;
  555. stat("../Storage/OCPP", &stats);
  556. // Check for directory existence
  557. if (S_ISDIR(stats.st_mode) == 1)
  558. {
  559. //DEBUG_INFO("\n OCPP directory exist \n");
  560. }
  561. else
  562. {
  563. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  564. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  565. system(rmFileCmd);
  566. }
  567. memset(rmFileCmd, 0, sizeof rmFileCmd);
  568. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  569. {
  570. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  571. }
  572. else
  573. {
  574. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  575. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  576. if(log == NULL)
  577. {
  578. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  579. return 0;
  580. }
  581. else
  582. {
  583. fclose(log);
  584. }
  585. }
  586. /* opening file for reading */
  587. fp = fopen("../Storage/OCPP/TransactionRelatedQueue" , "r");
  588. if(fp == NULL) {
  589. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  590. return FALSE;
  591. }
  592. if( fgets (str, 1200, fp)!=NULL ) {
  593. /* writing content to stdout */
  594. if (str[0] == '\n')
  595. {
  596. DEBUG_INFO("It is a blank line");
  597. fclose(fp);
  598. memset(rmFileCmd, 0, sizeof rmFileCmd);
  599. sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/TransactionRelatedQueue");
  600. system(rmFileCmd);
  601. result = FALSE;
  602. return result;
  603. }
  604. else
  605. {
  606. puts(str);
  607. /*********************uuid***************/
  608. loc = strstr(str, "\"");
  609. memset(sstr ,0, sizeof(sstr) );
  610. c = 0;
  611. while (loc[1+c] != '\"')
  612. {
  613. sstr[c] = loc[1+c];
  614. c++;
  615. }
  616. sstr[c] = '\0';
  617. //DEBUG_INFO("\n uuid:%s", sstr);
  618. //DEBUG_INFO("\n data:%s", str);
  619. strcpy(uuid,sstr);
  620. strcpy(data,str);
  621. result = TRUE;
  622. }
  623. //return 1;
  624. }
  625. else
  626. {
  627. //DEBUG_INFO("queue is null\n");
  628. strcpy(uuid,"");
  629. strcpy(data,"");
  630. result = FALSE;
  631. //return 0;
  632. }
  633. fclose(fp);
  634. return result;
  635. }
  636. int addq(char *uuid, char *data) {
  637. FILE *outfile;
  638. char rmFileCmd[100]={0};
  639. struct stat stats;
  640. stat("../Storage/OCPP", &stats);
  641. //DEBUG_INFO("addq\n");
  642. // Check for directory existence
  643. if (S_ISDIR(stats.st_mode) == 1)
  644. {
  645. //DEBUG_INFO("\n OCPP directory exist \n");
  646. }
  647. else
  648. {
  649. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  650. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  651. system(rmFileCmd);
  652. }
  653. memset(rmFileCmd, 0, sizeof rmFileCmd);
  654. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  655. {
  656. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  657. }
  658. else
  659. {
  660. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  661. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  662. if(log == NULL)
  663. {
  664. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  665. return 0;
  666. }
  667. else
  668. {
  669. fclose(log);
  670. }
  671. }
  672. // open file for writing
  673. outfile = fopen ("../Storage/OCPP/TransactionRelatedQueue", "a");
  674. //DEBUG_INFO("data=%s\n",data);
  675. fputs(data, outfile);
  676. fputs("\n", outfile);
  677. fclose (outfile);
  678. TransactionQueueNum = TransactionQueueNum + 1;
  679. return 0;
  680. }
  681. int delq() {
  682. char tempfile[] = "../Storage/OCPP/temp.json";
  683. FILE *infile;
  684. FILE *outfile;
  685. int resultRename=0;
  686. char filename[60]={0};
  687. char rmFileCmd[100]={0};
  688. struct stat stats;
  689. stat("../Storage/OCPP", &stats);
  690. // Check for directory existence
  691. if (S_ISDIR(stats.st_mode) == 1)
  692. {
  693. //DEBUG_INFO("\n OCPP directory exist \n");
  694. }
  695. else
  696. {
  697. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  698. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  699. system(rmFileCmd);
  700. }
  701. memset(rmFileCmd, 0, sizeof rmFileCmd);
  702. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  703. {
  704. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  705. }
  706. else
  707. {
  708. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  709. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  710. if(log == NULL)
  711. {
  712. DEBUG_INFO("log is NULL\n");
  713. return 0;
  714. }
  715. else
  716. {
  717. fclose(log);
  718. }
  719. }
  720. // open file for writing
  721. strcpy(filename, "../Storage/OCPP/TransactionRelatedQueue");
  722. infile = fopen ("../Storage/OCPP/TransactionRelatedQueue", "r");
  723. outfile = fopen (tempfile, "w");
  724. /*检测到文件结束标识返回1,否则返回0。*/
  725. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  726. int c;
  727. c = fgetc(infile);
  728. //printf("file c:%d\n",c);
  729. rewind(infile);
  730. if(c == EOF)
  731. {
  732. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  733. fclose(infile);
  734. fclose(outfile);
  735. sprintf(rmFileCmd,"rm -f %s",tempfile);
  736. system(rmFileCmd);
  737. }
  738. else
  739. {
  740. char buf[1200]={0};
  741. int i = 0;
  742. //DEBUG_INFO("Orignal File is not NULL\n");
  743. while (fgets(buf, sizeof(buf), infile) != NULL)
  744. {
  745. //printf("Orignal File get strings \n");
  746. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  747. if(i==0)
  748. {
  749. TransactionQueueNum = TransactionQueueNum - 1;
  750. TransactionQueueInterval = 0;
  751. TransactionMessageResend = 1;
  752. }
  753. if(i != 0)
  754. fprintf(outfile,"%s\n", buf);
  755. i = i + 1;
  756. }
  757. fclose(infile);
  758. fclose(outfile);
  759. sprintf(rmFileCmd,"rm -f %s",filename);
  760. system(rmFileCmd);
  761. resultRename = rename(tempfile, filename);
  762. if(resultRename == 0)
  763. {
  764. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  765. }
  766. else
  767. {
  768. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  769. }
  770. }
  771. return 0;
  772. }
  773. int showqueue() {
  774. char rmFileCmd[100]={0};
  775. struct stat stats;
  776. stat("../Storage/OCPP", &stats);
  777. // Check for directory existence
  778. if (S_ISDIR(stats.st_mode) == 1)
  779. {
  780. //DEBUG_INFO("\n OCPP directory exist \n");
  781. }
  782. else
  783. {
  784. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  785. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  786. system(rmFileCmd);
  787. }
  788. memset(rmFileCmd, 0, sizeof rmFileCmd);
  789. if((access("../Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  790. {
  791. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  792. }
  793. else
  794. {
  795. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  796. FILE *log = fopen("../Storage/OCPP/TransactionRelatedQueue", "w+");
  797. if(log == NULL)
  798. {
  799. DEBUG_INFO("log is NULL\n");
  800. return 0;
  801. }
  802. else
  803. {
  804. fclose(log);
  805. }
  806. }
  807. FILE *fp = fopen("../Storage/OCPP/TransactionRelatedQueue", "r");
  808. char line[1200]={0};
  809. // check if file exist (and you can open it) or not
  810. if (fp == NULL) {
  811. DEBUG_INFO("can open file TransactionRelatedQueue!");
  812. return 0;
  813. }
  814. while(fgets(line, sizeof line, fp) != NULL) {
  815. DEBUG_INFO("%s\n", line);
  816. }
  817. fclose(fp);
  818. return 0;
  819. }
  820. int sentqueue(){
  821. FILE *fp;
  822. int result = FALSE; // 1: TRUE 0:FALSE
  823. char str[1200]={0};
  824. char rmFileCmd[100]={0};
  825. struct stat stats;
  826. DEBUG_INFO("sentqueue\n");
  827. stat("../Storage/OCPP", &stats);
  828. // Check for directory existence
  829. if (S_ISDIR(stats.st_mode) == 1)
  830. {
  831. //DEBUG_INFO("\n OCPP directory exist \n");
  832. }
  833. else
  834. {
  835. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  836. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  837. system(rmFileCmd);
  838. }
  839. memset(rmFileCmd, 0, sizeof rmFileCmd);
  840. /* opening file for reading */
  841. fp = fopen("../Storage/OCPP/TransactionRelatedQueue" , "r");
  842. if(fp == NULL) {
  843. DEBUG_INFO("Error opening file");
  844. return FALSE;
  845. }
  846. if( fgets (str, 1200, fp)!=NULL ) {
  847. /* writing content to stdout */
  848. //puts(str);
  849. //DEBUG_INFO("\n uuid:%s", "");
  850. //DEBUG_INFO("\n data:%s", str);
  851. LWS_Send(str);
  852. result = TRUE;
  853. //return 1;
  854. }
  855. else
  856. {
  857. //DEBUG_INFO("queue is null\n");
  858. result = FALSE;
  859. //return 0;
  860. }
  861. fclose(fp);
  862. //DEBUG_INFO("sentqueue end\n");
  863. return result;
  864. }
  865. //
  866. void* processTransactionQueue(void* data) {
  867. char frontUUID[100] ={0};
  868. char frontData[1200/*1024*4*/] ={0};
  869. int queueNotEmpty = 0;
  870. while(1)
  871. {
  872. if(FirstHeartBeatResponse() == 1)
  873. {
  874. memset(frontUUID, 0, sizeof(frontUUID));
  875. memset(frontData, 0, sizeof(frontData));
  876. queueNotEmpty = 0;
  877. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  878. if((queueNotEmpty == 1) && (GetOcppConnStatus() == 1))
  879. {
  880. if((OfflineTransaction == 1) && (TransactionQueueNum != 0))
  881. {
  882. TransactionQueueInterval = 2;
  883. sleep(TransactionQueueInterval);
  884. sendbuffer = 1;
  885. }
  886. else
  887. {
  888. OfflineTransaction = 0;
  889. if(TransactionMessageResend < TransactionMessageAttemptsGet()) //
  890. {
  891. //DEBUG_INFO("processTransactionQueue queue is not empty!\n");
  892. TransactionQueueInterval= TransactionMessageRetryIntervalGet()* TransactionMessageResend;
  893. sleep(TransactionQueueInterval);
  894. sendbuffer = 1;
  895. TransactionMessageResend = TransactionMessageResend + 1;
  896. }
  897. else
  898. {
  899. queue_operation(2,"",""); //// delete item
  900. TransactionQueueInterval = 0;
  901. TransactionMessageResend = 1;
  902. sleep(TransactionQueueInterval);
  903. }
  904. }
  905. }
  906. else if((queueNotEmpty == 1) && (GetOcppConnStatus() == 0))
  907. {
  908. OfflineTransaction = 1;
  909. }
  910. else
  911. {
  912. TransactionQueueInterval = 0;//10;
  913. sleep(TransactionQueueInterval);
  914. }
  915. }
  916. usleep(5000);
  917. }
  918. pthread_exit(NULL); //
  919. return 0;
  920. }
  921. void CheckTransactionPacket(char *uuid)
  922. {
  923. char frontUUID[100]={0};
  924. char frontData[1200]={0};
  925. int queueNotEmpty = 0;
  926. int cmpResult = 0;
  927. //queue_operation(0,"","");//showqueue(); ---> remove temporally
  928. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  929. if(queueNotEmpty == 1)
  930. {
  931. cmpResult = strcmp(frontUUID, uuid);
  932. //cmpResult = strcmp(frontData, uuid);
  933. if (cmpResult == 0)
  934. {
  935. //DEBUG_INFO("TransactionPacket Compare All right!\n");
  936. queue_operation(2,"","");//delq(); ---> remove temporally
  937. }
  938. }
  939. }
  940. /* type: 0 (showqueue ); type: 1(showfront); type: 2(delq) type: 3 (sentqueue) type: 4 (addq) type: 5(store queue to /Storage/OCPP/ )*/
  941. int queue_operation(int type, char *frontUUID, char *frontData)
  942. {
  943. pthread_mutex_unlock(&lock_sentData);
  944. pthread_mutex_lock(&lock_sentData);
  945. int result=0;
  946. if(type == 0) // show items in queue
  947. result = showqueue();
  948. else if(type == 1) // show first item
  949. result = showfront(frontUUID, frontData);
  950. else if(type == 2) // delete item
  951. result = delq();
  952. else if(type == 3) // sent items in queue
  953. result = sentqueue();
  954. else if(type == 4) // add items to the queue
  955. result = addq(frontUUID, frontData);
  956. pthread_mutex_unlock(&lock_sentData);
  957. return result;
  958. }
  959. char * strchr(const char *p, int ch)
  960. {
  961. char c;
  962. c = ch;
  963. for (;; ++p) {
  964. if (*p == c)
  965. return ((char *)p);
  966. if (*p == '\0')
  967. return (NULL);
  968. }
  969. /* NOTREACHED */
  970. return NULL;
  971. }
  972. int removeMessageSentFile(void)
  973. {
  974. char rmFileCmd[100]={0};
  975. struct stat stats;
  976. //
  977. stat("../Storage/OCPP", &stats);
  978. // Check for directory existence
  979. if (S_ISDIR(stats.st_mode) == 1)
  980. {
  981. //DEBUG_INFO("\n OCPP directory exist \n");
  982. }
  983. else
  984. {
  985. DEBUG_INFO("\n directory not exist, create dir \n");
  986. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  987. system(rmFileCmd);
  988. }
  989. memset(rmFileCmd, 0, sizeof rmFileCmd);
  990. if((access("../Storage/OCPP/MessageSent",F_OK))!=-1)
  991. {
  992. DEBUG_INFO("MessageSent file exist.\n");
  993. sprintf(rmFileCmd,"rm -f %s","../Storage/OCPP/MessageSent");
  994. system(rmFileCmd);
  995. }
  996. memset(rmFileCmd, 0, sizeof rmFileCmd);
  997. return 0;
  998. }
  999. #define SystemLogMessage
  1000. //================================================
  1001. // Main process
  1002. //================================================
  1003. int main(void)
  1004. {
  1005. char rmFileCmd[100]={0};
  1006. struct stat stats;
  1007. pthread_t t;
  1008. #ifdef SystemLogMessage
  1009. DEBUG_INFO("Initialization...\n");
  1010. #endif
  1011. if(ProcessShareMemory()== FAIL)
  1012. {
  1013. return FAIL;
  1014. }
  1015. //Create OCPP dir
  1016. stat("../Storage/OCPP", &stats);
  1017. // Check for directory existence
  1018. if (S_ISDIR(stats.st_mode) == 1)
  1019. {
  1020. //DEBUG_INFO("\n OCPP directory exist \n");
  1021. }
  1022. else
  1023. {
  1024. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  1025. sprintf(rmFileCmd,"mkdir -p %s","../Storage/OCPP");
  1026. system(rmFileCmd);
  1027. }
  1028. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1029. //Create Process: Resend Transaction
  1030. pthread_create(&t, NULL, processTransactionQueue, NULL); //
  1031. sqlite3_config(SQLITE_CONFIG_URI,1);
  1032. if(sqlite3_open("file:/../Storage/OCPP/charger.db", &db))
  1033. {
  1034. #ifdef Debug
  1035. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1036. #endif
  1037. sqlite3_close( db );
  1038. exit(0);
  1039. }
  1040. else
  1041. {
  1042. #ifdef Debug
  1043. DEBUG_INFO( "Opened database successfully\n");
  1044. #endif
  1045. }
  1046. //Create Table log buffer
  1047. int rc =sqlite3_exec(db, createsql, 0, 0, &errMsg);
  1048. if (SQLITE_OK != rc)
  1049. {
  1050. #ifdef Debug
  1051. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1052. #endif
  1053. return 0;
  1054. }
  1055. else
  1056. {
  1057. #ifdef Debug
  1058. DEBUG_INFO( "Opened log buffer table successfully\n");
  1059. #endif
  1060. }
  1061. // Create Table OcppAuthCache
  1062. rc =sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg);
  1063. if (SQLITE_OK != rc)
  1064. {
  1065. #ifdef Debug
  1066. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1067. #endif
  1068. return 0;
  1069. }
  1070. else
  1071. {
  1072. #ifdef Debug
  1073. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1074. #endif
  1075. }
  1076. // Create Table OcppAuthLocal
  1077. rc =sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg);
  1078. if (SQLITE_OK != rc)
  1079. {
  1080. #ifdef Debug
  1081. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1082. #endif
  1083. return 0;
  1084. }
  1085. else
  1086. {
  1087. #ifdef Debug
  1088. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1089. #endif
  1090. }
  1091. initialConfigurationTable();
  1092. removeMessageSentFile();
  1093. //queryAllData();
  1094. OCPP_get_TableAuthlocalAllData();
  1095. for(;;)
  1096. {
  1097. while(ConnectionEstablished==0)
  1098. {
  1099. SetOcppConnStatus(FALSE);
  1100. if((time((time_t*)NULL)-startTime.connect)>=60)
  1101. {
  1102. #ifdef Debug
  1103. DEBUG_INFO("Execute ConnectWsServer\n");
  1104. #endif
  1105. ConnectWsServer();
  1106. startTime.connect=time((time_t*)NULL);
  1107. }
  1108. // Check System Value, process offline Transaction
  1109. CheckSystemValue();
  1110. lws_service(context, 10000);//timeout_ms
  1111. }
  1112. if(( (BootNotificationInterval != 0 && ((time((time_t*)NULL)-startTime.bootNotification)>=BootNotificationInterval) ) || ((time((time_t*)NULL)-startTime.bootNotification)>=defaultWaitingTime) ) && ((server_sign == FALSE)/*|| (server_pending == TRUE)*/))
  1113. {
  1114. //hashmapForMessageNew();
  1115. sendBootNotificationRequest();
  1116. startTime.bootNotification=time((time_t*)NULL);
  1117. }
  1118. if(server_sign == TRUE)
  1119. {
  1120. if(sendbuffer == 1)
  1121. {
  1122. queue_operation(3, "", "");//sentqueue()
  1123. sendbuffer = 0;
  1124. }
  1125. SetOcppConnStatus(TRUE);
  1126. // Check System Value
  1127. CheckSystemValue();
  1128. if(GetHeartBeatWithNOResponse() >= 3)
  1129. {
  1130. lws_context_destroy(context);
  1131. ConnectionEstablished=0;
  1132. context = NULL;
  1133. SetHeartBeatWithNOResponse();
  1134. }
  1135. }
  1136. lws_service(context, 100);//timeout_ms
  1137. }
  1138. pthread_join(t, NULL); //
  1139. //hashmapForMessageFree();
  1140. return FAIL;
  1141. }