How does ROS knows which node is publishing?
I was looking at the beginner's Publisher node boilerplate code from the wiki and I was wondering:
How does ROS knows which node is the publisher of a message?
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
def talker():
pub = rospy.Publisher('chatter', String, queue_size=10)
rospy.init_node('talker', anonymous=True)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
hello_str = "hello world %s" % rospy.get_time()
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
I see the creation of a chatter
Topic and talker
node, so, how does pub.publish
knows which topic is publishing and if pub.publish
doesn't need to know, how does rosmaster knows?
What exactly do you want to know?
Your first question "how does ROS knows which node is the publisher" is about the client library. In this case this is
rospy
. Here the node is registered and also the publisher with the topic is registered. Eventually the master handles setting up the communication with nodes that have subscriptions on this topic.Your second question "how does
pub.publish
know to which topic it is publishing" is more straightforward. When the publisher is created, the topic is given as an argument and publisher object is stored in the variablepub
. When you callpub.publish
later on, the object still knows what its topic is.Dear Bonestroo,
If I was to create 2 nodes in the same py script:
with all other the same, which one would be the node publishing data?
Hi, Now I see your question. There can be only one node per python process. According to the documentation "You can only have one node in a rospy process, so you can only call rospy.init_node() once."