-
Notifications
You must be signed in to change notification settings - Fork 1.1k
[WotCon] Add the HTTP, Modbus, OPC UA and MQTT binding executors #4144
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
marcschier
merged 172 commits into
marcschier/wot-11-bindings-core
from
marcschier/wot-12-executors
Aug 5, 2026
Merged
Changes from 33 commits
Commits
Show all changes
172 commits
Select commit
Hold shift + click to select a range
e417f55
Merge branch 'marcschier/wot-01-core-types' into marcschier/wot-15-cl…
marcschier b55fff4
Merge branch 'marcschier/wot-09-xregistry-client' into marcschier/wot…
marcschier 2803016
Add the WoT Connectivity registry client
marcschier 0cf6722
Add the HTTP, Modbus, OPC UA and MQTT binding executors
marcschier d76e581
Restore WoT Connectivity test project coverage
marcschier 2ea8965
Merge remote-tracking branch 'origin/marcschier/wot-10-wotcon-model' …
marcschier 1405aae
Merge branch 'marcschier/wot-10-wotcon-model' into marcschier/wot-13-…
marcschier e5f9da3
Merge remote-tracking branch 'origin/marcschier/wot-10-wotcon-model' …
marcschier 6b5d58d
Add the WoT Connectivity registry and its stores
marcschier ed6c93d
Add the fluent builder API the generated node managers require
marcschier c3a12ba
Add the fluent builder API the generated node managers require
marcschier 729d7ff
Add the fluent builder API the generated node managers require
marcschier 74b09c4
Wire the data-type lookup into the DI node manager builder
marcschier 1c60fb6
Wire the data-type lookup into the DI node manager builder
marcschier 442e023
Wire the data-type lookup into the DI node manager builder
marcschier cd04abc
Merge branch 'marcschier/wot-10-wotcon-model' into marcschier/wot-15-…
marcschier d72e973
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier e72d784
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-13…
marcschier 6ab4635
Fix WoT registry review issues
marcschier 47dd8ba
Apply an endpoint policy before opening a WoT binding channel
marcschier b48558b
Harden WoT binding executor sinks
marcschier 2ac7f7e
Re-apply the endpoint policy to every HTTP redirect hop
marcschier 3cf4ada
Merge branch 'marcschier/wot-10-wotcon-model' into marcschier/wot-15-…
marcschier d07786a
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier 61c346e
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-13…
marcschier ed86073
Merge branch 'marcschier/wot-10-wotcon-model' into marcschier/wot-15-…
marcschier 32d6f19
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier 415da4c
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-13…
marcschier d35bb31
Use ImmutableDictionary.Empty instead of a collection expression
marcschier 1e9c38c
Merge remote-tracking branch 'origin/marcschier/wot-05-lifecycle' int…
marcschier 61c6544
Merge remote-tracking branch 'origin/marcschier/wot-01-core-types' in…
marcschier a3ff604
Materialize WoT Thing Descriptions into the server address space
marcschier 689e194
Add WoT registry materialization tests
marcschier b2bf36f
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 2e0202c
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier 81d77a7
Register the MQTT binding project in the solution
marcschier 61093c2
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-13…
marcschier 9c1b75d
Merge branch 'marcschier/wot-13-registry' into marcschier/wot-14-mate…
marcschier 35df526
Merge branch 'marcschier/wot-14-materialization' into marcschier/wot-…
marcschier 4ce3d98
Merge branch 'marcschier/wot-12-executors' into marcschier/wot-16-sam…
marcschier 7567c9e
Add the WoT Connectivity samples and complete the documentation
marcschier 5c0006b
Add the remaining WoT binding and aggregation tests
marcschier 1018d78
Cover the DI transfer service binding extensions
marcschier 67307b1
Cover the registry client error and configuration paths
marcschier 3846fec
Merge branch 'marcschier/wot-10-wotcon-model' into marcschier/wot-15-…
marcschier f01902f
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier 9d44482
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-13…
marcschier 45689f9
Merge branch 'marcschier/wot-13-registry' into marcschier/wot-14-mate…
marcschier 22f7486
Merge branch 'marcschier/wot-05-lifecycle' into marcschier/wot-14-mat…
marcschier 15aedb2
Merge branch 'marcschier/wot-01-core-types' into marcschier/wot-14-ma…
marcschier 588799c
Merge branch 'marcschier/wot-14-materialization' into marcschier/wot-…
marcschier 0845948
Merge branch 'marcschier/wot-15-client' into marcschier/wot-16-samples
marcschier 95bead1
Merge branch 'marcschier/wot-12-executors' into marcschier/wot-16-sam…
marcschier 02473dd
Adapt WoT server methods to typed generated signatures
marcschier 7a2074e
Merge branch 'marcschier/wot-13-registry' into marcschier/wot-14-mate…
marcschier 507f750
Merge branch 'marcschier/wot-14-materialization' into marcschier/wot-…
marcschier b155e9c
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier b3b2ead
Merge wot-12-executors and retire IAtomicFileReplace
marcschier cd84294
Merge branch 'marcschier/wot-15-client' into marcschier/wot-14-materi…
marcschier 237c7d0
Merge branch 'marcschier/wot-13-registry' into marcschier/wot-15-client
marcschier 777e0a8
Merge branch 'marcschier/wot-15-client' into marcschier/wot-14-materi…
marcschier 9e5c9c5
Merge branch 'marcschier/wot-14-materialization' into marcschier/wot-…
marcschier 1387294
Merge branch 'marcschier/wot-15-client' into marcschier/wot-14-materi…
marcschier 9bce9c4
Merge branch 'marcschier/wot-14-materialization' into marcschier/wot-…
marcschier 523d7a8
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier 099ea11
Merge branch 'marcschier/wot-12-executors' into marcschier/wot-13-reg…
marcschier e19f175
Merge branch 'marcschier/wot-13-registry' into marcschier/wot-15-client
marcschier cd61d63
Merge branch 'marcschier/wot-15-client' into marcschier/wot-14-materi…
marcschier b3f594d
Merge branch 'marcschier/wot-14-materialization' into marcschier/wot-…
marcschier f53ceac
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier fbbb2f1
Merge branch 'marcschier/wot-11-bindings-core' into marcschier/wot-12…
marcschier 588a285
Merge branch 'marcschier/wot-12-executors' into marcschier/wot-13-reg…
marcschier 72d3395
Merge branch 'marcschier/wot-13-registry' into marcschier/wot-15-client
marcschier ce7dc6f
Merge branch 'marcschier/wot-15-client' into marcschier/wot-14-materi…
marcschier b9ddcb1
Merge branch 'marcschier/wot-14-materialization' into marcschier/wot-…
marcschier c2d5d16
Merge branch 'marcschier/wot-12-executors' into marcschier/wot-13-reg…
marcschier 6b1a93a
Merge branch 'marcschier/wot-13-registry' into marcschier/wot-15-client
marcschier cdc7064
Merge branch 'marcschier/wot-15-client' into marcschier/wot-14-materi…
marcschier 30d4259
Merge branch 'marcschier/wot-14-materialization' into marcschier/wot-…
marcschier 7abd67c
Address WoT registry review feedback
marcschier 36c3389
Address WoT materialization review feedback
marcschier 3966144
Address WoT samples review feedback
marcschier 5f19e8d
Address WoT executor review feedback
marcschier b3daa1c
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 8369ec8
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier c3ee677
Pass the executor telemetry context into polling subscriptions
marcschier 3ab37a1
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 316e93e
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier f0a69ad
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 182d905
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 01d58cb
Allow loopback endpoints in the aggregation sample
marcschier ae8e063
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier facc3b7
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier d614cc6
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 237730a
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier eaa7081
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 0c47b37
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier f60d0d0
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 3f38a12
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 571eaf4
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 598644f
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 74d2b90
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier ee1b4b9
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 980e346
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier eca062a
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 27ba9cd
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier bb60d87
Align the new WoT documentation links
marcschier fff8967
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 50c75d1
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 78b423f
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 7fc33ad
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 478110f
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 234130b
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 4347581
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier dc75d48
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 7498344
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier f093746
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier bf45718
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 3ea8430
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 6653b40
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 54a6f73
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 7b00194
Treat the registry management minimum security mode as a floor
marcschier 4fc98de
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 7f5cca0
Keep WoT materialization dry runs side-effect free
marcschier 828f6bd
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier a9a1239
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 6aeca99
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 66fe980
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 5a1aca1
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 8e101d0
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 7c29fe5
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier d4e3ffb
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 7c24898
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 76498d8
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier f643291
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 20db0ad
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier eba74e5
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier c63d712
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier a3eae58
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier a238381
Fix WoT materialization shutdown ordering
marcschier 9edb995
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 98a5070
Skip projection lifecycle removal during shutdown
marcschier b139d1a
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier aed8d5d
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier ec9586e
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 4df8cbc
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier ab8c175
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier f1993c9
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 668f84d
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 605dda4
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 07b4b83
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 33c2900
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 0377e13
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier 3d6b808
Pass an explicit caller context to the NodeManager lifecycle
marcschier 39f5042
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier cd5b72c
Pass an explicit caller context in the WoT live server tests
marcschier 16cf27f
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 7ae2e9c
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 01df322
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier cb6d517
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 0726236
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier a3cb074
Restore WoT asset registry bridge (#4171)
marcschier c68fc3c
Merge remote-tracking branch 'origin/marcschier/wot-11-bindings-core'…
marcschier 89ebba8
Merge remote-tracking branch 'origin/marcschier/wot-12-executors' int…
marcschier 9f4c9f8
Merge remote-tracking branch 'origin/marcschier/wot-13-registry' into…
marcschier 6d7bd53
Merge remote-tracking branch 'origin/marcschier/wot-15-client' into m…
marcschier 58f0f9f
Merge remote-tracking branch 'origin/marcschier/wot-14-materializatio…
marcschier e41c0e3
Merge remote-tracking branch 'origin/marcschier/wot-16-samples' into …
marcschier 39f655f
[WotCon] Add the WoT Connectivity samples and complete the documentat…
marcschier b6ac567
[WotCon] Materialize WoT Thing Descriptions into the server address s…
marcschier 3388cf5
[WotCon] Add the WoT Connectivity registry client (#4142)
marcschier e8ac13a
[WotCon] Add the WoT Connectivity registry and its stores (#4146)
marcschier File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
386 changes: 386 additions & 0 deletions
386
src/Opc.Ua.WotCon.Bindings.Mqtt/MqttWotBindingChannel.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,386 @@ | ||
| /* ======================================================================== | ||
| * Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved. | ||
| * | ||
| * OPC Foundation MIT License 1.00 | ||
| * | ||
| * Permission is hereby granted, free of charge, to any person | ||
| * obtaining a copy of this software and associated documentation | ||
| * files (the "Software"), to deal in the Software without | ||
| * restriction, including without limitation the rights to use, | ||
| * copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| * copies of the Software, and to permit persons to whom the | ||
| * Software is furnished to do so, subject to the following | ||
| * conditions: | ||
| * | ||
| * The above copyright notice and this permission notice shall be | ||
| * included in all copies or substantial portions of the Software. | ||
| * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | ||
| * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | ||
| * NONINFRINGEMENT. IN NO EVENT SHALL THE 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. | ||
| * | ||
| * The complete license agreement can be found here: | ||
| * http://opcfoundation.org/License/MIT/1.00/ | ||
| * ======================================================================*/ | ||
|
|
||
| using System; | ||
| using System.Buffers; | ||
| using System.Collections.Generic; | ||
| using System.Globalization; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using MQTTnet; | ||
| using MQTTnet.Exceptions; | ||
| using MQTTnet.Protocol; | ||
|
|
||
| namespace Opc.Ua.WotCon.Bindings.Mqtt | ||
| { | ||
| /// <summary> | ||
| /// A live MQTT binding channel that publishes writes / actions and subscribes | ||
| /// for reads / observes / events per the pinned MQTT binding, with bounded QoS, | ||
| /// payload sizes and read timeouts. | ||
| /// </summary> | ||
| internal sealed class MqttWotBindingChannel : IWotBindingChannel | ||
| { | ||
| public MqttWotBindingChannel( | ||
| IMqttClient client, | ||
| WotCompiledForm form, | ||
| WotExecutorContext context, | ||
| MqttWotBindingOptions options) | ||
| { | ||
| m_client = client; | ||
| Form = form; | ||
| m_options = options; | ||
| m_bounds = context.Bounds; | ||
| m_topic = form.Addressing.Target; | ||
| m_qos = ParseQos(form.Addressing.Metadata); | ||
| m_retain = ParseBool(form.Addressing.Metadata, "retain"); | ||
| context.Codecs.TrySelect(form.Payload.ContentType, out m_codec); | ||
| m_client.ApplicationMessageReceivedAsync += OnMessageAsync; | ||
| } | ||
|
|
||
| public WotCompiledForm Form { get; } | ||
|
|
||
| public async ValueTask<WotReadResult> ReadAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| var completion = new TaskCompletionSource<byte[]>(TaskCreationOptions.RunContinuationsAsynchronously); | ||
| if (Interlocked.CompareExchange(ref m_pendingRead, completion, null) is not null) | ||
| { | ||
| var exception = new ServiceResultException( | ||
| StatusCodes.BadInvalidState, | ||
| "An MQTT read is already pending on this channel."); | ||
| completion.SetCanceled(CancellationToken.None); | ||
| throw exception; | ||
| } | ||
| using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); | ||
| timeout.CancelAfter(m_options.ReadTimeout); | ||
| try | ||
| { | ||
| await SubscribeAsync(cancellationToken).ConfigureAwait(false); | ||
| byte[] payload = await completion.Task.WaitAsync(timeout.Token).ConfigureAwait(false); | ||
| WotDecodeResult decoded = m_codec.Decode(payload, Form.Payload); | ||
| if (!decoded.Success) | ||
| { | ||
| return new WotReadResult( | ||
| StatusCodes.BadDecodingError, | ||
| DataValue.FromStatusCode(StatusCodes.BadDecodingError), | ||
| decoded.Error); | ||
| } | ||
| return new WotReadResult( | ||
| StatusCodes.Good, new DataValue(decoded.Value, StatusCodes.Good, DateTimeUtc.Now, DateTimeUtc.Now)); | ||
| } | ||
| catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) | ||
| { | ||
| completion.TrySetCanceled(timeout.Token); | ||
| return new WotReadResult( | ||
| StatusCodes.BadTimeout, DataValue.FromStatusCode(StatusCodes.BadTimeout), | ||
| "Timed out waiting for an MQTT message."); | ||
| } | ||
| catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) | ||
| { | ||
| completion.TrySetCanceled(cancellationToken); | ||
| throw; | ||
| } | ||
| catch | ||
| { | ||
| completion.TrySetCanceled(CancellationToken.None); | ||
| throw; | ||
| } | ||
| finally | ||
| { | ||
| Interlocked.CompareExchange(ref m_pendingRead, null, completion); | ||
| if (!m_observing) | ||
| { | ||
| await TryUnsubscribeAsync().ConfigureAwait(false); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public async ValueTask<WotWriteResult> WriteAsync( | ||
| DataValue value, CancellationToken cancellationToken = default) | ||
| { | ||
| WotEncodeResult encoded = m_codec.Encode(value.WrappedValue, Form.Payload); | ||
| if (!encoded.Success) | ||
| { | ||
| return new WotWriteResult(StatusCodes.BadEncodingError, encoded.Error); | ||
| } | ||
| try | ||
| { | ||
| await PublishAsync(encoded.Data.ToArray(), cancellationToken).ConfigureAwait(false); | ||
| return new WotWriteResult(StatusCodes.Good); | ||
| } | ||
| catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) | ||
| { | ||
| return new WotWriteResult(StatusCodes.BadTimeout, "The MQTT publish timed out."); | ||
| } | ||
| catch (ArgumentException ex) | ||
| { | ||
| return new WotWriteResult(StatusCodes.BadInvalidArgument, ex.Message); | ||
| } | ||
| catch (MqttCommunicationException ex) | ||
| { | ||
| return new WotWriteResult(StatusCodes.BadCommunicationError, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| public async ValueTask<WotInvokeResult> InvokeAsync( | ||
| IReadOnlyList<Variant> inputs, CancellationToken cancellationToken = default) | ||
| { | ||
| byte[] payload = []; | ||
| if (inputs is { Count: > 0 }) | ||
| { | ||
| WotEncodeResult encoded = m_codec.Encode(inputs[0], Form.Payload); | ||
| if (!encoded.Success) | ||
| { | ||
| return new WotInvokeResult(StatusCodes.BadEncodingError, null, encoded.Error); | ||
| } | ||
| payload = encoded.Data.ToArray(); | ||
| } | ||
| try | ||
| { | ||
| await PublishAsync(payload, cancellationToken).ConfigureAwait(false); | ||
| return new WotInvokeResult(StatusCodes.Good, []); | ||
| } | ||
| catch (MqttCommunicationException ex) | ||
| { | ||
| return new WotInvokeResult(StatusCodes.BadCommunicationError, null, ex.Message); | ||
| } | ||
| catch (ArgumentException ex) | ||
| { | ||
| return new WotInvokeResult(StatusCodes.BadInvalidArgument, null, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| [System.Diagnostics.CodeAnalysis.SuppressMessage( | ||
| "Reliability", "CA2000:Dispose objects before losing scope", | ||
| Justification = "Ownership of the subscription is transferred to the caller, who disposes it.")] | ||
| public async ValueTask<IWotSubscription> ObserveAsync( | ||
| Action<WotNotification> onNotification, CancellationToken cancellationToken = default) | ||
| { | ||
| if (onNotification is null) | ||
| { | ||
| throw new ArgumentNullException(nameof(onNotification)); | ||
| } | ||
| lock (m_lock) | ||
| { | ||
| m_handlers.Add(onNotification); | ||
| m_observing = true; | ||
| } | ||
| try | ||
| { | ||
| await SubscribeAsync(cancellationToken).ConfigureAwait(false); | ||
| } | ||
| catch | ||
| { | ||
| RemoveHandler(onNotification); | ||
| throw; | ||
| } | ||
| return new HandlerSubscription(this, onNotification); | ||
| } | ||
|
|
||
| public ValueTask<IWotSubscription> SubscribeEventAsync( | ||
| Action<WotNotification> onEvent, CancellationToken cancellationToken = default) | ||
| { | ||
| return ObserveAsync(onEvent, cancellationToken); | ||
| } | ||
|
|
||
| public async ValueTask DisposeAsync() | ||
| { | ||
| m_client.ApplicationMessageReceivedAsync -= OnMessageAsync; | ||
| try | ||
| { | ||
| await m_client.DisconnectAsync(new MqttClientDisconnectOptionsBuilder().Build()) | ||
| .ConfigureAwait(false); | ||
| } | ||
| catch (MqttCommunicationException) | ||
| { | ||
| // Ignore disconnect faults during teardown. | ||
| } | ||
| m_client.Dispose(); | ||
| } | ||
|
|
||
| private Task OnMessageAsync(MqttApplicationMessageReceivedEventArgs args) | ||
| { | ||
| byte[] payload = ToArray(args.ApplicationMessage.Payload); | ||
| TaskCompletionSource<byte[]>? pending = Interlocked.Exchange(ref m_pendingRead, null); | ||
| pending?.TrySetResult(payload); | ||
|
|
||
| Action<WotNotification>[] handlers; | ||
| lock (m_lock) | ||
| { | ||
| if (m_handlers.Count == 0) | ||
| { | ||
| return Task.CompletedTask; | ||
| } | ||
| handlers = [.. m_handlers]; | ||
| } | ||
| WotDecodeResult decoded = m_codec.Decode(payload, Form.Payload); | ||
| if (decoded.Success) | ||
| { | ||
| var notification = new WotNotification( | ||
| new DataValue(decoded.Value, StatusCodes.Good, DateTimeUtc.Now, DateTimeUtc.Now)); | ||
| foreach (Action<WotNotification> handler in handlers) | ||
| { | ||
| handler(notification); | ||
| } | ||
| } | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| private async Task SubscribeAsync(CancellationToken cancellationToken) | ||
| { | ||
| ValidateSubscribeTopic(); | ||
| MqttClientSubscribeOptions options = new MqttClientSubscribeOptionsBuilder() | ||
| .WithTopicFilter(m_topic, m_qos) | ||
| .Build(); | ||
| await m_client.SubscribeAsync(options, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
marcschier marked this conversation as resolved.
|
||
|
|
||
| private async Task TryUnsubscribeAsync() | ||
| { | ||
| try | ||
| { | ||
| MqttClientUnsubscribeOptions options = new MqttClientUnsubscribeOptionsBuilder() | ||
| .WithTopicFilter(m_topic) | ||
| .Build(); | ||
| await m_client.UnsubscribeAsync(options).ConfigureAwait(false); | ||
| } | ||
| catch (MqttCommunicationException) | ||
| { | ||
| // Ignore unsubscribe faults. | ||
| } | ||
| } | ||
|
|
||
| private async Task PublishAsync(byte[] payload, CancellationToken cancellationToken) | ||
| { | ||
| if (ContainsMqttWildcard(m_topic)) | ||
| { | ||
| throw new ArgumentException("MQTT publish topics must not contain wildcard characters."); | ||
| } | ||
| MqttApplicationMessage message = new MqttApplicationMessageBuilder() | ||
| .WithTopic(m_topic) | ||
| .WithPayload(payload) | ||
| .WithQualityOfServiceLevel(m_qos) | ||
| .WithRetainFlag(m_retain) | ||
| .Build(); | ||
| await m_client.PublishAsync(message, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| private void ValidateSubscribeTopic() | ||
| { | ||
| WotBindingBounds.EnsurePositive(m_bounds.MaxTopicLength, nameof(WotBindingBounds.MaxTopicLength)); | ||
| if (m_topic.Length > m_bounds.MaxTopicLength) | ||
| { | ||
| throw new ServiceResultException( | ||
| StatusCodes.BadOutOfRange, | ||
| $"The MQTT subscribe topic exceeds the maximum length of {m_bounds.MaxTopicLength}."); | ||
| } | ||
| if (!m_bounds.AllowMqttWildcardTopics && ContainsMqttWildcard(m_topic)) | ||
| { | ||
| throw new ServiceResultException( | ||
| StatusCodes.BadInvalidArgument, | ||
| "MQTT subscribe topics must not contain wildcard characters unless explicitly allowed."); | ||
| } | ||
| } | ||
|
|
||
| private void RemoveHandler(Action<WotNotification> handler) | ||
| { | ||
| lock (m_lock) | ||
| { | ||
| m_handlers.Remove(handler); | ||
| m_observing = m_handlers.Count > 0; | ||
| } | ||
| } | ||
|
|
||
| private static byte[] ToArray(ReadOnlySequence<byte> payload) | ||
| { | ||
| return payload.IsEmpty ? [] : payload.ToArray(); | ||
| } | ||
|
|
||
| private static bool ContainsMqttWildcard(string topic) | ||
| { | ||
| return topic.Contains('#', StringComparison.Ordinal) || topic.Contains('+', StringComparison.Ordinal); | ||
| } | ||
|
|
||
| private static MqttQualityOfServiceLevel ParseQos( | ||
| System.Collections.Immutable.ImmutableDictionary<string, string> metadata) | ||
| { | ||
| if (metadata.TryGetValue("qos", out string? value) && | ||
| int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int qos)) | ||
| { | ||
| return qos switch | ||
| { | ||
| 1 => MqttQualityOfServiceLevel.AtLeastOnce, | ||
| 2 => MqttQualityOfServiceLevel.ExactlyOnce, | ||
| _ => MqttQualityOfServiceLevel.AtMostOnce | ||
| }; | ||
| } | ||
| return MqttQualityOfServiceLevel.AtMostOnce; | ||
| } | ||
|
|
||
| private static bool ParseBool( | ||
| System.Collections.Immutable.ImmutableDictionary<string, string> metadata, string key) | ||
| { | ||
| return metadata.TryGetValue(key, out string? value) && bool.TryParse(value, out bool result) && result; | ||
| } | ||
|
|
||
| private sealed class HandlerSubscription : IWotSubscription | ||
| { | ||
| public HandlerSubscription(MqttWotBindingChannel channel, Action<WotNotification> handler) | ||
| { | ||
| m_channel = channel; | ||
| m_handler = handler; | ||
| } | ||
|
|
||
| public WotCompiledForm Form => m_channel.Form; | ||
|
|
||
| public async ValueTask DisposeAsync() | ||
| { | ||
| m_channel.RemoveHandler(m_handler); | ||
| if (!m_channel.m_observing) | ||
| { | ||
| await m_channel.TryUnsubscribeAsync().ConfigureAwait(false); | ||
| } | ||
| } | ||
|
|
||
| private readonly MqttWotBindingChannel m_channel; | ||
| private readonly Action<WotNotification> m_handler; | ||
| } | ||
|
|
||
| private readonly IMqttClient m_client; | ||
| private readonly MqttWotBindingOptions m_options; | ||
| private readonly WotBindingBounds m_bounds; | ||
| private readonly string m_topic; | ||
| private readonly MqttQualityOfServiceLevel m_qos; | ||
| private readonly bool m_retain; | ||
| private readonly IWotPayloadCodec m_codec; | ||
| private readonly Lock m_lock = new(); | ||
| private readonly List<Action<WotNotification>> m_handlers = []; | ||
| private volatile bool m_observing; | ||
| private TaskCompletionSource<byte[]>? m_pendingRead; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.