ProtalServer.cs 68 KB

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