Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/Lsv2/Lsv2Data.cs
T
Joseph Doherty d50ee809e3 feat(heidenhain): native read-only LSV2 driver + in-process simulator (#803)
Native LSV2 TCP transport (default port 19000; no Java/Python/vendor SDK), ported from
the ignitionoee v0.20.3 reference driver:

- Lsv2ReadOnlyPolicy: payload-aware outbound allowlist (A_LG INSPECT/DNC/DATA, R_VR, R_PR,
  R_RI 22-28/30-34/51, bounded R_MB, R_DP), applied in Lsv2Codec.Frame before any byte is
  written; no public raw-command API.
- Lsv2Client: serialized transactions, one monotonic deadline per transaction, EOF/oversize/
  unexpected/trickle close the client; Close never waits on the gate.
- Lsv2Data / HeidenhainBindingCodec: reference decoders, R_PR byte-capacity + element-index
  rules, next-area cap, DATA Boolean 00/01/FF, strict non-truncating coercion.
- HeidenhainSession: per-batch wire cache, refusal suppression, provisional DNC denial retry,
  alarm cursor (57 = end, overflow = BadOutOfRange), capability strings.
- HeidenhainDeviceRuntime: one loop per control, generation-guarded publication, all-node
  BadNoCommunication on comms loss, bounded exponential reconnect.
- HeidenhainDriver: cached ReadAsync, push subscriptions deduped on (value,status), static
  catalog discovery (no connect), host status, diagnostics, skipped-tag report. No IWritable.
- Probe (INSPECT login + version) and factory registered in DriverFactoryBootstrap (probe on
  admin nodes too); DriverTypeNames.Heidenhain.

Tests: 159 unit tests against an in-process LSV2 simulator incl. the Java fixtures' captured
iTNC 530 replies as golden vectors; env-gated LiveIntegration category for real hardware.
2026-11-10 23:08:30 -05:00

232 lines
10 KiB
C#

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>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.</summary>
public static int U16(ReadOnlySpan<byte> bytes)
{
Lsv2Codec.Length(bytes, 2);
return BinaryPrimitives.ReadUInt16BigEndian(bytes);
}
/// <summary>Exactly four bytes, uint32be.</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.</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: feed, spindle, rapid.</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 with two float64le geometry values.</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 number, terminated text.</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.</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>
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);
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 })
{
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.");
}