Module_OcppBackend.c 46 KB

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