Merge lane K: clients, CLI, AB transport (#747)

Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 17:38:08 -04:00
53 changed files with 2339 additions and 510 deletions
@@ -0,0 +1,50 @@
using CliFx.Infrastructure;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.AbCip.Cli.Commands;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Cli.Tests;
/// <summary>
/// Review 07 U7: the AbCip probe/read/write commands had no <see cref="OperationCanceledException"/> arm, so a
/// Ctrl-C printed a stack trace. A command cancelled by the operator now exits cleanly with <c>Cancelled.</c>.
/// The gateway is TEST-NET (never answers), so nothing is sent to a real device.
/// </summary>
[Trait("Category", "Unit")]
public sealed class CancellationHandlingTests
{
private const string Blackhole = "ab://192.0.2.1/1,0";
private static async Task<string> RunCancelledAsync(AbCipCommandBase command)
{
using var console = new FakeInMemoryConsole();
console.RequestCancellation();
await Should.NotThrowAsync(async () => await command.ExecuteAsync(console));
return console.ReadErrorString();
}
/// <summary>A cancelled read prints Cancelled. and does not throw.</summary>
[Fact]
public async Task A_cancelled_read_prints_Cancelled()
{
(await RunCancelledAsync(new ReadCommand { Gateway = Blackhole, TagPath = "Motor01" }))
.ShouldContain("Cancelled.");
}
/// <summary>A cancelled probe prints Cancelled. and does not throw.</summary>
[Fact]
public async Task A_cancelled_probe_prints_Cancelled()
{
(await RunCancelledAsync(new ProbeCommand { Gateway = Blackhole, TagPath = "Motor01" }))
.ShouldContain("Cancelled.");
}
/// <summary>A cancelled write prints Cancelled. and does not throw.</summary>
[Fact]
public async Task A_cancelled_write_prints_Cancelled()
{
(await RunCancelledAsync(new WriteCommand { Gateway = Blackhole, TagPath = "Motor01", Value = "1" }))
.ShouldContain("Cancelled.");
}
}
@@ -0,0 +1,111 @@
using System.Text;
using CliFx.Infrastructure;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Cli.Common;
namespace ZB.MOM.WW.OtOpcUa.Driver.Cli.Common.Tests;
/// <summary>
/// Review 07 U7, shared half: arrays render their elements (not <c>System.Int32[]</c>), Ctrl-C prints
/// <c>Cancelled.</c>, and the subscribe change-line writer is serialised and never throws into the poll loop.
/// </summary>
[Trait("Category", "Unit")]
public sealed class CliHelpersU7Tests
{
private sealed record Handle(string DiagnosticId) : ISubscriptionHandle;
private static DataChangeEventArgs Change(string reference, object? value) =>
new(new Handle("h"), reference, new DataValueSnapshot(value, 0u, DateTime.UtcNow, DateTime.UtcNow));
/// <summary>An array value renders as its elements, each formatted like a scalar.</summary>
[Fact]
public void FormatValue_renders_array_elements()
{
SnapshotFormatter.FormatValue(new[] { 1, 2, 3 }).ShouldBe("[1, 2, 3]");
SnapshotFormatter.FormatValue(new[] { 1.5f, -2f }).ShouldBe("[1.5, -2]");
SnapshotFormatter.FormatValue(new[] { true, false }).ShouldBe("[true, false]");
SnapshotFormatter.FormatValue(new[] { "a", "b" }).ShouldBe("[\"a\", \"b\"]");
SnapshotFormatter.FormatValue(new List<short> { 7 }).ShouldBe("[7]");
SnapshotFormatter.FormatValue(Array.Empty<int>()).ShouldBe("[]");
}
/// <summary>A string is still a scalar, not a sequence of chars (positive control for the array arm).</summary>
[Fact]
public void FormatValue_keeps_a_string_scalar()
{
SnapshotFormatter.FormatValue("abc").ShouldBe("\"abc\"");
}
/// <summary>Operator Ctrl-C prints Cancelled. instead of a stack trace.</summary>
[Fact]
public async Task RunCancellableAsync_operator_cancellation_prints_Cancelled()
{
using var console = new FakeInMemoryConsole();
using var cts = new CancellationTokenSource();
cts.Cancel();
await Should.NotThrowAsync(async () =>
await DriverCommandBase.RunCancellableAsync(console, cts.Token, () => Task.FromCanceled(cts.Token)));
console.ReadErrorString().ShouldContain("Cancelled.");
}
/// <summary>A cancellation the operator did not request still propagates.</summary>
[Fact]
public async Task RunCancellableAsync_unrequested_cancellation_propagates()
{
using var console = new FakeInMemoryConsole();
await Should.ThrowAsync<OperationCanceledException>(async () =>
await DriverCommandBase.RunCancellableAsync(console, CancellationToken.None,
() => throw new OperationCanceledException()));
}
/// <summary>A change line carries the reference, the formatted value and the status.</summary>
[Fact]
public void ChangeLineWriter_writes_one_formatted_line_per_change()
{
var output = new StringWriter();
var write = DriverCommandBase.CreateChangeLineWriter(output, new object());
write(this, Change("Tag:DInt", new[] { 4, 5 }));
var line = output.ToString().TrimEnd();
line.ShouldContain("Tag:DInt = [4, 5] (0x00000000 (Good))");
}
/// <summary>Concurrent poll-thread changes produce whole lines, never interleaved fragments.</summary>
[Fact]
public async Task ChangeLineWriter_serialises_concurrent_writes()
{
var output = new StringWriter(new StringBuilder());
var write = DriverCommandBase.CreateChangeLineWriter(output, new object());
await Task.WhenAll(Enumerable.Range(0, 8).Select(t => Task.Run(() =>
{
for (var i = 0; i < 200; i++) write(this, Change($"T{t}", i));
})));
var lines = output.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines.Length.ShouldBe(1600);
lines.ShouldAllBe(l => l.StartsWith('[') && l.EndsWith("(Good))"));
}
/// <summary>A failing console (closed pipe) is swallowed so it cannot fault the driver's poll loop.</summary>
[Fact]
public void ChangeLineWriter_swallows_a_console_write_failure()
{
var write = DriverCommandBase.CreateChangeLineWriter(new ThrowingWriter(), new object());
Should.NotThrow(() => write(this, Change("T", 1)));
}
private sealed class ThrowingWriter : TextWriter
{
public override Encoding Encoding => Encoding.UTF8;
public override void Write(char value) => throw new IOException("pipe closed");
public override void WriteLine(string? value) => throw new IOException("pipe closed");
}
}
@@ -21,10 +21,15 @@ public sealed class AbStatusCodesTests
[InlineData((byte)0x0E, AbStatus.NotAllowed)]
[InlineData((byte)0x1E, AbStatus.BadReply)]
[InlineData((byte)0x01, AbStatus.BadReply)]
[InlineData((byte)0x07, AbStatus.BadReply)] // connection lost: opaque on purpose (AbLegacy #738)
// Lane K F1 (#737): the controller answered and refused this request — not a garbled reply.
[InlineData((byte)0x1C, AbStatus.Unsupported)] // missing attribute list entry data
[InlineData((byte)0x20, AbStatus.Unsupported)] // invalid parameter
public void Cip_general_status_maps(byte general, AbStatus expected) =>
AbStatusCodes.FromCip(general, ReadOnlySpan<ushort>.Empty).ShouldBe(expected);
[Theory]
[InlineData((ushort)0x2104, AbStatus.OutOfBounds)] // offset beyond end of the tag (Lane K F1)
[InlineData((ushort)0x2105, AbStatus.OutOfBounds)]
[InlineData((ushort)0x2107, AbStatus.TypeMismatch)]
[InlineData((ushort)0x9999, AbStatus.BadReply)]
@@ -37,16 +42,42 @@ public sealed class AbStatusCodesTests
[Theory]
[InlineData((byte)0x00, null, AbStatus.Ok)]
[InlineData((byte)0x10, null, AbStatus.Unsupported)]
[InlineData((byte)0x20, null, AbStatus.NotFound)]
[InlineData((byte)0x30, null, AbStatus.NotAllowed)]
[InlineData((byte)0x40, null, AbStatus.DeviceStateConflict)]
[InlineData((byte)0xF0, (byte)0x06, AbStatus.NotFound)]
[InlineData((byte)0xF0, (byte)0x07, AbStatus.NotFound)]
[InlineData((byte)0x10, null, AbStatus.Unsupported)] // illegal command or format
// Lane K F3 (AbLegacy F8, review 07 r0 I4), per the DF1/PCCC STS table (1770-6.5.16):
[InlineData((byte)0x20, null, AbStatus.BadConnection)] // host has a problem and will not communicate
[InlineData((byte)0x30, null, AbStatus.BadConnection)] // remote node host missing / disconnected / shut down
[InlineData((byte)0x40, null, AbStatus.DeviceStateConflict)] // host hardware fault (the host answered)
[InlineData((byte)0x50, null, AbStatus.NotFound)] // addressing problem or memory protect rungs
[InlineData((byte)0x60, null, AbStatus.NotAllowed)] // function not allowed due to command protection
[InlineData((byte)0x70, null, AbStatus.DeviceStateConflict)] // processor is in Program mode
[InlineData((byte)0x80, null, AbStatus.BadReply)] // compatibility-mode file missing: unclassified
[InlineData((byte)0x90, null, AbStatus.BadConnection)] // remote node cannot buffer command
[InlineData((byte)0xB0, null, AbStatus.DeviceStateConflict)] // remote node problem due to download
[InlineData((byte)0xF0, (byte)0x06, AbStatus.NotFound)] // address does not point to something usable
[InlineData((byte)0xF0, (byte)0x07, AbStatus.OutOfBounds)] // file is wrong size
[InlineData((byte)0xF0, (byte)0x0A, AbStatus.BadReply)]
[InlineData((byte)0xF0, null, AbStatus.BadReply)]
public void Pccc_status_maps(byte sts, byte? ext, AbStatus expected) =>
AbStatusCodes.FromPccc(sts, ext).ShouldBe(expected);
/// <summary>
/// A dead DH+/DH-485 node behind a bridge answers STS 0x30 (and a busy one 0x90). Neither proves the END
/// device answered, so they are the no-reply comms class, never one of the "answered" refusals — that
/// classification made such a device count as reachable forever (no backoff, no comms-loss watchdog).
/// </summary>
/// <param name="sts">The PCCC STS byte.</param>
[Theory]
[InlineData((byte)0x20)]
[InlineData((byte)0x30)]
[InlineData((byte)0x90)]
public void Pccc_no_reply_statuses_are_never_answered_refusals(byte sts)
{
var status = AbStatusCodes.FromPccc(sts, null);
status.ShouldBe(AbStatus.BadConnection);
status.ShouldNotBeOneOf(AbStatus.NotFound, AbStatus.NotAllowed, AbStatus.OutOfBounds,
AbStatus.DeviceStateConflict, AbStatus.TooLarge, AbStatus.TooSmall, AbStatus.TypeMismatch);
}
[Fact]
public void Ok_is_zero_and_every_error_is_negative()
{
@@ -115,6 +115,30 @@ public sealed class ConnectionManagerServicesTests
ex.Status.ShouldBe(AbStatus.BadConnection); // general 0x01 has no specific mapping
}
/// <summary>
/// Lane K F1 remapped general 0x1C / 0x20 and 0xFF/0x2104 for TAG requests (a per-request refusal). A Forward
/// Open refused with one of them is still a connection failure, exactly as before: the whole connection is
/// unusable, so it must not read as a per-tag refusal.
/// </summary>
/// <param name="hex">The refused Forward Open reply.</param>
[Theory]
[InlineData("DB001C00")]
[InlineData("DB002000")]
[InlineData("DB00FF010421")]
public void Forward_open_refused_with_a_request_level_status_is_still_BadConnection(string hex)
{
var ex = Should.Throw<ForwardOpenRefusedException>(() =>
ConnectionManagerServices.ParseForwardOpenReply(CipReply.Parse(Convert.FromHexString(hex))));
ex.Status.ShouldBe(AbStatus.BadConnection);
}
/// <summary>Positive control: a Forward Open refusal that was already specifically mapped keeps its status.</summary>
[Fact]
public void Forward_open_refused_service_not_supported_stays_Unsupported() =>
Should.Throw<ForwardOpenRefusedException>(() =>
ConnectionManagerServices.ParseForwardOpenReply(CipReply.Parse(Convert.FromHexString("DB000800"))))
.Status.ShouldBe(AbStatus.Unsupported);
[Fact]
public void Refused_forward_open_exception_is_not_aliased_to_the_reply_array()
{
@@ -90,6 +90,32 @@ public sealed class PcccServicesTests
[Fact]
public void Plc5_write_is_not_shipped_and_flagged() => PcccServices.Plc5WriteVerified.ShouldBeFalse();
// ---- ParseReply: golden STS replies (Lane K F3 / AbLegacy F8) ----
/// <summary>
/// Wire-level golden replies: the Execute PCCC reply bytes a device (or a bridge in front of it) sends for each
/// STS, through <see cref="PcccServices.ParseReply"/>, to the status the drivers classify.
/// </summary>
/// <param name="stsHex">The reply's STS (+ EXT STS) bytes as hex.</param>
/// <param name="expected">The status ParseReply raises.</param>
[Theory]
[InlineData("20", AbStatus.BadConnection)]
[InlineData("30", AbStatus.BadConnection)]
[InlineData("90", AbStatus.BadConnection)]
[InlineData("50", AbStatus.NotFound)]
[InlineData("60", AbStatus.NotAllowed)]
[InlineData("70", AbStatus.DeviceStateConflict)]
[InlineData("B0", AbStatus.DeviceStateConflict)]
[InlineData("F0|06", AbStatus.NotFound)]
[InlineData("F0|07", AbStatus.OutOfBounds)]
public void ParseReply_golden_sts(string stsHex, AbStatus expected)
{
var parts = stsHex.Split('|');
var hex = Id + "4F" + parts[0] + "9987" + (parts.Length > 1 ? parts[1] : "");
Should.Throw<AbTransportException>(() => PcccServices.ParseReply(Reply(hex), 0x8799))
.Status.ShouldBe(expected);
}
// ---- ParseReply ----
private static CipReply Reply(string hex, byte general = 0) =>
new(0x4B, general, [], Hex(hex));
@@ -122,7 +148,23 @@ public sealed class PcccServicesTests
[Fact]
public void ParseReply_cip_error_status_throws() =>
Should.Throw<AbTransportException>(() => PcccServices.ParseReply(Reply("", 0x08), 1)).Status.ShouldBe(AbStatus.Unsupported);
Should.Throw<AbDeviceReplyException>(() => PcccServices.ParseReply(Reply("", 0x08), 1)).Status.ShouldBe(AbStatus.Unsupported);
/// <summary>Review I2: a status the device REPLIED with is marked as such (envelope CIP status and PCCC STS).</summary>
[Fact]
public void ParseReply_marks_device_statuses_as_device_replies()
{
Should.Throw<AbDeviceReplyException>(() => PcccServices.ParseReply(Reply("", 0x20), 1)).Status.ShouldBe(AbStatus.Unsupported);
Should.Throw<AbDeviceReplyException>(() => PcccServices.ParseReply(Reply(Id + "4F10 9987"), 0x8799)).Status.ShouldBe(AbStatus.Unsupported);
}
/// <summary>Positive control: a refusal raised by a builder before anything is sent is NOT a device reply.</summary>
[Fact]
public void A_pre_wire_builder_refusal_is_not_a_device_reply()
{
var ex = Should.Throw<AbTransportException>(() => PcccServices.SlcTypedRead(1, A("N7:0"), 999));
ex.ShouldNotBeOfType<AbDeviceReplyException>();
}
[Fact]
public void ParseReply_wrong_command_byte_is_BadReply() =>
@@ -25,3 +25,60 @@ public sealed class CipWriterTests
w.ToArray().ShouldBe(new byte[] { 0, 0, 7 }); // nothing was patched
}
}
/// <summary>
/// R07:L5: <see cref="CipWriter"/> works in a buffer rented from <see cref="System.Buffers.ArrayPool{T}"/> and hands
/// it back on <see cref="CipWriter.ToArray"/>. The returned array must be the caller's own (a later writer reusing
/// the pooled buffer cannot change it), growth must keep every byte, and a writer used after ToArray must refuse
/// rather than write into a buffer it no longer owns.
/// </summary>
public sealed class CipWriterPoolingTests
{
[Fact]
public void Growth_past_the_initial_buffer_keeps_every_byte()
{
var w = new CipWriter();
for (var i = 0; i < 1000; i++) w.U8((byte)i);
var bytes = w.ToArray();
bytes.Length.ShouldBe(1000);
bytes.Select((b, i) => b == (byte)i).ShouldAllBe(ok => ok);
}
[Fact]
public void A_returned_array_is_not_affected_by_a_later_writer_reusing_the_pooled_buffer()
{
var first = new CipWriter().U32(0xAABBCCDD).ToArray();
for (var i = 0; i < 50; i++) new CipWriter().U32(0x11111111).U32(0x22222222).ToArray();
first.ShouldBe(new byte[] { 0xDD, 0xCC, 0xBB, 0xAA });
}
[Fact]
public void ToArray_twice_returns_equal_independent_copies()
{
var w = new CipWriter().U16(0x0102);
var a = w.ToArray();
var b = w.ToArray();
b.ShouldBe(a);
b.ShouldNotBeSameAs(a);
}
[Fact]
public void Writing_after_ToArray_is_refused()
{
var w = new CipWriter().U8(1);
_ = w.ToArray();
Should.Throw<InvalidOperationException>(() => w.U8(2));
Should.Throw<InvalidOperationException>(() => w.PatchU16(0, 1));
w.Length.ShouldBe(1);
}
[Fact]
public void Nested_writers_produce_independent_frames()
{
// The Execute PCCC / encapsulation builders build an inner writer while an outer one is live.
var outer = new CipWriter().U8(0xAA);
var inner = new CipWriter().U8(0x01).U8(0x02).ToArray();
var frame = outer.Bytes(inner).U8(0xBB).ToArray();
frame.ShouldBe(new byte[] { 0xAA, 0x01, 0x02, 0xBB });
}
}
@@ -297,6 +297,11 @@ public sealed class NativeAbCipTagRuntimeTests
[InlineData("D2000A00", AbStatus.OutOfBounds)]
[InlineData("D2000F00", AbStatus.NotAllowed)]
[InlineData("D200FF010521", AbStatus.OutOfBounds)]
// Lane K F1 (#737): these used to arrive as BadReply, i.e. a comms fault (Degraded + evict) for a tag the
// controller had simply refused. AbCipRefusals.IsDeviceRefusal classifies the new statuses with no driver change.
[InlineData("D2001C00", AbStatus.Unsupported)] // missing attribute list entry data
[InlineData("D2002000", AbStatus.Unsupported)] // invalid parameter
[InlineData("D200FF010421", AbStatus.OutOfBounds)] // offset beyond end of the tag
public async Task A_refused_tag_completes_initialize_and_reports_the_refusal_on_read(string reply, AbStatus expected)
{
var ch = new FakeCipChannel { Respond = _ => Task.FromResult(Convert.FromHexString(reply)) };
@@ -220,14 +220,30 @@ public sealed class NativeAbLegacyTagRuntimeTests
}
[Fact]
public async Task STS_0x20_on_initialize_is_NotFound()
public async Task STS_0x50_on_initialize_is_NotFound()
{
await using var h = new Harness("slc500", "N99:0").Responder((_, _) => (0x20, null, []));
await using var h = new Harness("slc500", "N99:0").Responder((_, _) => (0x50, null, []));
var ex = await Should.ThrowAsync<AbTransportException>(() => h.Runtime.InitializeAsync(CancellationToken.None));
ex.Status.ShouldBe(AbStatus.NotFound);
h.Runtime.GetStatus().ShouldBe((int)AbStatus.NotFound);
}
/// <summary>
/// Lane K F3 (F8): STS 0x20 / 0x30 come from the host or a bridge when the END device cannot be reached, so they
/// are the no-reply class (BadConnection), not an answered refusal.
/// </summary>
/// <param name="sts">The PCCC STS.</param>
[Theory]
[InlineData((byte)0x20)]
[InlineData((byte)0x30)]
public async Task STS_from_a_bridge_for_an_unreachable_node_is_BadConnection(byte sts)
{
await using var h = new Harness("slc500", "N7:0").Responder((_, _) => (sts, null, []));
var ex = await Should.ThrowAsync<AbTransportException>(() => h.Runtime.InitializeAsync(CancellationToken.None));
ex.Status.ShouldBe(AbStatus.BadConnection);
h.Runtime.GetStatus().ShouldBe((int)AbStatus.BadConnection);
}
[Fact]
public async Task Initialize_performs_exactly_one_read()
{
@@ -305,7 +321,7 @@ public sealed class NativeAbLegacyTagRuntimeTests
public async Task A_failed_second_write_chunk_is_reported_as_failed_not_Good()
{
await using var h = new Harness("slc500", "N7:0", count: 130).Responder((_, n) =>
n == 1 ? (0x30, null, []) : (0x00, null, []));
n == 1 ? (0x60, null, []) : (0x00, null, []));
var ex = await Should.ThrowAsync<AbTransportException>(() => h.Runtime.WriteAsync(CancellationToken.None));
ex.Status.ShouldBe(AbStatus.NotAllowed);
h.Runtime.GetStatus().ShouldBe((int)AbStatus.NotAllowed);
@@ -0,0 +1,131 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.PlcFamilies;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Tests.Fakes;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests;
/// <summary>
/// Lane K F3 (AbLegacy F8, review 07 r0 I4), end to end over a real socket with the PRODUCTION
/// <see cref="NativeAbLegacyTagFactory"/>: a bridge (DHRIO / 1761-NET-ENI) in front of a dead DH+ node answers every
/// PCCC request with STS 0x30 "remote node host missing". That is NOT the device answering, so the driver must treat
/// it as a comms fault — Degraded, <c>LastSuccessfulRead</c> not advanced — or the comms-loss watchdog never fires
/// for it. The positive control is a live device refusing a tag (STS 0x60, command protection): per-tag Bad, Healthy,
/// <c>LastSuccessfulRead</c> advanced.
/// </summary>
[Trait("Category", "Unit")]
public sealed class NativePcccBridgeStatusHealthTests
{
private static readonly byte[] FixedId = [0x07, 0x3D, 0xF3, 0x45, 0x43, 0x50, 0x21];
/// <summary>A fake whose Execute PCCC envelope itself is refused with CIP general status <paramref name="general"/>.</summary>
private static FakeEipServer CipEnvelopeServer(byte general)
{
var server = new FakeEipServer { ZeroReplyContext = true };
server.Handler = req => FakeEipServer.Command(req) == Ab.Transport.Eip.EncapCommand.SendRRData
? FakeEipServer.RRReply(req, [0xCB, 0x00, general, 0x00])
: null;
return server;
}
/// <summary>A PCCC fake that answers every request with one fixed STS.</summary>
private static FakeEipServer StsServer(byte sts)
{
var server = new FakeEipServer { ZeroReplyContext = true };
server.Handler = req =>
{
if (FakeEipServer.Command(req) != Ab.Transport.Eip.EncapCommand.SendRRData) return null;
var cip = FakeEipServer.RequestCip(req);
byte[] head = [0xCB, 0x00, 0x00, 0x00, .. FixedId, 0x4F];
return FakeEipServer.RRReply(req, [.. head, sts, cip[15], cip[16]]);
};
return server;
}
#pragma warning disable OTOPCUA0001 // the driver is called directly to pin its OWN classification (no resilience wrap)
private static async Task<AbLegacyDriver> DriverAsync(FakeEipServer server)
{
var host = $"ab://127.0.0.1:{server.Port}/1,0";
var driver = new AbLegacyDriver(new AbLegacyDriverOptions
{
Devices = [new AbLegacyDeviceOptions(host, AbLegacyPlcFamily.Slc500)],
RawTags = AbLegacyRawTags.Entries([new AbLegacyTagDefinition("T", host, "N7:0", AbLegacyDataType.Int)]),
Timeout = TimeSpan.FromSeconds(5),
Probe = new AbLegacyProbeOptions { Enabled = false },
}, "drv-pccc-bridge", new NativeAbLegacyTagFactory(new DeviceSessionPool()));
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
return driver;
}
/// <summary>STS 0x30 from a bridge: a comms fault, never evidence the device answered.</summary>
[Fact]
public async Task A_dead_node_behind_a_bridge_degrades_and_does_not_advance_LastSuccessfulRead()
{
var ct = TestContext.Current.CancellationToken;
await using var server = StsServer(0x30);
var driver = await DriverAsync(server);
var before = driver.GetHealth().LastSuccessfulRead;
var result = (await driver.ReadAsync(["T"], ct)).Single();
result.StatusCode.ShouldBe(AbLegacyStatusMapper.BadCommunicationError);
var health = driver.GetHealth();
health.State.ShouldBe(DriverState.Degraded);
health.LastSuccessfulRead.ShouldBe(before);
await driver.ShutdownAsync(ct);
server.HandlerErrors.ShouldBeEmpty();
}
/// <summary>Positive control: STS 0x60 is the live device refusing the tag — answered, so Healthy and advanced.</summary>
[Fact]
public async Task A_live_device_refusing_the_tag_stays_Healthy_and_advances_LastSuccessfulRead()
{
var ct = TestContext.Current.CancellationToken;
await using var server = StsServer(0x60);
var driver = await DriverAsync(server);
var before = driver.GetHealth().LastSuccessfulRead;
var result = (await driver.ReadAsync(["T"], ct)).Single();
result.StatusCode.ShouldBe(AbOpcUaStatusMap.BadNotWritable);
var health = driver.GetHealth();
health.State.ShouldBe(DriverState.Healthy);
health.LastSuccessfulRead.ShouldNotBeNull();
health.LastSuccessfulRead.ShouldNotBe(before);
await driver.ShutdownAsync(ct);
server.HandlerErrors.ShouldBeEmpty();
}
/// <summary>
/// Review I2: a refusal that came OFF THE WIRE — the device (or the bridge's Execute PCCC object) answered with
/// CIP 0x08 / 0x1C / 0x20 on the envelope, or PCCC STS 0x10 — is an answered refusal: per-tag BadNotSupported,
/// Healthy, <c>LastSuccessfulRead</c> advanced. It must not land in the "refused before the wire" neutral class
/// (which advances nothing). The local-refusal counterpart stays neutral (NativeAbLegacyRefusedWriteTests).
/// </summary>
/// <param name="general">The CIP general status of the envelope reply, or 0 for a PCCC STS 0x10 reply.</param>
[Theory]
[InlineData((byte)0x08)]
[InlineData((byte)0x1C)]
[InlineData((byte)0x20)]
[InlineData((byte)0x00)]
public async Task A_wire_Unsupported_reply_is_an_answered_refusal(byte general)
{
var ct = TestContext.Current.CancellationToken;
await using var server = general == 0 ? StsServer(0x10) : CipEnvelopeServer(general);
var driver = await DriverAsync(server);
var before = driver.GetHealth().LastSuccessfulRead;
var result = (await driver.ReadAsync(["T"], ct)).Single();
result.StatusCode.ShouldBe(AbLegacyStatusMapper.BadNotSupported);
var health = driver.GetHealth();
health.State.ShouldBe(DriverState.Healthy);
health.LastSuccessfulRead.ShouldNotBeNull();
health.LastSuccessfulRead.ShouldNotBe(before);
await driver.ShutdownAsync(ct);
server.HandlerErrors.ShouldBeEmpty();
}
#pragma warning restore OTOPCUA0001
}
@@ -0,0 +1,62 @@
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
/// <summary>
/// R07:L5 (Modbus half): the RTU ADU is now written into a pooled buffer and the response is deframed in one pooled
/// buffer. The wire bytes and the decoded PDUs must be exactly what the allocating code produced, and a reused pooled
/// buffer must never leak a previous frame's bytes into the next result.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusPooledFramingTests
{
/// <summary>The pooled ADU writer matches the reference construction (unit + PDU, CRC appended low byte first).</summary>
/// <param name="hex">The PDU as hex.</param>
[Theory]
[InlineData("0300000001")]
[InlineData("10000A0002040001000200")]
[InlineData("06")]
public void WriteAdu_matches_the_reference_ADU(string hex)
{
var pdu = Convert.FromHexString(hex);
var reference = ModbusCrc.Append([0x11, .. pdu]);
var pooled = new byte[ModbusRtuFraming.AduLength(pdu.Length) + 7]; // oversized, like a rented array
ModbusRtuFraming.WriteAdu(0x11, pdu, pooled.AsSpan(0, ModbusRtuFraming.AduLength(pdu.Length)));
pooled.AsSpan(0, reference.Length).ToArray().ShouldBe(reference);
ModbusRtuFraming.BuildAdu(0x11, pdu).ShouldBe(reference);
}
/// <summary>
/// A long read reply followed by a short echo and an exception frame, each deframed through the pooled buffer:
/// every result is exactly its own PDU (no stale tail from the previous, longer frame).
/// </summary>
[Fact]
public async Task Consecutive_deframes_through_the_pooled_buffer_do_not_leak_bytes()
{
var ct = TestContext.Current.CancellationToken;
byte[] longRead = [0x03, 200, .. Enumerable.Range(0, 200).Select(i => (byte)(i + 1))];
byte[] echo = [0x06, 0x00, 0x01, 0x00, 0x2A];
(await ModbusRtuFraming.ReadResponsePduAsync(new MemoryStream(ModbusRtuFraming.BuildAdu(1, longRead)), 1, ct))
.ShouldBe(longRead);
(await ModbusRtuFraming.ReadResponsePduAsync(new MemoryStream(ModbusRtuFraming.BuildAdu(1, echo)), 1, ct))
.ShouldBe(echo);
var ex = await Should.ThrowAsync<ModbusException>(() =>
ModbusRtuFraming.ReadResponsePduAsync(new MemoryStream(ModbusRtuFraming.BuildAdu(1, [0x83, 0x02])), 1, ct));
ex.ExceptionCode.ShouldBe((byte)0x02);
(await ModbusRtuFraming.ReadResponsePduAsync(new MemoryStream(ModbusRtuFraming.BuildAdu(1, [0x03, 2, 9, 8])), 1, ct))
.ShouldBe(new byte[] { 0x03, 2, 9, 8 });
}
/// <summary>A byte-count-255 read (the largest RTU reply) fits the pooled frame.</summary>
[Fact]
public async Task The_largest_read_reply_deframes()
{
byte[] max = [0x04, 255, .. new byte[255]];
(await ModbusRtuFraming.ReadResponsePduAsync(new MemoryStream(ModbusRtuFraming.BuildAdu(1, max)), 1,
TestContext.Current.CancellationToken)).ShouldBe(max);
}
}