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

Pass parameters to a service handler in rospy

asked 2016-11-08 09:18:02 -0500

antonio gravatar image

In rospy, message callbacks can have additional parameters, which allows me to write only one callback for different subscribers. For example:

def my_callback(msg, name):
    rp.logwarn(name + "has received the message: " + msg)

subscribers = [
    rp.Subscriber(
        name+'/my_topic',
        MyMessageType,
        my_callback,
        callback_args=name)
    for name in "Alice Bob Carl David".split()]

works perfectly fine. However, the same is not possible for service handlers. For example:

def my_hanlder(request, name):
    rp.logwarn(name + "has received the request: " + request)

providers = [
    rp.Service(
        name+'my_service',
        MyServiceType,
        my_handler,
        handler_args=name)
    for name in "Alice Bob Carl David".split()]

raises an error, because handler_args is not a parameter of the constructor rp.Subscriber.

How can I pass additional parameters to a service handler?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2016-11-08 12:41:02 -0500

ahendrix gravatar image

The rospy.Service docs show that there isn't a parameter to the service constructor that allows it to pass arguments to the callback.

However, it's relatively easy to do this with a lambda:

def my_hanlder(request, name):
    rp.logwarn(name + "has received the request: " + request)

providers = [
    rp.Service(
        name+'my_service',
        MyServiceType,
        lambda msg: my_handler(msg, name))
    for name in "Alice Bob Carl David".split()]

(my apologies if there's a small syntax error in there; I don't use lambda very often)

edit flag offensive delete link more

Comments

Yes, this was also my solution; but it has some faint "workaround" feel about it :)

antonio gravatar image antonio  ( 2016-11-23 06:33:00 -0500 )edit

Not sure if this is an issue due to newer python, but the lambdas are dynamically called on msg income. which means the last known 'name' is passed to all of them.

so for me all the my_hanlder calls report Dave is the receiver to fix this :

providers = [
rp.Service(
    name+'my_service',
    MyServiceType,
    lambda msg, name_=name: my_handler(msg, name_))
for name in "Alice Bob Carl David".split()]
mcmeat gravatar image mcmeat  ( 2022-10-18 02:37:01 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2016-11-08 09:18:02 -0500

Seen: 1,590 times

Last updated: Nov 08 '16