feat(heidenhain): R_RI runtime-info parity with pyLSV2 — state names, refusal codes, timer/unit docs

Compared every R_RI decoder we use (22-28, 30-34, 51) byte-for-byte with pyLSV2 (MIT,
97a3d691) and ran the captured iTNC 530 replies through pyLSV2 itself: no decode
disagreement, so no published value changes.

- Additive read-only String leaves Status/ExecutionStateName, Status/ProgramStateName and
  Tool/AxisName (pyLSV2 ExecState / PgmState / decode_tool_info names; out-of-table code =
  "Unknown"). They ride the raw leaf's feature, so no extra wire read; raw Int32 leaves unchanged.
- Refusals: 52/72 -> BadOutOfRange, 58 -> BadTimeout, 56 -> BadInvalidState, 57 (outside the
  alarm walk) -> BadNoData. IsStable and the 57-only alarm-walk end are unchanged.
  Lsv2RefusalCodes names every code (pyLSV2 LSV2StatusCode) in exception/log/probe text.
- Timers 30-34 documented as uint32be seconds (lifetime counters) per pyLSV2, hardware-unproven;
  TimersEnabled stays false. Axis/tool units: none on the wire, none assumed.
- Lsv2ReadOnlyPolicy untouched (pinned by a test); R_RI 20/21 left out.

Claude-Session: https://claude.ai/code/session_01GT67AD99zQQqpLCVm3p7xk
This commit is contained in:
Joseph Doherty
2026-11-12 23:55:34 -05:00
parent d9b2381235
commit 4cee05c2f8
12 changed files with 603 additions and 21 deletions
@@ -0,0 +1,304 @@
using System.Buffers.Binary;
using System.Text;
using Shouldly;
using Xunit;
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>
/// Parity with the open-source pyLSV2 (MIT, commit <c>97a3d691</c>) for every <c>R_RI</c> selector the driver
/// reads. The golden expectations below are what pyLSV2's own decoders (<c>misc.py:decode_axis_location</c>,
/// <c>decode_stack_info</c>, <c>decode_error_message</c>, <c>decode_tool_info</c>, <c>const.py:ExecState</c> /
/// <c>PgmState</c> / <c>LSV2StatusCode</c>) return for the captured iTNC 530 replies — produced by running pyLSV2
/// over <c>Fixtures/itnc530-inspect.properties</c>, then pinned here.
/// </summary>
[Trait("Category", "Unit")]
public sealed class HeidenhainPyLsv2ParityTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static byte[] Payload(string machine, int selector) =>
SimReply.FromFixture(Fixtures.Load("itnc530-inspect.properties")[$"{machine}.{selector}"]).Payload!;
// ---- decoders vs pyLSV2 on the real captures -------------------------------------------------------------
[Theory]
[InlineData("hermle49", new[] { 0.08392, 10.4304, 25.72673, 0.0, 270.0, -90.0 }, "TNC:\\PARTPROG\\00588001302.i")]
[InlineData("hermle59", new[] { 0.01119, 10.51793, 25.31073, 0.0, 180.0, -90.0 }, "TNC:\\partprog\\00588001302.i")]
public void Captured_replies_decode_exactly_as_pyLsv2_decodes_them(string machine, double[] positions, string main)
{
var axes = Lsv2Data.Axes(Payload(machine, 22));
axes.Names.ShouldBe(["X", "Y", "Z", "C", "a", "A"]);
axes.Positions.ShouldBe(positions);
HeidenhainStateNames.ExecutionState(Lsv2Data.U16(Payload(machine, 23))).ShouldBe("Automatic"); // pyLSV2 AUTOMATIC
HeidenhainStateNames.ProgramState(Lsv2Data.U16(Payload(machine, 26))).ShouldBe("Idle"); // pyLSV2 IDLE
var program = Lsv2Data.Program(Payload(machine, 24));
program.Line.ShouldBe(0L);
program.Main.ShouldBe(main);
program.Current.ShouldBe("");
var alarm = Lsv2Data.Alarm(Payload(machine, 27));
(alarm.ErrorClass, alarm.Group, alarm.Number, alarm.Message).ShouldBe((7, 4, -1, "Run test of cutout channels"));
}
[Fact]
public void Captured_24_byte_tool_reply_decodes_as_pyLsv2_with_axis_Z()
{
var tool = Lsv2Data.Tool(Payload("hermle59", 51));
(tool.Number, tool.Index, tool.Axis, tool.Length, tool.Radius).ShouldBe((0L, 0, 2, 0.0, 0.0));
HeidenhainStateNames.ToolAxis(tool.Axis).ShouldBe("Z");
}
[Theory]
[InlineData("hermle49", 25, 23, "T_ER_NO_PRIV")]
[InlineData("hermle49", 28, 57, "T_ER_NO_NEXT_ERROR")]
[InlineData("hermle49", 51, 24, "T_ER_WRONG_PARA")]
[InlineData("hermle59", 25, 23, "T_ER_NO_PRIV")]
public void Captured_refusals_carry_the_pyLsv2_status_code_names(string machine, int selector, int code, string name)
{
var refusal = Payload(machine, selector);
refusal[1].ShouldBe((byte)code);
Lsv2RefusalCodes.Name(code).ShouldBe(name);
new Lsv2RefusalException(refusal[0], refusal[1]).Message.ShouldContain(name);
}
// ---- decoders vs pyLSV2 layouts on synthetic vectors -----------------------------------------------------
[Fact]
public void Overrides_are_feed_spindle_rapid_hundredths_like_pyLsv2()
{
var o = new byte[12];
BinaryPrimitives.WriteUInt32BigEndian(o, 10000);
BinaryPrimitives.WriteUInt32BigEndian(o.AsSpan(4), 15050);
BinaryPrimitives.WriteUInt32BigEndian(o.AsSpan(8), 1);
Lsv2Data.Overrides(o).ShouldBe([100.0, 150.5, 0.01]);
}
[Fact]
public void Tool_geometry_is_little_endian_after_big_endian_identity_like_pyLsv2()
{
var t = new byte[24];
BinaryPrimitives.WriteUInt32BigEndian(t, 49);
BinaryPrimitives.WriteUInt16BigEndian(t.AsSpan(4), 3);
BinaryPrimitives.WriteUInt16BigEndian(t.AsSpan(6), 1);
BinaryPrimitives.WriteDoubleLittleEndian(t.AsSpan(8), 138.1506);
BinaryPrimitives.WriteDoubleLittleEndian(t.AsSpan(16), -0.0101);
var tool = Lsv2Data.Tool(t);
(tool.Number, tool.Index, tool.Axis, tool.Length, tool.Radius).ShouldBe((49L, 3, 1, 138.1506, -0.0101));
}
[Fact]
public void Alarm_number_is_signed_int32_like_pyLsv2()
{
// The live 2026-11-11 record 0x8100017B (HMI 702126) is negative as int32 — pyLSV2 unpacks "!l" too.
var a = new byte[8 + 2];
BinaryPrimitives.WriteUInt16BigEndian(a, 7);
BinaryPrimitives.WriteUInt16BigEndian(a.AsSpan(2), 3);
BinaryPrimitives.WriteUInt32BigEndian(a.AsSpan(4), 0x8100017Bu);
a[8] = (byte)'x';
Lsv2Data.Alarm(a).Number.ShouldBe(-2130706053);
}
[Fact]
public void Timers_are_u32be_seconds_published_raw()
{
// per pyLSV2 const.py:ParRRI: u32be, NC uptime +1/s. 0x0001_5180 = 86 400 s = one day; no rescaling.
Lsv2Data.U32([0x00, 0x01, 0x51, 0x80]).ShouldBe(86400L);
Lsv2Data.U32([0xFF, 0xFF, 0xFF, 0xFF]).ShouldBe(4294967295L);
Should.Throw<Lsv2DecodeException>(() => Lsv2Data.U32([0, 0, 1]));
}
// ---- enum names ------------------------------------------------------------------------------------------
[Fact]
public void Name_tables_cover_every_pyLsv2_enum_member_in_order()
{
// per pyLSV2 const.py:ExecState 0..5 and PgmState 0..8 (UPPER_SNAKE there, PascalCase here).
HeidenhainStateNames.ExecutionStates.ShouldBe(["Manual", "Mdi", "PassReferences", "SingleStep", "Automatic", "Undefined"]);
HeidenhainStateNames.ProgramStates.ShouldBe(
["Started", "Stopped", "Finished", "Cancelled", "Interrupted", "Error", "ErrorCleared", "Idle", "Undefined"]);
HeidenhainStateNames.ToolAxes.ShouldBe(["X", "Y", "Z"]);
}
[Theory]
[InlineData(6)]
[InlineData(300)]
[InlineData(65535)]
[InlineData(-1)]
public void An_out_of_table_code_is_Unknown_never_an_invented_name(int code)
{
HeidenhainStateNames.ExecutionState(code).ShouldBe(HeidenhainStateNames.Unknown);
HeidenhainStateNames.ToolAxis(code).ShouldBe(HeidenhainStateNames.Unknown);
if (code != 6) HeidenhainStateNames.ProgramState(code).ShouldBe(HeidenhainStateNames.Unknown);
}
[Fact]
public void Name_leaves_are_additive_String_catalog_entries_on_the_raw_leaves_feature()
{
foreach (var (name, raw) in new[] { ("Status/ExecutionStateName", "Status/ExecutionState"), ("Status/ProgramStateName", "Status/ProgramState"), ("Tool/AxisName", "Tool/AxisCode") })
{
HeidenhainCatalog.TryGet(name, out var n).ShouldBeTrue(name);
HeidenhainCatalog.TryGet(raw, out var r).ShouldBeTrue(raw);
n!.DataType.ShouldBe(Core.Abstractions.DriverDataType.String);
n.IsArray.ShouldBeFalse();
n.Feature.ShouldBe(r!.Feature); // one wire read serves both
n.Group.ShouldBe(r.Group);
r.DataType.ShouldBe(Core.Abstractions.DriverDataType.Int32); // the raw leaf is unchanged
}
}
[Fact]
public async Task Name_leaves_share_the_raw_read_and_leave_the_raw_value_unchanged()
{
var c = new SimulatedControl();
c.Runtime[23] = () => SimReply.Ok("S_RI", [0, 4]);
c.Runtime[26] = () => SimReply.Ok("S_RI", [0, 0]);
c.Runtime[51] = () => SimReply.Ok("S_RI", [0, 0, 0, 17, 0, 0, 0, 2]); // 8-byte identity-only reply
string[] addresses = ["Status/ExecutionState", "Status/ExecutionStateName", "Status/ProgramState", "Status/ProgramStateName",
"Tool/AxisCode", "Tool/AxisName", "Tool/Length"];
await using var sim = Lsv2Simulator.WithControl(c);
var client = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
var settings = new HeidenhainSessionSettings(true, true, false, 64, false, false, false);
await using var session = new HeidenhainSession(client, settings, (_, _) => ValueTask.FromResult(""));
await client.OpenAsync(Ct);
await session.InitializeAsync(Ct);
var v = await session.ReadBatchAsync(addresses.Select(a => TestTags.Def(a)).ToList(), Ct);
v[0].Value.ShouldBeOfType<int>().ShouldBe(4);
v[1].Value.ShouldBe("Automatic");
v[2].Value.ShouldBeOfType<int>().ShouldBe(0);
v[3].Value.ShouldBe("Started");
v[4].Value.ShouldBeOfType<int>().ShouldBe(2);
v[5].Value.ShouldBe("Z");
v[5].Status.ShouldBe(HeidenhainStatus.Good); // the axis is in the identity part, served even without geometry
v[6].Status.ShouldBe(HeidenhainStatus.BadNotSupported);
sim.Requests.Count(r => r.Command == "R_RI" && r.Selector == 23).ShouldBe(1);
sim.Requests.Count(r => r.Command == "R_RI" && r.Selector == 26).ShouldBe(1);
sim.Requests.Count(r => r.Command == "R_RI" && r.Selector == 51).ShouldBe(1);
c.Violations.ShouldBeEmpty();
}
[Fact]
public async Task A_refused_raw_selector_makes_its_name_leaf_bad_with_the_same_status()
{
var c = new SimulatedControl();
c.Runtime[26] = () => SimReply.Refuse(23);
await using var sim = Lsv2Simulator.WithControl(c);
var client = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
var settings = new HeidenhainSessionSettings(true, true, false, 64, false, false, false);
await using var session = new HeidenhainSession(client, settings, (_, _) => ValueTask.FromResult(""));
await client.OpenAsync(Ct);
await session.InitializeAsync(Ct);
var v = await session.ReadBatchAsync([TestTags.Def("Status/ProgramState"), TestTags.Def("Status/ProgramStateName")], Ct);
v.ShouldAllBe(s => s.Status == HeidenhainStatus.BadUserAccessDenied && s.Value == null);
}
// ---- refusal codes ---------------------------------------------------------------------------------------
[Theory]
[InlineData(22, HeidenhainStatus.BadNotSupported, true)] // T_ER_UNKNOWN_TELE
[InlineData(24, HeidenhainStatus.BadNotSupported, true)] // T_ER_WRONG_PARA
[InlineData(23, HeidenhainStatus.BadUserAccessDenied, true)] // T_ER_NO_PRIV
[InlineData(49, HeidenhainStatus.BadUserAccessDenied, true)] // T_ER_NO_LOGIN
[InlineData(52, HeidenhainStatus.BadOutOfRange, false)] // T_ER_BAD_MEMADR
[InlineData(72, HeidenhainStatus.BadOutOfRange, false)] // T_ER_OUT_OF_RANGE
[InlineData(58, HeidenhainStatus.BadTimeout, false)] // T_ER_ACCESS_TIMEOUT
[InlineData(56, HeidenhainStatus.BadInvalidState, false)] // T_ER_OPERATING_MODE
[InlineData(57, HeidenhainStatus.BadNoData, false)] // T_ER_NO_NEXT_ERROR (outside the alarm walk)
[InlineData(25, HeidenhainStatus.BadUnexpectedError, false)] // T_ER_BREAK
[InlineData(20, HeidenhainStatus.BadUnexpectedError, false)] // T_ER_BAD_FORMAT
[InlineData(250, HeidenhainStatus.BadUnexpectedError, false)] // not in the table
public void Refusal_codes_map_to_the_most_specific_status_and_only_the_old_stable_set_is_stable(int code, uint status, bool stable)
{
HeidenhainStatus.FromRefusal(code).ShouldBe(status);
HeidenhainStatus.IsStable(HeidenhainStatus.FromRefusal(code)).ShouldBe(stable);
}
[Fact]
public void New_status_constants_are_the_canonical_opc_ua_numerics()
{
HeidenhainStatus.BadTimeout.ShouldBe(0x800A0000u);
HeidenhainStatus.BadInvalidState.ShouldBe(0x80AF0000u);
HeidenhainStatus.BadNoData.ShouldBe(0x809B0000u);
}
[Theory]
[InlineData(23, "T_ER_NO_PRIV")]
[InlineData(24, "T_ER_WRONG_PARA")]
[InlineData(52, "T_ER_BAD_MEMADR")]
[InlineData(57, "T_ER_NO_NEXT_ERROR")]
[InlineData(58, "T_ER_ACCESS_TIMEOUT")]
[InlineData(111, "T_BD_CANCELLED")]
[InlineData(1, "UNKNOWN_1")]
public void Refusal_names_follow_the_pyLsv2_status_code_table(int code, string name) => Lsv2RefusalCodes.Name(code).ShouldBe(name);
[Fact]
public async Task An_access_timeout_refusal_is_BadTimeout_and_retried_not_suppressed()
{
var calls = 0;
var c = new SimulatedControl();
c.Runtime[23] = () => Interlocked.Increment(ref calls) == 1 ? SimReply.Refuse(58) : SimReply.Ok("S_RI", [0, 4]);
await using var sim = Lsv2Simulator.WithControl(c);
var client = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
var settings = new HeidenhainSessionSettings(true, true, false, 64, false, false, false);
await using var session = new HeidenhainSession(client, settings, (_, _) => ValueTask.FromResult(""));
await client.OpenAsync(Ct);
await session.InitializeAsync(Ct);
var tag = TestTags.Def("Status/ExecutionState");
(await session.ReadBatchAsync([tag], Ct))[0].Status.ShouldBe(HeidenhainStatus.BadTimeout);
var second = (await session.ReadBatchAsync([tag], Ct))[0];
second.Status.ShouldBe(HeidenhainStatus.Good);
second.Value.ShouldBe(4);
calls.ShouldBe(2);
session.CommunicationLost.ShouldBeFalse(); // a refusal is never a transport failure
}
[Fact]
public async Task Only_57_ends_the_alarm_walk_other_refusals_fail_it()
{
var c = new SimulatedControl();
var record = new byte[10];
BinaryPrimitives.WriteUInt16BigEndian(record, 1);
record[8] = (byte)'a';
c.Runtime[27] = () => SimReply.Ok("S_RI", record);
c.Runtime[28] = () => SimReply.Refuse(58);
await using var sim = Lsv2Simulator.WithControl(c);
var client = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
var settings = new HeidenhainSessionSettings(true, true, false, 64, false, false, false);
await using var session = new HeidenhainSession(client, settings, (_, _) => ValueTask.FromResult(""));
await client.OpenAsync(Ct);
await session.InitializeAsync(Ct);
var count = (await session.ReadBatchAsync([TestTags.Def("Alarms/Count")], Ct))[0];
count.Status.ShouldBe(HeidenhainStatus.BadTimeout); // never a truncated list of 1
c.Runtime[28] = () => SimReply.Refuse(57);
(await session.ReadBatchAsync([TestTags.Def("Alarms/Count")], Ct))[0].Value.ShouldBe(1);
}
[Fact]
public void The_read_only_allowlist_is_unchanged()
{
// This work adds derived leaves only: no new selector (pyLSV2's 20/21 axis names stay out), request type or role.
Lsv2ReadOnlyPolicy.Selectors.OrderBy(s => s).ShouldBe([22, 23, 24, 25, 26, 27, 28, 30, 31, 32, 33, 34, 51]);
Lsv2ReadOnlyPolicy.Roles.OrderBy(r => r, StringComparer.Ordinal).ShouldBe(["DATA", "DNC", "INSPECT"]);
Lsv2ReadOnlyPolicy.Commands.OrderBy(c => c, StringComparer.Ordinal).ShouldBe(["A_LG", "R_DP", "R_MB", "R_PR", "R_RI", "R_VR"]);
foreach (var s in new[] { 20, 21 })
{
var payload = new byte[2];
BinaryPrimitives.WriteUInt16BigEndian(payload, (ushort)s);
Should.Throw<Exception>(() => Lsv2ReadOnlyPolicy.Check("R_RI", payload), $"selector {s}");
}
Should.Throw<Exception>(() => Lsv2ReadOnlyPolicy.Check("A_LG", Encoding.Latin1.GetBytes("FILE\0\0")));
}
}