gramaziokohler / roslibpy

Python ROS Bridge library
MIT License
277 stars 57 forks source link

Blocking wait on a service call #27

Closed seraetzer closed 5 years ago

seraetzer commented 5 years ago

Hi guys, I'm using a roslib Service to send a control command to my robot. After his move he responds a travelled distance. I need to wait blocking until the Service call returns. Is there a way to do this with roslibpy?

import roslibpy

res = 0.0

client = roslibpy.Ros(host='localhost', port=9090)
service = roslibpy.Service(client, '/dist', 'robot/dist')

def call_service(angles):
    request = roslibpy.ServiceRequest(dict(str=angles))
    service.call(request, success_callback, error_callback)

def success_callback(result):
    res = result['dist']

def error_callback(result):
    print('Something went wrong')

if __name__ == "__main__":
    while(True):
        print(call_service("0 0 0 0"))# Here should be a blocking wait

    client.terminate()

Thanks in advance.

gonzalocasas commented 5 years ago

@seraetzer right now, this needs to be done on the calling side. e.g. use a threading.Event, wait for it after invocation and set it when a callback is called. But I think it makes a lot of sense to add it as a feature for an upcoming release.

seraetzer commented 5 years ago

Thanks for your reply,

@gonzalocasas I will do so and it will be fine for now. I'm looking forward for updates on roslibpy.

gonzalocasas commented 5 years ago

@seraetzer starting with roslibpy v0.5, you can use services with blocking calls! :)

To do that, simply do not pass a callback/errback to the call() function and instead of being non-blocking, the call will block and return the result as return value of the call. See some examples on the documentation.

Additionally, the .run() will now wait for the connection to be established, so the need to add on_ready handlers is minimized.