Skip to content

Tutorial 3: Smart home device node

This tutorial builds SmartLightNode, a node that switches one network light ON or OFF from a String command and publishes the resulting status. It is the first tutorial whose node owns something outside the graph: a device handle. After working through it you can give a node typed settings (a text field and a toggle), keep state and a device connection on the node object across executions, report the node's health, honour the graph-wide simulation switch, pause cooperatively, and release the device when the node stops. All code lives in examples/tutorials/smart_home/ and runs in CI.

What you will build

Item Value
Class SmartLightNode in smart_home_node.py
Data input command_in, std_msgs/msg/String, .data is ON or OFF
Data output status_out, std_msgs/msg/String, the command that was applied
Trigger ports start, stop in; start, error out
Typed settings light_ip (text field), simulate (toggle)
Hooks used on_get_configuration, on_configure, on_execute, on_health_check, on_toggle_simulation_mode, on_pause, on_resume, on_stop_execution, on_cleanup

The device is a stand-in class, FakeLightDevice, that only remembers the last power state. That keeps the example runnable anywhere. To drive real hardware, replace that one class with an HTTP, MQTT or Zigbee client and keep the node code as it is.

1. The schema

The schema file smart_home_node_schema.json sits next to smart_home_node.py:

{
  "id": "Examples",
  "name": "Smart Light",
  "type": "NODE_TYPE_ASSET_SOURCE",
  "description": "Switches a network light ON or OFF from a String command and publishes the resulting status",
  "tags": ["example", "tutorial", "smart-home"],
  "inputs": {
    "start": { "rosType": "Start", "edgeType": 2 },
    "stop": { "rosType": "Stop", "edgeType": 2 },
    "command_in": { "rosType": "std_msgs/msg/String", "edgeType": 1 }
  },
  "outputs": {
    "start": { "rosType": "Start", "edgeType": 2 },
    "error": { "rosType": "Error", "edgeType": 2 },
    "status_out": { "rosType": "std_msgs/msg/String", "edgeType": 1 }
  },
  "executionContext": {
    "type": "EXECUTION_TARGET_TYPE_GRPC",
    "target": "",
    "className": "SmartLightNode"
  },
  "configuration": {
    "light_ip": "192.168.1.50",
    "simulate": "false"
  }
}

Points to check against your own schema:

  • executionContext.className is the Python class name, SmartLightNode.
  • The data ports use the full pkg/msg/Type spelling; the trigger ports carry the trigger type in rosType and lowercase keys. There is no stop output: the SDK fires every declared Stop output after each successful execution, which would stop downstream nodes on every command.
  • The configuration block holds the same two keys as on_get_configuration() below, as plain strings. On the platform these strings arrive in the config argument of on_configure() and act as the fallback when no typed value is set. The test at the end of this page asserts that the two key sets match.

See Schema file for every field.

2. State lives on the node object

The node object is created once at initialisation and reused for every configure and execute call, so attributes on self are how a node keeps state between executions. Declare them in __init__ and give them harmless defaults:

class SmartLightNode(NodeBase):
    """Switches a network light ON or OFF and publishes the resulting status."""

    def __init__(self) -> None:
        super().__init__()
        # Attributes only. Anything that touches the outside world belongs in on_configure().
        self._device: Optional[FakeLightDevice] = None
        self._light_ip: str = DEFAULT_LIGHT_IP
        self._simulate: bool = False
        self._paused_flag: bool = False

__init__ assigns attributes and nothing else. No socket, no device probe, no logging. Everything that touches the outside world belongs in on_configure(), which the SDK calls with the actual settings, and which can be called again.

3. Declare typed settings: on_get_configuration

The SDK asks the node for its settings when the node is initialised, before any configure, and the editor renders one widget per entry:

    def on_get_configuration(self) -> dict[str, NodeConfigEntry]:
        """Typed defaults the editor renders as a text field and a toggle."""
        return {
            "light_ip": NodeConfigEntry(
                configValue=NodeConfigValue(stringValue=DEFAULT_LIGHT_IP),
                displayLabel="Light IP address",
                description="Address of the light this node controls.",
                required=True,
            ),
            "simulate": NodeConfigEntry(
                configValue=NodeConfigValue(toggleValue=ToggleValue(enabled=False)),
                displayLabel="Simulate",
                description="Log commands instead of sending them to the device.",
            ),
        }

A stringValue becomes a text field, a toggleValue becomes a switch. displayLabel and description are what the user sees; required=True is passed to the editor as metadata and the SDK does not enforce it, so validate the value in on_configure(). The hook must return NodeConfigEntry objects, never plain strings, and must not depend on runtime state because it runs before on_configure(). All value branches and entry fields are listed in Configuration.

4. Read the settings and open the device: on_configure

on_configure() always receives two arguments: the static string map from the schema and the typed map from the editor, or None when the editor sent nothing.

    def on_configure(
        self,
        config: ScalarMap[str, str],
        dynamic_config: Optional[MessageMap[str, NodeConfigEntry]] = None,
    ) -> None:
        # Typed values from the editor win; the schema's static string map is the fallback.
        self._light_ip = get_config_value("light_ip", config, dynamic_config) or DEFAULT_LIGHT_IP
        # get_config_value renders a toggle as the string "true" / "false".
        self._simulate = get_config_value("simulate", config, dynamic_config) == "true"
        self._paused_flag = False

        # on_configure runs again on every re-configure: release the old handle first.
        self._release_device()
        self._device = FakeLightDevice(self._light_ip)
        self.log_info(f"Connected to light at {self._light_ip} (simulate={self._simulate})")

get_config_value(key, config, dynamic_config) from neuraverse_sdk.utils.config looks in the typed map first and falls back to the static map. It returns a string in both cases and None when neither map has the key, hence the or DEFAULT_LIGHT_IP. A toggle comes back as the string "true" or "false", which is why the node compares with == "true".

The two lines after the settings are the heart of the device pattern:

  1. _release_device() closes whatever the previous configure opened. The SDK calls on_configure() again whenever the graph is re-configured or the user changes a setting, and a node that opens a new connection each time leaks the old ones.
  2. A fresh FakeLightDevice is created for the current address and stored on self.

Do not read data ports or publish from on_configure(). The graph has not started yet.

5. Handle commands: on_execute

    def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
        try:
            if self._is_paused():
                self.log_info("Paused: ignoring command")
                return

            msg = self.get_data("command_in")
            if msg is None:
                self.log_warning("No command received on 'command_in'")
                return
            command = msg.data
            if command not in VALID_COMMANDS:
                self.log_warning(f"Ignoring unknown command {command!r}; expected ON or OFF")
                return

            if self._device is None:
                self.send_health_update(False, "Light device handle is missing")
                raise NodeExecutionError("Light device is not configured")

            if self._simulate:
                self.log_info(f"[simulation] would switch light {self._light_ip} {command}")
            else:
                self._device.set_power(command == "ON")

            self.publish("status_out", String(data=command))
        except NodeExecutionError:
            raise
        except Exception as exc:
            self.send_health_update(False, f"Light command failed: {exc}")
            raise NodeExecutionError(f"Light command failed: {exc}") from exc

Walk through the branches in order:

Step Why
self._is_paused() Pause is cooperative; the SDK still calls on_execute() while the node is paused. Section 8 explains the helper.
get_data("command_in") may return None Nothing has arrived on the port yet. Log a warning and return; do not raise.
msg.data Inputs are ROS 2 message objects, so the command text is on .data.
Unknown command Logged and ignored, so a typo upstream does not put the node into error.
self._device is None Cannot happen after a successful configure, but if it does the node pushes an unhealthy snapshot and raises.
self._simulate In simulation the node logs what it would have done and skips the device call. It still publishes status_out, so downstream nodes behave the same in both modes.
self.publish("status_out", String(data=command)) Outputs must be ROS 2 message objects. A bare str is dropped by the transport and never arrives.
except Exception Any device failure is reported through send_health_update(False, ...) and re-raised as NodeExecutionError.

Raising NodeExecutionError is what marks the run as failed: the SDK fires the node's error trigger output, moves the node to ERROR and reports the failure to the engine. The next configure returns it to CONFIGURED. How the trigger context reaches a downstream error handler is covered in the cloud node tutorial.

6. Report health

Health is separate from the lifecycle state: a node can be CONFIGURED and unhealthy. The SDK runs on_health_check() once right after a successful configure and then on a background monitor every health_stream_check_interval_s seconds (10 s by default), and streams the result to the editor only when the pair of boolean and message changes.

    def on_health_check(self) -> bool:
        """Run by the SDK right after configure and on each periodic health poll.

        The message set here is what the editor shows next to the health state.
        """
        if self._device is None:
            self._health_check_message = "Light device handle is missing (node not configured)"
            return False
        self._health_check_message = f"Connected to light at {self._light_ip}"
        return True

Two rules make this hook cheap and correct:

  • Read state that already exists. The hook runs on the SDK's monitor thread, so do not contact the device inside it.
  • Set self._health_check_message on every path. The SDK clears it to None before each call and falls back to "Healthy" or "Unhealthy" when you set nothing.

The execute path adds the immediate variant. send_health_update(is_healthy, message) pushes a snapshot now instead of waiting up to 10 s for the monitor. It is deduplicated, so calling it on every failure is fine, and it is a silent no-op until the SDK has attached the node to a graph, so unit tests can call it freely. Because on_health_check() reads the same _device attribute the failure branch checks, the periodic check and the pushed snapshot never disagree. The full behaviour table is in Health reporting.

7. Honour the graph-wide simulation switch

The engine can switch a whole graph into simulation mode. The SDK calls on_toggle_simulation_mode(is_simulation) on every node and remembers nothing else, so the node stores the flag itself:

    def on_toggle_simulation_mode(self, is_simulation: bool) -> None:
        """Graph-wide simulation switch; it overrides the node's own 'simulate' setting."""
        self._simulate = is_simulation
        self.log_info(f"Simulation mode {'enabled' if is_simulation else 'disabled'}")

The same _simulate attribute is set by the node's own simulate toggle in on_configure(). The graph-wide switch overrides it, and a later re-configure returns the node to whatever its configuration says. Keep the hook a pure setter: no device calls, no exceptions for expected situations. An exception here is wrapped as NodeSimulationModeError and fails the engine's request. See Simulation mode for the full contract.

8. Pause cooperatively

Pausing marks the node PAUSED and calls on_pause(). Nothing is suspended for you: triggers keep arriving and on_execute() keeps being called. A device node must therefore decide for itself to ignore commands while paused. The admonition below says which SDK version made this the rule.

    def on_pause(self) -> None:
        self._paused_flag = True
        self.log_info("Light control paused")

    def on_resume(self) -> None:
        self._paused_flag = False
        self.log_info("Light control resumed")

    def _is_paused(self) -> bool:
        # Pause is cooperative: the SDK keeps calling on_execute() while paused, so the node
        # has to skip work itself. SDK 2.39.0 added is_paused(), which reads the state machine.
        # SDK 2.37.0 has no such method, so fall back to the flag on_pause()/on_resume() keep.
        return self.is_paused() if hasattr(self, "is_paused") else self._paused_flag

Pause became cooperative in this version and is_paused() was added to NodeBase; it reads the state machine, so the node does not need its own bookkeeping. Pause from CONFIGURED is legal, pause and resume never move a node to ERROR, resume returns to the state the node was paused from, and on_pause() / on_resume() fire only on the call that actually changes the state.

SDKs older than 2.39.0 have no is_paused(). The _is_paused() helper above therefore prefers is_paused() when it exists and otherwise falls back to the _paused_flag that on_pause() and on_resume() maintain. The Mock Runner and the node template ship SDK 2.46.2, so the fallback only matters for a project pinned below 2.39.0; drop it once every runtime you target is at 2.39.0 or later.

While paused, a returning on_execute() still fires the outgoing start trigger. If that matters for your graph, keep the early return at the very top of on_execute() as this node does. More on the state machine in Lifecycle and states.

9. End the run and release the device: on_stop_execution and on_cleanup

The engine can end a run and keep the node configured (stop execution), or tear the node down (stop and cleanup). on_stop_execution() runs on both; it only has to make a running on_execute() return. on_cleanup() runs only on the teardown, as its final step, exactly once per lifecycle.

    def on_stop_execution(self, trigger_context: Optional[TriggerContext] = None) -> None:
        """End the current run only. The device stays open for the next run.

        This node's on_execute returns on its own, so there is nothing to
        unblock; a node with a loop would set the flag the loop reads here.
        Called at most once per run, also when the node is idle.
        """
        self.log_info("SmartLightNode run ended")
    def on_cleanup(self) -> None:
        """Final step of the hard stop: release what on_configure() opened."""
        self._release_device()

    def on_stop(self, trigger_context: Optional[TriggerContext] = None) -> None:
        """Deprecated since SDK 2.43.0 and only kept so this class still
        instantiates on older SDKs, where on_stop was abstract. Leave it empty."""

    def _release_device(self) -> None:
        if self._device is not None:
            self._device.close()
            self._device = None

Release in on_cleanup() what on_configure() acquired. The same _release_device() helper is used in both places, so a re-configure and a teardown close the device the same way, and the test at the end checks that the old handle is closed on re-configure. The device survives a stop execution, so the next run skips reconnecting. The deprecated on_stop() is kept here only so the node still instantiates on SDKs before 2.43.0, where it was abstract; on 2.43.0 and later it can be deleted. The complete step order is in Hard stop teardown order.

10. Run it in the Mock Runner

The Mock Runner from the Quickstart runs this node with its real NodeBase, an in-memory dataflow and no engine. Point it at the tutorial folder from your checkout of the mock-nodegraph repository:

SRC_DIRPATH=/absolute/path/to/neuraverse-node-sdk-python/examples/tutorials docker compose up -d

Test modules (test_*.py) are skipped by the loader, so only the tutorial nodes appear in the palette. Then, in the browser:

  1. Click Reload Code. Smart Light appears in Available Nodes; drag it onto the canvas.
  2. Click Init. The card shows the form from on_get_configuration(): Light IP address prefilled with 192.168.1.50 and the Simulate switch, off.
  3. Click Configure. Node Logs shows Connected to light at 192.168.1.50 (simulate=False) from on_configure() and the SDK's Healthy check result: True, message: Connected to light at 192.168.1.50 from the one health check the mock runs.
  4. Open the Inputs tab, type ON next to command_in and click Override. Click Execute. Outputs shows ON on status_out.
  5. Override with DIM and execute again: a warning in Node Logs, nothing on Outputs.
  6. Flip Simulate on, click Configure, override OFF and execute. The log now reads [simulation] would switch light 192.168.1.50 OFF and status_out still shows OFF.

What the mock does not show for this node:

Feature In the Mock Runner
Static config map Always empty. get_config_value therefore falls back to DEFAULT_LIGHT_IP when the form field is cleared.
Untouched toggle A toggle whose default is off is absent from dynamic_config until you flip it. The node handles this: get_config_value returns None, which is not "true".
Health stream No indicator and no periodic monitor; send_health_update() is a no-op. You see the single log line after Configure.
Simulation switch No control. Use the node's own Simulate toggle, or the unit test.
Pause, resume, stop Not triggered from the UI. on_stop_execution() and on_cleanup() run only in the unit test or on an engine.

11. The tests CI runs

The test module drives every hook this page introduced without ROS 2 installed. It installs the shared transport stubs first, then uses FakeDataFlow from examples/_testing/ in place of the SDK adapters:

"""Tests for the tutorial SmartLightNode.

Runs without a ROS installation: the shared stubs shim ``std_msgs`` and the transport
libraries before the node module is imported. ``send_health_update`` is a no-op until the SDK
hands the node a ``health_queue`` and a ``node_id``, so most tests need no queue; the failure
test plugs one in to see the pushed snapshot.
"""

from examples._testing.stubs import install_stubs

install_stubs()

import json  # noqa: E402
import pathlib  # noqa: E402
import queue  # noqa: E402

import pytest  # noqa: E402
from google.protobuf.json_format import ParseDict  # noqa: E402
from neuraverse.models.v1.gen.business.node_graph_pb2 import (  # noqa: E402
    Node,
    NodeConfigEntry,
    NodeConfigValue,
    ToggleValue,
)
from std_msgs.msg import String  # noqa: E402

from examples._testing.fake_dataflow import FakeDataFlow  # noqa: E402
from examples.tutorials.smart_home.smart_home_node import SmartLightNode  # noqa: E402
from neuraverse_sdk.utils.exceptions import NodeExecutionError  # noqa: E402

SCHEMA_PATH = pathlib.Path(__file__).with_name("smart_home_node_schema.json")


def typed_config(light_ip: str | None = None, simulate: bool | None = None) -> dict:
    """Build the typed map the editor sends as ``dynamic_config``."""
    entries: dict[str, NodeConfigEntry] = {}
    if light_ip is not None:
        entries["light_ip"] = NodeConfigEntry(configValue=NodeConfigValue(stringValue=light_ip))
    if simulate is not None:
        entries["simulate"] = NodeConfigEntry(
            configValue=NodeConfigValue(toggleValue=ToggleValue(enabled=simulate))
        )
    return entries


def make_node(dynamic_config: dict | None = None) -> SmartLightNode:
    node = SmartLightNode()
    node.data_flow = FakeDataFlow()
    node.on_configure({}, dynamic_config)
    return node


def send(node: SmartLightNode, command: str) -> None:
    node.data_flow.input_ports["command_in"] = String(data=command)
    node.on_execute()


def statuses(node: SmartLightNode) -> list[str]:
    return [msg.data for msg in node.data_flow.published.get("status_out", [])]


def test_health_is_false_before_configure() -> None:
    node = SmartLightNode()

    is_healthy, message = node.get_health_check()

    assert is_healthy is False
    assert "not configured" in message


def test_health_is_true_after_configure_and_false_after_cleanup() -> None:
    node = make_node(typed_config(light_ip="10.0.0.7"))

    assert node.get_health_check() == (True, "Connected to light at 10.0.0.7")

    node.on_cleanup()

    assert node.get_health_check()[0] is False


def test_on_and_off_switch_the_device_and_publish_status() -> None:
    node = make_node(typed_config(light_ip="10.0.0.7"))
    assert node._light_ip == "10.0.0.7"

    send(node, "ON")
    assert node._device.is_on is True

    send(node, "OFF")
    assert node._device.is_on is False

    assert statuses(node) == ["ON", "OFF"]


def test_unknown_command_is_ignored() -> None:
    node = make_node()

    send(node, "DIM")

    assert node._device.is_on is False
    assert statuses(node) == []


def test_no_command_publishes_nothing() -> None:
    node = make_node()

    node.on_execute()

    assert statuses(node) == []


def test_simulate_toggle_from_config_skips_the_device_call() -> None:
    node = make_node(typed_config(simulate=True))

    send(node, "ON")

    assert node._device.is_on is False
    assert statuses(node) == ["ON"]


def test_graph_simulation_mode_overrides_config() -> None:
    node = make_node(typed_config(simulate=False))

    node.toggle_simulation_mode(True)
    send(node, "ON")
    assert node._device.is_on is False

    node.toggle_simulation_mode(False)
    send(node, "ON")
    assert node._device.is_on is True


def test_static_config_is_the_fallback_when_no_typed_value_is_set() -> None:
    node = SmartLightNode()
    node.data_flow = FakeDataFlow()

    node.on_configure({"light_ip": "10.0.0.9", "simulate": "true"}, None)

    assert node._light_ip == "10.0.0.9"
    assert node._simulate is True


def test_missing_device_raises_and_pushes_unhealthy_snapshot() -> None:
    node = make_node()
    node.health_queue = queue.Queue()
    node.node_id = "smart-light-1"
    node._device = None

    node.data_flow.input_ports["command_in"] = String(data="ON")
    with pytest.raises(NodeExecutionError):
        node.on_execute()

    snapshot = node.health_queue.get_nowait()
    assert snapshot["isHealthy"] is False
    assert snapshot["resultMessage"] == "Light device handle is missing"
    assert statuses(node) == []


def test_missing_device_without_health_queue_still_raises() -> None:
    node = make_node()
    node._device = None
    node.data_flow.input_ports["command_in"] = String(data="ON")

    with pytest.raises(NodeExecutionError):
        node.on_execute()


def test_paused_node_skips_commands_and_resumes() -> None:
    node = make_node()
    node.state_machine.configure()

    node.pause()
    assert node.is_paused() is True
    send(node, "ON")
    assert node._device.is_on is False
    assert statuses(node) == []

    node.resume()
    assert node.is_paused() is False
    send(node, "ON")
    assert node._device.is_on is True
    assert statuses(node) == ["ON"]


def test_pause_flag_fallback_without_is_paused() -> None:
    node = make_node()

    node.on_pause()
    assert node._paused_flag is True
    node.on_resume()
    assert node._paused_flag is False


def test_reconfigure_releases_the_previous_device() -> None:
    node = make_node(typed_config(light_ip="10.0.0.7"))
    first = node._device

    node.on_configure({}, typed_config(light_ip="10.0.0.8"))

    assert first.closed is True
    assert node._device is not first
    assert node._device.ip == "10.0.0.8"


def test_schema_parses_and_names_the_class() -> None:
    schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
    node_proto = ParseDict(schema, Node())

    assert node_proto.executionContext.className == SmartLightNode.__name__
    assert set(node_proto.inputs) == {"start", "stop", "command_in"}
    assert set(node_proto.outputs) == {"start", "error", "status_out"}
    assert set(node_proto.configuration) == set(SmartLightNode().on_get_configuration())

Points worth copying into your own tests:

  • typed_config() builds the same NodeConfigEntry map the editor sends, so on_configure({}, dynamic_config) is exercised with both arguments.
  • Health is asserted through node.get_health_check(), the public method the SDK calls, before configure, after configure and after cleanup.
  • The failure test attaches a queue.Queue as health_queue and sets node_id to see the snapshot that send_health_update() pushes; without them the call is a no-op and the second test proves the raise still happens.
  • Simulation is driven through node.toggle_simulation_mode(...), the public wrapper around the hook.
  • The pause test calls node.state_machine.configure() first, then node.pause() and node.resume(), and checks that commands are ignored only while is_paused() is True.
  • The schema test parses the JSON into the Node proto and checks the class name, the port keys and that the static configuration keys equal the typed ones.

Run it from the SDK repository root:

PYTHONPATH="$(pwd):$(pwd)/src" poetry run pytest examples/tutorials/smart_home -q -p no:cacheprovider

How the stubs and the fake dataflow work, and how to run the same tests inside the node image with real ROS 2, is explained in Testing.

Swapping in a real device

When you replace FakeLightDevice with a real client, keep these rules:

  • Open the connection in on_configure(), close it in _release_device(), and keep both idempotent. Use a connect timeout, and raise when the device is unreachable so the configure fails visibly: NodeDependencyError.unavailable() from SDK 2.42.0 (see Errors), or NodeConfigurationError from neuraverse_sdk.utils.exceptions on the pinned 2.37.0 this tutorial targets.
  • Give every device call in on_execute() a timeout. on_execute() runs on a single worker thread per node, and a call that hangs blocks every later command.
  • Let on_health_check() report a cached connection state, not a live probe. Update that state from on_execute() and from your client's error callbacks.
  • Keep the simulate branch. It is what lets reviewers and CI run the node without the hardware.

Next steps