Module_OcppBackend.c 42 KB

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