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