Module_OcppBackend.c 42 KB

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