Nav2 Navigation Stack - lyrical  lyrical
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 
158 protected:
159  nav2_core::NavigatorBase * current_navigator_{nullptr};
160  std::mutex mutex_;
161 };
162 
169 template<class ActionT>
171 {
172 public:
173  using Ptr = std::shared_ptr<nav2_core::BehaviorTreeNavigator<ActionT>>;
174 
179  : NavigatorBase()
180  {
181  plugin_muxer_ = nullptr;
182  }
183 
187  virtual ~BehaviorTreeNavigator() = default;
188 
200  nav2::LifecycleNode::WeakPtr parent_node,
201  const std::vector<std::string> & plugin_lib_names,
202  const FeedbackUtils & feedback_utils,
203  nav2_core::NavigatorMuxer * plugin_muxer,
204  std::shared_ptr<nav2_util::OdomSmoother> odom_smoother) final
205  {
206  auto node = parent_node.lock();
207  logger_ = node->get_logger();
208  clock_ = node->get_clock();
209  feedback_utils_ = feedback_utils;
210  plugin_muxer_ = plugin_muxer;
211 
212  // get the default behavior tree for this navigator
213  std::string default_bt_xml_filename = getDefaultBTFilepath(parent_node);
214 
215  auto search_directories = node->declare_or_get_parameter(
216  "bt_search_directories",
217  std::vector<std::string>{nav2::get_package_share_directory(
218  "nav2_bt_navigator") + "/behavior_trees"}
219  );
220 
221  allow_navigator_preemption_ = node->declare_or_get_parameter(
222  "allow_navigator_preemption", false);
223 
224  navigator_preemption_timeout_ = std::chrono::milliseconds(
225  node->declare_or_get_parameter("navigator_preemption_timeout", 500));
226 
227  // Create the Behavior Tree Action Server for this navigator
228  bt_action_server_ =
229  std::make_unique<nav2_behavior_tree::BtActionServer<ActionT, nav2::LifecycleNode>>(
230  node,
231  getName(),
232  plugin_lib_names,
233  default_bt_xml_filename,
234  std::bind(&BehaviorTreeNavigator::onGoalReceived, this, std::placeholders::_1),
235  std::bind(&BehaviorTreeNavigator::onLoop, this),
236  std::bind(&BehaviorTreeNavigator::onPreempt, this, std::placeholders::_1),
237  std::bind(
239  std::placeholders::_1, std::placeholders::_2),
240  search_directories);
241 
242  bool ok = true;
243  if (!bt_action_server_->on_configure()) {
244  ok = false;
245  }
246 
247  BT::Blackboard::Ptr blackboard = bt_action_server_->getBlackboard();
248  blackboard->set("tf_buffer", feedback_utils.tf); // NOLINT
249  blackboard->set("initial_pose_received", false); // NOLINT
250  blackboard->set("number_recoveries", 0); // NOLINT
251  blackboard->set("odom_smoother", odom_smoother); // NOLINT
252 
253  return configure(parent_node, odom_smoother) && ok;
254  }
255 
260  bool on_activate() final
261  {
262  bool ok = true;
263 
264  if (!bt_action_server_->on_activate()) {
265  ok = false;
266  }
267 
268  return activate() && ok;
269  }
270 
275  bool on_deactivate() final
276  {
277  bool ok = true;
278  if (!bt_action_server_->on_deactivate()) {
279  ok = false;
280  }
281 
282  return deactivate() && ok;
283  }
284 
289  bool on_cleanup() final
290  {
291  bool ok = true;
292  if (!bt_action_server_->on_cleanup()) {
293  ok = false;
294  }
295 
296  bt_action_server_.reset();
297 
298  return cleanup() && ok;
299  }
300 
301  virtual std::string getDefaultBTFilepath(nav2::LifecycleNode::WeakPtr node) = 0;
302 
307  virtual std::string getName() = 0;
308 
309  void preempt() final
310  {
311  bt_action_server_->preemptCurrentNavigator();
312  }
313 
314 protected:
318  bool onGoalReceived(typename ActionT::Goal::ConstSharedPtr goal)
319  {
320  if (plugin_muxer_->isNavigating()) {
321  if (!allow_navigator_preemption_) {
322  RCLCPP_ERROR(
323  logger_,
324  "Requested navigation from %s while another navigator is processing,"
325  " rejecting request.", getName().c_str());
326  return false;
327  }
328 
329  RCLCPP_INFO(
330  logger_,
331  "Requested navigation from %s while another navigator is processing,"
332  " stopping current navigator.", getName().c_str());
333  plugin_muxer_->preemptCurrentNavigator();
334 
335  const auto start = std::chrono::steady_clock::now();
336  rclcpp::Rate r(100);
337  while (plugin_muxer_->isNavigating()) {
338  if (std::chrono::steady_clock::now() - start > navigator_preemption_timeout_) {
339  RCLCPP_ERROR(
340  logger_,
341  "Timed out waiting for current navigator to stop before accepting"
342  " goal from %s. Rejecting request.", getName().c_str());
343  return false;
344  }
345  r.sleep();
346  }
347  }
348 
349  bool goal_accepted = goalReceived(goal);
350 
351  if (goal_accepted) {
352  plugin_muxer_->startNavigating(this);
353  }
354 
355  return goal_accepted;
356  }
357 
362  typename ActionT::Result::SharedPtr result,
363  nav2_behavior_tree::BtStatus & final_bt_status)
364  {
365  plugin_muxer_->stopNavigating(this);
366  goalCompleted(result, final_bt_status);
367  }
368 
374  virtual bool goalReceived(typename ActionT::Goal::ConstSharedPtr goal) = 0;
375 
380  virtual void onLoop() = 0;
381 
385  virtual void onPreempt(typename ActionT::Goal::ConstSharedPtr goal) = 0;
386 
391  virtual void goalCompleted(
392  typename ActionT::Result::SharedPtr result,
393  nav2_behavior_tree::BtStatus & final_bt_status) = 0;
394 
398  virtual bool configure(
399  nav2::LifecycleNode::WeakPtr /*node*/,
400  std::shared_ptr<nav2_util::OdomSmoother>/*odom_smoother*/)
401  {
402  return true;
403  }
404 
408  virtual bool cleanup() {return true;}
409 
413  virtual bool activate() {return true;}
414 
418  virtual bool deactivate() {return true;}
419 
420  std::unique_ptr<nav2_behavior_tree::BtActionServer<ActionT, nav2::LifecycleNode>>
421  bt_action_server_;
422  rclcpp::Logger logger_{rclcpp::get_logger("Navigator")};
423  rclcpp::Clock::SharedPtr clock_;
424  FeedbackUtils feedback_utils_;
425  NavigatorMuxer * plugin_muxer_;
426 
427  // True if you want to allow navigator preemption
428  bool allow_navigator_preemption_;
429 
430  // Timeout value while waiting for preemption of a navigator by another one
431  std::chrono::milliseconds navigator_preemption_timeout_;
432 };
433 
434 } // namespace nav2_core
435 
436 #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.
Navigator feedback utilities required to get transforms and reference frames.