Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipDriverFactoryExtensions.cs
T
Joseph Doherty 826312befe docs: fill missing XML docs and strip tracking IDs from src comments
Clears CommentChecker findings in src/ (3,280 -> 209, the remainder being false
positives like PLC-5/IEEE-754/M0.0) by adding missing summaries/params/returns,
normalising inheritdoc usage, and removing Gitea/review tracking IDs while keeping
the rationale they annotated. Comment-only: comment-stripped sources are identical
to the parent commit.
2026-10-15 06:14:58 -04:00

276 lines
13 KiB
C#

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;
/// <summary>
/// Static factory registration helper for <see cref="AbCipDriver"/>. Server's Program.cs
/// calls <see cref="Register"/> once at startup; the bootstrapper then
/// materialises AB CIP DriverInstance rows from the central config DB into live driver
/// instances. Mirrors <c>GalaxyProxyDriverFactoryExtensions</c>.
/// </summary>
public static class AbCipDriverFactoryExtensions
{
public const string DriverTypeName = "AbCip";
/// <summary>
/// Registers the AB CIP driver factory with the driver registry. The optional
/// <paramref name="loggerFactory"/> is captured at registration time and used to construct an
/// <see cref="ILogger{AbCipDriver}"/> 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.
/// </summary>
/// <param name="registry">The driver factory registry to register with.</param>
/// <param name="loggerFactory">Optional logger factory for driver instances.</param>
/// <param name="defaultTransport">The node-level transport for drivers whose config has no
/// <c>transport</c> key (<c>Drivers:AbCip:DefaultTransport</c>, final review I1). An explicit
/// per-driver key still wins.</param>
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));
}
/// <summary>
/// Creates an instance of the AB CIP driver from configuration.
/// </summary>
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
/// <param name="driverConfigJson">The driver configuration as a JSON string.</param>
/// <returns>A configured <see cref="AbCipDriver"/> instance.</returns>
internal static AbCipDriver CreateInstance(string driverInstanceId, string driverConfigJson)
=> CreateInstance(driverInstanceId, driverConfigJson, loggerFactory: null);
/// <summary>Creates an instance of the AB CIP driver with an optional logger.</summary>
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
/// <param name="driverConfigJson">The driver configuration as a JSON string.</param>
/// <param name="loggerFactory">Optional logger factory for the driver instance.</param>
/// <param name="defaultTransport">The node-level default for an absent <c>transport</c> key.</param>
/// <returns>A configured <see cref="AbCipDriver"/> instance.</returns>
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<AbCipDriver>(),
defaultTransport: defaultTransport);
}
/// <summary>
/// Deserialise an AB CIP driver-config JSON document into <see cref="AbCipDriverOptions"/>.
/// Shared by <see cref="CreateInstance(string, string, ILoggerFactory?, AbCipTransport)"/> (first construction) and
/// <see cref="AbCipDriver.InitializeAsync"/> / <see cref="AbCipDriver.ReinitializeAsync"/>
/// so a reinitialize with a changed config JSON (new device, new tag, changed timeout)
/// actually takes effect rather than being silently discarded.
/// </summary>
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
/// <param name="driverConfigJson">The driver configuration as a JSON string.</param>
/// <returns>Parsed driver options.</returns>
internal static AbCipDriverOptions ParseOptions(string driverInstanceId, string driverConfigJson)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);
var dto = JsonSerializer.Deserialize<AbCipDriverConfigDto>(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<AbCipPlcFamily>(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<AbCipTransport>(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,
};
}
/// <summary>
/// Maps an operator-supplied timeout (ms) to a positive <see cref="TimeSpan"/>, substituting
/// <paramref name="defaultMs"/> for a null / zero / negative value. libplctag's managed
/// <c>Tag.Timeout</c> setter throws <see cref="ArgumentOutOfRangeException"/> for a
/// non-positive value, which would otherwise fault tag creation on every read/write; clamping
/// here keeps a misconfigured <c>TimeoutMs: 0</c> running on the default bound instead. (Driver
/// timeout hardening, sibling of the S7 read-leg fix.)
/// </summary>
/// <param name="ms">The operator-supplied timeout in milliseconds, or null.</param>
/// <param name="defaultMs">The default applied when <paramref name="ms"/> is null or non-positive.</param>
/// <returns>A strictly positive timeout.</returns>
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<T>(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<T>(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<T>())}");
}
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
internal sealed class AbCipDriverConfigDto
{
/// <summary>
/// Gets or sets the transport (<c>Libplctag</c> or <c>Native</c>, case-insensitive); absent means the node default.
/// </summary>
public string? Transport { get; init; }
/// <summary>
/// Gets or sets the timeout in milliseconds for operations.
/// </summary>
public int? TimeoutMs { get; init; }
/// <summary>
/// Gets or sets whether controller browsing is enabled.
/// </summary>
public bool? EnableControllerBrowse { get; init; }
/// <summary>
/// Gets or sets the pause in milliseconds between symbol-listing pages (native transport); absent means 5.
/// </summary>
public int? BrowsePageDelayMs { get; init; }
/// <summary>
/// Gets or sets whether alarm projection is enabled.
/// </summary>
public bool? EnableAlarmProjection { get; init; }
/// <summary>
/// Gets or sets whether declaration-only UDT grouping is enabled.
/// </summary>
public bool? EnableDeclarationOnlyUdtGrouping { get; init; }
/// <summary>
/// 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.
/// </summary>
public int? MaxConcurrentReads { get; init; }
/// <summary>
/// Gets or sets the alarm poll interval in milliseconds.
/// </summary>
public int? AlarmPollIntervalMs { get; init; }
/// <summary>
/// Gets or sets the list of devices to connect to.
/// </summary>
public List<AbCipDeviceDto>? Devices { get; init; }
/// <summary>
/// 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.
/// </summary>
public List<RawTagEntry>? RawTags { get; init; }
/// <summary>
/// Gets or sets the probe configuration.
/// </summary>
public AbCipProbeDto? Probe { get; init; }
}
internal sealed class AbCipDeviceDto
{
/// <summary>
/// Gets or sets the host address of the device.
/// </summary>
public string? HostAddress { get; init; }
/// <summary>
/// Gets or sets the PLC family.
/// </summary>
public string? PlcFamily { get; init; }
/// <summary>
/// Gets or sets the device name.
/// </summary>
public string? DeviceName { get; init; }
/// <summary>
/// Gets or sets whether packing is allowed.
/// </summary>
public bool? AllowPacking { get; init; }
/// <summary>
/// Gets or sets the connection size.
/// </summary>
public int? ConnectionSize { get; init; }
}
internal sealed class AbCipProbeDto
{
/// <summary>
/// Gets or sets whether probing is enabled.
/// </summary>
public bool? Enabled { get; init; }
/// <summary>
/// Gets or sets the probe interval in milliseconds.
/// </summary>
public int? IntervalMs { get; init; }
/// <summary>
/// Gets or sets the probe timeout in milliseconds.
/// </summary>
public int? TimeoutMs { get; init; }
/// <summary>
/// Gets or sets the probe tag path.
/// </summary>
public string? ProbeTagPath { get; init; }
}
}