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:
@@ -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<object> 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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decode an FC01/FC02 coil-bitmap response into either a single bool (scalar tag) or a
|
||||
/// bool[] of <paramref name="count"/> elements (array tag). Modbus packs coils LSB-first
|
||||
/// within each byte, ascending address across bytes.
|
||||
/// </summary>
|
||||
private static object DecodeBitArray(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decode an array of register-backed values from a contiguous block. Each element
|
||||
/// occupies <paramref name="elementRegs"/> registers and is decoded with the same
|
||||
/// codec the scalar path uses, sliced from its position in the block.
|
||||
/// </summary>
|
||||
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<byte[]> 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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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"),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Read-modify-write one bit in a holding register. FC03 → bit-swap → FC06. Serialised
|
||||
/// against other bit writes targeting the same register via <see cref="GetRmwLock"/>.
|
||||
@@ -455,19 +626,49 @@ public sealed class ModbusDriver
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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):
|
||||
/// <list type="bullet">
|
||||
/// <item><b>BigEndian (ABCD)</b>: bytes as-is — Modbus spec default.</item>
|
||||
/// <item><b>WordSwap (CDAB)</b>: swap word pairs (full register reversal across the value).</item>
|
||||
/// <item><b>ByteSwap (BADC)</b>: swap bytes within each register.</item>
|
||||
/// <item><b>FullReverse (DCBA)</b>: full byte reversal — equivalent to little-endian.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
private static byte[] NormalizeWordOrder(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
@@ -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<ModbusStringByteOrder>(t.StringByteOrder, name, driverInstanceId, "StringByteOrder"),
|
||||
WriteIdempotent: t.WriteIdempotent ?? false,
|
||||
ArrayCount: parsed.ArrayCount);
|
||||
}
|
||||
|
||||
return new ModbusTagDefinition(
|
||||
Name: name,
|
||||
Region: ParseEnum<ModbusRegion>(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<ModbusStringByteOrder>(t.StringByteOrder, t.Name, driverInstanceId, "StringByteOrder"),
|
||||
WriteIdempotent: t.WriteIdempotent ?? false);
|
||||
WriteIdempotent: t.WriteIdempotent ?? false,
|
||||
ArrayCount: t.ArrayCount);
|
||||
}
|
||||
|
||||
private static T ParseEnum<T>(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; }
|
||||
|
||||
/// <summary>
|
||||
/// Address grammar string per <c>ModbusAddressParser</c> — when present, takes
|
||||
/// precedence over the structured Region/Address/DataType/ByteOrder/BitIndex/
|
||||
/// StringLength/ArrayCount fields. Examples: <c>"40001"</c>, <c>"40001:F"</c>,
|
||||
/// <c>"40001:F:CDAB:5"</c>, <c>"HR1:DI"</c>, <c>"C100"</c>.
|
||||
/// </summary>
|
||||
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
|
||||
|
||||
@@ -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.
|
||||
/// </param>
|
||||
/// <param name="ArrayCount">
|
||||
/// 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).
|
||||
/// </param>
|
||||
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,
|
||||
/// <summary>Single bit within a holding register. <see cref="ModbusTagDefinition.BitIndex"/> selects 0-15 LSB-first.</summary>
|
||||
BitInRegister,
|
||||
/// <summary>ASCII string packed 2 chars per register, <see cref="ModbusTagDefinition.StringLength"/> characters long.</summary>
|
||||
String,
|
||||
/// <summary>
|
||||
/// 16-bit binary-coded decimal. Each nibble encodes one decimal digit (0-9). Register
|
||||
/// value <c>0x1234</c> decodes as decimal <c>1234</c> — NOT binary <c>0x04D2 = 4660</c>.
|
||||
/// DL205/DL260 and several Mitsubishi / Omron families store timers, counters, and
|
||||
/// operator-facing numerics as BCD by default.
|
||||
/// </summary>
|
||||
Bcd16,
|
||||
/// <summary>
|
||||
/// 32-bit (two-register) BCD. Decodes 8 decimal digits. Word ordering follows
|
||||
/// <see cref="ModbusTagDefinition.ByteOrder"/> the same way <see cref="Int32"/> does.
|
||||
/// </summary>
|
||||
Bcd32,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Word ordering for multi-register types. Modbus TCP standard is <see cref="BigEndian"/>
|
||||
/// (ABCD for 32-bit: high word at the lower address). Many PLCs — Siemens S7, several
|
||||
/// Allen-Bradley series, some Modicon families — use <see cref="WordSwap"/> (CDAB), which
|
||||
/// keeps bytes big-endian within each register but reverses the word pair(s).
|
||||
/// </summary>
|
||||
public enum ModbusByteOrder
|
||||
{
|
||||
BigEndian,
|
||||
WordSwap,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Per-register byte order for ASCII strings packed 2 chars per register. Standard Modbus
|
||||
/// convention is <see cref="HighByteFirst"/> — 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 <see cref="LowByteFirst"/>, 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.
|
||||
/// </summary>
|
||||
public enum ModbusStringByteOrder
|
||||
{
|
||||
HighByteFirst,
|
||||
LowByteFirst,
|
||||
}
|
||||
bool WriteIdempotent = false,
|
||||
int? ArrayCount = null);
|
||||
|
||||
Reference in New Issue
Block a user