-
Couldn't load subscription status.
- Fork 24
Add shared MQTT client and ResourceManagement-based MQTT integration service #720
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MathoMathiasCamara
wants to merge
17
commits into
pre-release
Choose a base branch
from
feature/mqtt
base: pre-release
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
f68be8c
Expose ResourceChanged notifications from ResourceManagement as a non…
MathoMathiasCamara ec77e39
Add support for a shared MQTT.IMqttClient .
MathoMathiasCamara 0ee40da
add upload step in new CI workflow
MathoMathiasCamara 32b8e49
Update version and Trigger CI
MathoMathiasCamara d69d8dc
Trigger CI
MathoMathiasCamara 12761dc
Merge branch 'pre-release' into feature/mqtt
MathoMathiasCamara 3532480
Spell check correction
MathoMathiasCamara d25b0e6
Trigger CI
MathoMathiasCamara 5e0489f
Merge branch 'pre-release' into feature/mqtt
MathoMathiasCamara 4d9e61f
Update license attribution
MathoMathiasCamara 258e19f
Trigger Pipeline
MathoMathiasCamara 9be6f51
add pack attribute to MQTT projects to publish packages.
MathoMathiasCamara 734d7d2
update license text and link
MathoMathiasCamara 8a3546f
make *.Mqtt projects packable
MathoMathiasCamara 66ddca0
Add more documentations
MathoMathiasCamara 746b6b4
Add exception to describe missing resource or method and improve docu…
MathoMathiasCamara a12af5d
Fail when required dependencies are null
MathoMathiasCamara File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,3 @@ | ||
|
|
||
| Apache License | ||
| Version 2.0, January 2004 | ||
| http://www.apache.org/licenses/ | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| 8.5.3 | ||
| 8.6.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,265 @@ | ||
| # The goal: | ||
|
|
||
| The goal is to allow any MORYX developer to create their own Mqtt To MORYX facade, that way you can use Mqtt to communicate to with any MORYX facade ex: `ProductManagement`,`ResourceManagement` etc. | ||
|
|
||
| To achieve that, we took inspiration from 3 repositories : | ||
|
|
||
| 1. [Hosted Mqtt Server](https://github.com/dotnet/MQTTnet/wiki/Server) | ||
| 2. [How to use Mqtt as a service in asp.net controller](https://github.com/rafiulgits/mqtt-client-dotnet-core) | ||
| 3. [Mqtt AttributeRouting](https://www.nuget.org/packages/MQTTnet.AspNetCore.AttributeRouting) | ||
|
|
||
| _Checking those repositories will give you an idea of what the `ManagedMqtt` is trying to achieve._ | ||
|
|
||
| # APIs and classes | ||
|
|
||
| #### IManagedMqttClient : | ||
| A managed `IMqttClient` from the [MQTTnet](https://github.com/dotnet/MQTTnet) extensions package. | ||
| #### IMqttService : | ||
| Preferred base class for all services based on Mqtt . | ||
| #### IMqttEndpoint : | ||
| Mqtt Endpoint interface. Every endpoint will implement this interface. | ||
|
|
||
| # Usage: | ||
|
|
||
| To use the `IManagedMqttClient` you need to configure it in the `Program.cs` like so: | ||
|
|
||
| ```cs | ||
| builder.Services.AddMqttClient(); | ||
| ``` | ||
| Optionally you can also configure the Mqtt client connection details like so : | ||
| ```cs | ||
| builder.Services.AddMqttClient(options => | ||
| { | ||
| options.Connection = new MqttConnectionConfig | ||
| { | ||
| Port = 1883, | ||
| Id = "EndpointDemo1", | ||
| Host = "localhost", | ||
| QoS = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, | ||
| RootTopic = "mqtt/moryx" | ||
| }; | ||
| // optional: add your custom converter/serializer | ||
| options.JsonSerializerOptions.Converters.Add(new MyConverter()) | ||
| }) | ||
| ``` | ||
|
|
||
| You can also configure the Mqtt client using a configuration file just like any `MORYX` module. | ||
| ```cs | ||
| builder.Services.AddMqttClient("Moryx.Mqtt.Config"); // specify your config file name without extension | ||
| ``` | ||
|
|
||
| Add your configuration file `Moryx.Mqtt.Config.json`, inside the default MORYX Config folder. The content is as follow: | ||
|
|
||
| ``` json | ||
| { | ||
| "Id": "my-id", | ||
| "Host": "localhost", | ||
| "Port": 1883, | ||
| "Username": null, | ||
| "Password": null, | ||
| "Tls": false, | ||
| "QoS": 1, // check the MqttQualityOfServiceLevel enum for more info | ||
| "ReconnectDelayMs": 30000, | ||
| "ReconnectWithClientSession": true, | ||
| "RootTopic": "" // optional | ||
| } | ||
| ``` | ||
|
|
||
| ## Serialization | ||
| The serialization of payload is done via `MqttMessageSerialization` helper class, serialization and deserialization methods requires `JsonSerializerOptions` that is configured during setup of the Mqtt client. | ||
|
|
||
| - JsonSerializationOptions | ||
|
|
||
| ```cs | ||
| // Program.cs | ||
| builder.Services.AddMqttClient(builder: (provider, options) => | ||
| { | ||
| options.JsonSerializerOptions.Converters.Add(new MyCustomConverter()) // here you add your custom converter | ||
| options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // change how references are handled | ||
| //etc.. | ||
| }) | ||
| //.. other code | ||
| ``` | ||
|
|
||
| if you want to implement your custom service based on the `IManagedMqttClient` the recommended way is as follow : | ||
| - In your `program.cs` add the following: | ||
|
|
||
| ```cs | ||
| builder.Services.AddMqttClient(); // this adds the IManagedMqttClient to the service collection | ||
| ``` | ||
| - Create a new C# class and inherit from `IMqttService`. `Note: Dependency injection is supported `. Now your service has access to the `IManagedMqttClient`, | ||
| Example: | ||
|
|
||
| ```cs | ||
| public class BlablaService : IMqttService | ||
| { | ||
| private IMyDependency _dependency; | ||
| private IManagedMqttClient _client; | ||
| public Blabla(IMyDependency dependency, IManagedMqttClient client) | ||
| { | ||
| _dependency = dependency; | ||
| _client = client; | ||
| } | ||
|
|
||
| // </inherited> | ||
| public override Task StartAsync(CancellationToken cancellationToken) | ||
| { | ||
| // your logic here | ||
| // _client.OnConnectedAsync += .... | ||
| // _client.OnMessageReceived += ... | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| // </inherited> | ||
| public override Task StopAsync(CancellationToken cancellationToken) | ||
| { | ||
| //your logic here | ||
| return Task.CompletedTask; | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| To add your new service to the service collection do the following: | ||
| ```cs | ||
| builder.Services.AddMqttClient(); | ||
| .AddMqttService<BlablaService>(); // you custom service | ||
| ``` | ||
|
|
||
| #### Note : the connection to the broker (Connect, re-connect on connection lost etc...) is automatically handled by the `IManagedMqttClient`. | ||
|
|
||
| # Endpoints | ||
|
|
||
| If you need something with topic template and constraint support, you can use the `IMqttEndpoint`. Here is an example: | ||
| - In your `program.cs` add the following: | ||
|
|
||
| ```cs | ||
| builder.Services.AddMqttClient() // must be present | ||
| .AddMqttEndpoints(); // <-- this add supports for the endpoints | ||
| ``` | ||
| - Create a new C# class that implements the `IMqttEndpoint`: | ||
| ```cs | ||
| public class Blabla : IMqttEndpoint | ||
| { | ||
| private IMyDependency _dependency; | ||
| public Blabla(IMyDependency dependency) | ||
| { | ||
| _dependency = dependency; | ||
| } | ||
|
|
||
| public void Map(IMqttRouteBuilder route) | ||
| { | ||
| //topic template is supported here | ||
| route.MapGet("my-topic/{id:int}/method/{methodName}", context => | ||
| { | ||
| var messageBuilder = new MqttApplicationMessageBuilder(); | ||
| messageBuilder.WithTopic("another-topic"); | ||
| messageBuilder.WithPayload(MqttMessageSerialization.GetJsonPayload("Hello World!!!!")); | ||
| return messageBuilder.Build(); | ||
| }); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| There is a minimal version of the Mqtt endpoint, that you can use directly in the `program.cs`: | ||
|
|
||
| ```cs | ||
| builder.Services.AddMqttClient() | ||
| .AddMqttEndpoints(route => | ||
| { | ||
| route.MapGet("my-topic/{id:int}/method/{methodName}", context => | ||
| { | ||
| var messageBuilder = new MqttApplicationMessageBuilder(); | ||
| messageBuilder.WithTopic("another-topic"); | ||
| messageBuilder.WithPayload(MqttMessageSerialization.GetJsonPayload("Hello World!!!!")); | ||
| return messageBuilder.Build(); | ||
| }); | ||
| // optional : this behave like an eventStream | ||
| route.MapPost(stream => | ||
| { | ||
| var messageBuilder = new MqttApplicationMessageBuilder(); | ||
| messageBuilder.WithTopic("another-topic"); | ||
| var timer = new Timer(async arg => | ||
| { | ||
| var messageBuilder = new MqttApplicationMessageBuilder(); | ||
| messageBuilder.WithPayload(MqttMessageSerialization.GetJsonPayload("Hello World!!!!")); | ||
| var message = messageBuilder.Build(); | ||
| await stream.WriteAsync(message); | ||
| }, null, 0, 10 * 1000); | ||
| }); | ||
| }); | ||
| ``` | ||
| This can be useful for quick prototyping and testing. | ||
|
|
||
| ### Available features in endpoints | ||
| Endpoints topics support constraint just like in ASP.net controller route. | ||
| #### Route constraint | ||
|
|
||
| The available constraints are: | ||
|
|
||
| - {name: int} | ||
| - {name: int?} | ||
| - {name: string} | ||
| - {name: string?} | ||
| - {name: decimal} | ||
| - {name: decimal?} | ||
| - {name: bool} | ||
| - {name: bool?} | ||
| - {name: datetime} | ||
| - {name: datetime?} | ||
| - {name: double} | ||
| - {name: double?} | ||
| - {name: float} | ||
| - {name: float?} | ||
| - {name: guid} | ||
| - {name: guid?} | ||
| - {name: long} | ||
| - {name: long?} | ||
| - {name?} | ||
| - {name/*} | ||
|
|
||
| #### Message Body and Parameters inside a Topic | ||
|
|
||
| When the endpoint receives a message from the broker, it might come with a Body/payload and a parameter inside the topic. | ||
| To access the payload inside your endpoint you can use one of the following methods: | ||
| ```cs | ||
| FromBody<T>(string propertyName) | ||
| ``` | ||
| ```cs | ||
| FromBody(string propertyName, Type type) | ||
| ``` | ||
| ```cs | ||
| RequestBody<T>() | ||
| ``` | ||
| ```cs | ||
| RequestBodyObject() | ||
| ``` | ||
|
|
||
| Given the following message body in Json: | ||
| ```json | ||
| { | ||
| "Name": "Bloomberg", | ||
| "Temperature":"-2 degrees Celsius" | ||
| } | ||
| ``` | ||
|
|
||
| The following examples shows how to use the Message body methods to extract the relevant data: | ||
| ```cs | ||
| ... | ||
| route.MapGet("/my-topic/{id:int}", ctx => { | ||
| string name = ctx.FromBody<string>("Name"); // "Bloomberg" | ||
| City city = RequestBody<City>(); // "{Name, Temperature}" | ||
| }); | ||
| ... | ||
| ``` | ||
|
|
||
| The same thing is possible for the topic parameters. Example: | ||
| ```cs | ||
| ... | ||
| route.MapGet("/my-topic/{id:int}", ctx => { | ||
| int id = ctx.FromParameterValues<int>("id"); // this return 2 for '/my-topic/2' | ||
| }); | ||
| ... | ||
| ``` | ||
|
|
||
|
|
||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why must the filename be defined? The config manager normally does that automatically by the typename. Which class is used for the serialization?