Module_OcppBackend.c 40 KB

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