Module_OcppBackend.c 43 KB

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