Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
simple_non_charging_dock.cpp
1 // Copyright (c) 2024 Open Navigation LLC
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 #include <cmath>
16 #include <chrono>
17 
18 #include "nav2_ros_common/node_utils.hpp"
19 #include "nav2_util/robot_utils.hpp"
20 #include "opennav_docking/simple_non_charging_dock.hpp"
21 #include "opennav_docking/utils.hpp"
22 #include "nav2_ros_common/tf2_factories.hpp"
23 
24 using namespace std::chrono_literals;
25 
26 namespace opennav_docking
27 {
28 
29 void SimpleNonChargingDock::configure(
30  const nav2::LifecycleNode::WeakPtr & parent,
31  const std::string & name, nav2::TransformBuffer::SharedPtr tf)
32 {
33  name_ = name;
34  tf2_buffer_ = tf;
35  node_ = parent.lock();
36  if (!node_) {
37  throw std::runtime_error{"Failed to lock node"};
38  }
39 
40  // Parameters for optional external detection of dock pose
41  use_external_detection_pose_ = node_->declare_or_get_parameter(
42  name + ".use_external_detection_pose", false);
43  external_detection_timeout_ = node_->declare_or_get_parameter(
44  name + ".external_detection_timeout", 1.0);
45  external_detection_translation_x_ = node_->declare_or_get_parameter(
46  name + ".external_detection_translation_x", -0.20);
47  external_detection_translation_y_ = node_->declare_or_get_parameter(
48  name + ".external_detection_translation_y", 0.0);
49  double yaw = node_->declare_or_get_parameter(
50  name + ".external_detection_rotation_yaw", 0.0);
51  double pitch = node_->declare_or_get_parameter(
52  name + ".external_detection_rotation_pitch", 1.57);
53  double roll = node_->declare_or_get_parameter(
54  name + ".external_detection_rotation_roll", -1.57);
55  double filter_coef = node_->declare_or_get_parameter(
56  name + ".filter_coef", 0.1);
57 
58  // Parameters for optional detector control
59  detector_service_name_ = node_->declare_or_get_parameter(
60  name + ".detector_service_name", std::string(""));
61  detector_service_timeout_ = node_->declare_or_get_parameter(
62  name + ".detector_service_timeout", 5.0);
63  subscribe_toggle_ = node_->declare_or_get_parameter(
64  name + ".subscribe_toggle", false);
65 
66  // Optionally determine if docked via stall detection using joint_states
67  bool use_stall_detection = node_->declare_or_get_parameter(
68  name + ".use_stall_detection", false);
69  stall_joint_names_ = node_->declare_or_get_parameter(
70  name + ".stall_joint_names", std::vector<std::string>());
71  stall_velocity_threshold_ = node_->declare_or_get_parameter(
72  name + ".stall_velocity_threshold", 1.0);
73  stall_effort_threshold_ = node_->declare_or_get_parameter(
74  name + ".stall_effort_threshold", 1.0);
75 
76  // If not using stall detection, this is how close robot should get to pose
77  docking_threshold_ = node_->declare_or_get_parameter(
78  name + ".docking_threshold", 0.05);
79 
80  // Staging pose configuration
81  staging_x_offset_ = node_->declare_or_get_parameter(
82  name + ".staging_x_offset", -0.7);
83  staging_yaw_offset_ = node_->declare_or_get_parameter(
84  name + ".staging_yaw_offset", 0.0);
85 
86  // Direction of docking and if we should rotate to dock
87  std::string dock_direction = node_->declare_or_get_parameter(
88  name + ".dock_direction", std::string("forward"));
89  rotate_to_dock_ = node_->declare_or_get_parameter(
90  name + ".rotate_to_dock", false);
91 
92  transform_staleness_threshold_ = node_->declare_or_get_parameter(
93  name + ".transform_staleness_threshold", 0.0);
94 
95  node_->get_parameter("base_frame", base_frame_id_); // Get server base frame ID
96 
97  // Initialize detection state
98  detection_active_ = false;
99  initial_pose_received_ = false;
100 
101  // Create persistent subscription if toggling is disabled.
102  if (use_external_detection_pose_ && !subscribe_toggle_) {
103  dock_pose_.header.stamp = rclcpp::Time(0);
104  dock_pose_sub_ = node_->create_subscription<geometry_msgs::msg::PoseStamped>(
105  "detected_dock_pose",
106  [this](const geometry_msgs::msg::PoseStamped::ConstSharedPtr & pose) {
107  detected_dock_pose_ = *pose;
108  initial_pose_received_ = true;
109  },
111  }
112 
113  dock_direction_ = utils::getDockDirectionFromString(dock_direction);
114  if (dock_direction_ == opennav_docking_core::DockDirection::UNKNOWN) {
115  throw std::runtime_error{"Dock direction is not valid. Valid options are: forward or backward"};
116  }
117 
118  if (rotate_to_dock_ && dock_direction_ != opennav_docking_core::DockDirection::BACKWARD) {
119  throw std::runtime_error{"Parameter rotate_to_dock is enabled but dock direction is not "
120  "backward. Please set dock direction to backward."};
121  }
122 
123  // Setup filter
124  external_detection_rotation_.setRPY(roll, pitch, yaw);
125  filter_ = std::make_unique<PoseFilter>(filter_coef, external_detection_timeout_);
126 
127  if (!detector_service_name_.empty()) {
128  detector_client_ = node_->create_client<std_srvs::srv::Trigger>(
129  detector_service_name_, false);
130  }
131 
132  if (use_stall_detection) {
133  is_stalled_ = false;
134  if (stall_joint_names_.size() < 1) {
135  RCLCPP_ERROR(node_->get_logger(), "stall_joint_names cannot be empty!");
136  }
137  joint_state_sub_ = node_->create_subscription<sensor_msgs::msg::JointState>(
138  "joint_states",
139  std::bind(&SimpleNonChargingDock::jointStateCallback, this, std::placeholders::_1),
141  }
142 
143  dock_pose_pub_ = node_->create_publisher<geometry_msgs::msg::PoseStamped>(
144  "dock_pose", nav2::qos::LatchedPublisherQoS());
145  filtered_dock_pose_pub_ = node_->create_publisher<geometry_msgs::msg::PoseStamped>(
146  "filtered_dock_pose", nav2::qos::LatchedPublisherQoS());
147  staging_pose_pub_ = node_->create_publisher<geometry_msgs::msg::PoseStamped>(
148  "staging_pose", nav2::qos::LatchedPublisherQoS());
149 }
150 
151 geometry_msgs::msg::PoseStamped SimpleNonChargingDock::getStagingPose(
152  const geometry_msgs::msg::Pose & pose, const std::string & frame)
153 {
154  // If not using detection, set the dock pose as the given dock pose estimate
155  if (!use_external_detection_pose_) {
156  // This gets called at the start of docking
157  // Reset our internally tracked dock pose
158  dock_pose_.header.frame_id = frame;
159  dock_pose_.pose = pose;
160  }
161 
162  // Compute the staging pose with given offsets
163  const double yaw = tf2::getYaw(pose.orientation);
164  geometry_msgs::msg::PoseStamped staging_pose;
165  staging_pose.header.frame_id = frame;
166  staging_pose.header.stamp = node_->now();
167  staging_pose.pose = pose;
168  staging_pose.pose.position.x += cos(yaw) * staging_x_offset_;
169  staging_pose.pose.position.y += sin(yaw) * staging_x_offset_;
170  tf2::Quaternion orientation;
171  orientation.setRPY(0.0, 0.0, yaw + staging_yaw_offset_);
172  staging_pose.pose.orientation = tf2::toMsg(orientation);
173 
174  // Publish staging pose for debugging purposes
175  staging_pose_pub_->publish(std::make_unique<geometry_msgs::msg::PoseStamped>(staging_pose));
176  return staging_pose;
177 }
178 
179 bool SimpleNonChargingDock::getRefinedPose(geometry_msgs::msg::PoseStamped & pose, std::string)
180 {
181  // If using not detection, set the dock pose to the static fixed-frame version
182  if (!use_external_detection_pose_) {
183  dock_pose_pub_->publish(std::make_unique<geometry_msgs::msg::PoseStamped>(pose));
184  dock_pose_ = pose;
185  return true;
186  }
187 
188  // Guard against using pose data before the first detection has arrived.
189  if (!initial_pose_received_) {
190  RCLCPP_WARN(node_->get_logger(), "Waiting for first detected_dock_pose; none received yet");
191  return false;
192  }
193 
194  // If using detections, get current detections, transform to frame, and apply offsets
195  geometry_msgs::msg::PoseStamped detected = detected_dock_pose_;
196 
197  // Validate that external pose is new enough
198  auto timeout = rclcpp::Duration::from_seconds(external_detection_timeout_);
199  if (node_->now() - detected.header.stamp > timeout) {
200  RCLCPP_WARN(node_->get_logger(), "Lost detection or did not detect: timeout exceeded");
201  return false;
202  }
203 
204  // Transform detected pose into fixed frame. Note that the argument pose
205  // is the output of detection, but also acts as the initial estimate
206  // and contains the frame_id of docking
207  if (detected.header.frame_id != pose.header.frame_id) {
208  try {
209  if (rclcpp::Time(detected.header.stamp).nanoseconds() == 0) {
210  RCLCPP_ERROR_ONCE(node_->get_logger(),
211  "Provided a detection pose without a timestamp, unexpected");
212  }
213  geometry_msgs::msg::TransformStamped frame_transform = tf2_buffer_->lookupTransform(
214  pose.header.frame_id, detected.header.frame_id,
215  detected.header.stamp, rclcpp::Duration::from_seconds(0.2));
216  tf2::doTransform(detected, detected, frame_transform);
217  } catch (const tf2::TransformException & ex) {
218  RCLCPP_WARN(node_->get_logger(), "Failed to transform detected dock pose");
219  return false;
220  }
221  }
222 
223  // Filter the detected pose
224  detected = filter_->update(detected);
225  filtered_dock_pose_pub_->publish(std::make_unique<geometry_msgs::msg::PoseStamped>(detected));
226 
227  // Rotate the just the orientation, then remove roll/pitch
228  geometry_msgs::msg::PoseStamped just_orientation;
229  just_orientation.pose.orientation = tf2::toMsg(external_detection_rotation_);
230  geometry_msgs::msg::TransformStamped transform;
231  transform.transform.rotation = detected.pose.orientation;
232  tf2::doTransform(just_orientation, just_orientation, transform);
233 
234  tf2::Quaternion orientation;
235  orientation.setRPY(0.0, 0.0, tf2::getYaw(just_orientation.pose.orientation));
236  dock_pose_.pose.orientation = tf2::toMsg(orientation);
237 
238  // Construct dock_pose_ by applying translation/rotation
239  dock_pose_.header = detected.header;
240  dock_pose_.pose.position = detected.pose.position;
241  const double yaw = tf2::getYaw(dock_pose_.pose.orientation);
242  dock_pose_.pose.position.x += cos(yaw) * external_detection_translation_x_ -
243  sin(yaw) * external_detection_translation_y_;
244  dock_pose_.pose.position.y += sin(yaw) * external_detection_translation_x_ +
245  cos(yaw) * external_detection_translation_y_;
246  dock_pose_.pose.position.z = 0.0;
247 
248  // Publish & return dock pose for debugging purposes
249  dock_pose_pub_->publish(std::make_unique<geometry_msgs::msg::PoseStamped>(dock_pose_));
250  pose = dock_pose_;
251  return true;
252 }
253 
254 bool SimpleNonChargingDock::isDocked()
255 {
256  if (joint_state_sub_) {
257  // Using stall detection
258  return is_stalled_;
259  }
260 
261  if (dock_pose_.header.frame_id.empty()) {
262  // Dock pose is not yet valid
263  return false;
264  }
265 
266  // The latest base transform represents the current robot position, so reject
267  // stale dynamic TF before using its translation to decide whether we are docked.
268  geometry_msgs::msg::PoseStamped base_pose;
269  if (!nav2_util::getFreshPose(
270  *tf2_buffer_, dock_pose_.header.frame_id, base_frame_id_, node_->now(),
271  transform_staleness_threshold_, base_pose))
272  {
273  return false;
274  }
275 
276  // If we are close enough, we are docked
277  double d = std::hypot(
278  base_pose.pose.position.x - dock_pose_.pose.position.x,
279  base_pose.pose.position.y - dock_pose_.pose.position.y);
280  return d < docking_threshold_;
281 }
282 
283 void SimpleNonChargingDock::jointStateCallback(
284  const sensor_msgs::msg::JointState::ConstSharedPtr & state)
285 {
286  double velocity = 0.0;
287  double effort = 0.0;
288  for (size_t i = 0; i < state->name.size(); ++i) {
289  for (auto & name : stall_joint_names_) {
290  if (state->name[i] == name) {
291  // Tracking this joint
292  velocity += abs(state->velocity[i]);
293  effort += abs(state->effort[i]);
294  }
295  }
296  }
297 
298  // Take average
299  effort /= stall_joint_names_.size();
300  velocity /= stall_joint_names_.size();
301 
302  is_stalled_ = (velocity < stall_velocity_threshold_) && (effort > stall_effort_threshold_);
303 }
304 
305 bool SimpleNonChargingDock::startDetectionProcess()
306 {
307  // Skip if already active
308  if (detection_active_) {
309  return true;
310  }
311 
312  // 1. Service START request
313  if (detector_client_) {
314  auto req = std::make_shared<std_srvs::srv::Trigger::Request>();
315  try {
316  auto future = detector_client_->invoke(
317  req,
318  std::chrono::duration_cast<std::chrono::nanoseconds>(
319  std::chrono::duration<double>(detector_service_timeout_)));
320 
321  if (!future || !future->success) {
322  RCLCPP_ERROR(
323  node_->get_logger(), "Detector service '%s' failed to start.",
324  detector_service_name_.c_str());
325  return false;
326  }
327  } catch (const std::exception & e) {
328  RCLCPP_ERROR(
329  node_->get_logger(), "Calling detector service '%s' failed: %s",
330  detector_service_name_.c_str(), e.what());
331  return false;
332  }
333  }
334 
335  // 2. Subscription toggle
336  // Only subscribe once; will set state to ON on first message
337  if (subscribe_toggle_ && !dock_pose_sub_) {
338  dock_pose_sub_ = node_->create_subscription<geometry_msgs::msg::PoseStamped>(
339  "detected_dock_pose",
340  [this](const geometry_msgs::msg::PoseStamped::ConstSharedPtr & pose) {
341  detected_dock_pose_ = *pose;
342  initial_pose_received_ = true;
343  },
345  }
346 
347  detection_active_ = true;
348  RCLCPP_INFO(node_->get_logger(), "External detector activation requested.");
349  return true;
350 }
351 
352 bool SimpleNonChargingDock::stopDetectionProcess()
353 {
354  // Skip if already OFF
355  if (!detection_active_) {
356  return true;
357  }
358 
359  // 1. Service STOP request
360  if (detector_client_) {
361  auto req = std::make_shared<std_srvs::srv::Trigger::Request>();
362  try {
363  auto future = detector_client_->invoke(
364  req,
365  std::chrono::duration_cast<std::chrono::nanoseconds>(
366  std::chrono::duration<double>(detector_service_timeout_)));
367 
368  if (!future || !future->success) {
369  RCLCPP_ERROR(
370  node_->get_logger(), "Detector service '%s' failed to stop.",
371  detector_service_name_.c_str());
372  return false;
373  }
374  } catch (const std::exception & e) {
375  RCLCPP_ERROR(
376  node_->get_logger(), "Calling detector service '%s' failed: %s",
377  detector_service_name_.c_str(), e.what());
378  return false;
379  }
380  }
381 
382  // 2. Unsubscribe to release resources
383  // reset() will tear down the topic subscription immediately
384  if (subscribe_toggle_ && dock_pose_sub_) {
385  dock_pose_sub_.reset();
386  }
387 
388  detection_active_ = false;
389  initial_pose_received_ = false;
390  RCLCPP_INFO(node_->get_logger(), "External detector deactivation requested.");
391  return true;
392 }
393 
394 void SimpleNonChargingDock::activate()
395 {
396  dock_pose_pub_->on_activate();
397  filtered_dock_pose_pub_->on_activate();
398  staging_pose_pub_->on_activate();
399 }
400 
401 void SimpleNonChargingDock::deactivate()
402 {
403  stopDetectionProcess();
404  dock_pose_pub_->on_deactivate();
405  filtered_dock_pose_pub_->on_deactivate();
406  staging_pose_pub_->on_deactivate();
407  RCLCPP_DEBUG(node_->get_logger(), "SimpleNonChargingDock deactivated");
408 }
409 
410 void SimpleNonChargingDock::cleanup()
411 {
412  detector_client_.reset();
413  dock_pose_sub_.reset();
414  detection_active_ = false;
415  initial_pose_received_ = false;
416  RCLCPP_DEBUG(node_->get_logger(), "SimpleNonChargingDock cleaned up");
417 }
418 
419 } // namespace opennav_docking
420 
421 #include "pluginlib/class_list_macros.hpp"
A QoS profile for latched, reliable topics with a history of 1 messages.
A QoS profile for standard reliable topics with a history of 10 messages.
Abstract interface for a charging dock for the docking framework.