Skip to content

Commit

Permalink
Feature/update mqtt3 to mqtt4 (#140)
Browse files Browse the repository at this point in the history
* Update MQTTnet package to version 4.3.6.1152

This commit upgrades the MQTTnet package from version 3.0.9 to 4.3.6.1152 in both the main API project and the test project. This update is intended to leverage new features and improvements in the latest version of MQTTnet.

* Update MQTT message handling in CapabilitiesServiceTest

Refactor MQTT message handling to use the ApplicationMessageReceivedAsync event instead of UseApplicationMessageReceivedHandler. This aligns with updated MQTTnet library practices and ensures better async event handling. Removed the unnecessary MQTTnet.Client import.

* Update MQTTnet namespace import.

Switched from MQTTnet.Client.Publishing to MQTTnet.Client to resolve namespace discrepancies and ensure compatibility with updated library versions.

* Update MQTT connection timeout method

Replaced deprecated `.WithCommunicationTimeout()` method with `.WithTimeout()` for setting MQTT communication timeout. Removed unused `MQTTnet.Client.Options` import statement for cleanup.

* Refactor MQTT message publishing for clarity and consistency

Refactor the MQTT message publishing process by switching to the appropriate MQTTnet.Protocol namespace and improving code readability. Utilize the `MqttQualityOfServiceLevel.ExactlyOnce` for enhanced clarity and ensure proper formatting and spacing throughout.

* Switch to async handler for MQTT message receiving

Updated the application message handling in PingServiceTest to use the asynchronous event handler. This ensures better responsiveness and non-blocking execution while verifying response codes in the unit tests.

---------

Co-authored-by: Oliver Rahner <[email protected]>
  • Loading branch information
saschadoemer and oliverrahner authored Oct 14, 2024
1 parent c374ce2 commit b061aa3
Show file tree
Hide file tree
Showing 7 changed files with 22 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;
using MQTTnet.Client.Publishing;
using MQTTnet.Client;

namespace Agrirouter.Api.Exception
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

<ItemGroup>
<PackageReference Include="agrirouter-api-protobuf-definitions" Version="1.1.0" />
<PackageReference Include="MQTTnet" Version="3.0.9" />
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Serilog" Version="2.9.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
using Agrirouter.Api.Service.Parameters;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Publishing;
using MQTTnet.Protocol;
using Newtonsoft.Json;

namespace Agrirouter.Impl.Service.Common
Expand All @@ -25,7 +25,7 @@ public IMqttClient MqttClient
{
get { return _mqttClient; }
}

/// <summary>
/// Constructor.
/// </summary>
Expand Down Expand Up @@ -61,11 +61,13 @@ public async Task<MessagingResult> SendAsync(MessagingParameters messagingParame
var mqttMessage = BuildMqttApplicationMessage(messagingParameters);
var response = await _mqttClient.PublishAsync(mqttMessage, CancellationToken.None);

if (response.ReasonCode != MqttClientPublishReasonCode.Success) {
if (response.ReasonCode != MqttClientPublishReasonCode.Success)
{
throw new CouldNotSendMqttMessageException(response.ReasonCode, response.ReasonString);
}

return new MessagingResultBuilder().WithApplicationMessageId(messagingParameters.ApplicationMessageId).Build();
return new MessagingResultBuilder().WithApplicationMessageId(messagingParameters.ApplicationMessageId)
.Build();
}

private static MqttApplicationMessage BuildMqttApplicationMessage(MessagingParameters messagingParameters)
Expand All @@ -78,16 +80,16 @@ private static MqttApplicationMessage BuildMqttApplicationMessage(MessagingParam
};

foreach (var message in messagingParameters.EncodedMessages.Select(encodedMessage =>
new Api.Dto.Messaging.Inner.Message
{Content = encodedMessage, Timestamp = UtcDataService.NowAsUnixTimestamp()}))
new Api.Dto.Messaging.Inner.Message
{ Content = encodedMessage, Timestamp = UtcDataService.NowAsUnixTimestamp() }))
messageRequest.Messages.Add(message);

var messagePayload = JsonConvert.SerializeObject(messageRequest);

var mqttMessage = new MqttApplicationMessageBuilder()
.WithTopic(messagingParameters.OnboardResponse.ConnectionCriteria.Measures)
.WithPayload(messagePayload)
.WithExactlyOnceQoS()
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce)
.WithRetainFlag()
.Build();
return mqttMessage;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Agrirouter.Api.Dto.Onboard;
using Agrirouter.Impl.Service.Common;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using Xunit;

namespace Agrirouter.Test.Helper
Expand Down Expand Up @@ -47,7 +46,7 @@ public static async Task ConnectMqttClient(IMqttClient mqttClient, OnboardRespon
.WithTcpServer(onboardResponse.ConnectionCriteria.Host,
int.Parse(onboardResponse.ConnectionCriteria.Port))
.WithTls(tlsParameters)
.WithCommunicationTimeout(TimeSpan.FromSeconds(20))
.WithTimeout(TimeSpan.FromSeconds(20))
.Build();

await mqttClient.ConnectAsync(options);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
using Agrirouter.Test.Data;
using Agrirouter.Test.Helper;
using MQTTnet;
using MQTTnet.Client;
using Xunit;
using Agrirouter.Api.Dto.Messaging;
using Newtonsoft.Json;
Expand Down Expand Up @@ -52,15 +51,17 @@ public async void
var messageReceived = false;
var counter = 0;

mqttClient.UseApplicationMessageReceivedHandler(e =>
mqttClient.ApplicationMessageReceivedAsync += async e =>

Check warning on line 54 in agrirouter-sdk-dotnet-standard-test/Service/Messaging/Mqtt/CapabilitiesServiceTest.cs

View workflow job for this annotation

GitHub Actions / build

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
messageReceived = true;
MessageResponse msg = JsonConvert.DeserializeObject<MessageResponse>(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
MessageResponse msg =
JsonConvert.DeserializeObject<MessageResponse>(
Encoding.UTF8.GetString(e.ApplicationMessage.Payload));

Check warning on line 60 in agrirouter-sdk-dotnet-standard-test/Service/Messaging/Mqtt/CapabilitiesServiceTest.cs

View workflow job for this annotation

GitHub Actions / build

'MqttApplicationMessage.Payload' is obsolete: 'Use PayloadSegment instead. This property will be removed in a future release.'
var decodedMessage = DecodeMessageService.Decode(msg.Command.Message);
Assert.Equal(201, decodedMessage.ResponseEnvelope.ResponseCode);
});
};

while (!messageReceived && counter < 5)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public async void
var messageReceived = false;
var counter = 0;

mqttClient.UseApplicationMessageReceivedHandler(e =>
mqttClient.ApplicationMessageReceivedAsync += async e =>

Check warning on line 41 in agrirouter-sdk-dotnet-standard-test/Service/Messaging/Mqtt/PingServiceTest.cs

View workflow job for this annotation

GitHub Actions / build

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
messageReceived = true;
Expand All @@ -47,7 +47,7 @@ public async void
var decodedMessage = DecodeMessageService.Decode(msg.Command.Message);
Assert.Equal(200, decodedMessage.ResponseEnvelope.ResponseCode);
});
};

while (!messageReceived && counter < 5)
{
Expand Down Expand Up @@ -90,7 +90,7 @@ public async void
var messageReceived = false;
var counter = 0;

mqttClient.UseApplicationMessageReceivedHandler(e =>
mqttClient.ApplicationMessageReceivedAsync += async e =>

Check warning on line 93 in agrirouter-sdk-dotnet-standard-test/Service/Messaging/Mqtt/PingServiceTest.cs

View workflow job for this annotation

GitHub Actions / build

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
messageReceived = true;
Expand All @@ -100,7 +100,7 @@ public async void
// your own application should remove the endpoint from your endpoint list/registry now!
Assert.Equal(400, decodedMessage.ResponseEnvelope.ResponseCode);
});
};

while (!messageReceived && counter < 5)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.20.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
<PackageReference Include="MQTTnet" Version="3.0.9" />
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
<PackageReference Include="Serilog.Sinks.Debug" Version="1.0.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
Expand Down

0 comments on commit b061aa3

Please sign in to comment.