diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index c20978143..1a1dd481f 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -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 diff --git a/docs/drivers/TwinCAT.md b/docs/drivers/TwinCAT.md index 645fd0253..f0cb8d753 100644 --- a/docs/drivers/TwinCAT.md +++ b/docs/drivers/TwinCAT.md @@ -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.` = @@ -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 diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/AdsTwinCATClient.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/AdsTwinCATClient.cs index 649998b05..b5bb804c1 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/AdsTwinCATClient.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/AdsTwinCATClient.cs @@ -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; + + /// + /// Hooks the SDK's AdsSymbolVersionChanged 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 Connect 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 Beckhoff.TwinCAT.Ads 7.0.172: RegisterSymbolVersionChanged + /// only registers with the target when no delegate is attached yet). + /// + 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; + } + } + + /// + /// 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 — + /// BadTypeMismatch, no health impact. Anything else (connection, timeout, socket, disposed, an + /// unknown exception) returns null: 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). + /// + /// The exception the library threw. + /// BadTypeMismatch for a type / marshal failure; otherwise null. + 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, + }; + /// 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); + } } /// @@ -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, - }; } /// Default — one per call. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATBitAccess.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATBitAccess.cs index 277bd3173..f12aba6f9 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATBitAccess.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATBitAccess.cs @@ -32,6 +32,41 @@ internal static class TwinCATBitAccess : $"bit {bit} is outside the {parent.ByteSize * 8}-bit parent {parent.TypeName}"; } + /// + /// The status every bit path — poll read, native notification and write — gives a (parent, bit) pair: + /// Good when the bit addresses an integer parent; BadTypeMismatch for a parent that is not an + /// integer word; BadOutOfRange 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 false for bit 20 of a 16-bit WORD). + /// + /// The bit index. + /// The parent symbol's resolved shape. + /// The status shared by the three paths. + 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; + } + + /// + /// The decode step of a bit-indexed BOOL poll read: checks the bit against the parent + /// () and reads it from the parent's raw bytes at the parent's OWN width. + /// + /// The parent symbol's resolved shape. + /// The parent's raw bytes as read from the PLC. + /// The bit index. + /// The bit with Good, or no value with the refusal status; BadCommunicationError for a + /// read shorter than the parent. + public static (object? value, uint status) ReadBitFromParent(TwinCATPlcSymbolShape parent, ReadOnlySpan 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); + } + /// /// The modify step of a bit write's read-modify-write: checks the bit against the parent /// () and returns the parent's bytes — exactly parent.ByteSize 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(); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATDriver.cs index 1ffe7b4dd..d7b544cfe 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATDriver.cs @@ -57,11 +57,37 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // device twice (each device set is taken by exactly one swap). private volatile ConcurrentDictionary _devices = NewDeviceTable(); // v3: the authored RawPath → definition table. Keyed case-sensitive ordinal (the RawPath is - // the exact wire reference). Built in InitializeAsync from _options.RawTags via the pure mapper. - private volatile IReadOnlyDictionary _tagsByRawPath = EmptyTags; + // the exact wire reference). Built in InitializeAsync from _options.RawTags via the pure mapper. Each entry + // carries its ADS symbol name and bit index parsed ONCE at init (lmxopcua#982 P-19: they were re-parsed per + // tag per read, write and subscribe). + private volatile IReadOnlyDictionary _tagsByRawPath = EmptyTags; - private static readonly IReadOnlyDictionary EmptyTags = - new Dictionary(StringComparer.Ordinal); + private static readonly IReadOnlyDictionary EmptyTags = + new Dictionary(StringComparer.Ordinal); + + /// + /// One authored tag with its wire facts pre-computed at init: the ADS symbol name the client is asked for + /// (a bit-indexed BOOL keeps its .N), the bit index, and the parent word's symbol name for a bit write. + /// + /// The tag definition. + /// The ADS symbol name (, or the raw path + /// when it does not parse). + /// The parsed bit index, or null. + /// The symbol name without the bit suffix (for a bit write's parent word); the + /// symbol name itself when there is no bit. + internal sealed record TagEntry(TwinCATTagDefinition Def, string SymbolName, int? BitIndex, string ParentSymbolName) + { + /// Builds the entry, parsing the symbol path once. + /// The tag definition. + /// The entry. + public static TagEntry For(TwinCATTagDefinition def) + { + var parsed = TwinCATSymbolPath.TryParse(def.SymbolPath); + var symbolName = parsed?.ToAdsSymbolName() ?? def.SymbolPath; + var parent = parsed is { BitIndex: not null } ? (parsed with { BitIndex = null }).ToAdsSymbolName() : symbolName; + return new TagEntry(def, symbolName, parsed?.BitIndex, parent); + } + } private static ConcurrentDictionary NewDeviceTable() => new(StringComparer.OrdinalIgnoreCase); @@ -108,10 +134,21 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // v3: resolves a read/write/subscribe fullReference (always a RawPath) to a tag definition by a // single hit on the authored _tagsByRawPath table. A miss is a miss — the driver surfaces // BadNodeIdUnknown (no blob-parse fallback). - private readonly EquipmentTagRefResolver _resolver; + private readonly EquipmentTagRefResolver _resolver; private DriverHealth _health = new(DriverState.Unknown, null, null); + // Serialises the read-modify-write health updates (MarkCommsFault / RecordDeviceAnswered / …). Devices are + // read concurrently (lmxopcua#982 P-3) and native pushes + probe ticks already ran on their own threads, so + // an unguarded update could overwrite a Degraded written a moment earlier with a stale Healthy. + private readonly object _healthLock = new(); + + private int _deviceAnsweredScans; + + /// Test visibility: how many times a device answer re-derived the driver state (a scan over every + /// device + a health allocation). One per device per read call, not one per tag (lmxopcua#982 P-19). + internal int DeviceAnsweredScansForTest => Volatile.Read(ref _deviceAnsweredScans); + /// Occurs when a subscribed tag value changes. public event EventHandler? OnDataChange; /// @@ -139,7 +176,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery _driverInstanceId = driverInstanceId; _clientFactory = clientFactory ?? new AdsTwinCATClientFactory(); _logger = logger ?? NullLogger.Instance; - _resolver = new EquipmentTagRefResolver( + _resolver = new EquipmentTagRefResolver( r => _tagsByRawPath.TryGetValue(r, out var t) ? t : null); _poll = CreatePollEngine(); } @@ -176,9 +213,12 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery internal void HandlePollError(Exception ex) { _logger.LogWarning(ex, "TwinCAT poll reader failed. Driver={DriverInstanceId}", _driverInstanceId); - var current = _health; - if (current.State != DriverState.Faulted) - _health = new DriverHealth(DriverState.Degraded, current.LastSuccessfulRead, ex.Message); + lock (_healthLock) + { + var current = _health; + if (current.State != DriverState.Faulted) + _health = new DriverHealth(DriverState.Degraded, current.LastSuccessfulRead, ex.Message); + } } /// @@ -241,16 +281,16 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // DeviceName is resolved to the target's live host (def.DeviceHostAddress) via ResolveDeviceHost // so the existing device routing (_devices keyed by HostAddress) is unchanged. A mapper miss is // skipped (logged), never thrown — a bad tag must not fail the whole driver init. - var tags = new Dictionary(StringComparer.Ordinal); + var tags = new Dictionary(StringComparer.Ordinal); _skippedTags.BeginRebuild(options.RawTags.Count); foreach (var entry in options.RawTags) { if (TwinCATTagDefinitionFactory.FromTagConfig(entry.TagConfig, entry.RawPath, out var def)) - tags[entry.RawPath] = def with + tags[entry.RawPath] = TagEntry.For(def with { WriteIdempotent = entry.WriteIdempotent, DeviceHostAddress = ResolveDeviceHost(options, entry.DeviceName), - }; + }); else { _skippedTags.Skip(entry.RawPath, "TagConfig did not map to a definition"); @@ -447,113 +487,212 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // ---- IReadable ---- /// + /// + /// The references are bucketed by device and the devices are read CONCURRENTLY (lmxopcua#982 P-3): a PLC + /// that stopped answering costs its own timeout, never every other device's. Within one device the first + /// comms-class failure is checked against the device's ADS state (); + /// when the device is gone its remaining tags fail fast with no wire attempt, when it still answers the + /// failure is that one tag's. A device the probe already counts as unreachable fails fast outright. + /// public async Task> ReadAsync( IReadOnlyList fullReferences, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(fullReferences); var now = DateTime.UtcNow; var results = new DataValueSnapshot[fullReferences.Count]; + var devices = _devices; - // With UseSumRead the reads for one device are gathered and issued as ADS sum-reads - // after this pass; everything else (and a device that refused the sum command) reads one by one. - Dictionary>? buckets = null; - + Dictionary>? perDevice = null; for (var i = 0; i < fullReferences.Count; i++) { var reference = fullReferences[i]; - if (!_resolver.TryResolve(reference, out var def)) + if (!_resolver.TryResolve(reference, out var tag) + || !devices.TryGetValue(tag.Def.DeviceHostAddress, out var device)) { results[i] = new DataValueSnapshot(null, TwinCATStatusMapper.BadNodeIdUnknown, null, now); continue; } - if (!_devices.TryGetValue(def.DeviceHostAddress, out var device)) - { - results[i] = new DataValueSnapshot(null, TwinCATStatusMapper.BadNodeIdUnknown, null, now); - continue; - } - - if (_options.UseSumRead && !device.SumReadUnsupported) - { - var parsed = TwinCATSymbolPath.TryParse(def.SymbolPath); - var symbolName = parsed?.ToAdsSymbolName() ?? def.SymbolPath; - buckets ??= []; - if (!buckets.TryGetValue(device, out var bucket)) - buckets[device] = bucket = []; - bucket.Add(new SumReadEntry(i, reference, def, symbolName, parsed?.BitIndex)); - continue; - } - - results[i] = await ReadOneAsync(reference, def, device, now, cancellationToken).ConfigureAwait(false); + perDevice ??= []; + if (!perDevice.TryGetValue(device, out var list)) perDevice[device] = list = []; + list.Add(new ReadEntry(i, reference, tag)); } - if (buckets is not null) - foreach (var (device, bucket) in buckets) - await ReadBucketAsync(device, bucket, results, now, cancellationToken).ConfigureAwait(false); - + if (perDevice is null) return results; + if (perDevice.Count == 1) + { + foreach (var (device, entries) in perDevice) + await ReadDeviceAsync(device, entries, results, now, cancellationToken).ConfigureAwait(false); + } + else + { + var reads = new Task[perDevice.Count]; + var k = 0; + foreach (var (device, entries) in perDevice) + reads[k++] = ReadDeviceAsync(device, entries, results, now, cancellationToken); + await Task.WhenAll(reads).ConfigureAwait(false); + } return results; } - private readonly record struct SumReadEntry( - int Index, string Reference, TwinCATTagDefinition Def, string SymbolName, int? BitIndex); + private readonly record struct ReadEntry(int Index, string Reference, TagEntry Tag); + + /// + /// What one device's share of a read call observed. Health is applied ONCE per device per call from this + /// (lmxopcua#982 P-19: it used to be a lock-all device scan + a health allocation per Good tag), and it + /// carries the per-call fail-fast verdict (P-3). + /// + private sealed class DeviceReadBatch + { + /// At least one tag read Good. + public bool Answered; + + /// At least one tag was refused by the device (non-comms status). + public bool Refused; + + /// The first comms-class failure seen; null = none. + public string? CommsFault; + + /// The device is gone for the rest of this call: its remaining tags fail fast. + public bool Unreachable; + + /// The device's ADS state was already checked after a comms failure in this call. + public bool Verified; + } + + /// Reads one device's share of a read call, then applies that device's health outcome once. + private async Task ReadDeviceAsync(DeviceState device, List entries, DataValueSnapshot[] results, + DateTime now, CancellationToken cancellationToken) + { + var batch = new DeviceReadBatch(); + if (device.ConsecutiveProbeFailures >= ProbeFailuresBeforeDegraded) + { + // The probe already says this device is gone: no wire attempt per tag until it answers again. + batch.Unreachable = true; + batch.CommsFault = DeviceDegradedReason(device) ?? $"TwinCAT device {device.Options.HostAddress} unreachable"; + } + + try + { + if (_options.UseSumRead && !device.SumReadUnsupported) + await ReadBucketAsync(device, entries, results, now, batch, cancellationToken).ConfigureAwait(false); + else + foreach (var e in entries) + results[e.Index] = await ReadOneAsync(e, device, now, batch, cancellationToken).ConfigureAwait(false); + } + finally + { + ApplyBatchHealth(device, batch, now); + } + } + + /// + /// Applies one device's read outcome to the health surface: a device that answered (Good or a refusal) + /// advances LastSuccessfulRead; any comms-class failure then degrades — the #527 contract, now one + /// health write per device per call instead of one per tag. + /// + private void ApplyBatchHealth(DeviceState device, DeviceReadBatch batch, DateTime now) + { + if (batch.Answered) RecordDeviceAnswered(now, device, force: true); + else if (batch.Refused) RecordDeviceAnsweredKeepState(now); + if (batch.CommsFault is { } fault) MarkCommsFault(fault, device); + } + + private static DataValueSnapshot CommsBad(DateTime now) => + new(null, TwinCATStatusMapper.BadCommunicationError, null, now); /// One tag read on its own — the pre-sum-read path, also the fallback for a refused sum command. private async Task ReadOneAsync( - string reference, TwinCATTagDefinition def, DeviceState device, DateTime now, CancellationToken cancellationToken) + ReadEntry e, DeviceState device, DateTime now, DeviceReadBatch batch, CancellationToken cancellationToken) { + if (batch.Unreachable) return CommsBad(now); + ITwinCATClient? client = null; try { - var client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false); - var parsed = TwinCATSymbolPath.TryParse(def.SymbolPath); - var symbolName = parsed?.ToAdsSymbolName() ?? def.SymbolPath; + client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false); + var def = e.Tag.Def; // An array-typed tag (def.ArrayLength != null) reads the array as raw bytes and decodes // it with TwinCATArrayCodec — the same decode a native array notification runs — into an // element-typed CLR array. Scalar tags pass null (scalar path) — bit-indexed BOOLs are // inherently scalar so the client ignores arrayCount when a bitIndex is present. var (value, status) = await client.ReadValueAsync( - symbolName, def.DataType, parsed?.BitIndex, def.ArrayLength, cancellationToken) + e.Tag.SymbolName, def.DataType, e.Tag.BitIndex, def.ArrayLength, cancellationToken) .ConfigureAwait(false); - return CompleteRead(device, reference, def, symbolName, value, status, now); + var snapshot = CompleteRead(e, value, status, now, batch); + if (IsCommsStatus(status)) await VerifyDeviceAsync(device, client, batch, cancellationToken).ConfigureAwait(false); + return snapshot; } catch (OperationCanceledException) { throw; } catch (Exception ex) { - MarkCommsFault(ex.Message, device); - return new DataValueSnapshot(null, TwinCATStatusMapper.BadCommunicationError, null, now); + batch.CommsFault ??= ex.Message; + // No client means the connect itself failed (or was throttled): the device is unreachable. + if (client is null) batch.Unreachable = true; + else await VerifyDeviceAsync(device, client, batch, cancellationToken).ConfigureAwait(false); + return CommsBad(now); } } - /// Maps one read outcome to a snapshot and applies the health / log side effects. - private DataValueSnapshot CompleteRead(DeviceState device, - string reference, TwinCATTagDefinition def, string symbolName, object? value, uint status, DateTime now) + /// + /// After a comms-class failure, asks the device for its ADS state once per call: no answer ⇒ the device is + /// gone and its remaining tags fail fast; an answer ⇒ the failure was that one tag's (a slow / oversized + /// symbol), and its siblings are still read. + /// + private async Task VerifyDeviceAsync(DeviceState device, ITwinCATClient client, DeviceReadBatch batch, + CancellationToken cancellationToken) + { + if (batch.Verified || batch.Unreachable) return; + batch.Verified = true; + if (!await DeviceStillAnswersAsync(client, cancellationToken).ConfigureAwait(false)) + { + batch.Unreachable = true; + _logger.LogDebug( + "TwinCAT driver '{DriverInstanceId}' device '{HostAddress}' did not answer its state after a failed read; " + + "its remaining tags fail fast for this call", _driverInstanceId, device.Options.HostAddress); + } + } + + /// + /// A bounded ADS state read ( under the probe timeout): true when the + /// device still answers. Never throws except for the caller's own cancellation. + /// + private async Task DeviceStillAnswersAsync(ITwinCATClient client, CancellationToken cancellationToken) + { + using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + bounded.CancelAfter(_options.Probe.Timeout); + try { return await client.ProbeAsync(bounded.Token).ConfigureAwait(false); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } + catch { return false; } + } + + /// Maps one read outcome to a snapshot and records it on the device's batch (logging once per tag). + private DataValueSnapshot CompleteRead(ReadEntry e, object? value, uint status, DateTime now, DeviceReadBatch batch) { if (status == TwinCATStatusMapper.Good) { - _warnedRefs.TryRemove(reference, out _); // a later failure is a new episode and warns again - RecordDeviceAnswered(now, device, force: true); + _warnedRefs.TryRemove(e.Reference, out _); // a later failure is a new episode and warns again + batch.Answered = true; return new DataValueSnapshot(value, status, now, now); } // Once per tag per bad episode: a Warning every poll for every bad tag (50 typo'd symbols on a // 500 ms poll = 100 Warnings/s) buried everything else in the log. - if (_warnedRefs.TryAdd(reference, 0)) + if (_warnedRefs.TryAdd(e.Reference, 0)) { if (status == TwinCATStatusMapper.BadTypeMismatch) _logger.LogWarning( "TwinCAT driver '{DriverInstanceId}' refused '{Reference}': declared {DataType} " + "cannot decode the PLC symbol '{Symbol}' (string/numeric kind mismatch, array element type " + "or length mismatch, or a reference/container); logged once until the tag reads Good", - _driverInstanceId, reference, def.DataType, symbolName); + _driverInstanceId, e.Reference, e.Tag.Def.DataType, e.Tag.SymbolName); else _logger.LogWarning( "TwinCAT driver '{DriverInstanceId}' ADS read error 0x{Status:X8} for '{Reference}'; " + "logged once until the tag reads Good", - _driverInstanceId, status, reference); + _driverInstanceId, status, e.Reference); } - if (IsCommsStatus(status)) - MarkCommsFault($"ADS status {status:X8} reading {reference}", device); - else - RecordDeviceAnsweredKeepState(now); // a refusal: the device answered — no state change + if (IsCommsStatus(status)) batch.CommsFault ??= $"ADS status {status:X8} reading {e.Reference}"; + else batch.Refused = true; // a refusal: the device answered — no state change return new DataValueSnapshot(value, status, now, now); } @@ -583,42 +722,57 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery /// Advances LastSuccessfulRead without changing the state (the device answered with a refusal). private void RecordDeviceAnsweredKeepState(DateTime now) { - var current = _health; - if (current.State is DriverState.Faulted or DriverState.Unknown or DriverState.Initializing) return; - _health = current with { LastSuccessfulRead = now }; + lock (_healthLock) + { + var current = _health; + if (current.State is DriverState.Faulted or DriverState.Unknown or DriverState.Initializing) return; + _health = current with { LastSuccessfulRead = now }; + } } /// /// Reads one device's gathered tags as ADS sum-reads of at most SumReadMaxItems symbols each. /// A target that refuses the sum command flips and the - /// rest of the bucket is read individually; any other failure marks only the affected chunk Bad. + /// rest of the bucket is read individually; any other failure marks only the affected chunk Bad (and, + /// when the device then fails its state check, the rest of the bucket fails fast). /// private async Task ReadBucketAsync( - DeviceState device, List bucket, DataValueSnapshot[] results, DateTime now, + DeviceState device, List bucket, DataValueSnapshot[] results, DateTime now, DeviceReadBatch batch, CancellationToken cancellationToken) { var chunkSize = Math.Clamp(_options.SumReadMaxItems, 1, TwinCATSumReadPlanner.MaxItemsCeiling); for (var start = 0; start < bucket.Count; start += chunkSize) { - var chunk = bucket.GetRange(start, Math.Min(chunkSize, bucket.Count - start)); + var count = Math.Min(chunkSize, bucket.Count - start); - if (device.SumReadUnsupported || chunk.Count == 1) + if (batch.Unreachable) { - foreach (var e in chunk) - results[e.Index] = await ReadOneAsync(e.Reference, e.Def, device, now, cancellationToken).ConfigureAwait(false); + for (var k = 0; k < count; k++) results[bucket[start + k].Index] = CommsBad(now); + continue; + } + + if (device.SumReadUnsupported || count == 1) + { + for (var k = 0; k < count; k++) + { + var e = bucket[start + k]; + results[e.Index] = await ReadOneAsync(e, device, now, batch, cancellationToken).ConfigureAwait(false); + } continue; } // Set once the connect succeeded: a connect / backoff failure is the connect path's to report (it // logs its own Warning) and must not consume the once-per-device sum-chunk-failure Warning below. - var connected = false; + ITwinCATClient? client = null; try { - var client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false); - connected = true; - var items = new TwinCATBulkReadItem[chunk.Count]; - for (var k = 0; k < chunk.Count; k++) - items[k] = new TwinCATBulkReadItem(chunk[k].SymbolName, chunk[k].Def.DataType, chunk[k].BitIndex, chunk[k].Def.ArrayLength); + client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false); + var items = new TwinCATBulkReadItem[count]; + for (var k = 0; k < count; k++) + { + var t = bucket[start + k].Tag; + items[k] = new TwinCATBulkReadItem(t.SymbolName, t.Def.DataType, t.BitIndex, t.Def.ArrayLength); + } var fallbacksBefore = client.SumFallbackCount; var bulk = await client.ReadValuesAsync(items, cancellationToken).ConfigureAwait(false); @@ -631,12 +785,15 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery "is not working on this target; this warning is logged once per device", _driverInstanceId, device.Options.HostAddress, client.LastSumFallbackCode); } - for (var k = 0; k < chunk.Count; k++) + var anyComms = false; + for (var k = 0; k < count; k++) { - var e = chunk[k]; + var e = bucket[start + k]; var (value, status) = k < bulk.Count ? bulk[k] : (null, TwinCATStatusMapper.BadCommunicationError); - results[e.Index] = CompleteRead(device, e.Reference, e.Def, e.SymbolName, value, status, now); + results[e.Index] = CompleteRead(e, value, status, now, batch); + anyComms |= IsCommsStatus(status); } + if (anyComms) await VerifyDeviceAsync(device, client, batch, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (TwinCATSumReadRefusedException refused) @@ -646,24 +803,28 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery "TwinCAT driver '{DriverInstanceId}' device '{Device}' refused the ADS sum-read command " + "(ADS error {AdsError}); falling back to individual reads for this device", _driverInstanceId, device.Options.HostAddress, refused.AdsErrorCode); - foreach (var e in chunk) - results[e.Index] = await ReadOneAsync(e.Reference, e.Def, device, now, cancellationToken).ConfigureAwait(false); + for (var k = 0; k < count; k++) + { + var e = bucket[start + k]; + results[e.Index] = await ReadOneAsync(e, device, now, batch, cancellationToken).ConfigureAwait(false); + } } catch (Exception ex) { - foreach (var e in chunk) - results[e.Index] = new DataValueSnapshot(null, TwinCATStatusMapper.BadCommunicationError, null, now); - MarkCommsFault(ex.Message, device); + for (var k = 0; k < count; k++) results[bucket[start + k].Index] = CommsBad(now); + batch.CommsFault ??= ex.Message; // Once per device: the health message is overwritten by the next good read in the same poll, so // without this a sum-read path failing on every poll left no trace (hw2 live gate, 2026-10-08). - if (connected && !device.SumChunkFailureWarned) + if (client is not null && !device.SumChunkFailureWarned) { device.SumChunkFailureWarned = true; _logger.LogWarning(ex, "TwinCAT driver '{DriverInstanceId}' device '{Device}': an ADS sum-read chunk of {Count} tags " + "failed and was reported BadCommunicationError; this warning is logged once per device", - _driverInstanceId, device.Options.HostAddress, chunk.Count); + _driverInstanceId, device.Options.HostAddress, count); } + if (client is null) batch.Unreachable = true; + else await VerifyDeviceAsync(device, client, batch, cancellationToken).ConfigureAwait(false); } } } @@ -680,11 +841,12 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery for (var i = 0; i < writes.Count; i++) { var w = writes[i]; - if (!_resolver.TryResolve(w.FullReference, out var def)) + if (!_resolver.TryResolve(w.FullReference, out var tag)) { results[i] = new WriteResult(TwinCATStatusMapper.BadNodeIdUnknown); continue; } + var def = tag.Def; if (!def.Writable) { results[i] = new WriteResult(TwinCATStatusMapper.BadNotWritable); @@ -698,8 +860,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery try { - var parsed = TwinCATSymbolPath.TryParse(def.SymbolPath); - var bitIndex = def.DataType == TwinCATDataType.Bool ? parsed?.BitIndex : null; + var bitIndex = def.DataType == TwinCATDataType.Bool ? tag.BitIndex : null; // Shape checks run BEFORE any wire traffic (connect included): an array write needs exactly // ArrayLength elements, each converted to the declared element type (a CLR int[] to an Int16 // array converts; it is not exact-matched) — a length mismatch / out-of-range element is @@ -717,7 +878,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // word don't lose each other's updates. if (bitIndex is int bit) { - var parentPath = (parsed! with { BitIndex = null }).ToAdsSymbolName(); + var parentPath = tag.ParentSymbolName; var gate = _bitRmwLocks.GetOrAdd( $"{def.DeviceHostAddress}|{parentPath}", static _ => new SemaphoreSlim(1, 1)); await gate.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -734,7 +895,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery continue; } - var symbolName = parsed?.ToAdsSymbolName() ?? def.SymbolPath; + var symbolName = tag.SymbolName; if (elements is not null) { // Array tag: raw bytes encoded by TwinCATArrayCodec at the layout planned from the PLC @@ -746,7 +907,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery } var status = await client.WriteValueAsync( - symbolName, def.DataType, parsed?.BitIndex, w.Value, cancellationToken).ConfigureAwait(false); + symbolName, def.DataType, tag.BitIndex, w.Value, cancellationToken).ConfigureAwait(false); results[i] = new WriteResult(status); NoteWriteOutcome(device, status, w.FullReference); } @@ -802,7 +963,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // Authored raw tags (mapped into the RawPath → def table at Initialize) — always emitted // as the authoritative config path. The def's Name is the RawPath, used for both the browse // name and the driver FullName; it is routed to this device by def.DeviceHostAddress. - var tagsForDevice = _tagsByRawPath.Values.Where(t => + var tagsForDevice = _tagsByRawPath.Values.Select(t => t.Def).Where(t => string.Equals(t.DeviceHostAddress, device.HostAddress, StringComparison.OrdinalIgnoreCase)); foreach (var tag in tagsForDevice) { @@ -902,6 +1063,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // Devices whose connect failed during THIS call: the rest of their tags are stored as dead // intents straight away rather than each paying (and logging) its own failed connect. HashSet? unreachable = null; + // Devices whose ADS state was already checked after a failed registration in THIS call (once each). + HashSet? verified = null; try { @@ -910,17 +1073,17 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // An unresolvable reference (unknown RawPath, or a tag routed to an unconfigured device) // publishes BadNodeIdUnknown once — the poll path's status — instead of leaving the node on // whatever status the server seeded it with. - if (!_resolver.TryResolve(reference, out var def) - || !_devices.TryGetValue(def.DeviceHostAddress, out var device)) + if (!_resolver.TryResolve(reference, out var tag) + || !_devices.TryGetValue(tag.Def.DeviceHostAddress, out var device)) { RaiseDataChange(handle, reference, new DataValueSnapshot( null, TwinCATStatusMapper.BadNodeIdUnknown, null, DateTime.UtcNow)); continue; } - var parsed = TwinCATSymbolPath.TryParse(def.SymbolPath); - var symbolName = parsed?.ToAdsSymbolName() ?? def.SymbolPath; - var bitIndex = parsed?.BitIndex; + var def = tag.Def; + var symbolName = tag.SymbolName; + var bitIndex = tag.BitIndex; // The callback closes over the stable (handle, reference) pair, so it survives a // client swap unchanged — replay re-registers the SAME intent onto the new client. @@ -941,6 +1104,9 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery null, status, null, DateTime.UtcNow))); registrations.Add(reg); + // A device the probe already counts as unreachable is not dialled per tag (lmxopcua#982 P-3). + if (device.ConsecutiveProbeFailures >= ProbeFailuresBeforeDegraded) (unreachable ??= []).Add(device); + if (unreachable?.Contains(device) == true) { // Same device already failed to connect in this call: keep the intent dead for the @@ -995,6 +1161,13 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery NoteDeadFailure(reg, TwinCATStatusMapper.BadCommunicationError, refused: false, DateTime.UtcNow); RaiseDataChange(handle, reference, new DataValueSnapshot( null, TwinCATStatusMapper.BadCommunicationError, null, DateTime.UtcNow)); + // Is it this tag, or is the device gone? A device whose local AMS port still "connects" but + // that stopped answering would otherwise make every one of its tags pay the timeout in turn + // (lmxopcua#982 P-3). Gone ⇒ the rest of its tags are stored dead for the probe-tick retry. + if ((verified ??= []).Add(device) + && (device.Client is not { } current + || !await DeviceStillAnswersAsync(current, cancellationToken).ConfigureAwait(false))) + (unreachable ??= []).Add(device); } } } @@ -1035,10 +1208,13 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery private void MarkCommsFault(string message, DeviceState? device = null) { if (device?.Released == true) return; - if (device is not null) device.CommsFault = message; - var current = _health; - if (current.State != DriverState.Faulted) - _health = new DriverHealth(DriverState.Degraded, current.LastSuccessfulRead, message); + lock (_healthLock) + { + if (device is not null) device.CommsFault = message; + var current = _health; + if (current.State != DriverState.Faulted) + _health = new DriverHealth(DriverState.Degraded, current.LastSuccessfulRead, message); + } } /// @@ -1083,25 +1259,33 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery private void RecordDeviceAnswered(DateTime now, DeviceState? device = null, bool force = false) { if (device?.Released == true) return; - if (device?.CommsFault is not null) + // Hot path (a notification on a healthy driver inside the window): no lock, no device scan, no allocation. + if (!force && device?.CommsFault is null) { - device.CommsFault = null; - force = true; + var observed = _health; + if (observed.State == DriverState.Healthy && observed.LastSuccessfulRead is { } recent + && now - recent < AnsweredStampInterval) + return; + } + lock (_healthLock) + { + if (device?.CommsFault is not null) + { + device.CommsFault = null; + force = true; + } + var current = _health; + if (current.State == DriverState.Faulted) return; + Interlocked.Increment(ref _deviceAnsweredScans); + string? reason = null; + foreach (var d in _devices.Values) + if ((reason = DeviceDegradedReason(d)) is not null) break; + var state = reason is null ? DriverState.Healthy : DriverState.Degraded; + if (!force && current.State == state && current.LastSuccessfulRead is { } last + && now - last < AnsweredStampInterval) + return; + _health = new DriverHealth(state, now, reason); } - var current = _health; - if (current.State == DriverState.Faulted) return; - // Hot path (a notification on a healthy driver inside the window): no device scan, no allocation. - if (!force && current.State == DriverState.Healthy && current.LastSuccessfulRead is { } recent - && now - recent < AnsweredStampInterval) - return; - string? reason = null; - foreach (var d in _devices.Values) - if ((reason = DeviceDegradedReason(d)) is not null) break; - var state = reason is null ? DriverState.Healthy : DriverState.Degraded; - if (!force && current.State == state && current.LastSuccessfulRead is { } last - && now - last < AnsweredStampInterval) - return; - _health = new DriverHealth(state, now, reason); } /// First probe-tick retry delay of a REFUSED dead registration (the PLC answered and refused it). @@ -1179,7 +1363,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery ITwinCATClient client; try { - client = await EnsureConnectedUnderGateAsync(device, ct, timeoutOverride: null).ConfigureAwait(false); + client = await EnsureConnectedUnderGateAsync(device, ct).ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception ex) @@ -1195,7 +1379,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery { newHandle = await client.AddNotificationAsync( reg.SymbolName, reg.DataType, reg.BitIndex, reg.ArrayLength, reg.Interval, - _options.NotificationMaxDelayMs, reg.OnChange, ct).ConfigureAwait(false); + _options.NotificationMaxDelayMs, CallbackFor(device, client, reg), ct).ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception ex) @@ -1397,16 +1581,17 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery ITwinCATClient? probed = null; try { - // Probe-initiated connects honor TwinCATProbeOptions.Timeout — distinct from - // the driver-wide _options.Timeout used by reads/writes. - // The probe bypasses the connect backoff — its own interval is the bounded recovery - // cadence, and a successful probe connect resets the window for the data path. - var client = await EnsureConnectedAsync(state, ct, _options.Probe.Timeout, bypassBackoff: true) + // The client carries the DRIVER's timeout (it serves every data read); the probe bounds only its + // own ReadState by TwinCATProbeOptions.Timeout (lmxopcua#982 P-22 — the probe used to create the + // client with its own timeout, which then silently governed every read). + // The probe bypasses the connect backoff — its own interval is the bounded recovery cadence, and a + // successful probe connect resets the window for the data path. It connects WITHOUT replaying the + // stored native registrations: the connect is to the LOCAL AMS router and succeeds against an + // offline PLC, so replaying first cost one failed AddNotification (and one Warning) per + // registration per tick (lmxopcua#982 P-4). They are re-registered below once the probe succeeded. + var client = await EnsureConnectedAsync(state, ct, bypassBackoff: true, deferReplay: true) .ConfigureAwait(false); - success = await client.ProbeAsync(ct).ConfigureAwait(false); - // The probe's ReadState also says whether the PLC is in RUN; a stopped PLC answers but - // serves no live data, so it keeps the driver Degraded (RecordDeviceAnswered below). - if (success) state.PlcState = client.LastAdsState; + success = await DeviceStillAnswersAsync(client, ct).ConfigureAwait(false); // A locally-connected client whose wire probe FAILS is wire-dead but port-open: // force a recycle so the next tick rebuilds + replays native notifications. Without @@ -1416,8 +1601,22 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery await RecycleClientAsync(state, ct).ConfigureAwait(false); else { - // On a healthy tick, re-register any notifications whose replay - // failed (a transient AddNotification blip) so they recover without a client swap. + // The probe's ReadState also says whether the PLC is in RUN; a stopped PLC answers but + // serves no live data, so it keeps the driver Degraded (RecordDeviceAnswered below). + var previousState = state.PlcState; + state.PlcState = client.LastAdsState; + + // An online change or a Stop → download → Run on a target that keeps answering never fails + // the probe, and an online change raises no ADS symbol-version event: detect both here and + // rebuild the client (fresh symbol table) before anything else uses it (lmxopcua#982 P-1). + if (await DetectSymbolTableChangeAsync(state, client, previousState, ct).ConfigureAwait(false) + is { } reason + && InvalidateSymbols(state, client, reason, resetOnlineChangeBaseline: false, scheduleRefresh: false)) + client = await EnsureConnectedAsync(state, ct, bypassBackoff: true, deferReplay: true) + .ConfigureAwait(false); + + // Re-register every registration without a live handle: the ones a deferred connect left + // pending and any whose earlier (re-)registration failed. await RetryDeadRegistrationsAsync(state, ct).ConfigureAwait(false); probed = client; } @@ -1429,6 +1628,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery // failed; a throw from ProbeAsync on an already-connected client would leave it in // place, so force a recycle to guarantee the next tick rebuilds + replays. A shutdown // racing this recycle cancels the gate wait — exit the loop cleanly. + success = false; try { await RecycleClientAsync(state, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } } @@ -1436,13 +1636,20 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery if (success) { state.ConsecutiveProbeFailures = 0; + state.RegistrationOutageWarned = false; RecordDeviceAnswered(DateTime.UtcNow, state, force: true); if (probed is not null) ReportNotificationDrops(state, probed); } - else if (++state.ConsecutiveProbeFailures >= ProbeFailuresBeforeDegraded) + else { - MarkCommsFault($"TwinCAT device {state.Options.HostAddress} unreachable " + - $"({state.ConsecutiveProbeFailures} consecutive failed probes)", state); + // The client was recycled: the next one resolves every symbol anew, so an online change made while + // the device was unreachable needs no second rebuild — start a new counter baseline. + state.OnlineChangeBaseline = null; + if (++state.ConsecutiveProbeFailures >= ProbeFailuresBeforeDegraded) + MarkCommsFault($"TwinCAT device {state.Options.HostAddress} unreachable " + + $"({state.ConsecutiveProbeFailures} consecutive failed probes)", state); + try { await PublishUnregisteredAsUnavailableAsync(state, ct).ConfigureAwait(false); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } } TransitionDeviceState(state, success ? HostState.Running : HostState.Stopped); @@ -1460,6 +1667,81 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery } } + private static bool IsRun(string? adsState) => string.Equals(adsState, "Run", StringComparison.OrdinalIgnoreCase); + + /// + /// The probe tick's symbol-table-change check (lmxopcua#982 P-1): a non-Run → Run transition of the ADS + /// state (a program download is done with the PLC stopped), or a change of the PLC's + /// OnlineChangeCnt — sampled on every healthy tick, not only with diagnostics on, because an online + /// change can relocate variables and raises no ADS symbol-version event. One read per tick. + /// + /// The reason the symbol table must be re-resolved, or null. + private async Task DetectSymbolTableChangeAsync(DeviceState state, ITwinCATClient client, + string? previousState, CancellationToken ct) + { + string? reason = null; + if (previousState is not null && !IsRun(previousState) && IsRun(state.PlcState)) + reason = $"PLC state {previousState} → {state.PlcState} (program download or restart)"; + + uint? count; + using (var bounded = CancellationTokenSource.CreateLinkedTokenSource(ct)) + { + bounded.CancelAfter(_options.Probe.Timeout); + try + { + count = ToUInt(await ReadDiagSymbolAsync(state, client, SymOnlineChangeCnt, TwinCATDataType.UDInt, + SymTc2OnlineChangeCount, TwinCATDataType.UInt, bounded.Token).ConfigureAwait(false)); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch { count = null; } + } + if (count is uint now) + { + if (state.OnlineChangeBaseline is uint before && before != now) + reason ??= $"online change (OnlineChangeCnt {before} → {now})"; + state.OnlineChangeBaseline = now; + } + return reason; + } + + /// + /// After a failed probe tick: every stored registration that is not live (its handle belonged to the client + /// just recycled, or a deferred connect left it pending) is published BadCommunicationError once per + /// outage — the value it last pushed is no longer being refreshed — and one Warning is logged per device + /// per outage, never one per registration per tick (lmxopcua#982 P-4). Refused registrations keep their + /// refusal status and backoff. + /// + private async Task PublishUnregisteredAsUnavailableAsync(DeviceState device, CancellationToken ct) + { + if (device.NativeRegistrations.IsEmpty) return; + var pending = 0; + await device.ConnectGate.WaitAsync(ct).ConfigureAwait(false); + try + { + var now = DateTime.UtcNow; + foreach (var reg in device.NativeRegistrations.Values) + { + if (reg.HasLiveHandle) continue; + pending++; + if (reg.DeadStatus is not null) continue; // already Bad (comms) or refused: keep its status + NoteDeadFailure(reg, TwinCATStatusMapper.BadCommunicationError, refused: false, now); + try { reg.OnUnavailable(); } catch { /* never abort the rest */ } + } + } + finally + { + device.ConnectGate.Release(); + } + if (pending > 0 && !device.RegistrationOutageWarned) + { + device.RegistrationOutageWarned = true; + _logger.LogWarning( + "TwinCAT driver '{DriverInstanceId}' device '{HostAddress}' is not answering: {Pending} native notification(s) " + + "are not registered and will be re-registered once it answers its state probe; logged once per outage", + _driverInstanceId, device.Options.HostAddress, pending); + } + } + /// /// Logs a Warning when the client's native-notification queue dropped values since the last probe /// tick (the queue is bounded and drops on overflow — silently, before #739 L8). At most one @@ -1532,7 +1814,10 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery var appName = await ReadDiagSymbolAsync(state, client, SymAppName, TwinCATDataType.String, SymTc2ProjectName, TwinCATDataType.String, ct).ConfigureAwait(false) as string ?? prev?.AppName; - var onlineChange = ToUInt(await ReadDiagSymbolAsync(state, client, SymOnlineChangeCnt, TwinCATDataType.UDInt, + // The probe tick samples the counter itself on every healthy tick (lmxopcua#982 P-1); read it here only + // when it has not (a direct sample with the probe off). + var onlineChange = state.OnlineChangeBaseline + ?? ToUInt(await ReadDiagSymbolAsync(state, client, SymOnlineChangeCnt, TwinCATDataType.UDInt, SymTc2OnlineChangeCount, TwinCATDataType.UInt, ct).ConfigureAwait(false)) ?? prev?.OnlineChangeCnt; var cycleTicks = ToUInt(await ReadDiagSymbolAsync(state, client, SymCycleTime, TwinCATDataType.UDInt, @@ -1692,8 +1977,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery /// public string ResolveHost(string fullReference) { - if (_resolver.TryResolve(fullReference, out var def) && !string.IsNullOrEmpty(def.DeviceHostAddress)) - return def.DeviceHostAddress; + if (_resolver.TryResolve(fullReference, out var tag) && !string.IsNullOrEmpty(tag.Def.DeviceHostAddress)) + return tag.Def.DeviceHostAddress; // First device's HostAddress when one exists; otherwise the unresolved sentinel — // intentionally NOT DriverInstanceId, which is a config-DB key, not a host address. return _options.Devices.FirstOrDefault()?.HostAddress ?? UnresolvedHostSentinel; @@ -1707,16 +1992,21 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery /// AB-CIP drivers serialize device access the same way; single-connection-per-PLC is /// also what docs/v2/driver-specs.md recommends. /// + /// + /// A client whose symbol table is known stale (, lmxopcua#982 P-1) is + /// never handed out: the gate path retires it and connects a fresh one, so no read, write or registration + /// ever addresses the PLC through an IndexGroup/IndexOffset resolved before a program change. + /// private async Task EnsureConnectedAsync( - DeviceState device, CancellationToken ct, TimeSpan? timeoutOverride = null, bool bypassBackoff = false) + DeviceState device, CancellationToken ct, bool bypassBackoff = false, bool deferReplay = false) { - // Fast path — already connected, no gate needed. - if (device.Client is { IsConnected: true } fast) return fast; + // Fast path — already connected (and not invalidated), no gate needed. + if (device.Client is { IsConnected: true } fast && !ReferenceEquals(fast, device.StaleClient)) return fast; await device.ConnectGate.WaitAsync(ct).ConfigureAwait(false); try { - return await EnsureConnectedUnderGateAsync(device, ct, timeoutOverride, bypassBackoff).ConfigureAwait(false); + return await EnsureConnectedUnderGateAsync(device, ct, bypassBackoff, deferReplay).ConfigureAwait(false); } finally { @@ -1739,11 +2029,17 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery /// the initial subscribe () and the probe loop call /// through here under the same gate, so a replay can never race a register. /// + /// The device. + /// Cancellation token. + /// True for the probe: ignore the connect backoff window. + /// True for the probe: install the client and leave every registration pending + /// (no live handle) instead of replaying it; the probe re-registers them only after the device answered + /// its state read (lmxopcua#982 P-4). private async Task EnsureConnectedUnderGateAsync( - DeviceState device, CancellationToken ct, TimeSpan? timeoutOverride, bool bypassBackoff = false) + DeviceState device, CancellationToken ct, bool bypassBackoff = false, bool deferReplay = false) { // Re-check under the gate: another caller may have connected while we waited. - if (device.Client is { IsConnected: true } c) return c; + if (device.Client is { IsConnected: true } c && !ReferenceEquals(c, device.StaleClient)) return c; // A released device (swapped out by a re-initialise / teardown) never connects again. if (device.Released) throw new DeviceReleasedException(device.Options.HostAddress); @@ -1754,23 +2050,24 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery throw new ConnectionThrottledException( $"TwinCAT connect to {device.Options.HostAddress} throttled — backoff window open after a recent connect failure."); - // Discard a stale (created-but-disconnected) client before making a fresh one. - if (device.Client is { IsConnected: false } stale) + // Discard the previous client — created-but-disconnected, or connected with a stale symbol table — before + // making a fresh one. Its notification handles die with it: every intent is left pending (no live handle) + // and re-registered on the new client below. + if (device.Client is { } previous) { - stale.OnSymbolVersionChanged -= HandleSymbolVersionChanged; - try { stale.Dispose(); } catch { /* best-effort */ } + previous.OnSymbolVersionChanged -= HandleSymbolVersionChanged; + try { previous.Dispose(); } catch { /* best-effort */ } device.Client = null; + MarkRegistrationsPending(device); } var client = _clientFactory.Create(); client.OnSymbolVersionChanged += HandleSymbolVersionChanged; - // timeoutOverride lets the probe loop use TwinCATProbeOptions.Timeout for probe- - // initiated connects rather than the driver-level _options.Timeout. Reads / writes - // pass null and get the driver default. - var effectiveTimeout = timeoutOverride ?? _options.Timeout; try { - await client.ConnectAsync(device.ParsedAddress, effectiveTimeout, ct) + // Always the driver-level timeout: this client serves every read and write of the device, whoever + // happened to create it (lmxopcua#982 P-22). + await client.ConnectAsync(device.ParsedAddress, _options.Timeout, ct) .ConfigureAwait(false); _logger.LogInformation( "TwinCAT driver '{DriverInstanceId}' connected to {HostAddress}", @@ -1795,23 +2092,54 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery throw new DeviceReleasedException(device.Options.HostAddress); } device.Client = client; + device.StaleClient = null; // the fresh client resolves every symbol anew device.ReportedNotificationDrops = 0; device.UnavailableDiagSymbols.Clear(); // a rebuilt client may face a PLC that now exports them device.Backoff.RecordSuccess(); // recovery resets the window immediately // Re-register every native notification onto the fresh client. Native ADS is push, so // (unlike the poll fallback) it cannot self-heal by re-reading — without this the - // subscription is silently dead after a reconnect. - await ReplayNativeRegistrationsAsync(device, client, ct).ConfigureAwait(false); + // subscription is silently dead after a reconnect. The probe defers it until the device answered. + if (deferReplay) MarkRegistrationsPending(device); + else await ReplayNativeRegistrationsAsync(device, client, ct).ConfigureAwait(false); return client; } + /// + /// Leaves every stored registration of a device pending: its live handle (owned by a client being retired) + /// is retracted and the retry is due at once — including a refused one, which a reconnect has always + /// re-checked. Runs under . Its published status is untouched: the + /// re-registration either restores the value (the initial notification push) or publishes the failure. + /// + private static void MarkRegistrationsPending(DeviceState device) + { + foreach (var reg in device.NativeRegistrations.Values) + { + var dead = reg.MarkHandleDead(); + try { dead?.Dispose(); } catch { /* the handle of a disposed client */ } + reg.NextRetryUtc = DateTime.MinValue; + } + } + + /// + /// The notification callback handed to one client: values from a client whose symbol table is known stale + /// are dropped — its handles may address the old program — until the registration is re-established on a + /// fresh client (lmxopcua#982 P-1). + /// + private static Action CallbackFor(DeviceState device, ITwinCATClient client, NativeRegistration reg) => + (symbol, value) => + { + if (!ReferenceEquals(device.StaleClient, client)) reg.OnChange(symbol, value); + }; + /// /// Re-registers every stored for a device onto the given /// freshly-connected client and swaps in the new live handle (disposing the dead one from /// the previous client). Runs under . A single /// registration that fails to replay is logged and skipped — one bad symbol must not abort - /// recovery of the rest. + /// recovery of the rest. A comms-class failure is checked against the device's state once: when the + /// device is gone the remaining registrations are left pending with no further wire attempt + /// (lmxopcua#982 P-4). /// private async Task ReplayNativeRegistrationsAsync(DeviceState device, ITwinCATClient client, CancellationToken ct) { @@ -1819,13 +2147,19 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery if (intents.Length == 0) return; var replayed = 0; + var outcome = new RegistrationPass(); foreach (var reg in intents) { + if (outcome.Unreachable) + { + NoteUnreachable(reg); + continue; + } try { var newHandle = await client.AddNotificationAsync( reg.SymbolName, reg.DataType, reg.BitIndex, reg.ArrayLength, reg.Interval, - _options.NotificationMaxDelayMs, reg.OnChange, ct).ConfigureAwait(false); + _options.NotificationMaxDelayMs, CallbackFor(device, client, reg), ct).ConfigureAwait(false); var old = reg.SwapHandle(newHandle); try { old?.Dispose(); } catch { /* dead handle from the disposed client */ } // An UnsubscribeAsync (gate-free) can race this replay — if it removed the @@ -1840,6 +2174,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery NoteLive(reg); replayed++; } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } catch (TwinCATNotificationRefusedException refused) { // The PLC answered and refused this tag again (it was already isolated at subscribe, or a @@ -1856,19 +2191,11 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery } catch (Exception ex) { - _logger.LogWarning(ex, - "TwinCAT driver '{DriverInstanceId}' failed to replay native notification " + - "'{Symbol}' on device '{HostAddress}' after reconnect", - _driverInstanceId, reg.SymbolName, device.Options.HostAddress); - // The intent has no live handle now — mark it dead so the probe-tick // retry re-registers it, surface Bad quality to subscribers (the OnChange shape has // no quality channel), and degrade health preserving the last successful read. - var dead = reg.MarkHandleDead(); - try { dead?.Dispose(); } catch { /* already-dead handle from the disposed client */ } - if (NoteDeadFailure(reg, TwinCATStatusMapper.BadCommunicationError, refused: false, DateTime.UtcNow)) - try { reg.OnUnavailable(); } catch { /* never let a subscriber callback abort recovery of the rest */ } - MarkCommsFault($"native-notification replay failed for '{reg.SymbolName}' on {device.Options.HostAddress}", device); + NoteUnreachable(reg); + await OnCommsClassRegistrationFailureAsync(device, client, reg, ex, outcome, ct).ConfigureAwait(false); } } @@ -1878,6 +2205,57 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery _driverInstanceId, replayed, intents.Length, device.Options.HostAddress); } + /// The state of one replay / retry pass over a device's registrations. + private sealed class RegistrationPass + { + /// The device stopped answering during the pass: the rest stay pending without a wire attempt. + public bool Unreachable; + + /// The device's ADS state was already checked in this pass. + public bool Verified; + } + + /// Leaves one registration dead after a comms-class failure, publishing Bad when its status changes. + private static void NoteUnreachable(NativeRegistration reg) + { + var dead = reg.MarkHandleDead(); + try { dead?.Dispose(); } catch { /* already-dead handle from the disposed client */ } + if (NoteDeadFailure(reg, TwinCATStatusMapper.BadCommunicationError, refused: false, DateTime.UtcNow)) + try { reg.OnUnavailable(); } catch { /* never let a subscriber callback abort recovery of the rest */ } + } + + /// + /// A (re-)registration failed comms-class: degrade (once per pass), and check — once per pass — whether the + /// device still answers its state. Gone ⇒ the pass stops dialling it, one Warning per device per outage; + /// still answering ⇒ the failure was this one tag's, logged as such, and the pass carries on. + /// + private async Task OnCommsClassRegistrationFailureAsync(DeviceState device, ITwinCATClient client, + NativeRegistration reg, Exception ex, RegistrationPass pass, CancellationToken ct) + { + if (!pass.Verified) + { + pass.Verified = true; + MarkCommsFault($"native-notification registration failed for '{reg.SymbolName}' on {device.Options.HostAddress}", device); + pass.Unreachable = !await DeviceStillAnswersAsync(client, ct).ConfigureAwait(false); + } + if (pass.Unreachable) + { + if (!device.RegistrationOutageWarned) + { + device.RegistrationOutageWarned = true; + _logger.LogWarning(ex, + "TwinCAT driver '{DriverInstanceId}' device '{HostAddress}' stopped answering while its native " + + "notifications were being registered; the rest stay pending until it answers its state probe " + + "(logged once per outage)", _driverInstanceId, device.Options.HostAddress); + } + return; + } + _logger.LogWarning(ex, + "TwinCAT driver '{DriverInstanceId}' failed to register native notification " + + "'{Symbol}' on device '{HostAddress}'; it will be retried on the next healthy probe tick", + _driverInstanceId, reg.SymbolName, device.Options.HostAddress); + } + /// /// Re-registers every dead (failed-replay) onto /// the device's currently-connected client. Runs under @@ -1894,21 +2272,27 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery await device.ConnectGate.WaitAsync(ct).ConfigureAwait(false); try { - if (device.Client is not { IsConnected: true } client) return; + if (device.Client is not { IsConnected: true } client || ReferenceEquals(client, device.StaleClient)) return; var recovered = 0; var now = DateTime.UtcNow; + var pass = new RegistrationPass(); foreach (var reg in device.NativeRegistrations.Values) { if (reg.HasLiveHandle) continue; // A refused registration waits out its backoff (a symbol-version change re-arms it). if (now < reg.NextRetryUtc) continue; + if (pass.Unreachable) + { + NoteUnreachable(reg); + continue; + } var epoch = reg.RearmEpoch; try { var newHandle = await client.AddNotificationAsync( reg.SymbolName, reg.DataType, reg.BitIndex, reg.ArrayLength, reg.Interval, - _options.NotificationMaxDelayMs, reg.OnChange, ct).ConfigureAwait(false); + _options.NotificationMaxDelayMs, CallbackFor(device, client, reg), ct).ConfigureAwait(false); reg.SwapHandle(newHandle); // Ownership re-check — see ReplayNativeRegistrationsAsync. if (!device.NativeRegistrations.ContainsKey(reg.Id)) @@ -1929,6 +2313,15 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery var status = refusal?.StatusCode ?? TwinCATStatusMapper.BadCommunicationError; if (NoteDeadFailure(reg, status, refusal is not null, now, epoch)) try { reg.OnRefused(status); } catch { /* never abort the rest */ } + if (refusal is null) + { + // A comms-class failure: is the device gone (stop dialling it this tick) or is it this tag? + if (!pass.Verified) + { + pass.Verified = true; + pass.Unreachable = !await DeviceStillAnswersAsync(client, ct).ConfigureAwait(false); + } + } _logger.LogDebug(ex, "TwinCAT driver '{DriverInstanceId}' probe-tick retry of dead notification " + "'{Symbol}' on device '{HostAddress}' failed; will retry next tick", @@ -1954,7 +2347,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery /// by the probe loop when a wire-level probe fails on a locally-"connected" client — the /// fast-path keys on the AMS-port state, not wire /// liveness, so without this forced recycle a wire-dead-but-port-open client would keep - /// being reused and native pushes would never recover. + /// being reused and native pushes would never recover. The registrations' handles died with the + /// client, so they are left pending (and published Bad by the probe once per outage). /// private async Task RecycleClientAsync(DeviceState device, CancellationToken ct) { @@ -1969,6 +2363,7 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery c.OnSymbolVersionChanged -= HandleSymbolVersionChanged; try { c.Dispose(); } catch { /* best-effort */ } device.Client = null; + MarkRegistrationsPending(device); } } finally @@ -1978,23 +2373,94 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery } /// - /// Routes a wire-detected ADS symbol-version-changed (DeviceSymbolVersionInvalid 1809 / - /// 0x0711) to Core as an invocation. - /// A PLC re-download invalidates every symbol + notification handle, so the address - /// space must be rebuilt — this is the documented TwinCAT failure mode, not a transient - /// connection error. + /// Routes a client's symbol-table-changed signal — the ADS symbol-version event (a program download), a + /// DeviceSymbolVersionInvalid (1809 / 0x0711) answer, or the target invalidating a registered + /// notification — to . The device whose CURRENT client raised it is + /// invalidated once; a repeat from the same client (a sum-read with N 1809 sub-errors) or a late signal from + /// a client already retired is ignored. /// private void HandleSymbolVersionChanged(object? sender, EventArgs e) { - // A program change can make a refused registration valid: re-arm every backed-off dead intent of the - // device whose client saw it, so the next probe tick re-checks them at once. + if (sender is not ITwinCATClient client) return; foreach (var d in _devices.Values) - if (ReferenceEquals(d.Client, sender)) - foreach (var reg in d.NativeRegistrations.Values) - reg.Rearm(); - OnRediscoveryNeeded?.Invoke(this, new RediscoveryEventArgs( - "TwinCAT symbol-version-changed (DeviceSymbolVersionInvalid 0x0711) — PLC program re-downloaded", - ScopeHint: "TwinCAT")); + if (ReferenceEquals(d.Client, client)) + InvalidateSymbols(d, client, + "TwinCAT symbol-version-changed (DeviceSymbolVersionInvalid 0x0711) — PLC program re-downloaded", + resetOnlineChangeBaseline: true, scheduleRefresh: true); + } + + /// + /// Marks a device's current client as holding a stale symbol table (lmxopcua#982 P-1). Beckhoff's symbol + /// cache keeps every IndexGroup/IndexOffset it resolved until the client is disposed or + /// CleanupSymbolTable() is called — it cleans itself only on the ADS symbol-version event, which an + /// online change does not raise — so after a program change a read could address other memory and publish + /// it at Good. From here: the client is never handed out again (the next connect retires it and resolves + /// every symbol anew); its notification pushes are dropped; native registrations are re-established on the + /// fresh client (in the background, or by the probe tick that detected the change); refused registrations + /// are re-armed; and the advisory rediscovery signal is raised — once per event. + /// + /// The device. + /// The client the change was observed on; ignored unless it is the device's current one. + /// Why, for the log and the rediscovery signal. + /// True when the change was not detected through the online-change + /// counter (a download may reset it): the next probe sample starts a new baseline instead of reporting a + /// second change. + /// True to re-establish native registrations in the background now; the probe + /// passes false because it rebuilds the client itself. + /// True when this call invalidated the client (false for a repeat or a retired client). + private bool InvalidateSymbols(DeviceState device, ITwinCATClient client, string reason, + bool resetOnlineChangeBaseline, bool scheduleRefresh) + { + if (device.Released) return false; + lock (device.ProbeLock) + { + if (!ReferenceEquals(device.Client, client) || ReferenceEquals(device.StaleClient, client)) return false; + device.StaleClient = client; + if (resetOnlineChangeBaseline) device.OnlineChangeBaseline = null; + } + + // A program change can make a refused registration valid: re-arm every backed-off dead intent of the + // device, so the re-registration re-checks them at once. + foreach (var reg in device.NativeRegistrations.Values) reg.Rearm(); + + _logger.LogInformation( + "TwinCAT driver '{DriverInstanceId}' device '{HostAddress}': {Reason}; re-resolving every symbol on a fresh client", + _driverInstanceId, device.Options.HostAddress, reason); + if (scheduleRefresh) ScheduleRefresh(device); + try { OnRediscoveryNeeded?.Invoke(this, new RediscoveryEventArgs(reason, ScopeHint: "TwinCAT")); } + catch (Exception ex) + { + _logger.LogWarning(ex, "TwinCAT driver '{DriverInstanceId}' rediscovery handler threw", _driverInstanceId); + } + return true; + } + + /// + /// Re-establishes a device's native registrations on a fresh client in the background after its symbol table + /// was invalidated — so a notification-only device recovers even with the probe disabled. Poll reads need no + /// help: the next one connects a fresh client itself. At most one refresh per device runs at a time; a change + /// signalled during it is picked up by a bounded re-run. + /// + private void ScheduleRefresh(DeviceState device) + { + if (device.NativeRegistrations.IsEmpty) return; + if (Interlocked.Exchange(ref device.RefreshScheduled, 1) != 0) return; + _ = Task.Run(async () => + { + try + { + for (var pass = 0; pass < 3 && !device.Released; pass++) + { + try { await EnsureConnectedAsync(device, CancellationToken.None).ConfigureAwait(false); } + catch { return; /* connect failed or the device was released: the probe tick / next call retries */ } + if (device.StaleClient is null || !ReferenceEquals(device.Client, device.StaleClient)) return; + } + } + finally + { + Volatile.Write(ref device.RefreshScheduled, 0); + } + }); } /// @@ -2118,5 +2584,23 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery /// Total notification drops last reported for this device's current client. public long ReportedNotificationDrops; + + /// + /// The client whose symbol table is known stale (a program download / online change was signalled or + /// detected on it); null when the current client is fresh. Never handed out again — the next connect + /// retires it (lmxopcua#982 P-1). + /// + public volatile ITwinCATClient? StaleClient; + + /// The PLC's OnlineChangeCnt at the last healthy probe tick; null before the first sample or + /// after a symbol-version change (a download may reset the counter). + public uint? OnlineChangeBaseline { get; set; } + + /// 1 while a background re-registration after a symbol-table change is running. + public int RefreshScheduled; + + /// True once this outage's "native notifications not registered" Warning was logged; reset when + /// the probe succeeds. + public volatile bool RegistrationOutageWarned; } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATStatusMapper.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATStatusMapper.cs index 3347545d9..5ccf85158 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATStatusMapper.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATStatusMapper.cs @@ -46,8 +46,10 @@ public static class TwinCATStatusMapper /// /// Map an AMS / ADS error code (uint cast from AdsErrorCode 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 (a refusal, never a + /// comms fault) — except DeviceTimeOut (1817), which is a timeout. Anything outside that range + /// (AMS / router / client-layer / socket) is a comms failure. /// /// The ADS error code to map. /// The corresponding OPC UA status code. @@ -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, }; + + /// First ADS device-layer error code (DeviceError, 0x0700). + public const uint DeviceLayerFirst = 0x0700u; + + /// Last ADS device-layer error code (0x073F); client-layer codes start at 0x0740. + public const uint DeviceLayerLast = 0x073Fu; } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATSymbolPath.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATSymbolPath.cs index e57284a78..ea8eb12fe 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATSymbolPath.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATSymbolPath.cs @@ -39,11 +39,18 @@ public sealed record TwinCATSymbolPath( return buf.ToString(); } + /// + /// Test seam: when a test sets a counter on its own async flow, every made on that flow + /// counts — proves the read path parses nothing per tag (lmxopcua#982 P-19). Never set in production. + /// + internal static readonly AsyncLocal?> ParseCounterForTest = new(); + /// Attempts to parse a TwinCAT symbol path from the given string. /// The path string to parse. /// A TwinCATSymbolPath if parsing succeeds; otherwise null. 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(); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATTypeGuard.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATTypeGuard.cs index 4a1bdb4aa..706b5037b 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATTypeGuard.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATTypeGuard.cs @@ -25,8 +25,10 @@ internal enum TwinCATPlcKind /// True for a REAL / LREAL scalar. /// The (alias-resolved) PLC type name, for log messages. /// True for an ARRAY (a with array category or name). +/// True for a POINTER / REFERENCE / VAR_IN_OUT — a +/// whose own bytes are an address a scalar read may legitimately return. 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; } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/FakeTwinCATClient.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/FakeTwinCATClient.cs index 8559f9afd..7189aa9c9 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/FakeTwinCATClient.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/FakeTwinCATClient.cs @@ -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; } + /// Gets the timeout the most recent was given. + public TimeSpan? LastConnectTimeout { get; private set; } + + /// Gets the AMS address the most recent targeted. + public TwinCATAmsAddress? ConnectedAddress { get; private set; } + /// When set, does not complete (and ignores cancellation) until this /// is completed — a probe wedged in the synchronous ADS Connect. 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; + /// Gets every symbol an individual was served for, in order. + public ConcurrentQueue ReadSymbols { get; } = new(); + /// Gets the number of individual calls served. public int SingleReadCount { get => Volatile.Read(ref _singleReadCount); private set => Volatile.Write(ref _singleReadCount, value); } /// Gets the size of each batch the driver issued, in order (#645). @@ -277,6 +289,11 @@ internal class FakeTwinCATClient : ITwinCATClient /// The symbol path. /// The attempt count. public int AttemptsFor(string symbolPath) => _addAttempts.TryGetValue(symbolPath, out var n) ? n : 0; + + private int _totalAddAttempts; + + /// Gets how many times was called on this client, for any symbol. + public int TotalAddAttempts => Volatile.Read(ref _totalAddAttempts); /// Records the most recently-supplied maxDelayMs for Driver.TwinCAT-014 tests. public int LastMaxDelayMs { get; private set; } /// When set, awaits this gate BEFORE applying @@ -301,6 +318,7 @@ internal class FakeTwinCATClient : ITwinCATClient int maxDelayMs, Action 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"); diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATDiagnosticsTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATDiagnosticsTests.cs index c3935b6e8..75b22b2ed 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATDiagnosticsTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATDiagnosticsTests.cs @@ -208,7 +208,11 @@ public sealed class TwinCATDiagnosticsTests bag.Count.ShouldBe(12); } - /// Verifies sampling is opt-in: with it off the probe loop adds no reads and the bag stays empty. + /// + /// 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. + /// [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(); } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATLowFindingsRegressionTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATLowFindingsRegressionTests.cs index 4f6ec7520..5a0926b17 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATLowFindingsRegressionTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATLowFindingsRegressionTests.cs @@ -63,12 +63,15 @@ public sealed class TwinCATLowFindingsRegressionTests // ---- Driver.TwinCAT-014 — config surface knobs are honoured ---- - /// Verifies that ProbeOptions.Timeout is applied to probe calls. + /// + /// 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 Timeout. + /// [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(); 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)); } /// Verifies that NotificationMaxDelayMs is exposed on driver options. @@ -242,7 +245,7 @@ public sealed class TwinCATLowFindingsRegressionTests await Task.Delay(20); } - /// Captures the timeout argument from ProbeAsync invocations (via the connect path). + /// Captures the timeout argument the client is connected with. private sealed class ProbeTimeoutCapturingFake : FakeTwinCATClient { private readonly List _observed; @@ -254,9 +257,7 @@ public sealed class TwinCATLowFindingsRegressionTests /// 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); } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATReview20261202Tests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATReview20261202Tests.cs new file mode 100644 index 000000000..87983abbd --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests/TwinCATReview20261202Tests.cs @@ -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; + +/// +/// lmxopcua#982 — the TwinCAT findings of the 2026-12-02 review +/// (docs/reviews/2026-12-02/09-ab-twincat-focas.md): 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. +/// +[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 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 ======================= + + /// + /// A fake factory whose every client is a new "generation": a read through client n returns + /// n * 100 + 11. 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. + /// + 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; + } + + /// + /// 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. + /// + [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); + } + + /// + /// 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. + /// + [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(); + 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); + } + + /// + /// 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. + /// + [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); + } + + /// + /// 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 OnlineChangeCnt on every + /// healthy tick (not only with diagnostics on) and retires the client when it moves. + /// + [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); + } + + /// + /// 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. + /// + [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 ======================= + + /// A client that, for one AMS target, waits and answers BadTimeout (a silent PLC). + 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> ReadValuesAsync( + IReadOnlyList 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 ProbeAsync(CancellationToken ct) => + Silent && !targetAnswersProbe ? Task.FromResult(false) : base.ProbeAsync(ct); + + public override async Task AddNotificationAsync(string symbolPath, + TwinCATDataType type, int? bitIndex, int? arrayCount, TimeSpan cycleTime, int maxDelayMs, + Action 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 clients) SilentFactory( + TimeSpan delay, bool targetAnswersProbe) + { + var clients = new List(); + 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))]; + + /// + /// 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. + /// + [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); + } + + /// + /// 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). + /// + [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); + } + + /// A client on which one symbol times out while the device keeps answering. + 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); + } + } + + /// + /// 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. + /// + [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 ======================= + + /// A client whose target can be switched off: probes fail and every registration fails comms-class. + private sealed class OutageFake(Func offline) : FakeTwinCATClient + { + public override Task ProbeAsync(CancellationToken ct) => + offline() ? Task.FromResult(false) : base.ProbeAsync(ct); + + public override Task AddNotificationAsync(string symbolPath, TwinCATDataType type, + int? bitIndex, int? arrayCount, TimeSpan cycleTime, int maxDelayMs, Action 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); + } + + /// + /// 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. + /// + [Fact] + public async Task An_offline_plc_is_probed_before_any_registration_is_replayed() + { + var offline = false; + var clients = new List(); + 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 ======================= + + /// P-12: device-layer refusals (0x700–0x73F) are device failures, never comms faults. + [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(); + } + + /// P-12 positive control: transport, router, client-layer and socket codes stay comms-class. + [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(); + } + + /// + /// 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. + /// + [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); + } + + /// + /// 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). + /// + [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); + } + + /// + /// 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). + /// + [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(); + } + + /// + /// 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). + /// + [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 ======================= + + /// + /// 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). + /// + [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(); + 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); + } + + /// P-19: two devices read in one call → one state re-derivation each. + [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 ======================= + + /// + /// 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 false for bit 20 of a + /// 16-bit WORD, where the other two said BadOutOfRange. + /// + [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 ======================= + + /// A client whose state probe never answers until cancelled. + private sealed class HangingProbeFake : FakeTwinCATClient + { + public override async Task ProbeAsync(CancellationToken ct) + { + try { await Task.Delay(Timeout.Infinite, ct); } + catch (OperationCanceledException) { } + return false; + } + } + + /// + /// 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 TimeoutMs never reached a read — and a hung ReadState hung the probe. + /// + [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); + } +}