ProtalServer.cs 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  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. namespace EVCB_OCPP.WSServer
  40. {
  41. public class DestroyRequest : IRequest
  42. {
  43. public string Action { get; set; }
  44. public bool TransactionRelated()
  45. {
  46. return false;
  47. }
  48. public bool Validate()
  49. {
  50. return true;
  51. }
  52. }
  53. internal class ProtalServer : IHostedService
  54. {
  55. static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  56. private OuterHttpClient httpClient = new OuterHttpClient();
  57. private DateTime lastcheckdt = DateTime.UtcNow.AddSeconds(-20);
  58. private Dictionary<string, ClientData> clientDic = new Dictionary<string, ClientData>();
  59. private readonly Object _lockClientDic = new object();
  60. private readonly Object _lockConfirmPacketList = new object();
  61. private readonly IConfiguration configuration;
  62. private readonly IServiceProvider serviceProvider;
  63. private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
  64. private readonly ProfileHandler profileHandler;//= new ProfileHandler();
  65. private readonly string webConnectionString;// = ConfigurationManager.ConnectionStrings["WebDBContext"].ConnectionString;
  66. private readonly bool isInDocker;
  67. private List<NeedConfirmMessage> needConfirmPacketList = new List<NeedConfirmMessage>();
  68. private DateTime checkUpdateDt = DateTime.UtcNow;
  69. private DateTime _CheckFeeDt = DateTime.UtcNow;
  70. private DateTime _CheckWeatherDt = DateTime.UtcNow;
  71. private readonly LoadingBalanceService _loadingBalanceService;// = new LoadingBalanceService();
  72. private Dictionary<string, TCCWeatherDto> TCCStationDic = new Dictionary<string, TCCWeatherDto>();
  73. private List<string> needConfirmActions = new List<string>()
  74. {
  75. "GetConfiguration",
  76. "ChangeConfiguration",
  77. "RemoteStartTransaction",
  78. "RemoteStopTransaction",
  79. "ChangeAvailability",
  80. "ClearCache",
  81. "DataTransfer",
  82. "Reset",
  83. "UnlockConnector",
  84. "TriggerMessage",
  85. "GetDiagnostics",
  86. "UpdateFirmware",
  87. "GetLocalListVersion",
  88. "SendLocalList",
  89. "SetChargingProfile",
  90. "ClearChargingProfile",
  91. "GetCompositeSchedule",
  92. "ReserveNow",
  93. "CancelReservation",
  94. "ExtendedTriggerMessage"
  95. };
  96. private List<Profile> profiles = new List<Profile>()
  97. {
  98. new CoreProfile(),
  99. new FirmwareManagementProfile(),
  100. new ReservationProfile(),
  101. new RemoteTriggerProfile(),
  102. new SmartChargingProfile(),
  103. new LocalAuthListManagementProfile(),
  104. new SecurityProfile(),
  105. };
  106. private CancellationTokenSource _cts = new CancellationTokenSource();
  107. private CancellationToken _ct;
  108. private string _ocpp20NetworkSetting = "";
  109. public ProtalServer(
  110. IConfiguration configuration
  111. , IServiceProvider serviceProvider
  112. , IDbContextFactory<MainDBContext> maindbContextFactory)
  113. {
  114. _ct = _cts.Token;
  115. this.configuration = configuration;
  116. this.serviceProvider = serviceProvider;
  117. this.maindbContextFactory = maindbContextFactory;
  118. isInDocker = !string.IsNullOrEmpty(configuration["DOTNET_RUNNING_IN_CONTAINER"]);
  119. webConnectionString = configuration.GetConnectionString("WebDBContext");
  120. profileHandler = serviceProvider.GetService<ProfileHandler>();// new ProfileHandler(configuration, serviceProvider);
  121. _loadingBalanceService = new LoadingBalanceService(configuration);
  122. WarmUpLog();
  123. }
  124. public Task StartAsync(CancellationToken cancellationToken)
  125. {
  126. Start();
  127. return Task.CompletedTask;
  128. }
  129. public Task StopAsync(CancellationToken cancellationToken)
  130. {
  131. return Task.CompletedTask;
  132. }
  133. internal void Start()
  134. {
  135. Console.WriteLine("Starting Server...");
  136. if (!GlobalConfig.LoadAPPConfig(configuration))
  137. {
  138. Console.WriteLine("Please check App.Config setting .");
  139. return;
  140. }
  141. //ReadTCCSetting();
  142. OpenNetwork();
  143. Task serverCommandTask = new Task(ServerMessageTrigger, _ct);
  144. serverCommandTask.Start();
  145. Task serverUpdateTask = new Task(ServerUpdateTrigger, _ct);
  146. serverUpdateTask.Start();
  147. Task serverSetFeeTask = new Task(ServerSetFeeTrigger, _ct);
  148. serverSetFeeTask.Start();
  149. Task serverWeatherNotificationTask = new Task(ServerWeatherNotificationTrigger, _ct);
  150. serverWeatherNotificationTask.Start();
  151. Task serverBeatTask = new Task(HeartBeatCheckTrigger, _ct);
  152. serverBeatTask.Start();
  153. Task serverHealthTask = new Task(HealthCheckTrigger, _ct);
  154. serverHealthTask.Start();
  155. if (!isInDocker)
  156. {
  157. RunConsoleInteractive();
  158. return;
  159. }
  160. RunHttpConsoleService();
  161. }
  162. private void RunConsoleInteractive()
  163. {
  164. while (true)
  165. {
  166. if (Console.In is null)
  167. {
  168. break;
  169. }
  170. var input = Console.ReadLine();
  171. switch (input.ToLower())
  172. {
  173. case "stop":
  174. Console.WriteLine("Command stop");
  175. Stop();
  176. break;
  177. case "gc":
  178. Console.WriteLine("Command GC");
  179. GC.Collect();
  180. break;
  181. case "lc":
  182. {
  183. Console.WriteLine("Command List Clients");
  184. Dictionary<string, ClientData> _copyClientDic = null;
  185. lock (_lockClientDic)
  186. {
  187. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  188. }
  189. var list = _copyClientDic.Select(c => c.Value).ToList();
  190. var locations = _copyClientDic.Where(x => !string.IsNullOrEmpty(x.Value.StationLocation)).Distinct().Select(x => x.Value.StationLocation).ToList();
  191. int i = 1;
  192. foreach (var c in list)
  193. {
  194. Console.WriteLine(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  195. i++;
  196. }
  197. foreach (var c in TCCStationDic)
  198. {
  199. Console.WriteLine(i + ":" + c.Key + "-" + c.Value.Temperature + "/" + c.Value.WeatherID);
  200. i++;
  201. }
  202. }
  203. break;
  204. case "lcn":
  205. {
  206. Console.WriteLine("Command List Customer Name");
  207. Dictionary<string, ClientData> _copyClientDic = null;
  208. lock (_lockClientDic)
  209. {
  210. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  211. }
  212. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  213. int iLcn = 1;
  214. foreach (var c in lcn)
  215. {
  216. Console.WriteLine(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  217. iLcn++;
  218. }
  219. }
  220. break;
  221. case "help":
  222. Console.WriteLine("Command help!!");
  223. Console.WriteLine("lcn : List Customer Name");
  224. Console.WriteLine("gc : GC Collect");
  225. Console.WriteLine("lc : List Clients");
  226. Console.WriteLine("cls : clear console");
  227. Console.WriteLine("silent : silent");
  228. Console.WriteLine("show : show log");
  229. // logger.Info("rcl : show Real Connection Limit");
  230. break;
  231. case "cls":
  232. Console.WriteLine("Command clear");
  233. Console.Clear();
  234. break;
  235. case "silent":
  236. Console.WriteLine("Command silent");
  237. //var xe = XElement.Load("NLog.config");
  238. //var xns = xe.GetDefaultNamespace();
  239. //var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  240. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  241. //if (minlevelattr != null)
  242. //{
  243. // minlevelattr.Value = "Warn";
  244. //}
  245. //xe.Save("NLog.config");
  246. foreach (var rule in LogManager.Configuration.LoggingRules)
  247. {
  248. if (rule.RuleName != "ConsoleLog")
  249. {
  250. continue;
  251. }
  252. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  253. if (isTargetRule)
  254. {
  255. rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Off);
  256. }
  257. }
  258. break;
  259. case "show":
  260. Console.WriteLine("Command show");
  261. //var xe1 = XElement.Load("NLog.config");
  262. //var xns1 = xe1.GetDefaultNamespace();
  263. //var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  264. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  265. //if (minlevelattr1 != null)
  266. //{
  267. // minlevelattr1.Value = "trace";
  268. //}
  269. //xe1.Save("NLog.config");
  270. foreach (var rule in LogManager.Configuration.LoggingRules)
  271. {
  272. if (rule.RuleName != "ConsoleLog")
  273. {
  274. continue;
  275. }
  276. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  277. if (isTargetRule)
  278. {
  279. rule.SetLoggingLevels(LogLevel.Trace, LogLevel.Off);
  280. }
  281. }
  282. break;
  283. case "rcl":
  284. break;
  285. default:
  286. break;
  287. }
  288. }
  289. }
  290. private void RunHttpConsoleService()
  291. {
  292. var app = WebApplication.Create();
  293. var helpFunc = () => {
  294. return string.Join("\r\n", new[] {
  295. "Command help!!",
  296. "lcn : List Customer Name",
  297. "gc : GC Collect",
  298. "lc : List Clients",
  299. "silent : silent",
  300. "show : show log"
  301. });
  302. };
  303. app.MapGet("/", helpFunc);
  304. app.MapGet("/help", helpFunc);
  305. app.MapPost("/stop", () => {
  306. Stop();
  307. return "Command stop";
  308. });
  309. app.MapPost("/gc", () => {
  310. GC.Collect();
  311. return "Command GC";
  312. });
  313. app.MapPost("/lc", () => {
  314. List<string> toReturn = new List<string>() { "Command List Clients" };
  315. Dictionary<string, ClientData> _copyClientDic = null;
  316. lock (_lockClientDic)
  317. {
  318. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  319. }
  320. var list = _copyClientDic.Select(c => c.Value).ToList();
  321. var locations = _copyClientDic.Where(x => !string.IsNullOrEmpty(x.Value.StationLocation)).Distinct().Select(x => x.Value.StationLocation).ToList();
  322. int i = 1;
  323. foreach (var c in list)
  324. {
  325. toReturn.Add(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  326. i++;
  327. }
  328. foreach (var c in TCCStationDic)
  329. {
  330. toReturn.Add(i + ":" + c.Key + "-" + c.Value.Temperature + "/" + c.Value.WeatherID);
  331. i++;
  332. }
  333. return string.Join("\r\n", toReturn);
  334. });
  335. app.MapPost("/lcn", () => {
  336. List<string> toReturn = new List<string> { "Command List Customer Name" };
  337. Dictionary<string, ClientData> _copyClientDic = null;
  338. lock (_lockClientDic)
  339. {
  340. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  341. }
  342. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  343. int iLcn = 1;
  344. foreach (var c in lcn)
  345. {
  346. toReturn.Add(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  347. iLcn++;
  348. }
  349. return string.Join("\r\n", toReturn);
  350. });
  351. app.MapPost("/silent", () => {
  352. foreach (var rule in LogManager.Configuration.LoggingRules)
  353. {
  354. if (rule.RuleName != "ConsoleLog")
  355. {
  356. continue;
  357. }
  358. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  359. if (isTargetRule)
  360. {
  361. rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Off);
  362. }
  363. }
  364. return "Command silent";
  365. });
  366. app.MapPost("/show", () => {
  367. foreach (var rule in LogManager.Configuration.LoggingRules)
  368. {
  369. if (rule.RuleName != "ConsoleLog")
  370. {
  371. continue;
  372. }
  373. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  374. if (isTargetRule)
  375. {
  376. rule.SetLoggingLevels(LogLevel.Trace, LogLevel.Off);
  377. }
  378. }
  379. return "Command show";
  380. });
  381. app.Urls.Add("http://*:54088");
  382. _ = app.RunAsync();
  383. }
  384. internal void Stop()
  385. {
  386. if (_cts != null)
  387. {
  388. _cts.Cancel();
  389. }
  390. }
  391. private void CheckVersion(string chargeBoxId)
  392. {
  393. if (string.IsNullOrEmpty(chargeBoxId)) return;
  394. using (var db = maindbContextFactory.CreateDbContext())
  395. {
  396. db.ServerMessage.Add(new ServerMessage()
  397. {
  398. ChargeBoxId = chargeBoxId,
  399. CreatedBy = "Server",
  400. CreatedOn = DateTime.UtcNow,
  401. OutAction = Actions.DataTransfer.ToString(),
  402. OutRequest = JsonConvert.SerializeObject(
  403. new DataTransferRequest()
  404. {
  405. messageId = "ID_FirmwareVersion",
  406. vendorId = "Phihong Technology"
  407. },
  408. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  409. SerialNo = Guid.NewGuid().ToString(),
  410. InMessage = string.Empty
  411. });
  412. db.SaveChanges();
  413. }
  414. }
  415. private void CheckEVSEConfigure(string chargeBoxId)
  416. {
  417. if (string.IsNullOrEmpty(chargeBoxId)) return;
  418. using (var db = maindbContextFactory.CreateDbContext())
  419. {
  420. db.ServerMessage.Add(new ServerMessage()
  421. {
  422. ChargeBoxId = chargeBoxId,
  423. CreatedBy = "Server",
  424. CreatedOn = DateTime.UtcNow,
  425. OutAction = Actions.GetConfiguration.ToString(),
  426. OutRequest = JsonConvert.SerializeObject(
  427. new GetConfigurationRequest()
  428. {
  429. key = new List<string>()
  430. },
  431. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  432. SerialNo = Guid.NewGuid().ToString(),
  433. InMessage = string.Empty
  434. }); ;
  435. db.SaveChanges();
  436. }
  437. }
  438. #region 台泥
  439. private void ReadTCCSetting()
  440. {
  441. using (var db = maindbContextFactory.CreateDbContext())
  442. {
  443. var info = db.Customer.Where(x => x.Id == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8")).Select(x => new { x.ApiUrl, x.ApiKey }).FirstOrDefault();
  444. GlobalConfig.TCC_API_URL = info.ApiUrl;
  445. GlobalConfig.TCC_SALTKEY = info.ApiKey;
  446. }
  447. }
  448. async private Task<TCCStationInfoDto> GetStationInfo(string machineId)
  449. {
  450. TCCStationInfoDto stationInfo = null;
  451. if (string.IsNullOrEmpty(machineId)) return stationInfo;
  452. using (SqlConnection conn = new SqlConnection(webConnectionString))
  453. {
  454. var parameters = new DynamicParameters();
  455. parameters.Add("@MachineId", machineId, DbType.String, ParameterDirection.Input);
  456. string sql = " SELECT CAST([Latitude] as DECIMAL(5,2)) Lat,CAST([Longitude] as DECIMAL(5, 2)) Long ,SUBSTRING([Address],1,3) as zipcode FROM[StationMachine] left join [dbo].[Station]" +
  457. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId; ";
  458. var result = await conn.QueryAsync<TCCStationInfoDto>(sql, parameters);
  459. stationInfo = result.FirstOrDefault();
  460. }
  461. return stationInfo;
  462. }
  463. #endregion
  464. private void OpenNetwork()
  465. {
  466. //載入OCPP Protocol
  467. var appServer = new OCPPWSServer(
  468. new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0") }
  469. ,serviceProvider);
  470. List<IListenerConfig> llistener = new List<IListenerConfig>();
  471. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWS_Port()), Backlog = 100, Security = "None" });
  472. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWSS_Port()), Backlog = 100, Security = SslProtocols.Tls12.ToString() });
  473. //var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;\
  474. //var certificate = configuration.GetSection("superSocket").GetSection("Servers:0").GetSection("Certificate").Get<CertificateConfig>();
  475. var certificate = configuration.GetSection("SuperSocketServerCertificate").Get<CertificateConfig>();
  476. ICertificateConfig Certificate = certificate;
  477. IEnumerable<IListenerConfig> listeners = llistener;
  478. //設定server config
  479. var serverConfig = new ServerConfig
  480. {
  481. //Port = Convert.ToInt32(2012),
  482. //Ip = "172.17.40.13",
  483. MaxRequestLength = 204800,
  484. //Security = serverSecurity,
  485. Certificate = Certificate,
  486. Listeners = listeners,
  487. // LogAllSocketException = true,
  488. KeepAliveTime = 10,
  489. // LogBasicSessionActivity = true
  490. };
  491. //Setup with listening port
  492. if (!appServer.Setup(serverConfig, logFactory: new NLogLoggerFactory()))
  493. {
  494. Console.WriteLine("Failed to setup!");
  495. return;
  496. }
  497. appServer.NewSessionConnected += AppServer_NewSessionConnected;
  498. appServer.SessionClosed += AppServer_SessionClosed;
  499. //Try to start the appServer
  500. if (!appServer.Start())
  501. {
  502. Console.WriteLine("Failed to start!");
  503. //Console.ReadKey();
  504. return;
  505. }
  506. }
  507. private void AppServer_SessionClosed(ClientData session, CloseReason value)
  508. {
  509. WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
  510. RemoveClient(session);
  511. }
  512. private void AppServer_NewSessionConnected(ClientData session)
  513. {
  514. logger.Debug(string.Format("{0} NewSessionConnected", session.Path));
  515. try
  516. {
  517. lock (_lockClientDic)
  518. {
  519. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  520. if (isNotSupported)
  521. {
  522. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  523. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  524. return;
  525. }
  526. ClientData _removeClient = null;
  527. clientDic.TryGetValue(session.ChargeBoxId, out _removeClient);
  528. if (_removeClient != null)
  529. {
  530. WriteMachineLog(_removeClient, "Duplicate Logins", "Connection", "");
  531. _removeClient.Close(CloseReason.ServerShutdown);
  532. RemoveClient(_removeClient);
  533. }
  534. clientDic.Add(session.ChargeBoxId, session);
  535. session.m_ReceiveData += new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  536. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  537. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  538. using (var db = maindbContextFactory.CreateDbContext())
  539. {
  540. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  541. if (machine != null)
  542. {
  543. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  544. db.SaveChanges();
  545. }
  546. }
  547. }
  548. }
  549. catch (Exception ex)
  550. {
  551. logger.Error(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  552. }
  553. }
  554. async private void ReceivedMessage(ClientData session, string rawdata)
  555. {
  556. try
  557. {
  558. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  559. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  560. WriteMachineLog(session, rawdata,
  561. 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);
  562. if (session.ResetSecurityProfile)
  563. {
  564. logger.Error(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  565. RemoveClient(session);
  566. return;
  567. }
  568. if (!analysisResult.Success)
  569. {
  570. //解析RawData就發生錯誤
  571. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  572. {
  573. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  574. }
  575. else
  576. {
  577. if (analysisResult.Message == null)
  578. {
  579. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  580. string errorMsg = string.Empty;
  581. if (analysisResult.Exception != null)
  582. {
  583. errorMsg = analysisResult.Exception.ToString();
  584. }
  585. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  586. }
  587. else
  588. {
  589. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  590. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  591. string errorMsg = string.Empty;
  592. if (analysisResult.Exception != null)
  593. {
  594. errorMsg = analysisResult.Exception.ToString();
  595. }
  596. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  597. }
  598. }
  599. }
  600. else
  601. {
  602. switch (analysisResult.Id)
  603. {
  604. case BasicMessageHandler.TYPENUMBER_CALL:
  605. {
  606. if (!session.ISOCPP20)
  607. {
  608. Actions action = Convertor.GetAction(analysisResult.Action);
  609. ProcessRequestMessage(analysisResult, session, action);
  610. }
  611. else
  612. {
  613. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  614. MessageResult result = new MessageResult() { Success = true };
  615. //ocpp20 處理
  616. switch (action)
  617. {
  618. case EVCB_OCPP20.Packet.Features.Actions.BootNotification:
  619. {
  620. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  621. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  622. result.Message = confirm;
  623. result.Success = true;
  624. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  625. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  626. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  627. {
  628. ConfigurationSlot = 1,
  629. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  630. {
  631. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  632. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  633. MessageTimeout = 30,
  634. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  635. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  636. }
  637. };
  638. var uuid = session.queue20.store(request);
  639. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  640. Send(session, requestText, "SetNetworkProfile");
  641. }
  642. break;
  643. default:
  644. {
  645. logger.Error(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  646. }
  647. break;
  648. }
  649. }
  650. }
  651. break;
  652. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  653. {
  654. if (!session.ISOCPP20)
  655. {
  656. Actions action = Convertor.GetAction(analysisResult.Action);
  657. ProcessConfirmationMessage(analysisResult, session, action);
  658. }
  659. else
  660. {
  661. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  662. MessageResult result = new MessageResult() { Success = true };
  663. //ocpp20 處理
  664. switch (action)
  665. {
  666. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  667. {
  668. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  669. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  670. {
  671. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  672. {
  673. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  674. {
  675. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  676. {
  677. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  678. {
  679. Name="OCPPCommCtrlr",
  680. },
  681. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  682. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  683. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  684. {
  685. Name="NetworkConfigurationPriority",
  686. }
  687. }
  688. }
  689. };
  690. var uuid = session.queue20.store(request);
  691. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  692. Send(session, requestText, "SetVariables");
  693. }
  694. }
  695. break;
  696. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  697. {
  698. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  699. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  700. {
  701. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  702. {
  703. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  704. };
  705. var uuid = session.queue20.store(request);
  706. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  707. Send(session, requestText, "Reset");
  708. }
  709. }
  710. break;
  711. default:
  712. {
  713. logger.Error(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  714. }
  715. break;
  716. }
  717. }
  718. }
  719. break;
  720. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  721. {
  722. //只處理 丟出Request 收到Error的訊息
  723. if (analysisResult.Success && analysisResult.Message != null)
  724. {
  725. Actions action = Convertor.GetAction(analysisResult.Action);
  726. ProcessErrorMessage(analysisResult, session, action);
  727. }
  728. }
  729. break;
  730. default:
  731. {
  732. logger.Error(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  733. }
  734. break;
  735. }
  736. }
  737. await Task.Delay(10);
  738. }
  739. catch (Exception ex)
  740. {
  741. if (ex.InnerException != null)
  742. {
  743. logger.Error(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  744. }
  745. else
  746. {
  747. logger.Error(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  748. }
  749. }
  750. }
  751. async private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
  752. {
  753. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  754. if (!session.IsCheckIn && action != Actions.BootNotification)
  755. {
  756. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  757. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  758. }
  759. else
  760. {
  761. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  762. switch (profileName)
  763. {
  764. case "Core":
  765. {
  766. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  767. if (replyResult.Success)
  768. {
  769. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  770. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString());
  771. if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
  772. {
  773. session.IsCheckIn = true;
  774. if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  775. {
  776. CheckVersion(session.ChargeBoxId);
  777. CheckEVSEConfigure(session.ChargeBoxId);
  778. if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
  779. {
  780. using (var db = maindbContextFactory.CreateDbContext())
  781. {
  782. db.ServerMessage.Add(new ServerMessage()
  783. {
  784. ChargeBoxId = session.ChargeBoxId,
  785. CreatedBy = "Server",
  786. CreatedOn = DateTime.UtcNow,
  787. OutAction = Actions.ChangeConfiguration.ToString(),
  788. OutRequest = JsonConvert.SerializeObject(
  789. new ChangeConfigurationRequest()
  790. {
  791. key = "TimeOffset",
  792. value = "+08:00"
  793. },
  794. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  795. SerialNo = Guid.NewGuid().ToString(),
  796. InMessage = string.Empty
  797. });
  798. db.SaveChanges();
  799. }
  800. }
  801. if (session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  802. {
  803. var stationInfo = await GetStationInfo(session.MachineId);
  804. if (stationInfo != null)
  805. {
  806. session.StationLocation = string.Format("{0},{1}", stationInfo.Lat, stationInfo.Long);
  807. session.StationName = stationInfo.ZipCode;
  808. }
  809. using (var db = maindbContextFactory.CreateDbContext())
  810. {
  811. db.ServerMessage.Add(new ServerMessage()
  812. {
  813. ChargeBoxId = session.ChargeBoxId,
  814. CreatedBy = "Server",
  815. CreatedOn = DateTime.UtcNow,
  816. OutAction = Actions.DataTransfer.ToString(),
  817. OutRequest = JsonConvert.SerializeObject(
  818. new DataTransferRequest()
  819. {
  820. messageId = "ID_Station_Location",
  821. vendorId = "Phihong Technology",
  822. data = JsonConvert.SerializeObject(new { stationName = session.StationName })
  823. },
  824. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  825. SerialNo = Guid.NewGuid().ToString(),
  826. InMessage = string.Empty
  827. });
  828. db.ServerMessage.Add(new ServerMessage()
  829. {
  830. ChargeBoxId = session.ChargeBoxId,
  831. CreatedBy = "Server",
  832. CreatedOn = DateTime.UtcNow,
  833. OutAction = Actions.ChangeConfiguration.ToString(),
  834. OutRequest = JsonConvert.SerializeObject(
  835. new ChangeConfigurationRequest()
  836. {
  837. key = "TimeOffset",
  838. value = "+08:00"
  839. },
  840. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  841. SerialNo = Guid.NewGuid().ToString(),
  842. InMessage = string.Empty
  843. });
  844. if (!TCCStationDic.ContainsKey(session.StationLocation))
  845. {
  846. _CheckWeatherDt = DateTime.UtcNow.AddDays(-1);
  847. }
  848. else
  849. {
  850. db.ServerMessage.Add(new ServerMessage()
  851. {
  852. ChargeBoxId = session.ChargeBoxId,
  853. CreatedBy = "Server",
  854. CreatedOn = DateTime.UtcNow,
  855. OutAction = Actions.DataTransfer.ToString(),
  856. OutRequest = JsonConvert.SerializeObject(
  857. new DataTransferRequest()
  858. {
  859. messageId = "ID_Weather_Info",
  860. vendorId = "Phihong Technology",
  861. data = JsonConvert.SerializeObject(
  862. new
  863. {
  864. weatherId = TCCStationDic[session.StationLocation].WeatherID,
  865. Temperature = TCCStationDic[session.StationLocation].Temperature
  866. })
  867. },
  868. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  869. SerialNo = Guid.NewGuid().ToString(),
  870. InMessage = string.Empty
  871. });
  872. }
  873. db.SaveChanges();
  874. }
  875. }
  876. }
  877. else
  878. {
  879. using (var db = maindbContextFactory.CreateDbContext())
  880. {
  881. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  882. if (machine != null)
  883. {
  884. if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
  885. {
  886. session.IsAC = false;
  887. }
  888. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  889. db.SaveChanges();
  890. }
  891. }
  892. await SetDefaultFee(session);
  893. }
  894. }
  895. #region 台泥
  896. if (action == Actions.StartTransaction && session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8") && replyResult.Message is StartTransactionConfirmation)
  897. {
  898. StartTransactionConfirmation confirm = (StartTransactionConfirmation)replyResult.Message;
  899. StartTransactionRequest request = (StartTransactionRequest)analysisResult.Message;
  900. using (var db = maindbContextFactory.CreateDbContext())
  901. {
  902. db.ServerMessage.Add(new ServerMessage()
  903. {
  904. ChargeBoxId = session.ChargeBoxId,
  905. CreatedBy = "Server",
  906. CreatedOn = DateTime.UtcNow,
  907. OutAction = Actions.DataTransfer.ToString(),
  908. OutRequest = JsonConvert.SerializeObject(
  909. new DataTransferRequest()
  910. {
  911. messageId = "ID_GetTxUserInfo",
  912. vendorId = "Phihong Technology",
  913. data = JsonConvert.SerializeObject(new { txId = confirm.transactionId, ConnectorId = request.connectorId })
  914. },
  915. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  916. SerialNo = Guid.NewGuid().ToString(),
  917. InMessage = string.Empty
  918. });
  919. db.SaveChanges();
  920. }
  921. }
  922. #endregion
  923. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  924. {
  925. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  926. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  927. {
  928. using (var db = maindbContextFactory.CreateDbContext())
  929. {
  930. db.ServerMessage.Add(new ServerMessage()
  931. {
  932. ChargeBoxId = session.ChargeBoxId,
  933. CreatedBy = "Server",
  934. CreatedOn = DateTime.UtcNow,
  935. OutAction = Actions.DataTransfer.ToString(),
  936. OutRequest = JsonConvert.SerializeObject(
  937. new DataTransferRequest()
  938. {
  939. messageId = "SetUserPrice",
  940. vendorId = "Phihong Technology",
  941. data = JsonConvert.SerializeObject(
  942. new
  943. {
  944. idToken = authorizeRequest.idTag,
  945. price = session.UserDisplayPrices[authorizeRequest.idTag]
  946. })
  947. },
  948. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  949. SerialNo = Guid.NewGuid().ToString(),
  950. InMessage = string.Empty
  951. });
  952. db.SaveChanges();
  953. }
  954. }
  955. }
  956. }
  957. else
  958. {
  959. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  960. {
  961. //do nothing
  962. }
  963. else
  964. {
  965. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  966. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  967. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  968. }
  969. }
  970. if (action == Actions.StartTransaction)
  971. {
  972. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  973. var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
  974. if (_powerDic != null)
  975. {
  976. foreach (var kv in _powerDic)
  977. {
  978. try
  979. {
  980. string chargeBoxId = string.Empty;
  981. //set profile
  982. lock (_lockClientDic)
  983. {
  984. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  985. }
  986. if (chargeBoxId != null && kv.Value.HasValue)
  987. {
  988. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  989. }
  990. }
  991. catch (Exception ex)
  992. {
  993. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  994. }
  995. }
  996. }
  997. }
  998. if (action == Actions.StopTransaction)
  999. {
  1000. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  1001. if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
  1002. {
  1003. //Clear current profile
  1004. profileHandler.ClearChargingProfile(session.ChargeBoxId);
  1005. var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
  1006. if (_powerDic != null)
  1007. {
  1008. foreach (var kv in _powerDic)
  1009. {
  1010. try
  1011. {
  1012. string chargeBoxId = string.Empty;
  1013. //set profile
  1014. lock (_lockClientDic)
  1015. {
  1016. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  1017. }
  1018. if (chargeBoxId != null && kv.Value.HasValue)
  1019. {
  1020. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  1021. }
  1022. }
  1023. catch (Exception ex)
  1024. {
  1025. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  1026. }
  1027. }
  1028. }
  1029. }
  1030. }
  1031. }
  1032. break;
  1033. case "FirmwareManagement":
  1034. {
  1035. var replyResult = profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  1036. if (replyResult.Success)
  1037. {
  1038. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  1039. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  1040. }
  1041. else
  1042. {
  1043. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1044. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  1045. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1046. }
  1047. }
  1048. break;
  1049. case "Security":
  1050. {
  1051. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  1052. if (replyResult.Success)
  1053. {
  1054. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  1055. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  1056. }
  1057. else
  1058. {
  1059. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1060. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  1061. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1062. }
  1063. }
  1064. break;
  1065. default:
  1066. {
  1067. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1068. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1069. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1070. }
  1071. break;
  1072. }
  1073. }
  1074. }
  1075. async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  1076. {
  1077. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1078. if (ReConfirmMessage(analysisResult))
  1079. {
  1080. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1081. MessageResult confirmResult = null;
  1082. switch (profileName)
  1083. {
  1084. case "Core":
  1085. {
  1086. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1087. }
  1088. break;
  1089. case "FirmwareManagement":
  1090. {
  1091. confirmResult = profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1092. }
  1093. break;
  1094. case "RemoteTrigger":
  1095. {
  1096. confirmResult = profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1097. }
  1098. break;
  1099. case "Reservation":
  1100. {
  1101. confirmResult = profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1102. }
  1103. break;
  1104. case "LocalAuthListManagement":
  1105. {
  1106. confirmResult = profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1107. }
  1108. break;
  1109. case "SmartCharging":
  1110. {
  1111. confirmResult = profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1112. }
  1113. break;
  1114. case "Security":
  1115. {
  1116. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1117. }
  1118. break;
  1119. default:
  1120. {
  1121. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1122. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1123. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1124. }
  1125. break;
  1126. }
  1127. if (confirmResult == null || !confirmResult.Success)
  1128. {
  1129. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  1130. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  1131. }
  1132. }
  1133. else
  1134. {
  1135. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1136. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1137. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1138. }
  1139. }
  1140. private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  1141. {
  1142. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1143. if (ReConfirmMessage(analysisResult))
  1144. {
  1145. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1146. switch (profileName)
  1147. {
  1148. case "Core":
  1149. {
  1150. profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1151. }
  1152. break;
  1153. case "FirmwareManagement":
  1154. {
  1155. profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1156. }
  1157. break;
  1158. case "RemoteTrigger":
  1159. {
  1160. profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1161. }
  1162. break;
  1163. case "Reservation":
  1164. {
  1165. profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1166. }
  1167. break;
  1168. case "LocalAuthListManagement":
  1169. {
  1170. profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1171. }
  1172. break;
  1173. case "SmartCharging":
  1174. {
  1175. profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1176. }
  1177. break;
  1178. default:
  1179. {
  1180. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1181. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1182. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1183. }
  1184. break;
  1185. }
  1186. }
  1187. else
  1188. {
  1189. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1190. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1191. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1192. }
  1193. }
  1194. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  1195. {
  1196. try
  1197. {
  1198. if (session != null)
  1199. {
  1200. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1201. session.Send(msg);
  1202. }
  1203. }
  1204. catch (Exception ex)
  1205. {
  1206. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  1207. }
  1208. }
  1209. async private void ServerUpdateTrigger()
  1210. {
  1211. for (; ; )
  1212. {
  1213. if (_ct.IsCancellationRequested)
  1214. {
  1215. break;
  1216. }
  1217. var min_Interval = (DateTime.UtcNow - checkUpdateDt).TotalMinutes;
  1218. if (min_Interval > 3)
  1219. {
  1220. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1221. Dictionary<string, ClientData> _copyClientDic = null;
  1222. lock (_lockClientDic)
  1223. {
  1224. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1225. }
  1226. checkUpdateDt = DateTime.UtcNow;
  1227. using (var db = maindbContextFactory.CreateDbContext())
  1228. {
  1229. //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  1230. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
  1231. // .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
  1232. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
  1233. x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
  1234. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  1235. foreach (var chargeBoxId in needUpdateChargers)
  1236. {
  1237. try
  1238. {
  1239. ClientData session;
  1240. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  1241. {
  1242. string requestId = Guid.NewGuid().ToString();
  1243. // using (var db = maindbContextFactory.CreateDbContext())
  1244. if (session.IsCheckIn && !session.ISOCPP20)
  1245. {
  1246. var _request = new TriggerMessageRequest()
  1247. {
  1248. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  1249. };
  1250. var uuid = session.queue.store(_request);
  1251. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
  1252. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  1253. #region OCTT ,測試韌體更新方式
  1254. //--------------------> OCTT ,測試韌體更新方式
  1255. //{
  1256. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  1257. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  1258. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  1259. // if (machine != null)
  1260. // {
  1261. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  1262. // .Include(c => c.PublishVersion.PublishVersionFiles)
  1263. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  1264. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  1265. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  1266. // var _updateFWrequest = new UpdateFirmwareRequest()
  1267. // {
  1268. // location = new Uri(downloadUrl),
  1269. // retries = 3,
  1270. // retrieveDate = DateTime.UtcNow,
  1271. // retryInterval = 10
  1272. // };
  1273. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  1274. // {
  1275. // CreatedOn = DateTime.UtcNow,
  1276. // ChargeBoxId = session.ChargeBoxId,
  1277. // SerialNo = requestId,
  1278. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1279. // EVSE_Status = 0,
  1280. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  1281. // Status = 0,
  1282. // RequestType = 0,
  1283. // });
  1284. // db.ServerMessage.Add(new ServerMessage()
  1285. // {
  1286. // ChargeBoxId = session.ChargeBoxId,
  1287. // CreatedBy = "Server",
  1288. // CreatedOn = DateTime.UtcNow,
  1289. // OutAction = _updateFWrequest.Action.ToString(),
  1290. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1291. // SerialNo = requestId,
  1292. // InMessage = string.Empty
  1293. // });
  1294. // db.SaveChanges();
  1295. // }
  1296. //}
  1297. #endregion
  1298. }
  1299. }
  1300. }
  1301. catch (Exception ex)
  1302. {
  1303. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  1304. }
  1305. }
  1306. }
  1307. await Task.Delay(1000);
  1308. // Thread.CurrentThread.Join(1000);
  1309. }
  1310. }
  1311. }
  1312. //string webConnectionString = ConfigurationManager.ConnectionStrings["WebDBContext"].ConnectionString;
  1313. async private void ServerMessageTrigger()
  1314. {
  1315. for (; ; )
  1316. {
  1317. if (_ct.IsCancellationRequested)
  1318. {
  1319. break;
  1320. }
  1321. try
  1322. {
  1323. RemoveConfirmMessage();
  1324. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1325. using (var db = maindbContextFactory.CreateDbContext())
  1326. {
  1327. DateTime startDt = DateTime.UtcNow.AddSeconds(-30);
  1328. DateTime dt = new DateTime(1991, 1, 1);
  1329. DateTime currentTime = DateTime.UtcNow;
  1330. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= currentTime).AsNoTracking().ToList();
  1331. //處理主機傳送的有指令
  1332. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  1333. if (commandList.Count > 0)
  1334. {
  1335. // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  1336. }
  1337. var resendList = GetResendMessage();
  1338. foreach (var resendItem in resendList)
  1339. {
  1340. ClientData session;
  1341. if (clientDic.TryGetValue(resendItem.ChargePointSerialNumber, out session))
  1342. {
  1343. if (DateTime.UtcNow.Subtract(resendItem.SentOn).TotalSeconds > 1)
  1344. {
  1345. resendItem.SentTimes--;
  1346. resendItem.SentOn = DateTime.UtcNow;
  1347. Send(session, resendItem.SentMessage, string.Format("{0} {1}", resendItem.SentAction, "Request"), "");
  1348. }
  1349. }
  1350. }
  1351. foreach (var charger_SN in cmdMachineList)
  1352. {
  1353. ClientData session;
  1354. string uuid = string.Empty;
  1355. if (clientDic.TryGetValue(charger_SN, out session))
  1356. {
  1357. //logger.LogDebug(string.Format("charger_SN:{0} startDt:{1} CreatedOn:{2}", charger_SN, startDt.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss")));
  1358. if (session.IsCheckIn && !session.ISOCPP20)
  1359. {
  1360. string rawRequest = string.Empty;
  1361. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  1362. foreach (var item in cmdList)
  1363. {
  1364. IRequest request = null;
  1365. Actions action = Actions.None;
  1366. Enum.TryParse(item.OutAction, out action);
  1367. Type _RequestType = null;
  1368. for (int i = 0; i < profiles.Count; i++)
  1369. {
  1370. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  1371. if (feature != null)
  1372. {
  1373. _RequestType = feature.GetRequestType();
  1374. break;
  1375. }
  1376. }
  1377. if (_RequestType != null && item.CreatedBy != "Destroyer")
  1378. {
  1379. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  1380. uuid = session.queue.store(request);
  1381. rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
  1382. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1383. }
  1384. if (item.CreatedBy == "Destroyer")
  1385. {
  1386. if (_RequestType != null)
  1387. {
  1388. request = Activator.CreateInstance(_RequestType) as IRequest;
  1389. uuid = session.queue.store(request);
  1390. rawRequest = BasicMessageHandler.GenerateDestroyRequest(uuid, item.OutAction, item.OutRequest);
  1391. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1392. }
  1393. else
  1394. {
  1395. rawRequest = BasicMessageHandler.GenerateDestroyRequest(Guid.NewGuid().ToString(), item.OutAction, item.OutRequest);
  1396. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1397. }
  1398. }
  1399. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid, item.CreatedBy, rawRequest);
  1400. #region 更新資料表單一欄位
  1401. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.UtcNow };
  1402. //db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  1403. //db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  1404. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  1405. db.ServerMessage.Attach(_UpdatedItem);
  1406. _UpdatedItem.UpdatedOn = DateTime.UtcNow;
  1407. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  1408. db.SaveChanges();
  1409. #endregion
  1410. await Task.Delay(100);
  1411. }
  1412. }
  1413. }
  1414. }
  1415. }
  1416. await Task.Delay(500);
  1417. }
  1418. catch (Exception ex)
  1419. {
  1420. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  1421. }
  1422. }
  1423. }
  1424. async private void HeartBeatCheckTrigger()
  1425. {
  1426. for (; ; )
  1427. {
  1428. if (_ct.IsCancellationRequested)
  1429. {
  1430. break;
  1431. }
  1432. try
  1433. {
  1434. if (DateTime.UtcNow.Subtract(lastcheckdt).TotalSeconds > 30)
  1435. {
  1436. lastcheckdt = DateTime.UtcNow;
  1437. Stopwatch watch = new Stopwatch();
  1438. Dictionary<string, ClientData> _copyClientDic = null;
  1439. lock (_lockClientDic)
  1440. {
  1441. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1442. }
  1443. var cdt = DateTime.UtcNow;
  1444. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-120)).Select(x => x.Value).ToList();
  1445. watch.Start();
  1446. foreach (var session in clients)
  1447. {
  1448. using (var db = maindbContextFactory.CreateDbContext())
  1449. {
  1450. var machine = new Machine() { Id = session.MachineId };
  1451. if (machine != null)
  1452. {
  1453. //db.Configuration.AutoDetectChangesEnabled = false;
  1454. //db.Configuration.ValidateOnSaveEnabled = false;
  1455. db.Machine.Attach(machine);
  1456. machine.HeartbeatUpdatedOn = DateTime.UtcNow;
  1457. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  1458. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  1459. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  1460. await db.SaveChangesAsync();
  1461. }
  1462. }
  1463. }
  1464. watch.Stop();
  1465. if (watch.ElapsedMilliseconds / 1000 > 5)
  1466. {
  1467. logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  1468. }
  1469. }
  1470. await Task.Delay(10000);
  1471. }
  1472. catch (Exception ex)
  1473. {
  1474. Console.WriteLine("***********************************************************");
  1475. logger.Error(string.Format("HeartBeatCheckTrigger Ex:{0}", ex.ToString()));
  1476. }
  1477. }
  1478. }
  1479. async private void ServerWeatherNotificationTrigger()
  1480. {
  1481. for (; ; )
  1482. {
  1483. if (_ct.IsCancellationRequested)
  1484. {
  1485. break;
  1486. }
  1487. var min_Interval = (DateTime.UtcNow - _CheckWeatherDt).TotalMinutes;
  1488. if (min_Interval > 30)
  1489. {
  1490. // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
  1491. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1492. Dictionary<string, ClientData> _copyClientDic = null;
  1493. lock (_lockClientDic)
  1494. {
  1495. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1496. }
  1497. _CheckWeatherDt = DateTime.UtcNow;
  1498. var locations = _copyClientDic.Where(x => !string.IsNullOrEmpty(x.Value.StationLocation)).Distinct().Select(x => x.Value.StationLocation).ToList();
  1499. // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
  1500. foreach (var location in locations)
  1501. {
  1502. try
  1503. { //query weather
  1504. var httpResult = await httpClient.GetWeather("https://api.weatherapi.com/v1/current.json?key=874346abc0874e69a9423510222201&q=" + location, null, null);
  1505. string temp = "17";
  1506. string weather_code = "1183";
  1507. if (httpResult.Status == System.Net.HttpStatusCode.OK)
  1508. {
  1509. try
  1510. {
  1511. var jsonResult = JsonConvert.DeserializeObject(httpResult.Response) as JObject;
  1512. temp = jsonResult["current"]["temp_c"].ToString();
  1513. weather_code = jsonResult["current"]["condition"]["code"].ToString();
  1514. }
  1515. catch (Exception ex)
  1516. {
  1517. ;
  1518. }
  1519. }
  1520. #region 台泥氣象Mapping
  1521. switch (weather_code)
  1522. {
  1523. case "1000":
  1524. weather_code = "1";
  1525. break;
  1526. case "1003":
  1527. case "1006":
  1528. case "1009":
  1529. weather_code = "2";
  1530. break;
  1531. case "1063":
  1532. case "1072":
  1533. case "1150":
  1534. case "1153":
  1535. case "1168":
  1536. case "1171":
  1537. case "1180":
  1538. case "1183":
  1539. case "1186":
  1540. case "1189":
  1541. case "1192":
  1542. case "1195":
  1543. case "1198":
  1544. case "1201":
  1545. case "1237":
  1546. case "1240":
  1547. case "1243":
  1548. case "1246":
  1549. case "1261":
  1550. case "1264":
  1551. weather_code = "3";
  1552. break;
  1553. case "1087":
  1554. case "1273":
  1555. case "1276":
  1556. case "1279":
  1557. case "1282":
  1558. weather_code = "4";
  1559. break;
  1560. case "1066":
  1561. case "1069":
  1562. case "1114":
  1563. case "1117":
  1564. case "1204":
  1565. case "1207":
  1566. case "1210":
  1567. case "1213":
  1568. case "1216":
  1569. case "1219":
  1570. case "1222":
  1571. case "1225":
  1572. case "1249":
  1573. case "1252":
  1574. case "1255":
  1575. case "1258":
  1576. weather_code = "5";
  1577. break;
  1578. case "1030":
  1579. case "1135":
  1580. case "1147":
  1581. weather_code = "2";
  1582. break;
  1583. default:
  1584. weather_code = "2";
  1585. break;
  1586. }
  1587. #endregion
  1588. if (TCCStationDic.ContainsKey(location))
  1589. {
  1590. TCCStationDic[location].Temperature = (int)double.Parse(temp);
  1591. TCCStationDic[location].WeatherID = int.Parse(weather_code);
  1592. }
  1593. else
  1594. {
  1595. TCCStationDic.Add(location, new TCCWeatherDto() { WeatherID = int.Parse(weather_code), Temperature = (int)double.Parse(temp) });
  1596. }
  1597. }
  1598. catch (Exception ex)
  1599. {
  1600. logger.Error(string.Format("ServerWeatherNotificationTrigger ChargeBoxId:{0} Ex:{1}", location, ex.ToString()));
  1601. }
  1602. }
  1603. var clients = _copyClientDic.Where(x => x.Value.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8")).
  1604. Select(x => new { ChargeBoxId = x.Value.ChargeBoxId, StationLocation = x.Value.StationLocation }).ToList();
  1605. using (var db = maindbContextFactory.CreateDbContext())
  1606. {
  1607. foreach (var client in clients)
  1608. {
  1609. try
  1610. {
  1611. if (string.IsNullOrEmpty(client.StationLocation))
  1612. {
  1613. Console.WriteLine(client.StationLocation + " is empty");
  1614. continue;
  1615. }
  1616. if (TCCStationDic.ContainsKey(client.StationLocation))
  1617. {
  1618. db.ServerMessage.Add(new ServerMessage()
  1619. {
  1620. ChargeBoxId = client.ChargeBoxId,
  1621. CreatedBy = "Server",
  1622. CreatedOn = DateTime.UtcNow,
  1623. OutAction = Actions.DataTransfer.ToString(),
  1624. OutRequest = JsonConvert.SerializeObject(
  1625. new DataTransferRequest()
  1626. {
  1627. messageId = "ID_Weather_Info",
  1628. vendorId = "Phihong Technology",
  1629. data = JsonConvert.SerializeObject(
  1630. new
  1631. {
  1632. weatherId = TCCStationDic[client.StationLocation].WeatherID,
  1633. Temperature = TCCStationDic[client.StationLocation].Temperature
  1634. })
  1635. },
  1636. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1637. SerialNo = Guid.NewGuid().ToString(),
  1638. InMessage = string.Empty
  1639. });
  1640. await db.SaveChangesAsync();
  1641. }
  1642. }
  1643. catch (Exception ex)
  1644. {
  1645. logger.Error(string.Format("ServerWeatherNotificationTrigger ChargeBoxId:{0} Ex:{1}", client.ChargeBoxId, ex.ToString()));
  1646. }
  1647. }
  1648. }
  1649. }
  1650. await Task.Delay(1000);
  1651. }
  1652. }
  1653. async private void ServerSetFeeTrigger()
  1654. {
  1655. for (; ; )
  1656. {
  1657. if (_ct.IsCancellationRequested)
  1658. {
  1659. break;
  1660. }
  1661. var min_Interval = (DateTime.UtcNow - _CheckFeeDt).TotalMinutes;
  1662. if (min_Interval > 1)
  1663. {
  1664. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1665. Dictionary<string, ClientData> _copyClientDic = null;
  1666. lock (_lockClientDic)
  1667. {
  1668. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1669. }
  1670. _CheckFeeDt = DateTime.UtcNow;
  1671. foreach (var item in _copyClientDic)
  1672. {
  1673. try
  1674. {
  1675. ClientData session = item.Value;
  1676. if (session.IsCheckIn)
  1677. {
  1678. string displayPriceText = await SetDefaultFee(session);
  1679. if (!string.IsNullOrEmpty(displayPriceText) && displayPriceText != session.DisplayPrice)
  1680. {
  1681. clientDic[item.Key].DisplayPrice = displayPriceText;
  1682. using (var db = maindbContextFactory.CreateDbContext())
  1683. {
  1684. db.ServerMessage.Add(new ServerMessage()
  1685. {
  1686. ChargeBoxId = session.ChargeBoxId,
  1687. CreatedBy = "Server",
  1688. CreatedOn = DateTime.UtcNow,
  1689. OutAction = Actions.ChangeConfiguration.ToString(),
  1690. OutRequest = JsonConvert.SerializeObject(
  1691. new ChangeConfigurationRequest()
  1692. {
  1693. key = "DefaultPrice",
  1694. value = clientDic[item.Key].DisplayPrice
  1695. },
  1696. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1697. SerialNo = Guid.NewGuid().ToString(),
  1698. InMessage = string.Empty
  1699. }); ;
  1700. if (session.CustomerId == new Guid("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
  1701. {
  1702. db.ServerMessage.Add(new ServerMessage()
  1703. {
  1704. ChargeBoxId = session.ChargeBoxId,
  1705. CreatedBy = "Server",
  1706. CreatedOn = DateTime.UtcNow,
  1707. OutAction = Actions.ChangeConfiguration.ToString(),
  1708. OutRequest = JsonConvert.SerializeObject(
  1709. new ChangeConfigurationRequest()
  1710. {
  1711. key = "ConnectionTimeOut",
  1712. value = "120"
  1713. },
  1714. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1715. SerialNo = Guid.NewGuid().ToString(),
  1716. InMessage = string.Empty
  1717. });
  1718. db.ServerMessage.Add(new ServerMessage()
  1719. {
  1720. ChargeBoxId = session.ChargeBoxId,
  1721. CreatedBy = "Server",
  1722. CreatedOn = DateTime.UtcNow,
  1723. OutAction = Actions.ChangeConfiguration.ToString(),
  1724. OutRequest = JsonConvert.SerializeObject(
  1725. new ChangeConfigurationRequest()
  1726. {
  1727. key = "MeterValueSampleInterval",
  1728. value = "3"
  1729. },
  1730. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1731. SerialNo = Guid.NewGuid().ToString(),
  1732. InMessage = string.Empty
  1733. });
  1734. }
  1735. await db.SaveChangesAsync();
  1736. }
  1737. }
  1738. }
  1739. }
  1740. catch (Exception ex)
  1741. {
  1742. logger.Error(string.Format("ServerSetFeeTrigger ChargeBoxId:{0} Ex:{1}", item.Key, ex.ToString()));
  1743. }
  1744. }
  1745. }
  1746. await Task.Delay(1000);
  1747. }
  1748. }
  1749. async private Task<string> SetDefaultFee(ClientData client)
  1750. {
  1751. string displayPriceText = string.Empty;
  1752. string charingPriceText = string.Empty;
  1753. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1754. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1755. {
  1756. var parameters = new DynamicParameters();
  1757. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input);
  1758. string displayPricestrSql = "";
  1759. string strSql = "";
  1760. if (client.IsAC)
  1761. {
  1762. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1763. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1764. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1765. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1766. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1767. }
  1768. else
  1769. {
  1770. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1771. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1772. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1773. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1774. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1775. }
  1776. var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1777. if (result.Count() == 0)
  1778. {
  1779. return string.Empty;
  1780. }
  1781. var stationPrice = result.First();
  1782. if (stationPrice.BillingMethod == 1)
  1783. {
  1784. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1785. client.ChargingPrices = chargingPriceResult.ToList();
  1786. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1787. {
  1788. client.ChargingPrices = new List<ChargingPrice>();
  1789. }
  1790. }
  1791. displayPriceText = stationPrice.FeeName;
  1792. client.BillingMethod = stationPrice.BillingMethod;
  1793. client.Currency = stationPrice.Currency;
  1794. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1795. client.ParkingFee = stationPrice.ParkingFee;
  1796. client.IsBilling = true;
  1797. }
  1798. return displayPriceText;
  1799. }
  1800. async private void HealthCheckTrigger()
  1801. {
  1802. for (; ; )
  1803. {
  1804. if (_ct.IsCancellationRequested)
  1805. {
  1806. break;
  1807. }
  1808. try
  1809. {
  1810. Dictionary<string, ClientData> _copyClientDic = null;
  1811. lock (_lockClientDic)
  1812. {
  1813. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1814. }
  1815. var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.UtcNow.AddSeconds(-300)).Select(x => x.Value).ToList();
  1816. foreach (var session in removeClients)
  1817. {
  1818. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
  1819. RemoveClient(session);
  1820. }
  1821. await Task.Delay(60000);
  1822. }
  1823. catch (Exception ex)
  1824. {
  1825. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  1826. }
  1827. }
  1828. }
  1829. private List<NeedConfirmMessage> GetResendMessage()
  1830. {
  1831. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  1832. lock (_lockConfirmPacketList)
  1833. {
  1834. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  1835. }
  1836. return sendMessages;
  1837. }
  1838. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1839. {
  1840. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1841. _needConfirmMsg.Id = table_id;
  1842. _needConfirmMsg.SentAction = action;
  1843. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1844. _needConfirmMsg.SentTimes = 4;
  1845. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1846. _needConfirmMsg.RequestId = requestId;
  1847. _needConfirmMsg.SentUniqueId = msg_id;
  1848. _needConfirmMsg.CreatedBy = createdBy;
  1849. _needConfirmMsg.SentMessage = sendMessage;
  1850. if (needConfirmActions.Contains(action))
  1851. {
  1852. lock (_lockConfirmPacketList)
  1853. {
  1854. needConfirmPacketList.Add(_needConfirmMsg);
  1855. }
  1856. }
  1857. }
  1858. private void RemoveConfirmMessage()
  1859. {
  1860. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1861. lock (_lockConfirmPacketList)
  1862. {
  1863. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1864. foreach (var item in removeList)
  1865. {
  1866. needConfirmPacketList.Remove(item);
  1867. }
  1868. }
  1869. }
  1870. private bool ReConfirmMessage(MessageResult analysisResult)
  1871. {
  1872. bool confirmed = false;
  1873. if (needConfirmActions.Contains(analysisResult.Action))
  1874. {
  1875. NeedConfirmMessage foundRequest = null;
  1876. lock (_lockConfirmPacketList)
  1877. {
  1878. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1879. }
  1880. if (foundRequest != null && foundRequest.Id > 0)
  1881. {
  1882. foundRequest.SentTimes = 0;
  1883. foundRequest.SentInterval = 0;
  1884. analysisResult.RequestId = foundRequest.RequestId;
  1885. using (var db = maindbContextFactory.CreateDbContext())
  1886. {
  1887. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  1888. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1889. sc.ReceivedOn = DateTime.UtcNow;
  1890. db.SaveChanges();
  1891. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1892. }
  1893. confirmed = true;
  1894. }
  1895. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1896. {
  1897. confirmed = true;
  1898. }
  1899. else
  1900. {
  1901. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1902. }
  1903. }
  1904. return confirmed;
  1905. }
  1906. private void RemoveClient(ClientData session)
  1907. {
  1908. if (session != null)
  1909. {
  1910. if (!string.IsNullOrEmpty(session.MachineId))
  1911. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1912. if (session.Connected)
  1913. {
  1914. session.Close(CloseReason.ServerShutdown);
  1915. }
  1916. RemoveClientDic(session);
  1917. try
  1918. {
  1919. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1920. // session.Close(CloseReason.ServerShutdown);
  1921. }
  1922. catch (Exception ex)
  1923. {
  1924. //logger.LogWarning("Close client socket error!!");
  1925. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1926. }
  1927. if (session != null)
  1928. {
  1929. session = null;
  1930. }
  1931. }
  1932. }
  1933. private void RemoveClientDic(ClientData session)
  1934. {
  1935. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  1936. {
  1937. lock (_lockClientDic)
  1938. {
  1939. if (clientDic.ContainsKey(session.ChargeBoxId))
  1940. {
  1941. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1942. {
  1943. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1944. clientDic.Remove(session.ChargeBoxId);
  1945. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1946. }
  1947. }
  1948. }
  1949. }
  1950. }
  1951. private void WarmUpLog()
  1952. {
  1953. try
  1954. {
  1955. using (var log = serviceProvider.GetService<IDbContextFactory<ConnectionLogDBContext>>().CreateDbContext())
  1956. {
  1957. log.MachineConnectionLog.ToList();
  1958. }
  1959. }
  1960. catch (Exception ex)
  1961. {
  1962. Console.WriteLine(ex.ToString());
  1963. }
  1964. }
  1965. private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1966. {
  1967. try
  1968. {
  1969. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1970. if (clientData.ChargeBoxId == null)
  1971. {
  1972. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1973. }
  1974. using (var db = serviceProvider.GetService<IDbContextFactory<ConnectionLogDBContext>>().CreateDbContext())
  1975. {
  1976. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  1977. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  1978. var dd = DateTime.UtcNow;
  1979. SqlParameter[] parameter =
  1980. {
  1981. new SqlParameter("CreatedOn",dd),
  1982. new SqlParameter("ChargeBoxId",clientData.ChargeBoxId==null?"unknown":clientData.ChargeBoxId.Replace("'","''")),
  1983. new SqlParameter("MessageType",messageType.Replace("'","''")),
  1984. new SqlParameter("Data",data.Replace("'","''")),
  1985. new SqlParameter("Msg",errorMsg.Replace("'","''")),
  1986. new SqlParameter("IsSent",isSent),
  1987. new SqlParameter("EVSEEndPoint",clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()),
  1988. new SqlParameter("Session",clientData.SessionID==null?"123":clientData.SessionID)
  1989. };
  1990. db.Database.ExecuteSqlRaw(sp, parameter);
  1991. }
  1992. }
  1993. catch (Exception ex)
  1994. {
  1995. Console.WriteLine(ex.ToString());
  1996. }
  1997. }
  1998. }
  1999. }