Module_OcppBackend.c 43 KB

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