using System.Text.Json; using System.Text.Json.Serialization; 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 driver factory registry to register with. public static void Register(DriverFactoryRegistry registry) { ArgumentNullException.ThrowIfNull(registry); registry.Register(DriverTypeName, CreateInstance); } /// /// 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) { ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId); var options = ParseOptions(driverInstanceId, driverConfigJson); return new AbCipDriver(options, driverInstanceId); } /// /// 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, "device", driverInstanceId, "PlcFamily", fallback: AbCipPlcFamily.ControlLogix), DeviceName: d.DeviceName, AllowPacking: d.AllowPacking, ConnectionSize: d.ConnectionSize))] : [], Tags = dto.Tags is { Count: > 0 } ? [.. dto.Tags.Select(t => BuildTag(t, driverInstanceId))] : [], Probe = new AbCipProbeOptions { Enabled = dto.Probe?.Enabled ?? true, Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000), Timeout = TimeSpan.FromMilliseconds(dto.Probe?.TimeoutMs ?? 2_000), ProbeTagPath = dto.Probe?.ProbeTagPath, }, Timeout = TimeSpan.FromMilliseconds(dto.TimeoutMs ?? 2_000), EnableControllerBrowse = dto.EnableControllerBrowse ?? false, EnableAlarmProjection = dto.EnableAlarmProjection ?? false, AlarmPollInterval = TimeSpan.FromMilliseconds(dto.AlarmPollIntervalMs ?? 1_000), EnableDeclarationOnlyUdtGrouping = dto.EnableDeclarationOnlyUdtGrouping ?? false, }; } private static AbCipTagDefinition BuildTag(AbCipTagDto t, string driverInstanceId) => new( Name: t.Name ?? throw new InvalidOperationException( $"AB CIP config for '{driverInstanceId}' has a tag missing Name"), DeviceHostAddress: t.DeviceHostAddress ?? throw new InvalidOperationException( $"AB CIP tag '{t.Name}' in '{driverInstanceId}' missing DeviceHostAddress"), TagPath: t.TagPath ?? throw new InvalidOperationException( $"AB CIP tag '{t.Name}' in '{driverInstanceId}' missing TagPath"), DataType: ParseEnum(t.DataType, t.Name, driverInstanceId, "DataType"), Writable: t.Writable ?? true, WriteIdempotent: t.WriteIdempotent ?? false, Members: t.Members is { Count: > 0 } ? [.. t.Members.Select(m => new AbCipStructureMember( Name: m.Name ?? throw new InvalidOperationException( $"AB CIP tag '{t.Name}' in '{driverInstanceId}' has a member missing Name"), DataType: ParseEnum(m.DataType, t.Name, driverInstanceId, $"Members[{m.Name}].DataType"), Writable: m.Writable ?? true, WriteIdempotent: m.WriteIdempotent ?? false, ElementCount: m.ElementCount is > 0 ? m.ElementCount.Value : 1, IsArray: m.IsArray))] : null, SafetyTag: t.SafetyTag ?? false, ElementCount: t.ElementCount is > 0 ? t.ElementCount.Value : 1, IsArray: t.IsArray); private static T ParseEnum(string? raw, string? tagName, string driverInstanceId, string field, T? fallback = null) where T : struct, Enum { if (string.IsNullOrWhiteSpace(raw)) { if (fallback.HasValue) return fallback.Value; throw new InvalidOperationException( $"AB CIP tag '{tagName ?? ""}' in '{driverInstanceId}' missing {field}"); } return Enum.TryParse(raw, ignoreCase: true, out var v) ? v : throw new InvalidOperationException( $"AB CIP 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 AbCipDriverConfigDto { /// /// 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 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 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 list of tags to monitor. /// public List? Tags { 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 AbCipTagDto { /// /// Gets or sets the tag name. /// public string? Name { get; init; } /// /// Gets or sets the device host address. /// public string? DeviceHostAddress { get; init; } /// /// Gets or sets the tag path. /// public string? TagPath { get; init; } /// /// Gets or sets the data type. /// public string? DataType { get; init; } /// /// Gets or sets whether the tag is writable. /// public bool? Writable { get; init; } /// /// Gets or sets whether write is idempotent. /// public bool? WriteIdempotent { get; init; } /// /// Gets or sets the list of structure members. /// public List? Members { get; init; } /// /// Gets or sets whether this is a safety tag. /// public bool? SafetyTag { get; init; } /// /// Gets or sets the explicit 1-D array signal — true ⟺ the tag is an array (even a /// 1-element one). Mirrors AbCipTagDefinition.IsArray; optional (absent ⇒ scalar). /// [JsonPropertyName("isArray")] public bool IsArray { get; init; } /// /// Gets or sets the number of elements for a 1-D array tag; 1 (or absent) for a scalar. /// Mirrors AbCipTagDefinition.ElementCount; only positive values are honoured. /// [JsonPropertyName("elementCount")] public int? ElementCount { get; init; } } internal sealed class AbCipMemberDto { /// /// Gets or sets the member name. /// public string? Name { get; init; } /// /// Gets or sets the data type. /// public string? DataType { get; init; } /// /// Gets or sets whether the member is writable. /// public bool? Writable { get; init; } /// /// Gets or sets whether write is idempotent. /// public bool? WriteIdempotent { get; init; } /// /// Gets or sets the explicit 1-D array signal for the member — true ⟺ the member is /// an array (even a 1-element one). Mirrors AbCipStructureMember.IsArray; optional. /// [JsonPropertyName("isArray")] public bool IsArray { get; init; } /// /// Gets or sets the number of elements for a 1-D array member; 1 (or absent) for a /// scalar. Mirrors AbCipStructureMember.ElementCount; only positive values are honoured. /// [JsonPropertyName("elementCount")] public int? ElementCount { 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; } } }