ProtalServer.cs 54 KB

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