Your own message
Needs first: Pick and configure the RMW
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.
So far the project has sent text: std_msgs/String, a message package that
comes with ROS 2. A sensor sends numbers, with names and units. In this
chapter you write a message package of your own, tutorial_msgs, with one
message, Reading, and change both nodes to use it. At the end the board
prints
[INFO] sensor_node: [ 3.143246] Publishing: reading 1 (21100 mC)
[INFO] monitor_node: [ 3.167941] I heard: reading 1 (21100 mC)
and the package you wrote is an ordinary ROS 2 message package, which a ROS 2 machine builds unchanged.
Run every step from the root of sensor_ws. The chapter adds one package
and changes both nodes, in the language you picked:
sensor_ws/
└── src/
├── monitor_node/
│ ├── package.xml (changed)
│ └── src/lib.rs (changed)
├── sensor_node/
│ ├── package.xml (changed)
│ └── src/lib.rs (changed)
└── tutorial_msgs/ (new)
├── CMakeLists.txt (new)
├── package.xml (new)
└── msg/Reading.msg (new)
sensor_ws/
└── src/
├── monitor_node/
│ ├── CMakeLists.txt (changed)
│ ├── package.xml (changed)
│ └── src/Listener.c (changed)
├── sensor_node/
│ ├── CMakeLists.txt (changed)
│ ├── package.xml (changed)
│ └── src/Talker.c (changed)
└── tutorial_msgs/ (new)
├── CMakeLists.txt (new)
├── package.xml (new)
└── msg/Reading.msg (new)
sensor_ws/
└── src/
├── monitor_node/
│ ├── CMakeLists.txt (changed)
│ ├── package.xml (changed)
│ ├── include/monitor_node/Listener.hpp (changed)
│ └── src/Listener.cpp (changed)
├── sensor_node/
│ ├── CMakeLists.txt (changed)
│ ├── package.xml (changed)
│ ├── include/sensor_node/Talker.hpp (changed)
│ └── src/Talker.cpp (changed)
└── tutorial_msgs/ (new)
├── CMakeLists.txt (new)
├── package.xml (new)
└── msg/Reading.msg (new)
Write the message package
A message package is a directory under src/ with a package.xml, a
CMakeLists.txt and one file per message. nano-ros reads the stock ROS 2
shape, so these three files are exactly what the ROS 2 documentation’s
custom interfaces tutorial
has you write. Create them in an editor.
The manifest declares the package an interface package:
src/tutorial_msgs/package.xml<?xml version="1.0"?>
<package format="3">
<name>tutorial_msgs</name>
<version>0.1.0</version>
<description>The Tutorial project's messages</description>
<maintainer email="you@example.com">you</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<build_depend>rosidl_default_generators</build_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
The build file asks rosidl to generate the interfaces. nano-ros never runs
this file: its build reads the package’s msg/ directory itself. It is
there so the same package builds with colcon on a ROS 2 machine, which
chapter 10 does.
src/tutorial_msgs/CMakeLists.txtcmake_minimum_required(VERSION 3.20)
project(tutorial_msgs)
find_package(ament_cmake REQUIRED)
find_package(rosidl_default_generators REQUIRED)
rosidl_generate_interfaces(${PROJECT_NAME}
msg/Reading.msg
)
ament_export_dependencies(rosidl_default_runtime)
ament_package()
And the message, in the ROS 2 .msg format, one field per line:
src/tutorial_msgs/msg/Reading.msg# One sample from the sensor node.
int32 sequence # counts up from 1
int32 temperature_mc # milli-degrees Celsius
Each line is a type and a name. The types are ROS 2’s, and each maps to the same type in every language the project can use:
.msg type | Rust | C | C++ |
|---|---|---|---|
int32 | i32 | int32_t | int32_t |
float64 | f64 | double | double |
bool | bool | bool | bool |
string | a fixed-capacity string | a pointer, size and capacity into memory you own | a fixed-capacity string |
T[] | a fixed-capacity sequence | a pointer, size and capacity into memory you own | a fixed-capacity sequence |
The last two rows are where a microcontroller shows: a string or a sequence cannot grow at run time, because nothing allocates. What that costs is in “What just happened” below.
Both fields are integers. The temperature is in thousandths of a degree,
21100 for 21.1 °C, a common choice on a microcontroller: it keeps the
message small and exact, and printing it needs no floating-point formatting,
which costs flash on a board this size.
Ask nros whether it found the message:
nros interface show tutorial_msgs/msg/Reading
# One sample from the sensor node.
int32 sequence # counts up from 1
int32 temperature_mc # milli-degrees Celsius
nros interface show searches the workspace’s src/ first, then your ROS 2
install, so it prints any message a node in this workspace can use.
nros interface list prints all of them.
Depend on it
Each node declares the message packages it uses in its package.xml.
Replace std_msgs with tutorial_msgs in both nodes:
src/sensor_node/package.xml, change the marked lines <license>Apache-2.0</license>
- <depend>std_msgs</depend>
+ <depend>tutorial_msgs</depend>
<export>
src/monitor_node/package.xml, change the marked lines <license>Apache-2.0</license>
- <depend>std_msgs</depend>
+ <depend>tutorial_msgs</depend>
<export>
In Rust, that is the whole change to the build: the next build rewrites the
# nros-managed row in each Cargo.toml to the generated tutorial_msgs
crate. A C or C++ build finds message packages with find_package, so
change that line in each node’s CMakeLists.txt too:
Nothing more to change: Cargo.toml follows package.xml.
src/sensor_node/CMakeLists.txt, change the marked lines set(CMAKE_C_STANDARD_REQUIRED ON)
find_package(nano_ros REQUIRED)
-find_package(std_msgs REQUIRED)
+find_package(tutorial_msgs REQUIRED)
src/monitor_node/CMakeLists.txt, change the marked lines set(CMAKE_C_STANDARD_REQUIRED ON)
find_package(nano_ros REQUIRED)
-find_package(std_msgs REQUIRED)
+find_package(tutorial_msgs REQUIRED)
src/sensor_node/CMakeLists.txt, change the marked lines set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(nano_ros REQUIRED)
-find_package(std_msgs REQUIRED)
+find_package(tutorial_msgs REQUIRED)
src/sensor_node/CMakeLists.txt, change the marked lines target_link_libraries(sensor_node_sensor_node_component
- PUBLIC std_msgs__nano_ros_cpp)
+ PUBLIC tutorial_msgs__nano_ros_cpp)
src/monitor_node/CMakeLists.txt, change the marked lines set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(nano_ros REQUIRED)
-find_package(std_msgs REQUIRED)
+find_package(tutorial_msgs REQUIRED)
src/monitor_node/CMakeLists.txt, change the marked lines target_link_libraries(monitor_node_monitor_node_component
- PUBLIC std_msgs__nano_ros_cpp)
+ PUBLIC tutorial_msgs__nano_ros_cpp)
The C++ node also links the generated C++ message library by name, in its
target_link_libraries line.
Publish a reading
Replace the talker’s code. It publishes a Reading on /reading once a
second, with a sequence number and a temperature that steps through ten
values:
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, 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);
let mut node = ctx.create_node(NodeOptions::new("sensor_node"))?;
let pub_reading = node.create_publisher_for_topic::<Reading>("/reading")?;
let _timer = node.create_timer_for_callback_name(
"on_tick",
TimerDuration::from_millis(1000),
)?;
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);
}
tutorial_msgs::msg::Reading is a plain Rust struct with one field per line
of the .msg file, generated under generated/tutorial_msgs. The 32 in
publish_to_topic::<Reading, 32> is the size of the buffer the message is
serialized into, in bytes; a Reading needs 12.
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 <tutorial_msgs/tutorial_msgs.h>
typedef struct {
rcl_publisher_t pub;
rcl_timer_t timer;
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;
self->pub = rcl_get_zero_initialized_publisher();
rcl_ret_t 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, 1000000000ULL, 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 generated header, <tutorial_msgs/tutorial_msgs.h>, declares
tutorial_msgs__msg__Reading with rosidl’s C names, and
ROSIDL_GET_MSG_TYPE_SUPPORT(tutorial_msgs, msg, Reading) names its type
support, as in rclc.
src/sensor_node/include/sensor_node/Talker.hpp#pragma once
#include <rclcpp/rclcpp.hpp>
#include "tutorial_msgs.hpp"
namespace sensor_node {
class Talker {
::rclcpp::Publisher<::tutorial_msgs::msg::Reading> pub_;
::rclcpp::Timer timer_;
int32_t count_ = 0;
void on_tick();
public:
::rclcpp::Result configure(::rclcpp::Node& node);
};
} // namespace sensor_node
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;
return node.create_wall_timer<Talker, &Talker::on_tick>(timer_, 1000, this);
}
} // namespace sensor_node
The generated header, tutorial_msgs.hpp, declares
tutorial_msgs::msg::Reading with the member names of the .msg file, as
rclcpp’s generated headers do.
Hear a reading
Replace the listener’s code to match. It subscribes to /reading and
prints both fields:
src/monitor_node/src/lib.rs#![allow(unused)]
fn main() {
//! `monitor_node`: subscribes to `/reading` and logs each reading.
#![no_std]
use nros::{
Callback, CallbackCtx, Component, DeclarativeNode, ExecutableNode,
NodeContext, NodeOptions, NodeResult,
};
use nros_log::{Logger, log_info};
use tutorial_msgs::msg::Reading;
static LOGGER: Logger = Logger::new("monitor_node");
pub struct Listener;
impl Component for Listener {
const NAME: &'static str = "monitor_node";
const ENTITY_BOUNDS: nros::EntityBounds =
nros::EntityBounds::exact(0, 0, 0, 0, 0);
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::<Reading>(
"on_reading",
"/reading",
)?;
Ok(())
}
}
impl ExecutableNode for Listener {
/// Number of readings seen.
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_reading"
&& let Ok(msg) = ctx.message::<Reading>()
{
*state = state.wrapping_add(1);
log_info!(
&LOGGER,
"I heard: reading {} ({} mC)",
msg.sequence,
msg.temperature_mc
);
}
}
}
nros::node!(Listener);
}
src/monitor_node/src/Listener.c// monitor_node: subscribes to /reading and prints each reading.
#include <stdint.h>
#include <stdio.h>
#include <rcl/rcl.h>
#include <rclc/executor.h>
#include <rclc/rclc.h>
#include <tutorial_msgs/tutorial_msgs.h>
typedef struct {
rcl_subscription_t sub;
tutorial_msgs__msg__Reading msg;
int recv;
} listener_t;
static void on_msg(const void* msgin, void* ctx) {
listener_t* self = (listener_t*)ctx;
const tutorial_msgs__msg__Reading* msg =
(const tutorial_msgs__msg__Reading*)msgin;
printf("I heard: reading %d (%d mC)\n", (int)msg->sequence,
(int)msg->temperature_mc);
self->recv++;
}
static rcl_ret_t listener_configure(rcl_node_t* node, rclc_executor_t* executor,
listener_t* self) {
setvbuf(stdout, NULL, _IOLBF, 0);
self->recv = 0;
self->sub = rcl_get_zero_initialized_subscription();
rcl_ret_t rc = rclc_subscription_init_default(
&self->sub, node,
ROSIDL_GET_MSG_TYPE_SUPPORT(tutorial_msgs, msg, Reading), "/reading");
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)
The message lives in the node’s state struct, so nothing allocates when a
reading arrives. A Reading holds no string or sequence, so it needs no
storage beyond the struct.
src/monitor_node/include/monitor_node/Listener.hpp#pragma once
#include <rclcpp/rclcpp.hpp>
#include "tutorial_msgs.hpp"
namespace monitor_node {
class Listener {
int recv_ = 0;
void on_reading(const ::tutorial_msgs::msg::Reading& msg);
public:
::rclcpp::Result configure(::rclcpp::Node& node);
};
} // namespace monitor_node
src/monitor_node/src/Listener.cpp#include "monitor_node/Listener.hpp"
#include <stdio.h>
namespace monitor_node {
void Listener::on_reading(const ::tutorial_msgs::msg::Reading& msg) {
printf("I heard: reading %d (%d mC)\n",
static_cast<int>(msg.sequence),
static_cast<int>(msg.temperature_mc));
++recv_;
}
::rclcpp::Result Listener::configure(::rclcpp::Node& node) {
::setvbuf(stdout, nullptr, _IOLBF, 0);
return ::rclcpp::bind_subscription<::tutorial_msgs::msg::Reading, Listener,
&Listener::on_reading>(node, "/reading", this);
}
} // namespace monitor_node
Run it
source /opt/ros/humble/setup.bash
nros run
Publishing: reading 1 (21100 mC)
I heard: reading 1 (21100 mC)
The first lines of the build show the new package being generated before anything compiles (a Rust project’s output, trimmed):
sync: codegen tutorial_msgs
sync: message dependencies → /home/you/sensor_ws/src/sensor_node/Cargo.toml
sync: message dependencies → /home/you/sensor_ws/src/monitor_node/Cargo.toml
and the console then shows the readings:
[INFO] sensor_node: [ 3.143246] Publishing: reading 1 (21100 mC)
[INFO] monitor_node: [ 3.167941] I heard: reading 1 (21100 mC)
[INFO] sensor_node: [ 4.169282] Publishing: reading 2 (21200 mC)
[INFO] monitor_node: [ 4.225809] I heard: reading 2 (21200 mC)
A C or C++ project prints the same lines without the [INFO] prefix. Press
Ctrl-C to stop it.
generated/ now holds tutorial_msgs beside the packages generated before
it. A package no node depends on any more stays there until you delete
generated/; it is never linked into the image, so it costs nothing on the
board.
The topic changed with the type: both nodes now use /reading, and nothing
publishes on /chatter any more. A topic’s name and its type travel
together, so a subscriber on /reading with another type would match
nothing, on the board or in ROS 2.
Your own, or one from ROS 2
ROS 2 already ships a temperature message, sensor_msgs/msg/Temperature.
A node uses it exactly as it used std_msgs: <depend>sensor_msgs</depend>
in its package.xml, and the build generates it from your ROS 2 install. Use
an installed message when the machines you talk to expect it: a ROS 2 tool
that plots temperatures reads sensor_msgs/msg/Temperature, not yours.
Write your own when no standard message fits, or when the standard one costs
more than the board can spend. Temperature carries a std_msgs/Header,
whose frame_id is an unbounded string, and two float64 fields, so every
sample needs a string capacity and floating-point formatting to print.
Reading is 8 bytes of payload. The choice is per message, and a workspace
can mix both: one node can depend on tutorial_msgs and sensor_msgs at
once. Whichever you pick, a peer that receives it needs the same definition:
for a ROS 2 machine, an installed package or the same .msg source built
there.
Change it
Add a field and follow it through. Append a line to Reading.msg:
src/tutorial_msgs/msg/Reading.msgint32 humidity_pct # relative humidity, percent
then set humidity_pct in the talker and print it in the listener. The next
nros run regenerates tutorial_msgs before it compiles anything, and a node
that sets or reads a field the message lacks fails to compile, naming the
field. Nothing else in the workspace needs to know the message changed: the
two nodes share it through package.xml, never through each other.
If it doesn’t work
nros interface showsays the type is not found: the package is not where the search starts. It must sit directly undersrc/, with itspackage.xmland amsg/directory beside it.- Rust:
unresolved import tutorial_msgs: the node’spackage.xmlstill depends onstd_msgsonly. Check the<depend>line, then run again; the build writes theCargo.tomlrow. - C or C++: CMake cannot find
tutorial_msgs: the node’sCMakeLists.txtstill saysfind_package(std_msgs REQUIRED). Change it, and for C++ thetarget_link_librariesline too. - The build stops naming
AMENT_PREFIX_PATH: the generator readsrosidl_default_generatorsand the base types from ROS 2. Source ROS 2 in this shell, as in chapter 1.
What just happened
You wrote a message package, and the build turned it into code for every node that depends on it.
A message package holds definitions and no code. Its msg/ directory is the
whole interface; package.xml names it and marks it an interface package
with <member_of_group>rosidl_interface_packages</member_of_group>. On each
build, nros finds every message package a node depends on, in this order,
and generates code for it under generated/:
- a package under the workspace’s
src/, such astutorial_msgs; - a package in your ROS 2 install, such as
std_msgs, throughAMENT_PREFIX_PATHor the prefix the workspace’s first build recorded; - a few standard packages the nano-ros release carries, which only fill gaps under a ROS 2 install and never stand in for one.
A workspace package shadows an installed one of the same name, whole: it replaces all of that package’s messages, not one of them.
What the build generates is where nano-ros differs from ROS 2. ROS 2
generates code that allocates: a std::string, a std::vector, rosidl’s
__init and __fini in C. nano-ros generates code whose every string and
sequence has a capacity fixed when the image is built.
A Rust message is a no_std struct built on fixed-capacity types. A C
message’s strings and sequences point at memory the node owns. Because
nothing grows at run time, an unbounded string or [] sequence in a
.msg file needs a capacity stated at build time. A C or C++ node states it
in nros-codegen.toml beside its package.xml: the scaffold wrote one for
std_msgs/String, "std_msgs/String.data" = 256. Reading holds two
integers, so it needs none.
On the wire nothing differs. The generated types serialize to the same CDR
bytes and carry the same type name, tutorial_msgs/msg/Reading, as the code
ROS 2 generates from the same .msg file. That is why chapter 10 can build
the same package with colcon and hear the board with ros2 topic echo.
Message generation lists what the
build generates and the CMake functions behind it.
Next
- Services and actions: request and reply, and long-running goals, between nodes of the same project.
- Build inside an existing CMake or vendor tree: message packages in a tree that is not a nano-ros workspace.
Design background
Generating message code from the stock ROS 2 package shape, with the workspace first on the search path, follows RFC-0094 and RFC-0098.