using System.Text.Json; using Microsoft.Extensions.Logging; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Hosting; namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip; /// /// Static factory registration helper for . Server's Program.cs /// calls once at startup; the bootstrapper then /// materialises AB CIP DriverInstance rows from the central config DB into live driver /// instances. Mirrors GalaxyProxyDriverFactoryExtensions. /// public static class AbCipDriverFactoryExtensions { public const string DriverTypeName = "AbCip"; /// /// Registers the AB CIP driver 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, so none of its diagnostics (including the per-init transport line) reach the /// node log. Mirrors the AbLegacy / Modbus registration pattern. /// /// The driver factory registry to register with. /// Optional logger factory for driver instances. /// The node-level transport for drivers whose config has no /// transport key (Drivers:AbCip:DefaultTransport, final review I1). An explicit /// per-driver key still wins. public static void Register(DriverFactoryRegistry registry, ILoggerFactory? loggerFactory = null, AbCipTransport defaultTransport = AbCipTransportResolver.Default) { ArgumentNullException.ThrowIfNull(registry); registry.Register(DriverTypeName, (id, json) => CreateInstance(id, json, loggerFactory, defaultTransport)); } /// /// Creates an instance of the AB CIP driver from configuration. /// /// The unique identifier for this driver instance. /// The driver configuration as a JSON string. /// A configured instance. internal static AbCipDriver CreateInstance(string driverInstanceId, string driverConfigJson) => CreateInstance(driverInstanceId, driverConfigJson, loggerFactory: null); /// Creates an instance of the AB CIP driver with an optional logger. /// The unique identifier for this driver instance. /// The driver configuration as a JSON string. /// Optional logger factory for the driver instance. /// The node-level default for an absent transport key. /// A configured instance. internal static AbCipDriver CreateInstance( string driverInstanceId, string driverConfigJson, ILoggerFactory? loggerFactory, AbCipTransport defaultTransport = AbCipTransportResolver.Default) { ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId); var options = ParseOptions(driverInstanceId, driverConfigJson); return new AbCipDriver(options, driverInstanceId, logger: loggerFactory?.CreateLogger(), defaultTransport: defaultTransport); } /// /// Deserialise an AB CIP driver-config JSON document into . /// Shared by (first construction) and /// / /// so a reinitialize with a changed config JSON (new device, new tag, changed timeout) /// actually takes effect rather than being silently discarded. /// /// The unique identifier for this driver instance. /// The driver configuration as a JSON string. /// Parsed driver options. internal static AbCipDriverOptions ParseOptions(string driverInstanceId, string driverConfigJson) { ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId); ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson); var dto = JsonSerializer.Deserialize(driverConfigJson, JsonOptions) ?? throw new InvalidOperationException( $"AB CIP driver config for '{driverInstanceId}' deserialised to null"); return new AbCipDriverOptions { Devices = dto.Devices is { Count: > 0 } ? [.. dto.Devices.Select(d => new AbCipDeviceOptions( HostAddress: d.HostAddress ?? throw new InvalidOperationException( $"AB CIP config for '{driverInstanceId}' has a device missing HostAddress"), PlcFamily: ParseEnum(d.PlcFamily, tagName: null, driverInstanceId, "PlcFamily", fallback: AbCipPlcFamily.ControlLogix), DeviceName: d.DeviceName, AllowPacking: d.AllowPacking, ConnectionSize: d.ConnectionSize))] : [], // v3: the deploy artifact (Wave C) populates RawTags with the cluster's authored raw AbCip // tags (RawPath + TagConfig blob + WriteIdempotent + DeviceName). The driver maps each entry // through AbCipTagDefinitionFactory.FromTagConfig at Initialize; the legacy pre-declared DTO // tag path (structured Tags[] → BuildTag) is retired. RawTags = dto.RawTags is { Count: > 0 } ? [.. dto.RawTags] : [], Probe = new AbCipProbeOptions { Enabled = dto.Probe?.Enabled ?? true, Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000), Timeout = PositiveTimeoutOrDefault(dto.Probe?.TimeoutMs, 2_000), ProbeTagPath = dto.Probe?.ProbeTagPath, }, Timeout = PositiveTimeoutOrDefault(dto.TimeoutMs, 2_000), // Absent ⇒ null ("use the default", resolved by AbCipTransportResolver); a bad value still // fails exactly as any other bad enum field does. Transport = string.IsNullOrWhiteSpace(dto.Transport) ? null : ParseEnum(dto.Transport, tagName: null, driverInstanceId, "Transport"), EnableControllerBrowse = dto.EnableControllerBrowse ?? false, BrowsePageDelay = TimeSpan.FromMilliseconds(Math.Max(0, dto.BrowsePageDelayMs ?? 5)), EnableAlarmProjection = dto.EnableAlarmProjection ?? false, AlarmPollInterval = TimeSpan.FromMilliseconds(dto.AlarmPollIntervalMs ?? 1_000), EnableDeclarationOnlyUdtGrouping = dto.EnableDeclarationOnlyUdtGrouping ?? false, MaxConcurrentReads = dto.MaxConcurrentReads ?? 8, }; } /// /// Maps an operator-supplied timeout (ms) to a positive , substituting /// for a null / zero / negative value. libplctag's managed /// Tag.Timeout setter throws for a /// non-positive value, which would otherwise fault tag creation on every read/write; clamping /// here keeps a misconfigured TimeoutMs: 0 running on the default bound instead. (Driver /// timeout hardening, sibling of the S7 read-leg fix.) /// /// The operator-supplied timeout in milliseconds, or null. /// The default applied when is null or non-positive. /// A strictly positive timeout. private static TimeSpan PositiveTimeoutOrDefault(int? ms, int defaultMs) => TimeSpan.FromMilliseconds(ms is int v and > 0 ? v : defaultMs); // tagName null = a driver-level (or device-level) config field: the error text names the driver config, // not a tag. Never pass a placeholder like "device" as tagName — it renders as "tag 'device'". private static T ParseEnum(string? raw, string? tagName, string driverInstanceId, string field, T? fallback = null) where T : struct, Enum { var subject = tagName is null ? $"config in '{driverInstanceId}'" : $"tag '{tagName}'"; if (string.IsNullOrWhiteSpace(raw)) { if (fallback.HasValue) return fallback.Value; throw new InvalidOperationException( tagName is null ? $"AB CIP {subject} missing {field}" : $"AB CIP {subject} in '{driverInstanceId}' missing {field}"); } // Enum.TryParse also accepts any integer string ("7"), defined or not; an undefined value would // otherwise fall through to a switch's default arm silently. return Enum.TryParse(raw, ignoreCase: true, out var v) && Enum.IsDefined(v) ? v : throw new InvalidOperationException( $"AB CIP {subject} 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 AbCipDriverConfigDto { /// /// Gets or sets the transport (Libplctag or Native, case-insensitive); absent means the node default. /// public string? Transport { get; init; } /// /// Gets or sets the timeout in milliseconds for operations. /// public int? TimeoutMs { get; init; } /// /// Gets or sets whether controller browsing is enabled. /// public bool? EnableControllerBrowse { get; init; } /// /// Gets or sets the pause in milliseconds between symbol-listing pages (native transport); absent means 5. /// public int? BrowsePageDelayMs { get; init; } /// /// Gets or sets whether alarm projection is enabled. /// public bool? EnableAlarmProjection { get; init; } /// /// Gets or sets whether declaration-only UDT grouping is enabled. /// public bool? EnableDeclarationOnlyUdtGrouping { get; init; } /// /// Gets or sets the maximum number of read work items one ReadAsync batch may have in /// flight against the controller at once. Bounds concurrency across tags only; the per-tag /// runtime lock still serialises operations on any one handle. Defaults to 8; 1 is sequential. /// public int? MaxConcurrentReads { get; init; } /// /// Gets or sets the alarm poll interval in milliseconds. /// public int? AlarmPollIntervalMs { get; init; } /// /// Gets or sets the list of devices to connect to. /// public List? Devices { get; init; } /// /// Gets or sets the authored raw tags (RawPath + TagConfig blob + WriteIdempotent + DeviceName) /// the deploy artifact delivers. The driver maps each through the tag-definition factory at Initialize. /// public List? RawTags { get; init; } /// /// Gets or sets the probe configuration. /// public AbCipProbeDto? Probe { get; init; } } internal sealed class AbCipDeviceDto { /// /// Gets or sets the host address of the device. /// public string? HostAddress { get; init; } /// /// Gets or sets the PLC family. /// public string? PlcFamily { get; init; } /// /// Gets or sets the device name. /// public string? DeviceName { get; init; } /// /// Gets or sets whether packing is allowed. /// public bool? AllowPacking { get; init; } /// /// Gets or sets the connection size. /// public int? ConnectionSize { get; init; } } internal sealed class AbCipProbeDto { /// /// Gets or sets 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 tag path. /// public string? ProbeTagPath { get; init; } } }