ProtalServer.cs 68 KB

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