Module_OcppBackend.c 43 KB

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