Module_OcppBackend.c 37 KB

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