ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Read data from ROS2 topic when I want to instead of callback

asked 2022-10-26 09:58:50 -0500

dvy gravatar image

Hi,

Currently, if a topic is published, in order to listen to the message, I create a subscriber and a callback function which gets called whenever there is a new message on the topic. Instead of this approach, is it possible to read data from a topic only when I want to? Or to call a function which can read data from topic only when I want it?

Thanks, Dev

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-10-26 10:52:34 -0500

Mike Scheutzow gravatar image

No, you can not. Both ros1 and ros2 use publish/subscribe style for topics.

However, you could easily mimic what you are asking for by using the subscribe callback to save the message in a variable (using an appropriate mutex if needed.) Then your code can "read" this variable any time you want to.

edit flag offensive delete link more

Comments

What about wait_for_message(..)?

That exists in both ROS 1 and ROS 2.

Technically, it still creates a subscription and just waits for a single msg, so conceptually that's no different from creating your own subscription, but it's essentially what the OP asks for.

See #q270298 and #q292582 for previous Q&As about this.

gvdhoorn gravatar image gvdhoorn  ( 2022-10-27 01:06:22 -0500 )edit

@gvdhoorn That would be quite inefficient for repeat use; it still uses a standard subscribe callback, and each "read" would take much longer as the ros node now has to communicate with the master plus has to wait for the next message to arrive.

Mike Scheutzow gravatar image Mike Scheutzow  ( 2022-10-27 06:45:02 -0500 )edit

For everything more than incidental use I would not recommend using it no. But that's also not the intended use-case. It's intended for things like capturing a single message from a topic in a service or action callback, or for initialising a "current state" kind of thing.

message_filters/Cache would be something you'd use to implement a proper version of "save the message in a variable [..] and read this [..] any time you want to".

gvdhoorn gravatar image gvdhoorn  ( 2022-10-27 06:54:06 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2022-10-26 09:58:50 -0500

Seen: 51 times

Last updated: Oct 26 '22