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. default:
  324. DEBUG_INFO("Reason = %d\n", reason);
  325. break;
  326. }
  327. return 0;
  328. }
  329. static struct lws_protocols protocols[] =
  330. {
  331. {
  332. "ocpp1.6",
  333. OCPP16Callback,
  334. WEBSOCKET_BUFFER_SIZE,
  335. WEBSOCKET_BUFFER_SIZE,
  336. },
  337. {
  338. "ocpp2.0",
  339. OCPP16Callback,
  340. WEBSOCKET_BUFFER_SIZE,
  341. WEBSOCKET_BUFFER_SIZE,
  342. },
  343. {
  344. "ocpp1.6,ocpp2.0",
  345. OCPP16Callback,
  346. WEBSOCKET_BUFFER_SIZE,
  347. WEBSOCKET_BUFFER_SIZE,
  348. },
  349. {
  350. NULL, NULL, 0 /* End of list */
  351. }
  352. };
  353. void* ConnectWsServer(void* data) //int ConnectWsServer()
  354. {
  355. struct lws_context_creation_info ContextInfo;
  356. struct lws_client_connect_info ConnInfo;
  357. int use_ssl=0;
  358. counterConnect += 1;
  359. // If internet available synchronize datetime with ntp server
  360. if(GetInternetConn() == 1)
  361. {
  362. system("pkill ntpd");
  363. DEBUG_INFO("NTP synchronize with Microsoft\n", system("/usr/sbin/ntpd -nqp time.windows.com &"));
  364. DEBUG_INFO("NTP synchronize with China\n", system("/usr/sbin/ntpd -nqp cn.ntp.org.cn &"));
  365. DEBUG_INFO("NTP synchronize with Taiwan\n", system("/usr/sbin/ntpd -nqp tock.stdtime.gov.tw &"));
  366. DEBUG_INFO("NTP synchronize with Europe\n", system("/usr/sbin/ntpd -nqp 0.europe.pool.ntp.org &"));
  367. }
  368. if(context!=NULL)
  369. {
  370. pthread_detach(pthread_self());
  371. lws_context_destroy(context);
  372. ConnectionEstablished=0;
  373. context = NULL;
  374. }
  375. memset(&ContextInfo, 0, sizeof(struct lws_context_creation_info));
  376. if((GetOcppServerURL()==0) || (GetOcppPort() == 0) || (GetOcppPath()==0))
  377. {
  378. DEBUG_ERROR("OCPP URL is NULL or OCPP Port is zero or OCPP Path is NULL\n");
  379. goto end;
  380. }
  381. if((strcmp(OcppProtocol,"ws")==0)&&(strlen(OcppProtocol)== 2))
  382. {
  383. DEBUG_INFO("Web socket is non-security mode.\n");
  384. use_ssl=0;
  385. }
  386. else if((strcmp(OcppProtocol,"wss")==0)&&(strlen(OcppProtocol)== 3))
  387. {
  388. DEBUG_INFO("Web socket is security mode.\n");
  389. use_ssl=1;
  390. }
  391. ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
  392. ContextInfo.iface = NULL;
  393. ContextInfo.ssl_private_key_password = NULL;
  394. ContextInfo.ssl_cert_filepath = NULL;//"./ssl_key/client_cert.pem";
  395. ContextInfo.ssl_private_key_filepath = NULL;//"./ssl_key/client_key.pem";
  396. ContextInfo.ssl_ca_filepath = "/root/cacert.pem";//"./cacert.pem";
  397. ContextInfo.ssl_cipher_list = NULL; //use default one
  398. ContextInfo.gid = -1;
  399. ContextInfo.uid = -1;
  400. if(use_ssl)
  401. {
  402. ContextInfo.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT ;
  403. }
  404. ContextInfo.protocols = protocols;
  405. ContextInfo.timeout_secs = GetBackendConnectionTimeout();
  406. ContextInfo.ws_ping_pong_interval = GetWebSocketPingInterval();
  407. ContextInfo.ka_time = 20;
  408. ContextInfo.keepalive_timeout = 5;
  409. ContextInfo.ka_probes = 2;
  410. ContextInfo.ka_interval = 5;
  411. context = lws_create_context(&ContextInfo);
  412. if (context == NULL)
  413. {
  414. DEBUG_ERROR("lws_create_context NG");
  415. goto end;
  416. }
  417. memset(&ConnInfo,0,sizeof(struct lws_client_connect_info));
  418. // fill up below information
  419. ConnInfo.context = context;
  420. ConnInfo.address=(const char *)OcppHost;
  421. DEBUG_INFO("ConnInfo.address: %s\n", ConnInfo.address);
  422. ConnInfo.port = GetOcppPort();
  423. DEBUG_INFO("ConnInfo.port: %d\n", ConnInfo.port);
  424. ConnInfo.path=(const char *)OcppPath;
  425. DEBUG_INFO("ConnInfo.path: %s\n", ConnInfo.path);
  426. char addr_port[256] = { 0 };
  427. sprintf(addr_port, "%s:%u", ConnInfo.address, (ConnInfo.port & 65535) );
  428. ConnInfo.host= addr_port; // ConnInfo.address;//lws_canonical_hostname(context);
  429. //ConnInfo.origin="origin";
  430. ConnInfo.protocol = protocols[0].name;
  431. ConnInfo.ietf_version_or_minus_one = -1;
  432. if(use_ssl)
  433. {
  434. #ifdef TLS_VALID_CERT_EXPIRED
  435. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
  436. DEBUG_INFO("TLS does not allow expired certification.\n");
  437. #else
  438. ConnInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK | LCCSCF_ALLOW_EXPIRED;
  439. DEBUG_INFO("TLS allow expired certification.\n");
  440. #endif
  441. }
  442. wsi_client = lws_client_connect_via_info(&ConnInfo);
  443. if (!wsi_client)
  444. {
  445. DEBUG_ERROR("lws_client_connect_via_info NG\n");
  446. goto end;
  447. }
  448. counterConnect=0;
  449. DEBUG_INFO("counterConnect: %d\n", counterConnect);
  450. end:
  451. pthread_exit(NULL/*(void *) fname*/);
  452. }
  453. int isQueueOverSize()
  454. {
  455. FILE *fp;
  456. uint32_t file_size;
  457. uint8_t result = FALSE;
  458. fp = fopen("/Storage/OCPP_PH/TransactionRelatedQueue" , "r");
  459. if(fp != NULL)
  460. {
  461. fseek(fp, 0L, SEEK_END);
  462. file_size = ftell(fp);
  463. if(file_size > (500*1024*1024))
  464. {
  465. result = TRUE;
  466. DEBUG_WARN("Queue file over size.\n");
  467. }
  468. fclose(fp);
  469. }
  470. return result;
  471. }
  472. int showfront(char *uuid, char *data)
  473. {
  474. FILE *fp;
  475. int result = FALSE; // 1: TRUE 0:FALSE
  476. char str[QUEUE_MESSAGE_LENGTH]={0};
  477. char sstr[50]={ 0 };//sstr[200]={ 0 };
  478. int c = 0;
  479. char *loc;
  480. char rmFileCmd[100]={0};
  481. struct stat stats;
  482. stat("/Storage/OCPP_PH", &stats);
  483. // Check for directory existence
  484. if (S_ISDIR(stats.st_mode) == 1)
  485. {
  486. //DEBUG_INFO("\n OCPP directory exist \n");
  487. }
  488. else
  489. {
  490. DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  491. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP_PH");
  492. system(rmFileCmd);
  493. }
  494. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  495. if((access("/Storage/OCPP_PH/TransactionRelatedQueue",F_OK))!=-1)
  496. {
  497. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  498. }
  499. else
  500. {
  501. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  502. FILE *log = fopen("/Storage/OCPP_PH/TransactionRelatedQueue", "w+");
  503. if(log == NULL)
  504. {
  505. DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  506. return FALSE;
  507. }
  508. else
  509. {
  510. fclose(log);
  511. }
  512. }
  513. /* opening file for reading */
  514. fp = fopen("/Storage/OCPP_PH/TransactionRelatedQueue" , "r");
  515. if(fp == NULL) {
  516. DEBUG_INFO("Error opening TransactionRelatedQueue file");
  517. return FALSE;
  518. }
  519. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL ) {
  520. /* writing content to stdout */
  521. //DEBUG_INFO("str=%s",str);
  522. if ((str[0] == '\n')||(strcmp(str,"")==0))
  523. {
  524. DEBUG_INFO("It is a blank line");
  525. fclose(fp);
  526. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  527. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP_PH/TransactionRelatedQueue");
  528. system(rmFileCmd);
  529. result = FALSE;
  530. return result;
  531. }
  532. else
  533. {
  534. //puts(str);
  535. //----------------uuid--------------//
  536. loc = strstr(str, "\"");
  537. memset(sstr ,0, ARRAY_SIZE(sstr) );
  538. c = 0;
  539. while (loc[1+c] != '\"')
  540. {
  541. sstr[c] = loc[1+c];
  542. c++;
  543. }
  544. sstr[c] = '\0';
  545. //DEBUG_INFO("\n uuid:%s", sstr);
  546. //DEBUG_INFO("\n data:%s", str);
  547. strcpy(uuid,sstr);
  548. strcpy(data,str);
  549. result = TRUE;
  550. }
  551. }
  552. else
  553. {
  554. //DEBUG_INFO("queue is null\n");
  555. strcpy(uuid,"");
  556. strcpy(data,"");
  557. result = FALSE;
  558. }
  559. fclose(fp);
  560. return result;
  561. }
  562. int addq(char *uuid, char *data)
  563. {
  564. FILE *outfile;
  565. char rmFileCmd[100]={0};
  566. struct stat stats;
  567. stat("/Storage/OCPP_PH", &stats);
  568. DEBUG_INFO("addq\n");
  569. // Check for directory existence
  570. if (S_ISDIR(stats.st_mode) == 1)
  571. {
  572. //DEBUG_INFO("\n OCPP directory exist \n");
  573. }
  574. else
  575. {
  576. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  577. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP_PH");
  578. system(rmFileCmd);
  579. }
  580. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  581. if((access("/Storage/OCPP_PH/TransactionRelatedQueue",F_OK))!=-1)
  582. {
  583. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  584. }
  585. else
  586. {
  587. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  588. FILE *log = fopen("/Storage/OCPP_PH/TransactionRelatedQueue", "w+");
  589. if(log == NULL)
  590. {
  591. //DEBUG_INFO("Can't Create File TransactionRelatedQueue \n");
  592. return FALSE;
  593. }
  594. else
  595. {
  596. fclose(log);
  597. }
  598. }
  599. // open file for writing
  600. outfile = fopen ("/Storage/OCPP_PH/TransactionRelatedQueue", "a");
  601. DEBUG_INFO("data = %s\n",data);
  602. fputs(data, outfile);
  603. fputs("\n", outfile);
  604. fclose (outfile);
  605. TransactionQueueNum = TransactionQueueNum + 1;
  606. if(OfflineTransaction == 1) // 0: no offline Transaction 1: offline Transaction
  607. {
  608. OfflineTransactionQueueNum = OfflineTransactionQueueNum + 1;
  609. }
  610. DEBUG_INFO("add queue end\n");
  611. system("/bin/fsync -d /dev/mtdblock13;/bin/sync &");
  612. return FALSE;
  613. }
  614. //---------------- delq(): delete the top item --------------//
  615. int delq()
  616. {
  617. char tempfile[] = "/Storage/OCPP_PH/delqtemp.json";
  618. FILE *infile;
  619. FILE *outfile;
  620. int resultRename=0;
  621. char filename[60]={0};
  622. char rmFileCmd[100]={0};
  623. struct stat stats;
  624. stat("/Storage/OCPP_PH", &stats);
  625. DEBUG_INFO("delq()\n");
  626. // Check for directory existence
  627. if (S_ISDIR(stats.st_mode) == 1)
  628. {
  629. //DEBUG_INFO("\n OCPP directory exist \n");
  630. }
  631. else
  632. {
  633. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  634. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP_PH");
  635. system(rmFileCmd);
  636. }
  637. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  638. if((access("/Storage/OCPP_PH/TransactionRelatedQueue",F_OK))!=-1)
  639. {
  640. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  641. }
  642. else
  643. {
  644. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  645. FILE *log = fopen("/Storage/OCPP_PH/TransactionRelatedQueue", "w+");
  646. if(log == NULL)
  647. {
  648. //DEBUG_INFO("log is NULL\n");
  649. return 0;
  650. }
  651. else
  652. {
  653. fclose(log);
  654. }
  655. }
  656. // open file for writing
  657. strcpy(filename, "/Storage/OCPP_PH/TransactionRelatedQueue");
  658. infile = fopen ("/Storage/OCPP_PH/TransactionRelatedQueue", "r");
  659. outfile = fopen (tempfile, "w");
  660. /*检测到文件结束标识返回1,否则返回0。*/
  661. //DEBUG_INFO("feof(infile) =%d\n",feof(infile));
  662. int c;
  663. c = fgetc(infile);
  664. //printf("file c:%d\n",c);
  665. rewind(infile);
  666. if(c == EOF)
  667. {
  668. //DEBUG_INFO("TransactionRelatedQueue is NULL\n");
  669. fclose(infile);
  670. fclose(outfile);
  671. sprintf(rmFileCmd,"rm -f %s",tempfile);
  672. system(rmFileCmd);
  673. }
  674. else
  675. {
  676. char buf[QUEUE_MESSAGE_LENGTH]={0};
  677. int i = 0;
  678. //DEBUG_INFO("Orignal File is not NULL\n");
  679. while (fgets(buf, sizeof(buf), infile) != NULL)
  680. {
  681. //printf("Orignal File get strings \n");
  682. buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
  683. if(i==0)
  684. {
  685. TransactionQueueNum = TransactionQueueNum - 1;
  686. TransactionMessageResend = 1;
  687. DEBUG_INFO("delete the item\n");
  688. }
  689. if(i != 0)
  690. {
  691. fprintf(outfile,"%s\n", buf);
  692. }
  693. i = i + 1;
  694. }
  695. fclose(infile);
  696. fclose(outfile);
  697. sprintf(rmFileCmd,"rm -f %s",filename);
  698. system(rmFileCmd);
  699. resultRename = rename(tempfile, filename);
  700. if(resultRename == 0)
  701. {
  702. //DEBUG_INFO("TransactionRelatedQueue file renamed successfully");
  703. }
  704. else
  705. {
  706. //DEBUG_INFO("Error: unable to rename the TransactionRelatedQueue file");
  707. }
  708. DEBUG_INFO("delq() end\n");
  709. }
  710. system("/bin/fsync -d /dev/mtdblock13;/bin/sync &");
  711. return 0;
  712. }
  713. int showqueue()
  714. {
  715. char rmFileCmd[100]={0};
  716. struct stat stats;
  717. stat("/Storage/OCPP_PH", &stats);
  718. // Check for directory existence
  719. if (S_ISDIR(stats.st_mode) == 1)
  720. {
  721. //DEBUG_INFO("\n OCPP directory exist \n");
  722. }
  723. else
  724. {
  725. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  726. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP_PH");
  727. system(rmFileCmd);
  728. }
  729. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  730. if((access("/Storage/OCPP_PH/TransactionRelatedQueue",F_OK))!=-1)
  731. {
  732. //DEBUG_INFO("TransactionRelatedQueue exist.\n");
  733. }
  734. else
  735. {
  736. //DEBUG_INFO("TransactionRelatedQueue not exist\n");
  737. FILE *log = fopen("/Storage/OCPP_PH/TransactionRelatedQueue", "w+");
  738. if(log == NULL)
  739. {
  740. DEBUG_INFO("log is NULL\n");
  741. return FALSE;
  742. }
  743. else
  744. {
  745. fclose(log);
  746. }
  747. }
  748. FILE *fp = fopen("/Storage/OCPP_PH/TransactionRelatedQueue", "r");
  749. char line[QUEUE_MESSAGE_LENGTH]={0};
  750. // check if file exist (and you can open it) or not
  751. if (fp == NULL) {
  752. DEBUG_INFO("can open file TransactionRelatedQueue!");
  753. return FALSE;
  754. }
  755. TransactionQueueNum = 0; // the number of packets in queue
  756. while(fgets(line, sizeof line, fp) != NULL) {
  757. //DEBUG_INFO("%s\n", line);
  758. TransactionQueueNum = TransactionQueueNum + 1; //the number of packets in queue
  759. }
  760. fclose(fp);
  761. return TRUE;
  762. }
  763. int sentqueue(){
  764. FILE *fp;
  765. int result = FALSE; // 1: TRUE 0:FALSE
  766. int temptransactionId = 0, gettransactionId = 0;
  767. int tempconnectorId = 0;
  768. //int gunIndex = 0;
  769. char guid[37]={0};
  770. char tempdata[65]={0};
  771. char key_value[65]={0};
  772. int IsStopTransaction = FALSE;
  773. //int IsconnectorIdNULL = FALSE;
  774. //int IsIdtagNULL = FALSE;
  775. char str[QUEUE_MESSAGE_LENGTH]={0};
  776. char strcomposite[QUEUE_MESSAGE_LENGTH]={0};
  777. char rmFileCmd[100]={0};
  778. char connectorStr[2]={0};
  779. struct stat stats;
  780. char sstr[28]={0};
  781. unsigned char IdtagStr[20]={0};
  782. unsigned char timestampStr[30]={0};
  783. int tempmeterStart = 0;
  784. int tempreservationId = 0;
  785. int c = 0;
  786. char *loc;
  787. DEBUG_INFO("Sent queue.\n");
  788. stat("/Storage/OCPP_PH", &stats);
  789. // Check for directory existence
  790. if (S_ISDIR(stats.st_mode) == 1)
  791. {
  792. //DEBUG_INFO("\n OCPP directory exist \n");
  793. }
  794. else
  795. {
  796. //DEBUG_INFO("\n OCPP directory not exist, create dir \n");
  797. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP_PH");
  798. system(rmFileCmd);
  799. }
  800. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  801. /* opening file for reading */
  802. fp = fopen("/Storage/OCPP_PH/TransactionRelatedQueue" , "r");
  803. if(fp == NULL) {
  804. DEBUG_INFO("Error opening file");
  805. return FALSE;
  806. }
  807. if( fgets (str, QUEUE_MESSAGE_LENGTH, fp)!=NULL ) {
  808. //---- writing content to stdout ---//
  809. //*********************Start: StopTransaction***************************/
  810. loc = strstr(str, "StopTransaction");
  811. c = 0;
  812. memset(sstr ,0, ARRAY_SIZE(sstr) );
  813. if(loc != NULL)
  814. {
  815. IsStopTransaction = TRUE;
  816. }
  817. memset(connectorStr,0,ARRAY_SIZE(connectorStr));
  818. strncpy(connectorStr, str, 1);
  819. tempconnectorId = atoi(connectorStr);
  820. //*********************End: StopTransaction***************************/
  821. #if 0
  822. //*********************Start:connectorId***************************/
  823. loc = strstr(str, "connectorId");
  824. c = 0;
  825. memset(sstr ,0, ARRAY_SIZE(sstr) );
  826. if(loc != NULL)
  827. {
  828. while (loc[strlen("connectorId")+2+c] != ',')
  829. {
  830. sstr[c] = loc[strlen("connectorId")+2+c];
  831. c++;
  832. }
  833. sstr[c] = '\0';
  834. tempconnectorId = atoi(sstr);
  835. }
  836. // else
  837. // {
  838. // IsconnectorIdNULL = TRUE;
  839. // }
  840. //*********************End:connectorId***************************/
  841. #endif
  842. //*********************Start:idTag***************************/
  843. loc = strstr(str, "idTag");
  844. c = 0;
  845. memset(sstr ,0, ARRAY_SIZE(sstr) );
  846. if(loc != NULL)
  847. {
  848. while (loc[3+strlen("idTag")+c] != '\"')
  849. {
  850. sstr[c] = loc[3+strlen("idTag")+c];
  851. c++;
  852. }
  853. sstr[c] = '\0';
  854. strcpy((char*)IdtagStr, sstr);
  855. }
  856. // else
  857. // {
  858. // IsIdtagNULL = TRUE;
  859. // }
  860. //*********************End:idTag***************************/
  861. //*********************Start: StartTransaction***************************/
  862. loc = strstr(str, "StartTransaction");
  863. c = 0;
  864. memset(sstr ,0, ARRAY_SIZE(sstr) );
  865. if(loc != NULL)
  866. {
  867. // [2,0200000000000000000000000001584415776,StartTransaction,{connectorId:1,idTag:123,meterStart:100,reservationId:0,timestamp:2020-03-17T03:29:36Z}]
  868. //DEBUG_INFO("\n sent queue StartTransaction\n");
  869. if(tempconnectorId > 0)
  870. {
  871. sprintf(tempdata, "StartTransaction,%d", (tempconnectorId-1));
  872. }
  873. //GUID
  874. memset(sstr ,0, ARRAY_SIZE(sstr) );
  875. c=0;
  876. while (str[6+c] != '\"')
  877. {
  878. sstr[c] = str[6+c];
  879. c++;
  880. }
  881. sstr[c] = '\0';
  882. strcpy(guid, sstr);
  883. //Idtag
  884. loc = strstr(str, "idTag");
  885. memset(sstr ,0, ARRAY_SIZE(sstr) );
  886. c=0;
  887. while (loc[3+strlen("idTag")+c] != '\"')
  888. {
  889. sstr[c] = loc[3+strlen("idTag")+c];
  890. c++;
  891. }
  892. sstr[c] = '\0';
  893. strcpy((char*)IdtagStr, sstr);
  894. //meterStart
  895. loc = strstr(str, "meterStart");
  896. c = 0;
  897. memset(sstr ,0, ARRAY_SIZE(sstr) );
  898. if(loc != NULL)
  899. {
  900. while (loc[strlen("meterStart")+2+c] != ',')
  901. {
  902. sstr[c] = loc[strlen("meterStart")+2+c];
  903. c++;
  904. }
  905. sstr[c] = '\0';
  906. tempmeterStart = atoi(sstr);
  907. }
  908. //reservationId
  909. loc = strstr(str, "reservationId");
  910. c = 0;
  911. memset(sstr ,0, ARRAY_SIZE(sstr) );
  912. if(loc != NULL)
  913. {
  914. while (loc[strlen("reservationId")+2+c] != ',')
  915. {
  916. sstr[c] = loc[strlen("reservationId")+2+c];
  917. c++;
  918. }
  919. sstr[c] = '\0';
  920. tempreservationId = atoi(sstr);
  921. }
  922. //timestamp
  923. loc = strstr(str, "timestamp");
  924. memset(sstr ,0, ARRAY_SIZE(sstr) );
  925. c=0;
  926. while (loc[3+strlen("timestamp")+c] != '\"')
  927. {
  928. sstr[c] = loc[3+strlen("timestamp")+c];
  929. c++;
  930. }
  931. sstr[c] = '\0';
  932. strcpy((char*)timestampStr, sstr);
  933. if(hashmap_operation(HASH_OP_GET, guid, key_value) == TRUE)
  934. {
  935. //DEBUG_INFO("\n 1. sent queue guid=%s\n",guid);
  936. }
  937. else
  938. {
  939. hashmap_operation(HASH_OP_ADD, guid, tempdata);
  940. FillStartTransaction(tempconnectorId, IdtagStr, tempmeterStart, tempreservationId, timestampStr);
  941. //DEBUG_INFO("\n 2. sent queue guid=%s\n",guid);
  942. }
  943. }
  944. //*********************End: StartTransaction***************************/
  945. //****************transactionId********************/
  946. c=0;
  947. loc = strstr(str, "transactionId");
  948. memset(sstr ,0, ARRAY_SIZE(sstr) );
  949. if(loc != NULL)
  950. {
  951. // Only MeterValue with transactionId & StopTransaction will arrive here
  952. while ((loc[strlen("transactionId")+2+c] != '}') && (loc[strlen("transactionId")+2+c] != ','))
  953. {
  954. sstr[c] = loc[strlen("transactionId")+2+c];
  955. c++;
  956. }
  957. sstr[c] = '\0';
  958. temptransactionId = atoi(sstr);
  959. //Get IdTag from StartTransaction , store to StartTransactionIdTagTemp, For StopTransaction usage in Queue (StartTransaction. StopTransaction user id different), get actual TransactionId
  960. GetStartTransactionIdTag(tempconnectorId-1);
  961. gettransactionId = GetTransactionId(tempconnectorId, IdtagStr, IsStopTransaction);
  962. DEBUG_INFO("queue map transactionId = %d\n", gettransactionId);
  963. DEBUG_INFO("original connectorId = %d\n", tempconnectorId);
  964. DEBUG_INFO("original transactionId = %d\n", temptransactionId);
  965. DEBUG_INFO("original IdtagStr = %s\n", IdtagStr);
  966. if((gettransactionId != 0)&&(temptransactionId != gettransactionId))
  967. {
  968. //replace transactionId of metervalue or stopTransaction
  969. strncpy(strcomposite,str, (loc-str)+2+strlen("transactionId"));
  970. sprintf(strcomposite+((loc-str)+2+strlen("transactionId")),"%d",gettransactionId);
  971. strcat(strcomposite, loc+strlen("transactionId")+2+c); // 把 字串中transactionId後面的字串串接到 strcomposite後面
  972. LWS_Send(strcomposite+2); // skip 2 bytes String -> Connector ID,
  973. }
  974. else
  975. {
  976. LWS_Send(str+2); // skip 2 bytes String -> Connector ID
  977. gettransactionId = temptransactionId;
  978. }
  979. DEBUG_INFO("Final transactionId = %d\n", gettransactionId);
  980. if(IsStopTransaction == TRUE)//if((IsStopTransaction == TRUE)&&(gettransactionId != 0))
  981. {
  982. SetTransactionIdZero(gettransactionId);
  983. }
  984. }
  985. else
  986. {
  987. // MeterValue without transactionId & StartTransaction arrive here
  988. LWS_Send(str+2);
  989. }
  990. result = TRUE;
  991. }
  992. else
  993. {
  994. result = FALSE;
  995. }
  996. fclose(fp);
  997. return result;
  998. }
  999. void* processTransactionQueue(void* data)
  1000. {
  1001. char frontUUID[100] ={0};
  1002. char frontData[QUEUE_MESSAGE_LENGTH/*1024*4*/] ={0};
  1003. int queueNotEmpty = FALSE;
  1004. while(1)
  1005. {
  1006. if(!req_SendQueue && ((((time((time_t*)NULL) - startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))) || (isWebsocketSendable && ((time((time_t*)NULL) - startTimeQueue) >= ((counterQueueSent>=20)?5:0)))))
  1007. {
  1008. if(FirstHeartBeatResponse() == 1)
  1009. {
  1010. memset(frontUUID, 0, ARRAY_SIZE(frontUUID));
  1011. memset(frontData, 0, ARRAY_SIZE(frontData));
  1012. queueNotEmpty = FALSE;
  1013. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1014. if((queueNotEmpty == TRUE) && (GetOcppConnStatus() == 1)) //OcppConnStatus 0: disconnected, 1: connected
  1015. {
  1016. if(isWebsocketSendable)
  1017. DEBUG_INFO("isWebsocketSendable on.\n");
  1018. if((((time((time_t*)NULL) - startTimeQueue) > (TransactionMessageRetryIntervalGet()>10?TransactionMessageRetryIntervalGet():10))))
  1019. DEBUG_INFO("Queue timer(%d) over spec(%d).\n", (time((time_t*)NULL) - startTimeQueue), TransactionMessageRetryIntervalGet());
  1020. if((OfflineTransaction == 1) && (OfflineTransactionQueueNum != 0)) //OfflineTransaction 0: no offline Transaction 1: offline Transaction
  1021. {
  1022. DEBUG_INFO("Sent message from queue request off-line first.\n");
  1023. req_SendQueue = 1; // 0: no packets to send 1: send the top packet in queue
  1024. OfflineTransactionQueueNum = OfflineTransactionQueueNum - 1;
  1025. if(OfflineTransactionQueueNum == 0)
  1026. {
  1027. OfflineTransaction = 0;
  1028. }
  1029. }
  1030. else
  1031. {
  1032. if(TransactionMessageResend <= TransactionMessageAttemptsGet()) //
  1033. {
  1034. DEBUG_INFO("Sent message from queue request.\n");
  1035. DEBUG_INFO("TransactionMessageResend = %d\n",TransactionMessageResend);
  1036. req_SendQueue = 1;
  1037. TransactionMessageResend += 1;
  1038. }
  1039. else
  1040. {
  1041. DEBUG_INFO("Transaction message resend(%d) over spec(%d) message abandon.\n", TransactionMessageResend, TransactionMessageAttemptsGet());
  1042. queue_operation(QUEUE_OPERATION_DEL,"",""); //// delete item
  1043. TransactionMessageResend = 1;
  1044. }
  1045. }
  1046. }
  1047. }
  1048. if(GetOcppConnStatus() == 0)
  1049. {
  1050. if(queueNotEmpty == TRUE)
  1051. {
  1052. OfflineTransaction = 1; // 0: no offline Transaction 1: offline Transaction
  1053. }
  1054. }
  1055. // Refresh queue timer
  1056. startTimeQueue = time((time_t*)NULL);
  1057. if((counterQueueSent >= 10) || (queueNotEmpty == FALSE))
  1058. {
  1059. counterQueueSent = 0;
  1060. }
  1061. else
  1062. {
  1063. counterQueueSent += 1;
  1064. }
  1065. }
  1066. usleep(500000);
  1067. }
  1068. pthread_exit(NULL); //
  1069. return 0;
  1070. }
  1071. void* processWatchdog()
  1072. {
  1073. for(;;)
  1074. {
  1075. if(((time((time_t*)NULL) - startTimeDog) > 10) && (context != NULL))
  1076. {
  1077. DEBUG_INFO("LWS watch dog timeout.\n");
  1078. lws_cancel_service(context);
  1079. lws_cancel_service_pt(wsi_client);
  1080. if(counterLwsRestart >= 2)
  1081. {
  1082. DEBUG_INFO("LWS watch dog timeout over 3 count.\n");
  1083. system("pkill OcppBackend");
  1084. }
  1085. else
  1086. counterLwsRestart++;
  1087. startTimeDog = time((time_t*)NULL);
  1088. }
  1089. if(counterConnect >= 2)
  1090. {
  1091. DEBUG_INFO("Connect OCPP server timeout over 3 count.\n");
  1092. system("pkill OcppBackend");
  1093. }
  1094. /*
  1095. if(system("pidof -s Module_PhBackend > /dev/null") != 0)
  1096. {
  1097. DEBUG_INFO("Module_PhBackend not running, restart it.\r\n");
  1098. system("/root/Module_PhBackend &");
  1099. }*/
  1100. sleep(1);
  1101. }
  1102. pthread_exit(NULL); //
  1103. }
  1104. void CheckTransactionPacket(char *uuid)
  1105. {
  1106. char frontUUID[100]={0};
  1107. char frontData[QUEUE_MESSAGE_LENGTH]={0};
  1108. int queueNotEmpty = FALSE;
  1109. int cmpResult = 0;
  1110. queueNotEmpty = queue_operation(QUEUE_OPERATION_SHOWFRONT,frontUUID, frontData);//showfront(frontUUID, frontData); ---> remove temporally
  1111. if(queueNotEmpty == TRUE)
  1112. {
  1113. cmpResult = strcmp(frontUUID, uuid);
  1114. if (cmpResult == 0)
  1115. {
  1116. DEBUG_INFO("Receive queue response match.\n");
  1117. queue_operation(QUEUE_OPERATION_DEL,"","");//delq(); ---> remove temporally
  1118. TransactionMessageResend = 1;
  1119. }
  1120. else
  1121. DEBUG_INFO("Receive queue response mismatch.\n");
  1122. }
  1123. }
  1124. int queue_operation(int type, char *frontUUID, char *frontData)
  1125. {
  1126. int result=0;
  1127. while(1)
  1128. {
  1129. if (!IsUsing )
  1130. {
  1131. IsUsing = TRUE;
  1132. if(type == QUEUE_OPERATION_SHOWQUEUE) // show items in queue
  1133. {
  1134. result = showqueue();
  1135. }
  1136. else if(type == QUEUE_OPERATION_SHOWFRONT) // show first item
  1137. {
  1138. result = showfront(frontUUID, frontData);
  1139. }
  1140. else if(type == QUEUE_OPERATION_DEL) // delete item
  1141. {
  1142. result = delq();
  1143. }
  1144. else if(type == QUEUE_OPERATION_SENT) // sent items in queue
  1145. {
  1146. result = sentqueue();
  1147. }
  1148. else if(type == QUEUE_OPERATION_ADD) // add items to the queue
  1149. {
  1150. // If queue file over size only add start * stop transaction message
  1151. if(!isQueueOverSize() || (strstr(frontData, "MeterValues") == NULL))
  1152. {
  1153. result = addq(frontUUID, frontData);
  1154. }
  1155. }
  1156. IsUsing = FALSE;
  1157. break;
  1158. }
  1159. usleep(100000);
  1160. }
  1161. return result;
  1162. }
  1163. int removeMessageSentFile(void)
  1164. {
  1165. char rmFileCmd[100]={0};
  1166. struct stat stats;
  1167. stat("/Storage/OCPP_PH", &stats);
  1168. // Check for directory existence
  1169. if(S_ISDIR(stats.st_mode) == 1)
  1170. {
  1171. //DEBUG_INFO("\n OCPP directory exist \n");
  1172. }
  1173. else
  1174. {
  1175. DEBUG_INFO("\n directory not exist, create dir \n");
  1176. sprintf(rmFileCmd,"mkdir -p %s","/Storage/OCPP_PH");
  1177. system(rmFileCmd);
  1178. }
  1179. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1180. if((access("/Storage/OCPP_PH/MessageSent",F_OK))!=-1)
  1181. {
  1182. DEBUG_INFO("MessageSent file exist.\n");
  1183. sprintf(rmFileCmd,"rm -f %s","/Storage/OCPP_PH/MessageSent");
  1184. system(rmFileCmd);
  1185. }
  1186. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1187. return 0;
  1188. }
  1189. static int changeChageWebSocketPingInterval = FALSE;
  1190. void ChageWebSocketPingInterval(int WebSocketPingInterval)
  1191. {
  1192. changeChageWebSocketPingInterval = TRUE;
  1193. }
  1194. //================================================
  1195. // Main process
  1196. //================================================
  1197. int main(void)
  1198. {
  1199. char rmFileCmd[100]={0};
  1200. struct stat stats;
  1201. DEBUG_INFO("Module_OcppBackend task initialization...\n");
  1202. //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);
  1203. if(ProcessShareMemory()== FAIL)
  1204. {
  1205. return FAIL;
  1206. }
  1207. // Check & create OCPP dir
  1208. stat("/Storage/OCPP_PH", &stats);
  1209. if(S_ISDIR(stats.st_mode) != 1)
  1210. {
  1211. DEBUG_INFO("OCPP directory not exist, create dir \n");
  1212. sprintf(rmFileCmd,"mkdir -p /Storage/OCPP_PH");
  1213. system(rmFileCmd);
  1214. }
  1215. memset(rmFileCmd, 0, ARRAY_SIZE(rmFileCmd));
  1216. // Create Process: Resend Transaction
  1217. pthread_create(&tid_ProcQueue, NULL, processTransactionQueue, NULL);
  1218. pthread_create(&tid_Watchdog, NULL, processWatchdog, NULL);
  1219. // Sqlite3 initial
  1220. sqlite3_config(SQLITE_CONFIG_URI,1);
  1221. if(sqlite3_open("file:/Storage/OCPP_PH/charger.db", &db))
  1222. {
  1223. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1224. sqlite3_close( db );
  1225. exit(0);
  1226. }
  1227. else
  1228. {
  1229. DEBUG_INFO( "Opened database successfully\n");
  1230. }
  1231. //Create Table log buffer
  1232. if(sqlite3_exec(db, createsql, 0, 0, &errMsg) != SQLITE_OK)
  1233. {
  1234. DEBUG_INFO( "Create log buffer table error message: %s\n", errMsg);
  1235. return 0;
  1236. }
  1237. else
  1238. {
  1239. DEBUG_INFO( "Opened log buffer table successfully\n");
  1240. }
  1241. // Create Table OcppAuthCache
  1242. if(sqlite3_exec(db, sqlOcppAuthCache, 0, 0, &errMsg) != SQLITE_OK)
  1243. {
  1244. DEBUG_INFO( "Create OcppAuthCache error message: %s\n", errMsg);
  1245. return 0;
  1246. }
  1247. else
  1248. {
  1249. DEBUG_INFO( "Opened OcppAuthCache table successfully\n");
  1250. }
  1251. // Create Table OcppAuthLocal
  1252. if(sqlite3_exec(db, sqlOcppAuthLocal, 0, 0, &errMsg) != SQLITE_OK)
  1253. {
  1254. DEBUG_INFO( "Create Table OcppAuthLocal error %s\n",errMsg);
  1255. return 0;
  1256. }
  1257. else
  1258. {
  1259. DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
  1260. }
  1261. // Create Table Transaction
  1262. if(sqlite3_exec(db, sqlTransaction, 0, 0, &errMsg) != SQLITE_OK)
  1263. {
  1264. DEBUG_INFO( "Create Table ocpp_transaction_record error %s\n",errMsg);
  1265. return 0;
  1266. }
  1267. else
  1268. {
  1269. DEBUG_INFO( "Opened ocpp_transaction_record table successfully\n");
  1270. }
  1271. if(initialConfigurationTable() != PASS)
  1272. {
  1273. DEBUG_WARN("OCPPConfiguration version mismatch, upgrade it.\n");
  1274. system("rm -f /Storage/OCPP_PH/OCPPConfiguration");
  1275. initialConfigurationTable();
  1276. }
  1277. removeMessageSentFile();
  1278. for(;;)
  1279. {
  1280. startTimeDog = time((time_t*)NULL);
  1281. counterLwsRestart = 0;
  1282. // Connect server
  1283. if(ConnectionEstablished==0) // Check InternetConn 0: disconnected, 1: connected
  1284. {
  1285. isWebsocketSendable = 1;
  1286. SetOcppConnStatus(FALSE);
  1287. SetServerSign(FALSE);
  1288. InitialSystemValue();
  1289. if((time((time_t*)NULL)-startTime.connect) >= 30)
  1290. {
  1291. DEBUG_INFO("Server connecting...\n");
  1292. pthread_create(&tid_connectServer, NULL, ConnectWsServer, NULL);
  1293. startTime.connect=time((time_t*)NULL);
  1294. }
  1295. CheckSystemValue();
  1296. }
  1297. else
  1298. {
  1299. // Sign in
  1300. if((GetServerSign() == FALSE) &&
  1301. (isConnectorInitMode(0) != TRUE) &&
  1302. ( (GetBootNotificationInterval()>0) ? ((time((time_t*)NULL)-startTime.bootNotification) >= GetBootNotificationInterval()) : ((time((time_t*)NULL)-startTime.bootNotification) >= defaultWaitingTime) )
  1303. )
  1304. {
  1305. sendBootNotificationRequest();
  1306. startTime.bootNotification=time((time_t*)NULL);
  1307. }
  1308. // On line operation
  1309. if(GetServerSign() == TRUE)
  1310. {
  1311. // Send message from queue
  1312. if((req_SendQueue == 1) && isWebsocketSendable)
  1313. {
  1314. queue_operation(QUEUE_OPERATION_SENT, "", "");
  1315. req_SendQueue = 0;
  1316. }
  1317. // Check System Value
  1318. CheckSystemValue();
  1319. if(GetHeartBeatWithNOResponse() >= 30)
  1320. {
  1321. lws_context_destroy(context);
  1322. ConnectionEstablished = 0;
  1323. context = NULL;
  1324. SetHeartBeatWithNOResponse();
  1325. DEBUG_WARN("Heartbeat re-send over 30 count.\n");
  1326. }
  1327. if((changeChageWebSocketPingInterval == TRUE) || (GetOcppConnStatus() == 0))
  1328. {
  1329. if(((time((time_t*)NULL)-startTime.reConnect) >= 3) || ((time((time_t*)NULL)-startTime.reConnect) < 0))
  1330. {
  1331. DEBUG_INFO("GetOcppConnStatus() = %d\n", GetOcppConnStatus());
  1332. if(changeChageWebSocketPingInterval)
  1333. {
  1334. DEBUG_INFO("Websocket ping interval changed request.\n");
  1335. changeChageWebSocketPingInterval = FALSE;
  1336. }
  1337. lws_context_destroy(context);
  1338. ConnectionEstablished = 0;
  1339. context = NULL;
  1340. }
  1341. }
  1342. else
  1343. {
  1344. startTime.reConnect = time((time_t*)NULL);
  1345. }
  1346. }
  1347. }
  1348. do
  1349. {
  1350. lws_service(context, 0);//timeout_ms
  1351. }while((SendBufLen>0) && (context!=NULL) && GetOcppConnStatus());
  1352. refreshProcDogTimer();
  1353. usleep(100000);
  1354. }
  1355. pthread_join(tid_ProcQueue, NULL);
  1356. pthread_join(tid_Watchdog, NULL);
  1357. return FAIL;
  1358. }