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,5 +1,6 @@
using CliFx.Attributes;
using CliFx.Exceptions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Cli.Common;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Cli;
@@ -43,9 +44,12 @@ public abstract class ModbusCommandBase : DriverCommandBase
/// <summary>
/// Construct a <see cref="ModbusDriverOptions"/> with the endpoint fields this base
/// collected + whatever <paramref name="tags"/> the subclass declares. Probe is
/// disabled — CLI runs are one-shot, the probe loop would race the operator's
/// command against its own keep-alive reads.
/// collected + whatever <paramref name="tags"/> the subclass declares. The CLI holds typed
/// definitions (synthesised from operator flags), so each is serialised back to a
/// <see cref="RawTagEntry"/> — the v3 delivery unit — via
/// <see cref="ModbusTagDefinitionFactory.ToTagConfig"/>, keyed by the def's synthesised name as
/// its RawPath. Probe is disabled — CLI runs are one-shot, the probe loop would race the
/// operator's command against its own keep-alive reads.
/// </summary>
/// <param name="tags">The tag definitions to include in the options.</param>
/// <returns>A <see cref="ModbusDriverOptions"/> ready to hand to the driver constructor.</returns>
@@ -56,7 +60,7 @@ public abstract class ModbusCommandBase : DriverCommandBase
UnitId = UnitId,
Timeout = Timeout,
AutoReconnect = !DisableAutoReconnect,
Tags = tags,
RawTags = [.. tags.Select(t => new RawTagEntry(t.Name, ModbusTagDefinitionFactory.ToTagConfig(t), t.WriteIdempotent))],
Probe = new ModbusProbeOptions { Enabled = false },
};
@@ -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;
}
@@ -32,11 +32,12 @@ public sealed class ModbusDriver
// the reader + on-change bridge; the engine owns the loop, interval floor, and lifecycle.
private readonly PollGroupEngine _poll;
private readonly Dictionary<string, ModbusTagDefinition> _tagsByName = new(StringComparer.OrdinalIgnoreCase);
// v3 authored-tag table, keyed by RawPath (the tag identity + driver wire reference). RawPath is
// case-sensitive ordinal. Built in InitializeAsync from _options.RawTags via the pure mapper.
private readonly Dictionary<string, ModbusTagDefinition> _tagsByRawPath = new(StringComparer.Ordinal);
// Resolves a read/write/subscribe fullReference to a tag definition, bridging the two
// authoring models: an authored tag-table entry (by name) OR an equipment tag whose
// reference is its raw TagConfig JSON (parsed once via ModbusEquipmentTagParser, cached).
// Resolves a read/write/subscribe RawPath reference to its tag definition via a single hit on the
// authored _tagsByRawPath table (v3: the reference is always a RawPath; a miss is a miss).
private readonly EquipmentTagRefResolver<ModbusTagDefinition> _resolver;
// Last-published value per tag, keyed by FullReference. Used by ShouldPublish to apply
@@ -104,8 +105,7 @@ public sealed class ModbusDriver
_driverInstanceId = driverInstanceId;
_logger = logger ?? NullLogger<ModbusDriver>.Instance;
_resolver = new EquipmentTagRefResolver<ModbusTagDefinition>(
r => _tagsByName.TryGetValue(r, out var t) ? t : null,
r => ModbusEquipmentTagParser.TryParse(r, out var d) ? d : null);
r => _tagsByRawPath.TryGetValue(r, out var t) ? t : null);
_transportFactory = transportFactory
?? (o => new ModbusTcpTransport(
o.Host, o.Port, o.Timeout, o.AutoReconnect,
@@ -199,7 +199,19 @@ public sealed class ModbusDriver
{
_transport = _transportFactory(_options);
await _transport.ConnectAsync(cancellationToken).ConfigureAwait(false);
foreach (var t in _options.Tags) _tagsByName[t.Name] = t;
// Build the RawPath → definition table from the authored raw tags. Each entry's TagConfig
// blob is mapped by the pure factory; the entry's WriteIdempotent flag is threaded onto the
// def (it lives on the RawTagEntry, not inside the blob). A mapper miss is skipped (logged),
// never thrown — a bad tag must not fail the whole driver init.
foreach (var entry in _options.RawTags)
{
if (ModbusTagDefinitionFactory.FromTagConfig(entry.TagConfig, entry.RawPath, out var def))
_tagsByRawPath[entry.RawPath] = def with { WriteIdempotent = entry.WriteIdempotent };
else
_logger.LogWarning(
"Modbus tag config did not map to a definition; skipping. Driver={DriverInstanceId} RawPath={RawPath}",
_driverInstanceId, entry.RawPath);
}
WriteHealth(new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null));
// PR 23: kick off the probe loop once the transport is up. Initial state stays
@@ -269,7 +281,9 @@ public sealed class ModbusDriver
{
ArgumentNullException.ThrowIfNull(builder);
var folder = builder.Folder("Modbus", "Modbus");
foreach (var t in _options.Tags)
// Surface the authored raw tags (mapped into the RawPath → def table at Initialize). The def's
// Name is the RawPath, used for both the browse name and the driver FullName.
foreach (var t in _tagsByRawPath.Values)
{
folder.Variable(t.Name, t.Name, new DriverAttributeInfo(
FullName: t.Name,
@@ -1604,8 +1618,8 @@ public sealed class ModbusDriver
_reprobeCts?.Dispose();
_reprobeCts = null;
_tagsByName.Clear();
_resolver.Clear(); // drop transient equipment-tag parses so a config change re-parses
_tagsByRawPath.Clear();
_resolver.Clear(); // no-op in v3 (the resolver reads the live table by closure); kept for symmetry
_lastPublishedByRef.Clear();
lock (_lastWrittenLock) _lastWrittenByRef.Clear();
lock (_autoProhibitedLock) _autoProhibited.Clear();
@@ -1,6 +1,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
@@ -75,14 +76,11 @@ public static class ModbusDriverFactoryExtensions
: ParseEnum<MelsecFamily>(dto.MelsecSubFamily, "<driver-level>", driverInstanceId, "MelsecSubFamily"),
AutoProhibitReprobeInterval = dto.AutoProhibitReprobeMs is { } reprobeMs ? TimeSpan.FromMilliseconds(reprobeMs) : null,
AutoReconnect = dto.AutoReconnect ?? true,
Tags = dto.Tags is { Count: > 0 }
? [.. dto.Tags.Select(t => BuildTag(
t, driverInstanceId,
dto.Family is null ? ModbusFamily.Generic
: ParseEnum<ModbusFamily>(dto.Family, "<driver-level>", driverInstanceId, "Family"),
dto.MelsecSubFamily is null ? MelsecFamily.Q_L_iQR
: ParseEnum<MelsecFamily>(dto.MelsecSubFamily, "<driver-level>", driverInstanceId, "MelsecSubFamily")))]
: [],
// v3: the deploy artifact (Wave C) populates rawTags with the cluster's authored raw Modbus
// tags. The driver maps each RawTagEntry's TagConfig blob through ModbusTagDefinitionFactory
// at Initialize; the legacy pre-declared DTO tag path (structured/AddressString → BuildTag)
// is retired.
RawTags = dto.RawTags is { Count: > 0 } ? [.. dto.RawTags] : [],
Probe = new ModbusProbeOptions
{
Enabled = dto.Probe?.Enabled ?? true,
@@ -112,82 +110,6 @@ public static class ModbusDriverFactoryExtensions
logger: loggerFactory?.CreateLogger<ModbusDriver>());
}
private static ModbusTagDefinition BuildTag(ModbusTagDto t, string driverInstanceId)
=> BuildTag(t, driverInstanceId, ModbusFamily.Generic, MelsecFamily.Q_L_iQR);
private static ModbusTagDefinition BuildTag(ModbusTagDto t, string driverInstanceId, ModbusFamily family, MelsecFamily melsecSubFamily)
{
var name = t.Name ?? throw new InvalidOperationException(
$"Modbus config for '{driverInstanceId}' has a tag missing Name");
// AddressString takes precedence over the structured fields (Region/Address/DataType/
// ByteOrder/BitIndex/StringLength/ArrayCount). Tags can mix forms freely — newer pasted
// rows use the grammar string, legacy rows keep the structured form. Fields not derivable
// from the grammar (Writable, WriteIdempotent, StringByteOrder) always come from the DTO.
ModbusTagDefinition tag;
if (!string.IsNullOrWhiteSpace(t.AddressString))
{
if (!ModbusAddressParser.TryParse(t.AddressString, family, melsecSubFamily, out var parsed, out var parseError))
throw new InvalidOperationException(
$"Modbus tag '{name}' in '{driverInstanceId}' has invalid AddressString '{t.AddressString}': {parseError}");
tag = new ModbusTagDefinition(
Name: name,
Region: parsed!.Region,
Address: parsed.Offset,
DataType: parsed.DataType,
Writable: t.Writable ?? true,
ByteOrder: parsed.ByteOrder,
BitIndex: parsed.Bit ?? 0,
StringLength: parsed.StringLength,
StringByteOrder: t.StringByteOrder is null
? ModbusStringByteOrder.HighByteFirst
: ParseEnum<ModbusStringByteOrder>(t.StringByteOrder, name, driverInstanceId, "StringByteOrder"),
WriteIdempotent: t.WriteIdempotent ?? false,
ArrayCount: parsed.ArrayCount,
Deadband: t.Deadband,
UnitId: t.UnitId);
}
else
{
tag = new ModbusTagDefinition(
Name: name,
Region: ParseEnum<ModbusRegion>(t.Region, t.Name, driverInstanceId, "Region"),
Address: t.Address ?? throw new InvalidOperationException(
$"Modbus tag '{t.Name}' in '{driverInstanceId}' missing Address"),
DataType: ParseEnum<ModbusDataType>(t.DataType, t.Name, driverInstanceId, "DataType"),
Writable: t.Writable ?? true,
ByteOrder: t.ByteOrder is null
? ModbusByteOrder.BigEndian
: ParseEnum<ModbusByteOrder>(t.ByteOrder, t.Name, driverInstanceId, "ByteOrder"),
BitIndex: t.BitIndex ?? 0,
StringLength: t.StringLength ?? 0,
StringByteOrder: t.StringByteOrder is null
? ModbusStringByteOrder.HighByteFirst
: ParseEnum<ModbusStringByteOrder>(t.StringByteOrder, t.Name, driverInstanceId, "StringByteOrder"),
WriteIdempotent: t.WriteIdempotent ?? false,
ArrayCount: t.ArrayCount,
Deadband: t.Deadband,
UnitId: t.UnitId);
}
ValidateStringLength(tag, driverInstanceId);
return tag;
}
/// <summary>
/// Rejects <c>StringLength = 0</c> for <c>String</c>-typed tags. The
/// driver computes <c>RegisterCount = (StringLength + 1) / 2</c> which would emit an
/// FC03/FC04 with <c>quantity = 0</c>, a spec-illegal request the PLC rejects with
/// exception 03 (Illegal Data Value). Surface as a clear bind-time error.
/// </summary>
private static void ValidateStringLength(ModbusTagDefinition tag, string driverInstanceId)
{
if (tag.DataType == ModbusDataType.String && tag.StringLength < 1)
throw new InvalidOperationException(
$"Modbus tag '{tag.Name}' in '{driverInstanceId}' has DataType=String but StringLength={tag.StringLength}. " +
$"String tags must declare StringLength >= 1 (the number of ASCII characters, packed 2 per register).");
}
private static T ParseEnum<T>(string? raw, string? tagName, string driverInstanceId, string field) where T : struct, Enum
{
if (string.IsNullOrWhiteSpace(raw))
@@ -241,8 +163,9 @@ public static class ModbusDriverFactoryExtensions
public int? AutoProhibitReprobeMs { get; init; }
/// <summary>Gets or sets a value indicating whether automatic reconnection is enabled.</summary>
public bool? AutoReconnect { get; init; }
/// <summary>Gets or sets the collection of tag definitions.</summary>
public List<ModbusTagDto>? Tags { get; init; }
/// <summary>Gets or sets the authored raw tags (RawPath + TagConfig blob + WriteIdempotent) the
/// deploy artifact delivers. The driver maps each through the tag-definition factory at Initialize.</summary>
public List<RawTagEntry>? RawTags { get; init; }
/// <summary>Gets or sets the probe configuration.</summary>
public ModbusProbeDto? Probe { get; init; }
@@ -276,45 +199,6 @@ public static class ModbusDriverFactoryExtensions
public double? BackoffMultiplier { get; init; }
}
internal sealed class ModbusTagDto
{
/// <summary>Gets or sets the tag name.</summary>
public string? Name { get; init; }
/// <summary>
/// Address grammar string per <c>ModbusAddressParser</c> — when present, takes
/// precedence over the structured Region/Address/DataType/ByteOrder/BitIndex/
/// StringLength/ArrayCount fields. Examples: <c>"40001"</c>, <c>"40001:F"</c>,
/// <c>"40001:F:CDAB:5"</c>, <c>"HR1:I"</c>, <c>"C100"</c>.
/// </summary>
public string? AddressString { get; init; }
/// <summary>Gets or sets the register region.</summary>
public string? Region { get; init; }
/// <summary>Gets or sets the starting address.</summary>
public ushort? Address { get; init; }
/// <summary>Gets or sets the data type.</summary>
public string? DataType { get; init; }
/// <summary>Gets or sets a value indicating whether the tag is writable.</summary>
public bool? Writable { get; init; }
/// <summary>Gets or sets the byte order.</summary>
public string? ByteOrder { get; init; }
/// <summary>Gets or sets the bit index for bit-level tags.</summary>
public byte? BitIndex { get; init; }
/// <summary>Gets or sets the string length for string-typed tags.</summary>
public ushort? StringLength { get; init; }
/// <summary>Gets or sets the byte order for string values.</summary>
public string? StringByteOrder { get; init; }
/// <summary>Gets or sets a value indicating whether writes are idempotent.</summary>
public bool? WriteIdempotent { get; init; }
/// <summary>Gets or sets the array count for array-typed tags.</summary>
public int? ArrayCount { get; init; }
/// <summary>Gets or sets the deadband for change detection.</summary>
public double? Deadband { get; init; }
/// <summary>Gets or sets the unit identifier for this tag.</summary>
public byte? UnitId { get; init; }
}
internal sealed class ModbusProbeDto
{
/// <summary>Gets or sets a value indicating whether probing is enabled.</summary>