Merge #983: AbCip dead device fails fast, BOOL arrays read in DWORDs, throttled logging, RMW lock + probe fixes
This commit is contained in:
@@ -191,7 +191,7 @@ The driver has two interchangeable wire transports, selected by one `DriverConfi
|
||||
a held connection idling out, so this shape follows a controller restart / re-download or a network gap.
|
||||
- `ConnectionSize` / `Timeout` / `AllowPacking` are honoured per pooled connection, and the **first**
|
||||
driver/device to open a given device key wins — including a Test Connect probe on a fused `admin,driver`
|
||||
node (its connection carries the probe timeout). A later opener with different options is ignored and
|
||||
node (a Test Connect probe carries its own probe timeout). The driver's own probe loop leases with the DRIVER's `Timeout` and bounds only its wait with the probe timeout (#983 P-22: it used to lease with the probe's, so a short probe timeout became every data read's). A later opener with different options is ignored and
|
||||
logged once as a Warning (`DeviceSessionPool`). ⚠️ The device key compares the **host string**, so the
|
||||
same controller addressed by DNS name in one driver and by IP in another gets two connections and two
|
||||
Forward Open throttles (up to two opens per second); address a controller the same way everywhere. ControlLogix, GuardLogix and (since T21) CompactLogix default to 4002, a Large
|
||||
@@ -517,6 +517,9 @@ UDT-typed tags found in the walk.
|
||||
|
||||
## Operational Notes
|
||||
|
||||
- **A dead device does not stall the others, and logs once (#983, review 2026-12-02 P-2/P-16).** Three layers: (1) the native request scheduler faults everything queued behind a failed *channel* exchange (timeout / closed session / failed open) with the same exception — it used to start one fresh attempt per queued batch, ~N/20 timeouts for a 1000-tag device; a request submitted afterwards is a fresh attempt, so recovery is not delayed; (2) `ReadAsync` keeps one read window **per device** and a per-call fault latch — the first connection-level failure of a device (`Timeout`/`BadConnection`/`Abort`, not a device refusal) makes that device's remaining items fail fast `BadCommunicationError` and evicts their handles, so the next poll goes through the cold-create backoff instead of the wire; (3) per-read comms failures log one Warning **per device per outage** (Debug after), a throttled create no longer logs per tag, and the first success logs one Info with the suppressed count. The latch is deliberately per call and does not open the connect backoff itself: a transient single failure must still re-create the handle on the next read (`AbCipDriverCodeReviewRegressionTests`).
|
||||
- **Whole BOOL-array reads count DWORDs (#983, P-13).** A Logix `BOOL[n]` is `ceil(n/32)` DWORDs (type `0xD3`) and a Read Tag's element count is in DWORDs; the native runtime now asks for that and, when the reply type is `0xC1` (one byte per BOOL, as `ab_server` answers), re-reads once with `n` and remembers it. **Not hardware-verified** — the unit evidence is a fake controller that refuses a 64-element read of `BOOL[64]`; the live gate is a whole read of a real `BOOL[64]`. Controller *browse* still maps symbol type `0xD3` to `Structure` (no hardware capture of the symbol-listing dims for a BOOL array exists), so browse-commit does not yet produce a correct Bool-array tag.
|
||||
- **Bit selector 0..63; whole-word writes share the RMW lock (#983, P-23).** `Tag.n` accepts 0..63 (a LINT host); the width check refuses a bit the host does not have. A whole-word write to an integer tag takes the same per-parent lock as the bit read-modify-writes of `Tag.n` (case-insensitive, like the parent runtime table), so neither can land between the other's read and write. Probe / alarm-poll intervals are floored at 100 ms at config parse (0 hot-looped, negative killed the loop). The discovered-UDT cycle guard keys on the struct *type* (template id), not the member name, so a nested member sharing its parent's name is browsed. A connection-level fault reading a program's symbol listing now aborts the browse instead of silently dropping the program.
|
||||
- **Native heap is invisible to the GC.** libplctag's native `Tag` heap does not show up in CLR allocation figures. Watch whole-process RSS, and use `ReinitializeAsync` (tears down + re-creates every device's libplctag handles) as the remediation for native-heap growth. (There is no per-driver footprint number to consult: `IDriver.GetMemoryFootprint()` was deleted as unconsumed in Gitea #525.)
|
||||
- **Handle eviction on failure** — a non-zero libplctag status or a transport exception evicts the cached tag runtime so the next read/write re-creates a fresh handle, mirroring the probe loop's recreate-on-failure behaviour.
|
||||
- **Read statuses carry the libplctag cause** — a tag the controller does not have reads `BadNodeIdUnknown` (not `BadCommunicationError`), and it does **not** open the device's connect-backoff window (the controller answered; before this, one typo throttled every sibling tag on the device). A genuine connection failure still opens it.
|
||||
|
||||
@@ -39,7 +39,7 @@ public sealed record CipReply(byte Service, byte GeneralStatus, ushort[] Extende
|
||||
r.U8(); // reserved
|
||||
var general = r.U8();
|
||||
var extWords = r.U8();
|
||||
var ext = new ushort[extWords];
|
||||
var ext = extWords == 0 ? [] : new ushort[extWords];
|
||||
for (var i = 0; i < extWords; i++) ext[i] = r.U16();
|
||||
var data = raw[r.Position..];
|
||||
return new CipReply(service, general, ext, data);
|
||||
|
||||
@@ -19,6 +19,13 @@ public static class MultipleServicePacket
|
||||
return w.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Exact byte size of an MSP carrying <paramref name="count"/> requests totalling <paramref name="totalRequestBytes"/>:
|
||||
/// the running-total form of <see cref="BuildSize(IReadOnlyList{int})"/>, so a packer need not keep a list.</summary>
|
||||
/// <param name="count">The number of embedded requests.</param>
|
||||
/// <param name="totalRequestBytes">The summed byte size of the embedded requests.</param>
|
||||
/// <returns>The total packet size in bytes.</returns>
|
||||
public static int BuildSize(int count, int totalRequestBytes) => HeaderSize + 2 + 2 * count + totalRequestBytes;
|
||||
|
||||
/// <summary>Exact byte size of an MSP carrying requests of the given sizes.</summary>
|
||||
/// <param name="requestSizes">The byte size of each embedded request.</param>
|
||||
/// <returns>The total packet size in bytes.</returns>
|
||||
|
||||
@@ -207,29 +207,28 @@ public sealed class RequestScheduler : IAsyncDisposable
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var sizes = new List<int>();
|
||||
var replySizes = new List<int>();
|
||||
var replyBudget = _channel.MaxRequestBytes; // connections are symmetric: one size bounds both directions
|
||||
// Running totals, not lists: the packer used to rebuild two Lists per pump pass and re-sum them for every
|
||||
// candidate (quadratic under the queue lock, P-24).
|
||||
var requestBytes = 0;
|
||||
var replyBytes = 0;
|
||||
var maxRequestBytes = _channel.MaxRequestBytes;
|
||||
var replyBudget = maxRequestBytes; // connections are symmetric: one size bounds both directions
|
||||
while (_queue.First is { } n)
|
||||
{
|
||||
if (batch.Count > 0)
|
||||
{
|
||||
if (!_allowPacking || n.Value.Exclusive) break;
|
||||
sizes.Add(n.Value.Request.Length);
|
||||
replySizes.Add(n.Value.ExpectedReplyBytes);
|
||||
if (MultipleServicePacket.BuildSize(sizes) > _channel.MaxRequestBytes
|
||||
|| ReplyEnvelopeSize(replySizes) > replyBudget)
|
||||
var count = batch.Count + 1;
|
||||
if (MultipleServicePacket.BuildSize(count, requestBytes + n.Value.Request.Length) > maxRequestBytes
|
||||
|| ReplyEnvelopeSize(count, replyBytes + n.Value.ExpectedReplyBytes) > replyBudget)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// The first request always goes, even when it alone exceeds the limit: it is sent
|
||||
// bare, and callers that must fit (LogixTagClient) fragment before they get here.
|
||||
sizes.Add(n.Value.Request.Length);
|
||||
replySizes.Add(n.Value.ExpectedReplyBytes);
|
||||
}
|
||||
// The first request always goes, even when it alone exceeds the limit: it is sent
|
||||
// bare, and callers that must fit (LogixTagClient) fragment before they get here.
|
||||
requestBytes += n.Value.Request.Length;
|
||||
replyBytes += n.Value.ExpectedReplyBytes;
|
||||
batch.Add(n.Value);
|
||||
_queue.RemoveFirst();
|
||||
if (n.Value.Exclusive) break;
|
||||
@@ -248,6 +247,13 @@ public sealed class RequestScheduler : IAsyncDisposable
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>Running-total form of <see cref="ReplyEnvelopeSize(IReadOnlyList{int})"/>.</summary>
|
||||
/// <param name="count">The number of embedded replies.</param>
|
||||
/// <param name="totalReplyBytes">The summed expected size of the embedded replies.</param>
|
||||
/// <returns>The total size of the MSP reply in bytes.</returns>
|
||||
internal static int ReplyEnvelopeSize(int count, int totalReplyBytes) =>
|
||||
ReplyHeaderBytes + 2 + 2 * count + totalReplyBytes;
|
||||
|
||||
private async Task PumpAsync()
|
||||
{
|
||||
while (true)
|
||||
@@ -295,19 +301,34 @@ public sealed class RequestScheduler : IAsyncDisposable
|
||||
|
||||
private async Task ExecuteAsync(List<Pending> batch)
|
||||
{
|
||||
// True once the CHANNEL (not a reply parse / envelope check) failed: a connection-level fault.
|
||||
var channelFailed = false;
|
||||
async Task<ReadOnlyMemory<byte>> SendOnChannelAsync(ReadOnlyMemory<byte> request)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Never a waiter's token (B2).
|
||||
return await _channel.SendAsync(request, _stop.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception) when (!_stop.IsCancellationRequested)
|
||||
{
|
||||
channelFailed = true;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (batch.Count == 1)
|
||||
{
|
||||
// Never a waiter's token (B2).
|
||||
var raw = await _channel.SendAsync(batch[0].Request, _stop.Token).ConfigureAwait(false);
|
||||
var raw = await SendOnChannelAsync(batch[0].Request).ConfigureAwait(false);
|
||||
batch[0].Succeed(CipReply.Parse(raw), this);
|
||||
return;
|
||||
}
|
||||
|
||||
var requests = new List<byte[]>(batch.Count);
|
||||
foreach (var b in batch) requests.Add(b.Request);
|
||||
var envelopeRaw = await _channel.SendAsync(MultipleServicePacket.Build(requests), _stop.Token).ConfigureAwait(false);
|
||||
var envelopeRaw = await SendOnChannelAsync(MultipleServicePacket.Build(requests)).ConfigureAwait(false);
|
||||
var envelope = CipReply.Parse(envelopeRaw);
|
||||
if (envelope.Service != MultipleServiceCode)
|
||||
throw new AbTransportException(AbStatus.BadReply, $"MSP reply carries service 0x{envelope.Service:X2}.");
|
||||
@@ -325,14 +346,35 @@ public sealed class RequestScheduler : IAsyncDisposable
|
||||
catch (AbTransportException ex)
|
||||
{
|
||||
foreach (var b in batch) b.Fail(ex, this);
|
||||
if (channelFailed) FailQueued(ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var wrapped = new AbTransportException(AbStatus.BadConnection, $"CIP exchange failed: {ex.Message}", ex);
|
||||
foreach (var b in batch) b.Fail(wrapped, this);
|
||||
if (channelFailed) FailQueued(wrapped);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-2: the channel failed (timeout, closed session, failed open). Every request already queued behind
|
||||
/// the failed batch would otherwise start its OWN attempt against the same dead peer, each paying a
|
||||
/// timeout or a throttled re-open, so a 1000-tag device took N batches x timeout to give up. They are
|
||||
/// faulted with the same exception now; a request submitted AFTER this point is a fresh attempt and
|
||||
/// reopens the session as usual, so recovery is not delayed.
|
||||
/// </summary>
|
||||
/// <param name="error">The channel failure shared with every queued waiter.</param>
|
||||
private void FailQueued(Exception error)
|
||||
{
|
||||
List<Pending> queued;
|
||||
lock (_lock)
|
||||
{
|
||||
queued = [.. _queue];
|
||||
_queue.Clear();
|
||||
}
|
||||
foreach (var q in queued) q.Fail(error, this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The error a waiter sees when the scheduler (i.e. its connection) goes away under it. Deliberately
|
||||
/// NOT an <see cref="OperationCanceledException"/>: upstream treats OCE as "the caller unsubscribed"
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
@@ -911,13 +919,13 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
// and written once after the batch: an inline write to the shared _health field would race.
|
||||
var maxConcurrent = ReadWindow;
|
||||
var outcomes = new ReadOutcome[itemCount];
|
||||
using var window = new SemaphoreSlim(maxConcurrent, maxConcurrent);
|
||||
using var batch = new ReadBatch(maxConcurrent);
|
||||
var tasks = new Task[itemCount];
|
||||
for (var i = 0; i < itemCount; i++)
|
||||
tasks[i] = RunItemAsync(i);
|
||||
|
||||
// Task.WhenAll completes only once EVERY item has finished (it does not short-circuit on the
|
||||
// first fault), so disposing the window on the way out can never pull the semaphore out from
|
||||
// first fault), so disposing the windows on the way out can never pull a semaphore out from
|
||||
// under an item still waiting on it.
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
|
||||
@@ -931,15 +939,97 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
{
|
||||
if (slot < groups.Count)
|
||||
{
|
||||
outcomes[slot] = await ReadGroupAsync(groups[slot], results, now, window, cancellationToken)
|
||||
outcomes[slot] = await ReadGroupAsync(groups[slot], results, now, batch, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
NoteDeviceOutcome(groups[slot].ParentDefinition.DeviceHostAddress, outcomes[slot]);
|
||||
}
|
||||
else
|
||||
{
|
||||
var fb = fallbacks[slot - groups.Count];
|
||||
outcomes[slot] = await ReadSingleAsync(
|
||||
fb, fullReferences[fb.OriginalIndex], results, now, window, cancellationToken)
|
||||
fb, fullReferences[fb.OriginalIndex], results, now, batch, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (_resolver.TryResolve(fullReferences[fb.OriginalIndex], out var fbDef))
|
||||
NoteDeviceOutcome(fbDef.DeviceHostAddress, outcomes[slot]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Per-<see cref="ReadAsync"/>-call state. (1) A read window PER DEVICE: every device has its own request
|
||||
/// scheduler, so a shared window let one dead device's in-flight items hold every slot for a full timeout while
|
||||
/// a healthy device's items waited behind them (P-2). (2) A per-device fault latch: the first connection-level
|
||||
/// failure of a device in this call makes that device's remaining items fail fast, once they get their turn,
|
||||
/// instead of each paying its own timeout / throttled re-open against the same dead peer.
|
||||
/// </summary>
|
||||
private sealed class ReadBatch(int windowSize) : IDisposable
|
||||
{
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<DeviceState, SemaphoreSlim> _windows = new();
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<DeviceState, string> _faulted = new();
|
||||
|
||||
/// <summary>The bounded-parallel window for <paramref name="device"/>.</summary>
|
||||
/// <param name="device">The device.</param>
|
||||
/// <returns>The device's window.</returns>
|
||||
public SemaphoreSlim WindowFor(DeviceState device) =>
|
||||
_windows.GetOrAdd(device, _ => new SemaphoreSlim(windowSize, windowSize));
|
||||
|
||||
/// <summary>True when a connection-level failure of <paramref name="device"/> was already seen in this call.</summary>
|
||||
/// <param name="device">The device.</param>
|
||||
/// <param name="reason">The first failure's message.</param>
|
||||
/// <returns><see langword="true"/> when the device is latched.</returns>
|
||||
public bool IsFaulted(DeviceState device, out string reason)
|
||||
{
|
||||
if (_faulted.TryGetValue(device, out var r)) { reason = r; return true; }
|
||||
reason = string.Empty;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Latches <paramref name="device"/> for the rest of this call (first reason wins).</summary>
|
||||
/// <param name="device">The device.</param>
|
||||
/// <param name="reason">The failure message.</param>
|
||||
/// <returns><see langword="true"/> when this call latched the device (it was not latched yet).</returns>
|
||||
public bool Latch(DeviceState device, string reason) => _faulted.TryAdd(device, reason);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var w in _windows.Values) w.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets a device's outage-log state when one of its reads proved it reachable (a read that succeeded or
|
||||
/// was answered with a refusal), logging one Info that carries the suppressed-warning count (P-16).
|
||||
/// </summary>
|
||||
private void NoteDeviceOutcome(string deviceHostAddress, ReadOutcome outcome)
|
||||
{
|
||||
if (outcome.State != DriverState.Healthy && !outcome.Answered) return;
|
||||
if (!_devicesByRoutingKey.TryGetValue(deviceHostAddress, out var device)) return;
|
||||
if (device.EndOutage(out var suppressed))
|
||||
_logger.LogInformation(
|
||||
"AbCip device {Device} is reachable again; {Suppressed} per-read failure warning(s) were suppressed during the outage",
|
||||
deviceHostAddress, suppressed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs a per-read comms failure at Warning ONCE per device per outage (with the exception), and at Debug for
|
||||
/// every further one: a dead 1000-tag device used to emit ~1000 Warnings with stack traces per poll (P-16).
|
||||
/// </summary>
|
||||
private void LogReadFault(DeviceState device, Exception? ex, string message, params object?[] args)
|
||||
{
|
||||
if (device.TryBeginOutageWarning())
|
||||
{
|
||||
// Logged once per outage; every further failure is Debug until the device answers again.
|
||||
if (ex is null) _logger.LogWarning(message, args);
|
||||
else _logger.LogWarning(ex, message, args);
|
||||
}
|
||||
else
|
||||
{
|
||||
device.CountSuppressedWarning();
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
if (ex is null) _logger.LogDebug(message, args);
|
||||
else _logger.LogDebug(ex, message, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1042,7 +1132,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
|
||||
private async Task<ReadOutcome> ReadSingleAsync(
|
||||
AbCipUdtReadFallback fb, string reference, DataValueSnapshot[] results, DateTime now,
|
||||
SemaphoreSlim window, CancellationToken ct)
|
||||
ReadBatch batch, CancellationToken ct)
|
||||
{
|
||||
if (!_resolver.TryResolve(reference, out var def))
|
||||
{
|
||||
@@ -1069,6 +1159,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
var runtime = await EnsureTagRuntimeAsync(device, def, ct).ConfigureAwait(false);
|
||||
|
||||
// Window slot only now that the runtime exists (see ReadAsync); a wait that throws never acquired.
|
||||
var window = batch.WindowFor(device);
|
||||
await window.WaitAsync(ct).ConfigureAwait(false);
|
||||
// Serialise Read → GetStatus → Decode against the shared runtime — the cached libplctag
|
||||
// Tag handle is not concurrency-safe and GetStatus returns the LAST op's status.
|
||||
@@ -1078,6 +1169,16 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
await opLock.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// P-2: an earlier item of THIS call already proved the device's connection dead — fail fast
|
||||
// instead of paying another timeout, and drop the handle so the next poll goes through the
|
||||
// cold-create backoff rather than the wire.
|
||||
if (batch.IsFaulted(device, out var latched))
|
||||
{
|
||||
EvictRuntime(device, def.Name);
|
||||
results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now);
|
||||
return ReadOutcome.Degraded(latched);
|
||||
}
|
||||
|
||||
await runtime.ReadAsync(ct).ConfigureAwait(false);
|
||||
|
||||
var status = runtime.GetStatus();
|
||||
@@ -1110,11 +1211,13 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
EvictRuntime(device, def.Name);
|
||||
results[fb.OriginalIndex] = new DataValueSnapshot(null,
|
||||
AbCipStatusMapper.MapStatus(status), null, now);
|
||||
_logger.LogWarning(
|
||||
var statusMessage = $"transport status {status} reading {reference}";
|
||||
if (AbCipRefusals.IsConnectionFault(status)) batch.Latch(device, statusMessage);
|
||||
LogReadFault(device, null,
|
||||
"AbCip read returned non-zero transport status {Status} for tag {Tag} on device {Device}; " +
|
||||
"evicting cached runtime so next call re-creates it",
|
||||
status, reference, def.DeviceHostAddress);
|
||||
return ReadOutcome.Degraded($"transport status {status} reading {reference}");
|
||||
return ReadOutcome.Degraded(statusMessage);
|
||||
}
|
||||
|
||||
var tagPath = AbCipTagPath.TryParse(def.TagPath);
|
||||
@@ -1207,6 +1310,17 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now);
|
||||
return ReadOutcome.None;
|
||||
}
|
||||
catch (ConnectionThrottledException throttled)
|
||||
{
|
||||
// P-16: the device's connect backoff window is open — an expected state, not a per-tag event. No
|
||||
// eviction (nothing cached) and no stack trace; one Warning per device per outage (shared with the
|
||||
// failure that opened the window), Debug after.
|
||||
results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now);
|
||||
LogReadFault(device, null,
|
||||
"AbCip reads on device {Device} are throttled while its connect backoff window is open: {Reason}",
|
||||
def.DeviceHostAddress, throttled.Message);
|
||||
return ReadOutcome.Degraded(throttled.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Transport exception — evict so the next read creates a fresh handle. An AbTransportException
|
||||
@@ -1215,7 +1329,8 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
EvictRuntime(device, def.Name);
|
||||
results[fb.OriginalIndex] = new DataValueSnapshot(null,
|
||||
AbCipStatusMapper.MapException(ex), null, now);
|
||||
_logger.LogWarning(ex,
|
||||
if (AbCipRefusals.IsConnectionFault(ex)) batch.Latch(device, ex.Message);
|
||||
LogReadFault(device, ex,
|
||||
"AbCip read transport exception for tag {Tag} on device {Device}",
|
||||
reference, def.DeviceHostAddress);
|
||||
return ReadOutcome.Degraded(ex.Message);
|
||||
@@ -1230,7 +1345,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
/// per-tag fallback list are unaffected.
|
||||
/// </summary>
|
||||
private async Task<ReadOutcome> ReadGroupAsync(
|
||||
AbCipUdtReadGroup group, DataValueSnapshot[] results, DateTime now, SemaphoreSlim window, CancellationToken ct)
|
||||
AbCipUdtReadGroup group, DataValueSnapshot[] results, DateTime now, ReadBatch batch, CancellationToken ct)
|
||||
{
|
||||
var parent = group.ParentDefinition;
|
||||
|
||||
@@ -1245,6 +1360,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
var runtime = await EnsureTagRuntimeAsync(device, parent, ct).ConfigureAwait(false);
|
||||
|
||||
// Window slot only now that the runtime exists (see ReadAsync); a wait that throws never acquired.
|
||||
var window = batch.WindowFor(device);
|
||||
await window.WaitAsync(ct).ConfigureAwait(false);
|
||||
// Serialise the whole-UDT Read → GetStatus → per-member DecodeValueAt against the shared
|
||||
// parent runtime — the members decode from that one handle's buffer.
|
||||
@@ -1254,6 +1370,14 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
await opLock.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// P-2: see ReadSingleAsync — an earlier item of this call already proved the connection dead.
|
||||
if (batch.IsFaulted(device, out var latched))
|
||||
{
|
||||
EvictRuntime(device, parent.Name);
|
||||
StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError);
|
||||
return ReadOutcome.Degraded(latched);
|
||||
}
|
||||
|
||||
await runtime.ReadAsync(ct).ConfigureAwait(false);
|
||||
|
||||
var status = runtime.GetStatus();
|
||||
@@ -1278,11 +1402,13 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
EvictRuntime(device, parent.Name);
|
||||
var mapped = AbCipStatusMapper.MapStatus(status);
|
||||
StampGroupStatus(group, results, now, mapped);
|
||||
_logger.LogWarning(
|
||||
var statusMessage = $"transport status {status} reading UDT {group.ParentName}";
|
||||
if (AbCipRefusals.IsConnectionFault(status)) batch.Latch(device, statusMessage);
|
||||
LogReadFault(device, null,
|
||||
"AbCip whole-UDT read returned non-zero transport status {Status} for parent {Parent} " +
|
||||
"on device {Device}; {MemberCount} member values stamped with mapped status",
|
||||
status, group.ParentName, parent.DeviceHostAddress, group.Members.Count);
|
||||
return ReadOutcome.Degraded($"transport status {status} reading UDT {group.ParentName}");
|
||||
return ReadOutcome.Degraded(statusMessage);
|
||||
}
|
||||
|
||||
foreach (var member in group.Members)
|
||||
@@ -1344,11 +1470,21 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError);
|
||||
return ReadOutcome.None;
|
||||
}
|
||||
catch (ConnectionThrottledException throttled)
|
||||
{
|
||||
// P-16: see ReadSingleAsync — a throttled create is not a per-parent Warning.
|
||||
StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError);
|
||||
LogReadFault(device, null,
|
||||
"AbCip reads on device {Device} are throttled while its connect backoff window is open: {Reason}",
|
||||
parent.DeviceHostAddress, throttled.Message);
|
||||
return ReadOutcome.Degraded(throttled.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
EvictRuntime(device, parent.Name);
|
||||
StampGroupStatus(group, results, now, AbCipStatusMapper.MapException(ex));
|
||||
_logger.LogWarning(ex,
|
||||
if (AbCipRefusals.IsConnectionFault(ex)) batch.Latch(device, ex.Message);
|
||||
LogReadFault(device, ex,
|
||||
"AbCip whole-UDT read transport exception for parent {Parent} on device {Device}",
|
||||
group.ParentName, parent.DeviceHostAddress);
|
||||
return ReadOutcome.Degraded(ex.Message);
|
||||
@@ -1466,7 +1602,22 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
// Serialise Encode → Write → GetStatus against the shared runtime — the same cached
|
||||
// Tag handle may be in use by a concurrent ReadAsync or poll loop.
|
||||
var opLock = device.GetRuntimeLock(def.Name);
|
||||
await opLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
// P-23a: a whole-word write to an integer tag shares the read-modify-write lock of its bit writers
|
||||
// (`Flags.3`): both address the same controller word through DIFFERENT runtimes, so without it a bit
|
||||
// RMW's read-then-write could land over a whole-word write made between them (lost update).
|
||||
var hostLock = arrayElements is null && parsedPath is { BitIndex: null } && IsIntegerHostType(def.DataType)
|
||||
? device.GetRmwLock(parsedPath.ToLibplctagName())
|
||||
: null;
|
||||
if (hostLock is not null) await hostLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await opLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
hostLock?.Release();
|
||||
throw;
|
||||
}
|
||||
int status;
|
||||
uint? refusal;
|
||||
int size;
|
||||
@@ -1497,6 +1648,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
finally
|
||||
{
|
||||
opLock.Release();
|
||||
hostLock?.Release();
|
||||
}
|
||||
|
||||
if (refusal is { } refused)
|
||||
@@ -1687,6 +1839,11 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True for the integer types a bit selector (<c>Tag.n</c>) can address, i.e. a possible RMW host.</summary>
|
||||
private static bool IsIntegerHostType(AbCipDataType type) => type is AbCipDataType.SInt or AbCipDataType.USInt
|
||||
or AbCipDataType.Int or AbCipDataType.UInt or AbCipDataType.DInt or AbCipDataType.UDInt
|
||||
or AbCipDataType.LInt or AbCipDataType.ULInt;
|
||||
|
||||
/// <summary>
|
||||
/// Read-modify-write one bit within an integer parent (SINT / INT / DINT / LINT — Logix allows <c>.n</c> on
|
||||
/// each). Creates / reuses a parallel parent runtime (distinct from the bit-selector handle) + serialises
|
||||
@@ -2092,7 +2249,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
() => capturedDiscoveredFolder.Folder(fullName, discovered.Name));
|
||||
var anyEmitted = await FanOutDiscoveredUdtMembersAsync(
|
||||
udtFolder, device.HostAddress, fullName, shape, discovered.ReadOnly,
|
||||
depth: 1, emitted, visited: [discovered.Name], cancellationToken)
|
||||
depth: 1, emitted, visited: [StructKey(discovered.TemplateInstanceId, discovered.Name)], cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (anyEmitted) continue; // expanded — don't emit the placeholder Variable
|
||||
// Empty shape (no usable atomic leaf): degrade to a single Variable below.
|
||||
@@ -2205,6 +2362,18 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
return size == width * Math.Max(1, def.ElementCount) ? null : AbCipStatusMapper.BadTypeMismatch;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The cycle-guard key of a struct on the fan-out path: its template instance id when the controller supplied
|
||||
/// one (identity of the struct TYPE), else its name (seeded / test shapes carry none). Keying on the member
|
||||
/// NAME alone skipped a legitimate member whose nested type happened to contain a member of the same name
|
||||
/// (P-23d) — only a true re-entry of the same struct type is cyclic.
|
||||
/// </summary>
|
||||
/// <param name="templateInstanceId">The struct's CIP template instance id, if known.</param>
|
||||
/// <param name="name">The member / tag name, the fallback key.</param>
|
||||
/// <returns>The guard key.</returns>
|
||||
private static string StructKey(uint? templateInstanceId, string name) =>
|
||||
templateInstanceId is { } id ? $"tpl:{id}" : $"name:{name}";
|
||||
|
||||
/// <summary>
|
||||
/// Recursively fan a controller-discovered UDT shape out into Variable nodes — one per
|
||||
/// ATOMIC leaf — under the folder produced by <paramref name="folder"/>. Mirrors the
|
||||
@@ -2280,7 +2449,8 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
// live a level deeper, so the cap is checked against depth + 1.
|
||||
if (member.ArrayLength > 1) continue;
|
||||
if (depth + 1 > MaxUdtDepth) continue;
|
||||
if (!visited.Add(member.Name)) continue; // cyclic UDT reference — stop here
|
||||
var structKey = StructKey(member.NestedTemplateId, member.Name);
|
||||
if (!visited.Add(structKey)) continue; // cyclic UDT reference (same struct TYPE already on this path) — stop here
|
||||
if (nested is not null)
|
||||
{
|
||||
// Materialise the nested sub-folder lazily under the parent folder (itself lazy),
|
||||
@@ -2294,7 +2464,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
.ConfigureAwait(false);
|
||||
anyEmitted |= nestedEmitted;
|
||||
}
|
||||
visited.Remove(member.Name);
|
||||
visited.Remove(structKey);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -2438,6 +2608,30 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public SemaphoreSlim ConnectGate { get; } = new(1, 1);
|
||||
|
||||
private int _outageWarned;
|
||||
private int _suppressedWarnings;
|
||||
|
||||
/// <summary>
|
||||
/// True for the FIRST per-read failure of an outage (the caller logs it at Warning); false for every
|
||||
/// further one until <see cref="EndOutage"/> (P-16).
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when the caller should log at Warning.</returns>
|
||||
public bool TryBeginOutageWarning() => Interlocked.CompareExchange(ref _outageWarned, 1, 0) == 0;
|
||||
|
||||
/// <summary>Counts one failure that was logged below Warning because the outage was already announced.</summary>
|
||||
public void CountSuppressedWarning() => Interlocked.Increment(ref _suppressedWarnings);
|
||||
|
||||
/// <summary>Ends the outage: the device answered. Returns whether one was open, and how many warnings it suppressed.</summary>
|
||||
/// <param name="suppressed">The suppressed-warning count of the outage that ended.</param>
|
||||
/// <returns><see langword="true"/> when an outage was open.</returns>
|
||||
public bool EndOutage(out int suppressed)
|
||||
{
|
||||
suppressed = 0;
|
||||
if (Interlocked.Exchange(ref _outageWarned, 0) == 0) return false;
|
||||
suppressed = Interlocked.Exchange(ref _suppressedWarnings, 0);
|
||||
return true;
|
||||
}
|
||||
/// <summary>Gets or sets the current host state of this device.</summary>
|
||||
public HostState HostState { get; set; } = HostState.Unknown;
|
||||
/// <summary>Gets or sets the UTC timestamp when the host state was last changed.</summary>
|
||||
@@ -2478,7 +2672,10 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
|
||||
public System.Collections.Concurrent.ConcurrentDictionary<string, IAbCipTagRuntime> ParentRuntimes { get; } =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, SemaphoreSlim> _rmwLocks = new();
|
||||
// OrdinalIgnoreCase like ParentRuntimes: `Flags.3` and `FLAGS.4` share one parent runtime, so they must share
|
||||
// its lock (P-23a — a case-sensitive key gave them two locks over one handle: a lost update).
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, SemaphoreSlim> _rmwLocks =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Gets or creates a semaphore for coordinating RMW (read-modify-write) operations on a parent tag.</summary>
|
||||
/// <param name="parentTagName">The name of the parent tag.</param>
|
||||
|
||||
@@ -98,7 +98,7 @@ public static class AbCipDriverFactoryExtensions
|
||||
Probe = new AbCipProbeOptions
|
||||
{
|
||||
Enabled = dto.Probe?.Enabled ?? true,
|
||||
Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000),
|
||||
Interval = IntervalOrDefault(dto.Probe?.IntervalMs, 5_000),
|
||||
Timeout = PositiveTimeoutOrDefault(dto.Probe?.TimeoutMs, 2_000),
|
||||
ProbeTagPath = dto.Probe?.ProbeTagPath,
|
||||
},
|
||||
@@ -111,7 +111,7 @@ public static class AbCipDriverFactoryExtensions
|
||||
EnableControllerBrowse = dto.EnableControllerBrowse ?? false,
|
||||
BrowsePageDelay = TimeSpan.FromMilliseconds(Math.Max(0, dto.BrowsePageDelayMs ?? 5)),
|
||||
EnableAlarmProjection = dto.EnableAlarmProjection ?? false,
|
||||
AlarmPollInterval = TimeSpan.FromMilliseconds(dto.AlarmPollIntervalMs ?? 1_000),
|
||||
AlarmPollInterval = IntervalOrDefault(dto.AlarmPollIntervalMs, 1_000),
|
||||
EnableDeclarationOnlyUdtGrouping = dto.EnableDeclarationOnlyUdtGrouping ?? false,
|
||||
MaxConcurrentReads = dto.MaxConcurrentReads ?? 8,
|
||||
};
|
||||
@@ -131,6 +131,19 @@ public static class AbCipDriverFactoryExtensions
|
||||
private static TimeSpan PositiveTimeoutOrDefault(int? ms, int defaultMs) =>
|
||||
TimeSpan.FromMilliseconds(ms is int v and > 0 ? v : defaultMs);
|
||||
|
||||
/// <summary>Floor on a loop interval (probe / alarm poll): 0 would hot-loop against the PLC, a negative value makes <c>Task.Delay</c> throw out of the loop (P-23c).</summary>
|
||||
internal const int MinIntervalMs = 100;
|
||||
|
||||
/// <summary>
|
||||
/// Maps an operator-supplied loop interval (ms): null ⇒ <paramref name="defaultMs"/>, anything below
|
||||
/// <see cref="MinIntervalMs"/> (zero, negative) is clamped up to it.
|
||||
/// </summary>
|
||||
/// <param name="ms">The operator-supplied interval in milliseconds, or null.</param>
|
||||
/// <param name="defaultMs">The default applied when <paramref name="ms"/> is null.</param>
|
||||
/// <returns>An interval of at least <see cref="MinIntervalMs"/>.</returns>
|
||||
private static TimeSpan IntervalOrDefault(int? ms, int defaultMs) =>
|
||||
TimeSpan.FromMilliseconds(Math.Max(MinIntervalMs, ms ?? defaultMs));
|
||||
|
||||
// tagName null = a driver-level (or device-level) config field: the error text names the driver config,
|
||||
// not a tag. Never pass a placeholder like "device" as tagName — it renders as "tag 'device'".
|
||||
private static T ParseEnum<T>(string? raw, string? tagName, string driverInstanceId, string field,
|
||||
|
||||
@@ -28,6 +28,31 @@ internal static class AbCipRefusals
|
||||
or AbStatus.NotAllowed or AbStatus.TooLarge or AbStatus.TooSmall or AbStatus.TypeMismatch
|
||||
or AbStatus.Unsupported;
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="status"/> proves the CONNECTION failed (timeout, closed / unreachable session,
|
||||
/// aborted open) rather than one tag: every other tag on the same device would fail the same way (P-2).
|
||||
/// </summary>
|
||||
/// <param name="status">The transport status.</param>
|
||||
/// <returns><see langword="true"/> for a connection-level fault.</returns>
|
||||
public static bool IsConnectionFault(AbStatus status) => status is AbStatus.Timeout or AbStatus.BadConnection
|
||||
or AbStatus.Abort;
|
||||
|
||||
/// <summary>True when <paramref name="status"/> (an <see cref="AbStatus"/> value) is a connection-level fault.</summary>
|
||||
/// <param name="status">The runtime status word.</param>
|
||||
/// <returns><see langword="true"/> for a connection-level fault.</returns>
|
||||
public static bool IsConnectionFault(int status) => IsConnectionFault((AbStatus)status);
|
||||
|
||||
/// <summary>True when <paramref name="ex"/> is a connection-level failure (see <see cref="IsConnectionFault(AbStatus)"/>).</summary>
|
||||
/// <param name="ex">The exception.</param>
|
||||
/// <returns><see langword="true"/> for a connection-level fault.</returns>
|
||||
public static bool IsConnectionFault(Exception ex) => ex switch
|
||||
{
|
||||
AbCipLocalRefusalException => false,
|
||||
AbTransportException ate => IsConnectionFault(ate.Status),
|
||||
System.Net.Sockets.SocketException or IOException or TimeoutException => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>True when <paramref name="status"/> (an <see cref="AbStatus"/> value) is a device refusal.</summary>
|
||||
/// <param name="status">The runtime status word.</param>
|
||||
/// <returns><see langword="true"/> for a deterministic device refusal.</returns>
|
||||
|
||||
@@ -87,7 +87,7 @@ public sealed record AbCipTagPath(
|
||||
|
||||
int? bitIndex = null;
|
||||
if (parts.Count >= 2 && int.TryParse(parts[^1], out var maybeBit)
|
||||
&& maybeBit is >= 0 and <= 31
|
||||
&& maybeBit is >= 0 and <= 63
|
||||
&& !parts[^1].Contains('['))
|
||||
{
|
||||
bitIndex = maybeBit;
|
||||
|
||||
@@ -158,18 +158,28 @@ internal sealed class NativeAbCipTagEnumeratorFactory : IAbCipTagEnumeratorFacto
|
||||
/// <summary>Bounded lease release shared by the native enumerator and template reader.</summary>
|
||||
internal static class NativeLease
|
||||
{
|
||||
/// <summary>Upper bound on waiting for the lease release (and its Forward Close).</summary>
|
||||
private static readonly TimeSpan DisposeWait = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>Releases, waiting at most 2 s; never throws, whatever the release delegate does.</summary>
|
||||
/// <summary>
|
||||
/// Starts the lease release and returns WITHOUT waiting for its Forward Close; never throws, whatever the
|
||||
/// release delegate does (P-24: this used to block a thread-pool thread for up to 2 s per browse / template
|
||||
/// read, from an async iterator's <c>finally</c>). Nothing is lost by not waiting: the pool's release does its
|
||||
/// bookkeeping synchronously (ref-count drop, closing-chain registration) before its first await, so an
|
||||
/// acquire made the next instant still opens only after this close — the same guarantee
|
||||
/// <see cref="ConnectionLease.ReleaseInBackground"/> gives the tag runtimes.
|
||||
/// </summary>
|
||||
/// <param name="release">The delegate that releases the lease.</param>
|
||||
/// <param name="logger">The logger used to report a failed release.</param>
|
||||
public static void ReleaseBounded(Func<ValueTask> release, ILogger logger)
|
||||
{
|
||||
try { release().AsTask().Wait(DisposeWait); }
|
||||
Task teardown;
|
||||
try { teardown = release().AsTask(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Releasing the native AbCip device lease failed.");
|
||||
return;
|
||||
}
|
||||
_ = teardown.ContinueWith(
|
||||
t => logger.LogWarning(t.Exception, "Releasing the native AbCip device lease failed."),
|
||||
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, ReplyBytesPerElementHint()).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,40 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The reply bytes per element the scheduler budgets this read at. A scalar's width is static; a Structure (or an
|
||||
/// unknown authored type, e.g. the probe) has none, which used to send EVERY such read alone — N UDT parents cost
|
||||
/// N round trips per poll instead of ~N/20 (P-24). Once one read has returned, its size is the hint. An
|
||||
/// under-estimate (the UDT grew in an online edit) is safe: the controller answers Partial and the client's
|
||||
/// fragment loop completes the read.
|
||||
/// </summary>
|
||||
/// <returns>Bytes per element, or 0 when nothing is known (the read is then sent alone).</returns>
|
||||
private int ReplyBytesPerElementHint()
|
||||
{
|
||||
var known = ExpectedElementBytes(_p.AuthoredType);
|
||||
if (known > 0 || _data.Length == 0) return known;
|
||||
return (_data.Length + _wireElements - 1) / _wireElements;
|
||||
}
|
||||
|
||||
/// <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 +748,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -57,10 +57,13 @@ internal sealed class SymbolListingEnumerator : IAbCipTagEnumerator
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception)
|
||||
catch (Exception ex) when (!AbCipRefusals.IsConnectionFault(ex))
|
||||
{
|
||||
// A refusal (the controller answered "no" for this program) or a listing that cannot be read: skip it.
|
||||
continue;
|
||||
}
|
||||
// A connection-level fault (timeout, closed session, I/O) is NOT "this program is unreadable" — the rest of
|
||||
// the listing would be silently missing with no log (P-23e) — so it propagates and the browse reports it.
|
||||
|
||||
foreach (var tag in CipSymbolObjectDecoder.Decode(programBuffer, programScope: program))
|
||||
yield return tag;
|
||||
|
||||
+25
@@ -200,6 +200,31 @@ public sealed class RequestSchedulerTests
|
||||
(await s.SendAsync(Req(8, 3), CancellationToken.None).WaitAsync(Timeout, Ct)).GeneralStatus.ShouldBe((byte)0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Channel_failure_faults_everything_queued_behind_it_without_further_attempts()
|
||||
{
|
||||
// P-2: a dead peer used to cost one timeout / throttled re-open PER queued batch.
|
||||
var ch = new FakeCipChannel(maxRequestBytes: 64); // small budget: 200 requests would be many batches
|
||||
await using var s = new RequestScheduler(ch, allowPacking: true);
|
||||
var a = await HoldFirstAsync(s, ch, Req(8, 0));
|
||||
var boom = new AbTransportException(AbStatus.Timeout, "reply timeout");
|
||||
ch.Respond = _ => Task.FromException<byte[]>(boom);
|
||||
var queued = Enumerable.Range(1, 200).Select(i => s.SendAsync(Req(8, (byte)i), CancellationToken.None)).ToList();
|
||||
s.QueuedCount.ShouldBe(200);
|
||||
ch.Gate!.SetResult();
|
||||
|
||||
(await Should.ThrowAsync<AbTransportException>(() => a.WaitAsync(Timeout, Ct))).ShouldBeSameAs(boom);
|
||||
foreach (var q in queued)
|
||||
(await Should.ThrowAsync<AbTransportException>(() => q.WaitAsync(Timeout, Ct))).ShouldBeSameAs(boom);
|
||||
ch.SentCount.ShouldBe(1); // only the in-flight exchange ever reached the dead channel
|
||||
s.QueuedCount.ShouldBe(0);
|
||||
|
||||
// Positive control: a request submitted AFTER the failure is a fresh attempt (recovery is not delayed).
|
||||
ch.Respond = ch.DefaultRespond;
|
||||
(await s.SendAsync(Req(8, 9), CancellationToken.None).WaitAsync(Timeout, Ct)).GeneralStatus.ShouldBe((byte)0);
|
||||
ch.SentCount.ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_non_transport_channel_exception_is_wrapped_and_shared_by_the_batch()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.AbCip;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Review 2026-12-02 P-2 / P-16 (#983): one dead device in a multi-device read must not stall the healthy ones
|
||||
/// (warm handles used to bypass every backoff; each of N tags paid its own timeout), and a dead device must not
|
||||
/// log one Warning with a stack trace per tag per poll.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class AbCipDeadDeviceBatchTests
|
||||
{
|
||||
private const string DevA = "ab://10.0.0.5/1,0";
|
||||
private const string DevB = "ab://10.0.0.6/1,0";
|
||||
|
||||
/// <summary>A warm tag on a dead device: the read takes a while, then times out like a real session.</summary>
|
||||
private sealed class SlowTimeoutTag(AbCipTagCreateParams p) : FakeAbCipTag(p)
|
||||
{
|
||||
public override async Task ReadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await base.ReadAsync(cancellationToken);
|
||||
await Task.Delay(300, cancellationToken);
|
||||
throw new AbTransportException(AbStatus.Timeout, "reply timeout");
|
||||
}
|
||||
}
|
||||
|
||||
private static AbCipDriverOptions TwoDeviceOptions(int bTags, int window = 8)
|
||||
{
|
||||
var defs = new List<AbCipTagDefinition>();
|
||||
for (var i = 0; i < bTags; i++) defs.Add(new AbCipTagDefinition($"B{i}", DevB, $"B{i}", AbCipDataType.DInt));
|
||||
defs.Add(new AbCipTagDefinition("A0", DevA, "A0", AbCipDataType.DInt));
|
||||
return new AbCipDriverOptions
|
||||
{
|
||||
Devices = [new AbCipDeviceOptions(DevA), new AbCipDeviceOptions(DevB)],
|
||||
RawTags = AbCipRawTags.From([.. defs]),
|
||||
Probe = new AbCipProbeOptions { Enabled = false },
|
||||
MaxConcurrentReads = window,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Device B has 200 WARM runtimes that all time out (300 ms each). The first window's worth fail on the wire;
|
||||
/// the rest fail fast on the batch's fault latch, and device A (listed last) is read Good regardless.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_dead_device_with_warm_handles_costs_one_window_of_timeouts_not_one_per_tag()
|
||||
{
|
||||
var bCreates = 0;
|
||||
var factory = new FakeAbCipTagFactory
|
||||
{
|
||||
Customise = p =>
|
||||
{
|
||||
if (p.Gateway != "10.0.0.6") return new FakeAbCipTag(p) { Value = 1 };
|
||||
Interlocked.Increment(ref bCreates);
|
||||
return new FakeAbCipTag(p) { Value = 2 };
|
||||
},
|
||||
};
|
||||
var drv = new AbCipDriver(TwoDeviceOptions(bTags: 200), "abcip-dead", factory);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
string[] refs = [.. Enumerable.Range(0, 200).Select(i => $"B{i}"), "A0"];
|
||||
|
||||
// Warm every runtime while the device is healthy.
|
||||
(await drv.ReadAsync(refs, CancellationToken.None)).ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);
|
||||
bCreates.ShouldBe(200);
|
||||
|
||||
// The device dies mid-run: the cached (warm) handles now fail like a dead session.
|
||||
foreach (var tag in factory.Tags.Where(t => t.Key.StartsWith('B')).Select(t => t.Value))
|
||||
{
|
||||
tag.ThrowOnRead = true;
|
||||
tag.Exception = new AbTransportException(AbStatus.Timeout, "reply timeout");
|
||||
}
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
var r = await drv.ReadAsync(refs, CancellationToken.None);
|
||||
sw.Stop();
|
||||
|
||||
r[200].StatusCode.ShouldBe(AbCipStatusMapper.Good); // device A answered
|
||||
r[200].Value.ShouldBe(1);
|
||||
r.Take(200).ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
|
||||
// The in-flight window's worth carry the wire's own status (timeout); everything behind it the latch's.
|
||||
r.Take(200).Count(s => s.StatusCode == AbCipStatusMapper.BadCommunicationError).ShouldBeGreaterThanOrEqualTo(192);
|
||||
|
||||
// Only the items that were in flight (<= window) ever reached the wire; the rest were latched out.
|
||||
var bReads = factory.Tags.Where(t => t.Key.StartsWith('B')).Sum(t => t.Value.ReadCount) - 200; // minus the warm-up
|
||||
bReads.ShouldBeLessThanOrEqualTo(8);
|
||||
bReads.ShouldBeGreaterThan(0); // positive control: the failure did reach the wire
|
||||
}
|
||||
|
||||
/// <summary>Same shape with a real delay per failed read: the whole call must cost ~one timeout, not 200/8 of them.</summary>
|
||||
[Fact]
|
||||
public async Task The_whole_call_costs_about_one_timeout_and_a_healthy_device_is_not_blocked()
|
||||
{
|
||||
var factory = new FakeAbCipTagFactory
|
||||
{
|
||||
Customise = p => p.Gateway == "10.0.0.6" ? new SlowTimeoutTag(p) : new FakeAbCipTag(p) { Value = 1 },
|
||||
};
|
||||
var drv = new AbCipDriver(TwoDeviceOptions(bTags: 200), "abcip-dead2", factory);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
string[] refs = [.. Enumerable.Range(0, 200).Select(i => $"B{i}"), "A0"];
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
var r = await drv.ReadAsync(refs, CancellationToken.None);
|
||||
sw.Stop();
|
||||
|
||||
r[200].StatusCode.ShouldBe(AbCipStatusMapper.Good);
|
||||
// Unfixed: 25 windows x 300 ms = 7.5 s. Fixed: one 300 ms window (generous bound for slow CI).
|
||||
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(3));
|
||||
r.Take(200).ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After the failed call the dead device's handles are evicted, so the next poll re-creates cold: ONE
|
||||
/// single-flight attempt reaches the wire, fails, opens the backoff window, and the other 19 tags (and every
|
||||
/// later poll) are throttled without touching it. Once the window passes a recovered device reads Good.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task The_next_poll_of_a_dead_device_makes_one_attempt_then_throttles_and_recovery_still_works()
|
||||
{
|
||||
var down = false;
|
||||
var bCreates = 0;
|
||||
var factory = new FakeAbCipTagFactory
|
||||
{
|
||||
Customise = p =>
|
||||
{
|
||||
if (p.Gateway != "10.0.0.6") return new FakeAbCipTag(p) { Value = 1 };
|
||||
Interlocked.Increment(ref bCreates);
|
||||
return down
|
||||
? new FakeAbCipTag(p) { ThrowOnInitialize = true, Exception = new AbTransportException(AbStatus.Timeout, "connect timeout") }
|
||||
: new FakeAbCipTag(p) { Value = 2 };
|
||||
},
|
||||
};
|
||||
var drv = new AbCipDriver(TwoDeviceOptions(bTags: 20), "abcip-dead3", factory);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
string[] refs = [.. Enumerable.Range(0, 20).Select(i => $"B{i}"), "A0"];
|
||||
await drv.ReadAsync(refs, CancellationToken.None);
|
||||
bCreates.ShouldBe(20);
|
||||
|
||||
down = true;
|
||||
foreach (var tag in factory.Tags.Where(t => t.Key.StartsWith('B')).Select(t => t.Value))
|
||||
{
|
||||
tag.ThrowOnRead = true;
|
||||
tag.Exception = new AbTransportException(AbStatus.Timeout, "reply timeout");
|
||||
}
|
||||
await drv.ReadAsync(refs, CancellationToken.None); // warm failures; handles evicted
|
||||
bCreates.ShouldBe(20);
|
||||
|
||||
var r = await drv.ReadAsync(refs, CancellationToken.None); // cold: one real attempt, rest throttled
|
||||
bCreates.ShouldBe(21);
|
||||
r.Take(20).ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
|
||||
r[20].StatusCode.ShouldBe(AbCipStatusMapper.Good);
|
||||
|
||||
await drv.ReadAsync(refs, CancellationToken.None); // inside the window: nothing re-created
|
||||
bCreates.ShouldBe(21);
|
||||
|
||||
// Recovery once the window passes.
|
||||
down = false;
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(1300), TestContext.Current.CancellationToken);
|
||||
r = await drv.ReadAsync(refs, CancellationToken.None);
|
||||
r.ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);
|
||||
await drv.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>P-16: a dead device with 100 cold tags polled 10 times logs at most a couple of Warnings, not 1000.</summary>
|
||||
[Fact]
|
||||
public async Task A_dead_device_logs_one_warning_per_outage_not_one_per_tag_per_poll()
|
||||
{
|
||||
var logger = new AbCipLoggingTests.CapturingLogger<AbCipDriver>();
|
||||
var fail = true;
|
||||
var factory = new FakeAbCipTagFactory
|
||||
{
|
||||
Customise = p => new FakeAbCipTag(p)
|
||||
{
|
||||
ThrowOnInitialize = fail,
|
||||
Exception = new AbTransportException(AbStatus.Timeout, "connect timeout"),
|
||||
Value = 3,
|
||||
},
|
||||
};
|
||||
var defs = Enumerable.Range(0, 100)
|
||||
.Select(i => new AbCipTagDefinition($"T{i}", DevA, $"T{i}", AbCipDataType.DInt)).ToArray();
|
||||
var drv = new AbCipDriver(new AbCipDriverOptions
|
||||
{
|
||||
Devices = [new AbCipDeviceOptions(DevA)],
|
||||
RawTags = AbCipRawTags.From(defs),
|
||||
Probe = new AbCipProbeOptions { Enabled = false },
|
||||
}, "abcip-log", factory, logger: logger);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
string[] refs = [.. defs.Select(d => d.Name)];
|
||||
|
||||
for (var i = 0; i < 10; i++)
|
||||
(await drv.ReadAsync(refs, CancellationToken.None)).ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
|
||||
|
||||
var warnings = logger.Entries.Where(e => e.Level == LogLevel.Warning && e.Message.Contains(DevA)).ToList();
|
||||
warnings.Count.ShouldBeLessThanOrEqualTo(2);
|
||||
warnings.Count.ShouldBeGreaterThanOrEqualTo(1); // positive control: the outage IS announced
|
||||
|
||||
// Recovery ends the outage with one Info carrying the suppressed count, and re-arms the Warning.
|
||||
fail = false;
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(1300), TestContext.Current.CancellationToken);
|
||||
(await drv.ReadAsync(refs, CancellationToken.None)).ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);
|
||||
logger.Entries.Count(e => e.Level == LogLevel.Information && e.Message.Contains("reachable again")).ShouldBe(1);
|
||||
await drv.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -357,6 +357,46 @@ public sealed class AbCipDriverDiscoveryTests
|
||||
builder.Folders.ShouldContain(f => f.BrowseName == "Motor1.Status");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Review 2026-12-02 P-23d (#983): the fan-out's cycle guard keyed on member NAME, so a UDT tag <c>Status</c>
|
||||
/// whose nested type has a member also called <c>Status</c> was skipped as "cyclic" and never appeared in browse.
|
||||
/// Keyed on the struct TYPE (template id) it is emitted; a true re-entry of the same template id stays cut.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_nested_member_that_shares_its_parents_name_is_not_mistaken_for_a_cycle()
|
||||
{
|
||||
const string device = "ab://10.0.0.5/1,0";
|
||||
const uint outerTemplateId = 0x2A;
|
||||
const uint innerTemplateId = 0x123;
|
||||
|
||||
var builder = new RecordingBuilder();
|
||||
var enumeratorFactory = new FakeEnumeratorFactory(
|
||||
new AbCipDiscoveredTag("Status", null, AbCipDataType.Structure, ReadOnly: false,
|
||||
TemplateInstanceId: outerTemplateId));
|
||||
var templateReaderFactory = new IdKeyedTemplateReaderFactory
|
||||
{
|
||||
Templates =
|
||||
{
|
||||
[outerTemplateId] = BuildSimpleTemplate("OuterUdt", 12,
|
||||
("Speed", 0xCA, 0, 0),
|
||||
("Status", (ushort)(0x8000 | innerTemplateId), 0, 8)), // same NAME as the tag, different TYPE
|
||||
[innerTemplateId] = BuildSimpleTemplate("InnerUdt", 4, ("Code", 0xC4, 0, 0)),
|
||||
},
|
||||
};
|
||||
var drv = new AbCipDriver(new AbCipDriverOptions
|
||||
{
|
||||
Devices = [new AbCipDeviceOptions(device)],
|
||||
EnableControllerBrowse = true,
|
||||
}, "drv-1", enumeratorFactory: enumeratorFactory, templateReaderFactory: templateReaderFactory);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
await drv.DiscoverAsync(builder, CancellationToken.None);
|
||||
|
||||
var names = builder.Variables.Select(v => v.Info.FullName).ToList();
|
||||
names.ShouldContain("Status.Speed"); // positive control: the parent fanned out
|
||||
names.ShouldContain("Status.Status.Code"); // the same-named nested member is no longer dropped
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A discovered Structure whose shape cannot be resolved degrades to the prior single
|
||||
/// Variable behavior (no regression): one Variable under the Discovered folder keyed by
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+29
@@ -66,4 +66,33 @@ public sealed class AbCipProgramScopeEnumerationTests
|
||||
|
||||
tags.ShouldContain(t => t.Name == "WW_InCycle");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-23e (#983): a connection-level failure reading a program's listing used to be swallowed with no log,
|
||||
/// silently dropping the program (and everything after it) from browse. It must surface; a device refusal
|
||||
/// still skips just that program.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_timeout_reading_a_program_listing_surfaces_but_a_refusal_skips_the_program()
|
||||
{
|
||||
var controllerListing = Convert.FromHexString(ControllerListing);
|
||||
|
||||
using var timesOut = new SymbolListingEnumerator((_, name, _) => name == "@tags"
|
||||
? Task.FromResult(controllerListing)
|
||||
: Task.FromException<byte[]>(new ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbTransportException(
|
||||
ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbStatus.Timeout, "listing timeout")));
|
||||
await Should.ThrowAsync<ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbTransportException>(async () =>
|
||||
{
|
||||
await foreach (var _ in timesOut.EnumerateAsync(Params, TestContext.Current.CancellationToken)) { }
|
||||
});
|
||||
|
||||
// Positive control: the same shape with a device REFUSAL yields the controller tags and does not throw.
|
||||
using var refused = new SymbolListingEnumerator((_, name, _) => name == "@tags"
|
||||
? Task.FromResult(controllerListing)
|
||||
: Task.FromException<byte[]>(new ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbTransportException(
|
||||
ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbStatus.NotFound, "no such program")));
|
||||
var tags = new List<AbCipDiscoveredTag>();
|
||||
await foreach (var t in refused.EnumerateAsync(Params, TestContext.Current.CancellationToken)) tags.Add(t);
|
||||
tags.ShouldContain(t => t.Name == "WW_InCycle");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.AbCip;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests;
|
||||
|
||||
/// <summary>Review 2026-12-02 P-23 (#983) AbCip items a and c (b, d and e live beside the path, discovery and enumeration tests).</summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class AbCipReviewP23Tests
|
||||
{
|
||||
private const string Device = "ab://10.0.0.5/1,0";
|
||||
|
||||
/// <summary>A parent whose read takes a moment, so an unlocked read-modify-write interleaves with a sibling.</summary>
|
||||
private sealed class SlowReadParent(AbCipTagCreateParams p, ConcurrentQueue<string>? log = null) : FakeAbCipTag(p)
|
||||
{
|
||||
private object? _snapshot;
|
||||
|
||||
// A real read captures the controller's word when it is READ; the decode that follows sees that snapshot, not
|
||||
// whatever a later write made of it. Without this the fake hides every lost update.
|
||||
public override async Task ReadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await base.ReadAsync(cancellationToken);
|
||||
_snapshot = Value;
|
||||
log?.Enqueue("rmw-read");
|
||||
await Task.Delay(80, cancellationToken);
|
||||
}
|
||||
|
||||
public override object? DecodeValue(AbCipDataType type, int? bitIndex) => _snapshot;
|
||||
|
||||
public override Task WriteAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
log?.Enqueue("rmw-write");
|
||||
return base.WriteAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-23a: <c>Flags.3</c> and <c>FLAGS.4</c> share one case-insensitive parent runtime, so they must share its
|
||||
/// read-modify-write lock. With a case-sensitive lock table each took its own and one update was lost.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Bit_writes_whose_parent_names_differ_only_by_case_both_land()
|
||||
{
|
||||
var factory = new FakeAbCipTagFactory { Customise = p => new SlowReadParent(p) { Value = 0 } };
|
||||
var drv = new AbCipDriver(new AbCipDriverOptions
|
||||
{
|
||||
Devices = [new AbCipDeviceOptions(Device)],
|
||||
RawTags = AbCipRawTags.From(
|
||||
new AbCipTagDefinition("A", Device, "Flags.3", AbCipDataType.Bool),
|
||||
new AbCipTagDefinition("B", Device, "FLAGS.4", AbCipDataType.Bool)),
|
||||
Probe = new AbCipProbeOptions { Enabled = false },
|
||||
}, "abcip-rmw-case", factory);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var results = await Task.WhenAll(
|
||||
drv.WriteAsync([new WriteRequest("A", true)], CancellationToken.None),
|
||||
drv.WriteAsync([new WriteRequest("B", true)], CancellationToken.None));
|
||||
|
||||
results.ShouldAllBe(r => r.Single().StatusCode == AbCipStatusMapper.Good);
|
||||
Convert.ToInt32(factory.Tags["Flags"].Value).ShouldBe((1 << 3) | (1 << 4)); // neither update lost
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-23a: a whole-word write to the parent goes through a different runtime than the bit RMW's, so it must take
|
||||
/// the same lock — or it lands between the RMW's read and write and is overwritten by the stale read-back.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_whole_word_write_never_lands_between_a_bit_RMWs_read_and_write()
|
||||
{
|
||||
var log = new ConcurrentQueue<string>();
|
||||
var creates = 0;
|
||||
var factory = new FakeAbCipTagFactory
|
||||
{
|
||||
Customise = p =>
|
||||
{
|
||||
// 1st create = the bit write's parent runtime, 2nd = the whole-word tag's own runtime.
|
||||
var n = Interlocked.Increment(ref creates);
|
||||
return n == 1
|
||||
? new SlowReadParent(p, log) { Value = 0 }
|
||||
: new LoggingWholeWord(p, log) { Value = 0 };
|
||||
},
|
||||
};
|
||||
var drv = new AbCipDriver(new AbCipDriverOptions
|
||||
{
|
||||
Devices = [new AbCipDeviceOptions(Device)],
|
||||
RawTags = AbCipRawTags.From(
|
||||
new AbCipTagDefinition("Bit", Device, "Flags.3", AbCipDataType.Bool),
|
||||
new AbCipTagDefinition("Word", Device, "Flags", AbCipDataType.DInt)),
|
||||
Probe = new AbCipProbeOptions { Enabled = false },
|
||||
}, "abcip-rmw-whole", factory);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
// Warm both runtimes (1 = parent, 2 = whole), then clear the log and race them.
|
||||
await drv.WriteAsync([new WriteRequest("Bit", true)], CancellationToken.None);
|
||||
await drv.WriteAsync([new WriteRequest("Word", 7)], CancellationToken.None);
|
||||
log.Clear();
|
||||
|
||||
var rmw = drv.WriteAsync([new WriteRequest("Bit", false)], CancellationToken.None);
|
||||
var deadline = DateTime.UtcNow.AddSeconds(5);
|
||||
while (!log.Contains("rmw-read") && DateTime.UtcNow < deadline) await Task.Delay(1, TestContext.Current.CancellationToken);
|
||||
var whole = drv.WriteAsync([new WriteRequest("Word", 9)], CancellationToken.None);
|
||||
await Task.WhenAll(rmw, whole);
|
||||
|
||||
log.ToArray().ShouldBe(["rmw-read", "rmw-write", "whole-write"]);
|
||||
}
|
||||
|
||||
private sealed class LoggingWholeWord(AbCipTagCreateParams p, ConcurrentQueue<string> log) : FakeAbCipTag(p)
|
||||
{
|
||||
public override Task WriteAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
log.Enqueue("whole-write");
|
||||
return base.WriteAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>P-23c: a zero / negative probe or alarm interval hot-looped (0) or threw out of the loop (negative).</summary>
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-5)]
|
||||
[InlineData(10)]
|
||||
public void Probe_and_alarm_intervals_are_clamped_to_a_floor(int ms)
|
||||
{
|
||||
var json = $$"""{"devices":[{"hostAddress":"{{Device}}"}],"probe":{"intervalMs":{{ms}}},"alarmPollIntervalMs":{{ms}}}""";
|
||||
var o = AbCipDriverFactoryExtensions.ParseOptions("drv-1", json);
|
||||
o.Probe.Interval.ShouldBe(TimeSpan.FromMilliseconds(AbCipDriverFactoryExtensions.MinIntervalMs));
|
||||
o.AlarmPollInterval.ShouldBe(TimeSpan.FromMilliseconds(AbCipDriverFactoryExtensions.MinIntervalMs));
|
||||
}
|
||||
|
||||
/// <summary>Positive control: an interval at or above the floor, and an absent one, are untouched.</summary>
|
||||
[Fact]
|
||||
public void Intervals_at_or_above_the_floor_and_absent_ones_are_untouched()
|
||||
{
|
||||
var o = AbCipDriverFactoryExtensions.ParseOptions("drv-1",
|
||||
$$"""{"devices":[{"hostAddress":"{{Device}}"}],"probe":{"intervalMs":250},"alarmPollIntervalMs":1500}""");
|
||||
o.Probe.Interval.ShouldBe(TimeSpan.FromMilliseconds(250));
|
||||
o.AlarmPollInterval.ShouldBe(TimeSpan.FromMilliseconds(1500));
|
||||
|
||||
var d = AbCipDriverFactoryExtensions.ParseOptions("drv-1", $$"""{"devices":[{"hostAddress":"{{Device}}"}]}""");
|
||||
d.Probe.Interval.ShouldBe(TimeSpan.FromSeconds(5));
|
||||
d.AlarmPollInterval.ShouldBe(TimeSpan.FromSeconds(1));
|
||||
}
|
||||
}
|
||||
@@ -85,13 +85,27 @@ public sealed class AbCipTagPathTests
|
||||
p.ToLibplctagName().ShouldBe("Motor.Status.12");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that bit index 32 is rejected as out of range.</summary>
|
||||
[Fact]
|
||||
public void Bit_index_32_rejected_out_of_range()
|
||||
/// <summary>
|
||||
/// P-23b (#983): a LINT host has 64 bits, so the selector accepts 0..63 (it used to stop at 31 and
|
||||
/// <c>MyLint.40</c> was a malformed tag). The per-host width check refuses a bit the host does not have.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("Flags.31", 31)]
|
||||
[InlineData("Flags.32", 32)]
|
||||
[InlineData("MyLint.40", 40)]
|
||||
[InlineData("Flags.63", 63)]
|
||||
public void Bit_index_up_to_63_is_a_bit_selector(string path, int bit)
|
||||
{
|
||||
// 32 exceeds the DINT bit width — treated as a member name rather than bit selector,
|
||||
// which fails ident validation and returns null.
|
||||
AbCipTagPath.TryParse("Flags.32").ShouldBeNull();
|
||||
var p = AbCipTagPath.TryParse(path);
|
||||
p.ShouldNotBeNull();
|
||||
p.BitIndex.ShouldBe(bit);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that bit index 64 is rejected as out of range (a member name that fails ident validation).</summary>
|
||||
[Fact]
|
||||
public void Bit_index_64_rejected_out_of_range()
|
||||
{
|
||||
AbCipTagPath.TryParse("Flags.64").ShouldBeNull();
|
||||
}
|
||||
|
||||
/// <summary>Verifies that program scope with members, subscript, and bit index parses correctly.</summary>
|
||||
|
||||
@@ -81,6 +81,33 @@ public sealed class NativeAbCipTagEnumeratorTests
|
||||
return tags;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-24 (#983): the lease release (a Forward Close) must not be waited on from the async iterator's
|
||||
/// <c>finally</c> — it used to block a thread-pool thread for up to 2 s per browse. A release that never
|
||||
/// completes must not delay the enumeration; it is still started exactly once.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_slow_lease_release_does_not_delay_the_enumeration()
|
||||
{
|
||||
var ch = Serve(new() { [""] = Entries(CipSymbolObjectRealControllerCaptureTests.WwInCycle) });
|
||||
var neverCloses = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var releases = 0;
|
||||
await using var sched = new RequestScheduler(ch, allowPacking: false);
|
||||
using var enumerator = new NativeAbCipTagEnumerator(_ =>
|
||||
(sched, () => { Interlocked.Increment(ref releases); return new ValueTask(neverCloses.Task); }));
|
||||
|
||||
var tags = new List<AbCipDiscoveredTag>();
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
await foreach (var t in enumerator.EnumerateAsync(Params, TestContext.Current.CancellationToken))
|
||||
tags.Add(t);
|
||||
sw.Stop();
|
||||
|
||||
tags.ShouldContain(t => t.Name == "WW_InCycle"); // positive control: it enumerated
|
||||
releases.ShouldBe(1);
|
||||
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromMilliseconds(1500)); // unfixed: held for the 2 s DisposeWait
|
||||
neverCloses.SetResult();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Paged_controller_and_program_listings_decode_identically_to_the_captured_buffers()
|
||||
{
|
||||
|
||||
@@ -346,6 +346,97 @@ 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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-24 (#983): a Structure read has no static element width, so every one was sent alone (UnknownReply). After
|
||||
/// the first read the size is known and queued structure reads pack into one Multiple Service Packet.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Structure_reads_of_a_known_size_pack_into_one_MSP()
|
||||
{
|
||||
var udt = Convert.FromHexString("A002CE0F" + new string('1', 40)); // struct handle + 20 data bytes
|
||||
var ch = new FakeCipChannel { RespondPerService = req => Convert.FromHexString("D2000000").Concat(udt).ToArray() };
|
||||
using var rt = NativeAbCipTagRuntime.ForTest(ch, Params("Motor", AbCipDataType.Structure) with { AllowPacking = true });
|
||||
await rt.InitializeAsync(CancellationToken.None); // learns the size
|
||||
ch.SentCount.ShouldBe(1);
|
||||
|
||||
ch.Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var a = rt.ReadAsync(CancellationToken.None);
|
||||
await ch.WaitForSendsAsync(2); // `a` is in flight; the next two queue behind it
|
||||
var b = rt.ReadAsync(CancellationToken.None);
|
||||
var c = rt.ReadAsync(CancellationToken.None);
|
||||
var d = rt.ReadAsync(CancellationToken.None);
|
||||
ch.Gate.SetResult();
|
||||
await Task.WhenAll(a, b, c, d).WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
ch.SentCount.ShouldBe(3); // init, a alone, ONE packed MSP for b + c + d
|
||||
ch.Sent[2][0].ShouldBe((byte)0x0A);
|
||||
FakeCipChannel.SplitMsp(ch.Sent[2]).Count.ShouldBe(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_user_string_array_uses_the_buffer_derived_stride()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user