ProtalServer.cs 70 KB

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