Module_OcppBackend.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  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. void* ConnectWsServer(void* data) //int ConnectWsServer()
  550. {
  551. pthread_detach(pthread_self());
  552. int result = PASS;
  553. struct lws_context_creation_info ContextInfo;
  554. struct lws_client_connect_info ConnInfo;
  555. int use_ssl=0;
  556. //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);
  557. if(context!=NULL)
  558. lws_context_destroy(context);
  559. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  560. if((GetOcppServerURL()==0) || (GetOcppPort() == 0) || (GetOcppPath()==0) )
  561. {
  562. result = FAIL;
  563. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  564. //return result;
  565. }
  566. if((strcmp(OcppProtocol,"ws")==0)&&(strlen(OcppProtocol)== 2))
  567. {
  568. printf("ws!!! \n");
  569. use_ssl=0;
  570. }
  571. else if((strcmp(OcppProtocol,"wss")==0)&&(strlen(OcppProtocol)== 3))
  572. {
  573. printf("wss!!! \n");
  574. use_ssl=1;
  575. }
  576. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  577. ContextInfo.iface = NULL;
  578. ContextInfo.ssl_private_key_password = NULL;
  579. ContextInfo.ssl_cert_filepath = NULL;//"./ssl_key/client_cert.pem";
  580. ContextInfo.ssl_private_key_filepath = NULL;//"./ssl_key/client_key.pem";
  581. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";//"./cacert.pem";
  582. ContextInfo.ssl_cipher_list = NULL; //use default one
  583. ContextInfo.gid = -1;
  584. ContextInfo.uid = -1;
  585. if(use_ssl)
  586. {
  587. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT ;
  588. }
  589. ContextInfo.protocols = protocols;
  590. ContextInfo.timeout_secs = GetWebSocketPingInterval();//WebSocketPingInterval;//30;//9999;//30;
  591. //if(ping pong enabled)
  592. ContextInfo.ws_ping_pong_interval = GetWebSocketPingInterval();//WebSocketPingInterval;//30;//0 for none, else interval in seconds
  593. context = lws_create_context(&ContextInfo);
  594. if (context == NULL)
  595. {
  596. #ifdef SystemLogMessage
  597. DEBUG_ERROR("lws_create_context NG");
  598. #endif
  599. result = FAIL;
  600. }
  601. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  602. // fill up below information
  603. ConnInfo.context = context;
  604. ConnInfo.address=(const char *)OcppHost;
  605. printf("\n ConnInfo.address=%s\n",ConnInfo.address);
  606. ConnInfo.port = GetOcppPort();
  607. printf("\n ConnInfo.port=%d\n",ConnInfo.port);
  608. ConnInfo.path=(const char *)OcppPath;
  609. printf("\n ConnInfo.path=%s\n",ConnInfo.path);
  610. ConnInfo.host=ConnInfo.address;//lws_canonical_hostname(context);
  611. ConnInfo.origin="origin";
  612. ConnInfo.protocol = protocols[1].name;
  613. ConnInfo.ietf_version_or_minus_one = -1;
  614. if(use_ssl)
  615. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;;
  616. wsi_client = lws_client_connect_via_info(&ConnInfo);
  617. if (!wsi_client)
  618. {
  619. #ifdef SystemLogMessage
  620. DEBUG_ERROR("lws_client_connect_via_info NG");
  621. #endif
  622. result = FAIL;
  623. }
  624. pthread_exit(NULL/*(void *) fname*/);
  625. //return result;
  626. }
  627. //void createq();
  628. int showfront(char *uuid, char *data);
  629. int addq(char *uuid, char *data) ;
  630. int delq();
  631. int sentqueue();
  632. void CheckTransactionPacket(char *uuid);
  633. int queue_operation(int type, char *frontUUID, char *frontData);
  634. int showfront(char *uuid, char *data) {
  635. FILE *fp;
  636. int result = FALSE; // 1: TRUE 0:FALSE
  637. char str[1200]={0};
  638. char sstr[50]={ 0 };//sstr[200]={ 0 };
  639. int c = 0;
  640. char *loc;
  641. char rmFileCmd[100]={0};
  642. struct stat stats;
  643. stat("/Storage/OCPP", &stats);
  644. // Check for directory existence
  645. if (S_ISDIR(stats.st_mode) == 1)
  646. {
  647. //DEBUG_INFO("\n OCPP directory exist \n");
  648. }
  649. else
  650. {
  651. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  652. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  653. system(rmFileCmd);
  654. }
  655. memset(rmFileCmd, 0, sizeof rmFileCmd);
  656. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  657. {
  658. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  659. }
  660. else
  661. {
  662. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  663. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  664. if(log == NULL)
  665. {
  666. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  667. return 0;
  668. }
  669. else
  670. {
  671. fclose(log);
  672. }
  673. }
  674. /* opening file for reading */
  675. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  676. if(fp == NULL) {
  677. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  678. return FALSE;
  679. }
  680. #if 0
  681. if(fgetc(fp)==EOF)
  682. {
  683. //DEBUG_INFO("It is end of file");
  684. fclose(fp);
  685. memset(rmFileCmd, 0, sizeof rmFileCmd);
  686. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  687. {
  688. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/TransactionRelatedQueue");
  689. system(rmFileCmd);
  690. }
  691. result = FALSE;
  692. return result;
  693. }
  694. #endif
  695. if( fgets (str, 1200, fp)!=NULL ) {
  696. /* writing content to stdout */
  697. //DEBUG_INFO("str=%s",str);
  698. if ((str[0] == '\n')||(strcmp(str,"")==0))
  699. {
  700. DEBUG_INFO("It is a blank line");
  701. fclose(fp);
  702. memset(rmFileCmd, 0, sizeof rmFileCmd);
  703. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/TransactionRelatedQueue");
  704. system(rmFileCmd);
  705. result = FALSE;
  706. return result;
  707. }
  708. else
  709. {
  710. //puts(str);
  711. /*********************uuid***************/
  712. loc = strstr(str, "\"");
  713. memset(sstr ,0, sizeof(sstr) );
  714. c = 0;
  715. while (loc[1+c] != '\"')
  716. {
  717. sstr[c] = loc[1+c];
  718. c++;
  719. }
  720. sstr[c] = '\0';
  721. //DEBUG_INFO("\n uuid:%s", sstr);
  722. //DEBUG_INFO("\n data:%s", str);
  723. strcpy(uuid,sstr);
  724. strcpy(data,str);
  725. result = TRUE;
  726. }
  727. }
  728. else
  729. {
  730. //DEBUG_INFO("queue is null\n");
  731. strcpy(uuid,"");
  732. strcpy(data,"");
  733. result = FALSE;
  734. }
  735. fclose(fp);
  736. return result;
  737. }
  738. int addq(char *uuid, char *data) {
  739. FILE *outfile;
  740. char rmFileCmd[100]={0};
  741. struct stat stats;
  742. stat("/Storage/OCPP", &stats);
  743. DEBUG_INFO("addq\n");
  744. // Check for directory existence
  745. if (S_ISDIR(stats.st_mode) == 1)
  746. {
  747. DEBUG_INFO("\n OCPP directory exist \n");
  748. }
  749. else
  750. {
  751. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  752. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  753. system(rmFileCmd);
  754. }
  755. memset(rmFileCmd, 0, sizeof rmFileCmd);
  756. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  757. {
  758. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  759. }
  760. else
  761. {
  762. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  763. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  764. if(log == NULL)
  765. {
  766. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  767. return 0;
  768. }
  769. else
  770. {
  771. fclose(log);
  772. }
  773. }
  774. // open file for writing
  775. outfile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "a");
  776. //DEBUG_INFO("data=%s\n",data);
  777. fputs(data, outfile);
  778. fputs("\n", outfile);
  779. fclose (outfile);
  780. TransactionQueueNum = TransactionQueueNum + 1;
  781. return 0;
  782. }
  783. int delq() {
  784. char tempfile[] = "/Storage/OCPP/temp.json";
  785. FILE *infile;
  786. FILE *outfile;
  787. int resultRename=0;
  788. char filename[60]={0};
  789. char rmFileCmd[100]={0};
  790. struct stat stats;
  791. stat("/Storage/OCPP", &stats);
  792. DEBUG_INFO("delq()\n");
  793. // Check for directory existence
  794. if (S_ISDIR(stats.st_mode) == 1)
  795. {
  796. DEBUG_INFO("\n OCPP directory exist \n");
  797. }
  798. else
  799. {
  800. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  801. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  802. system(rmFileCmd);
  803. }
  804. memset(rmFileCmd, 0, sizeof rmFileCmd);
  805. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  806. {
  807. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  808. }
  809. else
  810. {
  811. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  812. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  813. if(log == NULL)
  814. {
  815. DEBUG_INFO("log is NULL\n");
  816. return 0;
  817. }
  818. else
  819. {
  820. fclose(log);
  821. }
  822. }
  823. // open file for writing
  824. strcpy(filename, "/Storage/OCPP/TransactionRelatedQueue");
  825. infile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "r");
  826. outfile = fopen (tempfile, "w");
  827. /*检测到文件结束标识返回1,否则返回0。*/
  828. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  829. int c;
  830. c = fgetc(infile);
  831. //printf("file c:%d\n",c);
  832. rewind(infile);
  833. if(c == EOF)
  834. {
  835. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  836. fclose(infile);
  837. fclose(outfile);
  838. sprintf(rmFileCmd,"rm -f %s",tempfile);
  839. system(rmFileCmd);
  840. }
  841. else
  842. {
  843. char buf[1200]={0};
  844. int i = 0;
  845. //DEBUG_INFO("Orignal File is not NULL\n");
  846. while (fgets(buf, sizeof(buf), infile) != NULL)
  847. {
  848. //printf("Orignal File get strings \n");
  849. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  850. if(i==0)
  851. {
  852. TransactionQueueNum = TransactionQueueNum - 1;
  853. TransactionQueueInterval = 0;
  854. TransactionMessageResend = 1;
  855. }
  856. if(i != 0)
  857. fprintf(outfile,"%s\n", buf);
  858. i = i + 1;
  859. }
  860. fclose(infile);
  861. fclose(outfile);
  862. sprintf(rmFileCmd,"rm -f %s",filename);
  863. system(rmFileCmd);
  864. resultRename = rename(tempfile, filename);
  865. if(resultRename == 0)
  866. {
  867. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  868. }
  869. else
  870. {
  871. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  872. }
  873. }
  874. return 0;
  875. }
  876. int showqueue() {
  877. char rmFileCmd[100]={0};
  878. struct stat stats;
  879. stat("/Storage/OCPP", &stats);
  880. // Check for directory existence
  881. if (S_ISDIR(stats.st_mode) == 1)
  882. {
  883. //DEBUG_INFO("\n OCPP directory exist \n");
  884. }
  885. else
  886. {
  887. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  888. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  889. system(rmFileCmd);
  890. }
  891. memset(rmFileCmd, 0, sizeof rmFileCmd);
  892. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  893. {
  894. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  895. }
  896. else
  897. {
  898. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  899. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  900. if(log == NULL)
  901. {
  902. DEBUG_INFO("log is NULL\n");
  903. return 0;
  904. }
  905. else
  906. {
  907. fclose(log);
  908. }
  909. }
  910. FILE *fp = fopen("/Storage/OCPP/TransactionRelatedQueue", "r");
  911. char line[1200]={0};
  912. // check if file exist (and you can open it) or not
  913. if (fp == NULL) {
  914. DEBUG_INFO("can open file TransactionRelatedQueue!");
  915. return 0;
  916. }
  917. while(fgets(line, sizeof line, fp) != NULL) {
  918. DEBUG_INFO("%s\n", line);
  919. }
  920. fclose(fp);
  921. return 0;
  922. }
  923. int sentqueue(){
  924. FILE *fp;
  925. int result = FALSE; // 1: TRUE 0:FALSE
  926. int temptransactionId = 0, gettransactionId = 0;
  927. int tempconnectorId = 0;
  928. //int gunIndex = 0;
  929. char guid[37]={0};
  930. char tempdata[65]={0};
  931. char key_value[65]={0};
  932. int IsStopTransaction = FALSE;
  933. //int IsconnectorIdNULL = FALSE;
  934. //int IsIdtagNULL = FALSE;
  935. char str[1200]={0};
  936. char strcomposite[1200]={0};
  937. char rmFileCmd[100]={0};
  938. struct stat stats;
  939. char sstr[28]={0};
  940. unsigned char IdtagStr[20]={0};
  941. unsigned char timestampStr[30]={0};
  942. int tempmeterStart = 0;
  943. int tempreservationId = 0;
  944. int c = 0;
  945. char *loc;
  946. DEBUG_INFO("sentqueue\n");
  947. stat("/Storage/OCPP", &stats);
  948. // Check for directory existence
  949. if (S_ISDIR(stats.st_mode) == 1)
  950. {
  951. //DEBUG_INFO("\n OCPP directory exist \n");
  952. }
  953. else
  954. {
  955. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  956. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  957. system(rmFileCmd);
  958. }
  959. memset(rmFileCmd, 0, sizeof rmFileCmd);
  960. /* opening file for reading */
  961. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  962. if(fp == NULL) {
  963. DEBUG_INFO("Error opening file");
  964. return FALSE;
  965. }
  966. if( fgets (str, 1200, fp)!=NULL ) {
  967. /* writing content to stdout */
  968. //*********************StopTransaction***************************/
  969. loc = strstr(str, "StopTransaction");
  970. c = 0;
  971. memset(sstr ,0, sizeof(sstr) );
  972. if(loc != NULL)
  973. {
  974. IsStopTransaction = TRUE;
  975. }
  976. //*********************Start:connectorId***************************/
  977. loc = strstr(str, "connectorId");
  978. c = 0;
  979. memset(sstr ,0, sizeof(sstr) );
  980. if(loc != NULL)
  981. {
  982. while (loc[strlen("connectorId")+2+c] != ',')
  983. {
  984. sstr[c] = loc[strlen("connectorId")+2+c];
  985. c++;
  986. }
  987. sstr[c] = '\0';
  988. tempconnectorId = atoi(sstr);
  989. }
  990. // else
  991. // {
  992. // IsconnectorIdNULL = TRUE;
  993. // }
  994. //*********************End:connectorId***************************/
  995. //*********************Start:idTag***************************/
  996. loc = strstr(str, "idTag");
  997. c = 0;
  998. memset(sstr ,0, sizeof(sstr) );
  999. if(loc != NULL)
  1000. {
  1001. while (loc[3+strlen("idTag")+c] != '\"')
  1002. {
  1003. sstr[c] = loc[3+strlen("idTag")+c];
  1004. c++;
  1005. }
  1006. sstr[c] = '\0';
  1007. strcpy((char*)IdtagStr, sstr);
  1008. }
  1009. // else
  1010. // {
  1011. // IsIdtagNULL = TRUE;
  1012. // }
  1013. //*********************End:idTag***************************/
  1014. //*********************Start: StartTransaction***************************/
  1015. loc = strstr(str, "StartTransaction");
  1016. c = 0;
  1017. memset(sstr ,0, sizeof(sstr) );
  1018. if(loc != NULL)
  1019. {
  1020. // [2,0200000000000000000000000001584415776,StartTransaction,{connectorId:1,idTag:123,meterStart:100,reservationId:0,timestamp:2020-03-17T03:29:36Z}]
  1021. //DEBUG_INFO("\n sent queue StartTransaction\n");
  1022. if(tempconnectorId > 0)
  1023. {
  1024. sprintf(tempdata, "StartTransaction,%d", (tempconnectorId-1));
  1025. }
  1026. //else if(tempconnectorId == 0)
  1027. //{
  1028. // sprintf(tempdata, "StartTransaction,%d", 0);
  1029. //}
  1030. //GUID
  1031. memset(sstr ,0, sizeof(sstr) );
  1032. c=0;
  1033. while (str[4+c] != '\"')
  1034. {
  1035. sstr[c] = str[4+c];
  1036. c++;
  1037. }
  1038. sstr[c] = '\0';
  1039. strcpy(guid, sstr);
  1040. //Idtag
  1041. loc = strstr(str, "idTag");
  1042. memset(sstr ,0, sizeof(sstr) );
  1043. c=0;
  1044. while (loc[3+strlen("idTag")+c] != '\"')
  1045. {
  1046. sstr[c] = loc[3+strlen("idTag")+c];
  1047. c++;
  1048. }
  1049. sstr[c] = '\0';
  1050. strcpy((char*)IdtagStr, sstr);
  1051. //meterStart
  1052. loc = strstr(str, "meterStart");
  1053. c = 0;
  1054. memset(sstr ,0, sizeof(sstr) );
  1055. if(loc != NULL)
  1056. {
  1057. while (loc[strlen("meterStart")+2+c] != ',')
  1058. {
  1059. sstr[c] = loc[strlen("meterStart")+2+c];
  1060. c++;
  1061. }
  1062. sstr[c] = '\0';
  1063. tempmeterStart = atoi(sstr);
  1064. }
  1065. //reservationId
  1066. loc = strstr(str, "reservationId");
  1067. c = 0;
  1068. memset(sstr ,0, sizeof(sstr) );
  1069. if(loc != NULL)
  1070. {
  1071. while (loc[strlen("reservationId")+2+c] != ',')
  1072. {
  1073. sstr[c] = loc[strlen("reservationId")+2+c];
  1074. c++;
  1075. }
  1076. sstr[c] = '\0';
  1077. tempreservationId = atoi(sstr);
  1078. }
  1079. //timestamp
  1080. loc = strstr(str, "timestamp");
  1081. memset(sstr ,0, sizeof(sstr) );
  1082. c=0;
  1083. while (loc[3+strlen("timestamp")+c] != '\"')
  1084. {
  1085. sstr[c] = loc[3+strlen("timestamp")+c];
  1086. c++;
  1087. }
  1088. sstr[c] = '\0';
  1089. strcpy((char*)timestampStr, sstr);
  1090. if(hashmap_operation(1, guid, key_value) == TRUE)
  1091. {
  1092. //DEBUG_INFO("\n 1. sent queue guid=%s\n",guid);
  1093. }
  1094. else
  1095. {
  1096. hashmap_operation(0, guid, tempdata);
  1097. FillStartTransaction(tempconnectorId, IdtagStr, tempmeterStart, tempreservationId, timestampStr);
  1098. //DEBUG_INFO("\n 2. sent queue guid=%s\n",guid);
  1099. }
  1100. }
  1101. //*********************End: StartTransaction***************************/
  1102. //****************transactionId********************/
  1103. c=0;
  1104. loc = strstr(str, "transactionId");
  1105. memset(sstr ,0, sizeof(sstr) );
  1106. if(loc != NULL)
  1107. {
  1108. while ((loc[strlen("transactionId")+2+c] != '}') && (loc[strlen("transactionId")+2+c] != ','))
  1109. {
  1110. sstr[c] = loc[strlen("transactionId")+2+c];
  1111. c++;
  1112. }
  1113. sstr[c] = '\0';
  1114. temptransactionId = atoi(sstr);
  1115. //puts(str);
  1116. //DEBUG_INFO("\n uuid:%s", "");
  1117. //DEBUG_INFO("\n data:%s", str);
  1118. #if 0
  1119. if(IsStopTransaction == TRUE)
  1120. {
  1121. for(int i=0; i <10; i++)
  1122. {
  1123. //DEBUG_INFO("\n StopTransaction i:%d\n", i);
  1124. //DEBUG_INFO("\n StopTransaction SentQueueTransactionId[i]:%d\n", SentQueueTransactionId[i]);
  1125. //DEBUG_INFO("\n sStopTransaction temptransactionId:%d\n", temptransactionId);
  1126. if(SentQueueTransactionId[i] == temptransactionId)
  1127. {
  1128. tempconnectorId = i;
  1129. gunIndex = i;
  1130. break;
  1131. }
  1132. }
  1133. }
  1134. else
  1135. {
  1136. if(tempconnectorId > 0)
  1137. {
  1138. SentQueueTransactionId[tempconnectorId-1] = temptransactionId;
  1139. gunIndex = tempconnectorId-1;
  1140. }
  1141. }
  1142. #endif
  1143. //DEBUG_INFO("\n gunIndex=%d \n",gunIndex);
  1144. //DEBUG_INFO("\n temptransactionId=%d \n",temptransactionId);
  1145. //DEBUG_INFO("\n GetTransactionId(gunIndex)=%d \n",GetTransactionId(gunIndex));
  1146. gettransactionId = GetTransactionId(tempconnectorId, IdtagStr);
  1147. if((gettransactionId != 0)&&(temptransactionId != gettransactionId))
  1148. {
  1149. strncpy(strcomposite,str, (loc-str)+2+strlen("transactionId"));
  1150. sprintf(strcomposite+((loc-str)+2+strlen("transactionId")),"%d",gettransactionId);
  1151. strcat(strcomposite, loc+strlen("transactionId")+2+c);
  1152. LWS_Send(strcomposite);
  1153. }
  1154. else
  1155. {
  1156. LWS_Send(str);
  1157. }
  1158. if((IsStopTransaction == TRUE)&&(gettransactionId != 0))
  1159. {
  1160. SetTransactionIdZero(gettransactionId);
  1161. }
  1162. }
  1163. else
  1164. {
  1165. LWS_Send(str);
  1166. }
  1167. result = TRUE;
  1168. }
  1169. else
  1170. {
  1171. result = FALSE;
  1172. }
  1173. fclose(fp);
  1174. return result;
  1175. }
  1176. //
  1177. void* processTransactionQueue(void* data) {
  1178. char frontUUID[100] ={0};
  1179. char frontData[1200/*1024*4*/] ={0};
  1180. int queueNotEmpty = 0;
  1181. while(1)
  1182. {
  1183. if(FirstHeartBeatResponse() == 1)
  1184. {
  1185. memset(frontUUID, 0, sizeof(frontUUID));
  1186. memset(frontData, 0, sizeof(frontData));
  1187. queueNotEmpty = 0;
  1188. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1189. if((queueNotEmpty == 1) && (GetOcppConnStatus() == 1))
  1190. {
  1191. if((OfflineTransaction == 1) && (TransactionQueueNum != 0))
  1192. {
  1193. TransactionQueueInterval = 10;//2;
  1194. sleep(TransactionQueueInterval);
  1195. sendbuffer = 1;
  1196. }
  1197. else
  1198. {
  1199. OfflineTransaction = 0;
  1200. if(TransactionMessageResend < TransactionMessageAttemptsGet()) //
  1201. {
  1202. //DEBUG_INFO("TransactionMessageResend=%d\n",TransactionMessageResend);
  1203. //DEBUG_INFO("TransactionMessageAttemptsGet=%d\n",TransactionMessageAttemptsGet());
  1204. //DEBUG_INFO("processTransactionQueue queue is not empty!\n");
  1205. TransactionQueueInterval= TransactionMessageRetryIntervalGet()* TransactionMessageResend;
  1206. //DEBUG_INFO("TransactionQueueInterval =%d\n",TransactionQueueInterval);
  1207. sendbuffer = 1;
  1208. TransactionMessageResend = TransactionMessageResend + 1;
  1209. //DEBUG_INFO("After ADD,TransactionMessageResend=%d\n",TransactionMessageResend);
  1210. sleep(TransactionQueueInterval);
  1211. }
  1212. else
  1213. {
  1214. queue_operation(2,"",""); //// delete item
  1215. TransactionQueueInterval = 0;
  1216. TransactionMessageResend = 1;
  1217. sleep(TransactionQueueInterval);
  1218. }
  1219. }
  1220. }
  1221. else if((queueNotEmpty == 1) && (GetOcppConnStatus() == 0))
  1222. {
  1223. OfflineTransaction = 1;
  1224. }
  1225. else
  1226. {
  1227. TransactionQueueInterval = 0;//10;
  1228. sleep(TransactionQueueInterval);
  1229. }
  1230. }
  1231. usleep(5000);
  1232. }
  1233. pthread_exit(NULL); //
  1234. return 0;
  1235. }
  1236. void CheckTransactionPacket(char *uuid)
  1237. {
  1238. char frontUUID[100]={0};
  1239. char frontData[1200]={0};
  1240. int queueNotEmpty = 0;
  1241. int cmpResult = 0;
  1242. //queue_operation(0,"","");//showqueue(); ---> remove temporally
  1243. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1244. if(queueNotEmpty == 1)
  1245. {
  1246. cmpResult = strcmp(frontUUID, uuid);
  1247. //cmpResult = strcmp(frontData, uuid);
  1248. if (cmpResult == 0)
  1249. {
  1250. DEBUG_INFO("TransactionPacket Compare All right!\n");
  1251. //DEBUG_INFO("frontUUID=%s\n",frontUUID);
  1252. //DEBUG_INFO("uuid=%s\n",uuid);
  1253. queue_operation(2,"","");//delq(); ---> remove temporally
  1254. TransactionQueueInterval = 0;
  1255. TransactionMessageResend = 1;
  1256. }
  1257. }
  1258. }
  1259. /* type: 0 (showqueue ); type: 1(showfront); type: 2(delq) type: 3 (sentqueue) type: 4 (addq) type: 5(store queue to /Storage/OCPP/ )*/
  1260. int queue_operation(int type, char *frontUUID, char *frontData)
  1261. {
  1262. pthread_mutex_unlock(&lock_sentData);
  1263. pthread_mutex_lock(&lock_sentData);
  1264. int result=0;
  1265. if(type == 0) // show items in queue
  1266. result = showqueue();
  1267. else if(type == 1) // show first item
  1268. result = showfront(frontUUID, frontData);
  1269. else if(type == 2) // delete item
  1270. result = delq();
  1271. else if(type == 3) // sent items in queue
  1272. result = sentqueue();
  1273. else if(type == 4) // add items to the queue
  1274. result = addq(frontUUID, frontData);
  1275. pthread_mutex_unlock(&lock_sentData);
  1276. return result;
  1277. }
  1278. char * strchr(const char *p, int ch)
  1279. {
  1280. char c;
  1281. c = ch;
  1282. for (;; ++p) {
  1283. if (*p == c)
  1284. return ((char *)p);
  1285. if (*p == '\0')
  1286. return (NULL);
  1287. }
  1288. /* NOTREACHED */
  1289. return NULL;
  1290. }
  1291. int removeMessageSentFile(void)
  1292. {
  1293. char rmFileCmd[100]={0};
  1294. struct stat stats;
  1295. //
  1296. stat("/Storage/OCPP", &stats);
  1297. // Check for directory existence
  1298. if (S_ISDIR(stats.st_mode) == 1)
  1299. {
  1300. //DEBUG_INFO("\n OCPP directory exist \n");
  1301. }
  1302. else
  1303. {
  1304. DEBUG_INFO("\n directory not exist, create dir \n");
  1305. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  1306. system(rmFileCmd);
  1307. }
  1308. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1309. if((access("/Storage/OCPP/MessageSent",F_OK))!=-1)
  1310. {
  1311. DEBUG_INFO("MessageSent file exist.\n");
  1312. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/MessageSent");
  1313. system(rmFileCmd);
  1314. }
  1315. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1316. return 0;
  1317. }
  1318. void work(char s[]) //删除首尾空格
  1319. {int i,j;
  1320. for(i=0;s[i]==' ';i++); //找到开头第一个非空格
  1321. for(j=0;s[i];)s[j++]=s[i++]; //删除开头空格
  1322. for(i--;s[i]==' ';i--)s[i]='\0'; //删除末尾空格
  1323. }
  1324. static int changeChageWebSocketPingInterval = FALSE;
  1325. void ChageWebSocketPingInterval(int WebSocketPingInterval)
  1326. {
  1327. changeChageWebSocketPingInterval = TRUE;
  1328. }
  1329. #define SystemLogMessage
  1330. //================================================
  1331. // Main process
  1332. //================================================
  1333. int main(void)
  1334. {
  1335. char rmFileCmd[100]={0};
  1336. struct stat stats;
  1337. pthread_t t;
  1338. pthread_t pid;
  1339. #ifdef SystemLogMessage
  1340. DEBUG_INFO("Initialization...\n");
  1341. #endif
  1342. if(ProcessShareMemory()== FAIL)
  1343. {
  1344. return FAIL;
  1345. }
  1346. //Create OCPP dir
  1347. stat("/Storage/OCPP", &stats);
  1348. // Check for directory existence
  1349. if (S_ISDIR(stats.st_mode) == 1)
  1350. {
  1351. //DEBUG_INFO("\n OCPP directory exist \n");
  1352. }
  1353. else
  1354. {
  1355. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  1356. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  1357. system(rmFileCmd);
  1358. }
  1359. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1360. //Create Process: Resend Transaction
  1361. pthread_create(&t, NULL, processTransactionQueue, NULL); //
  1362. sqlite3_config(SQLITE_CONFIG_URI,1);
  1363. if(sqlite3_open("file:/Storage/OCPP/charger.db", &db))
  1364. {
  1365. #ifdef Debug
  1366. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1367. #endif
  1368. sqlite3_close( db );
  1369. exit(0);
  1370. }
  1371. else
  1372. {
  1373. #ifdef Debug
  1374. DEBUG_INFO( "Opened database successfully\n");
  1375. #endif
  1376. }
  1377. //Create Table log buffer
  1378. int rc =sqlite3_exec(db, createsql, 0, 0, &errMsg);
  1379. if (SQLITE_OK != rc)
  1380. {
  1381. #ifdef Debug
  1382. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1383. #endif
  1384. return 0;
  1385. }
  1386. else
  1387. {
  1388. #ifdef Debug
  1389. DEBUG_INFO( "Opened log buffer table successfully\n");
  1390. #endif
  1391. }
  1392. // Create Table OcppAuthCache
  1393. rc =sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg);
  1394. if (SQLITE_OK != rc)
  1395. {
  1396. #ifdef Debug
  1397. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1398. #endif
  1399. return 0;
  1400. }
  1401. else
  1402. {
  1403. #ifdef Debug
  1404. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1405. #endif
  1406. }
  1407. // Create Table OcppAuthLocal
  1408. rc =sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg);
  1409. if (SQLITE_OK != rc)
  1410. {
  1411. #ifdef Debug
  1412. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1413. #endif
  1414. return 0;
  1415. }
  1416. else
  1417. {
  1418. #ifdef Debug
  1419. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1420. #endif
  1421. }
  1422. initialConfigurationTable();
  1423. removeMessageSentFile();
  1424. OCPP_get_TableAuthlocalAllData();
  1425. for(;;)
  1426. {
  1427. while(ConnectionEstablished==0)
  1428. {
  1429. SetOcppConnStatus(FALSE);
  1430. if((time((time_t*)NULL)-startTime.connect)>=60)
  1431. {
  1432. #ifdef Debug
  1433. DEBUG_INFO("Execute ConnectWsServer\n");
  1434. #endif
  1435. //ConnectWsServer();
  1436. pthread_create(&pid, NULL, ConnectWsServer, NULL);
  1437. startTime.connect=time((time_t*)NULL);
  1438. }
  1439. // Check System Value, process offline Transaction
  1440. CheckSystemValue();
  1441. lws_service(context, 10000);//timeout_ms
  1442. }
  1443. if(( (BootNotificationInterval != 0 && ((time((time_t*)NULL)-startTime.bootNotification)>=BootNotificationInterval) ) || ((time((time_t*)NULL)-startTime.bootNotification)>=defaultWaitingTime) ) && ((server_sign == FALSE)/*|| (server_pending == TRUE)*/))
  1444. {
  1445. //hashmapForMessageNew();
  1446. sendBootNotificationRequest();
  1447. startTime.bootNotification=time((time_t*)NULL);
  1448. }
  1449. if(server_sign == TRUE)
  1450. {
  1451. if(sendbuffer == 1)
  1452. {
  1453. queue_operation(3, "", "");//sentqueue()
  1454. sendbuffer = 0;
  1455. }
  1456. SetOcppConnStatus(TRUE);
  1457. // Check System Value
  1458. CheckSystemValue();
  1459. if(GetHeartBeatWithNOResponse() >= 3)
  1460. {
  1461. lws_context_destroy(context);
  1462. ConnectionEstablished=0;
  1463. context = NULL;
  1464. SetHeartBeatWithNOResponse();
  1465. }
  1466. if(changeChageWebSocketPingInterval == TRUE)
  1467. {
  1468. changeChageWebSocketPingInterval = FALSE;
  1469. lws_context_destroy(context);
  1470. ConnectionEstablished=0;
  1471. context = NULL;
  1472. }
  1473. }
  1474. lws_service(context, 100);//timeout_ms
  1475. }
  1476. pthread_join(t, NULL); //
  1477. //hashmapForMessageFree();
  1478. return FAIL;
  1479. }