Module_OcppBackend.c 42 KB

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