ProtalServer.cs 73 KB

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