ProtalServer.cs 63 KB

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