ProtalServer.cs 68 KB

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