ProtalServer.cs 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. using EVCB_OCPP.Packet.Features;
  2. using EVCB_OCPP.Packet.Messages;
  3. using EVCB_OCPP.Packet.Messages.Basic;
  4. using EVCB_OCPP.Packet.Messages.Core;
  5. using EVCB_OCPP.WSServer.Dto;
  6. using EVCB_OCPP.WSServer.Helper;
  7. using EVCB_OCPP.WSServer.Message;
  8. using EVCB_OCPP.WSServer.Service;
  9. using Microsoft.Extensions.Hosting;
  10. using Newtonsoft.Json;
  11. using OCPPServer.Protocol;
  12. using OCPPServer.SubProtocol;
  13. using SuperSocket.SocketBase;
  14. using SuperSocket.SocketBase.Config;
  15. using System.Data;
  16. using System.Diagnostics;
  17. using System.Security.Authentication;
  18. using System.Xml.Linq;
  19. using NLog;
  20. using Microsoft.Extensions.Configuration;
  21. using Microsoft.Extensions.DependencyInjection;
  22. using Microsoft.AspNetCore.Builder;
  23. using NLog.Extensions.Logging;
  24. using System.Collections.Concurrent;
  25. using EVCB_OCPP.WSServer.SuperSocket;
  26. using Microsoft.Extensions.Logging;
  27. using System.Net.WebSockets;
  28. using SuperWebSocket;
  29. using System.Net;
  30. using System.Text;
  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. , IMainDbService mainDbService
  52. , IOCPPWSServerFactory ocppWSServerFactory
  53. , IConnectionLogdbService connectionLogdbService
  54. , LoadingBalanceService loadingBalanceService
  55. , ServerMessageService serverMessageService
  56. , WebDbService webDbService
  57. , ProfileHandler profileHandler
  58. , WebsocketService<WsClientData> websocketService
  59. , OuterHttpClient httpClient)
  60. {
  61. this.logger = logger;
  62. this.configuration = configuration;
  63. this.mainDbService = mainDbService;
  64. this.ocppWSServerFactory = ocppWSServerFactory;
  65. this.connectionLogdbService = connectionLogdbService;
  66. this.webDbService = webDbService;
  67. this.httpClient = httpClient;
  68. isInDocker = !string.IsNullOrEmpty(configuration["DOTNET_RUNNING_IN_CONTAINER"]);
  69. this.profileHandler = profileHandler;// new ProfileHandler(configuration, serviceProvider);
  70. this.websocketService = websocketService;
  71. this._loadingBalanceService = loadingBalanceService;// new LoadingBalanceService(mainDbConnectionFactory, webDbConnectionFactory);
  72. this.messageService = serverMessageService;
  73. WarmUpLog();
  74. }
  75. #region private fields
  76. private OuterHttpClient httpClient;
  77. private DateTime lastcheckdt = DateTime.UtcNow.AddSeconds(-20);
  78. private ConcurrentDictionary<string, WsClientData> clientDic = new ConcurrentDictionary<string, WsClientData>();
  79. //private readonly Object _lockClientDic = new object();
  80. private readonly Object _lockConfirmPacketList = new object();
  81. private readonly ILogger<ProtalServer> logger;
  82. private readonly IConfiguration configuration;
  83. private readonly IMainDbService mainDbService;
  84. private readonly IOCPPWSServerFactory ocppWSServerFactory;
  85. private readonly IConnectionLogdbService connectionLogdbService;
  86. private readonly WebDbService webDbService;
  87. private readonly ProfileHandler profileHandler;
  88. private readonly WebsocketService<WsClientData> websocketService;
  89. private readonly bool isInDocker;
  90. private List<NeedConfirmMessage> needConfirmPacketList = new List<NeedConfirmMessage>();
  91. private DateTime checkUpdateDt = DateTime.UtcNow;
  92. private DateTime _CheckFeeDt = DateTime.UtcNow;
  93. private DateTime _CheckLBDt = DateTime.UtcNow;
  94. private DateTime _CheckDenyListDt = DateTime.UtcNow.AddDays(-1);
  95. private readonly LoadingBalanceService _loadingBalanceService;// = new LoadingBalanceService();
  96. private readonly ServerMessageService messageService;
  97. private List<StationInfoDto> _StationInfo = new List<StationInfoDto>();
  98. private readonly List<string> needConfirmActions = new List<string>()
  99. {
  100. "GetConfiguration",
  101. "ChangeConfiguration",
  102. "RemoteStartTransaction",
  103. "RemoteStopTransaction",
  104. "ChangeAvailability",
  105. "ClearCache",
  106. "DataTransfer",
  107. "Reset",
  108. "UnlockConnector",
  109. "TriggerMessage",
  110. "GetDiagnostics",
  111. "UpdateFirmware",
  112. "GetLocalListVersion",
  113. "SendLocalList",
  114. "SetChargingProfile",
  115. "ClearChargingProfile",
  116. "GetCompositeSchedule",
  117. "ReserveNow",
  118. "CancelReservation",
  119. "ExtendedTriggerMessage"
  120. };
  121. private readonly List<Profile> profiles = new List<Profile>()
  122. {
  123. new CoreProfile(),
  124. new FirmwareManagementProfile(),
  125. new ReservationProfile(),
  126. new RemoteTriggerProfile(),
  127. new SmartChargingProfile(),
  128. new LocalAuthListManagementProfile(),
  129. new SecurityProfile(),
  130. };
  131. #endregion
  132. private OCPPWSServer appServer;
  133. private WebApplication appApi;
  134. private WebApplication yarpApp;
  135. internal Dictionary<string, WsClientData> GetClientDic()
  136. {
  137. Dictionary<string, WsClientData> toReturn = null;
  138. toReturn = new Dictionary<string, WsClientData>(clientDic);
  139. return toReturn;
  140. }
  141. internal List<NeedConfirmMessage> GetResendMessage()
  142. {
  143. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  144. lock (_lockConfirmPacketList)
  145. {
  146. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  147. }
  148. return sendMessages;
  149. }
  150. internal IReadOnlyList<Profile> Profiles => profiles.AsReadOnly();
  151. internal LoadingBalanceService LoadingBalanceService => _loadingBalanceService;
  152. internal ProfileHandler ProfileHandler => profileHandler;
  153. public async Task StartAsync(CancellationToken cancellationToken)
  154. {
  155. GlobalConfig.DenyModelNames = await webDbService.GetDenyModelNames();
  156. Start();
  157. return;
  158. }
  159. public Task StopAsync(CancellationToken cancellationToken)
  160. {
  161. return Stop();
  162. //return Task.CompletedTask;
  163. }
  164. internal void UpdateClientDisplayPrice(string key,string price)
  165. {
  166. clientDic[key].DisplayPrice = price;
  167. }
  168. internal void SendMsg(WsClientData session, string msg, string messageType, string errorMsg = "")
  169. {
  170. Send(session,msg,messageType,errorMsg);
  171. }
  172. internal void Start()
  173. {
  174. logger.LogTrace("Starting Server...");
  175. if (!GlobalConfig.LoadAPPConfig(configuration))
  176. {
  177. logger.LogError("Please check App.Config setting .");
  178. return;
  179. }
  180. StartWsService();
  181. if (!isInDocker)
  182. {
  183. Task consoleReadTask = new Task(RunConsoleInteractive);
  184. consoleReadTask.Start();
  185. //RunConsoleInteractive();
  186. return;
  187. }
  188. return;
  189. }
  190. private void RunConsoleInteractive()
  191. {
  192. while (true)
  193. {
  194. if (Console.In is null)
  195. {
  196. break;
  197. }
  198. var input = Console.ReadLine();
  199. switch (input.ToLower())
  200. {
  201. case "stop":
  202. Console.WriteLine("Command stop");
  203. Stop();
  204. break;
  205. case "gc":
  206. Console.WriteLine("Command GC");
  207. GC.Collect();
  208. break;
  209. case "lc":
  210. {
  211. Console.WriteLine("Command List Clients");
  212. Dictionary<string, WsClientData> _copyClientDic = null;
  213. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  214. var list = _copyClientDic.Select(c => c.Value).ToList();
  215. int i = 1;
  216. foreach (var c in list)
  217. {
  218. Console.WriteLine(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  219. i++;
  220. }
  221. }
  222. break;
  223. case "lcn":
  224. {
  225. Console.WriteLine("Command List Customer Name");
  226. Dictionary<string, WsClientData> _copyClientDic = null;
  227. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  228. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  229. int iLcn = 1;
  230. foreach (var c in lcn)
  231. {
  232. Console.WriteLine(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  233. iLcn++;
  234. }
  235. }
  236. break;
  237. case "help":
  238. Console.WriteLine("Command help!!");
  239. Console.WriteLine("lcn : List Customer Name");
  240. Console.WriteLine("gc : GC Collect");
  241. Console.WriteLine("lc : List Clients");
  242. Console.WriteLine("cls : clear console");
  243. Console.WriteLine("silent : silent");
  244. Console.WriteLine("show : show log");
  245. // logger.Info("rcl : show Real Connection Limit");
  246. break;
  247. case "cls":
  248. Console.WriteLine("Command clear");
  249. Console.Clear();
  250. break;
  251. case "silent":
  252. Console.WriteLine("Command silent");
  253. //var xe = XElement.Load("NLog.config");
  254. //var xns = xe.GetDefaultNamespace();
  255. //var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  256. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  257. //if (minlevelattr != null)
  258. //{
  259. // minlevelattr.Value = "Warn";
  260. //}
  261. //xe.Save("NLog.config");
  262. foreach (var rule in LogManager.Configuration.LoggingRules)
  263. {
  264. if (rule.RuleName != "ConsoleLog")
  265. {
  266. continue;
  267. }
  268. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  269. if (isTargetRule)
  270. {
  271. rule.SetLoggingLevels(NLog.LogLevel.Warn, NLog.LogLevel.Off);
  272. }
  273. }
  274. break;
  275. case "show":
  276. Console.WriteLine("Command show");
  277. //var xe1 = XElement.Load("NLog.config");
  278. //var xns1 = xe1.GetDefaultNamespace();
  279. //var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  280. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  281. //if (minlevelattr1 != null)
  282. //{
  283. // minlevelattr1.Value = "trace";
  284. //}
  285. //xe1.Save("NLog.config");
  286. foreach (var rule in LogManager.Configuration.LoggingRules)
  287. {
  288. if (rule.RuleName != "ConsoleLog")
  289. {
  290. continue;
  291. }
  292. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  293. if (isTargetRule)
  294. {
  295. rule.SetLoggingLevels(NLog.LogLevel.Trace, NLog.LogLevel.Off);
  296. }
  297. }
  298. break;
  299. case "rcl":
  300. break;
  301. default:
  302. break;
  303. }
  304. }
  305. }
  306. internal Task Stop()
  307. {
  308. appServer?.Stop();
  309. return Task.WhenAll(new []{
  310. appApi?.StopAsync(),
  311. yarpApp?.StopAsync()
  312. });
  313. }
  314. private void StartWsService()
  315. {
  316. //載入OCPP Protocol
  317. //appServer = ocppWSServerFactory.Create(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0") });
  318. //var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0") });
  319. //List<IListenerConfig> llistener = new List<IListenerConfig>();
  320. //if (GlobalConfig.GetWS_Port() != 0)
  321. //{
  322. // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = GlobalConfig.GetWS_Port(), Backlog = 100, Security = "None" });
  323. //}
  324. //foreach (var securityport in GlobalConfig.GetWSS_Ports())
  325. //{
  326. // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = securityport, Backlog = 100, Security = SslProtocols.Tls12.ToString() });
  327. //}
  328. //var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;\
  329. //var certificate = configuration.GetSection("superSocket").GetSection("Servers:0").GetSection("Certificate").Get<CertificateConfig>();
  330. //var certificate = configuration.GetSection("SuperSocketServerCertificate").Get<CertificateConfig>();
  331. //ICertificateConfig Certificate = certificate;
  332. //IEnumerable<IListenerConfig> listeners = llistener;
  333. //設定server config
  334. var serverConfig = new ServerConfig
  335. {
  336. SendingQueueSize = 10,
  337. //Port = Convert.ToInt32(2012),
  338. //Ip = "172.17.40.13",
  339. MaxRequestLength = 204800,
  340. //Security = serverSecurity,
  341. //Certificate = Certificate,
  342. //Listeners = listeners,
  343. // LogAllSocketException = true,
  344. KeepAliveTime = 10,
  345. // LogBasicSessionActivity = true
  346. //Security = "None"
  347. };
  348. //Setup with listening port
  349. //if (!appServer.Setup(serverConfig, logFactory: new NLogLoggerFactory()))
  350. //{
  351. // //Console.WriteLine("Failed to setup!");
  352. // logger.LogCritical("Failed to setup!");
  353. // return;
  354. //}
  355. websocketService.ValidateHandshake = WebsocketServiceValidateHandshake;
  356. websocketService.NewSessionConnected += AppServer_NewSessionConnected;
  357. websocketService.SessionClosed += AppServer_SessionClosed;
  358. //Try to start the appServer
  359. if (!appServer.Start())
  360. {
  361. logger.LogCritical("Failed to start!");
  362. //Console.ReadKey();
  363. return;
  364. }
  365. }
  366. private async Task<bool> WebsocketServiceValidateHandshake(WsClientData session)
  367. {
  368. session.ISOCPP20 = session.SecWebSocketProtocol.ToLower().Contains("ocpp2.0");
  369. int securityProfile = 0;
  370. string authorizationKey = string.Empty;
  371. if (string.IsNullOrEmpty(session.Path))
  372. {
  373. //logger.Log();
  374. logger.LogWarning("===========================================");
  375. logger.LogWarning("session.Path EMPTY");
  376. logger.LogWarning("===========================================");
  377. }
  378. string[] words = session.Path.ToString().Split('/');
  379. session.ChargeBoxId = words.Last();
  380. foreach (var denyModel in GlobalConfig.DenyModelNames)
  381. {
  382. if (string.IsNullOrEmpty(denyModel))
  383. {
  384. continue;
  385. }
  386. if (session.ChargeBoxId.StartsWith(denyModel))
  387. {
  388. StringBuilder responseBuilder = new StringBuilder();
  389. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  390. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  391. responseBuilder.AppendWithCrCf();
  392. string sb = responseBuilder.ToString();
  393. byte[] data = Encoding.UTF8.GetBytes(sb);
  394. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  395. logger.LogTrace(sb);
  396. return false;
  397. }
  398. }
  399. if (configuration["MaintainMode"] == "1")
  400. {
  401. session.ChargeBoxId = session.ChargeBoxId + "_2";
  402. }
  403. logger.LogInformation(string.Format("ValidateHandshake: {0}", session.Path));
  404. bool isExistedSN = false;
  405. bool authorizated = false;
  406. var info = mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId).Result;
  407. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  408. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  409. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  410. //session.MachineId = machine == null ? String.Empty : machine.Id;
  411. //isExistedSN = machine == null ? false : true;
  412. session.CustomerName = info.CustomerName;
  413. session.CustomerId = info.CustomerId;
  414. session.MachineId = info.MachineId;
  415. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  416. if (!isExistedSN)
  417. {
  418. StringBuilder responseBuilder = new StringBuilder();
  419. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  420. (int)HttpStatusCode.NotFound, @"Not Found");
  421. responseBuilder.AppendWithCrCf();
  422. string sb = responseBuilder.ToString();
  423. byte[] data = Encoding.UTF8.GetBytes(sb);
  424. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  425. logger.LogInformation(sb);
  426. return false;
  427. }
  428. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  429. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  430. var configVaule = mainDbService.GetMachineSecurityProfile(session.ChargeBoxId).Result;
  431. int.TryParse(configVaule, out securityProfile);
  432. if (session.ISOCPP20)
  433. {
  434. // 1.6 server only support change server function
  435. securityProfile = 0;
  436. }
  437. if (securityProfile == 3 && session.UriScheme == "ws")
  438. {
  439. StringBuilder responseBuilder = new StringBuilder();
  440. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  441. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  442. responseBuilder.AppendWithCrCf();
  443. string sb = responseBuilder.ToString();
  444. byte[] data = Encoding.UTF8.GetBytes(sb);
  445. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  446. logger.LogInformation(sb);
  447. return false;
  448. }
  449. if (securityProfile == 1 || securityProfile == 2)
  450. {
  451. if (securityProfile == 2 && session.UriScheme == "ws")
  452. {
  453. authorizated = false;
  454. }
  455. //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  456. if (!string.IsNullOrEmpty(session.AuthHeader))
  457. {
  458. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  459. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  460. authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId);
  461. if (session.ISOCPP20)
  462. {
  463. // 1.6 server only support change server function
  464. securityProfile = 0;
  465. }
  466. logger.LogInformation("***********Authorization ");
  467. if (!string.IsNullOrEmpty(authorizationKey))
  468. {
  469. //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  470. string base64Encoded = session.AuthHeader.Replace("Basic ", "");
  471. byte[] data = Convert.FromBase64String(base64Encoded);
  472. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  473. logger.LogInformation("***********Authorization " + Encoding.ASCII.GetString(data));
  474. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  475. {
  476. authorizated = true;
  477. }
  478. }
  479. }
  480. else
  481. {
  482. authorizated = true;
  483. }
  484. if (!authorizated)
  485. {
  486. StringBuilder responseBuilder = new StringBuilder();
  487. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  488. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  489. responseBuilder.AppendWithCrCf();
  490. string sb = responseBuilder.ToString();
  491. byte[] data = Encoding.UTF8.GetBytes(sb);
  492. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  493. logger.LogInformation(sb);
  494. return false;
  495. }
  496. }
  497. logger.LogInformation(string.Format("ValidateHandshake PASS: {0}", session.Path));
  498. return true;
  499. }
  500. private async void AppServer_NewSessionConnected(object sender, WsClientData session)
  501. {
  502. logger.LogDebug(string.Format("{0} NewSessionConnected", session.Path));
  503. try
  504. {
  505. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  506. if (isNotSupported)
  507. {
  508. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  509. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  510. return;
  511. }
  512. TryRemoveDuplicatedSession(session);
  513. clientDic[session.ChargeBoxId] = session;
  514. session.m_ReceiveData += ReceivedMessageTimeLimited;
  515. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  516. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  517. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.Origin.Contains("https") ? 2 : 1);
  518. }
  519. catch (Exception ex)
  520. {
  521. logger.LogError(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  522. }
  523. }
  524. private void AppServer_SessionClosed(object sender, WsClientData session)
  525. {
  526. CloseReason value = CloseReason.ServerShutdown;
  527. WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
  528. RemoveClient(session);
  529. }
  530. private void TryRemoveDuplicatedSession(WsClientData session)
  531. {
  532. if (clientDic.ContainsKey(session.ChargeBoxId))
  533. {
  534. var oldSession = clientDic[session.ChargeBoxId];
  535. WriteMachineLog(oldSession, "Duplicate Logins", "Connection", "");
  536. oldSession.Close(CloseReason.ServerShutdown);
  537. RemoveClient(oldSession);
  538. }
  539. }
  540. async private void ReceivedMessageTimeLimited(WsClientData 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(WsClientData 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, WsClientData 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. return;
  768. }
  769. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  770. switch (profileName)
  771. {
  772. case "Core":
  773. {
  774. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  775. var sendTimer = Stopwatch.StartNew();
  776. if (replyResult.Success)
  777. {
  778. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  779. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception is null ? string.Empty : replyResult.Exception.ToString());
  780. if (action == Actions.BootNotification
  781. && replyResult.Message is BootNotificationConfirmation bootNotificationConfirmation)
  782. {
  783. if (bootNotificationConfirmation.status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  784. {
  785. session.IsCheckIn = true;
  786. await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId);
  787. await messageService.SendChangeConfigurationRequest(
  788. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  789. }
  790. else
  791. {
  792. bool? isAC = await mainDbService.GetChargeBoxIdIsAc(session.ChargeBoxId);
  793. if (isAC is not null)
  794. {
  795. session.IsAC = isAC.Value;
  796. }
  797. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.Origin.Contains("https") ? 2 : 1);
  798. await webDbService.SetDefaultFee(session);
  799. }
  800. }
  801. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  802. {
  803. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  804. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  805. {
  806. await messageService.SendDataTransferRequest(
  807. session.ChargeBoxId,
  808. messageId: "SetUserPrice",
  809. vendorId:"Phihong Technology",
  810. data: JsonConvert.SerializeObject(
  811. new
  812. {
  813. idToken = authorizeRequest.idTag,
  814. price = session.UserDisplayPrices[authorizeRequest.idTag]
  815. })
  816. );
  817. }
  818. }
  819. }
  820. else
  821. {
  822. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  823. {
  824. //do nothing
  825. }
  826. else
  827. {
  828. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  829. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  830. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  831. }
  832. }
  833. sendTimer.Stop();
  834. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  835. {
  836. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  837. }
  838. if (action == Actions.StartTransaction)
  839. {
  840. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  841. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  842. if (_powerDic != null)
  843. {
  844. foreach (var kv in _powerDic)
  845. {
  846. try
  847. {
  848. if (kv.Value.HasValue)
  849. {
  850. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  851. }
  852. }
  853. catch (Exception ex)
  854. {
  855. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  856. }
  857. }
  858. }
  859. }
  860. if (action == Actions.StopTransaction)
  861. {
  862. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  863. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  864. if (_powerDic != null)
  865. {
  866. foreach (var kv in _powerDic)
  867. {
  868. try
  869. {
  870. if (kv.Value.HasValue)
  871. {
  872. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  873. }
  874. }
  875. catch (Exception ex)
  876. {
  877. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  878. }
  879. }
  880. }
  881. }
  882. }
  883. break;
  884. case "FirmwareManagement":
  885. {
  886. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  887. if (replyResult.Success)
  888. {
  889. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  890. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  891. }
  892. else
  893. {
  894. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  895. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  896. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  897. }
  898. }
  899. break;
  900. case "Security":
  901. {
  902. var replyResult = profileHandler.ExecuteSecurityRequest(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. default:
  917. {
  918. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  919. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  920. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  921. }
  922. break;
  923. }
  924. outter_stopwatch.Stop();
  925. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  926. {
  927. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  928. }
  929. }
  930. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  931. {
  932. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  933. if (await ReConfirmMessage(analysisResult))
  934. {
  935. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  936. MessageResult confirmResult = null;
  937. switch (profileName)
  938. {
  939. case "Core":
  940. {
  941. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  942. }
  943. break;
  944. case "FirmwareManagement":
  945. {
  946. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  947. }
  948. break;
  949. case "RemoteTrigger":
  950. {
  951. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  952. }
  953. break;
  954. case "Reservation":
  955. {
  956. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  957. }
  958. break;
  959. case "LocalAuthListManagement":
  960. {
  961. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  962. }
  963. break;
  964. case "SmartCharging":
  965. {
  966. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  967. }
  968. break;
  969. case "Security":
  970. {
  971. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  972. }
  973. break;
  974. default:
  975. {
  976. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  977. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  978. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  979. }
  980. break;
  981. }
  982. if (confirmResult == null || !confirmResult.Success)
  983. {
  984. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  985. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  986. }
  987. }
  988. else
  989. {
  990. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  991. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  992. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  993. }
  994. }
  995. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  996. {
  997. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  998. if (await ReConfirmMessage(analysisResult))
  999. {
  1000. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1001. switch (profileName)
  1002. {
  1003. case "Core":
  1004. {
  1005. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1006. }
  1007. break;
  1008. case "FirmwareManagement":
  1009. {
  1010. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1011. }
  1012. break;
  1013. case "RemoteTrigger":
  1014. {
  1015. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1016. }
  1017. break;
  1018. case "Reservation":
  1019. {
  1020. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1021. }
  1022. break;
  1023. case "LocalAuthListManagement":
  1024. {
  1025. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1026. }
  1027. break;
  1028. case "SmartCharging":
  1029. {
  1030. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1031. }
  1032. break;
  1033. default:
  1034. {
  1035. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1036. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1037. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1038. }
  1039. break;
  1040. }
  1041. }
  1042. else
  1043. {
  1044. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1045. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1046. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1047. }
  1048. }
  1049. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  1050. {
  1051. try
  1052. {
  1053. if (session != null)
  1054. {
  1055. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1056. session.Send(msg);
  1057. }
  1058. }
  1059. catch (Exception ex)
  1060. {
  1061. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  1062. }
  1063. }
  1064. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1065. {
  1066. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1067. _needConfirmMsg.Id = table_id;
  1068. _needConfirmMsg.SentAction = action;
  1069. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1070. _needConfirmMsg.SentTimes = 4;
  1071. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1072. _needConfirmMsg.RequestId = requestId;
  1073. _needConfirmMsg.SentUniqueId = msg_id;
  1074. _needConfirmMsg.CreatedBy = createdBy;
  1075. _needConfirmMsg.SentMessage = sendMessage;
  1076. if (needConfirmActions.Contains(action))
  1077. {
  1078. lock (_lockConfirmPacketList)
  1079. {
  1080. needConfirmPacketList.Add(_needConfirmMsg);
  1081. }
  1082. }
  1083. }
  1084. internal void RemoveConfirmMessage()
  1085. {
  1086. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1087. lock (_lockConfirmPacketList)
  1088. {
  1089. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1090. foreach (var item in removeList)
  1091. {
  1092. needConfirmPacketList.Remove(item);
  1093. }
  1094. }
  1095. }
  1096. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1097. {
  1098. bool confirmed = false;
  1099. if (needConfirmActions.Contains(analysisResult.Action))
  1100. {
  1101. NeedConfirmMessage foundRequest = null;
  1102. lock (_lockConfirmPacketList)
  1103. {
  1104. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1105. }
  1106. if (foundRequest != null && foundRequest.Id > 0)
  1107. {
  1108. foundRequest.SentTimes = 0;
  1109. foundRequest.SentInterval = 0;
  1110. analysisResult.RequestId = foundRequest.RequestId;
  1111. await mainDbService.UpdateServerMessage(foundRequest.Id, inMessage: JsonConvert.SerializeObject(analysisResult.Message, Formatting.None), receivedOn: DateTime.UtcNow);
  1112. confirmed = true;
  1113. }
  1114. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1115. {
  1116. confirmed = true;
  1117. }
  1118. else
  1119. {
  1120. logger.LogError(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1121. }
  1122. }
  1123. return confirmed;
  1124. }
  1125. internal void RemoveClient(WsClientData session)
  1126. {
  1127. if (session == null)
  1128. {
  1129. return;
  1130. }
  1131. if (!string.IsNullOrEmpty(session.MachineId))
  1132. logger.LogTrace("RemoveClient[" + session.ChargeBoxId + "]");
  1133. if (session.State == WebSocketState.Open)
  1134. {
  1135. session.Close(CloseReason.ServerShutdown);
  1136. }
  1137. RemoveClientDic(session);
  1138. try
  1139. {
  1140. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  1141. // session.Close(CloseReason.ServerShutdown);
  1142. }
  1143. catch (Exception ex)
  1144. {
  1145. //logger.LogWarning("Close client socket error!!");
  1146. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1147. }
  1148. if (session != null)
  1149. {
  1150. session = null;
  1151. }
  1152. }
  1153. private void RemoveClientDic(WsClientData session)
  1154. {
  1155. if (string.IsNullOrEmpty(session.ChargeBoxId))
  1156. {
  1157. return;
  1158. }
  1159. if (clientDic.ContainsKey(session.ChargeBoxId))
  1160. {
  1161. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1162. {
  1163. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1164. clientDic.Remove(session.ChargeBoxId, out _);
  1165. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1166. }
  1167. }
  1168. }
  1169. private void WarmUpLog()
  1170. {
  1171. connectionLogdbService.WarmUpLog();
  1172. }
  1173. private void WriteMachineLog(WsClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1174. {
  1175. try
  1176. {
  1177. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1178. if (clientData.ChargeBoxId == null)
  1179. {
  1180. logger.LogCritical(clientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1181. }
  1182. connectionLogdbService.WriteMachineLog(clientData, data, messageType, errorMsg, isSent);
  1183. }
  1184. catch (Exception ex)
  1185. {
  1186. //Console.WriteLine(ex.ToString());
  1187. logger.LogError(ex,ex.Message);
  1188. }
  1189. }
  1190. }
  1191. }