Files
lmxopcua/src/ZB.MOM.WW.OtOpcUa.Driver.S7/S7DriverFactoryExtensions.cs
2026-04-26 10:51:07 -04:00

459 lines
22 KiB
C#

using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
using ZB.MOM.WW.OtOpcUa.Driver.S7.SymbolImport;
using S7NetCpuType = global::S7.Net.CpuType;
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";
public static void Register(DriverFactoryRegistry registry)
{
ArgumentNullException.ThrowIfNull(registry);
registry.Register(DriverTypeName, CreateInstance);
}
internal static S7Driver CreateInstance(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");
// PR-S7-C3 — translate ScanGroupIntervalsMs (string -> int ms) into the runtime
// string -> TimeSpan map. Skip any entry with a non-positive value rather than
// throwing, so a config typo (e.g. 0 ms) degrades to "fall back to default
// publishing interval" instead of breaking the whole driver init.
IReadOnlyDictionary<string, TimeSpan>? scanGroupMap = null;
if (dto.ScanGroupIntervalsMs is { Count: > 0 })
{
var built = new Dictionary<string, TimeSpan>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in dto.ScanGroupIntervalsMs)
{
if (string.IsNullOrWhiteSpace(kvp.Key) || kvp.Value <= 0) continue;
built[kvp.Key] = TimeSpan.FromMilliseconds(kvp.Value);
}
if (built.Count > 0) scanGroupMap = built;
}
var options = new S7DriverOptions
{
Host = dto.Host!,
Port = dto.Port ?? 102,
CpuType = ParseEnum<S7NetCpuType>(dto.CpuType, driverInstanceId, "CpuType",
fallback: S7NetCpuType.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),
// PR-S7-C5 — explicit empty-string in JSON skips the probe entirely
// (sites without a fingerprint address); a missing field falls back to
// the MW0 convention so existing configs keep working unchanged.
ProbeAddress = dto.Probe is null
? "MW0"
: (dto.Probe.ProbeAddress is null
? "MW0"
: (string.IsNullOrWhiteSpace(dto.Probe.ProbeAddress) ? null : dto.Probe.ProbeAddress)),
SkipPreflight = dto.Probe?.SkipPreflight ?? false,
},
TsapMode = ParseEnum<TsapMode>(dto.TsapMode, driverInstanceId, "TsapMode",
fallback: TsapMode.Auto),
LocalTsap = dto.LocalTsap,
RemoteTsap = dto.RemoteTsap,
// PR-S7-E2 / #303 — connection-level password + declarative protection-level
// hint. Password defaults to null (no auth) per the no-log invariant; an
// explicit empty-string in JSON also collapses to null so a "Password": ""
// typo doesn't try to send a 0-byte password to the PLC. ProtectionLevel
// defaults to Auto when the field is absent.
Password = string.IsNullOrEmpty(dto.Password) ? null : dto.Password,
ProtectionLevel = ParseEnum<ProtectionLevel>(dto.ProtectionLevel, driverInstanceId,
"ProtectionLevel", fallback: ProtectionLevel.Auto),
ScanGroupIntervals = scanGroupMap,
// PR-S7-D2 — UDT layout declarations referenced by tags whose UdtName is set.
// Empty list when the config doesn't declare any UDTs (the typical scalar-only case).
Udts = dto.Udts is { Count: > 0 }
? [.. dto.Udts.Select(u => BuildUdt(u, driverInstanceId))]
: [],
};
return new S7Driver(options, driverInstanceId);
}
private static S7TagDefinition BuildTag(S7TagDto t, string driverInstanceId) =>
new(
Name: t.Name ?? throw new InvalidOperationException(
$"S7 config for '{driverInstanceId}' has a tag missing Name"),
// PR-S7-D2 — UDT-typed tags use the UDT name as their type rather than a primitive
// S7 data type; Address is still required (the parent base address that the
// fan-out adds member offsets to). Address may legitimately be DBn.DBX0.0 for an
// entire-DB UDT pointer; the parser accepts that and the fan-out walks from there.
Address: t.Address ?? throw new InvalidOperationException(
$"S7 tag '{t.Name}' in '{driverInstanceId}' missing Address"),
DataType: string.IsNullOrWhiteSpace(t.UdtName)
? ParseEnum<S7DataType>(t.DataType, driverInstanceId, "DataType", tagName: t.Name)
: ParseEnum<S7DataType>(t.DataType, driverInstanceId, "DataType", tagName: t.Name,
fallback: S7DataType.Byte),
Writable: t.Writable ?? true,
StringLength: t.StringLength ?? 254,
WriteIdempotent: t.WriteIdempotent ?? false,
ScanGroup: string.IsNullOrWhiteSpace(t.ScanGroup) ? null : t.ScanGroup,
DeadbandAbsolute: t.DeadbandAbsolute,
DeadbandPercent: t.DeadbandPercent,
UdtName: string.IsNullOrWhiteSpace(t.UdtName) ? null : t.UdtName);
private static S7UdtDefinition BuildUdt(S7UdtDto u, string driverInstanceId)
{
if (string.IsNullOrWhiteSpace(u.Name))
throw new InvalidOperationException(
$"S7 config for '{driverInstanceId}' has a UDT entry missing Name");
var members = (u.Members ?? new List<S7UdtMemberDto>()).Select(m => BuildUdtMember(m, u.Name!, driverInstanceId)).ToList();
return new S7UdtDefinition(u.Name!, members, u.SizeBytes ?? 0);
}
private static S7UdtMember BuildUdtMember(S7UdtMemberDto m, string udtName, string driverInstanceId)
{
if (string.IsNullOrWhiteSpace(m.Name))
throw new InvalidOperationException(
$"S7 UDT '{udtName}' in '{driverInstanceId}' has a member missing Name");
var dataType = string.IsNullOrWhiteSpace(m.UdtName)
? ParseEnum<S7DataType>(m.DataType, driverInstanceId, $"UDT '{udtName}' member '{m.Name}' DataType")
: ParseEnum<S7DataType>(m.DataType, driverInstanceId, $"UDT '{udtName}' member '{m.Name}' DataType",
fallback: S7DataType.Byte);
return new S7UdtMember(
Name: m.Name!,
Offset: m.Offset ?? 0,
DataType: dataType,
ArrayDim: m.ArrayDim,
UdtName: string.IsNullOrWhiteSpace(m.UdtName) ? null : m.UdtName);
}
/// <summary>
/// PR-S7-D1 / #299 — append TIA Portal "Show all tags" CSV rows to
/// <paramref name="options"/> as <see cref="S7TagDefinition"/> entries. Returns a new
/// <see cref="S7DriverOptions"/> with the imported tags concatenated onto the existing
/// <c>Tags</c> list — useful both at startup-time (server-side bootstrap that wants
/// to seed a device's address space from a customer-supplied CSV) and from the CLI
/// (<c>import-symbols</c> emits the resulting JSON fragment for hand-merging into an
/// appsettings file).
/// </summary>
/// <remarks>
/// <para>
/// The importer is permissive by default — malformed rows are logged and skipped;
/// the resulting <see cref="S7ImportResult"/> counts surface on
/// <paramref name="result"/> for callers that want to assert "we got the row count
/// we expected".
/// </para>
/// <para>
/// UDT-typed rows materialise as placeholder tags (data type forced to
/// <see cref="S7DataType.Byte"/>); PR-S7-D2 will replace the placeholders with
/// proper UDT layout. See <c>docs/drivers/S7-TIA-Import.md</c>.
/// </para>
/// </remarks>
public static S7DriverOptions AddTiaCsvImport(
this S7DriverOptions options,
string path,
out S7ImportResult result,
S7ImportOptions? importOptions = null,
ILogger<TiaCsvImporter>? logger = null)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentException.ThrowIfNullOrWhiteSpace(path);
using var stream = File.OpenRead(path);
var importer = new TiaCsvImporter(logger ?? NullLogger<TiaCsvImporter>.Instance);
result = importer.Parse(stream, importOptions);
return MergeImportedTags(options, result.Tags);
}
/// <summary>
/// CLI-friendly overload that returns the <see cref="S7ImportResult"/> alongside the
/// modified options as a tuple. Mirrors <see cref="AddTiaCsvImport"/> but avoids the
/// <c>out</c> parameter for call sites that prefer pattern-matched destructuring.
/// </summary>
public static (S7DriverOptions Options, S7ImportResult Result) AddTiaCsvImportWithResult(
this S7DriverOptions options,
string path,
S7ImportOptions? importOptions = null,
ILogger<TiaCsvImporter>? logger = null)
{
var updated = options.AddTiaCsvImport(path, out var result, importOptions, logger);
return (updated, result);
}
/// <summary>
/// PR-S7-D1 / #299 — append STEP 7 Classic AWL <c>VAR_GLOBAL</c> + <c>DATA_BLOCK</c>
/// declarations to <paramref name="options"/> as <see cref="S7TagDefinition"/> entries.
/// Best-effort heuristic — see <see cref="AwlImporter"/> for the position-based
/// addressing rules.
/// </summary>
public static S7DriverOptions AddAwlImport(
this S7DriverOptions options,
string path,
out S7ImportResult result,
S7ImportOptions? importOptions = null,
ILogger<AwlImporter>? logger = null)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentException.ThrowIfNullOrWhiteSpace(path);
using var stream = File.OpenRead(path);
var importer = new AwlImporter(logger ?? NullLogger<AwlImporter>.Instance);
result = importer.Parse(stream, importOptions);
return MergeImportedTags(options, result.Tags);
}
/// <summary>
/// CLI-friendly overload that returns the <see cref="S7ImportResult"/> alongside the
/// modified options as a tuple. Mirrors <see cref="AddAwlImport"/>.
/// </summary>
public static (S7DriverOptions Options, S7ImportResult Result) AddAwlImportWithResult(
this S7DriverOptions options,
string path,
S7ImportOptions? importOptions = null,
ILogger<AwlImporter>? logger = null)
{
var updated = options.AddAwlImport(path, out var result, importOptions, logger);
return (updated, result);
}
/// <summary>
/// Concatenate <paramref name="imported"/> onto <paramref name="options"/>.<see cref="S7DriverOptions.Tags"/>
/// and return a new options object with every other field untouched. The importers
/// are additive so hand-edited Tags rows (e.g., system-status fields not surfaced by
/// the TIA / AWL export) keep sitting alongside the bulk-imported symbol rows.
/// </summary>
private static S7DriverOptions MergeImportedTags(
S7DriverOptions options, IReadOnlyList<S7TagDefinition> imported)
{
var merged = new List<S7TagDefinition>(options.Tags.Count + imported.Count);
merged.AddRange(options.Tags);
merged.AddRange(imported);
return new S7DriverOptions
{
Host = options.Host,
Port = options.Port,
CpuType = options.CpuType,
Rack = options.Rack,
Slot = options.Slot,
Timeout = options.Timeout,
Tags = merged,
Probe = options.Probe,
BlockCoalescingGapBytes = options.BlockCoalescingGapBytes,
TsapMode = options.TsapMode,
LocalTsap = options.LocalTsap,
RemoteTsap = options.RemoteTsap,
ScanGroupIntervals = options.ScanGroupIntervals,
Udts = options.Udts,
Password = options.Password,
ProtectionLevel = options.ProtectionLevel,
};
}
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,
};
internal sealed class S7DriverConfigDto
{
public string? Host { get; init; }
public int? Port { get; init; }
public string? CpuType { get; init; }
public short? Rack { get; init; }
public short? Slot { get; init; }
public int? TimeoutMs { get; init; }
public List<S7TagDto>? Tags { get; init; }
public S7ProbeDto? Probe { get; init; }
/// <summary>
/// Optional connection-class selector — one of <c>Auto</c> (default),
/// <c>Pg</c>, <c>Op</c>, <c>S7Basic</c>, <c>Other</c>. When omitted the driver
/// keeps the existing <c>Auto</c> behaviour (S7netplus picks the TSAP pair
/// from <see cref="CpuType"/>). See <c>docs/v2/s7.md</c> "TSAP / Connection
/// Type" section.
/// </summary>
public string? TsapMode { get; init; }
/// <summary>Optional 16-bit local TSAP override. Required (with <see cref="RemoteTsap"/>) when <c>TsapMode = Other</c>.</summary>
public ushort? LocalTsap { get; init; }
/// <summary>Optional 16-bit remote TSAP override. Required (with <see cref="LocalTsap"/>) when <c>TsapMode = Other</c>.</summary>
public ushort? RemoteTsap { get; init; }
/// <summary>
/// PR-S7-C3 — optional scan-group → publishing-interval (ms) map. Tags carrying
/// a matching <see cref="S7TagDto.ScanGroup"/> string poll at the configured
/// rate; tags with no group, or with a group not present here, fall back to
/// the subscription default. Group names are matched case-insensitively. See
/// <c>docs/v2/s7.md</c> "Per-tag scan groups" section.
/// </summary>
public Dictionary<string, int>? ScanGroupIntervalsMs { get; init; }
/// <summary>
/// PR-S7-D2 — UDT / STRUCT layout declarations. Tags whose
/// <see cref="S7TagDto.UdtName"/> matches a UDT here get fanned out into
/// scalar leaf member tags at <c>S7Driver.InitializeAsync</c> time.
/// See <c>docs/v2/s7.md</c> "UDT / STRUCT support" section.
/// </summary>
public List<S7UdtDto>? Udts { get; init; }
/// <summary>
/// PR-S7-E2 / #303 — connection-level password emitted to the PLC right
/// after <c>OpenAsync</c> succeeds and before the pre-flight PUT/GET probe
/// runs. Default <c>null</c> = no password is sent (the standard case).
/// <b>Secret:</b> never logged. See <c>docs/v2/s7.md</c> §"PLC password /
/// protection levels" for the no-log invariant and the S7netplus 0.20
/// library-limitation note.
/// </summary>
public string? Password { get; init; }
/// <summary>
/// PR-S7-E2 / #303 — declarative hint about the protection scheme on the
/// target PLC. One of <c>Auto</c> (default), <c>None</c>, <c>Level1</c>,
/// <c>Level2</c>, <c>Level3</c> (S7-300/400), or <c>ConnectionMechanism</c>
/// (S7-1200/1500). Surfaced via the driver-diagnostics RPC so a
/// misconfigured "level 3 PLC seen as level 1" deployment is spottable
/// from the Admin UI.
/// </summary>
public string? ProtectionLevel { get; init; }
}
internal sealed class S7TagDto
{
public string? Name { get; init; }
public string? Address { get; init; }
public string? DataType { get; init; }
public bool? Writable { get; init; }
public int? StringLength { get; init; }
public bool? WriteIdempotent { get; init; }
/// <summary>
/// PR-S7-C3 — optional scan-group identifier. Resolved against
/// <see cref="S7DriverConfigDto.ScanGroupIntervalsMs"/> at subscribe time.
/// Null / empty = no group (legacy behaviour, falls back to subscription
/// default publishing interval).
/// </summary>
public string? ScanGroup { get; init; }
/// <summary>
/// PR-S7-C4 — optional absolute deadband threshold. Numeric tags whose
/// <c>|new - prev|</c> is strictly less than this value are suppressed at
/// the driver layer before <c>OnDataChange</c> fires. Ignored for non-numeric
/// types. NaN / ±Infinity samples bypass the filter and always publish.
/// </summary>
public double? DeadbandAbsolute { get; init; }
/// <summary>
/// PR-S7-C4 — optional percent deadband (0..100). Numeric tags whose
/// <c>|new - prev|</c> is strictly less than <c>|prev| * pct / 100</c> are
/// suppressed. Falls back to <see cref="DeadbandAbsolute"/> when
/// <c>|prev| &lt; 1e-6</c> (near-zero baseline rule). When both deadbands are
/// set the filters are OR'd — publish if EITHER threshold triggers.
/// </summary>
public double? DeadbandPercent { get; init; }
/// <summary>
/// PR-S7-D2 — when set, the tag is a UDT / STRUCT-typed pointer. The driver
/// looks up the named UDT in <see cref="S7DriverConfigDto.Udts"/> and fans the
/// tag out into scalar leaf tags at <c>InitializeAsync</c> time. The primitive
/// <see cref="DataType"/> field is ignored when <c>UdtName</c> is set; the
/// leaves take their data types from the UDT member declarations.
/// </summary>
public string? UdtName { get; init; }
}
/// <summary>
/// PR-S7-D2 — JSON wire form for <see cref="S7UdtDefinition"/>. See
/// <c>docs/v2/s7.md</c> "UDT / STRUCT support" for the round-trip example.
/// </summary>
internal sealed class S7UdtDto
{
public string? Name { get; init; }
public List<S7UdtMemberDto>? Members { get; init; }
public int? SizeBytes { get; init; }
}
/// <summary>
/// PR-S7-D2 — JSON wire form for <see cref="S7UdtMember"/>. <c>UdtName</c> is set
/// for nested-UDT members; <c>DataType</c> is set for primitive members.
/// </summary>
internal sealed class S7UdtMemberDto
{
public string? Name { get; init; }
public int? Offset { get; init; }
public string? DataType { get; init; }
public int? ArrayDim { get; init; }
public string? UdtName { get; init; }
}
internal sealed class S7ProbeDto
{
public bool? Enabled { get; init; }
public int? IntervalMs { get; init; }
public int? TimeoutMs { get; init; }
/// <summary>
/// Address probed by the background liveness loop and (PR-S7-C5) by the
/// post-<c>OpenAsync</c> pre-flight check. Default <c>MW0</c> when the
/// <c>Probe</c> object is omitted entirely; explicit <c>null</c> /
/// whitespace skips both the background probe and the pre-flight read.
/// </summary>
public string? ProbeAddress { get; init; }
/// <summary>
/// PR-S7-C5 — opt out of the pre-flight PUT/GET enablement read at
/// <see cref="S7Driver.InitializeAsync"/> time. Default <c>false</c> =
/// pre-flight runs and a hardened CPU with PUT/GET disabled fails Init
/// with <see cref="S7PutGetDisabledException"/>. See
/// <c>docs/v2/s7.md</c> "Pre-flight PUT/GET enablement" section.
/// </summary>
public bool? SkipPreflight { get; init; }
}
}