ProtalServer.cs 57 KB

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