diff --git a/.editorconfig b/.editorconfig index 6555efd5..c4b05393 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,5 +1,84 @@ -[*.cs] +[*.cs] # CA1031: Do not catch general exception types -dotnet_diagnostic.CA1031.severity = none + +# Microsoft .NET properties +csharp_new_line_before_members_in_object_initializers = false +csharp_preferred_modifier_order = public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion +csharp_style_var_elsewhere = true:suggestion +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +dotnet_naming_rule.constants_rule.severity = warning +dotnet_naming_rule.constants_rule.style = upper_camel_case_style +dotnet_naming_rule.constants_rule.symbols = constants_symbols +dotnet_naming_rule.public_fields_rule.severity = warning +dotnet_naming_rule.public_fields_rule.style = lower_camel_case_style +dotnet_naming_rule.public_fields_rule.symbols = public_fields_symbols +dotnet_naming_rule.static_readonly_rule.severity = warning +dotnet_naming_rule.static_readonly_rule.style = upper_camel_case_style +dotnet_naming_rule.static_readonly_rule.symbols = static_readonly_symbols +dotnet_naming_style.lower_camel_case_style.capitalization = camel_case +dotnet_naming_style.lower_camel_case_style.required_prefix = _ +dotnet_naming_style.upper_camel_case_style.capitalization = pascal_case +dotnet_naming_symbols.constants_symbols.applicable_accessibilities = public,internal,protected,protected_internal,private_protected +dotnet_naming_symbols.constants_symbols.applicable_kinds = field +dotnet_naming_symbols.constants_symbols.required_modifiers = const +dotnet_naming_symbols.public_fields_symbols.applicable_accessibilities = public,internal,protected,protected_internal,private_protected +dotnet_naming_symbols.public_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.static_readonly_symbols.applicable_accessibilities = public,internal,protected,protected_internal,private_protected +dotnet_naming_symbols.static_readonly_symbols.applicable_kinds = field +dotnet_naming_symbols.static_readonly_symbols.required_modifiers = static,readonly +dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion +dotnet_style_qualification_for_event = false:suggestion +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_property = false:suggestion + +# ReSharper properties +resharper_autodetect_indent_settings = true +resharper_default_private_modifier = implicit +resharper_place_accessorholder_attribute_on_same_line = false +resharper_use_indent_from_vs = false + +# ReSharper inspection severities +resharper_arrange_redundant_parentheses_highlighting = hint +resharper_arrange_this_qualifier_highlighting = hint +resharper_built_in_type_reference_style_for_member_access_highlighting = hint +resharper_built_in_type_reference_style_highlighting = hint +resharper_redundant_base_qualifier_highlighting = warning +resharper_suggest_var_or_type_built_in_types_highlighting = hint +resharper_suggest_var_or_type_elsewhere_highlighting = hint +resharper_suggest_var_or_type_simple_types_highlighting = hint +resharper_web_config_module_not_resolved_highlighting = warning +resharper_web_config_type_not_resolved_highlighting = warning +resharper_web_config_wrong_module_highlighting = warning + +[*] +charset = utf-8 +end_of_line = crlf +trim_trailing_whitespace = false +insert_final_newline = false +indent_style = space +indent_size = 4 + +[{*.har,*.inputactions,*.jsb2,*.jsb3,*.json,.babelrc,.eslintrc,.stylelintrc,bowerrc,jest.config}] +indent_style = space +indent_size = 2 + +[{*.yaml,*.yml}] +indent_style = space +indent_size = 2 + +[{tsconfig.app.json,tsconfig.e2e.json,tsconfig.json,tsconfig.lib.json,tsconfig.spec.json}] +indent_style = space +indent_size = 2 + +[*.{appxmanifest,asax,ascx,aspx,axaml,build,cg,cginc,compute,cs,cshtml,dtd,hlsl,hlsli,hlslinc,master,nuspec,paml,razor,resw,resx,shader,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}] +indent_style = space +indent_size = 4 +tab_width = 4 diff --git a/Build/MQTTnet.AspNetCore.nuspec b/Build/MQTTnet.AspNetCore.nuspec index 53fb07ec..f9bc8a04 100644 --- a/Build/MQTTnet.AspNetCore.nuspec +++ b/Build/MQTTnet.AspNetCore.nuspec @@ -19,10 +19,14 @@ - + + + + + @@ -33,10 +37,13 @@ + + + - - + + - + diff --git a/Build/MQTTnet.Extensions.ManagedClient.nuspec b/Build/MQTTnet.Extensions.ManagedClient.nuspec index d7de8f47..b360569a 100644 --- a/Build/MQTTnet.Extensions.ManagedClient.nuspec +++ b/Build/MQTTnet.Extensions.ManagedClient.nuspec @@ -13,7 +13,7 @@ This is an extension library which provides a managed MQTT client with additional features using MQTTnet. For release notes please go to MQTTnet release notes (https://www.nuget.org/packages/MQTTnet/). Copyright Christian Kratky 2016-2020 - 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 Blazor + 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 Blazor @@ -26,20 +26,26 @@ + + + - + - + + + + - + - + - + diff --git a/Build/MQTTnet.Extensions.Rpc.nuspec b/Build/MQTTnet.Extensions.Rpc.nuspec index 109665af..283ac11e 100644 --- a/Build/MQTTnet.Extensions.Rpc.nuspec +++ b/Build/MQTTnet.Extensions.Rpc.nuspec @@ -13,7 +13,7 @@ This is an extension library which allows executing synchronous device calls including a response using MQTTnet. For release notes please go to MQTTnet release notes (https://www.nuget.org/packages/MQTTnet/). Copyright Christian Kratky 2016-2020 - 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 Blazor + 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 Blazor @@ -26,20 +26,26 @@ + + + - + - + + + + - + - + - + diff --git a/Build/MQTTnet.Extensions.WebSocket4Net.nuspec b/Build/MQTTnet.Extensions.WebSocket4Net.nuspec index 58a52295..640b6909 100644 --- a/Build/MQTTnet.Extensions.WebSocket4Net.nuspec +++ b/Build/MQTTnet.Extensions.WebSocket4Net.nuspec @@ -13,24 +13,10 @@ 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-2020 - 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 Blazor + 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 Blazor - - - - - - - - - - - - - - - - + + @@ -41,20 +27,26 @@ + + + - + - + + + + - + - + - + diff --git a/Build/MQTTnet.nuspec b/Build/MQTTnet.nuspec index a5aad211..30d6171d 100644 --- a/Build/MQTTnet.nuspec +++ b/Build/MQTTnet.nuspec @@ -12,50 +12,28 @@ true MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker) and supports v3.1.0, v3.1.1 and v5.0.0 of the MQTT protocol. -* [Core] Added .NET 5.0 TFMs (thanks to @StefanOssendorf, @JanEggers). -* [Core] Added support for TLS 1.3 (requires .NET Core 3.1+) (thanks to @Dvergatal). -* [Core] Added support for _MaximumQoS_ transmit when using MQTTv5 (thanks to @nayato). -* [Core] Aligned the format of some log messages. -* [Client] Fixed an issue with connection state detection (thanks to @tobiasfrick). -* [Client] Fixed an issue when receiving partial QoS 2 packets after a reconnect. -* [ManagedClient] Removed _AutoReconnect_ since this does no longer work (BREAKING CHANGE!). -* [RpcClient] Moved the RPC topic validation to the topic generation strategy. -* [RcpClient] Added interface for _MqttRpcClient_. -* [Server] Reduced async tasks count by moving dedicated keep alive tasks per connection to shared one. -* [Server] Session takeover and keep alive timeout are now properly set in DISCONNECT packet. -* [Server] Fixed bug in PubRel packet generation (MQTTv5 only). -* [Server] Improved message processing performance (+ ~5%). -* [Server] Fix wrong usage of client session items for undelivered messages. +* [Core] Fixed some issues in nuget packages. +* [Client] Changed exception types so that proper exceptions are thrown when connecting (#1082). +* [Client] Exposed Dup flag in application messages. +* [RpcClient] Fixed an issue when using a custom application message reveived handler (#1093). Git commit: $gitCommit Copyright Christian Kratky 2016-2020 - 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 Blazor + 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 Blazor + + - - - - - - - - - - - - - - - - - - - + + + + + @@ -70,28 +48,28 @@ Git commit: $gitCommit - + - - + + - + - + - + - + - + - + diff --git a/Build/build.ps1 b/Build/build.ps1 index 3275bf18..b1d3cc94 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -31,10 +31,12 @@ vstest.console.exe ..\Tests\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp3.1\M &$msbuild ..\Source\MQTTnet\MQTTnet.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.1" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" &$msbuild ..\Source\MQTTnet\MQTTnet.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp3.1" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" &$msbuild ..\Source\MQTTnet\MQTTnet.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" +&$msbuild ..\Source\MQTTnet\MQTTnet.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net5.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" # Build the ASP.NET Core 2.0 extension &$msbuild ..\Source\MQTTnet.AspNetCore\MQTTnet.AspNetCore.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.AspNetCore\MQTTnet.AspNetCore.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp3.1" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" +&$msbuild ..\Source\MQTTnet.AspNetCore\MQTTnet.AspNetCore.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net5.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" # Build the RPC extension &$msbuild ..\Source\MQTTnet.Extensions.Rpc\MQTTnet.Extensions.Rpc.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" @@ -43,6 +45,7 @@ vstest.console.exe ..\Tests\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp3.1\M &$msbuild ..\Source\MQTTnet.Extensions.Rpc\MQTTnet.Extensions.Rpc.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.Rpc\MQTTnet.Extensions.Rpc.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.1" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" &$msbuild ..\Source\MQTTnet.Extensions.Rpc\MQTTnet.Extensions.Rpc.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" +&$msbuild ..\Source\MQTTnet.Extensions.Rpc\MQTTnet.Extensions.Rpc.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net5.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" # Build the Managed Client extension &$msbuild ..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.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" @@ -51,6 +54,7 @@ vstest.console.exe ..\Tests\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp3.1\M &$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="netstandard2.1" /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" +&$msbuild ..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net5.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" @@ -59,6 +63,7 @@ vstest.console.exe ..\Tests\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp3.1\M &$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="netstandard2.1" /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" +&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net5.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx" # Create NuGet packages. @@ -97,7 +102,7 @@ Remove-Item "nuget.exe" -Force -Recurse -ErrorAction SilentlyContinue # Build MQTTnet.Server Portable &dotnet publish ..\Source\MQTTnet.Server\MQTTnet.Server.csproj --configuration Release /p:FileVersion=$assemblyVersion /p:Version=$nugetVersion --framework net5.0 -$source = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\Release\netcoreapp3.1\publish" +$source = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\Release\net5.0\publish" $destination = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\MQTTnet.Server-Portable-v$nugetVersion.zip" If(Test-path $destination) {Remove-item $destination} Add-Type -assembly "system.io.compression.filesystem" @@ -108,7 +113,7 @@ If(Test-path $destination) {Remove-item $destination} # Build MQTTnet.Server Linux-x64 &dotnet publish ..\Source\MQTTnet.Server\MQTTnet.Server.csproj --configuration Release /p:FileVersion=$assemblyVersion /p:Version=$nugetVersion --self-contained --runtime linux-x64 --framework net5.0 -$source = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\Release\netcoreapp3.1\linux-x64\publish" +$source = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\Release\net5.0\linux-x64\publish" $destination = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\MQTTnet.Server-Linux-x64-v$nugetVersion.zip" If(Test-path $destination) {Remove-item $destination} Add-Type -assembly "system.io.compression.filesystem" @@ -119,7 +124,7 @@ If(Test-path $destination) {Remove-item $destination} # Build MQTTnet.Server Linux-ARM &dotnet publish ..\Source\MQTTnet.Server\MQTTnet.Server.csproj --configuration Release /p:FileVersion=$assemblyVersion /p:Version=$nugetVersion --self-contained --runtime linux-arm --framework net5.0 -$source = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\Release\netcoreapp3.1\linux-ARM\publish" +$source = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\Release\net5.0\linux-ARM\publish" $destination = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\MQTTnet.Server-Linux-ARM-v$nugetVersion.zip" If(Test-path $destination) {Remove-item $destination} Add-Type -assembly "system.io.compression.filesystem" @@ -130,7 +135,7 @@ If(Test-path $destination) {Remove-item $destination} # Build MQTTnet.Server Windows-x64 &dotnet publish ..\Source\MQTTnet.Server\MQTTnet.Server.csproj --configuration Release /p:FileVersion=$assemblyVersion /p:Version=$nugetVersion --self-contained --runtime win-x64 --framework net5.0 -$source = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\Release\netcoreapp3.1\win-x64\publish" +$source = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\Release\net5.0\win-x64\publish" $destination = (Convert-Path .) + "\..\Source\MQTTnet.Server\bin\MQTTnet.Server-Windows-x64-v$nugetVersion.zip" If(Test-path $destination) {Remove-item $destination} Add-Type -assembly "system.io.compression.filesystem" diff --git a/MQTTnet.sln b/MQTTnet.sln index 74f27256..505290e3 100644 --- a/MQTTnet.sln +++ b/MQTTnet.sln @@ -9,8 +9,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{9248C2E1 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Source", "Source", "{32A630A7-2598-41D7-B625-204CD906F5FB}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.TestApp.UniversalWindows", "Tests\MQTTnet.TestApp.UniversalWindows\MQTTnet.TestApp.UniversalWindows.csproj", "{FF1F72D6-9524-4422-9497-3CC0002216ED}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet", "Source\MQTTnet\MQTTnet.csproj", "{3587E506-55A2-4EB3-99C7-DC01E42D25D2}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{67C28AC1-BC3A-420A-BE9C-FA2401431CF9}" @@ -91,28 +89,6 @@ Global {A7FF0C91-25DE-4BA6-B39E-F54E8DADF1CC}.Release|x64.Build.0 = Release|Any CPU {A7FF0C91-25DE-4BA6-B39E-F54E8DADF1CC}.Release|x86.ActiveCfg = Release|Any CPU {A7FF0C91-25DE-4BA6-B39E-F54E8DADF1CC}.Release|x86.Build.0 = Release|Any CPU - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|ARM.ActiveCfg = Debug|ARM - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|ARM.Build.0 = Debug|ARM - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|ARM.Deploy.0 = Debug|ARM - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|x64.ActiveCfg = Debug|x64 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|x64.Build.0 = Debug|x64 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|x64.Deploy.0 = Debug|x64 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|x86.ActiveCfg = Debug|x86 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|x86.Build.0 = Debug|x86 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Debug|x86.Deploy.0 = Debug|x86 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|Any CPU.Build.0 = Release|Any CPU - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|ARM.ActiveCfg = Release|ARM - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|ARM.Build.0 = Release|ARM - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|ARM.Deploy.0 = Release|ARM - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|x64.ActiveCfg = Release|x64 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|x64.Build.0 = Release|x64 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|x64.Deploy.0 = Release|x64 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|x86.ActiveCfg = Release|x86 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|x86.Build.0 = Release|x86 - {FF1F72D6-9524-4422-9497-3CC0002216ED}.Release|x86.Deploy.0 = Release|x86 {3587E506-55A2-4EB3-99C7-DC01E42D25D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3587E506-55A2-4EB3-99C7-DC01E42D25D2}.Debug|Any CPU.Build.0 = Debug|Any CPU {3587E506-55A2-4EB3-99C7-DC01E42D25D2}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -327,7 +303,6 @@ Global EndGlobalSection GlobalSection(NestedProjects) = preSolution {A7FF0C91-25DE-4BA6-B39E-F54E8DADF1CC} = {9248C2E1-B9D6-40BF-81EC-86004D7765B4} - {FF1F72D6-9524-4422-9497-3CC0002216ED} = {A56E3128-1639-4F31-873A-325E14BB6295} {3587E506-55A2-4EB3-99C7-DC01E42D25D2} = {32A630A7-2598-41D7-B625-204CD906F5FB} {3D283AAD-AAA8-4339-8394-52F80B6304DB} = {9248C2E1-B9D6-40BF-81EC-86004D7765B4} {C6FF8AEA-0855-41EC-A1F3-AC262225BAB9} = {9248C2E1-B9D6-40BF-81EC-86004D7765B4} diff --git a/README.md b/README.md index 5b4bf7f3..5576b311 100644 --- a/README.md +++ b/README.md @@ -64,15 +64,32 @@ _MQTTnet Server_ is a standalone cross platform MQTT server (like mosquitto) bas ## Supported frameworks +* .NET 5.0+ * .NET Standard 1.3+ * .NET Core 1.1+ * .NET Core App 1.1+ -* .NET Framework 4.5.2+ (x86, x64, AnyCPU) +* .NET Framework 4.5.2+ * Mono 5.2+ -* Universal Windows Platform (UWP) 10.0.10240+ (x86, x64, ARM, AnyCPU, Windows 10 IoT Core) +* Universal Windows Platform (UWP) 10.0.10240+ (Windows 10 IoT Core) * Xamarin.Android 7.5+ * Xamarin.iOS 10.14+ -* Blazor WebAssembly 3.2.0 +* Blazor WebAssembly 3.2.0+ + +## Supported platforms + +* x86 +* x64 +* AnyCPU +* ARM + +## Supported OS + +* Windows +* Windows 10 IoT Core +* Linux (Ubuntu, Raspbian etc.) +* macOS +* Android +* iOS ## Supported MQTT versions @@ -97,12 +114,14 @@ Also additions and updates in the Wiki are welcome. This library is used in the following projects: -* Azure Functions MQTT Bindings, [CaseOnline.Azure.WebJobs.Extensions.Mqtt](https://github.com/keesschollaart81/CaseOnline.Azure.WebJobs.Extensions.Mqtt/) +* Azure Functions MQTT Bindings, ) * HA4IoT (Open Source Home Automation system for .NET, ) * MQTT Client Rx (Wrapper for Reactive Extensions, ) * MQTT Client Rx (Managed Client Wrapper for Reactive Extensions, ) * MQTT Tester (MQTT client test app for [Android](https://play.google.com/store/apps/details?id=com.liveowl.mqtttester) and [iOS](https://itunes.apple.com/us/app/mqtt-tester/id1278621826?mt=8)) +* MQTTnet App (Cross platform client application for MQTT debugging, inspection etc., ) * Wirehome.Core (Open Source Home Automation system for .NET Core, ) +* SparkplugNet (Sparkplug library for .Net, ) Further projects using this project can be found under https://github.com/chkr1011/MQTTnet/network/dependents. @@ -112,7 +131,7 @@ If you use this library and want to see your project here please create a pull r MIT License -MQTTnet Copyright (c) 2016-2020 Christian Kratky +MQTTnet Copyright (c) 2016-2021 Christian Kratky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs b/Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs index 5520b936..cec833eb 100644 --- a/Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs +++ b/Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs @@ -49,7 +49,7 @@ namespace MQTTnet.AspNetCore var formatter = new MqttPacketFormatterAdapter(writer); var channel = new MqttWebSocketChannel(webSocket, endpoint, isSecureConnection, clientCertificate); - using (var channelAdapter = new MqttChannelAdapter(channel, formatter, _rootLogger)) + using (var channelAdapter = new MqttChannelAdapter(channel, formatter, null, _rootLogger)) { await clientHandler(channelAdapter).ConfigureAwait(false); } diff --git a/Source/MQTTnet.Extensions.ManagedClient/ManagedMqttClient.cs b/Source/MQTTnet.Extensions.ManagedClient/ManagedMqttClient.cs index 23105748..931326bc 100644 --- a/Source/MQTTnet.Extensions.ManagedClient/ManagedMqttClient.cs +++ b/Source/MQTTnet.Extensions.ManagedClient/ManagedMqttClient.cs @@ -53,11 +53,11 @@ namespace MQTTnet.Extensions.ManagedClient public bool IsConnected => InternalClient.IsConnected; public bool IsStarted => _connectionCancellationToken != null; - + public IMqttClient InternalClient { get; } public int PendingApplicationMessagesCount => _messageQueue.Count; - + public IManagedMqttClientOptions Options { get; private set; } public IMqttClientConnectedHandler ConnectedHandler @@ -92,7 +92,7 @@ namespace MQTTnet.Extensions.ManagedClient if (options == null) throw new ArgumentNullException(nameof(options)); if (options.ClientOptions == null) throw new ArgumentException("The client options are not set.", nameof(options)); - + if (!_maintainConnectionTask?.IsCompleted ?? false) throw new InvalidOperationException("The managed client is already started."); Options = options; @@ -292,7 +292,14 @@ namespace MQTTnet.Extensions.ManagedClient { try { - await InternalClient.DisconnectAsync().ConfigureAwait(false); + using (var disconnectTimeout = new CancellationTokenSource(Options.ClientOptions.CommunicationTimeout)) + { + await InternalClient.DisconnectAsync(disconnectTimeout.Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + _logger.Warning("Timeout while sending DISCONNECT packet."); } catch (Exception exception) { diff --git a/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs b/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs index c225230e..3fbec759 100644 --- a/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs +++ b/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs @@ -8,6 +8,7 @@ using System.Collections.Concurrent; using System.Text; using System.Threading; using System.Threading.Tasks; +using MQTTnet.Implementations; namespace MQTTnet.Extensions.Rpc { @@ -88,8 +89,8 @@ namespace MQTTnet.Extensions.Rpc try { - var tcs = new TaskCompletionSource(); - if (!_waitingCalls.TryAdd(responseTopic, tcs)) + var promise = new TaskCompletionSource(); + if (!_waitingCalls.TryAdd(responseTopic, promise)) { throw new InvalidOperationException(); } @@ -102,15 +103,15 @@ namespace MQTTnet.Extensions.Rpc { linkedCts.Token.Register(() => { - if (!tcs.Task.IsCompleted && !tcs.Task.IsFaulted && !tcs.Task.IsCanceled) + if (!promise.Task.IsCompleted && !promise.Task.IsFaulted && !promise.Task.IsCanceled) { - tcs.TrySetCanceled(); + promise.TrySetCanceled(); } }); try { - var result = await tcs.Task.ConfigureAwait(false); + var result = await promise.Task.ConfigureAwait(false); timeoutCts.Cancel(false); return result; } @@ -136,14 +137,17 @@ namespace MQTTnet.Extensions.Rpc Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs) { - if (!_waitingCalls.TryRemove(eventArgs.ApplicationMessage.Topic, out var tcs)) + if (!_waitingCalls.TryRemove(eventArgs.ApplicationMessage.Topic, out var promise)) { - return Task.FromResult(0); + return PlatformAbstractionLayer.CompletedTask; } - tcs.TrySetResult(eventArgs.ApplicationMessage.Payload); + promise.TrySetResult(eventArgs.ApplicationMessage.Payload); - return Task.FromResult(0); + // Set this message to handled to that other code can avoid execution etc. + eventArgs.IsHandled = true; + + return PlatformAbstractionLayer.CompletedTask; } public void Dispose() diff --git a/Source/MQTTnet.Extensions.Rpc/Options/TopicGeneration/TopicGenerationContext.cs b/Source/MQTTnet.Extensions.Rpc/Options/TopicGeneration/TopicGenerationContext.cs index cd82c52a..39110bb4 100644 --- a/Source/MQTTnet.Extensions.Rpc/Options/TopicGeneration/TopicGenerationContext.cs +++ b/Source/MQTTnet.Extensions.Rpc/Options/TopicGeneration/TopicGenerationContext.cs @@ -7,6 +7,14 @@ namespace MQTTnet.Extensions.Rpc.Options.TopicGeneration { public string MethodName { get; set; } + /// + /// Gets or sets the quality of service level. + /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message that defines the guarantee of delivery for a specific message. + /// There are 3 QoS levels in MQTT: + /// - At most once (0): Message gets delivered no time, once or multiple times. + /// - At least once (1): Message gets delivered at least once (one time or more often). + /// - Exactly once (2): Message gets delivered exactly once (It's ensured that the message only comes once). + /// public MqttQualityOfServiceLevel QualityOfServiceLevel { get; set; } public IMqttClient MqttClient { get; set; } diff --git a/Source/MQTTnet.Extensions.Rpc/RpcAwareApplicationMessageReceivedHandler.cs b/Source/MQTTnet.Extensions.Rpc/RpcAwareApplicationMessageReceivedHandler.cs index d7b75fc9..5d43eb68 100644 --- a/Source/MQTTnet.Extensions.Rpc/RpcAwareApplicationMessageReceivedHandler.cs +++ b/Source/MQTTnet.Extensions.Rpc/RpcAwareApplicationMessageReceivedHandler.cs @@ -18,14 +18,15 @@ namespace MQTTnet.Extensions.Rpc public IMqttApplicationMessageReceivedHandler OriginalHandler { get; } - public Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs) + public async Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs) { + // First try to check if there is a pending RPC call! + await _handleReceivedApplicationMessageAsync(eventArgs).ConfigureAwait(false); + if (OriginalHandler != null) { - return OriginalHandler.HandleApplicationMessageReceivedAsync(eventArgs); + await OriginalHandler.HandleApplicationMessageReceivedAsync(eventArgs).ConfigureAwait(false); } - - return _handleReceivedApplicationMessageAsync(eventArgs); } } } diff --git a/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttClientAdapterFactory.cs b/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttClientAdapterFactory.cs index 96f3c305..63826532 100644 --- a/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttClientAdapterFactory.cs +++ b/Source/MQTTnet.Extensions.WebSocket4Net/WebSocket4NetMqttClientAdapterFactory.cs @@ -7,7 +7,7 @@ using System; namespace MQTTnet.Extensions.WebSocket4Net { - public class WebSocket4NetMqttClientAdapterFactory : IMqttClientAdapterFactory + public sealed class WebSocket4NetMqttClientAdapterFactory : IMqttClientAdapterFactory { readonly IMqttNetLogger _logger; @@ -23,14 +23,22 @@ namespace MQTTnet.Extensions.WebSocket4Net switch (options.ChannelOptions) { case MqttClientTcpOptions _: - { - return new MqttChannelAdapter(new MqttTcpChannel(options), new MqttPacketFormatterAdapter(options.ProtocolVersion), _logger); - } + { + return new MqttChannelAdapter( + new MqttTcpChannel(options), + new MqttPacketFormatterAdapter(options.ProtocolVersion), + options.PacketInspector, + _logger); + } case MqttClientWebSocketOptions webSocketOptions: - { - return new MqttChannelAdapter(new WebSocket4NetMqttChannel(options, webSocketOptions), new MqttPacketFormatterAdapter(options.ProtocolVersion), _logger); - } + { + return new MqttChannelAdapter( + new WebSocket4NetMqttChannel(options, webSocketOptions), + new MqttPacketFormatterAdapter(options.ProtocolVersion), + options.PacketInspector, + _logger); + } default: { diff --git a/Source/MQTTnet.Server/MQTTnet.Server.csproj b/Source/MQTTnet.Server/MQTTnet.Server.csproj index 337a0636..3ea975cb 100644 --- a/Source/MQTTnet.Server/MQTTnet.Server.csproj +++ b/Source/MQTTnet.Server/MQTTnet.Server.csproj @@ -1,7 +1,7 @@ - netcoreapp3.1;net5.0 + net5.0 InProcess MQTTnet.Server MQTTnet.Server diff --git a/Source/MQTTnet/Adapter/MqttChannelAdapter.cs b/Source/MQTTnet/Adapter/MqttChannelAdapter.cs index 1b6bc068..8e3e8ddf 100644 --- a/Source/MQTTnet/Adapter/MqttChannelAdapter.cs +++ b/Source/MQTTnet/Adapter/MqttChannelAdapter.cs @@ -11,6 +11,7 @@ using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; +using MQTTnet.Diagnostics.PacketInspection; namespace MQTTnet.Adapter { @@ -19,26 +20,26 @@ namespace MQTTnet.Adapter const uint ErrorOperationAborted = 0x800703E3; const int ReadBufferSize = 4096; + readonly byte[] _singleByteBuffer = new byte[1]; + readonly byte[] _fixedHeaderBuffer = new byte[2]; + + readonly MqttPacketInspectorHandler _packetInspectorHandler; readonly IMqttNetScopedLogger _logger; readonly IMqttChannel _channel; - readonly MqttPacketReader _packetReader; - - readonly byte[] _fixedHeaderBuffer = new byte[2]; readonly AsyncLock _syncRoot = new AsyncLock(); long _bytesReceived; long _bytesSent; - public MqttChannelAdapter(IMqttChannel channel, MqttPacketFormatterAdapter packetFormatterAdapter, IMqttNetLogger logger) + public MqttChannelAdapter(IMqttChannel channel, MqttPacketFormatterAdapter packetFormatterAdapter, IMqttPacketInspector packetInspector, IMqttNetLogger logger) { - if (logger == null) throw new ArgumentNullException(nameof(logger)); - _channel = channel ?? throw new ArgumentNullException(nameof(channel)); PacketFormatterAdapter = packetFormatterAdapter ?? throw new ArgumentNullException(nameof(packetFormatterAdapter)); - _packetReader = new MqttPacketReader(_channel); + _packetInspectorHandler = new MqttPacketInspectorHandler(packetInspector, logger); + if (logger == null) throw new ArgumentNullException(nameof(logger)); _logger = logger.CreateScopedLogger(nameof(MqttChannelAdapter)); } @@ -124,6 +125,7 @@ namespace MQTTnet.Adapter try { var packetData = PacketFormatterAdapter.Encode(packet); + _packetInspectorHandler.BeginSendPacket(packetData); await _channel.WriteAsync(packetData.Array, packetData.Offset, packetData.Count, cancellationToken).ConfigureAwait(false); @@ -154,12 +156,16 @@ namespace MQTTnet.Adapter try { + _packetInspectorHandler.BeginReceivePacket(); + var receivedPacket = await ReceiveAsync(cancellationToken).ConfigureAwait(false); if (receivedPacket == null || cancellationToken.IsCancellationRequested) { return null; } + _packetInspectorHandler.EndReceivePacket(); + Interlocked.Add(ref _bytesSent, receivedPacket.TotalLength); if (PacketFormatterAdapter.ProtocolVersion == MqttProtocolVersion.Unknown) @@ -215,7 +221,12 @@ namespace MQTTnet.Adapter async Task ReceiveAsync(CancellationToken cancellationToken) { - var readFixedHeaderResult = await _packetReader.ReadFixedHeaderAsync(_fixedHeaderBuffer, cancellationToken).ConfigureAwait(false); + if (cancellationToken.IsCancellationRequested) + { + return null; + } + + var readFixedHeaderResult = await ReadFixedHeaderAsync(cancellationToken).ConfigureAwait(false); if (cancellationToken.IsCancellationRequested) { @@ -234,7 +245,7 @@ namespace MQTTnet.Adapter var fixedHeader = readFixedHeaderResult.FixedHeader; if (fixedHeader.RemainingLength == 0) { - return new ReceivedMqttPacket(fixedHeader.Flags, null, 2); + return new ReceivedMqttPacket(fixedHeader.Flags, new MqttPacketBodyReader(new byte[0], 0, 0), 2); } var bodyLength = fixedHeader.RemainingLength; @@ -266,6 +277,8 @@ namespace MQTTnet.Adapter bodyOffset += readBytes; } while (bodyOffset < bodyLength); + _packetInspectorHandler.FillReceiveBuffer(body); + var bodyReader = new MqttPacketBodyReader(body, 0, bodyLength); return new ReceivedMqttPacket(fixedHeader.Flags, bodyReader, fixedHeader.TotalLength); } @@ -275,11 +288,110 @@ namespace MQTTnet.Adapter } } + async Task ReadFixedHeaderAsync(CancellationToken cancellationToken) + { + // The MQTT fixed header contains 1 byte of flags and at least 1 byte for the remaining data length. + // So in all cases at least 2 bytes must be read for a complete MQTT packet. + var buffer = _fixedHeaderBuffer; + var totalBytesRead = 0; + + while (totalBytesRead < buffer.Length) + { + var bytesRead = await _channel.ReadAsync(buffer, totalBytesRead, buffer.Length - totalBytesRead, cancellationToken).ConfigureAwait(false); + + if (cancellationToken.IsCancellationRequested) + { + return null; + } + + if (bytesRead == 0) + { + return new ReadFixedHeaderResult + { + ConnectionClosed = true + }; + } + + totalBytesRead += bytesRead; + } + + _packetInspectorHandler.FillReceiveBuffer(buffer); + + var hasRemainingLength = buffer[1] != 0; + if (!hasRemainingLength) + { + return new ReadFixedHeaderResult + { + FixedHeader = new MqttFixedHeader(buffer[0], 0, totalBytesRead) + }; + } + + var bodyLength = await ReadBodyLengthAsync(buffer[1], cancellationToken).ConfigureAwait(false); + + if (!bodyLength.HasValue) + { + return new ReadFixedHeaderResult + { + ConnectionClosed = true + }; + } + + totalBytesRead += bodyLength.Value; + return new ReadFixedHeaderResult + { + FixedHeader = new MqttFixedHeader(buffer[0], bodyLength.Value, totalBytesRead) + }; + } + + async Task ReadBodyLengthAsync(byte initialEncodedByte, CancellationToken cancellationToken) + { + var offset = 0; + var multiplier = 128; + var value = initialEncodedByte & 127; + int encodedByte = initialEncodedByte; + + while ((encodedByte & 128) != 0) + { + offset++; + if (offset > 3) + { + throw new MqttProtocolViolationException("Remaining length is invalid."); + } + + if (cancellationToken.IsCancellationRequested) + { + return null; + } + + var readCount = await _channel.ReadAsync(_singleByteBuffer, 0, 1, cancellationToken).ConfigureAwait(false); + + if (cancellationToken.IsCancellationRequested) + { + return null; + } + + if (readCount == 0) + { + return null; + } + + _packetInspectorHandler.FillReceiveBuffer(_singleByteBuffer); + + encodedByte = _singleByteBuffer[0]; + + value += (encodedByte & 127) * multiplier; + multiplier *= 128; + } + + return value; + } + static bool IsWrappedException(Exception exception) { return exception is OperationCanceledException || exception is MqttCommunicationTimedOutException || - exception is MqttCommunicationException; + exception is MqttCommunicationException || + exception is MqttProtocolViolationException; } static void WrapAndThrowException(Exception exception) @@ -295,7 +407,7 @@ namespace MQTTnet.Adapter { throw new OperationCanceledException(); } - + if (socketException.SocketErrorCode == SocketError.ConnectionAborted) { throw new MqttCommunicationException(socketException); diff --git a/Source/MQTTnet/Adapter/MqttConnectingFailedException.cs b/Source/MQTTnet/Adapter/MqttConnectingFailedException.cs index ab49d934..447aaa69 100644 --- a/Source/MQTTnet/Adapter/MqttConnectingFailedException.cs +++ b/Source/MQTTnet/Adapter/MqttConnectingFailedException.cs @@ -1,17 +1,19 @@ -using MQTTnet.Client.Connecting; +using System; +using MQTTnet.Client.Connecting; using MQTTnet.Exceptions; namespace MQTTnet.Adapter { - public class MqttConnectingFailedException : MqttCommunicationException + public sealed class MqttConnectingFailedException : MqttCommunicationException { - public MqttConnectingFailedException(MqttClientAuthenticateResult result) - : base($"Connecting with MQTT server failed ({result.ResultCode.ToString()}).") + public MqttConnectingFailedException(string message, Exception innerException, MqttClientAuthenticateResult authenticateResult) + : base(message, innerException) { - Result = result; + Result = authenticateResult; } public MqttClientAuthenticateResult Result { get; } - public MqttClientConnectResultCode ResultCode => Result.ResultCode; + + public MqttClientConnectResultCode ResultCode => Result?.ResultCode ?? MqttClientConnectResultCode.UnspecifiedError; } } diff --git a/Source/MQTTnet/Adapter/MqttPacketInspectorHandler.cs b/Source/MQTTnet/Adapter/MqttPacketInspectorHandler.cs new file mode 100644 index 00000000..f8048d91 --- /dev/null +++ b/Source/MQTTnet/Adapter/MqttPacketInspectorHandler.cs @@ -0,0 +1,84 @@ +using System; +using System.IO; +using System.Linq; +using MQTTnet.Diagnostics; +using MQTTnet.Diagnostics.PacketInspection; + +namespace MQTTnet.Adapter +{ + public sealed class MqttPacketInspectorHandler + { + readonly MemoryStream _receivedPacketBuffer; + readonly IMqttPacketInspector _packetInspector; + readonly IMqttNetScopedLogger _logger; + + public MqttPacketInspectorHandler(IMqttPacketInspector packetInspector, IMqttNetLogger logger) + { + _packetInspector = packetInspector; + + if (packetInspector != null) + { + _receivedPacketBuffer = new MemoryStream(); + } + + if (logger == null) throw new ArgumentNullException(nameof(logger)); + _logger = logger.CreateScopedLogger(nameof(MqttPacketInspectorHandler)); + } + + public void BeginReceivePacket() + { + _receivedPacketBuffer?.SetLength(0); + } + + public void EndReceivePacket() + { + if (_packetInspector == null) + { + return; + } + + var buffer = _receivedPacketBuffer.ToArray(); + _receivedPacketBuffer.SetLength(0); + + InspectPacket(buffer, MqttPacketFlowDirection.Inbound); + } + + public void BeginSendPacket(ArraySegment buffer) + { + if (_packetInspector == null) + { + return; + } + + // Create a copy of the actual packet so that the inspector gets no access + // to the internal buffers. This is waste of memory but this feature is only + // intended for debugging etc. so that this is OK. + var bufferCopy = buffer.ToArray(); + + InspectPacket(bufferCopy, MqttPacketFlowDirection.Outbound); + } + + public void FillReceiveBuffer(byte[] buffer) + { + _receivedPacketBuffer?.Write(buffer, 0, buffer.Length); + } + + void InspectPacket(byte[] buffer, MqttPacketFlowDirection direction) + { + try + { + var context = new ProcessMqttPacketContext + { + Buffer = buffer, + Direction = direction + }; + + _packetInspector.ProcessMqttPacket(context); + } + catch (Exception exception) + { + _logger.Error(exception, "Error while inspecting packet."); + } + } + } +} \ No newline at end of file diff --git a/Source/MQTTnet/Adapter/ReceivedMqttPacket.cs b/Source/MQTTnet/Adapter/ReceivedMqttPacket.cs index 783f1d82..4a3c9314 100644 --- a/Source/MQTTnet/Adapter/ReceivedMqttPacket.cs +++ b/Source/MQTTnet/Adapter/ReceivedMqttPacket.cs @@ -1,19 +1,20 @@ -using MQTTnet.Formatter; +using System; +using MQTTnet.Formatter; namespace MQTTnet.Adapter { public sealed class ReceivedMqttPacket { - public ReceivedMqttPacket(byte fixedHeader, IMqttPacketBodyReader body, int totalLength) + public ReceivedMqttPacket(byte fixedHeader, IMqttPacketBodyReader bodyReader, int totalLength) { FixedHeader = fixedHeader; - Body = body; + BodyReader = bodyReader ?? throw new ArgumentNullException(nameof(bodyReader)); TotalLength = totalLength; } public byte FixedHeader { get; } - public IMqttPacketBodyReader Body { get; } + public IMqttPacketBodyReader BodyReader { get; } public int TotalLength { get; } } diff --git a/Source/MQTTnet/Client/Connecting/MqttClientAuthenticateResult.cs b/Source/MQTTnet/Client/Connecting/MqttClientAuthenticateResult.cs index 7419fae0..ecb1293c 100644 --- a/Source/MQTTnet/Client/Connecting/MqttClientAuthenticateResult.cs +++ b/Source/MQTTnet/Client/Connecting/MqttClientAuthenticateResult.cs @@ -7,6 +7,10 @@ namespace MQTTnet.Client.Connecting // TODO: Consider renaming this to _MqttClientConnectResult_ public class MqttClientAuthenticateResult { + /// + /// Gets or sets the result code. + /// Hint: MQTT 5 feature only. + /// public MqttClientConnectResultCode ResultCode { get; set; } public bool IsSessionPresent { get; set; } @@ -17,18 +21,34 @@ namespace MQTTnet.Client.Connecting public string AssignedClientIdentifier { get; set; } + /// + /// Gets or sets the authentication method. + /// Hint: MQTT 5 feature only. + /// public string AuthenticationMethod { get; set; } + /// + /// Gets or sets the authentication data. + /// Hint: MQTT 5 feature only. + /// public byte[] AuthenticationData { get; set; } public uint? MaximumPacketSize { get; set; } + /// + /// Gets or sets the reason string. + /// Hint: MQTT 5 feature only. + /// public string ReasonString { get; set; } public ushort? ReceiveMaximum { get; set; } public MqttQualityOfServiceLevel MaximumQoS { get; set; } + /// + /// Gets or sets the response information. + /// Hint: MQTT 5 feature only. + /// public string ResponseInformation { get; set; } public ushort? TopicAliasMaximum { get; set; } @@ -39,10 +59,25 @@ namespace MQTTnet.Client.Connecting public uint? SessionExpiryInterval { get; set; } + /// + /// Gets or sets a value indicating whether the subscription identifiers are available or not. + /// Hint: MQTT 5 feature only. + /// public bool? SubscriptionIdentifiersAvailable { get; set; } + /// + /// Gets or sets a value indicating whether the shared subscriptions are available or not. + /// Hint: MQTT 5 feature only. + /// public bool? SharedSubscriptionAvailable { get; set; } + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Client/Connecting/MqttClientConnectedEventArgs.cs b/Source/MQTTnet/Client/Connecting/MqttClientConnectedEventArgs.cs index e7f97b9e..02cd47f5 100644 --- a/Source/MQTTnet/Client/Connecting/MqttClientConnectedEventArgs.cs +++ b/Source/MQTTnet/Client/Connecting/MqttClientConnectedEventArgs.cs @@ -9,6 +9,10 @@ namespace MQTTnet.Client.Connecting AuthenticateResult = authenticateResult ?? throw new ArgumentNullException(nameof(authenticateResult)); } + /// + /// Gets the authentication result. + /// Hint: MQTT 5 feature only. + /// public MqttClientAuthenticateResult AuthenticateResult { get; } } } diff --git a/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectOptions.cs b/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectOptions.cs index 995806e7..7f8c6441 100644 --- a/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectOptions.cs +++ b/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectOptions.cs @@ -1,9 +1,17 @@ namespace MQTTnet.Client.Disconnecting { - public class MqttClientDisconnectOptions + public sealed class MqttClientDisconnectOptions { + /// + /// Gets or sets the reason code. + /// Hint: MQTT 5 feature only. + /// public MqttClientDisconnectReason ReasonCode { get; set; } = MqttClientDisconnectReason.NormalDisconnection; + /// + /// Gets or sets the reason string. + /// Hint: MQTT 5 feature only. + /// public string ReasonString { get; set; } } } diff --git a/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectReason.cs b/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectReason.cs index e1ea30d7..cce2377f 100644 --- a/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectReason.cs +++ b/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectReason.cs @@ -12,7 +12,7 @@ ServerBusy = 137, ServerShuttingDown = 139, BadAuthenticationMethod = 140, - KeepaliveTimeout = 141, + KeepAliveTimeout = 141, SessionTakenOver = 142, TopicFilterInvalid = 143, TopicNameInvalid = 144, diff --git a/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectedEventArgs.cs b/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectedEventArgs.cs index 5e2317cf..932f009c 100644 --- a/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectedEventArgs.cs +++ b/Source/MQTTnet/Client/Disconnecting/MqttClientDisconnectedEventArgs.cs @@ -19,8 +19,16 @@ namespace MQTTnet.Client.Disconnecting public Exception Exception { get; } + /// + /// Gets the authentication result. + /// Hint: MQTT 5 feature only. + /// public MqttClientAuthenticateResult AuthenticateResult { get; } + /// + /// Gets or sets the reason. + /// Hint: MQTT 5 feature only. + /// public MqttClientDisconnectReason Reason { get; set; } [Obsolete("Please use 'Reason' instead. This property will be removed in the future!")] diff --git a/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs index 9e88f039..082e9a8d 100644 --- a/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs +++ b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs @@ -20,14 +20,37 @@ namespace MQTTnet.Client.ExtendedAuthenticationExchange Client = client ?? throw new ArgumentNullException(nameof(client)); } + /// + /// Gets the reason code. + /// Hint: MQTT 5 feature only. + /// public MqttAuthenticateReasonCode ReasonCode { get; } + /// + /// Gets the reason string. + /// Hint: MQTT 5 feature only. + /// public string ReasonString { get; } + /// + /// Gets the authentication method. + /// Hint: MQTT 5 feature only. + /// public string AuthenticationMethod { get; } + /// + /// Gets the authentication data. + /// Hint: MQTT 5 feature only. + /// public byte[] AuthenticationData { get; } + /// + /// Gets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties { get; } public IMqttClient Client { get; } diff --git a/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeData.cs b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeData.cs index 8a49b08a..29f38217 100644 --- a/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeData.cs +++ b/Source/MQTTnet/Client/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeData.cs @@ -6,12 +6,33 @@ namespace MQTTnet.Client.ExtendedAuthenticationExchange { public class MqttExtendedAuthenticationExchangeData { + /// + /// Gets or sets the reason code. + /// Hint: MQTT 5 feature only. + /// public MqttAuthenticateReasonCode ReasonCode { get; set; } + /// + /// Gets or sets the reason string. + /// Hint: MQTT 5 feature only. + /// public string ReasonString { get; set; } + /// + /// Gets or sets the authentication data. + /// Authentication data is binary information used to transmit multiple iterations of cryptographic secrets of protocol steps. + /// The content of the authentication data is highly dependent on the specific implementation of the authentication method. + /// Hint: MQTT 5 feature only. + /// public byte[] AuthenticationData { get; set; } + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties { get; } } } diff --git a/Source/MQTTnet/Client/IMqttClient.cs b/Source/MQTTnet/Client/IMqttClient.cs index 58cfa0c1..394ec8dc 100644 --- a/Source/MQTTnet/Client/IMqttClient.cs +++ b/Source/MQTTnet/Client/IMqttClient.cs @@ -13,18 +13,38 @@ namespace MQTTnet.Client public interface IMqttClient : IApplicationMessageReceiver, IApplicationMessagePublisher, IDisposable { bool IsConnected { get; } + IMqttClientOptions Options { get; } + /// + /// Gets or sets the connected handler that is fired after the client has connected to the server successfully. + /// Hint: Initialize handlers before you connect the client to avoid issues. + /// IMqttClientConnectedHandler ConnectedHandler { get; set; } + /// + /// Gets or sets the disconnected handler that is fired after the client has disconnected from the server. + /// Hint: Initialize handlers before you connect the client to avoid issues. + /// IMqttClientDisconnectedHandler DisconnectedHandler { get; set; } Task ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken); + Task DisconnectAsync(MqttClientDisconnectOptions options, CancellationToken cancellationToken); + Task PingAsync(CancellationToken cancellationToken); + /// + /// Sends extended authentication data. + /// Hint: MQTT 5 feature only. + /// + /// The extended data. + /// A cancellation token to stop the task. + /// A representing any asynchronous operation. Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticationExchangeData data, CancellationToken cancellationToken); + Task SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken); + Task UnsubscribeAsync(MqttClientUnsubscribeOptions options, CancellationToken cancellationToken); } } \ No newline at end of file diff --git a/Source/MQTTnet/Client/IMqttClientFactory.cs b/Source/MQTTnet/Client/IMqttClientFactory.cs index b256e742..4bbb79a3 100644 --- a/Source/MQTTnet/Client/IMqttClientFactory.cs +++ b/Source/MQTTnet/Client/IMqttClientFactory.cs @@ -1,5 +1,4 @@ -using System; -using MQTTnet.Adapter; +using MQTTnet.Adapter; using MQTTnet.Diagnostics; using MQTTnet.LowLevelClient; diff --git a/Source/MQTTnet/Client/MqttClient.cs b/Source/MQTTnet/Client/MqttClient.cs index c5f11af7..16cb334a 100644 --- a/Source/MQTTnet/Client/MqttClient.cs +++ b/Source/MQTTnet/Client/MqttClient.cs @@ -167,7 +167,7 @@ namespace MQTTnet.Client public Task PingAsync(CancellationToken cancellationToken) { - return SendAndReceiveAsync(new MqttPingReqPacket(), cancellationToken); + return SendAndReceiveAsync(MqttPingReqPacket.Instance, cancellationToken); } public Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticationExchangeData data, CancellationToken cancellationToken) @@ -280,16 +280,25 @@ namespace MQTTnet.Client async Task AuthenticateAsync(IMqttChannelAdapter channelAdapter, MqttApplicationMessage willApplicationMessage, CancellationToken cancellationToken) { - var connectPacket = channelAdapter.PacketFormatterAdapter.DataConverter.CreateConnectPacket( - willApplicationMessage, - Options); + MqttClientAuthenticateResult result; - var connAckPacket = await SendAndReceiveAsync(connectPacket, cancellationToken).ConfigureAwait(false); - var result = channelAdapter.PacketFormatterAdapter.DataConverter.CreateClientConnectResult(connAckPacket); + try + { + var connectPacket = channelAdapter.PacketFormatterAdapter.DataConverter.CreateConnectPacket( + willApplicationMessage, + Options); + + var connAckPacket = await SendAndReceiveAsync(connectPacket, cancellationToken).ConfigureAwait(false); + result = channelAdapter.PacketFormatterAdapter.DataConverter.CreateClientConnectResult(connAckPacket); + } + catch (Exception exception) + { + throw new MqttConnectingFailedException($"Error while authenticating. {exception.Message}", exception, null); + } if (result.ResultCode != MqttClientConnectResultCode.Success) { - throw new MqttConnectingFailedException(result); + throw new MqttConnectingFailedException($"Connecting with MQTT server failed ({result.ResultCode}).", null, result); } _logger.Verbose("Authenticated MQTT connection with server established."); @@ -404,10 +413,10 @@ namespace MQTTnet.Client _lastSentAtTicks = Environment.TickCount; await _adapter.SendPacketAsync(requestPacket, cancellationToken).ConfigureAwait(false); } - catch (Exception e) + catch (Exception exception) { - _logger.Warning(e, "Error when sending request packet ({0}).", requestPacket.GetType().Name); - packetAwaiter.Cancel(); + _logger.Warning(exception, "Error when sending request packet ({0}).", requestPacket.GetType().Name); + packetAwaiter.Fail(exception); } try @@ -630,7 +639,7 @@ namespace MQTTnet.Client } var publishPacket = publishPacketDequeueResult.Item; - var publishResult = await HandleReceivedApplicationMessageAsync(publishPacket); + var eventArgs = await HandleReceivedApplicationMessageAsync(publishPacket); if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce) { @@ -638,28 +647,18 @@ namespace MQTTnet.Client } else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce) { - if (publishResult.ProcessingSucceeded) + if (!eventArgs.ProcessingFailed) { - var pubAckPacket = new MqttPubAckPacket - { - PacketIdentifier = publishPacket.PacketIdentifier, - ReasonCode = MqttPubAckReasonCode.Success - }; - - await SendResponseForReceivedPublishPacket(publishResult, pubAckPacket, cancellationToken).ConfigureAwait(false); + var pubAckPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubAckPacket(publishPacket, eventArgs.ReasonCode); + await SendResponseForReceivedPublishPacket(eventArgs, pubAckPacket, cancellationToken).ConfigureAwait(false); } } else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce) { - if (publishResult.ProcessingSucceeded) + if (!eventArgs.ProcessingFailed) { - var pubRecPacket = new MqttPubRecPacket - { - PacketIdentifier = publishPacket.PacketIdentifier, - ReasonCode = MqttPubRecReasonCode.Success - }; - - await SendResponseForReceivedPublishPacket(publishResult, pubRecPacket, cancellationToken).ConfigureAwait(false); + var pubRecPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubRecPacket(publishPacket, eventArgs.ReasonCode); + await SendResponseForReceivedPublishPacket(eventArgs, pubRecPacket, cancellationToken).ConfigureAwait(false); } } else @@ -677,15 +676,15 @@ namespace MQTTnet.Client } } - async Task SendResponseForReceivedPublishPacket(ReceivedApplicationMessageResult publishResult, MqttBasePacket resultPacket, CancellationToken cancellationToken) + async Task SendResponseForReceivedPublishPacket(MqttApplicationMessageReceivedEventArgs eventArgs, MqttBasePacket resultPacket, CancellationToken cancellationToken) { - if (publishResult.PendingTask == null) + if (eventArgs.PendingTask == null) { await SendAsync(resultPacket, cancellationToken).ConfigureAwait(false); } else { - _ = publishResult.PendingTask.ContinueWith(async x => + _ = eventArgs.PendingTask.ContinueWith(async x => { try { @@ -706,13 +705,10 @@ namespace MQTTnet.Client { if (!_packetDispatcher.TryDispatch(pubRecPacket)) { - // The packet is unknown. Probably due to a restart of the client. + // The packet is unknown. Probably due to a restart of the client. // So wen send this to the server to trigger a full resend of the message. - return SendAsync(new MqttPubRelPacket - { - PacketIdentifier = pubRecPacket.PacketIdentifier, - ReasonCode = MqttPubRelReasonCode.PacketIdentifierNotFound - }, cancellationToken); + var pubRelPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubRelPacket(pubRecPacket, MqttApplicationMessageReceivedReasonCode.PacketIdentifierNotFound); + return SendAsync(pubRelPacket, cancellationToken); } return PlatformAbstractionLayer.CompletedTask; @@ -720,11 +716,8 @@ namespace MQTTnet.Client Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken) { - return SendAsync(new MqttPubCompPacket - { - PacketIdentifier = pubRelPacket.PacketIdentifier, - ReasonCode = MqttPubCompReasonCode.Success - }, cancellationToken); + var pubCompPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubCompPacket(pubRelPacket, MqttApplicationMessageReceivedReasonCode.Success); + return SendAsync(pubCompPacket, cancellationToken); } Task ProcessReceivedDisconnectPacket(MqttDisconnectPacket disconnectPacket) @@ -757,14 +750,14 @@ namespace MQTTnet.Client { // No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier] await SendAsync(publishPacket, cancellationToken).ConfigureAwait(false); - return _adapter.PacketFormatterAdapter.DataConverter.CreatePublishResult(null); + return _adapter.PacketFormatterAdapter.DataConverter.CreateClientPublishResult(null); } async Task PublishAtLeastOnceAsync(MqttPublishPacket publishPacket, CancellationToken cancellationToken) { publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier(); var response = await SendAndReceiveAsync(publishPacket, cancellationToken).ConfigureAwait(false); - return _adapter.PacketFormatterAdapter.DataConverter.CreatePublishResult(response); + return _adapter.PacketFormatterAdapter.DataConverter.CreateClientPublishResult(response); } async Task PublishExactlyOnceAsync(MqttPublishPacket publishPacket, CancellationToken cancellationToken) @@ -773,42 +766,25 @@ namespace MQTTnet.Client var pubRecPacket = await SendAndReceiveAsync(publishPacket, cancellationToken).ConfigureAwait(false); - var pubRelPacket = new MqttPubRelPacket - { - PacketIdentifier = publishPacket.PacketIdentifier, - ReasonCode = MqttPubRelReasonCode.Success - }; - + var pubRelPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubRelPacket(pubRecPacket, MqttApplicationMessageReceivedReasonCode.Success); + var pubCompPacket = await SendAndReceiveAsync(pubRelPacket, cancellationToken).ConfigureAwait(false); - return _adapter.PacketFormatterAdapter.DataConverter.CreatePublishResult(pubRecPacket, pubCompPacket); + return _adapter.PacketFormatterAdapter.DataConverter.CreateClientPublishResult(pubRecPacket, pubCompPacket); } - struct ReceivedApplicationMessageResult - { - public readonly bool ProcessingSucceeded; - public readonly Task PendingTask; - - public ReceivedApplicationMessageResult(bool processingSucceeded, Task pendingTask) - { - this.ProcessingSucceeded = processingSucceeded; - this.PendingTask = pendingTask; - } - } - - async Task HandleReceivedApplicationMessageAsync(MqttPublishPacket publishPacket) + async Task HandleReceivedApplicationMessageAsync(MqttPublishPacket publishPacket) { var applicationMessage = _adapter.PacketFormatterAdapter.DataConverter.CreateApplicationMessage(publishPacket); + var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options.ClientId, applicationMessage); var handler = ApplicationMessageReceivedHandler; if (handler != null) { - var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options.ClientId, applicationMessage); await handler.HandleApplicationMessageReceivedAsync(eventArgs).ConfigureAwait(false); - return new ReceivedApplicationMessageResult(!eventArgs.ProcessingFailed, eventArgs.PendingTask); } - return new ReceivedApplicationMessageResult(true, null); + return eventArgs; } async Task WaitForTaskAsync(Task task, Task sender) diff --git a/Source/MQTTnet/Client/MqttClientExtensions.cs b/Source/MQTTnet/Client/MqttClientExtensions.cs index 2408a14a..e9fd4361 100644 --- a/Source/MQTTnet/Client/MqttClientExtensions.cs +++ b/Source/MQTTnet/Client/MqttClientExtensions.cs @@ -128,7 +128,21 @@ namespace MQTTnet.Client { if (client == null) throw new ArgumentNullException(nameof(client)); - return client.DisconnectAsync(new MqttClientDisconnectOptions()); + return client.DisconnectAsync(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 DisconnectAsync(this IMqttClient client, CancellationToken cancellationToken) + { + if (client == null) throw new ArgumentNullException(nameof(client)); + + return client.DisconnectAsync(new MqttClientDisconnectOptions(), cancellationToken); } public static Task SubscribeAsync(this IMqttClient client, params MqttTopicFilter[] topicFilters) @@ -176,13 +190,6 @@ namespace MQTTnet.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)); diff --git a/Source/MQTTnet/Client/Options/IMqttClientOptions.cs b/Source/MQTTnet/Client/Options/IMqttClientOptions.cs index e46162ae..1ef462a1 100644 --- a/Source/MQTTnet/Client/Options/IMqttClientOptions.cs +++ b/Source/MQTTnet/Client/Options/IMqttClientOptions.cs @@ -3,31 +3,112 @@ using MQTTnet.Formatter; using MQTTnet.Packets; using System; using System.Collections.Generic; +using MQTTnet.Diagnostics.PacketInspection; namespace MQTTnet.Client.Options { public interface IMqttClientOptions { + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// string ClientId { get; } + + /// + /// Gets a value indicating whether clean sessions are used or not. + /// When a client connects to a broker it can connect using either a non persistent connection (clean session) or a persistent connection. + /// With a non persistent connection the broker doesn't store any subscription information or undelivered messages for the client. + /// This mode is ideal when the client only publishes messages. + /// It can also connect as a durable client using a persistent connection. + /// In this mode, the broker will store subscription information, and undelivered messages for the client. + /// bool CleanSession { get; } + IMqttClientCredentials Credentials { get; } + IMqttExtendedAuthenticationExchangeHandler ExtendedAuthenticationExchangeHandler { get; } + MqttProtocolVersion ProtocolVersion { get; } + IMqttClientChannelOptions ChannelOptions { get; } TimeSpan CommunicationTimeout { get; } + + /// + /// Gets the keep alive period. + /// The connection is normally left open by the client so that is can send and receive data at any time. + /// If no data flows over an open connection for a certain time period then the client will generate a PINGREQ and expect to receive a PINGRESP from the broker. + /// This message exchange confirms that the connection is open and working. + /// This period is known as the keep alive period. + /// TimeSpan KeepAlivePeriod { get; } + + /// + /// Gets the last will message. + /// In MQTT, you use the last will message feature to notify other clients about an ungracefully disconnected client. + /// MqttApplicationMessage WillMessage { get; } + + /// + /// Gets the will delay interval. + /// This is the time between the client disconnect and the time the will message will be sent. + /// uint? WillDelayInterval { get; } + /// + /// Gets the authentication method. + /// Hint: MQTT 5 feature only. + /// string AuthenticationMethod { get; } + + /// + /// Gets the authentication data. + /// Hint: MQTT 5 feature only. + /// byte[] AuthenticationData { get; } + uint? MaximumPacketSize { get; } + + /// + /// Gets the receive maximum. + /// This gives the maximum length of the receive messages. + /// ushort? ReceiveMaximum { get; } + + /// + /// Gets the request problem information. + /// Hint: MQTT 5 feature only. + /// bool? RequestProblemInformation { get; } + + /// + /// Gets the request response information. + /// Hint: MQTT 5 feature only. + /// bool? RequestResponseInformation { get; } + + /// + /// Gets the session expiry interval. + /// The time after a session expires when it's not actively used. + /// uint? SessionExpiryInterval { get; } + + /// + /// Gets the topic alias maximum. + /// This gives the maximum length of the topic alias. + /// ushort? TopicAliasMaximum { get; } + + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// List UserProperties { get; set; } + + IMqttPacketInspector PacketInspector { get; set; } } } \ No newline at end of file diff --git a/Source/MQTTnet/Client/Options/MqttClientOptions.cs b/Source/MQTTnet/Client/Options/MqttClientOptions.cs index 79c6c702..d67410a9 100644 --- a/Source/MQTTnet/Client/Options/MqttClientOptions.cs +++ b/Source/MQTTnet/Client/Options/MqttClientOptions.cs @@ -3,33 +3,112 @@ using MQTTnet.Formatter; using MQTTnet.Packets; using System; using System.Collections.Generic; +using MQTTnet.Diagnostics.PacketInspection; namespace MQTTnet.Client.Options { public class MqttClientOptions : IMqttClientOptions { + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; set; } = Guid.NewGuid().ToString("N"); + + /// + /// Gets or sets a value indicating whether clean sessions are used or not. + /// When a client connects to a broker it can connect using either a non persistent connection (clean session) or a persistent connection. + /// With a non persistent connection the broker doesn't store any subscription information or undelivered messages for the client. + /// This mode is ideal when the client only publishes messages. + /// It can also connect as a durable client using a persistent connection. + /// In this mode, the broker will store subscription information, and undelivered messages for the client. + /// 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; } + public TimeSpan CommunicationTimeout { get; set; } = TimeSpan.FromSeconds(10); + + /// + /// Gets or sets the keep alive period. + /// The connection is normally left open by the client so that is can send and receive data at any time. + /// If no data flows over an open connection for a certain time period then the client will generate a PINGREQ and expect to receive a PINGRESP from the broker. + /// This message exchange confirms that the connection is open and working. + /// This period is known as the keep alive period. + /// public TimeSpan KeepAlivePeriod { get; set; } = TimeSpan.FromSeconds(15); + /// + /// Gets or sets the last will message. + /// In MQTT, you use the last will message feature to notify other clients about an ungracefully disconnected client. + /// public MqttApplicationMessage WillMessage { get; set; } + + /// + /// Gets or sets the will delay interval. + /// This is the time between the client disconnect and the time the will message will be sent. + /// public uint? WillDelayInterval { get; set; } + /// + /// Gets or sets the authentication method. + /// Hint: MQTT 5 feature only. + /// public string AuthenticationMethod { get; set; } + + /// + /// Gets or sets the authentication data. + /// Hint: MQTT 5 feature only. + /// public byte[] AuthenticationData { get; set; } public uint? MaximumPacketSize { get; set; } + + /// + /// Gets or sets the receive maximum. + /// This gives the maximum length of the receive messages. + /// public ushort? ReceiveMaximum { get; set; } + + /// + /// Gets or sets the request problem information. + /// Hint: MQTT 5 feature only. + /// public bool? RequestProblemInformation { get; set; } + + /// + /// Gets or sets the request response information. + /// Hint: MQTT 5 feature only. + /// public bool? RequestResponseInformation { get; set; } + + /// + /// Gets or sets the session expiry interval. + /// The time after a session expires when it's not actively used. + /// public uint? SessionExpiryInterval { get; set; } + + /// + /// Gets or sets the topic alias maximum. + /// This gives the maximum length of the topic alias. + /// public ushort? TopicAliasMaximum { get; set; } + + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties { get; set; } + + public IMqttPacketInspector PacketInspector { get; set; } } } diff --git a/Source/MQTTnet/Client/Options/MqttClientOptionsBuilder.cs b/Source/MQTTnet/Client/Options/MqttClientOptionsBuilder.cs index 68d1aa3f..c12c468e 100644 --- a/Source/MQTTnet/Client/Options/MqttClientOptionsBuilder.cs +++ b/Source/MQTTnet/Client/Options/MqttClientOptionsBuilder.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using MQTTnet.Diagnostics.PacketInspection; namespace MQTTnet.Client.Options { @@ -256,6 +257,12 @@ namespace MQTTnet.Client.Options return this; } + public MqttClientOptionsBuilder WithPacketInspector(IMqttPacketInspector packetInspector) + { + _options.PacketInspector = packetInspector; + return this; + } + public IMqttClientOptions Build() { if (_tcpOptions == null && _webSocketOptions == null) diff --git a/Source/MQTTnet/Client/Publishing/MqttClientPublishResult.cs b/Source/MQTTnet/Client/Publishing/MqttClientPublishResult.cs index 15035ec0..429f130a 100644 --- a/Source/MQTTnet/Client/Publishing/MqttClientPublishResult.cs +++ b/Source/MQTTnet/Client/Publishing/MqttClientPublishResult.cs @@ -8,10 +8,25 @@ namespace MQTTnet.Client.Publishing { public ushort? PacketIdentifier { get; set; } + /// + /// Gets or sets the reason code. + /// Hint: MQTT 5 feature only. + /// public MqttClientPublishReasonCode ReasonCode { get; set; } = MqttClientPublishReasonCode.Success; + /// + /// Gets or sets the reason string. + /// Hint: MQTT 5 feature only. + /// public string ReasonString { get; set; } + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptions.cs b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptions.cs index 42c38e11..2c43c42a 100644 --- a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptions.cs +++ b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptions.cs @@ -5,10 +5,28 @@ namespace MQTTnet.Client.Subscribing { public class MqttClientSubscribeOptions { + /// + /// Gets or sets a list of topic filters the client wants to subscribe to. + /// Topic filters can include regular topics or wild cards. + /// public List TopicFilters { get; set; } = new List(); + /// + /// Gets or sets the subscription identifier. + /// The client can specify a subscription identifier when subscribing. + /// The broker will establish and store the mapping relationship between this subscription and subscription identifier when successfully create or modify subscription. + /// The broker will return the subscription identifier associated with this PUBLISH packet and the PUBLISH packet to the client when need to forward PUBLISH packets matching this subscription to this client. + /// Hint: MQTT 5 feature only. + /// public uint? SubscriptionIdentifier { get; set; } + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties { get; set; } } } diff --git a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptionsBuilder.cs b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptionsBuilder.cs index 97b5b776..14d2ad6e 100644 --- a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptionsBuilder.cs +++ b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeOptionsBuilder.cs @@ -9,6 +9,13 @@ namespace MQTTnet.Client.Subscribing { private readonly MqttClientSubscribeOptions _subscribeOptions = new MqttClientSubscribeOptions(); + /// + /// Adds the user property to the subscribe options. + /// Hint: MQTT 5 feature only. + /// + /// The property name. + /// The property value. + /// A new instance of the class. public MqttClientSubscribeOptionsBuilder WithUserProperty(string name, string value) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -27,7 +34,6 @@ namespace MQTTnet.Client.Subscribing public MqttClientSubscribeOptionsBuilder WithSubscriptionIdentifier(uint? subscriptionIdentifier) { _subscribeOptions.SubscriptionIdentifier = subscriptionIdentifier; - return this; } diff --git a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeResultItem.cs b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeResultItem.cs index 65f15c43..3e2d27f1 100644 --- a/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeResultItem.cs +++ b/Source/MQTTnet/Client/Subscribing/MqttClientSubscribeResultItem.cs @@ -10,8 +10,16 @@ namespace MQTTnet.Client.Subscribing ResultCode = resultCode; } + /// + /// Gets or sets the topic filter. + /// The topic filter can contain topics and wildcards. + /// public MqttTopicFilter TopicFilter { get; } + /// + /// Gets or sets the result code. + /// Hint: MQTT 5 feature only. + /// public MqttClientSubscribeResultCode ResultCode { get; } } } diff --git a/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeOptions.cs b/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeOptions.cs index 73c21ef7..09a4ce29 100644 --- a/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeOptions.cs +++ b/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeOptions.cs @@ -5,8 +5,19 @@ namespace MQTTnet.Client.Unsubscribing { public class MqttClientUnsubscribeOptions { + /// + /// Gets or sets a list of topic filters the client wants to unsubscribe from. + /// Topic filters can include regular topics or wild cards. + /// public List TopicFilters { get; set; } = new List(); + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties { get; set; } = new List(); } } diff --git a/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeOptionsBuilder.cs b/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeOptionsBuilder.cs index 85162435..a7f022e1 100644 --- a/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeOptionsBuilder.cs +++ b/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeOptionsBuilder.cs @@ -8,6 +8,13 @@ namespace MQTTnet.Client.Unsubscribing { private readonly MqttClientUnsubscribeOptions _unsubscribeOptions = new MqttClientUnsubscribeOptions(); + /// + /// Adds the user property to the unsubscribe options. + /// Hint: MQTT 5 feature only. + /// + /// The property name. + /// The property value. + /// A new instance of the class. public MqttClientUnsubscribeOptionsBuilder WithUserProperty(string name, string value) { if (name is null) throw new ArgumentNullException(nameof(name)); @@ -16,6 +23,12 @@ namespace MQTTnet.Client.Unsubscribing return WithUserProperty(new MqttUserProperty(name, value)); } + /// + /// Adds the user property to the unsubscribe options. + /// Hint: MQTT 5 feature only. + /// + /// The user property. + /// A new instance of the class. public MqttClientUnsubscribeOptionsBuilder WithUserProperty(MqttUserProperty userProperty) { if (userProperty is null) throw new ArgumentNullException(nameof(userProperty)); diff --git a/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeResultItem.cs b/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeResultItem.cs index 755ee43c..065fb7f2 100644 --- a/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeResultItem.cs +++ b/Source/MQTTnet/Client/Unsubscribing/MqttClientUnsubscribeResultItem.cs @@ -10,8 +10,16 @@ namespace MQTTnet.Client.Unsubscribing ReasonCode = reasonCode; } + /// + /// Gets or sets the topic filter. + /// The topic filter can contain topics and wildcards. + /// public string TopicFilter { get; } + /// + /// Gets or sets the result code. + /// Hint: MQTT 5 feature only. + /// public MqttClientUnsubscribeResultCode ReasonCode { get; } } } \ No newline at end of file diff --git a/Source/MQTTnet/Diagnostics/MqttNetScopedLoggerExtensions.cs b/Source/MQTTnet/Diagnostics/MqttNetScopedLoggerExtensions.cs index abb019fa..8ecc94c1 100644 --- a/Source/MQTTnet/Diagnostics/MqttNetScopedLoggerExtensions.cs +++ b/Source/MQTTnet/Diagnostics/MqttNetScopedLoggerExtensions.cs @@ -18,6 +18,11 @@ namespace MQTTnet.Diagnostics { logger.Publish(MqttNetLogLevel.Warning, message, parameters, exception); } + + public static void Warning(this IMqttNetScopedLogger logger, string message, params object[] parameters) + { + logger.Publish(MqttNetLogLevel.Warning, message, parameters, null); + } public static void Error(this IMqttNetScopedLogger logger, Exception exception, string message, params object[] parameters) { diff --git a/Source/MQTTnet/Diagnostics/PacketInspection/IMqttPacketInspector.cs b/Source/MQTTnet/Diagnostics/PacketInspection/IMqttPacketInspector.cs new file mode 100644 index 00000000..9d7db80c --- /dev/null +++ b/Source/MQTTnet/Diagnostics/PacketInspection/IMqttPacketInspector.cs @@ -0,0 +1,7 @@ +namespace MQTTnet.Diagnostics.PacketInspection +{ + public interface IMqttPacketInspector + { + void ProcessMqttPacket(ProcessMqttPacketContext context); + } +} \ No newline at end of file diff --git a/Source/MQTTnet/Diagnostics/PacketInspection/MqttPacketFlowDirection.cs b/Source/MQTTnet/Diagnostics/PacketInspection/MqttPacketFlowDirection.cs new file mode 100644 index 00000000..7f391179 --- /dev/null +++ b/Source/MQTTnet/Diagnostics/PacketInspection/MqttPacketFlowDirection.cs @@ -0,0 +1,9 @@ +namespace MQTTnet.Diagnostics.PacketInspection +{ + public enum MqttPacketFlowDirection + { + Inbound, + + Outbound + } +} \ No newline at end of file diff --git a/Source/MQTTnet/Diagnostics/PacketInspection/ProcessMqttPacketContext.cs b/Source/MQTTnet/Diagnostics/PacketInspection/ProcessMqttPacketContext.cs new file mode 100644 index 00000000..644b2a77 --- /dev/null +++ b/Source/MQTTnet/Diagnostics/PacketInspection/ProcessMqttPacketContext.cs @@ -0,0 +1,9 @@ +namespace MQTTnet.Diagnostics.PacketInspection +{ + public sealed class ProcessMqttPacketContext + { + public MqttPacketFlowDirection Direction { get; set; } + + public byte[] Buffer { get; set; } + } +} \ No newline at end of file diff --git a/Source/MQTTnet/Formatter/IMqttDataConverter.cs b/Source/MQTTnet/Formatter/IMqttDataConverter.cs index 76079a1b..aec47027 100644 --- a/Source/MQTTnet/Formatter/IMqttDataConverter.cs +++ b/Source/MQTTnet/Formatter/IMqttDataConverter.cs @@ -14,24 +14,32 @@ namespace MQTTnet.Formatter { public interface IMqttDataConverter { - MqttPublishPacket CreatePublishPacket(MqttApplicationMessage applicationMessage); - - MqttPubAckPacket CreatePubAckPacket(MqttPublishPacket publishPacket); - - MqttBasePacket CreatePubRecPacket(MqttPublishPacket publishPacket); - MqttApplicationMessage CreateApplicationMessage(MqttPublishPacket publishPacket); MqttClientAuthenticateResult CreateClientConnectResult(MqttConnAckPacket connAckPacket); + MqttClientPublishResult CreateClientPublishResult(MqttPubAckPacket pubAckPacket); + + MqttClientPublishResult CreateClientPublishResult(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket); + + MqttClientSubscribeResult CreateClientSubscribeResult(MqttSubscribePacket subscribePacket, MqttSubAckPacket subAckPacket); + + MqttClientUnsubscribeResult CreateClientUnsubscribeResult(MqttUnsubscribePacket unsubscribePacket, MqttUnsubAckPacket unsubAckPacket); + MqttConnectPacket CreateConnectPacket(MqttApplicationMessage willApplicationMessage, IMqttClientOptions options); MqttConnAckPacket CreateConnAckPacket(MqttConnectionValidatorContext connectionValidatorContext); + + MqttPublishPacket CreatePublishPacket(MqttApplicationMessage applicationMessage); - MqttClientSubscribeResult CreateClientSubscribeResult(MqttSubscribePacket subscribePacket, MqttSubAckPacket subAckPacket); - - MqttClientUnsubscribeResult CreateClientUnsubscribeResult(MqttUnsubscribePacket unsubscribePacket, MqttUnsubAckPacket unsubAckPacket); + MqttPubAckPacket CreatePubAckPacket(MqttPublishPacket publishPacket, MqttApplicationMessageReceivedReasonCode reasonCode); + + MqttPubRecPacket CreatePubRecPacket(MqttPublishPacket publishPacket, MqttApplicationMessageReceivedReasonCode reasonCode); + MqttPubCompPacket CreatePubCompPacket(MqttPubRelPacket pubRelPacket, MqttApplicationMessageReceivedReasonCode reasonCode); + + MqttPubRelPacket CreatePubRelPacket(MqttPubRecPacket pubRecPacket, MqttApplicationMessageReceivedReasonCode reasonCode); + MqttSubscribePacket CreateSubscribePacket(MqttClientSubscribeOptions options); MqttSubAckPacket CreateSubAckPacket(MqttSubscribePacket subscribePacket, Server.MqttClientSubscribeResult subscribeResult); @@ -41,9 +49,5 @@ namespace MQTTnet.Formatter MqttUnsubAckPacket CreateUnsubAckPacket(MqttUnsubscribePacket unsubscribePacket, List reasonCodes); MqttDisconnectPacket CreateDisconnectPacket(MqttClientDisconnectOptions options); - - MqttClientPublishResult CreatePublishResult(MqttPubAckPacket pubAckPacket); - - MqttClientPublishResult CreatePublishResult(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket); } } diff --git a/Source/MQTTnet/Formatter/MqttPacketFormatterAdapter.cs b/Source/MQTTnet/Formatter/MqttPacketFormatterAdapter.cs index 7757accd..1e2df944 100644 --- a/Source/MQTTnet/Formatter/MqttPacketFormatterAdapter.cs +++ b/Source/MQTTnet/Formatter/MqttPacketFormatterAdapter.cs @@ -11,7 +11,7 @@ namespace MQTTnet.Formatter public sealed class MqttPacketFormatterAdapter { IMqttPacketFormatter _formatter; - + public MqttPacketFormatterAdapter(MqttProtocolVersion protocolVersion) : this(protocolVersion, new MqttPacketWriter()) { @@ -26,7 +26,7 @@ namespace MQTTnet.Formatter public MqttPacketFormatterAdapter(IMqttPacketWriter writer) { Writer = writer; - } + } public MqttProtocolVersion ProtocolVersion { get; private set; } = MqttProtocolVersion.Unknown; @@ -39,7 +39,7 @@ namespace MQTTnet.Formatter return _formatter.DataConverter; } } - + public IMqttPacketWriter Writer { get; } public ArraySegment Encode(MqttBasePacket packet) @@ -69,10 +69,10 @@ namespace MQTTnet.Formatter { var protocolVersion = ParseProtocolVersion(receivedMqttPacket); - // Reset the position of the stream because the protocol version is part of + // Reset the position of the stream because the protocol version is part of // the regular CONNECT packet. So it will not properly deserialized if this // data is missing. - receivedMqttPacket.Body.Seek(0); + receivedMqttPacket.BodyReader.Seek(0); UseProtocolVersion(protocolVersion); } @@ -83,7 +83,7 @@ namespace MQTTnet.Formatter { throw new InvalidOperationException("MQTT protocol version is invalid."); } - + switch (protocolVersion) { case MqttProtocolVersion.V500: @@ -120,7 +120,7 @@ namespace MQTTnet.Formatter { if (receivedMqttPacket == null) throw new ArgumentNullException(nameof(receivedMqttPacket)); - if (receivedMqttPacket.Body.Length < 7) + if (receivedMqttPacket.BodyReader.Length < 7) { // 2 byte protocol name length // at least 4 byte protocol name @@ -128,8 +128,8 @@ namespace MQTTnet.Formatter throw new MqttProtocolViolationException("CONNECT packet must have at least 7 bytes."); } - var protocolName = receivedMqttPacket.Body.ReadStringWithLengthPrefix(); - var protocolLevel = receivedMqttPacket.Body.ReadByte(); + var protocolName = receivedMqttPacket.BodyReader.ReadStringWithLengthPrefix(); + var protocolLevel = receivedMqttPacket.BodyReader.ReadByte(); if (protocolName == "MQTT") { diff --git a/Source/MQTTnet/Formatter/MqttPacketReader.cs b/Source/MQTTnet/Formatter/MqttPacketReader.cs deleted file mode 100644 index 0f1a9760..00000000 --- a/Source/MQTTnet/Formatter/MqttPacketReader.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using MQTTnet.Channel; -using MQTTnet.Exceptions; - -namespace MQTTnet.Formatter -{ - public sealed class MqttPacketReader - { - readonly byte[] _singleByteBuffer = new byte[1]; - - readonly IMqttChannel _channel; - - public MqttPacketReader(IMqttChannel channel) - { - _channel = channel ?? throw new ArgumentNullException(nameof(channel)); - } - - public async Task ReadFixedHeaderAsync(byte[] fixedHeaderBuffer, CancellationToken cancellationToken) - { - // The MQTT fixed header contains 1 byte of flags and at least 1 byte for the remaining data length. - // So in all cases at least 2 bytes must be read for a complete MQTT packet. - var buffer = fixedHeaderBuffer; - var totalBytesRead = 0; - - while (totalBytesRead < buffer.Length) - { - var bytesRead = await _channel.ReadAsync(buffer, totalBytesRead, buffer.Length - totalBytesRead, cancellationToken).ConfigureAwait(false); - - if (cancellationToken.IsCancellationRequested) - { - return null; - } - - if (bytesRead == 0) - { - return new ReadFixedHeaderResult - { - ConnectionClosed = true - }; - } - - totalBytesRead += bytesRead; - } - - var hasRemainingLength = buffer[1] != 0; - if (!hasRemainingLength) - { - return new ReadFixedHeaderResult - { - FixedHeader = new MqttFixedHeader(buffer[0], 0, totalBytesRead) - }; - } - - var bodyLength = await ReadBodyLengthAsync(buffer[1], cancellationToken).ConfigureAwait(false); - - if (!bodyLength.HasValue) - { - return new ReadFixedHeaderResult - { - ConnectionClosed = true - }; - } - - totalBytesRead += bodyLength.Value; - return new ReadFixedHeaderResult - { - FixedHeader = new MqttFixedHeader(buffer[0], bodyLength.Value, totalBytesRead) - }; - } - - async Task ReadBodyLengthAsync(byte initialEncodedByte, CancellationToken cancellationToken) - { - var offset = 0; - var multiplier = 128; - var value = initialEncodedByte & 127; - int encodedByte = initialEncodedByte; - - while ((encodedByte & 128) != 0) - { - offset++; - if (offset > 3) - { - throw new MqttProtocolViolationException("Remaining length is invalid."); - } - - if (cancellationToken.IsCancellationRequested) - { - return null; - } - - var readCount = await _channel.ReadAsync(_singleByteBuffer, 0, 1, cancellationToken).ConfigureAwait(false); - - if (cancellationToken.IsCancellationRequested) - { - return null; - } - - if (readCount == 0) - { - return null; - } - - encodedByte = _singleByteBuffer[0]; - - value += (encodedByte & 127) * multiplier; - multiplier *= 128; - } - - return value; - } - } -} diff --git a/Source/MQTTnet/Formatter/MqttPacketWriter.cs b/Source/MQTTnet/Formatter/MqttPacketWriter.cs index a51ba618..48d95783 100644 --- a/Source/MQTTnet/Formatter/MqttPacketWriter.cs +++ b/Source/MQTTnet/Formatter/MqttPacketWriter.cs @@ -14,7 +14,8 @@ namespace MQTTnet.Formatter public sealed class MqttPacketWriter : IMqttPacketWriter { public static int InitialBufferSize = 4096; - public static int MaxBufferSize = 4096 + 4; + + public static int MaxBufferSize = 4096 * 4; byte[] _buffer = new byte[InitialBufferSize]; @@ -97,7 +98,7 @@ namespace MQTTnet.Formatter _buffer[_offset] = (byte)(bufferSize >> 8); _buffer[_offset + 1] = (byte)bufferSize; - + Encoding.UTF8.GetBytes(value, 0, value.Length, _buffer, _offset + 2); IncreasePosition(bufferSize + 2); @@ -121,7 +122,7 @@ namespace MQTTnet.Formatter _buffer[_offset] = (byte)(value.Length >> 8); _buffer[_offset + 1] = (byte)value.Length; - + Array.Copy(value, 0, _buffer, _offset + 2, value.Length); IncreasePosition(value.Length + 2); } @@ -201,8 +202,8 @@ namespace MQTTnet.Formatter { // This method frees the used memory by shrinking the buffer. This is required because the buffer // is used across several messages. In general this is not a big issue because subsequent Ping packages - // have the same size but a very big publish package with 100 MB of payload will increase the buffer - // a lot and the size will never reduced. So this method tries to find a size which can be held in + // have the same size but a very big publish package with 100 MB of payload will increase the buffer + // a lot and the size will never reduced. So this method tries to find a size which can be held in // memory for a long time without causing troubles. if (_buffer.Length < MaxBufferSize) @@ -212,7 +213,7 @@ namespace MQTTnet.Formatter Array.Resize(ref _buffer, MaxBufferSize); } - + [MethodImpl(MethodImplOptions.AggressiveInlining)] void EnsureAdditionalCapacity(int additionalCapacity) { diff --git a/Source/MQTTnet/Formatter/V3/MqttV310DataConverter.cs b/Source/MQTTnet/Formatter/V3/MqttV310DataConverter.cs index 31ea9ed4..c2b16747 100644 --- a/Source/MQTTnet/Formatter/V3/MqttV310DataConverter.cs +++ b/Source/MQTTnet/Formatter/V3/MqttV310DataConverter.cs @@ -31,21 +31,43 @@ namespace MQTTnet.Formatter.V3 }; } - public MqttPubAckPacket CreatePubAckPacket(MqttPublishPacket publishPacket) + public MqttPubAckPacket CreatePubAckPacket(MqttPublishPacket publishPacket, MqttApplicationMessageReceivedReasonCode reasonCode) { + if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket)); + return new MqttPubAckPacket { - PacketIdentifier = publishPacket.PacketIdentifier, - ReasonCode = MqttPubAckReasonCode.Success + PacketIdentifier = publishPacket.PacketIdentifier }; } - public MqttBasePacket CreatePubRecPacket(MqttPublishPacket publishPacket) + public MqttPubRecPacket CreatePubRecPacket(MqttPublishPacket publishPacket, MqttApplicationMessageReceivedReasonCode reasonCode) { + if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket)); + return new MqttPubRecPacket { - PacketIdentifier = publishPacket.PacketIdentifier, - ReasonCode = MqttPubRecReasonCode.Success + PacketIdentifier = publishPacket.PacketIdentifier + }; + } + + public MqttPubCompPacket CreatePubCompPacket(MqttPubRelPacket pubRelPacket, MqttApplicationMessageReceivedReasonCode reasonCode) + { + if (pubRelPacket == null) throw new ArgumentNullException(nameof(pubRelPacket)); + + return new MqttPubCompPacket + { + PacketIdentifier = pubRelPacket.PacketIdentifier + }; + } + + public MqttPubRelPacket CreatePubRelPacket(MqttPubRecPacket pubRecPacket, MqttApplicationMessageReceivedReasonCode reasonCode) + { + if (pubRecPacket == null) throw new ArgumentNullException(nameof(pubRecPacket)); + + return new MqttPubRelPacket + { + PacketIdentifier = pubRecPacket.PacketIdentifier }; } @@ -58,7 +80,8 @@ namespace MQTTnet.Formatter.V3 Topic = publishPacket.Topic, Payload = publishPacket.Payload, QualityOfServiceLevel = publishPacket.QualityOfServiceLevel, - Retain = publishPacket.Retain + Retain = publishPacket.Retain, + Dup = publishPacket.Dup }; } @@ -184,6 +207,9 @@ namespace MQTTnet.Formatter.V3 public MqttSubAckPacket CreateSubAckPacket(MqttSubscribePacket subscribePacket, Server.MqttClientSubscribeResult subscribeResult) { + if (subscribePacket == null) throw new ArgumentNullException(nameof(subscribePacket)); + if (subscribeResult == null) throw new ArgumentNullException(nameof(subscribeResult)); + var subackPacket = new MqttSubAckPacket { PacketIdentifier = subscribePacket.PacketIdentifier @@ -206,6 +232,9 @@ namespace MQTTnet.Formatter.V3 public MqttUnsubAckPacket CreateUnsubAckPacket(MqttUnsubscribePacket unsubscribePacket, List reasonCodes) { + if (unsubscribePacket == null) throw new ArgumentNullException(nameof(unsubscribePacket)); + if (reasonCodes == null) throw new ArgumentNullException(nameof(reasonCodes)); + return new MqttUnsubAckPacket { PacketIdentifier = unsubscribePacket.PacketIdentifier, @@ -223,7 +252,7 @@ namespace MQTTnet.Formatter.V3 return new MqttDisconnectPacket(); } - public MqttClientPublishResult CreatePublishResult(MqttPubAckPacket pubAckPacket) + public MqttClientPublishResult CreateClientPublishResult(MqttPubAckPacket pubAckPacket) { return new MqttClientPublishResult { @@ -232,7 +261,7 @@ namespace MQTTnet.Formatter.V3 }; } - public MqttClientPublishResult CreatePublishResult(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket) + public MqttClientPublishResult CreateClientPublishResult(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket) { if (pubRecPacket == null || pubCompPacket == null) { diff --git a/Source/MQTTnet/Formatter/V3/MqttV310PacketFormatter.cs b/Source/MQTTnet/Formatter/V3/MqttV310PacketFormatter.cs index 43ffc1da..d872b1cf 100644 --- a/Source/MQTTnet/Formatter/V3/MqttV310PacketFormatter.cs +++ b/Source/MQTTnet/Formatter/V3/MqttV310PacketFormatter.cs @@ -63,20 +63,20 @@ namespace MQTTnet.Formatter.V3 switch ((MqttControlPacketType)controlPacketType) { - case MqttControlPacketType.Connect: return DecodeConnectPacket(receivedMqttPacket.Body); - case MqttControlPacketType.ConnAck: return DecodeConnAckPacket(receivedMqttPacket.Body); + case MqttControlPacketType.Connect: return DecodeConnectPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.ConnAck: return DecodeConnAckPacket(receivedMqttPacket.BodyReader); 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.PubAck: return DecodePubAckPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.PubRec: return DecodePubRecPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.PubRel: return DecodePubRelPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.PubComp: return DecodePubCompPacket(receivedMqttPacket.BodyReader); 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); - case MqttControlPacketType.UnsubAck: return DecodeUnsubAckPacket(receivedMqttPacket.Body); + case MqttControlPacketType.Subscribe: return DecodeSubscribePacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.SubAck: return DecodeSubAckPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.Unsubscibe: return DecodeUnsubscribePacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.UnsubAck: return DecodeUnsubAckPacket(receivedMqttPacket.BodyReader); default: throw new MqttProtocolViolationException($"Packet type ({controlPacketType}) not supported."); } @@ -202,18 +202,18 @@ namespace MQTTnet.Formatter.V3 static MqttBasePacket DecodePublishPacket(ReceivedMqttPacket receivedMqttPacket) { - ThrowIfBodyIsEmpty(receivedMqttPacket.Body); + ThrowIfBodyIsEmpty(receivedMqttPacket.BodyReader); var retain = (receivedMqttPacket.FixedHeader & 0x1) > 0; var qualityOfServiceLevel = (MqttQualityOfServiceLevel)(receivedMqttPacket.FixedHeader >> 1 & 0x3); var dup = (receivedMqttPacket.FixedHeader & 0x8) > 0; - var topic = receivedMqttPacket.Body.ReadStringWithLengthPrefix(); + var topic = receivedMqttPacket.BodyReader.ReadStringWithLengthPrefix(); ushort packetIdentifier = 0; if (qualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce) { - packetIdentifier = receivedMqttPacket.Body.ReadTwoByteInteger(); + packetIdentifier = receivedMqttPacket.BodyReader.ReadTwoByteInteger(); } var packet = new MqttPublishPacket @@ -225,9 +225,9 @@ namespace MQTTnet.Formatter.V3 Dup = dup }; - if (!receivedMqttPacket.Body.EndOfStream) + if (!receivedMqttPacket.BodyReader.EndOfStream) { - packet.Payload = receivedMqttPacket.Body.ReadRemainingData(); + packet.Payload = receivedMqttPacket.BodyReader.ReadRemainingData(); } return packet; diff --git a/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs b/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs index 038a4ed9..49da6fcd 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs @@ -15,7 +15,7 @@ using MqttClientSubscribeResult = MQTTnet.Client.Subscribing.MqttClientSubscribe namespace MQTTnet.Formatter.V5 { - public class MqttV500DataConverter : IMqttDataConverter + public sealed class MqttV500DataConverter : IMqttDataConverter { public MqttPublishPacket CreatePublishPacket(MqttApplicationMessage applicationMessage) { @@ -27,7 +27,7 @@ namespace MQTTnet.Formatter.V5 Payload = applicationMessage.Payload, QualityOfServiceLevel = applicationMessage.QualityOfServiceLevel, Retain = applicationMessage.Retain, - Dup = false, + Dup = applicationMessage.Dup, Properties = new MqttPublishPacketProperties { ContentType = applicationMessage.ContentType, @@ -49,32 +49,61 @@ namespace MQTTnet.Formatter.V5 return packet; } - public MqttPubAckPacket CreatePubAckPacket(MqttPublishPacket publishPacket) + public MqttPubAckPacket CreatePubAckPacket(MqttPublishPacket publishPacket, MqttApplicationMessageReceivedReasonCode reasonCode) { + if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket)); + return new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier, - ReasonCode = MqttPubAckReasonCode.Success + ReasonCode = (MqttPubAckReasonCode)(int)reasonCode }; } - public MqttBasePacket CreatePubRecPacket(MqttPublishPacket publishPacket) + public MqttPubRecPacket CreatePubRecPacket(MqttPublishPacket publishPacket, MqttApplicationMessageReceivedReasonCode reasonCode) { + if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket)); + return new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier, - ReasonCode = MqttPubRecReasonCode.Success + ReasonCode = (MqttPubRecReasonCode)(int)reasonCode + }; + } + + public MqttPubCompPacket CreatePubCompPacket(MqttPubRelPacket pubRelPacket, MqttApplicationMessageReceivedReasonCode reasonCode) + { + if (pubRelPacket == null) throw new ArgumentNullException(nameof(pubRelPacket)); + + return new MqttPubCompPacket + { + PacketIdentifier = pubRelPacket.PacketIdentifier, + ReasonCode = (MqttPubCompReasonCode)(int)reasonCode + }; + } + + public MqttPubRelPacket CreatePubRelPacket(MqttPubRecPacket pubRecPacket, MqttApplicationMessageReceivedReasonCode reasonCode) + { + if (pubRecPacket == null) throw new ArgumentNullException(nameof(pubRecPacket)); + + return new MqttPubRelPacket + { + PacketIdentifier = pubRecPacket.PacketIdentifier, + ReasonCode = (MqttPubRelReasonCode)(int)reasonCode }; } public MqttApplicationMessage CreateApplicationMessage(MqttPublishPacket publishPacket) { + if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket)); + return new MqttApplicationMessage { Topic = publishPacket.Topic, Payload = publishPacket.Payload, QualityOfServiceLevel = publishPacket.QualityOfServiceLevel, Retain = publishPacket.Retain, + Dup = publishPacket.Dup, ResponseTopic = publishPacket.Properties?.ResponseTopic, ContentType = publishPacket.Properties?.ContentType, CorrelationData = publishPacket.Properties?.CorrelationData, @@ -93,7 +122,7 @@ namespace MQTTnet.Formatter.V5 return new MqttClientAuthenticateResult { IsSessionPresent = connAckPacket.IsSessionPresent, - ResultCode = (MqttClientConnectResultCode)connAckPacket.ReasonCode.Value, + ResultCode = (MqttClientConnectResultCode)(int)(connAckPacket.ReasonCode ?? 0), WildcardSubscriptionAvailable = connAckPacket.Properties?.WildcardSubscriptionAvailable, RetainAvailable = connAckPacket.Properties?.RetainAvailable, AssignedClientIdentifier = connAckPacket.Properties?.AssignedClientIdentifier, @@ -144,6 +173,8 @@ namespace MQTTnet.Formatter.V5 public MqttConnAckPacket CreateConnAckPacket(MqttConnectionValidatorContext connectionValidatorContext) { + if (connectionValidatorContext == null) throw new ArgumentNullException(nameof(connectionValidatorContext)); + return new MqttConnAckPacket { ReasonCode = connectionValidatorContext.ReasonCode, @@ -213,6 +244,9 @@ namespace MQTTnet.Formatter.V5 public MqttSubAckPacket CreateSubAckPacket(MqttSubscribePacket subscribePacket, Server.MqttClientSubscribeResult subscribeResult) { + if (subscribePacket == null) throw new ArgumentNullException(nameof(subscribePacket)); + if (subscribeResult == null) throw new ArgumentNullException(nameof(subscribeResult)); + var subackPacket = new MqttSubAckPacket { PacketIdentifier = subscribePacket.PacketIdentifier @@ -240,6 +274,9 @@ namespace MQTTnet.Formatter.V5 public MqttUnsubAckPacket CreateUnsubAckPacket(MqttUnsubscribePacket unsubscribePacket, List reasonCodes) { + if (unsubscribePacket == null) throw new ArgumentNullException(nameof(unsubscribePacket)); + if (reasonCodes == null) throw new ArgumentNullException(nameof(reasonCodes)); + return new MqttUnsubAckPacket { PacketIdentifier = unsubscribePacket.PacketIdentifier, @@ -263,7 +300,7 @@ namespace MQTTnet.Formatter.V5 return packet; } - public MqttClientPublishResult CreatePublishResult(MqttPubAckPacket pubAckPacket) + public MqttClientPublishResult CreateClientPublishResult(MqttPubAckPacket pubAckPacket) { var result = new MqttClientPublishResult { @@ -276,7 +313,7 @@ namespace MQTTnet.Formatter.V5 { // QoS 0 has no response. So we treat it as a success always. // Both enums have the same values. So it can be easily converted. - result.ReasonCode = (MqttClientPublishReasonCode)pubAckPacket.ReasonCode; + result.ReasonCode = (MqttClientPublishReasonCode)(int)(pubAckPacket.ReasonCode ?? 0); result.PacketIdentifier = pubAckPacket.PacketIdentifier; } @@ -284,7 +321,7 @@ namespace MQTTnet.Formatter.V5 return result; } - public MqttClientPublishResult CreatePublishResult(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket) + public MqttClientPublishResult CreateClientPublishResult(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket) { if (pubRecPacket == null || pubCompPacket == null) { @@ -317,10 +354,10 @@ namespace MQTTnet.Formatter.V5 if (pubRecPacket.ReasonCode.HasValue) { // Both enums share the same values. - result.ReasonCode = (MqttClientPublishReasonCode)pubRecPacket.ReasonCode.Value; + result.ReasonCode = (MqttClientPublishReasonCode)(pubRecPacket.ReasonCode ?? 0); } return result; } } -} +} \ No newline at end of file diff --git a/Source/MQTTnet/Formatter/V5/MqttV500PacketDecoder.cs b/Source/MQTTnet/Formatter/V5/MqttV500PacketDecoder.cs index be8d74f4..fe355060 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV500PacketDecoder.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV500PacketDecoder.cs @@ -25,21 +25,21 @@ namespace MQTTnet.Formatter.V5 switch ((MqttControlPacketType)controlPacketType) { - case MqttControlPacketType.Connect: return DecodeConnectPacket(receivedMqttPacket.Body); - case MqttControlPacketType.ConnAck: return DecodeConnAckPacket(receivedMqttPacket.Body); - case MqttControlPacketType.Disconnect: return DecodeDisconnectPacket(receivedMqttPacket.Body); - case MqttControlPacketType.Publish: return DecodePublishPacket(receivedMqttPacket.FixedHeader, receivedMqttPacket.Body); - 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.Connect: return DecodeConnectPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.ConnAck: return DecodeConnAckPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.Disconnect: return DecodeDisconnectPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.Publish: return DecodePublishPacket(receivedMqttPacket.FixedHeader, receivedMqttPacket.BodyReader); + case MqttControlPacketType.PubAck: return DecodePubAckPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.PubRec: return DecodePubRecPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.PubRel: return DecodePubRelPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.PubComp: return DecodePubCompPacket(receivedMqttPacket.BodyReader); case MqttControlPacketType.PingReq: return DecodePingReqPacket(); case MqttControlPacketType.PingResp: return DecodePingRespPacket(); - case MqttControlPacketType.Subscribe: return DecodeSubscribePacket(receivedMqttPacket.Body); - case MqttControlPacketType.SubAck: return DecodeSubAckPacket(receivedMqttPacket.Body); - case MqttControlPacketType.Unsubscibe: return DecodeUnsubscribePacket(receivedMqttPacket.Body); - case MqttControlPacketType.UnsubAck: return DecodeUnsubAckPacket(receivedMqttPacket.Body); - case MqttControlPacketType.Auth: return DecodeAuthPacket(receivedMqttPacket.Body); + case MqttControlPacketType.Subscribe: return DecodeSubscribePacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.SubAck: return DecodeSubAckPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.Unsubscibe: return DecodeUnsubscribePacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.UnsubAck: return DecodeUnsubAckPacket(receivedMqttPacket.BodyReader); + case MqttControlPacketType.Auth: return DecodeAuthPacket(receivedMqttPacket.BodyReader); default: throw new MqttProtocolViolationException($"Packet type ({controlPacketType}) not supported."); } diff --git a/Source/MQTTnet/IApplicationMessageReceiver.cs b/Source/MQTTnet/IApplicationMessageReceiver.cs index 4e474856..a44470d1 100644 --- a/Source/MQTTnet/IApplicationMessageReceiver.cs +++ b/Source/MQTTnet/IApplicationMessageReceiver.cs @@ -4,6 +4,10 @@ namespace MQTTnet { public interface IApplicationMessageReceiver { + /// + /// Gets or sets the application message received handler that is fired every time a new message is received on the client's subscriptions. + /// Hint: Initialize handlers before you connect the client to avoid issues. + /// IMqttApplicationMessageReceivedHandler ApplicationMessageReceivedHandler { get; set; } } } diff --git a/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs b/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs index d7e85db4..920f9822 100644 --- a/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs +++ b/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs @@ -3,6 +3,7 @@ using MQTTnet.Client.Options; using MQTTnet.Diagnostics; using MQTTnet.Formatter; using System; +using MQTTnet.Channel; namespace MQTTnet.Implementations { @@ -19,16 +20,19 @@ namespace MQTTnet.Implementations { if (options == null) throw new ArgumentNullException(nameof(options)); + IMqttChannel channel; switch (options.ChannelOptions) { case MqttClientTcpOptions _: { - return new MqttChannelAdapter(new MqttTcpChannel(options), new MqttPacketFormatterAdapter(options.ProtocolVersion, new MqttPacketWriter()), _logger); + channel = new MqttTcpChannel(options); + break; } case MqttClientWebSocketOptions webSocketOptions: { - return new MqttChannelAdapter(new MqttWebSocketChannel(webSocketOptions), new MqttPacketFormatterAdapter(options.ProtocolVersion, new MqttPacketWriter()), _logger); + channel = new MqttWebSocketChannel(webSocketOptions); + break; } default: @@ -36,6 +40,9 @@ namespace MQTTnet.Implementations throw new NotSupportedException(); } } + + var packetFormatterAdapter = new MqttPacketFormatterAdapter(options.ProtocolVersion, new MqttPacketWriter()); + return new MqttChannelAdapter(channel, packetFormatterAdapter, options.PacketInspector, _logger); } } } diff --git a/Source/MQTTnet/Implementations/MqttTcpChannel.cs b/Source/MQTTnet/Implementations/MqttTcpChannel.cs index 30208773..6e308109 100644 --- a/Source/MQTTnet/Implementations/MqttTcpChannel.cs +++ b/Source/MQTTnet/Implementations/MqttTcpChannel.cs @@ -77,7 +77,7 @@ namespace MQTTnet.Implementations cancellationToken.ThrowIfCancellationRequested(); var networkStream = socket.GetStream(); - + if (_tcpOptions.TlsOptions?.UseTls == true) { var sslStream = new SslStream(networkStream, false, InternalUserCertificateValidationCallback); @@ -94,7 +94,7 @@ namespace MQTTnet.Implementations }; await sslStream.AuthenticateAsClientAsync(sslOptions, cancellationToken).ConfigureAwait(false); -#else +#else await sslStream.AuthenticateAsClientAsync(_tcpOptions.Server, LoadCertificates(), _tcpOptions.TlsOptions.SslProtocol, !_tcpOptions.TlsOptions.IgnoreCertificateRevocationErrors).ConfigureAwait(false); #endif } diff --git a/Source/MQTTnet/Implementations/MqttTcpServerAdapter.Uwp.cs b/Source/MQTTnet/Implementations/MqttTcpServerAdapter.Uwp.cs index 2010b5b0..dd164ba9 100644 --- a/Source/MQTTnet/Implementations/MqttTcpServerAdapter.Uwp.cs +++ b/Source/MQTTnet/Implementations/MqttTcpServerAdapter.Uwp.cs @@ -89,7 +89,7 @@ namespace MQTTnet.Implementations } } - using (var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(args.Socket, clientCertificate, _options), new MqttPacketFormatterAdapter(new MqttPacketWriter()), _rootLogger)) + using (var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(args.Socket, clientCertificate, _options), new MqttPacketFormatterAdapter(new MqttPacketWriter()), null, _rootLogger)) { await clientHandler(clientAdapter).ConfigureAwait(false); } diff --git a/Source/MQTTnet/Implementations/MqttTcpServerListener.cs b/Source/MQTTnet/Implementations/MqttTcpServerListener.cs index ef69890c..b7df3491 100644 --- a/Source/MQTTnet/Implementations/MqttTcpServerListener.cs +++ b/Source/MQTTnet/Implementations/MqttTcpServerListener.cs @@ -178,7 +178,11 @@ namespace MQTTnet.Implementations var clientHandler = ClientHandler; if (clientHandler != null) { - using (var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(stream, remoteEndPoint, clientCertificate), new MqttPacketFormatterAdapter(new MqttPacketWriter()), _rootLogger)) + using (var clientAdapter = new MqttChannelAdapter( + new MqttTcpChannel(stream, remoteEndPoint, clientCertificate), + new MqttPacketFormatterAdapter(new MqttPacketWriter()), + null, + _rootLogger)) { await clientHandler(clientAdapter).ConfigureAwait(false); } diff --git a/Source/MQTTnet/Internal/TestMqttChannel.cs b/Source/MQTTnet/Internal/TestMqttChannel.cs index fba12696..233a0cbb 100644 --- a/Source/MQTTnet/Internal/TestMqttChannel.cs +++ b/Source/MQTTnet/Internal/TestMqttChannel.cs @@ -6,7 +6,7 @@ using MQTTnet.Channel; namespace MQTTnet.Internal { - public class TestMqttChannel : IMqttChannel + public sealed class TestMqttChannel : IMqttChannel { readonly MemoryStream _stream; @@ -15,6 +15,11 @@ namespace MQTTnet.Internal _stream = stream; } + public TestMqttChannel(byte[] buffer) + { + _stream = new MemoryStream(buffer); + } + public string Endpoint { get; } = ""; public bool IsSecureConnection { get; } = false; diff --git a/Source/MQTTnet/MQTTnet.csproj b/Source/MQTTnet/MQTTnet.csproj index 42989f38..8efd8727 100644 --- a/Source/MQTTnet/MQTTnet.csproj +++ b/Source/MQTTnet/MQTTnet.csproj @@ -35,14 +35,6 @@ Full - - - - - - - RELEASE;NETSTANDARD1_3 - @@ -54,20 +46,8 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/Source/MQTTnet/MqttApplicationMessage.cs b/Source/MQTTnet/MqttApplicationMessage.cs index 6522d42f..d1fe2297 100644 --- a/Source/MQTTnet/MqttApplicationMessage.cs +++ b/Source/MQTTnet/MqttApplicationMessage.cs @@ -6,28 +6,107 @@ namespace MQTTnet { public class MqttApplicationMessage { + /// + /// Gets or sets the MQTT topic. + /// In MQTT, the word topic refers to an UTF-8 string that the broker uses to filter messages for each connected client. + /// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level separator). + /// public string Topic { get; set; } + /// + /// Gets or sets the payload. + /// The payload is the data bytes sent via the MQTT protocol. + /// public byte[] Payload { get; set; } + /// + /// Gets or sets the quality of service level. + /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message that defines the guarantee of delivery for a specific message. + /// There are 3 QoS levels in MQTT: + /// - At most once (0): Message gets delivered no time, once or multiple times. + /// - At least once (1): Message gets delivered at least once (one time or more often). + /// - Exactly once (2): Message gets delivered exactly once (It's ensured that the message only comes once). + /// public MqttQualityOfServiceLevel QualityOfServiceLevel { get; set; } + /// + /// Gets or sets a value indicating whether the message should be retained or not. + /// A retained message is a normal MQTT message with the retained flag set to true. + /// The broker stores the last retained message and the corresponding QoS for that topic. + /// public bool Retain { get; set; } + + /// + /// If the DUP flag is set to 0, it indicates that this is the first occasion that the Client or Server has attempted to send this MQTT PUBLISH Packet. + /// If the DUP flag is set to 1, it indicates that this might be re-delivery of an earlier attempt to send the Packet. + /// The DUP flag MUST be set to 1 by the Client or Server when it attempts to re-deliver a PUBLISH Packet [MQTT-3.3.1.-1]. + /// The DUP flag MUST be set to 0 for all QoS 0 messages [MQTT-3.3.1-2]. + /// + public bool Dup { get; set; } + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties { get; set; } + /// + /// Gets or sets the content type. + /// The content type must be a UTF-8 encoded string. The content type value identifies the kind of UTF-8 encoded payload. + /// public string ContentType { get; set; } + /// + /// Gets or sets the response topic. + /// In MQTT 5 the ability to publish a response topic was added in the publish message which allows you to implement the request/response pattern between clients that is common in web applications. + /// Hint: MQTT 5 feature only. + /// public string ResponseTopic { get; set; } + /// + /// Gets or sets the payload format indicator. + /// The payload format indicator is part of any MQTT packet that can contain a payload. The indicator is an optional byte value. + /// A value of 0 indicates an “unspecified byte stream”. + /// A value of 1 indicates a "UTF-8 encoded payload". + /// If no payload format indicator is provided, the default value is 0. + /// Hint: MQTT 5 feature only. + /// public MqttPayloadFormatIndicator? PayloadFormatIndicator { get; set; } + /// + /// Gets or sets the message expiry interval. + /// A client can set the message expiry interval in seconds for each PUBLISH message individually. + /// This interval defines the period of time that the broker stores the PUBLISH message for any matching subscribers that are not currently connected. + /// When no message expiry interval is set, the broker must store the message for matching subscribers indefinitely. + /// When the retained=true option is set on the PUBLISH message, this interval also defines how long a message is retained on a topic. + /// Hint: MQTT 5 feature only. + /// public uint? MessageExpiryInterval { get; set; } + /// + /// Gets or sets the topic alias. + /// Topic aliases were introduced are a mechanism for reducing the size of published packets by reducing the size of the topic field. + /// Hint: MQTT 5 feature only. + /// public ushort? TopicAlias { get; set; } + /// + /// Gets or sets the correlation data. + /// In order for the sender to know what sent message the response refers to it can also send correlation data with the published message. + /// Hint: MQTT 5 feature only. + /// public byte[] CorrelationData { get; set; } + /// + /// Gets or sets the subscription identifiers. + /// The client can specify a subscription identifier when subscribing. + /// The broker will establish and store the mapping relationship between this subscription and subscription identifier when successfully create or modify subscription. + /// The broker will return the subscription identifier associated with this PUBLISH packet and the PUBLISH packet to the client when need to forward PUBLISH packets matching this subscription to this client. + /// Hint: MQTT 5 feature only. + /// public List SubscriptionIdentifiers { get; set; } } } diff --git a/Source/MQTTnet/MqttApplicationMessageBuilder.cs b/Source/MQTTnet/MqttApplicationMessageBuilder.cs index 7e48531f..5254dd19 100644 --- a/Source/MQTTnet/MqttApplicationMessageBuilder.cs +++ b/Source/MQTTnet/MqttApplicationMessageBuilder.cs @@ -11,18 +11,102 @@ namespace MQTTnet { public class MqttApplicationMessageBuilder { - private MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce; - private string _topic; - private byte[] _payload; - private bool _retain; - private string _contentType; - private string _responseTopic; - private byte[] _correlationData; - private ushort? _topicAlias; - private List _subscriptionIdentifiers; - private uint? _messageExpiryInterval; - private MqttPayloadFormatIndicator? _payloadFormatIndicator; - private List _userProperties; + /// + /// The quality of service level. + /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message that defines the guarantee of delivery for a specific message. + /// There are 3 QoS levels in MQTT: + /// - At most once (0): Message gets delivered no time, once or multiple times. + /// - At least once (1): Message gets delivered at least once (one time or more often). + /// - Exactly once (2): Message gets delivered exactly once (It's ensured that the message only comes once). + /// + MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce; + + /// + /// The MQTT topic. + /// In MQTT, the word topic refers to an UTF-8 string that the broker uses to filter messages for each connected client. + /// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level separator). + /// + string _topic; + + /// + /// The payload. + /// The payload is the data bytes sent via the MQTT protocol. + /// + byte[] _payload; + + /// + /// A value indicating whether the message should be retained or not. + /// A retained message is a normal MQTT message with the retained flag set to true. + /// The broker stores the last retained message and the corresponding QoS for that topic. + /// + bool _retain; + + bool _dup; + + /// + /// The content type. + /// The content type must be a UTF-8 encoded string. The content type value identifies the kind of UTF-8 encoded payload. + /// + string _contentType; + + /// + /// The response topic. + /// In MQTT 5 the ability to publish a response topic was added in the publish message which allows you to implement the request/response pattern between clients that is common in web applications. + /// Hint: MQTT 5 feature only. + /// + string _responseTopic; + + /// + /// The correlation data. + /// In order for the sender to know what sent message the response refers to it can also send correlation data with the published message. + /// Hint: MQTT 5 feature only. + /// + byte[] _correlationData; + + /// + /// The topic alias. + /// Topic aliases were introduced are a mechanism for reducing the size of published packets by reducing the size of the topic field. + /// Hint: MQTT 5 feature only. + /// + ushort? _topicAlias; + + /// + /// The subscription identifiers. + /// The client can specify a subscription identifier when subscribing. + /// The broker will establish and store the mapping relationship between this subscription and subscription identifier when successfully create or modify subscription. + /// The broker will return the subscription identifier associated with this PUBLISH packet and the PUBLISH packet to the client when need to forward PUBLISH packets matching this subscription to this client. + /// Hint: MQTT 5 feature only. + /// + List _subscriptionIdentifiers; + + /// + /// The message expiry interval. + /// A client can set the message expiry interval in seconds for each PUBLISH message individually. + /// This interval defines the period of time that the broker stores the PUBLISH message for any matching subscribers that are not currently connected. + /// When no message expiry interval is set, the broker must store the message for matching subscribers indefinitely. + /// When the retained=true option is set on the PUBLISH message, this interval also defines how long a message is retained on a topic. + /// Hint: MQTT 5 feature only. + /// + uint? _messageExpiryInterval; + + /// + /// The payload format indicator. + /// The payload format indicator is part of any MQTT packet that can contain a payload. The indicator is an optional byte value. + /// A value of 0 indicates an “unspecified byte stream”. + /// A value of 1 indicates a "UTF-8 encoded payload". + /// If no payload format indicator is provided, the default value is 0. + /// Hint: MQTT 5 feature only. + /// + MqttPayloadFormatIndicator? _payloadFormatIndicator; + + /// + /// The user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// + /// Hint: MQTT 5 feature only. + List _userProperties; public MqttApplicationMessageBuilder WithTopic(string topic) { @@ -44,12 +128,7 @@ namespace MQTTnet return this; } - _payload = payload as byte[]; - - if (_payload == null) - { - _payload = payload.ToArray(); - } + _payload = payload as byte[] ?? payload.ToArray(); return this; } @@ -119,6 +198,12 @@ namespace MQTTnet _retain = value; return this; } + + public MqttApplicationMessageBuilder WithDupFlag(bool value = true) + { + _dup = value; + return this; + } public MqttApplicationMessageBuilder WithAtLeastOnceQoS() { @@ -139,8 +224,12 @@ namespace MQTTnet } /// - /// This is only supported when using MQTTv5. + /// Adds the user property to the message. + /// Hint: MQTT 5 feature only. /// + /// The property name. + /// The property value. + /// A new instance of the class. public MqttApplicationMessageBuilder WithUserProperty(string name, string value) { if (_userProperties == null) @@ -153,8 +242,10 @@ namespace MQTTnet } /// - /// This is only supported when using MQTTv5. + /// Adds the content type to the message. + /// Hint: MQTT 5 feature only. /// + /// A new instance of the class. public MqttApplicationMessageBuilder WithContentType(string contentType) { _contentType = contentType; @@ -162,8 +253,11 @@ namespace MQTTnet } /// - /// This is only supported when using MQTTv5. + /// Adds the response topic to the message. + /// Hint: MQTT 5 feature only. /// + /// The response topic. + /// A new instance of the class. public MqttApplicationMessageBuilder WithResponseTopic(string responseTopic) { _responseTopic = responseTopic; @@ -171,8 +265,11 @@ namespace MQTTnet } /// - /// This is only supported when using MQTTv5. + /// Adds the correlation data to the message. + /// Hint: MQTT 5 feature only. /// + /// The correlation data. + /// A new instance of the class. public MqttApplicationMessageBuilder WithCorrelationData(byte[] correlationData) { _correlationData = correlationData; @@ -180,8 +277,11 @@ namespace MQTTnet } /// - /// This is only supported when using MQTTv5. + /// Adds the topic alias to the message. + /// Hint: MQTT 5 feature only. /// + /// The topic alias. + /// A new instance of the class. public MqttApplicationMessageBuilder WithTopicAlias(ushort topicAlias) { _topicAlias = topicAlias; @@ -189,8 +289,11 @@ namespace MQTTnet } /// - /// This is only supported when using MQTTv5. + /// Adds the subscription identifier to the message. + /// Hint: MQTT 5 feature only. /// + /// The subscription identifier. + /// A new instance of the class. public MqttApplicationMessageBuilder WithSubscriptionIdentifier(uint subscriptionIdentifier) { if (_subscriptionIdentifiers == null) @@ -203,8 +306,11 @@ namespace MQTTnet } /// - /// This is only supported when using MQTTv5. + /// Adds the message expiry interval to the message. + /// Hint: MQTT 5 feature only. /// + /// The message expiry interval. + /// A new instance of the class. public MqttApplicationMessageBuilder WithMessageExpiryInterval(uint messageExpiryInterval) { _messageExpiryInterval = messageExpiryInterval; @@ -212,8 +318,11 @@ namespace MQTTnet } /// - /// This is only supported when using MQTTv5. + /// Adds the payload format indicator to the message. + /// Hint: MQTT 5 feature only. /// + /// The payload format indicator. + /// A new instance of the class. public MqttApplicationMessageBuilder WithPayloadFormatIndicator(MqttPayloadFormatIndicator payloadFormatIndicator) { _payloadFormatIndicator = payloadFormatIndicator; @@ -232,12 +341,18 @@ namespace MQTTnet throw new MqttProtocolViolationException("A Topic Alias of 0 is not permitted. A sender MUST NOT send a PUBLISH packet containing a Topic Alias which has the value 0 [MQTT-3.3.2-8]."); } + if (_qualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce && _dup) + { + throw new MqttProtocolViolationException("The DUP flag MUST be set to 0 for all QoS 0 messages [MQTT-3.3.1-2]."); + } + var applicationMessage = new MqttApplicationMessage { Topic = _topic, Payload = _payload, QualityOfServiceLevel = _qualityOfServiceLevel, Retain = _retain, + Dup = _dup, ContentType = _contentType, ResponseTopic = _responseTopic, CorrelationData = _correlationData, diff --git a/Source/MQTTnet/MqttApplicationMessageReceivedEventArgs.cs b/Source/MQTTnet/MqttApplicationMessageReceivedEventArgs.cs index 65673064..bd80dc60 100644 --- a/Source/MQTTnet/MqttApplicationMessageReceivedEventArgs.cs +++ b/Source/MQTTnet/MqttApplicationMessageReceivedEventArgs.cs @@ -11,12 +11,26 @@ namespace MQTTnet ApplicationMessage = applicationMessage ?? throw new ArgumentNullException(nameof(applicationMessage)); } + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; } public MqttApplicationMessage ApplicationMessage { get; } public bool ProcessingFailed { get; set; } + public MqttApplicationMessageReceivedReasonCode ReasonCode { get; set; } = MqttApplicationMessageReceivedReasonCode.Success; + + /// + /// Gets or sets whether this message was handled. + /// This value can be used in user code for custom control flow. + /// + public bool IsHandled { get; set; } + + public object Tag { get; set; } + public Task PendingTask { get; set; } } } diff --git a/Source/MQTTnet/MqttApplicationMessageReceivedReasonCode.cs b/Source/MQTTnet/MqttApplicationMessageReceivedReasonCode.cs new file mode 100644 index 00000000..3cd6e69d --- /dev/null +++ b/Source/MQTTnet/MqttApplicationMessageReceivedReasonCode.cs @@ -0,0 +1,16 @@ +namespace MQTTnet +{ + public enum MqttApplicationMessageReceivedReasonCode + { + Success = 0, + NoMatchingSubscribers = 16, + UnspecifiedError = 128, + ImplementationSpecificError = 131, + NotAuthorized = 135, + TopicNameInvalid = 144, + PacketIdentifierInUse = 145, + PacketIdentifierNotFound = 146, + QuotaExceeded = 151, + PayloadFormatInvalid = 153 + } +} \ No newline at end of file diff --git a/Source/MQTTnet/MqttTopicFilter.cs b/Source/MQTTnet/MqttTopicFilter.cs index 66ea94a4..fda60e0a 100644 --- a/Source/MQTTnet/MqttTopicFilter.cs +++ b/Source/MQTTnet/MqttTopicFilter.cs @@ -10,22 +10,38 @@ namespace MQTTnet public class MqttTopicFilter { + /// + /// Gets or sets the MQTT topic. + /// In MQTT, the word topic refers to an UTF-8 string that the broker uses to filter messages for each connected client. + /// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level separator). + /// public string Topic { get; set; } + /// + /// Gets or sets the quality of service level. + /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message that defines the guarantee of delivery for a specific message. + /// There are 3 QoS levels in MQTT: + /// - At most once (0): Message gets delivered no time, once or multiple times. + /// - At least once (1): Message gets delivered at least once (one time or more often). + /// - Exactly once (2): Message gets delivered exactly once (It's ensured that the message only comes once). + /// public MqttQualityOfServiceLevel QualityOfServiceLevel { get; set; } /// - /// This is only supported when using MQTTv5. + /// Gets or sets a value indicating whether to not send messages originating on this client (noLocal) or not. /// + /// Hint: MQTT 5 feature only. public bool? NoLocal { get; set; } /// - /// This is only supported when using MQTTv5. + /// Gets or sets a value indicating whether messages are retained as published or not. + /// Hint: MQTT 5 feature only. /// public bool? RetainAsPublished { get; set; } /// - /// This is only supported when using MQTTv5. + /// Gets or sets the retain handling. + /// Hint: MQTT 5 feature only. /// public MqttRetainHandling? RetainHandling { get; set; } diff --git a/Source/MQTTnet/MqttTopicFilterBuilder.cs b/Source/MQTTnet/MqttTopicFilterBuilder.cs index 712f25da..0143c411 100644 --- a/Source/MQTTnet/MqttTopicFilterBuilder.cs +++ b/Source/MQTTnet/MqttTopicFilterBuilder.cs @@ -11,8 +11,25 @@ namespace MQTTnet public class MqttTopicFilterBuilder { + /// + /// The quality of service level. + /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message that defines the guarantee of delivery for a specific message. + /// There are 3 QoS levels in MQTT: + /// - At most once (0): Message gets delivered no time, once or multiple times. + /// - At least once (1): Message gets delivered at least once (one time or more often). + /// - Exactly once (2): Message gets delivered exactly once (It's ensured that the message only comes once). + /// MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce; + + /// + /// The MQTT topic. + /// In MQTT, the word topic refers to an UTF-8 string that the broker uses to filter messages for each connected client. + /// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level separator). + /// string _topic; + bool? _noLocal; + bool? _retainAsPublished; + MqttRetainHandling? _retainHandling; public MqttTopicFilterBuilder WithTopic(string topic) { @@ -44,6 +61,24 @@ namespace MQTTnet return this; } + public MqttTopicFilterBuilder WithNoLocal(bool? value = true) + { + _noLocal = value; + return this; + } + + public MqttTopicFilterBuilder WithRetainAsPublished(bool? value = true) + { + _retainAsPublished = value; + return this; + } + + public MqttTopicFilterBuilder WithRetainHandling(MqttRetainHandling? value) + { + _retainHandling = value; + return this; + } + public MqttTopicFilter Build() { if (string.IsNullOrEmpty(_topic)) @@ -51,7 +86,14 @@ namespace MQTTnet throw new MqttProtocolViolationException("Topic is not set."); } - return new MqttTopicFilter { Topic = _topic, QualityOfServiceLevel = _qualityOfServiceLevel }; + return new MqttTopicFilter + { + Topic = _topic, + QualityOfServiceLevel = _qualityOfServiceLevel, + NoLocal = _noLocal, + RetainAsPublished = _retainAsPublished, + RetainHandling = _retainHandling + }; } } } diff --git a/Source/MQTTnet/Packets/MqttPingReqPacket.cs b/Source/MQTTnet/Packets/MqttPingReqPacket.cs index 459e8b91..18a3a162 100644 --- a/Source/MQTTnet/Packets/MqttPingReqPacket.cs +++ b/Source/MQTTnet/Packets/MqttPingReqPacket.cs @@ -3,7 +3,7 @@ public sealed class MqttPingReqPacket : MqttBasePacket { // This is a minor performance improvement. - public static MqttPingReqPacket Instance = new MqttPingReqPacket(); + public static readonly MqttPingReqPacket Instance = new MqttPingReqPacket(); public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttPingRespPacket.cs b/Source/MQTTnet/Packets/MqttPingRespPacket.cs index de1db5e2..8ddc349f 100644 --- a/Source/MQTTnet/Packets/MqttPingRespPacket.cs +++ b/Source/MQTTnet/Packets/MqttPingRespPacket.cs @@ -3,7 +3,7 @@ public sealed class MqttPingRespPacket : MqttBasePacket { // This is a minor performance improvement. - public static MqttPingRespPacket Instance = new MqttPingRespPacket(); + public static readonly MqttPingRespPacket Instance = new MqttPingRespPacket(); public override string ToString() { diff --git a/Source/MQTTnet/Server/CheckSubscriptionsResult.cs b/Source/MQTTnet/Server/CheckSubscriptionsResult.cs index b6e7dbd8..eb66f17e 100644 --- a/Source/MQTTnet/Server/CheckSubscriptionsResult.cs +++ b/Source/MQTTnet/Server/CheckSubscriptionsResult.cs @@ -8,6 +8,14 @@ namespace MQTTnet.Server public bool IsSubscribed { get; set; } + /// + /// Gets or sets the quality of service level. + /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message that defines the guarantee of delivery for a specific message. + /// There are 3 QoS levels in MQTT: + /// - At most once (0): Message gets delivered no time, once or multiple times. + /// - At least once (1): Message gets delivered at least once (one time or more often). + /// - Exactly once (2): Message gets delivered exactly once (It's ensured that the message only comes once). + /// public MqttQualityOfServiceLevel QualityOfServiceLevel { get; set; } } } diff --git a/Source/MQTTnet/Server/IMqttClientSession.cs b/Source/MQTTnet/Server/IMqttClientSession.cs index d7db2b13..f522df68 100644 --- a/Source/MQTTnet/Server/IMqttClientSession.cs +++ b/Source/MQTTnet/Server/IMqttClientSession.cs @@ -4,6 +4,10 @@ namespace MQTTnet.Server { public interface IMqttClientSession { + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// string ClientId { get; } Task StopAsync(); diff --git a/Source/MQTTnet/Server/IMqttServerOptions.cs b/Source/MQTTnet/Server/IMqttServerOptions.cs index 233048e5..cd0cd40b 100644 --- a/Source/MQTTnet/Server/IMqttServerOptions.cs +++ b/Source/MQTTnet/Server/IMqttServerOptions.cs @@ -4,6 +4,10 @@ namespace MQTTnet.Server { public interface IMqttServerOptions { + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// string ClientId { get; set; } bool EnablePersistentSessions { get; } diff --git a/Source/MQTTnet/Server/IMqttServerPersistedSession.cs b/Source/MQTTnet/Server/IMqttServerPersistedSession.cs index 9ca40761..a7b015ef 100644 --- a/Source/MQTTnet/Server/IMqttServerPersistedSession.cs +++ b/Source/MQTTnet/Server/IMqttServerPersistedSession.cs @@ -5,14 +5,26 @@ namespace MQTTnet.Server { public interface IMqttServerPersistedSession { + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// string ClientId { get; } IDictionary Items { get; } IList Subscriptions { get; } + /// + /// Gets the last will message. + /// In MQTT, you use the last will message feature to notify other clients about an ungracefully disconnected client. + /// MqttApplicationMessage WillMessage { get; } + /// + /// Gets the will delay interval. + /// This is the time between the client disconnect and the time the will message will be sent. + /// uint? WillDelayInterval { get; } DateTime? SessionExpiryTimestamp { get; } diff --git a/Source/MQTTnet/Server/MqttApplicationMessageInterceptorContext.cs b/Source/MQTTnet/Server/MqttApplicationMessageInterceptorContext.cs index cde9a855..f606a575 100644 --- a/Source/MQTTnet/Server/MqttApplicationMessageInterceptorContext.cs +++ b/Source/MQTTnet/Server/MqttApplicationMessageInterceptorContext.cs @@ -18,6 +18,10 @@ namespace MQTTnet.Server /// public IMqttNetScopedLogger Logger { get; } + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; } public MqttApplicationMessage ApplicationMessage { get; set; } diff --git a/Source/MQTTnet/Server/MqttClientConnection.cs b/Source/MQTTnet/Server/MqttClientConnection.cs index bd31f4b7..75083a54 100644 --- a/Source/MQTTnet/Server/MqttClientConnection.cs +++ b/Source/MQTTnet/Server/MqttClientConnection.cs @@ -13,6 +13,7 @@ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using MQTTnet.Client.Disconnecting; namespace MQTTnet.Server { @@ -42,7 +43,7 @@ namespace MQTTnet.Server long _sentPacketsCount = 1; // Start with 1 because the CONNECT packet is not counted anywhere. long _receivedApplicationMessagesCount; long _sentApplicationMessagesCount; - MqttDisconnectReasonCode _disconnectReason; + MqttClientDisconnectReason _disconnectReason; public MqttClientConnection(MqttConnectPacket connectPacket, IMqttChannelAdapter channelAdapter, @@ -84,12 +85,12 @@ namespace MQTTnet.Server public MqttClientSession Session { get; } - public async Task StopAsync(MqttDisconnectReasonCode reason) + public async Task StopAsync(MqttClientDisconnectReason reason) { Status = MqttClientConnectionStatus.Finalizing; _disconnectReason = reason; - if (reason == MqttDisconnectReasonCode.SessionTakenOver || reason == MqttDisconnectReasonCode.KeepAliveTimeout) + if (reason == MqttClientDisconnectReason.SessionTakenOver || reason == MqttClientDisconnectReason.KeepAliveTimeout) { // Is is very important to send the DISCONNECT packet here BEFORE cancelling the // token because the entire connection is closed (disposed) as soon as the cancellation @@ -97,10 +98,18 @@ namespace MQTTnet.Server // at the client! try { - await _channelAdapter.SendPacketAsync(new MqttDisconnectPacket + var disconnectOptions = new MqttClientDisconnectOptions { - ReasonCode = reason - }, CancellationToken.None).ConfigureAwait(false); + ReasonCode = reason, + ReasonString = reason.ToString() + }; + + var disconnectPacket = _channelAdapter.PacketFormatterAdapter.DataConverter.CreateDisconnectPacket(disconnectOptions); + + using (var timeout = new CancellationTokenSource(_serverOptions.DefaultCommunicationTimeout)) + { + await _channelAdapter.SendPacketAsync(disconnectPacket, timeout.Token).ConfigureAwait(false); + } } catch (Exception exception) { @@ -235,7 +244,7 @@ namespace MQTTnet.Server } finally { - if (_disconnectReason == MqttDisconnectReasonCode.SessionTakenOver) + if (_disconnectReason == MqttClientDisconnectReason.SessionTakenOver) { disconnectType = MqttClientDisconnectType.Takeover; } @@ -277,12 +286,7 @@ namespace MQTTnet.Server Task HandleIncomingPubRelPacketAsync(MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken) { - var pubCompPacket = new MqttPubCompPacket - { - PacketIdentifier = pubRelPacket.PacketIdentifier, - ReasonCode = MqttPubCompReasonCode.Success - }; - + var pubCompPacket = _channelAdapter.PacketFormatterAdapter.DataConverter.CreatePubCompPacket(pubRelPacket, MqttApplicationMessageReceivedReasonCode.Success); return SendAsync(pubCompPacket, cancellationToken); } @@ -327,12 +331,12 @@ namespace MQTTnet.Server } case MqttQualityOfServiceLevel.AtLeastOnce: { - var pubAckPacket = _dataConverter.CreatePubAckPacket(publishPacket); + var pubAckPacket = _dataConverter.CreatePubAckPacket(publishPacket, MqttApplicationMessageReceivedReasonCode.Success); return SendAsync(pubAckPacket, cancellationToken); } case MqttQualityOfServiceLevel.ExactlyOnce: { - var pubRecPacket = _dataConverter.CreatePubRecPacket(publishPacket); + var pubRecPacket = _dataConverter.CreatePubRecPacket(publishPacket, MqttApplicationMessageReceivedReasonCode.Success); return SendAsync(pubRecPacket, cancellationToken); } default: @@ -441,13 +445,10 @@ namespace MQTTnet.Server using (var awaiter2 = _packetDispatcher.AddAwaiter(publishPacket.PacketIdentifier)) { await SendAsync(publishPacket, cancellationToken).ConfigureAwait(false); - await awaiter1.WaitOneAsync(_serverOptions.DefaultCommunicationTimeout).ConfigureAwait(false); + var pubRecPacket = await awaiter1.WaitOneAsync(_serverOptions.DefaultCommunicationTimeout).ConfigureAwait(false); - await SendAsync(new MqttPubRelPacket - { - PacketIdentifier = publishPacket.PacketIdentifier, - ReasonCode = MqttPubRelReasonCode.Success - }, cancellationToken).ConfigureAwait(false); + var pubRelPacket = _channelAdapter.PacketFormatterAdapter.DataConverter.CreatePubRelPacket(pubRecPacket, MqttApplicationMessageReceivedReasonCode.Success); + await SendAsync(pubRelPacket, cancellationToken).ConfigureAwait(false); await awaiter2.WaitOneAsync(_serverOptions.DefaultCommunicationTimeout).ConfigureAwait(false); } diff --git a/Source/MQTTnet/Server/MqttClientMessageQueueInterceptorContext.cs b/Source/MQTTnet/Server/MqttClientMessageQueueInterceptorContext.cs index 209f8c03..881666eb 100644 --- a/Source/MQTTnet/Server/MqttClientMessageQueueInterceptorContext.cs +++ b/Source/MQTTnet/Server/MqttClientMessageQueueInterceptorContext.cs @@ -20,6 +20,14 @@ namespace MQTTnet.Server public bool AcceptEnqueue { get; set; } = true; + /// + /// Gets or sets the supscription quality of service level. + /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message that defines the guarantee of delivery for a specific message. + /// There are 3 QoS levels in MQTT: + /// - At most once (0): Message gets delivered no time, once or multiple times. + /// - At least once (1): Message gets delivered at least once (one time or more often). + /// - Exactly once (2): Message gets delivered exactly once (It's ensured that the message only comes once). + /// public MqttQualityOfServiceLevel SubscriptionQualityOfServiceLevel { get; set; } } } diff --git a/Source/MQTTnet/Server/MqttClientSessionsManager.cs b/Source/MQTTnet/Server/MqttClientSessionsManager.cs index 619f65fc..2c3202bb 100644 --- a/Source/MQTTnet/Server/MqttClientSessionsManager.cs +++ b/Source/MQTTnet/Server/MqttClientSessionsManager.cs @@ -12,6 +12,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MQTTnet.Client.Disconnecting; using OperationCanceledException = System.OperationCanceledException; namespace MQTTnet.Server @@ -121,7 +122,7 @@ namespace MQTTnet.Server foreach (var connection in connections) { - await connection.StopAsync(MqttDisconnectReasonCode.NormalDisconnection).ConfigureAwait(false); + await connection.StopAsync(MqttClientDisconnectReason.NormalDisconnection).ConfigureAwait(false); } } @@ -211,7 +212,7 @@ namespace MQTTnet.Server if (connection != null) { - await connection.StopAsync(MqttDisconnectReasonCode.NormalDisconnection).ConfigureAwait(false); + await connection.StopAsync(MqttClientDisconnectReason.NormalDisconnection).ConfigureAwait(false); } _logger.Verbose("Session for client '{0}' deleted.", clientId); @@ -301,7 +302,7 @@ namespace MQTTnet.Server { if (clientConnection != null) { - await clientConnection.StopAsync(MqttDisconnectReasonCode.NormalDisconnection).ConfigureAwait(false); + await clientConnection.StopAsync(MqttClientDisconnectReason.NormalDisconnection).ConfigureAwait(false); } } @@ -424,7 +425,7 @@ namespace MQTTnet.Server _connections[connectPacket.ClientId] = connection; } - existingConnection?.StopAsync(MqttDisconnectReasonCode.SessionTakenOver).GetAwaiter().GetResult(); + existingConnection?.StopAsync(MqttClientDisconnectReason.SessionTakenOver).GetAwaiter().GetResult(); return connection; } diff --git a/Source/MQTTnet/Server/MqttConnectionValidatorContext.cs b/Source/MQTTnet/Server/MqttConnectionValidatorContext.cs index 9a5b8b95..e9d6aebc 100644 --- a/Source/MQTTnet/Server/MqttConnectionValidatorContext.cs +++ b/Source/MQTTnet/Server/MqttConnectionValidatorContext.cs @@ -21,6 +21,10 @@ namespace MQTTnet.Server SessionItems = sessionItems; } + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId => _connectPacket.ClientId; public string Endpoint => _clientAdapter.Endpoint; @@ -37,30 +41,88 @@ namespace MQTTnet.Server public string Password => Encoding.UTF8.GetString(RawPassword ?? new byte[0]); + /// + /// Gets or sets the will delay interval. + /// This is the time between the client disconnect and the time the will message will be sent. + /// public MqttApplicationMessage WillMessage => _connectPacket?.WillMessage; + /// + /// Gets or sets a value indicating whether clean sessions are used or not. + /// When a client connects to a broker it can connect using either a non persistent connection (clean session) or a persistent connection. + /// With a non persistent connection the broker doesn't store any subscription information or undelivered messages for the client. + /// This mode is ideal when the client only publishes messages. + /// It can also connect as a durable client using a persistent connection. + /// In this mode, the broker will store subscription information, and undelivered messages for the client. + /// public bool? CleanSession => _connectPacket?.CleanSession; + /// + /// Gets or sets the keep alive period. + /// The connection is normally left open by the client so that is can send and receive data at any time. + /// If no data flows over an open connection for a certain time period then the client will generate a PINGREQ and expect to receive a PINGRESP from the broker. + /// This message exchange confirms that the connection is open and working. + /// This period is known as the keep alive period. + /// public ushort? KeepAlivePeriod => _connectPacket?.KeepAlivePeriod; + /// + /// Gets or sets the user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List UserProperties => _connectPacket?.Properties?.UserProperties; + /// + /// Gets or sets the authentication data. + /// Hint: MQTT 5 feature only. + /// public byte[] AuthenticationData => _connectPacket?.Properties?.AuthenticationData; + /// + /// Gets or sets the authentication method. + /// Hint: MQTT 5 feature only. + /// public string AuthenticationMethod => _connectPacket?.Properties?.AuthenticationMethod; public uint? MaximumPacketSize => _connectPacket?.Properties?.MaximumPacketSize; + /// + /// Gets or sets the receive maximum. + /// This gives the maximum length of the receive messages. + /// public ushort? ReceiveMaximum => _connectPacket?.Properties?.ReceiveMaximum; + /// + /// Gets or sets the topic alias maximum. + /// This gives the maximum length of the topic alias. + /// public ushort? TopicAliasMaximum => _connectPacket?.Properties?.TopicAliasMaximum; + /// + /// Gets the request problem information. + /// Hint: MQTT 5 feature only. + /// public bool? RequestProblemInformation => _connectPacket?.Properties?.RequestProblemInformation; + /// + /// Gets the request response information. + /// Hint: MQTT 5 feature only. + /// public bool? RequestResponseInformation => _connectPacket?.Properties?.RequestResponseInformation; + /// + /// Gets the session expiry interval. + /// The time after a session expires when it's not actively used. + /// public uint? SessionExpiryInterval => _connectPacket?.Properties?.SessionExpiryInterval; + /// + /// Gets or sets the will delay interval. + /// This is the time between the client disconnect and the time the will message will be sent. + /// public uint? WillDelayInterval => _connectPacket?.Properties?.WillDelayInterval; /// @@ -79,14 +141,26 @@ namespace MQTTnet.Server } /// - /// This is used for MQTTv5 only. When a MQTTv3 client connects the enum value must be one which is + /// Gets or sets the reason code. When a MQTTv3 client connects the enum value must be one which is /// also supported in MQTTv3. Otherwise the connection attempt will fail because not all codes can be /// converted properly. + /// Hint: MQTT 5 feature only. /// public MqttConnectReasonCode ReasonCode { get; set; } = MqttConnectReasonCode.Success; + /// + /// Gets or sets the response user properties. + /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet. + /// As long as you don’t exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber. + /// The feature is very similar to the HTTP header concept. + /// Hint: MQTT 5 feature only. + /// public List ResponseUserProperties { get; set; } + /// + /// Gets or sets the response authentication data. + /// Hint: MQTT 5 feature only. + /// public byte[] ResponseAuthenticationData { get; set; } public string AssignedClientIdentifier { get; set; } diff --git a/Source/MQTTnet/Server/MqttQueuedApplicationMessage.cs b/Source/MQTTnet/Server/MqttQueuedApplicationMessage.cs index 635894b3..5ca163dc 100644 --- a/Source/MQTTnet/Server/MqttQueuedApplicationMessage.cs +++ b/Source/MQTTnet/Server/MqttQueuedApplicationMessage.cs @@ -11,6 +11,14 @@ namespace MQTTnet.Server public bool IsRetainedMessage { get; set; } + /// + /// Gets or sets the subscription quality of service level. + /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message that defines the guarantee of delivery for a specific message. + /// There are 3 QoS levels in MQTT: + /// - At most once (0): Message gets delivered no time, once or multiple times. + /// - At least once (1): Message gets delivered at least once (one time or more often). + /// - Exactly once (2): Message gets delivered exactly once (It's ensured that the message only comes once). + /// public MqttQualityOfServiceLevel SubscriptionQualityOfServiceLevel { get; set; } [Obsolete("Use 'SubscriptionQualityOfServiceLevel' instead.")] diff --git a/Source/MQTTnet/Server/MqttServerClientConnectedEventArgs.cs b/Source/MQTTnet/Server/MqttServerClientConnectedEventArgs.cs index 71c42c3e..88f0c558 100644 --- a/Source/MQTTnet/Server/MqttServerClientConnectedEventArgs.cs +++ b/Source/MQTTnet/Server/MqttServerClientConnectedEventArgs.cs @@ -9,6 +9,10 @@ namespace MQTTnet.Server ClientId = clientId ?? throw new ArgumentNullException(nameof(clientId)); } + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; } } } diff --git a/Source/MQTTnet/Server/MqttServerClientDisconnectedEventArgs.cs b/Source/MQTTnet/Server/MqttServerClientDisconnectedEventArgs.cs index 9e742749..d2e7fe55 100644 --- a/Source/MQTTnet/Server/MqttServerClientDisconnectedEventArgs.cs +++ b/Source/MQTTnet/Server/MqttServerClientDisconnectedEventArgs.cs @@ -9,7 +9,11 @@ namespace MQTTnet.Server ClientId = clientId ?? throw new ArgumentNullException(nameof(clientId)); DisconnectType = disconnectType; } - + + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; } public MqttClientDisconnectType DisconnectType { get; } diff --git a/Source/MQTTnet/Server/MqttServerClientSubscribedTopicEventArgs.cs b/Source/MQTTnet/Server/MqttServerClientSubscribedTopicEventArgs.cs index 94d6e264..3586b731 100644 --- a/Source/MQTTnet/Server/MqttServerClientSubscribedTopicEventArgs.cs +++ b/Source/MQTTnet/Server/MqttServerClientSubscribedTopicEventArgs.cs @@ -10,8 +10,16 @@ namespace MQTTnet.Server TopicFilter = topicFilter ?? throw new ArgumentNullException(nameof(topicFilter)); } + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; } + /// + /// Gets the topic filter. + /// The topic filter can contain topics and wildcards. + /// public MqttTopicFilter TopicFilter { get; } } } diff --git a/Source/MQTTnet/Server/MqttServerClientUnsubscribedTopicEventArgs.cs b/Source/MQTTnet/Server/MqttServerClientUnsubscribedTopicEventArgs.cs index bb78bb28..8ed1264f 100644 --- a/Source/MQTTnet/Server/MqttServerClientUnsubscribedTopicEventArgs.cs +++ b/Source/MQTTnet/Server/MqttServerClientUnsubscribedTopicEventArgs.cs @@ -10,8 +10,16 @@ namespace MQTTnet.Server TopicFilter = topicFilter ?? throw new ArgumentNullException(nameof(topicFilter)); } + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; } + /// + /// Gets or sets the topic filter. + /// The topic filter can contain topics and wildcards. + /// public string TopicFilter { get; } } } diff --git a/Source/MQTTnet/Server/MqttServerKeepAliveMonitor.cs b/Source/MQTTnet/Server/MqttServerKeepAliveMonitor.cs index bd6eaa0a..7f967e9e 100644 --- a/Source/MQTTnet/Server/MqttServerKeepAliveMonitor.cs +++ b/Source/MQTTnet/Server/MqttServerKeepAliveMonitor.cs @@ -3,8 +3,8 @@ using MQTTnet.Internal; using System; using System.Threading; using System.Threading.Tasks; +using MQTTnet.Client.Disconnecting; using MQTTnet.Implementations; -using MQTTnet.Protocol; namespace MQTTnet.Server { @@ -108,7 +108,7 @@ namespace MQTTnet.Server // We do not need to wait for the task so no await is needed. // Also the internal state of the connection must be swapped to "Finalizing" because the // next iteration of the keep alive timer happens. - var _ = connection.StopAsync(MqttDisconnectReasonCode.KeepAliveTimeout); + var _ = connection.StopAsync(MqttClientDisconnectReason.KeepAliveTimeout); } catch (Exception exception) { diff --git a/Source/MQTTnet/Server/MqttServerOptions.cs b/Source/MQTTnet/Server/MqttServerOptions.cs index 31f56e5d..ab52813d 100644 --- a/Source/MQTTnet/Server/MqttServerOptions.cs +++ b/Source/MQTTnet/Server/MqttServerOptions.cs @@ -8,6 +8,10 @@ namespace MQTTnet.Server public MqttServerTlsTcpEndpointOptions TlsEndpointOptions { get; } = new MqttServerTlsTcpEndpointOptions(); + /// + /// Gets or sets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; set; } public bool EnablePersistentSessions { get; set; } diff --git a/Source/MQTTnet/Server/MqttSubscriptionInterceptorContext.cs b/Source/MQTTnet/Server/MqttSubscriptionInterceptorContext.cs index 0d800c85..cc186e53 100644 --- a/Source/MQTTnet/Server/MqttSubscriptionInterceptorContext.cs +++ b/Source/MQTTnet/Server/MqttSubscriptionInterceptorContext.cs @@ -11,8 +11,16 @@ namespace MQTTnet.Server SessionItems = sessionItems; } + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; } + /// + /// Gets or sets the topic filter. + /// The topic filter can contain topics and wildcards. + /// public MqttTopicFilter TopicFilter { get; set; } /// diff --git a/Source/MQTTnet/Server/MqttTopicFilterComparer.cs b/Source/MQTTnet/Server/MqttTopicFilterComparer.cs index 4ba614d4..5b104b48 100644 --- a/Source/MQTTnet/Server/MqttTopicFilterComparer.cs +++ b/Source/MQTTnet/Server/MqttTopicFilterComparer.cs @@ -31,6 +31,13 @@ namespace MQTTnet.Server { return true; } + // Check for e.g. foo/ matching foo/# + if (sPos == sLen - 2 + && filter[sPos] == LevelSeparator + && filter[sPos + 1] == MultiLevelWildcard) + { + return true; + } } sPos++; diff --git a/Source/MQTTnet/Server/MqttUnsubscriptionInterceptorContext.cs b/Source/MQTTnet/Server/MqttUnsubscriptionInterceptorContext.cs index b33cbac6..e5f8d755 100644 --- a/Source/MQTTnet/Server/MqttUnsubscriptionInterceptorContext.cs +++ b/Source/MQTTnet/Server/MqttUnsubscriptionInterceptorContext.cs @@ -11,8 +11,17 @@ namespace MQTTnet.Server SessionItems = sessionItems; } + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; } + /// + /// Gets or sets the MQTT topic. + /// In MQTT, the word topic refers to an UTF-8 string that the broker uses to filter messages for each connected client. + /// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level separator). + /// public string Topic { get; set; } /// diff --git a/Source/MQTTnet/Server/Status/IMqttClientStatus.cs b/Source/MQTTnet/Server/Status/IMqttClientStatus.cs index d7debdc6..c080b510 100644 --- a/Source/MQTTnet/Server/Status/IMqttClientStatus.cs +++ b/Source/MQTTnet/Server/Status/IMqttClientStatus.cs @@ -6,6 +6,10 @@ namespace MQTTnet.Server.Status { public interface IMqttClientStatus { + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// string ClientId { get; } string Endpoint { get; } diff --git a/Source/MQTTnet/Server/Status/IMqttSessionStatus.cs b/Source/MQTTnet/Server/Status/IMqttSessionStatus.cs index 2ff996b1..115da130 100644 --- a/Source/MQTTnet/Server/Status/IMqttSessionStatus.cs +++ b/Source/MQTTnet/Server/Status/IMqttSessionStatus.cs @@ -5,6 +5,10 @@ namespace MQTTnet.Server.Status { public interface IMqttSessionStatus { + /// + /// Gets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// string ClientId { get; } long PendingApplicationMessagesCount { get; } diff --git a/Source/MQTTnet/Server/Status/MqttClientStatus.cs b/Source/MQTTnet/Server/Status/MqttClientStatus.cs index 9acfea3e..9f2f670e 100644 --- a/Source/MQTTnet/Server/Status/MqttClientStatus.cs +++ b/Source/MQTTnet/Server/Status/MqttClientStatus.cs @@ -1,7 +1,7 @@ using MQTTnet.Formatter; using System; using System.Threading.Tasks; -using MQTTnet.Protocol; +using MQTTnet.Client.Disconnecting; namespace MQTTnet.Server.Status { @@ -14,6 +14,10 @@ namespace MQTTnet.Server.Status _connection = connection ?? throw new ArgumentNullException(nameof(connection)); } + /// + /// Gets or sets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; set; } public string Endpoint { get; set; } @@ -42,7 +46,7 @@ namespace MQTTnet.Server.Status public Task DisconnectAsync() { - return _connection.StopAsync(MqttDisconnectReasonCode.NormalDisconnection); + return _connection.StopAsync(MqttClientDisconnectReason.NormalDisconnection); } public void ResetStatistics() diff --git a/Source/MQTTnet/Server/Status/MqttSessionStatus.cs b/Source/MQTTnet/Server/Status/MqttSessionStatus.cs index a523a37e..af5a6e88 100644 --- a/Source/MQTTnet/Server/Status/MqttSessionStatus.cs +++ b/Source/MQTTnet/Server/Status/MqttSessionStatus.cs @@ -15,6 +15,10 @@ namespace MQTTnet.Server.Status _sessionsManager = sessionsManager ?? throw new ArgumentNullException(nameof(sessionsManager)); } + /// + /// Gets or sets the client identifier. + /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. + /// public string ClientId { get; set; } public long PendingApplicationMessagesCount { get; set; } diff --git a/Tests/MQTTnet.Benchmarks/ChannelAdapterBenchmark.cs b/Tests/MQTTnet.Benchmarks/ChannelAdapterBenchmark.cs index cbba6436..d6906f4b 100644 --- a/Tests/MQTTnet.Benchmarks/ChannelAdapterBenchmark.cs +++ b/Tests/MQTTnet.Benchmarks/ChannelAdapterBenchmark.cs @@ -43,7 +43,7 @@ namespace MQTTnet.Benchmarks var channel = new TestMqttChannel(_stream); - _channelAdapter = new MqttChannelAdapter(channel, serializer, new MqttNetLogger()); + _channelAdapter = new MqttChannelAdapter(channel, serializer, null, new MqttNetLogger()); } [Benchmark] diff --git a/Tests/MQTTnet.Benchmarks/SerializerBenchmark.cs b/Tests/MQTTnet.Benchmarks/SerializerBenchmark.cs index 3de03fae..ff567e87 100644 --- a/Tests/MQTTnet.Benchmarks/SerializerBenchmark.cs +++ b/Tests/MQTTnet.Benchmarks/SerializerBenchmark.cs @@ -9,6 +9,7 @@ using MQTTnet.Channel; using MQTTnet.Formatter; using MQTTnet.Formatter.V3; using BenchmarkDotNet.Jobs; +using MQTTnet.Diagnostics; namespace MQTTnet.Benchmarks { @@ -48,19 +49,13 @@ namespace MQTTnet.Benchmarks { var channel = new BenchmarkMqttChannel(_serializedPacket); var fixedHeader = new byte[2]; - var reader = new MqttPacketReader(channel); + var reader = new MqttChannelAdapter(channel, new MqttPacketFormatterAdapter(new MqttPacketWriter()), null, new MqttNetLogger()); for (var i = 0; i < 10000; i++) { channel.Reset(); - var header = reader.ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader; - - var receivedPacket = new ReceivedMqttPacket( - header.Flags, - new MqttPacketBodyReader(_serializedPacket.Array, _serializedPacket.Count - header.RemainingLength, _serializedPacket.Array.Length), 0); - - _serializer.Decode(receivedPacket); + var header = reader.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult(); } } diff --git a/Tests/MQTTnet.Core.Tests/MqttPacketReader_Tests.cs b/Tests/MQTTnet.Core.Tests/MqttPacketReader_Tests.cs index c073cfc6..c160f4dc 100644 --- a/Tests/MQTTnet.Core.Tests/MqttPacketReader_Tests.cs +++ b/Tests/MQTTnet.Core.Tests/MqttPacketReader_Tests.cs @@ -1,23 +1,24 @@ -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using MQTTnet.Formatter; -using MQTTnet.Internal; +//using System.IO; +//using System.Threading; +//using System.Threading.Tasks; +//using Microsoft.VisualStudio.TestTools.UnitTesting; +//using MQTTnet.Formatter; +//using MQTTnet.Internal; -namespace MQTTnet.Tests -{ - [TestClass] - public class MqttPacketReader_Tests - { - [TestMethod] - public async Task MqttPacketReader_EmptyStream() - { - var fixedHeader = new byte[2]; - var reader = new MqttPacketReader(new TestMqttChannel(new MemoryStream())); - var readResult = await reader.ReadFixedHeaderAsync(fixedHeader, CancellationToken.None); +//namespace MQTTnet.Tests +//{ +// [TestClass] +// public class MqttPacketReader_Tests +// { +// [TestMethod] +// public async Task MqttPacketReader_EmptyStream() +// { +// var fixedHeader = new byte[2]; +// var reader = new MqttPacketReader(new TestMqttChannel(new MemoryStream())); +// var readResult = await reader.ReadFixedHeaderAsync(fixedHeader, CancellationToken.None); - Assert.IsTrue(readResult.ConnectionClosed); - } - } -} +// Assert.IsTrue(readResult.ConnectionClosed); +// } +// } +//} +// TODO: Fix diff --git a/Tests/MQTTnet.Core.Tests/MqttPacketSerializer_Tests.cs b/Tests/MQTTnet.Core.Tests/MqttPacketSerializer_Tests.cs index da3500be..e51c911c 100644 --- a/Tests/MQTTnet.Core.Tests/MqttPacketSerializer_Tests.cs +++ b/Tests/MQTTnet.Core.Tests/MqttPacketSerializer_Tests.cs @@ -6,6 +6,7 @@ using System.Text; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using MQTTnet.Adapter; +using MQTTnet.Diagnostics; using MQTTnet.Exceptions; using MQTTnet.Formatter; using MQTTnet.Formatter.V3; @@ -22,7 +23,7 @@ namespace MQTTnet.Tests [TestMethod] public void DetectVersionFromMqttConnectPacket() { - var p = new MqttConnectPacket + var packet = new MqttConnectPacket { ClientId = "XYZ", Password = Encoding.UTF8.GetBytes("PASS"), @@ -30,17 +31,26 @@ namespace MQTTnet.Tests KeepAlivePeriod = 123, CleanSession = true }; - var adapter = new MqttPacketFormatterAdapter(WriterFactory()); - - Assert.AreEqual(MqttProtocolVersion.V310, DeserializeAndDetectVersion(adapter, Serialize(p, MqttProtocolVersion.V310))); - Assert.AreEqual(MqttProtocolVersion.V311, DeserializeAndDetectVersion(adapter, Serialize(p, MqttProtocolVersion.V311))); - Assert.AreEqual(MqttProtocolVersion.V500, DeserializeAndDetectVersion(adapter, Serialize(p, MqttProtocolVersion.V500))); - + + Assert.AreEqual( + MqttProtocolVersion.V310, + DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttPacketWriter()), Serialize(packet, MqttProtocolVersion.V310))); + + Assert.AreEqual( + MqttProtocolVersion.V311, + DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttPacketWriter()), Serialize(packet, MqttProtocolVersion.V311))); + + Assert.AreEqual( + MqttProtocolVersion.V500, + DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttPacketWriter()), Serialize(packet, MqttProtocolVersion.V500))); + + var adapter = new MqttPacketFormatterAdapter(new MqttPacketWriter()); + var ex = Assert.ThrowsException(() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[0]))); Assert.AreEqual("CONNECT packet must have at least 7 bytes.", ex.Message); ex = Assert.ThrowsException(() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[7]))); Assert.AreEqual("Protocol '' not supported.", ex.Message); - ex = Assert.ThrowsException(() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[] { 255, 255, 0,0,0,0,0 }))); + ex = Assert.ThrowsException(() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[] { 255, 255, 0, 0, 0, 0, 0 }))); Assert.AreEqual("Expected at least 65537 bytes but there are only 7 bytes", ex.Message); } @@ -205,24 +215,28 @@ namespace MQTTnet.Tests Payload = payload }; - var buffer = serializer.Encode(publishPacket); - var testChannel = new TestMqttChannel(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count)); - var header = new MqttPacketReader(testChannel).ReadFixedHeaderAsync( - new byte[2], - CancellationToken.None).GetAwaiter().GetResult().FixedHeader; + var publishPacketCopy = Roundtrip(publishPacket); - var eof = buffer.Offset + buffer.Count; + //var buffer = serializer.Encode(publishPacket); + //var testChannel = new TestMqttChannel(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count)); - var receivedPacket = new ReceivedMqttPacket( - header.Flags, - new MqttPacketBodyReader(buffer.Array, eof - header.RemainingLength, buffer.Count + buffer.Offset), - 0); - var packet = (MqttPublishPacket)serializer.Decode(receivedPacket); + //var header = new MqttPacketReader(testChannel).ReadFixedHeaderAsync( + // new byte[2], + // CancellationToken.None).GetAwaiter().GetResult().FixedHeader; - Assert.AreEqual(publishPacket.Topic, packet.Topic); - Assert.IsTrue(publishPacket.Payload.SequenceEqual(packet.Payload)); + //var eof = buffer.Offset + buffer.Count; + + //var receivedPacket = new ReceivedMqttPacket( + // header.Flags, + // new MqttPacketBodyReader(buffer.Array, eof - header.RemainingLength, buffer.Count + buffer.Offset), + // 0); + + //var packet = (MqttPublishPacket)serializer.Decode(receivedPacket); + + Assert.AreEqual(publishPacket.Topic, publishPacketCopy.Topic); + Assert.IsTrue(publishPacket.Payload.SequenceEqual(publishPacketCopy.Payload)); } [TestMethod] @@ -262,7 +276,7 @@ namespace MQTTnet.Tests [TestMethod] public void SerializeV500_MqttPublishPacket() { - var prop = new MqttPublishPacketProperties {UserProperties = new List()}; + var prop = new MqttPublishPacketProperties { UserProperties = new List() }; prop.ResponseTopic = "/Response"; @@ -581,15 +595,14 @@ namespace MQTTnet.Tests DeserializeAndCompare(p, "sAIAew=="); } - private void SerializeAndCompare(MqttBasePacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311) + void SerializeAndCompare(MqttBasePacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311) { Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(Serialize(packet, protocolVersion))); } - private byte[] Serialize(MqttBasePacket packet, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311) + byte[] Serialize(MqttBasePacket packet, MqttProtocolVersion protocolVersion) { - var serializer = MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, WriterFactory()); - return Join(serializer.Encode(packet)); + return MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, WriterFactory()).Encode(packet).ToArray(); } protected virtual IMqttPacketWriter WriterFactory() @@ -602,83 +615,92 @@ namespace MQTTnet.Tests return new MqttPacketBodyReader(data, 0, data.Length); } - private void DeserializeAndCompare(MqttBasePacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311) + void DeserializeAndCompare(MqttBasePacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311) { var writer = WriterFactory(); var serializer = MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, writer); - var buffer1 = serializer.Encode(packet); - using (var headerStream = new MemoryStream(Join(buffer1))) + using (var headerStream = new MemoryStream(buffer1.ToArray())) { var channel = new TestMqttChannel(headerStream); - var fixedHeader = new byte[2]; - var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader; + var adapter = new MqttChannelAdapter(channel, new MqttPacketFormatterAdapter(protocolVersion, writer), null, new MqttNetLogger()); + var receivedPacket = adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult(); - using (var bodyStream = new MemoryStream(Join(buffer1), (int)headerStream.Position, header.RemainingLength)) - { - var reader = ReaderFactory(bodyStream.ToArray()); - var deserializedPacket = serializer.Decode(new ReceivedMqttPacket(header.Flags, reader, 0)); - var buffer2 = serializer.Encode(deserializedPacket); + var buffer2 = serializer.Encode(receivedPacket); - Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(Join(buffer2))); - } + Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(buffer2.ToArray())); + + //adapter.ReceivePacketAsync(CancellationToken.None); + //var fixedHeader = new byte[2]; + //var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader; + + //using (var bodyStream = new MemoryStream(Join(buffer1), (int)headerStream.Position, header.RemainingLength)) + //{ + // var reader = ReaderFactory(bodyStream.ToArray()); + // var deserializedPacket = serializer.Decode(new ReceivedMqttPacket(header.Flags, reader, 0)); + // var buffer2 = serializer.Encode(deserializedPacket); + + // Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(Join(buffer2))); + //} } } - private T Roundtrip(T packet, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311) - where T : MqttBasePacket + TPacket Roundtrip(TPacket packet, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311) + where TPacket : MqttBasePacket { var writer = WriterFactory(); - var serializer = MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, writer); + var buffer = serializer.Encode(packet); - var buffer1 = serializer.Encode(packet); + var channel = new TestMqttChannel(buffer.ToArray()); + var adapter = new MqttChannelAdapter(channel, new MqttPacketFormatterAdapter(protocolVersion, writer), null, new MqttNetLogger()); + return (TPacket)adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult(); - using (var headerStream = new MemoryStream(Join(buffer1))) - { - var channel = new TestMqttChannel(headerStream); - var fixedHeader = new byte[2]; + //using (var headerStream = new MemoryStream(buffer1.ToArray())) + //{ - var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader; - using (var bodyStream = new MemoryStream(Join(buffer1), (int)headerStream.Position, (int)header.RemainingLength)) - { - var reader = ReaderFactory(bodyStream.ToArray()); - return (T)serializer.Decode(new ReceivedMqttPacket(header.Flags, reader, 0)); - } - } + + + // //var fixedHeader = new byte[2]; + + // //var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader; + + // //using (var bodyStream = new MemoryStream(Join(buffer1), (int)headerStream.Position, (int)header.RemainingLength)) + // //{ + // // var reader = ReaderFactory(bodyStream.ToArray()); + // // return (T)serializer.Decode(new ReceivedMqttPacket(header.Flags, reader, 0)); + // //} + //} } - private MqttProtocolVersion DeserializeAndDetectVersion(MqttPacketFormatterAdapter adapter, byte[] buffer) + MqttProtocolVersion DeserializeAndDetectVersion(MqttPacketFormatterAdapter packetFormatterAdapter, byte[] buffer) { - using (var headerStream = new MemoryStream(buffer)) - { - var channel = new TestMqttChannel(headerStream); - var fixedHeader = new byte[2]; + var channel = new TestMqttChannel(buffer); + var adapter = new MqttChannelAdapter(channel, packetFormatterAdapter, null, new MqttNetLogger()); - var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader; + adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult(); + return packetFormatterAdapter.ProtocolVersion; - using (var bodyStream = new MemoryStream(buffer, (int)headerStream.Position, (int)header.RemainingLength)) - { - var reader = ReaderFactory(bodyStream.ToArray()); - var packet = new ReceivedMqttPacket(header.Flags, reader, 0); - adapter.DetectProtocolVersion(packet); - return adapter.ProtocolVersion; - } - } - } + //using (var headerStream = new MemoryStream(buffer)) + //{ - private static byte[] Join(params ArraySegment[] chunks) - { - var buffer = new MemoryStream(); - foreach (var chunk in chunks) - { - buffer.Write(chunk.Array, chunk.Offset, chunk.Count); - } - return buffer.ToArray(); + + + // //var fixedHeader = new byte[2]; + // //var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader; + + // //using (var bodyStream = new MemoryStream(buffer, (int)headerStream.Position, (int)header.RemainingLength)) + // //{ + // // var reader = ReaderFactory(bodyStream.ToArray()); + // // var packet = new ReceivedMqttPacket(header.Flags, reader, 0); + // // packetFormatterAdapter.DetectProtocolVersion(packet); + // // return adapter.ProtocolVersion; + // //} + //} } } } diff --git a/Tests/MQTTnet.Core.Tests/Server_Tests.cs b/Tests/MQTTnet.Core.Tests/Server_Tests.cs index bf761ae9..09f085bb 100644 --- a/Tests/MQTTnet.Core.Tests/Server_Tests.cs +++ b/Tests/MQTTnet.Core.Tests/Server_Tests.cs @@ -1,4 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting; using MQTTnet.Adapter; using MQTTnet.Client; using MQTTnet.Client.Connecting; @@ -6,6 +6,7 @@ using MQTTnet.Client.Disconnecting; using MQTTnet.Client.Options; using MQTTnet.Client.Receiving; using MQTTnet.Client.Subscribing; +using MQTTnet.Exceptions; using MQTTnet.Protocol; using MQTTnet.Server; using MQTTnet.Tests.Mockups; @@ -25,6 +26,55 @@ namespace MQTTnet.Tests { public TestContext TestContext { get; set; } + [TestMethod] + [DataRow("", null)] + [DataRow("", "")] + [DataRow(null, null)] + public async Task Use_Admissible_Credentials(string username, string password) + { + using (var testEnvironment = new TestEnvironment()) + { + await testEnvironment.StartServerAsync(); + + var client = testEnvironment.CreateClient(); + + var clientOptions = new MqttClientOptionsBuilder() + .WithTcpServer("localhost", testEnvironment.ServerPort) + .WithCredentials(username, password) + .Build(); + + var connectResult = await client.ConnectAsync(clientOptions); + + Assert.IsFalse(connectResult.IsSessionPresent); + Assert.IsTrue(client.IsConnected); + } + } + + [TestMethod] + public async Task Use_Username_Null_Password_Empty() + { + string username = null; + string password = string.Empty; + + using (var testEnvironment = new TestEnvironment()) + { + testEnvironment.IgnoreClientLogErrors = true; + + await testEnvironment.StartServerAsync(); + + var client = testEnvironment.CreateClient(); + + var clientOptions = new MqttClientOptionsBuilder() + .WithTcpServer("localhost", testEnvironment.ServerPort) + .WithCredentials(username, password) + .Build(); + + var ex = await Assert.ThrowsExceptionAsync(async () => await client.ConnectAsync(clientOptions)); + Assert.IsInstanceOfType(ex.InnerException, typeof(MqttProtocolViolationException)); + Assert.AreEqual("Error while authenticating. If the User Name Flag is set to 0, the Password Flag MUST be set to 0 [MQTT-3.1.2-22].", ex.Message, false); + } + } + [TestMethod] public async Task Use_Empty_Client_ID() { @@ -416,7 +466,7 @@ namespace MQTTnet.Tests public async Task Publish_Multiple_Clients() { var receivedMessagesCount = 0; - + using (var testEnvironment = new TestEnvironment(TestContext)) { await testEnvironment.StartServerAsync(); @@ -446,7 +496,7 @@ namespace MQTTnet.Tests } SpinWait.SpinUntil(() => receivedMessagesCount == 1000, TimeSpan.FromSeconds(20)); - + Assert.AreEqual(1000, receivedMessagesCount); } } diff --git a/Tests/MQTTnet.Core.Tests/TopicFilterComparer_Tests.cs b/Tests/MQTTnet.Core.Tests/TopicFilterComparer_Tests.cs index 35e85047..5fb3d44e 100644 --- a/Tests/MQTTnet.Core.Tests/TopicFilterComparer_Tests.cs +++ b/Tests/MQTTnet.Core.Tests/TopicFilterComparer_Tests.cs @@ -6,6 +6,20 @@ namespace MQTTnet.Tests [TestClass] public class TopicFilterComparer_Tests { + [TestMethod] + public void TopicFilterComparer_Plus_Match_With_Separator_Only() + { + //A Topic Name or Topic Filter consisting only of the ‘/’ character is valid + CompareAndAssert("A", "+", true); + } + + [TestMethod] + public void TopicFilterComparer_Hash_Match_With_Separator_Only() + { + //A Topic Name or Topic Filter consisting only of the ‘/’ character is valid + CompareAndAssert("/", "#", true); + } + [TestMethod] public void TopicFilterComparer_DirectMatch() { @@ -54,6 +68,12 @@ namespace MQTTnet.Tests CompareAndAssert("A/B/C/D", "A/C/#", false); } + [TestMethod] + public void TopicFilterComparer_EndMultipleLevelsWildcardMatchEmptyLevel() + { + CompareAndAssert("A/", "A/#", true); + } + [TestMethod] public void TopicFilterComparer_AllLevelsWildcardMatch() { diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/App.xaml b/Tests/MQTTnet.TestApp.UniversalWindows/App.xaml deleted file mode 100644 index bdd5cc0f..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/App.xaml +++ /dev/null @@ -1,6 +0,0 @@ - - diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/App.xaml.cs b/Tests/MQTTnet.TestApp.UniversalWindows/App.xaml.cs deleted file mode 100644 index 13b5d0b4..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/App.xaml.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Navigation; - -namespace MQTTnet.TestApp.UniversalWindows -{ - sealed partial class App - { - public App() - { - InitializeComponent(); - Suspending += OnSuspending; - } - - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - if (!(Window.Current.Content is Frame rootFrame)) - { - rootFrame = new Frame(); - - rootFrame.NavigationFailed += OnNavigationFailed; - - Window.Current.Content = rootFrame; - } - - if (e.PrelaunchActivated == false) - { - if (rootFrame.Content == null) - { - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - - Window.Current.Activate(); - } - } - - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - deferral.Complete(); - } - } -} diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/LockScreenLogo.scale-200.png b/Tests/MQTTnet.TestApp.UniversalWindows/Assets/LockScreenLogo.scale-200.png deleted file mode 100644 index 735f57ad..00000000 Binary files a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/LockScreenLogo.scale-200.png and /dev/null differ diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/SplashScreen.scale-200.png b/Tests/MQTTnet.TestApp.UniversalWindows/Assets/SplashScreen.scale-200.png deleted file mode 100644 index 023e7f1f..00000000 Binary files a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/SplashScreen.scale-200.png and /dev/null differ diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square150x150Logo.scale-200.png b/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square150x150Logo.scale-200.png deleted file mode 100644 index af49fec1..00000000 Binary files a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square150x150Logo.scale-200.png and /dev/null differ diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square44x44Logo.scale-200.png b/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square44x44Logo.scale-200.png deleted file mode 100644 index ce342a2e..00000000 Binary files a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square44x44Logo.scale-200.png and /dev/null differ diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square44x44Logo.targetsize-24_altform-unplated.png deleted file mode 100644 index f6c02ce9..00000000 Binary files a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Square44x44Logo.targetsize-24_altform-unplated.png and /dev/null differ diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/StoreLogo.png b/Tests/MQTTnet.TestApp.UniversalWindows/Assets/StoreLogo.png deleted file mode 100644 index 7385b56c..00000000 Binary files a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/StoreLogo.png and /dev/null differ diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Wide310x150Logo.scale-200.png b/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Wide310x150Logo.scale-200.png deleted file mode 100644 index 288995b3..00000000 Binary files a/Tests/MQTTnet.TestApp.UniversalWindows/Assets/Wide310x150Logo.scale-200.png and /dev/null differ diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/JsonServerStorage.cs b/Tests/MQTTnet.TestApp.UniversalWindows/JsonServerStorage.cs deleted file mode 100644 index 1c8434bf..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/JsonServerStorage.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using MQTTnet.Server; -using Newtonsoft.Json; - -namespace MQTTnet.TestApp.UniversalWindows -{ - public sealed class JsonServerStorage : IMqttServerStorage - { - readonly string _filename = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Retained.json"); - - public Task SaveRetainedMessagesAsync(IList messages) - { - var json = JsonConvert.SerializeObject(messages); - File.WriteAllText(_filename, json); - - return Task.CompletedTask; - } - - public async Task> LoadRetainedMessagesAsync() - { - await Task.CompletedTask; - - if (!File.Exists(_filename)) - { - return new List(); - } - - try - { - var json = File.ReadAllText(_filename); - return JsonConvert.DeserializeObject>(json); - } - catch - { - return new List(); - } - } - - public void Clear() - { - if (File.Exists(_filename)) - { - File.Delete(_filename); - } - } - } -} diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows.csproj b/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows.csproj deleted file mode 100644 index 3c8c989b..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows.csproj +++ /dev/null @@ -1,196 +0,0 @@ - - - - - Debug - x86 - {FF1F72D6-9524-4422-9497-3CC0002216ED} - AppContainerExe - Properties - MQTTnet.TestApp.UniversalWindows - MQTTnet.TestApp.UniversalWindows - en-US - UAP - 10.0.18362.0 - 10.0.10240.0 - 14 - 512 - {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - true - MQTTnet.TestApp.UniversalWindows_TemporaryKey.pfx - 1B25E1E3A70C4FEF793B882295F383301B861796 - win10;win10-arm;win10-arm-aot;win10-x86;win10-x86-aot;win10-x64;win10-x64-aot - True - - - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x86 - false - prompt - true - - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x86 - false - prompt - true - false - - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - ARM - false - prompt - true - - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - ARM - false - prompt - true - true - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x64 - false - prompt - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x64 - false - prompt - true - true - - - - App.xaml - - - - MainPage.xaml - - - - - - Designer - - - .editorconfig - - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - {C400533A-8EBA-4F0B-BF4D-295C3708604B} - MQTTnet.Extensions.ManagedClient - - - {c444e9c8-95fa-430e-9126-274129de16cd} - MQTTnet.Extensions.Rpc - - - {2BD01D53-4CA5-4142-BE8D-313876395E3E} - MQTTnet.Extensions.WebSocket4Net - - - {3587e506-55a2-4eb3-99c7-dc01e42d25d2} - MQTTnet - - - - - 6.2.10 - - - 4.0.0 - - - - 14.0 - - - true - bin\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP;CODE_ANALYSIS - ;2008 - true - full - x86 - false - prompt - MinimumRecommendedRules.ruleset - true - - - bin\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP;CODE_ANALYSIS - true - ;2008 - true - pdbonly - x86 - false - prompt - MinimumRecommendedRules.ruleset - true - - - - \ No newline at end of file diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows_TemporaryKey.pfx b/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows_TemporaryKey.pfx deleted file mode 100644 index b8877c01..00000000 Binary files a/Tests/MQTTnet.TestApp.UniversalWindows/MQTTnet.TestApp.UniversalWindows_TemporaryKey.pfx and /dev/null differ diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml b/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml deleted file mode 100644 index 11e68c65..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml +++ /dev/null @@ -1,266 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Server: - - - Port: - - - Username: - - - Password: - - - Client ID: - - - Keep Alive interval: - - - Transport: - - TCP - WS - WS (WebSocket4Net) - Use TLS - - - Protocol: - - 5.0.0 - 3.1.1 - 3.1.0 - - - - Clean session - Use managed client - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Topic: - - - Content type: - - - Payload: - - - Payload format: - - Plain text - Base64 string - - - QoS level: - - 0 (At most once) - 1 (At least once) - 2 (Exactly once) - - - Response topic: - - - - Retain - - - - - - - - Method: - - - Payload: - - - Text - Base64 - - - QoS: - - 0 (At most once) - 1 (At least once) - 2 (Exactly once) - - - Responses: - - - - - - - - - - - - - - - - - - Topic: - - - QoS: - - 0 (At most once) - 1 (At least once) - 2 (Exactly once) - - - Received messages: - Add received messages to list - - - - - - - - - - - - - - - - - - - Port: - - - Persist retained messages in JSON format - Clear previously retained messages on startup - Allow persistent sessions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs b/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs deleted file mode 100644 index 836e01f6..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/MainPage.xaml.cs +++ /dev/null @@ -1,834 +0,0 @@ -using MQTTnet.Client; -using MQTTnet.Client.Connecting; -using MQTTnet.Client.Disconnecting; -using MQTTnet.Client.Options; -using MQTTnet.Diagnostics; -using MQTTnet.Exceptions; -using MQTTnet.Extensions.ManagedClient; -using MQTTnet.Extensions.Rpc; -using MQTTnet.Extensions.Rpc.Options; -using MQTTnet.Extensions.WebSocket4Net; -using MQTTnet.Formatter; -using MQTTnet.Implementations; -using MQTTnet.Protocol; -using MQTTnet.Server; -using MQTTnet.Server.Status; -using System; -using System.Collections.Concurrent; -using System.Collections.ObjectModel; -using System.Text; -using System.Threading.Tasks; -using Windows.Security.Cryptography.Certificates; -using Windows.UI.Core; -using Windows.UI.Xaml; - -namespace MQTTnet.TestApp.UniversalWindows -{ - public sealed partial class MainPage - { - private readonly ConcurrentQueue _traceMessages = new ConcurrentQueue(); - private readonly ObservableCollection _sessions = new ObservableCollection(); - - private IMqttClient _mqttClient; - private IManagedMqttClient _managedMqttClient; - private IMqttServer _mqttServer; - - public MainPage() - { - InitializeComponent(); - - ClientId.Text = Guid.NewGuid().ToString("D"); - - MqttNetGlobalLogger.LogMessagePublished += OnTraceMessagePublished; - } - - private async void OnTraceMessagePublished(object sender, MqttNetLogMessagePublishedEventArgs e) - { - _traceMessages.Enqueue(e.LogMessage); - await UpdateLogAsync(); - } - - private async Task UpdateLogAsync() - { - while (_traceMessages.Count > 100) - { - _traceMessages.TryDequeue(out _); - } - - var logText = new StringBuilder(); - foreach (var traceMessage in _traceMessages) - { - logText.AppendFormat( - "[{0:yyyy-MM-dd HH:mm:ss.fff}] [{1}] [{2}] [{3}] [{4}]{5}", - traceMessage.Timestamp, - traceMessage.Level, - traceMessage.Source, - traceMessage.ThreadId, - traceMessage.Message, - Environment.NewLine); - - if (traceMessage.Exception != null) - { - logText.AppendLine(traceMessage.Exception.ToString()); - } - } - - await Trace.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => - { - Trace.Text = logText.ToString(); - }); - } - - private async void Connect(object sender, RoutedEventArgs e) - { - var mqttFactory = new MqttFactory(); - - var tlsOptions = new MqttClientTlsOptions - { - UseTls = UseTls.IsChecked == true, - IgnoreCertificateChainErrors = true, - IgnoreCertificateRevocationErrors = true, - AllowUntrustedCertificates = true - }; - - var options = new MqttClientOptions - { - ClientId = ClientId.Text, - ProtocolVersion = MqttProtocolVersion.V500 - }; - - if (UseTcp.IsChecked == true) - { - options.ChannelOptions = new MqttClientTcpOptions - { - Server = Server.Text, - Port = int.Parse(Port.Text), - TlsOptions = tlsOptions - }; - } - - if (UseWs.IsChecked == true) - { - options.ChannelOptions = new MqttClientWebSocketOptions - { - Uri = Server.Text, - TlsOptions = tlsOptions - }; - } - - if (UseWs4Net.IsChecked == true) - { - options.ChannelOptions = new MqttClientWebSocketOptions - { - Uri = Server.Text, - TlsOptions = tlsOptions - }; - - mqttFactory.UseWebSocket4Net(); - } - - if (options.ChannelOptions == null) - { - throw new InvalidOperationException(); - } - - if (!string.IsNullOrEmpty(User.Text)) - { - options.Credentials = new MqttClientCredentials - { - Username = User.Text, - Password = Encoding.UTF8.GetBytes(Password.Text) - }; - } - - options.CleanSession = CleanSession.IsChecked == true; - options.KeepAlivePeriod = TimeSpan.FromSeconds(double.Parse(KeepAliveInterval.Text)); - - if (UseMqtt310.IsChecked == true) - { - options.ProtocolVersion = MqttProtocolVersion.V310; - } - else if (UseMqtt311.IsChecked == true) - { - options.ProtocolVersion = MqttProtocolVersion.V311; - } - else if (UseMqtt500.IsChecked == true) - { - options.ProtocolVersion = MqttProtocolVersion.V500; - } - - try - { - if (_mqttClient != null) - { - await _mqttClient.DisconnectAsync(); - _mqttClient.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage); - _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected()); - _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected()); - } - - if (UseManagedClient.IsChecked == true) - { - _managedMqttClient = mqttFactory.CreateManagedMqttClient(); - _managedMqttClient.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage); - _managedMqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected()); - _managedMqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected()); - - await _managedMqttClient.StartAsync(new ManagedMqttClientOptions - { - ClientOptions = options - }); - } - else - { - _mqttClient = mqttFactory.CreateMqttClient(); - _mqttClient.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage); - _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected()); - _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnected()); - - await _mqttClient.ConnectAsync(options); - } - } - catch (Exception exception) - { - Trace.Text += exception + Environment.NewLine; - } - } - - private void OnDisconnected() - { - _traceMessages.Enqueue(new MqttNetLogMessage - { - Timestamp = DateTime.UtcNow, - ThreadId = -1, - Level = MqttNetLogLevel.Info, - Message = "! DISCONNECTED EVENT FIRED", - }); - - Task.Run(UpdateLogAsync); - } - - private void OnConnected() - { - _traceMessages.Enqueue(new MqttNetLogMessage - { - Timestamp = DateTime.UtcNow, - ThreadId = -1, - Level = MqttNetLogLevel.Info, - Message = "! CONNECTED EVENT FIRED", - }); - - Task.Run(UpdateLogAsync); - } - - private async Task HandleReceivedApplicationMessage(MqttApplicationMessageReceivedEventArgs eventArgs) - { - var item = $"Timestamp: {DateTime.Now:O} | Topic: {eventArgs.ApplicationMessage.Topic} | Payload: {eventArgs.ApplicationMessage.ConvertPayloadToString()} | QoS: {eventArgs.ApplicationMessage.QualityOfServiceLevel}"; - - await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => - { - if (AddReceivedMessagesToList.IsChecked == true) - { - ReceivedMessages.Items.Add(item); - } - }); - } - - private async void Publish(object sender, RoutedEventArgs e) - { - try - { - var qos = MqttQualityOfServiceLevel.AtMostOnce; - if (QoS1.IsChecked == true) - { - qos = MqttQualityOfServiceLevel.AtLeastOnce; - } - - if (QoS2.IsChecked == true) - { - qos = MqttQualityOfServiceLevel.ExactlyOnce; - } - - var payload = Array.Empty(); - if (PlainText.IsChecked == true) - { - payload = Encoding.UTF8.GetBytes(Payload.Text); - } - - if (Base64.IsChecked == true) - { - payload = Convert.FromBase64String(Payload.Text); - } - - var message = new MqttApplicationMessageBuilder() - .WithContentType(ContentType.Text) - .WithResponseTopic(ResponseTopic.Text) - .WithTopic(Topic.Text) - .WithPayload(payload) - .WithQualityOfServiceLevel(qos) - .WithRetainFlag(Retain.IsChecked == true) - .Build(); - - if (_mqttClient != null) - { - await _mqttClient.PublishAsync(message); - } - - if (_managedMqttClient != null) - { - await _managedMqttClient.PublishAsync(message); - } - } - catch (Exception exception) - { - Trace.Text += exception + Environment.NewLine; - } - } - - private async void Disconnect(object sender, RoutedEventArgs e) - { - try - { - if (_mqttClient != null) - { - await _mqttClient.DisconnectAsync(); - _mqttClient.Dispose(); - _mqttClient = null; - } - - if (_managedMqttClient != null) - { - await _managedMqttClient.StopAsync(); - _managedMqttClient.Dispose(); - _managedMqttClient = null; - } - } - catch (Exception exception) - { - Trace.Text += exception + Environment.NewLine; - } - } - - private void ClearLog(object sender, RoutedEventArgs e) - { - while (_traceMessages.Count > 0) - { - _traceMessages.TryDequeue(out _); - } - - Trace.Text = string.Empty; - } - - private async void Subscribe(object sender, RoutedEventArgs e) - { - try - { - var qos = MqttQualityOfServiceLevel.AtMostOnce; - if (SubscribeQoS1.IsChecked == true) - { - qos = MqttQualityOfServiceLevel.AtLeastOnce; - } - - if (SubscribeQoS2.IsChecked == true) - { - qos = MqttQualityOfServiceLevel.ExactlyOnce; - } - - var topicFilter = new MqttTopicFilter { Topic = SubscribeTopic.Text, QualityOfServiceLevel = qos }; - - if (_mqttClient != null) - { - await _mqttClient.SubscribeAsync(topicFilter); - } - - if (_managedMqttClient != null) - { - await _managedMqttClient.SubscribeAsync(topicFilter); - } - } - catch (Exception exception) - { - Trace.Text += exception + Environment.NewLine; - } - } - - private async void Unsubscribe(object sender, RoutedEventArgs e) - { - try - { - if (_mqttClient != null) - { - await _mqttClient.UnsubscribeAsync(SubscribeTopic.Text); - } - - if (_managedMqttClient != null) - { - await _managedMqttClient.UnsubscribeAsync(SubscribeTopic.Text); - } - } - catch (Exception exception) - { - Trace.Text += exception + Environment.NewLine; - } - } - - // This code is for the Wiki at GitHub! - // ReSharper disable once UnusedMember.Local - - private async void StartServer(object sender, RoutedEventArgs e) - { - if (_mqttServer != null) - { - return; - } - - JsonServerStorage storage = null; - if (ServerPersistRetainedMessages.IsChecked == true) - { - storage = new JsonServerStorage(); - - if (ServerClearRetainedMessages.IsChecked == true) - { - storage.Clear(); - } - } - - _mqttServer = new MqttFactory().CreateMqttServer(); - - var options = new MqttServerOptions(); - options.DefaultEndpointOptions.Port = int.Parse(ServerPort.Text); - options.Storage = storage; - options.EnablePersistentSessions = ServerAllowPersistentSessions.IsChecked == true; - - await _mqttServer.StartAsync(options); - } - - private async void StopServer(object sender, RoutedEventArgs e) - { - if (_mqttServer == null) - { - return; - } - - await _mqttServer.StopAsync(); - _mqttServer = null; - } - - private void ClearReceivedMessages(object sender, RoutedEventArgs e) - { - ReceivedMessages.Items.Clear(); - } - - private async void ExecuteRpc(object sender, RoutedEventArgs e) - { - var qos = MqttQualityOfServiceLevel.AtMostOnce; - if (RpcQoS1.IsChecked == true) - { - qos = MqttQualityOfServiceLevel.AtLeastOnce; - } - - if (RpcQoS2.IsChecked == true) - { - qos = MqttQualityOfServiceLevel.ExactlyOnce; - } - - var payload = Array.Empty(); - if (RpcText.IsChecked == true) - { - payload = Encoding.UTF8.GetBytes(RpcPayload.Text); - } - - if (RpcBase64.IsChecked == true) - { - payload = Convert.FromBase64String(RpcPayload.Text); - } - - try - { - var rpcClient = new MqttRpcClient(_mqttClient, new MqttRpcClientOptions()); - var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), RpcMethod.Text, payload, qos); - - RpcResponses.Items.Add(RpcMethod.Text + " >>> " + Encoding.UTF8.GetString(response)); - } - catch (MqttCommunicationTimedOutException) - { - RpcResponses.Items.Add(RpcMethod.Text + " >>> [TIMEOUT]"); - } - catch (Exception exception) - { - RpcResponses.Items.Add(RpcMethod.Text + " >>> [EXCEPTION (" + exception.Message + ")]"); - } - } - - private void ClearRpcResponses(object sender, RoutedEventArgs e) - { - RpcResponses.Items.Clear(); - } - - private void ClearSessions(object sender, RoutedEventArgs e) - { - _sessions.Clear(); - } - - private void RefreshSessions(object sender, RoutedEventArgs e) - { - if (_mqttServer == null) - { - return; - } - - var sessions = _mqttServer.GetClientStatusAsync().GetAwaiter().GetResult(); - _sessions.Clear(); - - foreach (var session in sessions) - { - _sessions.Add(session); - } - - ListViewSessions.DataContext = _sessions; - } - - #region Wiki Code - -#pragma warning disable IDE0051 // Remove unused private members - private async Task WikiCode() -#pragma warning restore IDE0051 // Remove unused private members - { - { - // Use a custom identifier for the trace messages. - var clientOptions = new MqttClientOptionsBuilder() - .Build(); - } - - { - // Create a new MQTT client. - var factory = new MqttFactory(); - var client = factory.CreateMqttClient(); - - // Create TCP based options using the builder. - var options = new MqttClientOptionsBuilder() - .WithClientId("Client1") - .WithTcpServer("broker.hivemq.com") - .WithCredentials("bud", "%spencer%") - .WithTls() - .WithCleanSession() - .Build(); - - await client.ConnectAsync(options); - - // Reconnecting - - client.UseDisconnectedHandler(async e => - { - Console.WriteLine("### DISCONNECTED FROM SERVER ###"); - await Task.Delay(TimeSpan.FromSeconds(5)); - - try - { - await client.ConnectAsync(options); - } - catch - { - Console.WriteLine("### RECONNECTING FAILED ###"); - } - }); - - // Consuming messages - - client.UseApplicationMessageReceivedHandler(e => - { - Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); - Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}"); - Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); - Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); - Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); - Console.WriteLine(); - }); - - void Handler(MqttApplicationMessageReceivedEventArgs args) - { - //... - } - - client.UseApplicationMessageReceivedHandler(e => Handler(e)); - - // Subscribe after connect - - client.UseConnectedHandler(async e => - { - Console.WriteLine("### CONNECTED WITH SERVER ###"); - - // Subscribe to a topic - await client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").Build()); - - Console.WriteLine("### SUBSCRIBED ###"); - }); - - // Subscribe to a topic - await client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").Build()); - - // Unsubscribe from a topic - await client.UnsubscribeAsync("my/topic"); - - // Publish an application message - var applicationMessage = new MqttApplicationMessageBuilder() - .WithTopic("A/B/C") - .WithPayload("Hello World") - .WithAtLeastOnceQoS() - .Build(); - - await client.PublishAsync(applicationMessage); - } - - { - - { - // Use TCP connection. - var options = new MqttClientOptionsBuilder() - .WithTcpServer("broker.hivemq.com", 1883) // Port is optional - .Build(); - } - - { - // Use secure TCP connection. - var options = new MqttClientOptionsBuilder() - .WithTcpServer("broker.hivemq.com") - .WithTls() - .Build(); - } - - { - // Use WebSocket connection. - var options = new MqttClientOptionsBuilder() - .WithWebSocketServer("broker.hivemq.com:8000/mqtt") - .Build(); - } - - { - // Create TCP based options manually - var options = new MqttClientOptions - { - ClientId = "Client1", - Credentials = new MqttClientCredentials - { - Username = "bud", - Password = Encoding.UTF8.GetBytes("%spencer%") - }, - ChannelOptions = new MqttClientTcpOptions - { - Server = "broker.hivemq.org", - TlsOptions = new MqttClientTlsOptions - { - UseTls = true - } - }, - }; - } - } - - // ---------------------------------- - { - var options = new MqttServerOptions - { - ConnectionValidator = new MqttServerConnectionValidatorDelegate(c => - { - if (c.ClientId.Length < 10) - { - c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid; - return; - } - - if (c.Username != "mySecretUser") - { - c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; - return; - } - - if (c.Password != "mySecretPassword") - { - c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; - return; - } - - c.ReasonCode = MqttConnectReasonCode.Success; - }) - }; - - var factory = new MqttFactory(); - var mqttServer = factory.CreateMqttServer(); - await mqttServer.StartAsync(options); - - Console.WriteLine("Press any key to exit."); - Console.ReadLine(); - - await mqttServer.StopAsync(); - } - - // ---------------------------------- - - // For UWP apps: - MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o => - { - if (o.Server == "server_with_revoked_cert") - { - return new[] { ChainValidationResult.Revoked }; - } - - return Array.Empty(); - }; - - { - // Start a MQTT server. - var mqttServer = new MqttFactory().CreateMqttServer(); - await mqttServer.StartAsync(new MqttServerOptions()); - Console.WriteLine("Press any key to exit."); - Console.ReadLine(); - await mqttServer.StopAsync(); - } - - { - // Configure MQTT server. - var optionsBuilder = new MqttServerOptionsBuilder() - .WithConnectionBacklog(100) - .WithDefaultEndpointPort(1884); - - var options = new MqttServerOptions - { - }; - - options.ConnectionValidator = new MqttServerConnectionValidatorDelegate(c => - { - if (c.ClientId != "Highlander") - { - c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid; - return; - } - - c.ReasonCode = MqttConnectReasonCode.Success; - }); - - var mqttServer = new MqttFactory().CreateMqttServer(); - await mqttServer.StartAsync(optionsBuilder.Build()); - } - - { - // Setup client validator. - var options = new MqttServerOptions - { - ConnectionValidator = new MqttServerConnectionValidatorDelegate(c => - { - if (c.ClientId.Length < 10) - { - c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid; - return; - } - - if (c.Username != "mySecretUser") - { - c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; - return; - } - - if (c.Password != "mySecretPassword") - { - c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; - return; - } - - c.ReasonCode = MqttConnectReasonCode.Success; - }) - }; - } - - { - // Create a new MQTT server. - 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() - .WithSubscriptionInterceptor(context => - { - if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin") - { - context.AcceptSubscription = false; - } - - if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator") - { - context.AcceptSubscription = false; - context.CloseConnection = true; - } - }) - .Build(); - } - - { - // Setup and start a managed MQTT client. - var options = new ManagedMqttClientOptionsBuilder() - .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) - .WithClientOptions(new MqttClientOptionsBuilder() - .WithClientId("Client1") - .WithTcpServer("broker.hivemq.com") - .WithTls().Build()) - .Build(); - - var mqttClient = new MqttFactory().CreateManagedMqttClient(); - await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").Build()); - await mqttClient.StartAsync(options); - } - - { - // Use a custom log ID for the logger. - var factory = new MqttFactory(); - var client = factory.CreateMqttClient(new MqttNetLogger("MyCustomId")); - } - - { - var client = new MqttFactory().CreateMqttClient(); - - var message = new MqttApplicationMessageBuilder() - .WithTopic("MyTopic") - .WithPayload("Hello World") - .WithExactlyOnceQoS() - .WithRetainFlag() - .Build(); - - await client.PublishAsync(message); - } - - { - // Write all trace messages to the console window. - MqttNetGlobalLogger.LogMessagePublished += (s, e) => - { - var trace = $">> [{e.LogMessage.Timestamp:O}] [{e.LogMessage.ThreadId}] [{e.LogMessage.Source}] [{e.LogMessage.Level}]: {e.LogMessage.Message}"; - if (e.LogMessage.Exception != null) - { - trace += Environment.NewLine + e.LogMessage.Exception.ToString(); - } - - Console.WriteLine(trace); - }; - } - } - - #endregion - } -} diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Package.appxmanifest b/Tests/MQTTnet.TestApp.UniversalWindows/Package.appxmanifest deleted file mode 100644 index 81914fad..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/Package.appxmanifest +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - MQTTnet.TestApp.UniversalWindows - test - Assets\StoreLogo.png - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Properties/AssemblyInfo.cs b/Tests/MQTTnet.TestApp.UniversalWindows/Properties/AssemblyInfo.cs deleted file mode 100644 index d125e02e..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle("MQTTnet.TestApp.UniversalWindows")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Christian Kratky")] -[assembly: AssemblyProduct("MQTTnet")] -[assembly: AssemblyCopyright("Copyright © Christian Kratky 2016-2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/Tests/MQTTnet.TestApp.UniversalWindows/Properties/Default.rd.xml b/Tests/MQTTnet.TestApp.UniversalWindows/Properties/Default.rd.xml deleted file mode 100644 index 7c40ffeb..00000000 --- a/Tests/MQTTnet.TestApp.UniversalWindows/Properties/Default.rd.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file