Tutorial 1: Math node¶
In this tutorial you build MathAddNode, a node with two Float32 data inputs, one Float32
output and one static configuration value. After it you can declare data ports in a schema,
read a static default in on_configure(), read and publish ROS 2 messages in on_execute(),
run the node in the Mock Runner, and cover it with a pytest that runs without ROS 2. Every code
block on this page comes from examples/tutorials/math_node/ in the SDK repository, and the
test at the end is what keeps the page and the code in step.
What you build¶
| Port | Direction | rosType |
Purpose |
|---|---|---|---|
start, stop |
trigger in | Start, Stop |
The platform runs and stops the node through these. |
a, b |
data in | std_msgs/msg/Float32 |
The two summands. |
sum |
data out | std_msgs/msg/Float32 |
a + b + offset. |
start, error |
trigger out | Start, Error |
Fired by the SDK after a successful or a failed run. |
offset is a static configuration value with the default "0.0". It arrives as a string and the
node parses it once, in on_configure().
The node lives in one directory holding a module, a schema and a test, named after the directory:
math_node/
math_node.py # class MathAddNode(NodeBase)
math_node_schema.json # executionContext.className: "MathAddNode"
test_math_node.py # pytest, runs without ROS 2
1. Declare the ports: the schema¶
Write the schema first. It fixes the port keys your code will use and it is what the palette shows to the graph author.
{
"id": "Examples",
"name": "MathAddNode",
"type": 1,
"description": "Adds the Float32 inputs a and b plus a static offset and publishes the sum",
"tags": ["example", "tutorial", "math"],
"inputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"stop": { "rosType": "Stop", "edgeType": 2 },
"a": { "rosType": "std_msgs/msg/Float32", "edgeType": 1 },
"b": { "rosType": "std_msgs/msg/Float32", "edgeType": 1 }
},
"outputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"error": { "rosType": "Error", "edgeType": 2 },
"sum": { "rosType": "std_msgs/msg/Float32", "edgeType": 1 }
},
"errorOutputs": {},
"dataFlowEntry": {},
"triggerFlowEntry": {},
"executionContext": {
"type": "EXECUTION_TARGET_TYPE_GRPC",
"target": "",
"className": "MathAddNode"
},
"configuration": {
"offset": "0.0"
}
}
What to take from it:
| Part | Rule applied here |
|---|---|
executionContext.className |
"MathAddNode", exactly the Python class name. |
id |
Palette category. "Examples" here; use your own group name. |
Data ports a, b, sum |
Lowercase snake_case keys; rosType is the ROS 2 type as pkg/msg/Type; edgeType is 1. The keys are the strings you pass to get_data and publish. |
| Trigger ports | Inputs start and stop, outputs start and error. rosType holds the trigger type name. There is no stop output: the SDK would fire it after every successful run and stop the downstream node. |
configuration |
Static defaults, strings only. "offset": "0.0" must parse with float(). |
The complete field list and the port-key convention are in the schema file reference.
2. Write the node class¶
Imports¶
from typing import Optional
from google.protobuf.internal.containers import MessageMap, ScalarMap
from neuraverse.models.v1.gen.business.node_graph_pb2 import NodeConfigEntry
from std_msgs.msg import Float32
from neuraverse_sdk.node_base import NodeBase
from neuraverse_sdk.trigger.i_trigger import TriggerContext
from neuraverse_sdk.utils.exceptions import NodeExecutionError
Float32 is the ROS 2 message class behind std_msgs/msg/Float32; both reading and publishing
go through it. ScalarMap, MessageMap and NodeConfigEntry only type the on_configure
parameters. NodeExecutionError is what a failed run raises.
The class¶
class MathAddNode(NodeBase):
"""Adds the ``a`` and ``b`` inputs plus a static ``offset`` and publishes ``sum``."""
def __init__(self) -> None:
super().__init__()
# Plain defaults only; real setup happens in on_configure().
self.offset: float = 0.0
def on_configure(
self,
config: ScalarMap[str, str],
dynamic_config: Optional[MessageMap[str, NodeConfigEntry]] = None,
) -> None:
# ``config`` is the static string map from the schema's "configuration"
# block, so every value arrives as text and must be parsed here.
# A value that is not a number raises ValueError and fails configuration.
self.offset = float(config.get("offset", "0.0"))
self.log_info(f"MathAddNode configured with offset={self.offset}")
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
def on_stop(self, trigger_context: Optional[TriggerContext] = None) -> None:
self.log_info("MathAddNode stopped")
def on_get_configuration(self) -> dict[str, NodeConfigEntry]:
# This tutorial uses only the static "configuration" block, so there
# are no typed entries to show in the UI.
return {}
__init__ sets a plain default and nothing else. All setup that depends on configuration
belongs in on_configure(), because the SDK calls that hook again on every re-configure of the
same object. on_get_configuration returns an empty dict because this node has no typed settings
to show in the editor. The three hooks are required; leaving one out makes the class abstract and
it cannot be instantiated. This node runs to completion on every trigger, so it needs neither
on_stop_execution nor on_cleanup.
Read the static default: on_configure¶
def on_configure(
self,
config: ScalarMap[str, str],
dynamic_config: Optional[MessageMap[str, NodeConfigEntry]] = None,
) -> None:
# ``config`` is the static string map from the schema's "configuration"
# block, so every value arrives as text and must be parsed here.
# A value that is not a number raises ValueError and fails configuration.
self.offset = float(config.get("offset", "0.0"))
self.log_info(f"MathAddNode configured with offset={self.offset}")
Keep both parameters. The SDK always passes two positional arguments: config, the string map
from the schema's configuration block, and dynamic_config, the typed values from the editor
or None. A one-parameter override raises TypeError during configure and the node never
reaches the configured state.
Every value in config is a string, so the node converts it with float(). If the graph author
enters text that does not parse, float() raises ValueError, the SDK logs
Failed to update configuration: ..., moves the node to the error state and reports the failure.
That is the behaviour you want for bad input; do not swallow the exception. Typed settings with
widgets (toggle, slider, list) are introduced in the image node tutorial and
explained in Configuration.
Read, compute, publish: on_execute¶
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
Line by line, the rules this method follows:
self.get_data("a")takes only the port key. It returns the lastFloat32message received ona, orNonewhen nothing has arrived yet or the port is not connected. There is no timeout parameter.- Guard for
None. A node is often triggered before its upstream neighbour has published. Log a warning and return; do not raise, and do not publish a guessed value. - Read the payload through
msg.data. The message object is not a number;float(msg_a)fails.float(msg_a.data)is what you want. - Publish a message object.
Float32(data=total)is required. A barefloatis not a ROS 2 message: depending on the transport the publish is logged and dropped or raises, and in both cases the value never reaches the next node. - Wrap the body in
try/exceptand raiseNodeExecutionError. Any exception that leaveson_executeends the run with an error; re-raising asNodeExecutionErrorwith a clear message is what shows up in the node logs.
Repeated executions without a new message see the same object again. The SDK never clears the
slot behind get_data() after a read, so two runs in a row publish the same sum twice. If your
node must handle every message exactly once, compare something inside the message yourself. The
full behaviour table is in Dataflow.
3. Run it in the Mock Runner¶
Start the Mock Runner as in the Quickstart. Then make the node visible to it in one of two ways:
cp -r <sdk-repo>/examples/tutorials/math_node node-template/src/
The backend mounts src/ and imports every node module under it. Test files
(test_*.py) are skipped, so the test can stay next to the node.
From a checkout of the Mock Runner project, point the backend at the tutorials instead of the default sources:
SRC_DIRPATH=<sdk-repo>/examples/tutorials docker compose up -d
In the browser:
- Click Reload Code. MathAddNode appears in the Available Nodes panel.
- Drag it onto the canvas, click Init, then Configure.
- Select the node and open the Inputs tab. Under Current Inputs type
2next toaand click Override; type3next toband click Override. The Mock Runner turns the text into aFloat32message withfloat(), so letters are rejected silently and the port keeps its previous value. - Click Execute.
| Tab | What you see |
|---|---|
| Outputs | 5.0 on sum, one row per publish call. |
| Node Logs | MathAddNode configured with offset=0.0, then 2.0 + 3.0 + 0.0 = 5.0. |
Click Execute before both overrides are in place and the node logs
No message on input 'b' yet, skipping this run and publishes nothing. That is the None
guard at work.
The static configuration block is not delivered in the Mock Runner
The Mock Runner builds the configure request from your schema's ports only, so config
arrives as an empty map and offset stays at the 0.0 fallback from
config.get("offset", "0.0"). On the platform the map holds the schema defaults, edited by
the graph author. To test the parsing path use the pytest in step 4, which passes the
parsed schema to on_configure().
What happens on an engine¶
In the Mock Runner you click Execute. On the platform the node is part of a graph and the SDK drives it:
| Event | What the SDK does |
|---|---|
A Start trigger arrives |
Submits execute() on the node's single-worker executor and calls your on_execute(trigger_context=...). Runs queue; two never overlap. |
on_execute returns |
Puts the node back into the configured state and fires every output port of type Start. Two Start outputs mean two downstream nodes run; that is the fan-out. |
on_execute raises |
Attaches the exception type and message to the outgoing trigger context, fires every output port of type Error, moves the node to the error state and logs Execution error: .... Nothing is published for that run beyond what happened before the exception. |
A Stop trigger arrives |
Runs on_stop_execution() on a node that overrides it (the run ends, the node stays configured); a node without it is torn down as before 2.43.0. |
Because the SDK fires the Start outputs only after a successful return, an early return on a
missing input still counts as success and still triggers the next node. If downstream nodes
must not run without a sum, raise instead of returning and wire the error output to a handler.
The cloud upload tutorial shows that pattern; Triggers
has the full model.
4. Test it with pytest¶
The test drives the node the way the engine does, without ROS 2 installed: on_configure gets
the string map parsed from math_node_schema.json, on_execute reads latched inputs through
get_data() and the assertions check that a real Float32 object was published.
"""Tests for the tutorial MathAddNode.
Runs without a ROS installation: the shared stubs shim ``std_msgs`` and the
transport libraries before the node module is imported. The node is driven
exactly like the engine drives it: ``on_configure`` gets the static string map
parsed from ``math_node_schema.json``, ``on_execute`` reads the latched inputs
through ``get_data`` and publishes a real message object.
"""
from examples._testing.stubs import install_stubs
install_stubs()
import json # noqa: E402
import pathlib # noqa: E402
from google.protobuf.json_format import ParseDict # noqa: E402
from neuraverse.models.v1.gen.business.node_graph_pb2 import Node # noqa: E402
from std_msgs.msg import Float32 # noqa: E402
from examples._testing.fake_dataflow import FakeDataFlow # noqa: E402
from examples.tutorials.math_node.math_node import MathAddNode # noqa: E402
SCHEMA_PATH = pathlib.Path(__file__).with_name("math_node_schema.json")
def load_schema() -> Node:
return ParseDict(json.loads(SCHEMA_PATH.read_text(encoding="utf-8")), Node())
def make_node(config: dict[str, str] | None = None) -> MathAddNode:
node = MathAddNode()
node.data_flow = FakeDataFlow()
node.on_configure(config if config is not None else {}, None)
return node
def test_publishes_sum_of_inputs_and_offset() -> None:
node = make_node({"offset": "1.5"})
node.data_flow.input_ports["a"] = Float32(data=2.0)
node.data_flow.input_ports["b"] = Float32(data=3.0)
node.on_execute()
published = node.data_flow.published["sum"]
assert len(published) == 1
assert isinstance(published[0], Float32)
assert published[0].data == 6.5
def test_offset_defaults_to_zero() -> None:
node = make_node()
node.data_flow.input_ports["a"] = Float32(data=0.25)
node.data_flow.input_ports["b"] = Float32(data=0.5)
node.on_execute()
assert node.offset == 0.0
assert node.data_flow.published["sum"][0].data == 0.75
def test_missing_input_warns_and_publishes_nothing() -> None:
node = make_node()
warnings: list[str] = []
node.log_warning = warnings.append
node.data_flow.input_ports["a"] = Float32(data=1.0)
node.on_execute()
assert not node.data_flow.published.get("sum")
assert len(warnings) == 1
assert "'b'" in warnings[0]
def test_inputs_latch_between_executions() -> None:
node = make_node()
node.data_flow.input_ports["a"] = Float32(data=1.0)
node.data_flow.input_ports["b"] = Float32(data=1.0)
node.on_execute()
node.on_execute()
assert [msg.data for msg in node.data_flow.published["sum"]] == [2.0, 2.0]
def test_schema_configuration_drives_on_configure() -> None:
schema = load_schema()
node = MathAddNode()
node.data_flow = FakeDataFlow()
# The engine passes Node.configuration (a protobuf ScalarMap of strings).
node.on_configure(schema.configuration, None)
assert schema.executionContext.className == MathAddNode.__name__
assert set(schema.inputs) == {"start", "stop", "a", "b"}
assert set(schema.outputs) == {"start", "error", "sum"}
assert node.offset == 0.0
| Test | What it proves |
|---|---|
test_publishes_sum_of_inputs_and_offset |
offset="1.5" is parsed; the published object is a Float32 with data == 6.5. |
test_offset_defaults_to_zero |
An empty config leaves offset at 0.0. |
test_missing_input_warns_and_publishes_nothing |
The None guard logs one warning naming the port and publishes nothing. |
test_inputs_latch_between_executions |
Two runs without new input publish the same sum twice. |
test_schema_configuration_drives_on_configure |
The schema parses into the Node proto, className equals the class name, the port keys are the expected ones and Node.configuration feeds on_configure. |
Two helpers do the ROS-free part. install_stubs() from examples/_testing/stubs.py puts
stand-ins for rclpy, zenoh, livekit and the std_msgs message classes into sys.modules
before the node module is imported; on a machine with ROS 2 the real packages win.
FakeDataFlow from examples/_testing/fake_dataflow.py replaces the transport adapters:
input_ports is what get_data() reads and published collects every publish() call.
Run it from the SDK repository root:
PYTHONPATH="$(pwd):$(pwd)/src" poetry run pytest examples/tutorials/math_node -q
Expect 5 passed. The SDK's own test suite additionally runs every example node, this one
included, through configure, FakeDataFlow and on_execute in tests/test_examples_tutorials.py,
so a change that breaks the tutorial fails the SDK pipeline. How to set up the same two helpers in
your own project is described in Testing.
Next steps¶
- Register the class for deployment: add
MathAddNodetoset_node_classes([...])insrc/run_nodes.pyand themath_nodepackage topackagesinpyproject.toml. See Project layout and build. - Continue with the image node: binary image messages and a typed slider setting that the editor renders as a widget.