using System.Text.Json;
using System.Text.Json.Serialization;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
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),
ProbeAddress = dto.Probe?.ProbeAddress ?? "MW0",
},
TsapMode = ParseEnum(dto.TsapMode, driverInstanceId, "TsapMode",
fallback: TsapMode.Auto),
LocalTsap = dto.LocalTsap,
RemoteTsap = dto.RemoteTsap,
ScanGroupIntervals = scanGroupMap,
};
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"),
Address: t.Address ?? throw new InvalidOperationException(
$"S7 tag '{t.Name}' in '{driverInstanceId}' missing Address"),
DataType: ParseEnum(t.DataType, driverInstanceId, "DataType",
tagName: t.Name),
Writable: t.Writable ?? true,
StringLength: t.StringLength ?? 254,
WriteIdempotent: t.WriteIdempotent ?? false,
ScanGroup: string.IsNullOrWhiteSpace(t.ScanGroup) ? null : t.ScanGroup);
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; }
}
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; }
}
internal sealed class S7ProbeDto
{
public bool? Enabled { get; init; }
public int? IntervalMs { get; init; }
public int? TimeoutMs { get; init; }
public string? ProbeAddress { get; init; }
}
}