fix(abcip): #983 whole BOOL-array read counts DWORDs (P-13); probe leases with the driver timeout (P-22)

This commit is contained in:
Joseph Doherty
2026-12-03 09:50:16 -05:00
parent eff7775bca
commit c5c31a1671
4 changed files with 213 additions and 5 deletions
@@ -721,7 +721,11 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
private async Task ProbeLoopAsync(DeviceState state, CancellationToken ct)
{
var probeParams = state.BuildCreateParams(_options.Probe.ProbeTagPath!, _options.Probe.Timeout);
// P-22: the connection's timeout is part of its pooled identity and the first acquirer's options win, so the
// probe (which creates the connection first and again after every recycle) must lease with the DRIVER's
// timeout — a shorter probe timeout silently became every data read's timeout. The probe's own timeout
// bounds only its wait, below.
var probeParams = state.BuildCreateParams(_options.Probe.ProbeTagPath!, _options.Timeout);
IAbCipTagRuntime? probeRuntime = null;
while (!ct.IsCancellationRequested)
@@ -735,14 +739,18 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
try
{
probeRuntime ??= _tagFactory.Create(probeParams);
// The probe's own timeout bounds this tick's wait (cancelling a waiter never faults the shared
// session — scheduler B2); the pooled connection keeps the driver's timeout.
using var tick = CancellationTokenSource.CreateLinkedTokenSource(ct);
tick.CancelAfter(_options.Probe.Timeout);
// Lazy-init on first attempt; re-init after a transport failure has caused the
// native handle to be destroyed.
if (!state.ProbeInitialized)
{
await probeRuntime.InitializeAsync(ct).ConfigureAwait(false);
await probeRuntime.InitializeAsync(tick.Token).ConfigureAwait(false);
state.ProbeInitialized = true;
}
await probeRuntime.ReadAsync(ct).ConfigureAwait(false);
await probeRuntime.ReadAsync(tick.Token).ConfigureAwait(false);
var status = probeRuntime.GetStatus();
if (status == 0)
{
@@ -96,8 +96,22 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
{
_p = p ?? throw new ArgumentNullException(nameof(p));
_elements = (ushort)Math.Clamp(p.ElementCount, 1, ushort.MaxValue);
_isBoolArray = p.IsArray && p.AuthoredType == AbCipDataType.Bool;
// P-13: a Logix BOOL array is stored as DWORDs (0xD3) and its element count is in DWORDs, so a whole read of
// BOOL[64] asks for 2 elements, not 64. Packed until a reply type says otherwise (see ReadCoreAsync).
_wireElements = _isBoolArray ? PackedBoolElements(_elements) : _elements;
}
// P-13: whole BOOL-array read. _elements is the number of BOOLs authored; _wireElements is the element count
// actually sent: ceil(n / 32) DWORDs while the array is packed (0xD3), n when the controller answers per-element 0xC1.
private readonly bool _isBoolArray;
private ushort _wireElements;
/// <summary>DWORDs holding <paramref name="bits"/> packed BOOLs.</summary>
/// <param name="bits">The number of BOOL elements.</param>
/// <returns>ceil(bits / 32), at least 1.</returns>
internal static ushort PackedBoolElements(int bits) => (ushort)Math.Clamp((bits + 31) / 32, 1, ushort.MaxValue);
/// <summary>
/// Test seam: a runtime over <paramref name="channel"/> with a private scheduler and no pool
/// lease. Production code always goes through <see cref="NativeAbCipTagFactory"/>.
@@ -193,7 +207,19 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
var path = Path();
try
{
var (type, handle, data) = await client.ReadAsync(path, _elements, cancellationToken, ExpectedElementBytes(_p.AuthoredType)).ConfigureAwait(false);
var (type, handle, data) = await client.ReadAsync(path, _wireElements, cancellationToken, ExpectedElementBytes(_p.AuthoredType)).ConfigureAwait(false);
if (_isBoolArray && SettleWholeBoolArrayCount(type))
{
// The reply showed the OTHER layout than the one this read was sized for: discard it and ask again
// with the right element count (a packed array's count is DWORDs, a per-element one's is BOOLs).
if (mayRelayout)
{
await ReadCoreAsync(cancellationToken, mayRelayout: false).ConfigureAwait(false);
return;
}
throw new AbTransportException(AbStatus.TypeMismatch,
$"'{_p.TagName}': the controller's BOOL-array layout changed between two reads; retrying next read.");
}
if (_boolElementBit is not null)
{
BoolLayout? shown = type == LogixTypeCode.BoolArray ? BoolLayout.Packed
@@ -230,6 +256,25 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
}
}
/// <summary>
/// Re-sizes a whole BOOL-array read to the layout the reply TYPE showed: 0xD3 means packed DWORDs (count =
/// ceil(n / 32)), 0xC1 means one byte per element (count = n, e.g. ab_server). Any other type is no evidence.
/// </summary>
/// <param name="replyType">The reply's CIP type code.</param>
/// <returns><see langword="true"/> when the count had to change, so the reply just read is for the wrong size.</returns>
private bool SettleWholeBoolArrayCount(ushort replyType)
{
var wanted = replyType switch
{
LogixTypeCode.BoolArray => PackedBoolElements(_elements),
LogixTypeCode.Bool => _elements,
_ => _wireElements,
};
if (wanted == _wireElements) return false;
_wireElements = wanted;
return true;
}
/// <summary>Settles a BOOL-array element tag's layout and selects the matching request path.</summary>
private void SetBoolLayout(BoolLayout layout)
{
@@ -688,7 +733,10 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
private bool[] BuildBoolArray(int count)
{
var arr = new bool[count];
for (var i = 0; i < count; i++) arr[i] = GetBit(i);
// A per-element array (0xC1, one byte per BOOL) is not bit-packed: element i is byte i.
var perElement = _typeCode == LogixTypeCode.Bool;
for (var i = 0; i < count; i++)
arr[i] = perElement ? Span(i, 1)[0] != 0 : GetBit(i);
return arr;
}
@@ -0,0 +1,88 @@
using System.Collections.Concurrent;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests;
/// <summary>
/// Review 2026-12-02 P-22 (#983): the probe creates the pooled connection first (and again after every recycle)
/// and the first acquirer's options win, so a probe leasing with its own short timeout silently became every data
/// read's timeout. The probe must lease with the driver's timeout and bound only its own wait.
/// </summary>
[Trait("Category", "Unit")]
public sealed class AbCipProbeTimeoutTests
{
private const string Device = "ab://10.0.0.5/1,0";
/// <summary>A probe/data read that never completes until cancelled (a dead device).</summary>
private sealed class HangingReadTag(AbCipTagCreateParams p) : FakeAbCipTag(p)
{
public override async Task ReadAsync(CancellationToken cancellationToken)
{
await base.ReadAsync(cancellationToken);
await Task.Delay(Timeout.Infinite, cancellationToken);
}
}
[Fact]
public async Task The_probe_and_the_data_path_lease_the_connection_with_the_same_driver_timeout()
{
var factory = new FakeAbCipTagFactory { Customise = p => new FakeAbCipTag(p) { Value = 1 } };
var drv = new AbCipDriver(new AbCipDriverOptions
{
Devices = [new AbCipDeviceOptions(Device)],
RawTags = AbCipRawTags.From(new AbCipTagDefinition("Speed", Device, "Speed", AbCipDataType.DInt)),
Timeout = TimeSpan.FromSeconds(8),
Probe = new AbCipProbeOptions
{
Enabled = true,
Interval = TimeSpan.FromMilliseconds(50),
Timeout = TimeSpan.FromSeconds(2),
ProbeTagPath = "@raw_cpu_type",
},
}, "abcip-probe-timeout", factory);
var transitions = new ConcurrentQueue<HostStatusChangedEventArgs>();
drv.OnHostStatusChanged += (_, e) => transitions.Enqueue(e);
await drv.InitializeAsync("{}", CancellationToken.None);
var deadline = DateTime.UtcNow.AddSeconds(5);
while (!transitions.Any(t => t.NewState == HostState.Running) && DateTime.UtcNow < deadline)
await Task.Delay(10, TestContext.Current.CancellationToken);
(await drv.ReadAsync(["Speed"], CancellationToken.None))[0].StatusCode.ShouldBe(AbCipStatusMapper.Good);
var probe = factory.Tags["@raw_cpu_type"];
var data = factory.Tags["Speed"];
data.CreationParams.Timeout.ShouldBe(TimeSpan.FromSeconds(8));
probe.CreationParams.Timeout.ShouldBe(data.CreationParams.Timeout); // one identity, not the probe's 2 s
await drv.ShutdownAsync(CancellationToken.None);
}
/// <summary>Positive control: the probe's own timeout still bounds its wait, so a hung probe read goes Stopped.</summary>
[Fact]
public async Task A_hung_probe_read_is_still_bounded_by_the_probe_timeout()
{
var factory = new FakeAbCipTagFactory { Customise = p => new HangingReadTag(p) };
var drv = new AbCipDriver(new AbCipDriverOptions
{
Devices = [new AbCipDeviceOptions(Device)],
Timeout = TimeSpan.FromSeconds(30),
Probe = new AbCipProbeOptions
{
Enabled = true,
Interval = TimeSpan.FromMilliseconds(50),
Timeout = TimeSpan.FromMilliseconds(150),
ProbeTagPath = "@raw_cpu_type",
},
}, "abcip-probe-hang", factory);
var transitions = new ConcurrentQueue<HostStatusChangedEventArgs>();
drv.OnHostStatusChanged += (_, e) => transitions.Enqueue(e);
await drv.InitializeAsync("{}", CancellationToken.None);
var deadline = DateTime.UtcNow.AddSeconds(5);
while (!transitions.Any(t => t.NewState == HostState.Stopped) && DateTime.UtcNow < deadline)
await Task.Delay(10, TestContext.Current.CancellationToken);
transitions.Select(t => t.NewState).ShouldContain(HostState.Stopped);
await drv.ShutdownAsync(CancellationToken.None);
}
}
@@ -346,6 +346,70 @@ public sealed class NativeAbCipTagRuntimeTests
rt.DecodeArray(AbCipDataType.Bool, 3).ShouldBe(new[] { true, false, true });
}
/// <summary>The element count a Read Tag request carries: the u16 just before the 4-byte fragment offset.</summary>
private static int RequestedCount(byte[] request) =>
System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(request.AsSpan(request.Length - 6, 2));
[Theory]
[InlineData(1, 1)]
[InlineData(32, 1)]
[InlineData(33, 2)]
[InlineData(64, 2)]
[InlineData(65, 3)]
public void Packed_BOOL_element_counts_are_in_DWORDs(int bits, int dwords) =>
NativeAbCipTagRuntime.PackedBoolElements(bits).ShouldBe((ushort)dwords);
/// <summary>
/// P-13: a Logix BOOL[64] is two DWORDs (0xD3). A controller that refuses a 64-element read (the DWORD count
/// is what its element segment addresses) must be asked for 2 — the whole-array read used to send the bit count
/// and the tag was permanently Bad.
/// </summary>
[Fact]
public async Task A_whole_BOOL_array_read_requests_DWORDs_not_bits()
{
var ch = new FakeCipChannel
{
Respond = req => Task.FromResult(RequestedCount(req) > 2
? Convert.FromHexString("D200FF010521") // 0xFF / 0x2105: offset beyond the array
: Convert.FromHexString("D2000000D300")
.Concat(new byte[] { 0x05, 0, 0, 0, 0, 0, 0, 0x80 }.Take(4 * RequestedCount(req))).ToArray()),
};
using var rt = await ReadAsync(ch, Params("Bits", AbCipDataType.Bool, elementCount: 64, isArray: true));
RequestedCount(ch.Sent[0]).ShouldBe(2);
ch.SentCount.ShouldBe(2); // init read + explicit read; no re-layout on a packed reply
rt.GetStatus().ShouldBe((int)AbStatus.Ok);
var bits = (bool[])rt.DecodeArray(AbCipDataType.Bool, 64)!;
bits.Length.ShouldBe(64);
bits.Select((b, i) => (b, i)).Where(x => x.b).Select(x => x.i).ShouldBe([0, 2, 63]);
}
/// <summary>
/// P-13 positive control: a family that answers per-element (0xC1, one byte per BOOL — ab_server) is
/// recognised from the reply TYPE, the read is repeated once with the BOOL count, and the layout sticks.
/// </summary>
[Fact]
public async Task A_per_element_BOOL_array_is_re_read_with_the_BOOL_count_once()
{
var ch = new FakeCipChannel
{
Respond = req => Task.FromResult(Convert.FromHexString("D2000000C100")
.Concat(Enumerable.Range(0, RequestedCount(req)).Select(i => (byte)(i % 2))).ToArray()),
};
using var rt = NativeAbCipTagRuntime.ForTest(ch, Params("Flags", AbCipDataType.Bool, elementCount: 40, isArray: true));
await rt.InitializeAsync(CancellationToken.None);
RequestedCount(ch.Sent[0]).ShouldBe(2); // optimistic DWORD count…
RequestedCount(ch.Sent[1]).ShouldBe(40); // …corrected from the 0xC1 reply type
await rt.ReadAsync(CancellationToken.None);
RequestedCount(ch.Sent[2]).ShouldBe(40); // and remembered: no further re-layout
ch.SentCount.ShouldBe(3);
var bits = (bool[])rt.DecodeArray(AbCipDataType.Bool, 40)!;
bits.Length.ShouldBe(40);
bits.Select((b, i) => b == (i % 2 == 1)).ShouldAllBe(ok => ok); // byte i, not bit i
}
[Fact]
public async Task A_user_string_array_uses_the_buffer_derived_stride()
{