ProtalServer.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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 &&
  627. replyResult.Message is BootNotificationConfirmation bootNotificationConfirmation &&
  628. analysisResult.Message is BootNotificationRequest bootNotificationRequest)
  629. {
  630. session.ChargePointVendor = bootNotificationRequest.chargePointVendor;
  631. if (session.BootStatus == BootStatus.Startup)
  632. {
  633. session.BootStatus = BootStatus.Initializing;
  634. session.AddTask(StartInitializeEVSE(session));
  635. }
  636. if (bootNotificationConfirmation.status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  637. {
  638. session.IsCheckIn = true;
  639. var sendTask = async () => await messageService.SendDataTransferRequest(
  640. session.ChargeBoxId,
  641. messageId: "ID_FirmwareVersion",
  642. vendorId: "Phihong Technology",
  643. data: string.Empty);
  644. await sendTask();
  645. //await confirmWaitingMessageSerevice.SendAndWaitUntilResultAsync(sendTask, session.DisconnetCancellationToken);
  646. }
  647. }
  648. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  649. {
  650. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  651. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  652. {
  653. await messageService.SendDataTransferRequest(
  654. session.ChargeBoxId,
  655. messageId: "SetUserPrice",
  656. vendorId: "Phihong Technology",
  657. data: JsonConvert.SerializeObject(
  658. new
  659. {
  660. idToken = authorizeRequest.idTag,
  661. price = session.UserDisplayPrices[authorizeRequest.idTag]
  662. })
  663. );
  664. }
  665. }
  666. }
  667. else
  668. {
  669. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  670. {
  671. //do nothing
  672. logger.LogWarning(replyResult.Exception.ToString());
  673. }
  674. else
  675. {
  676. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  677. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  678. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  679. }
  680. }
  681. sendTimer.Stop();
  682. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  683. {
  684. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  685. }
  686. if (action == Actions.StartTransaction)
  687. {
  688. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  689. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  690. if (_powerDic != null)
  691. {
  692. foreach (var kv in _powerDic)
  693. {
  694. try
  695. {
  696. if (kv.Value.HasValue)
  697. {
  698. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  699. }
  700. }
  701. catch (Exception ex)
  702. {
  703. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  704. }
  705. }
  706. }
  707. }
  708. if (action == Actions.StopTransaction)
  709. {
  710. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  711. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  712. if (_powerDic != null)
  713. {
  714. foreach (var kv in _powerDic)
  715. {
  716. try
  717. {
  718. if (kv.Value.HasValue)
  719. {
  720. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  721. }
  722. }
  723. catch (Exception ex)
  724. {
  725. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  726. }
  727. }
  728. }
  729. }
  730. }
  731. break;
  732. case "FirmwareManagement":
  733. {
  734. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  735. if (replyResult.Success)
  736. {
  737. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  738. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  739. }
  740. else
  741. {
  742. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  743. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  744. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  745. }
  746. }
  747. break;
  748. case "Security":
  749. {
  750. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  751. if (replyResult.Success)
  752. {
  753. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  754. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  755. }
  756. else
  757. {
  758. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  759. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  760. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  761. }
  762. }
  763. break;
  764. default:
  765. {
  766. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  767. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  768. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  769. }
  770. break;
  771. }
  772. }
  773. outter_stopwatch.Stop();
  774. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  775. {
  776. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  777. }
  778. }
  779. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  780. {
  781. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  782. if (await confirmWaitingMessageSerevice.TryConfirmMessage(analysisResult))
  783. {
  784. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  785. MessageResult confirmResult = null;
  786. switch (profileName)
  787. {
  788. case "Core":
  789. {
  790. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  791. }
  792. break;
  793. case "FirmwareManagement":
  794. {
  795. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  796. }
  797. break;
  798. case "RemoteTrigger":
  799. {
  800. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  801. }
  802. break;
  803. case "Reservation":
  804. {
  805. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  806. }
  807. break;
  808. case "LocalAuthListManagement":
  809. {
  810. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  811. }
  812. break;
  813. case "SmartCharging":
  814. {
  815. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  816. }
  817. break;
  818. case "Security":
  819. {
  820. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  821. }
  822. break;
  823. default:
  824. {
  825. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  826. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  827. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  828. }
  829. break;
  830. }
  831. if (confirmResult == null || !confirmResult.Success)
  832. {
  833. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  834. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  835. }
  836. }
  837. else
  838. {
  839. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  840. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  841. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  842. }
  843. }
  844. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  845. {
  846. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  847. if (await confirmWaitingMessageSerevice.TryConfirmMessage(analysisResult))
  848. {
  849. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  850. switch (profileName)
  851. {
  852. case "Core":
  853. {
  854. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  855. }
  856. break;
  857. case "FirmwareManagement":
  858. {
  859. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  860. }
  861. break;
  862. case "RemoteTrigger":
  863. {
  864. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  865. }
  866. break;
  867. case "Reservation":
  868. {
  869. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  870. }
  871. break;
  872. case "LocalAuthListManagement":
  873. {
  874. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  875. }
  876. break;
  877. case "SmartCharging":
  878. {
  879. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  880. }
  881. break;
  882. default:
  883. {
  884. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  885. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  886. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  887. }
  888. break;
  889. }
  890. }
  891. else
  892. {
  893. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  894. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  895. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  896. }
  897. }
  898. private async Task StartInitializeEVSE(WsClientData session)
  899. {
  900. await InitializeEVSE(session);
  901. session.BootStatus = BootStatus.Pending;
  902. }
  903. private async Task InitializeEVSE(WsClientData session)
  904. {
  905. // Pending mode 下發設定
  906. string connectorType = await mainDbService.GetMachineConnectorType(session.ChargeBoxId, session.DisconnetCancellationToken);
  907. if (!string.IsNullOrEmpty(connectorType) &&
  908. (connectorType.Contains("6") || connectorType.Contains("7") || connectorType.Contains("8") || connectorType.Contains("9")))
  909. {
  910. session.IsAC = false;
  911. }
  912. await mainDbService.SetMachineConnectionType(session.ChargeBoxId, session.UriScheme.Contains("wss") ? 2 : 1, session.DisconnetCancellationToken);
  913. string requestId = string.Empty;
  914. MessageResult response = null;
  915. Func<Task<string>> sendTask = null;
  916. var displayPriceText = await webDbService.SetDefaultFee(session);
  917. UpdateClientDisplayPrice(session.ChargeBoxId, displayPriceText);
  918. if (!string.IsNullOrEmpty(displayPriceText))
  919. {
  920. sendTask = async () => await messageService.SendChangeConfigurationRequest(
  921. session.ChargeBoxId, key: "DefaultPrice", value: displayPriceText);
  922. await confirmWaitingMessageSerevice.SendAndWaitUntilResultAsync(sendTask, session.DisconnetCancellationToken);
  923. }
  924. if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
  925. {
  926. await messageService.SendChangeConfigurationRequest(
  927. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  928. }
  929. if (session.CustomerId == new Guid("D57D5BCC-C5B0-4031-A7AE-7516E00CB028"))
  930. {
  931. await messageService.SendChangeConfigurationRequest(
  932. session.ChargeBoxId, key: "StopTransactionOnInvalidId", value: "True");
  933. }
  934. foreach (var initFunction in InitActions)
  935. {
  936. await initFunction(session, session.DisconnetCancellationToken);
  937. }
  938. //await StationConfigService?.CheckAndUpdateEvseConfig(session, session.DisconnetCancellationToken);
  939. }
  940. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  941. {
  942. try
  943. {
  944. if (session != null)
  945. {
  946. WriteMachineLog(session, msg, messageType, errorMsg, true);
  947. session.Send(msg);
  948. }
  949. }
  950. catch (Exception ex)
  951. {
  952. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  953. }
  954. }
  955. internal async void RemoveClient(WsClientData session, string reason)
  956. {
  957. if (session == null)
  958. {
  959. return;
  960. }
  961. if (!string.IsNullOrEmpty(session.MachineId))
  962. logger.LogTrace("RemoveClient[{0}]:{1}", session.ChargeBoxId, reason);
  963. WriteMachineLog(session, string.Format("CloseReason: {0}", reason), "Connection", "");
  964. //if (session.Connected)
  965. //{
  966. // session.Close(CloseReason.ServerShutdown);
  967. //}
  968. RemoveClientDic(session);
  969. try
  970. {
  971. session.SessionClosed -= AppServer_SessionClosed;
  972. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  973. if (session.State == WebSocketState.Open)
  974. {
  975. await session.Close();
  976. }
  977. // session.Close(CloseReason.ServerShutdown);
  978. }
  979. catch (Exception ex)
  980. {
  981. //logger.LogWarning("Close client socket error!!");
  982. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  983. }
  984. if (session != null)
  985. {
  986. session = null;
  987. }
  988. }
  989. private void RemoveClientDic(WsClientData session)
  990. {
  991. if (string.IsNullOrEmpty(session.ChargeBoxId))
  992. {
  993. return;
  994. }
  995. if (clientDic.ContainsKey(session.ChargeBoxId))
  996. {
  997. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  998. {
  999. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1000. clientDic.Remove(session.ChargeBoxId, out _);
  1001. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1002. }
  1003. }
  1004. }
  1005. private void WarmUpLog()
  1006. {
  1007. connectionLogdbService.WarmUpLog();
  1008. }
  1009. private void WriteMachineLog(WsClientData WsClientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1010. {
  1011. try
  1012. {
  1013. if (WsClientData == null || string.IsNullOrEmpty(data)) return;
  1014. if (WsClientData.ChargeBoxId == null)
  1015. {
  1016. logger.LogCritical(WsClientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + WsClientData.SessionID);
  1017. }
  1018. connectionLogdbService.WriteMachineLog(WsClientData, data, messageType, errorMsg, isSent);
  1019. }
  1020. catch (Exception ex)
  1021. {
  1022. //Console.WriteLine(ex.ToString());
  1023. logger.LogError(ex,ex.Message);
  1024. }
  1025. }
  1026. }
  1027. }