#!/usr/bin/env python
import rospy
from std_msgs.msg import String
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
코드가 어떻게 구성되어 있는지 분석해보자.
#!/usr/bin/env python
python 스크립트 시작시 꼭 필요하다. 이 줄은 이 스크립트가 실행 되는 장치에서 python이 설치된 위치에 영향을 받 않고, python의 위치를 동적으로 찾아 실행하겠다는 것이다.
import rospy
ros 노드 작성을 python으로 작성하기 위한 필수 라이브러리이다. rospy를 통해 ROS Topics , Services 및 Parameters를 python으로 접근 가능하다. 다양한 ros도구들이 rospy를 기반으로 구축되었다. (rostopic, rosservice 등등)
from std_msgs.msg import String
std_msgs/String의 메세지(mesage, 노드간의 데이터를 주고받을 떄 사용하는 데이터의 형태)를 사용하기 위함.
std_msgs - ROS Wiki
kinetic melodic noetic Show EOL distros: EOL distros: electric fuerte groovy hydro indigo jade lunar diamondback: Only showing information from the released package extracted on Unknown. No API documentation available. Please see this page for in
wiki.ros.org
def talker():
talker라는 이름의 함수시작
pub = rospy.Publisher('chatter', String, queue_size=10)
rospy.Publisher (topic_name, msg_class, queue_size)
rospy.Publisher의 인자를 살펴보면 chatter 라는 이름의 토픽에게 String(msg_class)를 publish하겠다고 큐(quere)사이즈를 10으로 선언하여 주었다.
rospy/Overview/Publishers and Subscribers
Publishing to a topic See also: rospy.Publisher Code API You can create a handle to publish messages to a topic using the rospy.Publisher class. The most common usage for this is to provide the name of the topic and the message class/type of the topic. You
roswiki.autolabor.com.cn
rospy.init_node('talker', anonymous=True)
프로세스에 대한 노드 초기화를 진행한다. ros master와 통신을 시작하기 위해 rospy에 사용하는 코드의 고유한 이름을 알려주어야 한다. 이게 없다면 master와는 통신이 시작 되지 않는다. anonymous=True 이므로 노드 이름 끝에 임의의 숫자가 추가되어 고유한 이름으로 재생성 된다. 만약 ros 그래프에서 이름이 같은 노드가 두개라면 먼저 생성된 노드가 종료된다.
std_msgs - ROS Wiki
kinetic melodic noetic Show EOL distros: EOL distros: electric fuerte groovy hydro indigo jade lunar diamondback: Only showing information from the released package extracted on Unknown. No API documentation available. Please see this page for in
wiki.ros.org
rate = rospy.Rate(10) # 10hz
rate라는 변수에 rospy.Rate(10)이라는 값을 넣는다. (루프를 10hz로 유지한다.) 이건 뒤에 rate.sleep()에서 계속 반복해주기 위해 넣어 준 코드이다.
rospy/Overview/Time - ROS Wiki
Time and Duration ROS has builtin time and duration primitive types, which rospy provides as the rospy.Time and rospy.Duration classes, respectively. A Time is a specific moment (e.g. "today at 5pm") whereas a Duration is a period of time (e.g. "5 hours").
wiki.ros.org
*while not rospy.is_shutdown(): *
rospy.is_shutdown()의 값을 확인하며 while문을 돌리겠다는 뜻이다. 종료되지 않았다면 아래 코드를 반복해서 실행한다. *rospy.init_node('talker', anonymous=True)에서의 링크를 함께 참고하면 좋을 것 같다. *
hello_str = "hello world %s" % rospy.get_time()
rospy.get_time()에서 받아온 시간정보를 hello world라는 문자에 붙여서 hello_str이라는 이름의 변수에 저장한다.
rospy.get_time()에 대한 설명은 위에 설명한 rate = rospy.Rate(10) # 10hz <- 의 설명링크를 참고하여 더 자세히 알아보면 좋을 것 같다.
rospy.loginfo(hello_str)
hello_str라는 변수의 값을 다음과 같이 3가지에 각각 뿌려준다.
1. 터미널 화면에 프린트
2. 노드의 log 파일에 기록
3. rosout에 기록
어떤 데이터가 출력되는지 보는 것과, log 파일과 rosout을 통해 디버깅을 진행하는데에 도움이 된다.
rate = rospy.Rate(10) # 10hz <- 의 설명링크를 참고하여 더 자세히 알아보면 좋을 것 같다.
pub.publish(hello_str)
hello_str에 기록된 변수의 값(string 형태)을 맨 처음 pub = rospy.Publisher('chatter', String, queue_size=10) 에서 선언 한 내용대로 chatter라는 이름의 topic에 Publish 하겠다는 것이다.
rate.sleep()
위에서 설정한 rate라는 변수를 통해 지정된 기간동안 휴면상태가 되어 루프의 속도를 유지한다. 노드 종료시 rospy.ROSInterruptException 를 발생시킨다.
if __name__ == '__main__':
여기 이하는 python의 기본문법이므로 pass
'개발관련 > ROS' 카테고리의 다른 글
rosserial esp8266 wifi통신(tcp) (7) | 2021.01.28 |
---|---|
[ROS] 간단한 Publisher과 Subscriber 예제(python) (11) | 2021.01.22 |
WSL2 에서 Publickey error 발생시 (0) | 2021.01.02 |
WSL2로 윈도우10에서 ROS 설치하기 (2) | 2021.01.01 |
[ROS] ubuntu 18.04에 ROS Melodic 설치하기(PC) (1) | 2020.05.25 |