Robotics StackExchange | Archived questions

[ROS2]: Get topic name inside of callback

Like in the ROS1 question listed here: https://answers.ros.org/question/68434/get-topic-name-in-callback/

For ROS2 (galactic) I'd like to use one callback for several messages of the same type, and I'd also like the callback to be aware of the topic that the message came from.

I'm using C++, and in my class definition I tried:

rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
subscription_ = this->create_subscription<std_msgs::msg::String>(
  "topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1,"topic"));

with:

void MinimalSubscriber::topic_callback(const std_msgs::msg::String::SharedPtr msg, const std::string& topic) 
{
  RCLCPP_INFO(this->get_logger(), "I heard: '%s' on topic '%s'", msg->data.c_str(), topic.c_str());
}

But clearly this is very wrong as I get the following error message:

/opt/ros/galactic/include/rclcpp/any_subscription_callback.hpp:185:25: error: no match for ‘operator=’ (operand types are ‘rclcpp::detail::AnySubscriptionCallbackHelper<std_msgs::msg::String_<std::allocator<void> >, std::allocator<void> >::variant_type’ {aka ‘std::variant<std::function<void(const std_msgs::msg::String_<std::allocator<void> >&)>, std::function<void(const std_msgs::msg::String_<std::allocator<void> >&, const rclcpp::MessageInfo&)>, std::function<void(std::unique_ptr<std_msgs::msg::String_<std::allocator<void> >, std::default_delete<std_msgs::msg::String_<std::allocator<void> > > >)>, std::function<void(std::unique_ptr<std_msgs::msg::String_<std::allocator<void> >, std::default_delete<std_msgs::msg::String_<std::allocator<void> > > >, const rclcpp::MessageInfo&)>, std::function<void(std::shared_ptr<const std_msgs::msg::String_<std::allocator<void> > >)>, std::function<void(std::shared_ptr<const std_msgs::msg::String_<std::allocator<void> > >, const rclcpp::MessageInfo&)>, std::function<void(const std::shared_ptr<const std_msgs::msg::String_<std::allocator<void> > >&)>, std::function<void(const std::shared_ptr<const std_msgs::msg::String_<std::allocator<void> > >&, const rclcpp::MessageInfo&)>, std::function<void(std::shared_ptr<std_msgs::msg::String_<std::allocator<void> > >)>, std::function<void(std::shared_ptr<std_msgs::msg::String_<std::allocator<void> > >, const rclcpp::MessageInfo&)> >’} and ‘rclcpp::detail::SubscriptionCallbackTypeHelper<std_msgs::msg::String_<std::allocator<void> >, std::_Bind<void (MinimalSubscriber::*(MinimalSubscriber*, std::_Placeholder<1>, const char*))(std::shared_ptr<std_msgs::msg::String_<std::allocator<void> > >, const std::__cxx11::basic_string<char>&)>, void>::callback_type’ {aka ‘std::function<void(std::shared_ptr<std_msgs::msg::String_<std::allocator<void> > >, const std::__cxx11::basic_string<char>&)>’})

Asked by gituser369 on 2023-02-21 15:06:11 UTC

Comments

Answers