Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ecf658059 | ||
|
|
851db2e808 | ||
|
|
073cd5243f | ||
|
|
2918be18c6 | ||
|
|
9302e80d73 | ||
|
|
cf6f0ece0e | ||
|
|
50d65f2fed | ||
|
|
4614df7fa5 | ||
|
|
22aedcba09 | ||
|
|
2767d897a4 | ||
|
|
a4420063c0 | ||
|
|
2320352124 | ||
|
|
c0b4155ab4 | ||
|
|
b09f31d654 | ||
|
|
30c33d46f9 | ||
|
|
651b79a124 | ||
|
|
2e3cf54f11 | ||
|
|
d7948afd98 | ||
|
|
4cefa1dfa9 | ||
|
|
0cfb8b4020 | ||
|
|
9ac726b271 | ||
|
|
232605304e | ||
|
|
6c53677e7d | ||
|
|
6d0e2c2022 | ||
|
|
8ad1fb2871 | ||
|
|
4a7ff9e9ed | ||
|
|
f54598c201 | ||
|
|
2300e68fff | ||
|
|
6996824157 | ||
|
|
524f695829 | ||
|
|
72faa067cc | ||
|
|
01aa75471c | ||
|
|
048206eb1e | ||
|
|
ad5b0caa4d | ||
|
|
0f14ddcf79 | ||
|
|
59d2a8e551 | ||
|
|
8607ceb3b7 | ||
|
|
b82e5a48a4 | ||
|
|
30c5147c62 | ||
|
|
9d63500f95 | ||
|
|
a03bdc7616 | ||
|
|
413daee551 | ||
|
|
f3ea7008e5 | ||
|
|
8bfbbd2b29 | ||
|
|
ab8c7df0b9 | ||
|
|
975eb60e90 | ||
|
|
6076151222 | ||
|
|
9cc96f1888 | ||
|
|
7aa4d5159c | ||
|
|
9b021c4093 | ||
|
|
54c303369e | ||
|
|
8f30042e49 | ||
|
|
4c33270d26 | ||
|
|
5c40577bec | ||
|
|
3d404f9755 | ||
|
|
1b5e0197e4 | ||
|
|
1dab729d84 | ||
|
|
3eac5bcaf3 | ||
|
|
8eb23f0f1d | ||
|
|
1fd1a12fce | ||
|
|
349d506b37 | ||
|
|
a981b05aa7 | ||
|
|
654f06d20d | ||
|
|
c92cd10499 | ||
|
|
ed06ea6bc9 | ||
|
|
3d531151c6 | ||
|
|
e1590fc0c8 | ||
|
|
dbb227406b | ||
|
|
b891e1d1f4 | ||
|
|
1d697e3b87 | ||
|
|
128484c55a | ||
|
|
ff22c34bb2 | ||
|
|
e7ba3f76dc | ||
|
|
1ae3324581 | ||
|
|
ba8ce15ab4 | ||
|
|
87b4ce5185 | ||
|
|
4eb2b77138 | ||
|
|
70ee49f3c6 | ||
|
|
f223a26748 | ||
|
|
4574fdc951 | ||
|
|
4f66614cdd | ||
|
|
6608172719 | ||
|
|
6c8db47e25 | ||
|
|
3eb5e82d10 | ||
|
|
8563230f9c | ||
|
|
019f428f0a | ||
|
|
1847af13d2 | ||
|
|
8916df8d7b | ||
|
|
f66da92299 | ||
|
|
979df5f17e | ||
|
|
d50c8153b2 | ||
|
|
b3ab7a1069 | ||
|
|
6af58ad90d | ||
|
|
5c36a2d402 | ||
|
|
6df70cc5ed | ||
|
|
d5b0893e90 | ||
|
|
2ed8e55394 | ||
|
|
c5b6ca204d | ||
|
|
7a767c7d2f | ||
|
|
dd96cf98a8 | ||
|
|
6ee3d1640f | ||
|
|
6f8272210c | ||
|
|
ce05cc9936 | ||
|
|
985c3084a8 | ||
|
|
7b3be3a64f | ||
|
|
c50fb740fc | ||
|
|
5895a73f85 | ||
|
|
961a497798 | ||
|
|
6a90864c44 | ||
|
|
a9017b8795 | ||
|
|
f76e130283 | ||
|
|
5a48b146b4 | ||
|
|
1d1def3275 | ||
|
|
bd75a2440e | ||
|
|
7a642802ed | ||
|
|
a8f8601bc5 | ||
|
|
0c7a5a992b | ||
|
|
bd665c3d56 | ||
|
|
7e7b36aadf | ||
|
|
a79c2484b3 | ||
|
|
e4e46f0094 | ||
|
|
5a4c735b85 | ||
|
|
42516942ac | ||
|
|
591ccfec29 | ||
|
|
ffc1d950da | ||
|
|
1c004ead6d | ||
|
|
b0ad6bda70 | ||
|
|
6262a16504 | ||
|
|
0de683979d | ||
|
|
0a6f564446 | ||
|
|
f0be3ef0cf | ||
|
|
f79eebdf64 | ||
|
|
c3c0dcf313 | ||
|
|
60c6074953 | ||
|
|
2b9b22def6 | ||
|
|
5cfb092449 | ||
|
|
a450fc4e01 | ||
|
|
ffe9c57ae8 | ||
|
|
0257e31910 | ||
|
|
7fe5f521dc | ||
|
|
2d03c267e4 | ||
|
|
ccfe67e6a6 | ||
|
|
98e17903ea | ||
|
|
c7d56a78f3 | ||
|
|
b491c74228 | ||
|
|
a2414f48ca | ||
|
|
396e0e1697 | ||
|
|
01f6c959e1 | ||
|
|
f425d87562 | ||
|
|
6614b23ab8 | ||
|
|
02c9133a1c | ||
|
|
913afa3977 | ||
|
|
e068286f15 | ||
|
|
373fe8c72c | ||
|
|
396f040aae | ||
|
|
c90b5f6fb2 | ||
|
|
744b1b302b | ||
|
|
78e504dc2c | ||
|
|
79518d4a35 | ||
|
|
a50fb2a320 | ||
|
|
9fa9d22097 | ||
|
|
e4351b73bd | ||
|
|
2d3fdd4faf | ||
|
|
0a509fd685 | ||
|
|
d1a17314ef | ||
|
|
e96b66e9f8 | ||
|
|
80b05a8944 | ||
|
|
ab3df2ba65 | ||
|
|
f169aaa79b | ||
|
|
231001850a | ||
|
|
6839970d41 | ||
|
|
4df29be155 | ||
|
|
c5cfede231 | ||
|
|
c22b6033e3 | ||
|
|
27476a9194 | ||
|
|
12973a4179 | ||
|
|
01b437dc08 | ||
|
|
ac88f0a05a | ||
|
|
b02f30844c | ||
|
|
1a8bcae47c | ||
|
|
664549ab93 | ||
|
|
914d2b641f | ||
|
|
0cc0fcf5d9 | ||
|
|
5980cbd944 | ||
|
|
3ef7f60a18 |
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve.
|
||||
title: ''
|
||||
labels: 'bug'
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
### Describe the bug
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
### Which project is your bug related to?
|
||||
<!-- Remove the items which don't apply from the following list -->
|
||||
- Client
|
||||
- ManagedClient
|
||||
- MQTTnet.Server standalone
|
||||
- Server
|
||||
- Generic
|
||||
|
||||
### To Reproduce
|
||||
Steps to reproduce the behavior:
|
||||
1. Using this version of MQTTnet '...'.
|
||||
2. Run this code '....'.
|
||||
3. With these arguments '....'.
|
||||
4. See error.
|
||||
|
||||
### Expected behavior
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
### Screenshots
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
### Additional context / logging
|
||||
Add any other context about the problem here.
|
||||
Include debugging or logging information here:
|
||||
|
||||
```batch
|
||||
\\ Put your logging output here.
|
||||
```
|
||||
### Code example
|
||||
Please provide full code examples below where possible to make it easier for the developers to check your issues.
|
||||
|
||||
```csharp
|
||||
\\ Put your code here.
|
||||
```
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: Custom issue template
|
||||
about: Do you have a question related to the project? Use this template.
|
||||
title: ''
|
||||
labels: 'question'
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
### Describe your question
|
||||
A clear and concise description of what you want to know.
|
||||
|
||||
### Which project is your question related to?
|
||||
<!-- Remove the items which don't apply from the following list -->
|
||||
- Client
|
||||
- ManagedClient
|
||||
- MQTTnet.Server standalone
|
||||
- Server
|
||||
- Generic
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project.
|
||||
title: ''
|
||||
labels: 'feature-request'
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
### Describe the feature request
|
||||
Is your feature request related to a problem? Please describe.
|
||||
A clear and concise description of what the problem is. Example. I'm am trying to do [...] but [...]
|
||||
|
||||
### Which project is your feature request related to?
|
||||
<!-- Remove the items which don't apply from the following list -->
|
||||
- Client
|
||||
- ManagedClient
|
||||
- MQTTnet.Server standalone
|
||||
- Server
|
||||
- Generic
|
||||
|
||||
### Describe the solution you'd like
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
### Describe alternatives you've considered
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
### Additional context
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -292,3 +292,5 @@ __pycache__/
|
||||
*.map
|
||||
|
||||
/Tests/MQTTnet.TestApp.NetCore/RetainedMessages.json
|
||||
|
||||
Build/NuGet/
|
||||
|
||||
@@ -34,10 +34,9 @@
|
||||
<!-- .NET Framework -->
|
||||
<file src="..\Source\MQTTnet.Extensions.ManagedClient\bin\Release\net452\MQTTnet.Extensions.ManagedClient.*" target="lib\net452\"/>
|
||||
|
||||
<file src="..\Source\MQTTnet.Extensions.ManagedClient\bin\Release\netstandard2.0\MQTTnet.Extensions.ManagedClient.*" target="lib\net461\"/>
|
||||
<file src="..\Source\MQTTnet.Extensions.ManagedClient\bin\Release\netstandard2.0\MQTTnet.Extensions.ManagedClient.*" target="lib\net462\"/>
|
||||
<file src="..\Source\MQTTnet.Extensions.ManagedClient\bin\Release\netstandard2.0\MQTTnet.Extensions.ManagedClient.*" target="lib\net470\"/>
|
||||
<file src="..\Source\MQTTnet.Extensions.ManagedClient\bin\Release\netstandard2.0\MQTTnet.Extensions.ManagedClient.*" target="lib\net471\"/>
|
||||
<file src="..\Source\MQTTnet.Extensions.ManagedClient\bin\Release\netstandard2.0\MQTTnet.Extensions.ManagedClient.*" target="lib\net472\"/>
|
||||
<!-- .NET Framework 4.6.0 will use binaries from 4.5.2. -->
|
||||
<file src="..\Source\MQTTnet.Extensions.ManagedClient\bin\Release\net461\MQTTnet.Extensions.Rpc.*" target="lib\net461\"/>
|
||||
|
||||
<!-- Everything above .NET Framework 4.6.1 will use the binaries from 4.6.1. -->
|
||||
</files>
|
||||
</package>
|
||||
|
||||
@@ -34,10 +34,9 @@
|
||||
<!-- .NET Framework -->
|
||||
<file src="..\Source\MQTTnet.Extensions.Rpc\bin\Release\net452\MQTTnet.Extensions.Rpc.*" target="lib\net452\"/>
|
||||
|
||||
<file src="..\Source\MQTTnet.Extensions.Rpc\bin\Release\netstandard2.0\MQTTnet.Extensions.Rpc.*" target="lib\net461\"/>
|
||||
<file src="..\Source\MQTTnet.Extensions.Rpc\bin\Release\netstandard2.0\MQTTnet.Extensions.Rpc.*" target="lib\net462\"/>
|
||||
<file src="..\Source\MQTTnet.Extensions.Rpc\bin\Release\netstandard2.0\MQTTnet.Extensions.Rpc.*" target="lib\net470\"/>
|
||||
<file src="..\Source\MQTTnet.Extensions.Rpc\bin\Release\netstandard2.0\MQTTnet.Extensions.Rpc.*" target="lib\net471\"/>
|
||||
<file src="..\Source\MQTTnet.Extensions.Rpc\bin\Release\netstandard2.0\MQTTnet.Extensions.Rpc.*" target="lib\net472\"/>
|
||||
<!-- .NET Framework 4.6.0 will use binaries from 4.5.2. -->
|
||||
<file src="..\Source\MQTTnet.Extensions.Rpc\bin\Release\net461\MQTTnet.Extensions.Rpc.*" target="lib\net461\"/>
|
||||
|
||||
<!-- Everything above .NET Framework 4.6.1 will use the binaries from 4.6.1. -->
|
||||
</files>
|
||||
</package>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0"?>
|
||||
<package >
|
||||
<metadata>
|
||||
<id>MQTTnet.Extensions.WebSocket4Net</id>
|
||||
<version>0.0.0</version>
|
||||
<authors>Christian Kratky</authors>
|
||||
<owners>Christian Kratky</owners>
|
||||
<license type="file">LICENSE</license>
|
||||
<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 an extension library which allows using _WebSocket4Net_ as transport for MQTTnet clients.</description>
|
||||
<releaseNotes>For release notes please go to MQTTnet release notes (https://www.nuget.org/packages/MQTTnet/).</releaseNotes>
|
||||
<copyright>Copyright Christian Kratky 2016-2019</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>
|
||||
<dependency id="MQTTnet" version="$nugetVersion" />
|
||||
</dependencies>
|
||||
</metadata>
|
||||
|
||||
<files>
|
||||
<!-- License -->
|
||||
<file src="..\LICENSE" />
|
||||
|
||||
<!-- .NET Standard 1.3 -->
|
||||
<file src="..\Source\MQTTnet.Extensions.WebSocket4Net\bin\Release\netstandard1.3\MQTTnet.Extensions.WebSocket4Net.*" target="lib\netstandard1.3\"/>
|
||||
|
||||
<!-- .NET Standard 2.0 -->
|
||||
<file src="..\Source\MQTTnet.Extensions.WebSocket4Net\bin\Release\netstandard2.0\MQTTnet.Extensions.WebSocket4Net.*" target="lib\netstandard2.0\"/>
|
||||
|
||||
<!-- Universal Windows -->
|
||||
<file src="..\Source\MQTTnet.Extensions.WebSocket4Net\bin\Release\uap10.0\MQTTnet.Extensions.WebSocket4Net.*" target="lib\uap10.0\"/>
|
||||
|
||||
<!-- .NET Framework -->
|
||||
<file src="..\Source\MQTTnet.Extensions.WebSocket4Net\bin\Release\net452\MQTTnet.Extensions.WebSocket4Net.*" target="lib\net452\"/>
|
||||
|
||||
<!-- .NET Framework 4.6.0 will use binaries from 4.5.2. -->
|
||||
<file src="..\Source\MQTTnet.Extensions.WebSocket4Net\bin\Release\net461\MQTTnet.Extensions.WebSocket4Net.*" target="lib\net461\"/>
|
||||
|
||||
<!-- Everything above .NET Framework 4.6.1 will use the binaries from 4.6.1. -->
|
||||
</files>
|
||||
</package>
|
||||
@@ -9,7 +9,7 @@
|
||||
<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). This package contains the .NET Standard version of the library only.</description>
|
||||
<description>This package contains the .NET Standard version of MQTTnet only.</description>
|
||||
<releaseNotes>For release notes please go to MQTTnet release notes (https://www.nuget.org/packages/MQTTnet/).</releaseNotes>
|
||||
<copyright>Copyright Christian Kratky 2016-2019</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>
|
||||
|
||||
@@ -9,38 +9,10 @@
|
||||
<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>
|
||||
<description>MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker) and supports v3.1.0, v3.1.1 and v5.0.0 of the MQTT protocol.</description>
|
||||
<releaseNotes>
|
||||
* [Core] Added support for MQTTv5 packages.
|
||||
* [Core] Performance improvements.
|
||||
* [Core] Removed obsolete methods.
|
||||
* [Core] Fixed a memory leak when processing lots of messages (thanks to @tschanko)
|
||||
* [Core] Added more overloads for MQTT factory.
|
||||
* [Core] The client password is now hidden from the logs (replaced with **** if set).
|
||||
* [Core] Fixed a memory leak when using SSL connections (thanks to @biovoid).
|
||||
* [Client] Added validation of topics before publishing.
|
||||
* [Client] Added new MQTTv5 features to options builder.
|
||||
* [Client] Added uniform API across all supported MQTT versions (BREAKING CHANGE!)
|
||||
* [Client] The client will now avoid sending an ACK if an exception has been thrown in message handler (thanks to @ramonsmits).
|
||||
* [Client] Fixed issues in QoS 2 handling which leads to message loss.
|
||||
* [Client] Replaced all events with proper async compatible handlers (BREAKING CHANGE!).
|
||||
* [Client] Added more configuration values to TCP endpoint options.
|
||||
* [Client] Added used PacketIdentifier to publish result.
|
||||
* [ManagedClient] Replaced all events with proper async compatible handlers (BREAKING CHANGE!).
|
||||
* [ManagedClient] The log ID is now propagated to the internal client (thanks to @vbBerni).
|
||||
* [ManagedClient] Added validation of topics before publishing.
|
||||
* [ManagedClient] The internal MQTT client is now closed properly (thanks to @vbBerni).
|
||||
* [Server] Added support for MQTTv5 clients. The server will still return _success_ for all cases at the moment even if more granular codes are available.
|
||||
* [Server] Fixed issues in QoS 2 handling which leads to message loss.
|
||||
* [Server] Replaced all events with proper async compatible handlers (BREAKING CHANGE!).
|
||||
* [Server] The used logger instance is now propagated to the WebSocket server adapter.
|
||||
* [Server] Added the flag "IsSecureConnection" which is set to true when the connection is encrypted.
|
||||
* [Server] Fixed wrong will message behavior when stopping server (thanks to @JohBa)
|
||||
* [Server] Added validation of topics before publishing.
|
||||
* [Server] Added more configuration values to TCP endpoint options.
|
||||
* [MQTTnet Server] Added as first Alpha version of standalone cross platform MQTT server.
|
||||
|
||||
* [Note] Due to MQTTv5 a lot of new classes were introduced. This required adding new namespaces as well. Most classes are backward compatible but new namespaces must be added.
|
||||
* [ManagedClient] Added support for persisted sessions (thansk to @PMExtra).
|
||||
* [Server] Added support for assigned client IDs (MQTTv5 only) (thanks to @bcrosnier).
|
||||
</releaseNotes>
|
||||
<copyright>Copyright Christian Kratky 2016-2019</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>
|
||||
@@ -60,10 +32,6 @@
|
||||
<group targetFramework="uap10.0">
|
||||
<dependency id="Microsoft.NETCore.UniversalWindowsPlatform" version="6.2.8" />
|
||||
</group>
|
||||
<group targetFramework="net452">
|
||||
</group>
|
||||
<group targetFramework="net461">
|
||||
</group>
|
||||
</dependencies>
|
||||
</metadata>
|
||||
|
||||
@@ -83,10 +51,9 @@
|
||||
<!-- .NET Framework -->
|
||||
<file src="..\Source\MQTTnet\bin\Release\net452\MQTTnet.*" target="lib\net452\"/>
|
||||
|
||||
<file src="..\Source\MQTTnet\bin\Release\netstandard2.0\MQTTnet.*" target="lib\net461\"/>
|
||||
<file src="..\Source\MQTTnet\bin\Release\netstandard2.0\MQTTnet.*" target="lib\net462\"/>
|
||||
<file src="..\Source\MQTTnet\bin\Release\netstandard2.0\MQTTnet.*" target="lib\net470\"/>
|
||||
<file src="..\Source\MQTTnet\bin\Release\netstandard2.0\MQTTnet.*" target="lib\net471\"/>
|
||||
<file src="..\Source\MQTTnet\bin\Release\netstandard2.0\MQTTnet.*" target="lib\net472\"/>
|
||||
<!-- .NET Framework 4.6.0 will use binaries from 4.5.2. -->
|
||||
<file src="..\Source\MQTTnet\bin\Release\net461\MQTTnet.*" target="lib\net461\"/>
|
||||
|
||||
<!-- Everything above .NET Framework 4.6.1 will use the binaries from 4.6.1. -->
|
||||
</files>
|
||||
</package>
|
||||
</package>
|
||||
|
||||
@@ -12,6 +12,13 @@ Write-Host "Nuget version = $nugetVersion"
|
||||
Write-Host "MSBuild path = $msbuild"
|
||||
Write-Host
|
||||
|
||||
# Build and execute tests
|
||||
&$msbuild ..\Tests\MQTTnet.Core.Tests\MQTTnet.Tests.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp2.1" /verbosity:m
|
||||
&$msbuild ..\Tests\MQTTnet.AspNetCore.Tests\MQTTnet.AspNetCore.Tests.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp2.1" /verbosity:m
|
||||
|
||||
vstest.console.exe ..\Tests\MQTTnet.Core.Tests\bin\Release\netcoreapp2.1\MQTTnet.Tests.dll
|
||||
vstest.console.exe ..\Tests\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp2.1\MQTTnet.AspNetCore.Tests.dll
|
||||
|
||||
# Build the core library
|
||||
&$msbuild ..\Source\MQTTnet\MQTTnet.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net452" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
&$msbuild ..\Source\MQTTnet\MQTTnet.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net461" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
@@ -36,17 +43,16 @@ Write-Host
|
||||
&$msbuild ..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
&$msbuild ..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="uap10.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
|
||||
# Build MQTTnet.Server
|
||||
Remove-Item ..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2 -Recurse -Force -ErrorAction SilentlyContinue
|
||||
&$msbuild ..\Source\MQTTnet.Server\MQTTnet.Server.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp2.2" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
|
||||
$source = "..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2"
|
||||
$destination = "..\Source\MQTTnet.Server\bin\MQTTnet.Server-Portable-v$nugetVersion.zip"
|
||||
If(Test-path $destination) {Remove-item $destination}
|
||||
Add-Type -assembly "system.io.compression.filesystem"
|
||||
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
|
||||
# Build the WebSocket4Net extension
|
||||
&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net452" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net461" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard1.3" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netstandard2.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
&$msbuild ..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="uap10.0" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
|
||||
|
||||
# Create NuGet packages.
|
||||
Invoke-WebRequest -Uri "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" -OutFile "nuget.exe"
|
||||
|
||||
Remove-Item .\NuGet -Force -Recurse -ErrorAction SilentlyContinue
|
||||
|
||||
Copy-Item MQTTnet.AspNetCore.nuspec -Destination MQTTnet.AspNetCore.nuspec.old -Force
|
||||
@@ -55,14 +61,66 @@ Copy-Item MQTTnet.Extensions.Rpc.nuspec -Destination MQTTnet.Extensions.Rpc.nusp
|
||||
(Get-Content MQTTnet.Extensions.Rpc.nuspec) -replace '\$nugetVersion', $nugetVersion | Set-Content MQTTnet.Extensions.Rpc.nuspec
|
||||
Copy-Item MQTTnet.Extensions.ManagedClient.nuspec -Destination MQTTnet.Extensions.ManagedClient.nuspec.old -Force
|
||||
(Get-Content MQTTnet.Extensions.ManagedClient.nuspec) -replace '\$nugetVersion', $nugetVersion | Set-Content MQTTnet.Extensions.ManagedClient.nuspec
|
||||
Copy-Item MQTTnet.Extensions.WebSocket4Net.nuspec -Destination MQTTnet.Extensions.WebSocket4Net.nuspec.old -Force
|
||||
(Get-Content MQTTnet.Extensions.WebSocket4Net.nuspec) -replace '\$nugetVersion', $nugetVersion | Set-Content MQTTnet.Extensions.WebSocket4Net.nuspec
|
||||
|
||||
New-Item -ItemType Directory -Force -Path .\NuGet
|
||||
.\nuget.exe pack MQTTnet.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.NETStandard.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.AspNetCore.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.Extensions.Rpc.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.Extensions.ManagedClient.nuspec -Verbosity detailed -Symbols -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.nuspec -Verbosity detailed -Symbols -SymbolPackageFormat snupkg -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.NETStandard.nuspec -Verbosity detailed -Symbols -SymbolPackageFormat snupkg -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.AspNetCore.nuspec -Verbosity detailed -Symbols -SymbolPackageFormat snupkg -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.Extensions.Rpc.nuspec -Verbosity detailed -Symbols -SymbolPackageFormat snupkg -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.Extensions.ManagedClient.nuspec -Verbosity detailed -Symbols -SymbolPackageFormat snupkg -OutputDir "NuGet" -Version $nugetVersion
|
||||
.\nuget.exe pack MQTTnet.Extensions.WebSocket4Net.nuspec -Verbosity detailed -Symbols -SymbolPackageFormat snupkg -OutputDir "NuGet" -Version $nugetVersion
|
||||
|
||||
Move-Item MQTTnet.AspNetCore.nuspec.old -Destination MQTTnet.AspNetCore.nuspec -Force
|
||||
Move-Item MQTTnet.Extensions.Rpc.nuspec.old -Destination MQTTnet.Extensions.Rpc.nuspec -Force
|
||||
Move-Item MQTTnet.Extensions.ManagedClient.nuspec.old -Destination MQTTnet.Extensions.ManagedClient.nuspec -Force
|
||||
Move-Item MQTTnet.Extensions.ManagedClient.nuspec.old -Destination MQTTnet.Extensions.ManagedClient.nuspec -Force
|
||||
Move-Item MQTTnet.Extensions.WebSocket4Net.nuspec.old -Destination MQTTnet.Extensions.WebSocket4Net.nuspec -Force
|
||||
|
||||
Remove-Item "nuget.exe" -Force -Recurse -ErrorAction SilentlyContinue
|
||||
|
||||
####################################################################
|
||||
|
||||
# Build MQTTnet.Server Portable
|
||||
&dotnet publish ..\Source\MQTTnet.Server\MQTTnet.Server.csproj --configuration Release /p:FileVersion=$assemblyVersion /p:Version=$nugetVersion
|
||||
|
||||
$source = "..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2\publish"
|
||||
$destination = "..\Source\MQTTnet.Server\bin\MQTTnet.Server-Portable-v$nugetVersion.zip"
|
||||
If(Test-path $destination) {Remove-item $destination}
|
||||
Add-Type -assembly "system.io.compression.filesystem"
|
||||
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
|
||||
|
||||
####################################################################
|
||||
|
||||
# Build MQTTnet.Server Linux-x64
|
||||
&dotnet publish ..\Source\MQTTnet.Server\MQTTnet.Server.csproj --configuration Release /p:FileVersion=$assemblyVersion /p:Version=$nugetVersion --self-contained --runtime linux-x64
|
||||
|
||||
$source = "..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2\linux-x64\publish"
|
||||
$destination = "..\Source\MQTTnet.Server\bin\MQTTnet.Server-Linux-x64-v$nugetVersion.zip"
|
||||
If(Test-path $destination) {Remove-item $destination}
|
||||
Add-Type -assembly "system.io.compression.filesystem"
|
||||
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
|
||||
|
||||
####################################################################
|
||||
|
||||
# Build MQTTnet.Server Linux-ARM
|
||||
&dotnet publish ..\Source\MQTTnet.Server\MQTTnet.Server.csproj --configuration Release /p:FileVersion=$assemblyVersion /p:Version=$nugetVersion --self-contained --runtime linux-arm
|
||||
|
||||
$source = "..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2\linux-ARM\publish"
|
||||
$destination = "..\Source\MQTTnet.Server\bin\MQTTnet.Server-Linux-ARM-v$nugetVersion.zip"
|
||||
If(Test-path $destination) {Remove-item $destination}
|
||||
Add-Type -assembly "system.io.compression.filesystem"
|
||||
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
|
||||
|
||||
####################################################################
|
||||
|
||||
# Build MQTTnet.Server Windows-x64
|
||||
&dotnet publish ..\Source\MQTTnet.Server\MQTTnet.Server.csproj --configuration Release /p:FileVersion=$assemblyVersion /p:Version=$nugetVersion --self-contained --runtime win-x64
|
||||
|
||||
$source = "..\Source\MQTTnet.Server\bin\Release\netcoreapp2.2\win-x64\publish"
|
||||
$destination = "..\Source\MQTTnet.Server\bin\MQTTnet.Server-Windows-x64-v$nugetVersion.zip"
|
||||
If(Test-path $destination) {Remove-item $destination}
|
||||
Add-Type -assembly "system.io.compression.filesystem"
|
||||
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
|
||||
|
||||
####################################################################
|
||||
@@ -1,9 +1,13 @@
|
||||
param([string]$apiKey)
|
||||
|
||||
Invoke-WebRequest -Uri "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" -OutFile "nuget.exe"
|
||||
|
||||
$files = Get-ChildItem -Path ".\NuGet" -Filter "*.nupkg"
|
||||
foreach ($file in $files)
|
||||
{
|
||||
Write-Host "Uploading: " $file
|
||||
|
||||
.\nuget.exe push $file.Fullname $apiKey -NoSymbols -Source https://api.nuget.org/v3/index.json
|
||||
}
|
||||
.\nuget.exe push $file.Fullname $apiKey -Source https://api.nuget.org/v3/index.json
|
||||
}
|
||||
|
||||
Remove-Item "nuget.exe" -Force -Recurse -ErrorAction SilentlyContinue
|
||||
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,239 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="210mm"
|
||||
height="297mm"
|
||||
viewBox="0 0 210 297"
|
||||
version="1.1"
|
||||
id="svg8"
|
||||
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
|
||||
sodipodi:docname="MQTT.svg">
|
||||
<defs
|
||||
id="defs2">
|
||||
<filter
|
||||
inkscape:label="Blur Double"
|
||||
inkscape:menu="Blurs"
|
||||
inkscape:menu-tooltip="Overlays two copies with different blur amounts and modifiable blend and composite"
|
||||
style="color-interpolation-filters:sRGB;"
|
||||
id="filter3801">
|
||||
<feGaussianBlur
|
||||
stdDeviation="5"
|
||||
result="fbSourceGraphic"
|
||||
id="feGaussianBlur3793" />
|
||||
<feGaussianBlur
|
||||
stdDeviation="0.01"
|
||||
in="SourceGraphic"
|
||||
result="result1"
|
||||
id="feGaussianBlur3795" />
|
||||
<feComposite
|
||||
in2="result1"
|
||||
operator="arithmetic"
|
||||
in="fbSourceGraphic"
|
||||
k2="0.5"
|
||||
k3="0.5"
|
||||
result="result2"
|
||||
id="feComposite3797" />
|
||||
<feBlend
|
||||
in2="fbSourceGraphic"
|
||||
mode="normal"
|
||||
result="result3"
|
||||
id="feBlend3799" />
|
||||
</filter>
|
||||
</defs>
|
||||
<sodipodi:namedview
|
||||
id="base"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1.0"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:zoom="0.24748737"
|
||||
inkscape:cx="955.72999"
|
||||
inkscape:cy="295.38958"
|
||||
inkscape:document-units="mm"
|
||||
inkscape:current-layer="layer1"
|
||||
showgrid="false"
|
||||
inkscape:window-width="3840"
|
||||
inkscape:window-height="2066"
|
||||
inkscape:window-x="2989"
|
||||
inkscape:window-y="-11"
|
||||
inkscape:window-maximized="1" />
|
||||
<metadata
|
||||
id="metadata5">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
inkscape:label="Layer 1"
|
||||
inkscape:groupmode="layer"
|
||||
id="layer1">
|
||||
<rect
|
||||
ry="50"
|
||||
rx="50"
|
||||
style="fill:#000000;stroke-width:0.26458332;filter:url(#filter3801)"
|
||||
y="92.501205"
|
||||
x="56.367012"
|
||||
height="512"
|
||||
width="512"
|
||||
id="rect3791"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<rect
|
||||
id="rect3713"
|
||||
width="512"
|
||||
height="512"
|
||||
x="53.721176"
|
||||
y="88.797035"
|
||||
style="fill:#aa0000;stroke-width:0.26458332"
|
||||
rx="50"
|
||||
ry="50"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<rect
|
||||
style="fill:#ce0000;fill-opacity:0.60591131;stroke-width:0.28100395"
|
||||
id="rect3806"
|
||||
width="143.25298"
|
||||
height="9.0714283"
|
||||
x="270.81995"
|
||||
y="554.02386"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<path
|
||||
inkscape:connector-curvature="0"
|
||||
id="path4638"
|
||||
d="m 494.14104,142.00092 -5.35736,41.28822 67.77684,374.38977 a 263.46279,229.17651 36.835702 0 1 4.98278,-0.4605 263.46279,229.17651 36.835702 0 1 7.77403,0.0471 z"
|
||||
style="fill:#ce0000;fill-opacity:0.60591131;stroke-width:0.59952348"
|
||||
inkscape:transform-center-x="-28.818481"
|
||||
inkscape:transform-center-y="146.97441"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<path
|
||||
style="fill:#d40000;stroke-width:1.76103246"
|
||||
d="m 2138.1582,1411.377 a 995.76488,866.17897 0 0 0 -842.3984,854.3418 995.76488,866.17897 0 0 0 0.2988,5.0097 h 653.123 c 104.693,0 188.9766,-84.2836 188.9766,-188.9765 z"
|
||||
transform="scale(0.26458333)"
|
||||
id="path3715-5-8"
|
||||
inkscape:connector-curvature="0"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<ellipse
|
||||
style="fill:#d40000;stroke-width:0.06901014"
|
||||
id="path3715-5"
|
||||
cx="492.58557"
|
||||
cy="170.58017"
|
||||
rx="39.021355"
|
||||
ry="33.94323"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<path
|
||||
style="fill:#ce0000;fill-opacity:0.60591131;stroke-width:2.26591563"
|
||||
d="M 464.66602,532.89453 542.01562,669.92969 1595.373,1648.873 a 995.76487,866.17896 0 0 1 14.0293,-12.6835 995.76487,866.17896 0 0 1 23.6231,-17.4727 z"
|
||||
id="rect3806-2"
|
||||
inkscape:connector-curvature="0"
|
||||
transform="scale(0.26458333)"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-weight:normal;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332"
|
||||
x="102.34985"
|
||||
y="320.75201"
|
||||
id="text3774"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001"><tspan
|
||||
sodipodi:role="line"
|
||||
id="tspan3772"
|
||||
x="102.34985"
|
||||
y="320.75201"
|
||||
style="font-size:141.1111145px;fill:#ffffff;stroke-width:0.26458332">MQTT</tspan></text>
|
||||
<ellipse
|
||||
ry="33.94323"
|
||||
rx="39.021355"
|
||||
cy="148.56271"
|
||||
cx="124.47787"
|
||||
id="ellipse3768"
|
||||
style="fill:#d40000;stroke-width:0.06901014"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<ellipse
|
||||
style="fill:#d40000;stroke-width:0.06901014"
|
||||
id="ellipse3770"
|
||||
cx="234.9953"
|
||||
cy="556.91571"
|
||||
rx="39.021355"
|
||||
ry="33.94323"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001" />
|
||||
<text
|
||||
id="text3778"
|
||||
y="474.73837"
|
||||
x="194.57605"
|
||||
style="font-style:normal;font-weight:normal;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332"
|
||||
xml:space="preserve"
|
||||
inkscape:export-xdpi="2.6500001"
|
||||
inkscape:export-ydpi="2.6500001"><tspan
|
||||
style="font-size:141.1111145px;fill:#ffffff;stroke-width:0.26458332"
|
||||
y="474.73837"
|
||||
x="194.57605"
|
||||
id="tspan3776"
|
||||
sodipodi:role="line">net</tspan></text>
|
||||
<rect
|
||||
ry="50"
|
||||
rx="50"
|
||||
style="fill:#aa0000;stroke-width:0.26458332"
|
||||
y="97.349655"
|
||||
x="-672.18286"
|
||||
height="512"
|
||||
width="512"
|
||||
id="rect4642"
|
||||
inkscape:export-xdpi="6.3499999"
|
||||
inkscape:export-ydpi="6.3499999" />
|
||||
<path
|
||||
inkscape:connector-curvature="0"
|
||||
id="path4648"
|
||||
d="m -160.18302,381.97945 a 263.46279,229.17652 0 0 0 -222.88457,226.0446 263.46279,229.17652 0 0 0 0.0791,1.32549 h 172.80546 c 27.70002,0 50.00005,-22.30004 50.00005,-50.00004 z"
|
||||
style="fill:#d40000;stroke-width:0.46593982"
|
||||
inkscape:export-xdpi="6.3499999"
|
||||
inkscape:export-ydpi="6.3499999" />
|
||||
<text
|
||||
id="text4656"
|
||||
y="329.30466"
|
||||
x="-639.42944"
|
||||
style="font-style:normal;font-weight:normal;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332"
|
||||
xml:space="preserve"
|
||||
inkscape:export-xdpi="6.3499999"
|
||||
inkscape:export-ydpi="6.3499999"><tspan
|
||||
style="font-weight:bold;font-size:141.1111145px;fill:#ffffff;stroke-width:0.26458332"
|
||||
y="329.30466"
|
||||
x="-639.42944"
|
||||
id="tspan4654"
|
||||
sodipodi:role="line">MQTT</tspan></text>
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-weight:normal;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332"
|
||||
x="-550.90747"
|
||||
y="482.23267"
|
||||
id="text4664"
|
||||
inkscape:export-xdpi="6.3499999"
|
||||
inkscape:export-ydpi="6.3499999"><tspan
|
||||
sodipodi:role="line"
|
||||
id="tspan4662"
|
||||
x="-550.90747"
|
||||
y="482.23267"
|
||||
style="font-weight:bold;font-size:141.1111145px;fill:#ffffff;stroke-width:0.26458332">net</tspan></text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
@@ -47,6 +47,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Tests", "Tests\MQTT
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Server", "Source\MQTTnet.Server\MQTTnet.Server.csproj", "{DADEA836-5CC3-474C-A2D8-4D0F31118CD7}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Extensions.WebSocket4Net", "Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj", "{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -219,6 +221,22 @@ Global
|
||||
{DADEA836-5CC3-474C-A2D8-4D0F31118CD7}.Release|x64.Build.0 = Release|Any CPU
|
||||
{DADEA836-5CC3-474C-A2D8-4D0F31118CD7}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{DADEA836-5CC3-474C-A2D8-4D0F31118CD7}.Release|x86.Build.0 = Release|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Debug|ARM.ActiveCfg = Debug|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Debug|ARM.Build.0 = Debug|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Release|ARM.ActiveCfg = Release|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Release|ARM.Build.0 = Release|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Release|x64.Build.0 = Release|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -234,6 +252,7 @@ Global
|
||||
{61B62223-F5D0-48E4-BBD6-2CBA9353CB5E} = {9248C2E1-B9D6-40BF-81EC-86004D7765B4}
|
||||
{9C7106CA-96B8-4ABE-B3B4-9357AB8ACB41} = {9248C2E1-B9D6-40BF-81EC-86004D7765B4}
|
||||
{DADEA836-5CC3-474C-A2D8-4D0F31118CD7} = {32A630A7-2598-41D7-B625-204CD906F5FB}
|
||||
{9AE2F8DA-4178-470B-B8C4-88BE1DAE7D5F} = {12816BCC-AF9E-44A9-9AE5-C246AF2A0587}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {07536672-5CBC-4BE3-ACE0-708A431A7894}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.28729.10
|
||||
VisualStudioVersion = 16.0.29009.5
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Tests", "Tests\MQTTnet.Core.Tests\MQTTnet.Tests.csproj", "{A7FF0C91-25DE-4BA6-B39E-F54E8DADF1CC}"
|
||||
EndProject
|
||||
@@ -19,6 +19,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{67C28AC1
|
||||
Build\MQTTnet.AspNetCore.nuspec = Build\MQTTnet.AspNetCore.nuspec
|
||||
Build\MQTTnet.Extensions.ManagedClient.nuspec = Build\MQTTnet.Extensions.ManagedClient.nuspec
|
||||
Build\MQTTnet.Extensions.Rpc.nuspec = Build\MQTTnet.Extensions.Rpc.nuspec
|
||||
Build\MQTTnet.Extensions.WebSocket4Net.nuspec = Build\MQTTnet.Extensions.WebSocket4Net.nuspec
|
||||
Build\MQTTnet.NETStandard.nuspec = Build\MQTTnet.NETStandard.nuspec
|
||||
Build\MQTTnet.nuspec = Build\MQTTnet.nuspec
|
||||
Build\upload.ps1 = Build\upload.ps1
|
||||
@@ -50,6 +51,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.AspNetCore.Tests",
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Server", "Source\MQTTnet.Server\MQTTnet.Server.csproj", "{5699FB8C-838C-4AB0-80A5-9CA809F9B65B}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Extensions.WebSocket4Net", "Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj", "{2BD01D53-4CA5-4142-BE8D-313876395E3E}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -245,6 +248,22 @@ Global
|
||||
{5699FB8C-838C-4AB0-80A5-9CA809F9B65B}.Release|x64.Build.0 = Release|Any CPU
|
||||
{5699FB8C-838C-4AB0-80A5-9CA809F9B65B}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{5699FB8C-838C-4AB0-80A5-9CA809F9B65B}.Release|x86.Build.0 = Release|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|ARM.ActiveCfg = Debug|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|ARM.Build.0 = Debug|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|ARM.ActiveCfg = Release|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|ARM.Build.0 = Release|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -261,6 +280,7 @@ Global
|
||||
{C400533A-8EBA-4F0B-BF4D-295C3708604B} = {12816BCC-AF9E-44A9-9AE5-C246AF2A0587}
|
||||
{61B62223-F5D0-48E4-BBD6-2CBA9353CB5E} = {9248C2E1-B9D6-40BF-81EC-86004D7765B4}
|
||||
{5699FB8C-838C-4AB0-80A5-9CA809F9B65B} = {32A630A7-2598-41D7-B625-204CD906F5FB}
|
||||
{2BD01D53-4CA5-4142-BE8D-313876395E3E} = {12816BCC-AF9E-44A9-9AE5-C246AF2A0587}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {07536672-5CBC-4BE3-ACE0-708A431A7894}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img src="https://github.com/chkr1011/MQTTnet/blob/master/Images/Logo_128x128.png?raw=true" width="128">
|
||||
<img src="https://github.com/chkr1011/MQTTnet/blob/master/Images/icon_det_256.png?raw=true" width="196">
|
||||
<br/>
|
||||
<br/>
|
||||
</p>
|
||||
@@ -8,7 +8,8 @@
|
||||
[](https://ci.appveyor.com/project/chkr1011/mqttnet)
|
||||
[](https://bettercodehub.com/)
|
||||
[](https://opencollective.com/mqttnet)
|
||||
[](https://opencollective.com/mqttnet)
|
||||
[](https://opencollective.com/mqttnet) [](https://gitter.im/MQTTnet/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](https://raw.githubusercontent.com/chkr1011/MQTTnet/master/LICENSE)
|
||||
|
||||
# MQTTnet
|
||||
|
||||
@@ -26,7 +27,7 @@ MQTTnet is a high performance .NET library for MQTT based communication. It prov
|
||||
* Uniform API across all supported versions of the MQTT protocol
|
||||
* Interfaces included for mocking and testing
|
||||
* Access to internal trace messages
|
||||
* Unit tested (~200 tests)
|
||||
* Unit tested (~210 tests)
|
||||
* No external dependencies
|
||||
|
||||
\* Tested on local machine (Intel i7 8700K) with MQTTnet client and server running in the same process using the TCP channel. The app for verification is part of this repository and stored in _/Tests/MQTTnet.TestApp.NetCore_.
|
||||
@@ -104,6 +105,8 @@ This library is used in the following projects:
|
||||
* MQTT Tester (MQTT client test app for [Android](https://play.google.com/store/apps/details?id=com.liveowl.mqtttester) and [iOS](https://itunes.apple.com/us/app/mqtt-tester/id1278621826?mt=8))
|
||||
* Wirehome.Core (Open Source Home Automation system for .NET Core, <https://github.com/chkr1011/Wirehome.Core>)
|
||||
|
||||
Further projects using this project can be found under https://github.com/chkr1011/MQTTnet/network/dependents.
|
||||
|
||||
If you use this library and want to see your project here please create a pull request.
|
||||
|
||||
## License
|
||||
|
||||
@@ -7,6 +7,7 @@ using MQTTnet.Formatter;
|
||||
using MQTTnet.Packets;
|
||||
using System;
|
||||
using System.IO.Pipelines;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -48,6 +49,8 @@ namespace MQTTnet.AspNetCore
|
||||
|
||||
public bool IsSecureConnection => Http?.HttpContext?.Request?.IsHttps ?? false;
|
||||
|
||||
public X509Certificate2 ClientCertificate => Http?.HttpContext?.Connection?.ClientCertificate;
|
||||
|
||||
private IHttpContextFeature Http => Connection.Features.Get<IHttpContextFeature>();
|
||||
|
||||
public ConnectionContext Connection { get; }
|
||||
@@ -142,6 +145,12 @@ namespace MQTTnet.AspNetCore
|
||||
return null;
|
||||
}
|
||||
|
||||
public void ResetStatistics()
|
||||
{
|
||||
BytesReceived = 0;
|
||||
BytesSent = 0;
|
||||
}
|
||||
|
||||
public async Task SendPacketAsync(MqttBasePacket packet, TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
var formatter = PacketFormatterAdapter;
|
||||
@@ -153,11 +162,12 @@ namespace MQTTnet.AspNetCore
|
||||
var buffer = formatter.Encode(packet);
|
||||
var msg = buffer.AsMemory();
|
||||
var output = _output;
|
||||
msg.CopyTo(output.GetMemory(msg.Length));
|
||||
BytesSent += msg.Length;
|
||||
var result = await output.WriteAsync(msg, cancellationToken).ConfigureAwait(false);
|
||||
if (result.IsCompleted)
|
||||
{
|
||||
BytesSent += msg.Length;
|
||||
}
|
||||
PacketFormatterAdapter.FreeBuffer();
|
||||
output.Advance(msg.Length);
|
||||
await output.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -40,19 +40,26 @@ namespace MQTTnet.AspNetCore
|
||||
var endpoint = $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}";
|
||||
|
||||
var clientCertificate = await httpContext.Connection.GetClientCertificateAsync().ConfigureAwait(false);
|
||||
var isSecureConnection = clientCertificate != null;
|
||||
clientCertificate?.Dispose();
|
||||
|
||||
var clientHandler = ClientHandler;
|
||||
if (clientHandler != null)
|
||||
try
|
||||
{
|
||||
var writer = new SpanBasedMqttPacketWriter();
|
||||
var formatter = new MqttPacketFormatterAdapter(writer);
|
||||
var channel = new MqttWebSocketChannel(webSocket, endpoint, isSecureConnection);
|
||||
using (var channelAdapter = new MqttChannelAdapter(channel, formatter, _logger.CreateChildLogger(nameof(MqttWebSocketServerAdapter))))
|
||||
var isSecureConnection = clientCertificate != null;
|
||||
|
||||
var clientHandler = ClientHandler;
|
||||
if (clientHandler != null)
|
||||
{
|
||||
await clientHandler(channelAdapter).ConfigureAwait(false);
|
||||
}
|
||||
var writer = new SpanBasedMqttPacketWriter();
|
||||
var formatter = new MqttPacketFormatterAdapter(writer);
|
||||
var channel = new MqttWebSocketChannel(webSocket, endpoint, isSecureConnection, clientCertificate);
|
||||
|
||||
using (var channelAdapter = new MqttChannelAdapter(channel, formatter, _logger.CreateChildLogger(nameof(MqttWebSocketServerAdapter))))
|
||||
{
|
||||
await clientHandler(channelAdapter).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
clientCertificate?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ namespace MQTTnet.AspNetCore
|
||||
public class SpanBasedMqttPacketBodyReader : IMqttPacketBodyReader
|
||||
{
|
||||
private ReadOnlyMemory<byte> _buffer;
|
||||
|
||||
private int _offset;
|
||||
|
||||
public void SetBuffer(ReadOnlyMemory<byte> buffer)
|
||||
@@ -17,11 +18,11 @@ namespace MQTTnet.AspNetCore
|
||||
_offset = 0;
|
||||
}
|
||||
|
||||
public ulong Length => (ulong)_buffer.Length;
|
||||
public int Length => _buffer.Length;
|
||||
|
||||
public bool EndOfStream => _buffer.Length.Equals(_offset);
|
||||
|
||||
public ulong Offset => (ulong)_offset;
|
||||
public int Offset => _offset;
|
||||
|
||||
public byte ReadByte()
|
||||
{
|
||||
@@ -116,9 +117,9 @@ namespace MQTTnet.AspNetCore
|
||||
throw new MqttProtocolViolationException("Boolean values can be 0 or 1 only.");
|
||||
}
|
||||
|
||||
public void Seek(ulong position)
|
||||
public void Seek(int position)
|
||||
{
|
||||
_offset = (int)position;
|
||||
_offset = position;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,6 @@ namespace MQTTnet.AspNetCore
|
||||
|
||||
GrowIfNeeded(propertyWriter.Length);
|
||||
Write(propertyWriter.GetBuffer(), 0, propertyWriter.Length);
|
||||
Commit(propertyWriter.Length);
|
||||
}
|
||||
|
||||
public void Write(byte[] payload, int start, int length)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>netstandard1.3;netstandard2.0</TargetFrameworks>
|
||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461</TargetFrameworks>
|
||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core'">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' AND '$(SolutionName)' != 'MQTTnet.noUWP' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||
<Product />
|
||||
<Company />
|
||||
<Authors />
|
||||
|
||||
@@ -24,6 +24,8 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
|
||||
private readonly IMqttClient _mqttClient;
|
||||
private readonly IMqttNetChildLogger _logger;
|
||||
|
||||
private readonly AsyncLock _messageQueueLock = new AsyncLock();
|
||||
|
||||
private CancellationTokenSource _connectionCancellationToken;
|
||||
private CancellationTokenSource _publishingCancellationToken;
|
||||
@@ -31,7 +33,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
|
||||
private ManagedMqttClientStorageManager _storageManager;
|
||||
|
||||
private bool _disposed = false;
|
||||
private bool _disposed;
|
||||
private bool _subscriptionsNotPushed;
|
||||
|
||||
public ManagedMqttClient(IMqttClient mqttClient, IMqttNetChildLogger logger)
|
||||
@@ -102,9 +104,8 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
|
||||
_connectionCancellationToken = new CancellationTokenSource();
|
||||
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
_maintainConnectionTask = Task.Run(() => MaintainConnectionAsync(_connectionCancellationToken.Token), _connectionCancellationToken.Token);
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
_maintainConnectionTask.Forget(_logger);
|
||||
|
||||
_logger.Info("Started");
|
||||
}
|
||||
@@ -148,7 +149,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
|
||||
try
|
||||
{
|
||||
lock (_messageQueue)
|
||||
using (await _messageQueueLock.WaitAsync(CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
if (_messageQueue.Count >= Options.MaxPendingMessages)
|
||||
{
|
||||
@@ -168,6 +169,16 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
}
|
||||
|
||||
_messageQueue.Enqueue(applicationMessage);
|
||||
|
||||
if (_storageManager != null)
|
||||
{
|
||||
if (removedMessage != null)
|
||||
{
|
||||
await _storageManager.RemoveAsync(removedMessage).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _storageManager.AddAsync(applicationMessage).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -182,16 +193,6 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (_storageManager != null)
|
||||
{
|
||||
if (removedMessage != null)
|
||||
{
|
||||
await _storageManager.RemoveAsync(removedMessage).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _storageManager.AddAsync(applicationMessage).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public Task SubscribeAsync(IEnumerable<TopicFilter> topicFilters)
|
||||
@@ -251,6 +252,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
_maintainConnectionTask = null;
|
||||
}
|
||||
|
||||
_messageQueueLock.Dispose();
|
||||
_mqttClient.Dispose();
|
||||
}
|
||||
|
||||
@@ -333,20 +335,20 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
}
|
||||
}
|
||||
|
||||
private void PublishQueuedMessages(CancellationToken cancellationToken)
|
||||
private async Task PublishQueuedMessagesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested && _mqttClient.IsConnected)
|
||||
{
|
||||
//Peek at the message without dequeueing in order to prevent the
|
||||
//possibility of the queue growing beyond the configured cap.
|
||||
//Previously, messages could be re-enqueued if there was an
|
||||
//exception, and this re-enqueueing did not honor the cap.
|
||||
//Furthermore, because re-enqueueing would shuffle the order
|
||||
//of the messages, the DropOldestQueuedMessage strategy would
|
||||
//be unable to know which message is actually the oldest and would
|
||||
//instead drop the first item in the queue.
|
||||
// Peek at the message without dequeueing in order to prevent the
|
||||
// possibility of the queue growing beyond the configured cap.
|
||||
// Previously, messages could be re-enqueued if there was an
|
||||
// exception, and this re-enqueueing did not honor the cap.
|
||||
// Furthermore, because re-enqueueing would shuffle the order
|
||||
// of the messages, the DropOldestQueuedMessage strategy would
|
||||
// be unable to know which message is actually the oldest and would
|
||||
// instead drop the first item in the queue.
|
||||
var message = _messageQueue.PeekAndWait();
|
||||
if (message == null)
|
||||
{
|
||||
@@ -355,7 +357,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
TryPublishQueuedMessage(message);
|
||||
await TryPublishQueuedMessageAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
@@ -363,7 +365,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.Error(exception, "Unhandled exception while publishing queued application messages.");
|
||||
_logger.Error(exception, "Error while publishing queued application messages.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -371,23 +373,28 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
}
|
||||
}
|
||||
|
||||
private void TryPublishQueuedMessage(ManagedMqttApplicationMessage message)
|
||||
private async Task TryPublishQueuedMessageAsync(ManagedMqttApplicationMessage message)
|
||||
{
|
||||
Exception transmitException = null;
|
||||
try
|
||||
{
|
||||
_mqttClient.PublishAsync(message.ApplicationMessage).GetAwaiter().GetResult();
|
||||
lock (_messageQueue) //lock to avoid conflict with this.PublishAsync
|
||||
await _mqttClient.PublishAsync(message.ApplicationMessage).ConfigureAwait(false);
|
||||
|
||||
using (await _messageQueueLock.WaitAsync(CancellationToken.None).ConfigureAwait(false)) //lock to avoid conflict with this.PublishAsync
|
||||
{
|
||||
//While publishing this message, this.PublishAsync could have booted this
|
||||
//message off the queue to make room for another (when using a cap
|
||||
//with the DropOldestQueuedMessage strategy). If the first item
|
||||
//in the queue is equal to this message, then it's safe to remove
|
||||
//it from the queue. If not, that means this.PublishAsync has already
|
||||
//removed it, in which case we don't want to do anything.
|
||||
// While publishing this message, this.PublishAsync could have booted this
|
||||
// message off the queue to make room for another (when using a cap
|
||||
// with the DropOldestQueuedMessage strategy). If the first item
|
||||
// in the queue is equal to this message, then it's safe to remove
|
||||
// it from the queue. If not, that means this.PublishAsync has already
|
||||
// removed it, in which case we don't want to do anything.
|
||||
_messageQueue.RemoveFirst(i => i.Id.Equals(message.Id));
|
||||
|
||||
if (_storageManager != null)
|
||||
{
|
||||
await _storageManager.RemoveAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
_storageManager?.RemoveAsync(message).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (MqttCommunicationException exception)
|
||||
{
|
||||
@@ -404,20 +411,30 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
//contradict the expected behavior of QoS 1 and 2, that's also true
|
||||
//for the usage of a message queue cap, so it's still consistent
|
||||
//with prior behavior in that way.
|
||||
lock (_messageQueue) //lock to avoid conflict with this.PublishAsync
|
||||
using (await _messageQueueLock.WaitAsync(CancellationToken.None).ConfigureAwait(false)) //lock to avoid conflict with this.PublishAsync
|
||||
{
|
||||
_messageQueue.RemoveFirst(i => i.Id.Equals(message.Id));
|
||||
|
||||
if (_storageManager != null)
|
||||
{
|
||||
await _storageManager.RemoveAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
transmitException = exception;
|
||||
_logger.Error(exception, $"Unhandled exception while publishing application message ({message.Id}).");
|
||||
_logger.Error(exception, $"Error while publishing application message ({message.Id}).");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ApplicationMessageProcessedHandler?.HandleApplicationMessageProcessedAsync(new ApplicationMessageProcessedEventArgs(message, transmitException)).GetAwaiter().GetResult();
|
||||
var eventHandler = ApplicationMessageProcessedHandler;
|
||||
if (eventHandler != null)
|
||||
{
|
||||
var eventArguments = new ApplicationMessageProcessedEventArgs(message, transmitException);
|
||||
await eventHandler.HandleApplicationMessageProcessedAsync(eventArguments).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -502,7 +519,7 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
var cts = new CancellationTokenSource();
|
||||
_publishingCancellationToken = cts;
|
||||
|
||||
Task.Factory.StartNew(() => PublishQueuedMessages(cts.Token), cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
|
||||
Task.Run(() => PublishQueuedMessagesAsync(cts.Token), cts.Token).Forget(_logger);
|
||||
}
|
||||
|
||||
private void StopPublishing()
|
||||
@@ -519,4 +536,4 @@ namespace MQTTnet.Extensions.ManagedClient
|
||||
_connectionCancellationToken = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>netstandard1.3;netstandard2.0</TargetFrameworks>
|
||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461</TargetFrameworks>
|
||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core'">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' AND '$(SolutionName)' != 'MQTTnet.noUWP' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||
<Product />
|
||||
<Company />
|
||||
<Authors />
|
||||
|
||||
@@ -5,6 +5,8 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Extensions.Rpc.Options;
|
||||
using MQTTnet.Extensions.Rpc.Options.TopicGeneration;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Extensions.Rpc
|
||||
@@ -13,11 +15,18 @@ namespace MQTTnet.Extensions.Rpc
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, TaskCompletionSource<byte[]>> _waitingCalls = new ConcurrentDictionary<string, TaskCompletionSource<byte[]>>();
|
||||
private readonly IMqttClient _mqttClient;
|
||||
private readonly IMqttRpcClientOptions _options;
|
||||
private readonly RpcAwareApplicationMessageReceivedHandler _applicationMessageReceivedHandler;
|
||||
|
||||
public MqttRpcClient(IMqttClient mqttClient)
|
||||
[Obsolete("Use MqttRpcClient(IMqttClient mqttClient, IMqttRpcClientOptions options).")]
|
||||
public MqttRpcClient(IMqttClient mqttClient) : this(mqttClient, new MqttRpcClientOptions())
|
||||
{
|
||||
}
|
||||
|
||||
public MqttRpcClient(IMqttClient mqttClient, IMqttRpcClientOptions options)
|
||||
{
|
||||
_mqttClient = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient));
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
|
||||
_applicationMessageReceivedHandler = new RpcAwareApplicationMessageReceivedHandler(
|
||||
mqttClient.ApplicationMessageReceivedHandler,
|
||||
@@ -55,8 +64,26 @@ namespace MQTTnet.Extensions.Rpc
|
||||
throw new InvalidOperationException("The application message received handler was modified.");
|
||||
}
|
||||
|
||||
var requestTopic = $"MQTTnet.RPC/{Guid.NewGuid():N}/{methodName}";
|
||||
var responseTopic = requestTopic + "/response";
|
||||
var topicNames = _options.TopicGenerationStrategy.CreateRpcTopics(new TopicGenerationContext
|
||||
{
|
||||
MethodName = methodName,
|
||||
QualityOfServiceLevel = qualityOfServiceLevel,
|
||||
MqttClient = _mqttClient,
|
||||
Options = _options
|
||||
});
|
||||
|
||||
var requestTopic = topicNames.RequestTopic;
|
||||
var responseTopic = topicNames.ResponseTopic;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(requestTopic))
|
||||
{
|
||||
throw new MqttProtocolViolationException("RPC request topic is empty.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(responseTopic))
|
||||
{
|
||||
throw new MqttProtocolViolationException("RPC response topic is empty.");
|
||||
}
|
||||
|
||||
var requestMessage = new MqttApplicationMessageBuilder()
|
||||
.WithTopic(requestTopic)
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
using MQTTnet.Extensions.Rpc.Options.TopicGeneration;
|
||||
|
||||
namespace MQTTnet.Extensions.Rpc.Options
|
||||
{
|
||||
public interface IMqttRpcClientOptions
|
||||
{
|
||||
IMqttRpcClientTopicGenerationStrategy TopicGenerationStrategy { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using MQTTnet.Extensions.Rpc.Options.TopicGeneration;
|
||||
|
||||
namespace MQTTnet.Extensions.Rpc.Options
|
||||
{
|
||||
public class MqttRpcClientOptions : IMqttRpcClientOptions
|
||||
{
|
||||
public IMqttRpcClientTopicGenerationStrategy TopicGenerationStrategy { get; set; } = new DefaultMqttRpcClientTopicGenerationStrategy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using MQTTnet.Extensions.Rpc.Options.TopicGeneration;
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Extensions.Rpc.Options
|
||||
{
|
||||
public class MqttRpcClientOptionsBuilder
|
||||
{
|
||||
IMqttRpcClientTopicGenerationStrategy _topicGenerationStrategy = new DefaultMqttRpcClientTopicGenerationStrategy();
|
||||
|
||||
public MqttRpcClientOptionsBuilder WithTopicGenerationStrategy(IMqttRpcClientTopicGenerationStrategy value)
|
||||
{
|
||||
_topicGenerationStrategy = value ?? throw new ArgumentNullException(nameof(value));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public IMqttRpcClientOptions Build()
|
||||
{
|
||||
return new MqttRpcClientOptions
|
||||
{
|
||||
TopicGenerationStrategy = _topicGenerationStrategy
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace MQTTnet.Extensions.Rpc.Options
|
||||
{
|
||||
public class MqttRpcTopicPair
|
||||
{
|
||||
public string RequestTopic { get; set; }
|
||||
|
||||
public string ResponseTopic { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using MQTTnet.Extensions.Rpc.Options.TopicGeneration;
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Extensions.Rpc.Options
|
||||
{
|
||||
public class DefaultMqttRpcClientTopicGenerationStrategy : IMqttRpcClientTopicGenerationStrategy
|
||||
{
|
||||
public MqttRpcTopicPair CreateRpcTopics(TopicGenerationContext context)
|
||||
{
|
||||
var requestTopic = $"MQTTnet.RPC/{Guid.NewGuid():N}/{context.MethodName}";
|
||||
var responseTopic = requestTopic + "/response";
|
||||
|
||||
return new MqttRpcTopicPair
|
||||
{
|
||||
RequestTopic = requestTopic,
|
||||
ResponseTopic = responseTopic
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace MQTTnet.Extensions.Rpc.Options.TopicGeneration
|
||||
{
|
||||
public interface IMqttRpcClientTopicGenerationStrategy
|
||||
{
|
||||
MqttRpcTopicPair CreateRpcTopics(TopicGenerationContext context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Extensions.Rpc.Options.TopicGeneration
|
||||
{
|
||||
public class TopicGenerationContext
|
||||
{
|
||||
public string MethodName { get; set; }
|
||||
|
||||
public MqttQualityOfServiceLevel QualityOfServiceLevel { get; set; }
|
||||
|
||||
public IMqttClient MqttClient { get; set; }
|
||||
|
||||
public IMqttRpcClientOptions Options { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>netstandard1.3;netstandard2.0</TargetFrameworks>
|
||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">$(TargetFrameworks);net452;net461</TargetFrameworks>
|
||||
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' AND '$(MSBuildRuntimeType)' != 'Core' AND '$(SolutionName)' != 'MQTTnet.noUWP' ">$(TargetFrameworks);uap10.0</TargetFrameworks>
|
||||
<Product />
|
||||
<Company />
|
||||
<Authors />
|
||||
<PackageId />
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == 'uap10.0'">
|
||||
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||
<NugetTargetMoniker>UAP,Version=v10.0</NugetTargetMoniker>
|
||||
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
|
||||
<TargetPlatformVersion>10.0.17134.0</TargetPlatformVersion>
|
||||
<TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion>
|
||||
<TargetFrameworkIdentifier>.NETCore</TargetFrameworkIdentifier>
|
||||
<TargetFrameworkVersion>v5.0</TargetFrameworkVersion>
|
||||
<DefineConstants>$(DefineConstants);WINDOWS_UWP</DefineConstants>
|
||||
<DefaultLanguage>en</DefaultLanguage>
|
||||
<LanguageTargets>$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets</LanguageTargets>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="WebSocket4Net" Version="0.15.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MQTTnet\MQTTnet.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace MQTTnet.Extensions.WebSocket4Net
|
||||
{
|
||||
public static class MqttFactoryExtensions
|
||||
{
|
||||
public static IMqttFactory UseWebSocket4Net(this IMqttFactory mqttFactory)
|
||||
{
|
||||
if (mqttFactory == null) throw new ArgumentNullException(nameof(mqttFactory));
|
||||
|
||||
return mqttFactory.UseClientAdapterFactory(new WebSocket4NetMqttClientAdapterFactory());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Channel;
|
||||
using MQTTnet.Client.Options;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Internal;
|
||||
using SuperSocket.ClientEngine;
|
||||
using WebSocket4Net;
|
||||
|
||||
namespace MQTTnet.Extensions.WebSocket4Net
|
||||
{
|
||||
public class WebSocket4NetMqttChannel : IMqttChannel
|
||||
{
|
||||
private readonly BlockingCollection<byte> _receiveBuffer = new BlockingCollection<byte>();
|
||||
|
||||
private readonly IMqttClientOptions _clientOptions;
|
||||
private readonly MqttClientWebSocketOptions _webSocketOptions;
|
||||
|
||||
private WebSocket _webSocket;
|
||||
|
||||
public WebSocket4NetMqttChannel(IMqttClientOptions clientOptions, MqttClientWebSocketOptions webSocketOptions)
|
||||
{
|
||||
_clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
|
||||
_webSocketOptions = webSocketOptions ?? throw new ArgumentNullException(nameof(webSocketOptions));
|
||||
}
|
||||
|
||||
public string Endpoint => _webSocketOptions.Uri;
|
||||
|
||||
public bool IsSecureConnection { get; private set; }
|
||||
|
||||
public X509Certificate2 ClientCertificate { get; }
|
||||
|
||||
public async Task ConnectAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var uri = _webSocketOptions.Uri;
|
||||
if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) && !uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (_webSocketOptions.TlsOptions?.UseTls == false)
|
||||
{
|
||||
uri = "ws://" + uri;
|
||||
}
|
||||
else
|
||||
{
|
||||
uri = "wss://" + uri;
|
||||
}
|
||||
}
|
||||
|
||||
var sslProtocols = _webSocketOptions?.TlsOptions?.SslProtocol ?? SslProtocols.None;
|
||||
var subProtocol = _webSocketOptions.SubProtocols.FirstOrDefault() ?? string.Empty;
|
||||
|
||||
var cookies = new List<KeyValuePair<string, string>>();
|
||||
if (_webSocketOptions.CookieContainer != null)
|
||||
{
|
||||
throw new NotSupportedException("Cookies are not supported.");
|
||||
}
|
||||
|
||||
List<KeyValuePair<string, string>> customHeaders = null;
|
||||
if (_webSocketOptions.RequestHeaders != null)
|
||||
{
|
||||
customHeaders = _webSocketOptions.RequestHeaders.Select(i => new KeyValuePair<string, string>(i.Key, i.Value)).ToList();
|
||||
}
|
||||
|
||||
EndPoint proxy = null;
|
||||
if (_webSocketOptions.ProxyOptions != null)
|
||||
{
|
||||
throw new NotSupportedException("Proxies are not supported.");
|
||||
}
|
||||
|
||||
// The user agent can be empty always because it is just added to the custom headers as "User-Agent".
|
||||
var userAgent = string.Empty;
|
||||
|
||||
var origin = string.Empty;
|
||||
var webSocketVersion = WebSocketVersion.None;
|
||||
var receiveBufferSize = 0;
|
||||
|
||||
var certificates = new X509CertificateCollection();
|
||||
if (_webSocketOptions?.TlsOptions?.Certificates != null)
|
||||
{
|
||||
foreach (var certificate in _webSocketOptions.TlsOptions.Certificates)
|
||||
{
|
||||
certificates.Add(new X509Certificate(certificate));
|
||||
}
|
||||
}
|
||||
|
||||
_webSocket = new WebSocket(uri, subProtocol, cookies, customHeaders, userAgent, origin, webSocketVersion, proxy, sslProtocols, receiveBufferSize)
|
||||
{
|
||||
NoDelay = true,
|
||||
Security =
|
||||
{
|
||||
AllowUnstrustedCertificate = _webSocketOptions?.TlsOptions?.AllowUntrustedCertificates == true,
|
||||
AllowCertificateChainErrors = _webSocketOptions?.TlsOptions?.IgnoreCertificateChainErrors == true,
|
||||
Certificates = certificates
|
||||
}
|
||||
};
|
||||
|
||||
await ConnectInternalAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
IsSecureConnection = uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public Task DisconnectAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_webSocket != null && _webSocket.State == WebSocketState.Open)
|
||||
{
|
||||
_webSocket.Close();
|
||||
}
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
var readBytes = 0;
|
||||
while (count > 0 && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
if (!_receiveBuffer.TryTake(out var @byte))
|
||||
{
|
||||
if (readBytes == 0)
|
||||
{
|
||||
// Block until at least one byte was received.
|
||||
@byte = _receiveBuffer.Take(cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Task.FromResult(readBytes);
|
||||
}
|
||||
}
|
||||
|
||||
buffer[offset] = @byte;
|
||||
offset++;
|
||||
count--;
|
||||
readBytes++;
|
||||
}
|
||||
|
||||
return Task.FromResult(readBytes);
|
||||
}
|
||||
|
||||
public Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
_webSocket.Send(buffer, offset, count);
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_webSocket == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_webSocket.DataReceived -= OnDataReceived;
|
||||
_webSocket.Error -= OnError;
|
||||
_webSocket.Dispose();
|
||||
_webSocket = null;
|
||||
}
|
||||
|
||||
private void OnError(object sender, ErrorEventArgs e)
|
||||
{
|
||||
System.Diagnostics.Debug.Write(e.Exception.ToString());
|
||||
}
|
||||
|
||||
private void OnDataReceived(object sender, DataReceivedEventArgs e)
|
||||
{
|
||||
foreach (var @byte in e.Data)
|
||||
{
|
||||
_receiveBuffer.Add(@byte);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ConnectInternalAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_webSocket.Error += OnError;
|
||||
_webSocket.DataReceived += OnDataReceived;
|
||||
|
||||
var taskCompletionSource = new TaskCompletionSource<Exception>();
|
||||
|
||||
void ErrorHandler(object sender, ErrorEventArgs e)
|
||||
{
|
||||
taskCompletionSource.TrySetResult(e.Exception);
|
||||
}
|
||||
|
||||
void SuccessHandler(object sender, EventArgs e)
|
||||
{
|
||||
taskCompletionSource.TrySetResult(null);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_webSocket.Opened += SuccessHandler;
|
||||
_webSocket.Error += ErrorHandler;
|
||||
|
||||
_webSocket.Open();
|
||||
|
||||
var exception = await MqttTaskTimeout.WaitAsync(c =>
|
||||
{
|
||||
c.Register(() => taskCompletionSource.TrySetCanceled());
|
||||
return taskCompletionSource.Task;
|
||||
}, _clientOptions.CommunicationTimeout, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (exception != null)
|
||||
{
|
||||
if (exception is AuthenticationException authenticationException)
|
||||
{
|
||||
throw new MqttCommunicationException(authenticationException.InnerException);
|
||||
}
|
||||
|
||||
if (exception is OperationCanceledException)
|
||||
{
|
||||
throw new MqttCommunicationTimedOutException();
|
||||
}
|
||||
|
||||
throw new MqttCommunicationException(exception);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new MqttCommunicationTimedOutException();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_webSocket.Opened -= SuccessHandler;
|
||||
_webSocket.Error -= ErrorHandler;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using MQTTnet.Adapter;
|
||||
using MQTTnet.Client.Options;
|
||||
using MQTTnet.Diagnostics;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Implementations;
|
||||
|
||||
namespace MQTTnet.Extensions.WebSocket4Net
|
||||
{
|
||||
public class WebSocket4NetMqttClientAdapterFactory : IMqttClientAdapterFactory
|
||||
{
|
||||
public IMqttChannelAdapter CreateClientAdapter(IMqttClientOptions options, IMqttNetChildLogger logger)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
if (logger == null) throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
switch (options.ChannelOptions)
|
||||
{
|
||||
case MqttClientTcpOptions _:
|
||||
{
|
||||
return new MqttChannelAdapter(new MqttTcpChannel(options), new MqttPacketFormatterAdapter(options.ProtocolVersion), logger);
|
||||
}
|
||||
|
||||
case MqttClientWebSocketOptions webSocketOptions:
|
||||
{
|
||||
return new MqttChannelAdapter(new WebSocket4NetMqttChannel(options, webSocketOptions), new MqttPacketFormatterAdapter(options.ProtocolVersion), logger);
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.IO;
|
||||
|
||||
namespace MQTTnet.Server.Configuration
|
||||
{
|
||||
public class CertificateSettingsModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Path to certificate.
|
||||
/// </summary>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Password of certificate.
|
||||
/// </summary>
|
||||
public string Password { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Read certificate file.
|
||||
/// </summary>
|
||||
public byte[] ReadCertificate()
|
||||
{
|
||||
if (string.IsNullOrEmpty(Path) || string.IsNullOrWhiteSpace(Path))
|
||||
{
|
||||
throw new FileNotFoundException("No path set");
|
||||
}
|
||||
|
||||
if (!File.Exists(Path))
|
||||
{
|
||||
throw new FileNotFoundException($"Could not find Certificate in path: {Path}");
|
||||
}
|
||||
|
||||
return File.ReadAllBytes(Path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
namespace MQTTnet.Server.Configuration
|
||||
{
|
||||
/// <summary>
|
||||
/// Main Settings Model
|
||||
/// MQTT settings Model
|
||||
/// </summary>
|
||||
public class SettingsModel
|
||||
public class MqttSettingsModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Set default connection timeout in seconds
|
||||
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace MQTTnet.Server.Configuration
|
||||
{
|
||||
public static class PathHelper
|
||||
{
|
||||
public static string ExpandPath(string path)
|
||||
{
|
||||
if (path == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var uri = new Uri(path, UriKind.RelativeOrAbsolute);
|
||||
if (!uri.IsAbsoluteUri)
|
||||
{
|
||||
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,6 @@
|
||||
|
||||
public int WriteInterval { get; set; } = 10;
|
||||
|
||||
public string Filename { get; set; } = "RetainedApplicationMessages.json";
|
||||
public string Path { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MQTTnet.Server.Configuration
|
||||
{
|
||||
public class ScriptingSettingsModel
|
||||
{
|
||||
public string ScriptsPath { get; set; }
|
||||
|
||||
public List<string> IncludePaths { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,9 @@ namespace MQTTnet.Server.Configuration
|
||||
public class TcpEndPointModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Path to Certificate
|
||||
/// Certificate settings.
|
||||
/// </summary>
|
||||
public string CertificatePath { get; set; }
|
||||
public CertificateSettingsModel Certificate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Enabled / Disable
|
||||
@@ -33,25 +33,6 @@ namespace MQTTnet.Server.Configuration
|
||||
/// </summary>
|
||||
public int Port { get; set; } = 1883;
|
||||
|
||||
/// <summary>
|
||||
/// Read Certificate file
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public byte[] ReadCertificate()
|
||||
{
|
||||
if (string.IsNullOrEmpty(CertificatePath) || string.IsNullOrWhiteSpace(CertificatePath))
|
||||
{
|
||||
throw new FileNotFoundException("No path set");
|
||||
}
|
||||
|
||||
if (!File.Exists(CertificatePath))
|
||||
{
|
||||
throw new FileNotFoundException($"Could not find Certificate in path: {CertificatePath}");
|
||||
}
|
||||
|
||||
return File.ReadAllBytes(CertificatePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read IPv4
|
||||
/// </summary>
|
||||
|
||||
@@ -4,14 +4,16 @@ using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MQTTnet.Server.Mqtt;
|
||||
using MQTTnet.Server.Status;
|
||||
|
||||
namespace MQTTnet.Server.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
public class ClientsController : ControllerBase
|
||||
public class ClientsController : Controller
|
||||
{
|
||||
private readonly MqttServerService _mqttServerService;
|
||||
|
||||
@@ -57,5 +59,21 @@ namespace MQTTnet.Server.Controllers
|
||||
await client.DisconnectAsync();
|
||||
return StatusCode((int)HttpStatusCode.NoContent);
|
||||
}
|
||||
|
||||
[Route("api/v1/clients/{clientId}/statistics")]
|
||||
[HttpDelete]
|
||||
public async Task<ActionResult> DeleteClientStatistics(string clientId)
|
||||
{
|
||||
clientId = HttpUtility.UrlDecode(clientId);
|
||||
|
||||
var client = (await _mqttServerService.GetClientStatusAsync()).FirstOrDefault(c => c.ClientId == clientId);
|
||||
if (client == null)
|
||||
{
|
||||
return new StatusCodeResult((int)HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
client.ResetStatistics();
|
||||
return StatusCode((int)HttpStatusCode.NoContent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MQTTnet.Protocol;
|
||||
using MQTTnet.Server.Mqtt;
|
||||
|
||||
namespace MQTTnet.Server.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
public class MessagesController : Controller
|
||||
{
|
||||
private readonly MqttServerService _mqttServerService;
|
||||
|
||||
public MessagesController(MqttServerService mqttServerService)
|
||||
{
|
||||
_mqttServerService = mqttServerService ?? throw new ArgumentNullException(nameof(mqttServerService));
|
||||
}
|
||||
|
||||
[Route("api/v1/messages")]
|
||||
[HttpPost]
|
||||
public async Task<ActionResult> PostMessage(MqttApplicationMessage message)
|
||||
{
|
||||
await _mqttServerService.PublishAsync(message);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
[Route("api/v1/messages/{*topic}")]
|
||||
[HttpPost]
|
||||
public async Task<ActionResult> PostMessage(string topic, int qosLevel = 0)
|
||||
{
|
||||
byte[] payload;
|
||||
|
||||
using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
await HttpContext.Request.Body.CopyToAsync(memoryStream);
|
||||
payload = memoryStream.ToArray();
|
||||
}
|
||||
|
||||
var message = new MqttApplicationMessageBuilder()
|
||||
.WithTopic(topic)
|
||||
.WithPayload(payload)
|
||||
.WithQualityOfServiceLevel((MqttQualityOfServiceLevel)qosLevel)
|
||||
.Build();
|
||||
|
||||
return await PostMessage(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,15 @@ using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MQTTnet.Server.Mqtt;
|
||||
|
||||
namespace MQTTnet.Server.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
public class RetainedApplicationMessagesController : ControllerBase
|
||||
public class RetainedApplicationMessagesController : Controller
|
||||
{
|
||||
private readonly MqttServerService _mqttServerService;
|
||||
|
||||
|
||||
@@ -1,11 +1,65 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MQTTnet.Server.Scripting;
|
||||
using MQTTnet.Server.Web;
|
||||
|
||||
namespace MQTTnet.Server.Controllers
|
||||
{
|
||||
public class ScriptsController
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
public class ScriptsController : Controller
|
||||
{
|
||||
private readonly PythonScriptHostService _pythonScriptHostService;
|
||||
|
||||
public ScriptsController(PythonScriptHostService pythonScriptHostService)
|
||||
{
|
||||
_pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
|
||||
}
|
||||
|
||||
[Route("api/v1/scripts")]
|
||||
[HttpGet]
|
||||
public ActionResult<List<string>> GetScriptUids()
|
||||
{
|
||||
return _pythonScriptHostService.GetScriptUids();
|
||||
}
|
||||
|
||||
[Route("api/v1/scripts/uid")]
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<string>> GetScript(string uid)
|
||||
{
|
||||
var script = await _pythonScriptHostService.ReadScriptAsync(uid, HttpContext.RequestAborted);
|
||||
if (script == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
return Content(script);
|
||||
}
|
||||
|
||||
[Route("api/v1/scripts/uid")]
|
||||
[HttpPost]
|
||||
public Task PostScript(string uid)
|
||||
{
|
||||
var code = HttpContext.Request.ReadBodyAsString();
|
||||
return _pythonScriptHostService.WriteScriptAsync(uid, code, CancellationToken.None);
|
||||
}
|
||||
|
||||
[Route("api/v1/scripts/uid")]
|
||||
[HttpDelete]
|
||||
public Task DeleteScript(string uid)
|
||||
{
|
||||
return _pythonScriptHostService.DeleteScriptAsync(uid);
|
||||
}
|
||||
|
||||
[Route("api/v1/scripts/initialize")]
|
||||
[HttpPost]
|
||||
public Task PostInitializeScripts()
|
||||
{
|
||||
return _pythonScriptHostService.TryInitializeScriptsAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Reflection;
|
||||
|
||||
namespace MQTTnet.Server.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
public class ServerController : Controller
|
||||
{
|
||||
[Route("api/v1/server/version")]
|
||||
[HttpGet]
|
||||
public ActionResult<string> GetVersion()
|
||||
{
|
||||
return Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,16 @@ using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MQTTnet.Server.Mqtt;
|
||||
using MQTTnet.Server.Status;
|
||||
|
||||
namespace MQTTnet.Server.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
public class SessionsController : ControllerBase
|
||||
public class SessionsController : Controller
|
||||
{
|
||||
private readonly MqttServerService _mqttServerService;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# MQTTnet
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 Christian Kratky
|
||||
Copyright (c) 2019 MQTTnet Team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -19,3 +20,78 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
# Swashbuckle
|
||||
Copyright (c) 2013, Richard Morris
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
|
||||
|
||||
# IronPython
|
||||
Copyright (c) .NET Foundation and Contributors
|
||||
All Rights Reserved
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
|
||||
|
||||
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
|
||||
|
||||
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
|
||||
|
||||
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
@@ -14,11 +14,13 @@
|
||||
<SignAssembly>false</SignAssembly>
|
||||
<DelaySign>false</DelaySign>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Version>1.0.0</Version>
|
||||
<TypeScriptToolsVersion>3.3</TypeScriptToolsVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<StartupObject></StartupObject>
|
||||
<UserSecretsId>c564f0de-28b4-45bf-b726-4d665d705653</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
@@ -27,6 +29,13 @@
|
||||
<NoWarn>1701;1702</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="wwwroot\**" />
|
||||
<Content Remove="wwwroot\**" />
|
||||
<EmbeddedResource Remove="wwwroot\**" />
|
||||
<None Remove="wwwroot\**" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Update="appsettings.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
@@ -53,22 +62,23 @@
|
||||
<None Update="LICENSE">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="run.sh">
|
||||
<None Update="README.md">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="run.bat">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Scripts\readme.md">
|
||||
<None Update="Scripts\README.md">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Scripts\00_sample.py">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Web\authorization_handler.py">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="wwwroot\" />
|
||||
<Folder Include="Properties\PublishProfiles\" />
|
||||
<Folder Include="Web\wwwroot\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
private readonly MqttFactory _mqttFactory;
|
||||
|
||||
public CustomMqttFactory(SettingsModel settings, ILogger<MqttServer> logger)
|
||||
public CustomMqttFactory(MqttSettingsModel settings, ILogger<MqttServer> logger)
|
||||
{
|
||||
if (settings == null) throw new ArgumentNullException(nameof(settings));
|
||||
if (logger == null) throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
@@ -22,14 +22,18 @@ namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
try
|
||||
{
|
||||
// This might be not set when a message was published by the server instead of a client.
|
||||
context.SessionItems.TryGetValue(MqttServerConnectionValidator.WrappedSessionItemsKey, out var sessionItems);
|
||||
|
||||
var pythonContext = new PythonDictionary
|
||||
{
|
||||
{ "client_id", context.ClientId },
|
||||
{ "session_items", sessionItems },
|
||||
{ "retain", context.ApplicationMessage.Retain },
|
||||
{ "accept_publish", context.AcceptPublish },
|
||||
{ "close_connection", context.CloseConnection },
|
||||
{ "client_id", context.ClientId },
|
||||
{ "topic", context.ApplicationMessage.Topic },
|
||||
{ "qos", (int)context.ApplicationMessage.QualityOfServiceLevel },
|
||||
{ "retain", context.ApplicationMessage.Retain }
|
||||
{ "qos", (int)context.ApplicationMessage.QualityOfServiceLevel }
|
||||
};
|
||||
|
||||
_pythonScriptHostService.InvokeOptionalFunction("on_intercept_application_message", pythonContext);
|
||||
@@ -47,4 +51,4 @@ namespace MQTTnet.Server.Mqtt
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,14 @@ using MQTTnet.Server.Scripting;
|
||||
|
||||
namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
public class MqttConnectionValidator : IMqttServerConnectionValidator
|
||||
public class MqttServerConnectionValidator : IMqttServerConnectionValidator
|
||||
{
|
||||
public const string WrappedSessionItemsKey = "WRAPPED_ITEMS";
|
||||
|
||||
private readonly PythonScriptHostService _pythonScriptHostService;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public MqttConnectionValidator(PythonScriptHostService pythonScriptHostService, ILogger<MqttConnectionValidator> logger)
|
||||
public MqttServerConnectionValidator(PythonScriptHostService pythonScriptHostService, ILogger<MqttServerConnectionValidator> logger)
|
||||
{
|
||||
_pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
@@ -22,23 +24,35 @@ namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
try
|
||||
{
|
||||
var sessionItems = new PythonDictionary();
|
||||
|
||||
var pythonContext = new PythonDictionary
|
||||
{
|
||||
{ "client_id", context.ClientId },
|
||||
{ "endpoint", context.Endpoint },
|
||||
{ "is_secure_connection", context.IsSecureConnection },
|
||||
{ "client_id", context.ClientId },
|
||||
{ "username", context.Username },
|
||||
{ "password", context.Password },
|
||||
{ "result", PythonConvert.Pythonfy(context.ReturnCode) }
|
||||
{ "raw_password", new Bytes(context.RawPassword ?? new byte[0]) },
|
||||
{ "clean_session", context.CleanSession},
|
||||
{ "authentication_method", context.AuthenticationMethod},
|
||||
{ "authentication_data", new Bytes(context.AuthenticationData ?? new byte[0]) },
|
||||
{ "session_items", sessionItems },
|
||||
|
||||
{ "result", PythonConvert.Pythonfy(context.ReasonCode) }
|
||||
};
|
||||
|
||||
_pythonScriptHostService.InvokeOptionalFunction("on_validate_client_connection", pythonContext);
|
||||
|
||||
context.ReturnCode = PythonConvert.ParseEnum<MqttConnectReturnCode>((string)pythonContext["result"]);
|
||||
context.ReasonCode = PythonConvert.ParseEnum<MqttConnectReasonCode>((string)pythonContext["result"]);
|
||||
|
||||
context.SessionItems[WrappedSessionItemsKey] = sessionItems;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(exception, "Error while validating client connection.");
|
||||
|
||||
context.ReasonCode = MqttConnectReasonCode.UnspecifiedError;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
@@ -23,34 +23,34 @@ namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
private readonly ILogger<MqttServerService> _logger;
|
||||
|
||||
private readonly SettingsModel _settings;
|
||||
private readonly MqttSettingsModel _settings;
|
||||
private readonly MqttApplicationMessageInterceptor _mqttApplicationMessageInterceptor;
|
||||
private readonly MqttServerStorage _mqttServerStorage;
|
||||
private readonly MqttClientConnectedHandler _mqttClientConnectedHandler;
|
||||
private readonly MqttClientDisconnectedHandler _mqttClientDisconnectedHandler;
|
||||
private readonly MqttClientSubscribedTopicHandler _mqttClientSubscribedTopicHandler;
|
||||
private readonly MqttClientUnsubscribedTopicHandler _mqttClientUnsubscribedTopicHandler;
|
||||
private readonly MqttConnectionValidator _mqttConnectionValidator;
|
||||
private readonly MqttServerConnectionValidator _mqttConnectionValidator;
|
||||
private readonly IMqttServer _mqttServer;
|
||||
private readonly MqttSubscriptionInterceptor _mqttSubscriptionInterceptor;
|
||||
private readonly PythonScriptHostService _pythonScriptHostService;
|
||||
private readonly MqttWebSocketServerAdapter _webSocketServerAdapter;
|
||||
|
||||
public MqttServerService(
|
||||
SettingsModel settings,
|
||||
MqttSettingsModel mqttSettings,
|
||||
CustomMqttFactory mqttFactory,
|
||||
MqttClientConnectedHandler mqttClientConnectedHandler,
|
||||
MqttClientDisconnectedHandler mqttClientDisconnectedHandler,
|
||||
MqttClientSubscribedTopicHandler mqttClientSubscribedTopicHandler,
|
||||
MqttClientUnsubscribedTopicHandler mqttClientUnsubscribedTopicHandler,
|
||||
MqttConnectionValidator mqttConnectionValidator,
|
||||
MqttServerConnectionValidator mqttConnectionValidator,
|
||||
MqttSubscriptionInterceptor mqttSubscriptionInterceptor,
|
||||
MqttApplicationMessageInterceptor mqttApplicationMessageInterceptor,
|
||||
MqttServerStorage mqttServerStorage,
|
||||
PythonScriptHostService pythonScriptHostService,
|
||||
PythonScriptHostService pythonScriptHostService,
|
||||
ILogger<MqttServerService> logger)
|
||||
{
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
_settings = mqttSettings ?? throw new ArgumentNullException(nameof(mqttSettings));
|
||||
_mqttClientConnectedHandler = mqttClientConnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientConnectedHandler));
|
||||
_mqttClientDisconnectedHandler = mqttClientDisconnectedHandler ?? throw new ArgumentNullException(nameof(mqttClientDisconnectedHandler));
|
||||
_mqttClientSubscribedTopicHandler = mqttClientSubscribedTopicHandler ?? throw new ArgumentNullException(nameof(mqttClientSubscribedTopicHandler));
|
||||
@@ -66,7 +66,10 @@ namespace MQTTnet.Server.Mqtt
|
||||
|
||||
var adapters = new List<IMqttServerAdapter>
|
||||
{
|
||||
new MqttTcpServerAdapter(mqttFactory.Logger.CreateChildLogger()),
|
||||
new MqttTcpServerAdapter(mqttFactory.Logger.CreateChildLogger())
|
||||
{
|
||||
TreatSocketOpeningErrorAsWarning = true // Opening other ports than for HTTP is not allows in Azure App Services.
|
||||
},
|
||||
_webSocketServerAdapter
|
||||
};
|
||||
|
||||
@@ -176,7 +179,7 @@ namespace MQTTnet.Server.Mqtt
|
||||
.WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor)
|
||||
.WithSubscriptionInterceptor(_mqttSubscriptionInterceptor)
|
||||
.WithStorage(_mqttServerStorage);
|
||||
|
||||
|
||||
// Configure unencrypted connections
|
||||
if (_settings.TcpEndPoint.Enabled)
|
||||
{
|
||||
@@ -207,9 +210,23 @@ namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
options
|
||||
.WithEncryptedEndpoint()
|
||||
.WithEncryptionSslProtocol(SslProtocols.Tls12)
|
||||
.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.ReadCertificate());
|
||||
.WithEncryptionSslProtocol(SslProtocols.Tls12);
|
||||
|
||||
if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path))
|
||||
{
|
||||
IMqttServerCertificateCredentials certificateCredentials = null;
|
||||
|
||||
if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password))
|
||||
{
|
||||
certificateCredentials = new MqttServerCertificateCredentials
|
||||
{
|
||||
Password = _settings.EncryptedTcpEndPoint.Certificate.Password
|
||||
};
|
||||
}
|
||||
|
||||
options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials);
|
||||
}
|
||||
|
||||
if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4))
|
||||
{
|
||||
options.WithEncryptedEndpointBoundIPAddress(address4);
|
||||
|
||||
@@ -14,27 +14,28 @@ namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
private readonly List<MqttApplicationMessage> _messages = new List<MqttApplicationMessage>();
|
||||
|
||||
private readonly SettingsModel _settings;
|
||||
private readonly MqttSettingsModel _mqttSettings;
|
||||
private readonly ILogger<MqttServerStorage> _logger;
|
||||
|
||||
private string _filename;
|
||||
private string _path;
|
||||
private bool _messagesHaveChanged;
|
||||
|
||||
public MqttServerStorage(SettingsModel settings, ILogger<MqttServerStorage> logger)
|
||||
public MqttServerStorage(MqttSettingsModel mqttSettings, ILogger<MqttServerStorage> logger)
|
||||
{
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
_mqttSettings = mqttSettings ?? throw new ArgumentNullException(nameof(mqttSettings));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public void Configure()
|
||||
{
|
||||
if (_settings.RetainedApplicationMessages?.Persist != true)
|
||||
if (_mqttSettings.RetainedApplicationMessages?.Persist != true ||
|
||||
string.IsNullOrEmpty(_mqttSettings.RetainedApplicationMessages.Path))
|
||||
{
|
||||
_logger.LogInformation("Persisting of retained application messages is disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
_filename = ExpandFilename();
|
||||
_path = PathHelper.ExpandPath(_mqttSettings.RetainedApplicationMessages.Path);
|
||||
|
||||
// The retained application messages are stored in a separate thread.
|
||||
// This is mandatory because writing them to a slow storage (like RaspberryPi SD card)
|
||||
@@ -61,7 +62,7 @@ namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(_settings.RetainedApplicationMessages.WriteInterval)).ConfigureAwait(false);
|
||||
await Task.Delay(TimeSpan.FromSeconds(_mqttSettings.RetainedApplicationMessages.WriteInterval)).ConfigureAwait(false);
|
||||
|
||||
List<MqttApplicationMessage> messages;
|
||||
lock (_messages)
|
||||
@@ -76,7 +77,7 @@ namespace MQTTnet.Server.Mqtt
|
||||
}
|
||||
|
||||
var json = JsonConvert.SerializeObject(messages);
|
||||
await File.WriteAllTextAsync(_filename, json, Encoding.UTF8).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(_path, json, Encoding.UTF8).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation($"{messages.Count} retained MQTT messages written.");
|
||||
}
|
||||
@@ -89,19 +90,19 @@ namespace MQTTnet.Server.Mqtt
|
||||
|
||||
public async Task<IList<MqttApplicationMessage>> LoadRetainedMessagesAsync()
|
||||
{
|
||||
if (_settings.RetainedApplicationMessages?.Persist != true)
|
||||
if (_mqttSettings.RetainedApplicationMessages?.Persist != true)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!File.Exists(_filename))
|
||||
if (!File.Exists(_path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = await File.ReadAllTextAsync(_filename).ConfigureAwait(false);
|
||||
var json = await File.ReadAllTextAsync(_path).ConfigureAwait(false);
|
||||
var applicationMessages = JsonConvert.DeserializeObject<List<MqttApplicationMessage>>(json);
|
||||
|
||||
_logger.LogInformation($"{applicationMessages.Count} retained MQTT messages loaded.");
|
||||
@@ -114,18 +115,5 @@ namespace MQTTnet.Server.Mqtt
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private string ExpandFilename()
|
||||
{
|
||||
var filename = _settings.RetainedApplicationMessages.Filename;
|
||||
|
||||
var uri = new Uri(filename, UriKind.RelativeOrAbsolute);
|
||||
if (!uri.IsAbsoluteUri)
|
||||
{
|
||||
filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
|
||||
}
|
||||
|
||||
return filename;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,14 +21,16 @@ namespace MQTTnet.Server.Mqtt
|
||||
{
|
||||
try
|
||||
{
|
||||
var sessionItems = (PythonDictionary)context.SessionItems[MqttServerConnectionValidator.WrappedSessionItemsKey];
|
||||
|
||||
var pythonContext = new PythonDictionary
|
||||
{
|
||||
{ "accept_subscription", context.AcceptSubscription },
|
||||
{ "close_connection", context.CloseConnection },
|
||||
|
||||
{ "client_id", context.ClientId },
|
||||
{ "session_items", sessionItems },
|
||||
{ "topic", context.TopicFilter.Topic },
|
||||
{ "qos", (int)context.TopicFilter.QualityOfServiceLevel }
|
||||
{ "qos", (int)context.TopicFilter.QualityOfServiceLevel },
|
||||
{ "accept_subscription", context.AcceptSubscription },
|
||||
{ "close_connection", context.CloseConnection }
|
||||
};
|
||||
|
||||
_pythonScriptHostService.InvokeOptionalFunction("on_intercept_subscription", pythonContext);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using System.Reflection;
|
||||
using Microsoft.AspNetCore;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using MQTTnet.Server.Web;
|
||||
|
||||
namespace MQTTnet.Server
|
||||
{
|
||||
@@ -27,45 +28,40 @@ namespace MQTTnet.Server
|
||||
private static void PrintLogo()
|
||||
{
|
||||
Console.ResetColor();
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
Console.BackgroundColor = ConsoleColor.Red;
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
const string LogoText =
|
||||
@"| |
|
||||
| __ __ ____ _______ _______ _ _____ |
|
||||
| | \/ |/ __ \__ __|__ __| | | / ____| |
|
||||
| | \ / | | | | | | | |_ __ ___| |_ | (___ ___ _ ____ _____ _ __ |
|
||||
| | |\/| | | | | | | | | '_ \ / _ \ __| \___ \ / _ \ '__\ \ / / _ \ '__| |
|
||||
| | | | | |__| | | | | | | | | __/ |_ ____) | __/ | \ V / __/ | |
|
||||
| |_| |_|\___\_\ |_| |_|_| |_|\___|\__| |_____/ \___|_| \_/ \___|_| |
|
||||
| |
|
||||
| |";
|
||||
@"
|
||||
|
||||
███╗ ███╗ ██████╗ ████████╗████████╗███╗ ██╗███████╗████████╗ ███████╗███████╗██████╗ ██╗ ██╗███████╗██████╗
|
||||
████╗ ████║██╔═══██╗╚══██╔══╝╚══██╔══╝████╗ ██║██╔════╝╚══██╔══╝ ██╔════╝██╔════╝██╔══██╗██║ ██║██╔════╝██╔══██╗
|
||||
██╔████╔██║██║ ██║ ██║ ██║ ██╔██╗ ██║█████╗ ██║ ███████╗█████╗ ██████╔╝██║ ██║█████╗ ██████╔╝
|
||||
██║╚██╔╝██║██║▄▄ ██║ ██║ ██║ ██║╚██╗██║██╔══╝ ██║ ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██╔══╝ ██╔══██╗
|
||||
██║ ╚═╝ ██║╚██████╔╝ ██║ ██║ ██║ ╚████║███████╗ ██║ ███████║███████╗██║ ██║ ╚████╔╝ ███████╗██║ ██║
|
||||
╚═╝ ╚═╝ ╚══▀▀═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝
|
||||
|
||||
";
|
||||
|
||||
Console.WriteLine(LogoText);
|
||||
Console.ResetColor();
|
||||
Console.WriteLine();
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
Console.WriteLine(@"
|
||||
-- The official MQTT server implementation of MQTTnet --
|
||||
Copyright (c) 2017-2019 The MQTTnet Team");
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Blue;
|
||||
Console.WriteLine(@"
|
||||
https://github.com/chkr1011/MQTTnet");
|
||||
Console.WriteLine("The official MQTT server implementation of MQTTnet");
|
||||
Console.WriteLine("Copyright (c) 2017-2019 The MQTTnet Team");
|
||||
Console.WriteLine(@"https://github.com/chkr1011/MQTTnet");
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
Console.WriteLine($@"
|
||||
Version: {Assembly.GetExecutingAssembly().GetName().Version}
|
||||
License: MIT (read LICENSE file)
|
||||
Sponsoring: https://opencollective.com/mqttnet
|
||||
Support: https://github.com/chkr1011/MQTTnet/issues
|
||||
Docs: https://github.com/chkr1011/MQTTnet/wiki/MQTTnetServer
|
||||
Version: {Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion}
|
||||
License: MIT (read LICENSE file)
|
||||
Sponsoring: https://opencollective.com/mqttnet
|
||||
Support: https://github.com/chkr1011/MQTTnet/issues
|
||||
Docs: https://github.com/chkr1011/MQTTnet/wiki/MQTTnetServer
|
||||
");
|
||||
|
||||
Console.BackgroundColor = ConsoleColor.White;
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine(" ! THIS IS AN ALPHA VERSION! IT IS NOT RECOMMENDED TO USE IT FOR ANY DIFFERENT PURPOSE THAN TESTING OR EVALUATING!");
|
||||
Console.WriteLine();
|
||||
Console.ResetColor();
|
||||
Console.WriteLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Starting portable version
|
||||
The portable version requires a local installation of the .net core runtime. With that runtime installed the server can be started via the following comand.
|
||||
|
||||
dotnet .\MQTTnet.Server.dll
|
||||
|
||||
# Starting self contained versions
|
||||
The self contained versions are fully portable versions including the .net core runtime. The server can be started using the contained executable files.
|
||||
|
||||
Windows: MQTTnet.Server.exe
|
||||
Linux: MQTTnet.Server (must be set to _executable_ first)
|
||||
@@ -1 +0,0 @@
|
||||
[{"Topic":"a","Payload":"YWFzYXNhc2E=","QualityOfServiceLevel":0,"Retain":true,"UserProperties":[],"ContentType":null,"ResponseTopic":null,"PayloadFormatIndicator":null,"MessageExpiryInterval":null,"TopicAlias":null,"CorrelationData":null,"SubscriptionIdentifier":null},{"Topic":"fgdfgd","Payload":"YWFzYXNhc2E=","QualityOfServiceLevel":0,"Retain":true,"UserProperties":[],"ContentType":null,"ResponseTopic":null,"PayloadFormatIndicator":null,"MessageExpiryInterval":null,"TopicAlias":null,"CorrelationData":null,"SubscriptionIdentifier":null}]
|
||||
@@ -4,9 +4,12 @@ using System.Dynamic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Scripting;
|
||||
using Microsoft.Scripting.Hosting;
|
||||
using MQTTnet.Server.Configuration;
|
||||
|
||||
namespace MQTTnet.Server.Scripting
|
||||
{
|
||||
@@ -14,26 +17,27 @@ namespace MQTTnet.Server.Scripting
|
||||
{
|
||||
private readonly IDictionary<string, object> _proxyObjects = new ExpandoObject();
|
||||
private readonly List<PythonScriptInstance> _scriptInstances = new List<PythonScriptInstance>();
|
||||
private readonly string _scriptsPath;
|
||||
private readonly ScriptingSettingsModel _scriptingSettings;
|
||||
private readonly ILogger<PythonScriptHostService> _logger;
|
||||
private readonly ScriptEngine _scriptEngine;
|
||||
|
||||
public PythonScriptHostService(PythonIOStream pythonIOStream, ILogger<PythonScriptHostService> logger)
|
||||
public PythonScriptHostService(ScriptingSettingsModel scriptingSettings, PythonIOStream pythonIOStream, ILogger<PythonScriptHostService> logger)
|
||||
{
|
||||
_scriptingSettings = scriptingSettings ?? throw new ArgumentNullException(nameof(scriptingSettings));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
_scriptEngine = IronPython.Hosting.Python.CreateEngine();
|
||||
_scriptEngine.Runtime.IO.SetOutput(pythonIOStream, Encoding.UTF8);
|
||||
|
||||
_scriptsPath = PathHelper.ExpandPath(scriptingSettings.ScriptsPath);
|
||||
}
|
||||
|
||||
public void Configure()
|
||||
{
|
||||
AddSearchPaths(_scriptEngine);
|
||||
|
||||
var scriptsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts");
|
||||
foreach (var filename in Directory.GetFiles(scriptsDirectory, "*.py", SearchOption.AllDirectories).OrderBy(file => file))
|
||||
{
|
||||
TryInitializeScript(filename);
|
||||
}
|
||||
TryInitializeScriptsAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public void RegisterProxyObject(string name, object @object)
|
||||
@@ -58,35 +62,109 @@ namespace MQTTnet.Server.Scripting
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(exception, $"Error while invoking function '{name}' at script '{pythonScriptInstance.Name}'.");
|
||||
_logger.LogError(exception, $"Error while invoking function '{name}' at script '{pythonScriptInstance.Uid}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void TryInitializeScript(string filename)
|
||||
public List<string> GetScriptUids()
|
||||
{
|
||||
try
|
||||
lock (_scriptInstances)
|
||||
{
|
||||
var scriptName = new FileInfo(filename).Name;
|
||||
|
||||
_logger.LogTrace($"Initializing Python script '{scriptName}'...");
|
||||
var code = File.ReadAllText(filename);
|
||||
|
||||
var scriptInstance = CreateScriptInstance(scriptName, code);
|
||||
scriptInstance.InvokeOptionalFunction("initialize");
|
||||
|
||||
_scriptInstances.Add(scriptInstance);
|
||||
|
||||
_logger.LogInformation($"Initialized script '{scriptName}'.");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(exception, $"Error while initializing script '{new FileInfo(filename).Name}'.");
|
||||
return _scriptInstances.Select(si => si.Uid).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
private PythonScriptInstance CreateScriptInstance(string name, string code)
|
||||
public Task<string> ReadScriptAsync(string uid, CancellationToken cancellationToken)
|
||||
{
|
||||
if (uid == null) throw new ArgumentNullException(nameof(uid));
|
||||
|
||||
string path;
|
||||
|
||||
lock (_scriptInstances)
|
||||
{
|
||||
path = _scriptInstances.FirstOrDefault(si => si.Uid == uid)?.Path;
|
||||
}
|
||||
|
||||
if (path == null || !File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return File.ReadAllTextAsync(path, Encoding.UTF8, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task WriteScriptAsync(string uid, string code, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = Path.Combine(_scriptsPath, uid + ".py");
|
||||
|
||||
await File.WriteAllTextAsync(path, code, Encoding.UTF8, cancellationToken).ConfigureAwait(false);
|
||||
await TryInitializeScriptsAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task DeleteScriptAsync(string uid)
|
||||
{
|
||||
var path = Path.Combine(_scriptsPath, uid + ".py");
|
||||
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
await TryInitializeScriptsAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task TryInitializeScriptsAsync()
|
||||
{
|
||||
lock (_scriptInstances)
|
||||
{
|
||||
foreach (var scriptInstance in _scriptInstances)
|
||||
{
|
||||
try
|
||||
{
|
||||
scriptInstance.InvokeOptionalFunction("destroy");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogWarning(exception, $"Error while unloading script '{scriptInstance.Uid}'.");
|
||||
}
|
||||
}
|
||||
|
||||
_scriptInstances.Clear();
|
||||
}
|
||||
|
||||
foreach (var path in Directory.GetFiles(_scriptsPath, "*.py", SearchOption.AllDirectories).OrderBy(file => file))
|
||||
{
|
||||
await TryInitializeScriptAsync(path).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryInitializeScriptAsync(string path)
|
||||
{
|
||||
var uid = new FileInfo(path).Name.Replace(".py", string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogTrace($"Initializing Python script '{uid}'...");
|
||||
var code = await File.ReadAllTextAsync(path).ConfigureAwait(false);
|
||||
|
||||
var scriptInstance = CreateScriptInstance(uid, path, code);
|
||||
scriptInstance.InvokeOptionalFunction("initialize");
|
||||
|
||||
lock (_scriptInstances)
|
||||
{
|
||||
_scriptInstances.Add(scriptInstance);
|
||||
}
|
||||
|
||||
_logger.LogInformation($"Initialized script '{uid}'.");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogError(exception, $"Error while initializing script '{uid}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private PythonScriptInstance CreateScriptInstance(string uid, string path, string code)
|
||||
{
|
||||
var scriptScope = _scriptEngine.CreateScope();
|
||||
|
||||
@@ -96,31 +174,26 @@ namespace MQTTnet.Server.Scripting
|
||||
scriptScope.SetVariable("mqtt_net_server", _proxyObjects);
|
||||
compiledCode.Execute(scriptScope);
|
||||
|
||||
return new PythonScriptInstance(name, scriptScope);
|
||||
return new PythonScriptInstance(uid, path, scriptScope);
|
||||
}
|
||||
|
||||
private void AddSearchPaths(ScriptEngine scriptEngine)
|
||||
{
|
||||
var paths = new List<string>
|
||||
if (_scriptingSettings.IncludePaths?.Any() != true)
|
||||
{
|
||||
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Lib"),
|
||||
"/usr/lib/python2.7",
|
||||
@"C:\Python27\Lib"
|
||||
};
|
||||
|
||||
AddSearchPaths(scriptEngine, paths);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
private void AddSearchPaths(ScriptEngine scriptEngine, IEnumerable<string> paths)
|
||||
{
|
||||
var searchPaths = scriptEngine.GetSearchPaths();
|
||||
|
||||
foreach (var path in paths)
|
||||
foreach (var path in _scriptingSettings.IncludePaths)
|
||||
{
|
||||
if (Directory.Exists(path))
|
||||
var effectivePath = PathHelper.ExpandPath(path);
|
||||
|
||||
if (Directory.Exists(effectivePath))
|
||||
{
|
||||
searchPaths.Add(path);
|
||||
_logger.LogInformation($"Added Python lib path: {path}");
|
||||
searchPaths.Add(effectivePath);
|
||||
_logger.LogInformation($"Added Python lib path: {effectivePath}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,14 +8,17 @@ namespace MQTTnet.Server.Scripting
|
||||
{
|
||||
private readonly ScriptScope _scriptScope;
|
||||
|
||||
public PythonScriptInstance(string name, ScriptScope scriptScope)
|
||||
public PythonScriptInstance(string uid, string path, ScriptScope scriptScope)
|
||||
{
|
||||
_scriptScope = scriptScope;
|
||||
Uid = uid;
|
||||
Path = path;
|
||||
|
||||
Name = name;
|
||||
_scriptScope = scriptScope;
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
public string Uid { get; }
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public bool InvokeOptionalFunction(string name, params object[] parameters)
|
||||
{
|
||||
|
||||
@@ -7,9 +7,17 @@ def initialize():
|
||||
It will be executed only one time.
|
||||
"""
|
||||
|
||||
print("Hello World from Sample script.")
|
||||
print("Hello World from sample script.")
|
||||
|
||||
|
||||
def destroy():
|
||||
"""
|
||||
This function is invoked when the script is unloaded due to a script file update etc.
|
||||
"""
|
||||
|
||||
print("Bye from sample script.")
|
||||
|
||||
|
||||
def on_validate_client_connection(context):
|
||||
"""
|
||||
This function is invoked whenever a client wants to connect. It can be used to validate the connection.
|
||||
@@ -17,20 +25,45 @@ def on_validate_client_connection(context):
|
||||
|
||||
print(context)
|
||||
|
||||
# Access some custom data here which was inserted upon connect and may use it for validation.
|
||||
mqtt_net_server.write_shared_data(context["client_id"], {"custom_value_1": 1, "custom_value_2": True})
|
||||
|
||||
return
|
||||
|
||||
# Supported results:
|
||||
# * success
|
||||
# * unspecified_error
|
||||
# * malformed_packet
|
||||
# * protocol_error
|
||||
# * implementation_specific_error
|
||||
# * unsupported_protocol_version
|
||||
# * client_identifier_not_valid
|
||||
# * bad_user_name_or_password
|
||||
# * not_authorized
|
||||
# * server_unavailable
|
||||
# * server_busy
|
||||
# * banned
|
||||
# * bad_authentication_method
|
||||
# * topic_name_invalid
|
||||
# * packet_too_large
|
||||
# * quota_exceeded
|
||||
# * payload_format_invalid
|
||||
# * retain_not_supported
|
||||
# * qos_not_supported
|
||||
# * use_another_server
|
||||
# * server_moved
|
||||
# * connection_rate_exceeded
|
||||
|
||||
if context["client_id"] != "test_client":
|
||||
context["result"] = "connection_refused_not_authorized"
|
||||
context["result"] = "bad_user_name_or_password"
|
||||
return
|
||||
|
||||
if context["username"] != "bud spencer":
|
||||
context["result"] = "connection_refused_not_authorized"
|
||||
context["result"] = "bad_user_name_or_password"
|
||||
return
|
||||
|
||||
if context["password"] != "secret":
|
||||
context["result"] = "connection_refused_not_authorized"
|
||||
if context["password_string"] != "secret":
|
||||
context["result"] = "bad_user_name_or_password"
|
||||
|
||||
print(context)
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
This directory contains scripts which are loaded by the server and can be used to perform the following tasks.
|
||||
# MQTT Scripts
|
||||
|
||||
1. Validation of client connections via credentials, client IDs etc.
|
||||
2. Manipulation of every processed message.
|
||||
3. Validation of subscription attempts.
|
||||
4. Publishing of custom application messages.
|
||||
This directory contains scripts which are loaded by the server and can be used to perform the following tasks.
|
||||
|
||||
* Validation of client connections via credentials, client IDs etc.
|
||||
* Manipulation of every processed message.
|
||||
* Validation of subscription attempts.
|
||||
* Publishing of custom application messages.
|
||||
|
||||
All scripts are loaded and _MQTTnet Server_ will invoke functions according to predefined naming conventions.
|
||||
If a function is implemented in multiple scripts the context will be moved throug all instances. This allows overriding of results or passing data to other (following) scripts.
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Threading.Tasks;
|
||||
using IronPython.Runtime;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using Microsoft.Scripting;
|
||||
|
||||
namespace MQTTnet.Server.Web
|
||||
{
|
||||
public class AuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
private readonly ILogger<AuthenticationHandler> _logger;
|
||||
|
||||
public AuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory loggerFactory,
|
||||
UrlEncoder encoder,
|
||||
ISystemClock clock,
|
||||
ILogger<AuthenticationHandler> logger)
|
||||
: base(options, loggerFactory, encoder, clock)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (!Request.Headers.ContainsKey(HeaderNames.Authorization))
|
||||
{
|
||||
return AuthenticateResult.NoResult();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var headerValue = Request.Headers[HeaderNames.Authorization];
|
||||
var parsedHeaderValue = AuthenticationHeaderValue.Parse(Request.Headers[HeaderNames.Authorization]);
|
||||
|
||||
var scheme = parsedHeaderValue.Scheme;
|
||||
var parameter = parsedHeaderValue.Parameter;
|
||||
string username = null;
|
||||
string password = null;
|
||||
|
||||
if (scheme.Equals("Basic", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var credentialBytes = Convert.FromBase64String(parsedHeaderValue.Parameter);
|
||||
var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':');
|
||||
username = credentials[0];
|
||||
password = credentials[1];
|
||||
}
|
||||
|
||||
var context = new PythonDictionary
|
||||
{
|
||||
["header_value"] = headerValue,
|
||||
["scheme"] = scheme,
|
||||
["parameter"] = parameter,
|
||||
["username"] = username,
|
||||
["password"] = password,
|
||||
["is_authenticated"] = false
|
||||
};
|
||||
|
||||
if (!ValidateUser(context))
|
||||
{
|
||||
return AuthenticateResult.Fail("Invalid credentials.");
|
||||
}
|
||||
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, context.get("username") as string ?? string.Empty)
|
||||
};
|
||||
|
||||
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, Scheme.Name);
|
||||
|
||||
return AuthenticateResult.Success(ticket);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogWarning("Error while authenticating user.", exception);
|
||||
|
||||
return AuthenticateResult.Fail(exception);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private bool ValidateUser(PythonDictionary context)
|
||||
{
|
||||
var handlerPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "authorization_handler.py");
|
||||
if (!File.Exists(handlerPath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var code = File.ReadAllText(handlerPath);
|
||||
|
||||
var scriptEngine = IronPython.Hosting.Python.CreateEngine();
|
||||
//scriptEngine.Runtime.IO.SetOutput(new PythonIOStream(_logger.), Encoding.UTF8);
|
||||
|
||||
var scriptScope = scriptEngine.CreateScope();
|
||||
var scriptSource = scriptScope.Engine.CreateScriptSourceFromString(code, SourceCodeKind.File);
|
||||
var compiledCode = scriptSource.Compile();
|
||||
compiledCode.Execute(scriptScope);
|
||||
var function = scriptScope.Engine.Operations.GetMember<PythonFunction>(scriptScope, "handle_authenticate");
|
||||
scriptScope.Engine.Operations.Invoke(function, context);
|
||||
|
||||
return context.get("is_authenticated", false) as bool? == true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace MQTTnet.Server.Web
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
public static string ReadBodyAsString(this HttpRequest request)
|
||||
{
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
|
||||
using (var reader = new StreamReader(request.Body, Encoding.UTF8))
|
||||
{
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore.Internal;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Microsoft.Scripting.Utils;
|
||||
using MQTTnet.Server.Configuration;
|
||||
@@ -14,7 +18,7 @@ using MQTTnet.Server.Scripting;
|
||||
using MQTTnet.Server.Scripting.DataSharing;
|
||||
using Swashbuckle.AspNetCore.SwaggerUI;
|
||||
|
||||
namespace MQTTnet.Server
|
||||
namespace MQTTnet.Server.Web
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
@@ -35,7 +39,7 @@ namespace MQTTnet.Server
|
||||
MqttServerService mqttServerService,
|
||||
PythonScriptHostService pythonScriptHostService,
|
||||
DataSharingService dataSharingService,
|
||||
SettingsModel settings)
|
||||
MqttSettingsModel mqttSettings)
|
||||
{
|
||||
if (environment.IsDevelopment())
|
||||
{
|
||||
@@ -46,12 +50,20 @@ namespace MQTTnet.Server
|
||||
application.UseHsts();
|
||||
}
|
||||
|
||||
application.UseCors(x => x
|
||||
.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials());
|
||||
|
||||
application.UseAuthentication();
|
||||
|
||||
application.UseStaticFiles();
|
||||
|
||||
application.UseHttpsRedirection();
|
||||
application.UseMvc();
|
||||
|
||||
ConfigureWebSocketEndpoint(application, mqttServerService, settings);
|
||||
ConfigureWebSocketEndpoint(application, mqttServerService, mqttSettings);
|
||||
|
||||
dataSharingService.Configure();
|
||||
pythonScriptHostService.Configure();
|
||||
@@ -73,6 +85,8 @@ namespace MQTTnet.Server
|
||||
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddCors();
|
||||
|
||||
services.AddMvc()
|
||||
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
|
||||
.AddJsonOptions(options =>
|
||||
@@ -80,7 +94,7 @@ namespace MQTTnet.Server
|
||||
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
|
||||
});
|
||||
|
||||
services.AddSingleton(ReadSettings());
|
||||
ReadMqttSettings(services);
|
||||
|
||||
services.AddSingleton<PythonIOStream>();
|
||||
services.AddSingleton<PythonScriptHostService>();
|
||||
@@ -95,13 +109,29 @@ namespace MQTTnet.Server
|
||||
services.AddSingleton<MqttClientDisconnectedHandler>();
|
||||
services.AddSingleton<MqttClientSubscribedTopicHandler>();
|
||||
services.AddSingleton<MqttClientUnsubscribedTopicHandler>();
|
||||
services.AddSingleton<MqttConnectionValidator>();
|
||||
services.AddSingleton<MqttServerConnectionValidator>();
|
||||
services.AddSingleton<MqttSubscriptionInterceptor>();
|
||||
services.AddSingleton<MqttApplicationMessageInterceptor>();
|
||||
|
||||
|
||||
services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.DescribeAllEnumsAsStrings();
|
||||
|
||||
var securityScheme = new OpenApiSecurityScheme
|
||||
{
|
||||
Scheme = "Basic",
|
||||
Name = HeaderNames.Authorization,
|
||||
Type = SecuritySchemeType.Http,
|
||||
In = ParameterLocation.Header
|
||||
};
|
||||
|
||||
c.AddSecurityDefinition("Swagger", securityScheme);
|
||||
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
{
|
||||
[securityScheme] = new List<string>()
|
||||
});
|
||||
|
||||
c.SwaggerDoc("v1", new OpenApiInfo
|
||||
{
|
||||
Title = "MQTTnet.Server API",
|
||||
@@ -120,46 +150,54 @@ namespace MQTTnet.Server
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
services.AddAuthentication("Basic")
|
||||
.AddScheme<AuthenticationSchemeOptions, AuthenticationHandler>("Basic", null)
|
||||
.AddCookie();
|
||||
}
|
||||
|
||||
private SettingsModel ReadSettings()
|
||||
private void ReadMqttSettings(IServiceCollection services)
|
||||
{
|
||||
var settings = new Configuration.SettingsModel();
|
||||
Configuration.Bind("MQTT", settings);
|
||||
return settings;
|
||||
var mqttSettings = new MqttSettingsModel();
|
||||
Configuration.Bind("MQTT", mqttSettings);
|
||||
services.AddSingleton(mqttSettings);
|
||||
|
||||
var scriptingSettings = new ScriptingSettingsModel();
|
||||
Configuration.Bind("Scripting", scriptingSettings);
|
||||
services.AddSingleton(scriptingSettings);
|
||||
}
|
||||
|
||||
private static void ConfigureWebSocketEndpoint(
|
||||
IApplicationBuilder application,
|
||||
MqttServerService mqttServerService,
|
||||
SettingsModel settings)
|
||||
MqttSettingsModel mqttSettings)
|
||||
{
|
||||
if (settings?.WebSocketEndPoint?.Enabled != true)
|
||||
if (mqttSettings?.WebSocketEndPoint?.Enabled != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(settings.WebSocketEndPoint.Path))
|
||||
if (string.IsNullOrEmpty(mqttSettings.WebSocketEndPoint.Path))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var webSocketOptions = new WebSocketOptions
|
||||
{
|
||||
KeepAliveInterval = TimeSpan.FromSeconds(settings.WebSocketEndPoint.KeepAliveInterval),
|
||||
ReceiveBufferSize = settings.WebSocketEndPoint.ReceiveBufferSize
|
||||
KeepAliveInterval = TimeSpan.FromSeconds(mqttSettings.WebSocketEndPoint.KeepAliveInterval),
|
||||
ReceiveBufferSize = mqttSettings.WebSocketEndPoint.ReceiveBufferSize
|
||||
};
|
||||
|
||||
if (settings.WebSocketEndPoint.AllowedOrigins?.Any() == true)
|
||||
if (mqttSettings.WebSocketEndPoint.AllowedOrigins?.Any() == true)
|
||||
{
|
||||
webSocketOptions.AllowedOrigins.AddRange(settings.WebSocketEndPoint.AllowedOrigins);
|
||||
webSocketOptions.AllowedOrigins.AddRange(mqttSettings.WebSocketEndPoint.AllowedOrigins);
|
||||
}
|
||||
|
||||
|
||||
application.UseWebSockets(webSocketOptions);
|
||||
|
||||
application.Use(async (context, next) =>
|
||||
{
|
||||
if (context.Request.Path == settings.WebSocketEndPoint.Path)
|
||||
if (context.Request.Path == mqttSettings.WebSocketEndPoint.Path)
|
||||
{
|
||||
if (context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
@@ -170,7 +208,7 @@ namespace MQTTnet.Server
|
||||
}
|
||||
else
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -0,0 +1,20 @@
|
||||
def handle_authenticate(context):
|
||||
"""
|
||||
This function is invoked whenever a user tries to access protected HTTP resources.
|
||||
This function must exist and return a proper value. Otherwise the request is denied.
|
||||
All authentication data must be sent via using the "Authorization" header. This header
|
||||
will be parsed and all values will be exposed to the context.
|
||||
"""
|
||||
header_value = context["header_value"] # The untouched header value.
|
||||
|
||||
scheme = context["scheme"]
|
||||
parameter = context["parameter"]
|
||||
|
||||
username = context["username"] # Only set if proper "Basic" authorization is used.
|
||||
password = context["password"] # Only set if proper "Basic" authorization is used.
|
||||
|
||||
context["is_authenticated"] = True # Change this to _False_ in case of invalid credentials.
|
||||
|
||||
# Example for an API key with proper format.
|
||||
if header_value == "APIKey 123456":
|
||||
context["is_authenticated"] = True
|
||||
@@ -2,10 +2,10 @@
|
||||
"Kestrel": {
|
||||
"EndPoints": {
|
||||
"Http": {
|
||||
"Url": "http://localhost:80"
|
||||
"Url": "http://*:80"
|
||||
},
|
||||
"Https": {
|
||||
"Url": "http://localhost:443"
|
||||
"Url": "http://*:443"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -27,7 +27,10 @@
|
||||
"IPv4": "*",
|
||||
"IPv6": "*",
|
||||
"Port": 8883,
|
||||
"CertificatePath": "/absolute/path/to/pfx"
|
||||
"Certificate": {
|
||||
"Path": "/absolute/path/to/pfx",
|
||||
"Password": ""
|
||||
}
|
||||
},
|
||||
"WebSocketEndPoint": {
|
||||
"Enabled": true,
|
||||
@@ -37,15 +40,23 @@
|
||||
"AllowedOrigins": [] // List of strings with URLs.
|
||||
},
|
||||
"CommunicationTimeout": 15, // In seconds.
|
||||
"ConnectionBacklog": 0, /* Set 0 to disable */
|
||||
"EnablePersistentSessions": false,
|
||||
"ConnectionBacklog": 10, // Set 0 to disable
|
||||
"EnablePersistentSessions": true,
|
||||
"MaxPendingMessagesPerClient": 250,
|
||||
"RetainedApplicationMessages": {
|
||||
"Persist": true,
|
||||
"Filename": "RetainedApplicationMessages.json",
|
||||
"Path": "RetainedApplicationMessages.json",
|
||||
"WriteInterval": 10 // In seconds.
|
||||
},
|
||||
"EnableDebugLogging": true
|
||||
"EnableDebugLogging": false
|
||||
},
|
||||
"Scripting": {
|
||||
"ScriptsPath": "Scripts",
|
||||
"IncludePaths": [
|
||||
"Lib",
|
||||
"/usr/lib/python2.7",
|
||||
"C:\\Python27\\Lib"
|
||||
]
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
@@ -55,4 +66,4 @@
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
@echo off
|
||||
START "MQTTnet Server" dotnet .\MQTTnet.Server.dll
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/bash
|
||||
echo "Starting MQTTnet Server.."
|
||||
dotnet .\MQTTnet.Server.dll
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Formatter;
|
||||
@@ -12,6 +13,8 @@ namespace MQTTnet.Adapter
|
||||
|
||||
bool IsSecureConnection { get; }
|
||||
|
||||
X509Certificate2 ClientCertificate { get; }
|
||||
|
||||
MqttPacketFormatterAdapter PacketFormatterAdapter { get; }
|
||||
|
||||
long BytesSent { get; }
|
||||
@@ -29,5 +32,7 @@ namespace MQTTnet.Adapter
|
||||
Task SendPacketAsync(MqttBasePacket packet, TimeSpan timeout, CancellationToken cancellationToken);
|
||||
|
||||
Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken);
|
||||
|
||||
void ResetStatistics();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Channel;
|
||||
@@ -47,6 +48,8 @@ namespace MQTTnet.Adapter
|
||||
|
||||
public bool IsSecureConnection => _channel.IsSecureConnection;
|
||||
|
||||
public X509Certificate2 ClientCertificate => _channel.ClientCertificate;
|
||||
|
||||
public MqttPacketFormatterAdapter PacketFormatterAdapter { get; }
|
||||
|
||||
public long BytesSent => Interlocked.Read(ref _bytesSent);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -8,6 +9,7 @@ namespace MQTTnet.Channel
|
||||
{
|
||||
string Endpoint { get; }
|
||||
bool IsSecureConnection { get; }
|
||||
X509Certificate2 ClientCertificate { get; }
|
||||
|
||||
Task ConnectAsync(CancellationToken cancellationToken);
|
||||
Task DisconnectAsync(CancellationToken cancellationToken);
|
||||
|
||||
@@ -1,9 +1,45 @@
|
||||
namespace MQTTnet.Client.Connecting
|
||||
using System.Collections.Generic;
|
||||
using MQTTnet.Packets;
|
||||
|
||||
namespace MQTTnet.Client.Connecting
|
||||
{
|
||||
// TODO: Consider renaming this to _MqttClientConnectResult_
|
||||
public class MqttClientAuthenticateResult
|
||||
{
|
||||
public MqttClientConnectResultCode ResultCode { get; set; }
|
||||
|
||||
public bool IsSessionPresent { get; set; }
|
||||
|
||||
public MqttClientConnectResultCode ResultCode { get; set; }
|
||||
public bool? WildcardSubscriptionAvailable { get; set; }
|
||||
|
||||
public bool? RetainAvailable { get; set; }
|
||||
|
||||
public string AssignedClientIdentifier { get; set; }
|
||||
|
||||
public string AuthenticationMethod { get; set; }
|
||||
|
||||
public byte[] AuthenticationData { get; set; }
|
||||
|
||||
public uint? MaximumPacketSize { get; set; }
|
||||
|
||||
public string ReasonString { get; set; }
|
||||
|
||||
public ushort? ReceiveMaximum { get; set; }
|
||||
|
||||
public string ResponseInformation { get; set; }
|
||||
|
||||
public ushort? TopicAliasMaximum { get; set; }
|
||||
|
||||
public string ServerReference { get; set; }
|
||||
|
||||
public ushort? ServerKeepAlive { get; set; }
|
||||
|
||||
public uint? SessionExpiryInterval { get; set; }
|
||||
|
||||
public bool? SubscriptionIdentifiersAvailable { get; set; }
|
||||
|
||||
public bool? SharedSubscriptionAvailable { get; set; }
|
||||
|
||||
public List<MqttUserProperty> UserProperties { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
using System;
|
||||
using MQTTnet.Client.Connecting;
|
||||
|
||||
namespace MQTTnet.Client.Disconnecting
|
||||
{
|
||||
public class MqttClientDisconnectedEventArgs : EventArgs
|
||||
{
|
||||
public MqttClientDisconnectedEventArgs(bool clientWasConnected, Exception exception)
|
||||
public MqttClientDisconnectedEventArgs(bool clientWasConnected, Exception exception, MqttClientAuthenticateResult authenticateResult)
|
||||
{
|
||||
ClientWasConnected = clientWasConnected;
|
||||
Exception = exception;
|
||||
AuthenticateResult = authenticateResult;
|
||||
}
|
||||
|
||||
public bool ClientWasConnected { get; }
|
||||
|
||||
public Exception Exception { get; }
|
||||
|
||||
public MqttClientAuthenticateResult AuthenticateResult { get; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MQTTnet.Client.ExtendedAuthenticationExchange
|
||||
{
|
||||
public interface IMqttExtendedAuthenticationExchangeHandler
|
||||
{
|
||||
Task HandleRequestAsync(MqttExtendedAuthenticationExchangeContext context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Client.ExtendedAuthenticationExchange
|
||||
{
|
||||
public class MqttExtendedAuthenticationExchangeContext
|
||||
{
|
||||
public MqttExtendedAuthenticationExchangeContext(MqttAuthPacket authPacket, IMqttClient client)
|
||||
{
|
||||
if (authPacket == null) throw new ArgumentNullException(nameof(authPacket));
|
||||
|
||||
ReasonCode = authPacket.ReasonCode;
|
||||
ReasonString = authPacket.Properties?.ReasonString;
|
||||
AuthenticationMethod = authPacket.Properties?.AuthenticationMethod;
|
||||
AuthenticationData = authPacket.Properties?.AuthenticationData;
|
||||
UserProperties = authPacket.Properties?.UserProperties;
|
||||
|
||||
Client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
}
|
||||
|
||||
public MqttAuthenticateReasonCode ReasonCode { get; }
|
||||
|
||||
public string ReasonString { get; }
|
||||
|
||||
public string AuthenticationMethod { get; }
|
||||
|
||||
public byte[] AuthenticationData { get; }
|
||||
|
||||
public List<MqttUserProperty> UserProperties { get; }
|
||||
|
||||
public IMqttClient Client { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Collections.Generic;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Client.ExtendedAuthenticationExchange
|
||||
{
|
||||
public class MqttExtendedAuthenticationExchangeData
|
||||
{
|
||||
public MqttAuthenticateReasonCode ReasonCode { get; set; }
|
||||
|
||||
public string ReasonString { get; set; }
|
||||
|
||||
public byte[] AuthenticationData { get; set; }
|
||||
|
||||
public List<MqttUserProperty> UserProperties { get; }
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Client.Connecting;
|
||||
using MQTTnet.Client.Disconnecting;
|
||||
using MQTTnet.Client.ExtendedAuthenticationExchange;
|
||||
using MQTTnet.Client.Options;
|
||||
using MQTTnet.Client.Subscribing;
|
||||
using MQTTnet.Client.Unsubscribing;
|
||||
@@ -21,6 +22,7 @@ namespace MQTTnet.Client
|
||||
Task<MqttClientAuthenticateResult> ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken);
|
||||
Task DisconnectAsync(MqttClientDisconnectOptions options, CancellationToken cancellationToken);
|
||||
|
||||
Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticationExchangeData data, CancellationToken cancellationToken);
|
||||
Task<MqttClientSubscribeResult> SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken);
|
||||
Task<MqttClientUnsubscribeResult> UnsubscribeAsync(MqttClientUnsubscribeOptions options, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace MQTTnet.Client
|
||||
{
|
||||
public interface IMqttClientFactory
|
||||
{
|
||||
IMqttFactory UseClientAdapterFactory(IMqttClientAdapterFactory clientAdapterFactory);
|
||||
|
||||
IMqttClient CreateMqttClient();
|
||||
|
||||
IMqttClient CreateMqttClient(IMqttNetLogger logger);
|
||||
|
||||
@@ -5,6 +5,7 @@ using System.Threading.Tasks;
|
||||
using MQTTnet.Adapter;
|
||||
using MQTTnet.Client.Connecting;
|
||||
using MQTTnet.Client.Disconnecting;
|
||||
using MQTTnet.Client.ExtendedAuthenticationExchange;
|
||||
using MQTTnet.Client.Options;
|
||||
using MQTTnet.Client.Publishing;
|
||||
using MQTTnet.Client.Receiving;
|
||||
@@ -12,6 +13,7 @@ using MQTTnet.Client.Subscribing;
|
||||
using MQTTnet.Client.Unsubscribing;
|
||||
using MQTTnet.Diagnostics;
|
||||
using MQTTnet.Exceptions;
|
||||
using MQTTnet.Internal;
|
||||
using MQTTnet.PacketDispatcher;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
@@ -61,6 +63,8 @@ namespace MQTTnet.Client
|
||||
|
||||
ThrowIfConnected("It is not allowed to connect with a server after the connection is established.");
|
||||
|
||||
MqttClientAuthenticateResult authenticateResult = null;
|
||||
|
||||
try
|
||||
{
|
||||
Options = options;
|
||||
@@ -81,7 +85,7 @@ namespace MQTTnet.Client
|
||||
|
||||
_packetReceiverTask = Task.Run(() => TryReceivePacketsAsync(backgroundCancellationToken), backgroundCancellationToken);
|
||||
|
||||
var authenticateResult = await AuthenticateAsync(adapter, options.WillMessage, cancellationToken).ConfigureAwait(false);
|
||||
authenticateResult = await AuthenticateAsync(adapter, options.WillMessage, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_sendTracker.Restart();
|
||||
|
||||
@@ -108,7 +112,7 @@ namespace MQTTnet.Client
|
||||
|
||||
if (!DisconnectIsPending())
|
||||
{
|
||||
await DisconnectInternalAsync(null, exception).ConfigureAwait(false);
|
||||
await DisconnectInternalAsync(null, exception, authenticateResult).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
throw;
|
||||
@@ -131,11 +135,28 @@ namespace MQTTnet.Client
|
||||
{
|
||||
if (!DisconnectIsPending())
|
||||
{
|
||||
await DisconnectInternalAsync(null, null).ConfigureAwait(false);
|
||||
await DisconnectInternalAsync(null, null, null).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticationExchangeData data, CancellationToken cancellationToken)
|
||||
{
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
|
||||
return SendAsync(new MqttAuthPacket
|
||||
{
|
||||
Properties = new MqttAuthPacketProperties
|
||||
{
|
||||
// This must always be equal to the value from the CONNECT packet. So we use it here to ensure that.
|
||||
AuthenticationMethod = Options.AuthenticationMethod,
|
||||
AuthenticationData = data.AuthenticationData,
|
||||
ReasonString = data.ReasonString,
|
||||
UserProperties = data.UserProperties
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<MqttClientSubscribeResult> SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
@@ -232,16 +253,16 @@ namespace MQTTnet.Client
|
||||
if (IsConnected) throw new MqttProtocolViolationException(message);
|
||||
}
|
||||
|
||||
private async Task DisconnectInternalAsync(Task sender, Exception exception)
|
||||
private async Task DisconnectInternalAsync(Task sender, Exception exception, MqttClientAuthenticateResult authenticateResult)
|
||||
{
|
||||
var clientWasConnected = IsConnected;
|
||||
|
||||
InitiateDisconnect();
|
||||
|
||||
IsConnected = false;
|
||||
TryInitiateDisconnect();
|
||||
|
||||
try
|
||||
{
|
||||
IsConnected = false;
|
||||
|
||||
if (_adapter != null)
|
||||
{
|
||||
_logger.Verbose("Disconnecting [Timeout={0}]", Options.CommunicationTimeout);
|
||||
@@ -267,12 +288,14 @@ namespace MQTTnet.Client
|
||||
var disconnectedHandler = DisconnectedHandler;
|
||||
if (disconnectedHandler != null)
|
||||
{
|
||||
await disconnectedHandler.HandleDisconnectedAsync(new MqttClientDisconnectedEventArgs(clientWasConnected, exception)).ConfigureAwait(false);
|
||||
// This handler must be executed in a new thread because otherwise a dead lock may happen
|
||||
// when trying to reconnect in that handler etc.
|
||||
Task.Run(() => disconnectedHandler.HandleDisconnectedAsync(new MqttClientDisconnectedEventArgs(clientWasConnected, exception, authenticateResult))).Forget(_logger);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void InitiateDisconnect()
|
||||
private void TryInitiateDisconnect()
|
||||
{
|
||||
lock (_disconnectLock)
|
||||
{
|
||||
@@ -339,6 +362,7 @@ namespace MQTTnet.Client
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Values described here: [MQTT-3.1.2-24].
|
||||
var keepAliveSendInterval = TimeSpan.FromSeconds(Options.KeepAlivePeriod.TotalSeconds * 0.75);
|
||||
if (Options.KeepAliveSendInterval.HasValue)
|
||||
{
|
||||
@@ -376,7 +400,7 @@ namespace MQTTnet.Client
|
||||
|
||||
if (!DisconnectIsPending())
|
||||
{
|
||||
await DisconnectInternalAsync(_keepAlivePacketsSenderTask, exception).ConfigureAwait(false);
|
||||
await DisconnectInternalAsync(_keepAlivePacketsSenderTask, exception, null).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -404,7 +428,7 @@ namespace MQTTnet.Client
|
||||
{
|
||||
if (!DisconnectIsPending())
|
||||
{
|
||||
await DisconnectInternalAsync(_packetReceiverTask, null).ConfigureAwait(false);
|
||||
await DisconnectInternalAsync(_packetReceiverTask, null, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -436,7 +460,7 @@ namespace MQTTnet.Client
|
||||
|
||||
if (!DisconnectIsPending())
|
||||
{
|
||||
await DisconnectInternalAsync(_packetReceiverTask, exception).ConfigureAwait(false);
|
||||
await DisconnectInternalAsync(_packetReceiverTask, exception, null).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -467,8 +491,19 @@ namespace MQTTnet.Client
|
||||
}
|
||||
else if (packet is MqttDisconnectPacket)
|
||||
{
|
||||
// Also dispatch disconnect to waiting threads to generate a proper exception.
|
||||
_packetDispatcher.Dispatch(packet);
|
||||
|
||||
await DisconnectAsync(null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (packet is MqttAuthPacket authPacket)
|
||||
{
|
||||
var extendedAuthenticationExchangeHandler = Options.ExtendedAuthenticationExchangeHandler;
|
||||
if (extendedAuthenticationExchangeHandler != null)
|
||||
{
|
||||
await extendedAuthenticationExchangeHandler.HandleRequestAsync(new MqttExtendedAuthenticationExchangeContext(authPacket, this)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_packetDispatcher.Dispatch(packet);
|
||||
@@ -497,7 +532,7 @@ namespace MQTTnet.Client
|
||||
|
||||
if (!DisconnectIsPending())
|
||||
{
|
||||
await DisconnectInternalAsync(_packetReceiverTask, exception).ConfigureAwait(false);
|
||||
await DisconnectInternalAsync(_packetReceiverTask, exception, null).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -617,4 +652,4 @@ namespace MQTTnet.Client
|
||||
return Interlocked.CompareExchange(ref _disconnectGate, 1, 0) != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Client.Connecting;
|
||||
using MQTTnet.Client.Disconnecting;
|
||||
using MQTTnet.Client.ExtendedAuthenticationExchange;
|
||||
using MQTTnet.Client.Options;
|
||||
using MQTTnet.Client.Publishing;
|
||||
using MQTTnet.Client.Receiving;
|
||||
@@ -170,21 +171,36 @@ namespace MQTTnet.Client
|
||||
|
||||
public static Task<MqttClientAuthenticateResult> ConnectAsync(this IMqttClient client, IMqttClientOptions options)
|
||||
{
|
||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||
|
||||
return client.ConnectAsync(options, CancellationToken.None);
|
||||
}
|
||||
|
||||
public static Task DisconnectAsync(this IMqttClient client, MqttClientDisconnectOptions options)
|
||||
{
|
||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||
|
||||
return client.DisconnectAsync(options, CancellationToken.None);
|
||||
}
|
||||
|
||||
public static Task SendExtendedAuthenticationExchangeDataAsync(this IMqttClient client, MqttExtendedAuthenticationExchangeData data)
|
||||
{
|
||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||
|
||||
return client.SendExtendedAuthenticationExchangeDataAsync(data, CancellationToken.None);
|
||||
}
|
||||
|
||||
public static Task<MqttClientSubscribeResult> SubscribeAsync(this IMqttClient client, MqttClientSubscribeOptions options)
|
||||
{
|
||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||
|
||||
return client.SubscribeAsync(options, CancellationToken.None);
|
||||
}
|
||||
|
||||
public static Task<MqttClientUnsubscribeResult> UnsubscribeAsync(this IMqttClient client, MqttClientUnsubscribeOptions options)
|
||||
{
|
||||
if (client == null) throw new ArgumentNullException(nameof(client));
|
||||
|
||||
return client.UnsubscribeAsync(options, CancellationToken.None);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
{
|
||||
public interface IMqttClientCredentials
|
||||
{
|
||||
string Password { get; }
|
||||
string Username { get; }
|
||||
byte[] Password { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using MQTTnet.Client.ExtendedAuthenticationExchange;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Client.Options
|
||||
@@ -8,6 +9,7 @@ namespace MQTTnet.Client.Options
|
||||
string ClientId { get; }
|
||||
bool CleanSession { get; }
|
||||
IMqttClientCredentials Credentials { get; }
|
||||
IMqttExtendedAuthenticationExchangeHandler ExtendedAuthenticationExchangeHandler { get; }
|
||||
MqttProtocolVersion ProtocolVersion { get; }
|
||||
IMqttClientChannelOptions ChannelOptions { get; }
|
||||
|
||||
|
||||
@@ -4,6 +4,6 @@
|
||||
{
|
||||
public string Username { get; set; }
|
||||
|
||||
public string Password { get; set; }
|
||||
public byte[] Password { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using MQTTnet.Client.ExtendedAuthenticationExchange;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Client.Options
|
||||
@@ -8,6 +9,7 @@ namespace MQTTnet.Client.Options
|
||||
public string ClientId { get; set; } = Guid.NewGuid().ToString("N");
|
||||
public bool CleanSession { get; set; } = true;
|
||||
public IMqttClientCredentials Credentials { get; set; }
|
||||
public IMqttExtendedAuthenticationExchangeHandler ExtendedAuthenticationExchangeHandler { get; set; }
|
||||
public MqttProtocolVersion ProtocolVersion { get; set; } = MqttProtocolVersion.V311;
|
||||
|
||||
public IMqttClientChannelOptions ChannelOptions { get; set; }
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using MQTTnet.Client.ExtendedAuthenticationExchange;
|
||||
using MQTTnet.Formatter;
|
||||
|
||||
namespace MQTTnet.Client.Options
|
||||
@@ -115,6 +117,18 @@ namespace MQTTnet.Client.Options
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithCredentials(string username, string password = null)
|
||||
{
|
||||
byte[] passwordBuffer = null;
|
||||
|
||||
if (password != null)
|
||||
{
|
||||
passwordBuffer = Encoding.UTF8.GetBytes(password);
|
||||
}
|
||||
|
||||
return WithCredentials(username, passwordBuffer);
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithCredentials(string username, byte[] password = null)
|
||||
{
|
||||
_options.Credentials = new MqttClientCredentials
|
||||
{
|
||||
@@ -125,6 +139,19 @@ namespace MQTTnet.Client.Options
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithCredentials(IMqttClientCredentials credentials)
|
||||
{
|
||||
_options.Credentials = credentials;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithExtendedAuthenticationExchangeHandler(IMqttExtendedAuthenticationExchangeHandler handler)
|
||||
{
|
||||
_options.ExtendedAuthenticationExchangeHandler = handler;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithTcpServer(string server, int? port = null)
|
||||
{
|
||||
_tcpOptions = new MqttClientTcpOptions
|
||||
@@ -136,6 +163,17 @@ namespace MQTTnet.Client.Options
|
||||
return this;
|
||||
}
|
||||
|
||||
// TODO: Consider creating _MqttClientTcpOptionsBuilder_ as overload.
|
||||
public MqttClientOptionsBuilder WithTcpServer(Action<MqttClientTcpOptions> optionsBuilder)
|
||||
{
|
||||
if (optionsBuilder == null) throw new ArgumentNullException(nameof(optionsBuilder));
|
||||
|
||||
_tcpOptions = new MqttClientTcpOptions();
|
||||
optionsBuilder.Invoke(_tcpOptions);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithProxy(string address, string username = null, string password = null, string domain = null, bool bypassOnLocal = false, string[] bypassList = null)
|
||||
{
|
||||
_proxyOptions = new MqttClientWebSocketProxyOptions
|
||||
@@ -151,6 +189,15 @@ namespace MQTTnet.Client.Options
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithProxy(Action<MqttClientWebSocketProxyOptions> optionsBuilder)
|
||||
{
|
||||
if (optionsBuilder == null) throw new ArgumentNullException(nameof(optionsBuilder));
|
||||
|
||||
_proxyOptions = new MqttClientWebSocketProxyOptions();
|
||||
optionsBuilder(_proxyOptions);
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithWebSocketServer(string uri, MqttClientOptionsBuilderWebSocketParameters parameters = null)
|
||||
{
|
||||
_webSocketOptions = new MqttClientWebSocketOptions
|
||||
@@ -163,9 +210,19 @@ namespace MQTTnet.Client.Options
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithWebSocketServer(Action<MqttClientWebSocketOptions> optionsBuilder)
|
||||
{
|
||||
if (optionsBuilder == null) throw new ArgumentNullException(nameof(optionsBuilder));
|
||||
|
||||
_webSocketOptions = new MqttClientWebSocketOptions();
|
||||
optionsBuilder.Invoke(_webSocketOptions);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithTls(MqttClientOptionsBuilderTlsParameters parameters)
|
||||
{
|
||||
_tlsParameters = parameters ?? throw new ArgumentNullException(nameof(parameters));
|
||||
_tlsParameters = parameters;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -174,6 +231,15 @@ namespace MQTTnet.Client.Options
|
||||
return WithTls(new MqttClientOptionsBuilderTlsParameters { UseTls = true });
|
||||
}
|
||||
|
||||
public MqttClientOptionsBuilder WithTls(Action<MqttClientOptionsBuilderTlsParameters> optionsBuilder)
|
||||
{
|
||||
if (optionsBuilder == null) throw new ArgumentNullException(nameof(optionsBuilder));
|
||||
|
||||
_tlsParameters = new MqttClientOptionsBuilderTlsParameters();
|
||||
optionsBuilder(_tlsParameters);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IMqttClientOptions Build()
|
||||
{
|
||||
if (_tcpOptions == null && _webSocketOptions == null)
|
||||
|
||||
@@ -10,7 +10,7 @@ namespace MQTTnet.Client.Options
|
||||
|
||||
public int BufferSize { get; set; } = 65536;
|
||||
|
||||
public bool DualMode { get; set; } = true;
|
||||
public bool? DualMode { get; set; }
|
||||
|
||||
public bool NoDelay { get; set; } = true;
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ namespace MQTTnet.Client.Subscribing
|
||||
{
|
||||
public List<TopicFilter> TopicFilters { get; set; } = new List<TopicFilter>();
|
||||
|
||||
public List<MqttUserProperty> UserProperties { get; set; } = new List<MqttUserProperty>();
|
||||
public uint? SubscriptionIdentifier { get; set; }
|
||||
|
||||
public List<MqttUserProperty> UserProperties { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Client.Subscribing
|
||||
{
|
||||
public class MqttClientSubscribeOptionsBuilder
|
||||
{
|
||||
private readonly MqttClientSubscribeOptions _subscribeOptions = new MqttClientSubscribeOptions();
|
||||
|
||||
public MqttClientSubscribeOptionsBuilder WithUserProperty(string name, string value)
|
||||
{
|
||||
if (name == null) throw new ArgumentNullException(nameof(name));
|
||||
if (value == null) throw new ArgumentNullException(nameof(value));
|
||||
|
||||
if (_subscribeOptions.UserProperties == null)
|
||||
{
|
||||
_subscribeOptions.UserProperties = new List<MqttUserProperty>();
|
||||
}
|
||||
|
||||
_subscribeOptions.UserProperties.Add(new MqttUserProperty(name, value));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientSubscribeOptionsBuilder WithSubscriptionIdentifier(uint? subscriptionIdentifier)
|
||||
{
|
||||
_subscribeOptions.SubscriptionIdentifier = subscriptionIdentifier;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientSubscribeOptionsBuilder WithTopicFilter(
|
||||
string topic,
|
||||
MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
|
||||
bool? noLocal = null,
|
||||
bool? retainAsPublished = null,
|
||||
MqttRetainHandling? retainHandling = null)
|
||||
{
|
||||
return WithTopicFilter(new TopicFilter
|
||||
{
|
||||
Topic = topic,
|
||||
QualityOfServiceLevel = qualityOfServiceLevel,
|
||||
NoLocal = noLocal,
|
||||
RetainAsPublished = retainAsPublished,
|
||||
RetainHandling = retainHandling
|
||||
});
|
||||
}
|
||||
|
||||
public MqttClientSubscribeOptionsBuilder WithTopicFilter(Action<TopicFilterBuilder> topicFilterBuilder)
|
||||
{
|
||||
if (topicFilterBuilder == null) throw new ArgumentNullException(nameof(topicFilterBuilder));
|
||||
|
||||
var internalTopicFilterBuilder = new TopicFilterBuilder();
|
||||
topicFilterBuilder(internalTopicFilterBuilder);
|
||||
|
||||
return WithTopicFilter(internalTopicFilterBuilder);
|
||||
}
|
||||
|
||||
public MqttClientSubscribeOptionsBuilder WithTopicFilter(TopicFilterBuilder topicFilterBuilder)
|
||||
{
|
||||
if (topicFilterBuilder == null) throw new ArgumentNullException(nameof(topicFilterBuilder));
|
||||
|
||||
return WithTopicFilter(topicFilterBuilder.Build());
|
||||
}
|
||||
|
||||
public MqttClientSubscribeOptionsBuilder WithTopicFilter(TopicFilter topicFilter)
|
||||
{
|
||||
if (topicFilter == null) throw new ArgumentNullException(nameof(topicFilter));
|
||||
|
||||
if (_subscribeOptions.TopicFilters == null)
|
||||
{
|
||||
_subscribeOptions.TopicFilters = new List<TopicFilter>();
|
||||
}
|
||||
|
||||
_subscribeOptions.TopicFilters.Add(topicFilter);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MqttClientSubscribeOptions Build()
|
||||
{
|
||||
return _subscribeOptions;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Collections.Generic;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace MQTTnet.Exceptions
|
||||
{
|
||||
public class MqttUnexpectedDisconnectReceivedException : MqttCommunicationException
|
||||
{
|
||||
public MqttUnexpectedDisconnectReceivedException(MqttDisconnectPacket disconnectPacket)
|
||||
: base($"Unexpected DISCONNECT (Reason code={disconnectPacket.ReasonCode}) received.")
|
||||
{
|
||||
ReasonCode = disconnectPacket.ReasonCode;
|
||||
SessionExpiryInterval = disconnectPacket.Properties?.SessionExpiryInterval;
|
||||
ReasonString = disconnectPacket.Properties?.ReasonString;
|
||||
ServerReference = disconnectPacket.Properties?.ServerReference;
|
||||
UserProperties = disconnectPacket.Properties?.UserProperties;
|
||||
}
|
||||
|
||||
public MqttDisconnectReasonCode? ReasonCode { get; }
|
||||
|
||||
public uint? SessionExpiryInterval { get; }
|
||||
|
||||
public string ReasonString { get; }
|
||||
|
||||
public List<MqttUserProperty> UserProperties { get; }
|
||||
|
||||
public string ServerReference { get; }
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ using MQTTnet.Client.Publishing;
|
||||
using MQTTnet.Client.Subscribing;
|
||||
using MQTTnet.Client.Unsubscribing;
|
||||
using MQTTnet.Packets;
|
||||
using MQTTnet.Server;
|
||||
using MqttClientSubscribeResult = MQTTnet.Client.Subscribing.MqttClientSubscribeResult;
|
||||
|
||||
namespace MQTTnet.Formatter
|
||||
{
|
||||
@@ -20,6 +22,8 @@ namespace MQTTnet.Formatter
|
||||
|
||||
MqttConnectPacket CreateConnectPacket(MqttApplicationMessage willApplicationMessage, IMqttClientOptions options);
|
||||
|
||||
MqttConnAckPacket CreateConnAckPacket(MqttConnectionValidatorContext connectionValidatorContext);
|
||||
|
||||
MqttClientSubscribeResult CreateClientSubscribeResult(MqttSubscribePacket subscribePacket, MqttSubAckPacket subAckPacket);
|
||||
|
||||
MqttClientUnsubscribeResult CreateClientUnsubscribeResult(MqttUnsubscribePacket unsubscribePacket, MqttUnsubAckPacket unsubAckPacket);
|
||||
|
||||
@@ -4,9 +4,9 @@ namespace MQTTnet.Formatter
|
||||
{
|
||||
public interface IMqttPacketBodyReader
|
||||
{
|
||||
ulong Length { get; }
|
||||
int Length { get; }
|
||||
|
||||
ulong Offset { get; }
|
||||
int Offset { get; }
|
||||
|
||||
bool EndOfStream { get; }
|
||||
|
||||
@@ -26,6 +26,6 @@ namespace MQTTnet.Formatter
|
||||
|
||||
bool ReadBoolean();
|
||||
|
||||
void Seek(ulong position);
|
||||
void Seek(int position);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,16 +5,25 @@
|
||||
int Length { get; }
|
||||
|
||||
void WriteWithLengthPrefix(string value);
|
||||
void Write(byte returnCode);
|
||||
void WriteWithLengthPrefix(byte[] payload);
|
||||
void Write(ushort keepAlivePeriod);
|
||||
|
||||
void Write(IMqttPacketWriter propertyWriter);
|
||||
void WriteVariableLengthInteger(uint length);
|
||||
void Write(byte[] payload, int v, int length);
|
||||
void Reset(int v);
|
||||
void Seek(int v);
|
||||
void Write(byte value);
|
||||
|
||||
void WriteWithLengthPrefix(byte[] value);
|
||||
|
||||
void Write(ushort value);
|
||||
|
||||
void Write(IMqttPacketWriter value);
|
||||
|
||||
void WriteVariableLengthInteger(uint value);
|
||||
|
||||
void Write(byte[] value, int offset, int length);
|
||||
|
||||
void Reset(int length);
|
||||
|
||||
void Seek(int offset);
|
||||
|
||||
void FreeBuffer();
|
||||
|
||||
byte[] GetBuffer();
|
||||
}
|
||||
}
|
||||
|
||||