ProtalServer.cs 69 KB

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