feat(grpc-data): A1 initial-alarm-state signal in DriverInstanceActor/DriverHostActor — ordered forward, MarkConditionsKnown routing, OpcUaClient backstop, F5 signal timeout + diagnostic

This commit is contained in:
Joseph Doherty
2026-11-24 09:30:32 -05:00
parent d64578b1c5
commit ffdaa73d0c
5 changed files with 341 additions and 5 deletions
@@ -0,0 +1,100 @@
using System.Globalization;
using Microsoft.Extensions.Configuration;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// A1 (plan §5.1 F5 + the OpcUaClient backstop): how long <c>DriverHostActor</c> waits for a native driver's
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/>, and the per-driver-type backstop for a source
/// that reports itself unsignalable. Both are measured from the driver's quality going Good.
/// </summary>
/// <remarks>
/// <para><c>DataConnections:ConditionKnownSignalTimeout:&lt;DriverType&gt;</c> — default 120 s. On expiry the
/// conditions <b>stay unknown</b> (never known-inactive); the "initial alarm state not signalled" diagnostic is
/// raised on the <see cref="ConditionStateHub"/> and a later signal clears it.</para>
/// <para><c>DataConnections:ConditionKnownSettle:&lt;DriverType&gt;</c> — the backstop timer. Only
/// <see cref="DriverTypeNames.OpcUaClient"/> has one (default 60 s): an upstream with no ConditionRefresh is the
/// one source with no signal at all. A settle configured for any other driver type is ignored.</para>
/// <para>Values are seconds (<c>120</c>) or a <see cref="TimeSpan"/> (<c>00:02:00</c>).</para>
/// </remarks>
public sealed class ConditionSignalOptions
{
/// <summary>The configuration section of the per-DriverType signal timeouts.</summary>
public const string SignalTimeoutSection = "DataConnections:ConditionKnownSignalTimeout";
/// <summary>The configuration section of the per-DriverType backstop settle windows.</summary>
public const string SettleSection = "DataConnections:ConditionKnownSettle";
/// <summary>The default signal timeout (F5).</summary>
public static readonly TimeSpan DefaultSignalTimeout = TimeSpan.FromSeconds(120);
/// <summary>The default OpcUaClient backstop settle window.</summary>
public static readonly TimeSpan DefaultOpcUaClientSettle = TimeSpan.FromSeconds(60);
private readonly Dictionary<string, TimeSpan> _signalTimeouts = new(StringComparer.OrdinalIgnoreCase);
private TimeSpan _opcUaClientSettle = DefaultOpcUaClientSettle;
/// <summary>The hub the F5 diagnostic is raised on (null ⇒ log + counter only).</summary>
public ConditionStateHub? Hub { get; init; }
/// <summary>The signal timeout for <paramref name="driverType"/>.</summary>
/// <param name="driverType">The driver type.</param>
/// <returns>The timeout.</returns>
public TimeSpan SignalTimeoutFor(string driverType) =>
_signalTimeouts.TryGetValue(driverType, out var t) ? t : DefaultSignalTimeout;
/// <summary>The backstop settle window for <paramref name="driverType"/>, or null when it has none.</summary>
/// <param name="driverType">The driver type.</param>
/// <returns>The window.</returns>
public TimeSpan? BackstopSettleFor(string driverType) =>
string.Equals(driverType, DriverTypeNames.OpcUaClient, StringComparison.OrdinalIgnoreCase) ? _opcUaClientSettle : null;
/// <summary>Override one driver type's signal timeout (tests, configuration).</summary>
/// <param name="driverType">The driver type.</param>
/// <param name="timeout">The timeout (&gt; 0).</param>
/// <returns>This instance.</returns>
public ConditionSignalOptions WithSignalTimeout(string driverType, TimeSpan timeout)
{
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(timeout, TimeSpan.Zero);
_signalTimeouts[driverType] = timeout;
return this;
}
/// <summary>Override the OpcUaClient backstop window (tests, configuration).</summary>
/// <param name="settle">The window (≥ 0).</param>
/// <returns>This instance.</returns>
public ConditionSignalOptions WithOpcUaClientSettle(TimeSpan settle)
{
ArgumentOutOfRangeException.ThrowIfLessThan(settle, TimeSpan.Zero);
_opcUaClientSettle = settle;
return this;
}
/// <summary>Bind from configuration; malformed or non-positive values throw (fail host start).</summary>
/// <param name="configuration">The configuration, or null for the defaults.</param>
/// <param name="hub">The condition-state hub.</param>
/// <returns>The options.</returns>
public static ConditionSignalOptions FromConfiguration(IConfiguration? configuration, ConditionStateHub? hub)
{
var options = new ConditionSignalOptions { Hub = hub };
if (configuration is null) return options;
foreach (var child in configuration.GetSection(SignalTimeoutSection).GetChildren())
options.WithSignalTimeout(child.Key, Parse(child.Path, child.Value));
foreach (var child in configuration.GetSection(SettleSection).GetChildren())
{
if (string.Equals(child.Key, DriverTypeNames.OpcUaClient, StringComparison.OrdinalIgnoreCase))
options.WithOpcUaClientSettle(Parse(child.Path, child.Value));
}
return options;
}
private static TimeSpan Parse(string path, string? value)
{
if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var seconds) && seconds > 0)
return TimeSpan.FromSeconds(seconds);
if (TimeSpan.TryParse(value, CultureInfo.InvariantCulture, out var span) && span > TimeSpan.Zero) return span;
throw new InvalidOperationException($"{path} '{value}' is not a positive number of seconds or a TimeSpan.");
}
}
@@ -0,0 +1,197 @@
using Akka.Actor;
using Akka.Event;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using PublishActor = ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
/// <summary>
/// A1 (plan §5.1 T1/T2/F2/F5): native "standing alarms delivered" signals become
/// <see cref="PublishActor.MarkConditionsKnown"/>, sent to the publish actor AFTER the
/// <see cref="PublishActor.AlarmStateUpdate"/>s this host already forwarded for the same driver (Akka per-pair order),
/// plus the two Akka-scheduled timers that enter the same chain: the OpcUaClient-only backstop and the F5 signal
/// timeout.
/// </summary>
public sealed partial class DriverHostActor
{
private sealed record ConditionSignalTimedOut(string DriverInstanceId, long Epoch);
private sealed record ConditionBackstopElapsed(string DriverInstanceId, long Epoch);
/// <summary>Per driver instance: the current connectivity epoch, when its quality went Good, the conditions not
/// yet signalled since then, and the conditions the driver reported unsignalable.</summary>
private sealed class ConditionSignalTracker
{
public long Epoch;
public DateTime? GoodSinceUtc;
public readonly HashSet<string> Pending = new(StringComparer.Ordinal);
public readonly HashSet<string> Unsignalable = new(StringComparer.Ordinal);
public bool DiagnosticRaised;
}
private readonly ConditionSignalOptions _conditionSignals;
private readonly Dictionary<string, ConditionSignalTracker> _conditionSignalTrackers = new(StringComparer.Ordinal);
private static string SignalTimeoutKey(string driverInstanceId) => "cond-signal-timeout:" + driverInstanceId;
private static string BackstopKey(string driverInstanceId) => "cond-backstop:" + driverInstanceId;
private void ReceiveConditionSignals()
{
Receive<DriverInstanceActor.AlarmInitialStatePublished>(OnAlarmInitialState);
Receive<ConditionSignalTimedOut>(OnConditionSignalTimedOut);
Receive<ConditionBackstopElapsed>(OnConditionBackstopElapsed);
}
private void ReceiveConditionSignalsWhileStale()
{
Receive<DriverInstanceActor.AlarmInitialStatePublished>(m =>
_log.Debug("DriverHost {Node}: dropping an initial alarm-state signal from {Id} while Stale", _localNode, m.DriverInstanceId));
Receive<ConditionSignalTimedOut>(_ => { });
Receive<ConditionBackstopElapsed>(_ => { });
}
private ConditionSignalTracker Tracker(string driverInstanceId)
{
if (!_conditionSignalTrackers.TryGetValue(driverInstanceId, out var t))
_conditionSignalTrackers[driverInstanceId] = t = new ConditionSignalTracker();
return t;
}
private string? DriverTypeOf(string driverInstanceId) =>
_children.TryGetValue(driverInstanceId, out var child) ? child.DriverType : null;
/// <summary>A connectivity edge restarts the F5 window (from quality Good) and the backstop; a Bad edge cancels both.</summary>
private void OnConditionSignalConnectivity(string driverInstanceId, bool connected)
{
var t = Tracker(driverInstanceId);
t.Epoch++;
Timers.Cancel(SignalTimeoutKey(driverInstanceId));
Timers.Cancel(BackstopKey(driverInstanceId));
t.Pending.Clear();
if (!connected)
{
t.GoodSinceUtc = null;
return;
}
t.GoodSinceUtc = DateTime.UtcNow;
if (_alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs))
foreach (var (rawPath, _) in refs) t.Pending.Add(rawPath);
if (t.Pending.Count > 0 && DriverTypeOf(driverInstanceId) is { } type)
{
Timers.StartSingleTimer(SignalTimeoutKey(driverInstanceId), new ConditionSignalTimedOut(driverInstanceId, t.Epoch),
_conditionSignals.SignalTimeoutFor(type));
}
if (t.Unsignalable.Count > 0) ScheduleBackstop(driverInstanceId, t);
}
private void OnAlarmInitialState(DriverInstanceActor.AlarmInitialStatePublished msg)
{
var t = Tracker(msg.DriverInstanceId);
if (msg.Args.Unsignalable)
{
// InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks
// these known — after its settle window from quality Good. Any other type: they stay unknown.
t.Unsignalable.UnionWith(msg.Args.ConditionIds);
ScheduleBackstop(msg.DriverInstanceId, t);
return;
}
var marked = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds);
t.Pending.ExceptWith(msg.Args.ConditionIds);
t.Unsignalable.ExceptWith(msg.Args.ConditionIds);
if (t.Pending.Count == 0)
{
Timers.Cancel(SignalTimeoutKey(msg.DriverInstanceId));
// F5: a late signal clears the "not signalled" diagnostic.
if (t.DiagnosticRaised)
{
t.DiagnosticRaised = false;
_conditionSignals.Hub?.ClearUnsignalled(msg.DriverInstanceId);
_log.Info("DriverHost {Node}: driver {Driver} signalled its initial alarm state late — diagnostic cleared",
_localNode, msg.DriverInstanceId);
}
}
_log.Debug("DriverHost {Node}: driver {Driver} established {Count} condition(s) ({Marked} routed)",
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, marked);
}
private void ScheduleBackstop(string driverInstanceId, ConditionSignalTracker t)
{
if (t.GoodSinceUtc is not { } goodSince) return; // armed on the next Good edge
if (DriverTypeOf(driverInstanceId) is not { } type || _conditionSignals.BackstopSettleFor(type) is not { } settle)
{
_log.Debug("DriverHost {Node}: driver {Driver} reported unsignalable conditions but its type has no backstop — they stay unknown",
_localNode, driverInstanceId);
return;
}
var remaining = goodSince + settle - DateTime.UtcNow;
Timers.StartSingleTimer(BackstopKey(driverInstanceId), new ConditionBackstopElapsed(driverInstanceId, t.Epoch),
remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero);
}
private void OnConditionBackstopElapsed(ConditionBackstopElapsed msg)
{
if (!_conditionSignalTrackers.TryGetValue(msg.DriverInstanceId, out var t) || t.Epoch != msg.Epoch || t.GoodSinceUtc is null)
return;
var ids = t.Unsignalable.ToList();
t.Unsignalable.Clear();
t.Pending.ExceptWith(ids);
if (t.Pending.Count == 0) Timers.Cancel(SignalTimeoutKey(msg.DriverInstanceId));
var marked = MarkDriverConditionsKnown(msg.DriverInstanceId, ids);
_log.Info("DriverHost {Node}: backstop settled — {Count} unsignalable condition(s) of {Driver} marked known (residual: an upstream alarm active and never re-transitioned reads inactive)",
_localNode, marked, msg.DriverInstanceId);
}
private void OnConditionSignalTimedOut(ConditionSignalTimedOut msg)
{
if (!_conditionSignalTrackers.TryGetValue(msg.DriverInstanceId, out var t) || t.Epoch != msg.Epoch || t.Pending.Count == 0)
return;
// F5: the conditions STAY unknown (Uncertain on a consumer) — never known-inactive.
var elapsed = t.GoodSinceUtc is { } since ? DateTime.UtcNow - since : TimeSpan.Zero;
t.DiagnosticRaised = true;
if (_conditionSignals.Hub is { } hub) hub.ReportUnsignalled(msg.DriverInstanceId, elapsed, t.Pending.Count);
else OtOpcUaTelemetry.DataConnConditionsUnsignalled.Add(t.Pending.Count,
new KeyValuePair<string, object?>("driver", msg.DriverInstanceId));
_log.Warning("DriverHost {Node}: initial alarm state not signalled — driver {Driver}, {Count} condition(s) still unknown after {Elapsed}",
_localNode, msg.DriverInstanceId, t.Pending.Count, elapsed);
}
/// <summary>Route driver condition ids (RawPaths) to their condition nodes and send one mark per realm.</summary>
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds)
{
if (_opcUaPublishActor is null || conditionIds.Count == 0) return 0;
var byRealm = new Dictionary<AddressSpaceRealm, List<string>>();
foreach (var id in conditionIds)
{
if (!_alarmNodeIdByDriverRef.TryGetValue((driverInstanceId, id), out var nodes)) continue;
foreach (var n in nodes)
{
if (!byRealm.TryGetValue(n.Realm, out var list)) byRealm[n.Realm] = list = new List<string>();
list.Add(n.NodeId);
}
}
var count = 0;
foreach (var (realm, ids) in byRealm)
{
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm));
count += ids.Count;
}
return count;
}
private void ForgetConditionSignals(string driverInstanceId)
{
if (!_conditionSignalTrackers.Remove(driverInstanceId)) return;
Timers.Cancel(SignalTimeoutKey(driverInstanceId));
Timers.Cancel(BackstopKey(driverInstanceId));
_conditionSignals.Hub?.ClearUnsignalled(driverInstanceId);
}
}
@@ -59,7 +59,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
/// fabricates a batch of the same shape straight to the dependency mux, so the host neither receives nor
/// sends a per-value message any more (the per-value record is deleted).
/// </summary>
public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedStash
public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedStash
{
/// <summary>Replace the bounded physical gRPC interest for one driver; empty removes it.</summary>
public sealed record ApplyAcquisitionDemand(string DriverInstanceId, IReadOnlyList<string> FullReferences,
@@ -874,7 +874,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
DataWriteRuntime? dataWriteRuntime = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null,
ActorProjectedValuePublisher? projectedPublisher = null) =>
ActorProjectedValuePublisher? projectedPublisher = null,
ConditionSignalOptions? conditionSignals = null) =>
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
@@ -889,7 +890,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections, projectedPublisher));
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections, projectedPublisher,
conditionSignals));
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
/// <param name="dbFactory">Database context factory for configuration database access.</param>
@@ -1031,8 +1033,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
DataWriteRuntime? dataWriteRuntime = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null,
ActorProjectedValuePublisher? projectedPublisher = null)
ActorProjectedValuePublisher? projectedPublisher = null,
ConditionSignalOptions? conditionSignals = null)
{
_conditionSignals = conditionSignals ?? new ConditionSignalOptions();
_projectedPublisher = projectedPublisher;
_dataWriteRuntime = dataWriteRuntime;
_dataConnections = dataConnections;
@@ -1768,6 +1772,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
Receive<DriverInstanceActor.ConnectivityChanged>(OnDriverConnectivityChanged);
ReceiveConditionSignals();
Receive<CommsRecoveryAudit>(HandleCommsRecoveryAudit);
Receive<RestartDriver>(HandleRestartDriver);
Receive<DriverInstanceActor.ReprovisionRequested>(HandleReprovisionRequested);
@@ -1848,6 +1853,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
Receive<DriverInstanceActor.ConnectivityChanged>(OnDriverConnectivityChanged);
ReceiveConditionSignals();
Receive<CommsRecoveryAudit>(HandleCommsRecoveryAudit);
Receive<RestartDriver>(HandleRestartDriver);
Receive<DriverInstanceActor.ReprovisionRequested>(HandleReprovisionRequested);
@@ -2010,6 +2016,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// The mux fan-out is independent of the OPC UA sink — a node with scripted alarms but no
// publish actor (the mux-only test/dev path) must still see comms loss. Done before the early
// return for exactly that reason.
OnConditionSignalConnectivity(msg.DriverInstanceId, msg.Connected);
if (!msg.Connected)
{
if (!_retiredChildren.Contains(Sender) &&
@@ -2949,6 +2956,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Receive<DriverInstanceActor.AttributeAlarmPublished>(m =>
_log.Debug("DriverHost {Node}: dropping a native alarm transition ({Cond}) from {Id} while Stale",
_localNode, m.Args.ConditionId, m.DriverInstanceId));
// A1: a signal is dropped with the transitions it covers (no address space to mark), as are its timers.
ReceiveConditionSignalsWhileStale();
// A late artifact pipe-back from the apply that was in flight when the host fell Stale: that apply is
// lost (the coordinator's deadline and the boot-time orphan replay recover it). Warning, not Debug —
// an apply outcome is being discarded.
@@ -4671,6 +4680,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(driverInstanceId);
Context.Stop(entry.Actor);
_children.Remove(driverInstanceId);
ForgetConditionSignals(driverInstanceId);
PublishAckPreflight();
EvictRetainedValues(driverInstanceId);
// The instance left the plan (StopChild is only reached via plan.ToStop), so its cached
@@ -232,6 +232,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// to the materialised Part 9 condition. Parallels <see cref="AttributeValueBatchPublished"/>.</summary>
public sealed record AttributeAlarmPublished(string DriverInstanceId, AlarmEventArgs Args);
private sealed record NativeAlarmRaised(AlarmEventArgs Args);
/// <summary>A1 (plan §5.1 F2): published to the parent when the driver raises
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/>. It travels the SAME self-Tell → parent path as
/// <see cref="AttributeAlarmPublished"/>, so it reaches <see cref="DriverHostActor"/> after every alarm event the
/// driver raised before it.</summary>
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args);
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args);
/// <summary>Self-sent on Connected entry / when alarm refs are (re)pushed, to establish the native-alarm
/// subscription that un-gates an <see cref="IAlarmSource"/> driver's feed. Handled async so the
/// <see cref="IAlarmSource.SubscribeAlarmsAsync"/> call is bounded + off the synchronous handlers.</summary>
@@ -496,6 +502,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private sealed record ResumeDeferredLegacy;
private const int SourceBindingBatchSize = 128;
private EventHandler<AlarmEventArgs>? _alarmEventHandler;
// A1 (plan §5.1 G5): attached and detached WITH the alarm handler, so the signal obeys exactly the gate
// OnAlarmEvent obeys.
private EventHandler<AlarmInitialStateEventArgs>? _alarmInitialStateHandler;
private EventHandler<RediscoveryEventArgs>? _rediscoveryHandler;
private EventHandler<HostStatusChangedEventArgs>? _hostStatusHandler;
private EventHandler<DriverConnectionLossEventArgs>? _connectionLossHandler;
@@ -873,6 +882,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// own thread); drop it — the feed re-delivers active alarms once Connected. Trace only.
Receive<NativeAlarmRaised>(_ =>
_log.Debug("DriverInstance {Id}: native alarm arrived during connect — dropped (feed re-delivers)", _driverInstanceId));
// Its initial-state signal is dropped with it: a signal must never outlive the alarm events it covers.
Receive<NativeAlarmInitialState>(_ =>
_log.Debug("DriverInstance {Id}: initial alarm-state signal arrived during connect — dropped", _driverInstanceId));
// A SubscribeAlarms self-tell (from Connected) can be overtaken by an already-queued disconnect into
// this state; swallow it so it doesn't dead-letter — the next Connected entry re-subscribes.
Receive<SubscribeAlarms>(_ => { });
@@ -987,6 +999,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// Native alarm transition marshaled onto the actor thread from the driver's OnAlarmEvent;
// project it to the parent the same way DataChangeForward projects AttributeValueBatchPublished.
Receive<NativeAlarmRaised>(m => Context.Parent.Tell(new AttributeAlarmPublished(_driverInstanceId, m.Args)));
// A1 F2: the same mailbox and the same forward, so the signal follows every alarm event raised before it.
Receive<NativeAlarmInitialState>(m => Context.Parent.Tell(new AlarmInitialStatePublished(_driverInstanceId, m.Args)));
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive<SubscriptionEstablished>(msg =>
@@ -1235,6 +1249,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// own thread); drop it — the feed re-delivers active alarms once Connected. Trace only.
Receive<NativeAlarmRaised>(_ =>
_log.Debug("DriverInstance {Id}: native alarm arrived during reconnect — dropped (feed re-delivers)", _driverInstanceId));
Receive<NativeAlarmInitialState>(_ =>
_log.Debug("DriverInstance {Id}: initial alarm-state signal arrived during reconnect — dropped", _driverInstanceId));
// A SubscribeAlarms self-tell (from Connected) can be overtaken by an already-queued disconnect into
// this state; swallow it so it doesn't dead-letter — the next Connected entry re-subscribes.
Receive<SubscribeAlarms>(_ => { });
@@ -2539,6 +2555,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
var self = Self;
_alarmEventHandler = (_, e) => self.Tell(new NativeAlarmRaised(e));
src.OnAlarmEvent += _alarmEventHandler;
if (_driver is IAlarmInitialStateSignal signal)
{
_alarmInitialStateHandler = (_, e) => self.Tell(new NativeAlarmInitialState(e));
signal.InitialAlarmStateDelivered += _alarmInitialStateHandler;
}
}
/// <summary>Subscribe the driver's <see cref="IRediscoverable.OnRediscoveryNeeded"/> (if it is one),
@@ -2716,6 +2737,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
if (_driver is IAlarmSource src && _alarmEventHandler is not null)
src.OnAlarmEvent -= _alarmEventHandler;
_alarmEventHandler = null;
if (_driver is IAlarmInitialStateSignal signal && _alarmInitialStateHandler is not null)
signal.InitialAlarmStateDelivered -= _alarmInitialStateHandler;
_alarmInitialStateHandler = null;
// Drop our handle so the next Connected entry re-subscribes; the desired alarm refs persist across
// reconnects. NOTE: this does NOT tear down the driver-side subscription. For a session-bound
// IAlarmSource the old subscription dies with the session (no accumulation). For a session-less feed
@@ -681,7 +681,12 @@ public static class ServiceCollectionExtensions
acquisitionCapacity: resolver.GetService<SubscriptionAcquisitionCapacity>(),
writeClock: resolver.GetService<TimeProvider>(),
dataConnections: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataConnectionDeploymentRuntime>(),
projectedPublisher: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ActorProjectedValuePublisher>()),
projectedPublisher: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ActorProjectedValuePublisher>(),
// A1 (grpc-data §5.1 F5): per-DriverType signal timeout + the OpcUaClient backstop; the F5 diagnostic is
// raised on the condition-state hub. A malformed value fails host start.
conditionSignals: ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionSignalOptions.FromConfiguration(
resolver.GetService<IConfiguration>(),
resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub>())),
DriverHostActorName);
registry.Register<DriverHostActorKey>(driverHost);