I want to write two nodes such that each node sends a message alternatively in recurrent cycle and the message contains one string message and two age variables. For example, Node 1 sends a message to Node 2 (Node 1 Publisher, Node 2 Subscriber, node 1 age ++), then after receiving the message Node 2 sends the message back to Node 1 (Node 2 Publisher, Node 1 Subscriber, node 2 age ++) and this cycle continues. I am new to ROS, please help me to design this code in python or c++.
#!/usr/bin/env python
import rospy
from beginner_tutorials.msg import Num
def talker():
pub = rospy.Publisher('custom_Chat', Num,queue_size=1
)
rospy.init_node('custom_Node1', anonymous=True)
msg = Num()
msg.message = "Message sent to Node2"
msg.age1 =0
msg.age2=0
msg.flag=1
if msg.flag==1:
msg.age2+=1
print ("Hello! this is node 1!!")
rospy.loginfo(msg)
pub.publish(msg)
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException: pass
......................................................................................................................................................................
#!/usr/bin/env python
import rospy
from beginner_tutorials.msg import Num
def callback(data):
rospy.loginfo("Hello!this is node2")
rospy.loginfo("I heard the message %s. %d is my age." % (data.message, data.age2))
data.age1+=1
data.flag=2
def listener():
rospy.init_node('custom_Node2', anonymous=True)
rospy.Subscriber("custom_Chat", Num, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
listener()
Originally posted by user_123 on ROS Answers with karma: 23 on 2016-11-25
Post score: 0
Original comments
Comment by NEngelhard on 2016-11-25:
What do you achieve in the end? This looks like a heartbeat implementation to see if both nodes are alive, but there are easier ways to do that.
Comment by user_123 on 2016-11-25:
I was simply trying node1 to publish a messgae on "custom_chat" topic, and node 2 to receive it, but here, node 1 is publishing it but node2 isn't receiving
Comment by mgruhler on 2016-11-25:
Well, your custom_Node1
shuts down after having done one run. You have no subscriber in there, no callback.
Basically, take the listener node, add a publisher and publish the data from the callback. This should be all. Also, I'm not quite sure if this will work with the same topic. I don't know..
Comment by mgruhler on 2016-11-25:
.. if a node can "self-subscribe", so you are probably better of publishing/subscribing to different topics...
Comment by user_123 on 2016-11-28:
If possible, can you please modify the program and rewrite it for me using different topics and attach it as a link, I am getting puzzled after going midway...please help...