Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
waypoint_follower.cpp
1 // Copyright (c) 2019 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 #include "nav2_waypoint_follower/waypoint_follower.hpp"
16 
17 #include <fstream>
18 #include <memory>
19 #include <streambuf>
20 #include <string>
21 #include <utility>
22 #include <vector>
23 
24 #include "nav2_ros_common/rate.hpp"
25 
26 namespace nav2_waypoint_follower
27 {
28 
29 using rcl_interfaces::msg::ParameterType;
30 using std::placeholders::_1;
31 
32 WaypointFollower::WaypointFollower(const rclcpp::NodeOptions & options)
33 : nav2::LifecycleNode("waypoint_follower", "", options),
34  waypoint_task_executor_loader_("nav2_core",
35  "nav2_core::WaypointTaskExecutor")
36 {
37  RCLCPP_INFO(get_logger(), "Creating");
38 }
39 
41 {
42 }
43 
44 nav2::CallbackReturn
45 WaypointFollower::on_configure(const rclcpp_lifecycle::State & state)
46 {
47  RCLCPP_INFO(get_logger(), "Configuring");
48 
49  auto node = shared_from_this();
50 
51  param_handler_ = std::make_unique<ParameterHandler>(
52  node, get_logger());
53  params_ = param_handler_->getParams();
54 
55  callback_group_ = create_callback_group(
56  rclcpp::CallbackGroupType::MutuallyExclusive,
57  false);
58  callback_group_executor_.add_callback_group(callback_group_, get_node_base_interface());
59 
60  nav_to_pose_client_ = create_action_client<ClientT>(
61  "navigate_to_pose", callback_group_);
62 
63  xyz_action_server_ = create_action_server<ActionT>(
64  "follow_waypoints", std::bind(
66  this),
67  std::bind(&WaypointFollower::goalReceived<ActionT>, this, std::placeholders::_1),
68  nullptr, std::chrono::milliseconds(
69  500), false);
70 
71  from_ll_to_map_client_ = node->create_client<robot_localization::srv::FromLL>(
72  "/fromLL",
73  true /*creates and spins an internal executor*/);
74 
75  gps_action_server_ = create_action_server<ActionTGPS>(
76  "follow_gps_waypoints",
77  std::bind(
79  this),
80  std::bind(&WaypointFollower::goalReceived<ActionTGPS>, this, std::placeholders::_1),
81  nullptr, std::chrono::milliseconds(
82  500), false);
83 
84  try {
85  waypoint_task_executor_ = waypoint_task_executor_loader_.createUniqueInstance(
86  params_->waypoint_task_executor_type);
87  RCLCPP_INFO(
88  get_logger(), "Created waypoint_task_executor : %s of type %s",
89  params_->waypoint_task_executor_id.c_str(), params_->waypoint_task_executor_type.c_str());
90  waypoint_task_executor_->initialize(node, params_->waypoint_task_executor_id);
91  } catch (const std::exception & e) {
92  RCLCPP_FATAL(
93  get_logger(),
94  "Failed to create waypoint_task_executor. Exception: %s", e.what());
95  on_cleanup(state);
96  }
97 
98  return nav2::CallbackReturn::SUCCESS;
99 }
100 
101 nav2::CallbackReturn
102 WaypointFollower::on_activate(const rclcpp_lifecycle::State & /*state*/)
103 {
104  RCLCPP_INFO(get_logger(), "Activating");
105 
106  xyz_action_server_->activate();
107  gps_action_server_->activate();
108 
109  // create bond connection
110  createBond();
111 
112  return nav2::CallbackReturn::SUCCESS;
113 }
114 
115 nav2::CallbackReturn
116 WaypointFollower::on_deactivate(const rclcpp_lifecycle::State & /*state*/)
117 {
118  RCLCPP_INFO(get_logger(), "Deactivating");
119 
120  xyz_action_server_->deactivate();
121  gps_action_server_->deactivate();
122  // destroy bond connection
123  destroyBond();
124 
125  return nav2::CallbackReturn::SUCCESS;
126 }
127 
128 nav2::CallbackReturn
129 WaypointFollower::on_cleanup(const rclcpp_lifecycle::State & /*state*/)
130 {
131  RCLCPP_INFO(get_logger(), "Cleaning up");
132 
133  xyz_action_server_.reset();
134  nav_to_pose_client_.reset();
135  gps_action_server_.reset();
136  from_ll_to_map_client_.reset();
137 
138  return nav2::CallbackReturn::SUCCESS;
139 }
140 
141 nav2::CallbackReturn
142 WaypointFollower::on_shutdown(const rclcpp_lifecycle::State & /*state*/)
143 {
144  RCLCPP_INFO(get_logger(), "Shutting down");
145  return nav2::CallbackReturn::SUCCESS;
146 }
147 
148 template<typename T>
149 bool WaypointFollower::goalReceived(std::shared_ptr<const typename T::Goal> goal)
150 {
151  if constexpr (std::is_same_v<T, ActionTGPS>) {
152  if (goal->gps_poses.empty()) {
153  RCLCPP_ERROR(
154  get_logger(), "Empty vector of GPS waypoints passed to waypoint following action.");
155  return false;
156  }
157  } else {
158  if (goal->poses.empty()) {
159  RCLCPP_ERROR(
160  get_logger(), "Empty vector of waypoints passed to waypoint following action.");
161  return false;
162  }
163  }
164  return true;
165 }
166 
167 template<typename T>
168 std::vector<geometry_msgs::msg::PoseStamped> WaypointFollower::getLatestGoalPoses(
169  const T & action_server)
170 {
171  std::vector<geometry_msgs::msg::PoseStamped> poses;
172  const auto current_goal = action_server->get_current_goal();
173 
174  if (!current_goal) {
175  RCLCPP_ERROR(get_logger(), "No current action goal found!");
176  return poses;
177  }
178 
179  // compile time static check to decide which block of code to be built
180  if constexpr (std::is_same<T, ActionServer::SharedPtr>::value) {
181  // If normal waypoint following callback was called, we build here
182  poses = current_goal->poses;
183  } else {
184  // If GPS waypoint following callback was called, we build here
186  current_goal->gps_poses);
187  }
188  return poses;
189 }
190 
191 template<typename T, typename V, typename Z>
193  const T & action_server,
194  const V & feedback,
195  const Z & result)
196 {
197  auto goal = action_server->get_current_goal();
198 
199  // handling loops
200  unsigned int current_loop_no = 0;
201  auto no_of_loops = goal->number_of_loops;
202 
203  std::vector<geometry_msgs::msg::PoseStamped> poses;
204  poses = getLatestGoalPoses<T>(action_server);
205 
206  if (!action_server || !action_server->is_server_active()) {
207  RCLCPP_DEBUG(get_logger(), "Action server inactive. Stopping.");
208  return;
209  }
210 
211  RCLCPP_INFO(
212  get_logger(), "Received follow waypoint request with %i waypoints.",
213  static_cast<int>(poses.size()));
214 
215  // Check again, GPS waypoint following the poses may still be empty if conversion failed
216  if (poses.empty()) {
217  result->error_code =
218  nav2_msgs::action::FollowWaypoints::Result::NO_VALID_WAYPOINTS;
219  result->error_msg =
220  "Empty vector of waypoints, probably due to conversion failure.";
221  RCLCPP_ERROR(get_logger(), "%s", result->error_msg.c_str());
222  action_server->terminate_current(result);
223  return;
224  }
225 
226  nav2::Rate r(this, params_->loop_rate);
227 
228  // get the goal index, by default, the first in the list of waypoints given.
229  uint32_t goal_index = goal->goal_index;
230  bool new_goal = true;
231 
232  while (rclcpp::ok()) {
233  // Check if asked to stop processing action
234  if (action_server->is_cancel_requested()) {
235  auto cancel_future = nav_to_pose_client_->async_cancel_all_goals();
236  callback_group_executor_.spin_until_future_complete(cancel_future);
237  // for result callback processing
238  callback_group_executor_.spin_some();
239  action_server->terminate_all();
240  return;
241  }
242 
243  // Check if asked to process another action
244  if (action_server->is_preempt_requested()) {
245  RCLCPP_INFO(get_logger(), "Preempting the goal pose.");
246  goal = action_server->accept_pending_goal();
247  poses = getLatestGoalPoses<T>(action_server);
248  if (poses.empty()) {
249  result->error_code =
250  nav2_msgs::action::FollowWaypoints::Result::NO_VALID_WAYPOINTS;
251  result->error_msg =
252  "Empty vector of Waypoints passed to waypoint following logic. "
253  "Nothing to execute, returning with failure!";
254  RCLCPP_ERROR(get_logger(), "%s", result->error_msg.c_str());
255  action_server->terminate_current(result);
256  return;
257  }
258  goal_index = 0;
259  new_goal = true;
260  }
261 
262  // Check if we need to send a new goal
263  if (new_goal) {
264  new_goal = false;
265  ClientT::Goal client_goal;
266  client_goal.pose = poses[goal_index];
267  client_goal.pose.header.stamp = this->now();
268 
269  auto send_goal_options = nav2::ActionClient<ClientT>::SendGoalOptions();
270  send_goal_options.result_callback = std::bind(
272  std::placeholders::_1);
273  send_goal_options.goal_response_callback = std::bind(
275  this, std::placeholders::_1);
276 
277  future_goal_handle_ =
278  nav_to_pose_client_->async_send_goal(client_goal, send_goal_options);
279  current_goal_status_.status = ActionStatus::PROCESSING;
280  }
281 
282  feedback->current_waypoint = goal_index;
283  action_server->publish_feedback(feedback);
284 
285  if (
286  current_goal_status_.status == ActionStatus::FAILED ||
287  current_goal_status_.status == ActionStatus::UNKNOWN)
288  {
289  nav2_msgs::msg::WaypointStatus missedWaypoint;
290  missedWaypoint.waypoint_status = nav2_msgs::msg::WaypointStatus::FAILED;
291  missedWaypoint.waypoint_index = goal_index;
292  missedWaypoint.waypoint_pose = poses[goal_index];
293  missedWaypoint.error_code = current_goal_status_.error_code;
294  missedWaypoint.error_msg = current_goal_status_.error_msg;
295  result->missed_waypoints.push_back(missedWaypoint);
296 
297  if (params_->stop_on_failure) {
298  result->error_code =
299  nav2_msgs::action::FollowWaypoints::Result::STOP_ON_MISSED_WAYPOINT;
300  result->error_msg =
301  "Failed to process waypoint " + std::to_string(goal_index) +
302  " in waypoint list and stop on failure is enabled."
303  " Terminating action.";
304  RCLCPP_WARN(get_logger(), "%s", result->error_msg.c_str());
305  action_server->terminate_current(result);
306  current_goal_status_.error_code = 0;
307  current_goal_status_.error_msg = "";
308  return;
309  } else {
310  RCLCPP_INFO(
311  get_logger(), "Failed to process waypoint %i,"
312  " moving to next.", goal_index);
313  }
314  } else if (current_goal_status_.status == ActionStatus::SUCCEEDED) {
315  RCLCPP_INFO(
316  get_logger(), "Succeeded processing waypoint %i, processing waypoint task execution",
317  goal_index);
318  bool is_task_executed = waypoint_task_executor_->processAtWaypoint(
319  poses[goal_index], goal_index);
320  RCLCPP_INFO(
321  get_logger(), "Task execution at waypoint %i %s", goal_index,
322  is_task_executed ? "succeeded" : "failed!");
323 
324  if (!is_task_executed) {
325  nav2_msgs::msg::WaypointStatus missedWaypoint;
326  missedWaypoint.waypoint_status = nav2_msgs::msg::WaypointStatus::FAILED;
327  missedWaypoint.waypoint_index = goal_index;
328  missedWaypoint.waypoint_pose = poses[goal_index];
329  missedWaypoint.error_code =
330  nav2_msgs::action::FollowWaypoints::Result::TASK_EXECUTOR_FAILED;
331  missedWaypoint.error_msg = "Task execution failed";
332  result->missed_waypoints.push_back(missedWaypoint);
333  }
334  // if task execution was failed and stop_on_failure_ is on , terminate action
335  if (!is_task_executed && params_->stop_on_failure) {
336  result->error_code =
337  nav2_msgs::action::FollowWaypoints::Result::TASK_EXECUTOR_FAILED;
338  result->error_msg =
339  "Failed to execute task at waypoint " + std::to_string(goal_index) +
340  " stop on failure is enabled. Terminating action.";
341  RCLCPP_WARN(get_logger(), "%s", result->error_msg.c_str());
342  action_server->terminate_current(result);
343  current_goal_status_.error_code = 0;
344  current_goal_status_.error_msg = "";
345  return;
346  } else {
347  RCLCPP_INFO(
348  get_logger(), "Handled task execution on waypoint %i,"
349  " moving to next.", goal_index);
350  }
351  }
352 
353  if (current_goal_status_.status != ActionStatus::PROCESSING) {
354  // Update server state
355  goal_index++;
356  new_goal = true;
357  if (goal_index >= poses.size()) {
358  if (current_loop_no == no_of_loops) {
359  RCLCPP_INFO(
360  get_logger(), "Completed all %zu waypoints requested.",
361  poses.size());
362  action_server->succeeded_current(result);
363  current_goal_status_.error_code = 0;
364  current_goal_status_.error_msg = "";
365  return;
366  }
367  RCLCPP_INFO(
368  get_logger(), "Starting a new loop, current loop count is %i",
369  current_loop_no);
370  goal_index = 0;
371  current_loop_no++;
372  }
373  }
374 
375  callback_group_executor_.spin_some();
376  r.sleep();
377  }
378 }
379 
381 {
382  auto feedback = std::make_shared<ActionT::Feedback>();
383  auto result = std::make_shared<ActionT::Result>();
384 
385  followWaypointsHandler<typename ActionServer::SharedPtr,
386  ActionT::Feedback::SharedPtr,
387  ActionT::Result::SharedPtr>(
388  xyz_action_server_,
389  feedback, result);
390 }
391 
393 {
394  auto feedback = std::make_shared<ActionTGPS::Feedback>();
395  auto result = std::make_shared<ActionTGPS::Result>();
396 
397  followWaypointsHandler<typename ActionServerGPS::SharedPtr,
398  ActionTGPS::Feedback::SharedPtr,
399  ActionTGPS::Result::SharedPtr>(
400  gps_action_server_,
401  feedback, result);
402 }
403 
404 void
406  const rclcpp_action::ClientGoalHandle<ClientT>::WrappedResult & result)
407 {
408  if (result.goal_id != future_goal_handle_.get()->get_goal_id()) {
409  RCLCPP_DEBUG(
410  get_logger(),
411  "Goal IDs do not match for the current goal handle and received result."
412  "Ignoring likely due to receiving result for an old goal.");
413  return;
414  }
415 
416  switch (result.code) {
417  case rclcpp_action::ResultCode::SUCCEEDED:
418  current_goal_status_.status = ActionStatus::SUCCEEDED;
419  return;
420  case rclcpp_action::ResultCode::ABORTED:
421  current_goal_status_.status = ActionStatus::FAILED;
422  current_goal_status_.error_code = result.result->error_code;
423  current_goal_status_.error_msg = result.result->error_msg;
424  return;
425  case rclcpp_action::ResultCode::CANCELED:
426  current_goal_status_.status = ActionStatus::FAILED;
427  return;
428  default:
429  current_goal_status_.status = ActionStatus::UNKNOWN;
430  current_goal_status_.error_code = nav2_msgs::action::FollowWaypoints::Result::UNKNOWN;
431  current_goal_status_.error_msg = "Received an UNKNOWN result code from navigation action!";
432  RCLCPP_ERROR(get_logger(), "%s", current_goal_status_.error_msg.c_str());
433  return;
434  }
435 }
436 
437 void
439  const rclcpp_action::ClientGoalHandle<ClientT>::SharedPtr & goal)
440 {
441  if (!goal) {
442  current_goal_status_.status = ActionStatus::FAILED;
443  current_goal_status_.error_code = nav2_msgs::action::FollowWaypoints::Result::UNKNOWN;
444  current_goal_status_.error_msg =
445  "navigate_to_pose action client failed to send goal to server.";
446  RCLCPP_ERROR(get_logger(), "%s", current_goal_status_.error_msg.c_str());
447  }
448 }
449 
450 std::vector<geometry_msgs::msg::PoseStamped>
452  const std::vector<geographic_msgs::msg::GeoPose> & gps_poses)
453 {
454  RCLCPP_INFO(
455  this->get_logger(), "Converting GPS waypoints to %s Frame..",
456  params_->global_frame_id.c_str());
457 
458  std::vector<geometry_msgs::msg::PoseStamped> poses_in_map_frame_vector;
459  int waypoint_index = 0;
460  for (auto && curr_geopose : gps_poses) {
461  auto request = std::make_shared<robot_localization::srv::FromLL::Request>();
462  auto response = std::make_shared<robot_localization::srv::FromLL::Response>();
463  request->ll_point.latitude = curr_geopose.position.latitude;
464  request->ll_point.longitude = curr_geopose.position.longitude;
465  request->ll_point.altitude = curr_geopose.position.altitude;
466 
467  from_ll_to_map_client_->wait_for_service((std::chrono::seconds(1)));
468  if (!from_ll_to_map_client_->invoke(request, response)) {
469  RCLCPP_ERROR(
470  this->get_logger(),
471  "fromLL service of robot_localization could not convert %i th GPS waypoint to"
472  "%s frame, going to skip this point!"
473  "Make sure you have run navsat_transform_node of robot_localization",
474  waypoint_index, params_->global_frame_id.c_str());
475  if (params_->stop_on_failure) {
476  RCLCPP_ERROR(
477  this->get_logger(),
478  "Conversion of %i th GPS waypoint to"
479  "%s frame failed and stop_on_failure is set to true"
480  "Not going to execute any of waypoints, exiting with failure!",
481  waypoint_index, params_->global_frame_id.c_str());
482  return std::vector<geometry_msgs::msg::PoseStamped>();
483  }
484  continue;
485  } else {
486  geometry_msgs::msg::PoseStamped curr_pose_map_frame;
487  curr_pose_map_frame.header.frame_id = params_->global_frame_id;
488  curr_pose_map_frame.header.stamp = this->now();
489  curr_pose_map_frame.pose.position = response->map_point;
490  curr_pose_map_frame.pose.orientation = curr_geopose.orientation;
491  poses_in_map_frame_vector.push_back(curr_pose_map_frame);
492  }
493  waypoint_index++;
494  }
495  RCLCPP_INFO(
496  this->get_logger(),
497  "Converted all %i GPS waypoint to %s frame",
498  static_cast<int>(poses_in_map_frame_vector.size()), params_->global_frame_id.c_str());
499  return poses_in_map_frame_vector;
500 }
501 
502 } // namespace nav2_waypoint_follower
503 
504 #include "rclcpp_components/register_node_macro.hpp"
505 
506 // Register the component with class_loader.
507 // This acts as a sort of entry point, allowing the component to be discoverable when its library
508 // is being loaded into a running process.
509 RCLCPP_COMPONENTS_REGISTER_NODE(nav2_waypoint_follower::WaypointFollower)
void destroyBond()
Destroy bond connection to lifecycle manager.
nav2::LifecycleNode::SharedPtr shared_from_this()
Get a shared pointer of this.
void createBond()
Create bond connection to lifecycle manager.
A sim-time-aware rate for Nav2 loops.
Definition: rate.hpp:61
ResponseType::SharedPtr invoke(typename RequestType::SharedPtr &request, const std::chrono::nanoseconds timeout=std::chrono::nanoseconds(-1), const std::chrono::nanoseconds wait_for_service_timeout=std::chrono::seconds(10))
Invoke the service and block until completed or timed out.
bool wait_for_service(const std::chrono::nanoseconds timeout=std::chrono::nanoseconds::max())
Block until a service is available or timeout.
An action server that uses behavior tree for navigating a robot to its goal position.
nav2::CallbackReturn on_deactivate(const rclcpp_lifecycle::State &state) override
Deactivates action server.
bool goalReceived(std::shared_ptr< const typename T::Goal > goal)
Goal received callbacks to validate a new goal before acceptance. Rejects goals with empty waypoint l...
nav2::CallbackReturn on_shutdown(const rclcpp_lifecycle::State &state) override
Called when in shutdown state.
void resultCallback(const rclcpp_action::ClientGoalHandle< ClientT >::WrappedResult &result)
Action client result callback.
~WaypointFollower()
A destructor for nav2_waypoint_follower::WaypointFollower class.
WaypointFollower(const rclcpp::NodeOptions &options=rclcpp::NodeOptions())
A constructor for nav2_waypoint_follower::WaypointFollower class.
void goalResponseCallback(const rclcpp_action::ClientGoalHandle< ClientT >::SharedPtr &goal)
Action client goal response callback.
nav2::CallbackReturn on_cleanup(const rclcpp_lifecycle::State &state) override
Resets member variables.
nav2::CallbackReturn on_configure(const rclcpp_lifecycle::State &state) override
Configures member variables.
void followGPSWaypointsCallback()
send robot through each of GPS point , which are converted to map frame first then using a client to ...
std::vector< geometry_msgs::msg::PoseStamped > convertGPSPosesToMapPoses(const std::vector< geographic_msgs::msg::GeoPose > &gps_poses)
given some gps_poses, converts them to map frame using robot_localization's service fromLL....
void followWaypointsHandler(const T &action_server, const V &feedback, const Z &result)
Templated function to perform internal logic behind waypoint following, Both GPS and non GPS waypoint...
void followWaypointsCallback()
Action server callbacks.
std::vector< geometry_msgs::msg::PoseStamped > getLatestGoalPoses(const T &action_server)
get the latest poses on the action server goal. If they are GPS poses, convert them to the global car...
nav2::CallbackReturn on_activate(const rclcpp_lifecycle::State &state) override
Activates action server.