Module_OcppBackend.c 43 KB

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