Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
binary_filter.cpp
1 /*********************************************************************
2  *
3  * Software License Agreement (BSD License)
4  *
5  * Copyright (c) 2022 Samsung R&D Institute 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/binary_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_values.hpp"
47 #include "nav2_util/occ_grid_utils.hpp"
48 
49 namespace nav2_costmap_2d
50 {
51 
53 : filter_info_sub_(nullptr), mask_sub_(nullptr),
54  binary_state_pub_(nullptr), filter_mask_(nullptr), global_frame_(""),
55  default_state_(false), binary_state_(default_state_)
56 {
57 }
58 
60  const std::string & filter_info_topic)
61 {
62  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
63 
64  nav2::LifecycleNode::SharedPtr node = node_.lock();
65  if (!node) {
66  throw std::runtime_error{"Failed to lock node"};
67  }
68 
69  // Declare parameters specific to BinaryFilter only
70  default_state_ = node->declare_or_get_parameter(name_ + "." + "default_state", false);
71  std::string binary_state_topic = node->declare_or_get_parameter(name_ + "." +
72  "binary_state_topic", std::string("binary_state"));
73  flip_threshold_ = node->declare_or_get_parameter(name_ + "." + "flip_threshold", 50.0);
74 
75  filter_info_topic_ = filter_info_topic;
76  // Setting new costmap filter info subscriber
77  RCLCPP_INFO(
78  logger_,
79  "BinaryFilter: Subscribing to \"%s\" topic for filter info...",
80  filter_info_topic_.c_str());
81  filter_info_sub_ = node->create_subscription<nav2_msgs::msg::CostmapFilterInfo>(
83  std::bind(&BinaryFilter::filterInfoCallback, this, std::placeholders::_1),
85 
86  // Get global frame required for binary state publisher
87  global_frame_ = layered_costmap_->getGlobalFrameID();
88 
89  // Create new binary state publisher
90  binary_state_pub_ = node->create_publisher<std_msgs::msg::Bool>(
91  binary_state_topic);
92  binary_state_pub_->on_activate();
93 
94  // Reset parameters
95  base_ = BASE_DEFAULT;
96  multiplier_ = MULTIPLIER_DEFAULT;
97 
98  // Initialize state binary_state_ which at start its equal to default_state_
99  changeState(binary_state_);
100 }
101 
103  const nav2_msgs::msg::CostmapFilterInfo::ConstSharedPtr & msg)
104 {
105  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
106 
107  nav2::LifecycleNode::SharedPtr node = node_.lock();
108  if (!node) {
109  throw std::runtime_error{"Failed to lock node"};
110  }
111 
112  if (!mask_sub_) {
113  RCLCPP_INFO(
114  logger_,
115  "BinaryFilter: Received filter info from %s topic.", filter_info_topic_.c_str());
116  } else {
117  RCLCPP_WARN(
118  logger_,
119  "BinaryFilter: New costmap filter info arrived from %s topic. Updating old filter info.",
120  filter_info_topic_.c_str());
121  // Resetting previous subscriber each time when new costmap filter information arrives
122  mask_sub_.reset();
123  }
124 
125  if (msg->type != BINARY_FILTER) {
126  RCLCPP_ERROR(logger_, "BinaryFilter: Mode %i is not supported", msg->type);
127  return;
128  }
129 
130  // Set base_ and multiplier_
131  base_ = msg->base;
132  multiplier_ = msg->multiplier;
133  // Set topic name to receive filter mask from
134  mask_topic_ = msg->filter_mask_topic;
135 
136  // Setting new filter mask subscriber
137  RCLCPP_INFO(
138  logger_,
139  "BinaryFilter: Subscribing to \"%s\" topic for filter mask...",
140  mask_topic_.c_str());
141  mask_sub_ = node->create_subscription<nav_msgs::msg::OccupancyGrid>(
142  mask_topic_,
143  std::bind(&BinaryFilter::maskCallback, this, std::placeholders::_1),
145 }
146 
148  const nav_msgs::msg::OccupancyGrid::ConstSharedPtr & msg)
149 {
150  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
151 
152  if (!filter_mask_) {
153  RCLCPP_INFO(
154  logger_,
155  "BinaryFilter: Received filter mask from %s topic.", mask_topic_.c_str());
156  } else {
157  RCLCPP_WARN(
158  logger_,
159  "BinaryFilter: New filter mask arrived from %s topic. Updating old filter mask.",
160  mask_topic_.c_str());
161  filter_mask_.reset();
162  }
163 
164  filter_mask_ = msg;
165 }
166 
168  nav2_costmap_2d::Costmap2D & /*master_grid*/,
169  int /*min_i*/, int /*min_j*/, int /*max_i*/, int /*max_j*/,
170  const geometry_msgs::msg::Pose & pose)
171 {
172  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
173 
174  if (!filter_mask_) {
175  // Show warning message every 2 seconds to not litter an output
176  RCLCPP_WARN_THROTTLE(
177  logger_, *(clock_), 2000,
178  "BinaryFilter: Filter mask was not received");
179  return;
180  }
181 
182  geometry_msgs::msg::Pose mask_pose; // robot coordinates in mask frame
183 
184  // Transforming robot pose from current layer frame to mask frame
185  if (!transformPose(global_frame_, pose, filter_mask_->header.frame_id, mask_pose)) {
186  return;
187  }
188 
189  // Converting mask_pose robot position to filter_mask_ indexes (mask_robot_i, mask_robot_j)
190  unsigned int mask_robot_i, mask_robot_j;
191  if (!nav2_util::worldToMap(
192  filter_mask_, mask_pose.position.x, mask_pose.position.y,
193  mask_robot_i, mask_robot_j))
194  {
195  // Robot went out of mask range. Set "false" state by-default
196  RCLCPP_WARN(
197  logger_,
198  "BinaryFilter: Robot is outside of filter mask. Resetting binary state to default.");
199  changeState(default_state_);
200  return;
201  }
202 
203  // Getting filter_mask data from cell where the robot placed
204  int8_t mask_data = getMaskData(filter_mask_, mask_robot_i, mask_robot_j);
205  if (mask_data == nav2_util::OCC_GRID_UNKNOWN) {
206  // Corresponding filter mask cell is unknown.
207  // Warn and do nothing.
208  RCLCPP_WARN_THROTTLE(
209  logger_, *(clock_), 2000,
210  "BinaryFilter: Filter mask [%i, %i] data is unknown. Do nothing.",
211  mask_robot_i, mask_robot_j);
212  return;
213  }
214 
215  // Check and flip binary state, if necessary
216  if (base_ + mask_data * multiplier_ > flip_threshold_) {
217  if (binary_state_ == default_state_) {
218  changeState(!default_state_);
219  }
220  } else {
221  if (binary_state_ != default_state_) {
222  changeState(default_state_);
223  }
224  }
225 }
226 
228 {
229  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
230 
231  // Publishing new BinaryState ib reset
232  std::unique_ptr<std_msgs::msg::Bool> msg =
233  std::make_unique<std_msgs::msg::Bool>();
234  msg->data = binary_state_;
235  binary_state_pub_->publish(std::move(msg));
236 
237  filter_info_sub_.reset();
238  mask_sub_.reset();
239  if (binary_state_pub_) {
240  binary_state_pub_->on_deactivate();
241  binary_state_pub_.reset();
242  }
243 }
244 
246 {
247  std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
248 
249  if (filter_mask_) {
250  return true;
251  }
252  return false;
253 }
254 
255 void BinaryFilter::changeState(const bool state)
256 {
257  binary_state_ = state;
258  if (state) {
259  RCLCPP_INFO(logger_, "BinaryFilter: Switched on");
260  } else {
261  RCLCPP_INFO(logger_, "BinaryFilter: Switched off");
262  }
263 
264  // Forming and publishing new BinaryState message
265  std::unique_ptr<std_msgs::msg::Bool> msg =
266  std::make_unique<std_msgs::msg::Bool>();
267  msg->data = state;
268  binary_state_pub_->publish(std::move(msg));
269 }
270 
271 } // namespace nav2_costmap_2d
272 
273 #include "pluginlib/class_list_macros.hpp"
A QoS profile for latched, reliable topics with a history of 10 messages.
Reads in a speed restriction mask and enables a robot to dynamically adjust speed based on pose in ma...
void filterInfoCallback(const nav2_msgs::msg::CostmapFilterInfo::ConstSharedPtr &msg)
Callback for the filter information.
void changeState(const bool state)
Changes binary state of filter. Sends a message with new state.
void resetFilter() override
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) override
Process the keepout layer at the current pose / bounds / grid.
bool isActive()
If this filter is active.
void maskCallback(const nav_msgs::msg::OccupancyGrid::ConstSharedPtr &msg)
Callback for the filter mask.
void initializeFilter(const std::string &filter_info_topic) override
Initialize the filter and subscribe to the info topic.
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:60