Module_OcppBackend.c 40 KB

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