Module_OcppBackend.c 42 KB

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