mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-17 01:33:03 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c20edd3d0 | ||
|
|
b02b0ccd7c | ||
|
|
1bcf7ec29c | ||
|
|
e54b4f58df | ||
|
|
30540729df | ||
|
|
77b80dc53e | ||
|
|
861d3dfa0f | ||
|
|
e0235aedff | ||
|
|
8411382c42 | ||
|
|
f8078a6894 | ||
|
|
f66e8c8b3a | ||
|
|
acc269e702 | ||
|
|
5bcda12ca9 | ||
|
|
8de87c8772 | ||
|
|
b956623234 | ||
|
|
6e615f85eb | ||
|
|
b70b469201 | ||
|
|
c4b706f8ad | ||
|
|
9d971003d5 | ||
|
|
c322817cb1 | ||
|
|
0c4c93784d | ||
|
|
4cae09a4e9 | ||
|
|
c775867db4 | ||
|
|
8672fb2792 | ||
|
|
48c47c6fcf | ||
|
|
38904a6213 | ||
|
|
bdadfa1c26 | ||
|
|
e38142399e | ||
|
|
5cbbfedcce | ||
|
|
bc97575760 | ||
|
|
afd56a7f6f | ||
|
|
0844abd7e5 | ||
|
|
3625363fcf | ||
|
|
9692ae5617 | ||
|
|
c01edb192f | ||
|
|
acbf9153f4 | ||
|
|
b6cd4638b9 | ||
|
|
683d97dc14 | ||
|
|
ad77dc0bea | ||
|
|
587622af81 | ||
|
|
eaf27c1e12 | ||
|
|
1c78cd4c31 | ||
|
|
d1ab867afc | ||
|
|
522a385523 | ||
|
|
40dd620f90 | ||
|
|
7dfc19e588 | ||
|
|
0b002e8d11 | ||
|
|
d2e481719c | ||
|
|
7e48746944 | ||
|
|
f481c704c9 | ||
|
|
6e5b991406 | ||
|
|
e07ead53a9 | ||
|
|
e6e88e132b | ||
|
|
8778848301 | ||
|
|
5fbef7beb5 | ||
|
|
387a3bc281 | ||
|
|
11ccb951aa | ||
|
|
3a6df2eab0 | ||
|
|
c5e3bc70b1 | ||
|
|
9c46b8fd75 | ||
|
|
d5dc3a1361 | ||
|
|
f0e8d8e98c | ||
|
|
589fd22a63 | ||
|
|
83821453a0 | ||
|
|
d335b6393e | ||
|
|
6240d60003 | ||
|
|
4519c4fe3d | ||
|
|
e969b2f31f | ||
|
|
44ae9093f9 | ||
|
|
fcd3bdf297 | ||
|
|
cbb2f43047 | ||
|
|
5e74869dbc | ||
|
|
98cac153e6 | ||
|
|
b51a603aa9 | ||
|
|
2fe520ad46 | ||
|
|
c8846329f3 | ||
|
|
08f2db05a9 | ||
|
|
5427b488c3 | ||
|
|
ec24f03324 | ||
|
|
4ef16cfd8d | ||
|
|
177c7cbf03 | ||
|
|
8025717658 | ||
|
|
275d8d9f0b | ||
|
|
30df7d4c9e | ||
|
|
019ef1398e | ||
|
|
4a6f517e91 | ||
|
|
d560cb4c9e | ||
|
|
ba16ae6568 | ||
|
|
3b2c40d49e | ||
|
|
9894dbef87 | ||
|
|
dd447f24d2 | ||
|
|
3a250723d7 | ||
|
|
e0797e5d14 | ||
|
|
d0f1c18a2f | ||
|
|
bb6eb246e8 | ||
|
|
0e666f0316 | ||
|
|
0811938466 | ||
|
|
466b6a25cd | ||
|
|
15a564dcfe | ||
|
|
f85721fbf5 | ||
|
|
3b366f91fc | ||
|
|
418f2b2c3f | ||
|
|
8fa91736b6 | ||
|
|
a18c533603 | ||
|
|
a9b394401b | ||
|
|
c257e5cb77 | ||
|
|
93863ece0d | ||
|
|
29918fb454 | ||
|
|
412cf115a5 | ||
|
|
8dab5d3800 | ||
|
|
2cd3bd7588 | ||
|
|
0e0fcabc04 | ||
|
|
e80d21e852 | ||
|
|
a68343a306 | ||
|
|
d594b1447f | ||
|
|
1ca9b0bd62 | ||
|
|
1c0b2b55b6 | ||
|
|
41ca15120d | ||
|
|
49b1706495 | ||
|
|
daf22c762f | ||
|
|
3529724bdc | ||
|
|
56a86b6127 | ||
|
|
7e6f4453ad | ||
|
|
84a647e712 | ||
|
|
d10f29bbc6 | ||
|
|
41edc3a1ec | ||
|
|
3f080e04b9 | ||
|
|
4386ef1e56 | ||
|
|
df1dd0eec7 | ||
|
|
3954777d20 | ||
|
|
b52645f77a | ||
|
|
65e6f96e59 | ||
|
|
24c35de330 | ||
|
|
d052f409b6 | ||
|
|
f9eb6ed85e | ||
|
|
11ade8c3df | ||
|
|
fe88b7551c | ||
|
|
bddfadaefa | ||
|
|
40b1be075c | ||
|
|
680bc4658f | ||
|
|
870ed00e3c | ||
|
|
1f3b24d20f | ||
|
|
bc19f66812 | ||
|
|
9915cc4492 | ||
|
|
ad4585989a | ||
|
|
ea5616002a | ||
|
|
1f8a781dc2 | ||
|
|
fd63cf0086 | ||
|
|
60bdca8716 | ||
|
|
a2971aa03b | ||
|
|
05a3acb229 | ||
|
|
47257baba9 | ||
|
|
906a0ba189 | ||
|
|
69b02f3224 | ||
|
|
a7d0ad5f43 | ||
|
|
59f07c868d | ||
|
|
4517d80704 | ||
|
|
9bca4aa53f | ||
|
|
4c4539509c | ||
|
|
af3cebb266 | ||
|
|
d22528ca46 | ||
|
|
67267c05fd | ||
|
|
d23ab88add | ||
|
|
1d78d675f7 | ||
|
|
3079ad37ce | ||
|
|
c7b7d56229 | ||
|
|
c97b97c677 | ||
|
|
96a62551b2 | ||
|
|
300c9b9ccb | ||
|
|
342085db40 | ||
|
|
862f76fea2 | ||
|
|
3cce33415d | ||
|
|
d09455f78e | ||
|
|
e947881aca | ||
|
|
077c9ea00d | ||
|
|
f8af4597f2 | ||
|
|
32dc96ae93 | ||
|
|
153e83ee3e | ||
|
|
6402dfd9ea | ||
|
|
98bafb1f26 | ||
|
|
6d92937892 | ||
|
|
28d31d0cf5 | ||
|
|
07fd509e74 | ||
|
|
37a5dc7abe | ||
|
|
8604097ada | ||
|
|
ea587d97c8 | ||
|
|
fb272b07aa | ||
|
|
7067a8e411 | ||
|
|
50800b1d44 | ||
|
|
dcf6f94d77 | ||
|
|
8131995006 | ||
|
|
7de1634a36 | ||
|
|
b252781f8d | ||
|
|
023cb12079 | ||
|
|
b5b87f5272 | ||
|
|
f287bd4d1d | ||
|
|
222a154290 | ||
|
|
9b8af2455f | ||
|
|
493c934463 | ||
|
|
83f1d74a76 | ||
|
|
e7c8d1c1c1 | ||
|
|
305578e7e6 | ||
|
|
651f0aa15c | ||
|
|
51e7cd725e | ||
|
|
32473af7c2 | ||
|
|
b5fc6e3d12 | ||
|
|
dc65bdb913 | ||
|
|
d4ef1a7302 | ||
|
|
f8c01b2168 | ||
|
|
d7e2b18247 | ||
|
|
12a275918e | ||
|
|
eda8bff10b | ||
|
|
76105de4c7 | ||
|
|
eed56cdf55 | ||
|
|
da7adc1068 | ||
|
|
f1ff947697 | ||
|
|
9250853854 | ||
|
|
d1b634511d | ||
|
|
cf7b7191f8 | ||
|
|
0dcd8227da | ||
|
|
089eb9b604 | ||
|
|
f04a9c4f3e | ||
|
|
e2d15c8764 | ||
|
|
9a25fb63ad | ||
|
|
0e48076d25 | ||
|
|
a956de3df7 | ||
|
|
455a047242 | ||
|
|
27bb22de09 | ||
|
|
285c70f24f | ||
|
|
c7c1691d75 | ||
|
|
6c7e70f78a | ||
|
|
97338b016d | ||
|
|
473c8e0a15 | ||
|
|
090e59e99a | ||
|
|
5712bc11d2 | ||
|
|
323339b0b2 | ||
|
|
c001897590 | ||
|
|
8fd3e5070d | ||
|
|
01e739d524 | ||
|
|
16a184a92f | ||
|
|
1a1c0beabc | ||
|
|
ff0b022357 | ||
|
|
c0e6e54496 | ||
|
|
16bc9cb203 | ||
|
|
196a325f7f | ||
|
|
da70dc0565 | ||
|
|
f7a8b764d0 | ||
|
|
16949ffb21 | ||
|
|
de0dfb9265 | ||
|
|
9cde49f5f8 | ||
|
|
644bcfba27 | ||
|
|
a4d393ae28 | ||
|
|
a7a5eed0f2 | ||
|
|
80a6e6809c | ||
|
|
861efa5e75 | ||
|
|
6c8f85afe9 | ||
|
|
6b1a6c054e | ||
|
|
f2502ac431 | ||
|
|
76151deba0 | ||
|
|
4a6790f0aa | ||
|
|
95298202a3 | ||
|
|
1c30d14910 | ||
|
|
8aec1583df | ||
|
|
04036cf63a | ||
|
|
68aae70b44 | ||
|
|
0907eadb55 | ||
|
|
77818d669f | ||
|
|
70aee177c3 | ||
|
|
5e417affa5 | ||
|
|
783ee4328a | ||
|
|
caa857f318 | ||
|
|
20a1b77b58 | ||
|
|
960900dafa | ||
|
|
9bf287a1ac | ||
|
|
f886b0eed1 | ||
|
|
1f1f2d2e90 | ||
|
|
8ad619ebc1 | ||
|
|
85f1a31be3 | ||
|
|
4a57d050f6 | ||
|
|
3a1e32f5aa | ||
|
|
b407221ce6 | ||
|
|
96b92aabae | ||
|
|
d87dab2e25 | ||
|
|
b2f9d937e1 | ||
|
|
c9ac954bfd | ||
|
|
dea2da52f9 | ||
|
|
487a97c31e | ||
|
|
c90bdbfb93 | ||
|
|
598ed66a3b | ||
|
|
59b0b79a32 | ||
|
|
0172606747 | ||
|
|
65c2a0fd7c | ||
|
|
68926cef20 | ||
|
|
447ca6cabb | ||
|
|
0b0239bcf1 | ||
|
|
e021d5a56b | ||
|
|
36abf8450e | ||
|
|
d67b4a0b35 | ||
|
|
e4a376acdd | ||
|
|
8cfdb2fbf2 | ||
|
|
886b2d6b42 | ||
|
|
2193281c6a | ||
|
|
eb7ee420fc | ||
|
|
5a1d953278 | ||
|
|
67c291e15a | ||
|
|
3722bc9ae6 | ||
|
|
1fb0944e2b | ||
|
|
61c7ee0958 | ||
|
|
9c5e5b5e10 | ||
|
|
b3e11d47b7 | ||
|
|
31419fef03 | ||
|
|
b2e3686f59 | ||
|
|
9b90ae0c81 | ||
|
|
39beb4912b | ||
|
|
98d7bc980c | ||
|
|
2ff449b241 | ||
|
|
83f6ae4e54 | ||
|
|
d26d29e9a6 | ||
|
|
d0e8a0c4e5 | ||
|
|
35344b27c5 | ||
|
|
6b6b7f90c8 | ||
|
|
eeb3242573 | ||
|
|
cd5c295484 | ||
|
|
4ffe6dfc2b | ||
|
|
072c1c521a | ||
|
|
314fca3f89 | ||
|
|
dae5a06734 | ||
|
|
4b62236638 | ||
|
|
5117f9b30d | ||
|
|
818ffcab29 | ||
|
|
efe2ceebe0 | ||
|
|
67f9c07b44 | ||
|
|
c5978f5845 | ||
|
|
929cdb971a | ||
|
|
1317fa3e2a | ||
|
|
8a65850f1a | ||
|
|
5c1eceb8a9 | ||
|
|
2db289a658 | ||
|
|
201844a45b | ||
|
|
93a3bbd849 | ||
|
|
86dddd81c7 |
@@ -0,0 +1,8 @@
|
|||||||
|
exclude:
|
||||||
|
- /Frameworks/.*
|
||||||
|
- /MQTTnet.TestApp.NetCore/Program.cs
|
||||||
|
- /Tests/MQTTnet.TestApp.NetFramework/.*
|
||||||
|
- /Tests/MQTTnet.TestApp.UniversalWindows/.*
|
||||||
|
component_depth: 1
|
||||||
|
languages:
|
||||||
|
- csharp
|
||||||
+69
-22
@@ -1,5 +1,7 @@
|
|||||||
## Ignore Visual Studio temporary files, build results, and
|
## Ignore Visual Studio temporary files, build results, and
|
||||||
## files generated by popular Visual Studio add-ons.
|
## files generated by popular Visual Studio add-ons.
|
||||||
|
##
|
||||||
|
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||||
|
|
||||||
# User-specific files
|
# User-specific files
|
||||||
*.suo
|
*.suo
|
||||||
@@ -15,12 +17,12 @@
|
|||||||
[Dd]ebugPublic/
|
[Dd]ebugPublic/
|
||||||
[Rr]elease/
|
[Rr]elease/
|
||||||
[Rr]eleases/
|
[Rr]eleases/
|
||||||
[Xx]64/
|
x64/
|
||||||
[Xx]86/
|
x86/
|
||||||
[Bb]uild/
|
|
||||||
bld/
|
bld/
|
||||||
[Bb]in/
|
[Bb]in/
|
||||||
[Oo]bj/
|
[Oo]bj/
|
||||||
|
[Ll]og/
|
||||||
|
|
||||||
# Visual Studio 2015 cache/options directory
|
# Visual Studio 2015 cache/options directory
|
||||||
.vs/
|
.vs/
|
||||||
@@ -40,9 +42,11 @@ TestResult.xml
|
|||||||
[Rr]eleasePS/
|
[Rr]eleasePS/
|
||||||
dlldata.c
|
dlldata.c
|
||||||
|
|
||||||
# DNX
|
# .NET Core
|
||||||
project.lock.json
|
project.lock.json
|
||||||
|
project.fragment.lock.json
|
||||||
artifacts/
|
artifacts/
|
||||||
|
**/Properties/launchSettings.json
|
||||||
|
|
||||||
*_i.c
|
*_i.c
|
||||||
*_p.c
|
*_p.c
|
||||||
@@ -81,6 +85,7 @@ ipch/
|
|||||||
*.sdf
|
*.sdf
|
||||||
*.cachefile
|
*.cachefile
|
||||||
*.VC.db
|
*.VC.db
|
||||||
|
*.VC.VC.opendb
|
||||||
|
|
||||||
# Visual Studio profiler
|
# Visual Studio profiler
|
||||||
*.psess
|
*.psess
|
||||||
@@ -108,6 +113,10 @@ _TeamCity*
|
|||||||
# DotCover is a Code Coverage Tool
|
# DotCover is a Code Coverage Tool
|
||||||
*.dotCover
|
*.dotCover
|
||||||
|
|
||||||
|
# Visual Studio code coverage results
|
||||||
|
*.coverage
|
||||||
|
*.coveragexml
|
||||||
|
|
||||||
# NCrunch
|
# NCrunch
|
||||||
_NCrunch_*
|
_NCrunch_*
|
||||||
.*crunch*.local.xml
|
.*crunch*.local.xml
|
||||||
@@ -139,13 +148,16 @@ publish/
|
|||||||
# Publish Web Output
|
# Publish Web Output
|
||||||
*.[Pp]ublish.xml
|
*.[Pp]ublish.xml
|
||||||
*.azurePubxml
|
*.azurePubxml
|
||||||
|
# TODO: Comment the next line if you want to checkin your web deploy settings
|
||||||
# TODO: Un-comment the next line if you do not want to checkin
|
# but database connection strings (with potential passwords) will be unencrypted
|
||||||
# your web deploy settings because they may include unencrypted
|
*.pubxml
|
||||||
# passwords
|
|
||||||
#*.pubxml
|
|
||||||
*.publishproj
|
*.publishproj
|
||||||
|
|
||||||
|
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||||
|
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||||
|
# in these scripts will be unencrypted
|
||||||
|
PublishScripts/
|
||||||
|
|
||||||
# NuGet Packages
|
# NuGet Packages
|
||||||
*.nupkg
|
*.nupkg
|
||||||
# The packages folder can be ignored because of Package Restore
|
# The packages folder can be ignored because of Package Restore
|
||||||
@@ -154,7 +166,7 @@ publish/
|
|||||||
!**/packages/build/
|
!**/packages/build/
|
||||||
# Uncomment if necessary however generally it will be regenerated when needed
|
# Uncomment if necessary however generally it will be regenerated when needed
|
||||||
#!**/packages/repositories.config
|
#!**/packages/repositories.config
|
||||||
# NuGet v3's project.json files produces more ignoreable files
|
# NuGet v3's project.json files produces more ignorable files
|
||||||
*.nuget.props
|
*.nuget.props
|
||||||
*.nuget.targets
|
*.nuget.targets
|
||||||
|
|
||||||
@@ -166,12 +178,11 @@ csx/
|
|||||||
ecf/
|
ecf/
|
||||||
rcf/
|
rcf/
|
||||||
|
|
||||||
# Microsoft Azure ApplicationInsights config file
|
# Windows Store app package directories and files
|
||||||
ApplicationInsights.config
|
|
||||||
|
|
||||||
# Windows Store app package directory
|
|
||||||
AppPackages/
|
AppPackages/
|
||||||
BundleArtifacts/
|
BundleArtifacts/
|
||||||
|
Package.StoreAssociation.xml
|
||||||
|
_pkginfo.txt
|
||||||
|
|
||||||
# Visual Studio cache files
|
# Visual Studio cache files
|
||||||
# files ending in .cache can be ignored
|
# files ending in .cache can be ignored
|
||||||
@@ -181,16 +192,19 @@ BundleArtifacts/
|
|||||||
|
|
||||||
# Others
|
# Others
|
||||||
ClientBin/
|
ClientBin/
|
||||||
[Ss]tyle[Cc]op.*
|
|
||||||
~$*
|
~$*
|
||||||
*~
|
*~
|
||||||
*.dbmdl
|
*.dbmdl
|
||||||
*.dbproj.schemaview
|
*.dbproj.schemaview
|
||||||
*.pfx
|
*.jfm
|
||||||
|
# *.pfx
|
||||||
*.publishsettings
|
*.publishsettings
|
||||||
node_modules/
|
|
||||||
orleans.codegen.cs
|
orleans.codegen.cs
|
||||||
|
|
||||||
|
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||||
|
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||||
|
#bower_components/
|
||||||
|
|
||||||
# RIA/Silverlight projects
|
# RIA/Silverlight projects
|
||||||
Generated_Code/
|
Generated_Code/
|
||||||
|
|
||||||
@@ -205,6 +219,7 @@ UpgradeLog*.htm
|
|||||||
# SQL Server files
|
# SQL Server files
|
||||||
*.mdf
|
*.mdf
|
||||||
*.ldf
|
*.ldf
|
||||||
|
*.ndf
|
||||||
|
|
||||||
# Business Intelligence projects
|
# Business Intelligence projects
|
||||||
*.rdl.data
|
*.rdl.data
|
||||||
@@ -219,6 +234,10 @@ FakesAssemblies/
|
|||||||
|
|
||||||
# Node.js Tools for Visual Studio
|
# Node.js Tools for Visual Studio
|
||||||
.ntvs_analysis.dat
|
.ntvs_analysis.dat
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# Typescript v1 declaration files
|
||||||
|
typings/
|
||||||
|
|
||||||
# Visual Studio 6 build log
|
# Visual Studio 6 build log
|
||||||
*.plg
|
*.plg
|
||||||
@@ -226,6 +245,9 @@ FakesAssemblies/
|
|||||||
# Visual Studio 6 workspace options file
|
# Visual Studio 6 workspace options file
|
||||||
*.opt
|
*.opt
|
||||||
|
|
||||||
|
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||||
|
*.vbw
|
||||||
|
|
||||||
# Visual Studio LightSwitch build output
|
# Visual Studio LightSwitch build output
|
||||||
**/*.HTMLClient/GeneratedArtifacts
|
**/*.HTMLClient/GeneratedArtifacts
|
||||||
**/*.DesktopClient/GeneratedArtifacts
|
**/*.DesktopClient/GeneratedArtifacts
|
||||||
@@ -234,13 +256,38 @@ FakesAssemblies/
|
|||||||
**/*.Server/ModelManifest.xml
|
**/*.Server/ModelManifest.xml
|
||||||
_Pvt_Extensions
|
_Pvt_Extensions
|
||||||
|
|
||||||
# LightSwitch generated files
|
|
||||||
GeneratedArtifacts/
|
|
||||||
ModelManifest.xml
|
|
||||||
|
|
||||||
# Paket dependency manager
|
# Paket dependency manager
|
||||||
.paket/paket.exe
|
.paket/paket.exe
|
||||||
|
paket-files/
|
||||||
|
|
||||||
# FAKE - F# Make
|
# FAKE - F# Make
|
||||||
.fake/
|
.fake/
|
||||||
nuget.exe
|
|
||||||
|
# JetBrains Rider
|
||||||
|
.idea/
|
||||||
|
*.sln.iml
|
||||||
|
|
||||||
|
# CodeRush
|
||||||
|
.cr/
|
||||||
|
|
||||||
|
# Python Tools for Visual Studio (PTVS)
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
# Cake - Uncomment if you are using it
|
||||||
|
# tools/**
|
||||||
|
# !tools/packages.config
|
||||||
|
|
||||||
|
# Telerik's JustMock configuration file
|
||||||
|
*.jmconfig
|
||||||
|
|
||||||
|
# BizTalk build output
|
||||||
|
*.btp.cs
|
||||||
|
*.btm.cs
|
||||||
|
*.odx.cs
|
||||||
|
*.xsd.cs
|
||||||
|
|
||||||
|
|
||||||
|
Build/nuget.exe
|
||||||
|
*.js
|
||||||
|
*.map
|
||||||
|
|||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
language: csharp
|
||||||
|
solution: MQTTnet.sln
|
||||||
|
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- dotnet: 2.0.0
|
||||||
|
mono: none
|
||||||
|
dist: trusty
|
||||||
|
env: DOTNETCORE=1 # optional, can be used to take different code paths in your script
|
||||||
|
- mono: latest
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<package >
|
||||||
|
<metadata>
|
||||||
|
<id>MQTTnet.AspNetCore</id>
|
||||||
|
<version>2.5.3</version>
|
||||||
|
<authors>Christian Kratky</authors>
|
||||||
|
<owners>Christian Kratky</owners>
|
||||||
|
<licenseUrl>https://github.com/chkr1011/MQTTnet/blob/master/LICENSE</licenseUrl>
|
||||||
|
<projectUrl>https://github.com/chkr1011/MQTTnet</projectUrl>
|
||||||
|
<iconUrl>https://raw.githubusercontent.com/chkr1011/MQTTnet/master/Images/Logo_128x128.png</iconUrl>
|
||||||
|
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||||
|
<description>This is a support library to integrate MQTTnet into AspNetCore.</description>
|
||||||
|
<releaseNotes>* Updated to MQTTnet 2.5.3.
|
||||||
|
</releaseNotes>
|
||||||
|
<copyright>Copyright Christian Kratky 2016-2017</copyright>
|
||||||
|
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags>
|
||||||
|
<dependencies>
|
||||||
|
<group targetFramework="netstandard2.0">
|
||||||
|
<dependency id="MQTTnet" version="2.5.3-rc1" />
|
||||||
|
</group>
|
||||||
|
</dependencies>
|
||||||
|
</metadata>
|
||||||
|
|
||||||
|
<files>
|
||||||
|
<!-- .NET Standard 2.0 -->
|
||||||
|
<file src="..\Frameworks\MQTTnet.AspNetCore\bin\Release\netstandard2.0\MQTTnet.AspNetCore.*" target="lib\netstandard2.0\"/>
|
||||||
|
</files>
|
||||||
|
</package>
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<package >
|
||||||
|
<metadata>
|
||||||
|
<id>MQTTnet</id>
|
||||||
|
<version>2.5.3</version>
|
||||||
|
<authors>Christian Kratky</authors>
|
||||||
|
<owners>Christian Kratky</owners>
|
||||||
|
<licenseUrl>https://github.com/chkr1011/MQTTnet/blob/master/LICENSE</licenseUrl>
|
||||||
|
<projectUrl>https://github.com/chkr1011/MQTTnet</projectUrl>
|
||||||
|
<iconUrl>https://raw.githubusercontent.com/chkr1011/MQTTnet/master/Images/Logo_128x128.png</iconUrl>
|
||||||
|
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||||
|
<description>MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker).</description>
|
||||||
|
<releaseNotes>* [Core] Removed all dependencies to other libraries (BREAKING CHANGE!).
|
||||||
|
* [Core] Updated SDK libraries.
|
||||||
|
* [Client] Fixed broken support for WebSocketSecure connections (Thanks to @StAI).
|
||||||
|
</releaseNotes>
|
||||||
|
<copyright>Copyright Christian Kratky 2016-2017</copyright>
|
||||||
|
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags>
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<group targetFramework="netstandard1.3">
|
||||||
|
<dependency id="NETStandard.Library" version="1.3.0" />
|
||||||
|
<dependency id="System.Net.Security" version="4.3.2" />
|
||||||
|
<dependency id="System.Net.WebSockets" version="4.3.0" />
|
||||||
|
<dependency id="System.Net.WebSockets.Client" version="4.3.1" />
|
||||||
|
</group>
|
||||||
|
|
||||||
|
<group targetFramework="netstandard2.0">
|
||||||
|
<dependency id="NETStandard.Library" version="2.0.0" />
|
||||||
|
<dependency id="System.Net.Security" version="4.3.2" />
|
||||||
|
<dependency id="System.Net.WebSockets" version="4.3.0" />
|
||||||
|
<dependency id="System.Net.WebSockets.Client" version="4.3.1" />
|
||||||
|
</group>
|
||||||
|
|
||||||
|
<group targetFramework="uap10.0">
|
||||||
|
<dependency id="Microsoft.NETCore.UniversalWindowsPlatform" version="5.4.1" />
|
||||||
|
</group>
|
||||||
|
|
||||||
|
<group targetFramework="net452">
|
||||||
|
</group>
|
||||||
|
|
||||||
|
<group targetFramework="net461">
|
||||||
|
</group>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
</metadata>
|
||||||
|
|
||||||
|
<files>
|
||||||
|
<!-- .NET Standard 1.3 -->
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\netstandard1.3\MQTTnet.Core.*" target="lib\netstandard1.3\"/>
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\netstandard1.3\MQTTnet.*" target="lib\netstandard1.3\"/>
|
||||||
|
|
||||||
|
<!-- .NET Standard 2.0 -->
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\netstandard2.0\MQTTnet.Core.*" target="lib\netstandard2.0\"/>
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\netstandard2.0\MQTTnet.*" target="lib\netstandard2.0\"/>
|
||||||
|
|
||||||
|
<!-- Universal Windows -->
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\uap10.0\MQTTnet.Core.*" target="lib\uap10.0\"/>
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\uap10.0\MQTTnet.*" target="lib\uap10.0\"/>
|
||||||
|
|
||||||
|
<!-- .NET Framework -->
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\net452\MQTTnet.Core.*" target="lib\net452\"/>
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\net452\MQTTnet.*" target="lib\net452\"/>
|
||||||
|
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\net461\MQTTnet.Core.*" target="lib\net461\"/>
|
||||||
|
<file src="..\Frameworks\MQTTnet.Netstandard\bin\Release\net461\MQTTnet.*" target="lib\net461\"/>
|
||||||
|
|
||||||
|
</files>
|
||||||
|
</package>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
param([string]$assemblyVersion, [string]$nugetVersion)
|
||||||
|
|
||||||
|
if ([string]::IsNullOrEmpty($version)) {$version = "0.0.1"}
|
||||||
|
|
||||||
|
$vswhere = ${Env:\ProgramFiles(x86)} + '\Microsoft Visual Studio\Installer\vswhere'
|
||||||
|
|
||||||
|
$path = &$vswhere -latest -products * -requires Microsoft.Component.MSBuild -property installationPath
|
||||||
|
if ($path) {
|
||||||
|
$msbuild = join-path $path 'MSBuild\15.0\Bin\MSBuild.exe'
|
||||||
|
|
||||||
|
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net452" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m
|
||||||
|
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net461" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m
|
||||||
|
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard1.3" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m
|
||||||
|
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m
|
||||||
|
&$msbuild ..\Frameworks\MQTTnet.Netstandard\MQTTnet.Netstandard.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="uap10.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m
|
||||||
|
|
||||||
|
&$msbuild ..\Frameworks\MQTTnet.AspNetCore\MQTTnet.AspNetCore.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m
|
||||||
|
|
||||||
|
Remove-Item .\NuGet -Force -Recurse
|
||||||
|
New-Item -ItemType Directory -Force -Path .\NuGet
|
||||||
|
.\NuGet.exe pack MQTTnet.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion
|
||||||
|
.\NuGet.exe pack MQTTnet.AspNetCore.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using MQTTnet.Core.Server;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace MQTTnet.AspNetCore
|
||||||
|
{
|
||||||
|
public static class ApplicationBuilderExtensions
|
||||||
|
{
|
||||||
|
public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt")
|
||||||
|
{
|
||||||
|
app.UseWebSockets();
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
if (context.Request.Path == path && context.WebSockets.IsWebSocketRequest)
|
||||||
|
{
|
||||||
|
string subprotocol = null;
|
||||||
|
|
||||||
|
if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues)
|
||||||
|
&& requestedSubProtocolValues.Count > 0
|
||||||
|
&& requestedSubProtocolValues.Any(v => v.ToLower() == "mqtt")
|
||||||
|
)
|
||||||
|
{
|
||||||
|
subprotocol = "mqtt";
|
||||||
|
}
|
||||||
|
|
||||||
|
var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
|
||||||
|
using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subprotocol))
|
||||||
|
{
|
||||||
|
await adapter.AcceptWebSocketAsync(webSocket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await next();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
|
||||||
|
{
|
||||||
|
var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
|
||||||
|
|
||||||
|
configure(server);
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>netstandard2.0</TargetFramework>
|
||||||
|
<AssemblyVersion>2.5.2.0</AssemblyVersion>
|
||||||
|
<FileVersion>2.5.2.0</FileVersion>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="2.0.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\MQTTnet.Netstandard\MQTTnet.NetStandard.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using MQTTnet.Core.Adapter;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.Server;
|
||||||
|
|
||||||
|
namespace MQTTnet.AspNetCore
|
||||||
|
{
|
||||||
|
public class MqttHostedServer : MqttServer, IHostedService
|
||||||
|
{
|
||||||
|
private readonly MqttServerOptions _options;
|
||||||
|
|
||||||
|
public MqttHostedServer(MqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger) : base(adapters, logger)
|
||||||
|
{
|
||||||
|
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StartAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return StartAsync(_options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StopAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using System;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Adapter;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
using MQTTnet.Core.Server;
|
||||||
|
|
||||||
|
namespace MQTTnet.AspNetCore
|
||||||
|
{
|
||||||
|
public class MqttWebSocketServerAdapter : IMqttServerAdapter, IDisposable
|
||||||
|
{
|
||||||
|
public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||||
|
|
||||||
|
public Task StartAsync(MqttServerOptions options)
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StopAsync()
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task AcceptWebSocketAsync(WebSocket webSocket)
|
||||||
|
{
|
||||||
|
if (webSocket == null) throw new ArgumentNullException(nameof(webSocket));
|
||||||
|
|
||||||
|
var channel = new MqttWebSocketServerChannel(webSocket);
|
||||||
|
var clientAdapter = new MqttChannelAdapter(channel, new MqttPacketSerializer(), new MqttNetLogger());
|
||||||
|
|
||||||
|
var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);
|
||||||
|
ClientAccepted?.Invoke(this, eventArgs);
|
||||||
|
return eventArgs.SessionTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Channel;
|
||||||
|
using MQTTnet.Implementations;
|
||||||
|
|
||||||
|
namespace MQTTnet.AspNetCore
|
||||||
|
{
|
||||||
|
public class MqttWebSocketServerChannel : IMqttChannel, IDisposable
|
||||||
|
{
|
||||||
|
private WebSocket _webSocket;
|
||||||
|
|
||||||
|
public MqttWebSocketServerChannel(WebSocket webSocket)
|
||||||
|
{
|
||||||
|
_webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
|
||||||
|
|
||||||
|
SendStream = new WebSocketStream(_webSocket);
|
||||||
|
ReceiveStream = SendStream;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream SendStream { get; private set; }
|
||||||
|
public Stream ReceiveStream { get; private set; }
|
||||||
|
|
||||||
|
public Task ConnectAsync()
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DisconnectAsync()
|
||||||
|
{
|
||||||
|
if (_webSocket == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
SendStream?.Dispose();
|
||||||
|
ReceiveStream?.Dispose();
|
||||||
|
|
||||||
|
_webSocket?.Dispose();
|
||||||
|
|
||||||
|
SendStream = null;
|
||||||
|
ReceiveStream = null;
|
||||||
|
_webSocket = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using MQTTnet.Core.Adapter;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.Server;
|
||||||
|
|
||||||
|
namespace MQTTnet.AspNetCore
|
||||||
|
{
|
||||||
|
public static class ServiceCollectionExtensions
|
||||||
|
{
|
||||||
|
public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, MqttServerOptions options)
|
||||||
|
{
|
||||||
|
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||||
|
|
||||||
|
services.AddSingleton(options);
|
||||||
|
services.AddSingleton<IMqttNetLogger>(new MqttNetLogger());
|
||||||
|
services.AddSingleton<MqttHostedServer>();
|
||||||
|
services.AddSingleton<IHostedService>(s => s.GetService<MqttHostedServer>());
|
||||||
|
services.AddSingleton<IMqttServer>(s => s.GetService<MqttHostedServer>());
|
||||||
|
|
||||||
|
services.AddSingleton<MqttWebSocketServerAdapter>();
|
||||||
|
services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttWebSocketServerAdapter>());
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>netcoreapp1.1</TargetFramework>
|
|
||||||
<Authors>Christian Kratky</Authors>
|
|
||||||
<Company>Christian Kratky</Company>
|
|
||||||
<Product>MQTTnet</Product>
|
|
||||||
<Description>MQTTnet is a .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker).</Description>
|
|
||||||
<Copyright>Copyright © Christian Kratky 2016-2017</Copyright>
|
|
||||||
<Version>2.1.1.0</Version>
|
|
||||||
<AssemblyVersion>2.1.1.0</AssemblyVersion>
|
|
||||||
<FileVersion>2.1.1.0</FileVersion>
|
|
||||||
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
|
|
||||||
<AssemblyName>MQTTnet</AssemblyName>
|
|
||||||
<RootNamespace>MQTTnet</RootNamespace>
|
|
||||||
<PackageId>MQTTnet.NetCore</PackageId>
|
|
||||||
<PackageProjectUrl>https://github.com/chkr1011/MQTTnet</PackageProjectUrl>
|
|
||||||
<RepositoryUrl>https://github.com/chkr1011/MQTTnet</RepositoryUrl>
|
|
||||||
<PackageTags>MQTT MQTTClient MQTTServer MQTTBroker Broker</PackageTags>
|
|
||||||
<PackageIconUrl>https://raw.githubusercontent.com/chkr1011/MQTTnet/master/Images/Logo_128x128.png</PackageIconUrl>
|
|
||||||
<PackageLicenseUrl>https://github.com/chkr1011/MQTTnet/blob/master/LICENSE</PackageLicenseUrl>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|AnyCPU'" />
|
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|x64'" />
|
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|x86'" />
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
using System;
|
|
||||||
using MQTTnet.Core.Adapter;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
using MQTTnet.Core.Serializer;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public class MqttClientFactory
|
|
||||||
{
|
|
||||||
public MqttClient CreateMqttClient(MqttClientOptions options)
|
|
||||||
{
|
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
|
||||||
|
|
||||||
return new MqttClient(options, new MqttChannelCommunicationAdapter(new MqttTcpChannel(), new DefaultMqttV311PacketSerializer()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Net;
|
|
||||||
using System.Net.Sockets;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using MQTTnet.Core.Adapter;
|
|
||||||
using MQTTnet.Core.Serializer;
|
|
||||||
using MQTTnet.Core.Server;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public sealed class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
|
||||||
{
|
|
||||||
private CancellationTokenSource _cancellationTokenSource;
|
|
||||||
private Socket _socket;
|
|
||||||
|
|
||||||
public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
|
|
||||||
|
|
||||||
public void Start(MqttServerOptions options)
|
|
||||||
{
|
|
||||||
if (_socket != null) throw new InvalidOperationException("Server is already started.");
|
|
||||||
|
|
||||||
_cancellationTokenSource = new CancellationTokenSource();
|
|
||||||
|
|
||||||
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
|
||||||
_socket.Bind(new IPEndPoint(IPAddress.Any, options.Port));
|
|
||||||
_socket.Listen(options.ConnectionBacklog);
|
|
||||||
|
|
||||||
Task.Run(async () => await AcceptConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Stop()
|
|
||||||
{
|
|
||||||
_cancellationTokenSource?.Dispose();
|
|
||||||
_cancellationTokenSource = null;
|
|
||||||
|
|
||||||
_socket?.Dispose();
|
|
||||||
_socket = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
Stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task AcceptConnectionsAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
while (!cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
var clientSocket = await _socket.AcceptAsync();
|
|
||||||
var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket), new DefaultMqttV311PacketSerializer());
|
|
||||||
ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
using System;
|
|
||||||
using MQTTnet.Core.Server;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public class MqttServerFactory
|
|
||||||
{
|
|
||||||
public MqttServer CreateMqttServer(MqttServerOptions options)
|
|
||||||
{
|
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
|
||||||
|
|
||||||
return new MqttServer(options, new MqttServerAdapter());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Net.Sockets;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using MQTTnet.Core.Channel;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
using MQTTnet.Core.Exceptions;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public class MqttTcpChannel : IMqttCommunicationChannel, IDisposable
|
|
||||||
{
|
|
||||||
private readonly Socket _socket;
|
|
||||||
|
|
||||||
public MqttTcpChannel()
|
|
||||||
{
|
|
||||||
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
|
||||||
}
|
|
||||||
|
|
||||||
public MqttTcpChannel(Socket socket)
|
|
||||||
{
|
|
||||||
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task ConnectAsync(MqttClientOptions options)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await _socket.ConnectAsync(options.Server, options.Port);
|
|
||||||
}
|
|
||||||
catch (SocketException exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task DisconnectAsync()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_socket.Dispose();
|
|
||||||
await Task.FromResult(0);
|
|
||||||
}
|
|
||||||
catch (SocketException exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task WriteAsync(byte[] buffer)
|
|
||||||
{
|
|
||||||
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await _socket.SendAsync(new ArraySegment<byte>(buffer), SocketFlags.None);
|
|
||||||
}
|
|
||||||
catch (SocketException exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task ReadAsync(byte[] buffer)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var buffer2 = new ArraySegment<byte>(buffer);
|
|
||||||
await _socket.ReceiveAsync(buffer2, SocketFlags.None);
|
|
||||||
}
|
|
||||||
catch (SocketException exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
_socket?.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
|
||||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
|
||||||
<PropertyGroup>
|
|
||||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
|
||||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
|
||||||
<ProjectGuid>{A480EF90-0EAA-4D9A-B271-47A9C47F6F7D}</ProjectGuid>
|
|
||||||
<OutputType>Library</OutputType>
|
|
||||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
|
||||||
<RootNamespace>MQTTnet</RootNamespace>
|
|
||||||
<AssemblyName>MQTTnet</AssemblyName>
|
|
||||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
|
||||||
<FileAlignment>512</FileAlignment>
|
|
||||||
<TargetFrameworkProfile />
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
|
||||||
<DebugSymbols>true</DebugSymbols>
|
|
||||||
<DebugType>full</DebugType>
|
|
||||||
<Optimize>false</Optimize>
|
|
||||||
<OutputPath>bin\Debug\</OutputPath>
|
|
||||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<WarningLevel>4</WarningLevel>
|
|
||||||
<Prefer32Bit>false</Prefer32Bit>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
|
||||||
<DebugType>pdbonly</DebugType>
|
|
||||||
<Optimize>true</Optimize>
|
|
||||||
<OutputPath>bin\Release\</OutputPath>
|
|
||||||
<DefineConstants>TRACE</DefineConstants>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<WarningLevel>4</WarningLevel>
|
|
||||||
<Prefer32Bit>false</Prefer32Bit>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|AnyCPU'">
|
|
||||||
<OutputPath>bin\Any CPU\</OutputPath>
|
|
||||||
<DefineConstants>TRACE</DefineConstants>
|
|
||||||
<Optimize>true</Optimize>
|
|
||||||
<DebugType>pdbonly</DebugType>
|
|
||||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
|
||||||
<DebugSymbols>true</DebugSymbols>
|
|
||||||
<OutputPath>bin\x86\Debug\</OutputPath>
|
|
||||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
|
||||||
<DebugType>full</DebugType>
|
|
||||||
<PlatformTarget>x86</PlatformTarget>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
|
||||||
<OutputPath>bin\x86\Release\</OutputPath>
|
|
||||||
<DefineConstants>TRACE</DefineConstants>
|
|
||||||
<Optimize>true</Optimize>
|
|
||||||
<DebugType>pdbonly</DebugType>
|
|
||||||
<PlatformTarget>x86</PlatformTarget>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|x86'">
|
|
||||||
<OutputPath>bin\x86\Any CPU\</OutputPath>
|
|
||||||
<DefineConstants>TRACE</DefineConstants>
|
|
||||||
<Optimize>true</Optimize>
|
|
||||||
<DebugType>pdbonly</DebugType>
|
|
||||||
<PlatformTarget>x86</PlatformTarget>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
|
|
||||||
<DebugSymbols>true</DebugSymbols>
|
|
||||||
<OutputPath>bin\x64\Debug\</OutputPath>
|
|
||||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
|
||||||
<DebugType>full</DebugType>
|
|
||||||
<PlatformTarget>x64</PlatformTarget>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
|
|
||||||
<OutputPath>bin\x64\Release\</OutputPath>
|
|
||||||
<DefineConstants>TRACE</DefineConstants>
|
|
||||||
<Optimize>true</Optimize>
|
|
||||||
<DebugType>pdbonly</DebugType>
|
|
||||||
<PlatformTarget>x64</PlatformTarget>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Any CPU|x64'">
|
|
||||||
<OutputPath>bin\x64\Any CPU\</OutputPath>
|
|
||||||
<DefineConstants>TRACE</DefineConstants>
|
|
||||||
<Optimize>true</Optimize>
|
|
||||||
<DebugType>pdbonly</DebugType>
|
|
||||||
<PlatformTarget>x64</PlatformTarget>
|
|
||||||
<ErrorReport>prompt</ErrorReport>
|
|
||||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<Reference Include="System" />
|
|
||||||
<Reference Include="System.Core" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<Compile Include="MqttClientFactory.cs" />
|
|
||||||
<Compile Include="MqttServerAdapter.cs" />
|
|
||||||
<Compile Include="MqttServerFactory.cs" />
|
|
||||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
|
||||||
<Compile Include="MqttTcpChannel.cs" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj">
|
|
||||||
<Project>{2ecb99e4-72d0-4c23-99ba-93d511d3967d}</Project>
|
|
||||||
<Name>MQTTnet.Core</Name>
|
|
||||||
</ProjectReference>
|
|
||||||
</ItemGroup>
|
|
||||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
|
||||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
|
||||||
Other similar extension points exist, see Microsoft.Common.targets.
|
|
||||||
<Target Name="BeforeBuild">
|
|
||||||
</Target>
|
|
||||||
<Target Name="AfterBuild">
|
|
||||||
</Target>
|
|
||||||
-->
|
|
||||||
</Project>
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
using System;
|
|
||||||
using MQTTnet.Core.Adapter;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
using MQTTnet.Core.Serializer;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public class MqttClientFactory
|
|
||||||
{
|
|
||||||
public MqttClient CreateMqttClient(MqttClientOptions options)
|
|
||||||
{
|
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
|
||||||
|
|
||||||
return new MqttClient(options, new MqttChannelCommunicationAdapter(new MqttTcpChannel(), new DefaultMqttV311PacketSerializer()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Net;
|
|
||||||
using System.Net.Sockets;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using MQTTnet.Core.Adapter;
|
|
||||||
using MQTTnet.Core.Serializer;
|
|
||||||
using MQTTnet.Core.Server;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public sealed class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
|
||||||
{
|
|
||||||
private CancellationTokenSource _cancellationTokenSource;
|
|
||||||
private Socket _socket;
|
|
||||||
|
|
||||||
public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
|
|
||||||
|
|
||||||
public void Start(MqttServerOptions options)
|
|
||||||
{
|
|
||||||
if (_socket != null) throw new InvalidOperationException("Server is already started.");
|
|
||||||
|
|
||||||
_cancellationTokenSource = new CancellationTokenSource();
|
|
||||||
|
|
||||||
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
|
||||||
_socket.Bind(new IPEndPoint(IPAddress.Any, options.Port));
|
|
||||||
_socket.Listen(options.ConnectionBacklog);
|
|
||||||
|
|
||||||
Task.Run(async () => await AcceptConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Stop()
|
|
||||||
{
|
|
||||||
_cancellationTokenSource?.Dispose();
|
|
||||||
_cancellationTokenSource = null;
|
|
||||||
|
|
||||||
_socket?.Dispose();
|
|
||||||
_socket = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
Stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task AcceptConnectionsAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
while (!cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
var clientSocket = await Task.Factory.FromAsync(_socket.BeginAccept, _socket.EndAccept, null);
|
|
||||||
var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket), new DefaultMqttV311PacketSerializer());
|
|
||||||
ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
using System;
|
|
||||||
using MQTTnet.Core.Server;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public class MqttServerFactory
|
|
||||||
{
|
|
||||||
public MqttServer CreateMqttServer(MqttServerOptions options)
|
|
||||||
{
|
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
|
||||||
|
|
||||||
return new MqttServer(options, new MqttServerAdapter());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Net.Sockets;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using MQTTnet.Core.Channel;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
using MQTTnet.Core.Exceptions;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public class MqttTcpChannel : IMqttCommunicationChannel, IDisposable
|
|
||||||
{
|
|
||||||
private readonly Socket _socket;
|
|
||||||
|
|
||||||
public MqttTcpChannel()
|
|
||||||
{
|
|
||||||
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
|
||||||
}
|
|
||||||
|
|
||||||
public MqttTcpChannel(Socket socket)
|
|
||||||
{
|
|
||||||
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task ConnectAsync(MqttClientOptions options)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await Task.Factory.FromAsync(_socket.BeginConnect, _socket.EndConnect, options.Server, options.Port, null);
|
|
||||||
}
|
|
||||||
catch (SocketException exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task DisconnectAsync()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await Task.Factory.FromAsync(_socket.BeginDisconnect, _socket.EndDisconnect, true, null);
|
|
||||||
}
|
|
||||||
catch (SocketException exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task WriteAsync(byte[] buffer)
|
|
||||||
{
|
|
||||||
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await Task.Factory.FromAsync(
|
|
||||||
// ReSharper disable once AssignNullToNotNullAttribute
|
|
||||||
_socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, null, null),
|
|
||||||
_socket.EndSend);
|
|
||||||
}
|
|
||||||
catch (SocketException exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task ReadAsync(byte[] buffer)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await Task.Factory.FromAsync(
|
|
||||||
// ReSharper disable once AssignNullToNotNullAttribute
|
|
||||||
_socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, null, null),
|
|
||||||
_socket.EndReceive);
|
|
||||||
}
|
|
||||||
catch (SocketException exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
_socket?.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
using System.Reflection;
|
|
||||||
using System.Runtime.InteropServices;
|
|
||||||
|
|
||||||
[assembly: AssemblyTitle("MQTTnet")]
|
|
||||||
[assembly: AssemblyDescription("MQTTnet for .NET Framework")]
|
|
||||||
[assembly: AssemblyConfiguration("")]
|
|
||||||
[assembly: AssemblyCompany("Christian Kratky")]
|
|
||||||
[assembly: AssemblyProduct("MQTTnet")]
|
|
||||||
[assembly: AssemblyCopyright("Copyright © Christian Kratky 2016-2017")]
|
|
||||||
[assembly: AssemblyTrademark("")]
|
|
||||||
[assembly: AssemblyCulture("")]
|
|
||||||
[assembly: ComVisible(false)]
|
|
||||||
[assembly: Guid("a480ef90-0eaa-4d9a-b271-47a9c47f6f7d")]
|
|
||||||
[assembly: AssemblyVersion("2.1.1.0")]
|
|
||||||
[assembly: AssemblyFileVersion("2.1.1.0")]
|
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
|
||||||
|
namespace MQTTnet.Diagnostics
|
||||||
|
{
|
||||||
|
public static class MqttNetConsoleLogger
|
||||||
|
{
|
||||||
|
private static readonly object Lock = new object();
|
||||||
|
|
||||||
|
public static void ForwardToConsole()
|
||||||
|
{
|
||||||
|
MqttNetGlobalLog.LogMessagePublished -= PrintToConsole;
|
||||||
|
MqttNetGlobalLog.LogMessagePublished += PrintToConsole;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void PrintToConsole(object sender, MqttNetLogMessagePublishedEventArgs e)
|
||||||
|
{
|
||||||
|
var output = new StringBuilder();
|
||||||
|
output.AppendLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
|
||||||
|
if (e.TraceMessage.Exception != null)
|
||||||
|
{
|
||||||
|
output.AppendLine(e.TraceMessage.Exception.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (Lock)
|
||||||
|
{
|
||||||
|
var backupColor = Console.ForegroundColor;
|
||||||
|
switch (e.TraceMessage.Level)
|
||||||
|
{
|
||||||
|
case MqttNetLogLevel.Error:
|
||||||
|
Console.ForegroundColor = ConsoleColor.Red;
|
||||||
|
break;
|
||||||
|
case MqttNetLogLevel.Warning:
|
||||||
|
Console.ForegroundColor = ConsoleColor.Yellow;
|
||||||
|
break;
|
||||||
|
case MqttNetLogLevel.Info:
|
||||||
|
Console.ForegroundColor = ConsoleColor.Green;
|
||||||
|
break;
|
||||||
|
case MqttNetLogLevel.Verbose:
|
||||||
|
Console.ForegroundColor = ConsoleColor.Gray;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.Write(output);
|
||||||
|
Console.ForegroundColor = backupColor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace MQTTnet
|
||||||
|
{
|
||||||
|
public static class TargetFrameworkInfoProvider
|
||||||
|
{
|
||||||
|
public static string TargetFramework
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
#if NET452
|
||||||
|
return "net452";
|
||||||
|
#elif NET461
|
||||||
|
return "net461";
|
||||||
|
#elif NETSTANDARD1_3
|
||||||
|
return "netstandard1.3";
|
||||||
|
#elif NETSTANDARD2_0
|
||||||
|
return "netstandard2.0";
|
||||||
|
#elif WINDOWS_UWP
|
||||||
|
return "uap10.0";
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using System;
|
||||||
|
using MQTTnet.Core.Adapter;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
|
||||||
|
namespace MQTTnet.Implementations
|
||||||
|
{
|
||||||
|
public class MqttClientAdapterFactory : IMqttClientAdapterFactory
|
||||||
|
{
|
||||||
|
public IMqttChannelAdapter CreateClientAdapter(IMqttClientChannelOptions options, IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||||
|
|
||||||
|
switch (options)
|
||||||
|
{
|
||||||
|
case MqttClientTcpOptions tcpOptions:
|
||||||
|
return new MqttChannelAdapter(new MqttTcpChannel(tcpOptions), new MqttPacketSerializer(), logger);
|
||||||
|
case MqttClientWebSocketOptions webSocketOptions:
|
||||||
|
return new MqttChannelAdapter(new MqttWebSocketChannel(webSocketOptions), new MqttPacketSerializer(), logger);
|
||||||
|
default:
|
||||||
|
throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
#if WINDOWS_UWP
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Adapter;
|
||||||
|
using MQTTnet.Core.Server;
|
||||||
|
using Windows.Networking.Sockets;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
|
||||||
|
namespace MQTTnet.Implementations
|
||||||
|
{
|
||||||
|
public class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
||||||
|
{
|
||||||
|
private readonly IMqttNetLogger _logger;
|
||||||
|
private StreamSocketListener _defaultEndpointSocket;
|
||||||
|
|
||||||
|
public MqttServerAdapter(IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||||
|
}
|
||||||
|
|
||||||
|
public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||||
|
|
||||||
|
public async Task StartAsync(MqttServerOptions options)
|
||||||
|
{
|
||||||
|
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||||
|
|
||||||
|
if (_defaultEndpointSocket != null) throw new InvalidOperationException("Server is already started.");
|
||||||
|
|
||||||
|
if (options.DefaultEndpointOptions.IsEnabled)
|
||||||
|
{
|
||||||
|
_defaultEndpointSocket = new StreamSocketListener();
|
||||||
|
await _defaultEndpointSocket.BindServiceNameAsync(options.GetDefaultEndpointPort().ToString(), SocketProtectionLevel.PlainSocket);
|
||||||
|
_defaultEndpointSocket.ConnectionReceived += AcceptDefaultEndpointConnectionsAsync;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.TlsEndpointOptions.IsEnabled)
|
||||||
|
{
|
||||||
|
throw new NotSupportedException("TLS servers are not supported for UWP apps.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StopAsync()
|
||||||
|
{
|
||||||
|
if (_defaultEndpointSocket != null)
|
||||||
|
{
|
||||||
|
_defaultEndpointSocket.ConnectionReceived -= AcceptDefaultEndpointConnectionsAsync;
|
||||||
|
}
|
||||||
|
|
||||||
|
_defaultEndpointSocket?.Dispose();
|
||||||
|
_defaultEndpointSocket = null;
|
||||||
|
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
StopAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(args.Socket), new MqttPacketSerializer(), _logger);
|
||||||
|
ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
_logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
#if NET452 || NET461 || NETSTANDARD1_3 || NETSTANDARD2_0
|
||||||
|
using System;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Security.Authentication;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Adapter;
|
||||||
|
using MQTTnet.Core.Server;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
|
||||||
|
namespace MQTTnet.Implementations
|
||||||
|
{
|
||||||
|
public class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
||||||
|
{
|
||||||
|
private readonly IMqttNetLogger _logger;
|
||||||
|
|
||||||
|
private CancellationTokenSource _cancellationTokenSource;
|
||||||
|
private Socket _defaultEndpointSocket;
|
||||||
|
private Socket _tlsEndpointSocket;
|
||||||
|
private X509Certificate2 _tlsCertificate;
|
||||||
|
|
||||||
|
public MqttServerAdapter(IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||||
|
}
|
||||||
|
|
||||||
|
public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||||
|
|
||||||
|
public Task StartAsync(MqttServerOptions options)
|
||||||
|
{
|
||||||
|
if (_cancellationTokenSource != null) throw new InvalidOperationException("Server is already started.");
|
||||||
|
|
||||||
|
_cancellationTokenSource = new CancellationTokenSource();
|
||||||
|
|
||||||
|
if (options.DefaultEndpointOptions.IsEnabled)
|
||||||
|
{
|
||||||
|
_defaultEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||||
|
_defaultEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetDefaultEndpointPort()));
|
||||||
|
_defaultEndpointSocket.Listen(options.ConnectionBacklog);
|
||||||
|
|
||||||
|
Task.Run(() => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.TlsEndpointOptions.IsEnabled)
|
||||||
|
{
|
||||||
|
if (options.TlsEndpointOptions.Certificate == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("TLS certificate is not set.");
|
||||||
|
}
|
||||||
|
|
||||||
|
_tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
|
||||||
|
if (!_tlsCertificate.HasPrivateKey)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("The certificate for TLS encryption must contain the private key.");
|
||||||
|
}
|
||||||
|
|
||||||
|
_tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||||
|
_tlsEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetTlsEndpointPort()));
|
||||||
|
_tlsEndpointSocket.Listen(options.ConnectionBacklog);
|
||||||
|
|
||||||
|
Task.Run(() => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StopAsync()
|
||||||
|
{
|
||||||
|
_cancellationTokenSource?.Cancel(false);
|
||||||
|
_cancellationTokenSource?.Dispose();
|
||||||
|
_cancellationTokenSource = null;
|
||||||
|
|
||||||
|
_defaultEndpointSocket?.Dispose();
|
||||||
|
_defaultEndpointSocket = null;
|
||||||
|
|
||||||
|
_tlsCertificate = null;
|
||||||
|
|
||||||
|
_tlsEndpointSocket?.Dispose();
|
||||||
|
_tlsEndpointSocket = null;
|
||||||
|
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
StopAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//todo: else branch can be used with min dependency NET46
|
||||||
|
#if NET452 || NET461
|
||||||
|
var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
|
||||||
|
#else
|
||||||
|
var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);
|
||||||
|
#endif
|
||||||
|
var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, null), new MqttPacketSerializer(), _logger);
|
||||||
|
ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
_logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
|
||||||
|
|
||||||
|
//excessive CPU consumed if in endless loop of socket errors
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
#if NET452 || NET461
|
||||||
|
var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
|
||||||
|
#else
|
||||||
|
var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
var sslStream = new SslStream(new NetworkStream(clientSocket));
|
||||||
|
await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer(), _logger);
|
||||||
|
ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
_logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at TLS endpoint.");
|
||||||
|
|
||||||
|
//excessive CPU consumed if in endless loop of socket errors
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
#if WINDOWS_UWP
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.InteropServices.WindowsRuntime;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Windows.Networking;
|
||||||
|
using Windows.Networking.Sockets;
|
||||||
|
using Windows.Security.Cryptography.Certificates;
|
||||||
|
using MQTTnet.Core.Channel;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
|
||||||
|
namespace MQTTnet.Implementations
|
||||||
|
{
|
||||||
|
public sealed class MqttTcpChannel : IMqttChannel, IDisposable
|
||||||
|
{
|
||||||
|
private readonly MqttClientTcpOptions _options;
|
||||||
|
private StreamSocket _socket;
|
||||||
|
|
||||||
|
public MqttTcpChannel(MqttClientTcpOptions options)
|
||||||
|
{
|
||||||
|
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttTcpChannel(StreamSocket socket)
|
||||||
|
{
|
||||||
|
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
||||||
|
|
||||||
|
CreateStreams();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream SendStream { get; private set; }
|
||||||
|
public Stream ReceiveStream { get; private set; }
|
||||||
|
|
||||||
|
public static Func<MqttClientTcpOptions, IEnumerable<ChainValidationResult>> CustomIgnorableServerCertificateErrorsResolver { get; set; }
|
||||||
|
|
||||||
|
public async Task ConnectAsync()
|
||||||
|
{
|
||||||
|
if (_socket == null)
|
||||||
|
{
|
||||||
|
_socket = new StreamSocket();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_options.TlsOptions.UseTls)
|
||||||
|
{
|
||||||
|
await _socket.ConnectAsync(new HostName(_options.Server), _options.GetPort().ToString());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_socket.Control.ClientCertificate = LoadCertificate(_options);
|
||||||
|
|
||||||
|
foreach (var ignorableChainValidationResult in ResolveIgnorableServerCertificateErrors())
|
||||||
|
{
|
||||||
|
_socket.Control.IgnorableServerCertificateErrors.Add(ignorableChainValidationResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _socket.ConnectAsync(new HostName(_options.Server), _options.GetPort().ToString(), SocketProtectionLevel.Tls12);
|
||||||
|
}
|
||||||
|
|
||||||
|
CreateStreams();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task DisconnectAsync()
|
||||||
|
{
|
||||||
|
Dispose();
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
SendStream?.Dispose();
|
||||||
|
SendStream = null;
|
||||||
|
|
||||||
|
ReceiveStream?.Dispose();
|
||||||
|
ReceiveStream = null;
|
||||||
|
|
||||||
|
_socket?.Dispose();
|
||||||
|
_socket = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CreateStreams()
|
||||||
|
{
|
||||||
|
SendStream = _socket.OutputStream.AsStreamForWrite();
|
||||||
|
ReceiveStream = _socket.InputStream.AsStreamForRead();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Certificate LoadCertificate(MqttClientTcpOptions options)
|
||||||
|
{
|
||||||
|
if (options.TlsOptions.Certificates == null || !options.TlsOptions.Certificates.Any())
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.TlsOptions.Certificates.Count > 1)
|
||||||
|
{
|
||||||
|
throw new NotSupportedException("Only one client certificate is supported for UWP.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Certificate(options.TlsOptions.Certificates.First().AsBuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
private IEnumerable<ChainValidationResult> ResolveIgnorableServerCertificateErrors()
|
||||||
|
{
|
||||||
|
if (CustomIgnorableServerCertificateErrorsResolver != null)
|
||||||
|
{
|
||||||
|
return CustomIgnorableServerCertificateErrorsResolver(_options);
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = new List<ChainValidationResult>();
|
||||||
|
|
||||||
|
if (_options.TlsOptions.IgnoreCertificateRevocationErrors)
|
||||||
|
{
|
||||||
|
result.Add(ChainValidationResult.RevocationInformationMissing);
|
||||||
|
//_socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Revoked); Not supported.
|
||||||
|
result.Add(ChainValidationResult.RevocationFailure);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_options.TlsOptions.IgnoreCertificateChainErrors)
|
||||||
|
{
|
||||||
|
result.Add(ChainValidationResult.IncompleteChain);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_options.TlsOptions.AllowUntrustedCertificates)
|
||||||
|
{
|
||||||
|
result.Add(ChainValidationResult.Untrusted);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
#if NET452 || NET461 || NETSTANDARD1_3 || NETSTANDARD2_0
|
||||||
|
using System;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Security.Authentication;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Channel;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace MQTTnet.Implementations
|
||||||
|
{
|
||||||
|
public sealed class MqttTcpChannel : IMqttChannel, IDisposable
|
||||||
|
{
|
||||||
|
private readonly MqttClientTcpOptions _options;
|
||||||
|
|
||||||
|
//todo: this can be used with min dependency NetStandard1.6
|
||||||
|
#if NET452 || NET461
|
||||||
|
// ReSharper disable once MemberCanBePrivate.Global
|
||||||
|
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
|
||||||
|
public static int BufferSize { get; set; } = 4096 * 20; // Can be changed for fine tuning by library user.
|
||||||
|
#endif
|
||||||
|
|
||||||
|
private Socket _socket;
|
||||||
|
private SslStream _sslStream;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// called on client sockets are created in connect
|
||||||
|
/// </summary>
|
||||||
|
public MqttTcpChannel(MqttClientTcpOptions options)
|
||||||
|
{
|
||||||
|
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// called on server, sockets are passed in
|
||||||
|
/// connect will not be called
|
||||||
|
/// </summary>
|
||||||
|
public MqttTcpChannel(Socket socket, SslStream sslStream)
|
||||||
|
{
|
||||||
|
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
||||||
|
_sslStream = sslStream;
|
||||||
|
|
||||||
|
CreateStreams(socket, sslStream);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream SendStream { get; private set; }
|
||||||
|
public Stream ReceiveStream { get; private set; }
|
||||||
|
|
||||||
|
public static Func<X509Certificate, X509Chain, SslPolicyErrors, MqttClientTcpOptions, bool> CustomCertificateValidationCallback { get; set; }
|
||||||
|
|
||||||
|
public async Task ConnectAsync()
|
||||||
|
{
|
||||||
|
if (_socket == null)
|
||||||
|
{
|
||||||
|
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||||
|
}
|
||||||
|
|
||||||
|
//todo: else brach can be used with min dependency NET46
|
||||||
|
#if NET452 || NET461
|
||||||
|
await Task.Factory.FromAsync(_socket.BeginConnect, _socket.EndConnect, _options.Server, _options.GetPort(), null).ConfigureAwait(false);
|
||||||
|
#else
|
||||||
|
await _socket.ConnectAsync(_options.Server, _options.GetPort()).ConfigureAwait(false);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if (_options.TlsOptions.UseTls)
|
||||||
|
{
|
||||||
|
_sslStream = new SslStream(new NetworkStream(_socket, true), false, InternalUserCertificateValidationCallback);
|
||||||
|
await _sslStream.AuthenticateAsClientAsync(_options.Server, LoadCertificates(_options), SslProtocols.Tls12, _options.TlsOptions.IgnoreCertificateRevocationErrors).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
CreateStreams(_socket, _sslStream);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task DisconnectAsync()
|
||||||
|
{
|
||||||
|
Dispose();
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_socket?.Dispose();
|
||||||
|
_socket = null;
|
||||||
|
|
||||||
|
_sslStream?.Dispose();
|
||||||
|
_sslStream = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool InternalUserCertificateValidationCallback(object sender, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
|
||||||
|
{
|
||||||
|
if (CustomCertificateValidationCallback != null)
|
||||||
|
{
|
||||||
|
return CustomCertificateValidationCallback(x509Certificate, chain, sslPolicyErrors, _options);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sslPolicyErrors == SslPolicyErrors.None)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (chain.ChainStatus.Any(c => c.Status == X509ChainStatusFlags.RevocationStatusUnknown || c.Status == X509ChainStatusFlags.Revoked || c.Status == X509ChainStatusFlags.RevocationStatusUnknown))
|
||||||
|
{
|
||||||
|
if (!_options.TlsOptions.IgnoreCertificateRevocationErrors)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (chain.ChainStatus.Any(c => c.Status == X509ChainStatusFlags.PartialChain))
|
||||||
|
{
|
||||||
|
if (!_options.TlsOptions.IgnoreCertificateChainErrors)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return _options.TlsOptions.AllowUntrustedCertificates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static X509CertificateCollection LoadCertificates(MqttClientTcpOptions options)
|
||||||
|
{
|
||||||
|
var certificates = new X509CertificateCollection();
|
||||||
|
if (options.TlsOptions.Certificates == null)
|
||||||
|
{
|
||||||
|
return certificates;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var certificate in options.TlsOptions.Certificates)
|
||||||
|
{
|
||||||
|
certificates.Add(new X509Certificate(certificate));
|
||||||
|
}
|
||||||
|
|
||||||
|
return certificates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CreateStreams(Socket socket, Stream sslStream)
|
||||||
|
{
|
||||||
|
var stream = sslStream ?? new NetworkStream(socket);
|
||||||
|
|
||||||
|
//cannot use this as default buffering prevents from receiving the first connect message
|
||||||
|
//need two streams otherwise read and write have to be synchronized
|
||||||
|
|
||||||
|
//todo: if branch can be used with min dependency NetStandard1.6
|
||||||
|
#if NET452 || NET461
|
||||||
|
SendStream = new BufferedStream(stream, BufferSize);
|
||||||
|
ReceiveStream = new BufferedStream(stream, BufferSize);
|
||||||
|
#else
|
||||||
|
SendStream = stream;
|
||||||
|
ReceiveStream = stream;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
using MQTTnet.Core.Channel;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Implementations
|
||||||
|
{
|
||||||
|
public sealed class MqttWebSocketChannel : IMqttChannel, IDisposable
|
||||||
|
{
|
||||||
|
// ReSharper disable once MemberCanBePrivate.Global
|
||||||
|
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
|
||||||
|
public static int BufferSize { get; set; } = 4096 * 20; // Can be changed for fine tuning by library user.
|
||||||
|
|
||||||
|
private readonly MqttClientWebSocketOptions _options;
|
||||||
|
private ClientWebSocket _webSocket;
|
||||||
|
|
||||||
|
public MqttWebSocketChannel(MqttClientWebSocketOptions options)
|
||||||
|
{
|
||||||
|
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream SendStream { get; private set; }
|
||||||
|
public Stream ReceiveStream { get; private set; }
|
||||||
|
|
||||||
|
public async Task ConnectAsync()
|
||||||
|
{
|
||||||
|
var uri = _options.Uri;
|
||||||
|
if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) && !uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
if (_options.TlsOptions?.UseTls == false)
|
||||||
|
{
|
||||||
|
uri = "ws://" + uri;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
uri = "wss://" + uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_webSocket = new ClientWebSocket();
|
||||||
|
|
||||||
|
if (_options.RequestHeaders != null)
|
||||||
|
{
|
||||||
|
foreach (var requestHeader in _options.RequestHeaders)
|
||||||
|
{
|
||||||
|
_webSocket.Options.SetRequestHeader(requestHeader.Key, requestHeader.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_options.SubProtocols != null)
|
||||||
|
{
|
||||||
|
foreach (var subProtocol in _options.SubProtocols)
|
||||||
|
{
|
||||||
|
_webSocket.Options.AddSubProtocol(subProtocol);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_options.CookieContainer != null)
|
||||||
|
{
|
||||||
|
_webSocket.Options.Cookies = _options.CookieContainer;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_options.TlsOptions?.UseTls == true && _options.TlsOptions?.Certificates != null)
|
||||||
|
{
|
||||||
|
_webSocket.Options.ClientCertificates = new X509CertificateCollection();
|
||||||
|
foreach (var certificate in _options.TlsOptions.Certificates)
|
||||||
|
{
|
||||||
|
_webSocket.Options.ClientCertificates.Add(new X509Certificate(certificate));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await _webSocket.ConnectAsync(new Uri(uri), CancellationToken.None).ConfigureAwait(false);
|
||||||
|
|
||||||
|
SendStream = new WebSocketStream(_webSocket);
|
||||||
|
ReceiveStream = SendStream;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DisconnectAsync()
|
||||||
|
{
|
||||||
|
if (_webSocket == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_webSocket.State == WebSocketState.Open || _webSocket.State == WebSocketState.Connecting)
|
||||||
|
{
|
||||||
|
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_webSocket?.Dispose();
|
||||||
|
_webSocket = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Exceptions;
|
||||||
|
|
||||||
|
namespace MQTTnet.Implementations
|
||||||
|
{
|
||||||
|
public class WebSocketStream : Stream
|
||||||
|
{
|
||||||
|
private readonly WebSocket _webSocket;
|
||||||
|
private readonly byte[] _chunkBuffer = new byte[MqttWebSocketChannel.BufferSize];
|
||||||
|
private readonly Queue<byte> _buffer = new Queue<byte>(MqttWebSocketChannel.BufferSize);
|
||||||
|
|
||||||
|
public WebSocketStream(WebSocket webSocket)
|
||||||
|
{
|
||||||
|
_webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanRead => true;
|
||||||
|
|
||||||
|
public override bool CanSeek => false;
|
||||||
|
|
||||||
|
public override bool CanWrite => true;
|
||||||
|
|
||||||
|
public override long Length => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Position
|
||||||
|
{
|
||||||
|
get => throw new NotSupportedException();
|
||||||
|
set => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Flush()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count)
|
||||||
|
{
|
||||||
|
return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var bytesRead = 0;
|
||||||
|
|
||||||
|
// Use existing date from buffer.
|
||||||
|
while (count > 0 && _buffer.Any())
|
||||||
|
{
|
||||||
|
buffer[offset++] = _buffer.Dequeue();
|
||||||
|
count--;
|
||||||
|
bytesRead++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count == 0)
|
||||||
|
{
|
||||||
|
return bytesRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (_webSocket.State == WebSocketState.Open)
|
||||||
|
{
|
||||||
|
await FetchChunkAsync(cancellationToken);
|
||||||
|
|
||||||
|
while (count > 0 && _buffer.Any())
|
||||||
|
{
|
||||||
|
buffer[offset++] = _buffer.Dequeue();
|
||||||
|
count--;
|
||||||
|
bytesRead++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count == 0)
|
||||||
|
{
|
||||||
|
return bytesRead;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_webSocket.State == WebSocketState.Closed)
|
||||||
|
{
|
||||||
|
throw new MqttCommunicationException("WebSocket connection closed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytesRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Write(byte[] buffer, int offset, int count)
|
||||||
|
{
|
||||||
|
WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), WebSocketMessageType.Binary, true, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override long Seek(long offset, SeekOrigin origin)
|
||||||
|
{
|
||||||
|
throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void SetLength(long value)
|
||||||
|
{
|
||||||
|
throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task FetchChunkAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var response = await _webSocket.ReceiveAsync(new ArraySegment<byte>(_chunkBuffer, 0, _chunkBuffer.Length), cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
for (var i = 0; i < response.Count; i++)
|
||||||
|
{
|
||||||
|
var @byte = _chunkBuffer[i];
|
||||||
|
_buffer.Enqueue(@byte);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.MessageType == WebSocketMessageType.Close)
|
||||||
|
{
|
||||||
|
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFrameworks>netstandard1.3;netstandard2.0;net452;net461;uap10.0</TargetFrameworks>
|
||||||
|
<AssemblyName>MQTTnet</AssemblyName>
|
||||||
|
<RootNamespace>MQTTnet</RootNamespace>
|
||||||
|
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
|
||||||
|
<DebugType>Full</DebugType>
|
||||||
|
<AssemblyVersion>2.5.3.0</AssemblyVersion>
|
||||||
|
<FileVersion>2.5.3.0</FileVersion>
|
||||||
|
<Version>0.0.0.0</Version>
|
||||||
|
<Company />
|
||||||
|
<Product />
|
||||||
|
<Description />
|
||||||
|
<Authors />
|
||||||
|
<PackageId />
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(TargetFramework)' == 'uap10.0'">
|
||||||
|
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||||
|
<NugetTargetMoniker>UAP,Version=v10.0</NugetTargetMoniker>
|
||||||
|
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
|
||||||
|
<TargetPlatformVersion>10.0.16299.0</TargetPlatformVersion>
|
||||||
|
<TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion>
|
||||||
|
<TargetFrameworkIdentifier>.NETCore</TargetFrameworkIdentifier>
|
||||||
|
<TargetFrameworkVersion>v5.0</TargetFrameworkVersion>
|
||||||
|
<DefineConstants>$(DefineConstants);WINDOWS_UWP</DefineConstants>
|
||||||
|
<LanguageTargets>$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets</LanguageTargets>
|
||||||
|
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'" />
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup Condition="'$(TargetFramework)'=='netstandard2.0'">
|
||||||
|
<PackageReference Include="System.Net.Security" Version="4.3.2" />
|
||||||
|
<PackageReference Include="System.Net.WebSockets" Version="4.3.0" />
|
||||||
|
<PackageReference Include="System.Net.WebSockets.Client" Version="4.3.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup Condition="'$(TargetFramework)'=='netstandard1.3'">
|
||||||
|
<PackageReference Include="System.Net.Security" Version="4.3.2" />
|
||||||
|
<PackageReference Include="System.Net.WebSockets" Version="4.3.0" />
|
||||||
|
<PackageReference Include="System.Net.WebSockets.Client" Version="4.3.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup Condition="'$(TargetFramework)'=='uap10.0'">
|
||||||
|
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="5.4.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup Condition="'$(TargetFramework)'=='net452'">
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup Condition="'$(TargetFramework)'=='net461'">
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using MQTTnet.Core.Adapter;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
using MQTTnet.Implementations;
|
||||||
|
using MQTTnet.Core.ManagedClient;
|
||||||
|
using MQTTnet.Core.Server;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
|
||||||
|
namespace MQTTnet
|
||||||
|
{
|
||||||
|
public class MqttFactory : IMqttClientFactory, IMqttServerFactory
|
||||||
|
{
|
||||||
|
public IMqttClient CreateMqttClient()
|
||||||
|
{
|
||||||
|
return CreateMqttClient(new MqttNetLogger());
|
||||||
|
}
|
||||||
|
|
||||||
|
public IMqttClient CreateMqttClient(IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
if (logger == null) throw new ArgumentNullException(nameof(logger));
|
||||||
|
|
||||||
|
return new MqttClient(new MqttClientAdapterFactory(), logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IManagedMqttClient CreateManagedMqttClient()
|
||||||
|
{
|
||||||
|
return new ManagedMqttClient(CreateMqttClient(), new MqttNetLogger());
|
||||||
|
}
|
||||||
|
|
||||||
|
public IManagedMqttClient CreateManagedMqttClient(IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
if (logger == null) throw new ArgumentNullException(nameof(logger));
|
||||||
|
|
||||||
|
return new ManagedMqttClient(CreateMqttClient(), logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IMqttServer CreateMqttServer()
|
||||||
|
{
|
||||||
|
var logger = new MqttNetLogger();
|
||||||
|
return CreateMqttServer(new List<IMqttServerAdapter> { new MqttServerAdapter(logger) }, logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IMqttServer CreateMqttServer(IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
if (adapters == null) throw new ArgumentNullException(nameof(adapters));
|
||||||
|
if (logger == null) throw new ArgumentNullException(nameof(logger));
|
||||||
|
|
||||||
|
return new MqttServer(adapters, logger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
using System;
|
|
||||||
using MQTTnet.Core.Adapter;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
using MQTTnet.Core.Serializer;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public class MqttClientFactory
|
|
||||||
{
|
|
||||||
public MqttClient CreateMqttClient(MqttClientOptions options)
|
|
||||||
{
|
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
|
||||||
|
|
||||||
return new MqttClient(options, new MqttChannelCommunicationAdapter(new MqttTcpChannel(), new DefaultMqttV311PacketSerializer()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Threading;
|
|
||||||
using Windows.Networking.Sockets;
|
|
||||||
using MQTTnet.Core.Adapter;
|
|
||||||
using MQTTnet.Core.Serializer;
|
|
||||||
using MQTTnet.Core.Server;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public sealed class MqttServerAdapter : IMqttServerAdapter, IDisposable
|
|
||||||
{
|
|
||||||
private CancellationTokenSource _cancellationTokenSource;
|
|
||||||
private StreamSocketListener _socket;
|
|
||||||
|
|
||||||
public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
|
|
||||||
|
|
||||||
public void Start(MqttServerOptions options)
|
|
||||||
{
|
|
||||||
if (_socket != null) throw new InvalidOperationException("Server is already started.");
|
|
||||||
|
|
||||||
_cancellationTokenSource = new CancellationTokenSource();
|
|
||||||
|
|
||||||
_socket = new StreamSocketListener();
|
|
||||||
_socket.BindServiceNameAsync(options.Port.ToString()).AsTask().Wait();
|
|
||||||
_socket.ConnectionReceived += ConnectionReceived;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
|
|
||||||
{
|
|
||||||
var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(args.Socket), new DefaultMqttV311PacketSerializer());
|
|
||||||
|
|
||||||
var identifier = $"{args.Socket.Information.RemoteAddress}:{args.Socket.Information.RemotePort}";
|
|
||||||
ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(identifier, clientAdapter));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Stop()
|
|
||||||
{
|
|
||||||
_cancellationTokenSource?.Dispose();
|
|
||||||
|
|
||||||
if (_socket != null)
|
|
||||||
{
|
|
||||||
_socket.ConnectionReceived -= ConnectionReceived;
|
|
||||||
}
|
|
||||||
|
|
||||||
_socket?.Dispose();
|
|
||||||
_socket = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
Stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
using System;
|
|
||||||
using MQTTnet.Core.Server;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public class MqttServerFactory
|
|
||||||
{
|
|
||||||
public MqttServer CreateMqttServer(MqttServerOptions options)
|
|
||||||
{
|
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
|
||||||
|
|
||||||
return new MqttServer(options, new MqttServerAdapter());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Runtime.InteropServices.WindowsRuntime;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using Windows.Networking;
|
|
||||||
using Windows.Networking.Sockets;
|
|
||||||
using Windows.Storage.Streams;
|
|
||||||
using MQTTnet.Core.Channel;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
using Buffer = Windows.Storage.Streams.Buffer;
|
|
||||||
|
|
||||||
namespace MQTTnet
|
|
||||||
{
|
|
||||||
public sealed class MqttTcpChannel : IMqttCommunicationChannel, IDisposable
|
|
||||||
{
|
|
||||||
private readonly StreamSocket _socket;
|
|
||||||
|
|
||||||
public MqttTcpChannel()
|
|
||||||
{
|
|
||||||
_socket = new StreamSocket();
|
|
||||||
}
|
|
||||||
|
|
||||||
public MqttTcpChannel(StreamSocket socket)
|
|
||||||
{
|
|
||||||
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task ConnectAsync(MqttClientOptions options)
|
|
||||||
{
|
|
||||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
|
||||||
|
|
||||||
await _socket.ConnectAsync(new HostName(options.Server), options.Port.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task DisconnectAsync()
|
|
||||||
{
|
|
||||||
await _socket.CancelIOAsync();
|
|
||||||
_socket.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task WriteAsync(byte[] buffer)
|
|
||||||
{
|
|
||||||
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
|
|
||||||
|
|
||||||
await _socket.OutputStream.WriteAsync(buffer.AsBuffer());
|
|
||||||
await _socket.OutputStream.FlushAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task ReadAsync(byte[] buffer)
|
|
||||||
{
|
|
||||||
var buffer2 = new Buffer((uint)buffer.Length);
|
|
||||||
await _socket.InputStream.ReadAsync(buffer2, (uint)buffer.Length, InputStreamOptions.None);
|
|
||||||
|
|
||||||
var array2 = buffer2.ToArray();
|
|
||||||
Array.Copy(array2, buffer, array2.Length);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
_socket?.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
using System.Reflection;
|
|
||||||
using System.Runtime.InteropServices;
|
|
||||||
|
|
||||||
[assembly: AssemblyTitle("MQTTnet")]
|
|
||||||
[assembly: AssemblyDescription("MQTTnet for Universal Windows")]
|
|
||||||
[assembly: AssemblyConfiguration("")]
|
|
||||||
[assembly: AssemblyCompany("Christian Kratky")]
|
|
||||||
[assembly: AssemblyProduct("MQTTnet")]
|
|
||||||
[assembly: AssemblyCopyright("Copyright © Christian Kratky 2016-2017")]
|
|
||||||
[assembly: AssemblyTrademark("")]
|
|
||||||
[assembly: AssemblyCulture("")]
|
|
||||||
[assembly: ComVisible(false)]
|
|
||||||
[assembly: AssemblyVersion("2.1.1.0")]
|
|
||||||
[assembly: AssemblyFileVersion("2.1.1.0")]
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
|
|
||||||
<Library Name="MQTTnet.Universal">
|
|
||||||
</Library>
|
|
||||||
</Directives>
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
{
|
|
||||||
"dependencies": {
|
|
||||||
"Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0"
|
|
||||||
},
|
|
||||||
"frameworks": {
|
|
||||||
"uap10.0": {},
|
|
||||||
"netstandard1.1": {}
|
|
||||||
},
|
|
||||||
"runtimes": {
|
|
||||||
"win10-arm": {},
|
|
||||||
"win10-arm-aot": {},
|
|
||||||
"win10-x86": {},
|
|
||||||
"win10-x86-aot": {},
|
|
||||||
"win10-x64": {},
|
|
||||||
"win10-x64-aot": {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 1.2 KiB |
@@ -1,6 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2017 Christian
|
Copyright (c) 2017 Christian Kratky
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Packets;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Adapter
|
||||||
|
{
|
||||||
|
public interface IMqttChannelAdapter
|
||||||
|
{
|
||||||
|
IMqttPacketSerializer PacketSerializer { get; }
|
||||||
|
|
||||||
|
Task ConnectAsync(TimeSpan timeout);
|
||||||
|
|
||||||
|
Task DisconnectAsync(TimeSpan timeout);
|
||||||
|
|
||||||
|
Task SendPacketsAsync(TimeSpan timeout, CancellationToken cancellationToken, IEnumerable<MqttBasePacket> packets);
|
||||||
|
|
||||||
|
Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
using MQTTnet.Core.Packets;
|
|
||||||
|
|
||||||
namespace MQTTnet.Core.Adapter
|
|
||||||
{
|
|
||||||
public interface IMqttCommunicationAdapter
|
|
||||||
{
|
|
||||||
Task ConnectAsync(MqttClientOptions options, TimeSpan timeout);
|
|
||||||
|
|
||||||
Task DisconnectAsync();
|
|
||||||
|
|
||||||
Task SendPacketAsync(MqttBasePacket packet, TimeSpan timeout);
|
|
||||||
|
|
||||||
Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Core.Server;
|
using MQTTnet.Core.Server;
|
||||||
|
|
||||||
namespace MQTTnet.Core.Adapter
|
namespace MQTTnet.Core.Adapter
|
||||||
{
|
{
|
||||||
public interface IMqttServerAdapter
|
public interface IMqttServerAdapter
|
||||||
{
|
{
|
||||||
event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
|
event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||||
|
|
||||||
void Start(MqttServerOptions options);
|
Task StartAsync(MqttServerOptions options);
|
||||||
|
Task StopAsync();
|
||||||
void Stop();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Channel;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.Exceptions;
|
||||||
|
using MQTTnet.Core.Internal;
|
||||||
|
using MQTTnet.Core.Packets;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Adapter
|
||||||
|
{
|
||||||
|
public class MqttChannelAdapter : IMqttChannelAdapter
|
||||||
|
{
|
||||||
|
private const uint ErrorOperationAborted = 0x800703E3;
|
||||||
|
|
||||||
|
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
|
||||||
|
private readonly IMqttNetLogger _logger;
|
||||||
|
private readonly IMqttChannel _channel;
|
||||||
|
|
||||||
|
public MqttChannelAdapter(IMqttChannel channel, IMqttPacketSerializer serializer, IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||||
|
_channel = channel ?? throw new ArgumentNullException(nameof(channel));
|
||||||
|
PacketSerializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
|
||||||
|
}
|
||||||
|
|
||||||
|
public IMqttPacketSerializer PacketSerializer { get; }
|
||||||
|
|
||||||
|
public async Task ConnectAsync(TimeSpan timeout)
|
||||||
|
{
|
||||||
|
_logger.Info<MqttChannelAdapter>("Connecting [Timeout={0}]", timeout);
|
||||||
|
|
||||||
|
await ExecuteAndWrapExceptionAsync(() => _channel.ConnectAsync().TimeoutAfter(timeout));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DisconnectAsync(TimeSpan timeout)
|
||||||
|
{
|
||||||
|
_logger.Info<MqttChannelAdapter>("Disconnecting [Timeout={0}]", timeout);
|
||||||
|
|
||||||
|
await ExecuteAndWrapExceptionAsync(() => _channel.DisconnectAsync().TimeoutAfter(timeout));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendPacketsAsync(TimeSpan timeout, CancellationToken cancellationToken, IEnumerable<MqttBasePacket> packets)
|
||||||
|
{
|
||||||
|
await ExecuteAndWrapExceptionAsync(async () =>
|
||||||
|
{
|
||||||
|
await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var packet in packets)
|
||||||
|
{
|
||||||
|
if (packet == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Trace<MqttChannelAdapter>("TX >>> {0} [Timeout={1}]", packet, timeout);
|
||||||
|
|
||||||
|
var writeBuffer = PacketSerializer.Serialize(packet);
|
||||||
|
await _channel.SendStream.WriteAsync(writeBuffer, 0, writeBuffer.Length, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (timeout > TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
await _channel.SendStream.FlushAsync(cancellationToken).TimeoutAfter(timeout).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _channel.SendStream.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_semaphore.Release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
MqttBasePacket packet = null;
|
||||||
|
await ExecuteAndWrapExceptionAsync(async () =>
|
||||||
|
{
|
||||||
|
ReceivedMqttPacket receivedMqttPacket = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (timeout > TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
receivedMqttPacket = await ReceiveAsync(_channel.ReceiveStream, cancellationToken).TimeoutAfter(timeout).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
receivedMqttPacket = await ReceiveAsync(_channel.ReceiveStream, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (receivedMqttPacket == null || cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw new TaskCanceledException();
|
||||||
|
}
|
||||||
|
|
||||||
|
packet = PacketSerializer.Deserialize(receivedMqttPacket);
|
||||||
|
if (packet == null)
|
||||||
|
{
|
||||||
|
throw new MqttProtocolViolationException("Received malformed packet.");
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Trace<MqttChannelAdapter>("RX <<< {0}", packet);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
receivedMqttPacket?.Dispose();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<ReceivedMqttPacket> ReceiveAsync(Stream stream, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var header = MqttPacketReader.ReadHeaderFromSource(stream, cancellationToken);
|
||||||
|
if (header == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (header.BodyLength == 0)
|
||||||
|
{
|
||||||
|
return new ReceivedMqttPacket(header, new MemoryStream(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
var body = new byte[header.BodyLength];
|
||||||
|
|
||||||
|
var offset = 0;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
var readBytesCount = await stream.ReadAsync(body, offset, body.Length - offset, cancellationToken).ConfigureAwait(false);
|
||||||
|
offset += readBytesCount;
|
||||||
|
} while (offset < header.BodyLength);
|
||||||
|
|
||||||
|
return new ReceivedMqttPacket(header, new MemoryStream(body, 0, body.Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task ExecuteAndWrapExceptionAsync(Func<Task> action)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await action().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (MqttCommunicationTimedOutException)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (MqttCommunicationException)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (COMException comException)
|
||||||
|
{
|
||||||
|
if ((uint)comException.HResult == ErrorOperationAborted)
|
||||||
|
{
|
||||||
|
throw new OperationCanceledException();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new MqttCommunicationException(comException);
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
throw new MqttCommunicationException(exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Packets;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Adapter
|
||||||
|
{
|
||||||
|
public static class MqttChannelAdapterExtensions
|
||||||
|
{
|
||||||
|
public static Task SendPacketsAsync(this IMqttChannelAdapter adapter, TimeSpan timeout, CancellationToken cancellationToken, params MqttBasePacket[] packets)
|
||||||
|
{
|
||||||
|
if (adapter == null) throw new ArgumentNullException(nameof(adapter));
|
||||||
|
|
||||||
|
return adapter.SendPacketsAsync(timeout, cancellationToken, packets);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using MQTTnet.Core.Channel;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
using MQTTnet.Core.Diagnostics;
|
|
||||||
using MQTTnet.Core.Exceptions;
|
|
||||||
using MQTTnet.Core.Packets;
|
|
||||||
using MQTTnet.Core.Serializer;
|
|
||||||
|
|
||||||
namespace MQTTnet.Core.Adapter
|
|
||||||
{
|
|
||||||
public class MqttChannelCommunicationAdapter : IMqttCommunicationAdapter
|
|
||||||
{
|
|
||||||
private readonly IMqttPacketSerializer _serializer;
|
|
||||||
private readonly IMqttCommunicationChannel _channel;
|
|
||||||
|
|
||||||
public MqttChannelCommunicationAdapter(IMqttCommunicationChannel channel, IMqttPacketSerializer serializer)
|
|
||||||
{
|
|
||||||
_channel = channel ?? throw new ArgumentNullException(nameof(channel));
|
|
||||||
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task ConnectAsync(MqttClientOptions options, TimeSpan timeout)
|
|
||||||
{
|
|
||||||
var task = _channel.ConnectAsync(options);
|
|
||||||
if (await Task.WhenAny(Task.Delay(timeout), task) != task)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationTimedOutException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task DisconnectAsync()
|
|
||||||
{
|
|
||||||
await _channel.DisconnectAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task SendPacketAsync(MqttBasePacket packet, TimeSpan timeout)
|
|
||||||
{
|
|
||||||
MqttTrace.Information(nameof(MqttChannelCommunicationAdapter), $"TX >>> {packet} [Timeout={timeout}]");
|
|
||||||
|
|
||||||
bool hasTimeout;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var task = _serializer.SerializeAsync(packet, _channel);
|
|
||||||
hasTimeout = await Task.WhenAny(Task.Delay(timeout), task) != task;
|
|
||||||
}
|
|
||||||
catch (Exception exception)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationException(exception);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasTimeout)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationTimedOutException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout)
|
|
||||||
{
|
|
||||||
MqttBasePacket packet;
|
|
||||||
if (timeout > TimeSpan.Zero)
|
|
||||||
{
|
|
||||||
var workerTask = _serializer.DeserializeAsync(_channel);
|
|
||||||
var timeoutTask = Task.Delay(timeout);
|
|
||||||
var hasTimeout = Task.WhenAny(timeoutTask, workerTask) == timeoutTask;
|
|
||||||
|
|
||||||
if (hasTimeout)
|
|
||||||
{
|
|
||||||
throw new MqttCommunicationTimedOutException();
|
|
||||||
}
|
|
||||||
|
|
||||||
packet = workerTask.Result;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
packet = await _serializer.DeserializeAsync(_channel);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (packet == null)
|
|
||||||
{
|
|
||||||
throw new MqttProtocolViolationException("Received malformed packet.");
|
|
||||||
}
|
|
||||||
|
|
||||||
MqttTrace.Information(nameof(MqttChannelCommunicationAdapter), $"RX <<< {packet}");
|
|
||||||
return packet;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
using System;
|
|
||||||
|
|
||||||
namespace MQTTnet.Core.Adapter
|
|
||||||
{
|
|
||||||
public class MqttClientConnectedEventArgs : EventArgs
|
|
||||||
{
|
|
||||||
public MqttClientConnectedEventArgs(string identifier, IMqttCommunicationAdapter clientAdapter)
|
|
||||||
{
|
|
||||||
Identifier = identifier ?? throw new ArgumentNullException(nameof(identifier));
|
|
||||||
ClientAdapter = clientAdapter ?? throw new ArgumentNullException(nameof(clientAdapter));
|
|
||||||
}
|
|
||||||
|
|
||||||
public string Identifier { get; }
|
|
||||||
|
|
||||||
public IMqttCommunicationAdapter ClientAdapter { get; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,7 +5,7 @@ namespace MQTTnet.Core.Adapter
|
|||||||
{
|
{
|
||||||
public class MqttConnectingFailedException : MqttCommunicationException
|
public class MqttConnectingFailedException : MqttCommunicationException
|
||||||
{
|
{
|
||||||
public MqttConnectingFailedException(MqttConnectReturnCode returnCode)
|
public MqttConnectingFailedException(MqttConnectReturnCode returnCode)
|
||||||
: base($"Connecting with MQTT server failed ({returnCode}).")
|
: base($"Connecting with MQTT server failed ({returnCode}).")
|
||||||
{
|
{
|
||||||
ReturnCode = returnCode;
|
ReturnCode = returnCode;
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Adapter
|
||||||
|
{
|
||||||
|
public class MqttServerAdapterClientAcceptedEventArgs : EventArgs
|
||||||
|
{
|
||||||
|
public MqttServerAdapterClientAcceptedEventArgs(IMqttChannelAdapter client)
|
||||||
|
{
|
||||||
|
Client = client ?? throw new ArgumentNullException(nameof(client));
|
||||||
|
}
|
||||||
|
|
||||||
|
public IMqttChannelAdapter Client { get; }
|
||||||
|
|
||||||
|
public Task SessionTask { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using MQTTnet.Core.Packets;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Adapter
|
||||||
|
{
|
||||||
|
public sealed class ReceivedMqttPacket : IDisposable
|
||||||
|
{
|
||||||
|
public ReceivedMqttPacket(MqttPacketHeader header, MemoryStream body)
|
||||||
|
{
|
||||||
|
Header = header ?? throw new ArgumentNullException(nameof(header));
|
||||||
|
Body = body ?? throw new ArgumentNullException(nameof(body));
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttPacketHeader Header { get; }
|
||||||
|
|
||||||
|
public MemoryStream Body { get; }
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Body?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core
|
||||||
|
{
|
||||||
|
public static class ApplicationMessagePublisherExtensions
|
||||||
|
{
|
||||||
|
public static Task PublishAsync(this IApplicationMessagePublisher client, params MqttApplicationMessage[] applicationMessages)
|
||||||
|
{
|
||||||
|
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||||
|
if (applicationMessages == null) throw new ArgumentNullException(nameof(applicationMessages));
|
||||||
|
|
||||||
|
return client.PublishAsync(applicationMessages);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Channel
|
||||||
|
{
|
||||||
|
public interface IMqttChannel
|
||||||
|
{
|
||||||
|
Stream SendStream { get; }
|
||||||
|
Stream ReceiveStream { get; }
|
||||||
|
|
||||||
|
Task ConnectAsync();
|
||||||
|
Task DisconnectAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
using System.Threading.Tasks;
|
|
||||||
using MQTTnet.Core.Client;
|
|
||||||
|
|
||||||
namespace MQTTnet.Core.Channel
|
|
||||||
{
|
|
||||||
public interface IMqttCommunicationChannel
|
|
||||||
{
|
|
||||||
Task ConnectAsync(MqttClientOptions options);
|
|
||||||
|
|
||||||
Task DisconnectAsync();
|
|
||||||
|
|
||||||
Task WriteAsync(byte[] buffer);
|
|
||||||
|
|
||||||
Task ReadAsync(byte[] buffer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Packets;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public interface IMqttClient : IApplicationMessageReceiver, IApplicationMessagePublisher
|
||||||
|
{
|
||||||
|
bool IsConnected { get; }
|
||||||
|
|
||||||
|
event EventHandler<MqttClientConnectedEventArgs> Connected;
|
||||||
|
event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
|
||||||
|
|
||||||
|
Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options);
|
||||||
|
Task DisconnectAsync();
|
||||||
|
|
||||||
|
Task<IList<MqttSubscribeResult>> SubscribeAsync(IEnumerable<TopicFilter> topicFilters);
|
||||||
|
Task UnsubscribeAsync(IEnumerable<string> topicFilters);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using MQTTnet.Core.Adapter;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public interface IMqttClientAdapterFactory
|
||||||
|
{
|
||||||
|
IMqttChannelAdapter CreateClientAdapter(IMqttClientChannelOptions options, IMqttNetLogger logger);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public interface IMqttClientChannelOptions
|
||||||
|
{
|
||||||
|
MqttClientTlsOptions TlsOptions { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public interface IMqttClientCredentials
|
||||||
|
{
|
||||||
|
string Password { get; }
|
||||||
|
string Username { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.ManagedClient;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public interface IMqttClientFactory
|
||||||
|
{
|
||||||
|
IMqttClient CreateMqttClient();
|
||||||
|
|
||||||
|
IMqttClient CreateMqttClient(IMqttNetLogger logger);
|
||||||
|
|
||||||
|
IManagedMqttClient CreateManagedMqttClient();
|
||||||
|
|
||||||
|
IManagedMqttClient CreateManagedMqttClient(IMqttNetLogger logger);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
using System;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public interface IMqttClientOptions
|
||||||
|
{
|
||||||
|
string ClientId { get; }
|
||||||
|
|
||||||
|
IMqttClientCredentials Credentials { get; }
|
||||||
|
bool CleanSession { get; }
|
||||||
|
MqttApplicationMessage WillMessage { get; }
|
||||||
|
|
||||||
|
TimeSpan CommunicationTimeout { get; }
|
||||||
|
TimeSpan KeepAlivePeriod { get; }
|
||||||
|
MqttProtocolVersion ProtocolVersion { get; }
|
||||||
|
|
||||||
|
IMqttClientChannelOptions ChannelOptions { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
+286
-170
@@ -1,5 +1,4 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Concurrent;
|
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -13,155 +12,195 @@ using MQTTnet.Core.Protocol;
|
|||||||
|
|
||||||
namespace MQTTnet.Core.Client
|
namespace MQTTnet.Core.Client
|
||||||
{
|
{
|
||||||
public class MqttClient
|
public class MqttClient : IMqttClient
|
||||||
{
|
{
|
||||||
private readonly ConcurrentDictionary<ushort, MqttPublishPacket> _pendingExactlyOncePublishPackets = new ConcurrentDictionary<ushort, MqttPublishPacket>();
|
private readonly HashSet<ushort> _unacknowledgedPublishPackets = new HashSet<ushort>();
|
||||||
private readonly HashSet<ushort> _processedPublishPackets = new HashSet<ushort>();
|
|
||||||
|
|
||||||
private readonly MqttPacketDispatcher _packetDispatcher = new MqttPacketDispatcher();
|
private readonly IMqttClientAdapterFactory _adapterFactory;
|
||||||
private readonly MqttClientOptions _options;
|
private readonly MqttPacketDispatcher _packetDispatcher;
|
||||||
private readonly IMqttCommunicationAdapter _adapter;
|
private readonly IMqttNetLogger _logger;
|
||||||
|
|
||||||
|
private IMqttClientOptions _options;
|
||||||
|
private bool _isReceivingPackets;
|
||||||
private int _latestPacketIdentifier;
|
private int _latestPacketIdentifier;
|
||||||
private CancellationTokenSource _cancellationTokenSource;
|
private CancellationTokenSource _cancellationTokenSource;
|
||||||
|
private IMqttChannelAdapter _adapter;
|
||||||
|
|
||||||
public MqttClient(MqttClientOptions options, IMqttCommunicationAdapter adapter)
|
public MqttClient(IMqttClientAdapterFactory channelFactory, IMqttNetLogger logger)
|
||||||
{
|
{
|
||||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
_adapterFactory = channelFactory ?? throw new ArgumentNullException(nameof(channelFactory));
|
||||||
_adapter = adapter ?? throw new ArgumentNullException(nameof(adapter));
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||||
|
|
||||||
|
_packetDispatcher = new MqttPacketDispatcher(logger);
|
||||||
}
|
}
|
||||||
|
|
||||||
public event EventHandler Connected;
|
public event EventHandler<MqttClientConnectedEventArgs> Connected;
|
||||||
|
public event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
|
||||||
public event EventHandler Disconnected;
|
|
||||||
|
|
||||||
public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
|
public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
|
||||||
|
|
||||||
public bool IsConnected { get; private set; }
|
public bool IsConnected { get; private set; }
|
||||||
|
|
||||||
public async Task ConnectAsync(MqttApplicationMessage willApplicationMessage = null)
|
public async Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
|
||||||
{
|
{
|
||||||
MqttTrace.Verbose(nameof(MqttClient), "Trying to connect.");
|
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||||
|
if (options.ChannelOptions == null) throw new ArgumentException("ChannelOptions are not set.");
|
||||||
|
|
||||||
if (IsConnected)
|
ThrowIfConnected("It is not allowed to connect with a server after the connection is established.");
|
||||||
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
throw new MqttProtocolViolationException("It is not allowed to connect with a server after the connection is established.");
|
_options = options;
|
||||||
|
_cancellationTokenSource = new CancellationTokenSource();
|
||||||
|
_latestPacketIdentifier = 0;
|
||||||
|
_packetDispatcher.Reset();
|
||||||
|
|
||||||
|
_adapter = _adapterFactory.CreateClientAdapter(options.ChannelOptions, _logger);
|
||||||
|
|
||||||
|
_logger.Trace<MqttClient>("Trying to connect with server.");
|
||||||
|
await _adapter.ConnectAsync(_options.CommunicationTimeout).ConfigureAwait(false);
|
||||||
|
_logger.Trace<MqttClient>("Connection with server established.");
|
||||||
|
|
||||||
|
await StartReceivingPacketsAsync(_cancellationTokenSource.Token).ConfigureAwait(false);
|
||||||
|
var connectResponse = await AuthenticateAsync(options.WillMessage).ConfigureAwait(false);
|
||||||
|
|
||||||
|
_logger.Trace<MqttClient>("MQTT connection with server established.");
|
||||||
|
|
||||||
|
if (_options.KeepAlivePeriod != TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
StartSendingKeepAliveMessages(_cancellationTokenSource.Token);
|
||||||
|
}
|
||||||
|
|
||||||
|
IsConnected = true;
|
||||||
|
Connected?.Invoke(this, new MqttClientConnectedEventArgs(connectResponse.IsSessionPresent));
|
||||||
|
return new MqttClientConnectResult(connectResponse.IsSessionPresent);
|
||||||
}
|
}
|
||||||
|
catch (Exception exception)
|
||||||
var connectPacket = new MqttConnectPacket
|
|
||||||
{
|
{
|
||||||
ClientId = _options.ClientId,
|
_logger.Error<MqttClient>(exception, "Error while connecting with server.");
|
||||||
Username = _options.UserName,
|
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||||
Password = _options.Password,
|
throw;
|
||||||
CleanSession = _options.CleanSession,
|
|
||||||
KeepAlivePeriod = (ushort)_options.KeepAlivePeriod.TotalSeconds,
|
|
||||||
WillMessage = willApplicationMessage
|
|
||||||
};
|
|
||||||
|
|
||||||
await _adapter.ConnectAsync(_options, _options.DefaultCommunicationTimeout);
|
|
||||||
MqttTrace.Verbose(nameof(MqttClient), "Connection with server established.");
|
|
||||||
|
|
||||||
_cancellationTokenSource = new CancellationTokenSource();
|
|
||||||
_latestPacketIdentifier = 0;
|
|
||||||
_processedPublishPackets.Clear();
|
|
||||||
_packetDispatcher.Reset();
|
|
||||||
IsConnected = true;
|
|
||||||
|
|
||||||
Task.Run(() => ReceivePackets(_cancellationTokenSource.Token), _cancellationTokenSource.Token).Forget();
|
|
||||||
|
|
||||||
var response = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket);
|
|
||||||
if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted)
|
|
||||||
{
|
|
||||||
throw new MqttConnectingFailedException(response.ConnectReturnCode);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_options.KeepAlivePeriod != TimeSpan.Zero)
|
|
||||||
{
|
|
||||||
Task.Run(() => SendKeepAliveMessagesAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token).Forget();
|
|
||||||
}
|
|
||||||
|
|
||||||
Connected?.Invoke(this, EventArgs.Empty);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task DisconnectAsync()
|
public async Task DisconnectAsync()
|
||||||
{
|
{
|
||||||
await SendAsync(new MqttDisconnectPacket());
|
if (!IsConnected)
|
||||||
await DisconnectInternalAsync();
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await SendAsync(new MqttDisconnectPacket()).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<IList<MqttSubscribeResult>> SubscribeAsync(params TopicFilter[] topicFilters)
|
public async Task<IList<MqttSubscribeResult>> SubscribeAsync(IEnumerable<TopicFilter> topicFilters)
|
||||||
{
|
{
|
||||||
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
||||||
|
|
||||||
return SubscribeAsync(topicFilters.ToList());
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<IList<MqttSubscribeResult>> SubscribeAsync(IList<TopicFilter> topicFilters)
|
|
||||||
{
|
|
||||||
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
|
||||||
if (!topicFilters.Any()) throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.8.3-3].");
|
|
||||||
ThrowIfNotConnected();
|
ThrowIfNotConnected();
|
||||||
|
|
||||||
var subscribePacket = new MqttSubscribePacket
|
var subscribePacket = new MqttSubscribePacket
|
||||||
{
|
{
|
||||||
PacketIdentifier = GetNewPacketIdentifier(),
|
PacketIdentifier = GetNewPacketIdentifier(),
|
||||||
TopicFilters = topicFilters
|
TopicFilters = topicFilters.ToList()
|
||||||
};
|
};
|
||||||
|
|
||||||
var response = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket);
|
var response = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket).ConfigureAwait(false);
|
||||||
|
|
||||||
if (response.SubscribeReturnCodes.Count != topicFilters.Count)
|
if (response.SubscribeReturnCodes.Count != subscribePacket.TopicFilters.Count)
|
||||||
{
|
{
|
||||||
throw new MqttProtocolViolationException("The return codes are not matching the topic filters [MQTT-3.9.3-1].");
|
throw new MqttProtocolViolationException("The return codes are not matching the topic filters [MQTT-3.9.3-1].");
|
||||||
}
|
}
|
||||||
|
|
||||||
return topicFilters.Select((t, i) => new MqttSubscribeResult(t, response.SubscribeReturnCodes[i])).ToList();
|
return subscribePacket.TopicFilters.Select((t, i) => new MqttSubscribeResult(t, response.SubscribeReturnCodes[i])).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task Unsubscribe(params string[] topicFilters)
|
public async Task UnsubscribeAsync(IEnumerable<string> topicFilters)
|
||||||
{
|
{
|
||||||
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
||||||
|
|
||||||
return Unsubscribe(topicFilters.ToList());
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Unsubscribe(IList<string> topicFilters)
|
|
||||||
{
|
|
||||||
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
|
||||||
if (!topicFilters.Any()) throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.10.3-2].");
|
|
||||||
ThrowIfNotConnected();
|
ThrowIfNotConnected();
|
||||||
|
|
||||||
var unsubscribePacket = new MqttUnsubscribePacket
|
var unsubscribePacket = new MqttUnsubscribePacket
|
||||||
{
|
{
|
||||||
PacketIdentifier = GetNewPacketIdentifier(),
|
PacketIdentifier = GetNewPacketIdentifier(),
|
||||||
TopicFilters = topicFilters
|
TopicFilters = topicFilters.ToList()
|
||||||
};
|
};
|
||||||
|
|
||||||
await SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket);
|
await SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task PublishAsync(MqttApplicationMessage applicationMessage)
|
public async Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages)
|
||||||
{
|
{
|
||||||
if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
|
|
||||||
ThrowIfNotConnected();
|
ThrowIfNotConnected();
|
||||||
|
|
||||||
var publishPacket = applicationMessage.ToPublishPacket();
|
var publishPackets = applicationMessages.Select(m => m.ToPublishPacket());
|
||||||
|
|
||||||
if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
|
foreach (var qosGroup in publishPackets.GroupBy(p => p.QualityOfServiceLevel))
|
||||||
{
|
{
|
||||||
await SendAsync(publishPacket);
|
var qosPackets = qosGroup.ToArray();
|
||||||
|
switch (qosGroup.Key)
|
||||||
|
{
|
||||||
|
case MqttQualityOfServiceLevel.AtMostOnce:
|
||||||
|
{
|
||||||
|
// No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
|
||||||
|
await _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, qosPackets).ConfigureAwait(false);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case MqttQualityOfServiceLevel.AtLeastOnce:
|
||||||
|
{
|
||||||
|
foreach (var publishPacket in qosPackets)
|
||||||
|
{
|
||||||
|
publishPacket.PacketIdentifier = GetNewPacketIdentifier();
|
||||||
|
await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case MqttQualityOfServiceLevel.ExactlyOnce:
|
||||||
|
{
|
||||||
|
foreach (var publishPacket in qosPackets)
|
||||||
|
{
|
||||||
|
publishPacket.PacketIdentifier = GetNewPacketIdentifier();
|
||||||
|
var pubRecPacket = await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket).ConfigureAwait(false);
|
||||||
|
await SendAndReceiveAsync<MqttPubCompPacket>(pubRecPacket.CreateResponse<MqttPubRelPacket>()).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
|
}
|
||||||
|
|
||||||
|
private async Task<MqttConnAckPacket> AuthenticateAsync(MqttApplicationMessage willApplicationMessage)
|
||||||
|
{
|
||||||
|
var connectPacket = new MqttConnectPacket
|
||||||
{
|
{
|
||||||
publishPacket.PacketIdentifier = GetNewPacketIdentifier();
|
ClientId = _options.ClientId,
|
||||||
await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
|
Username = _options.Credentials?.Username,
|
||||||
}
|
Password = _options.Credentials?.Password,
|
||||||
else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
|
CleanSession = _options.CleanSession,
|
||||||
|
KeepAlivePeriod = (ushort)_options.KeepAlivePeriod.TotalSeconds,
|
||||||
|
WillMessage = willApplicationMessage
|
||||||
|
};
|
||||||
|
|
||||||
|
var response = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket).ConfigureAwait(false);
|
||||||
|
if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted)
|
||||||
{
|
{
|
||||||
publishPacket.PacketIdentifier = GetNewPacketIdentifier();
|
throw new MqttConnectingFailedException(response.ConnectReturnCode);
|
||||||
await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket);
|
|
||||||
await SendAsync(publishPacket.CreateResponse<MqttPubCompPacket>());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ThrowIfNotConnected()
|
private void ThrowIfNotConnected()
|
||||||
@@ -169,76 +208,91 @@ namespace MQTTnet.Core.Client
|
|||||||
if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
|
if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ThrowIfConnected(string message)
|
||||||
|
{
|
||||||
|
if (IsConnected) throw new MqttProtocolViolationException(message);
|
||||||
|
}
|
||||||
|
|
||||||
private async Task DisconnectInternalAsync()
|
private async Task DisconnectInternalAsync()
|
||||||
{
|
{
|
||||||
|
var clientWasConnected = IsConnected;
|
||||||
|
IsConnected = false;
|
||||||
|
|
||||||
|
var cts = _cancellationTokenSource;
|
||||||
|
if (cts == null || cts.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
cts.Cancel(false);
|
||||||
|
cts.Dispose();
|
||||||
|
_cancellationTokenSource = null;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await _adapter.DisconnectAsync();
|
await _adapter.DisconnectAsync(_options.CommunicationTimeout).ConfigureAwait(false);
|
||||||
|
_logger.Info<MqttClient>("Disconnected from adapter.");
|
||||||
}
|
}
|
||||||
catch
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
|
_logger.Warning<MqttClient>(exception, "Error while disconnecting from adapter.");
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
_cancellationTokenSource?.Cancel();
|
_logger.Info<MqttClient>("Disconnected.");
|
||||||
IsConnected = false;
|
Disconnected?.Invoke(this, new MqttClientDisconnectedEventArgs(clientWasConnected));
|
||||||
Disconnected?.Invoke(this, EventArgs.Empty);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async void ProcessReceivedPacket(MqttBasePacket mqttPacket)
|
private async Task ProcessReceivedPacketAsync(MqttBasePacket packet)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (mqttPacket is MqttPingReqPacket)
|
_logger.Info<MqttClient>("Received <<< {0}", packet);
|
||||||
|
|
||||||
|
if (packet is MqttPingReqPacket)
|
||||||
{
|
{
|
||||||
await SendAsync(new MqttPingRespPacket());
|
await SendAsync(new MqttPingRespPacket());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mqttPacket is MqttDisconnectPacket)
|
if (packet is MqttDisconnectPacket)
|
||||||
{
|
{
|
||||||
await DisconnectAsync();
|
await DisconnectAsync();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var publishPacket = mqttPacket as MqttPublishPacket;
|
if (packet is MqttPublishPacket publishPacket)
|
||||||
if (publishPacket != null)
|
|
||||||
{
|
{
|
||||||
await ProcessReceivedPublishPacket(publishPacket);
|
await ProcessReceivedPublishPacket(publishPacket);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var pubRelPacket = mqttPacket as MqttPubRelPacket;
|
if (packet is MqttPubRelPacket pubRelPacket)
|
||||||
if (pubRelPacket != null)
|
|
||||||
{
|
{
|
||||||
await ProcessReceivedPubRelPacket(pubRelPacket);
|
await ProcessReceivedPubRelPacket(pubRelPacket);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_packetDispatcher.Dispatch(mqttPacket);
|
_packetDispatcher.Dispatch(packet);
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
MqttTrace.Error(nameof(MqttClient), exception, "Error while processing received packet.");
|
_logger.Error<MqttClient>(exception, "Unhandled exception while processing received packet.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void FireApplicationMessageReceivedEvent(MqttPublishPacket publishPacket)
|
private void FireApplicationMessageReceivedEvent(MqttPublishPacket publishPacket)
|
||||||
{
|
{
|
||||||
if (publishPacket.QualityOfServiceLevel != MqttQualityOfServiceLevel.AtMostOnce)
|
try
|
||||||
{
|
{
|
||||||
_processedPublishPackets.Add(publishPacket.PacketIdentifier);
|
var applicationMessage = publishPacket.ToApplicationMessage();
|
||||||
|
ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(_options.ClientId, applicationMessage));
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
_logger.Error<MqttClient>(exception, "Unhandled exception while handling application message.");
|
||||||
}
|
}
|
||||||
|
|
||||||
var applicationMessage = new MqttApplicationMessage(
|
|
||||||
publishPacket.Topic,
|
|
||||||
publishPacket.Payload,
|
|
||||||
publishPacket.QualityOfServiceLevel,
|
|
||||||
publishPacket.Retain
|
|
||||||
);
|
|
||||||
|
|
||||||
ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(applicationMessage));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ProcessReceivedPublishPacket(MqttPublishPacket publishPacket)
|
private async Task ProcessReceivedPublishPacket(MqttPublishPacket publishPacket)
|
||||||
@@ -246,66 +300,52 @@ namespace MQTTnet.Core.Client
|
|||||||
if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
|
if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
|
||||||
{
|
{
|
||||||
FireApplicationMessageReceivedEvent(publishPacket);
|
FireApplicationMessageReceivedEvent(publishPacket);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
else
|
|
||||||
|
if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
|
||||||
{
|
{
|
||||||
if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
|
FireApplicationMessageReceivedEvent(publishPacket);
|
||||||
{
|
await SendAsync(new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
|
||||||
FireApplicationMessageReceivedEvent(publishPacket);
|
return;
|
||||||
await SendAsync(new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
|
|
||||||
}
|
|
||||||
else if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
|
|
||||||
{
|
|
||||||
_pendingExactlyOncePublishPackets[publishPacket.PacketIdentifier] = publishPacket;
|
|
||||||
await SendAsync(new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
|
||||||
|
{
|
||||||
|
// QoS 2 is implement as method "B" [4.3.3 QoS 2: Exactly once delivery]
|
||||||
|
lock (_unacknowledgedPublishPackets)
|
||||||
|
{
|
||||||
|
_unacknowledgedPublishPackets.Add(publishPacket.PacketIdentifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
FireApplicationMessageReceivedEvent(publishPacket);
|
||||||
|
await SendAsync(new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new MqttCommunicationException("Received a not supported QoS level.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket)
|
private Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket)
|
||||||
{
|
{
|
||||||
MqttPublishPacket originalPublishPacket;
|
lock (_unacknowledgedPublishPackets)
|
||||||
if (!_pendingExactlyOncePublishPackets.TryRemove(pubRelPacket.PacketIdentifier, out originalPublishPacket))
|
|
||||||
{
|
{
|
||||||
throw new MqttCommunicationException();
|
_unacknowledgedPublishPackets.Remove(pubRelPacket.PacketIdentifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
await SendAsync(originalPublishPacket.CreateResponse<MqttPubCompPacket>());
|
return SendAsync(pubRelPacket.CreateResponse<MqttPubCompPacket>());
|
||||||
|
|
||||||
FireApplicationMessageReceivedEvent(originalPublishPacket);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task SendAsync(MqttBasePacket packet)
|
private Task SendAsync(MqttBasePacket packet)
|
||||||
{
|
{
|
||||||
return _adapter.SendPacketAsync(packet, _options.DefaultCommunicationTimeout);
|
return _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
|
private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
|
||||||
{
|
{
|
||||||
bool ResponsePacketSelector(MqttBasePacket p)
|
var packetAwaiter = _packetDispatcher.WaitForPacketAsync(requestPacket, typeof(TResponsePacket), _options.CommunicationTimeout);
|
||||||
{
|
await _adapter.SendPacketsAsync(_options.CommunicationTimeout, _cancellationTokenSource.Token, requestPacket).ConfigureAwait(false);
|
||||||
var p1 = p as TResponsePacket;
|
return (TResponsePacket)await packetAwaiter.ConfigureAwait(false);
|
||||||
if (p1 == null)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var pi1 = requestPacket as IPacketWithIdentifier;
|
|
||||||
var pi2 = p as IPacketWithIdentifier;
|
|
||||||
|
|
||||||
if (pi1 != null && pi2 != null)
|
|
||||||
{
|
|
||||||
if (pi1.PacketIdentifier != pi2.PacketIdentifier)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
await _adapter.SendPacketAsync(requestPacket, _options.DefaultCommunicationTimeout);
|
|
||||||
return (TResponsePacket)await _packetDispatcher.WaitForPacketAsync(ResponsePacketSelector, _options.DefaultCommunicationTimeout);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ushort GetNewPacketIdentifier()
|
private ushort GetNewPacketIdentifier()
|
||||||
@@ -315,57 +355,133 @@ namespace MQTTnet.Core.Client
|
|||||||
|
|
||||||
private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
|
private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
MqttTrace.Information(nameof(MqttClient), "Start sending keep alive packets.");
|
_logger.Info<MqttClient>("Start sending keep alive packets.");
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
while (!cancellationToken.IsCancellationRequested)
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
await Task.Delay(_options.KeepAlivePeriod, cancellationToken);
|
await Task.Delay(_options.KeepAlivePeriod, cancellationToken).ConfigureAwait(false);
|
||||||
await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket());
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket()).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
catch (MqttCommunicationException exception)
|
catch (MqttCommunicationException exception)
|
||||||
{
|
{
|
||||||
MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning<MqttClient>(exception, "MQTT communication exception while sending/receiving keep alive packets.");
|
||||||
|
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
MqttTrace.Warning(nameof(MqttClient), exception, "Error while sending/receiving keep alive packets.");
|
_logger.Warning<MqttClient>(exception, "Unhandled exception while sending/receiving keep alive packets.");
|
||||||
|
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
MqttTrace.Information(nameof(MqttClient), "Stopped sending keep alive packets.");
|
_logger.Info<MqttClient>("Stopped sending keep alive packets.");
|
||||||
await DisconnectInternalAsync();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ReceivePackets(CancellationToken cancellationToken)
|
private async Task ReceivePacketsAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
MqttTrace.Information(nameof(MqttClient), "Start receiving packets.");
|
_logger.Info<MqttClient>("Start receiving packets.");
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
while (!cancellationToken.IsCancellationRequested)
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
var mqttPacket = await _adapter.ReceivePacketAsync(TimeSpan.Zero);
|
_isReceivingPackets = true;
|
||||||
MqttTrace.Information(nameof(MqttClient), $"Received <<< {mqttPacket}");
|
|
||||||
|
|
||||||
Task.Run(() => ProcessReceivedPacket(mqttPacket), cancellationToken).Forget();
|
var packet = await _adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
StartProcessReceivedPacket(packet, cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
catch (MqttCommunicationException exception)
|
catch (MqttCommunicationException exception)
|
||||||
{
|
{
|
||||||
MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Warning<MqttClient>(exception, "MQTT communication exception while receiving packets.");
|
||||||
|
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
MqttTrace.Error(nameof(MqttClient), exception, "Error while receiving packets.");
|
_logger.Error<MqttClient>(exception, "Unhandled exception while receiving packets.");
|
||||||
|
await DisconnectInternalAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
MqttTrace.Information(nameof(MqttClient), "Stopped receiving packets.");
|
_logger.Info<MqttClient>("Stopped receiving packets.");
|
||||||
await DisconnectInternalAsync();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void StartProcessReceivedPacket(MqttBasePacket packet, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
Task.Run(
|
||||||
|
() => ProcessReceivedPacketAsync(packet),
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task StartReceivingPacketsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
_isReceivingPackets = false;
|
||||||
|
|
||||||
|
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
Task.Run(
|
||||||
|
async () => await ReceivePacketsAsync(cancellationToken),
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
|
||||||
|
while (!_isReceivingPackets && !cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartSendingKeepAliveMessages(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
Task.Run(
|
||||||
|
async () => await SendKeepAliveMessagesAsync(cancellationToken),
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public class MqttClientConnectResult
|
||||||
|
{
|
||||||
|
public MqttClientConnectResult(bool isSessionPresent)
|
||||||
|
{
|
||||||
|
IsSessionPresent = isSessionPresent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsSessionPresent { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public class MqttClientConnectedEventArgs : EventArgs
|
||||||
|
{
|
||||||
|
public MqttClientConnectedEventArgs(bool isSessionPresent)
|
||||||
|
{
|
||||||
|
IsSessionPresent = isSessionPresent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsSessionPresent { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public class MqttClientCredentials : IMqttClientCredentials
|
||||||
|
{
|
||||||
|
public string Username { get; set; }
|
||||||
|
|
||||||
|
public string Password { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public class MqttClientDisconnectedEventArgs : EventArgs
|
||||||
|
{
|
||||||
|
public MqttClientDisconnectedEventArgs(bool clientWasConnected)
|
||||||
|
{
|
||||||
|
ClientWasConnected = clientWasConnected;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ClientWasConnected { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public static class MqttClientExtensions
|
||||||
|
{
|
||||||
|
public static Task<IList<MqttSubscribeResult>> SubscribeAsync(this IMqttClient client, params TopicFilter[] topicFilters)
|
||||||
|
{
|
||||||
|
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||||
|
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
||||||
|
|
||||||
|
return client.SubscribeAsync(topicFilters.ToList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Task UnsubscribeAsync(this IMqttClient client, params string[] topicFilters)
|
||||||
|
{
|
||||||
|
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||||
|
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
||||||
|
|
||||||
|
return client.UnsubscribeAsync(topicFilters.ToList());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +1,24 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
|
||||||
namespace MQTTnet.Core.Client
|
namespace MQTTnet.Core.Client
|
||||||
{
|
{
|
||||||
public class MqttClientOptions
|
public class MqttClientOptions : IMqttClientOptions
|
||||||
{
|
{
|
||||||
public string Server { get; set; }
|
public MqttApplicationMessage WillMessage { get; set; }
|
||||||
|
|
||||||
public int Port { get; set; } = 1883;
|
public string ClientId { get; set; } = Guid.NewGuid().ToString("N");
|
||||||
|
|
||||||
public string UserName { get; set; }
|
|
||||||
|
|
||||||
public string Password { get; set; }
|
|
||||||
|
|
||||||
public string ClientId { get; set; } = Guid.NewGuid().ToString().Replace("-", string.Empty);
|
|
||||||
|
|
||||||
public bool CleanSession { get; set; } = true;
|
public bool CleanSession { get; set; } = true;
|
||||||
|
|
||||||
|
public IMqttClientCredentials Credentials { get; set; } = new MqttClientCredentials();
|
||||||
|
|
||||||
public TimeSpan KeepAlivePeriod { get; set; } = TimeSpan.FromSeconds(5);
|
public TimeSpan KeepAlivePeriod { get; set; } = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
public TimeSpan DefaultCommunicationTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
public TimeSpan CommunicationTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
|
public MqttProtocolVersion ProtocolVersion { get; set; } = MqttProtocolVersion.V311;
|
||||||
|
|
||||||
|
public IMqttClientChannelOptions ChannelOptions { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using MQTTnet.Core.Serializer;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public class MqttClientOptionsBuilder
|
||||||
|
{
|
||||||
|
private readonly MqttClientOptions _options = new MqttClientOptions();
|
||||||
|
private MqttClientTcpOptions _tcpOptions;
|
||||||
|
private MqttClientWebSocketOptions _webSocketOptions;
|
||||||
|
|
||||||
|
private MqttClientTlsOptions _tlsOptions;
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithProtocolVersion(MqttProtocolVersion value)
|
||||||
|
{
|
||||||
|
_options.ProtocolVersion = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithCommunicationTimeout(TimeSpan value)
|
||||||
|
{
|
||||||
|
_options.CommunicationTimeout = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithCleanSession(bool value = true)
|
||||||
|
{
|
||||||
|
_options.CleanSession = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithKeepAlivePeriod(TimeSpan value)
|
||||||
|
{
|
||||||
|
_options.KeepAlivePeriod = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithClientId(string value)
|
||||||
|
{
|
||||||
|
_options.ClientId = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithWillMessage(MqttApplicationMessage value)
|
||||||
|
{
|
||||||
|
_options.WillMessage = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithCredentials(string username, string password = null)
|
||||||
|
{
|
||||||
|
_options.Credentials = new MqttClientCredentials
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
Password = password
|
||||||
|
};
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithTcpServer(string server, int? port = null)
|
||||||
|
{
|
||||||
|
_tcpOptions = new MqttClientTcpOptions
|
||||||
|
{
|
||||||
|
Server = server,
|
||||||
|
Port = port
|
||||||
|
};
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithWebSocketServer(string uri)
|
||||||
|
{
|
||||||
|
_webSocketOptions = new MqttClientWebSocketOptions
|
||||||
|
{
|
||||||
|
Uri = uri
|
||||||
|
};
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithTls(
|
||||||
|
bool allowUntrustedCertificates = false,
|
||||||
|
bool ignoreCertificateChainErrors = false,
|
||||||
|
bool ignoreCertificateRevocationErrors = false,
|
||||||
|
params byte[][] certificates)
|
||||||
|
{
|
||||||
|
_tlsOptions = new MqttClientTlsOptions
|
||||||
|
{
|
||||||
|
UseTls = true,
|
||||||
|
AllowUntrustedCertificates = allowUntrustedCertificates,
|
||||||
|
IgnoreCertificateChainErrors = ignoreCertificateChainErrors,
|
||||||
|
IgnoreCertificateRevocationErrors = ignoreCertificateRevocationErrors,
|
||||||
|
Certificates = certificates?.ToList()
|
||||||
|
};
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttClientOptionsBuilder WithTls()
|
||||||
|
{
|
||||||
|
_tlsOptions = new MqttClientTlsOptions
|
||||||
|
{
|
||||||
|
UseTls = true
|
||||||
|
};
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IMqttClientOptions Build()
|
||||||
|
{
|
||||||
|
if (_tlsOptions != null)
|
||||||
|
{
|
||||||
|
if (_tcpOptions == null && _webSocketOptions == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("A channel (TCP or WebSocket) must be set if TLS is configured.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_tcpOptions != null)
|
||||||
|
{
|
||||||
|
_options.ChannelOptions = _tcpOptions;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_options.ChannelOptions = _webSocketOptions;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_options.ChannelOptions = (IMqttClientChannelOptions)_tcpOptions ?? _webSocketOptions;
|
||||||
|
|
||||||
|
return _options;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public class MqttClientTcpOptions : IMqttClientChannelOptions
|
||||||
|
{
|
||||||
|
public string Server { get; set; }
|
||||||
|
|
||||||
|
public int? Port { get; set; }
|
||||||
|
|
||||||
|
public MqttClientTlsOptions TlsOptions { get; set; } = new MqttClientTlsOptions();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public class MqttClientTlsOptions
|
||||||
|
{
|
||||||
|
public bool UseTls { get; set; }
|
||||||
|
|
||||||
|
public bool IgnoreCertificateRevocationErrors { get; set; }
|
||||||
|
|
||||||
|
public bool IgnoreCertificateChainErrors { get; set; }
|
||||||
|
|
||||||
|
public bool AllowUntrustedCertificates { get; set; }
|
||||||
|
|
||||||
|
public List<byte[]> Certificates { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Net;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Client
|
||||||
|
{
|
||||||
|
public class MqttClientWebSocketOptions : IMqttClientChannelOptions
|
||||||
|
{
|
||||||
|
public string Uri { get; set; }
|
||||||
|
|
||||||
|
public IDictionary<string, string> RequestHeaders { get; set; }
|
||||||
|
|
||||||
|
public ICollection<string> SubProtocols { get; set; }
|
||||||
|
|
||||||
|
public CookieContainer CookieContainer { get; set; }
|
||||||
|
|
||||||
|
public MqttClientTlsOptions TlsOptions { get; set; } = new MqttClientTlsOptions();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using MQTTnet.Core.Packets;
|
|
||||||
|
|
||||||
namespace MQTTnet.Core.Client
|
|
||||||
{
|
|
||||||
public class MqttPacketAwaiter : TaskCompletionSource<MqttBasePacket>
|
|
||||||
{
|
|
||||||
public MqttPacketAwaiter(Func<MqttBasePacket, bool> packetSelector)
|
|
||||||
{
|
|
||||||
PacketSelector = packetSelector ?? throw new ArgumentNullException(nameof(packetSelector));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Func<MqttBasePacket, bool> PacketSelector { get; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,111 +1,102 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Concurrent;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using MQTTnet.Core.Diagnostics;
|
using MQTTnet.Core.Diagnostics;
|
||||||
using MQTTnet.Core.Exceptions;
|
using MQTTnet.Core.Exceptions;
|
||||||
|
using MQTTnet.Core.Internal;
|
||||||
using MQTTnet.Core.Packets;
|
using MQTTnet.Core.Packets;
|
||||||
|
|
||||||
namespace MQTTnet.Core.Client
|
namespace MQTTnet.Core.Client
|
||||||
{
|
{
|
||||||
public class MqttPacketDispatcher
|
public class MqttPacketDispatcher
|
||||||
{
|
{
|
||||||
private readonly object _syncRoot = new object();
|
private readonly ConcurrentDictionary<Type, TaskCompletionSource<MqttBasePacket>> _packetByResponseType = new ConcurrentDictionary<Type, TaskCompletionSource<MqttBasePacket>>();
|
||||||
private readonly List<MqttBasePacket> _receivedPackets = new List<MqttBasePacket>();
|
private readonly ConcurrentDictionary<Type, ConcurrentDictionary<ushort, TaskCompletionSource<MqttBasePacket>>> _packetByResponseTypeAndIdentifier = new ConcurrentDictionary<Type, ConcurrentDictionary<ushort, TaskCompletionSource<MqttBasePacket>>>();
|
||||||
private readonly List<MqttPacketAwaiter> _packetAwaiters = new List<MqttPacketAwaiter>();
|
private readonly IMqttNetLogger _logger;
|
||||||
|
|
||||||
public async Task<MqttBasePacket> WaitForPacketAsync(Func<MqttBasePacket, bool> selector, TimeSpan timeout)
|
public MqttPacketDispatcher(IMqttNetLogger logger)
|
||||||
{
|
{
|
||||||
if (selector == null) throw new ArgumentNullException(nameof(selector));
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||||
|
}
|
||||||
|
|
||||||
var packetAwaiter = AddPacketAwaiter(selector);
|
public async Task<MqttBasePacket> WaitForPacketAsync(MqttBasePacket request, Type responseType, TimeSpan timeout)
|
||||||
DispatchPendingPackets();
|
{
|
||||||
|
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||||
|
|
||||||
var hasTimeout = await Task.WhenAny(Task.Delay(timeout), packetAwaiter.Task) != packetAwaiter.Task;
|
var packetAwaiter = AddPacketAwaiter(request, responseType);
|
||||||
RemovePacketAwaiter(packetAwaiter);
|
try
|
||||||
|
|
||||||
if (hasTimeout)
|
|
||||||
{
|
{
|
||||||
MqttTrace.Warning(nameof(MqttPacketDispatcher), "Timeout while waiting for packet.");
|
return await packetAwaiter.Task.TimeoutAfter(timeout).ConfigureAwait(false);
|
||||||
throw new MqttCommunicationTimedOutException();
|
}
|
||||||
|
catch (MqttCommunicationTimedOutException)
|
||||||
|
{
|
||||||
|
_logger.Warning<MqttPacketDispatcher>("Timeout while waiting for packet of type '{0}'.", responseType.Name);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
RemovePacketAwaiter(request, responseType);
|
||||||
}
|
}
|
||||||
|
|
||||||
return packetAwaiter.Task.Result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispatch(MqttBasePacket packet)
|
public void Dispatch(MqttBasePacket packet)
|
||||||
{
|
{
|
||||||
if (packet == null) throw new ArgumentNullException(nameof(packet));
|
if (packet == null) throw new ArgumentNullException(nameof(packet));
|
||||||
|
|
||||||
var packetDispatched = false;
|
var type = packet.GetType();
|
||||||
foreach (var packetAwaiter in GetPacketAwaiters())
|
if (packet is IMqttPacketWithIdentifier withIdentifier)
|
||||||
{
|
{
|
||||||
if (packetAwaiter.PacketSelector(packet))
|
if (_packetByResponseTypeAndIdentifier.TryGetValue(type, out var byid))
|
||||||
{
|
{
|
||||||
packetAwaiter.SetResult(packet);
|
if (byid.TryRemove(withIdentifier.PacketIdentifier, out var tcs))
|
||||||
packetDispatched = true;
|
{
|
||||||
break;
|
tcs.TrySetResult(packet);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else if (_packetByResponseType.TryRemove(type, out var tcs))
|
||||||
|
{
|
||||||
|
tcs.TrySetResult(packet);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
lock (_syncRoot)
|
throw new InvalidOperationException($"Packet of type '{type.Name}' not handled or dispatched.");
|
||||||
{
|
|
||||||
if (!packetDispatched)
|
|
||||||
{
|
|
||||||
_receivedPackets.Add(packet);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_receivedPackets.Remove(packet);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Reset()
|
public void Reset()
|
||||||
{
|
{
|
||||||
lock (_syncRoot)
|
_packetByResponseTypeAndIdentifier.Clear();
|
||||||
{
|
_packetByResponseType.Clear();
|
||||||
_packetAwaiters.Clear();
|
|
||||||
_receivedPackets.Clear();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<MqttPacketAwaiter> GetPacketAwaiters()
|
private TaskCompletionSource<MqttBasePacket> AddPacketAwaiter(MqttBasePacket request, Type responseType)
|
||||||
{
|
{
|
||||||
lock (_packetAwaiters)
|
var tcs = new TaskCompletionSource<MqttBasePacket>();
|
||||||
|
|
||||||
|
if (request is IMqttPacketWithIdentifier requestWithIdentifier)
|
||||||
{
|
{
|
||||||
return new List<MqttPacketAwaiter>(_packetAwaiters);
|
var byId = _packetByResponseTypeAndIdentifier.GetOrAdd(responseType, key => new ConcurrentDictionary<ushort, TaskCompletionSource<MqttBasePacket>>());
|
||||||
|
byId[requestWithIdentifier.PacketIdentifier] = tcs;
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_packetByResponseType[responseType] = tcs;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tcs;
|
||||||
}
|
}
|
||||||
|
|
||||||
private MqttPacketAwaiter AddPacketAwaiter(Func<MqttBasePacket, bool> selector)
|
private void RemovePacketAwaiter(MqttBasePacket request, Type responseType)
|
||||||
{
|
{
|
||||||
lock (_syncRoot)
|
if (request is IMqttPacketWithIdentifier requestWithIdentifier)
|
||||||
{
|
{
|
||||||
var packetAwaiter = new MqttPacketAwaiter(selector);
|
var byId = _packetByResponseTypeAndIdentifier.GetOrAdd(responseType, key => new ConcurrentDictionary<ushort, TaskCompletionSource<MqttBasePacket>>());
|
||||||
_packetAwaiters.Add(packetAwaiter);
|
byId.TryRemove(requestWithIdentifier.PacketIdentifier, out var _);
|
||||||
return packetAwaiter;
|
|
||||||
}
|
}
|
||||||
}
|
else
|
||||||
|
|
||||||
private void RemovePacketAwaiter(MqttPacketAwaiter packetAwaiter)
|
|
||||||
{
|
|
||||||
lock (_syncRoot)
|
|
||||||
{
|
{
|
||||||
_packetAwaiters.Remove(packetAwaiter);
|
_packetByResponseType.TryRemove(responseType, out var _);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void DispatchPendingPackets()
|
|
||||||
{
|
|
||||||
List<MqttBasePacket> receivedPackets;
|
|
||||||
lock (_syncRoot)
|
|
||||||
{
|
|
||||||
receivedPackets = new List<MqttBasePacket>(_receivedPackets);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var pendingPacket in receivedPackets)
|
|
||||||
{
|
|
||||||
Dispatch(pendingPacket);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Diagnostics
|
||||||
|
{
|
||||||
|
public interface IMqttNetLogger
|
||||||
|
{
|
||||||
|
event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished;
|
||||||
|
|
||||||
|
void Trace<TSource>(string message, params object[] parameters);
|
||||||
|
|
||||||
|
void Info<TSource>(string message, params object[] parameters);
|
||||||
|
|
||||||
|
void Warning<TSource>(Exception exception, string message, params object[] parameters);
|
||||||
|
|
||||||
|
void Warning<TSource>(string message, params object[] parameters);
|
||||||
|
|
||||||
|
void Error<TSource>(Exception exception, string message, params object[] parameters);
|
||||||
|
|
||||||
|
void Error<TSource>(string message, params object[] parameters);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Diagnostics
|
||||||
|
{
|
||||||
|
public static class MqttNetGlobalLog
|
||||||
|
{
|
||||||
|
public static event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished;
|
||||||
|
|
||||||
|
public static bool HasListeners => LogMessagePublished != null;
|
||||||
|
|
||||||
|
public static void Publish(MqttNetLogMessage logMessage)
|
||||||
|
{
|
||||||
|
if (logMessage == null) throw new ArgumentNullException(nameof(logMessage));
|
||||||
|
|
||||||
|
LogMessagePublished?.Invoke(null, new MqttNetLogMessagePublishedEventArgs(logMessage));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
-2
@@ -1,10 +1,13 @@
|
|||||||
namespace MQTTnet.Core.Diagnostics
|
namespace MQTTnet.Core.Diagnostics
|
||||||
{
|
{
|
||||||
public enum MqttTraceLevel
|
public enum MqttNetLogLevel
|
||||||
{
|
{
|
||||||
Verbose,
|
Verbose,
|
||||||
Information,
|
|
||||||
|
Info,
|
||||||
|
|
||||||
Warning,
|
Warning,
|
||||||
|
|
||||||
Error
|
Error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+9
-3
@@ -2,10 +2,12 @@
|
|||||||
|
|
||||||
namespace MQTTnet.Core.Diagnostics
|
namespace MQTTnet.Core.Diagnostics
|
||||||
{
|
{
|
||||||
public class MqttTraceMessagePublishedEventArgs : EventArgs
|
public sealed class MqttNetLogMessage
|
||||||
{
|
{
|
||||||
public MqttTraceMessagePublishedEventArgs(int threadId, string source, MqttTraceLevel level, string message, Exception exception)
|
public MqttNetLogMessage(string logId, DateTime timestamp, int threadId, string source, MqttNetLogLevel level, string message, Exception exception)
|
||||||
{
|
{
|
||||||
|
LogId = logId;
|
||||||
|
Timestamp = timestamp;
|
||||||
ThreadId = threadId;
|
ThreadId = threadId;
|
||||||
Source = source;
|
Source = source;
|
||||||
Level = level;
|
Level = level;
|
||||||
@@ -13,11 +15,15 @@ namespace MQTTnet.Core.Diagnostics
|
|||||||
Exception = exception;
|
Exception = exception;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public string LogId { get; }
|
||||||
|
|
||||||
|
public DateTime Timestamp { get; }
|
||||||
|
|
||||||
public int ThreadId { get; }
|
public int ThreadId { get; }
|
||||||
|
|
||||||
public string Source { get; }
|
public string Source { get; }
|
||||||
|
|
||||||
public MqttTraceLevel Level { get; }
|
public MqttNetLogLevel Level { get; }
|
||||||
|
|
||||||
public string Message { get; }
|
public string Message { get; }
|
||||||
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Diagnostics
|
||||||
|
{
|
||||||
|
public sealed class MqttNetLogMessagePublishedEventArgs : EventArgs
|
||||||
|
{
|
||||||
|
public MqttNetLogMessagePublishedEventArgs(MqttNetLogMessage logMessage)
|
||||||
|
{
|
||||||
|
TraceMessage = logMessage ?? throw new ArgumentNullException(nameof(logMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
public MqttNetLogMessage TraceMessage { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.Diagnostics
|
||||||
|
{
|
||||||
|
public class MqttNetLogger : IMqttNetLogger
|
||||||
|
{
|
||||||
|
private readonly string _logId;
|
||||||
|
|
||||||
|
public MqttNetLogger(string logId = null)
|
||||||
|
{
|
||||||
|
_logId = logId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished;
|
||||||
|
|
||||||
|
public void Trace<TSource>(string message, params object[] parameters)
|
||||||
|
{
|
||||||
|
Publish<TSource>(MqttNetLogLevel.Verbose, null, message, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Info<TSource>(string message, params object[] parameters)
|
||||||
|
{
|
||||||
|
Publish<TSource>(MqttNetLogLevel.Info, null, message, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Warning<TSource>(Exception exception, string message, params object[] parameters)
|
||||||
|
{
|
||||||
|
Publish<TSource>(MqttNetLogLevel.Warning, exception, message, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Warning<TSource>(string message, params object[] parameters)
|
||||||
|
{
|
||||||
|
Warning<TSource>(null, message, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Error<TSource>(Exception exception, string message, params object[] parameters)
|
||||||
|
{
|
||||||
|
Publish<TSource>(MqttNetLogLevel.Error, exception, message, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Error<TSource>(string message, params object[] parameters)
|
||||||
|
{
|
||||||
|
Warning<TSource>(null, message, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Publish<TSource>(MqttNetLogLevel logLevel, Exception exception, string message, object[] parameters)
|
||||||
|
{
|
||||||
|
var hasLocalListeners = LogMessagePublished != null;
|
||||||
|
var hasGlobalListeners = MqttNetGlobalLog.HasListeners;
|
||||||
|
|
||||||
|
if (!hasLocalListeners && !hasGlobalListeners)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parameters.Length > 0)
|
||||||
|
{
|
||||||
|
message = string.Format(message, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
var traceMessage = new MqttNetLogMessage(_logId, DateTime.Now, Environment.CurrentManagedThreadId, typeof(TSource).Name, logLevel, message, exception);
|
||||||
|
|
||||||
|
if (hasGlobalListeners)
|
||||||
|
{
|
||||||
|
MqttNetGlobalLog.Publish(traceMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasLocalListeners)
|
||||||
|
{
|
||||||
|
LogMessagePublished?.Invoke(this, new MqttNetLogMessagePublishedEventArgs(traceMessage));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
using System;
|
|
||||||
|
|
||||||
namespace MQTTnet.Core.Diagnostics
|
|
||||||
{
|
|
||||||
public static class MqttTrace
|
|
||||||
{
|
|
||||||
public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
|
|
||||||
|
|
||||||
public static void Verbose(string source, string message)
|
|
||||||
{
|
|
||||||
Publish(source, MqttTraceLevel.Verbose, null, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void Information(string source, string message)
|
|
||||||
{
|
|
||||||
Publish(source, MqttTraceLevel.Information, null, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void Warning(string source, string message)
|
|
||||||
{
|
|
||||||
Publish(source, MqttTraceLevel.Warning, null, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void Warning(string source, Exception exception, string message)
|
|
||||||
{
|
|
||||||
Publish(source, MqttTraceLevel.Warning, exception, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void Error(string source, string message)
|
|
||||||
{
|
|
||||||
Publish(source, MqttTraceLevel.Error, null, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void Error(string source, Exception exception, string message)
|
|
||||||
{
|
|
||||||
Publish(source, MqttTraceLevel.Error, exception, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
|
|
||||||
{
|
|
||||||
TraceMessagePublished?.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ namespace MQTTnet.Core.Exceptions
|
|||||||
{
|
{
|
||||||
public class MqttCommunicationException : Exception
|
public class MqttCommunicationException : Exception
|
||||||
{
|
{
|
||||||
public MqttCommunicationException()
|
protected MqttCommunicationException()
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
namespace MQTTnet.Core.Exceptions
|
namespace MQTTnet.Core.Exceptions
|
||||||
{
|
{
|
||||||
public class MqttCommunicationTimedOutException : MqttCommunicationException
|
public sealed class MqttCommunicationTimedOutException : MqttCommunicationException
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
namespace MQTTnet.Core.Exceptions
|
namespace MQTTnet.Core.Exceptions
|
||||||
{
|
{
|
||||||
public class MqttProtocolViolationException : Exception
|
public sealed class MqttProtocolViolationException : Exception
|
||||||
{
|
{
|
||||||
public MqttProtocolViolationException(string message)
|
public MqttProtocolViolationException(string message)
|
||||||
: base(message)
|
: base(message)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core
|
||||||
|
{
|
||||||
|
public interface IApplicationMessagePublisher
|
||||||
|
{
|
||||||
|
Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using System;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core
|
||||||
|
{
|
||||||
|
public interface IApplicationMessageReceiver
|
||||||
|
{
|
||||||
|
event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace MQTTnet.Core.Internal
|
|
||||||
{
|
|
||||||
public class AsyncGate
|
|
||||||
{
|
|
||||||
private readonly Queue<TaskCompletionSource<bool>> _waitingTasks = new Queue<TaskCompletionSource<bool>>();
|
|
||||||
|
|
||||||
public Task WaitOneAsync()
|
|
||||||
{
|
|
||||||
var tcs = new TaskCompletionSource<bool>();
|
|
||||||
lock (_waitingTasks)
|
|
||||||
{
|
|
||||||
_waitingTasks.Enqueue(tcs);
|
|
||||||
}
|
|
||||||
|
|
||||||
return tcs.Task;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Set()
|
|
||||||
{
|
|
||||||
lock (_waitingTasks)
|
|
||||||
{
|
|
||||||
if (_waitingTasks.Count > 0)
|
|
||||||
{
|
|
||||||
_waitingTasks.Dequeue().SetResult(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,6 +4,17 @@ namespace MQTTnet.Core.Internal
|
|||||||
{
|
{
|
||||||
internal static class MqttApplicationMessageExtensions
|
internal static class MqttApplicationMessageExtensions
|
||||||
{
|
{
|
||||||
|
public static MqttApplicationMessage ToApplicationMessage(this MqttPublishPacket publishPacket)
|
||||||
|
{
|
||||||
|
return new MqttApplicationMessage
|
||||||
|
{
|
||||||
|
Topic = publishPacket.Topic,
|
||||||
|
Payload = publishPacket.Payload,
|
||||||
|
QualityOfServiceLevel = publishPacket.QualityOfServiceLevel,
|
||||||
|
Retain = publishPacket.Retain
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
public static MqttPublishPacket ToPublishPacket(this MqttApplicationMessage applicationMessage)
|
public static MqttPublishPacket ToPublishPacket(this MqttApplicationMessage applicationMessage)
|
||||||
{
|
{
|
||||||
if (applicationMessage == null)
|
if (applicationMessage == null)
|
||||||
|
|||||||
@@ -1,11 +1,74 @@
|
|||||||
using System.Threading.Tasks;
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Exceptions;
|
||||||
|
|
||||||
namespace MQTTnet.Core.Internal
|
namespace MQTTnet.Core.Internal
|
||||||
{
|
{
|
||||||
internal static class TaskExtensions
|
public static class TaskExtensions
|
||||||
{
|
{
|
||||||
public static void Forget(this Task task)
|
public static async Task TimeoutAfter(this Task task, TimeSpan timeout)
|
||||||
{
|
{
|
||||||
|
using (var cancellationTokenSource = new CancellationTokenSource())
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var timeoutTask = Task.Delay(timeout, cancellationTokenSource.Token);
|
||||||
|
var finishedTask = await Task.WhenAny(timeoutTask, task).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (finishedTask == timeoutTask)
|
||||||
|
{
|
||||||
|
throw new MqttCommunicationTimedOutException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task.IsCanceled)
|
||||||
|
{
|
||||||
|
throw new TaskCanceledException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task.IsFaulted)
|
||||||
|
{
|
||||||
|
throw new MqttCommunicationException(task.Exception.GetBaseException());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
cancellationTokenSource.Cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout)
|
||||||
|
{
|
||||||
|
using (var cancellationTokenSource = new CancellationTokenSource())
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var timeoutTask = Task.Delay(timeout, cancellationTokenSource.Token);
|
||||||
|
var finishedTask = await Task.WhenAny(timeoutTask, task).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (finishedTask == timeoutTask)
|
||||||
|
{
|
||||||
|
throw new MqttCommunicationTimedOutException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task.IsCanceled)
|
||||||
|
{
|
||||||
|
throw new TaskCanceledException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task.IsFaulted)
|
||||||
|
{
|
||||||
|
throw new MqttCommunicationException(task.Exception.GetBaseException());
|
||||||
|
}
|
||||||
|
|
||||||
|
return task.Result;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
cancellationTokenSource.Cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,30 +5,21 @@
|
|||||||
<AssemblyName>MQTTnet.Core</AssemblyName>
|
<AssemblyName>MQTTnet.Core</AssemblyName>
|
||||||
<RootNamespace>MQTTnet.Core</RootNamespace>
|
<RootNamespace>MQTTnet.Core</RootNamespace>
|
||||||
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
|
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
|
||||||
<Description>MQTTnet is a .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker).</Description>
|
<DebugType>Full</DebugType>
|
||||||
<Product>MQTTnet</Product>
|
<Description></Description>
|
||||||
<Company>Christian Kratky</Company>
|
<Product></Product>
|
||||||
<Authors>Christian Kratky</Authors>
|
<Company></Company>
|
||||||
<Version>2.1.2.0</Version>
|
<Authors></Authors>
|
||||||
<PackageId>MQTTnet.Core</PackageId>
|
<Version>0.0.0.0</Version>
|
||||||
<Copyright>Copyright © Christian Kratky 2016-2017</Copyright>
|
<PackageId></PackageId>
|
||||||
<PackageProjectUrl>https://github.com/chkr1011/MQTTnet</PackageProjectUrl>
|
<Copyright></Copyright>
|
||||||
<PackageIconUrl>https://raw.githubusercontent.com/chkr1011/MQTTnet/master/Images/Logo_128x128.png</PackageIconUrl>
|
<PackageProjectUrl></PackageProjectUrl>
|
||||||
<RepositoryUrl>https://github.com/chkr1011/MQTTnet</RepositoryUrl>
|
<PackageIconUrl></PackageIconUrl>
|
||||||
<PackageTags>MQTT MQTTClient MQTTServer MQTTBroker Broker</PackageTags>
|
<RepositoryUrl></RepositoryUrl>
|
||||||
<FileVersion>2.1.2.0</FileVersion>
|
<PackageTags></PackageTags>
|
||||||
<AssemblyVersion>2.1.2.0</AssemblyVersion>
|
<FileVersion>2.5.3.0</FileVersion>
|
||||||
<PackageLicenseUrl>https://github.com/chkr1011/MQTTnet/blob/master/LICENSE</PackageLicenseUrl>
|
<AssemblyVersion>2.5.3.0</AssemblyVersion>
|
||||||
|
<PackageLicenseUrl></PackageLicenseUrl>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|AnyCPU'" />
|
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|x64'" />
|
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'" />
|
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'" />
|
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Any CPU|x86'" />
|
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.ManagedClient
|
||||||
|
{
|
||||||
|
public interface IManagedMqttClient : IApplicationMessageReceiver, IApplicationMessagePublisher
|
||||||
|
{
|
||||||
|
bool IsConnected { get; }
|
||||||
|
|
||||||
|
event EventHandler<MqttClientConnectedEventArgs> Connected;
|
||||||
|
event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
|
||||||
|
|
||||||
|
Task StartAsync(IManagedMqttClientOptions options);
|
||||||
|
Task StopAsync();
|
||||||
|
|
||||||
|
Task SubscribeAsync(IEnumerable<TopicFilter> topicFilters);
|
||||||
|
Task UnsubscribeAsync(IEnumerable<TopicFilter> topicFilters);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.ManagedClient
|
||||||
|
{
|
||||||
|
public interface IManagedMqttClientOptions
|
||||||
|
{
|
||||||
|
IMqttClientOptions ClientOptions { get; }
|
||||||
|
|
||||||
|
TimeSpan AutoReconnectDelay { get; }
|
||||||
|
|
||||||
|
IManagedMqttClientStorage Storage { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.ManagedClient
|
||||||
|
{
|
||||||
|
public interface IManagedMqttClientStorage
|
||||||
|
{
|
||||||
|
Task SaveQueuedMessagesAsync(IList<MqttApplicationMessage> messages);
|
||||||
|
|
||||||
|
Task<IList<MqttApplicationMessage>> LoadQueuedMessagesAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
using MQTTnet.Core.Diagnostics;
|
||||||
|
using MQTTnet.Core.Exceptions;
|
||||||
|
using MQTTnet.Core.Protocol;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.ManagedClient
|
||||||
|
{
|
||||||
|
public class ManagedMqttClient : IManagedMqttClient
|
||||||
|
{
|
||||||
|
private readonly ManagedMqttClientStorageManager _storageManager = new ManagedMqttClientStorageManager();
|
||||||
|
private readonly BlockingCollection<MqttApplicationMessage> _messageQueue = new BlockingCollection<MqttApplicationMessage>();
|
||||||
|
private readonly HashSet<TopicFilter> _subscriptions = new HashSet<TopicFilter>();
|
||||||
|
|
||||||
|
private readonly IMqttClient _mqttClient;
|
||||||
|
private readonly IMqttNetLogger _logger;
|
||||||
|
|
||||||
|
private CancellationTokenSource _connectionCancellationToken;
|
||||||
|
private CancellationTokenSource _publishingCancellationToken;
|
||||||
|
|
||||||
|
private IManagedMqttClientOptions _options;
|
||||||
|
private bool _subscriptionsNotPushed;
|
||||||
|
|
||||||
|
public ManagedMqttClient(IMqttClient mqttClient, IMqttNetLogger logger)
|
||||||
|
{
|
||||||
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||||
|
_mqttClient = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient));
|
||||||
|
|
||||||
|
_mqttClient.Connected += OnConnected;
|
||||||
|
_mqttClient.Disconnected += OnDisconnected;
|
||||||
|
_mqttClient.ApplicationMessageReceived += OnApplicationMessageReceived;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsConnected => _mqttClient.IsConnected;
|
||||||
|
|
||||||
|
public event EventHandler<MqttClientConnectedEventArgs> Connected;
|
||||||
|
public event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
|
||||||
|
public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
|
||||||
|
|
||||||
|
public async Task StartAsync(IManagedMqttClientOptions options)
|
||||||
|
{
|
||||||
|
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||||
|
if (options.ClientOptions == null) throw new ArgumentException("The client options are not set.", nameof(options));
|
||||||
|
|
||||||
|
if (!options.ClientOptions.CleanSession)
|
||||||
|
{
|
||||||
|
throw new NotSupportedException("The managed client does not support existing sessions.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_connectionCancellationToken != null) throw new InvalidOperationException("The managed client is already started.");
|
||||||
|
|
||||||
|
_options = options;
|
||||||
|
await _storageManager.SetStorageAsync(_options.Storage).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (_options.Storage != null)
|
||||||
|
{
|
||||||
|
var loadedMessages = await _options.Storage.LoadQueuedMessagesAsync().ConfigureAwait(false);
|
||||||
|
foreach (var loadedMessage in loadedMessages)
|
||||||
|
{
|
||||||
|
_messageQueue.Add(loadedMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_connectionCancellationToken = new CancellationTokenSource();
|
||||||
|
|
||||||
|
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
Task.Run(async () => await MaintainConnectionAsync(_connectionCancellationToken.Token), _connectionCancellationToken.Token).ConfigureAwait(false);
|
||||||
|
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
|
||||||
|
_logger.Info<ManagedMqttClient>("Started");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StopAsync()
|
||||||
|
{
|
||||||
|
_connectionCancellationToken?.Cancel(false);
|
||||||
|
_connectionCancellationToken = null;
|
||||||
|
|
||||||
|
_publishingCancellationToken?.Cancel(false);
|
||||||
|
_publishingCancellationToken = null;
|
||||||
|
|
||||||
|
while (_messageQueue.Any())
|
||||||
|
{
|
||||||
|
_messageQueue.Take();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages)
|
||||||
|
{
|
||||||
|
if (applicationMessages == null) throw new ArgumentNullException(nameof(applicationMessages));
|
||||||
|
|
||||||
|
foreach (var applicationMessage in applicationMessages)
|
||||||
|
{
|
||||||
|
await _storageManager.AddAsync(applicationMessage).ConfigureAwait(false);
|
||||||
|
_messageQueue.Add(applicationMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task SubscribeAsync(IEnumerable<TopicFilter> topicFilters)
|
||||||
|
{
|
||||||
|
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
|
||||||
|
|
||||||
|
lock (_subscriptions)
|
||||||
|
{
|
||||||
|
foreach (var topicFilter in topicFilters)
|
||||||
|
{
|
||||||
|
if (_subscriptions.Add(topicFilter))
|
||||||
|
{
|
||||||
|
_subscriptionsNotPushed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task UnsubscribeAsync(IEnumerable<TopicFilter> topicFilters)
|
||||||
|
{
|
||||||
|
lock (_subscriptions)
|
||||||
|
{
|
||||||
|
foreach (var topicFilter in topicFilters)
|
||||||
|
{
|
||||||
|
if (_subscriptions.Remove(topicFilter))
|
||||||
|
{
|
||||||
|
_subscriptionsNotPushed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task MaintainConnectionAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var connectionState = await ReconnectIfRequiredAsync().ConfigureAwait(false);
|
||||||
|
if (connectionState == ReconnectionResult.NotConnected)
|
||||||
|
{
|
||||||
|
_publishingCancellationToken?.Cancel(false);
|
||||||
|
_publishingCancellationToken = null;
|
||||||
|
|
||||||
|
await Task.Delay(_options.AutoReconnectDelay, cancellationToken).ConfigureAwait(false);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connectionState == ReconnectionResult.Reconnected || _subscriptionsNotPushed)
|
||||||
|
{
|
||||||
|
await PushSubscriptionsAsync();
|
||||||
|
|
||||||
|
_publishingCancellationToken = new CancellationTokenSource();
|
||||||
|
|
||||||
|
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
Task.Run(async () => await PublishQueuedMessagesAsync(_publishingCancellationToken.Token), _publishingCancellationToken.Token).ConfigureAwait(false);
|
||||||
|
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connectionState == ReconnectionResult.StillConnected)
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(1), _connectionCancellationToken.Token).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (MqttCommunicationException exception)
|
||||||
|
{
|
||||||
|
_logger.Warning<ManagedMqttClient>(exception, "Communication exception while maintaining connection.");
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
_logger.Error<ManagedMqttClient>(exception, "Unhandled exception while maintaining connection.");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await _mqttClient.DisconnectAsync().ConfigureAwait(false);
|
||||||
|
_logger.Info<ManagedMqttClient>("Stopped");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PublishQueuedMessagesAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var message = _messageQueue.Take(cancellationToken);
|
||||||
|
if (message == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
await TryPublishQueuedMessageAsync(message).ConfigureAwait(false);
|
||||||
|
await _storageManager.RemoveAsync(message).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_logger.Info<ManagedMqttClient>("Stopped publishing messages");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task TryPublishQueuedMessageAsync(MqttApplicationMessage message)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _mqttClient.PublishAsync(message).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (MqttCommunicationException exception)
|
||||||
|
{
|
||||||
|
_logger.Warning<ManagedMqttClient>(exception, "Publishing application message failed.");
|
||||||
|
|
||||||
|
if (message.QualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
|
||||||
|
{
|
||||||
|
_messageQueue.Add(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
_logger.Error<ManagedMqttClient>(exception, "Unhandled exception while publishing queued application message.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PushSubscriptionsAsync()
|
||||||
|
{
|
||||||
|
_logger.Info<ManagedMqttClient>(nameof(ManagedMqttClient), "Synchronizing subscriptions");
|
||||||
|
|
||||||
|
List<TopicFilter> subscriptions;
|
||||||
|
lock (_subscriptions)
|
||||||
|
{
|
||||||
|
subscriptions = _subscriptions.ToList();
|
||||||
|
_subscriptionsNotPushed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_subscriptions.Any())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _mqttClient.SubscribeAsync(subscriptions).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
_logger.Warning<ManagedMqttClient>(exception, "Synchronizing subscriptions failed");
|
||||||
|
_subscriptionsNotPushed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<ReconnectionResult> ReconnectIfRequiredAsync()
|
||||||
|
{
|
||||||
|
if (_mqttClient.IsConnected)
|
||||||
|
{
|
||||||
|
return ReconnectionResult.StillConnected;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _mqttClient.ConnectAsync(_options.ClientOptions).ConfigureAwait(false);
|
||||||
|
return ReconnectionResult.Reconnected;
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
return ReconnectionResult.NotConnected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||||
|
{
|
||||||
|
ApplicationMessageReceived?.Invoke(this, eventArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnDisconnected(object sender, MqttClientDisconnectedEventArgs eventArgs)
|
||||||
|
{
|
||||||
|
Disconnected?.Invoke(this, eventArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnConnected(object sender, MqttClientConnectedEventArgs eventArgs)
|
||||||
|
{
|
||||||
|
Connected?.Invoke(this, eventArgs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.ManagedClient
|
||||||
|
{
|
||||||
|
public static class ManagedMqttClientExtensions
|
||||||
|
{
|
||||||
|
public static Task SubscribeAsync(this IManagedMqttClient managedClient, params TopicFilter[] topicFilters)
|
||||||
|
{
|
||||||
|
if (managedClient == null) throw new ArgumentNullException(nameof(managedClient));
|
||||||
|
|
||||||
|
return managedClient.SubscribeAsync(topicFilters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Task UnsubscribeAsync(this IManagedMqttClient managedClient, params TopicFilter[] topicFilters)
|
||||||
|
{
|
||||||
|
if (managedClient == null) throw new ArgumentNullException(nameof(managedClient));
|
||||||
|
|
||||||
|
return managedClient.UnsubscribeAsync(topicFilters);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.ManagedClient
|
||||||
|
{
|
||||||
|
public class ManagedMqttClientOptions : IManagedMqttClientOptions
|
||||||
|
{
|
||||||
|
public IMqttClientOptions ClientOptions { get; set; }
|
||||||
|
|
||||||
|
public TimeSpan AutoReconnectDelay { get; set; } = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
|
public IManagedMqttClientStorage Storage { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using System;
|
||||||
|
using MQTTnet.Core.Client;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.ManagedClient
|
||||||
|
{
|
||||||
|
public class ManagedMqttClientOptionsBuilder
|
||||||
|
{
|
||||||
|
private readonly ManagedMqttClientOptions _options = new ManagedMqttClientOptions();
|
||||||
|
|
||||||
|
public ManagedMqttClientOptionsBuilder WithAutoReconnectDelay(TimeSpan value)
|
||||||
|
{
|
||||||
|
_options.AutoReconnectDelay = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ManagedMqttClientOptionsBuilder WithStorage(IManagedMqttClientStorage value)
|
||||||
|
{
|
||||||
|
_options.Storage = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ManagedMqttClientOptionsBuilder WithClientOptions(IMqttClientOptions value)
|
||||||
|
{
|
||||||
|
_options.ClientOptions = value ?? throw new ArgumentNullException(nameof(value));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ManagedMqttClientOptionsBuilder WithClientOptions(Action<MqttClientOptionsBuilder> options)
|
||||||
|
{
|
||||||
|
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||||
|
|
||||||
|
var builder = new MqttClientOptionsBuilder();
|
||||||
|
options(builder);
|
||||||
|
_options.ClientOptions = builder.Build();
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ManagedMqttClientOptions Build()
|
||||||
|
{
|
||||||
|
if (_options.ClientOptions == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("The ClientOptions cannot be null.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return _options;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MQTTnet.Core.ManagedClient
|
||||||
|
{
|
||||||
|
public class ManagedMqttClientStorageManager
|
||||||
|
{
|
||||||
|
private readonly List<MqttApplicationMessage> _applicationMessages = new List<MqttApplicationMessage>();
|
||||||
|
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
|
||||||
|
private IManagedMqttClientStorage _storage;
|
||||||
|
|
||||||
|
public async Task SetStorageAsync(IManagedMqttClientStorage storage)
|
||||||
|
{
|
||||||
|
await _semaphore.WaitAsync().ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_storage = storage;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_semaphore.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task AddAsync(MqttApplicationMessage applicationMessage)
|
||||||
|
{
|
||||||
|
await _semaphore.WaitAsync().ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_storage == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_applicationMessages.Add(applicationMessage);
|
||||||
|
await SaveAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_semaphore.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task RemoveAsync(MqttApplicationMessage applicationMessage)
|
||||||
|
{
|
||||||
|
await _semaphore.WaitAsync().ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_storage == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var index = _applicationMessages.IndexOf(applicationMessage);
|
||||||
|
if (index == -1)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_applicationMessages.RemoveAt(index);
|
||||||
|
await SaveAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_semaphore.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task SaveAsync()
|
||||||
|
{
|
||||||
|
return _storage.SaveQueuedMessagesAsync(_applicationMessages);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user