In ROS 2, messages can be accessed by "subscriber.LatestMessage" 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
0 件のコメント
採用された回答
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
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!