Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/Lsv2/Lsv2Data.cs
T
Joseph Doherty f8785cfa2c Merge branch 'worktree-agent-a71443b71c4c01c13' into heidenhain-pylsv2-parity
# Conflicts:
#	.claude/rules/drivers.md
#	docs/drivers/Heidenhain.md
#	tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainPyLsv2ParityTests.cs
2026-11-12 23:57:06 -05:00

278 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Buffers.Binary;
using System.Globalization;
using System.Text;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Lsv2;
/// <summary>Controller identity from <c>R_VR</c>.</summary>
public sealed record Lsv2Versions(string Model, string Nc, string Plc, string Options)
{
/// <summary>The control family derived from <see cref="Model"/> (computed, no backing field: equality and the #831 identity-change signal are unchanged).</summary>
public HeidenhainControlFamily Family => HeidenhainControlFamilies.Classify(Model);
}
/// <summary>Program stack from <c>R_RI 24</c>.</summary>
public sealed record Lsv2Program(long Line, string Main, string Current);
/// <summary>Tool from <c>R_RI 51</c>; geometry is null on the 8-byte identity-only reply.</summary>
public sealed record Lsv2Tool(long Number, int Index, int Axis, double? Length, double? Radius);
/// <summary>One alarm record from <c>R_RI 27/28</c>.</summary>
public sealed record Lsv2Alarm(int ErrorClass, int Group, int Number, string Message);
/// <summary>Aligned axis names and positions from <c>R_RI 22</c> (controller units, no inference).</summary>
public sealed record Lsv2Axes(string[] Names, double[] Positions);
/// <summary>An advertised PLC region: base address, capacity in bytes, native element width.</summary>
public sealed record Lsv2Region(long Base, long Bytes, int Width);
/// <summary>The <c>R_PR</c> PLC memory layout.</summary>
public sealed record Lsv2Layout(IReadOnlyDictionary<HeidenhainPlcArea, Lsv2Region> Regions)
{
/// <summary>The region for an area, or null.</summary>
/// <param name="area">The area.</param>
/// <returns>The region.</returns>
public Lsv2Region? Region(HeidenhainPlcArea area) => Regions.TryGetValue(area, out var r) ? r : null;
}
/// <summary>
/// Pure reference-derived decoders (port of <c>Lsv2Data</c>). Malformed data is never repaired into a Good
/// value: every rule throws <see cref="Lsv2DecodeException"/>.
/// </summary>
public static class Lsv2Data
{
/// <summary>Exactly four or five NUL-terminated fields; an optional SPLC 4th field is skipped; empty final options are preserved.</summary>
public static Lsv2Versions Versions(ReadOnlySpan<byte> bytes)
{
var parts = Strings(bytes, 0);
// Empty final options are meaningful; trimming them would relabel SPLC as options.
if ((parts.Count != 4 && parts.Count != 5) || string.IsNullOrWhiteSpace(parts[0])) throw Bad();
return new Lsv2Versions(parts[0], parts[1], parts[2], parts[^1]);
}
/// <summary>
/// Exactly two bytes, uint16be — <c>R_RI 23</c> execution mode / <c>R_RI 26</c> program state, per pyLSV2 (MIT)
/// <c>client.py:execution_state</c> / <c>program_status</c> (<c>struct "!H"</c>).
/// </summary>
public static int U16(ReadOnlySpan<byte> bytes)
{
Lsv2Codec.Length(bytes, 2);
return BinaryPrimitives.ReadUInt16BigEndian(bytes);
}
/// <summary>
/// Exactly four bytes, uint32be — the <c>R_RI 30–34</c> lifetime timers, in SECONDS per pyLSV2 (MIT)
/// <c>const.py:ParRRI</c> + <c>docs/protocol.rst</c> (hardware-unproven here). Published raw, never rescaled.
/// </summary>
public static long U32(ReadOnlySpan<byte> bytes)
{
Lsv2Codec.Length(bytes, 4);
return BinaryPrimitives.ReadUInt32BigEndian(bytes);
}
/// <summary>
/// uint32be line, main NUL, current NUL, optional NUL padding only — per pyLSV2 (MIT)
/// <c>misc.py:decode_stack_info</c>, but strict (pyLSV2 ignores what follows the second string).
/// </summary>
public static Lsv2Program Program(ReadOnlySpan<byte> bytes)
{
if (bytes.Length < 6) throw Bad();
var parts = Strings(bytes, 4);
if (parts.Count < 2 || parts.Skip(2).Any(s => s.Length != 0)) throw Bad();
return new Lsv2Program(BinaryPrimitives.ReadUInt32BigEndian(bytes), parts[0], parts[1]);
}
/// <summary>
/// Three uint32be hundredths of percent, in the order feed, spindle, rapid — per pyLSV2 (MIT)
/// <c>misc.py:decode_override_state</c> (<c>/ 100</c>).
/// </summary>
public static double[] Overrides(ReadOnlySpan<byte> bytes)
{
Lsv2Codec.Length(bytes, 12);
return
[
BinaryPrimitives.ReadUInt32BigEndian(bytes) / 100.0,
BinaryPrimitives.ReadUInt32BigEndian(bytes[4..]) / 100.0,
BinaryPrimitives.ReadUInt32BigEndian(bytes[8..]) / 100.0,
];
}
/// <summary>
/// 8-byte identity-only or 24-byte reply: uint32be number, uint16be index, uint16be axis code (0 X, 1 Y, 2 Z),
/// then float64 LITTLE-endian length and radius — per pyLSV2 (MIT) <c>misc.py:decode_tool_info</c> (<c>"&lt;d"</c>;
/// the mixed endianness is real: a live iTNC 530 read L 138.1506 / R −0.0101 through this decoder, 2026-11-11).
/// No unit is on the wire and pyLSV2 assumes none either; none is inferred here.
/// </summary>
public static Lsv2Tool Tool(ReadOnlySpan<byte> bytes)
{
if (bytes.Length != 8 && bytes.Length != 24) throw Bad();
long number = BinaryPrimitives.ReadUInt32BigEndian(bytes);
int index = BinaryPrimitives.ReadUInt16BigEndian(bytes[4..]);
int axis = BinaryPrimitives.ReadUInt16BigEndian(bytes[6..]);
double? length = null, radius = null;
if (bytes.Length == 24)
{
length = Finite(BinaryPrimitives.ReadDoubleLittleEndian(bytes[8..]));
radius = Finite(BinaryPrimitives.ReadDoubleLittleEndian(bytes[16..]));
}
return new Lsv2Tool(number, index, axis, length, radius);
}
/// <summary>
/// uint16be class, uint16be group, int32be (signed) number, terminated text — per pyLSV2 (MIT)
/// <c>misc.py:decode_error_message</c>. Stricter on the text: it must be NUL-terminated with NUL padding only,
/// and trailing blanks are kept (pyLSV2 <c>ba_to_ustr</c> strips them; the text is part of a condition's identity).
/// </summary>
public static Lsv2Alarm Alarm(ReadOnlySpan<byte> bytes)
{
if (bytes.Length < 9) throw Bad();
return new Lsv2Alarm(
BinaryPrimitives.ReadUInt16BigEndian(bytes),
BinaryPrimitives.ReadUInt16BigEndian(bytes[2..]),
BinaryPrimitives.ReadInt32BigEndian(bytes[4..]),
Lsv2Codec.Text(bytes[8..]));
}
/// <summary>
/// Opaque byte, uint8 count, count numeric strings, count unique non-blank names — per pyLSV2 (MIT)
/// <c>misc.py:decode_axis_location</c> (values first, then names; byte 0 undocumented there too). Positions are
/// the control's display strings parsed as-is: no unit is on the wire and pyLSV2 assumes none (linear vs rotary
/// axes and mm vs inch are neither reported nor inferred here).
/// </summary>
public static Lsv2Axes Axes(ReadOnlySpan<byte> bytes)
{
if (bytes.Length < 2) throw Bad();
int count = bytes[1];
if (count > 64) throw Bad();
var parts = Strings(bytes, 2);
if (parts.Count != count * 2) throw Bad();
var names = new string[count];
var values = new double[count];
var seen = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < count; i++)
{
names[i] = parts[i + count];
if (string.IsNullOrWhiteSpace(names[i]) || !seen.Add(names[i])) throw Bad();
if (!double.TryParse(parts[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var v)) throw Bad();
values[i] = Finite(v);
}
return new Lsv2Axes(names, values);
}
/// <summary>
/// <c>R_PR</c>: 120 or 124 bytes. Numeric R_PR counts are BYTE capacities (live-verified on three iTNC 530:
/// B9999/W9998/D9996 are the last valid values for a count of 10000); bit and string counts are entries.
/// The next populated distinct area remains a defensive cap for inconsistent layouts.
/// </summary>
/// <remarks>
/// Field offsets agree with pyLSV2 (MIT) misc.py:decode_system_parameters (<c>!14L8B8L…</c>): eight
/// uint32be (base, count) pairs for markers/inputs/outputs/counters/timers/words/strings at 0–55, the string
/// length byte at 56, input words at 64, output words at 72; the trailing LSV2-version/buffer/key fields are
/// not used. pyLSV2's count UNITS conflict with the real captures and are deliberately not followed:
/// client.py:read_plc_memory caps BYTE at count×2, WORD and INPUT_WORD/OUTPUT_WORD at count (as if the
/// count were words) and only DWORD at count/4 — the iTNC 530 replies in plc-count-units.properties
/// refuse B10000, W10000 and IW1000, and every advertised base + count lands exactly on the next base.
/// </remarks>
public static Lsv2Layout Layout(ReadOnlySpan<byte> bytes)
{
if (bytes.Length != 120 && bytes.Length != 124) throw Bad();
var regions = new Dictionary<HeidenhainPlcArea, Lsv2Region>();
HeidenhainPlcArea[] bits = [HeidenhainPlcArea.Marker, HeidenhainPlcArea.Input, HeidenhainPlcArea.Output, HeidenhainPlcArea.Counter, HeidenhainPlcArea.Timer];
for (var i = 0; i < bits.Length; i++) Add(regions, bytes, bits[i], i * 8, 1, 1);
Add(regions, bytes, HeidenhainPlcArea.Byte, 40, 1, 1);
Add(regions, bytes, HeidenhainPlcArea.Word, 40, 1, 2);
Add(regions, bytes, HeidenhainPlcArea.Dword, 40, 1, 4);
int stringWidth = bytes[56];
Add(regions, bytes, HeidenhainPlcArea.String, 48, stringWidth, stringWidth);
Add(regions, bytes, HeidenhainPlcArea.InputWord, 64, 1, 2);
Add(regions, bytes, HeidenhainPlcArea.OutputWord, 72, 1, 2);
// per pyLSV2 (MIT) client.py:read_plc_memory — the DWORD views share the input/output-word pools.
Add(regions, bytes, HeidenhainPlcArea.InputDword, 64, 1, 4);
Add(regions, bytes, HeidenhainPlcArea.OutputDword, 72, 1, 4);
CapNumericRegionsAtNextArea(regions);
return new Lsv2Layout(regions);
}
private static void CapNumericRegionsAtNextArea(Dictionary<HeidenhainPlcArea, Lsv2Region> regions)
{
// Same-base BYTE/WORD/DWORD views intentionally share an area, not a boundary.
var starts = new SortedSet<long>(regions.Values.Where(r => r.Bytes > 0 && r.Width > 0).Select(r => r.Base));
foreach (var area in new[]
{
HeidenhainPlcArea.Byte, HeidenhainPlcArea.Word, HeidenhainPlcArea.Dword, HeidenhainPlcArea.InputWord,
HeidenhainPlcArea.OutputWord, HeidenhainPlcArea.InputDword, HeidenhainPlcArea.OutputDword,
})
{
var region = regions[area];
var next = starts.GetViewBetween(region.Base + 1, long.MaxValue).Cast<long?>().FirstOrDefault();
if (next is { } n && n - region.Base < region.Bytes)
regions[area] = region with { Bytes = n - region.Base };
}
}
private static void Add(Dictionary<HeidenhainPlcArea, Lsv2Region> r, ReadOnlySpan<byte> b, HeidenhainPlcArea area, int offset, int unit, int width)
{
long @base = BinaryPrimitives.ReadUInt32BigEndian(b[offset..]);
long size = (long)BinaryPrimitives.ReadUInt32BigEndian(b[(offset + 4)..]) * unit;
if (@base + size > 0x1_0000_0000L) throw Bad();
r[area] = new Lsv2Region(@base, size, width);
}
/// <summary>
/// <c>R_DP</c> value: uint32be type then 2=int16be, 3=int32be, 5=float64le, 8=terminated text,
/// 11=Boolean byte (00 false; 01/FF true — FF observed on real iTNC 530 I/O), 16=int8, 17=uint8.
/// </summary>
public static object DataPath(ReadOnlySpan<byte> bytes)
{
if (bytes.Length < 4) throw Bad();
var type = BinaryPrimitives.ReadUInt32BigEndian(bytes);
switch (type)
{
case 2:
Lsv2Codec.Length(bytes, 6);
return (int)BinaryPrimitives.ReadInt16BigEndian(bytes[4..]);
case 3:
Lsv2Codec.Length(bytes, 8);
return BinaryPrimitives.ReadInt32BigEndian(bytes[4..]);
case 5:
Lsv2Codec.Length(bytes, 12);
return Finite(BinaryPrimitives.ReadDoubleLittleEndian(bytes[4..]));
case 8:
return Lsv2Codec.Text(bytes[4..]);
case 11:
Lsv2Codec.Length(bytes, 5);
if (bytes[4] is not (0 or 1 or 0xFF)) throw Bad();
return bytes[4] != 0;
case 16:
Lsv2Codec.Length(bytes, 5);
return (int)(sbyte)bytes[4];
case 17:
Lsv2Codec.Length(bytes, 5);
return (int)bytes[4];
default:
throw Bad();
}
}
private static double Finite(double value) => double.IsFinite(value) ? value : throw Bad();
private static List<string> Strings(ReadOnlySpan<byte> bytes, int offset)
{
if (offset > bytes.Length || (offset < bytes.Length && bytes[^1] != 0)) throw Bad();
var result = new List<string>();
var start = offset;
for (var i = offset; i < bytes.Length; i++)
{
if (bytes[i] != 0) continue;
result.Add(Encoding.Latin1.GetString(bytes[start..i]));
start = i + 1;
}
return result;
}
private static Lsv2DecodeException Bad() => new("Malformed LSV2 data record.");
}