ProtalServer.cs 87 KB

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