ProtalServer.cs 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  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. logger.Warn(replyResult.Exception.ToString());
  648. }
  649. else
  650. {
  651. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  652. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  653. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  654. }
  655. }
  656. if (action == Actions.StartTransaction)
  657. {
  658. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  659. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  660. if (_powerDic != null)
  661. {
  662. foreach (var kv in _powerDic)
  663. {
  664. try
  665. {
  666. if (kv.Value.HasValue)
  667. {
  668. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  669. }
  670. }
  671. catch (Exception ex)
  672. {
  673. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  674. }
  675. }
  676. }
  677. }
  678. if (action == Actions.StopTransaction)
  679. {
  680. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  681. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  682. if (_powerDic != null)
  683. {
  684. foreach (var kv in _powerDic)
  685. {
  686. try
  687. {
  688. if (kv.Value.HasValue)
  689. {
  690. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  691. }
  692. }
  693. catch (Exception ex)
  694. {
  695. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  696. }
  697. }
  698. }
  699. }
  700. }
  701. break;
  702. case "FirmwareManagement":
  703. {
  704. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  705. if (replyResult.Success)
  706. {
  707. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  708. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  709. }
  710. else
  711. {
  712. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  713. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  714. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  715. }
  716. }
  717. break;
  718. case "Security":
  719. {
  720. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  721. if (replyResult.Success)
  722. {
  723. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  724. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  725. }
  726. else
  727. {
  728. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  729. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  730. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  731. }
  732. }
  733. break;
  734. default:
  735. {
  736. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  737. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  738. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  739. }
  740. break;
  741. }
  742. }
  743. }
  744. async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  745. {
  746. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  747. if (ReConfirmMessage(analysisResult))
  748. {
  749. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  750. MessageResult confirmResult = null;
  751. switch (profileName)
  752. {
  753. case "Core":
  754. {
  755. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  756. }
  757. break;
  758. case "FirmwareManagement":
  759. {
  760. confirmResult = profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  761. }
  762. break;
  763. case "RemoteTrigger":
  764. {
  765. confirmResult = profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  766. }
  767. break;
  768. case "Reservation":
  769. {
  770. confirmResult = profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  771. }
  772. break;
  773. case "LocalAuthListManagement":
  774. {
  775. confirmResult = profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  776. }
  777. break;
  778. case "SmartCharging":
  779. {
  780. confirmResult = profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  781. }
  782. break;
  783. case "Security":
  784. {
  785. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  786. }
  787. break;
  788. default:
  789. {
  790. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  791. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  792. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  793. }
  794. break;
  795. }
  796. if (confirmResult == null || !confirmResult.Success)
  797. {
  798. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  799. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  800. }
  801. }
  802. else
  803. {
  804. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  805. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  806. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  807. }
  808. }
  809. private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  810. {
  811. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  812. if (ReConfirmMessage(analysisResult))
  813. {
  814. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  815. switch (profileName)
  816. {
  817. case "Core":
  818. {
  819. profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  820. }
  821. break;
  822. case "FirmwareManagement":
  823. {
  824. profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  825. }
  826. break;
  827. case "RemoteTrigger":
  828. {
  829. profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  830. }
  831. break;
  832. case "Reservation":
  833. {
  834. profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  835. }
  836. break;
  837. case "LocalAuthListManagement":
  838. {
  839. profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  840. }
  841. break;
  842. case "SmartCharging":
  843. {
  844. profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  845. }
  846. break;
  847. default:
  848. {
  849. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  850. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  851. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  852. }
  853. break;
  854. }
  855. }
  856. else
  857. {
  858. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  859. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  860. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  861. }
  862. }
  863. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  864. {
  865. try
  866. {
  867. if (session != null)
  868. {
  869. WriteMachineLog(session, msg, messageType, errorMsg, true);
  870. session.Send(msg);
  871. }
  872. }
  873. catch (Exception ex)
  874. {
  875. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  876. }
  877. }
  878. async private void DenyModelCheckTrigger(bool warmup)
  879. {
  880. for (; ; )
  881. {
  882. if (_ct.IsCancellationRequested)
  883. {
  884. break;
  885. }
  886. try
  887. {
  888. var min_Interval = (DateTime.UtcNow - _CheckDenyListDt).TotalMinutes;
  889. if (min_Interval > 5)
  890. {
  891. _CheckDenyListDt = DateTime.UtcNow;
  892. using (SqlConnection conn = new SqlConnection(webConnectionString))
  893. {
  894. string strSql = "SELECT [Value] FROM [dbo].[KernelConfig] " +
  895. "where SystemKey = 'DenyModelNames'; ";
  896. var result = await conn.QueryAsync<string>(strSql);
  897. GlobalConfig.DenyModelNames = result.FirstOrDefault().Split(',').ToList();
  898. // logger.Debug(string.Format("Current DenyList:[{0}]", string.Join(",", GlobalConfig.DenyModelNames)));
  899. }
  900. if (!string.IsNullOrEmpty(GlobalConfig.DenyModelNames[0]))
  901. {
  902. Dictionary<string, ClientData> _copyClientDic = null;
  903. lock (_lockClientDic)
  904. {
  905. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  906. }
  907. foreach (var denyName in GlobalConfig.DenyModelNames)
  908. {
  909. var removeClients = _copyClientDic.Where(x => x.Key.StartsWith(denyName)).Select(x => x.Value).ToList();
  910. foreach (var session in removeClients)
  911. {
  912. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: Reason: DenyModelName-{1}", session.ChargeBoxId, denyName));
  913. RemoveClient(session);
  914. }
  915. }
  916. }
  917. }
  918. await Task.Delay(500);
  919. }
  920. catch (Exception ex)
  921. {
  922. // logger.Error(string.Format("DenyModelCheckTrigger Ex:{0}", ex.ToString()));
  923. }
  924. if (warmup) break;
  925. }
  926. }
  927. async private void ServerUpdateTrigger()
  928. {
  929. for (; ; )
  930. {
  931. if (_ct.IsCancellationRequested)
  932. {
  933. break;
  934. }
  935. var min_Interval = (DateTime.UtcNow - checkUpdateDt).TotalMinutes;
  936. if (min_Interval > 3)
  937. {
  938. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  939. Dictionary<string, ClientData> _copyClientDic = null;
  940. lock (_lockClientDic)
  941. {
  942. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  943. }
  944. checkUpdateDt = DateTime.UtcNow;
  945. using (var db = new MainDBContext())
  946. {
  947. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
  948. x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
  949. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  950. foreach (var chargeBoxId in needUpdateChargers)
  951. {
  952. try
  953. {
  954. ClientData session;
  955. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  956. {
  957. string requestId = Guid.NewGuid().ToString();
  958. if (session.IsCheckIn && !session.ISOCPP20)
  959. {
  960. var _request = new TriggerMessageRequest()
  961. {
  962. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  963. };
  964. var uuid = session.queue.store(_request);
  965. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
  966. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  967. #region OCTT ,測試韌體更新方式
  968. //--------------------> OCTT ,測試韌體更新方式
  969. //{
  970. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  971. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  972. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  973. // if (machine != null)
  974. // {
  975. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  976. // .Include(c => c.PublishVersion.PublishVersionFiles)
  977. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  978. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  979. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  980. // var _updateFWrequest = new UpdateFirmwareRequest()
  981. // {
  982. // location = new Uri(downloadUrl),
  983. // retries = 3,
  984. // retrieveDate = DateTime.UtcNow,
  985. // retryInterval = 10
  986. // };
  987. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  988. // {
  989. // CreatedOn = DateTime.UtcNow,
  990. // ChargeBoxId = session.ChargeBoxId,
  991. // SerialNo = requestId,
  992. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  993. // EVSE_Status = 0,
  994. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  995. // Status = 0,
  996. // RequestType = 0,
  997. // });
  998. // db.ServerMessage.Add(new ServerMessage()
  999. // {
  1000. // ChargeBoxId = session.ChargeBoxId,
  1001. // CreatedBy = "Server",
  1002. // CreatedOn = DateTime.UtcNow,
  1003. // OutAction = _updateFWrequest.Action.ToString(),
  1004. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1005. // SerialNo = requestId,
  1006. // InMessage = string.Empty
  1007. // });
  1008. // db.SaveChanges();
  1009. // }
  1010. //}
  1011. #endregion
  1012. }
  1013. }
  1014. }
  1015. catch (Exception ex)
  1016. {
  1017. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  1018. }
  1019. }
  1020. }
  1021. await Task.Delay(1000);
  1022. }
  1023. }
  1024. }
  1025. async private void ServerMessageTrigger()
  1026. {
  1027. for (; ; )
  1028. {
  1029. if (_ct.IsCancellationRequested)
  1030. {
  1031. break;
  1032. }
  1033. try
  1034. {
  1035. RemoveConfirmMessage();
  1036. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1037. using (var db = new MainDBContext())
  1038. {
  1039. DateTime startDt = DateTime.UtcNow.AddSeconds(-30);
  1040. DateTime dt = new DateTime(1991, 1, 1);
  1041. DateTime currentTime = DateTime.UtcNow;
  1042. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= currentTime).AsNoTracking().ToList();
  1043. //處理主機傳送的有指令
  1044. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  1045. if (commandList.Count > 0)
  1046. {
  1047. // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  1048. }
  1049. var resendList = GetResendMessage();
  1050. foreach (var resendItem in resendList)
  1051. {
  1052. ClientData session;
  1053. if (clientDic.TryGetValue(resendItem.ChargePointSerialNumber, out session))
  1054. {
  1055. if (DateTime.UtcNow.Subtract(resendItem.SentOn).TotalSeconds > 1)
  1056. {
  1057. resendItem.SentTimes--;
  1058. resendItem.SentOn = DateTime.UtcNow;
  1059. Send(session, resendItem.SentMessage, string.Format("{0} {1}", resendItem.SentAction, "Request"), "");
  1060. }
  1061. }
  1062. }
  1063. foreach (var charger_SN in cmdMachineList)
  1064. {
  1065. ClientData session;
  1066. string uuid = string.Empty;
  1067. if (clientDic.TryGetValue(charger_SN, out session))
  1068. {
  1069. //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")));
  1070. if (session.IsCheckIn && !session.ISOCPP20)
  1071. {
  1072. string rawRequest = string.Empty;
  1073. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  1074. foreach (var item in cmdList)
  1075. {
  1076. IRequest request = null;
  1077. Actions action = Actions.None;
  1078. Enum.TryParse(item.OutAction, out action);
  1079. Type _RequestType = null;
  1080. for (int i = 0; i < profiles.Count; i++)
  1081. {
  1082. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  1083. if (feature != null)
  1084. {
  1085. _RequestType = feature.GetRequestType();
  1086. break;
  1087. }
  1088. }
  1089. if (_RequestType != null && item.CreatedBy != "Destroyer")
  1090. {
  1091. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  1092. uuid = session.queue.store(request);
  1093. rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
  1094. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1095. }
  1096. if (item.CreatedBy == "Destroyer")
  1097. {
  1098. if (_RequestType != null)
  1099. {
  1100. request = Activator.CreateInstance(_RequestType) as IRequest;
  1101. uuid = session.queue.store(request);
  1102. rawRequest = BasicMessageHandler.GenerateDestroyRequest(uuid, item.OutAction, item.OutRequest);
  1103. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1104. }
  1105. else
  1106. {
  1107. rawRequest = BasicMessageHandler.GenerateDestroyRequest(Guid.NewGuid().ToString(), item.OutAction, item.OutRequest);
  1108. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1109. }
  1110. }
  1111. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid, item.CreatedBy, rawRequest);
  1112. #region 更新資料表單一欄位
  1113. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.UtcNow };
  1114. db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  1115. db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  1116. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  1117. db.ServerMessage.Attach(_UpdatedItem);
  1118. _UpdatedItem.UpdatedOn = DateTime.UtcNow;
  1119. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  1120. db.SaveChanges();
  1121. #endregion
  1122. await Task.Delay(100);
  1123. }
  1124. }
  1125. }
  1126. }
  1127. }
  1128. await Task.Delay(500);
  1129. }
  1130. catch (Exception ex)
  1131. {
  1132. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  1133. }
  1134. }
  1135. }
  1136. async private void HeartBeatCheckTrigger()
  1137. {
  1138. for (; ; )
  1139. {
  1140. if (_ct.IsCancellationRequested)
  1141. {
  1142. break;
  1143. }
  1144. try
  1145. {
  1146. // if (DateTime.UtcNow.Subtract(lastcheckdt).TotalSeconds > 30)
  1147. {
  1148. // lastcheckdt = DateTime.UtcNow;
  1149. Stopwatch watch = new Stopwatch();
  1150. Dictionary<string, ClientData> _copyClientDic = null;
  1151. lock (_lockClientDic)
  1152. {
  1153. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1154. }
  1155. var cdt = DateTime.UtcNow;
  1156. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-120)).Select(x => x.Value).ToList();
  1157. watch.Start();
  1158. foreach (var session in clients)
  1159. {
  1160. using (var db = new MainDBContext())
  1161. {
  1162. using (var transaction = db.Database.BeginTransaction())
  1163. {
  1164. try
  1165. {
  1166. var machine = new Machine() { Id = session.MachineId };
  1167. if (machine != null)
  1168. {
  1169. db.Configuration.AutoDetectChangesEnabled = false;
  1170. db.Configuration.ValidateOnSaveEnabled = false;
  1171. db.Machine.Attach(machine);
  1172. machine.HeartbeatUpdatedOn = DateTime.UtcNow;
  1173. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  1174. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  1175. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  1176.                                             //await db.SaveChangesAsync();
  1177.                                             db.SaveChanges();
  1178. transaction.Commit();
  1179. }
  1180. }
  1181. catch (Exception ex)
  1182. {
  1183. transaction.Rollback();
  1184. }
  1185. }
  1186. }
  1187. }
  1188. watch.Stop();
  1189. if (watch.ElapsedMilliseconds / 1000 > 5)
  1190. {
  1191. logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  1192. }
  1193. }
  1194. await Task.Delay(10000);
  1195. }
  1196. catch (Exception ex)
  1197. {
  1198. Console.WriteLine("***********************************************************");
  1199. logger.Error(string.Format("HeartBeatCheckTrigger Ex:{0}", ex.ToString()));
  1200. }
  1201. }
  1202. }
  1203. async private void ServerSetFeeTrigger()
  1204. {
  1205. for (; ; )
  1206. {
  1207. if (_ct.IsCancellationRequested)
  1208. {
  1209. break;
  1210. }
  1211. var min_Interval = (DateTime.UtcNow - _CheckFeeDt).TotalMinutes;
  1212. if (min_Interval > 1)
  1213. {
  1214. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1215. Dictionary<string, ClientData> _copyClientDic = null;
  1216. lock (_lockClientDic)
  1217. {
  1218. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1219. }
  1220. _CheckFeeDt = DateTime.UtcNow;
  1221. foreach (var item in _copyClientDic)
  1222. {
  1223. try
  1224. {
  1225. ClientData session = item.Value;
  1226. if (session.IsCheckIn)
  1227. {
  1228. string displayPriceText = await SetDefaultFee(session);
  1229. if (!string.IsNullOrEmpty(displayPriceText) && displayPriceText != session.DisplayPrice)
  1230. {
  1231. clientDic[item.Key].DisplayPrice = displayPriceText;
  1232. using (var db = new MainDBContext())
  1233. {
  1234. db.ServerMessage.Add(new ServerMessage()
  1235. {
  1236. ChargeBoxId = session.ChargeBoxId,
  1237. CreatedBy = "Server",
  1238. CreatedOn = DateTime.UtcNow,
  1239. OutAction = Actions.ChangeConfiguration.ToString(),
  1240. OutRequest = JsonConvert.SerializeObject(
  1241. new ChangeConfigurationRequest()
  1242. {
  1243. key = "DefaultPrice",
  1244. value = clientDic[item.Key].DisplayPrice
  1245. },
  1246. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1247. SerialNo = Guid.NewGuid().ToString(),
  1248. InMessage = string.Empty
  1249. }); ;
  1250. if (session.CustomerId == new Guid("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
  1251. {
  1252. db.ServerMessage.Add(new ServerMessage()
  1253. {
  1254. ChargeBoxId = session.ChargeBoxId,
  1255. CreatedBy = "Server",
  1256. CreatedOn = DateTime.UtcNow,
  1257. OutAction = Actions.ChangeConfiguration.ToString(),
  1258. OutRequest = JsonConvert.SerializeObject(
  1259. new ChangeConfigurationRequest()
  1260. {
  1261. key = "ConnectionTimeOut",
  1262. value = "120"
  1263. },
  1264. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1265. SerialNo = Guid.NewGuid().ToString(),
  1266. InMessage = string.Empty
  1267. });
  1268. db.ServerMessage.Add(new ServerMessage()
  1269. {
  1270. ChargeBoxId = session.ChargeBoxId,
  1271. CreatedBy = "Server",
  1272. CreatedOn = DateTime.UtcNow,
  1273. OutAction = Actions.ChangeConfiguration.ToString(),
  1274. OutRequest = JsonConvert.SerializeObject(
  1275. new ChangeConfigurationRequest()
  1276. {
  1277. key = "MeterValueSampleInterval",
  1278. value = "3"
  1279. },
  1280. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1281. SerialNo = Guid.NewGuid().ToString(),
  1282. InMessage = string.Empty
  1283. });
  1284. }
  1285. await db.SaveChangesAsync();
  1286. }
  1287. }
  1288. }
  1289. }
  1290. catch (Exception ex)
  1291. {
  1292. logger.Error(string.Format("ServerSetFeeTrigger ChargeBoxId:{0} Ex:{1}", item.Key, ex.ToString()));
  1293. }
  1294. }
  1295. }
  1296. await Task.Delay(1000);
  1297. }
  1298. }
  1299. async private void SmartChargingTrigger()
  1300. {
  1301. for (; ; )
  1302. {
  1303. if (_ct.IsCancellationRequested)
  1304. {
  1305. break;
  1306. }
  1307. var min_Interval = (DateTime.UtcNow - _CheckLBDt).TotalMinutes;
  1308. if (min_Interval > 1)
  1309. {
  1310. List<StationInfoDto> stations = null;
  1311. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1312. {
  1313. string strSql = "SELECT[Id],[LBMode],[LBCurrent] as Availability FROM [dbo].[Station] " +
  1314. "where LBMode = 1; ";
  1315. var result = await conn.QueryAsync<StationInfoDto>(strSql);
  1316. stations = result.ToList();
  1317. }
  1318. foreach (var station in stations)
  1319. {
  1320. var compareStation = _StationInfo.Where(x => x.Id == station.Id).FirstOrDefault();
  1321. if (compareStation == null || (station.Id == compareStation.Id && station.Availability != compareStation.Availability))
  1322. {
  1323. var _powerDic = await _loadingBalanceService.GetSettingPower(station.Id);
  1324. if (_powerDic != null)
  1325. {
  1326. foreach (var kv in _powerDic)
  1327. {
  1328. try
  1329. {
  1330. if (kv.Value.HasValue)
  1331. {
  1332. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  1333. }
  1334. }
  1335. catch (Exception ex)
  1336. {
  1337. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. _StationInfo = stations;
  1344. _CheckLBDt = DateTime.UtcNow;
  1345. }
  1346. await Task.Delay(1000);
  1347. }
  1348. }
  1349. async private Task<string> SetDefaultFee(ClientData client)
  1350. {
  1351. string displayPriceText = string.Empty;
  1352. string charingPriceText = string.Empty;
  1353. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1354. try
  1355. {
  1356. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1357. {
  1358. var parameters = new DynamicParameters();
  1359. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input);
  1360. string displayPricestrSql = "";
  1361. string strSql = "";
  1362. if (client.IsAC)
  1363. {
  1364. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1365. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1366. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1367. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1368. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1369. }
  1370. else
  1371. {
  1372. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1373. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1374. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1375. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1376. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1377. }
  1378. var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1379. if (result.Count() == 0)
  1380. {
  1381. return string.Empty;
  1382. }
  1383. var stationPrice = result.First();
  1384. if (stationPrice.BillingMethod == 1)
  1385. {
  1386. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1387. client.ChargingPrices = chargingPriceResult.ToList();
  1388. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1389. {
  1390. client.ChargingPrices = new List<ChargingPrice>();
  1391. }
  1392. }
  1393. displayPriceText = stationPrice.FeeName;
  1394. client.BillingMethod = stationPrice.BillingMethod;
  1395. client.Currency = stationPrice.Currency;
  1396. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1397. client.ParkingFee = stationPrice.ParkingFee;
  1398. client.IsBilling = true;
  1399. }
  1400. }
  1401. catch (Exception ex)
  1402. {
  1403. logger.Error("SetDefaultFee", ex.ToString());
  1404. }
  1405. return displayPriceText;
  1406. }
  1407. async private void HealthCheckTrigger()
  1408. {
  1409. for (; ; )
  1410. {
  1411. if (_ct.IsCancellationRequested)
  1412. {
  1413. break;
  1414. }
  1415. try
  1416. {
  1417. Dictionary<string, ClientData> _copyClientDic = null;
  1418. lock (_lockClientDic)
  1419. {
  1420. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1421. }
  1422. var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.UtcNow.AddSeconds(-300)).Select(x => x.Value).ToList();
  1423. foreach (var session in removeClients)
  1424. {
  1425. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
  1426. RemoveClient(session);
  1427. }
  1428. await Task.Delay(60000);
  1429. }
  1430. catch (Exception ex)
  1431. {
  1432. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  1433. }
  1434. }
  1435. }
  1436. private List<NeedConfirmMessage> GetResendMessage()
  1437. {
  1438. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  1439. lock (_lockConfirmPacketList)
  1440. {
  1441. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  1442. }
  1443. return sendMessages;
  1444. }
  1445. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1446. {
  1447. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1448. _needConfirmMsg.Id = table_id;
  1449. _needConfirmMsg.SentAction = action;
  1450. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1451. _needConfirmMsg.SentTimes = 4;
  1452. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1453. _needConfirmMsg.RequestId = requestId;
  1454. _needConfirmMsg.SentUniqueId = msg_id;
  1455. _needConfirmMsg.CreatedBy = createdBy;
  1456. _needConfirmMsg.SentMessage = sendMessage;
  1457. if (needConfirmActions.Contains(action))
  1458. {
  1459. lock (_lockConfirmPacketList)
  1460. {
  1461. needConfirmPacketList.Add(_needConfirmMsg);
  1462. }
  1463. }
  1464. }
  1465. private void RemoveConfirmMessage()
  1466. {
  1467. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1468. lock (_lockConfirmPacketList)
  1469. {
  1470. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1471. foreach (var item in removeList)
  1472. {
  1473. needConfirmPacketList.Remove(item);
  1474. }
  1475. }
  1476. }
  1477. private bool ReConfirmMessage(MessageResult analysisResult)
  1478. {
  1479. bool confirmed = false;
  1480. if (needConfirmActions.Contains(analysisResult.Action))
  1481. {
  1482. NeedConfirmMessage foundRequest = null;
  1483. lock (_lockConfirmPacketList)
  1484. {
  1485. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1486. }
  1487. if (foundRequest != null && foundRequest.Id > 0)
  1488. {
  1489. foundRequest.SentTimes = 0;
  1490. foundRequest.SentInterval = 0;
  1491. analysisResult.RequestId = foundRequest.RequestId;
  1492. using (var db = new MainDBContext())
  1493. {
  1494. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  1495. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1496. sc.ReceivedOn = DateTime.UtcNow;
  1497. db.SaveChanges();
  1498. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1499. }
  1500. confirmed = true;
  1501. }
  1502. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1503. {
  1504. confirmed = true;
  1505. }
  1506. else
  1507. {
  1508. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1509. }
  1510. }
  1511. return confirmed;
  1512. }
  1513. private void RemoveClient(ClientData session)
  1514. {
  1515. if (session != null)
  1516. {
  1517. if (!string.IsNullOrEmpty(session.MachineId))
  1518. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1519. if (session.Connected)
  1520. {
  1521. session.Close(CloseReason.ServerShutdown);
  1522. }
  1523. RemoveClientDic(session);
  1524. try
  1525. {
  1526. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1527. // session.Close(CloseReason.ServerShutdown);
  1528. }
  1529. catch (Exception ex)
  1530. {
  1531. //logger.Warn("Close client socket error!!");
  1532. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1533. }
  1534. if (session != null)
  1535. {
  1536. session = null;
  1537. }
  1538. }
  1539. }
  1540. private void RemoveClientDic(ClientData session)
  1541. {
  1542. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  1543. {
  1544. lock (_lockClientDic)
  1545. {
  1546. if (clientDic.ContainsKey(session.ChargeBoxId))
  1547. {
  1548. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1549. {
  1550. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1551. clientDic.Remove(session.ChargeBoxId);
  1552. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1553. }
  1554. }
  1555. }
  1556. }
  1557. }
  1558. private void WarmUpLog()
  1559. {
  1560. try
  1561. {
  1562. using (var main = new MainDBContext())
  1563. {
  1564. main.Machine.Where(x => x.ChargeBoxId == "AAA").FirstOrDefault();
  1565. // log.MachineConnectionLog.ToList();
  1566. }
  1567. using (var log = new ConnectionLogDBContext())
  1568. {
  1569. log.MachineConnectionLog.ToList();
  1570. }
  1571. }
  1572. catch (Exception ex)
  1573. {
  1574. logger.Error(ex.ToString());
  1575. //Console.WriteLine(ex.ToString());
  1576. }
  1577. }
  1578. private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1579. {
  1580. try
  1581. {
  1582. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1583. if (clientData.ChargeBoxId == null)
  1584. {
  1585. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1586. }
  1587. using (var db = new ConnectionLogDBContext())
  1588. {
  1589. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  1590. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  1591. var dd = DateTime.UtcNow;
  1592. SqlParameter[] parameter =
  1593. {
  1594. new SqlParameter("CreatedOn",23){ Value=dd},
  1595. new SqlParameter("ChargeBoxId",50){ Value=clientData.ChargeBoxId==null?"unknown":clientData.ChargeBoxId.Replace("'","''")},
  1596. new SqlParameter("MessageType",50){ Value=messageType.Replace("'","''")},
  1597. new SqlParameter("Data",data.Replace("'","''")),
  1598. new SqlParameter("Msg",200){ Value=errorMsg.Replace("'","''")},
  1599. new SqlParameter("IsSent",1){ Value=isSent},
  1600. new SqlParameter("EVSEEndPoint",25){ Value=clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()},
  1601. new SqlParameter("Session",36){ Value=clientData.SessionID==null?"123":clientData.SessionID}
  1602. };
  1603. db.Database.ExecuteSqlCommand(sp, parameter);
  1604. }
  1605. }
  1606. catch (Exception ex)
  1607. {
  1608. Console.WriteLine(ex.ToString());
  1609. }
  1610. }
  1611. }
  1612. }