Parameters and launch files
Needs first: Services and actions
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.
Until now the bringup’s [[component]] rows were the whole description of
the system, and nros generated a launch file from them. In this chapter the
bringup gets a launch file of its own. Through it you set a parameter that the
talker reads, so it publishes twice a second with no change to its code
afterwards, and you move both nodes to another topic name with a remap. At the
end the board prints
[INFO] sensor_node: [ 3.041841] Publishing every 500 ms
and ros2 topic list on your host shows /sensor/reading, a name that
appears in no node’s code.
Run every step from the root of sensor_ws. The chapter adds a launch file
to the bringup and changes the talker, in the language you picked:
sensor_ws/
└── src/
├── sensor_node/
│ └── src/lib.rs (changed)
└── sensor_node_bringup/
└── launch/
└── system.launch.xml (new)
sensor_ws/
└── src/
├── sensor_node/
│ └── src/Talker.c (changed)
└── sensor_node_bringup/
├── system.toml (changed)
└── launch/
└── system.launch.xml (new)
sensor_ws/
└── src/
├── sensor_node/
│ └── src/Talker.cpp (changed)
└── sensor_node_bringup/
├── system.toml (changed)
└── launch/
└── system.launch.xml (new)
Start from the generated launch file
A bringup with no launch/ directory gets a launch file generated from its
[[component]] rows on every build. Start from that file, so that adding
launch/ changes nothing until you edit it:
mkdir -p src/sensor_node_bringup/launch
cp build/nros/launch/sensor_node_bringup/launch/system.launch.xml \
src/sensor_node_bringup/launch/system.launch.xml
cat src/sensor_node_bringup/launch/system.launch.xml
<?xml version="1.0"?>
<!-- Generated by nros from this bringup's system.toml [[component]] rows.
Add launch/system.launch.xml to the bringup to replace it. -->
<launch>
<node pkg="sensor_node" exec="sensor_node" name="sensor_node"/>
<node pkg="monitor_node" exec="monitor_node" name="monitor_node"/>
<node pkg="server_node" exec="server_node" name="server_node"/>
<node pkg="client_node" exec="client_node" name="client_node"/>
<node pkg="action_server_node" exec="action_server_node" name="action_server_node"/>
<node pkg="action_client_node" exec="action_client_node" name="action_client_node"/>
</launch>
From now on launch/system.launch.xml is used instead of the generated one.
Deleting the launch/ directory goes back to generation, and the
[[component]] rows stay the list of packages the bringup runs. The file is the
ROS 2 launch XML format,
read with the same parser, so a launch file from another ROS 2 project pastes
in. Keep each <node>’s pkg and exec as the generated file wrote them:
they name the package and the class it registers.
Read a parameter in the talker
A parameter is a value a launch file gives a node. Make the talker’s period
one: read period_ms when the node starts, and keep 1,000 ms when the
launch file sets none.
src/sensor_node/src/lib.rs#![allow(unused)]
fn main() {
//! `sensor_node`: publishes a `tutorial_msgs/Reading` on `/reading` once a second.
#![no_std]
use nros::{
Callback, CallbackCtx, Component, DeclarativeNode, ExecutableNode,
NodeContext, NodeOptions, NodeResult, ParameterDefault, TimerDuration,
};
use nros_log::{Logger, log_info};
use tutorial_msgs::msg::Reading;
static LOGGER: Logger = Logger::new("sensor_node");
pub struct Talker;
impl Component for Talker {
const NAME: &'static str = "sensor_node";
const ENTITY_BOUNDS: nros::EntityBounds =
nros::EntityBounds::exact(1, 0, 0, 0, 0);
fn register(ctx: &mut NodeContext<'_>) -> NodeResult<()> {
nros_log::register_logger(&LOGGER);
// The launch file's `<param name="period_ms" .../>`, baked in at build
// time; 1000 ms when the launch file sets none.
let period_ms: u64 = ctx
.param("period_ms")
.and_then(|v| v.parse().ok())
.unwrap_or(1000);
let mut node = ctx.create_node(NodeOptions::new("sensor_node"))?;
// State the parameter and its default, so the build sees it.
node.declare_parameter_for_name_with_default(
"period_ms",
ParameterDefault::Integer(1000),
)?;
let pub_reading = node.create_publisher_for_topic::<Reading>("/reading")?;
let _timer = node.create_timer_for_callback_name(
"on_tick",
TimerDuration::from_millis(period_ms),
)?;
log_info!(&LOGGER, "Publishing every {} ms", period_ms);
node.callback_for_name("on_tick")
.publishes_entity(&pub_reading)?;
Ok(())
}
}
impl ExecutableNode for Talker {
/// The sequence number of the last reading published.
type State = i32;
const HAS_TICK: bool = false;
fn init() -> Self::State {
0
}
fn on_callback(
state: &mut Self::State,
callback: Callback<'_>,
ctx: &mut CallbackCtx<'_>,
) {
if callback.as_str() == "on_tick" {
*state = state.wrapping_add(1);
let msg = Reading {
sequence: *state,
temperature_mc: 21_000 + (*state % 10) * 100,
};
let _ = ctx.publish_to_topic::<Reading, 32>("/reading", &msg);
log_info!(
&LOGGER,
"Publishing: reading {} ({} mC)",
msg.sequence,
msg.temperature_mc
);
}
}
}
nros::node!(Talker);
}
ctx.param("period_ms") returns the value the launch file gives, as text,
or None. The value is baked into the image when it is built, so reading it
costs no lookup at run time and needs no parameter store.
declare_parameter_for_name_with_default states that the node has the
parameter, as a ROS 2 node declares one; chapter 9’s host image checks the
contract against such declarations.
src/sensor_node/src/Talker.c// sensor_node: publishes a tutorial_msgs/Reading on /reading once a second.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <rcl/rcl.h>
#include <rclc/executor.h>
#include <rclc/rclc.h>
#include <rclc_parameter/rclc_parameter.h>
#include <tutorial_msgs/tutorial_msgs.h>
typedef struct {
rcl_publisher_t pub;
rcl_timer_t timer;
rclc_parameter_server_t params;
int32_t count;
} talker_t;
static void on_tick(rcl_timer_t* timer, int64_t last_call_time) {
talker_t* self = RCLC_CONTAINER_OF(timer, talker_t, timer);
(void)last_call_time;
self->count++;
tutorial_msgs__msg__Reading msg;
memset(&msg, 0, sizeof msg);
msg.sequence = self->count;
msg.temperature_mc = 21000 + (self->count % 10) * 100;
if (rcl_publish(&self->pub, &msg, NULL) == RCL_RET_OK) {
printf("Publishing: reading %d (%d mC)\n", (int)msg.sequence,
(int)msg.temperature_mc);
}
}
static rcl_ret_t talker_configure(rcl_node_t* node, rclc_executor_t* executor,
talker_t* self) {
setvbuf(stdout, NULL, _IOLBF, 0);
self->count = 0;
// The launch file's <param name="period_ms" .../>; 1000 ms when it sets none.
rcl_ret_t rc = rclc_parameter_server_init_default(&self->params, node);
if (rc != RCL_RET_OK) {
return rc;
}
rc = rclc_parameter_declare_int(&self->params, "period_ms", 1000);
if (rc != RCL_RET_OK) {
return rc;
}
int64_t period_ms = 1000;
(void)rclc_parameter_get_int(&self->params, "period_ms", &period_ms);
printf("Publishing every %d ms\n", (int)period_ms);
self->pub = rcl_get_zero_initialized_publisher();
rc = rclc_publisher_init_default(
&self->pub, node,
ROSIDL_GET_MSG_TYPE_SUPPORT(tutorial_msgs, msg, Reading), "/reading");
if (rc != RCL_RET_OK) {
return rc;
}
self->timer = rcl_get_zero_initialized_timer();
rc = rclc_timer_init_default(&self->timer, NULL,
(uint64_t)period_ms * 1000000ULL, on_tick);
if (rc != RCL_RET_OK) {
return rc;
}
return rclc_executor_add_timer(executor, &self->timer);
}
RCLC_C_COMPONENT(talker_t, talker_configure)
The C node keeps its parameters in rclc’s parameter server.
rclc_parameter_declare_int states that the node has period_ms, with
1000 as its default; a value the launch file gives is kept. The declaration
is what chapter 9’s host image records and compares with the contract.
src/sensor_node/src/Talker.cpp#include "sensor_node/Talker.hpp"
#include <stdio.h>
namespace sensor_node {
void Talker::on_tick() {
++count_;
::tutorial_msgs::msg::Reading msg;
msg.sequence = count_;
msg.temperature_mc = 21000 + (count_ % 10) * 100;
if (pub_.publish(msg).ok()) {
printf("Publishing: reading %d (%d mC)\n",
static_cast<int>(msg.sequence),
static_cast<int>(msg.temperature_mc));
}
}
::rclcpp::Result Talker::configure(::rclcpp::Node& node) {
::setvbuf(stdout, nullptr, _IOLBF, 0);
::rclcpp::Result r = node.create_publisher(pub_, "/reading");
if (!r.ok()) return r;
// The launch file's <param name="period_ms" .../>; 1000 ms when it sets none.
const int64_t period_ms = node.declare_parameter<int64_t>("period_ms", 1000);
printf("Publishing every %d ms\n", static_cast<int>(period_ms));
return node.create_wall_timer<Talker, &Talker::on_tick>(
timer_, static_cast<uint32_t>(period_ms), this);
}
} // namespace sensor_node
node.declare_parameter states that the node has period_ms, with 1000 as
its default, and returns the value the launch file gives when it gives one,
as rclcpp’s does. The declaration is what chapter 9’s host image records and
compares with the contract.
Set it in the launch file
Now give the talker a period, and move the reading topic to a name of your choosing. Replace the launch file:
src/sensor_node_bringup/launch/system.launch.xml<?xml version="1.0"?>
<launch>
<arg name="topic" default="/sensor/reading"/>
<node pkg="sensor_node" exec="sensor_node" name="sensor_node">
<param name="period_ms" value="500"/>
<remap from="/reading" to="$(var topic)"/>
</node>
<node pkg="monitor_node" exec="monitor_node" name="monitor_node">
<remap from="/reading" to="$(var topic)"/>
</node>
<node pkg="server_node" exec="server_node" name="server_node"/>
<node pkg="client_node" exec="client_node" name="client_node"/>
<node pkg="action_server_node" exec="action_server_node" name="action_server_node"/>
<node pkg="action_client_node" exec="action_client_node" name="action_client_node"/>
</launch>
Three things changed:
<arg name="topic" default="/sensor/reading"/>declares a launch argument with a default.$(var topic)expands it anywhere below.<param name="period_ms" value="500"/>inside the talker’s<node>sets the parameter the code reads.<remap from="/reading" to="$(var topic)"/>inside both nodes renames the topic they create as/reading, so both now publish and subscribe on/sensor/reading. Remap both or neither: a remap applies to the node it is in, and two nodes on different names do not hear each other.
Run it
Leave this run going for the next section:
source /opt/ros/humble/setup.bash
nros run
Publishing every 500 ms
I heard: reading 4
A Rust project’s console, trimmed to the talker and listener:
[INFO] sensor_node: [ 3.041841] Publishing every 500 ms
[INFO] sensor_node: [ 3.485234] Publishing: reading 1 (21100 mC)
[INFO] monitor_node: [ 3.487297] I heard: reading 1 (21100 mC)
[INFO] sensor_node: [ 3.975575] Publishing: reading 2 (21200 mC)
[INFO] monitor_node: [ 3.991086] I heard: reading 2 (21200 mC)
[INFO] sensor_node: [ 4.423176] Publishing: reading 3 (21300 mC)
[INFO] monitor_node: [ 4.431667] I heard: reading 3 (21300 mC)
[INFO] sensor_node: [ 5.038481] Publishing: reading 4 (21400 mC)
[INFO] monitor_node: [ 5.073491] I heard: reading 4 (21400 mC)
Readings now arrive every half second. Change value="500" to another
period and run again: only the image rebuilds, and the talker’s package
does not change.
The same mechanism serves a second board or a second deployment of the same board. Two launch files in one bringup, each with its own parameters and remaps, can run the same node packages as two different systems; chapter 9 gives the project a second image, and an image can name the launch file it builds. A node package that reads its configuration from parameters, rather than from constants in its code, is a node package you never fork.
See the new name in ROS 2
In a second terminal, list the topics and the nodes the router knows.
--no-daemon asks the router directly: a ros2 daemon left over from an
earlier chapter still holds a session to the router that nros run has
since replaced, and it answers with an error.
source /opt/ros/humble/setup.bash
export RMW_IMPLEMENTATION=rmw_zenoh_cpp
ros2 topic list --no-daemon --spin-time 3
ros2 node list --no-daemon --spin-time 3
/parameter_events
/rosout
/sensor/reading
/action_client_node
/action_server_node
/client_node
/monitor_node
/sensor_node
/server_node
/sensor/reading is the remapped topic, and the six nodes of the image are
six nodes on the ROS 2 graph. Press Ctrl-C in the first terminal when you
are done.
Compare this with what ROS 2 shows for nodes on your own machine: the same two commands, the same names. The board’s launch file decided those names when it was built, and the graph sees the result. Nothing on the ROS 2 side can tell that the remap happened at build time rather than at launch.
Parameters from a file
For more than a few values, a node loads a standard ROS 2 parameter file.
Start its path with $(dirname), the launch file’s own directory. A bare
relative path is resolved against the working directory, not the launch
file, exactly as ros2 launch resolves it, so it breaks as soon as the
command runs from another directory:
# launch/sensor.param.yaml
/**: # every node
ros__parameters:
use_sim_time: false
sensor_node: # this node only
ros__parameters:
period_ms: 250
<node pkg="sensor_node" exec="sensor_node" name="sensor_node">
<param from="$(dirname)/sensor.param.yaml"/>
<param name="period_ms" value="500"/> <!-- wins over the file -->
</node>
The file is the same YAML a ROS 2 node loads with --params-file, so a
parameter file written for the same node on a ROS 2 machine works here
unchanged, and the build reads it as it reads the launch file: once, when the
image is built.
Precedence is ROS 2’s: the /** block, then the node’s own block (keyed
sensor_node, /ns/sensor_node or /**/sensor_node), then an inline
<param name= value=>. A from= naming a missing file is a build error.
What the image does with parameters at run time is decided in system.toml.
Every image gets the parameter services, as a ROS 2 node does, unless it opts
out with node_interfaces = "none":
system.toml states | Parameter store (get_parameter, launch values) | ros2 param services |
|---|---|---|
| nothing (the default) | yes | six per node: get, set, list, describe, and two more |
node_interfaces = "none" and features = ["params"] | yes | none |
node_interfaces = "none" | Rust’s ctx.param reads the baked value | none |
The store alone suits a small board whose nodes only read their
configuration: each of the six services costs memory per node. What it gives
up is ros2 param get, set, list, describe and dump, and the
use_sim_time switch. node_interfaces = "none" also turns off each node’s
/rosout publisher.
Read once, or read live
The talker reads period_ms once, in register or configure, and builds
its timer from it. That is the right shape for a value that sizes or shapes
the node: a period, a buffer length, a frame name. It is also why the launch
file is the place to set it: the value is decided when the image is built,
and every boot of the image starts with it.
A value the node should follow while it runs is read in the callback
instead, from the parameter store, on every call. With the parameter
services on (the default), ros2 param set /sensor_node <name> <value> from a ROS 2 shell
changes that live value on the board. It changes nothing a node read once:
setting period_ms that way would leave the timer at the period it was built
with. A value set at run time is also volatile. The next boot starts from the
launch file again, because the board has nowhere to store the change.
If it doesn’t work
- The talker prints
Publishing every 1000 ms: the parameter did not reach it. Check that the<param>is inside the talker’s own<node>, and that itsnameis exactly the one the code reads. - The listener stops hearing readings: only one of the two nodes is remapped. Remap both, or neither.
- A C build stops with
#error "<rclc_parameter/rclc_parameter.h> needs the param_services capability": the bringup opts out withnode_interfaces = "none", which removes the parameter services even wherefeaturesdeclares them. Remove it from the image whose node reads parameters. - The build names a package that does not exist: a
<node>’spkgnames no package in the workspace.nros check --workspace .lists every such mistake before a build. - A C++ node stops at boot with
parameter "…" is declared double but the launch value is the integer 1; write 1.0 in the YAML: the launch file or YAML gives the parameter a value of another type thandeclare_parameter<T>asks for. Write the value in the declared type, as the line says.
The launch file, briefly
| Tag | Purpose |
|---|---|
<arg name="…" default="…"/> | declare a launch argument |
<node pkg="…" exec="…" name="…"/> | start a node |
<param name="…" value="…"/> | set one parameter (inside <node>) |
<param from="$(dirname)/….yaml"/> | load a ROS 2 parameter file (inside <node>), named from the launch file’s directory |
<remap from="…" to="…"/> | rename a topic or service (inside <node>) |
<group ns="…"> | put a group of nodes in a namespace |
<include file="…"/> | include another launch file |
Substitutions: $(var <arg>) expands a launch argument, $(find <pkg>) a
package’s path, and $(env <name>) an environment variable.
What just happened
The bringup’s launch file became the system’s description: which nodes run, under which names, on which topics, with which parameters. The node packages say what a node can do; the launch file says what this system does with them.
Where ROS 2 reads a launch file when you run ros2 launch, nano-ros reads it
when it builds the image. There is no ros2 launch step and no launch
process on the board. The build resolves the file, arguments, remaps,
parameter files and all, into a fixed system: the nodes to construct, the
names to give them, and the parameter values to bake in. The image starts
exactly that system, every time, on a board that has no file system to read a
launch file from. Editing the launch file or a parameter file rebuilds the
image, and nothing in src/sensor_node/ changes.
The same resolved system is what the next chapter builds on. Because the build knows, before it compiles anything, every node the image will run and every topic, service and action they use, it can size the image’s memory for exactly that system, if you tell it what the nodes create.
Next
- Tell the build what your system creates: the contract beside this launch file, and what it sizes in the image.
- Use simulated time: the
use_sim_timeparameter and a clock from ROS 2. - Organize a larger workspace: several bringups and several launch files.
Design background
Resolving the launch file at build time, with the ROS 2 launch parser, follows RFC-0121 D2 and D3.