ProtalServer.cs 72 KB

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