-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathbt_navigator.cpp
358 lines (295 loc) · 12 KB
/
bt_navigator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "nav2_bt_navigator/bt_navigator.hpp"
#include <fstream>
#include <memory>
#include <streambuf>
#include <string>
#include <utility>
#include <vector>
#include <set>
#include <exception>
#include "nav2_util/geometry_utils.hpp"
#include "nav2_util/robot_utils.hpp"
#include "nav2_behavior_tree/bt_conversions.hpp"
#include "nav2_bt_navigator/ros_topic_logger.hpp"
namespace nav2_bt_navigator
{
BtNavigator::BtNavigator()
: nav2_util::LifecycleNode("bt_navigator", "", false),
start_time_(0)
{
RCLCPP_INFO(get_logger(), "Creating");
const std::vector<std::string> plugin_libs = {
"nav2_compute_path_to_pose_action_bt_node",
"nav2_follow_path_action_bt_node",
"nav2_back_up_action_bt_node",
"nav2_spin_action_bt_node",
"nav2_wait_action_bt_node",
"nav2_clear_costmap_service_bt_node",
"nav2_is_stuck_condition_bt_node",
"nav2_goal_reached_condition_bt_node",
"nav2_initial_pose_received_condition_bt_node",
"nav2_goal_updated_condition_bt_node",
"nav2_reinitialize_global_localization_service_bt_node",
"nav2_rate_controller_bt_node",
"nav2_distance_controller_bt_node",
"nav2_speed_controller_bt_node",
"nav2_truncate_path_action_bt_node",
"nav2_recovery_node_bt_node",
"nav2_pipeline_sequence_bt_node",
"nav2_round_robin_node_bt_node",
"nav2_transform_available_condition_bt_node",
"nav2_time_expired_condition_bt_node",
"nav2_distance_traveled_condition_bt_node",
"nav2_rotate_action_bt_node",
"nav2_translate_action_bt_node",
"nav2_is_battery_low_condition_bt_node",
"nav2_goal_updater_node_bt_node",
"nav2_navigate_to_pose_action_bt_node",
};
// Declare this node's parameters
declare_parameter("default_bt_xml_filename");
declare_parameter("plugin_lib_names", plugin_libs);
declare_parameter("transform_tolerance", rclcpp::ParameterValue(0.1));
declare_parameter("global_frame", std::string("map"));
declare_parameter("robot_base_frame", std::string("base_link"));
declare_parameter("odom_topic", std::string("odom"));
declare_parameter("enable_groot_monitoring", true);
declare_parameter("groot_zmq_publisher_port", 1666);
declare_parameter("groot_zmq_server_port", 1667);
}
BtNavigator::~BtNavigator()
{
RCLCPP_INFO(get_logger(), "Destroying");
}
nav2_util::CallbackReturn
BtNavigator::on_configure(const rclcpp_lifecycle::State & /*state*/)
{
RCLCPP_INFO(get_logger(), "Configuring");
// use suffix '_rclcpp_node' to keep parameter file consistency #1773
auto options = rclcpp::NodeOptions().arguments(
{"--ros-args",
"-r", std::string("__node:=") + get_name() + "_rclcpp_node",
"--"});
// Support for handling the topic-based goal pose from rviz
client_node_ = std::make_shared<rclcpp::Node>("_", options);
self_client_ = rclcpp_action::create_client<nav2_msgs::action::NavigateToPose>(
client_node_, "navigate_to_pose");
tf_ = std::make_shared<tf2_ros::Buffer>(get_clock());
auto timer_interface = std::make_shared<tf2_ros::CreateTimerROS>(
get_node_base_interface(), get_node_timers_interface());
tf_->setCreateTimerInterface(timer_interface);
tf_->setUsingDedicatedThread(true);
tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_, this, false);
goal_sub_ = create_subscription<geometry_msgs::msg::PoseStamped>(
"goal_pose",
rclcpp::SystemDefaultsQoS(),
std::bind(&BtNavigator::onGoalPoseReceived, this, std::placeholders::_1));
action_server_ = std::make_unique<ActionServer>(
get_node_base_interface(),
get_node_clock_interface(),
get_node_logging_interface(),
get_node_waitables_interface(),
"navigate_to_pose", std::bind(&BtNavigator::navigateToPose, this), false);
// Get the libraries to pull plugins from
plugin_lib_names_ = get_parameter("plugin_lib_names").as_string_array();
global_frame_ = get_parameter("global_frame").as_string();
robot_frame_ = get_parameter("robot_base_frame").as_string();
transform_tolerance_ = get_parameter("transform_tolerance").as_double();
// Create the class that registers our custom nodes and executes the BT
bt_ = std::make_unique<nav2_behavior_tree::BehaviorTreeEngine>(plugin_lib_names_);
// Create the blackboard that will be shared by all of the nodes in the tree
blackboard_ = BT::Blackboard::create();
// Put items on the blackboard
blackboard_->set<rclcpp::Node::SharedPtr>("node", client_node_); // NOLINT
blackboard_->set<std::shared_ptr<tf2_ros::Buffer>>("tf_buffer", tf_); // NOLINT
blackboard_->set<std::chrono::milliseconds>("server_timeout", std::chrono::milliseconds(10)); // NOLINT
blackboard_->set<bool>("path_updated", false); // NOLINT
blackboard_->set<bool>("initial_pose_received", false); // NOLINT
blackboard_->set<int>("number_recoveries", 0); // NOLINT
// Get the BT filename to use from the node parameter
get_parameter("default_bt_xml_filename", default_bt_xml_filename_);
if (!loadBehaviorTree(default_bt_xml_filename_)) {
RCLCPP_ERROR(get_logger(), "Error loading XML file: %s", default_bt_xml_filename_.c_str());
return nav2_util::CallbackReturn::FAILURE;
}
return nav2_util::CallbackReturn::SUCCESS;
}
bool
BtNavigator::loadBehaviorTree(const std::string & bt_xml_filename)
{
// Use previous BT if it is the existing one
if (current_bt_xml_filename_ == bt_xml_filename) {
RCLCPP_DEBUG(get_logger(), "BT will not be reloaded as the given xml is already loaded");
return true;
}
// if a new tree is created, than the ZMQ Publisher must be destroyed
bt_->resetGrootMonitor();
// Read the input BT XML from the specified file into a string
std::ifstream xml_file(bt_xml_filename);
if (!xml_file.good()) {
RCLCPP_ERROR(get_logger(), "Couldn't open input XML file: %s", bt_xml_filename.c_str());
return false;
}
auto xml_string = std::string(
std::istreambuf_iterator<char>(xml_file),
std::istreambuf_iterator<char>());
// Create the Behavior Tree from the XML input
tree_ = bt_->createTreeFromText(xml_string, blackboard_);
current_bt_xml_filename_ = bt_xml_filename;
// get parameter for monitoring with Groot via ZMQ Publisher
if (get_parameter("enable_groot_monitoring").as_bool()) {
uint16_t zmq_publisher_port = get_parameter("groot_zmq_publisher_port").as_int();
uint16_t zmq_server_port = get_parameter("groot_zmq_server_port").as_int();
// optionally add max_msg_per_second = 25 (default) here
try {
bt_->addGrootMonitoring(&tree_, zmq_publisher_port, zmq_server_port);
} catch (const std::logic_error & e) {
RCLCPP_ERROR(get_logger(), "ZMQ already enabled, Error: %s", e.what());
}
}
return true;
}
nav2_util::CallbackReturn
BtNavigator::on_activate(const rclcpp_lifecycle::State & /*state*/)
{
RCLCPP_INFO(get_logger(), "Activating");
action_server_->activate();
return nav2_util::CallbackReturn::SUCCESS;
}
nav2_util::CallbackReturn
BtNavigator::on_deactivate(const rclcpp_lifecycle::State & /*state*/)
{
RCLCPP_INFO(get_logger(), "Deactivating");
action_server_->deactivate();
return nav2_util::CallbackReturn::SUCCESS;
}
nav2_util::CallbackReturn
BtNavigator::on_cleanup(const rclcpp_lifecycle::State & /*state*/)
{
RCLCPP_INFO(get_logger(), "Cleaning up");
// TODO(orduno) Fix the race condition between the worker thread ticking the tree
// and the main thread resetting the resources, see #1344
goal_sub_.reset();
client_node_.reset();
self_client_.reset();
// Reset the listener before the buffer
tf_listener_.reset();
tf_.reset();
action_server_.reset();
plugin_lib_names_.clear();
current_bt_xml_filename_.clear();
blackboard_.reset();
bt_->haltAllActions(tree_.rootNode());
bt_->resetGrootMonitor();
bt_.reset();
RCLCPP_INFO(get_logger(), "Completed Cleaning up");
return nav2_util::CallbackReturn::SUCCESS;
}
nav2_util::CallbackReturn
BtNavigator::on_shutdown(const rclcpp_lifecycle::State & /*state*/)
{
RCLCPP_INFO(get_logger(), "Shutting down");
return nav2_util::CallbackReturn::SUCCESS;
}
void
BtNavigator::navigateToPose()
{
initializeGoalPose();
auto is_canceling = [this]() {
if (action_server_ == nullptr) {
RCLCPP_DEBUG(get_logger(), "Action server unavailable. Canceling.");
return true;
}
if (!action_server_->is_server_active()) {
RCLCPP_DEBUG(get_logger(), "Action server is inactive. Canceling.");
return true;
}
return action_server_->is_cancel_requested();
};
std::string bt_xml_filename = action_server_->get_current_goal()->behavior_tree;
// Empty id in request is default for backward compatibility
bt_xml_filename = bt_xml_filename == "" ? default_bt_xml_filename_ : bt_xml_filename;
if (!loadBehaviorTree(bt_xml_filename)) {
RCLCPP_ERROR(
get_logger(), "BT file not found: %s. Navigation canceled.",
bt_xml_filename.c_str());
action_server_->terminate_current();
return;
}
RosTopicLogger topic_logger(client_node_, tree_);
std::shared_ptr<Action::Feedback> feedback_msg = std::make_shared<Action::Feedback>();
auto on_loop = [&]() {
if (action_server_->is_preempt_requested()) {
RCLCPP_INFO(get_logger(), "Received goal preemption request");
action_server_->accept_pending_goal();
initializeGoalPose();
}
topic_logger.flush();
// action server feedback (pose, duration of task,
// number of recoveries, and distance remaining to goal)
nav2_util::getCurrentPose(
feedback_msg->current_pose, *tf_, global_frame_, robot_frame_, transform_tolerance_);
geometry_msgs::msg::PoseStamped goal_pose;
blackboard_->get("goal", goal_pose);
feedback_msg->distance_remaining = nav2_util::geometry_utils::euclidean_distance(
feedback_msg->current_pose.pose, goal_pose.pose);
int recovery_count = 0;
blackboard_->get<int>("number_recoveries", recovery_count);
feedback_msg->number_of_recoveries = recovery_count;
feedback_msg->navigation_time = now() - start_time_;
action_server_->publish_feedback(feedback_msg);
};
// Execute the BT that was previously created in the configure step
nav2_behavior_tree::BtStatus rc = bt_->run(&tree_, on_loop, is_canceling);
// Make sure that the Bt is not in a running state from a previous execution
// note: if all the ControlNodes are implemented correctly, this is not needed.
bt_->haltAllActions(tree_.rootNode());
switch (rc) {
case nav2_behavior_tree::BtStatus::SUCCEEDED:
RCLCPP_INFO(get_logger(), "Navigation succeeded");
action_server_->succeeded_current();
break;
case nav2_behavior_tree::BtStatus::FAILED:
RCLCPP_ERROR(get_logger(), "Navigation failed");
action_server_->terminate_current();
break;
case nav2_behavior_tree::BtStatus::CANCELED:
RCLCPP_INFO(get_logger(), "Navigation canceled");
action_server_->terminate_all();
break;
}
}
void
BtNavigator::initializeGoalPose()
{
auto goal = action_server_->get_current_goal();
RCLCPP_INFO(
get_logger(), "Begin navigating from current location to (%.2f, %.2f)",
goal->pose.pose.position.x, goal->pose.pose.position.y);
// Reset state for new action feedback
start_time_ = now();
blackboard_->set<int>("number_recoveries", 0); // NOLINT
// Update the goal pose on the blackboard
blackboard_->set("goal", goal->pose);
}
void
BtNavigator::onGoalPoseReceived(const geometry_msgs::msg::PoseStamped::SharedPtr pose)
{
nav2_msgs::action::NavigateToPose::Goal goal;
goal.pose = *pose;
self_client_->async_send_goal(goal);
}
} // namespace nav2_bt_navigator