namespace ZB.MOM.WW.OtOpcUa.Driver.S7;
///
/// Pure planner that turns one read batch into contiguous (area, DB) byte spans, so the
/// driver can serve many tags with one ReadBytesAsync instead of one wire request per
/// tag. No I/O, no driver state — the grouping rules are decided here and executed by
/// .
///
///
///
/// The safety invariant is that a span never extends past its last member's end. A
/// span may deliberately read bytes nobody asked for BETWEEN its members (that is what the
/// gap budget buys), but every byte it requests lies inside a range some member was going
/// to read anyway. A grouped read therefore cannot fault (area overrun, DB overrun) where
/// the individual per-tag reads would have succeeded.
///
///
/// Timer and Counter tags are never grouped. Their
/// holds the timer/counter DEVICE NUMBER rather
/// than a byte address, and S7.Net addresses those areas in per-device units — merging one
/// with a byte-addressed neighbour, or even with another Timer, would read from a
/// completely unrelated place. They come back as leftovers for the per-tag path.
///
///
internal static class S7ReadSpanPlanner
{
/// One tag inside a planned span, positioned relative to the span's start byte.
/// The tag's index in the caller's read batch — where its result must be written.
/// The resolved tag definition (carries the data type, array count and string length).
/// The tag's parsed address (carries the area, DB, access size and bit position).
/// Bytes this tag occupies — the exact number its decoder consumes.
/// The tag's first byte expressed against ; the slice offset into the block.
internal sealed record Member(
int OriginalIndex,
S7TagDefinition Tag,
S7ParsedAddress Addr,
int WidthBytes,
int RelativeOffset);
/// One planned block read: a contiguous byte range in one area, serving several tags.
/// The S7 area the block is read from.
/// Data-block number (0 for non-DB areas).
/// First byte of the block — the lowest member's byte offset.
/// Block length — always exactly the furthest member's end minus .
/// The tags this block serves, in ascending byte order.
internal sealed record Span(
S7Area Area,
int DbNumber,
int StartByte,
int LengthBytes,
IReadOnlyList Members);
/// The planned grouping of one read batch.
/// Block reads to issue, one wire request each.
/// Batch indexes the planner declined — the caller reads these one at a time.
internal sealed record Plan(IReadOnlyList Spans, IReadOnlyList LeftoverIndexes);
///
/// Groups the resolved tags of one read batch into block-read spans.
///
///
/// The batch's resolved tags, each paired with its parsed address and its index in the
/// caller's reference list. Unresolvable references must be handled by the caller and left
/// out of this list.
///
///
/// Largest hole to read through when merging (inclusive). 0 merges only strictly
/// adjacent or overlapping tags; any value below zero disables grouping and returns every
/// index as a leftover.
///
///
/// Largest planned span. A run that would exceed it is broken; a single tag wider than it
/// still forms its own span, because a tag is never split across requests.
///
/// The spans to read plus the indexes the caller must read individually.
internal static Plan Build(
IReadOnlyList<(int OriginalIndex, S7TagDefinition Tag, S7ParsedAddress Addr)> resolved,
int maxGapBytes,
int maxSpanBytes)
{
ArgumentNullException.ThrowIfNull(resolved);
var leftovers = new List();
// The off switch. Checked here (as well as at the call site) so the disabled behaviour is
// a property of the planner and can be proven without standing up a driver.
if (maxGapBytes < 0)
{
foreach (var (index, _, _) in resolved) leftovers.Add(index);
return new Plan([], leftovers);
}
List<(int Index, S7TagDefinition Tag, S7ParsedAddress Addr, int Width)>? eligible = null;
foreach (var (index, tag, addr) in resolved)
{
// Timer/Counter offsets are device numbers, not byte addresses — see the type remarks.
if (addr.Area is S7Area.Timer or S7Area.Counter)
{
leftovers.Add(index);
continue;
}
(eligible ??= []).Add((index, tag, addr, MemberWidthBytes(tag, addr)));
}
if (eligible is null) return new Plan([], leftovers);
var spans = new List();
// Group by (area, DB): two areas — or two data blocks — are separate address spaces, so a
// byte range in one says nothing about the same range in the other.
foreach (var group in eligible.GroupBy(e => (e.Addr.Area, e.Addr.DbNumber)))
{
OpenSpan? open = null;
// Ascending byte order. OrderBy is stable, so tags sharing a byte (two Bools at
// different bit positions) keep their batch order inside the span.
foreach (var (index, tag, addr, width) in group.OrderBy(e => e.Addr.ByteOffset))
{
var start = addr.ByteOffset;
var end = start + width; // exclusive
if (open is not null)
{
// A negative gap means the tags overlap (a word inside an already-open dword,
// or a second Bool in the same byte) — that is a gap of zero or better, so it
// always passes a non-negative budget without any clamping.
var gap = start - open.EndByte;
var mergedEnd = Math.Max(open.EndByte, end);
if (gap <= maxGapBytes && mergedEnd - open.StartByte <= maxSpanBytes)
{
open.Members.Add(new Member(index, tag, addr, width, start - open.StartByte));
// Max, not `end`: an overlapping member must never pull the span's end back.
open.EndByte = mergedEnd;
continue;
}
spans.Add(Seal(group.Key.Area, group.Key.DbNumber, open));
}
// Start a fresh span. Deliberately unconditional — a tag wider than maxSpanBytes
// gets its own oversized span rather than being split, and because the merge test
// above measures the RESULTING length, that oversized span can never absorb a
// neighbour afterwards.
open = new OpenSpan(start, end);
open.Members.Add(new Member(index, tag, addr, width, 0));
}
if (open is not null) spans.Add(Seal(group.Key.Area, group.Key.DbNumber, open));
}
return new Plan(spans, leftovers);
}
///
/// Bytes one tag occupies inside a contiguous block. The three arms are checked in exactly
/// the order routes a tag to its decoder, so the width
/// planned here is always the width the decoder that runs will consume.
///
/// The resolved tag definition.
/// The tag's parsed address.
/// The tag's byte width.
internal static int MemberWidthBytes(S7TagDefinition tag, S7ParsedAddress addr)
{
if (tag.ArrayCount is >= 1)
return tag.ArrayCount.Value * S7Driver.ElementByteSize(addr.Size);
if (S7Driver.IsBufferType(tag, addr))
return S7Driver.ScalarByteWidth(tag, addr);
return S7Driver.NarrowScalarWidth(addr);
}
/// Freezes an in-progress span into its immutable form.
/// The area the span reads from.
/// The data-block number.
/// The in-progress span.
/// The sealed span; its length is exactly the furthest member's end minus the start.
private static Span Seal(S7Area area, int dbNumber, OpenSpan open)
=> new(area, dbNumber, open.StartByte, open.EndByte - open.StartByte, open.Members);
///
/// Mutable accumulator for a span still being extended. is fixed at
/// creation (members arrive in ascending order, so nothing can ever start earlier);
/// is exclusive and only ever grows.
///
/// First byte of the span.
/// Exclusive end byte of the span so far.
private sealed class OpenSpan(int startByte, int endByte)
{
/// First byte of the span — fixed for the span's lifetime.
public int StartByte { get; } = startByte;
/// Exclusive end byte of the furthest member seen so far.
public int EndByte { get; set; } = endByte;
/// Members accumulated so far, in ascending byte order.
public List Members { get; } = [];
}
}