Module_OcppBackend.c 44 KB

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