ProtalServer.cs 56 KB

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