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.
This commit is contained in:
Joseph Doherty
2026-10-15 06:14:58 -04:00
parent ebcbd81fca
commit 826312befe
430 changed files with 4434 additions and 3923 deletions
@@ -211,8 +211,8 @@ internal sealed class S7PlcAdapter : IS7Plc
S7OperationDeadline.RunAsync(
t => _plc.ReadStatusAsync(t), _operationTimeout, "status read", cancellationToken);
/// <inheritdoc />
// Plc implements IDisposable explicitly, so cast to invoke it; disposal tears down the TcpClient.
/// <summary>Disposes the underlying PLC connection, tearing down its TcpClient.</summary>
// Plc implements IDisposable explicitly, so cast to invoke it.
public void Dispose() => ((IDisposable)_plc).Dispose();
}
@@ -34,7 +34,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.S7;
public sealed class S7Driver
: IDriver, ITagDiscovery, IReadable, IWritable, IBatchSubscribable, IHostConnectivityProbe, ISkippedTagReporter, IDriverDiagnostics, IDisposable, IAsyncDisposable
{
/// <summary>Authored tags this driver could not build into its poll table (Gitea #541).</summary>
/// <summary>Authored tags this driver could not build into its poll table.</summary>
private readonly SkippedTagLedger _skippedTags = new();
/// <inheritdoc />
@@ -60,7 +60,7 @@ public sealed class S7Driver
_logger = logger ?? NullLogger<S7Driver>.Instance;
_resolver = new EquipmentTagRefResolver<S7TagDefinition>(
r => _tagsByRawPath.TryGetValue(r, out var t) ? t : null);
// CONV-1: the polling overlay runs on the shared PollGroupEngine (structural array diff +
// The polling overlay runs on the shared PollGroupEngine (structural array diff +
// drain-before-dispose + capped-exponential failure backoff + caller-token-filtered OCE),
// retiring the bespoke S7 poll fork. minInterval 100 ms matches the S7 scan-mailbox floor;
// backoffCap 30 s matches the retired fork's PollBackoffCap.
@@ -197,7 +197,7 @@ public sealed class S7Driver
}
/// <summary>
/// Per-device connect-attempt throttle (STAB-21): a dead PLC costs one connect attempt per
/// Per-device connect-attempt throttle: a dead PLC costs one connect attempt per
/// backoff window (1 s doubling to 30 s) instead of one per data call / poll tick / probe tick.
/// Not internally synchronized — only touched from <see cref="EnsureConnectedAsync"/> (under
/// <see cref="_gate"/>) and from init/shutdown, which run with every loop drained.
@@ -225,7 +225,7 @@ public sealed class S7Driver
/// <inheritdoc />
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
// #630: InitializeAsync is reachable on a live driver with no teardown first (the IDriver contract
// 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). Stop the previous probe loop and drop the previous connection
// before they are overwritten below. Deliberately NOT ShutdownAsync: that also drops _poll and the
// subscriptions, which are owned by the shutdown path (the actor re-subscribes after every successful init).
@@ -287,7 +287,7 @@ public sealed class S7Driver
{
// The linked CancelAfter fired — a connect TIMEOUT, not a caller cancellation.
// Surface it as a TimeoutException so init-time and reconnect-time timeouts report
// the same exception type (STAB-14 consistency); the outer catch still faults health.
// the same exception type (for consistency); the outer catch still faults health.
try { plc.Dispose(); } catch { }
throw new TimeoutException(
$"S7 connect to {_options.Host}:{_options.Port} timed out after " +
@@ -365,7 +365,7 @@ public sealed class S7Driver
// and CTS objects. Without the drain, a loop iteration mid-_gate would call Release()
// on (or WaitAsync against) a disposed semaphore.
// Drain the polling overlay first — the engine cancels each loop and awaits it before
// disposing its CTS (drain-before-dispose, STAB-6-S7), so no poll iteration touches _gate
// disposing its CTS (drain-before-dispose), so no poll iteration touches _gate
// after this returns.
await _poll.DisposeAsync().ConfigureAwait(false);
await ReleaseConnectionAsync().ConfigureAwait(false);
@@ -463,11 +463,9 @@ public sealed class S7Driver
["S7.NegotiatedPduSize"] = NegotiatedPduSize,
};
/// <summary>
/// <see cref="IDriverDiagnostics"/> view of the same facts, as strings, for the <c>/hosts</c> page
/// (Gitea #640). Empty before the first connect (PDU size 0 is "not negotiated yet", not a size).
/// </summary>
/// <returns>The diagnostics bag.</returns>
// IDriverDiagnostics view of the same facts, as strings, for the /hosts page. Empty before the
// first connect (PDU size 0 is "not negotiated yet", not a size).
/// <inheritdoc />
IReadOnlyDictionary<string, string> IDriverDiagnostics.GetDiagnostics()
{
var pdu = NegotiatedPduSize;
@@ -567,7 +565,7 @@ public sealed class S7Driver
// element, mirroring the read), so a write would overwrite the 7 neighbouring bits of
// every byte it touches; a safe bit-packed write needs read-modify-write and is not
// implemented. Every other supported element type (Byte/Int16/UInt16/Int32/UInt32/
// Float32) writes as ONE contiguous block (EncodeArrayBlock) — S7-016. Wide-type arrays
// Float32) writes as ONE contiguous block (EncodeArrayBlock). Wide-type arrays
// are already rejected above (guard-a).
if (t.ArrayCount is >= 1 && t.Writable && t.DataType == S7DataType.Bool)
{
@@ -615,34 +613,24 @@ public sealed class S7Driver
// ---- IReadable ----
// The batch is served in two passes under ONE gate acquisition. First S7ReadSpanPlanner groups
// the resolved tags into contiguous (area, DB) byte spans and each span is read with a single
// ReadBytesAsync, its members decoded by slicing the returned block - this is what turns one wire
// request per tag into one per contiguous block. Whatever the planner declines (Timer/Counter,
// whose offsets are device numbers) plus any span not worth issuing (see PrefersPerTagRead) falls
// to the leftover list.
//
// Those leftovers get a SECOND grouping pass: the ones a S7DataItem expresses cleanly - the narrow
// scalars, which is what a demoted single-member span is - are batched into multi-var requests by
// ReadLeftoversByMultiVarAsync, which crosses (area, DB) boundaries a block read cannot. Whatever
// remains (Timer/Counter, unparseable addresses, and any chunk whose multi-var request faulted)
// goes through the unchanged per-tag ReadOneAsync path.
//
// Setting SpanReadMaxGapBytes below zero skips BOTH passes, which restores the pre-grouping
// behaviour exactly. Either way the result array is written by original index, so the caller sees
// its own ordering regardless of how the batch was partitioned, and both passes share
// RecordReadFailure so a fault stamps the same status whichever path observed it.
/// <inheritdoc />
/// <remarks>
/// <para>
/// The batch is served in two passes under ONE gate acquisition. First
/// <see cref="S7ReadSpanPlanner"/> groups the resolved tags into contiguous
/// <c>(area, DB)</c> byte spans and each span is read with a single
/// <c>ReadBytesAsync</c>, its members decoded by slicing the returned block — this is
/// what turns one wire request per tag into one per contiguous block. Whatever the
/// planner declines (Timer/Counter, whose offsets are device numbers) plus any span not
/// worth issuing (see <see cref="PrefersPerTagRead"/>) falls to the leftover list.
/// </para>
/// <para>
/// Those leftovers get a SECOND grouping pass: the ones a
/// <see cref="S7DataItem"/> expresses cleanly — the narrow scalars, which is what a
/// demoted single-member span is — are batched into multi-var requests by
/// <see cref="ReadLeftoversByMultiVarAsync"/>, which crosses <c>(area, DB)</c>
/// boundaries a block read cannot. Whatever remains (Timer/Counter, unparseable
/// addresses, and any chunk whose multi-var request faulted) goes through the unchanged
/// per-tag <see cref="ReadOneAsync"/> path.
/// </para>
/// <para>
/// Setting <c>SpanReadMaxGapBytes</c> below zero skips BOTH passes, which
/// restores the pre-grouping behaviour exactly. Either way the result array is written
/// by original index, so the caller sees its own ordering regardless of how the batch
/// was partitioned, and both passes share <see cref="RecordReadFailure"/> so a fault
/// stamps the same status whichever path observed it.
/// </para>
/// </remarks>
public async Task<IReadOnlyList<DataValueSnapshot>> ReadAsync(
IReadOnlyList<string> fullReferences, CancellationToken cancellationToken)
{
@@ -670,7 +658,7 @@ public sealed class S7Driver
}
// Rethrow ONLY caller cancellation. A timeout-born OCE (none expected after the
// EnsureConnectedAsync conversion, but e.g. an S7.Net-internal CTS) must degrade the
// batch below, not escape as teardown (STAB-14).
// batch below, not escape as teardown.
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception ex)
{
@@ -761,7 +749,7 @@ public sealed class S7Driver
catch (OperationCanceledException)
{
// Cancellation observed mid-PDU abandons a half-read ISO-on-TCP response on the
// single gated stream — the handle must be reopened, not reused (STAB-15a). Mark
// single gated stream — the handle must be reopened, not reused. Mark
// dead (we hold _gate) and propagate: the caller cancelled, nobody consumes the
// batch. Marking is unconditional on OCE (not routed through the type classifier):
// whether bytes moved is unknowable, and a false positive costs one cheap reopen
@@ -1045,7 +1033,7 @@ public sealed class S7Driver
catch (OperationCanceledException)
{
// Same reasoning as the per-tag and span paths: a cancelled read abandons a half-read
// response on the single gated stream, so the handle must be reopened (STAB-15a).
// response on the single gated stream, so the handle must be reopened.
_plcDead = true;
throw;
}
@@ -1164,7 +1152,7 @@ public sealed class S7Driver
catch (OperationCanceledException)
{
// Same reasoning as the per-tag path: a cancelled block read leaves the single gated
// stream at an untrustworthy position, so the handle must be reopened (STAB-15a).
// stream at an untrustworthy position, so the handle must be reopened.
_plcDead = true;
throw;
}
@@ -1477,7 +1465,7 @@ public sealed class S7Driver
// S7.Net Counter.FromByteArray returns the raw big-endian word ((bytes[0]<<8)|bytes[1]),
// without BCD reinterpretation. This preserves the raw value, not a verified PLC count:
// S7comm C-area response encoding still needs independent raw bytes and PLC-side
// count/binary/BCD references (#616). CPU family alone does not prove that encoding.
// count/binary/BCD references. CPU family alone does not prove that encoding.
// IEC counter integers in DB memory take the DB type codec, not this C-area path;
// S7-1500 also has legacy SIMATIC counters. See docs/drivers/S7.md for the evidence gate.
return (object)(int)global::S7.Net.Types.Counter.FromByteArray(block);
@@ -1569,7 +1557,7 @@ public sealed class S7Driver
// ReadScalarBlockAsync read, so WriteBytesAsync writes the whole reserved STRING. A value
// longer than StringLength throws ArgumentException (S7.Net rejects overflow; we do NOT
// silently truncate). A null value encodes as the empty string.
// #632: surfaced as S7ValueRangeException (→ BadOutOfRange) like the WSTRING codec — a
// Surfaced as S7ValueRangeException (→ BadOutOfRange) like the WSTRING codec — a
// client value error, not a comms fault (the raw ArgumentException used to land in the
// generic catch as BadCommunicationError + Degraded).
try { return global::S7.Net.Types.S7String.ToByteArray(Convert.ToString(value) ?? "", tag.StringLength); }
@@ -1580,7 +1568,7 @@ public sealed class S7Driver
// 1990–2089 DT range and throws ArgumentOutOfRangeException for an out-of-range year —
// we surface that (no silent clamp). Value coerced via Convert.ToDateTime (accepts a
// System.DateTime or a parseable timestamp string).
// #632: the range refusal maps to BadOutOfRange (see STRING above).
// The range refusal maps to BadOutOfRange (see STRING above).
var dt = Convert.ToDateTime(value);
try { return global::S7.Net.Types.DateTime.ToByteArray(dt); }
catch (ArgumentOutOfRangeException ex) { throw new S7ValueRangeException($"S7 DATE_AND_TIME value {dt:O} is outside the DT range (1990–2089): {ex.Message}"); }
@@ -1871,7 +1859,7 @@ public sealed class S7Driver
plc = await EnsureConnectedAsync(cancellationToken).ConfigureAwait(false);
}
// Rethrow ONLY caller cancellation — a timeout-born OCE degrades the batch below rather
// than escaping as teardown (STAB-14 defense-in-depth, mirrors ReadAsync).
// than escaping as teardown (defense-in-depth, mirrors ReadAsync).
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception ex)
{
@@ -1919,7 +1907,7 @@ public sealed class S7Driver
catch (OperationCanceledException)
{
// Cancellation observed mid-PDU abandons a half-written ISO-on-TCP request on
// the single gated stream — the handle must be reopened, not reused (STAB-15a).
// the single gated stream — the handle must be reopened, not reused.
// Mark dead (we hold _gate) and propagate: the caller cancelled, nobody consumes
// the batch, and Release() still runs in finally. Marking is unconditional on
// OCE — a false positive costs one cheap reopen versus permanent desync.
@@ -1983,7 +1971,7 @@ public sealed class S7Driver
}
/// <summary>
/// Publishes one write batch's verdict (STAB-22): worst state wins over every outcome the
/// Publishes one write batch's verdict: worst state wins over every outcome the
/// batch recorded, so a Faulted access-denied item is not erased by a later Degraded or
/// successful sibling. Maintains <see cref="_writeFault"/>, the sticky Faulted a read pass
/// must not erase. Caller holds <see cref="_gate"/>.
@@ -2058,7 +2046,7 @@ public sealed class S7Driver
? parsed
: S7AddressParser.Parse(tag.Address);
// Array path (S7-016): ONE contiguous WriteBytesAsync of count × element-bytes — the inverse
// Array path: ONE contiguous WriteBytesAsync of count × element-bytes — the inverse
// of ReadArrayAsync. Bool / wide-type arrays throw NotSupportedException (→ BadNotSupported);
// a wrong-shaped value throws S7WriteValueException (→ BadTypeMismatch, no health impact).
if (tag.ArrayCount is >= 1)
@@ -2246,9 +2234,9 @@ public sealed class S7Driver
/// enforces. The read / write / probe paths all take the gate before calling it.
/// <para>
/// While the PLC is down every data call and probe tick would pay a full connect attempt
/// bounded only by <c>_options.Timeout</c> (STAB-8). This method is the single
/// bounded only by <c>_options.Timeout</c>. This method is the single
/// choke-point all S7 reconnects flow through (already gate-serialized), so the
/// connect-attempt throttle lives here (STAB-21): the shared <see cref="ConnectionBackoff"/>
/// connect-attempt throttle lives here: the shared <see cref="ConnectionBackoff"/>
/// primitive is consulted with <c>ShouldAttempt(now)</c> at the top of the slow path —
/// inside the window the call fails fast with no connect attempt, which every caller
/// already degrades on — with <c>RecordFailure</c>/<c>RecordSuccess</c> around the connect.
@@ -2271,7 +2259,7 @@ public sealed class S7Driver
}
_plcDead = false;
// STAB-21: inside the backoff window fail fast WITHOUT a connect attempt. A plain
// Inside the backoff window fail fast WITHOUT a connect attempt. A plain
// InvalidOperationException (not an OCE) so the read/write/probe catch ladders degrade on it.
if (!_connectBackoff.ShouldAttempt(BackoffClock()))
throw new InvalidOperationException(
@@ -2290,7 +2278,7 @@ public sealed class S7Driver
// The linked CancelAfter fired — a connect TIMEOUT, not a caller cancellation.
// Surface it as a connection FAILURE (TimeoutException) so callers route it through
// their degrade paths: an escaping OCE reads as teardown and permanently killed the
// subscription poll loops (STAB-14, the unreachable-host regression in the Crit-3 fix).
// subscription poll loops (the unreachable-host regression).
try { plc.Dispose(); } catch { /* best-effort */ }
throw new TimeoutException(
$"S7 connect to {_options.Host}:{_options.Port} timed out after " +
@@ -2330,13 +2318,13 @@ public sealed class S7Driver
/// <see cref="System.Net.Sockets.SocketException"/> / <see cref="System.IO.IOException"/> /
/// <see cref="ObjectDisposedException"/>; a <see cref="TimeoutException"/> from a wire op that
/// blew its <see cref="S7OperationDeadline"/> wall-clock ceiling (an unresponsive but still
/// TCP-established peer — the READ-leg sibling of the connect-timeout fix, STAB-14); an S7.Net framing violation
/// TCP-established peer — the READ-leg sibling of the connect-timeout fix); an S7.Net framing violation
/// (<see cref="TPKTInvalidException"/> / <see cref="TPDUInvalidException"/> /
/// <see cref="WrongNumberOfBytesException"/>); or a <see cref="PlcException"/> carrying
/// <see cref="ErrorCode.ConnectionError"/> or <see cref="ErrorCode.WrongNumberReceivedBytes"/>.
/// A framing violation means the single serialized stream's position is untrustworthy — a
/// half-read PDU left by a timeout/cancellation makes every later response mis-frame, so only
/// a reopen recovers (STAB-15a: the Modbus STAB-3 desync mode rebuilt in S7).
/// a reopen recovers (the Modbus desync mode, rebuilt in S7).
/// <para>
/// Deliberately NOT <see cref="System.IO.InvalidDataException"/>: the driver's own decode
/// backstop (<see cref="ReinterpretRawValue"/> / <see cref="DecodeScalarBlock"/>) throws
@@ -2360,11 +2348,11 @@ public sealed class S7Driver
// A wire op that blew its wall-clock deadline (S7OperationDeadline — the async read/write
// ceiling S7.Net's ignored socket ReadTimeout/WriteTimeout can't provide) means the
// connection is unresponsive: discard + reopen. This is the READ-leg sibling of the
// connect-timeout fix (STAB-14) — without it a frozen-but-established peer wedges the
// connect-timeout fix — without it a frozen-but-established peer wedges the
// poll loop forever instead of surfacing Bad + reconnecting.
if (e is TimeoutException)
return true;
// ISO-on-TCP framing/desync surface (STAB-15a): the stream position is untrustworthy —
// ISO-on-TCP framing/desync surface: the stream position is untrustworthy —
// a half-read PDU left by a timeout/cancellation makes every later response mis-frame.
// NOTE: deliberately NOT System.IO.InvalidDataException — ReinterpretRawValue throws it
// for a declared-type/address-size CONFIG mismatch on a healthy socket.
@@ -2385,6 +2373,8 @@ public sealed class S7Driver
/// no typed error code for it, so the inner message is the only discriminator
/// S7.Net exposes.
/// </summary>
/// <param name="pex">The exception raised by S7.Net.</param>
/// <returns><see langword="true"/> when the PLC refused access to the object.</returns>
internal static bool IsAccessDenied(PlcException pex)
{
for (Exception? e = pex; e is not null; e = e.InnerException)
@@ -2465,7 +2455,7 @@ public sealed class S7Driver
}
/// <summary>
/// 05/STAB-9 — routes a poll-loop reader failure (surfaced by the shared
/// Routes a poll-loop reader failure (surfaced by the shared
/// <see cref="PollGroupEngine"/>'s onError sink) to the driver health surface: logs it and
/// degrades to <see cref="DriverState.Degraded"/> preserving <c>LastSuccessfulRead</c>. Never
/// downgrades a <see cref="DriverState.Faulted"/> state (e.g. PUT/GET-denied set by ReadAsync)
@@ -2518,7 +2508,7 @@ public sealed class S7Driver
// marked the handle dead (or the socket dropped between ticks), the probe
// reopens it here so recovery doesn't wait for the next data call.
// It runs on the LOOP token, not the (shorter) probe deadline: the connect is bounded by
// _options.Timeout inside, and a timeout there must count as a failure so STAB-21's
// _options.Timeout inside, and a timeout there must count as a failure so the
// backoff window opens — cutting it with the probe deadline looked like a caller cancel,
// recorded nothing, and let a black-holed host cost a connect attempt every probe tick.
var plc = await EnsureConnectedAsync(ct).ConfigureAwait(false);
@@ -2537,12 +2527,12 @@ public sealed class S7Driver
{
// Probe deadline fired mid-PDU: the CPU-status response may still be in
// flight, so the handle can't be reused (half-read ⇒ desync). We hold _gate
// here, keeping _plcDead gate-guarded (STAB-15b).
// here, keeping _plcDead gate-guarded.
_plcDead = true;
}
catch (Exception ex)
{
// STAB-15b: classify + mark while holding _gate so a wire-dead/desynced
// Classify + mark while holding _gate so a wire-dead/desynced
// handle whose TcpClient still claims Connected is reopened by the NEXT
// tick's EnsureConnectedAsync instead of being re-probed forever.
MarkConnectionDeadIfFatal(ex);
@@ -2607,7 +2597,7 @@ public sealed class S7Driver
/// </summary>
private void SynchronousTeardown()
{
// Drain the polling overlay (drain-before-dispose, STAB-6-S7).
// Drain the polling overlay (drain-before-dispose).
try { _poll.DisposeAsync().AsTask().Wait(DrainTimeout); }
catch { /* timeouts/loop faults are tolerated — teardown continues */ }
@@ -21,7 +21,7 @@ public static class S7DriverFactoryExtensions
/// The optional <paramref name="loggerFactory"/> is captured at registration time and used to
/// build an <see cref="ILogger{S7Driver}"/> per driver instance — without it the driver runs on
/// the null logger and none of its diagnostics (connect/reconnect, skipped tags, poll faults)
/// reach the node log (CONV-3).
/// reach the node log.
/// </remarks>
/// <param name="registry">The driver factory registry.</param>
/// <param name="loggerFactory">Optional logger factory for driver instances.</param>
@@ -13,7 +13,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.S7;
/// established-but-frozen connection (a frozen PLC, a firewall DROP, or a cable pulled
/// mid-flow — where the TCP session stays <i>open</i> but no reply ever arrives) blocks until
/// the OS TCP stack gives up, which can be minutes. That silently wedges the driver's poll
/// loop: no Bad tick, no reconnect — the STAB-14 "silently killed poll loop" failure, on the
/// loop: no Bad tick, no reconnect — the "silently killed poll loop" failure, on the
/// READ leg that the connect-timeout fix (<c>S7Driver.EnsureConnectedAsync</c>'s
/// <c>CancelAfter</c>) never covered.
/// </para>
@@ -45,6 +45,8 @@ internal static class S7ValueCodecs
// ---- CHAR / WCHAR ----
/// <summary>Decodes a 1-byte S7 CHAR (Latin-1) to a one-character string.</summary>
/// <param name="block">The raw big-endian S7 block.</param>
/// <returns>The decoded one-character string.</returns>
internal static string DecodeChar(ReadOnlySpan<byte> block)
{
RequireLength(block, 1, "CHAR");
@@ -52,6 +54,8 @@ internal static class S7ValueCodecs
}
/// <summary>Encodes a one-character string to a 1-byte S7 CHAR. Characters above U+00FF are out of range.</summary>
/// <param name="value">The value to encode.</param>
/// <returns>The encoded 1-byte CHAR.</returns>
internal static byte[] EncodeChar(object? value)
{
var c = SingleChar(value, "CHAR");
@@ -61,6 +65,8 @@ internal static class S7ValueCodecs
}
/// <summary>Decodes a 2-byte S7 WCHAR (UTF-16 big-endian code unit) to a one-character string.</summary>
/// <param name="block">The raw big-endian S7 block.</param>
/// <returns>The decoded one-character string.</returns>
internal static string DecodeWChar(ReadOnlySpan<byte> block)
{
RequireLength(block, 2, "WCHAR");
@@ -68,6 +74,8 @@ internal static class S7ValueCodecs
}
/// <summary>Encodes a one-character string to a 2-byte S7 WCHAR (UTF-16 big-endian).</summary>
/// <param name="value">The value to encode.</param>
/// <returns>The encoded 2-byte WCHAR.</returns>
internal static byte[] EncodeWChar(object? value)
{
var b = new byte[2];
@@ -88,12 +96,16 @@ internal static class S7ValueCodecs
// ---- WSTRING ----
/// <summary>Byte width of a WSTRING reserving <paramref name="maxLength"/> characters: 4-byte header + 2 bytes per character.</summary>
/// <param name="maxLength">The reserved character count.</param>
/// <returns>The total byte width of the WSTRING field.</returns>
internal static int WStringWidth(int maxLength) => 4 + (2 * maxLength);
/// <summary>
/// Decodes <c>[maxLen UInt16 BE][curLen UInt16 BE][curLen × UTF-16BE]</c>. Characters past
/// <c>curLen</c> (the reserved padding) are ignored.
/// </summary>
/// <param name="block">The raw big-endian S7 block.</param>
/// <returns>The decoded string.</returns>
internal static string DecodeWString(ReadOnlySpan<byte> block)
{
if (block.Length < 4)
@@ -112,6 +124,9 @@ internal static class S7ValueCodecs
/// Encodes a string into the full reserved WSTRING field (<see cref="WStringWidth"/> bytes, zero
/// padded). A value with more UTF-16 code units than <paramref name="maxLength"/> is refused, not truncated.
/// </summary>
/// <param name="value">The value to encode.</param>
/// <param name="maxLength">The reserved character count.</param>
/// <returns>The full reserved WSTRING field.</returns>
internal static byte[] EncodeWString(object? value, int maxLength)
{
var s = Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture) ?? "";
@@ -131,6 +146,8 @@ internal static class S7ValueCodecs
/// Decodes DTL: <c>year UInt16 BE, month, day, weekday, hour, minute, second, nanoseconds UInt32 BE</c>.
/// The weekday byte is ignored. An all-zero (uninitialised) buffer is refused.
/// </summary>
/// <param name="block">The raw big-endian S7 block.</param>
/// <returns>The decoded timestamp.</returns>
internal static DateTime DecodeDtl(ReadOnlySpan<byte> block)
{
RequireLength(block, 12, "DTL");
@@ -152,6 +169,8 @@ internal static class S7ValueCodecs
}
/// <summary>Encodes a DateTime to DTL. Years outside the PLC's 1970–2262 range are refused; sub-100 ns precision is not representable in a DateTime so nanoseconds are a multiple of 100.</summary>
/// <param name="value">The value to encode.</param>
/// <returns>The encoded DTL block.</returns>
internal static byte[] EncodeDtl(object? value)
{
var dt = ToDateTime(value, "DTL");
@@ -172,6 +191,8 @@ internal static class S7ValueCodecs
// ---- DATE (UInt16 days since 1990-01-01) ----
/// <summary>Decodes DATE (days since 1990-01-01, UInt16 BE) to a midnight DateTime.</summary>
/// <param name="block">The raw big-endian S7 block.</param>
/// <returns>The decoded date at midnight.</returns>
internal static DateTime DecodeDate(ReadOnlySpan<byte> block)
{
RequireLength(block, 2, "DATE");
@@ -179,6 +200,8 @@ internal static class S7ValueCodecs
}
/// <summary>Encodes the DATE part of a DateTime; dates before 1990-01-01 or past 2169-06-06 (the UInt16 ceiling) are refused. The time-of-day is dropped.</summary>
/// <param name="value">The value to encode.</param>
/// <returns>The encoded DATE block.</returns>
internal static byte[] EncodeDate(object? value)
{
var days = (ToDateTime(value, "DATE").Date - DateEpoch).Days;
@@ -192,6 +215,8 @@ internal static class S7ValueCodecs
// ---- TOD (UInt32 ms since midnight) ----
/// <summary>Decodes TIME_OF_DAY to Int32 milliseconds since midnight (0–86 399 999).</summary>
/// <param name="block">The raw big-endian S7 block.</param>
/// <returns>Milliseconds since midnight.</returns>
internal static int DecodeTod(ReadOnlySpan<byte> block)
{
RequireLength(block, 4, "TOD");
@@ -202,6 +227,8 @@ internal static class S7ValueCodecs
}
/// <summary>Encodes milliseconds since midnight (or a <see cref="TimeSpan"/>) to TOD; outside 0–86 399 999 is refused.</summary>
/// <param name="value">The value to encode.</param>
/// <returns>The encoded TOD block.</returns>
internal static byte[] EncodeTod(object? value)
{
var ms = ToMilliseconds(value, "TOD");
@@ -215,6 +242,8 @@ internal static class S7ValueCodecs
// ---- TIME (Int32 ms, signed) ----
/// <summary>Decodes IEC TIME to a signed Int32 millisecond duration.</summary>
/// <param name="block">The raw big-endian S7 block.</param>
/// <returns>The signed duration in milliseconds.</returns>
internal static int DecodeTime(ReadOnlySpan<byte> block)
{
RequireLength(block, 4, "TIME");
@@ -222,6 +251,8 @@ internal static class S7ValueCodecs
}
/// <summary>Encodes a signed millisecond duration (or <see cref="TimeSpan"/>) to TIME; outside the Int32 range is refused.</summary>
/// <param name="value">The value to encode.</param>
/// <returns>The encoded TIME block.</returns>
internal static byte[] EncodeTime(object? value)
{
var ms = ToMilliseconds(value, "TIME");
@@ -240,6 +271,8 @@ internal static class S7ValueCodecs
/// Decodes S5TIME — bits 13–12 select the time base (00 = 10 ms, 01 = 100 ms, 10 = 1 s, 11 = 10 s),
/// bits 11–0 are three BCD digits — to Int32 milliseconds. Bits 15–14 are ignored. A non-BCD nibble is refused.
/// </summary>
/// <param name="block">The raw big-endian S7 block.</param>
/// <returns>The duration in milliseconds.</returns>
internal static int DecodeS5Time(ReadOnlySpan<byte> block)
{
RequireLength(block, 2, "S5TIME");
@@ -254,6 +287,8 @@ internal static class S7ValueCodecs
/// Encodes a millisecond duration to S5TIME using the finest time base that holds it (value ≤ 999).
/// Refused when it exceeds 9 990 000 ms or is not an exact multiple of a base that fits — no rounding.
/// </summary>
/// <param name="value">The value to encode.</param>
/// <returns>The encoded S5TIME block.</returns>
internal static byte[] EncodeS5Time(object? value)
{
var ms = ToMilliseconds(value, "S5TIME");