Why do I need a sleep before publishing first message to a topic?
I am trying to get an explanation for some code that works.
To simplify the general issue, I created a bag file with exactly 2 messages with exact same header time stamp down to nano seconds. First message is of type sensor_msgs/Image
. Second message is of type sensor_msgs/PointCloud2
. If I read the two messages from the ROS Bag and publish them using two publishers, one for each topic, as shown below, I can not see the messages in rviz
or rostopic echo
.
#The code below does not show messages in rviz or rostopic echo
# ros_publishers in the code below is a dict of ros topic name -> rospy.Publisher
bag = rosbag.Bag(bag_path)
for ros_topic, ros_msg, _ in bag.read_messages():
ros_publishers[ros_topic].publish(ros_msg)
bag.close()
However, if I add a minimum sleep for 1 second, just before I publish a message on a topic for the first time, it works.
# This code successfully shows messages in rviz and rostopic echo
# ros_publishers is a dict of ros topic name -> rospy.Publisher
bag = rosbag.Bag(bag_path)
ros_topics = set()
for ros_topic, ros_msg, _ in bag.read_messages():
if not ros_topic in ros_topics:
time.sleep(1)
ros_topics.add(ros_topic)
ros_publishers[ros_topic].publish(ros_msg)
bag.close()
This issue is a proxy for the real issue, which is that if number of messages in the Bag file is below a threshold (don't know the threshold), the code needs the sleep for first time message on a topic before the message shows up in rviz
or rostopic echo
. If the number of messages in the Bag file is a above this unknown threshold, then it works without any sleep.
Interestingly, using rosbag play
shows messages in rviz
even if there are just two messages in the Bag, but that may or may not be beside the point for the problem I am trying to solve. I can change the time.sleep(1)
to print(str(ros_msg))
and that does the trick also. Note, if I put the time.sleep(1)
anywhere else in the code, it does not work, and less than 1 second also does not work.
I have a solution (maybe a hack) that works for what I am trying to do, but I am requesting an explanation for why it works, or maybe I need to do something else.