ProtalServer.cs 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  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 SetDefaultFee(session);
  810. if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
  811. {
  812. await messageService.SendChangeConfigurationRequest(
  813. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  814. }
  815. if (session.CustomerId == new Guid("D57D5BCC-C5B0-4031-A7AE-7516E00CB028") )
  816. {
  817. await messageService.SendChangeConfigurationRequest(
  818. session.ChargeBoxId, key: "StopTransactionOnInvalidId", value: "True");
  819. }
  820. }
  821. }
  822. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  823. {
  824. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  825. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  826. {
  827. await messageService.SendDataTransferRequest(
  828. session.ChargeBoxId,
  829. messageId: "SetUserPrice",
  830. vendorId: "Phihong Technology",
  831. data: JsonConvert.SerializeObject(
  832. new
  833. {
  834. idToken = authorizeRequest.idTag,
  835. price = session.UserDisplayPrices[authorizeRequest.idTag]
  836. })
  837. );
  838. }
  839. }
  840. }
  841. else
  842. {
  843. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  844. {
  845. //do nothing
  846. logger.LogWarning(replyResult.Exception.ToString());
  847. }
  848. else
  849. {
  850. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  851. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  852. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  853. }
  854. }
  855. sendTimer.Stop();
  856. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  857. {
  858. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  859. }
  860. if (action == Actions.StartTransaction)
  861. {
  862. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  863. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  864. if (_powerDic != null)
  865. {
  866. foreach (var kv in _powerDic)
  867. {
  868. try
  869. {
  870. if (kv.Value.HasValue)
  871. {
  872. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  873. }
  874. }
  875. catch (Exception ex)
  876. {
  877. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  878. }
  879. }
  880. }
  881. }
  882. if (action == Actions.StopTransaction)
  883. {
  884. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  885. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  886. if (_powerDic != null)
  887. {
  888. foreach (var kv in _powerDic)
  889. {
  890. try
  891. {
  892. if (kv.Value.HasValue)
  893. {
  894. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  895. }
  896. }
  897. catch (Exception ex)
  898. {
  899. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  900. }
  901. }
  902. }
  903. }
  904. }
  905. break;
  906. case "FirmwareManagement":
  907. {
  908. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  909. if (replyResult.Success)
  910. {
  911. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  912. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  913. }
  914. else
  915. {
  916. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  917. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  918. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  919. }
  920. }
  921. break;
  922. case "Security":
  923. {
  924. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  925. if (replyResult.Success)
  926. {
  927. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  928. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  929. }
  930. else
  931. {
  932. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  933. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  934. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  935. }
  936. }
  937. break;
  938. default:
  939. {
  940. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  941. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  942. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  943. }
  944. break;
  945. }
  946. }
  947. outter_stopwatch.Stop();
  948. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  949. {
  950. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  951. }
  952. }
  953. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  954. {
  955. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  956. if (await ReConfirmMessage(analysisResult))
  957. {
  958. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  959. MessageResult confirmResult = null;
  960. switch (profileName)
  961. {
  962. case "Core":
  963. {
  964. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  965. }
  966. break;
  967. case "FirmwareManagement":
  968. {
  969. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  970. }
  971. break;
  972. case "RemoteTrigger":
  973. {
  974. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  975. }
  976. break;
  977. case "Reservation":
  978. {
  979. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  980. }
  981. break;
  982. case "LocalAuthListManagement":
  983. {
  984. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  985. }
  986. break;
  987. case "SmartCharging":
  988. {
  989. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  990. }
  991. break;
  992. case "Security":
  993. {
  994. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  995. }
  996. break;
  997. default:
  998. {
  999. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1000. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1001. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1002. }
  1003. break;
  1004. }
  1005. if (confirmResult == null || !confirmResult.Success)
  1006. {
  1007. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  1008. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  1009. }
  1010. }
  1011. else
  1012. {
  1013. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1014. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1015. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1016. }
  1017. }
  1018. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  1019. {
  1020. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1021. if (await ReConfirmMessage(analysisResult))
  1022. {
  1023. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1024. switch (profileName)
  1025. {
  1026. case "Core":
  1027. {
  1028. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1029. }
  1030. break;
  1031. case "FirmwareManagement":
  1032. {
  1033. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1034. }
  1035. break;
  1036. case "RemoteTrigger":
  1037. {
  1038. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1039. }
  1040. break;
  1041. case "Reservation":
  1042. {
  1043. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1044. }
  1045. break;
  1046. case "LocalAuthListManagement":
  1047. {
  1048. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1049. }
  1050. break;
  1051. case "SmartCharging":
  1052. {
  1053. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1054. }
  1055. break;
  1056. default:
  1057. {
  1058. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1059. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1060. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1061. }
  1062. break;
  1063. }
  1064. }
  1065. else
  1066. {
  1067. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1068. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1069. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1070. }
  1071. }
  1072. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  1073. {
  1074. try
  1075. {
  1076. if (session != null)
  1077. {
  1078. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1079. session.Send(msg);
  1080. }
  1081. }
  1082. catch (Exception ex)
  1083. {
  1084. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  1085. }
  1086. }
  1087. async private Task<string> SetDefaultFee(WsClientData client)
  1088. {
  1089. string displayPriceText = string.Empty;
  1090. string charingPriceText = string.Empty;
  1091. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1092. try
  1093. {
  1094. using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
  1095. {
  1096. var parameters = new DynamicParameters();
  1097. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input, 36);
  1098. string displayPricestrSql = "";
  1099. string strSql = "";
  1100. if (client.IsAC)
  1101. {
  1102. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1103. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1104. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1105. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1106. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1107. }
  1108. else
  1109. {
  1110. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1111. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1112. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1113. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1114. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1115. }
  1116. //var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1117. var result = await conn.QueryFirstOrDefaultAsync<StationFee>(displayPricestrSql, parameters);
  1118. if (result == default)
  1119. {
  1120. return string.Empty;
  1121. }
  1122. var stationPrice = result;//.First();
  1123. if (stationPrice.BillingMethod == 1)
  1124. {
  1125. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1126. client.ChargingPrices = chargingPriceResult.ToList();
  1127. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1128. {
  1129. client.ChargingPrices = new List<ChargingPrice>();
  1130. }
  1131. }
  1132. displayPriceText = stationPrice.FeeName;
  1133. client.BillingMethod = stationPrice.BillingMethod;
  1134. client.Currency = stationPrice.Currency;
  1135. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1136. client.ParkingFee = stationPrice.ParkingFee;
  1137. client.IsBilling = true;
  1138. }
  1139. }
  1140. catch (Exception ex)
  1141. {
  1142. logger.LogError("SetDefaultFee", ex.ToString());
  1143. }
  1144. return displayPriceText;
  1145. }
  1146. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1147. {
  1148. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1149. _needConfirmMsg.Id = table_id;
  1150. _needConfirmMsg.SentAction = action;
  1151. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1152. _needConfirmMsg.SentTimes = 4;
  1153. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1154. _needConfirmMsg.RequestId = requestId;
  1155. _needConfirmMsg.SentUniqueId = msg_id;
  1156. _needConfirmMsg.CreatedBy = createdBy;
  1157. _needConfirmMsg.SentMessage = sendMessage;
  1158. if (needConfirmActions.Contains(action))
  1159. {
  1160. lock (_lockConfirmPacketList)
  1161. {
  1162. needConfirmPacketList.Add(_needConfirmMsg);
  1163. }
  1164. }
  1165. }
  1166. internal void RemoveConfirmMessage()
  1167. {
  1168. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1169. lock (_lockConfirmPacketList)
  1170. {
  1171. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1172. foreach (var item in removeList)
  1173. {
  1174. needConfirmPacketList.Remove(item);
  1175. }
  1176. }
  1177. }
  1178. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1179. {
  1180. bool confirmed = false;
  1181. if (needConfirmActions.Contains(analysisResult.Action))
  1182. {
  1183. NeedConfirmMessage foundRequest = null;
  1184. lock (_lockConfirmPacketList)
  1185. {
  1186. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1187. }
  1188. if (foundRequest != null && foundRequest.Id > 0)
  1189. {
  1190. foundRequest.SentTimes = 0;
  1191. foundRequest.SentInterval = 0;
  1192. analysisResult.RequestId = foundRequest.RequestId;
  1193. try
  1194. {
  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. }
  1204. catch (Exception ex)
  1205. {
  1206. logger.LogWarning(string.Format("ReConfirmMessage:{0}", JsonConvert.SerializeObject(analysisResult)));
  1207. logger.LogWarning(ex.ToString());
  1208. }
  1209. confirmed = true;
  1210. }
  1211. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1212. {
  1213. confirmed = true;
  1214. }
  1215. else
  1216. {
  1217. logger.LogError(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1218. }
  1219. }
  1220. return confirmed;
  1221. }
  1222. internal async void RemoveClient(WsClientData session, string reason)
  1223. {
  1224. if (session == null)
  1225. {
  1226. return;
  1227. }
  1228. if (!string.IsNullOrEmpty(session.MachineId))
  1229. logger.LogTrace("RemoveClient[{0}]:{1}", session.ChargeBoxId, reason);
  1230. WriteMachineLog(session, string.Format("CloseReason: {0}", reason), "Connection", "");
  1231. //if (session.Connected)
  1232. //{
  1233. // session.Close(CloseReason.ServerShutdown);
  1234. //}
  1235. RemoveClientDic(session);
  1236. try
  1237. {
  1238. session.SessionClosed -= AppServer_SessionClosed;
  1239. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  1240. if (session.State == WebSocketState.Open)
  1241. {
  1242. await session.Close();
  1243. }
  1244. // session.Close(CloseReason.ServerShutdown);
  1245. }
  1246. catch (Exception ex)
  1247. {
  1248. //logger.LogWarning("Close client socket error!!");
  1249. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1250. }
  1251. if (session != null)
  1252. {
  1253. session = null;
  1254. }
  1255. }
  1256. private void RemoveClientDic(WsClientData session)
  1257. {
  1258. if (string.IsNullOrEmpty(session.ChargeBoxId))
  1259. {
  1260. return;
  1261. }
  1262. if (clientDic.ContainsKey(session.ChargeBoxId))
  1263. {
  1264. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1265. {
  1266. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1267. clientDic.Remove(session.ChargeBoxId, out _);
  1268. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1269. }
  1270. }
  1271. }
  1272. private void WarmUpLog()
  1273. {
  1274. connectionLogdbService.WarmUpLog();
  1275. }
  1276. private void WriteMachineLog(WsClientData WsClientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1277. {
  1278. try
  1279. {
  1280. if (WsClientData == null || string.IsNullOrEmpty(data)) return;
  1281. if (WsClientData.ChargeBoxId == null)
  1282. {
  1283. logger.LogCritical(WsClientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + WsClientData.SessionID);
  1284. }
  1285. connectionLogdbService.WriteMachineLog(WsClientData, data, messageType, errorMsg, isSent);
  1286. }
  1287. catch (Exception ex)
  1288. {
  1289. //Console.WriteLine(ex.ToString());
  1290. logger.LogError(ex,ex.Message);
  1291. }
  1292. }
  1293. }
  1294. }