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:
@@ -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"/>
|
||||
|
||||
+80
-19
@@ -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 0–15. 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 (0–255). 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>
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ public static class EquipmentTagConfigInspector
|
||||
private static readonly IReadOnlyDictionary<string, Func<string, IReadOnlyList<string>>> Inspectors =
|
||||
new Dictionary<string, Func<string, IReadOnlyList<string>>>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Modbus"] = ModbusEquipmentTagParser.Inspect,
|
||||
["Modbus"] = ModbusTagDefinitionFactory.Inspect,
|
||||
["S7"] = S7EquipmentTagParser.Inspect,
|
||||
["AbCip"] = AbCipEquipmentTagParser.Inspect,
|
||||
["AbLegacy"] = AbLegacyEquipmentTagParser.Inspect,
|
||||
|
||||
+8
-4
@@ -92,9 +92,9 @@ public sealed class ModbusCommandBaseTests
|
||||
options.UnitId.ShouldBe((byte)17);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that BuildOptions forwards the tag list verbatim.</summary>
|
||||
/// <summary>Verifies that BuildOptions serialises each typed tag into a RawTagEntry (RawPath = name).</summary>
|
||||
[Fact]
|
||||
public void BuildOptions_forwards_tag_list_verbatim()
|
||||
public void BuildOptions_serialises_tags_into_raw_tag_entries()
|
||||
{
|
||||
var sut = new ProbeOnly { Host = "h" };
|
||||
var tag = new ModbusTagDefinition(
|
||||
@@ -102,8 +102,12 @@ public sealed class ModbusCommandBaseTests
|
||||
|
||||
var options = sut.Invoke([tag]);
|
||||
|
||||
options.Tags.Count.ShouldBe(1);
|
||||
options.Tags[0].ShouldBeSameAs(tag);
|
||||
options.RawTags.Count.ShouldBe(1);
|
||||
options.RawTags[0].RawPath.ShouldBe("T");
|
||||
// The blob the driver's factory reads round-trips back to the same definition.
|
||||
ModbusTagDefinitionFactory.FromTagConfig(options.RawTags[0].TagConfig, "T", out var def).ShouldBeTrue();
|
||||
def.Region.ShouldBe(ModbusRegion.HoldingRegisters);
|
||||
def.DataType.ShouldBe(ModbusDataType.UInt16);
|
||||
}
|
||||
|
||||
// --- Driver.Modbus.Cli-003: parse-time endpoint validation -------------------------------
|
||||
|
||||
@@ -16,7 +16,7 @@ public sealed class ModbusArrayTests
|
||||
private static (ModbusDriver driver, ModbusDriverTests.FakeTransport fake) NewDriver(params ModbusTagDefinition[] tags)
|
||||
{
|
||||
var fake = new ModbusDriverTests.FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = tags };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries(tags)};
|
||||
var drv = new ModbusDriver(opts, "modbus-array", _ => fake);
|
||||
return (drv, fake);
|
||||
}
|
||||
@@ -274,14 +274,14 @@ public sealed class ModbusArrayTests
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":20,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":true,"arrayLength":3}""";
|
||||
var fake = new ModbusDriverTests.FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [] };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry("cell/modbus/arr20", json, false)] };
|
||||
var drv = new ModbusDriver(opts, "modbus-eq-arr", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
fake.HoldingRegisters[20] = 100;
|
||||
fake.HoldingRegisters[21] = 200;
|
||||
fake.HoldingRegisters[22] = 300;
|
||||
|
||||
var r = await drv.ReadAsync([json], CancellationToken.None);
|
||||
var r = await drv.ReadAsync(["cell/modbus/arr20"], CancellationToken.None);
|
||||
|
||||
r[0].StatusCode.ShouldBe(0u);
|
||||
var arr = r[0].Value.ShouldBeOfType<short[]>();
|
||||
@@ -297,12 +297,12 @@ public sealed class ModbusArrayTests
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":30,"dataType":"UInt16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0}""";
|
||||
var fake = new ModbusDriverTests.FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [] };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry("cell/modbus/scalar30", json, false)] };
|
||||
var drv = new ModbusDriver(opts, "modbus-eq-scalar", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
fake.HoldingRegisters[30] = 1234;
|
||||
|
||||
var r = await drv.ReadAsync([json], CancellationToken.None);
|
||||
var r = await drv.ReadAsync(["cell/modbus/scalar30"], CancellationToken.None);
|
||||
|
||||
r[0].StatusCode.ShouldBe(0u);
|
||||
r[0].Value.ShouldBe((ushort)1234);
|
||||
@@ -316,7 +316,7 @@ public sealed class ModbusArrayTests
|
||||
public void Equipment_Tag_Parser_Threads_ArrayLength_Into_ArrayCount()
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":true,"arrayLength":5}""";
|
||||
ModbusEquipmentTagParser.TryParse(json, out var def).ShouldBeTrue();
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/arr", out var def).ShouldBeTrue();
|
||||
def!.ArrayCount.ShouldBe(5);
|
||||
}
|
||||
|
||||
@@ -328,7 +328,7 @@ public sealed class ModbusArrayTests
|
||||
public void Equipment_Tag_Parser_No_ArrayLength_Leaves_ArrayCount_Null()
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0}""";
|
||||
ModbusEquipmentTagParser.TryParse(json, out var def).ShouldBeTrue();
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/arr", out var def).ShouldBeTrue();
|
||||
def!.ArrayCount.ShouldBeNull();
|
||||
}
|
||||
|
||||
@@ -345,7 +345,7 @@ public sealed class ModbusArrayTests
|
||||
{
|
||||
// isArray:false, arrayLength:8 → must be scalar (ArrayCount == null).
|
||||
var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":false,"arrayLength":8}""";
|
||||
ModbusEquipmentTagParser.TryParse(json, out var def).ShouldBeTrue();
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/arr", out var def).ShouldBeTrue();
|
||||
def!.ArrayCount.ShouldBeNull();
|
||||
}
|
||||
|
||||
@@ -359,12 +359,12 @@ public sealed class ModbusArrayTests
|
||||
// isArray:false, arrayLength:8 → scalar read; only register[40] is consumed.
|
||||
var json = """{"region":"HoldingRegisters","address":40,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":false,"arrayLength":8}""";
|
||||
var fake = new ModbusDriverTests.FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [] };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry("cell/modbus/c1scalar40", json, false)] };
|
||||
var drv = new ModbusDriver(opts, "modbus-c1-scalar", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
fake.HoldingRegisters[40] = 9999;
|
||||
|
||||
var r = await drv.ReadAsync([json], CancellationToken.None);
|
||||
var r = await drv.ReadAsync(["cell/modbus/c1scalar40"], CancellationToken.None);
|
||||
|
||||
r[0].StatusCode.ShouldBe(0u);
|
||||
// Must be a scalar short, NOT a short[].
|
||||
@@ -380,7 +380,7 @@ public sealed class ModbusArrayTests
|
||||
public void Parser_IsArrayTrue_ArrayLength1_Gives_ArrayCount_1()
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":true,"arrayLength":1}""";
|
||||
ModbusEquipmentTagParser.TryParse(json, out var def).ShouldBeTrue();
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/arr", out var def).ShouldBeTrue();
|
||||
def!.ArrayCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
@@ -393,12 +393,12 @@ public sealed class ModbusArrayTests
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":50,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"isArray":true,"arrayLength":1}""";
|
||||
var fake = new ModbusDriverTests.FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [] };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry("cell/modbus/c1arr50", json, false)] };
|
||||
var drv = new ModbusDriver(opts, "modbus-c1-arr1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
fake.HoldingRegisters[50] = 777;
|
||||
|
||||
var r = await drv.ReadAsync([json], CancellationToken.None);
|
||||
var r = await drv.ReadAsync(["cell/modbus/c1arr50"], CancellationToken.None);
|
||||
|
||||
r[0].StatusCode.ShouldBe(0u);
|
||||
// Must be a short[] of length 1, NOT a scalar short.
|
||||
|
||||
@@ -64,7 +64,7 @@ public sealed class ModbusBitRmwTests
|
||||
var opts = new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake",
|
||||
Tags = tags,
|
||||
RawTags = ModbusRawTags.Entries(tags),
|
||||
Probe = new ModbusProbeOptions { Enabled = false },
|
||||
};
|
||||
return (new ModbusDriver(opts, "modbus-1", _ => fake), fake);
|
||||
@@ -198,7 +198,7 @@ public sealed class ModbusBitRmwTests
|
||||
var opts = new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake",
|
||||
Tags = [new ModbusTagDefinition("Bit5", ModbusRegion.HoldingRegisters, 10, ModbusDataType.BitInRegister, BitIndex: 5)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("Bit5", ModbusRegion.HoldingRegisters, 10, ModbusDataType.BitInRegister, BitIndex: 5)]),
|
||||
Probe = new ModbusProbeOptions { Enabled = false },
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-rmw-trunc", _ => truncated);
|
||||
|
||||
@@ -66,7 +66,7 @@ public sealed class ModbusCapTests
|
||||
var tag = new ModbusTagDefinition("S", ModbusRegion.HoldingRegisters, 0, ModbusDataType.String,
|
||||
StringLength: 40); // 20 regs — fits in default cap (125).
|
||||
var transport = new RecordingTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
await using var drv = new ModbusDriver(opts, "modbus-1", _ => transport);
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
@@ -91,7 +91,7 @@ public sealed class ModbusCapTests
|
||||
var opts = new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake",
|
||||
Tags = [tag],
|
||||
RawTags = ModbusRawTags.Entries([tag]),
|
||||
MaxRegistersPerRead = 100,
|
||||
Probe = new ModbusProbeOptions { Enabled = false },
|
||||
};
|
||||
@@ -119,7 +119,7 @@ public sealed class ModbusCapTests
|
||||
var tag = new ModbusTagDefinition("MitString", ModbusRegion.HoldingRegisters, 0, ModbusDataType.String,
|
||||
StringLength: 200);
|
||||
var transport = new RecordingTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [tag], MaxRegistersPerRead = 64, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), MaxRegistersPerRead = 64, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
await using var drv = new ModbusDriver(opts, "modbus-1", _ => transport);
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
@@ -140,7 +140,7 @@ public sealed class ModbusCapTests
|
||||
var tag = new ModbusTagDefinition("LongStringWrite", ModbusRegion.HoldingRegisters, 0, ModbusDataType.String,
|
||||
StringLength: 220); // 110 regs.
|
||||
var transport = new RecordingTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [tag], MaxRegistersPerWrite = 100, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), MaxRegistersPerWrite = 100, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
await using var drv = new ModbusDriver(opts, "modbus-1", _ => transport);
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
@@ -161,7 +161,7 @@ public sealed class ModbusCapTests
|
||||
var tag = new ModbusTagDefinition("ShortStringWrite", ModbusRegion.HoldingRegisters, 0, ModbusDataType.String,
|
||||
StringLength: 40); // 20 regs.
|
||||
var transport = new RecordingTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [tag], MaxRegistersPerWrite = 100, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), MaxRegistersPerWrite = 100, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
await using var drv = new ModbusDriver(opts, "modbus-1", _ => transport);
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
|
||||
+6
-6
@@ -65,7 +65,7 @@ public sealed class ModbusCoalescingAutoRecoveryTests
|
||||
var t100 = new ModbusTagDefinition("T100", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t102 = new ModbusTagDefinition("T102", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t104 = new ModbusTagDefinition("T104", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t100, t102, t104], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t100, t102, t104]), MaxReadGap = 5,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -89,7 +89,7 @@ public sealed class ModbusCoalescingAutoRecoveryTests
|
||||
var t100 = new ModbusTagDefinition("T100", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t102 = new ModbusTagDefinition("T102", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t104 = new ModbusTagDefinition("T104", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t100, t102, t104], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t100, t102, t104]), MaxReadGap = 5,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -122,7 +122,7 @@ public sealed class ModbusCoalescingAutoRecoveryTests
|
||||
var t100 = new ModbusTagDefinition("T100", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t102 = new ModbusTagDefinition("T102", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t104 = new ModbusTagDefinition("T104", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t100, t102, t104], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t100, t102, t104]), MaxReadGap = 5,
|
||||
AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(100),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
@@ -149,7 +149,7 @@ public sealed class ModbusCoalescingAutoRecoveryTests
|
||||
var t100 = new ModbusTagDefinition("T100", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t102 = new ModbusTagDefinition("T102", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t104 = new ModbusTagDefinition("T104", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t100, t102, t104], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t100, t102, t104]), MaxReadGap = 5,
|
||||
AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(100),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
@@ -176,7 +176,7 @@ public sealed class ModbusCoalescingAutoRecoveryTests
|
||||
var t100 = new ModbusTagDefinition("T100", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t102 = new ModbusTagDefinition("T102", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t104 = new ModbusTagDefinition("T104", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", UnitId = 7, Tags = [t100, t102, t104], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", UnitId = 7, RawTags = ModbusRawTags.Entries([t100, t102, t104]), MaxReadGap = 5,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -211,7 +211,7 @@ public sealed class ModbusCoalescingAutoRecoveryTests
|
||||
var t104 = new ModbusTagDefinition("T104", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var t200 = new ModbusTagDefinition("T200", ModbusRegion.HoldingRegisters, 200, ModbusDataType.Int16);
|
||||
var t202 = new ModbusTagDefinition("T202", ModbusRegion.HoldingRegisters, 202, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t100, t102, t104, t200, t202], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t100, t102, t104, t200, t202]), MaxReadGap = 5,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
+3
-3
@@ -65,7 +65,7 @@ public sealed class ModbusCoalescingBisectionTests
|
||||
var tags = Enumerable.Range(100, 11)
|
||||
.Select(i => new ModbusTagDefinition($"T{i}", ModbusRegion.HoldingRegisters, (ushort)i, ModbusDataType.Int16))
|
||||
.ToArray();
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = tags, MaxReadGap = 10,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries(tags), MaxReadGap = 10,
|
||||
AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(100),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
@@ -108,7 +108,7 @@ public sealed class ModbusCoalescingBisectionTests
|
||||
var tags = Enumerable.Range(100, 11)
|
||||
.Select(i => new ModbusTagDefinition($"T{i}", ModbusRegion.HoldingRegisters, (ushort)i, ModbusDataType.Int16))
|
||||
.ToArray();
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = tags, MaxReadGap = 10,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries(tags), MaxReadGap = 10,
|
||||
AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(100),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
@@ -140,7 +140,7 @@ public sealed class ModbusCoalescingBisectionTests
|
||||
var tags = Enumerable.Range(100, 11)
|
||||
.Select(i => new ModbusTagDefinition($"T{i}", ModbusRegion.HoldingRegisters, (ushort)i, ModbusDataType.Int16))
|
||||
.ToArray();
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = tags, MaxReadGap = 10,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries(tags), MaxReadGap = 10,
|
||||
AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(100),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => twoHole);
|
||||
|
||||
@@ -49,7 +49,7 @@ public sealed class ModbusCoalescingTests
|
||||
var fake = new CountingTransport();
|
||||
var t1 = new ModbusTagDefinition("T1", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t2 = new ModbusTagDefinition("T2", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t1, t2], MaxReadGap = 0,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t1, t2]), MaxReadGap = 0,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -70,7 +70,7 @@ public sealed class ModbusCoalescingTests
|
||||
var t1 = new ModbusTagDefinition("T1", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t2 = new ModbusTagDefinition("T2", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t3 = new ModbusTagDefinition("T3", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t1, t2, t3], MaxReadGap = 2,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t1, t2, t3]), MaxReadGap = 2,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -92,7 +92,7 @@ public sealed class ModbusCoalescingTests
|
||||
var t1 = new ModbusTagDefinition("T1", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t2 = new ModbusTagDefinition("T2", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t3 = new ModbusTagDefinition("T3", ModbusRegion.HoldingRegisters, 200, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t1, t2, t3], MaxReadGap = 10,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t1, t2, t3]), MaxReadGap = 10,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -111,7 +111,7 @@ public sealed class ModbusCoalescingTests
|
||||
var t1 = new ModbusTagDefinition("T1", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t2 = new ModbusTagDefinition("T2", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16, CoalesceProhibited: true);
|
||||
var t3 = new ModbusTagDefinition("T3", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t1, t2, t3], MaxReadGap = 10,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t1, t2, t3]), MaxReadGap = 10,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -132,7 +132,7 @@ public sealed class ModbusCoalescingTests
|
||||
// Same Region + adjacent addresses but different UnitIds → must NOT coalesce.
|
||||
var t1 = new ModbusTagDefinition("T1", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16, UnitId: 1);
|
||||
var t2 = new ModbusTagDefinition("T2", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16, UnitId: 2);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t1, t2], MaxReadGap = 100,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t1, t2]), MaxReadGap = 100,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -154,7 +154,7 @@ public sealed class ModbusCoalescingTests
|
||||
// resulting span exceeds the cap — it falls back to two separate reads.
|
||||
var t1 = new ModbusTagDefinition("T1", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var t2 = new ModbusTagDefinition("T2", ModbusRegion.HoldingRegisters, 200, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t1, t2], MaxReadGap = 300,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t1, t2]), MaxReadGap = 300,
|
||||
MaxRegistersPerRead = 125, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -174,7 +174,7 @@ public sealed class ModbusCoalescingTests
|
||||
var fake = new CountingTransport();
|
||||
var t1 = new ModbusTagDefinition("T1", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t2 = new ModbusTagDefinition("T2", ModbusRegion.HoldingRegisters, 101, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t1, t2], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t1, t2]), MaxReadGap = 5,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
+23
-18
@@ -6,44 +6,49 @@ using Xunit;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression guard for the 2026-06-19 enum-serialization bug (the FB-9 Modbus-Int64 authoring
|
||||
/// case). The AdminUI Modbus page now serialises tag enums (<see cref="ModbusRegion"/>,
|
||||
/// <see cref="ModbusDataType"/>, byte-order) as STRINGS. This proves the factory parses that
|
||||
/// AdminUI-shaped Int64-tag blob, and documents that the pre-fix NUMERIC form threw because the
|
||||
/// <c>ModbusTagDto</c> enum fields are <c>string?</c>.
|
||||
/// v3 factory RawTags binding. Under v3 tags are delivered as authored raw tags
|
||||
/// (<c>{rawPath, tagConfig, writeIdempotent}</c>) — the tag's address enums live INSIDE the opaque
|
||||
/// <c>tagConfig</c> blob (authored by the AdminUI <c>ModbusTagConfigModel</c>), not in the driver
|
||||
/// config DTO. This proves the factory binds a <c>rawTags</c> array and documents that the legacy
|
||||
/// structured/AddressString <c>tags</c> path (and the FB-9 numeric-vs-string tag-enum bug class it
|
||||
/// carried) is retired.
|
||||
/// </summary>
|
||||
public sealed class ModbusDriverConfigEnumSerializationTests
|
||||
{
|
||||
// Mirrors the (now fixed) AdminUI ModbusDriverPage._jsonOpts: camelCase + string enums.
|
||||
// Mirrors the AdminUI ModbusDriverPage._jsonOpts: camelCase + string enums.
|
||||
private static readonly JsonSerializerOptions _adminPageOpts = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
Converters = { new JsonStringEnumConverter() },
|
||||
};
|
||||
|
||||
/// <summary>Verifies the factory parses an AdminUI-authored Modbus config carrying an Int64
|
||||
/// holding-register tag (string enums) without throwing.</summary>
|
||||
/// <summary>Verifies the factory binds an AdminUI-authored Modbus config carrying an Int64
|
||||
/// holding-register raw tag (string enums inside the tagConfig blob) without throwing.</summary>
|
||||
[Fact]
|
||||
public void Factory_parses_admin_authored_int64_string_enum_config()
|
||||
public void Factory_binds_admin_authored_rawTags_config()
|
||||
{
|
||||
var tag = new ModbusTagDefinition("Int64Tag", ModbusRegion.HoldingRegisters, (ushort)100, ModbusDataType.Int64);
|
||||
var opts = new ModbusDriverOptions { Host = "10.0.0.5", Port = 502, UnitId = 1, Tags = new[] { tag } };
|
||||
var tag = new ModbusTagDefinition("cell/modbus/dev1/Int64Tag", ModbusRegion.HoldingRegisters, (ushort)100, ModbusDataType.Int64);
|
||||
var opts = new ModbusDriverOptions { Host = "10.0.0.5", Port = 502, UnitId = 1, RawTags = ModbusRawTags.Entries(new[] { tag }) };
|
||||
var blob = JsonSerializer.Serialize(opts, _adminPageOpts);
|
||||
// The fixed AdminUI page must emit tag enums as strings, not numbers.
|
||||
blob.ShouldContain("\"dataType\":\"Int64\"");
|
||||
// The raw tag serialises as {rawPath, tagConfig, writeIdempotent}; the address enums live
|
||||
// inside the (string-encoded) tagConfig blob.
|
||||
blob.ShouldContain("\"rawPath\":\"cell/modbus/dev1/Int64Tag\"");
|
||||
blob.ShouldContain("Int64");
|
||||
|
||||
using var driver = ModbusDriverFactoryExtensions.CreateInstance("mb-test", blob);
|
||||
driver.DriverType.ShouldBe("Modbus");
|
||||
}
|
||||
|
||||
/// <summary>Documents the original bug: the pre-fix AdminUI page emitted numeric tag enums
|
||||
/// (<c>"dataType":5,"region":3</c>) which the string-typed tag DTO cannot bind, so the factory throws.</summary>
|
||||
/// <summary>Documents the retirement of the legacy structured <c>tags</c> path: a legacy tag array
|
||||
/// (including the pre-fix numeric-enum shape) is no longer a recognised property, so it binds nothing
|
||||
/// and the factory succeeds rather than throwing on its enum shape.</summary>
|
||||
[Fact]
|
||||
public void Factory_throws_on_the_numeric_enum_form_the_pre_fix_page_emitted()
|
||||
public void Factory_ignores_the_retired_structured_tags_array()
|
||||
{
|
||||
const string numericBlob =
|
||||
const string legacyBlob =
|
||||
"{\"host\":\"10.0.0.5\",\"port\":502,\"unitId\":1,\"tags\":[" +
|
||||
"{\"name\":\"Int64Tag\",\"region\":3,\"address\":100,\"dataType\":5}]}";
|
||||
Should.Throw<Exception>(() => ModbusDriverFactoryExtensions.CreateInstance("mb-test", numericBlob));
|
||||
using var driver = ModbusDriverFactoryExtensions.CreateInstance("mb-test", legacyBlob);
|
||||
driver.DriverType.ShouldBe("Modbus");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ public sealed class ModbusDriverTests
|
||||
private static (ModbusDriver driver, FakeTransport fake) NewDriver(params ModbusTagDefinition[] tags)
|
||||
{
|
||||
var fake = new FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = tags };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries(tags)};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
return (drv, fake);
|
||||
}
|
||||
|
||||
+25
-54
@@ -7,9 +7,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
/// Regression coverage for Driver.Modbus-009: two configuration edge cases that previously
|
||||
/// silently produced wrong wire behaviour.
|
||||
/// (1) <c>StringLength = 0</c> for a <c>String</c>-typed tag — used to flow into an FC03
|
||||
/// with quantity 0, a spec-illegal request the PLC rejects with exception 03. Now bind-time
|
||||
/// validation in <c>ModbusDriverFactoryExtensions</c> rejects the misconfiguration with a
|
||||
/// clear diagnostic.
|
||||
/// with quantity 0, a spec-illegal request the PLC rejects with exception 03. In v3 the guard
|
||||
/// moved to the pure mapper (<see cref="ModbusTagDefinitionFactory.FromTagConfig"/>): a String
|
||||
/// tag with <c>stringLength < 1</c> fails to map (⇒ the driver skips it / surfaces
|
||||
/// <c>BadNodeIdUnknown</c>) instead of the factory throwing at bind time.
|
||||
/// (2) Sub-second <see cref="TimeSpan"/> values on <c>ModbusKeepAliveOptions.Time</c> /
|
||||
/// <c>Interval</c> — the int-cast in <c>EnableKeepAlive</c> truncated <c>500 ms</c> to
|
||||
/// <c>0</c>, which most OSes interpret as "use the default", silently defeating the
|
||||
@@ -19,71 +20,41 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ModbusEdgeCaseValidationTests
|
||||
{
|
||||
/// <summary>Verifies that string tags with zero length are rejected during factory creation.</summary>
|
||||
private const string RawPath = "cell/modbus/dev1/Greeting";
|
||||
|
||||
/// <summary>Verifies that a String tag with an explicit zero length fails to map.</summary>
|
||||
[Fact]
|
||||
public void Factory_rejects_String_tag_with_StringLength_zero_via_structured_form()
|
||||
public void Mapper_rejects_String_tag_with_StringLength_zero_explicit()
|
||||
{
|
||||
const string json = """
|
||||
{
|
||||
"host": "10.0.0.10",
|
||||
"tags": [
|
||||
{ "name": "Greeting", "region": "HoldingRegisters", "address": 100, "dataType": "String", "stringLength": 0 }
|
||||
]
|
||||
}
|
||||
""";
|
||||
var ex = Should.Throw<InvalidOperationException>(
|
||||
() => ModbusDriverFactoryExtensions.CreateInstance("modbus-1", json));
|
||||
ex.Message.ShouldContain("StringLength");
|
||||
ex.Message.ShouldContain("Greeting");
|
||||
const string json = """{"region":"HoldingRegisters","address":100,"dataType":"String","stringLength":0}""";
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, RawPath, out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
/// <summary>Verifies that omitted string length defaults to zero and is rejected.</summary>
|
||||
/// <summary>Verifies that a String tag with an omitted length (defaults to zero) fails to map.</summary>
|
||||
[Fact]
|
||||
public void Factory_rejects_String_tag_with_StringLength_zero_via_missing_field()
|
||||
public void Mapper_rejects_String_tag_with_StringLength_zero_missing_field()
|
||||
{
|
||||
// No stringLength → defaults to 0. Same misconfiguration via a different DTO shape.
|
||||
const string json = """
|
||||
{
|
||||
"host": "10.0.0.10",
|
||||
"tags": [
|
||||
{ "name": "Greeting", "region": "HoldingRegisters", "address": 100, "dataType": "String" }
|
||||
]
|
||||
}
|
||||
""";
|
||||
var ex = Should.Throw<InvalidOperationException>(
|
||||
() => ModbusDriverFactoryExtensions.CreateInstance("modbus-1", json));
|
||||
ex.Message.ShouldContain("StringLength");
|
||||
// No stringLength → defaults to 0. Same misconfiguration via a different blob shape.
|
||||
const string json = """{"region":"HoldingRegisters","address":100,"dataType":"String"}""";
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, RawPath, out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
/// <summary>Verifies that string tags with length one are accepted.</summary>
|
||||
/// <summary>Verifies that a String tag with length one maps successfully.</summary>
|
||||
[Fact]
|
||||
public void Factory_accepts_String_tag_with_StringLength_one()
|
||||
public void Mapper_accepts_String_tag_with_StringLength_one()
|
||||
{
|
||||
const string json = """
|
||||
{
|
||||
"host": "10.0.0.10",
|
||||
"tags": [
|
||||
{ "name": "Greeting", "region": "HoldingRegisters", "address": 100, "dataType": "String", "stringLength": 1 }
|
||||
]
|
||||
}
|
||||
""";
|
||||
Should.NotThrow(() => ModbusDriverFactoryExtensions.CreateInstance("modbus-1", json));
|
||||
const string json = """{"region":"HoldingRegisters","address":100,"dataType":"String","stringLength":1}""";
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, RawPath, out var def).ShouldBeTrue();
|
||||
def.StringLength.ShouldBe((ushort)1);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that non-string tags are unaffected by string length zero.</summary>
|
||||
/// <summary>Verifies that non-String tags are unaffected by a zero string length.</summary>
|
||||
[Fact]
|
||||
public void Factory_accepts_non_String_tag_with_StringLength_zero()
|
||||
public void Mapper_accepts_non_String_tag_with_StringLength_zero()
|
||||
{
|
||||
// The validation only kicks in for String tags — Int16 tags with StringLength=0 are normal.
|
||||
const string json = """
|
||||
{
|
||||
"host": "10.0.0.10",
|
||||
"tags": [
|
||||
{ "name": "Level", "region": "HoldingRegisters", "address": 100, "dataType": "Int16" }
|
||||
]
|
||||
}
|
||||
""";
|
||||
Should.NotThrow(() => ModbusDriverFactoryExtensions.CreateInstance("modbus-1", json));
|
||||
// The guard only kicks in for String tags — Int16 tags with StringLength=0 are normal.
|
||||
const string json = """{"region":"HoldingRegisters","address":100,"dataType":"Int16"}""";
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, RawPath, out _).ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>Verifies that sub-second time spans are rounded up to at least one second.</summary>
|
||||
|
||||
@@ -54,7 +54,7 @@ public sealed class ModbusExceptionMapperTests
|
||||
{
|
||||
var transport = new ExceptionRaisingTransport(exceptionCode: 0x02);
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
await using var drv = new ModbusDriver(opts, "modbus-1", _ => transport);
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
@@ -68,7 +68,7 @@ public sealed class ModbusExceptionMapperTests
|
||||
{
|
||||
var transport = new ExceptionRaisingTransport(exceptionCode: 0x04);
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
await using var drv = new ModbusDriver(opts, "modbus-1", _ => transport);
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
@@ -104,7 +104,7 @@ public sealed class ModbusExceptionMapperTests
|
||||
// Socket drop / timeout / malformed frame → transport-layer failure. Should surface
|
||||
// distinctly from tag-level faults so operators know to check the network, not the config.
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
await using var drv = new ModbusDriver(opts, "modbus-1", _ => new NonModbusFailureTransport());
|
||||
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
|
||||
+11
-11
@@ -76,12 +76,12 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a snapshot of the driver's private <c>_tagsByName</c> dictionary so the
|
||||
/// Returns a snapshot of the driver's private <c>_tagsByRawPath</c> dictionary so the
|
||||
/// hygiene tests can confirm the cache is empty after teardown.
|
||||
/// </summary>
|
||||
private static System.Collections.IDictionary GetTagsByName(ModbusDriver drv) =>
|
||||
(System.Collections.IDictionary)typeof(ModbusDriver)
|
||||
.GetField("_tagsByName", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.GetField("_tagsByRawPath", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.GetValue(drv)!;
|
||||
|
||||
// -------------------- Finding -002 / -012 (2) --------------------
|
||||
@@ -97,7 +97,7 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
var opts = new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake",
|
||||
Tags = [new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)]),
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -116,8 +116,8 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
{
|
||||
Host = "fake",
|
||||
WriteOnChangeOnly = true,
|
||||
Tags = [new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16,
|
||||
Deadband: 1.0)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16,
|
||||
Deadband: 1.0)]),
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -164,7 +164,7 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
},
|
||||
// Re-probe loop also opted in so DisposeAsync exercises both CTS cancellations.
|
||||
AutoProhibitReprobeInterval = TimeSpan.FromMilliseconds(50),
|
||||
Tags = [new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)]),
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -195,7 +195,7 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
{
|
||||
Host = "fake",
|
||||
Probe = new ModbusProbeOptions { Enabled = false },
|
||||
Tags = [new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)]),
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -258,7 +258,7 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
var opts = new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake",
|
||||
Tags = [new ModbusTagDefinition("Level", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("Level", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)]),
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -278,7 +278,7 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
var opts = new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake",
|
||||
Tags = [new ModbusTagDefinition("Level", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("Level", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)]),
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -300,7 +300,7 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
var opts = new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake",
|
||||
Tags = [new ModbusTagDefinition("Coil", ModbusRegion.Coils, 0, ModbusDataType.Bool)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("Coil", ModbusRegion.Coils, 0, ModbusDataType.Bool)]),
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
drv.InitializeAsync("{}", CancellationToken.None).GetAwaiter().GetResult();
|
||||
@@ -347,7 +347,7 @@ public sealed class ModbusLifecycleHygieneTests
|
||||
var opts = new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake",
|
||||
Tags = [new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)],
|
||||
RawTags = ModbusRawTags.Entries([new ModbusTagDefinition("A", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)]),
|
||||
};
|
||||
var drv = new ModbusDriver(opts, "modbus-1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
@@ -85,7 +85,7 @@ public sealed class ModbusLoggerInjectionTests
|
||||
var t100 = new ModbusTagDefinition("T100", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t102 = new ModbusTagDefinition("T102", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t104 = new ModbusTagDefinition("T104", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t100, t102, t104], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t100, t102, t104]), MaxReadGap = 5,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "drv-logged", _ => fake, logger: logger);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -116,7 +116,7 @@ public sealed class ModbusLoggerInjectionTests
|
||||
var t100 = new ModbusTagDefinition("T100", ModbusRegion.HoldingRegisters, 100, ModbusDataType.Int16);
|
||||
var t102 = new ModbusTagDefinition("T102", ModbusRegion.HoldingRegisters, 102, ModbusDataType.Int16);
|
||||
var t104 = new ModbusTagDefinition("T104", ModbusRegion.HoldingRegisters, 104, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [t100, t102, t104], MaxReadGap = 5,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([t100, t102, t104]), MaxReadGap = 5,
|
||||
AutoProhibitReprobeInterval = TimeSpan.FromHours(1), // long interval — we drive it manually
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "drv-logged", _ => fake, logger: logger);
|
||||
|
||||
@@ -47,7 +47,7 @@ public sealed class ModbusMultiUnitTests
|
||||
var fake = new UnitCapturingTransport();
|
||||
var tagSlave1 = new ModbusTagDefinition("S1Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, UnitId: 1);
|
||||
var tagSlave5 = new ModbusTagDefinition("S5Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, UnitId: 5);
|
||||
var opts = new ModbusDriverOptions { Host = "f", UnitId = 99, Tags = [tagSlave1, tagSlave5],
|
||||
var opts = new ModbusDriverOptions { Host = "f", UnitId = 99, RawTags = ModbusRawTags.Entries([tagSlave1, tagSlave5]),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -66,7 +66,7 @@ public sealed class ModbusMultiUnitTests
|
||||
{
|
||||
var fake = new UnitCapturingTransport();
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16); // no UnitId override
|
||||
var opts = new ModbusDriverOptions { Host = "f", UnitId = 7, Tags = [tag],
|
||||
var opts = new ModbusDriverOptions { Host = "f", UnitId = 7, RawTags = ModbusRawTags.Entries([tag]),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -83,7 +83,7 @@ public sealed class ModbusMultiUnitTests
|
||||
var fake = new UnitCapturingTransport();
|
||||
var t1 = new ModbusTagDefinition("S1Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, UnitId: 1);
|
||||
var t5 = new ModbusTagDefinition("S5Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, UnitId: 5);
|
||||
var opts = new ModbusDriverOptions { Host = "10.1.2.3", Port = 502, Tags = [t1, t5],
|
||||
var opts = new ModbusDriverOptions { Host = "10.1.2.3", Port = 502, RawTags = ModbusRawTags.Entries([t1, t5]),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -101,7 +101,7 @@ public sealed class ModbusMultiUnitTests
|
||||
public async Task IPerCallHostResolver_Unknown_Tag_Falls_Back_To_HostName()
|
||||
{
|
||||
var fake = new UnitCapturingTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "10.1.2.3", Port = 502, Tags = [],
|
||||
var opts = new ModbusDriverOptions { Host = "10.1.2.3", Port = 502, RawTags = [],
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
@@ -75,7 +75,7 @@ public sealed class ModbusProtocolOptionsTests
|
||||
{
|
||||
var fake = new CapturingTransport();
|
||||
var tag = new ModbusTagDefinition("Run", ModbusRegion.Coils, 0, ModbusDataType.Bool);
|
||||
var drv = new ModbusDriver(new ModbusDriverOptions { Host = "f", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } }, "m1", _ => fake);
|
||||
var drv = new ModbusDriver(new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } }, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
await drv.WriteAsync([new WriteRequest("Run", true)], CancellationToken.None);
|
||||
@@ -89,7 +89,7 @@ public sealed class ModbusProtocolOptionsTests
|
||||
{
|
||||
var fake = new CapturingTransport();
|
||||
var tag = new ModbusTagDefinition("Run", ModbusRegion.Coils, 0, ModbusDataType.Bool);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], UseFC15ForSingleCoilWrites = true, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), UseFC15ForSingleCoilWrites = true, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
@@ -104,7 +104,7 @@ public sealed class ModbusProtocolOptionsTests
|
||||
{
|
||||
var fake = new CapturingTransport();
|
||||
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var drv = new ModbusDriver(new ModbusDriverOptions { Host = "f", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } }, "m1", _ => fake);
|
||||
var drv = new ModbusDriver(new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } }, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None);
|
||||
@@ -118,7 +118,7 @@ public sealed class ModbusProtocolOptionsTests
|
||||
{
|
||||
var fake = new CapturingTransport();
|
||||
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], UseFC16ForSingleRegisterWrites = true, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), UseFC16ForSingleRegisterWrites = true, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
@@ -134,7 +134,7 @@ public sealed class ModbusProtocolOptionsTests
|
||||
var fake = new CapturingTransport();
|
||||
// 2500 coils with cap 2000 → 2 reads (2000 + 500).
|
||||
var tag = new ModbusTagDefinition("Big", ModbusRegion.Coils, 0, ModbusDataType.Bool, ArrayCount: 2500);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], MaxCoilsPerRead = 2000, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), MaxCoilsPerRead = 2000, Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Test helper bridging the v2 authoring shape (a typed <see cref="ModbusTagDefinition"/>) to the v3
|
||||
/// delivery shape (<see cref="RawTagEntry"/>). Under v3 the driver no longer takes pre-declared
|
||||
/// definitions — the deploy artifact hands it authored raw tags (RawPath + TagConfig blob), and the
|
||||
/// driver rebuilds the typed definitions via <see cref="ModbusTagDefinitionFactory"/>. These tests keep
|
||||
/// expressing their intent as typed definitions; this helper serialises each back to its TagConfig blob
|
||||
/// (via <see cref="ModbusTagDefinitionFactory.ToTagConfig"/>) and packages it as a <see cref="RawTagEntry"/>
|
||||
/// whose RawPath is the def's <c>Name</c> — so the round-trip through the real mapper reproduces the same
|
||||
/// definition the test authored, keyed by the same name the read/write/subscribe call sites use.
|
||||
/// </summary>
|
||||
internal static class ModbusRawTags
|
||||
{
|
||||
/// <summary>Serialises one typed definition into its <see cref="RawTagEntry"/> (RawPath = def.Name).</summary>
|
||||
/// <param name="def">The typed definition to convert.</param>
|
||||
/// <returns>The equivalent <see cref="RawTagEntry"/>.</returns>
|
||||
public static RawTagEntry Entry(ModbusTagDefinition def)
|
||||
=> new(def.Name, ModbusTagDefinitionFactory.ToTagConfig(def), def.WriteIdempotent);
|
||||
|
||||
/// <summary>Serialises a sequence of typed definitions into <see cref="RawTagEntry"/> records.</summary>
|
||||
/// <param name="defs">The typed definitions to convert.</param>
|
||||
/// <returns>The equivalent raw-tag entries.</returns>
|
||||
public static IReadOnlyList<RawTagEntry> Entries(IEnumerable<ModbusTagDefinition> defs)
|
||||
=> [.. defs.Select(Entry)];
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public sealed class ModbusSubscribeOptionsTests
|
||||
{
|
||||
var fake = new ProgrammableTransport();
|
||||
var tag = new ModbusTagDefinition("Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, Deadband: 5.0);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
@@ -102,7 +102,7 @@ public sealed class ModbusSubscribeOptionsTests
|
||||
{
|
||||
var fake = new ProgrammableTransport();
|
||||
var tag = new ModbusTagDefinition("Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16); // no deadband
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
@@ -127,7 +127,7 @@ public sealed class ModbusSubscribeOptionsTests
|
||||
{
|
||||
var fake = new ProgrammableTransport();
|
||||
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], WriteOnChangeOnly = true,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), WriteOnChangeOnly = true,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -146,7 +146,7 @@ public sealed class ModbusSubscribeOptionsTests
|
||||
{
|
||||
var fake = new ProgrammableTransport();
|
||||
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag],
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]),
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
@@ -164,7 +164,7 @@ public sealed class ModbusSubscribeOptionsTests
|
||||
{
|
||||
var fake = new ProgrammableTransport();
|
||||
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], WriteOnChangeOnly = true,
|
||||
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), WriteOnChangeOnly = true,
|
||||
Probe = new ModbusProbeOptions { Enabled = false } };
|
||||
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
@@ -48,7 +48,7 @@ public sealed class ModbusSubscriptionTests
|
||||
private static (ModbusDriver drv, FakeTransport fake) NewDriver(params ModbusTagDefinition[] tags)
|
||||
{
|
||||
var fake = new FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = tags };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries(tags)};
|
||||
return (new ModbusDriver(opts, "modbus-1", _ => fake), fake);
|
||||
}
|
||||
|
||||
|
||||
+23
-19
@@ -5,47 +5,51 @@ using ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// R2-11 Phase C strictness surface for the Modbus equipment-tag parser: the runtime is now STRICT — a
|
||||
/// present-but-invalid (typo'd) enum on any of the three enum fields (<c>region</c> / <c>dataType</c> /
|
||||
/// <c>byteOrder</c>) rejects the whole tag (<c>TryParse</c> ⇒ <see langword="false"/> ⇒
|
||||
/// R2-11 Phase C strictness surface for the Modbus tag-definition factory: the mapper is STRICT — a
|
||||
/// present-but-invalid (typo'd) enum on any enum field (<c>region</c> / <c>dataType</c> /
|
||||
/// <c>byteOrder</c>) rejects the whole tag (<c>FromTagConfig</c> ⇒ <see langword="false"/> ⇒
|
||||
/// <c>BadNodeIdUnknown</c>) instead of silently defaulting to a wrong-width <c>Good</c>. <c>Inspect</c>
|
||||
/// still reports the same typo at deploy time, and the <c>writable</c> key is honoured (default true).
|
||||
/// Under v3 the mapped definition's <c>Name</c> is the RawPath the mapper was handed, not the blob.
|
||||
/// </summary>
|
||||
public sealed class ModbusEquipmentTagParserStrictnessTests
|
||||
public sealed class ModbusTagDefinitionFactoryStrictnessTests
|
||||
{
|
||||
private const string RawPath = "cell/modbus/dev1/T1";
|
||||
|
||||
// ---- Phase C: a typo'd enum now rejects the tag (BadNodeIdUnknown), not a silent default ----
|
||||
|
||||
[Fact]
|
||||
public void Typo_dataType_rejects_the_tag()
|
||||
{
|
||||
ModbusEquipmentTagParser.TryParse(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Intt16\"}", out _)
|
||||
ModbusTagDefinitionFactory.FromTagConfig(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Intt16\"}", RawPath, out _)
|
||||
.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Typo_region_rejects_the_tag()
|
||||
{
|
||||
ModbusEquipmentTagParser.TryParse(
|
||||
"{\"region\":\"HoldingRegisterz\",\"address\":1,\"dataType\":\"Int16\"}", out _)
|
||||
ModbusTagDefinitionFactory.FromTagConfig(
|
||||
"{\"region\":\"HoldingRegisterz\",\"address\":1,\"dataType\":\"Int16\"}", RawPath, out _)
|
||||
.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Typo_byteOrder_rejects_the_tag()
|
||||
{
|
||||
ModbusEquipmentTagParser.TryParse(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\",\"byteOrder\":\"BigEndan\"}", out _)
|
||||
ModbusTagDefinitionFactory.FromTagConfig(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\",\"byteOrder\":\"BigEndan\"}", RawPath, out _)
|
||||
.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Valid_enums_still_parse()
|
||||
{
|
||||
ModbusEquipmentTagParser.TryParse(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\",\"byteOrder\":\"BigEndian\"}", out var def)
|
||||
ModbusTagDefinitionFactory.FromTagConfig(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\",\"byteOrder\":\"BigEndian\"}", RawPath, out var def)
|
||||
.ShouldBeTrue();
|
||||
def.DataType.ShouldBe(ModbusDataType.Int16);
|
||||
def.Name.ShouldBe(RawPath);
|
||||
}
|
||||
|
||||
// ---- Inspect reports the typo ----
|
||||
@@ -53,7 +57,7 @@ public sealed class ModbusEquipmentTagParserStrictnessTests
|
||||
[Fact]
|
||||
public void Inspect_reports_typo_dataType_with_field_and_valid_values()
|
||||
{
|
||||
var warnings = ModbusEquipmentTagParser.Inspect(
|
||||
var warnings = ModbusTagDefinitionFactory.Inspect(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Intt16\"}");
|
||||
warnings.ShouldHaveSingleItem();
|
||||
warnings[0].ShouldContain("Intt16");
|
||||
@@ -64,7 +68,7 @@ public sealed class ModbusEquipmentTagParserStrictnessTests
|
||||
[Fact]
|
||||
public void Inspect_clean_config_has_no_warnings()
|
||||
{
|
||||
ModbusEquipmentTagParser.Inspect(
|
||||
ModbusTagDefinitionFactory.Inspect(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\"}")
|
||||
.ShouldBeEmpty();
|
||||
}
|
||||
@@ -72,7 +76,7 @@ public sealed class ModbusEquipmentTagParserStrictnessTests
|
||||
[Fact]
|
||||
public void Inspect_malformed_json_warns_unresolvable()
|
||||
{
|
||||
ModbusEquipmentTagParser.Inspect("{not json").ShouldHaveSingleItem();
|
||||
ModbusTagDefinitionFactory.Inspect("{not json").ShouldHaveSingleItem();
|
||||
}
|
||||
|
||||
// ---- writable now honoured ----
|
||||
@@ -80,8 +84,8 @@ public sealed class ModbusEquipmentTagParserStrictnessTests
|
||||
[Fact]
|
||||
public void Writable_false_is_honoured()
|
||||
{
|
||||
ModbusEquipmentTagParser.TryParse(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\",\"writable\":false}", out var def)
|
||||
ModbusTagDefinitionFactory.FromTagConfig(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\",\"writable\":false}", RawPath, out var def)
|
||||
.ShouldBeTrue();
|
||||
def.Writable.ShouldBeFalse();
|
||||
}
|
||||
@@ -89,8 +93,8 @@ public sealed class ModbusEquipmentTagParserStrictnessTests
|
||||
[Fact]
|
||||
public void Writable_absent_defaults_to_true()
|
||||
{
|
||||
ModbusEquipmentTagParser.TryParse(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\"}", out var def)
|
||||
ModbusTagDefinitionFactory.FromTagConfig(
|
||||
"{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\"}", RawPath, out var def)
|
||||
.ShouldBeTrue();
|
||||
def.Writable.ShouldBeTrue();
|
||||
}
|
||||
+20
-16
@@ -1,18 +1,21 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
|
||||
[Trait("Category", "Unit")]
|
||||
public class ModbusEquipmentTagTests
|
||||
public class ModbusTagDefinitionFactoryTests
|
||||
{
|
||||
private const string RawPath = "cell/modbus/dev1/Reg";
|
||||
|
||||
[Fact]
|
||||
public void Parses_equipment_tagconfig_into_a_transient_definition()
|
||||
public void Maps_tagconfig_into_a_definition_keyed_by_rawpath()
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":40001,"dataType":"UInt16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0}""";
|
||||
ModbusEquipmentTagParser.TryParse(json, out var def).ShouldBeTrue();
|
||||
def!.Name.ShouldBe(json);
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, RawPath, out var def).ShouldBeTrue();
|
||||
def!.Name.ShouldBe(RawPath); // v3: identity is the RawPath, not the blob
|
||||
def.Region.ShouldBe(ModbusRegion.HoldingRegisters);
|
||||
def.Address.ShouldBe((ushort)40001);
|
||||
def.DataType.ShouldBe(ModbusDataType.UInt16);
|
||||
@@ -20,39 +23,40 @@ public class ModbusEquipmentTagTests
|
||||
|
||||
[Fact]
|
||||
public void Rejects_a_non_address_blob()
|
||||
=> ModbusEquipmentTagParser.TryParse("""{"FullName":"x"}""", out _).ShouldBeFalse();
|
||||
=> ModbusTagDefinitionFactory.FromTagConfig("""{"FullName":"x"}""", RawPath, out _).ShouldBeFalse();
|
||||
|
||||
[Fact]
|
||||
public void Rejects_garbage()
|
||||
=> ModbusEquipmentTagParser.TryParse("not json", out _).ShouldBeFalse();
|
||||
=> ModbusTagDefinitionFactory.FromTagConfig("not json", RawPath, out _).ShouldBeFalse();
|
||||
|
||||
[Fact]
|
||||
public void Rejects_address_as_a_json_string()
|
||||
=> ModbusEquipmentTagParser.TryParse(
|
||||
"""{"region":"HoldingRegisters","address":"40001","dataType":"UInt16"}""", out _).ShouldBeFalse();
|
||||
=> ModbusTagDefinitionFactory.FromTagConfig(
|
||||
"""{"region":"HoldingRegisters","address":"40001","dataType":"UInt16"}""", RawPath, out _).ShouldBeFalse();
|
||||
|
||||
[Fact]
|
||||
public void Rejects_address_out_of_ushort_range()
|
||||
=> ModbusEquipmentTagParser.TryParse(
|
||||
"""{"region":"HoldingRegisters","address":70000,"dataType":"UInt16"}""", out _).ShouldBeFalse();
|
||||
=> ModbusTagDefinitionFactory.FromTagConfig(
|
||||
"""{"region":"HoldingRegisters","address":70000,"dataType":"UInt16"}""", RawPath, out _).ShouldBeFalse();
|
||||
|
||||
/// <summary>
|
||||
/// End-to-end driver-level proof: a Modbus driver with NO authored tags can still read an
|
||||
/// equipment-tag ref (the raw TagConfig JSON) — the resolver parses it into a transient
|
||||
/// definition and the read goes to the wire instead of returning BadNodeIdUnknown.
|
||||
/// End-to-end driver-level proof: a Modbus driver handed an authored raw tag (RawPath + TagConfig
|
||||
/// blob) maps it into its RawPath → definition table and reads by RawPath — the read goes to the
|
||||
/// wire instead of returning BadNodeIdUnknown.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Driver_resolves_an_equipment_ref_and_reads_instead_of_BadNodeIdUnknown()
|
||||
public async Task Driver_resolves_a_rawpath_and_reads_instead_of_BadNodeIdUnknown()
|
||||
{
|
||||
// Address 10 fits the fake transport's 256-register bank (40001 would overflow it).
|
||||
const string rawPath = "cell/modbus/dev1/U16";
|
||||
var json = """{"region":"HoldingRegisters","address":10,"dataType":"UInt16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0}""";
|
||||
var fake = new ModbusDriverTests.FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = [] };
|
||||
var opts = new ModbusDriverOptions { Host = "fake", RawTags = [new RawTagEntry(rawPath, json, false)] };
|
||||
var drv = new ModbusDriver(opts, "modbus-eq", _ => fake);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
fake.HoldingRegisters[10] = 4242;
|
||||
|
||||
var r = await drv.ReadAsync([json], CancellationToken.None);
|
||||
var r = await drv.ReadAsync([rawPath], CancellationToken.None);
|
||||
|
||||
r[0].StatusCode.ShouldBe(0u);
|
||||
r[0].StatusCode.ShouldNotBe(0x80340000u); // not BadNodeIdUnknown
|
||||
+33
-20
@@ -1,14 +1,15 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// CONV-4 (Modbus leg) — Modbus keys per-host resilience per SLAVE UNIT
|
||||
/// (<c>host:port/unitN</c>). An equipment tag must carry its own <c>unitId</c> so multi-unit
|
||||
/// equipment tags key their own breaker; <see cref="ModbusDriver.ResolveHost"/> must resolve
|
||||
/// the equipment ref through the resolver rather than only matching authored names. Scope:
|
||||
/// <c>unitId</c> ONLY — the parser's other strictness gaps are R2-11's.
|
||||
/// (<c>host:port/unitN</c>). An authored raw tag carries its own <c>unitId</c> in its TagConfig so
|
||||
/// multi-unit tags key their own breaker; <see cref="ModbusDriver.ResolveHost"/> resolves a RawPath
|
||||
/// through the driver's authored RawPath → definition table. Under v3 the reference is always a
|
||||
/// RawPath — an unauthored RawPath falls back to the driver-level host.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ModbusUnitIdResolveHostTests
|
||||
@@ -21,43 +22,55 @@ public sealed class ModbusUnitIdResolveHostTests
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private static ModbusDriver NewDriver() => new(
|
||||
new ModbusDriverOptions { Host = "10.0.0.1", Port = 502, UnitId = 1, Probe = new ModbusProbeOptions { Enabled = false } },
|
||||
"modbus-1", _ => new NoopTransport());
|
||||
private static async Task<ModbusDriver> NewDriverAsync(params RawTagEntry[] rawTags)
|
||||
{
|
||||
var drv = new ModbusDriver(
|
||||
new ModbusDriverOptions
|
||||
{
|
||||
Host = "10.0.0.1", Port = 502, UnitId = 1, RawTags = rawTags,
|
||||
Probe = new ModbusProbeOptions { Enabled = false },
|
||||
},
|
||||
"modbus-1", _ => new NoopTransport());
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
return drv;
|
||||
}
|
||||
|
||||
/// <summary>The parser reads an optional unitId into the transient definition.</summary>
|
||||
/// <summary>The mapper reads an optional unitId into the definition.</summary>
|
||||
[Fact]
|
||||
public void Parser_reads_optional_unitId()
|
||||
public void FromTagConfig_reads_optional_unitId()
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","unitId":7}""";
|
||||
ModbusEquipmentTagParser.TryParse(json, out var def).ShouldBeTrue();
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/dev1/U7", out var def).ShouldBeTrue();
|
||||
def.Name.ShouldBe("cell/modbus/dev1/U7");
|
||||
def.UnitId.ShouldBe((byte)7);
|
||||
}
|
||||
|
||||
/// <summary>An absent unitId leaves the definition on the driver-level default (null override).</summary>
|
||||
[Fact]
|
||||
public void Parser_absent_unitId_is_null()
|
||||
public void FromTagConfig_absent_unitId_is_null()
|
||||
{
|
||||
var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16"}""";
|
||||
ModbusEquipmentTagParser.TryParse(json, out var def).ShouldBeTrue();
|
||||
ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/dev1/U0", out var def).ShouldBeTrue();
|
||||
def.UnitId.ShouldBeNull();
|
||||
}
|
||||
|
||||
/// <summary>An equipment ref carrying a unitId keys its own per-unit host name.</summary>
|
||||
/// <summary>An authored RawPath carrying a unitId keys its own per-unit host name.</summary>
|
||||
[Fact]
|
||||
public void EquipmentTag_WithUnitId_ResolvesPerUnitHostName()
|
||||
public async Task RawPath_WithUnitId_ResolvesPerUnitHostName()
|
||||
{
|
||||
var drv = NewDriver();
|
||||
const string rawPath = "cell/modbus/dev1/U7";
|
||||
var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","unitId":7}""";
|
||||
drv.ResolveHost(json).ShouldBe("10.0.0.1:502/unit7");
|
||||
var drv = await NewDriverAsync(new RawTagEntry(rawPath, json, false));
|
||||
drv.ResolveHost(rawPath).ShouldBe("10.0.0.1:502/unit7");
|
||||
}
|
||||
|
||||
/// <summary>An equipment ref without a unitId keys the driver-level unit host name.</summary>
|
||||
/// <summary>An authored RawPath without a unitId keys the driver-level unit host name.</summary>
|
||||
[Fact]
|
||||
public void EquipmentTag_WithoutUnitId_KeysDriverDefaultUnit()
|
||||
public async Task RawPath_WithoutUnitId_KeysDriverDefaultUnit()
|
||||
{
|
||||
var drv = NewDriver();
|
||||
const string rawPath = "cell/modbus/dev1/U0";
|
||||
var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16"}""";
|
||||
drv.ResolveHost(json).ShouldBe("10.0.0.1:502/unit1");
|
||||
var drv = await NewDriverAsync(new RawTagEntry(rawPath, json, false));
|
||||
drv.ResolveHost(rawPath).ShouldBe("10.0.0.1:502/unit1");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user