In ROS 2, messages can be accessed by "subscribe​r.LatestMe​ssage" but cannot be obtained via the MATLAB function "receive(subscriber, timeout)"

조회 수: 5 (최근 30일)
Hello everyone,
I am learning to use ROS 2 to communicate between agents. The problem I encountered is that the subscriber cannot receive any messages using the function receive() regardless how big the timeout I set, but in its property LatestMessage I can indeed see the latest message sent by the publisher.
I created a simple but complete example to showcase this:
% create ROS 2 nodes
node_1 = ros2node("/node_1");
node_2 = ros2node("/node_2");
pub = ros2publisher(node_1,"/topic_1","std_msgs/String"); % create publisher
msg = ros2message("std_msgs/String"); % create message structure
msg.data = 'Hello world';
ros2 topic list
ros2 node list
pause(2) % wait to ensure nodes and publisher are created
sub = ros2subscriber(node_2,"/topic_1"); % create subscriber
pause(2) % wait to ensure subscriber is created
send(pub,msg) % send message
pause(2)
disp(sub.LatestMessage) % message can be accessed in this way
[msg_received, status, statustext] = receive(sub,10) % but this way does not work
Any help would be appreciated.
(Note: I am using MATLAB R2022a in Windows 10 with version 21H2.)
Best,
Jianye Xu

채택된 답변

Prabeen Sahu
Prabeen Sahu 2022년 5월 18일
Hi Jianye Xu,
receive() blocks code execution until a new message is received by the subscriber, for the specific topic. If the subscriber does not receive a topic message and the timeout period elapses, the function displays error.
In your example when the publisher publishes the message using send(pub,msg), immediately subscriber gets that message. So sub.LatestMessage displays the latest message. At this point the message sent by the publisher is an older message for receive(). So receive(sub,10) waits for a new message and errors out after the timeout is elapsed.
You can get the latest published message using sub.LatestMessage. You can also make use of subscriber callbacks as mentioned in this example. Using callback function you can process the new messages as soon it is sent by the publisher and you can collect all the messages published.
-Prabeen
  댓글 수: 1
Jianye Xu
Jianye Xu 2022년 5월 18일
Hi Prabeen, thanks for the answer, which has corrected my understanding of the function receive(): only messages sent in a time interval defined by timeout would be received. If no message is sent in this time interval, it throws out an error.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 ROS Network Access in MATLAB에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by