ProtalServer.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. using EVCB_OCPP.Packet.Features;
  2. using EVCB_OCPP.Packet.Messages;
  3. using EVCB_OCPP.Packet.Messages.Basic;
  4. using EVCB_OCPP.Packet.Messages.Core;
  5. using EVCB_OCPP.WSServer.Dto;
  6. using EVCB_OCPP.WSServer.Helper;
  7. using EVCB_OCPP.WSServer.Message;
  8. using EVCB_OCPP.WSServer.Service;
  9. using Microsoft.Extensions.Hosting;
  10. using Newtonsoft.Json;
  11. using System.Data;
  12. using System.Diagnostics;
  13. using System.Xml.Linq;
  14. using NLog;
  15. using Microsoft.Extensions.Configuration;
  16. using System.Collections.Concurrent;
  17. using Microsoft.Extensions.Logging;
  18. using System.Net.WebSockets;
  19. using System.Net;
  20. using System.Text;
  21. using EVCB_OCPP.WSServer.Service.WsService;
  22. namespace EVCB_OCPP.WSServer
  23. {
  24. public class DestroyRequest : IRequest
  25. {
  26. public string Action { get; set; }
  27. public bool TransactionRelated()
  28. {
  29. return false;
  30. }
  31. public bool Validate()
  32. {
  33. return true;
  34. }
  35. }
  36. public class ProtalServer : IHostedService
  37. {
  38. //static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  39. public ProtalServer(
  40. ILogger<ProtalServer> logger
  41. , IConfiguration configuration
  42. , IMainDbService mainDbService
  43. , IConnectionLogdbService connectionLogdbService
  44. , LoadingBalanceService loadingBalanceService
  45. , ServerMessageService serverMessageService
  46. , WebDbService webDbService
  47. , ProfileHandler profileHandler
  48. , WebsocketService<WsClientData> websocketService
  49. , OuterHttpClient httpClient)
  50. {
  51. this.logger = logger;
  52. this.configuration = configuration;
  53. this.mainDbService = mainDbService;
  54. this.connectionLogdbService = connectionLogdbService;
  55. this.webDbService = webDbService;
  56. this.httpClient = httpClient;
  57. isInDocker = !string.IsNullOrEmpty(configuration["DOTNET_RUNNING_IN_CONTAINER"]);
  58. this.profileHandler = profileHandler;// new ProfileHandler(configuration, serviceProvider);
  59. this.websocketService = websocketService;
  60. this._loadingBalanceService = loadingBalanceService;// new LoadingBalanceService(mainDbConnectionFactory, webDbConnectionFactory);
  61. this.messageService = serverMessageService;
  62. WarmUpLog();
  63. }
  64. #region private fields
  65. private OuterHttpClient httpClient;
  66. private DateTime lastcheckdt = DateTime.UtcNow.AddSeconds(-20);
  67. private ConcurrentDictionary<string, WsClientData> clientDic = new ConcurrentDictionary<string, WsClientData>();
  68. //private readonly Object _lockClientDic = new object();
  69. private readonly Object _lockConfirmPacketList = new object();
  70. private readonly ILogger<ProtalServer> logger;
  71. private readonly IConfiguration configuration;
  72. private readonly IMainDbService mainDbService;
  73. private readonly IConnectionLogdbService connectionLogdbService;
  74. private readonly WebDbService webDbService;
  75. private readonly ProfileHandler profileHandler;
  76. private readonly WebsocketService<WsClientData> websocketService;
  77. private readonly bool isInDocker;
  78. private List<NeedConfirmMessage> needConfirmPacketList = new List<NeedConfirmMessage>();
  79. private DateTime checkUpdateDt = DateTime.UtcNow;
  80. private DateTime _CheckFeeDt = DateTime.UtcNow;
  81. private DateTime _CheckLBDt = DateTime.UtcNow;
  82. private DateTime _CheckDenyListDt = DateTime.UtcNow.AddDays(-1);
  83. private readonly LoadingBalanceService _loadingBalanceService;// = new LoadingBalanceService();
  84. private readonly ServerMessageService messageService;
  85. private List<StationInfoDto> _StationInfo = new List<StationInfoDto>();
  86. private readonly List<string> needConfirmActions = new List<string>()
  87. {
  88. "GetConfiguration",
  89. "ChangeConfiguration",
  90. "RemoteStartTransaction",
  91. "RemoteStopTransaction",
  92. "ChangeAvailability",
  93. "ClearCache",
  94. "DataTransfer",
  95. "Reset",
  96. "UnlockConnector",
  97. "TriggerMessage",
  98. "GetDiagnostics",
  99. "UpdateFirmware",
  100. "GetLocalListVersion",
  101. "SendLocalList",
  102. "SetChargingProfile",
  103. "ClearChargingProfile",
  104. "GetCompositeSchedule",
  105. "ReserveNow",
  106. "CancelReservation",
  107. "ExtendedTriggerMessage"
  108. };
  109. private readonly List<Profile> profiles = new List<Profile>()
  110. {
  111. new CoreProfile(),
  112. new FirmwareManagementProfile(),
  113. new ReservationProfile(),
  114. new RemoteTriggerProfile(),
  115. new SmartChargingProfile(),
  116. new LocalAuthListManagementProfile(),
  117. new SecurityProfile(),
  118. };
  119. #endregion
  120. //private OCPPWSServer appServer;
  121. //private WebApplication appApi;
  122. //private WebApplication yarpApp;
  123. internal Dictionary<string, WsClientData> GetClientDic()
  124. {
  125. Dictionary<string, WsClientData> toReturn = null;
  126. toReturn = new Dictionary<string, WsClientData>(clientDic);
  127. return toReturn;
  128. }
  129. internal List<NeedConfirmMessage> GetResendMessage()
  130. {
  131. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  132. lock (_lockConfirmPacketList)
  133. {
  134. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  135. }
  136. return sendMessages;
  137. }
  138. internal IReadOnlyList<Profile> Profiles => profiles.AsReadOnly();
  139. internal LoadingBalanceService LoadingBalanceService => _loadingBalanceService;
  140. internal ProfileHandler ProfileHandler => profileHandler;
  141. public async Task StartAsync(CancellationToken cancellationToken)
  142. {
  143. GlobalConfig.DenyModelNames = await webDbService.GetDenyModelNames();
  144. Start();
  145. return;
  146. }
  147. public Task StopAsync(CancellationToken cancellationToken)
  148. {
  149. Stop();
  150. return Task.CompletedTask;
  151. }
  152. internal void UpdateClientDisplayPrice(string key,string price)
  153. {
  154. clientDic[key].DisplayPrice = price;
  155. }
  156. internal void SendMsg(WsClientData session, string msg, string messageType, string errorMsg = "")
  157. {
  158. Send(session,msg,messageType,errorMsg);
  159. }
  160. internal void Start()
  161. {
  162. logger.LogTrace("Starting Server...");
  163. if (!GlobalConfig.LoadAPPConfig(configuration))
  164. {
  165. logger.LogError("Please check App.Config setting .");
  166. return;
  167. }
  168. StartWsService();
  169. if (!isInDocker)
  170. {
  171. Task consoleReadTask = new Task(RunConsoleInteractive);
  172. consoleReadTask.Start();
  173. //RunConsoleInteractive();
  174. return;
  175. }
  176. return;
  177. }
  178. private void RunConsoleInteractive()
  179. {
  180. while (true)
  181. {
  182. if (Console.In is null)
  183. {
  184. break;
  185. }
  186. var input = Console.ReadLine();
  187. switch (input.ToLower())
  188. {
  189. case "stop":
  190. Console.WriteLine("Command stop");
  191. Stop();
  192. break;
  193. case "gc":
  194. Console.WriteLine("Command GC");
  195. GC.Collect();
  196. break;
  197. case "lc":
  198. {
  199. Console.WriteLine("Command List Clients");
  200. Dictionary<string, WsClientData> _copyClientDic = null;
  201. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  202. var list = _copyClientDic.Select(c => c.Value).ToList();
  203. int i = 1;
  204. foreach (var c in list)
  205. {
  206. Console.WriteLine(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  207. i++;
  208. }
  209. }
  210. break;
  211. case "lcn":
  212. {
  213. Console.WriteLine("Command List Customer Name");
  214. Dictionary<string, WsClientData> _copyClientDic = null;
  215. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  216. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  217. int iLcn = 1;
  218. foreach (var c in lcn)
  219. {
  220. Console.WriteLine(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  221. iLcn++;
  222. }
  223. }
  224. break;
  225. case "help":
  226. Console.WriteLine("Command help!!");
  227. Console.WriteLine("lcn : List Customer Name");
  228. Console.WriteLine("gc : GC Collect");
  229. Console.WriteLine("lc : List Clients");
  230. Console.WriteLine("cls : clear console");
  231. Console.WriteLine("silent : silent");
  232. Console.WriteLine("show : show log");
  233. // logger.Info("rcl : show Real Connection Limit");
  234. break;
  235. case "cls":
  236. Console.WriteLine("Command clear");
  237. Console.Clear();
  238. break;
  239. case "silent":
  240. Console.WriteLine("Command silent");
  241. //var xe = XElement.Load("NLog.config");
  242. //var xns = xe.GetDefaultNamespace();
  243. //var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  244. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  245. //if (minlevelattr != null)
  246. //{
  247. // minlevelattr.Value = "Warn";
  248. //}
  249. //xe.Save("NLog.config");
  250. foreach (var rule in LogManager.Configuration.LoggingRules)
  251. {
  252. if (rule.RuleName != "ConsoleLog")
  253. {
  254. continue;
  255. }
  256. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  257. if (isTargetRule)
  258. {
  259. rule.SetLoggingLevels(NLog.LogLevel.Warn, NLog.LogLevel.Off);
  260. }
  261. }
  262. break;
  263. case "show":
  264. Console.WriteLine("Command show");
  265. //var xe1 = XElement.Load("NLog.config");
  266. //var xns1 = xe1.GetDefaultNamespace();
  267. //var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  268. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  269. //if (minlevelattr1 != null)
  270. //{
  271. // minlevelattr1.Value = "trace";
  272. //}
  273. //xe1.Save("NLog.config");
  274. foreach (var rule in LogManager.Configuration.LoggingRules)
  275. {
  276. if (rule.RuleName != "ConsoleLog")
  277. {
  278. continue;
  279. }
  280. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  281. if (isTargetRule)
  282. {
  283. rule.SetLoggingLevels(NLog.LogLevel.Trace, NLog.LogLevel.Off);
  284. }
  285. }
  286. break;
  287. case "rcl":
  288. break;
  289. default:
  290. break;
  291. }
  292. }
  293. }
  294. internal void Stop()
  295. {
  296. //appServer?.Stop();
  297. StopWsService();
  298. }
  299. private void StartWsService()
  300. {
  301. websocketService.ValidateHandshake = WebsocketServiceValidateHandshake;
  302. websocketService.NewSessionConnected += AppServer_NewSessionConnected;
  303. }
  304. private void StopWsService()
  305. {
  306. websocketService.ValidateHandshake = null;
  307. websocketService.NewSessionConnected -= AppServer_NewSessionConnected;
  308. }
  309. private async Task<bool> WebsocketServiceValidateHandshake(WsClientData session)
  310. {
  311. session.ISOCPP20 = session.SecWebSocketProtocol.ToLower().Contains("ocpp2.0");
  312. int securityProfile = 0;
  313. string authorizationKey = string.Empty;
  314. if (string.IsNullOrEmpty(session.Path))
  315. {
  316. //logger.Log();
  317. logger.LogWarning("===========================================");
  318. logger.LogWarning("session.Path EMPTY");
  319. logger.LogWarning("===========================================");
  320. }
  321. string[] words = session.Path.ToString().Split('/');
  322. session.ChargeBoxId = words.Last();
  323. foreach (var denyModel in GlobalConfig.DenyModelNames)
  324. {
  325. if (string.IsNullOrEmpty(denyModel))
  326. {
  327. continue;
  328. }
  329. if (session.ChargeBoxId.StartsWith(denyModel))
  330. {
  331. StringBuilder responseBuilder = new StringBuilder();
  332. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  333. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  334. responseBuilder.AppendWithCrCf();
  335. string sb = responseBuilder.ToString();
  336. byte[] data = Encoding.UTF8.GetBytes(sb);
  337. session.SendRawData(data, 0, data.Length);
  338. logger.LogTrace(sb);
  339. return false;
  340. }
  341. }
  342. if (configuration["MaintainMode"] == "1")
  343. {
  344. session.ChargeBoxId = session.ChargeBoxId + "_2";
  345. }
  346. logger.LogInformation(string.Format("ValidateHandshake: {0}", session.Path));
  347. bool isExistedSN = false;
  348. bool authorizated = false;
  349. var info = mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId).Result;
  350. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  351. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  352. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  353. //session.MachineId = machine == null ? String.Empty : machine.Id;
  354. //isExistedSN = machine == null ? false : true;
  355. session.CustomerName = info.CustomerName;
  356. session.CustomerId = info.CustomerId;
  357. session.MachineId = info.MachineId;
  358. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  359. if (!isExistedSN)
  360. {
  361. StringBuilder responseBuilder = new StringBuilder();
  362. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  363. (int)HttpStatusCode.NotFound, @"Not Found");
  364. responseBuilder.AppendWithCrCf();
  365. string sb = responseBuilder.ToString();
  366. byte[] data = Encoding.UTF8.GetBytes(sb);
  367. session.SendRawData(data, 0, data.Length);
  368. logger.LogInformation(sb);
  369. return false;
  370. }
  371. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  372. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  373. var configVaule = mainDbService.GetMachineSecurityProfile(session.ChargeBoxId).Result;
  374. int.TryParse(configVaule, out securityProfile);
  375. if (session.ISOCPP20)
  376. {
  377. // 1.6 server only support change server function
  378. securityProfile = 0;
  379. }
  380. if (securityProfile == 3 && session.UriScheme == "ws")
  381. {
  382. StringBuilder responseBuilder = new StringBuilder();
  383. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  384. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  385. responseBuilder.AppendWithCrCf();
  386. string sb = responseBuilder.ToString();
  387. byte[] data = Encoding.UTF8.GetBytes(sb);
  388. session.SendRawData(data, 0, data.Length);
  389. logger.LogInformation(sb);
  390. return false;
  391. }
  392. if (securityProfile == 1 || securityProfile == 2)
  393. {
  394. if (securityProfile == 2 && session.UriScheme == "ws")
  395. {
  396. authorizated = false;
  397. }
  398. //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  399. if (!string.IsNullOrEmpty(session.AuthHeader))
  400. {
  401. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  402. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  403. authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId);
  404. if (session.ISOCPP20)
  405. {
  406. // 1.6 server only support change server function
  407. securityProfile = 0;
  408. }
  409. logger.LogInformation("***********Authorization ");
  410. if (!string.IsNullOrEmpty(authorizationKey))
  411. {
  412. //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  413. string base64Encoded = session.AuthHeader.Replace("Basic ", "");
  414. byte[] data = Convert.FromBase64String(base64Encoded);
  415. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  416. logger.LogInformation("***********Authorization " + Encoding.ASCII.GetString(data));
  417. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  418. {
  419. authorizated = true;
  420. }
  421. }
  422. }
  423. else
  424. {
  425. authorizated = true;
  426. }
  427. if (!authorizated)
  428. {
  429. StringBuilder responseBuilder = new StringBuilder();
  430. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  431. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  432. responseBuilder.AppendWithCrCf();
  433. string sb = responseBuilder.ToString();
  434. byte[] data = Encoding.UTF8.GetBytes(sb);
  435. session.SendRawData(data, 0, data.Length);
  436. logger.LogInformation(sb);
  437. return false;
  438. }
  439. }
  440. logger.LogInformation(string.Format("ValidateHandshake PASS: {0}", session.Path));
  441. return true;
  442. }
  443. private async void AppServer_NewSessionConnected(object sender, WsClientData session)
  444. {
  445. logger.LogDebug(string.Format("{0} NewSessionConnected", session.Path));
  446. try
  447. {
  448. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  449. if (isNotSupported)
  450. {
  451. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  452. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  453. return;
  454. }
  455. TryRemoveDuplicatedSession(session);
  456. clientDic[session.ChargeBoxId] = session;
  457. session.SessionClosed += AppServer_SessionClosed;
  458. session.m_ReceiveData += ReceivedMessageTimeLimited;
  459. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  460. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  461. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.Origin.Contains("https") ? 2 : 1);
  462. }
  463. catch (Exception ex)
  464. {
  465. logger.LogError(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  466. }
  467. }
  468. private void AppServer_SessionClosed(object sender, CloseReason closeReason)
  469. {
  470. if (sender is not WsClientData session)
  471. {
  472. return;
  473. }
  474. session.SessionClosed -= AppServer_SessionClosed;
  475. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  476. WriteMachineLog(session, string.Format("CloseReason: {0}", closeReason), "Connection", "");
  477. RemoveClient(session);
  478. }
  479. private void TryRemoveDuplicatedSession(WsClientData session)
  480. {
  481. if (clientDic.ContainsKey(session.ChargeBoxId))
  482. {
  483. var oldSession = clientDic[session.ChargeBoxId];
  484. WriteMachineLog(oldSession, "Duplicate Logins", "Connection", "");
  485. RemoveClient(oldSession);
  486. }
  487. }
  488. async private void ReceivedMessageTimeLimited(object sender , string rawdata)
  489. {
  490. if (sender is not WsClientData session)
  491. {
  492. return;
  493. }
  494. CancellationTokenSource tokenSource = new();
  495. var task = ReceivedMessage(session, rawdata);
  496. var completedTask = await Task.WhenAny(task, Task.Delay(90_000, tokenSource.Token));
  497. if (completedTask != task)
  498. {
  499. logger.LogCritical("Process timeout: {0} ", rawdata);
  500. await task;
  501. return;
  502. }
  503. tokenSource.Cancel();
  504. return;
  505. }
  506. async private Task ReceivedMessage(WsClientData session, string rawdata)
  507. {
  508. try
  509. {
  510. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  511. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  512. WriteMachineLog(session, rawdata,
  513. string.Format("{0} {1}", string.IsNullOrEmpty(analysisResult.Action) ? "unknown" : analysisResult.Action, analysisResult.Id == 2 ? "Request" : (analysisResult.Id == 3 ? "Confirmation" : "Error")), analysisResult.Exception == null ? "" : analysisResult.Exception.Message);
  514. if (session.ResetSecurityProfile)
  515. {
  516. logger.LogError(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  517. RemoveClient(session);
  518. return;
  519. }
  520. if (!analysisResult.Success)
  521. {
  522. //解析RawData就發生錯誤
  523. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  524. {
  525. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  526. }
  527. else
  528. {
  529. if (analysisResult.Message == null)
  530. {
  531. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  532. string errorMsg = string.Empty;
  533. if (analysisResult.Exception != null)
  534. {
  535. errorMsg = analysisResult.Exception.ToString();
  536. }
  537. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  538. }
  539. else
  540. {
  541. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  542. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  543. string errorMsg = string.Empty;
  544. if (analysisResult.Exception != null)
  545. {
  546. errorMsg = analysisResult.Exception.ToString();
  547. }
  548. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  549. }
  550. }
  551. }
  552. else
  553. {
  554. switch (analysisResult.Id)
  555. {
  556. case BasicMessageHandler.TYPENUMBER_CALL:
  557. {
  558. if (!session.ISOCPP20)
  559. {
  560. Actions action = Convertor.GetAction(analysisResult.Action);
  561. try
  562. {
  563. await ProcessRequestMessage(analysisResult, session, action);
  564. }
  565. catch (Exception e)
  566. {
  567. logger.LogError($"Processing {action} exception!");
  568. throw;
  569. }
  570. }
  571. else
  572. {
  573. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  574. MessageResult result = new MessageResult() { Success = true };
  575. //ocpp20 處理
  576. switch (action)
  577. {
  578. case EVCB_OCPP20.Packet.Features.Actions.BootNotification:
  579. {
  580. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  581. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  582. result.Message = confirm;
  583. result.Success = true;
  584. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  585. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  586. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  587. {
  588. ConfigurationSlot = 1,
  589. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  590. {
  591. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  592. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  593. MessageTimeout = 30,
  594. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  595. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  596. }
  597. };
  598. var uuid = session.queue20.store(request);
  599. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  600. Send(session, requestText, "SetNetworkProfile");
  601. }
  602. break;
  603. default:
  604. {
  605. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  606. }
  607. break;
  608. }
  609. }
  610. }
  611. break;
  612. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  613. {
  614. if (!session.ISOCPP20)
  615. {
  616. Actions action = Convertor.GetAction(analysisResult.Action);
  617. ProcessConfirmationMessage(analysisResult, session, action);
  618. }
  619. else
  620. {
  621. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  622. MessageResult result = new MessageResult() { Success = true };
  623. //ocpp20 處理
  624. switch (action)
  625. {
  626. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  627. {
  628. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  629. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  630. {
  631. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  632. {
  633. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  634. {
  635. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  636. {
  637. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  638. {
  639. Name="OCPPCommCtrlr",
  640. },
  641. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  642. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  643. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  644. {
  645. Name="NetworkConfigurationPriority",
  646. }
  647. }
  648. }
  649. };
  650. var uuid = session.queue20.store(request);
  651. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  652. Send(session, requestText, "SetVariables");
  653. }
  654. }
  655. break;
  656. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  657. {
  658. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  659. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  660. {
  661. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  662. {
  663. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  664. };
  665. var uuid = session.queue20.store(request);
  666. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  667. Send(session, requestText, "Reset");
  668. }
  669. }
  670. break;
  671. default:
  672. {
  673. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  674. }
  675. break;
  676. }
  677. }
  678. }
  679. break;
  680. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  681. {
  682. //只處理 丟出Request 收到Error的訊息
  683. if (analysisResult.Success && analysisResult.Message != null)
  684. {
  685. Actions action = Convertor.GetAction(analysisResult.Action);
  686. ProcessErrorMessage(analysisResult, session, action);
  687. }
  688. }
  689. break;
  690. default:
  691. {
  692. logger.LogError(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  693. }
  694. break;
  695. }
  696. }
  697. await Task.Delay(10);
  698. }
  699. catch (Exception ex)
  700. {
  701. if (ex.InnerException != null)
  702. {
  703. logger.LogError(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  704. }
  705. else
  706. {
  707. logger.LogError(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  708. }
  709. }
  710. }
  711. private async Task ProcessRequestMessage(MessageResult analysisResult, WsClientData session, Actions action)
  712. {
  713. Stopwatch outter_stopwatch = Stopwatch.StartNew();
  714. //BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  715. if (!session.IsCheckIn && action != Actions.BootNotification)
  716. {
  717. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  718. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  719. return;
  720. }
  721. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  722. switch (profileName)
  723. {
  724. case "Core":
  725. {
  726. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  727. var sendTimer = Stopwatch.StartNew();
  728. if (replyResult.Success)
  729. {
  730. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  731. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception is null ? string.Empty : replyResult.Exception.ToString());
  732. if (action == Actions.BootNotification
  733. && replyResult.Message is BootNotificationConfirmation bootNotificationConfirmation)
  734. {
  735. if (bootNotificationConfirmation.status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  736. {
  737. session.IsCheckIn = true;
  738. await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId);
  739. await messageService.SendChangeConfigurationRequest(
  740. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  741. }
  742. else
  743. {
  744. bool? isAC = await mainDbService.GetChargeBoxIdIsAc(session.ChargeBoxId);
  745. if (isAC is not null)
  746. {
  747. session.IsAC = isAC.Value;
  748. }
  749. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.Origin.Contains("https") ? 2 : 1);
  750. await webDbService.SetDefaultFee(session);
  751. }
  752. }
  753. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  754. {
  755. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  756. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  757. {
  758. await messageService.SendDataTransferRequest(
  759. session.ChargeBoxId,
  760. messageId: "SetUserPrice",
  761. vendorId:"Phihong Technology",
  762. data: JsonConvert.SerializeObject(
  763. new
  764. {
  765. idToken = authorizeRequest.idTag,
  766. price = session.UserDisplayPrices[authorizeRequest.idTag]
  767. })
  768. );
  769. }
  770. }
  771. }
  772. else
  773. {
  774. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  775. {
  776. //do nothing
  777. }
  778. else
  779. {
  780. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  781. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  782. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  783. }
  784. }
  785. sendTimer.Stop();
  786. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  787. {
  788. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  789. }
  790. if (action == Actions.StartTransaction)
  791. {
  792. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  793. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  794. if (_powerDic != null)
  795. {
  796. foreach (var kv in _powerDic)
  797. {
  798. try
  799. {
  800. if (kv.Value.HasValue)
  801. {
  802. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  803. }
  804. }
  805. catch (Exception ex)
  806. {
  807. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  808. }
  809. }
  810. }
  811. }
  812. if (action == Actions.StopTransaction)
  813. {
  814. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  815. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  816. if (_powerDic != null)
  817. {
  818. foreach (var kv in _powerDic)
  819. {
  820. try
  821. {
  822. if (kv.Value.HasValue)
  823. {
  824. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  825. }
  826. }
  827. catch (Exception ex)
  828. {
  829. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  830. }
  831. }
  832. }
  833. }
  834. }
  835. break;
  836. case "FirmwareManagement":
  837. {
  838. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  839. if (replyResult.Success)
  840. {
  841. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  842. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  843. }
  844. else
  845. {
  846. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  847. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  848. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  849. }
  850. }
  851. break;
  852. case "Security":
  853. {
  854. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  855. if (replyResult.Success)
  856. {
  857. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  858. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  859. }
  860. else
  861. {
  862. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  863. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  864. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  865. }
  866. }
  867. break;
  868. default:
  869. {
  870. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  871. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  872. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  873. }
  874. break;
  875. }
  876. outter_stopwatch.Stop();
  877. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  878. {
  879. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  880. }
  881. }
  882. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  883. {
  884. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  885. if (await ReConfirmMessage(analysisResult))
  886. {
  887. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  888. MessageResult confirmResult = null;
  889. switch (profileName)
  890. {
  891. case "Core":
  892. {
  893. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  894. }
  895. break;
  896. case "FirmwareManagement":
  897. {
  898. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  899. }
  900. break;
  901. case "RemoteTrigger":
  902. {
  903. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  904. }
  905. break;
  906. case "Reservation":
  907. {
  908. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  909. }
  910. break;
  911. case "LocalAuthListManagement":
  912. {
  913. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  914. }
  915. break;
  916. case "SmartCharging":
  917. {
  918. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  919. }
  920. break;
  921. case "Security":
  922. {
  923. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  924. }
  925. break;
  926. default:
  927. {
  928. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  929. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  930. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  931. }
  932. break;
  933. }
  934. if (confirmResult == null || !confirmResult.Success)
  935. {
  936. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  937. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  938. }
  939. }
  940. else
  941. {
  942. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  943. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  944. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  945. }
  946. }
  947. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  948. {
  949. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  950. if (await ReConfirmMessage(analysisResult))
  951. {
  952. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  953. switch (profileName)
  954. {
  955. case "Core":
  956. {
  957. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  958. }
  959. break;
  960. case "FirmwareManagement":
  961. {
  962. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  963. }
  964. break;
  965. case "RemoteTrigger":
  966. {
  967. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  968. }
  969. break;
  970. case "Reservation":
  971. {
  972. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  973. }
  974. break;
  975. case "LocalAuthListManagement":
  976. {
  977. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  978. }
  979. break;
  980. case "SmartCharging":
  981. {
  982. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  983. }
  984. break;
  985. default:
  986. {
  987. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  988. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  989. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  990. }
  991. break;
  992. }
  993. }
  994. else
  995. {
  996. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  997. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  998. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  999. }
  1000. }
  1001. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  1002. {
  1003. try
  1004. {
  1005. if (session != null)
  1006. {
  1007. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1008. session.Send(msg);
  1009. }
  1010. }
  1011. catch (Exception ex)
  1012. {
  1013. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  1014. }
  1015. }
  1016. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1017. {
  1018. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1019. _needConfirmMsg.Id = table_id;
  1020. _needConfirmMsg.SentAction = action;
  1021. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1022. _needConfirmMsg.SentTimes = 4;
  1023. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1024. _needConfirmMsg.RequestId = requestId;
  1025. _needConfirmMsg.SentUniqueId = msg_id;
  1026. _needConfirmMsg.CreatedBy = createdBy;
  1027. _needConfirmMsg.SentMessage = sendMessage;
  1028. if (needConfirmActions.Contains(action))
  1029. {
  1030. lock (_lockConfirmPacketList)
  1031. {
  1032. needConfirmPacketList.Add(_needConfirmMsg);
  1033. }
  1034. }
  1035. }
  1036. internal void RemoveConfirmMessage()
  1037. {
  1038. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1039. lock (_lockConfirmPacketList)
  1040. {
  1041. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1042. foreach (var item in removeList)
  1043. {
  1044. needConfirmPacketList.Remove(item);
  1045. }
  1046. }
  1047. }
  1048. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1049. {
  1050. bool confirmed = false;
  1051. if (needConfirmActions.Contains(analysisResult.Action))
  1052. {
  1053. NeedConfirmMessage foundRequest = null;
  1054. lock (_lockConfirmPacketList)
  1055. {
  1056. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1057. }
  1058. if (foundRequest != null && foundRequest.Id > 0)
  1059. {
  1060. foundRequest.SentTimes = 0;
  1061. foundRequest.SentInterval = 0;
  1062. analysisResult.RequestId = foundRequest.RequestId;
  1063. await mainDbService.UpdateServerMessage(foundRequest.Id, inMessage: JsonConvert.SerializeObject(analysisResult.Message, Formatting.None), receivedOn: DateTime.UtcNow);
  1064. confirmed = true;
  1065. }
  1066. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1067. {
  1068. confirmed = true;
  1069. }
  1070. else
  1071. {
  1072. logger.LogError(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1073. }
  1074. }
  1075. return confirmed;
  1076. }
  1077. internal async void RemoveClient(WsClientData session)
  1078. {
  1079. if (session is null)
  1080. {
  1081. return;
  1082. }
  1083. if (!string.IsNullOrEmpty(session.MachineId))
  1084. logger.LogTrace("RemoveClient[" + session.ChargeBoxId + "]");
  1085. RemoveClientDic(session);
  1086. try
  1087. {
  1088. if (session.State == WebSocketState.Open)
  1089. {
  1090. await session.Close(CloseReason.ServerShutdown);
  1091. }
  1092. //session.m_ReceiveData -= ReceivedMessageTimeLimited;
  1093. // session.Close(CloseReason.ServerShutdown);
  1094. }
  1095. catch (Exception ex)
  1096. {
  1097. //logger.LogWarning("Close client socket error!!");
  1098. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1099. }
  1100. }
  1101. private void RemoveClientDic(WsClientData session)
  1102. {
  1103. if (string.IsNullOrEmpty(session.ChargeBoxId) ||
  1104. !clientDic.ContainsKey(session.ChargeBoxId) ||
  1105. clientDic[session.ChargeBoxId].SessionID != session.SessionID)
  1106. {
  1107. return;
  1108. }
  1109. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1110. clientDic.Remove(session.ChargeBoxId, out _);
  1111. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1112. }
  1113. private void WarmUpLog()
  1114. {
  1115. connectionLogdbService.WarmUpLog();
  1116. }
  1117. private void WriteMachineLog(WsClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1118. {
  1119. try
  1120. {
  1121. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1122. if (clientData.ChargeBoxId == null)
  1123. {
  1124. logger.LogCritical(clientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1125. }
  1126. connectionLogdbService.WriteMachineLog(clientData, data, messageType, errorMsg, isSent);
  1127. }
  1128. catch (Exception ex)
  1129. {
  1130. //Console.WriteLine(ex.ToString());
  1131. logger.LogError(ex,ex.Message);
  1132. }
  1133. }
  1134. }
  1135. }