Module_OcppBackend.c 40 KB

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