15 #ifndef NAV2_BEHAVIOR_TREE__BT_ACTION_NODE_HPP_
16 #define NAV2_BEHAVIOR_TREE__BT_ACTION_NODE_HPP_
22 #include "behaviortree_cpp/action_node.h"
23 #include "nav2_util/node_utils.hpp"
24 #include "rclcpp_action/rclcpp_action.hpp"
25 #include "nav2_behavior_tree/bt_utils.hpp"
27 namespace nav2_behavior_tree
30 using namespace std::chrono_literals;
36 template<
class ActionT>
47 const std::string & xml_tag_name,
48 const std::string & action_name,
49 const BT::NodeConfiguration & conf)
50 : BT::ActionNodeBase(xml_tag_name, conf), action_name_(action_name), should_send_goal_(true)
52 node_ = config().blackboard->template get<rclcpp::Node::SharedPtr>(
"node");
53 callback_group_ = node_->create_callback_group(
54 rclcpp::CallbackGroupType::MutuallyExclusive,
56 callback_group_executor_.add_callback_group(callback_group_, node_->get_node_base_interface());
59 auto bt_loop_duration =
60 config().blackboard->template get<std::chrono::milliseconds>(
"bt_loop_duration");
61 getInputOrBlackboard(
"server_timeout", server_timeout_);
62 wait_for_service_timeout_ =
63 config().blackboard->template get<std::chrono::milliseconds>(
"wait_for_service_timeout");
66 max_timeout_ = std::chrono::duration_cast<std::chrono::milliseconds>(bt_loop_duration * 0.5);
69 goal_ =
typename ActionT::Goal();
70 result_ =
typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult();
72 std::string remapped_action_name;
73 if (getInput(
"server_name", remapped_action_name)) {
74 action_name_ = remapped_action_name;
76 createActionClient(action_name_);
79 RCLCPP_DEBUG(node_->get_logger(),
"\"%s\" BtActionNode initialized", xml_tag_name.c_str());
95 action_client_ = rclcpp_action::create_client<ActionT>(node_, action_name, callback_group_);
98 RCLCPP_DEBUG(node_->get_logger(),
"Waiting for \"%s\" action server", action_name.c_str());
99 if (!action_client_->wait_for_action_server(wait_for_service_timeout_)) {
101 node_->get_logger(),
"\"%s\" action server not available after waiting for %.2fs",
103 wait_for_service_timeout_.count() / 1000.0);
104 throw std::runtime_error(
105 std::string(
"Action server ") + action_name +
106 std::string(
" not available"));
118 BT::PortsList basic = {
119 BT::InputPort<std::string>(
"server_name",
"Action server name"),
120 BT::InputPort<std::chrono::milliseconds>(
"server_timeout")
122 basic.insert(addition.begin(), addition.end());
133 return providedBasicPorts({});
165 return BT::NodeStatus::SUCCESS;
174 return BT::NodeStatus::FAILURE;
183 return BT::NodeStatus::SUCCESS;
193 if (!BT::isStatusActive(status())) {
195 should_send_goal_ =
true;
198 goal_ =
typename ActionT::Goal();
199 result_ =
typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult();
205 setStatus(BT::NodeStatus::RUNNING);
207 if (!should_send_goal_) {
208 return BT::NodeStatus::FAILURE;
216 if (future_goal_handle_) {
218 (node_->now() - time_goal_sent_).
template to_chrono<std::chrono::milliseconds>();
219 if (!is_future_goal_handle_complete(elapsed)) {
221 if (elapsed < server_timeout_) {
222 return BT::NodeStatus::RUNNING;
227 "Timed out while waiting for action server to acknowledge goal request for %s",
228 action_name_.c_str());
229 future_goal_handle_.reset();
230 return BT::NodeStatus::FAILURE;
235 if (rclcpp::ok() && !goal_result_available_) {
237 on_wait_for_result(feedback_);
242 auto goal_status = goal_handle_->get_status();
244 (goal_status == action_msgs::msg::GoalStatus::STATUS_EXECUTING ||
245 goal_status == action_msgs::msg::GoalStatus::STATUS_ACCEPTED))
247 goal_updated_ =
false;
250 (node_->now() - time_goal_sent_).
template to_chrono<std::chrono::milliseconds>();
251 if (!is_future_goal_handle_complete(elapsed)) {
252 if (elapsed < server_timeout_) {
253 return BT::NodeStatus::RUNNING;
257 "Timed out while waiting for action server to acknowledge goal request for %s",
258 action_name_.c_str());
259 future_goal_handle_.reset();
260 return BT::NodeStatus::FAILURE;
264 callback_group_executor_.spin_some();
267 if (!goal_result_available_) {
269 return BT::NodeStatus::RUNNING;
272 }
catch (
const std::runtime_error & e) {
273 if (e.what() == std::string(
"send_goal failed") ||
274 e.what() == std::string(
"Goal was rejected by the action server"))
277 return BT::NodeStatus::FAILURE;
284 BT::NodeStatus status;
285 switch (result_.code) {
286 case rclcpp_action::ResultCode::SUCCEEDED:
287 status = on_success();
290 case rclcpp_action::ResultCode::ABORTED:
291 status = on_aborted();
294 case rclcpp_action::ResultCode::CANCELED:
295 status = on_cancelled();
299 throw std::logic_error(
"BtActionNode::Tick: invalid status value");
302 goal_handle_.reset();
312 if (should_cancel_goal()) {
313 auto future_result = action_client_->async_get_result(goal_handle_);
314 auto future_cancel = action_client_->async_cancel_goal(goal_handle_);
315 if (callback_group_executor_.spin_until_future_complete(future_cancel, server_timeout_) !=
316 rclcpp::FutureReturnCode::SUCCESS)
320 "Failed to cancel action server for %s", action_name_.c_str());
323 if (callback_group_executor_.spin_until_future_complete(future_result, server_timeout_) !=
324 rclcpp::FutureReturnCode::SUCCESS)
328 "Failed to get result for %s in node halt!", action_name_.c_str());
347 if (status() != BT::NodeStatus::RUNNING) {
356 callback_group_executor_.spin_some();
357 auto status = goal_handle_->get_status();
360 return status == action_msgs::msg::GoalStatus::STATUS_ACCEPTED ||
361 status == action_msgs::msg::GoalStatus::STATUS_EXECUTING;
369 goal_result_available_ =
false;
370 auto send_goal_options =
typename rclcpp_action::Client<ActionT>::SendGoalOptions();
371 send_goal_options.result_callback =
372 [
this](
const typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult & result) {
373 if (future_goal_handle_) {
376 "Goal result for %s available, but it hasn't received the goal response yet. "
377 "It's probably a goal result for the last goal request", action_name_.c_str());
384 if (this->goal_handle_->get_goal_id() == result.goal_id) {
385 goal_result_available_ =
true;
390 send_goal_options.feedback_callback =
391 [
this](
typename rclcpp_action::ClientGoalHandle<ActionT>::SharedPtr,
392 const std::shared_ptr<const typename ActionT::Feedback> feedback) {
393 feedback_ = feedback;
397 future_goal_handle_ = std::make_shared<
398 std::shared_future<typename rclcpp_action::ClientGoalHandle<ActionT>::SharedPtr>>(
399 action_client_->async_send_goal(goal_, send_goal_options));
400 time_goal_sent_ = node_->now();
411 auto remaining = server_timeout_ - elapsed;
414 if (remaining <= std::chrono::milliseconds(0)) {
415 future_goal_handle_.reset();
419 auto timeout = remaining > max_timeout_ ? max_timeout_ : remaining;
421 callback_group_executor_.spin_until_future_complete(*future_goal_handle_, timeout);
424 if (result == rclcpp::FutureReturnCode::INTERRUPTED) {
425 future_goal_handle_.reset();
426 throw std::runtime_error(
"send_goal failed");
429 if (result == rclcpp::FutureReturnCode::SUCCESS) {
430 goal_handle_ = future_goal_handle_->get();
431 future_goal_handle_.reset();
433 throw std::runtime_error(
"Goal was rejected by the action server");
446 int recovery_count = 0;
447 [[maybe_unused]]
auto res = config().blackboard->get(
"number_recoveries", recovery_count);
449 config().blackboard->set(
"number_recoveries", recovery_count);
452 std::string action_name_;
453 typename std::shared_ptr<rclcpp_action::Client<ActionT>> action_client_;
456 typename ActionT::Goal goal_;
457 bool goal_updated_{
false};
458 bool goal_result_available_{
false};
459 typename rclcpp_action::ClientGoalHandle<ActionT>::SharedPtr goal_handle_;
460 typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult result_;
463 std::shared_ptr<const typename ActionT::Feedback> feedback_;
466 rclcpp::Node::SharedPtr node_;
467 rclcpp::CallbackGroup::SharedPtr callback_group_;
468 rclcpp::executors::SingleThreadedExecutor callback_group_executor_;
472 std::chrono::milliseconds server_timeout_;
475 std::chrono::milliseconds max_timeout_;
478 std::chrono::milliseconds wait_for_service_timeout_;
481 std::shared_ptr<std::shared_future<typename rclcpp_action::ClientGoalHandle<ActionT>::SharedPtr>>
483 rclcpp::Time time_goal_sent_;
486 bool should_send_goal_;
Abstract class representing an action based BT node.
BT::NodeStatus tick() override
The main override required by a BT action.
bool is_future_goal_handle_complete(std::chrono::milliseconds &elapsed)
Function to check if the action server acknowledged a new goal.
virtual BT::NodeStatus on_cancelled()
Function to perform some user-defined operation when the action is cancelled.
virtual BT::NodeStatus on_success()
Function to perform some user-defined operation upon successful completion of the action....
void halt() override
The other (optional) override required by a BT action. In this case, we make sure to cancel the ROS2 ...
virtual BT::NodeStatus on_aborted()
Function to perform some user-defined operation when the action is aborted.
static BT::PortsList providedBasicPorts(BT::PortsList addition)
Any subclass of BtActionNode that accepts parameters must provide a providedPorts method and call pro...
virtual void on_tick()
Function to perform some user-defined operation on tick Could do dynamic checks, such as getting upda...
void createActionClient(const std::string &action_name)
Create instance of an action client.
virtual void on_wait_for_result(std::shared_ptr< const typename ActionT::Feedback >)
Function to perform some user-defined operation after a timeout waiting for a result that hasn't been...
void send_new_goal()
Function to send new goal to action server.
BtActionNode(const std::string &xml_tag_name, const std::string &action_name, const BT::NodeConfiguration &conf)
A nav2_behavior_tree::BtActionNode constructor.
static BT::PortsList providedPorts()
Creates list of BT ports.
bool should_cancel_goal()
Function to check if current goal should be cancelled.
void increment_recovery_count()
Function to increment recovery count on blackboard if this node wraps a recovery.