[ROS] ROS 순서대로 실행

happy_quokka·2023년 10월 16일
0

ROS

목록 보기
8/25

ROS topic을 발행하고 이를 받을 때 여러 파일에서 topic을 발행한다면 topic이 뒤죽박죽으로 받아진다. 이를 원하는 순서대로 받기 위해 어떻게 해야하는지 실습해보았다.

1. 기존 방법

실행 파일들

receiver_order.py

#!/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()

sender_first.py

#!/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()

sr_order.launch

<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

실행

순서 뒤죽박죽이다아아아아ㅏㅏㅏㅏ


2. 순서대로 실행되도록 파일 수정

수정한 receiver

#!/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()

수정한 sender

#!/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()

결과

rostopic echo /start_node

rostopic echo /msg_to_receiver

roslaunch msg_send sr_order.launch

0개의 댓글