using Microsoft.AspNetCore.Http.Connections; using MQTTnet.AspNetCore; using MQTTnet.Server; namespace iotweb { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseKestrel(o => { o.ListenAnyIP(1883, l => l.UseMqtt()); o.ListenAnyIP(5000); }); builder.Services.AddMqttServer(optionsBuilder => { optionsBuilder.WithDefaultEndpoint(); }); builder.Services.AddMqttConnectionHandler(); builder.Services.AddConnections(); builder.Services.AddSingleton(); builder.Services.AddControllers(); var app = builder.Build(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints((endpoints) => { endpoints.MapConnectionHandler("/mqtt", ConfigureWebSocketOptions); }); app.UseMqttServer( server => { server.ValidatingConnectionAsync += Server_ValidatingConnectionAsync; ; server.ClientConnectedAsync += Server_ClientConnectedAsync; }); app.MapControllers(); app.Run(); } private static void ConfigureWebSocketOptions(HttpConnectionDispatcherOptions options) { options.WebSockets.SubProtocolSelector = new Func, string>((IList protocols) => { return protocols.FirstOrDefault() ?? "mqtt"; }); } private static Task Server_ClientConnectedAsync(ClientConnectedEventArgs arg) { return Task.CompletedTask; } private static Task Server_ValidatingConnectionAsync(ValidatingConnectionEventArgs arg) { Console.WriteLine(arg.ClientId); return Task.CompletedTask; } } sealed class MqttController { public MqttController() { // Inject other services via constructor. } public Task OnClientConnected(ClientConnectedEventArgs eventArgs) { Console.WriteLine($"Client '{eventArgs.ClientId}' connected."); return Task.CompletedTask; } public Task ValidateConnection(ValidatingConnectionEventArgs eventArgs) { Console.WriteLine($"Client '{eventArgs.ClientId}' wants to connect. Accepting!"); return Task.CompletedTask; } } }