ProtalServer.cs 57 KB

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