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.
This commit is contained in:
Joseph Doherty
2026-04-25 00:16:41 -04:00
parent 4cf0b4eb73
commit ad7d811f69
4 changed files with 156 additions and 22 deletions

View File

@@ -16,8 +16,25 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <see cref="PollGroupEngine"/> since Modbus has no native push model.
/// </remarks>
public sealed class ModbusDriver
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IDisposable, IAsyncDisposable
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IPerCallHostResolver, IDisposable, IAsyncDisposable
{
/// <summary>
/// #142 multi-unit-ID gateway support: per-tag UnitId override drives per-slave host
/// name surfacing through this method. The resilience pipeline keys breakers on the
/// returned host string, so a dead RTU slave behind an Ethernet gateway opens its own
/// breaker without tripping siblings on the same TCP socket.
/// </summary>
public string ResolveHost(string fullReference)
{
if (_tagsByName.TryGetValue(fullReference, out var tag))
return BuildSlaveHostName(ResolveUnitId(tag));
// Unknown reference — fall back to driver-instance host (single-slave behaviour).
return HostName;
}
/// <summary>Format a per-slave host string. Multi-slave deployments distinguish breakers by this string.</summary>
private string BuildSlaveHostName(byte unitId) => $"{_options.Host}:{_options.Port}/unit{unitId}";
// Polled subscriptions delegate to the shared PollGroupEngine. The driver only supplies
// the reader + on-change bridge; the engine owns the loop, interval floor, and lifecycle.
private readonly PollGroupEngine _poll;
@@ -235,9 +252,10 @@ public sealed class ModbusDriver
// (we trust the caller-provided MaxCoilsPerRead).
var fc = tag.Region == ModbusRegion.Coils ? (byte)0x01 : (byte)0x02;
var cap = _options.MaxCoilsPerRead == 0 ? (ushort)2000 : _options.MaxCoilsPerRead;
var unitId = ResolveUnitId(tag);
var bitmap = arrayCount <= cap
? await ReadBitBlockAsync(transport, fc, tag.Address, (ushort)arrayCount, ct).ConfigureAwait(false)
: await ReadBitBlockChunkedAsync(transport, fc, tag.Address, arrayCount, cap, ct).ConfigureAwait(false);
? await ReadBitBlockAsync(transport, unitId, fc, tag.Address, (ushort)arrayCount, ct).ConfigureAwait(false)
: await ReadBitBlockChunkedAsync(transport, unitId, fc, tag.Address, arrayCount, cap, ct).ConfigureAwait(false);
return DecodeBitArray(bitmap, arrayCount, tag.ArrayCount.HasValue);
}
case ModbusRegion.HoldingRegisters:
@@ -251,9 +269,10 @@ public sealed class ModbusDriver
// at 128, Mitsubishi Q caps at 64). Scalar non-string tags max out at 4 regs so
// the cap never triggers for them.
var cap = _options.MaxRegistersPerRead == 0 ? (ushort)125 : _options.MaxRegistersPerRead;
var unitId = ResolveUnitId(tag);
var data = totalRegs <= cap
? await ReadRegisterBlockAsync(transport, fc, tag.Address, totalRegs, ct).ConfigureAwait(false)
: await ReadRegisterBlockChunkedAsync(transport, fc, tag.Address, totalRegs, cap, ct).ConfigureAwait(false);
? await ReadRegisterBlockAsync(transport, unitId, fc, tag.Address, totalRegs, ct).ConfigureAwait(false)
: await ReadRegisterBlockChunkedAsync(transport, unitId, fc, tag.Address, totalRegs, cap, ct).ConfigureAwait(false);
if (!tag.ArrayCount.HasValue)
return DecodeRegister(data, tag);
@@ -355,12 +374,15 @@ public sealed class ModbusDriver
}
}
/// <summary>Resolve the UnitId for a tag — per-tag override (#142) or driver-level fallback.</summary>
private byte ResolveUnitId(ModbusTagDefinition tag) => tag.UnitId ?? _options.UnitId;
private async Task<byte[]> ReadRegisterBlockAsync(
IModbusTransport transport, byte fc, ushort address, ushort quantity, CancellationToken ct)
IModbusTransport transport, byte unitId, byte fc, ushort address, ushort quantity, CancellationToken ct)
{
var pdu = new byte[] { fc, (byte)(address >> 8), (byte)(address & 0xFF),
(byte)(quantity >> 8), (byte)(quantity & 0xFF) };
var resp = await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false);
var resp = await transport.SendAsync(unitId, pdu, ct).ConfigureAwait(false);
// resp = [fc][byte-count][data...]
var data = new byte[resp[1]];
Buffer.BlockCopy(resp, 2, data, 0, resp[1]);
@@ -368,11 +390,11 @@ public sealed class ModbusDriver
}
private async Task<byte[]> ReadBitBlockAsync(
IModbusTransport transport, byte fc, ushort address, ushort qty, CancellationToken ct)
IModbusTransport transport, byte unitId, byte fc, ushort address, ushort qty, CancellationToken ct)
{
var pdu = new byte[] { fc, (byte)(address >> 8), (byte)(address & 0xFF),
(byte)(qty >> 8), (byte)(qty & 0xFF) };
var resp = await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false);
var resp = await transport.SendAsync(unitId, pdu, ct).ConfigureAwait(false);
var bitmap = new byte[resp[1]];
Buffer.BlockCopy(resp, 2, bitmap, 0, resp[1]);
return bitmap;
@@ -385,14 +407,14 @@ public sealed class ModbusDriver
/// for a single-chunk response.
/// </summary>
private async Task<byte[]> ReadBitBlockChunkedAsync(
IModbusTransport transport, byte fc, ushort address, int totalBits, ushort cap, CancellationToken ct)
IModbusTransport transport, byte unitId, byte fc, ushort address, int totalBits, ushort cap, CancellationToken ct)
{
var assembled = new byte[(totalBits + 7) / 8];
var done = 0;
while (done < totalBits)
{
var chunk = (ushort)Math.Min(cap, totalBits - done);
var chunkBitmap = await ReadBitBlockAsync(transport, fc, (ushort)(address + done), chunk, ct).ConfigureAwait(false);
var chunkBitmap = await ReadBitBlockAsync(transport, unitId, fc, (ushort)(address + done), chunk, ct).ConfigureAwait(false);
// Re-pack per-chunk LSB-first bits into the assembled bitmap at the right offset.
for (var i = 0; i < chunk; i++)
{
@@ -406,14 +428,14 @@ public sealed class ModbusDriver
}
private async Task<byte[]> ReadRegisterBlockChunkedAsync(
IModbusTransport transport, byte fc, ushort address, ushort totalRegs, ushort cap, CancellationToken ct)
IModbusTransport transport, byte unitId, byte fc, ushort address, ushort totalRegs, ushort cap, CancellationToken ct)
{
var assembled = new byte[totalRegs * 2];
ushort done = 0;
while (done < totalRegs)
{
var chunk = (ushort)Math.Min(cap, totalRegs - done);
var chunkBytes = await ReadRegisterBlockAsync(transport, fc, (ushort)(address + done), chunk, ct).ConfigureAwait(false);
var chunkBytes = await ReadRegisterBlockAsync(transport, unitId, fc, (ushort)(address + done), chunk, ct).ConfigureAwait(false);
Buffer.BlockCopy(chunkBytes, 0, assembled, done * 2, chunkBytes.Length);
done += chunk;
}
@@ -511,7 +533,7 @@ public sealed class ModbusDriver
var on = Convert.ToBoolean(value);
var pdu = new byte[] { 0x05, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF),
on ? (byte)0xFF : (byte)0x00, 0x00 };
await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false);
await transport.SendAsync(ResolveUnitId(tag), pdu, ct).ConfigureAwait(false);
return;
}
// FC15 path: either an explicit array, or UseFC15ForSingleCoilWrites=true forced
@@ -532,7 +554,7 @@ public sealed class ModbusDriver
pdu15[3] = (byte)(qty >> 8); pdu15[4] = (byte)(qty & 0xFF);
pdu15[5] = (byte)byteCount;
Buffer.BlockCopy(bitmap, 0, pdu15, 6, byteCount);
await transport.SendAsync(_options.UnitId, pdu15, ct).ConfigureAwait(false);
await transport.SendAsync(ResolveUnitId(tag), pdu15, ct).ConfigureAwait(false);
return;
}
case ModbusRegion.HoldingRegisters:
@@ -549,7 +571,7 @@ public sealed class ModbusDriver
// PLCs that only accept the multi-write codes.
var pdu = new byte[] { 0x06, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF),
bytes[0], bytes[1] };
await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false);
await transport.SendAsync(ResolveUnitId(tag), pdu, ct).ConfigureAwait(false);
}
else
{
@@ -566,7 +588,7 @@ public sealed class ModbusDriver
pdu[3] = (byte)(qty >> 8); pdu[4] = (byte)(qty & 0xFF);
pdu[5] = (byte)bytes.Length;
Buffer.BlockCopy(bytes, 0, pdu, 6, bytes.Length);
await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false);
await transport.SendAsync(ResolveUnitId(tag), pdu, ct).ConfigureAwait(false);
}
return;
}
@@ -640,7 +662,7 @@ public sealed class ModbusDriver
{
// FC03 read 1 holding register at tag.Address.
var readPdu = new byte[] { 0x03, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF), 0x00, 0x01 };
var readResp = await transport.SendAsync(_options.UnitId, readPdu, ct).ConfigureAwait(false);
var readResp = await transport.SendAsync(ResolveUnitId(tag), readPdu, ct).ConfigureAwait(false);
// resp = [fc][byte-count=2][hi][lo]
var current = (ushort)((readResp[2] << 8) | readResp[3]);
@@ -651,7 +673,7 @@ public sealed class ModbusDriver
// FC06 write single holding register.
var writePdu = new byte[] { 0x06, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF),
(byte)(updated >> 8), (byte)(updated & 0xFF) };
await transport.SendAsync(_options.UnitId, writePdu, ct).ConfigureAwait(false);
await transport.SendAsync(ResolveUnitId(tag), writePdu, ct).ConfigureAwait(false);
}
finally
{

View File

@@ -116,7 +116,8 @@ public static class ModbusDriverFactoryExtensions
: ParseEnum<ModbusStringByteOrder>(t.StringByteOrder, name, driverInstanceId, "StringByteOrder"),
WriteIdempotent: t.WriteIdempotent ?? false,
ArrayCount: parsed.ArrayCount,
Deadband: t.Deadband);
Deadband: t.Deadband,
UnitId: t.UnitId);
}
return new ModbusTagDefinition(
@@ -136,7 +137,8 @@ public static class ModbusDriverFactoryExtensions
: ParseEnum<ModbusStringByteOrder>(t.StringByteOrder, t.Name, driverInstanceId, "StringByteOrder"),
WriteIdempotent: t.WriteIdempotent ?? false,
ArrayCount: t.ArrayCount,
Deadband: t.Deadband);
Deadband: t.Deadband,
UnitId: t.UnitId);
}
private static T ParseEnum<T>(string? raw, string? tagName, string driverInstanceId, string field) where T : struct, Enum
@@ -221,6 +223,7 @@ public static class ModbusDriverFactoryExtensions
public bool? WriteIdempotent { get; init; }
public int? ArrayCount { get; init; }
public double? Deadband { get; init; }
public byte? UnitId { get; init; }
}
internal sealed class ModbusProbeDto

View File

@@ -218,6 +218,13 @@ public sealed class ModbusProbeOptions
/// (Int*, UInt*, Float32, Float64, Bcd*); ignored for Bool / BitInRegister / String /
/// array tags. Default null = no deadband (every change publishes).
/// </param>
/// <param name="UnitId">
/// Per-tag UnitId override for multi-slave gateway topology (#142). When non-null this
/// UnitId is used in the MBAP header instead of the driver-level <c>ModbusDriverOptions.UnitId</c>.
/// Defaults to null = use the driver-level value (preserves single-slave deployments).
/// Tags with different UnitIds belong to different physical slaves and the read planner
/// must NOT coalesce them across slaves — even at the same address.
/// </param>
public sealed record ModbusTagDefinition(
string Name,
ModbusRegion Region,
@@ -230,4 +237,5 @@ public sealed record ModbusTagDefinition(
ModbusStringByteOrder StringByteOrder = ModbusStringByteOrder.HighByteFirst,
bool WriteIdempotent = false,
int? ArrayCount = null,
double? Deadband = null);
double? Deadband = null,
byte? UnitId = null);

View File

@@ -0,0 +1,101 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
/// <summary>
/// #142 multi-unit-ID gateway support: per-tag UnitId override + IPerCallHostResolver +
/// wire-level routing of UnitId in the MBAP header per-PDU.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusMultiUnitTests
{
private sealed class UnitCapturingTransport : IModbusTransport
{
public readonly List<byte> SeenUnitIds = new();
public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
{
SeenUnitIds.Add(unitId);
switch (pdu[0])
{
case 0x03: case 0x04:
{
var qty = (ushort)((pdu[3] << 8) | pdu[4]);
var resp = new byte[2 + qty * 2];
resp[0] = pdu[0]; resp[1] = (byte)(qty * 2);
return Task.FromResult(resp);
}
default: return Task.FromResult(new byte[] { pdu[0], 0, 0 });
}
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
[Fact]
public async Task PerTag_UnitId_Routes_To_Correct_Slave_In_MBAP()
{
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],
Probe = new ModbusProbeOptions { Enabled = false } };
var drv = new ModbusDriver(opts, "m1", _ => fake);
await drv.InitializeAsync("{}", CancellationToken.None);
await drv.ReadAsync(["S1Temp", "S5Temp"], CancellationToken.None);
// Two reads: one for slave 1, one for slave 5. Driver-level UnitId=99 must NOT appear.
fake.SeenUnitIds.ShouldContain((byte)1);
fake.SeenUnitIds.ShouldContain((byte)5);
fake.SeenUnitIds.ShouldNotContain((byte)99);
}
[Fact]
public async Task Tag_Without_UnitId_Falls_Back_To_DriverLevel()
{
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],
Probe = new ModbusProbeOptions { Enabled = false } };
var drv = new ModbusDriver(opts, "m1", _ => fake);
await drv.InitializeAsync("{}", CancellationToken.None);
await drv.ReadAsync(["T"], CancellationToken.None);
fake.SeenUnitIds.ShouldContain((byte)7);
}
[Fact]
public async Task IPerCallHostResolver_Returns_Per_Slave_Host_String()
{
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],
Probe = new ModbusProbeOptions { Enabled = false } };
var drv = new ModbusDriver(opts, "m1", _ => fake);
await drv.InitializeAsync("{}", CancellationToken.None);
// The pipeline keys breakers on these strings; distinct slave IDs must produce distinct
// host strings so per-PLC isolation works.
var resolver = (IPerCallHostResolver)drv;
resolver.ResolveHost("S1Temp").ShouldBe("10.1.2.3:502/unit1");
resolver.ResolveHost("S5Temp").ShouldBe("10.1.2.3:502/unit5");
resolver.ResolveHost("S1Temp").ShouldNotBe(resolver.ResolveHost("S5Temp"));
}
[Fact]
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 = [],
Probe = new ModbusProbeOptions { Enabled = false } };
var drv = new ModbusDriver(opts, "m1", _ => fake);
await drv.InitializeAsync("{}", CancellationToken.None);
var resolver = (IPerCallHostResolver)drv;
resolver.ResolveHost("never-defined").ShouldBe("10.1.2.3:502");
}
}