ROS2_pubsub/non-ros-files/Programming_Rules.md

2.2 KiB

Rules for programming with Python in ROS2

File Structure

colcon_workspace  
      |  
      |- build     (holds build files)
      |- install   (holds build elements)
      |- src       (contains your source code - this is where you work)

Colcon Build

Performing a colcon build is neccessary after every change to the src directory. This must be performed in the root of the colcon workspace (eg. cd ~/colcon_ws).

In order to avoid this procedure after every change made to a Python script you must run colcon build --symlink-install once. This links the files created in /build and /install to your source files in /src. However, after creating a new Python script this procedure must be repeated in order to also link this new script.

Source Directory

The source directory holds your ROS2 packages as further directories. In this example the src directory contains the packages pubsub and pubsub_msg:

colcon_workspace/
      |
      |- src/
          |
          |- pubsub/
          |- pubsub_msg/

The src directory is also the place where you create your new packages using ros2 pkg create ... and not in the root of the workspace.

The next chapters will describe the content of the files inside a package directory. However, the occuring files depend on the type of package (ament_cmake for C++ scripts or ament_python for Python scripts). This is described in detail here. The following chapters only describe Python packages.

setup.py

The file <colcon_ws>/<package_dir>/setup.py defines how you can call your scripts using a self defined in the command line. This results in commands such as
ros2 run pubsub talker
ros2 run pubsub listener.
This is done by linking the correct Python scripts to the names talker and listener using the file setup.py, eg.

entry_points={
   'console_scripts': [
       'talker = pubsub.talker:main',
       'listener = pubsub.listener:main'
   ],
},

From this you can see that you need to follow the Python programming style of creating a main procedure, in order for the entry points to work.