[ROS] node간 동기화 문제

happy_quokka·2023년 10월 16일
0

ROS

목록 보기
16/25

1. sender_serial.py 작성

#!/usr/bin/env python

import rospy
from std_msgs.msg import Int32

rospy.init_node('sender_serial', anonymous=True)
pub = rospy.Publisher('my_topic', Int32)

rate = rospy.Rate(2)
count = 1

while not rospy.is_shutdown():
    pub.publish(count)
    print(count, " sended")
    count = count + 1
    rate.sleep()

2. receiver_serial.py 작성

#!/usr/bin/env python

import rospy
from std_msgs.msg import Int32

def callback(msg):
    print msg.data

rospy.init_node('msg_receiver', anonymous=True)
sub = rospy.Subscriber('my_topic', Int32, callback)
rospy.spin()

3. 권한 설정

$ chmod +x receiver_serial.py sender_serial.py 

4. 실행

t1 : roscore
t2 :rosrun msg_send receiver_serial.py
t3 : rosrun msg_send sender_serial.py

5. 결과 : sender는 1을 보냈지만 receiver에는 1이 나오지 않는다!!!

6. 왤까??(내 생각)

아마도... receiver와 sender가 서로 통신을 연결하는 과정에서 시간이 걸리고 그 사이에 sender가 값을 보냈기 때문에 1을 받지 못하는거 아닐까?

7. 해결방안(내 생각)

음... 서로 통신이 연결된 후부터 sender가 값을 보내기 시작한다면 해결될까??

8. 해결

sender_serial.py에 while(pub.get_num_connections() == 0): 추가

get_num_connections()
등록된 node의 수를 반환해주는 함수

#!/usr/bin/env python

import rospy
from std_msgs.msg import Int32

rospy.init_node('sender_serial', anonymous=True)
pub = rospy.Publisher('my_topic', Int32)

rate = rospy.Rate(2)
count = 1

while(pub.get_num_connections() == 0):
    count = 1

while not rospy.is_shutdown():
    pub.publish(count)
    print(count, " sended")
    count = count + 1
    rate.sleep()

1:3인 경우

sender_serial.py

#!/usr/bin/env python

import rospy
from std_msgs.msg import Int32

rospy.init_node('sender_serial', anonymous=True)
pub = rospy.Publisher('my_topic', Int32, queue_size=1)

rate = rospy.Rate(2)
count = 1

while(pub.get_num_connections() != 3):
    count=1

while not rospy.is_shutdown():
    pub.publish(count)
    print(count, " sended")
    count = count + 1
    rate.sleep()

receiver_serial.py

그대로

serial_1n.launch

<launch>
    <node pkg="msg_send" type="sender_serial.py" name="sender"/>
    <node pkg="msg_send" type="receiver_serial.py" name="receiver1" output="screen"/>
    <node pkg="msg_send" type="receiver_serial.py" name="receiver2" output="screen"/>
    <node pkg="msg_send" type="receiver_serial.py" name="receiver3" output="screen"/>
</launch>

결과

1부터 다 나온다!

0개의 댓글