feat(heidenhain): controller alarms as native Part 9 conditions; rediscovery on identity change (#831)

- ALARM: selectors (HeidenhainAlarmSelector, Contracts): ALARM:*, ALARM:OTHER,
  ALARM:CLASS=<r>[/GROUP=<r>][/NUMBER=<r>] (<r> = n | lo..hi; negative numbers allowed).
  An ALARM: address and the cross-driver alarm object only work together — the factory
  refuses either alone, so editor, save path, CSV and deploy inspector agree. Data type
  fixed Boolean; never a value (ReadAsync BadNotSupported), never in a data subscription.
- HeidenhainDriver implements IAlarmSource: one condition per ALARM: tag at its RawPath,
  driven by the SAME allowlisted R_RI 27/28 walk on the control's single loop, on the new
  Polling.AlarmMs cadence (default 2000 ms, only for controls carrying an ALARM: tag).
  FOCAS #647 transition rules (Raise / Retrigger / Clear), identity = class+group+number+text,
  deterministic display order, told-record on the driver instance, recorded only while a
  handler listens. A failed walk (refusal, overflow, comms loss) is quality-only, never a clear.
- Acknowledge is LOCAL-ONLY: AcknowledgeAsync is a no-op success (FOCAS/MTConnect posture);
  Lsv2ReadOnlyPolicy is unchanged — no ack or write request exists.
- Opt-in per tag, no driver flag (FOCAS #647 / MTConnect #626 precedent); Alarms/* arrays unchanged.
- IRediscoverable: a reconnect whose R_VR identity (model / NC / PLC / options) differs from
  the previous session raises OnRediscoveryNeeded once (advisory re-browse chip). No extra traffic.
- AdminUI: Heidenhain joins NativeAlarmModel's alarm drivers; the typed editor fixes ALARM:
  tags at Boolean and seeds/drops the alarm object with the selector; driver form gains
  "Alarm conditions (ms)". (HeidenhainDriverFormModel also carries the #830 credential-notice change.)

Tests: HeidenhainAlarmTests (grammar, pairing, rules, simulator e2e with the captured iTNC 530
alarm record, local-only ack = zero bytes sent, quality-only outage/refusal, rediscovery),
Runtime.Tests HeidenhainNativeAlarmEndToEndTests (real DriverHostActor condition), a
DraftValidator case, and the NativeAlarmDriverSetGuard now scans the Heidenhain driver.
This commit is contained in:
Joseph Doherty
2026-11-11 01:37:41 -05:00
parent 5bbe1e3c7a
commit 2b0eed1a8f
22 changed files with 1379 additions and 31 deletions
@@ -92,6 +92,21 @@ public sealed class DraftValidatorHeidenhainTests
=> Validate(Driver("""{"Polling":{"MaxAlarms":999}}"""), Dev(), T(TagAccessLevel.Read))
.ShouldContain(e => e.Code == HeidenhainDeployChecks.ConfigCode);
[Fact]
public void An_alarm_condition_tag_deploys_as_Boolean_and_any_other_data_type_is_refused()
{
// lmxopcua#831: an ALARM: selector + the alarm object is a Part 9 condition; its Tag.DataType is fixed.
var tag = T(TagAccessLevel.Read);
tag.TagConfig = """{"address":"ALARM:CLASS=7","dataType":"Boolean","alarm":{"alarmType":"AlarmCondition","severity":800}}""";
tag.DataType = "Boolean";
Validate(Driver(), Dev(), tag).ShouldNotContain(e => e.Code.StartsWith("Heidenhain", StringComparison.Ordinal));
tag.DataType = "Int32";
Validate(Driver(), Dev(), tag).ShouldContain(e => e.Code == HeidenhainDeployChecks.DataTypeCode && e.Message.Contains("Boolean"));
tag.DataType = "Boolean";
tag.AccessLevel = TagAccessLevel.ReadWrite;
Validate(Driver(), Dev(), tag).ShouldContain(e => e.Code == HeidenhainDeployChecks.WritableCode);
}
[Fact]
public void Other_drivers_are_unaffected()
=> Validate(Driver("""{"Access":{"InspectPassword":"x"}}""", type: "Modbus"), Dev(), T(TagAccessLevel.ReadWrite))
@@ -0,0 +1,384 @@
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Text;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Lsv2;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests.Simulator;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests;
/// <summary>
/// lmxopcua#831: controller alarms as native Part 9 conditions (<c>ALARM:</c> selectors + the <c>alarm</c> object),
/// local-only acknowledgement (nothing sent to the control), quality-only annotation of a failed walk, and the
/// identity-change rediscovery signal — against the in-process LSV2 simulator and the captured iTNC 530 alarm reply.
/// </summary>
[Trait("Category", "Unit")]
public sealed class HeidenhainAlarmTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private const string Alarm = """, "alarm": {"alarmType": "AlarmCondition", "severity": 800}""";
private static RawTagEntry AlarmTag(string selector, string name, bool withAlarm = true) =>
new($"Plant/H/dev1/{name}",
$$"""{"address": "ALARM:{{selector}}", "dataType": "Boolean"{{(withAlarm ? Alarm : "")}}}""", false, "dev1");
// ---- selector grammar ----
[Theory]
[InlineData("*", "*")]
[InlineData("other", "OTHER")]
[InlineData("class=7", "CLASS=7")]
[InlineData("NUMBER=-5..-1/class=7", "CLASS=7/NUMBER=-5..-1")]
[InlineData("GROUP=4/NUMBER=100..199", "GROUP=4/NUMBER=100..199")]
public void Selector_grammar_accepts_and_canonicalises(string body, string canonical)
{
HeidenhainAlarmSelector.TryParse(body, out var s, out var error).ShouldBeTrue(error);
s!.Canonical.ShouldBe(canonical);
HeidenhainAddress.TryParse("ALARM:" + body, out var a, out _).ShouldBeTrue();
a!.Kind.ShouldBe(HeidenhainAddressKind.Alarm);
a.Text.ShouldBe("ALARM:" + canonical);
}
[Theory]
[InlineData("")]
[InlineData("CLASS")]
[InlineData("CLASS=x")]
[InlineData("CLASS=70000")]
[InlineData("CLASS=-1")]
[InlineData("NUMBER=5..1")]
[InlineData("CLASS=1/CLASS=2")]
[InlineData("TYPE=1")]
[InlineData("NUMBER=3000000000")]
public void Selector_grammar_refuses(string body)
{
HeidenhainAlarmSelector.TryParse(body, out _, out var error).ShouldBeFalse();
error.ShouldNotBeNullOrEmpty();
}
[Fact]
public void Selector_matching_and_negative_numbers()
{
HeidenhainAlarmSelector.TryParse("CLASS=7/NUMBER=-1", out var s, out _).ShouldBeTrue();
s!.Matches(7, 4, -1).ShouldBeTrue();
s.Matches(7, 4, 1).ShouldBeFalse();
s.Matches(6, 4, -1).ShouldBeFalse();
}
// ---- TagConfig pairing ----
[Fact]
public void An_alarm_selector_and_the_alarm_object_only_work_together()
{
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", AlarmTag("*", "a").TagConfig, out var def, out var error).ShouldBeTrue(error);
def!.IsAlarmCondition.ShouldBeTrue();
def.DataType.ShouldBe(DriverDataType.Boolean);
def.Alarm!.Severity.ShouldBe(800);
def.Group.ShouldBe(HeidenhainPollGroup.Alarm);
HeidenhainTagRules.ExpectedTagDataType(AlarmTag("*", "a").TagConfig).ShouldBe("Boolean");
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", AlarmTag("*", "a", withAlarm: false).TagConfig, out _, out error).ShouldBeFalse();
error!.ShouldContain("alarm");
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", """{"address":"Status/ExecutionState","alarm":{}}""", out _, out error).ShouldBeFalse();
error!.ShouldContain("not an ALARM: selector");
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", """{"address":"ALARM:*","dataType":"Int32","alarm":{}}""", out _, out _).ShouldBeFalse();
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", """{"address":"ALARM:*","isArray":true,"alarm":{}}""", out _, out _).ShouldBeFalse();
HeidenhainTagDefinitionFactory.Inspect(AlarmTag("*", "a").TagConfig).ShouldBeEmpty();
}
// ---- pure transition rules ----
private static HeidenhainAlarmTag Tag(string selector, int? severity = null) =>
new("Plant/H/dev1/a", "h:1", Parse(selector), severity);
private static HeidenhainAlarmSelector Parse(string body)
{
HeidenhainAlarmSelector.TryParse(body, out var s, out _).ShouldBeTrue();
return s!;
}
private static readonly IAlarmSubscriptionHandle H = new HeidenhainAlarmSubscriptionHandle(1);
[Fact]
public void Transitions_raise_retrigger_clear_and_ignore_reordering()
{
var tag = Tag("*", 900);
var a = new Lsv2Alarm(7, 4, -1, "Run test of cutout channels");
var b = new Lsv2Alarm(3, 1, 100, "Coolant low");
var all = new[] { tag.Selector };
var now = DateTime.UtcNow;
var (e1, t1) = HeidenhainAlarmRules.Transition(null, HeidenhainAlarmRules.Evaluate(tag.Selector, [a], all), tag, H, now);
e1!.Kind.ShouldBe(AlarmTransitionKind.Raise);
e1.ConditionId.ShouldBe(tag.RawPath);
e1.OpcUaSeverity.ShouldBe(900);
e1.Severity.ShouldBe(AlarmSeverity.Critical);
e1.Message.ShouldBe("-1 Run test of cutout channels (class 7, group 4)");
// unchanged → nothing
HeidenhainAlarmRules.Transition(t1, HeidenhainAlarmRules.Evaluate(tag.Selector, [a], all), tag, H, now).Event.ShouldBeNull();
// a new alarm (it also becomes the displayed one) → Retrigger
var (e2, t2) = HeidenhainAlarmRules.Transition(t1, HeidenhainAlarmRules.Evaluate(tag.Selector, [a, b], all), tag, H, now);
e2!.Kind.ShouldBe(AlarmTransitionKind.Retrigger);
e2.Message.ShouldBe("100 Coolant low (class 3, group 1) [+1 more]");
// the same set in another wire order → nothing (deterministic display order)
HeidenhainAlarmRules.Transition(t2, HeidenhainAlarmRules.Evaluate(tag.Selector, [b, a], all), tag, H, now).Event.ShouldBeNull();
// the displayed alarm leaves while another remains → Retrigger with the next one down
var (e3, t3) = HeidenhainAlarmRules.Transition(t2, HeidenhainAlarmRules.Evaluate(tag.Selector, [a], all), tag, H, now);
e3!.Kind.ShouldBe(AlarmTransitionKind.Retrigger);
var (e4, _) = HeidenhainAlarmRules.Transition(t3, [], tag, H, now);
e4!.Kind.ShouldBe(AlarmTransitionKind.Clear);
}
[Fact]
public void Other_is_what_no_filter_on_the_control_claims_and_severity_defaults_to_high()
{
var a = new Lsv2Alarm(7, 4, -1, "x");
var b = new Lsv2Alarm(3, 1, 100, "y");
var selectors = new[] { Parse("CLASS=7"), Parse("*"), Parse("OTHER") };
HeidenhainAlarmRules.Evaluate(Parse("OTHER"), [a, b], selectors).Select(k => k.Number).ShouldBe(new[] { 100 });
HeidenhainAlarmRules.Evaluate(Parse("*"), [a, b], selectors).Count.ShouldBe(2);
var (e, _) = HeidenhainAlarmRules.Transition(null, HeidenhainAlarmRules.Evaluate(Parse("OTHER"), [a, b], selectors),
Tag("OTHER"), H, DateTime.UtcNow);
e!.Severity.ShouldBe(AlarmSeverity.High);
e.OpcUaSeverity.ShouldBeNull();
}
// ---- 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>
private sealed class AlarmList
{
private volatile byte[][] _records = [];
private int _cursor;
public void Set(params byte[][] records) => _records = records;
public void Install(SimulatedControl c)
{
c.Runtime[27] = () => { _cursor = 0; return Next(); };
c.Runtime[28] = Next;
}
private SimReply Next()
{
var r = _records;
return _cursor < r.Length ? SimReply.Ok("S_RI", r[_cursor++]) : SimReply.Refuse(57);
}
}
/// <summary>The captured iTNC 530 reply (Java fixture <c>hermle49.27</c>): class 7, group 4, number -1.</summary>
private static byte[] Golden() => SimReply.FromFixture(Fixtures.Load("itnc530-inspect.properties")["hermle49.27"]).Payload!;
private static byte[] Record(int cls, int group, int number, string text)
{
var t = Encoding.Latin1.GetBytes(text + "\0");
var b = new byte[8 + t.Length];
BinaryPrimitives.WriteUInt16BigEndian(b, (ushort)cls);
BinaryPrimitives.WriteUInt16BigEndian(b.AsSpan(2), (ushort)group);
BinaryPrimitives.WriteInt32BigEndian(b.AsSpan(4), number);
t.CopyTo(b, 8);
return b;
}
private static HeidenhainDriverOptions Options(int port, params RawTagEntry[] tags) => new()
{
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = port, DeviceName = "dev1" }],
RawTags = tags,
TimeoutMs = 500,
Polling = new HeidenhainPollingOptions { StatusMs = 100, CustomMs = 100, SlowMs = 300, AlarmMs = 100 },
Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 200 },
};
private static HeidenhainDriver Create(HeidenhainDriverOptions o) =>
new(o, "hh-1", null, new HeidenhainCredentials(null), null, null);
private static async Task WaitUntil(Func<bool> condition, int timeoutMs = 5000)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (!condition())
{
if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached");
await Task.Delay(20, Ct);
}
}
private static readonly string[] ReadOnlyCommands = ["A_LG", "R_VR", "R_PR", "R_RI", "R_MB", "R_DP"];
[Fact]
public async Task Golden_controller_alarm_raises_and_clears_conditions_with_only_allowlisted_reads()
{
var control = new SimulatedControl();
var list = new AlarmList();
list.Install(control);
list.Set(Golden());
await using var sim = Lsv2Simulator.WithControl(control);
var any = AlarmTag("*", "Any");
var cls7 = AlarmTag("CLASS=7", "Class7");
var cls1 = AlarmTag("CLASS=1", "Class1");
var other = AlarmTag("OTHER", "Other");
await using var d = Create(Options(sim.Port, any, cls7, cls1, other));
var events = new ConcurrentQueue<AlarmEventArgs>();
d.OnAlarmEvent += (_, e) => events.Enqueue(e);
await d.InitializeAsync("{}", Ct);
(await d.ReadAsync([any.RawPath], Ct))[0].StatusCode.ShouldBe(HeidenhainStatus.BadNotSupported); // a condition, not a value
await d.SubscribeAlarmsAsync([any.RawPath, cls7.RawPath, cls1.RawPath, other.RawPath], Ct);
await WaitUntil(() => events.Count(e => e.Kind == AlarmTransitionKind.Raise) >= 2);
await Task.Delay(400, Ct); // several more walks: an unchanged list re-raises nothing
var raises = events.Where(e => e.Kind == AlarmTransitionKind.Raise).ToList();
raises.Select(e => e.ConditionId).Order().ShouldBe(new[] { any.RawPath, cls7.RawPath }.Order());
raises.ShouldAllBe(e => e.Message == "-1 Run test of cutout channels (class 7, group 4)" && e.OpcUaSeverity == 800
&& e.SourceNodeId == $"127.0.0.1:{sim.Port}");
events.Count.ShouldBe(2);
list.Set();
await WaitUntil(() => events.Count(e => e.Kind == AlarmTransitionKind.Clear) == 2);
list.Set(Record(1, 2, 3, "Other alarm"), Golden());
await WaitUntil(() => events.Any(e => e.ConditionId == cls1.RawPath && e.Kind == AlarmTransitionKind.Raise));
await WaitUntil(() => events.Count(e => e.Kind == AlarmTransitionKind.Raise) == 5); // Any, Class7, Class1 again/new
events.ShouldNotContain(e => e.ConditionId == other.RawPath); // every alarm is claimed by a CLASS filter
// Read-only: only the allowlisted read set ever reached the wire, and every alarm walk is R_RI 27/28.
control.Violations.ShouldBeEmpty();
sim.Requests.Select(r => r.Command).Distinct().ShouldBeSubsetOf(ReadOnlyCommands);
sim.Requests.Where(r => r.Command == "R_RI").Select(r => r.Selector).Distinct().Order().ShouldBe(new[] { 27, 28 });
d.GetHealth().State.ShouldBe(DriverState.Healthy);
}
[Fact]
public async Task Acknowledge_is_local_only_and_never_touches_the_control()
{
var control = new SimulatedControl();
await using var sim = Lsv2Simulator.WithControl(control);
var any = AlarmTag("*", "Any");
await using var d = Create(Options(sim.Port, any));
await d.InitializeAsync("{}", Ct);
await d.AcknowledgeAsync([new AlarmAcknowledgeRequest($"127.0.0.1:{sim.Port}", any.RawPath, "seen", "op")], Ct);
await Task.Delay(200, Ct);
sim.Connections.ShouldBe(0); // no session was opened, so nothing at all was sent
sim.Requests.ShouldBeEmpty();
// And with a live session: the request log grows only by the poll's own allowlisted reads.
var list = new AlarmList();
list.Install(control);
list.Set(Golden());
await d.SubscribeAlarmsAsync([any.RawPath], Ct);
await WaitUntil(() => sim.Requests.Count(r => r.Command == "R_RI") >= 4);
await d.AcknowledgeAsync([new AlarmAcknowledgeRequest($"127.0.0.1:{sim.Port}", any.RawPath, "seen", "op")], Ct);
await Task.Delay(200, Ct);
sim.Requests.Select(r => r.Command).Distinct().ShouldBeSubsetOf(ReadOnlyCommands);
control.Violations.ShouldBeEmpty();
}
[Fact]
public async Task Comms_loss_annotates_quality_once_and_recovery_never_re_raises_an_active_condition()
{
var control = new SimulatedControl();
var list = new AlarmList();
list.Install(control);
list.Set(Golden());
await using var sim = Lsv2Simulator.WithControl(control);
var any = AlarmTag("*", "Any");
await using var d = Create(Options(sim.Port, any));
var events = new ConcurrentQueue<AlarmEventArgs>();
d.OnAlarmEvent += (_, e) => events.Enqueue(e);
await d.InitializeAsync("{}", Ct);
await d.SubscribeAlarmsAsync([any.RawPath], Ct);
await WaitUntil(() => events.Any(e => e.Kind == AlarmTransitionKind.Raise));
sim.GoOffline();
await WaitUntil(() => events.Any(e => e.QualityStatusCode == HeidenhainStatus.BadNoCommunication));
await WaitUntil(() => d.GetHealth().State == DriverState.Degraded);
await Task.Delay(500, Ct); // several failed reconnects: still ONE annotation
events.Count(e => e.IsQualityOnly && e.QualityStatusCode == HeidenhainStatus.BadNoCommunication).ShouldBe(1);
sim.GoOnline();
await WaitUntil(() => events.Any(e => e.IsQualityOnly && e.QualityStatusCode == HeidenhainStatus.Good), 8000);
await Task.Delay(400, Ct);
events.Count(e => e.Kind == AlarmTransitionKind.Raise).ShouldBe(1); // the same alarm is still active: no re-raise (no un-ack)
events.ShouldNotContain(e => e.Kind == AlarmTransitionKind.Retrigger || e.Kind == AlarmTransitionKind.Clear);
d.GetHealth().State.ShouldBe(DriverState.Healthy);
}
[Fact]
public async Task A_refused_alarm_walk_is_quality_only_and_does_not_degrade_health()
{
var control = new SimulatedControl();
control.Runtime[27] = () => SimReply.Refuse(49); // access denied
await using var sim = Lsv2Simulator.WithControl(control);
var any = AlarmTag("*", "Any");
await using var d = Create(Options(sim.Port, any));
var events = new ConcurrentQueue<AlarmEventArgs>();
d.OnAlarmEvent += (_, e) => events.Enqueue(e);
await d.InitializeAsync("{}", Ct);
await d.SubscribeAlarmsAsync([any.RawPath], Ct);
await WaitUntil(() => events.Any(e => e.QualityStatusCode == HeidenhainStatus.BadUserAccessDenied));
await Task.Delay(400, Ct);
events.ShouldAllBe(e => e.IsQualityOnly);
events.Count.ShouldBe(1);
d.GetHealth().State.ShouldBe(DriverState.Healthy);
}
[Fact]
public async Task Alarm_events_are_recorded_only_while_a_handler_listens()
{
var control = new SimulatedControl();
var list = new AlarmList();
list.Install(control);
list.Set(Golden());
await using var sim = Lsv2Simulator.WithControl(control);
var any = AlarmTag("*", "Any");
await using var d = Create(Options(sim.Port, any));
await d.InitializeAsync("{}", Ct);
await d.SubscribeAlarmsAsync([any.RawPath], Ct);
await WaitUntil(() => sim.Requests.Count(r => r.Command == "R_RI" && r.Selector == 27) >= 3);
var events = new ConcurrentQueue<AlarmEventArgs>();
d.OnAlarmEvent += (_, e) => events.Enqueue(e);
await WaitUntil(() => events.Any(e => e.Kind == AlarmTransitionKind.Raise)); // nothing was "told" while detached
}
// ---- rediscovery ----
[Fact]
public async Task A_reconnect_with_a_different_identity_raises_rediscovery_once()
{
var control = new SimulatedControl();
control.Runtime[23] = () => SimulatedControl.U16(4);
await using var sim = Lsv2Simulator.WithControl(control);
var tag = TestTags.Raw("Status/ExecutionState");
await using var d = Create(Options(sim.Port, tag));
var raised = new ConcurrentQueue<RediscoveryEventArgs>();
d.OnRediscoveryNeeded += (_, e) => raised.Enqueue(e);
await d.InitializeAsync("{}", Ct);
await d.SubscribeAsync([tag.RawPath], TimeSpan.FromMilliseconds(100), Ct);
await WaitUntil(() => d.GetHostStatuses().Single().State == HostState.Running);
var connections = sim.Connections;
// Same identity across a reconnect: baseline only, nothing raised.
sim.GoOffline();
await WaitUntil(() => d.GetHealth().State == DriverState.Degraded);
sim.GoOnline();
await WaitUntil(() => sim.Connections > connections && d.GetHealth().State == DriverState.Healthy, 8000);
raised.ShouldBeEmpty();
// NC software update while it was away.
control.Version = Encoding.Latin1.GetBytes("iTNC 530\0NC 340490 08\0PLC\0OPT\0");
connections = sim.Connections;
sim.GoOffline();
await WaitUntil(() => d.GetHealth().State == DriverState.Degraded);
sim.GoOnline();
await WaitUntil(() => !raised.IsEmpty, 8000);
await Task.Delay(300, Ct);
raised.Count.ShouldBe(1);
raised.Single().Reason.ShouldContain("340490 04");
raised.Single().Reason.ShouldContain("340490 08");
control.Violations.ShouldBeEmpty();
}
}
@@ -98,7 +98,7 @@ public sealed class NativeAlarmEditorModelTests
public void SupportsNativeAlarms_covers_exactly_the_IAlarmSource_drivers()
{
foreach (var t in new[] { DriverTypeNames.MTConnect, DriverTypeNames.AbCip, DriverTypeNames.FOCAS,
DriverTypeNames.OpcUaClient, DriverTypeNames.Galaxy })
DriverTypeNames.OpcUaClient, DriverTypeNames.Galaxy, DriverTypeNames.Heidenhain })
NativeAlarmModel.SupportsNativeAlarms(t).ShouldBeTrue(t);
foreach (var t in new[] { DriverTypeNames.Modbus, DriverTypeNames.S7, DriverTypeNames.Mqtt, null })
NativeAlarmModel.SupportsNativeAlarms(t).ShouldBeFalse(t);
@@ -47,6 +47,9 @@
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.FOCAS\ZB.MOM.WW.OtOpcUa.Driver.FOCAS.csproj"/>
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient\ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.csproj"/>
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.Galaxy\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.csproj"/>
<!-- #831: NativeAlarmDriverSetGuardTests discovers IAlarmSource implementers by scanning the driver DLLs
deployed here, so a driver that raises native alarms must be referenced or the guard misses it. -->
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.Heidenhain\ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.csproj"/>
</ItemGroup>
</Project>
@@ -0,0 +1,164 @@
using System.Text.Json;
using Akka.Actor;
using Akka.TestKit;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests.Simulator;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// lmxopcua#831 — a Heidenhain controller alarm reaches its Part 9 condition END TO END: the REAL
/// <see cref="HeidenhainDriver"/> against the in-process LSV2 simulator (replaying the captured iTNC 530 alarm
/// record), fed the raw tags exactly as the deployment artifact delivers them, raising into the REAL
/// <see cref="DriverHostActor"/>, whose projector must turn it into an Active and then an inactive condition at
/// the tag's RawPath (the FOCAS #647 lesson: a test that stops at the driver's event cannot see a routing miss).
/// </summary>
public sealed class HeidenhainNativeAlarmEndToEndTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("heidenhain-alarm-e2e");
private static readonly RevisionHash Rev = RevisionHash.Parse(new string('a', 64));
private const string DriverId = "drv-hh";
private const string ExpectedRawPath = "Plant/Hh/m1/cnc_alarms";
/// <summary>Java fixture <c>hermle49.27</c>: class 7, group 4, number -1, "Run test of cutout channels".</summary>
private static readonly byte[] Golden =
Convert.FromHexString("00070004ffffffff52756e2074657374206f66206375746f7574206368616e6e656c7300");
[Fact]
public async Task A_controller_alarm_activates_then_clears_the_condition_at_the_RawPath()
{
var db = NewInMemoryDbFactory();
var blob = BuildArtifact();
var (host, publish) = SpawnHostAndApply(db, Seed(db, blob));
var rawTags = RawTagsFor(blob);
rawTags.Select(t => t.RawPath).ShouldBe([ExpectedRawPath]);
var control = new SimulatedControl();
var active = true;
control.Runtime[27] = () => active ? SimReply.Ok("S_RI", Golden) : SimReply.Refuse(57);
control.Runtime[28] = () => SimReply.Refuse(57);
await using var sim = Lsv2Simulator.WithControl(control);
await using var driver = new HeidenhainDriver(new HeidenhainDriverOptions
{
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = sim.Port, DeviceName = "m1" }],
RawTags = rawTags,
TimeoutMs = 500,
Polling = new HeidenhainPollingOptions { AlarmMs = 100 },
}, DriverId);
driver.OnAlarmEvent += (_, e) => host.Tell(new DriverInstanceActor.AttributeAlarmPublished(DriverId, e));
await driver.InitializeAsync("{}", CancellationToken.None);
#pragma warning disable OTOPCUA0001 // routing under test, not resilience wrapping (the FOCAS e2e precedent)
await driver.SubscribeAlarmsAsync([.. rawTags.Select(t => t.RawPath)], CancellationToken.None);
#pragma warning restore OTOPCUA0001
var raised = publish.FishForMessage<OpcUaPublishActor.AlarmStateUpdate>(_ => true, TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken);
raised.AlarmNodeId.ShouldBe(ExpectedRawPath);
raised.Realm.ShouldBe(AddressSpaceRealm.Raw);
raised.State.Active.ShouldBeTrue();
raised.State.Acknowledged.ShouldBeFalse();
raised.State.Severity.ShouldBe((ushort)800);
raised.State.Message.ShouldStartWith("-1 Run test of cutout channels");
active = false;
var cleared = publish.FishForMessage<OpcUaPublishActor.AlarmStateUpdate>(u => !u.State.Active, TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken);
cleared.AlarmNodeId.ShouldBe(ExpectedRawPath);
control.Violations.ShouldBeEmpty();
sim.Requests.Select(r => r.Command).Distinct().ShouldBeSubsetOf(new[] { "A_LG", "R_VR", "R_RI" });
}
private static List<RawTagEntry> RawTagsFor(byte[] blob)
{
using var artifact = DeploymentArtifact.Open(blob);
var spec = artifact.ParseDriverInstances().Single(s => s.DriverInstanceId == DriverId);
using var doc = JsonDocument.Parse(spec.DriverConfig);
return JsonSerializer.Deserialize<List<RawTagEntry>>(
doc.RootElement.GetProperty("RawTags").GetRawText(),
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
}
private static byte[] BuildArtifact() => JsonSerializer.SerializeToUtf8Bytes(new
{
RawFolders = new[] { new { RawFolderId = "rf-plant", ParentRawFolderId = (string?)null, Name = "Plant", ClusterId = "c1" } },
DriverInstances = new[]
{
// Enabled=false: the host spawns no driver — the test drives its own instance against the simulator.
new { DriverInstanceId = DriverId, RawFolderId = "rf-plant", Name = "Hh", DriverType = "Heidenhain", DriverConfig = "{}", ClusterId = "c1", Enabled = false },
},
Devices = new[]
{
new { DeviceId = "dev-m1", DriverInstanceId = DriverId, Name = "m1", DeviceConfig = JsonSerializer.Serialize(new { Host = "127.0.0.1" }) },
},
TagGroups = Array.Empty<object>(),
Tags = new[]
{
new
{
TagId = "tag-alarms",
DeviceId = "dev-m1",
TagGroupId = (string?)null,
Name = "cnc_alarms",
DataType = "Boolean",
AccessLevel = 0,
TagConfig = JsonSerializer.Serialize(new
{
address = "ALARM:*",
dataType = "Boolean",
alarm = new { alarmType = "AlarmCondition", severity = 800 },
}),
},
},
});
private static DeploymentId Seed(IDbContextFactory<OtOpcUaConfigDbContext> db, byte[] blob)
{
var id = DeploymentId.NewId();
using var ctx = db.CreateDbContext();
ctx.Deployments.Add(new Deployment
{
DeploymentId = id.Value,
RevisionHash = Rev.Value,
Status = DeploymentStatus.Sealed,
CreatedBy = "test",
SealedAtUtc = DateTime.UtcNow,
ArtifactBlob = blob,
});
ctx.SaveChanges();
return id;
}
private (IActorRef Actor, TestProbe Publish) SpawnHostAndApply(IDbContextFactory<OtOpcUaConfigDbContext> db, DeploymentId deploymentId)
{
var coordinator = CreateTestProbe();
var publish = this.CreateCleanOutcomePublishProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" },
dependencyMux: CreateTestProbe().Ref,
opcUaPublishActor: publish.Ref,
virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref));
actor.Tell(new DispatchDeployment(deploymentId, Rev, CorrelationId.NewId()));
coordinator.ExpectMsg<ApplyAck>(TimeSpan.FromSeconds(5)).Outcome.ShouldBe(ApplyAckOutcome.Applied);
publish.ExpectMsg<OpcUaPublishActor.RebuildAddressSpace>(TimeSpan.FromSeconds(5));
return (actor, publish);
}
}