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:
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user