ProtalServer.cs 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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. if (GlobalConfig.GetWS_Port() != 0)
  436. {
  437. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = GlobalConfig.GetWS_Port(), Backlog = 100, Security = "None" });
  438. }
  439. foreach (var securityport in GlobalConfig.GetWSS_Ports())
  440. {
  441. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = securityport, Backlog = 100, Security = SslProtocols.Tls12.ToString() });
  442. }
  443. //var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;\
  444. //var certificate = configuration.GetSection("superSocket").GetSection("Servers:0").GetSection("Certificate").Get<CertificateConfig>();
  445. var certificate = configuration.GetSection("SuperSocketServerCertificate").Get<CertificateConfig>();
  446. ICertificateConfig Certificate = certificate;
  447. IEnumerable<IListenerConfig> listeners = llistener;
  448. //設定server config
  449. var serverConfig = new ServerConfig
  450. {
  451. SendingQueueSize = 10,
  452. //Port = Convert.ToInt32(2012),
  453. //Ip = "172.17.40.13",
  454. MaxRequestLength = 204800,
  455. //Security = serverSecurity,
  456. Certificate = Certificate,
  457. Listeners = listeners,
  458. // LogAllSocketException = true,
  459. KeepAliveTime = 10,
  460. // LogBasicSessionActivity = true
  461. };
  462. //Setup with listening port
  463. if (!appServer.Setup(serverConfig, logFactory: new NLogLoggerFactory()))
  464. {
  465. Console.WriteLine("Failed to setup!");
  466. return;
  467. }
  468. appServer.NewSessionConnected += AppServer_NewSessionConnected;
  469. appServer.SessionClosed += AppServer_SessionClosed;
  470. //Try to start the appServer
  471. if (!appServer.Start())
  472. {
  473. Console.WriteLine("Failed to start!");
  474. //Console.ReadKey();
  475. return;
  476. }
  477. }
  478. private void AppServer_SessionClosed(ClientData session, CloseReason value)
  479. {
  480. _ = WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
  481. RemoveClient(session);
  482. }
  483. private async void AppServer_NewSessionConnected(ClientData session)
  484. {
  485. logger.Debug(string.Format("{0} NewSessionConnected", session.Path));
  486. try
  487. {
  488. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  489. if (isNotSupported)
  490. {
  491. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  492. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  493. return;
  494. }
  495. //ClientData _removeClient = null;
  496. var addedClient = clientDic.GetOrAdd(session.ChargeBoxId, session);
  497. //clientDic.TryGetValue(session.ChargeBoxId, out _removeClient);
  498. if (addedClient != session)
  499. {
  500. WriteMachineLog(addedClient, "Duplicate Logins", "Connection", "");
  501. addedClient.Close(CloseReason.ServerShutdown);
  502. RemoveClient(addedClient);
  503. }
  504. //clientDic.add.Add(session.ChargeBoxId, session);
  505. session.m_ReceiveData += new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  506. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  507. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  508. using (var db = maindbContextFactory.CreateDbContext())
  509. {
  510. var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
  511. if (machine != null)
  512. {
  513. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  514. db.SaveChanges();
  515. }
  516. }
  517. }
  518. catch (Exception ex)
  519. {
  520. logger.Error(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  521. }
  522. }
  523. async private void ReceivedMessage(ClientData session, string rawdata)
  524. {
  525. try
  526. {
  527. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  528. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  529. WriteMachineLog(session, rawdata,
  530. 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);
  531. if (session.ResetSecurityProfile)
  532. {
  533. logger.Error(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  534. RemoveClient(session);
  535. return;
  536. }
  537. if (!analysisResult.Success)
  538. {
  539. //解析RawData就發生錯誤
  540. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  541. {
  542. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  543. }
  544. else
  545. {
  546. if (analysisResult.Message == null)
  547. {
  548. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, 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}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  555. }
  556. else
  557. {
  558. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  559. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  560. string errorMsg = string.Empty;
  561. if (analysisResult.Exception != null)
  562. {
  563. errorMsg = analysisResult.Exception.ToString();
  564. }
  565. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  566. }
  567. }
  568. }
  569. else
  570. {
  571. switch (analysisResult.Id)
  572. {
  573. case BasicMessageHandler.TYPENUMBER_CALL:
  574. {
  575. if (!session.ISOCPP20)
  576. {
  577. Actions action = Convertor.GetAction(analysisResult.Action);
  578. try
  579. {
  580. ProcessRequestMessage(analysisResult, session, action);
  581. }
  582. catch (Exception e)
  583. {
  584. logger.Error($"Processing {action} exception!");
  585. throw;
  586. }
  587. }
  588. else
  589. {
  590. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  591. MessageResult result = new MessageResult() { Success = true };
  592. //ocpp20 處理
  593. switch (action)
  594. {
  595. case EVCB_OCPP20.Packet.Features.Actions.BootNotification:
  596. {
  597. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  598. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  599. result.Message = confirm;
  600. result.Success = true;
  601. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  602. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  603. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  604. {
  605. ConfigurationSlot = 1,
  606. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  607. {
  608. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  609. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  610. MessageTimeout = 30,
  611. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  612. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  613. }
  614. };
  615. var uuid = session.queue20.store(request);
  616. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  617. Send(session, requestText, "SetNetworkProfile");
  618. }
  619. break;
  620. default:
  621. {
  622. logger.Error(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  623. }
  624. break;
  625. }
  626. }
  627. }
  628. break;
  629. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  630. {
  631. if (!session.ISOCPP20)
  632. {
  633. Actions action = Convertor.GetAction(analysisResult.Action);
  634. ProcessConfirmationMessage(analysisResult, session, action);
  635. }
  636. else
  637. {
  638. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  639. MessageResult result = new MessageResult() { Success = true };
  640. //ocpp20 處理
  641. switch (action)
  642. {
  643. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  644. {
  645. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  646. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  647. {
  648. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  649. {
  650. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  651. {
  652. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  653. {
  654. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  655. {
  656. Name="OCPPCommCtrlr",
  657. },
  658. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  659. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  660. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  661. {
  662. Name="NetworkConfigurationPriority",
  663. }
  664. }
  665. }
  666. };
  667. var uuid = session.queue20.store(request);
  668. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  669. Send(session, requestText, "SetVariables");
  670. }
  671. }
  672. break;
  673. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  674. {
  675. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  676. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  677. {
  678. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  679. {
  680. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  681. };
  682. var uuid = session.queue20.store(request);
  683. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  684. Send(session, requestText, "Reset");
  685. }
  686. }
  687. break;
  688. default:
  689. {
  690. logger.Error(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  691. }
  692. break;
  693. }
  694. }
  695. }
  696. break;
  697. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  698. {
  699. //只處理 丟出Request 收到Error的訊息
  700. if (analysisResult.Success && analysisResult.Message != null)
  701. {
  702. Actions action = Convertor.GetAction(analysisResult.Action);
  703. ProcessErrorMessage(analysisResult, session, action);
  704. }
  705. }
  706. break;
  707. default:
  708. {
  709. logger.Error(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  710. }
  711. break;
  712. }
  713. }
  714. await Task.Delay(10);
  715. }
  716. catch (Exception ex)
  717. {
  718. if (ex.InnerException != null)
  719. {
  720. logger.Error(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  721. }
  722. else
  723. {
  724. logger.Error(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  725. }
  726. }
  727. }
  728. async private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
  729. {
  730. Stopwatch outter_stopwatch = Stopwatch.StartNew();
  731. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  732. if (!session.IsCheckIn && action != Actions.BootNotification)
  733. {
  734. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  735. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  736. }
  737. else
  738. {
  739. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  740. switch (profileName)
  741. {
  742. case "Core":
  743. {
  744. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  745. var sendTimer = Stopwatch.StartNew();
  746. if (replyResult.Success)
  747. {
  748. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  749. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString());
  750. if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
  751. {
  752. session.IsCheckIn = true;
  753. if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  754. {
  755. CheckEVSEConfigure(session.ChargeBoxId);
  756. if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
  757. {
  758. using (var db = maindbContextFactory.CreateDbContext())
  759. {
  760. db.ServerMessage.Add(new ServerMessage()
  761. {
  762. ChargeBoxId = session.ChargeBoxId,
  763. CreatedBy = "Server",
  764. CreatedOn = DateTime.UtcNow,
  765. OutAction = Actions.ChangeConfiguration.ToString(),
  766. OutRequest = JsonConvert.SerializeObject(
  767. new ChangeConfigurationRequest()
  768. {
  769. key = "TimeOffset",
  770. value = "+08:00"
  771. },
  772. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  773. SerialNo = Guid.NewGuid().ToString(),
  774. InMessage = string.Empty
  775. });
  776. db.SaveChanges();
  777. }
  778. }
  779. }
  780. else
  781. {
  782. using (var db = maindbContextFactory.CreateDbContext())
  783. {
  784. var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
  785. if (machine != null)
  786. {
  787. if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
  788. {
  789. session.IsAC = false;
  790. }
  791. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  792. db.SaveChanges();
  793. }
  794. }
  795. await SetDefaultFee(session);
  796. }
  797. }
  798. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  799. {
  800. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  801. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  802. {
  803. using (var db = maindbContextFactory.CreateDbContext())
  804. {
  805. db.ServerMessage.Add(new ServerMessage()
  806. {
  807. ChargeBoxId = session.ChargeBoxId,
  808. CreatedBy = "Server",
  809. CreatedOn = DateTime.UtcNow,
  810. OutAction = Actions.DataTransfer.ToString(),
  811. OutRequest = JsonConvert.SerializeObject(
  812. new DataTransferRequest()
  813. {
  814. messageId = "SetUserPrice",
  815. vendorId = "Phihong Technology",
  816. data = JsonConvert.SerializeObject(
  817. new
  818. {
  819. idToken = authorizeRequest.idTag,
  820. price = session.UserDisplayPrices[authorizeRequest.idTag]
  821. })
  822. },
  823. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  824. SerialNo = Guid.NewGuid().ToString(),
  825. InMessage = string.Empty
  826. });
  827. db.SaveChanges();
  828. }
  829. }
  830. }
  831. }
  832. else
  833. {
  834. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  835. {
  836. //do nothing
  837. }
  838. else
  839. {
  840. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  841. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  842. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  843. }
  844. }
  845. sendTimer.Stop();
  846. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  847. {
  848. logger.Fatal("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  849. }
  850. if (action == Actions.StartTransaction)
  851. {
  852. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  853. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  854. if (_powerDic != null)
  855. {
  856. foreach (var kv in _powerDic)
  857. {
  858. try
  859. {
  860. if (kv.Value.HasValue)
  861. {
  862. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  863. }
  864. }
  865. catch (Exception ex)
  866. {
  867. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  868. }
  869. }
  870. }
  871. }
  872. if (action == Actions.StopTransaction)
  873. {
  874. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  875. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  876. if (_powerDic != null)
  877. {
  878. foreach (var kv in _powerDic)
  879. {
  880. try
  881. {
  882. if (kv.Value.HasValue)
  883. {
  884. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  885. }
  886. }
  887. catch (Exception ex)
  888. {
  889. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  890. }
  891. }
  892. }
  893. }
  894. }
  895. break;
  896. case "FirmwareManagement":
  897. {
  898. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  899. if (replyResult.Success)
  900. {
  901. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  902. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  903. }
  904. else
  905. {
  906. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  907. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  908. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  909. }
  910. }
  911. break;
  912. case "Security":
  913. {
  914. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  915. if (replyResult.Success)
  916. {
  917. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  918. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  919. }
  920. else
  921. {
  922. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  923. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  924. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  925. }
  926. }
  927. break;
  928. default:
  929. {
  930. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  931. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  932. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  933. }
  934. break;
  935. }
  936. }
  937. outter_stopwatch.Stop();
  938. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  939. {
  940. logger.Fatal("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  941. }
  942. }
  943. async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  944. {
  945. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  946. if (await ReConfirmMessage(analysisResult))
  947. {
  948. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  949. MessageResult confirmResult = null;
  950. switch (profileName)
  951. {
  952. case "Core":
  953. {
  954. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  955. }
  956. break;
  957. case "FirmwareManagement":
  958. {
  959. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  960. }
  961. break;
  962. case "RemoteTrigger":
  963. {
  964. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  965. }
  966. break;
  967. case "Reservation":
  968. {
  969. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  970. }
  971. break;
  972. case "LocalAuthListManagement":
  973. {
  974. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  975. }
  976. break;
  977. case "SmartCharging":
  978. {
  979. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  980. }
  981. break;
  982. case "Security":
  983. {
  984. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  985. }
  986. break;
  987. default:
  988. {
  989. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  990. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  991. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  992. }
  993. break;
  994. }
  995. if (confirmResult == null || !confirmResult.Success)
  996. {
  997. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  998. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  999. }
  1000. }
  1001. else
  1002. {
  1003. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1004. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1005. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1006. }
  1007. }
  1008. private async void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  1009. {
  1010. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1011. if (await ReConfirmMessage(analysisResult))
  1012. {
  1013. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1014. switch (profileName)
  1015. {
  1016. case "Core":
  1017. {
  1018. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1019. }
  1020. break;
  1021. case "FirmwareManagement":
  1022. {
  1023. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1024. }
  1025. break;
  1026. case "RemoteTrigger":
  1027. {
  1028. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1029. }
  1030. break;
  1031. case "Reservation":
  1032. {
  1033. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1034. }
  1035. break;
  1036. case "LocalAuthListManagement":
  1037. {
  1038. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1039. }
  1040. break;
  1041. case "SmartCharging":
  1042. {
  1043. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1044. }
  1045. break;
  1046. default:
  1047. {
  1048. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1049. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1050. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1051. }
  1052. break;
  1053. }
  1054. }
  1055. else
  1056. {
  1057. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1058. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1059. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1060. }
  1061. }
  1062. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  1063. {
  1064. try
  1065. {
  1066. if (session != null)
  1067. {
  1068. WriteMachineLog(session, msg, messageType, errorMsg, true).Wait();
  1069. session.Send(msg);
  1070. }
  1071. }
  1072. catch (Exception ex)
  1073. {
  1074. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  1075. }
  1076. }
  1077. async private Task<string> SetDefaultFee(ClientData client)
  1078. {
  1079. string displayPriceText = string.Empty;
  1080. string charingPriceText = string.Empty;
  1081. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1082. try
  1083. {
  1084. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1085. {
  1086. var parameters = new DynamicParameters();
  1087. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input, 36);
  1088. string displayPricestrSql = "";
  1089. string strSql = "";
  1090. if (client.IsAC)
  1091. {
  1092. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1093. " ,[AC_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=1; ";
  1097. }
  1098. else
  1099. {
  1100. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1101. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1102. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1103. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1104. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1105. }
  1106. //var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1107. var result = await conn.QueryFirstOrDefaultAsync<StationFee>(displayPricestrSql, parameters);
  1108. if (result == default)
  1109. {
  1110. return string.Empty;
  1111. }
  1112. var stationPrice = result;//.First();
  1113. if (stationPrice.BillingMethod == 1)
  1114. {
  1115. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1116. client.ChargingPrices = chargingPriceResult.ToList();
  1117. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1118. {
  1119. client.ChargingPrices = new List<ChargingPrice>();
  1120. }
  1121. }
  1122. displayPriceText = stationPrice.FeeName;
  1123. client.BillingMethod = stationPrice.BillingMethod;
  1124. client.Currency = stationPrice.Currency;
  1125. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1126. client.ParkingFee = stationPrice.ParkingFee;
  1127. client.IsBilling = true;
  1128. }
  1129. }
  1130. catch (Exception ex)
  1131. {
  1132. logger.Error("SetDefaultFee", ex.ToString());
  1133. }
  1134. return displayPriceText;
  1135. }
  1136. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1137. {
  1138. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1139. _needConfirmMsg.Id = table_id;
  1140. _needConfirmMsg.SentAction = action;
  1141. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1142. _needConfirmMsg.SentTimes = 4;
  1143. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1144. _needConfirmMsg.RequestId = requestId;
  1145. _needConfirmMsg.SentUniqueId = msg_id;
  1146. _needConfirmMsg.CreatedBy = createdBy;
  1147. _needConfirmMsg.SentMessage = sendMessage;
  1148. if (needConfirmActions.Contains(action))
  1149. {
  1150. lock (_lockConfirmPacketList)
  1151. {
  1152. needConfirmPacketList.Add(_needConfirmMsg);
  1153. }
  1154. }
  1155. }
  1156. internal void RemoveConfirmMessage()
  1157. {
  1158. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1159. lock (_lockConfirmPacketList)
  1160. {
  1161. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1162. foreach (var item in removeList)
  1163. {
  1164. needConfirmPacketList.Remove(item);
  1165. }
  1166. }
  1167. }
  1168. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1169. {
  1170. bool confirmed = false;
  1171. if (needConfirmActions.Contains(analysisResult.Action))
  1172. {
  1173. NeedConfirmMessage foundRequest = null;
  1174. lock (_lockConfirmPacketList)
  1175. {
  1176. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1177. }
  1178. if (foundRequest != null && foundRequest.Id > 0)
  1179. {
  1180. foundRequest.SentTimes = 0;
  1181. foundRequest.SentInterval = 0;
  1182. analysisResult.RequestId = foundRequest.RequestId;
  1183. using (var db = maindbContextFactory.CreateDbContext())
  1184. {
  1185. var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
  1186. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1187. sc.ReceivedOn = DateTime.UtcNow;
  1188. db.SaveChanges();
  1189. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1190. }
  1191. confirmed = true;
  1192. }
  1193. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1194. {
  1195. confirmed = true;
  1196. }
  1197. else
  1198. {
  1199. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1200. }
  1201. }
  1202. return confirmed;
  1203. }
  1204. internal void RemoveClient(ClientData session)
  1205. {
  1206. if (session == null)
  1207. {
  1208. return;
  1209. }
  1210. if (!string.IsNullOrEmpty(session.MachineId))
  1211. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1212. if (session.Connected)
  1213. {
  1214. session.Close(CloseReason.ServerShutdown);
  1215. }
  1216. RemoveClientDic(session);
  1217. try
  1218. {
  1219. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1220. // session.Close(CloseReason.ServerShutdown);
  1221. }
  1222. catch (Exception ex)
  1223. {
  1224. //logger.LogWarning("Close client socket error!!");
  1225. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1226. }
  1227. if (session != null)
  1228. {
  1229. session = null;
  1230. }
  1231. }
  1232. private void RemoveClientDic(ClientData session)
  1233. {
  1234. if (string.IsNullOrEmpty(session.ChargeBoxId))
  1235. {
  1236. return;
  1237. }
  1238. if (clientDic.ContainsKey(session.ChargeBoxId))
  1239. {
  1240. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1241. {
  1242. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1243. clientDic.Remove(session.ChargeBoxId, out _);
  1244. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1245. }
  1246. }
  1247. }
  1248. private void WarmUpLog()
  1249. {
  1250. connectionLogdbService.WarmUpLog();
  1251. }
  1252. private async Task WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1253. {
  1254. try
  1255. {
  1256. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1257. if (clientData.ChargeBoxId == null)
  1258. {
  1259. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1260. }
  1261. connectionLogdbService.WriteMachineLog(clientData, data, messageType, errorMsg, isSent);
  1262. }
  1263. catch (Exception ex)
  1264. {
  1265. Console.WriteLine(ex.ToString());
  1266. }
  1267. }
  1268. }
  1269. }