DEV Community

Ryan D. Lewis
Ryan D. Lewis

Posted on • Originally published at ryandlewis.dev

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.

Top comments (0)