Module_OcppBackend.c 40 KB

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