ProtalServer.cs 62 KB

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