0
$\begingroup$

Rosanswers logo

Hi guys, I noticed following somehow strange behaviour. A topic subscriber is not ready to receive messages directly after its creation and needs some time until the first message can be received. The minimal example below illustrates this.

import rospy
from std_msgs.msg import String

def callback(data):
    rospy.loginfo("I heard %s",data.data)
    
rospy.init_node('node_name')

pub = rospy.Publisher('topic_name', String, queue_size=10)

sub = rospy.Subscriber("topic_name", String, callback)

pub.publish("no delay")

rospy.sleep(1)

pub.publish("with delay")

rospy.spin()

Results in:

[INFO] [1483456752.613187]: I heard with delay

I would expect:

[INFO] [1483457135.695501]: I heard no delay
[INFO] [1483457135.696547]: I heard with delay

Is this behaviour correct, as it is somehow understandable that it needs time to initialize the callback thread for the subscriber, or is it actually a bug? Does exist a better way to solve this issue instead of using rospy.sleep?


Originally posted by chrisLB on ROS Answers with karma: 46 on 2017-01-03

Post score: 0


Original comments

Comment by NEngelhard on 2017-01-03:
It's the normal behaviour. You can check for a listener with getNumSubscribers/Publishers. Could you also have a look at latched topics.

Comment by chrisLB on 2017-01-04:
Thank you for the valuable hint! I answered below.

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

The hint from @NEngelhard was correct, using the option latch=True results in what I had expected before. Thanks a lot!

import rospy
from std_msgs.msg import String

def callback(data):
    rospy.loginfo("I heard %s",data.data)

rospy.init_node('node_name')

pub = rospy.Publisher('topic_name', String, queue_size=10, latch=True) # working as expected
#pub = rospy.Publisher('topic_name', String, queue_size=10) # not working as expected

sub = rospy.Subscriber("topic_name", String, callback)

pub.publish("no delay")

rospy.sleep(1)

pub.publish("with delay")

rospy.spin()

Originally posted by chrisLB with karma: 46 on 2017-01-04

This answer was ACCEPTED on the original site

Post score: 1

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.