ProtalServer.cs 68 KB

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