12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using Newtonsoft.Json;
- using System.Net.WebSockets;
- namespace EVCB_OCPP.WSServer.Service.WsService;
- public static class AppExtention
- {
- public static void AddOcppWsServer(this IServiceCollection services)
- {
- services.AddTransient<WsClientData>();
- services.AddSingleton<OcppWebsocketService>();
- }
- public static void MapOcppWsService(this WebApplication webApplication)
- {
- webApplication.UseWebSockets(new WebSocketOptions()
- {
- KeepAliveInterval = TimeSpan.FromSeconds(10)
- });
- webApplication.Use(async (context, next) =>
- {
- if (!context.WebSockets.IsWebSocketRequest)
- {
- await next(context);
- return;
- }
- var servcie = context.RequestServices.GetService<OcppWebsocketService>();
- await servcie.AcceptWebSocket(context);
- return;
- });
- }
- }
- public class OcppWebsocketService : WebsocketService<WsClientData>
- {
- public static List<string> protocals = new List<string>() { "", "ocpp1.6", "ocpp2.0.1" };
- private readonly ILogger<OcppWebsocketService> logger;
- public OcppWebsocketService(
- IServiceProvider serviceProvider,
- ILogger<OcppWebsocketService> logger
- ) : base(serviceProvider)
- {
- this.logger = logger;
- }
- internal override async ValueTask<string> AcceptWebSocketHandler(HttpContext context)
- {
- logger.LogInformation("{function}:{Path}/{SubProtocol}", nameof(AcceptWebSocketHandler), context.Request.Path, context.WebSockets.WebSocketRequestedProtocols);
- var protocol = GetSupportedPortocol(context.WebSockets.WebSocketRequestedProtocols, protocals);
- if (string.IsNullOrEmpty(protocol))
- {
- logger.LogInformation("{function}:{Path} Protocol Not Supported, Disconnecting", nameof(AcceptWebSocketHandler), context.Request.Path);
- using WebSocket toRejectwebSocket = await context.WebSockets.AcceptWebSocketAsync();
- await toRejectwebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default);
- return string.Empty;
- }
- return protocol;
- }
- private static string GetSupportedPortocol(IList<string> clientProtocols, IList<string> supportedProtocols)
- {
- int supportedProtocolIndex = supportedProtocols.Count - 1;
- for (; supportedProtocolIndex >= 0; supportedProtocolIndex--)
- {
- var testProtocol = supportedProtocols[supportedProtocolIndex];
- if (clientProtocols.Contains(testProtocol))
- {
- return testProtocol;
- }
- }
- return string.Empty;
- }
- }
|