ProtalServer.cs 63 KB

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