Module_OcppBackend.c 43 KB

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