Module_OcppBackend.c 43 KB

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