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:
@@ -840,6 +840,14 @@ NodeIds moved together in every leg. Fixture containers were restored healthy af
|
||||
baseline, where several states are simultaneously active, and only to CONDITION observations. A `/sample` chunk is a
|
||||
time-ordered delta, so it is last-wins: Fault then Normal reads Normal, Fault then UNAVAILABLE reads
|
||||
`BadNoCommunication`. (The native-alarm path never had the problem — `MTConnectConditionTracker`.)
|
||||
**Follow-up (#1037/#1055):** the value word is now DERIVED from the tracker (`MTConnectObservationIndex.Apply(..., conditions)`;
|
||||
the driver folds the tracker first), so it is the most severe still-active `nativeCode` across chunks: Fault(A) then
|
||||
Warning(B) — in one chunk or two — reads Fault, and clearing A leaves B's Warning. A document with no tracker (the
|
||||
index's own unit tests) keeps the per-document reconcile above.
|
||||
- **Malformed observation, per item (#1055).** An observation skipped for a missing/unparseable `timestamp` still names its
|
||||
`dataItemId`; the result carries it in `MalformedDataItemIds` and the index marks that item `BadDecodingError` (published to
|
||||
its subscribers) until a valid observation replaces it — the last Good value no longer stands forever. One with no
|
||||
`dataItemId` cannot be attributed and is only counted.
|
||||
- **M-5 — subscription leak.** `ShutdownAsync` releases every data and alarm subscription. The host actor abandons its
|
||||
handles on each reconnect/Force Reconnect and re-subscribes after the next init, so the old registrations used to pile up
|
||||
(one per cycle: an extra callback per observation and a pump that never stopped). `InitializeAsync` deliberately does
|
||||
|
||||
@@ -436,8 +436,10 @@ initialise (the AdminUI form drops them on the next save). Pinned by
|
||||
> resolve to an upstream node id (`BadNodeIdInvalid`, no wire call) or the server refused the create (`BadNodeIdUnknown`,
|
||||
> `BadAttributeIdInvalid`, … — `CreateItemsAsync` reports these on the item's status, it does not throw) — is published
|
||||
> **Bad once with that code** and counted in ONE summarised Warning (G-12); it used to sit silently at the host's last
|
||||
> stamp, `BadNoCommunication`, pointing at comms rather than the address. (It is not added to the skipped-tag report, which
|
||||
> is an init-time snapshot.) The recovery / reconcile re-publish finds a ref's subscriptions through a per-subscription ref
|
||||
> stamp, `BadNoCommunication`, pointing at comms rather than the address. (#1039: it is also appended to the skipped-tag
|
||||
> report through `SkippedTagLedger.Append` — once per path however often the subscribe is retried, withdrawn by a later
|
||||
> subscribe that gets the item, and cleared by the next re-initialise's rebuild, which re-appends what is still refused.
|
||||
> The TCP preflight of Test Connect dials `Uri.IdnHost`, so a zone-qualified IPv6 endpoint keeps its zone.) The recovery / reconcile re-publish finds a ref's subscriptions through a per-subscription ref
|
||||
> set, not a scan of every monitored item under the delivery lock (G-10: 20k refs went from ~6 s to ~1 s). `UnsubscribeAsync` /
|
||||
> `UnsubscribeAlarmsAsync` leave the subscription tracked until they hold the subscription gate; if the wait is **cancelled**
|
||||
> (the host's 5 s unsubscribe token vs a slow `ConditionRefresh`), the handlers are detached synchronously — nothing more is
|
||||
|
||||
@@ -337,6 +337,14 @@ client, and its 2 s used to silently override a raised driver `Timeout` for ever
|
||||
and the rest of that device's tags fail fast with no wire attempt, an answer and the failure was that one
|
||||
tag's. A device the probe already counts unreachable (3 failed ticks) fails fast outright. A native subscribe
|
||||
applies the same rule. Health is applied once per device per call (P-19), still Degraded on a comms failure.
|
||||
**Writes get the same per-call verdict (#1035):** the first comms-class write failure is state-checked once per
|
||||
device, and a gone (or never-connected / probe-unreachable) device's remaining writes answer `BadCommunicationError`
|
||||
with no wire attempt — a 10-write batch used to pay the timeout ten times. And a read already in flight when the
|
||||
client is retired (symbol-table invalidation / reconnect) is discarded and re-read once on a fresh client rather than
|
||||
published from the retired symbol cache (a sum-read chunk falls back to single reads). A retirement landing after
|
||||
the read returned is still the P-1 window; writes cannot be un-sent and are not re-run. Hardware gate: stop the PLC
|
||||
runtime/route mid-batch on a real device and confirm the batch returns in ~one timeout, and an online change during a
|
||||
slow read never publishes a pre-change value.
|
||||
- **The probe does not replay against an offline PLC (P-4).** The probe connects without replaying the stored
|
||||
registrations, probes, and re-registers them only after the device answered; a replay that hits a dead device
|
||||
stops dialling it. While the device is down the registrations publish `BadCommunicationError` once and one
|
||||
|
||||
@@ -124,6 +124,16 @@ public sealed class SkippedTagLedger
|
||||
private int _stagedAuthored;
|
||||
private int _stagedSkipped;
|
||||
private List<SkippedTag>? _stagedSample;
|
||||
private HashSet<string>? _stagedPaths;
|
||||
|
||||
// What the VISIBLE report was built from, kept so a late Append / Withdraw can recompute it (#1039).
|
||||
private int _builtAuthored;
|
||||
private int _builtSkipped;
|
||||
private List<SkippedTag> _builtSample = [];
|
||||
private HashSet<string> _builtPaths = [];
|
||||
|
||||
/// <summary>Skips noticed AFTER the build (a subscribe-time refusal), in encounter order. Reset by every rebuild.</summary>
|
||||
private readonly List<SkippedTag> _appended = [];
|
||||
|
||||
/// <summary>
|
||||
/// Starts staging a new tag-table build. The visible snapshot is left alone until
|
||||
@@ -137,6 +147,7 @@ public sealed class SkippedTagLedger
|
||||
_stagedAuthored = authoredCount;
|
||||
_stagedSkipped = 0;
|
||||
_stagedSample = new List<SkippedTag>(Math.Min(authoredCount, MaxSample));
|
||||
_stagedPaths = new HashSet<string>(StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,11 +165,75 @@ public sealed class SkippedTagLedger
|
||||
{
|
||||
if (_stagedSample is null) return;
|
||||
_stagedSkipped++;
|
||||
_stagedPaths?.Add(rawPath ?? "");
|
||||
if (_stagedSample.Count < MaxSample)
|
||||
_stagedSample.Add(new SkippedTag(rawPath ?? "", reason ?? ""));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a skip that was only discovered AFTER the build, against the already-visible report (#1039) — e.g. the
|
||||
/// upstream server refusing a monitored item at subscribe time. The build-time skips are authored-config
|
||||
/// problems; this is the same operator signal for a tag that only fails once the driver dials the device. Idempotent
|
||||
/// per raw path (a subscribe retried every health tick must not inflate the count); a path the build already
|
||||
/// skipped is not counted twice. A no-op before the first <see cref="Commit"/> ("no answer yet" is never turned
|
||||
/// into a report), and cleared by the next <see cref="BeginRebuild"/>/<see cref="Commit"/> — a re-initialise
|
||||
/// re-subscribes and re-appends what is still refused.
|
||||
/// </summary>
|
||||
/// <param name="rawPath">The authored raw path that was refused.</param>
|
||||
/// <param name="reason">Operator-facing reason; should name the offending status.</param>
|
||||
/// <returns><see langword="true"/> when the report changed.</returns>
|
||||
public bool Append(string rawPath, string reason)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_visible is null) return false;
|
||||
rawPath ??= "";
|
||||
if (_builtPaths.Contains(rawPath)) return false;
|
||||
var existing = _appended.FindIndex(s => string.Equals(s.RawPath, rawPath, StringComparison.Ordinal));
|
||||
if (existing >= 0)
|
||||
{
|
||||
if (_appended[existing].Reason == (reason ?? "")) return false;
|
||||
_appended[existing] = new SkippedTag(rawPath, reason ?? "");
|
||||
}
|
||||
else
|
||||
{
|
||||
_appended.Add(new SkippedTag(rawPath, reason ?? ""));
|
||||
}
|
||||
Republish();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Withdraws a skip recorded by <see cref="Append"/> — the ref now has its upstream item (a later subscribe
|
||||
/// succeeded), so it must stop being reported. Build-time skips are never withdrawn.
|
||||
/// </summary>
|
||||
/// <param name="rawPath">The raw path that is no longer refused.</param>
|
||||
/// <returns><see langword="true"/> when the report changed.</returns>
|
||||
public bool Withdraw(string rawPath)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_appended.Count == 0) return false;
|
||||
var removed = _appended.RemoveAll(s => string.Equals(s.RawPath, rawPath ?? "", StringComparison.Ordinal)) > 0;
|
||||
if (removed) Republish();
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the visible report from the committed build + the appended skips. Caller holds the gate.</summary>
|
||||
private void Republish()
|
||||
{
|
||||
var sample = new List<SkippedTag>(_builtSample);
|
||||
foreach (var a in _appended)
|
||||
{
|
||||
if (sample.Count >= MaxSample) break;
|
||||
sample.Add(a);
|
||||
}
|
||||
_visible = new SkippedTagReport(_builtAuthored, _builtSkipped + _appended.Count, sample);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes the staged build as the visible snapshot, atomically. A call with no staged build
|
||||
/// is a no-op.
|
||||
@@ -168,8 +243,14 @@ public sealed class SkippedTagLedger
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stagedSample is null) return;
|
||||
_visible = new SkippedTagReport(_stagedAuthored, _stagedSkipped, _stagedSample);
|
||||
_builtAuthored = _stagedAuthored;
|
||||
_builtSkipped = _stagedSkipped;
|
||||
_builtSample = _stagedSample;
|
||||
_builtPaths = _stagedPaths ?? [];
|
||||
_appended.Clear();
|
||||
_visible = new SkippedTagReport(_stagedAuthored, _stagedSkipped, _builtSample);
|
||||
_stagedSample = null;
|
||||
_stagedPaths = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 />
|
||||
|
||||
@@ -235,4 +235,102 @@ public sealed class SkippedTagLedgerTests
|
||||
|
||||
await Task.WhenAll(writer, reader);
|
||||
}
|
||||
|
||||
// ── #1039: skips discovered AFTER the build (a subscribe-time refusal) ────────────────────────────────────
|
||||
|
||||
private static SkippedTagLedger Built(int authored, params string[] skipped)
|
||||
{
|
||||
var ledger = new SkippedTagLedger();
|
||||
ledger.BeginRebuild(authored);
|
||||
foreach (var s in skipped) ledger.Skip(s, "build reason");
|
||||
ledger.Commit();
|
||||
return ledger;
|
||||
}
|
||||
|
||||
/// <summary>An appended skip changes the visible report: the true count grows, the sample carries it, the denominator is unchanged.</summary>
|
||||
[Fact]
|
||||
public void Append_adds_a_late_skip_to_the_visible_report()
|
||||
{
|
||||
var ledger = Built(5, "a");
|
||||
|
||||
ledger.Append("b", "server refused 0x80340000").ShouldBeTrue();
|
||||
|
||||
var report = ledger.Snapshot()!;
|
||||
report.AuthoredCount.ShouldBe(5);
|
||||
report.SkippedCount.ShouldBe(2);
|
||||
report.Sample.Select(s => (s.RawPath, s.Reason)).ShouldBe([("a", "build reason"), ("b", "server refused 0x80340000")]);
|
||||
}
|
||||
|
||||
/// <summary>Idempotent per path (a retried subscribe), and a path the build already skipped is never double counted.</summary>
|
||||
[Fact]
|
||||
public void Append_is_idempotent_per_path_and_never_double_counts_a_build_skip()
|
||||
{
|
||||
var ledger = Built(5, "a");
|
||||
|
||||
ledger.Append("b", "why").ShouldBeTrue();
|
||||
ledger.Append("b", "why").ShouldBeFalse("the same refusal again is not a change");
|
||||
ledger.Append("a", "why").ShouldBeFalse("the build already reported this path");
|
||||
|
||||
ledger.Snapshot()!.SkippedCount.ShouldBe(2);
|
||||
|
||||
// A changed reason for an appended path replaces it rather than adding a second entry.
|
||||
ledger.Append("b", "different why").ShouldBeTrue();
|
||||
var report = ledger.Snapshot()!;
|
||||
report.SkippedCount.ShouldBe(2);
|
||||
report.Sample.Single(s => s.RawPath == "b").Reason.ShouldBe("different why");
|
||||
}
|
||||
|
||||
/// <summary>The count stays exact past the cap; only the detail list is capped, build skips first.</summary>
|
||||
[Fact]
|
||||
public void Append_keeps_the_count_exact_and_the_sample_capped()
|
||||
{
|
||||
var ledger = Built(100, Enumerable.Range(0, SkippedTagLedger.MaxSample - 1).Select(i => $"b{i}").ToArray());
|
||||
|
||||
for (var i = 0; i < 10; i++) ledger.Append($"late{i}", "why");
|
||||
|
||||
var report = ledger.Snapshot()!;
|
||||
report.SkippedCount.ShouldBe(SkippedTagLedger.MaxSample - 1 + 10);
|
||||
report.Sample.Count.ShouldBe(SkippedTagLedger.MaxSample);
|
||||
report.Sample[SkippedTagLedger.MaxSample - 1].RawPath.ShouldBe("late0");
|
||||
}
|
||||
|
||||
/// <summary>Withdraw removes an appended skip (the ref is served now) but never a build-time one.</summary>
|
||||
[Fact]
|
||||
public void Withdraw_removes_only_appended_skips()
|
||||
{
|
||||
var ledger = Built(5, "a");
|
||||
ledger.Append("b", "why");
|
||||
|
||||
ledger.Withdraw("b").ShouldBeTrue();
|
||||
ledger.Withdraw("b").ShouldBeFalse();
|
||||
ledger.Withdraw("a").ShouldBeFalse("a build-time skip is not the subscribe's to withdraw");
|
||||
|
||||
var report = ledger.Snapshot()!;
|
||||
report.SkippedCount.ShouldBe(1);
|
||||
report.Sample.ShouldHaveSingleItem().RawPath.ShouldBe("a");
|
||||
}
|
||||
|
||||
/// <summary>A rebuild starts over: appended skips are dropped at commit, and an in-flight rebuild does not leak them early.</summary>
|
||||
[Fact]
|
||||
public void A_rebuild_clears_appended_skips_only_at_commit()
|
||||
{
|
||||
var ledger = Built(5, "a");
|
||||
ledger.Append("b", "why");
|
||||
|
||||
ledger.BeginRebuild(5);
|
||||
ledger.Snapshot()!.SkippedCount.ShouldBe(2, "the previous complete answer stands until the rebuild commits");
|
||||
ledger.Commit();
|
||||
|
||||
ledger.Snapshot()!.SkippedCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
/// <summary>"No answer yet" is never turned into a report by a late skip.</summary>
|
||||
[Fact]
|
||||
public void Append_before_any_build_is_a_no_op()
|
||||
{
|
||||
var ledger = new SkippedTagLedger();
|
||||
|
||||
ledger.Append("x", "why").ShouldBeFalse();
|
||||
ledger.Snapshot().ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
+68
@@ -826,6 +826,74 @@ public sealed class MTConnectObservationIndexTests
|
||||
idx.Get("e").Value.ShouldBe("Normal");
|
||||
}
|
||||
|
||||
private static MTConnectObservation CondCode(string state, string code, int second) =>
|
||||
new("c", state, new DateTime(2026, 7, 24, 12, 0, second, DateTimeKind.Utc),
|
||||
Condition: new MTConnectConditionDetail(null, code, null, null, null));
|
||||
|
||||
/// <summary>#1037: the value word comes from the tracker, so two codes in one chunk read the most severe, not the last.</summary>
|
||||
[Fact]
|
||||
public void With_a_tracker_two_codes_in_one_chunk_read_the_most_severe()
|
||||
{
|
||||
var idx = new MTConnectObservationIndex([new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]);
|
||||
var tracker = new MTConnectConditionTracker();
|
||||
var chunk = new MTConnectStreamsResult(1L, 3L, 1L, [CondCode("Fault", "A", 0), CondCode("Warning", "B", 1)]);
|
||||
|
||||
tracker.Apply(chunk, baseline: false);
|
||||
idx.Apply(chunk, baseline: false, tracker);
|
||||
|
||||
idx.Get("c").Value.ShouldBe("Fault");
|
||||
// Control: with no tracker the per-document reconcile is last-wins (unchanged behaviour).
|
||||
var bare = new MTConnectObservationIndex([new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]);
|
||||
bare.Apply(chunk);
|
||||
bare.Get("c").Value.ShouldBe("Warning");
|
||||
}
|
||||
|
||||
/// <summary>#1037: across chunks, a Warning on B does not mask A's Fault, and clearing A leaves B's Warning.</summary>
|
||||
[Fact]
|
||||
public void With_a_tracker_a_later_chunk_cannot_mask_a_still_active_fault()
|
||||
{
|
||||
var idx = new MTConnectObservationIndex([new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]);
|
||||
var tracker = new MTConnectConditionTracker();
|
||||
|
||||
void Feed(params MTConnectObservation[] o)
|
||||
{
|
||||
var doc = new MTConnectStreamsResult(1L, 3L, 1L, o);
|
||||
tracker.Apply(doc, baseline: false);
|
||||
idx.Apply(doc, baseline: false, tracker);
|
||||
}
|
||||
|
||||
Feed(CondCode("Fault", "A", 0));
|
||||
Feed(CondCode("Warning", "B", 1));
|
||||
idx.Get("c").Value.ShouldBe("Fault");
|
||||
Feed(CondCode("Normal", "A", 2));
|
||||
idx.Get("c").Value.ShouldBe("Warning");
|
||||
Feed(CondCode("Normal", "B", 3));
|
||||
idx.Get("c").Value.ShouldBe("Normal");
|
||||
Feed(CondCode("Fault", "A", 4));
|
||||
Feed(new MTConnectObservation("c", "UNAVAILABLE", new DateTime(2026, 7, 24, 12, 0, 5, DateTimeKind.Utc),
|
||||
Condition: new MTConnectConditionDetail(null, null, null, null, null)));
|
||||
idx.Get("c").StatusCode.ShouldBe(BadNoCommunication);
|
||||
}
|
||||
|
||||
/// <summary>#1055: a skipped observation that named its item turns it BadDecodingError; a valid one in the same document wins.</summary>
|
||||
[Fact]
|
||||
public void A_malformed_data_item_reads_BadDecodingError_and_a_valid_observation_replaces_it()
|
||||
{
|
||||
var idx = new MTConnectObservationIndex([Tag("x", DriverDataType.Int64), Tag("y", DriverDataType.Int64)]);
|
||||
idx.Apply(new MTConnectStreamsResult(1L, 3L, 1L, [
|
||||
new MTConnectObservation("x", "1", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)),
|
||||
new MTConnectObservation("y", "1", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)),
|
||||
]));
|
||||
|
||||
idx.Apply(new MTConnectStreamsResult(1L, 4L, 1L, [
|
||||
new MTConnectObservation("y", "2", new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)),
|
||||
], null, 2, "bad", ["x", "y"]));
|
||||
|
||||
idx.Get("x").StatusCode.ShouldBe(0x80070000u);
|
||||
idx.Get("y").Value.ShouldBe(2L);
|
||||
idx.Get("y").StatusCode.ShouldBe(Good);
|
||||
}
|
||||
|
||||
/// <summary>An active fault carries more information than "no value"; it outranks UNAVAILABLE.</summary>
|
||||
[Fact]
|
||||
public void An_active_fault_outranks_unavailable_within_one_apply()
|
||||
|
||||
+94
@@ -232,4 +232,98 @@ public sealed class MTConnectReview20261202Tests
|
||||
|
||||
await driver.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------ #1037 / #1055 follow-ups
|
||||
|
||||
private static MTConnectDriverOptions CondOpts() =>
|
||||
new()
|
||||
{
|
||||
AgentUri = "http://fixture-agent:5000",
|
||||
RequestTimeoutMs = 5000,
|
||||
Tags =
|
||||
[
|
||||
new MTConnectTagDefinition("dev1_pos", DriverDataType.Float64),
|
||||
new MTConnectTagDefinition("dev1_execution", DriverDataType.String),
|
||||
new MTConnectTagDefinition("dev1_cond", DriverDataType.String, MtCategory: "CONDITION"),
|
||||
],
|
||||
};
|
||||
|
||||
private static MTConnectObservation CondObs(string state, string? code, int second) =>
|
||||
new("dev1_cond", state, ObservedAt.AddSeconds(second),
|
||||
Condition: new MTConnectConditionDetail(null, code, null, null, null));
|
||||
|
||||
/// <summary>
|
||||
/// #1037. The condition item's plain value tag is derived from the tracker: a Warning on code B in a LATER chunk must not
|
||||
/// mask the still-active Fault on code A, and clearing A then leaves B's Warning (not "Normal").
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_condition_value_tag_keeps_the_most_severe_active_code_across_chunks()
|
||||
{
|
||||
var client = CannedAgentClient.FromFixtures();
|
||||
var driver = new MTConnectDriver(CondOpts(), "mt1", _ => client);
|
||||
var seen = Record(driver);
|
||||
await driver.InitializeAsync("{}", Ct);
|
||||
await driver.SubscribeAsync(["dev1_cond"], TimeSpan.FromMilliseconds(50), Ct);
|
||||
|
||||
string? Latest() => seen.Where(e => e.FullReference == "dev1_cond").Select(e => e.Snapshot.Value as string).LastOrDefault();
|
||||
|
||||
await client.PumpAsync(new(FixtureInstanceId, 109, 108, [CondObs("Fault", "A", 1)])).WaitAsync(Watchdog, Ct);
|
||||
Latest().ShouldBe("Fault");
|
||||
|
||||
await client.PumpAsync(new(FixtureInstanceId, 110, 109, [CondObs("Warning", "B", 2)])).WaitAsync(Watchdog, Ct);
|
||||
Latest().ShouldBe("Fault", "a Warning on code B must not mask code A's still-active Fault");
|
||||
|
||||
await client.PumpAsync(new(FixtureInstanceId, 111, 110, [CondObs("Normal", "A", 3)])).WaitAsync(Watchdog, Ct);
|
||||
Latest().ShouldBe("Warning", "code B is still active");
|
||||
|
||||
await client.PumpAsync(new(FixtureInstanceId, 112, 111, [CondObs("Normal", "B", 4)])).WaitAsync(Watchdog, Ct);
|
||||
Latest().ShouldBe("Normal");
|
||||
|
||||
await driver.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>#1037 / #1055: the SAME chunk carrying Fault(A) then Warning(B) reads Fault, not the last word.</summary>
|
||||
[Fact]
|
||||
public async Task Two_codes_in_one_chunk_read_the_most_severe_not_the_last()
|
||||
{
|
||||
var client = CannedAgentClient.FromFixtures();
|
||||
var driver = new MTConnectDriver(CondOpts(), "mt1", _ => client);
|
||||
var seen = Record(driver);
|
||||
await driver.InitializeAsync("{}", Ct);
|
||||
await driver.SubscribeAsync(["dev1_cond"], TimeSpan.FromMilliseconds(50), Ct);
|
||||
|
||||
await client.PumpAsync(new(FixtureInstanceId, 109, 108, [CondObs("Fault", "A", 1), CondObs("Warning", "B", 2)]))
|
||||
.WaitAsync(Watchdog, Ct);
|
||||
|
||||
seen.Where(e => e.FullReference == "dev1_cond").Last().Snapshot.Value.ShouldBe("Fault");
|
||||
|
||||
await driver.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1055. An observation skipped for an unparseable timestamp still names its item: the item must read
|
||||
/// BadDecodingError instead of its last Good value standing forever, and recover on the next valid observation.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_malformed_observation_marks_its_item_BadDecodingError_until_the_next_valid_one()
|
||||
{
|
||||
var client = CannedAgentClient.FromFixtures();
|
||||
var driver = new MTConnectDriver(Opts(), "mt1", _ => client);
|
||||
var seen = Record(driver);
|
||||
await driver.InitializeAsync("{}", Ct);
|
||||
await driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct);
|
||||
|
||||
await client.PumpAsync(Chunk(FixtureInstanceId, 108, 109, ("dev1_pos", "1.5"))).WaitAsync(Watchdog, Ct);
|
||||
seen.Where(e => e.FullReference == "dev1_pos").Last().Snapshot.StatusCode.ShouldBe(Good);
|
||||
|
||||
await client.PumpAsync(new(FixtureInstanceId, 110, 109, [], null, 1, "timestamp", ["dev1_pos"])).WaitAsync(Watchdog, Ct);
|
||||
seen.Where(e => e.FullReference == "dev1_pos").Last().Snapshot.StatusCode.ShouldBe(0x80070000u);
|
||||
|
||||
await client.PumpAsync(Chunk(FixtureInstanceId, 110, 111, ("dev1_pos", "2.5"))).WaitAsync(Watchdog, Ct);
|
||||
var recovered = seen.Where(e => e.FullReference == "dev1_pos").Last().Snapshot;
|
||||
recovered.StatusCode.ShouldBe(Good);
|
||||
recovered.Value.ShouldBe(2.5d);
|
||||
|
||||
await driver.ShutdownAsync(Ct);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,6 +503,20 @@ public sealed class MTConnectStreamsParseTests
|
||||
result.InstanceId.ShouldBe(1L);
|
||||
}
|
||||
|
||||
/// <summary>#1055: a skip that still names its item reports the id (so the index can mark it Bad); an id-less one cannot.</summary>
|
||||
[Theory]
|
||||
[InlineData("""<Position timestamp="2026-07-24T12:00:00Z">1</Position>""", null)] // no dataItemId: unattributable
|
||||
[InlineData("""<Position dataItemId="p">1</Position>""", "p")] // no timestamp
|
||||
[InlineData("""<Position dataItemId="p" timestamp="whenever">1</Position>""", "p")] // unparseable timestamp
|
||||
public void Parse_reports_the_data_item_of_a_skipped_observation_when_it_names_one(string observationXml, string? expectedId)
|
||||
{
|
||||
var result = MTConnectStreamsParser.Parse(StreamsDocument($"""<Samples>{observationXml}</Samples>"""));
|
||||
|
||||
result.SkippedObservations.ShouldBe(1);
|
||||
if (expectedId is null) result.MalformedDataItemIds.ShouldBeNull();
|
||||
else result.MalformedDataItemIds.ShouldBe([expectedId]);
|
||||
}
|
||||
|
||||
/// <summary>M-8 positive control: a clean document reports nothing skipped.</summary>
|
||||
[Fact]
|
||||
public void Parse_of_a_clean_document_reports_nothing_skipped()
|
||||
|
||||
@@ -175,4 +175,48 @@ public sealed class ModbusCallerCancelDesyncTests
|
||||
(await transport.SendAsync(1, ReadPdu(9), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
|
||||
server.Accepted.ShouldBe(1, "the teardown must be tied to the cancelled exit, not to every call");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1055: with auto-reconnect OFF a caller-cancelled RTU transaction used to leave the transport dead (the
|
||||
/// discarded socket was never re-dialled) until the 90 s watchdog re-initialised the driver. The discard was
|
||||
/// ours, so one redial is owed; a real link fault under auto-reconnect OFF must still stay down.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task RtuOverTcp_AutoReconnectOff_caller_cancel_still_redials_for_the_next_read()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var server = new LateReplyServer(rtu: true);
|
||||
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5), autoReconnect: false);
|
||||
await transport.ConnectAsync(ct);
|
||||
|
||||
using var cancel = new CancellationTokenSource();
|
||||
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
|
||||
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
||||
await cancel.CancelAsync();
|
||||
await Should.ThrowAsync<OperationCanceledException>(first);
|
||||
server.ReleaseFirst();
|
||||
|
||||
(await transport.SendAsync(1, ReadPdu(9), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
|
||||
server.Accepted.ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RtuOverTcp_AutoReconnectOff_link_fault_stays_down_and_the_cancel_allowance_is_spent_once()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var server = new LateReplyServer(rtu: true);
|
||||
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5), autoReconnect: false);
|
||||
await transport.ConnectAsync(ct);
|
||||
|
||||
using var cancel = new CancellationTokenSource();
|
||||
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
|
||||
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
||||
await cancel.CancelAsync();
|
||||
await Should.ThrowAsync<OperationCanceledException>(first);
|
||||
|
||||
// The device goes away: the one owed redial fails, and the next call must fail fast, not dial again.
|
||||
await server.DisposeAsync();
|
||||
await Should.ThrowAsync<SocketException>(transport.SendAsync(1, ReadPdu(9), ct));
|
||||
await Should.ThrowAsync<ModbusTransportUnavailableException>(transport.SendAsync(1, ReadPdu(9), ct));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,56 @@ public sealed class ModbusRtuFramingTests
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.TruncatedFrame);
|
||||
}
|
||||
|
||||
/// <summary>#1029: a CRC-valid reply from the right unit that answers a DIFFERENT function is a desync.</summary>
|
||||
[Fact]
|
||||
public async Task ReadResponse_response_function_code_not_matching_request_throws_desync()
|
||||
{
|
||||
var frame = ModbusCrc.Append(new byte[] { 0x01, 0x04, 0x02, 0x00, 0x0A }); // an FC04 reply...
|
||||
await using var s = Canned(frame);
|
||||
var ex = await Should.ThrowAsync<ModbusTransportDesyncException>(
|
||||
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken,
|
||||
new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 })); // ...to an FC03 request
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
|
||||
}
|
||||
|
||||
/// <summary>#1029: a stale exception reply for another function must not become this request's ModbusException.</summary>
|
||||
[Fact]
|
||||
public async Task ReadResponse_exception_for_another_function_throws_desync_not_ModbusException()
|
||||
{
|
||||
var frame = ModbusCrc.Append(new byte[] { 0x01, 0x86, 0x02 }); // exception for FC06
|
||||
await using var s = Canned(frame);
|
||||
var ex = await Should.ThrowAsync<ModbusTransportDesyncException>(
|
||||
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken,
|
||||
new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }));
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
|
||||
}
|
||||
|
||||
/// <summary>#1029: a write echo for another address is a stale reply, not this write's acknowledgement.</summary>
|
||||
[Theory]
|
||||
[InlineData((byte)0x06, new byte[] { 0x06, 0x00, 0x08, 0x00, 0x2A })]
|
||||
[InlineData((byte)0x10, new byte[] { 0x10, 0x00, 0x08, 0x00, 0x01 })]
|
||||
public async Task ReadResponse_write_echo_with_other_address_throws_desync(byte fc, byte[] echo)
|
||||
{
|
||||
await using var s = Canned(ModbusCrc.Append(new byte[] { 0x01 }.Concat(echo).ToArray()));
|
||||
var request = new byte[] { fc, 0x00, 0x07, 0x00, 0x2A };
|
||||
var ex = await Should.ThrowAsync<ModbusTransportDesyncException>(
|
||||
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken, request));
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
|
||||
}
|
||||
|
||||
/// <summary>Positive control for the three above: the matching reply and a matching exception still pass.</summary>
|
||||
[Fact]
|
||||
public async Task ReadResponse_matching_request_is_accepted_and_matching_exception_still_surfaces()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using (var s = Canned(ModbusCrc.Append(new byte[] { 0x01, 0x06, 0x00, 0x07, 0x00, 0x2A })))
|
||||
(await ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, ct, new byte[] { 0x06, 0x00, 0x07, 0x00, 0x2A }))
|
||||
.ShouldBe(new byte[] { 0x06, 0x00, 0x07, 0x00, 0x2A });
|
||||
await using (var s = Canned(ModbusCrc.Append(new byte[] { 0x01, 0x83, 0x02 })))
|
||||
await Should.ThrowAsync<ModbusException>(
|
||||
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, ct, new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A read-only test double that dribbles its backing bytes out at most <c>chunk</c> at a time
|
||||
/// per <see cref="ReadAsync(Memory{byte}, CancellationToken)"/> call, then returns 0 (EOF)
|
||||
|
||||
@@ -39,6 +39,17 @@ public sealed class ModbusRtuOverTcpTransportTests
|
||||
TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>#1029: the transport hands the request PDU to the deframer, so another request's reply is refused.</summary>
|
||||
[Fact]
|
||||
public async Task SendAsync_reply_to_a_different_function_is_a_desync()
|
||||
{
|
||||
var fake = new CapturingDuplexStream(ModbusCrc.Append(new byte[] { 0x01, 0x04, 0x02, 0x00, 0x0A }));
|
||||
await using var transport = ModbusRtuOverTcpTransport.ForTest(fake, TimeSpan.FromSeconds(2));
|
||||
var ex = await Should.ThrowAsync<ModbusTransportDesyncException>(
|
||||
transport.SendAsync(0x01, new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }, TestContext.Current.CancellationToken));
|
||||
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_stalled_gateway_hits_per_op_deadline()
|
||||
{
|
||||
|
||||
+55
@@ -189,4 +189,59 @@ public sealed class OpcUaClientDriverProbeTests
|
||||
}
|
||||
finally { listener.Stop(); }
|
||||
}
|
||||
|
||||
// ── #1039: zone-qualified IPv6 hosts reach the preflight with their zone ───────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The preflight dials the host <see cref="OpcUaClientDriverProbe.ExtractTarget"/> returns. .NET's
|
||||
/// <see cref="Uri.Host"/> drops an IPv6 zone index (#819), so a link-local <c>fe80::1%eth0</c> endpoint was dialled
|
||||
/// zone-less — unroutable, a false "Connect failed" before any OPC UA traffic. The host must carry the zone.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("opc.tcp://[fe80::1%eth0]:4841", "fe80::1%eth0", 4841)]
|
||||
[InlineData("opc.tcp://[fe80::1%4]:4841/Ua", "fe80::1%4", 4841)]
|
||||
// RFC 6874's encoded delimiter is accepted and normalised to the '%' the socket layer wants.
|
||||
[InlineData("opc.tcp://[fe80::1%25eth0]:4841", "fe80::1%eth0", 4841)]
|
||||
[InlineData("opc.tcp://[fe80::1%eth0]", "fe80::1%eth0", 4840)]
|
||||
// Positive controls: a zone-less literal and a name are unchanged.
|
||||
[InlineData("opc.tcp://[::1]:4841", "::1", 4841)]
|
||||
[InlineData("opc.tcp://plc-host:4841", "plc-host", 4841)]
|
||||
public void The_preflight_target_keeps_an_IPv6_zone_index(string endpointUrl, string expectedHost, int expectedPort)
|
||||
{
|
||||
var (host, port, url) = OpcUaClientDriverProbe.ExtractTarget(new OpcUaClientDriverOptions { EndpointUrl = endpointUrl });
|
||||
|
||||
host.ShouldBe(expectedHost);
|
||||
port.ShouldBe(expectedPort);
|
||||
url.ShouldBe(endpointUrl);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// End to end: a zone-qualified loopback literal reaches the preflight's socket connect (a listener that accepts
|
||||
/// then closes proves it dialled), so the failure is the discovery handshake, never "Connect failed".
|
||||
/// <c>::1%0</c> is a numeric zone that is valid everywhere an IPv6 socket is.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_zone_qualified_IPv6_literal_endpoint_passes_the_tcp_preflight()
|
||||
{
|
||||
if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host.");
|
||||
var listener = new TcpListener(IPAddress.IPv6Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
var testCt = TestContext.Current.CancellationToken;
|
||||
var accepted = Task.Run(async () =>
|
||||
{
|
||||
try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; }
|
||||
catch { return false; }
|
||||
}, testCt);
|
||||
try
|
||||
{
|
||||
var result = await _probe.ProbeAsync(
|
||||
$$"""{"EndpointUrl":"opc.tcp://[::1%0]:{{port}}"}""", TimeSpan.FromSeconds(5), testCt);
|
||||
|
||||
result.Ok.ShouldBeFalse("the listener is not an OPC UA server");
|
||||
result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive);
|
||||
(await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the listener");
|
||||
}
|
||||
finally { listener.Stop(); }
|
||||
}
|
||||
}
|
||||
|
||||
+29
@@ -164,6 +164,35 @@ public sealed class OpcUaClientReview1202FindingsTests
|
||||
log.Entries.Where(e => e.Level == LogLevel.Warning).ShouldHaveSingleItem().Message.ShouldContain("2 of the subscribed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1039: the same refusals ride the skipped-tag report (so /hosts shows them without the log), once per path even
|
||||
/// when the subscribe is retried; a re-initialise's rebuild clears them. Positive control: nothing is reported
|
||||
/// before any refusal.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Subscribe_time_refusals_are_added_to_the_skipped_tag_report_once_per_path()
|
||||
{
|
||||
var (drv, _) = NewConnectedDriver();
|
||||
using var _ = drv;
|
||||
drv.RecordSkippedTags(NamespaceMap.FromTable(new NamespaceTable(), Tags));
|
||||
drv.GetSkippedTags().ShouldNotBeNull().SkippedCount.ShouldBe(0);
|
||||
|
||||
var handle = drv.AddSubscriptionForTest([SpeedRef]);
|
||||
OpcUaClientDriver.RejectedItem[] refused =
|
||||
[new("Plant/dev/Gone", 0x80340000u, "the server refused the monitored item (0x80340000)")];
|
||||
drv.ReportRejectedItems(handle, refused);
|
||||
drv.ReportRejectedItems(handle, refused); // the host retries the subscribe every health tick
|
||||
|
||||
var report = drv.GetSkippedTags().ShouldNotBeNull();
|
||||
report.SkippedCount.ShouldBe(1);
|
||||
report.Sample.ShouldHaveSingleItem().RawPath.ShouldBe("Plant/dev/Gone");
|
||||
report.Sample[0].Reason.ShouldContain("refused");
|
||||
report.AuthoredCount.ShouldBe(1);
|
||||
|
||||
drv.RecordSkippedTags(NamespaceMap.FromTable(new NamespaceTable(), Tags)); // re-initialise
|
||||
drv.GetSkippedTags()!.SkippedCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
// ── G-13 ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly Dictionary<string, string> TripIndex = new() { ["ns=3;s=Alarms.Trip1"] = "Plant/opc/plc/Trip1" };
|
||||
|
||||
@@ -709,4 +709,160 @@ public sealed class TwinCATReview20261202Tests
|
||||
factory.Clients.ShouldContain(c => c.LastConnectTimeout == TimeSpan.FromSeconds(8));
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
// ======================= #1035 — write fail-fast + retired-client read =======================
|
||||
|
||||
/// <summary>A client for one silent AMS target that waits <see cref="Delay"/> per write, then answers BadTimeout.</summary>
|
||||
private sealed class SilentWriteFake(string silentNetId, TimeSpan delay, bool targetAnswersProbe) : FakeTwinCATClient
|
||||
{
|
||||
private int _silentWrites;
|
||||
public int SilentWrites => Volatile.Read(ref _silentWrites);
|
||||
private bool Silent => ConnectedAddress?.NetId == silentNetId;
|
||||
|
||||
public override async Task<uint> WriteValueAsync(
|
||||
string symbolPath, TwinCATDataType type, int? bitIndex, object? value, CancellationToken ct)
|
||||
{
|
||||
if (!Silent) return await base.WriteValueAsync(symbolPath, type, bitIndex, value, ct);
|
||||
Interlocked.Increment(ref _silentWrites);
|
||||
await Task.Delay(delay, ct);
|
||||
return TwinCATStatusMapper.BadTimeout;
|
||||
}
|
||||
|
||||
public override Task<bool> ProbeAsync(CancellationToken ct) =>
|
||||
Silent && !targetAnswersProbe ? Task.FromResult(false) : base.ProbeAsync(ct);
|
||||
}
|
||||
|
||||
private static (TwinCATDriver drv, List<SilentWriteFake> clients, TwinCATTagDefinition[] tags) SilentWriteDriver(
|
||||
TimeSpan delay, bool targetAnswersProbe)
|
||||
{
|
||||
var clients = new List<SilentWriteFake>();
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
factory.Customise = () =>
|
||||
{
|
||||
var c = new SilentWriteFake("5.23.91.23.1.1", delay, targetAnswersProbe);
|
||||
lock (clients) clients.Add(c);
|
||||
return c;
|
||||
};
|
||||
var tags = TagsOn(HostA, "A", 10)
|
||||
.Append(new TwinCATTagDefinition("B0", HostB, "MAIN.B0", TwinCATDataType.DInt)).ToArray();
|
||||
tags = [.. tags.Select(t => t with { Writable = true })];
|
||||
var drv = new TwinCATDriver(new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions(HostA), new TwinCATDeviceOptions(HostB)],
|
||||
RawTags = TwinCATRawTags.Entries(tags),
|
||||
Probe = NoProbe,
|
||||
Timeout = TimeSpan.FromSeconds(2),
|
||||
}, "drv-1035", factory);
|
||||
return (drv, clients, tags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1035: a write batch to a device that stopped answering paid the timeout once PER WRITE (reads got the P-3 fail-fast,
|
||||
/// writes did not). Now the first comms failure is checked against the device's ADS state and the rest of that
|
||||
/// device's writes in the call answer BadCommunicationError with no wire attempt; another device's write is unaffected.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_silent_device_costs_one_write_timeout_per_call_not_one_per_write()
|
||||
{
|
||||
var delay = TimeSpan.FromMilliseconds(300);
|
||||
var (drv, clients, tags) = SilentWriteDriver(delay, targetAnswersProbe: false);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var results = await drv.WriteAsync([.. tags.Select(t => new WriteRequest(t.Name, 5))], Ct);
|
||||
sw.Stop();
|
||||
|
||||
sw.Elapsed.ShouldBeLessThan(delay * 5, "A's writes must short-circuit after the first comms failure");
|
||||
clients.Sum(c => c.SilentWrites).ShouldBe(1, "one wire attempt on the silent device per call");
|
||||
results.Take(10).ShouldAllBe(r => IsComms(r.StatusCode));
|
||||
results[10].StatusCode.ShouldBe(TwinCATStatusMapper.Good, "the healthy device's write goes out");
|
||||
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1035 positive control: a write that times out on a device that STILL answers its state read is that one write's
|
||||
/// fault — its siblings are still attempted (the short-circuit is reserved for a device that is gone).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_write_timeout_on_a_device_that_still_answers_does_not_short_circuit_its_siblings()
|
||||
{
|
||||
var (drv, clients, tags) = SilentWriteDriver(TimeSpan.FromMilliseconds(20), targetAnswersProbe: true);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var results = await drv.WriteAsync([.. tags.Take(10).Select(t => new WriteRequest(t.Name, 5))], Ct);
|
||||
|
||||
clients.Sum(c => c.SilentWrites).ShouldBe(10, "every sibling is still attempted on a live device");
|
||||
results.ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.BadTimeout);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>A device whose connect fails: the first write pays it, the throttled rest do not even try.</summary>
|
||||
[Fact]
|
||||
public async Task A_device_that_cannot_connect_fails_the_rest_of_the_batch_without_further_attempts()
|
||||
{
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
factory.Customise = () => new FakeTwinCATClient { ThrowOnConnect = true };
|
||||
var tags = TagsOn(HostA, "A", 6).Select(t => t with { Writable = true }).ToArray();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA], tags);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var results = await drv.WriteAsync([.. tags.Select(t => new WriteRequest(t.Name, 1))], Ct);
|
||||
|
||||
results.ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.BadCommunicationError);
|
||||
factory.Clients.Count.ShouldBe(1, "one connect attempt; the rest of the batch failed fast");
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
private static bool IsComms(uint status) =>
|
||||
status is TwinCATStatusMapper.BadCommunicationError or TwinCATStatusMapper.BadTimeout;
|
||||
|
||||
/// <summary>
|
||||
/// #1035: a read already in flight when the symbol table is invalidated used to finish on the retired client and
|
||||
/// publish its stale-offset value at Good. It is now discarded and re-read on a fresh client.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_read_in_flight_when_the_client_is_retired_is_re_read_on_a_fresh_client()
|
||||
{
|
||||
var factory = GenerationalFactory();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldBe(111);
|
||||
|
||||
var first = factory.Clients[0];
|
||||
first.BlockRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var inFlight = drv.ReadAsync(["X"], Ct);
|
||||
await Task.Delay(100, Ct);
|
||||
inFlight.IsCompleted.ShouldBeFalse("the read must be wedged in the wire call");
|
||||
|
||||
first.FireSymbolVersionChanged(); // a program change retires the client mid-read
|
||||
first.BlockRead!.SetResult();
|
||||
|
||||
var after = (await inFlight.WaitAsync(TimeSpan.FromSeconds(5), Ct))[0];
|
||||
after.StatusCode.ShouldBe(TwinCATStatusMapper.Good);
|
||||
after.Value.ShouldBe(211, "the retired client's 111 must be discarded, not published");
|
||||
factory.Clients.Count.ShouldBe(2);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>Positive control for the above: with no invalidation the in-flight read keeps its value and no reconnect happens.</summary>
|
||||
[Fact]
|
||||
public async Task A_read_in_flight_with_no_invalidation_keeps_its_client_and_value()
|
||||
{
|
||||
var factory = GenerationalFactory();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldBe(111);
|
||||
|
||||
factory.Clients[0].BlockRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var inFlight = drv.ReadAsync(["X"], Ct);
|
||||
await Task.Delay(100, Ct);
|
||||
factory.Clients[0].BlockRead!.SetResult();
|
||||
|
||||
(await inFlight.WaitAsync(TimeSpan.FromSeconds(5), Ct))[0].Value.ShouldBe(111);
|
||||
factory.Clients.Count.ShouldBe(1);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
}
|
||||
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Akka.Actor;
|
||||
using Akka.TestKit;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
|
||||
/// <summary>
|
||||
/// #1029 / #981 S-2 end to end: a deploy that fully REBUILDS the address space while a REAL
|
||||
/// <see cref="ModbusDriver"/> is kept (its config is untouched) recreates every node at
|
||||
/// <c>BadWaitingForInitialData</c> and re-subscribes the driver. The driver's deadband baseline from the earlier
|
||||
/// subscription must not swallow the forced first raise, or a tag whose device value is still inside its deadband
|
||||
/// (what a deadband is for) stays Bad until the process value drifts. A node-modelling sink stands in for the OPC UA
|
||||
/// node manager: it resets every node on rebuild and only a driver publish makes one Good again.
|
||||
/// </summary>
|
||||
[Collection("opcua-publish-meters")]
|
||||
public sealed class ModbusDeployRebuildEndToEndTests : RuntimeActorTestBase
|
||||
{
|
||||
private static readonly NodeId TestNode = NodeId.Parse("node-1:4054");
|
||||
private const string SpeedPath = "Plant/Modbus/dev1/speed";
|
||||
private const uint Good = 0;
|
||||
private const string SpeedTagConfig = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"deadband":5}""";
|
||||
|
||||
private static readonly (string, string, string, string, string, bool)[] Initial =
|
||||
[("drv-1", "Modbus", "dev1", "speed", "Int16", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false)];
|
||||
|
||||
// drv-2's driver folder renamed: a raw CONTAINER rename = full rebuild; drv-1 (the real Modbus driver) is untouched.
|
||||
private static readonly (string, string, string, string, string, bool)[] Renamed =
|
||||
[("drv-1", "Modbus", "dev1", "speed", "Int16", false), ("drv-2", "Modbus2Renamed", "dev2", "pressure", "Float", false)];
|
||||
|
||||
private static RevisionHash Rev(char c) => RevisionHash.Parse(new string(c, 64));
|
||||
|
||||
[Fact]
|
||||
public void A_full_rebuild_with_a_kept_Modbus_driver_leaves_no_deadbanded_node_at_BadWaitingForInitialData()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var db = NewInMemoryDbFactory();
|
||||
var sink = new NodeModelSink();
|
||||
var factory = new KeptModbusFactory();
|
||||
var coordinator = CreateTestProbe();
|
||||
var publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
|
||||
sink: sink, applier: new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance)));
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(
|
||||
db, TestNode, coordinator.Ref, driverFactory: factory,
|
||||
localRoles: new HashSet<string> { "driver" }, dependencyMux: CreateTestProbe().Ref,
|
||||
opcUaPublishActor: publish, virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
|
||||
virtualTagHostOverride: CreateTestProbe().Ref));
|
||||
|
||||
void Deploy((string, string, string, string, string, bool)[] tags, RevisionHash rev)
|
||||
{
|
||||
var id = V3ArtifactSeeder.SeedV3Deployment(db, rev, tags, [], enabled: true,
|
||||
tagConfigByTag: new Dictionary<string, string> { ["speed"] = SpeedTagConfig },
|
||||
driverConfigByDriver: new Dictionary<string, string> { ["drv-1"] = """{"host":"fake","probe":{"enabled":false}}""" });
|
||||
host.Tell(new DispatchDeployment(id, rev, CorrelationId.NewId()));
|
||||
var ack = coordinator.FishForMessage<ApplyAck>(m => m.DeploymentId == id, PresenceBudget, cancellationToken: ct);
|
||||
ack.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
ack.Degraded.ShouldBeFalse(ack.DegradedReason);
|
||||
}
|
||||
|
||||
Deploy(Initial, Rev('a'));
|
||||
AwaitAssert(() => sink.StatusOf(SpeedPath).ShouldBe(Good, "the first deploy's initial publish; log: " + string.Join(";", sink.Log)), PresenceBudget, cancellationToken: ct);
|
||||
factory.Transport.Reads.ShouldBeGreaterThan(0);
|
||||
|
||||
// Same device value (inside the 5-unit deadband); the rebuild resets the node and the kept driver is re-subscribed.
|
||||
Deploy(Renamed, Rev('b'));
|
||||
sink.RebuildCount.ShouldBe(1, "the container rename must be a full rebuild");
|
||||
AwaitAssert(() => sink.StatusOf(SpeedPath).ShouldBe(Good,
|
||||
"the rebuilt node must receive the kept driver's first raise, not stay BadWaitingForInitialData"),
|
||||
PresenceBudget, cancellationToken: ct);
|
||||
factory.Created.ShouldBe(1, "the Modbus driver must have been KEPT across the rebuild, not respawned");
|
||||
}
|
||||
|
||||
private sealed class ConstantTransport : IModbusTransport
|
||||
{
|
||||
private int _reads;
|
||||
public int Reads => Volatile.Read(ref _reads);
|
||||
public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _reads);
|
||||
return Task.FromResult(new byte[] { 3, 2, 0, 100 }); // register = 100, forever
|
||||
}
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Materialises ONE real Modbus driver for drv-1 (deadband 5); everything else is a recording stub.</summary>
|
||||
private sealed class KeptModbusFactory : IDriverFactory
|
||||
{
|
||||
private readonly RecordingSubscribableDriverFactory _others = new("Modbus");
|
||||
private int _created;
|
||||
public ConstantTransport Transport { get; } = new();
|
||||
public ModbusDriver? Driver;
|
||||
public int Created => Volatile.Read(ref _created);
|
||||
|
||||
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson)
|
||||
{
|
||||
if (driverInstanceId != "drv-1") return _others.TryCreate(driverType, driverInstanceId, driverConfigJson);
|
||||
Interlocked.Increment(ref _created);
|
||||
// The deploy folds the artifact's raw tags + driver config into driverConfigJson and the driver re-parses it at
|
||||
// Initialize, so only the TRANSPORT is injected here.
|
||||
return Driver = new ModbusDriver(new ModbusDriverOptions { Host = "fake" }, driverInstanceId, _ => Transport);
|
||||
}
|
||||
|
||||
public IReadOnlyCollection<string> SupportedTypes => ["Modbus"];
|
||||
}
|
||||
|
||||
/// <summary>Models node status: a created/rebuilt variable is BadWaitingForInitialData until a value is written.</summary>
|
||||
private sealed class NodeModelSink : IOpcUaAddressSpaceSink
|
||||
{
|
||||
private const uint BadWaiting = 0x80320000;
|
||||
private readonly ConcurrentDictionary<string, uint> _status = new();
|
||||
public int RebuildCount;
|
||||
public ConcurrentQueue<string> Log = new();
|
||||
|
||||
public uint StatusOf(string nodeId) => _status.TryGetValue(nodeId, out var s) ? s : uint.MaxValue;
|
||||
|
||||
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm = AddressSpaceRealm.Uns)
|
||||
{
|
||||
Log.Enqueue($"W {nodeId} {statusCode:X}");
|
||||
if (_status.ContainsKey(nodeId)) _status[nodeId] = statusCode; // writes are non-creating, like the real node manager
|
||||
}
|
||||
public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { }
|
||||
public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime occurredUtc, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
|
||||
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { }
|
||||
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
|
||||
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) =>
|
||||
LogAndAdd(variableNodeId);
|
||||
private void LogAndAdd(string id) { Log.Enqueue("E " + id); _status.TryAdd(id, BadWaiting); }
|
||||
public void RebuildAddressSpace()
|
||||
{
|
||||
Interlocked.Increment(ref RebuildCount);
|
||||
_status.Clear();
|
||||
}
|
||||
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
|
||||
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
|
||||
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,8 @@ public static class V3ArtifactSeeder
|
||||
/// hand that child an explicit EMPTY set rather than skipping it.</param>
|
||||
/// <param name="virtualTags">Optional Equipment VirtualTags (#995): each gets its own script row with
|
||||
/// <c>Source</c> as its body; <c>EquipmentId</c> must name a seeded equipment (<c>EQ-{area}-{line}-{equip}</c>).</param>
|
||||
/// <param name="driverConfigByDriver">Optional <c>DriverConfig</c> JSON per driver id (the deploy folds the raw
|
||||
/// tags into it); absent ids keep <c>"{}"</c>.</param>
|
||||
/// <returns>The seeded deployment's id.</returns>
|
||||
public static DeploymentId SeedV3Deployment(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev,
|
||||
@@ -64,15 +66,17 @@ public static class V3ArtifactSeeder
|
||||
IReadOnlyDictionary<string, string>? tagConfigByTag = null,
|
||||
string[]? taglessDrivers = null,
|
||||
IReadOnlyDictionary<string, Guid>? driverRowIds = null,
|
||||
(string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null)
|
||||
(string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null,
|
||||
IReadOnlyDictionary<string, string>? driverConfigByDriver = null)
|
||||
{
|
||||
string ConfigOf(string id) => driverConfigByDriver is not null && driverConfigByDriver.TryGetValue(id, out var c) ? c : "{}";
|
||||
Guid RowId(string id) => driverRowIds is not null && driverRowIds.TryGetValue(id, out var g) ? g : Guid.Empty;
|
||||
var drivers = rawTags
|
||||
.Select(t => (t.Driver, t.DriverName))
|
||||
.Distinct()
|
||||
.Select(d => new { DriverInstanceRowId = RowId(d.Driver), DriverInstanceId = d.Driver, RawFolderId = "rf-plant", Name = d.DriverName, DriverType = "Modbus", DriverConfig = "{}", ClusterId = "c1", Enabled = enabled })
|
||||
.Select(d => new { DriverInstanceRowId = RowId(d.Driver), DriverInstanceId = d.Driver, RawFolderId = "rf-plant", Name = d.DriverName, DriverType = "Modbus", DriverConfig = ConfigOf(d.Driver), ClusterId = "c1", Enabled = enabled })
|
||||
.Concat((taglessDrivers ?? Array.Empty<string>())
|
||||
.Select(id => new { DriverInstanceRowId = RowId(id), DriverInstanceId = id, RawFolderId = "rf-plant", Name = id, DriverType = "Modbus", DriverConfig = "{}", ClusterId = "c1", Enabled = enabled }))
|
||||
.Select(id => new { DriverInstanceRowId = RowId(id), DriverInstanceId = id, RawFolderId = "rf-plant", Name = id, DriverType = "Modbus", DriverConfig = ConfigOf(id), ClusterId = "c1", Enabled = enabled }))
|
||||
.ToArray();
|
||||
var devices = rawTags
|
||||
.Select(t => (t.Driver, t.Device))
|
||||
|
||||
Reference in New Issue
Block a user