Code Monkey home page Code Monkey logo

mqttnet.aspnetcore.routing's Introduction

NuGet Badge License: MIT Build status

MQTTnet AspNetCore Routing

MQTTnet AspNetCore Routing is a fork of https://github.com/Atlas-LiftTech/MQTTnet.AspNetCore.AttributeRouting

This addon to MQTTnet provides the ability to define controllers and use attribute-based routing against message topics in a manner that is very similar to AspNet Core.

When should I use this library?

This library is a completely optional addon to MQTTnet (i.e. it is never required). You would WANT to use this if:

  • Your primary use case is validating/processing the MQTT messages on your server
  • Your server is not primarily sending data to clients via MQTT
  • You appreciate encapsulating your message processing logic in controllers in a way similar to AspNetCore and WebAPI

You can do everything that this addon does directly by using MQTTnet delegates yourself. However, as the amount of logic you write to validate or process incoming messages grows, the ability to organize your logic into controllers start to make much more sense. This library helps with organizing that code as well as bringing together your dependency injection framework to MQTTnet.

Features

  • Encapsulate your incoming message logic in controllers
  • Use familiar paradigms from AspNetCore in your MQTT logic (Controllers and Actions)
  • First-class support for dependency injection using existing ServiceProvider implementaiton in your AspNetCore project
  • Support for sync and async/await Actions on your controllers
  • Use together with any other MQTTnet options

Performance Note

This library has not been tested against a very high-load environment yet. Ensure you do your own load testing prior to use in production. All performance improvement PRs are welcome.

Supported frameworks

  • .NET Core 3.1+

Supported MQTT versions

  • 5.0.0
  • 3.1.1
  • 3.1.0

Nuget

This library is available as a nuget package: https://www.nuget.org/packages/MQTTnet.AspNetCore.Routing/

Usage

Install this package and MQTTnet from nuget. For dotnet CLI:

dotnet add package MQTTnet.AspNetCore.Routing

Example configuration on ASP.NET Core 6 MVC Configuration

using MQTTnet.AspNetCore;
using MQTTnet.AspNetCore.Routing;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(o =>
    {
        o.ListenAnyIP(iotaboardMqttSettings.Port, l => l.UseMqtt());
        o.ListenAnyIP(iotaboardHttpSettings.Port);
    }
);

// Configure MQTTServer service
builder.Services
    .AddHostedMqttServerWithServices(o =>
    {
        // other configurations
        o.WithoutDefaultEndpoint();
    })
    .AddMqttConnectionHandler()
    .AddConnections()
    .AddMqttControllers( // <== NOTICE THIS PART
    /*
        By default, all controllers within the executing assembly are
        discovered (just pass nothing here). To provide a list of assemblies
        explicitly, pass an array of Assembly[] here.
    */)
    /*
        optionally, set System.Text.Json serialization default for use with 
        [FromPayload] in the controllers. We can specify a JsonSerializerOptions
        or use JsonSerializerDefaults, useful for case-sensitivity or comment-handling
    */
    .AddMqttDefaultJsonOptions(new JsonSerializerOptions(JsonSerializerDefaults.Web)); 
    
var app = builder.Build();

app.MapControllers();
app.UseMqttServer(server => {  
    // other MqttServer configurations, for example client connect intercepts
    server.WithAttributeRouting(app.Services, allowUnmatchedRoutes: false);
});
app.Run();

Create your controllers by inheriting from MqttBaseController and adding actions to it like so:

[MqttController]
[MqttRoute("[controller]")] // Optional route prefix
public class MqttWeatherForecastController : MqttBaseController // Inherit from MqttBaseController for convenience functions
{
	private readonly ILogger<MqttWeatherForecastController> _logger;

	// Controllers have full support for dependency injection just like AspNetCore controllers
	public MqttWeatherForecastController(ILogger<MqttWeatherForecastController> logger)
	{
		_logger = logger;
	}

	// Supports template routing with typed constraints just like AspNetCore
	// Action routes compose together with the route prefix on the controller level
	[MqttRoute("{zipCode:int}/temperature")]
	public Task WeatherReport(int zipCode)
	{
		// We have access to the MqttContext
		if (zipCode != 90210) { MqttContext.CloseConnection = true; }

		// We have access to the raw message
		var temperature = BitConverter.ToDouble(Message.Payload);

		_logger.LogInformation($"It's {temperature} degrees in Hollywood");

		// Example validation
		if (temperature <= 0 || temperature >= 130)
		{
			return BadMessage();
		}

		return Ok();
	}
	
	// Supports binding JSON message payload to parameters with [FromPayload] attribute,
	// Similar to ASP.NET Core [FromBody]
	[MqttRoute("{deviceName}/telemetry")]
	public async Task NewTelemetry(string deviceName, [FromPayload] Telemetry telemetry)
	{
	    // here telemetry is JSON-deserialized from message payload to type Telemetry
		bool success = await DoSomething(telemetry);
		if (success) {
		    await Ok();
		    return;
		}
		else {
		    await BadMessage();
		    return;
		}
	}
}

See server example project here

See client example project here

Contributions

Contributions are welcome. Please open an issue to discuss your idea prior to sending a PR.

MIT License

See https://github.com/Atlas-LiftTech/MQTTnet.AspNetCore.AttributeRouting/LICENSE.

About Atlas LiftTech

This library is sponsored by Atlas Lift Tech. Atlas Lift Tech is a safe patient handling and mobility (SPHM) solution provider, helping hospitals improve patient outcomes and improve patient mobility.

mqttnet.aspnetcore.routing's People

Contributors

avishnyak avatar behroozbc avatar jfrancke avatar maikebing avatar mcaden avatar phenek avatar seikosantana avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

mqttnet.aspnetcore.routing's Issues

Dependency Injection Restrictions Preventing Use of MQTT Server Options

Describe the bug

I am unable to add the server options as mentioned below because my options require dependency injection. Therefore, I can't use the given example. Moreover, I've had to create my own background service to instantiate the MQTT server.
That gave me some null reference exceptions.

To Reproduce

Steps to reproduce the behavior:

  1. Try adding server options with dependencies injected.
  2. Notice that the below example can't be used:
startup
    services
        .AddHostedMqttServerWithServices(s =>
        {
            //Can't get ICertificateVaultManagerFactory here from dependency injection, because they are not injected yet. 
            s.WithoutDefaultEndpoint();
        })
        .AddMqttConnectionHandler()
        .AddConnections();

Expected behavior

I should be able to add server options even when there are dependencies that need to be injected.

Code example

To workaround this, I've created my own background service:

    public class MqttBroker : BackgroundService
    {
        private readonly IServiceProvider _services;
        private readonly ILogger<MqttBroker> _logger;
        private ICertificateRepository _certificateRepository;
        private CertVaultManager _mqttCertVault;

        public MqttBroker(IServiceProvider services, ILogger<MqttBroker> logger)
        {
            _services = services;
            _logger = logger;
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            using var scope = _services.CreateScope();
            _certificateRepository = scope.ServiceProvider.GetRequiredService<ICertificateRepository>();
            _mqttCertVault = scope.ServiceProvider.GetRequiredService<ICertVaultManagerFactory>().MqttCertVault();

            _logger.LogInformation("Starting service");
            await StartMqttServer();
            _logger.LogInformation("Service started");
            await base.StartAsync(cancellationToken);
        }
        
        private async Task StartMqttServer()
        {
          // Certificate setup
          var serverCertificate = ...; // Retrieve server certificate from dependency injection (vault & repository)
          var trustedCaCertificates = ...; // Retrieve trusted CA certificates from dependency injection (vault & repository)

          var optionsBuilder = new MqttServerOptionsBuilder()
              .WithEncryptedEndpoint()
              .WithEncryptedEndpointPort(/*specific port*/)
              .WithEncryptionCertificate(serverCertificate)
              .WithEncryptionSslProtocol(SslProtocols.Tls12)
              .WithClientCertificate(ValidateClientCertificate);

          var mqttServer = new MqttFactory().CreateMqttServer(optionsBuilder.Build());
          mqttServer.WithAttributeRouting(_services, true);
          // Additional setup methods...

          await mqttServer.StartAsync();
}

However, I've had to rely on WithAttributeRouting, which is marked as obsolete now, but it's indispensable in my scenario.

Additionally, when using a custom background service created after the service initialization, the following is always null because it as never been resolved in startup services:

var server = app.ApplicationServices.GetRequiredService<MqttServer>()

I'd like to shed light on two main points:

  1. I've started making modifications so that the library works only in my case. HERE the PR
    I removed unecessary
var server = app.ApplicationServices.GetRequiredService<MqttServer>();
  1. By doing this it's open a new interogation about singleton MqttRouter
    It would be beneficial to remove this, too make mqttRouter working great with multi mqttServer
services.AddSingleton<MqttRouter>();

because I added server property in MqttRouter class

public MqttServer Server { get; set; }

It means one MqttRouter per MqttServer.

The reason being, I am planning to have multiple instances of mqttServer on a single machine.
For instance, managing two MQTT ports: 8883 and 8884, both with TLS.

Because I might want to run

  • port: 8884 with an new CA certificate,
  • port: 8883 with a the old Ca certificate

making two distinct server certificates coexist on a single machine.

What do you think about this?

Yeah i need someone to think about this multi/custom hosted mqttServer :P
I hope you will share your thoughts. See you soon.

Async Action Example

Hi, i currently have this implementation of the controller:

[MqttController]
[MqttRoute("telemetry")]
public class DeviceTelemetryController: MqttBaseController
{
    public Task NewTelemetry()
    {
        return BadMessage();
    }
}

My question is, how to make the Action async?
Thanks in advance

WithAttributeRouting

How to use WithAttributeRouting? I was reading readme and the extension WithAttributeRouting is not there, instead it is

    public static void WithAttributeRouting(
      this MqttServer server,
      IServiceProvider svcProvider,
      bool allowUnmatchedRoutes = false)

How to get the IServiceProvider for this method?

Thanks in advance

Feature Request | Support for intercepting method invocations

Describe the feature request

I would like to be able to more easily do request- and performance logging of the controller methods. One way to generically implement this, could be to add support for an 'route invocation interceptor' that are called before- and after the controller method is invoked in the MqttRouter. This could allow for many different use cases apart from logging.

Describe the solution you'd like

In program.cs I would like the ability to configure .WithRouteInvocationInterceptor() with an type-reference to IRouteInvocationInterceptor that can be resolved via dependency injection.

public interface IRouteInvocationInterceptor {
    /// <summary>
    /// Executed before the route handler is executed
    /// </summary>
    /// <param name="clientId">The identifier of sender of the message</param>
    /// <param name="applicationMessage">The message being handled</param>
    /// <returns>Returns an opague object that may be used to correlate before- and after route execution. May be null</returns>
    Task<object?> RouteExecuting( string clientId, MqttApplicationMessage applicationMessage );
    
    /// <summary>
    /// Executed after the route handler has been executed.
    /// </summary>
    /// <param name="o">Set to the the response of <see cref="RouteExecuting(string, MqttApplicationMessage)"/>. May be null.</param>
    /// <param name="ex">An exception if the route handler failed. Otherwise null.</param>
    /// <returns></returns>
    Task RouteExecuted(object? o, Exception? ex);
}

If the interceptor is configured, it should be called in the MqttRouter.OnIncomingApplicationMessage method.

Describe alternatives you've considered

The alternative, currently, is to add logging to each individual controller method which is tedious and potentially error prone.

Please note

Please note that all names are purely suggestions ;)

When the server is Sending a Message, the message get descarded from the MqttRouter

Describe the bug

Inside one of the controller Route I'm using this code to send an message to all subscriber
// Now inject the new message at the broker.
await Server.InjectApplicationMessage(new InjectedMqttApplicationMessage(msg)
{
SenderClientId = MqttServerConstants.ClientId
});

But What I found is an error on the Logs saying that the Message will be drop

logger.LogDebug($"Rejecting message publish because '{context.ApplicationMessage.Topic}' did not match any known routes.");

To Reproduce

Steps to reproduce the behavior:

  1. Using this version of MQTTnet 4.X.X

  2. Create a controller then send a message using Server.InjectApplicationMessage

  3. Make sure you are using:
    app.UseMqttServer(server =>
    {
    server.WithAttributeRouting(app.ApplicationServices, allowUnmatchedRoutes: false);
    });

  4. See error.

Expected behavior

A clear and concise description of what you expected to happen.

Need the ability to ignore the Server message from the router
by maybe looking at the sender id

Screenshots

None

Additional context / logging

Using this example
https://github.com/dotnet/MQTTnet/blob/7f5c437c46dd52ecb1d53dfc8ea9fb8ff46caf5d/Samples/Server/Server_Simple_Samples.cs#L53C12-L53C55

dbug: MQTTnet.AspNetCore.Routing.MqttRouter[0]
      Rejecting message publish because 'route/path' did not match any known routes.

Authorized Publish and View Model Binding From Message Payload

This repository seems to be the most actively developed of all forks, so i think there may be a few ways where the library can be improved more.

Describe the feature request

For the routes, i think it will be nice to have something like ASP.NET Core's [Authorize] attribute which client validation method can be specified, and some way to deserialize the json payload in a action parameter decorated with [FromPayload] automatically if Authorize is successful or not present

Describe the solution you'd like

in ASP.NET Core we can have

[Route("{someNumber:int}"]
public async Task<IActionResult> SomeAction(int someNumber, [FromForm] SomeModel viewModel) {
  return Ok();
}

I think it's nice and streamlined way for the part to do stuff in a manner that is very similar to AspNet Core, so I'd imagine something like

[Authorize(Policy = "AuthorizedDevices")]
[MqttRoute("{someNumber:int}"]
public async Task SomeAction(int someNumber, [FromPayload] SomeModel viewModel) {
  // do something
  await Ok();
  return;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.