備註
您正在閱讀開發版本的文件。對於最新發行的版本,請參見 Lyrical。
開發一個 ROS 2 軟體包
本教學將教您如何建立您的第一個 ROS 2 應用程式。它適用於想要學習如何在 ROS 2 中建立自訂軟體包的開發者,而非想要使用 ROS 2 現有軟體包的人員。
先備條件
透過 source 您的 ROS 2 安裝來設定工作區。
建立軟體包
所有 ROS 2 軟體包都是透過執行以下命令來建立的
$ ros2 pkg create --license Apache-2.0 <pkg-name> --dependencies [deps]
在您的工作區中(通常為 ~/ros2_ws/src)。
若要為特定客戶端程式庫庫建立軟體包:
$ ros2 pkg create --build-type ament_cmake --license Apache-2.0 <pkg-name> --dependencies [deps]
$ ros2 pkg create --build-type ament_python --license Apache-2.0 <pkg-name> --dependencies [deps]
然後您可以使用依賴、描述和作者資訊等軟體包資訊來更新 package.xml。
C++ 軟體包
您大多會使用 add_executable() CMake 巨集,搭配
target_link_libraries(<executable-name> PUBLIC [targets from your dependencies])
來建立可執行節點並連結依賴。
若要安裝您的啟動檔和節點,可以使用 install() 巨集,將其放置在檔案結尾處,但在 ament_package() 巨集之前。
啟動檔和節點的範例:
# 安裝啟動檔
install(
DIRECTORY launch
DESTINATION share/${PROJECT_NAME}
)
# 安裝節點
install(
TARGETS [node-names]
DESTINATION lib/${PROJECT_NAME}
)
Python 軟體包
ROS 2 遵循 Python 使用 setuptools 的標準模組發布流程。對於 Python 軟體包,setup.py 檔案是對 C++ 軟體包 CMakeLists.txt 的補充。更多關於發布的詳細資訊可參閱 官方文件。
在您的 ROS 2 軟體包中,應該有一個 setup.cfg 檔案,其內容如下:
[develop]
script_dir=$base/lib/<package-name>
[install]
install_scripts=$base/lib/<package-name>
以及一個 setup.py 檔案,其內容如下:
import os
from glob import glob
from setuptools import find_packages, setup
package_name = 'my_package'
setup(
name=package_name,
version='0.0.0',
# Packages to export
packages=find_packages(exclude=['test']),
# Files we want to install, specifically launch files
data_files=[
# Install marker file in the package index
('share/ament_index/resource_index/packages', ['resource/' + package_name]),
# Include our package.xml file
(os.path.join('share', package_name), ['package.xml']),
# Include all launch files.
(os.path.join('share', package_name, 'launch'), glob('launch/*')),
],
# This is important as well
install_requires=['setuptools'],
zip_safe=True,
author='ROS 2 Developer',
author_email='ros2@ros.com',
maintainer='ROS 2 Developer',
maintainer_email='ros2@ros.com',
keywords=['foo', 'bar'],
classifiers=[
'Intended Audience :: Developers',
'License :: TODO',
'Programming Language :: Python',
'Topic :: Software Development',
],
description='My awesome package.',
license='TODO',
# Like the CMakeLists add_executable macro, you can add your python
# scripts here.
entry_points={
'console_scripts': [
'my_script = my_package.my_script:main'
],
},
)
合併的 C++ 與 Python 軟體包
When writing a package with both C++ and Python code, the setup.py file and setup.cfg file are not used.
Instead, use ament_cmake_python.