Přeskočit obsah

TCP Transport

Start here: For overall communication architecture, see Communication Overview.

The framework provides a ready-made TCP transport for adapters communicating with devices over TCP/IP. You provide framing, response matching, and protocol logic. The framework handles sockets, buffering, backpressure, disconnect propagation, and the serialized request-response channel.


Architecture

+---------------------------------------------------------------------+
|                    Framework TCP Transport                            |
+---------------------------------------------------------------------+
|                                                                       |
|  Transport (singleton, per adapter host)                              |
|  +------------------------------------------------------------------+|
|  | SingleTcpTransportBase<TFrame, TEvent>                           ||
|  |   ConnectChannel(host, port, router, ct, ...) -> channel         ||
|  +------------------------------------------------------------------+|
|       |                                                               |
|       | one channel per device connection                            |
|       v                                                               |
|  +------------------------------------------------------------------+|
|  | ProtocolChannel<TFrame> where TFrame : FrameBase                 ||
|  |                                                                  ||
|  |  Send(request, options, ct)                                      ||
|  |  SendBulk(...)                                                   ||
|  |  OnUnmatchedFrame / OnDisconnected                               ||
|  +---------------------------+--------------------------------------+|
|                              |                                       |
|                              v                                       |
|  +------------------------------------------------------------------+|
|  | TcpConnection<TFrame>                                            ||
|  |                                                                  ||
|  |  Socket ──> PipeReader ──> IFrameParser ──> Channel<TFrame>      ||
|  |                                                                  ||
|  |  Write(bytes, ct)            = raw socket write                  ||
|  |  Frames                      = parsed incoming frames            ||
|  +------------------------------------------------------------------+|
|                                                                       |
+---------------------------------------------------------------------+

Key properties:

  • ProtocolChannel owns request-response — Send() serializes a frame, waits for matching response
  • Matching via FrameBase — your frame type defines how requests pair with responses
  • Unmatched frames dispatched — unsolicited device events go to OnUnmatchedFrame / TransformToEvents()
  • Zero-copy reads via System.IO.Pipelines (pooled buffers)
  • Backpressure — if adapter can't process frames fast enough, TCP window closes
  • Thread-safe writes — transport serializes writes internally
  • Automatic disconnect signaling — framework handles reconnection via ConnectionStateTracker
  • Retransmit on response timeout — the same frame is written again up to TimeoutRetries times (default 2); an IAtMostOnce frame is written once
  • Receive silence rule — with ReceiveSilenceTimeout set, a channel that receives no frame for that time counts the connection as lost, also when the TCP socket stays open
  • Channel poison on terminal timeout/cancel/disconnect — caller must reconnect after session loss

What You Provide vs What Framework Provides

Concern Framework Adapter
TCP socket lifecycle Yes -
Read loop + buffering Yes (PipeReader) -
Frame parsing (bytes → frame) - Yes (IFrameParser)
Frame serialization (frame → bytes) - Yes (FrameBase.Serialize())
Request-response matching Yes (ProtocolChannel) Yes (FrameBase.MatchResponse() / IsResponseTo())
Request-response dispatch Yes (ProtocolChannel.Send()) -
Unmatched frame routing Yes Yes (handler logic)
Write serialization Yes (SemaphoreSlim) -
Disconnect detection + reconnect Yes -
Keepalive heartbeat Yes (idle-based) Yes (frame factory)
Frame interpretation - Yes (Protocol)
Command sequencing - Yes (Protocol via CommandQueue)
Domain event conversion - Yes (Protocol)

Core Concept: FrameBase

All TCP frame types must inherit FrameBase. A frame is one message between the adapter and the device. This abstract class has four responsibilities:

  1. Serialize — convert a request frame to bytes for transmission
  2. ExpectsResponse — declare whether a request is request-response or fire-and-forget
  3. MatchResponse / IsResponseTo — decide how an incoming frame relates to the pending request: the response, a transient busy response, a further part of the reply, or a frame that arrives independently of any request
  4. ToString — render the frame as its documented packet name followed by key addressing fields, for readable trace logs
public abstract class FrameBase
{
    public virtual bool ExpectsResponse => true;

    /// <summary>
    /// Serializes this frame to bytes for transmission.
    /// </summary>
    public abstract byte[] Serialize();

    public virtual MatchResult MatchResponse(FrameBase request)
        => IsResponseTo(request) ? MatchResult.Match : MatchResult.NoMatch;

    /// <summary>
    /// Checks if this frame is a response to the given request frame.
    /// </summary>
    public abstract bool IsResponseTo(FrameBase request);

    /// <summary>
    /// Packet name from the protocol documentation plus key fields. Never raw hex only —
    /// the transport already trace-logs the hex bytes.
    /// </summary>
    public abstract override string ToString();
}

How matching works

When you call channel.Send(request):

  1. Framework registers a pending entry (before writing, to avoid race conditions)
  2. Calls request.Serialize() → sends bytes over TCP
  3. TcpConnection read loop parses incoming frames
  4. ProtocolChannel matches each frame against the active pending request via MatchResponse()
  5. MatchResponse() returns one verdict per frame (table below)
  6. The verdict decides whether the frame completes the Send() caller, is forwarded to the unmatched-frame handlers, or both
Verdict Meaning What the channel does
Match The frame is the final response. Completes the Send() caller with that frame.
Busy The frame is the response, and it says the device is busy. Applies the configured RetryPolicy. No exception is thrown for normal busy control flow.
Continue The frame belongs to the pending request and more frames follow (for example a receipt before the data reply). Forwards the frame to OnUnmatchedFrame at Trace level. The request keeps waiting.
OutOfBand The frame does not belong to the request, but the device may send it at any time (poll, heartbeat, status push). Forwards the frame to OnUnmatchedFrame at Trace level. The request keeps waiting.
NoMatch The frame does not belong to the request and nobody expects it. Forwards the frame to OnUnmatchedFrame. While a request waits, the channel logs a Warning.

Continue and OutOfBand do not restart the request timeout. The whole reply, including all Continue frames, must arrive within the request timeout.

Send(requestFrame)                          ProtocolChannel / TcpConnection
  │                                            │
  ├─ register pending                          ├─ read frame from parser
  ├─ serialize + write bytes                   ├─ frame.MatchResponse(pending)?
  └─ await response                            │    Match / Busy       → complete Send() caller
                                               │    Continue / OutOfBand → OnUnmatchedFrame, keep waiting
                                               │    NoMatch            → OnUnmatchedFrame + Warning

Choose OutOfBand for every frame the protocol defines as device-initiated. Choose NoMatch only for frames that indicate a mistake, such as a reply to a request that already timed out.

Matching strategies

Sequential protocol (one command at a time, e.g. Acme):

// All data packets share ctrl=0x09 — safe because CommandQueue serializes
public override bool IsResponseTo(FrameBase request) =>
    request is MyFrame req && req.Control == Control;

Type-based protocol (e.g. Acme — ACK for any command, events are separate):

public override bool IsResponseTo(FrameBase request) =>
    request is AcmeFrame req
    && req.Type != MessageType.EventNotification    // request is a command
    && Type != MessageType.EventNotification;       // response is not an event

Correlation-ID protocol (future — tagged requests):

public override bool IsResponseTo(FrameBase request) =>
    request is TaggedFrame req && req.Tag == Tag;

Busy-aware protocol (device returns explicit busy response code):

public override MatchResult MatchResponse(FrameBase request)
{
    if (!IsResponseTo(request))
        return MatchResult.NoMatch;

    return ResponseCode == 0xDD
        ? MatchResult.Busy
        : MatchResult.Match;
}

Receipt, device polls and data reply (the device confirms the request, polls the adapter on its own, then sends the data):

public override MatchResult MatchResponse(FrameBase request) => Type switch
{
    MessageType.Poll or MessageType.Status => MatchResult.OutOfBand, // device sends these at any time
    MessageType.Receipt => MatchResult.Continue,                     // the data reply follows
    _ => IsResponseTo(request) ? MatchResult.Match : MatchResult.NoMatch,
};

Adapter code answers device polls in the unmatched-frame path (TransformToEvents), not in MatchResponse.


Step-by-Step: Creating a TCP Adapter

1. Define transport in adapter.yaml

transport:
  type: tcp
  protocol:
    address_type: byte
    frame_type: "MyAdapter.Communication.MyFrame"
    event_type: "MyAdapter.Communication.MyEvent"

2. Define your frame type (inheriting FrameBase)

Your frame type has two roles:

  • Parsed incoming frame — created by IFrameParser, RawPacket is null
  • Outgoing request frame — created by CreateSend() factory, RawPacket holds pre-built bytes
using Pq.Adapters.Framework.Communication.Tcp;

namespace MyAdapter.Communication;

/// <summary>
/// Parsed protocol frame. Inherits FrameBase for request-response matching.
/// </summary>
public sealed class MyFrame : FrameBase
{
    /// <summary>
    /// Gets the message type code.
    /// </summary>
    public required byte Type { get; init; }

    /// <summary>
    /// Gets the payload data.
    /// </summary>
    public required byte[] Payload { get; init; }

    /// <summary>
    /// Gets pre-built packet bytes for outgoing requests. Null for parsed incoming frames.
    /// </summary>
    internal byte[]? RawPacket { get; init; }

    /// <inheritdoc/>
    public override byte[] Serialize() =>
        RawPacket ?? throw new InvalidOperationException("Frame was not created as a request");

    /// <inheritdoc/>
    public override bool IsResponseTo(FrameBase request) =>
        request is MyFrame req && req.Type == Type;

    /// <summary>
    /// Creates a request frame for sending.
    /// </summary>
    internal static MyFrame CreateSend(byte type, byte[] rawPacket) => new()
    {
        Type = type,
        Payload = [],
        RawPacket = rawPacket,
    };
}

Key pattern: The parser creates frames from incoming bytes (RawPacket stays null). The protocol creates request frames via CreateSend() with pre-built packet bytes. The same class serves both roles.

3. Implement IFrameParser

Tells the framework what the start of the received bytes holds. The parser gets every unconsumed byte in one ReadOnlySpan<byte> and indexes it like an array. It answers with one of three results; the framework consumes the bytes, calls again, and waits for more data:

Result Meaning The framework
ParseResult.NeedMore The frame is not complete yet waits for more bytes, consumes nothing
ParseResult.Skip(n) n bytes cannot begin a frame (garbage, a bad checksum) drops them and calls again at once
ParseResult.Frame(n) frame is set, it took n bytes consumes them, delivers the frame, calls again at once
using Pq.Adapters.Framework.Communication.Tcp;

namespace MyAdapter.Communication;

/// <summary>
/// Parses frames: start byte 0xAB, length byte, type, payload, checksum.
/// </summary>
public sealed class MyFrameParser : IFrameParser<MyFrame>
{
    /// <inheritdoc/>
    public ParseResult Parse(ReadOnlySpan<byte> data, out MyFrame? frame)
    {
        frame = null;
        if (data[0] != 0xAB)
            return ParseResult.Skip(1);          // not a frame start: drop one byte, the framework calls again

        if (data.Length < 2)
            return ParseResult.NeedMore;         // the length byte has not arrived

        var total = data[1] + 4;                 // start + length + type + payload + checksum
        if (data.Length < total)
            return ParseResult.NeedMore;         // the frame is not complete

        if (!ChecksumOk(data[..total]))
            return ParseResult.Skip(1);          // damaged frame: drop its start byte and look for the next one

        frame = new MyFrame
        {
            Type = data[2],
            Payload = data[3..(total - 1)].ToArray(),   // the one copy: what the frame keeps
        };
        return ParseResult.Frame(total);
    }
}

Rules:

  • data is never empty. It is valid only during the call: copy what the frame keeps, once (data[a..b].ToArray()). Slice with spans everywhere else; never copy the whole data
  • Return NeedMore for incomplete data, Skip(n) for bytes that cannot begin a frame, Frame(n) with the frame. Skip and Frame consume at least one byte. Write no resync loop: the framework calls again after every skip
  • Never throw for malformed data; skip it
  • No length guard against endless input is needed: the connection drops when more than TcpConnectionOptions.MaxUnparsedBytes stay unconsumed
  • Build log text (hex dumps) only under logger.IsEnabled(level): Parse runs for every received frame
  • In a parser test, read frames with parser.TryRead(ref buffer, out frame): it reads exactly like the connection does (skips, frames across segments), so the test sees what the adapter sees
  • The source generator auto-discovers and registers this class in DI

4. Write Protocol (using ProtocolChannel for request-response)

The generated Protocol extends TcpProtocolBase<MyEvent, MyFrame> when frame_type is declared in adapter-registration.yaml. You write the partial class that uses the attached channel:

using Microsoft.Extensions.Logging;
using Pq.Adapters.Framework.Communication.Protocol;
using Pq.Adapters.Framework.Communication.Tcp;
using Pq.Adapters.Framework.Events;

namespace MyAdapter.Communication;

/// <summary>
/// Device protocol implementation.
/// </summary>
public partial class Protocol
{
    /// <summary>
    /// Connects to a device via the framework TCP transport.
    /// </summary>
    internal async Task<bool> Connect(
        MyDevice device,
        IEventRouter<MyEvent> router,
        CancellationToken ct)
    {
        var connected = false;

        // 1. Establish TCP channel (framework manages TCP + request-response orchestration)
        var channel = await Transport.ConnectChannel(
            device.IpAddress,
            device.Port,
            router,
            ct);
        AttachChannel(channel, router);

        try
        {
            // 2. Protocol handshake using Send()
            var helloPacket = BuildPacket(0x01, []);
            var request = MyFrame.CreateSend(0x01, helloPacket);
            var response = await Send(request, TimeSpan.FromSeconds(5), ct);

            if (response.Payload[0] != 0x00)
            {
                Logger.LogWarning("Handshake rejected");
                return false;
            }

            connected = true;
            Logger.LogInformation("Connected and authenticated");
            return true;
        }
        finally
        {
            if (!connected)
                await channel.Disconnect();
        }
    }

    /// <summary>
    /// Disconnects from the device.
    /// </summary>
    internal async Task Disconnect(CancellationToken ct)
    {
        if (Channel != null)
            await Channel.Disconnect();
        DetachChannel();
    }

    /// <summary>
    /// Sends a command and waits for the matching response.
    /// </summary>
    internal async Task<byte[]?> SendCommand(byte type, byte[] payload, CancellationToken ct)
    {
        if (Channel == null)
            return null;

        var packet = BuildPacket(type, payload);
        var request = MyFrame.CreateSend(type, packet);

        try
        {
            var response = await Send(request, TimeSpan.FromSeconds(2), ct);
            return response.Payload;
        }
        catch (OperationCanceledException)
        {
            Logger.LogWarning("Command timeout for type {Type}", type);
            return null;
        }
    }

    /// <summary>
    /// Handles frames that don't match any pending Send() — device events.
    /// </summary>
    protected override IEnumerable<MyEvent> TransformToEvents(MyFrame frame)
    {
        Logger.LogDebug("Unsolicited frame: type={Type}", frame.Type);
        return [];
    }

    /// <summary>
    /// Builds a protocol packet from type and payload.
    /// </summary>
    private byte[] BuildPacket(byte type, byte[] payload)
    {
        // your protocol's packet framing logic
        var packet = new byte[3 + payload.Length];
        var length = (ushort)packet.Length;
        packet[0] = (byte)(length >> 8);
        packet[1] = (byte)(length & 0xFF);
        packet[2] = type;
        Array.Copy(payload, 0, packet, 3, payload.Length);
        return packet;
    }
}

5. Implement Device Thing

using Pq.Adapters.Framework.Communication;

namespace MyAdapter;

/// <summary>
/// Device thing implementing framework connection interface.
/// </summary>
public partial class MyDevice : IDeviceConnection
{
    /// <inheritdoc/>
    public async Task<bool> Connect(ConnectionContext context, CancellationToken ct) =>
        await Connection.Protocol.Connect(this, Connection, ct);

    /// <inheritdoc/>
    public async Task Disconnect(CancellationToken ct) =>
        await Connection.Protocol.Disconnect(ct);
}

Connection Flow Summary

1. Framework calls IDeviceConnection.Connect()
      │
2. Protocol calls Transport.ConnectChannel(host, port, router, ct)
      │  → creates TcpConnection and ProtocolChannel (identified by the channel instance)
      │  → carries the event router, wires OnDisconnected for retry
      │
3. Protocol calls AttachChannel(channel, router)
      │  → unmatched frames can flow through TransformToEvents / OnUnmatchedFrame
      │
4. Protocol does handshake using Send(frame, timeout, ct)
      │  → framework serializes, sends, waits for matching response
      │
5. Connection is live — adapter sends commands via Send()
      │  → unsolicited events flow through TransformToEvents / OnUnmatchedFrame
      │
6. On disconnect:
      │  → read loop detects EOF/error
      │  → OnDisconnected fires → framework retry via ConnectionStateTracker
      │  → IDeviceConnection.Disconnect() called, then Connect() again

Two separate jobs, with two owners:

Job Owner
Make the device send something regularly The adapter: a poll loop, or a keepalive request as a normal command or no-reply send. The framework injects no keepalive packets, so heartbeat semantics stay adapter-specific and no hidden traffic runs during reconnect and timeout scenarios.
Notice that nothing arrives The framework: ProtocolChannelOptions.ReceiveSilenceTimeout

ReceiveSilenceTimeout. When the channel receives no frame for this time, it counts the connection as lost: the pending request fails with the connection-lost IOException, the framework publishes pq.event.connection.lost, reconnects with backoff, and resumes an interrupted access synchronization after the reconnect.

  • Every parsed frame resets the clock: a response, an event, an unmatched frame. Bytes the parser cannot frame do not.
  • It detects a link whose TCP socket stays open while the device behind it no longer answers: an RS485/TCP gateway with a dead bus, a hung converter, a path that drops packets without a reset. OS TCP keepalive (TcpConnectionOptions.KeepAliveEnabled) does not detect these, because the TCP peer still answers. A response timeout does not detect them either when the sends set TimeoutIsExpected (a multi-drop bus where one absent module is normal).
  • Set it above the longest silence of a healthy link, so that one late reply or an empty bus scan does not drop it. The silence of a healthy link grows with every send that may stay unanswered, because each waits for its own timeout. Reference: TechFass APS mini publishes it as the controller property gateway_silence_timeout_seconds (default 300 s: a bus of 32 offline modules at connect).
  • Do not set it on a channel that may stay silent for long without a keepalive request.
  • Null (default) disables the rule; zero or a negative value throws ArgumentOutOfRangeException when the options are created.

API Reference

FrameBase (abstract, your frame inherits this)

Member Description
Serialize() Convert frame to bytes for transmission
ExpectsResponse Declare whether the request expects a reply
MatchResponse(FrameBase request) Rich matching result (NoMatch, Match, Busy, Continue, OutOfBand)
IsResponseTo(FrameBase request) Boolean matching used by the default MatchResponse
ToString() Documented packet name plus key fields, for trace logs

SingleTcpTransportBase

Singleton per adapter host. Every transport: type: tcp adapter's generated Transport class inherits this. A TCP connection is one device per socket; the transport identifies each connection by its own ProtocolChannel instance, so several device connections coexist on the one shared host transport without colliding on a key.

Method Description
ConnectChannel(host, port, router, ct, tcpOptions?, channelOptions?) Opens the connection and returns its ProtocolChannel<TFrame>; the caller owns and drives that channel

Close a connection through its own channel (channel.Disconnect()), which the transport observes and drops. There is no address-keyed Disconnect or GetChannel — a caller never reaches another device's connection.

ProtocolChannel where TFrame : FrameBase

One per device connection. Created and returned by Transport.ConnectChannel().

Member Description
Send(request, options?, ct) Request-response or no-reply send
SendBulk(...) Sequential bulk send with stop-on-first-error semantics
ExclusiveSession((session, ct) => ..., ct) Caller-driven exclusive lease for multi-packet logical operations; the operation sends through session.Send
Disconnect() Closes this connection; the owning transport drops exactly this channel
OnUnmatchedFrame Hook for unsolicited frames not consumed by matching
OnDisconnected Fires when the channel becomes terminally unusable
TcpConnection Access to raw TCP transport when a protocol truly needs it
IsConnected Whether the channel is still usable

TcpConnection where TFrame : FrameBase

Raw framed transport under ProtocolChannel.

Member Description
Write(data, ct) Fire-and-forget: send raw bytes (thread-safe)
Frames ChannelReader<TFrame> with parsed incoming frames
IsConnected Whether the connection is active
OnDisconnected Callback (set by Transport, triggers framework retry)

IFrameParser where TFrame : FrameBase

Adapter implements this. Auto-discovered and registered by source generator.

Method Description
Parse(data, out frame) Says what the start of data (every unconsumed byte, one span) holds: ParseResult.NeedMore, ParseResult.Skip(n) or ParseResult.Frame(n)
TryRead(ref buffer, out frame) (extension) Reads the next frame the way the connection does; for parser tests

TcpConnectionOptions

Optional configuration passed to Transport.ConnectChannel() as tcpOptions.

Property Default Description
FrameQueueCapacity 256 Max buffered frames before backpressure
PipeReaderOptions null PipeReader configuration (buffer sizes, pool)
MaxUnparsedBytes 64 KiB Received bytes the frame parser may leave unconsumed. More without a complete frame drops the connection, and the framework reconnects
ConnectTimeout 10s TCP connect timeout

Frames larger than 64 KiB. The default covers every frame up to 64 KiB. When the parser holds more received bytes without returning a frame (a missing terminator, a damaged length field, another service on the port), the connection drops with a warning: the frame parser found no complete frame in N bytes (limit 65536). The parser needs no length check of its own for this. An adapter whose protocol really sends larger frames must raise the limit to its largest frame:

var tcpOptions = new TcpConnectionOptions { MaxUnparsedBytes = 256 * 1024 };
var channel = await Transport.ConnectChannel(host, port, router, ct, tcpOptions: tcpOptions);

ProtocolChannelOptions

Optional configuration passed to Transport.ConnectChannel() as channelOptions.

Property Default Description
DefaultTimeout 5s Default response timeout when no per-send timeout is provided
TimeoutRetries 2 Retransmits of the same frame after a response timeout, each with a fresh timeout and the normal quiet time. The connection counts as lost only after the last attempt times out. 0 = disconnect on the first timeout. TimeoutIsExpected requests and IAtMostOnce frames are written once
MaxQueueSize 256 Buffered normal-priority requests. A full queue makes the caller wait (backpressure); a request is never dropped
HighPriorityBurstLimit 10 Fairness limit before one normal item is forced
QuietTimeBeforeSend 5 ms Minimum quiet line before every frame the channel writes, measured from the last written frame, the last response to a pending request, or a request timeout. Unsolicited device frames do not restart it. A frame overrides it via FrameBase.QuietTimeBeforeSend
QuietTimeAfterNoReplyFrame Zero Minimum gap after any frame written without awaiting a reply (sequence acknowledge, follow-up, no-reply send). The next frame waits the larger of this and its quiet time before send
AdaptiveQuietTime AdaptiveQuietTime.Default (max 1 s, 50) new(Max, RecoveryTransactions): widens QuietTimeBeforeSend while the device drops or refuses frames. null keeps the gap fixed and is the only way to run with a zero QuietTimeBeforeSend. See Adaptive quiet time below
ReceiveSilenceTimeout null (off) No frame received for this time = connection lost, also while the TCP socket stays open. See Keepalive and Link Liveness above

For multi-step mandatory exchanges (e.g. a history/log drain that must run to completion on the wire), use the frame-typed subtype ProtocolChannelOptions<TFrame>, which adds a SequencePolicies list. See Sequence Policies below and compliance rule COMM-007.

Adaptive quiet time

Most panels and controllers are single-chip devices with no capacity guarantee: a pace that works on a demo rig fails on a fully populated site, during an event burst, while the panel writes its log, or when another client shares the panel or the bus. A fixed gap is either too slow for the healthy site or too fast for the loaded one. AdaptiveQuietTime lets the channel find the pace the device can take right now. QuietTimeBeforeSend is the floor; the rule widens it when the device signals overload (a frame it did not answer, a busy reply) and narrows it back when answers are clean.

Every channel runs with it by default: floor 5 ms, max 1 s, 50 clean answers per halving. Lab traces (Paradox EVO, Dominus Millenium) show replies in 35-50 ms and the next request within 1 ms, so the floor waits on almost every frame: 5 ms costs about 10 % of throughput, 50 ms about 100 %. Raise the floor only for a device known to be slow or to report busy:

channelOptions: new ProtocolChannelOptions
{
    QuietTimeBeforeSend = TimeSpan.FromMilliseconds(100),                      // floor, from the field trace
}
stateDiagram-v2
    direction LR
    [*] --> Floor : channel opens
    Floor --> Widened : timeout → retransmit<br/>or busy reply (gap ×2)
    Widened --> Widened : timeout or busy (gap ×2, capped at Max)
    Widened --> Widened : RecoveryTransactions clean answers (gap ÷2)
    Widened --> Floor : gap ÷2 reaches QuietTimeBeforeSend
Event Gap
channel opens QuietTimeBeforeSend; must be positive, the channel throws ArgumentOutOfRangeException on a zero floor
response timeout → retransmit, or Busy reply ×2, capped at Max; clean-answer count reset
RecoveryTransactions consecutive first-attempt answers ÷2, never below the floor
frame with its own FrameBase.QuietTimeBeforeSend that value wins; the widened gap is ignored for that frame

The channel logs every change (Quiet time 100ms -> 200ms (timeout)), at Warning when the gap reaches Max. Pick Max so that a device at the ceiling still polls acceptably (1 s for a panel with a few status reads per cycle); pick RecoveryTransactions so that a single drop does not keep the gap wide for minutes (50 transactions ≈ one or two poll cycles).

Recommended for every request/reply channel that retransmits on timeout, unless the vendor mandates a fixed cadence that the channel must not stretch. It costs nothing while the device keeps up. Reference deployments: Satel INTEGRA (floor 100 ms, max 1 s), TechFass APS mini (floor 50 ms, max 1 s) and Ademco Galaxy (floor 50 ms, max 1 s, widened by busy replies). Not a compliance rule. It is not a substitute for the response timeout: a device that answers every frame, only late, needs a longer timeout, not a wider gap. A protocol-mandated busy cadence stays in RetryPolicy; the adaptive gap adds to it only after the device has refused.

ProtocolChannelOptions<TFrame> — Sequence Policies

Some packet types carry a protocol obligation: their response must be acknowledged and the request repeated until the device signals the end (GetLog → AckLog → GetLog → … → NoData). That obligation is a property of the protocol, not the call site, so it is declared once per channel instead of looped per call:

channelOptions: new ProtocolChannelOptions<XFrame>
{
    QuietTimeAfterNoReplyFrame = interFrameGap,
    SequencePolicies = [GetLogSequence.Create(BuildFrame)],
}

A SequencePolicy<TFrame> is (request, response) → next step or null, consulted on the dispatch loop after every matched response. It must be pure decision logic — no blocking, no await, no I/O, no throwing. Returning an action makes the channel write the no-reply Acknowledge, honor QuietTimeAfterNoReplyFrame, then send Continue; a null Continue (or a null action) ends the sequence.

While a sequence runs it occupies a single dispatch-queue slot — nothing interleaves between an ACK and the next request. Externally it is a plain Send that returns the final response; intermediate responses are forwarded, in order, to the unmatched-frame → event path after the sequence completes. SendOptions.Timeout applies per step. Define the policy as a static factory next to the packet definition, parameterized by the protocol's frame builder (which owns the packet-number counter). See Pattern 18: Multi-Step Protocol Sequences for the full behavior — lifecycle walkthrough, event delivery timing, per-step timeouts, failure modes — and compliance rule COMM-007 for the reviewer contract.

Exclusive Sessions

Use ExclusiveSession(...) when a caller-driven logical operation issues many request-reply packets and must not be interleaved with status polls or commands. Typical examples are device discovery, bulk configuration reads, and panel restore flows. A plain loop of await Send(...) is not enough for these operations: every awaited send releases the dispatch slot, so queued traffic can slip between two packets of the same logical operation.

ExclusiveSession takes the dispatch slot as one queued item, then holds it until the delegate completes. The delegate receives a session handle (IChannelSession<TFrame>); only session.Send(...) writes on the held slot, one request at a time, while all foreign sends wait. Pass the session to every inner read method. The handle throws ObjectDisposedException after the session ends, and a plain Send(...) or SendBulk(...) on the same channel inside the session throws InvalidOperationException (it would otherwise wait for the session that waits for it). Foreign background sends wait indefinitely; a send belonging to an interactive command waits only for its send deadline, after which it stays unsent and the operator is answered Busy. A session shorter than that deadline is therefore invisible to operator commands.

Inside a TcpProtocolBase subclass, expose a narrow adapter-local wrapper when discovery or another capability needs to start a session from outside the protocol class:

internal Task<TResult> RunSession<TResult>(Func<IChannelSession<MyFrame>, CancellationToken, Task<TResult>> operation, CancellationToken ct)
    => ExclusiveSession(operation, ct);

Then wrap the whole logical operation once and pass the session to the inner reads:

public static Task<AdapterDeviceCollection> Discover(Panel panel, Protocol protocol, CancellationToken ct)
    => protocol.RunSession(async (session, leaseCt) =>
    {
        var readers = await protocol.EnumerateReaders(session, leaseCt);
        var doors = await protocol.EnumerateDoors(session, leaseCt);
        return BuildTree(readers, doors);
    }, ct);

SendBulk inside an exclusive session throws InvalidOperationException: bulk is deliberately interruptible and fills idle gaps, and the held dispatch loop does not pull bulk items. Single request-reply operations do not need a session.

SendOptions

Per-request configuration passed to Send(request, options, ct).

Property Default Description
Timeout null (uses channel default) Per-request timeout override
RetryPolicy RetryPolicy.None Retry behavior on transient failures
NoReply false Fire-and-forget mode (no response expected)
Priority Normal Queue priority (Normal or High)

RetryPolicy

Configures automatic retry on transient failures, including matched MatchResult.Busy responses. Not retried: OperationCanceledException, TimeoutException, disconnect. Timeouts are handled by the channel option TimeoutRetries instead: it retransmits the same frame (default twice) and drops the connection only after the last attempt times out. A request with TimeoutIsExpected and an IAtMostOnce frame are never retransmitted.

Frames sent at most once. A device that acts on every delivery (e.g. a toggle) must never get the same frame twice. Its frame type implements the marker interface IAtMostOnce (namespace Pq.Adapters.Framework.Communication.Tcp): the channel writes it once and does not retransmit it after a response timeout. The timeout still counts as a link fault and drops the connection.

Situation Use
The operation must never reach the device twice, whatever the target IAtMostOnce on the frame type
This target may legitimately not answer (absent bus address in a scan) SendOptions.TimeoutIsExpected on that send
Both Both: written once, and the timeout does not drop the connection

RetryPolicy never resends after a timeout (it does not retry TimeoutException), so it cannot defeat IAtMostOnce. It resends only after a busy reply, where the device answered that it did not act.

// No retry (default)
RetryPolicy.None

// Fixed delay between attempts
RetryPolicy.Fixed(maxAttempts: 3, delay: TimeSpan.FromMilliseconds(100))

// Exponential backoff: 50ms → 100ms → 200ms → 400ms
RetryPolicy.Exponential(maxAttempts: 5, initialDelay: TimeSpan.FromMilliseconds(50))

// Capped exponential backoff: 100ms → 200ms → 400ms → 500ms (cap)
RetryPolicy.Exponential(
    maxAttempts: 5,
    initialDelay: TimeSpan.FromMilliseconds(100),
    maxDelay: TimeSpan.FromMilliseconds(500))

// Custom delay factory
new RetryPolicy(maxAttempts: 4, attempt => TimeSpan.FromMilliseconds(attempt * 50))

Use capped exponential when short retries are useful but unbounded growth would hurt command latency (for example, user-facing commands on temporarily busy controllers).

Priority Queues

ProtocolChannel maintains two queues:

  • High priority (unbounded) — urgent commands, status polls
  • Normal priority (bounded, backpressure) — bulk operations, background work

Fairness rule: after HighPriorityBurstLimit (default 10) consecutive high-priority items, one normal item is forced. This prevents starvation during access sync.

// High priority (e.g., user-initiated command)
await Send(request, new SendOptions { Priority = Priority.High }, ct);

// Normal priority (e.g., bulk credential upload)
await SendBulk(frames, new BulkOptions { Priority = Priority.Normal }, ct);

BulkOptions and SendBulk

For bulk operations (access sync, mass configuration):

var result = await SendBulk(frames, new BulkOptions
{
    Timeout = TimeSpan.FromSeconds(2),
    RetryPolicy = RetryPolicy.Fixed(2, TimeSpan.FromMilliseconds(50)),
    Priority = Priority.Normal
}, ct);

// Check results
if (result.IsSuccess)
    Logger.LogInformation("All {Count} items succeeded", result.SuccessCount);
else
    Logger.LogWarning("Bulk stopped at index {Index}: {Error}", 
        result.StoppedAtIndex, result.Items.Last().Exception?.Message);

Semantics:

  • Items sent sequentially (protocol constraint)
  • First failure stops the bulk (no partial success hidden)
  • BulkResult<TFrame> contains per-item outcomes

Practical Examples

Simple command (most common)

public async Task<bool> Arm(int partition, CancellationToken ct)
{
    var request = MyFrame.CreateSend(0x01, BuildPacket(partition));
    var response = await Send(request, TimeSpan.FromSeconds(5), ct);
    return response.Payload[0] == 0x00; // ACK
}

Command with capped exponential retry (unreliable device)

public async Task<byte[]?> ReadMemory(ushort address, CancellationToken ct)
{
    var request = MyFrame.CreateSend(0x10, BitConverter.GetBytes(address));
    try
    {
        var response = await Send(request, new SendOptions
        {
            Timeout = TimeSpan.FromSeconds(2),
            RetryPolicy = RetryPolicy.Exponential(
                maxAttempts: 3,
                initialDelay: TimeSpan.FromMilliseconds(100),
                maxDelay: TimeSpan.FromMilliseconds(300))
        }, ct);
        return response.Payload;
    }
    catch (TimeoutException)
    {
        Logger.LogWarning("ReadMemory timeout at 0x{Address:X4}", address);
        return null;
    }
}

Fire-and-forget (no response expected)

public async Task SendKeepalive(CancellationToken ct)
{
    var request = MyFrame.CreateSend(0xFF, []);
    await Send(request, new SendOptions { NoReply = true }, ct);
}

Bulk upload (access sync)

public async Task<int> UploadCredentials(IReadOnlyList<Credential> credentials, CancellationToken ct)
{
    var frames = credentials
        .Select(c => MyFrame.CreateSend(0x20, EncodeCredential(c)))
        .ToList();

    var result = await SendBulk(frames, new BulkOptions
    {
        Timeout = TimeSpan.FromSeconds(2),
        RetryPolicy = RetryPolicy.Fixed(2, TimeSpan.FromMilliseconds(50))
    }, ct);

    if (!result.IsSuccess)
        Logger.LogWarning("Upload stopped at {Index}/{Total}", result.StoppedAtIndex, credentials.Count);

    return result.SuccessCount;
}

High-priority command (user action)

public async Task<bool> EmergencyUnlock(int door, CancellationToken ct)
{
    var request = MyFrame.CreateSend(0x99, [(byte)door]);
    var response = await Send(request, new SendOptions
    {
        Timeout = TimeSpan.FromSeconds(1),
        Priority = Priority.High  // jumps queue
    }, ct);
    return response.Payload[0] == 0x00;
}

Common Mistakes

Mistake Fix
Manually reading from TcpConnection.Frames in adapter protocol code Use ProtocolChannel and TransformToEvents() / OnUnmatchedFrame instead
Using TcpConnection directly for request-response Use Send() on TcpProtocolBase / ProtocolChannel
IsResponseTo() matches unsolicited events Exclude event types in your matching logic (e.g. Type != "nq")
Serialize() called on parsed frame (no RawPacket) Use a factory method like CreateSend() for outgoing frames
Multiple Send() with same matching key without CommandQueue Serialize commands through ProtocolBase.Enqueue() to avoid collisions
Multi-packet discovery/config read implemented as a plain Send() loop Wrap the whole logical operation in one ExclusiveSession((session, ct) => ...) and send through session.Send
Returning false from Connect() after opening a channel without cleanup Always disconnect partial sessions in finally so reconnect starts clean

See Also