using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.OtOpcUa.Commons.Observability; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Driver.AbCip.PlcFamilies; namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip; /// /// Allen-Bradley CIP / EtherNet-IP driver for ControlLogix / CompactLogix / Micro800 / /// GuardLogix families. Implements all read/write/subscribe/discover/probe/alarm /// capabilities via the libplctag.NET wrapper. /// /// /// Wire layer is libplctag 1.6.x. Per-device host addresses use /// the ab://gateway[:port]/cip-path canonical form parsed via /// ; those strings become the hostName key /// for Polly per-host circuit-breaker isolation. /// /// Tier A — in-process, shares server lifetime, no /// sidecar. is the Tier-B escape hatch for recovering /// from native-heap growth that the CLR allocator can't see; it tears down the /// libplctag.NET Tag instances held in DeviceState.Runtimes and reconnects /// each device. Native tag lifetime is owned by the libplctag.NET Tag.Dispose() /// (called in ); the library's own finalizer /// handles GC-collected tags. /// public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, IAlarmSource, ISkippedTagReporter, IAsyncDisposable, IDisposable { /// Authored tags this driver could not build into its poll table. private readonly SkippedTagLedger _skippedTags = new(); /// public SkippedTagReport? GetSkippedTags() => _skippedTags.Snapshot(); private AbCipDriverOptions _options; private readonly string _driverInstanceId; private readonly IAbCipTagFactory _tagFactory; private readonly IAbCipTagEnumeratorFactory _enumeratorFactory; private readonly IAbCipTemplateReaderFactory _templateReaderFactory; /// /// The batch template reader of the discovery run in progress on this async flow, if any. While set, /// reads through it so a browse that fetches many templates holds ONE /// device lease across them instead of opening a connection per template. /// private readonly AsyncLocal _batchTemplateReader = new(); private readonly AbCipTemplateCache _templateCache = new(); /// /// Maximum nesting depth the controller-discovered UDT fan-out recurses through. A member /// whose path would sit deeper than this (a struct-of-struct chain longer than the cap) is /// dropped rather than emitted, bounding both browse-tree breadth and the recursion. Depth /// is counted in dotted segments below the discovered parent (the parent's direct atomic /// members sit at depth 1). /// public const int MaxUdtDepth = 8; // Name-keyed UDT shapes consulted by the controller-discovered fan-out, keyed on // (deviceHostAddress, structTypeOrMemberName). PRODUCTION REALITY of the two population paths: // * TOP-LEVEL discovered UDT — FUNCTIONAL in production. The Symbol Object decoder surfaces the // discovered tag's CIP template instance id (AbCipDiscoveredTag.TemplateInstanceId), which // DiscoverAsync threads into ResolveDiscoveredUdtShapeAsync -> FetchUdtShapeAsync to read the // Template Object off the controller and cache it in the id-keyed _templateCache. No seed // needed. // * NESTED struct members — FUNCTIONAL in production. A decoded Template Object member block carries // the nested UDT's template instance id (low 12 bits of the member info, captured by // CipTemplateObjectDecoder onto AbCipUdtMember.NestedTemplateId), which the fan-out threads into // ResolveDiscoveredUdtShapeAsync -> FetchUdtShapeAsync to read the nested Template Object off the // controller. The name-keyed seed (SeedDiscoveredUdtShapeForTest) still wins first for tests; a // nested member whose id can't be resolved is dropped (the top-level UDT still expands). private readonly Dictionary _discoveredUdtShapes = new(StringComparer.OrdinalIgnoreCase); // Composite key for _discoveredUdtShapes: device + struct/member name joined by a NUL ('\0'). // A NUL appears in neither a canonical ab:// host address nor a Logix symbol name, so the // separator is unambiguous regardless of what either part contains. private static string UdtShapeKey(string deviceHostAddress, string structName) => $"{deviceHostAddress}\0{structName}"; /// /// Test seam — seed a discovered-UDT shape under for /// , consulted by name before any id-keyed fetch. Lets a /// fan-out test link a nested sub-shape by member name without a live Template Object read. /// Neither the TOP-LEVEL discovered UDT nor a NESTED-struct member needs a seed in production: /// both carry a template instance id (the top level on /// , a nested member on /// ) that the fan-out fetches via /// . /// /// The device the struct lives on. /// The discovered struct type or nested-member name. /// The shape to associate with that name. internal void SeedDiscoveredUdtShapeForTest(string deviceHostAddress, string structName, AbCipUdtShape shape) => _discoveredUdtShapes[UdtShapeKey(deviceHostAddress, structName)] = shape; private readonly PollGroupEngine _poll; // Devices keyed by host address — the primary registry (GetDeviceState, discovery, probe, diagnostics). // BUILD-AND-SWAP, never mutated after publish: the retained poll engine, the alarm projection, discovery and // the actor's GetHostStatuses pull all read it while a re-init / shutdown runs. Each teardown takes the table // it replaces, so concurrent teardowns (ShutdownAsync racing DisposeAsync) own disjoint device states. private volatile Dictionary _devices = new(StringComparer.OrdinalIgnoreCase); // Tag-routing index: a tag's device routing key (DeviceName ?? HostAddress, plus the HostAddress alias) // → its DeviceState. A tag resolves to its device by DeviceName-or-host so multi-device routing keys on // the RawPath's device segment. The HostAddress alias is deliberate (Client CLI + tests route by host); // _options.Devices is already the merged per-device DeviceConfig. Swapped with _devices, same rule. private volatile Dictionary _devicesByRoutingKey = new(StringComparer.OrdinalIgnoreCase); // Serialises table publish/retire. _lifecycleGeneration is bumped by every retire (an init's own release, a // shutdown, a dispose); an init publishes only if no retire happened after its own, so an abandoned init that a // shutdown overtook can never resurrect devices or probe loops after that shutdown returned. private readonly object _lifecycleLock = new(); private int _lifecycleGeneration; // v3 authored RawPath → definition table (parents + fanned-out UDT members), keyed case-sensitive // ordinal. Built in InitializeAsync from _options.RawTags via the pure mapper. private volatile Dictionary _tagsByRawPath = new(StringComparer.Ordinal); // Top-level authored definitions (parents + flat tags, NOT synthesised members), in author order — // the source DiscoverAsync groups by device. Members are synthesised inside the discovery/read paths. private volatile List _declaredTags = new(); // Resolves a read/write/subscribe fullReference (always a RawPath in v3) to a tag definition by a // single hit on the authored _tagsByRawPath table; a miss is a miss (the pre-v3 blob-parse fallback // is retired — see EquipmentTagRefResolver). private readonly EquipmentTagRefResolver _resolver; private readonly ILogger _logger; private AbCipAlarmProjection _alarmProjection; /// The ALMD projection's last-told InAlarm per alarm ref; outlives every /// projection and subscription (see ). internal AbCipAlarmFaultRecord AlarmFaultRecord { get; } = new(); /// The ALMA projection's last-told (active-limit mask, acked) per alarm ref; driver-owned for the /// same reason as . internal AbCipAlarmAnalogRecord AlarmAnalogRecord { get; } = new(); /// Resolves an authored tag definition by RawPath (the alarm projection's ALMA/ALMD discriminator). /// The tag RawPath. /// The authored definition when found. /// when a definition exists for . internal bool TryGetTagDefinition(string rawPath, out AbCipTagDefinition definition) => _tagsByRawPath.TryGetValue(rawPath, out definition!); // volatile: written from the read batch, the write path, the poll engine's error hook and the lifecycle, and // read from the actor thread (GetHealth). Read-modify-write updates go through UpdateHealth (CAS) so a // concurrent update is never lost. private volatile DriverHealth _health = new(DriverState.Unknown, null, null); /// Atomically replaces with applied to its current value. /// Computes the new health from the current one. private void UpdateHealth(Func update) { while (true) { var current = _health; var next = update(current); #pragma warning disable CS0420 // a volatile field passed by ref to Interlocked keeps its full-fence semantics if (ReferenceEquals(Interlocked.CompareExchange(ref _health, next, current), current)) return; #pragma warning restore CS0420 } } /// Occurs when a subscribed tag's value changes. public event EventHandler? OnDataChange; /// /// Occurs once per poll cycle that produced at least one change, carrying that cycle's /// changed tags. Both data-change events fire by design — this one once per cycle, /// once per changed tag — so a consumer subscribes to EXACTLY /// ONE of the two; subscribing both double-delivers. /// public event EventHandler? OnDataChangeBatch; /// Occurs when a device's host connectivity status changes. public event EventHandler? OnHostStatusChanged; /// Occurs when an alarm event is raised. public event EventHandler? OnAlarmEvent; /// Internal seam for the alarm projection to raise events through the driver. /// The alarm event arguments. internal void InvokeAlarmEvent(AlarmEventArgs args) => OnAlarmEvent?.Invoke(this, args); /// Initializes a new instance of the class. /// The driver configuration options. /// A unique identifier for this driver instance. /// Optional factory for creating tag runtimes; when null the resolved transport's (see ) is used. /// Optional factory for enumerating tags; when null the resolved transport's is used. /// Optional factory for reading UDT templates; when null the resolved transport's is used. /// Optional logger; uses null logger if not provided. /// The node-level default for an absent transport key /// (Drivers:AbCip:DefaultTransport); null means the compiled . public AbCipDriver(AbCipDriverOptions options, string driverInstanceId, IAbCipTagFactory? tagFactory = null, IAbCipTagEnumeratorFactory? enumeratorFactory = null, IAbCipTemplateReaderFactory? templateReaderFactory = null, ILogger? logger = null, AbCipTransport? defaultTransport = null) { ArgumentNullException.ThrowIfNull(options); _options = options; _driverInstanceId = driverInstanceId; // Chosen once here and held across ReinitializeAsync (Shutdown+Initialize): a changed // Transport in a reinit config is inert; a deploy recreates the instance instead. var nodeDefault = defaultTransport ?? AbCipTransportResolver.Default; _transport = AbCipTransportResolver.Resolve(options, nodeDefault); _transportDescription = AbCipTransportResolver.Describe(options.Transport, nodeDefault); var defaults = AbCipTransportFactories.For(_transport, options.BrowsePageDelay); _tagFactory = tagFactory ?? defaults.Tags; _enumeratorFactory = enumeratorFactory ?? defaults.Enumerators; _templateReaderFactory = templateReaderFactory ?? defaults.Templates; _logger = logger ?? NullLogger.Instance; _resolver = new EquipmentTagRefResolver( r => _tagsByRawPath.TryGetValue(r, out var t) ? t : null); _poll = new PollGroupEngine( reader: ReadAsync, onChange: (handle, tagRef, snapshot) => OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, tagRef, snapshot)), onError: HandlePollError, backoffCap: PollBackoffCap, onBatch: (handle, items) => OnDataChangeBatch?.Invoke(this, new DataChangeBatchEventArgs(handle, items)), // The engine owns no Meter (Core.Abstractions takes no metrics dependency), so this // closure IS the production consumer of its overrun signal. onOverrun: _ => OtOpcUaTelemetry.PollOverruns.Add(1, new KeyValuePair(OtOpcUaTelemetry.PollOverrunDriverTypeTag, DriverTypeNames.AbCip), new KeyValuePair(OtOpcUaTelemetry.PollOverrunDriverInstanceTag, driverInstanceId))); _alarmProjection = new AbCipAlarmProjection(this, _options.AlarmPollInterval, _logger); } /// The tag factory chosen at construction; exposed so tests can pin transport selection. internal IAbCipTagFactory TagFactory => _tagFactory; /// The effective transport resolved at construction (see ). /// Describes the OPTION only: injected factories (tests) are used regardless. public AbCipTransport EffectiveTransport => _transport; // The transport chosen at construction (see the ctor); logged at every init so an operator can tell // from the node log which stack serves this instance. private readonly AbCipTransport _transport; // Configured-vs-effective rendering of _transport for the init log, e.g. "Native (default)". private readonly string _transportDescription; // Tags whose type-mismatch Warning has already been logged (final review I4): a mis-authored tag is // polled forever, so the Warning is once per tag per driver instance, not once per poll. private readonly System.Collections.Concurrent.ConcurrentDictionary _typeMismatchWarned = new(StringComparer.OrdinalIgnoreCase); /// Logs a type-mismatch Warning the first time reports one on this instance. private void WarnTypeMismatchOnce(string tagName, string message, params object?[] args) { if (_typeMismatchWarned.TryAdd(tagName, 0)) _logger.LogWarning(message, args); } // Tags whose write-refusal Warning has already been logged — a client may retry forever. private readonly System.Collections.Concurrent.ConcurrentDictionary _writeRefusalWarned = new(StringComparer.OrdinalIgnoreCase); /// Logs a write-refusal Warning the first time reports one on this instance. private void WarnWriteRefusedOnce(string tagName, string message, params object?[] args) { if (_writeRefusalWarned.TryAdd(tagName, 0)) _logger.LogWarning(message, args); } // Tags whose device-refusal Warning has already been logged, per operation ("read"/"write"/…): a refused tag is // polled (or retried) forever, so the Warning is once per tag per operation per driver instance. private readonly System.Collections.Concurrent.ConcurrentDictionary _refusalWarned = new(StringComparer.OrdinalIgnoreCase); /// Logs a device-refusal Warning the first time is refused for . private void WarnRefusalOnce(string tagName, string operation, string reference, string device, string reason) { if (_refusalWarned.TryAdd($"{operation}\0{tagName}", 0)) _logger.LogWarning( "AbCip {Operation} of {Tag} on device {Device} refused by the controller: {Reason}; reporting it Bad " + "for this tag only — the device and its other tags are unaffected (logged once per tag)", operation, reference, device, reason); } // Tags whose malformed-name Warning has already been logged — polled forever, warned once. private readonly System.Collections.Concurrent.ConcurrentDictionary _configErrorWarned = new(StringComparer.OrdinalIgnoreCase); /// /// Logs the Warning for a tag whose own configuration cannot become a request /// (), the first time reports /// one on this instance. /// private void WarnConfigurationErrorOnce(string tagName, string reference, string device, AbCipTagConfigurationException ex) { if (_configErrorWarned.TryAdd(tagName, 0)) _logger.LogWarning( "AbCip tag {Tag} on device {Device} is misconfigured: {Reason}; reporting BadConfigurationError " + "until it is corrected — the device and its other tags are unaffected (logged once per tag)", reference, device, ex.Message); } /// Upper bound on the poll-loop failure backoff — adopts the S7-proven 30 s cap fleet-wide. private static readonly TimeSpan PollBackoffCap = TimeSpan.FromSeconds(30); /// /// Routes a poll-loop reader failure to the driver health surface: logs it and /// degrades to preserving LastSuccessfulRead. /// Never downgrades a state (a stronger, config-level signal). /// /// The exception caught by the poll engine. internal void HandlePollError(Exception ex) { _logger.LogWarning(ex, "AbCip poll reader failed. Driver={DriverInstanceId}", _driverInstanceId); UpdateHealth(current => current.State == DriverState.Faulted ? current : new DriverHealth(DriverState.Degraded, current.LastSuccessfulRead, ex.Message)); } /// /// Fetch + cache the shape of a Logix UDT by template instance id. First call reads /// the Template Object off the controller; subsequent calls for the same /// (deviceHostAddress, templateInstanceId) return the cached shape without /// additional network traffic. null on template-not-found / decode failure so /// callers can fall back to declaration-driven UDT fan-out. /// /// The host address of the device to read the template from. /// The instance ID of the UDT template to fetch. /// Cancellation token for the operation. /// The UDT shape if found and decoded successfully; null otherwise. internal async Task FetchUdtShapeAsync( string deviceHostAddress, uint templateInstanceId, CancellationToken cancellationToken) { var cached = _templateCache.TryGet(deviceHostAddress, templateInstanceId); if (cached is not null) return cached; if (!_devices.TryGetValue(deviceHostAddress, out var device)) return null; var deviceParams = device.BuildCreateParams($"@udt/{templateInstanceId}", _options.Timeout); try { var batch = _batchTemplateReader.Value; using var own = batch is null ? _templateReaderFactory.Create() : null; var reader = batch ?? own!; var buffer = await reader.ReadAsync(deviceParams, templateInstanceId, cancellationToken).ConfigureAwait(false); var shape = CipTemplateObjectDecoder.Decode(buffer); if (shape is not null) _templateCache.Put(deviceHostAddress, templateInstanceId, shape); return shape; } catch (OperationCanceledException) { throw; } catch (Exception ex) { // Template read failure — surface via the driver's health surface AND a warning // log so operators see it; don't propagate since callers should fall back to // declaration-driven UDT semantics rather than failing the whole discovery run. _logger.LogWarning(ex, "AbCip driver {DriverInstanceId} failed to read UDT template {TemplateInstanceId} from device {Device}; " + "falling back to declaration-driven UDT semantics", _driverInstanceId, templateInstanceId, deviceHostAddress); return null; } } /// /// Resolve the shape of a controller-discovered struct/UDT (or a nested-struct member) by /// name. Consults the name-keyed first (the source for /// nested-struct sub-shapes + the test seam), then — for the top level only — the id-keyed /// template cache via when a template instance id is /// available. Returns null when no shape can be resolved so the caller degrades to a /// single Variable rather than emitting a broken fan-out. /// /// The device the struct lives on. /// The discovered struct type name or a nested-member name. /// Template instance id when known — the top-level UDT's id, or a /// nested-struct member's decoded from the parent /// shape; null only when neither a seeded name-keyed shape nor an id can resolve the struct /// (the caller then degrades to a single Variable rather than a broken fan-out). /// Cancellation token for any live template read. private async Task ResolveDiscoveredUdtShapeAsync( string deviceHostAddress, string structName, uint? templateInstanceId, CancellationToken cancellationToken) { if (_discoveredUdtShapes.TryGetValue(UdtShapeKey(deviceHostAddress, structName), out var seeded)) return seeded; if (templateInstanceId is { } id) return await FetchUdtShapeAsync(deviceHostAddress, id, cancellationToken).ConfigureAwait(false); return null; } /// /// Shared UDT template cache populated by . Exposed /// internally so tests + diagnostics can inspect cached shapes. /// internal AbCipTemplateCache TemplateCache => _templateCache; /// public string DriverInstanceId => _driverInstanceId; /// public string DriverType => "AbCip"; /// public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) { // InitializeAsync is reachable on a live driver with no teardown first (the IDriver contract // allows it, and a reconnect retry can overlap a running attempt). Retire the previous device states' probe // loops + handles before building new ones. Deliberately NOT ShutdownAsync: that also drops _poll and the // subscriptions. The generation this release produced is what the publish below is checked against. var generation = await ReleaseDeviceStatesAsync().ConfigureAwait(false); lock (_lifecycleLock) { if (generation == _lifecycleGeneration) _health = new DriverHealth(DriverState.Initializing, null, null); } _logger.LogInformation( "AbCip driver {DriverInstanceId} initializing: transport={Transport} tagFactory={TagFactory}", _driverInstanceId, _transportDescription, _tagFactory.GetType().Name); Dictionary? builtDevices = null; try { var options = _options; var adoptedConfig = false; if (!string.IsNullOrWhiteSpace(driverConfigJson)) { var parsed = AbCipDriverFactoryExtensions.ParseOptions(_driverInstanceId, driverConfigJson); if (parsed.Devices.Count > 0 || parsed.RawTags.Count > 0) { options = parsed; adoptedConfig = true; } } builtDevices = new Dictionary(StringComparer.OrdinalIgnoreCase); var builtRoutes = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var device in options.Devices) { var addr = AbCipHostAddress.TryParse(device.HostAddress) ?? throw new InvalidOperationException( $"AbCip device has invalid HostAddress '{device.HostAddress}' — expected 'ab://gateway[:port]/cip-path'."); var profile = AbCipPlcFamilyProfile.ForFamily(device.PlcFamily); var state = new DeviceState(addr, device, profile); builtDevices[device.HostAddress] = state; // Route index: a tag reaches this device by matching its DeviceName routing key OR its // host address. Devices with no explicit DeviceName are identified purely by host today. builtRoutes[device.HostAddress] = state; if (!string.IsNullOrEmpty(device.DeviceName)) builtRoutes[device.DeviceName] = state; } // Build the RawPath → definition table from the authored raw tags. Each entry's TagConfig blob // is mapped by the pure factory; the entry's DeviceName (routing key) + WriteIdempotent flag are // threaded onto the def (they live on the RawTagEntry, not inside the blob). A mapper miss is // skipped (logged), never thrown — a bad tag must not fail the whole driver init. _skippedTags.BeginRebuild(options.RawTags.Count); var builtTagsByRawPath = new Dictionary(StringComparer.Ordinal); var builtDeclaredTags = new List(); foreach (var entry in options.RawTags) { if (!AbCipTagDefinitionFactory.FromTagConfig(entry.TagConfig, entry.RawPath, out var mapped)) { _skippedTags.Skip(entry.RawPath, "TagConfig did not map to a definition"); _logger.LogWarning( "AbCip tag config did not map to a definition; skipping. Driver={DriverInstanceId} RawPath={RawPath}", _driverInstanceId, entry.RawPath); continue; } var tag = mapped with { DeviceHostAddress = entry.DeviceName, WriteIdempotent = entry.WriteIdempotent }; // Duplicate-key check: a collision means two authored tags share the same RawPath. // Fail fast at init time with a diagnostic rather than silently clobbering. if (builtTagsByRawPath.TryGetValue(tag.Name, out var existingTag)) throw new InvalidOperationException( $"AbCip tag name collision: '{tag.Name}' is declared more than once. " + $"Existing entry DeviceHostAddress='{existingTag.DeviceHostAddress}', " + $"TagPath='{existingTag.TagPath}'. Rename or remove the duplicate."); builtTagsByRawPath[tag.Name] = tag; builtDeclaredTags.Add(tag); if (tag.DataType == AbCipDataType.Structure && tag.Members is { Count: > 0 }) { foreach (var member in tag.Members) { var memberTag = new AbCipTagDefinition( Name: $"{tag.Name}.{member.Name}", DeviceHostAddress: tag.DeviceHostAddress, TagPath: $"{tag.TagPath}.{member.Name}", DataType: member.DataType, Writable: member.Writable, WriteIdempotent: member.WriteIdempotent, // Carry the member's array shape into the fanned-out // runtime definition. Discovery already emits an array node for an array // member (member.IsArray || member.ElementCount > 1); without these the // runtime def defaulted to scalar and the read returned a single element // instead of the typed array, a declared-type-vs-runtime-value mismatch. ElementCount: member.ElementCount, IsArray: member.IsArray); // Member fan-out duplicate check: a member-path collision means two // configured structure tags produce the same member path, or a member // name collides with an independently-declared tag. if (builtTagsByRawPath.TryGetValue(memberTag.Name, out var existingMember)) throw new InvalidOperationException( $"AbCip tag name collision: '{memberTag.Name}' is produced by both " + $"'{tag.Name}.{member.Name}' (member fan-out) and an existing tag " + $"'{existingMember.Name}'. Rename one of the configured tags to resolve."); builtTagsByRawPath[memberTag.Name] = memberTag; } } } // Publish everything under the lifecycle lock, and only if no shutdown / other init retired the tables // after this init's own release — readers see the old tables or the new ones, never a half-built one, // and an overtaken init leaves nothing running behind the shutdown that overtook it. lock (_lifecycleLock) { if (generation != _lifecycleGeneration) throw new AbCipInitializationSupersededException( $"AbCip driver {_driverInstanceId} initialization was superseded by a shutdown or a newer initialization."); _options = options; if (adoptedConfig) _alarmProjection = new AbCipAlarmProjection(this, options.AlarmPollInterval, _logger); _devices = builtDevices; _devicesByRoutingKey = builtRoutes; _tagsByRawPath = builtTagsByRawPath; _declaredTags = builtDeclaredTags; _skippedTags.Commit(); // Probe loops — one per device when enabled + a ProbeTagPath is configured. Started inside the lock so // a retire that follows this publish always sees (and joins) them. if (options.Probe.Enabled && !string.IsNullOrWhiteSpace(options.Probe.ProbeTagPath)) { foreach (var state in builtDevices.Values) { state.ProbeCts = new CancellationTokenSource(); var ct = state.ProbeCts.Token; // Keep the loop Task so a teardown can await its clean exit before // disposing the CTS / handles the loop is still using. state.ProbeTask = Task.Run(() => ProbeLoopAsync(state, ct), ct); } } _health = new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null); } builtDevices = null; // published: owned by the next retire now if (options.Probe.Enabled && string.IsNullOrWhiteSpace(options.Probe.ProbeTagPath) && options.Devices.Count > 0) { // Probe is Enabled but no ProbeTagPath is configured. Without a // tag path the loop has nothing to read, so HostState would stay Unknown forever // and GetHostStatuses() would report every device as Unknown with no warning. // Log a warning so the misconfiguration is visible in the rolling Serilog file. _logger.LogWarning( "AbCip probe is enabled but no ProbeTagPath is configured for driver {DriverInstanceId} — " + "host connectivity probe loops were NOT started; GetHostStatuses() will report every device " + "as Unknown until a ProbeTagPath is set or Probe.Enabled is set to false.", _driverInstanceId); } } catch (Exception ex) { // Never-published states hold no probe loop and no runtime yet; dispose for symmetry. if (builtDevices is not null) foreach (var state in builtDevices.Values) state.Retire(); if (ex is AbCipInitializationSupersededException) { _logger.LogInformation("AbCip driver {DriverInstanceId} initialization abandoned: {Reason}", _driverInstanceId, ex.Message); throw; } lock (_lifecycleLock) { // A superseded init must not overwrite the health of whatever superseded it. if (generation == _lifecycleGeneration) _health = new DriverHealth(DriverState.Faulted, null, ex.Message); } _logger.LogError(ex, "AbCip driver {DriverInstanceId} failed to initialize", _driverInstanceId); throw; } } /// Bound on joining the retired probe loops — matches the fleet's "≤ 5 s join" teardown rule. private static readonly TimeSpan ProbeJoinTimeout = TimeSpan.FromSeconds(5); /// /// Retires the published device states: swaps empty device/route/tag tables in under the lifecycle lock /// (bumping the generation), then cancels, joins (bounded, independent of any caller token — a cancelled /// caller must not dispose handles under a probe loop that is still running) and disposes the states it took. /// Concurrent callers each take a disjoint table, so every state is torn down exactly once. The device part of /// and the first step of . /// /// The lifecycle generation this retire produced. private async Task ReleaseDeviceStatesAsync() { Dictionary retired; AbCipAlarmProjection projection; int generation; lock (_lifecycleLock) { generation = ++_lifecycleGeneration; retired = _devices; _devices = new Dictionary(StringComparer.OrdinalIgnoreCase); _devicesByRoutingKey = new Dictionary(StringComparer.OrdinalIgnoreCase); // Rebuilt wholesale by Initialize; swap, never Clear(): the retained poll engine / discovery may be enumerating. _tagsByRawPath = new(StringComparer.Ordinal); _declaredTags = new(); projection = _alarmProjection; } // The projection is replaced (not reused) when a config body is adopted; dispose it so its poll loop does // not outlive it and raise duplicate alarm events through this driver. Idempotent, and reusable afterwards. await projection.DisposeAsync().ConfigureAwait(false); foreach (var state in retired.Values) { try { state.ProbeCts?.Cancel(); } catch (ObjectDisposedException) { } } var loops = retired.Values.Select(s => s.ProbeTask).OfType().ToArray(); if (loops.Length > 0) { try { await Task.WhenAll(loops).WaitAsync(ProbeJoinTimeout).ConfigureAwait(false); } catch (TimeoutException) { _logger.LogWarning("AbCip driver {DriverInstanceId}: a probe loop did not exit within {Timeout}; disposing anyway", _driverInstanceId, ProbeJoinTimeout); } catch (Exception) { /* a loop never faults by design; nothing to add here */ } } foreach (var state in retired.Values) { state.ProbeCts?.Dispose(); state.ProbeCts = null; state.ProbeTask = null; state.Retire(); } return generation; } /// public async Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) { await ShutdownAsync(cancellationToken).ConfigureAwait(false); await InitializeAsync(driverConfigJson, cancellationToken).ConfigureAwait(false); } /// /// /// A complete teardown: the poll engine (and every subscription), the alarm projection, every probe loop /// (joined ≤ 5 s) and every runtime handle. Safe to run concurrently with and with /// an it overtakes (that init then publishes nothing). /// public async Task ShutdownAsync(CancellationToken cancellationToken) { await _poll.DisposeAsync().ConfigureAwait(false); var generation = await ReleaseDeviceStatesAsync().ConfigureAwait(false); _resolver.Clear(); // no-op in v3 (the resolver reads the live table by closure); kept for symmetry lock (_lifecycleLock) { // M4: a newer InitializeAsync that published while this shutdown was still joining its probe loops owns the // health now — stamping Unknown over its Healthy would misreport a live driver. if (generation == _lifecycleGeneration) UpdateHealth(h => new DriverHealth(DriverState.Unknown, h.LastSuccessfulRead, null)); } } // ---- ISubscribable (polling overlay via shared engine) ---- /// public Task SubscribeAsync( IReadOnlyList fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken) => Task.FromResult(_poll.Subscribe(fullReferences, publishingInterval)); /// public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) { // Async teardown: the engine drains the in-flight poll without blocking the caller's // thread — this runs inside a DriverInstanceActor mailbox turn. await _poll.UnsubscribeAsync(handle).ConfigureAwait(false); } // ---- IAlarmSource (ALMD projection) ---- /// public Task SubscribeAlarmsAsync( IReadOnlyList sourceNodeIds, CancellationToken cancellationToken) { if (!_options.EnableAlarmProjection) { var disabled = new AbCipAlarmSubscriptionHandle(0); return Task.FromResult(disabled); } return _alarmProjection.SubscribeAsync(sourceNodeIds, cancellationToken); } /// public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken) => _options.EnableAlarmProjection ? _alarmProjection.UnsubscribeAsync(handle, cancellationToken) : Task.CompletedTask; /// public Task AcknowledgeAsync( IReadOnlyList acknowledgements, CancellationToken cancellationToken) => _options.EnableAlarmProjection ? _alarmProjection.AcknowledgeAsync(acknowledgements, cancellationToken) : Task.CompletedTask; // ---- IHostConnectivityProbe ---- /// public IReadOnlyList GetHostStatuses() => [.. _devices.Values.Select(s => new HostConnectivityStatus(s.Options.HostAddress, s.HostState, s.HostStateChangedUtc))]; private async Task ProbeLoopAsync(DeviceState state, CancellationToken ct) { var probeParams = state.BuildCreateParams(_options.Probe.ProbeTagPath!, _options.Probe.Timeout); IAbCipTagRuntime? probeRuntime = null; while (!ct.IsCancellationRequested) { // The probe's verdicts for this tick, decided SEPARATELY (review 07 H10): // backoffVerdict — true = record success, false = record failure, null = no signal; // hostState — the host transition, null = no evidence either way (leave it). // Recorded AFTER the try/catch so the per-device connect gate is taken outside a catch block. bool? backoffVerdict = null; HostState? hostState = HostState.Stopped; try { probeRuntime ??= _tagFactory.Create(probeParams); // Lazy-init on first attempt; re-init after a transport failure has caused the // native handle to be destroyed. if (!state.ProbeInitialized) { await probeRuntime.InitializeAsync(ct).ConfigureAwait(false); state.ProbeInitialized = true; } await probeRuntime.ReadAsync(ct).ConfigureAwait(false); var status = probeRuntime.GetStatus(); if (status == 0) { backoffVerdict = true; // Device reachable — reset the data-path window hostState = HostState.Running; } else if (AbCipRefusals.IsDeviceRefusal(status)) { // The controller answered, refusing the probe tag: reachable. backoffVerdict = true; hostState = HostState.Running; WarnProbeRefusedOnce(state, ((AbStatus)status).ToString()); } } catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } catch (Exception ex) when (AbCipRefusals.IsDeviceRefusal(ex)) { // H10: a missing / typo'd / download-deleted probe tag. The controller ANSWERED over a working session, // so this is a config error on the probe tag — not a Forward-Open failure. Recording a failure here // every tick saturated the backoff (5 s ticks vs a 30 s cap ⇒ ShouldAttempt never true) and blacked out // every cold / evicted data tag on a reachable device, indefinitely. backoffVerdict = true; hostState = HostState.Running; WarnProbeRefusedOnce(state, ex.Message); // Keep an initialised runtime (its lease stays up — no Forward Open/Close per tick); one whose // initialisation threw is re-created next tick, as before. if (!state.ProbeInitialized) { try { probeRuntime?.Dispose(); } catch { } probeRuntime = null; } } catch (Exception ace) when (ace is AbCipTagConfigurationException or AbCipLocalRefusalException) { // The probe tag's own name cannot become a request (or the library refused it locally) — it never // reached the device, so it is no evidence either way: no backoff signal, no host transition, one Warning. try { probeRuntime?.Dispose(); } catch { } probeRuntime = null; state.ProbeInitialized = false; hostState = null; WarnProbeRefusedOnce(state, ace.Message); } catch (Exception ex) { // Wire / init error — tear down the probe runtime so the next tick re-creates it. // Log at debug because a wedged device produces one per tick; the // OnHostStatusChanged event is the persistent record once the state transitions. _logger.LogDebug(ex, "AbCip probe tick failed for driver {DriverInstanceId} device {Device}", _driverInstanceId, state.Options.HostAddress); try { probeRuntime?.Dispose(); } catch { } probeRuntime = null; state.ProbeInitialized = false; backoffVerdict = false; // the device did not answer — keep the data-path window open } // ConnectionBackoff is caller-serialized, and the data path now records under the // per-device connect gate — so the probe records under it too, or its reset/increment // could interleave with a concurrent cold-tag connect record and lose one. The gate is // held by the data path only across ONE connect attempt, so this wait is bounded by a // Forward-Open timeout; the data path never waits on anything the probe holds, so no // deadlock is possible. Cancellation exits the loop as it does anywhere else. if (backoffVerdict is { } verdict) { try { await state.ConnectGate.WaitAsync(ct).ConfigureAwait(false); } catch (OperationCanceledException) { break; } try { if (verdict) state.Backoff.RecordSuccess(); else state.Backoff.RecordFailure(DateTime.UtcNow); } finally { state.ConnectGate.Release(); } } if (hostState is { } host) TransitionDeviceState(state, host); try { await Task.Delay(_options.Probe.Interval, ct).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } try { probeRuntime?.Dispose(); } catch { } } /// Logs, once per device state, that the controller answered but refused the configured probe tag. private void WarnProbeRefusedOnce(DeviceState state, string reason) { if (Interlocked.Exchange(ref state.ProbeRefusalWarned, 1) != 0) return; _logger.LogWarning( "AbCip probe tag {ProbeTag} on device {Device} cannot be read: {Reason}. The controller answered, so the device " + "is treated as reachable; fix Probe.ProbeTagPath for driver {DriverInstanceId} (logged once per device)", _options.Probe.ProbeTagPath, state.Options.HostAddress, reason, _driverInstanceId); } private void TransitionDeviceState(DeviceState state, HostState newState) { HostState old; lock (state.ProbeLock) { old = state.HostState; if (old == newState) return; state.HostState = newState; state.HostStateChangedUtc = DateTime.UtcNow; } OnHostStatusChanged?.Invoke(this, new HostStatusChangedEventArgs(state.Options.HostAddress, old, newState)); } // ---- IPerCallHostResolver ---- // Resolves a read/write/subscribe reference (a RawPath) to the device host that keys its per-host // resilience (bulkhead / circuit breaker). Routes through the authored table so a tag resolves to // its OWN device's host rather than the first-device fallback - else a broken device B would trip // device A's breaker. The tag's device routing key is resolved to the device's actual host address // (the resilience key), matching by DeviceName-or-host. /// public string ResolveHost(string fullReference) { if (_resolver.TryResolve(fullReference, out var def) && _devicesByRoutingKey.TryGetValue(def.DeviceHostAddress, out var state)) return state.Options.HostAddress; return _options.Devices.FirstOrDefault()?.HostAddress ?? DriverInstanceId; } // ---- IReadable ---- /// public async Task> ReadAsync( IReadOnlyList fullReferences, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(fullReferences); var now = DateTime.UtcNow; var results = new DataValueSnapshot[fullReferences.Count]; // Plan the batch: members of the same parent UDT get collapsed into one // whole-UDT read + in-memory member decode; every other reference falls back to the // per-tag read path. Planner is a pure function over the // current tag map; BOOL/String/Structure members stay on the fallback path because // declaration-only offsets can't place them under Logix alignment rules. Whole-UDT // grouping is itself gated behind EnableDeclarationOnlyUdtGrouping — Studio 5000 may // reorder UDT members vs declaration order, so the fast path is opt-in only. var plan = AbCipUdtReadPlanner.Build( fullReferences, _tagsByRawPath, _options.EnableDeclarationOnlyUdtGrouping); var groups = plan.Groups; var fallbacks = plan.Fallbacks; var itemCount = groups.Count + fallbacks.Count; if (itemCount == 0) return results; // Bounded-parallel window ACROSS work items (groups ∪ fallbacks). Each item still takes its // OWN per-tag runtime lock inside ReadGroupAsync / ReadSingleAsync, so one libplctag handle // is never touched concurrently — the window only lets DIFFERENT tags' device // round trips overlap, which a strictly sequential await chain made impossible. Results are // index-addressed, so completion order is irrelevant. Per-item health verdicts are COLLECTED // and written once after the batch: an inline write to the shared _health field would race. var maxConcurrent = ReadWindow; var outcomes = new ReadOutcome[itemCount]; using var window = new SemaphoreSlim(maxConcurrent, maxConcurrent); var tasks = new Task[itemCount]; for (var i = 0; i < itemCount; i++) tasks[i] = RunItemAsync(i); // Task.WhenAll completes only once EVERY item has finished (it does not short-circuit on the // first fault), so disposing the window on the way out can never pull the semaphore out from // under an item still waiting on it. await Task.WhenAll(tasks).ConfigureAwait(false); ApplyBatchHealth(outcomes, now); return results; // The window slot is taken INSIDE each item, after its runtime exists (P7): a cold create queues on its // device's single-flight connect gate, and holding a slot while queued there let one dead device's // backoff-expiry attempt occupy the whole window for a full Timeout, stalling every other device's reads. async Task RunItemAsync(int slot) { if (slot < groups.Count) { outcomes[slot] = await ReadGroupAsync(groups[slot], results, now, window, cancellationToken) .ConfigureAwait(false); } else { var fb = fallbacks[slot - groups.Count]; outcomes[slot] = await ReadSingleAsync( fb, fullReferences[fb.OriginalIndex], results, now, window, cancellationToken) .ConfigureAwait(false); } } } /// /// Floor on the read window when the native transport serves this driver (P8). Its runtimes share one /// request scheduler per device that packs whatever is queued when the pump wakes into one Multiple Service /// Packet — bounded by the connection's request AND reply byte budget, so a wide window cannot over-pack. The /// window is therefore the cap on services per round trip: at 8, a 1000-tag controller paid ~125 round trips /// per poll instead of ~10. /// internal const int NativeMinReadWindow = 64; /// /// The effective bounded-parallel read window: (clamped /// to ≥ 1), raised to at least when the native tag factory serves the reads. /// libplctag overlaps per-handle round trips only, so it (and any injected factory) keeps the option as is. /// internal int ReadWindow => _tagFactory is NativeAbCipTagFactory ? Math.Max(NativeMinReadWindow, _options.MaxConcurrentReads) : Math.Max(1, _options.MaxConcurrentReads); /// /// One read work item's health verdict. Returned by / /// instead of written to the shared health field inline, because /// under the bounded-parallel read window those writes would race (last-writer-wins across /// threads could report Healthy for a batch that mostly failed, or vice versa). /// A null means "no health signal" — a config-level miss such as an /// unknown reference or unknown device, which never touched the wire and never touched health. /// private readonly record struct ReadOutcome(DriverState? State, string? Error, bool Answered = false) { /// The item produced no health signal at all. public static ReadOutcome None => new(null, null); /// /// The controller answered with a deterministic refusal: no health STATE signal (a refusal is not a comms /// fault), but proof the device is reachable, so LastSuccessfulRead advances. /// public static ReadOutcome Refused => new(null, null, Answered: true); /// The item read successfully. public static ReadOutcome Success => new(DriverState.Healthy, null); /// The item failed on the wire. /// The failure detail surfaced as LastError. /// A degraded outcome carrying . public static ReadOutcome Degraded(string message) => new(DriverState.Degraded, message); } private static int HealthRank(DriverState state) => state switch { // No ReadOutcome factory produces Faulted today (a read item is Healthy, Degraded, or no // signal at all); the tier is future-proofing for an outcome source that reports it, so the // worst-wins order stays correct without a second edit here. DriverState.Faulted => 2, DriverState.Degraded => 1, _ => 0, }; /// /// Write the batch's health ONCE, after every work item has finished: worst outcome wins /// (Faulted > Degraded > Healthy) and LastSuccessfulRead advances if ANY item /// succeeded — the contract the comms-loss watchdog reads (a success advances it; a batch /// where everything failed freezes it, which is what trips the watchdog). /// private void ApplyBatchHealth(ReadOnlySpan outcomes, DateTime now) { var anySuccess = false; var anyAnswered = false; DriverState? worst = null; string? worstError = null; foreach (var outcome in outcomes) { if (outcome.Answered) anyAnswered = true; if (outcome.State is not { } state) continue; if (state == DriverState.Healthy) anySuccess = true; if (worst is null || HealthRank(state) > HealthRank(worst.Value)) { worst = state; worstError = outcome.Error; } } if (worst is not { } worstState) { // No state signal. If a controller answered (a refusal), that still proves it reachable: advance // LastSuccessfulRead and leave the state alone. Otherwise nothing reached the wire (every reference was // unknown / unroutable / misconfigured) — leave health alone entirely. if (anyAnswered) UpdateHealth(current => current with { LastSuccessfulRead = now }); return; } UpdateHealth(current => new DriverHealth( worstState, anySuccess || anyAnswered ? now : current.LastSuccessfulRead, worstState == DriverState.Healthy ? null : worstError)); } private async Task ReadSingleAsync( AbCipUdtReadFallback fb, string reference, DataValueSnapshot[] results, DateTime now, SemaphoreSlim window, CancellationToken ct) { if (!_resolver.TryResolve(reference, out var def)) { results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadNodeIdUnknown, null, now); return ReadOutcome.None; } // A Structure tag whose Members are declared is a container — // its bare name is readable via the whole-UDT grouping path (ReadGroupAsync), not the // per-tag path. Reading it here returns BadNotSupported rather than Good/null so the // caller knows to address individual member paths (e.g. "Motor.Speed"). if (def.DataType == AbCipDataType.Structure && def.Members is { Count: > 0 }) { results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadNotSupported, null, now); return ReadOutcome.None; } if (!_devicesByRoutingKey.TryGetValue(def.DeviceHostAddress, out var device)) { results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadNodeIdUnknown, null, now); return ReadOutcome.None; } try { var runtime = await EnsureTagRuntimeAsync(device, def, ct).ConfigureAwait(false); // Window slot only now that the runtime exists (see ReadAsync); a wait that throws never acquired. await window.WaitAsync(ct).ConfigureAwait(false); // Serialise Read → GetStatus → Decode against the shared runtime — the cached libplctag // Tag handle is not concurrency-safe and GetStatus returns the LAST op's status. var opLock = device.GetRuntimeLock(def.Name); try { await opLock.WaitAsync(ct).ConfigureAwait(false); try { await runtime.ReadAsync(ct).ConfigureAwait(false); var status = runtime.GetStatus(); if (status == (int)AbStatus.TypeMismatch) { // Final review I4: the controller ANSWERED with a type that disagrees with the authored // one — a deterministic config error, not a comms fault. Keep the handle (evicting would // re-create it — and, for a sole lease holder, re-Forward-Open — on every poll), leave // health alone, warn once per tag. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadTypeMismatch, null, now); WarnTypeMismatchOnce(def.Name, "AbCip read of {Tag} on device {Device}: the controller's type does not match the authored " + "{DataType}; reporting BadTypeMismatch until the tag's dataType is corrected (logged once per tag)", reference, def.DeviceHostAddress, def.DataType); return ReadOutcome.Refused; } if (AbCipRefusals.IsDeviceRefusal(status)) { // The controller answered with a deterministic refusal: per-tag Bad, keep the handle. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.MapReadStatus((AbStatus)status), null, now); WarnRefusalOnce(def.Name, "read", reference, def.DeviceHostAddress, ((AbStatus)status).ToString()); return ReadOutcome.Refused; } if (status != 0) { // Evict the stale handle so the next call re-creates it. // A non-zero status can mean the controller dropped the connection or the tag // handle became permanently invalid (e.g. after a PLC download). Evicting // mirrors the probe loop's recreate-on-failure behaviour. EvictRuntime(device, def.Name); results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.MapStatus(status), null, now); _logger.LogWarning( "AbCip read returned non-zero transport status {Status} for tag {Tag} on device {Device}; " + "evicting cached runtime so next call re-creates it", status, reference, def.DeviceHostAddress); return ReadOutcome.Degraded($"transport status {status} reading {reference}"); } var tagPath = AbCipTagPath.TryParse(def.TagPath); var bitIndex = tagPath?.BitIndex; // libplctag never checks the CIP type the controller returned; it decodes the bytes as // the authored type. A scalar whose buffer is not that type's width is mis-typed config // (seen live: a REAL authored as INT read Good -17346), so refuse it rather than publish // garbage as Good. Same-width mismatches (DINT vs REAL) cannot be seen this way. if (!IsArrayTag(def) && bitIndex is null && ExpectedScalarWidth(def.DataType) is { } width && runtime.GetSize() is var size && size >= 0 && size != width) { // Same class as the native TypeMismatch above (final review I4): deterministic, device // answered — no Degraded, warn once per tag. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadTypeMismatch, null, now); WarnTypeMismatchOnce(def.Name, "AbCip read of {Tag} on device {Device} returned {Size} bytes but its authored type {DataType} is {Width} bytes wide; check the tag's dataType (logged once per tag)", reference, def.DeviceHostAddress, size, def.DataType, width); return ReadOutcome.Refused; } // Review I-1 — an array tag (the EXPLICIT IsArray flag) decodes the whole buffer into an // element-typed CLR array (int[]/float[]/bool[]/string[]…), INCLUDING a 1-element array // (ElementCount 1). Scalar tags keep the single-value path. var value = IsArrayTag(def) ? runtime.DecodeArray(def.DataType, Math.Max(1, def.ElementCount)) : runtime.DecodeValue(def.DataType, bitIndex); results[fb.OriginalIndex] = new DataValueSnapshot(value, AbCipStatusMapper.Good, now, now); return ReadOutcome.Success; } finally { opLock.Release(); } } finally { window.Release(); } } catch (OperationCanceledException) { throw; } catch (AbCipLocalRefusalException local) { // #737 I2: refused by the library / driver itself — no I/O, so no proof the device answered: BadNotSupported, // keep the handle, no health signal, LastSuccessfulRead untouched. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadNotSupported, null, now); WarnRefusalOnce(def.Name, "read", reference, def.DeviceHostAddress, local.Message); return ReadOutcome.None; } catch (AbTransportException ate) when (ate.Status == AbStatus.Unsupported) { // The DEVICE refused (CIP 0x08, or a decode refusal of data it returned) — not a comms fault: // BadNotSupported, keep the handle, no state change; it answered, so LastSuccessfulRead advances (M2). results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadNotSupported, null, now); WarnRefusalOnce(def.Name, "read", reference, def.DeviceHostAddress, ate.Message); return ReadOutcome.Refused; } catch (AbCipTagConfigurationException ace) { // This tag's name/path cannot become a request — nothing reached the device, so // no evict (nothing was cached), no health signal, no backoff; siblings keep reading. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadConfigurationError, null, now); WarnConfigurationErrorOnce(def.Name, reference, def.DeviceHostAddress, ace); return ReadOutcome.None; } catch (AbTransportException ate) when (ate.Status == AbStatus.TypeMismatch) { // Final review I4: deterministic, keep the handle, no health signal, warn once per tag. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadTypeMismatch, null, now); WarnTypeMismatchOnce(def.Name, "AbCip read of {Tag} on device {Device} refused: {Reason} (logged once per tag)", reference, def.DeviceHostAddress, ate.Message); return ReadOutcome.Refused; } catch (AbTransportException ate) when (AbCipRefusals.IsDeviceRefusal(ate)) { // H1/L4: the controller answered "no" (renamed tag, Arr[999], read-protected …) — a per-tag config // error, not a comms fault. Keep the handle (no evict → no lease / Forward-Open churn), no Degraded, // no backoff (EnsureTagRuntimeAsync already recorded the answer as reachable), warn once per tag. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.MapReadStatus(ate.Status), null, now); WarnRefusalOnce(def.Name, "read", reference, def.DeviceHostAddress, ate.Message); return ReadOutcome.Refused; } catch (Exception) when (device.Retired) { // A re-init / shutdown retired this device under the read: its handles were disposed by the teardown, not // lost on the wire — no evict (the teardown owns them), no health signal. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now); return ReadOutcome.None; } catch (Exception ex) { // Transport exception — evict so the next read creates a fresh handle. An AbTransportException // carries its AbStatus, so a tag the controller does not have reads // BadNodeIdUnknown and a decode past the buffer BadOutOfRange, not a comms error. EvictRuntime(device, def.Name); results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.MapException(ex), null, now); _logger.LogWarning(ex, "AbCip read transport exception for tag {Tag} on device {Device}", reference, def.DeviceHostAddress); return ReadOutcome.Degraded(ex.Message); } } /// /// Perform one whole-UDT read on the parent tag, then decode each /// grouped member from the runtime's buffer at its computed byte offset. A per-group /// failure (parent read raised, non-zero transport status, or missing device) stamps /// the mapped fault across every grouped member only — sibling groups + the /// per-tag fallback list are unaffected. /// private async Task ReadGroupAsync( AbCipUdtReadGroup group, DataValueSnapshot[] results, DateTime now, SemaphoreSlim window, CancellationToken ct) { var parent = group.ParentDefinition; if (!_devicesByRoutingKey.TryGetValue(parent.DeviceHostAddress, out var device)) { StampGroupStatus(group, results, now, AbCipStatusMapper.BadNodeIdUnknown); return ReadOutcome.None; } try { var runtime = await EnsureTagRuntimeAsync(device, parent, ct).ConfigureAwait(false); // Window slot only now that the runtime exists (see ReadAsync); a wait that throws never acquired. await window.WaitAsync(ct).ConfigureAwait(false); // Serialise the whole-UDT Read → GetStatus → per-member DecodeValueAt against the shared // parent runtime — the members decode from that one handle's buffer. var opLock = device.GetRuntimeLock(parent.Name); try { await opLock.WaitAsync(ct).ConfigureAwait(false); try { await runtime.ReadAsync(ct).ConfigureAwait(false); var status = runtime.GetStatus(); if (status == (int)AbStatus.TypeMismatch) { // Final review I4: deterministic — keep the handle, no health signal, warn once. StampGroupStatus(group, results, now, AbCipStatusMapper.BadTypeMismatch); WarnTypeMismatchOnce(parent.Name, "AbCip whole-UDT read of {Parent} on device {Device}: the controller's type does not match " + "the authored type; {MemberCount} members report BadTypeMismatch (logged once per tag)", group.ParentName, parent.DeviceHostAddress, group.Members.Count); return ReadOutcome.Refused; } if (AbCipRefusals.IsDeviceRefusal(status)) { StampGroupStatus(group, results, now, AbCipStatusMapper.MapReadStatus((AbStatus)status)); WarnRefusalOnce(parent.Name, "whole-UDT read", group.ParentName, parent.DeviceHostAddress, ((AbStatus)status).ToString()); return ReadOutcome.Refused; } if (status != 0) { EvictRuntime(device, parent.Name); var mapped = AbCipStatusMapper.MapStatus(status); StampGroupStatus(group, results, now, mapped); _logger.LogWarning( "AbCip whole-UDT read returned non-zero transport status {Status} for parent {Parent} " + "on device {Device}; {MemberCount} member values stamped with mapped status", status, group.ParentName, parent.DeviceHostAddress, group.Members.Count); return ReadOutcome.Degraded($"transport status {status} reading UDT {group.ParentName}"); } foreach (var member in group.Members) { var value = runtime.DecodeValueAt(member.Definition.DataType, member.Offset, bitIndex: null); results[member.OriginalIndex] = new DataValueSnapshot(value, AbCipStatusMapper.Good, now, now); } return ReadOutcome.Success; } finally { opLock.Release(); } } finally { window.Release(); } } catch (OperationCanceledException) { throw; } catch (AbCipLocalRefusalException local) { StampGroupStatus(group, results, now, AbCipStatusMapper.BadNotSupported); WarnRefusalOnce(parent.Name, "whole-UDT read", group.ParentName, parent.DeviceHostAddress, local.Message); return ReadOutcome.None; } catch (AbTransportException ate) when (ate.Status == AbStatus.Unsupported) { StampGroupStatus(group, results, now, AbCipStatusMapper.BadNotSupported); WarnRefusalOnce(parent.Name, "whole-UDT read", group.ParentName, parent.DeviceHostAddress, ate.Message); return ReadOutcome.Refused; } catch (AbCipTagConfigurationException ace) { // The parent's name cannot become a request — per-group config error, device untouched. StampGroupStatus(group, results, now, AbCipStatusMapper.BadConfigurationError); WarnConfigurationErrorOnce(parent.Name, group.ParentName, parent.DeviceHostAddress, ace); return ReadOutcome.None; } catch (AbTransportException ate) when (ate.Status == AbStatus.TypeMismatch) { StampGroupStatus(group, results, now, AbCipStatusMapper.BadTypeMismatch); WarnTypeMismatchOnce(parent.Name, "AbCip whole-UDT read of {Parent} on device {Device} refused: {Reason} (logged once per tag)", group.ParentName, parent.DeviceHostAddress, ate.Message); return ReadOutcome.Refused; } catch (AbTransportException ate) when (AbCipRefusals.IsDeviceRefusal(ate.Status)) { StampGroupStatus(group, results, now, AbCipStatusMapper.MapReadStatus(ate.Status)); WarnRefusalOnce(parent.Name, "whole-UDT read", group.ParentName, parent.DeviceHostAddress, ate.Message); return ReadOutcome.Refused; } catch (Exception) when (device.Retired) { StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError); return ReadOutcome.None; } catch (Exception ex) { EvictRuntime(device, parent.Name); StampGroupStatus(group, results, now, AbCipStatusMapper.MapException(ex)); _logger.LogWarning(ex, "AbCip whole-UDT read transport exception for parent {Parent} on device {Device}", group.ParentName, parent.DeviceHostAddress); return ReadOutcome.Degraded(ex.Message); } } private static void StampGroupStatus( AbCipUdtReadGroup group, DataValueSnapshot[] results, DateTime now, uint statusCode) { foreach (var member in group.Members) results[member.OriginalIndex] = new DataValueSnapshot(null, statusCode, null, now); } // ---- IWritable ---- /// public async Task> WriteAsync( IReadOnlyList writes, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(writes); var results = new WriteResult[writes.Count]; var now = DateTime.UtcNow; for (var i = 0; i < writes.Count; i++) { var w = writes[i]; if (!_resolver.TryResolve(w.FullReference, out var def)) { results[i] = new WriteResult(AbCipStatusMapper.BadNodeIdUnknown); continue; } if (!def.Writable || def.SafetyTag) { results[i] = new WriteResult(AbCipStatusMapper.BadNotWritable); continue; } if (!_devicesByRoutingKey.TryGetValue(def.DeviceHostAddress, out var device)) { results[i] = new WriteResult(AbCipStatusMapper.BadNodeIdUnknown); continue; } // Whole-UDT writes are refused by DECISION, not deferred: a structure write // overwrites every member of the controller's instance, hidden BOOL hosts and padding included, // with whatever the client sent. Address the members instead (each is its own raw tag). Refused // before a runtime exists, so nothing is read or sent; a refusal is not a fault — no health change. if (def.DataType == AbCipDataType.Structure) { results[i] = new WriteResult(AbCipStatusMapper.BadNotSupported); WarnWriteRefusedOnce(def.Name, "AbCip write to {Tag} on device {Device} refused: whole-UDT writes are not supported — write its members (logged once per tag)", w.FullReference, def.DeviceHostAddress); continue; } string? rmwParent = null; // U10: an array tag writes the WHOLE array. Shape is checked before any runtime exists, so a refused // write creates, reads and sends nothing; a refusal is not a fault — no health change. object?[]? arrayElements = null; if (IsArrayTag(def)) { var count = Math.Max(1, def.ElementCount); uint? shapeRefusal = null; string reason = ""; if (AbCipArrayCodec.ElementWidth(def.DataType) is null) { shapeRefusal = AbCipStatusMapper.BadNotSupported; reason = $"{def.DataType} arrays cannot be written element-wise (BOOL arrays are bit-packed DWORDs, STRING/structure elements are structures)"; } else if (AbCipArrayCodec.Elements(w.Value) is not { } elements) { shapeRefusal = AbCipStatusMapper.BadTypeMismatch; reason = $"the value is not an array ({w.Value?.GetType().Name ?? "null"})"; } else if (elements.Length != count) { shapeRefusal = AbCipStatusMapper.BadOutOfRange; reason = $"{elements.Length} element(s) written to a {count}-element array"; } else { arrayElements = elements; } if (shapeRefusal is { } refusedShape) { results[i] = new WriteResult(refusedShape); WarnWriteRefusedOnce(def.Name, "AbCip array write to {Tag} on device {Device} refused: {Reason} (logged once per tag)", w.FullReference, def.DeviceHostAddress, reason); continue; } } try { var parsedPath = AbCipTagPath.TryParse(def.TagPath); // BOOL-within-DINT writes — RMW against a parallel parent-DINT // runtime. Dispatching here keeps the normal EncodeValue path clean; the // per-parent lock prevents two concurrent bit writes to the same DINT from // losing one another's update. if (def.DataType == AbCipDataType.Bool && parsedPath?.BitIndex is int bit) { rmwParent = (parsedPath with { BitIndex = null }).ToLibplctagName(); results[i] = new WriteResult( await WriteBitInDIntAsync(device, parsedPath, bit, w.Value, cancellationToken) .ConfigureAwait(false)); if (results[i].StatusCode == AbCipStatusMapper.Good) RecordWriteAnswered(now); continue; } var runtime = await EnsureTagRuntimeAsync(device, def, cancellationToken).ConfigureAwait(false); // Serialise Encode → Write → GetStatus against the shared runtime — the same cached // Tag handle may be in use by a concurrent ReadAsync or poll loop. var opLock = device.GetRuntimeLock(def.Name); await opLock.WaitAsync(cancellationToken).ConfigureAwait(false); int status; uint? refusal; int size; try { // The bytes the controller holds for this path must be what the authored type // encodes, BEFORE anything is sent — on BOTH transports. libplctag never checks: it encodes // into the buffer the last read sized and sends the whole buffer, so an INT authored over a // DINT patched two bytes and wrote four (stale high word), and a BOOL over a packed // BOOL-array DWORD wrote all 32 bits. Discovered UDT members are where a mis-authored type // is most likely (browse-commit fills dataType from the template, an operator may retype). size = runtime.GetSize(); refusal = arrayElements is not null ? ArrayWriteWidthRefusal(def, size) : WriteWidthRefusal(def, parsedPath?.BitIndex, size, runtimeTypesBool: runtime is NativeAbCipTagRuntime); if (refusal is null) { if (arrayElements is not null) runtime.EncodeArray(def.DataType, arrayElements); else runtime.EncodeValue(def.DataType, parsedPath?.BitIndex, w.Value); await runtime.WriteAsync(cancellationToken).ConfigureAwait(false); status = runtime.GetStatus(); } else { status = 0; } } finally { opLock.Release(); } if (refusal is { } refused) { // Deterministic, nothing sent: keep the handle, leave health alone, warn once per tag. results[i] = new WriteResult(refused); WarnTypeMismatchOnce(def.Name, "AbCip write to {Tag} on device {Device} refused before sending: the controller holds {Size} byte(s) there but the authored {DataType} encodes {Width} (logged once per tag)", w.FullReference, def.DeviceHostAddress, size, def.DataType, arrayElements is not null ? AbCipArrayCodec.ElementWidth(def.DataType) * arrayElements.Length : ExpectedScalarWriteWidth(def.DataType)); } else if (status == (int)AbStatus.TypeMismatch) { // Final review I4: deterministic — keep the handle, leave health, warn once per tag. results[i] = new WriteResult(AbCipStatusMapper.BadTypeMismatch); RecordWriteAnswered(now); WarnTypeMismatchOnce(def.Name, "AbCip write to {Tag} on device {Device} refused: the controller's type does not match the authored {DataType} (logged once per tag)", w.FullReference, def.DeviceHostAddress, def.DataType); } else if (AbCipRefusals.IsDeviceRefusal(status)) { // The controller refused this write (read-only, out of bounds …): keep the handle, no state change; // it answered, so LastSuccessfulRead advances (M2). results[i] = new WriteResult(AbCipStatusMapper.MapStatus(status)); RecordWriteAnswered(now); WarnRefusalOnce(def.Name, "write", w.FullReference, def.DeviceHostAddress, ((AbStatus)status).ToString()); } else if (status != 0) { EvictRuntime(device, def.Name); results[i] = new WriteResult(AbCipStatusMapper.MapStatus(status)); RecordWriteCommsFault($"transport status {status} writing {w.FullReference}"); _logger.LogWarning( "AbCip write returned non-zero transport status {Status} for tag {Tag} on device {Device}; " + "evicting cached runtime so next call re-creates it", status, w.FullReference, def.DeviceHostAddress); } else { results[i] = new WriteResult(AbCipStatusMapper.Good); RecordWriteAnswered(now); } } catch (OperationCanceledException) { throw; } catch (NotSupportedException nse) { // A deterministic local refusal (a runtime that cannot encode this write without clobbering // something — e.g. a BOOL-array element as a single BOOL) — not a transport fault: keep the // handle and leave driver health alone (same rule as the Unsupported refusal // below). It used to latch Degraded, which a refusal the device never saw must not do. results[i] = new WriteResult(AbCipStatusMapper.BadNotSupported); WarnWriteRefusedOnce(def.Name, "AbCip write not supported for tag {Tag} on device {Device}: {Reason} (logged once per tag)", w.FullReference, def.DeviceHostAddress, nse.Message); } // H19: the three client-value conversion failures below never touched the wire — they say nothing about // the device, so they write no health (a Degraded here latched until the next good read, and AbLegacy // already maps the same three with no health write). Not a transport fault either: no evict. catch (FormatException fe) { results[i] = new WriteResult(AbCipStatusMapper.BadTypeMismatch); WarnWriteRefusedOnce(def.Name, "AbCip write to {Tag} on device {Device}: the value cannot be converted to {DataType}: {Reason} (logged once per tag)", w.FullReference, def.DeviceHostAddress, def.DataType, fe.Message); } catch (InvalidCastException ice) { results[i] = new WriteResult(AbCipStatusMapper.BadTypeMismatch); WarnWriteRefusedOnce(def.Name, "AbCip write to {Tag} on device {Device}: the value cannot be converted to {DataType}: {Reason} (logged once per tag)", w.FullReference, def.DeviceHostAddress, def.DataType, ice.Message); } catch (OverflowException oe) { results[i] = new WriteResult(AbCipStatusMapper.BadOutOfRange); WarnWriteRefusedOnce(def.Name, "AbCip write to {Tag} on device {Device}: the value is out of range for {DataType}: {Reason} (logged once per tag)", w.FullReference, def.DeviceHostAddress, def.DataType, oe.Message); } catch (AbCipLocalRefusalException local) { // Refused locally (e.g. the native runtime cannot type the write; libplctag NotImplemented) — nothing // sent: BadNotSupported, keep the handle, leave health alone. results[i] = new WriteResult(AbCipStatusMapper.BadNotSupported); WarnRefusalOnce(def.Name, "write", w.FullReference, def.DeviceHostAddress, local.Message); } catch (AbTransportException ate) when (ate.Status == AbStatus.Unsupported) { // The device refused the write as unsupported — BadNotSupported, keep the handle, no state change; // it answered, so LastSuccessfulRead advances (M2). results[i] = new WriteResult(AbCipStatusMapper.BadNotSupported); RecordWriteAnswered(now); WarnRefusalOnce(def.Name, "write", w.FullReference, def.DeviceHostAddress, ate.Message); } catch (AbCipTagConfigurationException ace) { // A config error on this tag — no evict, no health signal, no backoff. results[i] = new WriteResult(AbCipStatusMapper.BadConfigurationError); WarnConfigurationErrorOnce(def.Name, w.FullReference, def.DeviceHostAddress, ace); } catch (AbTransportException ate) when (ate.Status == AbStatus.TypeMismatch) { // Final review I4: the controller's type disagrees with the authored one (native type gate, or // CIP 0xFF/0x2107 from the controller) — deterministic: BadTypeMismatch, keep the handle, leave // health alone, warn once per tag. Retrying cannot succeed until the config is corrected. // No LastSuccessfulRead advance: the native type gate throws this BEFORE sending. results[i] = new WriteResult(AbCipStatusMapper.BadTypeMismatch); WarnTypeMismatchOnce(def.Name, "AbCip write to {Tag} on device {Device} refused: {Reason} (logged once per tag)", w.FullReference, def.DeviceHostAddress, ate.Message); } catch (AbTransportException ate) when (AbCipRefusals.IsDeviceRefusal(ate)) { // H1: the controller answered "no" to this write — keep the handle, no state change, warn once; it // answered, so LastSuccessfulRead advances (M2). results[i] = new WriteResult(AbCipStatusMapper.MapStatus(ate.Status)); RecordWriteAnswered(now); WarnRefusalOnce(def.Name, "write", w.FullReference, def.DeviceHostAddress, ate.Message); } catch (Exception) when (device.Retired) { // The device was retired under this write by a re-init / shutdown — not a comms fault. results[i] = new WriteResult(AbCipStatusMapper.BadCommunicationError); } catch (Exception ex) { // Transport / wire error — evict so the next write creates a fresh handle (for a bit write, the // parent runtime the read-modify-write used; the bit tag itself holds none). if (rmwParent is not null) EvictParentRuntime(device, rmwParent); else EvictRuntime(device, def.Name); results[i] = new WriteResult(AbCipStatusMapper.BadCommunicationError); RecordWriteCommsFault(ex.Message); _logger.LogWarning(ex, "AbCip write transport exception for tag {Tag} on device {Device}", w.FullReference, def.DeviceHostAddress); } } return results; } /// /// A good write proves the device answered: advance LastSuccessfulRead but leave the STATE alone. Writing /// Healthy here (H19) overwrote a Degraded the poll loop had just recorded for other tags. /// /// /// M3: a Degraded that a WRITE comms fault recorded (still the current health — same error, no read has /// replaced it since) is cleared back to Healthy: the device just accepted a write. A Degraded the read /// path recorded is left for the read path to clear. /// private void RecordWriteAnswered(DateTime now) => UpdateHealth(h => h.State == DriverState.Degraded && h.LastError is { } err && ReferenceEquals(err, Volatile.Read(ref _writeFaultError)) ? new DriverHealth(DriverState.Healthy, now, null) : h with { LastSuccessfulRead = now }); // The LastError string the most recent write-side comms fault wrote (reference identity marks "write-owned"). private string? _writeFaultError; /// A write-side comms fault: Degraded (never downgrading Faulted), LastSuccessfulRead preserved. private void RecordWriteCommsFault(string error) { var owned = new string(error.AsSpan()); // a distinct instance, so reference identity cannot alias a read error Volatile.Write(ref _writeFaultError, owned); UpdateHealth(h => h.State == DriverState.Faulted ? h : new DriverHealth(DriverState.Degraded, h.LastSuccessfulRead, owned)); } /// /// Read-modify-write one bit within an integer parent (SINT / INT / DINT / LINT — Logix allows .n on /// each). Creates / reuses a parallel parent runtime (distinct from the bit-selector handle) + serialises /// concurrent writers against the same parent via a per-parent . The parent's /// width comes from the size its read returned (H17 — a hard-coded DINT decode threw OutOfBounds on an INT /// host and was reported as a comms fault). Matches the Modbus BitInRegister + FOCAS PMC Bit pattern. /// private async Task WriteBitInDIntAsync( DeviceState device, AbCipTagPath bitPath, int bit, object? value, CancellationToken ct) { var parentPath = bitPath with { BitIndex = null }; var parentName = parentPath.ToLibplctagName(); var rmwLock = device.GetRmwLock(parentName); await rmwLock.WaitAsync(ct).ConfigureAwait(false); try { var parentRuntime = await EnsureParentRuntimeAsync(device, parentName, ct).ConfigureAwait(false); await parentRuntime.ReadAsync(ct).ConfigureAwait(false); var readStatus = parentRuntime.GetStatus(); if (readStatus != 0) return BitWriteStatusWord(device, parentName, readStatus, "read"); // Unsigned at the narrow widths so a set top bit (SINT bit 7, INT bit 15) encodes without overflowing the // signed type; DINT keeps its signed int arithmetic (1 << 31 is int.MinValue, which a DINT encodes as is). var size = parentRuntime.GetSize(); AbCipDataType? hostType = size switch { 1 => AbCipDataType.USInt, 2 => AbCipDataType.UInt, 8 => AbCipDataType.LInt, 4 or <= 0 => AbCipDataType.DInt, // <= 0: the runtime cannot say — the historical DINT assumption _ => null, }; if (hostType is not { } type) { WarnTypeMismatchOnce(parentName, "AbCip bit write to {Parent}.{Bit} on device {Device} refused: the parent is {Size} byte(s), not an integer host (logged once per tag)", parentName, bit, device.Options.HostAddress, size); return AbCipStatusMapper.BadTypeMismatch; } var widthBits = type switch { AbCipDataType.USInt => 8, AbCipDataType.UInt => 16, AbCipDataType.LInt => 64, _ => 32 }; if (bit >= widthBits) { WarnTypeMismatchOnce(parentName, "AbCip bit write to {Parent}.{Bit} on device {Device} refused: the parent holds only {Bits} bits (logged once per tag)", parentName, bit, device.Options.HostAddress, widthBits); return AbCipStatusMapper.BadOutOfRange; } var set = Convert.ToBoolean(value); var decoded = parentRuntime.DecodeValue(type, bitIndex: null) ?? 0; object updated; if (type == AbCipDataType.LInt) { var current = Convert.ToInt64(decoded); updated = set ? current | (1L << bit) : current & ~(1L << bit); } else { var mask = type switch { AbCipDataType.USInt => 0xFF, AbCipDataType.UInt => 0xFFFF, _ => -1 }; var current = Convert.ToInt32(decoded) & mask; updated = (set ? current | (1 << bit) : current & ~(1 << bit)) & mask; } parentRuntime.EncodeValue(type, bitIndex: null, updated); await parentRuntime.WriteAsync(ct).ConfigureAwait(false); var writeStatus = parentRuntime.GetStatus(); return writeStatus == 0 ? AbCipStatusMapper.Good : BitWriteStatusWord(device, parentName, writeStatus, "write"); } finally { rmwLock.Release(); } } /// /// M1: a non-zero status word on the bit write's parent read / write follows the health contract — a device /// refusal is per-tag Bad with one Warning and no state change (it answered: LastSuccessfulRead advances); any /// other status is a comms fault: evict the PARENT runtime and write Degraded (LastSuccessfulRead preserved). /// private uint BitWriteStatusWord(DeviceState device, string parentName, int status, string phase) { var mapped = AbCipStatusMapper.MapStatus(status); if (AbCipRefusals.IsDeviceRefusal(status)) { RecordWriteAnswered(DateTime.UtcNow); WarnRefusalOnce(parentName, $"bit-write parent {phase}", parentName, device.Options.HostAddress, ((AbStatus)status).ToString()); return mapped; } EvictParentRuntime(device, parentName); RecordWriteCommsFault($"transport status {status} on the bit-write parent {phase} of {parentName}"); _logger.LogWarning( "AbCip bit-write parent {Phase} of {Parent} on device {Device} returned transport status {Status}; evicting the parent runtime", phase, parentName, device.Options.HostAddress, status); return mapped; } /// /// Get or lazily create a parent-DINT runtime for a parent tag path, cached per-device /// so repeated bit writes against the same DINT share one handle. /// private async Task EnsureParentRuntimeAsync( DeviceState device, string parentTagName, CancellationToken ct) { if (device.ParentRuntimes.TryGetValue(parentTagName, out var existing)) return existing; ThrowIfRetired(device); var runtime = _tagFactory.Create(device.BuildCreateParams(parentTagName, _options.Timeout)); try { await runtime.InitializeAsync(ct).ConfigureAwait(false); } catch { runtime.Dispose(); throw; } // Two concurrent callers can both miss the cache + both initialize a runtime; only the // first TryAdd wins. Dispose the loser so it doesn't leak a native tag handle. if (!device.ParentRuntimes.TryAdd(parentTagName, runtime)) { runtime.Dispose(); return device.ParentRuntimes[parentTagName]; } Interlocked.MemoryBarrier(); // pairs with DeviceState.Retire if (device.Retired) { if (device.ParentRuntimes.TryRemove(parentTagName, out var orphan)) orphan.Dispose(); ThrowIfRetired(device); } return runtime; } /// Throws when a teardown has retired (a reader raced a re-init / shutdown). private static void ThrowIfRetired(DeviceState device) { if (device.Retired) throw new ObjectDisposedException(nameof(DeviceState), $"AbCip device {device.Options.HostAddress} was retired by a re-initialization or shutdown."); } /// /// Thrown when a per-device window is still open /// — a fail-fast that costs no wire traffic. Read/write map it to BadCommunicationError /// via their generic catch, exactly as a real Forward-Open failure. /// private sealed class ConnectionThrottledException(string message) : Exception(message); /// /// Idempotently materialise the runtime handle for a tag definition. First call creates /// + initialises the libplctag Tag; subsequent calls reuse the cached handle for the /// lifetime of the device. /// /// /// The COLD path (no cached handle) runs single-flight per device under /// so the backoff check, the Forward-Open, and the /// failure/success record form one atomic sequence — see that property for why. The HOT path /// (cached handle) never touches the gate, so the bounded-parallel read window is undiminished /// in steady state. /// private async Task EnsureTagRuntimeAsync( DeviceState device, AbCipTagDefinition def, CancellationToken ct) { if (device.Runtimes.TryGetValue(def.Name, out var existing)) return existing; var parsed = AbCipTagPath.TryParse(def.TagPath) ?? throw new AbCipTagConfigurationException( $"AbCip tag '{def.Name}' has malformed TagPath '{def.TagPath}'."); await device.ConnectGate.WaitAsync(ct).ConfigureAwait(false); try { // Re-check under the gate: a sibling cold tag may have connected (or a concurrent write // may have materialised this very handle) while this caller waited. if (device.Runtimes.TryGetValue(def.Name, out var raced)) return raced; ThrowIfRetired(device); // Inside an open backoff window a data-path caller fails fast — no runtime // create, no Forward-Open. The malformed-path config error above still surfaces (a permanent // fault must never be masked by the window); only the expensive create+init is throttled. The // probe loop uses its own runtime, and records under this same gate. if (!device.Backoff.ShouldAttempt(DateTime.UtcNow)) throw new ConnectionThrottledException( $"AbCip runtime create for '{def.Name}' on {device.Options.HostAddress} throttled — backoff window open after a recent Forward-Open failure."); // Review I-1 — an array tag (the EXPLICIT IsArray flag, incl. a 1-element array) sets // libplctag's elem_count so the read pulls every element in one CIP transaction; the read // path then boxes them into a typed CLR array. Scalar tags pass count 1 + IsArray false. var runtime = _tagFactory.Create( device.BuildCreateParams( parsed.ToLibplctagName(), _options.Timeout, def.ElementCount, IsArrayTag(def), authoredType: def.DataType)); try { await runtime.InitializeAsync(ct).ConfigureAwait(false); } catch (AbTransportException ate) when (ate.Status == AbStatus.TypeMismatch) { // The controller ANSWERED with a type refusal — the tag exists and the session // works. Keep the handle (disposing it re-creates it, and for a sole lease holder // re-Forward-Opens, on every poll) and let the caller report BadTypeMismatch. The native // runtime completes its initialization instead of throwing this; the cache keeps any runtime // that does throw it from churning. device.Backoff.RecordSuccess(); if (!device.Runtimes.TryAdd(def.Name, runtime)) runtime.Dispose(); throw; } catch (Exception ex) when (ex is AbCipTagConfigurationException or AbCipLocalRefusalException) { // The tag's own name cannot become a request, or the library refused the tag locally — no I/O happened, // so it says nothing about the device: leave the backoff window exactly as it was. runtime.Dispose(); throw; } catch (Exception ex) { runtime.Dispose(); // A failed create opens the backoff window — but only when the device did // not answer. "Tag not found" means the controller replied over a working session; it // is a config error on this one tag, and counting it as a failed Forward-Open throttled // every sibling tag on the device (seen live: one typo blacked out the whole device). if (AbCipRefusals.IsDeviceRefusal(ex)) device.Backoff.RecordSuccess(); else device.Backoff.RecordFailure(DateTime.UtcNow); throw; } device.Backoff.RecordSuccess(); // Forward-Open succeeded — reset the window // The gate makes a cold create single-flight, but a concurrent EvictRuntime (a failed read // on this handle) can still land between the re-check and the add; only the first TryAdd // wins. Dispose the loser so it doesn't leak a native tag handle. if (!device.Runtimes.TryAdd(def.Name, runtime)) { runtime.Dispose(); return device.Runtimes[def.Name]; } // A teardown that retired this state while we created would never see this handle: take it back out // (TryRemove — exactly one of us disposes it) rather than leak it into a dead table. Interlocked.MemoryBarrier(); // pairs with DeviceState.Retire if (device.Retired) { if (device.Runtimes.TryRemove(def.Name, out var orphan)) orphan.Dispose(); ThrowIfRetired(device); } return runtime; } finally { device.ConnectGate.Release(); } } /// /// Evict the runtime for from the device's cache and dispose /// it so the next read/write call re-creates and re-initializes a fresh handle. /// Called from , , and /// after a non-zero transport status or transport exception — /// mirroring the probe loop's recreate-on-failure behaviour. /// private static void EvictRuntime(DeviceState device, string tagName) { if (device.Runtimes.TryRemove(tagName, out var stale)) { try { stale.Dispose(); } catch { } } } /// Evicts + disposes a bit-write parent runtime so the next read-modify-write re-creates it. private static void EvictParentRuntime(DeviceState device, string parentName) { if (device.ParentRuntimes.TryRemove(parentName, out var stale)) { try { stale.Dispose(); } catch { } } } /// public DriverHealth GetHealth() => _health; // ---- ITagDiscovery ---- /// public DiscoveryRediscoverPolicy RediscoverPolicy => DiscoveryRediscoverPolicy.Once; // Controller enumeration is real (CIP Symbol Object walk) - config-gated on // EnableControllerBrowse, which the universal browser's PatchForBrowse guarantees at open time. /// public bool SupportsOnlineDiscovery => true; /// public async Task DiscoverAsync(IAddressSpaceBuilder builder, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(builder); var root = builder.Folder("AbCip", "AbCip"); foreach (var device in _options.Devices) { var deviceLabel = device.DeviceName ?? device.HostAddress; var deviceFolder = root.Folder(device.HostAddress, deviceLabel); // Pre-declared tags — always emitted; the primary config path. UDT tags with declared // Members fan out into a sub-folder + one Variable per member instead of a single // Structure Variable (Structure has no useful scalar value + member-addressable paths // are what downstream consumers actually want). A tag reaches this device when its // device routing key matches the device's DeviceName or its host address. var preDeclared = _declaredTags.Where(t => RoutesToDevice(t, device)); foreach (var tag in preDeclared) { if (AbCipSystemTagFilter.IsSystemTag(tag.Name)) continue; if (tag.DataType == AbCipDataType.Structure && tag.Members is { Count: > 0 }) { var udtFolder = deviceFolder.Folder(tag.Name, tag.Name); foreach (var member in tag.Members) { var memberFullName = $"{tag.Name}.{member.Name}"; // Review I-1 — array-ness is the EXPLICIT IsArray flag (a 1-element array is // still an array); a legacy member with ElementCount > 1 but the flag unset // remains an array for back-compat. var memberIsArray = member.IsArray || member.ElementCount > 1; udtFolder.Variable(member.Name, member.Name, new DriverAttributeInfo( FullName: memberFullName, DriverDataType: member.DataType.ToDriverDataType(), IsArray: memberIsArray, ArrayDim: memberIsArray ? (uint)Math.Max(1, member.ElementCount) : null, SecurityClass: member.Writable ? SecurityClassification.Operate : SecurityClassification.ViewOnly, IsHistorized: false, IsAlarm: false, WriteIdempotent: member.WriteIdempotent, NativeDataType: member.DataType.ToString())); } continue; } deviceFolder.Variable(tag.Name, tag.Name, ToAttributeInfo(tag)); } // Controller-discovered tags — opt-in via EnableControllerBrowse. The real @tags // walker (SymbolListingEnumerator) is the factory default, // so leaving the flag off keeps the strict-config path for deployments where only // declared tags should appear. if (_options.EnableControllerBrowse && _devices.TryGetValue(device.HostAddress, out var state)) { using var enumerator = _enumeratorFactory.Create(); var deviceParams = state.BuildCreateParams("@tags", _options.Timeout); // One template-reader lease across every UDT shape this device's browse fetches. using var batchReader = _templateReaderFactory.CreateBatch(); _batchTemplateReader.Value = batchReader; using var clearBatch = new ClearOnDispose(_batchTemplateReader); IAddressSpaceBuilder? discoveredFolder = null; // Dedup discovered member full-names within this device's Discovered folder. var emitted = new HashSet(StringComparer.OrdinalIgnoreCase); await foreach (var discovered in enumerator.EnumerateAsync(deviceParams, cancellationToken) .ConfigureAwait(false)) { if (discovered.IsSystemTag) continue; if (AbCipSystemTagFilter.IsSystemTag(discovered.Name)) continue; discoveredFolder ??= deviceFolder.Folder("Discovered", "Discovered"); var fullName = discovered.ProgramScope is null ? discovered.Name : $"Program:{discovered.ProgramScope}.{discovered.Name}"; // A discovered UDT/struct is expanded into a member sub-folder with one Variable // per ATOMIC leaf (mirroring the pre-declared fan-out above), rather than the // bogus single Structure → String placeholder Variable. When the shape can't be // resolved (or yields no emittable leaf) we fall through to the legacy single // Variable so nothing regresses. // Review I-1 — a discovered array of length 1 is still an array; honour the // explicit IsArray flag (legacy ElementCount > 1 still surfaces as an array). var discoveredIsArray = discovered.IsArray || discovered.ElementCount > 1; var discoveredType = discovered.DataType; if (discovered.DataType == AbCipDataType.Structure) { // Pass the discovered tag's CIP template instance id (surfaced by the Symbol // Object decoder) so ResolveDiscoveredUdtShapeAsync can fetch the Template Object // off the controller via FetchUdtShapeAsync — this is what makes the production // top-level UDT fan-out functional (rather than degrading to a placeholder). var shape = await ResolveDiscoveredUdtShapeAsync( device.HostAddress, discovered.Name, discovered.TemplateInstanceId, cancellationToken) .ConfigureAwait(false); if (shape is { IsStringFamily: true }) { // A controller reports every STRING (built-in or a user string type such as // STR0016) as a LEN + DATA struct. It is one String value — the read path reads // it as such — so it becomes one String Variable, never a LEN/DATA folder. discoveredType = AbCipDataType.String; } else if (shape is not null && !discoveredIsArray) { // Materialise the member sub-folder LAZILY — only once a leaf is actually // about to be emitted into it. A shape that yields no usable atomic leaf // then leaves no empty sub-folder behind, and we fall through to the legacy // single Variable below. var capturedDiscoveredFolder = discoveredFolder; var udtFolder = new Lazy( () => capturedDiscoveredFolder.Folder(fullName, discovered.Name)); var anyEmitted = await FanOutDiscoveredUdtMembersAsync( udtFolder, device.HostAddress, fullName, shape, discovered.ReadOnly, depth: 1, emitted, visited: [discovered.Name], cancellationToken) .ConfigureAwait(false); if (anyEmitted) continue; // expanded — don't emit the placeholder Variable // Empty shape (no usable atomic leaf): degrade to a single Variable below. } } if (!emitted.Add(fullName)) continue; discoveredFolder.Variable(fullName, discovered.Name, new DriverAttributeInfo( FullName: fullName, DriverDataType: discoveredType.ToDriverDataType(), IsArray: discoveredIsArray, ArrayDim: discoveredIsArray ? (uint)Math.Max(1, discovered.ElementCount) : null, SecurityClass: discovered.ReadOnly ? SecurityClassification.ViewOnly : SecurityClassification.Operate, IsHistorized: false, IsAlarm: false, WriteIdempotent: false, NativeDataType: discoveredType.ToString())); } } } } /// Clears an when the scope that set it ends. private sealed class ClearOnDispose(AsyncLocal slot) : IDisposable { /// public void Dispose() => slot.Value = null; } /// /// true for a UDT member the controller generates rather than the user declares: the /// hidden SINT/DINT hosts Logix packs BOOL members into (ZZZZZZZZZZAlarms0) and AOI /// backing members (__BitHost00). A user-declared Logix name can never begin with two /// underscores, so neither rule can hide a real member. /// /// The member name from the template. /// true when the member is controller-generated. internal static bool IsHiddenUdtMember(string memberName) => memberName.StartsWith("ZZZZZZZZZZ", StringComparison.Ordinal) || memberName.StartsWith("__", StringComparison.Ordinal); /// /// Wire width of a scalar atomic Logix type, or null where the read buffer's size is not /// a reliable type check (BOOL, STRING, DT, structures). /// /// The authored type. /// The width in bytes, or null. internal static int? ExpectedScalarWidth(AbCipDataType type) => type switch { AbCipDataType.SInt or AbCipDataType.USInt => 1, AbCipDataType.Int or AbCipDataType.UInt => 2, AbCipDataType.DInt or AbCipDataType.UDInt or AbCipDataType.Real => 4, AbCipDataType.LInt or AbCipDataType.ULInt or AbCipDataType.LReal => 8, _ => null, }; /// /// Bytes one scalar write of encodes: the read-side width, plus BOOL (one byte — /// a Logix BOOL tag or UDT BIT member reads back as one byte, type 0xC1). null where the encoded /// size is not fixed (STRING, DT, structures). /// /// The authored type. /// The width in bytes, or null. internal static int? ExpectedScalarWriteWidth(AbCipDataType type) => type == AbCipDataType.Bool ? 1 : ExpectedScalarWidth(type); /// /// The refusal status for a scalar write whose authored type does not fit what the controller /// holds at that path ( bytes, from the runtime's last read), or null to /// write. A BOOL over a wider value (a packed BOOL-array DWORD) is BadNotSupported — writing it /// would clobber the neighbouring bits, the same refusal the native runtime raises; any other width /// mismatch is BadTypeMismatch. Arrays, bit selectors (Flags.3, served by the /// read-modify-write path) and an unknown size (<= 0) are not judged here. /// /// A BOOL over a wider value is left to the runtime when it can see the CIP type /// ( — the native transport): it tells a packed BOOL-array DWORD /// (0xD3, BadNotSupported) from a mistyped integer member (BadTypeMismatch, the /// same verdict as its read), and refuses both before sending. libplctag exposes only the size, so the /// two are indistinguishable there and both get the safe BadNotSupported. /// /// /// The tag being written. /// The parsed bit selector, if any. /// The runtime's read-buffer size in bytes. /// The runtime checks a BOOL write against the controller's CIP type itself. /// The refusal status, or null. internal static uint? WriteWidthRefusal(AbCipTagDefinition def, int? bitIndex, int size, bool runtimeTypesBool = false) { if (IsArrayTag(def) || bitIndex is not null || size <= 0) return null; if (ExpectedScalarWriteWidth(def.DataType) is not { } width || size == width) return null; if (def.DataType == AbCipDataType.Bool && runtimeTypesBool) return null; return def.DataType == AbCipDataType.Bool ? AbCipStatusMapper.BadNotSupported : AbCipStatusMapper.BadTypeMismatch; } /// /// The refusal for a whole-array write whose authored shape does not fit what the controller holds: the last /// read returned bytes, which must be the element width × the element count. Unknown /// size (<= 0) is not judged here (the native runtime re-checks against the controller's type code). /// /// The array tag being written. /// The runtime's read-buffer size in bytes. /// BadTypeMismatch, or null to write. internal static uint? ArrayWriteWidthRefusal(AbCipTagDefinition def, int size) { if (size <= 0 || AbCipArrayCodec.ElementWidth(def.DataType) is not { } width) return null; return size == width * Math.Max(1, def.ElementCount) ? null : AbCipStatusMapper.BadTypeMismatch; } /// /// Recursively fan a controller-discovered UDT shape out into Variable nodes — one per /// ATOMIC leaf — under the folder produced by . Mirrors the /// pre-declared UDT fan-out (member full-name = Parent.Member, dot-joined for nested /// structs; atomic DriverDataType; SecurityClass from writability; /// IsHistorized:false, IsAlarm:false). Atomic members emit directly; a /// nested-struct member recurses into ITS members. Bounded by /// (deeper members are dropped) and a per-path set (cyclic struct /// references can't loop). A nested struct whose sub-shape can't be resolved is dropped — /// never mis-emitted as a placeholder. /// /// /// The is a so the sub-folder node is /// materialised only once a leaf is actually about to be emitted into it. A shape (or nested /// sub-shape) that yields no emittable leaf therefore never leaves an empty sub-folder in the /// browse tree. /// /// Lazy producer of the address-space sub-folder the member Variables are /// emitted under; only forced when the first leaf is emitted. /// The device the UDT lives on (for nested sub-shape lookup). /// Dotted full-name prefix of the parent (e.g. Motor1 or /// Motor1.Status). /// The resolved shape whose members are fanned out. /// Whether the discovered parent tag was read-only (propagated to /// members — the Symbol Object carries no per-member access bits). /// Current recursion depth (the parent's direct members are depth 1). /// Dedup set of member full-names already emitted in this Discovered folder. /// Struct names on the current recursion path (cycle guard). /// Cancellation token for any nested sub-shape read. /// true when at least one atomic leaf was emitted. private async Task FanOutDiscoveredUdtMembersAsync( Lazy folder, string deviceHostAddress, string parentFullName, AbCipUdtShape shape, bool parentReadOnly, int depth, HashSet emitted, HashSet visited, CancellationToken cancellationToken) { // Defensive: the only caller already gates each descent on depth + 1 <= MaxUdtDepth, so a // depth past the cap can't be reached here — kept as a belt-and-suspenders guard. if (depth > MaxUdtDepth) return false; var anyEmitted = false; foreach (var member in shape.Members) { if (IsHiddenUdtMember(member.Name)) continue; var memberFullName = $"{parentFullName}.{member.Name}"; var leafType = member.DataType; if (member.DataType == AbCipDataType.Structure) { // Nested struct: resolve its sub-shape first. The decoded parent shape carries the nested // UDT's template instance id (low 12 bits of the member type word, captured by // CipTemplateObjectDecoder) — thread it so the nested shape is fetched off the controller // via FetchUdtShapeAsync (name-keyed seeded shapes still win first, for the test seam). var nested = await ResolveDiscoveredUdtShapeAsync( deviceHostAddress, member.Name, templateInstanceId: member.NestedTemplateId, cancellationToken) .ConfigureAwait(false); if (nested is { IsStringFamily: true }) { // A nested STRING (or user string type) member is one String leaf, not LEN + DATA. leafType = AbCipDataType.String; } else { // An array of a UDT has no element-free member path (Parent.Arr.X names no element), // so it is not recursed into. Otherwise recurse if the depth cap allows it and we're // not re-entering a struct already on this path (cycle guard). The nested members // live a level deeper, so the cap is checked against depth + 1. if (member.ArrayLength > 1) continue; if (depth + 1 > MaxUdtDepth) continue; if (!visited.Add(member.Name)) continue; // cyclic UDT reference — stop here if (nested is not null) { // Materialise the nested sub-folder lazily under the parent folder (itself lazy), // so a nested struct that yields no leaf leaves no empty sub-folder behind. var parentFolder = folder; var nestedFolder = new Lazy( () => parentFolder.Value.Folder(memberFullName, member.Name)); var nestedEmitted = await FanOutDiscoveredUdtMembersAsync( nestedFolder, deviceHostAddress, memberFullName, nested, parentReadOnly, depth + 1, emitted, visited, cancellationToken) .ConfigureAwait(false); anyEmitted |= nestedEmitted; } visited.Remove(member.Name); continue; } } // Atomic leaf — emit one Variable. Dedup by full-name within the Discovered folder. // Forcing folder.Value here is what materialises the sub-folder on the first real leaf. if (!emitted.Add(memberFullName)) continue; var memberIsArray = member.ArrayLength > 1; folder.Value.Variable(member.Name, member.Name, new DriverAttributeInfo( FullName: memberFullName, DriverDataType: leafType.ToDriverDataType(), IsArray: memberIsArray, ArrayDim: memberIsArray ? (uint)Math.Max(1, member.ArrayLength) : null, // The Symbol Object carries no per-member ExternalAccess bits, so members inherit the // parent tag's read-only state (a safety/read-only UDT keeps all its members ViewOnly). SecurityClass: parentReadOnly ? SecurityClassification.ViewOnly : SecurityClassification.Operate, IsHistorized: false, IsAlarm: false, WriteIdempotent: false, NativeDataType: leafType.ToString())); anyEmitted = true; } return anyEmitted; } // Review I-1 — array-ness is the EXPLICIT IsArray flag (a 1-element array is still an array); // a legacy definition carrying only ElementCount > 1 stays an array for back-compat. private static bool IsArrayTag(AbCipTagDefinition tag) => tag.IsArray || tag.ElementCount > 1; // A tag routes to a device when its device routing key (DeviceHostAddress, threaded from the // RawTagEntry.DeviceName) matches the device's DeviceName or its host address (the host alias is // deliberate: the Client CLI routes by host). private static bool RoutesToDevice(AbCipTagDefinition tag, AbCipDeviceOptions device) => string.Equals(tag.DeviceHostAddress, device.HostAddress, StringComparison.OrdinalIgnoreCase) || (!string.IsNullOrEmpty(device.DeviceName) && string.Equals(tag.DeviceHostAddress, device.DeviceName, StringComparison.OrdinalIgnoreCase)); private static DriverAttributeInfo ToAttributeInfo(AbCipTagDefinition tag) => new( FullName: tag.Name, DriverDataType: tag.DataType.ToDriverDataType(), IsArray: IsArrayTag(tag), ArrayDim: IsArrayTag(tag) ? (uint)Math.Max(1, tag.ElementCount) : null, SecurityClass: (tag.Writable && !tag.SafetyTag) ? SecurityClassification.Operate : SecurityClassification.ViewOnly, IsHistorized: false, IsAlarm: false, WriteIdempotent: tag.WriteIdempotent, NativeDataType: tag.DataType.ToString()); /// Count of registered devices — exposed for diagnostics + tests. internal int DeviceCount => _devices.Count; /// Looked-up device state for the given host address. Tests + later-PR capabilities hit this. /// The host address of the device to look up. /// The device state if found; null otherwise. internal DeviceState? GetDeviceState(string hostAddress) => _devices.TryGetValue(hostAddress, out var s) ? s : null; /// /// Asynchronously releases all resources used by the driver — the same complete teardown as /// . Idempotent, and safe CONCURRENTLY with a still-running /// (the runtime's final stop abandons a shutdown that overruns its budget and /// disposes anyway): each teardown retires a disjoint device table. This is the dispose the runtime calls /// (it prefers ). /// /// A value task representing the asynchronous disposal. public async ValueTask DisposeAsync() { await ShutdownAsync(CancellationToken.None).ConfigureAwait(false); } /// /// Starts the same teardown as WITHOUT blocking the calling thread on it (review /// 07 F10: the old DisposeAsync().AsTask().GetAwaiter().GetResult() parked the caller — a dispatcher /// thread — for up to the probe join, with the usual sync-over-async deadlock exposure). The teardown runs to /// completion in the background and any fault is logged. Callers that need completion use /// ; kept only for synchronous using / Dispose() call sites. /// public void Dispose() { var teardown = DisposeAsync().AsTask(); if (teardown.IsCompleted) { teardown.GetAwaiter().GetResult(); return; } _ = teardown.ContinueWith( t => _logger.LogWarning(t.Exception, "AbCip driver {DriverInstanceId}: background dispose failed", _driverInstanceId), CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); } /// /// Per-device runtime state. Holds the parsed host address, family profile, and the /// live libplctag.NET instances keyed by tag name. /// Native tag lifetime is owned by the Tag.Dispose() inside each /// ; libplctag.NET's own finalizer covers GC-collected /// instances so no separate SafeHandle wrapper is needed here. /// internal sealed class DeviceState( AbCipHostAddress parsedAddress, AbCipDeviceOptions options, AbCipPlcFamilyProfile profile) { /// Gets the parsed host address for this device. public AbCipHostAddress ParsedAddress { get; } = parsedAddress; /// Gets the configuration options for this device. public AbCipDeviceOptions Options { get; } = options; /// Gets the PLC family profile for this device. public AbCipPlcFamilyProfile Profile { get; } = profile; /// Gets the lock object used for probe synchronization. public object ProbeLock { get; } = new(); /// /// Per-device connect-attempt throttle. After a failed runtime create /// (Forward-Open), data-path callers fail fast inside the backoff window instead of /// re-creating + re-initializing a runtime per tag per tick; the probe loop bypasses it /// (its own runtime) and drives failure/success so a recovered device resets the window. /// public ConnectionBackoff Backoff { get; } = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30)); /// /// Per-device connect gate. is documented as /// caller-serialized — it mutates plain fields — so EVERY touch of /// plus the connect attempt it guards runs under this semaphore. The bounded-parallel /// read window otherwise let up to MaxConcurrentReads work items run the /// ShouldAttempt → create+Initialize → RecordFailure/RecordSuccess sequence at once for /// DIFFERENT cold tags on the SAME device: every one passed ShouldAttempt before any /// failure was recorded (N concurrent Forward-Opens at a down device) and the unsynchronized /// _consecutiveFailures++ lost increments, weakening the backoff window into a /// reconnect storm. Cold-tag creation is therefore single-flight per device; an /// already-created runtime bypasses the gate entirely, so the steady-state read path keeps /// the full window. /// /// Deliberately NOT disposed in , unlike the per-tag gates: /// the probe loop also waits on it, and 's wait /// for that loop is bounded (10 s), so disposal could race a still-unwinding probe into /// an . A whose /// AvailableWaitHandle was never touched holds no unmanaged resource, and the /// whole is dropped on reinitialize. /// /// public SemaphoreSlim ConnectGate { get; } = new(1, 1); /// Gets or sets the current host state of this device. public HostState HostState { get; set; } = HostState.Unknown; /// Gets or sets the UTC timestamp when the host state was last changed. public DateTime HostStateChangedUtc { get; set; } = DateTime.UtcNow; /// Gets or sets the cancellation token source for the probe loop. public CancellationTokenSource? ProbeCts { get; set; } /// Gets or sets whether the probe has been initialized. public bool ProbeInitialized { get; set; } /// 1 once the probe-tag refusal Warning has been logged for this device state. public int ProbeRefusalWarned; /// /// The fire-and-forget probe loop's . Stored so /// can await the loop's clean exit after /// cancelling and BEFORE disposing the CTS or the runtime /// handles — otherwise the still-running loop can touch a disposed CTS or a cleared /// runtime dictionary. /// public Task? ProbeTask { get; set; } /// /// Per-tag runtime handles owned by this device. One entry per configured tag is /// created lazily on first read (see ). /// /// because ReadAsync is invoked concurrently by the server read path, every /// polled subscription loop, and the alarm projection loop. /// public System.Collections.Concurrent.ConcurrentDictionary Runtimes { get; } = new(StringComparer.OrdinalIgnoreCase); /// /// Parent-DINT runtimes created on-demand by /// for BOOL-within-DINT RMW writes. Separate from because a /// bit-selector tag name ("Motor.Flags.3") needs a distinct handle from the DINT /// parent ("Motor.Flags") used to do the read + write. /// public System.Collections.Concurrent.ConcurrentDictionary ParentRuntimes { get; } = new(StringComparer.OrdinalIgnoreCase); private readonly System.Collections.Concurrent.ConcurrentDictionary _rmwLocks = new(); /// Gets or creates a semaphore for coordinating RMW (read-modify-write) operations on a parent tag. /// The name of the parent tag. /// A semaphore for coordinating RMW operations. public SemaphoreSlim GetRmwLock(string parentTagName) => _rmwLocks.GetOrAdd(parentTagName, _ => new SemaphoreSlim(1, 1)); private readonly System.Collections.Concurrent.ConcurrentDictionary _runtimeLocks = new(StringComparer.OrdinalIgnoreCase); /// /// Per-runtime operation lock. A libplctag Tag handle is not safe for /// concurrent Read/GetStatus/DecodeValue (or Encode/Write/GetStatus) — the server read /// path, every poll-group loop, and the alarm-projection loop all call /// / against the /// same cached runtime, and GetStatus returns the last operation's status /// — so an unserialised overlap decodes a torn / cross-attributed value with Good status. /// Callers hold this lock around the whole op sequence. Keyed by tag name, which is also /// the dictionary key. Mirrors the field-proven AbLegacy pattern. /// /// The tag name (the key). /// The per-runtime operation semaphore. public SemaphoreSlim GetRuntimeLock(string tagName) => _runtimeLocks.GetOrAdd(tagName, _ => new SemaphoreSlim(1, 1)); /// /// Compute the effective for a /// tag on this device. Combines the per-device options /// (, /// ) with the family profile defaults /// so the wire layer sees one place that resolves both. /// /// The name of the tag to create parameters for. /// The timeout for tag operations. /// libplctag elem_count — 1 for a scalar tag, the array /// length for a 1-D array tag (Phase 4c). Coerced to a minimum of 1. /// Review I-1 — the EXPLICIT array signal threaded through so a /// 1-element array ( 1) is still read as an array. /// The tag definition's authored type, for the native runtime's /// returned-type check; null skips it. /// The computed tag creation parameters. public AbCipTagCreateParams BuildCreateParams( string tagName, TimeSpan timeout, int elementCount = 1, bool isArray = false, AbCipDataType? authoredType = null) => new( Gateway: ParsedAddress.Gateway, Port: ParsedAddress.Port, CipPath: ParsedAddress.CipPath, LibplctagPlcAttribute: Profile.LibplctagPlcAttribute, TagName: tagName, Timeout: timeout, AllowPacking: Options.AllowPacking ?? Profile.SupportsRequestPacking, ConnectionSize: Options.ConnectionSize ?? Profile.DefaultConnectionSize, ElementCount: elementCount < 1 ? 1 : elementCount, IsArray: isArray, AuthoredType: authoredType, UseConnectedMessaging: Profile.SupportsConnectedMessaging); private volatile bool _retired; /// /// True once a teardown retired this state. A reader that resolved the device just before the swap can /// still be running against it: its failures are the teardown's doing, not the device's (no Degraded), and a /// runtime it cold-creates afterwards is disposed by the creator instead of leaking into a dead table. /// public bool Retired => _retired; /// Marks the state retired, then disposes every runtime handle (see ). public void Retire() { _retired = true; // Dekker pairing with the creator's post-add check: the flag is globally visible before the tables are // enumerated, and the creator fences between its add and its read of the flag — so at least one of the two // sees the other's write and the handle is disposed. Interlocked.MemoryBarrier(); DisposeHandles(); } /// /// Disposes every runtime tag handle, each exactly once (removed before it is disposed, so a racing /// creator's own cleanup cannot dispose it a second time). The per-runtime / RMW gates are deliberately NOT /// disposed, for the same reason as : an in-flight reader of a retired state may /// still release one, and a only awaited asynchronously holds no wait handle. /// public void DisposeHandles() { foreach (var key in Runtimes.Keys) if (Runtimes.TryRemove(key, out var r)) r.Dispose(); foreach (var key in ParentRuntimes.Keys) if (ParentRuntimes.TryRemove(key, out var r)) r.Dispose(); } } }