ProtalServer.cs 72 KB

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