Two driver-side filters that ≥5 of 6 surveyed vendors expose: 1. Per-tag Deadband (double?, on ModbusTagDefinition) — when set, the PollGroupEngine onChange callback suppresses publishes whose distance from the last-published value is below the threshold. Reduces wire traffic to OPC UA clients on noisy analog signals (flow meters, temperatures). Numeric scalar types only — Bool / BitInRegister / String / array tags publish unconditionally. 2. WriteOnChangeOnly (bool, on ModbusDriverOptions) — when true, the driver short-circuits writes whose value matches the most recent successful write to that tag. Saves PLC bandwidth on clients that re-publish the same setpoint every scan. Cache invalidates on any read that returns a different value, so HMI-side changes don't get masked. Both default off so existing deployments see no behaviour change. Implementation: - ShouldPublish guard wraps the existing OnDataChange invocation. First sample always passes through (no baseline); subsequent samples compare via Convert.ToDouble for the cross-numeric-type math. - IsRedundantWrite check at the top of WriteAsync; on success the cache is populated. Object.Equals handles boxed-numeric equality; arrays are excluded (reference-equality would never match anyway). - ReadAsync invalidates the WriteOnChangeOnly cache when the new value differs from the cached last-written value. Tests (5 new ModbusSubscribeOptionsTests): - Deadband suppresses sub-threshold changes (100 → 102 → 106 → 107 with deadband=5 publishes 100 and 106 only). - Deadband=null still publishes every change. - WriteOnChangeOnly suppresses 3 identical 42 writes (only first hits wire). - WriteOnChangeOnly default false hits the wire every time. - Read-divergence cache invalidation: external panel write to 99, our client's re-write of 42 must NOT be suppressed. 220/220 unit tests green; existing ProtocolOptions tests hardened against probe-loop noise by disabling the probe in their fixtures.
136 lines
6.0 KiB
C#
136 lines
6.0 KiB
C#
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
|
|
|
/// <summary>
|
|
/// #140 protocol-behavior knobs: MaxCoilsPerRead, UseFC15ForSingleCoilWrites,
|
|
/// UseFC16ForSingleRegisterWrites, DisableFC23. Coverage focuses on default behaviour
|
|
/// (no change from pre-#140) and the wire-FC selection when the knobs are flipped.
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class ModbusProtocolOptionsTests
|
|
{
|
|
private sealed class CapturingTransport : IModbusTransport
|
|
{
|
|
public readonly List<byte[]> Sent = new();
|
|
public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
|
|
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
|
|
{
|
|
Sent.Add(pdu);
|
|
// Return a minimal valid response per FC. We zero-fill the data slot but size it
|
|
// correctly so the driver's bitmap walker doesn't IndexOutOfRange on chunked reads.
|
|
switch (pdu[0])
|
|
{
|
|
case 0x05: case 0x06: case 0x0F: case 0x10:
|
|
return Task.FromResult(pdu); // echo
|
|
case 0x01: case 0x02:
|
|
{
|
|
var qty = (ushort)((pdu[3] << 8) | pdu[4]);
|
|
var byteCount = (byte)((qty + 7) / 8);
|
|
var resp = new byte[2 + byteCount];
|
|
resp[0] = pdu[0]; resp[1] = byteCount;
|
|
return Task.FromResult(resp);
|
|
}
|
|
case 0x03: case 0x04:
|
|
{
|
|
var qty = (ushort)((pdu[3] << 8) | pdu[4]);
|
|
var byteCount = (byte)(qty * 2);
|
|
var resp = new byte[2 + byteCount];
|
|
resp[0] = pdu[0]; resp[1] = byteCount;
|
|
return Task.FromResult(resp);
|
|
}
|
|
default:
|
|
return Task.FromResult(new byte[] { pdu[0], 0, 0 });
|
|
}
|
|
}
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|
|
|
|
[Fact]
|
|
public void Defaults_Match_Historical_Behaviour()
|
|
{
|
|
var opts = new ModbusDriverOptions();
|
|
opts.MaxCoilsPerRead.ShouldBe((ushort)2000);
|
|
opts.UseFC15ForSingleCoilWrites.ShouldBeFalse();
|
|
opts.UseFC16ForSingleRegisterWrites.ShouldBeFalse();
|
|
opts.DisableFC23.ShouldBeFalse();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Single_Coil_Write_Uses_FC05_By_Default()
|
|
{
|
|
var fake = new CapturingTransport();
|
|
var tag = new ModbusTagDefinition("Run", ModbusRegion.Coils, 0, ModbusDataType.Bool);
|
|
var drv = new ModbusDriver(new ModbusDriverOptions { Host = "f", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } }, "m1", _ => fake);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
await drv.WriteAsync([new WriteRequest("Run", true)], CancellationToken.None);
|
|
|
|
fake.Sent.Last()[0].ShouldBe((byte)0x05); // FC05 Write Single Coil
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Single_Coil_Write_Uses_FC15_When_Forced()
|
|
{
|
|
var fake = new CapturingTransport();
|
|
var tag = new ModbusTagDefinition("Run", ModbusRegion.Coils, 0, ModbusDataType.Bool);
|
|
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], UseFC15ForSingleCoilWrites = true, Probe = new ModbusProbeOptions { Enabled = false } };
|
|
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
await drv.WriteAsync([new WriteRequest("Run", true)], CancellationToken.None);
|
|
|
|
fake.Sent.Last()[0].ShouldBe((byte)0x0F); // FC15 Write Multiple Coils
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Single_Register_Write_Uses_FC06_By_Default()
|
|
{
|
|
var fake = new CapturingTransport();
|
|
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
|
var drv = new ModbusDriver(new ModbusDriverOptions { Host = "f", Tags = [tag], Probe = new ModbusProbeOptions { Enabled = false } }, "m1", _ => fake);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None);
|
|
|
|
fake.Sent.Last()[0].ShouldBe((byte)0x06); // FC06 Write Single Register
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Single_Register_Write_Uses_FC16_When_Forced()
|
|
{
|
|
var fake = new CapturingTransport();
|
|
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
|
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], UseFC16ForSingleRegisterWrites = true, Probe = new ModbusProbeOptions { Enabled = false } };
|
|
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None);
|
|
|
|
fake.Sent.Last()[0].ShouldBe((byte)0x10); // FC16 Write Multiple Registers
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Coil_Array_Read_Auto_Chunks_At_MaxCoilsPerRead()
|
|
{
|
|
var fake = new CapturingTransport();
|
|
// 2500 coils with cap 2000 → 2 reads (2000 + 500).
|
|
var tag = new ModbusTagDefinition("Big", ModbusRegion.Coils, 0, ModbusDataType.Bool, ArrayCount: 2500);
|
|
var opts = new ModbusDriverOptions { Host = "f", Tags = [tag], MaxCoilsPerRead = 2000, Probe = new ModbusProbeOptions { Enabled = false } };
|
|
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
await drv.ReadAsync(["Big"], CancellationToken.None);
|
|
|
|
// Ignore the probe FC03 from InitializeAsync; count only FC01 reads.
|
|
var fc01s = fake.Sent.Where(p => p[0] == 0x01).ToList();
|
|
fc01s.Count.ShouldBe(2);
|
|
// First chunk asks for 2000.
|
|
((ushort)((fc01s[0][3] << 8) | fc01s[0][4])).ShouldBe((ushort)2000);
|
|
// Second chunk asks for 500.
|
|
((ushort)((fc01s[1][3] << 8) | fc01s[1][4])).ShouldBe((ushort)500);
|
|
}
|
|
}
|