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