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

Services and actions

Tutorial · Level 2: Building real applications

Needs first: Your own message

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.

Topics carry a stream with no reply. ROS 2 has two other ways for nodes to talk: a service answers one request with one reply, and an action runs a long goal, sends feedback while it works, and ends with a result. nano-ros carries both, with the same names, types and wire format as ROS 2.

In this chapter you add four nodes to the project from the scaffold’s templates: an AddTwoInts service server and its client, and a Fibonacci action server and its client, the roles of the ROS 2 demos. At the end one run of the board prints a service reply and an action result, and a ROS 2 shell on your host calls the board’s service and sends its action server a goal:

response:
example_interfaces.srv.AddTwoInts_Response(sum=9)

This chapter introduces no new nano-ros idea. It shows the one rule services and actions add to chapter 3’s: where a node may wait for a reply.

Run every step from the root of sensor_ws. The chapter adds four node packages and a row for each to the bringup:

sensor_ws/
└── src/
    ├── action_client_node/       (new)
    ├── action_server_node/       (new)
    ├── client_node/              (new)
    ├── server_node/              (new)
    └── sensor_node_bringup/
        ├── package.xml           (changed)
        ├── system.contract.yaml  (changed)
        └── system.toml           (changed)

Add a service server and its client

nros new server_node --template server --lang rust --to sensor_node_bringup
nros new client_node --template client --lang rust --to sensor_node_bringup
nros new server_node --template server --lang c --to sensor_node_bringup
nros new client_node --template client --lang c --to sensor_node_bringup
nros new server_node --template server --lang cpp --to sensor_node_bringup
nros new client_node --template client --lang cpp --to sensor_node_bringup

Both templates use example_interfaces/srv/AddTwoInts, a standard ROS 2 interface package: two int64 fields in the request, a and b, and one in the reply, sum. Each package’s package.xml depends on example_interfaces, and the next build generates it from your ROS 2 install like any message package. Both installs on Install include it. On any other ROS 2 install, add it now: sudo apt install ros-$ROS_DISTRO-example-interfaces. A service type is a pair of messages, so a .srv file in a package of your own, beside chapter 5’s .msg, works the same way. As in chapter 3, --to also gives each node a row in the bringup’s contract, and the services: section names who serves /add_two_ints and who calls it.

The server answers each request in its callback:

#![allow(unused)]
fn main() {
fn on_callback(
    _state: &mut Self::State,
    callback: Callback<'_>,
    ctx: &mut CallbackCtx<'_>,
) {
    if callback.as_str() == "handle_add" {
        if let Ok(req) = ctx.message::<AddTwoIntsRequest>() {
            log_info!(&LOGGER, "Incoming request");
            log_info!(&LOGGER, "a: {} b: {}", req.a, req.b);
            let reply = AddTwoIntsResponse { sum: req.a + req.b };
            let _ = ctx.reply::<AddTwoIntsResponse, 64>(&reply);
        }
    }
}
}

register created the server with create_service_server_for_name_with_callback::<AddTwoInts>("/add_two_ints", "handle_add"), which binds requests on /add_two_ints to the callback named handle_add. The server’s ENTITY_BOUNDS is exact(0, 1, 0, 0, 0): one service server.

static void on_request(const example_interfaces__srv__AddTwoInts_Request* req,
                       example_interfaces__srv__AddTwoInts_Response* resp,
                       void* ctx) {
    add_server_t* self = (add_server_t*)ctx;
    self->request_count++;
    resp->sum = req->a + req->b;
    printf("[server_node] %lld + %lld = %lld\n", (long long)req->a,
           (long long)req->b, (long long)resp->sum);
}

The handler fills the reply the executor sends. configure creates the service and adds it to the executor through the functions generated for the service type, example_interfaces__srv__AddTwoInts__service_init and ..._executor_add_service.

example_interfaces::srv::AddTwoInts::Response
AddTwoIntsServer::on_request(
    const example_interfaces::srv::AddTwoInts::Request& req) {
    example_interfaces::srv::AddTwoInts::Response resp;
    resp.sum = req.a + req.b;
    printf("[server_node] %lld + %lld = %lld\n",
           static_cast<long long>(req.a), static_cast<long long>(req.b),
           static_cast<long long>(resp.sum));
    return resp;
}

configure binds the member as the handler of /add_two_ints with rclcpp::bind_service<Svc, AddTwoIntsServer, &AddTwoIntsServer::on_request>, by identity, as chapter 3’s listener bound its subscription. The member takes the request and returns the reply.

The client is where services differ from topics. A ROS 2 client often calls the service and waits for the reply. A nano-ros node cannot wait inside a callback: the executor is in the middle of running that callback, and the reply it waits for can only be delivered by the same executor, so the image would stop. The client splits the call in two:

#![allow(unused)]
fn main() {
fn on_callback(
    state: &mut Self::State,
    callback: Callback<'_>,
    _ctx: &mut CallbackCtx<'_>,
) {
    if callback.as_str() == "issue_call" && !state.done {
        state.pending = true;                        // decide; do not call here
    }
}

fn tick(state: &mut Self::State, ctx: &mut TickCtx<'_>) {
    if !state.pending || state.done {
        return;
    }
    state.pending = false;
    let req = AddTwoIntsRequest { a: 2, b: 3 };
    match ctx.call_for_name::<AddTwoIntsRequest, AddTwoIntsResponse, 64, 64>(
        "/add_two_ints",
        &req,
    ) {
        Ok(reply) => {
            log_info!(&LOGGER, "Result of add_two_ints: {}", reply.sum);
            state.done = true;
        }
        Err(e) => log_info!(&LOGGER, "Service call failed, retrying: {:?}", e),
    }
}
}

The timer callback only decides that a call is due. tick runs once per spin of the executor, between callbacks, where a call may wait for its reply. The scaffold’s client calls once, with a: 2 and b: 3, and then stops.

The C client sends a request from its timer callback every 500 ms and takes the reply on a later tick, so the callback never waits. Each request adds 1 to a counter: a counts up, b is 1.

The C++ client sends a request from its timer callback every 500 ms and takes the reply on a later tick, so the callback never waits. Each request adds 1 to a counter: a counts up, b is 1.

Add an action server and its client

nros new action_server_node --template action-server --lang rust \
    --to sensor_node_bringup
nros new action_client_node --template action-client --lang rust \
    --to sensor_node_bringup
nros new action_server_node --template action-server --lang c \
    --to sensor_node_bringup
nros new action_client_node --template action-client --lang c \
    --to sensor_node_bringup
nros new action_server_node --template action-server --lang cpp \
    --to sensor_node_bringup
nros new action_client_node --template action-client --lang cpp \
    --to sensor_node_bringup

Both use example_interfaces/action/Fibonacci: the goal is an order, the feedback is the sequence so far, and the result is the whole sequence. The client sends one goal, order: 10. The server accepts it, computes one term at a time, publishes feedback as it goes, and completes the goal with the result.

The server follows the same rule as the client. Its callbacks only decide: on_goal accepts or rejects a goal, and on_cancel accepts a cancel. The work happens in tick, which visits every active goal on each spin, adds a term, and publishes feedback or completes the goal. Spreading the work over spins is what lets the six nodes share one processor: no callback runs for long, so the talker still publishes every second while a goal is in progress. A goal’s result has a fixed capacity too: the Rust template keeps the sequence in a heapless::Vec<i32, 64> and caps order at 50.

The bringup’s system.toml now has six [[component]] rows, one per node package, and nros check --workspace . still passes. Six nodes in one image is not a limit of the board: each node’s slots are counted when the image is built, so an image too large for the board fails to build rather than failing at boot.

Run all six nodes

Leave this run going: the next section calls the board from ROS 2.

source /opt/ros/humble/setup.bash
nros run

The service reply and the action result come from different nodes, and either may print first. The run prints both:

Result of add_two_ints: 5
Result received: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
[client_node] sum:
[action_client_node] result last=
[client_node] sum:
[action_client_node] result last=

A Rust project’s console, trimmed to the four new nodes:

[INFO] server_node: [    2.143647] Waiting for service requests
[INFO] action_server_node: [    2.181442] Waiting for action goals
[INFO] action_client_node: [    2.249390] Sending goal
[INFO] action_client_node: [    2.252703] Goal sent, waiting for result
[INFO] action_server_node: [    2.254812] Received goal request with order 10
[INFO] action_server_node: [    2.258269] Publish feedback
[INFO] action_client_node: [    2.261516] Next number in sequence received: [0]
[INFO] server_node: [    3.240558] Incoming request
[INFO] server_node: [    3.244643] a: 2 b: 3
[INFO] client_node: [    3.268359] Result of add_two_ints: 5
[INFO] action_server_node: [    4.484253] Publish feedback
...
[INFO] action_server_node: [   26.009786] Goal succeeded
[INFO] action_client_node: [   26.125114] Result received: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Between those lines, the talker and the listener keep exchanging a reading every second. The goal takes about 25 seconds because the template’s server paces itself, one term every few spins, so a cancel has time to arrive.

Call them from ROS 2

The service and the action are on the ROS 2 graph like any other. The ros2 command needs the example_interfaces package on the host to call the board. Both installs on Install include it. With nros run still going, this line in a second terminal makes sure:

sudo apt-get install -y ros-humble-example-interfaces

Then call the board’s service:

source /opt/ros/humble/setup.bash
export RMW_IMPLEMENTATION=rmw_zenoh_cpp
ros2 service call /add_two_ints example_interfaces/srv/AddTwoInts '{a: 4, b: 5}'
response:
example_interfaces.srv.AddTwoInts_Response(sum=9)

and send its action server a goal of your own:

ros2 action send_goal /fibonacci example_interfaces/action/Fibonacci '{order: 5}'
Result:
    sequence:
- 0
- 1
- 1
- 2
- 3
- 5

Goal finished with status: SUCCEEDED

The board’s server printed Incoming request and a: 4 b: 5 in the first terminal, then worked through your goal while its own nodes kept running. Press Ctrl-C in the first terminal when you are done.

Change it

Make the client ask a question of your own. In the Rust client, change the request in tick to AddTwoIntsRequest { a: 20, b: 22 } and run again: the console prints Result of add_two_ints: 42. In the C and C++ clients, the request is built in the timer callback from the counter a and the constant b; set b to 41 and the first reply is sum: 41. Either way only the client package rebuilds, and the server neither knows nor cares who asked.

If it doesn’t work

  • The Rust client logs service not available, waiting again...: the client asked before the server’s service was on the graph. It asks again on its next timer tick, so a few of these lines at boot are normal. If they never stop, check that server_node is a [[component]] row of the same bringup, or running in another image on the same router.
  • ros2 service call prints waiting for service to become available... and stops there: that shell is not on zenoh, or the board is not running. Check RMW_IMPLEMENTATION=rmw_zenoh_cpp in that shell and that nros run is still going in the other.
  • ros2 action send_goal reports the goal rejected: the Rust template’s server rejects a negative order. It accepts a large one but computes only 50 terms, because its result has a fixed capacity: a sequence that could grow without bound would need a heap the board does not have. Raise the capacity in the server’s code, and the build sizes the image for it.
  • The action goal never finishes: the server works through one goal at a time. A goal sent while the in-image client’s goal is running waits its turn; the template paces each term, so a goal of order 10 takes about 25 seconds.

What just happened

You added the two remaining ROS 2 communication patterns, and they work as they do in ROS 2: the same types from example_interfaces, the same names on the graph, and a ROS 2 command line on the other end that cannot tell it is talking to a microcontroller.

What nano-ros adds is one rule, which follows from chapter 3’s one executor per image: a node never waits inside a callback. A callback decides; it records what is due in the node’s state and returns. Work that waits for a reply, or that takes many steps, goes in tick, which the executor runs on each spin, between callbacks. The client calls there, and the action server advances its goals there. That is also why nothing here needs a thread: one loop runs six nodes, and none of them holds the processor for long.

The other half of the rule is that a reply must have somewhere to go. Every request, reply, goal, feedback message and result is serialized into a buffer of a size fixed at build time: the 64 and 256 in the templates’ calls are those sizes, in bytes. Too small a buffer fails the call with an error you can log; it never writes past the end.

Each server and client also took a slot in its node’s ENTITY_BOUNDS, the second to fifth numbers of exact(...): service servers, service clients, action clients and action servers. Those slots are static memory, fixed when the image is built. Chapter 8 shows how the build sizes them, and the rest of the image, from a statement of what the system creates.

If you write ROS 2 nodes in C++, the mapping is direct:

rclcppnano-ros
create_service<Srv>(name, handler)a server bound to a callback by name (Rust) or to a member by identity (C++)
create_client<Srv>(name), then async_send_request and spin_until_future_completea client that sends in a callback or tick and takes the reply in tick
rclcpp_action::create_server with goal, cancel and accepted handlerson_goal, on_cancel and on_accepted, with the work in tick
a multi-threaded executor so a handler can blockone executor; nothing blocks inside a callback

Port a C++ node shows the C++ spellings a ported node keeps.

Next

Design background

The templates follow the ROS 2 demos’ roles and interfaces (RFC-0121 D4); one Tutorial path that adds services and actions to the same project is RFC-0124 D3.