ProtalServer.cs 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362
  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 async void CheckVersion(string chargeBoxId)
  392. {
  393. if (string.IsNullOrEmpty(chargeBoxId)) return;
  394. using (var db = await maindbContextFactory.CreateDbContextAsync())
  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. await db.SaveChangesAsync();
  413. }
  414. }
  415. private async void CheckEVSEConfigure(string chargeBoxId)
  416. {
  417. if (string.IsNullOrEmpty(chargeBoxId)) return;
  418. using (var db = await maindbContextFactory.CreateDbContextAsync())
  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. await db.SaveChangesAsync();
  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. SendingQueueSize = 10,
  482. //Port = Convert.ToInt32(2012),
  483. //Ip = "172.17.40.13",
  484. MaxRequestLength = 204800,
  485. //Security = serverSecurity,
  486. Certificate = Certificate,
  487. Listeners = listeners,
  488. // LogAllSocketException = true,
  489. KeepAliveTime = 10,
  490. // LogBasicSessionActivity = true
  491. };
  492. //Setup with listening port
  493. if (!appServer.Setup(serverConfig, logFactory: new NLogLoggerFactory()))
  494. {
  495. Console.WriteLine("Failed to setup!");
  496. return;
  497. }
  498. appServer.NewSessionConnected += AppServer_NewSessionConnected;
  499. appServer.SessionClosed += AppServer_SessionClosed;
  500. //Try to start the appServer
  501. if (!appServer.Start())
  502. {
  503. Console.WriteLine("Failed to start!");
  504. //Console.ReadKey();
  505. return;
  506. }
  507. }
  508. private void AppServer_SessionClosed(ClientData session, CloseReason value)
  509. {
  510. WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
  511. RemoveClient(session);
  512. }
  513. private void AppServer_NewSessionConnected(ClientData session)
  514. {
  515. logger.Debug(string.Format("{0} NewSessionConnected", session.Path));
  516. try
  517. {
  518. lock (_lockClientDic)
  519. {
  520. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  521. if (isNotSupported)
  522. {
  523. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  524. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  525. return;
  526. }
  527. ClientData _removeClient = null;
  528. clientDic.TryGetValue(session.ChargeBoxId, out _removeClient);
  529. if (_removeClient != null)
  530. {
  531. WriteMachineLog(_removeClient, "Duplicate Logins", "Connection", "");
  532. _removeClient.Close(CloseReason.ServerShutdown);
  533. RemoveClient(_removeClient);
  534. }
  535. clientDic.Add(session.ChargeBoxId, session);
  536. session.m_ReceiveData += new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  537. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  538. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  539. using (var db = maindbContextFactory.CreateDbContext())
  540. {
  541. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  542. if (machine != null)
  543. {
  544. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  545. db.SaveChanges();
  546. }
  547. }
  548. }
  549. }
  550. catch (Exception ex)
  551. {
  552. logger.Error(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  553. }
  554. }
  555. async private void ReceivedMessage(ClientData session, string rawdata)
  556. {
  557. try
  558. {
  559. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  560. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  561. WriteMachineLog(session, rawdata,
  562. 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);
  563. if (session.ResetSecurityProfile)
  564. {
  565. logger.Error(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  566. RemoveClient(session);
  567. return;
  568. }
  569. if (!analysisResult.Success)
  570. {
  571. //解析RawData就發生錯誤
  572. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  573. {
  574. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  575. }
  576. else
  577. {
  578. if (analysisResult.Message == null)
  579. {
  580. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  581. string errorMsg = string.Empty;
  582. if (analysisResult.Exception != null)
  583. {
  584. errorMsg = analysisResult.Exception.ToString();
  585. }
  586. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  587. }
  588. else
  589. {
  590. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  591. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  592. string errorMsg = string.Empty;
  593. if (analysisResult.Exception != null)
  594. {
  595. errorMsg = analysisResult.Exception.ToString();
  596. }
  597. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  598. }
  599. }
  600. }
  601. else
  602. {
  603. switch (analysisResult.Id)
  604. {
  605. case BasicMessageHandler.TYPENUMBER_CALL:
  606. {
  607. if (!session.ISOCPP20)
  608. {
  609. Actions action = Convertor.GetAction(analysisResult.Action);
  610. ProcessRequestMessage(analysisResult, session, action);
  611. }
  612. else
  613. {
  614. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  615. MessageResult result = new MessageResult() { Success = true };
  616. //ocpp20 處理
  617. switch (action)
  618. {
  619. case EVCB_OCPP20.Packet.Features.Actions.BootNotification:
  620. {
  621. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  622. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  623. result.Message = confirm;
  624. result.Success = true;
  625. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  626. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  627. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  628. {
  629. ConfigurationSlot = 1,
  630. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  631. {
  632. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  633. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  634. MessageTimeout = 30,
  635. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  636. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  637. }
  638. };
  639. var uuid = session.queue20.store(request);
  640. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  641. Send(session, requestText, "SetNetworkProfile");
  642. }
  643. break;
  644. default:
  645. {
  646. logger.Error(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  647. }
  648. break;
  649. }
  650. }
  651. }
  652. break;
  653. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  654. {
  655. if (!session.ISOCPP20)
  656. {
  657. Actions action = Convertor.GetAction(analysisResult.Action);
  658. ProcessConfirmationMessage(analysisResult, session, action);
  659. }
  660. else
  661. {
  662. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  663. MessageResult result = new MessageResult() { Success = true };
  664. //ocpp20 處理
  665. switch (action)
  666. {
  667. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  668. {
  669. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  670. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  671. {
  672. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  673. {
  674. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  675. {
  676. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  677. {
  678. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  679. {
  680. Name="OCPPCommCtrlr",
  681. },
  682. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  683. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  684. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  685. {
  686. Name="NetworkConfigurationPriority",
  687. }
  688. }
  689. }
  690. };
  691. var uuid = session.queue20.store(request);
  692. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  693. Send(session, requestText, "SetVariables");
  694. }
  695. }
  696. break;
  697. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  698. {
  699. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  700. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  701. {
  702. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  703. {
  704. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  705. };
  706. var uuid = session.queue20.store(request);
  707. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  708. Send(session, requestText, "Reset");
  709. }
  710. }
  711. break;
  712. default:
  713. {
  714. logger.Error(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  715. }
  716. break;
  717. }
  718. }
  719. }
  720. break;
  721. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  722. {
  723. //只處理 丟出Request 收到Error的訊息
  724. if (analysisResult.Success && analysisResult.Message != null)
  725. {
  726. Actions action = Convertor.GetAction(analysisResult.Action);
  727. ProcessErrorMessage(analysisResult, session, action);
  728. }
  729. }
  730. break;
  731. default:
  732. {
  733. logger.Error(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  734. }
  735. break;
  736. }
  737. }
  738. await Task.Delay(10);
  739. }
  740. catch (Exception ex)
  741. {
  742. if (ex.InnerException != null)
  743. {
  744. logger.Error(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  745. }
  746. else
  747. {
  748. logger.Error(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  749. }
  750. }
  751. }
  752. async private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
  753. {
  754. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  755. if (!session.IsCheckIn && action != Actions.BootNotification)
  756. {
  757. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  758. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  759. }
  760. else
  761. {
  762. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  763. switch (profileName)
  764. {
  765. case "Core":
  766. {
  767. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  768. if (replyResult.Success)
  769. {
  770. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  771. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString());
  772. if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
  773. {
  774. session.IsCheckIn = true;
  775. if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  776. {
  777. CheckVersion(session.ChargeBoxId);
  778. CheckEVSEConfigure(session.ChargeBoxId);
  779. if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
  780. {
  781. using (var db = await maindbContextFactory.CreateDbContextAsync())
  782. {
  783. db.ServerMessage.Add(new ServerMessage()
  784. {
  785. ChargeBoxId = session.ChargeBoxId,
  786. CreatedBy = "Server",
  787. CreatedOn = DateTime.UtcNow,
  788. OutAction = Actions.ChangeConfiguration.ToString(),
  789. OutRequest = JsonConvert.SerializeObject(
  790. new ChangeConfigurationRequest()
  791. {
  792. key = "TimeOffset",
  793. value = "+08:00"
  794. },
  795. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  796. SerialNo = Guid.NewGuid().ToString(),
  797. InMessage = string.Empty
  798. });
  799. await db.SaveChangesAsync();
  800. }
  801. }
  802. if (session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  803. {
  804. var stationInfo = await GetStationInfo(session.MachineId);
  805. if (stationInfo != null)
  806. {
  807. session.StationLocation = string.Format("{0},{1}", stationInfo.Lat, stationInfo.Long);
  808. session.StationName = stationInfo.ZipCode;
  809. }
  810. using (var db = await maindbContextFactory.CreateDbContextAsync())
  811. {
  812. db.ServerMessage.Add(new ServerMessage()
  813. {
  814. ChargeBoxId = session.ChargeBoxId,
  815. CreatedBy = "Server",
  816. CreatedOn = DateTime.UtcNow,
  817. OutAction = Actions.DataTransfer.ToString(),
  818. OutRequest = JsonConvert.SerializeObject(
  819. new DataTransferRequest()
  820. {
  821. messageId = "ID_Station_Location",
  822. vendorId = "Phihong Technology",
  823. data = JsonConvert.SerializeObject(new { stationName = session.StationName })
  824. },
  825. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  826. SerialNo = Guid.NewGuid().ToString(),
  827. InMessage = string.Empty
  828. });
  829. db.ServerMessage.Add(new ServerMessage()
  830. {
  831. ChargeBoxId = session.ChargeBoxId,
  832. CreatedBy = "Server",
  833. CreatedOn = DateTime.UtcNow,
  834. OutAction = Actions.ChangeConfiguration.ToString(),
  835. OutRequest = JsonConvert.SerializeObject(
  836. new ChangeConfigurationRequest()
  837. {
  838. key = "TimeOffset",
  839. value = "+08:00"
  840. },
  841. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  842. SerialNo = Guid.NewGuid().ToString(),
  843. InMessage = string.Empty
  844. });
  845. if (!TCCStationDic.ContainsKey(session.StationLocation))
  846. {
  847. _CheckWeatherDt = DateTime.UtcNow.AddDays(-1);
  848. }
  849. else
  850. {
  851. db.ServerMessage.Add(new ServerMessage()
  852. {
  853. ChargeBoxId = session.ChargeBoxId,
  854. CreatedBy = "Server",
  855. CreatedOn = DateTime.UtcNow,
  856. OutAction = Actions.DataTransfer.ToString(),
  857. OutRequest = JsonConvert.SerializeObject(
  858. new DataTransferRequest()
  859. {
  860. messageId = "ID_Weather_Info",
  861. vendorId = "Phihong Technology",
  862. data = JsonConvert.SerializeObject(
  863. new
  864. {
  865. weatherId = TCCStationDic[session.StationLocation].WeatherID,
  866. Temperature = TCCStationDic[session.StationLocation].Temperature
  867. })
  868. },
  869. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  870. SerialNo = Guid.NewGuid().ToString(),
  871. InMessage = string.Empty
  872. });
  873. }
  874. await db.SaveChangesAsync();
  875. }
  876. }
  877. }
  878. else
  879. {
  880. using (var db = await maindbContextFactory.CreateDbContextAsync())
  881. {
  882. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  883. if (machine != null)
  884. {
  885. if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
  886. {
  887. session.IsAC = false;
  888. }
  889. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  890. await db.SaveChangesAsync();
  891. }
  892. }
  893. await SetDefaultFee(session);
  894. }
  895. }
  896. #region 台泥
  897. if (action == Actions.StartTransaction && session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8") && replyResult.Message is StartTransactionConfirmation)
  898. {
  899. StartTransactionConfirmation confirm = (StartTransactionConfirmation)replyResult.Message;
  900. StartTransactionRequest request = (StartTransactionRequest)analysisResult.Message;
  901. using (var db = await maindbContextFactory.CreateDbContextAsync())
  902. {
  903. db.ServerMessage.Add(new ServerMessage()
  904. {
  905. ChargeBoxId = session.ChargeBoxId,
  906. CreatedBy = "Server",
  907. CreatedOn = DateTime.UtcNow,
  908. OutAction = Actions.DataTransfer.ToString(),
  909. OutRequest = JsonConvert.SerializeObject(
  910. new DataTransferRequest()
  911. {
  912. messageId = "ID_GetTxUserInfo",
  913. vendorId = "Phihong Technology",
  914. data = JsonConvert.SerializeObject(new { txId = confirm.transactionId, ConnectorId = request.connectorId })
  915. },
  916. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  917. SerialNo = Guid.NewGuid().ToString(),
  918. InMessage = string.Empty
  919. });
  920. await db.SaveChangesAsync();
  921. }
  922. }
  923. #endregion
  924. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  925. {
  926. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  927. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  928. {
  929. using (var db = await maindbContextFactory.CreateDbContextAsync())
  930. {
  931. db.ServerMessage.Add(new ServerMessage()
  932. {
  933. ChargeBoxId = session.ChargeBoxId,
  934. CreatedBy = "Server",
  935. CreatedOn = DateTime.UtcNow,
  936. OutAction = Actions.DataTransfer.ToString(),
  937. OutRequest = JsonConvert.SerializeObject(
  938. new DataTransferRequest()
  939. {
  940. messageId = "SetUserPrice",
  941. vendorId = "Phihong Technology",
  942. data = JsonConvert.SerializeObject(
  943. new
  944. {
  945. idToken = authorizeRequest.idTag,
  946. price = session.UserDisplayPrices[authorizeRequest.idTag]
  947. })
  948. },
  949. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  950. SerialNo = Guid.NewGuid().ToString(),
  951. InMessage = string.Empty
  952. });
  953. await db.SaveChangesAsync();
  954. }
  955. }
  956. }
  957. }
  958. else
  959. {
  960. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  961. {
  962. //do nothing
  963. }
  964. else
  965. {
  966. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  967. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  968. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  969. }
  970. }
  971. if (action == Actions.StartTransaction)
  972. {
  973. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  974. var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
  975. if (_powerDic != null)
  976. {
  977. foreach (var kv in _powerDic)
  978. {
  979. try
  980. {
  981. string chargeBoxId = string.Empty;
  982. //set profile
  983. lock (_lockClientDic)
  984. {
  985. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  986. }
  987. if (chargeBoxId != null && kv.Value.HasValue)
  988. {
  989. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  990. }
  991. }
  992. catch (Exception ex)
  993. {
  994. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  995. }
  996. }
  997. }
  998. }
  999. if (action == Actions.StopTransaction)
  1000. {
  1001. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  1002. if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
  1003. {
  1004. //Clear current profile
  1005. profileHandler.ClearChargingProfile(session.ChargeBoxId);
  1006. var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
  1007. if (_powerDic != null)
  1008. {
  1009. foreach (var kv in _powerDic)
  1010. {
  1011. try
  1012. {
  1013. string chargeBoxId = string.Empty;
  1014. //set profile
  1015. lock (_lockClientDic)
  1016. {
  1017. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  1018. }
  1019. if (chargeBoxId != null && kv.Value.HasValue)
  1020. {
  1021. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  1022. }
  1023. }
  1024. catch (Exception ex)
  1025. {
  1026. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  1027. }
  1028. }
  1029. }
  1030. }
  1031. }
  1032. }
  1033. break;
  1034. case "FirmwareManagement":
  1035. {
  1036. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  1037. if (replyResult.Success)
  1038. {
  1039. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  1040. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  1041. }
  1042. else
  1043. {
  1044. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1045. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  1046. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1047. }
  1048. }
  1049. break;
  1050. case "Security":
  1051. {
  1052. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  1053. if (replyResult.Success)
  1054. {
  1055. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  1056. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  1057. }
  1058. else
  1059. {
  1060. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1061. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  1062. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1063. }
  1064. }
  1065. break;
  1066. default:
  1067. {
  1068. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1069. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1070. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1071. }
  1072. break;
  1073. }
  1074. }
  1075. }
  1076. async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  1077. {
  1078. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1079. if (await ReConfirmMessage(analysisResult))
  1080. {
  1081. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1082. MessageResult confirmResult = null;
  1083. switch (profileName)
  1084. {
  1085. case "Core":
  1086. {
  1087. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1088. }
  1089. break;
  1090. case "FirmwareManagement":
  1091. {
  1092. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1093. }
  1094. break;
  1095. case "RemoteTrigger":
  1096. {
  1097. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1098. }
  1099. break;
  1100. case "Reservation":
  1101. {
  1102. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1103. }
  1104. break;
  1105. case "LocalAuthListManagement":
  1106. {
  1107. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1108. }
  1109. break;
  1110. case "SmartCharging":
  1111. {
  1112. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1113. }
  1114. break;
  1115. case "Security":
  1116. {
  1117. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  1118. }
  1119. break;
  1120. default:
  1121. {
  1122. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1123. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1124. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1125. }
  1126. break;
  1127. }
  1128. if (confirmResult == null || !confirmResult.Success)
  1129. {
  1130. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  1131. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  1132. }
  1133. }
  1134. else
  1135. {
  1136. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1137. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1138. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1139. }
  1140. }
  1141. private async void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  1142. {
  1143. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1144. if (await ReConfirmMessage(analysisResult))
  1145. {
  1146. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  1147. switch (profileName)
  1148. {
  1149. case "Core":
  1150. {
  1151. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1152. }
  1153. break;
  1154. case "FirmwareManagement":
  1155. {
  1156. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1157. }
  1158. break;
  1159. case "RemoteTrigger":
  1160. {
  1161. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1162. }
  1163. break;
  1164. case "Reservation":
  1165. {
  1166. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1167. }
  1168. break;
  1169. case "LocalAuthListManagement":
  1170. {
  1171. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1172. }
  1173. break;
  1174. case "SmartCharging":
  1175. {
  1176. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  1177. }
  1178. break;
  1179. default:
  1180. {
  1181. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1182. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  1183. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1184. }
  1185. break;
  1186. }
  1187. }
  1188. else
  1189. {
  1190. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  1191. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  1192. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  1193. }
  1194. }
  1195. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  1196. {
  1197. try
  1198. {
  1199. if (session != null)
  1200. {
  1201. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1202. session.Send(msg);
  1203. }
  1204. }
  1205. catch (Exception ex)
  1206. {
  1207. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  1208. }
  1209. }
  1210. async private void ServerUpdateTrigger()
  1211. {
  1212. for (; ; )
  1213. {
  1214. if (_ct.IsCancellationRequested)
  1215. {
  1216. break;
  1217. }
  1218. var min_Interval = (DateTime.UtcNow - checkUpdateDt).TotalMinutes;
  1219. if (min_Interval > 3)
  1220. {
  1221. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1222. Dictionary<string, ClientData> _copyClientDic = null;
  1223. lock (_lockClientDic)
  1224. {
  1225. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1226. }
  1227. checkUpdateDt = DateTime.UtcNow;
  1228. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1229. {
  1230. //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  1231. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
  1232. // .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
  1233. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
  1234. x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
  1235. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  1236. foreach (var chargeBoxId in needUpdateChargers)
  1237. {
  1238. try
  1239. {
  1240. ClientData session;
  1241. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  1242. {
  1243. string requestId = Guid.NewGuid().ToString();
  1244. // using (var db = maindbContextFactory.CreateDbContext())
  1245. if (session.IsCheckIn && !session.ISOCPP20)
  1246. {
  1247. var _request = new TriggerMessageRequest()
  1248. {
  1249. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  1250. };
  1251. var uuid = session.queue.store(_request);
  1252. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
  1253. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  1254. #region OCTT ,測試韌體更新方式
  1255. //--------------------> OCTT ,測試韌體更新方式
  1256. //{
  1257. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  1258. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  1259. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  1260. // if (machine != null)
  1261. // {
  1262. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  1263. // .Include(c => c.PublishVersion.PublishVersionFiles)
  1264. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  1265. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  1266. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  1267. // var _updateFWrequest = new UpdateFirmwareRequest()
  1268. // {
  1269. // location = new Uri(downloadUrl),
  1270. // retries = 3,
  1271. // retrieveDate = DateTime.UtcNow,
  1272. // retryInterval = 10
  1273. // };
  1274. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  1275. // {
  1276. // CreatedOn = DateTime.UtcNow,
  1277. // ChargeBoxId = session.ChargeBoxId,
  1278. // SerialNo = requestId,
  1279. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1280. // EVSE_Status = 0,
  1281. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  1282. // Status = 0,
  1283. // RequestType = 0,
  1284. // });
  1285. // db.ServerMessage.Add(new ServerMessage()
  1286. // {
  1287. // ChargeBoxId = session.ChargeBoxId,
  1288. // CreatedBy = "Server",
  1289. // CreatedOn = DateTime.UtcNow,
  1290. // OutAction = _updateFWrequest.Action.ToString(),
  1291. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1292. // SerialNo = requestId,
  1293. // InMessage = string.Empty
  1294. // });
  1295. // db.SaveChanges();
  1296. // }
  1297. //}
  1298. #endregion
  1299. }
  1300. }
  1301. }
  1302. catch (Exception ex)
  1303. {
  1304. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  1305. }
  1306. }
  1307. }
  1308. await Task.Delay(1000);
  1309. // Thread.CurrentThread.Join(1000);
  1310. }
  1311. }
  1312. }
  1313. //string webConnectionString = ConfigurationManager.ConnectionStrings["WebDBContext"].ConnectionString;
  1314. async private void ServerMessageTrigger()
  1315. {
  1316. for (; ; )
  1317. {
  1318. if (_ct.IsCancellationRequested)
  1319. {
  1320. break;
  1321. }
  1322. try
  1323. {
  1324. RemoveConfirmMessage();
  1325. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1326. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1327. {
  1328. DateTime startDt = DateTime.UtcNow.AddSeconds(-30);
  1329. DateTime dt = new DateTime(1991, 1, 1);
  1330. DateTime currentTime = DateTime.UtcNow;
  1331. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= currentTime).AsNoTracking().ToList();
  1332. //處理主機傳送的有指令
  1333. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  1334. if (commandList.Count > 0)
  1335. {
  1336. // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  1337. }
  1338. var resendList = GetResendMessage();
  1339. foreach (var resendItem in resendList)
  1340. {
  1341. ClientData session;
  1342. if (clientDic.TryGetValue(resendItem.ChargePointSerialNumber, out session))
  1343. {
  1344. if (DateTime.UtcNow.Subtract(resendItem.SentOn).TotalSeconds > 1)
  1345. {
  1346. resendItem.SentTimes--;
  1347. resendItem.SentOn = DateTime.UtcNow;
  1348. Send(session, resendItem.SentMessage, string.Format("{0} {1}", resendItem.SentAction, "Request"), "");
  1349. }
  1350. }
  1351. }
  1352. foreach (var charger_SN in cmdMachineList)
  1353. {
  1354. ClientData session;
  1355. string uuid = string.Empty;
  1356. if (clientDic.TryGetValue(charger_SN, out session))
  1357. {
  1358. //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")));
  1359. if (session.IsCheckIn && !session.ISOCPP20)
  1360. {
  1361. string rawRequest = string.Empty;
  1362. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  1363. foreach (var item in cmdList)
  1364. {
  1365. IRequest request = null;
  1366. Actions action = Actions.None;
  1367. Enum.TryParse(item.OutAction, out action);
  1368. Type _RequestType = null;
  1369. for (int i = 0; i < profiles.Count; i++)
  1370. {
  1371. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  1372. if (feature != null)
  1373. {
  1374. _RequestType = feature.GetRequestType();
  1375. break;
  1376. }
  1377. }
  1378. if (_RequestType != null && item.CreatedBy != "Destroyer")
  1379. {
  1380. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  1381. uuid = session.queue.store(request);
  1382. rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
  1383. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1384. }
  1385. if (item.CreatedBy == "Destroyer")
  1386. {
  1387. if (_RequestType != null)
  1388. {
  1389. request = Activator.CreateInstance(_RequestType) as IRequest;
  1390. uuid = session.queue.store(request);
  1391. rawRequest = BasicMessageHandler.GenerateDestroyRequest(uuid, item.OutAction, item.OutRequest);
  1392. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1393. }
  1394. else
  1395. {
  1396. rawRequest = BasicMessageHandler.GenerateDestroyRequest(Guid.NewGuid().ToString(), item.OutAction, item.OutRequest);
  1397. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1398. }
  1399. }
  1400. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid, item.CreatedBy, rawRequest);
  1401. #region 更新資料表單一欄位
  1402. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.UtcNow };
  1403. //db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  1404. //db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  1405. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  1406. db.ServerMessage.Attach(_UpdatedItem);
  1407. _UpdatedItem.UpdatedOn = DateTime.UtcNow;
  1408. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  1409. db.SaveChanges();
  1410. #endregion
  1411. await Task.Delay(100);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. }
  1417. await Task.Delay(500);
  1418. }
  1419. catch (Exception ex)
  1420. {
  1421. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  1422. }
  1423. }
  1424. }
  1425. async private void HeartBeatCheckTrigger()
  1426. {
  1427. for (; ; )
  1428. {
  1429. if (_ct.IsCancellationRequested)
  1430. {
  1431. break;
  1432. }
  1433. try
  1434. {
  1435. if (DateTime.UtcNow.Subtract(lastcheckdt).TotalSeconds > 30)
  1436. {
  1437. lastcheckdt = DateTime.UtcNow;
  1438. Stopwatch watch = new Stopwatch();
  1439. Dictionary<string, ClientData> _copyClientDic = null;
  1440. lock (_lockClientDic)
  1441. {
  1442. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1443. }
  1444. var cdt = DateTime.UtcNow;
  1445. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-120)).Select(x => x.Value).ToList();
  1446. watch.Start();
  1447. foreach (var session in clients)
  1448. {
  1449. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1450. {
  1451. var machine = new Machine() { Id = session.MachineId };
  1452. if (machine != null)
  1453. {
  1454. //db.Configuration.AutoDetectChangesEnabled = false;
  1455. //db.Configuration.ValidateOnSaveEnabled = false;
  1456. db.Machine.Attach(machine);
  1457. machine.HeartbeatUpdatedOn = DateTime.UtcNow;
  1458. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  1459. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  1460. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  1461. await db.SaveChangesAsync();
  1462. }
  1463. }
  1464. }
  1465. watch.Stop();
  1466. if (watch.ElapsedMilliseconds / 1000 > 5)
  1467. {
  1468. logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  1469. }
  1470. }
  1471. await Task.Delay(10000);
  1472. }
  1473. catch (Exception ex)
  1474. {
  1475. Console.WriteLine("***********************************************************");
  1476. logger.Error(string.Format("HeartBeatCheckTrigger Ex:{0}", ex.ToString()));
  1477. }
  1478. }
  1479. }
  1480. async private void ServerWeatherNotificationTrigger()
  1481. {
  1482. for (; ; )
  1483. {
  1484. if (_ct.IsCancellationRequested)
  1485. {
  1486. break;
  1487. }
  1488. var min_Interval = (DateTime.UtcNow - _CheckWeatherDt).TotalMinutes;
  1489. if (min_Interval > 30)
  1490. {
  1491. // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
  1492. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1493. Dictionary<string, ClientData> _copyClientDic = null;
  1494. lock (_lockClientDic)
  1495. {
  1496. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1497. }
  1498. _CheckWeatherDt = DateTime.UtcNow;
  1499. var locations = _copyClientDic.Where(x => !string.IsNullOrEmpty(x.Value.StationLocation)).Distinct().Select(x => x.Value.StationLocation).ToList();
  1500. // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
  1501. foreach (var location in locations)
  1502. {
  1503. try
  1504. { //query weather
  1505. var httpResult = await httpClient.GetWeather("https://api.weatherapi.com/v1/current.json?key=874346abc0874e69a9423510222201&q=" + location, null, null);
  1506. string temp = "17";
  1507. string weather_code = "1183";
  1508. if (httpResult.Status == System.Net.HttpStatusCode.OK)
  1509. {
  1510. try
  1511. {
  1512. var jsonResult = JsonConvert.DeserializeObject(httpResult.Response) as JObject;
  1513. temp = jsonResult["current"]["temp_c"].ToString();
  1514. weather_code = jsonResult["current"]["condition"]["code"].ToString();
  1515. }
  1516. catch (Exception ex)
  1517. {
  1518. ;
  1519. }
  1520. }
  1521. #region 台泥氣象Mapping
  1522. switch (weather_code)
  1523. {
  1524. case "1000":
  1525. weather_code = "1";
  1526. break;
  1527. case "1003":
  1528. case "1006":
  1529. case "1009":
  1530. weather_code = "2";
  1531. break;
  1532. case "1063":
  1533. case "1072":
  1534. case "1150":
  1535. case "1153":
  1536. case "1168":
  1537. case "1171":
  1538. case "1180":
  1539. case "1183":
  1540. case "1186":
  1541. case "1189":
  1542. case "1192":
  1543. case "1195":
  1544. case "1198":
  1545. case "1201":
  1546. case "1237":
  1547. case "1240":
  1548. case "1243":
  1549. case "1246":
  1550. case "1261":
  1551. case "1264":
  1552. weather_code = "3";
  1553. break;
  1554. case "1087":
  1555. case "1273":
  1556. case "1276":
  1557. case "1279":
  1558. case "1282":
  1559. weather_code = "4";
  1560. break;
  1561. case "1066":
  1562. case "1069":
  1563. case "1114":
  1564. case "1117":
  1565. case "1204":
  1566. case "1207":
  1567. case "1210":
  1568. case "1213":
  1569. case "1216":
  1570. case "1219":
  1571. case "1222":
  1572. case "1225":
  1573. case "1249":
  1574. case "1252":
  1575. case "1255":
  1576. case "1258":
  1577. weather_code = "5";
  1578. break;
  1579. case "1030":
  1580. case "1135":
  1581. case "1147":
  1582. weather_code = "2";
  1583. break;
  1584. default:
  1585. weather_code = "2";
  1586. break;
  1587. }
  1588. #endregion
  1589. if (TCCStationDic.ContainsKey(location))
  1590. {
  1591. TCCStationDic[location].Temperature = (int)double.Parse(temp);
  1592. TCCStationDic[location].WeatherID = int.Parse(weather_code);
  1593. }
  1594. else
  1595. {
  1596. TCCStationDic.Add(location, new TCCWeatherDto() { WeatherID = int.Parse(weather_code), Temperature = (int)double.Parse(temp) });
  1597. }
  1598. }
  1599. catch (Exception ex)
  1600. {
  1601. logger.Error(string.Format("ServerWeatherNotificationTrigger ChargeBoxId:{0} Ex:{1}", location, ex.ToString()));
  1602. }
  1603. }
  1604. var clients = _copyClientDic.Where(x => x.Value.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8")).
  1605. Select(x => new { ChargeBoxId = x.Value.ChargeBoxId, StationLocation = x.Value.StationLocation }).ToList();
  1606. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1607. {
  1608. foreach (var client in clients)
  1609. {
  1610. try
  1611. {
  1612. if (string.IsNullOrEmpty(client.StationLocation))
  1613. {
  1614. Console.WriteLine(client.StationLocation + " is empty");
  1615. continue;
  1616. }
  1617. if (TCCStationDic.ContainsKey(client.StationLocation))
  1618. {
  1619. db.ServerMessage.Add(new ServerMessage()
  1620. {
  1621. ChargeBoxId = client.ChargeBoxId,
  1622. CreatedBy = "Server",
  1623. CreatedOn = DateTime.UtcNow,
  1624. OutAction = Actions.DataTransfer.ToString(),
  1625. OutRequest = JsonConvert.SerializeObject(
  1626. new DataTransferRequest()
  1627. {
  1628. messageId = "ID_Weather_Info",
  1629. vendorId = "Phihong Technology",
  1630. data = JsonConvert.SerializeObject(
  1631. new
  1632. {
  1633. weatherId = TCCStationDic[client.StationLocation].WeatherID,
  1634. Temperature = TCCStationDic[client.StationLocation].Temperature
  1635. })
  1636. },
  1637. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1638. SerialNo = Guid.NewGuid().ToString(),
  1639. InMessage = string.Empty
  1640. });
  1641. await db.SaveChangesAsync();
  1642. }
  1643. }
  1644. catch (Exception ex)
  1645. {
  1646. logger.Error(string.Format("ServerWeatherNotificationTrigger ChargeBoxId:{0} Ex:{1}", client.ChargeBoxId, ex.ToString()));
  1647. }
  1648. }
  1649. }
  1650. }
  1651. await Task.Delay(1000);
  1652. }
  1653. }
  1654. async private void ServerSetFeeTrigger()
  1655. {
  1656. for (; ; )
  1657. {
  1658. if (_ct.IsCancellationRequested)
  1659. {
  1660. break;
  1661. }
  1662. var min_Interval = (DateTime.UtcNow - _CheckFeeDt).TotalMinutes;
  1663. if (min_Interval > 1)
  1664. {
  1665. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1666. Dictionary<string, ClientData> _copyClientDic = null;
  1667. lock (_lockClientDic)
  1668. {
  1669. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1670. }
  1671. _CheckFeeDt = DateTime.UtcNow;
  1672. foreach (var item in _copyClientDic)
  1673. {
  1674. try
  1675. {
  1676. ClientData session = item.Value;
  1677. if (session.IsCheckIn)
  1678. {
  1679. string displayPriceText = await SetDefaultFee(session);
  1680. if (!string.IsNullOrEmpty(displayPriceText) && displayPriceText != session.DisplayPrice)
  1681. {
  1682. clientDic[item.Key].DisplayPrice = displayPriceText;
  1683. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1684. {
  1685. db.ServerMessage.Add(new ServerMessage()
  1686. {
  1687. ChargeBoxId = session.ChargeBoxId,
  1688. CreatedBy = "Server",
  1689. CreatedOn = DateTime.UtcNow,
  1690. OutAction = Actions.ChangeConfiguration.ToString(),
  1691. OutRequest = JsonConvert.SerializeObject(
  1692. new ChangeConfigurationRequest()
  1693. {
  1694. key = "DefaultPrice",
  1695. value = clientDic[item.Key].DisplayPrice
  1696. },
  1697. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1698. SerialNo = Guid.NewGuid().ToString(),
  1699. InMessage = string.Empty
  1700. }); ;
  1701. if (session.CustomerId == new Guid("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
  1702. {
  1703. db.ServerMessage.Add(new ServerMessage()
  1704. {
  1705. ChargeBoxId = session.ChargeBoxId,
  1706. CreatedBy = "Server",
  1707. CreatedOn = DateTime.UtcNow,
  1708. OutAction = Actions.ChangeConfiguration.ToString(),
  1709. OutRequest = JsonConvert.SerializeObject(
  1710. new ChangeConfigurationRequest()
  1711. {
  1712. key = "ConnectionTimeOut",
  1713. value = "120"
  1714. },
  1715. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1716. SerialNo = Guid.NewGuid().ToString(),
  1717. InMessage = string.Empty
  1718. });
  1719. db.ServerMessage.Add(new ServerMessage()
  1720. {
  1721. ChargeBoxId = session.ChargeBoxId,
  1722. CreatedBy = "Server",
  1723. CreatedOn = DateTime.UtcNow,
  1724. OutAction = Actions.ChangeConfiguration.ToString(),
  1725. OutRequest = JsonConvert.SerializeObject(
  1726. new ChangeConfigurationRequest()
  1727. {
  1728. key = "MeterValueSampleInterval",
  1729. value = "3"
  1730. },
  1731. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1732. SerialNo = Guid.NewGuid().ToString(),
  1733. InMessage = string.Empty
  1734. });
  1735. }
  1736. await db.SaveChangesAsync();
  1737. }
  1738. }
  1739. }
  1740. }
  1741. catch (Exception ex)
  1742. {
  1743. logger.Error(string.Format("ServerSetFeeTrigger ChargeBoxId:{0} Ex:{1}", item.Key, ex.ToString()));
  1744. }
  1745. }
  1746. }
  1747. await Task.Delay(1000);
  1748. }
  1749. }
  1750. async private Task<string> SetDefaultFee(ClientData client)
  1751. {
  1752. string displayPriceText = string.Empty;
  1753. string charingPriceText = string.Empty;
  1754. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1755. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1756. {
  1757. var parameters = new DynamicParameters();
  1758. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input);
  1759. string displayPricestrSql = "";
  1760. string strSql = "";
  1761. if (client.IsAC)
  1762. {
  1763. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1764. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1765. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1766. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1767. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1768. }
  1769. else
  1770. {
  1771. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1772. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1773. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1774. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1775. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1776. }
  1777. var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1778. if (result.Count() == 0)
  1779. {
  1780. return string.Empty;
  1781. }
  1782. var stationPrice = result.First();
  1783. if (stationPrice.BillingMethod == 1)
  1784. {
  1785. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1786. client.ChargingPrices = chargingPriceResult.ToList();
  1787. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1788. {
  1789. client.ChargingPrices = new List<ChargingPrice>();
  1790. }
  1791. }
  1792. displayPriceText = stationPrice.FeeName;
  1793. client.BillingMethod = stationPrice.BillingMethod;
  1794. client.Currency = stationPrice.Currency;
  1795. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1796. client.ParkingFee = stationPrice.ParkingFee;
  1797. client.IsBilling = true;
  1798. }
  1799. return displayPriceText;
  1800. }
  1801. async private void HealthCheckTrigger()
  1802. {
  1803. for (; ; )
  1804. {
  1805. if (_ct.IsCancellationRequested)
  1806. {
  1807. break;
  1808. }
  1809. try
  1810. {
  1811. Dictionary<string, ClientData> _copyClientDic = null;
  1812. lock (_lockClientDic)
  1813. {
  1814. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1815. }
  1816. var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.UtcNow.AddSeconds(-300)).Select(x => x.Value).ToList();
  1817. foreach (var session in removeClients)
  1818. {
  1819. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
  1820. RemoveClient(session);
  1821. }
  1822. await Task.Delay(60000);
  1823. }
  1824. catch (Exception ex)
  1825. {
  1826. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  1827. }
  1828. }
  1829. }
  1830. private List<NeedConfirmMessage> GetResendMessage()
  1831. {
  1832. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  1833. lock (_lockConfirmPacketList)
  1834. {
  1835. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  1836. }
  1837. return sendMessages;
  1838. }
  1839. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1840. {
  1841. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1842. _needConfirmMsg.Id = table_id;
  1843. _needConfirmMsg.SentAction = action;
  1844. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1845. _needConfirmMsg.SentTimes = 4;
  1846. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1847. _needConfirmMsg.RequestId = requestId;
  1848. _needConfirmMsg.SentUniqueId = msg_id;
  1849. _needConfirmMsg.CreatedBy = createdBy;
  1850. _needConfirmMsg.SentMessage = sendMessage;
  1851. if (needConfirmActions.Contains(action))
  1852. {
  1853. lock (_lockConfirmPacketList)
  1854. {
  1855. needConfirmPacketList.Add(_needConfirmMsg);
  1856. }
  1857. }
  1858. }
  1859. private void RemoveConfirmMessage()
  1860. {
  1861. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1862. lock (_lockConfirmPacketList)
  1863. {
  1864. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1865. foreach (var item in removeList)
  1866. {
  1867. needConfirmPacketList.Remove(item);
  1868. }
  1869. }
  1870. }
  1871. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  1872. {
  1873. bool confirmed = false;
  1874. if (needConfirmActions.Contains(analysisResult.Action))
  1875. {
  1876. NeedConfirmMessage foundRequest = null;
  1877. lock (_lockConfirmPacketList)
  1878. {
  1879. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1880. }
  1881. if (foundRequest != null && foundRequest.Id > 0)
  1882. {
  1883. foundRequest.SentTimes = 0;
  1884. foundRequest.SentInterval = 0;
  1885. analysisResult.RequestId = foundRequest.RequestId;
  1886. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1887. {
  1888. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  1889. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1890. sc.ReceivedOn = DateTime.UtcNow;
  1891. await db.SaveChangesAsync();
  1892. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1893. }
  1894. confirmed = true;
  1895. }
  1896. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1897. {
  1898. confirmed = true;
  1899. }
  1900. else
  1901. {
  1902. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1903. }
  1904. }
  1905. return confirmed;
  1906. }
  1907. private void RemoveClient(ClientData session)
  1908. {
  1909. if (session != null)
  1910. {
  1911. if (!string.IsNullOrEmpty(session.MachineId))
  1912. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1913. if (session.Connected)
  1914. {
  1915. session.Close(CloseReason.ServerShutdown);
  1916. }
  1917. RemoveClientDic(session);
  1918. try
  1919. {
  1920. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1921. // session.Close(CloseReason.ServerShutdown);
  1922. }
  1923. catch (Exception ex)
  1924. {
  1925. //logger.LogWarning("Close client socket error!!");
  1926. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1927. }
  1928. if (session != null)
  1929. {
  1930. session = null;
  1931. }
  1932. }
  1933. }
  1934. private void RemoveClientDic(ClientData session)
  1935. {
  1936. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  1937. {
  1938. lock (_lockClientDic)
  1939. {
  1940. if (clientDic.ContainsKey(session.ChargeBoxId))
  1941. {
  1942. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1943. {
  1944. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1945. clientDic.Remove(session.ChargeBoxId);
  1946. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1947. }
  1948. }
  1949. }
  1950. }
  1951. }
  1952. private async void WarmUpLog()
  1953. {
  1954. try
  1955. {
  1956. using (var log = await serviceProvider.GetService<IDbContextFactory<ConnectionLogDBContext>>().CreateDbContextAsync())
  1957. {
  1958. log.MachineConnectionLog.ToList();
  1959. }
  1960. }
  1961. catch (Exception ex)
  1962. {
  1963. Console.WriteLine(ex.ToString());
  1964. }
  1965. }
  1966. private async void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1967. {
  1968. try
  1969. {
  1970. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1971. if (clientData.ChargeBoxId == null)
  1972. {
  1973. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1974. }
  1975. using (var db = await serviceProvider.GetService<IDbContextFactory<ConnectionLogDBContext>>().CreateDbContextAsync())
  1976. {
  1977. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  1978. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  1979. var dd = DateTime.UtcNow;
  1980. SqlParameter[] parameter =
  1981. {
  1982. new SqlParameter("CreatedOn",dd),
  1983. new SqlParameter("ChargeBoxId",clientData.ChargeBoxId==null?"unknown":clientData.ChargeBoxId.Replace("'","''")),
  1984. new SqlParameter("MessageType",messageType.Replace("'","''")),
  1985. new SqlParameter("Data",data.Replace("'","''")),
  1986. new SqlParameter("Msg",errorMsg.Replace("'","''")),
  1987. new SqlParameter("IsSent",isSent),
  1988. new SqlParameter("EVSEEndPoint",clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()),
  1989. new SqlParameter("Session",clientData.SessionID==null?"123":clientData.SessionID)
  1990. };
  1991. db.Database.ExecuteSqlRaw(sp, parameter);
  1992. }
  1993. }
  1994. catch (Exception ex)
  1995. {
  1996. Console.WriteLine(ex.ToString());
  1997. }
  1998. }
  1999. }
  2000. }