ProtalServer.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  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. try
  1077. {
  1078. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1079. {
  1080. var parameters = new DynamicParameters();
  1081. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input, 36);
  1082. string displayPricestrSql = "";
  1083. string strSql = "";
  1084. if (client.IsAC)
  1085. {
  1086. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1087. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1088. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1089. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1090. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1091. }
  1092. else
  1093. {
  1094. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1095. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1096. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1097. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1098. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1099. }
  1100. //var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1101. var result = await conn.QueryFirstOrDefaultAsync<StationFee>(displayPricestrSql, parameters);
  1102. if (result == default)
  1103. {
  1104. return string.Empty;
  1105. }
  1106. var stationPrice = result;//.First();
  1107. if (stationPrice.BillingMethod == 1)
  1108. {
  1109. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1110. client.ChargingPrices = chargingPriceResult.ToList();
  1111. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1112. {
  1113. client.ChargingPrices = new List<ChargingPrice>();
  1114. }
  1115. }
  1116. displayPriceText = stationPrice.FeeName;
  1117. client.BillingMethod = stationPrice.BillingMethod;
  1118. client.Currency = stationPrice.Currency;
  1119. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1120. client.ParkingFee = stationPrice.ParkingFee;
  1121. client.IsBilling = true;
  1122. }
  1123. }
  1124. catch (Exception ex)
  1125. {
  1126. logger.Error("SetDefaultFee", ex.ToString());
  1127. }
  1128. return displayPriceText;
  1129. }
  1130. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1131. {
  1132. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1133. _needConfirmMsg.Id = table_id;
  1134. _needConfirmMsg.SentAction = action;
  1135. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1136. _needConfirmMsg.SentTimes = 4;
  1137. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1138. _needConfirmMsg.RequestId = requestId;
  1139. _needConfirmMsg.SentUniqueId = msg_id;
  1140. _needConfirmMsg.CreatedBy = createdBy;
  1141. _needConfirmMsg.SentMessage = sendMessage;
  1142. if (needConfirmActions.Contains(action))
  1143. {
  1144. lock (_lockConfirmPacketList)
  1145. {
  1146. needConfirmPacketList.Add(_needConfirmMsg);
  1147. }
  1148. }
  1149. }
  1150. internal void RemoveConfirmMessage()
  1151. {
  1152. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1153. lock (_lockConfirmPacketList)
  1154. {
  1155. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1156. foreach (var item in removeList)
  1157. {
  1158. needConfirmPacketList.Remove(item);
  1159. }
  1160. }
  1161. }
  1162. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1163. {
  1164. bool confirmed = false;
  1165. if (needConfirmActions.Contains(analysisResult.Action))
  1166. {
  1167. NeedConfirmMessage foundRequest = null;
  1168. lock (_lockConfirmPacketList)
  1169. {
  1170. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1171. }
  1172. if (foundRequest != null && foundRequest.Id > 0)
  1173. {
  1174. foundRequest.SentTimes = 0;
  1175. foundRequest.SentInterval = 0;
  1176. analysisResult.RequestId = foundRequest.RequestId;
  1177. using (var db = maindbContextFactory.CreateDbContext())
  1178. {
  1179. var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
  1180. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1181. sc.ReceivedOn = DateTime.UtcNow;
  1182. db.SaveChanges();
  1183. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1184. }
  1185. confirmed = true;
  1186. }
  1187. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1188. {
  1189. confirmed = true;
  1190. }
  1191. else
  1192. {
  1193. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1194. }
  1195. }
  1196. return confirmed;
  1197. }
  1198. internal void RemoveClient(ClientData session)
  1199. {
  1200. if (session == null)
  1201. {
  1202. return;
  1203. }
  1204. if (!string.IsNullOrEmpty(session.MachineId))
  1205. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1206. if (session.Connected)
  1207. {
  1208. session.Close(CloseReason.ServerShutdown);
  1209. }
  1210. RemoveClientDic(session);
  1211. try
  1212. {
  1213. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1214. // session.Close(CloseReason.ServerShutdown);
  1215. }
  1216. catch (Exception ex)
  1217. {
  1218. //logger.LogWarning("Close client socket error!!");
  1219. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1220. }
  1221. if (session != null)
  1222. {
  1223. session = null;
  1224. }
  1225. }
  1226. private void RemoveClientDic(ClientData session)
  1227. {
  1228. if (string.IsNullOrEmpty(session.ChargeBoxId))
  1229. {
  1230. return;
  1231. }
  1232. if (clientDic.ContainsKey(session.ChargeBoxId))
  1233. {
  1234. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1235. {
  1236. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1237. clientDic.Remove(session.ChargeBoxId, out _);
  1238. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1239. }
  1240. }
  1241. }
  1242. private void WarmUpLog()
  1243. {
  1244. connectionLogdbService.WarmUpLog();
  1245. }
  1246. private async Task WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1247. {
  1248. try
  1249. {
  1250. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1251. if (clientData.ChargeBoxId == null)
  1252. {
  1253. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1254. }
  1255. connectionLogdbService.WriteMachineLog(clientData, data, messageType, errorMsg, isSent);
  1256. }
  1257. catch (Exception ex)
  1258. {
  1259. Console.WriteLine(ex.ToString());
  1260. }
  1261. }
  1262. }
  1263. }