Workspace and Packages
A ROS 2 workspace is a directory on your filesystem where you can store, build, and manage your ROS 2 packages. It's the central place for developing your robot applications.
Colcon: The Build System
colcon is the primary build tool for ROS 2. It's a command-line tool that automates the process of building, testing, and installing multiple packages in a workspace. colcon is designed to be flexible and extensible, supporting various build types (e.g., ament_cmake, ament_python).
Creating a Workspace
To create a new ROS 2 workspace, you typically follow these steps:
-
Create the workspace directory:
mkdir -p ~/ros2_ws/srcThe
srcsubdirectory is where your source packages will reside. -
Navigate into the workspace:
cd ~/ros2_ws
Packages
A package is the fundamental unit of organization in ROS 2. It contains source code, build scripts, configuration files, and other resources that together provide a specific functionality (e.g., a driver for a sensor, an algorithm for path planning, or a set of launch files).
Every ROS 2 package must contain a package.xml file, which provides metadata about the package (name, version, description, dependencies, maintainers).
Creating a New Package
You can create a new ROS 2 package using the ros2 pkg create command. This command generates a basic package structure with necessary files.
For a Python package:
cd ~/ros2_ws/src
ros2 pkg create --build-type ament_python my_robot_controller
For a C++ package:
cd ~/ros2_ws/src
ros2 pkg create --build-type ament_cmake my_sensor_driver
Building a Workspace
After adding or modifying packages in your workspace, you need to build them using colcon:
cd ~/ros2_ws
colcon build
This command compiles your code, generates executables, and installs necessary files into the install directory within your workspace.
Sourcing the Setup Files
To use the executables and libraries from your workspace, you need to source the setup files generated by colcon. This adds your workspace's environment variables to your shell.
# In your ~/ros2_ws directory
source install/setup.bash # For bash/zsh
# source install/setup.ps1 # For PowerShell
It's common practice to source the main ROS 2 installation first, and then your workspace setup files, to ensure your workspace's packages take precedence.
Overlays
ROS 2 workspaces can be overlaid. This means you can build a new workspace on top of an existing one (e.g., your development workspace on top of your main ROS 2 installation). This allows you to work on specific packages without rebuilding the entire ROS 2 distribution.
The workspace model with colcon and packages promotes modularity, reusability, and efficient development workflows in ROS 2.