Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
speed_filter.cpp
1 /*********************************************************************
2  *
3  * Software License Agreement (BSD License)
4  *
5  * Copyright (c) 2020 Samsung Research Russia
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * * Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  * * Redistributions in binary form must reproduce the above
15  * copyright notice, this list of conditions and the following
16  * disclaimer in the documentation and/or other materials provided
17  * with the distribution.
18  * * Neither the name of the <ORGANIZATION> nor the names of its
19  * contributors may be used to endorse or promote products derived
20  * from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  *
35  * Author: Alexey Merzlyakov
36  *********************************************************************/
37 
38 #include "nav2_costmap_2d/costmap_filters/speed_filter.hpp"
39 
40 #include <cmath>
41 #include <utility>
42 #include <memory>
43 #include <string>
44 
45 #include "nav2_costmap_2d/costmap_filters/filter_values.hpp"
46 #include "nav2_util/occ_grid_utils.hpp"
47 
48 namespace nav2_costmap_2d
49 {
50 
52 : filter_info_sub_(nullptr), mask_sub_(nullptr),
53  speed_limit_pub_(nullptr), filter_mask_(nullptr), global_frame_(""),
54  speed_limit_(NO_SPEED_LIMIT), speed_limit_prev_(NO_SPEED_LIMIT)
55 {
56 }
57 
59  const std::string & filter_info_topic)
60 {
61  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
62 
63  nav2::LifecycleNode::SharedPtr node = node_.lock();
64  if (!node) {
65  throw std::runtime_error{"Failed to lock node"};
66  }
67 
68  // Declare "speed_limit_topic" parameter specific to SpeedFilter only
69  std::string speed_limit_topic;
70  declareParameter("speed_limit_topic", rclcpp::ParameterValue("speed_limit"));
71  node->get_parameter(name_ + "." + "speed_limit_topic", speed_limit_topic);
72  speed_limit_topic = joinWithParentNamespace(speed_limit_topic);
73 
74  filter_info_topic_ = joinWithParentNamespace(filter_info_topic);
75  // Setting new costmap filter info subscriber
76  RCLCPP_INFO(
77  logger_,
78  "SpeedFilter: Subscribing to \"%s\" topic for filter info...",
79  filter_info_topic_.c_str());
80  filter_info_sub_ = node->create_subscription<nav2_msgs::msg::CostmapFilterInfo>(
82  std::bind(&SpeedFilter::filterInfoCallback, this, std::placeholders::_1),
84 
85  // Get global frame required for speed limit publisher
86  global_frame_ = layered_costmap_->getGlobalFrameID();
87 
88  // Create new speed limit publisher
89  speed_limit_pub_ = node->create_publisher<nav2_msgs::msg::SpeedLimit>(
90  speed_limit_topic);
91  speed_limit_pub_->on_activate();
92 
93  // Reset speed conversion states
94  base_ = BASE_DEFAULT;
95  multiplier_ = MULTIPLIER_DEFAULT;
96  percentage_ = false;
97 }
98 
99 void SpeedFilter::filterInfoCallback(
100  const nav2_msgs::msg::CostmapFilterInfo::SharedPtr msg)
101 {
102  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
103 
104  nav2::LifecycleNode::SharedPtr node = node_.lock();
105  if (!node) {
106  throw std::runtime_error{"Failed to lock node"};
107  }
108 
109  if (!mask_sub_) {
110  RCLCPP_INFO(
111  logger_,
112  "SpeedFilter: Received filter info from %s topic.", filter_info_topic_.c_str());
113  } else {
114  RCLCPP_WARN(
115  logger_,
116  "SpeedFilter: New costmap filter info arrived from %s topic. Updating old filter info.",
117  filter_info_topic_.c_str());
118  // Resetting previous subscriber each time when new costmap filter information arrives
119  mask_sub_.reset();
120  }
121 
122  // Set base_/multiplier_ or use speed limit in % of maximum speed
123  base_ = msg->base;
124  multiplier_ = msg->multiplier;
125  if (msg->type == SPEED_FILTER_PERCENT) {
126  // Using speed limit in % of maximum speed
127  percentage_ = true;
128  RCLCPP_INFO(
129  logger_,
130  "SpeedFilter: Using expressed in a percent from maximum speed"
131  "speed_limit = %f + filter_mask_data * %f",
132  base_, multiplier_);
133  } else if (msg->type == SPEED_FILTER_ABSOLUTE) {
134  // Using speed limit in m/s
135  percentage_ = false;
136  RCLCPP_INFO(
137  logger_,
138  "SpeedFilter: Using absolute speed_limit = %f + filter_mask_data * %f",
139  base_, multiplier_);
140  } else {
141  RCLCPP_ERROR(logger_, "SpeedFilter: Mode is not supported");
142  return;
143  }
144 
145  mask_topic_ = joinWithParentNamespace(msg->filter_mask_topic);
146 
147  // Setting new filter mask subscriber
148  RCLCPP_INFO(
149  logger_,
150  "SpeedFilter: Subscribing to \"%s\" topic for filter mask...",
151  mask_topic_.c_str());
152  mask_sub_ = node->create_subscription<nav_msgs::msg::OccupancyGrid>(
153  mask_topic_,
154  std::bind(&SpeedFilter::maskCallback, this, std::placeholders::_1),
156 }
157 
158 void SpeedFilter::maskCallback(
159  const nav_msgs::msg::OccupancyGrid::SharedPtr msg)
160 {
161  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
162 
163  if (!filter_mask_) {
164  RCLCPP_INFO(
165  logger_,
166  "SpeedFilter: Received filter mask from %s topic.", mask_topic_.c_str());
167  } else {
168  RCLCPP_WARN(
169  logger_,
170  "SpeedFilter: New filter mask arrived from %s topic. Updating old filter mask.",
171  mask_topic_.c_str());
172  filter_mask_.reset();
173  }
174 
175  filter_mask_ = msg;
176 }
177 
179  nav2_costmap_2d::Costmap2D & /*master_grid*/,
180  int /*min_i*/, int /*min_j*/, int /*max_i*/, int /*max_j*/,
181  const geometry_msgs::msg::Pose & pose)
182 {
183  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
184 
185  if (!filter_mask_) {
186  // Show warning message every 2 seconds to not litter an output
187  RCLCPP_WARN_THROTTLE(
188  logger_, *(clock_), 2000,
189  "SpeedFilter: Filter mask was not received");
190  return;
191  }
192 
193  geometry_msgs::msg::Pose mask_pose; // robot coordinates in mask frame
194 
195  // Transforming robot pose from current layer frame to mask frame
196  if (!transformPose(global_frame_, pose, filter_mask_->header.frame_id, mask_pose)) {
197  return;
198  }
199 
200  // Converting mask_pose robot position to filter_mask_ indexes (mask_robot_i, mask_robot_j)
201  unsigned int mask_robot_i, mask_robot_j;
202  if (!nav2_util::worldToMap(filter_mask_, mask_pose.position.x, mask_pose.position.y,
203  mask_robot_i, mask_robot_j))
204  {
205  return;
206  }
207 
208  // Getting filter_mask data from cell where the robot placed and
209  // calculating speed limit value
210  int8_t speed_mask_data = getMaskData(filter_mask_, mask_robot_i, mask_robot_j);
211  if (speed_mask_data == SPEED_MASK_NO_LIMIT) {
212  // Corresponding filter mask cell is free.
213  // Setting no speed limit there.
214  speed_limit_ = NO_SPEED_LIMIT;
215  } else if (speed_mask_data == SPEED_MASK_UNKNOWN) {
216  // Corresponding filter mask cell is unknown.
217  // Do nothing.
218  RCLCPP_ERROR(
219  logger_,
220  "SpeedFilter: Found unknown cell in filter_mask[%i, %i], "
221  "which is invalid for this kind of filter",
222  mask_robot_i, mask_robot_j);
223  return;
224  } else {
225  // Normal case: speed_mask_data in range of [1..100]
226  speed_limit_ = speed_mask_data * multiplier_ + base_;
227  if (percentage_) {
228  if (speed_limit_ < 0.0 || speed_limit_ > 100.0) {
229  RCLCPP_WARN(
230  logger_,
231  "SpeedFilter: Speed limit in filter_mask[%i, %i] is %f%%, "
232  "out of bounds of [0, 100]. Setting it to no-limit value.",
233  mask_robot_i, mask_robot_j, speed_limit_);
234  speed_limit_ = NO_SPEED_LIMIT;
235  }
236  } else {
237  if (speed_limit_ < 0.0) {
238  RCLCPP_WARN(
239  logger_,
240  "SpeedFilter: Speed limit in filter_mask[%i, %i] is less than 0 m/s, "
241  "which can not be true. Setting it to no-limit value.",
242  mask_robot_i, mask_robot_j);
243  speed_limit_ = NO_SPEED_LIMIT;
244  }
245  }
246  }
247 
248  if (speed_limit_ != speed_limit_prev_) {
249  if (speed_limit_ != NO_SPEED_LIMIT) {
250  RCLCPP_DEBUG(logger_, "SpeedFilter: Speed limit is set to %f", speed_limit_);
251  } else {
252  RCLCPP_DEBUG(logger_, "SpeedFilter: Speed limit is set to its default value");
253  }
254 
255  // Forming and publishing new SpeedLimit message
256  std::unique_ptr<nav2_msgs::msg::SpeedLimit> msg =
257  std::make_unique<nav2_msgs::msg::SpeedLimit>();
258  msg->header.frame_id = global_frame_;
259  msg->header.stamp = clock_->now();
260  msg->percentage = percentage_;
261  msg->speed_limit = speed_limit_;
262  speed_limit_pub_->publish(std::move(msg));
263 
264  speed_limit_prev_ = speed_limit_;
265  }
266 }
267 
269 {
270  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
271 
272  filter_info_sub_.reset();
273  mask_sub_.reset();
274  if (speed_limit_pub_) {
275  speed_limit_pub_->on_deactivate();
276  speed_limit_pub_.reset();
277  }
278 }
279 
281 {
282  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
283 
284  if (filter_mask_) {
285  return true;
286  }
287  return false;
288 }
289 
290 } // namespace nav2_costmap_2d
291 
292 #include "pluginlib/class_list_macros.hpp"
A QoS profile for latched, reliable topics with a history of 10 messages.
A 2D costmap provides a mapping between points in the world and their associated "costs".
Definition: costmap_2d.hpp:69
int8_t getMaskData(nav_msgs::msg::OccupancyGrid::ConstSharedPtr filter_mask, const unsigned int mx, const unsigned int my) const
Get the data of a cell in the filter mask.
bool transformPose(const std::string global_frame, const geometry_msgs::msg::Pose &global_pose, const std::string mask_frame, geometry_msgs::msg::Pose &mask_pose) const
: Transforms robot pose from current layer frame to mask frame
std::string filter_info_topic_
: Name of costmap filter info topic
std::string mask_topic_
: Name of filter mask topic
mutex_t * getMutex()
: returns pointer to a mutex
Abstract class for layered costmap plugin implementations.
Definition: layer.hpp:59
std::string joinWithParentNamespace(const std::string &topic)
Definition: layer.cpp:121
void declareParameter(const std::string &param_name, const rclcpp::ParameterValue &value)
Convenience functions for declaring ROS parameters.
Definition: layer.cpp:76
Reads in a speed restriction mask and enables a robot to dynamically adjust speed based on pose in ma...
void initializeFilter(const std::string &filter_info_topic)
Initialize the filter and subscribe to the info topic.
void resetFilter()
Reset the costmap filter / topic / info.
void process(nav2_costmap_2d::Costmap2D &master_grid, int min_i, int min_j, int max_i, int max_j, const geometry_msgs::msg::Pose &pose)
Process the keepout layer at the current pose / bounds / grid.
bool isActive()
If this filter is active.