feat(heidenhain): Part 9 condition class from alarm class/group, ALARM: selectors in the browse picker, unclaimed alarms counted + logged (#839)

- Core: optional AlarmEventArgs.ConditionClass (AlarmConditionClass Base/Process/Maintenance/System/Safety)
  carried by NativeAlarmProjector on AlarmConditionSnapshot and written to ConditionClassId/Name by
  OtOpcUaNodeManager (kept across class-less events, carried across a #641 rebuild).
- Heidenhain: HeidenhainAlarmClasses — HEIDENHAIN DNC-interface class/group names (corroborated by the
  captured iTNC 530 record); class 5 => Safety, group 1/2 => Process, 4/5 => System, else Base.
- DiscoverAsync offers AlarmConditions/ selector leaves (IsAlarm Boolean); browse-commit seeds the alarm object.
- Alarms no selector claims: otopcua.driver.alarms.unmatched counter, /hosts diagnostics, rate-limited Warning.

Refs #839
This commit is contained in:
Joseph Doherty
2026-11-11 03:41:14 -05:00
parent 481985e20b
commit ddc1f29e3a
17 changed files with 593 additions and 39 deletions
@@ -150,6 +150,131 @@ public sealed class HeidenhainAlarmTests
e.OpcUaSeverity.ShouldBeNull();
}
// ---- Part 9 condition class (lmxopcua#839) ----
[Theory]
[InlineData(5, 3, AlarmConditionClass.Safety)] // EMERGENCY STOP, whatever the group
[InlineData(5, 0, AlarmConditionClass.Safety)]
[InlineData(8, 1, AlarmConditionClass.Process)] // OPERATING
[InlineData(1, 2, AlarmConditionClass.Process)] // PROGRAMMING
[InlineData(7, 4, AlarmConditionClass.System)] // GENERAL — the captured iTNC 530 "Run test of cutout channels"
[InlineData(8, 5, AlarmConditionClass.System)] // REMOTE
[InlineData(8, 3, AlarmConditionClass.Base)] // PLC: machine-builder text, no evidence either way
[InlineData(8, 6, AlarmConditionClass.Base)] // PYTHON
[InlineData(8, 0, AlarmConditionClass.Base)]
[InlineData(99, 99, AlarmConditionClass.Base)] // unknown codes never guess
public void Condition_class_maps_only_where_the_codes_say_where_the_alarm_comes_from(int cls, int group, AlarmConditionClass expected) =>
HeidenhainAlarmClasses.ConditionClassOf(cls, group).ShouldBe(expected);
[Fact]
public void Raise_and_retrigger_carry_the_displayed_alarms_class_and_clear_carries_none()
{
var tag = Tag("*");
var all = new[] { tag.Selector };
var now = DateTime.UtcNow;
var info = new Lsv2Alarm(7, 4, -1, "Run test of cutout channels");
var estop = new Lsv2Alarm(5, 3, 10, "Emergency stop");
var (e1, t1) = HeidenhainAlarmRules.Transition(null, HeidenhainAlarmRules.Evaluate(tag.Selector, [info], all), tag, H, now);
e1!.ConditionClass.ShouldBe(AlarmConditionClass.System);
var (e2, t2) = HeidenhainAlarmRules.Transition(t1, HeidenhainAlarmRules.Evaluate(tag.Selector, [info, estop], all), tag, H, now);
e2!.Kind.ShouldBe(AlarmTransitionKind.Retrigger);
e2.ConditionClass.ShouldBe(AlarmConditionClass.Safety); // the class-5 alarm is now the displayed one
var (e3, _) = HeidenhainAlarmRules.Transition(t2, [], tag, H, now);
e3!.Kind.ShouldBe(AlarmTransitionKind.Clear);
e3.ConditionClass.ShouldBeNull(); // the node keeps the class of the alarm it last showed
e1.Message.ShouldBe("-1 Run test of cutout channels (class 7, group 4)"); // the message is unchanged by #839
}
// ---- unclaimed alarms are counted and logged (lmxopcua#839) ----
private sealed class ListLogger : Microsoft.Extensions.Logging.ILogger
{
public ConcurrentQueue<(Microsoft.Extensions.Logging.LogLevel Level, string Text)> Entries { get; } = new();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId,
TState state, Exception? exception, Func<TState, Exception?, string> formatter) =>
Entries.Enqueue((logLevel, formatter(state, exception)));
}
private static HeidenhainAlarmProjection Projection(ListLogger log, params HeidenhainAlarmTag[] tags)
{
var p = new HeidenhainAlarmProjection(new object(), () => null, log, "hh-1")
{
Tags = tags.ToDictionary(t => t.RawPath, StringComparer.Ordinal),
};
p.Subscribe(tags.Select(t => t.RawPath).ToList());
return p;
}
private static HeidenhainAlarmTag TagOn(string host, string selector, string name) =>
new($"Plant/H/dev1/{name}", host, Parse(selector), null);
[Fact]
public void Alarms_no_selector_claims_are_counted_once_per_occurrence_and_logged_rate_limited()
{
var log = new ListLogger();
var p = Projection(log, TagOn("h:1", "CLASS=7", "Info"));
var claimed = new Lsv2Alarm(7, 4, -1, "Run test of cutout channels");
var lost = new Lsv2Alarm(3, 1, 100, "Coolant low");
var lost2 = new Lsv2Alarm(8, 2, 200, "Program error");
static int Warnings(ListLogger l) => l.Entries.Count(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Warning);
p.OnWalk("h:1", HeidenhainStatus.Good, [claimed, lost]);
p.UnmatchedSnapshot()["h:1"].ShouldBe((1, 1L));
Warnings(log).ShouldBe(1);
log.Entries.Last().Text.ShouldContain("100 Coolant low (class 3, group 1)");
// A standing alarm is not re-counted, and the log is rate-limited.
p.OnWalk("h:1", HeidenhainStatus.Good, [claimed, lost]);
p.OnWalk("h:1", HeidenhainStatus.Good, [lost, lost2]);
p.UnmatchedSnapshot()["h:1"].ShouldBe((2, 2L));
Warnings(log).ShouldBe(1);
// It leaves and comes back — a new occurrence. The next permitted line reports what was suppressed.
p.OnWalk("h:1", HeidenhainStatus.Good, [lost2]);
p.UnmatchedLogInterval = TimeSpan.Zero;
p.OnWalk("h:1", HeidenhainStatus.Good, [lost, lost2]);
p.UnmatchedSnapshot()["h:1"].ShouldBe((2, 3L));
Warnings(log).ShouldBe(2);
log.Entries.Last().Text.ShouldContain("1 more since the previous report");
// A failed walk is not "no alarms": it changes nothing.
p.OnWalk("h:1", HeidenhainStatus.BadNoCommunication, null);
p.UnmatchedSnapshot()["h:1"].ShouldBe((2, 3L));
}
[Theory]
[InlineData("*")]
[InlineData("OTHER")]
public void A_catch_all_selector_claims_every_alarm(string catchAll)
{
var log = new ListLogger();
var p = Projection(log, TagOn("h:1", "CLASS=7", "Info"), TagOn("h:1", catchAll, "All"));
p.OnWalk("h:1", HeidenhainStatus.Good, [new Lsv2Alarm(3, 1, 100, "Coolant low")]);
p.UnmatchedSnapshot()["h:1"].ShouldBe((0, 0L));
log.Entries.ShouldNotContain(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Warning);
}
[Fact]
public async Task Unclaimed_alarms_reach_the_hosts_diagnostics()
{
var control = new SimulatedControl();
var list = new AlarmList();
list.Install(control);
list.Set(Golden(), Record(3, 1, 100, "Coolant low"));
await using var sim = Lsv2Simulator.WithControl(control);
var cls7 = AlarmTag("CLASS=7", "Class7");
await using var d = Create(Options(sim.Port, cls7));
await d.InitializeAsync("{}", Ct);
await d.SubscribeAlarmsAsync([cls7.RawPath], Ct);
var host = $"127.0.0.1:{sim.Port}";
await WaitUntil(() => d.GetDiagnostics().TryGetValue($"{host}.alarms.unmatched", out var v) && v == "1");
d.GetDiagnostics()[$"{host}.alarms.unmatchedTotal"].ShouldBe("1");
}
// ---- end to end against the simulator ----
/// <summary>A control whose active-alarm list can be changed between walks (27 = first, 28 = next, 57 = end).</summary>
@@ -80,7 +80,21 @@ public sealed class HeidenhainDriverTests
await d.DiscoverAsync(builder, Ct);
await Task.Delay(200, Ct);
sim.Connections.ShouldBe(0);
builder.Variables.Count.ShouldBe(HeidenhainCatalog.Entries.Count);
// The fixed catalog plus the ALARM: selectors (lmxopcua#839) — every one an IsAlarm Boolean leaf whose address
// the driver's own parser takes as a condition selector.
builder.Variables.Count.ShouldBe(HeidenhainCatalog.Entries.Count + HeidenhainAlarmClasses.BrowseSelectors.Count);
var alarmLeaves = builder.Variables.Where(v => v.IsAlarm).ToList();
alarmLeaves.Select(v => v.FullName).ShouldBe(HeidenhainAlarmClasses.BrowseSelectors.Select(x => x.Address));
alarmLeaves.ShouldAllBe(v => v.DriverDataType == DriverDataType.Boolean && !v.IsArray);
foreach (var leaf in alarmLeaves)
{
HeidenhainAddress.TryParse(leaf.FullName, out var a, out var error).ShouldBeTrue(error);
a!.Kind.ShouldBe(HeidenhainAddressKind.Alarm);
}
alarmLeaves.Select(v => v.FullName).ShouldContain("ALARM:*");
alarmLeaves.Select(v => v.FullName).ShouldContain("ALARM:OTHER");
alarmLeaves.Select(v => v.FullName).ShouldContain("ALARM:CLASS=5");
builder.Variables.ShouldContain(v => v.FullName == "Axes/Positions" && v.IsArray && v.DriverDataType == DriverDataType.Float64);
builder.Variables.ShouldAllBe(v => v.SecurityClass == SecurityClassification.ViewOnly);
d.GetHealth().State.ShouldBe(DriverState.Healthy);
@@ -122,4 +122,27 @@ public sealed class HeidenhainAuthoringTests
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, json).ShouldBeNull();
HeidenhainTagConfigModel.FromJson(json).Address.ShouldBe(address);
}
/// <summary>
/// lmxopcua#839: every <c>ALARM:</c> selector the browse picker offers commits as a complete condition tag — the
/// paired <c>alarm</c> object seeded, Boolean, accepted by the driver's own factory and the editor's validator —
/// so a browse-commit never lands a tag the deploy gate would refuse.
/// </summary>
[Fact]
public void Browse_committed_alarm_selectors_are_complete_conditions_the_driver_accepts()
{
HeidenhainAlarmClasses.BrowseSelectors.Count.ShouldBeGreaterThan(2);
foreach (var (_, name, address) in HeidenhainAlarmClasses.BrowseSelectors)
{
var row = RawBrowseCommitMapper.MapLeaf(
DriverTypeNames.Heidenhain, address, name, nameof(DriverDataType.Boolean), "String",
groupPrefix: null, folderPath: null, createGroups: false);
row.Tag.DataType.ShouldBe("Boolean");
var json = row.Tag.TagConfig!;
JsonNode.Parse(json)!["alarm"].ShouldNotBeNull(address);
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", json, out var def, out var error).ShouldBeTrue(error);
def!.IsAlarmCondition.ShouldBeTrue();
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, json).ShouldBeNull();
}
}
}
@@ -123,6 +123,37 @@ public sealed class NodeManagerNativeAlarmRebuildCarryOverTests : IDisposable
await host.DisposeAsync();
}
/// <summary>
/// lmxopcua#839 — a classifying native source's Part 9 ConditionClass lands on the node, a later snapshot
/// without one (a quality-only annotation, a non-classifying path) keeps it, and a rebuild carries it.
/// </summary>
[Trait("Category", "Unit")]
[Fact]
public async Task A_driver_assigned_condition_class_is_applied_kept_and_carried_across_a_rebuild()
{
var (host, nm) = await BootAsync();
Materialise(nm, native: true);
Condition(nm).ConditionClassId!.Value.ShouldBe(ObjectTypeIds.BaseConditionClassType);
nm.WriteAlarmCondition(Alarm, Fault(acked: false) with { ConditionClass = ZB.MOM.WW.OtOpcUa.Core.Abstractions.AlarmConditionClass.Safety },
DateTime.UtcNow, AddressSpaceRealm.Raw);
Condition(nm).ConditionClassId!.Value.ShouldBe(ObjectTypeIds.SafetyConditionClassType);
Condition(nm).ConditionClassName!.Value.Text.ShouldBe("SafetyConditionClass");
nm.WriteAlarmCondition(Alarm, Fault(acked: false) with { StatusCode = OpcUaStatus.Bad }, DateTime.UtcNow, AddressSpaceRealm.Raw);
Condition(nm).ConditionClassId!.Value.ShouldBe(ObjectTypeIds.SafetyConditionClassType);
// Even a NORMAL condition keeps its class across a rebuild — the class is not state.
nm.WriteAlarmCondition(Alarm, Fault(acked: true) with { Active = false }, DateTime.UtcNow, AddressSpaceRealm.Raw);
nm.RebuildAddressSpace();
Materialise(nm, native: true);
nm.CompleteAddressSpaceApply();
Condition(nm).ConditionClassId!.Value.ShouldBe(ObjectTypeIds.SafetyConditionClassType);
Condition(nm).ConditionClassName!.Value.Text.ShouldBe("SafetyConditionClass");
await host.DisposeAsync();
}
/// <summary>Falsification control: a condition in the no-event position comes back exactly as a fresh
/// materialise builds it, and reports nothing.</summary>
[Trait("Category", "Unit")]
@@ -24,6 +24,26 @@ public class NativeAlarmProjectorTests
snap.Message.ShouldBe("boom");
}
/// <summary>lmxopcua#839 — a classifying source's ConditionClass rides the snapshot; an event without one (a
/// quality-only annotation, a Clear) keeps the class the condition last carried, and the default is null
/// (= leave the node's class alone).</summary>
[Fact]
public void Condition_class_is_carried_and_kept_until_restated()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise)).ConditionClass.ShouldBeNull();
sut.Project("n1", Evt(AlarmTransitionKind.Retrigger) with { ConditionClass = AlarmConditionClass.System })
.ConditionClass.ShouldBe(AlarmConditionClass.System);
sut.Project("n1", Evt(AlarmTransitionKind.Unspecified) with { QualityStatusCode = 0x80310000u })
.ConditionClass.ShouldBe(AlarmConditionClass.System);
sut.Project("n1", Evt(AlarmTransitionKind.Clear)).ConditionClass.ShouldBe(AlarmConditionClass.System);
sut.MarkAcknowledged("n1");
sut.Project("n1", Evt(AlarmTransitionKind.Raise) with { ConditionClass = AlarmConditionClass.Safety });
sut.MarkAcknowledged("n1");
sut.TryRevertAcknowledge("n1", out var reverted).ShouldBeTrue();
reverted!.ConditionClass.ShouldBe(AlarmConditionClass.Safety);
}
/// <summary>Gitea #641 — <c>RetainOnly</c> keeps a still-deployed condition's prior state and forgets a removed
/// one's (which then starts from the default inactive + acked).</summary>
[Fact]