ProtalServer.cs 72 KB

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