Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
navigate_to_pose.cpp
1 // Copyright (c) 2021 Samsung Research
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 #include <vector>
16 #include <string>
17 #include <memory>
18 #include <limits>
19 #include "nav2_bt_navigator/navigators/navigate_to_pose.hpp"
20 #include "nav2_util/path_utils.hpp"
21 #include "nav2_msgs/msg/tracking_feedback.hpp"
22 #include "nav2_ros_common/node_utils.hpp"
23 
24 namespace nav2_bt_navigator
25 {
26 
27 bool
29  nav2::LifecycleNode::WeakPtr parent_node,
30  std::shared_ptr<nav2_util::OdomSmoother> odom_smoother)
31 {
32  start_time_ = rclcpp::Time(0);
33  auto node = parent_node.lock();
34 
35  goal_blackboard_id_ = node->declare_or_get_parameter(
36  getName() + ".goal_blackboard_id",
37  std::string("goal"));
38  path_blackboard_id_ = node->declare_or_get_parameter(
39  getName() + ".path_blackboard_id",
40  std::string("path"));
41  tracking_feedback_blackboard_id_ = node->declare_or_get_parameter(
42  getName() + ".tracking_feedback_blackboard_id",
43  std::string("tracking_feedback"));
44 
45  search_window_ = node->declare_or_get_parameter(getName() + "search_window", 2.0);
46 
47  // Odometry smoother object for getting current speed
48  odom_smoother_ = odom_smoother;
49 
50  self_client_ = node->create_action_client<ActionT>(getName());
51 
52  goal_sub_ = node->create_subscription<geometry_msgs::msg::PoseStamped>(
53  "goal_pose",
54  std::bind(&NavigateToPoseNavigator::onGoalPoseReceived, this, std::placeholders::_1));
55 
56  bool enable_groot_monitoring =
57  node->declare_or_get_parameter(getName() + ".enable_groot_monitoring", false);
58  int groot_server_port =
59  node->declare_or_get_parameter(getName() + ".groot_server_port", 1669);
60 
61  bt_action_server_->setGrootMonitoring(
62  enable_groot_monitoring,
63  groot_server_port);
64 
65  return true;
66 }
67 
68 std::string
70  nav2::LifecycleNode::WeakPtr parent_node)
71 {
72  auto node = parent_node.lock();
73  std::string pkg_share_dir =
74  nav2::get_package_share_directory("nav2_bt_navigator");
75 
76  auto default_bt_xml_filename = node->declare_or_get_parameter(
77  "default_nav_to_pose_bt_xml",
78  pkg_share_dir +
79  "/behavior_trees/navigate_to_pose_w_replanning_and_recovery.xml");
80 
81  return default_bt_xml_filename;
82 }
83 
84 bool
86 {
87  goal_sub_.reset();
88  self_client_.reset();
89  return true;
90 }
91 
92 bool
93 NavigateToPoseNavigator::goalReceived(ActionT::Goal::ConstSharedPtr goal)
94 {
95  return initializeGoalPose(goal);
96 }
97 
98 void
100  typename ActionT::Result::SharedPtr result,
101  nav2_behavior_tree::BtStatus & /*final_bt_status*/)
102 {
103  if (result->error_code == 0) {
104  if (bt_action_server_->populateInternalError(result)) {
105  RCLCPP_WARN(
106  logger_,
107  "NavigateToPoseNavigator::goalCompleted, internal error %d:%s.",
108  result->error_code,
109  result->error_msg.c_str());
110  }
111  } else {
112  RCLCPP_WARN(
113  logger_, "NavigateToPoseNavigator::goalCompleted error %d:%s.",
114  result->error_code,
115  result->error_msg.c_str());
116  }
117 }
118 
119 void
121 {
122  // action server feedback (pose, duration of task,
123  // number of recoveries, and distance remaining to goal)
124  auto feedback_msg = std::make_shared<ActionT::Feedback>();
125 
126  geometry_msgs::msg::PoseStamped current_pose;
127  if (!nav2_util::getCurrentPose(
128  current_pose, *feedback_utils_.tf,
129  feedback_utils_.global_frame, feedback_utils_.robot_frame,
130  feedback_utils_.transform_tolerance))
131  {
132  RCLCPP_ERROR(logger_, "Robot pose is not available.");
133  return;
134  }
135 
136  auto blackboard = bt_action_server_->getBlackboard();
137 
138  // Get current path points
139  nav_msgs::msg::Path current_path;
140  auto res = blackboard->get(path_blackboard_id_, current_path);
141  if (res && current_path.poses.size() > 0u) {
142  // Reset start index if path or goal is updated
143  if (nav2_util::isPathUpdated(current_path, previous_path_) ||
144  nav2_util::isGoalUpdated(current_path, previous_path_) ||
145  previous_path_.poses.size() == 0u)
146  {
147  start_index_ = 0;
148  previous_path_ = current_path;
149  }
150  // Find the closest pose to current pose on global path
151  const auto path_search_result = nav2_util::distance_from_path(
152  current_path, current_pose.pose, start_index_, search_window_);
153 
154  // Calculate distance on the path
155  start_index_ = path_search_result.closest_segment_index;
156  double distance_remaining =
157  nav2_util::geometry_utils::calculate_path_length(current_path, start_index_);
158 
159  // Default value for time remaining
160  rclcpp::Duration estimated_time_remaining = rclcpp::Duration::from_seconds(0.0);
161 
162  // Get current speed
163  geometry_msgs::msg::Twist current_odom = odom_smoother_->getTwist();
164  double current_linear_speed = std::hypot(current_odom.linear.x, current_odom.linear.y);
165 
166  // Calculate estimated time taken to goal if speed is higher than 1cm/s
167  // and at least 10cm to go
168  if ((std::abs(current_linear_speed) > 0.01) && (distance_remaining > 0.1)) {
169  estimated_time_remaining =
170  rclcpp::Duration::from_seconds(distance_remaining / std::abs(current_linear_speed));
171  }
172 
173  feedback_msg->distance_remaining = distance_remaining;
174  feedback_msg->estimated_time_remaining = estimated_time_remaining;
175  }
176 
177  int recovery_count = 0;
178  res = blackboard->get("number_recoveries", recovery_count);
179  feedback_msg->number_of_recoveries = recovery_count;
180  feedback_msg->current_pose = current_pose;
181  feedback_msg->navigation_time = clock_->now() - start_time_;
182  nav2_msgs::msg::TrackingFeedback tracking_feedback;
183  res = blackboard->get(
184  tracking_feedback_blackboard_id_,
185  tracking_feedback);
186  feedback_msg->position_tracking_error = tracking_feedback.position_tracking_error;
187  feedback_msg->heading_tracking_error = tracking_feedback.heading_tracking_error;
188 
189  bt_action_server_->publishFeedback(feedback_msg);
190 }
191 
192 void
193 NavigateToPoseNavigator::onPreempt(ActionT::Goal::ConstSharedPtr goal)
194 {
195  RCLCPP_INFO(logger_, "Received goal preemption request");
196 
197  if (goal->behavior_tree == bt_action_server_->getCurrentBTFilenameOrID() ||
198  (goal->behavior_tree.empty() &&
199  bt_action_server_->getCurrentBTFilenameOrID() == bt_action_server_->getDefaultBTFilenameOrID()))
200  {
201  // if pending goal requests the same BT as the current goal, accept the pending goal
202  // if pending goal has an empty behavior_tree field, it requests the default BT file
203  // accept the pending goal if the current goal is running the default BT file
204  if (!initializeGoalPose(bt_action_server_->acceptPendingGoal())) {
205  RCLCPP_WARN(
206  logger_,
207  "Preemption request was rejected since the goal pose could not be "
208  "transformed. For now, continuing to track the last goal until completion.");
209  bt_action_server_->terminatePendingGoal();
210  }
211  } else {
212  RCLCPP_WARN(
213  logger_,
214  "Preemption request was rejected since the requested BT XML file is not the same "
215  "as the one that the current goal is executing. Preemption with a new BT is invalid "
216  "since it would require cancellation of the previous goal instead of true preemption."
217  "\nCancel the current goal and send a new action request if you want to use a "
218  "different BT XML file. For now, continuing to track the last goal until completion.");
219  bt_action_server_->terminatePendingGoal();
220  }
221 }
222 
223 bool
224 NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
225 {
226  geometry_msgs::msg::PoseStamped current_pose;
227  if (!nav2_util::getCurrentPose(
228  current_pose, *feedback_utils_.tf,
229  feedback_utils_.global_frame, feedback_utils_.robot_frame,
230  feedback_utils_.transform_tolerance))
231  {
232  bt_action_server_->setInternalError(
233  ActionT::Result::TF_ERROR,
234  "Initial robot pose is not available.");
235  return false;
236  }
237 
238  geometry_msgs::msg::PoseStamped goal_pose;
239  if (!nav2_util::transformPoseInTargetFrame(
240  goal->pose, goal_pose, *feedback_utils_.tf, feedback_utils_.global_frame,
241  feedback_utils_.transform_tolerance))
242  {
243  bt_action_server_->setInternalError(
244  ActionT::Result::TF_ERROR,
245  "Failed to transform a goal pose provided with frame_id '" +
246  goal->pose.header.frame_id +
247  "' to the global frame '" +
248  feedback_utils_.global_frame +
249  "'.");
250  return false;
251  }
252 
253  RCLCPP_INFO(
254  logger_, "Begin navigating from current location (%.2f, %.2f) to (%.2f, %.2f)",
255  current_pose.pose.position.x, current_pose.pose.position.y,
256  goal_pose.pose.position.x, goal_pose.pose.position.y);
257 
258  // Reset state for new action feedback
259  start_time_ = clock_->now();
260  auto blackboard = bt_action_server_->getBlackboard();
261  blackboard->set("number_recoveries", 0); // NOLINT
262  previous_path_ = nav_msgs::msg::Path();
263 
264  // Update the goal pose and path on the blackboard
265  blackboard->set(goal_blackboard_id_, goal_pose);
266  blackboard->set(path_blackboard_id_, nav_msgs::msg::Path());
267 
268  return true;
269 }
270 
271 void
273  const geometry_msgs::msg::PoseStamped::ConstSharedPtr & pose)
274 {
275  ActionT::Goal goal;
276  goal.pose = *pose;
277  self_client_->async_send_goal(goal);
278 }
279 
280 } // namespace nav2_bt_navigator
281 
282 #include "pluginlib/class_list_macros.hpp"
283 PLUGINLIB_EXPORT_CLASS(
A navigator for navigating to a specified pose.
void onPreempt(ActionT::Goal::ConstSharedPtr goal) override
A callback that is called when a preempt is requested.
void goalCompleted(typename ActionT::Result::SharedPtr result, nav2_behavior_tree::BtStatus &final_bt_status) override
A callback that is called when a the action is completed, can fill in action result message or indica...
bool goalReceived(ActionT::Goal::ConstSharedPtr goal) override
A callback to be called when a new goal is received by the BT action server Can be used to check if g...
bool initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
Goal pose initialization on the blackboard.
bool configure(nav2::LifecycleNode::WeakPtr node, std::shared_ptr< nav2_util::OdomSmoother > odom_smoother) override
A configure state transition to configure navigator's state.
std::string getName() override
Get action name for this navigator.
std::string getDefaultBTFilepath(nav2::LifecycleNode::WeakPtr node) override
Get navigator's default BT.
void onGoalPoseReceived(const geometry_msgs::msg::PoseStamped::ConstSharedPtr &pose)
A subscription and callback to handle the topic-based goal published from rviz.
void onLoop() override
A callback that defines execution that happens on one iteration through the BT Can be used to publish...
bool cleanup() override
A cleanup state transition to remove memory allocated.
Navigator interface to allow navigators to be stored in a vector and accessed via pluginlib due to te...