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