ProtalServer.cs 70 KB

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