chore: organize solution into module folders (Core/Server/Drivers/Client/Tooling)

Group all 69 projects into category subfolders under src/ and tests/ so the
Rider Solution Explorer mirrors the module structure. Folders: Core, Server,
Drivers (with a nested Driver CLIs subfolder), Client, Tooling.

- Move every project folder on disk with git mv (history preserved as renames).
- Recompute relative paths in 57 .csproj files: cross-category ProjectReferences,
  the lib/ HintPath+None refs in Driver.Historian.Wonderware, and the external
  mxaccessgw refs in Driver.Galaxy and its test project.
- Rebuild ZB.MOM.WW.OtOpcUa.slnx with nested solution folders.
- Re-prefix project paths in functional scripts (e2e, compliance, smoke SQL,
  integration, install).

Build green (0 errors); unit tests pass. Docs left for a separate pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-05-17 01:55:28 -04:00
parent 69f02fed7f
commit a25593a9c6
1044 changed files with 365 additions and 343 deletions

View File

@@ -0,0 +1,165 @@
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>
/// AutomationDirect DirectLOGIC address-translation helpers. DL205 / DL260 / DL350 CPUs
/// address V-memory in OCTAL while the Modbus wire uses DECIMAL PDU addresses — operators
/// see "V2000" in the PLC ladder-logic editor but the Modbus client must write PDU 0x0400.
/// The formulas differ between user V-memory (simple octal-to-decimal) and system V-memory
/// (fixed bank mappings), so the two cases are separate methods rather than one overloaded
/// "ToPdu" call.
/// </summary>
/// <remarks>
/// See <c>docs/v2/dl205.md</c> §V-memory for the full CPU-family matrix + rationale.
/// References: D2-USER-M appendix (DL205/D2-260), H2-ECOM-M §6.5 (absolute vs relative
/// addressing), AutomationDirect forum guidance on V40400 system-base.
/// </remarks>
public static class DirectLogicAddress
{
/// <summary>
/// Convert a DirectLOGIC user V-memory address (octal) to a 0-based Modbus PDU address.
/// Accepts bare octal (<c>"2000"</c>) or <c>V</c>-prefixed (<c>"V2000"</c>). Range
/// depends on CPU model — DL205 D2-260 user memory is V1400-V7377 + V10000-V17777
/// octal, DL260 extends to V77777 octal.
/// </summary>
/// <exception cref="ArgumentException">Input is null / empty / contains non-octal digits (8,9).</exception>
/// <exception cref="OverflowException">Parsed value exceeds ushort.MaxValue (0xFFFF).</exception>
public static ushort UserVMemoryToPdu(string vAddress)
{
if (string.IsNullOrWhiteSpace(vAddress))
throw new ArgumentException("V-memory address must not be empty", nameof(vAddress));
var s = vAddress.Trim();
if (s[0] == 'V' || s[0] == 'v') s = s.Substring(1);
if (s.Length == 0)
throw new ArgumentException($"V-memory address '{vAddress}' has no digits", nameof(vAddress));
// Octal conversion. Reject 8/9 digits up-front — int.Parse in the obvious base would
// accept them silently because .NET has no built-in base-8 parser.
uint result = 0;
foreach (var ch in s)
{
if (ch < '0' || ch > '7')
throw new ArgumentException(
$"V-memory address '{vAddress}' contains non-octal digit '{ch}' — DirectLOGIC V-addresses are octal (0-7)",
nameof(vAddress));
result = result * 8 + (uint)(ch - '0');
if (result > ushort.MaxValue)
throw new OverflowException(
$"V-memory address '{vAddress}' exceeds the 16-bit Modbus PDU address range");
}
return (ushort)result;
}
/// <summary>
/// DirectLOGIC system V-memory starts at octal V40400 on DL260 / H2-ECOM100 in factory
/// "absolute" addressing mode. Unlike user V-memory, the mapping is NOT a simple
/// octal-to-decimal conversion — the CPU relocates the system bank to Modbus PDU 0x2100
/// (decimal 8448). This helper returns the CPU-family base plus a user-supplied offset
/// within the system bank.
/// </summary>
public const ushort SystemVMemoryBasePdu = 0x2100;
/// <param name="offsetWithinSystemBank">
/// 0-based register offset within the system bank. Pass 0 for V40400 itself; pass 1 for
/// V40401 (octal), and so on. NOT an octal-decoded value — the system bank lives at
/// consecutive PDU addresses, so the offset is plain decimal.
/// </param>
public static ushort SystemVMemoryToPdu(ushort offsetWithinSystemBank)
{
var pdu = SystemVMemoryBasePdu + offsetWithinSystemBank;
if (pdu > ushort.MaxValue)
throw new OverflowException(
$"System V-memory offset {offsetWithinSystemBank} maps past 0xFFFF");
return (ushort)pdu;
}
// Bit-memory bases per DL260 user manual §I/O-configuration.
// Numbers after X / Y / C / SP are OCTAL in DirectLOGIC notation. The Modbus base is
// added to the octal-decoded offset; e.g. Y017 = Modbus coil 2048 + octal(17) = 2048 + 15 = 2063.
/// <summary>
/// DL260 Y-output coil base. Y0 octal → Modbus coil address 2048 (0-based).
/// </summary>
public const ushort YOutputBaseCoil = 2048;
/// <summary>
/// DL260 C-relay coil base. C0 octal → Modbus coil address 3072 (0-based).
/// </summary>
public const ushort CRelayBaseCoil = 3072;
/// <summary>
/// DL260 X-input discrete-input base. X0 octal → Modbus discrete input 0.
/// </summary>
public const ushort XInputBaseDiscrete = 0;
/// <summary>
/// DL260 SP special-relay discrete-input base. SP0 octal → Modbus discrete input 1024.
/// Read-only; writing SP relays is rejected with Illegal Data Address.
/// </summary>
public const ushort SpecialBaseDiscrete = 1024;
/// <summary>
/// Translate a DirectLOGIC Y-output address (e.g. <c>"Y0"</c>, <c>"Y17"</c>) to its
/// 0-based Modbus coil address on DL260. The trailing number is OCTAL, matching the
/// ladder-logic editor's notation.
/// </summary>
public static ushort YOutputToCoil(string yAddress) =>
AddOctalOffset(YOutputBaseCoil, StripPrefix(yAddress, 'Y'));
/// <summary>
/// Translate a DirectLOGIC C-relay address (e.g. <c>"C0"</c>, <c>"C1777"</c>) to its
/// 0-based Modbus coil address.
/// </summary>
public static ushort CRelayToCoil(string cAddress) =>
AddOctalOffset(CRelayBaseCoil, StripPrefix(cAddress, 'C'));
/// <summary>
/// Translate a DirectLOGIC X-input address (e.g. <c>"X0"</c>, <c>"X17"</c>) to its
/// 0-based Modbus discrete-input address. Reading an unpopulated X returns 0, not an
/// exception — the CPU sizes the table to configured I/O, not installed modules.
/// </summary>
public static ushort XInputToDiscrete(string xAddress) =>
AddOctalOffset(XInputBaseDiscrete, StripPrefix(xAddress, 'X'));
/// <summary>
/// Translate a DirectLOGIC SP-special-relay address (e.g. <c>"SP0"</c>) to its 0-based
/// Modbus discrete-input address. Accepts <c>"SP"</c> prefix case-insensitively.
/// </summary>
public static ushort SpecialToDiscrete(string spAddress)
{
if (string.IsNullOrWhiteSpace(spAddress))
throw new ArgumentException("SP address must not be empty", nameof(spAddress));
var s = spAddress.Trim();
if (s.Length >= 2 && (s[0] == 'S' || s[0] == 's') && (s[1] == 'P' || s[1] == 'p'))
s = s.Substring(2);
return AddOctalOffset(SpecialBaseDiscrete, s);
}
private static string StripPrefix(string address, char expectedPrefix)
{
if (string.IsNullOrWhiteSpace(address))
throw new ArgumentException("Address must not be empty", nameof(address));
var s = address.Trim();
if (s.Length > 0 && char.ToUpperInvariant(s[0]) == char.ToUpperInvariant(expectedPrefix))
s = s.Substring(1);
return s;
}
private static ushort AddOctalOffset(ushort baseAddr, string octalDigits)
{
if (octalDigits.Length == 0)
throw new ArgumentException("Address has no digits", nameof(octalDigits));
uint offset = 0;
foreach (var ch in octalDigits)
{
if (ch < '0' || ch > '7')
throw new ArgumentException(
$"Address contains non-octal digit '{ch}' — DirectLOGIC I/O addresses are octal (0-7)",
nameof(octalDigits));
offset = offset * 8 + (uint)(ch - '0');
}
var result = baseAddr + offset;
if (result > ushort.MaxValue)
throw new OverflowException($"Address {baseAddr}+{offset} exceeds 0xFFFF");
return (ushort)result;
}
}

View File

@@ -0,0 +1,161 @@
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>
/// Mitsubishi MELSEC PLC family selector for address-translation helpers. The Q/L/iQ-R
/// families write bit-device addresses (X, Y) in <b>hexadecimal</b> in GX Works and the
/// CPU manuals; the FX and iQ-F families write them in <b>octal</b> (same convention as
/// AutomationDirect DirectLOGIC). Mixing the two up is the #1 MELSEC driver bug source —
/// an operator typing <c>X20</c> into a Q-series tag config means decimal 32, but the
/// same string on an FX3U means decimal 16, so the helper must know the family to route
/// correctly.
/// </summary>
public enum MelsecFamily
{
/// <summary>
/// MELSEC-Q / MELSEC-L / MELSEC iQ-R. X and Y device numbers are interpreted as
/// <b>hexadecimal</b>; <c>X20</c> means decimal 32.
/// </summary>
Q_L_iQR,
/// <summary>
/// MELSEC-F (FX3U / FX3GE / FX3G) and MELSEC iQ-F (FX5U). X and Y device numbers
/// are interpreted as <b>octal</b> (same as DirectLOGIC); <c>X20</c> means decimal 16.
/// iQ-F has a GX Works3 project toggle that can flip to decimal — if a site uses
/// that, configure the tag's Address directly as a decimal PDU address and do not
/// route through this helper.
/// </summary>
F_iQF,
}
/// <summary>
/// Mitsubishi MELSEC address-translation helpers for the QJ71MT91 / LJ71MT91 / RJ71EN71 /
/// iQ-R built-in / iQ-F / FX3U-ENET-P502 Modbus modules. MELSEC does NOT hard-wire
/// Modbus-to-device mappings like DL260 does — every site configures its own "Modbus
/// Device Assignment Parameter" block of up to 16 entries. The helpers here cover only
/// the <b>address-notation</b> portion of the translation (hex X20 vs octal X20 + adding
/// the bank base); the caller is still responsible for knowing the assignment-block
/// offset for their site.
/// </summary>
/// <remarks>
/// See <c>docs/v2/mitsubishi.md</c> §device-assignment + §X-Y-hex-trap for the full
/// matrix and primary-source citations.
/// </remarks>
public static class MelsecAddress
{
/// <summary>
/// Translate a MELSEC X-input address (e.g. <c>"X0"</c>, <c>"X10"</c>) to a 0-based
/// Modbus discrete-input address, given the PLC family's address notation (hex or
/// octal) and the Modbus Device Assignment block's X-range base.
/// </summary>
/// <param name="xAddress">MELSEC X address. <c>X</c> prefix optional, case-insensitive.</param>
/// <param name="family">The PLC family — determines whether the trailing digits are hex or octal.</param>
/// <param name="xBankBase">
/// 0-based Modbus DI address the assignment-block has configured X0 to land at.
/// Typical default on QJ71MT91 sample projects: 0. Pass the site-specific value.
/// </param>
public static ushort XInputToDiscrete(string xAddress, MelsecFamily family, ushort xBankBase = 0) =>
AddFamilyOffset(xBankBase, StripPrefix(xAddress, 'X'), family);
/// <summary>
/// Translate a MELSEC Y-output address to a 0-based Modbus coil address. Same rules
/// as <see cref="XInputToDiscrete"/> for hex/octal parsing.
/// </summary>
public static ushort YOutputToCoil(string yAddress, MelsecFamily family, ushort yBankBase = 0) =>
AddFamilyOffset(yBankBase, StripPrefix(yAddress, 'Y'), family);
/// <summary>
/// Translate a MELSEC M-relay address (internal relay) to a 0-based Modbus coil
/// address. M-addresses are <b>decimal</b> on every MELSEC family — unlike X/Y which
/// are hex on Q/L/iQ-R. Includes the bank base that the assignment-block configured.
/// </summary>
public static ushort MRelayToCoil(string mAddress, ushort mBankBase = 0)
{
var digits = StripPrefix(mAddress, 'M');
if (!ushort.TryParse(digits, out var offset))
throw new ArgumentException(
$"M-relay address '{mAddress}' is not a valid decimal integer", nameof(mAddress));
var result = mBankBase + offset;
if (result > ushort.MaxValue)
throw new OverflowException($"M-relay {mAddress} + base {mBankBase} exceeds 0xFFFF");
return (ushort)result;
}
/// <summary>
/// Translate a MELSEC D-register address (data register) to a 0-based Modbus holding
/// register address. D-addresses are <b>decimal</b>. Default assignment convention is
/// D0 → HR 0 (pass <paramref name="dBankBase"/> = 0); sites with shifted layouts pass
/// their configured base.
/// </summary>
public static ushort DRegisterToHolding(string dAddress, ushort dBankBase = 0)
{
var digits = StripPrefix(dAddress, 'D');
if (!ushort.TryParse(digits, out var offset))
throw new ArgumentException(
$"D-register address '{dAddress}' is not a valid decimal integer", nameof(dAddress));
var result = dBankBase + offset;
if (result > ushort.MaxValue)
throw new OverflowException($"D-register {dAddress} + base {dBankBase} exceeds 0xFFFF");
return (ushort)result;
}
private static string StripPrefix(string address, char expectedPrefix)
{
if (string.IsNullOrWhiteSpace(address))
throw new ArgumentException("Address must not be empty", nameof(address));
var s = address.Trim();
if (s.Length > 0 && char.ToUpperInvariant(s[0]) == char.ToUpperInvariant(expectedPrefix))
s = s.Substring(1);
if (s.Length == 0)
throw new ArgumentException($"Address '{address}' has no digits after prefix", nameof(address));
return s;
}
private static ushort AddFamilyOffset(ushort baseAddr, string digits, MelsecFamily family)
{
uint offset = family switch
{
MelsecFamily.Q_L_iQR => ParseHex(digits),
MelsecFamily.F_iQF => ParseOctal(digits),
_ => throw new ArgumentOutOfRangeException(nameof(family), family, "Unknown MELSEC family"),
};
var result = baseAddr + offset;
if (result > ushort.MaxValue)
throw new OverflowException($"Address {baseAddr}+{offset} exceeds 0xFFFF");
return (ushort)result;
}
private static uint ParseHex(string digits)
{
uint result = 0;
foreach (var ch in digits)
{
uint nibble;
if (ch >= '0' && ch <= '9') nibble = (uint)(ch - '0');
else if (ch >= 'A' && ch <= 'F') nibble = (uint)(ch - 'A' + 10);
else if (ch >= 'a' && ch <= 'f') nibble = (uint)(ch - 'a' + 10);
else throw new ArgumentException(
$"Address contains non-hex digit '{ch}' — Q/L/iQ-R X/Y addresses are hexadecimal",
nameof(digits));
result = result * 16 + nibble;
if (result > ushort.MaxValue)
throw new OverflowException($"Hex address exceeds 0xFFFF");
}
return result;
}
private static uint ParseOctal(string digits)
{
uint result = 0;
foreach (var ch in digits)
{
if (ch < '0' || ch > '7')
throw new ArgumentException(
$"Address contains non-octal digit '{ch}' — FX/iQ-F X/Y addresses are octal (0-7)",
nameof(digits));
result = result * 8 + (uint)(ch - '0');
if (result > ushort.MaxValue)
throw new OverflowException($"Octal address exceeds 0xFFFF");
}
return result;
}
}

View File

@@ -0,0 +1,450 @@
using System.Globalization;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>
/// Parses the full Modbus tag-address grammar:
/// <c>&lt;region&gt;&lt;offset&gt;[.&lt;bit&gt;][:&lt;type&gt;[&lt;len&gt;]][:&lt;order&gt;][:&lt;count&gt;]</c>.
/// Output is a <see cref="ParsedModbusAddress"/> the driver-side config layer maps onto a
/// <c>ModbusTagDefinition</c>.
/// </summary>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// <para>
/// Examples (post-#146 type codes — verified against Wonderware DASMBTCP + Ignition):
/// <list type="bullet">
/// <item><c>40001</c> — HoldingRegisters[0], Int16 (default).</item>
/// <item><c>400001</c> — HoldingRegisters[0], Int16 (6-digit form).</item>
/// <item><c>40001.5</c> — bit 5 of HoldingRegisters[0].</item>
/// <item><c>40001:F</c> — Float32 starting at HR[0] (consumes HR[0..1]).</item>
/// <item><c>40001:F:CDAB</c> — same with word-swap byte order.</item>
/// <item><c>40001:STR20</c> — 20-char ASCII string.</item>
/// <item><c>HR1:I</c> — Int32 at HR[0] using mnemonic region (Wonderware-aligned).</item>
/// <item><c>40001:F:5</c> — Float32[5] array (consumes HR[0..9]).</item>
/// <item><c>40001:S::10</c> — Int16[10] using default byte order (empty order field).</item>
/// <item><c>C100</c> — Coils[99] (mnemonic).</item>
/// </list>
/// </para>
/// </remarks>
public static class ModbusAddressParser
{
/// <summary>Parse an address string. Throws <see cref="FormatException"/> on invalid input.</summary>
public static ParsedModbusAddress Parse(string address) => Parse(address, ModbusFamily.Generic, MelsecFamily.Q_L_iQR);
/// <summary>Parse with a family hint (#144 family-native branch).</summary>
public static ParsedModbusAddress Parse(string address, ModbusFamily family, MelsecFamily melsecSubFamily = MelsecFamily.Q_L_iQR)
{
if (TryParse(address, family, melsecSubFamily, out var parsed, out var error))
return parsed!;
throw new FormatException(error);
}
public static bool TryParse(string? address, out ParsedModbusAddress? result, out string? error)
=> TryParse(address, ModbusFamily.Generic, MelsecFamily.Q_L_iQR, out result, out error);
/// <summary>
/// Try-parse with a family hint. When <paramref name="family"/> is non-Generic, the
/// parser tries the family-native form first (DL205 V-memory, MELSEC D-register, etc.)
/// and falls back to Modicon / mnemonic on miss. <paramref name="result"/> is null and
/// <paramref name="error"/> non-null on failure.
/// </summary>
public static bool TryParse(string? address, ModbusFamily family, MelsecFamily melsecSubFamily,
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: <region+offset>[.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: <addr>:<type>:<X>. 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, family, melsecSubFamily, 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, ModbusFamily family, MelsecFamily melsecSubFamily,
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;
}
// Family-native branch (#144) — when a non-Generic family is configured, try its native
// syntax first. Successful native parse wins; failure falls through to Modicon / mnemonic.
// The order matters for cross-family ambiguity: DL205 'C100' is a control relay, not a
// Modicon coil, when the user has explicitly selected DL205.
if (family != ModbusFamily.Generic && TryParseFamilyNative(addrText, family, melsecSubFamily, out region, out offset, out error))
return true;
// Try mnemonic prefix first (HR, IR, C, DI). Cheaper than the digit branch and
// unambiguous when present.
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 TryParseFamilyNative(string text, ModbusFamily family, MelsecFamily melsecSubFamily,
out ModbusRegion region, out ushort offset, out string? error)
{
region = default;
offset = 0;
error = null;
try
{
switch (family)
{
case ModbusFamily.DL205:
// V-memory → HoldingRegisters; Y → Coils; C → Coils (relays); X → DiscreteInputs;
// SP → DiscreteInputs (special relays).
if (text.StartsWith("V", StringComparison.OrdinalIgnoreCase))
{
offset = DirectLogicAddress.UserVMemoryToPdu(text);
region = ModbusRegion.HoldingRegisters;
return true;
}
if (text.StartsWith("Y", StringComparison.OrdinalIgnoreCase))
{
offset = DirectLogicAddress.YOutputToCoil(text);
region = ModbusRegion.Coils;
return true;
}
if (text.StartsWith("C", StringComparison.OrdinalIgnoreCase))
{
offset = DirectLogicAddress.CRelayToCoil(text);
region = ModbusRegion.Coils;
return true;
}
if (text.StartsWith("X", StringComparison.OrdinalIgnoreCase))
{
offset = DirectLogicAddress.XInputToDiscrete(text);
region = ModbusRegion.DiscreteInputs;
return true;
}
if (text.StartsWith("SP", StringComparison.OrdinalIgnoreCase))
{
offset = DirectLogicAddress.SpecialToDiscrete(text);
region = ModbusRegion.DiscreteInputs;
return true;
}
return false;
case ModbusFamily.MELSEC:
// D-registers → HoldingRegisters; X → DiscreteInputs; Y → Coils; M → Coils.
// The MelsecAddress helpers honour the sub-family (Q hex vs F octal) and use
// bank base 0; users with non-zero assignment bases must use the structured
// tag form to override. The grammar string covers the common base-0 path.
if (text.StartsWith("D", StringComparison.OrdinalIgnoreCase))
{
offset = MelsecAddress.DRegisterToHolding(text);
region = ModbusRegion.HoldingRegisters;
return true;
}
if (text.StartsWith("X", StringComparison.OrdinalIgnoreCase))
{
offset = MelsecAddress.XInputToDiscrete(text, melsecSubFamily);
region = ModbusRegion.DiscreteInputs;
return true;
}
if (text.StartsWith("Y", StringComparison.OrdinalIgnoreCase))
{
offset = MelsecAddress.YOutputToCoil(text, melsecSubFamily);
region = ModbusRegion.Coils;
return true;
}
if (text.StartsWith("M", StringComparison.OrdinalIgnoreCase))
{
offset = MelsecAddress.MRelayToCoil(text);
region = ModbusRegion.Coils;
return true;
}
return false;
default:
return false;
}
}
catch (Exception ex) when (ex is ArgumentException or OverflowException)
{
error = $"Family-native parse for {family} failed on '{text}': {ex.Message}";
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<n> — 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<n>";
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;
}
// #146 — codes aligned with Wonderware DASMBTCP + Ignition Modbus driver after the
// 2026-04-25 vendor-doc verification:
// - `:I` is Int32 (Wonderware: "letter 'I' follow ... 32-bit signed quantity, two
// consecutive registers"). Ignition's HRI is also Int32. The pre-#146 mapping
// `:I` = Int16 silently produced wrong-typed data + offset-shifted neighbours when
// a tag spreadsheet was pasted from another vendor.
// - `:S` is the explicit Int16 code (Wonderware: "letter 'S' ... 16-bit signed").
// - `:US` is UInt16 (Ignition: HRUS = "Unsigned Short").
// - `:UI` is UInt32 (parallel to `:I` shape; matches Ignition HRUI).
// - `:I_64` / `:UI_64` for 64-bit (Ignition HRI_64 / HRUI_64 underscore-N convention).
// - `:BCD_32` for 32-bit BCD (Ignition HRBCD_32). The pre-#146 `:LBCD` is dropped.
// - HR/IR with no explicit type still default to Int16 (matches Ignition `HR`).
type = text.ToUpperInvariant() switch
{
"BOOL" => ModbusDataType.Bool,
"S" => ModbusDataType.Int16,
"US" => ModbusDataType.UInt16,
"I" => ModbusDataType.Int32,
"UI" => ModbusDataType.UInt32,
"I_64" => ModbusDataType.Int64,
"UI_64" => ModbusDataType.UInt64,
"F" => ModbusDataType.Float32,
"D" => ModbusDataType.Float64,
"BCD" => ModbusDataType.Bcd16,
"BCD_32" => ModbusDataType.Bcd32,
_ => (ModbusDataType)(-1),
};
if ((int)type == -1)
{
error = $"Unknown type code '{text}'. Valid: BOOL, S, US, I, UI, I_64, UI_64, F, D, BCD, BCD_32, STR<n>";
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;
}
}
/// <summary>
/// Result of parsing a Modbus tag-address string. Maps directly onto the driver-side
/// <c>ModbusTagDefinition</c> at config-bind time.
/// </summary>
/// <param name="Region">Coils / DiscreteInputs / InputRegisters / HoldingRegisters.</param>
/// <param name="Offset">Zero-based PDU offset.</param>
/// <param name="Bit">When non-null, the tag is a single-bit-in-register selector (0..15).</param>
/// <param name="DataType">Inferred from explicit type code or region default.</param>
/// <param name="StringLength">Character count for <see cref="ModbusDataType.String"/>; zero otherwise.</param>
/// <param name="ByteOrder">Word/byte ordering for multi-register types.</param>
/// <param name="ArrayCount">Element count when the tag is an array; null for scalars.</param>
public sealed record ParsedModbusAddress(
ModbusRegion Region,
ushort Offset,
byte? Bit,
ModbusDataType DataType,
ushort StringLength,
ModbusByteOrder ByteOrder,
int? ArrayCount);

View File

@@ -0,0 +1,95 @@
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>
/// The set of value types a Modbus tag can decode to. Each type implies a fixed
/// register-count: <see cref="Bool"/> / <see cref="Int16"/> / <see cref="UInt16"/> /
/// <see cref="BitInRegister"/> / <see cref="Bcd16"/> = 1 register; <see cref="Int32"/> /
/// <see cref="UInt32"/> / <see cref="Float32"/> / <see cref="Bcd32"/> = 2 registers;
/// <see cref="Int64"/> / <see cref="UInt64"/> / <see cref="Float64"/> = 4 registers;
/// <see cref="String"/> = ceil(StringLength / 2) registers.
/// </summary>
/// <remarks>
/// Lives in the shared addressing assembly (alongside <see cref="ModbusRegion"/>) so the
/// Admin UI and the parser can speak about value types without taking a transport-layer
/// dependency on the wire driver.
/// </remarks>
public enum ModbusDataType
{
Bool,
Int16,
UInt16,
Int32,
UInt32,
Int64,
UInt64,
Float32,
Float64,
/// <summary>Single bit within a holding register. <c>BitIndex</c> selects 0-15 LSB-first.</summary>
BitInRegister,
/// <summary>ASCII string packed 2 chars per register, <c>StringLength</c> 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 the tag's
/// <see cref="ModbusByteOrder"/> the same way <see cref="Int32"/> does.
/// </summary>
Bcd32,
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="BigEndian"/> (<c>ABCD</c>) is the Modbus-spec default: high word at lower
/// address, big-endian within each register.
/// </para>
/// <para>
/// <see cref="WordSwap"/> (<c>CDAB</c>): keeps bytes big-endian within each register
/// but swaps the word pair. Common on Siemens S7 over Modbus, Allen-Bradley, several
/// Modicon families.
/// </para>
/// <para>
/// <see cref="ByteSwap"/> (<c>BADC</c>): 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.
/// </para>
/// <para>
/// <see cref="FullReverse"/> (<c>DCBA</c>): 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </remarks>
public enum ModbusByteOrder
{
BigEndian,
WordSwap,
ByteSwap,
FullReverse,
}
/// <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,
}

View File

@@ -0,0 +1,39 @@
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>
/// PLC family selector that drives the parser's family-native branch (#144). When the
/// driver is configured for a specific family, address strings using that family's native
/// notation (DirectLOGIC <c>V2000</c> octal, MELSEC <c>X20</c> hex/octal, etc.) are
/// translated to <see cref="ModbusRegion"/> + PDU offset directly — without forcing
/// integration engineers to pre-translate to Modicon notation.
/// </summary>
/// <remarks>
/// <para>
/// When set to <see cref="Generic"/> (the default), the parser only accepts Modicon and
/// mnemonic forms — preserves pre-#144 behaviour exactly. Setting a non-Generic family
/// is the only way to enable family-native parsing.
/// </para>
/// <para>
/// <b>Cross-family ambiguity</b>: <c>C100</c> means coil 100 under
/// <see cref="Generic"/>, but DL260 control-relay 100 under <see cref="DL205"/>, etc.
/// Per-driver Family selection makes the choice unambiguous within one driver instance;
/// users with mixed families need separate driver instances per device.
/// </para>
/// </remarks>
public enum ModbusFamily
{
/// <summary>Default — only Modicon (4xxxx) and mnemonic (HR1, C100) forms are accepted.</summary>
Generic,
/// <summary>
/// AutomationDirect DirectLOGIC (DL205 / DL260 / DL350). V-memory is octal; Y / C
/// are coils with hard-wired bank bases; X / SP are discrete inputs.
/// </summary>
DL205,
/// <summary>
/// Mitsubishi MELSEC. X / Y interpretation depends on sub-family selection — see
/// <see cref="MelsecFamily"/>. Defaults to Q/L/iQR (hex) when this family is selected.
/// </summary>
MELSEC,
}

View File

@@ -0,0 +1,116 @@
using System.Globalization;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>
/// Parses classic Modicon address strings — both 5-digit (<c>40001</c>) and 6-digit
/// (<c>400001</c>) forms — into the protocol-level <see cref="ModbusRegion"/> +
/// zero-based PDU offset the driver speaks on the wire.
/// </summary>
/// <remarks>
/// <para>
/// Modicon notation uses a leading region digit (<c>0</c> coil, <c>1</c> discrete input,
/// <c>3</c> input register, <c>4</c> holding register) followed by a 1-based register
/// number. The two forms differ only in how many trailing digits encode the register
/// number: 5-digit caps at 9999, 6-digit at 65535. Both decode to the same wire
/// representation — the PDU offset is always 0..65535 — so the only meaningful
/// distinction is range coverage.
/// </para>
/// <para>
/// Foundational helper for the addressing grammar work tracked in
/// <c>docs/v2/modbus-addressing.md</c>. The richer suffix grammar (type / bit /
/// byte-order / array) layered on top in a follow-up calls into this parser to extract
/// the region + offset before processing modifiers.
/// </para>
/// </remarks>
public static class ModbusModiconAddress
{
/// <summary>Parse a Modicon address string.</summary>
/// <param name="address">Either 5-digit (<c>40001</c>) or 6-digit (<c>400001</c>) form.</param>
/// <returns>Region + zero-based PDU offset the driver uses on the wire.</returns>
/// <exception cref="FormatException">When the input is not a valid Modicon address.</exception>
public static (ModbusRegion Region, ushort Offset) Parse(string address)
{
if (TryParse(address, out var region, out var offset, out var error))
return (region, offset);
throw new FormatException(error);
}
/// <summary>
/// Try-parse variant for hot-path / config-bind scenarios where a parse failure should
/// surface a structured diagnostic rather than throw. <paramref name="error"/> is
/// <c>null</c> on success.
/// </summary>
public static bool TryParse(string? address, out ModbusRegion region, out ushort offset, out string? error)
{
region = default;
offset = 0;
if (string.IsNullOrWhiteSpace(address))
{
error = "Modicon address is null or empty";
return false;
}
// Range check up-front — keeps the rest of the parser straight-line. 5-digit Modicon
// is always exactly 5 chars (40001..49999, with the lead digit selecting region), and
// 6-digit is exactly 6 (400001..465536-shaped). Anything else is unambiguously
// malformed so we reject before doing the per-character work.
var s = address.Trim();
if (s.Length is not (5 or 6))
{
error = $"Modicon address must be 5 or 6 digits, got {s.Length} ('{address}')";
return false;
}
if (!s.All(char.IsDigit))
{
error = $"Modicon address must contain only digits ('{address}')";
return false;
}
var leading = s[0];
region = leading switch
{
'0' => ModbusRegion.Coils,
'1' => ModbusRegion.DiscreteInputs,
'3' => ModbusRegion.InputRegisters,
'4' => ModbusRegion.HoldingRegisters,
_ => (ModbusRegion)(-1),
};
if ((int)region == -1)
{
error = $"Modicon address leading digit must be 0/1/3/4, got '{leading}'";
return false;
}
// The remaining 4 (5-digit) or 5 (6-digit) digits are the 1-based register number.
// 1-based-to-0-based conversion happens here so callers downstream uniformly see PDU
// offsets — which is what the wire format actually uses.
var registerNumberText = s[1..];
if (!int.TryParse(registerNumberText, NumberStyles.None, CultureInfo.InvariantCulture, out var registerNumber))
{
error = $"Modicon register number is not a valid integer ('{registerNumberText}')";
return false;
}
if (registerNumber < 1)
{
error = $"Modicon register number must be >= 1 (got {registerNumber})";
return false;
}
// 5-digit form caps at 9999 by construction (4 trailing digits); reject if the parsed
// value exceeds the wire-protocol maximum of 65536 (i.e. PDU offset 65535). 6-digit
// form can address the full 65535-offset range.
if (registerNumber > 65536)
{
error = $"Modicon register number {registerNumber} exceeds the wire maximum (65536 / PDU offset 65535)";
return false;
}
offset = (ushort)(registerNumber - 1);
error = null;
return true;
}
}

View File

@@ -0,0 +1,21 @@
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <summary>
/// The four Modbus register regions a tag can target. Maps directly to function-code
/// selection on the wire: <see cref="Coils"/> uses FC01/FC05/FC15, <see cref="DiscreteInputs"/>
/// uses FC02 (read-only), <see cref="InputRegisters"/> uses FC04 (read-only), and
/// <see cref="HoldingRegisters"/> uses FC03/FC06/FC16.
/// </summary>
/// <remarks>
/// Lives in the shared addressing assembly so Admin UI and the parser library can speak
/// about regions without taking a dependency on the wire driver. The driver-side
/// <c>Driver.Modbus</c> assembly extends the same namespace, so callers see this type as
/// if it lived in one place.
/// </remarks>
public enum ModbusRegion
{
Coils,
DiscreteInputs,
InputRegisters,
HoldingRegisters,
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<RootNamespace>ZB.MOM.WW.OtOpcUa.Driver.Modbus</RootNamespace>
<Description>Pure Modbus address-grammar parsing — shared by Driver.Modbus, Driver.Modbus.Cli, and Admin so the wire driver and the configuration UI agree on a single grammar definition. Namespace is intentionally identical to Driver.Modbus's so callers see addressing types as if they lived in one assembly; this assembly stays dependency-free so Admin can reference it without taking a transport-layer dep.</Description>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests"/>
</ItemGroup>
</Project>