Adding node from within OpaqueFunction in ROS2 Python Launch File
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
Asked by zkytony on 2023-06-13 16:16:45 UTC
Answers
Works for me:
https://github.com/danzimmerman/dz_launch_examples/blob/rolling/launch/opaque_multi_nodes.launch.py
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_launch_examples/
It also seems that you can use LaunchDescription.add_action()
to modify a passed-in launch description as your question suggests:
Asked by danzimmerman on 2023-06-13 22:24:16 UTC
Comments