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

When is it safe to publish after declaring a rospy.Publisher?

asked 2013-12-05 16:55:39 -0600

joq gravatar image

updated 2013-12-06 06:04:34 -0600

I recently had a problem on Hydro with publishing a message to a topic I had recently declared. The logic looked like:

self.pub = rospy.Publisher(self.pub_topic, SchedulerRequests)
self.pub.publish(msg)

The message does not appear. But, if I wait a tenth of a second, it works:

self.pub = rospy.Publisher(self.pub_topic, SchedulerRequests)
rospy.sleep(0.1)
self.pub.publish(msg)

The Tutorial has a call to rospy.ros_init() between the Publisher() and publish() calls. That does not work for the class I am writing, because ros_init() was called earlier in the main program.

Is there a safe way to check that self.pub is ready to send messages?

Clarification: the subscriber(s) are already up and running. My problem is that unless I wait a while, no message gets sent.

How do I determine that my own Publish object is ready to use?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2013-12-06 05:45:11 -0600

Dirk Thomas gravatar image

updated 2013-12-06 05:45:40 -0600

The not satisfying answer is: you don't know. ROS does not provide any mechanism to decide when all potential subscribers have established a connection with your publisher.

You could sleep (as you already suggested) for an unknown amount of time or check the number of current subscribers but actually your node should neither know now care about that. So the recommended way is to write your publish/subscribe application in a way that it can handle this.

If you want to just send one message (e.g. announce a configuration or something similar) you might want to use a latched topic. Every future subscribe will then receive the latest published message.

edit flag offensive delete link more

Comments

Sorry that my question was unclear, Dirk. I am not concerned with the behavior of other nodes. This problem is internal to my sender.

joq gravatar image joq  ( 2013-12-06 06:06:03 -0600 )edit

It takes some time for all subscribers to actually establish a connection to your new publisher. For you 0.1 seconds might be enough on a local machine if all subscribers are already running but that is not generally the case.

Dirk Thomas gravatar image Dirk Thomas  ( 2013-12-06 06:18:29 -0600 )edit

Yes, the time delay is not an adequate solution. But, `latch=True` seems to close the timing window and causes no harm that I can see. Thanks for the hint, Dirk.

joq gravatar image joq  ( 2013-12-06 06:44:02 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2013-12-05 16:55:39 -0600

Seen: 1,853 times

Last updated: Dec 06 '13