ProtalServer.cs 57 KB

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