Merge #986 + #990: S7 bad write values are refusals; Heidenhain dispose/backoff/login-retry fixes

This commit is contained in:
Joseph Doherty
2026-12-03 10:12:40 -05:00
8 changed files with 315 additions and 23 deletions
+5
View File
@@ -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.
@@ -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;
/// <summary>Consecutive sessions that ended without one published poll batch (test/diagnostic).</summary>
@@ -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); }
}
/// <summary>True once a connect has failed or a session was lost since the last successful connect.</summary>
internal bool AfterFailure { get { lock (_publication) return _afterFailure; } }
/// <summary>
/// The host status a runtime state presents. <c>Connecting</c> keeps the previous effective state: it is
/// <c>Stopped</c> while the control is down (retrying) and <c>Unknown</c> only on the first connect.
/// </summary>
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);
@@ -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<string, int>(StringComparer.Ordinal);
_subscriptions.Clear();
lock (_lifecycleLock) _state = DriverState.Unknown;
}
/// <summary>Largest consecutive-failure count across the device runtimes (test/diagnostic).</summary>
internal int MaxConsecutiveFailures => _devices.Select(d => d.ConsecutiveFailures).DefaultIfEmpty(0).Max();
private Dictionary<string, int> _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<string, int>(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<string, HeidenhainDeviceRuntime>();
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<HeidenhainDeviceRuntime, HostState> _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,
};
/// <inheritdoc />
public IReadOnlyList<HostConnectivityStatus> 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();
/// <inheritdoc />
public string ResolveHost(string fullReference) =>
@@ -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;
}
/// <summary>True once a transport failure ended this session.</summary>
@@ -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<string, Raw> wire, CancellationToken ct)
{
if (!_settings.TelemetryEnabled) throw new QualityException(HeidenhainStatus.BadNotSupported, HeidenhainCatalog.States.Disabled);
@@ -2322,7 +2322,17 @@ public sealed class S7Driver
// match the address's size-suffix type: DBX=bool, DBB=byte, DBW=ushort, DBD=uint.
// Our S7DataType lets the caller pass short/int/float; convert to the unsigned
// wire representation before handing off.
var boxed = BoxValueForWrite(tag.DataType, value);
object boxed;
try { boxed = BoxValueForWrite(tag.DataType, value); }
catch (OverflowException ex)
{
// #986 (S-5): a client value outside the narrow type's range is a refusal, not a comms fault.
throw new S7ValueRangeException($"value out of range for S7 {tag.DataType}: {ex.Message}");
}
catch (Exception ex) when (ex is FormatException or InvalidCastException)
{
throw new S7WriteValueException($"value is not convertible to S7 {tag.DataType}: {ex.Message}");
}
await plc.WriteAsync(tag.Address, boxed, ct).ConfigureAwait(false);
}
@@ -220,17 +220,130 @@ public sealed class HeidenhainReviewFixTests
}
}
private static HeidenhainDeviceRuntime NewRuntime(int port, Action<string, DataValueSnapshot> publish)
// ---- #990 M-16: stopping a control loop is deterministic wherever the loop is. ----
/// <summary>Idle in the poll delay: the stopped runtime must not leave Good snapshots in the cache.</summary>
[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<DataValueSnapshot>();
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);
}
/// <summary>
/// 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.
/// </summary>
[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<HeidenhainConnectionState>();
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);
}
/// <summary>Positive control: a genuine session loss still takes the Backoff / outage path.</summary>
[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<HeidenhainConnectionState>();
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<bool> 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<HostStatusChangedEventArgs>();
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<string, DataValueSnapshot> publish,
int statusMs = 100, Action<HeidenhainConnectionState, HeidenhainConnectionState>? 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);
}
}
@@ -19,6 +19,7 @@ public sealed class HeidenhainSessionTests
public required SimulatedControl Control { get; init; }
public required HeidenhainSession Session { get; init; }
public required IReadOnlyList<HeidenhainTagDefinition> Tags { get; init; }
public required ManualTime Time { get; init; }
public async Task<Dictionary<string, HeidenhainSample>> 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 };
}
/// <summary>A manually advanced clock for the optional-login retry schedule (#990 M-18).</summary>
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<HeidenhainTagDefinition> 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);
}
/// <summary>#990 M-18: a refused optional login is not re-sent on every batch; it follows a growing schedule.</summary>
[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()
{
@@ -167,6 +167,49 @@ public sealed class S7ArrayWriteAndHealthTests
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
}
// ---- #986 S-5: bad scalar values are refusals ----
private const uint BadOutOfRange = 0x803C0000u;
/// <summary>
/// Out-of-range / unconvertible values to narrow scalars are BadOutOfRange / BadTypeMismatch,
/// never reach the PLC and leave health Healthy.
/// </summary>
[Theory]
[InlineData(S7DataType.Int16, "DB1.DBW0", 70000, BadOutOfRange)]
[InlineData(S7DataType.Byte, "DB1.DBB0", 300, BadOutOfRange)]
[InlineData(S7DataType.UInt16, "DB1.DBW0", -1, BadOutOfRange)]
[InlineData(S7DataType.Int32, "DB1.DBD0", "abc", BadTypeMismatch)]
[InlineData(S7DataType.Bool, "DB1.DBX0.0", "abc", BadTypeMismatch)]
public async Task Write_bad_scalar_value_is_a_refusal_not_a_comms_fault(S7DataType dt, string addr, object value, uint expected)
{
var factory = new RecordingFactory();
using var drv = new S7Driver(Options(new S7TagDefinition("T", addr, dt, Writable: true)), "s7-bad-scalar", factory);
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
var res = await drv.WriteAsync([new WriteRequest("T", value)], TestContext.Current.CancellationToken);
res[0].StatusCode.ShouldBe(expected);
factory.Created[0].ScalarWrites.ShouldBe(0);
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
}
/// <summary>Positive control: a real connection failure on a valid value still degrades health.</summary>
[Fact]
public async Task Write_valid_value_with_connection_failure_still_degrades()
{
var factory = new RecordingFactory();
using var drv = new S7Driver(Options(new S7TagDefinition("T", "DB1.DBW0", S7DataType.Int16, Writable: true)), "s7-conn-fail", factory);
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
factory.Created[0].WriteFaults["DB1.DBW0"] = new PlcException(ErrorCode.SendData, "device glitch");
var res = await drv.WriteAsync([new WriteRequest("T", 5)], TestContext.Current.CancellationToken);
res[0].StatusCode.ShouldNotBe(0u);
factory.Created[0].ScalarWrites.ShouldBe(1);
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
}
// ---- STAB-21 connect backoff ----
/// <summary>