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; /// /// Static factory registration helper for . Server's Program.cs /// calls once at startup; the bootstrapper (task #248) then /// materialises S7 DriverInstance rows from the central config DB into live driver /// instances. Mirrors GalaxyProxyDriverFactoryExtensions. /// 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(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? scanGroupMap = null; if (dto.ScanGroupIntervalsMs is { Count: > 0 }) { var built = new Dictionary(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(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(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(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(t.DataType, driverInstanceId, "DataType", tagName: t.Name) : ParseEnum(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()).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(m.DataType, driverInstanceId, $"UDT '{udtName}' member '{m.Name}' DataType") : ParseEnum(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); } /// /// PR-S7-D1 / #299 — append TIA Portal "Show all tags" CSV rows to /// as entries. Returns a new /// with the imported tags concatenated onto the existing /// Tags 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 /// (import-symbols emits the resulting JSON fragment for hand-merging into an /// appsettings file). /// /// /// /// The importer is permissive by default — malformed rows are logged and skipped; /// the resulting counts surface on /// for callers that want to assert "we got the row count /// we expected". /// /// /// UDT-typed rows materialise as placeholder tags (data type forced to /// ); PR-S7-D2 will replace the placeholders with /// proper UDT layout. See docs/drivers/S7-TIA-Import.md. /// /// public static S7DriverOptions AddTiaCsvImport( this S7DriverOptions options, string path, out S7ImportResult result, S7ImportOptions? importOptions = null, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(options); ArgumentException.ThrowIfNullOrWhiteSpace(path); using var stream = File.OpenRead(path); var importer = new TiaCsvImporter(logger ?? NullLogger.Instance); result = importer.Parse(stream, importOptions); return MergeImportedTags(options, result.Tags); } /// /// CLI-friendly overload that returns the alongside the /// modified options as a tuple. Mirrors but avoids the /// out parameter for call sites that prefer pattern-matched destructuring. /// public static (S7DriverOptions Options, S7ImportResult Result) AddTiaCsvImportWithResult( this S7DriverOptions options, string path, S7ImportOptions? importOptions = null, ILogger? logger = null) { var updated = options.AddTiaCsvImport(path, out var result, importOptions, logger); return (updated, result); } /// /// PR-S7-D1 / #299 — append STEP 7 Classic AWL VAR_GLOBAL + DATA_BLOCK /// declarations to as entries. /// Best-effort heuristic — see for the position-based /// addressing rules. /// public static S7DriverOptions AddAwlImport( this S7DriverOptions options, string path, out S7ImportResult result, S7ImportOptions? importOptions = null, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(options); ArgumentException.ThrowIfNullOrWhiteSpace(path); using var stream = File.OpenRead(path); var importer = new AwlImporter(logger ?? NullLogger.Instance); result = importer.Parse(stream, importOptions); return MergeImportedTags(options, result.Tags); } /// /// CLI-friendly overload that returns the alongside the /// modified options as a tuple. Mirrors . /// public static (S7DriverOptions Options, S7ImportResult Result) AddAwlImportWithResult( this S7DriverOptions options, string path, S7ImportOptions? importOptions = null, ILogger? logger = null) { var updated = options.AddAwlImport(path, out var result, importOptions, logger); return (updated, result); } /// /// Concatenate onto . /// 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. /// private static S7DriverOptions MergeImportedTags( S7DriverOptions options, IReadOnlyList imported) { var merged = new List(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(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 ?? ""}' in '{driverInstanceId}' missing {field}"); } return Enum.TryParse(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())}"); } 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? Tags { get; init; } public S7ProbeDto? Probe { get; init; } /// /// Optional connection-class selector — one of Auto (default), /// Pg, Op, S7Basic, Other. When omitted the driver /// keeps the existing Auto behaviour (S7netplus picks the TSAP pair /// from ). See docs/v2/s7.md "TSAP / Connection /// Type" section. /// public string? TsapMode { get; init; } /// Optional 16-bit local TSAP override. Required (with ) when TsapMode = Other. public ushort? LocalTsap { get; init; } /// Optional 16-bit remote TSAP override. Required (with ) when TsapMode = Other. public ushort? RemoteTsap { get; init; } /// /// PR-S7-C3 — optional scan-group → publishing-interval (ms) map. Tags carrying /// a matching 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 /// docs/v2/s7.md "Per-tag scan groups" section. /// public Dictionary? ScanGroupIntervalsMs { get; init; } /// /// PR-S7-D2 — UDT / STRUCT layout declarations. Tags whose /// matches a UDT here get fanned out into /// scalar leaf member tags at S7Driver.InitializeAsync time. /// See docs/v2/s7.md "UDT / STRUCT support" section. /// public List? Udts { get; init; } /// /// PR-S7-E2 / #303 — connection-level password emitted to the PLC right /// after OpenAsync succeeds and before the pre-flight PUT/GET probe /// runs. Default null = no password is sent (the standard case). /// Secret: never logged. See docs/v2/s7.md §"PLC password / /// protection levels" for the no-log invariant and the S7netplus 0.20 /// library-limitation note. /// public string? Password { get; init; } /// /// PR-S7-E2 / #303 — declarative hint about the protection scheme on the /// target PLC. One of Auto (default), None, Level1, /// Level2, Level3 (S7-300/400), or ConnectionMechanism /// (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. /// 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; } /// /// PR-S7-C3 — optional scan-group identifier. Resolved against /// at subscribe time. /// Null / empty = no group (legacy behaviour, falls back to subscription /// default publishing interval). /// public string? ScanGroup { get; init; } /// /// PR-S7-C4 — optional absolute deadband threshold. Numeric tags whose /// |new - prev| is strictly less than this value are suppressed at /// the driver layer before OnDataChange fires. Ignored for non-numeric /// types. NaN / ±Infinity samples bypass the filter and always publish. /// public double? DeadbandAbsolute { get; init; } /// /// PR-S7-C4 — optional percent deadband (0..100). Numeric tags whose /// |new - prev| is strictly less than |prev| * pct / 100 are /// suppressed. Falls back to when /// |prev| < 1e-6 (near-zero baseline rule). When both deadbands are /// set the filters are OR'd — publish if EITHER threshold triggers. /// public double? DeadbandPercent { get; init; } /// /// PR-S7-D2 — when set, the tag is a UDT / STRUCT-typed pointer. The driver /// looks up the named UDT in and fans the /// tag out into scalar leaf tags at InitializeAsync time. The primitive /// field is ignored when UdtName is set; the /// leaves take their data types from the UDT member declarations. /// public string? UdtName { get; init; } } /// /// PR-S7-D2 — JSON wire form for . See /// docs/v2/s7.md "UDT / STRUCT support" for the round-trip example. /// internal sealed class S7UdtDto { public string? Name { get; init; } public List? Members { get; init; } public int? SizeBytes { get; init; } } /// /// PR-S7-D2 — JSON wire form for . UdtName is set /// for nested-UDT members; DataType is set for primitive members. /// 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; } /// /// Address probed by the background liveness loop and (PR-S7-C5) by the /// post-OpenAsync pre-flight check. Default MW0 when the /// Probe object is omitted entirely; explicit null / /// whitespace skips both the background probe and the pre-flight read. /// public string? ProbeAddress { get; init; } /// /// PR-S7-C5 — opt out of the pre-flight PUT/GET enablement read at /// time. Default false = /// pre-flight runs and a hardened CPU with PUT/GET disabled fails Init /// with . See /// docs/v2/s7.md "Pre-flight PUT/GET enablement" section. /// public bool? SkipPreflight { get; init; } } }