Class SerialSender

Streams pipeline samples to a serial device as delimited ASCII lines, off the pipeline thread.

JSON configuration

Use these block entries inside a pipeline configuration. Input names must match other blocks in that pipeline; device addresses and file paths must match your setup.

JSON configuration:

{
  "HandSerial": {
    "Type": "SerialSender",
    "Params": [ "COM3", 115200, "\n", ",", 2, 256, 500, 2000, 0.0, true, "DropNewest" ],
    "Inputs": [ "Predictor" ],
    "DesiredRate": 50,
    "Path": "C:/Data/session1"
  }
}

A sample of [84.3712, -0.5, 0.0] leaves as 84.37,-0.50,0.00\n.

The Path above writes HandSerial_data.csv and HandSerial_wire.txt into that directory — the sample as it arrived and the line as it left. Omit it and the block transmits exactly the same, logging nothing.

Params — positional; an empty string keeps the default for that position:

IndexDescription
0portName (string) — required, e.g. "COM3" or "/dev/ttyUSB0". The starting port; the card can retarget it while running.
1baudRate (int) — default 115200. Likewise.
2terminator (string) — default "\n".
3separator (string) — default ",".
4decimals (int) — default 2.
5queueCapacity (int) — default 256.
6writeTimeoutMs (int) — default 500.
7resetDelayMs (int) — default 2000.
8nonFiniteValue (double) — default 0.0.
9autoReconnect (bool) — default true.
10dropPolicy (string) — "DropNewest" (default) or "DropOldest".

How Type, Inputs and Params work · Block catalogue and parameter reference

Inheritance
SerialSender
Namespace: MOSAIC.Models.Streaming
Assembly: MOSAIC.dll
Syntax
public sealed class SerialSender : BaseBlock, INotifyPropertyChanged, INotifyPropertyChanging, ISubscriber, IPublisher, IBaseBlockProps, IJsonExportable, IDisposable, IAsyncDisposable
Remarks

Overview: each incoming sample is formatted into one line — fields joined by separator, closed by terminator — and handed to a bounded queue that a dedicated writer thread drains. Firmware that reads Serial.readStringUntil('\n') and splits on a comma needs no adapter.

Why a queue and a thread: serial writes block. A USB-CDC peer that stops draining its buffer stalls the writer for the full writeTimeoutMs, and doing that inline would hold up Publish(object) for every subscriber of the upstream block — see the back-pressure contract on BaseBlock, where a slow OnReceive costs samples graph-wide. Here the cost of a stalled port is bounded: it is paid by this block's queue and nothing else.

Back-pressure: the queue holds queueCapacity lines. Once full, dropPolicy decides who loses — DropNewest protects ordering and the oldest backlog, DropOldest protects recency. Either way Send(ReadOnlySpan<double>) returns promptly and never blocks the caller, and every discarded sample is counted.

Formatting: values are written with ToString("F{decimals}", InvariantCulture). The invariant culture is not decoration — under a comma-decimal locale such as de-DE the default formatter would emit 84,37, which a comma-separated line turns into two fields and a desynchronised parser. Non-finite values are replaced by nonFiniteValue before formatting for the same reason: "NaN" is not a number to most firmware.

Reconnection: construction never fails because of hardware. If the port is absent or busy, the block starts disconnected and — when autoReconnect is set — keeps retrying while samples flow through the queue's drop policy. A broken link (any non-timeout failure) closes the port and re-enters that same retry path. Write timeouts deliberately do not close the port: a receiver that is merely slow would otherwise be met with a reconnect storm.

Changing port at runtime: TryChangePort(string, int?, out string?) retargets a running block — the card exposes it as a port picker, so a wrong COM number in the JSON is a click to fix rather than an edit and a reload. The request is validated on the caller's thread and applied on the writer's, which closes the old port and reconnects through the path above. The pipeline is never interrupted: samples keep arriving and keep being published downstream, and the ones that cannot be sent during the changeover are counted as dropped like any others.

Reset delay: opening a USB-CDC port asserts DTR, which resets boards like the Arduino; resetDelayMs waits out the bootloader before the first write. Note the interaction with the queue: while the writer waits, samples keep arriving, so at R Hz a settle window discards roughly R × resetDelayMs / 1000 − queueCapacity samples. Devices that do not reset on connect should set it to 0.

Threading: Send(ReadOnlySpan<double>) is safe to call concurrently — formatting uses a thread-local buffer and only the enqueue is locked, so two threads can never interleave halves of a line. Exactly one thread ever touches the port — TryChangePort(string, int?, out string?) is callable from anywhere but only leaves a request behind for that thread to act on. IsConnected changes are raised from the writer thread, so a view model must marshal them before binding.

Disposal: Dispose() flushes what is already queued, then closes the port. The flush is bounded — a port that blocks forever cannot hold up application shutdown — and anything still unsent when the deadline passes is counted as dropped.

Logging: a Path in the JSON turns on two files, and the pair is the point — each answers a question the other cannot.

  • <Name>_data.csv — every sample handed to this block, at full precision, written from the publishing thread by Dumper. This is the input record: a sample the queue later discarded still appears here.
  • <Name>_wire.txt — the bytes that actually left the port, verbatim, written from the writer thread after each successful write. This is the output record: rounded to decimals, delimiters included, and containing nothing that was dropped.

Diffing the two shows exactly what the link cost, in a way GetStats() can only total up.

Constructors

SerialSender(SerialSenderOptions)

Initializes a new SerialSender and starts its writer thread.

Declaration
public SerialSender(SerialSenderOptions options)
Parameters
Type Name Description
SerialSenderOptions options

Configuration. Validated here; this is the only place that throws.

Remarks

Hardware trouble is not a construction failure. If the port cannot be opened the block starts disconnected and retries on the writer thread, because a pipeline that refuses to load because a USB cable is loose is worse than one that reports a disconnected block.

Exceptions
Type Condition
ArgumentNullException

options is null.

ArgumentException

Any configuration value is invalid.

SerialSender(SerialSenderOptions, bool)

Real constructor, reached only with options already validated.

Declaration
private SerialSender(SerialSenderOptions options, bool alreadyValidated)
Parameters
Type Name Description
SerialSenderOptions options

Options that have already been through Validate(SerialSenderOptions).

bool alreadyValidated

Never read. It exists to give this constructor a signature distinct from the public one.

Remarks

Exists so that validation runs exactly once, in the argument list of the this(...) call above — BaseBlock's constructor has to be handed a name and rate that have already survived checking, and it runs before any statement in a body could do the checking.

Fields

MinFlushJoinMs

Floor on how long Dispose() waits for the flush to finish.

Declaration
private const int MinFlushJoinMs = 2000
Field Value
Type Description
int

QueueWaitMs

How long the writer parks on an empty queue before re-checking for shutdown.

Declaration
private const int QueueWaitMs = 50
Field Value
Type Description
int

ReconnectDelayMs

Delay between failed open attempts while auto-reconnecting.

Declaration
private const int ReconnectDelayMs = 1000
Field Value
Type Description
int

_builder

Scratch buffer for line formatting.

Declaration
[ThreadStatic]
private static StringBuilder? _builder
Field Value
Type Description
StringBuilder
Remarks

Thread-static rather than shared: Send(ReadOnlySpan<double>) is documented as concurrency-safe, and a per-thread builder delivers that without a lock on the formatting path.

_disposed

Whether Dispose() has run.

Declaration
private volatile bool _disposed
Field Value
Type Description
bool

_dropped

Declaration
private long _dropped
Field Value
Type Description
long

_dumpErrors

Failures writing _wireDump, including a failure to open it.

Declaration
private long _dumpErrors
Field Value
Type Description
long
Remarks

Kept apart from _errors on purpose. A dump failure costs no data and says nothing about the link; folding it into the port's error count would make a full disk look like a loose cable.

_enqueued

Declaration
private long _enqueued
Field Value
Type Description
long

_errors

Declaration
private long _errors
Field Value
Type Description
long

_everConnected

Whether the port has ever opened, used to tell a reconnect from the first connect.

Declaration
private bool _everConnected
Field Value
Type Description
bool

_inFlight

1 while a dequeued line is being written and has not yet been counted, 0 otherwise.

Declaration
private int _inFlight
Field Value
Type Description
int
Remarks

A line in that window belongs to neither the queue nor the counters, which would leave it unaccounted if disposal abandoned a writer blocked inside a port write. Both the writer and Dispose() claim it through ClaimInFlight(), so exactly one of them counts it and the totals stay exact either way.

_isConnected

Backing field for IsConnected.

Declaration
private bool _isConnected
Field Value
Type Description
bool

_lastError

Message of the most recent port failure.

Declaration
private volatile string? _lastError
Field Value
Type Description
string

_lastLine

Most recently written line, kept for UI display. Written by the writer thread only.

Declaration
private volatile byte[]? _lastLine
Field Value
Type Description
byte[]

_numberFormat

Numeric format string, precomputed as "F{decimals}".

Declaration
private readonly string _numberFormat
Field Value
Type Description
string

_openAttempted

Whether an open has been attempted at least once, gating non-reconnecting retries.

Declaration
private bool _openAttempted
Field Value
Type Description
bool

_options

Validated configuration in effect right now.

Declaration
private SerialSenderOptions _options
Field Value
Type Description
SerialSenderOptions
Remarks

Replaced wholesale — never mutated — when TryChangePort(string, int?, out string?) is applied, and only by the writer thread. The record is immutable and the reference assignment is atomic, so a reader on the pipeline thread always sees one coherent configuration; the worst it can see is the previous one for an instant, which costs at most one line addressed with the old port's name in a status string.

Only PortName and BaudRate ever change. The framing fields are fixed for the block's lifetime — _numberFormat and _queue are derived from them at construction, and altering them mid-stream would desynchronise the firmware's parser rather than reconfigure it.

_pendingOptions

A validated configuration waiting to be adopted by the writer thread, or null when there is none.

Declaration
private SerialSenderOptions? _pendingOptions
Field Value
Type Description
SerialSenderOptions
Remarks

The handoff for TryChangePort(string, int?, out string?). Published by whichever thread calls that method — in practice the UI thread — and claimed by the writer through Exchange<T>(ref T, T), so the port itself is still only ever touched by one thread. A second change requested before the first is picked up simply replaces it: the last choice made is the one that takes effect, which is what a person clicking through a combo box means.

_port

The port this block transmits through. Created and owned here.

Declaration
private SystemSerialPort _port
Field Value
Type Description
SystemSerialPort
Remarks

Replaced with a fresh SystemSerialPort when a port change is applied, which is why this is not readonly. Only the writer thread assigns it, and only from ApplyPendingPort() — the same thread that is the sole legitimate user of a port, so the swap can never happen underneath an in-progress write.

_queue

Outbound lines awaiting the port. Guarded by _queueLock.

Declaration
private readonly Queue<byte[]> _queue
Field Value
Type Description
Queue<byte[]>

_queueLock

Guards _queue and carries the writer's wake-up pulse.

Declaration
private readonly object _queueLock
Field Value
Type Description
object

_reconnects

Declaration
private long _reconnects
Field Value
Type Description
long

_stopRequested

Set by Dispose() to stop the writer once the queue is drained.

Declaration
private volatile bool _stopRequested
Field Value
Type Description
bool

_stopSignal

Set on shutdown to cut short any wait the writer is parked in.

Declaration
private readonly ManualResetEventSlim _stopSignal
Field Value
Type Description
ManualResetEventSlim

_timeouts

Declaration
private long _timeouts
Field Value
Type Description
long

_wireDump

Verbatim log of the bytes that left the port, or null when no Path was configured or the file could not be opened.

Declaration
private readonly StreamWriter? _wireDump
Field Value
Type Description
StreamWriter
Remarks

Touched by the writer thread only, which is why it needs no lock and no queue of its own. That thread is already the slow path — it spends its time blocked in a port write — so one buffered file write costs nothing that matters, and doing it inline keeps the file's order identical to the wire's.

AutoFlush is on so the file is complete after every line rather than after a buffer fills. A crash mid-session then still leaves a truthful record, which is most of the reason to keep this log at all.

_writer

The single thread permitted to touch _port.

Declaration
private readonly Thread _writer
Field Value
Type Description
Thread

_written

Declaration
private long _written
Field Value
Type Description
long

Properties

DumpFilePrefix

Recordings from this block are named <block>_data.csv.

Declaration
protected override string DumpFilePrefix { get; }
Property Value
Type Description
string
Overrides
BaseBlock.DumpFilePrefix

IsConnected

Whether the port is currently open.

Declaration
public bool IsConnected { get; private set; }
Property Value
Type Description
bool
Remarks

Maintained by the writer thread, so PropertyChanged is raised off the UI thread and a view model must marshal it.

JsonTypeName

Block type identifier for JSON serialization. Override for a custom name.

Declaration
protected override string JsonTypeName { get; }
Property Value
Type Description
string
Overrides
BaseBlock.JsonTypeName

LastLine

The last line written, with its terminator trimmed, or null if none.

Declaration
public string? LastLine { get; }
Property Value
Type Description
string
Remarks

Decoded on read rather than on write, so displaying it costs the UI thread and not the hot path.

Options

The validated configuration in effect.

Declaration
public SerialSenderOptions Options { get; }
Property Value
Type Description
SerialSenderOptions
Remarks

Everything here is fixed at construction except the port name and baud rate, which TryChangePort(string, int?, out string?) can replace. Re-read it after a change rather than caching it — the record is swapped, not edited.

QueueDepth

Lines currently queued and not yet handed to the port.

Declaration
public int QueueDepth { get; }
Property Value
Type Description
int

Viz

Visualization helper bound by the card; fed with every sample sent.

Declaration
public BlockVisualization Viz { get; }
Property Value
Type Description
BlockVisualization

Methods

ApplyPendingPort()

Adopts a pending port change, if one was requested since the last iteration.

Declaration
private void ApplyPendingPort()
Remarks

Runs on the writer thread, which is what makes the swap safe without a lock on the port: the only thread that could be mid-write is the one executing this, and it is plainly not.

A fresh SystemSerialPort rather than a reconfigured one — that wrapper caches its name and rate for the reopen strategy documented on it, and building a new one keeps that arrangement honest instead of introducing a second way to change them.

_openAttempted is cleared so that a block configured with autoReconnect: false, having already spent its single attempt, still gets one for the port just chosen. Asking for a different port is an explicit request to try again; _everConnected is left alone, so that attempt is counted as a reconnect.

ClaimInFlight()

Takes ownership of counting the line currently in flight.

Declaration
private bool ClaimInFlight()
Returns
Type Description
bool

true for the first caller, false for any other — so a writer that returns after Dispose() already wrote the line off does not count it a second time.

ConfigureInput(IServiceProvider, JsonModel)

Creates a SerialSender from a JSON pipeline definition.

Declaration
public static SerialSender ConfigureInput(IServiceProvider sp, JsonModel m)
Parameters
Type Name Description
IServiceProvider sp

Service provider, used only to resolve the CSV dumper.

JsonModel m

JSON model. See the class-level example for the Params layout.

Returns
Type Description
SerialSender

A configured, running SerialSender.

Exceptions
Type Condition
ArgumentException

Any configuration value is invalid.

Dispose()

Flushes the queue, stops the writer thread, and releases the port.

Declaration
public override void Dispose()
Overrides
BaseBlock.Dispose()
Remarks

The flush is bounded. If the writer is stuck in a port write that never returns, waiting for it would hang shutdown, so it is abandoned after the deadline — safely, since it is a background thread that catches everything it might hit on the way out. Whatever it never got to is counted as dropped, keeping Enqueued == Written + Dropped exact once this returns.

_stopSignal and _wireDump are only disposed when the thread actually finished; leaving them alive for an abandoned writer costs two handles and avoids an ObjectDisposedException on a thread nobody is watching. The dump loses nothing by staying open — autoflush already put every line on disk.

DumpWire(byte[])

Appends one transmitted line to the wire dump, verbatim.

Declaration
private void DumpWire(byte[] line)
Parameters
Type Name Description
byte[] line

The buffer just handed to the port.

Remarks

Decoded from the same bytes the port received rather than from the string they were built from, so the file shows what the wire carried and not what was meant to be on it.

Written with Write(string), not WriteLine: the terminator is already part of the line. Adding one would put a byte in the file that never left the port, which is the one thing this log must not do — and would silently break a config whose terminator is \r or something else entirely.

Its own try/catch, deliberately nested inside the caller's. Letting a disk error escape here would reach the link-failure handler in WriteToPort(byte[]), which would close a perfectly good port because a log file filled up.

Enqueue(byte[])

Appends a formatted line to the queue, applying the drop policy when it is full.

Declaration
private bool Enqueue(byte[] line)
Parameters
Type Name Description
byte[] line
Returns
Type Description
bool

true if the line was queued.

FormatLine(ReadOnlySpan<double>)

Renders one sample as ASCII: fields joined by the separator, closed by the terminator.

Declaration
private byte[] FormatLine(ReadOnlySpan<double> sample)
Parameters
Type Name Description
ReadOnlySpan<double> sample
Returns
Type Description
byte[]
Remarks

Every byte produced here is ASCII by construction — the invariant-culture "F" format emits only digits, '-' and '.', and both delimiters were checked for ASCII during validation — so the encoding step cannot substitute a replacement character.

GetJsonParams()

Block-specific parameters for JSON. Override to provide custom parameters.

Declaration
protected override IReadOnlyList<object>? GetJsonParams()
Returns
Type Description
IReadOnlyList<object>

The values for Params, in the order this block's ConfigureInput reads them, or null when the block takes no parameters.

Overrides
BaseBlock.GetJsonParams()
Remarks

Emits every position so a round-tripped pipeline is explicit about its configuration rather than inheriting whatever the defaults happen to be next release. Delimiters are written unescaped — the JSON writer escapes them again on the way out.

Reads the live options, so a port chosen on the card is what gets saved. Picking the right board and then saving the pipeline is how that choice becomes permanent — nothing is written back to the source file on its own.

GetStats()

Samples the traffic counters.

Declaration
public SerialSenderStats GetStats()
Returns
Type Description
SerialSenderStats

A consistent snapshot; see SerialSenderStats for the invariant it upholds.

Remarks

Cheap enough to poll from a UI timer, which is the intended use — the send path raises no per-line events, precisely so that a 1 kHz stream does not turn into 1 000 UI notifications a second.

OnReceive(object, object)

Formats a sample, queues it for transmission, and publishes it downstream.

Declaration
protected override void OnReceive(object sender, object data)
Parameters
Type Name Description
object sender

The upstream block.

object data

A MathNet.Numerics.LinearAlgebra.Vector<T> of double, a double[], or a single double. Anything else is logged and ignored.

Overrides
BaseBlock.OnReceive(object, object)
Remarks

The sample is published even when the port is down, so downstream blocks and the CSV dumper see a continuous signal regardless of the link's state.

OpenWireDump(SerialSenderOptions)

Opens <Name>_wire.txt for the session, or returns null.

Declaration
private StreamWriter? OpenWireDump(SerialSenderOptions options)
Parameters
Type Name Description
SerialSenderOptions options
Returns
Type Description
StreamWriter
Remarks

Create truncates, so a file always describes exactly one run. Appending would blur session boundaries in a log whose whole value is being able to say "this is what the board received, in order, this time".

Read lets the file be tailed while the pipeline runs. Combined with autoflush, that makes it a live view of the link rather than a post-mortem.

Never throws. The constructor is the only place allowed to, and it is allowed to for bad configuration — a directory that cannot be written is not that, and must not take a working serial link down with it.

RaiseStatus(string)

Raises StatusChanged, absorbing anything a handler throws.

Declaration
private void RaiseStatus(string status)
Parameters
Type Name Description
string status
Remarks

A subscriber's exception would otherwise unwind the writer loop and stop transmission entirely — too steep a price for a misbehaving view model.

RecordError(Exception)

Records a failure for GetStats() and notifies listeners.

Declaration
private void RecordError(Exception ex)
Parameters
Type Name Description
Exception ex

SafeClose()

Closes the port, ignoring failures from a device that has already vanished.

Declaration
private void SafeClose()

Send(ReadOnlySpan<double>)

Formats one sample and queues it for the writer thread.

Declaration
public bool Send(ReadOnlySpan<double> sample)
Parameters
Type Name Description
ReadOnlySpan<double> sample

Field values, in wire order. An empty span is legal and emits a bare terminator, which is how a heartbeat or an end-of-record marker is sent.

Returns
Type Description
bool

true if the line was queued, false if it was dropped because the queue was full or the block is shutting down.

Remarks

Never blocks on the port: formatting is thread-local and the only lock held is the queue's, for the duration of one enqueue. A port stuck in a write does not slow this down.

SetConnected(bool)

Updates IsConnected and announces the transition once.

Declaration
private void SetConnected(bool connected)
Parameters
Type Name Description
bool connected

TryChangePort(string, int?, out string?)

Requests a switch to a different serial port, baud rate, or both.

Declaration
public bool TryChangePort(string portName, int? baudRate, out string? error)
Parameters
Type Name Description
string portName

Target port, e.g. "COM12" or "/dev/ttyUSB0". A bare number is expanded to COM{n} when the port is opened.

int? baudRate

New baud rate, or null to keep the current one.

string error

On failure, why the request was refused. null when this returns true.

Returns
Type Description
bool

true if the request was accepted and handed to the writer thread. Note what that does not promise: the new port may still fail to open, exactly as the original one may have. Watch IsConnected for the outcome.

Remarks

Asynchronous by design. This validates the request and returns; the writer thread picks it up at the top of its next iteration, closes the current port, and lets the ordinary open path take over — reset delay, reconnect back-off and status events all included. Doing the close inline would mean a UI click could block on a port stuck in a write.

Cost. Samples keep arriving while the switch happens, so the queue's drop policy applies throughout and a change is visible as a step in Dropped — at R Hz roughly R × resetDelayMs / 1000 − queueCapacity samples, the same arithmetic as the first connect. Nothing already queued is discarded on purpose: whatever fits is sent to the new port.

Allowed while connected. Deliberately: the case this exists for is a port that opened perfectly well and turned out to be the wrong device, which is precisely the case a "disconnect first" guard would lock out.

TryDequeue(int)

Takes the next queued line, waiting up to waitMs for one to arrive.

Declaration
private byte[]? TryDequeue(int waitMs)
Parameters
Type Name Description
int waitMs
Returns
Type Description
byte[]

The next line, or null if none arrived in time.

Remarks

Marks the line in-flight while still holding the lock, so it is never invisible to both the queue and _inFlight at the same time.

TryOpen()

Attempts to open the port, waiting out the reset delay on success and backing off on failure.

Declaration
private bool TryOpen()
Returns
Type Description
bool

true if the port is open and settled.

Remarks

Every wait goes through _stopSignal rather than Thread.Sleep, so disposal is not held hostage by a two-second reset delay or a reconnect back-off.

Validate(SerialSenderOptions)

Null-checks and validates options on the way into the constructor chain.

Declaration
private static SerialSenderOptions Validate(SerialSenderOptions options)
Parameters
Type Name Description
SerialSenderOptions options
Returns
Type Description
SerialSenderOptions

WriteToPort(byte[])

Writes one line, classifying any failure as either a stalled peer or a broken link.

Declaration
private void WriteToPort(byte[] line)
Parameters
Type Name Description
byte[] line
Remarks

A timeout leaves the port open. The receiver is not draining its buffer, which is a condition that clears on its own; closing would convert a slow consumer into a reconnect storm and lose far more than the one sample. Anything else means the link itself is gone, so the port is closed and the loop reopens it.

WriterLoop()

Drains the queue to the port for the block's lifetime, reopening as needed.

Declaration
private void WriterLoop()
Remarks

The loop owns the port exclusively. On a stop request it finishes whatever is already queued and exits; it does not attempt to open a closed port to flush, because waiting out a reset delay during shutdown would be worse than losing the backlog.

Events

StatusChanged

Raised on connect, disconnect and port failure. Fired from the writer thread.

Declaration
public event EventHandler<string>? StatusChanged
Event Type
Type Description
EventHandler<string>

Implements

INotifyPropertyChanged
INotifyPropertyChanging
ISubscriber
IPublisher
IBaseBlockProps
IJsonExportable
IDisposable
IAsyncDisposable

Search documentation

Start typing to search the documentation.