Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
drive_on_heading.hpp
1 // Copyright (c) 2018 Intel Corporation
2 // Copyright (c) 2022 Joshua Wallace
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #ifndef NAV2_BEHAVIORS__PLUGINS__DRIVE_ON_HEADING_HPP_
17 #define NAV2_BEHAVIORS__PLUGINS__DRIVE_ON_HEADING_HPP_
18 
19 #include <chrono>
20 #include <memory>
21 #include <string>
22 #include <utility>
23 #include <limits>
24 
25 #include "nav2_behaviors/timed_behavior.hpp"
26 #include "nav2_msgs/action/drive_on_heading.hpp"
27 #include "nav2_msgs/action/back_up.hpp"
28 #include "nav2_ros_common/node_utils.hpp"
29 #include "geometry_msgs/msg/twist_stamped.hpp"
30 
31 namespace nav2_behaviors
32 {
33 
38 template<typename ActionT = nav2_msgs::action::DriveOnHeading>
39 class DriveOnHeading : public TimedBehavior<ActionT>
40 {
41  using CostmapInfoType = nav2_core::CostmapInfoType;
42 
43 public:
48  : TimedBehavior<ActionT>(),
49  feedback_(std::make_shared<typename ActionT::Feedback>()),
50  command_x_(0.0),
51  command_speed_(0.0),
52  command_disable_collision_checks_(false),
53  simulate_ahead_time_(0.0)
54  {
55  }
56 
57  ~DriveOnHeading() = default;
58 
64  ResultStatus onRun(const std::shared_ptr<const typename ActionT::Goal> command) override
65  {
66  std::string error_msg;
67  if (command->target.y != 0.0 || command->target.z != 0.0) {
68  error_msg = "DrivingOnHeading in Y and Z not supported, will only move in X.";
69  RCLCPP_INFO(this->logger_, "%s", error_msg.c_str());
70  return ResultStatus{Status::FAILED, ActionT::Result::INVALID_INPUT, error_msg};
71  }
72 
73  // Ensure that both the speed and direction have the same sign
74  if (!((command->target.x > 0.0) == (command->speed > 0.0)) ) {
75  error_msg = "Speed and command sign did not match";
76  RCLCPP_ERROR(this->logger_, "%s", error_msg.c_str());
77  return ResultStatus{Status::FAILED, ActionT::Result::INVALID_INPUT, error_msg};
78  }
79 
80  command_x_ = command->target.x;
81  command_speed_ = command->speed;
82  command_time_allowance_ = command->time_allowance;
83  command_disable_collision_checks_ = command->disable_collision_checks;
84 
85  end_time_ = this->clock_->now() + command_time_allowance_;
86 
87  if (!this->getCurrentPoseChecked(initial_pose_)) {
88  error_msg = "Initial robot pose is not available.";
89  RCLCPP_ERROR(this->logger_, "%s", error_msg.c_str());
90  return ResultStatus{Status::FAILED, ActionT::Result::TF_ERROR, error_msg};
91  }
92 
93  return ResultStatus{Status::SUCCEEDED, ActionT::Result::NONE, ""};
94  }
95 
101  {
102  rclcpp::Duration time_remaining = end_time_ - this->clock_->now();
103  if (time_remaining.seconds() < 0.0 && command_time_allowance_.seconds() > 0.0) {
104  this->stopRobot();
105  std::string error_msg =
106  "Exceeded time allowance before reaching the DriveOnHeading goal - Exiting DriveOnHeading";
107  RCLCPP_WARN(this->logger_, "%s", error_msg.c_str());
108  return ResultStatus{Status::FAILED, ActionT::Result::TIMEOUT, error_msg};
109  }
110 
111  geometry_msgs::msg::PoseStamped current_pose;
112  if (!this->getCurrentPoseChecked(current_pose)) {
113  this->stopRobot();
114  std::string error_msg = "Current robot pose is not available.";
115  RCLCPP_ERROR(this->logger_, "%s", error_msg.c_str());
116  return ResultStatus{Status::FAILED, ActionT::Result::TF_ERROR, error_msg};
117  }
118 
119  double diff_x = initial_pose_.pose.position.x - current_pose.pose.position.x;
120  double diff_y = initial_pose_.pose.position.y - current_pose.pose.position.y;
121  double distance = hypot(diff_x, diff_y);
122 
123  feedback_->distance_traveled = distance;
124  this->action_server_->publish_feedback(feedback_);
125 
126  if (distance >= std::fabs(command_x_)) {
127  this->stopRobot();
128  return ResultStatus{Status::SUCCEEDED, ActionT::Result::NONE, ""};
129  }
130 
131  auto cmd_vel = std::make_unique<geometry_msgs::msg::TwistStamped>();
132  cmd_vel->header.stamp = this->clock_->now();
133  cmd_vel->header.frame_id = this->robot_base_frame_;
134  cmd_vel->twist.linear.y = 0.0;
135  cmd_vel->twist.angular.z = 0.0;
136 
137  double current_speed = last_vel_ == std::numeric_limits<double>::max() ? 0.0 : last_vel_;
138  bool forward = command_speed_ > 0.0;
139  double min_feasible_speed, max_feasible_speed;
140  if (forward) {
141  min_feasible_speed = current_speed + deceleration_limit_ / this->cycle_frequency_;
142  max_feasible_speed = current_speed + acceleration_limit_ / this->cycle_frequency_;
143  } else {
144  min_feasible_speed = current_speed - acceleration_limit_ / this->cycle_frequency_;
145  max_feasible_speed = current_speed - deceleration_limit_ / this->cycle_frequency_;
146  }
147  cmd_vel->twist.linear.x = std::clamp(command_speed_, min_feasible_speed, max_feasible_speed);
148 
149  // Check if we need to slow down to avoid overshooting
150  auto remaining_distance = std::fabs(command_x_) - distance;
151  double max_vel_to_stop = std::sqrt(-2.0 * deceleration_limit_ * remaining_distance);
152  if (max_vel_to_stop < std::abs(cmd_vel->twist.linear.x)) {
153  cmd_vel->twist.linear.x = forward ? max_vel_to_stop : -max_vel_to_stop;
154  }
155 
156  // Ensure we don't go below minimum speed
157  if (std::fabs(cmd_vel->twist.linear.x) < minimum_speed_) {
158  cmd_vel->twist.linear.x = forward ? minimum_speed_ : -minimum_speed_;
159  }
160 
161  geometry_msgs::msg::Pose pose2d = current_pose.pose;
162 
163  if (!isCollisionFree(distance, cmd_vel->twist, pose2d)) {
164  this->stopRobot();
165  std::string error_msg = "Collision Ahead - Exiting DriveOnHeading";
166  RCLCPP_WARN(this->logger_, "%s", error_msg.c_str());
167  return ResultStatus{Status::FAILED, ActionT::Result::COLLISION_AHEAD, error_msg};
168  }
169 
170  last_vel_ = cmd_vel->twist.linear.x;
171  this->vel_pub_->publish(std::move(cmd_vel));
172 
173  return ResultStatus{Status::RUNNING, ActionT::Result::NONE, ""};
174  }
175 
180  CostmapInfoType getResourceInfo() override {return CostmapInfoType::LOCAL;}
181 
182  void onCleanup() override {last_vel_ = std::numeric_limits<double>::max();}
183 
184  void onActionCompletion(std::shared_ptr<typename ActionT::Result>/*result*/)
185  override
186  {
187  last_vel_ = std::numeric_limits<double>::max();
188  }
189 
190 protected:
199  const double & distance,
200  const geometry_msgs::msg::Twist & cmd_vel,
201  geometry_msgs::msg::Pose & pose)
202  {
203  if (command_disable_collision_checks_) {
204  return true;
205  }
206 
207  // Simulate ahead by simulate_ahead_time_ in this->cycle_frequency_ increments
208  int cycle_count = 0;
209  double sim_position_change;
210  const double diff_dist = abs(command_x_) - distance;
211  const int max_cycle_count = static_cast<int>(this->cycle_frequency_ * simulate_ahead_time_);
212  geometry_msgs::msg::Pose init_pose = pose;
213  double init_theta = tf2::getYaw(init_pose.orientation);
214  bool fetch_data = true;
215 
216  while (cycle_count < max_cycle_count) {
217  sim_position_change = cmd_vel.linear.x * (cycle_count / this->cycle_frequency_);
218  pose.position.x = init_pose.position.x + sim_position_change * cos(init_theta);
219  pose.position.y = init_pose.position.y + sim_position_change * sin(init_theta);
220  cycle_count++;
221 
222  if (diff_dist - abs(sim_position_change) <= 0.) {
223  break;
224  }
225 
226  if (!this->local_collision_checker_->isCollisionFree(pose, fetch_data)) {
227  return false;
228  }
229  fetch_data = false;
230  }
231  return true;
232  }
233 
237  void onConfigure() override
238  {
239  auto node = this->node_.lock();
240  if (!node) {
241  throw std::runtime_error{"Failed to lock node"};
242  }
243 
244  simulate_ahead_time_ = node->declare_or_get_parameter(
245  this->behavior_name_ + ".simulate_ahead_time", 2.0);
246  acceleration_limit_ = node->declare_or_get_parameter(
247  this->behavior_name_ + ".acceleration_limit", 2.5);
248  deceleration_limit_ = node->declare_or_get_parameter(
249  this->behavior_name_ + ".deceleration_limit", -2.5);
250  minimum_speed_ = node->declare_or_get_parameter(
251  this->behavior_name_ + ".minimum_speed", 0.10);
252 
253  if (acceleration_limit_ <= 0.0 || deceleration_limit_ >= 0.0) {
254  RCLCPP_ERROR(
255  this->logger_,
256  "DriveOnHeading: acceleration_limit and deceleration_limit must be "
257  "positive and negative respectively");
258  acceleration_limit_ = std::abs(acceleration_limit_);
259  deceleration_limit_ = -std::abs(deceleration_limit_);
260  }
261  }
262 
263  typename ActionT::Feedback::SharedPtr feedback_;
264 
265  geometry_msgs::msg::PoseStamped initial_pose_;
266  double command_x_;
267  double command_speed_;
268  bool command_disable_collision_checks_;
269  rclcpp::Duration command_time_allowance_{0, 0};
270  rclcpp::Time end_time_;
271  double simulate_ahead_time_;
272  double acceleration_limit_;
273  double deceleration_limit_;
274  double minimum_speed_;
275  double last_vel_ = std::numeric_limits<double>::max();
276 };
277 
278 } // namespace nav2_behaviors
279 
280 #endif // NAV2_BEHAVIORS__PLUGINS__DRIVE_ON_HEADING_HPP_
An action server Behavior for spinning in.
ResultStatus onCycleUpdate() override
Loop function to run behavior.
void onConfigure() override
Configuration of behavior action.
DriveOnHeading()
A constructor for nav2_behaviors::DriveOnHeading.
bool isCollisionFree(const double &distance, const geometry_msgs::msg::Twist &cmd_vel, geometry_msgs::msg::Pose &pose)
Check if pose is collision free.
ResultStatus onRun(const std::shared_ptr< const typename ActionT::Goal > command) override
Initialization to run behavior.
CostmapInfoType getResourceInfo() override
Method to determine the required costmap info.
bool getCurrentPoseChecked(geometry_msgs::msg::PoseStamped &pose)
Get one checked robot pose in the local frame, preserving the TF timestamp.