ProtalServer.cs 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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. namespace EVCB_OCPP.WSServer
  30. {
  31. public class DestroyRequest : IRequest
  32. {
  33. public string Action { get; set; }
  34. public bool TransactionRelated()
  35. {
  36. return false;
  37. }
  38. public bool Validate()
  39. {
  40. return true;
  41. }
  42. }
  43. public class ProtalServer : IHostedService
  44. {
  45. //static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  46. public ProtalServer(
  47. ILogger<ProtalServer> logger
  48. , IConfiguration configuration
  49. , IDbContextFactory<MainDBContext> maindbContextFactory
  50. , IMainDbService mainDbService
  51. , IDbContextFactory<ConnectionLogDBContext> connectionLogdbContextFactory
  52. , ISqlConnectionFactory<WebDBConetext> webDbConnectionFactory
  53. , ISqlConnectionFactory<MainDBContext> mainDbConnectionFactory
  54. , IHostEnvironment environment
  55. //, IOCPPWSServerFactory ocppWSServerFactory
  56. , IConnectionLogdbService connectionLogdbService
  57. , WebDbService webDbService
  58. , ServerMessageService serverMessageService
  59. , IServiceProvider serviceProvider
  60. , OcppWebsocketService websocketService
  61. , OuterHttpClient httpClient)
  62. {
  63. _ct = _cts.Token;
  64. this.logger = logger;
  65. this.configuration = configuration;
  66. this.maindbContextFactory = maindbContextFactory;
  67. this.mainDbService = mainDbService;
  68. this.webDbConnectionFactory = webDbConnectionFactory;
  69. //this.connectionLogdbContextFactory = connectionLogdbContextFactory;
  70. //this.ocppWSServerFactory = ocppWSServerFactory;
  71. this.connectionLogdbService = connectionLogdbService;
  72. this.webDbService = webDbService;
  73. this.messageService = serverMessageService;
  74. this.websocketService = websocketService;
  75. this.httpClient = httpClient;
  76. isInDocker = !string.IsNullOrEmpty(configuration["DOTNET_RUNNING_IN_CONTAINER"]);
  77. // = configuration.GetConnectionString("WebDBContext");
  78. this.profileHandler = serviceProvider.GetService<ProfileHandler>();// new ProfileHandler(configuration, serviceProvider);
  79. _loadingBalanceService = new LoadingBalanceService(mainDbConnectionFactory, webDbConnectionFactory);
  80. WarmUpLog();
  81. }
  82. #region private fields
  83. private OuterHttpClient httpClient;
  84. private DateTime lastcheckdt = DateTime.UtcNow.AddSeconds(-20);
  85. private ConcurrentDictionary<string, WsClientData> clientDic = new ConcurrentDictionary<string, WsClientData>();
  86. //private readonly Object _lockClientDic = new object();
  87. private readonly Object _lockConfirmPacketList = new object();
  88. private readonly ILogger<ProtalServer> logger;
  89. private readonly IConfiguration configuration;
  90. //private readonly IServiceProvider serviceProvider;
  91. private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
  92. private readonly IMainDbService mainDbService;
  93. private readonly ISqlConnectionFactory<WebDBConetext> webDbConnectionFactory;
  94. //private readonly IDbContextFactory<ConnectionLogDBContext> connectionLogdbContextFactory;
  95. //private readonly IOCPPWSServerFactory ocppWSServerFactory;
  96. private readonly IConnectionLogdbService connectionLogdbService;
  97. private readonly WebDbService webDbService;
  98. private readonly ServerMessageService messageService;
  99. private readonly OcppWebsocketService websocketService;
  100. private readonly ProfileHandler profileHandler;//= new ProfileHandler();
  101. //private readonly string webConnectionString;// = ConfigurationManager.ConnectionStrings["WebDBContext"].ConnectionString;
  102. private readonly bool isInDocker;
  103. private List<NeedConfirmMessage> needConfirmPacketList = new List<NeedConfirmMessage>();
  104. private DateTime checkUpdateDt = DateTime.UtcNow;
  105. private DateTime _CheckFeeDt = DateTime.UtcNow;
  106. private DateTime _CheckLBDt = DateTime.UtcNow;
  107. private DateTime _CheckDenyListDt = DateTime.UtcNow.AddDays(-1);
  108. private readonly LoadingBalanceService _loadingBalanceService;// = new LoadingBalanceService();
  109. private List<StationInfoDto> _StationInfo = new List<StationInfoDto>();
  110. private readonly List<string> needConfirmActions = new List<string>()
  111. {
  112. "GetConfiguration",
  113. "ChangeConfiguration",
  114. "RemoteStartTransaction",
  115. "RemoteStopTransaction",
  116. "ChangeAvailability",
  117. "ClearCache",
  118. "DataTransfer",
  119. "Reset",
  120. "UnlockConnector",
  121. "TriggerMessage",
  122. "GetDiagnostics",
  123. "UpdateFirmware",
  124. "GetLocalListVersion",
  125. "SendLocalList",
  126. "SetChargingProfile",
  127. "ClearChargingProfile",
  128. "GetCompositeSchedule",
  129. "ReserveNow",
  130. "CancelReservation",
  131. "ExtendedTriggerMessage"
  132. };
  133. private readonly List<Profile> profiles = new List<Profile>()
  134. {
  135. new CoreProfile(),
  136. new FirmwareManagementProfile(),
  137. new ReservationProfile(),
  138. new RemoteTriggerProfile(),
  139. new SmartChargingProfile(),
  140. new LocalAuthListManagementProfile(),
  141. new SecurityProfile(),
  142. };
  143. private CancellationTokenSource _cts = new CancellationTokenSource();
  144. private CancellationToken _ct;
  145. #endregion
  146. internal Dictionary<string, WsClientData> GetClientDic()
  147. {
  148. Dictionary<string, WsClientData> toReturn = null;
  149. toReturn = new Dictionary<string, WsClientData>(clientDic);
  150. return toReturn;
  151. }
  152. internal List<NeedConfirmMessage> GetResendMessage()
  153. {
  154. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  155. lock (_lockConfirmPacketList)
  156. {
  157. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  158. }
  159. return sendMessages;
  160. }
  161. internal IReadOnlyList<Profile> Profiles => profiles.AsReadOnly();
  162. internal LoadingBalanceService LoadingBalanceService => _loadingBalanceService;
  163. internal ProfileHandler ProfileHandler => profileHandler;
  164. public async Task StartAsync(CancellationToken cancellationToken)
  165. {
  166. GlobalConfig.DenyModelNames = await webDbService.GetDenyModelNames(cancellationToken);
  167. Start();
  168. return;
  169. }
  170. public Task StopAsync(CancellationToken cancellationToken)
  171. {
  172. return Task.CompletedTask;
  173. }
  174. internal void UpdateClientDisplayPrice(string key,string price)
  175. {
  176. clientDic[key].DisplayPrice = price;
  177. }
  178. internal void SendMsg(WsClientData session, string msg, string messageType, string errorMsg = "")
  179. {
  180. Send(session,msg,messageType,errorMsg);
  181. }
  182. internal void Start()
  183. {
  184. Console.WriteLine("Starting Server...");
  185. if (!GlobalConfig.LoadAPPConfig(configuration))
  186. {
  187. Console.WriteLine("Please check App.Config setting .");
  188. return;
  189. }
  190. StartWsService();
  191. //OpenNetwork();
  192. //RunHttpConsoleService();
  193. return;
  194. if (!isInDocker)
  195. {
  196. Task consoleReadTask = new Task(RunConsoleInteractive);
  197. consoleReadTask.Start();
  198. //RunConsoleInteractive();
  199. return;
  200. }
  201. }
  202. private void StartWsService()
  203. {
  204. websocketService.NewSessionConnected += AppServer_NewSessionConnected;
  205. }
  206. private void StopWsService()
  207. {
  208. websocketService.NewSessionConnected -= AppServer_NewSessionConnected;
  209. }
  210. private async void AppServer_NewSessionConnected(object sender, WsClientData session)
  211. {
  212. logger.LogDebug(string.Format("{0} NewSessionConnected", session.Path));
  213. try
  214. {
  215. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  216. if (isNotSupported)
  217. {
  218. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  219. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  220. return;
  221. }
  222. TryRemoveDuplicatedSession(session);
  223. clientDic[session.ChargeBoxId] = session;
  224. session.SessionClosed += AppServer_SessionClosed;
  225. session.m_ReceiveData += ReceivedMessageTimeLimited;
  226. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  227. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  228. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.UriScheme.Contains("wss") ? 2 : 1);
  229. }
  230. catch (Exception ex)
  231. {
  232. logger.LogError(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  233. }
  234. }
  235. private void AppServer_SessionClosed(object sender, string closeReason)
  236. {
  237. if (sender is not WsClientData session)
  238. {
  239. return;
  240. }
  241. //session.SessionClosed -= AppServer_SessionClosed;
  242. //session.m_ReceiveData -= ReceivedMessageTimeLimited;
  243. //WriteMachineLog(session, string.Format("CloseReason: {0}", closeReason), "Connection", "");
  244. RemoveClient(session, closeReason);
  245. }
  246. private void TryRemoveDuplicatedSession(WsClientData session)
  247. {
  248. if (clientDic.ContainsKey(session.ChargeBoxId))
  249. {
  250. var oldSession = clientDic[session.ChargeBoxId];
  251. //WriteMachineLog(oldSession, "Duplicate Logins", "Connection", "");
  252. RemoveClient(oldSession, "Duplicate Logins");
  253. }
  254. }
  255. private void RunConsoleInteractive()
  256. {
  257. while (true)
  258. {
  259. if (Console.In is null)
  260. {
  261. break;
  262. }
  263. var input = Console.ReadLine();
  264. switch (input.ToLower())
  265. {
  266. case "stop":
  267. Console.WriteLine("Command stop");
  268. Stop();
  269. break;
  270. case "gc":
  271. Console.WriteLine("Command GC");
  272. GC.Collect();
  273. break;
  274. case "lc":
  275. {
  276. Console.WriteLine("Command List Clients");
  277. Dictionary<string, WsClientData> _copyClientDic = null;
  278. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  279. var list = _copyClientDic.Select(c => c.Value).ToList();
  280. int i = 1;
  281. foreach (var c in list)
  282. {
  283. Console.WriteLine(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  284. i++;
  285. }
  286. }
  287. break;
  288. case "lcn":
  289. {
  290. Console.WriteLine("Command List Customer Name");
  291. Dictionary<string, WsClientData> _copyClientDic = null;
  292. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  293. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  294. int iLcn = 1;
  295. foreach (var c in lcn)
  296. {
  297. Console.WriteLine(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  298. iLcn++;
  299. }
  300. }
  301. break;
  302. case "help":
  303. Console.WriteLine("Command help!!");
  304. Console.WriteLine("lcn : List Customer Name");
  305. Console.WriteLine("gc : GC Collect");
  306. Console.WriteLine("lc : List Clients");
  307. Console.WriteLine("cls : clear console");
  308. Console.WriteLine("silent : silent");
  309. Console.WriteLine("show : show log");
  310. // logger.Info("rcl : show Real Connection Limit");
  311. break;
  312. case "cls":
  313. Console.WriteLine("Command clear");
  314. Console.Clear();
  315. break;
  316. case "silent":
  317. Console.WriteLine("Command silent");
  318. //var xe = XElement.Load("NLog.config");
  319. //var xns = xe.GetDefaultNamespace();
  320. //var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  321. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  322. //if (minlevelattr != null)
  323. //{
  324. // minlevelattr.Value = "Warn";
  325. //}
  326. //xe.Save("NLog.config");
  327. foreach (var rule in LogManager.Configuration.LoggingRules)
  328. {
  329. if (rule.RuleName != "ConsoleLog")
  330. {
  331. continue;
  332. }
  333. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  334. if (isTargetRule)
  335. {
  336. rule.SetLoggingLevels(NLog.LogLevel.Warn, NLog.LogLevel.Off);
  337. }
  338. }
  339. break;
  340. case "show":
  341. Console.WriteLine("Command show");
  342. //var xe1 = XElement.Load("NLog.config");
  343. //var xns1 = xe1.GetDefaultNamespace();
  344. //var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  345. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  346. //if (minlevelattr1 != null)
  347. //{
  348. // minlevelattr1.Value = "trace";
  349. //}
  350. //xe1.Save("NLog.config");
  351. foreach (var rule in LogManager.Configuration.LoggingRules)
  352. {
  353. if (rule.RuleName != "ConsoleLog")
  354. {
  355. continue;
  356. }
  357. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  358. if (isTargetRule)
  359. {
  360. rule.SetLoggingLevels(NLog.LogLevel.Trace, NLog.LogLevel.Off);
  361. }
  362. }
  363. break;
  364. case "rcl":
  365. break;
  366. default:
  367. break;
  368. }
  369. }
  370. }
  371. private void RunHttpConsoleService()
  372. {
  373. var appBuilder = WebApplication.CreateBuilder();
  374. appBuilder.Services.AddSingleton<IHostLifetime, DummyHostLifeTime>();
  375. var app = appBuilder.Build();
  376. var helpFunc = () => {
  377. return string.Join("\r\n", new[] {
  378. "Command help!!",
  379. "lcn : List Customer Name",
  380. "gc : GC Collect",
  381. "lc : List Clients",
  382. "silent : silent",
  383. "show : show log"
  384. });
  385. };
  386. app.MapGet("/", helpFunc);
  387. app.MapGet("/help", helpFunc);
  388. app.MapPost("/stop", () => {
  389. Stop();
  390. return "Command stop";
  391. });
  392. app.MapPost("/gc", () => {
  393. GC.Collect();
  394. return "Command GC";
  395. });
  396. app.MapPost("/lc", () => {
  397. List<string> toReturn = new List<string>() { "Command List Clients" };
  398. Dictionary<string, WsClientData> _copyClientDic = null;
  399. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  400. var list = _copyClientDic.Select(c => c.Value).ToList();
  401. int i = 1;
  402. foreach (var c in list)
  403. {
  404. toReturn.Add(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  405. i++;
  406. }
  407. return string.Join("\r\n", toReturn);
  408. });
  409. app.MapPost("/lcn", () => {
  410. List<string> toReturn = new List<string> { "Command List Customer Name" };
  411. Dictionary<string, WsClientData> _copyClientDic = null;
  412. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  413. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  414. int iLcn = 1;
  415. foreach (var c in lcn)
  416. {
  417. toReturn.Add(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  418. iLcn++;
  419. }
  420. return string.Join("\r\n", toReturn);
  421. });
  422. app.MapPost("/silent", () => {
  423. foreach (var rule in LogManager.Configuration.LoggingRules)
  424. {
  425. if (rule.RuleName != "ConsoleLog")
  426. {
  427. continue;
  428. }
  429. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  430. if (isTargetRule)
  431. {
  432. rule.SetLoggingLevels(NLog.LogLevel.Warn, NLog.LogLevel.Off);
  433. }
  434. }
  435. return "Command silent";
  436. });
  437. app.MapPost("/show", () => {
  438. foreach (var rule in LogManager.Configuration.LoggingRules)
  439. {
  440. if (rule.RuleName != "ConsoleLog")
  441. {
  442. continue;
  443. }
  444. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  445. if (isTargetRule)
  446. {
  447. rule.SetLoggingLevels(NLog.LogLevel.Trace, NLog.LogLevel.Off);
  448. }
  449. }
  450. return "Command show";
  451. });
  452. app.MapGet("/threads", () => {
  453. ThreadPool.GetMaxThreads(out var maxWorkerThread,out var maxCompletionPortThreads);
  454. ThreadPool.GetAvailableThreads(out var avaliableWorkerThread, out var avaliableCompletionPortThreads);
  455. return $"WorkerThread:{avaliableWorkerThread}/{maxWorkerThread} CompletionPortThreads{avaliableCompletionPortThreads}/{maxCompletionPortThreads}";
  456. });
  457. app.MapPost("/threads", (int min, int max) => {
  458. ThreadPool.GetMaxThreads(out var maxWorkerThread, out var maxCompletionPortThreads);
  459. ThreadPool.GetAvailableThreads(out var avaliableWorkerThread, out var avaliableCompletionPortThreads);
  460. ThreadPool.SetMinThreads(min, 0);
  461. ThreadPool.SetMaxThreads(max, maxCompletionPortThreads);
  462. return $"WorkerThread:{avaliableWorkerThread}/{maxWorkerThread} CompletionPortThreads{avaliableCompletionPortThreads}/{maxCompletionPortThreads}";
  463. });
  464. app.Urls.Add("http://*:54088");
  465. _ = app.RunAsync();
  466. var builder = WebApplication.CreateBuilder();
  467. //builder.Configuration.AddJsonFile("./EVCB_OCPP.WSServer/appsettings.json");
  468. //var sec = builder.Configuration.GetSection("ReverseProxy");
  469. //Console.WriteLine($"Printing.............");
  470. //foreach (var pair in sec.AsEnumerable())
  471. //{
  472. // Console.WriteLine($"{pair.Key}:{pair.Value} \n");
  473. //}
  474. builder.Services.AddReverseProxy()
  475. .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
  476. builder.Services.AddSingleton<IHostLifetime, DummyHostLifeTime>();
  477. var yarpApp = builder.Build();
  478. yarpApp.Urls.Add("http://*:80");
  479. yarpApp.MapReverseProxy();
  480. _ = yarpApp.RunAsync();
  481. }
  482. internal void Stop()
  483. {
  484. _cts?.Cancel();
  485. }
  486. //private void OpenNetwork()
  487. //{
  488. // //載入OCPP Protocol
  489. // OCPPWSServer appServer = ocppWSServerFactory.Create(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0") });
  490. // //var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0") });
  491. // List<IListenerConfig> llistener = new List<IListenerConfig>();
  492. // if (GlobalConfig.GetWS_Port() != 0)
  493. // {
  494. // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = GlobalConfig.GetWS_Port(), Backlog = 100, Security = "None" });
  495. // }
  496. // foreach (var securityport in GlobalConfig.GetWSS_Ports())
  497. // {
  498. // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = securityport, Backlog = 100, Security = SslProtocols.Tls12.ToString() });
  499. // }
  500. // //var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;\
  501. // //var certificate = configuration.GetSection("superSocket").GetSection("Servers:0").GetSection("Certificate").Get<CertificateConfig>();
  502. // var certificate = configuration.GetSection("SuperSocketServerCertificate").Get<CertificateConfig>();
  503. // ICertificateConfig Certificate = certificate;
  504. // IEnumerable<IListenerConfig> listeners = llistener;
  505. // //設定server config
  506. // var serverConfig = new ServerConfig
  507. // {
  508. // SendingQueueSize = 10,
  509. // //Port = Convert.ToInt32(2012),
  510. // //Ip = "172.17.40.13",
  511. // MaxRequestLength = 204800,
  512. // //Security = serverSecurity,
  513. // //Certificate = Certificate,
  514. // Listeners = listeners,
  515. // // LogAllSocketException = true,
  516. // KeepAliveTime = 10,
  517. // // LogBasicSessionActivity = true
  518. // //Security = "None"
  519. // };
  520. // //Setup with listening port
  521. // if (!appServer.Setup(serverConfig, logFactory: new NLogLoggerFactory()))
  522. // {
  523. // Console.WriteLine("Failed to setup!");
  524. // return;
  525. // }
  526. // appServer.NewSessionConnected += AppServer_NewSessionConnected;
  527. // appServer.SessionClosed += AppServer_SessionClosed;
  528. // //Try to start the appServer
  529. // if (!appServer.Start())
  530. // {
  531. // Console.WriteLine("Failed to start!");
  532. // //Console.ReadKey();
  533. // return;
  534. // }
  535. //}
  536. async private void ReceivedMessageTimeLimited(object sender, string rawdata)
  537. {
  538. if (sender is not WsClientData session)
  539. {
  540. return;
  541. }
  542. CancellationTokenSource tokenSource = new();
  543. var task = ReceivedMessage(session, rawdata);
  544. var completedTask = await Task.WhenAny(task, Task.Delay(90_000, tokenSource.Token));
  545. if (completedTask != task)
  546. {
  547. logger.LogCritical("Process timeout: {0} ", rawdata);
  548. await task;
  549. return;
  550. }
  551. tokenSource.Cancel();
  552. return;
  553. }
  554. async private Task ReceivedMessage(WsClientData session, string rawdata)
  555. {
  556. try
  557. {
  558. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  559. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  560. WriteMachineLog(session, rawdata,
  561. 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);
  562. if (session.ResetSecurityProfile)
  563. {
  564. logger.LogError(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  565. RemoveClient(session, "ResetSecurityProfile");
  566. return;
  567. }
  568. if (!analysisResult.Success)
  569. {
  570. //解析RawData就發生錯誤
  571. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  572. {
  573. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  574. }
  575. else
  576. {
  577. if (analysisResult.Message == null)
  578. {
  579. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  580. string errorMsg = string.Empty;
  581. if (analysisResult.Exception != null)
  582. {
  583. errorMsg = analysisResult.Exception.ToString();
  584. }
  585. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  586. }
  587. else
  588. {
  589. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  590. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  591. string errorMsg = string.Empty;
  592. if (analysisResult.Exception != null)
  593. {
  594. errorMsg = analysisResult.Exception.ToString();
  595. }
  596. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  597. }
  598. }
  599. }
  600. else
  601. {
  602. switch (analysisResult.Id)
  603. {
  604. case BasicMessageHandler.TYPENUMBER_CALL:
  605. {
  606. if (!session.ISOCPP20)
  607. {
  608. Actions action = Convertor.GetAction(analysisResult.Action);
  609. try
  610. {
  611. await ProcessRequestMessage(analysisResult, session, action);
  612. }
  613. catch (Exception e)
  614. {
  615. logger.LogError($"Processing {action} exception!");
  616. throw;
  617. }
  618. }
  619. else
  620. {
  621. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  622. MessageResult result = new MessageResult() { Success = true };
  623. //ocpp20 處理
  624. switch (action)
  625. {
  626. case EVCB_OCPP20.Packet.Features.Actions.BootNotification:
  627. {
  628. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  629. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  630. result.Message = confirm;
  631. result.Success = true;
  632. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  633. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  634. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  635. {
  636. ConfigurationSlot = 1,
  637. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  638. {
  639. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  640. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  641. MessageTimeout = 30,
  642. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  643. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  644. }
  645. };
  646. var uuid = session.queue20.store(request);
  647. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  648. Send(session, requestText, "SetNetworkProfile");
  649. }
  650. break;
  651. default:
  652. {
  653. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  654. }
  655. break;
  656. }
  657. }
  658. }
  659. break;
  660. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  661. {
  662. if (!session.ISOCPP20)
  663. {
  664. Actions action = Convertor.GetAction(analysisResult.Action);
  665. ProcessConfirmationMessage(analysisResult, session, action);
  666. }
  667. else
  668. {
  669. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  670. MessageResult result = new MessageResult() { Success = true };
  671. //ocpp20 處理
  672. switch (action)
  673. {
  674. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  675. {
  676. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  677. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  678. {
  679. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  680. {
  681. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  682. {
  683. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  684. {
  685. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  686. {
  687. Name="OCPPCommCtrlr",
  688. },
  689. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  690. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  691. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  692. {
  693. Name="NetworkConfigurationPriority",
  694. }
  695. }
  696. }
  697. };
  698. var uuid = session.queue20.store(request);
  699. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  700. Send(session, requestText, "SetVariables");
  701. }
  702. }
  703. break;
  704. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  705. {
  706. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  707. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  708. {
  709. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  710. {
  711. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  712. };
  713. var uuid = session.queue20.store(request);
  714. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  715. Send(session, requestText, "Reset");
  716. }
  717. }
  718. break;
  719. default:
  720. {
  721. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  722. }
  723. break;
  724. }
  725. }
  726. }
  727. break;
  728. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  729. {
  730. //只處理 丟出Request 收到Error的訊息
  731. if (analysisResult.Success && analysisResult.Message != null)
  732. {
  733. Actions action = Convertor.GetAction(analysisResult.Action);
  734. ProcessErrorMessage(analysisResult, session, action);
  735. }
  736. }
  737. break;
  738. default:
  739. {
  740. logger.LogError(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  741. }
  742. break;
  743. }
  744. }
  745. await Task.Delay(10);
  746. }
  747. catch (Exception ex)
  748. {
  749. if (ex.InnerException != null)
  750. {
  751. logger.LogError(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  752. }
  753. else
  754. {
  755. logger.LogError(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  756. }
  757. }
  758. }
  759. private async Task ProcessRequestMessage(MessageResult analysisResult, WsClientData session, Actions action)
  760. {
  761. Stopwatch outter_stopwatch = Stopwatch.StartNew();
  762. //BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  763. if (!session.IsCheckIn && action != Actions.BootNotification)
  764. {
  765. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  766. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  767. }
  768. else
  769. {
  770. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  771. switch (profileName)
  772. {
  773. case "Core":
  774. {
  775. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  776. var sendTimer = Stopwatch.StartNew();
  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. if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
  782. {
  783. if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  784. {
  785. session.IsCheckIn = true;
  786. await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId);
  787. await messageService.SendDataTransferRequest(
  788. session.ChargeBoxId,
  789. messageId: "ID_FirmwareVersion",
  790. vendorId: "Phihong Technology",
  791. data: string.Empty);
  792. }
  793. else
  794. {
  795. // Pending mode 下發設定
  796. using (var db = await maindbContextFactory.CreateDbContextAsync())
  797. {
  798. var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
  799. if (machine != null)
  800. {
  801. if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
  802. {
  803. session.IsAC = false;
  804. }
  805. machine.ConnectionType = session.UriScheme.Contains("wss") ? 2 : 1;
  806. await db.SaveChangesAsync();
  807. }
  808. }
  809. await messageService.SendChangeConfigurationRequest(
  810. session.ChargeBoxId, key: "MeteringWithKilowatt", value: "True");
  811. await SetDefaultFee(session);
  812. if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
  813. {
  814. await messageService.SendChangeConfigurationRequest(
  815. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  816. }
  817. if (session.CustomerId == new Guid("D57D5BCC-C5B0-4031-A7AE-7516E00CB028") )
  818. {
  819. await messageService.SendChangeConfigurationRequest(
  820. session.ChargeBoxId, key: "StopTransactionOnInvalidId", value: "True");
  821. }
  822. }
  823. }
  824. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  825. {
  826. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  827. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  828. {
  829. await messageService.SendDataTransferRequest(
  830. session.ChargeBoxId,
  831. messageId: "SetUserPrice",
  832. vendorId: "Phihong Technology",
  833. data: JsonConvert.SerializeObject(
  834. new
  835. {
  836. idToken = authorizeRequest.idTag,
  837. price = session.UserDisplayPrices[authorizeRequest.idTag]
  838. })
  839. );
  840. }
  841. }
  842. }
  843. else
  844. {
  845. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  846. {
  847. //do nothing
  848. logger.LogWarning(replyResult.Exception.ToString());
  849. }
  850. else
  851. {
  852. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  853. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  854. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  855. }
  856. }
  857. sendTimer.Stop();
  858. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  859. {
  860. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  861. }
  862. if (action == Actions.StartTransaction)
  863. {
  864. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  865. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  866. if (_powerDic != null)
  867. {
  868. foreach (var kv in _powerDic)
  869. {
  870. try
  871. {
  872. if (kv.Value.HasValue)
  873. {
  874. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  875. }
  876. }
  877. catch (Exception ex)
  878. {
  879. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  880. }
  881. }
  882. }
  883. }
  884. if (action == Actions.StopTransaction)
  885. {
  886. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  887. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  888. if (_powerDic != null)
  889. {
  890. foreach (var kv in _powerDic)
  891. {
  892. try
  893. {
  894. if (kv.Value.HasValue)
  895. {
  896. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  897. }
  898. }
  899. catch (Exception ex)
  900. {
  901. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  902. }
  903. }
  904. }
  905. }
  906. }
  907. break;
  908. case "FirmwareManagement":
  909. {
  910. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  911. if (replyResult.Success)
  912. {
  913. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  914. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  915. }
  916. else
  917. {
  918. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  919. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  920. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  921. }
  922. }
  923. break;
  924. case "Security":
  925. {
  926. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  927. if (replyResult.Success)
  928. {
  929. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  930. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  931. }
  932. else
  933. {
  934. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  935. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  936. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  937. }
  938. }
  939. break;
  940. default:
  941. {
  942. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  943. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  944. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  945. }
  946. break;
  947. }
  948. }
  949. outter_stopwatch.Stop();
  950. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  951. {
  952. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  953. }
  954. }
  955. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  956. {
  957. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  958. if (await ReConfirmMessage(analysisResult))
  959. {
  960. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  961. MessageResult confirmResult = null;
  962. switch (profileName)
  963. {
  964. case "Core":
  965. {
  966. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  967. }
  968. break;
  969. case "FirmwareManagement":
  970. {
  971. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  972. }
  973. break;
  974. case "RemoteTrigger":
  975. {
  976. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  977. }
  978. break;
  979. case "Reservation":
  980. {
  981. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  982. }
  983. break;
  984. case "LocalAuthListManagement":
  985. {
  986. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  987. }
  988. break;
  989. case "SmartCharging":
  990. {
  991. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  992. }
  993. break;
  994. case "Security":
  995. {
  996. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  997. }
  998. break;
  999. default:
  1000. {
  1001. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1002. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1003. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1004. }
  1005. break;
  1006. }
  1007. if (confirmResult == null || !confirmResult.Success)
  1008. {
  1009. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  1010. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  1011. }
  1012. }
  1013. else
  1014. {
  1015. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1016. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1017. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1018. }
  1019. }
  1020. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  1021. {
  1022. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1023. if (await ReConfirmMessage(analysisResult))
  1024. {
  1025. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1026. switch (profileName)
  1027. {
  1028. case "Core":
  1029. {
  1030. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1031. }
  1032. break;
  1033. case "FirmwareManagement":
  1034. {
  1035. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1036. }
  1037. break;
  1038. case "RemoteTrigger":
  1039. {
  1040. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1041. }
  1042. break;
  1043. case "Reservation":
  1044. {
  1045. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1046. }
  1047. break;
  1048. case "LocalAuthListManagement":
  1049. {
  1050. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1051. }
  1052. break;
  1053. case "SmartCharging":
  1054. {
  1055. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1056. }
  1057. break;
  1058. default:
  1059. {
  1060. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1061. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1062. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1063. }
  1064. break;
  1065. }
  1066. }
  1067. else
  1068. {
  1069. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1070. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1071. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1072. }
  1073. }
  1074. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  1075. {
  1076. try
  1077. {
  1078. if (session != null)
  1079. {
  1080. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1081. session.Send(msg);
  1082. }
  1083. }
  1084. catch (Exception ex)
  1085. {
  1086. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  1087. }
  1088. }
  1089. async private Task<string> SetDefaultFee(WsClientData client)
  1090. {
  1091. string displayPriceText = string.Empty;
  1092. string charingPriceText = string.Empty;
  1093. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1094. try
  1095. {
  1096. using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
  1097. {
  1098. var parameters = new DynamicParameters();
  1099. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input, 36);
  1100. string displayPricestrSql = "";
  1101. string strSql = "";
  1102. if (client.IsAC)
  1103. {
  1104. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1105. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1106. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1107. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1108. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1109. }
  1110. else
  1111. {
  1112. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1113. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1114. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1115. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1116. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1117. }
  1118. //var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1119. var result = await conn.QueryFirstOrDefaultAsync<StationFee>(displayPricestrSql, parameters);
  1120. if (result == default)
  1121. {
  1122. return string.Empty;
  1123. }
  1124. var stationPrice = result;//.First();
  1125. if (stationPrice.BillingMethod == 1)
  1126. {
  1127. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1128. client.ChargingPrices = chargingPriceResult.ToList();
  1129. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1130. {
  1131. client.ChargingPrices = new List<ChargingPrice>();
  1132. }
  1133. }
  1134. displayPriceText = stationPrice.FeeName;
  1135. client.BillingMethod = stationPrice.BillingMethod;
  1136. client.Currency = stationPrice.Currency;
  1137. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1138. client.ParkingFee = stationPrice.ParkingFee;
  1139. client.IsBilling = true;
  1140. }
  1141. }
  1142. catch (Exception ex)
  1143. {
  1144. logger.LogError("SetDefaultFee", ex.ToString());
  1145. }
  1146. return displayPriceText;
  1147. }
  1148. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1149. {
  1150. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1151. _needConfirmMsg.Id = table_id;
  1152. _needConfirmMsg.SentAction = action;
  1153. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1154. _needConfirmMsg.SentTimes = 4;
  1155. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1156. _needConfirmMsg.RequestId = requestId;
  1157. _needConfirmMsg.SentUniqueId = msg_id;
  1158. _needConfirmMsg.CreatedBy = createdBy;
  1159. _needConfirmMsg.SentMessage = sendMessage;
  1160. if (needConfirmActions.Contains(action))
  1161. {
  1162. lock (_lockConfirmPacketList)
  1163. {
  1164. needConfirmPacketList.Add(_needConfirmMsg);
  1165. }
  1166. }
  1167. }
  1168. internal void RemoveConfirmMessage()
  1169. {
  1170. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1171. lock (_lockConfirmPacketList)
  1172. {
  1173. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1174. foreach (var item in removeList)
  1175. {
  1176. needConfirmPacketList.Remove(item);
  1177. }
  1178. }
  1179. }
  1180. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1181. {
  1182. bool confirmed = false;
  1183. if (needConfirmActions.Contains(analysisResult.Action))
  1184. {
  1185. NeedConfirmMessage foundRequest = null;
  1186. lock (_lockConfirmPacketList)
  1187. {
  1188. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1189. }
  1190. if (foundRequest != null && foundRequest.Id > 0)
  1191. {
  1192. foundRequest.SentTimes = 0;
  1193. foundRequest.SentInterval = 0;
  1194. analysisResult.RequestId = foundRequest.RequestId;
  1195. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1196. {
  1197. var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
  1198. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1199. sc.ReceivedOn = DateTime.UtcNow;
  1200. await db.SaveChangesAsync();
  1201. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1202. }
  1203. confirmed = true;
  1204. }
  1205. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1206. {
  1207. confirmed = true;
  1208. }
  1209. else
  1210. {
  1211. logger.LogError(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1212. }
  1213. }
  1214. return confirmed;
  1215. }
  1216. internal async void RemoveClient(WsClientData session, string reason)
  1217. {
  1218. if (session == null)
  1219. {
  1220. return;
  1221. }
  1222. if (!string.IsNullOrEmpty(session.MachineId))
  1223. logger.LogTrace("RemoveClient[{0}]:{1}", session.ChargeBoxId, reason);
  1224. WriteMachineLog(session, string.Format("CloseReason: {0}", reason), "Connection", "");
  1225. //if (session.Connected)
  1226. //{
  1227. // session.Close(CloseReason.ServerShutdown);
  1228. //}
  1229. RemoveClientDic(session);
  1230. try
  1231. {
  1232. session.SessionClosed -= AppServer_SessionClosed;
  1233. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  1234. if (session.State == WebSocketState.Open)
  1235. {
  1236. await session.Close();
  1237. }
  1238. // session.Close(CloseReason.ServerShutdown);
  1239. }
  1240. catch (Exception ex)
  1241. {
  1242. //logger.LogWarning("Close client socket error!!");
  1243. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1244. }
  1245. if (session != null)
  1246. {
  1247. session = null;
  1248. }
  1249. }
  1250. private void RemoveClientDic(WsClientData session)
  1251. {
  1252. if (string.IsNullOrEmpty(session.ChargeBoxId))
  1253. {
  1254. return;
  1255. }
  1256. if (clientDic.ContainsKey(session.ChargeBoxId))
  1257. {
  1258. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1259. {
  1260. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1261. clientDic.Remove(session.ChargeBoxId, out _);
  1262. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1263. }
  1264. }
  1265. }
  1266. private void WarmUpLog()
  1267. {
  1268. connectionLogdbService.WarmUpLog();
  1269. }
  1270. private void WriteMachineLog(WsClientData WsClientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1271. {
  1272. try
  1273. {
  1274. if (WsClientData == null || string.IsNullOrEmpty(data)) return;
  1275. if (WsClientData.ChargeBoxId == null)
  1276. {
  1277. logger.LogCritical(WsClientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + WsClientData.SessionID);
  1278. }
  1279. connectionLogdbService.WriteMachineLog(WsClientData, data, messageType, errorMsg, isSent);
  1280. }
  1281. catch (Exception ex)
  1282. {
  1283. //Console.WriteLine(ex.ToString());
  1284. logger.LogError(ex,ex.Message);
  1285. }
  1286. }
  1287. }
  1288. }