This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

References

Low level reference docs of the ROS course

1 - Concepts (ROS Guide)

A complete ROS Guide to search specific things

Tabla de Contenidos

Guía

Getting Started

Una vez tengas un workspace, puedes buildearlo de la siguiente forma:

$ colcon build --symlink-install

Nota: Gracias a --symlink-install, no necesitas recompilar cada vez que hagas una modificación en un archivo de Python. Modificaciones en otros archivos o en C++ requieren recompilar y generalmente volver a hacer el source. Esto creará varios directorios: log, install, build. En caso de que la compilación falle, puedes consultar los logs (log/latest_build).

Ahora, asumiendo que estás utilizando bash, sourcea el setup.bash.

source install/setup.bash

Esto tambien proporcionará autocompletado en la linea de comandos.

Crear un package nuevo

En tu workspace, ejecuta el siguiente comando reemplazando example_package por el nombre del paquete:

$ ros2 pkg create example_package --build-type ament_python --dependencies rlcpy

Si necesitas añadir más dependencias, puedes especificarlas en el package.xml.

Una vez ejecutado el comando, se creará una directorio con el nombre que le has dado con todo lo necesario para empezar a desarrollar en Python con la siguiente estructura.

example_package
├── example_package
│   └── __init__.py
├── package.xml
├── resource
│   └── example_package
├── setup.cfg
├── setup.py
└── test
    ├── test_copyright.py
    ├── test_flake8.py
    └── test_pep257.py

Tus scripts los crearás en el directorio example_package/example_package.

Crear un nodo nuevo

Puedes utilizar los ejemplos que vienen con ROS (talker.py o listener.py) como base:

$ cp /opt/ros/$ROS_DISTRO/share/launch_testing_ros/examples/talker.py example_package/mi_nodo.py

En el caso de que quieras que este script sea ejecutable, marca en el setup.py de tu package el entry_point (es decir, la función main).

from setuptools import setup
package_name = 'example_package'
setup(
    name=package_name,
    # ...
    entry_points={
        'console_scripts': [
            'NOMBRE_SCRIPT = example_package.NOMBRE_SCRIPT:main',
        ],  
    },  
)

Ahora podrás ejecutarlo de la siguiente forma:

$ ros2 run example_package NOMBRE_SCRIPT

Leer mensajes de topics

Saber los topics activos y el tipo de mensajes que mandan (gracias a la opción -t):

$ ros2 topic list -t
/parameter_events [rcl_interfaces/msg/ParameterEvent]
/rosout [rcl_interfaces/msg/Log]
...

Si sabemos el nombre del topic, podemos ver la especificación directamente:

$ ros2 topic info <TOPIC>

Ahora, podemos leer qué mensajes se están publicando a tiempo real usando el siguiente comando:

$ ros2 topic echo <TOPIC>

Como ver la estructura de un mensaje en yaml:

$ ros2 interface show geometry_msgs/msg/Pose
# A representation of pose in free space, composed of position and orientation.
Point position
  float64 x
  float64 y
  float64 z
Quaternion orientation
  float64 x 0
  float64 y 0
  float64 z 0
  float64 w 1

Publicar en un topic desde terminal

$ ros2 topic pub <TOPIC> <MSG_TYPE> '<args>'

Donde los argumentos son los atributos necesarios para construir el mensaje deseado.

Usando como ejemplo el mensaje geometry_msgs/msg/Pose del apartado anterior. Podemos la orientación tiene un valor por defecto, así que no tenemos que especificarlo.

$ ros2 topic pub <TOPIC> <MSG_TYPE> '{ position: { x: 0, y: 0, z: 0 } }'
publisher: beginning loop
...

Lanzar un launcher

Puedes usar tab para autocompletar. Si ROS no encuentra tu paquete, lee la sección de package.

$ ros2 launch PACKAGE LAUNCHER

Crear un msg propio

Antes de crear un msg propio, asegurate de que no existe ninguno que satisfazca tus necesidades. Puedes ver los mensajes que trae ROS por defecto en std_msgs y geometry_msgs, o los mensajes que utiliza la universidad de Edimburgo: eufs_msgs.

Si no hay ninguno que te sirva, puedes crear uno propio.

  1. En general, se recomienda almacenar todos los mensajes en un package aparte, que solo tenga los archivos .msg y/o funcionalidad muy especifica relacionada con ellos.

Ten en cuenta que los archivos .msg requieren compilarse a Python/C++, y este proceso requiere de cmake, la herramienta de automaticación de compilado. Esta herramienta no está disponible en los packages de Python así que probablemente necesites crear un paquete nuevo:

$ ros2 pkg create uvigo_msgs --build-type ament_cmake

  1. Una vez tengas el package, añade estas lineas al archivo package.xml
  <build_depend>rosidl_default_generators</build_depend>
  <exec_depend>rosidl_default_runtime</exec_depend>
  <member_of_group>rosidl_interface_packages</member_of_group>

Estas líneas especifican las dependencias del package (por ejemplo si quieres que tus mensajes tengan atributos cuyos tipos están definidos en eufs_msgs, std_msgs, o otro package) y el miembro del grupo para generar y usar interfaces ROS2 (mensajes, servicios y acciones) mediante la herramienta rosidl.

  1. En el archivo CMakeLists.txt, añade estas lineas:
# find dependencies
find_package(ament_cmake REQUIRED)
+find_package(rosidl_default_generators REQUIRED)
# Al final del archivo
endif()
+rosidl_generate_interfaces(${PROJECT_NAME}
+  "msg/MiMensaje.msg"
+)
ament_package()
  1. Ahora ya puedes crear tu directorio msg y añadir ahí tu mensaje propio:
# Descripción de mi mensaje
std_msgs/Header header
float64 x
float64 y
  1. Finalmente, comprueba que todo ha ido correcto:
$ colcon build && source install/setup.bash
...
$ ros2 interface show uvigo_msgs/msg/MiMensaje
# Descripción de mi mensaje
std_msgs/Header header
float64 x
float64 y

Recomendaciones

  • Puedes ver los nodos y topics que se ejecutan en cada momento ejecutando el programa rqt_graph en la terminal.
  • Una vez instalado ROS, tenéis ejemplos de paquetes en /opt/ros/$ROS_DISTRO/share

2 - launch file

How to make a launch file to startup a complex ROS system.

ROS2 launch file allow us to start up and configure a number of executables containing ROS 2 nodes simultaneously. You don’t to execute each node with a ros2 run <package> <node>. ROS 2 launch files can be written in Python, XML, and YAML. Python, XML, and YAML for ROS 2 Launch Files

In this course this little example assume you want to write your launch file on YAML; but it is more common to find launch files written on Python.

How to launch a launcher

ros2 launch <launcher>.yaml

if you have more than a package you need to specify the package.

ros2 launch <package> <launcher>.yaml

3 - rosdep

how to manage ros dependencies.

What is rosdep?

rosdep is ROS’s dependency management utility that can work with ROS packages and external libraries. rosdep is a command-line utility for identifying and installing dependencies to build or install a package.

When we need rosdep

  • Dependencies to build our Project.
  • Dependencies to execute our Project.

package.xml

package.xml is the file where is specified all the dependencies for our project. Should be an exhaustive list of any non-builtin libraries and packages it requires.

The dependencies need to be in package.xml like:

  • For dependencies only used in building the code, use <build_depend>.

  • For dependencies needed by headers the code exports, use <build_export_depend>.

  • For dependencies only used when running the code, use <exec_depend>.

  • Recommended by default: For mixed purposes, use <depend>, which covers build, export, and execution time dependencies.

Example package.xml

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>eufs_launcher</name>
  <version>2.0.0</version>
  <description>Configures and launches eufs_sim.</description>

  <maintainer email="cambobmat@icloud.com">Cameron Matthew</maintainer>
  <maintainer email="siliconlad@protonmail.com">Angus Stewart</maintainer>

  <license>MIT</license>

  <url type="website">http://eufs.co</url>
  <url type="repository">https://gitlab.com/eufs/eufs_sim</url>
  <url type="bugtracker">https://gitlab.com/eufs/eufs_sim/issues</url>

  <depend>rclpy</depend>
  <depend>rqt_gui</depend>

  <depend>launch</depend>
  <depend>launch_ros</depend>

  <depend>python3-yaml</depend>
  <depend>python3-pandas</depend>

  <export>
    <build_type>ament_python</build_type>
    <rqt_gui plugin="${prefix}/plugin.xml"/>
  </export>
</package>

4 - ROS on same LAN

Low level reference docs of the ROS course

ROS_DOMAIN_ID

By default, ROS 2 communication is not limited to localhost. So, you can have a distributed node system only by connecting the computers via Ethernet.

If you want to change the ROS_DOMAIN_ID you need to choose a number between 0 and 101, inclusive, and:

export ROS_DOMAIN_ID=<your_domain_id>

Changing ROS_DOMAIN_ID leads to have a isolated environment for your ROS nodes. If you want to have two or more computers to communicate, you need to have the same ID.

5 - Tips and Tricks

Different advices to make a ROS proyect.

How to use rqt utilities