ProtalServer.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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. , OcppWebsocketService 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 OcppWebsocketService 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. logger.LogDebug("{0}:{1}", session.ChargeBoxId, session.UriScheme);
  324. foreach (var denyModel in GlobalConfig.DenyModelNames)
  325. {
  326. if (string.IsNullOrEmpty(denyModel))
  327. {
  328. continue;
  329. }
  330. if (session.ChargeBoxId.StartsWith(denyModel))
  331. {
  332. StringBuilder responseBuilder = new StringBuilder();
  333. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  334. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  335. responseBuilder.AppendWithCrCf();
  336. string sb = responseBuilder.ToString();
  337. byte[] data = Encoding.UTF8.GetBytes(sb);
  338. await session.Send(data, 0, data.Length);
  339. logger.LogTrace(sb);
  340. return false;
  341. }
  342. }
  343. if (configuration["MaintainMode"] == "1")
  344. {
  345. session.ChargeBoxId = session.ChargeBoxId + "_2";
  346. }
  347. logger.LogInformation(string.Format("ValidateHandshake: {0}", session.Path));
  348. bool isExistedSN = false;
  349. bool authorizated = false;
  350. var info = mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId).Result;
  351. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  352. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  353. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  354. //session.MachineId = machine == null ? String.Empty : machine.Id;
  355. //isExistedSN = machine == null ? false : true;
  356. session.CustomerName = info.CustomerName;
  357. session.CustomerId = info.CustomerId;
  358. session.MachineId = info.MachineId;
  359. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  360. if (!isExistedSN)
  361. {
  362. StringBuilder responseBuilder = new StringBuilder();
  363. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  364. (int)HttpStatusCode.NotFound, @"Not Found");
  365. responseBuilder.AppendWithCrCf();
  366. string sb = responseBuilder.ToString();
  367. byte[] data = Encoding.UTF8.GetBytes(sb);
  368. await session.Send(data, 0, data.Length);
  369. logger.LogInformation(sb);
  370. return false;
  371. }
  372. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  373. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  374. var configVaule = mainDbService.GetMachineSecurityProfile(session.ChargeBoxId).Result;
  375. int.TryParse(configVaule, out securityProfile);
  376. if (session.ISOCPP20)
  377. {
  378. // 1.6 server only support change server function
  379. securityProfile = 0;
  380. }
  381. if (securityProfile == 3 && session.UriScheme == "ws")
  382. {
  383. StringBuilder responseBuilder = new StringBuilder();
  384. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  385. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  386. responseBuilder.AppendWithCrCf();
  387. string sb = responseBuilder.ToString();
  388. byte[] data = Encoding.UTF8.GetBytes(sb);
  389. await session.Send(data, 0, data.Length);
  390. logger.LogInformation(sb);
  391. return false;
  392. }
  393. if (securityProfile == 1 || securityProfile == 2)
  394. {
  395. if (securityProfile == 2 && session.UriScheme == "ws")
  396. {
  397. authorizated = false;
  398. }
  399. //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  400. if (!string.IsNullOrEmpty(session.AuthHeader))
  401. {
  402. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  403. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  404. authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId);
  405. if (session.ISOCPP20)
  406. {
  407. // 1.6 server only support change server function
  408. securityProfile = 0;
  409. }
  410. logger.LogInformation("***********Authorization ");
  411. if (!string.IsNullOrEmpty(authorizationKey))
  412. {
  413. //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  414. string base64Encoded = session.AuthHeader.Replace("Basic ", "");
  415. byte[] data = Convert.FromBase64String(base64Encoded);
  416. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  417. logger.LogInformation("***********Authorization " + Encoding.ASCII.GetString(data));
  418. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  419. {
  420. authorizated = true;
  421. }
  422. }
  423. }
  424. else
  425. {
  426. authorizated = true;
  427. }
  428. if (!authorizated)
  429. {
  430. StringBuilder responseBuilder = new StringBuilder();
  431. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  432. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  433. responseBuilder.AppendWithCrCf();
  434. string sb = responseBuilder.ToString();
  435. byte[] data = Encoding.UTF8.GetBytes(sb);
  436. await session.Send(data, 0, data.Length);
  437. logger.LogInformation(sb);
  438. return false;
  439. }
  440. }
  441. logger.LogInformation(string.Format("ValidateHandshake PASS: {0}", session.Path));
  442. return true;
  443. }
  444. private async void AppServer_NewSessionConnected(object sender, WsClientData session)
  445. {
  446. logger.LogDebug(string.Format("{0} NewSessionConnected", session.Path));
  447. try
  448. {
  449. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  450. if (isNotSupported)
  451. {
  452. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  453. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  454. return;
  455. }
  456. TryRemoveDuplicatedSession(session);
  457. clientDic[session.ChargeBoxId] = session;
  458. session.SessionClosed += AppServer_SessionClosed;
  459. session.m_ReceiveData += ReceivedMessageTimeLimited;
  460. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  461. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  462. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.UriScheme.Contains("wss") ? 2 : 1);
  463. }
  464. catch (Exception ex)
  465. {
  466. logger.LogError(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  467. }
  468. }
  469. private void AppServer_SessionClosed(object sender, string closeReason)
  470. {
  471. if (sender is not WsClientData session)
  472. {
  473. return;
  474. }
  475. session.SessionClosed -= AppServer_SessionClosed;
  476. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  477. WriteMachineLog(session, string.Format("CloseReason: {0}", closeReason), "Connection", "");
  478. RemoveClient(session);
  479. }
  480. private void TryRemoveDuplicatedSession(WsClientData session)
  481. {
  482. if (clientDic.ContainsKey(session.ChargeBoxId))
  483. {
  484. var oldSession = clientDic[session.ChargeBoxId];
  485. WriteMachineLog(oldSession, "Duplicate Logins", "Connection", "");
  486. RemoveClient(oldSession);
  487. }
  488. }
  489. async private void ReceivedMessageTimeLimited(object sender , string rawdata)
  490. {
  491. if (sender is not WsClientData session)
  492. {
  493. return;
  494. }
  495. CancellationTokenSource tokenSource = new();
  496. var task = ReceivedMessage(session, rawdata);
  497. var completedTask = await Task.WhenAny(task, Task.Delay(90_000, tokenSource.Token));
  498. if (completedTask != task)
  499. {
  500. logger.LogCritical("Process timeout: {0} ", rawdata);
  501. await task;
  502. return;
  503. }
  504. tokenSource.Cancel();
  505. return;
  506. }
  507. async private Task ReceivedMessage(WsClientData session, string rawdata)
  508. {
  509. try
  510. {
  511. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  512. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  513. WriteMachineLog(session, rawdata,
  514. 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);
  515. if (session.ResetSecurityProfile)
  516. {
  517. logger.LogError(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  518. RemoveClient(session);
  519. return;
  520. }
  521. if (!analysisResult.Success)
  522. {
  523. //解析RawData就發生錯誤
  524. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  525. {
  526. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  527. }
  528. else
  529. {
  530. if (analysisResult.Message == null)
  531. {
  532. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  533. string errorMsg = string.Empty;
  534. if (analysisResult.Exception != null)
  535. {
  536. errorMsg = analysisResult.Exception.ToString();
  537. }
  538. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  539. }
  540. else
  541. {
  542. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  543. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  544. string errorMsg = string.Empty;
  545. if (analysisResult.Exception != null)
  546. {
  547. errorMsg = analysisResult.Exception.ToString();
  548. }
  549. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  550. }
  551. }
  552. }
  553. else
  554. {
  555. switch (analysisResult.Id)
  556. {
  557. case BasicMessageHandler.TYPENUMBER_CALL:
  558. {
  559. if (!session.ISOCPP20)
  560. {
  561. Actions action = Convertor.GetAction(analysisResult.Action);
  562. try
  563. {
  564. await ProcessRequestMessage(analysisResult, session, action);
  565. }
  566. catch (Exception e)
  567. {
  568. logger.LogError($"Processing {action} exception!");
  569. throw;
  570. }
  571. }
  572. else
  573. {
  574. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  575. MessageResult result = new MessageResult() { Success = true };
  576. //ocpp20 處理
  577. switch (action)
  578. {
  579. case EVCB_OCPP20.Packet.Features.Actions.BootNotification:
  580. {
  581. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  582. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  583. result.Message = confirm;
  584. result.Success = true;
  585. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  586. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  587. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  588. {
  589. ConfigurationSlot = 1,
  590. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  591. {
  592. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  593. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  594. MessageTimeout = 30,
  595. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  596. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  597. }
  598. };
  599. var uuid = session.queue20.store(request);
  600. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  601. Send(session, requestText, "SetNetworkProfile");
  602. }
  603. break;
  604. default:
  605. {
  606. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  607. }
  608. break;
  609. }
  610. }
  611. }
  612. break;
  613. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  614. {
  615. if (!session.ISOCPP20)
  616. {
  617. Actions action = Convertor.GetAction(analysisResult.Action);
  618. ProcessConfirmationMessage(analysisResult, session, action);
  619. }
  620. else
  621. {
  622. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  623. MessageResult result = new MessageResult() { Success = true };
  624. //ocpp20 處理
  625. switch (action)
  626. {
  627. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  628. {
  629. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  630. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  631. {
  632. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  633. {
  634. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  635. {
  636. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  637. {
  638. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  639. {
  640. Name="OCPPCommCtrlr",
  641. },
  642. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  643. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  644. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  645. {
  646. Name="NetworkConfigurationPriority",
  647. }
  648. }
  649. }
  650. };
  651. var uuid = session.queue20.store(request);
  652. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  653. Send(session, requestText, "SetVariables");
  654. }
  655. }
  656. break;
  657. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  658. {
  659. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  660. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  661. {
  662. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  663. {
  664. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  665. };
  666. var uuid = session.queue20.store(request);
  667. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  668. Send(session, requestText, "Reset");
  669. }
  670. }
  671. break;
  672. default:
  673. {
  674. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  675. }
  676. break;
  677. }
  678. }
  679. }
  680. break;
  681. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  682. {
  683. //只處理 丟出Request 收到Error的訊息
  684. if (analysisResult.Success && analysisResult.Message != null)
  685. {
  686. Actions action = Convertor.GetAction(analysisResult.Action);
  687. ProcessErrorMessage(analysisResult, session, action);
  688. }
  689. }
  690. break;
  691. default:
  692. {
  693. logger.LogError(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  694. }
  695. break;
  696. }
  697. }
  698. await Task.Delay(10);
  699. }
  700. catch (Exception ex)
  701. {
  702. if (ex.InnerException != null)
  703. {
  704. logger.LogError(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  705. }
  706. else
  707. {
  708. logger.LogError(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  709. }
  710. }
  711. }
  712. private async Task ProcessRequestMessage(MessageResult analysisResult, WsClientData session, Actions action)
  713. {
  714. Stopwatch outter_stopwatch = Stopwatch.StartNew();
  715. //BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  716. if (!session.IsCheckIn && action != Actions.BootNotification)
  717. {
  718. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  719. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  720. return;
  721. }
  722. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  723. switch (profileName)
  724. {
  725. case "Core":
  726. {
  727. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  728. var sendTimer = Stopwatch.StartNew();
  729. if (replyResult.Success)
  730. {
  731. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  732. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception is null ? string.Empty : replyResult.Exception.ToString());
  733. if (action == Actions.BootNotification
  734. && replyResult.Message is BootNotificationConfirmation bootNotificationConfirmation)
  735. {
  736. if (bootNotificationConfirmation.status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  737. {
  738. session.IsCheckIn = true;
  739. await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId);
  740. await messageService.SendChangeConfigurationRequest(
  741. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  742. }
  743. else
  744. {
  745. bool? isAC = await mainDbService.GetChargeBoxIdIsAc(session.ChargeBoxId);
  746. if (isAC is not null)
  747. {
  748. session.IsAC = isAC.Value;
  749. }
  750. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.UriScheme.Contains("wss") ? 2 : 1);
  751. await webDbService.SetDefaultFee(session);
  752. }
  753. }
  754. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  755. {
  756. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  757. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  758. {
  759. await messageService.SendDataTransferRequest(
  760. session.ChargeBoxId,
  761. messageId: "SetUserPrice",
  762. vendorId:"Phihong Technology",
  763. data: JsonConvert.SerializeObject(
  764. new
  765. {
  766. idToken = authorizeRequest.idTag,
  767. price = session.UserDisplayPrices[authorizeRequest.idTag]
  768. })
  769. );
  770. }
  771. }
  772. }
  773. else
  774. {
  775. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  776. {
  777. //do nothing
  778. }
  779. else
  780. {
  781. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  782. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  783. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  784. }
  785. }
  786. sendTimer.Stop();
  787. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  788. {
  789. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  790. }
  791. if (action == Actions.StartTransaction)
  792. {
  793. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  794. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  795. if (_powerDic != null)
  796. {
  797. foreach (var kv in _powerDic)
  798. {
  799. try
  800. {
  801. if (kv.Value.HasValue)
  802. {
  803. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  804. }
  805. }
  806. catch (Exception ex)
  807. {
  808. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  809. }
  810. }
  811. }
  812. }
  813. if (action == Actions.StopTransaction)
  814. {
  815. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  816. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  817. if (_powerDic != null)
  818. {
  819. foreach (var kv in _powerDic)
  820. {
  821. try
  822. {
  823. if (kv.Value.HasValue)
  824. {
  825. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  826. }
  827. }
  828. catch (Exception ex)
  829. {
  830. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  831. }
  832. }
  833. }
  834. }
  835. }
  836. break;
  837. case "FirmwareManagement":
  838. {
  839. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  840. if (replyResult.Success)
  841. {
  842. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  843. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  844. }
  845. else
  846. {
  847. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  848. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  849. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  850. }
  851. }
  852. break;
  853. case "Security":
  854. {
  855. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  856. if (replyResult.Success)
  857. {
  858. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  859. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  860. }
  861. else
  862. {
  863. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  864. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  865. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  866. }
  867. }
  868. break;
  869. default:
  870. {
  871. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  872. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  873. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  874. }
  875. break;
  876. }
  877. outter_stopwatch.Stop();
  878. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  879. {
  880. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  881. }
  882. }
  883. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  884. {
  885. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  886. if (await ReConfirmMessage(analysisResult))
  887. {
  888. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  889. MessageResult confirmResult = null;
  890. switch (profileName)
  891. {
  892. case "Core":
  893. {
  894. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  895. }
  896. break;
  897. case "FirmwareManagement":
  898. {
  899. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  900. }
  901. break;
  902. case "RemoteTrigger":
  903. {
  904. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  905. }
  906. break;
  907. case "Reservation":
  908. {
  909. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  910. }
  911. break;
  912. case "LocalAuthListManagement":
  913. {
  914. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  915. }
  916. break;
  917. case "SmartCharging":
  918. {
  919. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  920. }
  921. break;
  922. case "Security":
  923. {
  924. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  925. }
  926. break;
  927. default:
  928. {
  929. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  930. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  931. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  932. }
  933. break;
  934. }
  935. if (confirmResult == null || !confirmResult.Success)
  936. {
  937. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  938. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  939. }
  940. }
  941. else
  942. {
  943. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  944. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  945. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  946. }
  947. }
  948. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  949. {
  950. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  951. if (await ReConfirmMessage(analysisResult))
  952. {
  953. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  954. switch (profileName)
  955. {
  956. case "Core":
  957. {
  958. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  959. }
  960. break;
  961. case "FirmwareManagement":
  962. {
  963. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  964. }
  965. break;
  966. case "RemoteTrigger":
  967. {
  968. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  969. }
  970. break;
  971. case "Reservation":
  972. {
  973. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  974. }
  975. break;
  976. case "LocalAuthListManagement":
  977. {
  978. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  979. }
  980. break;
  981. case "SmartCharging":
  982. {
  983. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  984. }
  985. break;
  986. default:
  987. {
  988. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  989. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  990. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  991. }
  992. break;
  993. }
  994. }
  995. else
  996. {
  997. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  998. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  999. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1000. }
  1001. }
  1002. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  1003. {
  1004. try
  1005. {
  1006. if (session != null)
  1007. {
  1008. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1009. session.Send(msg);
  1010. }
  1011. }
  1012. catch (Exception ex)
  1013. {
  1014. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  1015. }
  1016. }
  1017. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1018. {
  1019. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1020. _needConfirmMsg.Id = table_id;
  1021. _needConfirmMsg.SentAction = action;
  1022. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1023. _needConfirmMsg.SentTimes = 4;
  1024. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1025. _needConfirmMsg.RequestId = requestId;
  1026. _needConfirmMsg.SentUniqueId = msg_id;
  1027. _needConfirmMsg.CreatedBy = createdBy;
  1028. _needConfirmMsg.SentMessage = sendMessage;
  1029. if (needConfirmActions.Contains(action))
  1030. {
  1031. lock (_lockConfirmPacketList)
  1032. {
  1033. needConfirmPacketList.Add(_needConfirmMsg);
  1034. }
  1035. }
  1036. }
  1037. internal void RemoveConfirmMessage()
  1038. {
  1039. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1040. lock (_lockConfirmPacketList)
  1041. {
  1042. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1043. foreach (var item in removeList)
  1044. {
  1045. needConfirmPacketList.Remove(item);
  1046. }
  1047. }
  1048. }
  1049. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1050. {
  1051. bool confirmed = false;
  1052. if (needConfirmActions.Contains(analysisResult.Action))
  1053. {
  1054. NeedConfirmMessage foundRequest = null;
  1055. lock (_lockConfirmPacketList)
  1056. {
  1057. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1058. }
  1059. if (foundRequest != null && foundRequest.Id > 0)
  1060. {
  1061. foundRequest.SentTimes = 0;
  1062. foundRequest.SentInterval = 0;
  1063. analysisResult.RequestId = foundRequest.RequestId;
  1064. await mainDbService.UpdateServerMessage(foundRequest.Id, inMessage: JsonConvert.SerializeObject(analysisResult.Message, Formatting.None), receivedOn: DateTime.UtcNow);
  1065. confirmed = true;
  1066. }
  1067. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1068. {
  1069. confirmed = true;
  1070. }
  1071. else
  1072. {
  1073. logger.LogError(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1074. }
  1075. }
  1076. return confirmed;
  1077. }
  1078. internal async void RemoveClient(WsClientData session)
  1079. {
  1080. if (session is null)
  1081. {
  1082. return;
  1083. }
  1084. if (!string.IsNullOrEmpty(session.MachineId))
  1085. logger.LogTrace("RemoveClient[" + session.ChargeBoxId + "]");
  1086. RemoveClientDic(session);
  1087. try
  1088. {
  1089. if (session.State == WebSocketState.Open)
  1090. {
  1091. await session.Close();
  1092. }
  1093. //session.m_ReceiveData -= ReceivedMessageTimeLimited;
  1094. // session.Close(CloseReason.ServerShutdown);
  1095. }
  1096. catch (Exception ex)
  1097. {
  1098. //logger.LogWarning("Close client socket error!!");
  1099. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1100. }
  1101. }
  1102. private void RemoveClientDic(WsClientData session)
  1103. {
  1104. if (string.IsNullOrEmpty(session.ChargeBoxId) ||
  1105. !clientDic.ContainsKey(session.ChargeBoxId) ||
  1106. clientDic[session.ChargeBoxId].SessionID != session.SessionID)
  1107. {
  1108. return;
  1109. }
  1110. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1111. clientDic.Remove(session.ChargeBoxId, out _);
  1112. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1113. }
  1114. private void WarmUpLog()
  1115. {
  1116. connectionLogdbService.WarmUpLog();
  1117. }
  1118. private void WriteMachineLog(WsClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1119. {
  1120. try
  1121. {
  1122. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1123. if (clientData.ChargeBoxId == null)
  1124. {
  1125. logger.LogCritical(clientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1126. }
  1127. connectionLogdbService.WriteMachineLog(clientData, data, messageType, errorMsg, isSent);
  1128. }
  1129. catch (Exception ex)
  1130. {
  1131. //Console.WriteLine(ex.ToString());
  1132. logger.LogError(ex,ex.Message);
  1133. }
  1134. }
  1135. }
  1136. }