using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.Extensions.Logging; using ZB.MOM.WW.OtOpcUa.Core.Hosting; namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus; /// /// Static factory registration helper for . Server's Program.cs /// calls once at startup; the bootstrapper (task #248) then /// materialises Modbus DriverInstance rows from the central config DB into live driver /// instances. Mirrors GalaxyProxyDriverFactoryExtensions / FocasDriverFactoryExtensions. /// public static class ModbusDriverFactoryExtensions { public const string DriverTypeName = "Modbus"; /// /// Register the Modbus factory with the driver registry. The optional /// is captured at registration time and used to /// construct an per driver instance — without it, /// the driver runs with the null logger (existing tests and standalone callers stay /// unchanged). /// /// The driver factory registry to register with. /// Optional logger factory for creating loggers per driver instance. public static void Register(DriverFactoryRegistry registry, ILoggerFactory? loggerFactory = null) { ArgumentNullException.ThrowIfNull(registry); registry.Register(DriverTypeName, (id, json) => CreateInstance(id, json, loggerFactory)); } /// Public for the Server-side bootstrapper + test consumers (Admin.Tests, etc.). /// The unique identifier for the driver instance. /// The JSON configuration string for the driver. public static ModbusDriver CreateInstance(string driverInstanceId, string driverConfigJson) => CreateInstance(driverInstanceId, driverConfigJson, loggerFactory: null); /// Logger-aware overload — used by 's closure when wired through DI. /// The unique identifier for the driver instance. /// The JSON configuration string for the driver. /// Optional logger factory for creating loggers per driver instance. public static ModbusDriver CreateInstance(string driverInstanceId, string driverConfigJson, ILoggerFactory? loggerFactory) { ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId); ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson); var dto = JsonSerializer.Deserialize(driverConfigJson, JsonOptions) ?? throw new InvalidOperationException( $"Modbus driver config for '{driverInstanceId}' deserialised to null"); if (string.IsNullOrWhiteSpace(dto.Host)) throw new InvalidOperationException( $"Modbus driver config for '{driverInstanceId}' missing required Host"); var options = new ModbusDriverOptions { Host = dto.Host!, Port = dto.Port ?? 502, UnitId = dto.UnitId ?? 1, Timeout = TimeSpan.FromMilliseconds(dto.TimeoutMs ?? 2_000), MaxRegistersPerRead = dto.MaxRegistersPerRead ?? 125, MaxRegistersPerWrite = dto.MaxRegistersPerWrite ?? 123, MaxCoilsPerRead = dto.MaxCoilsPerRead ?? 2000, UseFC15ForSingleCoilWrites = dto.UseFC15ForSingleCoilWrites ?? false, UseFC16ForSingleRegisterWrites = dto.UseFC16ForSingleRegisterWrites ?? false, DisableFC23 = dto.DisableFC23 ?? false, WriteOnChangeOnly = dto.WriteOnChangeOnly ?? false, MaxReadGap = dto.MaxReadGap ?? 0, Family = dto.Family is null ? ModbusFamily.Generic : ParseEnum(dto.Family, "", driverInstanceId, "Family"), MelsecSubFamily = dto.MelsecSubFamily is null ? MelsecFamily.Q_L_iQR : ParseEnum(dto.MelsecSubFamily, "", driverInstanceId, "MelsecSubFamily"), AutoProhibitReprobeInterval = dto.AutoProhibitReprobeMs is { } reprobeMs ? TimeSpan.FromMilliseconds(reprobeMs) : null, AutoReconnect = dto.AutoReconnect ?? true, Tags = dto.Tags is { Count: > 0 } ? [.. dto.Tags.Select(t => BuildTag( t, driverInstanceId, dto.Family is null ? ModbusFamily.Generic : ParseEnum(dto.Family, "", driverInstanceId, "Family"), dto.MelsecSubFamily is null ? MelsecFamily.Q_L_iQR : ParseEnum(dto.MelsecSubFamily, "", driverInstanceId, "MelsecSubFamily")))] : [], Probe = new ModbusProbeOptions { Enabled = dto.Probe?.Enabled ?? true, Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000), Timeout = TimeSpan.FromMilliseconds(dto.Probe?.TimeoutMs ?? 2_000), ProbeAddress = dto.Probe?.ProbeAddress ?? 0, }, KeepAlive = dto.KeepAlive is null ? new ModbusKeepAliveOptions() : new ModbusKeepAliveOptions { Enabled = dto.KeepAlive.Enabled ?? true, Time = TimeSpan.FromMilliseconds(dto.KeepAlive.TimeMs ?? 30_000), Interval = TimeSpan.FromMilliseconds(dto.KeepAlive.IntervalMs ?? 10_000), RetryCount = dto.KeepAlive.RetryCount ?? 3, }, IdleDisconnectTimeout = dto.IdleDisconnectMs is { } ms ? TimeSpan.FromMilliseconds(ms) : null, Reconnect = dto.Reconnect is null ? new ModbusReconnectOptions() : new ModbusReconnectOptions { InitialDelay = TimeSpan.FromMilliseconds(dto.Reconnect.InitialDelayMs ?? 0), MaxDelay = TimeSpan.FromMilliseconds(dto.Reconnect.MaxDelayMs ?? 30_000), BackoffMultiplier = dto.Reconnect.BackoffMultiplier ?? 2.0, }, }; return new ModbusDriver( options, driverInstanceId, transportFactory: null, logger: loggerFactory?.CreateLogger()); } private static ModbusTagDefinition BuildTag(ModbusTagDto t, string driverInstanceId) => BuildTag(t, driverInstanceId, ModbusFamily.Generic, MelsecFamily.Q_L_iQR); private static ModbusTagDefinition BuildTag(ModbusTagDto t, string driverInstanceId, ModbusFamily family, MelsecFamily melsecSubFamily) { var name = t.Name ?? throw new InvalidOperationException( $"Modbus config for '{driverInstanceId}' has a tag missing Name"); // Driver.Modbus-009: a String tag with StringLength = 0 yields RegisterCount = 0, which // turns into an FC03/FC04 with quantity 0 — a spec-illegal request the PLC rejects with // exception 03. Catch the misconfiguration at bind time with a clear diagnostic instead // of waiting for the cryptic Illegal Data Value to surface at runtime. // 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. ModbusTagDefinition tag; if (!string.IsNullOrWhiteSpace(t.AddressString)) { if (!ModbusAddressParser.TryParse(t.AddressString, family, melsecSubFamily, out var parsed, out var parseError)) throw new InvalidOperationException( $"Modbus tag '{name}' in '{driverInstanceId}' has invalid AddressString '{t.AddressString}': {parseError}"); tag = 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, Deadband: t.Deadband, UnitId: t.UnitId); } else { tag = 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"), DataType: ParseEnum(t.DataType, t.Name, driverInstanceId, "DataType"), Writable: t.Writable ?? true, ByteOrder: t.ByteOrder is null ? ModbusByteOrder.BigEndian : ParseEnum(t.ByteOrder, t.Name, driverInstanceId, "ByteOrder"), BitIndex: t.BitIndex ?? 0, StringLength: t.StringLength ?? 0, StringByteOrder: t.StringByteOrder is null ? ModbusStringByteOrder.HighByteFirst : ParseEnum(t.StringByteOrder, t.Name, driverInstanceId, "StringByteOrder"), WriteIdempotent: t.WriteIdempotent ?? false, ArrayCount: t.ArrayCount, Deadband: t.Deadband, UnitId: t.UnitId); } ValidateStringLength(tag, driverInstanceId); return tag; } /// /// Driver.Modbus-009: reject StringLength = 0 for String-typed tags. The /// driver computes RegisterCount = (StringLength + 1) / 2 which would emit an /// FC03/FC04 with quantity = 0, a spec-illegal request the PLC rejects with /// exception 03 (Illegal Data Value). Surface as a clear bind-time error. /// private static void ValidateStringLength(ModbusTagDefinition tag, string driverInstanceId) { if (tag.DataType == ModbusDataType.String && tag.StringLength < 1) throw new InvalidOperationException( $"Modbus tag '{tag.Name}' in '{driverInstanceId}' has DataType=String but StringLength={tag.StringLength}. " + $"String tags must declare StringLength >= 1 (the number of ASCII characters, packed 2 per register)."); } private static T ParseEnum(string? raw, string? tagName, string driverInstanceId, string field) where T : struct, Enum { if (string.IsNullOrWhiteSpace(raw)) throw new InvalidOperationException( $"Modbus tag '{tagName ?? ""}' in '{driverInstanceId}' missing {field}"); return Enum.TryParse(raw, ignoreCase: true, out var v) ? v : throw new InvalidOperationException( $"Modbus tag '{tagName}' has unknown {field} '{raw}'. " + $"Expected one of {string.Join(", ", Enum.GetNames())}"); } private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; internal sealed class ModbusDriverConfigDto { /// Gets or sets the host address. public string? Host { get; init; } /// Gets or sets the port number. public int? Port { get; init; } /// Gets or sets the unit identifier. public byte? UnitId { get; init; } /// Gets or sets the timeout in milliseconds. public int? TimeoutMs { get; init; } /// Gets or sets the maximum number of registers per read operation. public ushort? MaxRegistersPerRead { get; init; } /// Gets or sets the maximum number of registers per write operation. public ushort? MaxRegistersPerWrite { get; init; } /// Gets or sets the maximum number of coils per read operation. public ushort? MaxCoilsPerRead { get; init; } /// Gets or sets a value indicating whether to use function code 15 for single coil writes. public bool? UseFC15ForSingleCoilWrites { get; init; } /// Gets or sets a value indicating whether to use function code 16 for single register writes. public bool? UseFC16ForSingleRegisterWrites { get; init; } /// Gets or sets a value indicating whether to disable function code 23. public bool? DisableFC23 { get; init; } /// Gets or sets a value indicating whether to write only on change. public bool? WriteOnChangeOnly { get; init; } /// Gets or sets the maximum gap between register addresses for coalescing. public ushort? MaxReadGap { get; init; } /// Gets or sets the Modbus family type. public string? Family { get; init; } /// Gets or sets the Melsec subfamily. public string? MelsecSubFamily { get; init; } /// Gets or sets the automatic prohibition reprobei interval in milliseconds. public int? AutoProhibitReprobeMs { get; init; } /// Gets or sets a value indicating whether automatic reconnection is enabled. public bool? AutoReconnect { get; init; } /// Gets or sets the collection of tag definitions. public List? Tags { get; init; } /// Gets or sets the probe configuration. public ModbusProbeDto? Probe { get; init; } /// Gets or sets the keep-alive configuration (connection-layer knob #139). public ModbusKeepAliveDto? KeepAlive { get; init; } /// Gets or sets the idle disconnect timeout in milliseconds. public int? IdleDisconnectMs { get; init; } /// Gets or sets the reconnect configuration. public ModbusReconnectDto? Reconnect { get; init; } } internal sealed class ModbusKeepAliveDto { /// Gets or sets a value indicating whether keep-alive is enabled. public bool? Enabled { get; init; } /// Gets or sets the keep-alive time in milliseconds. public int? TimeMs { get; init; } /// Gets or sets the keep-alive interval in milliseconds. public int? IntervalMs { get; init; } /// Gets or sets the retry count. public int? RetryCount { get; init; } } internal sealed class ModbusReconnectDto { /// Gets or sets the initial reconnect delay in milliseconds. public int? InitialDelayMs { get; init; } /// Gets or sets the maximum reconnect delay in milliseconds. public int? MaxDelayMs { get; init; } /// Gets or sets the backoff multiplier for exponential reconnect delays. public double? BackoffMultiplier { get; init; } } internal sealed class ModbusTagDto { /// Gets or sets the tag name. 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:I", "C100". /// public string? AddressString { get; init; } /// Gets or sets the register region. public string? Region { get; init; } /// Gets or sets the starting address. public ushort? Address { get; init; } /// Gets or sets the data type. public string? DataType { get; init; } /// Gets or sets a value indicating whether the tag is writable. public bool? Writable { get; init; } /// Gets or sets the byte order. public string? ByteOrder { get; init; } /// Gets or sets the bit index for bit-level tags. public byte? BitIndex { get; init; } /// Gets or sets the string length for string-typed tags. public ushort? StringLength { get; init; } /// Gets or sets the byte order for string values. public string? StringByteOrder { get; init; } /// Gets or sets a value indicating whether writes are idempotent. public bool? WriteIdempotent { get; init; } /// Gets or sets the array count for array-typed tags. public int? ArrayCount { get; init; } /// Gets or sets the deadband for change detection. public double? Deadband { get; init; } /// Gets or sets the unit identifier for this tag. public byte? UnitId { get; init; } } internal sealed class ModbusProbeDto { /// Gets or sets a value indicating whether probing is enabled. public bool? Enabled { get; init; } /// Gets or sets the probe interval in milliseconds. public int? IntervalMs { get; init; } /// Gets or sets the probe timeout in milliseconds. public int? TimeoutMs { get; init; } /// Gets or sets the probe register address. public ushort? ProbeAddress { get; init; } } }