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