Skip to content

Commit

Permalink
Add load_param_file()
Browse files Browse the repository at this point in the history
  • Loading branch information
Tacha-S committed Nov 18, 2023
1 parent c883de4 commit ace05fc
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 1 deletion.
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -449,3 +449,43 @@ arg2 = gen.add_arg(name, default_value, description, choices)
gen.add_node('executable_name', 'package_name',
condition=launch_generator.condition([arg, '< 10 or ', arg2])) # the node is launched only if arg is less than 10 or greater than 20
```

### load_param_file()

`load_param_file()` is a function to load a yaml file to parameter dictionary.
The function can replace the value of parameters written in the form of `$(arg arg_name)` like `subst_value` of ROS1 with `LaunchConfiguration(arg_name)`.

Example of yaml file:

```yaml
node_name:
ros__parameters:
param1: $(arg arg_name)
param2:
sub1: prefix_$(arg arg_name)
sub2: $(arg arg_name)_suffix
sub3: $(arg arg_name)_$(arg_name2)
```
```python
arg = gen.add_arg('arg_name', 'default_value')
arg2 = gen.add_arg('arg_name2', 'default_value')
param_dict = launch_generator.load_param_file('package_name', 'config/file_name.yaml')

# param_dict = {
# 'node_name': {
# 'ros__parameters': {
# 'param1': launch.substitutions.LaunchConfiguration('arg_name'),
# 'param2': {
# 'sub1': ['prefix_', launch.substitutions.LaunchConfiguration('arg_name')],
# 'sub2': [launch.substitutions.LaunchConfiguration('arg_name'), '_suffix'],
# 'sub3': [launch.substitutions.LaunchConfiguration('arg_name'), '_', launch.substitutions.LaunchConfiguration('arg_name2')],
# }
# }
# }
# }

gen.add_node('executable_name', 'package_name', parameters=[param_dict['node_name']['ros__parameters']])

return LaunchDescription(gen.generate_launch_description())
```
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description = "Simple launch file generator for ROS2."
authors = [
{ name = "Tatsuro Sakaguchi", email = "tatsuro.sakaguchi@g.softbank.co.jp" },
]
dependencies = ["launch", "launch_ros"]
dependencies = ["launch", "launch_ros", "pyyaml"]
readme = "README.md"
requires-python = ">= 3.10"

Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@
url='https://github.com/Tacha-S/launch_generator',
package_dir={'': 'src'},
packages=setuptools.find_packages('src', include=['launch_generator']),
install_requires=['pyyaml'],
)
2 changes: 2 additions & 0 deletions src/launch_generator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@
from launch_generator.event_handler_generator import EventTriggerType
from launch_generator.generator import Generator
from launch_generator.utils import condition
from launch_generator.utils import load_param_file
from launch_generator.utils import package_path

__all__ = [
'EventTriggerType',
'Generator',
'condition',
'load_param_file',
'package_path',
]
65 changes: 65 additions & 0 deletions src/launch_generator/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
#

import pathlib
import re
import typing

import launch
import launch_ros
import yaml


def condition(
Expand Down Expand Up @@ -71,3 +73,66 @@ def package_path(package_name: str) -> pathlib.Path:
Package path.
"""
return pathlib.Path(launch_ros.substitutions.FindPackageShare(package_name).find(package_name))


def load_param_file(package: launch.some_substitutions_type.SomeSubstitutionsType,
relative_file_path: typing.Text) -> dict:
"""Load param file to dict. Replace $(arg xxx) with LaunchConfiguration(xxx).
Args:
package: Package name.
relative_file_path: Relative file path.
Returns:
Parameters.
"""
path = package_path(package) / relative_file_path
with open(path, 'r') as f:
parameters = yaml.safe_load(f.read())

def __replace_arg(params: dict[str, typing.Any]) -> None:
"""Replace $(arg xxx) with LaunchConfiguration(xxx).
Args:
params: Parameters.
"""
regex = re.compile(r'\$\(arg \w+?\)')
replaced_keys = {}
for key, value in params.items():
if isinstance(value, dict):
__replace_arg(value)
elif isinstance(value, str):
match = regex.findall(value)
if match:
replaced = []
start = 0
for m in match:
i = value.find(m)
if i > start:
replaced.append(value[start:i])
replaced.append(launch.substitutions.LaunchConfiguration(m[6:-1]))
start = i + len(m)
if start < len(value):
replaced.append(value[start:])
params[key] = replaced
value = replaced

match = regex.findall(key)
if match:
replaced = []
start = 0
for m in match:
i = key.find(m)
if i > start:
replaced.append(key[start:i])
replaced.append(launch.substitutions.LaunchConfiguration(m[6:-1]))
start = i + len(m)
if start < len(key):
replaced.append(key[start:])
replaced = tuple(replaced)
replaced_keys[replaced] = value
params.update(replaced_keys)

__replace_arg(parameters)

return parameters

0 comments on commit ace05fc

Please sign in to comment.