Task #137 — Modbus per-tag suffix grammar (type / bit / byte-order / array)
Adds the full Wonderware/Kepware/Ignition-style address suffix grammar so users paste tag spreadsheets without per-tag manual translation: <region><offset>[.<bit>][:<type>[<len>]][:<order>][:<count>] Examples that now parse end-to-end: 40001 HoldingRegisters[0], Int16 400001 same, 6-digit form 40001.5 bit 5 of HR[0] 40001:F Float32 (HR[0..1]) 40001:F:CDAB word-swapped Float32 40001:STR20 20-char ASCII string HR1:DI Int32 via mnemonic region C100 Coils[99] (mnemonic) 40001:F:5 Float32[5] array (3-field shorthand) 40001:I:CDAB:10 Int16[10] word-swapped (4-field strict) Driver-side plumbing: - ModbusAddressParser + ParsedModbusAddress in the shared Addressing assembly. 91 parser tests (every grammar variant + malformed shapes). - ModbusDataType / ModbusByteOrder moved to shared (with the same namespace so callers compile unchanged). ModbusByteOrder gains ByteSwap (BADC) and FullReverse (DCBA) alongside the existing BigEndian (ABCD) and WordSwap (CDAB). - NormalizeWordOrder extended to honor all four orders for both 4-byte and 8-byte values. Old WordSwap behavior preserved bit-for-bit. - ModbusTagDefinition gains optional ArrayCount. - ReadOneAsync / WriteOneAsync handle array fan-out: one FC03/04 read covers N consecutive register-typed elements, decoded into a typed array (short[], float[], etc.). Coil arrays use FC01 reads + FC15 writes (FakeTransport in tests gains FC15 support to match). - DriverAttributeInfo IsArray / ArrayDim flow from ArrayCount so the OPC UA address space surfaces ValueRank=1 + ArrayDimensions to clients. - ModbusDriverFactoryExtensions gains AddressString DTO field. When present, the parser drives Region/Address/DataType/ByteOrder/Bit/ StringLength/ArrayCount; structured fields (Writable, WriteIdempotent, StringByteOrder) still come from the DTO. Existing structured tag rows keep working unchanged. Tests: 91 parser unit tests (Driver.Modbus.Addressing.Tests, all green) + 204 driver tests including new ModbusByteOrderTests (BADC/DCBA roundtrips across Int32/Float32/Float64) and ModbusArrayTests (Int16[5], Float32[3] CDAB, Coil[10], length-mismatch error, IsArray/ArrayDim discovery). Solution-wide build clean. Caveat: grammar names (type codes, byte-order mnemonics, the :count shorthand) were synthesized from training-era vendor docs. Verify against current Kepware Modbus Ethernet Driver Help and Ignition Modbus Addressing manuals before freezing for production deployments — naming may need a back-compat layer if vendor wording has shifted.
This commit is contained in:
172
tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusArrayTests.cs
Normal file
172
tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusArrayTests.cs
Normal file
@@ -0,0 +1,172 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Round-trip coverage for #137 array support — read N consecutive registers (or coils)
|
||||
/// and surface them as a typed OPC UA array. Builds on the FakeTransport in
|
||||
/// <see cref="ModbusDriverTests"/>; tests are co-located with the rest of the in-memory
|
||||
/// driver coverage so they all share the same harness.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ModbusArrayTests
|
||||
{
|
||||
private static (ModbusDriver driver, ModbusDriverTests.FakeTransport fake) NewDriver(params ModbusTagDefinition[] tags)
|
||||
{
|
||||
var fake = new ModbusDriverTests.FakeTransport();
|
||||
var opts = new ModbusDriverOptions { Host = "fake", Tags = tags };
|
||||
var drv = new ModbusDriver(opts, "modbus-array", _ => fake);
|
||||
return (drv, fake);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Read_Int16_Array_Returns_Typed_Array()
|
||||
{
|
||||
var tag = new ModbusTagDefinition("Levels", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, ArrayCount: 5);
|
||||
var (drv, fake) = NewDriver(tag);
|
||||
for (var i = 0; i < 5; i++) fake.HoldingRegisters[i] = (ushort)(100 + i);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var values = await drv.ReadAsync(["Levels"], CancellationToken.None);
|
||||
var arr = values[0].Value.ShouldBeOfType<short[]>();
|
||||
arr.ShouldBe(new short[] { 100, 101, 102, 103, 104 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Read_Float32_Array_Returns_Typed_Array_With_WordSwap()
|
||||
{
|
||||
var tag = new ModbusTagDefinition("Temps", ModbusRegion.HoldingRegisters, 10, ModbusDataType.Float32,
|
||||
ArrayCount: 3, ByteOrder: ModbusByteOrder.WordSwap);
|
||||
var (drv, fake) = NewDriver(tag);
|
||||
|
||||
// Pre-encode 3 floats into the fake bank using the matching CDAB layout.
|
||||
// Float 1.5f = 0x3FC00000; word-swap → low word in high reg pair: reg0=0x0000, reg1=0x3FC0.
|
||||
// Loop encodes 1.5, 2.5, 3.5.
|
||||
var src = new[] { 1.5f, 2.5f, 3.5f };
|
||||
for (var i = 0; i < src.Length; i++)
|
||||
{
|
||||
var bytes = BitConverter.GetBytes(src[i]);
|
||||
// BitConverter is little-endian on x86; rearrange to big-endian register pair.
|
||||
// CDAB means: reg(addr+0) holds bytes[1..0] (low word), reg(addr+1) holds bytes[3..2] (high word).
|
||||
fake.HoldingRegisters[10 + i * 2 + 0] = (ushort)((bytes[1] << 8) | bytes[0]);
|
||||
fake.HoldingRegisters[10 + i * 2 + 1] = (ushort)((bytes[3] << 8) | bytes[2]);
|
||||
}
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var values = await drv.ReadAsync(["Temps"], CancellationToken.None);
|
||||
var arr = values[0].Value.ShouldBeOfType<float[]>();
|
||||
arr.ShouldBe(src);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Read_Coil_Array_Returns_Bool_Array()
|
||||
{
|
||||
var tag = new ModbusTagDefinition("Flags", ModbusRegion.Coils, 0, ModbusDataType.Bool, ArrayCount: 10);
|
||||
var (drv, fake) = NewDriver(tag);
|
||||
// alternating pattern: T F T F T F T F T F
|
||||
for (var i = 0; i < 10; i++) fake.Coils[i] = i % 2 == 0;
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var values = await drv.ReadAsync(["Flags"], CancellationToken.None);
|
||||
var arr = values[0].Value.ShouldBeOfType<bool[]>();
|
||||
arr.ShouldBe(new[] { true, false, true, false, true, false, true, false, true, false });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Write_Int16_Array_Lands_Contiguous_In_Bank()
|
||||
{
|
||||
var tag = new ModbusTagDefinition("Setpoints", ModbusRegion.HoldingRegisters, 50, ModbusDataType.Int16, ArrayCount: 4);
|
||||
var (drv, fake) = NewDriver(tag);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var write = new[] { (short)10, (short)20, (short)30, (short)40 };
|
||||
var results = await drv.WriteAsync(
|
||||
new[] { new WriteRequest("Setpoints", write) },
|
||||
CancellationToken.None);
|
||||
|
||||
results[0].StatusCode.ShouldBe(0u);
|
||||
for (var i = 0; i < 4; i++)
|
||||
fake.HoldingRegisters[50 + i].ShouldBe((ushort)write[i]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Write_Coil_Array_Packs_LSB_First()
|
||||
{
|
||||
var tag = new ModbusTagDefinition("Outputs", ModbusRegion.Coils, 0, ModbusDataType.Bool, ArrayCount: 10);
|
||||
var (drv, fake) = NewDriver(tag);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var pattern = new[] { true, true, false, true, false, false, true, false, true, true };
|
||||
var results = await drv.WriteAsync(
|
||||
new[] { new WriteRequest("Outputs", pattern) },
|
||||
CancellationToken.None);
|
||||
|
||||
results[0].StatusCode.ShouldBe(0u);
|
||||
for (var i = 0; i < pattern.Length; i++)
|
||||
fake.Coils[i].ShouldBe(pattern[i]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Write_Array_Mismatch_Length_Surfaces_Error()
|
||||
{
|
||||
var tag = new ModbusTagDefinition("Setpoints", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, ArrayCount: 4);
|
||||
var (drv, _) = NewDriver(tag);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var results = await drv.WriteAsync(
|
||||
new[] { new WriteRequest("Setpoints", new short[] { 1, 2, 3 }) }, // 3 != 4
|
||||
CancellationToken.None);
|
||||
|
||||
results[0].StatusCode.ShouldNotBe(0u);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Discovery_Surfaces_IsArray_And_ArrayDim()
|
||||
{
|
||||
var tag = new ModbusTagDefinition("Vector", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Float32, ArrayCount: 8);
|
||||
var (drv, _) = NewDriver(tag);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var captured = new List<DriverAttributeInfo>();
|
||||
await drv.DiscoverAsync(new RecordingBuilder(captured), CancellationToken.None);
|
||||
|
||||
captured.Count.ShouldBe(1);
|
||||
captured[0].IsArray.ShouldBeTrue();
|
||||
captured[0].ArrayDim.ShouldBe(8u);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Scalar_Tag_Discovery_Stays_NonArray()
|
||||
{
|
||||
// Regression guard: scalar tags must keep IsArray=false / ArrayDim=null.
|
||||
var tag = new ModbusTagDefinition("Single", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
|
||||
var (drv, _) = NewDriver(tag);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
var captured = new List<DriverAttributeInfo>();
|
||||
await drv.DiscoverAsync(new RecordingBuilder(captured), CancellationToken.None);
|
||||
|
||||
captured[0].IsArray.ShouldBeFalse();
|
||||
captured[0].ArrayDim.ShouldBeNull();
|
||||
}
|
||||
|
||||
private sealed class RecordingBuilder(List<DriverAttributeInfo> captured) : IAddressSpaceBuilder
|
||||
{
|
||||
public IAddressSpaceBuilder Folder(string browseName, string displayName) => this;
|
||||
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
||||
{
|
||||
captured.Add(attributeInfo);
|
||||
return new StubHandle(browseName);
|
||||
}
|
||||
public void AddProperty(string browseName, DriverDataType dataType, object? value) { }
|
||||
|
||||
private sealed class StubHandle(string fullRef) : IVariableHandle
|
||||
{
|
||||
public string FullReference => fullRef;
|
||||
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info)
|
||||
=> throw new NotSupportedException("RecordingBuilder doesn't model alarms");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Coverage for the new ByteSwap (BADC) and FullReverse (DCBA) byte orders added by #137.
|
||||
/// The existing BigEndian (ABCD) and WordSwap (CDAB) cases live in <see cref="ModbusDataTypeTests"/>.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ModbusByteOrderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Int32_ByteSwap_decodes_BADC_layout()
|
||||
{
|
||||
// Value 0x12345678. PLC stores bytes within each register swapped:
|
||||
// register[0] = 0x3412, register[1] = 0x7856 → wire [0x34, 0x12, 0x78, 0x56].
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int32,
|
||||
ByteOrder: ModbusByteOrder.ByteSwap);
|
||||
var bytes = new byte[] { 0x34, 0x12, 0x78, 0x56 };
|
||||
ModbusDriver.DecodeRegister(bytes, tag).ShouldBe(0x12345678);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Int32_FullReverse_decodes_DCBA_layout()
|
||||
{
|
||||
// Value 0x12345678 stored fully little-endian:
|
||||
// wire [0x78, 0x56, 0x34, 0x12].
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int32,
|
||||
ByteOrder: ModbusByteOrder.FullReverse);
|
||||
var bytes = new byte[] { 0x78, 0x56, 0x34, 0x12 };
|
||||
ModbusDriver.DecodeRegister(bytes, tag).ShouldBe(0x12345678);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ModbusByteOrder.BigEndian)]
|
||||
[InlineData(ModbusByteOrder.WordSwap)]
|
||||
[InlineData(ModbusByteOrder.ByteSwap)]
|
||||
[InlineData(ModbusByteOrder.FullReverse)]
|
||||
public void Float32_All_ByteOrders_Roundtrip(ModbusByteOrder order)
|
||||
{
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Float32, ByteOrder: order);
|
||||
var wire = ModbusDriver.EncodeRegister(3.14159f, tag);
|
||||
wire.Length.ShouldBe(4);
|
||||
ModbusDriver.DecodeRegister(wire, tag).ShouldBe(3.14159f);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ModbusByteOrder.BigEndian)]
|
||||
[InlineData(ModbusByteOrder.WordSwap)]
|
||||
[InlineData(ModbusByteOrder.ByteSwap)]
|
||||
[InlineData(ModbusByteOrder.FullReverse)]
|
||||
public void Float64_All_ByteOrders_Roundtrip(ModbusByteOrder order)
|
||||
{
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Float64, ByteOrder: order);
|
||||
var wire = ModbusDriver.EncodeRegister(2.718281828459045d, tag);
|
||||
wire.Length.ShouldBe(8);
|
||||
ModbusDriver.DecodeRegister(wire, tag).ShouldBe(2.718281828459045d);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ModbusByteOrder.BigEndian)]
|
||||
[InlineData(ModbusByteOrder.WordSwap)]
|
||||
[InlineData(ModbusByteOrder.ByteSwap)]
|
||||
[InlineData(ModbusByteOrder.FullReverse)]
|
||||
public void Int32_All_ByteOrders_Roundtrip(ModbusByteOrder order)
|
||||
{
|
||||
var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int32, ByteOrder: order);
|
||||
var wire = ModbusDriver.EncodeRegister(unchecked((int)0xDEADBEEF), tag);
|
||||
wire.Length.ShouldBe(4);
|
||||
ModbusDriver.DecodeRegister(wire, tag).ShouldBe(unchecked((int)0xDEADBEEF));
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,11 @@ public sealed class ModbusDriverTests
|
||||
{
|
||||
/// <summary>
|
||||
/// In-memory Modbus TCP server impl that speaks the function codes the driver uses.
|
||||
/// Maintains a register/coil bank so Read/Write round-trips work.
|
||||
/// Maintains a register/coil bank so Read/Write round-trips work. Internal (rather than
|
||||
/// private) so sibling test files in this project can reuse it without duplicating the
|
||||
/// fake.
|
||||
/// </summary>
|
||||
private sealed class FakeTransport : IModbusTransport
|
||||
internal sealed class FakeTransport : IModbusTransport
|
||||
{
|
||||
public readonly ushort[] HoldingRegisters = new ushort[256];
|
||||
public readonly ushort[] InputRegisters = new ushort[256];
|
||||
@@ -35,6 +37,7 @@ public sealed class ModbusDriverTests
|
||||
0x04 => Task.FromResult(ReadRegs(pdu, InputRegisters)),
|
||||
0x05 => Task.FromResult(WriteCoil(pdu)),
|
||||
0x06 => Task.FromResult(WriteSingleReg(pdu)),
|
||||
0x0F => Task.FromResult(WriteMultipleCoils(pdu)),
|
||||
0x10 => Task.FromResult(WriteMultipleRegs(pdu)),
|
||||
_ => Task.FromException<byte[]>(new ModbusException(fc, 0x01, $"fc={fc} not supported by fake")),
|
||||
};
|
||||
@@ -92,6 +95,15 @@ public sealed class ModbusDriverTests
|
||||
return new byte[] { 0x10, pdu[1], pdu[2], pdu[3], pdu[4] };
|
||||
}
|
||||
|
||||
private byte[] WriteMultipleCoils(byte[] pdu)
|
||||
{
|
||||
var addr = (ushort)((pdu[1] << 8) | pdu[2]);
|
||||
var qty = (ushort)((pdu[3] << 8) | pdu[4]);
|
||||
for (var i = 0; i < qty; i++)
|
||||
Coils[addr + i] = ((pdu[6 + (i / 8)] >> (i % 8)) & 0x01) == 1;
|
||||
return new byte[] { 0x0F, pdu[1], pdu[2], pdu[3], pdu[4] };
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user