Files
lmxopcua/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs
Joseph Doherty ad7d811f69 Task #142 — Modbus multi-unit-ID per TCP connection (gateway support)
Lifts the previous "one driver = one slave" assumption so a single Modbus
driver instance can front N RTU slaves behind one Ethernet gateway (Anybus,
ProSoft, Lantronix style). Each tag carries an optional UnitId that drives
the MBAP unit-id byte per-PDU, and the IPerCallHostResolver contract surfaces
per-slave host strings so per-PLC circuit breakers fire per-slave (matches
the AB CIP template documented in docs/v2/multi-host-dispatch.md).

Changes:

- ModbusTagDefinition gains optional UnitId (byte?). Null = use driver-level
  ModbusDriverOptions.UnitId (preserves single-slave deployments verbatim).
- ResolveUnitId(tag) helper computed once per ReadOneAsync / WriteOneAsync
  call; passed through ReadRegisterBlockAsync / ReadBitBlockAsync /
  ReadRegisterBlockChunkedAsync / ReadBitBlockChunkedAsync explicitly. The
  probe loop continues using driver-level UnitId (the probe is a
  connection-health check, not slave-specific).
- ModbusDriver implements IPerCallHostResolver. ResolveHost(fullReference)
  returns "host:port/unitN" — distinct strings per slave so the resilience
  pipeline keys breakers on the right granularity. Unknown references fall
  back to the bare HostName (single-slave behaviour).
- BitInRegister RMW path also threads the per-tag UnitId through both the
  read and write halves so a multi-slave deployment stays correct under bit-
  level writes.
- Factory DTO + JSON binding extended with the per-tag UnitId field.

Tests (4 new ModbusMultiUnitTests):
- Per-tag UnitId routes to the correct slave in the MBAP header (driver-level
  UnitId=99 must NOT appear when both tags override).
- Tag without override falls back to driver-level UnitId.
- IPerCallHostResolver returns distinct "host:port/unitN" strings per slave.
- Unknown reference returns the bare HostName fallback.

Existing 220 unit tests + 107 addressing tests still green. Per-PLC breaker
isolation under simulated dead slaves is verifiable via the existing AB CIP
test infra; live coverage lands as an integration test in the #138 docs/e2e
refresh.
2026-04-25 00:16:41 -04:00

237 lines
11 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
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 (task #248) 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";
public static void Register(DriverFactoryRegistry registry)
{
ArgumentNullException.ThrowIfNull(registry);
registry.Register(DriverTypeName, CreateInstance);
}
internal static ModbusDriver CreateInstance(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 = TimeSpan.FromMilliseconds(dto.TimeoutMs ?? 2_000),
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,
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"),
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")))]
: [],
Probe = new ModbusProbeOptions
{
Enabled = dto.Probe?.Enabled ?? true,
Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000),
Timeout = TimeSpan.FromMilliseconds(dto.Probe?.TimeoutMs ?? 2_000),
ProbeAddress = dto.Probe?.ProbeAddress ?? 0,
},
KeepAlive = dto.KeepAlive is null ? new ModbusKeepAliveOptions() : new ModbusKeepAliveOptions
{
Enabled = dto.KeepAlive.Enabled ?? true,
Time = TimeSpan.FromMilliseconds(dto.KeepAlive.TimeMs ?? 30_000),
Interval = TimeSpan.FromMilliseconds(dto.KeepAlive.IntervalMs ?? 10_000),
RetryCount = dto.KeepAlive.RetryCount ?? 3,
},
IdleDisconnectTimeout = dto.IdleDisconnectMs is { } ms ? TimeSpan.FromMilliseconds(ms) : null,
Reconnect = dto.Reconnect is null ? new ModbusReconnectOptions() : new ModbusReconnectOptions
{
InitialDelay = TimeSpan.FromMilliseconds(dto.Reconnect.InitialDelayMs ?? 0),
MaxDelay = TimeSpan.FromMilliseconds(dto.Reconnect.MaxDelayMs ?? 30_000),
BackoffMultiplier = dto.Reconnect.BackoffMultiplier ?? 2.0,
},
};
return new ModbusDriver(options, driverInstanceId);
}
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.
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}");
return 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);
}
return 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);
}
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
{
public string? Host { get; init; }
public int? Port { get; init; }
public byte? UnitId { get; init; }
public int? TimeoutMs { get; init; }
public ushort? MaxRegistersPerRead { get; init; }
public ushort? MaxRegistersPerWrite { get; init; }
public ushort? MaxCoilsPerRead { get; init; }
public bool? UseFC15ForSingleCoilWrites { get; init; }
public bool? UseFC16ForSingleRegisterWrites { get; init; }
public bool? DisableFC23 { get; init; }
public bool? WriteOnChangeOnly { get; init; }
public string? Family { get; init; }
public string? MelsecSubFamily { get; init; }
public bool? AutoReconnect { get; init; }
public List<ModbusTagDto>? Tags { get; init; }
public ModbusProbeDto? Probe { get; init; }
// #139 connection-layer knobs.
public ModbusKeepAliveDto? KeepAlive { get; init; }
public int? IdleDisconnectMs { get; init; }
public ModbusReconnectDto? Reconnect { get; init; }
}
internal sealed class ModbusKeepAliveDto
{
public bool? Enabled { get; init; }
public int? TimeMs { get; init; }
public int? IntervalMs { get; init; }
public int? RetryCount { get; init; }
}
internal sealed class ModbusReconnectDto
{
public int? InitialDelayMs { get; init; }
public int? MaxDelayMs { get; init; }
public double? BackoffMultiplier { get; init; }
}
internal sealed class ModbusTagDto
{
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:DI"</c>, <c>"C100"</c>.
/// </summary>
public string? AddressString { get; init; }
public string? Region { get; init; }
public ushort? Address { get; init; }
public string? DataType { get; init; }
public bool? Writable { get; init; }
public string? ByteOrder { get; init; }
public byte? BitIndex { get; init; }
public ushort? StringLength { get; init; }
public string? StringByteOrder { get; init; }
public bool? WriteIdempotent { get; init; }
public int? ArrayCount { get; init; }
public double? Deadband { get; init; }
public byte? UnitId { get; init; }
}
internal sealed class ModbusProbeDto
{
public bool? Enabled { get; init; }
public int? IntervalMs { get; init; }
public int? TimeoutMs { get; init; }
public ushort? ProbeAddress { get; init; }
}
}