ProtalServer.cs 91 KB

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