ProtalServer.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. using EVCB_OCPP.Packet.Features;
  2. using EVCB_OCPP.Packet.Messages;
  3. using EVCB_OCPP.Packet.Messages.Basic;
  4. using EVCB_OCPP.Packet.Messages.Core;
  5. using EVCB_OCPP.WSServer.Dto;
  6. using EVCB_OCPP.WSServer.Helper;
  7. using EVCB_OCPP.WSServer.Message;
  8. using EVCB_OCPP.WSServer.Service;
  9. using Microsoft.Extensions.Hosting;
  10. using Newtonsoft.Json;
  11. using System.Data;
  12. using System.Diagnostics;
  13. using System.Xml.Linq;
  14. using NLog;
  15. using Microsoft.Extensions.Configuration;
  16. using System.Collections.Concurrent;
  17. using Microsoft.Extensions.Logging;
  18. using System.Net.WebSockets;
  19. using System.Net;
  20. using System.Text;
  21. using EVCB_OCPP.WSServer.Service.WsService;
  22. using System.ServiceModel.Channels;
  23. namespace EVCB_OCPP.WSServer
  24. {
  25. public class DestroyRequest : IRequest
  26. {
  27. public string Action { get; set; }
  28. public bool TransactionRelated()
  29. {
  30. return false;
  31. }
  32. public bool Validate()
  33. {
  34. return true;
  35. }
  36. }
  37. public class ProtalServer : IHostedService
  38. {
  39. //static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  40. public ProtalServer(
  41. ILogger<ProtalServer> logger
  42. , IConfiguration configuration
  43. , IMainDbService mainDbService
  44. , IConnectionLogdbService connectionLogdbService
  45. , LoadingBalanceService loadingBalanceService
  46. , ServerMessageService serverMessageService
  47. , WebDbService webDbService
  48. , ProfileHandler profileHandler
  49. , OcppWebsocketService websocketService
  50. , OuterHttpClient httpClient)
  51. {
  52. this.logger = logger;
  53. this.configuration = configuration;
  54. this.mainDbService = mainDbService;
  55. this.connectionLogdbService = connectionLogdbService;
  56. this.webDbService = webDbService;
  57. this.httpClient = httpClient;
  58. isInDocker = !string.IsNullOrEmpty(configuration["DOTNET_RUNNING_IN_CONTAINER"]);
  59. this.profileHandler = profileHandler;// new ProfileHandler(configuration, serviceProvider);
  60. this.websocketService = websocketService;
  61. this._loadingBalanceService = loadingBalanceService;// new LoadingBalanceService(mainDbConnectionFactory, webDbConnectionFactory);
  62. this.messageService = serverMessageService;
  63. WarmUpLog();
  64. }
  65. #region private fields
  66. private OuterHttpClient httpClient;
  67. private DateTime lastcheckdt = DateTime.UtcNow.AddSeconds(-20);
  68. private ConcurrentDictionary<string, WsClientData> clientDic = new ConcurrentDictionary<string, WsClientData>();
  69. //private readonly Object _lockClientDic = new object();
  70. private readonly Object _lockConfirmPacketList = new object();
  71. private readonly ILogger<ProtalServer> logger;
  72. private readonly IConfiguration configuration;
  73. private readonly IMainDbService mainDbService;
  74. private readonly IConnectionLogdbService connectionLogdbService;
  75. private readonly WebDbService webDbService;
  76. private readonly ProfileHandler profileHandler;
  77. private readonly OcppWebsocketService websocketService;
  78. private readonly bool isInDocker;
  79. private List<NeedConfirmMessage> needConfirmPacketList = new List<NeedConfirmMessage>();
  80. private DateTime checkUpdateDt = DateTime.UtcNow;
  81. private DateTime _CheckFeeDt = DateTime.UtcNow;
  82. private DateTime _CheckLBDt = DateTime.UtcNow;
  83. private DateTime _CheckDenyListDt = DateTime.UtcNow.AddDays(-1);
  84. private readonly LoadingBalanceService _loadingBalanceService;// = new LoadingBalanceService();
  85. private readonly ServerMessageService messageService;
  86. private List<StationInfoDto> _StationInfo = new List<StationInfoDto>();
  87. private readonly List<string> needConfirmActions = new List<string>()
  88. {
  89. "GetConfiguration",
  90. "ChangeConfiguration",
  91. "RemoteStartTransaction",
  92. "RemoteStopTransaction",
  93. "ChangeAvailability",
  94. "ClearCache",
  95. "DataTransfer",
  96. "Reset",
  97. "UnlockConnector",
  98. "TriggerMessage",
  99. "GetDiagnostics",
  100. "UpdateFirmware",
  101. "GetLocalListVersion",
  102. "SendLocalList",
  103. "SetChargingProfile",
  104. "ClearChargingProfile",
  105. "GetCompositeSchedule",
  106. "ReserveNow",
  107. "CancelReservation",
  108. "ExtendedTriggerMessage"
  109. };
  110. private readonly List<Profile> profiles = new List<Profile>()
  111. {
  112. new CoreProfile(),
  113. new FirmwareManagementProfile(),
  114. new ReservationProfile(),
  115. new RemoteTriggerProfile(),
  116. new SmartChargingProfile(),
  117. new LocalAuthListManagementProfile(),
  118. new SecurityProfile(),
  119. };
  120. #endregion
  121. //private OCPPWSServer appServer;
  122. //private WebApplication appApi;
  123. //private WebApplication yarpApp;
  124. internal Dictionary<string, WsClientData> GetClientDic()
  125. {
  126. Dictionary<string, WsClientData> toReturn = null;
  127. toReturn = new Dictionary<string, WsClientData>(clientDic);
  128. return toReturn;
  129. }
  130. internal List<NeedConfirmMessage> GetResendMessage()
  131. {
  132. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  133. lock (_lockConfirmPacketList)
  134. {
  135. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  136. }
  137. return sendMessages;
  138. }
  139. internal IReadOnlyList<Profile> Profiles => profiles.AsReadOnly();
  140. internal LoadingBalanceService LoadingBalanceService => _loadingBalanceService;
  141. internal ProfileHandler ProfileHandler => profileHandler;
  142. public async Task StartAsync(CancellationToken cancellationToken)
  143. {
  144. GlobalConfig.DenyModelNames = await webDbService.GetDenyModelNames();
  145. Start();
  146. return;
  147. }
  148. public Task StopAsync(CancellationToken cancellationToken)
  149. {
  150. Stop();
  151. return Task.CompletedTask;
  152. }
  153. internal void UpdateClientDisplayPrice(string key,string price)
  154. {
  155. clientDic[key].DisplayPrice = price;
  156. }
  157. internal void SendMsg(WsClientData session, string msg, string messageType, string errorMsg = "")
  158. {
  159. Send(session,msg,messageType,errorMsg);
  160. }
  161. internal void Start()
  162. {
  163. logger.LogTrace("Starting Server...");
  164. if (!GlobalConfig.LoadAPPConfig(configuration))
  165. {
  166. logger.LogError("Please check App.Config setting .");
  167. return;
  168. }
  169. StartWsService();
  170. if (!isInDocker)
  171. {
  172. Task consoleReadTask = new Task(RunConsoleInteractive);
  173. consoleReadTask.Start();
  174. //RunConsoleInteractive();
  175. return;
  176. }
  177. return;
  178. }
  179. private void RunConsoleInteractive()
  180. {
  181. while (true)
  182. {
  183. if (Console.In is null)
  184. {
  185. break;
  186. }
  187. var input = Console.ReadLine();
  188. switch (input.ToLower())
  189. {
  190. case "stop":
  191. Console.WriteLine("Command stop");
  192. Stop();
  193. break;
  194. case "gc":
  195. Console.WriteLine("Command GC");
  196. GC.Collect();
  197. break;
  198. case "lc":
  199. {
  200. Console.WriteLine("Command List Clients");
  201. Dictionary<string, WsClientData> _copyClientDic = null;
  202. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  203. var list = _copyClientDic.Select(c => c.Value).ToList();
  204. int i = 1;
  205. foreach (var c in list)
  206. {
  207. Console.WriteLine(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  208. i++;
  209. }
  210. }
  211. break;
  212. case "lcn":
  213. {
  214. Console.WriteLine("Command List Customer Name");
  215. Dictionary<string, WsClientData> _copyClientDic = null;
  216. _copyClientDic = new Dictionary<string, WsClientData>(clientDic);
  217. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  218. int iLcn = 1;
  219. foreach (var c in lcn)
  220. {
  221. Console.WriteLine(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  222. iLcn++;
  223. }
  224. }
  225. break;
  226. case "help":
  227. Console.WriteLine("Command help!!");
  228. Console.WriteLine("lcn : List Customer Name");
  229. Console.WriteLine("gc : GC Collect");
  230. Console.WriteLine("lc : List Clients");
  231. Console.WriteLine("cls : clear console");
  232. Console.WriteLine("silent : silent");
  233. Console.WriteLine("show : show log");
  234. // logger.Info("rcl : show Real Connection Limit");
  235. break;
  236. case "cls":
  237. Console.WriteLine("Command clear");
  238. Console.Clear();
  239. break;
  240. case "silent":
  241. Console.WriteLine("Command silent");
  242. //var xe = XElement.Load("NLog.config");
  243. //var xns = xe.GetDefaultNamespace();
  244. //var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  245. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  246. //if (minlevelattr != null)
  247. //{
  248. // minlevelattr.Value = "Warn";
  249. //}
  250. //xe.Save("NLog.config");
  251. foreach (var rule in LogManager.Configuration.LoggingRules)
  252. {
  253. if (rule.RuleName != "ConsoleLog")
  254. {
  255. continue;
  256. }
  257. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  258. if (isTargetRule)
  259. {
  260. rule.SetLoggingLevels(NLog.LogLevel.Warn, NLog.LogLevel.Off);
  261. }
  262. }
  263. break;
  264. case "show":
  265. Console.WriteLine("Command show");
  266. //var xe1 = XElement.Load("NLog.config");
  267. //var xns1 = xe1.GetDefaultNamespace();
  268. //var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  269. // .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  270. //if (minlevelattr1 != null)
  271. //{
  272. // minlevelattr1.Value = "trace";
  273. //}
  274. //xe1.Save("NLog.config");
  275. foreach (var rule in LogManager.Configuration.LoggingRules)
  276. {
  277. if (rule.RuleName != "ConsoleLog")
  278. {
  279. continue;
  280. }
  281. var isTargetRule = rule.Targets.Any(x => x.Name.ToLower() == "console");
  282. if (isTargetRule)
  283. {
  284. rule.SetLoggingLevels(NLog.LogLevel.Trace, NLog.LogLevel.Off);
  285. }
  286. }
  287. break;
  288. case "rcl":
  289. break;
  290. default:
  291. break;
  292. }
  293. }
  294. }
  295. internal void Stop()
  296. {
  297. //appServer?.Stop();
  298. StopWsService();
  299. }
  300. private void StartWsService()
  301. {
  302. websocketService.NewSessionConnected += AppServer_NewSessionConnected;
  303. }
  304. private void StopWsService()
  305. {
  306. websocketService.NewSessionConnected -= AppServer_NewSessionConnected;
  307. }
  308. private async void AppServer_NewSessionConnected(object sender, WsClientData session)
  309. {
  310. logger.LogDebug(string.Format("{0} NewSessionConnected", session.Path));
  311. try
  312. {
  313. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : session.SecWebSocketProtocol.Contains("ocpp2.0") ? false : true;
  314. if (isNotSupported)
  315. {
  316. //logger.LogDebug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  317. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  318. return;
  319. }
  320. TryRemoveDuplicatedSession(session);
  321. clientDic[session.ChargeBoxId] = session;
  322. session.SessionClosed += AppServer_SessionClosed;
  323. session.m_ReceiveData += ReceivedMessageTimeLimited;
  324. // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  325. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  326. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.UriScheme.Contains("wss") ? 2 : 1);
  327. }
  328. catch (Exception ex)
  329. {
  330. logger.LogError(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  331. }
  332. }
  333. private void AppServer_SessionClosed(object sender, string closeReason)
  334. {
  335. if (sender is not WsClientData session)
  336. {
  337. return;
  338. }
  339. session.SessionClosed -= AppServer_SessionClosed;
  340. session.m_ReceiveData -= ReceivedMessageTimeLimited;
  341. WriteMachineLog(session, string.Format("CloseReason: {0}", closeReason), "Connection", "");
  342. RemoveClient(session);
  343. }
  344. private void TryRemoveDuplicatedSession(WsClientData session)
  345. {
  346. if (clientDic.ContainsKey(session.ChargeBoxId))
  347. {
  348. var oldSession = clientDic[session.ChargeBoxId];
  349. WriteMachineLog(oldSession, "Duplicate Logins", "Connection", "");
  350. RemoveClient(oldSession);
  351. }
  352. }
  353. async private void ReceivedMessageTimeLimited(object sender , string rawdata)
  354. {
  355. if (sender is not WsClientData session)
  356. {
  357. return;
  358. }
  359. CancellationTokenSource tokenSource = new();
  360. var task = ReceivedMessage(session, rawdata);
  361. var completedTask = await Task.WhenAny(task, Task.Delay(90_000, tokenSource.Token));
  362. if (completedTask != task)
  363. {
  364. logger.LogCritical("Process timeout: {0} ", rawdata);
  365. await task;
  366. return;
  367. }
  368. tokenSource.Cancel();
  369. return;
  370. }
  371. async private Task ReceivedMessage(WsClientData session, string rawdata)
  372. {
  373. try
  374. {
  375. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  376. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  377. WriteMachineLog(session, rawdata,
  378. 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);
  379. if (session.ResetSecurityProfile)
  380. {
  381. logger.LogError(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.UtcNow, session.ChargeBoxId));
  382. RemoveClient(session);
  383. return;
  384. }
  385. if (!analysisResult.Success)
  386. {
  387. //解析RawData就發生錯誤
  388. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  389. {
  390. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  391. }
  392. else
  393. {
  394. if (analysisResult.Message == null)
  395. {
  396. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  397. string errorMsg = string.Empty;
  398. if (analysisResult.Exception != null)
  399. {
  400. errorMsg = analysisResult.Exception.ToString();
  401. }
  402. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  403. }
  404. else
  405. {
  406. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  407. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  408. string errorMsg = string.Empty;
  409. if (analysisResult.Exception != null)
  410. {
  411. errorMsg = analysisResult.Exception.ToString();
  412. }
  413. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  414. }
  415. }
  416. }
  417. else
  418. {
  419. switch (analysisResult.Id)
  420. {
  421. case BasicMessageHandler.TYPENUMBER_CALL:
  422. {
  423. if (!session.ISOCPP20)
  424. {
  425. Actions action = Convertor.GetAction(analysisResult.Action);
  426. try
  427. {
  428. await ProcessRequestMessage(analysisResult, session, action);
  429. }
  430. catch (Exception e)
  431. {
  432. logger.LogError($"Processing {action} exception!");
  433. throw;
  434. }
  435. }
  436. else
  437. {
  438. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  439. MessageResult result = new MessageResult() { Success = true };
  440. //ocpp20 處理
  441. switch (action)
  442. {
  443. case EVCB_OCPP20.Packet.Features.Actions.BootNotification:
  444. {
  445. EVCB_OCPP20.Packet.Messages.BootNotificationRequest _request = (EVCB_OCPP20.Packet.Messages.IRequest)analysisResult.Message as EVCB_OCPP20.Packet.Messages.BootNotificationRequest;
  446. var confirm = new EVCB_OCPP20.Packet.Messages.BootNotificationResponse() { CurrentTime = DateTime.UtcNow, Interval = 180, Status = EVCB_OCPP20.Packet.DataTypes.EnumTypes.RegistrationStatusEnumType.Pending };
  447. result.Message = confirm;
  448. result.Success = true;
  449. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (EVCB_OCPP20.Packet.Messages.IConfirmation)result.Message);
  450. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  451. var request = new EVCB_OCPP20.Packet.Messages.SetNetworkProfileRequest()
  452. {
  453. ConfigurationSlot = 1,
  454. ConnectionData = new EVCB_OCPP20.Packet.DataTypes.NetworkConnectionProfileType()
  455. {
  456. OcppVersion = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPVersionEnumType.OCPP20,
  457. OcppTransport = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPTransportEnumType.JSON,
  458. MessageTimeout = 30,
  459. OcppCsmsUrl = session.UriScheme == "ws" ? GlobalConfig.OCPP20_WSUrl : GlobalConfig.OCPP20_WSSUrl,
  460. OcppInterface = EVCB_OCPP20.Packet.DataTypes.EnumTypes.OCPPInterfaceEnumType.Wired0
  461. }
  462. };
  463. var uuid = session.queue20.store(request);
  464. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetNetworkProfile", request);
  465. Send(session, requestText, "SetNetworkProfile");
  466. }
  467. break;
  468. default:
  469. {
  470. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  471. }
  472. break;
  473. }
  474. }
  475. }
  476. break;
  477. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  478. {
  479. if (!session.ISOCPP20)
  480. {
  481. Actions action = Convertor.GetAction(analysisResult.Action);
  482. ProcessConfirmationMessage(analysisResult, session, action);
  483. }
  484. else
  485. {
  486. EVCB_OCPP20.Packet.Features.Actions action = Convertor.GetActionby20(analysisResult.Action);
  487. MessageResult result = new MessageResult() { Success = true };
  488. //ocpp20 處理
  489. switch (action)
  490. {
  491. case EVCB_OCPP20.Packet.Features.Actions.SetNetworkProfile:
  492. {
  493. EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetNetworkProfileResponse;
  494. if (response.Status == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetNetworkProfileStatusEnumType.Accepted)
  495. {
  496. var request = new EVCB_OCPP20.Packet.Messages.SetVariablesRequest()
  497. {
  498. SetVariableData = new List<EVCB_OCPP20.Packet.DataTypes.SetVariableDataType>()
  499. {
  500. new EVCB_OCPP20.Packet.DataTypes.SetVariableDataType()
  501. {
  502. Component=new EVCB_OCPP20.Packet.DataTypes.ComponentType()
  503. {
  504. Name="OCPPCommCtrlr",
  505. },
  506. AttributeType= EVCB_OCPP20.Packet.DataTypes.EnumTypes.AttributeEnumType.Actual,
  507. AttributeValue= JsonConvert.SerializeObject(new List<int>(){ 1 }),
  508. Variable=new EVCB_OCPP20.Packet.DataTypes.VariableType()
  509. {
  510. Name="NetworkConfigurationPriority",
  511. }
  512. }
  513. }
  514. };
  515. var uuid = session.queue20.store(request);
  516. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "SetVariables", request);
  517. Send(session, requestText, "SetVariables");
  518. }
  519. }
  520. break;
  521. case EVCB_OCPP20.Packet.Features.Actions.SetVariables:
  522. {
  523. EVCB_OCPP20.Packet.Messages.SetVariablesResponse response = (EVCB_OCPP20.Packet.Messages.IConfirmation)analysisResult.Message as EVCB_OCPP20.Packet.Messages.SetVariablesResponse;
  524. if (response.SetVariableResult[0].AttributeStatus == EVCB_OCPP20.Packet.DataTypes.EnumTypes.SetVariableStatusEnumType.RebootRequired)
  525. {
  526. var request = new EVCB_OCPP20.Packet.Messages.ResetRequest()
  527. {
  528. Type = EVCB_OCPP20.Packet.DataTypes.EnumTypes.ResetEnumType.OnIdle
  529. };
  530. var uuid = session.queue20.store(request);
  531. string requestText = BasicMessageHandler.GenerateRequestofOCPP20(uuid, "Reset", request);
  532. Send(session, requestText, "Reset");
  533. }
  534. }
  535. break;
  536. default:
  537. {
  538. logger.LogError(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  539. }
  540. break;
  541. }
  542. }
  543. }
  544. break;
  545. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  546. {
  547. //只處理 丟出Request 收到Error的訊息
  548. if (analysisResult.Success && analysisResult.Message != null)
  549. {
  550. Actions action = Convertor.GetAction(analysisResult.Action);
  551. ProcessErrorMessage(analysisResult, session, action);
  552. }
  553. }
  554. break;
  555. default:
  556. {
  557. logger.LogError(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  558. }
  559. break;
  560. }
  561. }
  562. await Task.Delay(10);
  563. }
  564. catch (Exception ex)
  565. {
  566. if (ex.InnerException != null)
  567. {
  568. logger.LogError(string.Format("{0} **Inner Exception :{1} ", session.ChargeBoxId + rawdata, ex.ToString()));
  569. }
  570. else
  571. {
  572. logger.LogError(string.Format("{0} **Exception :{1} ", session.ChargeBoxId, ex.ToString()));
  573. }
  574. }
  575. }
  576. private async Task ProcessRequestMessage(MessageResult analysisResult, WsClientData session, Actions action)
  577. {
  578. Stopwatch outter_stopwatch = Stopwatch.StartNew();
  579. //BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  580. if (!session.IsCheckIn && action != Actions.BootNotification)
  581. {
  582. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  583. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  584. return;
  585. }
  586. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  587. switch (profileName)
  588. {
  589. case "Core":
  590. {
  591. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  592. var sendTimer = Stopwatch.StartNew();
  593. if (replyResult.Success)
  594. {
  595. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  596. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception is null ? string.Empty : replyResult.Exception.ToString());
  597. if (action == Actions.BootNotification
  598. && replyResult.Message is BootNotificationConfirmation bootNotificationConfirmation)
  599. {
  600. if (bootNotificationConfirmation.status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  601. {
  602. session.IsCheckIn = true;
  603. await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId);
  604. await messageService.SendChangeConfigurationRequest(
  605. session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
  606. await messageService.SendDataTransferRequest(
  607. session.ChargeBoxId,
  608. messageId:"ID_FirmwareVersion",
  609. vendorId: "Phihong Technology",
  610. data: string.Empty);
  611. }
  612. else
  613. {
  614. bool? isAC = await mainDbService.GetChargeBoxIdIsAc(session.ChargeBoxId);
  615. if (isAC is not null)
  616. {
  617. session.IsAC = isAC.Value;
  618. }
  619. await mainDbService.UpdateMachineConnectionType(session.ChargeBoxId, session.UriScheme.Contains("wss") ? 2 : 1);
  620. await webDbService.SetDefaultFee(session);
  621. }
  622. }
  623. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  624. {
  625. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  626. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  627. {
  628. await messageService.SendDataTransferRequest(
  629. session.ChargeBoxId,
  630. messageId: "SetUserPrice",
  631. vendorId:"Phihong Technology",
  632. data: JsonConvert.SerializeObject(
  633. new
  634. {
  635. idToken = authorizeRequest.idTag,
  636. price = session.UserDisplayPrices[authorizeRequest.idTag]
  637. })
  638. );
  639. }
  640. }
  641. }
  642. else
  643. {
  644. if (action == Actions.StopTransaction && replyResult.CallErrorMsg == "Reject Response Message")
  645. {
  646. //do nothing
  647. }
  648. else
  649. {
  650. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  651. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  652. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  653. }
  654. }
  655. sendTimer.Stop();
  656. if(sendTimer.ElapsedMilliseconds/1000 > 1)
  657. {
  658. logger.LogCritical("ProcessRequestMessage Send Cost {time} sec", sendTimer.ElapsedMilliseconds / 1000);
  659. }
  660. if (action == Actions.StartTransaction)
  661. {
  662. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  663. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  664. if (_powerDic != null)
  665. {
  666. foreach (var kv in _powerDic)
  667. {
  668. try
  669. {
  670. if (kv.Value.HasValue)
  671. {
  672. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  673. }
  674. }
  675. catch (Exception ex)
  676. {
  677. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  678. }
  679. }
  680. }
  681. }
  682. if (action == Actions.StopTransaction)
  683. {
  684. var stationId = await _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  685. var _powerDic = await _loadingBalanceService.GetSettingPower(stationId);
  686. if (_powerDic != null)
  687. {
  688. foreach (var kv in _powerDic)
  689. {
  690. try
  691. {
  692. if (kv.Value.HasValue)
  693. {
  694. profileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  695. }
  696. }
  697. catch (Exception ex)
  698. {
  699. logger.LogError(string.Format("Set Profile Exception: {0}", ex.ToString()));
  700. }
  701. }
  702. }
  703. }
  704. }
  705. break;
  706. case "FirmwareManagement":
  707. {
  708. var replyResult = await profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  709. if (replyResult.Success)
  710. {
  711. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  712. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  713. }
  714. else
  715. {
  716. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  717. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  718. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  719. }
  720. }
  721. break;
  722. case "Security":
  723. {
  724. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  725. if (replyResult.Success)
  726. {
  727. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  728. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  729. }
  730. else
  731. {
  732. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  733. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  734. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  735. }
  736. }
  737. break;
  738. default:
  739. {
  740. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  741. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  742. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  743. }
  744. break;
  745. }
  746. outter_stopwatch.Stop();
  747. if (outter_stopwatch.ElapsedMilliseconds > 1000)
  748. {
  749. logger.LogCritical("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
  750. }
  751. }
  752. async private void ProcessConfirmationMessage(MessageResult analysisResult, WsClientData session, Actions action)
  753. {
  754. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  755. if (await ReConfirmMessage(analysisResult))
  756. {
  757. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  758. MessageResult confirmResult = null;
  759. switch (profileName)
  760. {
  761. case "Core":
  762. {
  763. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  764. }
  765. break;
  766. case "FirmwareManagement":
  767. {
  768. confirmResult = await profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  769. }
  770. break;
  771. case "RemoteTrigger":
  772. {
  773. confirmResult = await profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  774. }
  775. break;
  776. case "Reservation":
  777. {
  778. confirmResult = await profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  779. }
  780. break;
  781. case "LocalAuthListManagement":
  782. {
  783. confirmResult = await profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  784. }
  785. break;
  786. case "SmartCharging":
  787. {
  788. confirmResult = await profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  789. }
  790. break;
  791. case "Security":
  792. {
  793. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  794. }
  795. break;
  796. default:
  797. {
  798. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  799. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  800. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  801. }
  802. break;
  803. }
  804. if (confirmResult == null || !confirmResult.Success)
  805. {
  806. logger.LogError(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  807. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  808. }
  809. }
  810. else
  811. {
  812. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  813. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  814. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  815. }
  816. }
  817. private async void ProcessErrorMessage(MessageResult analysisResult, WsClientData session, Actions action)
  818. {
  819. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  820. if (await ReConfirmMessage(analysisResult))
  821. {
  822. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  823. switch (profileName)
  824. {
  825. case "Core":
  826. {
  827. _ = profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  828. }
  829. break;
  830. case "FirmwareManagement":
  831. {
  832. _ = profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  833. }
  834. break;
  835. case "RemoteTrigger":
  836. {
  837. _ = profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  838. }
  839. break;
  840. case "Reservation":
  841. {
  842. _ = profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  843. }
  844. break;
  845. case "LocalAuthListManagement":
  846. {
  847. _ = profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  848. }
  849. break;
  850. case "SmartCharging":
  851. {
  852. _ = profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  853. }
  854. break;
  855. default:
  856. {
  857. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  858. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  859. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  860. }
  861. break;
  862. }
  863. }
  864. else
  865. {
  866. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  867. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  868. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  869. }
  870. }
  871. private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
  872. {
  873. try
  874. {
  875. if (session != null)
  876. {
  877. WriteMachineLog(session, msg, messageType, errorMsg, true);
  878. session.Send(msg);
  879. }
  880. }
  881. catch (Exception ex)
  882. {
  883. logger.LogError(string.Format("Send Ex:{0}", ex.ToString()));
  884. }
  885. }
  886. internal void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  887. {
  888. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  889. _needConfirmMsg.Id = table_id;
  890. _needConfirmMsg.SentAction = action;
  891. _needConfirmMsg.SentOn = DateTime.UtcNow;
  892. _needConfirmMsg.SentTimes = 4;
  893. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  894. _needConfirmMsg.RequestId = requestId;
  895. _needConfirmMsg.SentUniqueId = msg_id;
  896. _needConfirmMsg.CreatedBy = createdBy;
  897. _needConfirmMsg.SentMessage = sendMessage;
  898. if (needConfirmActions.Contains(action))
  899. {
  900. lock (_lockConfirmPacketList)
  901. {
  902. needConfirmPacketList.Add(_needConfirmMsg);
  903. }
  904. }
  905. }
  906. internal void RemoveConfirmMessage()
  907. {
  908. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  909. lock (_lockConfirmPacketList)
  910. {
  911. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  912. foreach (var item in removeList)
  913. {
  914. needConfirmPacketList.Remove(item);
  915. }
  916. }
  917. }
  918. private async Task<bool> ReConfirmMessage(MessageResult analysisResult)
  919. {
  920. bool confirmed = false;
  921. if (needConfirmActions.Contains(analysisResult.Action))
  922. {
  923. NeedConfirmMessage foundRequest = null;
  924. lock (_lockConfirmPacketList)
  925. {
  926. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  927. }
  928. if (foundRequest != null && foundRequest.Id > 0)
  929. {
  930. foundRequest.SentTimes = 0;
  931. foundRequest.SentInterval = 0;
  932. analysisResult.RequestId = foundRequest.RequestId;
  933. await mainDbService.UpdateServerMessage(foundRequest.Id, inMessage: JsonConvert.SerializeObject(analysisResult.Message, Formatting.None), receivedOn: DateTime.UtcNow);
  934. confirmed = true;
  935. }
  936. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  937. {
  938. confirmed = true;
  939. }
  940. else
  941. {
  942. logger.LogError(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  943. }
  944. }
  945. return confirmed;
  946. }
  947. internal async void RemoveClient(WsClientData session)
  948. {
  949. if (session is null)
  950. {
  951. return;
  952. }
  953. if (!string.IsNullOrEmpty(session.MachineId))
  954. logger.LogTrace("RemoveClient[" + session.ChargeBoxId + "]");
  955. RemoveClientDic(session);
  956. try
  957. {
  958. if (session.State == WebSocketState.Open)
  959. {
  960. await session.Close();
  961. }
  962. //session.m_ReceiveData -= ReceivedMessageTimeLimited;
  963. // session.Close(CloseReason.ServerShutdown);
  964. }
  965. catch (Exception ex)
  966. {
  967. //logger.LogWarning("Close client socket error!!");
  968. logger.LogWarning(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  969. }
  970. }
  971. private void RemoveClientDic(WsClientData session)
  972. {
  973. if (string.IsNullOrEmpty(session.ChargeBoxId) ||
  974. !clientDic.ContainsKey(session.ChargeBoxId) ||
  975. clientDic[session.ChargeBoxId].SessionID != session.SessionID)
  976. {
  977. return;
  978. }
  979. logger.LogDebug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  980. clientDic.Remove(session.ChargeBoxId, out _);
  981. logger.LogTrace("RemoveClient ContainsKey " + session.ChargeBoxId);
  982. }
  983. private void WarmUpLog()
  984. {
  985. connectionLogdbService.WarmUpLog();
  986. }
  987. private void WriteMachineLog(WsClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  988. {
  989. try
  990. {
  991. if (clientData == null || string.IsNullOrEmpty(data)) return;
  992. if (clientData.ChargeBoxId == null)
  993. {
  994. logger.LogCritical(clientData.Path.ToString() + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  995. }
  996. connectionLogdbService.WriteMachineLog(clientData, data, messageType, errorMsg, isSent);
  997. }
  998. catch (Exception ex)
  999. {
  1000. //Console.WriteLine(ex.ToString());
  1001. logger.LogError(ex,ex.Message);
  1002. }
  1003. }
  1004. }
  1005. }