ROS2 cheatsheet

ROS2. Resumen de código

En este artículo voy a ir recopilando código de uso frecuente para tenerlo a mano.

Espacios de trabajo

Crear un espacio de trabajo
source /opt/ros/galactic/setup.bash
mkdir -p ~/dev_ws/src
Resolver dependencias
rosdep install -i --from-path src --rosdistro galactic -y
Compilar todo el espacio de trabajo
colcon build

Paquetes

Crear un paquete
ros2 pkg create <package_name> --build-type ament_python --dependencies rclpy
Crear un paquete con un ejecutable (nodo) vacío
ros2 pkg create <package_name> --node-name <node_name> --build-type ament_python --dependencies rclpy 
Compilar un paquete
colcon build --packages-select <package_name>

ARCHIVOS LAUNCH

PYTHON

Estructura básica

Indicando directamente las acciones en el constructor del objeto LaunchDescription
from launch import LaunchDescription

def generate_launch_description():
    return LaunchDescription([
        # Incluir aquí las acciones:
        # action_1,
        # action_n,
    ])

Acciones

GENERICAS
DeclareLaunchArgument
from launch.actions import DeclareLaunchArgument

DeclareLaunchArgument(
    'argument_name',
    default_value='A',
    description='Description text for the argument',
    choices=['A', 'B']
)
IncludeLaunchDescription
from launch.actions import IncludeLaunchDescription
from launch_ros.substitutions import FindPackageShare
from launch.launch_description_sources import PythonLaunchDescriptionSource


IncludeLaunchDescription(
    PythonLaunchDescriptionSource(
        [
            FindPackageShare('package_name'), 
            '/launch', '/my_file.launch.py'
        ],
        launch_arguments = {'arg1_name': arg1_val, 'arg2_name': arg2_val}.items()
    )
)
SetLaunchConfiguration
from launch.actions import SetLaunchConfiguration
 
SetLaunchConfiguration('arg_name', 'arg_value')
SetEnvironmentVariable
from launch.actions import SetEnvironmentVariable

SetEnvironmentVariable('VAR_NAME', 'var_value')
UnsetEnvironmentVariable
from launch.actions import UnsetEnvironmentVariable

UnsetEnvironmentVariable('VAR_NAME')
LogInfo
from launch.actions import LogInfo

LogInfo(msg='My text')
GroupAction
from launch.actions import GroupAction

GroupAction(
    actions=[
        # Incluir aquí las acciones:
        # action_1,
        # action_n,
    ]
)
ExecuteProcess
from launch.actions import ExecuteProcess

ExecuteProcess(
    cmd=['my_cmd'],
    name='my_process',  
    output='both',       # Puede ser: screen, log, both.
    additional_env={'env_var': 'env_var_value'},
)
TimerAction
from launch.actions import TimerAction

TimerAction(period=5.0, actions=[action_1, action_n])
RegisterEventHandler
from launch.actions import RegisterEventHandler
from launch.event_handlers import <event_handler>

RegisterEventHandler(
    event_handler=<event_handler>( <args> )
)
ESPECIFICAS DE ROS
Node
from launch_ros.actions import Node

Node(
    package='package_name',
    executable='executable_name',
    name='node_name',
    exec_name='process_name',
    output='screen', 
    namespace='my_namespace',
    remappings=[("src_topic1", "dest_topic1"), ("src_topic2", "dest_topic2")],
    arguments=['-arg1_name', 'arg1_value', '-arg2_name', 'arg2_value'],
    parameter=[{'param1': 'param1_value', 'param2': 'param2_value'}],
    ros_arguments=['__ros_arg_name', 'value'],
)
RosTimer
from launch_ros.actions import RosTimer

RosTimer(period=5.0, actions=[action1, action2])
SetParameter
from launch_ros.actions import SetParameter

SetParameter(name='param_name', value='param_value')
SetParameterFromFile
from launch_ros.actions import SetParameterFromFile

SetParametersFromFile('path/to/file.yaml')
SetRemap
from launch_ros.actions import SetRemap

SetRemap(src='src_topic', dst='dst_topic')
SetUseSimTime
from launch_ros.actions import SetUseSimTime

SetUseSimTime(True)
PushRosNamespace
from launch_ros.actions import PushRosNamespace

PushRosNamespace('my_namespace')

Sustituciones

Condiciones

IfCondition
# La acción se ejecutara si el argumento my_arg = 'true'.
condition=IfCondition(LaunchConfiguration('my_arg'))

# La acción se ejecutara si la variable de entorno USER = 'Alex'.
condition=IfCondition(PythonExpression(["'", EnvironmentVariable('USER'), "' == 'Alex'"]))
UnlessCondition
from launch.conditions import IfCondition

# La acción se ejecutara si el argumento my_arg = 'false'.
condition=UnlessCondition(LaunchConfiguration('my_arg'))

# La acción se ejecutara si la variable de entorno USER != 'Alex'.
condition=UnlessCondition(PythonExpression(["'", EnvironmentVariable('USER'), "' == 'Alex'"]))
LaunchConfigurationEquals
from launch.conditions import UnlessCondition

# La acción se ejecutara si el argumento user = 'Alex'.
condition=LaunchConfigurationEquals('user', 'Alex')

# La acción se ejecutara si el valor del argumentos user y my_name coinciden.
condition=LaunchConfigurationEquals('user', LaunchConfiguration('my_name'))

Eventos

XML

YAML

TF2

Transformaciones estáticas

Publicar una transformación estática
from geometry_msgs.msg import TransformStamped
from tf2_ros.static_transform_broadcaster import StaticTransformBroadcaster


self.static_tf_broadcaster = StaticTransformBroadcaster(self)

tf = TransformStamped()
tf.header.stamp = self.get_clock().now().to_msg()
tf.header.frame_id = 'parent_frame'
tf.child_frame_id = 'child_frame'

tf.transform.translation.x = <translation_x_value>
tf.transform.translation.y = <translation_y_value>
tf.transform.translation.z = <translation_z_value>

tf.transform.rotation.x = <quaternion_x_value>
tf.transform.rotation.y = <quaternion_y_value>
tf.transform.rotation.z = <quaternion_z_value>
tf.transform.rotation.w = <quaternion_w_value>

self.static_tf_broadcaster.sendTransform(tf)
Convertir de ángulos de Euler a cuaternion
from tf_transformations import quaternion_from_euler

quat = quaternion_from_euler(roll, pitch, yaw)
Convertir de cuaternion a ángulos de Euler
from tf_transformations import euler_from_quaternion

euler = euler_from_quaternion(x, y, z, w)

Robot State Publisher

robot_state_publisher_node = Node(
    package='robot_state_publisher',
    executable='robot_state_publisher',
    name='my_robot_state_publisher',
    emulate_tty=True,
    parameters=[{'use_sim_time': True, 'robot_description': xml}],
    remappings=[("/robot_description", "/my_robot_description")
    ],
    output="screen"
)
Comparte este artículo:

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *