ProtalServer.cs 69 KB

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