using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS;
///
/// Polls the CNC active-alarm list (cnc_rdalmmsg2) of every device that owns a subscribed
/// ALARM: raw tag and drives ONE Part 9 condition per such tag.
///
///
///
/// Which tags are conditions. The server decides: a raw tag whose TagConfig carries the
/// cross-driver alarm object is materialised as a condition at its RawPath, and those RawPaths
/// arrive through . Every event uses the RawPath as
/// — the exact key the host routes on — and carries a
/// , without which the host's projector keeps the prior state. Before
/// alarm selectors were supported this class treated the RawPaths as device-host filters (so nothing was ever polled) and raised
/// "{host}#{Type}:{Number}" with no kind (so nothing would have routed anyway).
///
///
/// A failed read is not an empty list. throws on any
/// failure; the device is then skipped for that tick and every condition on it keeps its state. The
/// host already annotates the driver's conditions BadNoCommunication on comms loss.
///
///
/// Delivery is diffed against what the server was TOLD (, the MTConnect
/// pattern), recorded only while an OnAlarmEvent handler is attached. The record lives on this
/// object, which lives as long as the driver: it survives a re-subscribe with the same set (a reconnect),
/// a re-initialise and a shutdown/re-init cycle — the server's condition nodes outlive all three, and
/// re-raising there would un-acknowledge an acknowledged alarm. A changed subscribed set prunes only the
/// RawPaths that LEFT it (the server carries every survivor across the rebuild).
///
///
/// One poll loop, owned by the current subscription. Evaluation and delivery run under
/// and re-check that the subscription is still current, so a superseded loop
/// that is still finishing its last read can never emit — the duplicate-per-reconnect window the old
/// design documented is closed. The only production handler is DriverInstanceActor's
/// non-blocking Tell.
///
/// Read-only. FOCAS has no alarm acknowledgement; the Part 9 Acknowledge is applied server-side.
///
internal sealed class FocasAlarmProjection : IAsyncDisposable
{
private readonly FocasDriver _driver;
private readonly ILogger _logger;
/// Serializes evaluation + delivery + the told record. Never held across an await.
private readonly Lock _alarmLock = new();
/// ConditionId (RawPath) → what the server was last told. Guarded by .
private readonly Dictionary _told = new(StringComparer.Ordinal);
/// Per device: the alarm keys already logged as matched by no tag. Guarded by .
private readonly Dictionary> _unmatchedLogged = new(StringComparer.OrdinalIgnoreCase);
/// Devices whose last read came back at the per-read cap. Guarded by .
private readonly HashSet _truncationWarned = new(StringComparer.OrdinalIgnoreCase);
///
/// Devices whose alarm read is currently failing → the quality that failure maps to (one Warning per episode
/// and per kind: a refusal turning into a transport fault warns again). Guarded by .
///
private readonly Dictionary _failingDevices = new(StringComparer.OrdinalIgnoreCase);
///
/// ConditionIds this projection has annotated BadNoCommunication and not yet lifted. Guarded by
/// . Kept apart from : a quality annotation never touches a
/// condition's Active/Acked state.
///
private readonly Dictionary _qualityBadTold = new(StringComparer.Ordinal);
/// Canonical Opc.Ua.StatusCodes.Good.
private const uint QualityGood = 0x00000000u;
/// Canonical Opc.Ua.StatusCodes.BadNoCommunication — the CNC could not be reached.
private const uint QualityBadNoCommunication = 0x80310000u;
///
/// Whether an alarm-read failure is a CNC REFUSAL: the CNC answered with a non-OK
/// FOCAS return code, so the transport is fine and the control simply will not serve cnc_rdalmmsg2
/// (e.g. EW_FUNC, as cnc_rdparam does on the Makino). That is a capability answer, not comms
/// loss: it must NOT degrade driver health, or an alarm-only driver on such a control would be reconnected by
/// the comms-loss watchdog every 90 s forever. Everything else (session down, wire fault, malformed reply, backoff)
/// is a transport failure.
///
/// The alarm-read failure.
/// for a refusal.
internal static bool IsCncRefusal(Exception error) => error is Wire.FocasWireException { Rc: not null };
/// Serializes loop start/stop.
private readonly SemaphoreSlim _loopGate = new(1, 1);
private Subscription? _current;
private CancellationTokenSource? _loopCts;
private Task _loop = Task.CompletedTask;
private long _nextId;
/// Initializes a new FOCAS alarm projection.
/// The owning driver.
/// Optional logger.
public FocasAlarmProjection(FocasDriver driver, ILogger? logger = null)
{
_driver = driver;
_logger = logger ?? NullLogger.Instance;
}
/// Gets the live subscription, or . Test seam.
internal Subscription? Current => Volatile.Read(ref _current);
///
/// Replaces the live subscription with one over (alarm-tag RawPaths) and
/// (re)starts the poll loop. Collapses to ONE subscription: the owning DriverInstanceActor is the
/// only caller and re-subscribes on every Connected entry.
///
/// The alarm-bearing raw tags' RawPaths.
/// The subscription handle.
public async Task SubscribeAsync(IReadOnlyList sourceNodeIds)
{
ArgumentNullException.ThrowIfNull(sourceNodeIds);
var refs = new HashSet(StringComparer.Ordinal);
foreach (var r in sourceNodeIds)
if (!string.IsNullOrWhiteSpace(r)) refs.Add(r);
var sub = new Subscription(new FocasAlarmSubscriptionHandle(Interlocked.Increment(ref _nextId)), refs);
lock (_alarmLock)
{
// Forget only the conditions that LEFT the set — the SAME set (a reconnect) prunes nothing.
foreach (var gone in _told.Keys.Where(k => !refs.Contains(k)).ToList()) _told.Remove(gone);
// A (re)subscribe follows a reconnect, where the host re-annotates every condition Good; forget
// which conditions this projection marked Bad, so a still-failing device re-asserts its Bad.
_qualityBadTold.Clear();
Volatile.Write(ref _current, sub);
}
await RestartLoopAsync().ConfigureAwait(false);
return sub.Handle;
}
/// Drops the live subscription when is it; a superseded handle is a no-op.
/// The handle returned by .
/// A task representing the asynchronous operation.
public async Task UnsubscribeAsync(IAlarmSubscriptionHandle handle)
{
lock (_alarmLock)
{
if (Volatile.Read(ref _current) is not { } live || !ReferenceEquals(live.Handle, handle)) return;
Volatile.Write(ref _current, null);
}
await StopLoopAsync().ConfigureAwait(false);
}
///
/// FOCAS has no ack wire call — the CNC clears alarms on its own when the underlying condition resolves.
/// The Part 9 Acknowledge is applied server-side; this is the no-op success the host routes it to, so
/// nothing is ever written to the CNC.
///
/// Alarms to acknowledge.
/// A completed task.
public static Task AcknowledgeAsync(IReadOnlyList acknowledgements)
{
ArgumentNullException.ThrowIfNull(acknowledgements);
return Task.CompletedTask;
}
///
/// Stops the poll loop but KEEPS the subscription and the told record — the device/tag tables are about
/// to be rebuilt (re-initialise, shutdown). restarts it.
///
/// A task representing the asynchronous operation.
public Task PauseAsync() => StopLoopAsync();
/// Restarts the poll loop when a subscription is live — after the driver's tables are rebuilt.
/// A task representing the asynchronous operation.
public Task ResumeAsync() => Volatile.Read(ref _current) is null ? Task.CompletedTask : RestartLoopAsync();
/// Stops the poll loop and releases the projection.
/// A task that represents the asynchronous operation.
public async ValueTask DisposeAsync() => await StopLoopAsync().ConfigureAwait(false);
private async Task RestartLoopAsync()
{
await _loopGate.WaitAsync().ConfigureAwait(false);
try
{
await StopLoopCoreAsync().ConfigureAwait(false);
if (Volatile.Read(ref _current) is not { } sub) return;
var cts = new CancellationTokenSource();
_loopCts = cts;
_loop = Task.Run(() => RunPollLoopAsync(sub, cts.Token), CancellationToken.None);
}
finally { _loopGate.Release(); }
}
private async Task StopLoopAsync()
{
await _loopGate.WaitAsync().ConfigureAwait(false);
try { await StopLoopCoreAsync().ConfigureAwait(false); }
finally { _loopGate.Release(); }
}
/// Cancels and joins the loop (bounded). Caller holds .
private async Task StopLoopCoreAsync()
{
if (_loopCts is not { } cts) return;
_loopCts = null;
try { cts.Cancel(); }
catch (Exception ex) { _logger.LogDebug(ex, "Cancelling the FOCAS alarm poll loop failed"); }
var loop = _loop;
try
{
var finished = await Task.WhenAny(loop, Task.Delay(FocasDriver.LoopJoinTimeout)).ConfigureAwait(false);
if (finished != loop)
_logger.LogWarning("FOCAS alarm poll loop did not stop within {Timeout}; it cannot emit once superseded",
FocasDriver.LoopJoinTimeout);
}
catch (Exception ex) { _logger.LogDebug(ex, "Awaiting the FOCAS alarm poll loop failed"); }
cts.Dispose();
}
private async Task RunPollLoopAsync(Subscription sub, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await PollOnceAsync(sub, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; }
catch (Exception ex)
{
_logger.LogDebug(ex, "FOCAS alarm-projection poll tick failed");
}
try { await Task.Delay(_driver.AlarmPollInterval, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
/// One pass: read each device that owns a subscribed alarm tag, and evaluate its conditions.
/// The subscription the pass serves.
/// Cancellation.
/// A task representing the asynchronous operation.
internal async Task PollOnceAsync(Subscription sub, CancellationToken ct)
{
var tags = _driver.AlarmTags;
var devices = sub.References
.Select(r => tags.GetValueOrDefault(r))
.OfType()
.Select(t => t.DeviceHostAddress)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
foreach (var host in devices)
{
ct.ThrowIfCancellationRequested();
IReadOnlyList alarms;
try
{
alarms = await _driver.ReadDeviceAlarmsAsync(host, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception ex)
{
// Not "no alarms": keep every condition on this device exactly as the server was last told, but say
// why it cannot be read. A transport failure reaches driver health (an alarm-only driver has no other
// read to trip the comms-loss watchdog with); a CNC refusal does not (R2). Polling continues at the
// normal cadence either way.
if (!IsCncRefusal(ex)) _driver.NoteAlarmReadFailed(host, ex);
else _driver.NoteAlarmReadRefused(host); // the CNC answered: the transport to it is fine
TickFailed(sub, host, tags, ex);
continue;
}
_driver.NoteAlarmReadSucceeded(host);
Tick(sub, host, alarms, tags);
}
}
///
/// Evaluates every subscribed condition on against one SUCCESSFUL read
/// and delivers what changed. Extracted so tests can drive a tick without the loop.
///
/// The subscription the read was taken for; a superseded one emits nothing.
/// The device read.
/// Its active alarms.
/// The driver's alarm-tag table (RawPath → tag).
internal void Tick(
Subscription sub,
string deviceHostAddress,
IReadOnlyList alarms,
IReadOnlyDictionary tags)
{
var deviceTags = tags.Values
.Where(t => string.Equals(t.DeviceHostAddress, deviceHostAddress, StringComparison.OrdinalIgnoreCase))
.ToList();
var deviceSelectors = deviceTags.Select(t => t.Selector).ToList();
var truncated = alarms.Count >= Wire.WireFocasClient.MaxAlarmsPerRead;
var now = DateTime.UtcNow;
lock (_alarmLock)
{
if (!ReferenceEquals(Volatile.Read(ref _current), sub)) return;
NoteTruncation(deviceHostAddress, truncated, alarms.Count);
NoteUnmatched(deviceHostAddress, alarms, deviceSelectors);
// Nobody to tell (the host detached while it reconnects): record nothing, so the re-subscribe that
// follows still sees the difference and delivers it.
var handlers = _driver.AlarmHandlers;
if (handlers is null) return;
if (_failingDevices.Remove(deviceHostAddress, out _))
_logger.LogInformation("FOCAS alarm read for {Host} recovered", deviceHostAddress);
foreach (var tag in deviceTags.Where(t => sub.References.Contains(t.RawPath)))
{
// Lift a Bad this projection put there BEFORE the normal diff, so a recovery that also changed the
// alarm state (cleared during the outage) lands as Good then Clear.
if (_qualityBadTold.Remove(tag.RawPath, out _))
Deliver(handlers, QualityOnly(tag, sub.Handle, QualityGood, now), tag.RawPath);
var view = FocasAlarmMatcher.Evaluate(tag.Selector, alarms, deviceSelectors, truncated);
_told.TryGetValue(tag.RawPath, out var told);
var (evt, nowTold) = FocasAlarmConditionMapper.Transition(told, view, tag, sub.Handle, now);
_told[tag.RawPath] = nowTold;
if (evt is null) continue;
Deliver(handlers, evt, tag.RawPath);
}
}
}
///
/// A FAILED read of : conditions keep their state, but
/// each subscribed one is annotated once per outage through the quality-only path (no Active/Acked change,
/// no /alerts row) — BadNoCommunication for a transport failure, BadNotSupported for a CNC
/// refusal (R2, ) — and the first failure of the episode (per kind) logs one
/// Warning. The next successful read lifts the Bad in .
///
/// The subscription the read was taken for; a superseded one emits nothing.
/// The device whose read failed.
/// The driver's alarm-tag table (RawPath → tag).
/// Why the read failed.
internal void TickFailed(
Subscription sub, string deviceHostAddress, IReadOnlyDictionary tags, Exception error)
{
var now = DateTime.UtcNow;
lock (_alarmLock)
{
if (!ReferenceEquals(Volatile.Read(ref _current), sub)) return;
var refusal = IsCncRefusal(error);
var quality = refusal ? FocasStatusMapper.BadNotSupported : QualityBadNoCommunication;
if (!_failingDevices.TryGetValue(deviceHostAddress, out var was) || was != quality)
{
_failingDevices[deviceHostAddress] = quality;
if (refusal)
_logger.LogWarning(error,
"FOCAS CNC {Host} refuses the alarm read (cnc_rdalmmsg2); its alarm conditions keep their state " +
"and are marked BadNotSupported. This is a capability answer, not comms loss — driver health is " +
"unaffected and polling continues", deviceHostAddress);
else
_logger.LogWarning(error,
"FOCAS alarm read (cnc_rdalmmsg2) failed for {Host}; its alarm conditions keep their state and " +
"are marked BadNoCommunication until a read succeeds", deviceHostAddress);
}
else
_logger.LogDebug(error, "FOCAS alarm read for {Host} still failing", deviceHostAddress);
// As for transitions: with nobody listening, record nothing, so the next failure tells it.
var handlers = _driver.AlarmHandlers;
if (handlers is null) return;
foreach (var tag in tags.Values.Where(t =>
string.Equals(t.DeviceHostAddress, deviceHostAddress, StringComparison.OrdinalIgnoreCase)
&& sub.References.Contains(t.RawPath)))
{
if (_qualityBadTold.TryGetValue(tag.RawPath, out var told) && told == quality) continue;
_qualityBadTold[tag.RawPath] = quality;
Deliver(handlers, QualityOnly(tag, sub.Handle, quality, now), tag.RawPath);
}
}
}
/// A quality-only annotation: + a status code.
private AlarmEventArgs QualityOnly(FocasAlarmTag tag, IAlarmSubscriptionHandle handle, uint quality, DateTime now)
{
_told.TryGetValue(tag.RawPath, out var told);
return new AlarmEventArgs(handle,
SourceNodeId: tag.DeviceHostAddress,
ConditionId: tag.RawPath,
AlarmType: told?.Winner is { } w ? FocasAlarmConditionMapper.TypeLabel(w.Type) : "CncAlarm",
Message: told?.Message ?? "",
Severity: told?.Severity ?? AlarmSeverity.Low,
SourceTimestampUtc: now,
Kind: AlarmTransitionKind.Unspecified,
OpcUaSeverity: told?.OpcUaSeverity,
QualityStatusCode: quality);
}
/// Invokes every handler, isolating a faulting one. Caller holds the lock.
private void Deliver(EventHandler handlers, AlarmEventArgs evt, string conditionId)
{
foreach (var registration in handlers.GetInvocationList())
{
try { ((EventHandler)registration).Invoke(_driver, evt); }
catch (Exception ex)
{
_logger.LogWarning(ex,
"FOCAS driver caught a fault from an alarm subscriber for {ConditionId}; delivery continues.",
conditionId);
}
}
}
/// Warns once (per episode) when a read came back at the per-read cap. Caller holds the lock.
private void NoteTruncation(string host, bool truncated, int count)
{
if (!truncated)
{
_truncationWarned.Remove(host);
return;
}
if (_truncationWarned.Add(host))
_logger.LogWarning(
"FOCAS device {Host} returned {Count} active alarms — the per-read cap; more may be active and unseen. " +
"ALARM:* / ALARM:OTHER conditions on it are marked '[alarm list truncated]'.", host, count);
}
///
/// Logs (once per alarm) an active alarm that no condition on its device will show — no *, no
/// OTHER and no matching type selector. Caller holds the lock.
///
private void NoteUnmatched(string host, IReadOnlyList alarms, IReadOnlyCollection selectors)
{
var uncovered = alarms.Where(a => !FocasAlarmMatcher.IsCovered(a, selectors))
.Select(a => new FocasAlarmKey(a.Type, a.AlarmNumber))
.ToHashSet();
if (!_unmatchedLogged.TryGetValue(host, out var logged))
_unmatchedLogged[host] = logged = [];
foreach (var key in uncovered.Where(k => !logged.Contains(k)))
_logger.LogInformation(
"FOCAS device {Host} has active alarm {Number} (type {Type}) that no ALARM: tag selects — author " +
"ALARM:OTHER or ALARM:* on the device to surface it.", host, key.Number, key.Type);
// Remember exactly the currently-uncovered set, so an alarm that clears and comes back is logged again.
_unmatchedLogged[host] = uncovered;
}
/// The live alarm subscription: its handle and the ConditionIds (RawPaths) it names.
/// The handle.
/// The subscribed RawPaths.
internal sealed record Subscription(FocasAlarmSubscriptionHandle Handle, IReadOnlySet References);
}
/// Handle returned by .
public sealed record FocasAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle
{
///
public string DiagnosticId => $"focas-alarm-sub-{Id}";
}