Module_OcppBackend.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  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[1024*4]={0};
  491. int c = 0;
  492. char *loc;
  493. char sstr[600]={ 0 };
  494. //**********Receive Message**********/
  495. c = 0;
  496. loc = strstr((const char *)in, "][2,");
  497. if(loc == NULL)
  498. {
  499. loc = strstr((const char *)in, "][3,");
  500. if(loc == NULL)
  501. {
  502. loc = strstr((const char *)in, "][4,");
  503. }
  504. }
  505. memset(sstr ,0, sizeof(sstr) );
  506. if(loc != NULL)
  507. {
  508. DEBUG_INFO("there are continuous second packet []\n");
  509. while (loc[1+c] != '\0')
  510. {
  511. sstr[c] = loc[1+c];
  512. c++;
  513. }
  514. sstr[c] = '\0';
  515. strcpy(tempin, sstr);
  516. DEBUG_INFO("Final Receive: %s\n", tempin);
  517. }
  518. else
  519. {
  520. strcpy(tempin,(char *)in);
  521. }
  522. ReceivedMessage((void *)tempin, len);
  523. break;
  524. default:
  525. #ifdef Debug
  526. DEBUG_INFO("OCPP16Callback:reason=%d\n", reason);
  527. #endif
  528. break;
  529. }
  530. return 0;
  531. }
  532. static struct lws_protocols protocols[] = {
  533. {
  534. "ocpp1.6",
  535. OCPP16Callback,
  536. 10240,
  537. 10240,
  538. },
  539. {
  540. "ocpp1.6",
  541. OCPP16Callback,
  542. 10240,
  543. 10240,
  544. },
  545. {
  546. NULL, NULL, 0 /* End of list */
  547. }
  548. };
  549. int ConnectWsServer()
  550. {
  551. int result = PASS;
  552. struct lws_context_creation_info ContextInfo;
  553. struct lws_client_connect_info ConnInfo;
  554. int use_ssl=0;
  555. //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);
  556. if(context!=NULL)
  557. lws_context_destroy(context);
  558. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  559. if((GetOcppServerURL()==0) || (GetOcppPort() == 0) || (GetOcppPath()==0) )
  560. {
  561. result = FAIL;
  562. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  563. return result;
  564. }
  565. if((strcmp(OcppProtocol,"ws")==0)&&(strlen(OcppProtocol)== 2))
  566. {
  567. printf("ws!!! \n");
  568. use_ssl=0;
  569. }
  570. else if((strcmp(OcppProtocol,"wss")==0)&&(strlen(OcppProtocol)== 3))
  571. {
  572. printf("wss!!! \n");
  573. use_ssl=1;
  574. }
  575. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  576. ContextInfo.iface = NULL;
  577. ContextInfo.ssl_private_key_password = NULL;
  578. ContextInfo.ssl_cert_filepath = NULL;//"./ssl_key/client_cert.pem";
  579. ContextInfo.ssl_private_key_filepath = NULL;//"./ssl_key/client_key.pem";
  580. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";//"./cacert.pem";
  581. ContextInfo.ssl_cipher_list = NULL; //use default one
  582. ContextInfo.gid = -1;
  583. ContextInfo.uid = -1;
  584. if(use_ssl)
  585. {
  586. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT ;
  587. }
  588. ContextInfo.protocols = protocols;
  589. ContextInfo.timeout_secs = 9999;//30;
  590. //if(ping pong enabled)
  591. ContextInfo.ws_ping_pong_interval = 30;//0 for none, else interval in seconds
  592. context = lws_create_context(&ContextInfo);
  593. if (context == NULL)
  594. {
  595. #ifdef SystemLogMessage
  596. DEBUG_ERROR("lws_create_context NG");
  597. #endif
  598. result = FAIL;
  599. }
  600. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  601. // fill up below information
  602. ConnInfo.context = context;
  603. ConnInfo.address=(const char *)OcppHost;
  604. printf("\n ConnInfo.address=%s\n",ConnInfo.address);
  605. ConnInfo.port = GetOcppPort();
  606. printf("\n ConnInfo.port=%d\n",ConnInfo.port);
  607. ConnInfo.path=(const char *)OcppPath;
  608. printf("\n ConnInfo.path=%s\n",ConnInfo.path);
  609. ConnInfo.host=ConnInfo.address;//lws_canonical_hostname(context);
  610. ConnInfo.origin="origin";
  611. ConnInfo.protocol = protocols[1].name;
  612. ConnInfo.ietf_version_or_minus_one = -1;
  613. if(use_ssl)
  614. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;;
  615. wsi_client = lws_client_connect_via_info(&ConnInfo);
  616. if (!wsi_client)
  617. {
  618. #ifdef SystemLogMessage
  619. DEBUG_ERROR("lws_client_connect_via_info NG");
  620. #endif
  621. result = FAIL;
  622. }
  623. return result;
  624. }
  625. //void createq();
  626. int showfront(char *uuid, char *data);
  627. int addq(char *uuid, char *data) ;
  628. int delq();
  629. int sentqueue();
  630. void CheckTransactionPacket(char *uuid);
  631. int queue_operation(int type, char *frontUUID, char *frontData);
  632. int showfront(char *uuid, char *data) {
  633. FILE *fp;
  634. int result = FALSE; // 1: TRUE 0:FALSE
  635. char str[1200]={0};
  636. char sstr[50]={ 0 };//sstr[200]={ 0 };
  637. int c = 0;
  638. char *loc;
  639. char rmFileCmd[100]={0};
  640. struct stat stats;
  641. stat("/Storage/OCPP", &stats);
  642. // Check for directory existence
  643. if (S_ISDIR(stats.st_mode) == 1)
  644. {
  645. //DEBUG_INFO("\n OCPP directory exist \n");
  646. }
  647. else
  648. {
  649. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  650. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  651. system(rmFileCmd);
  652. }
  653. memset(rmFileCmd, 0, sizeof rmFileCmd);
  654. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  655. {
  656. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  657. }
  658. else
  659. {
  660. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  661. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  662. if(log == NULL)
  663. {
  664. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  665. return 0;
  666. }
  667. else
  668. {
  669. fclose(log);
  670. }
  671. }
  672. /* opening file for reading */
  673. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  674. if(fp == NULL) {
  675. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  676. return FALSE;
  677. }
  678. #if 0
  679. if(fgetc(fp)==EOF)
  680. {
  681. //DEBUG_INFO("It is end of file");
  682. fclose(fp);
  683. memset(rmFileCmd, 0, sizeof rmFileCmd);
  684. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  685. {
  686. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/TransactionRelatedQueue");
  687. system(rmFileCmd);
  688. }
  689. result = FALSE;
  690. return result;
  691. }
  692. #endif
  693. if( fgets (str, 1200, fp)!=NULL ) {
  694. /* writing content to stdout */
  695. //DEBUG_INFO("str=%s",str);
  696. if ((str[0] == '\n')||(strcmp(str,"")==0))
  697. {
  698. DEBUG_INFO("It is a blank line");
  699. fclose(fp);
  700. memset(rmFileCmd, 0, sizeof rmFileCmd);
  701. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/TransactionRelatedQueue");
  702. system(rmFileCmd);
  703. result = FALSE;
  704. return result;
  705. }
  706. else
  707. {
  708. //puts(str);
  709. /*********************uuid***************/
  710. loc = strstr(str, "\"");
  711. memset(sstr ,0, sizeof(sstr) );
  712. c = 0;
  713. while (loc[1+c] != '\"')
  714. {
  715. sstr[c] = loc[1+c];
  716. c++;
  717. }
  718. sstr[c] = '\0';
  719. //DEBUG_INFO("\n uuid:%s", sstr);
  720. //DEBUG_INFO("\n data:%s", str);
  721. strcpy(uuid,sstr);
  722. strcpy(data,str);
  723. result = TRUE;
  724. }
  725. }
  726. else
  727. {
  728. //DEBUG_INFO("queue is null\n");
  729. strcpy(uuid,"");
  730. strcpy(data,"");
  731. result = FALSE;
  732. }
  733. fclose(fp);
  734. return result;
  735. }
  736. int addq(char *uuid, char *data) {
  737. FILE *outfile;
  738. char rmFileCmd[100]={0};
  739. struct stat stats;
  740. stat("/Storage/OCPP", &stats);
  741. DEBUG_INFO("addq\n");
  742. // Check for directory existence
  743. if (S_ISDIR(stats.st_mode) == 1)
  744. {
  745. DEBUG_INFO("\n OCPP directory exist \n");
  746. }
  747. else
  748. {
  749. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  750. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  751. system(rmFileCmd);
  752. }
  753. memset(rmFileCmd, 0, sizeof rmFileCmd);
  754. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  755. {
  756. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  757. }
  758. else
  759. {
  760. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  761. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  762. if(log == NULL)
  763. {
  764. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  765. return 0;
  766. }
  767. else
  768. {
  769. fclose(log);
  770. }
  771. }
  772. // open file for writing
  773. outfile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "a");
  774. //DEBUG_INFO("data=%s\n",data);
  775. fputs(data, outfile);
  776. fputs("\n", outfile);
  777. fclose (outfile);
  778. TransactionQueueNum = TransactionQueueNum + 1;
  779. return 0;
  780. }
  781. int delq() {
  782. char tempfile[] = "/Storage/OCPP/temp.json";
  783. FILE *infile;
  784. FILE *outfile;
  785. int resultRename=0;
  786. char filename[60]={0};
  787. char rmFileCmd[100]={0};
  788. struct stat stats;
  789. stat("/Storage/OCPP", &stats);
  790. DEBUG_INFO("delq()\n");
  791. // Check for directory existence
  792. if (S_ISDIR(stats.st_mode) == 1)
  793. {
  794. DEBUG_INFO("\n OCPP directory exist \n");
  795. }
  796. else
  797. {
  798. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  799. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  800. system(rmFileCmd);
  801. }
  802. memset(rmFileCmd, 0, sizeof rmFileCmd);
  803. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  804. {
  805. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  806. }
  807. else
  808. {
  809. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  810. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  811. if(log == NULL)
  812. {
  813. DEBUG_INFO("log is NULL\n");
  814. return 0;
  815. }
  816. else
  817. {
  818. fclose(log);
  819. }
  820. }
  821. // open file for writing
  822. strcpy(filename, "/Storage/OCPP/TransactionRelatedQueue");
  823. infile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "r");
  824. outfile = fopen (tempfile, "w");
  825. /*检测到文件结束标识返回1,否则返回0。*/
  826. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  827. int c;
  828. c = fgetc(infile);
  829. //printf("file c:%d\n",c);
  830. rewind(infile);
  831. if(c == EOF)
  832. {
  833. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  834. fclose(infile);
  835. fclose(outfile);
  836. sprintf(rmFileCmd,"rm -f %s",tempfile);
  837. system(rmFileCmd);
  838. }
  839. else
  840. {
  841. char buf[1200]={0};
  842. int i = 0;
  843. //DEBUG_INFO("Orignal File is not NULL\n");
  844. while (fgets(buf, sizeof(buf), infile) != NULL)
  845. {
  846. //printf("Orignal File get strings \n");
  847. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  848. if(i==0)
  849. {
  850. TransactionQueueNum = TransactionQueueNum - 1;
  851. TransactionQueueInterval = 0;
  852. TransactionMessageResend = 1;
  853. }
  854. if(i != 0)
  855. fprintf(outfile,"%s\n", buf);
  856. i = i + 1;
  857. }
  858. fclose(infile);
  859. fclose(outfile);
  860. sprintf(rmFileCmd,"rm -f %s",filename);
  861. system(rmFileCmd);
  862. resultRename = rename(tempfile, filename);
  863. if(resultRename == 0)
  864. {
  865. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  866. }
  867. else
  868. {
  869. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  870. }
  871. }
  872. return 0;
  873. }
  874. int showqueue() {
  875. char rmFileCmd[100]={0};
  876. struct stat stats;
  877. stat("/Storage/OCPP", &stats);
  878. // Check for directory existence
  879. if (S_ISDIR(stats.st_mode) == 1)
  880. {
  881. //DEBUG_INFO("\n OCPP directory exist \n");
  882. }
  883. else
  884. {
  885. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  886. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  887. system(rmFileCmd);
  888. }
  889. memset(rmFileCmd, 0, sizeof rmFileCmd);
  890. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  891. {
  892. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  893. }
  894. else
  895. {
  896. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  897. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  898. if(log == NULL)
  899. {
  900. DEBUG_INFO("log is NULL\n");
  901. return 0;
  902. }
  903. else
  904. {
  905. fclose(log);
  906. }
  907. }
  908. FILE *fp = fopen("/Storage/OCPP/TransactionRelatedQueue", "r");
  909. char line[1200]={0};
  910. // check if file exist (and you can open it) or not
  911. if (fp == NULL) {
  912. DEBUG_INFO("can open file TransactionRelatedQueue!");
  913. return 0;
  914. }
  915. while(fgets(line, sizeof line, fp) != NULL) {
  916. DEBUG_INFO("%s\n", line);
  917. }
  918. fclose(fp);
  919. return 0;
  920. }
  921. int sentqueue(){
  922. FILE *fp;
  923. int result = FALSE; // 1: TRUE 0:FALSE
  924. int temptransactionId = 0;
  925. int tempconnectorId = 0;
  926. int gunIndex = 0;
  927. char guid[37]={0};
  928. char tempdata[65]={0};
  929. char key_value[65]={0};
  930. int IsStopTransaction = FALSE;
  931. char str[1200]={0};
  932. char strcomposite[1200]={0};
  933. char rmFileCmd[100]={0};
  934. struct stat stats;
  935. char sstr[28]={ 0 };
  936. int c = 0;
  937. char *loc;
  938. DEBUG_INFO("sentqueue\n");
  939. stat("/Storage/OCPP", &stats);
  940. // Check for directory existence
  941. if (S_ISDIR(stats.st_mode) == 1)
  942. {
  943. //DEBUG_INFO("\n OCPP directory exist \n");
  944. }
  945. else
  946. {
  947. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  948. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  949. system(rmFileCmd);
  950. }
  951. memset(rmFileCmd, 0, sizeof rmFileCmd);
  952. /* opening file for reading */
  953. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  954. if(fp == NULL) {
  955. DEBUG_INFO("Error opening file");
  956. return FALSE;
  957. }
  958. if( fgets (str, 1200, fp)!=NULL ) {
  959. /* writing content to stdout */
  960. //*********************StopTransaction***************************/
  961. loc = strstr(str, "StopTransaction");
  962. c = 0;
  963. memset(sstr ,0, sizeof(sstr) );
  964. if(loc != NULL)
  965. {
  966. IsStopTransaction = TRUE;
  967. }
  968. //*********************connectorId***************************/
  969. loc = strstr(str, "connectorId");
  970. c = 0;
  971. memset(sstr ,0, sizeof(sstr) );
  972. if(loc != NULL)
  973. {
  974. while (loc[strlen("connectorId")+2+c] != ',')
  975. {
  976. sstr[c] = loc[strlen("connectorId")+2+c];
  977. c++;
  978. }
  979. sstr[c] = '\0';
  980. tempconnectorId = atoi(sstr);
  981. //DEBUG_INFO("\n tempconnectorId:%d\n", tempconnectorId);
  982. }
  983. //*********************StartTransaction***************************/
  984. loc = strstr(str, "StartTransaction");
  985. c = 0;
  986. memset(sstr ,0, sizeof(sstr) );
  987. if(loc != NULL)
  988. {
  989. //DEBUG_INFO("\n sent queue StartTransaction\n");
  990. if(tempconnectorId > 0)
  991. {
  992. sprintf(tempdata, "StartTransaction,%d", (tempconnectorId-1));
  993. }
  994. //else if(tempconnectorId == 0)
  995. //{
  996. // sprintf(tempdata, "StartTransaction,%d", 0);
  997. //}
  998. memset(sstr ,0, sizeof(sstr) );
  999. //DEBUG_INFO("\n 0-0. sent queue str=%s\n",str);
  1000. c=0;
  1001. while (str[4+c] != '\"')
  1002. {
  1003. sstr[c] = str[4+c];
  1004. c++;
  1005. }
  1006. sstr[c] = '\0';
  1007. strcpy(guid, sstr);
  1008. //DEBUG_INFO("\n 0. sent queue sstr=%s\n",sstr);
  1009. if(hashmap_operation(1, guid, key_value) == TRUE)
  1010. {
  1011. //DEBUG_INFO("\n 1. sent queue guid=%s\n",guid);
  1012. }
  1013. else
  1014. {
  1015. hashmap_operation(0, guid, tempdata);
  1016. //DEBUG_INFO("\n 2. sent queue guid=%s\n",guid);
  1017. }
  1018. }
  1019. //****************transactionId********************/
  1020. c=0;
  1021. loc = strstr(str, "transactionId");
  1022. memset(sstr ,0, sizeof(sstr) );
  1023. if(loc != NULL)
  1024. {
  1025. while ((loc[strlen("transactionId")+2+c] != '}') && (loc[strlen("transactionId")+2+c] != ','))
  1026. {
  1027. sstr[c] = loc[strlen("transactionId")+2+c];
  1028. c++;
  1029. }
  1030. sstr[c] = '\0';
  1031. temptransactionId = atoi(sstr);
  1032. //puts(str);
  1033. //DEBUG_INFO("\n uuid:%s", "");
  1034. //DEBUG_INFO("\n data:%s", str);
  1035. if(IsStopTransaction == TRUE)
  1036. {
  1037. for(int i=0; i <10; i++)
  1038. {
  1039. //DEBUG_INFO("\n StopTransaction i:%d\n", i);
  1040. //DEBUG_INFO("\n StopTransaction SentQueueTransactionId[i]:%d\n", SentQueueTransactionId[i]);
  1041. //DEBUG_INFO("\n sStopTransaction temptransactionId:%d\n", temptransactionId);
  1042. if(SentQueueTransactionId[i] == temptransactionId)
  1043. {
  1044. tempconnectorId = i;
  1045. gunIndex = i;
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. else
  1051. {
  1052. if(tempconnectorId > 0)
  1053. {
  1054. SentQueueTransactionId[tempconnectorId-1] = temptransactionId;
  1055. gunIndex = tempconnectorId-1;
  1056. }
  1057. }
  1058. //DEBUG_INFO("\n gunIndex=%d \n",gunIndex);
  1059. //DEBUG_INFO("\n temptransactionId=%d \n",temptransactionId);
  1060. //DEBUG_INFO("\n GetTransactionId(gunIndex)=%d \n",GetTransactionId(gunIndex));
  1061. if((GetTransactionId(gunIndex) != 0)&&(temptransactionId != GetTransactionId(gunIndex)))
  1062. {
  1063. strncpy(strcomposite,str, (loc-str)+2+strlen("transactionId"));
  1064. sprintf(strcomposite+((loc-str)+2+strlen("transactionId")),"%d",GetTransactionId(gunIndex));
  1065. strcat(strcomposite, loc+strlen("transactionId")+2+c);
  1066. LWS_Send(strcomposite);
  1067. }
  1068. else
  1069. {
  1070. LWS_Send(str);
  1071. }
  1072. if((IsStopTransaction == TRUE)&&(GetTransactionId(gunIndex) != 0))
  1073. {
  1074. SetTransactionIdZero(gunIndex);
  1075. }
  1076. }
  1077. else
  1078. {
  1079. LWS_Send(str);
  1080. }
  1081. result = TRUE;
  1082. }
  1083. else
  1084. {
  1085. result = FALSE;
  1086. }
  1087. fclose(fp);
  1088. return result;
  1089. }
  1090. //
  1091. void* processTransactionQueue(void* data) {
  1092. char frontUUID[100] ={0};
  1093. char frontData[1200/*1024*4*/] ={0};
  1094. int queueNotEmpty = 0;
  1095. while(1)
  1096. {
  1097. if(FirstHeartBeatResponse() == 1)
  1098. {
  1099. memset(frontUUID, 0, sizeof(frontUUID));
  1100. memset(frontData, 0, sizeof(frontData));
  1101. queueNotEmpty = 0;
  1102. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1103. if((queueNotEmpty == 1) && (GetOcppConnStatus() == 1))
  1104. {
  1105. if((OfflineTransaction == 1) && (TransactionQueueNum != 0))
  1106. {
  1107. TransactionQueueInterval = 10;//2;
  1108. sleep(TransactionQueueInterval);
  1109. sendbuffer = 1;
  1110. }
  1111. else
  1112. {
  1113. OfflineTransaction = 0;
  1114. if(TransactionMessageResend < TransactionMessageAttemptsGet()) //
  1115. {
  1116. //DEBUG_INFO("TransactionMessageResend=%d\n",TransactionMessageResend);
  1117. //DEBUG_INFO("TransactionMessageAttemptsGet=%d\n",TransactionMessageAttemptsGet());
  1118. //DEBUG_INFO("processTransactionQueue queue is not empty!\n");
  1119. TransactionQueueInterval= TransactionMessageRetryIntervalGet()* TransactionMessageResend;
  1120. //DEBUG_INFO("TransactionQueueInterval =%d\n",TransactionQueueInterval);
  1121. sendbuffer = 1;
  1122. TransactionMessageResend = TransactionMessageResend + 1;
  1123. //DEBUG_INFO("After ADD,TransactionMessageResend=%d\n",TransactionMessageResend);
  1124. sleep(TransactionQueueInterval);
  1125. }
  1126. else
  1127. {
  1128. queue_operation(2,"",""); //// delete item
  1129. TransactionQueueInterval = 0;
  1130. TransactionMessageResend = 1;
  1131. sleep(TransactionQueueInterval);
  1132. }
  1133. }
  1134. }
  1135. else if((queueNotEmpty == 1) && (GetOcppConnStatus() == 0))
  1136. {
  1137. OfflineTransaction = 1;
  1138. }
  1139. else
  1140. {
  1141. TransactionQueueInterval = 0;//10;
  1142. sleep(TransactionQueueInterval);
  1143. }
  1144. }
  1145. usleep(5000);
  1146. }
  1147. pthread_exit(NULL); //
  1148. return 0;
  1149. }
  1150. void CheckTransactionPacket(char *uuid)
  1151. {
  1152. char frontUUID[100]={0};
  1153. char frontData[1200]={0};
  1154. int queueNotEmpty = 0;
  1155. int cmpResult = 0;
  1156. //queue_operation(0,"","");//showqueue(); ---> remove temporally
  1157. queueNotEmpty = queue_operation(1,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1158. if(queueNotEmpty == 1)
  1159. {
  1160. cmpResult = strcmp(frontUUID, uuid);
  1161. //cmpResult = strcmp(frontData, uuid);
  1162. if (cmpResult == 0)
  1163. {
  1164. DEBUG_INFO("TransactionPacket Compare All right!\n");
  1165. //DEBUG_INFO("frontUUID=%s\n",frontUUID);
  1166. //DEBUG_INFO("uuid=%s\n",uuid);
  1167. queue_operation(2,"","");//delq(); ---> remove temporally
  1168. TransactionQueueInterval = 0;
  1169. TransactionMessageResend = 1;
  1170. }
  1171. }
  1172. }
  1173. /* type: 0 (showqueue ); type: 1(showfront); type: 2(delq) type: 3 (sentqueue) type: 4 (addq) type: 5(store queue to /Storage/OCPP/ )*/
  1174. int queue_operation(int type, char *frontUUID, char *frontData)
  1175. {
  1176. pthread_mutex_unlock(&lock_sentData);
  1177. pthread_mutex_lock(&lock_sentData);
  1178. int result=0;
  1179. if(type == 0) // show items in queue
  1180. result = showqueue();
  1181. else if(type == 1) // show first item
  1182. result = showfront(frontUUID, frontData);
  1183. else if(type == 2) // delete item
  1184. result = delq();
  1185. else if(type == 3) // sent items in queue
  1186. result = sentqueue();
  1187. else if(type == 4) // add items to the queue
  1188. result = addq(frontUUID, frontData);
  1189. pthread_mutex_unlock(&lock_sentData);
  1190. return result;
  1191. }
  1192. char * strchr(const char *p, int ch)
  1193. {
  1194. char c;
  1195. c = ch;
  1196. for (;; ++p) {
  1197. if (*p == c)
  1198. return ((char *)p);
  1199. if (*p == '\0')
  1200. return (NULL);
  1201. }
  1202. /* NOTREACHED */
  1203. return NULL;
  1204. }
  1205. int removeMessageSentFile(void)
  1206. {
  1207. char rmFileCmd[100]={0};
  1208. struct stat stats;
  1209. //
  1210. stat("/Storage/OCPP", &stats);
  1211. // Check for directory existence
  1212. if (S_ISDIR(stats.st_mode) == 1)
  1213. {
  1214. //DEBUG_INFO("\n OCPP directory exist \n");
  1215. }
  1216. else
  1217. {
  1218. DEBUG_INFO("\n directory not exist, create dir \n");
  1219. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  1220. system(rmFileCmd);
  1221. }
  1222. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1223. if((access("/Storage/OCPP/MessageSent",F_OK))!=-1)
  1224. {
  1225. DEBUG_INFO("MessageSent file exist.\n");
  1226. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/MessageSent");
  1227. system(rmFileCmd);
  1228. }
  1229. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1230. return 0;
  1231. }
  1232. void work(char s[]) //删除首尾空格
  1233. {int i,j;
  1234. for(i=0;s[i]==' ';i++); //找到开头第一个非空格
  1235. for(j=0;s[i];)s[j++]=s[i++]; //删除开头空格
  1236. for(i--;s[i]==' ';i--)s[i]='\0'; //删除末尾空格
  1237. }
  1238. #define SystemLogMessage
  1239. //================================================
  1240. // Main process
  1241. //================================================
  1242. int main(void)
  1243. {
  1244. char rmFileCmd[100]={0};
  1245. struct stat stats;
  1246. pthread_t t;
  1247. #ifdef SystemLogMessage
  1248. DEBUG_INFO("Initialization...\n");
  1249. #endif
  1250. if(ProcessShareMemory()== FAIL)
  1251. {
  1252. return FAIL;
  1253. }
  1254. //Create OCPP dir
  1255. stat("/Storage/OCPP", &stats);
  1256. // Check for directory existence
  1257. if (S_ISDIR(stats.st_mode) == 1)
  1258. {
  1259. //DEBUG_INFO("\n OCPP directory exist \n");
  1260. }
  1261. else
  1262. {
  1263. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  1264. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  1265. system(rmFileCmd);
  1266. }
  1267. memset(rmFileCmd, 0, sizeof rmFileCmd);
  1268. //Create Process: Resend Transaction
  1269. pthread_create(&t, NULL, processTransactionQueue, NULL); //
  1270. sqlite3_config(SQLITE_CONFIG_URI,1);
  1271. if(sqlite3_open("file:/Storage/OCPP/charger.db", &db))
  1272. {
  1273. #ifdef Debug
  1274. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1275. #endif
  1276. sqlite3_close( db );
  1277. exit(0);
  1278. }
  1279. else
  1280. {
  1281. #ifdef Debug
  1282. DEBUG_INFO( "Opened database successfully\n");
  1283. #endif
  1284. }
  1285. //Create Table log buffer
  1286. int rc =sqlite3_exec(db, createsql, 0, 0, &errMsg);
  1287. if (SQLITE_OK != rc)
  1288. {
  1289. #ifdef Debug
  1290. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1291. #endif
  1292. return 0;
  1293. }
  1294. else
  1295. {
  1296. #ifdef Debug
  1297. DEBUG_INFO( "Opened log buffer table successfully\n");
  1298. #endif
  1299. }
  1300. // Create Table OcppAuthCache
  1301. rc =sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg);
  1302. if (SQLITE_OK != rc)
  1303. {
  1304. #ifdef Debug
  1305. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1306. #endif
  1307. return 0;
  1308. }
  1309. else
  1310. {
  1311. #ifdef Debug
  1312. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1313. #endif
  1314. }
  1315. // Create Table OcppAuthLocal
  1316. rc =sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg);
  1317. if (SQLITE_OK != rc)
  1318. {
  1319. #ifdef Debug
  1320. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1321. #endif
  1322. return 0;
  1323. }
  1324. else
  1325. {
  1326. #ifdef Debug
  1327. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1328. #endif
  1329. }
  1330. initialConfigurationTable();
  1331. removeMessageSentFile();
  1332. OCPP_get_TableAuthlocalAllData();
  1333. for(;;)
  1334. {
  1335. while(ConnectionEstablished==0)
  1336. {
  1337. SetOcppConnStatus(FALSE);
  1338. if((time((time_t*)NULL)-startTime.connect)>=60)
  1339. {
  1340. #ifdef Debug
  1341. DEBUG_INFO("Execute ConnectWsServer\n");
  1342. #endif
  1343. ConnectWsServer();
  1344. startTime.connect=time((time_t*)NULL);
  1345. }
  1346. // Check System Value, process offline Transaction
  1347. CheckSystemValue();
  1348. lws_service(context, 10000);//timeout_ms
  1349. }
  1350. if(( (BootNotificationInterval != 0 && ((time((time_t*)NULL)-startTime.bootNotification)>=BootNotificationInterval) ) || ((time((time_t*)NULL)-startTime.bootNotification)>=defaultWaitingTime) ) && ((server_sign == FALSE)/*|| (server_pending == TRUE)*/))
  1351. {
  1352. //hashmapForMessageNew();
  1353. sendBootNotificationRequest();
  1354. startTime.bootNotification=time((time_t*)NULL);
  1355. }
  1356. if(server_sign == TRUE)
  1357. {
  1358. if(sendbuffer == 1)
  1359. {
  1360. queue_operation(3, "", "");//sentqueue()
  1361. sendbuffer = 0;
  1362. }
  1363. SetOcppConnStatus(TRUE);
  1364. // Check System Value
  1365. CheckSystemValue();
  1366. if(GetHeartBeatWithNOResponse() >= 3)
  1367. {
  1368. lws_context_destroy(context);
  1369. ConnectionEstablished=0;
  1370. context = NULL;
  1371. SetHeartBeatWithNOResponse();
  1372. }
  1373. }
  1374. lws_service(context, 100);//timeout_ms
  1375. }
  1376. pthread_join(t, NULL); //
  1377. //hashmapForMessageFree();
  1378. return FAIL;
  1379. }