Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT/TwinCATSumReadPlanner.cs
T
Joseph Doherty 826312befe docs: fill missing XML docs and strip tracking IDs from src comments
Clears CommentChecker findings in src/ (3,280 -> 209, the remainder being false
positives like PLC-5/IEEE-754/M0.0) by adding missing summaries/params/returns,
normalising inheritdoc usage, and removing Gitea/review tracking IDs while keeping
the rationale they annotated. Comment-only: comment-stripped sources are identical
to the parent commit.
2026-10-15 06:14:58 -04:00

114 lines
5.9 KiB
C#

using Beckhoff = TwinCAT.Ads;
namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT;
/// <summary>
/// The pure decisions behind an ADS sum-read, split out of
/// <see cref="AdsTwinCATClient"/> so they are unit-testable without an ADS connection: which items may
/// ride a sum command, how a poll is split to fit a request budget, which overall ADS codes mean what,
/// and how one item's raw block becomes a value.
/// </summary>
internal static class TwinCATSumReadPlanner
{
/// <summary>Hard ceiling on items per sum command (ADS documents roughly 500 sub-commands).</summary>
public const int MaxItemsCeiling = 500;
/// <summary>Per-command byte budget: the sum of the items' read lengths plus <see cref="PerItemOverhead"/> each.
/// Keeps a poll that includes large arrays inside a modest router / CE buffer.</summary>
public const int MaxBatchBytes = 32 * 1024;
/// <summary>Bytes of per-item ADS error code carried in a sum response.</summary>
public const int PerItemOverhead = 4;
/// <summary>
/// True when a SCALAR may be read as raw bytes in a sum command. The sum path decodes the bytes as the
/// DECLARED type, so it needs the strict width + float/integer-kind rule (the notification rule); the
/// lenient <see cref="TwinCATTypeGuard.CheckRead"/> relies on the Beckhoff value conversion a raw read
/// does not do. An item failing this but passing CheckRead must be read individually.
/// </summary>
/// <param name="declared">The tag's declared type.</param>
/// <param name="plc">The PLC symbol's shape.</param>
/// <returns>True when the raw-bytes decode is exact.</returns>
public static bool ScalarEligible(TwinCATDataType declared, TwinCATPlcSymbolShape plc) =>
TwinCATTypeGuard.CheckNotification(declared, plc) is null;
/// <summary>The service or index group itself is unsupported: the device never does sum commands. Latches.</summary>
/// <param name="adsError">The overall ADS code.</param>
/// <returns>True for 1793 (service not supported) and 1794 (invalid index group).</returns>
public static bool IsRefusal(uint adsError) => adsError is 1793 or 1794;
/// <summary>A transport-level failure (router / port / timeout), not an answer from the sum service.</summary>
/// <param name="adsError">The overall ADS code.</param>
/// <returns>True when the code maps to a communication error or timeout.</returns>
public static bool IsCommsFailure(uint adsError) =>
TwinCATStatusMapper.MapAdsError(adsError) is var s
&& (s == TwinCATStatusMapper.BadCommunicationError || s == TwinCATStatusMapper.BadTimeout);
/// <summary>
/// The sum service answered with an overall error that is neither "unsupported" nor a comms failure
/// (general error, bad size / data / offset, ...): it rejected THIS request. Read the chunk singly for this
/// poll, do not latch.
/// </summary>
/// <param name="adsError">The overall ADS code.</param>
/// <returns>True for any such code.</returns>
public static bool IsRequestRejected(uint adsError) => !IsRefusal(adsError) && !IsCommsFailure(adsError);
/// <summary>
/// Splits items (in order) into groups whose summed <c>length + PerItemOverhead</c> stays within
/// <paramref name="budget"/>. An item that alone exceeds the budget gets its own group (the caller reads a
/// one-item group individually).
/// </summary>
/// <param name="byteLengths">Each item's read length.</param>
/// <param name="budget">The byte budget per command.</param>
/// <returns>Groups of positions into <paramref name="byteLengths"/>.</returns>
public static List<List<int>> Partition(IReadOnlyList<int> byteLengths, int budget)
{
var groups = new List<List<int>>();
List<int>? current = null;
var used = 0;
for (var i = 0; i < byteLengths.Count; i++)
{
var cost = byteLengths[i] + PerItemOverhead;
if (current is null || used + cost > budget)
{
current = [];
groups.Add(current);
used = 0;
}
current.Add(i);
used += cost;
}
return groups;
}
/// <summary>
/// Turns one item's sum-response slice into a value. A per-item ADS error maps to its status; a missing or
/// short block (a target answering with less than was asked for) is a size error for that item only.
/// </summary>
/// <param name="type">The declared type.</param>
/// <param name="subError">The item's ADS error code (0 = none).</param>
/// <param name="block">The item's bytes, or null when the response had none.</param>
/// <param name="layout">The planned layout (a scalar is one element).</param>
/// <param name="isArray">True to return the whole array, false for element 0.</param>
/// <param name="utf8">True when the target's STRINGs are UTF-8.</param>
/// <param name="mapError">Maps an ADS code to an OPC UA status (also raises symbol-version signals).</param>
/// <returns>The value and status.</returns>
public static (object? value, uint status) DecodeItem(
TwinCATDataType type, Beckhoff.AdsErrorCode subError, ReadOnlyMemory<byte>? block,
TwinCATArrayLayout layout, bool isArray, bool utf8, Func<uint, uint> mapError)
{
if (subError != Beckhoff.AdsErrorCode.NoError) return (null, mapError((uint)subError));
if (block is not { } b || b.Length < layout.ByteLength)
return (null, TwinCATStatusMapper.MapAdsError(1797));
try
{
var decoded = TwinCATArrayCodec.Decode(type, b.Span, layout, utf8);
return (isArray ? decoded : decoded.GetValue(0), TwinCATStatusMapper.Good);
}
catch (ArgumentException)
{
return (null, TwinCATStatusMapper.MapAdsError(1797));
}
}
}