Ask Your Question
1

How to execute a ros callback just once

asked 2013-05-06 01:44:56 -0600

Oier gravatar image

updated 2016-10-24 08:59:25 -0600

ngrennan gravatar image

I want to subscribe to openni's "camera/rgb/camera_info" topic to get the camera matrix. Since the matrix doesn't change, I would like to execute the callback just once. How could I achieve this? Is the only way to unsubscribe? Or is it possible to use a ros service for this?

Regards,

Oier

edit retag flag offensive close merge delete

4 Answers

Sort by ยป oldest newest most voted
4

answered 2013-05-06 02:30:41 -0600

joq gravatar image

Since camera_info is published with every image frame, the simplest solution is to subscribe to it. In you message callback: collect the data, then unsubscribe.

It is possible your callback may run a few more times after you unsubscribe. Just to be safe, set a flag when you unsubscribe and return immediately if you get called again.

edit flag offensive delete link more

Comments

What is the reason for the callback running a few more times after unsubscribing?

2ROS0 gravatar image2ROS0 ( 2017-04-18 16:51:24 -0600 )edit
4

answered 2018-05-25 02:47:42 -0600

gvdhoorn gravatar image

I know this question has been answered by @joq, but that was quite some time ago.

Not sure when it was added, but I believe that ros::topic::waitForMessage(..) (api docs) is a much more elegant solution when only needing a single message.

This function takes care of everything that @joq suggests, ie: subscribing, waiting for a message and then unsubcribing immediately. The caller does not need to maintain any state him or herself (ie: no flag handling, no additional callbacks to ignore).

See #q270298 for an example that shows how to use ros::topic::waitForMessage(..).

edit flag offensive delete link more
1

answered 2013-05-06 02:07:27 -0600

davinci gravatar image

updated 2013-05-06 02:08:13 -0600

A service is better suited for this indeed but than you probably have to create a subscriber node which advertises this service. Perhaps you can also set a variable after the first time the callback is called that prevents executing of the other callback code.

edit flag offensive delete link more

Comments

1

A service only makes sense if both sides of the communication is nodes written by you. If the publisher is some other library then it wouldn't work.

2ROS0 gravatar image2ROS0 ( 2017-04-18 16:53:06 -0600 )edit
0

answered 2018-05-24 14:13:27 -0600

matwilso gravatar image

updated 2018-05-29 10:53:16 -0600

In rospy, the easiest way is to use (as gvdhoorn suggests):

msg = rospy.wait_for_message('/example_topic', ExampleMsg).

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-05-06 01:44:56 -0600

Seen: 1,870 times

Last updated: May 29 '18