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 "behaviortree_cpp/json_export.h"
24 #include "nav2_util/node_utils.hpp"
25 #include "rclcpp_action/rclcpp_action.hpp"
26 #include "nav2_behavior_tree/bt_utils.hpp"
27 #include "nav2_behavior_tree/json_utils.hpp"
29 namespace nav2_behavior_tree
32 using namespace std::chrono_literals;
38 template<
class ActionT>
49 const std::string & xml_tag_name,
50 const std::string & action_name,
51 const BT::NodeConfiguration & conf)
52 : BT::ActionNodeBase(xml_tag_name, conf), action_name_(action_name), should_send_goal_(true)
54 node_ = config().blackboard->template get<rclcpp::Node::SharedPtr>(
"node");
55 callback_group_ = node_->create_callback_group(
56 rclcpp::CallbackGroupType::MutuallyExclusive,
58 callback_group_executor_.add_callback_group(callback_group_, node_->get_node_base_interface());
61 auto bt_loop_duration =
62 config().blackboard->template get<std::chrono::milliseconds>(
"bt_loop_duration");
63 getInputOrBlackboard(
"server_timeout", server_timeout_);
64 getInputOrBlackboard(
"cancel_timeout", cancel_timeout_);
65 wait_for_service_timeout_ =
66 config().blackboard->template get<std::chrono::milliseconds>(
"wait_for_service_timeout");
69 max_timeout_ = std::chrono::duration_cast<std::chrono::milliseconds>(bt_loop_duration * 0.5);
72 goal_ =
typename ActionT::Goal();
73 result_ =
typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult();
75 std::string remapped_action_name;
76 if (getInput(
"server_name", remapped_action_name)) {
77 action_name_ = remapped_action_name;
79 createActionClient(action_name_);
82 RCLCPP_DEBUG(node_->get_logger(),
"\"%s\" BtActionNode initialized", xml_tag_name.c_str());
98 action_client_ = rclcpp_action::create_client<ActionT>(node_, action_name, callback_group_);
101 RCLCPP_DEBUG(node_->get_logger(),
"Waiting for \"%s\" action server", action_name.c_str());
102 if (!action_client_->wait_for_action_server(wait_for_service_timeout_)) {
104 node_->get_logger(),
"\"%s\" action server not available after waiting for %.2fs",
106 wait_for_service_timeout_.count() / 1000.0);
107 throw std::runtime_error(
108 std::string(
"Action server ") + action_name +
109 std::string(
" not available"));
121 BT::PortsList basic = {
122 BT::InputPort<std::string>(
"server_name",
"Action server name"),
123 BT::InputPort<std::chrono::milliseconds>(
"server_timeout")
125 basic.insert(addition.begin(), addition.end());
136 return providedBasicPorts({});
168 return BT::NodeStatus::SUCCESS;
177 return BT::NodeStatus::FAILURE;
186 return BT::NodeStatus::SUCCESS;
196 if (!BT::isStatusActive(status())) {
198 should_send_goal_ =
true;
201 goal_ =
typename ActionT::Goal();
202 result_ =
typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult();
208 setStatus(BT::NodeStatus::RUNNING);
210 if (!should_send_goal_) {
211 return BT::NodeStatus::FAILURE;
219 if (future_goal_handle_) {
221 (node_->now() - time_goal_sent_).
template to_chrono<std::chrono::milliseconds>();
222 if (!is_future_goal_handle_complete(elapsed)) {
224 if (elapsed < server_timeout_) {
225 return BT::NodeStatus::RUNNING;
230 "Timed out while waiting for action server to acknowledge goal request for %s",
231 action_name_.c_str());
232 future_goal_handle_.reset();
233 return BT::NodeStatus::FAILURE;
238 if (rclcpp::ok() && !goal_result_available_) {
240 on_wait_for_result(feedback_);
245 auto goal_status = goal_handle_->get_status();
247 (goal_status == action_msgs::msg::GoalStatus::STATUS_EXECUTING ||
248 goal_status == action_msgs::msg::GoalStatus::STATUS_ACCEPTED))
250 goal_updated_ =
false;
253 (node_->now() - time_goal_sent_).
template to_chrono<std::chrono::milliseconds>();
254 if (!is_future_goal_handle_complete(elapsed)) {
255 if (elapsed < server_timeout_) {
256 return BT::NodeStatus::RUNNING;
260 "Timed out while waiting for action server to acknowledge goal request for %s",
261 action_name_.c_str());
262 future_goal_handle_.reset();
263 return BT::NodeStatus::FAILURE;
267 callback_group_executor_.spin_some();
270 if (!goal_result_available_) {
272 return BT::NodeStatus::RUNNING;
275 }
catch (
const std::runtime_error & e) {
276 if (e.what() == std::string(
"send_goal failed") ||
277 e.what() == std::string(
"Goal was rejected by the action server"))
280 return BT::NodeStatus::FAILURE;
287 BT::NodeStatus status;
288 switch (result_.code) {
289 case rclcpp_action::ResultCode::SUCCEEDED:
290 status = on_success();
293 case rclcpp_action::ResultCode::ABORTED:
294 status = on_aborted();
297 case rclcpp_action::ResultCode::CANCELED:
298 status = on_cancelled();
302 throw std::logic_error(
"BtActionNode::Tick: invalid status value");
305 goal_handle_.reset();
315 if (should_cancel_goal()) {
316 auto future_result = action_client_->async_get_result(goal_handle_);
317 auto future_cancel = action_client_->async_cancel_goal(goal_handle_);
318 if (callback_group_executor_.spin_until_future_complete(future_cancel, server_timeout_) !=
319 rclcpp::FutureReturnCode::SUCCESS)
323 "Failed to cancel action server for %s", action_name_.c_str());
326 if (callback_group_executor_.spin_until_future_complete(future_result, cancel_timeout_) !=
327 rclcpp::FutureReturnCode::SUCCESS)
331 "Failed to get result for %s in node halt!", action_name_.c_str());
350 if (status() != BT::NodeStatus::RUNNING) {
359 callback_group_executor_.spin_some();
360 auto status = goal_handle_->get_status();
363 return status == action_msgs::msg::GoalStatus::STATUS_ACCEPTED ||
364 status == action_msgs::msg::GoalStatus::STATUS_EXECUTING;
372 goal_result_available_ =
false;
373 auto send_goal_options =
typename rclcpp_action::Client<ActionT>::SendGoalOptions();
374 send_goal_options.result_callback =
375 [
this](
const typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult & result) {
376 if (future_goal_handle_) {
379 "Goal result for %s available, but it hasn't received the goal response yet. "
380 "It's probably a goal result for the last goal request", action_name_.c_str());
387 if (this->goal_handle_->get_goal_id() == result.goal_id) {
388 goal_result_available_ =
true;
393 send_goal_options.feedback_callback =
394 [
this](
typename rclcpp_action::ClientGoalHandle<ActionT>::SharedPtr,
395 const std::shared_ptr<const typename ActionT::Feedback> feedback) {
396 feedback_ = feedback;
400 future_goal_handle_ = std::make_shared<
401 std::shared_future<typename rclcpp_action::ClientGoalHandle<ActionT>::SharedPtr>>(
402 action_client_->async_send_goal(goal_, send_goal_options));
403 time_goal_sent_ = node_->now();
414 auto remaining = server_timeout_ - elapsed;
417 if (remaining <= std::chrono::milliseconds(0)) {
418 future_goal_handle_.reset();
422 auto timeout = remaining > max_timeout_ ? max_timeout_ : remaining;
424 callback_group_executor_.spin_until_future_complete(*future_goal_handle_, timeout);
427 if (result == rclcpp::FutureReturnCode::INTERRUPTED) {
428 future_goal_handle_.reset();
429 throw std::runtime_error(
"send_goal failed");
432 if (result == rclcpp::FutureReturnCode::SUCCESS) {
433 goal_handle_ = future_goal_handle_->get();
434 future_goal_handle_.reset();
436 throw std::runtime_error(
"Goal was rejected by the action server");
449 int recovery_count = 0;
450 [[maybe_unused]]
auto res = config().blackboard->get(
"number_recoveries", recovery_count);
452 config().blackboard->set(
"number_recoveries", recovery_count);
455 std::string action_name_;
456 typename std::shared_ptr<rclcpp_action::Client<ActionT>> action_client_;
459 typename ActionT::Goal goal_;
460 bool goal_updated_{
false};
461 bool goal_result_available_{
false};
462 typename rclcpp_action::ClientGoalHandle<ActionT>::SharedPtr goal_handle_;
463 typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult result_;
466 std::shared_ptr<const typename ActionT::Feedback> feedback_;
469 rclcpp::Node::SharedPtr node_;
470 rclcpp::CallbackGroup::SharedPtr callback_group_;
471 rclcpp::executors::SingleThreadedExecutor callback_group_executor_;
475 std::chrono::milliseconds server_timeout_;
478 std::chrono::milliseconds cancel_timeout_;
481 std::chrono::milliseconds max_timeout_;
484 std::chrono::milliseconds wait_for_service_timeout_;
487 std::shared_ptr<std::shared_future<typename rclcpp_action::ClientGoalHandle<ActionT>::SharedPtr>>
489 rclcpp::Time time_goal_sent_;
492 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.