Часть 2.1.3 Создание пакета ROS
Для того, чтобы называться пакетом Catkin, пакет должен отвечать ряду требований:
- Пакет должен содержать Catkin совместимый файл package.xml
- Этот package.xml файл содержит метаинформацию о пакете
- Это не означает, что не должно быть вложенных пакетов
Простейший пакет может выглядеть так:
2. Пакеты в рабочем пространстве Catkin
Рекомендуемый метод работы с catkin пакетами, это с использованием рабочего пространства catkin, но вы также можете создавать catkin пакеты отдельно. Обычно, рабочее пространство выглядит следующим образом:
Перед тем как продолжить этот урок необходимо создать рабочее пространство catkin следуя инструкции.
3. Создание пакета Catkin
Этот урок покажет, как использовать скрипт catkin_create_pkg для создания нового пакета catkin.
Перейдите а рабочее пространство catkin:
Теперь используйте сценарий catkin_create_pkg для того, чтобы создать новый пакет под названием «beginner_tutorials» который зависит от std_msgs, roscpp и rospy:
В результате выполнения команды вы должны увидеть следующее:
Эта команда создаст папку beginner_tutorials которая содержит package.xml и CMakeLists.txt, которые будут частично заполнены информацией которую вы указали в качестве параметров для catkin_create_pkg.
catkin_create_pkg требует, чтобы вы задали package_name и список зависимостей, от которых будет зависеть этот пакет:
catkin_create_pkg имеет расширенные функциональные возможности, которые описаны в catkin/commands/catkin_create_pkg.
4. Сборка рабочего пространства Catkin
Теперь вы должны собрать пакеты в рабочем пространстве catkin:
Результат должен быть примерно таким:
После того как рабочее пространство будет построено в каталоге будет создана структура аналогичная /opt/ros/$ROSDISTRO_NAME.
Для того, чтобы добавить рабочее пространство в ваше ROS окружение необходимо выполнить команду source:
5. Зависимости пакета
5.1 Зависимости первого порядка
При использовании catkin_create_pkg ранее, были указаны некоторые зависимости пакетов. Это и есть зависимости первого порядка.
Как вы можете видеть, команда rospack показала те же зависимости, которые были использованы в качестве аргументов при запуске catkin_create_pkg. Эти зависимости для пакета хранятся в файле package.xml:
Как видите в файле присутствуют следующие строки:
5.2 Косвенные зависимости
Во многих случаях зависимости будут также иметь свои собственные зависимости. Например, rospy имеет несколько зависимостей.
Пакет может иметь несколько косвенных зависимостей. К счастью rospack может рекурсивно определить все вложенные зависимости.
6. Настройка пакета
Эта часть урока будет рассматривать каждый файл, созданный catkin_create_pkg и описывать, каждую строку в этих файлах и, как вы можете настроить их под ваш пакет.
6.1 Настройка package.xml
Сгенерированный package.xml должен находиться в вашем новом пакете. Теперь давайте рассмотрим package.xml и подправим некоторые элементы, на которые нужно обратить ваше внимание.
6.1.1 Тег description
В первую очередь обновите описание:
Изменить описание можно на любое, но по традиции предложение должно быть коротким и описывать назначение пакета.
6.1.2 Тег maintainer
Далее рассмотрим тег описывающий создателя пакета:
Это необходимый и важный тег в package.xml, потому что это позволяет другим узнать, к кому обращаться по поводу пакета. По крайней мере, необходимы данные одного человека ведущего разработку данного пакета, но можно добавить и несколько, если хотите. Также обязательно должно быть заполнено поле с email:
6.1.3 Тег license
Далее идет тег с лицензией, который также необходимо заполнить:
Вы должны выбрать лицензию и заполнить этот тег. Вот список некоторых лицензии используемых с открытым исходным кодом BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, и LGPLv3. Вы можете прочитать о некоторых из них в Open Source Initiative. Для этого урока мы будем использовать лицензию BSD, потому что основные компоненты ROS используют ее:
6.1.4 Тег dependencies
Следующий набор тегов это описание зависимостей пакета. Зависимости можно разделить на build_depend, buildtool_depend, run_depend, test_depend. Для получения более подробной информации об этих тегах обратитесь к документации по Catkin Dependencies. И так мы задали std_msgs, roscpp и rospy в качестве аргументов для catkin_create_pkg, поэтому зависимости будут выглядеть следующим образом:
Все наши перечисленные зависимости были добавлены в build_depend за нас, в buildtool_depend добавлены зависимости по умолчанию в catkin. Также мы хотим, чтобы все наши зависимости были доступны во время сборки и во время выполнения, поэтому мы добавим тег run_depend для каждой из них:
ROS — Урок 3 — Создание пакета для ROS
Прежде чем создать пакет, давайте посмотрим, как работает утилита roscreate-pkg.
Эта утилита создает новый пакет ROS. Все пакеты ROS содержат набор схожих файлов: манифесты, CMakeLists.txt, mainpage.dox, и Makefile. roscreate-pkg берёт на себя большую часть утомительных задач, которые нужно выполнить при создании нового пакета вручную, и тем самым устраняет распространённые ошибки, вызванные ручным созданием файлов сборки и манифестов.Чтобы создать новый пакет в текущем каталоге нужно выполнить команду:
Также сразу можно указать зависимости этого пакета:
1.2 Создание нового пакета ROS
Теперь, перейдём в наш домашний каталог или каталог проекта и создадим наш пакет под названием beginner_tutorials. Наш тестовый пакет будет зависеть от std_msgs, roscpp, и rospy, которые являются общими пакетами ROS.
Обратите внимание, что каталог с установленной ROS, вероятно, защищен от записи, но в любом случае, неразумно изменять базовую систему без особых причин. Вместо этого, вам следует создать новый каталог в своей домашней директории и добавить его в ROS_PACKAGE_PATH, как это будет показано ниже, и создавать дополнительные пакеты уже там. Прописывание дополнительного пути в начале ROS_PACKAGE_PATH заставит все утилиты rosbash, такие как roscd, искать пакеты сначала по этому пути, прежде чем переходить к следующему каталогу по списку (дефолтный каталог обычно оставляют в списке последним).
Обратите внимание, что экспорт в ROS_PACKAGE_PATH произведённый командой выше, должны быть выполнен при каждом открытии нового терминала (если только вы не измените ваш файл .bashrc чтобы он делал это автоматически).
Теперь перейдём в каталог
/ros_tutorials и создадим там наш первый пакет:
Вы увидите что-то вроде:
Вы можете потратить пару минут и посмотреть содержимое файла beginner_tutorials/manifest.xml. Манифест играет важную роль в ROS, так как он определяет, как пакеты собираются, выполняются и документируются.
Теперь давайте убедимся, что ROS может найти свой новый пакет. Часто бывает полезным вызвать rospack профиля после внесения изменений в директориях своего проекта, чтобы новые каталоги были корректно найдены:
Если это не сработало, значит ROS не может найти свой новый пакет. Обычно проблема кроется в ROS_PACKAGE_PATH. Обратитесь к инструкции по установке из SVN или из пакетов, в зависимости от того, как вы установили ROS. Если вы создали или добавили пакет, который находится за пределами существующих путей в ROS_PACKAGE_PATH, вы должны изменить свою переменную окружения ROS_PACKAGE_PATH, чтобы включить в неё новый каталог.
Попробуем перейти в каталог нашего пакета.
1.3 Зависимости пакета первого порядка
При использовании roscreate-pkg, мы указали несколько зависимостей нашего пакета. Это зависимости первого порядка, теперь мы можем их посмотреть с помощью утилиты rospack.
Как вы можете видеть, rospack вывел список тех же зависимостей, которые были заданы в качестве аргументов при запуске roscreate-pkg. Эти зависимости пакета хранятся в файле манифеста. Взгляните на файл манифеста.
1.4 Косвенные зависимости пакета
В большинстве случаев, зависимость также будет иметь свои собственные зависимости. Например, rospy зависит от других пакетов.
Пакет может иметь довольно много косвенных зависимостей. К счастью, rospack может рекурсивно определить все вложенные зависимости.
1.5 Клиентские библиотеки ROS
Вы можете быть удивлены, что rospy и roscpp зависят от других пакетов, как это видно по предыдущему примеру. Дело в том, что rospy и roscpp являются клиентскими библиотеками (Client Libraries). Клиентские библиотеки позволяют различным языкам программирования, общаться через ROS. rospy — это клиентская библиотека для Python, а roscpp — это клиентская библиотека для C++.
Перечислим команды, с которыми мы познакомились:
roscreate-pkg = ros + create-pkg: генерирует все файлы, необходимые для создания пакета ROS
rospack = ros+pack(age): предоставляет информацию, связанную с пакетами ROS
rosstack = ros+stack: предоставляет информацию, связанную со стеками ROSCreating a ROS Package
Description: This tutorial covers using roscreate-pkg or catkin to create a new package, and rospack to list package dependencies.
Tutorial Level: BEGINNER
- Using roscreate
- Creating a New ROS Package
- First-order package dependencies
- Indirect package dependencies
- ROS Client Libraries
- Review
Using roscreate
Before we create a package, let’s see how the roscreate-pkg command-line tool works. This creates a new ROS package. All ROS packages consist of the many similar files : manifests, CMakeLists.txt, mainpage.dox, and Makefiles. roscreate-pkg eliminates many tedious tasks of creating a new package by hand, and eliminates common errors caused by hand-typing build files and manifests.
To create a new package in the current directory:
You can also specify dependencies of that package:
Creating a New ROS Package
Now we’re going to go into your home or project directory and create our beginner_tutorials package. We are going to make it depend on std_msgs, roscpp, and rospy, which are common ROS packages.
Now go into the
Alternatively, if you use Fuerte or later release, you can simply do:
Then create your package:
You will see something similar to:
You’re going to want to spend some time looking at beginner_tutorials/manifest.xml. manifests play an important role in ROS as they define how Packages are built, run, and documented.
Now lets make sure that ROS can find your new package. It is often useful to call rospack profile after making changes to your path so that new directories will be found:
If this fails, it means ROS can’t find your new package, which may be an issue with your ROS_PACKAGE_PATH. Please consult the installation instructions for setup from SVN or from binaries, depending how you installed ROS. If you’ve created or added a package that’s outside of the existing package paths, you will need to amend your ROS_PACKAGE_PATH environment variable to include that new location. Try re-sourcing your setup.sh in your fuerte_workspace.
Try moving to the directory for the package.
First-order package dependencies
When using roscreate-pkg earlier, a few package dependencies were provided. These first-order dependencies can now be reviewed with the rospack tool.
(Jan 9, 2013) There is a bug reported and already fixed in rospack in groovy; it may take some time to be reflected in the packages. If you see an issue similar to this with the next command, you can skip to the following command.
As you can see, rospack lists the same dependencies that were used as arguments when running roscreate-pkg. These dependencies for a package are stored in the manifest file. Take a look at the manifest file.
Indirect package dependencies
In many cases, a dependency will also have its own dependencies. For instance, rospy has other dependencies.
(Jan 9, 2013) There is a bug reported and already fixed in rospack in groovy; it may take some time to be reflected in the packages. If you see an issue similar to this with the next command, you can skip to the following command.
A package can have quite a few indirect dependencies. Luckily rospack can recursively determine all nested dependencies.
Note: in Fuerte, the list is much shorter:
ROS Client Libraries
You may be wondering what rospy and roscpp dependencies are from the previous examples. rospy and roscpp are Client Libraries. The client libraries allow different programming languages to communicate through ROS. rospy is the client library for Python. roscpp is the client library for C++.
Review
- roscreate-pkg = ros+create-pkg : generates all the files needed to create a ROS package
- rospack = ros+pack(age) : provides information related to ROS packages
- rosstack = ros+stack : provides information related to ROS stacks
- What makes up a catkin Package?
- Packages in a catkin Workspace
- Creating a catkin Package
- Building a catkin workspace and sourcing the setup file
- package dependencies
- First-order dependencies
- Indirect dependencies
- Customizing the package.xml
- description tag
- maintainer tags
- license tags
- dependencies tags
- Final package.xml
What makes up a catkin Package?
- That package.xml file provides meta information about the package.
- This means no nested packages nor multiple packages sharing the same directory.
The simplest possible package might have a structure which looks like this:
Packages in a catkin Workspace
The recommended method of working with catkin packages is using a catkin workspace, but you can also build catkin packages standalone. A trivial workspace might look like this:
Before continuing with this tutorial create an empty catkin workspace by following the Creating a workspace for catkin tutorial.
Creating a catkin Package
This tutorial will demonstrate how to use the catkin_create_pkg script to create a new catkin package, and what you can do with it after it has been created.
First change to the source space directory of the catkin workspace you created in the Creating a Workspace for catkin tutorial:
Now use the catkin_create_pkg script to create a new package called ‘beginner_tutorials’ which depends on std_msgs, roscpp, and rospy:
This will create a beginner_tutorials folder which contains a package.xml and a CMakeLists.txt, which have been partially filled out with the information you gave catkin_create_pkg.
catkin_create_pkg requires that you give it a package_name and optionally a list of dependencies on which that package depends:
catkin_create_pkg also has more advanced functionalities which are described in catkin/commands/catkin_create_pkg.
Building a catkin workspace and sourcing the setup file
Now you need to build the packages in the catkin workspace:
After the workspace has been built it has created a similar structure in the devel subfolder as you usually find under /opt/ros/$ROSDISTRO_NAME.
To add the workspace to your ROS environment you need to source the generated setup file:
package dependencies
First-order dependencies
When using catkin_create_pkg earlier, a few package dependencies were provided. These first-order dependencies can now be reviewed with the rospack tool.
As you can see, rospack lists the same dependencies that were used as arguments when running catkin_create_pkg. These dependencies for a package are stored in the package.xml file:
Indirect dependencies
In many cases, a dependency will also have its own dependencies. For instance, rospy has other dependencies.
A package can have quite a few indirect dependencies. Luckily rospack can recursively determine all nested dependencies.
Customizing Your Package
This part of the tutorial will look at each file generated by catkin_create_pkg and describe, line by line, each component of those files and how you can customize them for your package.
Customizing the package.xml
The generated package.xml should be in your new package. Now lets go through the new package.xml and touch up any elements that need your attention.
description tag
First update the description tag:
Change the description to anything you like, but by convention the first sentence should be short while covering the scope of the package. If it is hard to describe the package in a single sentence then it might need to be broken up.
maintainer tags
Next comes the maintainer tag:
This is a required and important tag for the package.xml because it lets others know who to contact about the package. At least one maintainer is required, but you can have many if you like. The name of the maintainer goes into the body of the tag, but there is also an email attribute that should be filled out:
license tags
Next is the license tag, which is also required:
You should choose a license and fill it in here. Some common open source licenses are BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, and LGPLv3. You can read about several of these at the Open Source Initiative. For this tutorial we’ll use the BSD license because the rest of the core ROS components use it already:
dependencies tags
The next set of tags describe the dependencies of your package. The dependencies are split into build_depend, buildtool_depend, exec_depend, test_depend. For a more detailed explanation of these tags see the documentation about Catkin Dependencies. Since we passed std_msgs, roscpp, and rospy as arguments to catkin_create_pkg, the dependencies will look like this:
All of our listed dependencies have been added as a build_depend for us, in addition to the default buildtool_depend on catkin. In this case we want all of our specified dependencies to be available at build and run time, so we’ll add a exec_depend tag for each of them as well:
Final package.xml
As you can see the final package.xml, without comments and unused tags, is much more concise:
Customizing the CMakeLists.txt
Now that the package.xml, which contains meta information, has been tailored to your package, you are ready to move on in the tutorials. The CMakeLists.txt file created by catkin_create_pkg will be covered in the later tutorials about building ROS code.
Now that you’ve made a new ROS package, let’s build our ROS package.
Video Demonstration
Watch the video below to have more explanation on Custom Workspace and Package Creation with step by step guide .
Wiki: ROS/Tutorials/CreatingPackage (последним исправлял пользователь Muhammad Luqman 2021-09-30 16:31:23)