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