Module_OcppBackend.c 42 KB

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