Module_OcppBackend.c 46 KB

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