Module_OcppBackend.c 40 KB

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