From 850b816873991dbfa42e4d2e4f411d4c5b755c1c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Fri, 24 Apr 2026 23:49:22 -0400 Subject: [PATCH] =?UTF-8?q?Task=20#137=20=E2=80=94=20Modbus=20per-tag=20su?= =?UTF-8?q?ffix=20grammar=20(type=20/=20bit=20/=20byte-order=20/=20array)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the full Wonderware/Kepware/Ignition-style address suffix grammar so users paste tag spreadsheets without per-tag manual translation: [.][:[]][:][:] 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. --- .../ModbusAddressParser.cs | 334 ++++++++++++++++++ .../ModbusDataType.cs | 95 +++++ .../ModbusDriver.cs | 259 ++++++++++++-- .../ModbusDriverFactoryExtensions.cs | 50 ++- .../ModbusDriverOptions.cs | 63 +--- .../ModbusAddressParserTests.cs | 276 +++++++++++++++ .../ModbusArrayTests.cs | 172 +++++++++ .../ModbusByteOrderTests.cs | 73 ++++ .../ModbusDriverTests.cs | 16 +- 9 files changed, 1246 insertions(+), 92 deletions(-) create mode 100644 src/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs create mode 100644 src/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusDataType.cs create mode 100644 tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests/ModbusAddressParserTests.cs create mode 100644 tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusArrayTests.cs create mode 100644 tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusByteOrderTests.cs diff --git a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs new file mode 100644 index 0000000..477bb94 --- /dev/null +++ b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs @@ -0,0 +1,334 @@ +using System.Globalization; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus; + +/// +/// Parses the full Modbus tag-address grammar: +/// <region><offset>[.<bit>][:<type>[<len>]][:<order>][:<count>]. +/// Output is a the driver-side config layer maps onto a +/// ModbusTagDefinition. +/// +/// +/// +/// The grammar mirrors industry conventions (Wonderware suffix style, Kepware/Modicon +/// digit prefixes, Ignition mnemonic prefixes — all accepted) so users can paste tag +/// spreadsheets from any of those tools without per-tag manual translation. +/// +/// +/// Examples: +/// +/// 40001 — HoldingRegisters[0], Int16 (default). +/// 400001 — HoldingRegisters[0], Int16 (6-digit form). +/// 40001.5 — bit 5 of HoldingRegisters[0]. +/// 40001:F — Float32 starting at HR[0] (consumes HR[0..1]). +/// 40001:F:CDAB — same with word-swap byte order. +/// 40001:STR20 — 20-char ASCII string. +/// HR1:DI — Int32 at HR[0] using mnemonic region. +/// 40001:F:5 — Float32[5] array (consumes HR[0..9]). +/// 40001:I::10 — Int16[10] using default byte order (empty order field). +/// C100 — Coils[99] (mnemonic). +/// +/// +/// +public static class ModbusAddressParser +{ + /// Parse an address string. Throws on invalid input. + public static ParsedModbusAddress Parse(string address) + { + if (TryParse(address, out var parsed, out var error)) + return parsed!; + throw new FormatException(error); + } + + /// + /// Try-parse variant for config-bind paths that surface diagnostics rather than throw. + /// is null and non-null on failure. + /// + public static bool TryParse(string? address, out ParsedModbusAddress? result, out string? error) + { + result = null; + + if (string.IsNullOrWhiteSpace(address)) + { + error = "Modbus address is null or empty"; + return false; + } + + var s = address.Trim(); + + // Split on ':' — the fields are: [.bit] :type :order :count. + // Empty fields (e.g. "40001:I::5") are allowed and mean "use default." + var parts = s.Split(':'); + if (parts.Length > 4) + { + error = $"Modbus address has too many ':'-separated fields ({parts.Length} > 4): '{address}'"; + return false; + } + + var addressPart = parts[0]; + var typePart = parts.Length > 1 ? parts[1] : null; + string? orderPart = null; + string? countPart = null; + + // 3-field form is shorthand: ::. X is either a byte-order mnemonic + // (4 letters — ABCD/CDAB/BADC/DCBA) or an array count (digits). Disambiguate by shape + // so users can write 40001:F:5 for Float[5] without the awkward 40001:F::5. Anything + // else surfaces a clear error in whichever slot it lands. + if (parts.Length == 3) + { + if (LooksLikeByteOrderToken(parts[2])) orderPart = parts[2]; + else if (parts[2].All(char.IsDigit)) countPart = parts[2]; + else + { + error = $"3rd field '{parts[2]}' must be a 4-letter byte order (ABCD/CDAB/BADC/DCBA) or a positive integer array count in '{address}'"; + return false; + } + } + else if (parts.Length == 4) + { + orderPart = parts[2]; + countPart = parts[3]; + } + + if (!TryParseRegionAndOffset(addressPart, out var region, out var offset, out var bit, out error)) + return false; + + // Type field — defaults: Bool for Coils/DiscreteInputs, Int16 for InputRegisters/HoldingRegisters, + // BitInRegister when bit-suffix is present. + ModbusDataType dataType; + ushort stringLen = 0; + + if (bit.HasValue) + { + // Bit suffix forces BitInRegister; explicit type would conflict. + if (!string.IsNullOrEmpty(typePart)) + { + error = $"Bit suffix '.{bit.Value}' cannot combine with explicit type ':{typePart}' in '{address}'"; + return false; + } + dataType = ModbusDataType.BitInRegister; + } + else if (string.IsNullOrEmpty(typePart)) + { + dataType = region is ModbusRegion.Coils or ModbusRegion.DiscreteInputs + ? ModbusDataType.Bool + : ModbusDataType.Int16; + } + else + { + if (!TryParseType(typePart, out dataType, out stringLen, out error)) + return false; + } + + // Region/type compatibility check — Coils and DiscreteInputs only carry Bool semantics. + if (region is ModbusRegion.Coils or ModbusRegion.DiscreteInputs && dataType != ModbusDataType.Bool) + { + error = $"Region {region} only supports Bool-typed tags; got {dataType} in '{address}'"; + return false; + } + + // Order field — defaults to BigEndian; only meaningful for multi-register types. + var order = ModbusByteOrder.BigEndian; + if (!string.IsNullOrEmpty(orderPart)) + { + if (!TryParseByteOrder(orderPart, out order, out error)) + return false; + } + + // Count field — array length. Bit + array is rejected. + int? arrayCount = null; + if (!string.IsNullOrEmpty(countPart)) + { + if (bit.HasValue) + { + error = $"Bit suffix and array count cannot combine in '{address}'"; + return false; + } + if (!int.TryParse(countPart, NumberStyles.None, CultureInfo.InvariantCulture, out var parsedCount) || parsedCount < 1) + { + error = $"Array count must be a positive integer; got '{countPart}' in '{address}'"; + return false; + } + arrayCount = parsedCount; + } + + result = new ParsedModbusAddress(region, offset, bit, dataType, stringLen, order, arrayCount); + error = null; + return true; + } + + private static bool TryParseRegionAndOffset(string text, out ModbusRegion region, out ushort offset, out byte? bit, out string? error) + { + region = default; + offset = 0; + bit = null; + + if (string.IsNullOrEmpty(text)) + { + error = "Region/offset segment is empty"; + return false; + } + + // Optional bit suffix: '.N' at the end, N in 0..15. Strip before parsing region/offset. + var dotIdx = text.IndexOf('.'); + var addrText = dotIdx < 0 ? text : text[..dotIdx]; + if (dotIdx >= 0) + { + var bitText = text[(dotIdx + 1)..]; + if (!byte.TryParse(bitText, NumberStyles.None, CultureInfo.InvariantCulture, out var bitVal) || bitVal > 15) + { + error = $"Bit index must be 0..15; got '{bitText}'"; + return false; + } + bit = bitVal; + } + + // Try mnemonic prefix first (HR, IR, C, DI). Cheaper than the digit branch and + // unambiguous when present. DI must be checked before D — we don't currently use D + // alone but stay defensive. + if (TryParseMnemonicAddress(addrText, out region, out offset, out error)) + return true; + + // Fall back to Modicon (5/6-digit). Reuses #136's parser. + if (ModbusModiconAddress.TryParse(addrText, out region, out offset, out error)) + return true; + + // Both branches failed; the Modicon error is the more specific diagnostic. + return false; + } + + private static bool TryParseMnemonicAddress(string text, out ModbusRegion region, out ushort offset, out string? error) + { + region = default; + offset = 0; + error = null; + + // Mnemonic = letter prefix + 1-based register number. We require pure-digit suffix + // after the prefix; anything else (including the Modicon-digit forms) falls through + // to the Modicon parser. + (string Prefix, ModbusRegion Region)[] candidates = + [ + ("HR", ModbusRegion.HoldingRegisters), + ("IR", ModbusRegion.InputRegisters), + ("DI", ModbusRegion.DiscreteInputs), + ("C", ModbusRegion.Coils), + ]; + + foreach (var (prefix, mnemonicRegion) in candidates) + { + if (!text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; + var rest = text[prefix.Length..]; + if (rest.Length == 0 || !rest.All(char.IsDigit)) + { + // Prefix matched but body is non-numeric — not a mnemonic address. + continue; + } + if (!int.TryParse(rest, NumberStyles.None, CultureInfo.InvariantCulture, out var n) || n < 1 || n > 65536) + { + error = $"Mnemonic register number must be 1..65536; got '{rest}'"; + return false; + } + region = mnemonicRegion; + offset = (ushort)(n - 1); + return true; + } + + return false; + } + + private static bool TryParseType(string text, out ModbusDataType type, out ushort stringLen, out string? error) + { + type = default; + stringLen = 0; + error = null; + + // STR — string length glued to the type code. + if (text.StartsWith("STR", StringComparison.OrdinalIgnoreCase)) + { + var lenText = text[3..]; + if (lenText.Length == 0) + { + error = "STR type requires a length: STR"; + return false; + } + if (!ushort.TryParse(lenText, NumberStyles.None, CultureInfo.InvariantCulture, out var len) || len < 1) + { + error = $"STR length must be a positive integer; got '{lenText}'"; + return false; + } + type = ModbusDataType.String; + stringLen = len; + return true; + } + + type = text.ToUpperInvariant() switch + { + "BOOL" => ModbusDataType.Bool, + "I" => ModbusDataType.Int16, + "UI" => ModbusDataType.UInt16, + "DI" or "L" => ModbusDataType.Int32, + "UDI" or "UL" => ModbusDataType.UInt32, + "LI" => ModbusDataType.Int64, + "ULI" => ModbusDataType.UInt64, + "F" => ModbusDataType.Float32, + "D" => ModbusDataType.Float64, + "BCD" => ModbusDataType.Bcd16, + "LBCD" => ModbusDataType.Bcd32, + _ => (ModbusDataType)(-1), + }; + + if ((int)type == -1) + { + error = $"Unknown type code '{text}'. Valid: BOOL, I, UI, DI, L, UDI, UL, LI, ULI, F, D, BCD, LBCD, STR"; + return false; + } + + return true; + } + + private static bool LooksLikeByteOrderToken(string text) => + text.Length == 4 && text.All(char.IsLetter); + + private static bool TryParseByteOrder(string text, out ModbusByteOrder order, out string? error) + { + order = ModbusByteOrder.BigEndian; + error = null; + + order = text.ToUpperInvariant() switch + { + "ABCD" => ModbusByteOrder.BigEndian, + "CDAB" => ModbusByteOrder.WordSwap, + "BADC" => ModbusByteOrder.ByteSwap, + "DCBA" => ModbusByteOrder.FullReverse, + _ => (ModbusByteOrder)(-1), + }; + + if ((int)order == -1) + { + error = $"Unknown byte order '{text}'. Valid: ABCD, CDAB, BADC, DCBA"; + return false; + } + + return true; + } +} + +/// +/// Result of parsing a Modbus tag-address string. Maps directly onto the driver-side +/// ModbusTagDefinition at config-bind time. +/// +/// Coils / DiscreteInputs / InputRegisters / HoldingRegisters. +/// Zero-based PDU offset. +/// When non-null, the tag is a single-bit-in-register selector (0..15). +/// Inferred from explicit type code or region default. +/// Character count for ; zero otherwise. +/// Word/byte ordering for multi-register types. +/// Element count when the tag is an array; null for scalars. +public sealed record ParsedModbusAddress( + ModbusRegion Region, + ushort Offset, + byte? Bit, + ModbusDataType DataType, + ushort StringLength, + ModbusByteOrder ByteOrder, + int? ArrayCount); diff --git a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusDataType.cs b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusDataType.cs new file mode 100644 index 0000000..2fce635 --- /dev/null +++ b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusDataType.cs @@ -0,0 +1,95 @@ +namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus; + +/// +/// The set of value types a Modbus tag can decode to. Each type implies a fixed +/// register-count: / / / +/// / = 1 register; / +/// / / = 2 registers; +/// / / = 4 registers; +/// = ceil(StringLength / 2) registers. +/// +/// +/// Lives in the shared addressing assembly (alongside ) so the +/// Admin UI and the parser can speak about value types without taking a transport-layer +/// dependency on the wire driver. +/// +public enum ModbusDataType +{ + Bool, + Int16, + UInt16, + Int32, + UInt32, + Int64, + UInt64, + Float32, + Float64, + /// Single bit within a holding register. BitIndex selects 0-15 LSB-first. + BitInRegister, + /// ASCII string packed 2 chars per register, StringLength characters long. + String, + /// + /// 16-bit binary-coded decimal. Each nibble encodes one decimal digit (0-9). Register + /// value 0x1234 decodes as decimal 1234 — NOT binary 0x04D2 = 4660. + /// DL205/DL260 and several Mitsubishi / Omron families store timers, counters, and + /// operator-facing numerics as BCD by default. + /// + Bcd16, + /// + /// 32-bit (two-register) BCD. Decodes 8 decimal digits. Word ordering follows the tag's + /// the same way does. + /// + Bcd32, +} + +/// +/// Word/byte ordering for multi-register types. The four-letter mnemonic refers to the +/// order in which bytes A, B, C, D appear on the wire when decoding a 4-byte value (e.g. +/// a Float32) from two consecutive 16-bit registers. +/// +/// +/// +/// (ABCD) is the Modbus-spec default: high word at lower +/// address, big-endian within each register. +/// +/// +/// (CDAB): keeps bytes big-endian within each register +/// but swaps the word pair. Common on Siemens S7 over Modbus, Allen-Bradley, several +/// Modicon families. +/// +/// +/// (BADC): keeps the word pair in spec order but swaps +/// bytes within each register. Encountered on a handful of legacy controllers exposing +/// little-endian internals through Modbus. +/// +/// +/// (DCBA): full byte reversal — equivalent to reading +/// the value as little-endian. Some industrial PCs and gateways that bridge CAN / +/// EtherNet/IP into Modbus surface their backplane order this way. +/// +/// +/// For 8-byte (Int64 / UInt64 / Float64) values the same A/B/C/D semantics apply +/// pairwise across the four registers; the implementation is straight-line. +/// +/// +public enum ModbusByteOrder +{ + BigEndian, + WordSwap, + ByteSwap, + FullReverse, +} + +/// +/// Per-register byte order for ASCII strings packed 2 chars per register. Standard Modbus +/// convention is — the first character of each pair occupies +/// the high byte of the register. AutomationDirect DirectLOGIC (DL205, DL260, DL350) and a +/// handful of legacy controllers pack , which inverts that within +/// each register. Word ordering across multiple registers is always ascending address for +/// strings — only the byte order inside each register flips. +/// +public enum ModbusStringByteOrder +{ + HighByteFirst, + LowByteFirst, +} diff --git a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs index 2b17486..5a3979b 100644 --- a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs +++ b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs @@ -117,8 +117,8 @@ public sealed class ModbusDriver folder.Variable(t.Name, t.Name, new DriverAttributeInfo( FullName: t.Name, DriverDataType: MapDataType(t.DataType), - IsArray: false, - ArrayDim: null, + IsArray: t.ArrayCount.HasValue, + ArrayDim: t.ArrayCount.HasValue ? (uint)t.ArrayCount.Value : null, SecurityClass: t.Writable ? SecurityClassification.Operate : SecurityClassification.ViewOnly, IsHistorized: false, IsAlarm: false, @@ -166,40 +166,142 @@ public sealed class ModbusDriver private async Task ReadOneAsync(IModbusTransport transport, ModbusTagDefinition tag, CancellationToken ct) { + var arrayCount = tag.ArrayCount ?? 1; + switch (tag.Region) { case ModbusRegion.Coils: { - var pdu = new byte[] { 0x01, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF), 0x00, 0x01 }; + // 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 (resp[2] & 0x01) == 1; + return DecodeBitArray(resp.AsSpan(2, resp[1]), arrayCount, tag.ArrayCount.HasValue); } case ModbusRegion.DiscreteInputs: { - var pdu = new byte[] { 0x02, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF), 0x00, 0x01 }; + 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 (resp[2] & 0x01) == 1; + return DecodeBitArray(resp.AsSpan(2, resp[1]), arrayCount, tag.ArrayCount.HasValue); } case ModbusRegion.HoldingRegisters: case ModbusRegion.InputRegisters: { - var quantity = RegisterCount(tag); + var elementRegs = RegisterCount(tag); + var totalRegs = (ushort)(elementRegs * arrayCount); var fc = tag.Region == ModbusRegion.HoldingRegisters ? (byte)0x03 : (byte)0x04; // Auto-chunk when the tag's register span exceeds the caller-configured cap. - // Affects long strings (FC03/04 > 125 regs is spec-forbidden; DL205 caps at 128, - // Mitsubishi Q caps at 64). Non-string tags max out at 4 regs so the cap never - // triggers for numerics. + // Affects long strings + arrays (FC03/04 > 125 regs is spec-forbidden; DL205 caps + // at 128, Mitsubishi Q caps at 64). Scalar non-string tags max out at 4 regs so + // the cap never triggers for them. var cap = _options.MaxRegistersPerRead == 0 ? (ushort)125 : _options.MaxRegistersPerRead; - var data = quantity <= cap - ? await ReadRegisterBlockAsync(transport, fc, tag.Address, quantity, ct).ConfigureAwait(false) - : await ReadRegisterBlockChunkedAsync(transport, fc, tag.Address, quantity, cap, ct).ConfigureAwait(false); - return DecodeRegister(data, tag); + var data = totalRegs <= cap + ? await ReadRegisterBlockAsync(transport, fc, tag.Address, totalRegs, ct).ConfigureAwait(false) + : await ReadRegisterBlockChunkedAsync(transport, fc, tag.Address, totalRegs, cap, ct).ConfigureAwait(false); + + if (!tag.ArrayCount.HasValue) + return DecodeRegister(data, tag); + + return DecodeRegisterArray(data, tag, elementRegs, arrayCount); } default: throw new InvalidOperationException($"Unknown region {tag.Region}"); } } + /// + /// Decode an FC01/FC02 coil-bitmap response into either a single bool (scalar tag) or a + /// bool[] of elements (array tag). Modbus packs coils LSB-first + /// within each byte, ascending address across bytes. + /// + private static object DecodeBitArray(ReadOnlySpan bitmap, int count, bool isArray) + { + if (!isArray) return (bitmap[0] & 0x01) == 1; + var result = new bool[count]; + for (var i = 0; i < count; i++) + result[i] = ((bitmap[i / 8] >> (i % 8)) & 0x01) == 1; + return result; + } + + /// + /// Decode an array of register-backed values from a contiguous block. Each element + /// occupies registers and is decoded with the same + /// codec the scalar path uses, sliced from its position in the block. + /// + private static object DecodeRegisterArray(byte[] data, ModbusTagDefinition tag, int elementRegs, int count) + { + var elementBytes = elementRegs * 2; + // Element type drives the array CLR type. Boxed into Array so the Read pipeline can + // surface it directly without a per-call type-switch on the caller side. + switch (tag.DataType) + { + case ModbusDataType.Int16: + { + var arr = new short[count]; + for (var i = 0; i < count; i++) + arr[i] = (short)DecodeRegister(data.AsSpan(i * elementBytes, elementBytes), tag); + return arr; + } + case ModbusDataType.UInt16: + { + var arr = new ushort[count]; + for (var i = 0; i < count; i++) + arr[i] = (ushort)DecodeRegister(data.AsSpan(i * elementBytes, elementBytes), tag); + return arr; + } + case ModbusDataType.Int32: + case ModbusDataType.Bcd16: + case ModbusDataType.Bcd32: + { + var arr = new int[count]; + for (var i = 0; i < count; i++) + arr[i] = (int)DecodeRegister(data.AsSpan(i * elementBytes, elementBytes), tag); + return arr; + } + case ModbusDataType.UInt32: + { + var arr = new uint[count]; + for (var i = 0; i < count; i++) + arr[i] = (uint)DecodeRegister(data.AsSpan(i * elementBytes, elementBytes), tag); + return arr; + } + case ModbusDataType.Int64: + { + var arr = new long[count]; + for (var i = 0; i < count; i++) + arr[i] = (long)DecodeRegister(data.AsSpan(i * elementBytes, elementBytes), tag); + return arr; + } + case ModbusDataType.UInt64: + { + var arr = new ulong[count]; + for (var i = 0; i < count; i++) + arr[i] = (ulong)DecodeRegister(data.AsSpan(i * elementBytes, elementBytes), tag); + return arr; + } + case ModbusDataType.Float32: + { + var arr = new float[count]; + for (var i = 0; i < count; i++) + arr[i] = (float)DecodeRegister(data.AsSpan(i * elementBytes, elementBytes), tag); + return arr; + } + case ModbusDataType.Float64: + { + var arr = new double[count]; + for (var i = 0; i < count; i++) + arr[i] = (double)DecodeRegister(data.AsSpan(i * elementBytes, elementBytes), tag); + return arr; + } + default: + throw new InvalidOperationException( + $"Array decode not supported for {tag.DataType} (use scalar tags or split by element)"); + } + } + private async Task ReadRegisterBlockAsync( IModbusTransport transport, byte fc, ushort address, ushort quantity, CancellationToken ct) { @@ -289,30 +391,53 @@ public sealed class ModbusDriver { case ModbusRegion.Coils: { - var on = Convert.ToBoolean(value); - var pdu = new byte[] { 0x05, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF), - on ? (byte)0xFF : (byte)0x00, 0x00 }; - await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false); + if (!tag.ArrayCount.HasValue) + { + var on = Convert.ToBoolean(value); + var pdu = new byte[] { 0x05, (byte)(tag.Address >> 8), (byte)(tag.Address & 0xFF), + on ? (byte)0xFF : (byte)0x00, 0x00 }; + await transport.SendAsync(_options.UnitId, pdu, ct).ConfigureAwait(false); + return; + } + // FC15 — Write Multiple Coils. Pack the bool[] into LSB-first bitmap. + var values = ToBoolArray(value, tag.ArrayCount.Value, tag.Name); + var byteCount = (values.Length + 7) / 8; + var bitmap = new byte[byteCount]; + for (var i = 0; i < values.Length; i++) + if (values[i]) bitmap[i / 8] |= (byte)(1 << (i % 8)); + var qty = (ushort)values.Length; + var pdu15 = new byte[6 + 1 + byteCount]; + pdu15[0] = 0x0F; + pdu15[1] = (byte)(tag.Address >> 8); pdu15[2] = (byte)(tag.Address & 0xFF); + pdu15[3] = (byte)(qty >> 8); pdu15[4] = (byte)(qty & 0xFF); + pdu15[5] = (byte)byteCount; + Buffer.BlockCopy(bitmap, 0, pdu15, 6, byteCount); + await transport.SendAsync(_options.UnitId, pdu15, ct).ConfigureAwait(false); return; } case ModbusRegion.HoldingRegisters: { - var bytes = EncodeRegister(value, tag); - if (bytes.Length == 2) + var bytes = tag.ArrayCount.HasValue + ? EncodeRegisterArray(value, tag) + : EncodeRegister(value, tag); + + if (bytes.Length == 2 && !tag.ArrayCount.HasValue) { + // 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. 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); } else { - // FC 16 (Write Multiple Registers) for 32-bit types. + // FC 16 (Write Multiple Registers) for 32-bit / 64-bit / array / string types. var qty = (ushort)(bytes.Length / 2); var writeCap = _options.MaxRegistersPerWrite == 0 ? (ushort)123 : _options.MaxRegistersPerWrite; if (qty > writeCap) throw new InvalidOperationException( $"Write of {qty} registers to {tag.Name} exceeds MaxRegistersPerWrite={writeCap}. " + - $"Split the tag (e.g. shorter StringLength) — partial FC16 chunks would lose atomicity."); + $"Split the tag (e.g. shorter StringLength or smaller ArrayCount) — partial FC16 chunks would lose atomicity."); var pdu = new byte[6 + 1 + bytes.Length]; pdu[0] = 0x10; pdu[1] = (byte)(tag.Address >> 8); pdu[2] = (byte)(tag.Address & 0xFF); @@ -328,6 +453,52 @@ public sealed class ModbusDriver } } + /// + /// Encode an array-typed write value into a contiguous byte block by encoding each + /// element with the scalar codec. Caller submits IList / Array of the element CLR type. + /// + private static byte[] EncodeRegisterArray(object? value, ModbusTagDefinition tag) + { + var count = tag.ArrayCount!.Value; + if (value is not System.Collections.IList list || list.Count != count) + throw new InvalidOperationException( + $"Array write to {tag.Name} expects an IList of length {count}; got {value?.GetType().Name ?? "null"}"); + + var elementBytes = ElementByteCount(tag); + var result = new byte[count * elementBytes]; + for (var i = 0; i < count; i++) + { + var element = list[i]; + var encoded = EncodeRegister(element, tag); + if (encoded.Length != elementBytes) + throw new InvalidOperationException( + $"Encoder returned {encoded.Length} bytes for element {i} of {tag.Name}, expected {elementBytes}"); + Buffer.BlockCopy(encoded, 0, result, i * elementBytes, elementBytes); + } + return result; + } + + private static bool[] ToBoolArray(object? value, int expectedCount, string tagName) + { + if (value is bool[] direct && direct.Length == expectedCount) return direct; + if (value is System.Collections.IList list && list.Count == expectedCount) + { + var arr = new bool[expectedCount]; + for (var i = 0; i < expectedCount; i++) arr[i] = Convert.ToBoolean(list[i]); + return arr; + } + throw new InvalidOperationException( + $"Coil-array write to {tagName} expects a bool[] (or convertible IList) of length {expectedCount}; got {value?.GetType().Name ?? "null"}"); + } + + private static int ElementByteCount(ModbusTagDefinition tag) => tag.DataType switch + { + ModbusDataType.Int16 or ModbusDataType.UInt16 or ModbusDataType.Bcd16 => 2, + ModbusDataType.Int32 or ModbusDataType.UInt32 or ModbusDataType.Float32 or ModbusDataType.Bcd32 => 4, + ModbusDataType.Int64 or ModbusDataType.UInt64 or ModbusDataType.Float64 => 8, + _ => throw new InvalidOperationException($"Element byte count not defined for {tag.DataType} in array context"), + }; + /// /// Read-modify-write one bit in a holding register. FC03 → bit-swap → FC06. Serialised /// against other bit writes targeting the same register via . @@ -455,19 +626,49 @@ public sealed class ModbusDriver }; /// - /// Word-swap the input into the big-endian layout the decoders expect. For 2-register - /// types this reverses the two words; for 4-register types it reverses the four words - /// (PLC stored [hi-mid, low-mid, hi-high, low-high] → memory [hi-high, low-high, hi-mid, low-mid]). + /// Re-order the input bytes into the big-endian (ABCD) layout the decoders expect. + /// The four orders refer to how bytes A, B, C, D appear on the wire when reading a + /// 32-bit value from two consecutive registers (extends pairwise for 64-bit / 4 regs): + /// + /// BigEndian (ABCD): bytes as-is — Modbus spec default. + /// WordSwap (CDAB): swap word pairs (full register reversal across the value). + /// ByteSwap (BADC): swap bytes within each register. + /// FullReverse (DCBA): full byte reversal — equivalent to little-endian. + /// /// private static byte[] NormalizeWordOrder(ReadOnlySpan data, ModbusByteOrder order) { if (order == ModbusByteOrder.BigEndian) return data.ToArray(); + var result = new byte[data.Length]; - for (var word = 0; word < data.Length / 2; word++) + var registers = data.Length / 2; + + switch (order) { - var srcWord = data.Length / 2 - 1 - word; - result[word * 2] = data[srcWord * 2]; - result[word * 2 + 1] = data[srcWord * 2 + 1]; + case ModbusByteOrder.WordSwap: + // Reverse register order; bytes within each register stay big-endian. + for (var word = 0; word < registers; word++) + { + var srcWord = registers - 1 - word; + result[word * 2] = data[srcWord * 2]; + result[word * 2 + 1] = data[srcWord * 2 + 1]; + } + break; + case ModbusByteOrder.ByteSwap: + // Keep register order, swap two bytes within each register. + for (var word = 0; word < registers; word++) + { + result[word * 2] = data[word * 2 + 1]; + result[word * 2 + 1] = data[word * 2]; + } + break; + case ModbusByteOrder.FullReverse: + // Full byte-by-byte reversal — equivalent to interpreting the value little-endian. + for (var i = 0; i < data.Length; i++) + result[i] = data[data.Length - 1 - i]; + break; + default: + throw new InvalidOperationException($"Unhandled byte order {order}"); } return result; } diff --git a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs index d86772d..3decf7c 100644 --- a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs +++ b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverFactoryExtensions.cs @@ -57,10 +57,38 @@ public static class ModbusDriverFactoryExtensions return new ModbusDriver(options, driverInstanceId); } - private static ModbusTagDefinition BuildTag(ModbusTagDto t, string driverInstanceId) => - new( - Name: t.Name ?? throw new InvalidOperationException( - $"Modbus config for '{driverInstanceId}' has a tag missing Name"), + private static ModbusTagDefinition BuildTag(ModbusTagDto t, string driverInstanceId) + { + var name = t.Name ?? throw new InvalidOperationException( + $"Modbus config for '{driverInstanceId}' has a tag missing Name"); + + // AddressString takes precedence over the structured fields (Region/Address/DataType/ + // ByteOrder/BitIndex/StringLength/ArrayCount). Tags can mix forms freely — newer pasted + // rows use the grammar string, legacy rows keep the structured form. Fields not derivable + // from the grammar (Writable, WriteIdempotent, StringByteOrder) always come from the DTO. + if (!string.IsNullOrWhiteSpace(t.AddressString)) + { + if (!ModbusAddressParser.TryParse(t.AddressString, out var parsed, out var parseError)) + throw new InvalidOperationException( + $"Modbus tag '{name}' in '{driverInstanceId}' has invalid AddressString '{t.AddressString}': {parseError}"); + return new ModbusTagDefinition( + Name: name, + Region: parsed!.Region, + Address: parsed.Offset, + DataType: parsed.DataType, + Writable: t.Writable ?? true, + ByteOrder: parsed.ByteOrder, + BitIndex: parsed.Bit ?? 0, + StringLength: parsed.StringLength, + StringByteOrder: t.StringByteOrder is null + ? ModbusStringByteOrder.HighByteFirst + : ParseEnum(t.StringByteOrder, name, driverInstanceId, "StringByteOrder"), + WriteIdempotent: t.WriteIdempotent ?? false, + ArrayCount: parsed.ArrayCount); + } + + return new ModbusTagDefinition( + Name: name, Region: ParseEnum(t.Region, t.Name, driverInstanceId, "Region"), Address: t.Address ?? throw new InvalidOperationException( $"Modbus tag '{t.Name}' in '{driverInstanceId}' missing Address"), @@ -74,7 +102,9 @@ public static class ModbusDriverFactoryExtensions StringByteOrder: t.StringByteOrder is null ? ModbusStringByteOrder.HighByteFirst : ParseEnum(t.StringByteOrder, t.Name, driverInstanceId, "StringByteOrder"), - WriteIdempotent: t.WriteIdempotent ?? false); + WriteIdempotent: t.WriteIdempotent ?? false, + ArrayCount: t.ArrayCount); + } private static T ParseEnum(string? raw, string? tagName, string driverInstanceId, string field) where T : struct, Enum { @@ -111,6 +141,15 @@ public static class ModbusDriverFactoryExtensions internal sealed class ModbusTagDto { public string? Name { get; init; } + + /// + /// Address grammar string per ModbusAddressParser — when present, takes + /// precedence over the structured Region/Address/DataType/ByteOrder/BitIndex/ + /// StringLength/ArrayCount fields. Examples: "40001", "40001:F", + /// "40001:F:CDAB:5", "HR1:DI", "C100". + /// + public string? AddressString { get; init; } + public string? Region { get; init; } public ushort? Address { get; init; } public string? DataType { get; init; } @@ -120,6 +159,7 @@ public static class ModbusDriverFactoryExtensions public ushort? StringLength { get; init; } public string? StringByteOrder { get; init; } public bool? WriteIdempotent { get; init; } + public int? ArrayCount { get; init; } } internal sealed class ModbusProbeDto diff --git a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverOptions.cs b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverOptions.cs index 9e60b5c..c202acd 100644 --- a/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverOptions.cs +++ b/src/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriverOptions.cs @@ -100,6 +100,11 @@ public sealed class ModbusProbeOptions /// actions (pulse outputs), counter-increment addresses on PLCs that treat writes as deltas, /// any BCD / counter register where repeat-writes advance state. /// +/// +/// When non-null, the tag is exposed as an OPC UA array of this many elements. Total +/// registers consumed = ArrayCount * registers-per-element. Bit + array is rejected at +/// bind time (no use case). Default null = scalar (existing behavior). +/// public sealed record ModbusTagDefinition( string Name, ModbusRegion Region, @@ -110,59 +115,5 @@ public sealed record ModbusTagDefinition( byte BitIndex = 0, ushort StringLength = 0, ModbusStringByteOrder StringByteOrder = ModbusStringByteOrder.HighByteFirst, - bool WriteIdempotent = false); - -public enum ModbusDataType -{ - Bool, - Int16, - UInt16, - Int32, - UInt32, - Int64, - UInt64, - Float32, - Float64, - /// Single bit within a holding register. selects 0-15 LSB-first. - BitInRegister, - /// ASCII string packed 2 chars per register, characters long. - String, - /// - /// 16-bit binary-coded decimal. Each nibble encodes one decimal digit (0-9). Register - /// value 0x1234 decodes as decimal 1234 — NOT binary 0x04D2 = 4660. - /// DL205/DL260 and several Mitsubishi / Omron families store timers, counters, and - /// operator-facing numerics as BCD by default. - /// - Bcd16, - /// - /// 32-bit (two-register) BCD. Decodes 8 decimal digits. Word ordering follows - /// the same way does. - /// - Bcd32, -} - -/// -/// Word ordering for multi-register types. Modbus TCP standard is -/// (ABCD for 32-bit: high word at the lower address). Many PLCs — Siemens S7, several -/// Allen-Bradley series, some Modicon families — use (CDAB), which -/// keeps bytes big-endian within each register but reverses the word pair(s). -/// -public enum ModbusByteOrder -{ - BigEndian, - WordSwap, -} - -/// -/// Per-register byte order for ASCII strings packed 2 chars per register. Standard Modbus -/// convention is — the first character of each pair occupies -/// the high byte of the register. AutomationDirect DirectLOGIC (DL205, DL260, DL350) and a -/// handful of legacy controllers pack , which inverts that within -/// each register. Word ordering across multiple registers is always ascending address for -/// strings — only the byte order inside each register flips. -/// -public enum ModbusStringByteOrder -{ - HighByteFirst, - LowByteFirst, -} + bool WriteIdempotent = false, + int? ArrayCount = null); diff --git a/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests/ModbusAddressParserTests.cs b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests/ModbusAddressParserTests.cs new file mode 100644 index 0000000..e4e8773 --- /dev/null +++ b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests/ModbusAddressParserTests.cs @@ -0,0 +1,276 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Driver.Modbus; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests; + +[Trait("Category", "Unit")] +public sealed class ModbusAddressParserTests +{ + // ----- Bare Modicon-only forms inherit #136 behaviour; one sanity row per region. ----- + + [Theory] + [InlineData("40001", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)] + [InlineData("400001", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16)] + [InlineData("30001", ModbusRegion.InputRegisters, 0, ModbusDataType.Int16)] + [InlineData("00001", ModbusRegion.Coils, 0, ModbusDataType.Bool)] + [InlineData("10001", ModbusRegion.DiscreteInputs, 0, ModbusDataType.Bool)] + [InlineData("465536", ModbusRegion.HoldingRegisters, 65535, ModbusDataType.Int16)] + public void Bare_Modicon_Defaults_DataType_From_Region(string addr, ModbusRegion region, int offset, ModbusDataType type) + { + var p = ModbusAddressParser.Parse(addr); + p.Region.ShouldBe(region); + p.Offset.ShouldBe((ushort)offset); + p.DataType.ShouldBe(type); + p.Bit.ShouldBeNull(); + p.ArrayCount.ShouldBeNull(); + p.ByteOrder.ShouldBe(ModbusByteOrder.BigEndian); + } + + // ----- Mnemonic forms — HR / IR / C / DI ----- + + [Theory] + [InlineData("HR1", ModbusRegion.HoldingRegisters, 0)] + [InlineData("HR65536", ModbusRegion.HoldingRegisters, 65535)] + [InlineData("IR1", ModbusRegion.InputRegisters, 0)] + [InlineData("C100", ModbusRegion.Coils, 99)] + [InlineData("DI1", ModbusRegion.DiscreteInputs, 0)] + [InlineData("hr1", ModbusRegion.HoldingRegisters, 0)] // lowercase + [InlineData("Ir50", ModbusRegion.InputRegisters, 49)] // mixed case + public void Mnemonic_Region_Forms_Parse(string addr, ModbusRegion region, int offset) + { + var p = ModbusAddressParser.Parse(addr); + p.Region.ShouldBe(region); + p.Offset.ShouldBe((ushort)offset); + } + + // ----- Bit suffix .N ----- + + [Theory] + [InlineData("40001.0", 0)] + [InlineData("40001.5", 5)] + [InlineData("40001.15", 15)] + [InlineData("HR1.7", 7)] + public void Bit_Suffix_Implies_BitInRegister(string addr, int expectedBit) + { + var p = ModbusAddressParser.Parse(addr); + p.Bit.ShouldBe((byte)expectedBit); + p.DataType.ShouldBe(ModbusDataType.BitInRegister); + } + + [Fact] + public void Bit_Plus_Explicit_Type_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("40001.5:F")) + .Message.ShouldContain("Bit suffix"); + } + + [Fact] + public void Bit_Above_15_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("40001.16")) + .Message.ShouldContain("0..15"); + } + + // ----- Type codes ----- + + [Theory] + [InlineData("40001:BOOL", ModbusDataType.Bool)] + [InlineData("40001:I", ModbusDataType.Int16)] + [InlineData("40001:UI", ModbusDataType.UInt16)] + [InlineData("40001:DI", ModbusDataType.Int32)] + [InlineData("40001:L", ModbusDataType.Int32)] + [InlineData("40001:UDI", ModbusDataType.UInt32)] + [InlineData("40001:UL", ModbusDataType.UInt32)] + [InlineData("40001:LI", ModbusDataType.Int64)] + [InlineData("40001:ULI", ModbusDataType.UInt64)] + [InlineData("40001:F", ModbusDataType.Float32)] + [InlineData("40001:D", ModbusDataType.Float64)] + [InlineData("40001:BCD", ModbusDataType.Bcd16)] + [InlineData("40001:LBCD", ModbusDataType.Bcd32)] + [InlineData("40001:f", ModbusDataType.Float32)] // lowercase + public void Type_Codes_Parse(string addr, ModbusDataType expected) + { + ModbusAddressParser.Parse(addr).DataType.ShouldBe(expected); + } + + [Theory] + [InlineData("40001:STR1", 1)] + [InlineData("40001:STR20", 20)] + [InlineData("40001:STR255", 255)] + public void STR_Type_Carries_Length(string addr, int expectedLen) + { + var p = ModbusAddressParser.Parse(addr); + p.DataType.ShouldBe(ModbusDataType.String); + p.StringLength.ShouldBe((ushort)expectedLen); + } + + [Fact] + public void STR_Without_Length_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("40001:STR")) + .Message.ShouldContain("STR"); + } + + [Fact] + public void STR_Length_Zero_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("40001:STR0")) + .Message.ShouldContain("positive"); + } + + [Fact] + public void Unknown_Type_Code_Rejected_With_Catalog() + { + Should.Throw(() => ModbusAddressParser.Parse("40001:WIDGET")) + .Message.ShouldContain("Valid: BOOL, I,"); + } + + // ----- Region-type compatibility ----- + + [Fact] + public void Coils_With_Float_Type_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("00001:F")) + .Message.ShouldContain("only supports Bool"); + } + + [Fact] + public void DiscreteInputs_With_Int_Type_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("10001:I")) + .Message.ShouldContain("only supports Bool"); + } + + // ----- Byte order modifiers — all four ----- + + [Theory] + [InlineData("40001:F:ABCD", ModbusByteOrder.BigEndian)] + [InlineData("40001:F:CDAB", ModbusByteOrder.WordSwap)] + [InlineData("40001:F:BADC", ModbusByteOrder.ByteSwap)] + [InlineData("40001:F:DCBA", ModbusByteOrder.FullReverse)] + [InlineData("40001:F:cdab", ModbusByteOrder.WordSwap)] // lowercase + public void Byte_Order_Modifiers_Parse(string addr, ModbusByteOrder expected) + { + ModbusAddressParser.Parse(addr).ByteOrder.ShouldBe(expected); + } + + [Fact] + public void Unknown_Byte_Order_Rejected_With_Catalog() + { + Should.Throw(() => ModbusAddressParser.Parse("40001:F:WXYZ")) + .Message.ShouldContain("Valid: ABCD, CDAB, BADC, DCBA"); + } + + [Fact] + public void Empty_Order_Field_Means_Default() + { + // 40001:I::5 → Int16 array, no order override, default (BigEndian). + var p = ModbusAddressParser.Parse("40001:I::5"); + p.ByteOrder.ShouldBe(ModbusByteOrder.BigEndian); + p.ArrayCount.ShouldBe(5); + } + + // ----- Array count ----- + + [Theory] + [InlineData("40001:I:ABCD:1", 1)] + [InlineData("40001:F:5", 5)] + [InlineData("40001:F:CDAB:10", 10)] + [InlineData("40001:DI:100", 100)] + public void Array_Count_Parses(string addr, int expectedCount) + { + ModbusAddressParser.Parse(addr).ArrayCount.ShouldBe(expectedCount); + } + + [Fact] + public void Array_Count_Zero_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("40001:F:ABCD:0")) + .Message.ShouldContain("positive"); + } + + [Fact] + public void Array_Count_NonNumeric_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("40001:F:ABCD:five")) + .Message.ShouldContain("positive"); + } + + [Fact] + public void Bit_Plus_Array_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("40001.5:::5")) + .Message.ShouldContain("Bit suffix and array count"); + } + + // ----- Composition / examples ----- + + [Fact] + public void Worked_Example_Float_With_Word_Swap() + { + var p = ModbusAddressParser.Parse("40001:F:CDAB"); + p.Region.ShouldBe(ModbusRegion.HoldingRegisters); + p.Offset.ShouldBe((ushort)0); + p.DataType.ShouldBe(ModbusDataType.Float32); + p.ByteOrder.ShouldBe(ModbusByteOrder.WordSwap); + p.ArrayCount.ShouldBeNull(); + } + + [Fact] + public void Worked_Example_Int16_Array() + { + var p = ModbusAddressParser.Parse("40001:I::10"); + p.Region.ShouldBe(ModbusRegion.HoldingRegisters); + p.DataType.ShouldBe(ModbusDataType.Int16); + p.ArrayCount.ShouldBe(10); + p.ByteOrder.ShouldBe(ModbusByteOrder.BigEndian); + } + + [Fact] + public void Worked_Example_Float_Array_Word_Swap_6_Digit() + { + var p = ModbusAddressParser.Parse("465500:F:CDAB:5"); + p.Region.ShouldBe(ModbusRegion.HoldingRegisters); + p.Offset.ShouldBe((ushort)65499); + p.DataType.ShouldBe(ModbusDataType.Float32); + p.ByteOrder.ShouldBe(ModbusByteOrder.WordSwap); + p.ArrayCount.ShouldBe(5); + } + + [Fact] + public void Worked_Example_String_With_Length() + { + var p = ModbusAddressParser.Parse("40001:STR20"); + p.DataType.ShouldBe(ModbusDataType.String); + p.StringLength.ShouldBe((ushort)20); + p.ArrayCount.ShouldBeNull(); // strings ARE multi-register but they are not "array of string" + } + + [Fact] + public void TryParse_Returns_Diagnostic_On_Failure() + { + ModbusAddressParser.TryParse("garbage", out var p, out var err).ShouldBeFalse(); + p.ShouldBeNull(); + err.ShouldNotBeNull(); + } + + [Fact] + public void TryParse_Returns_Result_On_Success() + { + ModbusAddressParser.TryParse("HR1:F:CDAB:3", out var p, out var err).ShouldBeTrue(); + p.ShouldNotBeNull(); + err.ShouldBeNull(); + p!.Region.ShouldBe(ModbusRegion.HoldingRegisters); + p.DataType.ShouldBe(ModbusDataType.Float32); + p.ByteOrder.ShouldBe(ModbusByteOrder.WordSwap); + p.ArrayCount.ShouldBe(3); + } + + [Fact] + public void Too_Many_Colons_Rejected() + { + Should.Throw(() => ModbusAddressParser.Parse("40001:F:CDAB:5:extra")) + .Message.ShouldContain("too many"); + } +} diff --git a/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusArrayTests.cs b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusArrayTests.cs new file mode 100644 index 0000000..460cbcf --- /dev/null +++ b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusArrayTests.cs @@ -0,0 +1,172 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests; + +/// +/// 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 +/// ; tests are co-located with the rest of the in-memory +/// driver coverage so they all share the same harness. +/// +[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(); + 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(); + 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(); + 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(); + 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(); + await drv.DiscoverAsync(new RecordingBuilder(captured), CancellationToken.None); + + captured[0].IsArray.ShouldBeFalse(); + captured[0].ArrayDim.ShouldBeNull(); + } + + private sealed class RecordingBuilder(List 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"); + } + } +} diff --git a/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusByteOrderTests.cs b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusByteOrderTests.cs new file mode 100644 index 0000000..7067385 --- /dev/null +++ b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusByteOrderTests.cs @@ -0,0 +1,73 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests; + +/// +/// Coverage for the new ByteSwap (BADC) and FullReverse (DCBA) byte orders added by #137. +/// The existing BigEndian (ABCD) and WordSwap (CDAB) cases live in . +/// +[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)); + } +} diff --git a/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusDriverTests.cs b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusDriverTests.cs index 48bb565..5313b52 100644 --- a/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusDriverTests.cs +++ b/tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ModbusDriverTests.cs @@ -11,9 +11,11 @@ public sealed class ModbusDriverTests { /// /// 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. /// - 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(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; }