Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs
T
Joseph Doherty 3055646688 Merge branch 'worktree-agent-ab2193d7e99435def' into heidenhain-pylsv2-parity
# Conflicts:
#	.claude/rules/drivers.md
#	docs/drivers/Heidenhain.md
2026-11-12 23:56:31 -05:00

451 lines
20 KiB
C#

using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Lsv2;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
/// <summary>Connection state of one controller.</summary>
public enum HeidenhainConnectionState
{
/// <summary>Not started (no subscription/read yet) or between generations.</summary>
Idle,
/// <summary>Opening a session.</summary>
Connecting,
/// <summary>A session is established and polling.</summary>
Connected,
/// <summary>The last connect failed or the session was lost; waiting out the backoff.</summary>
Backoff,
/// <summary>Stopped (driver shutdown).</summary>
Stopped,
}
/// <summary>Builds the client for an endpoint (test seam).</summary>
internal delegate Lsv2Client Lsv2ClientFactory(string host, int port, TimeSpan timeout);
/// <summary>
/// The alarm-walk outcome for a control's <c>ALARM:</c> conditions (lmxopcua#831): <paramref name="status"/> Good
/// with the complete list, or a non-Good status (refusal, overflow, comms loss) with <c>null</c> — never "no alarms".
/// </summary>
internal delegate void HeidenhainAlarmSink(HeidenhainDeviceRuntime runtime, uint status, IReadOnlyList<Lsv2Alarm>? alarms);
/// <summary>A session's controller identity, reported once per established session (lmxopcua#831 rediscovery).</summary>
internal delegate void HeidenhainIdentitySink(HeidenhainDeviceRuntime runtime, Lsv2Versions identity);
/// <summary>
/// One controller's acquisition engine: a single background loop owns the session, so every LSV2 transaction
/// for the device is serialized. The loop connects, polls the three cadence groups, publishes into the cache
/// and, on transport loss, invalidates EVERY remote value of the device at once and reconnects with bounded
/// exponential backoff (port of the reference <c>HeidenhainAcquisition</c> + <c>HeidenhainDevice</c>).
/// </summary>
/// <remarks>
/// <para><b>Generation guard.</b> Each established session is a new generation. Publication checks the
/// generation under <see cref="_publication"/>, so a batch that returns from the wire after its session was
/// retired can never overwrite the outage invalidation. No lock is held across a network read.</para>
/// <para><b>Health vs. per-tag quality.</b> A controller refusal, a denial or a malformed record is per-tag
/// quality and does not degrade the device: only a failed connect or a lost session does. Otherwise a control
/// that simply denies one selector would latch Degraded with nothing for the comms-loss watchdog to fix, and
/// the watchdog would reconnect-loop a production control. The reference's "partial data" aggregate is kept
/// as a diagnostic (<see cref="DataHealth"/>).</para>
/// </remarks>
internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
{
private readonly HeidenhainDeviceOptions _device;
private readonly HeidenhainDriverOptions _options;
private readonly IReadOnlyList<HeidenhainTagDefinition> _tags;
private readonly IReadOnlyDictionary<HeidenhainPollGroup, IReadOnlyList<HeidenhainTagDefinition>> _groups;
private readonly HeidenhainSession.PasswordSource _passwords;
private readonly Action<string, DataValueSnapshot> _publish;
private readonly Action<HeidenhainDeviceRuntime, HeidenhainConnectionState, HeidenhainConnectionState> _stateChanged;
private readonly Lsv2ClientFactory _clientFactory;
private readonly TimeProvider _time;
private readonly ILogger _logger;
private readonly HeidenhainAlarmSink? _alarms;
private readonly HeidenhainIdentitySink? _identity;
private readonly IReadOnlyList<HeidenhainTagDefinition> _alarmTags;
private readonly object _publication = new();
private readonly object _lifecycle = new();
private readonly Dictionary<HeidenhainPollGroup, bool> _groupGood = new();
private CancellationTokenSource? _cts;
private Task? _loop;
private HeidenhainSession? _session;
private long _generation;
private HeidenhainConnectionState _state = HeidenhainConnectionState.Idle;
private DateTime _stateChangedUtc;
private DateTime? _lastSuccessUtc;
private string? _lastError;
private int _consecutiveFailures;
private bool _disposed;
private volatile bool _pollProgress;
/// <summary>Consecutive sessions that ended without one published poll batch (test/diagnostic).</summary>
internal int ConsecutiveFailures => Volatile.Read(ref _consecutiveFailures);
public HeidenhainDeviceRuntime(
HeidenhainDeviceOptions device,
HeidenhainDriverOptions options,
IReadOnlyList<HeidenhainTagDefinition> tags,
HeidenhainSession.PasswordSource passwords,
Action<string, DataValueSnapshot> publish,
Action<HeidenhainDeviceRuntime, HeidenhainConnectionState, HeidenhainConnectionState> stateChanged,
Lsv2ClientFactory clientFactory,
TimeProvider time,
ILogger logger,
HeidenhainAlarmSink? alarms = null,
HeidenhainIdentitySink? identity = null)
{
_device = device;
_options = HeidenhainOptionsParser.Normalize(options);
_tags = tags;
_passwords = passwords;
_publish = publish;
_stateChanged = stateChanged;
_clientFactory = clientFactory;
_time = time;
_logger = logger;
_alarms = alarms;
_identity = identity;
_alarmTags = tags.Where(t => t.IsAlarmCondition).ToList();
_stateChangedUtc = time.GetUtcNow().UtcDateTime;
_groups = tags.GroupBy(t => t.Group).ToDictionary(g => g.Key, g => (IReadOnlyList<HeidenhainTagDefinition>)g.ToList());
}
/// <summary>The <c>host:port</c> key used for host status and per-call host resolution.</summary>
public string HostName => $"{_device.Host}:{_device.Port}";
/// <summary>The <c>/raw</c> Device name.</summary>
public string DeviceName => _device.DeviceName ?? "";
/// <summary>The device's authored tags.</summary>
public IReadOnlyList<HeidenhainTagDefinition> Tags => _tags;
/// <summary>Current connection state.</summary>
public HeidenhainConnectionState State { get { lock (_publication) return _state; } }
/// <summary>When <see cref="State"/> last changed.</summary>
public DateTime StateChangedUtc { get { lock (_publication) return _stateChangedUtc; } }
/// <summary>The last time a batch completed with the session alive (liveness evidence for the watchdog).</summary>
public DateTime? LastSuccessUtc { get { lock (_publication) return _lastSuccessUtc; } }
/// <summary>The last connect/transport error (never a credential).</summary>
public string? LastError { get { lock (_publication) return _lastError; } }
/// <summary>The reference's poll-group aggregate for this generation: Good / Partial / Lost / Idle.</summary>
public string DataHealth
{
get
{
lock (_publication)
{
if (_state != HeidenhainConnectionState.Connected) return _state == HeidenhainConnectionState.Idle ? "Idle" : "Lost";
if (_groupGood.Count != _groups.Count || _groupGood.Values.Any(g => !g)) return "Partial";
return "Good";
}
}
}
/// <summary>The identity of the current session's control, when connected.</summary>
public string? ControllerModel { get { lock (_publication) return _session?.Identity?.Model; } }
/// <summary>The control family classified from the current session's identity, or null.</summary>
public HeidenhainControlFamily? ControllerFamily { get { lock (_publication) return _session?.Identity?.Family; } }
/// <summary>Starts the acquisition loop (idempotent).</summary>
public void Start()
{
lock (_lifecycle)
{
// A Start racing (or following) DisposeAsync must never revive an orphan loop: the driver may be
// iterating a device list it captured just before re-init disposed it.
if (_disposed || _loop is not null) return;
_cts = new CancellationTokenSource();
var token = _cts.Token;
_loop = Task.Run(() => RunAsync(token), CancellationToken.None);
}
}
private async Task RunAsync(CancellationToken ct)
{
// Nothing may kill this loop silently: every iteration — connect, poll, retire, backoff — is guarded,
// and an unexpected fault becomes a logged retire + backoff, never an unobserved faulted task.
while (!ct.IsCancellationRequested)
{
try
{
await RunOnceAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "Heidenhain {Host} acquisition loop fault; retrying", HostName);
try { RetireAll("Acquisition loop fault: " + ex.GetType().Name); }
catch (Exception inner) { _logger.LogError(inner, "Heidenhain {Host} retire failed", HostName); }
}
if (ct.IsCancellationRequested) break;
// Backoff resets only when the last session made real progress (published a poll batch): a control
// that accepts login + version and then drops must not be re-dialled every InitialDelayMs.
if (_pollProgress) _consecutiveFailures = 0;
_consecutiveFailures++;
try
{
SetState(HeidenhainConnectionState.Backoff, null);
await Task.Delay(BackoffDelay(_consecutiveFailures), _time, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; }
catch (Exception ex)
{
_logger.LogError(ex, "Heidenhain {Host} backoff fault", HostName);
try { await Task.Delay(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
}
/// <summary>The reconnect delay for the n-th consecutive failure, clamped to sane bounds (never a hot loop).</summary>
internal TimeSpan BackoffDelay(int failures)
{
var r = _options.Reconnect ?? new HeidenhainReconnectOptions();
var initial = TimeSpan.FromMilliseconds(Math.Clamp(r.InitialDelayMs, 100, 600_000));
var max = TimeSpan.FromMilliseconds(Math.Clamp(r.MaxDelayMs, (int)initial.TotalMilliseconds, 600_000));
return ConnectionBackoff.ComputeDelay(initial, failures, max);
}
private async Task RunOnceAsync(CancellationToken ct)
{
{
HeidenhainSession? session = null;
_pollProgress = false;
try
{
SetState(HeidenhainConnectionState.Connecting, null);
var client = _clientFactory(_device.Host, _device.Port, TimeSpan.FromMilliseconds(_options.TimeoutMs));
session = new HeidenhainSession(client, HeidenhainSessionSettings.From(_options, _tags), _passwords);
await client.OpenAsync(ct).ConfigureAwait(false);
await session.InitializeAsync(ct).ConfigureAwait(false);
long generation;
lock (_publication)
{
generation = ++_generation;
_session = session;
_groupGood.Clear();
}
SetState(HeidenhainConnectionState.Connected, null);
_logger.LogInformation("Heidenhain {Host} connected ({Model})", HostName, session.Identity?.Model);
if (session.Identity is { } identity && _identity is not null)
{
try { _identity(this, identity); }
catch (Exception ex) { _logger.LogWarning(ex, "Heidenhain {Host} identity handler threw", HostName); }
}
await PollAsync(session, generation, ct).ConfigureAwait(false);
// Poll returns only on session loss.
Retire(generation, "LSV2 communication lost");
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
// Connect / INSPECT / identity failure. Never log payloads or credentials: type + refusal code only.
var reason = ex switch
{
Lsv2RefusalException r => $"INSPECT/identity refused (code {r.Code} {Lsv2RefusalCodes.Name(r.Code)})",
Lsv2DecodeException => "Malformed identity record",
_ => ex.Message,
};
RetireAll(reason);
_logger.LogWarning("Heidenhain {Host} connect failed: {Reason}", HostName, reason);
}
finally
{
session?.Close();
}
}
}
private async Task PollAsync(HeidenhainSession session, long generation, CancellationToken ct)
{
var intervals = new Dictionary<HeidenhainPollGroup, TimeSpan>
{
[HeidenhainPollGroup.Status] = TimeSpan.FromMilliseconds(Math.Max(100, _options.Polling.StatusMs)),
[HeidenhainPollGroup.Custom] = TimeSpan.FromMilliseconds(Math.Max(100, _options.Polling.CustomMs)),
[HeidenhainPollGroup.Slow] = TimeSpan.FromMilliseconds(Math.Max(100, _options.Polling.SlowMs)),
[HeidenhainPollGroup.Alarm] = TimeSpan.FromMilliseconds(Math.Max(100, _options.Polling.AlarmMs)),
};
var start = _time.GetTimestamp();
var due = _groups.Keys.ToDictionary(g => g, _ => TimeSpan.Zero);
if (due.Count == 0)
{
// No tags: keep the session as a liveness check only at the slow cadence via identity.
await Task.Delay(Timeout.InfiniteTimeSpan, _time, ct).ConfigureAwait(false);
return;
}
while (!ct.IsCancellationRequested)
{
var elapsed = _time.GetElapsedTime(start);
foreach (var group in new[] { HeidenhainPollGroup.Status, HeidenhainPollGroup.Alarm, HeidenhainPollGroup.Custom, HeidenhainPollGroup.Slow })
{
if (!due.TryGetValue(group, out var at) || at > elapsed) continue;
var tags = _groups[group];
var samples = await session.ReadBatchAsync(tags, ct).ConfigureAwait(false);
if (!Publish(generation, session, group, tags, samples)) return;
due[group] = elapsed + intervals[group];
}
var next = due.Values.Min() - _time.GetElapsedTime(start);
if (next > TimeSpan.Zero) await Task.Delay(next, _time, ct).ConfigureAwait(false);
}
}
/// <summary>Publishes one batch iff its generation is still current. False when the session is lost/retired.</summary>
private bool Publish(long generation, HeidenhainSession session, HeidenhainPollGroup group,
IReadOnlyList<HeidenhainTagDefinition> tags, IReadOnlyList<HeidenhainSample> samples)
{
var now = _time.GetUtcNow().UtcDateTime;
lock (_publication)
{
if (generation != _generation || !ReferenceEquals(_session, session)) return false;
if (session.CommunicationLost) return false;
var good = true;
var alarmsDelivered = false;
for (var i = 0; i < tags.Count; i++)
{
var s = samples[i];
if (tags[i].IsAlarmCondition)
{
// One alarm walk per batch serves every ALARM: condition of this control (they share the outcome).
if (!alarmsDelivered) DeliverAlarms(s.Status, s.Status == HeidenhainStatus.Good ? s.Value as IReadOnlyList<Lsv2Alarm> : null);
alarmsDelivered = true;
if (s.Status != HeidenhainStatus.Good) good = false;
continue;
}
_publish(tags[i].RawPath, new DataValueSnapshot(s.Value, s.Status, now, now));
if (tags[i].Address.Catalog?.IsCapability == true) continue;
// Explicitly disabled optional timers are not partial data.
if (s.Status != HeidenhainStatus.Good
&& !(tags[i].Address.Catalog?.Feature.StartsWith("Timer_", StringComparison.Ordinal) == true && !_options.Polling.TimersEnabled))
good = false;
}
_groupGood[group] = good;
_lastSuccessUtc = now;
_pollProgress = true;
return true;
}
}
private void Retire(long generation, string reason)
{
lock (_publication)
{
if (generation != _generation) return;
}
RetireAll(reason);
_logger.LogWarning("Heidenhain {Host}: {Reason}; reconnecting with backoff", HostName, reason);
}
/// <summary>Retires the session and invalidates every remote value (capabilities report CommunicationLost).</summary>
private void RetireAll(string reason)
{
HeidenhainSession? old;
var now = _time.GetUtcNow().UtcDateTime;
lock (_publication)
{
old = _session;
_session = null;
_generation++;
_groupGood.Clear();
_lastError = reason;
Invalidate(now);
}
old?.Close();
SetState(HeidenhainConnectionState.Backoff, reason);
}
private void Invalidate(DateTime now)
{
if (_alarmTags.Count > 0) DeliverAlarms(HeidenhainStatus.BadNoCommunication, null);
foreach (var tag in _tags)
{
if (tag.IsAlarmCondition) continue;
_publish(tag.RawPath, tag.Address.Catalog?.IsCapability == true
? new DataValueSnapshot(HeidenhainCatalog.States.CommunicationLost, HeidenhainStatus.Good, now, now)
: new DataValueSnapshot(null, HeidenhainStatus.BadNoCommunication, now, now));
}
}
/// <summary>Hands an alarm-walk outcome to the projection. Called under <see cref="_publication"/> (ordered with the generation).</summary>
private void DeliverAlarms(uint status, IReadOnlyList<Lsv2Alarm>? alarms)
{
if (_alarms is null) return;
if (status == HeidenhainStatus.Good && alarms is null) status = HeidenhainStatus.BadDecodingError;
try { _alarms(this, status, status == HeidenhainStatus.Good ? alarms : null); }
catch (Exception ex) { _logger.LogWarning(ex, "Heidenhain {Host} alarm projection threw", HostName); }
}
private void SetState(HeidenhainConnectionState next, string? error)
{
HeidenhainConnectionState old;
lock (_publication)
{
old = _state;
if (error is not null) _lastError = error;
if (next == HeidenhainConnectionState.Connected) _lastError = null;
if (old == next) return;
_state = next;
_stateChangedUtc = _time.GetUtcNow().UtcDateTime;
}
try { _stateChanged(this, old, next); }
catch (Exception ex) { _logger.LogDebug(ex, "Heidenhain state-change handler threw"); }
}
/// <summary>Stops the loop: closes the session first (unblocks a read), cancels, joins ≤ 5 s, invalidates.</summary>
public async ValueTask DisposeAsync()
{
Task? loop;
CancellationTokenSource? cts;
lock (_lifecycle)
{
_disposed = true;
loop = _loop;
cts = _cts;
_loop = null;
_cts = null;
}
HeidenhainSession? session;
lock (_publication) session = _session;
session?.Close();
if (cts is not null) await cts.CancelAsync().ConfigureAwait(false);
if (loop is not null)
{
try { await loop.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); }
catch (Exception ex) when (ex is TimeoutException or OperationCanceledException) { /* bounded join */ }
}
cts?.Dispose();
lock (_publication)
{
_session = null;
_generation++;
}
SetState(HeidenhainConnectionState.Stopped, null);
}
}