# [rospy] suscriber: run a callback once using rospy.spin

cduguet
32 8 10 14

Hi,

I am sorry if I am not using the proper words when I refer to "run a callback function" from a subscriber while using rospy. I'm not sure I got the concept of keeping the nodes sleeping. However, this is not my question.

I want to make a logger node node which takes data from the first message received in a topic, and writes it as a header in a file. Then it will be storing the raw data as long as rospy.spin() says so. The problem is, I have not found an example of how to do this, or if there is such a function. All I can think about are pretty cluttered solutions, which take the time stamp and compares them in every message.

my question is, is there a way to call

rospy.Subscriber("Flow", OpticalFlow2D.msg.FrameFlow, callbackOF)

many times and

rospy.Subscriber("Flow", OpticalFlow2D.msg.FrameFlow, callbackOFonce)

just on the first time, to write the header?

Many thanks,

Cristian

edit retag close delete

Sort by » oldest newest most voted

Dan Lazewatsky
4399 31 57 97
http://web.engr.oregonsta...

If you want a particular callback for a topic only to be run for the first message received, you can unsubscribe from within the callback after you've finished your processing. For example:

def cb_once(msg, subscriber):
#do processing here
subscriber.unregister()

sub_once = None
sub_once = rospy.Subscriber('my_topic,', MyType, cb_once, sub_once)


In your case, however, you could have a single callback, and just keep a flag around like wrote_header, which you can set to true after the first message was received so you only write the header once.

more

The above may not be entirely correct. The callback args may have to be an iterable, so the line would be sub_once = rospy.Subscriber('my_topic,', MyType, cb_once, [sub_once])

( 2012-03-27 11:54:38 -0500 )edit

cduguet
32 8 10 14

Thank you!

I did it using a flag, because (I don't know why it doesn't work, because it usually does to me) the callback function does not get the argument sub_once, therefore throwing the error "cb_once needs exactly two arguments", and it is being given one (I don't know why it is not passing the argument, and yes, sub_once is given after the callback function name just as you wrote it).

Anyway, with the flags the problem is solved.

Thank you!

more