Module_OcppBackend.c 42 KB

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