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.
This commit is contained in:
Joseph Doherty
2026-12-03 10:04:42 -05:00
parent 65fd71de7a
commit e68d856fcb
13 changed files with 1568 additions and 100 deletions
@@ -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<string>()).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);
@@ -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,
}
}
/// <summary>
/// Whether a refused merged PMC range should be remembered as permanently unreadable (#985 P-21): only the
/// statuses a range itself causes — <c>EW_NUMBER</c> / <c>EW_LENGTH</c> / <c>EW_OVRFLOW</c>
/// (<see cref="FocasStatusMapper.BadOutOfRange"/>), <c>EW_DATA</c> / an unknown area
/// (<see cref="FocasStatusMapper.BadNodeIdUnknown"/>), <c>EW_ATTRIB</c>
/// (<see cref="FocasStatusMapper.BadTypeMismatch"/>) and <c>EW_FUNC</c> / <c>EW_NOOPT</c> / <c>EW_VERSION</c>
/// (<see cref="FocasStatusMapper.BadNotSupported"/>). Everything else is transient or link-shaped.
/// </summary>
/// <param name="status">The mapped status of the refused range read.</param>
/// <returns><see langword="true"/> to latch the range as rejected.</returns>
internal static bool IsRangeShapedRefusal(uint status) => status is FocasStatusMapper.BadOutOfRange
or FocasStatusMapper.BadNodeIdUnknown or FocasStatusMapper.BadTypeMismatch or FocasStatusMapper.BadNotSupported;
// ---- IWritable ----
/// <inheritdoc />
@@ -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);
/// <summary>
/// Caches <see cref="NoValue"/> (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 <c>cnc_rddynamic2</c> bundle — so
/// a refused axis never keeps serving its last value as fresh Good.
/// </summary>
private static void PublishAxisNoValue(DeviceState state, string axisSegment, bool rates)
{
var host = state.Options.HostAddress;
foreach (var field in (ReadOnlySpan<string>)["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.
/// </summary>
private static async Task<IReadOnlyList<T>> SafeProbe<T>(
Func<Task<IReadOnlyList<T>>> probe, IReadOnlyList<T> fallback)
IFocasClient client, Func<Task<IReadOnlyList<T>>> probe, IReadOnlyList<T> fallback)
{
try { return await probe().ConfigureAwait(false); }
catch { return fallback; }
catch (Exception ex) when (IsCapabilityAnswer(client, ex)) { return fallback; }
}
/// <summary>
/// Nullable variant — probe returns a single object or null on failure.
/// </summary>
private static async Task<T?> SafeTryProbe<T>(Func<Task<T>> probe) where T : class
private static async Task<T?> SafeTryProbe<T>(IFocasClient client, Func<Task<T>> probe) where T : class
{
try { return await probe().ConfigureAwait(false); }
catch { return null; }
catch (Exception ex) when (IsCapabilityAnswer(client, ex)) { return null; }
}
/// <summary>
/// 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.
/// </summary>
/// <param name="client">The probed client.</param>
/// <param name="error">The probe's failure.</param>
/// <returns><see langword="true"/> to record the capability as unsupported.</returns>
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;
}
/// <summary>The session dropped mid capability probe — the bootstrap retries instead of latching a partial set.</summary>
private sealed class FocasCapabilityProbeInterruptedException(string message) : Exception(message);
/// <summary>
/// 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<FocasSpindleName> Spindles,
FocasFixedTreeCapabilities Capabilities)
{
/// <summary>
/// The 1-based axis number <c>cnc_rddynamic2</c> addresses the <paramref name="i"/>-th named axis by: its
/// wire slot (#985 P-9). The position in <see cref="Axes"/> 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.
/// </summary>
/// <param name="i">The axis's position in <see cref="Axes"/>.</param>
/// <returns>The axis number to request.</returns>
public int AxisNumber(int i) => Axes[i].Slot > 0 ? Axes[i].Slot : i + 1;
/// <summary>
/// The 0-based <c>cnc_rdspmeter</c> record index of the <paramref name="i"/>-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.
/// </summary>
/// <param name="i">The spindle's position in <see cref="Spindles"/>.</param>
/// <returns>The meter-record index.</returns>
public int SpindleMeterIndex(int i) => Spindles[i].Slot > 0 ? Spindles[i].Slot - 1 : i;
/// <summary>
/// Unique <c>Axes/{segment}</c> path segments, one per axis in slot order — bare
/// display names when unique, occurrence-suffixed (<c>AA_1</c>, <c>AA_2</c>) 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
/// <see cref="ConnectGate"/>; the backoff is consulted inside it.
/// <see cref="ConnectGate"/>; 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.
/// </summary>
public ConnectionBackoff Backoff { get; } = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30));
private volatile bool _lastConnectFailed;
/// <summary>
/// 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
/// <see cref="ConnectGate"/> for the connect timeout (#985 P-11).
/// </summary>
public bool LastConnectFailed
{
get => _lastConnectFailed;
set => _lastConnectFailed = value;
}
/// <summary>
/// Serializes <c>EnsureConnectedAsync</c> 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.
@@ -278,7 +278,14 @@ public sealed record FocasSysInfo(
int AxesCount);
/// <summary>One configured axis name (e.g. "X", "X1").</summary>
public sealed record FocasAxisName(string Name, string Suffix)
/// <param name="Name">The axis letter.</param>
/// <param name="Suffix">The multi-channel suffix.</param>
/// <param name="Slot">
/// The 1-based wire slot the CNC reported the name in — the axis number <c>cnc_rddynamic2</c> 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.
/// </param>
public sealed record FocasAxisName(string Name, string Suffix, int Slot = 0)
{
/// <summary>
/// Display name — name + suffix concatenated, trimmed. Empty suffix yields
@@ -288,7 +295,15 @@ public sealed record FocasAxisName(string Name, string Suffix)
}
/// <summary>One configured spindle name (e.g. "S1").</summary>
public sealed record FocasSpindleName(string Name, string Suffix1, string Suffix2, string Suffix3)
/// <param name="Name">The spindle letter.</param>
/// <param name="Suffix1">First suffix character.</param>
/// <param name="Suffix2">Second suffix character.</param>
/// <param name="Suffix3">Third suffix character.</param>
/// <param name="Slot">
/// The 1-based wire slot the CNC reported the name in — the slot its <c>cnc_rdspmeter</c> records sit in
/// (#985 P-9). 0 = unknown, which falls back to the spindle's position in the list.
/// </param>
public sealed record FocasSpindleName(string Name, string Suffix1, string Suffix2, string Suffix3, int Slot = 0)
{
/// <summary>Gets the display name — name + concatenated suffixes, trimmed.</summary>
public string Display
@@ -22,8 +22,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Wire;
/// — <c>socket 2</c> is guarded by a <see cref="SemaphoreSlim"/> so at most one
/// request/response pair is in flight at a time. <see cref="ConnectAsync(string, int, int, CancellationToken)"/>
/// and <see cref="DisposeAsync"/> share a second semaphore to stop the two racing.</para>
/// <para><b>Transient failures.</b> When cancellation or a socket-level error happens
/// mid-request the client closes both sockets and throws
/// <para><b>Transient failures.</b> 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
/// <see cref="FocasWireException"/> with <see cref="FocasWireException.IsTransient"/>
/// 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
}
}
/// <summary>
/// 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.
/// </summary>
internal static readonly TimeSpan CloseHandshakeTimeout = TimeSpan.FromSeconds(1);
/// <summary>
/// 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<byte>.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<byte>.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<byte>.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<byte>.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<WireParameter>(result.Rc, null);
return new FocasResult<WireParameter>(
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)));
}
/// <summary>Typed 8-bit parameter read.</summary>
@@ -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<byte>(result.Rc, default)
: new FocasResult<byte>(result.Rc, result.Value.Length >= 1 ? result.Value[0] : default);
: new FocasResult<byte>(result.Rc, RequireParameterLength(result.Value, 1)[0]);
}
/// <summary>Typed 16-bit parameter read.</summary>
@@ -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<short>(result.Rc, default)
: new FocasResult<short>(result.Rc, result.Value.Length >= 2 ? ReadInt16(result.Value, 0) : default);
: new FocasResult<short>(result.Rc, ReadInt16(RequireParameterLength(result.Value, 2), 0));
}
/// <summary>Typed 32-bit parameter read.</summary>
@@ -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<int>(result.Rc, default)
: new FocasResult<int>(result.Rc, result.Value.Length >= 4 ? ReadInt32(result.Value, 0) : default);
: new FocasResult<int>(result.Rc, ReadInt32(RequireParameterLength(result.Value, 4), 0));
}
/// <summary>Typed IEEE-754 single-precision parameter read.</summary>
@@ -578,9 +622,9 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable
public async Task<FocasResult<float>> 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<float>(result.Rc, default)
: new FocasResult<float>(result.Rc, BitConverter.Int32BitsToSingle(ReadInt32(result.Value, 0)));
: new FocasResult<float>(result.Rc, BitConverter.Int32BitsToSingle(ReadInt32(RequireParameterLength(result.Value, 4), 0)));
}
/// <summary>Typed IEEE-754 double-precision parameter read.</summary>
@@ -593,9 +637,9 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable
public async Task<FocasResult<double>> 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<double>(result.Rc, default)
: new FocasResult<double>(result.Rc, BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(result.Value.AsSpan(0, 8))));
: new FocasResult<double>(result.Rc, BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(RequireParameterLength(result.Value, 8).AsSpan(0, 8))));
}
/// <summary>Read a single macro variable via <c>cnc_rdmacro</c> (command <c>0x0015</c>).</summary>
@@ -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
}
}
/// <summary>
/// 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
/// (<c>Fixtures/v3</c>, 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.
/// </summary>
/// <param name="request">The request blocks sent.</param>
/// <param name="response">The reply blocks received.</param>
/// <exception cref="FocasWireException">The reply does not match the request.</exception>
internal static void VerifyResponseMatchesRequest(IReadOnlyList<RequestBlock> request, IReadOnlyList<ResponseBlock> 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<TcpClient> ConnectSocketAsync(string host, int port, CancellationToken cancellationToken)
{
var socket = new TcpClient { NoDelay = true };
@@ -1253,7 +1329,8 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable
/// <summary>
/// Decode an axis-name (0x0089) or spindle-name (0x008A) payload: an array of 4-byte records,
/// each named by <see cref="FocasWireProtocol.ReadNameRecord"/>. 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
/// (<c>cnc_rddynamic2</c>, the spindle meters), which the adapter carries through (#985 P-9).
/// </summary>
/// <typeparam name="T">The record type the factory builds.</typeparam>
/// <param name="payload">The response-block payload.</param>
@@ -1272,6 +1349,16 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable
return names;
}
/// <summary>
/// A typed <c>cnc_rdparam</c> decode needs at least <paramref name="width"/> payload bytes (#985 P-25): a
/// shorter answer used to decode as a Good <c>0</c>. Refused like the macro path refuses a short payload.
/// </summary>
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)
@@ -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);
}
/// <summary>
/// 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 <c>cnc_rddynamic2</c> addresses the axis by.
/// </summary>
/// <param name="records">The wire records (blank slots already skipped, slots preserved).</param>
/// <returns>The named axes, in wire order.</returns>
internal static IReadOnlyList<FocasAxisName> MapAxisNames(IEnumerable<WireAxisRecord> 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();
/// <inheritdoc />
public async Task<IReadOnlyList<FocasSpindleName>> 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);
}
/// <summary>
/// Maps the wire's spindle-name records, keeping each one's wire SLOT (#985 P-9) — the slot its
/// <c>cnc_rdspmeter</c> records sit in.
/// </summary>
/// <param name="records">The wire records (blank slots already skipped, slots preserved).</param>
/// <returns>The named spindles, in wire order.</returns>
internal static IReadOnlyList<FocasSpindleName> MapSpindleNames(IEnumerable<WireSpindleRecord> 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();
/// <inheritdoc />
public async Task<FocasDynamicSnapshot> 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
}
}
/// <summary>
/// Decode an answered <c>cnc_rdparam</c> payload as the tag's declared type (Byte = 1 byte, Int16 = 2,
/// Int32 / Bit = 4, Float32 = 4, Float64 = 8; big-endian, offset 0 — unchanged).
/// </summary>
/// <remarks>
/// A payload SHORTER than the declared width is <see cref="FocasStatusMapper.BadTypeMismatch"/> (#985 P-25):
/// it used to decode as a Good <c>0</c>, 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
/// <c>cnc_rdparam</c> capture exists yet, so the layout itself is still unvalidated; see docs/drivers/FOCAS.md.)
/// </remarks>
/// <param name="payload">The answered payload.</param>
/// <param name="type">The tag's declared type.</param>
/// <param name="bitIndex">The bit of a <see cref="FocasDataType.Bit"/> tag, if any.</param>
/// <returns>The value and its status.</returns>
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.");
}
/// <summary>
/// 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 <see cref="ReadAlarmsAsync"/> does. It used to be a plain
/// <see cref="InvalidOperationException"/>, which the driver's refusal test
/// (<see cref="FocasAlarmProjection.IsCncRefusal"/>) could not recognise: a fixed-tree control that refused
/// <c>cnc_rddynamic2</c> looked silent, degraded the driver and reconnect-looped under the #527 watchdog.
/// </summary>
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);
}
}