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);

View File

@@ -41,6 +41,10 @@ public static class ModbusDriverFactoryExtensions
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,
AutoReconnect = dto.AutoReconnect ?? true,
Tags = dto.Tags is { Count: > 0 }
? [.. dto.Tags.Select(t => BuildTag(t, driverInstanceId))]
@@ -147,6 +151,10 @@ public static class ModbusDriverFactoryExtensions
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? AutoReconnect { get; init; }
public List<ModbusTagDto>? Tags { get; init; }
public ModbusProbeDto? Probe { get; init; }

View File

@@ -46,6 +46,39 @@ public sealed class ModbusDriverOptions
/// </summary>
public ushort MaxRegistersPerWrite { get; init; } = 123;
/// <summary>
/// Maximum coils per FC01 (Read Coils) / FC02 (Read Discrete Inputs) transaction. Modbus
/// spec allows up to <c>2000</c> bits per request — separate from
/// <see cref="MaxRegistersPerRead"/> because the underlying packing is different
/// (1 bit per coil vs 16 bits per register). Default <c>2000</c>; setting to <c>0</c>
/// disables the cap. The driver auto-chunks coil-array reads above the cap.
/// </summary>
public ushort MaxCoilsPerRead { get; init; } = 2000;
/// <summary>
/// When <c>true</c>, single-element coil writes use FC15 (Write Multiple Coils) with
/// <c>quantity=1</c> instead of the default FC05 (Write Single Coil). Safety / audit
/// PLCs that only accept the multi-write function codes need this. Default <c>false</c>
/// preserves the existing FC05 path.
/// </summary>
public bool UseFC15ForSingleCoilWrites { get; init; } = false;
/// <summary>
/// When <c>true</c>, single-element holding-register writes use FC16 (Write Multiple
/// Registers) with <c>quantity=1</c> instead of the default FC06 (Write Single
/// Register). Same use-case as <see cref="UseFC15ForSingleCoilWrites"/>. Default
/// <c>false</c>.
/// </summary>
public bool UseFC16ForSingleRegisterWrites { get; init; } = false;
/// <summary>
/// Reserved kill-switch for FC23 (Read/Write Multiple Registers). The driver does not
/// currently emit FC23, so this option is a no-op today but exists so future block-read
/// coalescing work that opts into FC23 can be disabled per-deployment without a code
/// change. Default <c>false</c> (FC23 not used either way today).
/// </summary>
public bool DisableFC23 { get; init; } = false;
/// <summary>
/// When <c>true</c> (default) the built-in <see cref="ModbusTcpTransport"/> detects
/// mid-transaction socket failures (<see cref="System.IO.EndOfStreamException"/>,