Merge feat/830-heidenhain-followups

This commit is contained in:
Joseph Doherty
2026-11-11 01:55:10 -05:00
33 changed files with 1802 additions and 82 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();
}
}
@@ -151,13 +151,26 @@ public sealed class HeidenhainDriverTests
sim.GoOffline();
// EVERY remote leaf — fast status, slow identity/alarms and custom PLC — goes Bad at once.
await WaitUntil(() => tags.Take(5).All(t => rec.Last(t.RawPath)?.StatusCode == HeidenhainStatus.BadNoCommunication));
rec.Last(tags[5].RawPath)!.Value.ShouldBe("CommunicationLost");
// The invalidation is ONE pass over the device's tags (in authored order, capability last), delivered to this
// thread's recorder as it runs — so wait for the WHOLE pass to land (the capability's CommunicationLost is
// its last publication) before asserting on any of it. Asserting the capability the instant the five value
// tags read Bad raced the pass's final publish (1/40 on 5bbe1e3c: "Supported").
await WaitUntil(() => tags.Take(5).All(t => rec.Last(t.RawPath)?.StatusCode == HeidenhainStatus.BadNoCommunication)
&& rec.Last(tags[5].RawPath)?.Value is "CommunicationLost");
rec.Last(tags[5].RawPath)!.StatusCode.ShouldBe(HeidenhainStatus.Good);
// ...and it is one pass: no remote value published Good again after its outage invalidation.
foreach (var t in tags.Take(5))
{
var seq = rec.For(t.RawPath).Select(s => s.StatusCode).ToList();
seq.Skip(seq.LastIndexOf(HeidenhainStatus.BadNoCommunication)).ShouldAllBe(s => s == HeidenhainStatus.BadNoCommunication);
}
(await d.ReadAsync([tags[2].RawPath], Ct))[0].StatusCode.ShouldBe(HeidenhainStatus.BadNoCommunication);
await WaitUntil(() => d.GetHealth().State == DriverState.Degraded);
// Degraded holds through every reconnect attempt (Backoff AND Connecting carry the last error), but the host
// status reads Stopped only in Backoff and Unknown while a reconnect attempt is in flight — so wait for the
// Backoff phase rather than sample whichever phase the loop happens to be in.
await WaitUntil(() => d.GetHealth().State == DriverState.Degraded && d.GetHostStatuses().Single().State == HostState.Stopped);
d.GetHealth().LastError.ShouldNotBeNullOrEmpty();
d.GetHostStatuses().Single().State.ShouldBe(HostState.Stopped);
hostEvents.ShouldContain(e => e.NewState == HostState.Stopped);
var frozen = d.GetHealth().LastSuccessfulRead;
await Task.Delay(500, Ct);
@@ -53,7 +53,10 @@ public sealed class HeidenhainAuthoringTests
{
var m = HeidenhainDriverFormModel.FromJson("{}");
m.DncPassword = "hunter2";
m.Validate()!.ShouldNotContain("hunter2");
// #830: the credential refusal is the hosting modal's (the save gate), reported once — not the form's too.
var refusal = DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, m.ToJson());
refusal.ShouldNotBeNull();
refusal.ShouldNotContain("hunter2");
m.DncPassword = null;
m.StatusMs = 10;
m.Validate().ShouldNotBeNull();
@@ -66,7 +69,7 @@ public sealed class HeidenhainAuthoringTests
d.Port.ShouldBe(19000);
d.Validate().ShouldBeNull();
d.DataPassword = "plain";
d.Validate().ShouldNotBeNull();
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, d.ToJson()).ShouldNotBeNull(); // #830: the modal's gate
d.DataPassword = "env:OTOPCUA_HEIDENHAIN_DATA";
var json = d.ToJson();
JsonNode.Parse(json)!["Note"]!.GetValue<string>().ShouldBe("keep");
@@ -0,0 +1,176 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.DeviceForms;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Forms;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns.TagEditors;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// lmxopcua#830 authoring UX: (a) the CSV review grid previews the SAME row rule the commit applies, (b) the
/// driver-dictated data type is a lock, never a silent rewrite, (c) a credential refusal is reported once.
/// Plus the #831 ALARM: authoring seams (editor seeding, native-alarm editor visibility).
/// </summary>
[Trait("Category", "Unit")]
public sealed class HeidenhainAuthoringUxTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private const string Header = "Name,DataType,AccessLevel,TagConfigJson";
private static string Csv(params string[] rows) => Header + "\n" + string.Join("\n", rows);
private static string Json(string json) => "\"" + json.Replace("\"", "\"\"") + "\"";
// ---- (a) CSV preview == commit ----
[Fact]
public void Csv_preview_flags_ReadWrite_and_data_type_mismatch_rows_like_the_commit()
{
var exec = Json("""{"address":"Status/ExecutionState"}""");
var result = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain, Csv(
$"ok,Int32,Read,{exec}",
$"rw,Int32,ReadWrite,{exec}",
$"dt,Double,Read,{exec}",
$"feed,Int32,Read,{Json("""{"address":"Overrides/Feed"}""")}"));
result.FatalError.ShouldBeNull();
var rows = result.Rows;
rows[0].Ok.ShouldBeTrue(rows[0].Error);
rows[1].Error!.ShouldContain("read-only");
rows[2].Error!.ShouldContain("Int32");
rows[3].Error!.ShouldContain("Double"); // a Float64 leaf publishes Double — picked as Int32 it used to preview OK
result.CanCommit.ShouldBeFalse();
}
[Fact]
public async Task Csv_preview_and_ImportTags_agree_row_for_row()
{
var exec = Json("""{"address":"Status/ExecutionState"}""");
var csv = Csv($"ok,Int32,Read,{exec}", $"rw,Int32,ReadWrite,{exec}", $"dt,String,Read,{exec}",
$"plc,Int64,Read,{Json("""{"address":"PLC:DWORD:0","dataType":"Int64"}""")}");
var preview = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain, csv);
var name = RawTreeTestDb.SeedFresh();
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
var created = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "hh1", DriverTypeNames.Heidenhain, "{}", Ct);
string deviceId;
using (var db = RawTreeTestDb.CreateNamed(name)) deviceId = db.Devices.Single(d => d.DriverInstanceId == created.CreatedId).DeviceId;
// Feed EVERY parsed row (the invalid ones too, rebuilt from their cells) to the commit and compare verdicts.
foreach (var row in preview.Rows)
{
var dataType = row.Cells[1];
var access = Enum.Parse<TagAccessLevel>(row.Cells[2]);
var input = new RawTagInput(row.Cells[0], dataType, access, false, null, row.Cells[3]);
var outcome = await svc.ImportTagsAsync(deviceId, [new RawTagImportRow(null, input)], Ct);
(outcome.Errors.Count == 0).ShouldBe(row.Ok, $"{row.Name}: preview {row.Error ?? "OK"} vs commit {string.Join("; ", outcome.Errors)}");
}
}
[Fact]
public void Row_rules_are_driver_dispatched_not_named_at_call_sites()
{
RawTagRowRules.DriverTypesWithRules.ShouldContain(DriverTypeNames.Heidenhain);
RawTagRowRules.Problem(DriverTypeNames.Modbus, TagAccessLevel.ReadWrite, "Float", "{}").ShouldBeNull();
RawTagRowRules.Problem(DriverTypeNames.Heidenhain, TagAccessLevel.ReadWrite, "Int32", """{"address":"Status/ExecutionState"}""")
.ShouldBe(HeidenhainTagRules.DescribeRowProblem(true, "Int32", """{"address":"Status/ExecutionState"}"""));
RawTagRowRules.IsReadOnlyDriver(DriverTypeNames.Heidenhain).ShouldBeTrue();
RawTagRowRules.IsReadOnlyDriver(DriverTypeNames.S7).ShouldBeFalse();
}
// ---- (b) dictated data type is a lock ----
[Theory]
[InlineData("""{"address":"Axes/Positions","isArray":true}""", "Double")]
[InlineData("""{"address":"PLC:WORD:3","dataType":"Int16"}""", "Int16")]
[InlineData("""{"address":"ALARM:*","alarm":{}}""", "Boolean")]
public void The_dictated_data_type_is_what_the_grid_and_modal_lock_to(string config, string expected)
{
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Heidenhain, config).ShouldBe(expected);
// ...and the locked value is exactly what the save path accepts — nothing to rewrite on commit.
RawTagRowRules.Problem(DriverTypeNames.Heidenhain, TagAccessLevel.Read, expected, config).ShouldBeNull();
}
[Fact]
public void An_unresolved_config_or_another_driver_leaves_the_data_type_to_the_operator()
{
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Heidenhain, "{}").ShouldBeNull();
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Modbus, """{"address":"Axes/Positions","isArray":true}""").ShouldBeNull();
}
// ---- (c) credential error shown once ----
[Fact]
public void A_literal_password_is_reported_by_the_modal_save_gate_only_not_also_by_the_form()
{
var driver = HeidenhainDriverFormModel.FromJson("{}");
driver.InspectPassword = "hunter2";
var json = driver.ToJson();
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, json).ShouldNotBeNull(); // the modal's one notice + Save disabled
driver.Validate().ShouldBeNull(); // the form no longer repeats it
driver.StatusMs = 10;
driver.Validate()!.ShouldContain("StatusMs"); // non-credential problems still show in the form
var device = HeidenhainDeviceModel.FromJson("""{"Host":"cnc-7"}""");
device.DncPassword = "hunter2";
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, device.ToJson()).ShouldNotBeNull();
device.Validate().ShouldBeNull();
HeidenhainDeviceModel.FromJson("{}").Validate().ShouldNotBeNull(); // host still required in the form
}
// ---- #831 authoring seams ----
[Fact]
public void Picking_an_alarm_selector_seeds_the_alarm_object_and_leaving_it_drops_it()
{
var m = HeidenhainTagConfigModel.FromJson("{}");
m.Address = "ALARM:CLASS=7";
var json = m.ToJson();
m.Validate().ShouldBeNull();
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, json).ShouldBeNull();
NativeAlarmModel.FromJson(json).IsAlarm.ShouldBeTrue();
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", json, out var def, out _).ShouldBeTrue();
def!.Alarm!.Severity.ShouldBe(HeidenhainTagConfigModel.DefaultAlarmSeverity);
// An authored severity is never overwritten by a later edit.
var edited = NativeAlarmModel.Edit(json, a => a.Severity = 950);
var again = HeidenhainTagConfigModel.FromJson(edited);
again.Address = "ALARM:*";
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", again.ToJson(), out def, out _).ShouldBeTrue();
def!.Alarm!.Severity.ShouldBe(950);
again.Address = "Status/ExecutionState";
var plain = again.ToJson();
NativeAlarmModel.FromJson(plain).IsAlarm.ShouldBeFalse();
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, plain).ShouldBeNull();
}
[Fact]
public void Heidenhain_offers_the_native_alarm_editor_and_a_csv_alarm_row_imports()
{
NativeAlarmModel.SupportsNativeAlarms(DriverTypeNames.Heidenhain).ShouldBeTrue();
var result = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain,
"Name,DataType,AccessLevel,TagConfigJson,Alarm.AlarmType,Alarm.Severity\n" +
$"Any,Boolean,Read,{Json("""{"address":"ALARM:*"}""")},AlarmCondition,800\n" +
$"NoAlarm,Boolean,Read,{Json("""{"address":"ALARM:*"}""")},,\n");
result.Rows[0].Ok.ShouldBeTrue(result.Rows[0].Error);
result.Rows[1].Ok.ShouldBeFalse(); // a selector without the alarm object is refused in the preview
}
[Fact]
public void The_driver_form_round_trips_the_alarm_cadence()
{
var m = HeidenhainDriverFormModel.FromJson("{}");
m.AlarmMs.ShouldBe(2000);
m.AlarmMs = 500;
var o = HeidenhainOptionsParser.Parse(m.ToJson());
o.Polling.AlarmMs.ShouldBe(500);
m.AlarmMs = 50;
m.Validate()!.ShouldContain("AlarmMs");
}
}
@@ -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);
}
}