Skip to content

Commit

Permalink
Updated MQTTnet to latest
Browse files Browse the repository at this point in the history
  • Loading branch information
DoctorMcKay committed Oct 25, 2023
1 parent 4205b78 commit 459b845
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 85 deletions.
4 changes: 2 additions & 2 deletions HSPI_IRobot/HSPI_IRobot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@
<Reference Include="HSCF, Version=1.0.0.2, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\HomeSeer-PluginSDK.1.4.4\lib\net462\HSCF.dll</HintPath>
</Reference>
<Reference Include="MQTTnet, Version=3.1.2.0, Culture=neutral, PublicKeyToken=b69712f52770c0a7, processorArchitecture=MSIL">
<HintPath>..\packages\MQTTnet.3.1.2\lib\net461\MQTTnet.dll</HintPath>
<Reference Include="MQTTnet, Version=4.3.1.873, Culture=neutral, PublicKeyToken=fdb7629f2e364a63, processorArchitecture=MSIL">
<HintPath>..\packages\MQTTnet.4.3.1.873\lib\net461\MQTTnet.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
Expand Down
2 changes: 1 addition & 1 deletion HSPI_IRobot/packages.config
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="HomeSeer-PluginSDK" version="1.4.4" targetFramework="net472" />
<package id="MQTTnet" version="3.1.2" targetFramework="net472" />
<package id="MQTTnet" version="4.3.1.873" targetFramework="net472" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net472" />
</packages>
6 changes: 3 additions & 3 deletions IRobotLANClient/IRobotLANClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<AssemblyName>IRobotLANClient</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<LangVersion>7.3</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
Expand All @@ -31,8 +32,8 @@
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="MQTTnet, Version=3.1.2.0, Culture=neutral, PublicKeyToken=b69712f52770c0a7, processorArchitecture=MSIL">
<HintPath>..\packages\MQTTnet.3.1.2\lib\net461\MQTTnet.dll</HintPath>
<Reference Include="MQTTnet, Version=4.3.1.873, Culture=neutral, PublicKeyToken=fdb7629f2e364a63, processorArchitecture=MSIL">
<HintPath>..\packages\MQTTnet.4.3.1.873\lib\net461\MQTTnet.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
Expand All @@ -58,7 +59,6 @@
<Compile Include="JsonObjects\ReportedState.cs" />
<Compile Include="JsonObjects\ReportedStateMop.cs" />
<Compile Include="JsonObjects\ReportedStateVacuum.cs" />
<Compile Include="MqttHandler.cs" />
<Compile Include="RobotClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="DiscoveryClient.cs" />
Expand Down
53 changes: 0 additions & 53 deletions IRobotLANClient/MqttHandler.cs

This file was deleted.

88 changes: 63 additions & 25 deletions IRobotLANClient/RobotClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Linq;
using System.Security.Authentication;
using System.Text;
using System.Threading;
Expand All @@ -8,8 +9,6 @@
using IRobotLANClient.JsonObjects;
using MQTTnet.Client;
using MQTTnet;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Options;
using MQTTnet.Formatter;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Expand Down Expand Up @@ -51,6 +50,8 @@ public abstract class RobotClient {
private bool _awaitingFirstReportTimer;
private DateTime _connectedTime;

private readonly TaskCompletionSource<Exception> _exceptionSource;

#if DEBUG
private static bool SpoofingSoftwareUpdate;
#endif
Expand All @@ -60,33 +61,35 @@ public RobotClient(string address, string blid, string password) {
Address = address;
Blid = blid;
Password = password;

_exceptionSource = new TaskCompletionSource<Exception>();
_exceptionSource.Task.ContinueWith(task => throw task.Result);
}

public async Task<MqttClientConnectResult> Connect() {
MqttFactory factory = new MqttFactory();
MqttClient = factory.CreateMqttClient();

MqttClientOptionsBuilderTlsParameters tlsParams = new MqttClientOptionsBuilderTlsParameters {
AllowUntrustedCertificates = true,
CertificateValidationHandler = _ => true,
SslProtocol = SslProtocols.Tls12,
UseTls = true
};
MqttClientTlsOptions tlsOptions = new MqttClientTlsOptionsBuilder()
.WithAllowUntrustedCertificates(true)
.WithCertificateValidationHandler(_ => true)
.WithSslProtocols(SslProtocols.Tls12)
.UseTls(true)
.Build();

IMqttClientOptions clientOptions = new MqttClientOptionsBuilder()
MqttClientOptions clientOptions = new MqttClientOptionsBuilder()
.WithTcpServer(Address, 8883)
.WithCredentials(Blid, Password)
.WithClientId(Blid)
.WithTls(tlsParams)
.WithTlsOptions(tlsOptions)
.WithProtocolVersion(MqttProtocolVersion.V311)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
.WithCommunicationTimeout(TimeSpan.FromSeconds(5))
.WithTimeout(TimeSpan.FromSeconds(5))
.Build();

MqttHandler handler = new MqttHandler(this);
MqttClient.ApplicationMessageReceivedHandler = handler;
MqttClient.ConnectedHandler = handler;
MqttClient.DisconnectedHandler = handler;

MqttClient.ConnectedAsync += OnConnectedAsync;
MqttClient.DisconnectedAsync += OnDisconnectedAsync;
MqttClient.ApplicationMessageReceivedAsync += OnApplicationMessageReceived;

#if DEBUG
if (SpoofingSoftwareUpdate) {
Expand Down Expand Up @@ -154,6 +157,41 @@ public async Task<MqttClientConnectResult> Connect() {
}
}

private Task OnConnectedAsync(MqttClientConnectedEventArgs args) {
// This is going to look ridiculous, but that's only because it is. MQTTnet swallows exceptions thrown in
// event handlers, because apparently continuing with undefined behavior if an exception isn't handled is
// preferable to crashing the app. So we have to escape this context to re-throw unhandled exceptions.

// This was true in v3, unsure if this is still true in v4.
try {
ConnectedStateChanged(true);
} catch (Exception ex) {
_exceptionSource.SetResult(ex);
}

return Task.CompletedTask;
}

private Task OnDisconnectedAsync(MqttClientDisconnectedEventArgs eventArgs) {
try {
ConnectedStateChanged(false);
} catch (Exception ex) {
_exceptionSource.SetResult(ex);
}

return Task.CompletedTask;
}

private Task OnApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs args) {
try {
ApplicationMessageReceived(args.ApplicationMessage);
} catch (Exception ex) {
_exceptionSource.SetResult(ex);
}

return Task.CompletedTask;
}

public async Task Disconnect() {
if (!MqttClient.IsConnected) {
return; // nothing to do
Expand Down Expand Up @@ -223,10 +261,10 @@ protected async void SendCommand(string command, JObject commandParams = null) {
cmd["time"] = (long) DateTime.Now.Subtract(unixEpoch).TotalSeconds;
cmd["initiator"] = "localApp";

MqttApplicationMessage msg = new MqttApplicationMessage {
Topic = "cmd",
Payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(cmd))
};
MqttApplicationMessage msg = new MqttApplicationMessageBuilder()
.WithTopic("cmd")
.WithPayload(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(cmd)))
.Build();

try {
await MqttClient.PublishAsync(msg, _cancellationTokenSource.Token);
Expand Down Expand Up @@ -282,10 +320,10 @@ public void SpoofSoftwareUpdate() {
#endif

protected void UpdateOption(object request) {
MqttApplicationMessage msg = new MqttApplicationMessage {
Topic = "delta",
Payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new {state = request}))
};
MqttApplicationMessage msg = new MqttApplicationMessageBuilder()
.WithTopic("delta")
.WithPayload(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new {state = request})))
.Build();

try {
MqttClient.PublishAsync(msg, _cancellationTokenSource.Token).Wait();
Expand All @@ -295,7 +333,7 @@ protected void UpdateOption(object request) {
}

internal void ApplicationMessageReceived(MqttApplicationMessage msg) {
string jsonPayload = Encoding.UTF8.GetString(msg.Payload);
string jsonPayload = Encoding.UTF8.GetString(msg.PayloadSegment.ToArray());
JObject payload = JObject.Parse(jsonPayload);

bool isStatusUpdate = msg.Topic == MqttStatusTopic;
Expand Down
2 changes: 1 addition & 1 deletion IRobotLANClient/packages.config
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MQTTnet" version="3.1.2" targetFramework="net472" />
<package id="MQTTnet" version="4.3.1.873" targetFramework="net472" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net472" />
</packages>

0 comments on commit 459b845

Please sign in to comment.