v3(b1-modbus): RawPath identity seam — RawTagEntry-driven Modbus driver

Wave-B EXEMPLAR. Retire the pre-declared/blob-parse tag model; the driver now
builds its RawPath -> definition table from the artifact's RawTagEntry set via a
pure mapper.

- Contracts: rename ModbusEquipmentTagParser -> ModbusTagDefinitionFactory;
  TryParse(reference) -> FromTagConfig(tagConfig, rawPath) (def.Name = rawPath,
  no leading-brace heuristic); add inverse ToTagConfig(def) serializer; keep all
  strict-enum reads + guards; also read stringByteOrder/deadband/coalesceProhibited
  so a RawTagEntry round-trips the full authored def. Inspect() unchanged.
- Options: Tags(IReadOnlyList<ModbusTagDefinition>) -> RawTags(IReadOnlyList<RawTagEntry>).
- Driver: _tagsByName -> _tagsByRawPath (Ordinal); resolver byRawPath-only; build
  the table from RawTags at Initialize threading entry.WriteIdempotent onto each def;
  Discover/Teardown updated.
- Factory: remove ModbusTagDto/BuildTag/ValidateStringLength + ConfigDto.Tags; bind
  RawTags from driver-config JSON.
- CLI ModbusCommandBase.BuildOptions: serialise typed defs -> RawTagEntry via ToTagConfig.
- Tests: migrate Tags= -> RawTags via ModbusRawTags.Entries helper; parser tests ->
  FromTagConfig(rawPath); factory String-length/enum tests re-seated on the mapper seam.
- Propagated rename to ControlPlane EquipmentTagConfigInspector (outside Modbus projects).

Modbus.Tests 315/315, Addressing.Tests 161/161, Cli.Tests 72/72 green.
Docker-gated Driver.Modbus.IntegrationTests left untouched (won't compile against
the new API; expected).
This commit is contained in:
Joseph Doherty
2026-07-15 19:50:10 -04:00
parent 906800abc0
commit aafb9d4929
27 changed files with 362 additions and 362 deletions
@@ -1,11 +1,13 @@
using System.ComponentModel.DataAnnotations;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>
/// Modbus TCP driver configuration. Bound from the driver's <c>DriverConfig</c> JSON at
/// <c>DriverHost.RegisterAsync</c>. Every register the driver exposes appears in
/// <see cref="Tags"/>; names become the OPC UA browse name + full reference.
/// <c>DriverHost.RegisterAsync</c>. The tags the driver serves are delivered as authored raw
/// tags in <see cref="RawTags"/>; the driver maps each through
/// <see cref="ModbusTagDefinitionFactory.FromTagConfig"/> to build its RawPath → definition table.
/// </summary>
public sealed class ModbusDriverOptions
{
@@ -18,8 +20,14 @@ public sealed class ModbusDriverOptions
/// <summary>Gets the communication timeout duration.</summary>
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(2);
/// <summary>Pre-declared tag map. Modbus has no discovery protocol — the driver returns exactly these.</summary>
public IReadOnlyList<ModbusTagDefinition> Tags { get; init; } = [];
/// <summary>
/// Authored raw tags this driver serves. The deploy artifact hands each authored raw
/// <c>Tag</c> as a <see cref="RawTagEntry"/> (RawPath identity + driver <c>TagConfig</c> blob +
/// WriteIdempotent flag); the driver maps each through
/// <see cref="ModbusTagDefinitionFactory.FromTagConfig"/> into its RawPath → definition table.
/// Modbus has no discovery protocol — the driver serves exactly these.
/// </summary>
public IReadOnlyList<RawTagEntry> RawTags { get; init; } = [];
/// <summary>
/// Background connectivity-probe settings. When <see cref="ModbusProbeOptions.Enabled"/>
@@ -1,26 +1,43 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>Parses an equipment tag's <c>TagConfig</c> JSON (the shape authored by the AdminUI
/// <c>ModbusTagConfigModel</c>) into a transient <see cref="ModbusTagDefinition"/> whose
/// <see cref="ModbusTagDefinition.Name"/> equals the reference string itself, so a value the
/// driver publishes back keys the runtime's forward router correctly.</summary>
public static class ModbusEquipmentTagParser
/// <summary>
/// v3 pure mapper: turns an authored raw tag's <c>TagConfig</c> JSON (the shape produced by the
/// AdminUI <c>ModbusTagConfigModel</c>) into a <see cref="ModbusTagDefinition"/>. Under v3 a tag's
/// identity is its <b>RawPath</b> (a cluster-scoped slash path), not the address blob — so the
/// produced definition's <see cref="ModbusTagDefinition.Name"/> is the RawPath the driver was handed,
/// which is exactly the wire reference the driver's <c>RawPath → def</c> resolver keys on. The driver
/// builds that table by mapping each <see cref="RawTagEntry"/> the deploy artifact delivers through
/// <see cref="FromTagConfig"/>; <see cref="ToTagConfig"/> is the inverse, used by authoring paths (the
/// Client CLI) that hold a typed definition and need to synthesise the <c>TagConfig</c> blob for a
/// <see cref="RawTagEntry"/>.
/// </summary>
public static class ModbusTagDefinitionFactory
{
/// <summary>Attempts to parse an equipment-tag reference into a transient definition.</summary>
/// <param name="reference">The equipment tag's TagConfig JSON (also used as the def identity).</param>
/// <param name="def">The transient definition when parsing succeeds.</param>
/// <returns><see langword="true"/> when <paramref name="reference"/> is a Modbus address object.</returns>
public static bool TryParse(string reference, out ModbusTagDefinition def)
/// <summary>
/// Maps an authored <c>TagConfig</c> object to a typed definition keyed by <paramref name="rawPath"/>.
/// The input is always an authored TagConfig JSON object (there is no name-vs-blob heuristic in v3).
/// Enum fields (<c>region</c> / <c>dataType</c> / <c>byteOrder</c> / <c>stringByteOrder</c>) are read
/// STRICTLY — a present-but-invalid (typo'd) value rejects the whole tag (returns
/// <see langword="false"/> ⇒ the driver surfaces <c>BadNodeIdUnknown</c>) rather than silently
/// defaulting to a wrong-width Good. <see cref="ModbusTagDefinition.WriteIdempotent"/> is NOT read
/// from the blob — it is a platform flag the caller threads in from the tag's
/// <see cref="RawTagEntry.WriteIdempotent"/>.
/// </summary>
/// <param name="tagConfig">The authored equipment-tag TagConfig JSON.</param>
/// <param name="rawPath">The tag's RawPath — becomes the definition's identity (<c>Name</c>).</param>
/// <param name="def">The mapped definition when this returns <see langword="true"/>.</param>
/// <returns><see langword="true"/> when <paramref name="tagConfig"/> is a valid Modbus address object.</returns>
public static bool FromTagConfig(string tagConfig, string rawPath, out ModbusTagDefinition def)
{
def = null!;
// Authored tag names never start with '{' (AdminUI name validation), so a leading brace marks an equipment-tag TagConfig blob.
if (string.IsNullOrWhiteSpace(reference) || reference[0] != '{') return false;
if (string.IsNullOrWhiteSpace(tagConfig)) return false;
try
{
using var doc = JsonDocument.Parse(reference);
using var doc = JsonDocument.Parse(tagConfig);
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object
|| !root.TryGetProperty("region", out _)
@@ -35,13 +52,13 @@ public static class ModbusEquipmentTagParser
if (!TagConfigJson.TryReadEnumStrict(root, "region", ModbusRegion.HoldingRegisters, out var region)) return false;
if (!TagConfigJson.TryReadEnumStrict(root, "dataType", ModbusDataType.Int16, out var dataType)) return false;
if (!TagConfigJson.TryReadEnumStrict(root, "byteOrder", ModbusByteOrder.BigEndian, out var byteOrder)) return false;
if (!TagConfigJson.TryReadEnumStrict(root, "stringByteOrder", ModbusStringByteOrder.HighByteFirst, out var stringByteOrder)) return false;
var bitIndex = (byte)ReadInt(root, "bitIndex");
var stringLength = (ushort)ReadInt(root, "stringLength");
// Guard: String tags require StringLength >= 1. RegisterCount = (StringLength+1)/2,
// so StringLength=0 → 0 registers → spec-illegal FC03/FC04 with quantity=0 → PLC
// returns exception 03. Reject here (analogous to ValidateStringLength
// in the pre-declared tag path) so the driver surfaces BadNodeIdUnknown rather than a
// misleading BadCommunicationError.
// returns exception 03. Reject here so the driver surfaces BadNodeIdUnknown rather
// than a misleading BadCommunicationError.
if (dataType == ModbusDataType.String && stringLength < 1) return false;
// Guard: BitInRegister tags require BitIndex 015. Shift by ≥ 16 on an int overflows
// a ushort mask silently — reads always return false, writes have no effect.
@@ -59,12 +76,17 @@ public static class ModbusEquipmentTagParser
var writable = TagConfigJson.ReadWritable(root);
// CONV-4: optional per-tag unitId (0255). Absent ⇒ null ⇒ the driver-level UnitId via
// ModbusDriver.ResolveUnitId, so multi-unit equipment tags key their own per-host breaker.
// Scope: unitId ONLY — the remaining parser-strictness gaps are R2-11's.
var unitId = ReadOptionalByte(root, "unitId");
// Optional per-tag encoding/planner knobs — carried on the def so a RawTagEntry round-trips
// the full authored definition (these have no AdminUI editor field yet; absent ⇒ default).
var deadband = ReadOptionalDouble(root, "deadband");
var coalesceProhibited = ReadBool(root, "coalesceProhibited");
def = new ModbusTagDefinition(
Name: reference, Region: region, Address: (ushort)address, DataType: dataType,
Name: rawPath, Region: region, Address: (ushort)address, DataType: dataType,
Writable: writable, ByteOrder: byteOrder, BitIndex: bitIndex, StringLength: stringLength,
ArrayCount: arrayCount, UnitId: unitId);
StringByteOrder: stringByteOrder, WriteIdempotent: false,
ArrayCount: arrayCount, Deadband: deadband, UnitId: unitId,
CoalesceProhibited: coalesceProhibited);
return true;
}
catch (JsonException) { return false; }
@@ -72,6 +94,41 @@ public static class ModbusEquipmentTagParser
catch (InvalidOperationException) { return false; }
}
/// <summary>
/// Inverse of <see cref="FromTagConfig"/>: serialises a typed definition back to the camelCase
/// <c>TagConfig</c> JSON the mapper reads. Used by authoring paths (the Client CLI) that construct a
/// <see cref="ModbusTagDefinition"/> from operator flags and need the <c>TagConfig</c> string to hand
/// the driver as a <see cref="RawTagEntry"/>. Enum values are written as their name strings; optional
/// fields are emitted only when non-default so the blob stays minimal. <c>WriteIdempotent</c> is NOT
/// emitted — it travels on the <see cref="RawTagEntry"/>, not inside the blob.
/// </summary>
/// <param name="def">The definition to serialise.</param>
/// <returns>The camelCase TagConfig JSON string.</returns>
public static string ToTagConfig(ModbusTagDefinition def)
{
ArgumentNullException.ThrowIfNull(def);
var o = new JsonObject
{
["region"] = def.Region.ToString(),
["address"] = def.Address,
["dataType"] = def.DataType.ToString(),
["byteOrder"] = def.ByteOrder.ToString(),
["bitIndex"] = def.BitIndex,
["stringLength"] = def.StringLength,
["stringByteOrder"] = def.StringByteOrder.ToString(),
["writable"] = def.Writable,
};
if (def.ArrayCount is { } count)
{
o["isArray"] = true;
o["arrayLength"] = count;
}
if (def.Deadband is { } deadband) o["deadband"] = deadband;
if (def.UnitId is { } unitId) o["unitId"] = unitId;
if (def.CoalesceProhibited) o["coalesceProhibited"] = true;
return o.ToJsonString();
}
/// <summary>
/// Deploy-time inspection of an equipment-tag <c>TagConfig</c> blob (05/CONV-2). Returns
/// human-readable warnings for present-but-invalid enum values (<c>region</c> / <c>dataType</c> /
@@ -119,6 +176,10 @@ public static class ModbusEquipmentTagParser
=> o.TryGetProperty(name, out var e) && e.ValueKind == JsonValueKind.Number
&& e.TryGetInt32(out var v) && v is >= 0 and <= 255 ? (byte)v : null;
private static double? ReadOptionalDouble(JsonElement o, string name)
=> o.TryGetProperty(name, out var e) && e.ValueKind == JsonValueKind.Number
&& e.TryGetDouble(out var v) ? v : null;
private static bool ReadBool(JsonElement o, string name)
=> o.TryGetProperty(name, out var e) && e.ValueKind == JsonValueKind.True;
}