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