fix(modbus): #1029 RTU reply must answer its request (FC + write-echo address); e2e rebuild-with-kept-driver; #1055 AutoReconnect=false redials once after a caller-cancel discard
#1029: ModbusRtuFraming.ReadResponsePduAsync takes the request PDU and refuses a CRC-valid, right-unit reply whose function code (exception frames included) or write-echo start address differs (new DesyncReason.ResponseMismatch). Runtime.Tests e2e: a full rebuild with a kept real ModbusDriver (deadbanded tag, same device value) leaves no node at BadWaitingForInitialData; falsified by removing the S-2 baseline clear. V3ArtifactSeeder gained driverConfigByDriver. #1055 (Modbus half): the RTU transport's caller-cancel teardown now grants ONE redial even with AutoReconnect=false, so an unsubscribe/probe cancel no longer leaves the transport dead until the 90 s watchdog re-init; a link fault still stays down. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -93,6 +93,14 @@ public static class ModbusRtuFraming
|
||||
/// it after the CRC passes; a mismatch is a unit-mismatch desync.
|
||||
/// </param>
|
||||
/// <param name="ct">A token to cancel the read.</param>
|
||||
/// <param name="requestPdu">
|
||||
/// 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
|
||||
/// <see cref="ModbusTransportDesyncException.DesyncReason.ResponseMismatch"/> desync. <see langword="null"/>
|
||||
/// keeps the unit-only validation (framing tests that have no request).
|
||||
/// </param>
|
||||
/// <returns>The bare response PDU (function code followed by its data).</returns>
|
||||
/// <exception cref="ModbusTransportDesyncException">
|
||||
/// 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).
|
||||
/// </exception>
|
||||
public static async Task<byte[]> 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 <paramref name="expectedUnit"/> and strips <c>addr</c> + <c>CRC</c> to return the bare PDU.
|
||||
/// A CRC-valid exception PDU throws <see cref="ModbusException"/>.
|
||||
/// </summary>
|
||||
private static byte[] ValidateAndStrip(byte expectedUnit, ReadOnlySpan<byte> frame)
|
||||
private static byte[] ValidateAndStrip(byte expectedUnit, ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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
|
||||
/// <see cref="ModbusException"/> attributed to this request.
|
||||
/// </summary>
|
||||
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]}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills <paramref name="buf"/> completely from <paramref name="stream"/>, throwing a
|
||||
/// truncation desync if the stream ends first. Mirrors
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
/// <summary>Records that a transaction just succeeded, resetting the idle-disconnect clock.</summary>
|
||||
public void MarkSuccess() => _lastSuccessUtc = DateTime.UtcNow;
|
||||
|
||||
// Guarded by the composing transport's single-flight gate, like the throttle state above.
|
||||
private bool _redialAfterDiscard;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="TearDownAsync"/> it grants the next
|
||||
/// <see cref="EnsureConnectedAsync"/> exactly one dial even when auto-reconnect is disabled (#1055).
|
||||
/// </summary>
|
||||
/// <returns>A task representing the asynchronous teardown operation.</returns>
|
||||
public async Task DiscardAsync()
|
||||
{
|
||||
await TearDownAsync().ConfigureAwait(false);
|
||||
_redialAfterDiscard = true;
|
||||
}
|
||||
|
||||
/// <summary>Tears down the current socket + stream, leaving the lifecycle ready to reconnect.</summary>
|
||||
/// <returns>A task representing the asynchronous teardown operation.</returns>
|
||||
public async Task TearDownAsync()
|
||||
|
||||
@@ -42,6 +42,12 @@ public sealed class ModbusTransportDesyncException : IOException
|
||||
/// RS-485 multi-drop bus, a reply from the wrong slave.
|
||||
/// </summary>
|
||||
UnitMismatch,
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
ResponseMismatch,
|
||||
}
|
||||
|
||||
/// <summary>Gets the reason the socket was classified desynchronized.</summary>
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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.
|
||||
/// </summary>
|
||||
[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<OperationCanceledException>(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<OperationCanceledException>(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<SocketException>(transport.SendAsync(1, ReadPdu(9), ct));
|
||||
await Should.ThrowAsync<ModbusTransportUnavailableException>(transport.SendAsync(1, ReadPdu(9), ct));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,56 @@ public sealed class ModbusRtuFramingTests
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.TruncatedFrame);
|
||||
}
|
||||
|
||||
/// <summary>#1029: a CRC-valid reply from the right unit that answers a DIFFERENT function is a desync.</summary>
|
||||
[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<ModbusTransportDesyncException>(
|
||||
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken,
|
||||
new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 })); // ...to an FC03 request
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
|
||||
}
|
||||
|
||||
/// <summary>#1029: a stale exception reply for another function must not become this request's ModbusException.</summary>
|
||||
[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<ModbusTransportDesyncException>(
|
||||
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken,
|
||||
new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }));
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
|
||||
}
|
||||
|
||||
/// <summary>#1029: a write echo for another address is a stale reply, not this write's acknowledgement.</summary>
|
||||
[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<ModbusTransportDesyncException>(
|
||||
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken, request));
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
|
||||
}
|
||||
|
||||
/// <summary>Positive control for the three above: the matching reply and a matching exception still pass.</summary>
|
||||
[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<ModbusException>(
|
||||
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, ct, new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A read-only test double that dribbles its backing bytes out at most <c>chunk</c> at a time
|
||||
/// per <see cref="ReadAsync(Memory{byte}, CancellationToken)"/> call, then returns 0 (EOF)
|
||||
|
||||
@@ -39,6 +39,17 @@ public sealed class ModbusRtuOverTcpTransportTests
|
||||
TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>#1029: the transport hands the request PDU to the deframer, so another request's reply is refused.</summary>
|
||||
[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<ModbusTransportDesyncException>(
|
||||
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()
|
||||
{
|
||||
|
||||
+152
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// #1029 / #981 S-2 end to end: a deploy that fully REBUILDS the address space while a REAL
|
||||
/// <see cref="ModbusDriver"/> is kept (its config is untouched) recreates every node at
|
||||
/// <c>BadWaitingForInitialData</c> 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.
|
||||
/// </summary>
|
||||
[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<AddressSpaceApplier>.Instance)));
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(
|
||||
db, TestNode, coordinator.Ref, driverFactory: factory,
|
||||
localRoles: new HashSet<string> { "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<string, string> { ["speed"] = SpeedTagConfig },
|
||||
driverConfigByDriver: new Dictionary<string, string> { ["drv-1"] = """{"host":"fake","probe":{"enabled":false}}""" });
|
||||
host.Tell(new DispatchDeployment(id, rev, CorrelationId.NewId()));
|
||||
var ack = coordinator.FishForMessage<ApplyAck>(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<byte[]> 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;
|
||||
}
|
||||
|
||||
/// <summary>Materialises ONE real Modbus driver for drv-1 (deadband 5); everything else is a recording stub.</summary>
|
||||
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<string> SupportedTypes => ["Modbus"];
|
||||
}
|
||||
|
||||
/// <summary>Models node status: a created/rebuilt variable is BadWaitingForInitialData until a value is written.</summary>
|
||||
private sealed class NodeModelSink : IOpcUaAddressSpaceSink
|
||||
{
|
||||
private const uint BadWaiting = 0x80320000;
|
||||
private readonly ConcurrentDictionary<string, uint> _status = new();
|
||||
public int RebuildCount;
|
||||
public ConcurrentQueue<string> 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<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
|
||||
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,8 @@ public static class V3ArtifactSeeder
|
||||
/// hand that child an explicit EMPTY set rather than skipping it.</param>
|
||||
/// <param name="virtualTags">Optional Equipment VirtualTags (#995): each gets its own script row with
|
||||
/// <c>Source</c> as its body; <c>EquipmentId</c> must name a seeded equipment (<c>EQ-{area}-{line}-{equip}</c>).</param>
|
||||
/// <param name="driverConfigByDriver">Optional <c>DriverConfig</c> JSON per driver id (the deploy folds the raw
|
||||
/// tags into it); absent ids keep <c>"{}"</c>.</param>
|
||||
/// <returns>The seeded deployment's id.</returns>
|
||||
public static DeploymentId SeedV3Deployment(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev,
|
||||
@@ -64,15 +66,17 @@ public static class V3ArtifactSeeder
|
||||
IReadOnlyDictionary<string, string>? tagConfigByTag = null,
|
||||
string[]? taglessDrivers = null,
|
||||
IReadOnlyDictionary<string, Guid>? driverRowIds = null,
|
||||
(string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null)
|
||||
(string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null,
|
||||
IReadOnlyDictionary<string, string>? 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<string>())
|
||||
.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))
|
||||
|
||||
Reference in New Issue
Block a user