ProtalServer.cs 70 KB

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