ProtalServer.cs 56 KB

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