ProtalServer.cs 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886
  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. }
  645. else
  646. {
  647. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  648. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  649. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  650. }
  651. }
  652. if (action == Actions.StartTransaction)
  653. {
  654. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  655. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  656. if (_powerDic != null)
  657. {
  658. foreach (var kv in _powerDic)
  659. {
  660. try
  661. {
  662. if (kv.Value.HasValue)
  663. {
  664. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  665. }
  666. }
  667. catch (Exception ex)
  668. {
  669. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  670. }
  671. }
  672. }
  673. }
  674. if (action == Actions.StopTransaction)
  675. {
  676. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  677. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  678. if (_powerDic != null)
  679. {
  680. foreach (var kv in _powerDic)
  681. {
  682. try
  683. {
  684. if (kv.Value.HasValue)
  685. {
  686. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  687. }
  688. }
  689. catch (Exception ex)
  690. {
  691. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  692. }
  693. }
  694. }
  695. }
  696. }
  697. break;
  698. case "FirmwareManagement":
  699. {
  700. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  701. if (replyResult.Success)
  702. {
  703. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  704. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  705. }
  706. else
  707. {
  708. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  709. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  710. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  711. }
  712. }
  713. break;
  714. case "Security":
  715. {
  716. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  717. if (replyResult.Success)
  718. {
  719. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  720. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  721. }
  722. else
  723. {
  724. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  725. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  726. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  727. }
  728. }
  729. break;
  730. default:
  731. {
  732. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  733. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  734. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  735. }
  736. break;
  737. }
  738. }
  739. }
  740. async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  741. {
  742. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  743. if (ReConfirmMessage(analysisResult))
  744. {
  745. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  746. MessageResult confirmResult = null;
  747. switch (profileName)
  748. {
  749. case "Core":
  750. {
  751. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  752. }
  753. break;
  754. case "FirmwareManagement":
  755. {
  756. confirmResult = profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  757. }
  758. break;
  759. case "RemoteTrigger":
  760. {
  761. confirmResult = profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  762. }
  763. break;
  764. case "Reservation":
  765. {
  766. confirmResult = profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  767. }
  768. break;
  769. case "LocalAuthListManagement":
  770. {
  771. confirmResult = profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  772. }
  773. break;
  774. case "SmartCharging":
  775. {
  776. confirmResult = profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  777. }
  778. break;
  779. case "Security":
  780. {
  781. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  782. }
  783. break;
  784. default:
  785. {
  786. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  787. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  788. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  789. }
  790. break;
  791. }
  792. if (confirmResult == null || !confirmResult.Success)
  793. {
  794. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  795. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  796. }
  797. }
  798. else
  799. {
  800. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  801. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  802. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  803. }
  804. }
  805. private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  806. {
  807. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  808. if (ReConfirmMessage(analysisResult))
  809. {
  810. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  811. switch (profileName)
  812. {
  813. case "Core":
  814. {
  815. profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  816. }
  817. break;
  818. case "FirmwareManagement":
  819. {
  820. profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  821. }
  822. break;
  823. case "RemoteTrigger":
  824. {
  825. profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  826. }
  827. break;
  828. case "Reservation":
  829. {
  830. profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  831. }
  832. break;
  833. case "LocalAuthListManagement":
  834. {
  835. profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  836. }
  837. break;
  838. case "SmartCharging":
  839. {
  840. profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  841. }
  842. break;
  843. default:
  844. {
  845. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  846. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  847. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  848. }
  849. break;
  850. }
  851. }
  852. else
  853. {
  854. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  855. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  856. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  857. }
  858. }
  859. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  860. {
  861. try
  862. {
  863. if (session != null)
  864. {
  865. WriteMachineLog(session, msg, messageType, errorMsg, true);
  866. session.Send(msg);
  867. }
  868. }
  869. catch (Exception ex)
  870. {
  871. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  872. }
  873. }
  874. async private void DenyModelCheckTrigger(bool warmup)
  875. {
  876. for (; ; )
  877. {
  878. if (_ct.IsCancellationRequested)
  879. {
  880. break;
  881. }
  882. try
  883. {
  884. var min_Interval = (DateTime.UtcNow - _CheckDenyListDt).TotalMinutes;
  885. if (min_Interval > 5)
  886. {
  887. _CheckDenyListDt = DateTime.UtcNow;
  888. using (SqlConnection conn = new SqlConnection(webConnectionString))
  889. {
  890. string strSql = "SELECT [Value] FROM [dbo].[KernelConfig] " +
  891. "where SystemKey = 'DenyModelNames'; ";
  892. var result = await conn.QueryAsync<string>(strSql);
  893. GlobalConfig.DenyModelNames = result.FirstOrDefault().Split(',').ToList();
  894. logger.Debug(string.Format("Current DenyList:[{0}]", string.Join(",", GlobalConfig.DenyModelNames)));
  895. }
  896. if (!string.IsNullOrEmpty(GlobalConfig.DenyModelNames[0]))
  897. {
  898. Dictionary<string, ClientData> _copyClientDic = null;
  899. lock (_lockClientDic)
  900. {
  901. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  902. }
  903. foreach (var denyName in GlobalConfig.DenyModelNames)
  904. {
  905. var removeClients = _copyClientDic.Where(x => x.Key.StartsWith(denyName)).Select(x => x.Value).ToList();
  906. foreach (var session in removeClients)
  907. {
  908. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: Reason: DenyModelName-{1}", session.ChargeBoxId, denyName));
  909. RemoveClient(session);
  910. }
  911. }
  912. }
  913. }
  914. await Task.Delay(500);
  915. }
  916. catch (Exception ex)
  917. {
  918. // logger.Error(string.Format("DenyModelCheckTrigger Ex:{0}", ex.ToString()));
  919. }
  920. if (warmup) break;
  921. }
  922. }
  923. async private void ServerUpdateTrigger()
  924. {
  925. for (; ; )
  926. {
  927. if (_ct.IsCancellationRequested)
  928. {
  929. break;
  930. }
  931. var min_Interval = (DateTime.UtcNow - checkUpdateDt).TotalMinutes;
  932. if (min_Interval > 3)
  933. {
  934. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  935. Dictionary<string, ClientData> _copyClientDic = null;
  936. lock (_lockClientDic)
  937. {
  938. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  939. }
  940. checkUpdateDt = DateTime.UtcNow;
  941. using (var db = new MainDBContext())
  942. {
  943. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
  944. x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
  945. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  946. foreach (var chargeBoxId in needUpdateChargers)
  947. {
  948. try
  949. {
  950. ClientData session;
  951. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  952. {
  953. string requestId = Guid.NewGuid().ToString();
  954. if (session.IsCheckIn && !session.ISOCPP20)
  955. {
  956. var _request = new TriggerMessageRequest()
  957. {
  958. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  959. };
  960. var uuid = session.queue.store(_request);
  961. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
  962. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  963. #region OCTT ,測試韌體更新方式
  964. //--------------------> OCTT ,測試韌體更新方式
  965. //{
  966. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  967. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  968. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  969. // if (machine != null)
  970. // {
  971. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  972. // .Include(c => c.PublishVersion.PublishVersionFiles)
  973. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  974. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  975. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  976. // var _updateFWrequest = new UpdateFirmwareRequest()
  977. // {
  978. // location = new Uri(downloadUrl),
  979. // retries = 3,
  980. // retrieveDate = DateTime.UtcNow,
  981. // retryInterval = 10
  982. // };
  983. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  984. // {
  985. // CreatedOn = DateTime.UtcNow,
  986. // ChargeBoxId = session.ChargeBoxId,
  987. // SerialNo = requestId,
  988. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  989. // EVSE_Status = 0,
  990. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  991. // Status = 0,
  992. // RequestType = 0,
  993. // });
  994. // db.ServerMessage.Add(new ServerMessage()
  995. // {
  996. // ChargeBoxId = session.ChargeBoxId,
  997. // CreatedBy = "Server",
  998. // CreatedOn = DateTime.UtcNow,
  999. // OutAction = _updateFWrequest.Action.ToString(),
  1000. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1001. // SerialNo = requestId,
  1002. // InMessage = string.Empty
  1003. // });
  1004. // db.SaveChanges();
  1005. // }
  1006. //}
  1007. #endregion
  1008. }
  1009. }
  1010. }
  1011. catch (Exception ex)
  1012. {
  1013. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  1014. }
  1015. }
  1016. }
  1017. await Task.Delay(1000);
  1018. }
  1019. }
  1020. }
  1021. async private void ServerMessageTrigger()
  1022. {
  1023. for (; ; )
  1024. {
  1025. if (_ct.IsCancellationRequested)
  1026. {
  1027. break;
  1028. }
  1029. try
  1030. {
  1031. RemoveConfirmMessage();
  1032. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1033. using (var db = new MainDBContext())
  1034. {
  1035. DateTime startDt = DateTime.UtcNow.AddSeconds(-30);
  1036. DateTime dt = new DateTime(1991, 1, 1);
  1037. DateTime currentTime = DateTime.UtcNow;
  1038. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= currentTime).AsNoTracking().ToList();
  1039. //處理主機傳送的有指令
  1040. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  1041. if (commandList.Count > 0)
  1042. {
  1043. // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  1044. }
  1045. var resendList = GetResendMessage();
  1046. foreach (var resendItem in resendList)
  1047. {
  1048. ClientData session;
  1049. if (clientDic.TryGetValue(resendItem.ChargePointSerialNumber, out session))
  1050. {
  1051. if (DateTime.UtcNow.Subtract(resendItem.SentOn).TotalSeconds > 1)
  1052. {
  1053. resendItem.SentTimes--;
  1054. resendItem.SentOn = DateTime.UtcNow;
  1055. Send(session, resendItem.SentMessage, string.Format("{0} {1}", resendItem.SentAction, "Request"), "");
  1056. }
  1057. }
  1058. }
  1059. foreach (var charger_SN in cmdMachineList)
  1060. {
  1061. ClientData session;
  1062. string uuid = string.Empty;
  1063. if (clientDic.TryGetValue(charger_SN, out session))
  1064. {
  1065. //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")));
  1066. if (session.IsCheckIn && !session.ISOCPP20)
  1067. {
  1068. string rawRequest = string.Empty;
  1069. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  1070. foreach (var item in cmdList)
  1071. {
  1072. IRequest request = null;
  1073. Actions action = Actions.None;
  1074. Enum.TryParse(item.OutAction, out action);
  1075. Type _RequestType = null;
  1076. for (int i = 0; i < profiles.Count; i++)
  1077. {
  1078. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  1079. if (feature != null)
  1080. {
  1081. _RequestType = feature.GetRequestType();
  1082. break;
  1083. }
  1084. }
  1085. if (_RequestType != null && item.CreatedBy != "Destroyer")
  1086. {
  1087. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  1088. uuid = session.queue.store(request);
  1089. rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
  1090. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1091. }
  1092. if (item.CreatedBy == "Destroyer")
  1093. {
  1094. if (_RequestType != null)
  1095. {
  1096. request = Activator.CreateInstance(_RequestType) as IRequest;
  1097. uuid = session.queue.store(request);
  1098. rawRequest = BasicMessageHandler.GenerateDestroyRequest(uuid, item.OutAction, item.OutRequest);
  1099. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1100. }
  1101. else
  1102. {
  1103. rawRequest = BasicMessageHandler.GenerateDestroyRequest(Guid.NewGuid().ToString(), item.OutAction, item.OutRequest);
  1104. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1105. }
  1106. }
  1107. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid, item.CreatedBy, rawRequest);
  1108. #region 更新資料表單一欄位
  1109. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.UtcNow };
  1110. db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  1111. db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  1112. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  1113. db.ServerMessage.Attach(_UpdatedItem);
  1114. _UpdatedItem.UpdatedOn = DateTime.UtcNow;
  1115. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  1116. db.SaveChanges();
  1117. #endregion
  1118. await Task.Delay(100);
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. await Task.Delay(500);
  1125. }
  1126. catch (Exception ex)
  1127. {
  1128. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  1129. }
  1130. }
  1131. }
  1132. async private void HeartBeatCheckTrigger()
  1133. {
  1134. for (; ; )
  1135. {
  1136. if (_ct.IsCancellationRequested)
  1137. {
  1138. break;
  1139. }
  1140. try
  1141. {
  1142. // if (DateTime.UtcNow.Subtract(lastcheckdt).TotalSeconds > 30)
  1143. {
  1144. // lastcheckdt = DateTime.UtcNow;
  1145. Stopwatch watch = new Stopwatch();
  1146. Dictionary<string, ClientData> _copyClientDic = null;
  1147. lock (_lockClientDic)
  1148. {
  1149. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1150. }
  1151. var cdt = DateTime.UtcNow;
  1152. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-120)).Select(x => x.Value).ToList();
  1153. watch.Start();
  1154. foreach (var session in clients)
  1155. {
  1156. using (var db = new MainDBContext())
  1157. {
  1158. using (var transaction = db.Database.BeginTransaction())
  1159. {
  1160. try
  1161. {
  1162. var machine = new Machine() { Id = session.MachineId };
  1163. if (machine != null)
  1164. {
  1165. db.Configuration.AutoDetectChangesEnabled = false;
  1166. db.Configuration.ValidateOnSaveEnabled = false;
  1167. db.Machine.Attach(machine);
  1168. machine.HeartbeatUpdatedOn = DateTime.UtcNow;
  1169. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  1170. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  1171. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  1172.                                             //await db.SaveChangesAsync();
  1173.                                             db.SaveChanges();
  1174. transaction.Commit();
  1175. }
  1176. }
  1177. catch (Exception ex)
  1178. {
  1179. transaction.Rollback();
  1180. }
  1181. }
  1182. }
  1183. }
  1184. watch.Stop();
  1185. if (watch.ElapsedMilliseconds / 1000 > 5)
  1186. {
  1187. logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  1188. }
  1189. }
  1190. await Task.Delay(10000);
  1191. }
  1192. catch (Exception ex)
  1193. {
  1194. Console.WriteLine("***********************************************************");
  1195. logger.Error(string.Format("HeartBeatCheckTrigger Ex:{0}", ex.ToString()));
  1196. }
  1197. }
  1198. }
  1199. async private void ServerSetFeeTrigger()
  1200. {
  1201. for (; ; )
  1202. {
  1203. if (_ct.IsCancellationRequested)
  1204. {
  1205. break;
  1206. }
  1207. var min_Interval = (DateTime.UtcNow - _CheckFeeDt).TotalMinutes;
  1208. if (min_Interval > 1)
  1209. {
  1210. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1211. Dictionary<string, ClientData> _copyClientDic = null;
  1212. lock (_lockClientDic)
  1213. {
  1214. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1215. }
  1216. _CheckFeeDt = DateTime.UtcNow;
  1217. foreach (var item in _copyClientDic)
  1218. {
  1219. try
  1220. {
  1221. ClientData session = item.Value;
  1222. if (session.IsCheckIn)
  1223. {
  1224. string displayPriceText = await SetDefaultFee(session);
  1225. if (!string.IsNullOrEmpty(displayPriceText) && displayPriceText != session.DisplayPrice)
  1226. {
  1227. clientDic[item.Key].DisplayPrice = displayPriceText;
  1228. using (var db = new MainDBContext())
  1229. {
  1230. db.ServerMessage.Add(new ServerMessage()
  1231. {
  1232. ChargeBoxId = session.ChargeBoxId,
  1233. CreatedBy = "Server",
  1234. CreatedOn = DateTime.UtcNow,
  1235. OutAction = Actions.ChangeConfiguration.ToString(),
  1236. OutRequest = JsonConvert.SerializeObject(
  1237. new ChangeConfigurationRequest()
  1238. {
  1239. key = "DefaultPrice",
  1240. value = clientDic[item.Key].DisplayPrice
  1241. },
  1242. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1243. SerialNo = Guid.NewGuid().ToString(),
  1244. InMessage = string.Empty
  1245. });
  1246. if (session.CustomerId == new Guid("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
  1247. {
  1248. db.ServerMessage.Add(new ServerMessage()
  1249. {
  1250. ChargeBoxId = session.ChargeBoxId,
  1251. CreatedBy = "Server",
  1252. CreatedOn = DateTime.UtcNow,
  1253. OutAction = Actions.ChangeConfiguration.ToString(),
  1254. OutRequest = JsonConvert.SerializeObject(
  1255. new ChangeConfigurationRequest()
  1256. {
  1257. key = "ConnectionTimeOut",
  1258. value = "120"
  1259. },
  1260. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1261. SerialNo = Guid.NewGuid().ToString(),
  1262. InMessage = string.Empty
  1263. });
  1264. db.ServerMessage.Add(new ServerMessage()
  1265. {
  1266. ChargeBoxId = session.ChargeBoxId,
  1267. CreatedBy = "Server",
  1268. CreatedOn = DateTime.UtcNow,
  1269. OutAction = Actions.ChangeConfiguration.ToString(),
  1270. OutRequest = JsonConvert.SerializeObject(
  1271. new ChangeConfigurationRequest()
  1272. {
  1273. key = "MeterValueSampleInterval",
  1274. value = "3"
  1275. },
  1276. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1277. SerialNo = Guid.NewGuid().ToString(),
  1278. InMessage = string.Empty
  1279. });
  1280. }
  1281. await db.SaveChangesAsync();
  1282. }
  1283. }
  1284. }
  1285. }
  1286. catch (Exception ex)
  1287. {
  1288. logger.Error(string.Format("ServerSetFeeTrigger ChargeBoxId:{0} Ex:{1}", item.Key, ex.ToString()));
  1289. }
  1290. }
  1291. }
  1292. await Task.Delay(1000);
  1293. }
  1294. }
  1295. async private void SmartChargingTrigger()
  1296. {
  1297. for (; ; )
  1298. {
  1299. if (_ct.IsCancellationRequested)
  1300. {
  1301. break;
  1302. }
  1303. var min_Interval = (DateTime.UtcNow - _CheckLBDt).TotalMinutes;
  1304. if (min_Interval > 1)
  1305. {
  1306. List<StationInfoDto> stations = null;
  1307. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1308. {
  1309. string strSql = "SELECT[Id],[LBMode],[LBCurrent] as Availability FROM [dbo].[Station] " +
  1310. "where LBMode = 1; ";
  1311. var result = await conn.QueryAsync<StationInfoDto>(strSql);
  1312. stations = result.ToList();
  1313. }
  1314. foreach (var station in stations)
  1315. {
  1316. var compareStation = _StationInfo.Where(x => x.Id == station.Id).FirstOrDefault();
  1317. if (compareStation == null || (station.Id == compareStation.Id && station.Availability != compareStation.Availability))
  1318. {
  1319. var _powerDic = await _loadingBalanceService.GetSettingPower(station.Id);
  1320. if (_powerDic != null)
  1321. {
  1322. foreach (var kv in _powerDic)
  1323. {
  1324. try
  1325. {
  1326. if (kv.Value.HasValue)
  1327. {
  1328. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  1329. }
  1330. }
  1331. catch (Exception ex)
  1332. {
  1333. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  1334. }
  1335. }
  1336. }
  1337. }
  1338. }
  1339. _StationInfo = stations;
  1340. _CheckLBDt = DateTime.UtcNow;
  1341. }
  1342. await Task.Delay(1000);
  1343. }
  1344. }
  1345. async private Task<string> SetDefaultFee(ClientData client)
  1346. {
  1347. string displayPriceText = string.Empty;
  1348. string charingPriceText = string.Empty;
  1349. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1350. try
  1351. {
  1352. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1353. {
  1354. var parameters = new DynamicParameters();
  1355. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input);
  1356. string displayPricestrSql = "";
  1357. string strSql = "";
  1358. if (client.IsAC)
  1359. {
  1360. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1361. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1362. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1363. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1364. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1365. }
  1366. else
  1367. {
  1368. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1369. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1370. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1371. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1372. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1373. }
  1374. var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1375. if (result.Count() == 0)
  1376. {
  1377. return string.Empty;
  1378. }
  1379. var stationPrice = result.First();
  1380. if (stationPrice.BillingMethod == 1)
  1381. {
  1382. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1383. client.ChargingPrices = chargingPriceResult.ToList();
  1384. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1385. {
  1386. client.ChargingPrices = new List<ChargingPrice>();
  1387. }
  1388. }
  1389. displayPriceText = stationPrice.FeeName;
  1390. client.BillingMethod = stationPrice.BillingMethod;
  1391. client.Currency = stationPrice.Currency;
  1392. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1393. client.ParkingFee = stationPrice.ParkingFee;
  1394. client.IsBilling = true;
  1395. }
  1396. }
  1397. catch (Exception ex)
  1398. {
  1399. logger.Error("SetDefaultFee", ex.ToString());
  1400. }
  1401. return displayPriceText;
  1402. }
  1403. async private void HealthCheckTrigger()
  1404. {
  1405. for (; ; )
  1406. {
  1407. if (_ct.IsCancellationRequested)
  1408. {
  1409. break;
  1410. }
  1411. try
  1412. {
  1413. Dictionary<string, ClientData> _copyClientDic = null;
  1414. lock (_lockClientDic)
  1415. {
  1416. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1417. }
  1418. var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.UtcNow.AddSeconds(-300)).Select(x => x.Value).ToList();
  1419. foreach (var session in removeClients)
  1420. {
  1421. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
  1422. RemoveClient(session);
  1423. }
  1424. await Task.Delay(60000);
  1425. }
  1426. catch (Exception ex)
  1427. {
  1428. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  1429. }
  1430. }
  1431. }
  1432. private List<NeedConfirmMessage> GetResendMessage()
  1433. {
  1434. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  1435. lock (_lockConfirmPacketList)
  1436. {
  1437. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  1438. }
  1439. return sendMessages;
  1440. }
  1441. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1442. {
  1443. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1444. _needConfirmMsg.Id = table_id;
  1445. _needConfirmMsg.SentAction = action;
  1446. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1447. _needConfirmMsg.SentTimes = 4;
  1448. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1449. _needConfirmMsg.RequestId = requestId;
  1450. _needConfirmMsg.SentUniqueId = msg_id;
  1451. _needConfirmMsg.CreatedBy = createdBy;
  1452. _needConfirmMsg.SentMessage = sendMessage;
  1453. if (needConfirmActions.Contains(action))
  1454. {
  1455. lock (_lockConfirmPacketList)
  1456. {
  1457. needConfirmPacketList.Add(_needConfirmMsg);
  1458. }
  1459. }
  1460. }
  1461. private void RemoveConfirmMessage()
  1462. {
  1463. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1464. lock (_lockConfirmPacketList)
  1465. {
  1466. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1467. foreach (var item in removeList)
  1468. {
  1469. needConfirmPacketList.Remove(item);
  1470. }
  1471. }
  1472. }
  1473. private bool ReConfirmMessage(MessageResult analysisResult)
  1474. {
  1475. bool confirmed = false;
  1476. if (needConfirmActions.Contains(analysisResult.Action))
  1477. {
  1478. NeedConfirmMessage foundRequest = null;
  1479. lock (_lockConfirmPacketList)
  1480. {
  1481. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1482. }
  1483. if (foundRequest != null && foundRequest.Id > 0)
  1484. {
  1485. foundRequest.SentTimes = 0;
  1486. foundRequest.SentInterval = 0;
  1487. analysisResult.RequestId = foundRequest.RequestId;
  1488. using (var db = new MainDBContext())
  1489. {
  1490. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  1491. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1492. sc.ReceivedOn = DateTime.UtcNow;
  1493. db.SaveChanges();
  1494. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1495. }
  1496. confirmed = true;
  1497. }
  1498. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1499. {
  1500. confirmed = true;
  1501. }
  1502. else
  1503. {
  1504. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1505. }
  1506. }
  1507. return confirmed;
  1508. }
  1509. private void RemoveClient(ClientData session)
  1510. {
  1511. if (session != null)
  1512. {
  1513. if (!string.IsNullOrEmpty(session.MachineId))
  1514. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1515. if (session.Connected)
  1516. {
  1517. session.Close(CloseReason.ServerShutdown);
  1518. }
  1519. RemoveClientDic(session);
  1520. try
  1521. {
  1522. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1523. // session.Close(CloseReason.ServerShutdown);
  1524. }
  1525. catch (Exception ex)
  1526. {
  1527. //logger.Warn("Close client socket error!!");
  1528. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1529. }
  1530. if (session != null)
  1531. {
  1532. session = null;
  1533. }
  1534. }
  1535. }
  1536. private void RemoveClientDic(ClientData session)
  1537. {
  1538. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  1539. {
  1540. lock (_lockClientDic)
  1541. {
  1542. if (clientDic.ContainsKey(session.ChargeBoxId))
  1543. {
  1544. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1545. {
  1546. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1547. clientDic.Remove(session.ChargeBoxId);
  1548. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1549. }
  1550. }
  1551. }
  1552. }
  1553. }
  1554. private void WarmUpLog()
  1555. {
  1556. try
  1557. {
  1558. using (var main = new MainDBContext())
  1559. {
  1560. main.Machine.Where(x => x.ChargeBoxId == "AAA").FirstOrDefault();
  1561. // log.MachineConnectionLog.ToList();
  1562. }
  1563. using (var log = new ConnectionLogDBContext())
  1564. {
  1565. log.MachineConnectionLog.ToList();
  1566. }
  1567. }
  1568. catch (Exception ex)
  1569. {
  1570. logger.Error(ex.ToString());
  1571. //Console.WriteLine(ex.ToString());
  1572. }
  1573. }
  1574. private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1575. {
  1576. try
  1577. {
  1578. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1579. if (clientData.ChargeBoxId == null)
  1580. {
  1581. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1582. }
  1583. using (var db = new ConnectionLogDBContext())
  1584. {
  1585. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  1586. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  1587. var dd = DateTime.UtcNow;
  1588. SqlParameter[] parameter =
  1589. {
  1590. new SqlParameter("CreatedOn",23){ Value=dd},
  1591. new SqlParameter("ChargeBoxId",50){ Value=clientData.ChargeBoxId==null?"unknown":clientData.ChargeBoxId.Replace("'","''")},
  1592. new SqlParameter("MessageType",50){ Value=messageType.Replace("'","''")},
  1593. new SqlParameter("Data",data.Replace("'","''")),
  1594. new SqlParameter("Msg",200){ Value=errorMsg.Replace("'","''")},
  1595. new SqlParameter("IsSent",1){ Value=isSent},
  1596. new SqlParameter("EVSEEndPoint",25){ Value=clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()},
  1597. new SqlParameter("Session",36){ Value=clientData.SessionID==null?"123":clientData.SessionID}
  1598. };
  1599. db.Database.ExecuteSqlCommand(sp, parameter);
  1600. }
  1601. }
  1602. catch (Exception ex)
  1603. {
  1604. Console.WriteLine(ex.ToString());
  1605. }
  1606. }
  1607. }
  1608. }