Dataflow: ports and messages¶
Data moves between nodes over data edges: an upstream node publishes a ROS 2 message on one of its output ports, the engine carries it to the connected input port, and the downstream node reads it. After reading this page you can read inputs and write outputs correctly, know what get_data() returns in every situation, react to a message the moment it arrives, and inspect the ports the engine wired for your node.
Ports are declared in the schema, wired by the engine¶
Python MQTT input setup waits for broker acknowledgement before marking the input ready. An unconfirmed subscription fails that transport's setup; the SDK does not report its input as connected.
Every data port is declared once, in the node's <module>_schema.json, under inputs or outputs with edgeType: 1 and a rosType such as std_msgs/msg/Float32. The schema file reference describes the format and the port-key convention (lowercase snake_case keys).
When the engine configures your node it passes, for every port, the transport and the topic it should use. The SDK sets all of that up before your on_configure() runs. Your code never sees topics; it addresses ports by their schema key:
msg = self.get_data("a") # input port "a"
self.publish("sum", Float32(data=1.0)) # output port "sum"
The key must match the schema exactly. What happens when it does not:
| Call | Key not declared / not wired | Effect |
|---|---|---|
self.get_data("typo") |
Input unknown | Returns None immediately and writes a debug log line. Nothing raises. |
self.publish("typo", msg) |
Output unknown | Raises DataFlowException("Unknown output target: typo"). Inside on_execute() this ends the run with an error and fires the node's error trigger. |
The math tutorial node shows the whole read-compute-publish cycle:
def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
try:
# get_data() returns the last message received on the port, or None
# when nothing has arrived yet (or the port is not connected).
msg_a = self.get_data("a")
msg_b = self.get_data("b")
if msg_a is None:
self.log_warning("No message on input 'a' yet, skipping this run")
return
if msg_b is None:
self.log_warning("No message on input 'b' yet, skipping this run")
return
total = float(msg_a.data) + float(msg_b.data) + self.offset
# publish() needs a ROS 2 message object, never a bare float.
self.publish("sum", Float32(data=total))
self.log_info(f"{msg_a.data} + {msg_b.data} + {self.offset} = {total}")
except Exception as exc:
raise NodeExecutionError(f"MathAddNode failed: {exc}") from exc
Messages are ROS 2 objects¶
The value that travels over a data edge is always a ROS 2 message instance of the port's rosType. Import the class from the message package (from std_msgs.msg import Float32, from sensor_msgs.msg import CompressedImage) and work with its fields:
- Reading:
get_data()returns the deserialized message object, so astd_msgs/msg/Stringinput gives youmsg.data, asensor_msgs/msg/CompressedImagegives youmsg.formatandmsg.data. - Writing:
publish()needs a message object. Wrap plain values:String(data="ok"),Float32(data=total).
The SDK turns a rosType of pkg/msg/Type into the Python import pkg.msg.Type when it builds the subscriptions, so the message package must be installed in your node image. The standard ROS 2 packages (std_msgs, sensor_msgs, geometry_msgs, ...) are part of the SDK base image; see Message types for the full list and the types the editor can visualize.
A bare str, float, dict or NumPy array is not a message
publish() does not type-check its argument. On the MQTT transport the serializer fails, the error is written to the node log and the message is dropped, so the downstream node simply never receives anything. On the ROS transport the failure raises out of publish() instead. Either way, always wrap values in the message class the schema declares for that port.
Publish exactly the type the port declares. The receiving side deserializes with a type as well; if the two ends disagree, deserialization fails, the receiving node logs an error and its get_data() returns None.
Reading inputs: get_data(port)¶
get_data() takes one argument, the input port key, and has no timeout parameter. It returns the deserialized message or None. The SDK keeps one slot per input port, overwritten by every incoming message, and get_data() reads that slot:
| Situation | get_data("port") returns |
Delay |
|---|---|---|
| Key unknown | None |
none |
| Declared input, but no message has arrived since configure | None |
waits up to 1 s for the first message |
| At least one message has arrived | the most recent message | none |
| Called again without a new message | the same message again | none |
| Asynchronous Stop accepted, teardown still pending | the old value may remain briefly; new external input is rejected | no retention guarantee |
| Stop teardown completed | slots are emptied; reads return None |
none |
| Node re-configured | slots are emptied and re-armed; the first read waits again | up to 1 s |
Declared disconnected inputs have their own input slot and wait for their first value. They can receive typed JSON input without a data edge.
Two consequences shape how you write on_execute():
- Guard for
None. A node is frequently triggered before its upstream neighbour has published. Log a warning and return; do not raise. - Repeated reads return the last value, not the next one. The SDK never clears the slot after a read, so two executions with no new message in between see the same object. If your node must process each message once, compare something inside the message yourself (a header stamp, a sequence number, or keep a reference to the last object you handled).
Typed JSON input¶
The platform can commit a typed JSON value to a declared input of a configured Python or C++ node. The message package must be installed in the node image.
The request names the input's schema key and carries rosType plus payloadJson.
For a std_msgs/msg/String input, the payload is {"data":"hello"}. For
std_msgs/msg/Int64, use {"data":"9223372036854775807"}. An empty object uses
the message's generated defaults.
Typed JSON also supports nested objects and arrays of scalars or messages. Generated defaults apply at every depth, including each object in an array.
Unknown fields, duplicate fields, malformed JSON, incorrect types and
out-of-range values are rejected before changing any part of the input or
invoking a handler. Schema errors identify the field, such as
$.records[0].count. See message types
for array bounds and numeric rules.
Successful acknowledgement confirms that the value is available to ordinary
reads. Waiting readers wake, and registered message handlers run with their
usual transport representation. Injection does not submit on_execute().
Native publications subsequently replace the value in the same input slot.
Paused nodes can receive data; a stopped run must be configured through the
normal lifecycle before it can receive external input again.
A timeout or disconnect can leave acceptance uncertain. There is no automatic replay; an explicit retry may repeat message-handler effects.
Pause does not stop the dataflow
Input slots keep updating while the node is PAUSED, so after resume get_data() returns the newest message, not the one from before the pause. See Lifecycle and states for the pause model.
The 1 s wait applies before the first message on any declared input, including a disconnected input. It runs on the thread that called get_data(), normally your on_execute() worker, so reading five empty inputs in a row can take five seconds.
Writing outputs: publish(port, msg)¶
publish() takes the output port key and the message object, and returns nothing. The engine may request more than one transport for one output; a single publish() call covers all of them. You can call it from on_execute(), from a handler registered with register_handler(), or from any thread your node owns, for example a camera loop started in on_configure().
The last value of every output is cached¶
Every publish() call that returns also stores the message as the last value of that port. On MQTT a serialization failure is only logged, so the value is cached even though it never left the node:
| Method | Returns |
|---|---|
get_cached_output(port) |
The last object passed to publish(port, ...), or None if the port was never published. |
get_cached_output_topics() |
The list of output port keys that have a cached value. |
The platform uses this cache to show a viewer who opens the data visualization late the most recent frame. You can use it yourself, for instance to re-publish the last state after a reconnect or to check in a test what the node emitted last.
Reacting to a message as it arrives: register_handler()¶
on_execute() is pull-based: it runs when a trigger arrives and reads whatever is in the input slots. When a node must react to every incoming message on a port, register a callback:
def on_configure(self, config, dynamic_config=None) -> None:
# Register once, here. The dataflow adapters exist only from this point on.
self.register_handler(self._on_command, "command_in")
def _on_command(self, _payload) -> None:
try:
# Ignore the raw argument; read the deserialized message through get_data().
msg = self.get_data("command_in")
if msg is not None:
self.publish("status_out", String(data=f"got {msg.data}"))
except Exception as exc:
self.log_error("command handler failed", exception=exc)
Rules that follow from how the SDK implements handlers:
| Rule | Why |
|---|---|
Register in on_configure(), once per port. |
Before configure there is no dataflow adapter, and register_handler() then silently does nothing. Registering in on_execute() means the handler only exists after the first trigger. Re-configure recreates the adapters, and on_configure() runs again, so the handler is re-registered by the same code. |
Read the message with self.get_data(port) inside the handler. |
The argument the SDK passes is the transport payload: a deserialized message on ROS, but the raw serialized payload on MQTT. By the time the handler runs, the slot for that port is already filled, so get_data() returns the new message without waiting. |
| Keep it short and never let it raise. | Native messages call handlers on the transport receive thread. Typed JSON input calls them on its request thread, after committing the value. A slow injected-input handler delays acknowledgement and lifecycle operations on that node. On the ROS transport an exception escapes into the subscription loop and stops message delivery for the node. |
| Synchronize shared state. | The handler runs concurrently with on_execute() and on_stop_execution(). Use a threading.Lock around anything both sides touch. |
register_handler(callback) without a port key installs a catch-all with the signature callback(input_name, msg, topic_info) that receives messages from every port without a dedicated handler. The per-port form is almost always what you want.
wait_for_message() is not implemented
NodeBase.wait_for_message(port, timeout) exists on the class, but every production transport raises NotImplementedError from it. Do not call it. Use get_data() in on_execute() or a handler from register_handler().
Transports: what the engine decides for you¶
You never choose a transport in node code or in the schema. For each connection the engine tells the SDK which transport to use, and the SDK routes the port to the matching adapter:
| Engine's choice for the connection | SDK behaviour |
|---|---|
| ROS | The message is published or received through an rclpy node the SDK owns; no serialization detour. |
| MQTT | The message is CDR-serialized, base64-encoded, wrapped in a small JSON envelope and sent through the platform's MQTT broker. |
| Zenoh | The message is CDR-serialized and sent through the Zenoh router named in service_config.yaml, with no envelope around it. |
| Unspecified | MQTT. |
| Several transports at once (outputs only) | One publish() sends on each of them. |
Since SDK 2.50.2
Configure also fails when a port name would put a wildcard or reserved character into an MQTT or Zenoh topic. Before, such a port configured and then received every output of the upstream node or never delivered.
| Transport | Rejected characters | Message |
|---|---|---|
| MQTT | #, + |
Output '+' maps to MQTT topic 'uuid/node-0/+', which contains reserved character '+'; rename the port |
| Zenoh | *, $, ?, # |
Output '*' maps to Zenoh key expression '...', which contains reserved character '*'; rename the port |
The check covers the output topic <node id>/<output> and every input's source topic, so an upstream output named + fails on the downstream input as well (Input '<name>' subscribes to ...; rename the upstream output port). Triggers follow the same rule and raise TriggerFlowException. It raises DataFlowException before any adapter is torn down, so an invalid reconfigure leaves the running node unchanged. Topic names are unchanged. Python and C++ behave the same.
Python Zenoh outputs now publish on the node id like C++ and MQTT; before, they never reached a subscriber.
Since SDK 2.50.1
Renaming a node in the frontend to any free text, including spaces, works on the ROS transport. The SDK derives a valid ROS node name from the display name and the node id; earlier versions failed at configure with InvalidNodeNameException.
On ROS the SDK also checks the topics before it creates the ROS node and raises a DataFlowException at configure when:
| Case | Message |
|---|---|
| Two outputs map to one topic after sanitizing, such as "pose out" and "pose_out" | Outputs 'pose out' and 'pose_out' both map to ROS topic '<topic>'; rename one of them |
An output topic or an input's source topic has an empty segment, from a port name ending in / or containing // |
... has an empty segment; an output port name contains '/' |
The check runs before any adapter is torn down, so a failed configure or reconfigure leaves an already configured node running unchanged. Several inputs subscribing to one source, absolute topics with a leading /, and the same name on two different transports stay valid. Name ports [A-Za-z][A-Za-z0-9_]*: that is valid on every transport and never needs sanitizing.
Before 2.40.1 a port the engine had resolved to Zenoh was published on ROS
topics instead, or was served by nothing at all, so Zenoh edges did not
work. If your graph has Zenoh edges, your node needs 2.40.1 or newer and a
zenoh: block in its service_config.yaml.
ROS and MQTT graphs behave the same on both sides of that version.
If one transport your node uses is unreachable when the node configures itself, that transport's ports report as not connected and the rest of the node keeps running. A Zenoh router that is down no longer stops a node whose other ports are on MQTT.
What this means for you: the same node runs unchanged on the edge next to a robot and in the cloud. But message size still matters. Base64 adds about one third to a payload, and every MQTT message passes through the broker, so high-rate images or point clouds are cheap over ROS and expensive over MQTT. If your node emits large messages at high rate, compress them (sensor_msgs/msg/CompressedImage instead of sensor_msgs/msg/Image) and prefer publishing only what downstream nodes need.
If your node needs its own ROS 2 subscriptions or publishers besides the ports (a recorder capturing extra topics, for example), self.get_ros_node() returns the rclpy node the SDK uses for ROS ports. It returns None when the node has no ROS-routed port, so check before use. Override it in a subclass that manages its own rclpy node.
Inspecting the wiring at runtime¶
These methods are read-only views on what the engine configured. They are handy for logging in on_configure() and for skipping work on ports nobody listens to.
| Method | Returns | Before the node is configured |
|---|---|---|
get_inputs(), get_outputs() |
dict[str, NodeIO] of data ports by key; each entry carries rosType and edgeType. |
{} |
get_trigger_inputs(), get_trigger_outputs() |
Same for the trigger ports. | {} |
get_connected_ports() |
dict[str, bool]: for every input port, whether a source is wired to it. Outputs are not listed. |
{}; NodeStateError when no dataflow exists yet (in a unit test without initialize()) |
get_input_topics(), get_output_topics() |
dict[str, dict] per port with topic_name and ros_type. Inputs, and outputs routed over ROS, also carry the imported msg_type class. |
{}; NodeStateError when no dataflow exists yet |
get_node_id(), get_node_name() |
The node's id and display name in the graph. | NodeStateError |
get_node_class_name() |
The Python class name. | always available |
get_ros_node() |
The SDK's rclpy node, or None without ROS ports. |
None |
execute_background() also exists on NodeBase. It starts one execute() on a daemon thread and returns at once; the engine's gRPC layer uses it to run a node without a trigger. Do not call it from node code; a run started this way bypasses the single-worker execute queue.
Logging¶
Use the logging methods on NodeBase, never print(). They write to the node service's log through one shared SDK logger, so when a service hosts several nodes, put the node or port name into the message text.
| Method | Use for |
|---|---|
log_debug(message) |
Per-message detail you only want while diagnosing. |
log_info(message) |
Milestones: configured, connected, published a result. |
log_warning(message) |
Recoverable situations: an input is still empty, a retry happened. |
log_error(message, exception=None) |
Failures. Pass the exception; its text is appended to the message. |
Log at most a line or two per execution in on_execute() and none per message in a handler at info level, or the node log becomes unreadable at camera frame rates.
Image inputs and visualization¶
While a viewer watches a segmentation output of your node, every sensor_msgs/msg/CompressedImage or sensor_msgs/msg/Image you read with get_data() on an input port is also used as the background frame under the rendered masks. You do not write any code for this; it is described in Data visualization.
Testing the dataflow without a platform¶
In unit tests replace the SDK's adapters with the in-memory FakeDataFlow from examples/_testing/fake_dataflow.py: put a message per input port into input_ports, run on_execute() and assert on published[port]. It latches like the real adapters, so the "same message twice" behaviour is testable too. Testing shows the complete setup, including the ROS stubs needed on a machine without ROS.