Publisher와 Subscriber간의 데이터 교환

김주형·2021년 7월 22일
0

ROS2

목록 보기
3/3
post-thumbnail

ROS2는 노드끼리 메시지를 주고 받을 수 있게 만들었습니다. ROS2 네트워크에서 메시지는 토픽으로써 전달되며, 각 토픽은 특정한 이름을 가지고 있습니다. 토픽은 반드시 Publisher에 의해 보내져야 하며 Subscriber에 의해 보내진 토픽을 받아야 합니다. 토픽에는 메시지 타입이 포함되어 있고, 메시지 타입 덕분에 원하는 데이터를 토픽에 담을 수 있습니다.

1. 메시지 보내기 그리고 기다리기

예제를 이용해서 ROS2 네트워크를 생성해 봅시다.

exampleHelperROS2CreateSampleNetwork

ros2 topic list를 이용해 어떤 토픽을 사용할 수 있는지 확인할 수 있습니다.

ros2 topic list


/scan 토픽을 보내봅시다. ros2subscriber를 사용해서 /scan 토픽을 보낼 수 있습니다. 토픽의 이름을 정하세요. 만약 ROS2 네트워크에 토픽이 이미 존재한다면, ros2subscriber는 메시지 타입을 자동으로 감지합니다.

detectNode = ros2node("/detection");
pause(2)
laserSub = ros2subscriber(detectNode,"/scan");
pause(2)


우측 작업 공간에 laserSub라는 Subscriber가 생성된 것을 볼 수 있습니다.
receive를 이용해 새 메시지를 받는 것을 기다릴 수 있습니다. 10초 동안 받도록 설정하세요. scanData의 출력은 받은 메시지 데이터를 포함하고 있습니다.
우측 작업 공간에서 scanData 변수를 더블 클릭하면 확인할 수 있습니다.

laserSub와 이와 관련된 노드들을 제거할 수 있습니다.

clear laserSub
clear detectNode

콜백 함수를 이용해 메시지 받기

receive를 이용해 데이터를 받는 대신 함수를 이용해 새로운 메시지를 받을 수 있습니다.
/pose 토픽을 발행하고 exampleHelperROS2PoseCallback라는 콜백 함로 받아봅시다. 주로 사용하는 작업공간과 호출 함수 간에는 global 변수를 통해 데이터를 나눌 수 있습니다. global 변수 pos와 orient를 정의해 봅시다.

controlNode = ros2node("/base_station");
poseSub = ros2subscriber(controlNode,"/pose",@exampleHelperROS2PoseCallback);
global pos
global orient

좌측 현재 폴더에 보면 exampleHelperROS2PoseCallback.m 파일로 이미 콜백 함수가 작성되어 있습니다.

function exampleHelperROS2PoseCallback(message)
    %exampleHelperROS2PoseCallback Subscriber callback function for pose data    
    %   exampleHelperROS2PoseCallback(MESSAGE) returns no arguments - it instead sets 
    %   global variables to the values of position and orientation that are
    %   received in the ROS 2 message MESSAGE.
    %   
    %   See also ROSPublishAndSubscribeExample.
    
    %   Copyright 2019 The MathWorks, Inc.
    
    % Declare global variables to store position and orientation
    global pos
    global orient
    
    % Extract position and orientation from the ROS message and assign the
    % data to the global variables.
    pos = [message.linear.x message.linear.y message.linear.z];
    orient = [message.angular.x message.angular.y message.angular.z];
end

받은 pos 데이터를 화면에 출력해 봅시다.

disp(pos)


orient도 출력해 봅시다.

disp(orient)


disp(pos)와 disp(orient)를 명령 줄에 입력할 때 마다 값이 바뀌는 것을 볼 수 있습니다. 이제 처음에 생성한 Subscriber와 노드들을 정리하세요.

clear poseSub
clear controlNode

메시지 전송하기

/chatter 토픽의 문자열를 보내기 위해 Publisher를 만들어 보세요.

chatterPub = ros2publisher(node_1,"/chatter","std_msgs/String");

그리고 /chatter 토픽에 메시지를 만들고 채웁니다.

chatterMsg = ros2message(chatterPub);
chatterMsg.data = 'hello world';

/chatter 토픽을 받기위한 Subcriber를 정의합시다. exampleHelperROS2ChatterCallback는 새로운 메시지를 받을 때 마다 호출되고 화면에 메시지 내용을 출력할 것입니다.

/chatter 토픽을 발행해 봅시다. 콜백 함수에 의해 문자열이 나타나는 것을 볼 수 있습니다.

profile
안녕하세요!

0개의 댓글