Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
behavior_tree_engine.cpp
1 // Copyright (c) 2018 Intel Corporation
2 // Copyright (c) 2020 Florian Gramss
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include "nav2_behavior_tree/behavior_tree_engine.hpp"
17 
18 #include <memory>
19 #include <string>
20 #include <vector>
21 #include "tinyxml2.h" //NOLINT
22 
23 #include "rclcpp/rclcpp.hpp"
24 #include "behaviortree_cpp/json_export.h"
25 #include "behaviortree_cpp/utils/shared_library.h"
26 #include "nav2_behavior_tree/json_utils.hpp"
27 #include "nav2_behavior_tree/utils/loop_rate.hpp"
28 #include "nav2_ros_common/rate.hpp"
29 
30 namespace nav2_behavior_tree
31 {
32 
34  const std::vector<std::string> & plugin_libraries,
35  const nav2::LifecycleNode::SharedPtr node)
36 {
37  BT::SharedLibrary loader;
38  for (const auto & p : plugin_libraries) {
39  factory_.registerFromPlugin(loader.getOSName(p));
40  }
41 
42  node_ = node;
43 }
44 
45 BtStatus
47  BT::Tree * tree,
48  std::function<void()> onLoop,
49  std::function<bool()> cancelRequested,
50  std::chrono::milliseconds loopTimeout)
51 {
52  auto node = node_.lock();
53  if (!node) {
54  RCLCPP_ERROR(
55  rclcpp::get_logger("BehaviorTreeEngine"),
56  "BehaviorTreeEngine node expired. Exiting with failure.");
57  return BtStatus::FAILED;
58  }
59 
60  auto rate_clock = nav2::selectSteadyOrSimClock(node);
61  nav2_behavior_tree::LoopRate loopRate(loopTimeout, tree, rate_clock);
62  BT::NodeStatus result = BT::NodeStatus::RUNNING;
63 
64  // Loop until something happens with ROS or the node completes
65  try {
66  while (rclcpp::ok() && result == BT::NodeStatus::RUNNING) {
67  if (cancelRequested()) {
68  tree->haltTree();
69  return BtStatus::CANCELED;
70  }
71 
72  result = tree->tickOnce();
73 
74  if (result == BT::NodeStatus::RUNNING || result == BT::NodeStatus::IDLE) {
75  onLoop();
76  }
77 
78  if (!loopRate.sleep()) {
79  RCLCPP_DEBUG_THROTTLE(
80  rclcpp::get_logger("BehaviorTreeEngine"),
81  *rate_clock, 1000,
82  "Behavior Tree tick rate %0.2f was exceeded!",
83  1.0 / (loopRate.period().count() * 1.0e-9));
84  }
85  }
86  } catch (const BT::NodeExecutionError & ex) {
87  RCLCPP_ERROR(
88  rclcpp::get_logger("BehaviorTreeEngine"),
89  "BT Exception at Node: [%s] (Path: %s). Original error: %s. Exiting with failure.",
90  ex.failedNode().registration_name.c_str(),
91  ex.failedNode().node_path.c_str(),
92  ex.originalMessage().c_str());
93  return BtStatus::FAILED;
94  } catch (const std::exception & ex) {
95  RCLCPP_ERROR(
96  rclcpp::get_logger("BehaviorTreeEngine"),
97  "Behavior tree threw exception: %s. Exiting with failure.", ex.what());
98  return BtStatus::FAILED;
99  }
100 
101  return (result == BT::NodeStatus::SUCCESS) ? BtStatus::SUCCEEDED : BtStatus::FAILED;
102 }
103 
104 BT::Tree
106  const std::string & xml_string,
107  BT::Blackboard::Ptr blackboard)
108 {
109  return factory_.createTreeFromText(xml_string, blackboard);
110 }
111 
112 BT::Tree
114  const std::string & file_path,
115  BT::Blackboard::Ptr blackboard)
116 {
117  return factory_.createTreeFromFile(file_path, blackboard);
118 }
119 
120 BTInfo BehaviorTreeEngine::parseTreeInfo(const std::string & filename)
121 {
122  BTInfo info;
123  if (filename.empty()) {
124  RCLCPP_ERROR(rclcpp::get_logger("BehaviorTreeEngine"), "Empty BT file path.");
125  return info;
126  }
127 
128  tinyxml2::XMLDocument doc;
129  if (doc.LoadFile(filename.c_str()) != tinyxml2::XML_SUCCESS) {
130  RCLCPP_ERROR(rclcpp::get_logger("BehaviorTreeEngine"), "Could not parse: %s", filename.c_str());
131  return info;
132  }
133 
134  tinyxml2::XMLElement * root = doc.RootElement();
135  if (!root) {
136  RCLCPP_ERROR(rclcpp::get_logger("BehaviorTreeEngine"), "No root element in: %s",
137  filename.c_str());
138  return info;
139  }
140 
141  // Loop through all BehaviorTree elements to get all IDs
142  for (auto * bt = root->FirstChildElement("BehaviorTree"); bt;
143  bt = bt->NextSiblingElement("BehaviorTree"))
144  {
145  const char * id = bt->Attribute("ID");
146  if (id) {
147  info.behavior_tree_ids.emplace_back(id);
148  }
149  }
150 
151  // First try to get main_tree_to_execute attribute
152  const char * main_attr = root->Attribute("main_tree_to_execute");
153  if (main_attr) {
154  info.main_id = main_attr;
155  }
156 
157  // If main_tree_to_execute attribute is not set, we first check the number of BehaviorTree tags
158  if (info.main_id.empty()) {
159  // If only one BehaviorTree tag is found, we can use that as the main ID
160  // If multiple are found, we throw an error since we don't know
161  // which one to use as the main tree
162  if (info.behavior_tree_ids.size() == 1) {
163  info.main_id = info.behavior_tree_ids[0];
164  } else if (info.behavior_tree_ids.size() > 1) {
165  throw std::runtime_error(
166  "Multiple BehaviorTree elements found in " + filename +
167  " but no main_tree_to_execute attribute specified. Unable to determine main tree.");
168  }
169  }
170 
171  return info;
172 }
173 
174 BT::Tree
176  const std::string & tree_id,
177  BT::Blackboard::Ptr blackboard)
178 {
179  return factory_.createTree(tree_id, blackboard);
180 }
181 
184  const std::string & file_path)
185 {
186  factory_.registerBehaviorTreeFromFile(file_path);
187 }
188 
189 void
191  BT::Tree * tree,
192  uint16_t server_port)
193 {
194  // This logger publish status changes using Groot2
195  groot_monitor_ = std::make_unique<BT::Groot2Publisher>(*tree, server_port);
196 
197  // Register common types JSON definitions
198  BT::RegisterJsonDefinition<builtin_interfaces::msg::Time>();
199  BT::RegisterJsonDefinition<std_msgs::msg::Header>();
200 }
201 
202 void
204 {
205  if (groot_monitor_) {
206  groot_monitor_.reset();
207  }
208 }
209 
210 // In order to re-run a Behavior Tree, we must be able to reset all nodes to the initial state
211 void
213 {
214  // this halt signal should propagate through the entire tree.
215  tree.haltTree();
216 }
217 
218 } // namespace nav2_behavior_tree
BT::Tree createTree(const std::string &tree_id, BT::Blackboard::Ptr blackboard)
Function to create a BT from a BehaviorTree ID.
BehaviorTreeEngine(const std::vector< std::string > &plugin_libraries, nav2::LifecycleNode::SharedPtr node)
A constructor for nav2_behavior_tree::BehaviorTreeEngine.
void addGrootMonitoring(BT::Tree *tree, uint16_t server_port)
Add Groot2 monitor to publish BT status changes.
BT::Tree createTreeFromFile(const std::string &file_path, BT::Blackboard::Ptr blackboard)
Function to create a BT from an XML file.
void registerTreeFromFile(const std::string &file_path)
Function to register a BT from an XML file.
BT::Tree createTreeFromText(const std::string &xml_string, BT::Blackboard::Ptr blackboard)
Function to create a BT from a XML string.
void haltAllActions(BT::Tree &tree)
Function to explicitly reset all BT nodes to initial state.
BtStatus run(BT::Tree *tree, std::function< void()> onLoop, std::function< bool()> cancelRequested, std::chrono::milliseconds loopTimeout=std::chrono::milliseconds(10))
Function to execute a BT at a specific rate.
BTInfo parseTreeInfo(const std::string &filename)
Function to parse Behavior Tree information from an XML file.
A struct to hold Behavior Tree ID information.