[ROS] 받은 토픽 가공해서 보내기

Nodazi·2024년 1월 5일
0

ROS

목록 보기
1/21
post-thumbnail

🤔0.개요

두 가지 노드가 통신을 할 때 받은 토픽을 가공하여 다시 토픽으로 보내는 실습을 진행한다.

💻1.코드구성

student_remoteteacher_remote 노드는 서로 Publisher, Subscriber 두가지 역할을 모두 가지고 있다.
student_remote 에서 자신의 인적사항이 담긴 메세지( my_msg 형태) 를 보내면 teacher_remote에서 이를 인지하고,
토픽을 분석하여 "Good Moring" + 이름 + 현재시간 의 메세지를 다시 student_remote 노드에 토픽을 보낸다.
코드는 아래와 같다.

🚀remote.launch

<launch>
	<node pkg = "msg_send" type = "remote_teacher.py" name = "teacher" output="screen"/>
	<node pkg = "msg_send" type = "remote_student.py" name = "student" output="screen"/>
</launch>

🐍teacher_remote.py

import rospy
from std_msgs.msg import String
from msg_send.msg import my_msg
from datetime import datetime

msg = "Good Morning"
return_name = ""
return_time = ""

def callback(msg) :
	global return_name, return_time
	return_name = msg.last_name + msg.first_name
	current_time = rospy.get_rostime()
	current_datetime = datetime.fromtimestamp(current_time.to_sec())
	formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
	return_time = str(formatted_time)
	pub.publish(msg + " " + return_name + " " +return_time)
    
rospy.init_node('teacher')
sub = rospy.Subscriber('msg_from_student', my_msg, callback)

pub = rospy.Publisher('msg_to_student', String)
rate = rospy.Rate(1)

rospy.spin()

🐍student_remote.py

import rospy  

from std_msgs.msg import String
from msg_send.msg import my_msg

def callback(msg):		
    print msg.data		
    
rospy.init_node('student')	

sub = rospy.Subscriber('msg_to_student', String, callback)	

msg = my_msg()
msg.first_name = "Gildong"
msg.last_name = "Hong"
msg.id_number = 20041003
msg.phone_number = "010-4545-4848"

pub = rospy.Publisher('msg_from_student', my_msg)
rate = rospy.Rate(1)

while not pub.get_num_connections() :
	pass

while not rospy.is_shutdown():
	pub.publish(msg)
	rate.sleep()

rospy.spin()

🖥️2.실행화면

remote 실행화면

노드에서 받은 토픽을 가공하여 다시 다른 토픽으로 보내지는 화면을 확인 할 수 있었다.

profile
GoGoSing

0개의 댓글

관련 채용 정보