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

Adding node from within OpaqueFunction in ROS2 Python Launch File

asked 2023-06-13 16:16:45 -0600

zkytony gravatar image

Is it possible to do something like this

def myfunc(context, ld):
    ld.add_action(Node(...))

def generate_launch_description() -> launch.LaunchDescription:
    ld = launch.LaunchDescription(...)
    ld.add_action(OpaqueFunction(
        function=myfunc, args=[ld]))

This is very useful if some parameter of the Node requires information dependent on the context

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-13 22:24:16 -0600

danzimmerman gravatar image

Works for me:

https://github.com/danzimmerman/dz_la...

import launch
import launch_ros
import os

def prepare_multiple_nodes(context, *args, **kwargs):
    """
    """
    N_lc = launch.substitutions.LaunchConfiguration("num_node_pairs")
    N = int(N_lc.perform(context))

    nodes = []

    if N<1 or N>5:
        message = launch.actions.LogInfo(
            msg="ERROR: Number of launched node pairs must be between 1 and 5, not launching any."
        )
    else:
        message = launch.actions.LogInfo(msg=f"Starting {N} node pairs.")
        for i in range(0, N):
            # launch N talkers in distinct namespaces
            nodes.append(
                launch_ros.actions.Node(
                    package="demo_nodes_cpp", 
                    executable="talker", 
                    output="screen",
                    namespace=f"ns{i}"
                )
            )
            # launch N listeners in distinct namespaces
            nodes.append(
                launch_ros.actions.Node(
                    package="demo_nodes_cpp", 
                    executable="listener", 
                    output="screen",
                    namespace=f"ns{i}"
                )
            )

    return nodes + [message]

def generate_launch_description():

    declared_args = []

    declared_args.append(
        launch.actions.DeclareLaunchArgument(
            "num_node_pairs",
            default_value="1",
        )
    )

    return launch.LaunchDescription(
        declared_args + 
       [launch.actions.OpaqueFunction(function=prepare_multiple_nodes)]
    )

From https://github.com/danzimmerman/dz_la...

It also seems that you can use LaunchDescription.add_action() to modify a passed-in launch description as your question suggests:

https://github.com/danzimmerman/dz_la...

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2023-06-13 16:16:45 -0600

Seen: 309 times

Last updated: Jun 13 '23