feat(mqtt): read Sparkplug B array metrics as 1-D OPC UA arrays (lmxopcua#754)
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:
Joseph Doherty
2026-11-09 13:58:38 -05:00
parent 919009c5ef
commit 7f29a75edb
19 changed files with 1112 additions and 53 deletions
@@ -526,8 +526,10 @@ public sealed class MqttDriver
folder.Variable(def.Name, def.Name, new DriverAttributeInfo(
FullName: def.Name,
DriverDataType: ResolveDiscoveredDataType(def),
IsArray: false,
ArrayDim: null,
// The authored array shape (#754, Sparkplug only), as the composer materialises it:
// element DataType + ValueRank=1, a declared length or variable-length (null).
IsArray: def.IsArray,
ArrayDim: def.IsArray && def.ArrayLength is > 0u ? def.ArrayLength : null,
// MQTT now has a write leg, so a tag that declares a write destination is
// an Operate node. One that does not stays ViewOnly — the point of the distinction is
// that a node must never look writable while its writes would go nowhere.
@@ -126,6 +126,9 @@ public sealed class SparkplugIngestor
/// <summary>The metric's value does not fit the tag's effective data type — including an explicit Sparkplug null.</summary>
private const uint StatusBadTypeMismatch = 0x80740000u;
/// <summary>A Sparkplug <c>*Array</c> body that is not a whole, well-formed vector (lmxopcua#754).</summary>
private const uint StatusBadDecodingError = 0x80070000u;
/// <summary>The subscribed reference is not an authored Sparkplug tag.</summary>
private const uint StatusBadNodeIdUnknown = 0x80340000u;
@@ -1270,25 +1273,6 @@ public sealed class SparkplugIngestor
return; // A published metric nobody authored a tag for. Not an error — that is most of them.
}
// Arrays slip past the unsupported-type gate below, because ToDriverDataType maps every
// *Array variant to its ELEMENT type and is therefore never null for one. Design §3.5 defers
// array support, and the failure is not benign: the value rides in bytes_value as a byte[] at
// ValueKind.Scalar, so a numeric target throws its way to BadTypeMismatch (safe, wrong reason)
// while a String/Reference target reaches Convert.ToBase64String and publishes a packed binary
// buffer as a plausible string at GOOD quality. Gate on the array bit itself.
if (binding.DataType.IsSparkplugArray())
{
WarnOnce(
$"array-type:{key}",
"MQTT driver '{DriverId}': metric '{Metric}' on '{Scope}' is a Sparkplug array "
+ "({DataType}); array metrics are not supported in v1 and its tag(s) are not being fed.",
_driverId,
binding.Name,
scope,
binding.DataType);
return;
}
var birthType = binding.DataType.ToDriverDataType();
if (birthType is null)
{
@@ -1308,12 +1292,24 @@ public sealed class SparkplugIngestor
var serverUtc = _utcNow();
// An *Array metric (#754). ToDriverDataType maps every array variant to its ELEMENT type, so the
// birth type above is the element type and the array bit is read separately. The packed body is
// decoded ONCE per metric, not per tag: every tag bound to it sees the same vector or the same
// refusal. A scalar tag never gets this path's value — that used to publish the packed buffer as
// base64 at GOOD quality on a String tag; it is now BadTypeMismatch (see BuildSnapshot).
var isArrayMetric = binding.DataType.IsSparkplugArray();
var decoded = isArrayMetric ? DecodeArray(binding, metric) : default;
foreach (var def in defs)
{
// The authored dataType wins when the operator declared one; otherwise the birth's own
// declaration does. That is what lets a tag be authored with nothing but the metric tuple.
// For an array tag it is the ELEMENT type, exactly as the composer's DataType is.
var target = def.DataTypeAuthored ? def.DataType : birthType.Value;
if (BuildSnapshot(def, binding, metric, target, sourceUtc, serverUtc) is not { } snapshot)
var built = isArrayMetric
? BuildArraySnapshot(def, binding, metric, decoded, target, sourceUtc, serverUtc)
: BuildSnapshot(def, binding, metric, target, sourceUtc, serverUtc);
if (built is not { } snapshot)
{
continue;
}
@@ -1363,6 +1359,14 @@ public sealed class SparkplugIngestor
return null;
}
// A scalar metric on an ARRAY tag (#754): the node is ValueRank=1 and a scalar is not a value of
// it. Refused rather than wrapped in a one-element array — the shapes disagree, and guessing which
// side is right would hide an authoring error behind a Good value.
if (def.IsArray)
{
return ShapeMismatch(def, binding, stamp, serverUtc);
}
// THE call. Sparkplug carries signed integers as two's complement in an unsigned field, and a
// DATA metric carries no datatype of its own — only the birth binding knows which applies.
// Skipping this publishes 4294967254 for a value of -42: plausible, Good, and wrong.
@@ -1373,6 +1377,169 @@ public sealed class SparkplugIngestor
: BadTypeMismatch(def, binding, target, stamp, serverUtc);
}
/// <summary>The outcome of decoding one array metric's packed body, shared by every tag bound to it.</summary>
/// <param name="Elements">The decoded elements (wire-typed), or <see langword="null"/> when there are none.</param>
/// <param name="Malformed">Whether the metric carried a body that is not a well-formed vector.</param>
private readonly record struct DecodedArray(Array? Elements, bool Malformed);
/// <summary>
/// Decodes an <c>*Array</c> metric's packed <c>bytes_value</c> once, for every tag bound to it. A
/// value-less metric (null / absent / a non-bytes value) is not decoded here — the per-tag build reports
/// it with the same verdicts the scalar path reaches.
/// </summary>
private DecodedArray DecodeArray(SparkplugMetricBinding binding, SparkplugMetric metric)
{
if (metric.ValueKind != SparkplugValueKind.Scalar || metric.Value is not byte[] packed)
{
return default;
}
if (SparkplugArrayCodec.TryDecode(binding.DataType, packed, out var elements, out var error))
{
return new DecodedArray(elements, Malformed: false);
}
WarnOnce(
$"array-decode:{binding.Name}",
"MQTT driver '{DriverId}': array metric '{Metric}' ({DataType}) carried a malformed body ({Reason}); "
+ "its tag(s) read BadDecodingError until a well-formed value arrives.",
_driverId,
binding.Name,
binding.DataType,
error);
return new DecodedArray(null, Malformed: true);
}
/// <summary>
/// Turns one decoded array metric into a snapshot for one authored tag (#754): a 1-D array of the tag's
/// effective element type, all-or-nothing, or a Bad status that says why not. Returns
/// <see langword="null"/> when the metric carried no value at all, exactly as <see cref="BuildSnapshot"/>.
/// </summary>
private DataValueSnapshot? BuildArraySnapshot(
MqttTagDefinition def,
SparkplugMetricBinding binding,
SparkplugMetric metric,
DecodedArray decoded,
DriverDataType target,
DateTime? sourceUtc,
DateTime serverUtc)
{
var stamp = ToUtc(metric.TimestampMs) ?? sourceUtc;
switch (metric.ValueKind)
{
case SparkplugValueKind.Scalar:
break;
case SparkplugValueKind.Null:
return new DataValueSnapshot(null, StatusBadTypeMismatch, stamp, serverUtc);
default:
WarnOnce(
$"valuekind:{def.Name}",
"MQTT driver '{DriverId}': metric '{Metric}' for '{RawPath}' carried {ValueKind} rather "
+ "than a value; skipped.",
_driverId,
binding.Name,
def.Name,
metric.ValueKind);
return null;
}
// An array metric on a SCALAR tag: the node is ValueRank=Scalar, and no single element is "the" value.
if (!def.IsArray)
{
return ShapeMismatch(def, binding, stamp, serverUtc);
}
if (decoded.Malformed)
{
return new DataValueSnapshot(null, StatusBadDecodingError, stamp, serverUtc);
}
// A value that is not a packed body at all (an int_value on an Int32Array metric): it does not fit.
if (decoded.Elements is not { } elements)
{
return BadTypeMismatch(def, binding, target, stamp, serverUtc);
}
// A declared length is the node's ArrayDimensions; a vector of another length is not a value of that
// node. BadDecodingError, the verdict MTConnect gives a TIME_SERIES vector that disagrees with a fixed
// ArrayDim (#627). Null / 0 = variable length, any count fits.
if (def.ArrayLength is { } declared && declared > 0 && elements.Length != declared)
{
WarnOnce(
$"array-length:{def.Name}",
"MQTT driver '{DriverId}': array metric '{Metric}' carried {Count} element(s) but tag '{RawPath}' "
+ "declares arrayLength {Declared}; status BadDecodingError.",
_driverId,
binding.Name,
elements.Length,
def.Name,
declared);
return new DataValueSnapshot(null, StatusBadDecodingError, stamp, serverUtc);
}
if (ElementClrType(target) is not { } clrType)
{
return BadTypeMismatch(def, binding, target, stamp, serverUtc);
}
// Element by element through the SCALAR coercion, all-or-nothing: one element that does not fit the
// effective type refuses the whole vector (a partial array served as Good is a wrong value).
var result = Array.CreateInstance(clrType, elements.Length);
for (var i = 0; i < elements.Length; i++)
{
if (!SparkplugValueCoercion.TryCoerce(elements.GetValue(i), target, out var element))
{
return BadTypeMismatch(def, binding, target, stamp, serverUtc);
}
result.SetValue(element, i);
}
return new DataValueSnapshot(result, StatusGood, stamp, serverUtc);
}
/// <summary>
/// The CLR element type <see cref="SparkplugValueCoercion.TryCoerce"/> produces for
/// <paramref name="target"/> — the element type of the array a tag of that type is served as.
/// </summary>
private static Type? ElementClrType(DriverDataType target) => target switch
{
DriverDataType.Boolean => typeof(bool),
DriverDataType.Int16 => typeof(short),
DriverDataType.Int32 => typeof(int),
DriverDataType.Int64 => typeof(long),
DriverDataType.UInt16 => typeof(ushort),
DriverDataType.UInt32 => typeof(uint),
DriverDataType.UInt64 => typeof(ulong),
DriverDataType.Float32 => typeof(float),
DriverDataType.Float64 => typeof(double),
DriverDataType.String or DriverDataType.Reference => typeof(string),
DriverDataType.DateTime => typeof(DateTime),
_ => null,
};
/// <summary>
/// The metric's shape (array or scalar) disagrees with the tag's (<c>isArray</c>). Warned once per tag
/// with the fix, since this is always an authoring error, never a wire one.
/// </summary>
private DataValueSnapshot ShapeMismatch(
MqttTagDefinition def, SparkplugMetricBinding binding, DateTime? stamp, DateTime serverUtc)
{
WarnOnce(
$"shape:{def.Name}",
"MQTT driver '{DriverId}': metric '{Metric}' is a Sparkplug {DataType} but tag '{RawPath}' is "
+ "{TagShape}; status BadTypeMismatch. Make the tag's \"isArray\" match the metric.",
_driverId,
binding.Name,
binding.DataType,
def.Name,
def.IsArray ? "an array (isArray: true)" : "a scalar (no isArray)");
return new DataValueSnapshot(null, StatusBadTypeMismatch, stamp, serverUtc);
}
/// <summary>
/// Publishes each flattened member of a structured (<c>Template</c> / <c>DataSet</c>) metric as
/// the sibling metric <c>{parent}/{memberPath}</c>.
@@ -1380,7 +1547,7 @@ public sealed class SparkplugIngestor
/// <remarks>
/// <para>
/// <b>Each member is re-entered through <see cref="PublishMetric"/> as a scalar</b>, rather
/// than duplicating the coercion, array-gate and authored-tag fan-out here. A second copy of
/// than duplicating the coercion, array decode and authored-tag fan-out here. A second copy of
/// that logic would be free to drift — and the drift would be silent, since both paths
/// publish values that look plausible.
/// </para>