feat(mqtt): read Sparkplug B array metrics as 1-D OPC UA arrays (lmxopcua#754)
v2-ci / unit-tests (push) Has been cancelled
v2-ci / unit-tests (push) Has been cancelled
R06:M-5 made Sparkplug *Array leaves unbindable because the ingestor refused them. The ingestor now decodes the packed bytes_value of all 13 array types (new SparkplugArrayCodec: LE fixed widths, int64-ms DateTime, uint32-count + MSB-first BooleanArray, NUL-terminated UTF-8 StringArray; golden vectors are the spec's examples, reproduced byte-for-byte by SparkplugNet 1.3.10) and publishes a typed 1-D array through the scalar coercion, all-or-nothing. Shape uses the fleet's one array model: the tag's platform isArray/arrayLength keys (ValueRank=1, ArrayDimensions=[arrayLength] or [0] = variable length). The driver reads them with TagConfigIntent's exact semantics and never rejects on them, so composer, driver, authoring model and deploy inspector agree (MqttArrayShapeParityTests). Shape mismatch (array metric on a scalar tag, or the reverse) is BadTypeMismatch - a String tag no longer gets the packed buffer as base64; a malformed body or a length differing from a declared arrayLength is BadDecodingError (MTConnect #627 verdict). Template/DataSet members of an array type take the same path. Arrays stay read-only (encoder refuses them; MQTT is not in DriverArrayWriteSupport). Browser: array leaves are bindable again and state isArray in AddressFields; the commit mapper writes "isArray": true (no arrayLength). Discovery reports IsArray/ArrayDim. Docs: Mqtt.md "Array metrics", design table, drivers rule. Tests: codec (golden + malformed), ingest through the real codec + Dispatch (the project's MiniBroker never forwards a PUBLISH, so there is no in-process broker harness), browse, discovery, commit mapper, parity corpus. Mutating the fix back out fails 18 MQTT + 9 AdminUI tests. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using TahuDataType = Org.Eclipse.Tahu.Protobuf.DataType;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Sparkplug;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the packed <c>bytes_value</c> of a Sparkplug B <c>*Array</c> metric into its elements
|
||||
/// (lmxopcua#754, R06:M-5).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>The wire format (Sparkplug B 3.0, "Datatype details").</b> Every array rides in the metric's
|
||||
/// <c>bytes_value</c>, packed little-endian with no header: <c>Int8</c>/<c>UInt8</c> one byte per
|
||||
/// element, <c>Int16</c>/<c>UInt16</c> two, <c>Int32</c>/<c>UInt32</c>/<c>Float</c> four,
|
||||
/// <c>Int64</c>/<c>UInt64</c>/<c>Double</c> eight, <c>DateTime</c> eight (signed epoch milliseconds).
|
||||
/// Two types differ: a <c>BooleanArray</c> is a little-endian <c>uint32</c> element count followed by
|
||||
/// the bits packed eight per byte, the FIRST element in the MOST significant bit, the last byte
|
||||
/// zero-padded; a <c>StringArray</c> is the UTF-8 strings each terminated by <c>0x00</c>. The unit
|
||||
/// tests pin the spec's own examples, which an independent encoder (SparkplugNet 1.3.10) reproduces
|
||||
/// byte for byte.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>All-or-nothing.</b> A body whose length is not a whole number of elements, a Boolean count the
|
||||
/// body cannot hold (or a body longer than the count needs), an unterminated last string or invalid
|
||||
/// UTF-8 is malformed, and NOTHING is returned: a partial vector served as Good is a wrong value,
|
||||
/// which is worse than none (the MTConnect TIME_SERIES rule, #627).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Elements keep their wire type</b> (<see cref="sbyte"/> for <c>Int8</c>, <see cref="byte"/> for
|
||||
/// <c>UInt8</c>, <see cref="long"/> epoch milliseconds for <c>DateTime</c>, …). Coercing them onto the
|
||||
/// tag's effective type is the ingestor's job, element by element, through the same coercion the
|
||||
/// scalar path uses — so an array element and a scalar of the same value cannot disagree.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class SparkplugArrayCodec
|
||||
{
|
||||
/// <summary>Decodes one packed array body.</summary>
|
||||
/// <param name="dataType">The metric's birth-declared datatype; must be one of the 13 <c>*Array</c> variants.</param>
|
||||
/// <param name="packed">The metric's <c>bytes_value</c>.</param>
|
||||
/// <param name="elements">The decoded elements on success; <see langword="null"/> otherwise.</param>
|
||||
/// <param name="error">Why the body was refused, when this returns <see langword="false"/>; never plant data.</param>
|
||||
/// <returns><see langword="true"/> when the whole body decoded.</returns>
|
||||
public static bool TryDecode(TahuDataType dataType, ReadOnlySpan<byte> packed, out Array? elements, out string? error)
|
||||
{
|
||||
elements = null;
|
||||
error = null;
|
||||
|
||||
switch (dataType)
|
||||
{
|
||||
case TahuDataType.Int8Array:
|
||||
return Fixed(packed, 1, s => (sbyte)s[0], out elements, out error);
|
||||
case TahuDataType.Uint8Array:
|
||||
return Fixed(packed, 1, s => s[0], out elements, out error);
|
||||
case TahuDataType.Int16Array:
|
||||
return Fixed(packed, 2, BinaryPrimitives.ReadInt16LittleEndian, out elements, out error);
|
||||
case TahuDataType.Uint16Array:
|
||||
return Fixed(packed, 2, BinaryPrimitives.ReadUInt16LittleEndian, out elements, out error);
|
||||
case TahuDataType.Int32Array:
|
||||
return Fixed(packed, 4, BinaryPrimitives.ReadInt32LittleEndian, out elements, out error);
|
||||
case TahuDataType.Uint32Array:
|
||||
return Fixed(packed, 4, BinaryPrimitives.ReadUInt32LittleEndian, out elements, out error);
|
||||
case TahuDataType.Int64Array:
|
||||
case TahuDataType.DateTimeArray:
|
||||
return Fixed(packed, 8, BinaryPrimitives.ReadInt64LittleEndian, out elements, out error);
|
||||
case TahuDataType.Uint64Array:
|
||||
return Fixed(packed, 8, BinaryPrimitives.ReadUInt64LittleEndian, out elements, out error);
|
||||
case TahuDataType.FloatArray:
|
||||
return Fixed(packed, 4, BinaryPrimitives.ReadSingleLittleEndian, out elements, out error);
|
||||
case TahuDataType.DoubleArray:
|
||||
return Fixed(packed, 8, BinaryPrimitives.ReadDoubleLittleEndian, out elements, out error);
|
||||
case TahuDataType.BooleanArray:
|
||||
return Booleans(packed, out elements, out error);
|
||||
case TahuDataType.StringArray:
|
||||
return Strings(packed, out elements, out error);
|
||||
default:
|
||||
error = $"{dataType} is not a Sparkplug array datatype";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private delegate T ReadElement<out T>(ReadOnlySpan<byte> source);
|
||||
|
||||
private static bool Fixed<T>(
|
||||
ReadOnlySpan<byte> packed, int width, ReadElement<T> read, out Array? elements, out string? error)
|
||||
{
|
||||
elements = null;
|
||||
error = null;
|
||||
if (packed.Length % width != 0)
|
||||
{
|
||||
error = $"{packed.Length} bytes is not a whole number of {width}-byte elements";
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = new T[packed.Length / width];
|
||||
for (var i = 0; i < result.Length; i++)
|
||||
{
|
||||
result[i] = read(packed.Slice(i * width, width));
|
||||
}
|
||||
|
||||
elements = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool Booleans(ReadOnlySpan<byte> packed, out Array? elements, out string? error)
|
||||
{
|
||||
elements = null;
|
||||
error = null;
|
||||
if (packed.Length < 4)
|
||||
{
|
||||
error = $"{packed.Length} bytes cannot hold a BooleanArray's 4-byte element count";
|
||||
return false;
|
||||
}
|
||||
|
||||
var count = BinaryPrimitives.ReadUInt32LittleEndian(packed);
|
||||
var bits = packed[4..];
|
||||
|
||||
// Exact, not "at least": a body longer than its count needs is as malformed as a shorter one, and
|
||||
// taking the count on trust would let a corrupt header select an arbitrary prefix of the bits.
|
||||
if ((ulong)bits.Length != (count + 7UL) / 8UL)
|
||||
{
|
||||
error = $"a BooleanArray of {count} element(s) needs {(count + 7UL) / 8UL} packed byte(s), got {bits.Length}";
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = new bool[count];
|
||||
for (var i = 0; i < result.Length; i++)
|
||||
{
|
||||
// First element in the most significant bit (the spec's example: 0x34 = F,F,T,T,F,T,F,F).
|
||||
result[i] = (bits[i >> 3] & (0x80 >> (i & 7))) != 0;
|
||||
}
|
||||
|
||||
elements = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
|
||||
|
||||
private static bool Strings(ReadOnlySpan<byte> packed, out Array? elements, out string? error)
|
||||
{
|
||||
elements = null;
|
||||
error = null;
|
||||
if (packed.Length > 0 && packed[^1] != 0)
|
||||
{
|
||||
error = "the last string of a StringArray is not 0x00-terminated";
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = new List<string>();
|
||||
var rest = packed;
|
||||
try
|
||||
{
|
||||
while (!rest.IsEmpty)
|
||||
{
|
||||
var end = rest.IndexOf((byte)0);
|
||||
result.Add(StrictUtf8.GetString(rest[..end]));
|
||||
rest = rest[(end + 1)..];
|
||||
}
|
||||
}
|
||||
catch (DecoderFallbackException)
|
||||
{
|
||||
error = "a StringArray element is not valid UTF-8";
|
||||
return false;
|
||||
}
|
||||
|
||||
elements = result.ToArray();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user