Base#

class rb_sdk.rb_sdk_cpp.ConnectOptions#

Bases: pybind11_object

Options for connecting this SDK process as a remote zenoh peer.

Passed to RBBaseSDK::connect() when the SDK runs on a different machine than the robot (for example a developer PC or an external vision PC). The SDK opens a zenoh listen port, registers its IP and port with the robot’s common service over HTTP, and keeps that registration alive with periodic heartbeats so that the robot’s services connect back to it and the process joins the robot’s zenoh mesh.

Only token and host are required; every other field has a usable default.

property heartbeat#

Heartbeat interval in seconds. When omitted, ttl / 2 is used, with a lower bound of 1 second. Must be shorter than ttl or the registration expires between heartbeats.

property host#

IPv4 address or hostname of the robot that runs the common service. The service is reached at http://<host>:8000. If this resolves to the local machine (“127.0.0.1”, “localhost”, “::1”, or an address of this host), connect() does nothing because the process is already in the local mesh.

property mesh_probe_interval#

0.5.

Type:

Delay in seconds between two consecutive echo probes. Default

property mesh_probe_timeout#

Time in seconds to wait for each individual echo probe reply. Default: 1.0.

property mesh_timeout#

Maximum time in seconds connect() waits for the zenoh echo check to prove that the robot can reach this process. When omitted, 5 seconds is used. If the check does not pass in time, the peer is unregistered and connect() returns no peer id.

property token#

Bearer <token>” on every peer registration, heartbeat, and unregistration request to the common service.

Type:

Bearer token sent as “Authorization

property ttl#

Peer registration time-to-live in seconds. The common service drops the peer if no heartbeat arrives within this time. Default: 30.

property zenoh_port#

Local TCP port on which this process listens for zenoh connections from the robot. When omitted, a free port is picked by the OS. Set it when a firewall only allows a known port.

class rb_sdk.rb_sdk_cpp.QueuedSample#

Bases: pybind11_object

property attachment#
property key#
property payload#
class rb_sdk.rb_sdk_cpp.RBBaseSDK(*args, **kwargs)#

Bases: pybind11_object

Common SDK base for zenoh transport, lifecycle, logging, and shared helpers.

Every domain SDK (RBManipulateSDK, RBAmrSDK, RBProgramSDK, RBRby1SDK, …) derives from this class. It provides:

  • One zenoh session per process. All SDK instances in the same process share a single rb_zenoh::ZenohClient. The session is opened lazily by the first constructor and is closed only when the last SDK instance is closed (reference counted per process id).

  • Raw and FlatBuffer-typed request/reply (query, query_one, query_all), publish/subscribe (publish, zenoh_subscribe, receive_one), and serving requests (zenoh_queryable).

  • Automatic recovery: query-style calls that fail with a transport error or no reply reconnect the shared session and retry exactly once.

  • Remote peer mode (connect/disconnect): lets a process running off- robot join the robot’s zenoh mesh through the common service.

  • Cross-domain helpers: program logs (log), PyFM step result checks (manipulate_return_value, validate_single_return_value), CAN bus access through the host_pcan service (connect_can, disconnect_can, transmit_can), and vendor vision client registries.

Threading: blocking network calls release the Python GIL when it is

held,

so other Python threads and zenoh callbacks keep running while a call waits for a reply. Calls are safe to make from multiple threads.

Fork safety: the zenoh runtime does not survive fork(). An instance that was created in a parent process is ignored by close() in a forked child; the child must create its own SDK instances.

Python binding: the Python class keeps one instance per (process id, class), so constructing the same SDK class twice in one process returns the same object. connect() and disconnect() return awaitables in Python, and zenoh_subscribe()/zenoh_queryable() are used as decorators.

close(*args, **kwargs)#

Releases this instance’s resources and closes the shared session when it is the last SDK.

In order: runs before_close(), decrements the per-process SDK reference count, then either calls disconnect() when a remote peer is registered (which always closes the shared session), or undeclares only this instance’s subscribers and queryables and closes the shared session if no other SDK instance is left.

Idempotent: later calls do nothing. Does nothing in a forked child for an instance created by the parent process. Called automatically by the destructor.

Python: also removes this object from the per-process instance cache, so the next construction of the same class creates a new object.

static close_all_for_pid()#

Closes every live SDK instance in the current process.

Calls close() on every RBBaseSDK (including derived SDKs and sub-SDKs held as members of an aggregate SDK) that was constructed in this process and is not closed yet. The reference count therefore reaches zero and the shared zenoh session is closed. Use it at shutdown when relying on destructor or garbage-collection order is not acceptable. Errors from individual close() calls are logged and skipped.

In Python this also clears the per-process instance cache, so the next construction creates a fresh object.

Returns:

Number of instances that were closed. 0 when called from a forked child.

Return type:

int

connect(options)#

Registers this process as a remote zenoh peer through the common service.

Use this when the SDK runs on a machine other than the robot. The steps are:

  1. If options.host resolves to this machine, return std::nullopt immediately: the process is already part of the local mesh.

  2. If a peer is already registered in this process, return its id.

  3. Pick the listen port (options.zenoh_port or a free port), add “tcp/0.0.0.0:<port>” to ZENOH_PEER_LISTEN_ENDPOINTS, and reopen the shared zenoh session so it listens on that port.

  4. POST this machine’s IP (the local address used to reach the host), port, and ttl to http://<host>:8000/zenoh/peer.

  5. Start a background keepalive thread that sends a heartbeat every options.heartbeat seconds (ttl / 2 by default) and re-registers the peer if the common service forgets it (for example after a restart).

  6. Publish echo probes on “muscat/zenoh/echo_req” until a matching reply arrives on “muscat/zenoh/echo_res” or options.mesh_timeout expires.

If the first registration request fails (for example the robot is still booting), the error is logged, the keepalive thread keeps retrying with exponential backoff (2 s up to 30 s), and std::nullopt is returned. If registration succeeds but the echo check times out, the peer is unregistered and std::nullopt is returned.

In Python this method returns an awaitable that runs the blocking work in a worker thread: use “await sdk.connect(options)”.

Parameters:

options – Remote peer registration and heartbeat options.

Returns:

Registered peer id, or std::nullopt when registration is skipped, still pending in the background, or the mesh echo check fails.

Raises:

std::runtime_error – If local IP/port detection or zenoh reconnection fails, or if unregistering the peer after a failed echo check fails.

Python: returns an awaitable that runs the blocking work in a worker thread (asyncio.to_thread). Use peer_id = await sdk.connect(options); the awaited value is the peer id string or None.

connect_can(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, *, channel: str, bitrate: int, fd: bool = False, dataBitrate: int = 0, receiveOwnMessages: bool = False, interface: str = 'pcan', flow_manager_args: rb_schemas.sdk.FlowManagerArgs | None = None) → rb_schemas.fbs_types.ipc.ResponseCANConnectTD#

Opens a CAN channel through the host_pcan service.

Sends a request on “muscat/can/connect” (1 s timeout) to the host service, which opens the bus on the robot PC. Each channel is opened once and stays open until disconnect_can() is called; frames are then sent with transmit_can().

In Python the keyword arguments use the FlatBuffer field names: channel, bitrate, fd, dataBitrate, receiveOwnMessages, interface, flow_manager_args (all keyword-only).

Parameters:
  • channel – CAN channel name as understood by the interface backend, for example “PCAN_USBBUS1”.

  • bitrate – Nominal (arbitration phase) bitrate in bit/s, for example 500000.

  • fd – Whether to open the channel in CAN-FD mode.

  • data_bitrate – CAN-FD data phase bitrate in bit/s. Used only when fd is true; 0 leaves it to the backend default.

  • receive_own_messages – Whether transmitted frames should be looped back to this channel’s receivers.

  • iface – CAN interface backend, defaults to “pcan” (PEAK-System adapters).

  • flow_manager_args – Optional PyFM step context. If provided, the step is marked done on success and an unsuccessful response raises.

Returns:

IPC::ResponseCANConnectT returned by the host service. Check success and message when flow_manager_args is not given, because a failure is then returned instead of raised.

Raises:
  • std::runtime_error – If no response is received, or if flow_manager_args is provided and the response reports failure (the exception message is the service’s message).

  • rb_zenoh::ZenohNoReply – , rb_zenoh::ZenohTransportError If the host service cannot be reached.

disconnect()#

Unregisters this process from the remote peer mesh and closes its shared zenoh session.

Reverses connect(): stops and joins the keepalive thread, sends DELETE /zenoh/peer/<peer_id> to the common service (a failure is logged, not thrown), undeclares this instance’s subscribers and queryables, and closes the shared zenoh session unconditionally. Other SDK instances in the process lose their session too; their next query-style call reopens it, but their subscribers and queryables are not restored.

In Python this method returns an awaitable: use “await sdk.disconnect()”.

Returns:

true when a peer registration or keepalive thread was active and has been torn down; false when there was nothing to disconnect.

Python: returns an awaitable (asyncio.to_thread). Use await sdk.disconnect(); the awaited value is the bool result.

disconnect_can(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, *, channel: str, flow_manager_args: rb_schemas.sdk.FlowManagerArgs | None = None) → rb_schemas.fbs_types.ipc.ResponseCANDisconnectTD#

Closes a CAN channel through the host_pcan service.

Sends a request on “muscat/can/disconnect” (1 s timeout). Same success and error handling as connect_can().

Parameters:
  • channel – CAN channel name previously passed to connect_can().

  • flow_manager_args – Optional PyFM step context. If provided, the step is marked done on success and an unsuccessful response raises.

Returns:

IPC::ResponseCANDisconnectT returned by the host service.

Raises:
  • std::runtime_error – If no response is received, or if flow_manager_args is provided and the response reports failure.

  • rb_zenoh::ZenohNoReply – , rb_zenoh::ZenohTransportError If the host service cannot be reached.

static instance() → rb_sdk.rb_sdk_cpp.RBBaseSDK#

Returns a process-local singleton base SDK instance.

The instance is created on first use and lives until process exit. Use it when only the shared transport and helpers are needed and no domain SDK is involved.

Returns:

Reference to the singleton. Do not delete it.

log(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, *, content: str, robot_model: str, level: str, disable_db: bool = False, flow_manager_args: rb_schemas.sdk.FlowManagerArgs | None = None) → None#

Emits a program log entry on the shared muscat log topic.

Publishes a muscat::RB_Program_LogT on “muscat/program/log”, where the common service’s program feature picks it up as a program log. The call is fire-and-forget (see publish()); it does not wait for the log to be stored.

Parameters:
  • content – Log message content.

  • robot_model – Name of the robot model associated with the log.

  • level – Log level: “INFO”, “WARNING”, “ERROR”, “USER”, “DEBUG”, or “GENERAL”. Matching is case-sensitive. Any other string leaves the log type at its FlatBuffer default.

  • disable_db – Kept for parity with the Python SDK; currently ignored.

  • flow_manager_args – Optional PyFM step context. If provided, the step is marked done after publishing the log.

publish(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, topic: str, payload: list[int], extra_attachment: str = '', congestion_control: int = 1, priority: int = 5, express: bool = False) → None#

Publishes raw bytes to a zenoh topic.

Non-blocking: the sample is put on the session’s transmit queue and sent by a background worker, so this returns before the data is on the wire. The queue holds up to 4096 samples; when it is full, the oldest pending sample is dropped. While the session is closing, samples are silently discarded. There is no delivery confirmation; use query_one() when an acknowledgement is needed.

Parameters:
  • topic – Zenoh key expression to publish to. Must not contain wildcards.

  • payload – Raw payload bytes.

  • extra_attachment – Optional attachment string appended to the sender metadata that subscribers receive.

  • congestion_control – zenoh-c congestion control: 1 = DROP (default, drop the sample when the network is congested) or 0 = BLOCK (wait until it can be sent). See CongestionControl.

  • priority – zenoh-c priority 1 (REAL_TIME) to 7 (BACKGROUND). Default 5 (DATA). See Priority.

  • express – If true, zenoh sends the sample immediately instead of batching it with others. Lowers latency at the cost of throughput.

Raises:

std::runtime_error – If topic is not a valid key expression.

query(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, topic: str, payload: list[int] | None = None, timeout_ms: int = 1000, target: int = 0) → list[rb_sdk.rb_sdk_cpp.RawReply]#

Sends a raw zenoh query and returns every raw reply.

Blocks until every matching queryable has answered or timeout_ms elapses, then returns all replies received, including error replies (RawReply::is_error is true for those). Unlike query_one(), getting no reply is not an error: the result is simply empty.

Parameters:
  • topic – Zenoh key expression to query. Wildcards fan the query out to every matching queryable.

  • payload – Optional raw payload bytes sent with the query.

  • timeout_ms – Query timeout in milliseconds.

  • target – zenoh-c query target: 0 = BEST_MATCHING (default), 1 = ALL, 2 = ALL_COMPLETE.

Returns:

Raw replies (key, payload, attachment, encoding, is_error) received before timeout. May be empty.

Raises:
  • rb_zenoh::ZenohTransportError – If the session is not open or the query cannot be sent, even after one reconnect and retry.

  • std::runtime_error – If topic is not a valid key expression.

query_all(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, topic: str, payload: list[int] | None = None, timeout_ms: int = 1000, target: int = 0) → list[rb_sdk.rb_sdk_cpp.RawReply]#

Sends a raw zenoh query and returns every successful raw reply.

Like query(), but error replies are dropped from the result. Use it to collect answers from several responders, for example with a wildcard key expression. Getting no reply is not an error.

Parameters:
  • topic – Zenoh key expression to query.

  • payload – Optional raw payload bytes sent with the query.

  • timeout_ms – Query timeout in milliseconds.

  • target – zenoh-c query target: 0 = BEST_MATCHING (default), 1 = ALL, 2 = ALL_COMPLETE.

Returns:

Successful raw replies received before timeout. May be empty.

Raises:

rb_zenoh::ZenohTransportError – If the session is not open or the query cannot be sent, even after one reconnect and retry.

query_one(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, topic: str, payload: list[int] | None = None, timeout_ms: int = 1000, target: int = 0) → rb_sdk.rb_sdk_cpp.RawReply#

Sends a raw zenoh query and returns one raw reply.

Waits for the query to finish (all replies or timeout_ms), then returns the first non-error reply. This is the usual call for a service RPC that has exactly one responder.

In Python, ZenohNoReply and ZenohTransportError keep their rb_zenoh exception types, which the FastAPI services map to HTTP 504 and 502.

Parameters:
  • topic – Zenoh key expression to query.

  • payload – Optional raw payload bytes sent with the query.

  • timeout_ms – Query timeout in milliseconds. With the single reconnect-and-retry, the worst case is about twice this value.

  • target – zenoh-c query target: 0 = BEST_MATCHING (default), 1 = ALL, 2 = ALL_COMPLETE.

Returns:

The first successful raw reply (key, payload, attachment, encoding, is_error = false).

Raises:
  • rb_zenoh::ZenohTransportError – If the session is not open or the query cannot be sent, even after one reconnect and retry.

  • rb_zenoh::ZenohNoReply – If no reply arrives before timeout, even after one reconnect and retry.

  • rb_zenoh::ZenohReplyError – If only error replies arrive. The message contains the first error payload. Not retried.

receive_one(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, topic: str, timeout_ms: int = 1000, self_sender_id: str = '') → rb_sdk.rb_sdk_cpp.QueuedSample#

Receives one raw queued sample from topic.

Declares a temporary subscriber, waits for the first sample published after this call, undeclares the subscriber, and returns the sample. Samples published before the call are not seen. Use it to wait for the next value of a periodic stream or for a one-off event.

Parameters:
  • topic – Zenoh key expression to receive from.

  • timeout_ms – Receive timeout in milliseconds. With the single reconnect-and-retry, the worst case is about twice this value.

  • self_sender_id – Sender id to ignore when filtering self-originated samples. Empty means no filtering.

Returns:

Raw queued sample (key, payload, attachment).

Raises:

rb_zenoh::ZenohNoReply – If no sample arrives before timeout, even after one reconnect and retry.

register_zenoh_queryable(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, topic: str) → None#

Registers an externally declared queryable topic for cleanup by close().

Same as register_zenoh_subscriber() for queryables. Registering a topic also makes later zenoh_queryable() calls for that topic on this instance a no-op, because the topic is treated as already declared.

Parameters:

topic – Zenoh key expression of the queryable.

register_zenoh_subscriber(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, topic: str) → None#

Registers an externally declared subscriber topic for cleanup by close().

Use this when a subscriber was declared on the shared zenoh session by some path other than zenoh_subscribe() and should still be removed when this instance is closed or disconnected. Cleanup is by topic, so every subscriber on that topic in the shared session is removed.

Parameters:

topic – Zenoh key expression of the subscriber.

transmit_can(self: rb_sdk.rb_sdk_cpp.RBBaseSDK, *, channel: str, arbitrationId: int, data: list[int] = [], dlc: int = 0, isExtendedId: bool = False, isRemoteFrame: bool = False, isFd: bool = False, bitrateSwitch: bool = False, isErrorFrame: bool = False, errorStateIndicator: bool = False, timestamp: float = 0.0, flow_manager_args: rb_schemas.sdk.FlowManagerArgs | None = None) → rb_schemas.fbs_types.ipc.ResponseCANTransmitTD#

Transmits one CAN/CAN-FD frame through the host_pcan service.

Sends a request on “muscat/can/transmit” (1 s timeout) carrying one IPC::CANMessageT. The channel must have been opened with connect_can(). The call returns once the host service has handed the frame to the bus, not when another node acknowledges it. Same success and error handling as connect_can().

In Python the keyword arguments use the FlatBuffer field names: channel, arbitrationId, data, dlc, isExtendedId, isRemoteFrame, isFd, bitrateSwitch, isErrorFrame, errorStateIndicator, timestamp, flow_manager_args (all keyword-only).

Parameters:
  • channel – CAN channel name previously passed to connect_can().

  • arbitration_id – CAN arbitration id: 11-bit (0x000-0x7FF) for a standard id, 29-bit for an extended id.

  • data – Frame payload bytes: up to 8 for classic CAN, up to 64 for CAN-FD.

  • dlc – Data length code. 0 lets the backend derive it from data.

  • is_extended_id – Whether arbitration_id is an extended (29-bit) id.

  • is_remote_frame – Whether the frame is a remote transmission request (no data).

  • is_fd – Whether the frame is CAN-FD.

  • bitrate_switch – Whether the CAN-FD data phase uses the faster data bitrate.

  • is_error_frame – Whether the frame is an error frame.

  • error_state_indicator – CAN-FD error-state indicator flag.

  • timestamp – Optional frame timestamp in seconds. 0 means unset.

  • flow_manager_args – Optional PyFM step context. If provided, the step is marked done on success and an unsuccessful response raises.

Returns:

IPC::ResponseCANTransmitT returned by the host service.

Raises:
  • std::runtime_error – If no response is received, or if flow_manager_args is provided and the response reports failure.

  • rb_zenoh::ZenohNoReply – , rb_zenoh::ZenohTransportError If the host service cannot be reached.

zenoh_queryable(topic, *, flatbuffer_req_T_class=None, flatbuffer_res_buf_size=None)#

Decorator that serves zenoh queries on a topic with the decorated function.

Usage:

@sdk.zenoh_queryable("my_plugin/add", flatbuffer_req_T_class=AddReqT,
                     flatbuffer_res_buf_size=256)
def on_add(*, req):
    return AddResT(result=req.a + req.b)

The handler runs on an rb_zenoh worker thread for every query. It is called with keyword arguments only, and receives only the names it declares:

  • key (str): the key expression of the query.

  • params (str): the selector parameters of the query.

  • payload / dict_payload (dict | None): the query payload parsed as UTF-8 JSON; None if absent or not JSON.

  • raw_payload (bytes): the raw query payload (b”” if absent).

  • req: the payload decoded with flatbuffer_req_T_class when it is given; None otherwise or if decoding fails.

  • attachment (str): the raw query attachment string.

The return value becomes the reply:

  • None: no reply is sent; the caller sees no answer from this queryable.

  • FlatBuffer object (has Pack), or a dict whose obj_payload is one: packed and sent. Requires flatbuffer_res_buf_size.

  • dict: sent as UTF-8 JSON.

  • bytes / bytearray / list[int]: sent as raw bytes.

  • Anything else raises TypeError.

If the handler raises, the error is printed and no reply is sent. If flatbuffer_req_T_class is given and the query has no payload, the handler is not called and no reply is sent.

Parameters:
  • topic – Zenoh key expression to serve.

  • flatbuffer_req_T_class – Optional FlatBuffer object class used to decode the request into req.

  • flatbuffer_res_buf_size – Initial FlatBuffer builder size in bytes, required when the handler returns a FlatBuffer object.

Returns:

A decorator that registers the handler and returns it unchanged.

A second declaration of the same topic on the same SDK is ignored with a warning. The queryable lives until close() or disconnect().

zenoh_subscribe(topic, *, flatbuffer_obj_t=None, opts=None)#

Decorator that subscribes the decorated function to a zenoh topic.

Usage:

@sdk.zenoh_subscribe("robot/state", flatbuffer_obj_t=StateT)
def on_state(*, topic, obj_payload, attachment):
    ...

The callback runs on an rb_zenoh dispatch worker thread (not the asyncio loop) for every sample. It is called with keyword arguments only, and receives only the names it declares:

  • topic (str): the key of the received sample.

  • mv (memoryview): the raw payload bytes.

  • dict_payload (dict | None): the payload parsed as UTF-8 JSON when flatbuffer_obj_t is not given; None if it is not JSON.

  • obj_payload: the payload decoded with flatbuffer_obj_t.InitFromPackedBuf when flatbuffer_obj_t is given, with bytes fields converted to str; None if decoding fails.

  • attachment (dict): {"sender": ..., "sender_id": ...} parsed from the sample attachment.

Parameters:
  • topic – Zenoh key expression to subscribe to. Wildcards are allowed.

  • flatbuffer_obj_t – Optional FlatBuffer object class (the ...T class) used to decode the payload into obj_payload.

  • opts – Optional rb_zenoh.schema.SubscribeOptions or rb_zenoh._core.CppSubscribeOptions (queue size, overflow policy, dispatch mode, rate limit). Defaults keep only the newest pending sample when the callback falls behind.

Returns:

A decorator. The decorator registers the function and returns it unchanged, so it can still be called directly.

The subscription lives until close() or disconnect() of this SDK. Exceptions raised by the callback are not propagated to the caller of zenoh_subscribe.

class rb_sdk.rb_sdk_cpp.RawReply#

Bases: pybind11_object

property attachment#
property encoding#
property is_error#
property key#
property payload#