ProtalServer.cs 72 KB

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