Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.S7/S7DriverFactoryExtensions.cs
T
Joseph Doherty 9f62f2c242 refactor(driver-s7): extract S7DriverOptions to .Contracts with parallel CpuType enum
Introduces Driver.S7.Contracts (dependency-free POCO project) and moves
S7DriverOptions / S7ProbeOptions / S7TagDefinition / S7DataType into it.
Adds S7CpuType enum mirroring S7.Net.CpuType exactly (7 values with
explicit integer codes). Runtime S7CpuTypeMap bridges S7CpuType →
S7.Net.CpuType at the single Plc construction site in S7Driver.InitializeAsync.
S7DriverFactoryExtensions and S7CommandBase updated to use S7CpuType; test
files updated to match (S7_1500Profile, S7DriverScaffoldTests). AdminUI can
now reference Driver.S7.Contracts without pulling in S7netplus.
2026-05-28 09:08:27 -04:00

167 lines
7.9 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
namespace ZB.MOM.WW.OtOpcUa.Driver.S7;
/// <summary>
/// Static factory registration helper for <see cref="S7Driver"/>. Server's Program.cs
/// calls <see cref="Register"/> once at startup; the bootstrapper (task #248) then
/// materialises S7 DriverInstance rows from the central config DB into live driver
/// instances. Mirrors <c>GalaxyProxyDriverFactoryExtensions</c>.
/// </summary>
public static class S7DriverFactoryExtensions
{
public const string DriverTypeName = "S7";
/// <summary>Registers the S7 driver factory with the registry.</summary>
/// <param name="registry">The driver factory registry.</param>
public static void Register(DriverFactoryRegistry registry)
{
ArgumentNullException.ThrowIfNull(registry);
registry.Register(DriverTypeName, CreateInstance);
}
/// <summary>Creates a new S7 driver instance from configuration.</summary>
/// <param name="driverInstanceId">The unique identifier for the driver instance.</param>
/// <param name="driverConfigJson">The JSON configuration for the driver.</param>
/// <returns>A newly created S7 driver instance.</returns>
internal static S7Driver CreateInstance(string driverInstanceId, string driverConfigJson)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);
return new S7Driver(ParseOptions(driverInstanceId, driverConfigJson), driverInstanceId);
}
/// <summary>
/// Parse a driver-config JSON document into a strongly-typed <see cref="S7DriverOptions"/>.
/// Shared by the factory (instance creation) and by <see cref="S7Driver.InitializeAsync"/>
/// / <see cref="S7Driver.ReinitializeAsync"/> so a config change delivered through the
/// <c>IDriver</c> contract is actually applied — see code-review finding Driver.S7-011.
/// </summary>
/// <param name="driverInstanceId">The unique identifier for the driver instance.</param>
/// <param name="driverConfigJson">The JSON configuration for the driver.</param>
/// <returns>Parsed S7 driver options.</returns>
internal static S7DriverOptions ParseOptions(string driverInstanceId, string driverConfigJson)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);
var dto = JsonSerializer.Deserialize<S7DriverConfigDto>(driverConfigJson, JsonOptions)
?? throw new InvalidOperationException(
$"S7 driver config for '{driverInstanceId}' deserialised to null");
if (string.IsNullOrWhiteSpace(dto.Host))
throw new InvalidOperationException(
$"S7 driver config for '{driverInstanceId}' missing required Host");
return new S7DriverOptions
{
Host = dto.Host!,
Port = dto.Port ?? 102,
CpuType = ParseEnum<S7CpuType>(dto.CpuType, driverInstanceId, "CpuType",
fallback: S7CpuType.S71500),
Rack = dto.Rack ?? 0,
Slot = dto.Slot ?? 0,
Timeout = TimeSpan.FromMilliseconds(dto.TimeoutMs ?? 5_000),
Tags = dto.Tags is { Count: > 0 }
? [.. dto.Tags.Select(t => BuildTag(t, driverInstanceId))]
: [],
Probe = new S7ProbeOptions
{
Enabled = dto.Probe?.Enabled ?? true,
Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000),
Timeout = TimeSpan.FromMilliseconds(dto.Probe?.TimeoutMs ?? 2_000),
// Driver.S7-012: ProbeAddress removed — probe uses ReadStatusAsync, not a tag read.
},
};
}
private static S7TagDefinition BuildTag(S7TagDto t, string driverInstanceId) =>
new(
Name: t.Name ?? throw new InvalidOperationException(
$"S7 config for '{driverInstanceId}' has a tag missing Name"),
Address: t.Address ?? throw new InvalidOperationException(
$"S7 tag '{t.Name}' in '{driverInstanceId}' missing Address"),
DataType: ParseEnum<S7DataType>(t.DataType, driverInstanceId, "DataType",
tagName: t.Name),
Writable: t.Writable ?? true,
StringLength: t.StringLength ?? 254,
WriteIdempotent: t.WriteIdempotent ?? false);
private static T ParseEnum<T>(string? raw, string driverInstanceId, string field,
string? tagName = null, T? fallback = null) where T : struct, Enum
{
if (string.IsNullOrWhiteSpace(raw))
{
if (fallback.HasValue) return fallback.Value;
throw new InvalidOperationException(
$"S7 tag '{tagName ?? "<unnamed>"}' in '{driverInstanceId}' missing {field}");
}
return Enum.TryParse<T>(raw, ignoreCase: true, out var v)
? v
: throw new InvalidOperationException(
$"S7 {(tagName is null ? "config" : $"tag '{tagName}'")} 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,
};
/// <summary>Data transfer object for S7 driver configuration.</summary>
internal sealed class S7DriverConfigDto
{
/// <summary>Gets the PLC host address.</summary>
public string? Host { get; init; }
/// <summary>Gets the PLC port.</summary>
public int? Port { get; init; }
/// <summary>Gets the CPU type name.</summary>
public string? CpuType { get; init; }
/// <summary>Gets the rack number.</summary>
public short? Rack { get; init; }
/// <summary>Gets the slot number.</summary>
public short? Slot { get; init; }
/// <summary>Gets the connection timeout in milliseconds.</summary>
public int? TimeoutMs { get; init; }
/// <summary>Gets the list of tag definitions.</summary>
public List<S7TagDto>? Tags { get; init; }
/// <summary>Gets the probe configuration.</summary>
public S7ProbeDto? Probe { get; init; }
}
/// <summary>Data transfer object for S7 tag definition.</summary>
internal sealed class S7TagDto
{
/// <summary>Gets the tag name.</summary>
public string? Name { get; init; }
/// <summary>Gets the S7 address (e.g., DB1.DBD0).</summary>
public string? Address { get; init; }
/// <summary>Gets the data type name.</summary>
public string? DataType { get; init; }
/// <summary>Gets a value indicating whether the tag is writable.</summary>
public bool? Writable { get; init; }
/// <summary>Gets the string length for string types.</summary>
public int? StringLength { get; init; }
/// <summary>Gets a value indicating whether write is idempotent.</summary>
public bool? WriteIdempotent { get; init; }
}
/// <summary>Data transfer object for S7 probe configuration.</summary>
internal sealed class S7ProbeDto
{
/// <summary>Gets a value indicating whether probing is enabled.</summary>
public bool? Enabled { get; init; }
/// <summary>Gets the probe interval in milliseconds.</summary>
public int? IntervalMs { get; init; }
/// <summary>Gets the probe timeout in milliseconds.</summary>
public int? TimeoutMs { get; init; }
// Driver.S7-012: ProbeAddress removed from the configurable surface — the probe uses
// ReadStatusAsync (CPU status), not a tag-address read. Config documents that previously
// set probeAddress are safely ignored (unknown JSON fields are tolerated by the deserialiser).
}
}