Nav2 Navigation Stack - jazzy  jazzy
ROS 2 Navigation Stack
bt_service_node.hpp
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 #ifndef NAV2_BEHAVIOR_TREE__BT_SERVICE_NODE_HPP_
16 #define NAV2_BEHAVIOR_TREE__BT_SERVICE_NODE_HPP_
17 
18 #include <string>
19 #include <memory>
20 #include <chrono>
21 
22 #include "behaviortree_cpp/action_node.h"
23 #include "behaviortree_cpp/json_export.h"
24 #include "nav2_util/node_utils.hpp"
25 #include "rclcpp/rclcpp.hpp"
26 #include "nav2_behavior_tree/bt_utils.hpp"
27 #include "nav2_behavior_tree/json_utils.hpp"
28 
29 namespace nav2_behavior_tree
30 {
31 
32 using namespace std::chrono_literals; // NOLINT
33 
38 template<class ServiceT>
39 class BtServiceNode : public BT::ActionNodeBase
40 {
41 public:
49  const std::string & service_node_name,
50  const BT::NodeConfiguration & conf,
51  const std::string & service_name = "")
52  : BT::ActionNodeBase(service_node_name, conf), service_name_(service_name), service_node_name_(
53  service_node_name)
54  {
55  node_ = config().blackboard->template get<rclcpp::Node::SharedPtr>("node");
56  callback_group_ = node_->create_callback_group(
57  rclcpp::CallbackGroupType::MutuallyExclusive,
58  false);
59  callback_group_executor_.add_callback_group(callback_group_, node_->get_node_base_interface());
60 
61  // Get the required items from the blackboard
62  auto bt_loop_duration =
63  config().blackboard->template get<std::chrono::milliseconds>("bt_loop_duration");
64  getInputOrBlackboard("server_timeout", server_timeout_);
65  wait_for_service_timeout_ =
66  config().blackboard->template get<std::chrono::milliseconds>("wait_for_service_timeout");
67 
68  // timeout should be less than bt_loop_duration to be able to finish the current tick
69  max_timeout_ = std::chrono::duration_cast<std::chrono::milliseconds>(bt_loop_duration * 0.5);
70 
71  // Now that we have node_ to use, create the service client for this BT service
72  getInput("service_name", service_name_);
73  service_client_ = node_->create_client<ServiceT>(
74  service_name_,
75  rclcpp::SystemDefaultsQoS(),
76  callback_group_);
77 
78  // Make a request for the service without parameter
79  request_ = std::make_shared<typename ServiceT::Request>();
80 
81  // Make sure the server is actually there before continuing
82  RCLCPP_DEBUG(
83  node_->get_logger(), "Waiting for \"%s\" service",
84  service_name_.c_str());
85  if (!service_client_->wait_for_service(wait_for_service_timeout_)) {
86  RCLCPP_ERROR(
87  node_->get_logger(), "\"%s\" service server not available after waiting for %.2fs",
88  service_name_.c_str(), wait_for_service_timeout_.count() / 1000.0);
89  throw std::runtime_error(
90  std::string("Service server ") + service_name_ +
91  std::string(" not available"));
92  }
93 
94  RCLCPP_DEBUG(
95  node_->get_logger(), "\"%s\" BtServiceNode initialized",
96  service_node_name_.c_str());
97  }
98 
99  BtServiceNode() = delete;
100 
101  virtual ~BtServiceNode()
102  {
103  }
104 
111  static BT::PortsList providedBasicPorts(BT::PortsList addition)
112  {
113  BT::PortsList basic = {
114  BT::InputPort<std::string>("service_name", "please_set_service_name_in_BT_Node"),
115  BT::InputPort<std::chrono::milliseconds>("server_timeout")
116  };
117  basic.insert(addition.begin(), addition.end());
118 
119  return basic;
120  }
121 
126  static BT::PortsList providedPorts()
127  {
128  return providedBasicPorts({});
129  }
130 
135  BT::NodeStatus tick() override
136  {
137  if (!request_sent_) {
138  // reset the flag to send the request or not,
139  // allowing the user the option to set it in on_tick
140  should_send_request_ = true;
141 
142  // Clear the input request to make sure we have no leftover from previous calls
143  request_ = std::make_shared<typename ServiceT::Request>();
144 
145  // user defined callback, may modify "should_send_request_".
146  on_tick();
147 
148  if (!should_send_request_) {
149  return BT::NodeStatus::FAILURE;
150  }
151 
152  future_result_ = service_client_->async_send_request(request_).share();
153  sent_time_ = node_->now();
154  request_sent_ = true;
155  }
156  return check_future();
157  }
158 
162  void halt() override
163  {
164  request_sent_ = false;
165  resetStatus();
166  }
167 
172  virtual void on_tick()
173  {
174  }
175 
182  virtual BT::NodeStatus on_completion(std::shared_ptr<typename ServiceT::Response>/*response*/)
183  {
184  return BT::NodeStatus::SUCCESS;
185  }
186 
191  virtual BT::NodeStatus check_future()
192  {
193  auto elapsed = (node_->now() - sent_time_).template to_chrono<std::chrono::milliseconds>();
194  auto remaining = server_timeout_ - elapsed;
195 
196  if (remaining > std::chrono::milliseconds(0)) {
197  auto timeout = remaining > max_timeout_ ? max_timeout_ : remaining;
198 
199  rclcpp::FutureReturnCode rc;
200  rc = callback_group_executor_.spin_until_future_complete(future_result_, timeout);
201  if (rc == rclcpp::FutureReturnCode::SUCCESS) {
202  request_sent_ = false;
203  BT::NodeStatus status = on_completion(future_result_.get());
204  return status;
205  }
206 
207  if (rc == rclcpp::FutureReturnCode::TIMEOUT) {
208  on_wait_for_result();
209  elapsed = (node_->now() - sent_time_).template to_chrono<std::chrono::milliseconds>();
210  if (elapsed < server_timeout_) {
211  return BT::NodeStatus::RUNNING;
212  }
213  }
214  }
215 
216  RCLCPP_WARN(
217  node_->get_logger(),
218  "Node timed out while executing service call to %s.", service_name_.c_str());
219  request_sent_ = false;
220  return BT::NodeStatus::FAILURE;
221  }
222 
227  virtual void on_wait_for_result()
228  {
229  }
230 
231 protected:
236  {
237  int recovery_count = 0;
238  [[maybe_unused]] auto res = config().blackboard->get("number_recoveries", recovery_count); // NOLINT
239  recovery_count += 1;
240  config().blackboard->set("number_recoveries", recovery_count); // NOLINT
241  }
242 
243  std::string service_name_, service_node_name_;
244  typename std::shared_ptr<rclcpp::Client<ServiceT>> service_client_;
245  std::shared_ptr<typename ServiceT::Request> request_;
246 
247  // The node that will be used for any ROS operations
248  rclcpp::Node::SharedPtr node_;
249  rclcpp::CallbackGroup::SharedPtr callback_group_;
250  rclcpp::executors::SingleThreadedExecutor callback_group_executor_;
251 
252  // The timeout value while to use in the tick loop while waiting for
253  // a result from the server
254  std::chrono::milliseconds server_timeout_;
255 
256  // The timeout value for BT loop execution
257  std::chrono::milliseconds max_timeout_;
258 
259  // The timeout value for waiting for a service to response
260  std::chrono::milliseconds wait_for_service_timeout_;
261 
262  // To track the server response when a new request is sent
263  std::shared_future<typename ServiceT::Response::SharedPtr> future_result_;
264  bool request_sent_{false};
265  rclcpp::Time sent_time_;
266 
267  // Can be set in on_tick or on_wait_for_result to indicate if a request should be sent.
268  bool should_send_request_;
269 };
270 
271 } // namespace nav2_behavior_tree
272 
273 #endif // NAV2_BEHAVIOR_TREE__BT_SERVICE_NODE_HPP_
Abstract class representing a service based BT node.
BT::NodeStatus tick() override
The main override required by a BT service.
virtual void on_tick()
Function to perform some user-defined operation on tick Fill in service request with information if n...
static BT::PortsList providedPorts()
Creates list of BT ports.
static BT::PortsList providedBasicPorts(BT::PortsList addition)
Any subclass of BtServiceNode that accepts parameters must provide a providedPorts method and call pr...
virtual BT::NodeStatus check_future()
Check the future and decide the status of BT.
void halt() override
The other (optional) override required by a BT service.
void increment_recovery_count()
Function to increment recovery count on blackboard if this node wraps a recovery.
virtual void on_wait_for_result()
Function to perform some user-defined operation after a timeout waiting for a result that hasn't been...
BtServiceNode(const std::string &service_node_name, const BT::NodeConfiguration &conf, const std::string &service_name="")
A nav2_behavior_tree::BtServiceNode constructor.
virtual BT::NodeStatus on_completion(std::shared_ptr< typename ServiceT::Response >)
Function to perform some user-defined operation upon successful completion of the service....