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.
173 lines
7.3 KiB
C#
173 lines
7.3 KiB
C#
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");
|
|
}
|
|
}
|
|
}
|