ProtalServer.cs 70 KB

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