Skip to content

External inputs: velocity, acknowledgement and Stop

Use the platform endpoint to supply a typed velocity, wait for acknowledgement, and then start one node. A normal downstream connection carries the output to a second node. An unrelated heartbeat branch continues when you explicitly stop the target. The Python author nodes and client below have local tests; deployed and released-artifact qualification is a separate step, not a result implied by this tutorial.

Compound JSON input requires SDK 2.45.0 in the target node image and supporting platform APIs. Rebuild your node images after upgrading. Installing a new DevKit or changing a version label does not replace the SDK inside an already running node.

The graph

Copy examples/tutorials/external_inputs/ into your node project's source directory. Configure a graph with these three nodes, using the supplied schemas:

Logical node ID Python class Purpose
echo VelocityEchoNode Read velocity, publish velocity_out, then return
downstream VelocityEchoNode Read the first node's output and publish the same value
heartbeat HeartbeatNode Publish a counter until its own run is stopped

Connect echo.velocity_out to downstream.velocity as a data edge, and echo.start to downstream.start as a Start trigger edge. Leave the heartbeat on an unrelated branch. The SDK's normal automatic Start output dispatch runs the downstream node after a successful echo execution. The author does not send a second manual Start or declare a Stop output.

Use the configured run ID returned by the platform, and logical node IDs in that graph. Configure alone does not execute these hooks. This example deliberately sends node-specific Start inputs; do not also launch the whole graph while following this sequence.

The Python echo works with the typed ROS message returned by get_data, preserving all its fields rather than converting it through display JSON:

class VelocityEchoNode(NodeBase):
    """Read a Twist and publish it unchanged before normal downstream dispatch."""

    def on_configure(
        self,
        config: ScalarMap[str, str],
        dynamic_config: Optional[MessageMap[str, NodeConfigEntry]] = None,
    ) -> None:
        pass

    def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
        try:
            velocity = self.get_data("velocity")
            if velocity is None:
                self.log_warning("No velocity input is available")
                return
            self.publish("velocity_out", velocity)
            self.log_info(f"Velocity: linear.x={velocity.linear.x}, angular.z={velocity.angular.z}")
        except Exception as exc:
            raise NodeExecutionError(f"Velocity echo failed: {exc}") from exc


    def on_stop(self, trigger_context: Optional[TriggerContext] = None) -> None:
        self.log_info("Velocity echo stopped")

    def on_get_configuration(self) -> dict[str, NodeConfigEntry]:
        return {}

The unrelated branch cooperates with Stop and pause:

class HeartbeatNode(NodeBase):
    """Publish until this node's run ends; stopping another node has no effect."""

    def __init__(self) -> None:
        super().__init__()
        self._wake = Event()

    def on_configure(
        self,
        config: ScalarMap[str, str],
        dynamic_config: Optional[MessageMap[str, NodeConfigEntry]] = None,
    ) -> None:
        self._wake.clear()

    def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
        try:
            # Older DevKits can load this module but cannot demonstrate run isolation.
            self._wake.clear()
            count = 0
            while not self._wake.is_set():
                if not hasattr(self, "is_paused") or not self.is_paused():
                    count += 1
                    self.publish("heartbeat", Int32(data=count))
                if self._wake.wait(0.1):
                    return
        except Exception as exc:
            raise NodeExecutionError(f"Heartbeat failed: {exc}") from exc

    def on_stop(self, trigger_context: Optional[TriggerContext] = None) -> None:
        self._wake.set()
        self.log_info("Heartbeat stopped")

    def on_cleanup(self) -> None:
        self._wake.set()

    def on_get_configuration(self) -> dict[str, NodeConfigEntry]:
        return {}

The Mock Runner can exercise individual hooks and schema loading. It does not prove external-input delivery, automatic downstream dispatch, or isolated Stop on a deployed graph.

Inject, observe, then stop

Run client.py in a Python environment containing the supporting SDK dependencies, including the generated platform API messages. The same client drives Python and C++ nodes because both expose the same platform operation. Older DevKits can still import this module when loading the examples. Running a command with missing input API bindings reports an explicit upgrade requirement before sending any request; inject-start checks support for both operations before injection.

Set PLATFORM_ENDPOINT to the authorized gRPC host:port, and RUN_ID to the configured run ID. Supply your access token in NODEGRAPH_TOKEN through your normal secret mechanism; the client reads it from the environment and does not print it. Add --edge EDGE_ID to each command when the platform requires an edge destination. TLS is the default. --insecure is only allowed for local loopback testing.

First start the independent branch:

poetry run python examples/tutorials/external_inputs/client.py \
  --endpoint "$PLATFORM_ENDPOINT" --graph "$RUN_ID" --node heartbeat start

Then inject the example Twist and start the echo:

poetry run python examples/tutorials/external_inputs/client.py \
  --endpoint "$PLATFORM_ENDPOINT" --graph "$RUN_ID" --node echo \
  --payload examples/tutorials/external_inputs/velocity.json inject-start

The client's ordering is tested against a protocol peer that deliberately withholds the injection acknowledgement. Start is sent only after resultCode == "0":

def inject_then_start(
    stub,
    *,
    graph_id,
    node_id,
    payload_json,
    edge_id="",
    metadata=(),
    timeout=5.0,
):
    """Inject one Twist, await acknowledgement, then send one Start."""
    require_input_api(stub, "InjectNodeInputData", "TriggerNodeInput")
    acknowledged = stub.InjectNodeInputData(
        api.InjectNodeInputDataRequest(
            nodeGraphId=graph_id,
            nodeId=node_id,
            edgeId=edge_id,
            inputPort="velocity",
            rosType="geometry_msgs/msg/Twist",
            payloadJson=payload_json,
        ),
        metadata=metadata,
        timeout=timeout,
    )
    require_success(acknowledged)
    return require_success(
        stub.TriggerNodeInput(
            api.TriggerNodeInputRequest(
                nodeGraphId=graph_id, nodeId=node_id, edgeId=edge_id, inputPort="start"
            ),
            metadata=metadata,
            timeout=timeout,
        )
    )

An injection acknowledgement confirms accepted input delivery, not execution or downstream output. Observe the downstream node's output in your normal node logs or application: linear.x = 1.25, angular.z = -0.5, and the other vector components are zero. The echo logs those two components when it executes. This example adds no output-subscription API.

After observing that output, perform a separate, explicit Stop:

poetry run python examples/tutorials/external_inputs/client.py \
  --endpoint "$PLATFORM_ENDPOINT" --graph "$RUN_ID" --node echo stop

Confirm that the target's Stop hook ran and heartbeat publications continue. Stop does not erase an output already observed and does not stop the unrelated branch. When finished, explicitly stop heartbeat too; clean up the entire graph only when all its work may end.

JSON rules

Input Rule
Root and nested messages JSON objects; omitted fields keep generated ROS defaults at every level
Unknown fields or wrong shapes Reject the whole payload; diagnostics identify the offending field
Fixed arrays and bounded sequences Exact fixed length, or no more than the declared sequence limit
Smaller integers JSON integer numbers within the ROS range; booleans are not integers
int64 and uint64 Decimal strings, including inside arrays; no plus sign or leading zeroes
Floating-point fields Finite values within range; nonzero values that underflow to zero reject
Bytes / uint8 arrays JSON integer arrays in 0..255; base64 is not an alternative
Bounded strings UTF-8 byte limits; wide strings use UTF-16 code-unit limits
Malformed nested values No partially committed input and no input handler invocation

These rules apply to installed/registered types only. Input does not install a schema. See Message types and Dataflow.

Ownership, timeouts and cleanup

Use the same authorized owner that configured the graph. Data and trigger inputs do not bypass ownership or revive an inactive run. A rejected injection must not be followed by Start; fix the cause first. A target already stopped is not re-armed by another injected value or node-specific Start.

The client gives each RPC a finite deadline and disables automatic retries. A timeout or lost connection can leave delivery uncertain: the operation may have reached the target. Do not replay injection, Start or Stop automatically. Inspect the run and observed output, then decide on the next explicit action.

Input Stop tears down its target using the existing 2.x cleanup and stop hooks. Graph Stop and idle removal discard the graph run; a stale run ID cannot be recovered by repeating the input. Check whether the graph still exists. For a removed graph, configure a replacement, use its newly returned run ID, and deliberately restore the required inputs before starting it. Older peers may provide only a generic missing/inactive response. Supporting platforms retain confirmed idle-removal history for seven days by default and return NOT_FOUND with graph_removed_idle to the original owner. History that is expired or cannot establish removal returns graph_not_configured; it does not prove the graph never existed. Previously verified retained history remains valid during a temporary storage outage. A different owner receives not_session_owner.

Reconfiguration clears retained history only after a successful durable replacement. If history cannot be checked or replaced, UNAVAILABLE with graph_history_unavailable means configuration did not succeed. Restore the storage service before retrying configuration. Platforms with durable history explicitly disabled cannot offer retained diagnostics across restart.

C++ authoring

Keep the same ports, ROS type and graph connections in a C++ node. Read the typed geometry_msgs::msg::Twist through getDataAny, check has_value(), extract the typed message with std::any_cast, pass it to publish, and return so the normal automatic Start output can run the downstream node. A long-running C++ hook must cooperate with pause and set a cancellation flag in onStopExecution(), as the Heartbeat example does. The client and JSON rules above remain the same. See the C++ mapping for hook signatures and native transport behavior.

These snippets are vendored copies of the C++ example's compiled headers. A documentation drift test checks them against that source. The C++ author tests exercise real NodeService and MQTT behavior, including unchanged typed output and isolated Stop:

#pragma once

#include <geometry_msgs/msg/twist.hpp>
#include <neuraverse_sdk/NodeBase.hpp>
#include <neuraverse_sdk/utils/Exceptions.hpp>

namespace examples::external_inputs
{
class VelocityEchoNode : public neuraverse::sdk::NodeBase
{
public:
    void onConfigure(const NodeConfigStringMap&,
                     const NodeConfigEntryMap* = nullptr) override {}

    void onExecute() override
    {
        try
        {
            // An empty read means no message arrived within the SDK's read
            // interval. Do not turn that into a default zero-velocity publish.
            const auto input = getDataAny("velocity");
            if (!input.has_value())
            {
                logWarning("No velocity input is available");
                return;
            }
            const auto& velocity = std::any_cast<const geometry_msgs::msg::Twist&>(input);
            publish("velocity_out", velocity);
            logInfo("Velocity: linear.x=" + std::to_string(velocity.linear.x) +
                    ", angular.z=" + std::to_string(velocity.angular.z));
            // NodeBase forwards the configured Start output after this hook.
        }
        catch (const std::exception& error)
        {
            throw neuraverse::sdk::NodeExecutionError(
                "Velocity echo failed: " + std::string(error.what()));
        }
    }

    void onStop() override { logInfo("Velocity echo stopped"); }
    NodeConfigEntryMap onGetConfiguration() override { return {}; }
};
}
#pragma once

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <limits>
#include <mutex>
#include <neuraverse_sdk/NodeBase.hpp>
#include <neuraverse_sdk/utils/Exceptions.hpp>
#include <std_msgs/msg/int32.hpp>

namespace examples::external_inputs
{
class HeartbeatNode : public neuraverse::sdk::NodeBase
{
public:
    void onConfigure(const NodeConfigStringMap&,
                     const NodeConfigEntryMap* = nullptr) override { stop_requested_ = false; }
    void onExecute() override
    {
        try
        {
            std_msgs::msg::Int32 heartbeat;
            while (!stop_requested_.load())
            {
                if (!isPaused())
                {
                    if (heartbeat.data == std::numeric_limits<int32_t>::max())
                        heartbeat.data = 0;
                    ++heartbeat.data;
                    publish("heartbeat", heartbeat);
                }
                std::unique_lock<std::mutex> lock(wake_mutex_);
                wake_.wait_for(lock, std::chrono::milliseconds(100),
                               [this] { return stop_requested_.load(); });
            }
        }
        catch (const std::exception& error)
        {
            throw neuraverse::sdk::NodeExecutionError(
                "Heartbeat failed: " + std::string(error.what()));
        }
    }

    void onStopExecution() override
    {
        stop_requested_ = true;
        wake_.notify_all();
    }

    void onStop() override
    {
        wake_.notify_all();
        logInfo("Heartbeat stopped");
    }
    void onCleanup() override { wake_.notify_all(); }
    NodeConfigEntryMap onGetConfiguration() override { return {}; }

private:
    std::atomic<bool> stop_requested_{false};
    std::mutex wake_mutex_;
    std::condition_variable wake_;
};
}

The standalone C++ project, schemas and image build live in the SDK repository's neuraverse-node-sdk-cpp/examples/external_inputs/. Use its native builder/runtime image workflow. These local compiled checks do not establish published-image qualification.