Module_OcppBackend.c 42 KB

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