using System.Buffers.Binary;
using System.Globalization;
using System.Text;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Lsv2;
/// Controller identity from R_VR.
public sealed record Lsv2Versions(string Model, string Nc, string Plc, string Options);
/// Program stack from R_RI 24.
public sealed record Lsv2Program(long Line, string Main, string Current);
/// Tool from R_RI 51; geometry is null on the 8-byte identity-only reply.
public sealed record Lsv2Tool(long Number, int Index, int Axis, double? Length, double? Radius);
/// One alarm record from R_RI 27/28.
public sealed record Lsv2Alarm(int ErrorClass, int Group, int Number, string Message);
/// Aligned axis names and positions from R_RI 22 (controller units, no inference).
public sealed record Lsv2Axes(string[] Names, double[] Positions);
/// An advertised PLC region: base address, capacity in bytes, native element width.
public sealed record Lsv2Region(long Base, long Bytes, int Width);
/// The R_PR PLC memory layout.
public sealed record Lsv2Layout(IReadOnlyDictionary Regions)
{
/// The region for an area, or null.
/// The area.
/// The region.
public Lsv2Region? Region(HeidenhainPlcArea area) => Regions.TryGetValue(area, out var r) ? r : null;
}
///
/// Pure reference-derived decoders (port of Lsv2Data). Malformed data is never repaired into a Good
/// value: every rule throws .
///
public static class Lsv2Data
{
/// Exactly four or five NUL-terminated fields; an optional SPLC 4th field is skipped; empty final options are preserved.
public static Lsv2Versions Versions(ReadOnlySpan 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]);
}
/// Exactly two bytes, uint16be.
public static int U16(ReadOnlySpan bytes)
{
Lsv2Codec.Length(bytes, 2);
return BinaryPrimitives.ReadUInt16BigEndian(bytes);
}
/// Exactly four bytes, uint32be.
public static long U32(ReadOnlySpan bytes)
{
Lsv2Codec.Length(bytes, 4);
return BinaryPrimitives.ReadUInt32BigEndian(bytes);
}
/// uint32be line, main NUL, current NUL, optional NUL padding only.
public static Lsv2Program Program(ReadOnlySpan 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]);
}
/// Three uint32be hundredths of percent: feed, spindle, rapid.
public static double[] Overrides(ReadOnlySpan bytes)
{
Lsv2Codec.Length(bytes, 12);
return
[
BinaryPrimitives.ReadUInt32BigEndian(bytes) / 100.0,
BinaryPrimitives.ReadUInt32BigEndian(bytes[4..]) / 100.0,
BinaryPrimitives.ReadUInt32BigEndian(bytes[8..]) / 100.0,
];
}
/// 8-byte identity-only or 24-byte reply with two float64le geometry values.
public static Lsv2Tool Tool(ReadOnlySpan 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);
}
/// uint16be class, uint16be group, int32be number, terminated text.
public static Lsv2Alarm Alarm(ReadOnlySpan 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..]));
}
/// Opaque byte, uint8 count, count numeric strings, count unique non-blank names.
public static Lsv2Axes Axes(ReadOnlySpan 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(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);
}
///
/// R_PR: 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.
///
public static Lsv2Layout Layout(ReadOnlySpan bytes)
{
if (bytes.Length != 120 && bytes.Length != 124) throw Bad();
var regions = new Dictionary();
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 regions)
{
// Same-base BYTE/WORD/DWORD views intentionally share an area, not a boundary.
var starts = new SortedSet(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().FirstOrDefault();
if (next is { } n && n - region.Base < region.Bytes)
regions[area] = region with { Bytes = n - region.Base };
}
}
private static void Add(Dictionary r, ReadOnlySpan 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);
}
///
/// R_DP 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.
///
public static object DataPath(ReadOnlySpan 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 Strings(ReadOnlySpan bytes, int offset)
{
if (offset > bytes.Length || (offset < bytes.Length && bytes[^1] != 0)) throw Bad();
var result = new List();
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.");
}