Search code examples
ros

Why does the following code only publish a single ROS message?


The first call to publish() results in this message:

[DEBUG] [1707520305.010403219]: Trying to publish message of type [std_msgs/String/992ce8a1687cec8c8bd883ec73ca41d1] on a publisher with type [std_msgs/String/992ce8a1687cec8c8bd883ec73ca41d1]

Is this a known bug in ROS? For what its worth I am running ros noetic on Ubuntu 20.04.

I have verified that only one message gets published by running rostopic echo test_topic in another terminal.

#include <ros/ros.h>
#include <iostream>
#include "std_msgs/String.h"

int main(int argc, char *argv[])
{
  ros::init(argc, argv, "test_pub_node");
  ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug);
  ros::NodeHandle nh;
  auto pub = nh.advertise<std_msgs::String>("test_topic", 1);
  auto msg = boost::make_shared<std_msgs::String>();
  msg->data = "hello";
  
  usleep(1.0e6);
  pub.publish(msg);

  ros::spinOnce();

  usleep(1.0e6);
  pub.publish(msg);

  ros::spinOnce();

  return 0;
}

Solution

  • This issue was discussed for an older version of ROS at ROSwiki and it is not a bug. Re-writing the answer in short because ROSwiki is now read-only. The 1 seconds of sleep time between publisher setup and publishing a data is often not enough for the subscriber(rostopic echo) to start listening. If you want to listen to all messages with certainty, you have to wait until you see a subscriber(from the same source).

    while (0 == pub.getNumSubscribers()) {
          ROS_INFO("Waiting for subscribers to connect");
          ros::Duration(0.1).sleep();
    }