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
@@ -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);
}
}