fix(ablegacy): #984 per-tag family-type rejection + gate, bit arrays sized in words, Bit write RMWs bit 0, T/C/R read coalescing, answered-refusal/gate-race/null-write fixes

P-5 Long on MicroLogix/PLC-5 is BadConfigurationError per tag (init no longer throws), deploy gate warns via family-aware Inspect.
P-14 Bit array wire read sized in 16-bit words. P-15 Bit without /n RMWs bit 0; Bit on non-bit file refused.
P-18 native T/C/R sub-elements coalesce into one whole-element block read.
P-23f local OutOfBounds/TooLarge no longer count as answers, element/file >65535 is malformed; g block read re-resolves under the gate with identity-checked eviction; h null scalar write BadTypeMismatch.
This commit is contained in:
Joseph Doherty
2026-12-03 09:47:13 -05:00
parent 65fd71de7a
commit a9bc103eea
10 changed files with 601 additions and 75 deletions
+31 -3
View File
@@ -28,9 +28,15 @@ Per family the `AbLegacyPlcFamilyProfile` supplies the libplctag `plc` attribute
default CIP path, max-payload bytes, and the `SupportsStringFile` /
`SupportsLongFile` capability flags. MicroLogix uses direct EIP (empty default
path); MicroLogix and PLC-5 don't ship L-files; PLC-5 predates them entirely.
Tag types are validated against the device's profile at init time — declaring a
`Long` or `String` tag on a family that can't support it fails fast with a clear
message.
Tag types are validated against the device's profile — declaring a `Long` or
`String` tag on a family that can't support it is **that tag's** configuration
error (review 2026-12-02 P-5): init still succeeds, the tag reads and writes
`BadConfigurationError` without touching the wire, one Warning is logged, and the tag
appears in the skipped-tag report. The deploy gate (`AbLegacyTagDefinitionFactory.Inspect`
with the device's `PlcFamily`, same `AbLegacyPlcFamilyProfile.UnsupportedDataTypeReason`
authority) warns earlier. Note the MicroLogix profile says `SupportsLongFile: false`;
MicroLogix 1100/1400 may in fact ship L files (product knowledge, unverified on
hardware here) — flipping the flag is a one-line change once a real controller confirms.
## Capability Surface
@@ -81,6 +87,28 @@ PCCC structural rules — bit-addressing only on 16/32-bit element files,
sub-elements only on T/C/R files, no file number on I/O/S — rejecting malformed
addresses before they reach libplctag.
**A `Bit` tag authored without `/n`** reads as bit 0 of its word, so it **writes as bit 0**
through the same read-modify-write (decision, P-15: reading and writing the same bit is the
least surprising and preserves the other 15; refusing would have broken existing tags). It used to
write the whole word as 0x0001 / 0x0000. A `Bit` tag with no `/n` and no status sub-element on a
file with no bit layout (F, ST, a bare T/C/R element) has no sound write and is `BadNotSupported`.
**Bit arrays** — `arrayLength` counts BITS; the wire read is sized in 16-bit words
(`(bits + 15) / 16`, `AbLegacyDriver.WireElementCount`), so 256 bits on a 16-word `B3` file is one
16-word read, not a 256-word read past the end of the file (P-14).
**Read coalescing of Timer / Counter / Control sub-elements (P-18)** — on the **Native** transport, `T4:n.ACC` /
`.PRE` / `.DN`… (and C/R) of nearby elements of one file ride ONE whole-element read (6 bytes per element)
and each tag is sliced out of its element; N/B/F/L word coalescing is unchanged. libplctag keeps the
per-sub-element reads (its multi-element T/C/R layout is not verified here), and `S:`/`I:`/`O:` words
(implicit file number, octal PLC-5 I/O) are still not coalesced. Hardware gate: native block read on a real
controller with timers.
**Answered refusals (P-23f)** — only a refusal the DEVICE sent (`AbDeviceReplyException`, or a libplctag
status) counts as proof the device is alive; a locally raised `OutOfBounds`/`TooLarge` does not. A file or
element number above 65535 (cannot be encoded) is a malformed address (`BadNodeIdUnknown`), never a wire
read. A **null** scalar write value is `BadTypeMismatch` before any runtime is created (P-23h).
**Bit-within-word writes** — B-file (`B3:0/0`), I/O image (`I:0/0`, `O:1/2`),
N-file (`N7:0/3`), and L-file bit addresses all use the same parent-word
read-modify-write (RMW) path: the driver reads the parent word, flips the target
@@ -169,7 +169,7 @@ public sealed record AbLegacyAddress(
}
else
{
if (!int.TryParse(fileTail, out var fn) || fn < 0) return null;
if (!int.TryParse(fileTail, out var fn) || fn < 0 || fn > MaxWireField) return null;
fileNumber = fn;
}
}
@@ -192,7 +192,7 @@ public sealed record AbLegacyAddress(
indirectWord = ParseInner(wordPart[1..^1], profile);
if (indirectWord is null) return null;
}
else if (!TryParseIndex(wordPart, octal, out word) || word < 0) return null;
else if (!TryParseIndex(wordPart, octal, out word) || word < 0 || word > MaxWireField) return null;
int? bitIndex = null;
if (bitText is not null)
@@ -272,6 +272,21 @@ public sealed record AbLegacyAddress(
/// bit-addressable. 16-bit element files (N/B/I/O/S/A) permit bits 0..15; the 32-bit
/// L-file permits 0..31.
/// </summary>
/// <summary>
/// Largest file / element number a PCCC address field can carry (the 0xFF-escaped 16-bit form). A larger literal
/// can never reach the wire — the native encoder refuses it locally — so it is a malformed address (configuration
/// error), not a device refusal that proves a device is alive.
/// </summary>
internal const int MaxWireField = ushort.MaxValue;
/// <summary>
/// Whether <paramref name="letter"/> is a bit-addressable word file (N/B/I/O/S/A 16-bit, L 32-bit), i.e. one a
/// <c>/n</c> bit suffix is legal on and a bit-in-word read-modify-write applies to.
/// </summary>
/// <param name="letter">The file-type letter (upper case).</param>
/// <returns><see langword="true"/> for a bit-addressable word file.</returns>
public static bool IsBitAddressableFile(string letter) => MaxBitIndexFor(letter) >= 0;
private static int MaxBitIndexFor(string letter) => letter switch
{
"L" => 31,
@@ -24,6 +24,23 @@ public sealed record AbLegacyPlcFamilyProfile(
/// <summary>MicroLogix only: RTC / HSC / DLS / MMI / PTO / PWM / STI / EII / IOS / BHI function files.</summary>
bool SupportsFunctionFiles = false)
{
/// <summary>
/// Why <paramref name="type"/> cannot be authored on a device of this family (an L-file <c>Long</c> or ST-file
/// <c>String</c> the profile says the family does not ship), or <see langword="null"/> when it can. The single
/// authority the driver's per-tag rejection and the deploy gate both read.
/// </summary>
/// <param name="type">The authored data type.</param>
/// <param name="family">The device family the profile belongs to (for the message).</param>
/// <returns>The refusal reason, or <see langword="null"/>.</returns>
public string? UnsupportedDataTypeReason(AbLegacyDataType type, AbLegacyPlcFamily family) => type switch
{
AbLegacyDataType.Long when !SupportsLongFile =>
$"a Long (32-bit L-file) tag is not supported on a {family} device (the family does not support L-files).",
AbLegacyDataType.String when !SupportsStringFile =>
$"a String (ST-file) tag is not supported on a {family} device (the family does not support ST-files).",
_ => null,
};
/// <summary>Gets the profile for the specified PLC family.</summary>
/// <param name="family">The PLC family.</param>
/// <remarks>
@@ -177,6 +177,11 @@ public static class AbLegacyTagDefinitionFactory
{
if (AbLegacyAddress.Validate(accepted.Address, family) is { } addressError)
warnings.Add($"AbLegacy tag address: {addressError} The driver reads this tag as BadNodeIdUnknown.");
else if (family is { } fam
&& AbLegacyPlcFamilyProfile.ForFamily(fam).UnsupportedDataTypeReason(accepted.DataType, fam) is { } typeError)
// The same rule the driver applies per tag at init: the tag reads BadConfigurationError and the
// rest of the driver keeps running.
warnings.Add($"AbLegacy tag: {typeError} The driver reads this tag as BadConfigurationError.");
else if (accepted.ArrayLength is not null
&& ArrayFileMismatch(accepted.DataType, accepted.Address) is { } widthError)
warnings.Add(widthError);
@@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Pccc;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy;
@@ -41,6 +42,16 @@ public sealed partial class AbLegacyDriver
private sealed record CoalescedBlock(
string FileLetter, int FileNumber, int Start, int Count, AbLegacyDataType ElementType, List<ReadItem> Members)
{
/// <summary>True for a Timer / Counter / Control block: whole 3-word (6-byte) elements are read and each member's
/// word / status bit is sliced out of them (<see cref="AbLegacyDataType.TimerElement"/> is the grouping marker).</summary>
public bool IsStructured => ElementType == AbLegacyDataType.TimerElement;
/// <summary>The type the block's buffer is decoded as: a structured element is read as its raw 16-bit words.</summary>
public AbLegacyDataType DecodeType => IsStructured ? AbLegacyDataType.Int : ElementType;
/// <summary>The number of <see cref="DecodeType"/> values the buffer holds.</summary>
public int DecodeCount => IsStructured ? Count * 3 : Count;
/// <summary>The runtime-cache key; distinct from any RawPath (RawPaths never contain '|').</summary>
public string Key => $"|block|{FileLetter}{FileNumber}:{Start}+{Count}";
@@ -52,10 +63,23 @@ public sealed partial class AbLegacyDriver
/// The element type a scalar tag is decoded from when it rides a coalesced block, or <see langword="null"/>
/// when the tag keeps the single-tag path.
/// </summary>
private static AbLegacyDataType? CoalescedElementType(ReadItem item)
private AbLegacyDataType? CoalescedElementType(DeviceState device, ReadItem item)
{
var a = item.Parsed;
if (a.IsIndirect || a.SubElement is not null || a.FileNumber is null || IsArrayTag(item.Def)) return null;
if (a.IsIndirect || a.FileNumber is null || IsArrayTag(item.Def)) return null;
// T / C / R sub-elements (T4:0.ACC / .PRE / .DN ...): one whole-element read returns every sub-element of every
// timer in a span, where each used to cost its own exchange (review 2026-12-02 P-18). Native transport only: its
// 6-byte element layout is what the wire captures pin; libplctag's multi-element T/C/R buffer layout is not
// verified here, so that stack keeps the per-sub-element reads it has always had. PLC-5 native reads are
// refused for every non-N file, so it never rides a block either.
if (a.SubElement is not null)
return _transport == AbLegacyTransport.Native
&& device.Profile.LibplctagPlcAttribute != "plc5"
&& a.FileLetter is "T" or "C" or "R"
&& item.Def.DataType is AbLegacyDataType.Int or AbLegacyDataType.AnalogInt or AbLegacyDataType.Bit
&& TrySubElement(a) is not null
? AbLegacyDataType.TimerElement
: null;
return (a.FileLetter, item.Def.DataType) switch
{
("N" or "B", AbLegacyDataType.Int or AbLegacyDataType.AnalogInt or AbLegacyDataType.Bit) => AbLegacyDataType.Int,
@@ -66,6 +90,13 @@ public sealed partial class AbLegacyDriver
};
}
/// <summary>The resolved word / status-bit position of a T/C/R sub-element address, or null if it names none.</summary>
private static PcccAddress? TrySubElement(AbLegacyAddress a)
{
try { return PcccAddress.WithSubElementName(a.FileLetter, a.FileNumber, a.WordNumber, a.SubElement!); }
catch (AbTransportException) { return null; }
}
/// <summary>
/// Plans a device pass: coalescable tags grouped per file into runs of nearby elements (a run of two or more
/// tags becomes a block), everything else a single unit. Block shapes the device refused before stay single.
@@ -78,7 +109,7 @@ public sealed partial class AbLegacyDriver
var groups = new Dictionary<(string Letter, int File, AbLegacyDataType Type), List<ReadItem>>();
foreach (var item in items)
{
if (CoalescedElementType(item) is not { } type)
if (CoalescedElementType(device, item) is not { } type)
{
units.Add(new ReadUnit(item, null));
continue;
@@ -90,7 +121,7 @@ public sealed partial class AbLegacyDriver
foreach (var ((letter, file, type), members) in groups)
{
var width = type == AbLegacyDataType.Int ? 2 : 4;
var width = type switch { AbLegacyDataType.Int => 2, AbLegacyDataType.TimerElement => 6, _ => 4 };
var maxElements = MaxCoalescedBytes / width;
var ordered = members.OrderBy(m => m.Parsed.WordNumber).ToList();
var run = new List<ReadItem> { ordered[0] };
@@ -132,10 +163,18 @@ public sealed partial class AbLegacyDriver
foreach (var m in block.Members) results[m.Index] = new DataValueSnapshot(null, status, null, now);
}
// The runtime this call actually used; every eviction below targets IT (identity-checked), never a fresh one a
// concurrent caller reconnected under the gate in the meantime.
IAbLegacyTagRuntime? used = null;
void EvictUsed()
{
if (used is not null) EvictRuntime(device, block.Key, used);
}
(BlockOutcome, OpVerdict, string?) Refused(string why)
{
// The handle is never kept for a refused shape (review 07 r0 M5): it may never be planned again.
EvictRuntime(device, block.Key);
EvictUsed();
// Every refusal falls back to per-member reads THIS pass, so each member gets its own answer and a bad
// member can never black out its neighbours. The shape is only REMEMBERED after a repeat — one refusal can
// be transient (program mode, a download in progress), two in a row are deterministic.
@@ -166,12 +205,30 @@ public sealed partial class AbLegacyDriver
int status;
Array? data = null;
var opLock = device.GetRuntimeLock(block.Key);
device.BeforeOperationGate?.Invoke(block.Key);
await opLock.WaitAsync(ct).ConfigureAwait(false);
try
{
// Re-resolve under the gate (as the single-tag path does): the handle fetched above may have been evicted
// and disposed by a sibling's failed call while this one waited, and reading it would fail every member as
// a comms fault (review 2026-12-02 P-23g).
if (!device.Runtimes.TryGetValue(block.Key, out var live))
{
live = device.IsRetired
? runtime
: await CreateSingleFlightAsync(
device, device.Runtimes, block.Key, () => _tagFactory.Create(createParams), ct).ConfigureAwait(false);
}
runtime = used = live;
await runtime.ReadAsync(ct).ConfigureAwait(false);
status = runtime.GetStatus();
if (status == 0) data = runtime.DecodeArray(block.ElementType, block.Count) as Array;
if (status == 0) data = runtime.DecodeArray(block.DecodeType, block.DecodeCount) as Array;
}
catch (Exception ex) when (ex is not OperationCanceledException and not ConnectionThrottledException)
{
// Evict while the gate is still held so a waiter never picks up the failed handle.
EvictUsed();
throw;
}
finally
{
@@ -184,11 +241,11 @@ public sealed partial class AbLegacyDriver
// to per-member reads; only a no-reply status fails the block's members together (review 07 r0 I1).
if (!IsNoReply((AbStatus)status))
return Refused($"device status {(AbStatus)status}");
EvictRuntime(device, block.Key);
EvictUsed();
FailAll(AbLegacyStatusMapper.MapStatus(status));
return (BlockOutcome.Done, OpVerdict.Fault, $"transport status {status} reading {block.StartName}+{block.Count}");
}
if (data is null || data.Length < block.Count)
if (data is null || data.Length < block.DecodeCount)
return Refused("the block decoded short");
foreach (var m in block.Members)
@@ -213,7 +270,7 @@ public sealed partial class AbLegacyDriver
}
catch (Exception ex)
{
EvictRuntime(device, block.Key);
EvictUsed();
FailAll(AbLegacyStatusMapper.BadCommunicationError);
return (BlockOutcome.Done, OpVerdict.Fault, ex.Message);
}
@@ -227,6 +284,20 @@ public sealed partial class AbLegacyDriver
{
var offset = m.Parsed.WordNumber - block.Start;
var bit = m.Parsed.BitIndex;
if (block.IsStructured)
{
// Mirrors the native single-tag DecodeValue of a T/C/R sub-element: a status bit decodes as that bit (bool for a
// Bit tag, 0/1 for a word-typed one); a word sub-element as its 16-bit value (a Bit tag reads bit 0).
var words16 = (short[])data;
var sub = TrySubElement(m.Parsed)!;
var w = words16[offset * 3 + sub.SubElement!.Value];
if (sub.Bit is int sb)
{
var v = ((ushort)w >> sb & 1) != 0;
return m.Def.DataType == AbLegacyDataType.Bit ? v : (object)(v ? 1 : 0);
}
return m.Def.DataType == AbLegacyDataType.Bit ? (w & 1) != 0 : (int)w;
}
switch (data)
{
case short[] words:
@@ -40,6 +40,10 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
// by reference alongside _devices (same build-and-swap rule).
private volatile Dictionary<string, AbLegacyTagDefinition> _tagsByRawPath = new(StringComparer.Ordinal);
// RawPath → why the tag is a per-tag configuration error (its data type is not available on its device's PLC
// family). Published with the tag table; such a tag answers BadConfigurationError on read and write.
private volatile Dictionary<string, string> _configRejected = new(StringComparer.Ordinal);
// Serialises every PUBLISH/RETIRE of the two tables with the lifecycle epoch. Never held across an await.
private readonly object _lifecycleLock = new();
@@ -187,6 +191,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
// is ever mutated.
var devices = new Dictionary<string, DeviceState>(StringComparer.OrdinalIgnoreCase);
var tags = new Dictionary<string, AbLegacyTagDefinition>(StringComparer.Ordinal);
var rejected = new Dictionary<string, string>(StringComparer.Ordinal);
try
{
// re-parse the supplied DriverConfig so a config change delivered through the IDriver
@@ -238,32 +243,30 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
_driverInstanceId, entry.RawPath, reason);
continue;
}
tags[entry.RawPath] = def with
var resolved = def with
{
WriteIdempotent = entry.WriteIdempotent,
DeviceHostAddress = ResolveDeviceHost(options, entry.DeviceName),
};
tags[entry.RawPath] = resolved;
// A data type the owning device's PLC family does not ship (an L-file Long on a MicroLogix, an ST-file
// String on a family without one) is THIS TAG's configuration error — it reads/writes
// BadConfigurationError and is reported in the skipped-tag ledger — never a reason to fault every other
// tag and device of the instance (review 2026-12-02 P-5). The deploy gate says the same thing earlier
// (AbLegacyTagDefinitionFactory.Inspect, family-aware) from the same profile authority.
if (devices.TryGetValue(resolved.DeviceHostAddress, out var deviceForTag)
&& deviceForTag.Profile.UnsupportedDataTypeReason(resolved.DataType, deviceForTag.Options.PlcFamily) is { } typeReason)
{
rejected[entry.RawPath] = typeReason;
_skippedTags.Skip(entry.RawPath, typeReason);
_logger.LogWarning(
"AbLegacy tag rejected for its device's PLC family; it will read BadConfigurationError. Driver={DriverInstanceId} RawPath={RawPath} Device={DeviceHostAddress} Reason={Reason}",
_driverInstanceId, entry.RawPath, resolved.DeviceHostAddress, typeReason);
}
}
_skippedTags.Commit();
// Validate tag types against their device's family profile. Long (32-bit integer)
// and String (ST-file) are not supported by all PCCC families; reject them early
// so a misconfigured tag fails at init time with a clear message rather than
// surfacing an opaque comms error at runtime.
foreach (var tag in tags.Values)
{
if (!devices.TryGetValue(tag.DeviceHostAddress, out var deviceForTag)) continue;
var profile = deviceForTag.Profile;
if (tag.DataType == AbLegacyDataType.Long && !profile.SupportsLongFile)
throw new InvalidOperationException(
$"Tag '{tag.Name}' is typed as Long but device '{tag.DeviceHostAddress}' " +
$"(family {deviceForTag.Options.PlcFamily}) does not support L-files.");
if (tag.DataType == AbLegacyDataType.String && !profile.SupportsStringFile)
throw new InvalidOperationException(
$"Tag '{tag.Name}' is typed as String but device '{tag.DeviceHostAddress}' " +
$"(family {deviceForTag.Options.PlcFamily}) does not support ST-files.");
}
// Publish, start the probe loops and go Healthy as ONE step under the lifecycle lock, and only if no
// teardown (or newer initialise) ran since this attempt began. Starting the loops inside the lock
// means a teardown that swaps this table out always sees their tasks and joins them.
@@ -274,6 +277,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
$"AbLegacy driver {_driverInstanceId} initialise was superseded by a shutdown or a newer initialise.");
_options = options;
_tagsByRawPath = tags;
_configRejected = rejected;
_devices = devices;
_resolver.Clear(); // drop transient parses made against the previous table
if (options.Probe.Enabled && !string.IsNullOrWhiteSpace(options.Probe.ProbeAddress))
@@ -338,6 +342,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
{
_lifecycleEpoch++;
_tagsByRawPath = new Dictionary<string, AbLegacyTagDefinition>(StringComparer.Ordinal);
_configRejected = new Dictionary<string, string>(StringComparer.Ordinal);
}
var retired = _devices.Values.ToList();
_devices = new Dictionary<string, DeviceState>(StringComparer.OrdinalIgnoreCase);
@@ -523,6 +528,13 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadNodeIdUnknown, null, now);
continue;
}
// A tag whose data type its device's PLC family does not ship is a per-tag configuration error: answered
// without touching the wire or the device's health (already warned once at init).
if (_configRejected.ContainsKey(def.Name))
{
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadConfigurationError, null, now);
continue;
}
var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily);
if (parsed is null)
{
@@ -895,6 +907,18 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
results[i] = new WriteResult(AbLegacyStatusMapper.BadNodeIdUnknown);
continue;
}
if (_configRejected.ContainsKey(def.Name))
{
results[i] = new WriteResult(AbLegacyStatusMapper.BadConfigurationError);
continue;
}
// A null scalar value has no encoding: the runtimes' Convert.To* would write it as 0 / false / "" (review
// 2026-12-02 P-23h). Refused before any runtime — and so any init read — exists; the array path already does.
if (w.Value is null && !IsArrayTag(def))
{
results[i] = new WriteResult(AbLegacyStatusMapper.BadTypeMismatch);
continue;
}
try
{
@@ -991,9 +1015,22 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
// sub-element combined with a /N bit index, so their BitIndex is always null. NOTE: an Input-image (I) write is sent
// to the PLC like any other write — the device drives the input image from physical inputs and
// may reject it; we surface that real PCCC status rather than pre-rejecting at the driver.
else if (def.DataType == AbLegacyDataType.Bit && parsed.BitIndex is int bit)
//
// A Bit tag authored WITHOUT /n reads as bit 0 of its word (DecodeValue), so it WRITES as bit 0 too — through
// the same RMW. The old fall-through encoded the whole word as 0x0001 / 0x0000 and silently cleared the
// other 15 bits (review 2026-12-02 P-15). A Bit tag on a file with no bit layout (F, ST, T/C/R element
// without a sub-element, ...) has no sound write at all: refused BadNotSupported.
else if (def.DataType == AbLegacyDataType.Bit && parsed.SubElement is null
&& parsed.BitIndex is null && !AbLegacyAddress.IsBitAddressableFile(parsed.FileLetter))
{
var (code, raw) = await WriteBitInWordAsync(device, def, parsed, bit, w.Value, cancellationToken)
WarnRefusalOnce(device, def, "write",
$"a Bit tag on {parsed.FileLetter}-file '{def.Address}' has no bit to write; author the address with a /n bit index on a word file, or a status sub-element.");
results[i] = new WriteResult(AbLegacyStatusMapper.BadNotSupported);
continue;
}
else if (def.DataType == AbLegacyDataType.Bit && parsed.SubElement is null)
{
var (code, raw) = await WriteBitInWordAsync(device, def, parsed, parsed.BitIndex ?? 0, w.Value, cancellationToken)
.ConfigureAwait(false);
results[i] = new WriteResult(code);
RecordWriteStatus(device, def, raw, ref outcome);
@@ -1613,6 +1650,17 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
private static int EffectiveArrayLength(AbLegacyTagDefinition def) =>
def.ArrayLength is int len && len >= 1 ? Math.Min(len, AbLegacyArray.MaxElements) : 1;
/// <summary>
/// The element count the WIRE read / runtime buffer is sized for. Equal to <see cref="EffectiveArrayLength"/> for
/// every array except a <c>Bit</c> array: its <c>arrayLength</c> counts BITS, but the file is read in 16-bit
/// words, so 256 bits are 16 words — not 256 (16x the bytes, and a read past the end of a short file that the
/// PLC refuses forever; review 2026-12-02 P-14). The decode still takes <see cref="EffectiveArrayLength"/> bits.
/// </summary>
internal static int WireElementCount(AbLegacyTagDefinition def) =>
IsArrayTag(def) && def.DataType == AbLegacyDataType.Bit
? (EffectiveArrayLength(def) + 15) / 16
: EffectiveArrayLength(def);
/// <summary>
/// True for a deterministic refusal of the operation itself (<see cref="AbStatus.Unsupported"/>) — the
/// native runtime raises it BEFORE anything reaches the wire (status-bit writes, PLC-5 non-N reads and
@@ -1638,7 +1686,13 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
/// <returns><see langword="true"/> for an answered refusal.</returns>
internal static bool IsAnsweredRefusal(Exception ex) =>
ex is AbTransportException ate
&& (IsDeviceRefusal(ate.Status) || ate is AbDeviceReplyException { Status: AbStatus.Unsupported });
&& (ate is AbDeviceReplyException { Status: AbStatus.Unsupported }
// A refusal STATUS proves an answer only when the DEVICE sent it. The native transport raises the same
// OutOfBounds / TooLarge / TypeMismatch locally (an element number that does not fit a PCCC field, an oversize
// count, a short buffer) with no wire involved, and counting those as answers let one unreachable tag on a dead
// device keep resetting its fault streak (review 2026-12-02 P-23f). A libplctag status arrives wrapped (it has
// an inner exception) and always came back from the library's own exchange, so it still counts.
|| (IsDeviceRefusal(ate.Status) && (ate is AbDeviceReplyException || ate.InnerException is not null)));
/// <summary>
/// Initializes a freshly created runtime. A runtime whose init is refused locally is still KEPT: the
@@ -1703,7 +1757,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
LibplctagPlcAttribute: device.Profile.LibplctagPlcAttribute,
TagName: parsed.ToLibplctagName(),
Timeout: _options.Timeout,
ElementCount: EffectiveArrayLength(def));
ElementCount: WireElementCount(def));
private async Task<IAbLegacyTagRuntime> EnsureTagRuntimeAsync(
DeviceState device, AbLegacyTagDefinition def, CancellationToken ct)
@@ -1759,6 +1813,21 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
}
}
/// <summary>
/// <see cref="EvictRuntime(DeviceState, string)"/>, but only if the cached runtime for <paramref name="tagName"/>
/// is still <paramref name="expected"/> — the one the caller actually used and saw fail. Without the identity
/// check a caller evicting after it released the operation gate could dispose the FRESH runtime a waiting
/// sibling had just reconnected under that gate, failing the sibling mid-read as a comms fault (review
/// 2026-12-02 P-23g).
/// </summary>
private static void EvictRuntime(DeviceState device, string tagName, IAbLegacyTagRuntime expected)
{
if (device.Runtimes.TryRemove(new KeyValuePair<string, IAbLegacyTagRuntime>(tagName, expected)))
{
try { expected.Dispose(); } catch { /* best-effort */ }
}
}
/// <summary>
/// Synchronous teardown. Mirrors the body of
/// <see cref="ShutdownAsync"/> but never wraps the async path in
@@ -19,6 +19,7 @@ public static class AbLegacyStatusMapper
public const uint BadCommunicationError = 0x80050000u;
public const uint BadTimeout = 0x800A0000u;
public const uint BadTypeMismatch = 0x80740000u;
public const uint BadConfigurationError = 0x80890000u;
/// <summary>
/// Map the integer form of an <see cref="AbStatus"/> (what <see cref="IAbLegacyTagRuntime.GetStatus"/>
@@ -164,20 +164,26 @@ public sealed class AbLegacyDriverTests
factory.Tags["N7:0"].CreationParams.CipPath.ShouldBe("1,2");
}
/// <summary>Verifies that long tag on MicroLogix device is rejected at initialization.</summary>
/// <summary>
/// A Long tag on a MicroLogix is THAT TAG's configuration error and must not fault the whole instance (review
/// 2026-12-02 P-5; this test used to pin the throw). Init succeeds, the tag reads BadConfigurationError, and the
/// skipped-tag ledger names it.
/// </summary>
[Fact]
public async Task Long_tag_on_MicroLogix_device_rejected_at_init()
public async Task Long_tag_on_MicroLogix_device_is_rejected_per_tag_not_at_init()
{
var drv = new AbLegacyDriver(new AbLegacyDriverOptions
{
Devices = [new AbLegacyDeviceOptions("ab://10.0.0.5/", AbLegacyPlcFamily.MicroLogix)],
RawTags = AbLegacyRawTags.Entries([new AbLegacyTagDefinition("X", "ab://10.0.0.5/", "L9:0", AbLegacyDataType.Long)]),
}, "drv-1");
Probe = new AbLegacyProbeOptions { Enabled = false },
}, "drv-1", new FakeAbLegacyTagFactory());
var ex = await Should.ThrowAsync<InvalidOperationException>(
() => drv.InitializeAsync("{}", CancellationToken.None));
ex.Message.ShouldContain("Long");
ex.Message.ShouldContain("L-files");
await drv.InitializeAsync("{}", CancellationToken.None);
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
(await drv.ReadAsync(["X"], CancellationToken.None)).Single().StatusCode.ShouldBe(AbLegacyStatusMapper.BadConfigurationError);
drv.GetSkippedTags()!.Sample.ShouldContain(t => t.RawPath == "X");
}
/// <summary>Verifies that long tag on SLC 500 device is accepted.</summary>
@@ -196,24 +202,20 @@ public sealed class AbLegacyDriverTests
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
}
/// <summary>Verifies that string tag on PLC-5 device is rejected at initialization.</summary>
/// <summary>Same rule for a Long on a PLC-5 (no L files): per-tag, never an init fault.</summary>
[Fact]
public async Task String_tag_on_Plc5_device_rejected_at_init()
public async Task Long_tag_on_Plc5_device_is_rejected_per_tag_not_at_init()
{
// PLC-5 profile has SupportsStringFile = true per the current profile, but we test the
// rejection path for a family that explicitly disables it. MicroLogix supports strings,
// so we fabricate a scenario via a custom profile test — actually PLC-5 DOES support
// string files per the profile. Instead test MicroLogix + Long, which is already covered.
// Test String tag rejection with a hypothetical: use Long on Plc5 which has
// SupportsLongFile = false.
var drv = new AbLegacyDriver(new AbLegacyDriverOptions
{
Devices = [new AbLegacyDeviceOptions("ab://10.0.0.5/1,0", AbLegacyPlcFamily.Plc5)],
RawTags = AbLegacyRawTags.Entries([new AbLegacyTagDefinition("X", "ab://10.0.0.5/1,0", "L9:0", AbLegacyDataType.Long)]),
}, "drv-1");
Probe = new AbLegacyProbeOptions { Enabled = false },
}, "drv-1", new FakeAbLegacyTagFactory());
var ex = await Should.ThrowAsync<InvalidOperationException>(
() => drv.InitializeAsync("{}", CancellationToken.None));
ex.Message.ShouldContain("Long");
await drv.InitializeAsync("{}", CancellationToken.None);
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
(await drv.ReadAsync(["X"], CancellationToken.None)).Single().StatusCode.ShouldBe(AbLegacyStatusMapper.BadConfigurationError);
}
}
@@ -190,37 +190,49 @@ public sealed class AbLegacyReadWriteTests
}
/// <summary>
/// Driver.AbLegacy-014 — a Bit-typed tag with no bit suffix (e.g. B3:0, DataType=Bit)
/// takes the EncodeValue(Bit, bitIndex:null, …) path (not RMW). The encode must be
/// symmetric with the DecodeValue path, which reads the full 16-bit word via GetInt16.
/// Through the fake factory this verifies the driver dispatches through EncodeValue with
/// the right arguments; the SetInt16/SetInt8 delta is exercised against a live PLC.
/// A Bit tag authored without /n reads as bit 0, so it writes as bit 0 through the read-modify-write; it must
/// NOT overwrite the whole word (review 2026-12-02 P-15; this test used to pin the clobbering encode).
/// </summary>
[Fact]
public async Task Bit_tag_without_suffix_writes_via_EncodeValue_not_RMW()
public async Task Bit_tag_without_suffix_read_modify_writes_bit_zero_and_keeps_the_other_bits()
{
// A Bit-typed tag with NO /N bit suffix — bitIndex is null, so write must NOT
// route through WriteBitInWordAsync (which requires bitIndex). Instead it goes
// through EncodeValue(Bit, null, value) on the tag's own runtime, not a parent runtime.
var factory = new FakeAbLegacyTagFactory();
var factory = new FakeAbLegacyTagFactory { Customise = p => new FakeAbLegacyTag(p) { Value = unchecked((short)0x00F1) } };
var drv = new AbLegacyDriver(new AbLegacyDriverOptions
{
Devices = [new AbLegacyDeviceOptions("ab://10.0.0.5/1,0")],
RawTags = AbLegacyRawTags.Entries([new AbLegacyTagDefinition("Flag", "ab://10.0.0.5/1,0", "B3:0", AbLegacyDataType.Bit)]),
RawTags = AbLegacyRawTags.Entries([new AbLegacyTagDefinition("Flag", "ab://10.0.0.5/1,0", "B3:5", AbLegacyDataType.Bit)]),
Probe = new AbLegacyProbeOptions { Enabled = false },
}, "drv-1", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
var results = await drv.WriteAsync(
[new WriteRequest("Flag", true)], CancellationToken.None);
var results = await drv.WriteAsync([new WriteRequest("Flag", false)], CancellationToken.None);
// Must succeed (Good) and route through the tag's own runtime, NOT a parent runtime.
results.Single().StatusCode.ShouldBe(AbLegacyStatusMapper.Good);
factory.Tags.ShouldContainKey("B3:0");
factory.Tags.ShouldNotContainKey("B3"); // no parent-word runtime created
factory.Tags["B3:0"].WriteCount.ShouldBe(1);
// FakeAbLegacyTag.EncodeValue stores the raw value; verify it received true.
factory.Tags["B3:0"].Value.ShouldBe(true);
Convert.ToInt32(factory.Tags["B3:5"].Value).ShouldBe(0x00F0); // only bit 0 cleared; the other seven set bits survive
factory.Tags["B3:5"].WriteCount.ShouldBe(1);
// Positive control: setting it ORs bit 0 into the current word.
await drv.WriteAsync([new WriteRequest("Flag", true)], CancellationToken.None);
Convert.ToInt32(factory.Tags["B3:5"].Value).ShouldBe(0x00F1);
}
/// <summary>A Bit tag on a file with no bit layout (F-file) has no sound write: refused, nothing written.</summary>
[Fact]
public async Task Bit_tag_on_a_float_file_without_suffix_write_is_refused_and_writes_nothing()
{
var factory = new FakeAbLegacyTagFactory();
var drv = new AbLegacyDriver(new AbLegacyDriverOptions
{
Devices = [new AbLegacyDeviceOptions("ab://10.0.0.5/1,0")],
RawTags = AbLegacyRawTags.Entries([new AbLegacyTagDefinition("Flag", "ab://10.0.0.5/1,0", "F8:0", AbLegacyDataType.Bit)]),
Probe = new AbLegacyProbeOptions { Enabled = false },
}, "drv-1", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
var results = await drv.WriteAsync([new WriteRequest("Flag", true)], CancellationToken.None);
results.Single().StatusCode.ShouldBe(AbLegacyStatusMapper.BadNotSupported);
factory.Tags.Values.Sum(t => t.WriteCount).ShouldBe(0);
}
/// <summary>Verifies that write exceptions surface as BadCommunicationError.</summary>
@@ -0,0 +1,306 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport;
using ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.PlcFamilies;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests;
/// <summary>
/// Review 2026-12-02 (slice 09) AbLegacy findings P-5 (per-tag family-type rejection + deploy gate), P-14 (bit arrays
/// sized in words), P-18 (T/C/R coalescing), P-23 f/g/h (answered-refusal classification + address cap, block-read
/// gate race, null scalar writes). P-15 (Bit write without /n) lives in <c>AbLegacyReadWriteTests</c>.
/// </summary>
[Trait("Category", "Unit")]
public sealed class AbLegacyReview20261202Tests
{
private const string Slc = "ab://10.0.0.5/1,0";
private const string Ml = "ab://10.0.0.6/";
private static AbLegacyDriver NewDriver(
FakeAbLegacyTagFactory factory, IReadOnlyList<AbLegacyDeviceOptions> devices,
AbLegacyTransport? transport = null, params AbLegacyTagDefinition[] tags) =>
new(new AbLegacyDriverOptions
{
Devices = devices,
RawTags = AbLegacyRawTags.Entries(tags),
Probe = new AbLegacyProbeOptions { Enabled = false },
Transport = transport,
}, "drv-review", factory);
// ---- P-5 ----
[Fact]
public async Task P5_one_Long_tag_on_a_MicroLogix_does_not_fault_the_other_devices_or_tags()
{
var factory = new FakeAbLegacyTagFactory { Customise = p => new FakeAbLegacyTag(p) { Value = 7 } };
var drv = NewDriver(factory,
[new AbLegacyDeviceOptions(Slc), new AbLegacyDeviceOptions(Ml, AbLegacyPlcFamily.MicroLogix)],
null,
new AbLegacyTagDefinition("Good", Slc, "N7:0", AbLegacyDataType.Int),
new AbLegacyTagDefinition("LongOnSlc", Slc, "L9:0", AbLegacyDataType.Long), // positive control: SLC has L files
new AbLegacyTagDefinition("GoodMl", Ml, "N7:1", AbLegacyDataType.Int),
new AbLegacyTagDefinition("LongOnMl", Ml, "L9:0", AbLegacyDataType.Long));
await drv.InitializeAsync("{}", CancellationToken.None); // used to throw and fault every device
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
var r = await drv.ReadAsync(["Good", "LongOnSlc", "GoodMl", "LongOnMl"], CancellationToken.None);
r[0].StatusCode.ShouldBe(AbLegacyStatusMapper.Good);
r[1].StatusCode.ShouldBe(AbLegacyStatusMapper.Good);
r[2].StatusCode.ShouldBe(AbLegacyStatusMapper.Good);
r[3].StatusCode.ShouldBe(AbLegacyStatusMapper.BadConfigurationError);
r[3].Value.ShouldBeNull();
factory.Tags.ContainsKey("L9:0").ShouldBeTrue(); // the SLC's Long created its runtime ...
drv.GetDeviceState(Ml)!.Runtimes.ContainsKey("LongOnMl").ShouldBeFalse(); // ... the rejected one never did
var report = drv.GetSkippedTags()!;
report.SkippedCount.ShouldBe(1);
report.Sample.Single().RawPath.ShouldBe("LongOnMl");
var w = await drv.WriteAsync([new WriteRequest("LongOnMl", 5)], CancellationToken.None);
w.Single().StatusCode.ShouldBe(AbLegacyStatusMapper.BadConfigurationError);
await drv.ShutdownAsync(CancellationToken.None);
}
[Fact]
public void P5_deploy_gate_flags_a_Long_on_a_MicroLogix_only_when_the_family_is_known()
{
const string longCfg = """{"address":"L9:0","dataType":"Long"}""";
AbLegacyTagDefinitionFactory.Inspect(longCfg, AbLegacyPlcFamily.MicroLogix)
.ShouldContain(w => w.Contains("Long") && w.Contains("MicroLogix") && w.Contains("BadConfigurationError"));
AbLegacyTagDefinitionFactory.Inspect(longCfg, AbLegacyPlcFamily.Plc5).ShouldNotBeEmpty();
// Controls: a family that ships L files, an unknown family and the family-less overload stay clean; and an
// Int on a MicroLogix is not touched.
AbLegacyTagDefinitionFactory.Inspect(longCfg, AbLegacyPlcFamily.Slc500).ShouldBeEmpty();
AbLegacyTagDefinitionFactory.Inspect(longCfg, family: null).ShouldBeEmpty();
AbLegacyTagDefinitionFactory.Inspect(longCfg).ShouldBeEmpty();
AbLegacyTagDefinitionFactory.Inspect("""{"address":"N7:0","dataType":"Int"}""", AbLegacyPlcFamily.MicroLogix).ShouldBeEmpty();
}
// ---- P-14 ----
[Theory]
[InlineData(256, 16)] // exactly a 16-word B3 file: used to ask for 256 words
[InlineData(33, 3)]
[InlineData(32, 2)]
[InlineData(16, 1)]
[InlineData(1, 1)]
public async Task P14_a_bit_array_is_read_in_words_and_still_decodes_every_bit(int bits, int words)
{
var created = new List<AbLegacyTagCreateParams>();
var factory = new FakeAbLegacyTagFactory
{
Customise = p =>
{
created.Add(p);
return new FakeAbLegacyTag(p) { ArrayValue = Enumerable.Range(0, bits).Select(i => i % 2 == 0).ToArray() };
},
};
var def = new AbLegacyTagDefinition("Bits", Slc, "B3:0", AbLegacyDataType.Bit, ArrayLength: bits);
var drv = NewDriver(factory, [new AbLegacyDeviceOptions(Slc)], null, def);
await drv.InitializeAsync("{}", CancellationToken.None);
var r = await drv.ReadAsync(["Bits"], CancellationToken.None);
r[0].StatusCode.ShouldBe(AbLegacyStatusMapper.Good);
((bool[])r[0].Value!).Length.ShouldBe(bits);
created.Single().ElementCount.ShouldBe(words);
await drv.ShutdownAsync(CancellationToken.None);
}
[Fact]
public void P14_non_bit_arrays_keep_their_element_count()
{
AbLegacyDriver.WireElementCount(new AbLegacyTagDefinition("W", Slc, "N7:0", AbLegacyDataType.Int, ArrayLength: 40)).ShouldBe(40);
AbLegacyDriver.WireElementCount(new AbLegacyTagDefinition("L", Slc, "L9:0", AbLegacyDataType.Long, ArrayLength: 40)).ShouldBe(40);
AbLegacyDriver.WireElementCount(new AbLegacyTagDefinition("S", Slc, "N7:0", AbLegacyDataType.Int)).ShouldBe(1);
}
// ---- P-18 ----
private static short[] TimerWords(int count) =>
[.. Enumerable.Range(0, count).SelectMany(n => new short[]
{
unchecked((short)(0x8000 | (n % 2 == 1 ? 0x2000 : 0))), // EN always; DN on odd timers
(short)(100 + n), // PRE
(short)(n * 7), // ACC
})];
private static AbLegacyTagDefinition[] TimerTags(int count) =>
[
.. Enumerable.Range(0, count).SelectMany(n => new[]
{
new AbLegacyTagDefinition($"T{n}.ACC", Slc, $"T4:{n}.ACC", AbLegacyDataType.Int),
new AbLegacyTagDefinition($"T{n}.PRE", Slc, $"T4:{n}.PRE", AbLegacyDataType.Int),
new AbLegacyTagDefinition($"T{n}.DN", Slc, $"T4:{n}.DN", AbLegacyDataType.Bit),
}),
];
[Fact]
public async Task P18_ten_timers_times_three_sub_elements_ride_one_native_read_and_decode_like_single_reads()
{
var created = new List<AbLegacyTagCreateParams>();
var factory = new FakeAbLegacyTagFactory
{
Customise = p => { lock (created) created.Add(p); return new FakeAbLegacyTag(p) { ArrayValue = TimerWords(10) }; },
};
var tags = TimerTags(10);
var drv = NewDriver(factory, [new AbLegacyDeviceOptions(Slc)], AbLegacyTransport.Native, tags);
await drv.InitializeAsync("{}", CancellationToken.None);
var r = await drv.ReadAsync([.. tags.Select(t => t.Name)], CancellationToken.None);
r.ShouldAllBe(s => s.StatusCode == AbLegacyStatusMapper.Good);
created.Count.ShouldBe(1); // 30 sub-element reads -> one block read
created[0].TagName.ShouldBe("T4:0");
created[0].ElementCount.ShouldBe(10);
for (var n = 0; n < 10; n++)
{
r[n * 3].Value.ShouldBe(n * 7); // ACC: int, as the single read returns it
r[n * 3 + 1].Value.ShouldBe(100 + n); // PRE
r[n * 3 + 2].Value.ShouldBe(n % 2 == 1); // DN: bit 13 of word 0
}
await drv.ShutdownAsync(CancellationToken.None);
}
[Fact]
public async Task P18_timer_sub_elements_keep_their_single_reads_on_the_libplctag_transport()
{
// Negative control: the 6-byte T/C/R block layout is only pinned for the native transport.
var created = new List<AbLegacyTagCreateParams>();
var factory = new FakeAbLegacyTagFactory
{
Customise = p => { lock (created) created.Add(p); return new FakeAbLegacyTag(p) { Value = (short)1 }; },
};
var tags = TimerTags(4);
var drv = NewDriver(factory, [new AbLegacyDeviceOptions(Slc)], AbLegacyTransport.Libplctag, tags);
await drv.InitializeAsync("{}", CancellationToken.None);
await drv.ReadAsync([.. tags.Select(t => t.Name)], CancellationToken.None);
created.Count.ShouldBe(12);
await drv.ShutdownAsync(CancellationToken.None);
}
[Fact]
public async Task P18_a_counter_status_bit_decodes_from_its_own_word_and_a_word_typed_status_bit_reads_0_or_1()
{
// C5:1: word0 = CU (bit 15) + OV (bit 12); PRE = 50; ACC = 51.
short[] words = [0, 0, 0, unchecked((short)(0x8000 | 0x1000)), 50, 51];
var factory = new FakeAbLegacyTagFactory { Customise = p => new FakeAbLegacyTag(p) { ArrayValue = words } };
var drv = NewDriver(factory, [new AbLegacyDeviceOptions(Slc)], AbLegacyTransport.Native,
new AbLegacyTagDefinition("cu", Slc, "C5:1.CU", AbLegacyDataType.Bit),
new AbLegacyTagDefinition("dn", Slc, "C5:1.DN", AbLegacyDataType.Bit),
new AbLegacyTagDefinition("ov", Slc, "C5:1.OV", AbLegacyDataType.Int),
new AbLegacyTagDefinition("acc", Slc, "C5:1.ACC", AbLegacyDataType.Int),
new AbLegacyTagDefinition("c0", Slc, "C5:0.PRE", AbLegacyDataType.Int));
await drv.InitializeAsync("{}", CancellationToken.None);
var r = await drv.ReadAsync(["cu", "dn", "ov", "acc", "c0"], CancellationToken.None);
r.Select(s => s.Value).ShouldBe(new object[] { true, false, 1, 51, 0 });
await drv.ShutdownAsync(CancellationToken.None);
}
// ---- P-23 f ----
[Fact]
public void P23f_only_a_refusal_the_device_sent_counts_as_an_answer()
{
// Raised locally by the native encoder / buffer (no wire involved): NOT an answer.
AbLegacyDriver.IsAnsweredRefusal(new AbTransportException(AbStatus.OutOfBounds, "PCCC field 70000 exceeds 65535.")).ShouldBeFalse();
AbLegacyDriver.IsAnsweredRefusal(new AbTransportException(AbStatus.TooLarge, "PCCC byte count")).ShouldBeFalse();
// Positive controls: the device's own reply, and libplctag's wrapped status.
AbLegacyDriver.IsAnsweredRefusal(new AbDeviceReplyException(AbStatus.OutOfBounds, "STS 0x10")).ShouldBeTrue();
AbLegacyDriver.IsAnsweredRefusal(new AbDeviceReplyException(AbStatus.Unsupported, "STS 0x10")).ShouldBeTrue();
AbLegacyDriver.IsAnsweredRefusal(
new AbTransportException(AbStatus.NotFound, "ERR_NOT_FOUND", new InvalidOperationException("libplctag"))).ShouldBeTrue();
}
[Fact]
public async Task P23f_an_element_number_that_cannot_reach_the_wire_is_a_malformed_address_not_a_wire_read()
{
AbLegacyAddress.TryParse("N7:70000").ShouldBeNull();
AbLegacyAddress.TryParse("N70000:1").ShouldBeNull();
AbLegacyAddress.TryParse("N7:65535").ShouldNotBeNull(); // boundary stays valid
var factory = new FakeAbLegacyTagFactory();
var drv = NewDriver(factory, [new AbLegacyDeviceOptions(Slc)], null,
new AbLegacyTagDefinition("Far", Slc, "N7:70000", AbLegacyDataType.Int));
await drv.InitializeAsync("{}", CancellationToken.None);
var r = await drv.ReadAsync(["Far"], CancellationToken.None);
r[0].StatusCode.ShouldBe(AbLegacyStatusMapper.BadNodeIdUnknown);
factory.Tags.ShouldBeEmpty(); // never dialled, so it can never reset a dead device's fault streak
await drv.ShutdownAsync(CancellationToken.None);
}
// ---- P-23 g ----
private sealed class DisposeAwareTag(AbLegacyTagCreateParams p) : FakeAbLegacyTag(p)
{
public override Task ReadAsync(CancellationToken ct) =>
Disposed ? throw new ObjectDisposedException("tag") : base.ReadAsync(ct);
}
[Fact]
public async Task P23g_a_coalesced_block_whose_handle_was_evicted_while_waiting_for_its_gate_is_re_resolved()
{
var factory = new FakeAbLegacyTagFactory
{
Customise = p => new DisposeAwareTag(p) { ArrayValue = new short[] { 10, 11, 12 } },
};
var drv = NewDriver(factory, [new AbLegacyDeviceOptions(Slc)], null,
new AbLegacyTagDefinition("A", Slc, "N7:0", AbLegacyDataType.Int),
new AbLegacyTagDefinition("B", Slc, "N7:2", AbLegacyDataType.Int));
await drv.InitializeAsync("{}", CancellationToken.None);
(await drv.ReadAsync(["A", "B"], CancellationToken.None)).ShouldAllBe(s => s.StatusCode == AbLegacyStatusMapper.Good);
var state = drv.GetDeviceState(Slc)!;
const string key = "|block|N7:0+3";
state.Runtimes.ContainsKey(key).ShouldBeTrue("the two tags rode one block");
var first = factory.Tags["N7:0"];
var gate = state.GetRuntimeLock(key);
await gate.WaitAsync(TestContext.Current.CancellationToken);
var atGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
state.BeforeOperationGate = k => { if (k == key) atGate.TrySetResult(); };
var read = drv.ReadAsync(["A", "B"], CancellationToken.None);
await atGate.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
// A sibling's failed call evicts and disposes the handle this reader already fetched.
state.Runtimes.TryRemove(key, out var evicted).ShouldBeTrue();
evicted!.Dispose();
gate.Release();
var r = await read;
r.ShouldAllBe(s => s.StatusCode == AbLegacyStatusMapper.Good); // used to fail every member BadCommunicationError
r[1].Value.ShouldBe(12);
factory.Tags["N7:0"].ShouldNotBeSameAs(first);
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
await drv.ShutdownAsync(CancellationToken.None);
}
// ---- P-23 h ----
[Fact]
public async Task P23h_a_null_scalar_write_is_refused_before_any_runtime_exists()
{
var factory = new FakeAbLegacyTagFactory();
var drv = NewDriver(factory, [new AbLegacyDeviceOptions(Slc)], null,
new AbLegacyTagDefinition("W", Slc, "N7:0", AbLegacyDataType.Int));
await drv.InitializeAsync("{}", CancellationToken.None);
var w = await drv.WriteAsync([new WriteRequest("W", null)], CancellationToken.None);
w.Single().StatusCode.ShouldBe(AbLegacyStatusMapper.BadTypeMismatch);
factory.Tags.ShouldBeEmpty();
// Positive control: a real value goes through the same path.
(await drv.WriteAsync([new WriteRequest("W", 5)], CancellationToken.None)).Single().StatusCode.ShouldBe(AbLegacyStatusMapper.Good);
factory.Tags["N7:0"].WriteCount.ShouldBe(1);
await drv.ShutdownAsync(CancellationToken.None);
}
}