Merge driver follow-ups A: Modbus RTU response correlation + cancel redial + rebuild e2e (#1029/#1055), MTConnect malformed-item BadDecodingError + cross-chunk condition severity (#1055/#1037), TwinCAT write fail-fast + retired-client reads (#1035), OpcUaClient skipped-tag ledger append + zone-qualified IPv6 probe (#1039)

This commit is contained in:
Joseph Doherty
2026-12-03 15:25:42 -05:00
28 changed files with 1137 additions and 38 deletions
@@ -27,11 +27,16 @@ internal enum MTConnectConditionLevel
/// </param>
/// <param name="TimestampUtc">That observation's Agent timestamp.</param>
/// <param name="ActiveCount">How many distinct conditions (by <c>nativeCode</c>) are active at once.</param>
/// <param name="ValueWord">
/// The state word, as the Agent spelled it, of the observation the level comes from — what a CONDITION DataItem's
/// plain value tag must read (#1037). <c>null</c> only for a state built by hand.
/// </param>
internal sealed record MTConnectConditionState(
MTConnectConditionLevel Level,
MTConnectConditionDetail Detail,
DateTime TimestampUtc,
int ActiveCount)
int ActiveCount,
string? ValueWord = null)
{
/// <summary>Whether the derived condition is active (Warning or Fault).</summary>
public bool IsActive => Level is MTConnectConditionLevel.Warning or MTConnectConditionLevel.Fault;
@@ -162,7 +167,7 @@ internal sealed class MTConnectConditionTracker
.ThenBy(e => e.Detail.ConditionType ?? string.Empty, StringComparer.Ordinal)
.First();
return new MTConnectConditionState(winner.Level, winner.Detail, winner.TimestampUtc, item.Active.Count);
return new MTConnectConditionState(winner.Level, winner.Detail, winner.TimestampUtc, item.Active.Count, winner.Word);
}
var last = item.LastInactive;
@@ -172,7 +177,8 @@ internal sealed class MTConnectConditionTracker
item.Unavailable ? MTConnectConditionLevel.Unavailable : MTConnectConditionLevel.Normal,
last.Detail,
last.TimestampUtc,
0);
0,
last.Word);
}
}
@@ -198,7 +204,7 @@ internal sealed class MTConnectConditionTracker
private void ApplyOne(ItemState item, MTConnectObservation observation)
{
var detail = observation.Condition!;
var entry = new Entry(LevelOf(observation.Value), detail, observation.TimestampUtc);
var entry = new Entry(LevelOf(observation.Value), detail, observation.TimestampUtc, observation.Value);
switch (entry.Level)
{
@@ -222,7 +228,7 @@ internal sealed class MTConnectConditionTracker
}
}
private sealed record Entry(MTConnectConditionLevel Level, MTConnectConditionDetail Detail, DateTime TimestampUtc);
private sealed record Entry(MTConnectConditionLevel Level, MTConnectConditionDetail Detail, DateTime TimestampUtc, string Word);
private sealed class ItemState
{
@@ -832,7 +832,9 @@ public sealed partial class MTConnectDriver
// Built from the SAME authored tags as the shared index, so the authored-vs-unknown
// distinction and every coercion behave identically — it is a snapshot, not a variant.
var snapshot = MTConnectObservationIndex.OverFrozenTags(binding.IndexTagMap);
snapshot.Apply(current, baseline: true);
var snapshotConditions = new MTConnectConditionTracker();
snapshotConditions.Apply(current, baseline: true);
snapshot.Apply(current, baseline: true, snapshotConditions);
var results = new DataValueSnapshot[fullReferences.Count];
for (var i = 0; i < results.Length; i++)
@@ -2834,14 +2836,16 @@ public sealed partial class MTConnectDriver
return false;
}
index.Apply(document, baseline);
// CONDITION observations also feed the alarm path, which keeps its own multi-condition state
// (a /sample Normal for one nativeCode is not a return to normal while another code is active).
// (a /sample Normal for one nativeCode is not a return to normal while another code is active). The tracker folds
// FIRST: the index then derives a condition DataItem's value word from it (#1037), so the value tag and the
// native alarm agree about which code is the most severe active one.
var touchedConditions = tracker.Apply(document, baseline);
index.Apply(document, baseline, tracker);
EmitConditionTransitions(touchedConditions, resync: false, baselineRead: baseline);
if (document.Observations is not { Count: > 0 })
var malformedIds = document.MalformedDataItemIds;
if (document.Observations is not { Count: > 0 } && malformedIds is not { Count: > 0 })
{
return true;
}
@@ -2856,9 +2860,9 @@ public sealed partial class MTConnectDriver
// dataItemId-keyed authoring surface (the driver CLI). Publishing the id instead of the
// RawPath would miss DriverHostActor's NodeId table and drop the value silently.
var binding = Volatile.Read(ref _binding);
var touched = new List<string>(document.Observations.Count);
var touched = new List<string>(document.Observations?.Count ?? 0);
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var observation in document.Observations)
foreach (var observation in document.Observations ?? [])
{
if (observation is null || string.IsNullOrWhiteSpace(observation.DataItemId))
{
@@ -2871,6 +2875,16 @@ public sealed partial class MTConnectDriver
}
}
// #1055: an item whose only observation in this document was malformed was marked BadDecodingError by the
// index; its subscribers must hear it, or the last Good value they hold stands forever.
foreach (var id in malformedIds ?? [])
{
if (!string.IsNullOrWhiteSpace(id) && seen.Add(id))
{
binding.AppendReferences(id, touched);
}
}
FanOut(touched, index);
return true;
@@ -2911,8 +2925,8 @@ public sealed partial class MTConnectDriver
var tracker = Volatile.Read(ref _conditions);
index.Clear();
tracker.Clear();
index.Apply(current, baseline: true);
tracker.Apply(current, baseline: true);
index.Apply(current, baseline: true, tracker);
}
}
@@ -3485,12 +3499,12 @@ public sealed partial class MTConnectDriver
// between them would start a pump on the OLD session stamped with the NEW generation, and
// the restart's own StartSampleStreamCore would then treat it as current.
var index = new MTConnectObservationIndex(binding.IndexTags);
index.Apply(current, baseline: true);
// the CONDITION tracker is per-session state like the index. Nothing is RAISED here — the
// lifecycle semaphore is held; the restarted pump delivers the diff as its first act.
// lifecycle semaphore is held; the restarted pump delivers the diff as its first act. It folds first:
// the index derives a condition item's value word from it (#1037).
var conditions = new MTConnectConditionTracker();
conditions.Apply(current, baseline: true);
index.Apply(current, baseline: true, conditions);
// The index and the tracker are installed in the SAME critical section as the session and its
// generation (R06:T-1 / review m3): a pump that reads them under this lock with its generation still
@@ -125,6 +125,12 @@ public sealed record MTConnectDataItem(
/// rather than failing the whole document (M-8). Zero for a clean document.
/// </param>
/// <param name="FirstSkipReason">Why the first of them was dropped; <c>null</c> when none was.</param>
/// <param name="MalformedDataItemIds">
/// The <c>dataItemId</c> of each skipped observation that DID name one (an unparseable / missing timestamp) — the
/// skip is not silent for those: the index marks the item <c>BadDecodingError</c> instead of leaving its last Good
/// value standing forever (#1055). An observation with no <c>dataItemId</c> cannot be attributed and is only counted.
/// <c>null</c> when none.
/// </param>
public sealed record MTConnectStreamsResult(
long InstanceId,
long NextSequence,
@@ -132,7 +138,8 @@ public sealed record MTConnectStreamsResult(
IReadOnlyList<MTConnectObservation> Observations,
long? LastSequence = null,
int SkippedObservations = 0,
string? FirstSkipReason = null);
string? FirstSkipReason = null,
IReadOnlyList<string>? MalformedDataItemIds = null);
/// <summary>
/// One observed value for a single DataItem, as reported in a <c>/current</c> snapshot or a
@@ -209,10 +209,28 @@ internal sealed class MTConnectObservationIndex
/// <c>true</c> for a <c>/current</c> document, which states the <b>whole</b> DATA_SET / TABLE and so replaces
/// the accumulated set; <c>false</c> (default) for a <c>/sample</c> chunk, whose entries are deltas merged into it.
/// </param>
public void Apply(MTConnectStreamsResult result, bool baseline = false)
/// <param name="conditions">
/// The condition tracker that has ALREADY folded this document (#1037): a CONDITION DataItem's value word is then
/// taken from its derived state (most severe active code, across chunks) instead of from the document alone, so a
/// Warning on code B can never mask a still-active Fault on code A that an earlier chunk raised. Null keeps the
/// per-document reconcile (<see cref="Reconcile"/>).
/// </param>
public void Apply(MTConnectStreamsResult result, bool baseline = false, MTConnectConditionTracker? conditions = null)
{
ArgumentNullException.ThrowIfNull(result);
// #1055: an observation skipped for a bad / missing timestamp still NAMED its item. Leaving the index alone kept
// that item's last Good value standing forever, so it reads BadDecodingError (a valid observation of the same
// item in this document, applied below, replaces it).
if (result.MalformedDataItemIds is { Count: > 0 } malformed)
{
foreach (var id in malformed)
{
if (!string.IsNullOrWhiteSpace(id))
_snapshots[id] = new DataValueSnapshot(null, BadDecodingError, null, Now);
}
}
if (result.Observations is not { Count: > 0 }) return;
// Duplicates are reconciled on the RAW observations first, so each dataItemId is written
@@ -233,8 +251,17 @@ internal sealed class MTConnectObservationIndex
: observation;
}
foreach (var (dataItemId, observation) in resolved)
foreach (var (dataItemId, resolvedObservation) in resolved)
{
var observation = resolvedObservation;
if (conditions is not null && observation.Condition is not null
&& conditions.Get(dataItemId) is { ValueWord: { } word })
{
// The tracker's derived word: the most severe still-active code across every chunk, else the latest
// Normal/Unavailable. Source timestamp stays the document's own latest observation (last heard).
observation = observation with { Value = word };
}
_snapshots[dataItemId] = BuildSnapshot(observation);
}
}
@@ -343,7 +343,8 @@ internal static class MTConnectStreamsParser
observations,
sequences.LastSequence,
observations.Skipped,
observations.FirstReason);
observations.FirstReason,
observations.MalformedIds is { Count: > 0 } malformed ? malformed : null);
}
/// <summary>
@@ -435,7 +436,7 @@ internal static class MTConnectStreamsParser
if (skipReason is not null)
{
(observations as ObservationList)?.NoteSkipped(skipReason);
(observations as ObservationList)?.NoteSkipped(skipReason, dataItemId);
// Consume the subtree to honour the cursor contract (nothing inside a malformed observation is read).
if (!reader.IsEmptyElement)
@@ -694,10 +695,14 @@ internal static class MTConnectStreamsParser
public string? FirstReason { get; private set; }
public void NoteSkipped(string reason)
/// <summary>The distinct <c>dataItemId</c>s of skipped observations that named one (#1055).</summary>
public List<string>? MalformedIds { get; private set; }
public void NoteSkipped(string reason, string? dataItemId)
{
Skipped++;
FirstReason ??= reason;
if (dataItemId is not null && (MalformedIds ??= []) is { } ids && !ids.Contains(dataItemId)) ids.Add(dataItemId);
}
}
@@ -93,6 +93,14 @@ public static class ModbusRtuFraming
/// it after the CRC passes; a mismatch is a unit-mismatch desync.
/// </param>
/// <param name="ct">A token to cancel the read.</param>
/// <param name="requestPdu">
/// The request PDU this response answers (#1029). When supplied, the reply's function code (an exception
/// frame's masked code too) must equal the request's, and a write echo (FC 05/06/0F/10) must echo the
/// request's start address — RTU has no transaction id, so a CRC-valid reply from the right unit that
/// answers a DIFFERENT request is otherwise indistinguishable. A mismatch is a
/// <see cref="ModbusTransportDesyncException.DesyncReason.ResponseMismatch"/> desync. <see langword="null"/>
/// keeps the unit-only validation (framing tests that have no request).
/// </param>
/// <returns>The bare response PDU (function code followed by its data).</returns>
/// <exception cref="ModbusTransportDesyncException">
/// The frame was truncated (stream closed mid-frame), its trailing CRC did not validate, or its
@@ -102,7 +110,7 @@ public static class ModbusRtuFraming
/// The frame was a CRC-valid Modbus exception PDU (high bit set on the function code).
/// </exception>
public static async Task<byte[]> ReadResponsePduAsync(
Stream stream, byte expectedUnit, CancellationToken ct)
Stream stream, byte expectedUnit, CancellationToken ct, byte[]? requestPdu = null)
{
// R07:L5: the whole frame is read into ONE pooled buffer and validated in place; only the returned PDU is
// allocated (it used to be five arrays: header, byteCount, rest, the reassembled frame and the PDU).
@@ -137,7 +145,7 @@ public static class ModbusRtuFraming
}
await ReadExactlyAsync(stream, frame.AsMemory(already, length - already), ct).ConfigureAwait(false);
return ValidateAndStrip(expectedUnit, frame.AsSpan(0, length));
return ValidateAndStrip(expectedUnit, frame.AsSpan(0, length), requestPdu);
}
finally
{
@@ -150,7 +158,7 @@ public static class ModbusRtuFraming
/// against <paramref name="expectedUnit"/> and strips <c>addr</c> + <c>CRC</c> to return the bare PDU.
/// A CRC-valid exception PDU throws <see cref="ModbusException"/>.
/// </summary>
private static byte[] ValidateAndStrip(byte expectedUnit, ReadOnlySpan<byte> frame)
private static byte[] ValidateAndStrip(byte expectedUnit, ReadOnlySpan<byte> frame, byte[]? requestPdu)
{
// CRC covers everything except the trailing 2 CRC bytes.
var body = frame[..^2];
@@ -173,6 +181,8 @@ public static class ModbusRtuFraming
// Bare PDU = frame minus leading addr and trailing CRC.
var pdu = body[1..].ToArray();
if (requestPdu is { Length: > 0 }) CorrelateWithRequest(requestPdu, pdu);
// Exception PDU: high bit set on the function code. The CRC already validated, so this is a
// coherent protocol-level error — surface the ORIGINAL function code (fc & 0x7F).
if ((pdu[0] & 0x80) != 0)
@@ -185,6 +195,30 @@ public static class ModbusRtuFraming
return pdu;
}
/// <summary>
/// #1029: checks a CRC-valid, correctly-addressed reply against the request it must answer. Runs BEFORE the
/// exception-PDU throw, so a stale exception reply for another function is a desync, not a
/// <see cref="ModbusException"/> attributed to this request.
/// </summary>
private static void CorrelateWithRequest(byte[] request, byte[] response)
{
var requestFc = request[0];
var responseFc = (byte)(response[0] & 0x7F);
if (responseFc != requestFc)
throw new ModbusTransportDesyncException(
ModbusTransportDesyncException.DesyncReason.ResponseMismatch,
$"Modbus RTU response function code 0x{response[0]:X2} does not answer the request (fc 0x{requestFc:X2})");
// A write reply echoes the start address (bytes 1-2 of the PDU). The exception frame has no address.
if ((response[0] & 0x80) == 0
&& requestFc is 0x05 or 0x06 or 0x0F or 0x10
&& request.Length >= 3 && response.Length >= 3
&& (request[1] != response[1] || request[2] != response[2]))
throw new ModbusTransportDesyncException(
ModbusTransportDesyncException.DesyncReason.ResponseMismatch,
$"Modbus RTU write echo address {(response[1] << 8) | response[2]} does not match the request's {(request[1] << 8) | request[2]}");
}
/// <summary>
/// Fills <paramref name="buf"/> completely from <paramref name="stream"/>, throwing a
/// truncation desync if the stream ends first. Mirrors
@@ -178,7 +178,7 @@ public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
// Framing owns the length-less RTU deframe + CRC + unit-address validation. A CRC-valid
// exception PDU throws ModbusException (socket still coherent — propagates, no teardown);
// truncation / CRC / unit-mismatch throw ModbusTransportDesyncException.
return await ModbusRtuFraming.ReadResponsePduAsync(stream, unitId, cts.Token).ConfigureAwait(false);
return await ModbusRtuFraming.ReadResponsePduAsync(stream, unitId, cts.Token, pdu).ConfigureAwait(false);
}
catch (ModbusTransportDesyncException)
{
@@ -204,7 +204,12 @@ public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
// request on this socket would read that stale reply as its own answer (valid CRC, same unit) and
// publish it Good. Discard the socket; the next call re-dials. A ModbusException is a CRC-valid
// exception PDU: the frame was fully consumed, the socket is coherent, so it is excluded.
if (_life is not null) await _life.TearDownAsync().ConfigureAwait(false);
// A caller cancel is OUR abandonment, not a link fault: with auto-reconnect off it still owes one redial (#1055).
if (_life is not null)
{
if (ex is OperationCanceledException) await _life.DiscardAsync().ConfigureAwait(false);
else await _life.TearDownAsync().ConfigureAwait(false);
}
throw;
}
finally
@@ -146,9 +146,21 @@ public sealed class ModbusSocketLifecycle : IAsyncDisposable
public async Task EnsureConnectedAsync(CancellationToken ct)
{
if (_stream is not null) return;
var redialAfterDiscard = _redialAfterDiscard;
_redialAfterDiscard = false;
if (!_autoReconnect)
throw new ModbusTransportUnavailableException(
$"Modbus transport to {_host}:{_port} is not connected and auto-reconnect is disabled");
{
if (!redialAfterDiscard)
throw new ModbusTransportUnavailableException(
$"Modbus transport to {_host}:{_port} is not connected and auto-reconnect is disabled");
// #1055: the socket was discarded by US (a caller-cancelled RTU transaction), not lost to a fault —
// one fresh dial is owed even with auto-reconnect off, otherwise a single unsubscribe/probe cancel
// would leave the transport dead until the 90 s comms-loss watchdog re-initialised the driver. A
// failed dial just throws; the allowance is spent, so a dead device stays "not connected".
await ConnectAsync(ct).ConfigureAwait(false);
return;
}
var now = NowMs();
if (now < _connectNotBeforeMs)
@@ -198,6 +210,21 @@ public sealed class ModbusSocketLifecycle : IAsyncDisposable
/// <summary>Records that a transaction just succeeded, resetting the idle-disconnect clock.</summary>
public void MarkSuccess() => _lastSuccessUtc = DateTime.UtcNow;
// Guarded by the composing transport's single-flight gate, like the throttle state above.
private bool _redialAfterDiscard;
/// <summary>
/// Discards the current socket because THIS side abandoned a transaction (a caller cancel with a reply possibly in
/// flight) — not because the link failed. Unlike <see cref="TearDownAsync"/> it grants the next
/// <see cref="EnsureConnectedAsync"/> exactly one dial even when auto-reconnect is disabled (#1055).
/// </summary>
/// <returns>A task representing the asynchronous teardown operation.</returns>
public async Task DiscardAsync()
{
await TearDownAsync().ConfigureAwait(false);
_redialAfterDiscard = true;
}
/// <summary>Tears down the current socket + stream, leaving the lifecycle ready to reconnect.</summary>
/// <returns>A task representing the asynchronous teardown operation.</returns>
public async Task TearDownAsync()
@@ -42,6 +42,12 @@ public sealed class ModbusTransportDesyncException : IOException
/// RS-485 multi-drop bus, a reply from the wrong slave.
/// </summary>
UnitMismatch,
/// <summary>
/// A CRC-valid reply from the addressed unit answered a different request than the one in flight — its
/// function code (or, for a write echo, its start address) differs from the request's (#1029).
/// </summary>
ResponseMismatch,
}
/// <summary>Gets the reason the socket was classified desynchronized.</summary>
@@ -46,7 +46,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// type stays free of driver bookkeeping.
/// </summary>
/// <param name="map">The map just built from the live session.</param>
private void RecordSkippedTags(NamespaceMap map)
internal void RecordSkippedTags(NamespaceMap map)
{
var authored = _options.RawTags;
_skippedTags.BeginRebuild(authored.Count);
@@ -2128,6 +2128,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
foreach (var pair in itemHandlers)
if (RejectedMonitoredItemStatus(pair.Item) is { } refused)
rejected.Add(new RejectedItem(RefOf(pair.Item), refused, $"the server refused the monitored item (0x{refused:X8})"));
// #1039: a ref a LATER subscribe now serves stops being reported skipped (the report is re-asserted from the
// refusals of each subscribe, so a fixed upstream node drops off it).
if (rejected.Count == 0) { foreach (var fullRef in fullReferences) _skippedTags.Withdraw(fullRef); }
else
{
var refused = rejected.Select(r => r.Ref).ToHashSet(StringComparer.Ordinal);
foreach (var fullRef in fullReferences)
if (!refused.Contains(fullRef)) _skippedTags.Withdraw(fullRef);
}
}
}
@@ -2160,6 +2170,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
internal void ReportRejectedItems(ISubscriptionHandle handle, IReadOnlyList<RejectedItem> rejected)
{
var now = Clock.GetUtcNow().UtcDateTime;
// #1039: the same refusals ride the skipped-tag report (/hosts), so an operator sees them without the log.
foreach (var r in rejected) _skippedTags.Append(r.Ref, r.Why);
lock (_deliveryLock)
{
foreach (var r in rejected)
@@ -143,7 +143,7 @@ public sealed class OpcUaClientDriverProbe : IDriverProbe
DisableHiResClock = true,
};
private static (string host, int port, string endpointUrl) ExtractTarget(OpcUaClientDriverOptions opts)
internal static (string host, int port, string endpointUrl) ExtractTarget(OpcUaClientDriverOptions opts)
{
// EndpointUrls wins over the convenience EndpointUrl when both are set.
var endpointUrl = opts.EndpointUrls.FirstOrDefault()
@@ -154,7 +154,11 @@ public sealed class OpcUaClientDriverProbe : IDriverProbe
if (!Uri.TryCreate(endpointUrl, UriKind.Absolute, out var uri))
return (string.Empty, 0, string.Empty);
var host = uri.Host;
// IdnHost, not Host: Uri.Host drops an IPv6 zone index (#819), so a link-local endpoint was dialled zone-less and
// failed the preflight as "Connect failed" before any OPC UA traffic. IdnHost is what the SDK's own transport
// dials (and it carries no brackets, which Socket.ConnectAsync's host overload does not want). An RFC 6874 "%25"
// delimiter is normalised to the "%" the socket layer expects.
var host = uri.IdnHost.Replace("%25", "%", StringComparison.Ordinal);
var port = uri.IsDefaultPort ? 4840 : uri.Port;
return (host, port, endpointUrl);
}
@@ -617,6 +617,18 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
var (value, status) = await client.ReadValueAsync(
e.Tag.SymbolName, def.DataType, e.Tag.BitIndex, def.ArrayLength, cancellationToken)
.ConfigureAwait(false);
if (IsRetiredClient(device, client))
{
// #1035: the symbol table was invalidated (or the client replaced) WHILE this read was in flight, so the
// value was addressed through an IndexGroup/IndexOffset resolved before the program change — it could be
// other memory. Discard it and read once on a fresh client; if that one is retired too, answer Bad for
// this poll (no health write: nothing about the device's comms was learned) rather than publish it.
client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false);
(value, status) = await client.ReadValueAsync(
e.Tag.SymbolName, def.DataType, e.Tag.BitIndex, def.ArrayLength, cancellationToken)
.ConfigureAwait(false);
if (IsRetiredClient(device, client)) return CommsBad(now);
}
var snapshot = CompleteRead(e, value, status, now, batch);
if (IsCommsStatus(status)) await VerifyDeviceAsync(device, client, batch, cancellationToken).ConfigureAwait(false);
return snapshot;
@@ -632,6 +644,13 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
}
}
/// <summary>
/// True when <paramref name="client"/> is no longer the device's usable client: its symbol table was invalidated
/// (<see cref="DeviceState.StaleClient"/>) or a reconnect replaced it while a call was in flight.
/// </summary>
private static bool IsRetiredClient(DeviceState device, ITwinCATClient client) =>
ReferenceEquals(device.StaleClient, client) || !ReferenceEquals(device.Client, client);
/// <summary>
/// After a comms-class failure, asks the device for its ADS state once per call: no answer ⇒ the device is
/// gone and its remaining tags fail fast; an answer ⇒ the failure was that one tag's (a slow / oversized
@@ -785,6 +804,18 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
"is not working on this target; this warning is logged once per device",
_driverInstanceId, device.Options.HostAddress, client.LastSumFallbackCode);
}
if (IsRetiredClient(device, client))
{
// #1035: retired while the sum-read was in flight — its values are not trustworthy; re-read each tag
// singly (ReadOneAsync repeats this check and reconnects).
for (var k = 0; k < count; k++)
{
var e = bucket[start + k];
results[e.Index] = await ReadOneAsync(e, device, now, batch, cancellationToken).ConfigureAwait(false);
}
continue;
}
var anyComms = false;
for (var k = 0; k < count; k++)
{
@@ -838,6 +869,13 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
ArgumentNullException.ThrowIfNull(writes);
var results = new WriteResult[writes.Count];
// #1035: the per-call fail-fast verdict the read path has (P-3), for writes. A device that is gone costs ONE
// timeout per call — its remaining writes answer BadCommunicationError at once, with no wire attempt. A device
// the probe already counts as unreachable is never dialled; a comms failure is checked against the device's
// ADS state once per call (an answer = that one write's fault, its siblings still go out).
HashSet<DeviceState> unreachable = [];
HashSet<DeviceState> verified = [];
for (var i = 0; i < writes.Count; i++)
{
var w = writes[i];
@@ -870,6 +908,13 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
? TwinCATArrayCodec.ToWriteElements(def.DataType, w.Value, arrayLength)
: null;
if (device.ConsecutiveProbeFailures >= ProbeFailuresBeforeDegraded) unreachable.Add(device);
if (unreachable.Contains(device))
{
results[i] = new WriteResult(TwinCATStatusMapper.BadCommunicationError);
continue;
}
var client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false);
// BOOL-within-word write — a read-modify-write of the parent word at the parent's OWN
@@ -892,6 +937,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
gate.Release();
}
NoteWriteOutcome(device, results[i].StatusCode, w.FullReference);
if (IsCommsStatus(results[i].StatusCode))
await NoteWriteCommsFailureAsync(device, client, verified, unreachable, cancellationToken).ConfigureAwait(false);
continue;
}
@@ -903,6 +950,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
results[i] = new WriteResult(await client.WriteArrayAsync(
symbolName, def.DataType, elements, cancellationToken).ConfigureAwait(false));
NoteWriteOutcome(device, results[i].StatusCode, w.FullReference);
if (IsCommsStatus(results[i].StatusCode))
await NoteWriteCommsFailureAsync(device, client, verified, unreachable, cancellationToken).ConfigureAwait(false);
continue;
}
@@ -910,6 +959,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
symbolName, def.DataType, tag.BitIndex, w.Value, cancellationToken).ConfigureAwait(false);
results[i] = new WriteResult(status);
NoteWriteOutcome(device, status, w.FullReference);
if (IsCommsStatus(status))
await NoteWriteCommsFailureAsync(device, client, verified, unreachable, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) { throw; }
catch (NotSupportedException)
@@ -930,12 +981,39 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
{
results[i] = new WriteResult(TwinCATStatusMapper.BadCommunicationError);
MarkCommsFault(ex.Message, device);
// No live client = the connect itself failed or was throttled: the device is unreachable.
await NoteWriteCommsFailureAsync(
device, device.Client is { IsConnected: true } live ? live : null, verified, unreachable,
cancellationToken).ConfigureAwait(false);
}
}
return results;
}
/// <summary>
/// After a comms-class write failure, asks the device for its ADS state once per call: no answer (or no client at
/// all) ⇒ the device is gone and its remaining writes fail fast; an answer ⇒ the failure was that one write's.
/// </summary>
private async Task NoteWriteCommsFailureAsync(DeviceState device, ITwinCATClient? client,
HashSet<DeviceState> verified, HashSet<DeviceState> unreachable, CancellationToken cancellationToken)
{
if (unreachable.Contains(device)) return;
if (client is null)
{
unreachable.Add(device);
return;
}
if (!verified.Add(device)) return;
if (!await DeviceStillAnswersAsync(client, cancellationToken).ConfigureAwait(false))
{
unreachable.Add(device);
_logger.LogDebug(
"TwinCAT driver '{DriverInstanceId}' device '{HostAddress}' did not answer its state after a failed write; " +
"its remaining writes fail fast for this call", _driverInstanceId, device.Options.HostAddress);
}
}
// ---- ITagDiscovery ----
/// <inheritdoc />