ProtalServer.cs 91 KB

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