Module_OcppBackend.c 45 KB

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