Module_OcppBackend.c 41 KB

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