Module_OcppBackend.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818
  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/mman.h>
  10. #include <linux/wireless.h>
  11. #include <linux/sockios.h>
  12. #include <linux/socket.h>
  13. #include <arpa/inet.h>
  14. #include <netinet/in.h>
  15. #include <unistd.h>
  16. #include <stdarg.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <unistd.h>
  20. #include <fcntl.h>
  21. #include <termios.h>
  22. #include <errno.h>
  23. #include <string.h>
  24. #include <time.h>
  25. #include <ctype.h>
  26. #include <ifaddrs.h>
  27. #include "libwebsockets.h"
  28. #include <lws_config.h>
  29. #include "hashmap.h"
  30. #include "SystemLogMessage.h"
  31. #include "ShareMemory.h"
  32. #include <pthread.h>
  33. #include "MessageHandler.h"
  34. #include "sqlite3.h"
  35. #ifndef SPEC_LATEST_SUPPORTED
  36. #define SPEC_LATEST_SUPPORTED 13
  37. #endif
  38. #define Debug
  39. //#define ARRAY_SIZE(A) (sizeof(A) / sizeof(A[0]))
  40. #define PASS 1
  41. #define FAIL -1
  42. typedef enum boolean { FALSE, TRUE } BOOL;
  43. struct lws *wsi_client;
  44. struct lws_context *context;
  45. static int sendbuffer = 0;
  46. pthread_t pid;
  47. //extern int server_sign;
  48. extern void CheckSystemValue(void);
  49. extern int FirstHeartBeatResponse(void);
  50. extern void OCPP_get_TableAuthlocalAllData(void);
  51. extern int TransactionMessageAttemptsGet(void);
  52. extern int TransactionMessageRetryIntervalGet(void);
  53. extern int GetOcppConnStatus(void);
  54. extern void SetOcppConnStatus(uint8_t status);
  55. extern int GetHeartBeatWithNOResponse(void);
  56. extern void SetHeartBeatWithNOResponse(void);
  57. pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
  58. pthread_mutex_t lock_sentData = PTHREAD_MUTEX_INITIALIZER;
  59. pthread_mutex_t receiveData = PTHREAD_MUTEX_INITIALIZER;
  60. //==========================================
  61. // Function prototype
  62. //==========================================
  63. void trim(char *s);
  64. int mystrcmp(char *p1,char *p2);
  65. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
  66. void getSubStr(char *dest, char* src, char *split, int idx);
  67. void split(char **arr, char *str, const char *del);
  68. int strpos(char *source, char *substr, int skip);
  69. int strposs(char *source, char *substr, int idx);
  70. char *random_uuid( char buf[37] );
  71. static int OCPP16Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len);
  72. char * strchr(const char *p, int ch);
  73. void ReceivedMessage(void *in, size_t len);
  74. struct StartTime
  75. {
  76. unsigned int connect;
  77. unsigned int bootNotification;
  78. }startTime;
  79. #if 0
  80. unsigned char *SendBuffer;
  81. int SendBufLen=(1024*4);//(1024*3);
  82. #endif
  83. int SendBufLen=(1024*4);//(1024*3);
  84. unsigned char SendBuffer[1024*4]={0};
  85. static int ConnectionEstablished=0;
  86. static int TransactionMessageResend = 1; // the number of retry to submit a transaction-related message when the Central System fails to process it.
  87. static int TransactionQueueInterval = 10;//3;
  88. static int TransactionQueueNum = 0;
  89. static int OfflineTransactionQueueNum = 0; // Number of offline transactions
  90. static int OfflineTransaction = 0;
  91. static int IsUsing = FALSE;
  92. int defaultWaitingTime = 10; //10 second
  93. char OcppPath[160]={0};
  94. char OcppProtocol[10]={0},OcppHost[50]={0}, OcppTempPath[50]={0};
  95. //===============================
  96. // OCPP SentQueue TransactionId
  97. //===============================
  98. //static int SentQueueTransactionId[10]={0};
  99. //extern int BootNotificationInterval;
  100. //char guid[37];
  101. //map_t hashMap;
  102. //data_struct_t* mapItem; --- remove for temporally
  103. //data_struct_t mapItem[0]={0};
  104. sqlite3 *db;
  105. char *errMsg = NULL;
  106. static char *createsql = "CREATE TABLE IF NOT EXISTS log_buffer("
  107. "idx integer primary key,"
  108. "user_id text,"
  109. "cmd_sn text,"
  110. "charger_id text,"
  111. "gun_type text,"
  112. "gun_no text,"
  113. "rfid_no text,"
  114. "stime text,"
  115. "etime text,"
  116. "time_len text,"
  117. "s_soc text,"
  118. "e_soc text,"
  119. "stop_reason text,"
  120. "power text,"
  121. "meter_before text,"
  122. "meter_after text,"
  123. "charge_price text,"
  124. "reserve text,"
  125. "surplus_before text,"
  126. "surplus_after text,"
  127. "service_price text,"
  128. "is_pay text,"
  129. "charge_strategy text,"
  130. "charge_parameter text,"
  131. "vin text,"
  132. "vehicle_no text,"
  133. "start_method text,"
  134. "card_type text,"
  135. "is_upload text,"
  136. "guid text UNIQUE,"
  137. "is_buf2OK text);";
  138. #if 0
  139. static char *createsChargingRecordsql = "CREATE TABLE IF NOT EXISTS ChargingRecord("
  140. "idx integer primary key,"
  141. "gun_type text,"
  142. "connectorId text,"
  143. "idTag text,"
  144. "transactionId text,"
  145. "stime text,"
  146. "etime text,"
  147. "time_len text,"
  148. "s_soc text,"
  149. "e_soc text,"
  150. "stop_reason text,"
  151. "power text,"
  152. "meter_before text,"
  153. "meter_after text,"
  154. "reservationId text,"
  155. "guid text UNIQUE);";
  156. //"is_buf2OK text);";
  157. #endif
  158. static char *sqlOcppAuthCache = "create table if not exists ocpp_auth_cache (idx integer primary key,"
  159. "idtag text UNIQUE,"
  160. "parent_idtag text,"
  161. "expir_date text,"
  162. "status text);";
  163. static char *sqlOcppAuthLocal = "create table if not exists ocpp_auth_local (idx integer primary key,"
  164. "idtag text UNIQUE,"
  165. "parent_idtag text,"
  166. "expir_date text,"
  167. "status text,"
  168. "version text);";
  169. #if 0
  170. 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')";
  171. #endif
  172. int DiffTimeb(struct timeb ST, struct timeb ET)
  173. {
  174. //return milli-second
  175. unsigned int StartTime,StopTime;
  176. StartTime=(unsigned int)ST.time;
  177. StopTime=(unsigned int)ET.time;
  178. return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
  179. }
  180. //=================================
  181. // Common routine
  182. //=================================
  183. void trim(char *s)
  184. {
  185. int i=0, j, k, l=0;
  186. while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
  187. i++;
  188. j = strlen(s)-1;
  189. while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
  190. j--;
  191. if(i==0 && j==strlen(s)-1) { }
  192. else if(i==0) s[j+1] = '\0';
  193. else {
  194. for(k=i; k<=j; k++) s[l++] = s[k];
  195. s[l] = '\0';
  196. }
  197. }
  198. int mystrcmp(char *p1,char *p2)
  199. {
  200. while(*p1==*p2)
  201. {
  202. if(*p1=='\0' || *p2=='\0')
  203. break;
  204. p1++;
  205. p2++;
  206. }
  207. if(*p1=='\0' && *p2=='\0')
  208. return(PASS);
  209. else
  210. return(FAIL);
  211. }
  212. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
  213. {
  214. strncpy(dest, src + start, cnt);
  215. dest[cnt] = 0;
  216. }
  217. void getSubStr(char *dest, char* src, char *split, int idx)
  218. {
  219. int start = (strposs(src,",",idx)+1);
  220. int cnt = (strposs(src,",",idx+1)-2)-(strposs(src,",",idx)+1);
  221. strncpy(dest, src + start, cnt);
  222. dest[cnt] = 0;
  223. }
  224. void split(char **arr, char *str, const char *del)
  225. {
  226. char *s = strtok(str, del);
  227. while(s != NULL)
  228. {
  229. *arr++ = s;
  230. s = strtok(NULL, del);
  231. }
  232. }
  233. int strpos(char *source, char *substr, int skip)
  234. {
  235. char stack[strlen(source)];
  236. strncpy(stack, source+skip, strlen(source)-skip);
  237. char *p = strstr(stack, substr);
  238. if (p)
  239. return p - stack+skip;
  240. return -1;
  241. }
  242. int strposs(char *source, char *substr, int idx)
  243. {
  244. char stack[strlen(source)];
  245. int result=0;
  246. int count=0;
  247. while(count<=idx)
  248. {
  249. memset(stack,0,sizeof stack);
  250. strncpy(stack, source+result, strlen(source)-result);
  251. int loc = strcspn(stack, substr);
  252. if(loc>0)
  253. result += (loc+1);
  254. else
  255. result = -1;
  256. count++;
  257. }
  258. return result;
  259. }
  260. char * strtrim( char * s )
  261. {
  262. char * p1 = s;
  263. char * p2 = s;
  264. while(*p1 != '\0')
  265. {
  266. while(*p1 == '\t' || *p1 == '\n' || *p1 == '\r') //while(*p1 == ' ' || *p1 == '\t' || *p1 == '\n' || *p1 == '\r')
  267. {
  268. p1 ++;
  269. }
  270. * p2 ++ = *p1 ++;
  271. //printf("p2=%s\n",p2);
  272. }
  273. *p2 = '\0';
  274. return (s);
  275. }
  276. static int testnum = 0;
  277. char *random_uuid( char buf[37] )
  278. {
  279. // const char *c = "89ab";
  280. char *p = buf;
  281. // int n;
  282. #if 1 // test
  283. time_t seconds;
  284. seconds = time(NULL);
  285. testnum = testnum % 999;
  286. testnum = testnum + 1;
  287. //printf("\n testnum:%d\n", testnum);
  288. //printf("\n seconds:%d\n", seconds);
  289. sprintf(p, "%03d%033d", testnum, (unsigned int)(seconds));
  290. //printf("\n p:%s\n", p);
  291. #endif
  292. #if 0
  293. for( n = 0; n < 16; ++n )
  294. {
  295. int b = rand()%255;
  296. switch( n )
  297. {
  298. case 6:
  299. sprintf(p, "4%x", b%15 );
  300. break;
  301. case 8:
  302. sprintf(p, "%c%x", c[rand()%strlen(c)], b%15 );
  303. break;
  304. default:
  305. sprintf(p, "%02x", b);
  306. break;
  307. }
  308. p += 2;
  309. switch( n )
  310. {
  311. case 3:
  312. case 5:
  313. case 7:
  314. case 9:
  315. *p++ = '-';
  316. break;
  317. }
  318. }
  319. *p = 0;
  320. #endif
  321. return buf;
  322. }
  323. int GetTransactionQueueNum(void)
  324. {
  325. return TransactionQueueNum;
  326. }
  327. //==========================================
  328. // Web socket tranceive routine
  329. //==========================================
  330. int SendData(struct lws *wsi)
  331. {
  332. int n;
  333. int len;
  334. char *ret;
  335. unsigned char out[LWS_SEND_BUFFER_PRE_PADDING + 4096 + LWS_SEND_BUFFER_POST_PADDING] = {0};
  336. len = strlen((char *)SendBuffer);
  337. if(len == 0)
  338. return 0;
  339. memcpy (out + LWS_SEND_BUFFER_PRE_PADDING, SendBuffer, len );
  340. ret = strstr((const char *)(out + LWS_SEND_BUFFER_PRE_PADDING), "Heartbeat");
  341. if(ret == NULL)
  342. {
  343. DEBUG_OCPPMESSAGE_INFO(" SendData= %s\n", out + LWS_SEND_BUFFER_PRE_PADDING);
  344. }
  345. n = lws_write(wsi, out + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
  346. memset(SendBuffer, 0, len);
  347. return n;
  348. }
  349. static int OCPP16Callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
  350. {
  351. switch (reason)
  352. {
  353. case LWS_CALLBACK_PROTOCOL_INIT:
  354. #ifdef SystemLogMessage
  355. DEBUG_INFO("LWS_CALLBACK_PROTOCOL_INIT\n");
  356. #endif
  357. break;
  358. case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH:
  359. #ifdef SystemLogMessage
  360. DEBUG_INFO("LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH\n");
  361. #endif
  362. char buf[64];
  363. char hash[20], key_b64[40];
  364. lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));// Sec-WebSocket-Key
  365. DEBUG_OCPPMESSAGE_INFO("------------------Handshake: Client Request START----------------\n");
  366. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, _WSI_TOKEN_CLIENT_URI);
  367. DEBUG_OCPPMESSAGE_INFO("GET %s HTTP/1.1 \n", buf);
  368. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, _WSI_TOKEN_CLIENT_HOST);
  369. DEBUG_OCPPMESSAGE_INFO("Host: %s\n", buf);
  370. //lws_hdr_copy(wsi, buf, sizeof(buf) - 1, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
  371. //DEBUG_OCPPMESSAGE_INFO("_WSI_TOKEN_CLIENT_PEER_ADDRESS %s\n", buf);
  372. DEBUG_OCPPMESSAGE_INFO("Upgrade: websocket\n");
  373. DEBUG_OCPPMESSAGE_INFO("Connection: Upgrade\n");
  374. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Key: %s\n", key_b64);
  375. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
  376. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  377. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Version: %d\n", SPEC_LATEST_SUPPORTED);
  378. DEBUG_OCPPMESSAGE_INFO("------------------Handshake: Client Request END----------------\n");
  379. DEBUG_OCPPMESSAGE_INFO("------------------Handshake: Server response START----------------\n");
  380. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, WSI_TOKEN_HTTP);
  381. DEBUG_OCPPMESSAGE_INFO("HTTP/1.1 %s\n", buf);
  382. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, WSI_TOKEN_UPGRADE);
  383. DEBUG_OCPPMESSAGE_INFO("Upgrade: %s\n", buf);
  384. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, WSI_TOKEN_CONNECTION);
  385. DEBUG_OCPPMESSAGE_INFO("Connection: %s\n", buf);
  386. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, WSI_TOKEN_ACCEPT);
  387. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Accept: %s\n", buf);
  388. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, WSI_TOKEN_PROTOCOL);
  389. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  390. DEBUG_OCPPMESSAGE_INFO("------------------Handshake: Server response END----------------\n");
  391. break;
  392. case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
  393. #ifdef SystemLogMessage
  394. DEBUG_INFO("LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION\n");
  395. #endif
  396. break;
  397. case LWS_CALLBACK_WSI_DESTROY:
  398. #ifdef SystemLogMessage
  399. DEBUG_INFO("LWS_CALLBACK_WSI_DESTROY\n");
  400. #endif
  401. pthread_detach(pid);
  402. SetServerSign(FALSE);
  403. //server_sign = FALSE;
  404. ConnectionEstablished=0;
  405. context = NULL;
  406. break;
  407. case LWS_CALLBACK_LOCK_POLL:
  408. break;
  409. case LWS_CALLBACK_ADD_POLL_FD:
  410. #ifdef SystemLogMessage
  411. DEBUG_INFO("LWS_CALLBACK_ADD_POLL_FD\n");
  412. #endif
  413. break;
  414. case LWS_CALLBACK_DEL_POLL_FD:
  415. #ifdef SystemLogMessage
  416. DEBUG_INFO("LWS_CALLBACK_DEL_POLL_FD\n");
  417. #endif
  418. break;
  419. case LWS_CALLBACK_UNLOCK_POLL:
  420. break;
  421. case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
  422. break;
  423. case LWS_CALLBACK_WSI_CREATE:
  424. #ifdef SystemLogMessage
  425. DEBUG_INFO("LWS_CALLBACK_WSI_CREATE\n");
  426. #endif
  427. break;
  428. case LWS_CALLBACK_GET_THREAD_ID:
  429. break;
  430. case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
  431. {
  432. #ifdef SystemLogMessage
  433. DEBUG_INFO("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
  434. #endif
  435. }
  436. break;
  437. case LWS_CALLBACK_CLIENT_ESTABLISHED: //3
  438. {
  439. #ifdef SystemLogMessage
  440. DEBUG_INFO("LWS_CALLBACK_CLIENT_ESTABLISHED\n");
  441. #endif
  442. char frontUUID[100] ={0};
  443. char frontData[1200] ={0};
  444. int queueNotEmpty = FALSE;
  445. //connected
  446. ConnectionEstablished=1;
  447. queueNotEmpty = queue_operation(1,frontUUID, frontData);
  448. if(queueNotEmpty == TRUE)
  449. {
  450. OfflineTransaction = 1; // 0: no packets in queue. 1: There are packets in queue.
  451. }
  452. TransactionQueueInterval = 0;
  453. TransactionMessageResend = 1;
  454. //get offline number
  455. queue_operation(0,"","");
  456. OfflineTransactionQueueNum =TransactionQueueNum ;
  457. }
  458. break;
  459. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR://1
  460. #ifdef SystemLogMessage
  461. DEBUG_ERROR("LWS_CALLBACK_CLIENT_CONNECTION_ERROR %s\n", (char *)in );
  462. #endif
  463. //disconnected
  464. ConnectionEstablished=0;
  465. char buf1[64];
  466. char hash1[20]={0}, key_b641[40]={0};
  467. lws_b64_encode_string(hash1, 16, key_b641, sizeof(key_b641));// Sec-WebSocket-Key
  468. DEBUG_OCPPMESSAGE_INFO("------------------Handshake: Client START----------------\n");
  469. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, _WSI_TOKEN_CLIENT_URI);
  470. DEBUG_OCPPMESSAGE_INFO("GET %s HTTP/1.1 \n", buf);
  471. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, _WSI_TOKEN_CLIENT_HOST);
  472. DEBUG_OCPPMESSAGE_INFO("Host: %s\n", buf);
  473. //lws_hdr_copy(wsi, buf, sizeof(buf) - 1, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
  474. //DEBUG_OCPPMESSAGE_INFO("_WSI_TOKEN_CLIENT_PEER_ADDRESS %s\n", buf);
  475. DEBUG_OCPPMESSAGE_INFO("Upgrade: websocket\n");
  476. DEBUG_OCPPMESSAGE_INFO("Connection: Upgrade\n");
  477. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Key: %s\n", key_b641);
  478. lws_hdr_copy(wsi, buf, sizeof(buf) - 1, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
  479. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf);
  480. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Version: %d\n", SPEC_LATEST_SUPPORTED);
  481. DEBUG_OCPPMESSAGE_INFO("------------------Handshake: Client END----------------\n");
  482. DEBUG_OCPPMESSAGE_INFO("------------------Handshake: Server response START----------------\n");
  483. lws_hdr_copy(wsi, buf1, sizeof(buf1) - 1, WSI_TOKEN_HTTP);
  484. DEBUG_OCPPMESSAGE_INFO("HTTP/1.1 %s\n", buf1);
  485. lws_hdr_copy(wsi, buf1, sizeof(buf1) - 1, WSI_TOKEN_UPGRADE);
  486. DEBUG_OCPPMESSAGE_INFO("Upgrade: %s\n", buf1);
  487. lws_hdr_copy(wsi, buf1, sizeof(buf1) - 1, WSI_TOKEN_CONNECTION);
  488. DEBUG_OCPPMESSAGE_INFO("Connection: %s\n", buf1);
  489. lws_hdr_copy(wsi, buf1, sizeof(buf1) - 1, WSI_TOKEN_ACCEPT);
  490. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Accept: %s\n", buf1);
  491. lws_hdr_copy(wsi, buf1, sizeof(buf1) - 1, WSI_TOKEN_PROTOCOL);
  492. DEBUG_OCPPMESSAGE_INFO("Sec-WebSocket-Protocol: %s\n", buf1);
  493. DEBUG_OCPPMESSAGE_INFO("------------------Handshake: Server response END----------------\n");
  494. break;
  495. case LWS_CALLBACK_CLOSED://4
  496. #ifdef SystemLogMessage
  497. DEBUG_INFO("LWS_CALLBACK_CLOSED\n");
  498. #endif
  499. //disconnected
  500. ConnectionEstablished=0;
  501. break;
  502. case LWS_CALLBACK_CLIENT_WRITEABLE://10
  503. //if(need to send message and its relevant data already store into SendBuffer)
  504. #ifdef SystemLogMessage
  505. //DEBUG_INFO("LWS_CALLBACK_CLIENT_WRITEABLE\n");
  506. #endif
  507. SendData(wsi);
  508. //lws_rx_flow_control( wsi, 1 );
  509. break;
  510. case LWS_CALLBACK_CLIENT_RECEIVE://8
  511. ((char *)in)[len] = '\0';
  512. //Print out OCPP Message , except for HeartBeat
  513. {
  514. char *ret, *ret1;
  515. ret = strstr((const char *)in, "currentTime");
  516. ret1 = strstr((const char *)in, "interval");
  517. if(!((ret != NULL)&&(ret1 == NULL)))
  518. {
  519. DEBUG_OCPPMESSAGE_INFO("Original Receive %s\n", (char *)in);
  520. }
  521. }
  522. char tempin[65536]={0};
  523. //char tempin[1024*4]={0};
  524. int c = 0;
  525. char *loc;
  526. char sstr[65536]={ 0 };
  527. //char sstr[600]={ 0 };
  528. //**********Receive Message**********/
  529. c = 0;
  530. loc = strstr((const char *)in, "][2,");
  531. if(loc == NULL)
  532. {
  533. loc = strstr((const char *)in, "][3,");
  534. if(loc == NULL)
  535. {
  536. loc = strstr((const char *)in, "][4,");
  537. }
  538. }
  539. memset(sstr ,0, sizeof(sstr) );
  540. if(loc != NULL)
  541. {
  542. DEBUG_INFO("there are continuous second packet []\n");
  543. while (loc[1+c] != '\0')
  544. {
  545. sstr[c] = loc[1+c];
  546. c++;
  547. }
  548. sstr[c] = '\0';
  549. strcpy(tempin, sstr);
  550. DEBUG_INFO("Final Receive: %s\n", tempin);
  551. }
  552. else
  553. {
  554. strcpy(tempin,(char *)in);
  555. }
  556. //ReceivedMessage((void *)tempin, len);
  557. ReceivedMessage((void *)strtrim(tempin), len);
  558. break;
  559. default:
  560. #ifdef Debug
  561. DEBUG_INFO("OCPP16Callback:reason=%d\n", reason);
  562. #endif
  563. break;
  564. }
  565. return 0;
  566. }
  567. static struct lws_protocols protocols[] = {
  568. {
  569. "ocpp1.6",
  570. OCPP16Callback,
  571. 10240,//65536,//10240,
  572. 10240,//65536,//10240,
  573. },
  574. {
  575. "ocpp1.6",
  576. OCPP16Callback,
  577. 10240,//65536,//10240,
  578. 10240,//65536,//10240,
  579. },
  580. {
  581. NULL, NULL, 0 /* End of list */
  582. }
  583. };
  584. void* ConnectWsServer(void* data) //int ConnectWsServer()
  585. {
  586. //pthread_detach(pthread_self());
  587. //int result = PASS;
  588. struct lws_context_creation_info ContextInfo;
  589. struct lws_client_connect_info ConnInfo;
  590. int use_ssl=0;
  591. //lws_set_log_level(LLL_PARSER | LLL_HEADER | LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_INFO | LLL_DEBUG | LLL_EXT | LLL_CLIENT | LLL_LATENCY , NULL);
  592. if(context!=NULL)
  593. {
  594. pthread_detach(pthread_self());
  595. lws_context_destroy(context);
  596. ConnectionEstablished=0;
  597. context = NULL;
  598. }
  599. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  600. if((GetOcppServerURL()==0) || (GetOcppPort() == 0) || (GetOcppPath()==0))
  601. {
  602. //result = FAIL;
  603. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  604. goto end;
  605. //return result;
  606. }
  607. if((strcmp(OcppProtocol,"ws")==0)&&(strlen(OcppProtocol)== 2))
  608. {
  609. printf("ws!!! \n");
  610. use_ssl=0;
  611. }
  612. else if((strcmp(OcppProtocol,"wss")==0)&&(strlen(OcppProtocol)== 3))
  613. {
  614. printf("wss!!! \n");
  615. use_ssl=1;
  616. }
  617. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  618. ContextInfo.iface = NULL;
  619. ContextInfo.ssl_private_key_password = NULL;
  620. ContextInfo.ssl_cert_filepath = NULL;//"./ssl_key/client_cert.pem";
  621. ContextInfo.ssl_private_key_filepath = NULL;//"./ssl_key/client_key.pem";
  622. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";//"./cacert.pem";
  623. ContextInfo.ssl_cipher_list = NULL; //use default one
  624. ContextInfo.gid = -1;
  625. ContextInfo.uid = -1;
  626. if(use_ssl)
  627. {
  628. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT ;
  629. }
  630. ContextInfo.protocols = protocols;
  631. ContextInfo.timeout_secs = GetWebSocketPingInterval();//WebSocketPingInterval;//30;//9999;//30;
  632. //if(ping pong enabled)
  633. ContextInfo.ws_ping_pong_interval = GetWebSocketPingInterval();//WebSocketPingInterval;//30;//0 for none, else interval in seconds
  634. context = lws_create_context(&ContextInfo);
  635. if (context == NULL)
  636. {
  637. //#ifdef SystemLogMessage
  638. DEBUG_ERROR("lws_create_context NG");
  639. //#endif
  640. //result = FAIL;
  641. goto end;
  642. }
  643. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  644. // fill up below information
  645. ConnInfo.context = context;
  646. ConnInfo.address=(const char *)OcppHost;
  647. printf("\n ConnInfo.address=%s\n",ConnInfo.address);
  648. ConnInfo.port = GetOcppPort();
  649. printf("\n ConnInfo.port=%d\n",ConnInfo.port);
  650. ConnInfo.path=(const char *)OcppPath;
  651. printf("\n ConnInfo.path=%s\n",ConnInfo.path);
  652. char addr_port[256] = { 0 };
  653. sprintf(addr_port, "%s:%u", ConnInfo.address, ConnInfo.port & 65535 );
  654. ConnInfo.host= addr_port; // ConnInfo.address;//lws_canonical_hostname(context);
  655. ConnInfo.origin="origin";
  656. ConnInfo.protocol = protocols[1].name;
  657. ConnInfo.ietf_version_or_minus_one = -1;
  658. if(use_ssl)
  659. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
  660. wsi_client = lws_client_connect_via_info(&ConnInfo);
  661. if (!wsi_client)
  662. {
  663. //#ifdef SystemLogMessage
  664. DEBUG_ERROR("lws_client_connect_via_info NG");
  665. //#endif
  666. //result = FAIL;
  667. goto end;
  668. }
  669. end:
  670. pthread_exit(NULL/*(void *) fname*/);
  671. //return result;
  672. }
  673. //void createq();
  674. int showfront(char *uuid, char *data);
  675. int addq(char *uuid, char *data) ;
  676. int delq();
  677. int sentqueue();
  678. void CheckTransactionPacket(char *uuid);
  679. int queue_operation(int type, char *frontUUID, char *frontData);
  680. int showfront(char *uuid, char *data) {
  681. FILE *fp;
  682. int result = FALSE; // 1: TRUE 0:FALSE
  683. char str[1200]={0};
  684. char sstr[50]={ 0 };//sstr[200]={ 0 };
  685. int c = 0;
  686. char *loc;
  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("Can't Create File TransactionRelatedQueue \n");
  713. return FALSE;
  714. }
  715. else
  716. {
  717. fclose(log);
  718. }
  719. }
  720. /* opening file for reading */
  721. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  722. if(fp == NULL) {
  723. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  724. return FALSE;
  725. }
  726. if( fgets (str, 1200, fp)!=NULL ) {
  727. /* writing content to stdout */
  728. //DEBUG_INFO("str=%s",str);
  729. if ((str[0] == '\n')||(strcmp(str,"")==0))
  730. {
  731. DEBUG_INFO("It is a blank line");
  732. fclose(fp);
  733. memset(rmFileCmd, 0, sizeof rmFileCmd);
  734. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/TransactionRelatedQueue");
  735. system(rmFileCmd);
  736. result = FALSE;
  737. return result;
  738. }
  739. else
  740. {
  741. //puts(str);
  742. //----------------uuid--------------//
  743. loc = strstr(str, "\"");
  744. memset(sstr ,0, sizeof(sstr) );
  745. c = 0;
  746. while (loc[1+c] != '\"')
  747. {
  748. sstr[c] = loc[1+c];
  749. c++;
  750. }
  751. sstr[c] = '\0';
  752. //DEBUG_INFO("\n uuid:%s", sstr);
  753. //DEBUG_INFO("\n data:%s", str);
  754. strcpy(uuid,sstr);
  755. strcpy(data,str);
  756. result = TRUE;
  757. }
  758. }
  759. else
  760. {
  761. //DEBUG_INFO("queue is null\n");
  762. strcpy(uuid,"");
  763. strcpy(data,"");
  764. result = FALSE;
  765. }
  766. fclose(fp);
  767. return result;
  768. }
  769. int addq(char *uuid, char *data) {
  770. FILE *outfile;
  771. char rmFileCmd[100]={0};
  772. struct stat stats;
  773. stat("/Storage/OCPP", &stats);
  774. DEBUG_INFO("addq ");
  775. // Check for directory existence
  776. if (S_ISDIR(stats.st_mode) == 1)
  777. {
  778. //DEBUG_INFO("\n OCPP directory exist \n");
  779. }
  780. else
  781. {
  782. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  783. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  784. system(rmFileCmd);
  785. }
  786. memset(rmFileCmd, 0, sizeof rmFileCmd);
  787. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  788. {
  789. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  790. }
  791. else
  792. {
  793. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  794. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  795. if(log == NULL)
  796. {
  797. //DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  798. return FALSE;
  799. }
  800. else
  801. {
  802. fclose(log);
  803. }
  804. }
  805. // open file for writing
  806. outfile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "a");
  807. DEBUG_INFO("data=%s\n",data);
  808. fputs(data, outfile);
  809. fputs("\n", outfile);
  810. fclose (outfile);
  811. TransactionQueueNum = TransactionQueueNum + 1;
  812. if(OfflineTransaction == 1) // 0: no offline Transaction 1: offline Transaction
  813. {
  814. OfflineTransactionQueueNum = OfflineTransactionQueueNum + 1;
  815. }
  816. DEBUG_INFO("add queue end\n");
  817. return FALSE;
  818. }
  819. int delq() {
  820. char tempfile[] = "/Storage/OCPP/delqtemp.json";
  821. FILE *infile;
  822. FILE *outfile;
  823. int resultRename=0;
  824. char filename[60]={0};
  825. char rmFileCmd[100]={0};
  826. struct stat stats;
  827. stat("/Storage/OCPP", &stats);
  828. DEBUG_INFO("delq()\n");
  829. // Check for directory existence
  830. if (S_ISDIR(stats.st_mode) == 1)
  831. {
  832. //DEBUG_INFO("\n OCPP directory exist \n");
  833. }
  834. else
  835. {
  836. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  837. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  838. system(rmFileCmd);
  839. }
  840. memset(rmFileCmd, 0, sizeof rmFileCmd);
  841. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  842. {
  843. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  844. }
  845. else
  846. {
  847. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  848. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  849. if(log == NULL)
  850. {
  851. //DEBUG_INFO("log is NULL\n");
  852. return 0;
  853. }
  854. else
  855. {
  856. fclose(log);
  857. }
  858. }
  859. // open file for writing
  860. strcpy(filename, "/Storage/OCPP/TransactionRelatedQueue");
  861. infile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "r");
  862. outfile = fopen (tempfile, "w");
  863. /*检测到文件结束标识返回1,否则返回0。*/
  864. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  865. int c;
  866. c = fgetc(infile);
  867. //printf("file c:%d\n",c);
  868. rewind(infile);
  869. if(c == EOF)
  870. {
  871. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  872. fclose(infile);
  873. fclose(outfile);
  874. sprintf(rmFileCmd,"rm -f %s",tempfile);
  875. system(rmFileCmd);
  876. }
  877. else
  878. {
  879. char buf[1200]={0};
  880. int i = 0;
  881. //DEBUG_INFO("Orignal File is not NULL\n");
  882. while (fgets(buf, sizeof(buf), infile) != NULL)
  883. {
  884. //printf("Orignal File get strings \n");
  885. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  886. if(i==0)
  887. {
  888. TransactionQueueNum = TransactionQueueNum - 1;
  889. TransactionQueueInterval = 0;
  890. TransactionMessageResend = 1;
  891. DEBUG_INFO("delete the item\n");
  892. }
  893. if(i != 0)
  894. {
  895. fprintf(outfile,"%s\n", buf);
  896. }
  897. i = i + 1;
  898. }
  899. fclose(infile);
  900. fclose(outfile);
  901. sprintf(rmFileCmd,"rm -f %s",filename);
  902. system(rmFileCmd);
  903. resultRename = rename(tempfile, filename);
  904. if(resultRename == 0)
  905. {
  906. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  907. }
  908. else
  909. {
  910. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  911. }
  912. DEBUG_INFO("delq() end\n");
  913. }
  914. return 0;
  915. }
  916. int showqueue() {
  917. char rmFileCmd[100]={0};
  918. struct stat stats;
  919. stat("/Storage/OCPP", &stats);
  920. // Check for directory existence
  921. if (S_ISDIR(stats.st_mode) == 1)
  922. {
  923. //DEBUG_INFO("\n OCPP directory exist \n");
  924. }
  925. else
  926. {
  927. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  928. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  929. system(rmFileCmd);
  930. }
  931. memset(rmFileCmd, 0, sizeof rmFileCmd);
  932. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  933. {
  934. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  935. }
  936. else
  937. {
  938. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  939. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  940. if(log == NULL)
  941. {
  942. DEBUG_INFO("log is NULL\n");
  943. return FALSE;
  944. }
  945. else
  946. {
  947. fclose(log);
  948. }
  949. }
  950. FILE *fp = fopen("/Storage/OCPP/TransactionRelatedQueue", "r");
  951. char line[1200]={0};
  952. // check if file exist (and you can open it) or not
  953. if (fp == NULL) {
  954. DEBUG_INFO("can open file TransactionRelatedQueue!");
  955. return FALSE;
  956. }
  957. TransactionQueueNum = 0; // the number of packets in queue
  958. while(fgets(line, sizeof line, fp) != NULL) {
  959. //DEBUG_INFO("%s\n", line);
  960. TransactionQueueNum = TransactionQueueNum + 1; //the number of packets in queue
  961. }
  962. fclose(fp);
  963. return TRUE;
  964. }
  965. int sentqueue(){
  966. FILE *fp;
  967. int result = FALSE; // 1: TRUE 0:FALSE
  968. int temptransactionId = 0, gettransactionId = 0;
  969. int tempconnectorId = 0;
  970. //int gunIndex = 0;
  971. char guid[37]={0};
  972. char tempdata[65]={0};
  973. char key_value[65]={0};
  974. int IsStopTransaction = FALSE;
  975. //int IsconnectorIdNULL = FALSE;
  976. //int IsIdtagNULL = FALSE;
  977. char str[1200]={0};
  978. char strcomposite[1200]={0};
  979. char rmFileCmd[100]={0};
  980. struct stat stats;
  981. char sstr[28]={0};
  982. unsigned char IdtagStr[20]={0};
  983. unsigned char timestampStr[30]={0};
  984. int tempmeterStart = 0;
  985. int tempreservationId = 0;
  986. int c = 0;
  987. char *loc;
  988. DEBUG_INFO("sentqueue\n");
  989. stat("/Storage/OCPP", &stats);
  990. // Check for directory existence
  991. if (S_ISDIR(stats.st_mode) == 1)
  992. {
  993. //DEBUG_INFO("\n OCPP directory exist \n");
  994. }
  995. else
  996. {
  997. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  998. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  999. system(rmFileCmd);
  1000. }
  1001. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1002. /* opening file for reading */
  1003. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  1004. if(fp == NULL) {
  1005. DEBUG_INFO("Error opening file");
  1006. return FALSE;
  1007. }
  1008. if( fgets (str, 1200, fp)!=NULL ) {
  1009. //---- writing content to stdout ---//
  1010. //*********************StopTransaction***************************/
  1011. loc = strstr(str, "StopTransaction");
  1012. c = 0;
  1013. memset(sstr ,0, sizeof(sstr) );
  1014. if(loc != NULL)
  1015. {
  1016. IsStopTransaction = TRUE;
  1017. }
  1018. //*********************Start:connectorId***************************/
  1019. loc = strstr(str, "connectorId");
  1020. c = 0;
  1021. memset(sstr ,0, sizeof(sstr) );
  1022. if(loc != NULL)
  1023. {
  1024. while (loc[strlen("connectorId")+2+c] != ',')
  1025. {
  1026. sstr[c] = loc[strlen("connectorId")+2+c];
  1027. c++;
  1028. }
  1029. sstr[c] = '\0';
  1030. tempconnectorId = atoi(sstr);
  1031. }
  1032. // else
  1033. // {
  1034. // IsconnectorIdNULL = TRUE;
  1035. // }
  1036. //*********************End:connectorId***************************/
  1037. //*********************Start:idTag***************************/
  1038. loc = strstr(str, "idTag");
  1039. c = 0;
  1040. memset(sstr ,0, sizeof(sstr) );
  1041. if(loc != NULL)
  1042. {
  1043. while (loc[3+strlen("idTag")+c] != '\"')
  1044. {
  1045. sstr[c] = loc[3+strlen("idTag")+c];
  1046. c++;
  1047. }
  1048. sstr[c] = '\0';
  1049. strcpy((char*)IdtagStr, sstr);
  1050. }
  1051. // else
  1052. // {
  1053. // IsIdtagNULL = TRUE;
  1054. // }
  1055. //*********************End:idTag***************************/
  1056. //*********************Start: StartTransaction***************************/
  1057. loc = strstr(str, "StartTransaction");
  1058. c = 0;
  1059. memset(sstr ,0, sizeof(sstr) );
  1060. if(loc != NULL)
  1061. {
  1062. // [2,0200000000000000000000000001584415776,StartTransaction,{connectorId:1,idTag:123,meterStart:100,reservationId:0,timestamp:2020-03-17T03:29:36Z}]
  1063. //DEBUG_INFO("\n sent queue StartTransaction\n");
  1064. if(tempconnectorId > 0)
  1065. {
  1066. sprintf(tempdata, "StartTransaction,%d", (tempconnectorId-1));
  1067. }
  1068. //GUID
  1069. memset(sstr ,0, sizeof(sstr) );
  1070. c=0;
  1071. while (str[4+c] != '\"')
  1072. {
  1073. sstr[c] = str[4+c];
  1074. c++;
  1075. }
  1076. sstr[c] = '\0';
  1077. strcpy(guid, sstr);
  1078. //Idtag
  1079. loc = strstr(str, "idTag");
  1080. memset(sstr ,0, sizeof(sstr) );
  1081. c=0;
  1082. while (loc[3+strlen("idTag")+c] != '\"')
  1083. {
  1084. sstr[c] = loc[3+strlen("idTag")+c];
  1085. c++;
  1086. }
  1087. sstr[c] = '\0';
  1088. strcpy((char*)IdtagStr, sstr);
  1089. //meterStart
  1090. loc = strstr(str, "meterStart");
  1091. c = 0;
  1092. memset(sstr ,0, sizeof(sstr) );
  1093. if(loc != NULL)
  1094. {
  1095. while (loc[strlen("meterStart")+2+c] != ',')
  1096. {
  1097. sstr[c] = loc[strlen("meterStart")+2+c];
  1098. c++;
  1099. }
  1100. sstr[c] = '\0';
  1101. tempmeterStart = atoi(sstr);
  1102. }
  1103. //reservationId
  1104. loc = strstr(str, "reservationId");
  1105. c = 0;
  1106. memset(sstr ,0, sizeof(sstr) );
  1107. if(loc != NULL)
  1108. {
  1109. while (loc[strlen("reservationId")+2+c] != ',')
  1110. {
  1111. sstr[c] = loc[strlen("reservationId")+2+c];
  1112. c++;
  1113. }
  1114. sstr[c] = '\0';
  1115. tempreservationId = atoi(sstr);
  1116. }
  1117. //timestamp
  1118. loc = strstr(str, "timestamp");
  1119. memset(sstr ,0, sizeof(sstr) );
  1120. c=0;
  1121. while (loc[3+strlen("timestamp")+c] != '\"')
  1122. {
  1123. sstr[c] = loc[3+strlen("timestamp")+c];
  1124. c++;
  1125. }
  1126. sstr[c] = '\0';
  1127. strcpy((char*)timestampStr, sstr);
  1128. if(hashmap_operation(1, guid, key_value) == TRUE)
  1129. {
  1130. //DEBUG_INFO("\n 1. sent queue guid=%s\n",guid);
  1131. }
  1132. else
  1133. {
  1134. hashmap_operation(0, guid, tempdata);
  1135. FillStartTransaction(tempconnectorId, IdtagStr, tempmeterStart, tempreservationId, timestampStr);
  1136. //DEBUG_INFO("\n 2. sent queue guid=%s\n",guid);
  1137. }
  1138. }
  1139. //*********************End: StartTransaction***************************/
  1140. //****************transactionId********************/
  1141. c=0;
  1142. loc = strstr(str, "transactionId");
  1143. memset(sstr ,0, sizeof(sstr) );
  1144. if(loc != NULL)
  1145. {
  1146. while ((loc[strlen("transactionId")+2+c] != '}') && (loc[strlen("transactionId")+2+c] != ','))
  1147. {
  1148. sstr[c] = loc[strlen("transactionId")+2+c];
  1149. c++;
  1150. }
  1151. sstr[c] = '\0';
  1152. temptransactionId = atoi(sstr);
  1153. gettransactionId = GetTransactionId(tempconnectorId, IdtagStr);
  1154. if((gettransactionId != 0)&&(temptransactionId != gettransactionId))
  1155. {
  1156. strncpy(strcomposite,str, (loc-str)+2+strlen("transactionId"));
  1157. sprintf(strcomposite+((loc-str)+2+strlen("transactionId")),"%d",gettransactionId);
  1158. strcat(strcomposite, loc+strlen("transactionId")+2+c);
  1159. LWS_Send(strcomposite);
  1160. }
  1161. else
  1162. {
  1163. LWS_Send(str);
  1164. }
  1165. if((IsStopTransaction == TRUE)&&(gettransactionId != 0))
  1166. {
  1167. SetTransactionIdZero(gettransactionId);
  1168. }
  1169. }
  1170. else
  1171. {
  1172. LWS_Send(str);
  1173. }
  1174. result = TRUE;
  1175. }
  1176. else
  1177. {
  1178. result = FALSE;
  1179. }
  1180. fclose(fp);
  1181. return result;
  1182. }
  1183. //
  1184. void* processTransactionQueue(void* data) {
  1185. char frontUUID[100] ={0};
  1186. char frontData[1200/*1024*4*/] ={0};
  1187. int queueNotEmpty = FALSE;
  1188. while(1)
  1189. {
  1190. if(FirstHeartBeatResponse() == 1)
  1191. {
  1192. memset(frontUUID, 0, sizeof(frontUUID));
  1193. memset(frontData, 0, sizeof(frontData));
  1194. queueNotEmpty = FALSE;
  1195. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1196. if((queueNotEmpty == TRUE) && (GetOcppConnStatus() == 1)) //OcppConnStatus 0: disconnected, 1: connected
  1197. {
  1198. //DEBUG_INFO("OfflineTransaction=%d\n",OfflineTransaction);
  1199. //DEBUG_INFO("OfflineTransactionQueueNum=%d\n",OfflineTransactionQueueNum);
  1200. if((OfflineTransaction == 1) && (OfflineTransactionQueueNum != 0)) //OfflineTransaction 0: no offline Transaction 1: offline Transaction
  1201. {
  1202. TransactionQueueInterval = 10;//10;//2;
  1203. sendbuffer = 1; // 0: no packets to send 1: send the top packet in queue
  1204. OfflineTransactionQueueNum = OfflineTransactionQueueNum - 1;
  1205. if(OfflineTransactionQueueNum == 0)
  1206. {
  1207. OfflineTransaction = 0;
  1208. }
  1209. //DEBUG_INFO(" Offline Transaction , online sent queue .... \n");
  1210. sleep(TransactionQueueInterval);
  1211. }
  1212. else
  1213. {
  1214. //DEBUG_INFO(" online sent queue .... \n");
  1215. //OfflineTransaction = 0;
  1216. if(TransactionMessageResend <= TransactionMessageAttemptsGet()) //
  1217. {
  1218. DEBUG_INFO("processTransactionQueue queue is not empty!\n");
  1219. TransactionQueueInterval= TransactionMessageRetryIntervalGet()* TransactionMessageResend;
  1220. DEBUG_INFO("TransactionQueueInterval =%d\n",TransactionQueueInterval);
  1221. sleep(TransactionQueueInterval);
  1222. sendbuffer = 1;
  1223. TransactionMessageResend = TransactionMessageResend + 1;
  1224. DEBUG_INFO("After ADD,TransactionMessageResend=%d\n",TransactionMessageResend);
  1225. //sleep(TransactionQueueInterval);
  1226. }
  1227. else
  1228. {
  1229. queue_operation(2,"",""); //// delete item
  1230. TransactionQueueInterval = 0;
  1231. TransactionMessageResend = 1;
  1232. sleep(TransactionQueueInterval);
  1233. }
  1234. }
  1235. }
  1236. else
  1237. {
  1238. TransactionQueueInterval = 0;//10;
  1239. sleep(TransactionQueueInterval);
  1240. }
  1241. }
  1242. if(GetOcppConnStatus() == 0)
  1243. {
  1244. //DEBUG_INFO(" Offline .... \n");
  1245. if(queueNotEmpty == TRUE)
  1246. {
  1247. OfflineTransaction = 1; // 0: no offline Transaction 1: offline Transaction
  1248. //DEBUG_INFO(" Offline Transaction .... \n");
  1249. }
  1250. }
  1251. usleep(5000);
  1252. }
  1253. pthread_exit(NULL); //
  1254. return 0;
  1255. }
  1256. void CheckTransactionPacket(char *uuid)
  1257. {
  1258. char frontUUID[100]={0};
  1259. char frontData[1200]={0};
  1260. int queueNotEmpty = FALSE;
  1261. int cmpResult = 0;
  1262. //queue_operation(0,"","");//showqueue(); ---> remove temporally
  1263. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1264. if(queueNotEmpty == TRUE)
  1265. {
  1266. cmpResult = strcmp(frontUUID, uuid);
  1267. if (cmpResult == 0)
  1268. {
  1269. DEBUG_INFO("TransactionPacket Compare All right!\n");
  1270. //DEBUG_INFO("frontUUID=%s\n",frontUUID);
  1271. //DEBUG_INFO("uuid=%s\n",uuid);
  1272. queue_operation(2,"","");//delq(); ---> remove temporally
  1273. TransactionQueueInterval = 0;
  1274. TransactionMessageResend = 1;
  1275. }
  1276. }
  1277. }
  1278. //---- type: 0 (showqueue ); type: 1(showfront); type: 2(delq) type: 3 (sentqueue) type: 4 (addq) type: 5(store queue to /Storage/OCPP/ ) ---//
  1279. int queue_operation(int type, char *frontUUID, char *frontData)
  1280. {
  1281. int result=0;
  1282. while(1)
  1283. {
  1284. if (!IsUsing )
  1285. {
  1286. IsUsing = TRUE;
  1287. //pthread_mutex_unlock(&lock_sentData);
  1288. //pthread_mutex_lock(&lock_sentData);
  1289. if(type == 0) // show items in queue
  1290. {
  1291. result = showqueue();
  1292. }
  1293. else if(type == 1) // show first item
  1294. {
  1295. result = showfront(frontUUID, frontData);
  1296. }
  1297. else if(type == 2) // delete item
  1298. {
  1299. result = delq();
  1300. }
  1301. else if(type == 3) // sent items in queue
  1302. {
  1303. result = sentqueue();
  1304. }
  1305. else if(type == 4) // add items to the queue
  1306. {
  1307. result = addq(frontUUID, frontData);
  1308. }
  1309. //pthread_mutex_unlock(&lock_sentData);
  1310. IsUsing = FALSE;
  1311. break;
  1312. }
  1313. }
  1314. return result;
  1315. }
  1316. char * strchr(const char *p, int ch)
  1317. {
  1318. char c;
  1319. c = ch;
  1320. for (;; ++p) {
  1321. if (*p == c)
  1322. return ((char *)p);
  1323. if (*p == '\0')
  1324. return (NULL);
  1325. }
  1326. /* NOTREACHED */
  1327. return NULL;
  1328. }
  1329. int removeMessageSentFile(void)
  1330. {
  1331. char rmFileCmd[100]={0};
  1332. struct stat stats;
  1333. //
  1334. stat("/Storage/OCPP", &stats);
  1335. // Check for directory existence
  1336. if (S_ISDIR(stats.st_mode) == 1)
  1337. {
  1338. //DEBUG_INFO("\n OCPP directory exist \n");
  1339. }
  1340. else
  1341. {
  1342. DEBUG_INFO("\n directory not exist, create dir \n");
  1343. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  1344. system(rmFileCmd);
  1345. }
  1346. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1347. if((access("/Storage/OCPP/MessageSent",F_OK))!=-1)
  1348. {
  1349. DEBUG_INFO("MessageSent file exist.\n");
  1350. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/MessageSent");
  1351. system(rmFileCmd);
  1352. }
  1353. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1354. return 0;
  1355. }
  1356. void work(char s[]) //删除首尾空格
  1357. {int i,j;
  1358. for(i=0;s[i]==' ';i++); //找到开头第一个非空格
  1359. for(j=0;s[i];)s[j++]=s[i++]; //删除开头空格
  1360. for(i--;s[i]==' ';i--)s[i]='\0'; //删除末尾空格
  1361. }
  1362. static int changeChageWebSocketPingInterval = FALSE;
  1363. void ChageWebSocketPingInterval(int WebSocketPingInterval)
  1364. {
  1365. changeChageWebSocketPingInterval = TRUE;
  1366. }
  1367. #define SystemLogMessage
  1368. //================================================
  1369. // Main process
  1370. //================================================
  1371. int main(void)
  1372. {
  1373. char rmFileCmd[100]={0};
  1374. struct stat stats;
  1375. pthread_t t;
  1376. //pthread_t pid;
  1377. #ifdef SystemLogMessage
  1378. DEBUG_INFO("Initialization...\n");
  1379. #endif
  1380. if(ProcessShareMemory()== FAIL)
  1381. {
  1382. return FAIL;
  1383. }
  1384. //Create OCPP dir
  1385. stat("/Storage/OCPP", &stats);
  1386. // Check for directory existence
  1387. if (S_ISDIR(stats.st_mode) == 1)
  1388. {
  1389. //DEBUG_INFO("\n OCPP directory exist \n");
  1390. }
  1391. else
  1392. {
  1393. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  1394. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  1395. system(rmFileCmd);
  1396. }
  1397. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1398. //Create Process: Resend Transaction
  1399. pthread_create(&t, NULL, processTransactionQueue, NULL); //
  1400. sqlite3_config(SQLITE_CONFIG_URI,1);
  1401. if(sqlite3_open("file:/Storage/OCPP/charger.db", &db))
  1402. {
  1403. #ifdef Debug
  1404. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1405. #endif
  1406. sqlite3_close( db );
  1407. exit(0);
  1408. }
  1409. else
  1410. {
  1411. #ifdef Debug
  1412. DEBUG_INFO( "Opened database successfully\n");
  1413. #endif
  1414. }
  1415. //Create Table log buffer
  1416. int rc =sqlite3_exec(db, createsql, 0, 0, &errMsg);
  1417. if (SQLITE_OK != rc)
  1418. {
  1419. #ifdef Debug
  1420. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1421. #endif
  1422. return 0;
  1423. }
  1424. else
  1425. {
  1426. #ifdef Debug
  1427. DEBUG_INFO( "Opened log buffer table successfully\n");
  1428. #endif
  1429. }
  1430. // Create Table OcppAuthCache
  1431. rc =sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg);
  1432. if (SQLITE_OK != rc)
  1433. {
  1434. #ifdef Debug
  1435. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1436. #endif
  1437. return 0;
  1438. }
  1439. else
  1440. {
  1441. #ifdef Debug
  1442. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1443. #endif
  1444. }
  1445. // Create Table OcppAuthLocal
  1446. rc =sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg);
  1447. if (SQLITE_OK != rc)
  1448. {
  1449. #ifdef Debug
  1450. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1451. #endif
  1452. return 0;
  1453. }
  1454. else
  1455. {
  1456. #ifdef Debug
  1457. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1458. #endif
  1459. }
  1460. initialConfigurationTable();
  1461. removeMessageSentFile();
  1462. //OCPP_get_TableAuthlocalAllData();
  1463. for(;;)
  1464. {
  1465. while(ConnectionEstablished==0) // Check InternetConn 0: disconnected, 1: connected
  1466. {
  1467. SetOcppConnStatus(FALSE);
  1468. SetServerSign(FALSE);
  1469. InitialSystemValue();
  1470. if((time((time_t*)NULL)-startTime.connect)>=60)
  1471. {
  1472. #ifdef Debug
  1473. DEBUG_INFO("Execute ConnectWsServer\n");
  1474. #endif
  1475. //ConnectWsServer();
  1476. pthread_create(&pid, NULL, ConnectWsServer, NULL);
  1477. startTime.connect=time((time_t*)NULL);
  1478. }
  1479. // Check System Value, process offline Transaction
  1480. CheckSystemValue();
  1481. sleep(5);
  1482. lws_service(context, 10000);//timeout_ms
  1483. //lws_service(context, 100);//timeout_ms
  1484. }
  1485. if(((GetBootNotificationInterval() != 0 && ((time((time_t*)NULL)-startTime.bootNotification)>= GetBootNotificationInterval()) ) || ((time((time_t*)NULL)-startTime.bootNotification)>=defaultWaitingTime) ) && (GetServerSign() == FALSE))
  1486. {
  1487. //hashmapForMessageNew();
  1488. sendBootNotificationRequest();
  1489. startTime.bootNotification=time((time_t*)NULL);
  1490. }
  1491. if(GetServerSign() == TRUE)
  1492. {
  1493. if(sendbuffer == 1)
  1494. {
  1495. queue_operation(3, "", "");//sentqueue()
  1496. sendbuffer = 0;
  1497. }
  1498. SetOcppConnStatus(TRUE);
  1499. // Check System Value
  1500. CheckSystemValue();
  1501. if(GetHeartBeatWithNOResponse() >= 3)
  1502. {
  1503. lws_context_destroy(context);
  1504. ConnectionEstablished=0;
  1505. context = NULL;
  1506. SetHeartBeatWithNOResponse();
  1507. }
  1508. if((changeChageWebSocketPingInterval == TRUE) || (GetInternetConn() == 0)) // Check InternetConn 0: disconnected, 1: connected
  1509. {
  1510. DEBUG_INFO("GetInternetConn()=%d\n",GetInternetConn());
  1511. changeChageWebSocketPingInterval = FALSE;
  1512. lws_context_destroy(context);
  1513. ConnectionEstablished=0;
  1514. context = NULL;
  1515. }
  1516. }
  1517. lws_service(context, 100);//timeout_ms
  1518. }
  1519. pthread_join(t, NULL); //
  1520. //hashmapForMessageFree();
  1521. return FAIL;
  1522. }