Module_OcppBackend.c 43 KB

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