diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasAlarmProjection.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasAlarmProjection.cs index aa20cbeac..bc776fb52 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasAlarmProjection.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasAlarmProjection.cs @@ -311,8 +311,10 @@ internal sealed class FocasAlarmProjection : IAsyncDisposable if (_failingDevices.Remove(deviceHostAddress, out _)) _logger.LogInformation("FOCAS alarm read for {Host} recovered", deviceHostAddress); + List? established = null; foreach (var tag in deviceTags.Where(t => sub.References.Contains(t.RawPath))) { + (established ??= new List()).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); + } + } + + /// Raises the driver's InitialAlarmStateDelivered for . Caller holds the lock. + /// The RawPaths the completed read established. + private void SignalEstablished(IReadOnlyList conditionIds) + { + if (_driver.InitialStateHandlers is not { } signal) return; + var args = new AlarmInitialStateEventArgs(conditionIds); + foreach (var registration in signal.GetInvocationList()) + { + try { ((EventHandler)registration).Invoke(_driver, args); } + catch (Exception ex) + { + _logger.LogWarning(ex, "FOCAS driver caught a fault from an initial-alarm-state subscriber; delivery continues."); + } } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs index bebe023ae..8b31a863f 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs @@ -20,7 +20,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS; /// fail fast. /// public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, IBatchSubscribable, - IHostConnectivityProbe, IPerCallHostResolver, IAlarmSource, ISkippedTagReporter, IDisposable, IAsyncDisposable + IHostConnectivityProbe, IPerCallHostResolver, IAlarmSource, IAlarmInitialStateSignal, ISkippedTagReporter, IDisposable, IAsyncDisposable { /// 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. @@ -141,6 +141,11 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, /// Occurs when an alarm event is raised. public event EventHandler? OnAlarmEvent; + /// + /// 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 ALARM: conditions. A failed read raises nothing. + public event EventHandler? InitialAlarmStateDelivered; + /// Initializes a new instance of the class with the provided options and dependencies. /// The driver configuration options. /// The unique identifier for this driver instance. @@ -1993,6 +1998,9 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery, /// Gets the attached alarm handlers, or when nobody is listening. internal EventHandler? AlarmHandlers => OnAlarmEvent; + /// Gets the attached initial-state signal handlers (grpc-data A1), or . + internal EventHandler? InitialStateHandlers => InitialAlarmStateDelivered; + /// Gets the authored ALARM: tags (RawPath → tag). Test seam + projection input. internal IReadOnlyDictionary AlarmTags => Volatile.Read(ref _alarmTags); diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasInitialAlarmStateSignalTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasInitialAlarmStateSignalTests.cs new file mode 100644 index 000000000..06ae6f672 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasInitialAlarmStateSignalTests.cs @@ -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; + +/// +/// grpc-data A1 (§5.1 FOCAS row): the real poll loop raises +/// 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). +/// +[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; + + /// (ii) the first read's Raise precedes the signal, which covers the device's subscribed conditions. + [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}"); + } + + /// + /// (viii) G1: two devices, the second unreachable. The reachable one signals on every successful read; no + /// signal ever names the unreachable device's condition. + /// + [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"); + } + + /// (xi) G5: a successful tick with no alarm handler attached raises no signal; with one it does. + [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(); + 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 Record(FocasDriver drv) + { + var trace = new List(); + 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 trace) + { + lock (trace) return [.. trace]; + } + + private static (FocasDriver Driver, FakeFocasClientFactory Factory) NewDriver( + IReadOnlyList 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 + { + ["address"] = address, + ["dataType"] = "Int32", + ["alarm"] = new Dictionary { ["alarmType"] = "AlarmCondition" }, + }), WriteIdempotent: false, DeviceName: device); + + private static async Task WaitFor(Func 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"); + } +}