ProtalServer.cs 70 KB

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