이번에는 파이썬을 통해서 토픽을 발행하고 구독해보자.
참고한 링크는 다음과 같다.
https://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28python%29
C++ 패키지의 경우 src 폴더에 노드를 작성해서 실행하였지만, 파이썬 패키지의 경우 scripts 폴더를 생성한 다음에 거기에 노드(소스코드)를 작성하게 된다.
$ cd catkin_ws/src/beginner_tutorials
$ mkdir -p scripts
$ wget https://raw.github.com/ros/ros_tutorials/noetic-devel/rospy_tutorials/001_talker_listener/talker.py
$ chmod +x talker.py
$ wget https://raw.github.com/ros/ros_tutorials/noetic-devel/rospy_tutorials/001_talker_listener/listener.py
$ chmod +x listener.py
import rospy # ROS에서 파이썬 사용하기, ros/ros.h와 같은 역할
from std_msgs.msg import String # include "std_msgs/String.h"와 같은 역할
def talker():
pub = rospy.Publisher('chatter', String, queue_size=10) # 퍼블리셔 선언
rospy.init_node('talker', anonymous=True) #노드 초기화 하기
rate = rospy.Rate(10) # 10hz , 발행 주기 작성하기
while not rospy.is_shutdown(): # 노드가 살아있는 한, 반복문 실행하기
hello_str = "hello world %s" % rospy.get_time()
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
import rospy # ROS 불러오기
from std_msgs.msg import String # std_msgs의 String 사용하겠다는 의미
def callback(data):
rospy.loginfo(rospy.get_caller_id() + 'I heard %s', data.data)
# 데이터 수신시 사용하는 콜백 함수
def listener():
rospy.init_node('listener', anonymous=True)
# anonymous=True 옵션은, 해당 노드에 고유한 식별자를 부여한다는 뜻이다.
# ROS에서 이름이 중복되면 이전 노드가 강제 종료된다.
# 해당 옵션은 이름이 같더라도 식별자를 다르게 해서, 동시에 사용 가능하게 한다.
rospy.Subscriber('chatter', String, callback)
# 수신하고, 콜백을 실행한다.
# 노드 실행
rospy.spin()
if __name__ == '__main__':
listener()
여기까지 따라왔으면, 한가지만 특별한 처리를 추가하면 파이썬 파일을 사용할 수 있다. 바로, CMakeLists.txt에 다음 내용을 추가하는 것이다.
catkin_install_python(PROGRAMS scripts/talker.py scripts/listener.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
위 내용은 CMake에서 파이썬 패키지를 빌드할 수 있도록 해주는 명령어이다. 파이썬 패키지를 만들 때는 위 코드를 참고하여, 해당 내용에 맞는 catkin_install_python() 함수를 꼭 작성할 수 있도록 하자.
그런 다음에 다음 절차를 거치면 된다.
// 1번째 터미널
$ roscore
// 2번째 터미널
// 처음이라면
$ cd catkin_ws
$ catkin_make
$ source devel/setup.bash
$ rosrun beginner_tutorials talker.py
// 3번째 터미널
$ cd catkin_ws && source devel/setup.bash
$ rosrun beginner_tutorials listener.py
파이썬 파일을 실행할 때는 뒤에 .py 확장자를 붙여줘야 하는 것을 반드시 기억하고 있어야 한다.