diff --git a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs
index 847efa1..af536fc 100644
--- a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs
+++ b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs
@@ -16,8 +16,25 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// since Modbus has no native push model.
///
public sealed class ModbusDriver
- : IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IDisposable, IAsyncDisposable
+ : IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IPerCallHostResolver, IDisposable, IAsyncDisposable
{
+ ///
+ /// #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.
+ ///
+ 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;
+ }
+
+ /// Format a per-slave host string. Multi-slave deployments distinguish breakers by this string.
+ 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
}
}
+ /// Resolve the UnitId for a tag — per-tag override (#142) or driver-level fallback.
+ private byte ResolveUnitId(ModbusTagDefinition tag) => tag.UnitId ?? _options.UnitId;
+
private async Task 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 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.
///
private async Task 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 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
{
diff --git a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs
index 2b790a7..23e6f6e 100644
--- a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs
+++ b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs
@@ -116,7 +116,8 @@ public static class ModbusDriverFactoryExtensions
: ParseEnum(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(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(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
diff --git a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverOptions.cs b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverOptions.cs
index d9e2ab8..91391c9 100644
--- a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverOptions.cs
+++ b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverOptions.cs
@@ -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).
///
+///
+/// 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 ModbusDriverOptions.UnitId.
+/// 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.
+///
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);
diff --git a/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusMultiUnitTests.cs b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusMultiUnitTests.cs
new file mode 100644
index 0000000..fa1c233
--- /dev/null
+++ b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusMultiUnitTests.cs
@@ -0,0 +1,101 @@
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+
+namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
+
+///
+/// #142 multi-unit-ID gateway support: per-tag UnitId override + IPerCallHostResolver +
+/// wire-level routing of UnitId in the MBAP header per-PDU.
+///
+[Trait("Category", "Unit")]
+public sealed class ModbusMultiUnitTests
+{
+ private sealed class UnitCapturingTransport : IModbusTransport
+ {
+ public readonly List SeenUnitIds = new();
+ public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
+ public Task 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");
+ }
+}