Module_OcppBackend.c 44 KB

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