mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-19 11:03:07 +08:00
Compare commits
85
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41d5b70344 | ||
|
|
b4769778af | ||
|
|
473f9c31b1 | ||
|
|
ae4f168066 | ||
|
|
c5578a93e8 | ||
|
|
f4b2a10616 | ||
|
|
ed63aa4910 | ||
|
|
4481869d42 | ||
|
|
abbf14b1ec | ||
|
|
4f9e54ba1d | ||
|
|
d80188167a | ||
|
|
4ab956abd1 | ||
|
|
1aa91e3828 | ||
|
|
2410d7b4c1 | ||
|
|
b7328e5fd2 | ||
|
|
7f5c437c46 | ||
|
|
ae5e038548 | ||
|
|
67e0fb8b0b | ||
|
|
b763542329 | ||
|
|
d061da6077 | ||
|
|
82a235aef4 | ||
|
|
fd55982d98 | ||
|
|
aabf180b23 | ||
|
|
1245d8299a | ||
|
|
1ffffaff47 | ||
|
|
c204f6d8b2 | ||
|
|
b775fb256b | ||
|
|
f82d382f23 | ||
|
|
4214af283a | ||
|
|
b32a5c9fa0 | ||
|
|
e7e13a631f | ||
|
|
c12096705f | ||
|
|
eb25500f50 | ||
|
|
4df06980a1 | ||
|
|
f3499013f4 | ||
|
|
158a7fca46 | ||
|
|
09ab30fb0f | ||
|
|
ae84aa43d2 | ||
|
|
b431a5d3fe | ||
|
|
b9683c2943 | ||
|
|
1ba8f74555 | ||
|
|
ec637f7946 | ||
|
|
2599b3dfdc | ||
|
|
d22caa7b70 | ||
|
|
01c90badf9 | ||
|
|
e4f605fbd5 | ||
|
|
6fdee9e0db | ||
|
|
cae7206733 | ||
|
|
e2e7aacc09 | ||
|
|
0d3dd96f2a | ||
|
|
e0660ba887 | ||
|
|
5965ded488 | ||
|
|
fc31c3077c | ||
|
|
e604345e65 | ||
|
|
111a0d69cf | ||
|
|
1a08ec17ba | ||
|
|
c537d290c3 | ||
|
|
2180f59725 | ||
|
|
b1dc8607af | ||
|
|
101898695e | ||
|
|
9295626503 | ||
|
|
18614d4e81 | ||
|
|
560e80455f | ||
|
|
a97e88be29 | ||
|
|
3b5667c882 | ||
|
|
0790e54794 | ||
|
|
94f9fac2bd | ||
|
|
8ad86928f1 | ||
|
|
d8e5936d45 | ||
|
|
caa717544b | ||
|
|
66b77f8d6d | ||
|
|
ab5264c8ca | ||
|
|
db12309bae | ||
|
|
2953e0dcc5 | ||
|
|
1b18ac9fe3 | ||
|
|
2cdad6622a | ||
|
|
7601d11a7a | ||
|
|
0bb4c6ef09 | ||
|
|
449624fd72 | ||
|
|
99f4f46062 | ||
|
|
b08d11c069 | ||
|
|
ac41e838ec | ||
|
|
836ddf3bbc | ||
|
|
0e815c626c | ||
|
|
4b7d035e9e |
+1
-2
@@ -40,7 +40,6 @@ dotnet_style_qualification_for_method = false:suggestion
|
|||||||
dotnet_style_qualification_for_property = false:suggestion
|
dotnet_style_qualification_for_property = false:suggestion
|
||||||
|
|
||||||
# ReSharper properties
|
# ReSharper properties
|
||||||
resharper_autodetect_indent_settings = true
|
|
||||||
resharper_default_private_modifier = implicit
|
resharper_default_private_modifier = implicit
|
||||||
resharper_place_accessorholder_attribute_on_same_line = false
|
resharper_place_accessorholder_attribute_on_same_line = false
|
||||||
resharper_use_indent_from_vs = false
|
resharper_use_indent_from_vs = false
|
||||||
@@ -61,7 +60,7 @@ resharper_web_config_wrong_module_highlighting = warning
|
|||||||
[*]
|
[*]
|
||||||
charset = utf-8
|
charset = utf-8
|
||||||
end_of_line = crlf
|
end_of_line = crlf
|
||||||
trim_trailing_whitespace = false
|
trim_trailing_whitespace = true
|
||||||
insert_final_newline = false
|
insert_final_newline = false
|
||||||
indent_style = space
|
indent_style = space
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
|
|||||||
@@ -1,20 +1,13 @@
|
|||||||
* [Core] Added net7.0 builds (#1635, thanks to @YAJeff).
|
* [Core] Optimized packet serialization of PUBACK and PUBREC packets for protocol version 5.0.0 (#1939, thanks to @Y-Sindo).
|
||||||
* [Core] Added support for payload segments (#1585, thanks to @xljiulang)
|
* [Core] The package inspector is now fully async (#1941).
|
||||||
* [Client] Added support for passing MQTT v5 options (User properties etc.) for disconnects.
|
* [Core] Fixed decoding of DISCONNECT packet with empty body (#1994, thanks to @Y-Sindo).
|
||||||
* [Client] An internal exception is no longer caught silently when calling _DisconnectAsync_ to indicate that the disconnect is not clean (BREAKING CHANGE).
|
* [Client] Exposed the _EndPoint_ type to support other endpoint types (like Unix Domain Sockets) in client options (#1919).
|
||||||
* [Client] MQTTv5 features are now checked and an exception is thrown if they are used when using protocol version 3.1.1 and lower. These checks can be disabled in client options. (BREAKING CHANGE!).
|
* [Client] Fixed support for unix sockets by exposing more options (#1995).
|
||||||
* [Client] Added support for disabling packet fragmentation (required for i.e. AWS, #1690, thanks to @logicaloud).
|
* [Client] Added a dedicated exception when the client is not connected (#1954, thanks to @marcpiulachs).
|
||||||
* [Client] Added new overloads for options builder.
|
* [Client] The client will now throw a _MqttClientUnexpectedDisconnectReceivedException_ when publishing a QoS 0 message which leads to a server disconnect (BREAKING CHANGE!, #1974, thanks to @fazho).
|
||||||
* [Client] Renamed _InspectPackage_ to _InspectPacketAsync_ (BREAKING CHANGE).
|
* [Client] Exposed the certificate selection event handler in client options (#1984).
|
||||||
* [ManagedClient] Exposed added and removed topics in _ManagedProcessFailedEventArgs_ (#1678, thanks to @scottbrogden-iheartmedia).
|
* [Server] The server will no longer send _NoMatchingSubscribers_ when the actual subscription was non success (#1965, BREAKING CHANGE!).
|
||||||
* [Server] Exposed MQTT v5 sent properties from the affected client in _ClientDisconnectedAsync_ event.
|
* [Server] Fixed broken support for _null_ in _AddServer_ method in ASP.NET integration (#1981).
|
||||||
* [Server] Fixed wrong client ID passed to _InterceptingUnsubscriptionEventArgs_ (#1631, thanks to @ghord).
|
* [ManagedClient] Added a new event (SubscriptionsChangedAsync) which is fired when a subscription or unsubscription was made (#1894, thanks to @pdufrene).
|
||||||
* [Server] Exposed socket settings for TCP keep alive in TCP options (#1544).
|
* [ManagedClient] Fixed race condition when server shuts down while subscribing (#1987, thanks to @marve).
|
||||||
* [Server] Exposed server session items at server level and allow custom session items for injected application messages (#1638).
|
* [TopicTemplate] Added new extension which provides a template engine for topics (#1932, thanks to @simonthum).
|
||||||
* [Server] Improved performance for retained message handling when subscribing using "DoNotSendOnSubscribe" or "SendAtSubscribeIfNewSubscriptionOnly" (#1661, thanks to @Int32Overflow).
|
|
||||||
* [Server] Added support for changing the used TLS certificate while the server is running (#1652, thanks to @YAJeff). The certificate provider will now be invoked for every new connection!
|
|
||||||
* [Server] Added a new API method which allows reading a single retained message without the need to processing the entire set of retained messages (#1659).
|
|
||||||
* [Server] Added a new event (InterceptingClientEnqueueAsync) which allows intercepting when an application message is enqueued for a client (#1648).
|
|
||||||
* [Server] Fixed race condition when handling connections which leads to stopped message transfers (#1677, thanks to @RazvanEmilR).
|
|
||||||
* [Server] Fixed not delivered packets to other sessions if the _InterceptingClientEnqueueEvent_ is used and accepting the packet is denied (#1685, thanks to @RossHNPC).
|
|
||||||
* [Server] Added missing user properties to subscribe and unsubscribe interceptor (#1702).
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ name: CI
|
|||||||
on: [push, pull_request]
|
on: [push, pull_request]
|
||||||
|
|
||||||
env:
|
env:
|
||||||
VERSION: "4.2.0.${{github.run_number}}"
|
VERSION: "4.3.4.${{github.run_number}}"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -54,7 +54,7 @@ jobs:
|
|||||||
uses: darenm/Setup-VSTest@v1
|
uses: darenm/Setup-VSTest@v1
|
||||||
|
|
||||||
- name: Core Tests
|
- name: Core Tests
|
||||||
run: vstest.console.exe Source\MQTTnet.Tests\bin\Release\net6.0\MQTTnet.Tests.dll
|
run: vstest.console.exe Source\MQTTnet.Tests\bin\Release\net7.0\MQTTnet.Tests.dll
|
||||||
|
|
||||||
- name: ASP.NET Tests
|
- name: ASP.NET Tests
|
||||||
run: vstest.console.exe Source\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp3.1\MQTTnet.AspNetCore.Tests.dll
|
run: vstest.console.exe Source\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp3.1\MQTTnet.AspNetCore.Tests.dll
|
||||||
|
|||||||
+13
-9
@@ -7,9 +7,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet", "Source\MQTTnet\M
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B3F60ECB-45BA-4C66-8903-8BB89CA67998}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B3F60ECB-45BA-4C66-8903-8BB89CA67998}"
|
||||||
ProjectSection(SolutionItems) = preProject
|
ProjectSection(SolutionItems) = preProject
|
||||||
|
CODE-OF-CONDUCT.md = CODE-OF-CONDUCT.md
|
||||||
LICENSE = LICENSE
|
LICENSE = LICENSE
|
||||||
README.md = README.md
|
README.md = README.md
|
||||||
CODE-OF-CONDUCT.md = CODE-OF-CONDUCT.md
|
|
||||||
EndProjectSection
|
EndProjectSection
|
||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.AspNetCore", "Source\MQTTnet.AspnetCore\MQTTnet.AspNetCore.csproj", "{F10C4060-F7EE-4A83-919F-FF723E72F94A}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.AspNetCore", "Source\MQTTnet.AspnetCore\MQTTnet.AspNetCore.csproj", "{F10C4060-F7EE-4A83-919F-FF723E72F94A}"
|
||||||
@@ -20,17 +20,19 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Extensions.ManagedC
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Extensions.WebSocket4Net", "Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj", "{2BD01D53-4CA5-4142-BE8D-313876395E3E}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Extensions.WebSocket4Net", "Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj", "{2BD01D53-4CA5-4142-BE8D-313876395E3E}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.Samples", "Samples\MQTTnet.Samples.csproj", "{71CF35F5-3327-4A91-AAF4-5340F6701771}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Samples", "Samples\MQTTnet.Samples.csproj", "{71CF35F5-3327-4A91-AAF4-5340F6701771}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.Tests", "Source\MQTTnet.Tests\MQTTnet.Tests.csproj", "{B270F32A-9F3E-42EE-A989-813E35E29ADB}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Tests", "Source\MQTTnet.Tests\MQTTnet.Tests.csproj", "{B270F32A-9F3E-42EE-A989-813E35E29ADB}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.AspNetCore.Tests", "Source\MQTTnet.AspNetCore.Tests\MQTTnet.AspNetCore.Tests.csproj", "{A238BBBF-C75F-482D-9CC3-BB34ABA9B675}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.AspNetCore.Tests", "Source\MQTTnet.AspNetCore.Tests\MQTTnet.AspNetCore.Tests.csproj", "{A238BBBF-C75F-482D-9CC3-BB34ABA9B675}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.Benchmarks", "Source\MQTTnet.Benchmarks\MQTTnet.Benchmarks.csproj", "{2F516E76-AAC4-4219-B7D1-34CDD3CFF381}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Benchmarks", "Source\MQTTnet.Benchmarks\MQTTnet.Benchmarks.csproj", "{2F516E76-AAC4-4219-B7D1-34CDD3CFF381}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.TestApp", "Source\MQTTnet.TestApp\MQTTnet.TestApp.csproj", "{175D5340-CC5B-4542-939D-4E7D15A0BC8D}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.TestApp", "Source\MQTTnet.TestApp\MQTTnet.TestApp.csproj", "{175D5340-CC5B-4542-939D-4E7D15A0BC8D}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.AspTestApp", "Source\MQTTnet.AspTestApp\MQTTnet.AspTestApp.csproj", "{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.AspTestApp", "Source\MQTTnet.AspTestApp\MQTTnet.AspTestApp.csproj", "{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}"
|
||||||
|
EndProject
|
||||||
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Extensions.TopicTemplate", "Source\MQTTnet.Extensions.TopicTemplate\MQTTnet.Extensions.TopicTemplate.csproj", "{374D5861-F7A6-42A2-8CBE-040846000EF9}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
@@ -82,12 +84,14 @@ Global
|
|||||||
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Release|Any CPU.Build.0 = Release|Any CPU
|
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{374D5861-F7A6-42A2-8CBE-040846000EF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{374D5861-F7A6-42A2-8CBE-040846000EF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{374D5861-F7A6-42A2-8CBE-040846000EF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{374D5861-F7A6-42A2-8CBE-040846000EF9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(NestedProjects) = preSolution
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
SolutionGuid = {07536672-5CBC-4BE3-ACE0-708A431A7894}
|
SolutionGuid = {07536672-5CBC-4BE3-ACE0-708A431A7894}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
|
|||||||
@@ -230,6 +230,7 @@
|
|||||||
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">Licensed to the .NET Foundation under one or more agreements.
|
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">Licensed to the .NET Foundation under one or more agreements.
|
||||||
The .NET Foundation licenses this file to you under the MIT license.
|
The .NET Foundation licenses this file to you under the MIT license.
|
||||||
See the LICENSE file in the project root for more information.</s:String>
|
See the LICENSE file in the project root for more information.</s:String>
|
||||||
|
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EFeature_002EServices_002ECodeCleanup_002EFileHeader_002EFileHeaderSettingsMigrate/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpAttributeForSingleLineMethodUpgrade/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpAttributeForSingleLineMethodUpgrade/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
|
||||||
@@ -240,6 +241,7 @@ See the LICENSE file in the project root for more information.</s:String>
|
|||||||
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002ECSharpPlaceAttributeOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002ECSharpPlaceAttributeOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean>
|
||||||
|
<s:Boolean x:Key="/Default/UserDictionary/Words/=catched/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=CONNACK/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/UserDictionary/Words/=CONNACK/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=PINGREQ/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/UserDictionary/Words/=PINGREQ/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=PINGRESP/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/UserDictionary/Words/=PINGRESP/@EntryIndexedValue">True</s:Boolean>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
// ReSharper disable InconsistentNaming
|
// ReSharper disable InconsistentNaming
|
||||||
|
|
||||||
using System.Security.Authentication;
|
using System.Security.Authentication;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using MQTTnet.Extensions.WebSocket4Net;
|
using MQTTnet.Extensions.WebSocket4Net;
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
@@ -71,32 +72,6 @@ public static class Client_Connection_Samples
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task Connect_With_Amazon_AWS()
|
|
||||||
{
|
|
||||||
/*
|
|
||||||
* This sample creates a simple MQTT client and connects to an Amazon Web Services broker.
|
|
||||||
*
|
|
||||||
* The broker requires special settings which are set here.
|
|
||||||
*/
|
|
||||||
|
|
||||||
var mqttFactory = new MqttFactory();
|
|
||||||
|
|
||||||
using (var mqttClient = mqttFactory.CreateMqttClient())
|
|
||||||
{
|
|
||||||
var mqttClientOptions = new MqttClientOptionsBuilder()
|
|
||||||
.WithTcpServer("amazon.web.services.broker")
|
|
||||||
// Disabling packet fragmentation is very important!
|
|
||||||
.WithoutPacketFragmentation()
|
|
||||||
.Build();
|
|
||||||
|
|
||||||
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
|
||||||
|
|
||||||
Console.WriteLine("The MQTT client is connected.");
|
|
||||||
|
|
||||||
await mqttClient.DisconnectAsync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task Connect_Client_Timeout()
|
public static async Task Connect_Client_Timeout()
|
||||||
{
|
{
|
||||||
/*
|
/*
|
||||||
@@ -161,15 +136,15 @@ public static class Client_Connection_Samples
|
|||||||
using (var mqttClient = mqttFactory.CreateMqttClient())
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
||||||
{
|
{
|
||||||
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("mqtt.fluux.io")
|
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("mqtt.fluux.io")
|
||||||
.WithTls(
|
.WithTlsOptions(
|
||||||
o =>
|
o =>
|
||||||
{
|
{
|
||||||
// The used public broker sometimes has invalid certificates. This sample accepts all
|
// The used public broker sometimes has invalid certificates. This sample accepts all
|
||||||
// certificates. This should not be used in live environments.
|
// certificates. This should not be used in live environments.
|
||||||
o.CertificateValidationHandler = _ => true;
|
o.WithCertificateValidationHandler(_ => true);
|
||||||
|
|
||||||
// The default value is determined by the OS. Set manually to force version.
|
// The default value is determined by the OS. Set manually to force version.
|
||||||
o.SslProtocol = SslProtocols.Tls12;
|
o.WithSslProtocols(SslProtocols.Tls12);
|
||||||
})
|
})
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
@@ -196,7 +171,7 @@ public static class Client_Connection_Samples
|
|||||||
|
|
||||||
using (var mqttClient = mqttFactory.CreateMqttClient())
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
||||||
{
|
{
|
||||||
var mqttClientOptions = new MqttClientOptionsBuilder().WithWebSocketServer("broker.hivemq.com:8000/mqtt").Build();
|
var mqttClientOptions = new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("broker.hivemq.com:8000/mqtt")).Build();
|
||||||
|
|
||||||
var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
||||||
|
|
||||||
@@ -218,7 +193,7 @@ public static class Client_Connection_Samples
|
|||||||
|
|
||||||
using (var mqttClient = mqttFactory.CreateMqttClient())
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
||||||
{
|
{
|
||||||
var mqttClientOptions = new MqttClientOptionsBuilder().WithWebSocketServer("broker.hivemq.com:8000/mqtt").Build();
|
var mqttClientOptions = new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("broker.hivemq.com:8000/mqtt")).Build();
|
||||||
|
|
||||||
var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
||||||
|
|
||||||
@@ -241,13 +216,11 @@ public static class Client_Connection_Samples
|
|||||||
using (var mqttClient = mqttFactory.CreateMqttClient())
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
||||||
{
|
{
|
||||||
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8883)
|
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8883)
|
||||||
.WithTls(
|
.WithTlsOptions(
|
||||||
o =>
|
o => o.WithCertificateValidationHandler(
|
||||||
{
|
|
||||||
// The used public broker sometimes has invalid certificates. This sample accepts all
|
// The used public broker sometimes has invalid certificates. This sample accepts all
|
||||||
// certificates. This should not be used in live environments.
|
// certificates. This should not be used in live environments.
|
||||||
o.CertificateValidationHandler = _ => true;
|
_ => true))
|
||||||
})
|
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
// In MQTTv5 the response contains much more information.
|
// In MQTTv5 the response contains much more information.
|
||||||
@@ -262,6 +235,31 @@ public static class Client_Connection_Samples
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static async Task Connect_With_Amazon_AWS()
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* This sample creates a simple MQTT client and connects to an Amazon Web Services broker.
|
||||||
|
*
|
||||||
|
* The broker requires special settings which are set here.
|
||||||
|
*/
|
||||||
|
|
||||||
|
var mqttFactory = new MqttFactory();
|
||||||
|
|
||||||
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
||||||
|
{
|
||||||
|
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("amazon.web.services.broker")
|
||||||
|
// Disabling packet fragmentation is very important!
|
||||||
|
.WithoutPacketFragmentation()
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
||||||
|
|
||||||
|
Console.WriteLine("The MQTT client is connected.");
|
||||||
|
|
||||||
|
await mqttClient.DisconnectAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static async Task Disconnect_Clean()
|
public static async Task Disconnect_Clean()
|
||||||
{
|
{
|
||||||
/*
|
/*
|
||||||
@@ -317,18 +315,19 @@ public static class Client_Connection_Samples
|
|||||||
using (var mqttClient = mqttFactory.CreateMqttClient())
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
||||||
{
|
{
|
||||||
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("mqtt.fluux.io", 8883)
|
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("mqtt.fluux.io", 8883)
|
||||||
.WithTls(
|
.WithTlsOptions(
|
||||||
o =>
|
o =>
|
||||||
{
|
{
|
||||||
o.CertificateValidationHandler = eventArgs =>
|
o.WithCertificateValidationHandler(
|
||||||
{
|
eventArgs =>
|
||||||
eventArgs.Certificate.Subject.DumpToConsole();
|
{
|
||||||
eventArgs.Certificate.GetExpirationDateString().DumpToConsole();
|
eventArgs.Certificate.Subject.DumpToConsole();
|
||||||
eventArgs.Chain.ChainPolicy.RevocationMode.DumpToConsole();
|
eventArgs.Certificate.GetExpirationDateString().DumpToConsole();
|
||||||
eventArgs.Chain.ChainStatus.DumpToConsole();
|
eventArgs.Chain.ChainPolicy.RevocationMode.DumpToConsole();
|
||||||
eventArgs.SslPolicyErrors.DumpToConsole();
|
eventArgs.Chain.ChainStatus.DumpToConsole();
|
||||||
return true;
|
eventArgs.SslPolicyErrors.DumpToConsole();
|
||||||
};
|
return true;
|
||||||
|
});
|
||||||
})
|
})
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
@@ -432,6 +431,59 @@ public static class Client_Connection_Samples
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Console.WriteLine("Press <Enter> to exit");
|
||||||
|
Console.ReadLine();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static async Task ConnectTls_WithCaFile()
|
||||||
|
{
|
||||||
|
var mqttFactory = new MqttFactory();
|
||||||
|
|
||||||
|
X509Certificate2Collection caChain = new X509Certificate2Collection();
|
||||||
|
caChain.ImportFromPem(mosquitto_org); // from https://test.mosquitto.org/ssl/mosquitto.org.crt
|
||||||
|
|
||||||
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
||||||
|
{
|
||||||
|
var mqttClientOptions = new MqttClientOptionsBuilder()
|
||||||
|
.WithTcpServer("test.mosquitto.org", 8883)
|
||||||
|
.WithTlsOptions(new MqttClientTlsOptionsBuilder()
|
||||||
|
.WithTrustChain(caChain)
|
||||||
|
.Build())
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
var connAck = await mqttClient.ConnectAsync(mqttClientOptions);
|
||||||
|
Console.WriteLine("Connected to test.moquitto.org:8883 with CaFile mosquitto.org.crt: " + connAck.ResultCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
const string mosquitto_org = @"
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIEAzCCAuugAwIBAgIUBY1hlCGvdj4NhBXkZ/uLUZNILAwwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwgZAxCzAJBgNVBAYTAkdCMRcwFQYDVQQIDA5Vbml0ZWQgS2luZ2RvbTEOMAwG
|
||||||
|
A1UEBwwFRGVyYnkxEjAQBgNVBAoMCU1vc3F1aXR0bzELMAkGA1UECwwCQ0ExFjAU
|
||||||
|
BgNVBAMMDW1vc3F1aXR0by5vcmcxHzAdBgkqhkiG9w0BCQEWEHJvZ2VyQGF0Y2hv
|
||||||
|
by5vcmcwHhcNMjAwNjA5MTEwNjM5WhcNMzAwNjA3MTEwNjM5WjCBkDELMAkGA1UE
|
||||||
|
BhMCR0IxFzAVBgNVBAgMDlVuaXRlZCBLaW5nZG9tMQ4wDAYDVQQHDAVEZXJieTES
|
||||||
|
MBAGA1UECgwJTW9zcXVpdHRvMQswCQYDVQQLDAJDQTEWMBQGA1UEAwwNbW9zcXVp
|
||||||
|
dHRvLm9yZzEfMB0GCSqGSIb3DQEJARYQcm9nZXJAYXRjaG9vLm9yZzCCASIwDQYJ
|
||||||
|
KoZIhvcNAQEBBQADggEPADCCAQoCggEBAME0HKmIzfTOwkKLT3THHe+ObdizamPg
|
||||||
|
UZmD64Tf3zJdNeYGYn4CEXbyP6fy3tWc8S2boW6dzrH8SdFf9uo320GJA9B7U1FW
|
||||||
|
Te3xda/Lm3JFfaHjkWw7jBwcauQZjpGINHapHRlpiCZsquAthOgxW9SgDgYlGzEA
|
||||||
|
s06pkEFiMw+qDfLo/sxFKB6vQlFekMeCymjLCbNwPJyqyhFmPWwio/PDMruBTzPH
|
||||||
|
3cioBnrJWKXc3OjXdLGFJOfj7pP0j/dr2LH72eSvv3PQQFl90CZPFhrCUcRHSSxo
|
||||||
|
E6yjGOdnz7f6PveLIB574kQORwt8ePn0yidrTC1ictikED3nHYhMUOUCAwEAAaNT
|
||||||
|
MFEwHQYDVR0OBBYEFPVV6xBUFPiGKDyo5V3+Hbh4N9YSMB8GA1UdIwQYMBaAFPVV
|
||||||
|
6xBUFPiGKDyo5V3+Hbh4N9YSMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL
|
||||||
|
BQADggEBAGa9kS21N70ThM6/Hj9D7mbVxKLBjVWe2TPsGfbl3rEDfZ+OKRZ2j6AC
|
||||||
|
6r7jb4TZO3dzF2p6dgbrlU71Y/4K0TdzIjRj3cQ3KSm41JvUQ0hZ/c04iGDg/xWf
|
||||||
|
+pp58nfPAYwuerruPNWmlStWAXf0UTqRtg4hQDWBuUFDJTuWuuBvEXudz74eh/wK
|
||||||
|
sMwfu1HFvjy5Z0iMDU8PUDepjVolOCue9ashlS4EB5IECdSR2TItnAIiIwimx839
|
||||||
|
LdUdRudafMu5T5Xma182OC0/u/xRlEm+tvKGGmfFcN0piqVl8OrSPBgIlb+1IKJE
|
||||||
|
m/XriWr/Cq4h/JfB7NTsezVslgkBaoU=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
";
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@
|
|||||||
// ReSharper disable UnusedType.Global
|
// ReSharper disable UnusedType.Global
|
||||||
// ReSharper disable UnusedMember.Global
|
// ReSharper disable UnusedMember.Global
|
||||||
// ReSharper disable InconsistentNaming
|
// ReSharper disable InconsistentNaming
|
||||||
|
// ReSharper disable UnusedMember.Local
|
||||||
|
|
||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using MQTTnet.Packets;
|
using MQTTnet.Packets;
|
||||||
@@ -176,4 +177,62 @@ public static class Client_Subscribe_Samples
|
|||||||
response.DumpToConsole();
|
response.DumpToConsole();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void ConcurrentProcessingDisableAutoAcknowledge(CancellationToken shutdownToken, IMqttClient mqttClient)
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* This sample shows how to achieve concurrent processing and not have message AutoAcknowledged
|
||||||
|
* This to have a proper QoS1 (at-least-once) experience for what at least MQTT specification can provide
|
||||||
|
*/
|
||||||
|
mqttClient.ApplicationMessageReceivedAsync += ea =>
|
||||||
|
{
|
||||||
|
ea.AutoAcknowledge = false;
|
||||||
|
|
||||||
|
async Task ProcessAsync()
|
||||||
|
{
|
||||||
|
// DO YOUR WORK HERE!
|
||||||
|
await Task.Delay(1000, shutdownToken);
|
||||||
|
await ea.AcknowledgeAsync(shutdownToken);
|
||||||
|
// WARNING: If process failures are not transient the message will be retried on every restart of the client
|
||||||
|
// A failed message will not be dispatched again to the client as MQTT does not have a NACK packet to let
|
||||||
|
// the broker know processing failed
|
||||||
|
//
|
||||||
|
// Optionally: Use a framework like Polly to create a retry policy: https://github.com/App-vNext/Polly#retry
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = Task.Run(ProcessAsync, shutdownToken);
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ConcurrentProcessingWithLimit(CancellationToken shutdownToken, IMqttClient mqttClient)
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* This sample shows how to achieve concurrent processing, with:
|
||||||
|
* - a maximum concurrency limit based on Environment.ProcessorCount
|
||||||
|
*/
|
||||||
|
|
||||||
|
var concurrent = new SemaphoreSlim(Environment.ProcessorCount);
|
||||||
|
|
||||||
|
mqttClient.ApplicationMessageReceivedAsync += async ea =>
|
||||||
|
{
|
||||||
|
await concurrent.WaitAsync(shutdownToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
async Task ProcessAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// DO YOUR WORK HERE!
|
||||||
|
await Task.Delay(1000, shutdownToken);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
concurrent.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = Task.Run(ProcessAsync, shutdownToken);
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<TargetFramework>net6.0</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
// ReSharper disable UnusedType.Global
|
||||||
|
// ReSharper disable UnusedMember.Global
|
||||||
|
// ReSharper disable InconsistentNaming
|
||||||
|
|
||||||
|
using MQTTnet.Client;
|
||||||
|
using MQTTnet.Extensions.ManagedClient;
|
||||||
|
|
||||||
|
namespace MQTTnet.Samples.ManagedClient;
|
||||||
|
|
||||||
|
public sealed class Managed_Client_Subscribe_Samples
|
||||||
|
{
|
||||||
|
public static async Task Connect_Client()
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* This sample creates a simple managed MQTT client and connects to a public broker, subscribe to a topic and verifies subscription result.
|
||||||
|
*
|
||||||
|
* The managed client extends the existing _MqttClient_. It adds the following features.
|
||||||
|
* - Reconnecting when connection is lost.
|
||||||
|
* - Storing pending messages in an internal queue so that an enqueue is possible while the client remains not connected.
|
||||||
|
*/
|
||||||
|
|
||||||
|
var mqttFactory = new MqttFactory();
|
||||||
|
var subscribed = false;
|
||||||
|
|
||||||
|
using (var managedMqttClient = mqttFactory.CreateManagedMqttClient())
|
||||||
|
{
|
||||||
|
var mqttClientOptions = new MqttClientOptionsBuilder()
|
||||||
|
.WithTcpServer("broker.hivemq.com")
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
var managedMqttClientOptions = new ManagedMqttClientOptionsBuilder()
|
||||||
|
.WithClientOptions(mqttClientOptions)
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
await managedMqttClient.StartAsync(managedMqttClientOptions);
|
||||||
|
|
||||||
|
// The application message is not sent. It is stored in an internal queue and
|
||||||
|
// will be sent when the client is connected.
|
||||||
|
await managedMqttClient.EnqueueAsync("Topic", "Payload");
|
||||||
|
|
||||||
|
Console.WriteLine("The managed MQTT client is connected.");
|
||||||
|
|
||||||
|
// Wait until the queue is fully processed.
|
||||||
|
SpinWait.SpinUntil(() => managedMqttClient.PendingApplicationMessagesCount == 0, 10000);
|
||||||
|
|
||||||
|
Console.WriteLine($"Pending messages = {managedMqttClient.PendingApplicationMessagesCount}");
|
||||||
|
|
||||||
|
managedMqttClient.SubscriptionsChangedAsync += args => SubscriptionsResultAsync(args, subscribed);
|
||||||
|
await managedMqttClient.SubscribeAsync("Topic").ConfigureAwait(false);
|
||||||
|
|
||||||
|
SpinWait.SpinUntil(() => subscribed, 1000);
|
||||||
|
Console.WriteLine("Subscription properly done");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task SubscriptionsResultAsync(SubscriptionsChangedEventArgs arg, bool subscribed)
|
||||||
|
{
|
||||||
|
foreach (var mqttClientSubscribeResult in arg.SubscribeResult)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Subscription reason {mqttClientSubscribeResult.ReasonString}");
|
||||||
|
foreach (var item in mqttClientSubscribeResult.Items)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"For topic filter {item.TopicFilter}, result code: {item.ResultCode}");
|
||||||
|
|
||||||
|
if (item.TopicFilter.Topic == "Topic" && item.ResultCode == MqttClientSubscribeResultCode.GrantedQoS0 && !subscribed)
|
||||||
|
{
|
||||||
|
subscribed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var mqttClientUnsubscribeResult in arg.UnsubscribeResult)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Unsubscription reason {mqttClientUnsubscribeResult.ReasonString}");
|
||||||
|
foreach (var item in mqttClientUnsubscribeResult.Items)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"For topic filter {item.TopicFilter}, result code: {item.ResultCode}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,8 @@
|
|||||||
// ReSharper disable InconsistentNaming
|
// ReSharper disable InconsistentNaming
|
||||||
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using MQTTnet.Packets;
|
||||||
|
using MQTTnet.Protocol;
|
||||||
|
|
||||||
namespace MQTTnet.Samples.Server;
|
namespace MQTTnet.Samples.Server;
|
||||||
|
|
||||||
@@ -32,7 +34,10 @@ public static class Server_Retained_Messages_Samples
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
eventArgs.LoadedRetainedMessages = await JsonSerializer.DeserializeAsync<List<MqttApplicationMessage>>(File.OpenRead(storePath));
|
var models = await JsonSerializer.DeserializeAsync<List<MqttRetainedMessageModel>>(File.OpenRead(storePath)) ?? new List<MqttRetainedMessageModel>();
|
||||||
|
var retainedMessages = models.Select(m => m.ToApplicationMessage()).ToList();
|
||||||
|
|
||||||
|
eventArgs.LoadedRetainedMessages = retainedMessages;
|
||||||
Console.WriteLine("Retained messages loaded.");
|
Console.WriteLine("Retained messages loaded.");
|
||||||
}
|
}
|
||||||
catch (FileNotFoundException)
|
catch (FileNotFoundException)
|
||||||
@@ -56,7 +61,9 @@ public static class Server_Retained_Messages_Samples
|
|||||||
// used to write all retained messages to dedicated files etc. Then all files must be loaded and a full list
|
// used to write all retained messages to dedicated files etc. Then all files must be loaded and a full list
|
||||||
// of retained messages must be provided in the loaded event.
|
// of retained messages must be provided in the loaded event.
|
||||||
|
|
||||||
var buffer = JsonSerializer.SerializeToUtf8Bytes(eventArgs.StoredRetainedMessages);
|
var models = eventArgs.StoredRetainedMessages.Select(MqttRetainedMessageModel.Create);
|
||||||
|
|
||||||
|
var buffer = JsonSerializer.SerializeToUtf8Bytes(models);
|
||||||
await File.WriteAllBytesAsync(storePath, buffer);
|
await File.WriteAllBytesAsync(storePath, buffer);
|
||||||
Console.WriteLine("Retained messages saved.");
|
Console.WriteLine("Retained messages saved.");
|
||||||
}
|
}
|
||||||
@@ -79,4 +86,59 @@ public static class Server_Retained_Messages_Samples
|
|||||||
Console.ReadLine();
|
Console.ReadLine();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sealed class MqttRetainedMessageModel
|
||||||
|
{
|
||||||
|
public string? ContentType { get; set; }
|
||||||
|
public byte[]? CorrelationData { get; set; }
|
||||||
|
public byte[]? Payload { get; set; }
|
||||||
|
public MqttPayloadFormatIndicator PayloadFormatIndicator { get; set; }
|
||||||
|
public MqttQualityOfServiceLevel QualityOfServiceLevel { get; set; }
|
||||||
|
public string? ResponseTopic { get; set; }
|
||||||
|
public string? Topic { get; set; }
|
||||||
|
public List<MqttUserProperty>? UserProperties { get; set; }
|
||||||
|
|
||||||
|
public static MqttRetainedMessageModel Create(MqttApplicationMessage message)
|
||||||
|
{
|
||||||
|
if (message == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(message));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new MqttRetainedMessageModel
|
||||||
|
{
|
||||||
|
Topic = message.Topic,
|
||||||
|
|
||||||
|
// Create a copy of the buffer from the payload segment because
|
||||||
|
// it cannot be serialized and deserialized with the JSON serializer.
|
||||||
|
Payload = message.PayloadSegment.ToArray(),
|
||||||
|
UserProperties = message.UserProperties,
|
||||||
|
ResponseTopic = message.ResponseTopic,
|
||||||
|
CorrelationData = message.CorrelationData,
|
||||||
|
ContentType = message.ContentType,
|
||||||
|
PayloadFormatIndicator = message.PayloadFormatIndicator,
|
||||||
|
QualityOfServiceLevel = message.QualityOfServiceLevel
|
||||||
|
|
||||||
|
// Other properties like "Retain" are not if interest in the storage.
|
||||||
|
// That's why a custom model makes sense.
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttApplicationMessage ToApplicationMessage()
|
||||||
|
{
|
||||||
|
return new MqttApplicationMessage
|
||||||
|
{
|
||||||
|
Topic = Topic,
|
||||||
|
PayloadSegment = new ArraySegment<byte>(Payload ?? Array.Empty<byte>()),
|
||||||
|
PayloadFormatIndicator = PayloadFormatIndicator,
|
||||||
|
ResponseTopic = ResponseTopic,
|
||||||
|
CorrelationData = CorrelationData,
|
||||||
|
ContentType = ContentType,
|
||||||
|
UserProperties = UserProperties,
|
||||||
|
QualityOfServiceLevel = QualityOfServiceLevel,
|
||||||
|
Dup = false,
|
||||||
|
Retain = true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,6 @@ namespace MQTTnet.AspNetCore.Tests
|
|||||||
{
|
{
|
||||||
var mockup = new ConnectionHandlerMockup();
|
var mockup = new ConnectionHandlerMockup();
|
||||||
|
|
||||||
|
|
||||||
using (var host = new WebHostBuilder().UseKestrel(kestrel => kestrel.ListenLocalhost(1883, listener => listener.Use((ctx, next) => mockup.OnConnectedAsync(ctx))))
|
using (var host = new WebHostBuilder().UseKestrel(kestrel => kestrel.ListenLocalhost(1883, listener => listener.Use((ctx, next) => mockup.OnConnectedAsync(ctx))))
|
||||||
.UseStartup<Startup>()
|
.UseStartup<Startup>()
|
||||||
.ConfigureServices(
|
.ConfigureServices(
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ using MQTTnet.Adapter;
|
|||||||
using MQTTnet.AspNetCore.Client.Tcp;
|
using MQTTnet.AspNetCore.Client.Tcp;
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
using System;
|
using System;
|
||||||
using System.Net;
|
|
||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using MQTTnet.Diagnostics;
|
using MQTTnet.Diagnostics;
|
||||||
|
|
||||||
@@ -22,8 +21,7 @@ namespace MQTTnet.AspNetCore.Client
|
|||||||
{
|
{
|
||||||
case MqttClientTcpOptions tcpOptions:
|
case MqttClientTcpOptions tcpOptions:
|
||||||
{
|
{
|
||||||
var endpoint = new DnsEndPoint(tcpOptions.Server, tcpOptions.GetPort());
|
var tcpConnection = new SocketConnection(tcpOptions.RemoteEndpoint);
|
||||||
var tcpConnection = new TcpConnection(endpoint);
|
|
||||||
|
|
||||||
var formatter = new MqttPacketFormatterAdapter(options.ProtocolVersion, new MqttBufferWriter(4096, 65535));
|
var formatter = new MqttPacketFormatterAdapter(options.ProtocolVersion, new MqttBufferWriter(4096, 65535));
|
||||||
return new MqttConnectionContext(formatter, tcpConnection);
|
return new MqttConnectionContext(formatter, tcpConnection);
|
||||||
|
|||||||
+17
-16
@@ -15,15 +15,15 @@ using System.Threading.Tasks;
|
|||||||
|
|
||||||
namespace MQTTnet.AspNetCore.Client.Tcp
|
namespace MQTTnet.AspNetCore.Client.Tcp
|
||||||
{
|
{
|
||||||
public class TcpConnection : ConnectionContext
|
public sealed class SocketConnection : ConnectionContext
|
||||||
{
|
{
|
||||||
private volatile bool _aborted;
|
volatile bool _aborted;
|
||||||
private readonly EndPoint _endPoint;
|
readonly EndPoint _endPoint;
|
||||||
private SocketSender _sender;
|
SocketSender _sender;
|
||||||
private SocketReceiver _receiver;
|
SocketReceiver _receiver;
|
||||||
|
|
||||||
private Socket _socket;
|
Socket _socket;
|
||||||
private IDuplexPipe _application;
|
IDuplexPipe _application;
|
||||||
|
|
||||||
public bool IsConnected { get; private set; }
|
public bool IsConnected { get; private set; }
|
||||||
public override string ConnectionId { get; set; }
|
public override string ConnectionId { get; set; }
|
||||||
@@ -31,12 +31,12 @@ namespace MQTTnet.AspNetCore.Client.Tcp
|
|||||||
public override IDictionary<object, object> Items { get; set; }
|
public override IDictionary<object, object> Items { get; set; }
|
||||||
public override IDuplexPipe Transport { get; set; }
|
public override IDuplexPipe Transport { get; set; }
|
||||||
|
|
||||||
public TcpConnection(EndPoint endPoint)
|
public SocketConnection(EndPoint endPoint)
|
||||||
{
|
{
|
||||||
_endPoint = endPoint;
|
_endPoint = endPoint;
|
||||||
}
|
}
|
||||||
|
|
||||||
public TcpConnection(Socket socket)
|
public SocketConnection(Socket socket)
|
||||||
{
|
{
|
||||||
_socket = socket;
|
_socket = socket;
|
||||||
_endPoint = socket.RemoteEndPoint;
|
_endPoint = socket.RemoteEndPoint;
|
||||||
@@ -87,7 +87,7 @@ namespace MQTTnet.AspNetCore.Client.Tcp
|
|||||||
IsConnected = true;
|
IsConnected = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ExecuteAsync()
|
async Task ExecuteAsync()
|
||||||
{
|
{
|
||||||
Exception sendError = null;
|
Exception sendError = null;
|
||||||
try
|
try
|
||||||
@@ -114,7 +114,7 @@ namespace MQTTnet.AspNetCore.Client.Tcp
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Unexpected exception in {nameof(TcpConnection)}.{nameof(StartAsync)}: " + ex);
|
Console.WriteLine($"Unexpected exception in {nameof(SocketConnection)}.{nameof(StartAsync)}: " + ex);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -122,7 +122,8 @@ namespace MQTTnet.AspNetCore.Client.Tcp
|
|||||||
_application.Input.Complete(sendError);
|
_application.Input.Complete(sendError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private async Task DoReceive()
|
|
||||||
|
async Task DoReceive()
|
||||||
{
|
{
|
||||||
Exception error = null;
|
Exception error = null;
|
||||||
|
|
||||||
@@ -171,7 +172,7 @@ namespace MQTTnet.AspNetCore.Client.Tcp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ProcessReceives()
|
async Task ProcessReceives()
|
||||||
{
|
{
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
@@ -204,12 +205,12 @@ namespace MQTTnet.AspNetCore.Client.Tcp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Exception ConnectionAborted()
|
Exception ConnectionAborted()
|
||||||
{
|
{
|
||||||
return new MqttCommunicationException("Connection Aborted");
|
return new MqttCommunicationException("Connection Aborted");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<Exception> DoSend()
|
async Task<Exception> DoSend()
|
||||||
{
|
{
|
||||||
Exception error = null;
|
Exception error = null;
|
||||||
|
|
||||||
@@ -240,7 +241,7 @@ namespace MQTTnet.AspNetCore.Client.Tcp
|
|||||||
return error;
|
return error;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ProcessSends()
|
async Task ProcessSends()
|
||||||
{
|
{
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
@@ -51,11 +51,11 @@
|
|||||||
<DefineConstants>RELEASE;NETSTANDARD2_0</DefineConstants>
|
<DefineConstants>RELEASE;NETSTANDARD2_0</DefineConstants>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1' or '$(TargetFramework)' == 'net5.0' or '$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' ">
|
<ItemGroup Condition="'$(TargetFramework)' != 'netstandard2.0' and '$(TargetFramework)' != 'netcoreapp2.1' ">
|
||||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup Condition="'$(TargetFramework)' != 'netcoreapp3.1' and '$(TargetFramework)' != 'net5.0' and '$(TargetFramework)' != 'net6.0' and '$(TargetFramework)' != 'net7.0' ">
|
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netcoreapp2.1' ">
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Http.Connections" Version="1.1.0" />
|
<PackageReference Include="Microsoft.AspNetCore.Http.Connections" Version="1.1.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -33,8 +33,11 @@ namespace MQTTnet.AspNetCore
|
|||||||
PacketFormatterAdapter = packetFormatterAdapter ?? throw new ArgumentNullException(nameof(packetFormatterAdapter));
|
PacketFormatterAdapter = packetFormatterAdapter ?? throw new ArgumentNullException(nameof(packetFormatterAdapter));
|
||||||
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
|
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
|
||||||
|
|
||||||
_input = connection.Transport.Input;
|
if (!(_connection is SocketConnection tcp) || tcp.IsConnected)
|
||||||
_output = connection.Transport.Output;
|
{
|
||||||
|
_input = connection.Transport.Input;
|
||||||
|
_output = connection.Transport.Output;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public long BytesReceived { get; private set; }
|
public long BytesReceived { get; private set; }
|
||||||
@@ -80,8 +83,6 @@ namespace MQTTnet.AspNetCore
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool IsReadingPacket { get; private set; }
|
|
||||||
|
|
||||||
public bool IsSecureConnection
|
public bool IsSecureConnection
|
||||||
{
|
{
|
||||||
get
|
get
|
||||||
@@ -108,7 +109,7 @@ namespace MQTTnet.AspNetCore
|
|||||||
|
|
||||||
public async Task ConnectAsync(CancellationToken cancellationToken)
|
public async Task ConnectAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
if (_connection is TcpConnection tcp && !tcp.IsConnected)
|
if (_connection is SocketConnection tcp && !tcp.IsConnected)
|
||||||
{
|
{
|
||||||
await tcp.StartAsync().ConfigureAwait(false);
|
await tcp.StartAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
@@ -161,11 +162,6 @@ namespace MQTTnet.AspNetCore
|
|||||||
BytesReceived += received;
|
BytesReceived += received;
|
||||||
return packet;
|
return packet;
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
// we did receive something but the message is not yet complete
|
|
||||||
IsReadingPacket = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else if (readResult.IsCompleted)
|
else if (readResult.IsCompleted)
|
||||||
{
|
{
|
||||||
@@ -186,12 +182,9 @@ namespace MQTTnet.AspNetCore
|
|||||||
// completing the channel makes sure that there is no more data read after a protocol error
|
// completing the channel makes sure that there is no more data read after a protocol error
|
||||||
_input?.Complete(exception);
|
_input?.Complete(exception);
|
||||||
_output?.Complete(exception);
|
_output?.Complete(exception);
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
finally
|
|
||||||
{
|
|
||||||
IsReadingPacket = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
// The .NET Foundation licenses this file to you under the MIT license.
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -14,20 +15,27 @@ namespace MQTTnet.AspNetCore
|
|||||||
{
|
{
|
||||||
public sealed class MqttHostedServer : MqttServer, IHostedService
|
public sealed class MqttHostedServer : MqttServer, IHostedService
|
||||||
{
|
{
|
||||||
public MqttHostedServer(MqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger)
|
readonly MqttFactory _mqttFactory;
|
||||||
: base(options, adapters, logger)
|
|
||||||
|
public MqttHostedServer(MqttFactory mqttFactory, MqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger) : base(
|
||||||
|
options,
|
||||||
|
adapters,
|
||||||
|
logger)
|
||||||
{
|
{
|
||||||
|
_mqttFactory = mqttFactory ?? throw new ArgumentNullException(nameof(mqttFactory));
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task StartAsync(CancellationToken cancellationToken)
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
_ = StartAsync();
|
// The yield makes sure that the hosted service is considered up and running.
|
||||||
return Task.CompletedTask;
|
await Task.Yield();
|
||||||
|
|
||||||
|
_ = StartAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task StopAsync(CancellationToken cancellationToken)
|
public Task StopAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
return StopAsync();
|
return StopAsync(_mqttFactory.CreateMqttServerStopOptionsBuilder().Build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
using System;
|
using System;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using MQTTnet.Adapter;
|
using MQTTnet.Adapter;
|
||||||
using MQTTnet.Diagnostics;
|
using MQTTnet.Diagnostics;
|
||||||
@@ -14,6 +15,89 @@ namespace MQTTnet.AspNetCore
|
|||||||
{
|
{
|
||||||
public static class ServiceCollectionExtensions
|
public static class ServiceCollectionExtensions
|
||||||
{
|
{
|
||||||
|
public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, MqttServerOptions options)
|
||||||
|
{
|
||||||
|
if (services == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(services));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
services.AddSingleton(options);
|
||||||
|
services.AddHostedMqttServer();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, Action<MqttServerOptionsBuilder> configure)
|
||||||
|
{
|
||||||
|
if (services == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(services));
|
||||||
|
}
|
||||||
|
|
||||||
|
var serverOptionsBuilder = new MqttServerOptionsBuilder();
|
||||||
|
|
||||||
|
configure?.Invoke(serverOptionsBuilder);
|
||||||
|
|
||||||
|
var options = serverOptionsBuilder.Build();
|
||||||
|
|
||||||
|
return AddHostedMqttServer(services, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void AddHostedMqttServer(this IServiceCollection services)
|
||||||
|
{
|
||||||
|
// The user may have these services already registered.
|
||||||
|
services.TryAddSingleton<IMqttNetLogger>(MqttNetNullLogger.Instance);
|
||||||
|
services.TryAddSingleton(new MqttFactory());
|
||||||
|
|
||||||
|
services.AddSingleton<MqttHostedServer>();
|
||||||
|
services.AddSingleton<IHostedService>(s => s.GetService<MqttHostedServer>());
|
||||||
|
services.AddSingleton<MqttServer>(s => s.GetService<MqttHostedServer>());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IServiceCollection AddHostedMqttServerWithServices(this IServiceCollection services, Action<AspNetMqttServerOptionsBuilder> configure)
|
||||||
|
{
|
||||||
|
if (services == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(services));
|
||||||
|
}
|
||||||
|
|
||||||
|
services.AddSingleton(
|
||||||
|
s =>
|
||||||
|
{
|
||||||
|
var builder = new AspNetMqttServerOptionsBuilder(s);
|
||||||
|
configure(builder);
|
||||||
|
return builder.Build();
|
||||||
|
});
|
||||||
|
|
||||||
|
services.AddHostedMqttServer();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IServiceCollection AddMqttConnectionHandler(this IServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<MqttConnectionHandler>();
|
||||||
|
services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttConnectionHandler>());
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void AddMqttLogger(this IServiceCollection services, IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
if (services == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(services));
|
||||||
|
}
|
||||||
|
|
||||||
|
services.AddSingleton(logger);
|
||||||
|
}
|
||||||
|
|
||||||
public static IServiceCollection AddMqttServer(this IServiceCollection serviceCollection, Action<MqttServerOptionsBuilder> configure = null)
|
public static IServiceCollection AddMqttServer(this IServiceCollection serviceCollection, Action<MqttServerOptionsBuilder> configure = null)
|
||||||
{
|
{
|
||||||
if (serviceCollection is null)
|
if (serviceCollection is null)
|
||||||
@@ -27,53 +111,10 @@ namespace MQTTnet.AspNetCore
|
|||||||
return serviceCollection;
|
return serviceCollection;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, MqttServerOptions options)
|
public static IServiceCollection AddMqttTcpServerAdapter(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
services.AddSingleton<MqttTcpServerAdapter>();
|
||||||
|
services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttTcpServerAdapter>());
|
||||||
services.AddSingleton(options);
|
|
||||||
|
|
||||||
services.AddHostedMqttServer();
|
|
||||||
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, Action<MqttServerOptionsBuilder> configure = null)
|
|
||||||
{
|
|
||||||
services.AddSingleton(s =>
|
|
||||||
{
|
|
||||||
var serverOptionsBuilder = new MqttServerOptionsBuilder();
|
|
||||||
configure?.Invoke(serverOptionsBuilder);
|
|
||||||
return serverOptionsBuilder.Build();
|
|
||||||
});
|
|
||||||
|
|
||||||
services.AddHostedMqttServer();
|
|
||||||
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IServiceCollection AddHostedMqttServerWithServices(this IServiceCollection services, Action<AspNetMqttServerOptionsBuilder> configure)
|
|
||||||
{
|
|
||||||
services.AddSingleton(s =>
|
|
||||||
{
|
|
||||||
var builder = new AspNetMqttServerOptionsBuilder(s);
|
|
||||||
configure(builder);
|
|
||||||
return builder.Build();
|
|
||||||
});
|
|
||||||
|
|
||||||
services.AddHostedMqttServer();
|
|
||||||
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
static IServiceCollection AddHostedMqttServer(this IServiceCollection services)
|
|
||||||
{
|
|
||||||
var logger = new MqttNetEventLogger();
|
|
||||||
|
|
||||||
services.AddSingleton<IMqttNetLogger>(logger);
|
|
||||||
services.AddSingleton<MqttHostedServer>();
|
|
||||||
services.AddSingleton<IHostedService>(s => s.GetService<MqttHostedServer>());
|
|
||||||
services.AddSingleton<MqttServer>(s => s.GetService<MqttHostedServer>());
|
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
@@ -85,21 +126,5 @@ namespace MQTTnet.AspNetCore
|
|||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IServiceCollection AddMqttTcpServerAdapter(this IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddSingleton<MqttTcpServerAdapter>();
|
|
||||||
services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttTcpServerAdapter>());
|
|
||||||
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IServiceCollection AddMqttConnectionHandler(this IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddSingleton<MqttConnectionHandler>();
|
|
||||||
services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttConnectionHandler>());
|
|
||||||
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -30,17 +30,17 @@ namespace MQTTnet.Benchmarks
|
|||||||
|
|
||||||
var writer = new MqttBufferWriter(4096, 65535);
|
var writer = new MqttBufferWriter(4096, 65535);
|
||||||
writer.WriteString("A relative short string.");
|
writer.WriteString("A relative short string.");
|
||||||
writer.WriteBinaryData(_demoPayload);
|
writer.WriteBinary(_demoPayload);
|
||||||
writer.WriteByte(0x01);
|
writer.WriteByte(0x01);
|
||||||
writer.WriteByte(0x02);
|
writer.WriteByte(0x02);
|
||||||
writer.WriteVariableByteInteger(5647382);
|
writer.WriteVariableByteInteger(5647382);
|
||||||
writer.WriteString("A relative short string.");
|
writer.WriteString("A relative short string.");
|
||||||
writer.WriteVariableByteInteger(8574489);
|
writer.WriteVariableByteInteger(8574489);
|
||||||
writer.WriteBinaryData(_demoPayload);
|
writer.WriteBinary(_demoPayload);
|
||||||
writer.WriteByte(2);
|
writer.WriteByte(2);
|
||||||
writer.WriteByte(0x02);
|
writer.WriteByte(0x02);
|
||||||
writer.WriteString("fjgffiogfhgfhoihgoireghreghreguhreguireoghreouighreouighreughreguiorehreuiohruiorehreuioghreug");
|
writer.WriteString("fjgffiogfhgfhoihgoireghreghreguhreguireoghreouighreouighreughreguiorehreuiohruiorehreuioghreug");
|
||||||
writer.WriteBinaryData(_demoPayload);
|
writer.WriteBinary(_demoPayload);
|
||||||
|
|
||||||
_readPayload = new ArraySegment<byte>(writer.GetBuffer(), 0, writer.Length).ToArray();
|
_readPayload = new ArraySegment<byte>(writer.GetBuffer(), 0, writer.Length).ToArray();
|
||||||
}
|
}
|
||||||
@@ -83,11 +83,11 @@ namespace MQTTnet.Benchmarks
|
|||||||
writer.WriteVariableByteInteger(5647382);
|
writer.WriteVariableByteInteger(5647382);
|
||||||
writer.WriteString("A relative short string.");
|
writer.WriteString("A relative short string.");
|
||||||
writer.WriteVariableByteInteger(8574589);
|
writer.WriteVariableByteInteger(8574589);
|
||||||
writer.WriteBinaryData(_demoPayload);
|
writer.WriteBinary(_demoPayload);
|
||||||
writer.WriteByte(2);
|
writer.WriteByte(2);
|
||||||
writer.WriteByte(0x02);
|
writer.WriteByte(0x02);
|
||||||
writer.WriteString("fjgffiogfhgfhoihgoireghreghreguhreguireoghreouighreouighreughreguiorehreuiohruiorehreuioghreug");
|
writer.WriteString("fjgffiogfhgfhoihgoireghreghreguhreguireoghreouighreouighreughreguiorehreuiohruiorehreuioghreug");
|
||||||
writer.WriteBinaryData(_demoPayload);
|
writer.WriteBinary(_demoPayload);
|
||||||
|
|
||||||
writer.Reset(0);
|
writer.Reset(0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,12 +29,12 @@ namespace MQTTnet.Benchmarks
|
|||||||
|
|
||||||
var task = Task.Run(() => server.AcceptSocket());
|
var task = Task.Run(() => server.AcceptSocket());
|
||||||
|
|
||||||
var clientConnection = new TcpConnection(new IPEndPoint(IPAddress.Loopback, 1883));
|
var clientConnection = new SocketConnection(new IPEndPoint(IPAddress.Loopback, 1883));
|
||||||
|
|
||||||
clientConnection.StartAsync().GetAwaiter().GetResult();
|
clientConnection.StartAsync().GetAwaiter().GetResult();
|
||||||
_client = clientConnection.Transport;
|
_client = clientConnection.Transport;
|
||||||
|
|
||||||
var serverConnection = new TcpConnection(task.GetAwaiter().GetResult());
|
var serverConnection = new SocketConnection(task.GetAwaiter().GetResult());
|
||||||
serverConnection.StartAsync().GetAwaiter().GetResult();
|
serverConnection.StartAsync().GetAwaiter().GetResult();
|
||||||
_server = serverConnection.Transport;
|
_server = serverConnection.Transport;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
|
|
||||||
event Func<ManagedProcessFailedEventArgs, Task> SynchronizingSubscriptionsFailedAsync;
|
event Func<ManagedProcessFailedEventArgs, Task> SynchronizingSubscriptionsFailedAsync;
|
||||||
|
|
||||||
|
event Func<SubscriptionsChangedEventArgs, Task> SubscriptionsChangedAsync;
|
||||||
|
|
||||||
IMqttClient InternalClient { get; }
|
IMqttClient InternalClient { get; }
|
||||||
|
|
||||||
bool IsConnected { get; }
|
bool IsConnected { get; }
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Extensions.ManagedClient
|
||||||
|
{
|
||||||
|
public sealed class InterceptingPublishMessageEventArgs : EventArgs
|
||||||
|
{
|
||||||
|
public InterceptingPublishMessageEventArgs(ManagedMqttApplicationMessage applicationMessage)
|
||||||
|
{
|
||||||
|
ApplicationMessage = applicationMessage ?? throw new ArgumentNullException(nameof(applicationMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
public ManagedMqttApplicationMessage ApplicationMessage { get; }
|
||||||
|
|
||||||
|
public bool AcceptPublish { get; set; } = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFrameworks>netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
|
<TargetFrameworks>netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
|
||||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461</TargetFrameworks>
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461;net48</TargetFrameworks>
|
||||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||||
|
|
||||||
<AssemblyName>MQTTnet.Extensions.ManagedClient</AssemblyName>
|
<AssemblyName>MQTTnet.Extensions.ManagedClient</AssemblyName>
|
||||||
|
|||||||
@@ -19,15 +19,17 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
{
|
{
|
||||||
public sealed class ManagedMqttClient : Disposable, IManagedMqttClient
|
public sealed class ManagedMqttClient : Disposable, IManagedMqttClient
|
||||||
{
|
{
|
||||||
|
readonly MqttNetSourceLogger _logger;
|
||||||
|
|
||||||
|
readonly AsyncEvent<InterceptingPublishMessageEventArgs> _interceptingPublishMessageEvent = new AsyncEvent<InterceptingPublishMessageEventArgs>();
|
||||||
readonly AsyncEvent<ApplicationMessageProcessedEventArgs> _applicationMessageProcessedEvent = new AsyncEvent<ApplicationMessageProcessedEventArgs>();
|
readonly AsyncEvent<ApplicationMessageProcessedEventArgs> _applicationMessageProcessedEvent = new AsyncEvent<ApplicationMessageProcessedEventArgs>();
|
||||||
readonly AsyncEvent<ApplicationMessageSkippedEventArgs> _applicationMessageSkippedEvent = new AsyncEvent<ApplicationMessageSkippedEventArgs>();
|
readonly AsyncEvent<ApplicationMessageSkippedEventArgs> _applicationMessageSkippedEvent = new AsyncEvent<ApplicationMessageSkippedEventArgs>();
|
||||||
readonly AsyncEvent<ConnectingFailedEventArgs> _connectingFailedEvent = new AsyncEvent<ConnectingFailedEventArgs>();
|
readonly AsyncEvent<ConnectingFailedEventArgs> _connectingFailedEvent = new AsyncEvent<ConnectingFailedEventArgs>();
|
||||||
readonly AsyncEvent<EventArgs> _connectionStateChangedEvent = new AsyncEvent<EventArgs>();
|
readonly AsyncEvent<EventArgs> _connectionStateChangedEvent = new AsyncEvent<EventArgs>();
|
||||||
readonly AsyncEvent<ManagedProcessFailedEventArgs> _synchronizingSubscriptionsFailedEvent = new AsyncEvent<ManagedProcessFailedEventArgs>();
|
readonly AsyncEvent<ManagedProcessFailedEventArgs> _synchronizingSubscriptionsFailedEvent = new AsyncEvent<ManagedProcessFailedEventArgs>();
|
||||||
|
readonly AsyncEvent<SubscriptionsChangedEventArgs> _subscriptionsChangedEvent = new AsyncEvent<SubscriptionsChangedEventArgs>();
|
||||||
|
|
||||||
readonly MqttNetSourceLogger _logger;
|
|
||||||
readonly BlockingQueue<ManagedMqttApplicationMessage> _messageQueue = new BlockingQueue<ManagedMqttApplicationMessage>();
|
readonly BlockingQueue<ManagedMqttApplicationMessage> _messageQueue = new BlockingQueue<ManagedMqttApplicationMessage>();
|
||||||
|
|
||||||
readonly AsyncLock _messageQueueLock = new AsyncLock();
|
readonly AsyncLock _messageQueueLock = new AsyncLock();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -88,6 +90,12 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
remove => _applicationMessageProcessedEvent.RemoveHandler(value);
|
remove => _applicationMessageProcessedEvent.RemoveHandler(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public event Func<InterceptingPublishMessageEventArgs, Task> InterceptPublishMessageAsync
|
||||||
|
{
|
||||||
|
add => _interceptingPublishMessageEvent.AddHandler(value);
|
||||||
|
remove => _interceptingPublishMessageEvent.RemoveHandler(value);
|
||||||
|
}
|
||||||
|
|
||||||
public event Func<MqttApplicationMessageReceivedEventArgs, Task> ApplicationMessageReceivedAsync
|
public event Func<MqttApplicationMessageReceivedEventArgs, Task> ApplicationMessageReceivedAsync
|
||||||
{
|
{
|
||||||
add => InternalClient.ApplicationMessageReceivedAsync += value;
|
add => InternalClient.ApplicationMessageReceivedAsync += value;
|
||||||
@@ -124,6 +132,12 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
remove => _synchronizingSubscriptionsFailedEvent.RemoveHandler(value);
|
remove => _synchronizingSubscriptionsFailedEvent.RemoveHandler(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public event Func<SubscriptionsChangedEventArgs, Task> SubscriptionsChangedAsync
|
||||||
|
{
|
||||||
|
add => _subscriptionsChangedEvent.AddHandler(value);
|
||||||
|
remove => _subscriptionsChangedEvent.RemoveHandler(value);
|
||||||
|
}
|
||||||
|
|
||||||
public IMqttClient InternalClient { get; }
|
public IMqttClient InternalClient { get; }
|
||||||
|
|
||||||
public bool IsConnected => InternalClient.IsConnected;
|
public bool IsConnected => InternalClient.IsConnected;
|
||||||
@@ -353,6 +367,13 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
return remainingTime < TimeSpan.Zero ? TimeSpan.Zero : remainingTime;
|
return remainingTime < TimeSpan.Zero ? TimeSpan.Zero : remainingTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CancellationTokenSource NewTimeoutToken(CancellationToken linkedToken)
|
||||||
|
{
|
||||||
|
var newTimeoutToken = CancellationTokenSource.CreateLinkedTokenSource(linkedToken);
|
||||||
|
newTimeoutToken.CancelAfter(Options.ClientOptions.Timeout);
|
||||||
|
return newTimeoutToken;
|
||||||
|
}
|
||||||
|
|
||||||
async Task HandleSubscriptionExceptionAsync(Exception exception, List<MqttTopicFilter> addedSubscriptions, List<string> removedSubscriptions)
|
async Task HandleSubscriptionExceptionAsync(Exception exception, List<MqttTopicFilter> addedSubscriptions, List<string> removedSubscriptions)
|
||||||
{
|
{
|
||||||
_logger.Warning(exception, "Synchronizing subscriptions failed.");
|
_logger.Warning(exception, "Synchronizing subscriptions failed.");
|
||||||
@@ -363,6 +384,14 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async Task HandleSubscriptionsResultAsync(SendSubscribeUnsubscribeResult subscribeUnsubscribeResult)
|
||||||
|
{
|
||||||
|
if (_subscriptionsChangedEvent.HasHandlers)
|
||||||
|
{
|
||||||
|
await _subscriptionsChangedEvent.InvokeAsync(new SubscriptionsChangedEventArgs(subscribeUnsubscribeResult.SubscribeResults, subscribeUnsubscribeResult.UnsubscribeResults)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async Task MaintainConnectionAsync(CancellationToken cancellationToken)
|
async Task MaintainConnectionAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -387,7 +416,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
{
|
{
|
||||||
if (_isCleanDisconnect)
|
if (_isCleanDisconnect)
|
||||||
{
|
{
|
||||||
using (var disconnectTimeout = new CancellationTokenSource(Options.ClientOptions.Timeout))
|
using (var disconnectTimeout = NewTimeoutToken(CancellationToken.None))
|
||||||
{
|
{
|
||||||
await InternalClient.DisconnectAsync(new MqttClientDisconnectOptions(), disconnectTimeout.Token).ConfigureAwait(false);
|
await InternalClient.DisconnectAsync(new MqttClientDisconnectOptions(), disconnectTimeout.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
@@ -437,7 +466,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
|
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
await TryPublishQueuedMessageAsync(message).ConfigureAwait(false);
|
await TryPublishQueuedMessageAsync(message, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
@@ -453,7 +482,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task PublishReconnectSubscriptionsAsync()
|
async Task PublishReconnectSubscriptionsAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
_logger.Info("Publishing subscriptions at reconnect");
|
_logger.Info("Publishing subscriptions at reconnect");
|
||||||
|
|
||||||
@@ -464,6 +493,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
if (_reconnectSubscriptions.Any())
|
if (_reconnectSubscriptions.Any())
|
||||||
{
|
{
|
||||||
topicFilters = new List<MqttTopicFilter>();
|
topicFilters = new List<MqttTopicFilter>();
|
||||||
|
SendSubscribeUnsubscribeResult subscribeUnsubscribeResult;
|
||||||
|
|
||||||
foreach (var sub in _reconnectSubscriptions)
|
foreach (var sub in _reconnectSubscriptions)
|
||||||
{
|
{
|
||||||
@@ -471,12 +501,14 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
|
|
||||||
if (topicFilters.Count == Options.MaxTopicFiltersInSubscribeUnsubscribePackets)
|
if (topicFilters.Count == Options.MaxTopicFiltersInSubscribeUnsubscribePackets)
|
||||||
{
|
{
|
||||||
await SendSubscribeUnsubscribe(topicFilters, null).ConfigureAwait(false);
|
subscribeUnsubscribeResult = await SendSubscribeUnsubscribe(topicFilters, null, cancellationToken).ConfigureAwait(false);
|
||||||
topicFilters.Clear();
|
topicFilters.Clear();
|
||||||
|
await HandleSubscriptionsResultAsync(subscribeUnsubscribeResult).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await SendSubscribeUnsubscribe(topicFilters, null).ConfigureAwait(false);
|
subscribeUnsubscribeResult = await SendSubscribeUnsubscribe(topicFilters, null, cancellationToken).ConfigureAwait(false);
|
||||||
|
await HandleSubscriptionsResultAsync(subscribeUnsubscribeResult).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
@@ -492,6 +524,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
while (await _subscriptionsQueuedSignal.WaitAsync(GetRemainingTime(endTime), cancellationToken).ConfigureAwait(false))
|
while (await _subscriptionsQueuedSignal.WaitAsync(GetRemainingTime(endTime), cancellationToken).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
List<MqttTopicFilter> subscriptions;
|
List<MqttTopicFilter> subscriptions;
|
||||||
|
SendSubscribeUnsubscribeResult subscribeUnsubscribeResult;
|
||||||
HashSet<string> unsubscriptions;
|
HashSet<string> unsubscriptions;
|
||||||
|
|
||||||
lock (_subscriptions)
|
lock (_subscriptions)
|
||||||
@@ -527,12 +560,14 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
|
|
||||||
if (addedTopicFilters.Count == Options.MaxTopicFiltersInSubscribeUnsubscribePackets)
|
if (addedTopicFilters.Count == Options.MaxTopicFiltersInSubscribeUnsubscribePackets)
|
||||||
{
|
{
|
||||||
await SendSubscribeUnsubscribe(addedTopicFilters, null).ConfigureAwait(false);
|
subscribeUnsubscribeResult = await SendSubscribeUnsubscribe(addedTopicFilters, null, cancellationToken).ConfigureAwait(false);
|
||||||
addedTopicFilters.Clear();
|
addedTopicFilters.Clear();
|
||||||
|
await HandleSubscriptionsResultAsync(subscribeUnsubscribeResult).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await SendSubscribeUnsubscribe(addedTopicFilters, null).ConfigureAwait(false);
|
subscribeUnsubscribeResult = await SendSubscribeUnsubscribe(addedTopicFilters, null, cancellationToken).ConfigureAwait(false);
|
||||||
|
await HandleSubscriptionsResultAsync(subscribeUnsubscribeResult).ConfigureAwait(false);
|
||||||
|
|
||||||
var removedTopicFilters = new List<string>();
|
var removedTopicFilters = new List<string>();
|
||||||
foreach (var unSub in unsubscriptions)
|
foreach (var unSub in unsubscriptions)
|
||||||
@@ -541,12 +576,14 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
|
|
||||||
if (removedTopicFilters.Count == Options.MaxTopicFiltersInSubscribeUnsubscribePackets)
|
if (removedTopicFilters.Count == Options.MaxTopicFiltersInSubscribeUnsubscribePackets)
|
||||||
{
|
{
|
||||||
await SendSubscribeUnsubscribe(null, removedTopicFilters).ConfigureAwait(false);
|
subscribeUnsubscribeResult = await SendSubscribeUnsubscribe(null, removedTopicFilters, cancellationToken).ConfigureAwait(false);
|
||||||
removedTopicFilters.Clear();
|
removedTopicFilters.Clear();
|
||||||
|
await HandleSubscriptionsResultAsync(subscribeUnsubscribeResult).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await SendSubscribeUnsubscribe(null, removedTopicFilters).ConfigureAwait(false);
|
subscribeUnsubscribeResult = await SendSubscribeUnsubscribe(null, removedTopicFilters, cancellationToken).ConfigureAwait(false);
|
||||||
|
await HandleSubscriptionsResultAsync(subscribeUnsubscribeResult).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -560,7 +597,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
MqttClientConnectResult connectResult = null;
|
MqttClientConnectResult connectResult = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using (var connectTimeout = new CancellationTokenSource(Options.ClientOptions.Timeout))
|
using (var connectTimeout = NewTimeoutToken(cancellationToken))
|
||||||
{
|
{
|
||||||
connectResult = await InternalClient.ConnectAsync(Options.ClientOptions, connectTimeout.Token).ConfigureAwait(false);
|
connectResult = await InternalClient.ConnectAsync(Options.ClientOptions, connectTimeout.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
@@ -579,8 +616,10 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task SendSubscribeUnsubscribe(List<MqttTopicFilter> addedSubscriptions, List<string> removedSubscriptions)
|
async Task<SendSubscribeUnsubscribeResult> SendSubscribeUnsubscribe(List<MqttTopicFilter> addedSubscriptions, List<string> removedSubscriptions, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
var subscribeResults = new List<MqttClientSubscribeResult>();
|
||||||
|
var unsubscribeResults = new List<MqttClientUnsubscribeResult>();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (removedSubscriptions != null && removedSubscriptions.Any())
|
if (removedSubscriptions != null && removedSubscriptions.Any())
|
||||||
@@ -592,7 +631,11 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
unsubscribeOptionsBuilder.WithTopicFilter(removedSubscription);
|
unsubscribeOptionsBuilder.WithTopicFilter(removedSubscription);
|
||||||
}
|
}
|
||||||
|
|
||||||
await InternalClient.UnsubscribeAsync(unsubscribeOptionsBuilder.Build()).ConfigureAwait(false);
|
using (var unsubscribeTimeout = NewTimeoutToken(cancellationToken))
|
||||||
|
{
|
||||||
|
var unsubscribeResult = await InternalClient.UnsubscribeAsync(unsubscribeOptionsBuilder.Build(), unsubscribeTimeout.Token).ConfigureAwait(false);
|
||||||
|
unsubscribeResults.Add(unsubscribeResult);
|
||||||
|
}
|
||||||
|
|
||||||
//clear because these worked, maybe the subscribe below will fail, only report those
|
//clear because these worked, maybe the subscribe below will fail, only report those
|
||||||
removedSubscriptions.Clear();
|
removedSubscriptions.Clear();
|
||||||
@@ -607,13 +650,19 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
subscribeOptionsBuilder.WithTopicFilter(addedSubscription);
|
subscribeOptionsBuilder.WithTopicFilter(addedSubscription);
|
||||||
}
|
}
|
||||||
|
|
||||||
await InternalClient.SubscribeAsync(subscribeOptionsBuilder.Build()).ConfigureAwait(false);
|
using (var subscribeTimeout = NewTimeoutToken(cancellationToken))
|
||||||
|
{
|
||||||
|
var subscribeResult = await InternalClient.SubscribeAsync(subscribeOptionsBuilder.Build(), subscribeTimeout.Token).ConfigureAwait(false);
|
||||||
|
subscribeResults.Add(subscribeResult);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
await HandleSubscriptionExceptionAsync(exception, addedSubscriptions, removedSubscriptions).ConfigureAwait(false);
|
await HandleSubscriptionExceptionAsync(exception, addedSubscriptions, removedSubscriptions).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return new SendSubscribeUnsubscribeResult(subscribeResults, unsubscribeResults);
|
||||||
}
|
}
|
||||||
|
|
||||||
void StartPublishing()
|
void StartPublishing()
|
||||||
@@ -667,7 +716,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
}
|
}
|
||||||
else if (connectionState == ReconnectionResult.Reconnected)
|
else if (connectionState == ReconnectionResult.Reconnected)
|
||||||
{
|
{
|
||||||
await PublishReconnectSubscriptionsAsync().ConfigureAwait(false);
|
await PublishReconnectSubscriptionsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
StartPublishing();
|
StartPublishing();
|
||||||
}
|
}
|
||||||
else if (connectionState == ReconnectionResult.Recovered)
|
else if (connectionState == ReconnectionResult.Recovered)
|
||||||
@@ -697,12 +746,26 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task TryPublishQueuedMessageAsync(ManagedMqttApplicationMessage message)
|
async Task TryPublishQueuedMessageAsync(ManagedMqttApplicationMessage message, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
Exception transmitException = null;
|
Exception transmitException = null;
|
||||||
|
bool acceptPublish = true;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await InternalClient.PublishAsync(message.ApplicationMessage).ConfigureAwait(false);
|
if (_interceptingPublishMessageEvent.HasHandlers)
|
||||||
|
{
|
||||||
|
var interceptEventArgs = new InterceptingPublishMessageEventArgs(message);
|
||||||
|
await _interceptingPublishMessageEvent.InvokeAsync(interceptEventArgs).ConfigureAwait(false);
|
||||||
|
acceptPublish = interceptEventArgs.AcceptPublish;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (acceptPublish)
|
||||||
|
{
|
||||||
|
using (var publishTimeout = NewTimeoutToken(cancellationToken))
|
||||||
|
{
|
||||||
|
await InternalClient.PublishAsync(message.ApplicationMessage, publishTimeout.Token).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
using (await _messageQueueLock.EnterAsync().ConfigureAwait(false)) //lock to avoid conflict with this.PublishAsync
|
using (await _messageQueueLock.EnterAsync().ConfigureAwait(false)) //lock to avoid conflict with this.PublishAsync
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
{
|
{
|
||||||
public static IManagedMqttClient CreateManagedMqttClient(this MqttFactory factory, IMqttClient mqttClient = null)
|
public static IManagedMqttClient CreateManagedMqttClient(this MqttFactory factory, IMqttClient mqttClient = null)
|
||||||
{
|
{
|
||||||
if (factory == null) throw new ArgumentNullException(nameof(factory));
|
if (factory == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(factory));
|
||||||
|
}
|
||||||
|
|
||||||
if (mqttClient == null)
|
if (mqttClient == null)
|
||||||
{
|
{
|
||||||
@@ -24,10 +27,22 @@ namespace MQTTnet.Extensions.ManagedClient
|
|||||||
|
|
||||||
public static IManagedMqttClient CreateManagedMqttClient(this MqttFactory factory, IMqttNetLogger logger)
|
public static IManagedMqttClient CreateManagedMqttClient(this MqttFactory factory, IMqttNetLogger logger)
|
||||||
{
|
{
|
||||||
if (factory == null) throw new ArgumentNullException(nameof(factory));
|
if (factory == null)
|
||||||
if (logger == null) throw new ArgumentNullException(nameof(logger));
|
{
|
||||||
|
throw new ArgumentNullException(nameof(factory));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logger == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(logger));
|
||||||
|
}
|
||||||
|
|
||||||
return new ManagedMqttClient(factory.CreateMqttClient(logger), logger);
|
return new ManagedMqttClient(factory.CreateMqttClient(logger), logger);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static ManagedMqttClientOptionsBuilder CreateManagedMqttClientOptionsBuilder(this MqttFactory _)
|
||||||
|
{
|
||||||
|
return new ManagedMqttClientOptionsBuilder();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using MQTTnet.Client;
|
||||||
|
|
||||||
|
namespace MQTTnet.Extensions.ManagedClient
|
||||||
|
{
|
||||||
|
public sealed class SendSubscribeUnsubscribeResult
|
||||||
|
{
|
||||||
|
public SendSubscribeUnsubscribeResult(List<MqttClientSubscribeResult> subscribeResults, List<MqttClientUnsubscribeResult> unsubscribeResults)
|
||||||
|
{
|
||||||
|
SubscribeResults = subscribeResults ?? throw new ArgumentNullException(nameof(subscribeResults));
|
||||||
|
UnsubscribeResults = unsubscribeResults ?? throw new ArgumentNullException(nameof(unsubscribeResults));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<MqttClientSubscribeResult> SubscribeResults { get; private set; }
|
||||||
|
|
||||||
|
public List<MqttClientUnsubscribeResult> UnsubscribeResults { get; private set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using MQTTnet.Client;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace MQTTnet.Extensions.ManagedClient
|
||||||
|
{
|
||||||
|
public sealed class SubscriptionsChangedEventArgs : EventArgs
|
||||||
|
{
|
||||||
|
public SubscriptionsChangedEventArgs(List<MqttClientSubscribeResult> subscribeResult, List<MqttClientUnsubscribeResult> unsubscribeResult)
|
||||||
|
{
|
||||||
|
SubscribeResult = subscribeResult ?? throw new ArgumentNullException(nameof(subscribeResult));
|
||||||
|
UnsubscribeResult = unsubscribeResult ?? throw new ArgumentNullException(nameof(unsubscribeResult));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<MqttClientSubscribeResult> SubscribeResult { get; }
|
||||||
|
|
||||||
|
public List<MqttClientUnsubscribeResult> UnsubscribeResult { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,9 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
@@ -7,8 +12,8 @@ namespace MQTTnet.Extensions.Rpc
|
|||||||
{
|
{
|
||||||
public interface IMqttRpcClient : IDisposable
|
public interface IMqttRpcClient : IDisposable
|
||||||
{
|
{
|
||||||
Task<byte[]> ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel);
|
Task<byte[]> ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string,object> parameters = null);
|
||||||
|
|
||||||
Task<byte[]> ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, CancellationToken cancellationToken = default);
|
Task<byte[]> ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string, object> parameters = null, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFrameworks>netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
|
<TargetFrameworks>netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
|
||||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461</TargetFrameworks>
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461;net48</TargetFrameworks>
|
||||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||||
|
|
||||||
<AssemblyName>MQTTnet.Extensions.Rpc</AssemblyName>
|
<AssemblyName>MQTTnet.Extensions.Rpc</AssemblyName>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -42,13 +43,13 @@ namespace MQTTnet.Extensions.Rpc
|
|||||||
_waitingCalls.Clear();
|
_waitingCalls.Clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<byte[]> ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel)
|
public async Task<byte[]> ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string, object> parameters = null)
|
||||||
{
|
{
|
||||||
using (var timeoutToken = new CancellationTokenSource(timeout))
|
using (var timeoutToken = new CancellationTokenSource(timeout))
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return await ExecuteAsync(methodName, payload, qualityOfServiceLevel, timeoutToken.Token).ConfigureAwait(false);
|
return await ExecuteAsync(methodName, payload, qualityOfServiceLevel, parameters, timeoutToken.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException exception)
|
catch (OperationCanceledException exception)
|
||||||
{
|
{
|
||||||
@@ -62,14 +63,14 @@ namespace MQTTnet.Extensions.Rpc
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<byte[]> ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, CancellationToken cancellationToken = default)
|
public async Task<byte[]> ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string, object> parameters = null, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
if (methodName == null)
|
if (methodName == null)
|
||||||
{
|
{
|
||||||
throw new ArgumentNullException(nameof(methodName));
|
throw new ArgumentNullException(nameof(methodName));
|
||||||
}
|
}
|
||||||
|
|
||||||
var context = new TopicGenerationContext(_mqttClient, _options, methodName, qualityOfServiceLevel);
|
var context = new TopicGenerationContext(_mqttClient, _options, methodName, parameters, qualityOfServiceLevel);
|
||||||
var topicNames = _options.TopicGenerationStrategy.CreateRpcTopics(context);
|
var topicNames = _options.TopicGenerationStrategy.CreateRpcTopics(context);
|
||||||
|
|
||||||
var requestTopic = topicNames.RequestTopic;
|
var requestTopic = topicNames.RequestTopic;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
@@ -11,13 +12,13 @@ namespace MQTTnet.Extensions.Rpc
|
|||||||
{
|
{
|
||||||
public static class MqttRpcClientExtensions
|
public static class MqttRpcClientExtensions
|
||||||
{
|
{
|
||||||
public static Task<byte[]> ExecuteAsync(this IMqttRpcClient client, TimeSpan timeout, string methodName, string payload, MqttQualityOfServiceLevel qualityOfServiceLevel)
|
public static Task<byte[]> ExecuteAsync(this IMqttRpcClient client, TimeSpan timeout, string methodName, string payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string,object> parameters = null)
|
||||||
{
|
{
|
||||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||||
|
|
||||||
var buffer = Encoding.UTF8.GetBytes(payload ?? string.Empty);
|
var buffer = Encoding.UTF8.GetBytes(payload ?? string.Empty);
|
||||||
|
|
||||||
return client.ExecuteAsync(timeout, methodName, buffer, qualityOfServiceLevel);
|
return client.ExecuteAsync(timeout, methodName, buffer, qualityOfServiceLevel, parameters);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
|
|
||||||
@@ -10,9 +11,11 @@ namespace MQTTnet.Extensions.Rpc
|
|||||||
{
|
{
|
||||||
public sealed class TopicGenerationContext
|
public sealed class TopicGenerationContext
|
||||||
{
|
{
|
||||||
public TopicGenerationContext(IMqttClient mqttClient, MqttRpcClientOptions options, string methodName, MqttQualityOfServiceLevel qualityOfServiceLevel)
|
public TopicGenerationContext(IMqttClient mqttClient, MqttRpcClientOptions options, string methodName,
|
||||||
|
IDictionary<string, object> parameters, MqttQualityOfServiceLevel qualityOfServiceLevel)
|
||||||
{
|
{
|
||||||
MethodName = methodName ?? throw new ArgumentNullException(nameof(methodName));
|
MethodName = methodName ?? throw new ArgumentNullException(nameof(methodName));
|
||||||
|
Parameters = parameters;
|
||||||
QualityOfServiceLevel = qualityOfServiceLevel;
|
QualityOfServiceLevel = qualityOfServiceLevel;
|
||||||
MqttClient = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient));
|
MqttClient = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient));
|
||||||
Options = options ?? throw new ArgumentNullException(nameof(options));
|
Options = options ?? throw new ArgumentNullException(nameof(options));
|
||||||
@@ -20,6 +23,8 @@ namespace MQTTnet.Extensions.Rpc
|
|||||||
|
|
||||||
public string MethodName { get; }
|
public string MethodName { get; }
|
||||||
|
|
||||||
|
public IDictionary<string, object> Parameters { get; }
|
||||||
|
|
||||||
public IMqttClient MqttClient { get; }
|
public IMqttClient MqttClient { get; }
|
||||||
|
|
||||||
public MqttRpcClientOptions Options { get; }
|
public MqttRpcClientOptions Options { get; }
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFrameworks>netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
|
||||||
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461;net48</TargetFrameworks>
|
||||||
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||||
|
|
||||||
|
<AssemblyName>MQTTnet.Extensions.TopicTemplate</AssemblyName>
|
||||||
|
<RootNamespace>MQTTnet.Extensions.TopicTemplate</RootNamespace>
|
||||||
|
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||||
|
<Company>The contributors of MQTTnet</Company>
|
||||||
|
<Product>MQTTnet</Product>
|
||||||
|
<Description>
|
||||||
|
This is an extension library which provides mqtt topic templating logic to support dispatch,
|
||||||
|
routing and similar functionality based on the well known moustache syntax, aka
|
||||||
|
AsyncAPI dynamic channel address.
|
||||||
|
</Description>
|
||||||
|
<Authors>The contributors of MQTTnet</Authors>
|
||||||
|
<PackageId>MQTTnet.Extensions.TopicTemplate</PackageId>
|
||||||
|
<SignAssembly>false</SignAssembly>
|
||||||
|
<DelaySign>false</DelaySign>
|
||||||
|
<PublishRepositoryUrl>true</PublishRepositoryUrl>
|
||||||
|
<IncludeSymbols>true</IncludeSymbols>
|
||||||
|
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||||
|
<Copyright>Copyright (c) .NET Foundation and Contributors</Copyright>
|
||||||
|
<PackageProjectUrl>https://github.com/dotnet/MQTTnet</PackageProjectUrl>
|
||||||
|
<RepositoryUrl>https://github.com/dotnet/MQTTnet.git</RepositoryUrl>
|
||||||
|
<RepositoryType>git</RepositoryType>
|
||||||
|
<PackageTags>MQTT Message Queue Telemetry MQTTClient Messaging Routing AsyncAPI Template</PackageTags>
|
||||||
|
<NeutralLanguage>en-US</NeutralLanguage>
|
||||||
|
<PackageIcon>nuget.png</PackageIcon>
|
||||||
|
<EmbedUntrackedSources>true</EmbedUntrackedSources>
|
||||||
|
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
|
||||||
|
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||||
|
<PackageReleaseNotes>For release notes please go to MQTTnet release notes (https://www.nuget.org/packages/MQTTnet/).</PackageReleaseNotes>
|
||||||
|
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||||
|
<NoWarn>1591;NETSDK1138</NoWarn>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(TargetFramework)' == 'uap10.0'">
|
||||||
|
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||||
|
<NugetTargetMoniker>UAP,Version=v10.0</NugetTargetMoniker>
|
||||||
|
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
|
||||||
|
<TargetPlatformVersion>10.0.18362.0</TargetPlatformVersion>
|
||||||
|
<TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion>
|
||||||
|
<TargetFrameworkIdentifier>.NETCore</TargetFrameworkIdentifier>
|
||||||
|
<TargetFrameworkVersion>v5.0</TargetFrameworkVersion>
|
||||||
|
<DefineConstants>$(DefineConstants);WINDOWS_UWP</DefineConstants>
|
||||||
|
<DefaultLanguage>en</DefaultLanguage>
|
||||||
|
<LanguageTargets>$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets</LanguageTargets>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="..\..\Images\nuget.png">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
|
||||||
|
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\MQTTnet\MQTTnet.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Threading;
|
||||||
|
using MQTTnet.Protocol;
|
||||||
|
|
||||||
|
namespace MQTTnet.Extensions.TopicTemplate
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A topic template is an MQTT topic filter string that may contain
|
||||||
|
/// segments in curly braces called parameters. This well-known
|
||||||
|
/// 'moustache' syntax also matches AsyncAPI Channel Address Expressions.
|
||||||
|
/// The topic template is designed to support dynamic subscription/publication,
|
||||||
|
/// message-topic matching and routing. It is intended to be more convenient
|
||||||
|
/// than String.Format() for aforementioned purposes.
|
||||||
|
/// </summary>
|
||||||
|
/// <example>
|
||||||
|
/// topic/subtopic/{parameter}/{otherParameter}
|
||||||
|
/// </example>
|
||||||
|
public sealed class MqttTopicTemplate : IEquatable<MqttTopicTemplate>
|
||||||
|
{
|
||||||
|
static readonly Regex MoustacheRegex = new Regex("{([^/]+?)}", RegexOptions.Compiled);
|
||||||
|
|
||||||
|
readonly string[] _parameterSegments;
|
||||||
|
|
||||||
|
string _topicFilter;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Create a topic template from an mqtt topic filter with moustache placeholders.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="topicTemplate">
|
||||||
|
/// </param>
|
||||||
|
/// <exception
|
||||||
|
/// cref="ArgumentNullException">
|
||||||
|
/// </exception>
|
||||||
|
public MqttTopicTemplate(string topicTemplate)
|
||||||
|
{
|
||||||
|
if (topicTemplate == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(topicTemplate));
|
||||||
|
}
|
||||||
|
|
||||||
|
MqttTopicValidator.ThrowIfInvalidSubscribe(topicTemplate);
|
||||||
|
|
||||||
|
Template = topicTemplate;
|
||||||
|
_parameterSegments = topicTemplate.Split(MqttTopicFilterComparer.LevelSeparator)
|
||||||
|
.Select(segment => MoustacheRegex.Match(segment).Groups[1].Value)
|
||||||
|
.Select(s => s.Length > 0 ? s : null)
|
||||||
|
.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Yield the template parameter names.
|
||||||
|
/// </summary>
|
||||||
|
public IEnumerable<string> Parameters => _parameterSegments.Where(s => s != null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The topic template string representation, e.g. A/B/{foo}/D.
|
||||||
|
/// </summary>
|
||||||
|
public string Template { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The topic template as an MQTT topic filter (+ substituted for all parameters). If the template
|
||||||
|
/// ends with a multi-level wildcard (hash), this will be reflected here.
|
||||||
|
/// </summary>
|
||||||
|
public string TopicFilter
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
LazyInitializer.EnsureInitialized(ref _topicFilter, () => MoustacheRegex.Replace(Template, MqttTopicFilterComparer.SingleLevelWildcard.ToString()));
|
||||||
|
return _topicFilter;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Return the topic filter of this template, ending with a multi-level wildcard (hash).
|
||||||
|
/// </summary>
|
||||||
|
public string TopicTreeRootFilter
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
var filter = TopicFilter;
|
||||||
|
// append slash if neccessary
|
||||||
|
if (filter.Length > 0 && !filter.EndsWith(MqttTopicFilterComparer.LevelSeparator.ToString()) &&
|
||||||
|
!filter.EndsWith(MqttTopicFilterComparer.MultiLevelWildcard.ToString()))
|
||||||
|
{
|
||||||
|
filter += MqttTopicFilterComparer.LevelSeparator;
|
||||||
|
}
|
||||||
|
|
||||||
|
// append hash if neccessary
|
||||||
|
if (!filter.EndsWith(MqttTopicFilterComparer.MultiLevelWildcard.ToString()))
|
||||||
|
{
|
||||||
|
filter += MqttTopicFilterComparer.MultiLevelWildcard;
|
||||||
|
}
|
||||||
|
|
||||||
|
return filter;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Equals(MqttTopicTemplate other)
|
||||||
|
{
|
||||||
|
return other != null && Template == other.Template;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Equals(object obj)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(null, obj))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ReferenceEquals(this, obj))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (obj.GetType() != GetType())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Equals((MqttTopicTemplate)obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Determine the shortest common prefix of the given templates. Partial segments
|
||||||
|
/// are not returned.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="templates">
|
||||||
|
/// topic templates
|
||||||
|
/// </param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static MqttTopicTemplate FindCanonicalPrefix(IEnumerable<MqttTopicTemplate> templates)
|
||||||
|
{
|
||||||
|
string root = null;
|
||||||
|
|
||||||
|
string CommonPrefix(string a, string b)
|
||||||
|
{
|
||||||
|
var maxIndex = Math.Min(a.Length, b.Length) - 1;
|
||||||
|
for (var i = 0; i <= maxIndex; i++)
|
||||||
|
{
|
||||||
|
if (a[i] != b[i])
|
||||||
|
{
|
||||||
|
return a.Substring(0, i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return a.Substring(0, maxIndex+1);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (string topic in from template in templates select template.Template)
|
||||||
|
{
|
||||||
|
root = root == null ? topic : CommonPrefix(root, topic);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(root))
|
||||||
|
return new MqttTopicTemplate(MqttTopicFilterComparer.MultiLevelWildcard.ToString());
|
||||||
|
|
||||||
|
if (root.Contains(MqttTopicFilterComparer.LevelSeparator) &&
|
||||||
|
!root.EndsWith(MqttTopicFilterComparer.LevelSeparator.ToString()) &&
|
||||||
|
!root.EndsWith("}"))
|
||||||
|
{
|
||||||
|
root = root.Substring(0, root.LastIndexOf(MqttTopicFilterComparer.LevelSeparator)+1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (root.EndsWith(MqttTopicFilterComparer.LevelSeparator.ToString()))
|
||||||
|
root += MqttTopicFilterComparer.SingleLevelWildcard;
|
||||||
|
|
||||||
|
return new MqttTopicTemplate(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int GetHashCode()
|
||||||
|
{
|
||||||
|
return Template.GetHashCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Test if this topic template matches a given topic.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="topic">
|
||||||
|
/// a fully specified topic
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="subtree">
|
||||||
|
/// true to match including the subtree (multi-level wildcard)
|
||||||
|
/// </param>
|
||||||
|
/// <returns>true iff the topic matches the template's filter</returns>
|
||||||
|
/// <exception
|
||||||
|
/// cref="InvalidOperationException">
|
||||||
|
/// </exception>
|
||||||
|
/// <exception
|
||||||
|
/// cref="ArgumentException">
|
||||||
|
/// if the topic is invalid
|
||||||
|
/// </exception>
|
||||||
|
public bool MatchesTopic(string topic, bool subtree = false)
|
||||||
|
{
|
||||||
|
var comparison = MqttTopicFilterComparer.Compare(topic, subtree ? TopicTreeRootFilter : TopicFilter);
|
||||||
|
if (comparison == MqttTopicFilterCompareResult.FilterInvalid)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Invalid filter");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (comparison == MqttTopicFilterCompareResult.TopicInvalid)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Invalid topic", nameof(topic));
|
||||||
|
}
|
||||||
|
|
||||||
|
return comparison == MqttTopicFilterCompareResult.IsMatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract the parameter values from a topic corresponding to the template
|
||||||
|
/// parameters. The topic has to match this template.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="topic">
|
||||||
|
/// the topic
|
||||||
|
/// </param>
|
||||||
|
/// <returns>an enumeration of (parameter, index, value)</returns>
|
||||||
|
public IEnumerable<(string parameter, int index, string value)> ParseParameterValues(string topic)
|
||||||
|
{
|
||||||
|
if (!MatchesTopic(topic))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("the topic has to match this template", nameof(topic));
|
||||||
|
}
|
||||||
|
|
||||||
|
return parseParameterValuesInternal(topic);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extract the parameter values from the message topic corresponding to the template
|
||||||
|
/// parameters. The message topic has to match this topic template.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="message">
|
||||||
|
/// the message
|
||||||
|
/// </param>
|
||||||
|
/// <returns>an enumeration of (parameter, index, value)</returns>
|
||||||
|
public IEnumerable<(string parameter, int index, string value)> ParseParameterValues(MqttApplicationMessage message)
|
||||||
|
{
|
||||||
|
return ParseParameterValues(message.Topic);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Try to set a parameter to a given value. If the parameter is not present,
|
||||||
|
/// this is returned. The value must not contain slashes.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="parameter">
|
||||||
|
/// a template parameter
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="value">
|
||||||
|
/// a string
|
||||||
|
/// </param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public MqttTopicTemplate TrySetParameter(string parameter, string value)
|
||||||
|
{
|
||||||
|
if (parameter != null && _parameterSegments.Contains(parameter))
|
||||||
|
{
|
||||||
|
return WithParameter(parameter, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Replace the given parameter with a single-level wildcard (plus sign).
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="parameter">
|
||||||
|
/// parameter name
|
||||||
|
/// </param>
|
||||||
|
/// <returns>the topic template (without the parameter)</returns>
|
||||||
|
public MqttTopicTemplate WithoutParameter(string parameter)
|
||||||
|
{
|
||||||
|
return WithParameter(parameter, MqttTopicFilterComparer.SingleLevelWildcard.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Substitute a parameter with a given value, thus removing the parameter. If the parameter is not present,
|
||||||
|
/// the method trows. The value must not contain slashes.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="parameter">
|
||||||
|
/// a template parameter
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="value">
|
||||||
|
/// a string
|
||||||
|
/// </param>
|
||||||
|
/// <exception
|
||||||
|
/// cref="ArgumentException">
|
||||||
|
/// when the parameter is not present
|
||||||
|
/// </exception>
|
||||||
|
/// <returns>the topic template (without the parameter)</returns>
|
||||||
|
public MqttTopicTemplate WithParameter(string parameter, string value)
|
||||||
|
{
|
||||||
|
if (value == null || string.IsNullOrEmpty(parameter) || !_parameterSegments.Contains(parameter) || value.Contains(MqttTopicFilterComparer.LevelSeparator) ||
|
||||||
|
value.Contains(MqttTopicFilterComparer.MultiLevelWildcard))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("parameter must exist and value must not contain slashes.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var moustache = "{" + parameter + "}";
|
||||||
|
return new MqttTopicTemplate(Template.Replace(moustache, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reuse parameters as they are extracted using another topic template on this template
|
||||||
|
/// when the parameter name matches. Useful
|
||||||
|
/// for compatibility routing.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="parameters">
|
||||||
|
/// </param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public MqttTopicTemplate WithParameterValuesFrom(IEnumerable<(string parameter, int index, string value)> parameters)
|
||||||
|
{
|
||||||
|
return parameters.Aggregate(this, (t, p) => t.TrySetParameter(p.parameter, p.value));
|
||||||
|
}
|
||||||
|
|
||||||
|
IEnumerable<(string parameter, int index, string value)> parseParameterValuesInternal(string topic)
|
||||||
|
{
|
||||||
|
// because we have a match, we know the segment array is at least the template's length
|
||||||
|
var segments = topic.Split(MqttTopicFilterComparer.LevelSeparator);
|
||||||
|
for (var i = 0; i < _parameterSegments.Length; i++)
|
||||||
|
{
|
||||||
|
var name = _parameterSegments[i];
|
||||||
|
if (name != null)
|
||||||
|
{
|
||||||
|
yield return (name, i, segments[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using MQTTnet.Protocol;
|
||||||
|
|
||||||
|
namespace MQTTnet.Extensions.TopicTemplate
|
||||||
|
{
|
||||||
|
public static class TopicTemplateExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Modify this message builder to respond to a given message. The
|
||||||
|
/// message's response topic and correlation data are included
|
||||||
|
/// in the message builder.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="builder">
|
||||||
|
/// a message builder
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="message">
|
||||||
|
/// a message with a response topic
|
||||||
|
/// </param>
|
||||||
|
/// <returns>a message builder</returns>
|
||||||
|
/// <see
|
||||||
|
/// cref="BuildResponse" />
|
||||||
|
public static MqttApplicationMessageBuilder AsResponseTo(this MqttApplicationMessageBuilder builder, MqttApplicationMessage message)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(message.ResponseTopic))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("message does not have a response topic");
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.WithTopic(message.ResponseTopic).WithCorrelationData(message.CorrelationData);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Set the filter topic according to the template, with
|
||||||
|
/// remaining template parameters substituted by single-level
|
||||||
|
/// wildcard.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="topicTemplate">
|
||||||
|
/// a topic template
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="subscribeTreeRoot">
|
||||||
|
/// whether to subscribe to the whole topic tree
|
||||||
|
/// </param>
|
||||||
|
/// <returns>the modified topic filter</returns>
|
||||||
|
public static MqttTopicFilterBuilder BuildFilter(this MqttTopicTemplate topicTemplate, bool subscribeTreeRoot = false)
|
||||||
|
{
|
||||||
|
return new MqttTopicFilterBuilder().WithTopicTemplate(topicTemplate, subscribeTreeRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Return a message builder to respond to this message. The
|
||||||
|
/// message's response topic and correlation data are included
|
||||||
|
/// in the response message builder.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="message">
|
||||||
|
/// a message with a response topic
|
||||||
|
/// </param>
|
||||||
|
/// <returns>a message builder</returns>
|
||||||
|
/// <see
|
||||||
|
/// cref="AsResponseTo" />
|
||||||
|
public static MqttApplicationMessageBuilder BuildResponse(this MqttApplicationMessage message)
|
||||||
|
{
|
||||||
|
return new MqttApplicationMessageBuilder().AsResponseTo(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Return whether the message matches the given topic template.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="message">
|
||||||
|
/// a message
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="topicTemplate">
|
||||||
|
/// a topic template
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="subtree">
|
||||||
|
/// whether to include the topic subtree
|
||||||
|
/// </param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static bool MatchesTopicTemplate(this MqttApplicationMessage message, MqttTopicTemplate topicTemplate, bool subtree = false)
|
||||||
|
{
|
||||||
|
return topicTemplate.MatchesTopic(message.Topic, subtree);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Set the filter topic according to the template, with
|
||||||
|
/// template parameters substituted by a single-level
|
||||||
|
/// wildcard.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="builder">
|
||||||
|
/// a filter builder
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="topicTemplate">
|
||||||
|
/// a topic template
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="subscribeTreeRoot">
|
||||||
|
/// whether to subscribe to the whole topic tree
|
||||||
|
/// </param>
|
||||||
|
/// <returns>the modified topic filter</returns>
|
||||||
|
public static MqttTopicFilterBuilder WithTopicTemplate(this MqttTopicFilterBuilder builder, MqttTopicTemplate topicTemplate, bool subscribeTreeRoot = false)
|
||||||
|
{
|
||||||
|
return builder.WithTopic(subscribeTreeRoot ? topicTemplate.TopicTreeRootFilter : topicTemplate.TopicFilter);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Set the publication topic according to the topic template. The template
|
||||||
|
/// must not have remaining (unset) parameters or contain wildcards.
|
||||||
|
/// </summary>
|
||||||
|
/// <param
|
||||||
|
/// name="builder">
|
||||||
|
/// a message builder
|
||||||
|
/// </param>
|
||||||
|
/// <param
|
||||||
|
/// name="topicTemplate">
|
||||||
|
/// a parameterless topic template
|
||||||
|
/// </param>
|
||||||
|
/// <returns>the modified message builder</returns>
|
||||||
|
/// <exception
|
||||||
|
/// cref="ArgumentException">
|
||||||
|
/// if the topic template has parameters
|
||||||
|
/// </exception>
|
||||||
|
public static MqttApplicationMessageBuilder WithTopicTemplate(this MqttApplicationMessageBuilder builder, MqttTopicTemplate topicTemplate)
|
||||||
|
{
|
||||||
|
if (topicTemplate.Parameters.Any())
|
||||||
|
{
|
||||||
|
throw new ArgumentException("topic templates must be parameter-less when sending " + topicTemplate.Template);
|
||||||
|
}
|
||||||
|
|
||||||
|
MqttTopicValidator.ThrowIfInvalid(topicTemplate.Template);
|
||||||
|
return builder.WithTopic(topicTemplate.Template);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFrameworks>netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
|
<TargetFrameworks>netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
|
||||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461</TargetFrameworks>
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461;net48</TargetFrameworks>
|
||||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||||
|
|
||||||
<AssemblyName>MQTTnet.Extensions.WebSocket4Net</AssemblyName>
|
<AssemblyName>MQTTnet.Extensions.WebSocket4Net</AssemblyName>
|
||||||
|
|||||||
@@ -47,13 +47,13 @@ namespace MQTTnet.Extensions.WebSocket4Net
|
|||||||
var uri = _webSocketOptions.Uri;
|
var uri = _webSocketOptions.Uri;
|
||||||
if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) && !uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase))
|
if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) && !uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
if (_webSocketOptions.TlsOptions?.UseTls == false)
|
if (_webSocketOptions.TlsOptions?.UseTls == true)
|
||||||
{
|
{
|
||||||
uri = "ws://" + uri;
|
uri = "wss://" + uri;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
uri = "wss://" + uri;
|
uri = "ws://" + uri;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ namespace MQTTnet.Extensions.WebSocket4Net
|
|||||||
List<KeyValuePair<string, string>> customHeaders = null;
|
List<KeyValuePair<string, string>> customHeaders = null;
|
||||||
if (_webSocketOptions.RequestHeaders != null)
|
if (_webSocketOptions.RequestHeaders != null)
|
||||||
{
|
{
|
||||||
customHeaders = _webSocketOptions.RequestHeaders.Select(i => new KeyValuePair<string, string>(i.Key, i.Value)).ToList();
|
customHeaders = _webSocketOptions.RequestHeaders.ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
EndPoint proxy = null;
|
EndPoint proxy = null;
|
||||||
@@ -92,18 +92,7 @@ namespace MQTTnet.Extensions.WebSocket4Net
|
|||||||
var webSocketVersion = WebSocketVersion.None;
|
var webSocketVersion = WebSocketVersion.None;
|
||||||
var receiveBufferSize = 0;
|
var receiveBufferSize = 0;
|
||||||
|
|
||||||
var certificates = new X509CertificateCollection();
|
var certificates = _webSocketOptions.TlsOptions?.ClientCertificatesProvider?.GetCertificates();
|
||||||
if (_webSocketOptions.TlsOptions?.Certificates != null)
|
|
||||||
{
|
|
||||||
foreach (var certificate in _webSocketOptions.TlsOptions.Certificates)
|
|
||||||
{
|
|
||||||
#if WINDOWS_UWP
|
|
||||||
certificates.Add(new X509Certificate(certificate));
|
|
||||||
#else
|
|
||||||
certificates.Add(certificate);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_webSocket = new WebSocket(uri, subProtocol, cookies, customHeaders, userAgent, origin, webSocketVersion, proxy, sslProtocols, receiveBufferSize)
|
_webSocket = new WebSocket(uri, subProtocol, cookies, customHeaders, userAgent, origin, webSocketVersion, proxy, sslProtocols, receiveBufferSize)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using System;
|
using System;
|
||||||
|
using System.Net;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Diagnostics;
|
using MQTTnet.Diagnostics;
|
||||||
@@ -27,7 +28,7 @@ namespace MQTTnet.TestApp
|
|||||||
{
|
{
|
||||||
ChannelOptions = new MqttClientTcpOptions
|
ChannelOptions = new MqttClientTcpOptions
|
||||||
{
|
{
|
||||||
Server = "127.0.0.1"
|
RemoteEndpoint = new DnsEndPoint("127.0.0.1", 0)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
|
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
|
||||||
<DisableImplicitAspNetCoreAnalyzers>true</DisableImplicitAspNetCoreAnalyzers>
|
<DisableImplicitAspNetCoreAnalyzers>true</DisableImplicitAspNetCoreAnalyzers>
|
||||||
<NoWarn>1591;NETSDK1138</NoWarn>
|
<NoWarn>1591;NETSDK1138</NoWarn>
|
||||||
|
<LangVersion>7.3</LangVersion>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Net;
|
||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using MQTTnet.Extensions.ManagedClient;
|
using MQTTnet.Extensions.ManagedClient;
|
||||||
using MQTTnet.Internal;
|
using MQTTnet.Internal;
|
||||||
@@ -28,7 +29,7 @@ namespace MQTTnet.TestApp
|
|||||||
Credentials = new RandomPassword(),
|
Credentials = new RandomPassword(),
|
||||||
ChannelOptions = new MqttClientTcpOptions
|
ChannelOptions = new MqttClientTcpOptions
|
||||||
{
|
{
|
||||||
Server = "broker.hivemq.com"
|
RemoteEndpoint = new DnsEndPoint("broker.hivemq.com", 0)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -5,13 +5,13 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Net;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
using MQTTnet.Server;
|
using MQTTnet.Server;
|
||||||
using MqttClient = MQTTnet.Client.MqttClient;
|
|
||||||
|
|
||||||
namespace MQTTnet.TestApp
|
namespace MQTTnet.TestApp
|
||||||
{
|
{
|
||||||
@@ -25,7 +25,7 @@ namespace MQTTnet.TestApp
|
|||||||
{
|
{
|
||||||
ChannelOptions = new MqttClientTcpOptions
|
ChannelOptions = new MqttClientTcpOptions
|
||||||
{
|
{
|
||||||
Server = "127.0.0.1"
|
RemoteEndpoint = new DnsEndPoint("127.0.0.1", 0)
|
||||||
},
|
},
|
||||||
CleanSession = true
|
CleanSession = true
|
||||||
};
|
};
|
||||||
@@ -71,7 +71,7 @@ namespace MQTTnet.TestApp
|
|||||||
{
|
{
|
||||||
ChannelOptions = new MqttClientTcpOptions
|
ChannelOptions = new MqttClientTcpOptions
|
||||||
{
|
{
|
||||||
Server = "127.0.0.1"
|
RemoteEndpoint = new DnsEndPoint("127.0.0.1", 0)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -114,7 +114,10 @@ namespace MQTTnet.TestApp
|
|||||||
{
|
{
|
||||||
var options = new MqttClientOptions
|
var options = new MqttClientOptions
|
||||||
{
|
{
|
||||||
ChannelOptions = new MqttClientTcpOptions { Server = "localhost" },
|
ChannelOptions = new MqttClientTcpOptions
|
||||||
|
{
|
||||||
|
RemoteEndpoint = new DnsEndPoint("localhost", 0)
|
||||||
|
},
|
||||||
ClientId = "Client1",
|
ClientId = "Client1",
|
||||||
CleanSession = true
|
CleanSession = true
|
||||||
};
|
};
|
||||||
@@ -218,7 +221,7 @@ namespace MQTTnet.TestApp
|
|||||||
{
|
{
|
||||||
ChannelOptions = new MqttClientTcpOptions
|
ChannelOptions = new MqttClientTcpOptions
|
||||||
{
|
{
|
||||||
Server = "127.0.0.1"
|
RemoteEndpoint = new DnsEndPoint("127.0.0.1", 0)
|
||||||
},
|
},
|
||||||
CleanSession = true
|
CleanSession = true
|
||||||
};
|
};
|
||||||
@@ -269,7 +272,7 @@ namespace MQTTnet.TestApp
|
|||||||
{
|
{
|
||||||
ChannelOptions = new MqttClientTcpOptions
|
ChannelOptions = new MqttClientTcpOptions
|
||||||
{
|
{
|
||||||
Server = "127.0.0.1"
|
RemoteEndpoint = new DnsEndPoint("127.0.0.1", 0)
|
||||||
},
|
},
|
||||||
CleanSession = true
|
CleanSession = true
|
||||||
};
|
};
|
||||||
@@ -320,7 +323,7 @@ namespace MQTTnet.TestApp
|
|||||||
{
|
{
|
||||||
ChannelOptions = new MqttClientTcpOptions
|
ChannelOptions = new MqttClientTcpOptions
|
||||||
{
|
{
|
||||||
Server = "127.0.0.1"
|
RemoteEndpoint = new DnsEndPoint("127.0.0.1", 0)
|
||||||
},
|
},
|
||||||
CleanSession = true
|
CleanSession = true
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -20,143 +20,155 @@ namespace MQTTnet.TestApp
|
|||||||
{
|
{
|
||||||
#if NET5_0_OR_GREATER
|
#if NET5_0_OR_GREATER
|
||||||
// TLS13 is only available in Net5.0
|
// TLS13 is only available in Net5.0
|
||||||
var unsafeTls13 = new MqttClientOptionsBuilderTlsParameters
|
var unsafeTls13 = new MqttClientTlsOptions
|
||||||
{
|
{
|
||||||
UseTls = true,
|
UseTls = true,
|
||||||
SslProtocol = SslProtocols.Tls13,
|
SslProtocol = SslProtocols.Tls13,
|
||||||
// Don't use this in production code. This handler simply allows any invalid certificate to work.
|
// Don't use this in production code. This handler simply allows any invalid certificate to work.
|
||||||
CertificateValidationHandler = w => true
|
AllowUntrustedCertificates = true,
|
||||||
|
IgnoreCertificateChainErrors = true,
|
||||||
|
CertificateValidationHandler = _ => true
|
||||||
};
|
};
|
||||||
#endif
|
#endif
|
||||||
// Also defining TLS12 for servers that don't seem no to support TLS13.
|
// Also defining TLS12 for servers that don't seem no to support TLS13.
|
||||||
var unsafeTls12 = new MqttClientOptionsBuilderTlsParameters
|
var unsafeTls12 = new MqttClientTlsOptions
|
||||||
{
|
{
|
||||||
UseTls = true,
|
UseTls = true,
|
||||||
SslProtocol = SslProtocols.Tls12,
|
SslProtocol = SslProtocols.Tls12,
|
||||||
// Don't use this in production code. This handler simply allows any invalid certificate to work.
|
// Don't use this in production code. This handler simply allows any invalid certificate to work.
|
||||||
CertificateValidationHandler = w => true
|
AllowUntrustedCertificates = true,
|
||||||
|
IgnoreCertificateChainErrors = true,
|
||||||
|
CertificateValidationHandler = _ => true
|
||||||
};
|
};
|
||||||
|
|
||||||
// mqtt.eclipseprojects.io
|
// mqtt.eclipseprojects.io
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"mqtt.eclipseprojects.io TCP",
|
"mqtt.eclipseprojects.io TCP",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("mqtt.eclipseprojects.io", 1883).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithTcpServer("mqtt.eclipseprojects.io", 1883).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"mqtt.eclipseprojects.io WS",
|
"mqtt.eclipseprojects.io WS",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("mqtt.eclipseprojects.io:80/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("mqtt.eclipseprojects.io:80/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
#if NET5_0_OR_GREATER
|
#if NET5_0_OR_GREATER
|
||||||
await ExecuteTestAsync("mqtt.eclipseprojects.io WS TLS13",
|
await ExecuteTestsAsync("mqtt.eclipseprojects.io WS TLS13",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("mqtt.eclipseprojects.io:443/mqtt")
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("mqtt.eclipseprojects.io:443/mqtt"))
|
||||||
.WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls13).Build());
|
.WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls13).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync("mqtt.eclipseprojects.io WS TLS13 (WebSocket4Net)",
|
await ExecuteTestsAsync("mqtt.eclipseprojects.io WS TLS13 (WebSocket4Net)",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("mqtt.eclipseprojects.io:443/mqtt")
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("mqtt.eclipseprojects.io:443/mqtt"))
|
||||||
.WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls13).Build(),
|
.WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls13).Build(),
|
||||||
true);
|
true);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// test.mosquitto.org
|
// test.mosquitto.org
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"test.mosquitto.org TCP",
|
"test.mosquitto.org TCP",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 1883).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 1883).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"test.mosquitto.org TCP - Authenticated",
|
"test.mosquitto.org TCP - Authenticated",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 1884).WithCredentials("rw", "readwrite").WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 1884).WithCredentials("rw", "readwrite").WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"test.mosquitto.org TCP TLS12",
|
"test.mosquitto.org TCP TLS12",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8883).WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls12).Build());
|
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8883).WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls12).Build());
|
||||||
|
|
||||||
#if NET5_0_OR_GREATER
|
#if NET5_0_OR_GREATER
|
||||||
await ExecuteTestAsync("test.mosquitto.org TCP TLS13",
|
await ExecuteTestsAsync("test.mosquitto.org TCP TLS13",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8883)
|
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8883)
|
||||||
.WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls13).Build());
|
.WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls13).Build());
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"test.mosquitto.org TCP TLS12 - Authenticated",
|
"test.mosquitto.org TCP TLS12 - Authenticated",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8885)
|
new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8885)
|
||||||
.WithCredentials("rw", "readwrite")
|
.WithCredentials("rw", "readwrite")
|
||||||
.WithProtocolVersion(MqttProtocolVersion.V311)
|
.WithProtocolVersion(MqttProtocolVersion.V311)
|
||||||
.WithTls(unsafeTls12)
|
.WithTlsOptions(unsafeTls12)
|
||||||
.Build());
|
.Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"test.mosquitto.org WS",
|
"test.mosquitto.org WS",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("test.mosquitto.org:8080/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("test.mosquitto.org:8080/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"test.mosquitto.org WS (WebSocket4Net)",
|
"test.mosquitto.org WS (WebSocket4Net)",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("test.mosquitto.org:8080/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).Build(),
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("test.mosquitto.org:8080/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).Build(),
|
||||||
true);
|
true);
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"test.mosquitto.org WS TLS12",
|
"test.mosquitto.org WS TLS12",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("test.mosquitto.org:8081/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls12).Build());
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("test.mosquitto.org:8081/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls12).Build());
|
||||||
|
|
||||||
// await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
// "test.mosquitto.org WS TLS12 (WebSocket4Net)",
|
"test.mosquitto.org WS TLS12 (WebSocket4Net)",
|
||||||
// new MqttClientOptionsBuilder().WithWebSocketServer("test.mosquitto.org:8081/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls12).Build(),
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("test.mosquitto.org:8081/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls12).Build(),
|
||||||
// true);
|
true);
|
||||||
|
|
||||||
// broker.emqx.io
|
// broker.emqx.io
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.emqx.io TCP",
|
"broker.emqx.io TCP",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 1883).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 1883).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.emqx.io TCP TLS12",
|
"broker.emqx.io TCP TLS12",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 8883).WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls12).Build());
|
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 8883).WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls12).Build());
|
||||||
|
|
||||||
#if NET5_0_OR_GREATER
|
#if NET5_0_OR_GREATER
|
||||||
await ExecuteTestAsync("broker.emqx.io TCP TLS13",
|
await ExecuteTestsAsync("broker.emqx.io TCP TLS13",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 8883)
|
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 8883)
|
||||||
.WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls13).Build());
|
.WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls13).Build());
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.emqx.io WS",
|
"broker.emqx.io WS",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("broker.emqx.io:8083/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("broker.emqx.io:8083/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.emqx.io WS (WebSocket4Net)",
|
"broker.emqx.io WS (WebSocket4Net)",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("broker.emqx.io:8084/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).Build(),
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("broker.emqx.io:8084/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).Build(),
|
||||||
true);
|
true);
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.emqx.io WS TLS12",
|
"broker.emqx.io WS TLS12",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("broker.emqx.io:8084/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls12).Build());
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("broker.emqx.io:8084/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls12).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.emqx.io WS TLS12 (WebSocket4Net)",
|
"broker.emqx.io WS TLS12 (WebSocket4Net)",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("broker.emqx.io:8084/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls12).Build(),
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("broker.emqx.io:8084/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).WithTlsOptions(unsafeTls12).Build(),
|
||||||
true);
|
true);
|
||||||
|
|
||||||
// broker.hivemq.com
|
// broker.hivemq.com
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.hivemq.com TCP",
|
"broker.hivemq.com TCP",
|
||||||
new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com", 1883).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com", 1883).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.hivemq.com WS",
|
"broker.hivemq.com WS",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("broker.hivemq.com:8000/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("broker.hivemq.com:8000/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).Build());
|
||||||
|
|
||||||
await ExecuteTestAsync(
|
await ExecuteTestsAsync(
|
||||||
"broker.hivemq.com WS (WebSocket4Net)",
|
"broker.hivemq.com WS (WebSocket4Net)",
|
||||||
new MqttClientOptionsBuilder().WithWebSocketServer("broker.hivemq.com:8000/mqtt").WithProtocolVersion(MqttProtocolVersion.V311).Build(),
|
new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("broker.hivemq.com:8000/mqtt")).WithProtocolVersion(MqttProtocolVersion.V311).Build(),
|
||||||
true);
|
true);
|
||||||
|
|
||||||
// mqtt.swifitch.cz: Does not seem to operate any more
|
// mqtt.swifitch.cz: Does not seem to operate any more
|
||||||
|
|
||||||
// cloudmqtt.com: Cannot test because it does not offer a free plan any more.
|
// cloudmqtt.com: Cannot test because it does not offer a free plan any more.
|
||||||
|
|
||||||
Write("Finished.", ConsoleColor.White);
|
Write("Finished.", ConsoleColor.White);
|
||||||
Console.ReadLine();
|
Console.ReadLine();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static async Task ExecuteTestsAsync(string name, MqttClientOptions options, bool useWebSocket4Net = false)
|
||||||
|
{
|
||||||
|
options.ProtocolVersion = MqttProtocolVersion.V311;
|
||||||
|
await ExecuteTestAsync(name + " V3.1.1", options, useWebSocket4Net);
|
||||||
|
|
||||||
|
options.ProtocolVersion = MqttProtocolVersion.V500;
|
||||||
|
await ExecuteTestAsync(name + " V5.0.0", options, useWebSocket4Net);
|
||||||
|
}
|
||||||
|
|
||||||
static async Task ExecuteTestAsync(string name, MqttClientOptions options, bool useWebSocket4Net = false)
|
static async Task ExecuteTestAsync(string name, MqttClientOptions options, bool useWebSocket4Net = false)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -197,9 +209,10 @@ namespace MQTTnet.TestApp
|
|||||||
|
|
||||||
Write("[OK]\n", ConsoleColor.Green);
|
Write("[OK]\n", ConsoleColor.Green);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
Write("[FAILED] " + e.Message + "\n", ConsoleColor.Red);
|
Write("[FAILED]" + Environment.NewLine, ConsoleColor.Red);
|
||||||
|
Write(exception + Environment.NewLine, ConsoleColor.Red);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ using MQTTnet.Exceptions;
|
|||||||
using MQTTnet.LowLevelClient;
|
using MQTTnet.LowLevelClient;
|
||||||
using MQTTnet.Packets;
|
using MQTTnet.Packets;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
|
using MQTTnet.Server;
|
||||||
|
|
||||||
namespace MQTTnet.Tests.Clients.LowLevelMqttClient
|
namespace MQTTnet.Tests.Clients.LowLevelMqttClient
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ using MQTTnet.Diagnostics;
|
|||||||
using MQTTnet.Extensions.ManagedClient;
|
using MQTTnet.Extensions.ManagedClient;
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
using MQTTnet.Internal;
|
using MQTTnet.Internal;
|
||||||
|
using MQTTnet.Packets;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
using MQTTnet.Server;
|
using MQTTnet.Server;
|
||||||
using MQTTnet.Tests.Mockups;
|
using MQTTnet.Tests.Mockups;
|
||||||
@@ -22,67 +23,6 @@ namespace MQTTnet.Tests.Clients.ManagedMqttClient
|
|||||||
[TestClass]
|
[TestClass]
|
||||||
public sealed class ManagedMqttClient_Tests : BaseTestClass
|
public sealed class ManagedMqttClient_Tests : BaseTestClass
|
||||||
{
|
{
|
||||||
[TestMethod]
|
|
||||||
public async Task Receive_While_Not_Cleanly_Disconnected()
|
|
||||||
{
|
|
||||||
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
|
||||||
{
|
|
||||||
await testEnvironment.StartServer(o => o.WithPersistentSessions());
|
|
||||||
|
|
||||||
var senderClient = await testEnvironment.ConnectClient();
|
|
||||||
|
|
||||||
// Prepare managed client.
|
|
||||||
var managedClient = testEnvironment.Factory.CreateManagedMqttClient();
|
|
||||||
await managedClient.SubscribeAsync("#");
|
|
||||||
var receivedMessages = testEnvironment.CreateApplicationMessageHandler(managedClient);
|
|
||||||
|
|
||||||
var managedClientOptions = new ManagedMqttClientOptions
|
|
||||||
{
|
|
||||||
ClientOptions = testEnvironment.Factory.CreateClientOptionsBuilder()
|
|
||||||
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
|
||||||
.WithClientId(nameof(Receive_While_Not_Cleanly_Disconnected) + "_managed")
|
|
||||||
.WithCleanSession(false)
|
|
||||||
.Build()
|
|
||||||
};
|
|
||||||
|
|
||||||
await managedClient.StartAsync(managedClientOptions);
|
|
||||||
await LongTestDelay();
|
|
||||||
await LongTestDelay();
|
|
||||||
|
|
||||||
// Send test data.
|
|
||||||
await senderClient.PublishStringAsync("topic1");
|
|
||||||
await LongTestDelay();
|
|
||||||
await LongTestDelay();
|
|
||||||
|
|
||||||
receivedMessages.AssertReceivedCountEquals(1);
|
|
||||||
|
|
||||||
// Stop the managed client but keep session at server (not clean disconnect required).
|
|
||||||
await managedClient.StopAsync(false);
|
|
||||||
await LongTestDelay();
|
|
||||||
|
|
||||||
// Send new messages in the meantime.
|
|
||||||
await senderClient.PublishStringAsync("topic2", qualityOfServiceLevel: MqttQualityOfServiceLevel.ExactlyOnce);
|
|
||||||
await LongTestDelay();
|
|
||||||
|
|
||||||
// Start the managed client, it should receive the new message.
|
|
||||||
await managedClient.StartAsync(managedClientOptions);
|
|
||||||
await LongTestDelay();
|
|
||||||
|
|
||||||
receivedMessages.AssertReceivedCountEquals(2);
|
|
||||||
|
|
||||||
// Stop and start again, no new message should be received.
|
|
||||||
for (var i = 0; i < 3; i++)
|
|
||||||
{
|
|
||||||
await managedClient.StopAsync(false);
|
|
||||||
await LongTestDelay();
|
|
||||||
await managedClient.StartAsync(managedClientOptions);
|
|
||||||
await LongTestDelay();
|
|
||||||
}
|
|
||||||
|
|
||||||
receivedMessages.AssertReceivedCountEquals(2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public async Task Connect_To_Invalid_Server()
|
public async Task Connect_To_Invalid_Server()
|
||||||
{
|
{
|
||||||
@@ -149,6 +89,38 @@ namespace MQTTnet.Tests.Clients.ManagedMqttClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Expose_Custom_Connection_Error()
|
||||||
|
{
|
||||||
|
using (var testEnvironment = CreateTestEnvironment())
|
||||||
|
{
|
||||||
|
var server = await testEnvironment.StartServer();
|
||||||
|
|
||||||
|
server.ValidatingConnectionAsync += args =>
|
||||||
|
{
|
||||||
|
args.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
var managedClient = testEnvironment.Factory.CreateManagedMqttClient();
|
||||||
|
|
||||||
|
MqttClientDisconnectedEventArgs disconnectedArgs = null;
|
||||||
|
managedClient.DisconnectedAsync += args =>
|
||||||
|
{
|
||||||
|
disconnectedArgs = args;
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
var clientOptions = testEnvironment.Factory.CreateManagedMqttClientOptionsBuilder().WithClientOptions(testEnvironment.CreateDefaultClientOptions()).Build();
|
||||||
|
await managedClient.StartAsync(clientOptions);
|
||||||
|
|
||||||
|
await LongTestDelay();
|
||||||
|
|
||||||
|
Assert.IsNotNull(disconnectedArgs);
|
||||||
|
Assert.AreEqual(MqttClientConnectResultCode.BadUserNameOrPassword, disconnectedArgs.ConnectResult.ResultCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public async Task ManagedClients_Will_Message_Send()
|
public async Task ManagedClients_Will_Message_Send()
|
||||||
{
|
{
|
||||||
@@ -192,6 +164,67 @@ namespace MQTTnet.Tests.Clients.ManagedMqttClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Receive_While_Not_Cleanly_Disconnected()
|
||||||
|
{
|
||||||
|
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||||
|
{
|
||||||
|
await testEnvironment.StartServer(o => o.WithPersistentSessions());
|
||||||
|
|
||||||
|
var senderClient = await testEnvironment.ConnectClient();
|
||||||
|
|
||||||
|
// Prepare managed client.
|
||||||
|
var managedClient = testEnvironment.Factory.CreateManagedMqttClient();
|
||||||
|
await managedClient.SubscribeAsync("#");
|
||||||
|
var receivedMessages = testEnvironment.CreateApplicationMessageHandler(managedClient);
|
||||||
|
|
||||||
|
var managedClientOptions = new ManagedMqttClientOptions
|
||||||
|
{
|
||||||
|
ClientOptions = testEnvironment.Factory.CreateClientOptionsBuilder()
|
||||||
|
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||||
|
.WithClientId(nameof(Receive_While_Not_Cleanly_Disconnected) + "_managed")
|
||||||
|
.WithCleanSession(false)
|
||||||
|
.Build()
|
||||||
|
};
|
||||||
|
|
||||||
|
await managedClient.StartAsync(managedClientOptions);
|
||||||
|
await LongTestDelay();
|
||||||
|
await LongTestDelay();
|
||||||
|
|
||||||
|
// Send test data.
|
||||||
|
await senderClient.PublishStringAsync("topic1");
|
||||||
|
await LongTestDelay();
|
||||||
|
await LongTestDelay();
|
||||||
|
|
||||||
|
receivedMessages.AssertReceivedCountEquals(1);
|
||||||
|
|
||||||
|
// Stop the managed client but keep session at server (not clean disconnect required).
|
||||||
|
await managedClient.StopAsync(false);
|
||||||
|
await LongTestDelay();
|
||||||
|
|
||||||
|
// Send new messages in the meantime.
|
||||||
|
await senderClient.PublishStringAsync("topic2", qualityOfServiceLevel: MqttQualityOfServiceLevel.ExactlyOnce);
|
||||||
|
await LongTestDelay();
|
||||||
|
|
||||||
|
// Start the managed client, it should receive the new message.
|
||||||
|
await managedClient.StartAsync(managedClientOptions);
|
||||||
|
await LongTestDelay();
|
||||||
|
|
||||||
|
receivedMessages.AssertReceivedCountEquals(2);
|
||||||
|
|
||||||
|
// Stop and start again, no new message should be received.
|
||||||
|
for (var i = 0; i < 3; i++)
|
||||||
|
{
|
||||||
|
await managedClient.StopAsync(false);
|
||||||
|
await LongTestDelay();
|
||||||
|
await managedClient.StartAsync(managedClientOptions);
|
||||||
|
await LongTestDelay();
|
||||||
|
}
|
||||||
|
|
||||||
|
receivedMessages.AssertReceivedCountEquals(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public async Task Start_Stop()
|
public async Task Start_Stop()
|
||||||
{
|
{
|
||||||
@@ -389,7 +422,7 @@ namespace MQTTnet.Tests.Clients.ManagedMqttClient
|
|||||||
var receivingClient = await CreateManagedClientAsync(testEnvironment, null, connectionCheckInterval);
|
var receivingClient = await CreateManagedClientAsync(testEnvironment, null, connectionCheckInterval);
|
||||||
var sendingClient = await testEnvironment.ConnectClient();
|
var sendingClient = await testEnvironment.ConnectClient();
|
||||||
|
|
||||||
await sendingClient.PublishAsync(new MqttApplicationMessage { Topic = "topic", Payload = new byte[] { 1 }, Retain = true });
|
await sendingClient.PublishAsync(new MqttApplicationMessage { Topic = "topic", PayloadSegment = new ArraySegment<byte>(new byte[] { 1 }), Retain = true });
|
||||||
|
|
||||||
var subscribeTime = DateTime.UtcNow;
|
var subscribeTime = DateTime.UtcNow;
|
||||||
|
|
||||||
@@ -405,6 +438,109 @@ namespace MQTTnet.Tests.Clients.ManagedMqttClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ManagedClients_CanInterceptPublishedMessage_PreventingPublish()
|
||||||
|
{
|
||||||
|
using (var testEnvironment = CreateTestEnvironment())
|
||||||
|
{
|
||||||
|
await testEnvironment.StartServer();
|
||||||
|
|
||||||
|
var receivedMessagesCount = 0;
|
||||||
|
var interceptedMessagesCount = 0;
|
||||||
|
|
||||||
|
var clientOptions = new MqttClientOptionsBuilder()
|
||||||
|
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
var sendingClient = testEnvironment.CreateClient();
|
||||||
|
var sendingManagedClient = new MQTTnet.Extensions.ManagedClient.ManagedMqttClient(sendingClient, testEnvironment.ClientLogger);
|
||||||
|
|
||||||
|
await sendingManagedClient.StartAsync(new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).Build());
|
||||||
|
|
||||||
|
// Wait until the managed client is fully set up and running.
|
||||||
|
await Task.Delay(1000);
|
||||||
|
|
||||||
|
var receivingClient = await testEnvironment.ConnectClient();
|
||||||
|
|
||||||
|
receivingClient.ApplicationMessageReceivedAsync += e =>
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref receivedMessagesCount);
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
sendingManagedClient.InterceptPublishMessageAsync += e =>
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref interceptedMessagesCount);
|
||||||
|
e.AcceptPublish = false;
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
await receivingClient.SubscribeAsync("My/last/will");
|
||||||
|
|
||||||
|
// Wait for arrival of the will message at the receiver.
|
||||||
|
await Task.Delay(5000);
|
||||||
|
|
||||||
|
await sendingManagedClient.EnqueueAsync("My/last/will", "hello world");
|
||||||
|
|
||||||
|
// Wait for arrival of the will message at the receiver.
|
||||||
|
await Task.Delay(5000);
|
||||||
|
|
||||||
|
Assert.AreEqual(0, receivedMessagesCount);
|
||||||
|
Assert.AreEqual(1, interceptedMessagesCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ManagedClients_CanInterceptPublishedMessage_AllowingPublish()
|
||||||
|
{
|
||||||
|
using (var testEnvironment = CreateTestEnvironment())
|
||||||
|
{
|
||||||
|
await testEnvironment.StartServer();
|
||||||
|
|
||||||
|
var receivedMessagesCount = 0;
|
||||||
|
var interceptedMessagesCount = 0;
|
||||||
|
|
||||||
|
var clientOptions = new MqttClientOptionsBuilder()
|
||||||
|
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
var sendingClient = testEnvironment.CreateClient();
|
||||||
|
var sendingManagedClient = new MQTTnet.Extensions.ManagedClient.ManagedMqttClient(sendingClient, testEnvironment.ClientLogger);
|
||||||
|
|
||||||
|
await sendingManagedClient.StartAsync(new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).Build());
|
||||||
|
|
||||||
|
// Wait until the managed client is fully set up and running.
|
||||||
|
await Task.Delay(1000);
|
||||||
|
|
||||||
|
var receivingClient = await testEnvironment.ConnectClient();
|
||||||
|
|
||||||
|
receivingClient.ApplicationMessageReceivedAsync += e =>
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref receivedMessagesCount);
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
sendingManagedClient.InterceptPublishMessageAsync += e =>
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref interceptedMessagesCount);
|
||||||
|
e.AcceptPublish = true;
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
await receivingClient.SubscribeAsync("My/last/will");
|
||||||
|
|
||||||
|
// Wait for arrival of the will message at the receiver.
|
||||||
|
await Task.Delay(5000);
|
||||||
|
|
||||||
|
await sendingManagedClient.EnqueueAsync("My/last/will", "hello world");
|
||||||
|
|
||||||
|
// Wait for arrival of the will message at the receiver.
|
||||||
|
await Task.Delay(5000);
|
||||||
|
|
||||||
|
Assert.AreEqual(1, receivedMessagesCount);
|
||||||
|
Assert.AreEqual(1, interceptedMessagesCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// This case also serves as a regression test for the previous behavior which re-published
|
// This case also serves as a regression test for the previous behavior which re-published
|
||||||
// each and every existing subscriptions with every new subscription that was made
|
// each and every existing subscriptions with every new subscription that was made
|
||||||
// (causing performance problems and having the visible symptom of retained messages being received again)
|
// (causing performance problems and having the visible symptom of retained messages being received again)
|
||||||
@@ -422,7 +558,7 @@ namespace MQTTnet.Tests.Clients.ManagedMqttClient
|
|||||||
//wait a bit for the subscription to become established
|
//wait a bit for the subscription to become established
|
||||||
await Task.Delay(500);
|
await Task.Delay(500);
|
||||||
|
|
||||||
await sendingClient.PublishAsync(new MqttApplicationMessage { Topic = "topic", Payload = new byte[] { 1 }, Retain = true });
|
await sendingClient.PublishAsync(new MqttApplicationMessage { Topic = "topic", PayloadSegment = new ArraySegment<byte>(new byte[] { 1 }), Retain = true });
|
||||||
|
|
||||||
var messages = await SetupReceivingOfMessages(managedClient, 1);
|
var messages = await SetupReceivingOfMessages(managedClient, 1);
|
||||||
|
|
||||||
@@ -439,16 +575,154 @@ namespace MQTTnet.Tests.Clients.ManagedMqttClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Subscribe_Does_Not_Hang_On_Server_Stop()
|
||||||
|
{
|
||||||
|
var timeout = TimeSpan.FromSeconds(2);
|
||||||
|
var testTimeout = TimeSpan.FromSeconds(timeout.TotalSeconds * 2);
|
||||||
|
const string topic = "test_topic_2";
|
||||||
|
using (var testEnvironment = CreateTestEnvironment())
|
||||||
|
using (var managedClient = await CreateManagedClientAsync(testEnvironment, timeout: timeout))
|
||||||
|
{
|
||||||
|
testEnvironment.IgnoreClientLogErrors = true;
|
||||||
|
bool reject = true;
|
||||||
|
var receivedOnServer = new SemaphoreSlim(0, 1);
|
||||||
|
var failedOnClient = new SemaphoreSlim(0, 1);
|
||||||
|
testEnvironment.Server.InterceptingInboundPacketAsync += e =>
|
||||||
|
{
|
||||||
|
if (e.Packet is MqttSubscribePacket)
|
||||||
|
{
|
||||||
|
if (reject)
|
||||||
|
{
|
||||||
|
e.ProcessPacket = false;
|
||||||
|
}
|
||||||
|
receivedOnServer.Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
managedClient.SynchronizingSubscriptionsFailedAsync += e =>
|
||||||
|
{
|
||||||
|
failedOnClient.Release();
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
await managedClient.SubscribeAsync(topic);
|
||||||
|
Assert.IsTrue(await receivedOnServer.WaitAsync(testTimeout));
|
||||||
|
Assert.IsTrue(await failedOnClient.WaitAsync(testTimeout));
|
||||||
|
|
||||||
|
reject = false;
|
||||||
|
await managedClient.SubscribeAsync(topic);
|
||||||
|
Assert.IsTrue(await receivedOnServer.WaitAsync(testTimeout));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Unsubscribe_Does_Not_Hang_On_Server_Stop()
|
||||||
|
{
|
||||||
|
var timeout = TimeSpan.FromSeconds(2);
|
||||||
|
var testTimeout = TimeSpan.FromSeconds(timeout.TotalSeconds * 2);
|
||||||
|
const string topic = "test_topic_2";
|
||||||
|
using (var testEnvironment = CreateTestEnvironment())
|
||||||
|
using (var managedClient = await CreateManagedClientAsync(testEnvironment, timeout: timeout))
|
||||||
|
{
|
||||||
|
testEnvironment.IgnoreClientLogErrors = true;
|
||||||
|
bool reject = true;
|
||||||
|
var receivedOnServer = new SemaphoreSlim(0, 1);
|
||||||
|
var failedOnClient = new SemaphoreSlim(0, 1);
|
||||||
|
testEnvironment.Server.InterceptingInboundPacketAsync += e =>
|
||||||
|
{
|
||||||
|
if (e.Packet is MqttUnsubscribePacket)
|
||||||
|
{
|
||||||
|
if (reject)
|
||||||
|
{
|
||||||
|
e.ProcessPacket = false;
|
||||||
|
}
|
||||||
|
receivedOnServer.Release();
|
||||||
|
}
|
||||||
|
else if (e.Packet is MqttSubscribePacket)
|
||||||
|
{
|
||||||
|
receivedOnServer.Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
managedClient.SynchronizingSubscriptionsFailedAsync += e =>
|
||||||
|
{
|
||||||
|
failedOnClient.Release();
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
await managedClient.SubscribeAsync(topic);
|
||||||
|
Assert.IsTrue(await receivedOnServer.WaitAsync(testTimeout));
|
||||||
|
|
||||||
|
await managedClient.UnsubscribeAsync(topic);
|
||||||
|
Assert.IsTrue(await receivedOnServer.WaitAsync(testTimeout));
|
||||||
|
Assert.IsTrue(await failedOnClient.WaitAsync(testTimeout));
|
||||||
|
|
||||||
|
reject = false;
|
||||||
|
await managedClient.UnsubscribeAsync(topic);
|
||||||
|
Assert.IsTrue(await receivedOnServer.WaitAsync(testTimeout));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Publish_Does_Not_Hang_On_Server_Error()
|
||||||
|
{
|
||||||
|
var timeout = TimeSpan.FromSeconds(2);
|
||||||
|
var testTimeout = TimeSpan.FromSeconds(timeout.TotalSeconds * 2);
|
||||||
|
|
||||||
|
const string topic = "test_topic_42";
|
||||||
|
|
||||||
|
using (var testEnvironment = CreateTestEnvironment())
|
||||||
|
using (var managedClient = await CreateManagedClientAsync(testEnvironment, timeout: timeout))
|
||||||
|
{
|
||||||
|
testEnvironment.IgnoreClientLogErrors = true;
|
||||||
|
bool reject = true;
|
||||||
|
var receivedOnServer = new TaskCompletionSource<object>();
|
||||||
|
managedClient.ApplicationMessageProcessedAsync += e => Task.FromResult(reject &= e.Exception is null);
|
||||||
|
testEnvironment.Server.InterceptingInboundPacketAsync += e =>
|
||||||
|
{
|
||||||
|
if (e.Packet is MqttPublishPacket)
|
||||||
|
{
|
||||||
|
if (reject)
|
||||||
|
{
|
||||||
|
e.ProcessPacket = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
receivedOnServer.TrySetResult(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
await managedClient.EnqueueAsync(new MqttApplicationMessage { Topic = topic, PayloadSegment = new ArraySegment<byte>(new byte[] { 1 }), Retain = true, QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce });
|
||||||
|
|
||||||
|
var timeoutTask = Task.Delay(testTimeout);
|
||||||
|
|
||||||
|
var firstDone = await Task.WhenAny(receivedOnServer.Task, timeoutTask);
|
||||||
|
Assert.AreEqual(receivedOnServer.Task, firstDone, "Client is hung on publish!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async Task<MQTTnet.Extensions.ManagedClient.ManagedMqttClient> CreateManagedClientAsync(
|
async Task<MQTTnet.Extensions.ManagedClient.ManagedMqttClient> CreateManagedClientAsync(
|
||||||
TestEnvironment testEnvironment,
|
TestEnvironment testEnvironment,
|
||||||
IMqttClient underlyingClient = null,
|
IMqttClient underlyingClient = null,
|
||||||
TimeSpan? connectionCheckInterval = null,
|
TimeSpan? connectionCheckInterval = null,
|
||||||
string host = "localhost")
|
string host = "localhost",
|
||||||
|
TimeSpan? timeout = null)
|
||||||
{
|
{
|
||||||
await testEnvironment.StartServer();
|
await testEnvironment.StartServer();
|
||||||
|
|
||||||
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer(host, testEnvironment.ServerPort);
|
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer(host, testEnvironment.ServerPort);
|
||||||
|
|
||||||
|
if (timeout != null)
|
||||||
|
{
|
||||||
|
clientOptions.WithTimeout(timeout.Value);
|
||||||
|
}
|
||||||
|
|
||||||
var managedOptions = new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).Build();
|
var managedOptions = new ManagedMqttClientOptionsBuilder().WithClientOptions(clientOptions).Build();
|
||||||
|
|
||||||
// Use a short connection check interval so that subscription operations are performed quickly
|
// Use a short connection check interval so that subscription operations are performed quickly
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
@@ -10,6 +11,7 @@ using MQTTnet.Client;
|
|||||||
using MQTTnet.Exceptions;
|
using MQTTnet.Exceptions;
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
using MQTTnet.Internal;
|
using MQTTnet.Internal;
|
||||||
|
using MQTTnet.Packets;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
using MQTTnet.Server;
|
using MQTTnet.Server;
|
||||||
|
|
||||||
@@ -63,7 +65,7 @@ namespace MQTTnet.Tests.Clients.MqttClient
|
|||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
};
|
};
|
||||||
|
|
||||||
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("1.2.3.4").Build());
|
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").Build());
|
||||||
|
|
||||||
Assert.Fail("Must fail!");
|
Assert.Fail("Must fail!");
|
||||||
}
|
}
|
||||||
@@ -127,6 +129,8 @@ namespace MQTTnet.Tests.Clients.MqttClient
|
|||||||
// Perform a clean disconnect.
|
// Perform a clean disconnect.
|
||||||
await client.DisconnectAsync(disconnectOptions);
|
await client.DisconnectAsync(disconnectOptions);
|
||||||
|
|
||||||
|
await LongTestDelay();
|
||||||
|
|
||||||
Assert.IsNotNull(eventArgs);
|
Assert.IsNotNull(eventArgs);
|
||||||
Assert.AreEqual(MqttDisconnectReasonCode.MessageRateTooHigh, eventArgs.ReasonCode);
|
Assert.AreEqual(MqttDisconnectReasonCode.MessageRateTooHigh, eventArgs.ReasonCode);
|
||||||
}
|
}
|
||||||
@@ -162,5 +166,89 @@ namespace MQTTnet.Tests.Clients.MqttClient
|
|||||||
Assert.AreEqual("test_value", eventArgs.UserProperties[0].Value);
|
Assert.AreEqual("test_value", eventArgs.UserProperties[0].Value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task No_Unobserved_Exception()
|
||||||
|
{
|
||||||
|
using (var testEnvironment = CreateTestEnvironment())
|
||||||
|
{
|
||||||
|
testEnvironment.IgnoreClientLogErrors = true;
|
||||||
|
|
||||||
|
var client = testEnvironment.CreateClient();
|
||||||
|
var options = new MqttClientOptionsBuilder().WithTcpServer("1.2.3.4").WithTimeout(TimeSpan.FromSeconds(2)).Build();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)))
|
||||||
|
{
|
||||||
|
await client.ConnectAsync(options, timeout.Token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
client.Dispose();
|
||||||
|
|
||||||
|
// These delays and GC calls are required in order to make calling the finalizer reproducible.
|
||||||
|
GC.Collect();
|
||||||
|
GC.WaitForPendingFinalizers();
|
||||||
|
await LongTestDelay();
|
||||||
|
await LongTestDelay();
|
||||||
|
await LongTestDelay();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Return_Non_Success()
|
||||||
|
{
|
||||||
|
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||||
|
{
|
||||||
|
var server = await testEnvironment.StartServer();
|
||||||
|
|
||||||
|
server.ValidatingConnectionAsync += args =>
|
||||||
|
{
|
||||||
|
args.ResponseUserProperties = new List<MqttUserProperty>
|
||||||
|
{
|
||||||
|
new MqttUserProperty("Property", "Value")
|
||||||
|
};
|
||||||
|
|
||||||
|
args.ReasonCode = MqttConnectReasonCode.QuotaExceeded;
|
||||||
|
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
var client = testEnvironment.CreateClient();
|
||||||
|
|
||||||
|
var response = await client.ConnectAsync(testEnvironment.CreateDefaultClientOptionsBuilder().WithoutThrowOnNonSuccessfulConnectResponse().Build());
|
||||||
|
|
||||||
|
Assert.IsNotNull(response);
|
||||||
|
Assert.AreEqual(MqttClientConnectResultCode.QuotaExceeded, response.ResultCode);
|
||||||
|
Assert.AreEqual(response.UserProperties[0].Name, "Property");
|
||||||
|
Assert.AreEqual(response.UserProperties[0].Value, "Value");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Throw_Proper_Exception_When_Not_Connected()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var mqttFactory = new MqttFactory();
|
||||||
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
||||||
|
{
|
||||||
|
await mqttClient.SubscribeAsync("test", MqttQualityOfServiceLevel.AtLeastOnce);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (MqttClientNotConnectedException exception)
|
||||||
|
{
|
||||||
|
if (exception.Message == "The MQTT client is not connected.")
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Fail();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,6 +17,7 @@ using MQTTnet.Formatter;
|
|||||||
using MQTTnet.Internal;
|
using MQTTnet.Internal;
|
||||||
using MQTTnet.Packets;
|
using MQTTnet.Packets;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
|
using MQTTnet.Server;
|
||||||
using MQTTnet.Tests.Mockups;
|
using MQTTnet.Tests.Mockups;
|
||||||
|
|
||||||
// ReSharper disable InconsistentNaming
|
// ReSharper disable InconsistentNaming
|
||||||
@@ -296,7 +297,7 @@ namespace MQTTnet.Tests.Clients.MqttClient
|
|||||||
|
|
||||||
Assert.IsNotNull(receivedMessage);
|
Assert.IsNotNull(receivedMessage);
|
||||||
Assert.AreEqual("A", receivedMessage.Topic);
|
Assert.AreEqual("A", receivedMessage.Topic);
|
||||||
Assert.AreEqual(null, receivedMessage.Payload);
|
Assert.AreEqual(null, receivedMessage.PayloadSegment.Array);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -507,7 +508,7 @@ namespace MQTTnet.Tests.Clients.MqttClient
|
|||||||
|
|
||||||
client2.ApplicationMessageReceivedAsync += e =>
|
client2.ApplicationMessageReceivedAsync += e =>
|
||||||
{
|
{
|
||||||
client2TopicResults.Add(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
|
client2TopicResults.Add(Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment.ToArray()));
|
||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
// Licensed to the .NET Foundation under one or more agreements.
|
|
||||||
// The .NET Foundation licenses this file to you under the MIT license.
|
|
||||||
// See the LICENSE file in the project root for more information.
|
|
||||||
|
|
||||||
using System;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
|
||||||
using MQTTnet.Exceptions;
|
|
||||||
using MQTTnet.Internal;
|
|
||||||
|
|
||||||
namespace MQTTnet.Tests
|
|
||||||
{
|
|
||||||
[TestClass]
|
|
||||||
public class Extension_Tests
|
|
||||||
{
|
|
||||||
[ExpectedException(typeof(MqttCommunicationTimedOutException))]
|
|
||||||
[TestMethod]
|
|
||||||
public async Task TimeoutAfter()
|
|
||||||
{
|
|
||||||
await MqttTaskTimeout.WaitAsync(ct => Task.Delay(TimeSpan.FromMilliseconds(500), ct),
|
|
||||||
TimeSpan.FromMilliseconds(100), CancellationToken.None);
|
|
||||||
}
|
|
||||||
|
|
||||||
[ExpectedException(typeof(MqttCommunicationTimedOutException))]
|
|
||||||
[TestMethod]
|
|
||||||
public async Task TimeoutAfterWithResult()
|
|
||||||
{
|
|
||||||
await MqttTaskTimeout.WaitAsync(
|
|
||||||
ct => Task.Delay(TimeSpan.FromMilliseconds(500), ct).ContinueWith(t => 5, ct),
|
|
||||||
TimeSpan.FromMilliseconds(100), CancellationToken.None);
|
|
||||||
}
|
|
||||||
|
|
||||||
[TestMethod]
|
|
||||||
public async Task TimeoutAfterWithInnerException()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await MqttTaskTimeout.WaitAsync(ct => Task.Run(() =>
|
|
||||||
{
|
|
||||||
var iis = new int[0];
|
|
||||||
iis[1] = 0;
|
|
||||||
}, ct), TimeSpan.FromSeconds(1), CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Fail();
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Assert.IsTrue(e is IndexOutOfRangeException);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[TestMethod]
|
|
||||||
public async Task TimeoutAfterWithInnerExceptionWithResult()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await MqttTaskTimeout.WaitAsync(ct => Task.Run(() =>
|
|
||||||
{
|
|
||||||
var iis = new int[0];
|
|
||||||
iis[1] = 0;
|
|
||||||
return iis[0];
|
|
||||||
}, ct), TimeSpan.FromSeconds(1), CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Fail();
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Assert.IsTrue(e is IndexOutOfRangeException);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[TestMethod]
|
|
||||||
public async Task TimeoutAfterMemoryUsage()
|
|
||||||
{
|
|
||||||
var initialMemory = GC.GetTotalMemory(true);
|
|
||||||
|
|
||||||
var tasks = Enumerable.Range(0, 100000)
|
|
||||||
.Select(i =>
|
|
||||||
{
|
|
||||||
return MqttTaskTimeout.WaitAsync(ct => Task.Delay(TimeSpan.FromMilliseconds(1), ct),
|
|
||||||
TimeSpan.FromMinutes(1), CancellationToken.None);
|
|
||||||
});
|
|
||||||
|
|
||||||
await Task.WhenAll(tasks);
|
|
||||||
AssertIsLess(initialMemory + 2_000_000, GC.GetTotalMemory(true));
|
|
||||||
}
|
|
||||||
|
|
||||||
static void AssertIsLess(long bound, long actual)
|
|
||||||
{
|
|
||||||
if (bound < actual)
|
|
||||||
{
|
|
||||||
Assert.Fail($"value must be less than {bound:N0} but is {actual:N0}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
using MQTTnet.Exceptions;
|
||||||
|
using MQTTnet.Extensions.TopicTemplate;
|
||||||
|
|
||||||
|
namespace MQTTnet.Tests.Extensions
|
||||||
|
{
|
||||||
|
[TestClass]
|
||||||
|
public sealed class MqttTopicTemplate_Tests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void BasicOps()
|
||||||
|
{
|
||||||
|
var template = new MqttTopicTemplate("A/B/{param}/D");
|
||||||
|
Assert.AreEqual("A/B/C/D", template.WithParameter("param", "C").Template);
|
||||||
|
Assert.AreEqual("A/B/+/D", template.WithoutParameter("param").Template);
|
||||||
|
Assert.AreEqual("A/B/+/D", template.TopicFilter);
|
||||||
|
Assert.AreEqual("A/B/+/D/#", template.TopicTreeRootFilter);
|
||||||
|
|
||||||
|
// corner cases
|
||||||
|
Assert.AreEqual("#", new MqttTopicTemplate("#").TopicFilter);
|
||||||
|
Assert.AreEqual("+", new MqttTopicTemplate("+").TopicFilter);
|
||||||
|
Assert.AreEqual("/", new MqttTopicTemplate("/").TopicFilter);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void BasicOpsWithHash()
|
||||||
|
{
|
||||||
|
var template = new MqttTopicTemplate("A/B/{param}/D/#");
|
||||||
|
Assert.AreEqual("A/B/C/D/#", template.WithParameter("param", "C").Template);
|
||||||
|
Assert.AreEqual("A/B/+/D/#", template.WithoutParameter("param").Template);
|
||||||
|
Assert.AreEqual("A/B/+/D/#", template.TopicFilter);
|
||||||
|
Assert.AreEqual("A/B/+/D/#", template.TopicTreeRootFilter);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[ExpectedException(typeof(ArgumentException))]
|
||||||
|
public void RejectsReservedChars1()
|
||||||
|
{
|
||||||
|
var template = new MqttTopicTemplate("A/B/{foo}/D");
|
||||||
|
template.WithParameter("foo", "a#");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[ExpectedException(typeof(MqttProtocolViolationException))]
|
||||||
|
public void RejectsEmptyTemplate()
|
||||||
|
{
|
||||||
|
var _ = new MqttTopicTemplate("");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[ExpectedException(typeof(ArgumentNullException))]
|
||||||
|
public void RejectsNullTemplate()
|
||||||
|
{
|
||||||
|
var _ = new MqttTopicTemplate(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[ExpectedException(typeof(ArgumentException))]
|
||||||
|
public void RejectsReservedChars2()
|
||||||
|
{
|
||||||
|
var template = new MqttTopicTemplate("A/B/{foo}/D");
|
||||||
|
template.WithParameter("foo", "e/f");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void IgnoresEmptyParameters()
|
||||||
|
{
|
||||||
|
var template = new MqttTopicTemplate("A/B/{}/D");
|
||||||
|
Assert.IsFalse(template.Parameters.Any());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AcceptsValidTopics()
|
||||||
|
{
|
||||||
|
_ = new MqttTopicTemplate("A");
|
||||||
|
_ = new MqttTopicTemplate("/");
|
||||||
|
_ = new MqttTopicTemplate("/A");
|
||||||
|
_ = new MqttTopicTemplate("A/#");
|
||||||
|
_ = new MqttTopicTemplate("$SYS/#");
|
||||||
|
_ = new MqttTopicTemplate("////");
|
||||||
|
_ = new MqttTopicTemplate("A/B/{foo}/D/");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DynamicRoutingSupport()
|
||||||
|
{
|
||||||
|
var v1template = new MqttTopicTemplate("A/v1/{id}/F");
|
||||||
|
var v2template = new MqttTopicTemplate("A/v2/foo/{id}/{bar}");
|
||||||
|
var incoming_v1_topic = "A/v1/32/F";
|
||||||
|
|
||||||
|
var compat_v2_topic = v2template
|
||||||
|
.WithParameterValuesFrom(
|
||||||
|
v1template.ParseParameterValues(incoming_v1_topic))
|
||||||
|
.WithParameter("bar", "unknown");
|
||||||
|
|
||||||
|
// id: 32 was relocated and bar: unknown added
|
||||||
|
Assert.AreEqual("A/v2/foo/32/unknown", compat_v2_topic.Template);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SubscriptionSupport()
|
||||||
|
{
|
||||||
|
var template = new MqttTopicTemplate("A/v1/{param}/F");
|
||||||
|
var filter = template.BuildFilter()
|
||||||
|
.WithAtLeastOnceQoS()
|
||||||
|
.WithNoLocal()
|
||||||
|
.Build();
|
||||||
|
Assert.AreEqual("A/v1/+/F", filter.Topic);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CanonicalPrefixFilter()
|
||||||
|
{
|
||||||
|
var template1 = new MqttTopicTemplate("A/v1/{param}/F");
|
||||||
|
var template2 = new MqttTopicTemplate("A/v1/E/F");
|
||||||
|
var template3 = new MqttTopicTemplate("A/v1/E/F/G/H");
|
||||||
|
var canonicalFilter = MqttTopicTemplate.FindCanonicalPrefix(new[] { template1, template2, template3 });
|
||||||
|
// possible improvement: Assert.AreEqual("A/v1/+/F", canonicalFilter.TopicFilter);
|
||||||
|
Assert.AreEqual("A/v1/+", canonicalFilter.TopicFilter);
|
||||||
|
Assert.AreEqual("A/v1/+/#", canonicalFilter.TopicTreeRootFilter);
|
||||||
|
|
||||||
|
var template2b = new MqttTopicTemplate("A/v1/E/X");
|
||||||
|
canonicalFilter = MqttTopicTemplate.FindCanonicalPrefix(new[] { template1, template2, template3, template2b });
|
||||||
|
Assert.AreEqual("A/v1/+", canonicalFilter.Template);
|
||||||
|
Assert.AreEqual("A/v1/+", canonicalFilter.TopicFilter);
|
||||||
|
Assert.AreEqual("A/v1/+/#", canonicalFilter.TopicTreeRootFilter);
|
||||||
|
|
||||||
|
|
||||||
|
var template4 = new MqttTopicTemplate("A/v2/{prefix}");
|
||||||
|
var canonicalFilter2 = MqttTopicTemplate.FindCanonicalPrefix(new[] { template1, template2, template3, template4 });
|
||||||
|
Assert.AreEqual("A/+", canonicalFilter2.TopicFilter);
|
||||||
|
Assert.AreEqual("A/+/#", canonicalFilter2.TopicTreeRootFilter);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CanonicalPrefixFilterSimple1()
|
||||||
|
{
|
||||||
|
var template = MqttTopicTemplate.FindCanonicalPrefix(new[]
|
||||||
|
{
|
||||||
|
new MqttTopicTemplate("A"),
|
||||||
|
new MqttTopicTemplate("B")
|
||||||
|
});
|
||||||
|
Assert.AreEqual("#", template.TopicFilter);
|
||||||
|
Assert.AreEqual("#", template.Template);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CanonicalPrefixFilterSimple2()
|
||||||
|
{
|
||||||
|
var template = MqttTopicTemplate.FindCanonicalPrefix(new[]
|
||||||
|
{
|
||||||
|
new MqttTopicTemplate("A/v1/{param}/F/"),
|
||||||
|
new MqttTopicTemplate("A/v1/E/X")
|
||||||
|
});
|
||||||
|
Assert.AreEqual("A/v1/+", template.TopicFilter);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CanonicalPrefixFilterSimple3()
|
||||||
|
{
|
||||||
|
var template = MqttTopicTemplate.FindCanonicalPrefix(new[]
|
||||||
|
{
|
||||||
|
new MqttTopicTemplate("A/v1/{param}/F"),
|
||||||
|
new MqttTopicTemplate("A/v1/{param}/F/X")
|
||||||
|
});
|
||||||
|
Assert.AreEqual("A/v1/+/+", template.TopicFilter);
|
||||||
|
Assert.AreEqual("A/v1/{param}/+", template.Template);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CanonicalPrefixFilterSimple4()
|
||||||
|
{
|
||||||
|
var template = MqttTopicTemplate.FindCanonicalPrefix(new[]
|
||||||
|
{
|
||||||
|
new MqttTopicTemplate("A/v1/{param}/FFA"),
|
||||||
|
new MqttTopicTemplate("A/v1/{param}/FX")
|
||||||
|
});
|
||||||
|
Assert.AreEqual("A/v1/+/+", template.TopicFilter);
|
||||||
|
Assert.AreEqual("A/v1/{param}/+", template.Template);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CanonicalPrefixFilterSimple5()
|
||||||
|
{
|
||||||
|
var template = MqttTopicTemplate.FindCanonicalPrefix(new[]
|
||||||
|
{
|
||||||
|
new MqttTopicTemplate("A/v1/E/F/G/H"),
|
||||||
|
new MqttTopicTemplate("A/v2/{param}")
|
||||||
|
});
|
||||||
|
Assert.AreEqual("A/+", template.TopicFilter);
|
||||||
|
Assert.AreEqual("A/+/#", template.TopicTreeRootFilter);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CanonicalPrefixFilterSimple6()
|
||||||
|
{
|
||||||
|
var template = MqttTopicTemplate.FindCanonicalPrefix(new[]
|
||||||
|
{
|
||||||
|
new MqttTopicTemplate("A/{version}/E/F/G/H"),
|
||||||
|
new MqttTopicTemplate("A/{version}/{param}")
|
||||||
|
});
|
||||||
|
Assert.AreEqual("A/+/+", template.TopicFilter);
|
||||||
|
Assert.AreEqual("A/+/+/#", template.TopicTreeRootFilter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
@@ -45,6 +46,34 @@ namespace MQTTnet.Tests.Extensions
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Execute_Success_Parameters_Propagated_Correctly()
|
||||||
|
{
|
||||||
|
var paramValue = "123";
|
||||||
|
var parameters = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ TestParametersTopicGenerationStrategy.ExpectedParamName, "123" }
|
||||||
|
};
|
||||||
|
|
||||||
|
using (var testEnvironment = CreateTestEnvironment())
|
||||||
|
{
|
||||||
|
await testEnvironment.StartServer();
|
||||||
|
|
||||||
|
var responseSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder());
|
||||||
|
await responseSender.SubscribeAsync($"MQTTnet.RPC/+/ping/{paramValue}");
|
||||||
|
|
||||||
|
responseSender.ApplicationMessageReceivedAsync += e => responseSender.PublishStringAsync(e.ApplicationMessage.Topic + "/response", "pong");
|
||||||
|
|
||||||
|
using (var rpcClient = await testEnvironment.ConnectRpcClient(new MqttRpcClientOptionsBuilder()
|
||||||
|
.WithTopicGenerationStrategy(new TestParametersTopicGenerationStrategy()).Build()))
|
||||||
|
{
|
||||||
|
var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), "ping", "", MqttQualityOfServiceLevel.AtMostOnce, parameters);
|
||||||
|
|
||||||
|
Assert.AreEqual("pong", Encoding.UTF8.GetString(response));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public Task Execute_Success_With_QoS_0()
|
public Task Execute_Success_With_QoS_0()
|
||||||
{
|
{
|
||||||
@@ -135,7 +164,7 @@ namespace MQTTnet.Tests.Extensions
|
|||||||
|
|
||||||
using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
|
using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
|
||||||
{
|
{
|
||||||
var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(2), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
|
await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(2), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -222,5 +251,32 @@ namespace MQTTnet.Tests.Extensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class TestParametersTopicGenerationStrategy : IMqttRpcClientTopicGenerationStrategy
|
||||||
|
{
|
||||||
|
internal const string ExpectedParamName = "test_param_name";
|
||||||
|
|
||||||
|
public MqttRpcTopicPair CreateRpcTopics(TopicGenerationContext context)
|
||||||
|
{
|
||||||
|
if (context.Parameters == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Parameters dictionary expected to be not null");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!context.Parameters.TryGetValue(ExpectedParamName, out var paramValue))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"Parameter with name {ExpectedParamName} not present");
|
||||||
|
}
|
||||||
|
|
||||||
|
var requestTopic = $"MQTTnet.RPC/{Guid.NewGuid():N}/{context.MethodName}/{paramValue}";
|
||||||
|
var responseTopic = requestTopic + "/response";
|
||||||
|
|
||||||
|
return new MqttRpcTopicPair
|
||||||
|
{
|
||||||
|
RequestTopic = requestTopic,
|
||||||
|
ResponseTopic = responseTopic
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@ namespace MQTTnet.Tests.Extensions
|
|||||||
|
|
||||||
using (var client = factory.CreateMqttClient())
|
using (var client = factory.CreateMqttClient())
|
||||||
{
|
{
|
||||||
var options = new MqttClientOptionsBuilder().WithWebSocketServer("ws://a.b/mqtt").WithTimeout(TimeSpan.FromSeconds(2)).Build();
|
var options = new MqttClientOptionsBuilder().WithWebSocketServer(o => o.WithUri("ws://a.b/mqtt")).WithTimeout(TimeSpan.FromSeconds(2)).Build();
|
||||||
await client.ConnectAsync(options).ConfigureAwait(false);
|
await client.ConnectAsync(options).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ namespace MQTTnet.Tests.Formatter
|
|||||||
Assert.IsNull(deserialized.UserProperties); // Not supported in v3.1.1
|
Assert.IsNull(deserialized.UserProperties); // Not supported in v3.1.1
|
||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void Serialize_Full_MqttConnAckPacket_V310()
|
public void Serialize_Full_MqttConnAckPacket_V310()
|
||||||
{
|
{
|
||||||
var connAckPacket = new MqttConnAckPacket
|
var connAckPacket = new MqttConnAckPacket
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
using MQTTnet.Exceptions;
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
|
|
||||||
namespace MQTTnet.Tests.Formatter
|
namespace MQTTnet.Tests.Formatter
|
||||||
@@ -48,22 +49,31 @@ namespace MQTTnet.Tests.Formatter
|
|||||||
Assert.AreEqual(9876U, reader.ReadVariableByteInteger());
|
Assert.AreEqual(9876U, reader.ReadVariableByteInteger());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[ExpectedException(typeof(MqttProtocolViolationException))]
|
||||||
|
public void Throw_If_String_Too_Long()
|
||||||
|
{
|
||||||
|
var writer = new MqttBufferWriter(4096, 65535);
|
||||||
|
|
||||||
|
writer.WriteString(string.Empty.PadLeft(65536));
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void Write_And_Read_Multiple_Times()
|
public void Write_And_Read_Multiple_Times()
|
||||||
{
|
{
|
||||||
var writer = new MqttBufferWriter(4096, 65535);
|
var writer = new MqttBufferWriter(4096, 65535);
|
||||||
writer.WriteString("A relative short string.");
|
writer.WriteString("A relative short string.");
|
||||||
writer.WriteBinaryData(new byte[1234]);
|
writer.WriteBinary(new byte[1234]);
|
||||||
writer.WriteByte(0x01);
|
writer.WriteByte(0x01);
|
||||||
writer.WriteByte(0x02);
|
writer.WriteByte(0x02);
|
||||||
writer.WriteVariableByteInteger(5647382);
|
writer.WriteVariableByteInteger(5647382);
|
||||||
writer.WriteString("A relative short string.");
|
writer.WriteString("A relative short string.");
|
||||||
writer.WriteVariableByteInteger(8574489);
|
writer.WriteVariableByteInteger(8574489);
|
||||||
writer.WriteBinaryData(new byte[48]);
|
writer.WriteBinary(new byte[48]);
|
||||||
writer.WriteByte(2);
|
writer.WriteByte(2);
|
||||||
writer.WriteByte(0x02);
|
writer.WriteByte(0x02);
|
||||||
writer.WriteString("fjgffiogfhgfhoihgoireghreghreguhreguireoghreouighreouighreughreguiorehreuiohruiorehreuioghreug");
|
writer.WriteString("fjgffiogfhgfhoihgoireghreghreguhreguireoghreouighreouighreughreguiorehreuiohruiorehreuioghreug");
|
||||||
writer.WriteBinaryData(new byte[3]);
|
writer.WriteBinary(new byte[3]);
|
||||||
|
|
||||||
var readPayload = new ArraySegment<byte>(writer.GetBuffer(), 0, writer.Length).ToArray();
|
var readPayload = new ArraySegment<byte>(writer.GetBuffer(), 0, writer.Length).ToArray();
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFrameworks>net452;net461;net48;netcoreapp3.1;net6.0;net7.0</TargetFrameworks>
|
<TargetFrameworks>netcoreapp3.1;net7.0</TargetFrameworks>
|
||||||
|
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net48</TargetFrameworks>
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
<LangVersion>7.3</LangVersion>
|
<LangVersion>7.3</LangVersion>
|
||||||
<EnableNETAnalyzers>false</EnableNETAnalyzers>
|
<EnableNETAnalyzers>false</EnableNETAnalyzers>
|
||||||
@@ -20,6 +21,7 @@
|
|||||||
<ProjectReference Include="..\..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj" />
|
<ProjectReference Include="..\..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj" />
|
||||||
<ProjectReference Include="..\..\Source\MQTTnet.Extensions.Rpc\MQTTnet.Extensions.Rpc.csproj" />
|
<ProjectReference Include="..\..\Source\MQTTnet.Extensions.Rpc\MQTTnet.Extensions.Rpc.csproj" />
|
||||||
<ProjectReference Include="..\..\Source\MQTTnet\MQTTnet.csproj" />
|
<ProjectReference Include="..\..\Source\MQTTnet\MQTTnet.csproj" />
|
||||||
|
<ProjectReference Include="..\MQTTnet.Extensions.TopicTemplate\MQTTnet.Extensions.TopicTemplate.csproj" />
|
||||||
<ProjectReference Include="..\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj" />
|
<ProjectReference Include="..\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -273,7 +273,7 @@ namespace MQTTnet.Tests.MQTTv5
|
|||||||
Assert.AreEqual(applicationMessage.ResponseTopic, receivedMessage.ResponseTopic);
|
Assert.AreEqual(applicationMessage.ResponseTopic, receivedMessage.ResponseTopic);
|
||||||
Assert.AreEqual(applicationMessage.MessageExpiryInterval, receivedMessage.MessageExpiryInterval);
|
Assert.AreEqual(applicationMessage.MessageExpiryInterval, receivedMessage.MessageExpiryInterval);
|
||||||
CollectionAssert.AreEqual(applicationMessage.CorrelationData, receivedMessage.CorrelationData);
|
CollectionAssert.AreEqual(applicationMessage.CorrelationData, receivedMessage.CorrelationData);
|
||||||
CollectionAssert.AreEqual(applicationMessage.Payload, receivedMessage.Payload);
|
CollectionAssert.AreEqual(applicationMessage.PayloadSegment.ToArray(), receivedMessage.PayloadSegment.ToArray());
|
||||||
CollectionAssert.AreEqual(applicationMessage.UserProperties, receivedMessage.UserProperties);
|
CollectionAssert.AreEqual(applicationMessage.UserProperties, receivedMessage.UserProperties);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Internal;
|
using MQTTnet.Internal;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
|
using MQTTnet.Server;
|
||||||
|
|
||||||
namespace MQTTnet.Tests.MQTTv5
|
namespace MQTTnet.Tests.MQTTv5
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ namespace MQTTnet.Tests.Mockups
|
|||||||
{
|
{
|
||||||
readonly List<string> _clientErrors = new List<string>();
|
readonly List<string> _clientErrors = new List<string>();
|
||||||
readonly List<IMqttClient> _clients = new List<IMqttClient>();
|
readonly List<IMqttClient> _clients = new List<IMqttClient>();
|
||||||
|
|
||||||
readonly List<Exception> _exceptions = new List<Exception>();
|
readonly List<Exception> _exceptions = new List<Exception>();
|
||||||
readonly List<ILowLevelMqttClient> _lowLevelClients = new List<ILowLevelMqttClient>();
|
readonly List<ILowLevelMqttClient> _lowLevelClients = new List<ILowLevelMqttClient>();
|
||||||
readonly MqttProtocolVersion _protocolVersion;
|
readonly MqttProtocolVersion _protocolVersion;
|
||||||
@@ -40,6 +39,8 @@ namespace MQTTnet.Tests.Mockups
|
|||||||
_protocolVersion = protocolVersion;
|
_protocolVersion = protocolVersion;
|
||||||
TestContext = testContext;
|
TestContext = testContext;
|
||||||
|
|
||||||
|
TaskScheduler.UnobservedTaskException += TrackUnobservedTaskException;
|
||||||
|
|
||||||
ServerLogger.LogMessagePublished += (s, e) =>
|
ServerLogger.LogMessagePublished += (s, e) =>
|
||||||
{
|
{
|
||||||
if (Debugger.IsAttached)
|
if (Debugger.IsAttached)
|
||||||
@@ -65,9 +66,12 @@ namespace MQTTnet.Tests.Mockups
|
|||||||
|
|
||||||
if (e.LogMessage.Level == MqttNetLogLevel.Error)
|
if (e.LogMessage.Level == MqttNetLogLevel.Error)
|
||||||
{
|
{
|
||||||
lock (_clientErrors)
|
if (!IgnoreClientLogErrors)
|
||||||
{
|
{
|
||||||
_clientErrors.Add(e.LogMessage.ToString());
|
lock (_clientErrors)
|
||||||
|
{
|
||||||
|
_clientErrors.Add(e.LogMessage.ToString());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -212,30 +216,31 @@ namespace MQTTnet.Tests.Mockups
|
|||||||
|
|
||||||
public IMqttClient CreateClient()
|
public IMqttClient CreateClient()
|
||||||
{
|
{
|
||||||
|
var logger = EnableLogger ? (IMqttNetLogger)ClientLogger : MqttNetNullLogger.Instance;
|
||||||
|
|
||||||
|
var client = Factory.CreateMqttClient(logger);
|
||||||
|
|
||||||
|
client.ConnectingAsync += e =>
|
||||||
|
{
|
||||||
|
if (TestContext != null)
|
||||||
|
{
|
||||||
|
var clientOptions = e.ClientOptions;
|
||||||
|
var existingClientId = clientOptions.ClientId;
|
||||||
|
if (existingClientId != null && !existingClientId.StartsWith(TestContext.TestName))
|
||||||
|
{
|
||||||
|
clientOptions.ClientId = TestContext.TestName + "_" + existingClientId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
};
|
||||||
|
|
||||||
lock (_clients)
|
lock (_clients)
|
||||||
{
|
{
|
||||||
var logger = EnableLogger ? (IMqttNetLogger)ClientLogger : new MqttNetNullLogger();
|
|
||||||
|
|
||||||
var client = Factory.CreateMqttClient(logger);
|
|
||||||
_clients.Add(client);
|
_clients.Add(client);
|
||||||
|
|
||||||
client.ConnectingAsync += e =>
|
|
||||||
{
|
|
||||||
if (TestContext != null)
|
|
||||||
{
|
|
||||||
var clientOptions = e.ClientOptions;
|
|
||||||
var existingClientId = clientOptions.ClientId;
|
|
||||||
if (existingClientId != null && !existingClientId.StartsWith(TestContext.TestName))
|
|
||||||
{
|
|
||||||
clientOptions.ClientId = TestContext.TestName + "_" + existingClientId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return CompletedTask.Instance;
|
|
||||||
};
|
|
||||||
|
|
||||||
return client;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MqttClientOptions CreateDefaultClientOptions()
|
public MqttClientOptions CreateDefaultClientOptions()
|
||||||
@@ -245,18 +250,22 @@ namespace MQTTnet.Tests.Mockups
|
|||||||
|
|
||||||
public MqttClientOptionsBuilder CreateDefaultClientOptionsBuilder()
|
public MqttClientOptionsBuilder CreateDefaultClientOptionsBuilder()
|
||||||
{
|
{
|
||||||
return Factory.CreateClientOptionsBuilder().WithProtocolVersion(_protocolVersion).WithTcpServer("127.0.0.1", ServerPort);
|
return Factory.CreateClientOptionsBuilder()
|
||||||
|
.WithProtocolVersion(_protocolVersion)
|
||||||
|
.WithTcpServer("127.0.0.1", ServerPort)
|
||||||
|
.WithClientId(TestContext.TestName + "_" + Guid.NewGuid());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ILowLevelMqttClient CreateLowLevelClient()
|
public ILowLevelMqttClient CreateLowLevelClient()
|
||||||
{
|
{
|
||||||
lock (_clients)
|
var client = Factory.CreateLowLevelMqttClient(ClientLogger);
|
||||||
{
|
|
||||||
var client = Factory.CreateLowLevelMqttClient(ClientLogger);
|
|
||||||
_lowLevelClients.Add(client);
|
|
||||||
|
|
||||||
return client;
|
lock (_lowLevelClients)
|
||||||
|
{
|
||||||
|
_lowLevelClients.Add(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MqttServer CreateServer(MqttServerOptions options)
|
public MqttServer CreateServer(MqttServerOptions options)
|
||||||
@@ -290,45 +299,68 @@ namespace MQTTnet.Tests.Mockups
|
|||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
foreach (var mqttClient in _clients)
|
try
|
||||||
{
|
{
|
||||||
|
lock (_clients)
|
||||||
|
{
|
||||||
|
foreach (var mqttClient in _clients)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//mqttClient.DisconnectAsync().GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// This can happen when the test already disconnected the client.
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
mqttClient?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_clients.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_lowLevelClients)
|
||||||
|
{
|
||||||
|
foreach (var lowLevelMqttClient in _lowLevelClients)
|
||||||
|
{
|
||||||
|
lowLevelMqttClient.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
_lowLevelClients.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
//mqttClient.DisconnectAsync().GetAwaiter().GetResult();
|
Server?.StopAsync().GetAwaiter().GetResult();
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
// This can happen when the test already disconnected the client.
|
// This can happen when the test already stopped the server.
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
mqttClient?.Dispose();
|
Server?.Dispose();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var lowLevelMqttClient in _lowLevelClients)
|
Server = null;
|
||||||
{
|
|
||||||
lowLevelMqttClient.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
ThrowIfLogErrors();
|
||||||
{
|
|
||||||
Server?.StopAsync().GetAwaiter().GetResult();
|
GC.Collect();
|
||||||
}
|
GC.WaitForFullGCComplete();
|
||||||
catch
|
GC.WaitForPendingFinalizers();
|
||||||
{
|
|
||||||
// This can happen when the test already stopped the server.
|
if (_exceptions.Any())
|
||||||
|
{
|
||||||
|
throw new Exception($"{_exceptions.Count} exceptions tracked.\r\n" + string.Join(Environment.NewLine, _exceptions));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
Server?.Dispose();
|
TaskScheduler.UnobservedTaskException -= TrackUnobservedTaskException;
|
||||||
}
|
|
||||||
|
|
||||||
ThrowIfLogErrors();
|
|
||||||
|
|
||||||
if (_exceptions.Any())
|
|
||||||
{
|
|
||||||
throw new Exception($"{_exceptions.Count} exceptions tracked.\r\n" + string.Join(Environment.NewLine, _exceptions));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -345,7 +377,7 @@ namespace MQTTnet.Tests.Mockups
|
|||||||
|
|
||||||
var options = optionsBuilder.Build();
|
var options = optionsBuilder.Build();
|
||||||
var server = CreateServer(options);
|
var server = CreateServer(options);
|
||||||
await server.StartAsync();
|
await server.StartAsync().ConfigureAwait(false);
|
||||||
|
|
||||||
// The OS has chosen the port to we have to properly expose it to the tests.
|
// The OS has chosen the port to we have to properly expose it to the tests.
|
||||||
ServerPort = options.DefaultEndpointOptions.Port;
|
ServerPort = options.DefaultEndpointOptions.Port;
|
||||||
@@ -373,33 +405,49 @@ namespace MQTTnet.Tests.Mockups
|
|||||||
|
|
||||||
public void ThrowIfLogErrors()
|
public void ThrowIfLogErrors()
|
||||||
{
|
{
|
||||||
lock (_serverErrors)
|
if (!IgnoreServerLogErrors)
|
||||||
{
|
{
|
||||||
if (!IgnoreServerLogErrors && _serverErrors.Count > 0)
|
lock (_serverErrors)
|
||||||
{
|
{
|
||||||
var message = $"Server had {_serverErrors.Count} errors (${string.Join(Environment.NewLine, _serverErrors)}).";
|
if (_serverErrors.Count > 0)
|
||||||
Console.WriteLine(message);
|
{
|
||||||
throw new Exception(message);
|
var message = $"Server had {_serverErrors.Count} errors (${string.Join(Environment.NewLine, _serverErrors)}).";
|
||||||
|
Console.WriteLine(message);
|
||||||
|
throw new Exception(message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
lock (_clientErrors)
|
if (!IgnoreClientLogErrors)
|
||||||
{
|
{
|
||||||
if (!IgnoreClientLogErrors && _clientErrors.Count > 0)
|
lock (_clientErrors)
|
||||||
{
|
{
|
||||||
var message = $"Client(s) had {_clientErrors.Count} errors (${string.Join(Environment.NewLine, _clientErrors)})";
|
if (_clientErrors.Count > 0)
|
||||||
Console.WriteLine(message);
|
{
|
||||||
throw new Exception(message);
|
var message = $"Client(s) had {_clientErrors.Count} errors (${string.Join(Environment.NewLine, _clientErrors)})";
|
||||||
|
Console.WriteLine(message);
|
||||||
|
throw new Exception(message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void TrackException(Exception exception)
|
public void TrackException(Exception exception)
|
||||||
{
|
{
|
||||||
|
if (exception == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
lock (_exceptions)
|
lock (_exceptions)
|
||||||
{
|
{
|
||||||
_exceptions.Add(exception);
|
_exceptions.Add(exception);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TrackUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
|
||||||
|
{
|
||||||
|
TrackException(e.Exception);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
@@ -11,7 +12,7 @@ using MQTTnet.Protocol;
|
|||||||
namespace MQTTnet.Tests
|
namespace MQTTnet.Tests
|
||||||
{
|
{
|
||||||
[TestClass]
|
[TestClass]
|
||||||
public class MqttApplicationMessageBuilder_Tests
|
public sealed class MqttApplicationMessageBuilder_Tests
|
||||||
{
|
{
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void CreateApplicationMessage_TopicOnly()
|
public void CreateApplicationMessage_TopicOnly()
|
||||||
@@ -29,7 +30,7 @@ namespace MQTTnet.Tests
|
|||||||
Assert.AreEqual("xyz", message.Topic);
|
Assert.AreEqual("xyz", message.Topic);
|
||||||
Assert.IsFalse(message.Retain);
|
Assert.IsFalse(message.Retain);
|
||||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, message.QualityOfServiceLevel);
|
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, message.QualityOfServiceLevel);
|
||||||
Assert.AreEqual(Encoding.UTF8.GetString(message.Payload), "00:06:00");
|
Assert.AreEqual(Encoding.UTF8.GetString(message.PayloadSegment.ToArray()), "00:06:00");
|
||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
@@ -41,7 +42,7 @@ namespace MQTTnet.Tests
|
|||||||
Assert.AreEqual("123", message.Topic);
|
Assert.AreEqual("123", message.Topic);
|
||||||
Assert.IsFalse(message.Retain);
|
Assert.IsFalse(message.Retain);
|
||||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, message.QualityOfServiceLevel);
|
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, message.QualityOfServiceLevel);
|
||||||
Assert.AreEqual(Encoding.UTF8.GetString(message.Payload), "Hello");
|
Assert.AreEqual(Encoding.UTF8.GetString(message.PayloadSegment.ToArray()), "Hello");
|
||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
#pragma warning disable CS0618 // Type or member is obsolete
|
||||||
|
|
||||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -8,7 +10,7 @@ using System.Threading.Tasks;
|
|||||||
namespace MQTTnet.Tests
|
namespace MQTTnet.Tests
|
||||||
{
|
{
|
||||||
[TestClass]
|
[TestClass]
|
||||||
public class MqttApplicationMessageTest
|
public sealed class MqttApplicationMessageTest
|
||||||
{
|
{
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void PayloadSegment()
|
public void PayloadSegment()
|
||||||
@@ -17,32 +19,27 @@ namespace MQTTnet.Tests
|
|||||||
Assert.AreEqual(0, message.Payload.Length);
|
Assert.AreEqual(0, message.Payload.Length);
|
||||||
Assert.AreEqual(0, message.PayloadSegment.Count);
|
Assert.AreEqual(0, message.PayloadSegment.Count);
|
||||||
|
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.Payload));
|
Assert.IsTrue(ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
|
||||||
|
|
||||||
message.Payload = new byte[] { 1, 2 };
|
message.Payload = new byte[] { 1, 2 };
|
||||||
Assert.AreEqual(2, message.Payload.Length);
|
Assert.AreEqual(2, message.Payload.Length);
|
||||||
Assert.AreEqual(2, message.PayloadSegment.Count);
|
Assert.AreEqual(2, message.PayloadSegment.Count);
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.Payload));
|
Assert.IsTrue(ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
|
||||||
|
|
||||||
message.Payload = new byte[] { 1, 2, 3 };
|
message.Payload = new byte[] { 1, 2, 3 };
|
||||||
Assert.AreEqual(3, message.Payload.Length);
|
Assert.AreEqual(3, message.Payload.Length);
|
||||||
Assert.AreEqual(3, message.PayloadSegment.Count);
|
Assert.AreEqual(3, message.PayloadSegment.Count);
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.Payload));
|
Assert.IsTrue(ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
|
||||||
|
|
||||||
message.PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3 });
|
message.PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3 });
|
||||||
Assert.AreEqual(3, message.Payload.Length);
|
Assert.AreEqual(3, message.Payload.Length);
|
||||||
Assert.AreEqual(3, message.PayloadSegment.Count);
|
Assert.AreEqual(3, message.PayloadSegment.Count);
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.Payload));
|
Assert.IsTrue(ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
|
||||||
|
|
||||||
message.PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3 }, 1, 1);
|
message.PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3 }, 1, 1);
|
||||||
Assert.AreEqual(1, message.Payload.Length);
|
Assert.AreEqual(1, message.Payload.Length);
|
||||||
Assert.AreEqual(1, message.PayloadSegment.Count);
|
Assert.AreEqual(1, message.PayloadSegment.Count);
|
||||||
Assert.IsTrue(object.ReferenceEquals(message.Payload, message.Payload));
|
Assert.IsFalse(ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
||||||
Assert.IsFalse(object.ReferenceEquals(message.Payload, message.PayloadSegment.Array));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,10 +24,10 @@ namespace MQTTnet.Tests
|
|||||||
writer.WriteString("1234567890");
|
writer.WriteString("1234567890");
|
||||||
Assert.AreEqual(10 + 2, writer.Length);
|
Assert.AreEqual(10 + 2, writer.Length);
|
||||||
|
|
||||||
writer.WriteBinaryData(new byte[300]);
|
writer.WriteBinary(new byte[300]);
|
||||||
Assert.AreEqual(300 + 2 + 12, writer.Length);
|
Assert.AreEqual(300 + 2 + 12, writer.Length);
|
||||||
|
|
||||||
writer.WriteBinaryData(new byte[5000]);
|
writer.WriteBinary(new byte[5000]);
|
||||||
Assert.AreEqual(5000 + 2 + 300 + 2 + 12, writer.Length);
|
Assert.AreEqual(5000 + 2 + 300 + 2 + 12, writer.Length);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ namespace MQTTnet.Tests
|
|||||||
public async Task Dispose_Channel_While_Used()
|
public async Task Dispose_Channel_While_Used()
|
||||||
{
|
{
|
||||||
var ct = new CancellationTokenSource();
|
var ct = new CancellationTokenSource();
|
||||||
var serverSocket = new CrossPlatformSocket(AddressFamily.InterNetwork);
|
var serverSocket = new CrossPlatformSocket(AddressFamily.InterNetwork, ProtocolType.Tcp);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -38,7 +38,7 @@ namespace MQTTnet.Tests
|
|||||||
}
|
}
|
||||||
}, ct.Token);
|
}, ct.Token);
|
||||||
|
|
||||||
var clientSocket = new CrossPlatformSocket(AddressFamily.InterNetwork);
|
var clientSocket = new CrossPlatformSocket(AddressFamily.InterNetwork, ProtocolType.Tcp);
|
||||||
await clientSocket.ConnectAsync("localhost", 50001, CancellationToken.None);
|
await clientSocket.ConnectAsync("localhost", 50001, CancellationToken.None);
|
||||||
|
|
||||||
var tcpChannel = new MqttTcpChannel(clientSocket.GetStream(), "test", null);
|
var tcpChannel = new MqttTcpChannel(clientSocket.GetStream(), "test", null);
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
{
|
{
|
||||||
await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(1)));
|
await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(1)));
|
||||||
|
|
||||||
var client = new CrossPlatformSocket(AddressFamily.InterNetwork);
|
var client = new CrossPlatformSocket(AddressFamily.InterNetwork, ProtocolType.Tcp);
|
||||||
await client.ConnectAsync("localhost", testEnvironment.ServerPort, CancellationToken.None);
|
await client.ConnectAsync("localhost", testEnvironment.ServerPort, CancellationToken.None);
|
||||||
|
|
||||||
// Don't send anything. The server should close the connection.
|
// Don't send anything. The server should close the connection.
|
||||||
@@ -54,7 +54,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
|
|
||||||
// Send an invalid packet and ensure that the server will close the connection and stay in a waiting state
|
// Send an invalid packet and ensure that the server will close the connection and stay in a waiting state
|
||||||
// forever. This is security related.
|
// forever. This is security related.
|
||||||
var client = new CrossPlatformSocket(AddressFamily.InterNetwork);
|
var client = new CrossPlatformSocket(AddressFamily.InterNetwork, ProtocolType.Tcp);
|
||||||
await client.ConnectAsync("localhost", testEnvironment.ServerPort, CancellationToken.None);
|
await client.ConnectAsync("localhost", testEnvironment.ServerPort, CancellationToken.None);
|
||||||
|
|
||||||
var buffer = Encoding.UTF8.GetBytes("Garbage");
|
var buffer = Encoding.UTF8.GetBytes("Garbage");
|
||||||
|
|||||||
@@ -303,7 +303,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
var server = await testEnvironment.StartServer();
|
var server = await testEnvironment.StartServer();
|
||||||
server.InterceptingPublishAsync += e =>
|
server.InterceptingPublishAsync += e =>
|
||||||
{
|
{
|
||||||
e.ApplicationMessage.Payload = Encoding.ASCII.GetBytes("extended");
|
e.ApplicationMessage.PayloadSegment = new ArraySegment<byte>(Encoding.ASCII.GetBytes("extended"));
|
||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -314,7 +314,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
var isIntercepted = false;
|
var isIntercepted = false;
|
||||||
c2.ApplicationMessageReceivedAsync += e =>
|
c2.ApplicationMessageReceivedAsync += e =>
|
||||||
{
|
{
|
||||||
isIntercepted = string.Compare("extended", Encoding.UTF8.GetString(e.ApplicationMessage.Payload), StringComparison.Ordinal) == 0;
|
isIntercepted = string.Compare("extended", Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment.ToArray()), StringComparison.Ordinal) == 0;
|
||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -425,7 +425,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
new MqttApplicationMessage
|
new MqttApplicationMessage
|
||||||
{
|
{
|
||||||
Topic = "/test/1",
|
Topic = "/test/1",
|
||||||
Payload = Encoding.UTF8.GetBytes("true"),
|
PayloadSegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes("true")),
|
||||||
QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce
|
QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce
|
||||||
})
|
})
|
||||||
{
|
{
|
||||||
@@ -598,8 +598,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
// c
|
// c
|
||||||
var c1 = await testEnvironment.ConnectClient(clientOptionsBuilder);
|
var c1 = await testEnvironment.ConnectClient(clientOptionsBuilder);
|
||||||
|
|
||||||
await Task.Delay(500);
|
await LongTestDelay();
|
||||||
|
|
||||||
var flow = string.Join(string.Empty, events);
|
var flow = string.Join(string.Empty, events);
|
||||||
Assert.AreEqual("c", flow);
|
Assert.AreEqual("c", flow);
|
||||||
|
|
||||||
@@ -607,10 +606,8 @@ namespace MQTTnet.Tests.Server
|
|||||||
// Connect client with same client ID. Should disconnect existing client.
|
// Connect client with same client ID. Should disconnect existing client.
|
||||||
var c2 = await testEnvironment.ConnectClient(clientOptionsBuilder);
|
var c2 = await testEnvironment.ConnectClient(clientOptionsBuilder);
|
||||||
|
|
||||||
await Task.Delay(500);
|
await LongTestDelay();
|
||||||
|
|
||||||
flow = string.Join(string.Empty, events);
|
flow = string.Join(string.Empty, events);
|
||||||
|
|
||||||
Assert.AreEqual("cdc", flow);
|
Assert.AreEqual("cdc", flow);
|
||||||
|
|
||||||
c2.ApplicationMessageReceivedAsync += e =>
|
c2.ApplicationMessageReceivedAsync += e =>
|
||||||
@@ -628,8 +625,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
// r
|
// r
|
||||||
await c2.PublishStringAsync("topic");
|
await c2.PublishStringAsync("topic");
|
||||||
|
|
||||||
await Task.Delay(500);
|
await LongTestDelay();
|
||||||
|
|
||||||
flow = string.Join(string.Empty, events);
|
flow = string.Join(string.Empty, events);
|
||||||
Assert.AreEqual("cdcr", flow);
|
Assert.AreEqual("cdcr", flow);
|
||||||
|
|
||||||
@@ -639,16 +635,17 @@ namespace MQTTnet.Tests.Server
|
|||||||
await c1.TryDisconnectAsync();
|
await c1.TryDisconnectAsync();
|
||||||
Assert.AreEqual(false, c1.IsConnected);
|
Assert.AreEqual(false, c1.IsConnected);
|
||||||
|
|
||||||
await Task.Delay(500);
|
await LongTestDelay();
|
||||||
|
|
||||||
// d
|
// d
|
||||||
Assert.AreEqual(true, c2.IsConnected);
|
Assert.AreEqual(true, c2.IsConnected);
|
||||||
await c2.DisconnectAsync();
|
await c2.DisconnectAsync();
|
||||||
|
|
||||||
await Task.Delay(500);
|
await LongTestDelay();
|
||||||
|
|
||||||
await server.StopAsync();
|
await server.StopAsync();
|
||||||
|
|
||||||
|
await LongTestDelay();
|
||||||
flow = string.Join(string.Empty, events);
|
flow = string.Join(string.Empty, events);
|
||||||
Assert.AreEqual("cdcrd", flow);
|
Assert.AreEqual("cdcrd", flow);
|
||||||
}
|
}
|
||||||
@@ -783,7 +780,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
var client1 = await testEnvironment.ConnectClient();
|
var client1 = await testEnvironment.ConnectClient();
|
||||||
client1.ApplicationMessageReceivedAsync += e =>
|
client1.ApplicationMessageReceivedAsync += e =>
|
||||||
{
|
{
|
||||||
receivedBody = e.ApplicationMessage.Payload;
|
receivedBody = e.ApplicationMessage.PayloadSegment.ToArray();
|
||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -852,11 +849,11 @@ namespace MQTTnet.Tests.Server
|
|||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
};
|
};
|
||||||
|
|
||||||
await Task.Delay(100);
|
// Stopping the server should disconnect the connection with the client
|
||||||
|
// which, it turn, will fire the disconnected event at the client.
|
||||||
await server.StopAsync();
|
await server.StopAsync();
|
||||||
|
|
||||||
await Task.Delay(100);
|
await LongTestDelay();
|
||||||
|
|
||||||
Assert.AreEqual(1, disconnectCalled);
|
Assert.AreEqual(1, disconnectCalled);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,426 @@
|
|||||||
|
#if !(NET452 || NET461 || NET48)
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Security.Authentication;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
using MQTTnet.Certificates;
|
||||||
|
using MQTTnet.Client;
|
||||||
|
using MQTTnet.Formatter;
|
||||||
|
using MQTTnet.Protocol;
|
||||||
|
using MQTTnet.Server;
|
||||||
|
|
||||||
|
namespace MQTTnet.Tests.Server
|
||||||
|
{
|
||||||
|
// missing certificate builder api means tests won't work for older frameworks
|
||||||
|
|
||||||
|
[TestClass]
|
||||||
|
public sealed class HotSwapCerts_Tests
|
||||||
|
{
|
||||||
|
static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ClientCertChangeWithoutServerUpdateFailsReconnect()
|
||||||
|
{
|
||||||
|
using (var server = new ServerTestHarness())
|
||||||
|
using (var client01 = new ClientTestHarness())
|
||||||
|
{
|
||||||
|
server.InstallNewClientCert(client01.GetCurrentClientCert());
|
||||||
|
client01.InstallNewServerCert(server.GetCurrentServerCert());
|
||||||
|
|
||||||
|
await server.StartServer();
|
||||||
|
|
||||||
|
await client01.Connect();
|
||||||
|
|
||||||
|
client01.WaitForConnectOrFail(DefaultTimeout);
|
||||||
|
|
||||||
|
client01.HotSwapClientCert();
|
||||||
|
server.ForceDisconnectAsync(client01).Wait(DefaultTimeout);
|
||||||
|
client01.WaitForDisconnectOrFail(DefaultTimeout);
|
||||||
|
|
||||||
|
client01.WaitForConnectToFail(DefaultTimeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ClientCertChangeWithServerUpdateAcceptsReconnect()
|
||||||
|
{
|
||||||
|
using (var server = new ServerTestHarness())
|
||||||
|
using (var client01 = new ClientTestHarness())
|
||||||
|
{
|
||||||
|
server.InstallNewClientCert(client01.GetCurrentClientCert());
|
||||||
|
client01.InstallNewServerCert(server.GetCurrentServerCert());
|
||||||
|
|
||||||
|
await server.StartServer();
|
||||||
|
|
||||||
|
await client01.Connect();
|
||||||
|
|
||||||
|
client01.WaitForConnectOrFail(DefaultTimeout);
|
||||||
|
|
||||||
|
client01.HotSwapClientCert();
|
||||||
|
server.ForceDisconnectAsync(client01).Wait(DefaultTimeout);
|
||||||
|
client01.WaitForDisconnectOrFail(DefaultTimeout);
|
||||||
|
|
||||||
|
server.InstallNewClientCert(client01.GetCurrentClientCert());
|
||||||
|
|
||||||
|
client01.WaitForConnectOrFail(DefaultTimeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ServerCertChangeWithClientCertUpdateAllowsReconnect()
|
||||||
|
{
|
||||||
|
using (var server = new ServerTestHarness())
|
||||||
|
using (var client01 = new ClientTestHarness())
|
||||||
|
{
|
||||||
|
server.InstallNewClientCert(client01.GetCurrentClientCert());
|
||||||
|
client01.InstallNewServerCert(server.GetCurrentServerCert());
|
||||||
|
|
||||||
|
await server.StartServer();
|
||||||
|
await client01.Connect();
|
||||||
|
|
||||||
|
client01.WaitForConnectOrFail(DefaultTimeout);
|
||||||
|
server.HotSwapServerCert();
|
||||||
|
|
||||||
|
server.ForceDisconnectAsync(client01).Wait(DefaultTimeout);
|
||||||
|
client01.WaitForDisconnectOrFail(DefaultTimeout);
|
||||||
|
client01.InstallNewServerCert(server.GetCurrentServerCert());
|
||||||
|
|
||||||
|
client01.WaitForConnectOrFail(DefaultTimeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ServerCertChangeWithoutClientCertUpdateFailsReconnect()
|
||||||
|
{
|
||||||
|
using (var server = new ServerTestHarness())
|
||||||
|
using (var client01 = new ClientTestHarness())
|
||||||
|
{
|
||||||
|
server.InstallNewClientCert(client01.GetCurrentClientCert());
|
||||||
|
client01.InstallNewServerCert(server.GetCurrentServerCert());
|
||||||
|
|
||||||
|
await server.StartServer();
|
||||||
|
await client01.Connect();
|
||||||
|
|
||||||
|
client01.WaitForConnectOrFail(DefaultTimeout);
|
||||||
|
server.HotSwapServerCert();
|
||||||
|
|
||||||
|
server.ForceDisconnectAsync(client01).Wait(DefaultTimeout);
|
||||||
|
client01.WaitForDisconnectOrFail(DefaultTimeout);
|
||||||
|
|
||||||
|
client01.WaitForConnectToFail(DefaultTimeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static X509Certificate2 CreateSelfSignedCertificate(string oid)
|
||||||
|
{
|
||||||
|
var sanBuilder = new SubjectAlternativeNameBuilder();
|
||||||
|
sanBuilder.AddIpAddress(IPAddress.Loopback);
|
||||||
|
sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
|
||||||
|
sanBuilder.AddDnsName("localhost");
|
||||||
|
|
||||||
|
using (var rsa = RSA.Create())
|
||||||
|
{
|
||||||
|
var certRequest = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
|
||||||
|
|
||||||
|
certRequest.CertificateExtensions.Add(
|
||||||
|
new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));
|
||||||
|
|
||||||
|
certRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid(oid) }, false));
|
||||||
|
|
||||||
|
certRequest.CertificateExtensions.Add(sanBuilder.Build());
|
||||||
|
|
||||||
|
using (var certificate = certRequest.CreateSelfSigned(DateTimeOffset.Now.AddMinutes(-10), DateTimeOffset.Now.AddMinutes(10)))
|
||||||
|
{
|
||||||
|
var pfxCertificate = new X509Certificate2(
|
||||||
|
certificate.Export(X509ContentType.Pfx),
|
||||||
|
(string)null,
|
||||||
|
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
|
||||||
|
|
||||||
|
return pfxCertificate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed class ClientTestHarness : IDisposable
|
||||||
|
{
|
||||||
|
readonly HotSwappableClientCertProvider _hotSwapClient = new HotSwappableClientCertProvider();
|
||||||
|
|
||||||
|
IMqttClient _client;
|
||||||
|
|
||||||
|
public string ClientId => _client.Options.ClientId;
|
||||||
|
|
||||||
|
public Task Connect()
|
||||||
|
{
|
||||||
|
return Run_Client_Connection();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_client.Dispose();
|
||||||
|
_hotSwapClient.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
public X509Certificate2 GetCurrentClientCert()
|
||||||
|
{
|
||||||
|
var result = _hotSwapClient.GetCertificates()[0];
|
||||||
|
return new X509Certificate2(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void HotSwapClientCert()
|
||||||
|
{
|
||||||
|
_hotSwapClient.HotSwapCert();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void InstallNewServerCert(X509Certificate2 serverCert)
|
||||||
|
{
|
||||||
|
_hotSwapClient.InstallNewServerCert(serverCert);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void WaitForConnectOrFail(TimeSpan timeout)
|
||||||
|
{
|
||||||
|
Thread.Sleep(100);
|
||||||
|
|
||||||
|
if (!_client.IsConnected)
|
||||||
|
{
|
||||||
|
_client.ReconnectAsync().Wait(timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
WaitForConnect(timeout);
|
||||||
|
|
||||||
|
Assert.IsNotNull(_client, "Client was never initialized");
|
||||||
|
Assert.IsTrue(_client.IsConnected, $"Client connection failed after {timeout}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void WaitForConnectToFail(TimeSpan timeout)
|
||||||
|
{
|
||||||
|
Assert.IsFalse(_client.IsConnected, "Client should be disconnected before waiting for connect.");
|
||||||
|
|
||||||
|
WaitForConnect(timeout);
|
||||||
|
|
||||||
|
Assert.IsNotNull(_client, "Client was never initialized");
|
||||||
|
Assert.IsFalse(_client.IsConnected, "Client connection success but test wanted fail");
|
||||||
|
}
|
||||||
|
|
||||||
|
void WaitForDisconnect(TimeSpan timeout)
|
||||||
|
{
|
||||||
|
var timer = Stopwatch.StartNew();
|
||||||
|
while ((_client == null || _client.IsConnected) && timer.Elapsed < timeout)
|
||||||
|
{
|
||||||
|
Thread.Sleep(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void WaitForDisconnectOrFail(TimeSpan timeout)
|
||||||
|
{
|
||||||
|
WaitForDisconnect(timeout);
|
||||||
|
|
||||||
|
Assert.IsNotNull(_client, "Client was never initialized");
|
||||||
|
Assert.IsFalse(_client.IsConnected, $"Client connection should have disconnected after {timeout}");
|
||||||
|
}
|
||||||
|
|
||||||
|
async Task Run_Client_Connection()
|
||||||
|
{
|
||||||
|
var optionsBuilder = new MqttClientOptionsBuilder()
|
||||||
|
.WithTlsOptions(
|
||||||
|
o => o.WithClientCertificatesProvider(_hotSwapClient)
|
||||||
|
.WithCertificateValidationHandler(_hotSwapClient.OnCertificateValidation)
|
||||||
|
.WithSslProtocols(SslProtocols.Tls12))
|
||||||
|
.WithTcpServer("localhost")
|
||||||
|
.WithCleanSession()
|
||||||
|
.WithProtocolVersion(MqttProtocolVersion.V500);
|
||||||
|
|
||||||
|
var mqttClientOptions = optionsBuilder.Build();
|
||||||
|
|
||||||
|
var factory = new MqttFactory();
|
||||||
|
var mqttClient = factory.CreateMqttClient();
|
||||||
|
_client = mqttClient;
|
||||||
|
|
||||||
|
await mqttClient.ConnectAsync(mqttClientOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
void WaitForConnect(TimeSpan timeout)
|
||||||
|
{
|
||||||
|
var timer = Stopwatch.StartNew();
|
||||||
|
while ((_client == null || !_client.IsConnected) && timer.Elapsed < timeout)
|
||||||
|
{
|
||||||
|
Thread.Sleep(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed class ServerTestHarness : IDisposable
|
||||||
|
{
|
||||||
|
readonly HotSwappableServerCertProvider _hotSwapServer = new HotSwappableServerCertProvider();
|
||||||
|
|
||||||
|
MqttServer _server;
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_server != null)
|
||||||
|
{
|
||||||
|
_server.StopAsync().Wait();
|
||||||
|
_server.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
_hotSwapServer?.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task ForceDisconnectAsync(ClientTestHarness client)
|
||||||
|
{
|
||||||
|
return _server.DisconnectClientAsync(client.ClientId, MqttDisconnectReasonCode.UnspecifiedError);
|
||||||
|
}
|
||||||
|
|
||||||
|
public X509Certificate2 GetCurrentServerCert()
|
||||||
|
{
|
||||||
|
return _hotSwapServer.GetCertificate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void HotSwapServerCert()
|
||||||
|
{
|
||||||
|
_hotSwapServer.HotSwapCert();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void InstallNewClientCert(X509Certificate2 serverCert)
|
||||||
|
{
|
||||||
|
_hotSwapServer.InstallNewClientCert(serverCert);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StartServer()
|
||||||
|
{
|
||||||
|
var mqttFactory = new MqttFactory();
|
||||||
|
|
||||||
|
var mqttServerOptions = new MqttServerOptionsBuilder().WithEncryptionCertificate(_hotSwapServer)
|
||||||
|
.WithRemoteCertificateValidationCallback(_hotSwapServer.RemoteCertificateValidationCallback)
|
||||||
|
.WithEncryptedEndpoint()
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
mqttServerOptions.TlsEndpointOptions.ClientCertificateRequired = true;
|
||||||
|
|
||||||
|
_server = mqttFactory.CreateMqttServer(mqttServerOptions);
|
||||||
|
return _server.StartAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class HotSwappableClientCertProvider : IMqttClientCertificatesProvider, IDisposable
|
||||||
|
{
|
||||||
|
X509Certificate2Collection _certificates;
|
||||||
|
ConcurrentBag<X509Certificate2> _serverCerts = new ConcurrentBag<X509Certificate2>();
|
||||||
|
|
||||||
|
public HotSwappableClientCertProvider()
|
||||||
|
{
|
||||||
|
_certificates = new X509Certificate2Collection(CreateSelfSignedCertificate("1.3.6.1.5.5.7.3.2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_certificates != null)
|
||||||
|
{
|
||||||
|
foreach (var certs in _certificates)
|
||||||
|
{
|
||||||
|
#if !NET452
|
||||||
|
certs.Dispose();
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public X509CertificateCollection GetCertificates()
|
||||||
|
{
|
||||||
|
return new X509Certificate2Collection(_certificates);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void HotSwapCert()
|
||||||
|
{
|
||||||
|
_certificates = new X509Certificate2Collection(CreateSelfSignedCertificate("1.3.6.1.5.5.7.3.2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void InstallNewServerCert(X509Certificate2 serverCert)
|
||||||
|
{
|
||||||
|
_serverCerts.Add(serverCert);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool OnCertificateValidation(MqttClientCertificateValidationEventArgs certContext)
|
||||||
|
{
|
||||||
|
var serverCerts = _serverCerts.ToArray();
|
||||||
|
|
||||||
|
var providedCert = certContext.Certificate.GetRawCertData();
|
||||||
|
for (int i = 0, n = serverCerts.Length; i < n; i++)
|
||||||
|
{
|
||||||
|
var currentcert = serverCerts[i];
|
||||||
|
|
||||||
|
if (currentcert.RawData.SequenceEqual(providedCert))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed class HotSwappableServerCertProvider : ICertificateProvider, IDisposable
|
||||||
|
{
|
||||||
|
readonly ConcurrentBag<X509Certificate2> _clientCerts = new ConcurrentBag<X509Certificate2>();
|
||||||
|
X509Certificate2 _certificate;
|
||||||
|
|
||||||
|
public HotSwappableServerCertProvider()
|
||||||
|
{
|
||||||
|
_certificate = CreateSelfSignedCertificate("1.3.6.1.5.5.7.3.1");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
#if !NET452
|
||||||
|
_certificate.Dispose();
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
public X509Certificate2 GetCertificate()
|
||||||
|
{
|
||||||
|
return _certificate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void HotSwapCert()
|
||||||
|
{
|
||||||
|
var newCert = CreateSelfSignedCertificate("1.3.6.1.5.5.7.3.1");
|
||||||
|
var oldCert = Interlocked.Exchange(ref _certificate, newCert);
|
||||||
|
#if !NET452
|
||||||
|
oldCert.Dispose();
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
public void InstallNewClientCert(X509Certificate2 certificate)
|
||||||
|
{
|
||||||
|
_clientCerts.Add(certificate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
|
||||||
|
{
|
||||||
|
var serverCerts = _clientCerts.ToArray();
|
||||||
|
|
||||||
|
var providedCert = certificate.GetRawCertData();
|
||||||
|
for (int i = 0, n = serverCerts.Length; i < n; i++)
|
||||||
|
{
|
||||||
|
var currentCert = serverCerts[i];
|
||||||
|
|
||||||
|
if (currentCert.RawData.SequenceEqual(providedCert))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Tests.Server
|
||||||
|
{
|
||||||
|
[TestClass]
|
||||||
|
public sealed class MqttRetainedMessageManager_Tests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public async Task MqttRetainedMessageManager_GetUndefinedTopic()
|
||||||
|
{
|
||||||
|
var logger = new Mockups.TestLogger();
|
||||||
|
var eventContainer = new MQTTnet.Server.MqttServerEventContainer();
|
||||||
|
var retainedMessagesManager = new MQTTnet.Server.MqttRetainedMessagesManager(eventContainer, logger);
|
||||||
|
var task = retainedMessagesManager.GetMessage("undefined");
|
||||||
|
Assert.IsNotNull(task, "Task should not be null");
|
||||||
|
var result = await task;
|
||||||
|
Assert.IsNull(result, "Null result expected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -221,7 +221,10 @@ namespace MQTTnet.Tests.Server
|
|||||||
var eventContainer = new MqttServerEventContainer();
|
var eventContainer = new MqttServerEventContainer();
|
||||||
var clientSessionManager = new MqttClientSessionsManager(options, retainedMessagesManager, eventContainer, logger);
|
var clientSessionManager = new MqttClientSessionsManager(options, retainedMessagesManager, eventContainer, logger);
|
||||||
|
|
||||||
var session = new MqttSession("", false, new ConcurrentDictionary<object, object>(), options, eventContainer, retainedMessagesManager, clientSessionManager);
|
var session = new MqttSession(new MqttConnectPacket
|
||||||
|
{
|
||||||
|
ClientId = ""
|
||||||
|
}, new ConcurrentDictionary<object, object>(), options, eventContainer, retainedMessagesManager, clientSessionManager);
|
||||||
|
|
||||||
_subscriptionsManager = new MqttClientSubscriptionsManager(session, new MqttServerEventContainer(), retainedMessagesManager, clientSessionManager);
|
_subscriptionsManager = new MqttClientSubscriptionsManager(session, new MqttServerEventContainer(), retainedMessagesManager, clientSessionManager);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ using MQTTnet.Client;
|
|||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
using MQTTnet.Internal;
|
using MQTTnet.Internal;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
|
using MQTTnet.Server;
|
||||||
|
|
||||||
namespace MQTTnet.Tests.Server
|
namespace MQTTnet.Tests.Server
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -70,6 +70,28 @@ namespace MQTTnet.Tests.Server
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Do_Not_Use_Expired_Session()
|
||||||
|
{
|
||||||
|
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
|
||||||
|
{
|
||||||
|
await testEnvironment.StartServer(o => o.WithPersistentSessions());
|
||||||
|
|
||||||
|
var c1 = await testEnvironment.ConnectClient(o => o.WithClientId("Client1").WithCleanSession(false).WithSessionExpiryInterval(3));
|
||||||
|
|
||||||
|
// Kill the client connection and ensure that the session will stay there but is expired after 3 seconds!
|
||||||
|
c1.Dispose();
|
||||||
|
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(6));
|
||||||
|
|
||||||
|
c1 = testEnvironment.CreateClient();
|
||||||
|
var options = testEnvironment.CreateDefaultClientOptionsBuilder().WithClientId("Client1").WithCleanSession(false).WithSessionExpiryInterval(3).Build();
|
||||||
|
|
||||||
|
var connectResult = await c1.ConnectAsync(options);
|
||||||
|
Assert.AreEqual(false, connectResult.IsSessionPresent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public async Task Fire_Deleted_Event()
|
public async Task Fire_Deleted_Event()
|
||||||
{
|
{
|
||||||
@@ -134,16 +156,12 @@ namespace MQTTnet.Tests.Server
|
|||||||
|
|
||||||
await testEnvironment.StartServer();
|
await testEnvironment.StartServer();
|
||||||
|
|
||||||
var options = new MqttClientOptionsBuilder().WithClientId("1").WithTimeout(TimeSpan.FromSeconds(1)).WithProtocolVersion(protocolVersion);
|
var options = new MqttClientOptionsBuilder().WithClientId("1").WithTimeout(TimeSpan.FromSeconds(10)).WithProtocolVersion(protocolVersion);
|
||||||
|
|
||||||
var hasReceive = false;
|
var hasReceive = false;
|
||||||
|
|
||||||
void OnReceive()
|
void OnReceive()
|
||||||
{
|
{
|
||||||
if (!hasReceive)
|
hasReceive = true;
|
||||||
{
|
|
||||||
hasReceive = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to connect 50 clients at the same time.
|
// Try to connect 50 clients at the same time.
|
||||||
@@ -265,7 +283,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
|
|
||||||
server.InterceptingPublishAsync += e =>
|
server.InterceptingPublishAsync += e =>
|
||||||
{
|
{
|
||||||
e.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(e.SessionItems["default_payload"] as string ?? string.Empty);
|
e.ApplicationMessage.PayloadSegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes(e.SessionItems["default_payload"] as string ?? string.Empty));
|
||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -356,7 +374,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
};
|
};
|
||||||
|
|
||||||
using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
|
using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
|
||||||
{
|
{
|
||||||
await client.SubscribeAsync("aaa", MqttQualityOfServiceLevel.AtMostOnce, timeout.Token).ConfigureAwait(false);
|
await client.SubscribeAsync("aaa", MqttQualityOfServiceLevel.AtMostOnce, timeout.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -557,7 +557,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
var eventContainer = new MqttServerEventContainer();
|
var eventContainer = new MqttServerEventContainer();
|
||||||
var retainedMessagesManager = new MqttRetainedMessagesManager(eventContainer, logger);
|
var retainedMessagesManager = new MqttRetainedMessagesManager(eventContainer, logger);
|
||||||
var sessionManager = new MqttClientSessionsManager(serverOptions, retainedMessagesManager, eventContainer, logger);
|
var sessionManager = new MqttClientSessionsManager(serverOptions, retainedMessagesManager, eventContainer, logger);
|
||||||
_clientSession = new MqttSession(clientId, false, new Dictionary<object, object>(), serverOptions, eventContainer, retainedMessagesManager, sessionManager);
|
_clientSession = new MqttSession(new MqttConnectPacket{ ClientId = clientId }, new Dictionary<object, object>(), serverOptions, eventContainer, retainedMessagesManager, sessionManager);
|
||||||
|
|
||||||
List<string> topicsToSubscribe;
|
List<string> topicsToSubscribe;
|
||||||
|
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
new MqttApplicationMessage
|
new MqttApplicationMessage
|
||||||
{
|
{
|
||||||
Topic = "TestTopic1",
|
Topic = "TestTopic1",
|
||||||
Payload = new byte[] { 1, 2, 3, 4 }
|
PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3, 4 })
|
||||||
});
|
});
|
||||||
|
|
||||||
await testEnvironment.Server.InjectApplicationMessage(
|
await testEnvironment.Server.InjectApplicationMessage(
|
||||||
@@ -109,7 +109,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
new MqttApplicationMessage
|
new MqttApplicationMessage
|
||||||
{
|
{
|
||||||
Topic = "TestTopic1",
|
Topic = "TestTopic1",
|
||||||
Payload = new byte[] { 1, 2, 3, 4 }
|
PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3, 4 })
|
||||||
}));
|
}));
|
||||||
|
|
||||||
certificateProvider.CurrentCertificate = CreateCertificate(secondOid);
|
certificateProvider.CurrentCertificate = CreateCertificate(secondOid);
|
||||||
@@ -137,7 +137,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
new MqttApplicationMessage
|
new MqttApplicationMessage
|
||||||
{
|
{
|
||||||
Topic = "TestTopic2",
|
Topic = "TestTopic2",
|
||||||
Payload = new byte[] { 1, 2, 3, 4 }
|
PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3, 4 })
|
||||||
});
|
});
|
||||||
|
|
||||||
await testEnvironment.Server.InjectApplicationMessage(
|
await testEnvironment.Server.InjectApplicationMessage(
|
||||||
@@ -145,7 +145,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
new MqttApplicationMessage
|
new MqttApplicationMessage
|
||||||
{
|
{
|
||||||
Topic = "TestTopic2",
|
Topic = "TestTopic2",
|
||||||
Payload = new byte[] { 1, 2, 3, 4 }
|
PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3, 4 })
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Ensure first client still works
|
// Ensure first client still works
|
||||||
@@ -153,7 +153,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
new MqttApplicationMessage
|
new MqttApplicationMessage
|
||||||
{
|
{
|
||||||
Topic = "TestTopic1",
|
Topic = "TestTopic1",
|
||||||
Payload = new byte[] { 1, 2, 3, 4 }
|
PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3, 4 })
|
||||||
});
|
});
|
||||||
|
|
||||||
await testEnvironment.Server.InjectApplicationMessage(
|
await testEnvironment.Server.InjectApplicationMessage(
|
||||||
@@ -161,7 +161,7 @@ namespace MQTTnet.Tests.Server
|
|||||||
new MqttApplicationMessage
|
new MqttApplicationMessage
|
||||||
{
|
{
|
||||||
Topic = "TestTopic1",
|
Topic = "TestTopic1",
|
||||||
Payload = new byte[] { 1, 2, 3, 4 }
|
PayloadSegment = new ArraySegment<byte>(new byte[] { 1, 2, 3, 4 })
|
||||||
}));
|
}));
|
||||||
|
|
||||||
await Task.Delay(1000);
|
await Task.Delay(1000);
|
||||||
@@ -178,12 +178,10 @@ namespace MQTTnet.Tests.Server
|
|||||||
var clientOptionsBuilder = testEnvironment.Factory.CreateClientOptionsBuilder();
|
var clientOptionsBuilder = testEnvironment.Factory.CreateClientOptionsBuilder();
|
||||||
clientOptionsBuilder.WithClientId(Guid.NewGuid().ToString())
|
clientOptionsBuilder.WithClientId(Guid.NewGuid().ToString())
|
||||||
.WithTcpServer("localhost", 8883)
|
.WithTcpServer("localhost", 8883)
|
||||||
.WithTls(
|
.WithTlsOptions(
|
||||||
tls =>
|
o =>
|
||||||
{
|
{
|
||||||
tls.UseTls = true;
|
o.WithSslProtocols(SslProtocols.Tls12).WithCertificateValidationHandler(certValidator);
|
||||||
tls.SslProtocol = SslProtocols.Tls12;
|
|
||||||
tls.CertificateValidationHandler = certValidator;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
var clientOptions = clientOptionsBuilder.Build();
|
var clientOptions = clientOptionsBuilder.Build();
|
||||||
|
|||||||
@@ -25,8 +25,6 @@ namespace MQTTnet.Adapter
|
|||||||
|
|
||||||
long BytesReceived { get; }
|
long BytesReceived { get; }
|
||||||
|
|
||||||
bool IsReadingPacket { get; }
|
|
||||||
|
|
||||||
Task ConnectAsync(CancellationToken cancellationToken);
|
Task ConnectAsync(CancellationToken cancellationToken);
|
||||||
|
|
||||||
Task DisconnectAsync(CancellationToken cancellationToken);
|
Task DisconnectAsync(CancellationToken cancellationToken);
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ namespace MQTTnet.Adapter
|
|||||||
Func<IMqttChannelAdapter, Task> ClientHandler { get; set; }
|
Func<IMqttChannelAdapter, Task> ClientHandler { get; set; }
|
||||||
|
|
||||||
Task StartAsync(MqttServerOptions options, IMqttNetLogger logger);
|
Task StartAsync(MqttServerOptions options, IMqttNetLogger logger);
|
||||||
|
|
||||||
Task StopAsync();
|
Task StopAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,9 +26,7 @@ namespace MQTTnet.Adapter
|
|||||||
readonly IMqttChannel _channel;
|
readonly IMqttChannel _channel;
|
||||||
readonly byte[] _fixedHeaderBuffer = new byte[2];
|
readonly byte[] _fixedHeaderBuffer = new byte[2];
|
||||||
readonly MqttNetSourceLogger _logger;
|
readonly MqttNetSourceLogger _logger;
|
||||||
|
|
||||||
readonly byte[] _singleByteBuffer = new byte[1];
|
readonly byte[] _singleByteBuffer = new byte[1];
|
||||||
|
|
||||||
readonly AsyncLock _syncRoot = new AsyncLock();
|
readonly AsyncLock _syncRoot = new AsyncLock();
|
||||||
|
|
||||||
Statistics _statistics; // mutable struct, don't make readonly!
|
Statistics _statistics; // mutable struct, don't make readonly!
|
||||||
@@ -47,6 +45,8 @@ namespace MQTTnet.Adapter
|
|||||||
_logger = logger.WithSource(nameof(MqttChannelAdapter));
|
_logger = logger.WithSource(nameof(MqttChannelAdapter));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public bool AllowPacketFragmentation { get; set; } = true;
|
||||||
|
|
||||||
public long BytesReceived => Volatile.Read(ref _statistics._bytesReceived);
|
public long BytesReceived => Volatile.Read(ref _statistics._bytesReceived);
|
||||||
|
|
||||||
public long BytesSent => Volatile.Read(ref _statistics._bytesSent);
|
public long BytesSent => Volatile.Read(ref _statistics._bytesSent);
|
||||||
@@ -55,16 +55,12 @@ namespace MQTTnet.Adapter
|
|||||||
|
|
||||||
public string Endpoint => _channel.Endpoint;
|
public string Endpoint => _channel.Endpoint;
|
||||||
|
|
||||||
public bool IsReadingPacket { get; private set; }
|
|
||||||
|
|
||||||
public bool IsSecureConnection => _channel.IsSecureConnection;
|
public bool IsSecureConnection => _channel.IsSecureConnection;
|
||||||
|
|
||||||
public MqttPacketFormatterAdapter PacketFormatterAdapter { get; }
|
public MqttPacketFormatterAdapter PacketFormatterAdapter { get; }
|
||||||
|
|
||||||
public MqttPacketInspector PacketInspector { get; set; }
|
public MqttPacketInspector PacketInspector { get; set; }
|
||||||
|
|
||||||
public bool AllowPacketFragmentation { get; set; } = true;
|
|
||||||
|
|
||||||
public async Task ConnectAsync(CancellationToken cancellationToken)
|
public async Task ConnectAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -78,12 +74,30 @@ namespace MQTTnet.Adapter
|
|||||||
* block forever. Even a cancellation token is not supported properly.
|
* block forever. Even a cancellation token is not supported properly.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
var connectTask = _channel.ConnectAsync(cancellationToken);
|
|
||||||
|
|
||||||
var timeout = new TaskCompletionSource<object>();
|
var timeout = new TaskCompletionSource<object>();
|
||||||
using (cancellationToken.Register(() => timeout.TrySetResult(null)))
|
using (cancellationToken.Register(() => timeout.TrySetResult(null)))
|
||||||
{
|
{
|
||||||
|
var connectTask = Task.Run(
|
||||||
|
async () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _channel.ConnectAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// If the timeout is already reached the exception is no longer of interest and
|
||||||
|
// must be catched. Otherwise it will arrive at the TaskScheduler.UnobservedTaskException.
|
||||||
|
if (!timeout.Task.IsCompleted)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
CancellationToken.None);
|
||||||
|
|
||||||
await Task.WhenAny(connectTask, timeout.Task).ConfigureAwait(false);
|
await Task.WhenAny(connectTask, timeout.Task).ConfigureAwait(false);
|
||||||
|
|
||||||
if (timeout.Task.IsCompleted && !connectTask.IsCompleted)
|
if (timeout.Task.IsCompleted && !connectTask.IsCompleted)
|
||||||
{
|
{
|
||||||
throw new OperationCanceledException("MQTT connect canceled.", cancellationToken);
|
throw new OperationCanceledException("MQTT connect canceled.", cancellationToken);
|
||||||
@@ -127,7 +141,8 @@ namespace MQTTnet.Adapter
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
PacketInspector?.BeginReceivePacket();
|
var localPacketInspector = PacketInspector;
|
||||||
|
localPacketInspector?.BeginReceivePacket();
|
||||||
|
|
||||||
ReceivedMqttPacket receivedPacket;
|
ReceivedMqttPacket receivedPacket;
|
||||||
var receivedPacketTask = ReceiveAsync(cancellationToken);
|
var receivedPacketTask = ReceiveAsync(cancellationToken);
|
||||||
@@ -145,7 +160,10 @@ namespace MQTTnet.Adapter
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
PacketInspector?.EndReceivePacket();
|
if (localPacketInspector != null)
|
||||||
|
{
|
||||||
|
await localPacketInspector.EndReceivePacket().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
Interlocked.Add(ref _statistics._bytesSent, receivedPacket.TotalLength);
|
Interlocked.Add(ref _statistics._bytesSent, receivedPacket.TotalLength);
|
||||||
|
|
||||||
@@ -201,7 +219,12 @@ namespace MQTTnet.Adapter
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var packetBuffer = PacketFormatterAdapter.Encode(packet);
|
var packetBuffer = PacketFormatterAdapter.Encode(packet);
|
||||||
PacketInspector?.BeginSendPacket(packetBuffer);
|
|
||||||
|
var localPacketInspector = PacketInspector;
|
||||||
|
if (localPacketInspector != null)
|
||||||
|
{
|
||||||
|
await localPacketInspector.BeginSendPacket(packetBuffer).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
_logger.Verbose("TX ({0} bytes) >>> {1}", packetBuffer.Length, packet);
|
_logger.Verbose("TX ({0} bytes) >>> {1}", packetBuffer.Length, packet);
|
||||||
|
|
||||||
@@ -373,53 +396,45 @@ namespace MQTTnet.Adapter
|
|||||||
return ReceivedMqttPacket.Empty;
|
return ReceivedMqttPacket.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
IsReadingPacket = true;
|
var fixedHeader = readFixedHeaderResult.FixedHeader;
|
||||||
try
|
if (fixedHeader.RemainingLength == 0)
|
||||||
{
|
{
|
||||||
var fixedHeader = readFixedHeaderResult.FixedHeader;
|
return new ReceivedMqttPacket(fixedHeader.Flags, EmptyBuffer.ArraySegment, 2);
|
||||||
if (fixedHeader.RemainingLength == 0)
|
}
|
||||||
|
|
||||||
|
var bodyLength = fixedHeader.RemainingLength;
|
||||||
|
var body = new byte[bodyLength];
|
||||||
|
|
||||||
|
var bodyOffset = 0;
|
||||||
|
var chunkSize = Math.Min(ReadBufferSize, bodyLength);
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
var bytesLeft = body.Length - bodyOffset;
|
||||||
|
if (chunkSize > bytesLeft)
|
||||||
{
|
{
|
||||||
return new ReceivedMqttPacket(fixedHeader.Flags, EmptyBuffer.ArraySegment, 2);
|
chunkSize = bytesLeft;
|
||||||
}
|
}
|
||||||
|
|
||||||
var bodyLength = fixedHeader.RemainingLength;
|
var readBytes = await _channel.ReadAsync(body, bodyOffset, chunkSize, cancellationToken).ConfigureAwait(false);
|
||||||
var body = new byte[bodyLength];
|
|
||||||
|
|
||||||
var bodyOffset = 0;
|
if (cancellationToken.IsCancellationRequested)
|
||||||
var chunkSize = Math.Min(ReadBufferSize, bodyLength);
|
|
||||||
|
|
||||||
do
|
|
||||||
{
|
{
|
||||||
var bytesLeft = body.Length - bodyOffset;
|
return ReceivedMqttPacket.Empty;
|
||||||
if (chunkSize > bytesLeft)
|
}
|
||||||
{
|
|
||||||
chunkSize = bytesLeft;
|
|
||||||
}
|
|
||||||
|
|
||||||
var readBytes = await _channel.ReadAsync(body, bodyOffset, chunkSize, cancellationToken).ConfigureAwait(false);
|
if (readBytes == 0)
|
||||||
|
{
|
||||||
|
return ReceivedMqttPacket.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
if (cancellationToken.IsCancellationRequested)
|
bodyOffset += readBytes;
|
||||||
{
|
} while (bodyOffset < bodyLength);
|
||||||
return ReceivedMqttPacket.Empty;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (readBytes == 0)
|
PacketInspector?.FillReceiveBuffer(body);
|
||||||
{
|
|
||||||
return ReceivedMqttPacket.Empty;
|
|
||||||
}
|
|
||||||
|
|
||||||
bodyOffset += readBytes;
|
var bodySegment = new ArraySegment<byte>(body, 0, bodyLength);
|
||||||
} while (bodyOffset < bodyLength);
|
return new ReceivedMqttPacket(fixedHeader.Flags, bodySegment, fixedHeader.TotalLength);
|
||||||
|
|
||||||
PacketInspector?.FillReceiveBuffer(body);
|
|
||||||
|
|
||||||
var bodySegment = new ArraySegment<byte>(body, 0, bodyLength);
|
|
||||||
return new ReceivedMqttPacket(fixedHeader.Flags, bodySegment, fixedHeader.TotalLength);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
IsReadingPacket = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool WrapAndThrowException(Exception exception)
|
static bool WrapAndThrowException(Exception exception)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Diagnostics;
|
using MQTTnet.Diagnostics;
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
using MQTTnet.Internal;
|
using MQTTnet.Internal;
|
||||||
@@ -12,8 +13,8 @@ namespace MQTTnet.Adapter
|
|||||||
{
|
{
|
||||||
public sealed class MqttPacketInspector
|
public sealed class MqttPacketInspector
|
||||||
{
|
{
|
||||||
readonly MqttNetSourceLogger _logger;
|
|
||||||
readonly AsyncEvent<InspectMqttPacketEventArgs> _asyncEvent;
|
readonly AsyncEvent<InspectMqttPacketEventArgs> _asyncEvent;
|
||||||
|
readonly MqttNetSourceLogger _logger;
|
||||||
|
|
||||||
MemoryStream _receivedPacketBuffer;
|
MemoryStream _receivedPacketBuffer;
|
||||||
|
|
||||||
@@ -21,7 +22,11 @@ namespace MQTTnet.Adapter
|
|||||||
{
|
{
|
||||||
_asyncEvent = asyncEvent ?? throw new ArgumentNullException(nameof(asyncEvent));
|
_asyncEvent = asyncEvent ?? throw new ArgumentNullException(nameof(asyncEvent));
|
||||||
|
|
||||||
if (logger == null) throw new ArgumentNullException(nameof(logger));
|
if (logger == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(logger));
|
||||||
|
}
|
||||||
|
|
||||||
_logger = logger.WithSource(nameof(MqttPacketInspector));
|
_logger = logger.WithSource(nameof(MqttPacketInspector));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,24 +45,11 @@ namespace MQTTnet.Adapter
|
|||||||
_receivedPacketBuffer?.SetLength(0);
|
_receivedPacketBuffer?.SetLength(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void EndReceivePacket()
|
public Task BeginSendPacket(MqttPacketBuffer buffer)
|
||||||
{
|
{
|
||||||
if (!_asyncEvent.HasHandlers)
|
if (!_asyncEvent.HasHandlers)
|
||||||
{
|
{
|
||||||
return;
|
return CompletedTask.Instance;
|
||||||
}
|
|
||||||
|
|
||||||
var buffer = _receivedPacketBuffer.ToArray();
|
|
||||||
_receivedPacketBuffer.SetLength(0);
|
|
||||||
|
|
||||||
InspectPacket(buffer, MqttPacketFlowDirection.Inbound);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void BeginSendPacket(MqttPacketBuffer buffer)
|
|
||||||
{
|
|
||||||
if (!_asyncEvent.HasHandlers)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a copy of the actual packet so that the inspector gets no access
|
// Create a copy of the actual packet so that the inspector gets no access
|
||||||
@@ -65,7 +57,20 @@ namespace MQTTnet.Adapter
|
|||||||
// intended for debugging etc. so that this is OK.
|
// intended for debugging etc. so that this is OK.
|
||||||
var bufferCopy = buffer.ToArray();
|
var bufferCopy = buffer.ToArray();
|
||||||
|
|
||||||
InspectPacket(bufferCopy, MqttPacketFlowDirection.Outbound);
|
return InspectPacket(bufferCopy, MqttPacketFlowDirection.Outbound);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task EndReceivePacket()
|
||||||
|
{
|
||||||
|
if (!_asyncEvent.HasHandlers)
|
||||||
|
{
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
var buffer = _receivedPacketBuffer.ToArray();
|
||||||
|
_receivedPacketBuffer.SetLength(0);
|
||||||
|
|
||||||
|
return InspectPacket(buffer, MqttPacketFlowDirection.Inbound);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void FillReceiveBuffer(byte[] buffer)
|
public void FillReceiveBuffer(byte[] buffer)
|
||||||
@@ -78,12 +83,12 @@ namespace MQTTnet.Adapter
|
|||||||
_receivedPacketBuffer?.Write(buffer, 0, buffer.Length);
|
_receivedPacketBuffer?.Write(buffer, 0, buffer.Length);
|
||||||
}
|
}
|
||||||
|
|
||||||
void InspectPacket(byte[] buffer, MqttPacketFlowDirection direction)
|
async Task InspectPacket(byte[] buffer, MqttPacketFlowDirection direction)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var eventArgs = new InspectMqttPacketEventArgs(direction, buffer);
|
var eventArgs = new InspectMqttPacketEventArgs(direction, buffer);
|
||||||
_asyncEvent.InvokeAsync(eventArgs).GetAwaiter().GetResult();
|
await _asyncEvent.InvokeAsync(eventArgs).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
// The .NET Foundation licenses this file to you under the MIT license.
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using MQTTnet.Exceptions;
|
using MQTTnet.Exceptions;
|
||||||
using MQTTnet.Packets;
|
using MQTTnet.Packets;
|
||||||
@@ -11,8 +12,9 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
public sealed class MqttClientUnexpectedDisconnectReceivedException : MqttCommunicationException
|
public sealed class MqttClientUnexpectedDisconnectReceivedException : MqttCommunicationException
|
||||||
{
|
{
|
||||||
public MqttClientUnexpectedDisconnectReceivedException(MqttDisconnectPacket disconnectPacket)
|
public MqttClientUnexpectedDisconnectReceivedException(MqttDisconnectPacket disconnectPacket, Exception innerExcpetion = null) : base(
|
||||||
: base($"Unexpected DISCONNECT (Reason code={disconnectPacket.ReasonCode}) received.")
|
$"Unexpected DISCONNECT (Reason code={disconnectPacket.ReasonCode}) received.",
|
||||||
|
innerExcpetion)
|
||||||
{
|
{
|
||||||
ReasonCode = disconnectPacket.ReasonCode;
|
ReasonCode = disconnectPacket.ReasonCode;
|
||||||
SessionExpiryInterval = disconnectPacket.SessionExpiryInterval;
|
SessionExpiryInterval = disconnectPacket.SessionExpiryInterval;
|
||||||
@@ -23,12 +25,12 @@ namespace MQTTnet.Client
|
|||||||
|
|
||||||
public MqttDisconnectReasonCode? ReasonCode { get; }
|
public MqttDisconnectReasonCode? ReasonCode { get; }
|
||||||
|
|
||||||
public uint? SessionExpiryInterval { get; }
|
|
||||||
|
|
||||||
public string ReasonString { get; }
|
public string ReasonString { get; }
|
||||||
|
|
||||||
public List<MqttUserProperty> UserProperties { get; }
|
|
||||||
|
|
||||||
public string ServerReference { get; }
|
public string ServerReference { get; }
|
||||||
|
|
||||||
|
public uint? SessionExpiryInterval { get; }
|
||||||
|
|
||||||
|
public List<MqttUserProperty> UserProperties { get; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using MQTTnet.Diagnostics;
|
||||||
|
using MQTTnet.Internal;
|
||||||
|
|
||||||
|
namespace MQTTnet.Client.Internal
|
||||||
|
{
|
||||||
|
public sealed class MqttClientEvents
|
||||||
|
{
|
||||||
|
public AsyncEvent<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceivedEvent { get; } = new AsyncEvent<MqttApplicationMessageReceivedEventArgs>();
|
||||||
|
public AsyncEvent<MqttClientConnectedEventArgs> ConnectedEvent { get; } = new AsyncEvent<MqttClientConnectedEventArgs>();
|
||||||
|
public AsyncEvent<MqttClientConnectingEventArgs> ConnectingEvent { get; } = new AsyncEvent<MqttClientConnectingEventArgs>();
|
||||||
|
public AsyncEvent<MqttClientDisconnectedEventArgs> DisconnectedEvent { get; } = new AsyncEvent<MqttClientDisconnectedEventArgs>();
|
||||||
|
public AsyncEvent<InspectMqttPacketEventArgs> InspectPacketEvent { get; } = new AsyncEvent<InspectMqttPacketEventArgs>();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
namespace MQTTnet.Client.Internal
|
||||||
|
{
|
||||||
|
public static class MqttClientResultFactory
|
||||||
|
{
|
||||||
|
public static readonly MqttClientConnectResultFactory ConnectResult = new MqttClientConnectResultFactory();
|
||||||
|
public static readonly MqttClientPublishResultFactory PublishResult = new MqttClientPublishResultFactory();
|
||||||
|
public static readonly MqttClientSubscribeResultFactory SubscribeResult = new MqttClientSubscribeResultFactory();
|
||||||
|
public static readonly MqttClientUnsubscribeResultFactory UnsubscribeResult = new MqttClientUnsubscribeResultFactory();
|
||||||
|
}
|
||||||
|
}
|
||||||
+334
-256
@@ -7,6 +7,7 @@ using System.Collections.Generic;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Adapter;
|
using MQTTnet.Adapter;
|
||||||
|
using MQTTnet.Client.Internal;
|
||||||
using MQTTnet.Diagnostics;
|
using MQTTnet.Diagnostics;
|
||||||
using MQTTnet.Exceptions;
|
using MQTTnet.Exceptions;
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
@@ -20,17 +21,9 @@ namespace MQTTnet.Client
|
|||||||
public sealed class MqttClient : Disposable, IMqttClient
|
public sealed class MqttClient : Disposable, IMqttClient
|
||||||
{
|
{
|
||||||
readonly IMqttClientAdapterFactory _adapterFactory;
|
readonly IMqttClientAdapterFactory _adapterFactory;
|
||||||
readonly AsyncEvent<MqttApplicationMessageReceivedEventArgs> _applicationMessageReceivedEvent = new AsyncEvent<MqttApplicationMessageReceivedEventArgs>();
|
|
||||||
|
|
||||||
readonly MqttClientPublishResultFactory _clientPublishResultFactory = new MqttClientPublishResultFactory();
|
|
||||||
readonly MqttClientSubscribeResultFactory _clientSubscribeResultFactory = new MqttClientSubscribeResultFactory();
|
|
||||||
readonly MqttClientUnsubscribeResultFactory _clientUnsubscribeResultFactory = new MqttClientUnsubscribeResultFactory();
|
|
||||||
|
|
||||||
readonly AsyncEvent<MqttClientConnectedEventArgs> _connectedEvent = new AsyncEvent<MqttClientConnectedEventArgs>();
|
|
||||||
readonly AsyncEvent<MqttClientConnectingEventArgs> _connectingEvent = new AsyncEvent<MqttClientConnectingEventArgs>();
|
|
||||||
readonly AsyncEvent<MqttClientDisconnectedEventArgs> _disconnectedEvent = new AsyncEvent<MqttClientDisconnectedEventArgs>();
|
|
||||||
readonly object _disconnectLock = new object();
|
readonly object _disconnectLock = new object();
|
||||||
readonly AsyncEvent<InspectMqttPacketEventArgs> _inspectPacketEvent = new AsyncEvent<InspectMqttPacketEventArgs>();
|
readonly MqttClientEvents _events = new MqttClientEvents();
|
||||||
readonly MqttNetSourceLogger _logger;
|
readonly MqttNetSourceLogger _logger;
|
||||||
|
|
||||||
readonly MqttPacketIdentifierProvider _packetIdentifierProvider = new MqttPacketIdentifierProvider();
|
readonly MqttPacketIdentifierProvider _packetIdentifierProvider = new MqttPacketIdentifierProvider();
|
||||||
@@ -55,6 +48,7 @@ namespace MQTTnet.Client
|
|||||||
Task _packetReceiverTask;
|
Task _packetReceiverTask;
|
||||||
AsyncQueue<MqttPublishPacket> _publishPacketReceiverQueue;
|
AsyncQueue<MqttPublishPacket> _publishPacketReceiverQueue;
|
||||||
Task _publishPacketReceiverTask;
|
Task _publishPacketReceiverTask;
|
||||||
|
MqttDisconnectPacket _unexpectedDisconnectPacket;
|
||||||
|
|
||||||
public MqttClient(IMqttClientAdapterFactory channelFactory, IMqttNetLogger logger)
|
public MqttClient(IMqttClientAdapterFactory channelFactory, IMqttNetLogger logger)
|
||||||
{
|
{
|
||||||
@@ -65,32 +59,32 @@ namespace MQTTnet.Client
|
|||||||
|
|
||||||
public event Func<MqttApplicationMessageReceivedEventArgs, Task> ApplicationMessageReceivedAsync
|
public event Func<MqttApplicationMessageReceivedEventArgs, Task> ApplicationMessageReceivedAsync
|
||||||
{
|
{
|
||||||
add => _applicationMessageReceivedEvent.AddHandler(value);
|
add => _events.ApplicationMessageReceivedEvent.AddHandler(value);
|
||||||
remove => _applicationMessageReceivedEvent.RemoveHandler(value);
|
remove => _events.ApplicationMessageReceivedEvent.RemoveHandler(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public event Func<MqttClientConnectedEventArgs, Task> ConnectedAsync
|
public event Func<MqttClientConnectedEventArgs, Task> ConnectedAsync
|
||||||
{
|
{
|
||||||
add => _connectedEvent.AddHandler(value);
|
add => _events.ConnectedEvent.AddHandler(value);
|
||||||
remove => _connectedEvent.RemoveHandler(value);
|
remove => _events.ConnectedEvent.RemoveHandler(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public event Func<MqttClientConnectingEventArgs, Task> ConnectingAsync
|
public event Func<MqttClientConnectingEventArgs, Task> ConnectingAsync
|
||||||
{
|
{
|
||||||
add => _connectingEvent.AddHandler(value);
|
add => _events.ConnectingEvent.AddHandler(value);
|
||||||
remove => _connectingEvent.RemoveHandler(value);
|
remove => _events.ConnectingEvent.RemoveHandler(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public event Func<MqttClientDisconnectedEventArgs, Task> DisconnectedAsync
|
public event Func<MqttClientDisconnectedEventArgs, Task> DisconnectedAsync
|
||||||
{
|
{
|
||||||
add => _disconnectedEvent.AddHandler(value);
|
add => _events.DisconnectedEvent.AddHandler(value);
|
||||||
remove => _disconnectedEvent.RemoveHandler(value);
|
remove => _events.DisconnectedEvent.RemoveHandler(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public event Func<InspectMqttPacketEventArgs, Task> InspectPacketAsync
|
public event Func<InspectMqttPacketEventArgs, Task> InspectPacketAsync
|
||||||
{
|
{
|
||||||
add => _inspectPacketEvent.AddHandler(value);
|
add => _events.InspectPacketEvent.AddHandler(value);
|
||||||
remove => _inspectPacketEvent.RemoveHandler(value);
|
remove => _events.InspectPacketEvent.RemoveHandler(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool IsConnected => (MqttClientConnectionStatus)_connectionStatus == MqttClientConnectionStatus.Connected;
|
public bool IsConnected => (MqttClientConnectionStatus)_connectionStatus == MqttClientConnectionStatus.Connected;
|
||||||
@@ -114,9 +108,9 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
Options = options;
|
Options = options;
|
||||||
|
|
||||||
if (_connectingEvent.HasHandlers)
|
if (_events.ConnectingEvent.HasHandlers)
|
||||||
{
|
{
|
||||||
await _connectingEvent.InvokeAsync(new MqttClientConnectingEventArgs(options));
|
await _events.ConnectingEvent.InvokeAsync(new MqttClientConnectingEventArgs(options));
|
||||||
}
|
}
|
||||||
|
|
||||||
Cleanup();
|
Cleanup();
|
||||||
@@ -127,12 +121,14 @@ namespace MQTTnet.Client
|
|||||||
_mqttClientAlive = new CancellationTokenSource();
|
_mqttClientAlive = new CancellationTokenSource();
|
||||||
var mqttClientAliveToken = _mqttClientAlive.Token;
|
var mqttClientAliveToken = _mqttClientAlive.Token;
|
||||||
|
|
||||||
var adapter = _adapterFactory.CreateClientAdapter(options, new MqttPacketInspector(_inspectPacketEvent, _rootLogger), _rootLogger);
|
var adapter = _adapterFactory.CreateClientAdapter(options, new MqttPacketInspector(_events.InspectPacketEvent, _rootLogger), _rootLogger);
|
||||||
_adapter = adapter;
|
_adapter = adapter ?? throw new InvalidOperationException("The adapter factory did not provide an adapter.");
|
||||||
|
|
||||||
|
_unexpectedDisconnectPacket = null;
|
||||||
|
|
||||||
if (cancellationToken.CanBeCanceled)
|
if (cancellationToken.CanBeCanceled)
|
||||||
{
|
{
|
||||||
connectResult = await ConnectInternal(cancellationToken).ConfigureAwait(false);
|
connectResult = await ConnectInternal(adapter, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -140,43 +136,51 @@ namespace MQTTnet.Client
|
|||||||
// CancellationToken.None or similar.
|
// CancellationToken.None or similar.
|
||||||
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
||||||
{
|
{
|
||||||
connectResult = await ConnectInternal(timeout.Token).ConfigureAwait(false);
|
connectResult = await ConnectInternal(adapter, timeout.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (connectResult.ResultCode != MqttClientConnectResultCode.Success)
|
||||||
|
{
|
||||||
|
_logger.Warning("Connecting failed: {0}", connectResult.ResultCode);
|
||||||
|
await DisconnectInternal(null, null, connectResult).ConfigureAwait(false);
|
||||||
|
return connectResult;
|
||||||
|
}
|
||||||
|
|
||||||
_lastPacketSentTimestamp = DateTime.UtcNow;
|
_lastPacketSentTimestamp = DateTime.UtcNow;
|
||||||
|
|
||||||
var keepAliveInterval = Options.KeepAlivePeriod;
|
var keepAliveInterval = Options.KeepAlivePeriod;
|
||||||
if (connectResult.ServerKeepAlive > 0)
|
if (connectResult.ServerKeepAlive > 0)
|
||||||
{
|
{
|
||||||
_logger.Info($"Using keep alive value ({connectResult.ServerKeepAlive}) sent from the server.");
|
_logger.Info($"Using keep alive value ({connectResult.ServerKeepAlive}) sent from the server");
|
||||||
keepAliveInterval = TimeSpan.FromSeconds(connectResult.ServerKeepAlive);
|
keepAliveInterval = TimeSpan.FromSeconds(connectResult.ServerKeepAlive);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (keepAliveInterval != TimeSpan.Zero)
|
if (keepAliveInterval != TimeSpan.Zero)
|
||||||
{
|
{
|
||||||
_keepAlivePacketsSenderTask = Task.Run(() => TrySendKeepAliveMessagesAsync(mqttClientAliveToken), mqttClientAliveToken);
|
_keepAlivePacketsSenderTask = Task.Run(() => TrySendKeepAliveMessages(mqttClientAliveToken), mqttClientAliveToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
CompareExchangeConnectionStatus(MqttClientConnectionStatus.Connected, MqttClientConnectionStatus.Connecting);
|
CompareExchangeConnectionStatus(MqttClientConnectionStatus.Connected, MqttClientConnectionStatus.Connecting);
|
||||||
|
|
||||||
_logger.Info("Connected.");
|
_logger.Info("Connected");
|
||||||
|
|
||||||
if (_connectedEvent.HasHandlers)
|
await OnConnected(connectResult).ConfigureAwait(false);
|
||||||
{
|
|
||||||
var eventArgs = new MqttClientConnectedEventArgs(connectResult);
|
|
||||||
await _connectedEvent.InvokeAsync(eventArgs).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
return connectResult;
|
return connectResult;
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
|
if (exception is MqttConnectingFailedException connectingFailedException)
|
||||||
|
{
|
||||||
|
connectResult = connectingFailedException.Result;
|
||||||
|
}
|
||||||
|
|
||||||
_disconnectReason = (int)MqttClientDisconnectOptionsReason.UnspecifiedError;
|
_disconnectReason = (int)MqttClientDisconnectOptionsReason.UnspecifiedError;
|
||||||
|
|
||||||
_logger.Error(exception, "Error while connecting with server.");
|
_logger.Error(exception, "Error while connecting with server");
|
||||||
|
|
||||||
await DisconnectInternalAsync(null, exception, connectResult).ConfigureAwait(false);
|
await DisconnectInternal(null, exception, connectResult).ConfigureAwait(false);
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
@@ -214,38 +218,43 @@ namespace MQTTnet.Client
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sending the DISCONNECT may fail due to connection issues. The resulting exception
|
// Sending the DISCONNECT may fail due to connection issues. The resulting exception
|
||||||
// must be throw to let the caller know that the disconnect is not a clean one.
|
// must be thrown to let the caller know that the disconnect was not clean.
|
||||||
var disconnectPacket = MqttPacketFactories.Disconnect.Create(options);
|
var disconnectPacket = MqttPacketFactories.Disconnect.Create(options);
|
||||||
|
|
||||||
if (cancellationToken.CanBeCanceled)
|
if (cancellationToken.CanBeCanceled)
|
||||||
{
|
{
|
||||||
await SendAsync(disconnectPacket, cancellationToken).ConfigureAwait(false);
|
await Send(disconnectPacket, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
||||||
{
|
{
|
||||||
await SendAsync(disconnectPacket, timeout.Token).ConfigureAwait(false);
|
await Send(disconnectPacket, timeout.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
await DisconnectCoreAsync(null, null, null, clientWasConnected).ConfigureAwait(false);
|
await DisconnectCore(null, null, null, clientWasConnected).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task PingAsync(CancellationToken cancellationToken = default)
|
public async Task PingAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
ThrowIfDisposed();
|
||||||
|
ThrowIfNotConnected();
|
||||||
|
|
||||||
if (cancellationToken.CanBeCanceled)
|
if (cancellationToken.CanBeCanceled)
|
||||||
{
|
{
|
||||||
await SendAndReceiveAsync<MqttPingRespPacket>(MqttPingReqPacket.Instance, cancellationToken).ConfigureAwait(false);
|
await Request<MqttPingRespPacket>(MqttPingReqPacket.Instance, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
||||||
{
|
{
|
||||||
await SendAndReceiveAsync<MqttPingRespPacket>(MqttPingReqPacket.Instance, timeout.Token).ConfigureAwait(false);
|
await Request<MqttPingRespPacket>(MqttPingReqPacket.Instance, timeout.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,11 +283,11 @@ namespace MQTTnet.Client
|
|||||||
}
|
}
|
||||||
case MqttQualityOfServiceLevel.AtLeastOnce:
|
case MqttQualityOfServiceLevel.AtLeastOnce:
|
||||||
{
|
{
|
||||||
return PublishAtLeastOnceAsync(publishPacket, cancellationToken);
|
return PublishAtLeastOnce(publishPacket, cancellationToken);
|
||||||
}
|
}
|
||||||
case MqttQualityOfServiceLevel.ExactlyOnce:
|
case MqttQualityOfServiceLevel.ExactlyOnce:
|
||||||
{
|
{
|
||||||
return PublishExactlyOnceAsync(publishPacket, cancellationToken);
|
return PublishExactlyOnce(publishPacket, cancellationToken);
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
{
|
{
|
||||||
@@ -303,10 +312,11 @@ namespace MQTTnet.Client
|
|||||||
AuthenticationMethod = Options.AuthenticationMethod,
|
AuthenticationMethod = Options.AuthenticationMethod,
|
||||||
AuthenticationData = data.AuthenticationData,
|
AuthenticationData = data.AuthenticationData,
|
||||||
ReasonString = data.ReasonString,
|
ReasonString = data.ReasonString,
|
||||||
|
ReasonCode = data.ReasonCode,
|
||||||
UserProperties = data.UserProperties
|
UserProperties = data.UserProperties
|
||||||
};
|
};
|
||||||
|
|
||||||
return SendAsync(authPacket, cancellationToken);
|
return Send(authPacket, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<MqttClientSubscribeResult> SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken = default)
|
public async Task<MqttClientSubscribeResult> SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken = default)
|
||||||
@@ -321,31 +331,31 @@ namespace MQTTnet.Client
|
|||||||
MqttTopicValidator.ThrowIfInvalidSubscribe(topicFilter.Topic);
|
MqttTopicValidator.ThrowIfInvalidSubscribe(topicFilter.Topic);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ThrowIfDisposed();
|
||||||
|
ThrowIfNotConnected();
|
||||||
|
|
||||||
if (Options.ValidateFeatures)
|
if (Options.ValidateFeatures)
|
||||||
{
|
{
|
||||||
MqttClientSubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion);
|
MqttClientSubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion);
|
||||||
}
|
}
|
||||||
|
|
||||||
ThrowIfDisposed();
|
|
||||||
ThrowIfNotConnected();
|
|
||||||
|
|
||||||
var subscribePacket = MqttPacketFactories.Subscribe.Create(options);
|
var subscribePacket = MqttPacketFactories.Subscribe.Create(options);
|
||||||
subscribePacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
|
subscribePacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
|
||||||
|
|
||||||
MqttSubAckPacket subAckPacket;
|
MqttSubAckPacket subAckPacket;
|
||||||
if (cancellationToken.CanBeCanceled)
|
if (cancellationToken.CanBeCanceled)
|
||||||
{
|
{
|
||||||
subAckPacket = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket, cancellationToken).ConfigureAwait(false);
|
subAckPacket = await Request<MqttSubAckPacket>(subscribePacket, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
||||||
{
|
{
|
||||||
subAckPacket = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket, timeout.Token).ConfigureAwait(false);
|
subAckPacket = await Request<MqttSubAckPacket>(subscribePacket, timeout.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return _clientSubscribeResultFactory.Create(subscribePacket, subAckPacket);
|
return MqttClientResultFactory.SubscribeResult.Create(subscribePacket, subAckPacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<MqttClientUnsubscribeResult> UnsubscribeAsync(MqttClientUnsubscribeOptions options, CancellationToken cancellationToken = default)
|
public async Task<MqttClientUnsubscribeResult> UnsubscribeAsync(MqttClientUnsubscribeOptions options, CancellationToken cancellationToken = default)
|
||||||
@@ -374,17 +384,17 @@ namespace MQTTnet.Client
|
|||||||
MqttUnsubAckPacket unsubAckPacket;
|
MqttUnsubAckPacket unsubAckPacket;
|
||||||
if (cancellationToken.CanBeCanceled)
|
if (cancellationToken.CanBeCanceled)
|
||||||
{
|
{
|
||||||
unsubAckPacket = await SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket, cancellationToken).ConfigureAwait(false);
|
unsubAckPacket = await Request<MqttUnsubAckPacket>(unsubscribePacket, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
using (var timeout = new CancellationTokenSource(Options.Timeout))
|
||||||
{
|
{
|
||||||
unsubAckPacket = await SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket, timeout.Token).ConfigureAwait(false);
|
unsubAckPacket = await Request<MqttUnsubAckPacket>(unsubscribePacket, timeout.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return _clientUnsubscribeResultFactory.Create(unsubscribePacket, unsubAckPacket);
|
return MqttClientResultFactory.UnsubscribeResult.Create(unsubscribePacket, unsubAckPacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void Dispose(bool disposing)
|
protected override void Dispose(bool disposing)
|
||||||
@@ -399,55 +409,90 @@ namespace MQTTnet.Client
|
|||||||
|
|
||||||
Task AcknowledgeReceivedPublishPacket(MqttApplicationMessageReceivedEventArgs eventArgs, CancellationToken cancellationToken)
|
Task AcknowledgeReceivedPublishPacket(MqttApplicationMessageReceivedEventArgs eventArgs, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
if (eventArgs.PublishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
|
switch (eventArgs.PublishPacket.QualityOfServiceLevel)
|
||||||
{
|
{
|
||||||
// no response required
|
case MqttQualityOfServiceLevel.AtMostOnce:
|
||||||
}
|
|
||||||
else if (eventArgs.PublishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
|
|
||||||
{
|
|
||||||
if (!eventArgs.ProcessingFailed)
|
|
||||||
{
|
{
|
||||||
var pubAckPacket = MqttPacketFactories.PubAck.Create(eventArgs);
|
// no response required
|
||||||
return SendAsync(pubAckPacket, cancellationToken);
|
break;
|
||||||
}
|
}
|
||||||
}
|
case MqttQualityOfServiceLevel.AtLeastOnce:
|
||||||
else if (eventArgs.PublishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
|
|
||||||
{
|
|
||||||
if (!eventArgs.ProcessingFailed)
|
|
||||||
{
|
{
|
||||||
var pubRecPacket = MqttPacketFactories.PubRec.Create(eventArgs);
|
if (!eventArgs.ProcessingFailed)
|
||||||
return SendAsync(pubRecPacket, cancellationToken);
|
{
|
||||||
|
var pubAckPacket = MqttPacketFactories.PubAck.Create(eventArgs);
|
||||||
|
return Send(pubAckPacket, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case MqttQualityOfServiceLevel.ExactlyOnce:
|
||||||
|
{
|
||||||
|
if (!eventArgs.ProcessingFailed)
|
||||||
|
{
|
||||||
|
var pubRecPacket = MqttPacketFactories.PubRec.Create(eventArgs);
|
||||||
|
return Send(pubRecPacket, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
throw new MqttProtocolViolationException("Received a not supported QoS level.");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
throw new MqttProtocolViolationException("Received a not supported QoS level.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return CompletedTask.Instance;
|
return CompletedTask.Instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task<MqttClientConnectResult> AuthenticateAsync(MqttClientOptions options, CancellationToken cancellationToken)
|
async Task<MqttClientConnectResult> Authenticate(IMqttChannelAdapter channelAdapter, MqttClientOptions options, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
MqttClientConnectResult result;
|
MqttClientConnectResult result;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var connectPacket = MqttPacketFactories.Connect.Create(options);
|
var connectPacket = MqttPacketFactories.Connect.Create(options);
|
||||||
|
await Send(connectPacket, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
var connAckPacket = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket, cancellationToken).ConfigureAwait(false);
|
var receivedPacket = await Receive(cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
var clientConnectResultFactory = new MqttClientConnectResultFactory();
|
switch (receivedPacket)
|
||||||
result = clientConnectResultFactory.Create(connAckPacket, _adapter.PacketFormatterAdapter.ProtocolVersion);
|
{
|
||||||
|
case MqttConnAckPacket connAckPacket:
|
||||||
|
{
|
||||||
|
result = MqttClientResultFactory.ConnectResult.Create(connAckPacket, channelAdapter.PacketFormatterAdapter.ProtocolVersion);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case MqttAuthPacket _:
|
||||||
|
{
|
||||||
|
throw new NotSupportedException("Extended authentication handler is not yet supported");
|
||||||
|
}
|
||||||
|
case null:
|
||||||
|
{
|
||||||
|
throw new MqttCommunicationException("Connection closed.");
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"Received an unexpected MQTT packet ({receivedPacket}).");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
throw new MqttConnectingFailedException($"Error while authenticating. {exception.Message}", exception, null);
|
throw new MqttConnectingFailedException($"Error while authenticating. {exception.Message}", exception, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.ResultCode != MqttClientConnectResultCode.Success)
|
// This is no feature. It is basically a backward compatibility option and should be removed in the future.
|
||||||
|
// The client should not throw any exception if the transport layer connection was successful and the server
|
||||||
|
// did send a proper ACK packet with a non success response.
|
||||||
|
if (options.ThrowOnNonSuccessfulConnectResponse)
|
||||||
{
|
{
|
||||||
throw new MqttConnectingFailedException($"Connecting with MQTT server failed ({result.ResultCode}).", null, result);
|
if (result.ResultCode != MqttClientConnectResultCode.Success)
|
||||||
|
{
|
||||||
|
_logger.Warning(
|
||||||
|
"Client will now throw an _MqttConnectingFailedException_. This is obsolete and will be removed in the future. Consider setting _ThrowOnNonSuccessfulResponseFromServer=False_ in client options.");
|
||||||
|
throw new MqttConnectingFailedException($"Connecting with MQTT server failed ({result.ResultCode}).", null, result);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_logger.Verbose("Authenticated MQTT connection with server established.");
|
_logger.Verbose("Authenticated MQTT connection with server established.");
|
||||||
@@ -482,27 +527,31 @@ namespace MQTTnet.Client
|
|||||||
return (MqttClientConnectionStatus)Interlocked.CompareExchange(ref _connectionStatus, (int)value, (int)comparand);
|
return (MqttClientConnectionStatus)Interlocked.CompareExchange(ref _connectionStatus, (int)value, (int)comparand);
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task<MqttClientConnectResult> ConnectInternal(CancellationToken cancellationToken)
|
async Task<MqttClientConnectResult> ConnectInternal(IMqttChannelAdapter channelAdapter, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var backgroundCancellationToken = _mqttClientAlive.Token;
|
var backgroundCancellationToken = _mqttClientAlive.Token;
|
||||||
|
|
||||||
using (var effectiveCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(backgroundCancellationToken, cancellationToken))
|
using (var effectiveCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(backgroundCancellationToken, cancellationToken))
|
||||||
{
|
{
|
||||||
_logger.Verbose("Trying to connect with server '{0}'", Options.ChannelOptions);
|
_logger.Verbose("Trying to connect with server '{0}'", Options.ChannelOptions);
|
||||||
await _adapter.ConnectAsync(effectiveCancellationToken.Token).ConfigureAwait(false);
|
await channelAdapter.ConnectAsync(effectiveCancellationToken.Token).ConfigureAwait(false);
|
||||||
_logger.Verbose("Connection with server established");
|
_logger.Verbose("Connection with server established");
|
||||||
|
|
||||||
_publishPacketReceiverQueue?.Dispose();
|
_publishPacketReceiverQueue?.Dispose();
|
||||||
_publishPacketReceiverQueue = new AsyncQueue<MqttPublishPacket>();
|
_publishPacketReceiverQueue = new AsyncQueue<MqttPublishPacket>();
|
||||||
|
|
||||||
_publishPacketReceiverTask = Task.Run(() => ProcessReceivedPublishPackets(backgroundCancellationToken), backgroundCancellationToken);
|
var connectResult = await Authenticate(channelAdapter, Options, effectiveCancellationToken.Token).ConfigureAwait(false);
|
||||||
_packetReceiverTask = Task.Run(() => TryReceivePacketsAsync(backgroundCancellationToken), backgroundCancellationToken);
|
if (connectResult.ResultCode == MqttClientConnectResultCode.Success)
|
||||||
|
{
|
||||||
|
_publishPacketReceiverTask = Task.Run(() => ProcessReceivedPublishPackets(backgroundCancellationToken), backgroundCancellationToken);
|
||||||
|
_packetReceiverTask = Task.Run(() => ReceivePacketsLoop(backgroundCancellationToken), backgroundCancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
return await AuthenticateAsync(Options, effectiveCancellationToken.Token).ConfigureAwait(false);
|
return connectResult;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task DisconnectCoreAsync(Task sender, Exception exception, MqttClientConnectResult connectResult, bool clientWasConnected)
|
async Task DisconnectCore(Task sender, Exception exception, MqttClientConnectResult connectResult, bool clientWasConnected)
|
||||||
{
|
{
|
||||||
TryInitiateDisconnect();
|
TryInitiateDisconnect();
|
||||||
|
|
||||||
@@ -527,7 +576,7 @@ namespace MQTTnet.Client
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_packetDispatcher.Dispose(new MqttClientDisconnectedException(exception));
|
_packetDispatcher?.Dispose(new MqttClientDisconnectedException(exception));
|
||||||
|
|
||||||
var receiverTask = _packetReceiverTask.WaitAsync(sender, _logger);
|
var receiverTask = _packetReceiverTask.WaitAsync(sender, _logger);
|
||||||
var publishPacketReceiverTask = _publishPacketReceiverTask.WaitAsync(sender, _logger);
|
var publishPacketReceiverTask = _publishPacketReceiverTask.WaitAsync(sender, _logger);
|
||||||
@@ -555,22 +604,19 @@ namespace MQTTnet.Client
|
|||||||
_disconnectUserProperties,
|
_disconnectUserProperties,
|
||||||
exception);
|
exception);
|
||||||
|
|
||||||
// This handler must be executed in a new thread because otherwise a dead lock may happen
|
// This handler must be executed in a new thread to prevent a deadlock
|
||||||
// when trying to reconnect in that handler etc.
|
// that may occur when attempting to reconnect within that handler, etc.
|
||||||
Task.Run(() => _disconnectedEvent.InvokeAsync(eventArgs)).RunInBackground(_logger);
|
Task.Run(() => _events.DisconnectedEvent.InvokeAsync(eventArgs)).RunInBackground(_logger);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Task DisconnectInternalAsync(Task sender, Exception exception, MqttClientConnectResult connectResult)
|
Task DisconnectInternal(Task sender, Exception exception, MqttClientConnectResult connectResult)
|
||||||
{
|
{
|
||||||
var clientWasConnected = IsConnected;
|
var clientWasConnected = IsConnected;
|
||||||
|
|
||||||
if (!DisconnectIsPendingOrFinished())
|
return !DisconnectIsPendingOrFinished() ?
|
||||||
{
|
DisconnectCore(sender, exception, connectResult, clientWasConnected)
|
||||||
return DisconnectCoreAsync(sender, exception, connectResult, clientWasConnected);
|
: CompletedTask.Instance;
|
||||||
}
|
|
||||||
|
|
||||||
return CompletedTask.Instance;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool DisconnectIsPendingOrFinished()
|
bool DisconnectIsPendingOrFinished()
|
||||||
@@ -612,24 +658,30 @@ namespace MQTTnet.Client
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task<MqttApplicationMessageReceivedEventArgs> HandleReceivedApplicationMessageAsync(MqttPublishPacket publishPacket)
|
async Task<MqttApplicationMessageReceivedEventArgs> HandleReceivedApplicationMessage(MqttPublishPacket publishPacket)
|
||||||
{
|
{
|
||||||
var applicationMessage = MqttApplicationMessageFactory.Create(publishPacket);
|
var applicationMessage = MqttApplicationMessageFactory.Create(publishPacket);
|
||||||
var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options.ClientId, applicationMessage, publishPacket, AcknowledgeReceivedPublishPacket);
|
var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options.ClientId, applicationMessage, publishPacket, AcknowledgeReceivedPublishPacket);
|
||||||
await _applicationMessageReceivedEvent.InvokeAsync(eventArgs).ConfigureAwait(false);
|
await _events.ApplicationMessageReceivedEvent.InvokeAsync(eventArgs).ConfigureAwait(false);
|
||||||
|
|
||||||
return eventArgs;
|
return eventArgs;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Task OnConnected(MqttClientConnectResult connectResult)
|
||||||
|
{
|
||||||
|
if (!_events.ConnectedEvent.HasHandlers)
|
||||||
|
{
|
||||||
|
return CompletedTask.Instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
var eventArgs = new MqttClientConnectedEventArgs(connectResult);
|
||||||
|
return _events.ConnectedEvent.InvokeAsync(eventArgs);
|
||||||
|
}
|
||||||
|
|
||||||
Task ProcessReceivedAuthPacket(MqttAuthPacket authPacket)
|
Task ProcessReceivedAuthPacket(MqttAuthPacket authPacket)
|
||||||
{
|
{
|
||||||
var extendedAuthenticationExchangeHandler = Options.ExtendedAuthenticationExchangeHandler;
|
var extendedAuthenticationExchangeHandler = Options.ExtendedAuthenticationExchangeHandler;
|
||||||
if (extendedAuthenticationExchangeHandler != null)
|
return extendedAuthenticationExchangeHandler != null ? extendedAuthenticationExchangeHandler.HandleRequestAsync(new MqttExtendedAuthenticationExchangeContext(authPacket, this)) : CompletedTask.Instance;
|
||||||
{
|
|
||||||
return extendedAuthenticationExchangeHandler.HandleRequestAsync(new MqttExtendedAuthenticationExchangeContext(authPacket, this));
|
|
||||||
}
|
|
||||||
|
|
||||||
return CompletedTask.Instance;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Task ProcessReceivedDisconnectPacket(MqttDisconnectPacket disconnectPacket)
|
Task ProcessReceivedDisconnectPacket(MqttDisconnectPacket disconnectPacket)
|
||||||
@@ -637,11 +689,12 @@ namespace MQTTnet.Client
|
|||||||
_disconnectReason = (int)disconnectPacket.ReasonCode;
|
_disconnectReason = (int)disconnectPacket.ReasonCode;
|
||||||
_disconnectReasonString = disconnectPacket.ReasonString;
|
_disconnectReasonString = disconnectPacket.ReasonString;
|
||||||
_disconnectUserProperties = disconnectPacket.UserProperties;
|
_disconnectUserProperties = disconnectPacket.UserProperties;
|
||||||
|
_unexpectedDisconnectPacket = disconnectPacket;
|
||||||
|
|
||||||
// Also dispatch disconnect to waiting threads to generate a proper exception.
|
// Also dispatch disconnect to waiting threads to generate a proper exception.
|
||||||
_packetDispatcher.Dispose(new MqttClientUnexpectedDisconnectReceivedException(disconnectPacket));
|
_packetDispatcher.Dispose(new MqttClientUnexpectedDisconnectReceivedException(disconnectPacket, null));
|
||||||
|
|
||||||
return DisconnectInternalAsync(_packetReceiverTask, null, null);
|
return DisconnectInternal(_packetReceiverTask, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task ProcessReceivedPublishPackets(CancellationToken cancellationToken)
|
async Task ProcessReceivedPublishPackets(CancellationToken cancellationToken)
|
||||||
@@ -657,72 +710,169 @@ namespace MQTTnet.Client
|
|||||||
}
|
}
|
||||||
|
|
||||||
var publishPacket = publishPacketDequeueResult.Item;
|
var publishPacket = publishPacketDequeueResult.Item;
|
||||||
var eventArgs = await HandleReceivedApplicationMessageAsync(publishPacket).ConfigureAwait(false);
|
var eventArgs = await HandleReceivedApplicationMessage(publishPacket).ConfigureAwait(false);
|
||||||
|
|
||||||
if (eventArgs.AutoAcknowledge)
|
if (eventArgs.AutoAcknowledge)
|
||||||
{
|
{
|
||||||
await eventArgs.AcknowledgeAsync(cancellationToken).ConfigureAwait(false);
|
await eventArgs.AcknowledgeAsync(cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
catch (ObjectDisposedException)
|
||||||
|
{
|
||||||
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
_logger.Error(exception, "Error while handling application message.");
|
_logger.Error(exception, "Error while handling application message");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Task ProcessReceivedPubRecPacket(MqttPubRecPacket pubRecPacket, CancellationToken cancellationToken)
|
Task ProcessReceivedPubRecPacket(MqttPubRecPacket pubRecPacket, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
if (!_packetDispatcher.TryDispatch(pubRecPacket))
|
if (_packetDispatcher.TryDispatch(pubRecPacket))
|
||||||
{
|
{
|
||||||
// The packet is unknown. Probably due to a restart of the client.
|
return CompletedTask.Instance;
|
||||||
// So wen send this to the server to trigger a full resend of the message.
|
|
||||||
var pubRelPacket = MqttPacketFactories.PubRel.Create(pubRecPacket, MqttApplicationMessageReceivedReasonCode.PacketIdentifierNotFound);
|
|
||||||
return SendAsync(pubRelPacket, cancellationToken);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return CompletedTask.Instance;
|
// The packet is unknown, probably due to a restart of the client.
|
||||||
|
// So we send this to the server to trigger a full resend of the message.
|
||||||
|
var pubRelPacket = MqttPacketFactories.PubRel.Create(pubRecPacket, MqttApplicationMessageReceivedReasonCode.PacketIdentifierNotFound);
|
||||||
|
return Send(pubRelPacket, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken)
|
Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var pubCompPacket = MqttPacketFactories.PubComp.Create(pubRelPacket, MqttApplicationMessageReceivedReasonCode.Success);
|
var pubCompPacket = MqttPacketFactories.PubComp.Create(pubRelPacket, MqttApplicationMessageReceivedReasonCode.Success);
|
||||||
return SendAsync(pubCompPacket, cancellationToken);
|
return Send(pubCompPacket, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task<MqttClientPublishResult> PublishAtLeastOnceAsync(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
|
async Task<MqttClientPublishResult> PublishAtLeastOnce(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
|
publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
|
||||||
|
|
||||||
var pubAckPacket = await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket, cancellationToken).ConfigureAwait(false);
|
var pubAckPacket = await Request<MqttPubAckPacket>(publishPacket, cancellationToken).ConfigureAwait(false);
|
||||||
return _clientPublishResultFactory.Create(pubAckPacket);
|
return MqttClientResultFactory.PublishResult.Create(pubAckPacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task<MqttClientPublishResult> PublishAtMostOnce(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
|
async Task<MqttClientPublishResult> PublishAtMostOnce(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
|
try
|
||||||
await SendAsync(publishPacket, cancellationToken).ConfigureAwait(false);
|
{
|
||||||
|
// No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
|
||||||
|
await Send(publishPacket, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
return _clientPublishResultFactory.Create(null);
|
return MqttClientResultFactory.PublishResult.Create(null);
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
// We have to check if the server has sent a disconnect packet in response to the published message.
|
||||||
|
// Since we are in QoS 0 we do not get a direct response via an PUBACK packet and thus basically no
|
||||||
|
// feedback at all.
|
||||||
|
var localUnexpectedDisconnectPacket = _unexpectedDisconnectPacket;
|
||||||
|
|
||||||
|
if (localUnexpectedDisconnectPacket != null)
|
||||||
|
{
|
||||||
|
throw new MqttClientUnexpectedDisconnectReceivedException(localUnexpectedDisconnectPacket, exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task<MqttClientPublishResult> PublishExactlyOnceAsync(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
|
async Task<MqttClientPublishResult> PublishExactlyOnce(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
|
publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
|
||||||
|
|
||||||
var pubRecPacket = await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket, cancellationToken).ConfigureAwait(false);
|
var pubRecPacket = await Request<MqttPubRecPacket>(publishPacket, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
var pubRelPacket = MqttPacketFactories.PubRel.Create(pubRecPacket, MqttApplicationMessageReceivedReasonCode.Success);
|
var pubRelPacket = MqttPacketFactories.PubRel.Create(pubRecPacket, MqttApplicationMessageReceivedReasonCode.Success);
|
||||||
|
|
||||||
var pubCompPacket = await SendAndReceiveAsync<MqttPubCompPacket>(pubRelPacket, cancellationToken).ConfigureAwait(false);
|
var pubCompPacket = await Request<MqttPubCompPacket>(pubRelPacket, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
return _clientPublishResultFactory.Create(pubRecPacket, pubCompPacket);
|
return MqttClientResultFactory.PublishResult.Create(pubRecPacket, pubCompPacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttPacket requestPacket, CancellationToken cancellationToken) where TResponsePacket : MqttPacket
|
async Task<MqttPacket> Receive(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var packetTask = _adapter.ReceivePacketAsync(cancellationToken);
|
||||||
|
|
||||||
|
MqttPacket packet;
|
||||||
|
if (packetTask.IsCompleted)
|
||||||
|
{
|
||||||
|
packet = packetTask.Result;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
packet = await packetTask.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
async Task ReceivePacketsLoop(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.Verbose("Start receiving packets");
|
||||||
|
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var packet = await Receive(cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (packet == null)
|
||||||
|
{
|
||||||
|
await DisconnectInternal(_packetReceiverTask, null, null).ConfigureAwait(false);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await TryProcessReceivedPacket(packet, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
if (_cleanDisconnectInitiated)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exception is AggregateException aggregateException)
|
||||||
|
{
|
||||||
|
exception = aggregateException.GetBaseException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exception is OperationCanceledException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
else if (exception is MqttCommunicationException)
|
||||||
|
{
|
||||||
|
_logger.Warning(exception, "Communication error while receiving packets");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.Error(exception, "Error while receiving packets");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The packet dispatcher is set to null when the client is being disposed so it may already being gone!
|
||||||
|
_packetDispatcher?.FailAll(exception);
|
||||||
|
|
||||||
|
await DisconnectInternal(_packetReceiverTask, exception, null).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_logger.Verbose("Stopped receiving packets");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async Task<TResponsePacket> Request<TResponsePacket>(MqttPacket requestPacket, CancellationToken cancellationToken) where TResponsePacket : MqttPacket
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
@@ -736,11 +886,11 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await SendAsync(requestPacket, cancellationToken).ConfigureAwait(false);
|
await Send(requestPacket, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
_logger.Warning(exception, "Error when sending request packet ({0}).", requestPacket.GetType().Name);
|
_logger.Warning(exception, "Error when sending {0} request packet", requestPacket.GetType().Name);
|
||||||
packetAwaitable.Fail(exception);
|
packetAwaitable.Fail(exception);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -752,7 +902,7 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
if (exception is MqttCommunicationTimedOutException)
|
if (exception is MqttCommunicationTimedOutException)
|
||||||
{
|
{
|
||||||
_logger.Warning("Timeout while waiting for response packet ({0}).", typeof(TResponsePacket).Name);
|
_logger.Warning("Timeout while waiting for {0} response packet", typeof(TResponsePacket).Name);
|
||||||
}
|
}
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
@@ -760,7 +910,7 @@ namespace MQTTnet.Client
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Task SendAsync(MqttPacket packet, CancellationToken cancellationToken)
|
Task Send(MqttPacket packet, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
@@ -805,7 +955,7 @@ namespace MQTTnet.Client
|
|||||||
|
|
||||||
static void ThrowNotConnected()
|
static void ThrowNotConnected()
|
||||||
{
|
{
|
||||||
throw new MqttCommunicationException("The client is not connected.");
|
throw new MqttClientNotConnectedException();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TryInitiateDisconnect()
|
void TryInitiateDisconnect()
|
||||||
@@ -818,48 +968,45 @@ namespace MQTTnet.Client
|
|||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
_logger.Warning(exception, "Error while initiating disconnect.");
|
_logger.Warning(exception, "Error while initiating disconnect");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task TryProcessReceivedPacketAsync(MqttPacket packet, CancellationToken cancellationToken)
|
async Task TryProcessReceivedPacket(MqttPacket packet, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (packet is MqttPublishPacket publishPacket)
|
switch (packet)
|
||||||
{
|
{
|
||||||
EnqueueReceivedPublishPacket(publishPacket);
|
case MqttPublishPacket publishPacket:
|
||||||
}
|
EnqueueReceivedPublishPacket(publishPacket);
|
||||||
else if (packet is MqttPubRecPacket pubRecPacket)
|
break;
|
||||||
{
|
case MqttPubRecPacket pubRecPacket:
|
||||||
await ProcessReceivedPubRecPacket(pubRecPacket, cancellationToken).ConfigureAwait(false);
|
await ProcessReceivedPubRecPacket(pubRecPacket, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
break;
|
||||||
else if (packet is MqttPubRelPacket pubRelPacket)
|
case MqttPubRelPacket pubRelPacket:
|
||||||
{
|
await ProcessReceivedPubRelPacket(pubRelPacket, cancellationToken).ConfigureAwait(false);
|
||||||
await ProcessReceivedPubRelPacket(pubRelPacket, cancellationToken).ConfigureAwait(false);
|
break;
|
||||||
}
|
case MqttDisconnectPacket disconnectPacket:
|
||||||
else if (packet is MqttDisconnectPacket disconnectPacket)
|
await ProcessReceivedDisconnectPacket(disconnectPacket).ConfigureAwait(false);
|
||||||
{
|
break;
|
||||||
await ProcessReceivedDisconnectPacket(disconnectPacket).ConfigureAwait(false);
|
case MqttAuthPacket authPacket:
|
||||||
}
|
await ProcessReceivedAuthPacket(authPacket).ConfigureAwait(false);
|
||||||
else if (packet is MqttAuthPacket authPacket)
|
break;
|
||||||
{
|
case MqttPingRespPacket _:
|
||||||
await ProcessReceivedAuthPacket(authPacket).ConfigureAwait(false);
|
_packetDispatcher.TryDispatch(packet);
|
||||||
}
|
break;
|
||||||
else if (packet is MqttPingRespPacket)
|
case MqttPingReqPacket _:
|
||||||
{
|
throw new MqttProtocolViolationException("The PINGREQ Packet is sent from a client to the server only.");
|
||||||
_packetDispatcher.TryDispatch(packet);
|
default:
|
||||||
}
|
|
||||||
else if (packet is MqttPingReqPacket)
|
|
||||||
{
|
|
||||||
throw new MqttProtocolViolationException("The PINGREQ Packet is sent from a Client to the Server only.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (!_packetDispatcher.TryDispatch(packet))
|
|
||||||
{
|
{
|
||||||
throw new MqttProtocolViolationException($"Received packet '{packet}' at an unexpected time.");
|
if (!_packetDispatcher.TryDispatch(packet))
|
||||||
|
{
|
||||||
|
throw new MqttProtocolViolationException($"Received packet '{packet}' at an unexpected time.");
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -870,98 +1017,30 @@ namespace MQTTnet.Client
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (exception is OperationCanceledException)
|
switch (exception)
|
||||||
{
|
{
|
||||||
}
|
case OperationCanceledException _:
|
||||||
else if (exception is MqttCommunicationException)
|
break;
|
||||||
{
|
case MqttCommunicationException _:
|
||||||
_logger.Warning(exception, "Communication error while receiving packets.");
|
_logger.Warning(exception, "Communication error while receiving packets");
|
||||||
}
|
break;
|
||||||
else
|
default:
|
||||||
{
|
_logger.Error(exception, "Error while processing received {0} packet", packet.GetType().Name);
|
||||||
_logger.Error(exception, $"Error while processing received packet ({packet.GetType().Name}).");
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
_packetDispatcher.FailAll(exception);
|
// The packet dispatcher may already be gone due to disconnect etc.!
|
||||||
|
_packetDispatcher?.FailAll(exception);
|
||||||
|
|
||||||
await DisconnectInternalAsync(_packetReceiverTask, exception, null).ConfigureAwait(false);
|
await DisconnectInternal(_packetReceiverTask, exception, null).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async Task TryReceivePacketsAsync(CancellationToken cancellationToken)
|
async Task TrySendKeepAliveMessages(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_logger.Verbose("Start receiving packets.");
|
_logger.Verbose("Start sending keep alive packets");
|
||||||
|
|
||||||
while (!cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
MqttPacket packet;
|
|
||||||
var packetTask = _adapter.ReceivePacketAsync(cancellationToken);
|
|
||||||
|
|
||||||
if (packetTask.IsCompleted)
|
|
||||||
{
|
|
||||||
packet = packetTask.Result;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
packet = await packetTask.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (packet == null)
|
|
||||||
{
|
|
||||||
await DisconnectInternalAsync(_packetReceiverTask, null, null).ConfigureAwait(false);
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await TryProcessReceivedPacketAsync(packet, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception exception)
|
|
||||||
{
|
|
||||||
if (_cleanDisconnectInitiated)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (exception is AggregateException aggregateException)
|
|
||||||
{
|
|
||||||
exception = aggregateException.GetBaseException();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (exception is OperationCanceledException)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
else if (exception is MqttCommunicationException)
|
|
||||||
{
|
|
||||||
_logger.Warning(exception, "Communication error while receiving packets.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_logger.Error(exception, "Error while receiving packets.");
|
|
||||||
}
|
|
||||||
|
|
||||||
_packetDispatcher.FailAll(exception);
|
|
||||||
|
|
||||||
await DisconnectInternalAsync(_packetReceiverTask, exception, null).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_logger.Verbose("Stopped receiving packets.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async Task TrySendKeepAliveMessagesAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_logger.Verbose("Start sending keep alive packets.");
|
|
||||||
|
|
||||||
var keepAlivePeriod = Options.KeepAlivePeriod;
|
var keepAlivePeriod = Options.KeepAlivePeriod;
|
||||||
|
|
||||||
@@ -993,24 +1072,23 @@ namespace MQTTnet.Client
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (exception is OperationCanceledException)
|
switch (exception)
|
||||||
{
|
{
|
||||||
return;
|
case OperationCanceledException _:
|
||||||
}
|
return;
|
||||||
else if (exception is MqttCommunicationException)
|
case MqttCommunicationException _:
|
||||||
{
|
_logger.Warning(exception, "Communication error while sending/receiving keep alive packets");
|
||||||
_logger.Warning(exception, "Communication error while sending/receiving keep alive packets.");
|
break;
|
||||||
}
|
default:
|
||||||
else
|
_logger.Error(exception, "Error exception while sending/receiving keep alive packets");
|
||||||
{
|
break;
|
||||||
_logger.Error(exception, "Error exception while sending/receiving keep alive packets.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await DisconnectInternalAsync(_keepAlivePacketsSenderTask, exception, null).ConfigureAwait(false);
|
await DisconnectInternal(_keepAlivePacketsSenderTask, exception, null).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
_logger.Verbose("Stopped sending keep alive packets.");
|
_logger.Verbose("Stopped sending keep alive packets");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
|
||||||
|
namespace MQTTnet.Client
|
||||||
|
{
|
||||||
|
public sealed class DefaultMqttCertificatesProvider : IMqttClientCertificatesProvider
|
||||||
|
{
|
||||||
|
readonly X509Certificate2Collection _certificates;
|
||||||
|
|
||||||
|
public DefaultMqttCertificatesProvider(X509Certificate2Collection certificates)
|
||||||
|
{
|
||||||
|
_certificates = certificates;
|
||||||
|
}
|
||||||
|
|
||||||
|
public DefaultMqttCertificatesProvider(IEnumerable<X509Certificate> certificates)
|
||||||
|
{
|
||||||
|
if (certificates != null)
|
||||||
|
{
|
||||||
|
_certificates = new X509Certificate2Collection();
|
||||||
|
foreach (var certificate in certificates)
|
||||||
|
{
|
||||||
|
_certificates.Add(certificate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public X509CertificateCollection GetCertificates()
|
||||||
|
{
|
||||||
|
return _certificates;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
namespace MQTTnet.Client
|
||||||
|
{
|
||||||
|
public interface IMqttClientCertificatesProvider
|
||||||
|
{
|
||||||
|
System.Security.Cryptography.X509Certificates.X509CertificateCollection GetCertificates();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
|
||||||
|
namespace MQTTnet.Client
|
||||||
|
{
|
||||||
|
public sealed class MqttClientCertificateSelectionEventArgs : EventArgs
|
||||||
|
{
|
||||||
|
public MqttClientCertificateSelectionEventArgs(
|
||||||
|
string targetHost,
|
||||||
|
X509CertificateCollection localCertificates,
|
||||||
|
X509Certificate remoteCertificate,
|
||||||
|
string[] acceptableIssuers,
|
||||||
|
MqttClientTcpOptions tcpOptions)
|
||||||
|
{
|
||||||
|
TargetHost = targetHost;
|
||||||
|
LocalCertificates = localCertificates;
|
||||||
|
RemoveCertificate = remoteCertificate;
|
||||||
|
AcceptableIssuers = acceptableIssuers;
|
||||||
|
TcpOptions = tcpOptions ?? throw new ArgumentNullException(nameof(tcpOptions));
|
||||||
|
}
|
||||||
|
|
||||||
|
public string[] AcceptableIssuers { get; }
|
||||||
|
|
||||||
|
public X509CertificateCollection LocalCertificates { get; }
|
||||||
|
|
||||||
|
public X509Certificate RemoveCertificate { get; }
|
||||||
|
|
||||||
|
public string TargetHost { get; }
|
||||||
|
|
||||||
|
public MqttClientTcpOptions TcpOptions { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,12 +10,27 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
public sealed class MqttClientCertificateValidationEventArgs : EventArgs
|
public sealed class MqttClientCertificateValidationEventArgs : EventArgs
|
||||||
{
|
{
|
||||||
public X509Certificate Certificate { get; set; }
|
public MqttClientCertificateValidationEventArgs(X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors, IMqttClientChannelOptions clientOptions)
|
||||||
|
{
|
||||||
|
Certificate = certificate;
|
||||||
|
Chain = chain;
|
||||||
|
SslPolicyErrors = sslPolicyErrors;
|
||||||
|
ClientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
|
||||||
|
}
|
||||||
|
|
||||||
public X509Chain Chain { get; set; }
|
public X509Certificate Certificate { get; }
|
||||||
|
|
||||||
public SslPolicyErrors SslPolicyErrors { get; set; }
|
public X509Chain Chain { get; }
|
||||||
|
|
||||||
public IMqttClientChannelOptions ClientOptions { get; set; }
|
public IMqttClientChannelOptions ClientOptions { get; }
|
||||||
|
|
||||||
|
#if NET452 || NET461 || NET48
|
||||||
|
/// <summary>
|
||||||
|
/// Can be a host string name or an object derived from WebRequest.
|
||||||
|
/// </summary>
|
||||||
|
public object Sender { get; set; }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
public SslPolicyErrors SslPolicyErrors { get; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,6 +12,14 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
public sealed class MqttClientOptions
|
public sealed class MqttClientOptions
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Usually the MQTT packets can be send partially. This is done by using multiple TCP packets
|
||||||
|
/// or WebSocket frames etc. Unfortunately not all brokers (like Amazon Web Services (AWS)) do support this feature and
|
||||||
|
/// will close the connection when receiving such packets. If such a service is used this flag must
|
||||||
|
/// be set to _false_.
|
||||||
|
/// </summary>
|
||||||
|
public bool AllowPacketFragmentation { get; set; } = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the authentication data.
|
/// Gets or sets the authentication data.
|
||||||
/// <remarks>MQTT 5.0.0+ feature.</remarks>
|
/// <remarks>MQTT 5.0.0+ feature.</remarks>
|
||||||
@@ -24,14 +32,6 @@ namespace MQTTnet.Client
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public string AuthenticationMethod { get; set; }
|
public string AuthenticationMethod { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Usually the MQTT packets can be send partially. This is done by using multiple TCP packets
|
|
||||||
/// or WebSocket frames etc. Unfortunately not all brokers (like Amazon Web Services (AWS)) do support this feature and
|
|
||||||
/// will close the connection when receiving such packets. If such a service is used this flag must
|
|
||||||
/// be set to _false_.
|
|
||||||
/// </summary>
|
|
||||||
public bool AllowPacketFragmentation { get; set; } = true;
|
|
||||||
|
|
||||||
public IMqttClientChannelOptions ChannelOptions { get; set; }
|
public IMqttClientChannelOptions ChannelOptions { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -100,6 +100,11 @@ namespace MQTTnet.Client
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public uint SessionExpiryInterval { get; set; }
|
public uint SessionExpiryInterval { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets whether an exception should be thrown when the server has sent a non success ACK packet.
|
||||||
|
/// </summary>
|
||||||
|
public bool ThrowOnNonSuccessfulConnectResponse { get; set; } = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the timeout which will be applied at socket level and internal operations.
|
/// Gets or sets the timeout which will be applied at socket level and internal operations.
|
||||||
/// The default value is the same as for sockets in .NET in general.
|
/// The default value is the same as for sockets in .NET in general.
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
// Licensed to the .NET Foundation under one or more agreements.
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
// The .NET Foundation licenses this file to you under the MIT license.
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
#pragma warning disable CS0612 // Type or member is obsolete
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Sockets;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
using MQTTnet.Packets;
|
using MQTTnet.Packets;
|
||||||
@@ -15,10 +19,16 @@ namespace MQTTnet.Client
|
|||||||
public sealed class MqttClientOptionsBuilder
|
public sealed class MqttClientOptionsBuilder
|
||||||
{
|
{
|
||||||
readonly MqttClientOptions _options = new MqttClientOptions();
|
readonly MqttClientOptions _options = new MqttClientOptions();
|
||||||
MqttClientWebSocketProxyOptions _proxyOptions;
|
int? _port;
|
||||||
|
|
||||||
|
[Obsolete] MqttClientWebSocketProxyOptions _proxyOptions;
|
||||||
|
EndPoint _remoteEndPoint;
|
||||||
|
|
||||||
MqttClientTcpOptions _tcpOptions;
|
MqttClientTcpOptions _tcpOptions;
|
||||||
MqttClientOptionsBuilderTlsParameters _tlsParameters;
|
MqttClientTlsOptions _tlsOptions;
|
||||||
|
|
||||||
|
[Obsolete] MqttClientOptionsBuilderTlsParameters _tlsParameters;
|
||||||
|
|
||||||
MqttClientWebSocketOptions _webSocketOptions;
|
MqttClientWebSocketOptions _webSocketOptions;
|
||||||
|
|
||||||
public MqttClientOptions Build()
|
public MqttClientOptions Build()
|
||||||
@@ -28,11 +38,17 @@ namespace MQTTnet.Client
|
|||||||
throw new InvalidOperationException("A channel must be set.");
|
throw new InvalidOperationException("A channel must be set.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The user can specify the TCP options with already configured TLS options
|
||||||
|
// or start with TLS settings not knowing which transport will be used (depending
|
||||||
|
// on the order of called methods from the builder).
|
||||||
|
// The builder prefers the explicitly set TLS options!
|
||||||
|
var tlsOptions = _tlsOptions ?? _tcpOptions?.TlsOptions;
|
||||||
|
|
||||||
if (_tlsParameters != null)
|
if (_tlsParameters != null)
|
||||||
{
|
{
|
||||||
if (_tlsParameters?.UseTls == true)
|
if (_tlsParameters?.UseTls == true)
|
||||||
{
|
{
|
||||||
var tlsOptions = new MqttClientTlsOptions
|
tlsOptions = new MqttClientTlsOptions
|
||||||
{
|
{
|
||||||
UseTls = true,
|
UseTls = true,
|
||||||
SslProtocol = _tlsParameters.SslProtocol,
|
SslProtocol = _tlsParameters.SslProtocol,
|
||||||
@@ -40,26 +56,46 @@ namespace MQTTnet.Client
|
|||||||
CertificateValidationHandler = _tlsParameters.CertificateValidationHandler,
|
CertificateValidationHandler = _tlsParameters.CertificateValidationHandler,
|
||||||
IgnoreCertificateChainErrors = _tlsParameters.IgnoreCertificateChainErrors,
|
IgnoreCertificateChainErrors = _tlsParameters.IgnoreCertificateChainErrors,
|
||||||
IgnoreCertificateRevocationErrors = _tlsParameters.IgnoreCertificateRevocationErrors,
|
IgnoreCertificateRevocationErrors = _tlsParameters.IgnoreCertificateRevocationErrors,
|
||||||
#if WINDOWS_UWP
|
ClientCertificatesProvider = _tlsParameters.CertificatesProvider,
|
||||||
Certificates = _tlsParameters.Certificates?.Select(c => c.ToArray()).ToList(),
|
|
||||||
#else
|
|
||||||
Certificates = _tlsParameters.Certificates?.ToList(),
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if NETCOREAPP3_1_OR_GREATER
|
#if NETCOREAPP3_1_OR_GREATER
|
||||||
ApplicationProtocols = _tlsParameters.ApplicationProtocols,
|
ApplicationProtocols = _tlsParameters.ApplicationProtocols,
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (_tcpOptions != null)
|
if (_tcpOptions != null)
|
||||||
|
{
|
||||||
|
_tcpOptions.TlsOptions = tlsOptions;
|
||||||
|
|
||||||
|
if (_remoteEndPoint == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("No endpoint is set.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_remoteEndPoint is DnsEndPoint dns)
|
||||||
|
{
|
||||||
|
if (dns.Port == 0)
|
||||||
{
|
{
|
||||||
_tcpOptions.TlsOptions = tlsOptions;
|
if (_port.HasValue)
|
||||||
}
|
{
|
||||||
else if (_webSocketOptions != null)
|
_remoteEndPoint = new DnsEndPoint(dns.Host, _port.Value);
|
||||||
{
|
}
|
||||||
_webSocketOptions.TlsOptions = tlsOptions;
|
else
|
||||||
|
{
|
||||||
|
_remoteEndPoint = new DnsEndPoint(dns.Host, tlsOptions?.UseTls == false ? MqttPorts.Default : MqttPorts.Secure);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (_tcpOptions.RemoteEndpoint == null)
|
||||||
|
{
|
||||||
|
_tcpOptions.RemoteEndpoint = _remoteEndPoint;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (_webSocketOptions != null)
|
||||||
|
{
|
||||||
|
_webSocketOptions.TlsOptions = tlsOptions;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_proxyOptions != null)
|
if (_proxyOptions != null)
|
||||||
@@ -79,6 +115,12 @@ namespace MQTTnet.Client
|
|||||||
return _options;
|
return _options;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithAddressFamily(AddressFamily addressFamily)
|
||||||
|
{
|
||||||
|
_tcpOptions.AddressFamily = addressFamily;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public MqttClientOptionsBuilder WithAuthentication(string method, byte[] data)
|
public MqttClientOptionsBuilder WithAuthentication(string method, byte[] data)
|
||||||
{
|
{
|
||||||
_options.AuthenticationMethod = method;
|
_options.AuthenticationMethod = method;
|
||||||
@@ -110,6 +152,7 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithTcpServer(... configure) or WithWebSocketServer(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithConnectionUri(Uri uri)
|
public MqttClientOptionsBuilder WithConnectionUri(Uri uri)
|
||||||
{
|
{
|
||||||
if (uri == null)
|
if (uri == null)
|
||||||
@@ -126,12 +169,16 @@ namespace MQTTnet.Client
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case "mqtts":
|
case "mqtts":
|
||||||
WithTcpServer(uri.Host, port).WithTls();
|
WithTcpServer(uri.Host, port)
|
||||||
|
.WithTlsOptions(
|
||||||
|
o =>
|
||||||
|
{
|
||||||
|
});
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "ws":
|
case "ws":
|
||||||
case "wss":
|
case "wss":
|
||||||
WithWebSocketServer(uri.ToString());
|
WithWebSocketServer(o => o.WithUri(uri.ToString()));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -149,6 +196,7 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithTcpServer(... configure) or WithWebSocketServer(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithConnectionUri(string uri)
|
public MqttClientOptionsBuilder WithConnectionUri(string uri)
|
||||||
{
|
{
|
||||||
return WithConnectionUri(new Uri(uri, UriKind.Absolute));
|
return WithConnectionUri(new Uri(uri, UriKind.Absolute));
|
||||||
@@ -177,6 +225,14 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithEndPoint(EndPoint endPoint)
|
||||||
|
{
|
||||||
|
_remoteEndPoint = endPoint ?? throw new ArgumentNullException(nameof(endPoint));
|
||||||
|
_tcpOptions = new MqttClientTcpOptions();
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public MqttClientOptionsBuilder WithExtendedAuthenticationExchangeHandler(IMqttExtendedAuthenticationExchangeHandler handler)
|
public MqttClientOptionsBuilder WithExtendedAuthenticationExchangeHandler(IMqttExtendedAuthenticationExchangeHandler handler)
|
||||||
{
|
{
|
||||||
_options.ExtendedAuthenticationExchangeHandler = handler;
|
_options.ExtendedAuthenticationExchangeHandler = handler;
|
||||||
@@ -212,6 +268,22 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The client will not throw an exception when the MQTT server responds with a non success ACK packet.
|
||||||
|
/// This will become the default behavior in future versions of the library.
|
||||||
|
/// </summary>
|
||||||
|
public MqttClientOptionsBuilder WithoutThrowOnNonSuccessfulConnectResponse()
|
||||||
|
{
|
||||||
|
_options.ThrowOnNonSuccessfulConnectResponse = false;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithProtocolType(ProtocolType protocolType)
|
||||||
|
{
|
||||||
|
_tcpOptions.ProtocolType = protocolType;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public MqttClientOptionsBuilder WithProtocolVersion(MqttProtocolVersion value)
|
public MqttClientOptionsBuilder WithProtocolVersion(MqttProtocolVersion value)
|
||||||
{
|
{
|
||||||
if (value == MqttProtocolVersion.Unknown)
|
if (value == MqttProtocolVersion.Unknown)
|
||||||
@@ -223,6 +295,7 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithWebSocketServer(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithProxy(
|
public MqttClientOptionsBuilder WithProxy(
|
||||||
string address,
|
string address,
|
||||||
string username = null,
|
string username = null,
|
||||||
@@ -244,6 +317,7 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithWebSocketServer(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithProxy(Action<MqttClientWebSocketProxyOptions> optionsBuilder)
|
public MqttClientOptionsBuilder WithProxy(Action<MqttClientWebSocketProxyOptions> optionsBuilder)
|
||||||
{
|
{
|
||||||
if (optionsBuilder == null)
|
if (optionsBuilder == null)
|
||||||
@@ -282,11 +356,12 @@ namespace MQTTnet.Client
|
|||||||
|
|
||||||
public MqttClientOptionsBuilder WithTcpServer(string server, int? port = null)
|
public MqttClientOptionsBuilder WithTcpServer(string server, int? port = null)
|
||||||
{
|
{
|
||||||
_tcpOptions = new MqttClientTcpOptions
|
_tcpOptions = new MqttClientTcpOptions();
|
||||||
{
|
|
||||||
Server = server,
|
// The value 0 will be updated when building the options.
|
||||||
Port = port
|
// This a backward compatibility feature.
|
||||||
};
|
_remoteEndPoint = new DnsEndPoint(server, port ?? 0);
|
||||||
|
_port = port;
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -314,17 +389,20 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithTlsOptions(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithTls(MqttClientOptionsBuilderTlsParameters parameters)
|
public MqttClientOptionsBuilder WithTls(MqttClientOptionsBuilderTlsParameters parameters)
|
||||||
{
|
{
|
||||||
_tlsParameters = parameters;
|
_tlsParameters = parameters;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithTlsOptions(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithTls()
|
public MqttClientOptionsBuilder WithTls()
|
||||||
{
|
{
|
||||||
return WithTls(new MqttClientOptionsBuilderTlsParameters { UseTls = true });
|
return WithTls(new MqttClientOptionsBuilderTlsParameters { UseTls = true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithTlsOptions(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithTls(Action<MqttClientOptionsBuilderTlsParameters> optionsBuilder)
|
public MqttClientOptionsBuilder WithTls(Action<MqttClientOptionsBuilderTlsParameters> optionsBuilder)
|
||||||
{
|
{
|
||||||
if (optionsBuilder == null)
|
if (optionsBuilder == null)
|
||||||
@@ -341,6 +419,26 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithTlsOptions(MqttClientTlsOptions tlsOptions)
|
||||||
|
{
|
||||||
|
_tlsOptions = tlsOptions;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithTlsOptions(Action<MqttClientTlsOptionsBuilder> configure)
|
||||||
|
{
|
||||||
|
if (configure == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(configure));
|
||||||
|
}
|
||||||
|
|
||||||
|
var builder = new MqttClientTlsOptionsBuilder();
|
||||||
|
configure.Invoke(builder);
|
||||||
|
|
||||||
|
_tlsOptions = builder.Build();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public MqttClientOptionsBuilder WithTopicAliasMaximum(ushort topicAliasMaximum)
|
public MqttClientOptionsBuilder WithTopicAliasMaximum(ushort topicAliasMaximum)
|
||||||
{
|
{
|
||||||
_options.TopicAliasMaximum = topicAliasMaximum;
|
_options.TopicAliasMaximum = topicAliasMaximum;
|
||||||
@@ -372,6 +470,7 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithWebSocketServer(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithWebSocketServer(string uri, MqttClientOptionsBuilderWebSocketParameters parameters = null)
|
public MqttClientOptionsBuilder WithWebSocketServer(string uri, MqttClientOptionsBuilderWebSocketParameters parameters = null)
|
||||||
{
|
{
|
||||||
_webSocketOptions = new MqttClientWebSocketOptions
|
_webSocketOptions = new MqttClientWebSocketOptions
|
||||||
@@ -384,6 +483,21 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithWebSocketServer(Action<MqttClientWebSocketOptionsBuilder> configure)
|
||||||
|
{
|
||||||
|
if (configure == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(configure));
|
||||||
|
}
|
||||||
|
|
||||||
|
var webSocketOptionsBuilder = new MqttClientWebSocketOptionsBuilder();
|
||||||
|
configure.Invoke(webSocketOptionsBuilder);
|
||||||
|
|
||||||
|
_webSocketOptions = webSocketOptionsBuilder.Build();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use WithWebSocketServer(... configure) instead.")]
|
||||||
public MqttClientOptionsBuilder WithWebSocketServer(Action<MqttClientWebSocketOptions> optionsBuilder)
|
public MqttClientOptionsBuilder WithWebSocketServer(Action<MqttClientWebSocketOptions> optionsBuilder)
|
||||||
{
|
{
|
||||||
if (optionsBuilder == null)
|
if (optionsBuilder == null)
|
||||||
@@ -415,12 +529,30 @@ namespace MQTTnet.Client
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithWillMessageExpiryInterval(uint willMessageExpiryInterval)
|
||||||
|
{
|
||||||
|
_options.WillMessageExpiryInterval = willMessageExpiryInterval;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public MqttClientOptionsBuilder WithWillPayload(byte[] willPayload)
|
public MqttClientOptionsBuilder WithWillPayload(byte[] willPayload)
|
||||||
{
|
{
|
||||||
_options.WillPayload = willPayload;
|
_options.WillPayload = willPayload;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithWillPayload(ArraySegment<byte> willPayload)
|
||||||
|
{
|
||||||
|
if (willPayload.Count == 0)
|
||||||
|
{
|
||||||
|
_options.WillPayload = null;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
_options.WillPayload = willPayload.ToArray();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public MqttClientOptionsBuilder WithWillPayload(string willPayload)
|
public MqttClientOptionsBuilder WithWillPayload(string willPayload)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(willPayload))
|
if (string.IsNullOrEmpty(willPayload))
|
||||||
|
|||||||
@@ -5,12 +5,14 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Security.Authentication;
|
using System.Security.Authentication;
|
||||||
using System.Security.Cryptography.X509Certificates;
|
|
||||||
|
|
||||||
namespace MQTTnet.Client
|
namespace MQTTnet.Client
|
||||||
{
|
{
|
||||||
|
[Obsolete("Use methods from MqttClientOptionsBuilder instead.")]
|
||||||
public sealed class MqttClientOptionsBuilderTlsParameters
|
public sealed class MqttClientOptionsBuilderTlsParameters
|
||||||
{
|
{
|
||||||
|
IEnumerable<System.Security.Cryptography.X509Certificates.X509Certificate> _obsoleteCertificates;
|
||||||
|
|
||||||
public bool UseTls { get; set; }
|
public bool UseTls { get; set; }
|
||||||
|
|
||||||
public Func<MqttClientCertificateValidationEventArgs, bool> CertificateValidationHandler { get; set; }
|
public Func<MqttClientCertificateValidationEventArgs, bool> CertificateValidationHandler { get; set; }
|
||||||
@@ -24,7 +26,24 @@ namespace MQTTnet.Client
|
|||||||
#if WINDOWS_UWP
|
#if WINDOWS_UWP
|
||||||
public IEnumerable<IEnumerable<byte>> Certificates { get; set; }
|
public IEnumerable<IEnumerable<byte>> Certificates { get; set; }
|
||||||
#else
|
#else
|
||||||
public IEnumerable<X509Certificate> Certificates { get; set; }
|
[Obsolete("Use CertificatesProvider instead.")]
|
||||||
|
public IEnumerable<System.Security.Cryptography.X509Certificates.X509Certificate> Certificates
|
||||||
|
{
|
||||||
|
get => _obsoleteCertificates;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
_obsoleteCertificates = value;
|
||||||
|
|
||||||
|
if (value == null)
|
||||||
|
{
|
||||||
|
CertificatesProvider = null;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
CertificatesProvider = new DefaultMqttCertificatesProvider(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if NETCOREAPP3_1_OR_GREATER
|
#if NETCOREAPP3_1_OR_GREATER
|
||||||
@@ -36,5 +55,7 @@ namespace MQTTnet.Client
|
|||||||
public bool IgnoreCertificateChainErrors { get; set; }
|
public bool IgnoreCertificateChainErrors { get; set; }
|
||||||
|
|
||||||
public bool IgnoreCertificateRevocationErrors { get; set; }
|
public bool IgnoreCertificateRevocationErrors { get; set; }
|
||||||
|
|
||||||
|
public IMqttClientCertificatesProvider CertificatesProvider { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,11 +2,13 @@
|
|||||||
// The .NET Foundation licenses this file to you under the MIT license.
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
|
|
||||||
namespace MQTTnet.Client
|
namespace MQTTnet.Client
|
||||||
{
|
{
|
||||||
|
[Obsolete("Use dedicated methods in MqttClientOptionsBuilder.")]
|
||||||
public class MqttClientOptionsBuilderWebSocketParameters
|
public class MqttClientOptionsBuilderWebSocketParameters
|
||||||
{
|
{
|
||||||
public IDictionary<string, string> RequestHeaders { get; set; }
|
public IDictionary<string, string> RequestHeaders { get; set; }
|
||||||
|
|||||||
@@ -11,34 +11,44 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
public AddressFamily AddressFamily { get; set; } = AddressFamily.Unspecified;
|
public AddressFamily AddressFamily { get; set; } = AddressFamily.Unspecified;
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets the local endpoint (network card) which is used by the client.
|
|
||||||
/// Set it to _null_ to let the OS select the network card.
|
|
||||||
/// </summary>
|
|
||||||
public EndPoint LocalEndpoint { get; set; }
|
|
||||||
|
|
||||||
public int BufferSize { get; set; } = 8192;
|
public int BufferSize { get; set; } = 8192;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets whether the underlying socket should run in dual mode.
|
/// Gets or sets whether the underlying socket should run in dual mode.
|
||||||
/// Leaving this _null_ will avoid setting this value at socket level.
|
/// Leaving this _null_ will avoid setting this value at socket level.
|
||||||
/// Setting this a value other than _null_ will throw an exception when only IPv4 is supported on the machine.
|
/// Setting this a value other than _null_ will throw an exception when only IPv4 is supported on the machine.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool? DualMode { get; set; }
|
public bool? DualMode { get; set; }
|
||||||
|
|
||||||
public LingerOption LingerState { get; set; } = new LingerOption(true, 0);
|
public LingerOption LingerState { get; set; } = new LingerOption(true, 0);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the local endpoint (network card) which is used by the client.
|
||||||
|
/// Set it to _null_ to let the OS select the network card.
|
||||||
|
/// </summary>
|
||||||
|
public EndPoint LocalEndpoint { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enables or disables the Nagle algorithm for the socket.
|
||||||
|
/// This is only supported for TCP.
|
||||||
|
/// For other protocol types the value is ignored.
|
||||||
|
/// Default: true
|
||||||
|
/// </summary>
|
||||||
public bool NoDelay { get; set; } = true;
|
public bool NoDelay { get; set; } = true;
|
||||||
|
|
||||||
public int? Port { get; set; }
|
/// <summary>
|
||||||
|
/// The MQTT transport is usually TCP but when using other endpoint types like
|
||||||
|
/// unix sockets it must be changed (IP for unix sockets).
|
||||||
|
/// </summary>
|
||||||
|
public ProtocolType ProtocolType { get; set; } = ProtocolType.Tcp;
|
||||||
|
|
||||||
public string Server { get; set; }
|
public EndPoint RemoteEndpoint { get; set; }
|
||||||
|
|
||||||
public MqttClientTlsOptions TlsOptions { get; set; } = new MqttClientTlsOptions();
|
public MqttClientTlsOptions TlsOptions { get; set; } = new MqttClientTlsOptions();
|
||||||
|
|
||||||
public override string ToString()
|
public override string ToString()
|
||||||
{
|
{
|
||||||
return Server + ":" + this.GetPort();
|
return RemoteEndpoint?.ToString() ?? string.Empty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
// Licensed to the .NET Foundation under one or more agreements.
|
|
||||||
// The .NET Foundation licenses this file to you under the MIT license.
|
|
||||||
// See the LICENSE file in the project root for more information.
|
|
||||||
|
|
||||||
using System;
|
|
||||||
|
|
||||||
namespace MQTTnet.Client
|
|
||||||
{
|
|
||||||
public static class MqttClientTcpOptionsExtensions
|
|
||||||
{
|
|
||||||
public static int GetPort(this MqttClientTcpOptions options)
|
|
||||||
{
|
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
|
||||||
|
|
||||||
if (options.Port.HasValue)
|
|
||||||
{
|
|
||||||
return options.Port.Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return !options.TlsOptions.UseTls ? 1883 : 8883;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Net.Security;
|
||||||
using System.Security.Authentication;
|
using System.Security.Authentication;
|
||||||
using System.Security.Cryptography.X509Certificates;
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
|
||||||
@@ -13,6 +14,8 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
public Func<MqttClientCertificateValidationEventArgs, bool> CertificateValidationHandler { get; set; }
|
public Func<MqttClientCertificateValidationEventArgs, bool> CertificateValidationHandler { get; set; }
|
||||||
|
|
||||||
|
public Func<MqttClientCertificateSelectionEventArgs, X509Certificate> CertificateSelectionHandler { get; set; }
|
||||||
|
|
||||||
public bool UseTls { get; set; }
|
public bool UseTls { get; set; }
|
||||||
|
|
||||||
public bool IgnoreCertificateRevocationErrors { get; set; }
|
public bool IgnoreCertificateRevocationErrors { get; set; }
|
||||||
@@ -23,22 +26,39 @@ namespace MQTTnet.Client
|
|||||||
|
|
||||||
public X509RevocationMode RevocationMode { get; set; } = X509RevocationMode.Online;
|
public X509RevocationMode RevocationMode { get; set; } = X509RevocationMode.Online;
|
||||||
|
|
||||||
#if WINDOWS_UWP
|
/// <summary>
|
||||||
public List<byte[]> Certificates { get; set; }
|
/// Gets or sets the provider for certificates.
|
||||||
#else
|
/// This provider gets called whenever the client wants to connect
|
||||||
public List<X509Certificate> Certificates { get; set; }
|
/// with the server and requires certificates for authentication.
|
||||||
#endif
|
/// The implementation may return different certificates each time.
|
||||||
|
/// </summary>
|
||||||
|
public IMqttClientCertificatesProvider ClientCertificatesProvider { get; set; }
|
||||||
|
|
||||||
#if NETCOREAPP3_1_OR_GREATER
|
#if NETCOREAPP3_1_OR_GREATER
|
||||||
public List<System.Net.Security.SslApplicationProtocol> ApplicationProtocols { get; set; }
|
public List<SslApplicationProtocol> ApplicationProtocols { get; set; }
|
||||||
|
|
||||||
public System.Net.Security.CipherSuitesPolicy CipherSuitesPolicy { get; set; }
|
public CipherSuitesPolicy CipherSuitesPolicy { get; set; }
|
||||||
|
|
||||||
|
public EncryptionPolicy EncryptionPolicy { get; set; } = EncryptionPolicy.RequireEncryption;
|
||||||
|
|
||||||
|
public bool AllowRenegotiation { get; set; } = true;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the target host.
|
||||||
|
/// If the value is null or empty the same host as the TCP socket host will be used.
|
||||||
|
/// </summary>
|
||||||
|
public string TargetHost { get; set; }
|
||||||
|
|
||||||
#if NET48 || NETCOREAPP3_1_OR_GREATER
|
#if NET48 || NETCOREAPP3_1_OR_GREATER
|
||||||
public SslProtocols SslProtocol { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls13;
|
public SslProtocols SslProtocol { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls13;
|
||||||
|
|
||||||
#else
|
#else
|
||||||
public SslProtocols SslProtocol { get; set; } = SslProtocols.Tls12 | (SslProtocols)0x00003000 /*Tls13*/;
|
public SslProtocols SslProtocol { get; set; } = SslProtocols.Tls12 | (SslProtocols)0x00003000 /*Tls13*/;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if NET7_0_OR_GREATER
|
||||||
|
public X509Certificate2Collection TrustChain { get; set; }
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Security.Authentication;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
#if NETCOREAPP3_1_OR_GREATER
|
||||||
|
using System.Net.Security;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace MQTTnet.Client
|
||||||
|
{
|
||||||
|
public sealed class MqttClientTlsOptionsBuilder
|
||||||
|
{
|
||||||
|
readonly MqttClientTlsOptions _tlsOptions = new MqttClientTlsOptions
|
||||||
|
{
|
||||||
|
// If someone used this builder the change is very very high that TLS
|
||||||
|
// should be actually used.
|
||||||
|
UseTls = true
|
||||||
|
};
|
||||||
|
|
||||||
|
public MqttClientTlsOptions Build()
|
||||||
|
{
|
||||||
|
return _tlsOptions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder UseTls(bool useTls = true)
|
||||||
|
{
|
||||||
|
_tlsOptions.UseTls = useTls;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithAllowUntrustedCertificates(bool allowUntrustedCertificates = true)
|
||||||
|
{
|
||||||
|
_tlsOptions.AllowUntrustedCertificates = allowUntrustedCertificates;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithCertificateValidationHandler(Func<MqttClientCertificateValidationEventArgs, bool> certificateValidationHandler)
|
||||||
|
{
|
||||||
|
if (certificateValidationHandler == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(certificateValidationHandler));
|
||||||
|
}
|
||||||
|
|
||||||
|
_tlsOptions.CertificateValidationHandler = certificateValidationHandler;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithCertificateSelectionHandler(Func<MqttClientCertificateSelectionEventArgs, X509Certificate> certificateSelectionHandler)
|
||||||
|
{
|
||||||
|
if (certificateSelectionHandler == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(certificateSelectionHandler));
|
||||||
|
}
|
||||||
|
|
||||||
|
_tlsOptions.CertificateSelectionHandler = certificateSelectionHandler;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithClientCertificates(IEnumerable<X509Certificate2> certificates)
|
||||||
|
{
|
||||||
|
if (certificates == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(certificates));
|
||||||
|
}
|
||||||
|
|
||||||
|
_tlsOptions.ClientCertificatesProvider = new DefaultMqttCertificatesProvider(certificates);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithClientCertificates(X509Certificate2Collection certificates)
|
||||||
|
{
|
||||||
|
if (certificates == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(certificates));
|
||||||
|
}
|
||||||
|
|
||||||
|
_tlsOptions.ClientCertificatesProvider = new DefaultMqttCertificatesProvider(certificates);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithClientCertificatesProvider(IMqttClientCertificatesProvider clientCertificatesProvider)
|
||||||
|
{
|
||||||
|
_tlsOptions.ClientCertificatesProvider = clientCertificatesProvider;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithIgnoreCertificateChainErrors(bool ignoreCertificateChainErrors = true)
|
||||||
|
{
|
||||||
|
_tlsOptions.IgnoreCertificateChainErrors = ignoreCertificateChainErrors;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithIgnoreCertificateRevocationErrors(bool ignoreCertificateRevocationErrors = true)
|
||||||
|
{
|
||||||
|
_tlsOptions.IgnoreCertificateRevocationErrors = ignoreCertificateRevocationErrors;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithRevocationMode(X509RevocationMode revocationMode)
|
||||||
|
{
|
||||||
|
_tlsOptions.RevocationMode = revocationMode;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithSslProtocols(SslProtocols sslProtocols)
|
||||||
|
{
|
||||||
|
_tlsOptions.SslProtocol = sslProtocols;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithTargetHost(string targetHost)
|
||||||
|
{
|
||||||
|
_tlsOptions.TargetHost = targetHost;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if NETCOREAPP3_1_OR_GREATER
|
||||||
|
public MqttClientTlsOptionsBuilder WithAllowRenegotiation(bool allowRenegotiation = true)
|
||||||
|
{
|
||||||
|
_tlsOptions.AllowRenegotiation = allowRenegotiation;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithApplicationProtocols(List<SslApplicationProtocol> applicationProtocols)
|
||||||
|
{
|
||||||
|
_tlsOptions.ApplicationProtocols = applicationProtocols;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithCipherSuitesPolicy(CipherSuitesPolicy cipherSuitePolicy)
|
||||||
|
{
|
||||||
|
_tlsOptions.CipherSuitesPolicy = cipherSuitePolicy;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientTlsOptionsBuilder WithCipherSuitesPolicy(EncryptionPolicy encryptionPolicy)
|
||||||
|
{
|
||||||
|
_tlsOptions.EncryptionPolicy = encryptionPolicy;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if NET7_0_OR_GREATER
|
||||||
|
public MqttClientTlsOptionsBuilder WithTrustChain(X509Certificate2Collection chain)
|
||||||
|
{
|
||||||
|
_tlsOptions.TrustChain = chain;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,8 +2,10 @@
|
|||||||
// The .NET Foundation licenses this file to you under the MIT license.
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
|
||||||
namespace MQTTnet.Client
|
namespace MQTTnet.Client
|
||||||
{
|
{
|
||||||
@@ -11,6 +13,8 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
public CookieContainer CookieContainer { get; set; }
|
public CookieContainer CookieContainer { get; set; }
|
||||||
|
|
||||||
|
public ICredentials Credentials { get; set; }
|
||||||
|
|
||||||
public MqttClientWebSocketProxyOptions ProxyOptions { get; set; }
|
public MqttClientWebSocketProxyOptions ProxyOptions { get; set; }
|
||||||
|
|
||||||
public IDictionary<string, string> RequestHeaders { get; set; }
|
public IDictionary<string, string> RequestHeaders { get; set; }
|
||||||
@@ -25,5 +29,27 @@ namespace MQTTnet.Client
|
|||||||
{
|
{
|
||||||
return Uri;
|
return Uri;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#if !NETSTANDARD1_3
|
||||||
|
#if !WINDOWS_UWP
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the keep alive interval for the Web Socket connection.
|
||||||
|
/// This is not related to the keep alive interval for the MQTT protocol.
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan KeepAliveInterval { get; set; } = WebSocket.DefaultKeepAliveInterval;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets whether the default (system) credentials should be used when connecting via Web Socket connection.
|
||||||
|
/// This is not related to the credentials which are used for the MQTT protocol.
|
||||||
|
/// </summary>
|
||||||
|
public bool UseDefaultCredentials { get; set; }
|
||||||
|
#else
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the keep alive interval for the Web Socket connection.
|
||||||
|
/// This is not related to the keep alive interval for the MQTT protocol.
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan KeepAliveInterval { get; set; } = TimeSpan.FromSeconds(30);
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Net;
|
||||||
|
|
||||||
|
namespace MQTTnet.Client
|
||||||
|
{
|
||||||
|
public sealed class MqttClientWebSocketOptionsBuilder
|
||||||
|
{
|
||||||
|
readonly MqttClientWebSocketOptions _webSocketOptions = new MqttClientWebSocketOptions();
|
||||||
|
|
||||||
|
public MqttClientWebSocketOptions Build()
|
||||||
|
{
|
||||||
|
return _webSocketOptions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithCookieContainer(CookieContainer cookieContainer)
|
||||||
|
{
|
||||||
|
_webSocketOptions.CookieContainer = cookieContainer;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithCookieContainer(ICredentials credentials)
|
||||||
|
{
|
||||||
|
_webSocketOptions.Credentials = credentials;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithProxyOptions(MqttClientWebSocketProxyOptions proxyOptions)
|
||||||
|
{
|
||||||
|
_webSocketOptions.ProxyOptions = proxyOptions;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithProxyOptions(Action<MqttClientWebSocketProxyOptionsBuilder> configure)
|
||||||
|
{
|
||||||
|
if (configure == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(configure));
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxyOptionsBuilder = new MqttClientWebSocketProxyOptionsBuilder();
|
||||||
|
configure.Invoke(proxyOptionsBuilder);
|
||||||
|
|
||||||
|
_webSocketOptions.ProxyOptions = proxyOptionsBuilder.Build();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithRequestHeaders(IDictionary<string, string> requestHeaders)
|
||||||
|
{
|
||||||
|
_webSocketOptions.RequestHeaders = requestHeaders;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithSubProtocols(ICollection<string> subProtocols)
|
||||||
|
{
|
||||||
|
_webSocketOptions.SubProtocols = subProtocols;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithUri(string uri)
|
||||||
|
{
|
||||||
|
_webSocketOptions.Uri = uri;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if !NETSTANDARD1_3
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithKeepAliveInterval(TimeSpan keepAliveInterval)
|
||||||
|
{
|
||||||
|
_webSocketOptions.KeepAliveInterval = keepAliveInterval;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#if !WINDOWS_UWP && !NETSTANDARD1_3
|
||||||
|
public MqttClientWebSocketOptionsBuilder WithUseDefaultCredentials(bool useDefaultCredentials = true)
|
||||||
|
{
|
||||||
|
_webSocketOptions.UseDefaultCredentials = useDefaultCredentials;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,8 @@ namespace MQTTnet.Client
|
|||||||
|
|
||||||
public bool BypassOnLocal { get; set; }
|
public bool BypassOnLocal { get; set; }
|
||||||
|
|
||||||
|
public bool UseDefaultCredentials { get; set; }
|
||||||
|
|
||||||
public string[] BypassList { get; set; }
|
public string[] BypassList { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace MQTTnet.Client
|
||||||
|
{
|
||||||
|
public sealed class MqttClientWebSocketProxyOptionsBuilder
|
||||||
|
{
|
||||||
|
readonly MqttClientWebSocketProxyOptions _proxyOptions = new MqttClientWebSocketProxyOptions();
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptionsBuilder WithAddress(string address)
|
||||||
|
{
|
||||||
|
_proxyOptions.Address = address;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptionsBuilder WithUsername(string username)
|
||||||
|
{
|
||||||
|
_proxyOptions.Username = username;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptionsBuilder WithPassword(string password)
|
||||||
|
{
|
||||||
|
_proxyOptions.Password = password;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptionsBuilder WithDomain(string domain)
|
||||||
|
{
|
||||||
|
_proxyOptions.Domain = domain;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptionsBuilder WithBypassOnLocal(bool bypassOnLocal = true)
|
||||||
|
{
|
||||||
|
_proxyOptions.BypassOnLocal = bypassOnLocal;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptionsBuilder WithBypassList(string[] bypassList)
|
||||||
|
{
|
||||||
|
_proxyOptions.BypassList = bypassList;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptionsBuilder WithBypassList(IEnumerable<string> bypassList)
|
||||||
|
{
|
||||||
|
_proxyOptions.BypassList = bypassList?.ToArray();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptionsBuilder WithUseDefaultCredentials(bool useDefaultCredentials = true)
|
||||||
|
{
|
||||||
|
_proxyOptions.UseDefaultCredentials = useDefaultCredentials;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientWebSocketProxyOptions Build()
|
||||||
|
{
|
||||||
|
return _proxyOptions;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,7 +34,7 @@ namespace MQTTnet.Client
|
|||||||
/// Gets or sets the reason code.
|
/// Gets or sets the reason code.
|
||||||
/// <remarks>MQTT 5.0.0+ feature.</remarks>
|
/// <remarks>MQTT 5.0.0+ feature.</remarks>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public MqttClientPublishReasonCode ReasonCode { get; } = MqttClientPublishReasonCode.Success;
|
public MqttClientPublishReasonCode ReasonCode { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the reason string.
|
/// Gets or sets the reason string.
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ namespace MQTTnet.Diagnostics
|
|||||||
return "net461";
|
return "net461";
|
||||||
#elif NET472
|
#elif NET472
|
||||||
return "net472";
|
return "net472";
|
||||||
|
#elif NET48
|
||||||
|
return "net48";
|
||||||
#elif NETSTANDARD1_3
|
#elif NETSTANDARD1_3
|
||||||
return "netstandard1.3";
|
return "netstandard1.3";
|
||||||
#elif NETSTANDARD2_0
|
#elif NETSTANDARD2_0
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// Licensed to the .NET Foundation under one or more agreements.
|
||||||
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Exceptions
|
||||||
|
{
|
||||||
|
public class MqttClientNotConnectedException : MqttCommunicationException
|
||||||
|
{
|
||||||
|
public MqttClientNotConnectedException() : base("The MQTT client is not connected.")
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientNotConnectedException(Exception innerException) : base("The MQTT client is not connected.", innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,8 @@ namespace MQTTnet.Formatter
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class MqttBufferWriter
|
public sealed class MqttBufferWriter
|
||||||
{
|
{
|
||||||
public const uint VariableByteIntegerMaxValue = 268435455;
|
const uint VariableByteIntegerMaxValue = 268435455;
|
||||||
|
const int EncodedStringMaxLength = 65535;
|
||||||
|
|
||||||
readonly int _maxBufferSize;
|
readonly int _maxBufferSize;
|
||||||
|
|
||||||
@@ -112,25 +113,7 @@ namespace MQTTnet.Formatter
|
|||||||
WriteBinary(propertyWriter._buffer, 0, propertyWriter.Length);
|
WriteBinary(propertyWriter._buffer, 0, propertyWriter.Length);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void WriteBinary(byte[] buffer, int offset, int count)
|
public void WriteBinary(byte[] value)
|
||||||
{
|
|
||||||
if (buffer == null)
|
|
||||||
{
|
|
||||||
throw new ArgumentNullException(nameof(buffer));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (count == 0)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
EnsureAdditionalCapacity(count);
|
|
||||||
|
|
||||||
MqttMemoryHelper.Copy(buffer, offset, _buffer, _position, count);
|
|
||||||
IncreasePosition(count);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void WriteBinaryData(byte[] value)
|
|
||||||
{
|
{
|
||||||
if (value == null || value.Length == 0)
|
if (value == null || value.Length == 0)
|
||||||
{
|
{
|
||||||
@@ -155,6 +138,24 @@ namespace MQTTnet.Formatter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void WriteBinary(byte[] buffer, int offset, int count)
|
||||||
|
{
|
||||||
|
if (buffer == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(buffer));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
EnsureAdditionalCapacity(count);
|
||||||
|
|
||||||
|
MqttMemoryHelper.Copy(buffer, offset, _buffer, _position, count);
|
||||||
|
IncreasePosition(count);
|
||||||
|
}
|
||||||
|
|
||||||
public void WriteByte(byte @byte)
|
public void WriteByte(byte @byte)
|
||||||
{
|
{
|
||||||
EnsureAdditionalCapacity(1);
|
EnsureAdditionalCapacity(1);
|
||||||
@@ -186,6 +187,13 @@ namespace MQTTnet.Formatter
|
|||||||
|
|
||||||
var writtenBytes = Encoding.UTF8.GetBytes(value, 0, value.Length, _buffer, _position + 2);
|
var writtenBytes = Encoding.UTF8.GetBytes(value, 0, value.Length, _buffer, _position + 2);
|
||||||
|
|
||||||
|
// From RFC: 1.5.4 UTF-8 Encoded String
|
||||||
|
// Unless stated otherwise all UTF-8 encoded strings can have any length in the range 0 to 65,535 bytes.
|
||||||
|
if (writtenBytes > EncodedStringMaxLength)
|
||||||
|
{
|
||||||
|
throw new MqttProtocolViolationException($"The maximum string length is 65535. The current string has a length of {writtenBytes}.");
|
||||||
|
}
|
||||||
|
|
||||||
_buffer[_position] = (byte)(writtenBytes >> 8);
|
_buffer[_position] = (byte)(writtenBytes >> 8);
|
||||||
_buffer[_position + 1] = (byte)writtenBytes;
|
_buffer[_position + 1] = (byte)writtenBytes;
|
||||||
|
|
||||||
@@ -273,8 +281,7 @@ namespace MQTTnet.Formatter
|
|||||||
newBufferLength *= 2;
|
newBufferLength *= 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Array.Resize will create a new array and copy the existing
|
// Array.Resize will create a new array and copy the existing data to the new one.
|
||||||
// data to the new one.
|
|
||||||
Array.Resize(ref _buffer, newBufferLength);
|
Array.Resize(ref _buffer, newBufferLength);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -285,6 +292,8 @@ namespace MQTTnet.Formatter
|
|||||||
|
|
||||||
if (_position > Length)
|
if (_position > Length)
|
||||||
{
|
{
|
||||||
|
// Also extend the position because we reached the end of the
|
||||||
|
// pre allocated buffer.
|
||||||
Length = _position;
|
Length = _position;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,54 +2,12 @@
|
|||||||
// The .NET Foundation licenses this file to you under the MIT license.
|
// The .NET Foundation licenses this file to you under the MIT license.
|
||||||
// See the LICENSE file in the project root for more information.
|
// See the LICENSE file in the project root for more information.
|
||||||
|
|
||||||
using MQTTnet.Exceptions;
|
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
|
|
||||||
namespace MQTTnet.Formatter
|
namespace MQTTnet.Formatter
|
||||||
{
|
{
|
||||||
public static class MqttConnectReasonCodeConverter
|
public static class MqttConnectReasonCodeConverter
|
||||||
{
|
{
|
||||||
public static MqttConnectReasonCode ToConnectReasonCode(MqttConnectReturnCode returnCode)
|
|
||||||
{
|
|
||||||
switch (returnCode)
|
|
||||||
{
|
|
||||||
case MqttConnectReturnCode.ConnectionAccepted:
|
|
||||||
{
|
|
||||||
return MqttConnectReasonCode.Success;
|
|
||||||
}
|
|
||||||
|
|
||||||
case MqttConnectReturnCode.ConnectionRefusedUnacceptableProtocolVersion:
|
|
||||||
{
|
|
||||||
return MqttConnectReasonCode.UnsupportedProtocolVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
case MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword:
|
|
||||||
{
|
|
||||||
return MqttConnectReasonCode.BadUserNameOrPassword;
|
|
||||||
}
|
|
||||||
|
|
||||||
case MqttConnectReturnCode.ConnectionRefusedIdentifierRejected:
|
|
||||||
{
|
|
||||||
return MqttConnectReasonCode.ClientIdentifierNotValid;
|
|
||||||
}
|
|
||||||
|
|
||||||
case MqttConnectReturnCode.ConnectionRefusedServerUnavailable:
|
|
||||||
{
|
|
||||||
return MqttConnectReasonCode.ServerUnavailable;
|
|
||||||
}
|
|
||||||
|
|
||||||
case MqttConnectReturnCode.ConnectionRefusedNotAuthorized:
|
|
||||||
{
|
|
||||||
return MqttConnectReasonCode.NotAuthorized;
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
{
|
|
||||||
throw new MqttProtocolViolationException("Unable to convert connect reason code (MQTTv5) to return code (MQTTv3).");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static MqttConnectReturnCode ToConnectReturnCode(MqttConnectReasonCode reasonCode)
|
public static MqttConnectReturnCode ToConnectReturnCode(MqttConnectReasonCode reasonCode)
|
||||||
{
|
{
|
||||||
switch (reasonCode)
|
switch (reasonCode)
|
||||||
@@ -59,11 +17,13 @@ namespace MQTTnet.Formatter
|
|||||||
return MqttConnectReturnCode.ConnectionAccepted;
|
return MqttConnectReturnCode.ConnectionAccepted;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case MqttConnectReasonCode.Banned:
|
||||||
case MqttConnectReasonCode.NotAuthorized:
|
case MqttConnectReasonCode.NotAuthorized:
|
||||||
{
|
{
|
||||||
return MqttConnectReturnCode.ConnectionRefusedNotAuthorized;
|
return MqttConnectReturnCode.ConnectionRefusedNotAuthorized;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case MqttConnectReasonCode.BadAuthenticationMethod:
|
||||||
case MqttConnectReasonCode.BadUserNameOrPassword:
|
case MqttConnectReasonCode.BadUserNameOrPassword:
|
||||||
{
|
{
|
||||||
return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
|
return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
|
||||||
@@ -79,6 +39,7 @@ namespace MQTTnet.Formatter
|
|||||||
return MqttConnectReturnCode.ConnectionRefusedUnacceptableProtocolVersion;
|
return MqttConnectReturnCode.ConnectionRefusedUnacceptableProtocolVersion;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case MqttConnectReasonCode.UseAnotherServer:
|
||||||
case MqttConnectReasonCode.ServerUnavailable:
|
case MqttConnectReasonCode.ServerUnavailable:
|
||||||
case MqttConnectReasonCode.ServerBusy:
|
case MqttConnectReasonCode.ServerBusy:
|
||||||
case MqttConnectReasonCode.ServerMoved:
|
case MqttConnectReasonCode.ServerMoved:
|
||||||
@@ -87,9 +48,7 @@ namespace MQTTnet.Formatter
|
|||||||
}
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
{
|
return MqttConnectReturnCode.ConnectionRefusedUnacceptableProtocolVersion;
|
||||||
throw new MqttProtocolViolationException("Unable to convert connect reason code (MQTTv5) to return code (MQTTv3).");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,45 +5,107 @@
|
|||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using MQTTnet.Packets;
|
using MQTTnet.Packets;
|
||||||
using MQTTnet.Protocol;
|
using MQTTnet.Protocol;
|
||||||
|
using MQTTnet.Server;
|
||||||
|
using MQTTnet.Server.Disconnecting;
|
||||||
|
|
||||||
namespace MQTTnet.Formatter
|
namespace MQTTnet.Formatter
|
||||||
{
|
{
|
||||||
public sealed class MqttDisconnectPacketFactory
|
public sealed class MqttDisconnectPacketFactory
|
||||||
{
|
{
|
||||||
readonly MqttDisconnectPacket _normalDisconnection = new MqttDisconnectPacket
|
static readonly MqttDisconnectPacket DefaultNormalDisconnection = new MqttDisconnectPacket
|
||||||
{
|
{
|
||||||
ReasonCode = MqttDisconnectReasonCode.NormalDisconnection
|
ReasonCode = MqttDisconnectReasonCode.NormalDisconnection,
|
||||||
|
UserProperties = null,
|
||||||
|
ReasonString = null,
|
||||||
|
ServerReference = null,
|
||||||
|
SessionExpiryInterval = 0
|
||||||
|
};
|
||||||
|
|
||||||
|
static readonly MqttDisconnectPacket DefaultServerShuttingDown = new MqttDisconnectPacket
|
||||||
|
{
|
||||||
|
ReasonCode = MqttDisconnectReasonCode.ServerShuttingDown,
|
||||||
|
UserProperties = null,
|
||||||
|
ReasonString = null,
|
||||||
|
ServerReference = null,
|
||||||
|
SessionExpiryInterval = 0
|
||||||
|
};
|
||||||
|
|
||||||
|
static readonly MqttDisconnectPacket DefaultUnspecifiedError = new MqttDisconnectPacket
|
||||||
|
{
|
||||||
|
ReasonCode = MqttDisconnectReasonCode.UnspecifiedError,
|
||||||
|
UserProperties = null,
|
||||||
|
ReasonString = null,
|
||||||
|
ServerReference = null,
|
||||||
|
SessionExpiryInterval = 0
|
||||||
};
|
};
|
||||||
|
|
||||||
public MqttDisconnectPacket Create(MqttDisconnectReasonCode reasonCode)
|
public MqttDisconnectPacket Create(MqttDisconnectReasonCode reasonCode)
|
||||||
{
|
{
|
||||||
if (reasonCode == MqttDisconnectReasonCode.NormalDisconnection)
|
if (reasonCode == MqttDisconnectReasonCode.NormalDisconnection)
|
||||||
{
|
{
|
||||||
return _normalDisconnection;
|
return DefaultNormalDisconnection;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reasonCode == MqttDisconnectReasonCode.ServerShuttingDown)
|
||||||
|
{
|
||||||
|
return DefaultServerShuttingDown;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reasonCode == MqttDisconnectReasonCode.UnspecifiedError)
|
||||||
|
{
|
||||||
|
return DefaultUnspecifiedError;
|
||||||
}
|
}
|
||||||
|
|
||||||
return new MqttDisconnectPacket
|
return new MqttDisconnectPacket
|
||||||
{
|
{
|
||||||
ReasonCode = reasonCode
|
ReasonCode = reasonCode,
|
||||||
|
UserProperties = null,
|
||||||
|
ReasonString = null,
|
||||||
|
ServerReference = null,
|
||||||
|
SessionExpiryInterval = 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttDisconnectPacket Create(MqttServerStopOptions serverStopOptions)
|
||||||
|
{
|
||||||
|
if (serverStopOptions == null)
|
||||||
|
{
|
||||||
|
return DefaultServerShuttingDown;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Create(serverStopOptions.DefaultClientDisconnectOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttDisconnectPacket Create(MqttServerClientDisconnectOptions clientDisconnectOptions)
|
||||||
|
{
|
||||||
|
if (clientDisconnectOptions == null)
|
||||||
|
{
|
||||||
|
return DefaultNormalDisconnection;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new MqttDisconnectPacket
|
||||||
|
{
|
||||||
|
ReasonCode = clientDisconnectOptions.ReasonCode,
|
||||||
|
UserProperties = clientDisconnectOptions.UserProperties,
|
||||||
|
ReasonString = clientDisconnectOptions.ReasonString,
|
||||||
|
ServerReference = clientDisconnectOptions.ServerReference,
|
||||||
|
SessionExpiryInterval = 0 // TODO: Not yet supported!
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public MqttDisconnectPacket Create(MqttClientDisconnectOptions clientDisconnectOptions)
|
public MqttDisconnectPacket Create(MqttClientDisconnectOptions clientDisconnectOptions)
|
||||||
{
|
{
|
||||||
var packet = new MqttDisconnectPacket();
|
|
||||||
|
|
||||||
if (clientDisconnectOptions == null)
|
if (clientDisconnectOptions == null)
|
||||||
{
|
{
|
||||||
packet.ReasonCode = MqttDisconnectReasonCode.NormalDisconnection;
|
return DefaultNormalDisconnection;
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
packet.ReasonCode = (MqttDisconnectReasonCode)clientDisconnectOptions.Reason;
|
|
||||||
packet.UserProperties = clientDisconnectOptions.UserProperties;
|
|
||||||
packet.SessionExpiryInterval = clientDisconnectOptions.SessionExpiryInterval;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return packet;
|
return new MqttDisconnectPacket
|
||||||
|
{
|
||||||
|
ReasonCode = (MqttDisconnectReasonCode)clientDisconnectOptions.Reason,
|
||||||
|
UserProperties = clientDisconnectOptions.UserProperties,
|
||||||
|
SessionExpiryInterval = clientDisconnectOptions.SessionExpiryInterval
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,10 +31,14 @@ namespace MQTTnet.Formatter
|
|||||||
|
|
||||||
public MqttProtocolVersion ProtocolVersion { get; private set; } = MqttProtocolVersion.Unknown;
|
public MqttProtocolVersion ProtocolVersion { get; private set; } = MqttProtocolVersion.Unknown;
|
||||||
|
|
||||||
|
public void Cleanup()
|
||||||
|
{
|
||||||
|
_bufferWriter.Cleanup();
|
||||||
|
}
|
||||||
|
|
||||||
public MqttPacket Decode(ReceivedMqttPacket receivedMqttPacket)
|
public MqttPacket Decode(ReceivedMqttPacket receivedMqttPacket)
|
||||||
{
|
{
|
||||||
ThrowIfFormatterNotSet();
|
ThrowIfFormatterNotSet();
|
||||||
|
|
||||||
return _formatter.Decode(receivedMqttPacket);
|
return _formatter.Decode(receivedMqttPacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,11 +54,6 @@ namespace MQTTnet.Formatter
|
|||||||
return _formatter.Encode(packet);
|
return _formatter.Encode(packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Cleanup()
|
|
||||||
{
|
|
||||||
_bufferWriter.Cleanup();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IMqttPacketFormatter GetMqttPacketFormatter(MqttProtocolVersion protocolVersion, MqttBufferWriter bufferWriter)
|
public static IMqttPacketFormatter GetMqttPacketFormatter(MqttProtocolVersion protocolVersion, MqttBufferWriter bufferWriter)
|
||||||
{
|
{
|
||||||
if (protocolVersion == MqttProtocolVersion.Unknown)
|
if (protocolVersion == MqttProtocolVersion.Unknown)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user