ProtalServer.cs 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  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);
  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);
  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. private async void AppServer_NewSessionConnected(WsClientData session)
  537. {
  538. logger.LogDebug(string.Format("{0} NewSessionConnected", session.Path));
  539. try
  540. {
  541. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  542. if (isNotSupported)
  543. {
  544. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  545. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  546. return;
  547. }
  548. //WsClientData _removeClient = null;
  549. //var addedClient = clientDic.GetOrAdd(session.ChargeBoxId, session);
  550. if (clientDic.ContainsKey(session.ChargeBoxId))
  551. {
  552. var oldSession = clientDic[session.ChargeBoxId];
  553. WriteMachineLog(oldSession, "Duplicate Logins", "Connection", "");
  554. //oldSession.Close(CloseReason.ServerShutdown);
  555. RemoveClient(oldSession);
  556. }
  557. clientDic[session.ChargeBoxId] = session;
  558. //clientDic.TryGetValue(session.ChargeBoxId, out _removeClient);
  559. //if (addedClient != session)
  560. //{
  561. // WriteMachineLog(addedClient, "Duplicate Logins", "Connection", "");
  562. // addedClient.Close(CloseReason.ServerShutdown);
  563. // RemoveClient(addedClient);
  564. //}
  565. //clientDic.add.Add(session.ChargeBoxId, session);
  566. session.m_ReceiveData += ReceivedMessageTimeLimited;
  567. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  568. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  569. using (var db = await maindbContextFactory.CreateDbContextAsync())
  570. {
  571. var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
  572. if (machine != null)
  573. {
  574. machine.ConnectionType = session.UriScheme.Contains("wss") ? 2 : 1;
  575. await db.SaveChangesAsync();
  576. }
  577. }
  578. }
  579. catch (Exception ex)
  580. {
  581. logger.LogError(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  582. }
  583. }
  584. async private void ReceivedMessageTimeLimited(object sender, string rawdata)
  585. {
  586. if (sender is not WsClientData session)
  587. {
  588. return;
  589. }
  590. CancellationTokenSource tokenSource = new();
  591. var task = ReceivedMessage(session, rawdata);
  592. var completedTask = await Task.WhenAny(task, Task.Delay(90_000, tokenSource.Token));
  593. if (completedTask != task)
  594. {
  595. logger.LogCritical("Process timeout: {0} ", rawdata);
  596. await task;
  597. return;
  598. }
  599. tokenSource.Cancel();
  600. return;
  601. }
  602. async private Task ReceivedMessage(WsClientData session, string rawdata)
  603. {
  604. try
  605. {
  606. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  607. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  608. WriteMachineLog(session, rawdata,
  609. 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);
  610. if (session.ResetSecurityProfile)
  611. {
  612. logger.LogError(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  613. RemoveClient(session);
  614. return;
  615. }
  616. if (!analysisResult.Success)
  617. {
  618. //解析RawData就發生錯誤
  619. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  620. {
  621. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  622. }
  623. else
  624. {
  625. if (analysisResult.Message == null)
  626. {
  627. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  628. string errorMsg = string.Empty;
  629. if (analysisResult.Exception != null)
  630. {
  631. errorMsg = analysisResult.Exception.ToString();
  632. }
  633. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  634. }
  635. else
  636. {
  637. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  638. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  639. string errorMsg = string.Empty;
  640. if (analysisResult.Exception != null)
  641. {
  642. errorMsg = analysisResult.Exception.ToString();
  643. }
  644. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  645. }
  646. }
  647. }
  648. else
  649. {
  650. switch (analysisResult.Id)
  651. {
  652. case BasicMessageHandler.TYPENUMBER_CALL:
  653. {
  654. if (!session.ISOCPP20)
  655. {
  656. Actions action = Convertor.GetAction(analysisResult.Action);
  657. try
  658. {
  659. await ProcessRequestMessage(analysisResult, session, action);
  660. }
  661. catch (Exception e)
  662. {
  663. logger.LogError($"Processing {action} exception!");
  664. throw;
  665. }
  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.BootNotification:
  675. {
  676. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  677. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  678. result.Message = confirm;
  679. result.Success = true;
  680. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  681. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  682. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  683. {
  684. ConfigurationSlot = 1,
  685. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  686. {
  687. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  688. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  689. MessageTimeout = 30,
  690. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  691. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  692. }
  693. };
  694. var uuid = session.queue20.store(request);
  695. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  696. Send(session, requestText, "SetNetworkProfile");
  697. }
  698. break;
  699. default:
  700. {
  701. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  702. }
  703. break;
  704. }
  705. }
  706. }
  707. break;
  708. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  709. {
  710. if (!session.ISOCPP20)
  711. {
  712. Actions action = Convertor.GetAction(analysisResult.Action);
  713. ProcessConfirmationMessage(analysisResult, session, action);
  714. }
  715. else
  716. {
  717. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  718. MessageResult result = new MessageResult() { Success = true };
  719. //ocpp20 處理
  720. switch (action)
  721. {
  722. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  723. {
  724. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  725. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  726. {
  727. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  728. {
  729. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  730. {
  731. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  732. {
  733. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  734. {
  735. Name="OCPPCommCtrlr",
  736. },
  737. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  738. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  739. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  740. {
  741. Name="NetworkConfigurationPriority",
  742. }
  743. }
  744. }
  745. };
  746. var uuid = session.queue20.store(request);
  747. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  748. Send(session, requestText, "SetVariables");
  749. }
  750. }
  751. break;
  752. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  753. {
  754. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  755. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  756. {
  757. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  758. {
  759. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  760. };
  761. var uuid = session.queue20.store(request);
  762. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  763. Send(session, requestText, "Reset");
  764. }
  765. }
  766. break;
  767. default:
  768. {
  769. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  770. }
  771. break;
  772. }
  773. }
  774. }
  775. break;
  776. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  777. {
  778. //只處理 丟出Request 收到Error的訊息
  779. if (analysisResult.Success && analysisResult.Message != null)
  780. {
  781. Actions action = Convertor.GetAction(analysisResult.Action);
  782. ProcessErrorMessage(analysisResult, session, action);
  783. }
  784. }
  785. break;
  786. default:
  787. {
  788. logger.LogError(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  789. }
  790. break;
  791. }
  792. }
  793. await Task.Delay(10);
  794. }
  795. catch (Exception ex)
  796. {
  797. if (ex.InnerException != null)
  798. {
  799. logger.LogError(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  800. }
  801. else
  802. {
  803. logger.LogError(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  804. }
  805. }
  806. }
  807. private async Task ProcessRequestMessage(MessageResult analysisResult, WsClientData session, Actions action)
  808. {
  809. Stopwatch outter_stopwatch = Stopwatch.StartNew();
  810. //BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  811. if (!session.IsCheckIn && action != Actions.BootNotification)
  812. {
  813. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  814. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  815. }
  816. else
  817. {
  818. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  819. switch (profileName)
  820. {
  821. case "Core":
  822. {
  823. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  824. var sendTimer = Stopwatch.StartNew();
  825. if (replyResult.Success)
  826. {
  827. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  828. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString());
  829. if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
  830. {
  831. if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  832. {
  833. session.IsCheckIn = true;
  834. await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId);
  835. await messageService.SendDataTransferRequest(
  836. session.ChargeBoxId,
  837. messageId: "ID_FirmwareVersion",
  838. vendorId: "Phihong Technology",
  839. data: string.Empty);
  840. }
  841. else
  842. {
  843. // Pending mode 下發設定
  844. using (var db = await maindbContextFactory.CreateDbContextAsync())
  845. {
  846. var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
  847. if (machine != null)
  848. {
  849. if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
  850. {
  851. session.IsAC = false;
  852. }
  853. machine.ConnectionType = session.UriScheme.Contains("wss") ? 2 : 1;
  854. await db.SaveChangesAsync();
  855. }
  856. }
  857. await messageService.SendChangeConfigurationRequest(
  858. session.ChargeBoxId, key: "MeteringWithKilowatt", value: "True");
  859. await SetDefaultFee(session);
  860. if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
  861. {
  862. await messageService.SendChangeConfigurationRequest(
  863. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  864. }
  865. if (session.CustomerId == new Guid("D57D5BCC-C5B0-4031-A7AE-7516E00CB028") )
  866. {
  867. await messageService.SendChangeConfigurationRequest(
  868. session.ChargeBoxId, key: "StopTransactionOnInvalidId", value: "True");
  869. }
  870. }
  871. }
  872. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  873. {
  874. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  875. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  876. {
  877. await messageService.SendDataTransferRequest(
  878. session.ChargeBoxId,
  879. messageId: "SetUserPrice",
  880. vendorId: "Phihong Technology",
  881. data: JsonConvert.SerializeObject(
  882. new
  883. {
  884. idToken = authorizeRequest.idTag,
  885. price = session.UserDisplayPrices[authorizeRequest.idTag]
  886. })
  887. );
  888. }
  889. }
  890. }
  891. else
  892. {
  893. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  894. {
  895. //do nothing
  896. logger.LogWarning(replyResult.Exception.ToString());
  897. }
  898. else
  899. {
  900. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  901. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  902. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  903. }
  904. }
  905. sendTimer.Stop();
  906. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  907. {
  908. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  909. }
  910. if (action == Actions.StartTransaction)
  911. {
  912. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  913. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  914. if (_powerDic != null)
  915. {
  916. foreach (var kv in _powerDic)
  917. {
  918. try
  919. {
  920. if (kv.Value.HasValue)
  921. {
  922. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  923. }
  924. }
  925. catch (Exception ex)
  926. {
  927. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  928. }
  929. }
  930. }
  931. }
  932. if (action == Actions.StopTransaction)
  933. {
  934. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  935. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  936. if (_powerDic != null)
  937. {
  938. foreach (var kv in _powerDic)
  939. {
  940. try
  941. {
  942. if (kv.Value.HasValue)
  943. {
  944. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  945. }
  946. }
  947. catch (Exception ex)
  948. {
  949. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  950. }
  951. }
  952. }
  953. }
  954. }
  955. break;
  956. case "FirmwareManagement":
  957. {
  958. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  959. if (replyResult.Success)
  960. {
  961. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  962. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  963. }
  964. else
  965. {
  966. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  967. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  968. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  969. }
  970. }
  971. break;
  972. case "Security":
  973. {
  974. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  975. if (replyResult.Success)
  976. {
  977. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  978. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  979. }
  980. else
  981. {
  982. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  983. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  984. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  985. }
  986. }
  987. break;
  988. default:
  989. {
  990. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  991. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  992. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  993. }
  994. break;
  995. }
  996. }
  997. outter_stopwatch.Stop();
  998. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  999. {
  1000. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  1001. }
  1002. }
  1003. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  1004. {
  1005. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1006. if (await ReConfirmMessage(analysisResult))
  1007. {
  1008. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1009. MessageResult confirmResult = null;
  1010. switch (profileName)
  1011. {
  1012. case "Core":
  1013. {
  1014. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1015. }
  1016. break;
  1017. case "FirmwareManagement":
  1018. {
  1019. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1020. }
  1021. break;
  1022. case "RemoteTrigger":
  1023. {
  1024. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1025. }
  1026. break;
  1027. case "Reservation":
  1028. {
  1029. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1030. }
  1031. break;
  1032. case "LocalAuthListManagement":
  1033. {
  1034. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1035. }
  1036. break;
  1037. case "SmartCharging":
  1038. {
  1039. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1040. }
  1041. break;
  1042. case "Security":
  1043. {
  1044. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1045. }
  1046. break;
  1047. default:
  1048. {
  1049. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1050. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1051. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1052. }
  1053. break;
  1054. }
  1055. if (confirmResult == null || !confirmResult.Success)
  1056. {
  1057. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  1058. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  1059. }
  1060. }
  1061. else
  1062. {
  1063. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1064. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1065. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1066. }
  1067. }
  1068. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  1069. {
  1070. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1071. if (await ReConfirmMessage(analysisResult))
  1072. {
  1073. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1074. switch (profileName)
  1075. {
  1076. case "Core":
  1077. {
  1078. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1079. }
  1080. break;
  1081. case "FirmwareManagement":
  1082. {
  1083. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1084. }
  1085. break;
  1086. case "RemoteTrigger":
  1087. {
  1088. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1089. }
  1090. break;
  1091. case "Reservation":
  1092. {
  1093. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1094. }
  1095. break;
  1096. case "LocalAuthListManagement":
  1097. {
  1098. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1099. }
  1100. break;
  1101. case "SmartCharging":
  1102. {
  1103. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1104. }
  1105. break;
  1106. default:
  1107. {
  1108. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1109. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1110. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1111. }
  1112. break;
  1113. }
  1114. }
  1115. else
  1116. {
  1117. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1118. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1119. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1120. }
  1121. }
  1122. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  1123. {
  1124. try
  1125. {
  1126. if (session != null)
  1127. {
  1128. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1129. session.Send(msg);
  1130. }
  1131. }
  1132. catch (Exception ex)
  1133. {
  1134. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  1135. }
  1136. }
  1137. async private Task<string> SetDefaultFee(WsClientData client)
  1138. {
  1139. string displayPriceText = string.Empty;
  1140. string charingPriceText = string.Empty;
  1141. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1142. try
  1143. {
  1144. using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
  1145. {
  1146. var parameters = new DynamicParameters();
  1147. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input, 36);
  1148. string displayPricestrSql = "";
  1149. string strSql = "";
  1150. if (client.IsAC)
  1151. {
  1152. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1153. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1154. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1155. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1156. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1157. }
  1158. else
  1159. {
  1160. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1161. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1162. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1163. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1164. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1165. }
  1166. //var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1167. var result = await conn.QueryFirstOrDefaultAsync<StationFee>(displayPricestrSql, parameters);
  1168. if (result == default)
  1169. {
  1170. return string.Empty;
  1171. }
  1172. var stationPrice = result;//.First();
  1173. if (stationPrice.BillingMethod == 1)
  1174. {
  1175. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1176. client.ChargingPrices = chargingPriceResult.ToList();
  1177. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1178. {
  1179. client.ChargingPrices = new List<ChargingPrice>();
  1180. }
  1181. }
  1182. displayPriceText = stationPrice.FeeName;
  1183. client.BillingMethod = stationPrice.BillingMethod;
  1184. client.Currency = stationPrice.Currency;
  1185. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1186. client.ParkingFee = stationPrice.ParkingFee;
  1187. client.IsBilling = true;
  1188. }
  1189. }
  1190. catch (Exception ex)
  1191. {
  1192. logger.LogError("SetDefaultFee", ex.ToString());
  1193. }
  1194. return displayPriceText;
  1195. }
  1196. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1197. {
  1198. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1199. _needConfirmMsg.Id = table_id;
  1200. _needConfirmMsg.SentAction = action;
  1201. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1202. _needConfirmMsg.SentTimes = 4;
  1203. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1204. _needConfirmMsg.RequestId = requestId;
  1205. _needConfirmMsg.SentUniqueId = msg_id;
  1206. _needConfirmMsg.CreatedBy = createdBy;
  1207. _needConfirmMsg.SentMessage = sendMessage;
  1208. if (needConfirmActions.Contains(action))
  1209. {
  1210. lock (_lockConfirmPacketList)
  1211. {
  1212. needConfirmPacketList.Add(_needConfirmMsg);
  1213. }
  1214. }
  1215. }
  1216. internal void RemoveConfirmMessage()
  1217. {
  1218. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1219. lock (_lockConfirmPacketList)
  1220. {
  1221. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1222. foreach (var item in removeList)
  1223. {
  1224. needConfirmPacketList.Remove(item);
  1225. }
  1226. }
  1227. }
  1228. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1229. {
  1230. bool confirmed = false;
  1231. if (needConfirmActions.Contains(analysisResult.Action))
  1232. {
  1233. NeedConfirmMessage foundRequest = null;
  1234. lock (_lockConfirmPacketList)
  1235. {
  1236. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1237. }
  1238. if (foundRequest != null && foundRequest.Id > 0)
  1239. {
  1240. foundRequest.SentTimes = 0;
  1241. foundRequest.SentInterval = 0;
  1242. analysisResult.RequestId = foundRequest.RequestId;
  1243. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1244. {
  1245. var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
  1246. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1247. sc.ReceivedOn = DateTime.UtcNow;
  1248. await db.SaveChangesAsync();
  1249. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1250. }
  1251. confirmed = true;
  1252. }
  1253. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1254. {
  1255. confirmed = true;
  1256. }
  1257. else
  1258. {
  1259. logger.LogError(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1260. }
  1261. }
  1262. return confirmed;
  1263. }
  1264. internal async void RemoveClient(WsClientData session)
  1265. {
  1266. if (session == null)
  1267. {
  1268. return;
  1269. }
  1270. if (!string.IsNullOrEmpty(session.MachineId))
  1271. logger.LogTrace("RemoveClient[" + session.ChargeBoxId + "]");
  1272. //if (session.Connected)
  1273. //{
  1274. // session.Close(CloseReason.ServerShutdown);
  1275. //}
  1276. RemoveClientDic(session);
  1277. try
  1278. {
  1279. if (session.State == WebSocketState.Open)
  1280. {
  1281. await session.Close();
  1282. }
  1283. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  1284. // session.Close(CloseReason.ServerShutdown);
  1285. }
  1286. catch (Exception ex)
  1287. {
  1288. //logger.LogWarning("Close client socket error!!");
  1289. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1290. }
  1291. if (session != null)
  1292. {
  1293. session = null;
  1294. }
  1295. }
  1296. private void RemoveClientDic(WsClientData session)
  1297. {
  1298. if (string.IsNullOrEmpty(session.ChargeBoxId))
  1299. {
  1300. return;
  1301. }
  1302. if (clientDic.ContainsKey(session.ChargeBoxId))
  1303. {
  1304. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1305. {
  1306. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1307. clientDic.Remove(session.ChargeBoxId, out _);
  1308. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1309. }
  1310. }
  1311. }
  1312. private void WarmUpLog()
  1313. {
  1314. connectionLogdbService.WarmUpLog();
  1315. }
  1316. private void WriteMachineLog(WsClientData WsClientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1317. {
  1318. try
  1319. {
  1320. if (WsClientData == null || string.IsNullOrEmpty(data)) return;
  1321. if (WsClientData.ChargeBoxId == null)
  1322. {
  1323. logger.LogCritical(WsClientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + WsClientData.SessionID);
  1324. }
  1325. connectionLogdbService.WriteMachineLog(WsClientData, data, messageType, errorMsg, isSent);
  1326. }
  1327. catch (Exception ex)
  1328. {
  1329. //Console.WriteLine(ex.ToString());
  1330. logger.LogError(ex,ex.Message);
  1331. }
  1332. }
  1333. }
  1334. }