ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

For anyone looking for a cpp solution:

#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "rclcpp/generic_subscription.hpp"
#include "std_msgs/msg/string.hpp"
using std::placeholders::_1;

class MinimalSubscriber : public rclcpp::Node
{
  public:
    MinimalSubscriber()
    : Node("minimal_subscriber")
    {
      auto data = rclcpp::Node::get_topic_names_and_types();
      auto msg_type = data["/topic_name"];

      for(auto type : msg_type){
      std::cout << type  << std::endl;
      rclcpp::QoS qos = rclcpp::QoS(10);
      std::function<void(std::shared_ptr<rclcpp::SerializedMessage>)> call = std::bind(&MinimalSubscriber::topic_callback, this, _1);
      subscription_ = this->create_generic_subscription("/topic_name",type ,qos, call );
    }
     }

  private:
    void topic_callback(std::shared_ptr<rclcpp::SerializedMessage> msg)
    {
      RCLCPP_INFO(this->get_logger(), "I heard:");
    }
    std::shared_ptr<rclcpp::GenericSubscription> subscription_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<MinimalSubscriber>());
  rclcpp::shutdown();
  return 0;
}