Module_OcppBackend.c 43 KB

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