How to Call a Service from a ROS2 Launch File

luckierdodge

Ryan D. Lewis

Posted on September 3, 2022

How to Call a Service from a ROS2 Launch File

This one is pretty straight forward, but took me a non-trivial amount of searching to find for myself. To call a ros2 service from a ros2 launch file, add the following to your launch file (see the official docs for more on launch files):

from launch.substitutions import FindExecutable
from launch.actions import ExecuteProcess

...

ld.add_action(
    ExecuteProcess(
        cmd=[[
            FindExecutable(name='ros2'),
            " service call ",
            "/namespace/service_to_call ",
            "example_msgs/srv/ExampleMsg ",
            '"{param_1: True, param_2: 0.0}"',
        ]],
        shell=True
    )
)
Enter fullscreen mode Exit fullscreen mode

Note the following:

  • ld here is a variable containing an instance of LaunchDescription
  • /namespace/service_to_call is replaced with the service you're looking to call (don't forget any appropriate namespaces) and can be found with ros2 service list
  • example_msgs/srv/ExampleMsg is the message type used by that service, which you can get with ros2 service info /namespace/service_to_call
  • "{param_1: True, param_2: 0.0}" is the dictionary defining the message data. To find the parameters you need to set, you may need to consult the .srv file or documentation.

Don't forget to include the shell=True argument, as the command will fail with a confusing "File not found" error without it.

💖 💪 🙅 🚩
luckierdodge
Ryan D. Lewis

Posted on September 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related