using Microsoft.Extensions.Logging; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport; namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy; /// /// Adjacent-element read coalescing (review 07 P7): scalar tags on the same N / B / F / L data file whose /// elements are close together are read as ONE multi-element PCCC read (the same path array tags already use), /// then each tag is decoded from its offset in the block. One round trip instead of one per tag. /// /// /// Only shapes the single-tag path decodes identically are coalesced: a word tag /// (Int/AnalogInt) or a bit of a word (Bit, with or without /n) on an N or B file; a /// Float on an F file; a Long or a bit of a long on an L file. Indirect addresses, sub-elements /// (T4:0.ACC), arrays, the file-number-less system files (S:, I:, O:) and any tag /// authored with a type that does not match its file's element width keep the single-tag path, so a /// mis-authored tag still gets exactly the answer it got before. /// The span is safe to read. A block runs from its lowest to its highest member, so every element /// it reads lies between two authored elements of the same file — inside the file whenever the authored tags /// are. A device REFUSAL of a block (an authored element past the end of the file, a PLC-5 native non-N file) /// falls back to single reads for that block's members, so one bad tag never blackens its neighbours, and the /// block shape is remembered so it is not retried every poll. A comms fault fails the members together — they /// share the connection — exactly as their single reads would have. /// Turned off with the driver-config key coalesceReads: false. /// public sealed partial class AbLegacyDriver { /// Largest block, in data bytes. Below the 236-byte PCCC typed-read limit, so libplctag never needs /// to fragment a coalesced read (the native runtime would chunk it anyway). internal const int MaxCoalescedBytes = 200; /// Largest run of UNAUTHORED elements a block may read across to join two members. internal const int MaxCoalesceGap = 8; /// One unit of a device pass: a single tag, or a coalesced block of several. private sealed record ReadUnit(ReadItem? Single, CoalescedBlock? Block); /// A coalesced block: elements of one file from . private sealed record CoalescedBlock( string FileLetter, int FileNumber, int Start, int Count, AbLegacyDataType ElementType, List Members) { /// The runtime-cache key; distinct from any RawPath (RawPaths never contain '|'). public string Key => $"|block|{FileLetter}{FileNumber}:{Start}+{Count}"; /// The block's base address in libplctag form. public string StartName => $"{FileLetter}{FileNumber}:{Start}"; } /// /// The element type a scalar tag is decoded from when it rides a coalesced block, or /// when the tag keeps the single-tag path. /// private static AbLegacyDataType? CoalescedElementType(ReadItem item) { var a = item.Parsed; if (a.IsIndirect || a.SubElement is not null || a.FileNumber is null || IsArrayTag(item.Def)) return null; return (a.FileLetter, item.Def.DataType) switch { ("N" or "B", AbLegacyDataType.Int or AbLegacyDataType.AnalogInt or AbLegacyDataType.Bit) => AbLegacyDataType.Int, ("F", AbLegacyDataType.Float) => AbLegacyDataType.Float, ("L", AbLegacyDataType.Long) => AbLegacyDataType.Long, ("L", AbLegacyDataType.Bit) when a.BitIndex is not null => AbLegacyDataType.Long, _ => null, }; } /// /// Plans a device pass: coalescable tags grouped per file into runs of nearby elements (a run of two or more /// tags becomes a block), everything else a single unit. Block shapes the device refused before stay single. /// private List PlanReadUnits(DeviceState device, List items) { if (!_options.CoalesceReads || items.Count < 2) return [.. items.Select(i => new ReadUnit(i, null))]; var units = new List(items.Count); var groups = new Dictionary<(string Letter, int File, AbLegacyDataType Type), List>(); foreach (var item in items) { if (CoalescedElementType(item) is not { } type) { units.Add(new ReadUnit(item, null)); continue; } var key = (item.Parsed.FileLetter, item.Parsed.FileNumber!.Value, type); if (!groups.TryGetValue(key, out var list)) groups[key] = list = []; list.Add(item); } foreach (var ((letter, file, type), members) in groups) { var width = type == AbLegacyDataType.Int ? 2 : 4; var maxElements = MaxCoalescedBytes / width; var ordered = members.OrderBy(m => m.Parsed.WordNumber).ToList(); var run = new List { ordered[0] }; for (var i = 1; i <= ordered.Count; i++) { var next = i < ordered.Count ? ordered[i] : null; var start = run[0].Parsed.WordNumber; if (next is not null && next.Parsed.WordNumber - run[^1].Parsed.WordNumber <= MaxCoalesceGap + 1 && next.Parsed.WordNumber - start + 1 <= maxElements) { run.Add(next); continue; } var count = run[^1].Parsed.WordNumber - start + 1; var block = new CoalescedBlock(letter, file, start, count, type, run); if (run.Count < 2 || device.RefusedBlocks.ContainsKey(block.Key)) units.AddRange(run.Select(r => new ReadUnit(r, null))); else units.Add(new ReadUnit(null, block)); if (next is not null) run = [next]; } } return units; } /// What a block read concluded; = read the members singly instead. private enum BlockOutcome { Done, Fallback } /// /// Reads one coalesced block and decodes each member from its offset. A device refusal or a local refusal /// returns (and remembers the shape) without writing any member's result. /// private async Task<(BlockOutcome Outcome, OpVerdict Verdict, string? Message)> ReadBlockAsync( DeviceState device, CoalescedBlock block, DataValueSnapshot[] results, DateTime now, CancellationToken ct) { void FailAll(uint status) { foreach (var m in block.Members) results[m.Index] = new DataValueSnapshot(null, status, null, now); } (BlockOutcome, OpVerdict, string?) Refused(string why) { device.RefusedBlocks.TryAdd(block.Key, 0); _logger.LogInformation( "AbLegacy coalesced read {Block} refused ({Reason}); its {Count} tags read singly from now on. Driver={DriverInstanceId} Device={DeviceHostAddress}", block.StartName + "+" + block.Count, why, block.Members.Count, _driverInstanceId, device.Options.HostAddress); return (BlockOutcome.Fallback, OpVerdict.Neutral, null); } try { var createParams = new AbLegacyTagCreateParams( Gateway: device.ParsedAddress.Gateway, Port: device.ParsedAddress.Port, CipPath: device.EffectiveCipPath, LibplctagPlcAttribute: device.Profile.LibplctagPlcAttribute, TagName: block.StartName, Timeout: _options.Timeout, ElementCount: block.Count); var runtime = await CreateSingleFlightAsync( device, device.Runtimes, block.Key, () => _tagFactory.Create(createParams), ct).ConfigureAwait(false); int status; Array? data = null; var opLock = device.GetRuntimeLock(block.Key); await opLock.WaitAsync(ct).ConfigureAwait(false); try { await runtime.ReadAsync(ct).ConfigureAwait(false); status = runtime.GetStatus(); if (status == 0) data = runtime.DecodeArray(block.ElementType, block.Count) as Array; } finally { opLock.Release(); } if (status != 0) { if (IsDeviceRefusal((AbStatus)status) || (AbStatus)status == AbStatus.Unsupported) { EvictRuntime(device, block.Key); return Refused($"device status {(AbStatus)status}"); } EvictRuntime(device, block.Key); FailAll(AbLegacyStatusMapper.MapStatus(status)); return (BlockOutcome.Done, OpVerdict.Fault, $"transport status {status} reading {block.StartName}+{block.Count}"); } if (data is null || data.Length < block.Count) return Refused("the block decoded short"); foreach (var m in block.Members) results[m.Index] = new DataValueSnapshot(DecodeMember(block, m, data), AbLegacyStatusMapper.Good, now, now); device.FirstNonZeroStatusLogged = false; return (BlockOutcome.Done, OpVerdict.Answered, null); } catch (OperationCanceledException) { throw; } catch (ConnectionThrottledException tex) { FailAll(AbLegacyStatusMapper.BadCommunicationError); return (BlockOutcome.Done, OpVerdict.Throttled, tex.Message); } catch (AbTransportException ex) when (IsLocalRefusal(ex) || IsDeviceRefusal(ex.Status)) { EvictRuntime(device, block.Key); return Refused(ex.Message); } catch (NotSupportedException nse) { EvictRuntime(device, block.Key); return Refused(nse.Message); } catch (Exception ex) { EvictRuntime(device, block.Key); FailAll(AbLegacyStatusMapper.BadCommunicationError); return (BlockOutcome.Done, OpVerdict.Fault, ex.Message); } } /// /// Decodes one member from the block, returning exactly the CLR type and value the single-tag path's /// would (int for a word or long, float, bool). /// private static object DecodeMember(CoalescedBlock block, ReadItem m, Array data) { var offset = m.Parsed.WordNumber - block.Start; var bit = m.Parsed.BitIndex; switch (data) { case short[] words: { var w = words[offset]; return m.Def.DataType == AbLegacyDataType.Bit ? ((ushort)w >> (bit ?? 0) & 1) != 0 : (int)w; } case int[] longs: { var l = longs[offset]; return m.Def.DataType == AbLegacyDataType.Bit ? ((uint)l >> bit!.Value & 1) != 0 : l; } case float[] floats: return floats[offset]; default: throw new InvalidOperationException($"Unexpected block buffer {data.GetType().Name}."); } } }