ProtalServer.cs 69 KB

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