better_launch

repository·main·Indexed 42 days ago

https://github.com/dfki-ric/better_launch

A replacement for the ROS2 launch system providing a more intuitive Python-based API and a TOML-based alternative for configurations. It features the `bl` CLI for executing launch files, a Terminal User Interface (TUI) for real-time node management, and simplified argument handling via Python function signatures and the `@launch_this` decorator.

Tokens
9.9K
Snippets
30
Records
44
Agent score
51%

What's inside better_launch

  1. Performance comparison with ros2 launch

    main

    Performance benchmarks indicate that better_launch (via the bl command) achieves performance comparable to ros2 launch.

    Key findings include:

    • Memory Efficiency: Using memray, better_launch shows approximately 30% less memory usage and fewer allocations compared to ros2 launch.
    • Resource Usage: Benchmarks using psutil suggest that better_launch may use more CPU during the initial startup phase and higher total memory (unique set size) compared to ros2 launch.

    Detailed benchmark scripts and results are available in the repository's docs/benchmarks directory.

  2. Core features of better_launch

    main

    The better_launch library is a complete replacement for ROS2 launch capabilities with additional features:

    • Node & Component Management: Create nodes, composers, components, and namespaces.
    • On-the-fly ROS2 Entities: Create subscribers, publishers, and services during the launch process.
    • Lifecycle Management: Manage lifecycle stages of nodes.
    • Topic Remapping: Use simple Python dictionaries for remapping.
    • File & Config Management: Easily locate files and load configurations.
    • Interoperability: Include better_launch files in regular ROS2 launchfiles, and vice versa.
    • Terminal UI: Manage nodes via a TUI (Terminal User Interface) similar to rosmon.
  3. Manage lifecycle nodes using LifecycleManager

    main

    In better_launch, there is no functional distinction between regular nodes and lifecycle nodes. Instead, any object that supports lifecycle management (like nodes or components) provides a lifecycle member which contains a LifecycleManager object.

    • Accessing the Manager: If the object is lifecyclable, object.lifecycle will return a LifecycleManager. If not, it returns None.
    • Default Behavior: All lifecyclable objects will transition to their ACTIVE state by default upon instantiation, unless you specify a different target state.
  4. Understand action immediacy in better_launch

    main

    Unlike ROS2 launch, which uses an asynchronous event loop to process tasks, better_launch executes actions immediately.

    • Immediate Execution: When you create a node, its process starts right away. When you include another launchfile, its contents are handled before the function returns.
    • ROS2 Launch Integration: If you include regular ROS2 launchfiles, better_launch must convert them into asynchronous tasks. To do this, it starts a LaunchService sub-process the first time a ROS2 action is encountered. Subsequent ROS2 actions are handled asynchronously by this background process.
    • TUI Behavior: ROS2 actions handled via the LaunchService will typically appear as a single launch_service unit in the TUI, even though their output is captured and formatted by better_launch.
  5. Apply Conditions to Call Tables

    main

    You can make a call table conditional by adding an if or unless parameter. The table will only execute if the condition evaluates to true (for if) or false (for unless) based on Python truthiness.

    • If a call table does not run (or has no return), None is stored under its name.
    • Note: Non-empty strings are considered true in Python truthiness.
  6. Manage nodes using the TUI

    main

    Once the TUI is active, you can perform several management tasks for all nodes managed by the current better_launch process:

    • List nodes and their status: View the current state of all managed nodes.
    • Control nodes: Start, stop, or manage the lifecycle of nodes.
    • Change log levels: Dynamically adjust a node's log level.
    • Inspect node information: View a specific node's available services and topics.
  7. How Call Tables work in TOML launchfiles

    main

    In TOML launchfiles, most tables are call tables. A call table is a dictionary containing a func key that refers to a public BetterLaunch member function (or functions from the convenience and gazebo modules).

    • Arguments: All other attributes in the table are treated as keyword arguments to the specified function.
    • Execution Order: Call tables are executed in the order they appear in the file.
    • Return Values: The return value of the function is stored under the table's name (the table's key).
    • Requirement: Every call table must have a unique name, even if the function has no return value or the result is not used.
    [a_simple_cube]
    func = "find"
    package = "better_launch"
    filename = "cube.sdf"
  8. How better_launch works compared to ROS2 launch

    main

    Unlike the standard ROS2 launch system which uses a declarative approach (describing what will happen), better_launch uses an imperative, Pythonic approach where actions are executed immediately.

    Key differences include:

    • Immediate Execution: Actions like starting nodes or calling services happen as the code runs. This allows you to interact with nodes, topics, and services (e.g., adjusting parameters based on a topic) while the launch process is still developing.
    • Natural Types: Launch arguments are defined as standard Python function arguments. This allows you to use native Python logic like if-else statements directly within your launch files.
    • Compatibility: better_launch files are fully compatible with the ROS2 launch system. They can be started via ros2 launch, can include regular ROS2 launch files, and can be included by regular ROS2 launch files.
    • Process Management: better_launch is designed to prevent zombie processes (unless killed with SIGKILL).
  9. Create a launch file with better_launch

    main

    To create a launch file, define a Python function and decorate it with @launch_this. You can define launch arguments as standard function parameters, which will then be available as command-line arguments.

    Inside the function, instantiate BetterLaunch() to access orchestration methods like .node(), .group(), and .call_service().

    Note: The function's docstring is automatically used to generate --help text for the CLI.

    #!/usr/bin/env python3
    from better_launch import BetterLaunch, launch_this
    
    @launch_this
    def my_launch_function(
        arg_one: str = "default_val", 
        arg_two: bool = True
    ):
        """This docstring is used for --help text."""
        bl = BetterLaunch()
    
        # Example: Starting a node within a namespace group
        with bl.group("my_namespace"):
            my_node = bl.node(
                package="my_package",
                executable="my_executable",
                name="my_node_name",
                params={"param_key": "value"},
            )
    
        # Example: Calling a service immediately after node setup
        bl.call_service(
            topic="/my_service",
            service_type="my_msgs/srv/MyService",
            request_args={"data": 1.0},
        )
    
        # Example: Interacting with a node after it is connected
        if arg_two:
            my_node.is_ros2_connected(timeout=None)
            my_node.set_live_params({"param_key": "new_value"})
  10. Install better_launch into a ROS2 workspace

    main

    To install better_launch, clone the repository directly into your ROS2 workspace's src folder. Since it is a regular ROS2 package, it will be available to all launch files within that workspace once built.

    Note: If you want to use experimental features, you can clone the devel branch instead of the default branch.

    # Get better_launch into your workspace src folder
    cd <your/ros2/workspace>/src
    git clone https://github.com/dfki-ric/better_launch.git
  11. Setup better_launch using a Python virtual environment (venv)

    main

    If you prefer using a Python virtual environment instead of installing system-wide packages, follow these steps to create a workspace-local venv that includes system site packages (required for ROS2 integration):

    1. Install python3-pip and python3-venv prerequisites.
    2. Create a venv directory in your workspace root.
    3. Initialize the venv with --system-site-packages and --symlinks.
    4. Create a COLCON_IGNORE file in the venv directory to prevent colcon from trying to build the virtual environment as a package.
    5. Activate the venv and your ROS2 workspace.
    6. Install dependencies from the better_launch requirements file.
    # Install some prerequisites
    sudo apt install python3-pip python3-venv
    
    # Create a virtual environment for your workspace
    cd your/ros2/workspace/
    mkdir venv
    python3 -m venv ./venv --system-site-packages --symlinks
    touch venv/COLCON_IGNORE
    
    # Activate the venv
    source ./venv/bin/activate
    
    # Activate your ROS2 workspace
    source ./install/setup.bash
    
    # Install the dependencies into your venv
    pip install -r path/to/better_launch/requirements.txt
  12. Use Comments and Docstrings in TOML Launchfiles

    main

    The better_launch TOML parser provides special handling for comments:

    • Docstrings: A block of comments at the very top of the file, followed by a blank line, is treated as the launchfile's docstring. This docstring appears in the --help output.
    • Argument Help Text: Any block of comments immediately preceding a key-value pair (like a launch argument) is associated with that key. These comments are used as the help text when viewing arguments via the command line.

    Example of a launchfile with a docstring and argument help:

    # Launchfiles sprawl in knots / 
    # One clean cut to banish chaos / 
    # Silence, then motion
    
    # I mean, who doesn't?
    i_like_haikus = True

    Running bl ./haiku.launch.toml --help will display the docstring and the argument description.

    ❯ bl ./haiku.toml --help
    Usage: bl ./haiku.toml [OPTIONS]
    
      Launchfiles sprawl in knots / One clean cut to banish chaos / Silence, then motion
    
    Options:
      --i_like_haikus BOOLEAN      I mean, who doesn't?  [default: True]