55ae230fa4
- v2-ci.yml: upload-artifact@v4 -> @v3 + continue-on-error (act_runner reports as GHES and v4 refuses GHES, failing every run); runner-capacity diagnostic step; AKKA_TEST_TIMEFACTOR=3 on the test step. - Runtime/ControlPlane harnesses: akka.test.timefactor from AKKA_TEST_TIMEFACTOR (TestTimeFactor), single-expect-default 15s; ControlPlane gains PresenceBudget. - Leaked spinner threads: the infinite-loop timeout tests (Calculation, Host.IntegrationTests RoslynVirtualTagEvaluator, 3x Core.Scripting) pinned a core for the rest of the test process (abandoned, never stopped). Now a bounded 5 s wall-clock spin; outer compile-inclusive bound 30 s. - Real test races fixed: ScriptedAlarmEngine push-during-drain (Inactive is also the start state + persist-before-update => wait for the Cleared save); DriverReconnectE2e (both nodes host the driver; Created[] is last-writer-wins and ForceReconnect is a no-op while Connecting); ControlPlaneStarterOrder (lost-race heal waited for a 60 s refresh tick). - Fixed sleeps -> poll-for-condition: ReconnectSupervisor LastError, Modbus deadband steps (wait for observed reads), Modbus dispose hygiene precondition, FOCAS probe-loop log. - Short presence budgets -> PresenceBudget in the Runtime/ControlPlane tests seen failing on Gitea; Calculation Settle 10 -> 30 s. No assertion removed, nothing skipped. - infra/README.md §10 CI; stale TreatWarningsAsErrors comment in Directory.Build.props. Claude-Session: https://claude.ai/code/session_01Ef2ozxS7QPanGT8uoATbTe
205 lines
9.9 KiB
C#
205 lines
9.9 KiB
C#
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
|
|
|
/// <summary>
|
|
/// #141 subscribe-side knobs: per-tag Deadband, driver-wide WriteOnChangeOnly.
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class ModbusSubscribeOptionsTests
|
|
{
|
|
/// <summary>
|
|
/// Programmable transport: caller seeds a bank-of-registers value, each FC03 returns
|
|
/// the current value. Lets tests step the underlying register through a sequence and
|
|
/// observe how the deadband filter responds.
|
|
/// </summary>
|
|
private sealed class ProgrammableTransport : IModbusTransport
|
|
{
|
|
public ushort CurrentValue;
|
|
public int WritesSent;
|
|
public int FC06Count;
|
|
public int ReadCount;
|
|
/// <summary>Establishes a connection (no-op for testing).</summary>
|
|
/// <param name="ct">The cancellation token.</param>
|
|
public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
|
|
/// <summary>Sends a Modbus PDU and returns a response.</summary>
|
|
/// <param name="unitId">The Modbus unit ID.</param>
|
|
/// <param name="pdu">The protocol data unit to send.</param>
|
|
/// <param name="ct">The cancellation token.</param>
|
|
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
|
|
{
|
|
switch (pdu[0])
|
|
{
|
|
case 0x03:
|
|
{
|
|
// Counted BEFORE CurrentValue is read, so a read counted after a step saw that step.
|
|
Interlocked.Increment(ref ReadCount);
|
|
var qty = (ushort)((pdu[3] << 8) | pdu[4]);
|
|
var resp = new byte[2 + qty * 2];
|
|
resp[0] = 0x03; resp[1] = (byte)(qty * 2);
|
|
for (var i = 0; i < qty; i++)
|
|
{
|
|
resp[2 + i * 2] = (byte)(CurrentValue >> 8);
|
|
resp[3 + i * 2] = (byte)(CurrentValue & 0xFF);
|
|
}
|
|
return Task.FromResult(resp);
|
|
}
|
|
case 0x06:
|
|
WritesSent++; FC06Count++;
|
|
CurrentValue = (ushort)((pdu[3] << 8) | pdu[4]);
|
|
return Task.FromResult(pdu);
|
|
default:
|
|
return Task.FromResult(new byte[] { pdu[0], 0, 0 });
|
|
}
|
|
}
|
|
/// <summary>Disposes the transport (no-op for testing).</summary>
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
|
|
/// <summary>
|
|
/// Step the register and wait until the poll loop has demonstrably observed it: two FC03 reads
|
|
/// counted after the step. The first may be the one that read the new value; the poll loop is
|
|
/// sequential, so the second cannot start until the first's publish has been raised. Replaces a
|
|
/// fixed 150 ms sleep that, on a loaded CI runner, let a whole step go unpolled — the deadband
|
|
/// test then saw [102, 107] or [100, 107] (#606).
|
|
/// </summary>
|
|
/// <param name="value">The new register value.</param>
|
|
public async Task StepAndObserveAsync(ushort value)
|
|
{
|
|
CurrentValue = value;
|
|
var target = Volatile.Read(ref ReadCount) + 2;
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
while (Volatile.Read(ref ReadCount) < target)
|
|
{
|
|
if (DateTime.UtcNow > deadline)
|
|
throw new TimeoutException($"poll loop did not read register value {value} within 10 s");
|
|
await Task.Delay(5);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Verifies that deadband filter suppresses changes below the threshold.</summary>
|
|
[Fact]
|
|
public async Task Deadband_Suppresses_SubThreshold_Changes()
|
|
{
|
|
var fake = new ProgrammableTransport();
|
|
var tag = new ModbusTagDefinition("Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, Deadband: 5.0);
|
|
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
|
|
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
var publishes = new List<short>();
|
|
drv.OnDataChange += (_, e) => publishes.Add((short)e.Snapshot.Value!);
|
|
|
|
// First publish always passes (no baseline). Then step the value:
|
|
// 100 → 102 (delta 2 < 5, suppressed) → 106 (delta 6 ≥ 5, published) → 107 (delta 1, suppressed).
|
|
var sub = await drv.SubscribeAsync(["Temp"], TimeSpan.FromMilliseconds(50), CancellationToken.None);
|
|
try
|
|
{
|
|
await fake.StepAndObserveAsync(100);
|
|
await fake.StepAndObserveAsync(102);
|
|
await fake.StepAndObserveAsync(106);
|
|
await fake.StepAndObserveAsync(107);
|
|
}
|
|
finally
|
|
{
|
|
await drv.UnsubscribeAsync(sub, CancellationToken.None);
|
|
}
|
|
|
|
// Expect at most 2 distinct values surfaced (100 baseline + 106). The 102 and 107 should
|
|
// be suppressed by the deadband. Ordering can be flaky on slow CI so we assert the set,
|
|
// not the exact sequence.
|
|
publishes.ShouldContain((short)100);
|
|
publishes.ShouldContain((short)106);
|
|
publishes.ShouldNotContain((short)102);
|
|
publishes.ShouldNotContain((short)107);
|
|
}
|
|
|
|
/// <summary>Verifies that null deadband publishes every value change.</summary>
|
|
[Fact]
|
|
public async Task Deadband_Null_Publishes_Every_Change()
|
|
{
|
|
var fake = new ProgrammableTransport();
|
|
var tag = new ModbusTagDefinition("Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16); // no deadband
|
|
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
|
|
var drv = new ModbusDriver(opts, "m1", _ => fake);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
var publishes = new List<short>();
|
|
drv.OnDataChange += (_, e) => publishes.Add((short)e.Snapshot.Value!);
|
|
|
|
var sub = await drv.SubscribeAsync(["Temp"], TimeSpan.FromMilliseconds(50), CancellationToken.None);
|
|
try
|
|
{
|
|
await fake.StepAndObserveAsync(100);
|
|
await fake.StepAndObserveAsync(101); // tiny change still publishes
|
|
}
|
|
finally { await drv.UnsubscribeAsync(sub, CancellationToken.None); }
|
|
|
|
publishes.ShouldContain((short)100);
|
|
publishes.ShouldContain((short)101);
|
|
}
|
|
|
|
/// <summary>Verifies that WriteOnChangeOnly suppresses writes with identical repeated values.</summary>
|
|
[Fact]
|
|
public async Task WriteOnChangeOnly_Suppresses_Identical_Repeated_Writes()
|
|
{
|
|
var fake = new ProgrammableTransport();
|
|
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
|
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), WriteOnChangeOnly = 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);
|
|
await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None); // suppressed
|
|
await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None); // suppressed
|
|
await drv.WriteAsync([new WriteRequest("Sp", (short)43)], CancellationToken.None); // distinct
|
|
|
|
fake.WritesSent.ShouldBe(2, "two distinct values written; identical-value repeats suppressed");
|
|
}
|
|
|
|
/// <summary>Verifies that WriteOnChangeOnly defaults to false and writes all values.</summary>
|
|
[Fact]
|
|
public async Task WriteOnChangeOnly_Default_False_Always_Writes()
|
|
{
|
|
var fake = new ProgrammableTransport();
|
|
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
|
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]),
|
|
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);
|
|
await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None);
|
|
await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None);
|
|
|
|
fake.WritesSent.ShouldBe(3, "default false → every write goes to the wire");
|
|
}
|
|
|
|
/// <summary>Verifies that external reads invalidate the WriteOnChangeOnly cache.</summary>
|
|
[Fact]
|
|
public async Task WriteOnChangeOnly_Cache_Invalidated_By_Read_Divergence()
|
|
{
|
|
var fake = new ProgrammableTransport();
|
|
var tag = new ModbusTagDefinition("Sp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
|
var opts = new ModbusDriverOptions { Host = "f", RawTags = ModbusRawTags.Entries([tag]), WriteOnChangeOnly = 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.FC06Count.ShouldBe(1);
|
|
|
|
// External change at the PLC (panel writes 99). Read sees 99 → invalidates the cache.
|
|
fake.CurrentValue = 99;
|
|
var read = await drv.ReadAsync(["Sp"], CancellationToken.None);
|
|
read[0].Value.ShouldBe((short)99);
|
|
|
|
// Now writing 42 again should NOT be suppressed because the cache was invalidated.
|
|
await drv.WriteAsync([new WriteRequest("Sp", (short)42)], CancellationToken.None);
|
|
fake.FC06Count.ShouldBe(2, "post-divergence write not suppressed");
|
|
}
|
|
}
|