ProtalServer.cs 56 KB

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