Task #140 — Modbus protocol-behavior knobs

Adds ModbusDriverOptions knobs that ≥4 of 6 surveyed vendors expose:

1. MaxCoilsPerRead (ushort, default 2000) — separate from MaxRegistersPerRead
   because coil packing (1 bit per coil) and register packing (16 bits each)
   have different spec ceilings. Coil-array reads above the cap auto-chunk
   the same way register reads have always done. New ReadBitBlockChunkedAsync
   re-assembles per-chunk LSB-first bitmaps into one logical bitmap.

2. UseFC15ForSingleCoilWrites (default false) — forces FC15 (Write Multiple
   Coils with quantity=1) for single-coil writes instead of the default FC05
   (Write Single Coil). Safety / audit PLCs that only accept the multi-write
   codes need this.

3. UseFC16ForSingleRegisterWrites (default false) — same idea for FC16 vs
   FC06 on single holding-register writes.

4. DisableFC23 (default false) — placeholder no-op for the future block-read
   coalescing (#143) work that may opt into FC23 (Read/Write Multiple
   Registers). Lets deployments pre-disable FC23 for PLCs that won't accept
   it, before we ship the optimisation that emits it.

Defaults preserve the historical wire output bit-for-bit (FC05/FC06 for
singles, no chunking under 2000 coils, no FC23). Factory DTO + JSON-binding
extended with parallel fields.

6 new ModbusProtocolOptionsTests covering: defaults, FC05→FC15 forcing,
FC06→FC16 forcing, MaxCoilsPerRead chunking math (2500 coils / 2000 cap →
2 reads of 2000 + 500). Existing 209 unit tests still green.
This commit is contained in:
Joseph Doherty
2026-04-24 23:59:04 -04:00
parent 6cf20131fe
commit 55f4044a69
4 changed files with 235 additions and 18 deletions

View File

@@ -175,21 +175,17 @@ public sealed class ModbusDriver
switch (tag.Region)
{
case ModbusRegion.Coils:
{
// Single FC01 read covers either one coil (scalar) or N consecutive coils (array).
var qty = (ushort)arrayCount;
var pdu = new byte[] { 0x01, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF),
(byte)(qty >> 8), (byte)(qty & 0xFF) };
var resp = await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false);
return DecodeBitArray(resp.AsSpan(2, resp[1]), arrayCount, tag.ArrayCount.HasValue);
}
case ModbusRegion.DiscreteInputs:
{
var qty = (ushort)arrayCount;
var pdu = new byte[] { 0x02, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF),
(byte)(qty >> 8), (byte)(qty & 0xFF) };
var resp = await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false);
return DecodeBitArray(resp.AsSpan(2, resp[1]), arrayCount, tag.ArrayCount.HasValue);
// FC01 (Coils) / FC02 (DiscreteInputs). Auto-chunk when array count exceeds the
// coil cap — Modbus spec says ≤ 2000 bits per request; some devices cap lower
// (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 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);
return DecodeBitArray(bitmap, arrayCount, tag.ArrayCount.HasValue);
}
case ModbusRegion.HoldingRegisters:
case ModbusRegion.InputRegisters:
@@ -318,6 +314,44 @@ public sealed class ModbusDriver
return data;
}
private async Task<byte[]> ReadBitBlockAsync(
IModbusTransport transport, 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 bitmap = new byte[resp[1]];
Buffer.BlockCopy(resp, 2, bitmap, 0, resp[1]);
return bitmap;
}
/// <summary>
/// Auto-chunk coil-array reads above MaxCoilsPerRead. Reassembles per-chunk bitmaps into
/// one logical bitmap byte array sized for the full <paramref name="totalBits"/>; the
/// downstream <see cref="DecodeBitArray"/> walks bits LSB-first the same way it would
/// for a single-chunk response.
/// </summary>
private async Task<byte[]> ReadBitBlockChunkedAsync(
IModbusTransport transport, 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);
// Re-pack per-chunk LSB-first bits into the assembled bitmap at the right offset.
for (var i = 0; i < chunk; i++)
{
if (((chunkBitmap[i / 8] >> (i % 8)) & 0x01) == 0) continue;
var dest = done + i;
assembled[dest / 8] |= (byte)(1 << (dest % 8));
}
done += chunk;
}
return assembled;
}
private async Task<byte[]> ReadRegisterBlockChunkedAsync(
IModbusTransport transport, byte fc, ushort address, ushort totalRegs, ushort cap, CancellationToken ct)
{
@@ -395,7 +429,7 @@ public sealed class ModbusDriver
{
case ModbusRegion.Coils:
{
if (!tag.ArrayCount.HasValue)
if (!tag.ArrayCount.HasValue && !_options.UseFC15ForSingleCoilWrites)
{
var on = Convert.ToBoolean(value);
var pdu = new byte[] { 0x05, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF),
@@ -403,8 +437,13 @@ public sealed class ModbusDriver
await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false);
return;
}
// FC15 path: either an explicit array, or UseFC15ForSingleCoilWrites=true forced
// it for a scalar (synthesise a 1-element bool[] from the scalar value).
var arrayLen = tag.ArrayCount ?? 1;
if (!tag.ArrayCount.HasValue)
value = new[] { Convert.ToBoolean(value) };
// FC15 — Write Multiple Coils. Pack the bool[] into LSB-first bitmap.
var values = ToBoolArray(value, tag.ArrayCount.Value, tag.Name);
var values = ToBoolArray(value, arrayLen, tag.Name);
var byteCount = (values.Length + 7) / 8;
var bitmap = new byte[byteCount];
for (var i = 0; i < values.Length; i++)
@@ -425,10 +464,12 @@ public sealed class ModbusDriver
? EncodeRegisterArray(value, tag)
: EncodeRegister(value, tag);
if (bytes.Length == 2 && !tag.ArrayCount.HasValue)
if (bytes.Length == 2 && !tag.ArrayCount.HasValue && !_options.UseFC16ForSingleRegisterWrites)
{
// FC06 fast-path for single-register scalar writes only. Arrays always use FC16
// even when the array is one element wide, because the encoder shape may need it.
// FC06 fast-path for single-register scalar writes only. Arrays always use
// FC16 even when the array is one element wide, because the encoder shape
// may need it. UseFC16ForSingleRegisterWrites=true forces FC16 even here for
// 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);