Module_OcppBackend.c 43 KB

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