ProtalServer.cs 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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. await WaitCanStartLateInitEVSE(session.DisconnetCancellationToken);
  1006. try
  1007. {
  1008. //await Task.Delay(TimeSpan.FromMinutes(5));
  1009. await LateInitializeEVSE(session);
  1010. }
  1011. catch (Exception e)
  1012. {
  1013. logger.LogCritical("StartLateInitializeEVSE:{errormsg}", e.Message);
  1014. logger.LogCritical("StartLateInitializeEVSE:{errorStackTrace}", e.StackTrace);
  1015. }
  1016. finally
  1017. {
  1018. //session.BootStatus = BootStatus.Pending;
  1019. bootSemaphore.Release();
  1020. }
  1021. }
  1022. private async Task WaitCanStartLateInitEVSE(CancellationToken token)
  1023. {
  1024. bool passed = false;
  1025. do
  1026. {
  1027. while (bootSemaphore.CurrentCount < bootReservCnt)
  1028. {
  1029. await Task.Delay(TimeSpan.FromMinutes(2), cancellationToken: token);
  1030. }
  1031. passed = bootSemaphore.Wait(0);
  1032. } while (!passed);
  1033. }
  1034. private async Task LateInitializeEVSE(WsClientData session)
  1035. {
  1036. Func<string, CancellationToken , Task<string>> sendTask;
  1037. sendTask = async (string serialNo, CancellationToken token) => await messageService.SendDataTransferRequest(
  1038. session.ChargeBoxId,
  1039. messageId: "ID_FirmwareVersion",
  1040. vendorId: "Phihong Technology",
  1041. data: string.Empty,
  1042. serialNo: serialNo,
  1043. token: token);
  1044. await confirmWaitingMessageSerevice.SendAndWaitResultAsync(sendTask, token: session.DisconnetCancellationToken);
  1045. sendTask = async (string serialNo, CancellationToken token) => await messageService.SendTriggerMessageRequest(
  1046. session.ChargeBoxId,
  1047. messageTrigger: MessageTrigger.DiagnosticsStatusNotification,
  1048. serialNo: serialNo,
  1049. token: token);
  1050. await confirmWaitingMessageSerevice.SendAndWaitResultAsync(sendTask, token: session.DisconnetCancellationToken);
  1051. for (var index = 0; index < LateInitActions.Count; index++)
  1052. {
  1053. var lateInitFunction = LateInitActions[index];
  1054. await lateInitFunction(session, session.DisconnetCancellationToken);
  1055. }
  1056. }
  1057. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  1058. {
  1059. try
  1060. {
  1061. if (session != null)
  1062. {
  1063. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1064. session.Send(msg);
  1065. }
  1066. }
  1067. catch (Exception ex)
  1068. {
  1069. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  1070. }
  1071. }
  1072. internal async void RemoveClient(WsClientData session, string reason)
  1073. {
  1074. if (session == null)
  1075. {
  1076. return;
  1077. }
  1078. if (!string.IsNullOrEmpty(session.MachineId))
  1079. logger.LogTrace("RemoveClient[{0}]:{1}", session.ChargeBoxId, reason);
  1080. WriteMachineLog(session, string.Format("CloseReason: {0}", reason), "Connection", "");
  1081. //if (session.Connected)
  1082. //{
  1083. // session.Close(CloseReason.ServerShutdown);
  1084. //}
  1085. RemoveClientDic(session);
  1086. try
  1087. {
  1088. session.SessionClosed -= AppServer_SessionClosed;
  1089. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  1090. if (session.State == WebSocketState.Open)
  1091. {
  1092. await session.Close();
  1093. }
  1094. // session.Close(CloseReason.ServerShutdown);
  1095. }
  1096. catch (Exception ex)
  1097. {
  1098. //logger.LogWarning("Close client socket error!!");
  1099. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1100. }
  1101. if (session != null)
  1102. {
  1103. session = null;
  1104. }
  1105. }
  1106. private void RemoveClientDic(WsClientData session)
  1107. {
  1108. if (string.IsNullOrEmpty(session.ChargeBoxId))
  1109. {
  1110. return;
  1111. }
  1112. if (clientDic.ContainsKey(session.ChargeBoxId))
  1113. {
  1114. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1115. {
  1116. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1117. clientDic.Remove(session.ChargeBoxId, out _);
  1118. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1119. }
  1120. }
  1121. }
  1122. private void WarmUpLog()
  1123. {
  1124. connectionLogdbService.WarmUpLog();
  1125. }
  1126. private void WriteMachineLog(WsClientData WsClientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1127. {
  1128. try
  1129. {
  1130. if (WsClientData == null || string.IsNullOrEmpty(data)) return;
  1131. if (WsClientData.ChargeBoxId == null)
  1132. {
  1133. logger.LogCritical(WsClientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + WsClientData.SessionID);
  1134. }
  1135. connectionLogdbService.WriteMachineLog(WsClientData, data, messageType, errorMsg, isSent);
  1136. }
  1137. catch (Exception ex)
  1138. {
  1139. //Console.WriteLine(ex.ToString());
  1140. logger.LogError(ex,ex.Message);
  1141. }
  1142. }
  1143. }
  1144. }