CodeTheRobot

C++ Advanced · Lesson 14 of 23

Actions

Goals with feedback, results and cancellation using rclcpp_action.

Estimated time · 90–120 min

Learning goals

What you will understand

  • Explain actions in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

An action is for work that takes time: a client sends a goal, the server accepts it, sends periodic feedback, and finally returns a result. The client can cancel the goal at any time. Navigating to a pose and moving an arm are typical actions.

An action server needs three callbacks: handle_goal (accept or reject), handle_cancel (accept a cancel request) and handle_accepted (start the work, usually on another thread so the executor is free). Test with ros2 action send_goal --feedback.

Guided lesson

Work through these steps

  1. 1.

    Read the actions example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

#include "rclcpp_action/rclcpp_action.hpp"
// Action server and client support for rclcpp.
#include "example_interfaces/action/fibonacci.hpp"
// A ready-made action type with a goal, feedback and result.
using Fib = example_interfaces::action::Fibonacci;
// A short name for the action type.
server_ = rclcpp_action::create_server<Fib>(this, "fibonacci",
// Create an action server named /fibonacci on this node.
  [](const rclcpp_action::GoalUUID&, std::shared_ptr<const Fib::Goal>) {
// handle_goal: called for every new goal.
    return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
// Accept every goal (real code validates it).
  },
// End of handle_goal.
  [](std::shared_ptr<rclcpp_action::ServerGoalHandle<Fib>>) {
// handle_cancel: called when a client cancels.
    return rclcpp_action::CancelResponse::ACCEPT;
// Allow cancellation.
  },
// End of handle_cancel.
  [this](std::shared_ptr<rclcpp_action::ServerGoalHandle<Fib>> h) {
// handle_accepted: start the work.
    std::thread{[h] { auto r = std::make_shared<Fib::Result>(); h->succeed(r); }}.detach();
// Run on a worker thread and report success (a real server sends feedback in a loop).
  });
// End of handle_accepted and the call.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Messages between nodes

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

requestresponseclientservercalls answered: 0MESSAGES BETWEEN NODES

Demo for Actions. Expected result: ros2 action send_goal /fibonacci example_interfaces/action/Fibonacci '{order: 5}' --feedback -> feedback lines, then a result

Practice code

Now type it yourself

Copy the starter into your ROS 2 package, replace every TODO, then build with colcon build and run it from a sourced terminal.

// Fragment for the constructor of a node class (see the lesson for the full package layout)
#include <thread>

#include "example_interfaces/action/fibonacci.hpp"
#include "rclcpp_action/rclcpp_action.hpp"

using Fib = example_interfaces::action::Fibonacci;
using GoalHandle = rclcpp_action::ServerGoalHandle<Fib>;

class FibServer : public rclcpp::Node {
 public:
  FibServer() : Node("fib_server") {
    // TODO: create the server with three callbacks: accept every goal, accept cancels, and run the goal on a worker thread
  }

 private:
  rclcpp_action::Server<Fib>::SharedPtr server_;
};

Expected output

ros2 action send_goal /fibonacci example_interfaces/action/Fibonacci '{order: 5}' --feedback  ->  feedback lines, then a result
Stuck? Show the full solution (try it yourself first)
// Fragment for the constructor of a node class (see the lesson for the full package layout)
#include <thread>

#include "example_interfaces/action/fibonacci.hpp"
#include "rclcpp_action/rclcpp_action.hpp"

using Fib = example_interfaces::action::Fibonacci;
using GoalHandle = rclcpp_action::ServerGoalHandle<Fib>;

class FibServer : public rclcpp::Node {
 public:
  FibServer() : Node("fib_server") {
    server_ = rclcpp_action::create_server<Fib>(
        this, "fibonacci",
        [](const rclcpp_action::GoalUUID&, std::shared_ptr<const Fib::Goal>) {
          return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
        },
        [](std::shared_ptr<GoalHandle>) { return rclcpp_action::CancelResponse::ACCEPT; },
        [](std::shared_ptr<GoalHandle> h) {
          std::thread{[h] { h->succeed(std::make_shared<Fib::Result>()); }}.detach();
        });
  }

 private:
  rclcpp_action::Server<Fib>::SharedPtr server_;
};

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Implement the Fibonacci action with feedback after each number and a cancel check inside the loop. Send a goal with ros2 action send_goal --feedback, then cancel it from a second terminal and confirm the server stops.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.