Files
lmxopcua/src/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipUdtMemberLayout.cs
Joseph Doherty 780358c790 AbCip whole-UDT read optimization (#194) — declaration-driven member grouping collapses N per-member reads into one parent-UDT read + client-side decode. Closes task #194. On a batch that includes multiple members of the same hand-declared UDT tag, ReadAsync now issues one libplctag read on the parent + decodes each member from the runtime's buffer at its computed byte offset. A 6-member Motor UDT read goes from 6 libplctag round-trips to 1 — the Rockwell-suggested pattern for minimizing CIP request overhead on batch reads of UDT state (decision #11's follow-through on what the template decoder from task #179 was meant to enable). AbCipUdtMemberLayout is a pure-function helper that computes declared-member byte offsets under Logix natural-alignment rules (SInt 1-byte / Int 2-byte / DInt + Real + Dt 4-byte / LInt + ULInt + LReal 8-byte; alignment pad inserted before each member as needed). Opts out for BOOL / String / Structure members — BOOL storage in Logix UDTs packs into a hidden host byte whose position can't be computed from declaration-only info, and String members need length-prefix + STRING[82] fan-out which libplctag already handles via a per-tag DecodeValue path. The CIP Template Object shape from task #179 (when populated via FetchUdtShapeAsync) carries real offsets for those members — layering that richer path on top of the planner is a separate follow-up and does not change this PR's conservative behaviour. AbCipUdtReadPlanner is the scheduling function ReadAsync consults each batch — pure over (requests, tagsByName), emits Groups + Fallbacks. A group is formed when (a) the reference resolves to "parent.member"; (b) parent is a Structure tag with declared Members; (c) the layout helper succeeds on those members; (d) the specific member appears in the computed offset map; (e) at least two members of the same parent appear in the batch — single-member groups demote to the fallback path because one whole-UDT read vs one per-member read is equivalent cost but more client-side work. Original batch indices are preserved through the plan so out-of-order batches write decoded values back at the right output slot; the caller's result array order is invariant. IAbCipTagRuntime.DecodeValueAt(AbCipDataType, int offset, int? bitIndex) is the new hot-path method — LibplctagTagRuntime delegates to libplctag's offset-aware Get*(offset) calls (GetInt32, GetFloat32, etc.) that were always there; previously every call passed offset 0. DecodeValue(type, bitIndex) stays as the shorthand + forwards to DecodeValueAt with offset 0, preserving the existing single-tag read path + every test that exercises it. FakeAbCipTag gains a ValuesByOffset dictionary so tests can drive multi-member decoding by setting offset→value before the read fires; unmapped offsets fall back to the existing Value field so the 200+ existing tests that never set ValuesByOffset keep working unchanged. AbCipDriver.ReadAsync refactored: planner splits the batch, ReadGroupAsync handles each UDT group (one EnsureTagRuntimeAsync on the parent + one ReadAsync + N DecodeValueAt calls), ReadSingleAsync handles each fallback (the pre-#194 per-tag path, now extracted + threaded through). A per-group failure stamps the mapped libplctag status across every grouped member only — sibling groups + fallback refs are unaffected. Health-surface updates happen once per successful group rather than once per member to avoid ping-ponging the DriverState bookkeeping. Five AbCipUdtMemberLayoutTests: packed atomics get natural-alignment offsets including 8-byte pad before LInt; SInts pack without padding; BOOL/String/Structure opt out + return null; empty member list returns null. Six AbCipUdtReadPlannerTests: two members group; single-member demotes to fallback; unknown references fall back without poisoning groups; atomic top-level tags fall back untouched; UDTs containing BOOL don't group; original indices survive out-of-order batches. Five AbCipDriverWholeUdtReadTests (real driver + fake runtime): two grouped members trigger exactly one parent read + one fake runtime (proving the optimization engages); each member decodes at its own offset via ValuesByOffset; parent-read non-zero status stamps Bad across the group; mixed UDT-member + atomic top-level batch produces 2 runtimes + 2 reads (not 3); single-member-of-UDT still uses the member-level runtime (proving demotion works). Driver builds 0 errors; AbCip.Tests 227/227 (was 211, +16 new).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 04:17:57 -04:00

79 lines
3.5 KiB
C#

namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip;
/// <summary>
/// Computes byte offsets for declared UDT members under Logix natural-alignment rules so
/// a single whole-UDT read (task #194) can decode each member from one buffer without
/// re-reading per member. Declaration-driven — the caller supplies
/// <see cref="AbCipStructureMember"/> rows; this helper produces the offset each member
/// sits at in the parent tag's read buffer.
/// </summary>
/// <remarks>
/// <para>Alignment rules applied per Rockwell "Logix 5000 Data Access" manual + the
/// libplctag test fixtures: each member aligns to its natural boundary (SInt 1, Int 2,
/// DInt/Real/Dt 4, LInt/ULInt/LReal 8), padding inserted before the member as needed.
/// The total size is padded to the alignment of the largest member so arrays-of-UDT also
/// work at element stride — though this helper is used only on single instances today.</para>
///
/// <para><see cref="TryBuild"/> returns <c>null</c> on unsupported member types
/// (<see cref="AbCipDataType.Bool"/>, <see cref="AbCipDataType.String"/>,
/// <see cref="AbCipDataType.Structure"/>). Whole-UDT grouping opts out of those groups
/// and falls back to the per-tag read path — BOOL members are packed into a hidden host
/// byte at the top of the UDT under Logix, so their offset can't be computed from
/// declared-member order alone. The CIP Template Object reader produces a
/// <see cref="AbCipUdtShape"/> that carries real offsets for BOOL + nested structs; when
/// that shape is cached the driver can take the richer path instead.</para>
/// </remarks>
public static class AbCipUdtMemberLayout
{
/// <summary>
/// Try to compute member offsets for the supplied declared members. Returns <c>null</c>
/// if any member type is unsupported for declaration-only layout.
/// </summary>
public static IReadOnlyDictionary<string, int>? TryBuild(
IReadOnlyList<AbCipStructureMember> members)
{
ArgumentNullException.ThrowIfNull(members);
if (members.Count == 0) return null;
var offsets = new Dictionary<string, int>(members.Count, StringComparer.OrdinalIgnoreCase);
var cursor = 0;
foreach (var member in members)
{
if (!TryGetSizeAlign(member.DataType, out var size, out var align))
return null;
if (cursor % align != 0)
cursor += align - (cursor % align);
offsets[member.Name] = cursor;
cursor += size;
}
return offsets;
}
/// <summary>
/// Natural size + alignment for a Logix atomic type. <c>false</c> for types excluded
/// from declaration-only grouping (Bool / String / Structure).
/// </summary>
private static bool TryGetSizeAlign(AbCipDataType type, out int size, out int align)
{
switch (type)
{
case AbCipDataType.SInt: case AbCipDataType.USInt:
size = 1; align = 1; return true;
case AbCipDataType.Int: case AbCipDataType.UInt:
size = 2; align = 2; return true;
case AbCipDataType.DInt: case AbCipDataType.UDInt:
case AbCipDataType.Real: case AbCipDataType.Dt:
size = 4; align = 4; return true;
case AbCipDataType.LInt: case AbCipDataType.ULInt:
case AbCipDataType.LReal:
size = 8; align = 8; return true;
default:
size = 0; align = 0; return false;
}
}
}