ProtalServer.cs 70 KB

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