mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-15 00:15:15 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eaf27c1e12 | ||
|
|
1c78cd4c31 | ||
|
|
d1ab867afc | ||
|
|
522a385523 | ||
|
|
40dd620f90 | ||
|
|
7dfc19e588 | ||
|
|
0b002e8d11 | ||
|
|
d2e481719c | ||
|
|
7e48746944 | ||
|
|
f481c704c9 | ||
|
|
6e5b991406 | ||
|
|
e07ead53a9 | ||
|
|
e6e88e132b | ||
|
|
8778848301 | ||
|
|
5fbef7beb5 | ||
|
|
387a3bc281 | ||
|
|
11ccb951aa | ||
|
|
3a6df2eab0 | ||
|
|
c5e3bc70b1 | ||
|
|
9c46b8fd75 | ||
|
|
d5dc3a1361 | ||
|
|
f0e8d8e98c | ||
|
|
589fd22a63 | ||
|
|
83821453a0 | ||
|
|
d335b6393e | ||
|
|
6240d60003 | ||
|
|
4519c4fe3d | ||
|
|
e969b2f31f | ||
|
|
44ae9093f9 | ||
|
|
fcd3bdf297 | ||
|
|
cbb2f43047 | ||
|
|
5e74869dbc | ||
|
|
98cac153e6 | ||
|
|
b51a603aa9 | ||
|
|
2fe520ad46 | ||
|
|
c8846329f3 | ||
|
|
08f2db05a9 | ||
|
|
5427b488c3 | ||
|
|
ec24f03324 | ||
|
|
4ef16cfd8d | ||
|
|
177c7cbf03 | ||
|
|
8025717658 | ||
|
|
275d8d9f0b | ||
|
|
30df7d4c9e | ||
|
|
019ef1398e | ||
|
|
4a6f517e91 | ||
|
|
d560cb4c9e | ||
|
|
ba16ae6568 | ||
|
|
3b2c40d49e | ||
|
|
9894dbef87 | ||
|
|
dd447f24d2 | ||
|
|
3a250723d7 | ||
|
|
e0797e5d14 | ||
|
|
d0f1c18a2f | ||
|
|
bb6eb246e8 | ||
|
|
0e666f0316 | ||
|
|
0811938466 | ||
|
|
466b6a25cd | ||
|
|
15a564dcfe | ||
|
|
f85721fbf5 | ||
|
|
3b366f91fc | ||
|
|
418f2b2c3f | ||
|
|
8fa91736b6 | ||
|
|
a18c533603 | ||
|
|
a9b394401b | ||
|
|
c257e5cb77 | ||
|
|
93863ece0d | ||
|
|
29918fb454 | ||
|
|
412cf115a5 | ||
|
|
8dab5d3800 | ||
|
|
2cd3bd7588 | ||
|
|
0e0fcabc04 | ||
|
|
e80d21e852 | ||
|
|
a68343a306 | ||
|
|
d594b1447f | ||
|
|
1ca9b0bd62 | ||
|
|
1c0b2b55b6 | ||
|
|
41ca15120d | ||
|
|
49b1706495 | ||
|
|
daf22c762f | ||
|
|
3529724bdc | ||
|
|
56a86b6127 | ||
|
|
7e6f4453ad | ||
|
|
84a647e712 | ||
|
|
d10f29bbc6 | ||
|
|
41edc3a1ec | ||
|
|
3f080e04b9 | ||
|
|
4386ef1e56 | ||
|
|
df1dd0eec7 | ||
|
|
3954777d20 | ||
|
|
b52645f77a | ||
|
|
65e6f96e59 | ||
|
|
24c35de330 | ||
|
|
d052f409b6 | ||
|
|
f9eb6ed85e | ||
|
|
11ade8c3df | ||
|
|
fe88b7551c | ||
|
|
bddfadaefa | ||
|
|
40b1be075c | ||
|
|
680bc4658f | ||
|
|
870ed00e3c | ||
|
|
1f3b24d20f | ||
|
|
bc19f66812 | ||
|
|
9915cc4492 | ||
|
|
ad4585989a | ||
|
|
ea5616002a | ||
|
|
1f8a781dc2 | ||
|
|
fd63cf0086 | ||
|
|
60bdca8716 | ||
|
|
a2971aa03b | ||
|
|
05a3acb229 | ||
|
|
47257baba9 | ||
|
|
906a0ba189 | ||
|
|
69b02f3224 | ||
|
|
a7d0ad5f43 | ||
|
|
59f07c868d | ||
|
|
4517d80704 | ||
|
|
9bca4aa53f | ||
|
|
4c4539509c | ||
|
|
af3cebb266 | ||
|
|
d22528ca46 | ||
|
|
67267c05fd | ||
|
|
d23ab88add | ||
|
|
1d78d675f7 | ||
|
|
3079ad37ce | ||
|
|
c7b7d56229 | ||
|
|
c97b97c677 | ||
|
|
96a62551b2 | ||
|
|
300c9b9ccb | ||
|
|
342085db40 | ||
|
|
862f76fea2 | ||
|
|
3cce33415d | ||
|
|
d09455f78e | ||
|
|
e947881aca | ||
|
|
077c9ea00d | ||
|
|
f8af4597f2 | ||
|
|
32dc96ae93 | ||
|
|
153e83ee3e | ||
|
|
6402dfd9ea | ||
|
|
98bafb1f26 | ||
|
|
6d92937892 | ||
|
|
28d31d0cf5 | ||
|
|
07fd509e74 | ||
|
|
37a5dc7abe | ||
|
|
8604097ada | ||
|
|
ea587d97c8 | ||
|
|
fb272b07aa | ||
|
|
7067a8e411 |
@@ -0,0 +1,8 @@
|
||||
exclude:
|
||||
- /Frameworks/.*
|
||||
- /MQTTnet.TestApp.NetCore/Program.cs
|
||||
- /Tests/MQTTnet.TestApp.NetFramework/.*
|
||||
- /Tests/MQTTnet.TestApp.UniversalWindows/.*
|
||||
component_depth: 1
|
||||
languages:
|
||||
- csharp
|
||||
+3
-1
@@ -197,7 +197,7 @@ ClientBin/
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
# *.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
@@ -289,3 +289,5 @@ __pycache__/
|
||||
|
||||
|
||||
Build/nuget.exe
|
||||
*.js
|
||||
*.map
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0"?>
|
||||
<package >
|
||||
<metadata>
|
||||
<id>MQTTnet.AspNetCore</id>
|
||||
<version>2.5.0</version>
|
||||
<authors>Christian Kratky</authors>
|
||||
<owners>Christian Kratky</owners>
|
||||
<licenseUrl>https://github.com/chkr1011/MQTTnet/blob/master/LICENSE</licenseUrl>
|
||||
<projectUrl>https://github.com/chkr1011/MQTTnet</projectUrl>
|
||||
<iconUrl>https://raw.githubusercontent.com/chkr1011/MQTTnet/master/Images/Logo_128x128.png</iconUrl>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<description>This is a support library to integrate MQTTnet into AspNetCore.</description>
|
||||
<releaseNotes>initial version
|
||||
</releaseNotes>
|
||||
<copyright>Copyright Christian Kratky 2016-2017</copyright>
|
||||
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags>
|
||||
<dependencies>
|
||||
<group targetFramework="netstandard2.0">
|
||||
<dependency id="MQTTnet" version="2.5" />
|
||||
</group>
|
||||
</dependencies>
|
||||
</metadata>
|
||||
|
||||
<files>
|
||||
<!-- .NET Standard 2.0 -->
|
||||
<file src="..\Frameworks\MQTTnet.AspNetCore\bin\Release\netstandard2.0\MQTTnet.AspNetCore.*" target="lib\netstandard2.0\"/>
|
||||
</files>
|
||||
</package>
|
||||
+39
-15
@@ -2,33 +2,57 @@
|
||||
<package >
|
||||
<metadata>
|
||||
<id>MQTTnet</id>
|
||||
<version>2.3.0</version>
|
||||
<version>2.5.0</version>
|
||||
<authors>Christian Kratky</authors>
|
||||
<owners>Christian Kratky</owners>
|
||||
<licenseUrl>https://github.com/chkr1011/MQTTnet/blob/master/LICENSE</licenseUrl>
|
||||
<projectUrl>https://github.com/chkr1011/MQTTnet</projectUrl>
|
||||
<iconUrl>https://raw.githubusercontent.com/chkr1011/MQTTnet/master/Images/Logo_128x128.png</iconUrl>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<description>MQTTnet is a .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker).</description>
|
||||
<releaseNotes>* [Client] Added support for web socket communication channel (thanks to nowakpiotr)
|
||||
* [Core] Huge performance optimizations (thanks to JanEggers)
|
||||
* [Client] Fixed an issue when calling _DisconnectAsync_ and the connection is already closed.
|
||||
* [Core] Added several new interfaces
|
||||
* [Core] Added a factory for creation of application messages
|
||||
* [Core] Fixed issues in connection handling
|
||||
* [Client] Fixed issues with subscribing/unsubscribing (breaking change!)
|
||||
<description>MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker).</description>
|
||||
<releaseNotes>* [Core] Merged the platform specific projects (Thanks to @JanEggers)
|
||||
* [Core] Migrated the trace to a non-static approach (Breaking Change!)
|
||||
* [Core] Added a builder for application messages using a fluent API
|
||||
* [Core] Introduced CI and DI (Thanks to @JanEggers)
|
||||
* [Core] Added interfaces for publishing and receiving which applies to every client and server (Thanks to @ChristianRiedl)
|
||||
* [Core] Fixed an issue when reading from closed streams
|
||||
* [Client] Added a first version of a managed client which will manage the connection, subscription etc. automatically (Thanks to @JTrotta)
|
||||
* [Client] The session state response from the server is now returned in the _ConnectAsync_ method and also part of the _Connected_ event args
|
||||
* [Client] Added a _TopicFilterBuilder_ using a fluent API (Namespace Changes!)
|
||||
* [Client] Added several new options for the WebSocket channel (Thanks to @ChristianRiedl)
|
||||
* [Client] Refactored the options and added a builder using a fluent API (Breaking Change!)
|
||||
* [Client] Added more options for WebSocket connections like RequestHeaders, SubProtocol etc.
|
||||
* [Server] Added support for WebSockets via ASP.NET Core 2.0 (additional nuget) (Thanks to @ChristianRiedl, @JanEggers)
|
||||
* [Server] Added support for a custom application message interceptor
|
||||
* [Server] Fixed an issue with dropped connections on UWP (Thanks to @haeberle)
|
||||
* [Server] Added support for a custom subscription interceptor which allows denying of subscriptions and closing the connection
|
||||
</releaseNotes>
|
||||
<copyright>Copyright Christian Kratky 2016-2017</copyright>
|
||||
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M</tags>
|
||||
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags>
|
||||
<dependencies>
|
||||
|
||||
<group targetFramework="netstandard1.3">
|
||||
<dependency id="NETStandard.Library" version="1.6.1" />
|
||||
<dependency id="System.Net.Security" version="4.3.1" />
|
||||
<dependency id="Microsoft.Extensions.DependencyInjection" version="1.1.1" />
|
||||
<dependency id="Microsoft.Extensions.Logging" version="1.1.2" />
|
||||
<dependency id="Microsoft.Extensions.Options" version="1.1.2" />
|
||||
<dependency id="System.Net.Security" version="4.3.2" />
|
||||
<dependency id="System.Net.WebSockets" version="4.3.0" />
|
||||
<dependency id="System.Net.WebSockets.Client" version="4.3.1" />
|
||||
<dependency id="System.Threading.Thread" version="4.3.0" />
|
||||
</group>
|
||||
|
||||
<group targetFramework="uap10.0">
|
||||
<dependency id="Microsoft.NETCore.UniversalWindowsPlatform" version="5.4.0" />
|
||||
<dependency id="Microsoft.Extensions.DependencyInjection" version="1.1.1" />
|
||||
<dependency id="Microsoft.Extensions.Logging" version="1.1.2" />
|
||||
<dependency id="Microsoft.Extensions.Options" version="1.1.2" />
|
||||
</group>
|
||||
|
||||
<group targetFramework="net451">
|
||||
<dependency id="Microsoft.Extensions.DependencyInjection" version="1.1.1" />
|
||||
<dependency id="Microsoft.Extensions.Logging" version="1.1.2" />
|
||||
<dependency id="Microsoft.Extensions.Options" version="1.1.2" />
|
||||
</group>
|
||||
|
||||
</dependencies>
|
||||
@@ -40,12 +64,12 @@
|
||||
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\netstandard1.3\MQTTnet.*" target="lib\netstandard1.3\"/>
|
||||
|
||||
<!-- Universal Windows -->
|
||||
<file src="..\Frameworks\MQTTnet.UniversalWindows\bin\Release\MQTTnet.Core.*" target="lib\uap10.0\"/>
|
||||
<file src="..\Frameworks\MQTTnet.UniversalWindows\bin\Release\MQTTnet.*" target="lib\uap10.0\"/>
|
||||
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\uap10.0\MQTTnet.Core.*" target="lib\uap10.0\"/>
|
||||
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\uap10.0\MQTTnet.*" target="lib\uap10.0\"/>
|
||||
|
||||
<!-- .NET Framework -->
|
||||
<file src="..\Frameworks\MQTTnet.NetFramework\bin\Release\MQTTnet.Core.*" target="lib\net45\"/>
|
||||
<file src="..\Frameworks\MQTTnet.NetFramework\bin\Release\MQTTnet.*" target="lib\net45\"/>
|
||||
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\net452\MQTTnet.Core.*" target="lib\net452\"/>
|
||||
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\net452\MQTTnet.*" target="lib\net452\"/>
|
||||
|
||||
</files>
|
||||
</package>
|
||||
+17
-7
@@ -2,11 +2,21 @@ param([string]$version)
|
||||
|
||||
if ([string]::IsNullOrEmpty($version)) {$version = "0.0.1"}
|
||||
|
||||
$msbuild = "MSBuild.exe"
|
||||
&$msbuild ..\Frameworks\MQTTnet.NetFramework\MQTTnet.NetFramework.csproj /t:Build /p:Configuration="Release"
|
||||
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release"
|
||||
&$msbuild ..\Frameworks\MQTTnet.UniversalWindows\MQTTnet.UniversalWindows.csproj /t:Build /p:Configuration="Release"
|
||||
$vswhere = ${Env:\ProgramFiles(x86)} + '\Microsoft Visual Studio\Installer\vswhere'
|
||||
|
||||
$path = &$vswhere -latest -products * -requires Microsoft.Component.MSBuild -property installationPath
|
||||
if ($path) {
|
||||
$msbuild = join-path $path 'MSBuild\15.0\Bin\MSBuild.exe'
|
||||
|
||||
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net452" /p:FileVersion=$version /p:AssemblyVersion=$version /verbosity:m
|
||||
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard1.3" /p:FileVersion=$version /p:AssemblyVersion=$version /verbosity:m
|
||||
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="uap10.0" /p:FileVersion=$version /p:AssemblyVersion=$version /verbosity:m
|
||||
|
||||
&$msbuild ..\Frameworks\MQTTnet.AspNetCore\MQTTnet.AspNetCore.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.0" /p:FileVersion=$version /p:AssemblyVersion=$version /verbosity:m
|
||||
|
||||
Remove-Item .\NuGet -Force -Recurse
|
||||
New-Item -ItemType Directory -Force -Path .\NuGet
|
||||
.\NuGet.exe pack MQTTnet.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $version
|
||||
.\NuGet.exe pack MQTTnet.AspNetCore.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $version
|
||||
}
|
||||
|
||||
Remove-Item .\NuGet -Force -Recurse
|
||||
New-Item -ItemType Directory -Force -Path .\NuGet
|
||||
.\NuGet.exe pack MQTTnet.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $version
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MQTTnet.Core.Server;
|
||||
|
||||
namespace MQTTnet.AspNetCore
|
||||
{
|
||||
public static class ApplicationBuilderExtensions
|
||||
{
|
||||
public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt")
|
||||
{
|
||||
app.UseWebSockets();
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
if (context.Request.Path == path && context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
|
||||
using (var webSocket = await context.WebSockets.AcceptWebSocketAsync("mqtt"))
|
||||
{
|
||||
await adapter.AcceptWebSocketAsync(webSocket);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await next();
|
||||
}
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
|
||||
{
|
||||
var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
|
||||
|
||||
configure(server);
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="2.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MQTTnet.Netstandard\MQTTnet.NetStandard.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Server;
|
||||
|
||||
namespace MQTTnet.AspNetCore
|
||||
{
|
||||
public class MqttHostedServer : MqttServer, IHostedService
|
||||
{
|
||||
public MqttHostedServer(
|
||||
IOptions<MqttServerOptions> options,
|
||||
IEnumerable<IMqttServerAdapter> adapters,
|
||||
ILogger<MqttServer> logger,
|
||||
MqttClientSessionsManager clientSessionsManager,
|
||||
IMqttClientRetainedMessageManager clientRetainedMessageManager
|
||||
)
|
||||
: base(options, adapters, logger, clientSessionsManager, clientRetainedMessageManager)
|
||||
{
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return StartAsync();
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return StopAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Server;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet.AspNetCore
|
||||
{
|
||||
public class MqttWebSocketServerAdapter : IMqttServerAdapter, IDisposable
|
||||
{
|
||||
private readonly IMqttCommunicationAdapterFactory _mqttCommunicationAdapterFactory;
|
||||
|
||||
public MqttWebSocketServerAdapter(IMqttCommunicationAdapterFactory mqttCommunicationAdapterFactory)
|
||||
{
|
||||
_mqttCommunicationAdapterFactory = mqttCommunicationAdapterFactory ?? throw new ArgumentNullException(nameof(mqttCommunicationAdapterFactory));
|
||||
}
|
||||
|
||||
public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||
|
||||
public Task StartAsync(MqttServerOptions options)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync()
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task AcceptWebSocketAsync(WebSocket webSocket)
|
||||
{
|
||||
if (webSocket == null) throw new ArgumentNullException(nameof(webSocket));
|
||||
|
||||
var channel = new MqttWebSocketServerChannel(webSocket);
|
||||
var clientAdapter = _mqttCommunicationAdapterFactory.CreateServerCommunicationAdapter(channel);
|
||||
|
||||
var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);
|
||||
ClientAccepted?.Invoke(this, eventArgs);
|
||||
return eventArgs.SessionTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
StopAsync();
|
||||
}
|
||||
|
||||
private class MqttWebSocketServerChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
private readonly WebSocket _webSocket;
|
||||
|
||||
public MqttWebSocketServerChannel(WebSocket webSocket)
|
||||
{
|
||||
_webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
|
||||
|
||||
RawReceiveStream = new WebSocketStream(_webSocket);
|
||||
}
|
||||
|
||||
public Stream SendStream => RawReceiveStream;
|
||||
public Stream ReceiveStream => RawReceiveStream;
|
||||
public Stream RawReceiveStream { get; }
|
||||
|
||||
public Task ConnectAsync()
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DisconnectAsync()
|
||||
{
|
||||
RawReceiveStream?.Dispose();
|
||||
|
||||
if (_webSocket == null)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
return _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
RawReceiveStream?.Dispose();
|
||||
SendStream?.Dispose();
|
||||
ReceiveStream?.Dispose();
|
||||
|
||||
_webSocket?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Server;
|
||||
|
||||
namespace MQTTnet.AspNetCore
|
||||
{
|
||||
public static class ServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddHostedMqttServer(this IServiceCollection services)
|
||||
{
|
||||
services.AddMqttServerServices();
|
||||
|
||||
services.AddSingleton<IHostedService>(s => s.GetService<MqttHostedServer>());
|
||||
services.AddSingleton<IMqttServer>(s => s.GetService<MqttHostedServer>());
|
||||
services.AddSingleton<MqttHostedServer>();
|
||||
|
||||
services.AddSingleton<MqttWebSocketServerAdapter>();
|
||||
services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttWebSocketServerAdapter>());
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using MQTTnet.Core.Server;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
||||
{
|
||||
private CancellationTokenSource _cancellationTokenSource;
|
||||
private Socket _defaultEndpointSocket;
|
||||
private Socket _tlsEndpointSocket;
|
||||
private X509Certificate2 _tlsCertificate;
|
||||
|
||||
private bool _isRunning;
|
||||
|
||||
public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
|
||||
|
||||
public void Start(MqttServerOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
if (_isRunning) throw new InvalidOperationException("Server is already started.");
|
||||
_isRunning = true;
|
||||
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
if (options.DefaultEndpointOptions.IsEnabled)
|
||||
{
|
||||
_defaultEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
_defaultEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetDefaultEndpointPort()));
|
||||
_defaultEndpointSocket.Listen(options.ConnectionBacklog);
|
||||
|
||||
Task.Run(() => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
if (options.TlsEndpointOptions.IsEnabled)
|
||||
{
|
||||
if (options.TlsEndpointOptions.Certificate == null)
|
||||
{
|
||||
throw new ArgumentException("TLS certificate is not set.");
|
||||
}
|
||||
|
||||
_tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
|
||||
|
||||
_tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
_tlsEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetTlsEndpointPort()));
|
||||
_tlsEndpointSocket.Listen(options.ConnectionBacklog);
|
||||
|
||||
Task.Run(() => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_isRunning = false;
|
||||
|
||||
_cancellationTokenSource?.Cancel(false);
|
||||
_cancellationTokenSource?.Dispose();
|
||||
_cancellationTokenSource = null;
|
||||
|
||||
_defaultEndpointSocket?.Dispose();
|
||||
_defaultEndpointSocket = null;
|
||||
|
||||
_tlsEndpointSocket?.Dispose();
|
||||
_tlsEndpointSocket = null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
}
|
||||
|
||||
private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
|
||||
|
||||
var tcpChannel = new MqttTcpChannel(clientSocket, null);
|
||||
var clientAdapter = new MqttChannelCommunicationAdapter(tcpChannel, new MqttPacketSerializer());
|
||||
ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
|
||||
}
|
||||
catch (Exception exception) when (!(exception is ObjectDisposedException))
|
||||
{
|
||||
MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at default endpoint.");
|
||||
|
||||
//excessive CPU consumed if in endless loop of socket errors
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
|
||||
|
||||
var sslStream = new SslStream(new NetworkStream(clientSocket));
|
||||
await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
|
||||
|
||||
var tcpChannel = new MqttTcpChannel(clientSocket, sslStream);
|
||||
var clientAdapter = new MqttChannelCommunicationAdapter(tcpChannel, new MqttPacketSerializer());
|
||||
ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at TLS endpoint.");
|
||||
|
||||
//excessive CPU consumed if in endless loop of socket errors
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
using System;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
using System.IO;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public sealed class MqttTcpChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
|
||||
public static int BufferSize { get; set; } = 4096 * 20; // Can be changed for fine tuning by library user.
|
||||
|
||||
private Socket _socket;
|
||||
private SslStream _sslStream;
|
||||
|
||||
/// <summary>
|
||||
/// called on client sockets are created in connect
|
||||
/// </summary>
|
||||
public MqttTcpChannel()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// called on server, sockets are passed in
|
||||
/// connect will not be called
|
||||
/// </summary>
|
||||
public MqttTcpChannel(Socket socket, SslStream sslStream)
|
||||
{
|
||||
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
||||
_sslStream = sslStream;
|
||||
CreateStreams(socket, sslStream);
|
||||
}
|
||||
|
||||
public Stream SendStream { get; private set; }
|
||||
public Stream ReceiveStream { get; private set; }
|
||||
public Stream RawReceiveStream { get; private set; }
|
||||
|
||||
public async Task ConnectAsync(MqttClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
if (_socket == null)
|
||||
{
|
||||
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
}
|
||||
|
||||
await Task.Factory.FromAsync(_socket.BeginConnect, _socket.EndConnect, options.Server, options.GetPort(), null).ConfigureAwait(false);
|
||||
|
||||
if (options.TlsOptions.UseTls)
|
||||
{
|
||||
_sslStream = new SslStream(new NetworkStream(_socket, true));
|
||||
|
||||
await _sslStream.AuthenticateAsClientAsync(options.Server, LoadCertificates(options), SslProtocols.Tls12, options.TlsOptions.CheckCertificateRevocation).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
CreateStreams(_socket, _sslStream);
|
||||
}
|
||||
|
||||
public Task DisconnectAsync()
|
||||
{
|
||||
Dispose();
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
RawReceiveStream?.Dispose();
|
||||
RawReceiveStream = null;
|
||||
|
||||
ReceiveStream?.Dispose();
|
||||
ReceiveStream = null;
|
||||
|
||||
SendStream?.Dispose();
|
||||
SendStream = null;
|
||||
|
||||
_socket?.Dispose();
|
||||
_socket = null;
|
||||
|
||||
_sslStream?.Dispose();
|
||||
_sslStream = null;
|
||||
}
|
||||
|
||||
private void CreateStreams(Socket socket, Stream sslStream)
|
||||
{
|
||||
RawReceiveStream = sslStream ?? new NetworkStream(socket);
|
||||
|
||||
//cannot use this as default buffering prevents from receiving the first connect message
|
||||
//need two streams otherwise read and write have to be synchronized
|
||||
SendStream = new BufferedStream(RawReceiveStream, BufferSize);
|
||||
ReceiveStream = new BufferedStream(RawReceiveStream, BufferSize);
|
||||
}
|
||||
|
||||
private static X509CertificateCollection LoadCertificates(MqttClientOptions options)
|
||||
{
|
||||
var certificates = new X509CertificateCollection();
|
||||
if (options.TlsOptions.Certificates == null)
|
||||
{
|
||||
return certificates;
|
||||
}
|
||||
|
||||
foreach (var certificate in options.TlsOptions.Certificates)
|
||||
{
|
||||
certificates.Add(new X509Certificate(certificate));
|
||||
}
|
||||
|
||||
return certificates;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public sealed class MqttWebSocketChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
private ClientWebSocket _webSocket;
|
||||
|
||||
public Stream RawReceiveStream { get; private set; }
|
||||
public Stream SendStream => RawReceiveStream;
|
||||
public Stream ReceiveStream => RawReceiveStream;
|
||||
|
||||
public async Task ConnectAsync(MqttClientOptions options)
|
||||
{
|
||||
var uri = options.Server;
|
||||
if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
uri = "ws://" + uri;
|
||||
}
|
||||
|
||||
if (options.Port.HasValue)
|
||||
{
|
||||
uri += ":" + options.Port;
|
||||
}
|
||||
|
||||
_webSocket = new ClientWebSocket();
|
||||
_webSocket.Options.KeepAliveInterval = options.KeepAlivePeriod;
|
||||
await _webSocket.ConnectAsync(new Uri(uri), CancellationToken.None).ConfigureAwait(false);
|
||||
RawReceiveStream = new WebSocketStream(_webSocket);
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync()
|
||||
{
|
||||
RawReceiveStream = null;
|
||||
|
||||
if (_webSocket == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_webSocket?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public class WebSocketStream : Stream
|
||||
{
|
||||
private readonly ClientWebSocket _webSocket;
|
||||
|
||||
public WebSocketStream(ClientWebSocket webSocket)
|
||||
{
|
||||
_webSocket = webSocket;
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
var currentOffset = offset;
|
||||
var targetOffset = offset + count;
|
||||
while (_webSocket.State == WebSocketState.Open && currentOffset < targetOffset)
|
||||
{
|
||||
var response = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, currentOffset, count), cancellationToken).ConfigureAwait(false);
|
||||
currentOffset += response.Count;
|
||||
|
||||
if (response.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return currentOffset - offset;
|
||||
}
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
return _webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), WebSocketMessageType.Binary, true, cancellationToken);
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public override bool CanRead => true;
|
||||
public override bool CanSeek => false;
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => throw new NotSupportedException();
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void SetLength(long value)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{A480EF90-0EAA-4D9A-B271-47A9C47F6F7D}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>MQTTnet</RootNamespace>
|
||||
<AssemblyName>MQTTnet</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|AnyCPU'">
|
||||
<OutputPath>bin\Any CPU\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x86\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
||||
<OutputPath>bin\x86\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|x86'">
|
||||
<OutputPath>bin\x86\Any CPU\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x64\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
|
||||
<OutputPath>bin\x64\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|x64'">
|
||||
<OutputPath>bin\x64\Any CPU\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Implementations\MqttWebSocketChannel.cs" />
|
||||
<Compile Include="Implementations\WebSocketStream.cs" />
|
||||
<Compile Include="MqttClientFactory.cs" />
|
||||
<Compile Include="MqttServerFactory.cs" />
|
||||
<Compile Include="Implementations\MqttServerAdapter.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Implementations\MqttTcpChannel.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj">
|
||||
<Project>{2ecb99e4-72d0-4c23-99ba-93d511d3967d}</Project>
|
||||
<Name>MQTTnet.Core</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet
|
||||
{
|
||||
public class MqttClientFactory : IMqttClientFactory
|
||||
{
|
||||
public IMqttClient CreateMqttClient(MqttClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
return new MqttClient(options, new MqttChannelCommunicationAdapter(GetMqttCommunicationChannel(options), new MqttPacketSerializer()));
|
||||
}
|
||||
|
||||
private static IMqttCommunicationChannel GetMqttCommunicationChannel(MqttClientOptions options)
|
||||
{
|
||||
switch (options.ConnectionType)
|
||||
{
|
||||
case MqttConnectionType.Tcp:
|
||||
return new MqttTcpChannel();
|
||||
case MqttConnectionType.Ws:
|
||||
return new MqttWebSocketChannel();
|
||||
|
||||
default:
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Server;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet
|
||||
{
|
||||
public class MqttServerFactory : IMqttServerFactory
|
||||
{
|
||||
public IMqttServer CreateMqttServer(MqttServerOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
return new MqttServer(options, new List<IMqttServerAdapter> { new MqttServerAdapter() });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
[assembly: AssemblyTitle("MQTTnet")]
|
||||
[assembly: AssemblyDescription("MQTTnet for .NET Framework")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Christian Kratky")]
|
||||
[assembly: AssemblyProduct("MQTTnet")]
|
||||
[assembly: AssemblyCopyright("Copyright © Christian Kratky 2016-2017")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
[assembly: ComVisible(false)]
|
||||
[assembly: Guid("a480ef90-0eaa-4d9a-b271-47a9c47f6f7d")]
|
||||
[assembly: AssemblyVersion("2.3.0.0")]
|
||||
[assembly: AssemblyFileVersion("2.3.0.0")]
|
||||
@@ -0,0 +1,76 @@
|
||||
#if WINDOWS_UWP
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Server;
|
||||
using Windows.Networking.Sockets;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
||||
{
|
||||
private readonly ILogger<MqttServerAdapter> _logger;
|
||||
private readonly IMqttCommunicationAdapterFactory _communicationAdapterFactory;
|
||||
private StreamSocketListener _defaultEndpointSocket;
|
||||
|
||||
public MqttServerAdapter(ILogger<MqttServerAdapter> logger, IMqttCommunicationAdapterFactory communicationAdapterFactory)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_communicationAdapterFactory = communicationAdapterFactory ?? throw new ArgumentNullException(nameof(communicationAdapterFactory));
|
||||
}
|
||||
|
||||
public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||
|
||||
public async Task StartAsync(MqttServerOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
if (_defaultEndpointSocket != null) throw new InvalidOperationException("Server is already started.");
|
||||
|
||||
if (options.DefaultEndpointOptions.IsEnabled)
|
||||
{
|
||||
_defaultEndpointSocket = new StreamSocketListener();
|
||||
await _defaultEndpointSocket.BindServiceNameAsync(options.GetDefaultEndpointPort().ToString(), SocketProtectionLevel.PlainSocket);
|
||||
_defaultEndpointSocket.ConnectionReceived += AcceptDefaultEndpointConnectionsAsync;
|
||||
}
|
||||
|
||||
if (options.TlsEndpointOptions.IsEnabled)
|
||||
{
|
||||
throw new NotSupportedException("TLS servers are not supported for UWP apps.");
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync()
|
||||
{
|
||||
if (_defaultEndpointSocket != null)
|
||||
{
|
||||
_defaultEndpointSocket.ConnectionReceived -= AcceptDefaultEndpointConnectionsAsync;
|
||||
}
|
||||
|
||||
_defaultEndpointSocket?.Dispose();
|
||||
_defaultEndpointSocket = null;
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
StopAsync();
|
||||
}
|
||||
|
||||
private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
|
||||
{
|
||||
try
|
||||
{
|
||||
var clientAdapter = _communicationAdapterFactory.CreateServerCommunicationAdapter(new MqttTcpChannel(args.Socket));
|
||||
ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(new EventId(), exception, "Error while accepting connection at default endpoint.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
#if NET452 || NETSTANDARD1_3
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
@@ -7,28 +8,32 @@ using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using MQTTnet.Core.Server;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
||||
{
|
||||
private readonly ILogger<MqttServerAdapter> _logger;
|
||||
private readonly IMqttCommunicationAdapterFactory _communicationAdapterFactory;
|
||||
|
||||
private CancellationTokenSource _cancellationTokenSource;
|
||||
private Socket _defaultEndpointSocket;
|
||||
private Socket _tlsEndpointSocket;
|
||||
private X509Certificate2 _tlsCertificate;
|
||||
|
||||
private bool _isRunning;
|
||||
|
||||
public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
|
||||
|
||||
public void Start(MqttServerOptions options)
|
||||
public MqttServerAdapter(ILogger<MqttServerAdapter> logger, IMqttCommunicationAdapterFactory communicationAdapterFactory)
|
||||
{
|
||||
if (_isRunning) throw new InvalidOperationException("Server is already started.");
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_communicationAdapterFactory = communicationAdapterFactory ?? throw new ArgumentNullException(nameof(communicationAdapterFactory));
|
||||
}
|
||||
|
||||
_isRunning = true;
|
||||
public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||
|
||||
public Task StartAsync(MqttServerOptions options)
|
||||
{
|
||||
if (_cancellationTokenSource != null) throw new InvalidOperationException("Server is already started.");
|
||||
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
@@ -49,6 +54,10 @@ namespace MQTTnet.Implementations
|
||||
}
|
||||
|
||||
_tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
|
||||
if (!_tlsCertificate.HasPrivateKey)
|
||||
{
|
||||
throw new InvalidOperationException("The certificate for TLS encryption must contain the private key.");
|
||||
}
|
||||
|
||||
_tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
_tlsEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetTlsEndpointPort()));
|
||||
@@ -56,12 +65,12 @@ namespace MQTTnet.Implementations
|
||||
|
||||
Task.Run(() => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
public Task StopAsync()
|
||||
{
|
||||
_isRunning = false;
|
||||
|
||||
_cancellationTokenSource?.Cancel(false);
|
||||
_cancellationTokenSource?.Dispose();
|
||||
_cancellationTokenSource = null;
|
||||
@@ -69,13 +78,17 @@ namespace MQTTnet.Implementations
|
||||
_defaultEndpointSocket?.Dispose();
|
||||
_defaultEndpointSocket = null;
|
||||
|
||||
_tlsCertificate = null;
|
||||
|
||||
_tlsEndpointSocket?.Dispose();
|
||||
_tlsEndpointSocket = null;
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
StopAsync();
|
||||
}
|
||||
|
||||
private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
|
||||
@@ -84,13 +97,18 @@ namespace MQTTnet.Implementations
|
||||
{
|
||||
try
|
||||
{
|
||||
//todo: else branch can be used with min dependency NET46
|
||||
#if NET452
|
||||
var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
|
||||
#else
|
||||
var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);
|
||||
var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, null), new MqttPacketSerializer());
|
||||
ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
|
||||
#endif
|
||||
var clientAdapter = _communicationAdapterFactory.CreateServerCommunicationAdapter(new MqttTcpChannel(clientSocket, null));
|
||||
ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at default endpoint.");
|
||||
_logger.LogError(new EventId(), exception, "Error while accepting connection at default endpoint.");
|
||||
|
||||
//excessive CPU consumed if in endless loop of socket errors
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
|
||||
@@ -104,17 +122,21 @@ namespace MQTTnet.Implementations
|
||||
{
|
||||
try
|
||||
{
|
||||
#if NET452
|
||||
var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
|
||||
#else
|
||||
var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
|
||||
#endif
|
||||
|
||||
var sslStream = new SslStream(new NetworkStream(clientSocket));
|
||||
await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
|
||||
|
||||
var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer());
|
||||
ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
|
||||
var clientAdapter = _communicationAdapterFactory.CreateServerCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream));
|
||||
ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at TLS endpoint.");
|
||||
_logger.LogError(new EventId(), exception, "Error while accepting connection at TLS endpoint.");
|
||||
|
||||
//excessive CPU consumed if in endless loop of socket errors
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
|
||||
@@ -122,4 +144,5 @@ namespace MQTTnet.Implementations
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,133 @@
|
||||
#if WINDOWS_UWP
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices.WindowsRuntime;
|
||||
using System.Threading.Tasks;
|
||||
using Windows.Networking;
|
||||
using Windows.Networking.Sockets;
|
||||
using Windows.Security.Cryptography.Certificates;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public sealed class MqttTcpChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
private readonly MqttClientTcpOptions _options;
|
||||
private StreamSocket _socket;
|
||||
|
||||
public MqttTcpChannel(MqttClientTcpOptions options)
|
||||
{
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
public MqttTcpChannel(StreamSocket socket)
|
||||
{
|
||||
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
||||
|
||||
CreateStreams();
|
||||
}
|
||||
|
||||
public Stream SendStream { get; private set; }
|
||||
public Stream ReceiveStream { get; private set; }
|
||||
|
||||
public static Func<MqttClientTcpOptions, IEnumerable<ChainValidationResult>> CustomIgnorableServerCertificateErrorsResolver { get; set; }
|
||||
|
||||
public async Task ConnectAsync()
|
||||
{
|
||||
if (_socket == null)
|
||||
{
|
||||
_socket = new StreamSocket();
|
||||
}
|
||||
|
||||
if (!_options.TlsOptions.UseTls)
|
||||
{
|
||||
await _socket.ConnectAsync(new HostName(_options.Server), _options.GetPort().ToString());
|
||||
}
|
||||
else
|
||||
{
|
||||
_socket.Control.ClientCertificate = LoadCertificate(_options);
|
||||
|
||||
foreach (var ignorableChainValidationResult in ResolveIgnorableServerCertificateErrors())
|
||||
{
|
||||
_socket.Control.IgnorableServerCertificateErrors.Add(ignorableChainValidationResult);
|
||||
}
|
||||
|
||||
await _socket.ConnectAsync(new HostName(_options.Server), _options.GetPort().ToString(), SocketProtectionLevel.Tls12);
|
||||
}
|
||||
|
||||
CreateStreams();
|
||||
}
|
||||
|
||||
public Task DisconnectAsync()
|
||||
{
|
||||
Dispose();
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
SendStream?.Dispose();
|
||||
SendStream = null;
|
||||
|
||||
ReceiveStream?.Dispose();
|
||||
ReceiveStream = null;
|
||||
|
||||
_socket?.Dispose();
|
||||
_socket = null;
|
||||
}
|
||||
|
||||
private void CreateStreams()
|
||||
{
|
||||
SendStream = _socket.OutputStream.AsStreamForWrite();
|
||||
ReceiveStream = _socket.InputStream.AsStreamForRead();
|
||||
}
|
||||
|
||||
private static Certificate LoadCertificate(MqttClientTcpOptions options)
|
||||
{
|
||||
if (options.TlsOptions.Certificates == null || !options.TlsOptions.Certificates.Any())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (options.TlsOptions.Certificates.Count > 1)
|
||||
{
|
||||
throw new NotSupportedException("Only one client certificate is supported for UWP.");
|
||||
}
|
||||
|
||||
return new Certificate(options.TlsOptions.Certificates.First().AsBuffer());
|
||||
}
|
||||
|
||||
private IEnumerable<ChainValidationResult> ResolveIgnorableServerCertificateErrors()
|
||||
{
|
||||
if (CustomIgnorableServerCertificateErrorsResolver != null)
|
||||
{
|
||||
return CustomIgnorableServerCertificateErrorsResolver(_options);
|
||||
}
|
||||
|
||||
var result = new List<ChainValidationResult>();
|
||||
|
||||
if (_options.TlsOptions.IgnoreCertificateRevocationErrors)
|
||||
{
|
||||
result.Add(ChainValidationResult.RevocationInformationMissing);
|
||||
//_socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Revoked); Not supported.
|
||||
result.Add(ChainValidationResult.RevocationFailure);
|
||||
}
|
||||
|
||||
if (_options.TlsOptions.IgnoreCertificateChainErrors)
|
||||
{
|
||||
result.Add(ChainValidationResult.IncompleteChain);
|
||||
}
|
||||
|
||||
if (_options.TlsOptions.AllowUntrustedCertificates)
|
||||
{
|
||||
result.Add(ChainValidationResult.Untrusted);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,3 +1,4 @@
|
||||
#if NET452 || NETSTANDARD1_3
|
||||
using System;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
@@ -7,19 +8,30 @@ using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public sealed class MqttTcpChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
private readonly MqttClientTcpOptions _options;
|
||||
|
||||
//todo: this can be used with min dependency NetStandard1.6
|
||||
#if NET452
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
|
||||
public static int BufferSize { get; set; } = 4096 * 20; // Can be changed for fine tuning by library user.
|
||||
#endif
|
||||
|
||||
private Socket _socket;
|
||||
private SslStream _sslStream;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// called on client sockets are created in connect
|
||||
/// </summary>
|
||||
public MqttTcpChannel()
|
||||
public MqttTcpChannel(MqttClientTcpOptions options)
|
||||
{
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -30,34 +42,36 @@ namespace MQTTnet.Implementations
|
||||
{
|
||||
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
||||
_sslStream = sslStream;
|
||||
ReceiveStream = (Stream)sslStream ?? new NetworkStream(socket);
|
||||
|
||||
CreateStreams(socket, sslStream);
|
||||
}
|
||||
|
||||
public Stream SendStream => ReceiveStream;
|
||||
public Stream SendStream { get; private set; }
|
||||
public Stream ReceiveStream { get; private set; }
|
||||
public Stream RawReceiveStream => ReceiveStream;
|
||||
|
||||
public async Task ConnectAsync(MqttClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
public static Func<X509Certificate, X509Chain, SslPolicyErrors, MqttClientTcpOptions, bool> CustomCertificateValidationCallback { get; set; }
|
||||
|
||||
public async Task ConnectAsync()
|
||||
{
|
||||
if (_socket == null)
|
||||
{
|
||||
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
}
|
||||
|
||||
await _socket.ConnectAsync(options.Server, options.GetPort()).ConfigureAwait(false);
|
||||
//todo: else brach can be used with min dependency NET46
|
||||
#if NET452
|
||||
await Task.Factory.FromAsync(_socket.BeginConnect, _socket.EndConnect, _options.Server, _options.GetPort(), null).ConfigureAwait(false);
|
||||
#else
|
||||
await _socket.ConnectAsync(_options.Server, _options.GetPort()).ConfigureAwait(false);
|
||||
#endif
|
||||
|
||||
if (options.TlsOptions.UseTls)
|
||||
if (_options.TlsOptions.UseTls)
|
||||
{
|
||||
_sslStream = new SslStream(new NetworkStream(_socket, true));
|
||||
ReceiveStream = _sslStream;
|
||||
await _sslStream.AuthenticateAsClientAsync(options.Server, LoadCertificates(options), SslProtocols.Tls12, options.TlsOptions.CheckCertificateRevocation).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
ReceiveStream = new NetworkStream(_socket);
|
||||
_sslStream = new SslStream(new NetworkStream(_socket, true), false, InternalUserCertificateValidationCallback);
|
||||
await _sslStream.AuthenticateAsClientAsync(_options.Server, LoadCertificates(_options), SslProtocols.Tls12, _options.TlsOptions.IgnoreCertificateRevocationErrors).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
CreateStreams(_socket, _sslStream);
|
||||
}
|
||||
|
||||
public Task DisconnectAsync()
|
||||
@@ -75,7 +89,38 @@ namespace MQTTnet.Implementations
|
||||
_sslStream = null;
|
||||
}
|
||||
|
||||
private static X509CertificateCollection LoadCertificates(MqttClientOptions options)
|
||||
private bool InternalUserCertificateValidationCallback(object sender, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
|
||||
{
|
||||
if (CustomCertificateValidationCallback != null)
|
||||
{
|
||||
return CustomCertificateValidationCallback(x509Certificate, chain, sslPolicyErrors, _options);
|
||||
}
|
||||
|
||||
if (sslPolicyErrors == SslPolicyErrors.None)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (chain.ChainStatus.Any(c => c.Status == X509ChainStatusFlags.RevocationStatusUnknown || c.Status == X509ChainStatusFlags.Revoked || c.Status == X509ChainStatusFlags.RevocationStatusUnknown))
|
||||
{
|
||||
if (!_options.TlsOptions.IgnoreCertificateRevocationErrors)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (chain.ChainStatus.Any(c => c.Status == X509ChainStatusFlags.PartialChain))
|
||||
{
|
||||
if (!_options.TlsOptions.IgnoreCertificateChainErrors)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return _options.TlsOptions.AllowUntrustedCertificates;
|
||||
}
|
||||
|
||||
private static X509CertificateCollection LoadCertificates(MqttClientTcpOptions options)
|
||||
{
|
||||
var certificates = new X509CertificateCollection();
|
||||
if (options.TlsOptions.Certificates == null)
|
||||
@@ -90,5 +135,24 @@ namespace MQTTnet.Implementations
|
||||
|
||||
return certificates;
|
||||
}
|
||||
|
||||
private void CreateStreams(Socket socket, Stream sslStream)
|
||||
{
|
||||
var stream = sslStream ?? new NetworkStream(socket);
|
||||
|
||||
//cannot use this as default buffering prevents from receiving the first connect message
|
||||
//need two streams otherwise read and write have to be synchronized
|
||||
|
||||
//todo: if branch can be used with min dependency NetStandard1.6
|
||||
#if NET452
|
||||
SendStream = new BufferedStream(stream, BufferSize);
|
||||
ReceiveStream = new BufferedStream(stream, BufferSize);
|
||||
#else
|
||||
SendStream = stream;
|
||||
ReceiveStream = stream;
|
||||
#endif
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -3,6 +3,7 @@ using MQTTnet.Core.Client;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -10,28 +11,59 @@ namespace MQTTnet.Implementations
|
||||
{
|
||||
public sealed class MqttWebSocketChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
private readonly MqttClientWebSocketOptions _options;
|
||||
private ClientWebSocket _webSocket;
|
||||
|
||||
public MqttWebSocketChannel(MqttClientWebSocketOptions options)
|
||||
{
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
public Stream SendStream => RawReceiveStream;
|
||||
public Stream ReceiveStream => RawReceiveStream;
|
||||
public Stream RawReceiveStream { get; private set; }
|
||||
|
||||
public async Task ConnectAsync(MqttClientOptions options)
|
||||
public async Task ConnectAsync()
|
||||
{
|
||||
var uri = options.Server;
|
||||
var uri = _options.Uri;
|
||||
if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
uri = "ws://" + uri;
|
||||
}
|
||||
|
||||
if (options.Port.HasValue)
|
||||
{
|
||||
uri += ":" + options.Port;
|
||||
}
|
||||
|
||||
_webSocket = new ClientWebSocket();
|
||||
_webSocket.Options.KeepAliveInterval = options.KeepAlivePeriod;
|
||||
await _webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
|
||||
|
||||
if (_options.RequestHeaders != null)
|
||||
{
|
||||
foreach (var requestHeader in _options.RequestHeaders)
|
||||
{
|
||||
_webSocket.Options.SetRequestHeader(requestHeader.Key, requestHeader.Value);
|
||||
}
|
||||
}
|
||||
|
||||
if (_options.SubProtocols != null)
|
||||
{
|
||||
foreach (var subProtocol in _options.SubProtocols)
|
||||
{
|
||||
_webSocket.Options.AddSubProtocol(subProtocol);
|
||||
}
|
||||
}
|
||||
|
||||
if (_options.CookieContainer != null)
|
||||
{
|
||||
_webSocket.Options.Cookies = _options.CookieContainer;
|
||||
}
|
||||
|
||||
if (_options.TlsOptions?.UseTls == true && _options.TlsOptions?.Certificates != null)
|
||||
{
|
||||
_webSocket.Options.ClientCertificates = new X509CertificateCollection();
|
||||
foreach (var certificate in _options.TlsOptions.Certificates)
|
||||
{
|
||||
_webSocket.Options.ClientCertificates.Add(new X509Certificate(certificate));
|
||||
}
|
||||
}
|
||||
|
||||
await _webSocket.ConnectAsync(new Uri(uri), CancellationToken.None).ConfigureAwait(false);
|
||||
RawReceiveStream = new WebSocketStream(_webSocket);
|
||||
}
|
||||
|
||||
@@ -44,12 +76,16 @@ namespace MQTTnet.Implementations
|
||||
return;
|
||||
}
|
||||
|
||||
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false);
|
||||
if (_webSocket.State == WebSocketState.Open || _webSocket.State == WebSocketState.Connecting)
|
||||
{
|
||||
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_webSocket?.Dispose();
|
||||
_webSocket = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,17 @@ using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Exceptions;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public class WebSocketStream : Stream
|
||||
{
|
||||
private readonly ClientWebSocket _webSocket;
|
||||
private readonly WebSocket _webSocket;
|
||||
|
||||
public WebSocketStream(ClientWebSocket webSocket)
|
||||
public WebSocketStream(WebSocket webSocket)
|
||||
{
|
||||
_webSocket = webSocket;
|
||||
_webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
|
||||
}
|
||||
|
||||
public override bool CanRead => true;
|
||||
@@ -41,6 +42,7 @@ namespace MQTTnet.Implementations
|
||||
{
|
||||
var response = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, currentOffset, count), cancellationToken).ConfigureAwait(false);
|
||||
currentOffset += response.Count;
|
||||
count -= response.Count;
|
||||
|
||||
if (response.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
@@ -48,6 +50,11 @@ namespace MQTTnet.Implementations
|
||||
}
|
||||
}
|
||||
|
||||
if (_webSocket.State == WebSocketState.Closed)
|
||||
{
|
||||
throw new MqttCommunicationException( "connection closed" );
|
||||
}
|
||||
|
||||
return currentOffset - offset;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard1.3</TargetFramework>
|
||||
<TargetFrameworks>netstandard1.3;net452;uap10.0</TargetFrameworks>
|
||||
<AssemblyName>MQTTnet</AssemblyName>
|
||||
<RootNamespace>MQTTnet</RootNamespace>
|
||||
<AssemblyVersion>2.3.0.0</AssemblyVersion>
|
||||
<FileVersion>2.3.0.0</FileVersion>
|
||||
<AssemblyVersion>2.5.0.0</AssemblyVersion>
|
||||
<FileVersion>2.5.0.0</FileVersion>
|
||||
<Version>0.0.0.0</Version>
|
||||
<Company />
|
||||
<Product />
|
||||
@@ -14,19 +14,41 @@
|
||||
<PackageId />
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == 'uap10.0'">
|
||||
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||
<NugetTargetMoniker>UAP,Version=v10.0</NugetTargetMoniker>
|
||||
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
|
||||
<TargetPlatformVersion>10.0.16299.0</TargetPlatformVersion>
|
||||
<TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion>
|
||||
<TargetFrameworkIdentifier>.NETCore</TargetFrameworkIdentifier>
|
||||
<TargetFrameworkVersion>v5.0</TargetFrameworkVersion>
|
||||
<DefineConstants>$(DefineConstants);WINDOWS_UWP</DefineConstants>
|
||||
<LanguageTargets>$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets</LanguageTargets>
|
||||
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'" />
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="1.1.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.Net.Security" Version="4.3.1" />
|
||||
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework)'=='netstandard1.3'">
|
||||
<PackageReference Include="System.Net.Security" Version="4.3.2" />
|
||||
<PackageReference Include="System.Net.WebSockets" Version="4.3.0" />
|
||||
<PackageReference Include="System.Net.WebSockets.Client" Version="4.3.1" />
|
||||
<PackageReference Include="System.Threading.Thread" Version="4.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework)'=='uap10.0'">
|
||||
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="5.4.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet
|
||||
{
|
||||
public class MqttClientFactory : IMqttClientFactory
|
||||
{
|
||||
public IMqttClient CreateMqttClient(MqttClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
return new MqttClient(options, new MqttChannelCommunicationAdapter(GetMqttCommunicationChannel(options), new MqttPacketSerializer()));
|
||||
}
|
||||
|
||||
private static IMqttCommunicationChannel GetMqttCommunicationChannel(MqttClientOptions options)
|
||||
{
|
||||
switch (options.ConnectionType)
|
||||
{
|
||||
case MqttConnectionType.Tcp:
|
||||
return new MqttTcpChannel();
|
||||
case MqttConnectionType.Ws:
|
||||
return new MqttWebSocketChannel();
|
||||
|
||||
default:
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MQTTnet.Implementations;
|
||||
using MQTTnet.Core.ManagedClient;
|
||||
using MQTTnet.Core.Server;
|
||||
using MQTTnet.Core.Channel;
|
||||
|
||||
namespace MQTTnet
|
||||
{
|
||||
public class MqttFactory : IMqttCommunicationAdapterFactory, IMqttClientSesssionFactory, IMqttClientFactory, IMqttServerFactory
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
private static IServiceProvider BuildServiceProvider()
|
||||
{
|
||||
var serviceProvider = new ServiceCollection()
|
||||
.AddMqttClient()
|
||||
.AddMqttServer()
|
||||
.AddLogging()
|
||||
.BuildServiceProvider();
|
||||
|
||||
serviceProvider.GetRequiredService<ILoggerFactory>()
|
||||
.AddMqttTrace();
|
||||
|
||||
return serviceProvider;
|
||||
}
|
||||
|
||||
public MqttFactory()
|
||||
: this(BuildServiceProvider())
|
||||
{
|
||||
}
|
||||
|
||||
public MqttFactory(IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
public ILoggerFactory GetLoggerFactory()
|
||||
{
|
||||
return _serviceProvider.GetRequiredService<ILoggerFactory>();
|
||||
}
|
||||
|
||||
public IMqttCommunicationAdapter CreateClientCommunicationAdapter(IMqttClientOptions options)
|
||||
{
|
||||
var logger = _serviceProvider.GetRequiredService<ILogger<MqttChannelCommunicationAdapter>>();
|
||||
return new MqttChannelCommunicationAdapter(CreateCommunicationChannel(options.ChannelOptions), CreateSerializer(options.ProtocolVersion), logger);
|
||||
}
|
||||
|
||||
public IMqttCommunicationAdapter CreateServerCommunicationAdapter(IMqttCommunicationChannel channel)
|
||||
{
|
||||
var serializer = _serviceProvider.GetRequiredService<IMqttPacketSerializer>();
|
||||
var logger = _serviceProvider.GetRequiredService<ILogger<MqttChannelCommunicationAdapter>>();
|
||||
return new MqttChannelCommunicationAdapter(channel, serializer, logger);
|
||||
}
|
||||
|
||||
public IMqttCommunicationChannel CreateCommunicationChannel(IMqttClientChannelOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
switch (options)
|
||||
{
|
||||
case MqttClientTcpOptions tcpOptions:
|
||||
return CreateTcpChannel(tcpOptions);
|
||||
case MqttClientWebSocketOptions webSocketOptions:
|
||||
return CreateWebSocketChannel(webSocketOptions);
|
||||
default:
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
|
||||
public MqttTcpChannel CreateTcpChannel(MqttClientTcpOptions tcpOptions)
|
||||
{
|
||||
return new MqttTcpChannel(tcpOptions);
|
||||
}
|
||||
|
||||
public MqttWebSocketChannel CreateWebSocketChannel(MqttClientWebSocketOptions webSocketOptions)
|
||||
{
|
||||
return new MqttWebSocketChannel(webSocketOptions);
|
||||
}
|
||||
|
||||
public MqttPacketSerializer CreateSerializer(MqttProtocolVersion protocolVersion)
|
||||
{
|
||||
return new MqttPacketSerializer
|
||||
{
|
||||
ProtocolVersion = protocolVersion
|
||||
};
|
||||
}
|
||||
|
||||
public MqttClientSession CreateClientSession(string clientId, MqttClientSessionsManager clientSessionsManager)
|
||||
{
|
||||
return new MqttClientSession(
|
||||
clientId,
|
||||
_serviceProvider.GetRequiredService<IOptions<MqttServerOptions>>(),
|
||||
clientSessionsManager,
|
||||
_serviceProvider.GetRequiredService<MqttClientSubscriptionsManager>(),
|
||||
_serviceProvider.GetRequiredService<ILogger<MqttClientSession>>(),
|
||||
_serviceProvider.GetRequiredService<ILogger<MqttClientPendingMessagesQueue>>(),
|
||||
_serviceProvider.GetRequiredService<IMqttClientRetainedMessageManager>()
|
||||
);
|
||||
}
|
||||
|
||||
public IMqttClient CreateMqttClient()
|
||||
{
|
||||
return _serviceProvider.GetRequiredService<IMqttClient>();
|
||||
}
|
||||
|
||||
public IManagedMqttClient CreateManagedMqttClient()
|
||||
{
|
||||
return _serviceProvider.GetRequiredService<IManagedMqttClient>();
|
||||
}
|
||||
|
||||
public IMqttServer CreateMqttServer()
|
||||
{
|
||||
return _serviceProvider.GetRequiredService<IMqttServer>();
|
||||
}
|
||||
|
||||
public IMqttServer CreateMqttServer(Action<MqttServerOptions> configure)
|
||||
{
|
||||
if (configure == null) throw new ArgumentNullException(nameof(configure));
|
||||
|
||||
var options = _serviceProvider.GetRequiredService<IOptions<MqttServerOptions>>();
|
||||
configure(options.Value);
|
||||
|
||||
return _serviceProvider.GetRequiredService<IMqttServer>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Server;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet
|
||||
{
|
||||
public class MqttServerFactory : IMqttServerFactory
|
||||
{
|
||||
public IMqttServer CreateMqttServer(MqttServerOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
return new MqttServer(options, new List<IMqttServerAdapter> { new MqttServerAdapter() });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.ManagedClient;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using MQTTnet.Core.Server;
|
||||
using MQTTnet.Implementations;
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
|
||||
namespace MQTTnet
|
||||
{
|
||||
public static class ServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddMqttServer(this IServiceCollection services)
|
||||
{
|
||||
services.AddMqttServerServices();
|
||||
|
||||
services.AddSingleton<IMqttServer>(s => s.GetService<MqttServer>());
|
||||
services.AddSingleton<MqttServer>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddMqttServerServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddOptions();
|
||||
services.AddSingleton<MqttFactory>();
|
||||
services.AddSingleton<IMqttCommunicationAdapterFactory>(s => s.GetService<MqttFactory>());
|
||||
services.AddSingleton<IMqttClientSesssionFactory>(s => s.GetService<MqttFactory>());
|
||||
|
||||
services.AddTransient<IMqttServerAdapter, MqttServerAdapter>();
|
||||
services.AddTransient<IMqttPacketSerializer, MqttPacketSerializer>();
|
||||
|
||||
services.AddSingleton<MqttClientSessionsManager>();
|
||||
services.AddTransient<MqttClientSubscriptionsManager>();
|
||||
services.AddSingleton<IMqttClientRetainedMessageManager, MqttClientRetainedMessagesManager>();
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddMqttServer(this IServiceCollection services, Action<MqttServerOptions> configureOptions)
|
||||
{
|
||||
return services
|
||||
.AddMqttServer()
|
||||
.Configure(configureOptions);
|
||||
}
|
||||
|
||||
public static IServiceCollection AddMqttClient(this IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<MqttFactory>();
|
||||
services.AddSingleton<IMqttCommunicationAdapterFactory>(s => s.GetService<MqttFactory>());
|
||||
|
||||
services.AddTransient<IMqttClient, MqttClient>();
|
||||
services.AddTransient<MqttClient>();
|
||||
services.AddTransient<IManagedMqttClient, ManagedMqttClient>();
|
||||
services.AddTransient<ManagedMqttClient>();
|
||||
services.AddTransient<IMqttPacketSerializer, MqttPacketSerializer>();
|
||||
services.AddTransient<MqttPacketDispatcher>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static ILoggerFactory AddMqttTrace(this ILoggerFactory factory)
|
||||
{
|
||||
factory.AddProvider(new MqttNetTrace());
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using MQTTnet.Core.Server;
|
||||
using Windows.Networking.Sockets;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
||||
{
|
||||
private StreamSocketListener _defaultEndpointSocket;
|
||||
|
||||
private bool _isRunning;
|
||||
|
||||
public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
|
||||
|
||||
public void Start(MqttServerOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
if (_isRunning) throw new InvalidOperationException("Server is already started.");
|
||||
|
||||
_isRunning = true;
|
||||
|
||||
if (options.DefaultEndpointOptions.IsEnabled)
|
||||
{
|
||||
_defaultEndpointSocket = new StreamSocketListener();
|
||||
_defaultEndpointSocket.BindServiceNameAsync(options.GetDefaultEndpointPort().ToString(), SocketProtectionLevel.PlainSocket).GetAwaiter().GetResult();
|
||||
_defaultEndpointSocket.ConnectionReceived += AcceptDefaultEndpointConnectionsAsync;
|
||||
}
|
||||
|
||||
if (options.TlsEndpointOptions.IsEnabled)
|
||||
{
|
||||
throw new NotSupportedException("TLS servers are not supported for UWP apps.");
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_isRunning = false;
|
||||
|
||||
_defaultEndpointSocket?.Dispose();
|
||||
_defaultEndpointSocket = null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
}
|
||||
|
||||
private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
|
||||
{
|
||||
try
|
||||
{
|
||||
var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(args.Socket), new MqttPacketSerializer());
|
||||
ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(args.Socket.Information.RemoteAddress.ToString(), clientAdapter));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at default endpoint.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices.WindowsRuntime;
|
||||
using System.Threading.Tasks;
|
||||
using Windows.Networking;
|
||||
using Windows.Networking.Sockets;
|
||||
using Windows.Security.Cryptography.Certificates;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public sealed class MqttTcpChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
private StreamSocket _socket;
|
||||
|
||||
public MqttTcpChannel()
|
||||
{
|
||||
}
|
||||
|
||||
public MqttTcpChannel(StreamSocket socket)
|
||||
{
|
||||
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
||||
}
|
||||
|
||||
public Stream SendStream { get; private set; }
|
||||
public Stream ReceiveStream { get; private set; }
|
||||
public Stream RawReceiveStream { get; private set; }
|
||||
|
||||
public async Task ConnectAsync(MqttClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
if (_socket == null)
|
||||
{
|
||||
_socket = new StreamSocket();
|
||||
}
|
||||
|
||||
if (!options.TlsOptions.UseTls)
|
||||
{
|
||||
await _socket.ConnectAsync(new HostName(options.Server), options.GetPort().ToString());
|
||||
}
|
||||
else
|
||||
{
|
||||
_socket.Control.ClientCertificate = LoadCertificate(options);
|
||||
|
||||
if (!options.TlsOptions.CheckCertificateRevocation)
|
||||
{
|
||||
_socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain);
|
||||
_socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationInformationMissing);
|
||||
}
|
||||
|
||||
await _socket.ConnectAsync(new HostName(options.Server), options.GetPort().ToString(), SocketProtectionLevel.Tls12);
|
||||
}
|
||||
|
||||
SendStream = _socket.OutputStream.AsStreamForWrite();
|
||||
ReceiveStream = _socket.InputStream.AsStreamForRead();
|
||||
RawReceiveStream = ReceiveStream;
|
||||
}
|
||||
|
||||
public Task DisconnectAsync()
|
||||
{
|
||||
Dispose();
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
RawReceiveStream?.Dispose();
|
||||
RawReceiveStream = null;
|
||||
|
||||
SendStream?.Dispose();
|
||||
SendStream = null;
|
||||
|
||||
ReceiveStream?.Dispose();
|
||||
ReceiveStream = null;
|
||||
|
||||
_socket?.Dispose();
|
||||
_socket = null;
|
||||
}
|
||||
|
||||
private static Certificate LoadCertificate(MqttClientOptions options)
|
||||
{
|
||||
if (options.TlsOptions.Certificates == null || !options.TlsOptions.Certificates.Any())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (options.TlsOptions.Certificates.Count > 1)
|
||||
{
|
||||
throw new NotSupportedException("Only one client certificate is supported for UWP.");
|
||||
}
|
||||
|
||||
return new Certificate(options.TlsOptions.Certificates.First().AsBuffer());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public sealed class MqttWebSocketChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
private ClientWebSocket _webSocket = new ClientWebSocket();
|
||||
|
||||
public Stream RawReceiveStream { get; private set; }
|
||||
public Stream SendStream => RawReceiveStream;
|
||||
public Stream ReceiveStream => RawReceiveStream;
|
||||
|
||||
public async Task ConnectAsync(MqttClientOptions options)
|
||||
{
|
||||
var uri = options.Server;
|
||||
if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
uri = "ws://" + uri;
|
||||
}
|
||||
|
||||
if (options.Port.HasValue)
|
||||
{
|
||||
uri += ":" + options.Port;
|
||||
}
|
||||
|
||||
_webSocket = new ClientWebSocket();
|
||||
_webSocket.Options.KeepAliveInterval = options.KeepAlivePeriod;
|
||||
await _webSocket.ConnectAsync(new Uri(uri), CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
RawReceiveStream = new WebSocketStream(_webSocket);
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync()
|
||||
{
|
||||
RawReceiveStream = null;
|
||||
|
||||
if (_webSocket == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_webSocket?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Implementations
|
||||
{
|
||||
public class WebSocketStream : Stream
|
||||
{
|
||||
private readonly ClientWebSocket _webSocket;
|
||||
|
||||
public WebSocketStream(ClientWebSocket webSocket)
|
||||
{
|
||||
_webSocket = webSocket;
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
var currentOffset = offset;
|
||||
var targetOffset = offset + count;
|
||||
while (_webSocket.State == WebSocketState.Open && currentOffset < targetOffset)
|
||||
{
|
||||
var response = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, currentOffset, count), cancellationToken).ConfigureAwait(false);
|
||||
currentOffset += response.Count;
|
||||
|
||||
if (response.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return currentOffset - offset;
|
||||
}
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
return _webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), WebSocketMessageType.Binary, true, cancellationToken);
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public override bool CanRead => true;
|
||||
public override bool CanSeek => false;
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => throw new NotSupportedException();
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void SetLength(long value)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{BD60C727-D8E8-40C3-B8E3-C95A864AE611}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>MQTTnet</RootNamespace>
|
||||
<AssemblyName>MQTTnet</AssemblyName>
|
||||
<DefaultLanguage>en-US</DefaultLanguage>
|
||||
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
|
||||
<TargetPlatformVersion>10.0.15063.0</TargetPlatformVersion>
|
||||
<TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion>
|
||||
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<RuntimeIdentifiers>win10-arm;win10-arm-aot;win10-x86;win10-x86-aot;win10-x64;win10-x64-aot</RuntimeIdentifiers>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<NoWarn>CS1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<NoWarn>CS1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x86\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<NoWarn>;2008,CS1591</NoWarn>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<OutputPath>bin\x86\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008,CS1591</NoWarn>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<DocumentationFile>bin\x86\Release\MQTTnet.XML</DocumentationFile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
|
||||
<PlatformTarget>ARM</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\ARM\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<NoWarn>;2008,CS1591</NoWarn>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>ARM</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
|
||||
<PlatformTarget>ARM</PlatformTarget>
|
||||
<OutputPath>bin\ARM\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008,CS1591</NoWarn>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>ARM</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<DocumentationFile>bin\ARM\Release\MQTTnet.XML</DocumentationFile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x64\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<NoWarn>;2008,CS1591</NoWarn>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<OutputPath>bin\x64\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008,CS1591</NoWarn>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<GenerateLibraryLayout>false</GenerateLibraryLayout>
|
||||
<DocumentationFile>bin\x64\Release\MQTTnet.XML</DocumentationFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Implementations\MqttWebSocketChannel.cs" />
|
||||
<Compile Include="MqttClientFactory.cs" />
|
||||
<Compile Include="Implementations\MqttServerAdapter.cs" />
|
||||
<Compile Include="Implementations\MqttTcpChannel.cs" />
|
||||
<Compile Include="MqttServerFactory.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Implementations\WebSocketStream.cs" />
|
||||
<EmbeddedResource Include="Properties\MQTTnet.Universal.rd.xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj">
|
||||
<Project>{2ecb99e4-72d0-4c23-99ba-93d511d3967d}</Project>
|
||||
<Name>MQTTnet.Core</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
|
||||
<Version>5.4.0</Version>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System.Net.Security">
|
||||
<HintPath>..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\System.Net.Security.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' < '14.0' ">
|
||||
<VisualStudioVersion>14.0</VisualStudioVersion>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|AnyCPU'">
|
||||
<OutputPath>bin\Any CPU\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|x86'">
|
||||
<OutputPath>bin\x86\Any CPU\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<DocumentationFile>bin\x86\Release\MQTTnet.XML</DocumentationFile>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|ARM'">
|
||||
<OutputPath>bin\ARM\Any CPU\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<DocumentationFile>bin\ARM\Release\MQTTnet.XML</DocumentationFile>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>ARM</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|x64'">
|
||||
<OutputPath>bin\x64\Any CPU\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<DocumentationFile>bin\x64\Release\MQTTnet.XML</DocumentationFile>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet
|
||||
{
|
||||
public class MqttClientFactory : IMqttClientFactory
|
||||
{
|
||||
public IMqttClient CreateMqttClient(MqttClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
return new MqttClient(options, new MqttChannelCommunicationAdapter(GetMqttCommunicationChannel(options), new MqttPacketSerializer()));
|
||||
}
|
||||
|
||||
private static IMqttCommunicationChannel GetMqttCommunicationChannel(MqttClientOptions options)
|
||||
{
|
||||
switch (options.ConnectionType)
|
||||
{
|
||||
case MqttConnectionType.Tcp:
|
||||
return new MqttTcpChannel();
|
||||
case MqttConnectionType.Ws:
|
||||
return new MqttWebSocketChannel();
|
||||
|
||||
default:
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Server;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet
|
||||
{
|
||||
public class MqttServerFactory : IMqttServerFactory
|
||||
{
|
||||
public IMqttServer CreateMqttServer(MqttServerOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
return new MqttServer(options, new List<IMqttServerAdapter> { new MqttServerAdapter() });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
[assembly: AssemblyTitle("MQTTnet")]
|
||||
[assembly: AssemblyDescription("MQTTnet for Universal Windows")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Christian Kratky")]
|
||||
[assembly: AssemblyProduct("MQTTnet")]
|
||||
[assembly: AssemblyCopyright("Copyright © Christian Kratky 2016-2017")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
[assembly: ComVisible(false)]
|
||||
[assembly: AssemblyVersion("2.3.0.0")]
|
||||
[assembly: AssemblyFileVersion("2.3.0.0")]
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
|
||||
<Library Name="MQTTnet.Universal">
|
||||
</Library>
|
||||
</Directives>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 1.2 KiB |
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 Christian
|
||||
Copyright (c) 2017 Christian Kratky
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Packets;
|
||||
using MQTTnet.Core.Serializer;
|
||||
|
||||
@@ -12,7 +11,7 @@ namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
IMqttPacketSerializer PacketSerializer { get; }
|
||||
|
||||
Task ConnectAsync(TimeSpan timeout, MqttClientOptions options);
|
||||
Task ConnectAsync(TimeSpan timeout);
|
||||
|
||||
Task DisconnectAsync(TimeSpan timeout);
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Channel;
|
||||
|
||||
namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
public interface IMqttCommunicationAdapterFactory
|
||||
{
|
||||
IMqttCommunicationAdapter CreateClientCommunicationAdapter(IMqttClientOptions options);
|
||||
|
||||
IMqttCommunicationAdapter CreateServerCommunicationAdapter(IMqttCommunicationChannel channel);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Server;
|
||||
|
||||
namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
public interface IMqttServerAdapter
|
||||
{
|
||||
event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
|
||||
event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||
|
||||
void Start(MqttServerOptions options);
|
||||
|
||||
void Stop();
|
||||
Task StartAsync(MqttServerOptions options);
|
||||
Task StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,39 +4,43 @@ using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.Exceptions;
|
||||
using MQTTnet.Core.Internal;
|
||||
using MQTTnet.Core.Packets;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
public class MqttChannelCommunicationAdapter : IMqttCommunicationAdapter
|
||||
{
|
||||
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
|
||||
private readonly ILogger<MqttChannelCommunicationAdapter> _logger;
|
||||
private readonly IMqttCommunicationChannel _channel;
|
||||
|
||||
private Task _sendTask = Task.FromResult(0); // this task is used to prevent overlapping write
|
||||
|
||||
public MqttChannelCommunicationAdapter(IMqttCommunicationChannel channel, IMqttPacketSerializer serializer)
|
||||
|
||||
public MqttChannelCommunicationAdapter(IMqttCommunicationChannel channel, IMqttPacketSerializer serializer, ILogger<MqttChannelCommunicationAdapter> logger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_channel = channel ?? throw new ArgumentNullException(nameof(channel));
|
||||
PacketSerializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
|
||||
}
|
||||
|
||||
public IMqttPacketSerializer PacketSerializer { get; }
|
||||
|
||||
public async Task ConnectAsync(TimeSpan timeout, MqttClientOptions options)
|
||||
public async Task ConnectAsync(TimeSpan timeout)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _channel.ConnectAsync(options).TimeoutAfter(timeout).ConfigureAwait(false);
|
||||
await _channel.ConnectAsync().TimeoutAfter(timeout).ConfigureAwait(false);
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (MqttCommunicationTimedOutException)
|
||||
{
|
||||
throw;
|
||||
@@ -61,6 +65,10 @@ namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (MqttCommunicationTimedOutException)
|
||||
{
|
||||
throw;
|
||||
@@ -79,18 +87,20 @@ namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_channel)
|
||||
await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
foreach (var packet in packets)
|
||||
{
|
||||
foreach (var packet in packets)
|
||||
if (packet == null)
|
||||
{
|
||||
MqttTrace.Information(nameof(MqttChannelCommunicationAdapter), "TX >>> {0} [Timeout={1}]", packet, timeout);
|
||||
|
||||
var writeBuffer = PacketSerializer.Serialize(packet);
|
||||
_sendTask = _sendTask.ContinueWith(p => _channel.SendStream.WriteAsync(writeBuffer, 0, writeBuffer.Length, cancellationToken).ConfigureAwait(false), cancellationToken);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
await _sendTask; // configure await false generates stackoverflow
|
||||
_logger.LogInformation("TX >>> {0} [Timeout={1}]", packet, timeout);
|
||||
|
||||
var writeBuffer = PacketSerializer.Serialize(packet);
|
||||
await _channel.SendStream.WriteAsync(writeBuffer, 0, writeBuffer.Length, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (timeout > TimeSpan.Zero)
|
||||
{
|
||||
@@ -105,6 +115,10 @@ namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (MqttCommunicationTimedOutException)
|
||||
{
|
||||
throw;
|
||||
@@ -117,23 +131,27 @@ namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
throw new MqttCommunicationException(exception);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
ReceivedMqttPacket receivedMqttPacket = null;
|
||||
try
|
||||
{
|
||||
ReceivedMqttPacket receivedMqttPacket;
|
||||
if (timeout > TimeSpan.Zero)
|
||||
{
|
||||
receivedMqttPacket = await ReceiveAsync(_channel.RawReceiveStream, cancellationToken).TimeoutAfter(timeout).ConfigureAwait(false);
|
||||
receivedMqttPacket = await ReceiveAsync(_channel.ReceiveStream, cancellationToken).TimeoutAfter(timeout).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
receivedMqttPacket = await ReceiveAsync(_channel.ReceiveStream, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
if (receivedMqttPacket == null || cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw new TaskCanceledException();
|
||||
}
|
||||
@@ -144,13 +162,17 @@ namespace MQTTnet.Core.Adapter
|
||||
throw new MqttProtocolViolationException("Received malformed packet.");
|
||||
}
|
||||
|
||||
MqttTrace.Information(nameof(MqttChannelCommunicationAdapter), "RX <<< {0}", packet);
|
||||
_logger.LogInformation("RX <<< {0}", packet);
|
||||
return packet;
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (MqttCommunicationTimedOutException)
|
||||
{
|
||||
throw;
|
||||
@@ -163,11 +185,19 @@ namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
throw new MqttCommunicationException(exception);
|
||||
}
|
||||
finally
|
||||
{
|
||||
receivedMqttPacket?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<ReceivedMqttPacket> ReceiveAsync(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = MqttPacketReader.ReadHeaderFromSource(stream, cancellationToken);
|
||||
if (header == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (header.BodyLength == 0)
|
||||
{
|
||||
@@ -186,4 +216,4 @@ namespace MQTTnet.Core.Adapter
|
||||
return new ReceivedMqttPacket(header, new MemoryStream(body, 0, body.Length));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
public class MqttClientConnectedEventArgs : EventArgs
|
||||
{
|
||||
public MqttClientConnectedEventArgs(string identifier, IMqttCommunicationAdapter clientAdapter)
|
||||
{
|
||||
Identifier = identifier ?? throw new ArgumentNullException(nameof(identifier));
|
||||
ClientAdapter = clientAdapter ?? throw new ArgumentNullException(nameof(clientAdapter));
|
||||
}
|
||||
|
||||
public string Identifier { get; }
|
||||
|
||||
public IMqttCommunicationAdapter ClientAdapter { get; }
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
public static Task SendPacketsAsync(this IMqttCommunicationAdapter adapter, TimeSpan timeout, CancellationToken cancellationToken, params MqttBasePacket[] packets)
|
||||
{
|
||||
if (adapter == null) throw new ArgumentNullException(nameof(adapter));
|
||||
|
||||
return adapter.SendPacketsAsync(timeout, cancellationToken, packets);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
public class MqttServerAdapterClientAcceptedEventArgs : EventArgs
|
||||
{
|
||||
public MqttServerAdapterClientAcceptedEventArgs(IMqttCommunicationAdapter client)
|
||||
{
|
||||
Client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
}
|
||||
|
||||
public IMqttCommunicationAdapter Client { get; }
|
||||
|
||||
public Task SessionTask { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ using MQTTnet.Core.Packets;
|
||||
|
||||
namespace MQTTnet.Core.Adapter
|
||||
{
|
||||
public class ReceivedMqttPacket
|
||||
public sealed class ReceivedMqttPacket : IDisposable
|
||||
{
|
||||
public ReceivedMqttPacket(MqttPacketHeader header, MemoryStream body)
|
||||
{
|
||||
@@ -15,5 +15,10 @@ namespace MQTTnet.Core.Adapter
|
||||
public MqttPacketHeader Header { get; }
|
||||
|
||||
public MemoryStream Body { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Body?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Core
|
||||
{
|
||||
public static class ApplicationMessagePublisherExtensions
|
||||
{
|
||||
public static Task PublishAsync(this IApplicationMessagePublisher client, params MqttApplicationMessage[] applicationMessages)
|
||||
{
|
||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||
if (applicationMessages == null) throw new ArgumentNullException(nameof(applicationMessages));
|
||||
|
||||
return client.PublishAsync(applicationMessages);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Client;
|
||||
using System.IO;
|
||||
|
||||
namespace MQTTnet.Core.Channel
|
||||
@@ -8,9 +7,8 @@ namespace MQTTnet.Core.Channel
|
||||
{
|
||||
Stream SendStream { get; }
|
||||
Stream ReceiveStream { get; }
|
||||
Stream RawReceiveStream { get; }
|
||||
|
||||
Task ConnectAsync(MqttClientOptions options);
|
||||
Task ConnectAsync();
|
||||
Task DisconnectAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,20 +5,17 @@ using MQTTnet.Core.Packets;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public interface IMqttClient
|
||||
public interface IMqttClient : IApplicationMessageReceiver, IApplicationMessagePublisher
|
||||
{
|
||||
bool IsConnected { get; }
|
||||
|
||||
event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
|
||||
event EventHandler Connected;
|
||||
event EventHandler Disconnected;
|
||||
event EventHandler<MqttClientConnectedEventArgs> Connected;
|
||||
event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
|
||||
|
||||
Task ConnectAsync(MqttApplicationMessage willApplicationMessage = null);
|
||||
Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options);
|
||||
Task DisconnectAsync();
|
||||
|
||||
Task<IList<MqttSubscribeResult>> SubscribeAsync(IEnumerable<TopicFilter> topicFilters);
|
||||
Task UnsubscribeAsync(IEnumerable<string> topicFilters);
|
||||
|
||||
Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public interface IMqttClientChannelOptions
|
||||
{
|
||||
MqttClientTlsOptions TlsOptions { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public interface IMqttClientCredentials
|
||||
{
|
||||
string Password { get; }
|
||||
string Username { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
namespace MQTTnet.Core.Client
|
||||
using MQTTnet.Core.ManagedClient;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public interface IMqttClientFactory
|
||||
{
|
||||
IMqttClient CreateMqttClient(MqttClientOptions options);
|
||||
IMqttClient CreateMqttClient();
|
||||
|
||||
IManagedMqttClient CreateManagedMqttClient();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Serializer;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public interface IMqttClientOptions
|
||||
{
|
||||
string ClientId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The LogId is used to create a scope to correlate logging. If no value is provided the ClientId is used instead
|
||||
/// </summary>
|
||||
string LogId { get; }
|
||||
IMqttClientCredentials Credentials { get; }
|
||||
bool CleanSession { get; }
|
||||
MqttApplicationMessage WillMessage { get; }
|
||||
|
||||
TimeSpan CommunicationTimeout { get; }
|
||||
TimeSpan KeepAlivePeriod { get; }
|
||||
MqttProtocolVersion ProtocolVersion { get; }
|
||||
|
||||
IMqttClientChannelOptions ChannelOptions { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public sealed class MqttApplicationMessageReceivedEventArgs : EventArgs
|
||||
{
|
||||
public MqttApplicationMessageReceivedEventArgs(MqttApplicationMessage applicationMessage)
|
||||
{
|
||||
ApplicationMessage = applicationMessage ?? throw new ArgumentNullException(nameof(applicationMessage));
|
||||
}
|
||||
|
||||
public MqttApplicationMessage ApplicationMessage { get; }
|
||||
}
|
||||
}
|
||||
@@ -4,81 +4,79 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.Exceptions;
|
||||
using MQTTnet.Core.Internal;
|
||||
using MQTTnet.Core.Packets;
|
||||
using MQTTnet.Core.Protocol;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public class MqttClient : IMqttClient
|
||||
{
|
||||
private readonly HashSet<ushort> _unacknowledgedPublishPackets = new HashSet<ushort>();
|
||||
private readonly MqttPacketDispatcher _packetDispatcher = new MqttPacketDispatcher();
|
||||
private readonly MqttClientOptions _options;
|
||||
private readonly IMqttCommunicationAdapter _adapter;
|
||||
private readonly MqttPacketDispatcher _packetDispatcher;
|
||||
private readonly IMqttCommunicationAdapterFactory _communicationAdapterFactory;
|
||||
private readonly ILogger<MqttClient> _logger;
|
||||
|
||||
private IMqttClientOptions _options;
|
||||
private bool _isReceivingPackets;
|
||||
private int _latestPacketIdentifier;
|
||||
private CancellationTokenSource _cancellationTokenSource;
|
||||
private IMqttCommunicationAdapter _adapter;
|
||||
private IDisposable _scopeHandle;
|
||||
|
||||
public MqttClient(MqttClientOptions options, IMqttCommunicationAdapter adapter)
|
||||
public MqttClient(IMqttCommunicationAdapterFactory communicationAdapterFactory, ILogger<MqttClient> logger, MqttPacketDispatcher packetDispatcher)
|
||||
{
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_adapter = adapter ?? throw new ArgumentNullException(nameof(adapter));
|
||||
|
||||
_adapter.PacketSerializer.ProtocolVersion = options.ProtocolVersion;
|
||||
_communicationAdapterFactory = communicationAdapterFactory ?? throw new ArgumentNullException(nameof(communicationAdapterFactory));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_packetDispatcher = packetDispatcher ?? throw new ArgumentNullException(nameof(packetDispatcher));
|
||||
}
|
||||
|
||||
public event EventHandler Connected;
|
||||
public event EventHandler Disconnected;
|
||||
public event EventHandler<MqttClientConnectedEventArgs> Connected;
|
||||
public event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
|
||||
public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
|
||||
|
||||
public bool IsConnected => _cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested;
|
||||
public bool IsConnected { get; private set; }
|
||||
|
||||
public async Task ConnectAsync(MqttApplicationMessage willApplicationMessage = null)
|
||||
public async Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
if (options.ChannelOptions == null) throw new ArgumentException("ChannelOptions are not set.");
|
||||
|
||||
ThrowIfConnected("It is not allowed to connect with a server after the connection is established.");
|
||||
|
||||
try
|
||||
{
|
||||
_options = options;
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
_latestPacketIdentifier = 0;
|
||||
_packetDispatcher.Reset();
|
||||
|
||||
MqttTrace.Verbose(nameof(MqttClient), "Trying to connect with server.");
|
||||
await _adapter.ConnectAsync(_options.DefaultCommunicationTimeout, _options).ConfigureAwait(false);
|
||||
MqttTrace.Verbose(nameof(MqttClient), "Connection with server established.");
|
||||
_adapter = _communicationAdapterFactory.CreateClientCommunicationAdapter(options);
|
||||
|
||||
StartReceivePackets(_cancellationTokenSource.Token);
|
||||
_scopeHandle = _logger.BeginScope(options.LogId ?? options.ClientId);
|
||||
_logger.LogTrace("Trying to connect with server.");
|
||||
await _adapter.ConnectAsync(_options.CommunicationTimeout).ConfigureAwait(false);
|
||||
_logger.LogTrace("Connection with server established.");
|
||||
|
||||
var connectPacket = new MqttConnectPacket
|
||||
{
|
||||
ClientId = _options.ClientId,
|
||||
Username = _options.UserName,
|
||||
Password = _options.Password,
|
||||
CleanSession = _options.CleanSession,
|
||||
KeepAlivePeriod = (ushort)_options.KeepAlivePeriod.TotalSeconds,
|
||||
WillMessage = willApplicationMessage
|
||||
};
|
||||
await SetupIncomingPacketProcessingAsync().ConfigureAwait(false);
|
||||
var connectResponse = await AuthenticateAsync(options.WillMessage).ConfigureAwait(false);
|
||||
|
||||
var response = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket).ConfigureAwait(false);
|
||||
if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted)
|
||||
{
|
||||
throw new MqttConnectingFailedException(response.ConnectReturnCode);
|
||||
}
|
||||
|
||||
MqttTrace.Verbose(nameof(MqttClient), "MQTT connection with server established.");
|
||||
_logger.LogTrace("MQTT connection with server established.");
|
||||
|
||||
if (_options.KeepAlivePeriod != TimeSpan.Zero)
|
||||
{
|
||||
StartSendKeepAliveMessages(_cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
Connected?.Invoke(this, EventArgs.Empty);
|
||||
IsConnected = true;
|
||||
Connected?.Invoke(this, new MqttClientConnectedEventArgs(connectResponse.IsSessionPresent));
|
||||
return new MqttClientConnectResult(connectResponse.IsSessionPresent);
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(new EventId(), exception, "Error while connecting with server.");
|
||||
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
@@ -98,6 +96,7 @@ namespace MQTTnet.Core.Client
|
||||
finally
|
||||
{
|
||||
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||
_scopeHandle.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,40 +149,79 @@ namespace MQTTnet.Core.Client
|
||||
switch (qosGroup.Key)
|
||||
{
|
||||
case MqttQualityOfServiceLevel.AtMostOnce:
|
||||
{
|
||||
// No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
|
||||
await _adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, _cancellationTokenSource.Token, qosPackets);
|
||||
break;
|
||||
}
|
||||
{
|
||||
// No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
|
||||
await _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, qosPackets).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
case MqttQualityOfServiceLevel.AtLeastOnce:
|
||||
{
|
||||
foreach (var publishPacket in qosPackets)
|
||||
{
|
||||
foreach (var publishPacket in qosPackets)
|
||||
{
|
||||
publishPacket.PacketIdentifier = GetNewPacketIdentifier();
|
||||
await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
|
||||
}
|
||||
|
||||
break;
|
||||
publishPacket.PacketIdentifier = GetNewPacketIdentifier();
|
||||
await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case MqttQualityOfServiceLevel.ExactlyOnce:
|
||||
{
|
||||
foreach (var publishPacket in qosPackets)
|
||||
{
|
||||
foreach (var publishPacket in qosPackets)
|
||||
{
|
||||
publishPacket.PacketIdentifier = GetNewPacketIdentifier();
|
||||
var pubRecPacket = await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket).ConfigureAwait(false);
|
||||
await SendAndReceiveAsync<MqttPubCompPacket>(pubRecPacket.CreateResponse<MqttPubRelPacket>()).ConfigureAwait(false);
|
||||
}
|
||||
publishPacket.PacketIdentifier = GetNewPacketIdentifier();
|
||||
var pubRecPacket = await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket).ConfigureAwait(false);
|
||||
await SendAndReceiveAsync<MqttPubCompPacket>(pubRecPacket.CreateResponse<MqttPubRelPacket>()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<MqttConnAckPacket> AuthenticateAsync(MqttApplicationMessage willApplicationMessage)
|
||||
{
|
||||
var connectPacket = new MqttConnectPacket
|
||||
{
|
||||
ClientId = _options.ClientId,
|
||||
Username = _options.Credentials?.Username,
|
||||
Password = _options.Credentials?.Password,
|
||||
CleanSession = _options.CleanSession,
|
||||
KeepAlivePeriod = (ushort) _options.KeepAlivePeriod.TotalSeconds,
|
||||
WillMessage = willApplicationMessage
|
||||
};
|
||||
|
||||
var response = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket).ConfigureAwait(false);
|
||||
if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted)
|
||||
{
|
||||
throw new MqttConnectingFailedException(response.ConnectReturnCode);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private async Task SetupIncomingPacketProcessingAsync()
|
||||
{
|
||||
_isReceivingPackets = false;
|
||||
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Factory.StartNew(
|
||||
() => ReceivePackets(_cancellationTokenSource.Token),
|
||||
_cancellationTokenSource.Token,
|
||||
TaskCreationOptions.LongRunning,
|
||||
TaskScheduler.Default).ConfigureAwait(false);
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
|
||||
while (!_isReceivingPackets && _cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(100)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfNotConnected()
|
||||
{
|
||||
if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
|
||||
@@ -196,6 +234,9 @@ namespace MQTTnet.Core.Client
|
||||
|
||||
private async Task DisconnectInternalAsync()
|
||||
{
|
||||
var clientWasConnected = IsConnected;
|
||||
IsConnected = false;
|
||||
|
||||
var cts = _cancellationTokenSource;
|
||||
if (cts == null || cts.IsCancellationRequested)
|
||||
{
|
||||
@@ -208,16 +249,16 @@ namespace MQTTnet.Core.Client
|
||||
|
||||
try
|
||||
{
|
||||
await _adapter.DisconnectAsync(_options.DefaultCommunicationTimeout).ConfigureAwait(false);
|
||||
MqttTrace.Information(nameof(MqttClient), "Disconnected from adapter.");
|
||||
await _adapter.DisconnectAsync(_options.CommunicationTimeout).ConfigureAwait(false);
|
||||
_logger.LogInformation("Disconnected from adapter.");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Warning(nameof(MqttClient), exception, "Error while disconnecting from adapter.");
|
||||
_logger.LogWarning(new EventId(), exception, "Error while disconnecting from adapter.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Disconnected?.Invoke(this, EventArgs.Empty);
|
||||
Disconnected?.Invoke(this, new MqttClientDisconnectedEventArgs(clientWasConnected));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,7 +266,7 @@ namespace MQTTnet.Core.Client
|
||||
{
|
||||
try
|
||||
{
|
||||
MqttTrace.Information(nameof(MqttClient), "Received <<< {0}", packet);
|
||||
_logger.LogInformation("Received <<< {0}", packet);
|
||||
|
||||
if (packet is MqttPingReqPacket)
|
||||
{
|
||||
@@ -255,7 +296,7 @@ namespace MQTTnet.Core.Client
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Error(nameof(MqttClient), exception, "Unhandled exception while processing received packet.");
|
||||
_logger.LogError(new EventId(), exception, "Unhandled exception while processing received packet.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,11 +305,11 @@ namespace MQTTnet.Core.Client
|
||||
try
|
||||
{
|
||||
var applicationMessage = publishPacket.ToApplicationMessage();
|
||||
ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(applicationMessage));
|
||||
ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(_options.ClientId, applicationMessage));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Error(nameof(MqttClient), exception, "Unhandled exception while handling application message.");
|
||||
_logger.LogError(new EventId(), exception, "Unhandled exception while handling application message.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +324,7 @@ namespace MQTTnet.Core.Client
|
||||
if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
|
||||
{
|
||||
FireApplicationMessageReceivedEvent(publishPacket);
|
||||
await SendAsync(new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
|
||||
await SendAsync(new MqttPubAckPacket {PacketIdentifier = publishPacket.PacketIdentifier});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -296,7 +337,7 @@ namespace MQTTnet.Core.Client
|
||||
}
|
||||
|
||||
FireApplicationMessageReceivedEvent(publishPacket);
|
||||
await SendAsync(new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
|
||||
await SendAsync(new MqttPubRecPacket {PacketIdentifier = publishPacket.PacketIdentifier});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -315,24 +356,24 @@ namespace MQTTnet.Core.Client
|
||||
|
||||
private Task SendAsync(MqttBasePacket packet)
|
||||
{
|
||||
return _adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, _cancellationTokenSource.Token, packet);
|
||||
return _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, packet);
|
||||
}
|
||||
|
||||
private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
|
||||
{
|
||||
var wait = _packetDispatcher.WaitForPacketAsync(requestPacket, typeof(TResponsePacket), _options.DefaultCommunicationTimeout);
|
||||
await _adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, _cancellationTokenSource.Token, requestPacket).ConfigureAwait(false);
|
||||
return (TResponsePacket)await wait.ConfigureAwait(false);
|
||||
var packetAwaiter = _packetDispatcher.WaitForPacketAsync(requestPacket, typeof(TResponsePacket), _options.CommunicationTimeout);
|
||||
await _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, requestPacket).ConfigureAwait(false);
|
||||
return (TResponsePacket) await packetAwaiter.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private ushort GetNewPacketIdentifier()
|
||||
{
|
||||
return (ushort)Interlocked.Increment(ref _latestPacketIdentifier);
|
||||
return (ushort) Interlocked.Increment(ref _latestPacketIdentifier);
|
||||
}
|
||||
|
||||
private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
MqttTrace.Information(nameof(MqttClient), "Start sending keep alive packets.");
|
||||
_logger.LogInformation("Start sending keep alive packets.");
|
||||
|
||||
try
|
||||
{
|
||||
@@ -347,7 +388,7 @@ namespace MQTTnet.Core.Client
|
||||
await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket()).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (MqttCommunicationException exception)
|
||||
@@ -357,28 +398,30 @@ namespace MQTTnet.Core.Client
|
||||
return;
|
||||
}
|
||||
|
||||
MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication exception while sending/receiving keep alive packets.");
|
||||
_logger.LogWarning(new EventId(), exception, "MQTT communication exception while sending/receiving keep alive packets.");
|
||||
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Warning(nameof(MqttClient), exception, "Unhandled exception while sending/receiving keep alive packets.");
|
||||
_logger.LogWarning(new EventId(), exception, "Unhandled exception while sending/receiving keep alive packets.");
|
||||
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
MqttTrace.Information(nameof(MqttClient), "Stopped sending keep alive packets.");
|
||||
_logger.LogInformation("Stopped sending keep alive packets.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReceivePackets(CancellationToken cancellationToken)
|
||||
{
|
||||
MqttTrace.Information(nameof(MqttClient), "Start receiving packets.");
|
||||
_logger.LogInformation("Start receiving packets.");
|
||||
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_isReceivingPackets = true;
|
||||
|
||||
var packet = await _adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
@@ -388,7 +431,7 @@ namespace MQTTnet.Core.Client
|
||||
StartProcessReceivedPacket(packet, cancellationToken);
|
||||
}
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (MqttCommunicationException exception)
|
||||
@@ -398,38 +441,32 @@ namespace MQTTnet.Core.Client
|
||||
return;
|
||||
}
|
||||
|
||||
MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication exception while receiving packets.");
|
||||
_logger.LogWarning(new EventId(), exception, "MQTT communication exception while receiving packets.");
|
||||
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MqttTrace.Error(nameof(MqttClient), exception, "Unhandled exception while receiving packets.");
|
||||
_logger.LogError(new EventId(), exception, "Unhandled exception while receiving packets.");
|
||||
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
MqttTrace.Information(nameof(MqttClient), "Stopped receiving packets.");
|
||||
_logger.LogInformation(nameof(MqttClient), "Stopped receiving packets.");
|
||||
}
|
||||
}
|
||||
|
||||
private void StartProcessReceivedPacket(MqttBasePacket packet, CancellationToken cancellationToken)
|
||||
{
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Run(async () => await ProcessReceivedPacketAsync(packet), cancellationToken).ConfigureAwait(false);
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
}
|
||||
|
||||
private void StartReceivePackets(CancellationToken cancellationToken)
|
||||
{
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Run(async () => await ReceivePackets(cancellationToken), cancellationToken).ConfigureAwait(false); ;
|
||||
Task.Run(() => ProcessReceivedPacketAsync(packet), cancellationToken).ConfigureAwait(false);
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
}
|
||||
|
||||
private void StartSendKeepAliveMessages(CancellationToken cancellationToken)
|
||||
{
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Run(async () => await SendKeepAliveMessagesAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
Task.Factory.StartNew(() => SendKeepAliveMessagesAsync(cancellationToken), cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default)
|
||||
.ConfigureAwait(false);
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public class MqttClientConnectResult
|
||||
{
|
||||
public MqttClientConnectResult(bool isSessionPresent)
|
||||
{
|
||||
IsSessionPresent = isSessionPresent;
|
||||
}
|
||||
|
||||
public bool IsSessionPresent { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public class MqttClientConnectedEventArgs : EventArgs
|
||||
{
|
||||
public MqttClientConnectedEventArgs(bool isSessionPresent)
|
||||
{
|
||||
IsSessionPresent = isSessionPresent;
|
||||
}
|
||||
|
||||
public bool IsSessionPresent { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public class MqttClientCredentials : IMqttClientCredentials
|
||||
{
|
||||
public string Username { get; set; }
|
||||
|
||||
public string Password { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public class MqttClientDisconnectedEventArgs : EventArgs
|
||||
{
|
||||
public MqttClientDisconnectedEventArgs(bool clientWasConnected)
|
||||
{
|
||||
ClientWasConnected = clientWasConnected;
|
||||
}
|
||||
|
||||
public bool ClientWasConnected { get; }
|
||||
}
|
||||
}
|
||||
@@ -2,20 +2,11 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Packets;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public static class MqttClientExtensions
|
||||
{
|
||||
public static Task PublishAsync(this IMqttClient client, params MqttApplicationMessage[] applicationMessages)
|
||||
{
|
||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||
if (applicationMessages == null) throw new ArgumentNullException(nameof(applicationMessages));
|
||||
|
||||
return client.PublishAsync(applicationMessages);
|
||||
}
|
||||
|
||||
public static Task<IList<MqttSubscribeResult>> SubscribeAsync(this IMqttClient client, params TopicFilter[] topicFilters)
|
||||
{
|
||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||
|
||||
@@ -3,28 +3,25 @@ using MQTTnet.Core.Serializer;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public sealed class MqttClientOptions
|
||||
public class MqttClientOptions : IMqttClientOptions
|
||||
{
|
||||
public string Server { get; set; }
|
||||
public MqttApplicationMessage WillMessage { get; set; }
|
||||
|
||||
public int? Port { get; set; }
|
||||
public string ClientId { get; set; } = Guid.NewGuid().ToString("N");
|
||||
|
||||
public MqttClientTlsOptions TlsOptions { get; set; } = new MqttClientTlsOptions();
|
||||
|
||||
public string UserName { get; set; }
|
||||
|
||||
public string Password { get; set; }
|
||||
|
||||
public string ClientId { get; set; } = Guid.NewGuid().ToString().Replace("-", string.Empty);
|
||||
/// <inheritdoc />
|
||||
public string LogId { get; set; }
|
||||
|
||||
public bool CleanSession { get; set; } = true;
|
||||
|
||||
public IMqttClientCredentials Credentials { get; set; } = new MqttClientCredentials();
|
||||
|
||||
public TimeSpan KeepAlivePeriod { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
public TimeSpan DefaultCommunicationTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
public TimeSpan CommunicationTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
public MqttProtocolVersion ProtocolVersion { get; set; } = MqttProtocolVersion.V311;
|
||||
|
||||
public MqttConnectionType ConnectionType { get; set; } = MqttConnectionType.Tcp;
|
||||
public IMqttClientChannelOptions ChannelOptions { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using MQTTnet.Core.Serializer;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public class MqttClientOptionsBuilder
|
||||
{
|
||||
private readonly MqttClientOptions _options = new MqttClientOptions();
|
||||
private MqttClientTcpOptions _tcpOptions;
|
||||
private MqttClientWebSocketOptions _webSocketOptions;
|
||||
|
||||
private MqttClientTlsOptions _tlsOptions;
|
||||
|
||||
public MqttClientOptionsBuilder WithLogId(string value)
|
||||
{
|
||||
_options.LogId = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithProtocolVersion(MqttProtocolVersion value)
|
||||
{
|
||||
_options.ProtocolVersion = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithCommunicationTimeout(TimeSpan value)
|
||||
{
|
||||
_options.CommunicationTimeout = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithCleanSession(bool value = true)
|
||||
{
|
||||
_options.CleanSession = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithKeepAlivePeriod(TimeSpan value)
|
||||
{
|
||||
_options.KeepAlivePeriod = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithClientId(string value)
|
||||
{
|
||||
_options.ClientId = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithWillMessage(MqttApplicationMessage value)
|
||||
{
|
||||
_options.WillMessage = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithCredentials(string username, string password = null)
|
||||
{
|
||||
_options.Credentials = new MqttClientCredentials
|
||||
{
|
||||
Username = username,
|
||||
Password = password
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithTcpServer(string server, int? port = null)
|
||||
{
|
||||
_tcpOptions = new MqttClientTcpOptions
|
||||
{
|
||||
Server = server,
|
||||
Port = port
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithWebSocketServer(string uri)
|
||||
{
|
||||
_webSocketOptions = new MqttClientWebSocketOptions
|
||||
{
|
||||
Uri = uri
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithTls(
|
||||
bool allowUntrustedCertificates = false,
|
||||
bool ignoreCertificateChainErrors = false,
|
||||
bool ignoreCertificateRevocationErrors = false,
|
||||
params byte[][] certificates)
|
||||
{
|
||||
_tlsOptions = new MqttClientTlsOptions
|
||||
{
|
||||
UseTls = true,
|
||||
AllowUntrustedCertificates = allowUntrustedCertificates,
|
||||
IgnoreCertificateChainErrors = ignoreCertificateChainErrors,
|
||||
IgnoreCertificateRevocationErrors = ignoreCertificateRevocationErrors,
|
||||
Certificates = certificates.ToList()
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithTls()
|
||||
{
|
||||
_tlsOptions = new MqttClientTlsOptions
|
||||
{
|
||||
UseTls = true
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public IMqttClientOptions Build()
|
||||
{
|
||||
if (_tlsOptions != null)
|
||||
{
|
||||
if (_tcpOptions == null && _webSocketOptions == null)
|
||||
{
|
||||
throw new InvalidOperationException("A channel (TCP or WebSocket) must be set if TLS is configured.");
|
||||
}
|
||||
|
||||
if (_tcpOptions != null)
|
||||
{
|
||||
_options.ChannelOptions = _tcpOptions;
|
||||
}
|
||||
else
|
||||
{
|
||||
_options.ChannelOptions = _webSocketOptions;
|
||||
}
|
||||
}
|
||||
|
||||
_options.ChannelOptions = (IMqttClientChannelOptions)_tcpOptions ?? _webSocketOptions;
|
||||
|
||||
return _options;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public class MqttClientTcpOptions : IMqttClientChannelOptions
|
||||
{
|
||||
public string Server { get; set; }
|
||||
|
||||
public int? Port { get; set; }
|
||||
|
||||
public MqttClientTlsOptions TlsOptions { get; set; } = new MqttClientTlsOptions();
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2,9 +2,9 @@
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public static class MqttClientOptionsExtensions
|
||||
public static class MqttClientTcpOptionsExtensions
|
||||
{
|
||||
public static int GetPort(this MqttClientOptions options)
|
||||
public static int GetPort(this MqttClientTcpOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
@@ -2,11 +2,15 @@
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public sealed class MqttClientTlsOptions
|
||||
public class MqttClientTlsOptions
|
||||
{
|
||||
public bool UseTls { get; set; }
|
||||
|
||||
public bool CheckCertificateRevocation { get; set; }
|
||||
public bool IgnoreCertificateRevocationErrors { get; set; }
|
||||
|
||||
public bool IgnoreCertificateChainErrors { get; set; }
|
||||
|
||||
public bool AllowUntrustedCertificates { get; set; }
|
||||
|
||||
public List<byte[]> Certificates { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public class MqttClientWebSocketOptions : IMqttClientChannelOptions
|
||||
{
|
||||
public string Uri { get; set; }
|
||||
|
||||
public IDictionary<string, string> RequestHeaders { get; set; }
|
||||
|
||||
public ICollection<string> SubProtocols { get; set; }
|
||||
|
||||
public CookieContainer CookieContainer { get; set; }
|
||||
|
||||
public MqttClientTlsOptions TlsOptions { get; set; } = new MqttClientTlsOptions();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
public enum MqttConnectionType
|
||||
{
|
||||
Tcp,
|
||||
Ws
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.Exceptions;
|
||||
using MQTTnet.Core.Internal;
|
||||
using MQTTnet.Core.Packets;
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Core.Client
|
||||
{
|
||||
@@ -12,6 +12,12 @@ namespace MQTTnet.Core.Client
|
||||
{
|
||||
private readonly ConcurrentDictionary<Type, TaskCompletionSource<MqttBasePacket>> _packetByResponseType = new ConcurrentDictionary<Type, TaskCompletionSource<MqttBasePacket>>();
|
||||
private readonly ConcurrentDictionary<Type, ConcurrentDictionary<ushort, TaskCompletionSource<MqttBasePacket>>> _packetByResponseTypeAndIdentifier = new ConcurrentDictionary<Type, ConcurrentDictionary<ushort, TaskCompletionSource<MqttBasePacket>>>();
|
||||
private readonly ILogger<MqttPacketDispatcher> _logger;
|
||||
|
||||
public MqttPacketDispatcher(ILogger<MqttPacketDispatcher> logger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public async Task<MqttBasePacket> WaitForPacketAsync(MqttBasePacket request, Type responseType, TimeSpan timeout)
|
||||
{
|
||||
@@ -20,11 +26,11 @@ namespace MQTTnet.Core.Client
|
||||
var packetAwaiter = AddPacketAwaiter(request, responseType);
|
||||
try
|
||||
{
|
||||
return await packetAwaiter.Task.TimeoutAfter(timeout);
|
||||
return await packetAwaiter.Task.TimeoutAfter(timeout).ConfigureAwait(false);
|
||||
}
|
||||
catch (MqttCommunicationTimedOutException)
|
||||
{
|
||||
MqttTrace.Warning(nameof(MqttPacketDispatcher), "Timeout while waiting for packet of type '{0}'.", responseType.Name);
|
||||
_logger.LogWarning("Timeout while waiting for packet of type '{0}'.", responseType.Name);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
@@ -67,10 +73,11 @@ namespace MQTTnet.Core.Client
|
||||
private TaskCompletionSource<MqttBasePacket> AddPacketAwaiter(MqttBasePacket request, Type responseType)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<MqttBasePacket>();
|
||||
if (request is IMqttPacketWithIdentifier withIdent)
|
||||
|
||||
if (request is IMqttPacketWithIdentifier requestWithIdentifier)
|
||||
{
|
||||
var byId = _packetByResponseTypeAndIdentifier.GetOrAdd(responseType, key => new ConcurrentDictionary<ushort, TaskCompletionSource<MqttBasePacket>>());
|
||||
byId[withIdent.PacketIdentifier] = tcs;
|
||||
byId[requestWithIdentifier.PacketIdentifier] = tcs;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -82,10 +89,10 @@ namespace MQTTnet.Core.Client
|
||||
|
||||
private void RemovePacketAwaiter(MqttBasePacket request, Type responseType)
|
||||
{
|
||||
if (request is IMqttPacketWithIdentifier withIdent)
|
||||
if (request is IMqttPacketWithIdentifier requestWithIdentifier)
|
||||
{
|
||||
var byId = _packetByResponseTypeAndIdentifier.GetOrAdd(responseType, key => new ConcurrentDictionary<ushort, TaskCompletionSource<MqttBasePacket>>());
|
||||
byId.TryRemove(withIdent.PacketIdentifier, out var _);
|
||||
byId.TryRemove(requestWithIdentifier.PacketIdentifier, out var _);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Core.Diagnostics
|
||||
{
|
||||
public class MqttNetLogger : ILogger
|
||||
{
|
||||
private readonly string _categoryName;
|
||||
private readonly MqttNetTrace _mqttNetTrace;
|
||||
|
||||
public MqttNetLogger(string categoryName, MqttNetTrace mqttNetTrace)
|
||||
{
|
||||
_categoryName = categoryName;
|
||||
_mqttNetTrace = mqttNetTrace;
|
||||
}
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
|
||||
{
|
||||
if (formatter == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(formatter));
|
||||
}
|
||||
|
||||
if (!MqttNetTrace.HasListeners)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var message = formatter(state, exception);
|
||||
var traceMessage = new MqttNetTraceMessage(DateTime.Now, Environment.CurrentManagedThreadId, _categoryName, logLevel, message, exception);
|
||||
_mqttNetTrace.Publish(traceMessage);
|
||||
}
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel)
|
||||
{
|
||||
return MqttNetTrace.HasListeners;
|
||||
}
|
||||
|
||||
//not supported: async local requires netstandard1.3
|
||||
//for implementation see https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Extensions.Logging.Console/ConsoleLogScope.cs
|
||||
public IDisposable BeginScope<TState>(TState state)
|
||||
{
|
||||
return new DisposableScope();
|
||||
}
|
||||
|
||||
private class DisposableScope : IDisposable
|
||||
{
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Core.Diagnostics
|
||||
{
|
||||
public class MqttNetTrace : ILoggerProvider
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, MqttNetLogger> _loggers = new ConcurrentDictionary<string, MqttNetLogger>();
|
||||
|
||||
public static event EventHandler<MqttNetTraceMessagePublishedEventArgs> TraceMessagePublished;
|
||||
|
||||
public static bool HasListeners => TraceMessagePublished != null;
|
||||
|
||||
public void Publish(MqttNetTraceMessage traceMessage)
|
||||
{
|
||||
TraceMessagePublished?.Invoke(this, new MqttNetTraceMessagePublishedEventArgs(traceMessage));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
TraceMessagePublished = null;
|
||||
}
|
||||
|
||||
public ILogger CreateLogger(string categoryName)
|
||||
{
|
||||
return _loggers.GetOrAdd(categoryName, CreateLoggerImplementation);
|
||||
}
|
||||
|
||||
private MqttNetLogger CreateLoggerImplementation(string categoryName)
|
||||
{
|
||||
return new MqttNetLogger(categoryName, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Core.Diagnostics
|
||||
{
|
||||
public sealed class MqttNetTraceMessagePublishedEventArgs : EventArgs
|
||||
{
|
||||
public MqttNetTraceMessagePublishedEventArgs(MqttNetTraceMessage traceMessage)
|
||||
{
|
||||
TraceMessage = traceMessage ?? throw new ArgumentNullException(nameof(traceMessage));
|
||||
}
|
||||
|
||||
public MqttNetTraceMessage TraceMessage { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Core.Diagnostics
|
||||
{
|
||||
public static class MqttTrace
|
||||
{
|
||||
public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
|
||||
|
||||
public static void Verbose(string source, string message, params object[] parameters)
|
||||
{
|
||||
Publish(source, MqttTraceLevel.Verbose, null, message, parameters);
|
||||
}
|
||||
|
||||
public static void Information(string source, string message, params object[] parameters)
|
||||
{
|
||||
Publish(source, MqttTraceLevel.Information, null, message, parameters);
|
||||
}
|
||||
|
||||
public static void Warning(string source, string message, params object[] parameters)
|
||||
{
|
||||
Publish(source, MqttTraceLevel.Warning, null, message, parameters);
|
||||
}
|
||||
|
||||
public static void Warning(string source, Exception exception, string message, params object[] parameters)
|
||||
{
|
||||
Publish(source, MqttTraceLevel.Warning, exception, message, parameters);
|
||||
}
|
||||
|
||||
public static void Error(string source, string message, params object[] parameters)
|
||||
{
|
||||
Publish(source, MqttTraceLevel.Error, null, message, parameters);
|
||||
}
|
||||
|
||||
public static void Error(string source, Exception exception, string message, params object[] parameters)
|
||||
{
|
||||
Publish(source, MqttTraceLevel.Error, exception, message, parameters);
|
||||
}
|
||||
|
||||
private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message, params object[] parameters)
|
||||
{
|
||||
var handler = TraceMessagePublished;
|
||||
if (handler == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (parameters?.Length > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
message = string.Format(message, parameters);
|
||||
}
|
||||
catch (Exception formatException)
|
||||
{
|
||||
Error(nameof(MqttTrace), formatException, "Error while tracing message: " + message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
handler.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace MQTTnet.Core.Diagnostics
|
||||
{
|
||||
public enum MqttTraceLevel
|
||||
{
|
||||
Verbose,
|
||||
Information,
|
||||
Warning,
|
||||
Error
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -1,11 +1,13 @@
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Core.Diagnostics
|
||||
{
|
||||
public sealed class MqttTraceMessagePublishedEventArgs : EventArgs
|
||||
public sealed class MqttNetTraceMessage
|
||||
{
|
||||
public MqttTraceMessagePublishedEventArgs(int threadId, string source, MqttTraceLevel level, string message, Exception exception)
|
||||
public MqttNetTraceMessage(DateTime timestamp, int threadId, string source, LogLevel level, string message, Exception exception)
|
||||
{
|
||||
Timestamp = timestamp;
|
||||
ThreadId = threadId;
|
||||
Source = source;
|
||||
Level = level;
|
||||
@@ -13,11 +15,13 @@ namespace MQTTnet.Core.Diagnostics
|
||||
Exception = exception;
|
||||
}
|
||||
|
||||
public DateTime Timestamp { get; }
|
||||
|
||||
public int ThreadId { get; }
|
||||
|
||||
public string Source { get; }
|
||||
|
||||
public MqttTraceLevel Level { get; }
|
||||
public LogLevel Level { get; }
|
||||
|
||||
public string Message { get; }
|
||||
|
||||
@@ -17,10 +17,5 @@ namespace MQTTnet.Core.Exceptions
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public MqttCommunicationException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Core
|
||||
{
|
||||
public interface IApplicationMessagePublisher
|
||||
{
|
||||
Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Client;
|
||||
|
||||
namespace MQTTnet.Core
|
||||
{
|
||||
public interface IApplicationMessageReceiver
|
||||
{
|
||||
event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,13 @@ namespace MQTTnet.Core.Internal
|
||||
{
|
||||
public static MqttApplicationMessage ToApplicationMessage(this MqttPublishPacket publishPacket)
|
||||
{
|
||||
return new MqttApplicationMessage(
|
||||
publishPacket.Topic,
|
||||
publishPacket.Payload,
|
||||
publishPacket.QualityOfServiceLevel,
|
||||
publishPacket.Retain
|
||||
);
|
||||
return new MqttApplicationMessage
|
||||
{
|
||||
Topic = publishPacket.Topic,
|
||||
Payload = publishPacket.Payload,
|
||||
QualityOfServiceLevel = publishPacket.QualityOfServiceLevel,
|
||||
Retain = publishPacket.Retain
|
||||
};
|
||||
}
|
||||
|
||||
public static MqttPublishPacket ToPublishPacket(this MqttApplicationMessage applicationMessage)
|
||||
|
||||
@@ -17,19 +17,15 @@
|
||||
<PackageIconUrl></PackageIconUrl>
|
||||
<RepositoryUrl></RepositoryUrl>
|
||||
<PackageTags></PackageTags>
|
||||
<FileVersion>2.3.0.0</FileVersion>
|
||||
<AssemblyVersion>2.3.0.0</AssemblyVersion>
|
||||
<FileVersion>2.5.0.0</FileVersion>
|
||||
<AssemblyVersion>2.5.0.0</AssemblyVersion>
|
||||
<PackageLicenseUrl></PackageLicenseUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|AnyCPU'" />
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|x64'" />
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'" />
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'" />
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|x86'" />
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="1.1.2" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="1.1.2" />
|
||||
<PackageReference Include="System.Threading" Version="4.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Client;
|
||||
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public interface IManagedMqttClient : IApplicationMessageReceiver, IApplicationMessagePublisher
|
||||
{
|
||||
bool IsConnected { get; }
|
||||
|
||||
event EventHandler<MqttClientConnectedEventArgs> Connected;
|
||||
event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
|
||||
|
||||
Task StartAsync(IManagedMqttClientOptions options);
|
||||
Task StopAsync();
|
||||
|
||||
Task SubscribeAsync(IEnumerable<TopicFilter> topicFilters);
|
||||
Task UnsubscribeAsync(IEnumerable<TopicFilter> topicFilters);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Client;
|
||||
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public interface IManagedMqttClientOptions
|
||||
{
|
||||
IMqttClientOptions ClientOptions { get; }
|
||||
|
||||
TimeSpan AutoReconnectDelay { get; }
|
||||
|
||||
IManagedMqttClientStorage Storage { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public interface IManagedMqttClientStorage
|
||||
{
|
||||
Task SaveQueuedMessagesAsync(IList<MqttApplicationMessage> messages);
|
||||
|
||||
Task<IList<MqttApplicationMessage>> LoadQueuedMessagesAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Exceptions;
|
||||
using MQTTnet.Core.Protocol;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public class ManagedMqttClient : IManagedMqttClient
|
||||
{
|
||||
private readonly ManagedMqttClientStorageManager _storageManager = new ManagedMqttClientStorageManager();
|
||||
private readonly BlockingCollection<MqttApplicationMessage> _messageQueue = new BlockingCollection<MqttApplicationMessage>();
|
||||
private readonly HashSet<TopicFilter> _subscriptions = new HashSet<TopicFilter>();
|
||||
|
||||
private readonly IMqttClient _mqttClient;
|
||||
private readonly ILogger<ManagedMqttClient> _logger;
|
||||
|
||||
private CancellationTokenSource _connectionCancellationToken;
|
||||
private CancellationTokenSource _publishingCancellationToken;
|
||||
|
||||
private IManagedMqttClientOptions _options;
|
||||
private bool _subscriptionsNotPushed;
|
||||
|
||||
public ManagedMqttClient(ILogger<ManagedMqttClient> logger, IMqttClient mqttClient)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_mqttClient = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient));
|
||||
|
||||
_mqttClient.Connected += OnConnected;
|
||||
_mqttClient.Disconnected += OnDisconnected;
|
||||
_mqttClient.ApplicationMessageReceived += OnApplicationMessageReceived;
|
||||
}
|
||||
|
||||
public bool IsConnected => _mqttClient.IsConnected;
|
||||
|
||||
public event EventHandler<MqttClientConnectedEventArgs> Connected;
|
||||
public event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
|
||||
public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
|
||||
|
||||
public async Task StartAsync(IManagedMqttClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
if (options.ClientOptions == null) throw new ArgumentException("The client options are not set.", nameof(options));
|
||||
|
||||
if (!options.ClientOptions.CleanSession)
|
||||
{
|
||||
throw new NotSupportedException("The managed client does not support existing sessions.");
|
||||
}
|
||||
|
||||
if (_connectionCancellationToken != null)
|
||||
{
|
||||
throw new InvalidOperationException("The managed client is already started.");
|
||||
}
|
||||
|
||||
_options = options;
|
||||
await _storageManager.SetStorageAsync(_options.Storage).ConfigureAwait(false);
|
||||
|
||||
if (_options.Storage != null)
|
||||
{
|
||||
var loadedMessages = await _options.Storage.LoadQueuedMessagesAsync().ConfigureAwait(false);
|
||||
foreach (var loadedMessage in loadedMessages)
|
||||
{
|
||||
_messageQueue.Add(loadedMessage);
|
||||
}
|
||||
}
|
||||
|
||||
_connectionCancellationToken = new CancellationTokenSource();
|
||||
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Factory.StartNew(() => MaintainConnectionAsync(_connectionCancellationToken.Token), _connectionCancellationToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
|
||||
_logger.LogInformation("Started");
|
||||
}
|
||||
|
||||
public Task StopAsync()
|
||||
{
|
||||
_connectionCancellationToken?.Cancel(false);
|
||||
_connectionCancellationToken = null;
|
||||
|
||||
while (_messageQueue.Any())
|
||||
{
|
||||
_messageQueue.Take();
|
||||
}
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public async Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages)
|
||||
{
|
||||
if (applicationMessages == null) throw new ArgumentNullException(nameof(applicationMessages));
|
||||
|
||||
foreach (var applicationMessage in applicationMessages)
|
||||
{
|
||||
await _storageManager.AddAsync(applicationMessage).ConfigureAwait(false);
|
||||
_messageQueue.Add(applicationMessage);
|
||||
}
|
||||
}
|
||||
|
||||
public Task SubscribeAsync(IEnumerable<TopicFilter> topicFilters)
|
||||
{
|
||||
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
||||
|
||||
lock (_subscriptions)
|
||||
{
|
||||
foreach (var topicFilter in topicFilters)
|
||||
{
|
||||
if (_subscriptions.Add(topicFilter))
|
||||
{
|
||||
_subscriptionsNotPushed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public Task UnsubscribeAsync(IEnumerable<TopicFilter> topicFilters)
|
||||
{
|
||||
lock (_subscriptions)
|
||||
{
|
||||
foreach (var topicFilter in topicFilters)
|
||||
{
|
||||
if (_subscriptions.Remove(topicFilter))
|
||||
{
|
||||
_subscriptionsNotPushed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
private async Task MaintainConnectionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var connectionState = await ReconnectIfRequiredAsync().ConfigureAwait(false);
|
||||
if (connectionState == ReconnectionResult.NotConnected)
|
||||
{
|
||||
_publishingCancellationToken?.Cancel(false);
|
||||
_publishingCancellationToken = null;
|
||||
|
||||
await Task.Delay(_options.AutoReconnectDelay, cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (connectionState == ReconnectionResult.Reconnected || _subscriptionsNotPushed)
|
||||
{
|
||||
await PushSubscriptionsAsync();
|
||||
|
||||
_publishingCancellationToken = new CancellationTokenSource();
|
||||
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Factory.StartNew(() => PublishQueuedMessagesAsync(_publishingCancellationToken.Token), _publishingCancellationToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (connectionState == ReconnectionResult.StillConnected)
|
||||
{
|
||||
await Task.Delay(100, _connectionCancellationToken.Token).ConfigureAwait(false); // Consider using the _Disconnected_ event here. (TaskCompletionSource)
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (MqttCommunicationException exception)
|
||||
{
|
||||
_logger.LogWarning(new EventId(), exception, "Communication exception while maintaining connection.");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(new EventId(), exception, "Unhandled exception while maintaining connection.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await _mqttClient.DisconnectAsync().ConfigureAwait(false);
|
||||
_logger.LogInformation("Stopped");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PublishQueuedMessagesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var message = _messageQueue.Take(cancellationToken);
|
||||
if (message == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await TryPublishQueuedMessageAsync(message).ConfigureAwait(false);
|
||||
await _storageManager.RemoveAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
_logger.LogInformation("Stopped publishing messages");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryPublishQueuedMessageAsync(MqttApplicationMessage message)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _mqttClient.PublishAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
catch (MqttCommunicationException exception)
|
||||
{
|
||||
_logger.LogWarning(new EventId(), exception, "Publishing application message failed.");
|
||||
|
||||
if (message.QualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
|
||||
{
|
||||
_messageQueue.Add(message);
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(new EventId(), exception, "Unhandled exception while publishing queued application message.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PushSubscriptionsAsync()
|
||||
{
|
||||
_logger.LogInformation(nameof(ManagedMqttClient), "Synchronizing subscriptions");
|
||||
|
||||
List<TopicFilter> subscriptions;
|
||||
lock (_subscriptions)
|
||||
{
|
||||
subscriptions = _subscriptions.ToList();
|
||||
_subscriptionsNotPushed = false;
|
||||
}
|
||||
|
||||
if (!_subscriptions.Any())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _mqttClient.SubscribeAsync(subscriptions).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogWarning(new EventId(), exception, "Synchronizing subscriptions failed");
|
||||
_subscriptionsNotPushed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ReconnectionResult> ReconnectIfRequiredAsync()
|
||||
{
|
||||
if (_mqttClient.IsConnected)
|
||||
{
|
||||
return ReconnectionResult.StillConnected;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _mqttClient.ConnectAsync(_options.ClientOptions).ConfigureAwait(false);
|
||||
return ReconnectionResult.Reconnected;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return ReconnectionResult.NotConnected;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||
{
|
||||
ApplicationMessageReceived?.Invoke(this, eventArgs);
|
||||
}
|
||||
|
||||
private void OnDisconnected(object sender, MqttClientDisconnectedEventArgs eventArgs)
|
||||
{
|
||||
Disconnected?.Invoke(this, eventArgs);
|
||||
}
|
||||
|
||||
private void OnConnected(object sender, MqttClientConnectedEventArgs eventArgs)
|
||||
{
|
||||
Connected?.Invoke(this, eventArgs);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public static class ManagedMqttClientExtensions
|
||||
{
|
||||
public static Task SubscribeAsync(this IManagedMqttClient managedClient, params TopicFilter[] topicFilters)
|
||||
{
|
||||
if (managedClient == null) throw new ArgumentNullException(nameof(managedClient));
|
||||
|
||||
return managedClient.SubscribeAsync(topicFilters);
|
||||
}
|
||||
|
||||
public static Task UnsubscribeAsync(this IManagedMqttClient managedClient, params TopicFilter[] topicFilters)
|
||||
{
|
||||
if (managedClient == null) throw new ArgumentNullException(nameof(managedClient));
|
||||
|
||||
return managedClient.UnsubscribeAsync(topicFilters);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Client;
|
||||
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public class ManagedMqttClientOptions : IManagedMqttClientOptions
|
||||
{
|
||||
public IMqttClientOptions ClientOptions { get; set; }
|
||||
|
||||
public TimeSpan AutoReconnectDelay { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
public IManagedMqttClientStorage Storage { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using MQTTnet.Core.Client;
|
||||
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public class ManagedMqttClientOptionsBuilder
|
||||
{
|
||||
private readonly ManagedMqttClientOptions _options = new ManagedMqttClientOptions();
|
||||
|
||||
public ManagedMqttClientOptionsBuilder WithAutoReconnectDelay(TimeSpan value)
|
||||
{
|
||||
_options.AutoReconnectDelay = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ManagedMqttClientOptionsBuilder WithStorage(IManagedMqttClientStorage value)
|
||||
{
|
||||
_options.Storage = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ManagedMqttClientOptionsBuilder WithClientOptions(IMqttClientOptions value)
|
||||
{
|
||||
_options.ClientOptions = value ?? throw new ArgumentNullException(nameof(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ManagedMqttClientOptionsBuilder WithClientOptions(Action<MqttClientOptionsBuilder> options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
|
||||
var builder = new MqttClientOptionsBuilder();
|
||||
options(builder);
|
||||
_options.ClientOptions = builder.Build();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public ManagedMqttClientOptions Build()
|
||||
{
|
||||
if (_options.ClientOptions == null)
|
||||
{
|
||||
throw new InvalidOperationException("The ClientOptions cannot be null.");
|
||||
}
|
||||
|
||||
return _options;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public class ManagedMqttClientStorageManager
|
||||
{
|
||||
private readonly List<MqttApplicationMessage> _applicationMessages = new List<MqttApplicationMessage>();
|
||||
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
|
||||
private IManagedMqttClientStorage _storage;
|
||||
|
||||
public async Task SetStorageAsync(IManagedMqttClientStorage storage)
|
||||
{
|
||||
await _semaphore.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
_storage = storage;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task AddAsync(MqttApplicationMessage applicationMessage)
|
||||
{
|
||||
await _semaphore.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_storage == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_applicationMessages.Add(applicationMessage);
|
||||
await SaveAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RemoveAsync(MqttApplicationMessage applicationMessage)
|
||||
{
|
||||
await _semaphore.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_storage == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var index = _applicationMessages.IndexOf(applicationMessage);
|
||||
if (index == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_applicationMessages.RemoveAt(index);
|
||||
await SaveAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private Task SaveAsync()
|
||||
{
|
||||
return _storage.SaveQueuedMessagesAsync(_applicationMessages);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace MQTTnet.Core.ManagedClient
|
||||
{
|
||||
public enum ReconnectionResult
|
||||
{
|
||||
StillConnected,
|
||||
Reconnected,
|
||||
NotConnected
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,11 @@ namespace MQTTnet.Core
|
||||
{
|
||||
public sealed class MqttApplicationMessage
|
||||
{
|
||||
public MqttApplicationMessage()
|
||||
{
|
||||
}
|
||||
|
||||
[Obsolete("Use object initializer or _MqttApplicationMessageBuilder_ instead.")]
|
||||
public MqttApplicationMessage(string topic, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, bool retain)
|
||||
{
|
||||
Topic = topic ?? throw new ArgumentNullException(nameof(topic));
|
||||
@@ -13,12 +18,12 @@ namespace MQTTnet.Core
|
||||
Retain = retain;
|
||||
}
|
||||
|
||||
public string Topic { get; }
|
||||
public string Topic { get; set; }
|
||||
|
||||
public byte[] Payload { get; }
|
||||
public byte[] Payload { get; set; }
|
||||
|
||||
public MqttQualityOfServiceLevel QualityOfServiceLevel { get; }
|
||||
public MqttQualityOfServiceLevel QualityOfServiceLevel { get; set; }
|
||||
|
||||
public bool Retain { get; }
|
||||
public bool Retain { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using MQTTnet.Core.Exceptions;
|
||||
using MQTTnet.Core.Protocol;
|
||||
|
||||
namespace MQTTnet.Core
|
||||
{
|
||||
public class MqttApplicationMessageBuilder
|
||||
{
|
||||
private MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
|
||||
private string _topic;
|
||||
private byte[] _payload;
|
||||
private bool _retain;
|
||||
|
||||
public MqttApplicationMessageBuilder WithTopic(string topic)
|
||||
{
|
||||
_topic = topic;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessageBuilder WithPayload(IEnumerable<byte> payload)
|
||||
{
|
||||
if (payload == null)
|
||||
{
|
||||
_payload = null;
|
||||
return this;
|
||||
}
|
||||
|
||||
_payload = payload.ToArray();
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessageBuilder WithPayload(MemoryStream payload)
|
||||
{
|
||||
if (payload == null)
|
||||
{
|
||||
_payload = null;
|
||||
return this;
|
||||
}
|
||||
|
||||
if (payload.Length == 0)
|
||||
{
|
||||
_payload = new byte[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
_payload = new byte[payload.Length - payload.Position];
|
||||
payload.Read(_payload, 0, _payload.Length);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessageBuilder WithPayload(string payload)
|
||||
{
|
||||
if (payload == null)
|
||||
{
|
||||
_payload = null;
|
||||
return this;
|
||||
}
|
||||
|
||||
_payload = string.IsNullOrEmpty(payload) ? new byte[0] : Encoding.UTF8.GetBytes(payload);
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessageBuilder WithQualityOfServiceLevel(MqttQualityOfServiceLevel qualityOfServiceLevel)
|
||||
{
|
||||
_qualityOfServiceLevel = qualityOfServiceLevel;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessageBuilder WithRetainFlag(bool value = true)
|
||||
{
|
||||
_retain = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessageBuilder WithAtLeastOnceQoS()
|
||||
{
|
||||
_qualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessageBuilder WithAtMostOnceQoS()
|
||||
{
|
||||
_qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessageBuilder WithExactlyOnceQoS()
|
||||
{
|
||||
_qualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttApplicationMessage Build()
|
||||
{
|
||||
if (string.IsNullOrEmpty(_topic))
|
||||
{
|
||||
throw new MqttProtocolViolationException("Topic is not set.");
|
||||
}
|
||||
|
||||
return new MqttApplicationMessage
|
||||
{
|
||||
Topic = _topic,
|
||||
Payload = _payload ?? new byte[0],
|
||||
QualityOfServiceLevel = _qualityOfServiceLevel,
|
||||
Retain = _retain
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using MQTTnet.Core.Protocol;
|
||||
|
||||
namespace MQTTnet.Core
|
||||
{
|
||||
public class MqttApplicationMessageFactory
|
||||
{
|
||||
public MqttApplicationMessage CreateApplicationMessage(string topic, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
|
||||
{
|
||||
if (topic == null) throw new ArgumentNullException(nameof(topic));
|
||||
|
||||
return CreateApplicationMessage(topic, new byte[0], qualityOfServiceLevel, retain);
|
||||
}
|
||||
|
||||
public MqttApplicationMessage CreateApplicationMessage(string topic, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
|
||||
{
|
||||
if (topic == null) throw new ArgumentNullException(nameof(topic));
|
||||
|
||||
if (payload == null)
|
||||
{
|
||||
payload = new byte[0];
|
||||
}
|
||||
|
||||
return new MqttApplicationMessage(topic, payload, qualityOfServiceLevel, retain);
|
||||
}
|
||||
|
||||
public MqttApplicationMessage CreateApplicationMessage<TPayload>(string topic, TPayload payload, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
|
||||
{
|
||||
if (topic == null) throw new ArgumentNullException(nameof(topic));
|
||||
|
||||
var payloadString = Convert.ToString(payload, CultureInfo.InvariantCulture);
|
||||
var payloadBuffer = string.IsNullOrEmpty(payloadString) ? new byte[0] : Encoding.UTF8.GetBytes(payloadString);
|
||||
|
||||
return CreateApplicationMessage(topic, payloadBuffer, qualityOfServiceLevel, retain);
|
||||
}
|
||||
|
||||
public MqttApplicationMessage CreateApplicationMessage(string topic, Stream payload, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
|
||||
{
|
||||
if (topic == null) throw new ArgumentNullException(nameof(topic));
|
||||
|
||||
byte[] payloadBuffer;
|
||||
if (payload == null || payload.Length == 0)
|
||||
{
|
||||
payloadBuffer = new byte[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
payloadBuffer = new byte[payload.Length - payload.Position];
|
||||
payload.Read(payloadBuffer, 0, payloadBuffer.Length);
|
||||
}
|
||||
|
||||
return CreateApplicationMessage(topic, payloadBuffer, qualityOfServiceLevel, retain);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Core.Server
|
||||
namespace MQTTnet.Core
|
||||
{
|
||||
public sealed class MqttApplicationMessageReceivedEventArgs : EventArgs
|
||||
{
|
||||
@@ -12,8 +12,7 @@ namespace MQTTnet.Core.Packets
|
||||
|
||||
if (responsePacket is IMqttPacketWithIdentifier responsePacketWithIdentifier)
|
||||
{
|
||||
var requestPacketWithIdentifier = packet as IMqttPacketWithIdentifier;
|
||||
if (requestPacketWithIdentifier == null)
|
||||
if (!(packet is IMqttPacketWithIdentifier requestPacketWithIdentifier))
|
||||
{
|
||||
throw new InvalidOperationException("Response packet has PacketIdentifier but request packet does not.");
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace MQTTnet.Core.Packets
|
||||
{
|
||||
public ushort PacketIdentifier { get; set; }
|
||||
|
||||
public IList<MqttSubscribeReturnCode> SubscribeReturnCodes { get; set; } = new List<MqttSubscribeReturnCode>();
|
||||
public IList<MqttSubscribeReturnCode> SubscribeReturnCodes { get; } = new List<MqttSubscribeReturnCode>();
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace MQTTnet.Core.Packets
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
var topicFiltersText = string.Join(",", TopicFilters.Select(f => $"{f.Topic}@{f.QualityOfServiceLevel}"));
|
||||
var topicFiltersText = string.Join(",", TopicFilters.Select(f => f.Topic + "@" + f.QualityOfServiceLevel));
|
||||
return nameof(MqttSubscribePacket) + ": [PacketIdentifier=" + PacketIdentifier + "] [TopicFilters=" + topicFiltersText + "]";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
using MQTTnet.Core.Protocol;
|
||||
|
||||
namespace MQTTnet.Core.Packets
|
||||
{
|
||||
public sealed class TopicFilter
|
||||
{
|
||||
public TopicFilter(string topic, MqttQualityOfServiceLevel qualityOfServiceLevel)
|
||||
{
|
||||
Topic = topic;
|
||||
QualityOfServiceLevel = qualityOfServiceLevel;
|
||||
}
|
||||
|
||||
public string Topic { get; }
|
||||
|
||||
public MqttQualityOfServiceLevel QualityOfServiceLevel { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
@@ -13,7 +14,7 @@ namespace MQTTnet.Core.Serializer
|
||||
public sealed class MqttPacketReader : BinaryReader
|
||||
{
|
||||
private readonly ReceivedMqttPacket _receivedMqttPacket;
|
||||
|
||||
|
||||
public MqttPacketReader(ReceivedMqttPacket receivedMqttPacket)
|
||||
: base(receivedMqttPacket.Body, Encoding.UTF8, true)
|
||||
{
|
||||
@@ -24,7 +25,13 @@ namespace MQTTnet.Core.Serializer
|
||||
|
||||
public static MqttPacketHeader ReadHeaderFromSource(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var fixedHeader = (byte)stream.ReadByte();
|
||||
var buffer = stream.ReadByte();
|
||||
if (buffer == -1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var fixedHeader = (byte)buffer;
|
||||
var controlPacketType = (MqttControlPacketType)(fixedHeader >> 4);
|
||||
var bodyLength = ReadBodyLengthFromSource(stream, cancellationToken);
|
||||
|
||||
@@ -70,6 +77,8 @@ namespace MQTTnet.Core.Serializer
|
||||
var multiplier = 1;
|
||||
var value = 0;
|
||||
byte encodedByte;
|
||||
|
||||
var readBytes = new List<int>();
|
||||
do
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
@@ -77,14 +86,23 @@ namespace MQTTnet.Core.Serializer
|
||||
throw new TaskCanceledException();
|
||||
}
|
||||
|
||||
encodedByte = (byte)stream.ReadByte();
|
||||
value += (encodedByte & 127) * multiplier;
|
||||
var buffer = stream.ReadByte();
|
||||
readBytes.Add(buffer);
|
||||
|
||||
if (buffer == -1)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
encodedByte = (byte)buffer;
|
||||
value += (byte)(encodedByte & 127) * multiplier;
|
||||
multiplier *= 128;
|
||||
if (multiplier > 128 * 128 * 128)
|
||||
{
|
||||
throw new MqttProtocolViolationException("Remaining length is invalid.");
|
||||
throw new MqttProtocolViolationException($"Remaining length is invalid (Data={string.Join(",", readBytes)}).");
|
||||
}
|
||||
} while ((encodedByte & 128) != 0);
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,93 +24,21 @@ namespace MQTTnet.Core.Serializer
|
||||
using (var stream = new MemoryStream())
|
||||
using (var writer = new MqttPacketWriter(stream))
|
||||
{
|
||||
var header = new List<byte> { SerializePacket(packet, writer) };
|
||||
var fixedHeader = SerializePacket(packet, writer);
|
||||
var headerBuffer = new List<byte> { fixedHeader };
|
||||
MqttPacketWriter.WriteRemainingLength((int)stream.Length, headerBuffer);
|
||||
|
||||
var header = headerBuffer.ToArray();
|
||||
var body = stream.ToArray();
|
||||
MqttPacketWriter.BuildLengthHeader(body.Length, header);
|
||||
var headerArray = header.ToArray();
|
||||
var writeBuffer = new byte[header.Count + body.Length];
|
||||
Buffer.BlockCopy(headerArray, 0, writeBuffer, 0, headerArray.Length);
|
||||
Buffer.BlockCopy(body, 0, writeBuffer, headerArray.Length, body.Length);
|
||||
|
||||
return writeBuffer;
|
||||
var buffer = new byte[header.Length + body.Length];
|
||||
Buffer.BlockCopy(header, 0, buffer, 0, header.Length);
|
||||
Buffer.BlockCopy(body, 0, buffer, header.Length, body.Length);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
|
||||
private byte SerializePacket(MqttBasePacket packet, MqttPacketWriter writer)
|
||||
{
|
||||
if (packet is MqttConnectPacket connectPacket)
|
||||
{
|
||||
return Serialize(connectPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttConnAckPacket connAckPacket)
|
||||
{
|
||||
return Serialize(connAckPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttDisconnectPacket disconnectPacket)
|
||||
{
|
||||
return Serialize(disconnectPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttPingReqPacket pingReqPacket)
|
||||
{
|
||||
return Serialize(pingReqPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttPingRespPacket pingRespPacket)
|
||||
{
|
||||
return Serialize(pingRespPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttPublishPacket publishPacket)
|
||||
{
|
||||
return Serialize(publishPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttPubAckPacket pubAckPacket)
|
||||
{
|
||||
return Serialize(pubAckPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttPubRecPacket pubRecPacket)
|
||||
{
|
||||
return Serialize(pubRecPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttPubRelPacket pubRelPacket)
|
||||
{
|
||||
return Serialize(pubRelPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttPubCompPacket pubCompPacket)
|
||||
{
|
||||
return Serialize(pubCompPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttSubscribePacket subscribePacket)
|
||||
{
|
||||
return Serialize(subscribePacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttSubAckPacket subAckPacket)
|
||||
{
|
||||
return Serialize(subAckPacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttUnsubscribePacket unsubscribePacket)
|
||||
{
|
||||
return Serialize(unsubscribePacket, writer);
|
||||
}
|
||||
|
||||
if (packet is MqttUnsubAckPacket unsubAckPacket)
|
||||
{
|
||||
return Serialize(unsubAckPacket, writer);
|
||||
}
|
||||
|
||||
throw new MqttProtocolViolationException("Packet type invalid.");
|
||||
}
|
||||
|
||||
public MqttBasePacket Deserialize(ReceivedMqttPacket receivedMqttPacket)
|
||||
{
|
||||
if (receivedMqttPacket == null) throw new ArgumentNullException(nameof(receivedMqttPacket));
|
||||
@@ -121,103 +49,90 @@ namespace MQTTnet.Core.Serializer
|
||||
}
|
||||
}
|
||||
|
||||
private byte SerializePacket(MqttBasePacket packet, MqttPacketWriter writer)
|
||||
{
|
||||
switch (packet)
|
||||
{
|
||||
case MqttConnectPacket connectPacket: return Serialize(connectPacket, writer);
|
||||
case MqttConnAckPacket connAckPacket: return Serialize(connAckPacket, writer);
|
||||
case MqttDisconnectPacket _: return SerializeEmptyPacket(MqttControlPacketType.Disconnect);
|
||||
case MqttPingReqPacket _: return SerializeEmptyPacket(MqttControlPacketType.PingReq);
|
||||
case MqttPingRespPacket _: return SerializeEmptyPacket(MqttControlPacketType.PingResp);
|
||||
case MqttPublishPacket publishPacket: return Serialize(publishPacket, writer);
|
||||
case MqttPubAckPacket pubAckPacket: return Serialize(pubAckPacket, writer);
|
||||
case MqttPubRecPacket pubRecPacket: return Serialize(pubRecPacket, writer);
|
||||
case MqttPubRelPacket pubRelPacket: return Serialize(pubRelPacket, writer);
|
||||
case MqttPubCompPacket pubCompPacket: return Serialize(pubCompPacket, writer);
|
||||
case MqttSubscribePacket subscribePacket: return Serialize(subscribePacket, writer);
|
||||
case MqttSubAckPacket subAckPacket: return Serialize(subAckPacket, writer);
|
||||
case MqttUnsubscribePacket unsubscribePacket: return Serialize(unsubscribePacket, writer);
|
||||
case MqttUnsubAckPacket unsubAckPacket: return Serialize(unsubAckPacket, writer);
|
||||
default: throw new MqttProtocolViolationException("Packet type invalid.");
|
||||
}
|
||||
}
|
||||
|
||||
private static MqttBasePacket Deserialize(MqttPacketHeader header, MqttPacketReader reader)
|
||||
{
|
||||
switch (header.ControlPacketType)
|
||||
{
|
||||
case MqttControlPacketType.Connect:
|
||||
{
|
||||
return DeserializeConnect(reader);
|
||||
}
|
||||
|
||||
case MqttControlPacketType.ConnAck:
|
||||
{
|
||||
return DeserializeConnAck(reader);
|
||||
}
|
||||
|
||||
case MqttControlPacketType.Disconnect:
|
||||
{
|
||||
return new MqttDisconnectPacket();
|
||||
}
|
||||
|
||||
case MqttControlPacketType.Publish:
|
||||
{
|
||||
return DeserializePublish(reader, header);
|
||||
}
|
||||
|
||||
case MqttControlPacketType.PubAck:
|
||||
{
|
||||
return new MqttPubAckPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
case MqttControlPacketType.PubRec:
|
||||
{
|
||||
return new MqttPubRecPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
case MqttControlPacketType.PubRel:
|
||||
{
|
||||
return new MqttPubRelPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
case MqttControlPacketType.PubComp:
|
||||
{
|
||||
return new MqttPubCompPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
case MqttControlPacketType.PingReq:
|
||||
{
|
||||
return new MqttPingReqPacket();
|
||||
}
|
||||
|
||||
case MqttControlPacketType.PingResp:
|
||||
{
|
||||
return new MqttPingRespPacket();
|
||||
}
|
||||
|
||||
case MqttControlPacketType.Subscribe:
|
||||
{
|
||||
return DeserializeSubscribe(reader);
|
||||
}
|
||||
|
||||
case MqttControlPacketType.SubAck:
|
||||
{
|
||||
return DeserializeSubAck(reader);
|
||||
}
|
||||
|
||||
case MqttControlPacketType.Unsubscibe:
|
||||
{
|
||||
return DeserializeUnsubscribe(reader);
|
||||
}
|
||||
|
||||
case MqttControlPacketType.UnsubAck:
|
||||
{
|
||||
return new MqttUnsubAckPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
throw new MqttProtocolViolationException(
|
||||
$"Packet type ({(int)header.ControlPacketType}) not supported.");
|
||||
}
|
||||
case MqttControlPacketType.Connect: return DeserializeConnect(reader);
|
||||
case MqttControlPacketType.ConnAck: return DeserializeConnAck(reader);
|
||||
case MqttControlPacketType.Disconnect: return new MqttDisconnectPacket();
|
||||
case MqttControlPacketType.Publish: return DeserializePublish(reader, header);
|
||||
case MqttControlPacketType.PubAck: return DeserializePubAck(reader);
|
||||
case MqttControlPacketType.PubRec: return DeserializePubRec(reader);
|
||||
case MqttControlPacketType.PubRel: return DeserializePubRel(reader);
|
||||
case MqttControlPacketType.PubComp: return DeserializePubComp(reader);
|
||||
case MqttControlPacketType.PingReq: return new MqttPingReqPacket();
|
||||
case MqttControlPacketType.PingResp: return new MqttPingRespPacket();
|
||||
case MqttControlPacketType.Subscribe: return DeserializeSubscribe(reader);
|
||||
case MqttControlPacketType.SubAck: return DeserializeSubAck(reader);
|
||||
case MqttControlPacketType.Unsubscibe: return DeserializeUnsubscribe(reader);
|
||||
case MqttControlPacketType.UnsubAck: return DeserializeUnsubAck(reader);
|
||||
default: throw new MqttProtocolViolationException($"Packet type ({(int)header.ControlPacketType}) not supported.");
|
||||
}
|
||||
}
|
||||
|
||||
private static MqttBasePacket DeserializeUnsubAck(MqttPacketReader reader)
|
||||
{
|
||||
return new MqttUnsubAckPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
private static MqttBasePacket DeserializePubComp(MqttPacketReader reader)
|
||||
{
|
||||
return new MqttPubCompPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
private static MqttBasePacket DeserializePubRel(MqttPacketReader reader)
|
||||
{
|
||||
return new MqttPubRelPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
private static MqttBasePacket DeserializePubRec(MqttPacketReader reader)
|
||||
{
|
||||
return new MqttPubRecPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
private static MqttBasePacket DeserializePubAck(MqttPacketReader reader)
|
||||
{
|
||||
return new MqttPubAckPacket
|
||||
{
|
||||
PacketIdentifier = reader.ReadUInt16()
|
||||
};
|
||||
}
|
||||
|
||||
private static MqttBasePacket DeserializeUnsubscribe(MqttPacketReader reader)
|
||||
{
|
||||
var packet = new MqttUnsubscribePacket
|
||||
@@ -298,7 +213,7 @@ namespace MQTTnet.Core.Serializer
|
||||
throw new MqttProtocolViolationException("Protocol name is not supported.");
|
||||
}
|
||||
|
||||
var protocolLevel = reader.ReadByte();
|
||||
reader.ReadByte(); // Skip protocol level
|
||||
var connectFlags = reader.ReadByte();
|
||||
|
||||
var connectFlagsReader = new ByteReader(connectFlags);
|
||||
@@ -321,11 +236,13 @@ namespace MQTTnet.Core.Serializer
|
||||
|
||||
if (willFlag)
|
||||
{
|
||||
packet.WillMessage = new MqttApplicationMessage(
|
||||
reader.ReadStringWithLengthPrefix(),
|
||||
reader.ReadWithLengthPrefix(),
|
||||
(MqttQualityOfServiceLevel)willQoS,
|
||||
willRetain);
|
||||
packet.WillMessage = new MqttApplicationMessage
|
||||
{
|
||||
Topic = reader.ReadStringWithLengthPrefix(),
|
||||
Payload = reader.ReadWithLengthPrefix(),
|
||||
QualityOfServiceLevel = (MqttQualityOfServiceLevel)willQoS,
|
||||
Retain = willRetain
|
||||
};
|
||||
}
|
||||
|
||||
if (usernameFlag)
|
||||
@@ -373,6 +290,8 @@ namespace MQTTnet.Core.Serializer
|
||||
|
||||
private static void ValidateConnectPacket(MqttConnectPacket packet)
|
||||
{
|
||||
if (packet == null) throw new ArgumentNullException(nameof(packet));
|
||||
|
||||
if (string.IsNullOrEmpty(packet.ClientId) && !packet.CleanSession)
|
||||
{
|
||||
throw new MqttProtocolViolationException("CleanSession must be set if ClientId is empty [MQTT-3.1.3-7].");
|
||||
@@ -381,6 +300,8 @@ namespace MQTTnet.Core.Serializer
|
||||
|
||||
private static void ValidatePublishPacket(MqttPublishPacket packet)
|
||||
{
|
||||
if (packet == null) throw new ArgumentNullException(nameof(packet));
|
||||
|
||||
if (packet.QualityOfServiceLevel == 0 && packet.Dup)
|
||||
{
|
||||
throw new MqttProtocolViolationException("Dup flag must be false for QoS 0 packets [MQTT-3.3.1-2].");
|
||||
@@ -468,21 +389,6 @@ namespace MQTTnet.Core.Serializer
|
||||
return MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.PubRel, 0x02);
|
||||
}
|
||||
|
||||
private static byte Serialize(MqttDisconnectPacket packet, MqttPacketWriter writer)
|
||||
{
|
||||
return SerializeEmptyPacketAsync(MqttControlPacketType.Disconnect, writer);
|
||||
}
|
||||
|
||||
private static byte Serialize(MqttPingReqPacket packet, MqttPacketWriter writer)
|
||||
{
|
||||
return SerializeEmptyPacketAsync(MqttControlPacketType.PingReq, writer);
|
||||
}
|
||||
|
||||
private static byte Serialize(MqttPingRespPacket packet, MqttPacketWriter writer)
|
||||
{
|
||||
return SerializeEmptyPacketAsync(MqttControlPacketType.PingResp, writer);
|
||||
}
|
||||
|
||||
private static byte Serialize(MqttPublishPacket packet, MqttPacketWriter writer)
|
||||
{
|
||||
ValidatePublishPacket(packet);
|
||||
@@ -594,14 +500,13 @@ namespace MQTTnet.Core.Serializer
|
||||
return MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Unsubscibe, 0x02);
|
||||
}
|
||||
|
||||
private static byte Serialize(MqttUnsubAckPacket packet, MqttPacketWriter writer)
|
||||
private static byte Serialize(IMqttPacketWithIdentifier packet, BinaryWriter writer)
|
||||
{
|
||||
writer.Write(packet.PacketIdentifier);
|
||||
|
||||
return MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.UnsubAck);
|
||||
}
|
||||
|
||||
private static byte SerializeEmptyPacketAsync(MqttControlPacketType type, MqttPacketWriter writer)
|
||||
private static byte SerializeEmptyPacket(MqttControlPacketType type)
|
||||
{
|
||||
return MqttPacketWriter.BuildFixedHeader(type);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user