From 4df29be155948dcdb9221add3f2bfe9f91ed1191 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Tue, 14 May 2019 20:40:44 +0200 Subject: [PATCH 01/12] Create MQTTnet.Server package from publish output instead build files. --- Build/build.ps1 | 4 +- Source/MQTTnet.Server/LICENSE | 78 ++++++++++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/Build/build.ps1 b/Build/build.ps1 index 3f5c487d..dd605dd6 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -38,9 +38,9 @@ Write-Host # Build MQTTnet.Server Remove-Item ..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2 -Recurse -Force -ErrorAction SilentlyContinue -&$msbuild ..\Source\MQTTnet.Server\MQTTnet.Server.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp2.2" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" +&$msbuild ..\Source\MQTTnet.Server\MQTTnet.Server.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp2.2" /p:publishprofile=FolderProfile /p:deployonbuild=true /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" -$source = "..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2" +$source = "..\Source\MQTTnet.Server\bin\publish" $destination = "..\Source\MQTTnet.Server\bin\MQTTnet.Server-Portable-v$nugetVersion.zip" If(Test-path $destination) {Remove-item $destination} Add-Type -assembly "system.io.compression.filesystem" diff --git a/Source/MQTTnet.Server/LICENSE b/Source/MQTTnet.Server/LICENSE index 7d84e2b1..3b188816 100644 --- a/Source/MQTTnet.Server/LICENSE +++ b/Source/MQTTnet.Server/LICENSE @@ -1,6 +1,7 @@ +# MQTTnet MIT License -Copyright (c) 2017 Christian Kratky +Copyright (c) 2019 MQTTnet Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -19,3 +20,78 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# Swashbuckle +Copyright (c) 2013, Richard Morris +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE + +# IronPython +Copyright (c) .NET Foundation and Contributors + All Rights Reserved + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + + +You must cause any modified files to carry prominent notices stating that You changed the files; and + + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + From 6839970d4167ea2b83e39c69ec9451d9948f4fef Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Tue, 14 May 2019 20:40:58 +0200 Subject: [PATCH 02/12] Update UnitTests. --- Tests/MQTTnet.Core.Tests/MQTTv5/Client_Tests.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Tests/MQTTnet.Core.Tests/MQTTv5/Client_Tests.cs b/Tests/MQTTnet.Core.Tests/MQTTv5/Client_Tests.cs index 52b3d5f6..3b813c31 100644 --- a/Tests/MQTTnet.Core.Tests/MQTTv5/Client_Tests.cs +++ b/Tests/MQTTnet.Core.Tests/MQTTv5/Client_Tests.cs @@ -36,7 +36,10 @@ namespace MQTTnet.Tests.MQTTv5 .WithWillDelayInterval(20) .Build()); + MqttApplicationMessage receivedMessage = null; + await client.SubscribeAsync("a"); + client.UseApplicationMessageReceivedHandler(context => { receivedMessage = context.ApplicationMessage; }); await client.PublishAsync(new MqttApplicationMessageBuilder() .WithTopic("a") @@ -48,6 +51,10 @@ namespace MQTTnet.Tests.MQTTv5 .Build()); await Task.Delay(500); + + Assert.IsNotNull(receivedMessage); + + Assert.AreEqual(2, receivedMessage.UserProperties.Count); } } From 231001850aa73d564a6085e7009cf8ded6a7ce77 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Tue, 14 May 2019 20:45:45 +0200 Subject: [PATCH 03/12] Add support for extended authentication exchange. --- Build/MQTTnet.nuspec | 1 + ...ttExtendedAuthenticationExchangeHandler.cs | 9 + ...ttExtendedAuthenticationExchangeContext.cs | 35 ++++ .../MqttExtendedAuthenticationExchangeData.cs | 17 ++ Source/MQTTnet/Client/IMqttClient.cs | 2 + Source/MQTTnet/Client/MqttClient.cs | 26 +++ Source/MQTTnet/Client/MqttClientExtensions.cs | 16 ++ .../Client/Options/IMqttClientOptions.cs | 2 + .../Client/Options/MqttClientOptions.cs | 2 + .../Options/MqttClientOptionsBuilder.cs | 7 + .../Formatter/V3/MqttV310PacketFormatter.cs | 14 +- .../Formatter/V5/MqttV500DataConverter.cs | 4 +- .../Formatter/V5/MqttV500PacketDecoder.cs | 179 ++++++++++++++---- .../Packets/MqttAuthPacketProperties.cs | 2 +- .../Packets/MqttConnAckPacketProperties.cs | 2 +- .../Packets/MqttConnectPacketProperties.cs | 2 +- .../Packets/MqttDisconnectPacketProperties.cs | 2 +- .../Packets/MqttPubAckPacketProperties.cs | 2 +- .../Packets/MqttPubCompPacketProperties.cs | 2 +- .../Packets/MqttPubRecPacketProperties.cs | 2 +- .../Packets/MqttPubRelPacketProperties.cs | 2 +- Source/MQTTnet/Packets/MqttSubAckPacket.cs | 2 +- .../Packets/MqttSubAckPacketProperties.cs | 2 +- Source/MQTTnet/Packets/MqttSubscribePacket.cs | 2 +- .../Packets/MqttSubscribePacketProperties.cs | 2 +- Source/MQTTnet/Packets/MqttUnsubAckPacket.cs | 2 +- .../Packets/MqttUnsubAckPacketProperties.cs | 2 +- .../MQTTnet/Packets/MqttUnsubscribePacket.cs | 2 +- .../MqttUnsubscribePacketProperties.cs | 2 +- 29 files changed, 289 insertions(+), 57 deletions(-) create mode 100644 Source/MQTTnet/Client/ExtendedAuthenticationExchange/IMqttExtendedAuthenticationExchangeHandler.cs create mode 100644 Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs create mode 100644 Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeData.cs diff --git a/Build/MQTTnet.nuspec b/Build/MQTTnet.nuspec index 2ecfc072..cd49b7f4 100644 --- a/Build/MQTTnet.nuspec +++ b/Build/MQTTnet.nuspec @@ -12,6 +12,7 @@ MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). * [Core] Fixed issues in MQTTv5 message encoding and decoding. +* [Client] Added support for extended authentication exchange. Copyright Christian Kratky 2016-2019 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 diff --git a/Source/MQTTnet/Client/ExtendedAuthenticationExchange/IMqttExtendedAuthenticationExchangeHandler.cs b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/IMqttExtendedAuthenticationExchangeHandler.cs new file mode 100644 index 00000000..8cd35420 --- /dev/null +++ b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/IMqttExtendedAuthenticationExchangeHandler.cs @@ -0,0 +1,9 @@ +using System.Threading.Tasks; + +namespace MQTTnet.Client.ExtendedAuthenticationExchange +{ + public interface IMqttExtendedAuthenticationExchangeHandler + { + Task HandleRequestAsync(MqttExtendedAuthenticationExchangeContext context); + } +} diff --git a/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs new file mode 100644 index 00000000..9e88f039 --- /dev/null +++ b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using MQTTnet.Packets; +using MQTTnet.Protocol; + +namespace MQTTnet.Client.ExtendedAuthenticationExchange +{ + public class MqttExtendedAuthenticationExchangeContext + { + public MqttExtendedAuthenticationExchangeContext(MqttAuthPacket authPacket, IMqttClient client) + { + if (authPacket == null) throw new ArgumentNullException(nameof(authPacket)); + + ReasonCode = authPacket.ReasonCode; + ReasonString = authPacket.Properties?.ReasonString; + AuthenticationMethod = authPacket.Properties?.AuthenticationMethod; + AuthenticationData = authPacket.Properties?.AuthenticationData; + UserProperties = authPacket.Properties?.UserProperties; + + Client = client ?? throw new ArgumentNullException(nameof(client)); + } + + public MqttAuthenticateReasonCode ReasonCode { get; } + + public string ReasonString { get; } + + public string AuthenticationMethod { get; } + + public byte[] AuthenticationData { get; } + + public List UserProperties { get; } + + public IMqttClient Client { get; } + } +} diff --git a/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeData.cs b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeData.cs new file mode 100644 index 00000000..8a49b08a --- /dev/null +++ b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeData.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; +using MQTTnet.Packets; +using MQTTnet.Protocol; + +namespace MQTTnet.Client.ExtendedAuthenticationExchange +{ + public class MqttExtendedAuthenticationExchangeData + { + public MqttAuthenticateReasonCode ReasonCode { get; set; } + + public string ReasonString { get; set; } + + public byte[] AuthenticationData { get; set; } + + public List UserProperties { get; } + } +} diff --git a/Source/MQTTnet/Client/IMqttClient.cs b/Source/MQTTnet/Client/IMqttClient.cs index 70259cf6..059f2e60 100644 --- a/Source/MQTTnet/Client/IMqttClient.cs +++ b/Source/MQTTnet/Client/IMqttClient.cs @@ -3,6 +3,7 @@ using System.Threading; using System.Threading.Tasks; using MQTTnet.Client.Connecting; using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.ExtendedAuthenticationExchange; using MQTTnet.Client.Options; using MQTTnet.Client.Subscribing; using MQTTnet.Client.Unsubscribing; @@ -21,6 +22,7 @@ namespace MQTTnet.Client Task ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken); Task DisconnectAsync(MqttClientDisconnectOptions options, CancellationToken cancellationToken); + Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticationExchangeData data, CancellationToken cancellationToken); Task SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken); Task UnsubscribeAsync(MqttClientUnsubscribeOptions options, CancellationToken cancellationToken); } diff --git a/Source/MQTTnet/Client/MqttClient.cs b/Source/MQTTnet/Client/MqttClient.cs index 8d877f68..76bceeed 100644 --- a/Source/MQTTnet/Client/MqttClient.cs +++ b/Source/MQTTnet/Client/MqttClient.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using MQTTnet.Adapter; using MQTTnet.Client.Connecting; using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.ExtendedAuthenticationExchange; using MQTTnet.Client.Options; using MQTTnet.Client.Publishing; using MQTTnet.Client.Receiving; @@ -138,6 +139,23 @@ namespace MQTTnet.Client } } + public Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticationExchangeData data, CancellationToken cancellationToken) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + + return SendAsync(new MqttAuthPacket + { + Properties = new MqttAuthPacketProperties + { + // This must always be equal to the value from the CONNECT packet. So we use it here to ensure that. + AuthenticationMethod = Options.AuthenticationMethod, + AuthenticationData = data.AuthenticationData, + ReasonString = data.ReasonString, + UserProperties = data.UserProperties + } + }, cancellationToken); + } + public async Task SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken) { if (options == null) throw new ArgumentNullException(nameof(options)); @@ -474,6 +492,14 @@ namespace MQTTnet.Client await DisconnectAsync(null, cancellationToken).ConfigureAwait(false); } + else if (packet is MqttAuthPacket authPacket) + { + var extendedAuthenticationExchangeHandler = Options.ExtendedAuthenticationExchangeHandler; + if (extendedAuthenticationExchangeHandler != null) + { + await extendedAuthenticationExchangeHandler.HandleRequestAsync(new MqttExtendedAuthenticationExchangeContext(authPacket, this)).ConfigureAwait(false); + } + } else { _packetDispatcher.Dispatch(packet); diff --git a/Source/MQTTnet/Client/MqttClientExtensions.cs b/Source/MQTTnet/Client/MqttClientExtensions.cs index e5e3cd75..58040f7d 100644 --- a/Source/MQTTnet/Client/MqttClientExtensions.cs +++ b/Source/MQTTnet/Client/MqttClientExtensions.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using MQTTnet.Client.Connecting; using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.ExtendedAuthenticationExchange; using MQTTnet.Client.Options; using MQTTnet.Client.Publishing; using MQTTnet.Client.Receiving; @@ -170,21 +171,36 @@ namespace MQTTnet.Client public static Task ConnectAsync(this IMqttClient client, IMqttClientOptions options) { + if (client == null) throw new ArgumentNullException(nameof(client)); + return client.ConnectAsync(options, CancellationToken.None); } public static Task DisconnectAsync(this IMqttClient client, MqttClientDisconnectOptions options) { + if (client == null) throw new ArgumentNullException(nameof(client)); + return client.DisconnectAsync(options, CancellationToken.None); } + public static Task SendExtendedAuthenticationExchangeDataAsync(this IMqttClient client, MqttExtendedAuthenticationExchangeData data) + { + if (client == null) throw new ArgumentNullException(nameof(client)); + + return client.SendExtendedAuthenticationExchangeDataAsync(data, CancellationToken.None); + } + public static Task SubscribeAsync(this IMqttClient client, MqttClientSubscribeOptions options) { + if (client == null) throw new ArgumentNullException(nameof(client)); + return client.SubscribeAsync(options, CancellationToken.None); } public static Task UnsubscribeAsync(this IMqttClient client, MqttClientUnsubscribeOptions options) { + if (client == null) throw new ArgumentNullException(nameof(client)); + return client.UnsubscribeAsync(options, CancellationToken.None); } diff --git a/Source/MQTTnet/Client/Options/IMqttClientOptions.cs b/Source/MQTTnet/Client/Options/IMqttClientOptions.cs index 3150baa3..822603dc 100644 --- a/Source/MQTTnet/Client/Options/IMqttClientOptions.cs +++ b/Source/MQTTnet/Client/Options/IMqttClientOptions.cs @@ -1,4 +1,5 @@ using System; +using MQTTnet.Client.ExtendedAuthenticationExchange; using MQTTnet.Formatter; namespace MQTTnet.Client.Options @@ -8,6 +9,7 @@ namespace MQTTnet.Client.Options string ClientId { get; } bool CleanSession { get; } IMqttClientCredentials Credentials { get; } + IMqttExtendedAuthenticationExchangeHandler ExtendedAuthenticationExchangeHandler { get; } MqttProtocolVersion ProtocolVersion { get; } IMqttClientChannelOptions ChannelOptions { get; } diff --git a/Source/MQTTnet/Client/Options/MqttClientOptions.cs b/Source/MQTTnet/Client/Options/MqttClientOptions.cs index be9dc7b0..c47f5c6a 100644 --- a/Source/MQTTnet/Client/Options/MqttClientOptions.cs +++ b/Source/MQTTnet/Client/Options/MqttClientOptions.cs @@ -1,4 +1,5 @@ using System; +using MQTTnet.Client.ExtendedAuthenticationExchange; using MQTTnet.Formatter; namespace MQTTnet.Client.Options @@ -8,6 +9,7 @@ namespace MQTTnet.Client.Options public string ClientId { get; set; } = Guid.NewGuid().ToString("N"); public bool CleanSession { get; set; } = true; public IMqttClientCredentials Credentials { get; set; } + public IMqttExtendedAuthenticationExchangeHandler ExtendedAuthenticationExchangeHandler { get; set; } public MqttProtocolVersion ProtocolVersion { get; set; } = MqttProtocolVersion.V311; public IMqttClientChannelOptions ChannelOptions { get; set; } diff --git a/Source/MQTTnet/Client/Options/MqttClientOptionsBuilder.cs b/Source/MQTTnet/Client/Options/MqttClientOptionsBuilder.cs index c4d7e6cb..25563fe9 100644 --- a/Source/MQTTnet/Client/Options/MqttClientOptionsBuilder.cs +++ b/Source/MQTTnet/Client/Options/MqttClientOptionsBuilder.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using MQTTnet.Client.ExtendedAuthenticationExchange; using MQTTnet.Formatter; namespace MQTTnet.Client.Options @@ -125,6 +126,12 @@ namespace MQTTnet.Client.Options return this; } + public MqttClientOptionsBuilder WithExtendedAuthenticationExchangeHandler(IMqttExtendedAuthenticationExchangeHandler handler) + { + _options.ExtendedAuthenticationExchangeHandler = handler; + return this; + } + public MqttClientOptionsBuilder WithTcpServer(string server, int? port = null) { _tcpOptions = new MqttClientTcpOptions diff --git a/Source/MQTTnet/Formatter/V3/MqttV310PacketFormatter.cs b/Source/MQTTnet/Formatter/V3/MqttV310PacketFormatter.cs index 70af10e6..56ffab6a 100644 --- a/Source/MQTTnet/Formatter/V3/MqttV310PacketFormatter.cs +++ b/Source/MQTTnet/Formatter/V3/MqttV310PacketFormatter.cs @@ -10,7 +10,11 @@ namespace MQTTnet.Formatter.V3 public class MqttV310PacketFormatter : IMqttPacketFormatter { private const int FixedHeaderSize = 1; - + + private static readonly MqttPingReqPacket PingReqPacket = new MqttPingReqPacket(); + private static readonly MqttPingRespPacket PingRespPacket = new MqttPingRespPacket(); + private static readonly MqttDisconnectPacket DisconnectPacket = new MqttDisconnectPacket(); + private readonly IMqttPacketWriter _packetWriter; public MqttV310PacketFormatter() @@ -67,14 +71,14 @@ namespace MQTTnet.Formatter.V3 { case MqttControlPacketType.Connect: return DecodeConnectPacket(receivedMqttPacket.Body); case MqttControlPacketType.ConnAck: return DecodeConnAckPacket(receivedMqttPacket.Body); - case MqttControlPacketType.Disconnect: return new MqttDisconnectPacket(); + case MqttControlPacketType.Disconnect: return DisconnectPacket; case MqttControlPacketType.Publish: return DecodePublishPacket(receivedMqttPacket); case MqttControlPacketType.PubAck: return DecodePubAckPacket(receivedMqttPacket.Body); case MqttControlPacketType.PubRec: return DecodePubRecPacket(receivedMqttPacket.Body); case MqttControlPacketType.PubRel: return DecodePubRelPacket(receivedMqttPacket.Body); case MqttControlPacketType.PubComp: return DecodePubCompPacket(receivedMqttPacket.Body); - case MqttControlPacketType.PingReq: return new MqttPingReqPacket(); - case MqttControlPacketType.PingResp: return new MqttPingRespPacket(); + case MqttControlPacketType.PingReq: return PingReqPacket; + case MqttControlPacketType.PingResp: return PingRespPacket; case MqttControlPacketType.Subscribe: return DecodeSubscribePacket(receivedMqttPacket.Body); case MqttControlPacketType.SubAck: return DecodeSubAckPacket(receivedMqttPacket.Body); case MqttControlPacketType.Unsubscibe: return DecodeUnsubscribePacket(receivedMqttPacket.Body); @@ -229,7 +233,7 @@ namespace MQTTnet.Formatter.V3 if (!receivedMqttPacket.Body.EndOfStream) { - packet.Payload = receivedMqttPacket.Body.ReadRemainingData().ToArray(); + packet.Payload = receivedMqttPacket.Body.ReadRemainingData(); } return packet; diff --git a/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs b/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs index 92766177..203181b6 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs @@ -160,7 +160,7 @@ namespace MQTTnet.Formatter.V5 packet.TopicFilters.AddRange(options.TopicFilters); packet.Properties.SubscriptionIdentifier = options.SubscriptionIdentifier; - packet.Properties.UserProperties.AddRange(options.UserProperties); + packet.Properties.UserProperties = options.UserProperties; return packet; } @@ -175,7 +175,7 @@ namespace MQTTnet.Formatter.V5 }; packet.TopicFilters.AddRange(options.TopicFilters); - packet.Properties.UserProperties.AddRange(options.UserProperties); + packet.Properties.UserProperties = options.UserProperties; return packet; } diff --git a/Source/MQTTnet/Formatter/V5/MqttV500PacketDecoder.cs b/Source/MQTTnet/Formatter/V5/MqttV500PacketDecoder.cs index 4c394e46..701c338f 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV500PacketDecoder.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV500PacketDecoder.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using MQTTnet.Adapter; using MQTTnet.Exceptions; using MQTTnet.Packets; @@ -10,6 +9,10 @@ namespace MQTTnet.Formatter.V5 { public class MqttV500PacketDecoder { + private static readonly MqttPingReqPacket PingReqPacket = new MqttPingReqPacket(); + + private static readonly MqttPingRespPacket PingRespPacket = new MqttPingRespPacket(); + public MqttBasePacket Decode(ReceivedMqttPacket receivedMqttPacket) { if (receivedMqttPacket == null) throw new ArgumentNullException(nameof(receivedMqttPacket)); @@ -46,10 +49,7 @@ namespace MQTTnet.Formatter.V5 { ThrowIfBodyIsEmpty(body); - var packet = new MqttConnectPacket - { - Properties = new MqttConnectPacketProperties() - }; + var packet = new MqttConnectPacket(); var protocolName = body.ReadStringWithLengthPrefix(); var protocolVersion = body.ReadByte(); @@ -84,6 +84,11 @@ namespace MQTTnet.Formatter.V5 var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttConnectPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.SessionExpiryInterval) { packet.Properties.SessionExpiryInterval = propertiesReader.ReadSessionExpiryInterval(); @@ -118,6 +123,11 @@ namespace MQTTnet.Formatter.V5 } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -213,13 +223,17 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttConnAckPacket { IsSessionPresent = (acknowledgeFlags & 0x1) > 0, - ReasonCode = (MqttConnectReasonCode)body.ReadByte(), - Properties = new MqttConnAckPacketProperties() + ReasonCode = (MqttConnectReasonCode)body.ReadByte() }; var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttConnAckPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.SessionExpiryInterval) { packet.Properties.SessionExpiryInterval = propertiesReader.ReadSessionExpiryInterval(); @@ -282,6 +296,11 @@ namespace MQTTnet.Formatter.V5 } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -299,13 +318,17 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttDisconnectPacket { - ReasonCode = (MqttDisconnectReasonCode)body.ReadByte(), - Properties = new MqttDisconnectPacketProperties() + ReasonCode = (MqttDisconnectReasonCode)body.ReadByte() }; var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttDisconnectPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.SessionExpiryInterval) { packet.Properties.SessionExpiryInterval = propertiesReader.ReadSessionExpiryInterval(); @@ -320,6 +343,11 @@ namespace MQTTnet.Formatter.V5 } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -337,19 +365,28 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttSubscribePacket { - PacketIdentifier = body.ReadTwoByteInteger(), - Properties = new MqttSubscribePacketProperties() + PacketIdentifier = body.ReadTwoByteInteger() }; var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttSubscribePacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.SubscriptionIdentifier) { packet.Properties.SubscriptionIdentifier = propertiesReader.ReadSubscriptionIdentifier(); } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -387,19 +424,28 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttSubAckPacket { - PacketIdentifier = body.ReadTwoByteInteger(), - Properties = new MqttSubAckPacketProperties() + PacketIdentifier = body.ReadTwoByteInteger() }; var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttSubAckPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.ReasonString) { packet.Properties.ReasonString = propertiesReader.ReadReasonString(); } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -423,15 +469,24 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttUnsubscribePacket { - PacketIdentifier = body.ReadTwoByteInteger(), - Properties = new MqttUnsubscribePacketProperties() + PacketIdentifier = body.ReadTwoByteInteger() }; var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttUnsubscribePacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -454,19 +509,28 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttUnsubAckPacket { - PacketIdentifier = body.ReadTwoByteInteger(), - Properties = new MqttUnsubAckPacketProperties() + PacketIdentifier = body.ReadTwoByteInteger() }; var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttUnsubAckPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.ReasonString) { packet.Properties.ReasonString = propertiesReader.ReadReasonString(); } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -486,12 +550,12 @@ namespace MQTTnet.Formatter.V5 private static MqttBasePacket DecodePingReqPacket() { - return new MqttPingReqPacket(); + return PingReqPacket; } private static MqttBasePacket DecodePingRespPacket() { - return new MqttPingRespPacket(); + return PingRespPacket; } private static MqttBasePacket DecodePublishPacket(byte header, IMqttPacketBodyReader body) @@ -507,8 +571,7 @@ namespace MQTTnet.Formatter.V5 Topic = body.ReadStringWithLengthPrefix(), Retain = retain, QualityOfServiceLevel = qos, - Dup = dup, - Properties = new MqttPublishPacketProperties() + Dup = dup }; if (qos > 0) @@ -519,6 +582,11 @@ namespace MQTTnet.Formatter.V5 var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttPublishPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.PayloadFormatIndicator) { packet.Properties.PayloadFormatIndicator = propertiesReader.ReadPayloadFormatIndicator(); @@ -569,7 +637,7 @@ namespace MQTTnet.Formatter.V5 if (!body.EndOfStream) { - packet.Payload = body.ReadRemainingData().ToArray(); + packet.Payload = body.ReadRemainingData(); } return packet; @@ -581,8 +649,7 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttPubAckPacket { - PacketIdentifier = body.ReadTwoByteInteger(), - Properties = new MqttPubAckPacketProperties() + PacketIdentifier = body.ReadTwoByteInteger() }; if (body.EndOfStream) @@ -596,12 +663,22 @@ namespace MQTTnet.Formatter.V5 var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttPubAckPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.ReasonString) { packet.Properties.ReasonString = propertiesReader.ReadReasonString(); } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -619,8 +696,7 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttPubRecPacket { - PacketIdentifier = body.ReadTwoByteInteger(), - Properties = new MqttPubRecPacketProperties() + PacketIdentifier = body.ReadTwoByteInteger() }; if (body.EndOfStream) @@ -634,12 +710,22 @@ namespace MQTTnet.Formatter.V5 var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttPubRecPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.ReasonString) { packet.Properties.ReasonString = propertiesReader.ReadReasonString(); } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -657,8 +743,7 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttPubRelPacket { - PacketIdentifier = body.ReadTwoByteInteger(), - Properties = new MqttPubRelPacketProperties() + PacketIdentifier = body.ReadTwoByteInteger() }; if (body.EndOfStream) @@ -672,12 +757,22 @@ namespace MQTTnet.Formatter.V5 var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttPubRelPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.ReasonString) { packet.Properties.ReasonString = propertiesReader.ReadReasonString(); } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -695,8 +790,7 @@ namespace MQTTnet.Formatter.V5 var packet = new MqttPubCompPacket { - PacketIdentifier = body.ReadTwoByteInteger(), - Properties = new MqttPubCompPacketProperties() + PacketIdentifier = body.ReadTwoByteInteger() }; if (body.EndOfStream) @@ -710,12 +804,22 @@ namespace MQTTnet.Formatter.V5 var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttPubCompPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.ReasonString) { packet.Properties.ReasonString = propertiesReader.ReadReasonString(); } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else @@ -731,10 +835,7 @@ namespace MQTTnet.Formatter.V5 { ThrowIfBodyIsEmpty(body); - var packet = new MqttAuthPacket - { - Properties = new MqttAuthPacketProperties() - }; + var packet = new MqttAuthPacket(); if (body.EndOfStream) { @@ -747,6 +848,11 @@ namespace MQTTnet.Formatter.V5 var propertiesReader = new MqttV500PropertiesReader(body); while (propertiesReader.MoveNext()) { + if (packet.Properties == null) + { + packet.Properties = new MqttAuthPacketProperties(); + } + if (propertiesReader.CurrentPropertyId == MqttPropertyId.AuthenticationMethod) { packet.Properties.AuthenticationMethod = propertiesReader.ReadAuthenticationMethod(); @@ -761,6 +867,11 @@ namespace MQTTnet.Formatter.V5 } else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty) { + if (packet.Properties.UserProperties == null) + { + packet.Properties.UserProperties = new List(); + } + propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties); } else diff --git a/Source/MQTTnet/Packets/MqttAuthPacketProperties.cs b/Source/MQTTnet/Packets/MqttAuthPacketProperties.cs index 6ed25ee0..057004d1 100644 --- a/Source/MQTTnet/Packets/MqttAuthPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttAuthPacketProperties.cs @@ -10,6 +10,6 @@ namespace MQTTnet.Packets public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Packets/MqttConnAckPacketProperties.cs b/Source/MQTTnet/Packets/MqttConnAckPacketProperties.cs index 262222db..d59735c6 100644 --- a/Source/MQTTnet/Packets/MqttConnAckPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttConnAckPacketProperties.cs @@ -18,7 +18,7 @@ namespace MQTTnet.Packets public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } public bool? WildcardSubscriptionAvailable { get; set; } diff --git a/Source/MQTTnet/Packets/MqttConnectPacketProperties.cs b/Source/MQTTnet/Packets/MqttConnectPacketProperties.cs index 25cf5bda..4cc405e2 100644 --- a/Source/MQTTnet/Packets/MqttConnectPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttConnectPacketProperties.cs @@ -22,6 +22,6 @@ namespace MQTTnet.Packets public uint? MaximumPacketSize { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } \ No newline at end of file diff --git a/Source/MQTTnet/Packets/MqttDisconnectPacketProperties.cs b/Source/MQTTnet/Packets/MqttDisconnectPacketProperties.cs index a5385cb0..e05529ff 100644 --- a/Source/MQTTnet/Packets/MqttDisconnectPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttDisconnectPacketProperties.cs @@ -8,7 +8,7 @@ namespace MQTTnet.Packets public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } public string ServerReference { get; set; } } diff --git a/Source/MQTTnet/Packets/MqttPubAckPacketProperties.cs b/Source/MQTTnet/Packets/MqttPubAckPacketProperties.cs index 061f72f9..e2debd4a 100644 --- a/Source/MQTTnet/Packets/MqttPubAckPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttPubAckPacketProperties.cs @@ -6,6 +6,6 @@ namespace MQTTnet.Packets { public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Packets/MqttPubCompPacketProperties.cs b/Source/MQTTnet/Packets/MqttPubCompPacketProperties.cs index c29ad6a6..35e040f5 100644 --- a/Source/MQTTnet/Packets/MqttPubCompPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttPubCompPacketProperties.cs @@ -6,6 +6,6 @@ namespace MQTTnet.Packets { public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Packets/MqttPubRecPacketProperties.cs b/Source/MQTTnet/Packets/MqttPubRecPacketProperties.cs index 574bc617..0cd72250 100644 --- a/Source/MQTTnet/Packets/MqttPubRecPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttPubRecPacketProperties.cs @@ -6,6 +6,6 @@ namespace MQTTnet.Packets { public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Packets/MqttPubRelPacketProperties.cs b/Source/MQTTnet/Packets/MqttPubRelPacketProperties.cs index d7a21f64..aa9625db 100644 --- a/Source/MQTTnet/Packets/MqttPubRelPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttPubRelPacketProperties.cs @@ -6,6 +6,6 @@ namespace MQTTnet.Packets { public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Packets/MqttSubAckPacket.cs b/Source/MQTTnet/Packets/MqttSubAckPacket.cs index 053e7137..4600a4e9 100644 --- a/Source/MQTTnet/Packets/MqttSubAckPacket.cs +++ b/Source/MQTTnet/Packets/MqttSubAckPacket.cs @@ -8,7 +8,7 @@ namespace MQTTnet.Packets { public ushort? PacketIdentifier { get; set; } - public List ReturnCodes { get; } = new List(); + public List ReturnCodes { get; set; } = new List(); #region Added in MQTTv5.0.0 diff --git a/Source/MQTTnet/Packets/MqttSubAckPacketProperties.cs b/Source/MQTTnet/Packets/MqttSubAckPacketProperties.cs index b2b3eff5..74d3e7f8 100644 --- a/Source/MQTTnet/Packets/MqttSubAckPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttSubAckPacketProperties.cs @@ -6,6 +6,6 @@ namespace MQTTnet.Packets { public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Packets/MqttSubscribePacket.cs b/Source/MQTTnet/Packets/MqttSubscribePacket.cs index c96c75bc..1ea1685f 100644 --- a/Source/MQTTnet/Packets/MqttSubscribePacket.cs +++ b/Source/MQTTnet/Packets/MqttSubscribePacket.cs @@ -7,7 +7,7 @@ namespace MQTTnet.Packets { public ushort? PacketIdentifier { get; set; } - public List TopicFilters { get; } = new List(); + public List TopicFilters { get; set; } = new List(); #region Added in MQTTv5 diff --git a/Source/MQTTnet/Packets/MqttSubscribePacketProperties.cs b/Source/MQTTnet/Packets/MqttSubscribePacketProperties.cs index 5b92c5f5..34f58f2f 100644 --- a/Source/MQTTnet/Packets/MqttSubscribePacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttSubscribePacketProperties.cs @@ -6,6 +6,6 @@ namespace MQTTnet.Packets { public uint? SubscriptionIdentifier { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Packets/MqttUnsubAckPacket.cs b/Source/MQTTnet/Packets/MqttUnsubAckPacket.cs index 0b45df67..a17261e1 100644 --- a/Source/MQTTnet/Packets/MqttUnsubAckPacket.cs +++ b/Source/MQTTnet/Packets/MqttUnsubAckPacket.cs @@ -12,7 +12,7 @@ namespace MQTTnet.Packets public MqttUnsubAckPacketProperties Properties { get; set; } - public List ReasonCodes { get; } = new List(); + public List ReasonCodes { get; set; } = new List(); #endregion diff --git a/Source/MQTTnet/Packets/MqttUnsubAckPacketProperties.cs b/Source/MQTTnet/Packets/MqttUnsubAckPacketProperties.cs index ca444d9e..2a102c64 100644 --- a/Source/MQTTnet/Packets/MqttUnsubAckPacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttUnsubAckPacketProperties.cs @@ -6,6 +6,6 @@ namespace MQTTnet.Packets { public string ReasonString { get; set; } - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Packets/MqttUnsubscribePacket.cs b/Source/MQTTnet/Packets/MqttUnsubscribePacket.cs index bb1d4c2a..7b07a245 100644 --- a/Source/MQTTnet/Packets/MqttUnsubscribePacket.cs +++ b/Source/MQTTnet/Packets/MqttUnsubscribePacket.cs @@ -6,7 +6,7 @@ namespace MQTTnet.Packets { public ushort? PacketIdentifier { get; set; } - public List TopicFilters { get; } = new List(); + public List TopicFilters { get; set; } = new List(); #region Added in MQTTv5 diff --git a/Source/MQTTnet/Packets/MqttUnsubscribePacketProperties.cs b/Source/MQTTnet/Packets/MqttUnsubscribePacketProperties.cs index 5fb4d66b..3ec68f1d 100644 --- a/Source/MQTTnet/Packets/MqttUnsubscribePacketProperties.cs +++ b/Source/MQTTnet/Packets/MqttUnsubscribePacketProperties.cs @@ -4,6 +4,6 @@ namespace MQTTnet.Packets { public class MqttUnsubscribePacketProperties { - public List UserProperties { get; } = new List(); + public List UserProperties { get; set; } } } From f169aaa79b4214d69d808fda4a8d5efebec36478 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Fri, 17 May 2019 20:56:58 +0200 Subject: [PATCH 04/12] Add connack properties to connect result. --- .../Formatter/V5/MqttV500DataConverter.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs b/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs index 203181b6..1a75839d 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs @@ -82,7 +82,23 @@ namespace MQTTnet.Formatter.V5 return new MqttClientAuthenticateResult { IsSessionPresent = connAckPacket.IsSessionPresent, - ResultCode = (MqttClientConnectResultCode)connAckPacket.ReasonCode.Value + ResultCode = (MqttClientConnectResultCode)connAckPacket.ReasonCode.Value, + WildcardSubscriptionAvailable = connAckPacket.Properties?.WildcardSubscriptionAvailable, + RetainAvailable = connAckPacket.Properties?.RetainAvailable, + AssignedClientIdentifier = connAckPacket.Properties?.AssignedClientIdentifier, + AuthenticationMethod = connAckPacket.Properties?.AuthenticationMethod, + AuthenticationData = connAckPacket.Properties?.AuthenticationData, + MaximumPacketSize = connAckPacket.Properties?.MaximumPacketSize, + ReasonString = connAckPacket.Properties?.ReasonString, + ReceiveMaximum = connAckPacket.Properties?.ReceiveMaximum, + ResponseInformation = connAckPacket.Properties?.ResponseInformation, + TopicAliasMaximum = connAckPacket.Properties?.TopicAliasMaximum, + ServerReference = connAckPacket.Properties?.ServerReference, + ServerKeepAlive = connAckPacket.Properties?.ServerKeepAlive, + SessionExpiryInterval = connAckPacket.Properties?.SessionExpiryInterval, + SubscriptionIdentifiersAvailable = connAckPacket.Properties?.SubscriptionIdentifiersAvailable, + SharedSubscriptionAvailable = connAckPacket.Properties?.SharedSubscriptionAvailable, + UserProperties = connAckPacket.Properties?.UserProperties }; } From ab3df2ba65f9882dc2aa2635154871f2de7b7a82 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Fri, 17 May 2019 20:57:15 +0200 Subject: [PATCH 05/12] Add subscribe options builder. --- .../Subscribing/MqttClientSubscribeOptions.cs | 2 +- .../MqttClientSubscribeOptionsBuilder.cs | 87 +++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptionsBuilder.cs diff --git a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptions.cs b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptions.cs index 49cf551b..dc4be2f9 100644 --- a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptions.cs +++ b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptions.cs @@ -9,6 +9,6 @@ namespace MQTTnet.Client.Subscribing public uint? SubscriptionIdentifier { get; set; } - public List UserProperties { get; set; } = new List(); + public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptionsBuilder.cs b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptionsBuilder.cs new file mode 100644 index 00000000..c33f9313 --- /dev/null +++ b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptionsBuilder.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using MQTTnet.Packets; +using MQTTnet.Protocol; + +namespace MQTTnet.Client.Subscribing +{ + public class MqttClientSubscribeOptionsBuilder + { + private readonly MqttClientSubscribeOptions _subscribeOptions = new MqttClientSubscribeOptions(); + + public MqttClientSubscribeOptionsBuilder WithUserProperty(string name, string value) + { + if (name == null) throw new ArgumentNullException(nameof(name)); + if (value == null) throw new ArgumentNullException(nameof(value)); + + if (_subscribeOptions.UserProperties == null) + { + _subscribeOptions.UserProperties = new List(); + } + + _subscribeOptions.UserProperties.Add(new MqttUserProperty(name, value)); + + return this; + } + + public MqttClientSubscribeOptionsBuilder WithSubscriptionIdentifier(uint? subscriptionIdentifier) + { + _subscribeOptions.SubscriptionIdentifier = subscriptionIdentifier; + + return this; + } + + public MqttClientSubscribeOptionsBuilder WithTopicFilter( + string topic, + MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, + bool? noLocal = null, + bool? retainAsPublished = null, + MqttRetainHandling? retainHandling = null) + { + return WithTopicFilter(new TopicFilter + { + Topic = topic, + QualityOfServiceLevel = qualityOfServiceLevel, + NoLocal = noLocal, + RetainAsPublished = retainAsPublished, + RetainHandling = retainHandling + }); + } + + public MqttClientSubscribeOptionsBuilder WithTopicFilter(Action topicFilterBuilder) + { + if (topicFilterBuilder == null) throw new ArgumentNullException(nameof(topicFilterBuilder)); + + var internalTopicFilterBuilder = new TopicFilterBuilder(); + topicFilterBuilder(internalTopicFilterBuilder); + + return WithTopicFilter(internalTopicFilterBuilder); + } + + public MqttClientSubscribeOptionsBuilder WithTopicFilter(TopicFilterBuilder topicFilterBuilder) + { + if (topicFilterBuilder == null) throw new ArgumentNullException(nameof(topicFilterBuilder)); + + return WithTopicFilter(topicFilterBuilder.Build()); + } + + public MqttClientSubscribeOptionsBuilder WithTopicFilter(TopicFilter topicFilter) + { + if (topicFilter == null) throw new ArgumentNullException(nameof(topicFilter)); + + if (_subscribeOptions.TopicFilters == null) + { + _subscribeOptions.TopicFilters = new List(); + } + + _subscribeOptions.TopicFilters.Add(topicFilter); + + return this; + } + + public MqttClientSubscribeOptions Build() + { + return _subscribeOptions; + } + } +} From 80b05a894400975ce1eb133bae5fa859c1b4b7dc Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Fri, 17 May 2019 20:57:40 +0200 Subject: [PATCH 06/12] Add connack properties to authenticate result. --- Build/MQTTnet.nuspec | 2 + .../MqttClientAuthenticateResult.cs | 40 ++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/Build/MQTTnet.nuspec b/Build/MQTTnet.nuspec index cd49b7f4..3a8585fc 100644 --- a/Build/MQTTnet.nuspec +++ b/Build/MQTTnet.nuspec @@ -13,6 +13,8 @@ * [Core] Fixed issues in MQTTv5 message encoding and decoding. * [Client] Added support for extended authentication exchange. +* [Client] Exposed MQTTv5 CONNACK values to client. +* [Client] Added _MqttClientSubscribeOptionsBuilder_. Copyright Christian Kratky 2016-2019 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 diff --git a/Source/MQTTnet/Client/Connecting/MqttClientAuthenticateResult.cs b/Source/MQTTnet/Client/Connecting/MqttClientAuthenticateResult.cs index db6e5be5..21d646ba 100644 --- a/Source/MQTTnet/Client/Connecting/MqttClientAuthenticateResult.cs +++ b/Source/MQTTnet/Client/Connecting/MqttClientAuthenticateResult.cs @@ -1,9 +1,45 @@ -namespace MQTTnet.Client.Connecting +using System.Collections.Generic; +using MQTTnet.Packets; + +namespace MQTTnet.Client.Connecting { + // TODO: Consider renaming this to _MqttClientConnectResult_ public class MqttClientAuthenticateResult { + public MqttClientConnectResultCode ResultCode { get; set; } + public bool IsSessionPresent { get; set; } - public MqttClientConnectResultCode ResultCode { get; set; } + public bool? WildcardSubscriptionAvailable { get; set; } + + public bool? RetainAvailable { get; set; } + + public string AssignedClientIdentifier { get; set; } + + public string AuthenticationMethod { get; set; } + + public byte[] AuthenticationData { get; set; } + + public uint? MaximumPacketSize { get; set; } + + public string ReasonString { get; set; } + + public ushort? ReceiveMaximum { get; set; } + + public string ResponseInformation { get; set; } + + public ushort? TopicAliasMaximum { get; set; } + + public string ServerReference { get; set; } + + public ushort? ServerKeepAlive { get; set; } + + public uint? SessionExpiryInterval { get; set; } + + public bool? SubscriptionIdentifiersAvailable { get; set; } + + public bool? SharedSubscriptionAvailable { get; set; } + + public List UserProperties { get; set; } } } From e96b66e9f84b400facf135ef41e0ce26fe4dfc06 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Fri, 17 May 2019 20:57:56 +0200 Subject: [PATCH 07/12] Update splash screen for MQTTnet.Server. --- Source/MQTTnet.Server/Program.cs | 43 +++++++++++++++----------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/Source/MQTTnet.Server/Program.cs b/Source/MQTTnet.Server/Program.cs index 3e8a0a0a..cb773ce3 100644 --- a/Source/MQTTnet.Server/Program.cs +++ b/Source/MQTTnet.Server/Program.cs @@ -27,45 +27,42 @@ namespace MQTTnet.Server private static void PrintLogo() { Console.ResetColor(); - Console.ForegroundColor = ConsoleColor.White; - Console.BackgroundColor = ConsoleColor.Red; + Console.ForegroundColor = ConsoleColor.Red; const string LogoText = -@"| | -| __ __ ____ _______ _______ _ _____ | -| | \/ |/ __ \__ __|__ __| | | / ____| | -| | \ / | | | | | | | |_ __ ___| |_ | (___ ___ _ ____ _____ _ __ | -| | |\/| | | | | | | | | '_ \ / _ \ __| \___ \ / _ \ '__\ \ / / _ \ '__| | -| | | | | |__| | | | | | | | | __/ |_ ____) | __/ | \ V / __/ | | -| |_| |_|\___\_\ |_| |_|_| |_|\___|\__| |_____/ \___|_| \_/ \___|_| | -| | -| |"; +@" + +███╗ ███╗ ██████╗ ████████╗████████╗███╗ ██╗███████╗████████╗ ███████╗███████╗██████╗ ██╗ ██╗███████╗██████╗ +████╗ ████║██╔═══██╗╚══██╔══╝╚══██╔══╝████╗ ██║██╔════╝╚══██╔══╝ ██╔════╝██╔════╝██╔══██╗██║ ██║██╔════╝██╔══██╗ +██╔████╔██║██║ ██║ ██║ ██║ ██╔██╗ ██║█████╗ ██║ ███████╗█████╗ ██████╔╝██║ ██║█████╗ ██████╔╝ +██║╚██╔╝██║██║▄▄ ██║ ██║ ██║ ██║╚██╗██║██╔══╝ ██║ ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██╔══╝ ██╔══██╗ +██║ ╚═╝ ██║╚██████╔╝ ██║ ██║ ██║ ╚████║███████╗ ██║ ███████║███████╗██║ ██║ ╚████╔╝ ███████╗██║ ██║ +╚═╝ ╚═╝ ╚══▀▀═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝ + +"; Console.WriteLine(LogoText); Console.ResetColor(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine(@" - -- The official MQTT server implementation of MQTTnet -- - Copyright (c) 2017-2019 The MQTTnet Team"); + Console.WriteLine("The official MQTT server implementation of MQTTnet"); + Console.WriteLine("Copyright (c) 2017-2019 The MQTTnet Team"); Console.ForegroundColor = ConsoleColor.Blue; - Console.WriteLine(@" - https://github.com/chkr1011/MQTTnet"); + Console.WriteLine(@"https://github.com/chkr1011/MQTTnet"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($@" - Version: {Assembly.GetExecutingAssembly().GetName().Version} - License: MIT (read LICENSE file) - Sponsoring: https://opencollective.com/mqttnet - Support: https://github.com/chkr1011/MQTTnet/issues - Docs: https://github.com/chkr1011/MQTTnet/wiki/MQTTnetServer +Version: {Assembly.GetExecutingAssembly().GetName().Version} +License: MIT (read LICENSE file) +Sponsoring: https://opencollective.com/mqttnet +Support: https://github.com/chkr1011/MQTTnet/issues +Docs: https://github.com/chkr1011/MQTTnet/wiki/MQTTnetServer "); - Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" ! THIS IS AN ALPHA VERSION! IT IS NOT RECOMMENDED TO USE IT FOR ANY DIFFERENT PURPOSE THAN TESTING OR EVALUATING!"); - Console.WriteLine(); Console.ResetColor(); + Console.WriteLine(); } } } \ No newline at end of file From d1a17314ef861ab0c49caa487bb7df02df20b7f6 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sat, 18 May 2019 09:48:44 +0200 Subject: [PATCH 08/12] Add extension library for WebSocket4Net usage. --- Build/MQTTnet.Extensions.WebSocket4Net.nuspec | 42 ++++ Build/MQTTnet.nuspec | 1 + Build/build.ps1 | 14 +- MQTTnet.sln | 20 ++ .../MQTTnet.Extensions.WebSocket4Net.csproj | 34 +++ .../MqttFactoryExtensions.cs | 14 ++ .../WebSocket4NetMqttChannel.cs | 231 ++++++++++++++++++ .../WebSocket4NetMqttClientAdapterFactory.cs | 36 +++ Source/MQTTnet/Client/IMqttClientFactory.cs | 2 + Source/MQTTnet/MqttFactory.cs | 34 ++- .../MQTTnet.TestApp.NetCore.csproj | 1 + .../PublicBrokerTest.cs | 4 + .../MQTTnet.TestApp.UniversalWindows.csproj | 4 + .../MainPage.xaml | 1 + .../MainPage.xaml.cs | 31 ++- 15 files changed, 448 insertions(+), 21 deletions(-) create mode 100644 Build/MQTTnet.Extensions.WebSocket4Net.nuspec create mode 100644 Source/MQTTnet.Extensions.WebSocket4Net/MQTTnet.Extensions.WebSocket4Net.csproj create mode 100644 Source/MQTTnet.Extensions.WebSocket4Net/MqttFactoryExtensions.cs create mode 100644 Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttChannel.cs create mode 100644 Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttClientAdapterFactory.cs diff --git a/Build/MQTTnet.Extensions.WebSocket4Net.nuspec b/Build/MQTTnet.Extensions.WebSocket4Net.nuspec new file mode 100644 index 00000000..054933ed --- /dev/null +++ b/Build/MQTTnet.Extensions.WebSocket4Net.nuspec @@ -0,0 +1,42 @@ + + + + MQTTnet.Extensions.WebSocket4Net + 0.0.0 + Christian Kratky + Christian Kratky + LICENSE + https://github.com/chkr1011/MQTTnet + https://raw.githubusercontent.com/chkr1011/MQTTnet/master/Images/Logo_128x128.png + false + This is an extension library which allows using _WebSocket4Net_ as transport for MQTTnet clients. + For release notes please go to MQTTnet release notes (https://www.nuget.org/packages/MQTTnet/). + Copyright Christian Kratky 2016-2019 + 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 + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Build/MQTTnet.nuspec b/Build/MQTTnet.nuspec index 3a8585fc..543719c5 100644 --- a/Build/MQTTnet.nuspec +++ b/Build/MQTTnet.nuspec @@ -12,6 +12,7 @@ MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). * [Core] Fixed issues in MQTTv5 message encoding and decoding. +* [Core] Added extension method to allow usage of _WebSocket4Net_ in clients to fix issues with AWS and Xamarin. * [Client] Added support for extended authentication exchange. * [Client] Exposed MQTTv5 CONNACK values to client. * [Client] Added _MqttClientSubscribeOptionsBuilder_. diff --git a/Build/build.ps1 b/Build/build.ps1 index dd605dd6..ff439f02 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -36,6 +36,14 @@ Write-Host &$msbuild ..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" &$msbuild ..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="uap10.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" +# Build the WebSocket4Net extension +&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net452" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" +&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net461" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" +&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard1.3" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" +&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" +&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="uap10.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" + + # Build MQTTnet.Server Remove-Item ..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2 -Recurse -Force -ErrorAction SilentlyContinue &$msbuild ..\Source\MQTTnet.Server\MQTTnet.Server.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp2.2" /p:publishprofile=FolderProfile /p:deployonbuild=true /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" @@ -55,6 +63,8 @@ Copy-Item MQTTnet.Extensions.Rpc.nuspec -Destination MQTTnet.Extensions.Rpc.nusp (Get-Content MQTTnet.Extensions.Rpc.nuspec) -replace '\$nugetVersion', $nugetVersion | Set-Content MQTTnet.Extensions.Rpc.nuspec Copy-Item MQTTnet.Extensions.ManagedClient.nuspec -Destination MQTTnet.Extensions.ManagedClient.nuspec.old -Force (Get-Content MQTTnet.Extensions.ManagedClient.nuspec) -replace '\$nugetVersion', $nugetVersion | Set-Content MQTTnet.Extensions.ManagedClient.nuspec +Copy-Item MQTTnet.Extensions.WebSocket4Net.nuspec -Destination MQTTnet.Extensions.WebSocket4Net.nuspec.old -Force +(Get-Content MQTTnet.Extensions.WebSocket4Net.nuspec) -replace '\$nugetVersion', $nugetVersion | Set-Content MQTTnet.Extensions.WebSocket4Net.nuspec New-Item -ItemType Directory -Force -Path .\NuGet .\nuget.exe pack MQTTnet.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion @@ -62,7 +72,9 @@ New-Item -ItemType Directory -Force -Path .\NuGet .\nuget.exe pack MQTTnet.AspNetCore.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion .\nuget.exe pack MQTTnet.Extensions.Rpc.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion .\nuget.exe pack MQTTnet.Extensions.ManagedClient.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion +.\nuget.exe pack MQTTnet.Extensions.WebSocket4Net.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion Move-Item MQTTnet.AspNetCore.nuspec.old -Destination MQTTnet.AspNetCore.nuspec -Force Move-Item MQTTnet.Extensions.Rpc.nuspec.old -Destination MQTTnet.Extensions.Rpc.nuspec -Force -Move-Item MQTTnet.Extensions.ManagedClient.nuspec.old -Destination MQTTnet.Extensions.ManagedClient.nuspec -Force \ No newline at end of file +Move-Item MQTTnet.Extensions.ManagedClient.nuspec.old -Destination MQTTnet.Extensions.ManagedClient.nuspec -Force +Move-Item MQTTnet.Extensions.WebSocket4Net.nuspec.old -Destination MQTTnet.Extensions.WebSocket4Net.nuspec -Force \ No newline at end of file diff --git a/MQTTnet.sln b/MQTTnet.sln index 28d5dcab..4504baaa 100644 --- a/MQTTnet.sln +++ b/MQTTnet.sln @@ -19,6 +19,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{67C28AC1 Build\MQTTnet.AspNetCore.nuspec = Build\MQTTnet.AspNetCore.nuspec Build\MQTTnet.Extensions.ManagedClient.nuspec = Build\MQTTnet.Extensions.ManagedClient.nuspec Build\MQTTnet.Extensions.Rpc.nuspec = Build\MQTTnet.Extensions.Rpc.nuspec + Build\MQTTnet.Extensions.WebSocket4Net.nuspec = Build\MQTTnet.Extensions.WebSocket4Net.nuspec Build\MQTTnet.NETStandard.nuspec = Build\MQTTnet.NETStandard.nuspec Build\MQTTnet.nuspec = Build\MQTTnet.nuspec Build\upload.ps1 = Build\upload.ps1 @@ -50,6 +51,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.AspNetCore.Tests", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Server", "Source\MQTTnet.Server\MQTTnet.Server.csproj", "{5699FB8C-838C-4AB0-80A5-9CA809F9B65B}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Extensions.WebSocket4Net", "Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj", "{2BD01D53-4CA5-4142-BE8D-313876395E3E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -245,6 +248,22 @@ Global {5699FB8C-838C-4AB0-80A5-9CA809F9B65B}.Release|x64.Build.0 = Release|Any CPU {5699FB8C-838C-4AB0-80A5-9CA809F9B65B}.Release|x86.ActiveCfg = Release|Any CPU {5699FB8C-838C-4AB0-80A5-9CA809F9B65B}.Release|x86.Build.0 = Release|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|ARM.ActiveCfg = Debug|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|ARM.Build.0 = Debug|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|x64.ActiveCfg = Debug|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|x64.Build.0 = Debug|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|x86.ActiveCfg = Debug|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|x86.Build.0 = Debug|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|Any CPU.Build.0 = Release|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|ARM.ActiveCfg = Release|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|ARM.Build.0 = Release|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|x64.ActiveCfg = Release|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|x64.Build.0 = Release|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|x86.ActiveCfg = Release|Any CPU + {2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -261,6 +280,7 @@ Global {C400533A-8EBA-4F0B-BF4D-295C3708604B} = {12816BCC-AF9E-44A9-9AE5-C246AF2A0587} {61B62223-F5D0-48E4-BBD6-2CBA9353CB5E} = {9248C2E1-B9D6-40BF-81EC-86004D7765B4} {5699FB8C-838C-4AB0-80A5-9CA809F9B65B} = {32A630A7-2598-41D7-B625-204CD906F5FB} + {2BD01D53-4CA5-4142-BE8D-313876395E3E} = {12816BCC-AF9E-44A9-9AE5-C246AF2A0587} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {07536672-5CBC-4BE3-ACE0-708A431A7894} diff --git a/Source/MQTTnet.Extensions.WebSocket4Net/MQTTnet.Extensions.WebSocket4Net.csproj b/Source/MQTTnet.Extensions.WebSocket4Net/MQTTnet.Extensions.WebSocket4Net.csproj new file mode 100644 index 00000000..b2aade0e --- /dev/null +++ b/Source/MQTTnet.Extensions.WebSocket4Net/MQTTnet.Extensions.WebSocket4Net.csproj @@ -0,0 +1,34 @@ + + + + netstandard1.3;netstandard2.0 + $(TargetFrameworks);net452;net461 + $(TargetFrameworks);uap10.0 + + + + + + + + false + UAP,Version=v10.0 + UAP + 10.0.17134.0 + 10.0.10240.0 + .NETCore + v5.0 + $(DefineConstants);WINDOWS_UWP + en + $(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets + + + + + + + + + + + diff --git a/Source/MQTTnet.Extensions.WebSocket4Net/MqttFactoryExtensions.cs b/Source/MQTTnet.Extensions.WebSocket4Net/MqttFactoryExtensions.cs new file mode 100644 index 00000000..e593a883 --- /dev/null +++ b/Source/MQTTnet.Extensions.WebSocket4Net/MqttFactoryExtensions.cs @@ -0,0 +1,14 @@ +using System; + +namespace MQTTnet.Extensions.WebSocket4Net +{ + public static class MqttFactoryExtensions + { + public static IMqttFactory UseWebSocket4Net(this IMqttFactory mqttFactory) + { + if (mqttFactory == null) throw new ArgumentNullException(nameof(mqttFactory)); + + return mqttFactory.UseClientAdapterFactory(new WebSocket4NetMqttClientAdapterFactory()); + } + } +} diff --git a/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttChannel.cs b/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttChannel.cs new file mode 100644 index 00000000..c3c6be29 --- /dev/null +++ b/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttChannel.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using MQTTnet.Channel; +using MQTTnet.Client.Options; +using MQTTnet.Exceptions; +using MQTTnet.Internal; +using SuperSocket.ClientEngine; +using WebSocket4Net; + +namespace MQTTnet.Extensions.WebSocket4Net +{ + public class WebSocket4NetMqttChannel : IMqttChannel + { + private readonly BlockingCollection _receiveBuffer = new BlockingCollection(); + + private readonly IMqttClientOptions _clientOptions; + private readonly MqttClientWebSocketOptions _webSocketOptions; + + private WebSocket _webSocket; + + public WebSocket4NetMqttChannel(IMqttClientOptions clientOptions, MqttClientWebSocketOptions webSocketOptions) + { + _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions)); + _webSocketOptions = webSocketOptions ?? throw new ArgumentNullException(nameof(webSocketOptions)); + } + + public string Endpoint => _webSocketOptions.Uri; + + public bool IsSecureConnection { get; private set; } + + public async Task ConnectAsync(CancellationToken cancellationToken) + { + var uri = _webSocketOptions.Uri; + if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) && !uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase)) + { + if (_webSocketOptions.TlsOptions?.UseTls == false) + { + uri = "ws://" + uri; + } + else + { + uri = "wss://" + uri; + } + } + + var sslProtocols = _webSocketOptions?.TlsOptions?.SslProtocol ?? SslProtocols.None; + var subProtocol = _webSocketOptions.SubProtocols.FirstOrDefault() ?? string.Empty; + + var cookies = new List>(); + if (_webSocketOptions.CookieContainer != null) + { + throw new NotSupportedException("Cookies are not supported."); + } + + List> customHeaders = null; + if (_webSocketOptions.RequestHeaders != null) + { + customHeaders = _webSocketOptions.RequestHeaders.Select(i => new KeyValuePair(i.Key, i.Value)).ToList(); + } + + EndPoint proxy = null; + if (_webSocketOptions.ProxyOptions != null) + { + throw new NotSupportedException("Proxies are not supported."); + } + + // The user agent can be empty always because it is just added to the custom headers as "User-Agent". + var userAgent = string.Empty; + + var origin = string.Empty; + var webSocketVersion = WebSocketVersion.None; + var receiveBufferSize = 0; + + var certificates = new X509CertificateCollection(); + if (_webSocketOptions?.TlsOptions?.Certificates != null) + { + foreach (var certificate in _webSocketOptions.TlsOptions.Certificates) + { + certificates.Add(new X509Certificate(certificate)); + } + } + + _webSocket = new WebSocket(uri, subProtocol, cookies, customHeaders, userAgent, origin, webSocketVersion, proxy, sslProtocols, receiveBufferSize) + { + NoDelay = true, + Security = + { + AllowUnstrustedCertificate = _webSocketOptions?.TlsOptions?.AllowUntrustedCertificates == true, + AllowCertificateChainErrors = _webSocketOptions?.TlsOptions?.IgnoreCertificateChainErrors == true, + Certificates = certificates + } + }; + + await ConnectInternalAsync(cancellationToken).ConfigureAwait(false); + + IsSecureConnection = uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase); + } + + public Task DisconnectAsync(CancellationToken cancellationToken) + { + if (_webSocket != null && _webSocket.State == WebSocketState.Open) + { + _webSocket.Close(); + } + + return Task.FromResult(0); + } + + public Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + var readBytes = 0; + while (count > 0 && !cancellationToken.IsCancellationRequested) + { + if (!_receiveBuffer.TryTake(out var @byte)) + { + if (readBytes == 0) + { + // Block until at least one byte was received. + @byte = _receiveBuffer.Take(cancellationToken); + } + else + { + return Task.FromResult(readBytes); + } + } + + buffer[offset] = @byte; + offset++; + count--; + readBytes++; + } + + return Task.FromResult(readBytes); + } + + public Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + _webSocket.Send(buffer, offset, count); + return Task.FromResult(0); + } + + public void Dispose() + { + if (_webSocket == null) + { + return; + } + + _webSocket.DataReceived -= OnDataReceived; + _webSocket.Error -= OnError; + _webSocket.Dispose(); + _webSocket = null; + } + + private void OnError(object sender, ErrorEventArgs e) + { + System.Diagnostics.Debug.Write(e.Exception.ToString()); + } + + private void OnDataReceived(object sender, DataReceivedEventArgs e) + { + foreach (var @byte in e.Data) + { + _receiveBuffer.Add(@byte); + } + } + + private async Task ConnectInternalAsync(CancellationToken cancellationToken) + { + _webSocket.Error += OnError; + _webSocket.DataReceived += OnDataReceived; + + var taskCompletionSource = new TaskCompletionSource(); + + void ErrorHandler(object sender, ErrorEventArgs e) + { + taskCompletionSource.TrySetResult(e.Exception); + } + + void SuccessHandler(object sender, EventArgs e) + { + taskCompletionSource.TrySetResult(null); + } + + try + { + _webSocket.Opened += SuccessHandler; + _webSocket.Error += ErrorHandler; + + _webSocket.Open(); + + var exception = await MqttTaskTimeout.WaitAsync(c => + { + c.Register(() => taskCompletionSource.TrySetCanceled()); + return taskCompletionSource.Task; + }, _clientOptions.CommunicationTimeout, cancellationToken).ConfigureAwait(false); + + if (exception != null) + { + if (exception is AuthenticationException authenticationException) + { + throw new MqttCommunicationException(authenticationException.InnerException); + } + + if (exception is OperationCanceledException) + { + throw new MqttCommunicationTimedOutException(); + } + + throw new MqttCommunicationException(exception); + } + } + catch (OperationCanceledException) + { + throw new MqttCommunicationTimedOutException(); + } + finally + { + _webSocket.Opened -= SuccessHandler; + _webSocket.Error -= ErrorHandler; + } + } + } +} diff --git a/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttClientAdapterFactory.cs b/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttClientAdapterFactory.cs new file mode 100644 index 00000000..7625fc92 --- /dev/null +++ b/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttClientAdapterFactory.cs @@ -0,0 +1,36 @@ +using System; +using MQTTnet.Adapter; +using MQTTnet.Client.Options; +using MQTTnet.Diagnostics; +using MQTTnet.Formatter; +using MQTTnet.Implementations; + +namespace MQTTnet.Extensions.WebSocket4Net +{ + public class WebSocket4NetMqttClientAdapterFactory : IMqttClientAdapterFactory + { + public IMqttChannelAdapter CreateClientAdapter(IMqttClientOptions options, IMqttNetChildLogger logger) + { + if (options == null) throw new ArgumentNullException(nameof(options)); + if (logger == null) throw new ArgumentNullException(nameof(logger)); + + switch (options.ChannelOptions) + { + case MqttClientTcpOptions _: + { + return new MqttChannelAdapter(new MqttTcpChannel(options), new MqttPacketFormatterAdapter(options.ProtocolVersion), logger); + } + + case MqttClientWebSocketOptions webSocketOptions: + { + return new MqttChannelAdapter(new WebSocket4NetMqttChannel(options, webSocketOptions), new MqttPacketFormatterAdapter(options.ProtocolVersion), logger); + } + + default: + { + throw new NotSupportedException(); + } + } + } + } +} diff --git a/Source/MQTTnet/Client/IMqttClientFactory.cs b/Source/MQTTnet/Client/IMqttClientFactory.cs index 95d567ea..bae75aca 100644 --- a/Source/MQTTnet/Client/IMqttClientFactory.cs +++ b/Source/MQTTnet/Client/IMqttClientFactory.cs @@ -5,6 +5,8 @@ namespace MQTTnet.Client { public interface IMqttClientFactory { + IMqttFactory UseClientAdapterFactory(IMqttClientAdapterFactory clientAdapterFactory); + IMqttClient CreateMqttClient(); IMqttClient CreateMqttClient(IMqttNetLogger logger); diff --git a/Source/MQTTnet/MqttFactory.cs b/Source/MQTTnet/MqttFactory.cs index ab6cc760..cb835f60 100644 --- a/Source/MQTTnet/MqttFactory.cs +++ b/Source/MQTTnet/MqttFactory.cs @@ -10,6 +10,8 @@ namespace MQTTnet { public class MqttFactory : IMqttFactory { + private IMqttClientAdapterFactory _clientAdapterFactory = new MqttClientAdapterFactory(); + public MqttFactory() : this(new MqttNetLogger()) { } @@ -21,6 +23,12 @@ namespace MQTTnet public IMqttNetLogger DefaultLogger { get; } + public IMqttFactory UseClientAdapterFactory(IMqttClientAdapterFactory clientAdapterFactory) + { + _clientAdapterFactory = clientAdapterFactory ?? throw new ArgumentNullException(nameof(clientAdapterFactory)); + return this; + } + public IMqttClient CreateMqttClient() { return CreateMqttClient(DefaultLogger); @@ -30,22 +38,22 @@ namespace MQTTnet { if (logger == null) throw new ArgumentNullException(nameof(logger)); - return new MqttClient(new MqttClientAdapterFactory(), logger); + return new MqttClient(_clientAdapterFactory, logger); } - public IMqttClient CreateMqttClient(IMqttClientAdapterFactory adapterFactory) + public IMqttClient CreateMqttClient(IMqttClientAdapterFactory clientAdapterFactory) { - if (adapterFactory == null) throw new ArgumentNullException(nameof(adapterFactory)); + if (clientAdapterFactory == null) throw new ArgumentNullException(nameof(clientAdapterFactory)); - return new MqttClient(adapterFactory, DefaultLogger); + return new MqttClient(clientAdapterFactory, DefaultLogger); } - public IMqttClient CreateMqttClient(IMqttNetLogger logger, IMqttClientAdapterFactory adapterFactory) + public IMqttClient CreateMqttClient(IMqttNetLogger logger, IMqttClientAdapterFactory clientAdapterFactory) { if (logger == null) throw new ArgumentNullException(nameof(logger)); - if (adapterFactory == null) throw new ArgumentNullException(nameof(adapterFactory)); + if (clientAdapterFactory == null) throw new ArgumentNullException(nameof(clientAdapterFactory)); - return new MqttClient(adapterFactory, logger); + return new MqttClient(clientAdapterFactory, logger); } public IMqttServer CreateMqttServer() @@ -60,19 +68,19 @@ namespace MQTTnet return CreateMqttServer(new List { new MqttTcpServerAdapter(logger.CreateChildLogger()) }, logger); } - public IMqttServer CreateMqttServer(IEnumerable adapters, IMqttNetLogger logger) + public IMqttServer CreateMqttServer(IEnumerable serverAdapters, IMqttNetLogger logger) { - if (adapters == null) throw new ArgumentNullException(nameof(adapters)); + if (serverAdapters == null) throw new ArgumentNullException(nameof(serverAdapters)); if (logger == null) throw new ArgumentNullException(nameof(logger)); - return new MqttServer(adapters, logger.CreateChildLogger()); + return new MqttServer(serverAdapters, logger.CreateChildLogger()); } - public IMqttServer CreateMqttServer(IEnumerable adapters) + public IMqttServer CreateMqttServer(IEnumerable serverAdapters) { - if (adapters == null) throw new ArgumentNullException(nameof(adapters)); + if (serverAdapters == null) throw new ArgumentNullException(nameof(serverAdapters)); - return new MqttServer(adapters, DefaultLogger.CreateChildLogger()); + return new MqttServer(serverAdapters, DefaultLogger.CreateChildLogger()); } } } \ No newline at end of file diff --git a/Tests/MQTTnet.TestApp.NetCore/MQTTnet.TestApp.NetCore.csproj b/Tests/MQTTnet.TestApp.NetCore/MQTTnet.TestApp.NetCore.csproj index 1900203e..f3114e32 100644 --- a/Tests/MQTTnet.TestApp.NetCore/MQTTnet.TestApp.NetCore.csproj +++ b/Tests/MQTTnet.TestApp.NetCore/MQTTnet.TestApp.NetCore.csproj @@ -17,6 +17,7 @@ + diff --git a/Tests/MQTTnet.TestApp.NetCore/PublicBrokerTest.cs b/Tests/MQTTnet.TestApp.NetCore/PublicBrokerTest.cs index ff4e3374..58c4ad10 100644 --- a/Tests/MQTTnet.TestApp.NetCore/PublicBrokerTest.cs +++ b/Tests/MQTTnet.TestApp.NetCore/PublicBrokerTest.cs @@ -1,10 +1,13 @@ using MQTTnet.Client; using System; using System.IO; +using System.Net; +using System.Security.Authentication; using System.Threading; using System.Threading.Tasks; using MQTTnet.Client.Options; using MQTTnet.Client.Receiving; +using MQTTnet.Extensions.WebSocket4Net; using MQTTnet.Formatter; using MQTTnet.Protocol; using Newtonsoft.Json; @@ -77,6 +80,7 @@ namespace MQTTnet.TestApp.NetCore { Write("Testing '" + name + "'... ", ConsoleColor.Gray); var factory = new MqttFactory(); + //factory.UseWebSocket4Net(); var client = factory.CreateMqttClient(); var topic = Guid.NewGuid().ToString(); diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows.csproj b/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows.csproj index c13db930..243c9c56 100644 --- a/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows.csproj +++ b/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows.csproj @@ -135,6 +135,10 @@ {c444e9c8-95fa-430e-9126-274129de16cd} MQTTnet.Extensions.Rpc + + {2BD01D53-4CA5-4142-BE8D-313876395E3E} + MQTTnet.Extensions.WebSocket4Net + {3587e506-55a2-4eb3-99c7-dc01e42d25d2} MQTTnet diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml b/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml index 210f0595..11e68c65 100644 --- a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml +++ b/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml @@ -63,6 +63,7 @@ TCP WS + WS (WebSocket4Net) Use TLS diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs b/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs index 226fcf23..899ee216 100644 --- a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs +++ b/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Concurrent; using System.Collections.ObjectModel; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using Windows.Security.Cryptography.Certificates; @@ -23,6 +21,7 @@ using MQTTnet.Server; using MQTTnet.Server.Status; using MqttClientConnectedEventArgs = MQTTnet.Client.Connecting.MqttClientConnectedEventArgs; using MqttClientDisconnectedEventArgs = MQTTnet.Client.Disconnecting.MqttClientDisconnectedEventArgs; +using MQTTnet.Extensions.WebSocket4Net; namespace MQTTnet.TestApp.UniversalWindows { @@ -83,6 +82,8 @@ namespace MQTTnet.TestApp.UniversalWindows private async void Connect(object sender, RoutedEventArgs e) { + var mqttFactory = new MqttFactory(); + var tlsOptions = new MqttClientTlsOptions { UseTls = UseTls.IsChecked == true, @@ -116,6 +117,17 @@ namespace MQTTnet.TestApp.UniversalWindows }; } + if (UseWs4Net.IsChecked == true) + { + options.ChannelOptions = new MqttClientWebSocketOptions + { + Uri = Server.Text, + TlsOptions = tlsOptions + }; + + mqttFactory.UseWebSocket4Net(); + } + if (options.ChannelOptions == null) { throw new InvalidOperationException(); @@ -156,11 +168,9 @@ namespace MQTTnet.TestApp.UniversalWindows _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected(x)); } - var factory = new MqttFactory(); - if (UseManagedClient.IsChecked == true) { - _managedMqttClient = factory.CreateManagedMqttClient(); + _managedMqttClient = mqttFactory.CreateManagedMqttClient(); _managedMqttClient.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage); _managedMqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected(x)); _managedMqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected(x)); @@ -172,7 +182,7 @@ namespace MQTTnet.TestApp.UniversalWindows } else { - _mqttClient = factory.CreateMqttClient(); + _mqttClient = mqttFactory.CreateMqttClient(); _mqttClient.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage); _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected(x)); _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected(x)); @@ -204,7 +214,7 @@ namespace MQTTnet.TestApp.UniversalWindows private async Task HandleReceivedApplicationMessage(MqttApplicationMessageReceivedEventArgs eventArgs) { - var item = $"Timestamp: {DateTime.Now:O} | Topic: {eventArgs.ApplicationMessage.Topic} | Payload: {Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)} | QoS: {eventArgs.ApplicationMessage.QualityOfServiceLevel}"; + var item = $"Timestamp: {DateTime.Now:O} | Topic: {eventArgs.ApplicationMessage.Topic} | Payload: {eventArgs.ApplicationMessage.ConvertPayloadToString()} | QoS: {eventArgs.ApplicationMessage.QualityOfServiceLevel}"; await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { @@ -524,6 +534,13 @@ namespace MQTTnet.TestApp.UniversalWindows Console.WriteLine(); }); + void Handler(MqttApplicationMessageReceivedEventArgs args) + { + //... + } + + client.UseApplicationMessageReceivedHandler(Handler); + // Subscribe after connect client.UseConnectedHandler(async e => From 0a509fd6857131414dc895f894893c846066be42 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sat, 18 May 2019 20:50:29 +0200 Subject: [PATCH 09/12] Add publish profiles. --- .../PublishProfiles/FolderProfile.pubxml | 19 +++++++++++++++ .../PublishProfiles/Linux_x64.pubxml | 23 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 Source/MQTTnet.Server/Properties/PublishProfiles/FolderProfile.pubxml create mode 100644 Source/MQTTnet.Server/Properties/PublishProfiles/Linux_x64.pubxml diff --git a/Source/MQTTnet.Server/Properties/PublishProfiles/FolderProfile.pubxml b/Source/MQTTnet.Server/Properties/PublishProfiles/FolderProfile.pubxml new file mode 100644 index 00000000..e13437c9 --- /dev/null +++ b/Source/MQTTnet.Server/Properties/PublishProfiles/FolderProfile.pubxml @@ -0,0 +1,19 @@ + + + + + FileSystem + FileSystem + Release + Any CPU + + True + False + 5699fb8c-838c-4ab0-80a5-9ca809f9b65b + bin\publish\ + False + + \ No newline at end of file diff --git a/Source/MQTTnet.Server/Properties/PublishProfiles/Linux_x64.pubxml b/Source/MQTTnet.Server/Properties/PublishProfiles/Linux_x64.pubxml new file mode 100644 index 00000000..74b808b3 --- /dev/null +++ b/Source/MQTTnet.Server/Properties/PublishProfiles/Linux_x64.pubxml @@ -0,0 +1,23 @@ + + + + + FileSystem + FileSystem + Release + x64 + + True + False + 5699fb8c-838c-4ab0-80a5-9ca809f9b65b + bin\linux_x64 + False + netcoreapp2.2 + linux-x64 + true + <_IsPortable>false + + \ No newline at end of file From 2d3fdd4fafab8b62485f188820cf4828f4b4d69a Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sat, 18 May 2019 20:51:19 +0200 Subject: [PATCH 10/12] Update publish profile. --- .../Properties/PublishProfiles/FolderProfile.pubxml | 4 ++-- .../Properties/PublishProfiles/Linux_x64.pubxml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Source/MQTTnet.Server/Properties/PublishProfiles/FolderProfile.pubxml b/Source/MQTTnet.Server/Properties/PublishProfiles/FolderProfile.pubxml index e13437c9..5b904474 100644 --- a/Source/MQTTnet.Server/Properties/PublishProfiles/FolderProfile.pubxml +++ b/Source/MQTTnet.Server/Properties/PublishProfiles/FolderProfile.pubxml @@ -10,10 +10,10 @@ by editing this MSBuild file. In order to learn more about this please visit htt Release Any CPU - True + False False 5699fb8c-838c-4ab0-80a5-9ca809f9b65b bin\publish\ - False + True \ No newline at end of file diff --git a/Source/MQTTnet.Server/Properties/PublishProfiles/Linux_x64.pubxml b/Source/MQTTnet.Server/Properties/PublishProfiles/Linux_x64.pubxml index 74b808b3..a3b0f6f3 100644 --- a/Source/MQTTnet.Server/Properties/PublishProfiles/Linux_x64.pubxml +++ b/Source/MQTTnet.Server/Properties/PublishProfiles/Linux_x64.pubxml @@ -10,11 +10,11 @@ by editing this MSBuild file. In order to learn more about this please visit htt Release x64 - True + False False 5699fb8c-838c-4ab0-80a5-9ca809f9b65b bin\linux_x64 - False + True netcoreapp2.2 linux-x64 true From e4351b73bd04bf960862949ce1881d459cd6144a Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sun, 19 May 2019 22:23:10 +0200 Subject: [PATCH 11/12] Add connected timestamp to connection status API. --- Source/MQTTnet/Server/MqttClientConnection.cs | 7 +++++-- Source/MQTTnet/Server/Status/MqttClientStatus.cs | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Source/MQTTnet/Server/MqttClientConnection.cs b/Source/MQTTnet/Server/MqttClientConnection.cs index d88d9739..6cc4bc56 100644 --- a/Source/MQTTnet/Server/MqttClientConnection.cs +++ b/Source/MQTTnet/Server/MqttClientConnection.cs @@ -31,11 +31,12 @@ namespace MQTTnet.Server private readonly IMqttDataConverter _dataConverter; private readonly string _endpoint; private readonly MqttConnectPacket _connectPacket; + private readonly DateTime _connectedTimestamp; private Task _packageReceiverTask; private DateTime _lastPacketReceivedTimestamp; private DateTime _lastNonKeepAlivePacketReceivedTimestamp; - + private long _receivedPacketsCount; private long _sentPacketsCount = 1; // Start with 1 because the CONNECT packet is not counted anywhere. private long _receivedApplicationMessagesCount; @@ -65,7 +66,8 @@ namespace MQTTnet.Server _keepAliveMonitor = new MqttClientKeepAliveMonitor(this, _logger); - _lastPacketReceivedTimestamp = DateTime.UtcNow; + _connectedTimestamp = DateTime.UtcNow; + _lastPacketReceivedTimestamp = _connectedTimestamp; _lastNonKeepAlivePacketReceivedTimestamp = _lastPacketReceivedTimestamp; } @@ -96,6 +98,7 @@ namespace MQTTnet.Server status.ReceivedPacketsCount = Interlocked.Read(ref _receivedPacketsCount); status.SentPacketsCount = Interlocked.Read(ref _sentPacketsCount); + status.ConnectedTimestamp = _connectedTimestamp; status.LastPacketReceivedTimestamp = _lastPacketReceivedTimestamp; status.LastNonKeepAlivePacketReceivedTimestamp = _lastNonKeepAlivePacketReceivedTimestamp; diff --git a/Source/MQTTnet/Server/Status/MqttClientStatus.cs b/Source/MQTTnet/Server/Status/MqttClientStatus.cs index cc6e77d3..05cd202f 100644 --- a/Source/MQTTnet/Server/Status/MqttClientStatus.cs +++ b/Source/MQTTnet/Server/Status/MqttClientStatus.cs @@ -21,6 +21,8 @@ namespace MQTTnet.Server.Status public DateTime LastPacketReceivedTimestamp { get; set; } + public DateTime ConnectedTimestamp { get; set; } + public DateTime LastNonKeepAlivePacketReceivedTimestamp { get; set; } public long ReceivedApplicationMessagesCount { get; set; } From 78e504dc2c839eaa2e75719c424acf1982b1ede8 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sun, 26 May 2019 23:44:42 +0200 Subject: [PATCH 12/12] Update Wiki samples. --- .../MainPage.xaml.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs b/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs index 899ee216..f186bc4c 100644 --- a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs +++ b/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs @@ -733,6 +733,22 @@ namespace MQTTnet.TestApp.UniversalWindows var mqttServer = new MqttFactory().CreateMqttServer(); } + { + // Setup application message interceptor. + var options = new MqttServerOptionsBuilder() + .WithApplicationMessageInterceptor(context => + { + if (context.ApplicationMessage.Topic == "my/custom/topic") + { + context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes("The server injected payload."); + } + + // It is also possible to read the payload and extend it. For example by adding a timestamp in a JSON document. + // This is useful when the IoT device has no own clock and the creation time of the message might be important. + }) + .Build(); + } + { // Setup subscription interceptor. var options = new MqttServerOptionsBuilder()