ProtalServer.cs 67 KB

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