ROS topic을 발행하고 이를 받을 때 여러 파일에서 topic을 발행한다면 topic이 뒤죽박죽으로 받아진다. 이를 원하는 순서대로 받기 위해 어떻게 해야하는지 실습해보았다.
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
name = "receiver"
sub_topic = "msg_to_receiver"
def callback(msg):
print(msg.data)
rospy.init_node(name)
rospy.Subscriber(sub_topic, String, callback)
rospy.spin()
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
name = "first"
pub_topic = "msg_to_receiver"
rospy.init_node(name)
pub = rospy.Publisher(pub_topic, String, queue_size=1)
rate = rospy.Rate(2)
hello_str = String()
while not rospy.is_shutdown():
hello_str.data = "my name is "+name
pub.publish(hello_str)
rate.sleep()
<launch>
<node name="receiver" pkg="msg_send" type="receiver_order.py" output="screen" />
<node name="first" pkg="msg_send" type="sender_first.py" output="screen" />
<node name="second" pkg="msg_send" type="sender_second.py" output="screen" />
<node name="third" pkg="msg_send" type="sender_third.py" output="screen" />
<node name="fourth" pkg="msg_send" type="sender_fourth.py" output="screen" />
</launch>
cm (catkin_make) 명령어를 통해 빌드 수행
python 파일들이기 때문에 chmod를 통해 실행 권한을 주어야한다
$ chmod +x sender_first.py sender_second.py sender_third.py sender_fourth.py receiver_order.py
순서 뒤죽박죽이다아아아아ㅏㅏㅏㅏ
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
name = "receiver"
pub_topic = "start_node"
sub_topic = "msg_to_receiver"
def callback(msg):
rospy.loginfo("I heard %s", msg.data)
rospy.init_node(name)
rospy.Subscriber(sub_topic, String, callback)
pub = rospy.Publisher(pub_topic, String, queue_size=1)
rospy.sleep(1)
sq = ["first", "second", "third", "fourth"]
pub_msg = String()
for i in sq:
pub_msg.data = i+":go"
pub.publish(pub_msg)
rospy.sleep(2)
rospy.spin()
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
name = "first"
pub_topic = "msg_to_receiver"
sub_topic = "start_node"
OK = None
def callback(msg):
global OK
OK = str(msg.data)
rospy.init_node(name)
rospy.Subscriber(sub_topic, String, callback)
while True:
if OK == None:
continue
d = OK.split(":")
if(len(d) == 2) and (d[0] == name) and (d[1] == "go"):
break
pub = rospy.Publisher(pub_topic, String, queue_size=1)
rate = rospy.Rate(2)
hello_str = String()
while not rospy.is_shutdown():
hello_str.data = "my name is " + name
pub.publish(hello_str)
rate.sleep()