Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs
T
Joseph Doherty 4a3d7a9361 feat(modbus): wire Family / MelsecSubFamily / DisableFC23, and the form's timing keys
U1: a tag's addressString (Modicon / mnemonic / DL205 V-memory / MELSEC
D-X-Y grammar) now resolves through ModbusAddressParser with the DRIVER's
Family and MelsecSubFamily at every initialize and is authoritative; the
family-unaware gates (deploy Inspect, AdminUI parse consult) accept what
some family resolves. The tag editor gets an address-text field that
resolves with the owning driver's family and persists both the string and
the resolved region/offset/type fields; a hand edit drops the string.
DisableFC23 now gates FC23: by default a 2..121-register holding write is
one FC23 write + read-back (a unit answering exception 01, or failing FC23 at
the transport, moves to FC16 for the rest of the generation); RTU framing
deframes the FC23 reply. Live-checked: the pymodbus fixture implements FC23.
Also: the AdminUI driver form serialises ModbusDriverOptions (TimeSpan
strings), which the factory DTO never read - every timing field on the form
was dead. The DTO now accepts both shapes (*Ms keys win).

Refs #741
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
2026-10-22 15:35:58 -04:00

270 lines
16 KiB
C#

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;
/// <summary>
/// Static factory registration helper for <see cref="ModbusDriver"/>. Server's Program.cs
/// calls <see cref="Register"/> once at startup; the bootstrapper then
/// materialises Modbus DriverInstance rows from the central config DB into live driver
/// instances. Mirrors <c>GalaxyProxyDriverFactoryExtensions</c> / <c>FocasDriverFactoryExtensions</c>.
/// </summary>
public static class ModbusDriverFactoryExtensions
{
public const string DriverTypeName = "Modbus";
/// <summary>
/// Register the Modbus factory with the driver registry. The optional
/// <paramref name="loggerFactory"/> is captured at registration time and used to
/// construct an <see cref="ILogger{ModbusDriver}"/> per driver instance — without it,
/// the driver runs with the null logger (existing tests and standalone callers stay
/// unchanged).
/// </summary>
/// <param name="registry">The driver factory registry to register with.</param>
/// <param name="loggerFactory">Optional logger factory for creating loggers per driver instance.</param>
public static void Register(DriverFactoryRegistry registry, ILoggerFactory? loggerFactory = null)
{
ArgumentNullException.ThrowIfNull(registry);
registry.Register(DriverTypeName, (id, json) => CreateInstance(id, json, loggerFactory));
}
/// <summary>Public for the Server-side bootstrapper + test consumers (Admin.Tests, etc.).</summary>
/// <param name="driverInstanceId">The unique identifier for the driver instance.</param>
/// <param name="driverConfigJson">The JSON configuration string for the driver.</param>
/// <returns>The constructed <see cref="ModbusDriver"/> instance.</returns>
public static ModbusDriver CreateInstance(string driverInstanceId, string driverConfigJson)
=> CreateInstance(driverInstanceId, driverConfigJson, loggerFactory: null);
/// <summary>Logger-aware overload — used by <see cref="Register"/>'s closure when wired through DI.</summary>
/// <param name="driverInstanceId">The unique identifier for the driver instance.</param>
/// <param name="driverConfigJson">The JSON configuration string for the driver.</param>
/// <param name="loggerFactory">Optional logger factory for creating loggers per driver instance.</param>
/// <returns>The constructed <see cref="ModbusDriver"/> instance.</returns>
public static ModbusDriver CreateInstance(string driverInstanceId, string driverConfigJson, ILoggerFactory? loggerFactory)
{
return new ModbusDriver(
ParseOptions(driverInstanceId, driverConfigJson), driverInstanceId,
transportFactory: null,
logger: loggerFactory?.CreateLogger<ModbusDriver>());
}
/// <summary>
/// Parses a Modbus <c>DriverConfig</c> JSON document into typed options. Extracted from
/// <see cref="CreateInstance(string,string,ILoggerFactory?)"/> so <see cref="ModbusDriver.InitializeAsync"/>
/// can re-parse a CHANGED config on reinitialize rather than serving the options it was
/// constructed with — which silently discarded every edit while the deployment still sealed green.
/// </summary>
/// <param name="driverInstanceId">The unique identifier for the driver instance.</param>
/// <param name="driverConfigJson">The JSON configuration string for the driver.</param>
/// <returns>The parsed <see cref="ModbusDriverOptions"/>.</returns>
internal static ModbusDriverOptions ParseOptions(string driverInstanceId, string driverConfigJson)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);
var dto = JsonSerializer.Deserialize<ModbusDriverConfigDto>(driverConfigJson, JsonOptions)
?? throw new InvalidOperationException(
$"Modbus driver config for '{driverInstanceId}' deserialised to null");
if (string.IsNullOrWhiteSpace(dto.Host))
throw new InvalidOperationException(
$"Modbus driver config for '{driverInstanceId}' missing required Host");
var options = new ModbusDriverOptions
{
Host = dto.Host!,
Port = dto.Port ?? 502,
UnitId = dto.UnitId ?? 1,
Timeout = Span(dto.TimeoutMs, dto.Timeout) ?? TimeSpan.FromSeconds(2),
MaxRegistersPerRead = dto.MaxRegistersPerRead ?? 125,
MaxRegistersPerWrite = dto.MaxRegistersPerWrite ?? 123,
MaxCoilsPerRead = dto.MaxCoilsPerRead ?? 2000,
UseFC15ForSingleCoilWrites = dto.UseFC15ForSingleCoilWrites ?? false,
UseFC16ForSingleRegisterWrites = dto.UseFC16ForSingleRegisterWrites ?? false,
DisableFC23 = dto.DisableFC23 ?? false,
WriteOnChangeOnly = dto.WriteOnChangeOnly ?? false,
MaxReadGap = dto.MaxReadGap ?? ModbusDriverOptions.DefaultMaxReadGap,
DisableReadCoalescing = dto.DisableReadCoalescing ?? false,
Family = dto.Family is null ? ModbusFamily.Generic
: ParseEnum<ModbusFamily>(dto.Family, "<driver-level>", driverInstanceId, "Family"),
MelsecSubFamily = dto.MelsecSubFamily is null ? MelsecFamily.Q_L_iQR
: ParseEnum<MelsecFamily>(dto.MelsecSubFamily, "<driver-level>", driverInstanceId, "MelsecSubFamily"),
Transport = dto.Transport is null ? ModbusTransportMode.Tcp
: ParseEnum<ModbusTransportMode>(dto.Transport, "<driver-level>", driverInstanceId, "Transport"),
AutoProhibitReprobeInterval = Span(dto.AutoProhibitReprobeMs, dto.AutoProhibitReprobeInterval),
AutoReconnect = dto.AutoReconnect ?? true,
// 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,
Interval = Span(dto.Probe?.IntervalMs, dto.Probe?.Interval) ?? TimeSpan.FromSeconds(5),
Timeout = Span(dto.Probe?.TimeoutMs, dto.Probe?.Timeout) ?? TimeSpan.FromSeconds(2),
ProbeAddress = dto.Probe?.ProbeAddress ?? 0,
},
KeepAlive = dto.KeepAlive is null ? new ModbusKeepAliveOptions() : new ModbusKeepAliveOptions
{
Enabled = dto.KeepAlive.Enabled ?? true,
Time = Span(dto.KeepAlive.TimeMs, dto.KeepAlive.Time) ?? TimeSpan.FromSeconds(30),
Interval = Span(dto.KeepAlive.IntervalMs, dto.KeepAlive.Interval) ?? TimeSpan.FromSeconds(10),
RetryCount = dto.KeepAlive.RetryCount ?? 3,
},
IdleDisconnectTimeout = Span(dto.IdleDisconnectMs, dto.IdleDisconnectTimeout),
Reconnect = dto.Reconnect is null ? new ModbusReconnectOptions() : new ModbusReconnectOptions
{
InitialDelay = Span(dto.Reconnect.InitialDelayMs, dto.Reconnect.InitialDelay) ?? TimeSpan.Zero,
MaxDelay = Span(dto.Reconnect.MaxDelayMs, dto.Reconnect.MaxDelay) ?? TimeSpan.FromSeconds(30),
BackoffMultiplier = dto.Reconnect.BackoffMultiplier ?? 2.0,
},
};
return options;
}
/// <summary>
/// One timing knob, accepted in BOTH shapes the config can carry: the <c>*Ms</c> integer keys (CLI,
/// seed data, hand-authored JSON) and the TimeSpan-string keys the AdminUI driver form emits — it
/// serialises <see cref="ModbusDriverOptions"/> itself, so it writes <c>"timeout":"00:00:07"</c>, not
/// <c>timeoutMs</c>. Before this every timing field on that form was silently ignored. The
/// millisecond key wins when both are present; an unparseable TimeSpan string is ignored (the
/// previous behaviour for these keys), never a reason to fail the driver.
/// </summary>
private static TimeSpan? Span(int? milliseconds, JsonElement? timeSpan)
{
if (milliseconds is { } ms) return TimeSpan.FromMilliseconds(ms);
if (timeSpan is { ValueKind: JsonValueKind.String } e
&& TimeSpan.TryParse(e.GetString(), System.Globalization.CultureInfo.InvariantCulture, out var parsed))
return parsed;
return null;
}
private static T ParseEnum<T>(string? raw, string? tagName, string driverInstanceId, string field) where T : struct, Enum
{
if (string.IsNullOrWhiteSpace(raw))
throw new InvalidOperationException(
$"Modbus tag '{tagName ?? "<unnamed>"}' in '{driverInstanceId}' missing {field}");
return Enum.TryParse<T>(raw, ignoreCase: true, out var v)
? v
: throw new InvalidOperationException(
$"Modbus tag '{tagName}' has unknown {field} '{raw}'. " +
$"Expected one of {string.Join(", ", Enum.GetNames<T>())}");
}
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
internal sealed class ModbusDriverConfigDto
{
/// <summary>Gets or sets the host address.</summary>
public string? Host { get; init; }
/// <summary>Gets or sets the port number.</summary>
public int? Port { get; init; }
/// <summary>Gets or sets the unit identifier.</summary>
public byte? UnitId { get; init; }
/// <summary>Gets or sets the timeout in milliseconds.</summary>
public int? TimeoutMs { get; init; }
/// <summary>Gets or sets the timeout as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? Timeout { get; init; }
/// <summary>Gets or sets the maximum number of registers per read operation.</summary>
public ushort? MaxRegistersPerRead { get; init; }
/// <summary>Gets or sets the maximum number of registers per write operation.</summary>
public ushort? MaxRegistersPerWrite { get; init; }
/// <summary>Gets or sets the maximum number of coils per read operation.</summary>
public ushort? MaxCoilsPerRead { get; init; }
/// <summary>Gets or sets a value indicating whether to use function code 15 for single coil writes.</summary>
public bool? UseFC15ForSingleCoilWrites { get; init; }
/// <summary>Gets or sets a value indicating whether to use function code 16 for single register writes.</summary>
public bool? UseFC16ForSingleRegisterWrites { get; init; }
/// <summary>Gets or sets a value indicating whether to disable function code 23.</summary>
public bool? DisableFC23 { get; init; }
/// <summary>Gets or sets a value indicating whether to write only on change.</summary>
public bool? WriteOnChangeOnly { get; init; }
/// <summary>Gets or sets the maximum gap between register addresses for coalescing.</summary>
public ushort? MaxReadGap { get; init; }
/// <summary>Gets or sets a value indicating whether block-read coalescing is turned off entirely.</summary>
public bool? DisableReadCoalescing { get; init; }
/// <summary>Gets or sets the Modbus family type.</summary>
public string? Family { get; init; }
/// <summary>Gets or sets the Melsec subfamily.</summary>
public string? MelsecSubFamily { get; init; }
/// <summary>Gets or sets the wire transport mode (Tcp / RtuOverTcp). Null defaults to Tcp.</summary>
public string? Transport { get; init; }
/// <summary>Gets or sets the automatic prohibition reprobei interval in milliseconds.</summary>
public int? AutoProhibitReprobeMs { get; init; }
/// <summary>Gets or sets the re-probe interval as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? AutoProhibitReprobeInterval { 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 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; }
/// <summary>Gets or sets the keep-alive configuration (connection-layer knob).</summary>
public ModbusKeepAliveDto? KeepAlive { get; init; }
/// <summary>Gets or sets the idle disconnect timeout in milliseconds.</summary>
public int? IdleDisconnectMs { get; init; }
/// <summary>Gets or sets the idle disconnect timeout as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? IdleDisconnectTimeout { get; init; }
/// <summary>Gets or sets the reconnect configuration.</summary>
public ModbusReconnectDto? Reconnect { get; init; }
}
internal sealed class ModbusKeepAliveDto
{
/// <summary>Gets or sets a value indicating whether keep-alive is enabled.</summary>
public bool? Enabled { get; init; }
/// <summary>Gets or sets the keep-alive time in milliseconds.</summary>
public int? TimeMs { get; init; }
/// <summary>Gets or sets the keep-alive interval in milliseconds.</summary>
public int? IntervalMs { get; init; }
/// <summary>Gets or sets the keep-alive time as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? Time { get; init; }
/// <summary>Gets or sets the keep-alive interval as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? Interval { get; init; }
/// <summary>Gets or sets the retry count.</summary>
public int? RetryCount { get; init; }
}
internal sealed class ModbusReconnectDto
{
/// <summary>Gets or sets the initial reconnect delay in milliseconds.</summary>
public int? InitialDelayMs { get; init; }
/// <summary>Gets or sets the maximum reconnect delay in milliseconds.</summary>
public int? MaxDelayMs { get; init; }
/// <summary>Gets or sets the initial reconnect delay as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? InitialDelay { get; init; }
/// <summary>Gets or sets the maximum reconnect delay as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? MaxDelay { get; init; }
/// <summary>Gets or sets the backoff multiplier for exponential reconnect delays.</summary>
public double? BackoffMultiplier { get; init; }
}
internal sealed class ModbusProbeDto
{
/// <summary>Gets or sets a value indicating whether probing is enabled.</summary>
public bool? Enabled { get; init; }
/// <summary>Gets or sets the probe interval in milliseconds.</summary>
public int? IntervalMs { get; init; }
/// <summary>Gets or sets the probe timeout in milliseconds.</summary>
public int? TimeoutMs { get; init; }
/// <summary>Gets or sets the probe interval as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? Interval { get; init; }
/// <summary>Gets or sets the probe timeout as a TimeSpan string (the AdminUI form's shape).</summary>
public JsonElement? Timeout { get; init; }
/// <summary>Gets or sets the probe register address.</summary>
public ushort? ProbeAddress { get; init; }
}
}