ProtalServer.cs 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. using NLog;
  2. using OCPPServer.Protocol;
  3. using OCPPServer.SubProtocol;
  4. using SuperSocket.SocketBase;
  5. using SuperSocket.SocketBase.Config;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Xml.Linq;
  12. using EVCB_OCPP.Packet.Messages.Basic;
  13. using EVCB_OCPP.Packet.Messages.Core;
  14. using EVCB_OCPP.WSServer.Message;
  15. using EVCB_OCPP.Packet.Messages;
  16. using EVCB_OCPP.Domain;
  17. using EVCB_OCPP.Domain.Models.Database;
  18. using System.Threading;
  19. using System.Data.Entity;
  20. using EVCB_OCPP.Packet.Features;
  21. using EVCB_OCPP.Packet.Features.Core;
  22. using Newtonsoft.Json;
  23. using OCPPPackage.Profiles;
  24. using System.Threading.Tasks;
  25. using EVCB_OCPP.WSServer.Helper;
  26. using System.Data.SqlClient;
  27. using EVCB_OCPP.Packet.Messages.FirmwareManagement;
  28. using EVCB_OCPP.Packet.Messages.RemoteTrigger;
  29. using System.Configuration;
  30. using System.Net;
  31. using System.Net.Security;
  32. using System.Security.Cryptography.X509Certificates;
  33. using EVCB_OCPP.WSServer.Service;
  34. using EVCB_OCPP.Packet.Messages.SmartCharging;
  35. using System.Security.Authentication;
  36. using NLog.Fluent;
  37. using System.Diagnostics;
  38. namespace EVCB_OCPP.WSServer
  39. {
  40. internal class ProtalServer
  41. {
  42. static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  43. private Dictionary<string, ClientData> clientDic = new Dictionary<string, ClientData>();
  44. private readonly Object _lockClientDic = new object();
  45. private readonly Object _lockConfirmPacketList = new object();
  46. private ProfileHandler profileHandler = new ProfileHandler();
  47. private List<NeedConfirmMessage> needConfirmPacketList = new List<NeedConfirmMessage>();
  48. private DateTime checkUpdateDt = DateTime.Now;
  49. private LoadingBalanceService _loadingBalanceService = new LoadingBalanceService();
  50. private List<string> needConfirmActions = new List<string>()
  51. {
  52. "GetConfiguration",
  53. "ChangeConfiguration",
  54. "RemoteStartTransaction",
  55. "RemoteStopTransaction",
  56. "ChangeAvailability",
  57. "ClearCache",
  58. "DataTransfer",
  59. "Reset",
  60. "UnlockConnector",
  61. "TriggerMessage",
  62. "GetDiagnostics",
  63. "UpdateFirmware",
  64. "GetLocalListVersion",
  65. "SendLocalList",
  66. "SetChargingProfile",
  67. "ClearChargingProfile",
  68. "GetCompositeSchedule",
  69. "ReserveNow",
  70. "CancelReservation",
  71. };
  72. private List<Profile> profiles = new List<Profile>()
  73. {
  74. new CoreProfile(),
  75. new FirmwareManagementProfile(),
  76. new ReservationProfile(),
  77. new RemoteTriggerProfile(),
  78. new SmartChargingProfile(),
  79. new LocalAuthListManagementProfile()
  80. };
  81. private CancellationTokenSource _cts = new CancellationTokenSource();
  82. private CancellationToken _ct;
  83. internal ProtalServer()
  84. {
  85. _ct = _cts.Token;
  86. WarmUpLog();
  87. }
  88. internal void Start()
  89. {
  90. if (!GlobalConfig.LoadAPPConfig())
  91. {
  92. Console.WriteLine("Please check App.Config setting .");
  93. return;
  94. }
  95. OpenNetwork();
  96. Task serverCommandTask = new Task(ServerMessageTrigger, _ct);
  97. serverCommandTask.Start();
  98. Task serverUpdateTask = new Task(ServerUpdateTrigger, _ct);
  99. serverUpdateTask.Start();
  100. Task serverBeatTask = new Task(HeartBeatCheckTrigger, _ct);
  101. serverBeatTask.Start();
  102. Task serverHealthTask = new Task(HealthCheckTrigger, _ct);
  103. serverHealthTask.Start();
  104. while (true)
  105. {
  106. var input = Console.ReadLine();
  107. switch (input.ToLower())
  108. {
  109. case "stop":
  110. logger.Info("Command stop");
  111. Stop();
  112. break;
  113. case "gc":
  114. logger.Info("Command GC");
  115. GC.Collect();
  116. break;
  117. case "lc":
  118. {
  119. logger.Info("Command List Clients");
  120. Dictionary<string, ClientData> _copyClientDic = null;
  121. lock (_lockClientDic)
  122. {
  123. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  124. }
  125. var list = _copyClientDic.Select(c => c.Value).ToList();
  126. int i = 1;
  127. foreach (var c in list)
  128. {
  129. logger.Info(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  130. i++;
  131. }
  132. }
  133. break;
  134. case "lcn":
  135. {
  136. logger.Info("Command List Customer Name");
  137. Dictionary<string, ClientData> _copyClientDic = null;
  138. lock (_lockClientDic)
  139. {
  140. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  141. }
  142. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  143. int iLcn = 1;
  144. foreach (var c in lcn)
  145. {
  146. logger.Info(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  147. iLcn++;
  148. }
  149. }
  150. break;
  151. case "help":
  152. logger.Info("Command help!!");
  153. logger.Info("lcn : List Customer Name");
  154. logger.Info("gc : GC Collect");
  155. logger.Info("lc : List Clients");
  156. logger.Info("cls : clear console");
  157. logger.Info("silent : silent");
  158. logger.Info("show : show log");
  159. // logger.Info("rcl : show Real Connection Limit");
  160. break;
  161. case "cls":
  162. logger.Info("Command clear");
  163. Console.Clear();
  164. break;
  165. case "silent":
  166. logger.Info("Command silent");
  167. var xe = XElement.Load("NLog.config");
  168. var xns = xe.GetDefaultNamespace();
  169. var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  170. .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  171. if (minlevelattr != null)
  172. {
  173. minlevelattr.Value = "info";
  174. }
  175. xe.Save("NLog.config");
  176. break;
  177. case "show":
  178. logger.Info("Command show");
  179. var xe1 = XElement.Load("NLog.config");
  180. var xns1 = xe1.GetDefaultNamespace();
  181. var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  182. .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  183. if (minlevelattr1 != null)
  184. {
  185. minlevelattr1.Value = "trace";
  186. }
  187. xe1.Save("NLog.config");
  188. break;
  189. case "rcl":
  190. break;
  191. default:
  192. break;
  193. }
  194. }
  195. }
  196. internal void Stop()
  197. {
  198. if (_cts != null)
  199. {
  200. _cts.Cancel();
  201. }
  202. }
  203. private void CheckVersion(string chargeBoxId)
  204. {
  205. if (string.IsNullOrEmpty(chargeBoxId)) return;
  206. using (var db = new MainDBContext())
  207. {
  208. db.ServerMessage.Add(new ServerMessage()
  209. {
  210. ChargeBoxId = chargeBoxId,
  211. CreatedBy = "Server",
  212. CreatedOn = DateTime.Now,
  213. OutAction = Actions.DataTransfer.ToString(),
  214. OutRequest = JsonConvert.SerializeObject(
  215. new DataTransferRequest()
  216. {
  217. messageId = "ID_FirmwareVersion",
  218. vendorId = "Phihong Technology"
  219. },
  220. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  221. SerialNo = Guid.NewGuid().ToString(),
  222. InMessage = string.Empty
  223. });
  224. db.SaveChanges();
  225. }
  226. }
  227. private void CheckEVSEConfigure(string chargeBoxId)
  228. {
  229. if (string.IsNullOrEmpty(chargeBoxId)) return;
  230. int skipCount = 0;
  231. int takeCount = 8;
  232. using (var db = new MainDBContext())
  233. {
  234. string maxKeys = StandardConfiguration.AllConfigs.Skip(skipCount).Take(1).FirstOrDefault();
  235. if (maxKeys == StandardConfiguration.GetConfigurationMaxKeys)
  236. {
  237. var _Configure = db.MachineConfiguration.Where(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == maxKeys).Select(x => new { ConfigureSetting = x.ConfigureSetting, ConfigureName = x.ConfigureName }).FirstOrDefault();
  238. if (_Configure != null)
  239. {
  240. int cp_ConfiureCount = 0;
  241. int.TryParse(_Configure.ConfigureSetting, out cp_ConfiureCount);
  242. takeCount = takeCount > cp_ConfiureCount ? cp_ConfiureCount : takeCount;
  243. skipCount = 1;
  244. if (string.IsNullOrEmpty(_Configure.ConfigureSetting)) return;
  245. }
  246. }
  247. while (StandardConfiguration.AllConfigs.Count > skipCount)
  248. {
  249. string _key = StandardConfiguration.AllConfigs.Skip(skipCount).Take(1).FirstOrDefault();
  250. var _Configure = db.MachineConfiguration.Where(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == _key).Select(x => new { ConfigureSetting = x.ConfigureSetting, ConfigureName = x.ConfigureName }).FirstOrDefault();
  251. takeCount = StandardConfiguration.AllConfigs.Count - skipCount > takeCount ? takeCount : StandardConfiguration.AllConfigs.Count - skipCount;
  252. var _keys = StandardConfiguration.AllConfigs.Skip(skipCount).Take(takeCount).ToList();
  253. // Console.WriteLine("===============Skip:" + skipCount);
  254. if (_Configure == null)
  255. {
  256. // Console.WriteLine("_Configure == null===============Skip:" + skipCount);
  257. db.ServerMessage.Add(new ServerMessage()
  258. {
  259. ChargeBoxId = chargeBoxId,
  260. CreatedBy = "Server",
  261. CreatedOn = DateTime.Now,
  262. OutAction = Actions.GetConfiguration.ToString(),
  263. OutRequest = JsonConvert.SerializeObject(
  264. new GetConfigurationRequest()
  265. {
  266. key = _keys
  267. },
  268. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  269. SerialNo = Guid.NewGuid().ToString(),
  270. InMessage = string.Empty
  271. });
  272. db.SaveChanges();
  273. }
  274. skipCount = skipCount + takeCount;
  275. }
  276. }
  277. }
  278. private void OpenNetwork()
  279. {
  280. //載入OCPP Protocol
  281. var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6") });
  282. List<IListenerConfig> llistener = new List<IListenerConfig>();
  283. //System.Net.IPAddress.Any.ToString()
  284. // llistener.Add(new ListenerConfig { Ip = "", Port = Convert.ToInt32(wssserverPort), Backlog = 100, Security = serverSecurity });
  285. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWS_Port()), Backlog = 100, Security = "None" });
  286. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWSS_Port()), Backlog = 100, Security = SslProtocols.Tls12.ToString() });
  287. // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWSS_Port()), Backlog = 100, Security = SslProtocols.Tls11.ToString() });
  288. var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;
  289. ICertificateConfig Certificate = config.Servers.ElementAt(0).Certificate;
  290. IEnumerable<IListenerConfig> listeners = llistener;
  291. //設定server config
  292. var serverConfig = new ServerConfig
  293. {
  294. //Port = Convert.ToInt32(2012),
  295. //Ip = "172.17.40.13",
  296. MaxRequestLength = 4096,
  297. //Security = serverSecurity,
  298. Certificate = Certificate,
  299. Listeners = listeners,
  300. LogAllSocketException = true,
  301. KeepAliveTime = 10,
  302. LogBasicSessionActivity = true
  303. };
  304. //Setup with listening port
  305. if (!appServer.Setup(serverConfig, logFactory: new OCPPLogFactory()))
  306. {
  307. Console.WriteLine("Failed to setup!");
  308. return;
  309. }
  310. appServer.NewSessionConnected += AppServer_NewSessionConnected;
  311. appServer.SessionClosed += AppServer_SessionClosed;
  312. //Try to start the appServer
  313. if (!appServer.Start())
  314. {
  315. Console.WriteLine("Failed to start!");
  316. Console.ReadKey();
  317. return;
  318. }
  319. }
  320. private void AppServer_SessionClosed(ClientData session, CloseReason value)
  321. {
  322. // Console.WriteLine(session.RemoteEndPoint.Address);
  323. WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
  324. RemoveClient(session);
  325. // close Connection
  326. }
  327. private void AppServer_NewSessionConnected(ClientData session)
  328. {
  329. try
  330. {
  331. lock (_lockClientDic)
  332. {
  333. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : true;
  334. if (isNotSupported)
  335. {
  336. //logger.Debug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  337. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  338. return;
  339. }
  340. ClientData _removeClient = null;
  341. clientDic.TryGetValue(session.ChargeBoxId, out _removeClient);
  342. if (_removeClient != null)
  343. {
  344. WriteMachineLog(_removeClient, "Duplicate Logins", "Connection", "");
  345. _removeClient.Close(CloseReason.ServerShutdown);
  346. RemoveClient(_removeClient);
  347. }
  348. session.IsCheckIn = true;
  349. clientDic.Add(session.ChargeBoxId, session);
  350. session.m_ReceiveData += new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  351. // logger.Debug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  352. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  353. using (var db = new MainDBContext())
  354. {
  355. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  356. if (machine != null)
  357. {
  358. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  359. db.SaveChanges();
  360. }
  361. }
  362. CheckVersion(session.ChargeBoxId);
  363. CheckEVSEConfigure(session.ChargeBoxId);
  364. }
  365. }
  366. catch (Exception ex)
  367. {
  368. logger.Error(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  369. }
  370. }
  371. async private void ReceivedMessage(ClientData session, string rawdata)
  372. {
  373. try
  374. {
  375. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  376. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  377. WriteMachineLog(session, rawdata,
  378. 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);
  379. if (!analysisResult.Success)
  380. {
  381. //解析RawData就發生錯誤
  382. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  383. {
  384. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  385. }
  386. else
  387. {
  388. if (analysisResult.Message == null)
  389. {
  390. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  391. string errorMsg = string.Empty;
  392. if (analysisResult.Exception != null)
  393. {
  394. errorMsg = analysisResult.Exception.ToString();
  395. }
  396. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  397. }
  398. else
  399. {
  400. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  401. string replyMsg = msgAnalyser.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  402. string errorMsg = string.Empty;
  403. if (analysisResult.Exception != null)
  404. {
  405. errorMsg = analysisResult.Exception.ToString();
  406. }
  407. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  408. }
  409. }
  410. }
  411. else
  412. {
  413. Actions action = Convertor.GetAction(analysisResult.Action);
  414. switch (analysisResult.Id)
  415. {
  416. case BasicMessageHandler.TYPENUMBER_CALL:
  417. {
  418. ProcessRequestMessage(analysisResult, session, action);
  419. }
  420. break;
  421. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  422. {
  423. ProcessConfirmationMessage(analysisResult, session, action);
  424. }
  425. break;
  426. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  427. {
  428. //只處理 丟出Request 收到Error的訊息
  429. if (analysisResult.Success && analysisResult.Message != null)
  430. {
  431. ProcessErrorMessage(analysisResult, session, action);
  432. }
  433. }
  434. break;
  435. default:
  436. {
  437. logger.Error(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  438. }
  439. break;
  440. }
  441. }
  442. await Task.Delay(10);
  443. }
  444. catch (Exception ex)
  445. {
  446. logger.Error(string.Format("**Exception :{0} ", ex.ToString()));
  447. if (ex.InnerException != null)
  448. {
  449. logger.Error(string.Format("**Inner exception :{0} ", ex.InnerException.ToString()));
  450. }
  451. }
  452. }
  453. async private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
  454. {
  455. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  456. if (!session.IsCheckIn && action != Actions.BootNotification)
  457. {
  458. string response = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  459. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  460. }
  461. else
  462. {
  463. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  464. switch (profileName)
  465. {
  466. case "Core":
  467. {
  468. bool oldstatus = session.IsCheckIn;
  469. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  470. if (replyResult.Success)
  471. {
  472. string response = msgAnalyser.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  473. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString());
  474. if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
  475. {
  476. if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  477. {
  478. session.IsCheckIn = true;
  479. if (!oldstatus)
  480. {
  481. using (var db = new MainDBContext())
  482. {
  483. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  484. if (machine != null)
  485. {
  486. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  487. db.SaveChanges();
  488. }
  489. }
  490. // CheckEVSEConfigure(session.ChargeBoxId);
  491. }
  492. }
  493. }
  494. }
  495. else
  496. {
  497. string response = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  498. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  499. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  500. }
  501. if (action == Actions.StartTransaction)
  502. {
  503. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  504. var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
  505. if (_powerDic != null)
  506. {
  507. foreach (var kv in _powerDic)
  508. {
  509. try
  510. {
  511. string chargeBoxId = string.Empty;
  512. //set profile
  513. lock (_lockClientDic)
  514. {
  515. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  516. }
  517. if (chargeBoxId != null && kv.Value.HasValue)
  518. {
  519. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  520. }
  521. }
  522. catch (Exception ex)
  523. {
  524. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  525. }
  526. }
  527. }
  528. }
  529. if (action == Actions.StopTransaction)
  530. {
  531. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  532. if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
  533. {
  534. //Clear current profile
  535. profileHandler.ClearChargingProfile(session.ChargeBoxId);
  536. var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
  537. if (_powerDic != null)
  538. {
  539. foreach (var kv in _powerDic)
  540. {
  541. try
  542. {
  543. string chargeBoxId = string.Empty;
  544. //set profile
  545. lock (_lockClientDic)
  546. {
  547. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  548. }
  549. if (chargeBoxId != null && kv.Value.HasValue)
  550. {
  551. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  552. }
  553. }
  554. catch (Exception ex)
  555. {
  556. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  557. }
  558. }
  559. }
  560. }
  561. }
  562. }
  563. break;
  564. case "FirmwareManagement":
  565. {
  566. var replyResult = profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  567. if (replyResult.Success)
  568. {
  569. string response = msgAnalyser.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  570. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  571. }
  572. else
  573. {
  574. string response = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  575. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  576. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  577. }
  578. }
  579. break;
  580. default:
  581. {
  582. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  583. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  584. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  585. }
  586. break;
  587. }
  588. }
  589. }
  590. private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  591. {
  592. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  593. if (ReConfirmMessage(analysisResult))
  594. {
  595. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  596. MessageResult confirmResult = null;
  597. switch (profileName)
  598. {
  599. case "Core":
  600. {
  601. confirmResult = profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  602. }
  603. break;
  604. case "FirmwareManagement":
  605. {
  606. confirmResult = profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  607. }
  608. break;
  609. case "RemoteTrigger":
  610. {
  611. confirmResult = profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  612. }
  613. break;
  614. case "Reservation":
  615. {
  616. confirmResult = profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  617. }
  618. break;
  619. case "LocalAuthListManagement":
  620. {
  621. confirmResult = profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  622. }
  623. break;
  624. case "SmartCharging":
  625. {
  626. confirmResult = profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  627. }
  628. break;
  629. default:
  630. {
  631. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  632. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  633. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  634. }
  635. break;
  636. }
  637. if (confirmResult == null || !confirmResult.Success)
  638. {
  639. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  640. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  641. }
  642. }
  643. else
  644. {
  645. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  646. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  647. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  648. }
  649. }
  650. private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  651. {
  652. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  653. if (ReConfirmMessage(analysisResult))
  654. {
  655. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  656. switch (profileName)
  657. {
  658. case "Core":
  659. {
  660. profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  661. }
  662. break;
  663. case "FirmwareManagement":
  664. {
  665. profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  666. }
  667. break;
  668. case "RemoteTrigger":
  669. {
  670. profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  671. }
  672. break;
  673. case "Reservation":
  674. {
  675. profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  676. }
  677. break;
  678. case "LocalAuthListManagement":
  679. {
  680. profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  681. }
  682. break;
  683. case "SmartCharging":
  684. {
  685. profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  686. }
  687. break;
  688. default:
  689. {
  690. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  691. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  692. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  693. }
  694. break;
  695. }
  696. }
  697. else
  698. {
  699. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  700. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  701. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  702. }
  703. }
  704. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  705. {
  706. try
  707. {
  708. if (session != null)
  709. {
  710. WriteMachineLog(session, msg, messageType, errorMsg, true);
  711. session.Send(msg);
  712. }
  713. }
  714. catch (Exception ex)
  715. {
  716. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  717. }
  718. }
  719. async private void ServerUpdateTrigger()
  720. {
  721. for (; ; )
  722. {
  723. if (_ct.IsCancellationRequested)
  724. {
  725. break;
  726. }
  727. var min_Interval = (DateTime.Now - checkUpdateDt).TotalMinutes;
  728. if (min_Interval > 3)
  729. {
  730. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  731. Dictionary<string, ClientData> _copyClientDic = null;
  732. lock (_lockClientDic)
  733. {
  734. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  735. }
  736. checkUpdateDt = DateTime.Now;
  737. using (var db = new MainDBContext())
  738. {
  739. //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  740. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
  741. // .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
  742. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
  743. x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
  744. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  745. foreach (var chargeBoxId in needUpdateChargers)
  746. {
  747. try
  748. {
  749. ClientData session;
  750. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  751. {
  752. string requestId = Guid.NewGuid().ToString();
  753. // using (var db = new MainDBContext())
  754. if (session.IsCheckIn)
  755. {
  756. var _request = new TriggerMessageRequest()
  757. {
  758. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  759. };
  760. var uuid = session.queue.store(_request);
  761. string rawRequest = msgAnalyser.GenerateRequest(uuid, _request.Action, _request);
  762. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  763. #region OCTT ,測試韌體更新方式
  764. //--------------------> OCTT ,測試韌體更新方式
  765. //{
  766. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  767. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  768. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  769. // if (machine != null)
  770. // {
  771. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  772. // .Include(c => c.PublishVersion.PublishVersionFiles)
  773. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  774. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  775. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  776. // var _updateFWrequest = new UpdateFirmwareRequest()
  777. // {
  778. // location = new Uri(downloadUrl),
  779. // retries = 3,
  780. // retrieveDate = DateTime.Now,
  781. // retryInterval = 10
  782. // };
  783. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  784. // {
  785. // CreatedOn = DateTime.Now,
  786. // ChargeBoxId = session.ChargeBoxId,
  787. // SerialNo = requestId,
  788. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  789. // EVSE_Status = 0,
  790. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  791. // Status = 0,
  792. // RequestType = 0,
  793. // });
  794. // db.ServerMessage.Add(new ServerMessage()
  795. // {
  796. // ChargeBoxId = session.ChargeBoxId,
  797. // CreatedBy = "Server",
  798. // CreatedOn = DateTime.Now,
  799. // OutAction = _updateFWrequest.Action.ToString(),
  800. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  801. // SerialNo = requestId,
  802. // InMessage = string.Empty
  803. // });
  804. // db.SaveChanges();
  805. // }
  806. //}
  807. #endregion
  808. }
  809. }
  810. }
  811. catch (Exception ex)
  812. {
  813. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  814. }
  815. }
  816. }
  817. await Task.Delay(1000);
  818. // Thread.CurrentThread.Join(1000);
  819. }
  820. }
  821. }
  822. async private void ServerMessageTrigger()
  823. {
  824. for (; ; )
  825. {
  826. if (_ct.IsCancellationRequested)
  827. {
  828. break;
  829. }
  830. try
  831. {
  832. RemoveConfirmMessage();
  833. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  834. using (var db = new MainDBContext())
  835. {
  836. DateTime startDt = DateTime.Now.AddSeconds(-30);
  837. DateTime dt = new DateTime(1991, 1, 1);
  838. //Console.WriteLine(string.Format("{0} IN", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
  839. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= DateTime.Now).AsNoTracking().ToList();
  840. //處理主機傳送的有指令
  841. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  842. if (commandList.Count > 0)
  843. {
  844. Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  845. }
  846. foreach (var charger_SN in cmdMachineList)
  847. {
  848. ClientData session;
  849. string uuid = string.Empty;
  850. if (clientDic.TryGetValue(charger_SN, out session))
  851. {
  852. Console.WriteLine(string.Format("charger_SN:{0} startDt:{1} CreatedOn:{2}", charger_SN, startDt.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
  853. if (session.IsCheckIn)
  854. {
  855. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  856. foreach (var item in cmdList)
  857. {
  858. IRequest request = null;
  859. Actions action = Actions.None;
  860. Enum.TryParse(item.OutAction, out action);
  861. Type _RequestType = null;
  862. for (int i = 0; i < profiles.Count; i++)
  863. {
  864. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  865. if (feature != null)
  866. {
  867. _RequestType = feature.GetRequestType();
  868. break;
  869. }
  870. }
  871. if (_RequestType != null)
  872. {
  873. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  874. uuid = session.queue.store(request);
  875. string rawRequest = msgAnalyser.GenerateRequest(uuid, item.OutAction, request);
  876. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  877. }
  878. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid);
  879. #region 更新資料表單一欄位
  880. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.Now };
  881. db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  882. db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  883. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  884. db.ServerMessage.Attach(_UpdatedItem);
  885. _UpdatedItem.UpdatedOn = DateTime.Now;
  886. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  887. db.SaveChanges();
  888. #endregion
  889. }
  890. }
  891. }
  892. }
  893. db.ChangeTracker.DetectChanges();
  894. }
  895. await Task.Delay(1000);
  896. // Thread.CurrentThread.Join(1000);
  897. }
  898. catch (Exception ex)
  899. {
  900. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  901. }
  902. }
  903. }
  904. DateTime lastcheckdt = new DateTime();
  905. async private void HeartBeatCheckTrigger()
  906. {
  907. for (; ; )
  908. {
  909. if (_ct.IsCancellationRequested)
  910. {
  911. break;
  912. }
  913. try
  914. {
  915. if (DateTime.Now.Subtract(lastcheckdt).TotalSeconds > 20)
  916. {
  917. Stopwatch watch = new Stopwatch();
  918. Dictionary<string, ClientData> _copyClientDic = null;
  919. lock (_lockClientDic)
  920. {
  921. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  922. }
  923. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > DateTime.Now.AddSeconds(-60)).Select(x => x.Value).ToList();
  924. watch.Start();
  925. foreach (var session in clients)
  926. {
  927. using (var db = new MainDBContext())
  928. {
  929. var machine = new Machine() { Id = session.MachineId };
  930. if (machine != null)
  931. {
  932. db.Configuration.AutoDetectChangesEnabled = false;
  933. db.Configuration.ValidateOnSaveEnabled = false;
  934. db.Machine.Attach(machine);
  935. machine.HeartbeatUpdatedOn = DateTime.Now;
  936. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  937. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  938. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  939. await db.SaveChangesAsync();
  940. }
  941. }
  942. }
  943. watch.Stop();
  944. if (watch.ElapsedMilliseconds/1000 > 5)
  945. {
  946. logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  947. }
  948. }
  949. lastcheckdt = DateTime.Now;
  950. await Task.Delay(60000);
  951. }
  952. catch (Exception ex)
  953. {
  954. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  955. }
  956. }
  957. }
  958. async private void HealthCheckTrigger()
  959. {
  960. for (; ; )
  961. {
  962. if (_ct.IsCancellationRequested)
  963. {
  964. break;
  965. }
  966. try
  967. {
  968. Dictionary<string, ClientData> _copyClientDic = null;
  969. lock (_lockClientDic)
  970. {
  971. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  972. }
  973. var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.Now.AddSeconds(-120)).Select(x => x.Value).ToList();
  974. foreach (var session in removeClients)
  975. {
  976. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
  977. RemoveClient(session);
  978. }
  979. await Task.Delay(60000);
  980. }
  981. catch (Exception ex)
  982. {
  983. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  984. }
  985. }
  986. }
  987. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id)
  988. {
  989. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  990. _needConfirmMsg.Id = table_id;
  991. _needConfirmMsg.SentAction = action;
  992. _needConfirmMsg.SentOn = DateTime.Now;
  993. _needConfirmMsg.SentTimes = 1;
  994. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  995. _needConfirmMsg.RequestId = requestId;
  996. _needConfirmMsg.SentUniqueId = msg_id;
  997. if (needConfirmActions.Contains(action))
  998. {
  999. lock (_lockConfirmPacketList)
  1000. {
  1001. needConfirmPacketList.Add(_needConfirmMsg);
  1002. if (action == "GetConfiguration")
  1003. {
  1004. Console.WriteLine("AddConfirmMessage: " + msg_id);
  1005. }
  1006. }
  1007. }
  1008. }
  1009. private void RemoveConfirmMessage()
  1010. {
  1011. var before_3mins = DateTime.Now.AddMinutes(-3);
  1012. lock (_lockConfirmPacketList)
  1013. {
  1014. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before_3mins).ToList();
  1015. foreach (var item in removeList)
  1016. {
  1017. needConfirmPacketList.Remove(item);
  1018. }
  1019. }
  1020. }
  1021. private bool ReConfirmMessage(MessageResult analysisResult)
  1022. {
  1023. bool confirmed = false;
  1024. if (needConfirmActions.Contains(analysisResult.Action))
  1025. {
  1026. if (analysisResult.Action == "GetConfiguration")
  1027. {
  1028. Console.WriteLine("ReConfirmMessage: " + analysisResult.UUID);
  1029. }
  1030. NeedConfirmMessage foundRequest = null;
  1031. lock (_lockConfirmPacketList)
  1032. {
  1033. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1034. }
  1035. if (foundRequest != null && foundRequest.Id > 0)
  1036. {
  1037. foundRequest.SentTimes = 0;
  1038. foundRequest.SentInterval = 0;
  1039. analysisResult.RequestId = foundRequest.RequestId;
  1040. using (var db = new MainDBContext())
  1041. {
  1042. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  1043. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1044. sc.ReceivedOn = DateTime.Now;
  1045. db.SaveChanges();
  1046. Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1047. }
  1048. confirmed = true;
  1049. }
  1050. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1051. {
  1052. confirmed = true;
  1053. }
  1054. else
  1055. {
  1056. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1057. }
  1058. }
  1059. return confirmed;
  1060. }
  1061. private void RemoveClient(ClientData session)
  1062. {
  1063. Console.WriteLine("*********");
  1064. if (session != null)
  1065. {
  1066. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1067. if (session.Connected)
  1068. {
  1069. session.Close(CloseReason.ServerShutdown);
  1070. }
  1071. RemoveClientDic(session);
  1072. try
  1073. {
  1074. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1075. // session.Close(CloseReason.ServerShutdown);
  1076. }
  1077. catch (Exception ex)
  1078. {
  1079. //logger.Warn("Close client socket error!!");
  1080. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1081. }
  1082. if (session != null)
  1083. {
  1084. session = null;
  1085. }
  1086. }
  1087. }
  1088. private void RemoveClientDic(ClientData session)
  1089. {
  1090. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  1091. {
  1092. lock (_lockClientDic)
  1093. {
  1094. if (clientDic.ContainsKey(session.ChargeBoxId))
  1095. {
  1096. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1097. {
  1098. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1099. clientDic.Remove(session.ChargeBoxId);
  1100. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1101. }
  1102. }
  1103. }
  1104. }
  1105. }
  1106. private void WarmUpLog()
  1107. {
  1108. using (var log = new ConnectionLogDBContext())
  1109. {
  1110. log.MachineConnectionLog.ToList();
  1111. }
  1112. }
  1113. private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1114. {
  1115. try
  1116. {
  1117. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1118. if (clientData.ChargeBoxId == null)
  1119. {
  1120. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1121. }
  1122. using (var db = new ConnectionLogDBContext())
  1123. {
  1124. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  1125. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  1126. var dd = DateTime.UtcNow;
  1127. SqlParameter[] parameter =
  1128. {
  1129. new SqlParameter("CreatedOn",dd),
  1130. new SqlParameter("ChargeBoxId",clientData.ChargeBoxId==null?"unknown":clientData.ChargeBoxId.Replace("'","''")),
  1131. new SqlParameter("MessageType",messageType.Replace("'","''")),
  1132. new SqlParameter("Data",data.Replace("'","''")),
  1133. new SqlParameter("Msg",errorMsg.Replace("'","''")),
  1134. new SqlParameter("IsSent",isSent),
  1135. new SqlParameter("EVSEEndPoint",clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()),
  1136. new SqlParameter("Session",clientData.SessionID==null?"123":clientData.SessionID)
  1137. };
  1138. db.Database.ExecuteSqlCommand(sp, parameter);
  1139. }
  1140. }
  1141. catch (Exception ex)
  1142. {
  1143. Console.WriteLine(ex.ToString());
  1144. }
  1145. }
  1146. }
  1147. }