diff --git a/docs/drivers/Heidenhain.md b/docs/drivers/Heidenhain.md
index fb3560a92..1e2c92419 100644
--- a/docs/drivers/Heidenhain.md
+++ b/docs/drivers/Heidenhain.md
@@ -440,6 +440,11 @@ overrides, axes, tool, the whole alarm walk) and aliased custom addresses are re
then drops is backed off, not re-dialled every `InitialDelayMs`. Unlike the Java base, an initial connect
failure also retries (no manual restart). The loop survives any unexpected fault (logged, retired, backed off);
JSON-`null` config sections are normalised to defaults by the parser.
+ (#990) A deliberate stop (deploy / Force Reconnect) is never an outage: the runtime's generation is bumped before
+ the session closes, and its values are invalidated. The backoff count is carried across a watchdog re-init, so a
+ `MaxDelayMs` above ~90 s is reachable. While a control is down its host status stays `Stopped` (no
+ `Stopped`/`Unknown` flap, "since" time stable). A refused optional DNC/DATA login is retried per session on a
+ 5 s to 5 min exponential schedule instead of on every poll batch.
- Subscriptions: the initial push and later publications are ordered under one lock, so a subscriber never
receives an older value after a newer one. A re-init disposes every control loop first; a late start of a
disposed loop is a no-op.
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs
index 9e4b07ef1..68a373ec0 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs
@@ -79,6 +79,8 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
private string? _lastError;
private int _consecutiveFailures;
private bool _disposed;
+ private bool _disposing;
+ private bool _afterFailure;
private volatile bool _pollProgress;
/// Consecutive sessions that ended without one published poll batch (test/diagnostic).
@@ -95,8 +97,13 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
TimeProvider time,
ILogger logger,
HeidenhainAlarmSink? alarms = null,
- HeidenhainIdentitySink? identity = null)
+ HeidenhainIdentitySink? identity = null,
+ int initialFailures = 0)
{
+ // #990 (M-19): a watchdog/force re-init rebuilds the runtime; the driver carries the failure count over
+ // so the reconnect backoff keeps growing instead of restarting at InitialDelayMs.
+ _consecutiveFailures = Math.Max(0, initialFailures);
+ _afterFailure = _consecutiveFailures > 0;
_device = device;
_options = HeidenhainOptionsParser.Normalize(options);
_tags = tags;
@@ -227,7 +234,7 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
{
SetState(HeidenhainConnectionState.Connecting, null);
var client = _clientFactory(_device.Host, _device.Port, TimeSpan.FromMilliseconds(_options.TimeoutMs));
- session = new HeidenhainSession(client, HeidenhainSessionSettings.From(_options, _tags), _passwords);
+ session = new HeidenhainSession(client, HeidenhainSessionSettings.From(_options, _tags), _passwords, _time);
await client.OpenAsync(ct).ConfigureAwait(false);
await session.InitializeAsync(ct).ConfigureAwait(false);
long generation;
@@ -364,6 +371,7 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
var now = _time.GetUtcNow().UtcDateTime;
lock (_publication)
{
+ if (_disposing) return; // a deliberate stop is not an outage (#990 M-16)
old = _session;
_session = null;
_generation++;
@@ -397,6 +405,21 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
catch (Exception ex) { _logger.LogWarning(ex, "Heidenhain {Host} alarm projection threw", HostName); }
}
+ /// True once a connect has failed or a session was lost since the last successful connect.
+ internal bool AfterFailure { get { lock (_publication) return _afterFailure; } }
+
+ ///
+ /// The host status a runtime state presents. Connecting keeps the previous effective state: it is
+ /// Stopped while the control is down (retrying) and Unknown only on the first connect.
+ ///
+ internal static HostState HostFacing(HeidenhainConnectionState s, bool afterFailure) => s switch
+ {
+ HeidenhainConnectionState.Connected => HostState.Running,
+ HeidenhainConnectionState.Backoff => HostState.Stopped,
+ HeidenhainConnectionState.Connecting when afterFailure => HostState.Stopped,
+ _ => HostState.Unknown,
+ };
+
private void SetState(HeidenhainConnectionState next, string? error)
{
HeidenhainConnectionState old;
@@ -406,8 +429,13 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
if (error is not null) _lastError = error;
if (next == HeidenhainConnectionState.Connected) _lastError = null;
if (old == next) return;
+ var oldFacing = HostFacing(old, _afterFailure);
+ if (next == HeidenhainConnectionState.Backoff) _afterFailure = true;
+ else if (next == HeidenhainConnectionState.Connected) _afterFailure = false;
_state = next;
- _stateChangedUtc = _time.GetUtcNow().UtcDateTime;
+ // #990 (M-17): the "since" time moves only when the host-facing state does, not on every
+ // Backoff<->Connecting retry edge.
+ if (HostFacing(next, _afterFailure) != oldFacing) _stateChangedUtc = _time.GetUtcNow().UtcDateTime;
}
try { _stateChanged(this, old, next); }
@@ -428,8 +456,17 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
_cts = null;
}
+ // #990 (M-16): a deliberate stop must look the same wherever the loop is. Bump the generation FIRST so a
+ // batch cut short by the closing session is dropped (Publish/Retire see a stale generation) instead of
+ // running the comms-loss outage path.
HeidenhainSession? session;
- lock (_publication) session = _session;
+ lock (_publication)
+ {
+ _disposing = true;
+ _generation++;
+ session = _session;
+ }
+
session?.Close();
if (cts is not null) await cts.CancelAsync().ConfigureAwait(false);
if (loop is not null)
@@ -443,6 +480,8 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
{
_session = null;
_generation++;
+ // Whatever the loop was doing, never leave the last Good snapshots behind a stopped runtime.
+ Invalidate(_time.GetUtcNow().UtcDateTime);
}
SetState(HeidenhainConnectionState.Stopped, null);
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs
index d0346a1e2..0323cba50 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs
@@ -221,7 +221,8 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
(role, ct) => _credentials.ResolveAsync(_options, dev, role, ct),
Publish, OnRuntimeState, _clientFactory, _time, _logger,
(r, status, alarms) => _alarms.OnWalk(r.HostName, status, alarms),
- OnIdentity);
+ OnIdentity,
+ _carriedFailures.GetValueOrDefault($"{dev.Host}:{dev.Port}"));
runtimes.Add(runtime);
foreach (var t in tags)
{
@@ -265,13 +266,26 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
{
_initialized = false;
await StopDevicesAsync().ConfigureAwait(false);
+ _carriedFailures = new Dictionary(StringComparer.Ordinal);
_subscriptions.Clear();
lock (_lifecycleLock) _state = DriverState.Unknown;
}
+ /// Largest consecutive-failure count across the device runtimes (test/diagnostic).
+ internal int MaxConsecutiveFailures => _devices.Select(d => d.ConsecutiveFailures).DefaultIfEmpty(0).Max();
+
+ private Dictionary _carriedFailures = new(StringComparer.Ordinal);
+
private async Task StopDevicesAsync()
{
var devices = _devices;
+ // #990 (M-19): carry a still-failing control's backoff count across the re-init (the watchdog rebuilds
+ // every runtime every ~90 s while a control is down, which restarted the dial at InitialDelayMs).
+ var carried = new Dictionary(StringComparer.Ordinal);
+ foreach (var d in devices)
+ if (d.State is HeidenhainConnectionState.Backoff or HeidenhainConnectionState.Connecting && d.ConsecutiveFailures > 0)
+ carried[d.HostName] = d.ConsecutiveFailures;
+ _carriedFailures = carried;
_devices = [];
_byRawPath = new Dictionary();
foreach (var d in devices) await d.DisposeAsync().ConfigureAwait(false);
@@ -386,25 +400,28 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
return a.Equals(b);
}
+ private readonly Dictionary _facing = new();
+
private void OnRuntimeState(HeidenhainDeviceRuntime runtime, HeidenhainConnectionState old, HeidenhainConnectionState next)
{
- var o = ToHostState(old);
- var n = ToHostState(next);
+ // Connecting-after-failure stays Stopped (#990 M-17): no Stopped<->Unknown flap per retry.
+ var n = HeidenhainDeviceRuntime.HostFacing(next, runtime.AfterFailure);
+ HostState o;
+ lock (_facing)
+ {
+ o = _facing.GetValueOrDefault(runtime, HostState.Unknown);
+ _facing[runtime] = n;
+ }
+
if (o == n) return;
try { OnHostStatusChanged?.Invoke(this, new HostStatusChangedEventArgs(runtime.HostName, o, n)); }
catch (Exception ex) { _logger.LogDebug(ex, "Heidenhain host-status handler threw"); }
}
- private static HostState ToHostState(HeidenhainConnectionState s) => s switch
- {
- HeidenhainConnectionState.Connected => HostState.Running,
- HeidenhainConnectionState.Backoff => HostState.Stopped,
- _ => HostState.Unknown,
- };
///
public IReadOnlyList GetHostStatuses() =>
- _devices.Select(d => new HostConnectivityStatus(d.HostName, ToHostState(d.State), d.StateChangedUtc)).ToList();
+ _devices.Select(d => new HostConnectivityStatus(d.HostName, HeidenhainDeviceRuntime.HostFacing(d.State, d.AfterFailure), d.StateChangedUtc)).ToList();
///
public string ResolveHost(string fullReference) =>
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainSession.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainSession.cs
index a8f7fa36b..fcf92728b 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainSession.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainSession.cs
@@ -53,11 +53,23 @@ internal sealed class HeidenhainSession : IAsyncDisposable
private volatile bool _closed;
private volatile bool _lost;
- public HeidenhainSession(Lsv2Client client, HeidenhainSessionSettings settings, PasswordSource passwords)
+ // #990 (M-18): a non-stable optional-role login refusal is retried on an exponential per-role schedule
+ // (5 s -> 5 min) instead of on every poll batch, so a control that keeps refusing is not sent the
+ // cleartext password ~1.5x/s. Per session: a reconnect starts fresh.
+ internal static readonly TimeSpan LoginRetryInitial = TimeSpan.FromSeconds(5);
+ internal static readonly TimeSpan LoginRetryMax = TimeSpan.FromMinutes(5);
+ private readonly TimeProvider _time;
+ private DateTimeOffset _dncNextLogin;
+ private DateTimeOffset _dataNextLogin;
+ private int _dncLoginFailures;
+ private int _dataLoginFailures;
+
+ public HeidenhainSession(Lsv2Client client, HeidenhainSessionSettings settings, PasswordSource passwords, TimeProvider? time = null)
{
_client = client;
_settings = settings;
_passwords = passwords;
+ _time = time ?? TimeProvider.System;
}
/// True once a transport failure ended this session.
@@ -106,6 +118,7 @@ internal sealed class HeidenhainSession : IAsyncDisposable
}
catch (Lsv2RefusalException e)
{
+ ScheduleLoginRetry(role == "DNC");
return HeidenhainStatus.FromRefusal(e.Code);
}
catch (QualityException e)
@@ -374,6 +387,8 @@ internal sealed class HeidenhainSession : IAsyncDisposable
var effective = status == NotAttempted ? HeidenhainStatus.BadNotSupported : status;
if (!enabled || status == NotAttempted || HeidenhainStatus.IsStable(effective))
throw new QualityException(effective, enabled ? HeidenhainStatus.State(effective) : HeidenhainCatalog.States.Disabled);
+ if (_time.GetUtcNow() < (dnc ? _dncNextLogin : _dataNextLogin))
+ throw new QualityException(effective, HeidenhainStatus.State(effective)); // throttled: no wire traffic
try
{
await WireAsync(wire, "Login_" + role, async c =>
@@ -381,13 +396,14 @@ internal sealed class HeidenhainSession : IAsyncDisposable
await LoginWithCredentialAsync(role, c).ConfigureAwait(false);
return [];
}, ct).ConfigureAwait(false);
- if (dnc) _dncStatus = HeidenhainStatus.Good;
- else _dataStatus = HeidenhainStatus.Good;
+ if (dnc) { _dncStatus = HeidenhainStatus.Good; _dncLoginFailures = 0; }
+ else { _dataStatus = HeidenhainStatus.Good; _dataLoginFailures = 0; }
}
catch (Lsv2RefusalException e)
{
if (dnc) _dncStatus = HeidenhainStatus.FromRefusal(e.Code);
else _dataStatus = HeidenhainStatus.FromRefusal(e.Code);
+ ScheduleLoginRetry(dnc);
throw;
}
catch (QualityException e)
@@ -399,6 +415,14 @@ internal sealed class HeidenhainSession : IAsyncDisposable
}
}
+ private void ScheduleLoginRetry(bool dnc)
+ {
+ var failures = dnc ? ++_dncLoginFailures : ++_dataLoginFailures;
+ var delay = ConnectionBackoff.ComputeDelay(LoginRetryInitial, failures, LoginRetryMax);
+ if (dnc) _dncNextLogin = _time.GetUtcNow() + delay;
+ else _dataNextLogin = _time.GetUtcNow() + delay;
+ }
+
private async Task PrepareTelemetryAsync(Dictionary wire, CancellationToken ct)
{
if (!_settings.TelemetryEnabled) throw new QualityException(HeidenhainStatus.BadNotSupported, HeidenhainCatalog.States.Disabled);
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs
index 63dfc37e2..550ea8649 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs
@@ -220,17 +220,130 @@ public sealed class HeidenhainReviewFixTests
}
}
- private static HeidenhainDeviceRuntime NewRuntime(int port, Action publish)
+ // ---- #990 M-16: stopping a control loop is deterministic wherever the loop is. ----
+
+ /// Idle in the poll delay: the stopped runtime must not leave Good snapshots in the cache.
+ [Fact]
+ public async Task Disposing_an_idle_runtime_invalidates_its_values()
+ {
+ var control = new SimulatedControl();
+ control.Runtime[23] = () => SimulatedControl.U16(4);
+ await using var sim = Lsv2Simulator.WithControl(control);
+ var published = new ConcurrentQueue();
+ var runtime = NewRuntime(sim.Port, (_, v) => published.Enqueue(v), statusMs: 60_000);
+ runtime.Start();
+ await WaitFor(() => published.Any(v => v.StatusCode == HeidenhainStatus.Good));
+ await runtime.DisposeAsync();
+ published.Last().StatusCode.ShouldBe(HeidenhainStatus.BadNoCommunication);
+ }
+
+ ///
+ /// Mid-batch: the closing session short-circuits the batch; that must NOT run the comms-loss outage
+ /// path (a Backoff transition + "communication lost" retire) for a deliberate stop.
+ ///
+ [Fact]
+ public async Task Disposing_mid_batch_is_not_reported_as_a_comms_loss()
+ {
+ var inRead = new ManualResetEventSlim();
+ var release = new ManualResetEventSlim();
+ var control = new SimulatedControl();
+ control.Runtime[23] = () => { inRead.Set(); release.Wait(TimeSpan.FromSeconds(5)); return SimulatedControl.U16(4); };
+ await using var sim = Lsv2Simulator.WithControl(control);
+ var states = new ConcurrentQueue();
+ var runtime = NewRuntime(sim.Port, (_, _) => { }, onState: (_, n) => states.Enqueue(n));
+ runtime.Start();
+ inRead.Wait(TimeSpan.FromSeconds(5), Ct).ShouldBeTrue();
+ var dispose = runtime.DisposeAsync().AsTask();
+ await Task.Delay(200, Ct);
+ release.Set();
+ await dispose;
+ states.ShouldNotContain(HeidenhainConnectionState.Backoff);
+ runtime.State.ShouldBe(HeidenhainConnectionState.Stopped);
+ }
+
+ /// Positive control: a genuine session loss still takes the Backoff / outage path.
+ [Fact]
+ public async Task A_real_session_loss_still_retires_to_backoff()
+ {
+ var control = new SimulatedControl();
+ control.Runtime[23] = SimReply.Drop;
+ await using var sim = Lsv2Simulator.WithControl(control);
+ var states = new ConcurrentQueue();
+ var runtime = NewRuntime(sim.Port, (_, _) => { }, onState: (_, n) => states.Enqueue(n));
+ await using var _ = runtime;
+ runtime.Start();
+ await WaitFor(() => states.Contains(HeidenhainConnectionState.Backoff));
+ }
+
+ private static async Task WaitFor(Func condition)
+ {
+ var deadline = DateTime.UtcNow.AddSeconds(5);
+ while (!condition())
+ {
+ if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached");
+ await Task.Delay(20, Ct);
+ }
+ }
+
+ // ---- #990 M-17: a down control's host status does not flap, and its since-time is stable. ----
+
+ [Fact]
+ public async Task A_down_control_host_status_does_not_flap_and_keeps_its_since_time()
{
var options = new HeidenhainDriverOptions
{
TimeoutMs = 500,
- Polling = new HeidenhainPollingOptions { StatusMs = 100, CustomMs = 100, SlowMs = 100 },
+ Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = 1, DeviceName = "dev1" }],
+ RawTags = [TestTags.Raw("Status/ExecutionState")],
+ Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 200 },
+ };
+ await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null), null, null);
+ var events = new ConcurrentQueue();
+ d.OnHostStatusChanged += (_, e) => events.Enqueue(e);
+ await d.InitializeAsync("{}", Ct);
+ await d.SubscribeAsync([options.RawTags[0].RawPath], TimeSpan.FromSeconds(1), Ct);
+ await WaitFor(() => d.GetHostStatuses().Single().State == HostState.Stopped);
+ var since = d.GetHostStatuses().Single().LastChangedUtc;
+ await Task.Delay(1200, Ct); // several Backoff <-> Connecting retries
+ d.MaxConsecutiveFailures.ShouldBeGreaterThan(3);
+ events.Count(e => e.NewState == HostState.Stopped).ShouldBe(1);
+ events.ShouldNotContain(e => e.OldState == HostState.Stopped); // never leaves Stopped while down
+ d.GetHostStatuses().Single().LastChangedUtc.ShouldBe(since);
+ }
+
+ // ---- #990 M-19: a re-init (the comms-loss watchdog's remedy) keeps the reconnect backoff. ----
+
+ [Fact]
+ public async Task Reinitialize_of_a_down_control_carries_the_backoff_count()
+ {
+ var options = new HeidenhainDriverOptions
+ {
+ TimeoutMs = 500,
+ Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = 1, DeviceName = "dev1" }],
+ RawTags = [TestTags.Raw("Status/ExecutionState")],
+ Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 400 },
+ };
+ await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null), null, null);
+ await d.InitializeAsync("{}", Ct);
+ await d.SubscribeAsync([options.RawTags[0].RawPath], TimeSpan.FromSeconds(1), Ct);
+ await WaitFor(() => d.MaxConsecutiveFailures >= 4);
+ var before = d.MaxConsecutiveFailures;
+ await d.ReinitializeAsync("{}", Ct);
+ d.MaxConsecutiveFailures.ShouldBeGreaterThanOrEqualTo(before - 1); // carried (not reset to 0)
+ }
+
+ private static HeidenhainDeviceRuntime NewRuntime(int port, Action publish,
+ int statusMs = 100, Action? onState = null)
+ {
+ var options = new HeidenhainDriverOptions
+ {
+ TimeoutMs = 500,
+ Polling = new HeidenhainPollingOptions { StatusMs = statusMs, CustomMs = 100, SlowMs = 100 },
Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 800 },
};
var device = new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = port, DeviceName = "dev1" };
return new HeidenhainDeviceRuntime(device, options, [TestTags.Def("Status/ExecutionState")],
- (_, _) => ValueTask.FromResult(""), publish, (_, _, _) => { },
+ (_, _) => ValueTask.FromResult(""), publish, (_, o, n) => onState?.Invoke(o, n),
(h, p, t) => new Lsv2Client(h, p, t), TimeProvider.System, NullLogger.Instance);
}
}
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainSessionTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainSessionTests.cs
index 830620649..ae0a6bd69 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainSessionTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainSessionTests.cs
@@ -19,6 +19,7 @@ public sealed class HeidenhainSessionTests
public required SimulatedControl Control { get; init; }
public required HeidenhainSession Session { get; init; }
public required IReadOnlyList Tags { get; init; }
+ public required ManualTime Time { get; init; }
public async Task> ReadAsync(params string[] addresses)
{
@@ -45,14 +46,23 @@ public sealed class HeidenhainSessionTests
bool telemetry = true, bool dnc = true, bool data = false, int maxAlarms = 64, bool timers = false,
HeidenhainSession.PasswordSource? passwords = null)
{
+ var time = new ManualTime();
var sim = Lsv2Simulator.WithControl(control);
var client = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
var settings = new HeidenhainSessionSettings(telemetry, dnc, data, maxAlarms, timers,
tags.Any(t => t.Address.Kind == HeidenhainAddressKind.Plc), tags.Any(t => t.Address.Kind == HeidenhainAddressKind.DataPath));
- var session = new HeidenhainSession(client, settings, passwords ?? ((_, _) => ValueTask.FromResult("")));
+ var session = new HeidenhainSession(client, settings, passwords ?? ((_, _) => ValueTask.FromResult("")), time);
await client.OpenAsync(Ct);
await session.InitializeAsync(Ct);
- return new Harness { Sim = sim, Control = control, Session = session, Tags = tags };
+ return new Harness { Sim = sim, Control = control, Session = session, Tags = tags, Time = time };
+ }
+
+ /// A manually advanced clock for the optional-login retry schedule (#990 M-18).
+ private sealed class ManualTime : TimeProvider
+ {
+ private DateTimeOffset _now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ public override DateTimeOffset GetUtcNow() => _now;
+ public void Advance(TimeSpan by) => _now += by;
}
private static List Standard(params string[] addresses) => addresses.Select(a => TestTags.Def(a)).ToList();
@@ -312,6 +322,7 @@ public sealed class HeidenhainSessionTests
var tags = role == "DATA" ? [TestTags.Def("DATA:/x", "Int64")] : Standard("Status/ExecutionState");
await using var h = await OpenAsync(c, tags, data: true,
passwords: (r, _) => { if (r == role) Interlocked.Increment(ref resolved); return ValueTask.FromResult("fresh"); });
+ h.Time.Advance(HeidenhainSession.LoginRetryInitial + TimeSpan.FromMilliseconds(1)); // past the retry window
var s = await h.Session.ReadBatchAsync(tags, Ct);
s[0].Status.ShouldBe(HeidenhainStatus.Good);
attempts.ShouldBe(2);
@@ -382,14 +393,44 @@ public sealed class HeidenhainSessionTests
c.Runtime[23] = () => logins < 3 ? SimReply.Refuse(23) : SimReply.Ok("S_RI", [0, 4]);
c.Runtime[26] = () => logins < 3 ? SimReply.Refuse(23) : SimReply.Ok("S_RI", [0, 7]);
await using var h = await OpenAsync(c, Standard("Status/ExecutionState", "Status/ProgramState"));
+ h.Time.Advance(TimeSpan.FromSeconds(6));
(await h.ReadAsync("Status/ExecutionState", "Status/ProgramState")).Values
.ShouldAllBe(s => s.Status == HeidenhainStatus.BadUserAccessDenied);
+ h.Time.Advance(TimeSpan.FromSeconds(11));
var recovered = await h.ReadAsync("Status/ExecutionState", "Status/ProgramState");
recovered["Status/ExecutionState"].Value.ShouldBe(4);
recovered["Status/ProgramState"].Value.ShouldBe(7);
logins.ShouldBe(3);
}
+ /// #990 M-18: a refused optional login is not re-sent on every batch; it follows a growing schedule.
+ [Fact]
+ public async Task Refused_optional_login_is_throttled_not_retried_every_batch()
+ {
+ var logins = 0;
+ var c = new SimulatedControl
+ {
+ Login = (r, _) => r == "DNC" && Interlocked.Increment(ref logins) < 100 ? SimReply.Refuse(25) : SimReply.Ok("T_OK", []),
+ };
+ c.Runtime[23] = () => SimReply.Refuse(23);
+ await using var h = await OpenAsync(c, Standard("Status/ExecutionState"));
+ logins.ShouldBe(1); // the init attempt
+ for (var i = 0; i < 50; i++) await h.ReadAsync("Status/ExecutionState");
+ logins.ShouldBe(1); // 50 batches inside the 5 s window: no further A_LG
+
+ h.Time.Advance(TimeSpan.FromSeconds(5.1)); // window elapsed -> exactly one more attempt
+ await h.ReadAsync("Status/ExecutionState");
+ await h.ReadAsync("Status/ExecutionState");
+ logins.ShouldBe(2);
+
+ h.Time.Advance(TimeSpan.FromSeconds(5.1)); // the window doubled to 10 s: still closed (positive control below)
+ await h.ReadAsync("Status/ExecutionState");
+ logins.ShouldBe(2);
+ h.Time.Advance(TimeSpan.FromSeconds(5)); // 10.1 s since the last attempt -> retried
+ await h.ReadAsync("Status/ExecutionState");
+ logins.ShouldBe(3);
+ }
+
[Fact]
public async Task Every_request_the_session_emits_is_allowlisted()
{