ProtalServer.cs 69 KB

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