Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
behavior_tree_navigator.hpp
1 // Copyright (c) 2021-2023 Samsung Research America
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef NAV2_CORE__BEHAVIOR_TREE_NAVIGATOR_HPP_
16 #define NAV2_CORE__BEHAVIOR_TREE_NAVIGATOR_HPP_
17 
18 #include <memory>
19 #include <string>
20 #include <vector>
21 #include <mutex>
22 #include <chrono>
23 
24 #include "nav2_util/odometry_utils.hpp"
25 #include "nav2_ros_common/tf2_factories.hpp"
26 #include "rclcpp/rclcpp.hpp"
27 #include "nav2_ros_common/lifecycle_node.hpp"
28 #include "pluginlib/class_loader.hpp"
29 #include "nav2_behavior_tree/bt_action_server.hpp"
30 #include "nav2_ros_common/node_utils.hpp"
31 
32 namespace nav2_core
33 {
34 class NavigatorMuxer;
35 
41 {
42  std::string robot_frame;
43  std::string global_frame;
44  double transform_tolerance;
45  nav2::TransformBuffer::SharedPtr tf;
46 };
47 
56 {
57 public:
58  NavigatorBase() = default;
59  virtual ~NavigatorBase() = default;
60 
65  virtual bool on_configure(
66  nav2::LifecycleNode::WeakPtr parent_node,
67  const std::vector<std::string> & plugin_lib_names,
68  const FeedbackUtils & feedback_utils,
69  nav2_core::NavigatorMuxer * plugin_muxer,
70  std::shared_ptr<nav2_util::OdomSmoother> odom_smoother) = 0;
71 
76  virtual bool on_activate() = 0;
77 
82  virtual bool on_deactivate() = 0;
83 
88  virtual bool on_cleanup() = 0;
89 
90  virtual void preempt() = 0;
91 };
92 
99 {
100 public:
105  : current_navigator_(nullptr) {}
106 
112  {
113  std::scoped_lock l(mutex_);
114  return current_navigator_ != nullptr;
115  }
116 
122  {
123  std::scoped_lock l(mutex_);
124  if (current_navigator_ != nullptr) {
125  RCLCPP_ERROR(
126  rclcpp::get_logger("NavigatorMutex"),
127  "Major error! Navigation requested while another navigation"
128  " task is in progress! This likely occurred from an incorrect"
129  "implementation of a navigator plugin.");
130  }
131  current_navigator_ = navigator;
132  }
133 
139  {
140  std::scoped_lock l(mutex_);
141  if (current_navigator_ != navigator) {
142  RCLCPP_ERROR(
143  rclcpp::get_logger("NavigatorMutex"),
144  "Major error! Navigation stopped while another navigation"
145  " task is in progress! This likely occurred from an incorrect"
146  "implementation of a navigator plugin.");
147  } else {
148  current_navigator_ = nullptr;
149  }
150  }
151 
152  void preemptCurrentNavigator()
153  {
154  std::scoped_lock l(mutex_);
155  current_navigator_->preempt();
156  }
157 
164  {
165  std::scoped_lock l(mutex_);
166  return current_navigator_ == navigator;
167  }
168 
169 protected:
170  nav2_core::NavigatorBase * current_navigator_{nullptr};
171  std::mutex mutex_;
172 };
173 
180 template<class ActionT>
182 {
183 public:
184  using Ptr = std::shared_ptr<nav2_core::BehaviorTreeNavigator<ActionT>>;
185 
190  : NavigatorBase()
191  {
192  plugin_muxer_ = nullptr;
193  }
194 
198  virtual ~BehaviorTreeNavigator() = default;
199 
211  nav2::LifecycleNode::WeakPtr parent_node,
212  const std::vector<std::string> & plugin_lib_names,
213  const FeedbackUtils & feedback_utils,
214  nav2_core::NavigatorMuxer * plugin_muxer,
215  std::shared_ptr<nav2_util::OdomSmoother> odom_smoother) final
216  {
217  auto node = parent_node.lock();
218  logger_ = node->get_logger();
219  clock_ = node->get_clock();
220  feedback_utils_ = feedback_utils;
221  plugin_muxer_ = plugin_muxer;
222 
223  // get the default behavior tree for this navigator
224  std::string default_bt_xml_filename = getDefaultBTFilepath(parent_node);
225 
226  auto search_directories = node->declare_or_get_parameter(
227  "bt_search_directories",
228  std::vector<std::string>{nav2::get_package_share_directory(
229  "nav2_bt_navigator") + "/behavior_trees"}
230  );
231 
232  allow_navigator_preemption_ = node->declare_or_get_parameter(
233  "allow_navigator_preemption", false);
234 
235  navigator_preemption_timeout_ = std::chrono::milliseconds(
236  node->declare_or_get_parameter("navigator_preemption_timeout", 500));
237 
238  // Create the Behavior Tree Action Server for this navigator
239  bt_action_server_ =
240  std::make_unique<nav2_behavior_tree::BtActionServer<ActionT, nav2::LifecycleNode>>(
241  node,
242  getName(),
243  plugin_lib_names,
244  default_bt_xml_filename,
245  std::bind(&BehaviorTreeNavigator::onGoalReceived, this, std::placeholders::_1),
246  std::bind(&BehaviorTreeNavigator::onLoop, this),
247  std::bind(&BehaviorTreeNavigator::onPreempt, this, std::placeholders::_1),
248  std::bind(
250  std::placeholders::_1, std::placeholders::_2),
251  search_directories);
252 
253  bool ok = true;
254  if (!bt_action_server_->on_configure()) {
255  ok = false;
256  }
257 
258  BT::Blackboard::Ptr blackboard = bt_action_server_->getBlackboard();
259  blackboard->set("tf_buffer", feedback_utils.tf); // NOLINT
260  blackboard->set("initial_pose_received", false); // NOLINT
261  blackboard->set("number_recoveries", 0); // NOLINT
262  blackboard->set("odom_smoother", odom_smoother); // NOLINT
263 
264  return configure(parent_node, odom_smoother) && ok;
265  }
266 
271  bool on_activate() final
272  {
273  bool ok = true;
274 
275  if (!bt_action_server_->on_activate()) {
276  ok = false;
277  }
278 
279  return activate() && ok;
280  }
281 
286  bool on_deactivate() final
287  {
288  bool ok = true;
289  if (!bt_action_server_->on_deactivate()) {
290  ok = false;
291  }
292 
293  return deactivate() && ok;
294  }
295 
300  bool on_cleanup() final
301  {
302  bool ok = true;
303  if (!bt_action_server_->on_cleanup()) {
304  ok = false;
305  }
306 
307  bt_action_server_.reset();
308 
309  return cleanup() && ok;
310  }
311 
312  virtual std::string getDefaultBTFilepath(nav2::LifecycleNode::WeakPtr node) = 0;
313 
318  virtual std::string getName() = 0;
319 
320  void preempt() final
321  {
322  bt_action_server_->preemptCurrentNavigator();
323  }
324 
325 protected:
329  bool onGoalReceived(typename ActionT::Goal::ConstSharedPtr goal)
330  {
331  if (plugin_muxer_->isNavigating() && !plugin_muxer_->isCurrentNavigator(this)) {
332  // A different navigator is processing; check if cross-navigator preemption is allowed
333  if (!allow_navigator_preemption_) {
334  RCLCPP_ERROR(
335  logger_,
336  "Requested navigation from %s while another navigator is processing,"
337  " rejecting request.", getName().c_str());
338  return false;
339  }
340 
341  RCLCPP_INFO(
342  logger_,
343  "Requested navigation from %s while another navigator is processing,"
344  " stopping current navigator.", getName().c_str());
345  plugin_muxer_->preemptCurrentNavigator();
346 
347  const auto start = std::chrono::steady_clock::now();
348  rclcpp::Rate r(100);
349  while (plugin_muxer_->isNavigating()) {
350  if (std::chrono::steady_clock::now() - start > navigator_preemption_timeout_) {
351  RCLCPP_ERROR(
352  logger_,
353  "Timed out waiting for current navigator to stop before accepting"
354  " goal from %s. Rejecting request.", getName().c_str());
355  return false;
356  }
357  r.sleep();
358  }
359  }
360 
361  bool goal_accepted = goalReceived(goal);
362 
363  if (goal_accepted) {
364  plugin_muxer_->startNavigating(this);
365  }
366 
367  return goal_accepted;
368  }
369 
374  typename ActionT::Result::SharedPtr result,
375  nav2_behavior_tree::BtStatus & final_bt_status)
376  {
377  plugin_muxer_->stopNavigating(this);
378  goalCompleted(result, final_bt_status);
379  }
380 
386  virtual bool goalReceived(typename ActionT::Goal::ConstSharedPtr goal) = 0;
387 
392  virtual void onLoop() = 0;
393 
397  virtual void onPreempt(typename ActionT::Goal::ConstSharedPtr goal) = 0;
398 
403  virtual void goalCompleted(
404  typename ActionT::Result::SharedPtr result,
405  nav2_behavior_tree::BtStatus & final_bt_status) = 0;
406 
410  virtual bool configure(
411  nav2::LifecycleNode::WeakPtr /*node*/,
412  std::shared_ptr<nav2_util::OdomSmoother>/*odom_smoother*/)
413  {
414  return true;
415  }
416 
420  virtual bool cleanup() {return true;}
421 
425  virtual bool activate() {return true;}
426 
430  virtual bool deactivate() {return true;}
431 
432  std::unique_ptr<nav2_behavior_tree::BtActionServer<ActionT, nav2::LifecycleNode>>
433  bt_action_server_;
434  rclcpp::Logger logger_{rclcpp::get_logger("Navigator")};
435  rclcpp::Clock::SharedPtr clock_;
436  FeedbackUtils feedback_utils_;
437  NavigatorMuxer * plugin_muxer_;
438 
439  // True if you want to allow navigator preemption
440  bool allow_navigator_preemption_;
441 
442  // Timeout value while waiting for preemption of a navigator by another one
443  std::chrono::milliseconds navigator_preemption_timeout_;
444 };
445 
446 } // namespace nav2_core
447 
448 #endif // NAV2_CORE__BEHAVIOR_TREE_NAVIGATOR_HPP_
Navigator interface that acts as a base class for all BT-based Navigator action's plugins All methods...
virtual void goalCompleted(typename ActionT::Result::SharedPtr result, nav2_behavior_tree::BtStatus &final_bt_status)=0
A callback that is called when a the action is completed; Can fill in action result message or indica...
virtual void onPreempt(typename ActionT::Goal::ConstSharedPtr goal)=0
A callback that is called when a preempt is requested.
void onCompletion(typename ActionT::Result::SharedPtr result, nav2_behavior_tree::BtStatus &final_bt_status)
An intermediate completion function to mux navigators.
BehaviorTreeNavigator()
A Navigator constructor.
virtual ~BehaviorTreeNavigator()=default
Virtual destructor.
virtual std::string getName()=0
Get the action name of this navigator to expose.
bool onGoalReceived(typename ActionT::Goal::ConstSharedPtr goal)
An intermediate goal reception function to mux navigators.
bool on_cleanup() final
Cleanup a navigator.
virtual bool deactivate()
Method to deactivate and any threads involved in execution.
virtual void onLoop()=0
A callback that defines execution that happens on one iteration through the BT Can be used to publish...
virtual bool activate()
Method to activate any threads involved in execution.
bool on_deactivate() final
Deactivation of the navigator's backend BT and actions.
virtual bool cleanup()
Method to cleanup resources.
virtual bool configure(nav2::LifecycleNode::WeakPtr, std::shared_ptr< nav2_util::OdomSmoother >)
virtual bool goalReceived(typename ActionT::Goal::ConstSharedPtr goal)=0
A callback to be called when a new goal is received by the BT action server Can be used to check if g...
bool on_activate() final
Activation of the navigator's backend BT and actions.
bool on_configure(nav2::LifecycleNode::WeakPtr parent_node, const std::vector< std::string > &plugin_lib_names, const FeedbackUtils &feedback_utils, nav2_core::NavigatorMuxer *plugin_muxer, std::shared_ptr< nav2_util::OdomSmoother > odom_smoother) final
Configuration to setup the navigator's backend BT and actions.
Navigator interface to allow navigators to be stored in a vector and accessed via pluginlib due to te...
virtual bool on_cleanup()=0
Cleanup a navigator.
virtual bool on_deactivate()=0
Deactivation of the navigator's backend BT and actions.
virtual bool on_activate()=0
Activation of the navigator's backend BT and actions.
virtual bool on_configure(nav2::LifecycleNode::WeakPtr parent_node, const std::vector< std::string > &plugin_lib_names, const FeedbackUtils &feedback_utils, nav2_core::NavigatorMuxer *plugin_muxer, std::shared_ptr< nav2_util::OdomSmoother > odom_smoother)=0
Configuration of the navigator's backend BT and actions.
A class to control the state of the BT navigator by allowing only a single plugin to be processed at ...
void stopNavigating(nav2_core::NavigatorBase *navigator)
Stop navigating with a given navigator.
void startNavigating(nav2_core::NavigatorBase *navigator)
Start navigating with a given navigator.
bool isNavigating()
Get the navigator muxer state.
NavigatorMuxer()
A Navigator Muxer constructor.
bool isCurrentNavigator(nav2_core::NavigatorBase *navigator)
Check if the given navigator is the currently active navigator.
Navigator feedback utilities required to get transforms and reference frames.