[ROS 튜토리얼] Python Publisher & Subscriber

Python Publisher & Subscriber

1. Publisher

  • my_publisher.py
#!/usr/bin/env python

import rospy
from std_msgs.msg import String

def my_publisher():
    pub=rospy.Publisher('/my_message', String, queue_size=10)
    rospy.init_node('first_publisher', anonymous=True)
    rate=rospy.Rate(5) # 5hz

    while not rospy.is_shutdown():
        pub_str = "hello world"
        pub.publish(pub_str)
        rate.sleep()

if __name__ == '__main__':
    try:
        my_publisher()
    except rospy.ROSInterruptException:
        pass

한 줄씩 코드를 분석해보겠다.

1 #!/usr/bin/env python # interpreter 경로
2
3 import rospy # ROS Node 작성 시 rospy를 import 해줘야 한다.
4 from std_msgs.msg import String # std_msgs/String message type을 publish하기위해 필요한 라인
5
6 def my_publisher():
7     pub=rospy.Publisher('/my_message', String, queue_size=10) # 작성한 노드가 my_message라는 String type의 topic message를 Publish할 것임을 선언한다.
8     rospy.init_node('first_publisher', anonymous=True) # rospy에 node이름을 알려주는 라인이다. 이를통해 ROS Master와 통신할 수 있게 된다.
9     rate=rospy.Rate(5) # rate라는 object를 생성한다. sleep method를 통해 1초에 5번 처리한다.
10
11    while not rospy.is_shutdown(): # ctrl+c가 입력되면 shutdown 된다.
12        pub_str = "hello world"
13        pub.publish(pub_str) # hello world라는 string을 publish한다.
14        rate.sleep() # 5hz
15
16    if __name__ == '__main__':
17        try:
18            my_publisher() 
19        except rospy.ROSInterruptException:
20            pass
  •  String message type

아래와 같이 field를 initialize할 수 있다.

str = "hello world"
msg = String()
msg.data = str

2. Subscriber

#!/usr/bin/env python

import rospy
from std_msgs.msg import String

def my_callback(data):
    rospy.loginfo("subscribing %s", data.data)

def my_subscriber():
    rospy.init_node('first_subscriber', anonymous=True)
    rospy.Subscriber("my_message", String, my_callback)
    rospy.spin()

if __name__ == '__main__':
    my_subscriber()

마찬가지로 한줄씩 분석해보자. publisher 예제코드와 유사하지만 callback기반 mechanism이 활용된다는 차이가 있다.

  • my_subscriber.py
1 #!/usr/bin/env python
2
3 import rospy
4 from std_msgs.msg import String
5
6 def my_callback(data):
7     rospy.loginfo("subscribing %s", data.data)
8
9 def my_subscriber():
10    rospy.init_node('first_subscriber', anonymous=True) # anonymous=True는 rospy가 unique한 node이름을 생성하도록 한다. 이에 my_subscriber.py를 여러개 가질 수 있게된다.
11    rospy.Subscriber("my_message", String, my_callback) # String type의 my_message라는 topic을 subscribe할 것임을 선언한다. 그리고 message를 받으면 이를 첫번째 argument로 넘겨주며 my_callback 함수를 호출한다.
12    rospy.spin() # shutdown되기 전까지 노드를 계속 유지시킨다.
13
14    if __name__ == '__main__':
15        my_subscriber()

3. reference

Leave a Reply

Your email address will not be published. Required fields are marked *