ProtalServer.cs 58 KB

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