Ask Your Question
0

How to make a server read the latest msg from a topic?

asked 2017-11-17 11:35:58 -0600

RobotWhisperer gravatar image

Greetings,
All I want to do is for my server to take a the latest msg from a topic and return it. The service server would take no inputs and return one output. Eg: Return robot position. Or Return a map.

I made a service server node. In the callback of the service I had the node subscribe to the topic I want. In the line were the service node subscribes to the topic, I expect the latest msg to be obtained right then and there from the topic because I made the topic latched by setting the latch argument to True. But it doesn't do as expected. As you can see from the code below I am forced to include the wait_for_message or else the server node never reads a msg.
The topic I am subscribed to doesn't publish frequently and waiting for a message is not practical, I just want the service to return the latest msg on the topic without waiting for the next one, I thought having the topic latched would take care of that. But it didn't.

Thank you

globvar = 0
def callback(msg_arg): # subscription callback 
    global globvar
    print "in sub cb ",globvar
    globvar = int(float(msg_arg.data)) #because you cant int(float_string)

def service_callback(req): # service callback
    print "in server cb "
    sb = rospy.Subscriber('chatter', String, callback)
    rospy.wait_for_message("chatter", String)
    global globvar
    print (globvar)
    sb.unregister()
    return globvar
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2017-11-17 13:56:40 -0600

gvdhoorn gravatar image

updated 2017-11-17 13:59:45 -0600

The best way to implement something like this is rospy.wait_for_message(..). Creating Subscribers in callbacks is not a good idea.

If you're really only interested in a single message (which happens to be 'the last' only because of latching) then don't create the Subscriber, but use rospy.wait_for_message(..) only.

Note btw that what you show in your question text is really brittle: there is no way to guarantee that globvar will contain an actual message object at that point.

edit flag offensive delete link more

Comments

It will also let you avoid all those ugly global vars.

gvdhoorn gravatar imagegvdhoorn ( 2017-11-17 13:56:58 -0600 )edit

Perfect. I didn't know I can use wait_for_message without subscribing. And I also didn't know that wait_for_message actually returns the message. My code is more robust now and doesn't have global variable. Thank you.

RobotWhisperer gravatar imageRobotWhisperer ( 2017-11-18 09:01:47 -0600 )edit

Your Answer

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

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-11-17 11:35:58 -0600

Seen: 485 times

Last updated: Nov 17 '17