From e68d856fcb4ffea3c8b3796e80968290bdfe8bbc Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:04:42 -0500 Subject: [PATCH] fix(focas): #985 refusals stay Healthy, protocol faults close the session, dead CNCs no longer stall others - P-6: the wire adapter throws refused fixed-tree calls as FocasWireException carrying the rc (was InvalidOperationException, so a refusing control looked silent, degraded and was reconnect-looped by the #527 watchdog); a refused axis is per-node BadNoData and the tick continues. - P-7: bootstrap capability probes latch only an ANSWER (rc, or session still up); a transport failure/timeout or a session dropped mid-pass retries the bootstrap. - P-21: CoalesceRejected latches only range-shaped codes (not EW_BUSY/EW_SOCKET/EW_UNEXP/EW_HANDLE/unknown). Macro/param multi-block batching deferred (unproven on hardware). - P-10: any fault once a request is on the wire closes the session (bad magic/version, unexpected PDU, malformed blocks); replies must echo the request's command ids in order (verified against every 31i-B capture). A refusal never closes the session. - P-8: close handshake bounded to 1 s and run under the request gate (sync + async dispose). - P-11: data-path callers check the backoff before ConnectGate and fail fast behind an in-flight reconnect to a device whose last connect failed. - P-9: axes/spindles carry their wire slot (FocasAxisName/FocasSpindleName.Slot); cnc_rddynamic2 and the spindle-meter lookup use it. - P-20: a truncated (>= 32) alarm list never clears/retriggers a told-active condition unless it shows a new key; unseen told keys are kept. - P-25: a refused connect-time sysinfo is not cached; a short PARAM payload reads BadTypeMismatch. Tests: loopback MockFocasWireServer drives the real wire client; every fix mutation-checked (reverting it fails its test). FOCAS.Tests 619/619, FOCAS.IntegrationTests 19/19 vs the sim on 10.100.0.35, Runtime.Tests FOCAS 7/7, FOCAS.Cli.Tests 57/57. --- .claude/rules/drivers.md | 9 + docs/drivers/FOCAS.md | 69 ++- .../FocasAlarmProjection.cs | 13 + .../FocasDriver.cs | 167 +++++- .../IFocasClient.cs | 19 +- .../Wire/FocasWireClient.cs | 133 ++++- .../Wire/WireFocasClient.cs | 143 +++-- .../FakeFocasClient.cs | 2 +- .../FocasAlarmProjectionTests.cs | 65 +++ .../FocasPmcCoalescingDriverTests.cs | 24 +- .../FocasRefusalAndIsolationTests.cs | 489 ++++++++++++++++++ .../FocasWireSessionIntegrityTests.cs | 306 +++++++++++ .../MockFocasWireServer.cs | 229 ++++++++ 13 files changed, 1568 insertions(+), 100 deletions(-) create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasRefusalAndIsolationTests.cs create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasWireSessionIntegrityTests.cs create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/MockFocasWireServer.cs diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index c20978143..c143d866a 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -218,6 +218,15 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa - **FOCAS (#257/#266):** `cnc_statinfo` flags are a `Status/` fixed-tree subtree (`FIXED:Status/Run`…, capability-probed); adjacent PMC tags in one poll batch coalesce into one `pmc_rdpmcrng` (`PmcCoalesce` config, default on) — a refused range falls back to per-tag reads, a transport failure fails all members without retry. Parts count stays `PARAM:6711` (docs only). +- **FOCAS refusal vs comms fault + wire integrity (#985):** every refused call the wire adapter makes THROWS + `FocasWireException` carrying its `Rc` (`IsCncRefusal`) — never a plain exception, or a refusing fixed-tree control + looks silent and the #527 watchdog reconnect-loops it. A refused axis is per-node `BadNoData`, the tick continues. + Bootstrap capabilities latch only on an ANSWER (rc, or session still up); a transport failure/timeout or a session + that dropped mid-pass retries the bootstrap. `CoalesceRejected` latches only range-shaped codes. ANY fault once a + request is on the wire closes the session (replies are positional; command ids must echo the request) — a refusal + never does. Close handshake ≤ 1 s under the request gate. Data callers check the backoff before `ConnectGate` and fail + fast behind an in-flight reconnect to a device whose last connect failed. Axes/spindles use the WIRE slot + (`FocasAxisName.Slot`). A truncated alarm list (≥ 32) never clears/retriggers a told-active condition unless it shows a new key. - **FOCAS alarms (#647):** an `ALARM:` address (`*`, ``, `/`, `/-`, `T`, `OTHER`) + the `alarm` object = ONE condition at the RawPath (either alone is skipped + reported). Overlapping selectors all fire; `OTHER` = what no type selector claims. ⚠️ A failed `cnc_rdalmmsg2` THROWS (it used to return `[]` ⇒ mass diff --git a/docs/drivers/FOCAS.md b/docs/drivers/FOCAS.md index 35daeb936..34f7a0635 100644 --- a/docs/drivers/FOCAS.md +++ b/docs/drivers/FOCAS.md @@ -213,6 +213,20 @@ Two caveats worth knowing before you browse: stops answering, its fixed-tree values go `BadCommunicationError` rather than continuing to serve the last snapshot as `Good`; the budget is eight poll cadences, floored at 30 s. +- **A refusal is an answer, not silence (#985).** A `cnc_rddynamic2` the CNC + answers with a non-OK return code (e.g. `EW_FUNC`, a sustained `EW_BUSY`) reads + `BadNoData` on *that axis's* nodes (and, for the first axis, `FeedRate` / + `SpindleSpeed`) while the other axes, meters, program and status keep polling; + the driver stays `Healthy` with `LastSuccessfulRead` advancing, so the #527 + comms-loss watchdog never reconnect-loops a control that merely declines a call. + Only a transport failure (no answer) degrades it. (Before #985 the wire adapter + threw a plain exception for every refused fixed-tree call, so a refusal read as + silence and degraded the driver.) +- **Axes and spindles are addressed by their wire slot (#985).** `cnc_rdaxisname` + reports each name in a 1-based slot and skips blank ones; that slot — not the + name's position in the blank-free list — is the axis number `cnc_rddynamic2` is + asked for, and the spindle meter record a `Spindle//…` node reads. A control + reporting names in slots 1, 2 and 4 used to poll its third axis as axis 3. What gets populated (all under `FOCAS/{deviceHostAddress}/`, addressed as `FIXED:{subtree}/{field}`): @@ -265,6 +279,13 @@ covers `Spindle/`, `Program/` + `OperationMode/`, `Status/`, `Timers/`, and per-axis `ServoLoad` independently. Identity + `Axes/*` position reads (which every Fanuc CNC supports) are always emitted. +The probe result is latched for the life of the device, so only an **answer** is +recorded (#985): a refusal (a non-OK return code), or any failure that left the +session up. A transport failure or timeout during the probe pass — or a session +that dropped part-way through it — retries the whole bootstrap two seconds later +instead. (A single stalled `cnc_rdsvmeter` at startup used to close the session +and record every later capability "unsupported" until the driver was respawned.) + Position values (`AbsolutePosition`, `MachinePosition`, `RelativePosition`, `DistanceToGo`) are published as `Float64` in engineering units. **Each `cnc_rddynamic2` position block carries its own scale** — `[i32 raw][u16 base][u16 exponent]`, value = `raw / base^exponent` (a real @@ -386,9 +407,13 @@ Rules worth knowing: are separate). A multi-byte tag joins a range only when its offset from the range start is a multiple of its width, because the CNC splits a range into width-sized slots from the start. - **Spare gap bytes must be valid PMC addresses.** A gap that crosses a hole in the CNC's PMC map makes the CNC - refuse the whole range. That is handled, not fatal: a refused range is remembered per device and its tags are - read **individually**, each with its own true status (a refusal is never stamped onto healthy members). If - that happens routinely, lower `MaxGapBytes` (0 disables gap-spanning entirely) or set `Enabled` to `false`. + refuse the whole range. That is handled, not fatal: the range's tags are read **individually**, each with its + own true status (a refusal is never stamped onto healthy members), and a range refused with a **range-shaped** + code (`EW_NUMBER` / `EW_LENGTH` / `EW_OVRFLOW` / `EW_DATA` / `EW_ATTRIB` / `EW_FUNC` / `EW_NOOPT`) is + remembered per device so later polls skip the merged read. Any other code (`EW_BUSY`, `EW_SOCKET`, + `EW_UNEXP`, `EW_PARITY`, `EW_HANDLE`, unknown) says nothing about the range and is **not** remembered (#985 — + one blip used to disable coalescing for the device's lifetime). If refusals happen routinely, lower + `MaxGapBytes` (0 disables gap-spanning entirely) or set `Enabled` to `false`. - A transport failure or timeout on the merged read fails every member with `BadCommunicationError` and does **not** retry per tag — the link is down, so per-tag retries would only multiply timeouts. - Read-only: this changes `pmc_rdpmcrng` reads only; nothing here can write. @@ -447,6 +472,12 @@ it, then author `ALARM:T`. Number ranges are series-independent. CNC alarm is a statement the operator has not seen); the **displayed** alarm leaves while others remain = `Retrigger` with the next one down (the MTConnect precedent); a **non-displayed** member leaves = nothing; nothing matches = `Clear`. +- **A list cut off at the cap (32) cannot take anything away (#985).** Any alarm a truncated read does not show + may simply be past the cap, so a condition the server was told is active keeps its told state — no `Clear`, no + `Retrigger` for a displayed alarm that fell past the cap — unless the list shows it a genuinely new alarm (a + `Retrigger`, as above). The members it could not see stay in the told set, so their reappearance when the + storm subsides is not "new" either. (An active `ALARM:Servo/401` used to clear in an alarm storm and re-raise + un-acknowledged once the list shrank.) - **Severity, explicitly.** An authored integer `alarm.severity` is the condition's exact Part 9 severity (`OpcUaSeverity`; the host clamps 1..1000). Without one, the bucket comes from the displayed alarm's type: Overtravel / Servo / PulseCode → Critical (900), Parameter / MacroAlarm → Medium (500), everything else @@ -537,6 +568,38 @@ single-client deployment. Reads / writes during recycle simply wait for the reconnect rather than failing — worst case, an operator sees a brief read latency spike once per cadence. +The close PDU a recycle (or a shutdown / re-initialise) sends is a courtesy to the +CNC's handle pool, and its reply wait is **bounded to 1 s** and runs under the +session's request gate (#985): a CNC that lost power, or hung while TCP still +ACKs, used to block the dispose until TCP gave up — with the recycle holding the +device's connect gate, so every poll of that device parked behind it with no +result and no health change. + +## Wire session integrity (#985) + +- **A protocol fault closes the session.** Once a request is on the wire, *any* + failure — a socket error or timeout, but equally a bad PDU magic or version, an + unexpected PDU type, a malformed block list, or a reply whose blocks do not echo + the request's command ids in order (or carry more blocks than were asked for) — + tears both sockets down and fails the call as transient; the next call + reconnects. Replies are matched to requests by position, so a kept session would + hand request N's reply to request N+1 (a macro publishing another macro's value + at `Good`). A CNC **refusal** (a non-OK return code inside a well-formed reply) + is an answer and never closes the session. Every captured 31i-B reply + (`Fixtures/v3`, refused blocks included) and the focas-mock fixture echo command + ids in request order; a *shorter* reply is tolerated as before. +- **A refused connect-time `cnc_sysinfo` is not cached** — only an answer is, so a + transient `EW_BUSY` at connect no longer fails every later sysinfo (and with it + the fixed-tree bootstrap) for the life of the session. +- **A `PARAM:` payload shorter than the tag's type reads `BadTypeMismatch`** (a + per-tag refusal; no health impact) — it used to decode as a `Good 0`. +- **A dead CNC does not stall the others.** A data-path caller checks the device's + connect backoff *before* queueing on its connect gate, and fails fast while a + reconnect to a device whose last connect failed is already in flight (the probe + bypasses the backoff and can hold the gate for a whole connect timeout). + `ReadAsync` awaits every device, so before #985 one black-holed CNC delayed the + healthy CNCs' publishes by up to the connect timeout. + ## Testing - **Unit tests** — `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/` cover the diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasAlarmProjection.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasAlarmProjection.cs index 107264d0d..d1f630e7c 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasAlarmProjection.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasAlarmProjection.cs @@ -325,7 +325,20 @@ internal sealed class FocasAlarmProjection : IAsyncDisposable // not signalled (it stays unknown). One that matched something is established either way. if (!truncated || view.Matched.Count > 0) (established ??= new List()).Add(tag.RawPath); _told.TryGetValue(tag.RawPath, out var told); + // #985 P-20: by the same token, a truncated list cannot take anything AWAY from a condition the server + // was told is active — every alarm it no longer sees may simply be past the cap. So unless the list + // shows it something NEW (a key not in the told set — a genuine new statement), keep the told state + // untouched: no Clear (an active condition used to clear in an alarm storm and re-raise un-acked once + // the list shrank), no Retrigger for a displayed alarm that merely fell past the cap, and the told + // keys are kept so the alarm's reappearance is not "new" either. + if (truncated && told is { Active: true } + && view.Matched.All(m => told.Keys.Contains(m.Key))) + continue; var (evt, nowTold) = FocasAlarmConditionMapper.Transition(told, view, tag, sub.Handle, now); + // A new statement on a truncated list still cannot prove the told keys it no longer sees are gone: + // keep them, so they do not read as new (and Retrigger again) when the list shrinks. + if (truncated && told is { Active: true } && nowTold.Active) + nowTold = nowTold with { Keys = nowTold.Keys.Union(told.Keys).ToHashSet() }; _told[tag.RawPath] = nowTold; if (evt is null) continue; Deliver(handlers, evt, tag.RawPath); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs index 8b31a863f..49d607361 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs @@ -1000,9 +1000,11 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, { // The CNC REFUSED the merged range (any return code, mapped or not). Don't guess which // member is at fault: let the per-tag loop give each its own answer. Remember the range - // so later polls skip the doomed read — except for a transient refusal (EW_BUSY maps to - // BadDeviceFailure), which says nothing about the range. - if (status != FocasStatusMapper.BadDeviceFailure) + // so later polls skip the doomed read — but only for a RANGE-SHAPED refusal (#985 P-21). Any + // other code (EW_BUSY, EW_SOCKET / EW_UNEXP / EW_PARITY / unknown → BadCommunicationError, + // EW_HANDLE → BadInternalError) says nothing about the range, and latching on it disabled + // coalescing for the device's lifetime after one transient blip. + if (IsRangeShapedRefusal(status)) device.CoalesceRejected[plan.Key] = 0; _logger.LogDebug( "FOCAS PMC range {Key} on {Host} rejected (0x{Status:X8}) — reading its {Count} tags individually", @@ -1031,6 +1033,19 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, } } + /// + /// Whether a refused merged PMC range should be remembered as permanently unreadable (#985 P-21): only the + /// statuses a range itself causes — EW_NUMBER / EW_LENGTH / EW_OVRFLOW + /// (), EW_DATA / an unknown area + /// (), EW_ATTRIB + /// () and EW_FUNC / EW_NOOPT / EW_VERSION + /// (). Everything else is transient or link-shaped. + /// + /// The mapped status of the refused range read. + /// to latch the range as rejected. + internal static bool IsRangeShapedRefusal(uint status) => status is FocasStatusMapper.BadOutOfRange + or FocasStatusMapper.BadNodeIdUnknown or FocasStatusMapper.BadTypeMismatch or FocasStatusMapper.BadNotSupported; + // ---- IWritable ---- /// @@ -1470,14 +1485,22 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, var sys = await client.GetSysInfoAsync(ct).ConfigureAwait(false); var axes = await client.GetAxisNamesAsync(ct).ConfigureAwait(false); - // Optional-API probes — each returns empty / throws when unsupported. - var spindles = await SafeProbe(() => client.GetSpindleNamesAsync(ct), []); - var spindleMotorSpeeds = await SafeProbe(() => client.GetSpindleMotorSpeedsAsync(ct), []); - var servoLoads = await SafeProbe(() => client.GetServoLoadsAsync(ct), []); - var programInfo = await SafeTryProbe(() => client.GetProgramInfoAsync(ct)); - var timer = await SafeTryProbe(() => client.GetTimerAsync(FocasTimerKind.PowerOn, ct)); - var statusProbe = await SafeTryProbe(() => client.GetStatusAsync(ct)); - var spindleLoad = await SafeProbe(() => client.GetSpindleLoadsAsync(ct), []); + // Optional-API probes — each returns empty / throws when unsupported. A probe that fails at the + // TRANSPORT rethrows instead (#985 P-7), and so does a pass whose session died part-way: the + // capabilities are latched for the life of the device, so only a pass the CNC answered end to end + // may publish them — else one stalled cnc_rdsvmeter recorded every later capability "unsupported" + // (the timeout closed the transport, so each later probe failed "not connected" and was swallowed). + var spindles = await SafeProbe(client, () => client.GetSpindleNamesAsync(ct), []); + var spindleMotorSpeeds = await SafeProbe(client, () => client.GetSpindleMotorSpeedsAsync(ct), []); + var servoLoads = await SafeProbe(client, () => client.GetServoLoadsAsync(ct), []); + var programInfo = await SafeTryProbe(client, () => client.GetProgramInfoAsync(ct)); + var timer = await SafeTryProbe(client, () => client.GetTimerAsync(FocasTimerKind.PowerOn, ct)); + var statusProbe = await SafeTryProbe(client, () => client.GetStatusAsync(ct)); + var spindleLoad = await SafeProbe(client, () => client.GetSpindleLoadsAsync(ct), []); + if (!client.IsConnected) + throw new FocasCapabilityProbeInterruptedException( + $"FOCAS session to {state.Options.HostAddress} dropped during the fixed-tree capability probe; " + + "retrying the bootstrap rather than latching a partial capability set."); var caps = new FocasFixedTreeCapabilities( Spindles: spindles.Count > 0, @@ -1541,8 +1564,20 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, FocasDynamicSnapshot? firstAxisSnap = null; for (var i = 0; i < cache.Axes.Count; i++) { - var axisIndex = i + 1; // FOCAS uses 1-based axis indexing - var snap = await client.ReadDynamicAsync(axisIndex, ct).ConfigureAwait(false); + // The axis's WIRE slot (1-based), not its position in the blank-free name list (#985 P-9). + var axisNumber = cache.AxisNumber(i); + FocasDynamicSnapshot snap; + try { snap = await client.ReadDynamicAsync(axisNumber, ct).ConfigureAwait(false); } + catch (Exception ex) when (FocasAlarmProjection.IsCncRefusal(ex)) + { + // The CNC REFUSED this one axis (#985 P-6): the transport is fine, so it is that axis's nodes + // that have no value — BadNoData — not a silent device, and the other axes, meters, program + // and status still poll this tick. (A refusal used to abort the whole tick.) + _logger.LogDebug(ex, "FOCAS cnc_rddynamic2 refused for {Host} axis {Axis}", + state.Options.HostAddress, axisNumber); + PublishAxisNoValue(state, cache.AxisSegments[i], rates: i == 0); + continue; + } // Keyed by the disambiguated segment, matching what DiscoverAsync emitted — // two same-named axes must not share (and overwrite) one cache slot. PublishAxisSnapshot(state, cache.AxisSegments[i], snap); @@ -1694,6 +1729,21 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, ? new DataValueSnapshot(null, status == FocasStatusMapper.Good ? FocasStatusMapper.BadNoData : status, sourceUtc, now) : new DataValueSnapshot(value, status, sourceUtc, now); + /// + /// Caches (read back as BadNoData) for every position of an axis the CNC refused — + /// and, for the first axis, the feed / spindle-speed rates that ride its cnc_rddynamic2 bundle — so + /// a refused axis never keeps serving its last value as fresh Good. + /// + private static void PublishAxisNoValue(DeviceState state, string axisSegment, bool rates) + { + var host = state.Options.HostAddress; + foreach (var field in (ReadOnlySpan)["AbsolutePosition", "MachinePosition", "RelativePosition", "DistanceToGo"]) + state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/{field}")] = NoValue; + if (!rates) return; + state.LastFixedSnapshots[FixedTreeReference(host, "Axes/FeedRate/Actual")] = NoValue; + state.LastFixedSnapshots[FixedTreeReference(host, "Axes/SpindleSpeed/Actual")] = NoValue; + } + private static void PublishRateSnapshot(DeviceState state, FocasDynamicSnapshot snap) { var host = state.Options.HostAddress; @@ -1752,21 +1802,41 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, /// entire bootstrap sequence. /// private static async Task> SafeProbe( - Func>> probe, IReadOnlyList fallback) + IFocasClient client, Func>> probe, IReadOnlyList fallback) { try { return await probe().ConfigureAwait(false); } - catch { return fallback; } + catch (Exception ex) when (IsCapabilityAnswer(client, ex)) { return fallback; } } /// /// Nullable variant — probe returns a single object or null on failure. /// - private static async Task SafeTryProbe(Func> probe) where T : class + private static async Task SafeTryProbe(IFocasClient client, Func> probe) where T : class { try { return await probe().ConfigureAwait(false); } - catch { return null; } + catch (Exception ex) when (IsCapabilityAnswer(client, ex)) { return null; } } + /// + /// Whether a failed capability probe is an ANSWER about the capability (#985 P-7) — a CNC refusal (an rc), or + /// any other failure that left the session up — as opposed to a transport failure or timeout, which says + /// nothing about the capability and must not be latched as "unsupported". Those propagate, and the bootstrap + /// retries the whole pass. + /// + /// The probed client. + /// The probe's failure. + /// to record the capability as unsupported. + internal static bool IsCapabilityAnswer(IFocasClient client, Exception error) + { + if (FocasAlarmProjection.IsCncRefusal(error)) return true; + if (error is OperationCanceledException or ObjectDisposedException) return false; + if (error is Wire.FocasWireException { IsTransient: true }) return false; + return client.IsConnected; + } + + /// The session dropped mid capability probe — the bootstrap retries instead of latching a partial set. + private sealed class FocasCapabilityProbeInterruptedException(string message) : Exception(message); + /// /// Read cached last-fixed-tree snapshots. Returns the projected value when /// the reference looks like a fixed-tree FullName; null when it doesn't @@ -1857,7 +1927,8 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, "MotorSpeedPct" => state.LastSpindleMotorSpeeds, _ => null, }; - if (meters is not null && meters.TryGetValue(idx, out var pct)) + // Meters are cached by wire slot; the name list skips blank slots (#985 P-9). + if (meters is not null && meters.TryGetValue(spindleCache.SpindleMeterIndex(idx), out var pct)) return CachedDouble(pct, status, sourceUtc, now); } } @@ -2164,7 +2235,28 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, // failure path then disposed the second caller's client — two sessions to a CNC with a small handle pool, // a disposed client handed back, and a spurious backoff failure (observed live as the fixed-tree // bootstrap failing with ObjectDisposedException: FocasWireClient). - await device.ConnectGate.WaitAsync(ct).ConfigureAwait(false); + // + // A data-path / loop caller checks the backoff BEFORE queueing on the gate (#985 P-11). The probe bypasses + // the backoff and holds the gate for a full connect timeout against a black-holed host; checked only inside + // the gate, every poll of that dead device queued behind it — and ReadAsync awaits all devices, so the + // healthy CNCs' publishes stalled by the same amount. Likewise, while a connect is already in flight to a + // device whose LAST connect failed, waiting for it is not worth the stall: fail fast instead. + if (!bypassBackoff) + { + if (!device.Backoff.ShouldAttempt(DateTime.UtcNow)) + throw new ConnectionThrottledException( + $"FOCAS connect to {device.Options.HostAddress} throttled — backoff window open after a recent connect failure."); + if (device.LastConnectFailed) + { + if (!await device.ConnectGate.WaitAsync(0, ct).ConfigureAwait(false)) + throw new ConnectionThrottledException( + $"FOCAS connect to {device.Options.HostAddress} throttled — a reconnect to the unreachable device is already in flight."); + } + else + await device.ConnectGate.WaitAsync(ct).ConfigureAwait(false); + } + else + await device.ConnectGate.WaitAsync(ct).ConfigureAwait(false); try { // A released device (re-initialise / shutdown) is never reconnected: whoever still holds it read @@ -2211,10 +2303,14 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, // The caller's OWN cancellation says nothing about the CNC: do not open the backoff window, or // every caller queued on ConnectGate behind it would be throttled for ~1 s for nothing. if (!(ex is OperationCanceledException && ct.IsCancellationRequested)) + { device.Backoff.RecordFailure(DateTime.UtcNow); // open the backoff window + device.LastConnectFailed = true; + } throw; } device.Backoff.RecordSuccess(); // recovery resets the window immediately + device.LastConnectFailed = false; // Retired WHILE this connect ran (the release waits on this gate only up to its bound): the connect // is ours to undo, or it leaves a live session on a shut-down driver. if (device.IsRetired) @@ -2246,6 +2342,24 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, IReadOnlyList Spindles, FocasFixedTreeCapabilities Capabilities) { + /// + /// The 1-based axis number cnc_rddynamic2 addresses the -th named axis by: its + /// wire slot (#985 P-9). The position in is only the fallback for a client that reports + /// no slot — a blank name slot mid-list used to shift every later axis onto its neighbour's number, so its + /// nodes published ANOTHER axis's positions at Good. + /// + /// The axis's position in . + /// The axis number to request. + public int AxisNumber(int i) => Axes[i].Slot > 0 ? Axes[i].Slot : i + 1; + + /// + /// The 0-based cnc_rdspmeter record index of the -th named spindle: its wire slot + /// (#985 P-9) — the meters are a slot-ordered buffer, so a blank name slot must not shift the lookup. + /// + /// The spindle's position in . + /// The meter-record index. + public int SpindleMeterIndex(int i) => Spindles[i].Slot > 0 ? Spindles[i].Slot - 1 : i; + /// /// Unique Axes/{segment} path segments, one per axis in slot order — bare /// display names when unique, occurrence-suffixed (AA_1, AA_2) when a @@ -2301,10 +2415,23 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, /// backoff window instead of paying a full two-socket reconnect on every tick of each of /// the read / write / probe / fixed-tree / recycle loops; the probe loop bypasses it and a /// successful connect resets it. The connect itself is serialized by - /// ; the backoff is consulted inside it. + /// ; the backoff is consulted before it (so a dead device never queues callers behind an in-flight probe connect, #985 P-11) and again inside it. /// public ConnectionBackoff Backoff { get; } = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30)); + private volatile bool _lastConnectFailed; + + /// + /// Whether the device's most recent connect attempt failed (cleared by the next success). A data-path + /// caller that finds a connect already in flight to such a device fails fast instead of queueing on + /// for the connect timeout (#985 P-11). + /// + public bool LastConnectFailed + { + get => _lastConnectFailed; + set => _lastConnectFailed = value; + } + /// /// Serializes EnsureConnectedAsync per device, so concurrent loops (alarm poll, fixed tree, data /// path) share ONE connect instead of racing two sessions and disposing each other's client. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/IFocasClient.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/IFocasClient.cs index 1738b3632..8229e843d 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/IFocasClient.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/IFocasClient.cs @@ -278,7 +278,14 @@ public sealed record FocasSysInfo( int AxesCount); /// One configured axis name (e.g. "X", "X1"). -public sealed record FocasAxisName(string Name, string Suffix) +/// The axis letter. +/// The multi-channel suffix. +/// +/// The 1-based wire slot the CNC reported the name in — the axis number cnc_rddynamic2 addresses it by +/// (#985 P-9: a blank name slot mid-list used to shift every later axis onto its neighbour's number). 0 = +/// unknown (a client that does not report slots), which falls back to the axis's position in the list. +/// +public sealed record FocasAxisName(string Name, string Suffix, int Slot = 0) { /// /// Display name — name + suffix concatenated, trimmed. Empty suffix yields @@ -288,7 +295,15 @@ public sealed record FocasAxisName(string Name, string Suffix) } /// One configured spindle name (e.g. "S1"). -public sealed record FocasSpindleName(string Name, string Suffix1, string Suffix2, string Suffix3) +/// The spindle letter. +/// First suffix character. +/// Second suffix character. +/// Third suffix character. +/// +/// The 1-based wire slot the CNC reported the name in — the slot its cnc_rdspmeter records sit in +/// (#985 P-9). 0 = unknown, which falls back to the spindle's position in the list. +/// +public sealed record FocasSpindleName(string Name, string Suffix1, string Suffix2, string Suffix3, int Slot = 0) { /// Gets the display name — name + concatenated suffixes, trimmed. public string Display diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs index fd76bf660..ad59440e3 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs @@ -22,8 +22,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Wire; /// — socket 2 is guarded by a so at most one /// request/response pair is in flight at a time. /// and share a second semaphore to stop the two racing. -/// Transient failures. When cancellation or a socket-level error happens -/// mid-request the client closes both sockets and throws +/// Transient failures. When cancellation, a socket-level error or a protocol +/// fault (bad magic / version, unexpected PDU, malformed blocks, a reply whose command ids do +/// not match the request — #985 P-10) happens mid-request the client closes both sockets and throws /// with /// set — the caller must reconnect before issuing the next request. The transport is /// left deliberately torn down rather than half-open so a truncated response never @@ -130,7 +131,11 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable // Cache the sysinfo payload from the setup exchange so later // ReadSysInfoAsync calls are a lookup rather than a wire hit. var sysInfoBlock = await SendSingleRequestAsync(timeout.Token, new RequestBlock(0x0018, PathId: PathId)).ConfigureAwait(false); - _sysInfo = ToResult(sysInfoBlock, ParseSysInfo); + // Only an ANSWER is cached (#985 P-25): a refused setup sysinfo used to be cached for the life of the + // session, so every later cnc_sysinfo — and with it the fixed-tree bootstrap — failed from the cache + // while other tags kept the session alive. A refusal now falls through to a real read next time. + var sysInfo = ToResult(sysInfoBlock, ParseSysInfo); + _sysInfo = sysInfo.IsOk ? sysInfo : null; // Kick the cached path/session metadata request the DLL sends // right after initiate. The result is ignored; the CNC uses it to // populate internal state the subsequent reads depend on. @@ -141,6 +146,13 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable CloseTransport(); throw new FocasWireException("FOCAS wire connect failed.", ex, isTransient: true); } + catch + { + // A protocol fault mid-handshake (bad magic, unexpected PDU, malformed setup reply) must not leave + // half-open sockets — or _connected = true — behind the exception (#985 P-10). + CloseTransport(); + throw; + } } finally { @@ -148,6 +160,14 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable } } + /// + /// Upper bound on the close handshake a dispose runs (#985 P-8). The close PDU is a courtesy to the CNC's + /// handle pool; a control that lost power, or hung while TCP still ACKs, never answers it, and the unbounded + /// read there blocked shutdown, re-initialise and the handle recycle (which holds the device's connect gate) + /// until TCP gave up — minutes, or forever for an application-level hang. + /// + internal static readonly TimeSpan CloseHandshakeTimeout = TimeSpan.FromSeconds(1); + /// /// Synchronous dispose — sends the close PDU when connected and tears down both /// sockets. Idempotent. Callers on an async context should prefer @@ -161,17 +181,30 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable if (_disposed) return; _disposed = true; - if (_stream2 is not null && _connected) + // The close exchange runs under the REQUEST gate, so it can never interleave with a request still in + // flight on the same stream, and only for a bounded time (#985 P-8). A request that holds the gate past + // the bound gets no close PDU: the transport is torn down under it, which fails it as a transient. + if (_stream2 is not null && _connected && _requestGate.Wait(CloseHandshakeTimeout)) { try { - SendPdu(_stream2, FocasWireProtocol.TypeClose, ReadOnlySpan.Empty); - _ = FocasWireProtocol.ReadPdu(_stream2); + if (_stream2 is { } stream && _connected && _socket2 is { } socket) + { + var ms = (int)CloseHandshakeTimeout.TotalMilliseconds; + socket.SendTimeout = ms; + socket.ReceiveTimeout = ms; + SendPdu(stream, FocasWireProtocol.TypeClose, ReadOnlySpan.Empty); + _ = FocasWireProtocol.ReadPdu(stream); + } } catch { // Close best-effort — don't let teardown failure hide a caller's real error. } + finally + { + _requestGate.Release(); + } } CloseTransport(); } @@ -194,17 +227,28 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable if (_disposed) return; _disposed = true; - if (_stream2 is not null && _connected) + // Bounded and under the request gate — see Dispose (#985 P-8). + if (_stream2 is not null && _connected + && await _requestGate.WaitAsync(CloseHandshakeTimeout).ConfigureAwait(false)) { try { - await SendPduAsync(_stream2, FocasWireProtocol.TypeClose, ReadOnlyMemory.Empty, CancellationToken.None).ConfigureAwait(false); - await FocasWireProtocol.ReadPduAsync(_stream2, CancellationToken.None).ConfigureAwait(false); + if (_stream2 is { } stream && _connected) + { + // ReadPduAsync disposes the stream when this token fires, so a silent peer cannot hold it. + using var bound = new CancellationTokenSource(CloseHandshakeTimeout); + await SendPduAsync(stream, FocasWireProtocol.TypeClose, ReadOnlyMemory.Empty, bound.Token).ConfigureAwait(false); + await FocasWireProtocol.ReadPduAsync(stream, bound.Token).ConfigureAwait(false); + } } catch { // Close best-effort — don't let teardown failure hide a caller's real error. } + finally + { + _requestGate.Release(); + } } CloseTransport(); } @@ -520,7 +564,7 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable if (!result.IsOk || result.Value is null) return new FocasResult(result.Rc, null); return new FocasResult( result.Rc, - new WireParameter(dataNumber, type, result.Value.Length >= 4 ? ReadInt32(result.Value, 0) : 0)); + new WireParameter(dataNumber, type, ReadInt32(RequireParameterLength(result.Value, 4), 0))); } /// Typed 8-bit parameter read. @@ -535,7 +579,7 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable var result = await ReadParameterBytesAsync(dataNumber, axis, cancellationToken, timeout, pathId).ConfigureAwait(false); return !result.IsOk || result.Value is null ? new FocasResult(result.Rc, default) - : new FocasResult(result.Rc, result.Value.Length >= 1 ? result.Value[0] : default); + : new FocasResult(result.Rc, RequireParameterLength(result.Value, 1)[0]); } /// Typed 16-bit parameter read. @@ -550,7 +594,7 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable var result = await ReadParameterBytesAsync(dataNumber, axis, cancellationToken, timeout, pathId).ConfigureAwait(false); return !result.IsOk || result.Value is null ? new FocasResult(result.Rc, default) - : new FocasResult(result.Rc, result.Value.Length >= 2 ? ReadInt16(result.Value, 0) : default); + : new FocasResult(result.Rc, ReadInt16(RequireParameterLength(result.Value, 2), 0)); } /// Typed 32-bit parameter read. @@ -565,7 +609,7 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable var result = await ReadParameterBytesAsync(dataNumber, axis, cancellationToken, timeout, pathId).ConfigureAwait(false); return !result.IsOk || result.Value is null ? new FocasResult(result.Rc, default) - : new FocasResult(result.Rc, result.Value.Length >= 4 ? ReadInt32(result.Value, 0) : default); + : new FocasResult(result.Rc, ReadInt32(RequireParameterLength(result.Value, 4), 0)); } /// Typed IEEE-754 single-precision parameter read. @@ -578,9 +622,9 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable public async Task> ReadParameterFloat32Async(int dataNumber, short axis = 0, CancellationToken cancellationToken = default, TimeSpan? timeout = null, ushort? pathId = null) { var result = await ReadParameterBytesAsync(dataNumber, axis, cancellationToken, timeout, pathId).ConfigureAwait(false); - return !result.IsOk || result.Value is null || result.Value.Length < 4 + return !result.IsOk || result.Value is null ? new FocasResult(result.Rc, default) - : new FocasResult(result.Rc, BitConverter.Int32BitsToSingle(ReadInt32(result.Value, 0))); + : new FocasResult(result.Rc, BitConverter.Int32BitsToSingle(ReadInt32(RequireParameterLength(result.Value, 4), 0))); } /// Typed IEEE-754 double-precision parameter read. @@ -593,9 +637,9 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable public async Task> ReadParameterFloat64Async(int dataNumber, short axis = 0, CancellationToken cancellationToken = default, TimeSpan? timeout = null, ushort? pathId = null) { var result = await ReadParameterBytesAsync(dataNumber, axis, cancellationToken, timeout, pathId).ConfigureAwait(false); - return !result.IsOk || result.Value is null || result.Value.Length < 8 + return !result.IsOk || result.Value is null ? new FocasResult(result.Rc, default) - : new FocasResult(result.Rc, BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(result.Value.AsSpan(0, 8)))); + : new FocasResult(result.Rc, BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(RequireParameterLength(result.Value, 8).AsSpan(0, 8)))); } /// Read a single macro variable via cnc_rdmacro (command 0x0015). @@ -878,15 +922,22 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable var responseBlocks = FocasWireProtocol.ParseResponseBlocks(response.Body); foreach (var block in responseBlocks) _logger?.LogDebug("FOCAS response command=0x{Command:x4} rc={Rc} payloadLength={PayloadLength}", block.Command, block.Rc, block.Payload.Length); + VerifyResponseMatchesRequest(blocks, responseBlocks); return responseBlocks; } - catch (Exception ex) when (requestStarted && IsTransientException(ex)) + catch (Exception ex) when (requestStarted) { - // A cancelled or failed mid-request write leaves the wire in an undefined state — - // tear the connection down so the next caller reconnects cleanly instead of - // consuming a stale response. + // ANY failure once the request is on the wire leaves the stream in an undefined state (#985 P-10): a + // cancelled or failed write/read, but equally a bad magic or unsupported version (body left unread), an + // unexpected PDU type, a malformed block list or a reply to some other request. Tear the connection + // down so the next caller reconnects cleanly instead of consuming a stale response — matching is + // positional, so a kept session would hand request N's reply to request N+1. A CNC refusal is NOT an + // exception here (it is an rc inside a well-formed reply), so this never closes a session over one. CloseTransport(); - throw new FocasWireException("FOCAS wire request failed; connection was closed to avoid response desynchronization.", ex, isTransient: true); + var reason = IsTransientException(ex) + ? "FOCAS wire request failed" + : $"FOCAS wire protocol error ({ex.Message})"; + throw new FocasWireException($"{reason}; connection was closed to avoid response desynchronization.", ex, isTransient: true); } finally { @@ -894,6 +945,31 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable } } + /// + /// Checks a reply belongs to the request it answers (#985 P-10): never more blocks than were asked for, and + /// each block's command id equal to the request block at the same position. Every captured 31i-B reply + /// (Fixtures/v3, refused blocks included) and the focas-mock fixture echo the request's command ids in + /// request order. A SHORTER reply is tolerated exactly as before (a missing block decodes as an empty + /// payload) — refusing one is not evidence-backed, and closing a production session over it would be a + /// reconnect loop. + /// + /// The request blocks sent. + /// The reply blocks received. + /// The reply does not match the request. + internal static void VerifyResponseMatchesRequest(IReadOnlyList request, IReadOnlyList response) + { + if (response.Count > request.Count) + throw new FocasWireException( + $"FOCAS reply carries {response.Count} blocks for a {request.Count}-block request.", rc: null); + for (var i = 0; i < response.Count; i++) + { + if (response[i].Command != request[i].Command) + throw new FocasWireException( + $"FOCAS reply block {i} is command 0x{response[i].Command:x4}, but the request asked for 0x{request[i].Command:x4}.", + rc: null); + } + } + private static async Task ConnectSocketAsync(string host, int port, CancellationToken cancellationToken) { var socket = new TcpClient { NoDelay = true }; @@ -1253,7 +1329,8 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable /// /// Decode an axis-name (0x0089) or spindle-name (0x008A) payload: an array of 4-byte records, /// each named by . Blank records are skipped but - /// keep their slot's 1-based index. + /// keep their slot's 1-based index — the number the CNC addresses that axis / spindle by + /// (cnc_rddynamic2, the spindle meters), which the adapter carries through (#985 P-9). /// /// The record type the factory builds. /// The response-block payload. @@ -1272,6 +1349,16 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable return names; } + /// + /// A typed cnc_rdparam decode needs at least payload bytes (#985 P-25): a + /// shorter answer used to decode as a Good 0. Refused like the macro path refuses a short payload. + /// + private static byte[] RequireParameterLength(byte[] payload, int width) + { + RequireLength(payload, width, "cnc_rdparam"); + return payload; + } + private static void RequireLength(byte[] payload, int length, string call) { if (payload.Length < length) diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs index ec44e6e31..918a1d195 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs @@ -178,39 +178,59 @@ public sealed class WireFocasClient : IFocasClient if (!_wire.IsConnected) return []; var result = await _wire.ReadAxisNamesAsync(32, cancellationToken).ConfigureAwait(false); if (!result.IsOk || result.Value is null) return []; - return result.Value.Select(SplitAxis).Where(n => n.Name.Length > 0).ToList(); - - // FocasWireClient returns axis records as a single Name string (e.g. "X" or "X1"). - // IFocasClient wants Name + Suffix split — the first char is the axis letter, the - // rest is the multi-channel suffix. - static FocasAxisName SplitAxis(WireAxisRecord r) - { - var n = r.Name ?? string.Empty; - return n.Length == 0 - ? new FocasAxisName(string.Empty, string.Empty) - : new FocasAxisName(n[..1], n.Length > 1 ? n[1..] : string.Empty); - } + return MapAxisNames(result.Value); } + /// + /// Maps the wire's axis-name records. FocasWireClient returns each as a single Name string (e.g. "X" or + /// "X1"); IFocasClient wants Name + Suffix split — the first char is the axis letter, the rest is the + /// multi-channel suffix. The record's wire SLOT is kept (#985 P-9): it, not the position in this blank-free + /// list, is the number cnc_rddynamic2 addresses the axis by. + /// + /// The wire records (blank slots already skipped, slots preserved). + /// The named axes, in wire order. + internal static IReadOnlyList MapAxisNames(IEnumerable records) => + records + .Select(r => + { + var n = r.Name ?? string.Empty; + return n.Length == 0 + ? new FocasAxisName(string.Empty, string.Empty, r.Index) + : new FocasAxisName(n[..1], n.Length > 1 ? n[1..] : string.Empty, r.Index); + }) + .Where(n => n.Name.Length > 0) + .ToList(); + /// public async Task> GetSpindleNamesAsync(CancellationToken cancellationToken) { if (!_wire.IsConnected) return []; var result = await _wire.ReadSpindleNamesAsync(8, cancellationToken).ConfigureAwait(false); if (!result.IsOk || result.Value is null) return []; - return result.Value.Select(SplitSpindle).Where(n => n.Name.Length > 0).ToList(); - - static FocasSpindleName SplitSpindle(WireSpindleRecord r) - { - var n = r.Name ?? string.Empty; - return new FocasSpindleName( - Name: n.Length > 0 ? n[..1] : string.Empty, - Suffix1: n.Length > 1 ? n[1..2] : string.Empty, - Suffix2: n.Length > 2 ? n[2..3] : string.Empty, - Suffix3: n.Length > 3 ? n[3..4] : string.Empty); - } + return MapSpindleNames(result.Value); } + /// + /// Maps the wire's spindle-name records, keeping each one's wire SLOT (#985 P-9) — the slot its + /// cnc_rdspmeter records sit in. + /// + /// The wire records (blank slots already skipped, slots preserved). + /// The named spindles, in wire order. + internal static IReadOnlyList MapSpindleNames(IEnumerable records) => + records + .Select(r => + { + var n = r.Name ?? string.Empty; + return new FocasSpindleName( + Name: n.Length > 0 ? n[..1] : string.Empty, + Suffix1: n.Length > 1 ? n[1..2] : string.Empty, + Suffix2: n.Length > 2 ? n[2..3] : string.Empty, + Suffix3: n.Length > 3 ? n[3..4] : string.Empty, + Slot: r.Index); + }) + .Where(n => n.Name.Length > 0) + .ToList(); + /// public async Task ReadDynamicAsync(int axisIndex, CancellationToken cancellationToken) { @@ -256,9 +276,10 @@ public sealed class WireFocasClient : IFocasClient // throw when neither the program-name nor the op-mode read succeeded — otherwise // SafeTryProbe records a false-positive capability and the driver emits Program/ // OperationMode/ subtrees that only ever return BadDeviceFailure. + // Thrown as a REFUSAL carrying the rc (#985 P-6): both reads came back over a working transport. if (!nameResult.IsOk && !modeResult.IsOk) - throw new InvalidOperationException( - $"cnc_exeprgname2 failed EW_{nameResult.Rc} and cnc_rdopmode failed EW_{modeResult.Rc}."); + throw new FocasWireException( + $"cnc_exeprgname2 failed EW_{nameResult.Rc} and cnc_rdopmode failed EW_{modeResult.Rc}.", nameResult.Rc); return MapProgramInfo(nameResult, blkResult, modeResult); } @@ -391,28 +412,10 @@ public sealed class WireFocasClient : IFocasClient { try { - switch (type) - { - case FocasDataType.Byte: - var b = await _wire.ReadParameterByteAsync(address.Number, 0, cancellationToken).ConfigureAwait(false); - return b.IsOk ? ((object)(sbyte)b.Value, FocasStatusMapper.Good) : (null, FocasStatusMapper.MapFocasReturn(b.Rc)); - case FocasDataType.Int16: - var s = await _wire.ReadParameterInt16Async(address.Number, 0, cancellationToken).ConfigureAwait(false); - return s.IsOk ? ((object)s.Value, FocasStatusMapper.Good) : (null, FocasStatusMapper.MapFocasReturn(s.Rc)); - case FocasDataType.Float32: - var f = await _wire.ReadParameterFloat32Async(address.Number, 0, cancellationToken).ConfigureAwait(false); - return f.IsOk ? ((object)f.Value, FocasStatusMapper.Good) : (null, FocasStatusMapper.MapFocasReturn(f.Rc)); - case FocasDataType.Float64: - var d = await _wire.ReadParameterFloat64Async(address.Number, 0, cancellationToken).ConfigureAwait(false); - return d.IsOk ? ((object)d.Value, FocasStatusMapper.Good) : (null, FocasStatusMapper.MapFocasReturn(d.Rc)); - case FocasDataType.Bit when address.BitIndex is int bit: - var bi = await _wire.ReadParameterInt32Async(address.Number, 0, cancellationToken).ConfigureAwait(false); - if (!bi.IsOk) return (null, FocasStatusMapper.MapFocasReturn(bi.Rc)); - return ((object)((bi.Value >> bit & 1) != 0), FocasStatusMapper.Good); - default: - var i = await _wire.ReadParameterInt32Async(address.Number, 0, cancellationToken).ConfigureAwait(false); - return i.IsOk ? ((object)i.Value, FocasStatusMapper.Good) : (null, FocasStatusMapper.MapFocasReturn(i.Rc)); - } + var result = await _wire.ReadParameterBytesAsync(address.Number, 0, cancellationToken).ConfigureAwait(false); + if (!result.IsOk || result.Value is null) + return (null, FocasStatusMapper.MapFocasReturn(result.Rc)); + return DecodeParameter(result.Value, type, address.BitIndex); } catch (FocasWireException ex) { @@ -420,6 +423,43 @@ public sealed class WireFocasClient : IFocasClient } } + /// + /// Decode an answered cnc_rdparam payload as the tag's declared type (Byte = 1 byte, Int16 = 2, + /// Int32 / Bit = 4, Float32 = 4, Float64 = 8; big-endian, offset 0 — unchanged). + /// + /// + /// A payload SHORTER than the declared width is (#985 P-25): + /// it used to decode as a Good 0, indistinguishable from a real zero. The CNC answered over a working + /// transport, so it is a per-tag refusal — no health impact — never a comms status. (No successful + /// cnc_rdparam capture exists yet, so the layout itself is still unvalidated; see docs/drivers/FOCAS.md.) + /// + /// The answered payload. + /// The tag's declared type. + /// The bit of a tag, if any. + /// The value and its status. + internal static (object? value, uint status) DecodeParameter(byte[] payload, FocasDataType type, int? bitIndex) + { + var width = type switch + { + FocasDataType.Byte => 1, + FocasDataType.Int16 => 2, + FocasDataType.Float64 => 8, + _ => 4, + }; + if (payload.Length < width) return (null, FocasStatusMapper.BadTypeMismatch); + var span = payload.AsSpan(); + return type switch + { + FocasDataType.Byte => ((sbyte)payload[0], FocasStatusMapper.Good), + FocasDataType.Int16 => (System.Buffers.Binary.BinaryPrimitives.ReadInt16BigEndian(span), FocasStatusMapper.Good), + FocasDataType.Float32 => (BitConverter.Int32BitsToSingle(System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(span)), FocasStatusMapper.Good), + FocasDataType.Float64 => (BitConverter.Int64BitsToDouble(System.Buffers.Binary.BinaryPrimitives.ReadInt64BigEndian(span)), FocasStatusMapper.Good), + FocasDataType.Bit when bitIndex is int bit => + ((System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(span) >> bit & 1) != 0, FocasStatusMapper.Good), + _ => ((object)System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(span), FocasStatusMapper.Good), + }; + } + private async Task<(object? value, uint status)> ReadMacroAsync( FocasAddress address, FocasDataType type, CancellationToken cancellationToken) { @@ -504,9 +544,16 @@ public sealed class WireFocasClient : IFocasClient throw new InvalidOperationException("FOCAS wire session not connected."); } + /// + /// A non-OK return code is the CNC REFUSING the call over a healthy transport, so it is thrown carrying its + /// rc (#985 P-6) — exactly as does. It used to be a plain + /// , which the driver's refusal test + /// () could not recognise: a fixed-tree control that refused + /// cnc_rddynamic2 looked silent, degraded the driver and reconnect-looped under the #527 watchdog. + /// private static void ThrowIfRcNonZero(short rc, string call, bool isOk) { - if (!isOk) throw new InvalidOperationException($"{call} failed EW_{rc}."); + if (!isOk) throw new FocasWireException($"{call} failed EW_{rc}.", rc); } } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FakeFocasClient.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FakeFocasClient.cs index 370bff156..18071fef6 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FakeFocasClient.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FakeFocasClient.cs @@ -5,7 +5,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests; internal class FakeFocasClient : IFocasClient { /// Gets a value indicating whether the client is connected. - public bool IsConnected { get; private set; } + public bool IsConnected { get; protected set; } /// Gets the count of connection attempts. public int ConnectCount { get; private set; } /// Gets the count of dispose operations. diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasAlarmProjectionTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasAlarmProjectionTests.cs index 0749aafca..c3b2e7f9e 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasAlarmProjectionTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasAlarmProjectionTests.cs @@ -573,6 +573,71 @@ public sealed class FocasAlarmProjectionTests (await FirstRaiseMessage(Overtravel506, Servo401(axis: 1))).ShouldNotBe(a, "a different set must not read as a re-statement"); } + // ---- #985 P-20: a list cut off at the per-read cap ---------------------------------------------------------- + + /// A full (cap-sized, hence possibly truncated) list of overheat alarms — none of them servo. + private static FocasActiveAlarm[] StormWithout401() => + [.. Enumerable.Range(0, Wire.WireFocasClient.MaxAlarmsPerRead) + .Select(i => new FocasActiveAlarm(1000 + i, FocasAlarmType.Overheat, 0, $"OVERHEAT {i}"))]; + + /// + /// The finding's repro: an alarm storm reaches the 32-entry cap and an active ALARM:Servo/401 falls past + /// it. The condition used to CLEAR — and when the list shrank it was raised again un-acknowledged (a Clear plus + /// an Activated /alerts row for an alarm that never went away). + /// + [Fact] + public async Task A_truncated_list_does_not_clear_an_active_condition_nor_re_raise_it_after() + { + var (drv, factory) = NewDriver(Tag(ServoPath, "ALARM:Servo/401")); + await InitAndSubscribeForTicksAsync(drv, factory, ServoPath); + var events = Capture(drv, transitionsOnly: true); + + Tick(drv, Servo401()); + events.Select(e => e.Kind).ShouldBe([AlarmTransitionKind.Raise]); + + Tick(drv, StormWithout401()); + events.Count.ShouldBe(1, "401 may only be past the cap — a truncated list cannot clear it"); + + Tick(drv, Servo401(), Overheat700, Overtravel506); + events.Count.ShouldBe(1, "its reappearance after the storm is not a new statement — no Raise / Retrigger"); + + // Positive control: a COMPLETE list without 401 does clear it. + Tick(drv, Overheat700); + events.Select(e => e.Kind).ShouldBe([AlarmTransitionKind.Raise, AlarmTransitionKind.Clear]); + } + + /// + /// Same rule for a condition with several members: the displayed alarm falling past the cap is no new + /// statement (no Retrigger), while a genuinely NEW alarm on a truncated list still retriggers — and the told + /// members it no longer sees are kept, so their return is not "new" either. + /// + [Fact] + public async Task A_truncated_list_only_retriggers_for_a_genuinely_new_alarm() + { + var (drv, factory) = NewDriver(Tag(ServoPath, "ALARM:Servo")); + await InitAndSubscribeForTicksAsync(drv, factory, ServoPath); + var events = Capture(drv, transitionsOnly: true); + var servo402 = new FocasActiveAlarm(402, FocasAlarmType.Servo, 2, "SERVO 402"); + var servo403 = new FocasActiveAlarm(403, FocasAlarmType.Servo, 3, "SERVO 403"); + + Tick(drv, Servo401(), servo402); + events.Select(e => e.Kind).ShouldBe([AlarmTransitionKind.Raise]); + + // Truncated: 401 (the displayed one) fell past the cap, 402 is still seen — nothing new. + Tick(drv, [servo402, .. StormWithout401().Take(Wire.WireFocasClient.MaxAlarmsPerRead - 1)]); + events.Count.ShouldBe(1, "the displayed alarm merely fell past the cap"); + Tick(drv, Servo401(), servo402); + events.Count.ShouldBe(1, "and its return is not a new statement"); + + // Truncated with a NEW servo alarm (402 past the cap): a real new statement. + Tick(drv, [Servo401(), servo403, .. StormWithout401().Take(Wire.WireFocasClient.MaxAlarmsPerRead - 2)]); + events.Select(e => e.Kind).ShouldBe([AlarmTransitionKind.Raise, AlarmTransitionKind.Retrigger]); + + // The storm ends with all three present: 402 was kept in the told set, so nothing is new. + Tick(drv, Servo401(), servo402, servo403); + events.Count.ShouldBe(2, "a member the truncated list could not see is not new when it reappears"); + } + private static Wire.FocasWireException CncRefusal() => new("cnc_rdalmmsg2 refused EW_FUNC", rc: 1); /// diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasPmcCoalescingDriverTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasPmcCoalescingDriverTests.cs index 8c1219d7b..fa0d5c8e0 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasPmcCoalescingDriverTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasPmcCoalescingDriverTests.cs @@ -133,11 +133,12 @@ public sealed class FocasPmcCoalescingDriverTests } [Fact] - public async Task A_refusal_with_an_unmapped_rc_that_maps_to_BadCommunicationError_still_falls_back_per_tag() + public async Task A_refusal_with_an_unmapped_rc_that_maps_to_BadCommunicationError_falls_back_per_tag_without_latching() { var (drv, c) = await StartAsync(null, Tag("A", "R100", FocasDataType.Byte), Tag("B", "R101", FocasDataType.Byte)); - c.PmcRangeRejectors.Add((_, _, _) => true); + var refuse = true; + c.PmcRangeRejectors.Add((_, _, _) => refuse); c.PmcRangeRejectStatus = FocasStatusMapper.BadCommunicationError; // what an unlisted rc / EW_PARITY / EW_SOCKET maps to c.Values["R100"] = (sbyte)1; c.Values["R101"] = (sbyte)2; @@ -145,11 +146,28 @@ public sealed class FocasPmcCoalescingDriverTests r.Select(s => s.Value).ShouldBe([(object)(sbyte)1, (sbyte)2]); r.ShouldAllBe(s => s.StatusCode == FocasStatusMapper.Good); + // #985 P-21: a link-shaped code says nothing about the range, so it must not disable coalescing for the + // device's lifetime — it used to be memoised ("deterministic") after one blip. + refuse = false; await drv.ReadAsync(["A", "B"], CancellationToken.None); - c.PmcRangeReads.Count.ShouldBe(1, "a deterministic rc refusal is memoised"); + c.PmcRangeReads.Count.ShouldBe(2, "a link-shaped refusal is not latched — the merged range is tried again"); + await drv.ReadAsync(["A", "B"], CancellationToken.None); + c.PmcRangeReads.Count.ShouldBe(3, "and coalescing keeps working once the blip is over"); await drv.ShutdownAsync(CancellationToken.None); } + [Theory] + [InlineData(FocasStatusMapper.BadCommunicationError, false)] // EW_SOCKET / EW_UNEXP / EW_PARITY / unknown + [InlineData(FocasStatusMapper.BadInternalError, false)] // EW_HANDLE + [InlineData(FocasStatusMapper.BadDeviceFailure, false)] // EW_BUSY + [InlineData(FocasStatusMapper.BadNotWritable, false)] // EW_PROT / EW_PASSWD — not a range property + [InlineData(FocasStatusMapper.BadOutOfRange, true)] // EW_NUMBER / EW_LENGTH / EW_OVRFLOW + [InlineData(FocasStatusMapper.BadNodeIdUnknown, true)] // EW_DATA + [InlineData(FocasStatusMapper.BadTypeMismatch, true)] // EW_ATTRIB + [InlineData(FocasStatusMapper.BadNotSupported, true)] // EW_FUNC / EW_NOOPT + public void Only_range_shaped_refusals_latch_a_merged_range(uint status, bool latches) => + FocasDriver.IsRangeShapedRefusal(status).ShouldBe(latches); + [Fact] public async Task A_transient_busy_refusal_is_not_memoised() { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasRefusalAndIsolationTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasRefusalAndIsolationTests.cs new file mode 100644 index 000000000..6612c364b --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasRefusalAndIsolationTests.cs @@ -0,0 +1,489 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Wire; + +namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests; + +/// +/// #985 — the FOCAS driver's health contract and device isolation: a CNC refusal of the fixed tree leaves the +/// driver Healthy while a real outage degrades it (P-6), a transient failure during the capability bootstrap is +/// not latched as "unsupported" (P-7), axes and spindles are addressed by their wire slot (P-9), a dead CNC does +/// not stall other devices' reads (P-11), and a handle recycle against a CNC that never answers the close PDU +/// completes instead of holding the connect gate forever (P-8). +/// +[Trait("Category", "Unit")] +public sealed class FocasRefusalAndIsolationTests +{ + private static readonly TimeSpan Stale = TimeSpan.FromMilliseconds(400); + + // ---- P-6 end to end: the real wire client against a CNC that refuses cnc_rddynamic2 ---- + + /// Two axis-name records, X and Y. + private static byte[] AxisNamesXY() => [0x58, 0, 0, 0, 0x59, 0, 0, 0]; + + private static FocasDriver FixedOnlyWireDriver(MockFocasWireServer srv) => new(new FocasDriverOptions + { + Devices = [new FocasDeviceOptions(srv.HostAddress)], + RawTags = [FocasRawTags.Entry(new FocasTagDefinition("raw/X", srv.HostAddress, "FIXED:Axes/X/AbsolutePosition", FocasDataType.Float64))], + Probe = new FocasProbeOptions { Enabled = false }, + Timeout = TimeSpan.FromSeconds(2), + FixedTree = new FocasFixedTreeOptions + { + PollInterval = TimeSpan.FromMilliseconds(20), + ProgramPollInterval = TimeSpan.Zero, + TimerPollInterval = TimeSpan.Zero, + }, + }, "focas-985-p6", new WireFocasClientFactory()) + { + FixedTreeStaleBudgetOverride = Stale, + }; + + /// + /// The finding's repro on the REAL wire client: a fixed-only driver on a control that answers every + /// cnc_rddynamic2 with EW_FUNC. The adapter used to throw a plain InvalidOperationException, so + /// the refusal read as silence and the driver degraded past the stale budget (then the #527 watchdog + /// reconnect-looped it). Now it stays Healthy with LastSuccessfulRead advancing, the refused axis reads + /// BadNoData — and (positive control) the same driver DOES degrade once the CNC really goes away. + /// + [Fact] + public async Task A_cnc_refusing_the_dynamic_read_stays_Healthy_but_a_real_outage_degrades() + { + await using var srv = new MockFocasWireServer(); + srv.Responder = r => r.Command switch + { + 0x0089 => (0, AxisNamesXY()), + 0x001a or 0x001c or 0x001d or 0x0024 or 0x0025 or 0x0026 => (1, []), // EW_FUNC + _ => MockFocasWireServer.DefaultResponder(r), + }; + await using var drv = FixedOnlyWireDriver(srv); + await drv.InitializeAsync("{}", CancellationToken.None); + await WaitUntil(() => drv.GetDeviceState(srv.HostAddress)?.FixedTreeCache is not null); + + var started = DateTime.UtcNow; + var first = drv.GetHealth().LastSuccessfulRead!.Value; + // Refused ticks for well past the staleness budget … + await WaitUntil(() => DateTime.UtcNow - started > Stale * 3 + && srv.CountOf(0x001a) >= 10); + // … and the driver is still Healthy, crediting each answer. + drv.GetHealth().State.ShouldBe(DriverState.Healthy); + drv.GetHealth().LastSuccessfulRead!.Value.ShouldBeGreaterThan(first); + var read = await drv.ReadAsync(["raw/X"], CancellationToken.None); + read[0].StatusCode.ShouldBe(FocasStatusMapper.BadNoData, "a refused axis has no value — never a stale Good"); + + // Positive control: the CNC goes away for real → Degraded with LastSuccessfulRead frozen. + srv.Stop(); + await WaitUntil(() => drv.GetHealth().State == DriverState.Degraded, TimeSpan.FromSeconds(10)); + } + + // ---- P-6: one refused axis does not abort the tick ---- + + private sealed class RefuseAxisCnc(int refusedAxis) : FakeFocasClient + { + public override Task ReadDynamicAsync(int axisIndex, CancellationToken ct) => + axisIndex == refusedAxis + ? throw new FocasWireException("cnc_rddynamic2 failed EW_4.", rc: 4) + : base.ReadDynamicAsync(axisIndex, ct); + } + + [Fact] + public async Task One_refused_axis_reads_BadNoData_while_the_others_keep_polling() + { + const string host = "focas://10.0.0.5:8193"; + var factory = new FakeFocasClientFactory + { + Customise = () => + { + var c = new RefuseAxisCnc(refusedAxis: 2); + c.DynamicByAxis[1] = new FocasDynamicSnapshot(1, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0); + c.DynamicByAxis[3] = new FocasDynamicSnapshot(3, 0, 0, 0, 0, 0, 0, 300, 0, 0, 0); + return c; + }, + }; + await using var drv = new FocasDriver(new FocasDriverOptions + { + Devices = [new FocasDeviceOptions(host)], + RawTags = FocasRawTags.Entries([ + new FocasTagDefinition("x", host, "FIXED:Axes/X/AbsolutePosition", FocasDataType.Float64), + new FocasTagDefinition("y", host, "FIXED:Axes/Y/AbsolutePosition", FocasDataType.Float64), + new FocasTagDefinition("z", host, "FIXED:Axes/Z/AbsolutePosition", FocasDataType.Float64), + ]), + Probe = new FocasProbeOptions { Enabled = false }, + FixedTree = new FocasFixedTreeOptions + { + PollInterval = TimeSpan.FromMilliseconds(20), ProgramPollInterval = TimeSpan.Zero, TimerPollInterval = TimeSpan.Zero, + }, + }, "focas-985-axis", factory); + await drv.InitializeAsync("{}", CancellationToken.None); + await WaitUntil(() => drv.GetDeviceState(host)?.LastFixedPollUtc is not null + && drv.GetDeviceState(host)!.LastFixedSnapshots.Count >= 12); + + var r = await drv.ReadAsync(["x", "y", "z"], CancellationToken.None); + r[0].Value.ShouldBe(100.0); + r[1].StatusCode.ShouldBe(FocasStatusMapper.BadNoData); + r[2].Value.ShouldBe(300.0, "the axis after a refused one still polls (a refusal used to abort the tick)"); + drv.GetHealth().State.ShouldBe(DriverState.Healthy); + } + + // ---- P-7: a transient failure during the capability bootstrap is not latched ---- + + private sealed class Shared + { + public int ServoCalls; + public bool RefuseStatus; + /// Bootstrap passes started (only the bootstrap reads sysinfo). + public int BootstrapPasses; + } + + /// + /// A CNC whose cnc_rdsvmeter stalls once at bootstrap: the timeout closes the session (IsConnected + /// false), and every later capability probe then fails the way the wire adapter does when disconnected — + /// empty lists and "not connected" throws. + /// + private sealed class FlakyBootstrapCnc : FakeFocasClient + { + private readonly Shared _shared; + + public FlakyBootstrapCnc(Shared shared) + { + _shared = shared; + ServoLoads.Add(new FocasServoLoad("X", 12.5)); + SpindleLoads.Add(40.0); + SpindleMotorSpeeds.Add(55.0); + } + + private InvalidOperationException NotConnected() => new("FOCAS wire session not connected."); + + public override Task GetSysInfoAsync(CancellationToken ct) + { + Interlocked.Increment(ref _shared.BootstrapPasses); + return base.GetSysInfoAsync(ct); + } + + public override Task> GetServoLoadsAsync(CancellationToken ct) + { + if (Interlocked.Increment(ref _shared.ServoCalls) == 1) + { + IsConnected = false; // the stalled call's timeout tore the transport down + throw new FocasWireException("FOCAS wire request failed", new OperationCanceledException(), isTransient: true); + } + return IsConnected ? base.GetServoLoadsAsync(ct) : Task.FromResult>([]); + } + + public override Task> GetSpindleLoadsAsync(CancellationToken ct) => + IsConnected ? base.GetSpindleLoadsAsync(ct) : Task.FromResult>([]); + + public override Task GetProgramInfoAsync(CancellationToken ct) => + IsConnected ? base.GetProgramInfoAsync(ct) : throw NotConnected(); + + public override Task GetTimerAsync(FocasTimerKind kind, CancellationToken ct) => + IsConnected ? base.GetTimerAsync(kind, ct) : throw NotConnected(); + + public override Task GetStatusAsync(CancellationToken ct) + { + if (!IsConnected) throw NotConnected(); + if (_shared.RefuseStatus) throw new FocasWireException("cnc_statinfo failed EW_1.", rc: 1); + return base.GetStatusAsync(ct); + } + } + + private static FocasDriver BootstrapDriver(string host, Shared shared) => new(new FocasDriverOptions + { + Devices = [new FocasDeviceOptions(host)], + RawTags = [FocasRawTags.Entry(new FocasTagDefinition("raw/X", host, "FIXED:Axes/X/AbsolutePosition", FocasDataType.Float64))], + Probe = new FocasProbeOptions { Enabled = false }, + FixedTree = new FocasFixedTreeOptions + { + PollInterval = TimeSpan.FromMilliseconds(20), ProgramPollInterval = TimeSpan.Zero, TimerPollInterval = TimeSpan.Zero, + }, + }, "focas-985-p7", new FakeFocasClientFactory { Customise = () => new FlakyBootstrapCnc(shared) }); + + /// + /// The finding's repro: a stalled cnc_rdsvmeter at startup used to record ServoLoad, ProgramInfo, + /// Timers, Status and SpindleLoad all false for the life of the device. Now the pass is retried and the + /// capabilities the CNC really has are all published. + /// + [Fact] + public async Task A_transient_failure_mid_bootstrap_is_retried_not_latched_as_unsupported() + { + const string host = "focas://10.0.0.7:8193"; + var shared = new Shared(); + await using var drv = BootstrapDriver(host, shared); + await drv.InitializeAsync("{}", CancellationToken.None); + await WaitUntil(() => drv.GetDeviceState(host)?.FixedTreeCache is not null, TimeSpan.FromSeconds(8)); + + Volatile.Read(ref shared.BootstrapPasses).ShouldBeGreaterThanOrEqualTo(2, "the bootstrap must have retried after the transient failure"); + var caps = drv.GetDeviceState(host)!.FixedTreeCache!.Capabilities; + caps.ShouldBe(new FocasDriver.FocasFixedTreeCapabilities( + Spindles: true, SpindleLoad: true, SpindleMotorSpeed: true, ServoLoad: true, + ProgramInfo: true, Timers: true, Status: true)); + } + + /// Positive control: a REFUSAL (rc, session up) is a capability answer — latched false, no retry. + [Fact] + public async Task A_refused_capability_probe_is_latched_unsupported_on_the_first_pass() + { + const string host = "focas://10.0.0.8:8193"; + var shared = new Shared { ServoCalls = 1, RefuseStatus = true }; // no stall; cnc_statinfo refused + await using var drv = BootstrapDriver(host, shared); + await drv.InitializeAsync("{}", CancellationToken.None); + await WaitUntil(() => drv.GetDeviceState(host)?.FixedTreeCache is not null); + + var caps = drv.GetDeviceState(host)!.FixedTreeCache!.Capabilities; + caps.Status.ShouldBeFalse(); + caps.ServoLoad.ShouldBeTrue(); + caps.ProgramInfo.ShouldBeTrue(); + Volatile.Read(ref shared.BootstrapPasses).ShouldBe(1, "one pass — a refusal is not retried"); + } + + [Fact] + public async Task Capability_answer_classification() + { + var up = new FakeFocasClient(); + await up.ConnectAsync(new FocasHostAddress("h", 8193), TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken); + var down = new FakeFocasClient(); + + FocasDriver.IsCapabilityAnswer(up, new FocasWireException("refused", rc: 1)).ShouldBeTrue(); + FocasDriver.IsCapabilityAnswer(down, new FocasWireException("refused", rc: 1)).ShouldBeTrue("an rc is an answer even if the session later dropped"); + FocasDriver.IsCapabilityAnswer(up, new InvalidOperationException("cnc_statinfo refused")).ShouldBeTrue("session still up ⇒ an answer"); + FocasDriver.IsCapabilityAnswer(down, new InvalidOperationException("not connected")).ShouldBeFalse(); + FocasDriver.IsCapabilityAnswer(up, new OperationCanceledException()).ShouldBeFalse("a per-call timeout says nothing about the capability"); + FocasDriver.IsCapabilityAnswer(up, new FocasWireException("io", new IOException(), isTransient: true)).ShouldBeFalse(); + FocasDriver.IsCapabilityAnswer(up, new ObjectDisposedException("client")).ShouldBeFalse(); + } + + // ---- P-9: axis and spindle wire slots ---- + + [Fact] + public void Wire_axis_names_keep_their_slot_across_a_blank_record() + { + // Axis-name payload X, Y, , Z → Z is wire slot 4, not list position 3. + byte[] payload = [0x58, 0, 0, 0, 0x59, 0, 0, 0, 0, 0, 0, 0, 0x5a, 0, 0, 0]; + var records = FocasWireClient.ReadNameRecords(payload, 32, (i, n) => new WireAxisRecord(i, n)); + var axes = WireFocasClient.MapAxisNames(records); + axes.Select(a => (a.Display, a.Slot)).ShouldBe([("X", 1), ("Y", 2), ("Z", 4)]); + + // Spindle payload with a blank FIRST slot: S2 is wire slot 2. + byte[] spindles = [0, 0, 0, 0, 0x53, 0x32, 0, 0]; + var sp = WireFocasClient.MapSpindleNames(FocasWireClient.ReadNameRecords(spindles, 8, (i, n) => new WireSpindleRecord(i, n))); + sp.Single().Display.ShouldBe("S2"); + sp.Single().Slot.ShouldBe(2); + } + + private sealed class SlotRecordingCnc : FakeFocasClient + { + public readonly List RequestedAxes = []; + + public override Task ReadDynamicAsync(int axisIndex, CancellationToken ct) + { + lock (RequestedAxes) RequestedAxes.Add(axisIndex); + return base.ReadDynamicAsync(axisIndex, ct); + } + } + + /// + /// The finding's repro: a control reporting names in slots 1, 2 and 4. The third named axis used to be polled + /// as axis 3 — another axis's positions at Good. A spindle in wire slot 2 must read meter record 2. + /// + [Fact] + public async Task Axes_and_spindles_are_addressed_by_their_wire_slot() + { + const string host = "focas://10.0.0.9:8193"; + SlotRecordingCnc? cnc = null; + var factory = new FakeFocasClientFactory + { + Customise = () => + { + var c = new SlotRecordingCnc(); + c.AxisNames.Clear(); + c.AxisNames.AddRange([new FocasAxisName("X", "", 1), new FocasAxisName("Y", "", 2), new FocasAxisName("Z", "", 4)]); + c.DynamicByAxis[3] = new FocasDynamicSnapshot(3, 0, 0, 0, 0, 0, 0, 333, 0, 0, 0); + c.DynamicByAxis[4] = new FocasDynamicSnapshot(4, 0, 0, 0, 0, 0, 0, 444, 0, 0, 0); + c.SpindleNames.Clear(); + c.SpindleNames.Add(new FocasSpindleName("S", "2", "", "", Slot: 2)); + c.SpindleLoads.AddRange([11.0, 22.0]); // meter records are slot-ordered: slot 1, slot 2 + return cnc = c; + }, + }; + await using var drv = new FocasDriver(new FocasDriverOptions + { + Devices = [new FocasDeviceOptions(host)], + RawTags = FocasRawTags.Entries([ + new FocasTagDefinition("z", host, "FIXED:Axes/Z/AbsolutePosition", FocasDataType.Float64), + new FocasTagDefinition("s2", host, "FIXED:Spindle/S2/Load", FocasDataType.Float64), + ]), + Probe = new FocasProbeOptions { Enabled = false }, + FixedTree = new FocasFixedTreeOptions + { + PollInterval = TimeSpan.FromMilliseconds(20), ProgramPollInterval = TimeSpan.Zero, TimerPollInterval = TimeSpan.Zero, + }, + }, "focas-985-p9", factory); + await drv.InitializeAsync("{}", CancellationToken.None); + await WaitUntil(() => cnc is not null && Snapshot(cnc).Count >= 3 && drv.GetDeviceState(host)?.LastFixedPollUtc is not null); + + Snapshot(cnc!).Distinct().Order().ToArray().ShouldBe(new[] { 1, 2, 4 }, "Z is wire slot 4 — axis 3 must never be requested"); + var r = await drv.ReadAsync(["z", "s2"], CancellationToken.None); + r[0].Value.ShouldBe(444.0); + r[1].Value.ShouldBe(22.0, "spindle S2 sits in meter record 2, not 1"); + + static List Snapshot(SlotRecordingCnc c) { lock (c.RequestedAxes) return [.. c.RequestedAxes]; } + } + + [Fact] + public void A_client_without_slots_falls_back_to_list_position() + { + var cache = new FocasDriver.FocasFixedTreeCache( + new FocasSysInfo(0, 2, "M", "M", "30i", "A", 2), + [new FocasAxisName("X", ""), new FocasAxisName("Y", "")], + [new FocasSpindleName("S", "1", "", "")], + new FocasDriver.FocasFixedTreeCapabilities(true, true, true, true, true, true)); + cache.AxisNumber(1).ShouldBe(2); + cache.SpindleMeterIndex(0).ShouldBe(0); + } + + // ---- P-11: one dead CNC does not stall the others ---- + + private sealed class DeadOrAliveCnc(string deadHost, TimeSpan connectStall, Action onDeadConnect) : FakeFocasClient + { + public override async Task ConnectAsync(FocasHostAddress address, TimeSpan timeout, CancellationToken ct) + { + if (address.Host == deadHost) + { + onDeadConnect(); + await Task.Delay(connectStall, ct); // a black-holed host: the connect only times out + throw new IOException("connect timed out"); + } + await base.ConnectAsync(address, timeout, ct); + Values["R100"] = (sbyte)7; + } + } + + /// + /// The finding's repro: the probe (which bypasses the backoff) holds a dead CNC's connect gate for its whole + /// connect timeout; the data path used to queue behind it — and ReadAsync awaits every device — so the healthy + /// CNC's read stalled by the same amount. Now the dead device fails fast and the healthy one returns at once. + /// + [Fact] + public async Task A_dead_cnc_mid_probe_connect_does_not_stall_a_healthy_devices_read() + { + const string dead = "focas://10.0.0.5:8193"; + const string alive = "focas://10.0.0.6:8193"; + var deadConnects = 0; + var stall = TimeSpan.FromSeconds(3); + await using var drv = new FocasDriver(new FocasDriverOptions + { + Devices = [new FocasDeviceOptions(dead), new FocasDeviceOptions(alive)], + RawTags = FocasRawTags.Entries([ + new FocasTagDefinition("dead", dead, "R100", FocasDataType.Byte), + new FocasTagDefinition("alive", alive, "R100", FocasDataType.Byte), + ]), + Probe = new FocasProbeOptions { Enabled = true, Interval = TimeSpan.FromMilliseconds(20), Timeout = TimeSpan.FromSeconds(10) }, + Timeout = TimeSpan.FromSeconds(10), + }, "focas-985-p11", new FakeFocasClientFactory + { + Customise = () => new DeadOrAliveCnc("10.0.0.5", stall, () => Interlocked.Increment(ref deadConnects)), + }); + await drv.InitializeAsync("{}", CancellationToken.None); + + // The probe's second connect to the dead CNC is in flight (its first already failed). + await WaitUntil(() => Volatile.Read(ref deadConnects) >= 2, TimeSpan.FromSeconds(10)); + + var sw = Stopwatch.StartNew(); + var r = await drv.ReadAsync(["dead", "alive"], CancellationToken.None); + sw.Stop(); + + r[1].StatusCode.ShouldBe(FocasStatusMapper.Good); + r[1].Value.ShouldBe((sbyte)7); + r[0].StatusCode.ShouldBe(FocasStatusMapper.BadCommunicationError); + sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(1), "the healthy CNC must not wait out the dead one's connect"); + } + + /// + /// Positive control for the fast-fail: with no failure on record the data path still WAITS for an in-flight + /// connect (the hw2 Makino race fix — two loops sharing one connect — must not regress into throttling). + /// + [Fact] + public async Task A_first_connect_in_flight_is_waited_for_not_throttled() + { + const string host = "focas://10.0.0.11:8193"; + var gate = new TaskCompletionSource(); + var factory = new FakeFocasClientFactory { Customise = () => new SlowFirstConnectCnc(gate.Task) }; + await using var drv = new FocasDriver(new FocasDriverOptions + { + Devices = [new FocasDeviceOptions(host)], + RawTags = [FocasRawTags.Entry(new FocasTagDefinition("r", host, "R100", FocasDataType.Byte))], + Probe = new FocasProbeOptions { Enabled = false }, + }, "focas-985-p11b", factory); + await drv.InitializeAsync("{}", CancellationToken.None); + + var first = drv.ReadAsync(["r"], CancellationToken.None); + await WaitUntil(() => factory.Clients.Count == 1); + var second = drv.ReadAsync(["r"], CancellationToken.None); + gate.SetResult(); + (await first)[0].StatusCode.ShouldBe(FocasStatusMapper.Good); + (await second)[0].StatusCode.ShouldBe(FocasStatusMapper.Good, "the queued caller shares the connect"); + factory.Clients.Count.ShouldBe(1); + } + + private sealed class SlowFirstConnectCnc(Task release) : FakeFocasClient + { + public override async Task ConnectAsync(FocasHostAddress address, TimeSpan timeout, CancellationToken ct) + { + await release.WaitAsync(ct); + await base.ConnectAsync(address, timeout, ct); + Values["R100"] = (sbyte)1; + } + } + + // ---- P-8: a recycle against a CNC that never answers the close PDU ---- + + /// + /// The finding's repro: the hourly handle recycle disposes the session UNDER the device's connect gate, and the + /// dispose blocked forever on a close reply that never came — every later poll parked on the gate with no + /// result and no health write. Now each recycle completes within the bound and reads keep succeeding on fresh + /// sessions. + /// + [Fact] + public async Task Handle_recycle_completes_when_the_cnc_never_answers_close() + { + await using var srv = new MockFocasWireServer { AnswerClose = false }; + await using var drv = new FocasDriver(new FocasDriverOptions + { + Devices = [new FocasDeviceOptions(srv.HostAddress)], + RawTags = [FocasRawTags.Entry(new FocasTagDefinition("m", srv.HostAddress, "MACRO:500", FocasDataType.Int32))], + Probe = new FocasProbeOptions { Enabled = false }, + Timeout = TimeSpan.FromMilliseconds(500), + HandleRecycle = new FocasHandleRecycleOptions { Enabled = true, Interval = TimeSpan.FromMilliseconds(200) }, + }, "focas-985-p8", new WireFocasClientFactory()); + await drv.InitializeAsync("{}", CancellationToken.None); + + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(20); + var goodAfterSecondRecycle = false; + while (DateTime.UtcNow < deadline && !goodAfterSecondRecycle) + { + var read = drv.ReadAsync(["m"], CancellationToken.None); + (await Task.WhenAny(read, Task.Delay(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken))).ShouldBe(read, + "a read parked behind a recycle that never finished its close handshake"); + var r = await read; + if (srv.Closes >= 2 && r[0].StatusCode == FocasStatusMapper.Good) + { + r[0].Value.ShouldBe(500); + goodAfterSecondRecycle = true; + } + await Task.Delay(50, TestContext.Current.CancellationToken); + } + goodAfterSecondRecycle.ShouldBeTrue("recycles must complete and reads must succeed on the fresh sessions"); + } + + private static async Task WaitUntil(Func condition, TimeSpan? timeout = null) + { + var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(5)); + while (!condition()) + { + if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached"); + await Task.Delay(10, TestContext.Current.CancellationToken); + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasWireSessionIntegrityTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasWireSessionIntegrityTests.cs new file mode 100644 index 000000000..d14dcb3e6 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasWireSessionIntegrityTests.cs @@ -0,0 +1,306 @@ +using System.Diagnostics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Wire; + +namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests; + +/// +/// #985 — the FOCAS wire client against a scripted loopback CNC (): a protocol +/// fault mid-request closes the session instead of leaving it desynchronised (P-10), the close handshake is +/// bounded (P-8), a refused setup sysinfo is not cached (P-25), and a fixed-tree refusal is thrown as a refusal +/// carrying its rc (P-6). +/// +[Trait("Category", "Unit")] +public sealed class FocasWireSessionIntegrityTests +{ + private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(3); + + private static async Task ConnectAsync(MockFocasWireServer srv) + { + var wire = new FocasWireClient(); + await wire.ConnectAsync("127.0.0.1", srv.Port, ConnectTimeout); + return wire; + } + + // ---- P-10: protocol faults close the session; replies are matched to requests ---- + + /// + /// The finding's repro: one stray non-data PDU ahead of the real reply. Before the fix the client threw + /// "unexpected PDU type" but KEPT the session, so the next request consumed the previous request's reply — + /// macro #200 published macro #100's value at Good. + /// + [Fact] + public async Task A_stray_PDU_closes_the_session_so_the_next_read_never_gets_the_previous_reply() + { + await using var srv = new MockFocasWireServer(); + var strayOnce = 1; + srv.OnData = reqs => reqs[0].Command == 0x0015 && Interlocked.Exchange(ref strayOnce, 0) == 1 + ? [.. MockFocasWireServer.Pdu(0x02, []), .. srv.Reply(reqs)] + : srv.Reply(reqs); + var client = new WireFocasClient(); + await client.ConnectAsync(FocasHostAddress.TryParse(srv.HostAddress)!, ConnectTimeout, CancellationToken.None); + + var first = await client.ReadAsync(FocasAddress.TryParse("MACRO:100")!, FocasDataType.Int32, CancellationToken.None); + first.status.ShouldBe(FocasStatusMapper.BadCommunicationError); + client.IsConnected.ShouldBeFalse("a protocol fault mid-request must tear the session down"); + + var second = await client.ReadAsync(FocasAddress.TryParse("MACRO:200")!, FocasDataType.Int32, CancellationToken.None); + second.value.ShouldNotBe(100, "request N+1 must never be answered with request N's reply"); + second.status.ShouldBe(FocasStatusMapper.BadCommunicationError); + + // …and the next connect is a fresh session whose reads answer for themselves (positive control). + await client.ConnectAsync(FocasHostAddress.TryParse(srv.HostAddress)!, ConnectTimeout, CancellationToken.None); + var third = await client.ReadAsync(FocasAddress.TryParse("MACRO:200")!, FocasDataType.Int32, CancellationToken.None); + third.status.ShouldBe(FocasStatusMapper.Good); + third.value.ShouldBe(200); + srv.Initiates.ShouldBe(4, "two sockets per session, two sessions"); + client.Dispose(); + } + + /// A reply whose block is a DIFFERENT command than the request asked for is refused and closes the session. + [Fact] + public async Task A_reply_for_another_command_closes_the_session() + { + await using var srv = new MockFocasWireServer(); + srv.OnData = reqs => reqs[0].Command == 0x0015 + ? MockFocasWireServer.DataPdu((0x0057, 0, new byte[2])) + : srv.Reply(reqs); + using var wire = await ConnectAsync(srv); + + var ex = await Should.ThrowAsync(() => wire.ReadMacroAsync(100, TestContext.Current.CancellationToken)); + ex.IsTransient.ShouldBeTrue(); + ex.Message.ShouldContain("0x0057"); + wire.IsConnected.ShouldBeFalse(); + } + + /// More reply blocks than request blocks is refused and closes the session. + [Fact] + public async Task A_reply_with_more_blocks_than_requested_closes_the_session() + { + await using var srv = new MockFocasWireServer(); + srv.OnData = reqs => reqs[0].Command == 0x0015 + ? MockFocasWireServer.DataPdu((0x0015, 0, MockFocasWireServer.MacroPayload(1, 0)), (0x0015, 0, MockFocasWireServer.MacroPayload(2, 0))) + : srv.Reply(reqs); + using var wire = await ConnectAsync(srv); + + await Should.ThrowAsync(() => wire.ReadMacroAsync(100, TestContext.Current.CancellationToken)); + wire.IsConnected.ShouldBeFalse(); + } + + /// Bad magic (body left unread) closes the session — it used to propagate with the session still "connected". + [Fact] + public async Task Bad_magic_closes_the_session() + { + await using var srv = new MockFocasWireServer(); + srv.OnData = reqs => reqs[0].Command == 0x0015 + ? MockFocasWireServer.Pdu(0x21, new byte[30], magic: [0xde, 0xad, 0xbe, 0xef]) + : srv.Reply(reqs); + using var wire = await ConnectAsync(srv); + + var ex = await Should.ThrowAsync(() => wire.ReadMacroAsync(100, TestContext.Current.CancellationToken)); + ex.IsTransient.ShouldBeTrue(); + wire.IsConnected.ShouldBeFalse(); + } + + /// + /// A CNC REFUSAL (an rc inside a well-formed reply) is an answer, not a protocol fault: the session stays up + /// — a production control that refuses a function must never be reconnected over it. + /// + [Fact] + public async Task A_refusal_keeps_the_session() + { + await using var srv = new MockFocasWireServer(); + srv.Responder = r => r.Command == 0x0015 ? ((short)1, []) : MockFocasWireServer.DefaultResponder(r); + using var wire = await ConnectAsync(srv); + + var result = await wire.ReadMacroAsync(100, TestContext.Current.CancellationToken); + result.Rc.ShouldBe((short)1); + wire.IsConnected.ShouldBeTrue(); + } + + [Fact] + public void Reply_matching_accepts_an_echo_and_a_shorter_reply_and_refuses_the_rest() + { + RequestBlock[] request = [new(0x0019), new(0x00e1), new(0x0098)]; + FocasWireClient.VerifyResponseMatchesRequest(request, + [new ResponseBlock(0x0019, 0, []), new ResponseBlock(0x00e1, 0, []), new ResponseBlock(0x0098, 0, [])]); + // Shorter is tolerated exactly as before the check existed (not evidence-backed to refuse). + FocasWireClient.VerifyResponseMatchesRequest(request, [new ResponseBlock(0x0019, 1, [])]); + FocasWireClient.VerifyResponseMatchesRequest(request, []); + Should.Throw(() => FocasWireClient.VerifyResponseMatchesRequest(request, + [new ResponseBlock(0x0019, 0, []), new ResponseBlock(0x0098, 0, [])])); + Should.Throw(() => FocasWireClient.VerifyResponseMatchesRequest([new(0x0015)], + [new ResponseBlock(0x0015, 0, []), new ResponseBlock(0x0015, 0, [])])); + } + + /// Every real 31i-B capture echoes its request's command ids — the evidence the matching rests on. + [Theory] + [InlineData("ref-dynamic2-axis1.bin", new ushort[] { 0x001a, 0x001c, 0x001d, 0x0024, 0x0025, 0x0026, 0x0026, 0x0026, 0x0026 })] + [InlineData("ref-statinfo.bin", new ushort[] { 0x0019, 0x00e1, 0x0098 })] + [InlineData("svmeter-pair-0x0056-0x0089.bin", new ushort[] { 0x0056, 0x0089 })] + [InlineData("param-100-0x000e.bin", new ushort[] { 0x000e })] + public void Real_captures_pass_reply_matching(string capture, ushort[] requestCommands) => + FocasWireClient.VerifyResponseMatchesRequest( + [.. requestCommands.Select(c => new RequestBlock(c))], WireFixtures.Blocks(capture)); + + // ---- P-8: the close handshake is bounded ---- + + /// The finding's repro: a CNC that answers data but never the close PDU must not hang Dispose. + [Fact] + public async Task Dispose_completes_within_the_bound_when_the_cnc_never_answers_close() + { + await using var srv = new MockFocasWireServer { AnswerClose = false }; + var wire = await ConnectAsync(srv); + (await wire.ReadMacroAsync(1, TestContext.Current.CancellationToken)).IsOk.ShouldBeTrue(); + + var sw = Stopwatch.StartNew(); + var dispose = Task.Run(wire.Dispose, TestContext.Current.CancellationToken); + (await Task.WhenAny(dispose, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken))).ShouldBe(dispose, "Dispose hung on the close reply"); + sw.Elapsed.ShouldBeLessThan(FocasWireClient.CloseHandshakeTimeout + TimeSpan.FromSeconds(2)); + await WaitUntil(() => srv.Closes == 1); + wire.IsConnected.ShouldBeFalse(); + } + + [Fact] + public async Task DisposeAsync_completes_within_the_bound_when_the_cnc_never_answers_close() + { + await using var srv = new MockFocasWireServer { AnswerClose = false }; + var wire = await ConnectAsync(srv); + + var dispose = wire.DisposeAsync().AsTask(); + (await Task.WhenAny(dispose, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken))).ShouldBe(dispose, "DisposeAsync hung on the close reply"); + await WaitUntil(() => srv.Closes == 1); + } + + /// + /// The close exchange runs under the request gate: with a request in flight against a stalled CNC, Dispose + /// never writes a close PDU into the middle of it, still completes within the bound, and fails the request. + /// + [Fact] + public async Task Dispose_with_a_request_stalled_in_flight_does_not_interleave_and_is_bounded() + { + await using var srv = new MockFocasWireServer(); + srv.OnData = reqs => reqs[0].Command == 0x0015 ? null : srv.Reply(reqs); // the macro read stalls + var wire = await ConnectAsync(srv); + var stalled = wire.ReadMacroAsync(1, TestContext.Current.CancellationToken); + await WaitUntil(() => srv.DataRequests >= 3); // sysinfo + setup + the stalled macro + + var dispose = Task.Run(wire.Dispose, TestContext.Current.CancellationToken); + (await Task.WhenAny(dispose, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken))).ShouldBe(dispose, "Dispose hung behind the stalled request"); + await Should.ThrowAsync(() => stalled); + srv.Closes.ShouldBe(0, "no close PDU may be written into the middle of an in-flight request"); + } + + // ---- P-25: a refused setup sysinfo is not cached ---- + + [Fact] + public async Task A_refused_setup_sysinfo_is_not_cached_for_the_session() + { + await using var srv = new MockFocasWireServer(); + var sysinfoReads = 0; + srv.Responder = r => r.Command == 0x0018 + ? Interlocked.Increment(ref sysinfoReads) == 1 ? ((short)-1, []) : ((short)0, MockFocasWireServer.SysInfoPayload()) + : MockFocasWireServer.DefaultResponder(r); + using var wire = await ConnectAsync(srv); + + var info = await wire.ReadSysInfoAsync(TestContext.Current.CancellationToken); + info.IsOk.ShouldBeTrue("the connect-time EW_BUSY must not be served from the cache for the life of the session"); + info.Value!.Series.ShouldBe("G431"); + sysinfoReads.ShouldBe(2); + } + + /// Positive control: an ANSWERED setup sysinfo is still cached — later reads cost no wire traffic. + [Fact] + public async Task An_answered_setup_sysinfo_is_still_cached() + { + await using var srv = new MockFocasWireServer(); + using var wire = await ConnectAsync(srv); + var before = srv.CountOf(0x0018); + + (await wire.ReadSysInfoAsync(TestContext.Current.CancellationToken)).IsOk.ShouldBeTrue(); + (await wire.ReadSysInfoAsync(TestContext.Current.CancellationToken)).IsOk.ShouldBeTrue(); + srv.CountOf(0x0018).ShouldBe(before); + before.ShouldBe(1); + } + + // ---- P-6: fixed-tree refusals carry their rc ---- + + /// + /// The adapter used to throw a plain InvalidOperationException for a non-OK rc, which the driver's refusal + /// test could not recognise — a control that refused cnc_rddynamic2 looked silent and degraded. + /// + [Fact] + public async Task A_refused_fixed_tree_call_is_thrown_as_a_refusal_carrying_its_rc() + { + await using var srv = new MockFocasWireServer(); + srv.Responder = r => r.Command is 0x001a or 0x0019 or 0x0120 + ? ((short)1, []) + : MockFocasWireServer.DefaultResponder(r); + var client = new WireFocasClient(); + await client.ConnectAsync(FocasHostAddress.TryParse(srv.HostAddress)!, ConnectTimeout, CancellationToken.None); + + var dyn = await Should.ThrowAsync(() => client.ReadDynamicAsync(1, CancellationToken.None)); + dyn.Rc.ShouldBe((short)1); + FocasAlarmProjection.IsCncRefusal(dyn).ShouldBeTrue(); + (await Should.ThrowAsync(() => client.GetStatusAsync(CancellationToken.None))).Rc.ShouldBe((short)1); + (await Should.ThrowAsync(() => client.GetTimerAsync(FocasTimerKind.PowerOn, CancellationToken.None))).Rc.ShouldBe((short)1); + client.IsConnected.ShouldBeTrue("a refusal leaves the session up"); + client.Dispose(); + } + + // ---- P-25: a short parameter payload is not a Good 0 ---- + + [Theory] + [InlineData(FocasDataType.Int32, 2)] + [InlineData(FocasDataType.Int16, 1)] + [InlineData(FocasDataType.Float32, 3)] + [InlineData(FocasDataType.Float64, 4)] + [InlineData(FocasDataType.Byte, 0)] + [InlineData(FocasDataType.Bit, 3)] + public void A_parameter_payload_shorter_than_its_type_is_BadTypeMismatch(FocasDataType type, int length) + { + var (value, status) = WireFocasClient.DecodeParameter(new byte[length], type, type == FocasDataType.Bit ? 1 : null); + status.ShouldBe(FocasStatusMapper.BadTypeMismatch); + value.ShouldBeNull(); + } + + [Fact] + public void A_full_parameter_payload_still_decodes_big_endian_at_offset_0() + { + WireFocasClient.DecodeParameter([0x00, 0x00, 0x01, 0x02], FocasDataType.Int32, null) + .ShouldBe(((object?)0x0102, FocasStatusMapper.Good)); + WireFocasClient.DecodeParameter([0xff, 0xfe], FocasDataType.Int16, null) + .ShouldBe(((object?)(short)-2, FocasStatusMapper.Good)); + WireFocasClient.DecodeParameter([0x80], FocasDataType.Byte, null) + .ShouldBe(((object?)(sbyte)-128, FocasStatusMapper.Good)); + WireFocasClient.DecodeParameter([0x00, 0x00, 0x00, 0x04], FocasDataType.Bit, 2) + .ShouldBe(((object?)true, FocasStatusMapper.Good)); + } + + [Fact] + public async Task A_short_parameter_reply_reads_BadTypeMismatch_end_to_end() + { + await using var srv = new MockFocasWireServer(); + srv.Responder = r => r.Command == 0x000e && r.Arg1 == 6711 + ? ((short)0, new byte[] { 0x00, 0x07 }) + : MockFocasWireServer.DefaultResponder(r); + var client = new WireFocasClient(); + await client.ConnectAsync(FocasHostAddress.TryParse(srv.HostAddress)!, ConnectTimeout, CancellationToken.None); + + var (value, status) = await client.ReadAsync(FocasAddress.TryParse("PARAM:6711")!, FocasDataType.Int32, CancellationToken.None); + status.ShouldBe(FocasStatusMapper.BadTypeMismatch, "two bytes cannot be an Int32 — it used to read Good 0"); + value.ShouldBeNull(); + client.Dispose(); + } + + private static async Task WaitUntil(Func condition) + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (!condition()) + { + if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached"); + await Task.Delay(10, TestContext.Current.CancellationToken); + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/MockFocasWireServer.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/MockFocasWireServer.cs new file mode 100644 index 000000000..86298e696 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/MockFocasWireServer.cs @@ -0,0 +1,229 @@ +using System.Buffers.Binary; +using System.Net; +using System.Net.Sockets; + +namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests; + +/// One request block as the mock CNC received it. +/// The FOCAS command id. +/// 32-bit argument 1. +/// 32-bit argument 2. +internal sealed record MockFocasRequest(ushort Command, int Arg1, int Arg2); + +/// +/// A loopback FOCAS/2 Ethernet peer speaking the real binary framing (the shape the 31i-B captures under +/// Fixtures/v3 and the focas-mock fixture use: initiate on both sockets, then 0x21 data PDUs whose +/// reply blocks echo the request's command ids in order). Each test scripts what it answers — a stray PDU, a +/// mismatched block, silence on the close PDU — to drive the real through +/// the protocol faults #985 is about. Default behaviour answers everything with rc 0. +/// +internal sealed class MockFocasWireServer : IAsyncDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _cts = new(); + private readonly List _connections = []; + private readonly Task _acceptLoop; + private int _initiates; + private int _closes; + private int _dataRequests; + + public MockFocasWireServer() + { + _listener.Start(); + Port = ((IPEndPoint)_listener.LocalEndpoint).Port; + _acceptLoop = AcceptLoopAsync(); + } + + /// The listening port. + public int Port { get; } + + /// The driver host address of this peer. + public string HostAddress => $"focas://127.0.0.1:{Port}"; + + /// Answer the close PDU (default) or stay silent on it with the socket left open. + public volatile bool AnswerClose = true; + + /// + /// Builds the bytes written for one data PDU (any number of whole PDUs, or to stay + /// silent). Default: of every block through . + /// + public Func, byte[]?>? OnData { get; set; } + + /// The (rc, payload) the default answers one block with. + public Func Responder { get; set; } = DefaultResponder; + + /// Initiate PDUs received (two per session). + public int Initiates => Volatile.Read(ref _initiates); + + /// Close PDUs received. + public int Closes => Volatile.Read(ref _closes); + + /// Data PDUs received. + public int DataRequests => Volatile.Read(ref _dataRequests); + + /// Every data request block received, in order (lock it to read while the server runs). + public List Requests { get; } = []; + + /// How many request blocks of have been received. + public int CountOf(ushort command) + { + lock (Requests) return Requests.Count(r => r.Command == command); + } + + /// The default answer: a sysinfo record for 0x0018, a macro whose mantissa is its number, else 4 zero bytes. + public static (short Rc, byte[] Payload) DefaultResponder(MockFocasRequest r) => r.Command switch + { + 0x0018 => (0, SysInfoPayload()), + 0x000e when r.Arg1 == 0x26f0 => (1, []), // the setup request — a real 31i-B answers EW_FUNC + 0x0015 => (0, MacroPayload(r.Arg1, 0)), + _ => (0, new byte[4]), + }; + + /// An 18-byte cnc_sysinfo payload (2 axes, "31", "MM", "G431", "22.0", "07"). + public static byte[] SysInfoPayload() => + [0x02, 0x02, 0x00, 0x20, 0x33, 0x31, 0x4d, 0x4d, 0x47, 0x34, 0x33, 0x31, 0x32, 0x32, 0x2e, 0x30, 0x30, 0x37]; + + /// An 8-byte cnc_rdmacro payload: mantissa, the constant 10, decimal places. + public static byte[] MacroPayload(int mantissa, short decimals) + { + var p = new byte[8]; + BinaryPrimitives.WriteInt32BigEndian(p.AsSpan(0, 4), mantissa); + BinaryPrimitives.WriteInt16BigEndian(p.AsSpan(4, 2), 10); + BinaryPrimitives.WriteInt16BigEndian(p.AsSpan(6, 2), decimals); + return p; + } + + /// A data-reply PDU answering block-for-block through . + public byte[] Reply(IReadOnlyList requests) => + DataPdu([.. requests.Select(r => { var (rc, p) = Responder(r); return (r.Command, rc, p); })]); + + /// A data-reply PDU carrying exactly the given blocks. + public static byte[] DataPdu(params (ushort Command, short Rc, byte[] Payload)[] blocks) + { + var encoded = blocks.Select(b => + { + var block = new byte[0x10 + b.Payload.Length]; + BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(0, 2), (ushort)block.Length); + BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(2, 2), 1); + BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(4, 2), 1); + BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(6, 2), b.Command); + BinaryPrimitives.WriteInt16BigEndian(block.AsSpan(8, 2), b.Rc); + BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(14, 2), (ushort)b.Payload.Length); + b.Payload.CopyTo(block.AsSpan(0x10)); + return block; + }).ToArray(); + var body = new byte[2 + encoded.Sum(b => b.Length)]; + BinaryPrimitives.WriteUInt16BigEndian(body.AsSpan(0, 2), (ushort)encoded.Length); + var offset = 2; + foreach (var b in encoded) { b.CopyTo(body.AsSpan(offset)); offset += b.Length; } + return Pdu(0x21, body); + } + + /// A whole response PDU (version 3, direction response) of . + public static byte[] Pdu(byte type, byte[] body, byte[]? magic = null) + { + var pdu = new byte[10 + body.Length]; + (magic ?? [0xa0, 0xa0, 0xa0, 0xa0]).CopyTo(pdu, 0); + BinaryPrimitives.WriteUInt16BigEndian(pdu.AsSpan(4, 2), 3); + pdu[6] = type; + pdu[7] = 0x02; + BinaryPrimitives.WriteUInt16BigEndian(pdu.AsSpan(8, 2), (ushort)body.Length); + body.CopyTo(pdu, 10); + return pdu; + } + + /// Drops every open connection (the CNC goes away) and stops accepting new ones. + public void Stop() + { + _listener.Stop(); + lock (_connections) + { + foreach (var c in _connections) c.Dispose(); + _connections.Clear(); + } + } + + private async Task AcceptLoopAsync() + { + while (!_cts.IsCancellationRequested) + { + TcpClient client; + try { client = await _listener.AcceptTcpClientAsync(_cts.Token); } + catch { return; } + lock (_connections) _connections.Add(client); + _ = ServeAsync(client); + } + } + + private async Task ServeAsync(TcpClient client) + { + try + { + var stream = client.GetStream(); + var header = new byte[10]; + while (!_cts.IsCancellationRequested) + { + await stream.ReadExactlyAsync(header, _cts.Token); + var length = BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(8, 2)); + var body = new byte[length]; + if (length > 0) await stream.ReadExactlyAsync(body, _cts.Token); + byte[]? answer; + switch (header[6]) + { + case 0x01: + Interlocked.Increment(ref _initiates); + answer = Pdu(0x01, new byte[24]); + break; + case 0x02: + Interlocked.Increment(ref _closes); + answer = AnswerClose ? Pdu(0x02, []) : null; + break; + case 0x21: + Interlocked.Increment(ref _dataRequests); + var requests = ParseRequests(body); + lock (Requests) Requests.AddRange(requests); + answer = (OnData ?? Reply)(requests); + break; + default: + answer = null; + break; + } + if (answer is not null) + { + await stream.WriteAsync(answer, _cts.Token); + await stream.FlushAsync(_cts.Token); + } + } + } + catch + { + // Peer closed / test over. + } + } + + private static List ParseRequests(byte[] body) + { + var list = new List(); + if (body.Length < 2) return list; + var count = BinaryPrimitives.ReadUInt16BigEndian(body.AsSpan(0, 2)); + var offset = 2; + for (var i = 0; i < count && offset + 0x1c <= body.Length; i++) + { + var blockLength = BinaryPrimitives.ReadUInt16BigEndian(body.AsSpan(offset, 2)); + list.Add(new MockFocasRequest( + BinaryPrimitives.ReadUInt16BigEndian(body.AsSpan(offset + 6, 2)), + BinaryPrimitives.ReadInt32BigEndian(body.AsSpan(offset + 8, 4)), + BinaryPrimitives.ReadInt32BigEndian(body.AsSpan(offset + 12, 4)))); + offset += blockLength; + } + return list; + } + + public async ValueTask DisposeAsync() + { + _cts.Cancel(); + Stop(); + try { await _acceptLoop; } catch { /* stopped */ } + _cts.Dispose(); + } +}