diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuFraming.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuFraming.cs
index bec5055d3..704abdc0c 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuFraming.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuFraming.cs
@@ -93,6 +93,14 @@ public static class ModbusRtuFraming
/// it after the CRC passes; a mismatch is a unit-mismatch desync.
///
/// A token to cancel the read.
+ ///
+ /// The request PDU this response answers (#1029). When supplied, the reply's function code (an exception
+ /// frame's masked code too) must equal the request's, and a write echo (FC 05/06/0F/10) must echo the
+ /// request's start address — RTU has no transaction id, so a CRC-valid reply from the right unit that
+ /// answers a DIFFERENT request is otherwise indistinguishable. A mismatch is a
+ /// desync.
+ /// keeps the unit-only validation (framing tests that have no request).
+ ///
/// The bare response PDU (function code followed by its data).
///
/// The frame was truncated (stream closed mid-frame), its trailing CRC did not validate, or its
@@ -102,7 +110,7 @@ public static class ModbusRtuFraming
/// The frame was a CRC-valid Modbus exception PDU (high bit set on the function code).
///
public static async Task ReadResponsePduAsync(
- Stream stream, byte expectedUnit, CancellationToken ct)
+ Stream stream, byte expectedUnit, CancellationToken ct, byte[]? requestPdu = null)
{
// R07:L5: the whole frame is read into ONE pooled buffer and validated in place; only the returned PDU is
// allocated (it used to be five arrays: header, byteCount, rest, the reassembled frame and the PDU).
@@ -137,7 +145,7 @@ public static class ModbusRtuFraming
}
await ReadExactlyAsync(stream, frame.AsMemory(already, length - already), ct).ConfigureAwait(false);
- return ValidateAndStrip(expectedUnit, frame.AsSpan(0, length));
+ return ValidateAndStrip(expectedUnit, frame.AsSpan(0, length), requestPdu);
}
finally
{
@@ -150,7 +158,7 @@ public static class ModbusRtuFraming
/// against and strips addr + CRC to return the bare PDU.
/// A CRC-valid exception PDU throws .
///
- private static byte[] ValidateAndStrip(byte expectedUnit, ReadOnlySpan frame)
+ private static byte[] ValidateAndStrip(byte expectedUnit, ReadOnlySpan frame, byte[]? requestPdu)
{
// CRC covers everything except the trailing 2 CRC bytes.
var body = frame[..^2];
@@ -173,6 +181,8 @@ public static class ModbusRtuFraming
// Bare PDU = frame minus leading addr and trailing CRC.
var pdu = body[1..].ToArray();
+ if (requestPdu is { Length: > 0 }) CorrelateWithRequest(requestPdu, pdu);
+
// Exception PDU: high bit set on the function code. The CRC already validated, so this is a
// coherent protocol-level error — surface the ORIGINAL function code (fc & 0x7F).
if ((pdu[0] & 0x80) != 0)
@@ -185,6 +195,30 @@ public static class ModbusRtuFraming
return pdu;
}
+ ///
+ /// #1029: checks a CRC-valid, correctly-addressed reply against the request it must answer. Runs BEFORE the
+ /// exception-PDU throw, so a stale exception reply for another function is a desync, not a
+ /// attributed to this request.
+ ///
+ private static void CorrelateWithRequest(byte[] request, byte[] response)
+ {
+ var requestFc = request[0];
+ var responseFc = (byte)(response[0] & 0x7F);
+ if (responseFc != requestFc)
+ throw new ModbusTransportDesyncException(
+ ModbusTransportDesyncException.DesyncReason.ResponseMismatch,
+ $"Modbus RTU response function code 0x{response[0]:X2} does not answer the request (fc 0x{requestFc:X2})");
+
+ // A write reply echoes the start address (bytes 1-2 of the PDU). The exception frame has no address.
+ if ((response[0] & 0x80) == 0
+ && requestFc is 0x05 or 0x06 or 0x0F or 0x10
+ && request.Length >= 3 && response.Length >= 3
+ && (request[1] != response[1] || request[2] != response[2]))
+ throw new ModbusTransportDesyncException(
+ ModbusTransportDesyncException.DesyncReason.ResponseMismatch,
+ $"Modbus RTU write echo address {(response[1] << 8) | response[2]} does not match the request's {(request[1] << 8) | request[2]}");
+ }
+
///
/// Fills completely from , throwing a
/// truncation desync if the stream ends first. Mirrors
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuOverTcpTransport.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuOverTcpTransport.cs
index fefb3e250..2dcc59e35 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuOverTcpTransport.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuOverTcpTransport.cs
@@ -178,7 +178,7 @@ public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
// Framing owns the length-less RTU deframe + CRC + unit-address validation. A CRC-valid
// exception PDU throws ModbusException (socket still coherent — propagates, no teardown);
// truncation / CRC / unit-mismatch throw ModbusTransportDesyncException.
- return await ModbusRtuFraming.ReadResponsePduAsync(stream, unitId, cts.Token).ConfigureAwait(false);
+ return await ModbusRtuFraming.ReadResponsePduAsync(stream, unitId, cts.Token, pdu).ConfigureAwait(false);
}
catch (ModbusTransportDesyncException)
{
@@ -204,7 +204,12 @@ public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
// 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);
+ // A caller cancel is OUR abandonment, not a link fault: with auto-reconnect off it still owes one redial (#1055).
+ if (_life is not null)
+ {
+ if (ex is OperationCanceledException) await _life.DiscardAsync().ConfigureAwait(false);
+ else await _life.TearDownAsync().ConfigureAwait(false);
+ }
throw;
}
finally
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusSocketLifecycle.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusSocketLifecycle.cs
index 3cb4fe82e..c8092c1b3 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusSocketLifecycle.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusSocketLifecycle.cs
@@ -146,9 +146,21 @@ public sealed class ModbusSocketLifecycle : IAsyncDisposable
public async Task EnsureConnectedAsync(CancellationToken ct)
{
if (_stream is not null) return;
+ var redialAfterDiscard = _redialAfterDiscard;
+ _redialAfterDiscard = false;
if (!_autoReconnect)
- throw new ModbusTransportUnavailableException(
- $"Modbus transport to {_host}:{_port} is not connected and auto-reconnect is disabled");
+ {
+ if (!redialAfterDiscard)
+ throw new ModbusTransportUnavailableException(
+ $"Modbus transport to {_host}:{_port} is not connected and auto-reconnect is disabled");
+
+ // #1055: the socket was discarded by US (a caller-cancelled RTU transaction), not lost to a fault —
+ // one fresh dial is owed even with auto-reconnect off, otherwise a single unsubscribe/probe cancel
+ // would leave the transport dead until the 90 s comms-loss watchdog re-initialised the driver. A
+ // failed dial just throws; the allowance is spent, so a dead device stays "not connected".
+ await ConnectAsync(ct).ConfigureAwait(false);
+ return;
+ }
var now = NowMs();
if (now < _connectNotBeforeMs)
@@ -198,6 +210,21 @@ public sealed class ModbusSocketLifecycle : IAsyncDisposable
/// Records that a transaction just succeeded, resetting the idle-disconnect clock.
public void MarkSuccess() => _lastSuccessUtc = DateTime.UtcNow;
+ // Guarded by the composing transport's single-flight gate, like the throttle state above.
+ private bool _redialAfterDiscard;
+
+ ///
+ /// Discards the current socket because THIS side abandoned a transaction (a caller cancel with a reply possibly in
+ /// flight) — not because the link failed. Unlike it grants the next
+ /// exactly one dial even when auto-reconnect is disabled (#1055).
+ ///
+ /// A task representing the asynchronous teardown operation.
+ public async Task DiscardAsync()
+ {
+ await TearDownAsync().ConfigureAwait(false);
+ _redialAfterDiscard = true;
+ }
+
/// Tears down the current socket + stream, leaving the lifecycle ready to reconnect.
/// A task representing the asynchronous teardown operation.
public async Task TearDownAsync()
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusTransportDesyncException.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusTransportDesyncException.cs
index 8a4bd31b0..5c95e9797 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusTransportDesyncException.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusTransportDesyncException.cs
@@ -42,6 +42,12 @@ public sealed class ModbusTransportDesyncException : IOException
/// RS-485 multi-drop bus, a reply from the wrong slave.
///
UnitMismatch,
+
+ ///
+ /// A CRC-valid reply from the addressed unit answered a different request than the one in flight — its
+ /// function code (or, for a write echo, its start address) differs from the request's (#1029).
+ ///
+ ResponseMismatch,
}
/// Gets the reason the socket was classified desynchronized.
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusCallerCancelDesyncTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusCallerCancelDesyncTests.cs
index c7bf2fcd5..bb322c3ed 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusCallerCancelDesyncTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusCallerCancelDesyncTests.cs
@@ -175,4 +175,48 @@ public sealed class ModbusCallerCancelDesyncTests
(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");
}
+
+ ///
+ /// #1055: with auto-reconnect OFF a caller-cancelled RTU transaction used to leave the transport dead (the
+ /// discarded socket was never re-dialled) until the 90 s watchdog re-initialised the driver. The discard was
+ /// ours, so one redial is owed; a real link fault under auto-reconnect OFF must still stay down.
+ ///
+ [Fact]
+ public async Task RtuOverTcp_AutoReconnectOff_caller_cancel_still_redials_for_the_next_read()
+ {
+ 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), autoReconnect: false);
+ 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(first);
+ server.ReleaseFirst();
+
+ (await transport.SendAsync(1, ReadPdu(9), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
+ server.Accepted.ShouldBe(2);
+ }
+
+ [Fact]
+ public async Task RtuOverTcp_AutoReconnectOff_link_fault_stays_down_and_the_cancel_allowance_is_spent_once()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var server = new LateReplyServer(rtu: true);
+ await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5), autoReconnect: false);
+ 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(first);
+
+ // The device goes away: the one owed redial fails, and the next call must fail fast, not dial again.
+ await server.DisposeAsync();
+ await Should.ThrowAsync(transport.SendAsync(1, ReadPdu(9), ct));
+ await Should.ThrowAsync(transport.SendAsync(1, ReadPdu(9), ct));
+ }
}
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusRtuFramingTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusRtuFramingTests.cs
index 6c0849040..fcb8d55fc 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusRtuFramingTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusRtuFramingTests.cs
@@ -104,6 +104,56 @@ public sealed class ModbusRtuFramingTests
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.TruncatedFrame);
}
+ /// #1029: a CRC-valid reply from the right unit that answers a DIFFERENT function is a desync.
+ [Fact]
+ public async Task ReadResponse_response_function_code_not_matching_request_throws_desync()
+ {
+ var frame = ModbusCrc.Append(new byte[] { 0x01, 0x04, 0x02, 0x00, 0x0A }); // an FC04 reply...
+ await using var s = Canned(frame);
+ var ex = await Should.ThrowAsync(
+ ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken,
+ new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 })); // ...to an FC03 request
+ ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
+ }
+
+ /// #1029: a stale exception reply for another function must not become this request's ModbusException.
+ [Fact]
+ public async Task ReadResponse_exception_for_another_function_throws_desync_not_ModbusException()
+ {
+ var frame = ModbusCrc.Append(new byte[] { 0x01, 0x86, 0x02 }); // exception for FC06
+ await using var s = Canned(frame);
+ var ex = await Should.ThrowAsync(
+ ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken,
+ new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }));
+ ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
+ }
+
+ /// #1029: a write echo for another address is a stale reply, not this write's acknowledgement.
+ [Theory]
+ [InlineData((byte)0x06, new byte[] { 0x06, 0x00, 0x08, 0x00, 0x2A })]
+ [InlineData((byte)0x10, new byte[] { 0x10, 0x00, 0x08, 0x00, 0x01 })]
+ public async Task ReadResponse_write_echo_with_other_address_throws_desync(byte fc, byte[] echo)
+ {
+ await using var s = Canned(ModbusCrc.Append(new byte[] { 0x01 }.Concat(echo).ToArray()));
+ var request = new byte[] { fc, 0x00, 0x07, 0x00, 0x2A };
+ var ex = await Should.ThrowAsync(
+ ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken, request));
+ ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
+ }
+
+ /// Positive control for the three above: the matching reply and a matching exception still pass.
+ [Fact]
+ public async Task ReadResponse_matching_request_is_accepted_and_matching_exception_still_surfaces()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ await using (var s = Canned(ModbusCrc.Append(new byte[] { 0x01, 0x06, 0x00, 0x07, 0x00, 0x2A })))
+ (await ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, ct, new byte[] { 0x06, 0x00, 0x07, 0x00, 0x2A }))
+ .ShouldBe(new byte[] { 0x06, 0x00, 0x07, 0x00, 0x2A });
+ await using (var s = Canned(ModbusCrc.Append(new byte[] { 0x01, 0x83, 0x02 })))
+ await Should.ThrowAsync(
+ ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, ct, new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }));
+ }
+
///
/// A read-only test double that dribbles its backing bytes out at most chunk at a time
/// per call, then returns 0 (EOF)
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusRtuOverTcpTransportTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusRtuOverTcpTransportTests.cs
index 2ba1a6228..aa9c9d8bb 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusRtuOverTcpTransportTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusRtuOverTcpTransportTests.cs
@@ -39,6 +39,17 @@ public sealed class ModbusRtuOverTcpTransportTests
TestContext.Current.CancellationToken));
}
+ /// #1029: the transport hands the request PDU to the deframer, so another request's reply is refused.
+ [Fact]
+ public async Task SendAsync_reply_to_a_different_function_is_a_desync()
+ {
+ var fake = new CapturingDuplexStream(ModbusCrc.Append(new byte[] { 0x01, 0x04, 0x02, 0x00, 0x0A }));
+ await using var transport = ModbusRtuOverTcpTransport.ForTest(fake, TimeSpan.FromSeconds(2));
+ var ex = await Should.ThrowAsync(
+ transport.SendAsync(0x01, new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }, TestContext.Current.CancellationToken));
+ ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
+ }
+
[Fact]
public async Task SendAsync_stalled_gateway_hits_per_op_deadline()
{
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ModbusDeployRebuildEndToEndTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ModbusDeployRebuildEndToEndTests.cs
new file mode 100644
index 000000000..d471d6224
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ModbusDeployRebuildEndToEndTests.cs
@@ -0,0 +1,152 @@
+using System.Collections.Concurrent;
+using Akka.Actor;
+using Akka.TestKit;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging.Abstractions;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Commons.Engines;
+using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
+using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
+using ZB.MOM.WW.OtOpcUa.Commons.Types;
+using ZB.MOM.WW.OtOpcUa.Configuration;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+using ZB.MOM.WW.OtOpcUa.Driver.Modbus;
+using ZB.MOM.WW.OtOpcUa.OpcUaServer;
+using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
+using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
+using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
+
+namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
+
+///
+/// #1029 / #981 S-2 end to end: a deploy that fully REBUILDS the address space while a REAL
+/// is kept (its config is untouched) recreates every node at
+/// BadWaitingForInitialData and re-subscribes the driver. The driver's deadband baseline from the earlier
+/// subscription must not swallow the forced first raise, or a tag whose device value is still inside its deadband
+/// (what a deadband is for) stays Bad until the process value drifts. A node-modelling sink stands in for the OPC UA
+/// node manager: it resets every node on rebuild and only a driver publish makes one Good again.
+///
+[Collection("opcua-publish-meters")]
+public sealed class ModbusDeployRebuildEndToEndTests : RuntimeActorTestBase
+{
+ private static readonly NodeId TestNode = NodeId.Parse("node-1:4054");
+ private const string SpeedPath = "Plant/Modbus/dev1/speed";
+ private const uint Good = 0;
+ private const string SpeedTagConfig = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"deadband":5}""";
+
+ private static readonly (string, string, string, string, string, bool)[] Initial =
+ [("drv-1", "Modbus", "dev1", "speed", "Int16", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false)];
+
+ // drv-2's driver folder renamed: a raw CONTAINER rename = full rebuild; drv-1 (the real Modbus driver) is untouched.
+ private static readonly (string, string, string, string, string, bool)[] Renamed =
+ [("drv-1", "Modbus", "dev1", "speed", "Int16", false), ("drv-2", "Modbus2Renamed", "dev2", "pressure", "Float", false)];
+
+ private static RevisionHash Rev(char c) => RevisionHash.Parse(new string(c, 64));
+
+ [Fact]
+ public void A_full_rebuild_with_a_kept_Modbus_driver_leaves_no_deadbanded_node_at_BadWaitingForInitialData()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var db = NewInMemoryDbFactory();
+ var sink = new NodeModelSink();
+ var factory = new KeptModbusFactory();
+ var coordinator = CreateTestProbe();
+ var publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
+ sink: sink, applier: new AddressSpaceApplier(sink, NullLogger.Instance)));
+ var host = Sys.ActorOf(DriverHostActor.Props(
+ db, TestNode, coordinator.Ref, driverFactory: factory,
+ localRoles: new HashSet { "driver" }, dependencyMux: CreateTestProbe().Ref,
+ opcUaPublishActor: publish, virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
+ virtualTagHostOverride: CreateTestProbe().Ref));
+
+ void Deploy((string, string, string, string, string, bool)[] tags, RevisionHash rev)
+ {
+ var id = V3ArtifactSeeder.SeedV3Deployment(db, rev, tags, [], enabled: true,
+ tagConfigByTag: new Dictionary { ["speed"] = SpeedTagConfig },
+ driverConfigByDriver: new Dictionary { ["drv-1"] = """{"host":"fake","probe":{"enabled":false}}""" });
+ host.Tell(new DispatchDeployment(id, rev, CorrelationId.NewId()));
+ var ack = coordinator.FishForMessage(m => m.DeploymentId == id, PresenceBudget, cancellationToken: ct);
+ ack.Outcome.ShouldBe(ApplyAckOutcome.Applied);
+ ack.Degraded.ShouldBeFalse(ack.DegradedReason);
+ }
+
+ Deploy(Initial, Rev('a'));
+ AwaitAssert(() => sink.StatusOf(SpeedPath).ShouldBe(Good, "the first deploy's initial publish; log: " + string.Join(";", sink.Log)), PresenceBudget, cancellationToken: ct);
+ factory.Transport.Reads.ShouldBeGreaterThan(0);
+
+ // Same device value (inside the 5-unit deadband); the rebuild resets the node and the kept driver is re-subscribed.
+ Deploy(Renamed, Rev('b'));
+ sink.RebuildCount.ShouldBe(1, "the container rename must be a full rebuild");
+ AwaitAssert(() => sink.StatusOf(SpeedPath).ShouldBe(Good,
+ "the rebuilt node must receive the kept driver's first raise, not stay BadWaitingForInitialData"),
+ PresenceBudget, cancellationToken: ct);
+ factory.Created.ShouldBe(1, "the Modbus driver must have been KEPT across the rebuild, not respawned");
+ }
+
+ private sealed class ConstantTransport : IModbusTransport
+ {
+ private int _reads;
+ public int Reads => Volatile.Read(ref _reads);
+ public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
+ public Task SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
+ {
+ Interlocked.Increment(ref _reads);
+ return Task.FromResult(new byte[] { 3, 2, 0, 100 }); // register = 100, forever
+ }
+ public ValueTask DisposeAsync() => ValueTask.CompletedTask;
+ }
+
+ /// Materialises ONE real Modbus driver for drv-1 (deadband 5); everything else is a recording stub.
+ private sealed class KeptModbusFactory : IDriverFactory
+ {
+ private readonly RecordingSubscribableDriverFactory _others = new("Modbus");
+ private int _created;
+ public ConstantTransport Transport { get; } = new();
+ public ModbusDriver? Driver;
+ public int Created => Volatile.Read(ref _created);
+
+ public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson)
+ {
+ if (driverInstanceId != "drv-1") return _others.TryCreate(driverType, driverInstanceId, driverConfigJson);
+ Interlocked.Increment(ref _created);
+ // The deploy folds the artifact's raw tags + driver config into driverConfigJson and the driver re-parses it at
+ // Initialize, so only the TRANSPORT is injected here.
+ return Driver = new ModbusDriver(new ModbusDriverOptions { Host = "fake" }, driverInstanceId, _ => Transport);
+ }
+
+ public IReadOnlyCollection SupportedTypes => ["Modbus"];
+ }
+
+ /// Models node status: a created/rebuilt variable is BadWaitingForInitialData until a value is written.
+ private sealed class NodeModelSink : IOpcUaAddressSpaceSink
+ {
+ private const uint BadWaiting = 0x80320000;
+ private readonly ConcurrentDictionary _status = new();
+ public int RebuildCount;
+ public ConcurrentQueue Log = new();
+
+ public uint StatusOf(string nodeId) => _status.TryGetValue(nodeId, out var s) ? s : uint.MaxValue;
+
+ public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm = AddressSpaceRealm.Uns)
+ {
+ Log.Enqueue($"W {nodeId} {statusCode:X}");
+ if (_status.ContainsKey(nodeId)) _status[nodeId] = statusCode; // writes are non-creating, like the real node manager
+ }
+ public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { }
+ public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime occurredUtc, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
+ public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { }
+ public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
+ public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) =>
+ LogAndAdd(variableNodeId);
+ private void LogAndAdd(string id) { Log.Enqueue("E " + id); _status.TryAdd(id, BadWaiting); }
+ public void RebuildAddressSpace()
+ {
+ Interlocked.Increment(ref RebuildCount);
+ _status.Clear();
+ }
+ public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
+ public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
+ public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
+ }
+}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs
index 632bf0e5f..cd65aa1d0 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs
@@ -55,6 +55,8 @@ public static class V3ArtifactSeeder
/// hand that child an explicit EMPTY set rather than skipping it.
/// Optional Equipment VirtualTags (#995): each gets its own script row with
/// Source as its body; EquipmentId must name a seeded equipment (EQ-{area}-{line}-{equip}).
+ /// Optional DriverConfig JSON per driver id (the deploy folds the raw
+ /// tags into it); absent ids keep "{}".
/// The seeded deployment's id.
public static DeploymentId SeedV3Deployment(
IDbContextFactory db, RevisionHash rev,
@@ -64,15 +66,17 @@ public static class V3ArtifactSeeder
IReadOnlyDictionary? tagConfigByTag = null,
string[]? taglessDrivers = null,
IReadOnlyDictionary? driverRowIds = null,
- (string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null)
+ (string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null,
+ IReadOnlyDictionary? driverConfigByDriver = null)
{
+ string ConfigOf(string id) => driverConfigByDriver is not null && driverConfigByDriver.TryGetValue(id, out var c) ? c : "{}";
Guid RowId(string id) => driverRowIds is not null && driverRowIds.TryGetValue(id, out var g) ? g : Guid.Empty;
var drivers = rawTags
.Select(t => (t.Driver, t.DriverName))
.Distinct()
- .Select(d => new { DriverInstanceRowId = RowId(d.Driver), DriverInstanceId = d.Driver, RawFolderId = "rf-plant", Name = d.DriverName, DriverType = "Modbus", DriverConfig = "{}", ClusterId = "c1", Enabled = enabled })
+ .Select(d => new { DriverInstanceRowId = RowId(d.Driver), DriverInstanceId = d.Driver, RawFolderId = "rf-plant", Name = d.DriverName, DriverType = "Modbus", DriverConfig = ConfigOf(d.Driver), ClusterId = "c1", Enabled = enabled })
.Concat((taglessDrivers ?? Array.Empty())
- .Select(id => new { DriverInstanceRowId = RowId(id), DriverInstanceId = id, RawFolderId = "rf-plant", Name = id, DriverType = "Modbus", DriverConfig = "{}", ClusterId = "c1", Enabled = enabled }))
+ .Select(id => new { DriverInstanceRowId = RowId(id), DriverInstanceId = id, RawFolderId = "rf-plant", Name = id, DriverType = "Modbus", DriverConfig = ConfigOf(id), ClusterId = "c1", Enabled = enabled }))
.ToArray();
var devices = rawTags
.Select(t => (t.Driver, t.Device))