我想创建两个相互通信的节点。我希望node1从node2接收信息并执行一些操作(例如,节点1和2中的信息总和),反之亦然。我该如何实现它?到目前为止,这是Node1的代码:
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def callback(msg):
print '%s' % msg.data
def nodo():
pub = rospy.Publisher('chatter1', String, queue_size=10)
rospy.init_node('nodo1', anonymous=True)
rospy.Subscriber('chatter2', String, callback)
rate = rospy.Rate(1) # 10hz
x = 5
while not rospy.is_shutdown():
for i in range(0,51):
pos1 = "%s" % (x)
pub.publish(pos1)
rate.sleep()
rospy.spin()
if __name__ == '__main__':
try:
nodo()
except rospy.ROSInterruptException:
pass
这是Node2的代码:
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def callback(msg):
print '%s' % msg.data
def nodo():
pub = rospy.Publisher('chatter2', String, queue_size=10)
rospy.init_node('nodo2', anonymous=True)
rospy.Subscriber('chatter1', String, callback)
rate = rospy.Rate(1) # 10hz
x2 = 4
while not rospy.is_shutdown():
for i in range(0,51):
pos2 = "%s" % (x2)
pub.publish(pos2)
rate.sleep()
rospy.spin()
if __name__ == '__main__':
try:
nodo()
except rospy.ROSInterruptException:
pass
答案 0 :(得分:0)
您的问题是node1
使用10的队列创建自己,但是node2
尝试将51个项目发送到该队列。 node2
将阻止node1
处理队列中的某些项目。问题是node1
同样被阻止了,因为它试图将51个项目发送到node2
。
廉价而愉快的工作环境是将队列大小设置为100.更好的解决方案是在队列中没有任何内容时不发送。
答案 1 :(得分:0)
为了对节点2发送的信息执行某些操作,您必须更改节点1中的订阅者回调。只要您收到消息,就会调用回调,只要您调用spin
。
您必须更改节点1,以便:
spin
(在您的代码中没有,它会卡在while
中)。import rospy
from std_msgs.msg import String
pub = None
def callback(msg):
x = int(msg.data)
pub.publish(str(x + 5))
def nodo():
global pub
rospy.init_node('nodo1', anonymous=True)
pub = rospy.Publisher('chatter1', String, queue_size=10)
rospy.Subscriber('chatter2', String, callback)
rospy.spin()
if __name__ == '__main__':
try:
nodo()
except rospy.ROSInterruptException:
pass