Class UDPControlClient

UDP block for impedance-controlled actuators: streams a control signal together with the proportional and derivative gains the receiver should apply to it.

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:

{
  "ForwardToBlender": {
    "Type": "UDPControlClient",
    "Params": [ 3338, "float", "172.27.7.236", 3338, 6.0, 1.0 ],
    "Inputs": [ "Predictor" ],
    "DesiredRate": 50
  }
}

Params:

IndexDescription
0ReceivePort (int) — local port to listen on (1–65535).
1ParsingFormat (string) — "float" or "double".
2RemoteHost (string) — target IP for sending. Required.
3RemotePort (int) — target port for sending. Required.
4Kp (double, optional) — impedance proportional gain. Defaults to 0.
5Kd (double, optional) — impedance derivative gain. Defaults to 0.

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

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

Overview: A specialisation of UDPClient for closed-loop actuator control. It behaves identically on the receive path (packets are parsed into vectors and published downstream), but every outgoing packet appends two extra fields — Kp then Kd — after the payload channels. Use UDPClient for general-purpose UDP transport; this block exists so that control-specific framing does not leak into it.

Wire format: a payload of N channels is sent as | ch0 | … | chN-1 | kp | kd |, i.e. N + 2 fields. For the common single-channel case in Float that is 12 bytes, matching a Python receiver doing struct.unpack('<fff', data). There is no way to suppress the gains — a receiver that expects a bare payload will fail to unpack and drop the packet, so pair this block only with an endpoint that expects the gain fields.

Byte order: all fields are written little-endian ('<'), matching the convention of the control port — not the big-endian framing used by the update/config ports.

Runtime tuning: Kp and Kd are observable and writable from the UI. Both are snapshotted once per packet, so a concurrent edit can never split a gain pair across two packets.

Send-only asymmetry: a remote endpoint is mandatory. Unlike UDPClient there is no receive-only mode — a controller that cannot transmit has nothing to configure.

CSV logging: When a Path is specified, Dumper automatically logs every published vector via Publish(object). Note this records the payload only; the gains are not part of the published vector.

Constructors

UDPControlClient(string, double, int, ParsingFormat, string, int, double, double)

Initializes a new UDPControlClient block.

Declaration
public UDPControlClient(string name, double desiredRate, int receivePort, UDPControlClient.ParsingFormat format, string remoteHost, int remotePort, double kp, double kd)
Parameters
Type Name Description
string name

Display name.

double desiredRate

Processing rate in Hz (typically inherited).

int receivePort

Local port to listen on (1–65535).

UDPControlClient.ParsingFormat format

Binary parsing format.

string remoteHost

Remote host IP for sending. Required.

int remotePort

Remote port for sending. Required.

double kp

Initial impedance proportional gain.

double kd

Initial impedance derivative gain.

Exceptions
Type Condition
ArgumentOutOfRangeException

Thrown if either port is out of valid range.

ArgumentException

Thrown if remoteHost is missing or unparsable.

Fields

GainFieldCount

Number of gain fields appended to every outgoing packet.

Declaration
private const int GainFieldCount = 2
Field Value
Type Description
int

_disposed

Whether the block has been disposed.

Declaration
private bool _disposed
Field Value
Type Description
bool

_format

Binary parsing format for UDP packets.

Declaration
private readonly UDPControlClient.ParsingFormat _format
Field Value
Type Description
UDPControlClient.ParsingFormat

_kd

Backing field for Kd.

Declaration
private double _kd
Field Value
Type Description
double

_kp

Backing field for Kp.

Declaration
private double _kp
Field Value
Type Description
double

_lastChannelCount

Channel count of the last payload, used to warn on an unexpected width.

Declaration
private int _lastChannelCount
Field Value
Type Description
int

_receiver

UDP client for receiving data on the local port.

Declaration
private readonly UdpClient _receiver
Field Value
Type Description
UdpClient

_remoteEndpoint

Remote endpoint the control packets are sent to. Never null.

Declaration
private readonly IPEndPoint _remoteEndpoint
Field Value
Type Description
IPEndPoint

_sendBuffer

Preallocated send buffer, reallocated whenever the channel count changes.

Declaration
private byte[]? _sendBuffer
Field Value
Type Description
byte[]

_sendLock

Semaphore guarding concurrent send operations.

Declaration
private readonly SemaphoreSlim _sendLock
Field Value
Type Description
SemaphoreSlim

_sender

UDP client for sending data to the remote endpoint.

Declaration
private readonly UdpClient _sender
Field Value
Type Description
UdpClient

Properties

BytesReceived

Total bytes received.

Declaration
public long BytesReceived { get; private set; }
Property Value
Type Description
long

BytesSent

Total bytes sent.

Declaration
public long BytesSent { get; private set; }
Property Value
Type Description
long

DumpFilePrefix

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

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

FieldSize

Size in bytes of a single field on the wire.

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

Format

Current parsing format.

Declaration
public UDPControlClient.ParsingFormat Format { get; }
Property Value
Type Description
UDPControlClient.ParsingFormat

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

Kd

Impedance derivative gain, sent as the last field of every packet.

Declaration
public double Kd { get; set; }
Property Value
Type Description
double
Remarks

Read once per packet on the send path; safe to write from the UI thread. Takes effect on the next packet.

Kp

Impedance proportional gain, sent as the second-to-last field of every packet.

Declaration
public double Kp { get; set; }
Property Value
Type Description
double
Remarks

Read once per packet on the send path; safe to write from the UI thread. Takes effect on the next packet — there is no handshake, so the receiver simply sees the new value arrive.

PacketsReceived

Total UDP packets received.

Declaration
public long PacketsReceived { get; private set; }
Property Value
Type Description
long

PacketsSent

Total UDP packets sent.

Declaration
public long PacketsSent { get; private set; }
Property Value
Type Description
long

PayloadChannels

Number of payload channels in the most recent outgoing packet, or -1 before the first send. The packet carries this many fields plus the two gains.

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

ReceivePort

Local port the receiver is listening on.

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

RemoteHost

Remote host IP the control packets are sent to.

Declaration
public string RemoteHost { get; }
Property Value
Type Description
string

RemotePort

Remote port the control packets are sent to.

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

Viz

Visualization helper for binding received/sent data to the UI scope.

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

Methods

AsyncReceiveCallback(IAsyncResult)

Handles an incoming UDP packet, parses it, and publishes the result.

Declaration
private void AsyncReceiveCallback(IAsyncResult ar)
Parameters
Type Name Description
IAsyncResult ar

ConfigureInput(IServiceProvider, JsonModel)

Creates a UDPControlClient from a JSON pipeline definition.

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

Service provider for dependency injection.

JsonModel m

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

Returns
Type Description
UDPControlClient

A configured UDPControlClient instance.

Exceptions
Type Condition
ArgumentException

Thrown if required parameters are missing or invalid.

Dispose()

Disposes UDP sockets, semaphore, visualization, and base class resources (including CSV dumper if configured).

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

FillSendBuffer(byte[], Vector<double>, double, double)

Writes the payload channels followed by the two gains into buffer as little-endian fields of the configured format.

Declaration
private void FillSendBuffer(byte[] buffer, Vector<double> vector, double kp, double kd)
Parameters
Type Name Description
byte[] buffer
Vector<double> vector
double kp
double kd
Remarks

Split out of SendUdpAsync(Vector<double>) because a Span<T> local cannot be declared in an async method. Callers must hold the send lock and must size buffer exactly.

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()

OnReceive(object, object)

Sends upstream data with the current gains appended, and publishes the payload downstream.

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

The upstream block.

object data

Expected to be a MathNet.Numerics.LinearAlgebra.Vector<T> of double. Other types are logged and ignored.

Overrides
BaseBlock.OnReceive(object, object)
Remarks

Only the payload is published and visualised — the gains are transmission metadata, not part of the dataflow.

ParseAsDoubles(byte[])

Parses a byte array as 64-bit doubles and returns a vector.

Declaration
private static Vector<double> ParseAsDoubles(byte[] bytes)
Parameters
Type Name Description
byte[] bytes
Returns
Type Description
Vector<double>

ParseAsFloats(byte[])

Parses a byte array as 32-bit floats and returns a double vector.

Declaration
private static Vector<double> ParseAsFloats(byte[] bytes)
Parameters
Type Name Description
byte[] bytes
Returns
Type Description
Vector<double>

ParseFormat(string?)

Parses a format string into a UDPControlClient.ParsingFormat enum value.

Declaration
private static UDPControlClient.ParsingFormat ParseFormat(string? format)
Parameters
Type Name Description
string format
Returns
Type Description
UDPControlClient.ParsingFormat

ParseReceivedData(byte[])

Parses received bytes into a vector. Returns null on failure.

Declaration
private Vector<double>? ParseReceivedData(byte[] bytes)
Parameters
Type Name Description
byte[] bytes
Returns
Type Description
Vector<double>

SendUdpAsync(Vector<double>)

Serialises and sends a control packet asynchronously over UDP.

Declaration
private void SendUdpAsync(Vector<double> vector)
Parameters
Type Name Description
Vector<double> vector
Remarks

Payload channels are written little-endian in order, followed by Kp and Kd. Both gains are snapshotted once per packet so a concurrent UI edit cannot split across two packets.

StartReceiving()

Starts the asynchronous receive loop.

Declaration
private void StartReceiving()

Events

PacketReceivedEvent

Raised after a packet is received.

Declaration
public event EventHandler<PacketEventArgs>? PacketReceivedEvent
Event Type
Type Description
EventHandler<PacketEventArgs>

PacketSentEvent

Raised after a packet is sent.

Declaration
public event EventHandler<PacketEventArgs>? PacketSentEvent
Event Type
Type Description
EventHandler<PacketEventArgs>

StatusChanged

Raised when the block's status changes (e.g. errors).

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.