Merge #981: Modbus RTU cancel no longer desyncs, re-subscribe publishes initial value, DL205 rejects non-octal

This commit is contained in:
Joseph Doherty
2026-12-03 09:42:45 -05:00
7 changed files with 298 additions and 6 deletions
+3 -2
View File
@@ -32,7 +32,7 @@ history capability; history is server-side.)
| `ITagDiscovery` | `DiscoverAsync` | Emits one `Modbus/{tag}` variable per pre-declared tag; Modbus has no browse protocol, so the driver returns exactly the configured `Tags`. |
| `IReadable` | `ReadAsync` → `ReadOneAsync` / `ReadCoalescedAsync` | FC01/FC02 for coils, FC03/FC04 for registers; auto-chunks reads past the per-device cap. |
| `IWritable` | `WriteAsync` → `WriteOneAsync` | FC05/FC15 for coils, FC06/FC16 for registers; `BitInRegister` writes do a per-register read-modify-write under a lock. `DiscreteInputs` / `InputRegisters` are read-only and return `BadNotWritable`. |
| `ISubscribable` | `SubscribeAsync` driven by the shared `PollGroupEngine` | No native push — subscriptions become per-tag polling groups with an optional per-tag `Deadband` filter. |
| `ISubscribable` | `SubscribeAsync` driven by the shared `PollGroupEngine` | No native push — subscriptions become per-tag polling groups with an optional per-tag `Deadband` filter. Each (re)subscribe forgets the deadband baselines of its references so its forced initial publish is never suppressed (#981). |
| `IHostConnectivityProbe` | `ProbeLoopAsync` + `GetHostStatuses` | Periodic cheap FC03 at `Probe.ProbeAddress`; `HostName` is the `Host:Port` string surfaced to the Admin UI. |
| `IPerCallHostResolver` | `ResolveHost` | Routes each call to a per-slave breaker key (`Host:Port/unit{UnitId}`) so a dead RTU slave behind a multi-unit gateway opens its own breaker. |
@@ -68,7 +68,7 @@ appear across consecutive registers when decoding a multi-register value.
(`ModbusFamily`):
- **`Generic`** (default) — only Modicon (`4xxxx`) and mnemonic (`HR1`, `C100`) forms are accepted.
- **`DL205`** — AutomationDirect DirectLOGIC. V-memory (octal) → HoldingRegisters, `Y`/`C` → Coils, `X`/`SP` → DiscreteInputs. Strings can be packed low-byte-first via `ModbusTagDefinition.StringByteOrder` (the grammar can't express this — see `ModbusStringByteOrder`).
- **`DL205`** — AutomationDirect DirectLOGIC. V-memory (octal) → HoldingRegisters, `Y`/`C` → Coils, `X`/`SP` → DiscreteInputs. A `C` relay with a non-octal digit (`C18`) is a parse error - it never falls back to the generic `C<n>` coil mnemonic (#981). Strings can be packed low-byte-first via `ModbusTagDefinition.StringByteOrder` (the grammar can't express this — see `ModbusStringByteOrder`).
- **`MELSEC`** — Mitsubishi. D-registers → HoldingRegisters, `X` → DiscreteInputs, `Y`/`M` → Coils; the `MelsecSubFamily` selector switches Q/L/iQR (hex) vs FX (octal) X/Y interpretation.
Per-family register caps are honoured through `MaxRegistersPerRead` /
@@ -97,6 +97,7 @@ from the driver's `DriverConfig` JSON. Key fields:
- **Endpoint** — `Host`, `Port` (default 502), `UnitId`, `Timeout`. Per-tag `UnitId` overrides drive multi-slave gateway topology.
- **`Transport`** — `Tcp` (default; MBAP header + transaction id) or `RtuOverTcp` (RTU `[addr][PDU][CRC-16]` framing tunnelled over the socket to a serial-to-Ethernet gateway); string-valued, absent = `Tcp`. The Test Connect probe follows the authored mode.
RTU carries no transaction id, so the transport discards the socket on ANY exit after the request was written without a complete validated reply - a caller cancellation (unsubscribe, probe timeout) included (#981); otherwise the late reply would answer the next request at Good.
- **`Tags`** — the pre-declared `ModbusTagDefinition` list; this *is* the address space.
- **`Probe`** — connectivity-probe interval / timeout / probe register (default register 0).
- **Read/write caps** — `MaxRegistersPerRead` (125), `MaxRegistersPerWrite` (123), `MaxCoilsPerRead` (2000), plus `MaxReadGap` and `AutoProhibitReprobeInterval` for coalescing.
@@ -268,7 +268,14 @@ public static class ModbusAddressParser
// Try mnemonic prefix first (HR, IR, C, DI). Cheaper than the digit branch and
// unambiguous when present.
if (TryParseMnemonicAddress(addrText, out region, out offset, out error))
//
// #981 / S-8: ONLY when no family grammar claimed the address. A non-Generic family that recognised the
// prefix and then rejected the body (DL205 "C18": a control relay with a non-octal digit) has already said
// what is wrong; falling through to the generic table resolved "C18" as Modbus coil 18 — a silently
// DIFFERENT memory area on a writable tag. `C` (and MELSEC `D…`/`DI…`) are the prefixes the two grammars
// share. The digit-only Modicon fallback below cannot collide (a family prefix is a letter) and stays.
if (familyNativeError is null
&& TryParseMnemonicAddress(addrText, out region, out offset, out error))
return true;
// Fall back to Modicon (5/6-digit). Reuses the shared Modicon parser.
@@ -2018,7 +2018,22 @@ public sealed class ModbusDriver
/// <inheritdoc />
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken) =>
Task.FromResult(_poll.Subscribe(fullReferences, publishingInterval));
Task.FromResult(SubscribeForgettingBaselines(fullReferences, publishingInterval));
/// <summary>
/// #981 / S-2: a (re)subscribe's forced first raise must reach the consumer. The deadband baseline is
/// keyed by tag reference only, so a baseline left by an EARLIER subscription (a full rebuild keeps the
/// driver, recreates every node at <c>BadWaitingForInitialData</c> and re-subscribes) would suppress that
/// first raise for any tag still inside its deadband, stranding the new node Bad. Drop the baselines for
/// these references BEFORE the engine starts polling them. A second live subscription sharing a
/// reference merely publishes once more — over-publishing is safe, suppression is the defect.
/// </summary>
private ISubscriptionHandle SubscribeForgettingBaselines(
IReadOnlyList<string> fullReferences, TimeSpan interval, Action<IReadOnlyList<DataChangeItem>>? onAcquired = null)
{
foreach (var r in fullReferences) _lastPublishedByRef.TryRemove(r, out _);
return onAcquired is null ? _poll.Subscribe(fullReferences, interval) : _poll.Subscribe(fullReferences, interval, onAcquired);
}
/// <inheritdoc />
/// <remarks>The polling engine uses a bounded drain during teardown. Consumers must fence late
@@ -2038,7 +2053,7 @@ public sealed class ModbusDriver
throw new ArgumentOutOfRangeException(nameof(request), "Revision and producer incarnation must be positive.");
cancellationToken.ThrowIfCancellationRequested();
var handle = _poll.Subscribe(request.FullReferences, request.RequestedSamplingInterval,
var handle = SubscribeForgettingBaselines(request.FullReferences, request.RequestedSamplingInterval,
items => onAcquired(new AcquisitionBatch(request.DesiredRevision, request.ProducerIncarnation, items)));
if (cancellationToken.IsCancellationRequested)
{
@@ -30,7 +30,8 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// frozen gateway can never wedge a poll: the deadline firing is normalised to a
/// <see cref="ModbusTransportDesyncException"/> and tears the socket down so the next attempt
/// reconnects. A <b>caller</b> cancellation is distinguished from that timeout and propagates
/// as a plain <see cref="OperationCanceledException"/> with no teardown.
/// as a plain <see cref="OperationCanceledException"/>, but it too tears the socket down (#981: the reply
/// may still be in flight and, without a transaction id, would answer the next request).
/// </para>
/// <para>
/// The constructor is connection-free; all socket I/O happens in <see cref="ConnectAsync"/> /
@@ -195,6 +196,17 @@ public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
ModbusTransportDesyncException.DesyncReason.Timeout,
$"Modbus per-op response timeout after {_timeout.TotalMilliseconds:0}ms");
}
catch (Exception ex) when (ex is not ModbusException)
{
// #981 / S-1: ANY other exit after the request was written without a complete, validated reply — a
// CALLER cancellation (unsubscribe cancels the poll token mid-read; the probe's linked token) or a
// socket error — leaves the device's reply possibly in flight. RTU has no transaction id, so the next
// request on this socket would read that stale reply as its own answer (valid CRC, same unit) and
// publish it Good. Discard the socket; the next call re-dials. A ModbusException is a CRC-valid
// exception PDU: the frame was fully consumed, the socket is coherent, so it is excluded.
if (_life is not null) await _life.TearDownAsync().ConfigureAwait(false);
throw;
}
finally
{
// The write has completed, or was cancelled and the stream torn down, so nothing still reads it.
@@ -171,6 +171,37 @@ public sealed class ModbusFamilyParserTests
p.Offset.ShouldBe((ushort)99);
}
/// <summary>
/// #981 / S-8: under DL205 a `C` address is an OCTAL control relay. A non-octal body (8/9) is an error —
/// it must NOT fall through to the generic `C&lt;n&gt;` coil mnemonic and resolve a different coil.
/// </summary>
/// <param name="addr">A DL205 control-relay address carrying a non-octal digit.</param>
[Theory]
[InlineData("C18")]
[InlineData("C9")]
[InlineData("c1280")]
public void DL205_ControlRelay_With_NonOctal_Digit_Is_An_Error_Not_A_Generic_Coil(string addr)
{
ModbusAddressParser.TryParse(addr, ModbusFamily.DL205, MelsecFamily.Q_L_iQR, out var result, out var error)
.ShouldBeFalse($"'{addr}' must not resolve to a generic coil under DL205");
result.ShouldBeNull();
error.ShouldNotBeNull();
error.ShouldContain("octal", Case.Insensitive);
}
/// <summary>S-8 positive controls: a valid octal relay still resolves natively; Generic still reads C18 as coil 17.</summary>
[Fact]
public void DL205_ValidOctal_ControlRelay_Still_Resolves_And_Generic_C18_Is_Coil_17()
{
var relay = ModbusAddressParser.Parse("C17", ModbusFamily.DL205);
relay.Region.ShouldBe(ModbusRegion.Coils);
relay.Offset.ShouldBe((ushort)(DirectLogicAddress.CRelayBaseCoil + 15)); // octal 17 = 15
var generic = ModbusAddressParser.Parse("C18", ModbusFamily.Generic);
generic.Region.ShouldBe(ModbusRegion.Coils);
generic.Offset.ShouldBe((ushort)17);
}
/// <summary>Verifies suffix grammar composes correctly with native addresses.</summary>
[Fact]
public void Suffix_Grammar_Composes_With_Native_Address()
@@ -0,0 +1,178 @@
using System.Net;
using System.Net.Sockets;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
/// <summary>
/// #981 / S-1 — a CALLER-cancelled transaction must never leave its reply in flight on a reused socket.
/// RTU has no transaction id, so a late reply would be read as the NEXT request's answer and published at
/// Good; the plain TCP transport matches transaction ids, but a cancel mid-frame can still leave half a
/// frame buffered. Both transports therefore discard the socket on any exit after the request was written
/// without a complete validated reply. Real loopback sockets: the teardown is only observable there.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusCallerCancelDesyncTests
{
/// <summary>
/// Loopback device. The reply to request index 0 is withheld until <see cref="ReleaseFirst"/>; every
/// other request is answered immediately. An FC03 reply carries the requested start address as its
/// single register value, so a test can tell WHOSE reply it received. Speaks RTU or MBAP framing.
/// </summary>
private sealed class LateReplyServer : IAsyncDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly CancellationTokenSource _stop = new();
private readonly TaskCompletionSource _firstReceived = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource _releaseFirst = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly bool _rtu;
private int _requests;
private int _accepted;
public LateReplyServer(bool rtu)
{
_rtu = rtu;
_listener.Start();
_ = Task.Run(AcceptLoopAsync);
}
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
public int Accepted => Volatile.Read(ref _accepted);
public Task FirstReceived => _firstReceived.Task;
public void ReleaseFirst() => _releaseFirst.TrySetResult();
private async Task AcceptLoopAsync()
{
while (!_stop.IsCancellationRequested)
{
TcpClient client;
try { client = await _listener.AcceptTcpClientAsync(_stop.Token); }
catch { return; }
Interlocked.Increment(ref _accepted);
_ = Task.Run(() => ServeAsync(client));
}
}
private async Task ServeAsync(TcpClient client)
{
using var _ = client;
try
{
var s = client.GetStream();
while (!_stop.IsCancellationRequested)
{
// RTU request: unit, FC, addr(2), qty(2), crc(2) = 8. MBAP: 7-byte header + 5-byte PDU.
var req = new byte[_rtu ? 8 : 12];
if (!await ReadExactly(s, req)) return;
var idx = Interlocked.Increment(ref _requests) - 1;
var pduOffset = _rtu ? 1 : 7;
var addr = (ushort)((req[pduOffset + 1] << 8) | req[pduOffset + 2]);
if (idx == 0)
{
_firstReceived.TrySetResult();
await _releaseFirst.Task.WaitAsync(_stop.Token);
}
var pdu = new byte[] { 0x03, 0x02, (byte)(addr >> 8), (byte)addr };
byte[] reply;
if (_rtu)
{
reply = ModbusCrc.Append(new byte[] { req[0] }.Concat(pdu).ToArray());
}
else
{
reply = new byte[7 + pdu.Length];
Array.Copy(req, reply, 4); // TxId + protocol id
reply[5] = (byte)(1 + pdu.Length);
reply[6] = req[6];
Array.Copy(pdu, 0, reply, 7, pdu.Length);
}
await s.WriteAsync(reply, _stop.Token);
await s.FlushAsync(_stop.Token);
}
}
catch { /* connection torn down */ }
}
private static async Task<bool> ReadExactly(NetworkStream s, byte[] buf)
{
var read = 0;
while (read < buf.Length)
{
var n = await s.ReadAsync(buf.AsMemory(read));
if (n == 0) return false;
read += n;
}
return true;
}
public ValueTask DisposeAsync()
{
_stop.Cancel();
_releaseFirst.TrySetResult();
_listener.Stop();
return ValueTask.CompletedTask;
}
}
private static byte[] ReadPdu(ushort addr) => new byte[] { 0x03, (byte)(addr >> 8), (byte)addr, 0x00, 0x01 };
[Fact]
public async Task RtuOverTcp_caller_cancel_mid_transaction_then_next_read_gets_its_own_reply()
{
var ct = TestContext.Current.CancellationToken;
await using var server = new LateReplyServer(rtu: true);
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5));
await transport.ConnectAsync(ct);
using var cancel = new CancellationTokenSource();
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
await cancel.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(first);
// The device answers the cancelled request late; the reply lands in whatever socket the transport kept.
server.ReleaseFirst();
await Task.Delay(200, ct);
var pdu = await transport.SendAsync(1, ReadPdu(9), ct);
pdu.ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 }, "the second read must carry ITS reply (register 9), never the cancelled request's (5)");
server.Accepted.ShouldBe(2, "the cancelled transaction's socket must have been discarded and re-dialled");
}
[Fact]
public async Task Tcp_caller_cancel_mid_transaction_then_next_read_gets_its_own_reply_on_a_fresh_socket()
{
var ct = TestContext.Current.CancellationToken;
await using var server = new LateReplyServer(rtu: false);
await using var transport = new ModbusTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5));
await transport.ConnectAsync(ct);
using var cancel = new CancellationTokenSource();
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
await cancel.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(first);
server.ReleaseFirst();
await Task.Delay(200, ct);
var pdu = await transport.SendAsync(1, ReadPdu(9), ct);
pdu.ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
server.Accepted.ShouldBe(2, "a cancelled in-flight transaction must not leave a half-read/late frame on the reused socket");
}
[Fact]
public async Task RtuOverTcp_uncancelled_reads_reuse_one_socket_positive_control()
{
var ct = TestContext.Current.CancellationToken;
await using var server = new LateReplyServer(rtu: true);
server.ReleaseFirst();
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5));
await transport.ConnectAsync(ct);
(await transport.SendAsync(1, ReadPdu(5), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x05 });
(await transport.SendAsync(1, ReadPdu(9), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
server.Accepted.ShouldBe(1, "the teardown must be tied to the cancelled exit, not to every call");
}
}
@@ -50,4 +50,52 @@ public sealed class ModbusDeadbandRecoveryTests
drv.ShouldPublish("Temp", Snap((short)12, Uncertain)).ShouldBeFalse("within deadband at the same quality");
drv.ShouldPublish("Temp", Snap((short)10, Good)).ShouldBeTrue("back to Good must publish");
}
/// <summary>
/// #981 / S-2: a re-subscribe (a full rebuild keeps the driver and re-subscribes onto fresh nodes at
/// BadWaitingForInitialData) must publish its initial value even when it is inside the deadband of what
/// an EARLIER subscription published. Replays the IDENTICAL device value on purpose.
/// </summary>
[Fact]
public async Task Resubscribe_publishes_the_initial_value_even_inside_the_deadband_of_the_previous_subscription()
{
var ct = TestContext.Current.CancellationToken;
var tag = new ModbusTagDefinition("Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, Deadband: 5.0);
var opts = new ModbusDriverOptions
{
Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false },
};
var fake = new ModbusDriverTests.FakeTransport();
fake.HoldingRegisters[0] = 10;
await using var drv = new ModbusDriver(opts, "m1", _ => fake);
await drv.InitializeAsync("{}", ct);
var changes = new System.Collections.Concurrent.ConcurrentQueue<DataChangeEventArgs>();
var batches = new System.Collections.Concurrent.ConcurrentQueue<DataChangeBatchEventArgs>();
drv.OnDataChange += (_, e) => changes.Enqueue(e);
((IBatchSubscribable)drv).OnDataChangeBatch += (_, e) => batches.Enqueue(e);
static async Task WaitAsync(Func<bool> cond, CancellationToken ct)
{
var until = DateTime.UtcNow.AddSeconds(5);
while (!cond() && DateTime.UtcNow < until) await Task.Delay(20, ct);
cond().ShouldBeTrue("timed out waiting for the initial publish");
}
var first = await drv.SubscribeAsync(["Temp"], TimeSpan.FromMilliseconds(100), ct);
await WaitAsync(() => changes.Any(c => ReferenceEquals(c.SubscriptionHandle, first)) && batches.Any(b => ReferenceEquals(b.SubscriptionHandle, first)), ct);
await drv.UnsubscribeAsync(first, ct);
// Same device value (still inside the deadband) on a brand-new subscription: the initial publish must arrive.
var second = await drv.SubscribeAsync(["Temp"], TimeSpan.FromMilliseconds(100), ct);
await WaitAsync(() => changes.Any(c => ReferenceEquals(c.SubscriptionHandle, second)) && batches.Any(b => ReferenceEquals(b.SubscriptionHandle, second)), ct);
changes.First(c => ReferenceEquals(c.SubscriptionHandle, second)).Snapshot.StatusCode.ShouldBe(Good);
// Positive control: once past the initial raise the deadband still suppresses an in-band drift.
var before = changes.Count(c => ReferenceEquals(c.SubscriptionHandle, second));
fake.HoldingRegisters[0] = 11;
await Task.Delay(400, ct);
changes.Count(c => ReferenceEquals(c.SubscriptionHandle, second)).ShouldBe(before, "the deadband must still apply after the initial raise");
await drv.UnsubscribeAsync(second, ct);
}
}