Skip to content
ImagineWorld

Implementing ROS 2 Applications Using

node_idnode-book_mastering-ros-2-for-robotics-programming_chapter-07-implementing-ros-2-applications-using
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleImplementing ROS 2 Applications Using
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Implementing ROS 2 Applications Using

Section titled “Chapter 7 — Implementing ROS 2 Applications Using”

Implementing robot autonomy is a complex task. Beyond executing individual tasks such as navigation, manipulation, and sensing (e.g., image processing and mapping), coordinating these tasks presents an additional challenge. For example, programming a warehouse robot to retrieve and deliver items requires carefully sequencing actions and making decisions based on the outcome of previous tasks. Traditionally, this is done using finite state machines (FSMs), but a newer approach in robotics is the use of behavior trees (BTs). An interesting scientific paper introducing BTs in the robotics environment can also be found at this link [1].

In this chapter, we will introduce the basic concepts of BTs and explain how to implement them using the BehaviorTree.CPP library, a flexible C++ tool that integrates easily with ROS 2 to handle robotic program flow based on the BT framework. We will see how to create both basic and complex structures and how to use ROS 2 functions in the BT nodes. We will also see how to use Groot, a graphical tool to create the BT by dragging, dropping, and connecting the nodes of the tree.

Here’s a list of the main topics that will be covered in the chapter:

  • Understanding BTs
  • Introducing the BehaviorTree.CPP library
  • Implementing your first BT
  • Integrating ROS 2 and BehaviorTree.CPP
  • Integrating BTs with ROS 2 actions

To follow this chapter, you should have one of the following setups on your computer:

  • A standard computer running the Ubuntu 24.04 LTS operating system
  • A Linux machine with a ROS 2 Jazzy version installed or with a running Docker container configured, as discussed in Chapter 2

The reference code for this chapter can be found in the Chapter07 folder of the following book code repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter07.

BTs are a modular and hierarchical framework designed to manage complex behaviors. Originally developed in the gaming industry to control the actions of non-player characters (NPCs), BTs have gained popularity in robotics due to their flexibility, reusability, and ability to handle dynamic and unpredictable environments. By providing a structured approach to organizing and executing behaviors, BTs are particularly well-suited for complex robotic systems.

In contrast, FSMs offer another common method for managing robotic behaviors. An FSM models a system’s behavior using a set of states and transitions, with the robot residing in one specific state at any given time and transitioning to another state when certain conditions or events occur. FSMs are straightforward and intuitive, making them ideal for modeling simple and well-defined tasks. However, as tasks become more complex, FSMs become increasingly challenging to manage due to the rapid growth in the number of states and transitions required to address all possible scenarios. This “state explosion problem” makes FSMs less practical for handling intricate or dynamic systems.

To illustrate the complexity of modeling even simple tasks with FSMs, Figure 7.1 depicts a state machine for a pick-and-place task using a mobile robot equipped with an arm. In this example, the robot must move toward an object, grasp it, and deliver it to a designated location. While this task may seem straightforward, various conditions must be considered. For instance, what happens if the robot’s battery depletes before the task is completed? In the FSM shown, only a failure to reach the destination is addressed. Questions arise, such as where to resume the task later or whether the task is truly sequential.

Could it be restructured to include additional actions, such as searching for the object if it is not found? Addressing these scenarios would require adding new conditions and transitions, complicating the implementation and making the source code harder to write, maintain, and read.

Figure 7.1: Example of an FSM for a pick-and-place task

Figure 7.1: Example of an FSM for a pick-and-place task

In the rest of this chapter, we will explore how this task can be formulated more effectively using the BT framework, which simplifies handling such complexities,

unlike traditional FSMs, which can become cumbersome with increasing complexity. Unlike FSMs, which rely on predefined transitions between states, BTs use nodes (selectors, sequences, etc.) to evaluate conditions in real time, enabling a more scalable and adaptable approach to decision-making. BTs provide clearer execution flow and better modularity, making them ideal for complex robotic tasks.

Let’s begin by introducing the basic theoretical concepts of the BT framework. In the following subsection, we will cover the BT key concepts and elements.

BTs are composed of nodes connected with arcs. Their type of execution model resembles directed trees, where nodes are structured in a hierarchical manner, typically referred to as parent and child nodes. At the top is the root node, which uniquely has no parent, serving as the starting point of the execution. From here, the execution process traverses the tree from top to bottom and left to right. The root node initiates the behavior by sending a signal known as a tick to its child nodes, prompting them to execute their designated actions or evaluations. We will introduce the kinds of nodes that can compose the tree. However, let’s start with how the nodes are executed into a tree.

The first concept that we must know about BTs is the tick. In BT, a tick is a fundamental concept that represents a single update cycle or execution step for the tree. The tick is responsible for performing the following operations:

  • Execution trigger: A tick initiates the process of evaluating the BT. Each tick updates the state of the tree and processes the nodes to determine their status and actions.
  • State update: During a tick, the tree’s nodes are assessed based on their current state and the conditions defined within them. The tree transitions through its nodes, updating their states according to the logic specified.
  • Decision-making: As the tick progresses, it evaluates the nodes to make decisions about which actions to take. This involves checking conditions, executing tasks, and managing transitions between nodes based on their behavior.
  • Iteration: The tree is generally ticked repeatedly at a regular interval, allowing it to continually assess and respond to changing conditions in the environment or system. This repetition ensures that the tree remains responsive and adaptive.

The tick frequency of a BT is crucial for system responsiveness. A higher frequency ensures quick updates, which is important for recognizing dangerous or unexpected situations, but it also increases computational load. Balancing responsiveness with efficiency requires matching the tick frequency to the system’s performance capabilities. Testing different frequencies, typically between 10 to 100 Hz, helps find the optimal balance for smooth tasks without overwhelming the system.

Two additional fundamental elements of a BT are the blackboard and the ports:

  • The blackboard is a shared memory that various nodes in the tree can read from or write to. It serves as a global storage space where information is stored for use by the BT’s nodes during execution. The blackboard is used to maintain state, share information across different parts of the tree, and facilitate communication between nodes. It acts as a central repository for storing variables or state information that different parts of the tree might need to access or modify.
  • Ports are interfaces through which nodes in the BT communicate with each other or with the blackboard. They serve as connection points for input and output data, allowing the nodes to pass information or receive data from the blackboard:
    • Input ports: These are used by a node to receive data necessary for its execution
      • Output ports: These are used by a node to send data back to the blackboard or to other nodes

The final core concept in working with BTs is understanding nodes. In a BT, nodes serve as the fundamental building blocks, typically implemented in C++ or Python, and can be combined to create complex behaviors. Each node has a specific function, representing actions, conditions, or control flow, which contribute to the robot’s decision-making process. Understanding the differences among node types is crucial for building complex trees. The following subsection will discuss the various node types.

The types of nodes can be broadly categorized into different types, each serving a particular role within the tree. A typical set of nodes is reported in the following:

  • Root node: This is the starting point of the BT. It does not perform any action itself but serves as the entry point from which the tree is executed. It connects the tree to the agent’s update loop and initiates the evaluation of child nodes.
  • Control flow nodes: These dictate the execution order of their child nodes. They are critical for managing the logic and flow of the tree. The most common control flow nodes are as follows:
    • Sequence: This executes its child nodes in order. It returns success only if all child nodes succeed. If any child fails, the sequence stops and returns failure. It’s used for tasks that require multiple steps to be completed in a specific order.
      • Selector (fallback): A selector node evaluates its child nodes sequentially from left to right, succeeding when one succeeds. If all fail, the selector fails. It’s used to choose the first successful action or behavior in decision-making.
      • Parallel: This runs multiple child nodes simultaneously and waits for them to complete. The result depends on the configuration (e.g., succeed if most children succeed or fail). It’s used when multiple actions need to occur concurrently, such as moving and scanning for enemies at the same time.
  • Decorator nodes: These modify the behavior of a single child node. They can change the outcome of the child or impose conditions on its execution:
    • Inverter: This flips the result of its child node. If the child succeeds, the inverter returns failure, and vice versa. It’s used to create opposite conditions or to negate the result of a condition.
      • ForceSuccess: This forces the result of an action to success, even though the action node returns a failure.
      • Repeat: This continually re-executes its child node a set number of times or indefinitely.
  • Leaf nodes: These are the endpoints of a BT and do not have children. They perform specific actions or check conditions. They represent a specific task or operation that the robot can perform. Typically, leaf nodes have a return type that represents the result of the action implemented into the node. If the action succeeded, it returns SUCCESS, or FAILURE otherwise. If the action is still executing, it returns RUNNING.

Depending on the specific library used to implement the BT, the list of available nodes can vary. In this book, we consider the implementation provided by the BehaviorTree.CPP library, introduced in the next section.

BehaviorTree.CPP is a modular C++ library for creating and running BTs in robotics, originally developed by Davide Faconti at Eurecat Centre Tecnològic of Catalonia. It’s designed for easy customization, allowing users to define custom nodes. As will be discussed in Chapter 8, this library is used in the ROS 2 navigation stack (Nav2) for tasks such as path planning and obstacle avoidance. Its extensibility makes it adaptable to various applications.

The following list outlines key elements of the BehaviorTree.CPP library:

  • Type-safe ports and blackboards: The library uses type-safe ports for data communication between nodes, ensuring that data passed through the tree is consistent and reduces runtime errors. In addition, the library provides a blackboard mechanism, a shared memory space where nodes can store and retrieve information. The blackboard supports type-safe access to stored data, improving the reliability of the tree.
  • Asynchronous execution: Nodes in BehaviorTree.CPP can run asynchronously, which is essential for applications such as robotics, where non-blocking operations are critical. This feature allows for more responsive and concurrent behaviors, such as parallel processing of sensor data while making decisions.
  • Action and condition nodes: The library includes predefined nodes such as action and condition nodes, which are the building blocks of BTs. These nodes can be customized or extended based on specific requirements.
  • Control nodes: BehaviorTree.CPP supports various control nodes such as sequences, selectors, and decorators (such as Inverter and Repeater), allowing complex decision-making processes to be constructed easily.
  • Integration with ROS: BehaviorTree.CPP is designed to integrate seamlessly with ROS 2, making it a popular choice for robotics applications.
  • XML-based tree definition: BTs in BehaviorTree.CPP can be defined using XML, which allows for a clear and structured representation of the tree. This feature also makes it easier to modify and maintain BTs without changing the underlying C++ code.

BehaviorTree.CPP also supports Groot, a graphical interface that makes designing, debugging, and monitoring BTs more accessible. Groot allows users to define trees using a drag-and-drop interface, bridging the gap between coding and visual management. In this chapter, we will use Groot to design nested BT structures and add new nodes later implemented as ROS 2 programs. BehaviorTree.CPP has evolved from version 3.x to 4.x, with version 4 offering a simplified API, improved performance, enhanced integration with Groot, additional built-in node types, streamlined custom node registration, and better support for asynchronous execution. These updates make version 4 more efficient and user-friendly while maintaining some backward compatibility.

Now that we have introduced the basic concepts of the BT framework and the library used to implement BTs that can be integrated with ROS 2, let’s implement our first tree.

The first step to create and execute a BT is to create a ROS 2 package to store all the necessary files to load and run the tree. Even if in this first example we will not use any ROS 2 API, its executor and package structure simplify the developer work.

The first step is to install the library. It can be installed directly from the APT repository:

sudo apt-get install ros-jazzy-behaviortree-cpp

Now, moving into the src directory of the ROS 2 workspace, let’s create the first_bts package:

ros2 pkg create first_bts --dependencies rclcpp std_msgs behaviortree_cpp

Now that the library is installed and the package storing the tree and the source code has been created, let’s see the necessary steps needed to create our first BT.

The first step is to define the model of the tree to execute, and we are going to directly write the .xml file representing the tree model. The goal of this tree is to run in sequence two nodes that have an input port called msg containing a message to print in the terminal. The tree structure is very easy: a root node with one child, and a Sequence node connected with two action nodes. Let’s create a folder called trees in the package and create a file called sequence.xml. The content is reported in the following:

  1. The file starts with the root tag, specifying the version of the library. In this case, version 4 is used:
    <root BTCPP_format="4">
  2. The BehaviorTree tag allows us to specify the nodes of the tree. It accepts as an argument the name of the tree, representing its name:
    <BehaviorTree ID="sequence">
  3. The Sequence node is then included and must contain all the nodes that must be executed:
    <Sequence>
  4. To define a new action node, its name must be defined and can be specified as a tag. In this example, we define two nodes of the same type, HelloNode, called HelloNode1 and HelloNode2. Both nodes have an input port called msg. The value of this port is hardcoded and can be used in the execution of the node:
    <HelloNode1 msg="Hello from Node1"/>
    <HelloNode2 msg="Hello from Node2"/>
    </Sequence>
    </BehaviorTree>
  5. Finally, the tree model terminates by closing the root tag:
    </root>

To execute the tree, we must create a C++ source code that configures, loads, and ticks it. To do this, we must use the following steps:

  1. Include the headers: Along with the typical headers used in ROS 2, we need to add the ones related to the BehaviorTree.CPP library – the behavior_tree.h and bt_factory.h headers:
    #include "rclcpp/rclcpp.hpp"
    #include "std_msgs/msg/string.hpp"
    #include "behaviortree_cpp/bt_factory.h"
    #include "behaviortree_cpp/behavior_tree.h"
  2. Define the BT nodes: For each node defined in the tree, we must create a C++ class representing the body of the action to execute. In this example, we have two nodes of the same type. For this reason, we must just define one class. Note that this class’s name is arbitrary and not associated with the .xml file defining the tree. We will see later the association between the class object and the tree of the node. This node is a StatefulActionNode; this means that the action node can return a state that could be SUCCESS, RUNNING, or FAILURE:
    class HelloNode : public BT::StatefulActionNode {
    public:

The constructor receives two parameters. One is the name of the action, and the other is the node configuration. Using the conf variable, we can access the BT blackboard once initialized, as we will see in the next example. In this example, the constructor is empty:

HelloNode(const std::string & action_name, const BT::NodeConfig & conf) : BT::StatefulActionNode(action_name, conf) {}
  1. Implement the BT methods:
    1. To define a BT node, we must implement some methods. The onStart method is called the first time a node is ticked. Here, we can put initialization stuff that must be executed every time the tree tick returns on this node:
      BT::NodeStatus onStart() {
      1. Using the getInput method of the BehaviorTree.CPP library, we retrieve the value assigned to the input port:
      getInput<std::string>("msg", hello_msg _ );
      1. Finally, to continue the execution of the tree, we return the RUNNING status:
      return BT::NodeStatus::RUNNING;
      1. The next step is to implement the onRunning method. This is the actual body of the action. Here, we just print on the screen the value contained in the port. To proceed with the execution of the other nodes of the sequence, the function returns a SUCCESS value:
      BT::NodeStatus onRunning() {
      std::cout << _hello_msg << std::endl;
      return BT::NodeStatus::SUCCESS;
      void onHalted() { return; }
      1. The providedPorts method is used to configure the ports of a node:
      static BT::PortsList providedPorts() {
      return {

In this example, we have only one port, called msg, which contains a string data type:

BT::InputPort<std::string>("msg")
  1. Define the tree executor:
    1. A ROS 2 node that executes the tree must be defined. As already discussed, to run the tree, we need to tick it. Let’s see the definition of the BTExecutor class:
      class BTExecutor : public rclcpp::Node {
      public:
      1. In the constructor, we call the init_tree() function, which initializes the tree starting from the .xml file and starts a timer. The callback of the timer ticks the tree. The time runs at 2 Hz. This means that the tree is ticked at 2 Hz:
      BTExecutor() : Node("bt_executor") {
      init_btree();
      timer_ = this->create_wall_timer( 0.5s, std::bind(&BTExecutor::tick_function, this));
      1. The init_tree method initializes the tree. To create the tree, we use the BehaviorTreeFactory object, which is used to register node types and create BTs from definitions (e.g., XML files):
      void init_btree() {
      1. For each node of the tree definition (the XML), we must specify the representative class (in our case, HelloNode) and a name. The name must be the same as the one included in the tree definition. In this way, each node of the .xml file has a physical implementation in this C++ source file:
      factory_.registerNodeType<HelloNode>("HelloNode1");
      factory_.registerNodeType<HelloNode>("HelloNode2");
      1. To load the tree, we must point to the .xml file. To avoid absolute paths, we share the file path from a convenient launch file, using the ROS 2 parameter:
      this->declare_parameter<std::string>("tree_xml_file", "");
      std::string tree_file;
      this->get_parameter("tree_xml_file", tree_file);
      1. Finally, after obtaining the .xml file path, we can create the tree starting from it:
      tree _ = factory_.createTreeFromFile(tree_file);
      1. tick_function ticks the tree at the frequency specified in the timer creation:
      void tick_function() {
      tree _.tickOnce();
      }
  2. Define the main function: The main function just creates the ROS 2 node and spins it:
    int main(int argc, char * argv[]) {
    rclcpp::init(argc, argv);
    auto node = std::make_shared<BTExecutor>();
    rclcpp::spin(node);rclcpp::shutdown();
    return 0;
    }

Step 3 – Compiling and installing the necessary files

Section titled “Step 3 – Compiling and installing the necessary files”

To compile and install the executable files and the other necessary resources, such as the XML model tree and the launch files, we must edit the CMakeLists.txt file of the package:

  1. In particular, let’s add the executable files with its dependencies:
    add_executable( sequence_tree src/sequence.cpp )
    ament_target_dependencies(sequence_tree rclcpp std_msgs behaviortree_cpp)
  2. Then, install the executable:
    install(TARGETS sequence_tree RUNTIME DESTINATION lib/${PROJECT_NAME})
  3. Finally, install the directory containing the XML model of the tree and the launch file we are going to create in the next and last step:
    install(DIRECTORY launch trees DESTINATION share/${PROJECT_NAME})

We are now ready to create the launch file to start the tree executor.

Step 4 – Creating a convenient launch file

Section titled “Step 4 – Creating a convenient launch file”

Follow these steps to create a convenient launch file:

  1. Create a launch directory in the first_bts package folder.
  2. In this folder, create a launch file called sequence_tree.launch.py.
  3. In the sequence_tree.launch.py file, the first operation is to retrieve the path of the XML model file defining the tree. We must refer to the share directory of the first_bts package, attaching to it the path to the sequence.xml file:
    tree_path = PathJoinSubstitution ([get_package_share_directory('first_bts'), 'trees', 'sequence.xml'])
  4. Finally, we create the node to launch:
    bt_node = Node(package='first_bts',
    executable='sequence_tree',
    name='sequence_tree',
    output='screen',
  5. As a parameter to the node, we must pass the path assigned to the tree_xml_file parameter:
    parameters=[{'tree_xml_file': tree_path}],)
  6. We can finally compile the workspace, source it, and launch the ROS 2 node using the following commands, after moving into the ROS 2 workspace using the terminal:
    colcon build –symlink-install
    source install/setup.bash
    ros2 launch first_bts sequence_tree.launch.py

As you can see from the terminal, the output will be like the one shown in the following:

[sequence_tree-1] Hello from Node1
[sequence_tree-1] Hello from Node2

This means that the two nodes are executed in sequence as specified by the tree structure. You can see how, by changing the content on the node ports in the XML file, the content of the print message will change.

Now that we have seen the first example of a BT, let’s try to implement something more complicated and integrated with ROS 2 API.

In this second example, we will create a more complex BT, using the blackboard to share a ROS 2 node variable, to use ROS 2 publishers, and the input port of a node to get information about which message to publish. We will create two nodes: a CheckNumber node, which generates a random number and tests whether it is lower than a given value. If it is lower, the node returns SUCCESS, or FAILURE otherwise. This is repeated three times, considering a higher value for the number checking. The generated number is then sent to the PublishResult node, which uses the ROS 2 node object to publish the generated value. To create such a testing structure, we will use the fallback control node while, to create the tree, we will use Groot 2, as discussed in the next section. Apart from the implementation discussed in this chapter, some wrappers for ROS 2 nodes shaped as BT nodes can be found at this link [2]. This wrapper can be used to speed up the implementation of the already wrapped nodes; however, the library is sporadically maintained and might not be suitable for specific use cases.

To use Groot 2, we first must install it in our system. We can do it by downloading Groot from the official web page: https://www.behaviortree.dev/groot/. It is downloaded as a .run file that can be executed to start an installation wizard. Assuming that the downloaded version is 1.6.1, you can install it with the following command:

./Groot2-v1.6.1-linux-installer.run

Notice that the name of the executable in the preceding command could change based on the downloaded version. However, after starting the installation wizard, you can follow the steps to finally install it and select the installation folder. In the selected installation folder, create a directory called Groot2. Assuming that Groot has been installed in the home folder, you can run it with the following command:

~/Groot2/bin/groot2

At this point, the main window of Groot is opened. From here, you can select different options – from opening already developed trees (for example, you can try to visualize the sequence.xml model tree file) to creating a new tree from scratch. Let’s create a new tree model. Click on Create Empty File to open a new blank page where we can drag and drop new nodes. The Groot 2 interface is intuitive and allows you to save the generated tree model with a desired filename and create projects with multiple trees inside.

Now, we can start to add the nodes that will be implemented in the C++ source code after the creation of the tree model. To do this, we must use the Models panel placed at the bottom left of the interface. In this panel, you can select an already present model (such as Fallback or Sequence or similar) or decide to add a new one. To add a new model, click on the + icon to open the Node Model Editor panel, as shown in Figure 7.2.

Figure 7.2: The Models and Node Model Editor panels in Groot 2

Figure 7.2: The Models and Node Model Editor panels in Groot 2

In the Node Model Editor panel, we can select the name of the action to be added and the eventual ports. We need to select two ports for the check_value and generated_number fields: an Input port, which represents the value to check, and an Output port, which shows the eventually generated number. We can also choose to add a default value for the ports. After completing the creation of the node, by clicking on the OK button, it will appear with a different color in the available node models. As you can see from the final shape of the tree (Figure 7.2), you should repeat the creation of this node three times (CheckNumber1, CheckNumber2, and CheckNumber3) to create different nodes working on the same input-output data types. Finally, you can create the last node type of the tree, the PublishResult node, consisting of two input ports: the topic_name port on which the generated number is to be published, and the generated_number port containing the value of the generated number.

Now, you have all the tools to create the tree. The final structure is shown in Figure 7.3.

Figure 7.3: The number_checker.xml tree edited using Groot 2

Figure 7.3: The number_checker.xml tree edited using Groot 2

As you can see, creating complex tree structures is quite easy using Groot. Let’s analyze the defined tree:

  • After the root node, a Sequence node regulates the sequential execution of the two node blocks: the one checking the value of the generated number and the one that publishes the final result.
  • In the left part of the tree branch, we need to test whether the generated number is lower than the one provided in the input port. The concept is that, in sequence, it will be more difficult to pass the first two checks than the last one.
  • In any case, we want to continue the execution of the tree, executing the right branch even if the third CheckNumber3 fails. For this reason, we use a ForceSuccess decorator node. In this way, if CheckNumber3 returns failure, the fallback node receives success.
  • How can we get the generated number to publish it on the ROS 2 topic? We can use the BT blackboard. To do this, the nodes generating the number save the output on a BT port using the label {generated_number}. This value is filled in the C++ source code. The PublishResult node reads this data from the same label. This is how we force data sharing among the nodes of the tree.

You can now save the generated tree as an .xml file. Let’s put it into the trees subfolder of the first_bts package, calling it number_checker.xml. Let’s discuss now how to implement the executor of this tree.

In this section, we will analyze the implementation of the BT nodes. Since the structure is like the one already discussed in the previous example, here, we will just explore the main differences between the two implementations. However, the complete source code can be found in the book’s code repository: https://github.com/PacktPublishing/Mastering-ROS-2/tree/main/Chapter07/first_bts.

First, let’s consider the BTExecutor class. We must declare the BT blackboard as a private member of this class:

BT::Blackboard::Ptr _blackboard;

As you can see, it is represented by a pointer. In the constructor’s body, we must initialize it:

_blackboard = BT::Blackboard::create();

At this point, in the initialization function, we must assign the ROS 2 node variable to a key of the blackboard. In this case, we set the key as node. This key must be used to retrieve the saved variable. To retrieve the node object, we use the shared_from_this function, which is used to obtain a std::shared_ptr that shares ownership of the current object (this):

void init_btree() {
_blackboard->set<rclcpp::Node::SharedPtr>("node", this->shared_from_this());

An additional difference with respect to the first example is that, here, we pass the _blackboard variable in the node creation. In this way, we link the tree with the model with the defined blackboard:

_tree = _factory.createTreeFromFile(tree_file, _blackboard);

In this example, the init_btree function is called directly in the tick function. This is because to obtain the ROS 2 node object (that we save into the blackboard), we must wait for the constructor to terminate its execution. For this reason, we use a flag variable (first) to understand whether this is the first execution of the function (and so, initialize the tree before ticking it):

void tick_function() {
if( first) {
init_btree();
first = false;

We must implement two classes, the NumberChecker and PublishResult classes. In providedPorts of the NumberChecker class, we set an input port (check_value) and an output port (generated_number) with the relative data types:

static BT::PortsList providedPorts() {
return {
BT::InputPort<int>("check_value"),
BT::OutputPort<int>("generated_number")};

The value saved in the input port representing the threshold value is retrieved with the getInput function. Since the code cannot work correctly without a proper parameter, we can check whether it has been correctly set from the specification of the tree. This prevents the situation in which a wrong type is inserted (e.g., a string or a float):

if(!getInput<int>("check_value", num_threshold_)) {
throw BT::RuntimeError("missing required input [goal]");
}

In the onRunning method, we generate a random number between 1 and 100 (random_number). If this number is lower than the control value, we assign a value to the output port and return a SUCCESS state, or FAILURE otherwise. In this latter case, a -1 value is assigned to the output port:

if( random_number < _num_threshold) {
setOutput("generated_number", random_number);
return BT::NodeStatus::SUCCESS;
}
else {
setOutput("generated_number", -1);
return BT::NodeStatus::FAILURE;

Finally, PublishResult must be implemented. As a class member, we declare the object to store the ROS 2 node variable, along with the publisher:

rclcpp::Node::SharedPtr _node;
rclcpp::Publisher<std_msgs::msg::Int32>::SharedPtr _pub;

In its constructor, we use the conf input variable to access the BT blackboard and save the shared content of the node key stored in the blackboard:

PublishResult(const std::string & action_name, const BT::NodeConfig & conf) :
BT::StatefulActionNode(action_name, conf) {
node _ = conf.blackboard->get<rclcpp::Node::SharedPtr>("node");}

In the onStart method, we retrieve the input port value, defining the name of the topic on which to publish the generated value:

BT::NodeStatus onStart() {
std::string topic_name;
getInput<std::string>("topic_name", topic_name);

Then, the publisher is initialized:

pub_ = node_->create_publisher<std_msgs::msg::Int32>(topic_name, 1);

When executing the onRunning method, the generated_number port, which is an input for the PublishResult node, contains the value to publish. So, we can retrieve its value using the getInput function and publish it:

getInput<int>("generated_number", value );
std_msgs::msg::Int32 v;
v.data = value;
pub_->publish( v );

As described in the previous example, the launch file and the CMakeLists.txt file must be edited to launch and compile the executor nodes. An example of the execution of the implemented tree is shown in the following:

[number_checker-1] Generated number: 48 - Threshold: 30 - Failure!
[number_checker-1] Generated number: 58 - Threshold: 50 - Failure!
[number_checker-1] Generated number: 47 - Threshold: 80 - Success!

As you can see from the previous output published on the Linux terminal, the tree nodes are executed in a sort of sequence, since the first two CheckNumber nodes fail in their execution.

We have seen with this example how to create a more complex BT using Groot 2 and ROS 2 API functions. However, in both examples seen so far, the actions programmed in the tree are trivial: just print or perform conditional statements. In the next section of this chapter, we will discuss how to implement BTs to execute more complex tasks.

The execution of a BT should never be blocked. If certain nodes within the tree perform checks during their tick to modify the robot’s actions and react to unexpected situations, the tree’s flow must remain uninterrupted. So, how can we allow complex task execution, such as commanding the robot to reach a given location or perform a manipulation task? The general way to do this is to implement the core functions with long-term executions as a ROS 2 server. The client is implemented in the tree nodes. Based on the result of the ROS 2 action, the node in which the client is implemented can return RUNNING (the action is not completed), SUCCESS (the action returns a successful state), or FAILURE (the action returns a failure state). Let’s discuss this case in the following example.

The steps to implement a similar tree are the same as already seen in the previous examples. The source code discussed here is included in the ROS 2 package called bt_action_node. However, to create this package from scratch, you can use the following command:

ros2 pkg create rclcpp rclcpp_action rosidl_default_generators behaviortree_cpp

In this package, we must implement a dummy server since we must execute the client of the ROS 2 action. In this example, the server has the goal to receive two coordinates (x and y), and a timeout to reach these coordinates from the 0, 0 starting point. The server generates a random velocity used to integrate the position. If, by using the generated velocity, the fake robot reaches the coordinates within the time, it returns success, or failure otherwise. We will not report the code of the server here, since it is quite trivial. However, you can check the full source code in the reach_location_server.cpp file.

The action is implemented in the header contained in the bt_action_server package.

Before contacting the server, the client should wait until the server is available. We can exploit the Sequence node to map this check in the BT formulation. The overall tree is depicted in Figure 7.4. We can use the Sequence decorator node to first check whether the server is running or not (the WaitForServer node) and then call the action (in the CallAction node).

Figure 7.4: BT to implement the ROS 2 action client

Figure 7.4: BT to implement the ROS 2 action client

Let’s discuss the implementation of the two BT nodes. At the start, the needed header files must be included. Along with the BT header files, the .hpp files to implement the ROS 2 client and the message to correctly invoke the server must also be included. In addition, we need to define an alias called Action to simplify the usage of the ReachLocation data type:

#include <bt_action_server/action/reach_location.hpp>
#include <rclcpp_action/rclcpp_action.hpp>
using Action = bt_action_server::action::ReachLocation;

To represent the outcome of the action, we define an enumeration type that includes possible results – success, failure, and cancellation:

enum class ActionResult : uint8_t {
ActionFailed,
ActionCancelled,
ActionSucceded
};

To implement the first behavior node, the WaitForServer behavior, we must define a proper class. Among the different members of this class, let’s declare a ROS 2 client object:

rclcpp_action::Client<Action>::SharedPtr _client;

In the constructor of the WaitForServer class, we must initialize a ROS 2 node object. This can be done by retrieving its value from the BT blackboard:

WaitForServer(const std::string & action_name, const BT::NodeConfig & conf) : BT::StatefulActionNode(action_name, conf) {
node _ = conf.blackboard->get<rclcpp::Node::SharedPtr>("node");

In the onStart method, we instantiate the server. The name of the server is taken as input in the node port. As you can see from Figure 7.4, the name is reach_location:

BT::NodeStatus onStart() {
std::string server_name;
getInput<std::string>("server_name", server_name );
_client = rclcpp_action::create_client<Action>(_node, server_name);

Finally, in the onRunning method, we return FAILURE if the action_server_is_ready() function is false, or SUCCESS otherwise:

BT::NodeStatus onRunning() {
if (!_client->action_server_is_ready())
return BT::NodeStatus::FAILURE;
return BT::NodeStatus::SUCCESS;

The second BT node to implement executes the action call, and it is called CallAction. In the representative class of the behavior, we must create a new ROS object node to handle everything related to the server. So, let’s define the following class attributes – a new ROS 2 node and the client object:

rclcpp::Node::SharedPtr _node2;
rclcpp_action::Client<Action>::SharedPtr _client;

In the constructor the node variable is initialized.

node2_ = rclcpp::Node::make_shared("action_client_node");

At this point, in the onRunning method, we must call the server, if it has not been called yet. For this reason, we consider a Boolean flag, _server_called, which switches to true after the server is called:

if ( !_server_called ) {
_server_called = true;

The goal of the action is filled with the data received from the input ports. The server is called after the goal object is filled:

auto goal = Action::Goal();
goal.x = _x;
goal.y = _y;
goal.timeout = _timeout;
auto send_goal_future = _client->async_send_goal(goal);

We can now spin the ROS 2 node initialized in the constructor to check whether the goal has been correctly sent:

if(rclcpp::spin_until_future_complete(node2_, send_goal_future)!= rclcpp::FutureReturnCode::SUCCESS)
return BT::NodeStatus::FAILURE;

We can now spin the ROS 2 node initialized in the constructor to later check the status of the action.

At each tick of the tree, we must wait for the server to complete its execution using the goal_handle variable. If this variable has a null value, the server has not accepted the goal. For this reason, we return a FAILURE state:

auto goal_handle = send_goal_future.get();
if (!goal_handle)
return BT::NodeStatus::FAILURE;

At the same time, we define a callback function that is invoked when the server completes its execution:

_client->async_get_result(goal_handle, std::bind(&CallAction::result_callback, this, std::placeholders::_1));

As you may know, to allow the callback of a node to receive new data, the spin function must be called. Of course, if we call spin now, we lock the execution of the BT node. For this reason, we will use the spin_some function:

rclcpp::spin_some( _node2 );

In the result_callback function, we check the server’s termination status and update the _action_result variable to indicate whether the server execution was successful or failed. The variable is set to 2 if the action succeeded, and to 1 or 0 if it terminates in an aborted or failed state. The same variable is used in the running function of the CallAction node to return the SUCCESS, FAILURE, or RUNNING status. Since the action_result_ variable has been initialized with -1, until it doesn’t change its value, the BT node running function returns the RUNNING status since it is still waiting for the execution of the action:

if(action_result == ActionResult::ActionSucceded )
return BT::NodeStatus::SUCCESS;
else if( action_result_ == ActionResult::ActionFailed) return BT::NodeStatus::FAILURE;
else if( action_result_ == ActionResult::ActionCancelled)
return BT::NodeStatus::FAILURE;

To run the tree correctly, you must clone the bt_action_server package from the GitHub repository of the book: https://github.com/PacktPublishing/Mastering-ROS-2. Then, after compiling and sourcing the workspace, you must run the following commands:

ros2 run bt_action_server reach_location_server
ros2 launch bt_action_server bt_action.launch.py

As a result, on the terminal, you can see the flow of the nodes. First, the success of the WaitForServer node, then the wait for the action accomplishment, and finally, the success when the server terminates correctly:

[bt_action-1] [Node WaitForServer]: Success
[bt_action-1] [Node CallAction]: Waiting server execution
[bt_action-1] [Node CallAction]: Waiting server execution
[bt_action-1] [Node CallAction]: Success

You can try to change the value associated with the input ports of the node to check how the result of the action changes. This additionally shows how flexible the BT framework is. If the behavior nodes are properly designed, you can use the node ports to adapt the execution of the program to the robot environment, without modifying the source code directly.

In this chapter, we introduced the BT framework, a modern method for implementing robot autonomy. A BT offers a straightforward and efficient way to define and manage the actions and control nodes that guide a robot’s behavior. We covered the fundamental elements of the BT framework and the key concepts behind it.

We also introduced BehaviorTree.CPP, a popular C++ library that seamlessly integrates with ROS 2. BehaviorTree.CPP includes support for Groot, a graphical interface for creating and visualizing BTs. To illustrate the framework, we presented three examples of varying complexity, from defining the tree using XML models to integrating ROS 2 actions for executing long-term tasks.

Additionally, we highlighted how BehaviorTree.CPP is utilized by the ROS 2 navigation stack (nav2), which will be explored further in the next chapter. The upcoming chapter will delve into how to enable robots with navigation capabilities.