feat(grpc-data): A1 — FOCAS signals per device after each successful alarm read

This commit is contained in:
Joseph Doherty
2026-11-24 10:16:39 -05:00
parent 4e984b160e
commit dbbc35e83d
3 changed files with 183 additions and 1 deletions
@@ -311,8 +311,10 @@ internal sealed class FocasAlarmProjection : IAsyncDisposable
if (_failingDevices.Remove(deviceHostAddress, out _))
_logger.LogInformation("FOCAS alarm read for {Host} recovered", deviceHostAddress);
List<string>? established = null;
foreach (var tag in deviceTags.Where(t => sub.References.Contains(t.RawPath)))
{
(established ??= new List<string>()).Add(tag.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 _))
@@ -325,6 +327,26 @@ internal sealed class FocasAlarmProjection : IAsyncDisposable
if (evt is null) continue;
Deliver(handlers, evt, tag.RawPath);
}
// grpc-data A1 (§5.1, G1): this device's read succeeded and its transitions were emitted — its conditions'
// state is established. Per device, under the same lock and gate as the events (G5), after them (F2).
if (established is not null) SignalEstablished(established);
}
}
/// <summary>Raises the driver's <c>InitialAlarmStateDelivered</c> for <paramref name="conditionIds"/>. Caller holds the lock.</summary>
/// <param name="conditionIds">The RawPaths the completed read established.</param>
private void SignalEstablished(IReadOnlyList<string> conditionIds)
{
if (_driver.InitialStateHandlers is not { } signal) return;
var args = new AlarmInitialStateEventArgs(conditionIds);
foreach (var registration in signal.GetInvocationList())
{
try { ((EventHandler<AlarmInitialStateEventArgs>)registration).Invoke(_driver, args); }
catch (Exception ex)
{
_logger.LogWarning(ex, "FOCAS driver caught a fault from an initial-alarm-state subscriber; delivery continues.");
}
}
}
@@ -20,7 +20,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS;
/// fail fast.
/// </remarks>
public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, IBatchSubscribable,
IHostConnectivityProbe, IPerCallHostResolver, IAlarmSource, ISkippedTagReporter, IDisposable, IAsyncDisposable
IHostConnectivityProbe, IPerCallHostResolver, IAlarmSource, IAlarmInitialStateSignal, ISkippedTagReporter, IDisposable, IAsyncDisposable
{
/// <summary>Authored tags this driver could not build into its poll table. FOCAS has three
/// skip paths — an unmappable TagConfig, an unparseable address, and a capability-matrix rejection — and the second of them once went unreported while the driver read Healthy.</summary>
@@ -141,6 +141,11 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// <summary>Occurs when an alarm event is raised.</summary>
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
/// <inheritdoc />
/// <remarks>grpc-data A1 (§5.1 FOCAS row): raised per device at the end of each SUCCESSFUL alarm read's tick, after
/// that device's transitions, covering its subscribed <c>ALARM:</c> conditions. A failed read raises nothing.</remarks>
public event EventHandler<AlarmInitialStateEventArgs>? InitialAlarmStateDelivered;
/// <summary>Initializes a new instance of the <see cref="FocasDriver"/> class with the provided options and dependencies.</summary>
/// <param name="options">The driver configuration options.</param>
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
@@ -1993,6 +1998,9 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// <summary>Gets the attached alarm handlers, or <see langword="null"/> when nobody is listening.</summary>
internal EventHandler<AlarmEventArgs>? AlarmHandlers => OnAlarmEvent;
/// <summary>Gets the attached initial-state signal handlers (grpc-data A1), or <see langword="null"/>.</summary>
internal EventHandler<AlarmInitialStateEventArgs>? InitialStateHandlers => InitialAlarmStateDelivered;
/// <summary>Gets the authored <c>ALARM:</c> tags (RawPath → tag). Test seam + projection input.</summary>
internal IReadOnlyDictionary<string, FocasAlarmTag> AlarmTags => Volatile.Read(ref _alarmTags);
@@ -0,0 +1,152 @@
using System.Text.Json;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests;
/// <summary>
/// grpc-data A1 (§5.1 FOCAS row): the real poll loop raises
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/> per device after that device's successful read
/// and its transitions (ii); a device whose read fails signals nothing and holds back no other device (G1, viii);
/// nothing while no alarm handler is attached (G5).
/// </summary>
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "A1")]
public sealed class FocasInitialAlarmStateSignalTests
{
private const string Host = "focas://10.0.0.5:8193";
private const string Host2 = "focas://10.0.0.6:8193";
private const string ServoM1 = "Plant/Cnc/m1/servo";
private const string AnyM1 = "Plant/Cnc/m1/any";
private const string ServoM2 = "Plant/Cnc/m2/servo";
private static CancellationToken Ct => TestContext.Current.CancellationToken;
/// <summary>(ii) the first read's Raise precedes the signal, which covers the device's subscribed conditions.</summary>
[Fact]
public async Task Signal_follows_the_first_reads_transitions_and_covers_the_device()
{
var (drv, factory) = NewDriver([new FocasDeviceOptions(Host, DeviceName: "m1")],
Tag(ServoM1, "ALARM:Servo", "m1"), Tag(AnyM1, "ALARM:Overheat", "m1"));
factory.Customise = () =>
{
var c = new FakeFocasClient();
c.SetAlarms(new FocasActiveAlarm(401, FocasAlarmType.Servo, 1, "SERVO V-READY OFF"));
return c;
};
var trace = Record(drv);
await drv.InitializeAsync("{}", Ct);
await drv.SubscribeAlarmsAsync([ServoM1, AnyM1], Ct);
await WaitFor(() => Snapshot(trace).Count(t => t.StartsWith("signal", StringComparison.Ordinal)) >= 1);
await drv.ShutdownAsync(Ct);
var lines = Snapshot(trace);
var firstSignal = Array.FindIndex(lines, t => t.StartsWith("signal", StringComparison.Ordinal));
lines[..firstSignal].ShouldBe(["event:" + ServoM1 + ":Raise"]);
lines[firstSignal].ShouldBe($"signal:{ServoM1},{AnyM1}");
}
/// <summary>
/// (viii) G1: two devices, the second unreachable. The reachable one signals on every successful read; no
/// signal ever names the unreachable device's condition.
/// </summary>
[Fact]
public async Task Unreachable_device_stays_unsignalled_without_holding_back_the_reachable_one()
{
var (drv, factory) = NewDriver(
[new FocasDeviceOptions(Host, DeviceName: "m1"), new FocasDeviceOptions(Host2, DeviceName: "m2")],
Tag(ServoM1, "ALARM:Servo", "m1"), Tag(ServoM2, "ALARM:Servo", "m2"));
var created = 0;
// Devices are polled in subscription order, so the first client is m1's (reachable), the second m2's.
factory.Customise = () => Interlocked.Increment(ref created) == 1
? new FakeFocasClient()
: new FakeFocasClient { ThrowOnReadAlarms = true };
var trace = Record(drv);
await drv.InitializeAsync("{}", Ct);
await drv.SubscribeAlarmsAsync([ServoM1, ServoM2], Ct);
await WaitFor(() => Snapshot(trace).Count(t => t.StartsWith("signal", StringComparison.Ordinal)) >= 3);
await drv.ShutdownAsync(Ct);
var signals = Snapshot(trace).Where(t => t.StartsWith("signal", StringComparison.Ordinal)).ToList();
signals.ShouldAllBe(s => s == "signal:" + ServoM1, "only the reachable device's condition is established");
}
/// <summary>(xi) G5: a successful tick with no alarm handler attached raises no signal; with one it does.</summary>
[Fact]
public async Task No_signal_while_no_alarm_handler_is_attached()
{
var (drv, factory) = NewDriver([new FocasDeviceOptions(Host, DeviceName: "m1")], Tag(ServoM1, "ALARM:Servo", "m1"));
factory.Customise = () => new FakeFocasClient { ThrowOnReadAlarms = true };
var signals = new List<AlarmInitialStateEventArgs>();
drv.InitialAlarmStateDelivered += (_, e) => { lock (signals) signals.Add(e); };
await drv.InitializeAsync("{}", Ct);
await drv.SubscribeAlarmsAsync([ServoM1], Ct);
await drv.AlarmProjection.PauseAsync();
drv.AlarmProjection.Tick(drv.AlarmProjection.Current!, Host, [], drv.AlarmTags);
signals.ShouldBeEmpty("the alarm feed is suppressed (no OnAlarmEvent handler)");
drv.OnAlarmEvent += (_, _) => { };
drv.AlarmProjection.Tick(drv.AlarmProjection.Current!, Host, [], drv.AlarmTags);
signals.ShouldHaveSingleItem().ConditionIds.ShouldBe([ServoM1]);
await drv.ShutdownAsync(Ct);
}
private static List<string> Record(FocasDriver drv)
{
var trace = new List<string>();
drv.OnAlarmEvent += (_, e) =>
{
if (e.IsQualityOnly) return;
lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}");
};
drv.InitialAlarmStateDelivered += (_, e) =>
{
lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds));
};
return trace;
}
private static string[] Snapshot(List<string> trace)
{
lock (trace) return [.. trace];
}
private static (FocasDriver Driver, FakeFocasClientFactory Factory) NewDriver(
IReadOnlyList<FocasDeviceOptions> devices, params RawTagEntry[] tags)
{
var factory = new FakeFocasClientFactory();
var drv = new FocasDriver(new FocasDriverOptions
{
Devices = [.. devices],
RawTags = [.. tags],
Probe = new FocasProbeOptions { Enabled = false },
AlarmProjection = new FocasAlarmProjectionOptions { PollInterval = TimeSpan.FromMilliseconds(20) },
}, "drv-1", factory);
return (drv, factory);
}
private static RawTagEntry Tag(string rawPath, string address, string device) =>
new(rawPath, JsonSerializer.Serialize(new Dictionary<string, object>
{
["address"] = address,
["dataType"] = "Int32",
["alarm"] = new Dictionary<string, object> { ["alarmType"] = "AlarmCondition" },
}), WriteIdempotent: false, DeviceName: device);
private static async Task WaitFor(Func<bool> pred, int timeoutMs = 5000)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < deadline)
{
if (pred()) return;
await Task.Delay(10, Ct);
}
pred().ShouldBeTrue("condition not reached in time");
}
}