fix(twincat): #982 symbol-table changes re-resolve on a fresh client; one dead device no longer stalls the rest
Review 2026-12-02 (09-ab-twincat-focas.md) TwinCAT findings: - P-1: a stale client (ADS symbol-version event, a 1809, an invalidated notification, a probe non-Run -> Run transition, or a moved OnlineChangeCnt sampled every healthy probe tick) is never handed out again: the next call retires it (fresh Beckhoff symbol cache), native registrations replay on the fresh client (background or probe tick), its pushes are dropped, refused registrations re-arm, rediscovery is raised once per event. Verified against decompiled Beckhoff.TwinCAT.Ads 7.0.172: SymbolCache cleans itself only on the symbol-version event, which an online change does not raise. - P-3: devices are read concurrently; the first comms failure on a device is checked against its ADS state once - gone => remaining tags fail fast with no wire attempt, alive => per-tag failure. Probe-unreachable devices fail fast; native subscribe applies the same rule. - P-4: the probe connects without replaying registrations, probes, and re-registers only after the device answered; a replay against a dead device stops dialling it; one Warning per device per outage, Bad published once. - P-12: unlisted device-layer ADS codes (0x700-0x73F) map to BadDeviceFailure (refusal, no health write, refusal backoff); 1817 DeviceTimeOut = BadTimeout; marshal/type read exceptions = BadTypeMismatch; the read guard refuses a scalar over a struct/FB (pointers/references still read as their address). - P-19: symbol name / bit index pre-computed at init; health re-derived once per device per read call (health updates now serialised under a lock). - P-22: the ADS client always carries the driver Timeout; the probe bounds only its own ReadState with Probe.Timeout. - P-25: bit-indexed BOOL poll reads resolve the parent and read it at its own width; poll / notification / write agree on BadOutOfRange / BadTypeMismatch. Tests: TwinCATReview20261202Tests (39 cases; the behavioural ones failed before the fix). TwinCAT.Tests 712/712.
This commit is contained in:
@@ -277,12 +277,21 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
|
||||
(`CheckNotification`) rides a batch; value-converted pairs (DInt over INT, Real over LREAL/DINT) read singly. Only overall
|
||||
ADS 1793/1794 latch the device to single reads; any other non-comms overall code (1792/1795/1797/1798...) reads that chunk singly for the poll without latching, with a once-per-device Warning; a comms failure neither.
|
||||
Opt-in `diagnosticsEnabled` (default off) puts ADS state/app/online-change/cycle/exec/`HeadroomMs` on the `/hosts`
|
||||
`IDriverDiagnostics` bag (≤ 4 extra reads per device per probe tick once settled; TC2 falls back to `.SYSTEMINFO` /
|
||||
`.SYSTEMTASKINFOARR[1]`, costing 8 on the first tick and after each reconnect). Live-gated read-only 2026-10-08 on
|
||||
`IDriverDiagnostics` bag (≤ 3 extra reads per device per probe tick once settled, on top of the always-on
|
||||
`OnlineChangeCnt` read below; TC2 falls back to `.SYSTEMINFO` / `.SYSTEMTASKINFOARR[1]`, double on the first tick
|
||||
and after each reconnect). Live-gated read-only 2026-10-08 on
|
||||
Z35474 (TC3) + Z34834 (TC2, which answers sum commands) via a harness driving `TwinCATDriver` — `/hosts` end-to-end
|
||||
not run (a stock host has no AMS router); the gate found ⚠️ Beckhoff's `SumRead` ctor throws for a `List<>` of entities (only an array survives
|
||||
its internal cast) — `AdsTwinCATClient.CreateSumRead` owns it. Flat browse stays (VirtualTree is a strict subset
|
||||
on TC3). Sum-write not ported.
|
||||
- **TwinCAT symbol-table changes + health (#982):** the Beckhoff symbol cache keeps resolved IG/IO until disposed and
|
||||
an ONLINE change raises no ADS symbol-version event — so a stale client is retired (fresh symbol table, native
|
||||
registrations replayed, rediscovery raised once) on the SDK event, a 1809, an invalidated notification, a probe
|
||||
non-Run → Run transition, or a moved `OnlineChangeCnt` (sampled every healthy probe tick, one read). Device-layer
|
||||
ADS codes 0x700–0x73F are refusals (`BadDeviceFailure`, no health write; 1817 `DeviceTimeOut` is a timeout); the
|
||||
client always carries the driver `Timeout` (the probe bounds only its own ReadState); devices are read
|
||||
concurrently and a dead one fails fast after one state check; the probe never replays registrations before the
|
||||
device answered. `docs/drivers/TwinCAT.md` §Symbol-table changes / §Health.
|
||||
- **AbLegacy (#636):** `AbLegacyAddress` (in `AbLegacy.Contracts`) is family-aware: PLC-5 `I:`/`O:` indices are OCTAL
|
||||
and are emitted to libplctag as decimal (libplctag's `pccc.c` parses decimal only). MicroLogix function files parse
|
||||
but read `BadNotSupported`. Indirect `N7:[N7:0]` (#646) is resolved by the driver at read/write time (index re-read
|
||||
|
||||
+64
-23
@@ -228,12 +228,14 @@ Behind `diagnosticsEnabled` (default **off**). Live-gated read-only 2026-10-08 o
|
||||
driving `TwinCATDriver` from a scratch harness with an in-process AMS router; the `/hosts` page end-to-end was
|
||||
**not** exercised (a stock host has no AMS router). The driver implements the optional
|
||||
`IDriverDiagnostics` bag (the S7 `NegotiatedPduSize` precedent, #640), deliberately not synthetic raw tags.
|
||||
When enabled, after each healthy probe tick **and after the host-state transition** it reads up to four
|
||||
`TwinCAT_SystemInfoVarList` symbols per device — `_AppInfo.AppName`, `_AppInfo.OnlineChangeCnt`,
|
||||
`_TaskInfo[1].CycleTime`, `_TaskInfo[1].LastExecTime` (100 ns ticks) — so at most **4 extra read requests per
|
||||
device per probe interval** (default 5 s) once settled. On **TwinCAT 2** (fallback below) the first tick, and the
|
||||
first tick after every reconnect, costs **8** (the four TC3 names answer "not found", then the four TC2 names);
|
||||
after that ≤ 4. The ADS state is the one `ProbeAsync` already read; no second
|
||||
When enabled, after each healthy probe tick **and after the host-state transition** it reads up to three more
|
||||
`TwinCAT_SystemInfoVarList` symbols per device — `_AppInfo.AppName`, `_TaskInfo[1].CycleTime`,
|
||||
`_TaskInfo[1].LastExecTime` (100 ns ticks) — and reuses `_AppInfo.OnlineChangeCnt`, which the probe now samples on
|
||||
**every** healthy tick whether diagnostics are on or not (#982 P-1, see
|
||||
[Symbol-table changes](#symbol-table-changes-online-change-and-program-download)). So once settled a probe tick costs
|
||||
the ReadState, **1** online-change read, and with diagnostics **3** more. On **TwinCAT 2** (fallback below) the first
|
||||
tick, and the first tick after every reconnect, costs twice that for those symbols (the TC3 names answer "not
|
||||
found", then the TC2 names). The ADS state is the one `ProbeAsync` already read; no second
|
||||
ReadState. One device: flat keys `TwinCAT.AdsState`, `.AppName`, `.OnlineChangeCnt`, `.CycleTimeMs`,
|
||||
`.LastExecTimeMs`, `.HeadroomMs` (cycle − last exec; negative = the task overran; this is spare time, not
|
||||
jitter). Several devices: one line per device, `TwinCAT.<DeviceName or host>` =
|
||||
@@ -255,28 +257,43 @@ none of the TC2 names on a TC3 target — are pinned by `TwinCATDiagnosticsTests
|
||||
| Capability | Path | Notes |
|
||||
|------------|------|-------|
|
||||
| `IReadable` | `ReadAsync` → ADS `ReadValueAsync` | Per-device client, lazily connected and serialized per device |
|
||||
| `IWritable` | `WriteAsync` → ADS `WriteValueAsync` | BOOL-within-word writes (e.g. `MAIN.Flags.3`) use a driver-level parent-word read-modify-write (read as UDInt, flip bit, write back) under a per-parent lock. Read-only tags return `BadNotWritable`. |
|
||||
| `IWritable` | `WriteAsync` → ADS `WriteValueAsync` | BOOL-within-word writes (e.g. `MAIN.Flags.3`) use a driver-level parent-word read-modify-write at the parent's own resolved width under a per-parent lock. Read-only tags return `BadNotWritable`. |
|
||||
| `ITagDiscovery` | `DiscoverAsync` | Pre-declared tags + opt-in controller symbol browse |
|
||||
| `ISubscribable` | native ADS notifications (default), poll fallback | `UseNativeNotifications=true` registers device notifications so the PLC pushes changes; `false` uses the shared `PollGroupEngine` |
|
||||
| `IHostConnectivityProbe` | per-device probe loop | One `HostConnectivityStatus` per configured device; `Running`/`Stopped` transitions raise `OnHostStatusChanged` |
|
||||
| `IPerCallHostResolver` | `ResolveHost` lookup in the tag map | Routes each call to the device of the referenced tag; returns an empty-string sentinel when unresolved |
|
||||
| `IRediscoverable` | symbol-version-changed callback | A PLC re-download fires `OnRediscoveryNeeded`. ⚠️ **No consumer wires it today** ([#518](https://gitea.dohertylan.com/dohertj2/lmxopcua/issues/518), [#507](https://gitea.dohertylan.com/dohertj2/lmxopcua/issues/507)) — the address space does **not** rebuild; a config redeploy is required. Driver-side behaviour is log-observable only |
|
||||
| `IRediscoverable` | symbol-table-change detection | A program download or online change re-resolves every symbol on a fresh client and raises `OnRediscoveryNeeded` once — the `/hosts` "re-browse" chip. The served address space does **not** rebuild (v3 authors tags explicitly; re-browse + commit) |
|
||||
|
||||
### Rediscovery on PLC re-download
|
||||
### Symbol-table changes (online change and program download)
|
||||
|
||||
`IRediscoverable` is the distinguishing capability. When the ADS client detects
|
||||
`DeviceSymbolVersionInvalid` (1809 / 0x0711) — the documented TwinCAT
|
||||
symbol-version-changed signal, raised when a PLC program is re-downloaded —
|
||||
every symbol and notification handle is invalidated. The driver raises
|
||||
`OnRediscoveryNeeded` with a `TwinCAT` scope hint, so that the signal is treated
|
||||
as an address-space change rather than a transient connection error.
|
||||
Reads, sum-reads, raw writes and the bit read-modify-write address the PLC by the IndexGroup/IndexOffset that
|
||||
the Beckhoff client's **symbol cache** resolved. That cache cleans itself only on the ADS symbol-version event
|
||||
(decompiled `Beckhoff.TwinCAT.Ads` 7.0.172: `SymbolCache` registers for `AdsSymbolVersionChanged` and calls
|
||||
`CleanupCache()`), and Beckhoff documents that an **online change does not raise that event** — yet it can
|
||||
relocate variables. Before #982 (P-1) the driver reacted only to an ADS `1809` answer, which an IG/IO read does not
|
||||
return, so after an online change a read could publish other memory at Good and a write could land on it; and
|
||||
after a download in native mode every registration kept a dead handle and its tag stayed frozen at Good.
|
||||
|
||||
⚠️ **That is the intended design, not present behaviour.** No consumer subscribes
|
||||
to `OnRediscoveryNeeded` anywhere in `src/`, and the scope hint is read by nothing
|
||||
([#518](https://gitea.dohertylan.com/dohertj2/lmxopcua/issues/518),
|
||||
[#507](https://gitea.dohertylan.com/dohertj2/lmxopcua/issues/507)). Today the
|
||||
signal is observable only in the driver log; after a PLC re-download the served
|
||||
address space changes only on a config redeploy.
|
||||
The driver now treats any of these as "this client's symbol table is stale":
|
||||
|
||||
- the SDK `AdsSymbolVersionChanged` event (hooked after the first symbol lookup, when the symbol cache has
|
||||
already registered with the target — so hooking it costs no I/O);
|
||||
- an ADS `DeviceSymbolVersionInvalid` (1809 / 0x0711) answer on any call (a sum-read with N such sub-errors counts once);
|
||||
- the target invalidating a registered notification (`AdsNotificationError` with an invalid handle, or a
|
||||
0-size notification);
|
||||
- on a healthy probe tick: the ADS state going non-Run → **Run** (a download is done with the PLC stopped), or a
|
||||
change of `_AppInfo.OnlineChangeCnt` (TC2: `.SYSTEMINFO.ONLINECHANGECOUNT`) — sampled on every healthy tick,
|
||||
one read, whether diagnostics are on or not.
|
||||
|
||||
On that signal the client is never handed out again: the next read / write / registration retires it and resolves
|
||||
every symbol on a fresh client; values its notifications still push are dropped; every native registration is
|
||||
re-established on the fresh client (immediately in the background, or by the probe tick that detected it);
|
||||
backed-off refused registrations are re-armed; and `OnRediscoveryNeeded` is raised **once** per event (the
|
||||
`/hosts` "re-browse" chip — advisory; the served address space changes only through `/raw` re-browse + commit).
|
||||
A re-registration that fails publishes its status (Bad), so a tag whose symbol the new program removed goes
|
||||
`BadNodeIdUnknown` instead of staying frozen. Detection latency: the SDK event and a 1809 are immediate; the
|
||||
probe checks run every `Probe.Interval`, and need the probe enabled (the default). ⚠️ Not yet live-gated: the
|
||||
TCBSD fixture gate (online change + full download) is still owed.
|
||||
|
||||
### Native notifications
|
||||
|
||||
@@ -300,8 +317,32 @@ fails the whole subscribe call.
|
||||
|
||||
Each device's ADS client is lazily connected and serialized by a per-device
|
||||
connect gate, so a concurrent read / write / probe can't race a client
|
||||
create-or-dispose. Probe-initiated connects use the probe timeout; reads and
|
||||
writes use the driver-wide `Timeout`.
|
||||
create-or-dispose. The client always carries the driver-wide `Timeout`, whoever creates it; the probe bounds only
|
||||
its own ReadState (and its online-change read) by `Probe.Timeout` (#982 P-22 — the probe usually creates the
|
||||
client, and its 2 s used to silently override a raised driver `Timeout` for every read).
|
||||
|
||||
## Health: refusals, comms faults and one dead device (#982)
|
||||
|
||||
- **Refusal vs comms fault (P-12).** Every ADS device-layer code (0x0700–0x073F) is the device answering: the
|
||||
listed ones map to a specific status and every other one (1800 Busy, 1803 InvalidParam, 1805 SyntaxError,
|
||||
1814 NoMoreHandles, 1815 InvalidWatchsize, licence codes, …) to `BadDeviceFailure` — per-tag Bad, no health
|
||||
write, and a refused native registration backs off (30 s doubling to 10 min) instead of retrying every probe
|
||||
tick. `DeviceTimeOut` (1817) is `BadTimeout`. AMS / router / client-layer (0x0740+) / socket codes stay comms
|
||||
faults. A Beckhoff marshal / type exception on a read is `BadTypeMismatch` (it used to reach the generic catch
|
||||
and degrade the driver), and the read guard refuses a scalar declared over a struct / FB (a pointer /
|
||||
reference is still read as its address).
|
||||
- **One dead device does not stall the rest (P-3).** `AdsClient.Connect` only opens the local AMS router port, so
|
||||
a PLC that stops answering still "connects". A read call reads its devices concurrently; within a device the
|
||||
first comms-class failure is checked against the device's ADS state (bounded by `Probe.Timeout`) — no answer
|
||||
and the rest of that device's tags fail fast with no wire attempt, an answer and the failure was that one
|
||||
tag's. A device the probe already counts unreachable (3 failed ticks) fails fast outright. A native subscribe
|
||||
applies the same rule. Health is applied once per device per call (P-19), still Degraded on a comms failure.
|
||||
- **The probe does not replay against an offline PLC (P-4).** The probe connects without replaying the stored
|
||||
registrations, probes, and re-registers them only after the device answered; a replay that hits a dead device
|
||||
stops dialling it. While the device is down the registrations publish `BadCommunicationError` once and one
|
||||
Warning is logged per device per outage.
|
||||
- **Bit-indexed BOOL reads (P-25)** resolve the parent and read it as raw bytes at its own width: bit 20 of a
|
||||
16-bit WORD is `BadOutOfRange` on the poll read, the notification and the write alike.
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
@@ -50,6 +50,12 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
public AdsTwinCATClient()
|
||||
{
|
||||
_client.AdsNotificationEx += OnAdsNotificationEx;
|
||||
// A program download / online change invalidates registered notification handles server-side; the
|
||||
// target says so with an error notification (or a 0-size one). Neither is a value: they are the
|
||||
// "symbol table changed" signal for a notification-only device that issues no reads (lmxopcua#982 P-1).
|
||||
// Plain events — subscribing does no I/O.
|
||||
_client.AdsNotificationError += OnAdsNotificationError;
|
||||
_client.AdsNotificationsInvalidated += OnAdsNotificationsInvalidated;
|
||||
_dispatchLoop = Task.Run(() => DispatchLoopAsync(_dispatchCts.Token));
|
||||
}
|
||||
|
||||
@@ -67,10 +73,73 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
private uint MapAndSignal(uint adsError)
|
||||
{
|
||||
if (TwinCATStatusMapper.IsSymbolVersionChanged(adsError))
|
||||
OnSymbolVersionChanged?.Invoke(this, EventArgs.Empty);
|
||||
SignalSymbolTableChanged();
|
||||
return TwinCATStatusMapper.MapAdsError(adsError);
|
||||
}
|
||||
|
||||
private void SignalSymbolTableChanged()
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0) return;
|
||||
try { OnSymbolVersionChanged?.Invoke(this, EventArgs.Empty); }
|
||||
catch { /* a consumer fault must never escape onto an ADS thread or into a read */ }
|
||||
}
|
||||
|
||||
private int _symbolVersionHooked;
|
||||
|
||||
/// <summary>
|
||||
/// Hooks the SDK's <c>AdsSymbolVersionChanged</c> event (a program download), once, AFTER the first
|
||||
/// successful symbol lookup. By then the Beckhoff symbol cache exists and has registered its own handler for
|
||||
/// the event, so adding ours is a plain delegate combine — no wire I/O. Subscribing before the cache exists
|
||||
/// would make <c>Connect</c> register the ADS notification synchronously against a possibly-dead target,
|
||||
/// and a failed registration there is never retried — which would also cost the symbol cache its own
|
||||
/// self-cleaning hook (decompiled <c>Beckhoff.TwinCAT.Ads</c> 7.0.172: <c>RegisterSymbolVersionChanged</c>
|
||||
/// only registers with the target when no delegate is attached yet).
|
||||
/// </summary>
|
||||
private void EnsureSymbolVersionHook()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _symbolVersionHooked, 1) != 0) return;
|
||||
try { _client.AdsSymbolVersionChanged += OnAdsSymbolVersionChanged; }
|
||||
catch { Volatile.Write(ref _symbolVersionHooked, 0); /* retried on the next lookup */ }
|
||||
}
|
||||
|
||||
private void OnAdsSymbolVersionChanged(object? sender, AdsSymbolVersionChangedEventArgs e) => SignalSymbolTableChanged();
|
||||
|
||||
private void OnAdsNotificationError(object? sender, AdsNotificationErrorEventArgs e)
|
||||
{
|
||||
if (e.Exception is AdsInvalidNotificationException invalid && _notifications.ContainsKey(invalid.Handle))
|
||||
SignalSymbolTableChanged();
|
||||
}
|
||||
|
||||
private void OnAdsNotificationsInvalidated(object? sender, AdsNotificationsInvalidatedEventArgs e)
|
||||
{
|
||||
foreach (var n in e.Notifications)
|
||||
{
|
||||
if (!_notifications.ContainsKey(n.Handle)) continue;
|
||||
SignalSymbolTableChanged();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classifies an exception thrown by the Beckhoff library while serving a READ. A type / marshal failure
|
||||
/// (the declared CLR type cannot carry the PLC value) is the device's data refused for this one tag —
|
||||
/// <c>BadTypeMismatch</c>, no health impact. Anything else (connection, timeout, socket, disposed, an
|
||||
/// unknown exception) returns <c>null</c>: the caller rethrows and it counts as a comms fault, as before.
|
||||
/// A whitelist on purpose: an exception we do not recognise must not be able to hide an outage
|
||||
/// (lmxopcua#982 P-12).
|
||||
/// </summary>
|
||||
/// <param name="ex">The exception the library threw.</param>
|
||||
/// <returns><c>BadTypeMismatch</c> for a type / marshal failure; otherwise <c>null</c>.</returns>
|
||||
internal static uint? MapReadException(Exception ex) => ex switch
|
||||
{
|
||||
OperationCanceledException or ObjectDisposedException or TimeoutException => null,
|
||||
global::TwinCAT.TypeSystem.MarshalException
|
||||
or global::TwinCAT.TypeSystem.DataTypeException
|
||||
or InvalidCastException or FormatException or OverflowException
|
||||
or NotSupportedException or ArgumentException => TwinCATStatusMapper.BadTypeMismatch,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ConnectAsync(TwinCATAmsAddress address, TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -100,12 +169,21 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
// is inherently scalar — arrayCount does not apply.
|
||||
if (bitIndex is int bit && type == TwinCATDataType.Bool)
|
||||
{
|
||||
var parent = TwinCATBitAccess.ParentPath(symbolPath);
|
||||
var parentResult = await _client.ReadValueAsync(parent, typeof(uint), cancellationToken)
|
||||
// The parent is resolved and read as raw bytes at its OWN width, and the bit is checked against
|
||||
// it — the notification and write paths' model (lmxopcua#982 P-25). Reading it as a 32-bit uint
|
||||
// answered Good false for bit 20 of a 16-bit WORD where the other two paths say BadOutOfRange,
|
||||
// and a float / struct parent threw in the marshaller (then counted as a comms fault).
|
||||
var parentPath = TwinCATBitAccess.ParentPath(symbolPath);
|
||||
var (parent, _, parentSymbol, parentStatus) = await DescribeSymbolAsync(parentPath, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (parentResult.ErrorCode != AdsErrorCode.NoError)
|
||||
return (null, MapAndSignal((uint)parentResult.ErrorCode));
|
||||
return (ExtractBit(parentResult.Value, bit), TwinCATStatusMapper.Good);
|
||||
if (parentStatus != TwinCATStatusMapper.Good) return (null, parentStatus);
|
||||
var bitStatus = TwinCATBitAccess.ParentStatus(bit, parent);
|
||||
if (bitStatus != TwinCATStatusMapper.Good) return (null, bitStatus);
|
||||
var (parentBytes, readStatus) = await ReadRawAsync(parentPath, parentSymbol!, parent.ByteSize, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return readStatus == TwinCATStatusMapper.Good
|
||||
? TwinCATBitAccess.ReadBitFromParent(parent, parentBytes, bit)
|
||||
: (null, readStatus);
|
||||
}
|
||||
|
||||
// Resolve the PLC symbol first so the declared type can be checked against it. The symbol is
|
||||
@@ -165,6 +243,10 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
{
|
||||
return (null, MapAndSignal((uint)ex.ErrorCode));
|
||||
}
|
||||
catch (Exception ex) when (MapReadException(ex) is uint refused)
|
||||
{
|
||||
return (null, refused);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -242,6 +324,10 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
{
|
||||
results[i] = (null, MapAndSignal((uint)ex.ErrorCode));
|
||||
}
|
||||
catch (Exception ex) when (MapReadException(ex) is uint refused)
|
||||
{
|
||||
results[i] = (null, refused);
|
||||
}
|
||||
}
|
||||
|
||||
if (planned.Count == 0) return results;
|
||||
@@ -378,6 +464,7 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
return (default, null, null, MapAndSignal((uint)result.ErrorCode));
|
||||
if (result.Value is not { } symbol)
|
||||
return (default, null, null, TwinCATStatusMapper.BadNodeIdUnknown);
|
||||
EnsureSymbolVersionHook();
|
||||
|
||||
// Resolve aliases (T_MaxString → STRING(255)) so the guard sees the base type, and take the
|
||||
// resolved type's byte size — a TwinCAT 2 member symbol's own ByteSize is under-reported.
|
||||
@@ -656,7 +743,9 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
if (parentStatus != TwinCATStatusMapper.Good)
|
||||
throw RegistrationFailure(registerPath, "resolving the parent word", parentStatus);
|
||||
if (TwinCATBitAccess.CheckParent(bit, parent) is { } bitReason)
|
||||
throw new TwinCATTypeMismatchException(symbolPath, bitReason);
|
||||
throw TwinCATBitAccess.ParentStatus(bit, parent) == TwinCATStatusMapper.BadTypeMismatch
|
||||
? new TwinCATTypeMismatchException(symbolPath, bitReason)
|
||||
: new TwinCATNotificationRefusedException(symbolPath, bitReason, TwinCATStatusMapper.BadOutOfRange);
|
||||
clrType = typeof(byte[]);
|
||||
anyTypeArgs = [parent.ByteSize];
|
||||
}
|
||||
@@ -971,6 +1060,10 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
_client.AdsNotificationEx -= OnAdsNotificationEx;
|
||||
_client.AdsNotificationError -= OnAdsNotificationError;
|
||||
_client.AdsNotificationsInvalidated -= OnAdsNotificationsInvalidated;
|
||||
// AdsSymbolVersionChanged is not unhooked: removing the last delegate unregisters on the wire, and the
|
||||
// client is disposed right below anyway (SignalSymbolTableChanged ignores a disposed client).
|
||||
_notifications.Clear();
|
||||
|
||||
// Stop the dispatch loop: complete the queue so the reader drains + exits, then
|
||||
@@ -1107,17 +1200,6 @@ internal sealed class AdsTwinCATClient : ITwinCATClient
|
||||
string s => s.Contains("inf", StringComparison.OrdinalIgnoreCase) || s.Contains('∞'),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static bool ExtractBit(object? rawWord, int bit) => rawWord switch
|
||||
{
|
||||
short s => (s & (1 << bit)) != 0,
|
||||
ushort us => (us & (1 << bit)) != 0,
|
||||
int i => (i & (1 << bit)) != 0,
|
||||
uint ui => (ui & (1u << bit)) != 0,
|
||||
long l => (l & (1L << bit)) != 0,
|
||||
ulong ul => (ul & (1UL << bit)) != 0,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Default <see cref="ITwinCATClientFactory"/> — one <see cref="AdsTwinCATClient"/> per call.</summary>
|
||||
|
||||
@@ -32,6 +32,41 @@ internal static class TwinCATBitAccess
|
||||
: $"bit {bit} is outside the {parent.ByteSize * 8}-bit parent {parent.TypeName}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The status every bit path — poll read, native notification and write — gives a (parent, bit) pair:
|
||||
/// Good when the bit addresses an integer parent; <c>BadTypeMismatch</c> for a parent that is not an
|
||||
/// integer word; <c>BadOutOfRange</c> for a bit beyond the parent's width (lmxopcua#982 P-25: the poll read
|
||||
/// used to read the parent as a 32-bit uint and return Good <c>false</c> for bit 20 of a 16-bit WORD).
|
||||
/// </summary>
|
||||
/// <param name="bit">The bit index.</param>
|
||||
/// <param name="parent">The parent symbol's resolved shape.</param>
|
||||
/// <returns>The status shared by the three paths.</returns>
|
||||
public static uint ParentStatus(int bit, TwinCATPlcSymbolShape parent)
|
||||
{
|
||||
if (CheckParent(bit, parent) is null) return TwinCATStatusMapper.Good;
|
||||
return parent.Kind != TwinCATPlcKind.Scalar || parent.IsFloat
|
||||
? TwinCATStatusMapper.BadTypeMismatch
|
||||
: TwinCATStatusMapper.BadOutOfRange;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The decode step of a bit-indexed BOOL poll read: checks the bit against the parent
|
||||
/// (<see cref="ParentStatus"/>) and reads it from the parent's raw bytes at the parent's OWN width.
|
||||
/// </summary>
|
||||
/// <param name="parent">The parent symbol's resolved shape.</param>
|
||||
/// <param name="bytes">The parent's raw bytes as read from the PLC.</param>
|
||||
/// <param name="bit">The bit index.</param>
|
||||
/// <returns>The bit with Good, or no value with the refusal status; <c>BadCommunicationError</c> for a
|
||||
/// read shorter than the parent.</returns>
|
||||
public static (object? value, uint status) ReadBitFromParent(TwinCATPlcSymbolShape parent, ReadOnlySpan<byte> bytes,
|
||||
int bit)
|
||||
{
|
||||
var status = ParentStatus(bit, parent);
|
||||
if (status != TwinCATStatusMapper.Good) return (null, status);
|
||||
if (bytes.Length < parent.ByteSize || bit / 8 >= bytes.Length) return (null, TwinCATStatusMapper.BadCommunicationError);
|
||||
return (ReadBit(bytes, bit), TwinCATStatusMapper.Good);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The modify step of a bit write's read-modify-write: checks the bit against the parent
|
||||
/// (<see cref="CheckParent"/>) and returns the parent's bytes — exactly <c>parent.ByteSize</c> of them —
|
||||
@@ -49,10 +84,8 @@ internal static class TwinCATBitAccess
|
||||
out byte[] updated)
|
||||
{
|
||||
updated = [];
|
||||
if (CheckParent(bit, parent) is not null)
|
||||
return parent.Kind != TwinCATPlcKind.Scalar || parent.IsFloat
|
||||
? TwinCATStatusMapper.BadTypeMismatch
|
||||
: TwinCATStatusMapper.BadOutOfRange;
|
||||
var parentStatus = ParentStatus(bit, parent);
|
||||
if (parentStatus != TwinCATStatusMapper.Good) return parentStatus;
|
||||
if (current.Length < parent.ByteSize) return TwinCATStatusMapper.BadCommunicationError;
|
||||
|
||||
var bytes = current[..parent.ByteSize].ToArray();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -46,8 +46,10 @@ public static class TwinCATStatusMapper
|
||||
|
||||
/// <summary>
|
||||
/// Map an AMS / ADS error code (uint cast from <c>AdsErrorCode</c> enum) to an OPC UA
|
||||
/// StatusCode. 0 = success. Device-layer codes (0x0700–0x073F) cover the operations a
|
||||
/// driver actually encounters during normal runtime.
|
||||
/// StatusCode. 0 = success. Device-layer codes (0x0700–0x073F) are the device answering: the listed
|
||||
/// ones map to a specific status, every other one to <see cref="BadDeviceFailure"/> (a refusal, never a
|
||||
/// comms fault) — except <c>DeviceTimeOut</c> (1817), which is a timeout. Anything outside that range
|
||||
/// (AMS / router / client-layer / socket) is a comms failure.
|
||||
/// </summary>
|
||||
/// <param name="adsError">The ADS error code to map.</param>
|
||||
/// <returns>The corresponding OPC UA status code.</returns>
|
||||
@@ -69,7 +71,6 @@ public static class TwinCATStatusMapper
|
||||
1798 => BadTypeMismatch, // DeviceInvalidData (data format mismatch)
|
||||
1799 => BadOutOfService, // DeviceNotReady (PLC not running / in config)
|
||||
1804 => BadNodeIdUnknown, // DeviceNotFound
|
||||
1807 => BadDeviceFailure, // DeviceIncompatible (0x070E)
|
||||
1808 => BadNodeIdUnknown, // DeviceSymbolNotFound (0x0710)
|
||||
1809 => BadInvalidState, // DeviceSymbolVersionInvalid — rediscovery trigger
|
||||
1810 => BadInvalidState, // DeviceInvalidState (PLC in Config mode, 0x0712)
|
||||
@@ -77,10 +78,25 @@ public static class TwinCATStatusMapper
|
||||
1812 => BadNodeIdUnknown, // DeviceNotifyHandleInvalid (stale handle, 0x0714)
|
||||
1827 => BadNotWritable, // DeviceAccessDenied (0x0723)
|
||||
1844 => BadOutOfRange, // DeviceOutOfRange (0x0734)
|
||||
1817 => BadTimeout, // DeviceTimeOut (0x0719) — the remote did not answer in time
|
||||
|
||||
// Every other device-layer code (0x0700–0x073F: 1800 Busy, 1803 InvalidParam, 1805 SyntaxError,
|
||||
// 1806 Incompatible, 1814 NoMoreHandles, 1815 InvalidWatchsize, 1828+ licence, …) is the DEVICE
|
||||
// answering and refusing this request. It must not map to a comms status: the driver would degrade
|
||||
// health and the comms-loss watchdog would reconnect a device that is talking to it (lmxopcua#982 P-12).
|
||||
>= DeviceLayerFirst and <= DeviceLayerLast => BadDeviceFailure,
|
||||
|
||||
// Client-layer timeout
|
||||
1861 => BadTimeout, // ClientSyncTimeOut (0x0745)
|
||||
|
||||
// General AMS (< 0x500), router (0x500), client-layer (0x740+) and socket (WSA) codes: the request
|
||||
// never got a device answer.
|
||||
_ => BadCommunicationError,
|
||||
};
|
||||
|
||||
/// <summary>First ADS device-layer error code (<c>DeviceError</c>, 0x0700).</summary>
|
||||
public const uint DeviceLayerFirst = 0x0700u;
|
||||
|
||||
/// <summary>Last ADS device-layer error code (0x073F); client-layer codes start at 0x0740.</summary>
|
||||
public const uint DeviceLayerLast = 0x073Fu;
|
||||
}
|
||||
|
||||
@@ -39,11 +39,18 @@ public sealed record TwinCATSymbolPath(
|
||||
return buf.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test seam: when a test sets a counter on its own async flow, every <see cref="TryParse"/> made on that flow
|
||||
/// counts — proves the read path parses nothing per tag (lmxopcua#982 P-19). Never set in production.
|
||||
/// </summary>
|
||||
internal static readonly AsyncLocal<System.Runtime.CompilerServices.StrongBox<int>?> ParseCounterForTest = new();
|
||||
|
||||
/// <summary>Attempts to parse a TwinCAT symbol path from the given string.</summary>
|
||||
/// <param name="value">The path string to parse.</param>
|
||||
/// <returns>A TwinCATSymbolPath if parsing succeeds; otherwise null.</returns>
|
||||
public static TwinCATSymbolPath? TryParse(string? value)
|
||||
{
|
||||
if (ParseCounterForTest.Value is { } counter) Interlocked.Increment(ref counter.Value);
|
||||
if (string.IsNullOrWhiteSpace(value)) return null;
|
||||
var src = value.Trim();
|
||||
|
||||
|
||||
@@ -25,8 +25,10 @@ internal enum TwinCATPlcKind
|
||||
/// <param name="IsFloat">True for a REAL / LREAL scalar.</param>
|
||||
/// <param name="TypeName">The (alias-resolved) PLC type name, for log messages.</param>
|
||||
/// <param name="IsArray">True for an ARRAY (a <see cref="TwinCATPlcKind.NonScalar"/> with array category or name).</param>
|
||||
/// <param name="IsAddress">True for a POINTER / REFERENCE / <c>VAR_IN_OUT</c> — a <see cref="TwinCATPlcKind.NonScalar"/>
|
||||
/// whose own bytes are an address a scalar read may legitimately return.</param>
|
||||
internal readonly record struct TwinCATPlcSymbolShape(
|
||||
TwinCATPlcKind Kind, int ByteSize, bool IsFloat, string TypeName, bool IsArray = false)
|
||||
TwinCATPlcKind Kind, int ByteSize, bool IsFloat, string TypeName, bool IsArray = false, bool IsAddress = false)
|
||||
{
|
||||
private static readonly Regex StringTypeName =
|
||||
new(@"^(W?)STRING(\s*\(\s*\d+\s*\))?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
@@ -53,7 +55,7 @@ internal readonly record struct TwinCATPlcSymbolShape(
|
||||
{
|
||||
if (symbolTypeName?.Contains("VAR_IN_OUT", StringComparison.OrdinalIgnoreCase) == true
|
||||
|| typeName?.Contains("VAR_IN_OUT", StringComparison.OrdinalIgnoreCase) == true)
|
||||
return new(TwinCATPlcKind.NonScalar, byteSize, false, (symbolTypeName ?? typeName)!.Trim());
|
||||
return new(TwinCATPlcKind.NonScalar, byteSize, false, (symbolTypeName ?? typeName)!.Trim(), IsAddress: true);
|
||||
|
||||
if (dataTypeByteSize is > 0) byteSize = dataTypeByteSize.Value;
|
||||
var name = (typeName ?? string.Empty).Trim();
|
||||
@@ -74,7 +76,11 @@ internal readonly record struct TwinCATPlcSymbolShape(
|
||||
|| name.StartsWith("REFERENCE TO", StringComparison.OrdinalIgnoreCase)
|
||||
|| name.Contains("VAR_IN_OUT", StringComparison.OrdinalIgnoreCase))
|
||||
return new(TwinCATPlcKind.NonScalar, byteSize, false, name,
|
||||
IsArray: category == DataTypeCategory.Array || name.StartsWith("ARRAY", StringComparison.OrdinalIgnoreCase));
|
||||
IsArray: category == DataTypeCategory.Array || name.StartsWith("ARRAY", StringComparison.OrdinalIgnoreCase),
|
||||
IsAddress: category is DataTypeCategory.Pointer or DataTypeCategory.Reference
|
||||
|| name.StartsWith("POINTER TO", StringComparison.OrdinalIgnoreCase)
|
||||
|| name.StartsWith("REFERENCE TO", StringComparison.OrdinalIgnoreCase)
|
||||
|| name.Contains("VAR_IN_OUT", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
var mapped = AdsTwinCATClient.MapSymbolTypeName(name);
|
||||
return new(TwinCATPlcKind.Scalar, byteSize, mapped is TwinCATDataType.Real or TwinCATDataType.LReal, name);
|
||||
@@ -151,8 +157,14 @@ internal static class TwinCATTypeGuard
|
||||
if (plc.IsArray)
|
||||
return $"declared scalar {declared} but the PLC symbol is the array {plc.TypeName} ({plc.ByteSize} B) — " +
|
||||
"author it as an array tag (isArray + arrayLength) or address one element (Arr[i])";
|
||||
return plc.Kind is TwinCATPlcKind.String or TwinCATPlcKind.WString
|
||||
? $"declared {declared} but the PLC symbol is the string {plc.TypeName} — declare it String/WString"
|
||||
if (plc.Kind is TwinCATPlcKind.String or TwinCATPlcKind.WString)
|
||||
return $"declared {declared} but the PLC symbol is the string {plc.TypeName} — declare it String/WString";
|
||||
// A struct / FB / program / union / interface has no scalar value: the Beckhoff marshaller throws
|
||||
// converting it to the declared CLR type, and that exception used to surface as a comms fault
|
||||
// (lmxopcua#982 P-12). Refuse it here, as the notification guard already does. A pointer / reference /
|
||||
// VAR_IN_OUT is still left to the read (it returns the address — an established, if odd, use).
|
||||
return plc.Kind == TwinCATPlcKind.NonScalar && !plc.IsAddress
|
||||
? $"declared scalar {declared} but the PLC symbol is {plc.TypeName} ({plc.ByteSize} B) — not a scalar"
|
||||
: null;
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@ internal class FakeTwinCATClient : ITwinCATClient
|
||||
public virtual Task ConnectAsync(TwinCATAmsAddress address, TimeSpan timeout, CancellationToken ct)
|
||||
{
|
||||
ConnectCount++;
|
||||
LastConnectTimeout = timeout;
|
||||
ConnectedAddress = address;
|
||||
if (ThrowOnConnect) throw Exception ?? new InvalidOperationException();
|
||||
if (BlockConnect is { } block)
|
||||
{
|
||||
@@ -66,6 +68,12 @@ internal class FakeTwinCATClient : ITwinCATClient
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Gets the timeout the most recent <see cref="ConnectAsync"/> was given.</summary>
|
||||
public TimeSpan? LastConnectTimeout { get; private set; }
|
||||
|
||||
/// <summary>Gets the AMS address the most recent <see cref="ConnectAsync"/> targeted.</summary>
|
||||
public TwinCATAmsAddress? ConnectedAddress { get; private set; }
|
||||
|
||||
/// <summary>When set, <see cref="ConnectAsync"/> does not complete (and ignores cancellation) until this
|
||||
/// is completed — a probe wedged in the synchronous ADS <c>Connect</c>.</summary>
|
||||
public TaskCompletionSource? BlockConnect { get; set; }
|
||||
@@ -94,6 +102,7 @@ internal class FakeTwinCATClient : ITwinCATClient
|
||||
}
|
||||
if (ThrowOnRead) throw Exception ?? new InvalidOperationException();
|
||||
Interlocked.Increment(ref _singleReadCount);
|
||||
ReadSymbols.Enqueue(symbolPath);
|
||||
LastReadArrayCount = arrayCount;
|
||||
var status = ReadStatuses.TryGetValue(symbolPath, out var s) ? s : TwinCATStatusMapper.Good;
|
||||
var value = Values.TryGetValue(symbolPath, out var v) ? v : null;
|
||||
@@ -106,6 +115,9 @@ internal class FakeTwinCATClient : ITwinCATClient
|
||||
|
||||
private int _singleReadCount;
|
||||
|
||||
/// <summary>Gets every symbol an individual <see cref="ReadValueAsync"/> was served for, in order.</summary>
|
||||
public ConcurrentQueue<string> ReadSymbols { get; } = new();
|
||||
|
||||
/// <summary>Gets the number of individual <see cref="ReadValueAsync"/> calls served.</summary>
|
||||
public int SingleReadCount { get => Volatile.Read(ref _singleReadCount); private set => Volatile.Write(ref _singleReadCount, value); }
|
||||
/// <summary>Gets the size of each <see cref="ReadValuesAsync"/> batch the driver issued, in order (#645).</summary>
|
||||
@@ -277,6 +289,11 @@ internal class FakeTwinCATClient : ITwinCATClient
|
||||
/// <param name="symbolPath">The symbol path.</param>
|
||||
/// <returns>The attempt count.</returns>
|
||||
public int AttemptsFor(string symbolPath) => _addAttempts.TryGetValue(symbolPath, out var n) ? n : 0;
|
||||
|
||||
private int _totalAddAttempts;
|
||||
|
||||
/// <summary>Gets how many times <see cref="AddNotificationAsync"/> was called on this client, for any symbol.</summary>
|
||||
public int TotalAddAttempts => Volatile.Read(ref _totalAddAttempts);
|
||||
/// <summary>Records the most recently-supplied <c>maxDelayMs</c> for Driver.TwinCAT-014 tests.</summary>
|
||||
public int LastMaxDelayMs { get; private set; }
|
||||
/// <summary>When set, <see cref="AddNotificationAsync"/> awaits this gate BEFORE applying
|
||||
@@ -301,6 +318,7 @@ internal class FakeTwinCATClient : ITwinCATClient
|
||||
int maxDelayMs, Action<string, object?> onChange, CancellationToken cancellationToken)
|
||||
{
|
||||
_addAttempts.AddOrUpdate(symbolPath, 1, (_, n) => n + 1);
|
||||
Interlocked.Increment(ref _totalAddAttempts);
|
||||
if (PreAttemptGate is { } pre) await pre.Task.ConfigureAwait(false);
|
||||
if (ThrowOnAddNotification)
|
||||
throw Exception ?? new InvalidOperationException("fake AddNotification failure");
|
||||
|
||||
@@ -208,7 +208,11 @@ public sealed class TwinCATDiagnosticsTests
|
||||
bag.Count.ShouldBe(12);
|
||||
}
|
||||
|
||||
/// <summary>Verifies sampling is opt-in: with it off the probe loop adds no reads and the bag stays empty.</summary>
|
||||
/// <summary>
|
||||
/// Verifies sampling is opt-in: with it off the bag stays empty and the probe loop reads nothing but the
|
||||
/// PLC's online-change counter — the one read per tick lmxopcua#982 P-1 needs to detect an online change
|
||||
/// (which raises no ADS symbol-version event). App name / cycle / exec time stay diagnostics-only.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Disabled_by_default_adds_no_reads()
|
||||
{
|
||||
@@ -223,7 +227,10 @@ public sealed class TwinCATDiagnosticsTests
|
||||
}
|
||||
finally { await drv.ShutdownAsync(CancellationToken.None); }
|
||||
|
||||
factory.Clients[0].SingleReadCount.ShouldBe(0);
|
||||
factory.Clients[0].ReadSymbols.ShouldAllBe(s => s == TwinCATDriver.SymOnlineChangeCnt);
|
||||
factory.Clients[0].ReadSymbols.ShouldNotBeEmpty("the online-change counter is sampled every healthy tick");
|
||||
factory.Clients[0].SingleReadCount.ShouldBeLessThanOrEqualTo(factory.Clients[0].ProbeCount,
|
||||
"at most one read per probe tick");
|
||||
((IDriverDiagnostics)drv).GetDiagnostics().ShouldBeEmpty();
|
||||
}
|
||||
|
||||
|
||||
+12
-11
@@ -63,12 +63,15 @@ public sealed class TwinCATLowFindingsRegressionTests
|
||||
|
||||
// ---- Driver.TwinCAT-014 — config surface knobs are honoured ----
|
||||
|
||||
/// <summary>Verifies that ProbeOptions.Timeout is applied to probe calls.</summary>
|
||||
/// <summary>
|
||||
/// Verifies the probe's timeout bounds the probe's own state read — and only that. lmxopcua#982 P-22 reversed
|
||||
/// the original Driver.TwinCAT-014 fix, which passed the probe timeout to the CONNECT: the probe loop usually
|
||||
/// creates the device's client (and re-creates it after every recycle), so its 750 ms then governed every
|
||||
/// data read, silently overriding a raised driver <c>Timeout</c>.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ProbeOptions_Timeout_is_applied_to_probe_calls()
|
||||
public async Task ProbeOptions_Timeout_bounds_the_probe_call_not_the_client()
|
||||
{
|
||||
// The previous implementation declared a Timeout field but never read it — the probe
|
||||
// path connected with _options.Timeout. The probe must use its own configured timeout.
|
||||
var observed = new List<TimeSpan>();
|
||||
var factory = new FakeTwinCATClientFactory
|
||||
{
|
||||
@@ -81,16 +84,16 @@ public sealed class TwinCATLowFindingsRegressionTests
|
||||
{
|
||||
Enabled = true,
|
||||
Interval = TimeSpan.FromMilliseconds(100),
|
||||
Timeout = TimeSpan.FromMilliseconds(750), // distinct from the connect timeout
|
||||
Timeout = TimeSpan.FromMilliseconds(750), // distinct from the driver timeout
|
||||
},
|
||||
Timeout = TimeSpan.FromMilliseconds(2_000),
|
||||
}, "drv-1", factory);
|
||||
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
await WaitForAsync(() => observed.Count >= 1, TimeSpan.FromSeconds(2));
|
||||
await WaitForAsync(() => { lock (observed) return observed.Count >= 1; }, TimeSpan.FromSeconds(2));
|
||||
await drv.ShutdownAsync(CancellationToken.None);
|
||||
|
||||
observed.ShouldContain(TimeSpan.FromMilliseconds(750));
|
||||
lock (observed) observed.ShouldAllBe(t => t == TimeSpan.FromMilliseconds(2_000));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that NotificationMaxDelayMs is exposed on driver options.</summary>
|
||||
@@ -242,7 +245,7 @@ public sealed class TwinCATLowFindingsRegressionTests
|
||||
await Task.Delay(20);
|
||||
}
|
||||
|
||||
/// <summary>Captures the timeout argument from ProbeAsync invocations (via the connect path).</summary>
|
||||
/// <summary>Captures the timeout argument the client is connected with.</summary>
|
||||
private sealed class ProbeTimeoutCapturingFake : FakeTwinCATClient
|
||||
{
|
||||
private readonly List<TimeSpan> _observed;
|
||||
@@ -254,9 +257,7 @@ public sealed class TwinCATLowFindingsRegressionTests
|
||||
/// <inheritdoc />
|
||||
public override Task ConnectAsync(TwinCATAmsAddress address, TimeSpan timeout, CancellationToken ct)
|
||||
{
|
||||
// The driver calls EnsureConnectedAsync with the probe timeout for probe-initiated
|
||||
// connects. The probe timeout is distinct from the driver-level Timeout; we record
|
||||
// it on the first connect.
|
||||
// Every connect — the probe's included — must carry the driver-level Timeout.
|
||||
lock (_observed) _observed.Add(timeout);
|
||||
return base.ConnectAsync(address, timeout, ct);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,712 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using Shouldly;
|
||||
using TwinCAT.TypeSystem;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.TwinCAT;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#982 — the TwinCAT findings of the 2026-12-02 review
|
||||
/// (<c>docs/reviews/2026-12-02/09-ab-twincat-focas.md</c>): P-1 symbol-table invalidation (online change /
|
||||
/// program download), P-3 one dead device stalling the rest, P-4 the probe replaying every registration
|
||||
/// against an offline PLC, P-12 device refusals counted as comms faults, P-19 per-tag health + parse cost,
|
||||
/// P-22 the probe's timeout replacing the driver's, P-25 the bit-read parent check.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class TwinCATReview20261202Tests
|
||||
{
|
||||
private const string HostA = "ads://5.23.91.23.1.1:851";
|
||||
private const string HostB = "ads://5.23.91.24.1.1:851";
|
||||
|
||||
private static TwinCATProbeOptions NoProbe => new() { Enabled = false };
|
||||
|
||||
private static TwinCATProbeOptions FastProbe => new()
|
||||
{
|
||||
Enabled = true,
|
||||
Interval = TimeSpan.FromMilliseconds(30),
|
||||
Timeout = TimeSpan.FromMilliseconds(200),
|
||||
};
|
||||
|
||||
private static TwinCATDriver NewDriver(FakeTwinCATClientFactory factory, TwinCATProbeOptions probe, bool native,
|
||||
TwinCATCapturingLogger? logger, string[] hosts, params TwinCATTagDefinition[] tags) =>
|
||||
new(new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [.. hosts.Select(h => new TwinCATDeviceOptions(h))],
|
||||
RawTags = TwinCATRawTags.Entries(tags),
|
||||
Probe = probe,
|
||||
UseNativeNotifications = native,
|
||||
Timeout = TimeSpan.FromSeconds(2),
|
||||
}, "drv-982", factory, logger);
|
||||
|
||||
private static async Task WaitForAsync(Func<bool> condition, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!condition() && DateTime.UtcNow < deadline)
|
||||
await Task.Delay(10);
|
||||
}
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
// ======================= P-1 — symbol-table invalidation =======================
|
||||
|
||||
/// <summary>
|
||||
/// A fake factory whose every client is a new "generation": a read through client <c>n</c> returns
|
||||
/// <c>n * 100 + 11</c>. A read through a stale client (generation 1 after a program change) therefore
|
||||
/// returns a recognisably stale value — the model of a cached IndexGroup/IndexOffset now addressing other memory.
|
||||
/// </summary>
|
||||
private static FakeTwinCATClientFactory GenerationalFactory()
|
||||
{
|
||||
var generation = 0;
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
factory.Customise = () =>
|
||||
{
|
||||
var c = new FakeTwinCATClient();
|
||||
var g = Interlocked.Increment(ref generation);
|
||||
c.Values["MAIN.X"] = g * 100 + 11;
|
||||
return c;
|
||||
};
|
||||
return factory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-1: after a symbol-version change the next read must not run on the client whose symbol cache holds the
|
||||
/// old offsets. Before the fix the signal only raised the advisory rediscovery event; the read went straight
|
||||
/// back through the cached client and published the stale-offset value at Good.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_symbol_version_change_retires_the_client_so_the_next_read_re_resolves()
|
||||
{
|
||||
var factory = GenerationalFactory();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldBe(111);
|
||||
factory.Clients[0].FireSymbolVersionChanged();
|
||||
|
||||
var after = (await drv.ReadAsync(["X"], Ct))[0];
|
||||
after.StatusCode.ShouldBe(TwinCATStatusMapper.Good);
|
||||
after.Value.ShouldBe(211, "the read must run on a fresh client (fresh symbol table), not the stale one");
|
||||
factory.Clients.Count.ShouldBe(2);
|
||||
factory.Clients[0].DisposeCount.ShouldBe(1, "the stale client is disposed");
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-1 (native): a program download drops the PLC's notifications while every registration still holds a
|
||||
/// handle. The symbol-version signal must re-register every notification on a fresh client — with the probe
|
||||
/// disabled, so nothing else would ever do it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_symbol_version_change_re_registers_every_native_notification_on_a_fresh_client()
|
||||
{
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
var drv = NewDriver(factory, NoProbe, native: true, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt),
|
||||
new TwinCATTagDefinition("Y", HostA, "MAIN.Y", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
_ = await drv.SubscribeAsync(["X", "Y"], TimeSpan.FromMilliseconds(100), Ct);
|
||||
factory.Clients.Single().Notifications.Count.ShouldBe(2);
|
||||
|
||||
factory.Clients[0].FireSymbolVersionChanged();
|
||||
|
||||
await WaitForAsync(() => factory.Clients.Count >= 2 && factory.Clients[1].Notifications.Count == 2,
|
||||
TimeSpan.FromSeconds(3));
|
||||
factory.Clients.Count.ShouldBe(2);
|
||||
factory.Clients[1].Notifications.Select(n => n.SymbolPath).ShouldBe(["MAIN.X", "MAIN.Y"], ignoreOrder: true);
|
||||
|
||||
// A value the retired client still pushes is not published (its handle addressed the old program).
|
||||
var events = new ConcurrentQueue<DataChangeEventArgs>();
|
||||
drv.OnDataChange += (_, e) => events.Enqueue(e);
|
||||
factory.Clients[1].FireNotification("MAIN.X", 42);
|
||||
await WaitForAsync(() => !events.IsEmpty, TimeSpan.FromSeconds(1));
|
||||
events.ShouldHaveSingleItem().Snapshot.Value.ShouldBe(42);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-1: a Stop → download → Run on a target whose port keeps answering never fails the probe. The probe's
|
||||
/// own ReadState shows the non-Run → Run transition; it must retire the client and replay the registrations.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_Plc_Stop_then_Run_without_a_probe_failure_replays_the_registrations()
|
||||
{
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
var drv = NewDriver(factory, FastProbe, native: true, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
_ = await drv.SubscribeAsync(["X"], TimeSpan.FromMilliseconds(100), Ct);
|
||||
var first = factory.Clients.Single();
|
||||
first.AdsStateText = "Run";
|
||||
var probes = first.ProbeCount;
|
||||
await WaitForAsync(() => first.ProbeCount >= probes + 2, TimeSpan.FromSeconds(3));
|
||||
first.AdsStateText = "Stop";
|
||||
probes = first.ProbeCount;
|
||||
await WaitForAsync(() => first.ProbeCount >= probes + 2, TimeSpan.FromSeconds(3));
|
||||
factory.Clients.Count.ShouldBe(1, "a stopped PLC that still answers is not a reason to rebuild");
|
||||
|
||||
first.AdsStateText = "Run";
|
||||
await WaitForAsync(() => factory.Clients.Count >= 2 && factory.Clients[1].Notifications.Count == 1,
|
||||
TimeSpan.FromSeconds(3));
|
||||
factory.Clients.Count.ShouldBeGreaterThanOrEqualTo(2);
|
||||
factory.Clients[1].Notifications.ShouldHaveSingleItem().SymbolPath.ShouldBe("MAIN.X");
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-1: an ONLINE change does not raise the ADS symbol-version event (Beckhoff: "online changes … don't trigger
|
||||
/// the SymbolVersionChanged event") yet can relocate variables. The probe samples <c>OnlineChangeCnt</c> on every
|
||||
/// healthy tick (not only with diagnostics on) and retires the client when it moves.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_online_change_counter_change_retires_the_client()
|
||||
{
|
||||
var factory = GenerationalFactory();
|
||||
var drv = NewDriver(factory, FastProbe, native: false, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldBe(111);
|
||||
var first = factory.Clients.Single();
|
||||
first.Values[TwinCATDriver.SymOnlineChangeCnt] = 5u;
|
||||
var probes = first.ProbeCount;
|
||||
await WaitForAsync(() => first.ProbeCount >= probes + 3, TimeSpan.FromSeconds(3));
|
||||
factory.Clients.Count.ShouldBe(1, "an unchanged counter keeps the client (positive control)");
|
||||
|
||||
first.Values[TwinCATDriver.SymOnlineChangeCnt] = 6u;
|
||||
await WaitForAsync(() => factory.Clients.Count >= 2, TimeSpan.FromSeconds(3));
|
||||
factory.Clients.Count.ShouldBeGreaterThanOrEqualTo(2);
|
||||
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldNotBe(111);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-1: a sum-read with N symbol-version sub-errors signals N times; rediscovery is raised once per event,
|
||||
/// and a signal from a client already retired is ignored.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Repeated_symbol_version_signals_from_one_client_raise_rediscovery_once()
|
||||
{
|
||||
var factory = GenerationalFactory();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
var raised = 0;
|
||||
drv.OnRediscoveryNeeded += (_, _) => Interlocked.Increment(ref raised);
|
||||
_ = await drv.ReadAsync(["X"], Ct);
|
||||
|
||||
for (var i = 0; i < 5; i++) factory.Clients[0].FireSymbolVersionChanged();
|
||||
raised.ShouldBe(1);
|
||||
|
||||
_ = await drv.ReadAsync(["X"], Ct); // the read retires client 0
|
||||
factory.Clients[0].FireSymbolVersionChanged(); // a late signal from the retired client
|
||||
raised.ShouldBe(1);
|
||||
|
||||
factory.Clients[1].FireSymbolVersionChanged(); // a NEW event on the live client (positive control)
|
||||
raised.ShouldBe(2);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
// ======================= P-3 — one dead device stalls the rest =======================
|
||||
|
||||
/// <summary>A client that, for one AMS target, waits <see cref="Delay"/> and answers BadTimeout (a silent PLC).</summary>
|
||||
private sealed class SilentTargetFake(string silentNetId, TimeSpan delay, bool targetAnswersProbe) : FakeTwinCATClient
|
||||
{
|
||||
public TimeSpan Delay { get; } = delay;
|
||||
private int _silentReads;
|
||||
public int SilentReads => Volatile.Read(ref _silentReads);
|
||||
private bool Silent => ConnectedAddress?.NetId == silentNetId;
|
||||
|
||||
public override async Task<(object? value, uint status)> ReadValueAsync(
|
||||
string symbolPath, TwinCATDataType type, int? bitIndex, int? arrayCount, CancellationToken ct)
|
||||
{
|
||||
if (!Silent || symbolPath.StartsWith("TwinCAT_SystemInfoVarList", StringComparison.Ordinal)
|
||||
|| symbolPath.StartsWith(".SYSTEM", StringComparison.Ordinal))
|
||||
return await base.ReadValueAsync(symbolPath, type, bitIndex, arrayCount, ct);
|
||||
Interlocked.Increment(ref _silentReads);
|
||||
await Task.Delay(Delay, ct);
|
||||
return (null, TwinCATStatusMapper.BadTimeout);
|
||||
}
|
||||
|
||||
public override async Task<IReadOnlyList<(object? value, uint status)>> ReadValuesAsync(
|
||||
IReadOnlyList<TwinCATBulkReadItem> reads, CancellationToken ct)
|
||||
{
|
||||
if (!Silent) return await base.ReadValuesAsync(reads, ct);
|
||||
Interlocked.Increment(ref _silentReads);
|
||||
await Task.Delay(Delay, ct);
|
||||
throw new TimeoutException("sum-read timed out");
|
||||
}
|
||||
|
||||
public override Task<bool> ProbeAsync(CancellationToken ct) =>
|
||||
Silent && !targetAnswersProbe ? Task.FromResult(false) : base.ProbeAsync(ct);
|
||||
|
||||
public override async Task<ITwinCATNotificationHandle> AddNotificationAsync(string symbolPath,
|
||||
TwinCATDataType type, int? bitIndex, int? arrayCount, TimeSpan cycleTime, int maxDelayMs,
|
||||
Action<string, object?> onChange, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Silent)
|
||||
return await base.AddNotificationAsync(symbolPath, type, bitIndex, arrayCount, cycleTime, maxDelayMs,
|
||||
onChange, cancellationToken);
|
||||
Interlocked.Increment(ref _silentReads);
|
||||
await Task.Delay(Delay, cancellationToken);
|
||||
throw new InvalidOperationException($"AddDeviceNotificationEx for {symbolPath} timed out");
|
||||
}
|
||||
}
|
||||
|
||||
private static (FakeTwinCATClientFactory factory, List<SilentTargetFake> clients) SilentFactory(
|
||||
TimeSpan delay, bool targetAnswersProbe)
|
||||
{
|
||||
var clients = new List<SilentTargetFake>();
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
factory.Customise = () =>
|
||||
{
|
||||
var c = new SilentTargetFake("5.23.91.23.1.1", delay, targetAnswersProbe);
|
||||
lock (clients) clients.Add(c);
|
||||
return c;
|
||||
};
|
||||
return (factory, clients);
|
||||
}
|
||||
|
||||
private static TwinCATTagDefinition[] TagsOn(string host, string prefix, int count) =>
|
||||
[.. Enumerable.Range(0, count).Select(i =>
|
||||
new TwinCATTagDefinition($"{prefix}{i}", host, $"MAIN.{prefix}{i}", TwinCATDataType.DInt))];
|
||||
|
||||
/// <summary>
|
||||
/// P-3: device A stopped answering (its local AMS port still "connects"); device B is healthy. A's tags must
|
||||
/// not each pay the timeout one after another, and B's read must not wait behind them. Before the fix:
|
||||
/// 10 serial waits on A (≈ 10 × delay) and B read last.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task A_silent_device_fails_fast_and_does_not_stall_another_device(bool sumRead)
|
||||
{
|
||||
var delay = TimeSpan.FromMilliseconds(300);
|
||||
var (factory, clients) = SilentFactory(delay, targetAnswersProbe: false);
|
||||
var tags = TagsOn(HostA, "A", 10).Append(new TwinCATTagDefinition("B0", HostB, "MAIN.B0", TwinCATDataType.DInt))
|
||||
.ToArray();
|
||||
var drv = new TwinCATDriver(new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions(HostA), new TwinCATDeviceOptions(HostB)],
|
||||
RawTags = TwinCATRawTags.Entries(tags),
|
||||
Probe = NoProbe,
|
||||
UseSumRead = sumRead,
|
||||
SumReadMaxItems = 2,
|
||||
}, "drv-982", factory);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
var refs = tags.Select(t => t.Name).ToArray();
|
||||
foreach (var c in clients) c.Values["MAIN.B0"] = 7;
|
||||
factory.Customise = () =>
|
||||
{
|
||||
var c = new SilentTargetFake("5.23.91.23.1.1", delay, targetAnswersProbe: false);
|
||||
c.Values["MAIN.B0"] = 7;
|
||||
lock (clients) clients.Add(c);
|
||||
return c;
|
||||
};
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var results = await drv.ReadAsync(refs, Ct);
|
||||
sw.Stop();
|
||||
|
||||
sw.Elapsed.ShouldBeLessThan(delay * 5, "A's tags must short-circuit after the first comms failure");
|
||||
clients.Sum(c => c.SilentReads).ShouldBe(1, "one wire attempt on the silent device per call");
|
||||
results.Take(10).ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.BadCommunicationError
|
||||
|| r.StatusCode == TwinCATStatusMapper.BadTimeout);
|
||||
results[10].StatusCode.ShouldBe(TwinCATStatusMapper.Good);
|
||||
results[10].Value.ShouldBe(7);
|
||||
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-3 positive control: one slow TAG on a device that still answers its state probe is a per-tag failure —
|
||||
/// the device's other tags are still read (the short-circuit is reserved for a device that is gone).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task One_slow_tag_on_a_live_device_does_not_blank_its_siblings()
|
||||
{
|
||||
var delay = TimeSpan.FromMilliseconds(50);
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
factory.Customise = () =>
|
||||
{
|
||||
var c = new SlowSymbolFake("MAIN.A0", delay);
|
||||
for (var i = 1; i < 5; i++) c.Values[$"MAIN.A{i}"] = i;
|
||||
return c;
|
||||
};
|
||||
var tags = TagsOn(HostA, "A", 5);
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA], tags);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var results = await drv.ReadAsync([.. tags.Select(t => t.Name)], Ct);
|
||||
|
||||
results[0].StatusCode.ShouldBe(TwinCATStatusMapper.BadTimeout);
|
||||
results.Skip(1).ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.Good);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>A client on which one symbol times out while the device keeps answering.</summary>
|
||||
private sealed class SlowSymbolFake(string slowSymbol, TimeSpan delay) : FakeTwinCATClient
|
||||
{
|
||||
public override async Task<(object? value, uint status)> ReadValueAsync(
|
||||
string symbolPath, TwinCATDataType type, int? bitIndex, int? arrayCount, CancellationToken ct)
|
||||
{
|
||||
if (!string.Equals(symbolPath, slowSymbol, StringComparison.OrdinalIgnoreCase))
|
||||
return await base.ReadValueAsync(symbolPath, type, bitIndex, arrayCount, ct);
|
||||
await Task.Delay(delay, ct);
|
||||
return (null, TwinCATStatusMapper.BadTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-3 (subscribe): a native subscribe across a silent device and a healthy one must not pay one registration
|
||||
/// timeout per tag of the silent device before the healthy device registers.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_native_subscribe_does_not_pay_a_timeout_per_tag_of_a_silent_device()
|
||||
{
|
||||
var delay = TimeSpan.FromMilliseconds(200);
|
||||
var (factory, clients) = SilentFactory(delay, targetAnswersProbe: false);
|
||||
var tags = TagsOn(HostA, "A", 10).Append(new TwinCATTagDefinition("B0", HostB, "MAIN.B0", TwinCATDataType.DInt))
|
||||
.ToArray();
|
||||
var drv = NewDriver(factory, NoProbe, native: true, null, [HostA, HostB], tags);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
_ = await drv.SubscribeAsync([.. tags.Select(t => t.Name)], TimeSpan.FromMilliseconds(100), Ct);
|
||||
sw.Stop();
|
||||
|
||||
sw.Elapsed.ShouldBeLessThan(delay * 5);
|
||||
clients.Sum(c => c.SilentReads).ShouldBe(1);
|
||||
clients.Sum(c => c.Notifications.Count).ShouldBe(1, "device B registered");
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
// ======================= P-4 — probe replays against an offline PLC =======================
|
||||
|
||||
/// <summary>A client whose target can be switched off: probes fail and every registration fails comms-class.</summary>
|
||||
private sealed class OutageFake(Func<bool> offline) : FakeTwinCATClient
|
||||
{
|
||||
public override Task<bool> ProbeAsync(CancellationToken ct) =>
|
||||
offline() ? Task.FromResult(false) : base.ProbeAsync(ct);
|
||||
|
||||
public override Task<ITwinCATNotificationHandle> AddNotificationAsync(string symbolPath, TwinCATDataType type,
|
||||
int? bitIndex, int? arrayCount, TimeSpan cycleTime, int maxDelayMs, Action<string, object?> onChange,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (offline())
|
||||
{
|
||||
RecordAttempt();
|
||||
throw new InvalidOperationException("AddDeviceNotificationEx failed with status 0x80050000");
|
||||
}
|
||||
return base.AddNotificationAsync(symbolPath, type, bitIndex, arrayCount, cycleTime, maxDelayMs, onChange,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
private int _offlineAttempts;
|
||||
public int OfflineAttempts => Volatile.Read(ref _offlineAttempts);
|
||||
private void RecordAttempt() => Interlocked.Increment(ref _offlineAttempts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-4: with the PLC off, each probe tick used to build a client, "connect" (local), replay EVERY stored
|
||||
/// registration against the dead target — one failed AddNotification and one Warning each — and only then
|
||||
/// probe. Now the probe connects without replaying, probes, and replays only on success; one Warning per
|
||||
/// device per outage.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_offline_plc_is_probed_before_any_registration_is_replayed()
|
||||
{
|
||||
var offline = false;
|
||||
var clients = new List<OutageFake>();
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
factory.Customise = () =>
|
||||
{
|
||||
var c = new OutageFake(() => Volatile.Read(ref offline));
|
||||
lock (clients) clients.Add(c);
|
||||
return c;
|
||||
};
|
||||
var logger = new TwinCATCapturingLogger();
|
||||
var tags = TagsOn(HostA, "N", 100);
|
||||
var drv = NewDriver(factory, FastProbe, native: true, logger, [HostA], tags);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
_ = await drv.SubscribeAsync([.. tags.Select(t => t.Name)], TimeSpan.FromMilliseconds(100), Ct);
|
||||
clients.Single().Notifications.Count.ShouldBe(100);
|
||||
var warningsBefore = logger.Warnings.Count;
|
||||
|
||||
Volatile.Write(ref offline, true);
|
||||
// Let at least three probe ticks run against the offline target (each rebuilds the client).
|
||||
await WaitForAsync(() => { lock (clients) return clients.Count >= 4; }, TimeSpan.FromSeconds(5));
|
||||
int ticks;
|
||||
lock (clients) ticks = clients.Count - 1;
|
||||
ticks.ShouldBeGreaterThanOrEqualTo(3);
|
||||
|
||||
int attempts;
|
||||
lock (clients) attempts = clients.Sum(c => c.OfflineAttempts);
|
||||
attempts.ShouldBeLessThanOrEqualTo(ticks, "at most one registration attempt per tick against an offline PLC");
|
||||
logger.Warnings.Skip(warningsBefore).Count(w => w.Contains("native notification", StringComparison.OrdinalIgnoreCase))
|
||||
.ShouldBeLessThanOrEqualTo(1, "one Warning per device per outage, not one per registration per tick");
|
||||
|
||||
// Positive control: the PLC returns and every registration is re-established on the live client.
|
||||
Volatile.Write(ref offline, false);
|
||||
await WaitForAsync(() => { lock (clients) return clients[^1].Notifications.Count == 100; }, TimeSpan.FromSeconds(5));
|
||||
lock (clients) clients[^1].Notifications.Count.ShouldBe(100);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
// ======================= P-12 — refusal vs comms classification =======================
|
||||
|
||||
/// <summary>P-12: device-layer refusals (0x700–0x73F) are device failures, never comms faults.</summary>
|
||||
[Theory]
|
||||
[InlineData(1800u)] // DeviceBusy
|
||||
[InlineData(1803u)] // DeviceInvalidParam
|
||||
[InlineData(1805u)] // DeviceSyntaxError
|
||||
[InlineData(1806u)] // DeviceIncompatible
|
||||
[InlineData(1814u)] // DeviceNoMoreHandles
|
||||
[InlineData(1815u)] // DeviceInvalidWatchsize
|
||||
[InlineData(1828u)] // DeviceLicenseNotFound
|
||||
[InlineData(1850u)] // last named device code
|
||||
public void A_device_layer_refusal_maps_to_a_non_comms_status(uint adsError)
|
||||
{
|
||||
var status = TwinCATStatusMapper.MapAdsError(adsError);
|
||||
status.ShouldBe(TwinCATStatusMapper.BadDeviceFailure);
|
||||
TwinCATDriver.IsCommsStatus(status).ShouldBeFalse();
|
||||
}
|
||||
|
||||
/// <summary>P-12 positive control: transport, router, client-layer and socket codes stay comms-class.</summary>
|
||||
[Theory]
|
||||
[InlineData(6u, TwinCATStatusMapper.BadCommunicationError)] // TargetPortNotFound
|
||||
[InlineData(7u, TwinCATStatusMapper.BadCommunicationError)] // TargetMachineNotFound
|
||||
[InlineData(1290u, TwinCATStatusMapper.BadCommunicationError)] // RouterNotActive
|
||||
[InlineData(1817u, TwinCATStatusMapper.BadTimeout)] // DeviceTimeOut — the remote did not answer
|
||||
[InlineData(1856u, TwinCATStatusMapper.BadCommunicationError)] // ClientError
|
||||
[InlineData(1861u, TwinCATStatusMapper.BadTimeout)] // ClientSyncTimeOut
|
||||
[InlineData(1864u, TwinCATStatusMapper.BadCommunicationError)] // ClientPortNotOpen
|
||||
[InlineData(10061u, TwinCATStatusMapper.BadCommunicationError)] // WSA_ConnectionRefused
|
||||
public void Transport_and_client_codes_stay_comms_class(uint adsError, uint expected)
|
||||
{
|
||||
var status = TwinCATStatusMapper.MapAdsError(adsError);
|
||||
status.ShouldBe(expected);
|
||||
TwinCATDriver.IsCommsStatus(status).ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-12: a tag whose read the PLC refuses with a device-layer code (1805 SyntaxError) leaves health Healthy —
|
||||
/// before the fix it degraded the driver on every poll and the next Good read flipped it back.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_device_refusal_on_read_leaves_health_alone()
|
||||
{
|
||||
var factory = new FakeTwinCATClientFactory
|
||||
{
|
||||
Customise = () =>
|
||||
{
|
||||
var c = new FakeTwinCATClient();
|
||||
c.ReadStatuses["MAIN.Bad"] = TwinCATStatusMapper.MapAdsError(1805);
|
||||
c.Values["MAIN.Ok"] = 1;
|
||||
return c;
|
||||
},
|
||||
};
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
|
||||
new TwinCATTagDefinition("Ok", HostA, "MAIN.Ok", TwinCATDataType.DInt),
|
||||
new TwinCATTagDefinition("Bad", HostA, "MAIN.Bad", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var results = await drv.ReadAsync(["Ok", "Bad"], Ct);
|
||||
|
||||
results[1].StatusCode.ShouldBe(TwinCATStatusMapper.BadDeviceFailure);
|
||||
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-12: a PLC out of notification handles (1814) refuses the registration — it backs off like any refusal
|
||||
/// and does not degrade health (before: comms-class, retried every probe tick, health Degraded).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_plc_out_of_notification_handles_is_a_refusal_with_backoff()
|
||||
{
|
||||
var fake = new FakeTwinCATClient();
|
||||
fake.AddNotificationErrors["MAIN.T"] = AdsTwinCATClient.RegistrationFailure("MAIN.T",
|
||||
"AddDeviceNotificationEx (ADS error DeviceNoMoreHandles)", TwinCATStatusMapper.MapAdsError(1814));
|
||||
var drv = NewDriver(new FakeTwinCATClientFactory { Customise = () => fake }, NoProbe, native: true, null, [HostA],
|
||||
new TwinCATTagDefinition("T", HostA, "MAIN.T", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
_ = await drv.SubscribeAsync(["T"], TimeSpan.FromMilliseconds(100), Ct);
|
||||
|
||||
var reg = drv.GetDeviceState(HostA)!.NativeRegistrations.Values.Single();
|
||||
reg.RefusalBackoff.ShouldBe(TwinCATDriver.RefusedRetryInitial);
|
||||
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-12: a scalar-declared tag over a STRUCT symbol is refused by the read guard (the Beckhoff marshaller would
|
||||
/// throw converting a struct to a number, and that exception used to count as a comms fault).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void The_read_guard_refuses_a_scalar_declaration_over_a_struct()
|
||||
{
|
||||
var shape = TwinCATPlcSymbolShape.Classify("ST_Motor", DataTypeCategory.Struct, 24);
|
||||
TwinCATTypeGuard.CheckRead(TwinCATDataType.DInt, shape).ShouldNotBeNull();
|
||||
// Positive control: a scalar over a scalar still passes.
|
||||
TwinCATTypeGuard.CheckRead(TwinCATDataType.DInt, TwinCATPlcSymbolShape.Classify("DINT", DataTypeCategory.Primitive, 4))
|
||||
.ShouldBeNull();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-12: a Beckhoff type / marshal exception on a read is that tag's data refused (BadTypeMismatch, no health
|
||||
/// impact); a connection-class or unknown exception stays a comms fault (the caller rethrows).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void A_marshal_failure_on_read_is_a_type_mismatch_and_a_connection_failure_is_not()
|
||||
{
|
||||
AdsTwinCATClient.MapReadException(new InvalidCastException()).ShouldBe(TwinCATStatusMapper.BadTypeMismatch);
|
||||
AdsTwinCATClient.MapReadException(new ArgumentException("size")).ShouldBe(TwinCATStatusMapper.BadTypeMismatch);
|
||||
AdsTwinCATClient.MapReadException(new NotSupportedException()).ShouldBe(TwinCATStatusMapper.BadTypeMismatch);
|
||||
AdsTwinCATClient.MapReadException(new TimeoutException()).ShouldBeNull();
|
||||
AdsTwinCATClient.MapReadException(new ObjectDisposedException("client")).ShouldBeNull();
|
||||
AdsTwinCATClient.MapReadException(new System.Net.Sockets.SocketException()).ShouldBeNull();
|
||||
AdsTwinCATClient.MapReadException(new OperationCanceledException()).ShouldBeNull();
|
||||
AdsTwinCATClient.MapReadException(new InvalidOperationException("unknown")).ShouldBeNull();
|
||||
}
|
||||
|
||||
// ======================= P-19 — per-tag health + parse cost =======================
|
||||
|
||||
/// <summary>
|
||||
/// P-19: a 50-tag read of one device re-derives the driver state ONCE (one device scan + one health record),
|
||||
/// not once per Good tag, and parses no symbol path (they are pre-computed at init).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_read_writes_health_once_per_device_and_parses_nothing()
|
||||
{
|
||||
var tags = TagsOn(HostA, "T", 50);
|
||||
var factory = new FakeTwinCATClientFactory
|
||||
{
|
||||
Customise = () =>
|
||||
{
|
||||
var c = new FakeTwinCATClient();
|
||||
foreach (var t in tags) c.Values[t.SymbolPath] = 1;
|
||||
return c;
|
||||
},
|
||||
};
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA], tags);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
_ = await drv.ReadAsync([.. tags.Select(t => t.Name)], Ct); // first read connects
|
||||
var scansBefore = drv.DeviceAnsweredScansForTest;
|
||||
|
||||
var counter = new System.Runtime.CompilerServices.StrongBox<int>();
|
||||
TwinCATSymbolPath.ParseCounterForTest.Value = counter;
|
||||
try
|
||||
{
|
||||
var results = await drv.ReadAsync([.. tags.Select(t => t.Name)], Ct);
|
||||
results.ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.Good);
|
||||
}
|
||||
finally { TwinCATSymbolPath.ParseCounterForTest.Value = null; }
|
||||
|
||||
(drv.DeviceAnsweredScansForTest - scansBefore).ShouldBe(1);
|
||||
counter.Value.ShouldBe(0, "the symbol name / bit index are parsed once at init, not per read");
|
||||
|
||||
// Positive control for the seam: parsing on this flow IS counted.
|
||||
TwinCATSymbolPath.ParseCounterForTest.Value = counter;
|
||||
try { _ = TwinCATSymbolPath.TryParse("MAIN.X"); }
|
||||
finally { TwinCATSymbolPath.ParseCounterForTest.Value = null; }
|
||||
counter.Value.ShouldBe(1);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>P-19: two devices read in one call → one state re-derivation each.</summary>
|
||||
[Fact]
|
||||
public async Task A_two_device_read_writes_health_once_per_device()
|
||||
{
|
||||
var tags = TagsOn(HostA, "A", 5).Concat(TagsOn(HostB, "B", 5)).ToArray();
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA, HostB], tags);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
_ = await drv.ReadAsync([.. tags.Select(t => t.Name)], Ct);
|
||||
var before = drv.DeviceAnsweredScansForTest;
|
||||
|
||||
_ = await drv.ReadAsync([.. tags.Select(t => t.Name)], Ct);
|
||||
|
||||
(drv.DeviceAnsweredScansForTest - before).ShouldBe(2);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
// ======================= P-25 — bit-read parent check =======================
|
||||
|
||||
/// <summary>
|
||||
/// P-25: the poll read, the native notification and the write give a (parent, bit) pair the SAME status.
|
||||
/// Before the fix the poll read read the parent as a 32-bit uint and answered Good <c>false</c> for bit 20 of a
|
||||
/// 16-bit WORD, where the other two said BadOutOfRange.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("WORD", DataTypeCategory.Primitive, 2, 20, TwinCATStatusMapper.BadOutOfRange)]
|
||||
[InlineData("WORD", DataTypeCategory.Primitive, 2, 3, TwinCATStatusMapper.Good)]
|
||||
[InlineData("UDINT", DataTypeCategory.Primitive, 4, 31, TwinCATStatusMapper.Good)]
|
||||
[InlineData("BYTE", DataTypeCategory.Primitive, 1, 8, TwinCATStatusMapper.BadOutOfRange)]
|
||||
[InlineData("REAL", DataTypeCategory.Primitive, 4, 1, TwinCATStatusMapper.BadTypeMismatch)]
|
||||
[InlineData("ST_Flags", DataTypeCategory.Struct, 4, 1, TwinCATStatusMapper.BadTypeMismatch)]
|
||||
public void Poll_notification_and_write_agree_on_a_bit_parent(string typeName, DataTypeCategory category, int size,
|
||||
int bit, uint expected)
|
||||
{
|
||||
var parent = TwinCATPlcSymbolShape.Classify(typeName, category, size);
|
||||
var bytes = new byte[size];
|
||||
Array.Fill(bytes, (byte)0xFF);
|
||||
|
||||
var (value, readStatus) = TwinCATBitAccess.ReadBitFromParent(parent, bytes, bit);
|
||||
var writeStatus = TwinCATBitAccess.ApplyBitWrite(parent, bytes, bit, false, out _);
|
||||
var notificationStatus = TwinCATBitAccess.ParentStatus(bit, parent); // what AddNotificationAsync refuses with
|
||||
|
||||
readStatus.ShouldBe(expected);
|
||||
writeStatus.ShouldBe(expected);
|
||||
notificationStatus.ShouldBe(expected);
|
||||
if (expected == TwinCATStatusMapper.Good) value.ShouldBe(true);
|
||||
else value.ShouldBeNull();
|
||||
}
|
||||
|
||||
// ======================= P-22 — the probe's timeout =======================
|
||||
|
||||
/// <summary>A client whose state probe never answers until cancelled.</summary>
|
||||
private sealed class HangingProbeFake : FakeTwinCATClient
|
||||
{
|
||||
public override async Task<bool> ProbeAsync(CancellationToken ct)
|
||||
{
|
||||
try { await Task.Delay(Timeout.Infinite, ct); }
|
||||
catch (OperationCanceledException) { }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-22: the ADS client's timeout is the DRIVER's (it serves every data read); the probe bounds its own
|
||||
/// ReadState with its own timeout. Before the fix the probe created the client first, with the probe's
|
||||
/// timeout, so a raised driver <c>TimeoutMs</c> never reached a read — and a hung ReadState hung the probe.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task The_client_keeps_the_driver_timeout_and_the_probe_bounds_its_own_call()
|
||||
{
|
||||
var factory = new FakeTwinCATClientFactory { Customise = () => new HangingProbeFake() };
|
||||
var drv = new TwinCATDriver(new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions(HostA)],
|
||||
Probe = new TwinCATProbeOptions
|
||||
{
|
||||
Enabled = true,
|
||||
Interval = TimeSpan.FromMilliseconds(30),
|
||||
Timeout = TimeSpan.FromMilliseconds(100),
|
||||
},
|
||||
Timeout = TimeSpan.FromSeconds(8),
|
||||
}, "drv-982", factory);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
await WaitForAsync(() => drv.GetDeviceState(HostA)?.ConsecutiveProbeFailures >= 2, TimeSpan.FromSeconds(3));
|
||||
|
||||
drv.GetDeviceState(HostA)!.ConsecutiveProbeFailures.ShouldBeGreaterThanOrEqualTo(2,
|
||||
"a ReadState that never answers is bounded by the probe timeout");
|
||||
factory.Clients.ShouldAllBe(c => c.LastConnectTimeout == null || c.LastConnectTimeout == TimeSpan.FromSeconds(8));
|
||||
factory.Clients.ShouldContain(c => c.LastConnectTimeout == TimeSpan.FromSeconds(8));
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user