ProtalServer.cs 89 KB

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