Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Add a second node

Tutorial · Level 1: First contact

Needs first: What you just built

Status: this chapter runs on nros-board-mps2-an385-freertos: Verified in emulator (daily). From the board support registry; Board Support Levels explains the words.

In this chapter you add a listener to the project: a second node package, monitor_node, that subscribes to /chatter. At the end, one run of the board prints both sides of the conversation:

[INFO] sensor_node: [    3.122528] Publishing: 'Hello World: 1'
[INFO] monitor_node: [    3.123277] I heard: [Hello World: 1]

Along the way you see what makes sensor_ws a workspace, and why adding a node is one package and one line in the bringup. This is the part of the workspace the chapter adds to:

sensor_ws/
└── src/
    ├── monitor_node/              (new)
    ├── sensor_node/
    └── sensor_node_bringup/
        ├── package.xml            (changed)
        ├── system.contract.yaml   (changed)
        └── system.toml            (changed)

Run every step from the root of sensor_ws.

Add the listener package

nros new monitor_node --template listener --lang rust --to sensor_node_bringup
nros new monitor_node --template listener --lang c --to sensor_node_bringup
nros new monitor_node --template listener --lang cpp --to sensor_node_bringup
nros new: added the node package src/monitor_node/ (listener, rust) to /home/you/sensor_ws
  declared it in /home/you/sensor_ws/src/sensor_node_bringup: a [[component]] row and an <exec_depend>

Inside a workspace, nros new adds a package under src/ instead of writing a new workspace. --template listener picks the node it holds: a subscription on /chatter that prints each message it receives. --to sensor_node_bringup also tells the bringup to run it, which the next step looks at. Without --to, no bringup is touched, and the package sits in the workspace until a bringup names it.

Use the language of the rest of your project. A workspace can mix languages, and Mix languages shows how, but this Tutorial keeps to one.

Read the listener

The new package has the shape of sensor_node: a library holding one node, with no main() and no board.

src/monitor_node/
├── Cargo.toml   # a [lib] crate; registers monitor_node::Listener
├── package.xml  # <depend>std_msgs</depend>
└── src/lib.rs   # the listener; its last line is nros::node!(Listener);

register creates one subscription and binds it to the callback named on_chatter. on_callback reads the message when that callback fires:

#![allow(unused)]
fn main() {
fn register(ctx: &mut NodeContext<'_>) -> NodeResult<()> {
    nros_log::register_logger(&LOGGER);
    let mut node = ctx.create_node(NodeOptions::new("monitor_node"))?;
    let _sub = node.create_subscription_for_callback_name::<StringMsg>(
        "on_chatter",
        "/chatter",
    )?;
    log_info!(&LOGGER, "Subscriber created for topic: /chatter");
    Ok(())
}

fn on_callback(
    state: &mut Self::State,
    callback: Callback<'_>,
    ctx: &mut CallbackCtx<'_>,
) {
    if callback.as_str() == "on_chatter"
        && let Ok(msg) = ctx.message::<StringMsg>()
    {
        *state = state.wrapping_add(1);
        log_info!(&LOGGER, "I heard: [{}]", msg.data);
    }
}
}

register declares what the node creates; it does not run the node. It runs once, at startup, and no message flows during it. on_callback is the body, which the executor calls each time one of the node’s callbacks fires; state is the node’s own storage, here a count of the messages it has seen.

The constant at the top of the impl Component block, ENTITY_BOUNDS, says how many publishers, service servers, service clients, action clients and action servers the node creates. The talker’s is exact(1, 0, 0, 0, 0): one publisher. The listener’s is all zeros, because a subscription needs no slot there. The numbers size static memory, so they are exact rather than generous; a node that creates more than it declares stops at boot, naming the node, rather than dropping one silently.

Cargo.toml registers the class the package exports:

[package.metadata.nros.node]
class = "monitor_node::Listener"
name = "monitor_node"
src/monitor_node/
├── CMakeLists.txt     # registers monitor_node::Listener
├── nros-codegen.toml  # the longest string a message holds
├── package.xml        # <depend>std_msgs</depend>
└── src/Listener.c     # the listener

listener_configure creates one subscription and adds it to the executor with a callback and a context pointer, the way rclc does. The message is owned by the node’s state struct, so nothing allocates when one arrives:

static void on_msg(const void* msgin, void* ctx) {
    listener_t* self = (listener_t*)ctx;
    const std_msgs__msg__String* msg = (const std_msgs__msg__String*)msgin;
    printf("I heard: [%.*s]\n", (int)msg->data.size, msg->data.data);
    self->recv++;
}

static rcl_ret_t listener_configure(rcl_node_t* node, rclc_executor_t* executor,
                                    listener_t* self) {
    self->recv = 0;
    std_msgs__msg__String__init_in(&self->msg, &self->msg_storage);
    self->sub = rcl_get_zero_initialized_subscription();
    rcl_ret_t rc = rclc_subscription_init_default(
        &self->sub, node, ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, String),
        "/chatter");
    if (rc != RCL_RET_OK) {
        return rc;
    }
    return rclc_executor_add_subscription_with_context(
        executor, &self->sub, &self->msg, on_msg, self, ON_NEW_DATA);
}

RCLC_C_COMPONENT(listener_t, listener_configure)

std_msgs__msg__String__init_in points the message’s string at msg_storage, memory the node owns. Generated messages take rosidl’s C names and member shape, and their strings and sequences always point at memory you own: nothing on this path allocates, so rosidl’s allocating __init and __fini are not declared.

src/monitor_node/
├── CMakeLists.txt                     # registers monitor_node::Listener
├── include/monitor_node/Listener.hpp  # the Listener class
├── nros-codegen.toml                  # the longest string a message holds
├── package.xml                        # <depend>std_msgs</depend>
└── src/Listener.cpp                   # its two members

configure binds the member on_msg as the subscription’s callback, by identity rather than through a std::function:

void Listener::on_msg(const ::std_msgs::msg::String& msg) {
    printf("I heard: [%s]\n", msg.data.c_str());
    ++recv_;
}

::rclcpp::Result Listener::configure(::rclcpp::Node& node) {
    return ::rclcpp::bind_subscription<::std_msgs::msg::String, Listener,
                                       &Listener::on_msg>(node, "/chatter", this);
}

Every call returns a Result rather than throwing, because every nano-ros build compiles with -fno-exceptions. configure returns the first failure, and the program stops at boot naming the node that failed. Port a C++ node shows the rclcpp-shaped constructors a ported node can keep.

Where its messages come from

In every language, the listener’s package.xml is a standard ROS 2 manifest, and its one <depend> names the message package the node uses:

<depend>std_msgs</depend>

That line is all you write for a message package. The build generates the message code from your ROS 2 install and links it into the node: in Rust it adds a dependency row to Cargo.toml, tagged # nros-managed, pointing at the crate it generated under generated/; in C and C++, find_package finds the generated code during the CMake configure. Removing the <depend> removes the generated code from the node’s build. A row in Cargo.toml without the # nros-managed tag is yours and is never touched, so to override a generated row, delete its tag.

Both nodes depend on std_msgs, and the build generates it once for the workspace, not once per package. Chapter 5 adds a message package of your own, which every node in the workspace can depend on the same way.

See the bringup run both

cat src/sensor_node_bringup/system.toml

--to sensor_node_bringup added a second [[component]] row, after the talker’s:

[[component]]
pkg = "sensor_node"
class = "sensor_node::Talker"
name = "sensor_node"

[[component]]
pkg = "monitor_node"
class = "monitor_node::Listener"
name = "monitor_node"
FieldMeaning
pkgthe node package: its <name> in package.xml
classthe class the package registers
namethe node’s name at run time; chapter 7 renames one

It also added <exec_depend>monitor_node</exec_depend> to the bringup’s package.xml, beside the talker’s, so the bringup states every package it runs, the way a ROS 2 bringup package does. To run a node package you copied in from elsewhere, write both lines by hand.

It also gave monitor_node a row in the bringup’s contract, system.contract.yaml, beside the talker’s: one subscription to chatter and no parameters. The contract states what each node creates, so the build can size the image from it, and it must name every node the image runs. Chapter 8 writes a contract of your own.

The image table did not change. [image.freertos] still names one board, and it now builds both rows into its one program.

nros graph shows the same facts as an order: each package after the packages it depends on, with the bringup last because it runs both nodes:

nros graph
monitor_node
sensor_node
sensor_node_bringup  <- monitor_node, sensor_node

The two node packages depend on nothing in the workspace. Neither one names the other: the only thing they share is the topic name /chatter and its type, std_msgs/String, which is all a ROS 2 publisher and subscriber ever share.

Before you build, nros check catches the common mistakes in a workspace: a row naming a package or class that does not exist, or a build file left in the bringup:

nros check --workspace .
nros check: ok (workspace ., 3 pkg(s), 0 warning(s))

Run both nodes

source /opt/ros/humble/setup.bash
nros run
Publishing: 'Hello World: 1'
I heard: [Hello World: 1]

The run builds the new package, then boots the board. A Rust project’s console, trimmed:

[INFO] monitor_node: [    2.128731] Subscriber created for topic: /chatter

Application setup complete — entering spin loop.
[INFO] sensor_node: [    3.122528] Publishing: 'Hello World: 1'
[INFO] monitor_node: [    3.123277] I heard: [Hello World: 1]
[INFO] sensor_node: [    4.130612] Publishing: 'Hello World: 2'
[INFO] monitor_node: [    4.144289] I heard: [Hello World: 2]

A C or C++ project prints the same lines without the [INFO] prefix. Press Ctrl-C when you have seen both nodes.

This time the command names nothing to run. With nothing named, nros run runs the workspace’s only image, and sensor_node_bringup:freertos is still the only one.

nros run sensor_node, the spelling from chapter 1, no longer works. It meant “the bringup whose only node is sensor_node”, and the bringup now has two, so it refuses and prints the full name that would work:

nros run: `sensor_node` is a component of `sensor_node_bringup`, but never the only one, so it names no one image; name one:
  sensor_node_bringup:freertos

nros run sensor_node_bringup:freertos always works: it is the bringup and the image, the name chapter 2’s --dry-run printed. nros run never guesses between several images; when a short name matches more than one, it lists the full names instead.

To see which rule picked the image when nothing is named, add --dry-run --why as in chapter 2. The [provenance] table’s image line now says the image was the workspace’s only one, rather than the only image of the only bringup that runs sensor_node. The same four spellings work for nros build too, and chapter 9, which gives the project a second image, lists them in the order they are tried.

The console also shows a warning from the listener’s subscription: it asked for a history of 10 messages, and this board’s receive buffer holds 4. The image granted 4 and told the ROS 2 graph so. Chapter 8 shows where that number comes from and how to state the one you need.

How two nodes share one board

Both nodes now run in one program, on a processor with one core, in one FreeRTOS task. One executor runs every callback of both nodes, one at a time: the talker’s timer callback, then the listener’s subscription callback when the message arrives, then whatever is ready next. Nothing runs two callbacks at once, so neither node needs a lock around its state.

The cost is that callbacks share the processor’s time. A callback that waits, spins or blocks holds up every other callback in the image, the other node’s included. Keep each callback short: read the message, update the state, publish, return. Work that takes longer belongs in a task of its own, which Pick a scheduling model covers, and The execution model explains how the executor decides what runs next.

For the same reason, a node cannot make a blocking service call from inside a callback: the executor is in the middle of running that callback, and the reply could never be delivered. Chapter 6 shows where such calls go instead.

What just happened

You turned a project of one node into a workspace of two, and the shape did not change.

A nano-ros workspace is a directory of packages under src/, like a colcon workspace. It has no root Cargo.toml or CMakeLists.txt, and no file that lists its packages: nros finds each package by its package.xml. nros list and nros graph show what it found. Each package keeps one role. A node package holds one node and no board; a bringup holds the board, the middleware and the list of nodes, and no code. Adding a node is therefore always two edits: a package under src/, and a row in the bringup that runs it. nros new --to makes both.

What differs from a colcon workspace is what a build produces. colcon build builds each package into its own executables. nros run built the bringup’s one image, and both node packages went into it: one program for the board, with one executor running both nodes’ callbacks. Neither node package knows the other is there. The talker would publish with no listener, and the listener would wait with no talker, in this image or in two images on two boards.

ROS 2nano-ros
ros2 pkg createnros new <pkg> inside the workspace; --to <bringup> adds its component row
colcon buildnros build (every image) or nros build <image>
ros2 run <pkg> <exe>nros run <node>, when one bringup runs only that node
ros2 launch <pkg> <file>nros run <bringup>:<image>

Organize a larger workspace covers what a workspace grows into: several bringups, shared packages, and every field of the two roles.

Next

Design background

The workspace layout and nros new --to follow RFC-0121; one page for the three languages follows RFC-0124 D9.