ProtalServer.cs 70 KB

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