Module_OcppBackend.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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. return FALSE;
  610. }
  611. //---------------- delq(): delete the top item --------------//
  612. int delq()
  613. {
  614. char tempfile[] = "/Storage/OCPP/delqtemp.json";
  615. FILE *infile;
  616. FILE *outfile;
  617. int resultRename=0;
  618. char filename[60]={0};
  619. char rmFileCmd[100]={0};
  620. struct stat stats;
  621. stat("/Storage/OCPP", &stats);
  622. DEBUG_INFO("delq()\n");
  623. // Check for directory existence
  624. if (S_ISDIR(stats.st_mode) == 1)
  625. {
  626. //DEBUG_INFO("\n OCPP directory exist \n");
  627. }
  628. else
  629. {
  630. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  631. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  632. system(rmFileCmd);
  633. }
  634. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  635. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  636. {
  637. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  638. }
  639. else
  640. {
  641. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  642. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  643. if(log == NULL)
  644. {
  645. //DEBUG_INFO("log is NULL\n");
  646. return 0;
  647. }
  648. else
  649. {
  650. fclose(log);
  651. }
  652. }
  653. // open file for writing
  654. strcpy(filename, "/Storage/OCPP/TransactionRelatedQueue");
  655. infile = fopen ("/Storage/OCPP/TransactionRelatedQueue", "r");
  656. outfile = fopen (tempfile, "w");
  657. /*检测到文件结束标识返回1,否则返回0。*/
  658. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  659. int c;
  660. c = fgetc(infile);
  661. //printf("file c:%d\n",c);
  662. rewind(infile);
  663. if(c == EOF)
  664. {
  665. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  666. fclose(infile);
  667. fclose(outfile);
  668. sprintf(rmFileCmd,"rm -f %s",tempfile);
  669. system(rmFileCmd);
  670. }
  671. else
  672. {
  673. char buf[QUEUE_MESSAGE_LENGTH]={0};
  674. int i = 0;
  675. //DEBUG_INFO("Orignal File is not NULL\n");
  676. while (fgets(buf, sizeof(buf), infile) != NULL)
  677. {
  678. //printf("Orignal File get strings \n");
  679. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  680. if(i==0)
  681. {
  682. TransactionQueueNum = TransactionQueueNum - 1;
  683. TransactionMessageResend = 1;
  684. DEBUG_INFO("delete the item\n");
  685. }
  686. if(i != 0)
  687. {
  688. fprintf(outfile,"%s\n", buf);
  689. }
  690. i = i + 1;
  691. }
  692. fclose(infile);
  693. fclose(outfile);
  694. sprintf(rmFileCmd,"rm -f %s",filename);
  695. system(rmFileCmd);
  696. resultRename = rename(tempfile, filename);
  697. if(resultRename == 0)
  698. {
  699. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  700. }
  701. else
  702. {
  703. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  704. }
  705. DEBUG_INFO("delq() end\n");
  706. }
  707. return 0;
  708. }
  709. int showqueue()
  710. {
  711. char rmFileCmd[100]={0};
  712. struct stat stats;
  713. stat("/Storage/OCPP", &stats);
  714. // Check for directory existence
  715. if (S_ISDIR(stats.st_mode) == 1)
  716. {
  717. //DEBUG_INFO("\n OCPP directory exist \n");
  718. }
  719. else
  720. {
  721. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  722. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  723. system(rmFileCmd);
  724. }
  725. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  726. if((access("/Storage/OCPP/TransactionRelatedQueue",F_OK))!=-1)
  727. {
  728. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  729. }
  730. else
  731. {
  732. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  733. FILE *log = fopen("/Storage/OCPP/TransactionRelatedQueue", "w+");
  734. if(log == NULL)
  735. {
  736. DEBUG_INFO("log is NULL\n");
  737. return FALSE;
  738. }
  739. else
  740. {
  741. fclose(log);
  742. }
  743. }
  744. FILE *fp = fopen("/Storage/OCPP/TransactionRelatedQueue", "r");
  745. char line[QUEUE_MESSAGE_LENGTH]={0};
  746. // check if file exist (and you can open it) or not
  747. if (fp == NULL) {
  748. DEBUG_INFO("can open file TransactionRelatedQueue!");
  749. return FALSE;
  750. }
  751. TransactionQueueNum = 0; // the number of packets in queue
  752. while(fgets(line, sizeof line, fp) != NULL) {
  753. //DEBUG_INFO("%s\n", line);
  754. TransactionQueueNum = TransactionQueueNum + 1; //the number of packets in queue
  755. }
  756. fclose(fp);
  757. return TRUE;
  758. }
  759. int sentqueue(){
  760. FILE *fp;
  761. int result = FALSE; // 1: TRUE 0:FALSE
  762. int temptransactionId = 0, gettransactionId = 0;
  763. int tempconnectorId = 0;
  764. //int gunIndex = 0;
  765. char guid[37]={0};
  766. char tempdata[65]={0};
  767. char key_value[65]={0};
  768. int IsStopTransaction = FALSE;
  769. //int IsconnectorIdNULL = FALSE;
  770. //int IsIdtagNULL = FALSE;
  771. char str[QUEUE_MESSAGE_LENGTH]={0};
  772. char strcomposite[QUEUE_MESSAGE_LENGTH]={0};
  773. char rmFileCmd[100]={0};
  774. char connectorStr[2]={0};
  775. struct stat stats;
  776. char sstr[28]={0};
  777. unsigned char IdtagStr[20]={0};
  778. unsigned char timestampStr[30]={0};
  779. int tempmeterStart = 0;
  780. int tempreservationId = 0;
  781. int c = 0;
  782. char *loc;
  783. DEBUG_INFO("Sent queue.\n");
  784. stat("/Storage/OCPP", &stats);
  785. // Check for directory existence
  786. if (S_ISDIR(stats.st_mode) == 1)
  787. {
  788. //DEBUG_INFO("\n OCPP directory exist \n");
  789. }
  790. else
  791. {
  792. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  793. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  794. system(rmFileCmd);
  795. }
  796. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  797. /* opening file for reading */
  798. fp = fopen("/Storage/OCPP/TransactionRelatedQueue" , "r");
  799. if(fp == NULL) {
  800. DEBUG_INFO("Error opening file");
  801. return FALSE;
  802. }
  803. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL ) {
  804. //---- writing content to stdout ---//
  805. //*********************Start: StopTransaction***************************/
  806. loc = strstr(str, "StopTransaction");
  807. c = 0;
  808. memset(sstr ,0, ARRAY_SIZE(sstr) );
  809. if(loc != NULL)
  810. {
  811. IsStopTransaction = TRUE;
  812. }
  813. memset(connectorStr,0,ARRAY_SIZE(connectorStr));
  814. strncpy(connectorStr, str, 1);
  815. tempconnectorId = atoi(connectorStr);
  816. //*********************End: StopTransaction***************************/
  817. #if 0
  818. //*********************Start:connectorId***************************/
  819. loc = strstr(str, "connectorId");
  820. c = 0;
  821. memset(sstr ,0, ARRAY_SIZE(sstr) );
  822. if(loc != NULL)
  823. {
  824. while (loc[strlen("connectorId")+2+c] != ',')
  825. {
  826. sstr[c] = loc[strlen("connectorId")+2+c];
  827. c++;
  828. }
  829. sstr[c] = '\0';
  830. tempconnectorId = atoi(sstr);
  831. }
  832. // else
  833. // {
  834. // IsconnectorIdNULL = TRUE;
  835. // }
  836. //*********************End:connectorId***************************/
  837. #endif
  838. //*********************Start:idTag***************************/
  839. loc = strstr(str, "idTag");
  840. c = 0;
  841. memset(sstr ,0, ARRAY_SIZE(sstr) );
  842. if(loc != NULL)
  843. {
  844. while (loc[3+strlen("idTag")+c] != '\"')
  845. {
  846. sstr[c] = loc[3+strlen("idTag")+c];
  847. c++;
  848. }
  849. sstr[c] = '\0';
  850. strcpy((char*)IdtagStr, sstr);
  851. }
  852. // else
  853. // {
  854. // IsIdtagNULL = TRUE;
  855. // }
  856. //*********************End:idTag***************************/
  857. //*********************Start: StartTransaction***************************/
  858. loc = strstr(str, "StartTransaction");
  859. c = 0;
  860. memset(sstr ,0, ARRAY_SIZE(sstr) );
  861. if(loc != NULL)
  862. {
  863. // [2,0200000000000000000000000001584415776,StartTransaction,{connectorId:1,idTag:123,meterStart:100,reservationId:0,timestamp:2020-03-17T03:29:36Z}]
  864. //DEBUG_INFO("\n sent queue StartTransaction\n");
  865. if(tempconnectorId > 0)
  866. {
  867. sprintf(tempdata, "StartTransaction,%d", (tempconnectorId-1));
  868. }
  869. //GUID
  870. memset(sstr ,0, ARRAY_SIZE(sstr) );
  871. c=0;
  872. while (str[6+c] != '\"')
  873. {
  874. sstr[c] = str[6+c];
  875. c++;
  876. }
  877. sstr[c] = '\0';
  878. strcpy(guid, sstr);
  879. //Idtag
  880. loc = strstr(str, "idTag");
  881. memset(sstr ,0, ARRAY_SIZE(sstr) );
  882. c=0;
  883. while (loc[3+strlen("idTag")+c] != '\"')
  884. {
  885. sstr[c] = loc[3+strlen("idTag")+c];
  886. c++;
  887. }
  888. sstr[c] = '\0';
  889. strcpy((char*)IdtagStr, sstr);
  890. //meterStart
  891. loc = strstr(str, "meterStart");
  892. c = 0;
  893. memset(sstr ,0, ARRAY_SIZE(sstr) );
  894. if(loc != NULL)
  895. {
  896. while (loc[strlen("meterStart")+2+c] != ',')
  897. {
  898. sstr[c] = loc[strlen("meterStart")+2+c];
  899. c++;
  900. }
  901. sstr[c] = '\0';
  902. tempmeterStart = atoi(sstr);
  903. }
  904. //reservationId
  905. loc = strstr(str, "reservationId");
  906. c = 0;
  907. memset(sstr ,0, ARRAY_SIZE(sstr) );
  908. if(loc != NULL)
  909. {
  910. while (loc[strlen("reservationId")+2+c] != ',')
  911. {
  912. sstr[c] = loc[strlen("reservationId")+2+c];
  913. c++;
  914. }
  915. sstr[c] = '\0';
  916. tempreservationId = atoi(sstr);
  917. }
  918. //timestamp
  919. loc = strstr(str, "timestamp");
  920. memset(sstr ,0, ARRAY_SIZE(sstr) );
  921. c=0;
  922. while (loc[3+strlen("timestamp")+c] != '\"')
  923. {
  924. sstr[c] = loc[3+strlen("timestamp")+c];
  925. c++;
  926. }
  927. sstr[c] = '\0';
  928. strcpy((char*)timestampStr, sstr);
  929. if(hashmap_operation(HASH_OP_GET, guid, key_value) == TRUE)
  930. {
  931. //DEBUG_INFO("\n 1. sent queue guid=%s\n",guid);
  932. }
  933. else
  934. {
  935. hashmap_operation(HASH_OP_ADD, guid, tempdata);
  936. FillStartTransaction(tempconnectorId, IdtagStr, tempmeterStart, tempreservationId, timestampStr);
  937. //DEBUG_INFO("\n 2. sent queue guid=%s\n",guid);
  938. }
  939. }
  940. //*********************End: StartTransaction***************************/
  941. //****************transactionId********************/
  942. c=0;
  943. loc = strstr(str, "transactionId");
  944. memset(sstr ,0, ARRAY_SIZE(sstr) );
  945. if(loc != NULL)
  946. {
  947. // Only MeterValue with transactionId & StopTransaction will arrive here
  948. while ((loc[strlen("transactionId")+2+c] != '}') && (loc[strlen("transactionId")+2+c] != ','))
  949. {
  950. sstr[c] = loc[strlen("transactionId")+2+c];
  951. c++;
  952. }
  953. sstr[c] = '\0';
  954. temptransactionId = atoi(sstr);
  955. //Get IdTag from StartTransaction , store to StartTransactionIdTagTemp, For StopTransaction usage in Queue (StartTransaction. StopTransaction user id different), get actual TransactionId
  956. GetStartTransactionIdTag(tempconnectorId-1);
  957. gettransactionId = GetTransactionId(tempconnectorId, IdtagStr, IsStopTransaction);
  958. DEBUG_INFO("queue map transactionId = %d\n", gettransactionId);
  959. DEBUG_INFO("original connectorId = %d\n", tempconnectorId);
  960. DEBUG_INFO("original transactionId = %d\n", temptransactionId);
  961. DEBUG_INFO("original IdtagStr = %s\n", IdtagStr);
  962. if((gettransactionId != 0)&&(temptransactionId != gettransactionId))
  963. {
  964. //replace transactionId of metervalue or stopTransaction
  965. strncpy(strcomposite,str, (loc-str)+2+strlen("transactionId"));
  966. sprintf(strcomposite+((loc-str)+2+strlen("transactionId")),"%d",gettransactionId);
  967. strcat(strcomposite, loc+strlen("transactionId")+2+c); // 把 字串中transactionId後面的字串串接到 strcomposite後面
  968. LWS_Send(strcomposite+2); // skip 2 bytes String -> Connector ID,
  969. }
  970. else
  971. {
  972. LWS_Send(str+2); // skip 2 bytes String -> Connector ID
  973. gettransactionId = temptransactionId;
  974. }
  975. DEBUG_INFO("Final transactionId = %d\n", gettransactionId);
  976. if(IsStopTransaction == TRUE)//if((IsStopTransaction == TRUE)&&(gettransactionId != 0))
  977. {
  978. SetTransactionIdZero(gettransactionId);
  979. }
  980. }
  981. else
  982. {
  983. // MeterValue without transactionId & StartTransaction arrive here
  984. LWS_Send(str+2);
  985. }
  986. result = TRUE;
  987. }
  988. else
  989. {
  990. result = FALSE;
  991. }
  992. fclose(fp);
  993. return result;
  994. }
  995. void* processTransactionQueue(void* data)
  996. {
  997. char frontUUID[100] ={0};
  998. char frontData[QUEUE_MESSAGE_LENGTH/*1024*4*/] ={0};
  999. int queueNotEmpty = FALSE;
  1000. while(1)
  1001. {
  1002. if(!req_SendQueue && ((((time((time_t*)NULL) - startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))) || (isWebsocketSendable && ((time((time_t*)NULL) - startTimeQueue) >= ((counterQueueSent>=20)?5:0)))))
  1003. {
  1004. if(FirstHeartBeatResponse() == 1)
  1005. {
  1006. memset(frontUUID, 0, ARRAY_SIZE(frontUUID));
  1007. memset(frontData, 0, ARRAY_SIZE(frontData));
  1008. queueNotEmpty = FALSE;
  1009. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1010. if((queueNotEmpty == TRUE) && (GetOcppConnStatus() == 1)) //OcppConnStatus 0: disconnected, 1: connected
  1011. {
  1012. if(isWebsocketSendable)
  1013. DEBUG_INFO("isWebsocketSendable on.\n");
  1014. if((((time((time_t*)NULL) - startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))))
  1015. DEBUG_INFO("Queue timer(%d) over spec(%d).\n", (time((time_t*)NULL) - startTimeQueue), TransactionMessageRetryIntervalGet());
  1016. if((OfflineTransaction == 1) && (OfflineTransactionQueueNum != 0)) //OfflineTransaction 0: no offline Transaction 1: offline Transaction
  1017. {
  1018. DEBUG_INFO("Sent message from queue request off-line first.\n");
  1019. req_SendQueue = 1; // 0: no packets to send 1: send the top packet in queue
  1020. OfflineTransactionQueueNum = OfflineTransactionQueueNum - 1;
  1021. if(OfflineTransactionQueueNum == 0)
  1022. {
  1023. OfflineTransaction = 0;
  1024. }
  1025. }
  1026. else
  1027. {
  1028. if(TransactionMessageResend <= TransactionMessageAttemptsGet()) //
  1029. {
  1030. DEBUG_INFO("Sent message from queue request.\n");
  1031. DEBUG_INFO("TransactionMessageResend = %d\n",TransactionMessageResend);
  1032. req_SendQueue = 1;
  1033. TransactionMessageResend += 1;
  1034. }
  1035. else
  1036. {
  1037. DEBUG_INFO("Transaction message resend(%d) over spec(%d) message abandon.\n", TransactionMessageResend, TransactionMessageAttemptsGet());
  1038. queue_operation(QUEUE_OPERATION_DEL,"",""); //// delete item
  1039. TransactionMessageResend = 1;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. if(GetOcppConnStatus() == 0)
  1045. {
  1046. if(queueNotEmpty == TRUE)
  1047. {
  1048. OfflineTransaction = 1; // 0: no offline Transaction 1: offline Transaction
  1049. }
  1050. }
  1051. // Refresh queue timer
  1052. startTimeQueue = time((time_t*)NULL);
  1053. if((counterQueueSent >= 10) || (queueNotEmpty == FALSE))
  1054. {
  1055. counterQueueSent = 0;
  1056. }
  1057. else
  1058. {
  1059. counterQueueSent += 1;
  1060. }
  1061. }
  1062. usleep(500000);
  1063. }
  1064. pthread_exit(NULL); //
  1065. return 0;
  1066. }
  1067. void* processWatchdog()
  1068. {
  1069. for(;;)
  1070. {
  1071. if(((time((time_t*)NULL) - startTimeDog) > 10) && (context != NULL))
  1072. {
  1073. DEBUG_INFO("LWS watch dog timeout.\n");
  1074. lws_cancel_service(context);
  1075. lws_cancel_service_pt(wsi_client);
  1076. if(counterLwsRestart >= 2)
  1077. {
  1078. DEBUG_INFO("LWS watch dog timeout over 3 count.\n");
  1079. system("pkill OcppBackend");
  1080. }
  1081. else
  1082. counterLwsRestart++;
  1083. startTimeDog = time((time_t*)NULL);
  1084. }
  1085. if(counterConnect >= 2)
  1086. {
  1087. DEBUG_INFO("Connect OCPP server timeout over 3 count.\n");
  1088. system("pkill OcppBackend");
  1089. }
  1090. /*
  1091. if(system("pidof -s Module_PhBackend > /dev/null") != 0)
  1092. {
  1093. DEBUG_INFO("Module_PhBackend not running, restart it.\r\n");
  1094. system("/root/Module_PhBackend &");
  1095. }*/
  1096. sleep(1);
  1097. }
  1098. pthread_exit(NULL); //
  1099. }
  1100. void CheckTransactionPacket(char *uuid)
  1101. {
  1102. char frontUUID[100]={0};
  1103. char frontData[QUEUE_MESSAGE_LENGTH]={0};
  1104. int queueNotEmpty = FALSE;
  1105. int cmpResult = 0;
  1106. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1107. if(queueNotEmpty == TRUE)
  1108. {
  1109. cmpResult = strcmp(frontUUID, uuid);
  1110. if (cmpResult == 0)
  1111. {
  1112. DEBUG_INFO("Receive queue response match.\n");
  1113. queue_operation(QUEUE_OPERATION_DEL,"","");//delq(); ---> remove temporally
  1114. TransactionMessageResend = 1;
  1115. }
  1116. else
  1117. DEBUG_INFO("Receive queue response mismatch.\n");
  1118. }
  1119. }
  1120. int queue_operation(int type, char *frontUUID, char *frontData)
  1121. {
  1122. int result=0;
  1123. while(1)
  1124. {
  1125. if (!IsUsing )
  1126. {
  1127. IsUsing = TRUE;
  1128. if(type == QUEUE_OPERATION_SHOWQUEUE) // show items in queue
  1129. {
  1130. result = showqueue();
  1131. }
  1132. else if(type == QUEUE_OPERATION_SHOWFRONT) // show first item
  1133. {
  1134. result = showfront(frontUUID, frontData);
  1135. }
  1136. else if(type == QUEUE_OPERATION_DEL) // delete item
  1137. {
  1138. result = delq();
  1139. }
  1140. else if(type == QUEUE_OPERATION_SENT) // sent items in queue
  1141. {
  1142. result = sentqueue();
  1143. }
  1144. else if(type == QUEUE_OPERATION_ADD) // add items to the queue
  1145. {
  1146. // If queue file over size only add start * stop transaction message
  1147. if(!isQueueOverSize() || (strstr(frontData, "MeterValues") == NULL))
  1148. {
  1149. result = addq(frontUUID, frontData);
  1150. }
  1151. }
  1152. IsUsing = FALSE;
  1153. break;
  1154. }
  1155. usleep(100000);
  1156. }
  1157. return result;
  1158. }
  1159. int removeMessageSentFile(void)
  1160. {
  1161. char rmFileCmd[100]={0};
  1162. struct stat stats;
  1163. stat("/Storage/OCPP", &stats);
  1164. // Check for directory existence
  1165. if(S_ISDIR(stats.st_mode) == 1)
  1166. {
  1167. //DEBUG_INFO("\n OCPP directory exist \n");
  1168. }
  1169. else
  1170. {
  1171. DEBUG_INFO("\n directory not exist, create dir \n");
  1172. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP");
  1173. system(rmFileCmd);
  1174. }
  1175. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1176. if((access("/Storage/OCPP/MessageSent",F_OK))!=-1)
  1177. {
  1178. DEBUG_INFO("MessageSent file exist.\n");
  1179. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP/MessageSent");
  1180. system(rmFileCmd);
  1181. }
  1182. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1183. return 0;
  1184. }
  1185. static int changeChageWebSocketPingInterval = FALSE;
  1186. void ChageWebSocketPingInterval(int WebSocketPingInterval)
  1187. {
  1188. changeChageWebSocketPingInterval = TRUE;
  1189. }
  1190. //================================================
  1191. // Main process
  1192. //================================================
  1193. int main(void)
  1194. {
  1195. char rmFileCmd[100]={0};
  1196. struct stat stats;
  1197. DEBUG_INFO("Module_OcppBackend task initialization...\n");
  1198. //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);
  1199. if(ProcessShareMemory()== FAIL)
  1200. {
  1201. return FAIL;
  1202. }
  1203. // Check & create OCPP dir
  1204. stat("/Storage/OCPP", &stats);
  1205. if(S_ISDIR(stats.st_mode) != 1)
  1206. {
  1207. DEBUG_INFO("OCPP directory not exist, create dir \n");
  1208. sprintf(rmFileCmd,"mkdir -p /Storage/OCPP");
  1209. system(rmFileCmd);
  1210. }
  1211. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1212. // Create Process: Resend Transaction
  1213. pthread_create(&tid_ProcQueue, NULL, processTransactionQueue, NULL);
  1214. pthread_create(&tid_Watchdog, NULL, processWatchdog, NULL);
  1215. // Sqlite3 initial
  1216. sqlite3_config(SQLITE_CONFIG_URI,1);
  1217. if(sqlite3_open("file:/Storage/OCPP/charger.db", &db))
  1218. {
  1219. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1220. sqlite3_close( db );
  1221. exit(0);
  1222. }
  1223. else
  1224. {
  1225. DEBUG_INFO( "Opened database successfully\n");
  1226. }
  1227. //Create Table log buffer
  1228. if(sqlite3_exec(db, createsql, 0, 0, &errMsg) != SQLITE_OK)
  1229. {
  1230. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1231. return 0;
  1232. }
  1233. else
  1234. {
  1235. DEBUG_INFO( "Opened log buffer table successfully\n");
  1236. }
  1237. // Create Table OcppAuthCache
  1238. if(sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg) != SQLITE_OK)
  1239. {
  1240. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1241. return 0;
  1242. }
  1243. else
  1244. {
  1245. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1246. }
  1247. // Create Table OcppAuthLocal
  1248. if(sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg) != SQLITE_OK)
  1249. {
  1250. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1251. return 0;
  1252. }
  1253. else
  1254. {
  1255. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1256. }
  1257. initialConfigurationTable();
  1258. removeMessageSentFile();
  1259. for(;;)
  1260. {
  1261. startTimeDog = time((time_t*)NULL);
  1262. counterLwsRestart = 0;
  1263. // Connect server
  1264. if(ConnectionEstablished==0) // Check InternetConn 0: disconnected, 1: connected
  1265. {
  1266. isWebsocketSendable = 1;
  1267. SetOcppConnStatus(FALSE);
  1268. SetServerSign(FALSE);
  1269. InitialSystemValue();
  1270. if((time((time_t*)NULL)-startTime.connect) >= 30)
  1271. {
  1272. DEBUG_INFO("Server connecting...\n");
  1273. pthread_create(&tid_connectServer, NULL, ConnectWsServer, NULL);
  1274. startTime.connect=time((time_t*)NULL);
  1275. }
  1276. CheckSystemValue();
  1277. }
  1278. else
  1279. {
  1280. // Sign in
  1281. if((GetServerSign() == FALSE) &&
  1282. ( ((GetBootNotificationInterval() != 0) && ((time((time_t*)NULL)-startTime.bootNotification)>= GetBootNotificationInterval())) || ((time((time_t*)NULL)-startTime.bootNotification) >= defaultWaitingTime) ) )
  1283. {
  1284. sendBootNotificationRequest();
  1285. startTime.bootNotification=time((time_t*)NULL);
  1286. }
  1287. // On line operation
  1288. if(GetServerSign() == TRUE)
  1289. {
  1290. // Send message from queue
  1291. if((req_SendQueue == 1) && isWebsocketSendable)
  1292. {
  1293. queue_operation(QUEUE_OPERATION_SENT, "", "");
  1294. req_SendQueue = 0;
  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. DEBUG_INFO("GetOcppConnStatus() = %d\n", GetOcppConnStatus());
  1309. if(changeChageWebSocketPingInterval)
  1310. {
  1311. DEBUG_INFO("Websocket ping interval changed request.\n");
  1312. changeChageWebSocketPingInterval = FALSE;
  1313. }
  1314. lws_context_destroy(context);
  1315. ConnectionEstablished = 0;
  1316. context = NULL;
  1317. }
  1318. }
  1319. }
  1320. do
  1321. {
  1322. lws_service(context, 0);//timeout_ms
  1323. }while((SendBufLen>0) && (context!=NULL) && GetOcppConnStatus());
  1324. usleep(100000);
  1325. }
  1326. pthread_join(tid_ProcQueue, NULL);
  1327. pthread_join(tid_Watchdog, NULL);
  1328. return FAIL;
  1329. }