ProtalServer.cs 69 KB

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