test(mqtt): C# Sparkplug edge-node simulator + §3.6 live matrix
Adds a project-owned, controllable Sparkplug B edge node (SparkplugEdgeNode) that
encodes with the SAME generated Tahu schema the driver decodes with — so the live
gate checks encode/decode symmetry rather than the driver against itself — and
drives the §3.6 matrix end-to-end over the real TLS+auth Mosquitto fixture.
The simulator frames its topics independently of SparkplugTopic.Format: a
simulator borrowing the parser's formatter could not detect a bug in it, because
both sides of the comparison would be wrong together. It registers a real NDEATH
Last Will at CONNECT, restarts seq at 0 on NBIRTH, publishes DATA metrics as
alias-only, carries bdSeq per session, and encodes signed ints as two's
complement in the unsigned proto field.
SparkplugLiveTests (Category=LiveIntegration, env-gated, skip-clean) covers:
birth -> alias-only data -> OnDataChange under the RawPath; late-join rebirth
NCMD honoured by an independent decoder; alias reuse across a rebirth routing by
metric NAME; a stale-bdSeq NDEATH ignored while the current one stales; the real
broker-published Will staling and the next birth restoring; seq wrap 255->0
requesting no rebirth while a deliberate gap does; and the browser's passive
window asserted ON THE WIRE (a third client watching spBv1.0/{group}/NCMD/#),
plus RequestRebirthAsync node-vs-group enumeration.
Two things make the suite falsifiable rather than decorative: the seq-wrap test
builds its ingestor with rebirthDebounce: TimeSpan.Zero (at the shipped 10s
default a wrap-triggered NCMD would be swallowed and the test would pass for the
wrong reason) and pairs the silence with a deliberate gap that must produce one;
and the passivity assertion observes the broker rather than the session's own
publish counter, which can only see the seam it guards.
Docker/docker-compose.yml gains a profile-gated `sparkplug-sim` service running
the same engine standalone against the same broker (TLS, CA-pinned) — a manual
driving aid for the AdminUI picker, deliberately NOT a test dependency, since the
matrix needs an edge node it can command mid-test. Its app directory is publish
output (publish-simulator.sh), gitignored like secrets/.
Offline: 15 skipped, 0 failed with no env set. Live: 15/15 passed against
10.100.0.35:8883. Falsifiability spot-check: mutating AliasTable.RebuildFromBirth
to merge instead of replace, and neutering SparkplugCodec.ReinterpretSigned for
Int32, turned exactly the two corresponding tests red and nothing else; both
mutations reverted.
Claude-Session: https://claude.ai/code/session_01GASWkNEi68FSCtvr6rLoEW
This commit is contained in:
+114
@@ -0,0 +1,114 @@
|
||||
using Org.Eclipse.Tahu.Protobuf;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Mqtt.SparkplugSimulator;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Standalone entry point for the `sparkplug-sim` fixture container.
|
||||
//
|
||||
// Runs one or more simulated edge nodes against the fixture broker, forever: NBIRTH + DBIRTH once,
|
||||
// then N/DDATA on a cadence, honouring rebirth NCMDs throughout. It exists so an operator (and Task
|
||||
// 26's AdminUI `/run` verification) has a live Sparkplug plant to browse, NOT so the live tests have
|
||||
// one — those drive `SparkplugEdgeNode` in process, because the §3.6 matrix needs an edge node it
|
||||
// can command mid-test.
|
||||
//
|
||||
// Every setting comes from the environment; nothing is defaulted to a credential.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
var host = Env("MQTT_SIM_HOST", "mosquitto");
|
||||
var port = int.TryParse(Env("MQTT_SIM_PORT", "8883"), out var p) ? p : 8883;
|
||||
var useTls = !string.Equals(Env("MQTT_SIM_USE_TLS", "true"), "false", StringComparison.OrdinalIgnoreCase);
|
||||
var group = Env("MQTT_SIM_GROUP", "OtOpcUaSim");
|
||||
var nodes = Env("MQTT_SIM_NODES", "EdgeA,EdgeB").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
var interval = int.TryParse(Env("MQTT_SIM_INTERVAL_SECONDS", "2"), out var i) && i > 0 ? i : 2;
|
||||
|
||||
var username = Environment.GetEnvironmentVariable("MQTT_FIXTURE_USERNAME");
|
||||
var password = Environment.GetEnvironmentVariable("MQTT_FIXTURE_PASSWORD");
|
||||
var caPath = Environment.GetEnvironmentVariable("MQTT_SIM_CA_CERT");
|
||||
var allowUntrusted = string.Equals(Env("MQTT_SIM_ALLOW_UNTRUSTED", "false"), "true", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (string.IsNullOrEmpty(password))
|
||||
{
|
||||
// Same fail-loud posture as the compose file's `${VAR:?}` guards: the broker runs
|
||||
// allow_anonymous=false, so a blank password would produce an unexplained connect refusal.
|
||||
Console.Error.WriteLine(
|
||||
"sparkplug-sim: MQTT_FIXTURE_PASSWORD is not set. The fixture broker runs allow_anonymous=false; "
|
||||
+ "supply the password gen-fixture-material.sh was run with.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
using var stopping = new CancellationTokenSource();
|
||||
Console.CancelKeyPress += (_, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
stopping.Cancel();
|
||||
};
|
||||
AppDomain.CurrentDomain.ProcessExit += (_, _) => stopping.Cancel();
|
||||
|
||||
Console.WriteLine(
|
||||
$"sparkplug-sim: broker={host}:{port} tls={useTls} group={group} nodes=[{string.Join(", ", nodes)}] "
|
||||
+ $"interval={interval}s");
|
||||
|
||||
var running = new List<Task>();
|
||||
var edges = new List<SparkplugEdgeNode>();
|
||||
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
var edge = new SparkplugEdgeNode(
|
||||
new SparkplugEdgeNodeOptions
|
||||
{
|
||||
Host = host,
|
||||
Port = port,
|
||||
UseTls = useTls,
|
||||
CaCertificatePath = caPath,
|
||||
AllowUntrustedServerCertificate = allowUntrusted,
|
||||
Username = username,
|
||||
Password = password,
|
||||
GroupId = group,
|
||||
EdgeNodeId = node,
|
||||
},
|
||||
Console.WriteLine);
|
||||
|
||||
// A small but genuinely heterogeneous catalog: a float, a double, a NEGATIVE int32 (the two's
|
||||
// complement case), a bool and a string — plus one device, so the picker's
|
||||
// Group → EdgeNode → Device → Metric tree has every level populated.
|
||||
edge.SetNodeMetrics(
|
||||
new SparkplugMetricSeed("Temperature", 1, DataType.Float, 21.5f),
|
||||
new SparkplugMetricSeed("Pressure", 2, DataType.Double, 101.325d),
|
||||
new SparkplugMetricSeed("Count", 3, DataType.Int32, -42),
|
||||
new SparkplugMetricSeed("Running", 4, DataType.Boolean, true),
|
||||
new SparkplugMetricSeed("Serial", 5, DataType.String, $"{node}-001"));
|
||||
|
||||
edge.SetDeviceMetrics(
|
||||
"Filler1",
|
||||
new SparkplugMetricSeed("Temperature", 10, DataType.Float, 55.5f),
|
||||
new SparkplugMetricSeed("FillCount", 11, DataType.Int64, 1000L),
|
||||
new SparkplugMetricSeed("Jammed", 12, DataType.Boolean, false));
|
||||
|
||||
edges.Add(edge);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var edge in edges)
|
||||
{
|
||||
await edge.ConnectAsync(stopping.Token);
|
||||
running.Add(edge.RunAsync(TimeSpan.FromSeconds(interval), stopping.Token));
|
||||
}
|
||||
|
||||
await Task.WhenAll(running);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Console.WriteLine("sparkplug-sim: stopping.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var edge in edges)
|
||||
{
|
||||
await edge.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
static string Env(string name, string fallback) =>
|
||||
Environment.GetEnvironmentVariable(name) is { Length: > 0 } value ? value : fallback;
|
||||
Reference in New Issue
Block a user