Module_OcppBackend.c 39 KB

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