Module_OcppBackend.c 42 KB

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