Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
timed_behavior.hpp
1 // Copyright (c) 2018 Intel Corporation
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_BEHAVIORS__TIMED_BEHAVIOR_HPP_
16 #define NAV2_BEHAVIORS__TIMED_BEHAVIOR_HPP_
17 
18 
19 #include <cstdint>
20 #include <memory>
21 #include <string>
22 #include <cmath>
23 #include <chrono>
24 #include <ctime>
25 #include <thread>
26 #include <utility>
27 
28 #include "rclcpp/clock.hpp"
29 #include "rclcpp/duration.hpp"
30 #include "rclcpp/logger.hpp"
31 #include "rclcpp/logging.hpp"
32 #include "rclcpp/utilities.hpp"
33 #include "nav2_ros_common/tf2_factories.hpp"
34 #include "geometry_msgs/msg/pose_stamped.hpp"
35 #include "geometry_msgs/msg/twist.hpp"
36 #include "nav2_util/robot_utils.hpp"
37 #include "nav2_util/twist_publisher.hpp"
38 #include "nav2_ros_common/simple_action_server.hpp"
39 #include "nav2_ros_common/rate.hpp"
40 #include "nav2_core/behavior.hpp"
41 #include "tf2/utils.hpp"
42 
43 
44 namespace nav2_behaviors
45 {
46 
47 enum class Status : int8_t
48 {
49  SUCCEEDED = 1,
50  FAILED = 2,
51  RUNNING = 3,
52 };
53 
55 {
56  Status status;
57  uint16_t error_code{0};
58  std::string error_msg;
59 };
60 
61 using namespace std::chrono_literals; //NOLINT
62 
67 template<typename ActionT>
69 {
70 public:
72 
77  : action_server_(nullptr),
78  cycle_frequency_(10.0),
79  enabled_(false)
80  {
81  }
82 
83  virtual ~TimedBehavior() = default;
84 
85  // Derived classes can override this method to catch the command and perform some checks
86  // before getting into the main loop. The method will only be called
87  // once and should return SUCCEEDED otherwise behavior will return FAILED.
88  virtual ResultStatus onRun(const std::shared_ptr<const typename ActionT::Goal> command) = 0;
89 
90 
91  // This is the method derived classes should mainly implement
92  // and will be called cyclically while it returns RUNNING.
93  // Implement the behavior such that it runs some unit of work on each call
94  // and provides a status. The Behavior will finish once SUCCEEDED is returned
95  // It's up to the derived class to define the final commanded velocity.
96  virtual ResultStatus onCycleUpdate() = 0;
97 
98  // an opportunity for derived classes to do something on configuration
99  // if they chose
100  virtual void onConfigure()
101  {
102  }
103 
104  // an opportunity for derived classes to do something on cleanup
105  // if they chose
106  virtual void onCleanup()
107  {
108  }
109 
110  // an opportunity for a derived class to do something on action completion
111  virtual void onActionCompletion(std::shared_ptr<typename ActionT::Result>/*result*/)
112  {
113  }
114 
115  // configure the server on lifecycle setup
116  void configure(
117  const nav2::LifecycleNode::WeakPtr & parent,
118  const std::string & name, nav2::TransformBuffer::SharedPtr tf,
119  std::shared_ptr<nav2_costmap_2d::CostmapTopicCollisionChecker> local_collision_checker,
120  std::shared_ptr<nav2_costmap_2d::CostmapTopicCollisionChecker> global_collision_checker)
121  override
122  {
123  node_ = parent;
124  auto node = node_.lock();
125  logger_ = node->get_logger();
126  clock_ = node->get_clock();
127 
128  RCLCPP_INFO(logger_, "Configuring %s", name.c_str());
129 
130  behavior_name_ = name;
131  tf_ = tf;
132 
133  node->get_parameter("cycle_frequency", cycle_frequency_);
134  node->get_parameter("local_frame", local_frame_);
135  node->get_parameter("global_frame", global_frame_);
136  node->get_parameter("robot_base_frame", robot_base_frame_);
137  transform_staleness_threshold_ = node->declare_or_get_parameter(
138  "transform_staleness_threshold", 0.0);
139 
140  action_server_ = node->create_action_server<ActionT>(
141  behavior_name_,
142  std::bind(&TimedBehavior::execute, this), nullptr, nullptr, std::chrono::milliseconds(
143  500), false);
144 
145  local_collision_checker_ = local_collision_checker;
146  global_collision_checker_ = global_collision_checker;
147 
148  vel_pub_ = std::make_unique<nav2_util::TwistPublisher>(node, "cmd_vel");
149 
150  onConfigure();
151  }
152 
153  // Cleanup server on lifecycle transition
154  void cleanup() override
155  {
156  action_server_.reset();
157  vel_pub_.reset();
158  onCleanup();
159  }
160 
161  // Activate server on lifecycle transition
162  void activate() override
163  {
164  RCLCPP_INFO(logger_, "Activating %s", behavior_name_.c_str());
165 
166  vel_pub_->on_activate();
167  action_server_->activate();
168  enabled_ = true;
169  }
170 
171  // Deactivate server on lifecycle transition
172  void deactivate() override
173  {
174  vel_pub_->on_deactivate();
175  action_server_->deactivate();
176  enabled_ = false;
177  }
178 
179 protected:
185  bool getCurrentPoseChecked(geometry_msgs::msg::PoseStamped & pose)
186  {
187  if (!nav2_util::getFreshPose(
188  *tf_, local_frame_, robot_base_frame_, clock_->now(),
189  transform_staleness_threshold_, pose))
190  {
191  return false;
192  }
193  return true;
194  }
195 
196  nav2::LifecycleNode::WeakPtr node_;
197 
198  std::string behavior_name_;
199  std::unique_ptr<nav2_util::TwistPublisher> vel_pub_;
200  typename ActionServer::SharedPtr action_server_;
201  std::shared_ptr<nav2_costmap_2d::CostmapTopicCollisionChecker> local_collision_checker_;
202  std::shared_ptr<nav2_costmap_2d::CostmapTopicCollisionChecker> global_collision_checker_;
203  nav2::TransformBuffer::SharedPtr tf_;
204 
205  double cycle_frequency_;
206  double enabled_;
207  std::string local_frame_;
208  std::string global_frame_;
209  std::string robot_base_frame_;
210  double transform_staleness_threshold_{0.0};
211  rclcpp::Duration elapsed_time_{0, 0};
212 
213  // Clock
214  rclcpp::Clock::SharedPtr clock_;
215 
216  // Logger
217  rclcpp::Logger logger_{rclcpp::get_logger("nav2_behaviors")};
218 
219  // Main execution callbacks for the action server implementation calling the Behavior's
220  // onRun and cycle functions to execute a specific behavior
221  void execute()
222  {
223  RCLCPP_INFO(logger_, "Running %s", behavior_name_.c_str());
224 
225  if (!enabled_) {
226  RCLCPP_WARN(
227  logger_,
228  "Called while inactive, ignoring request.");
229  return;
230  }
231 
232  // Initialize the ActionT result
233  auto result = std::make_shared<typename ActionT::Result>();
234 
235  ResultStatus on_run_result = onRun(action_server_->get_current_goal());
236  if (on_run_result.status != Status::SUCCEEDED) {
237  result->error_code = on_run_result.error_code;
238  result->error_msg = on_run_result.error_msg;
239  RCLCPP_INFO(
240  logger_, "Initial checks failed for %s - %s", behavior_name_.c_str(),
241  on_run_result.error_msg.c_str());
242  action_server_->terminate_current(result);
243  return;
244  }
245 
246  auto start_time = clock_->now();
247  auto node = node_.lock();
248  if (!node) {
249  RCLCPP_ERROR(
250  logger_,
251  "Failed to run %s because the parent node is no longer available.",
252  behavior_name_.c_str());
253  result->error_msg = behavior_name_ + " failed: parent node expired";
254  result->total_elapsed_time = clock_->now() - start_time;
255  onActionCompletion(result);
256  action_server_->terminate_current(result);
257  return;
258  }
259  nav2::Rate loop_rate(node, cycle_frequency_);
260 
261  while (rclcpp::ok()) {
262  elapsed_time_ = clock_->now() - start_time;
263  // TODO(orduno) #868 Enable preempting a Behavior on-the-fly without stopping
264  if (action_server_->is_preempt_requested()) {
265  RCLCPP_ERROR(
266  logger_, "Received a preemption request for %s,"
267  " however feature is currently not implemented. Aborting and stopping.",
268  behavior_name_.c_str());
269  stopRobot();
270  result->total_elapsed_time = clock_->now() - start_time;
271  onActionCompletion(result);
272  action_server_->terminate_current(result);
273  return;
274  }
275 
276  if (action_server_->is_cancel_requested()) {
277  RCLCPP_INFO(logger_, "Canceling %s", behavior_name_.c_str());
278  stopRobot();
279  result->total_elapsed_time = elapsed_time_;
280  onActionCompletion(result);
281  action_server_->terminate_all(result);
282  return;
283  }
284 
285  ResultStatus on_cycle_update_result = onCycleUpdate();
286  switch (on_cycle_update_result.status) {
287  case Status::SUCCEEDED:
288  RCLCPP_INFO(
289  logger_,
290  "%s completed successfully", behavior_name_.c_str());
291  result->total_elapsed_time = clock_->now() - start_time;
292  onActionCompletion(result);
293  action_server_->succeeded_current(result);
294  return;
295 
296  case Status::FAILED:
297  stopRobot();
298  result->error_code = on_cycle_update_result.error_code;
299  result->error_msg = behavior_name_ + " failed:" + on_cycle_update_result.error_msg;
300  RCLCPP_WARN(logger_, "%s", result->error_msg.c_str());
301  result->total_elapsed_time = clock_->now() - start_time;
302  onActionCompletion(result);
303  action_server_->terminate_current(result);
304  return;
305 
306  case Status::RUNNING:
307 
308  default:
309  loop_rate.sleep();
310  break;
311  }
312  }
313  }
314 
315  // Stop the robot with a commanded velocity
316  void stopRobot()
317  {
318  auto cmd_vel = std::make_unique<geometry_msgs::msg::TwistStamped>();
319  cmd_vel->header.frame_id = robot_base_frame_;
320  cmd_vel->header.stamp = clock_->now();
321  cmd_vel->twist.linear.x = 0.0;
322  cmd_vel->twist.linear.y = 0.0;
323  cmd_vel->twist.angular.z = 0.0;
324 
325  vel_pub_->publish(std::move(cmd_vel));
326  }
327 };
328 
329 } // namespace nav2_behaviors
330 
331 #endif // NAV2_BEHAVIORS__TIMED_BEHAVIOR_HPP_
A sim-time-aware rate for Nav2 loops.
Definition: rate.hpp:61
An action server wrapper to make applications simpler using Actions.
TimedBehavior()
A TimedBehavior constructor.
bool getCurrentPoseChecked(geometry_msgs::msg::PoseStamped &pose)
Get one checked robot pose in the local frame, preserving the TF timestamp.
void deactivate() override
Method to deactivate Behavior and any threads involved in execution.
void activate() override
Method to active Behavior and any threads involved in execution.
void configure(const nav2::LifecycleNode::WeakPtr &parent, const std::string &name, nav2::TransformBuffer::SharedPtr tf, std::shared_ptr< nav2_costmap_2d::CostmapTopicCollisionChecker > local_collision_checker, std::shared_ptr< nav2_costmap_2d::CostmapTopicCollisionChecker > global_collision_checker) override
void cleanup() override
Method to cleanup resources used on shutdown.
Abstract interface for behaviors to adhere to with pluginlib.
Definition: behavior.hpp:41