ProtalServer.cs 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  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. 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 void Stop()
  307. {
  308. //appServer?.Stop();
  309. StopWsService();
  310. }
  311. private void StartWsService()
  312. {
  313. //載入OCPP Protocol
  314. //appServer = ocppWSServerFactory.Create(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0") });
  315. //var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0") });
  316. //List<IListenerConfig> llistener = new List<IListenerConfig>();
  317. //if (GlobalConfig.GetWS_Port() != 0)
  318. //{
  319. // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = GlobalConfig.GetWS_Port(), Backlog = 100, Security = "None" });
  320. //}
  321. //foreach (var securityport in GlobalConfig.GetWSS_Ports())
  322. //{
  323. // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = securityport, Backlog = 100, Security = SslProtocols.Tls12.ToString() });
  324. //}
  325. //var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;\
  326. //var certificate = configuration.GetSection("superSocket").GetSection("Servers:0").GetSection("Certificate").Get<CertificateConfig>();
  327. //var certificate = configuration.GetSection("SuperSocketServerCertificate").Get<CertificateConfig>();
  328. //ICertificateConfig Certificate = certificate;
  329. //IEnumerable<IListenerConfig> listeners = llistener;
  330. //設定server config
  331. var serverConfig = new ServerConfig
  332. {
  333. SendingQueueSize = 10,
  334. //Port = Convert.ToInt32(2012),
  335. //Ip = "172.17.40.13",
  336. MaxRequestLength = 204800,
  337. //Security = serverSecurity,
  338. //Certificate = Certificate,
  339. //Listeners = listeners,
  340. // LogAllSocketException = true,
  341. KeepAliveTime = 10,
  342. // LogBasicSessionActivity = true
  343. //Security = "None"
  344. };
  345. //Setup with listening port
  346. //if (!appServer.Setup(serverConfig, logFactory: new NLogLoggerFactory()))
  347. //{
  348. // //Console.WriteLine("Failed to setup!");
  349. // logger.LogCritical("Failed to setup!");
  350. // return;
  351. //}
  352. websocketService.ValidateHandshake = WebsocketServiceValidateHandshake;
  353. websocketService.NewSessionConnected += AppServer_NewSessionConnected;
  354. //Try to start the appServer
  355. //if (!appServer.Start())
  356. //{
  357. // logger.LogCritical("Failed to start!");
  358. // //Console.ReadKey();
  359. // return;
  360. //}
  361. }
  362. private void StopWsService()
  363. {
  364. websocketService.ValidateHandshake = null;
  365. websocketService.NewSessionConnected -= AppServer_NewSessionConnected;
  366. }
  367. private async Task<bool> WebsocketServiceValidateHandshake(WsClientData session)
  368. {
  369. session.ISOCPP20 = session.SecWebSocketProtocol.ToLower().Contains("ocpp2.0");
  370. int securityProfile = 0;
  371. string authorizationKey = string.Empty;
  372. if (string.IsNullOrEmpty(session.Path))
  373. {
  374. //logger.Log();
  375. logger.LogWarning("===========================================");
  376. logger.LogWarning("session.Path EMPTY");
  377. logger.LogWarning("===========================================");
  378. }
  379. string[] words = session.Path.ToString().Split('/');
  380. session.ChargeBoxId = words.Last();
  381. foreach (var denyModel in GlobalConfig.DenyModelNames)
  382. {
  383. if (string.IsNullOrEmpty(denyModel))
  384. {
  385. continue;
  386. }
  387. if (session.ChargeBoxId.StartsWith(denyModel))
  388. {
  389. StringBuilder responseBuilder = new StringBuilder();
  390. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  391. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  392. responseBuilder.AppendWithCrCf();
  393. string sb = responseBuilder.ToString();
  394. byte[] data = Encoding.UTF8.GetBytes(sb);
  395. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  396. logger.LogTrace(sb);
  397. return false;
  398. }
  399. }
  400. if (configuration["MaintainMode"] == "1")
  401. {
  402. session.ChargeBoxId = session.ChargeBoxId + "_2";
  403. }
  404. logger.LogInformation(string.Format("ValidateHandshake: {0}", session.Path));
  405. bool isExistedSN = false;
  406. bool authorizated = false;
  407. var info = mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId).Result;
  408. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  409. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  410. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  411. //session.MachineId = machine == null ? String.Empty : machine.Id;
  412. //isExistedSN = machine == null ? false : true;
  413. session.CustomerName = info.CustomerName;
  414. session.CustomerId = info.CustomerId;
  415. session.MachineId = info.MachineId;
  416. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  417. if (!isExistedSN)
  418. {
  419. StringBuilder responseBuilder = new StringBuilder();
  420. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  421. (int)HttpStatusCode.NotFound, @"Not Found");
  422. responseBuilder.AppendWithCrCf();
  423. string sb = responseBuilder.ToString();
  424. byte[] data = Encoding.UTF8.GetBytes(sb);
  425. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  426. logger.LogInformation(sb);
  427. return false;
  428. }
  429. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  430. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  431. var configVaule = mainDbService.GetMachineSecurityProfile(session.ChargeBoxId).Result;
  432. int.TryParse(configVaule, out securityProfile);
  433. if (session.ISOCPP20)
  434. {
  435. // 1.6 server only support change server function
  436. securityProfile = 0;
  437. }
  438. if (securityProfile == 3 && session.UriScheme == "ws")
  439. {
  440. StringBuilder responseBuilder = new StringBuilder();
  441. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  442. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  443. responseBuilder.AppendWithCrCf();
  444. string sb = responseBuilder.ToString();
  445. byte[] data = Encoding.UTF8.GetBytes(sb);
  446. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  447. logger.LogInformation(sb);
  448. return false;
  449. }
  450. if (securityProfile == 1 || securityProfile == 2)
  451. {
  452. if (securityProfile == 2 && session.UriScheme == "ws")
  453. {
  454. authorizated = false;
  455. }
  456. //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  457. if (!string.IsNullOrEmpty(session.AuthHeader))
  458. {
  459. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  460. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  461. authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId);
  462. if (session.ISOCPP20)
  463. {
  464. // 1.6 server only support change server function
  465. securityProfile = 0;
  466. }
  467. logger.LogInformation("***********Authorization ");
  468. if (!string.IsNullOrEmpty(authorizationKey))
  469. {
  470. //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  471. string base64Encoded = session.AuthHeader.Replace("Basic ", "");
  472. byte[] data = Convert.FromBase64String(base64Encoded);
  473. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  474. logger.LogInformation("***********Authorization " + Encoding.ASCII.GetString(data));
  475. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  476. {
  477. authorizated = true;
  478. }
  479. }
  480. }
  481. else
  482. {
  483. authorizated = true;
  484. }
  485. if (!authorizated)
  486. {
  487. StringBuilder responseBuilder = new StringBuilder();
  488. responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
  489. (int)HttpStatusCode.Unauthorized, @"Unauthorized");
  490. responseBuilder.AppendWithCrCf();
  491. string sb = responseBuilder.ToString();
  492. byte[] data = Encoding.UTF8.GetBytes(sb);
  493. ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
  494. logger.LogInformation(sb);
  495. return false;
  496. }
  497. }
  498. logger.LogInformation(string.Format("ValidateHandshake PASS: {0}", session.Path));
  499. return true;
  500. }
  501. private async void AppServer_NewSessionConnected(object sender, WsClientData session)
  502. {
  503. logger.LogDebug(string.Format("{0} NewSessionConnected", session.Path));
  504. try
  505. {
  506. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  507. if (isNotSupported)
  508. {
  509. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  510. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  511. return;
  512. }
  513. TryRemoveDuplicatedSession(session);
  514. clientDic[session.ChargeBoxId] = session;
  515. session.SessionClosed += AppServer_SessionClosed;
  516. session.m_ReceiveData += ReceivedMessageTimeLimited;
  517. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  518. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  519. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.Origin.Contains("https") ? 2 : 1);
  520. }
  521. catch (Exception ex)
  522. {
  523. logger.LogError(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  524. }
  525. }
  526. private void AppServer_SessionClosed(object sender, EventArgs e)
  527. {
  528. if (sender is not WsClientData session)
  529. {
  530. return;
  531. }
  532. session.SessionClosed -= AppServer_SessionClosed;
  533. CloseReason value = CloseReason.ServerShutdown;
  534. WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
  535. RemoveClient(session);
  536. }
  537. private void TryRemoveDuplicatedSession(WsClientData session)
  538. {
  539. if (clientDic.ContainsKey(session.ChargeBoxId))
  540. {
  541. var oldSession = clientDic[session.ChargeBoxId];
  542. WriteMachineLog(oldSession, "Duplicate Logins", "Connection", "");
  543. oldSession.Close(CloseReason.ServerShutdown);
  544. RemoveClient(oldSession);
  545. }
  546. }
  547. async private void ReceivedMessageTimeLimited(WsClientData session, string rawdata)
  548. {
  549. CancellationTokenSource tokenSource = new();
  550. var task = ReceivedMessage(session, rawdata);
  551. var completedTask = await Task.WhenAny(task, Task.Delay(90_000, tokenSource.Token));
  552. if (completedTask != task)
  553. {
  554. logger.LogCritical("Process timeout: {0} ", rawdata);
  555. await task;
  556. return;
  557. }
  558. tokenSource.Cancel();
  559. return;
  560. }
  561. async private Task ReceivedMessage(WsClientData session, string rawdata)
  562. {
  563. try
  564. {
  565. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  566. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  567. WriteMachineLog(session, rawdata,
  568. 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);
  569. if (session.ResetSecurityProfile)
  570. {
  571. logger.LogError(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  572. RemoveClient(session);
  573. return;
  574. }
  575. if (!analysisResult.Success)
  576. {
  577. //解析RawData就發生錯誤
  578. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  579. {
  580. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  581. }
  582. else
  583. {
  584. if (analysisResult.Message == null)
  585. {
  586. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  587. string errorMsg = string.Empty;
  588. if (analysisResult.Exception != null)
  589. {
  590. errorMsg = analysisResult.Exception.ToString();
  591. }
  592. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  593. }
  594. else
  595. {
  596. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  597. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  598. string errorMsg = string.Empty;
  599. if (analysisResult.Exception != null)
  600. {
  601. errorMsg = analysisResult.Exception.ToString();
  602. }
  603. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  604. }
  605. }
  606. }
  607. else
  608. {
  609. switch (analysisResult.Id)
  610. {
  611. case BasicMessageHandler.TYPENUMBER_CALL:
  612. {
  613. if (!session.ISOCPP20)
  614. {
  615. Actions action = Convertor.GetAction(analysisResult.Action);
  616. try
  617. {
  618. await ProcessRequestMessage(analysisResult, session, action);
  619. }
  620. catch (Exception e)
  621. {
  622. logger.LogError($"Processing {action} exception!");
  623. throw;
  624. }
  625. }
  626. else
  627. {
  628. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  629. MessageResult result = new MessageResult() { Success = true };
  630. //ocpp20 處理
  631. switch (action)
  632. {
  633. case EVCB_OCPP20.Packet.Features.Actions.BootNotification:
  634. {
  635. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  636. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  637. result.Message = confirm;
  638. result.Success = true;
  639. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  640. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  641. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  642. {
  643. ConfigurationSlot = 1,
  644. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  645. {
  646. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  647. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  648. MessageTimeout = 30,
  649. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  650. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  651. }
  652. };
  653. var uuid = session.queue20.store(request);
  654. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  655. Send(session, requestText, "SetNetworkProfile");
  656. }
  657. break;
  658. default:
  659. {
  660. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  661. }
  662. break;
  663. }
  664. }
  665. }
  666. break;
  667. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  668. {
  669. if (!session.ISOCPP20)
  670. {
  671. Actions action = Convertor.GetAction(analysisResult.Action);
  672. ProcessConfirmationMessage(analysisResult, session, action);
  673. }
  674. else
  675. {
  676. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  677. MessageResult result = new MessageResult() { Success = true };
  678. //ocpp20 處理
  679. switch (action)
  680. {
  681. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  682. {
  683. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  684. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  685. {
  686. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  687. {
  688. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  689. {
  690. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  691. {
  692. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  693. {
  694. Name="OCPPCommCtrlr",
  695. },
  696. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  697. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  698. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  699. {
  700. Name="NetworkConfigurationPriority",
  701. }
  702. }
  703. }
  704. };
  705. var uuid = session.queue20.store(request);
  706. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  707. Send(session, requestText, "SetVariables");
  708. }
  709. }
  710. break;
  711. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  712. {
  713. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  714. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  715. {
  716. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  717. {
  718. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  719. };
  720. var uuid = session.queue20.store(request);
  721. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  722. Send(session, requestText, "Reset");
  723. }
  724. }
  725. break;
  726. default:
  727. {
  728. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  729. }
  730. break;
  731. }
  732. }
  733. }
  734. break;
  735. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  736. {
  737. //只處理 丟出Request 收到Error的訊息
  738. if (analysisResult.Success && analysisResult.Message != null)
  739. {
  740. Actions action = Convertor.GetAction(analysisResult.Action);
  741. ProcessErrorMessage(analysisResult, session, action);
  742. }
  743. }
  744. break;
  745. default:
  746. {
  747. logger.LogError(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  748. }
  749. break;
  750. }
  751. }
  752. await Task.Delay(10);
  753. }
  754. catch (Exception ex)
  755. {
  756. if (ex.InnerException != null)
  757. {
  758. logger.LogError(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  759. }
  760. else
  761. {
  762. logger.LogError(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  763. }
  764. }
  765. }
  766. private async Task ProcessRequestMessage(MessageResult analysisResult, WsClientData session, Actions action)
  767. {
  768. Stopwatch outter_stopwatch = Stopwatch.StartNew();
  769. //BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  770. if (!session.IsCheckIn && action != Actions.BootNotification)
  771. {
  772. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  773. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  774. return;
  775. }
  776. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  777. switch (profileName)
  778. {
  779. case "Core":
  780. {
  781. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  782. var sendTimer = Stopwatch.StartNew();
  783. if (replyResult.Success)
  784. {
  785. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  786. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception is null ? string.Empty : replyResult.Exception.ToString());
  787. if (action == Actions.BootNotification
  788. && replyResult.Message is BootNotificationConfirmation bootNotificationConfirmation)
  789. {
  790. if (bootNotificationConfirmation.status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  791. {
  792. session.IsCheckIn = true;
  793. await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId);
  794. await messageService.SendChangeConfigurationRequest(
  795. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  796. }
  797. else
  798. {
  799. bool? isAC = await mainDbService.GetChargeBoxIdIsAc(session.ChargeBoxId);
  800. if (isAC is not null)
  801. {
  802. session.IsAC = isAC.Value;
  803. }
  804. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.Origin.Contains("https") ? 2 : 1);
  805. await webDbService.SetDefaultFee(session);
  806. }
  807. }
  808. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  809. {
  810. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  811. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  812. {
  813. await messageService.SendDataTransferRequest(
  814. session.ChargeBoxId,
  815. messageId: "SetUserPrice",
  816. vendorId:"Phihong Technology",
  817. data: JsonConvert.SerializeObject(
  818. new
  819. {
  820. idToken = authorizeRequest.idTag,
  821. price = session.UserDisplayPrices[authorizeRequest.idTag]
  822. })
  823. );
  824. }
  825. }
  826. }
  827. else
  828. {
  829. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  830. {
  831. //do nothing
  832. }
  833. else
  834. {
  835. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  836. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  837. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  838. }
  839. }
  840. sendTimer.Stop();
  841. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  842. {
  843. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  844. }
  845. if (action == Actions.StartTransaction)
  846. {
  847. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  848. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  849. if (_powerDic != null)
  850. {
  851. foreach (var kv in _powerDic)
  852. {
  853. try
  854. {
  855. if (kv.Value.HasValue)
  856. {
  857. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  858. }
  859. }
  860. catch (Exception ex)
  861. {
  862. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  863. }
  864. }
  865. }
  866. }
  867. if (action == Actions.StopTransaction)
  868. {
  869. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  870. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  871. if (_powerDic != null)
  872. {
  873. foreach (var kv in _powerDic)
  874. {
  875. try
  876. {
  877. if (kv.Value.HasValue)
  878. {
  879. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  880. }
  881. }
  882. catch (Exception ex)
  883. {
  884. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  885. }
  886. }
  887. }
  888. }
  889. }
  890. break;
  891. case "FirmwareManagement":
  892. {
  893. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  894. if (replyResult.Success)
  895. {
  896. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  897. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  898. }
  899. else
  900. {
  901. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  902. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  903. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  904. }
  905. }
  906. break;
  907. case "Security":
  908. {
  909. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  910. if (replyResult.Success)
  911. {
  912. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  913. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  914. }
  915. else
  916. {
  917. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  918. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  919. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  920. }
  921. }
  922. break;
  923. default:
  924. {
  925. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  926. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  927. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  928. }
  929. break;
  930. }
  931. outter_stopwatch.Stop();
  932. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  933. {
  934. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  935. }
  936. }
  937. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  938. {
  939. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  940. if (await ReConfirmMessage(analysisResult))
  941. {
  942. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  943. MessageResult confirmResult = null;
  944. switch (profileName)
  945. {
  946. case "Core":
  947. {
  948. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  949. }
  950. break;
  951. case "FirmwareManagement":
  952. {
  953. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  954. }
  955. break;
  956. case "RemoteTrigger":
  957. {
  958. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  959. }
  960. break;
  961. case "Reservation":
  962. {
  963. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  964. }
  965. break;
  966. case "LocalAuthListManagement":
  967. {
  968. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  969. }
  970. break;
  971. case "SmartCharging":
  972. {
  973. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  974. }
  975. break;
  976. case "Security":
  977. {
  978. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  979. }
  980. break;
  981. default:
  982. {
  983. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  984. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  985. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  986. }
  987. break;
  988. }
  989. if (confirmResult == null || !confirmResult.Success)
  990. {
  991. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  992. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  993. }
  994. }
  995. else
  996. {
  997. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  998. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  999. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1000. }
  1001. }
  1002. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  1003. {
  1004. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1005. if (await ReConfirmMessage(analysisResult))
  1006. {
  1007. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1008. switch (profileName)
  1009. {
  1010. case "Core":
  1011. {
  1012. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1013. }
  1014. break;
  1015. case "FirmwareManagement":
  1016. {
  1017. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1018. }
  1019. break;
  1020. case "RemoteTrigger":
  1021. {
  1022. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1023. }
  1024. break;
  1025. case "Reservation":
  1026. {
  1027. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1028. }
  1029. break;
  1030. case "LocalAuthListManagement":
  1031. {
  1032. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1033. }
  1034. break;
  1035. case "SmartCharging":
  1036. {
  1037. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1038. }
  1039. break;
  1040. default:
  1041. {
  1042. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1043. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1044. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1045. }
  1046. break;
  1047. }
  1048. }
  1049. else
  1050. {
  1051. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1052. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1053. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1054. }
  1055. }
  1056. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  1057. {
  1058. try
  1059. {
  1060. if (session != null)
  1061. {
  1062. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1063. session.Send(msg);
  1064. }
  1065. }
  1066. catch (Exception ex)
  1067. {
  1068. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  1069. }
  1070. }
  1071. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1072. {
  1073. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1074. _needConfirmMsg.Id = table_id;
  1075. _needConfirmMsg.SentAction = action;
  1076. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1077. _needConfirmMsg.SentTimes = 4;
  1078. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1079. _needConfirmMsg.RequestId = requestId;
  1080. _needConfirmMsg.SentUniqueId = msg_id;
  1081. _needConfirmMsg.CreatedBy = createdBy;
  1082. _needConfirmMsg.SentMessage = sendMessage;
  1083. if (needConfirmActions.Contains(action))
  1084. {
  1085. lock (_lockConfirmPacketList)
  1086. {
  1087. needConfirmPacketList.Add(_needConfirmMsg);
  1088. }
  1089. }
  1090. }
  1091. internal void RemoveConfirmMessage()
  1092. {
  1093. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1094. lock (_lockConfirmPacketList)
  1095. {
  1096. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1097. foreach (var item in removeList)
  1098. {
  1099. needConfirmPacketList.Remove(item);
  1100. }
  1101. }
  1102. }
  1103. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1104. {
  1105. bool confirmed = false;
  1106. if (needConfirmActions.Contains(analysisResult.Action))
  1107. {
  1108. NeedConfirmMessage foundRequest = null;
  1109. lock (_lockConfirmPacketList)
  1110. {
  1111. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1112. }
  1113. if (foundRequest != null && foundRequest.Id > 0)
  1114. {
  1115. foundRequest.SentTimes = 0;
  1116. foundRequest.SentInterval = 0;
  1117. analysisResult.RequestId = foundRequest.RequestId;
  1118. await mainDbService.UpdateServerMessage(foundRequest.Id, inMessage: JsonConvert.SerializeObject(analysisResult.Message, Formatting.None), receivedOn: DateTime.UtcNow);
  1119. confirmed = true;
  1120. }
  1121. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1122. {
  1123. confirmed = true;
  1124. }
  1125. else
  1126. {
  1127. logger.LogError(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1128. }
  1129. }
  1130. return confirmed;
  1131. }
  1132. internal void RemoveClient(WsClientData session)
  1133. {
  1134. if (session == null)
  1135. {
  1136. return;
  1137. }
  1138. if (!string.IsNullOrEmpty(session.MachineId))
  1139. logger.LogTrace("RemoveClient[" + session.ChargeBoxId + "]");
  1140. if (session.State == WebSocketState.Open)
  1141. {
  1142. session.Close(CloseReason.ServerShutdown);
  1143. }
  1144. RemoveClientDic(session);
  1145. try
  1146. {
  1147. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  1148. // session.Close(CloseReason.ServerShutdown);
  1149. }
  1150. catch (Exception ex)
  1151. {
  1152. //logger.LogWarning("Close client socket error!!");
  1153. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1154. }
  1155. if (session != null)
  1156. {
  1157. session = null;
  1158. }
  1159. }
  1160. private void RemoveClientDic(WsClientData session)
  1161. {
  1162. if (string.IsNullOrEmpty(session.ChargeBoxId))
  1163. {
  1164. return;
  1165. }
  1166. if (clientDic.ContainsKey(session.ChargeBoxId))
  1167. {
  1168. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1169. {
  1170. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1171. clientDic.Remove(session.ChargeBoxId, out _);
  1172. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1173. }
  1174. }
  1175. }
  1176. private void WarmUpLog()
  1177. {
  1178. connectionLogdbService.WarmUpLog();
  1179. }
  1180. private void WriteMachineLog(WsClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1181. {
  1182. try
  1183. {
  1184. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1185. if (clientData.ChargeBoxId == null)
  1186. {
  1187. logger.LogCritical(clientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1188. }
  1189. connectionLogdbService.WriteMachineLog(clientData, data, messageType, errorMsg, isSent);
  1190. }
  1191. catch (Exception ex)
  1192. {
  1193. //Console.WriteLine(ex.ToString());
  1194. logger.LogError(ex,ex.Message);
  1195. }
  1196. }
  1197. }
  1198. }