ProtalServer.cs 87 KB

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