Ros2 create package

Ros2 create package DEFAULT

Creating your first ROS 2 package

You're reading the documentation for a version of ROS 2 that has reached its EOL (end-of-life), and is no longer officially supported. If you want up-to-date information, please have a look at Galactic.

Goal: Create a new package using either CMake or Python, and run its executable.

Tutorial level: Beginner

Time: 15 minutes

Background

1 What is a ROS 2 package?

A package can be considered a container for your ROS 2 code. If you want to be able to install your code or share it with others, then you’ll need it organized in a package. With packages, you can release your ROS 2 work and allow others to build and use it easily.

Package creation in ROS 2 uses ament as its build system and colcon as its build tool. You can create a package using either CMake or Python, which are officially supported, though other build types do exist.

2 What makes up a ROS 2 package?

ROS 2 Python and CMake packages each have their own minimum required contents:

  • file containing meta information about the package

  • file that describes how to build the code within the package

  • file containing meta information about the package

  • containing instructions for how to install the package

  • is required when a package has executables, so can find them

  • - a directory with the same name as your package, used by ROS 2 tools to find your package, contains

The simplest possible package may have a file structure that looks like:

my_package/ CMakeLists.txt package.xml
my_package/ setup.py package.xml resource/my_package

3 Packages in a workspace

A single workspace can contain as many packages as you want, each in their own folder. You can also have packages of different build types in one workspace (CMake, Python, etc.). You cannot have nested packages.

Best practice is to have a folder within your workspace, and to create your packages in there. This keeps the top level of the workspace “clean”.

A trivial workspace might look like:

workspace_folder/ src/ package_1/ CMakeLists.txt package.xml package_2/ setup.py package.xml resource/package_2 ... package_n/ CMakeLists.txt package.xml

Prerequisites

You should have a ROS 2 workspace after following the instructions in the previous tutorial. You will create your package in this workspace.

Tasks

1 Create a package

First, source your ROS 2 installation.

Let’s use the workspace you created in the previous tutorial, , for your new package.`

Make sure you are in the folder before running the package creation command.

The command syntax for creating a new package in ROS 2 is:

ros2 pkg create --build-type ament_cmake <package_name>
ros2 pkg create --build-type ament_python <package_name>

For this tutorial, you will use the optional argument which creates a simple Hello World type executable in the package.

Enter the following command in your terminal:

ros2 pkg create --build-type ament_cmake --node-name my_node my_package
ros2 pkg create --build-type ament_python --node-name my_node my_package

You will now have a new folder within your workspace’s directory called .

After running the command, your terminal will return the message:

going to create a new packagepackage name: my_packagedestination directory: /home/user/dev_ws/srcpackage format: 3version: 0.0.0description: TODO: Package descriptionmaintainer: ['<name> <email>']licenses: ['TODO: License declaration']build type: ament_cmakedependencies: []node_name: my_nodecreating folder ./my_packagecreating ./my_package/package.xmlcreating source and include foldercreating folder ./my_package/srccreating folder ./my_package/include/my_packagecreating ./my_package/CMakeLists.txtcreating ./my_package/src/my_node.cpp
going to create a new packagepackage name: my_packagedestination directory: /home/user/dev_ws/srcpackage format: 3version: 0.0.0description: TODO: Package descriptionmaintainer: ['<name> <email>']licenses: ['TODO: License declaration']build type: ament_pythondependencies: []node_name: my_nodecreating folder ./my_packagecreating ./my_package/package.xmlcreating source foldercreating folder ./my_package/my_packagecreating ./my_package/setup.pycreating ./my_package/setup.cfgcreating folder ./my_package/resourcecreating ./my_package/resource/my_packagecreating ./my_package/my_package/__init__.pycreating folder ./my_package/testcreating ./my_package/test/test_copyright.pycreating ./my_package/test/test_flake8.pycreating ./my_package/test/test_pep257.pycreating ./my_package/my_package/my_node.py

You can see the automatically generated files for the new package.

2 Build a package

Putting packages in a workspace is especially valuable because you can build many packages at once by running in the workspace root. Otherwise, you would have to build each package individually.

Return to the root of your workspace:

Now you can build your packages:

colcon build --merge-install

Windows doesn’t allow long paths, so will combine all the paths into the directory.

Recall from the last tutorial that you also have the packages in your . You might’ve noticed that running also built the package. That’s fine when you only have a few packages in your workspace, but when there are many packages, can take a long time.

To build only the package next time, you can run:

colcon build --packages-select my_package

3 Source the setup file

To use your new package and executable, first open a new terminal and source your main ROS 2 installation.

Then, from inside the directory, run the following command to source your workspace:

call install/local_setup.bat

Now that your workspace has been added to your path, you will be able to use your new package’s executables.

4 Use the package

To run the executable you created using the argument during package creation, enter the command:

ros2 run my_package my_node

Which will return a message to your terminal:

hello world my_package package

5 Examine package contents

Inside , you will see the files and folders that automatically generated:

CMakeLists.txt include package.xml src

is inside the directory. This is where all your custom C++ nodes will go in the future.

my_package package.xml resource setup.cfg setup.py test

is inside the directory. This is where all your custom Python nodes will go in the future.

6 Customize package.xml

You may have noticed in the return message after creating your package that the fields and contain notes. That’s because the package description and license declaration are not automatically set, but are required if you ever want to release your package. The field may also need to be filled in.

From , open using your preferred text editor:

1<?xml version="1.0"?> 2<?xml-model 3 href="http://download.ros.org/schema/package_format3.xsd" 4 schematypens="http://www.w3.org/2001/XMLSchema"?> 5<packageformat="3"> 6<name>my_package</name> 7<version>0.0.0</version> 8<description>TODO: Package description</description> 9<maintaineremail="[email protected]">user</maintainer>10<license>TODO: License declaration</license>1112<buildtool_depend>ament_cmake</buildtool_depend>1314<test_depend>ament_lint_auto</test_depend>15<test_depend>ament_lint_common</test_depend>1617<export>18<build_type>ament_cmake</build_type>19</export>20</package>
1<?xml version="1.0"?> 2<?xml-model 3 href="http://download.ros.org/schema/package_format3.xsd" 4 schematypens="http://www.w3.org/2001/XMLSchema"?> 5<packageformat="3"> 6<name>my_package</name> 7<version>0.0.0</version> 8<description>TODO: Package description</description> 9<maintaineremail="[email protected]">user</maintainer>10<license>TODO: License declaration</license>1112<buildtool_depend>ament_python</buildtool_depend>1314<test_depend>ament_copyright</test_depend>15<test_depend>ament_flake8</test_depend>16<test_depend>ament_pep257</test_depend>17<test_depend>python3-pytest</test_depend>1819<export>20<build_type>ament_python</build_type>21</export>22</package>

Input your name and email on line 7 if it hasn’t been automatically populated for you. Then, edit the description on line 6 to summarize the package:

<description>Beginner client libraries tutorials practice package</description>

Then, update the license on line 8. You can read more about open source licenses here.

Since this package is only for practice, it’s safe to use any license. We use :

<license>Apache License 2.0</license>

Don’t forget to save once you’re done editing.

Below the license tag, you will see some tag names ending with . This is where your would list its dependencies on other packages, for colcon to search for. is simple and doesn’t have any dependencies, but you will see this space being utilized in upcoming tutorials.

The file contains the same description, maintainer and license fields as , so you need to set those as well. They need to match exactly in both files. The version and name () also need to match exactly, and should be automatically populated in both files.

Open with your preferred text editor.

1fromsetuptoolsimportsetup 2 3package_name='my_py_pkg' 4 5setup( 6name=package_name, 7version='0.0.0', 8packages=[package_name], 9data_files=[10('share/ament_index/resource_index/packages',11['resource/'+package_name]),12('share/'+package_name,['package.xml']),13],14install_requires=['setuptools'],15zip_safe=True,16maintainer='TODO',17maintainer_email='TODO',18description='TODO: Package description',19license='TODO: License declaration',20tests_require=['pytest'],21entry_points={22'console_scripts':[23'my_node = my_py_pkg.my_node:main'24],25},26)

Edit lines 16-19 to match .

Don’t forget to save the file.

Summary

You’ve created a package to organize your code and make it easy to use for others.

Your package was automatically populated with the necessary files, and then you used colcon to build it so you can use its executables in your local environment.

Next steps

Next, let’s add something meaningful to a package. You’ll start with a simple publisher/subscriber system, which you can choose to write in either C++ or Python.


© Copyright 2021, Open Robotics.

Built with Sphinx using a theme provided by Read the Docs.
Sours: http://docs.ros.org.ros.informatik.uni-freiburg.de/en/crystal/Tutorials/Creating-Your-First-ROS2-Package.html

In this tutorial you’ll learn how to create and setup a ROS2 Cpp package.

I will explain every step, what every file does, how to install nodes and launch files. This will give you a good foundation for any future ROS2 Cpp package you create.

Let’s get started!

Setup your ROS2 Cpp package

Before you can create a ROS2 Python package, make sure you have :

  • correctly installed ROS2,
  • setup your environment (add in your .bashrc – don’t forget to replace “ROS_VERSION”),
  • and created a ROS2 workspace ().

Now, to create a Cpp package, execute:

$ cd ~/ros2_ws/src/ $ ros2 pkg create my_cpp_pkg --build-type ament_cmake going to create a new package package name: my_cpp_pkg destination directory: /home/user/ros2_ws/src package format: 3 version: 0.0.0 description: TODO: Package description maintainer: ['Name <[email protected]>'] licenses: ['TODO: License declaration'] build type: ament_cmake dependencies: [] creating folder ./my_cpp_pkg creating ./my_cpp_pkg/package.xml creating source and include folder creating folder ./my_cpp_pkg/src creating folder ./my_cpp_pkg/include/my_cpp_pkg creating ./my_cpp_pkg/CMakeLists.txt

will create a bunch of files required for a ROS2 package. Thanks to the option, only files specific to a Cpp package will be created.


You are learning ROS2...

As a complete beginner? Check out ROS2 For Beginners and learn ROS2 in 1 week.

As a ROS1 developer? Check out Learn ROS2 as a ROS1 Developer and Migrate Your ROS Projects.

Actually, you get those 2 courses for FREE for 14 days! Just click on one of the links above.


Here’s how the package looks like now:

my_cpp_pkg/ ├── CMakeLists.txt ├── include │   └── my_cpp_pkg ├── package.xml └── src

Explanation of files inside a ROS2 Cpp package

Let’s see what each file/folder does.

package.xml

Use this file to provide some general information about the package, and also specify which dependencies are required.

<?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>my_cpp_pkg</name> <version>0.0.0</version> <description>TODO: Package description</description> <maintainer email="[email protected]">Name</maintainer> <license>TODO: License declaration</license> <buildtool_depend>ament_cmake</buildtool_depend> <test_depend>ament_lint_auto</test_depend> <test_depend>ament_lint_common</test_depend> <export> <build_type>ament_cmake</build_type> </export> </package>

If you ever share or publish your package, you’ll need to edit 4 lines in order to provide more information:

  • version.
  • description: quickly say what your package does.
  • maintainer: fill in your name and email so that people can reach to you in case they have an issue with the package. You can also add an author tag in addition to the maintainer tag, if for example you wrote the package but someone else is in charge of maintaining it. And you can of course have multiple author and maintainer tags.
  • license: especially useful if you publish your project online. Having a license tells people what they can do (and can’t do) with your package.

Of course the package will correctly work even if you don’t edit those lines now, but don’t forget to add required info before you share your work.

CMakeLists.txt

In this file you’ll tell the compiler how to create your nodes, where to install them, where to install other files, how to link dependencies, etc.

By default CMakeLists.txt is already filled with the basics. You can clean it up a bit so it doesn’t become bloated too soon.

Here’s the minimal CMakeLists.txt I use. I removed the comments, the “Default to C99” section (since we’ll only use Cpp 14), and the test sections. Note: testing is very important. In this tutorial we only cover how to write minimal code, so we don’t need tests.

cmake_minimum_required(VERSION 3.5) project(my_cpp_pkg) if(NOT CMAKE_CXX_STANDARD) set(CMAKE_CXX_STANDARD 14) endif() if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") add_compile_options(-Wall -Wextra -Wpedantic) endif() find_package(ament_cmake REQUIRED) ament_package()

From there, place the additions you’ll make between and .

include/<package_name>/ folder

In ROS2 the recommended way to write nodes is to use OOP. Thus in this folder you’ll write the .hpp files containing class and method declarations for your nodes, as well as library headers you wish to export.

For our example this folder is named “include/my_cpp_package/”.

src/ folder

In this src/ folder you’ll write the implementation for the classes you create.

Also this will be the place to write standalone nodes and main() functions that you want to execute.

Compile your package

To compile your package, navigate into your ROS2 workspace and use . Add the option so you only build this package (this can save you some time if you have many other packages in your workspace).

$ colcon build --packages-select my_cpp_pkg Starting >>> my_cpp_pkg Finished <<< my_cpp_pkg [1.71s] Summary: 1 package finished [1.84s]

This will compile any Cpp executable you defined in CMakeLists.txt, and install them (+ some other files) into the install/ folder of your workspace.

Build a node inside a ROS2 Cpp package

Well now you know what’s inside your Cpp package. Let’s see how you can create a Cpp node in this package, compile it, and run it.

Create a Cpp file inside the src/ directory of your package.

$ cd ~/ros2_ws/src/my_cpp_pkg/src/ $ touch my_cpp_node.cpp

Here’s a simple Cpp node for the purpose of this tutorial.

#include "rclcpp/rclcpp.hpp" class MyNode : public rclcpp::Node { public: MyNode() : Node("my_node") { RCLCPP_INFO(this->get_logger(), "Hello cpp"); } private: }; int main(int argc, char **argv) { rclcpp::init(argc, argv); auto node = std::make_shared<MyNode>(); rclcpp::spin(node); rclcpp::shutdown(); }

This node does just one thing: say Hello when it’s started, and that’s it. Then it spins until you kill it. For more info about how to write Cpp node, check out this ROS2 Cpp node tutorial.

Add those lines into your CMakeLists.txt, between and .

... find_package(rclcpp REQUIRED) add_executable(test_node src/my_cpp_node.cpp) ament_target_dependencies(test_node rclcpp) install(TARGETS test_node DESTINATION lib/${PROJECT_NAME} ) ...

This will create an executable named “test_node”, from the file you created inside the src/ folder. This “test_node” executable will be installed into ~/ros2_ws/install/my_cpp_pkg/lib/my_cpp_pkg/.

Make sure you don’t mix the executable name (“test_node”), the source file name (“my_cpp_node”), and the node name (“my_node”, defined in the source file). If you want though, you can make them 3 identical, this will also work – but be careful about not mixing things up.

Note: if you want to split your file, one .hpp and one .cpp, and place the .hpp in the include/my_cpp_package/ directory, then you’ll need to add this line: , just after the lines. Otherwise the compiler won’t look into the include/ folder and you’ll get an error.

One final addition: add just after in your package.xml file.

Now you can compile your package with .

Open a new terminal, source your environment, and run your node:

$ ros2 run my_cpp_pkg test_node [INFO] [my_node]: Hello cpp

Add other files in your ROS2 Cpp package

You can install any file you want from your package, you’re absolutely not limited to Cpp nodes. Installing a file, here, simply means that it will be copied into the install/ folder of your ROS2 workspace.

Let’s see an example with some of the most used ones: launch files and YAML config files.

Launch files

Take the habit of placing your launch files inside a launch/ folder. So, create a launch/ folder at the root of your package.

$ cd ~/ros2_ws/src/my_cpp_pkg/ $ mkdir launch

To install your launch files you’ll need to add this to your CMakeLists.txt:

... install(DIRECTORY launch DESTINATION share/${PROJECT_NAME} ) ...

The launch/ folder will be copied and install into ~/ros2_ws/install/my_cpp_pkg/share/my_cpp_pkg/launch/.

You only need to configure this once for all launch files.

YAML config files

The technique is the same as for launch files.

First, create a config/ folder at the root of your package.

$ cd ~/ros2_ws/src/my_cpp_pkg/ $ mkdir config

And add this to your CMakeLists.txt:

... install(DIRECTORY config DESTINATION share/${PROJECT_NAME} ) ...

After the compilation you will find YAML files inside the ~/ros2_ws/install/my_cpp_pkg/share/my_cpp_pkg/config/ folder.

Now, for any other file or folder you wish to install from your ROS2 Cpp package, you can do the same.

ROS2 Cpp package: going further

In this tutorial you’ve seen how to create, configure, and compile a ROS2 Cpp package, with nodes, launch files, and YAML config files.

Here’s the final architecture that we have after all those steps.

my_cpp_pkg/ ├── CMakeLists.txt ├── config │   └── test.yaml ├── include │   └── my_cpp_pkg ├── launch │   └── test.launch.py ├── package.xml └── src └── my_cpp_node.cpp

With this foundation you’re ready to deal with complete ROS2 applications in Cpp.

To go further, learn how to:

Categories ROS2 TutorialsSours: https://roboticsbackend.com/create-a-ros2-cpp-package/
  1. Scholarship stock photo
  2. Volkswagen beetle buggy
  3. Soda crate shelf
  4. Akhal teke photos

ROS2 Tutorials #4: How to create a ROS2 Package for C++ [NEW]

About

In this post, you will learn how to create a simple ROS2 package for C++. You don’t need a ROS2 installation for this, as we will use the ROS Development Studio (ROSDS), an online platform that provides access to ROS (1 or 2) computers and other powerful ROS tools within a browser!

PS: If you have ROS2 installed locally on your machine, you can skip Step 1.

Step 1: Create a Project (ROSject) on ROSDS

Head to http://rosds.online and create a project with a similar configuration as the one shown below. You can change the details as you like, but please ensure you select “Ubuntu 18.04 + ROS2 Crystal” under “Configuration”.

Once done with that, open your ROSject. This might take a few moments, please be patient.

Step 2: Source the ROS2 workspace

Once the ROSject is open, head to the Tools menu and pick the Shell tool (if on your local PC just fire up a terminal) and run the following command to source the workspace:

user:~$ source /opt/ros/crystal/setup.bash ROS_DISTRO was set to 'melodic' before. Please make sure that the environment does not mix paths from different distributions. user:~$

If you get that  warning, just ignore it.

Step 3: Create a ROS2 package in your ROS2 workspace

The syntax for creating a ROS2 package is .

In the same terminal as in Step 2, change to your ROS2 workspace  directory and create a package there:

user:~$ cd ros2_ws/src user:~/ros2_ws/src$ ros2 pkg create ros2_cpp_pkg --build-type ament_cmake --dependencies rclcpp going to create a new package package name: ros2_cpp_pkg destination directory: /home/user/ros2_ws/src package format: 2 version: 0.0.0 description: TODO: Package description maintainer: ['user <[email protected]>'] licenses: ['TODO: License declaration'] build type: ament_cmake dependencies: ['rclcpp'] creating folder ./ros2_cpp_pkg creating ./ros2_cpp_pkg/package.xml creating source and include folder creating folder ./ros2_cpp_pkg/src creating folder ./ros2_cpp_pkg/include/ros2_cpp_pkg creating ./ros2_cpp_pkg/CMakeLists.txt user:~/ros2_ws/src$

Step 4: Create C++ code inside the package

Create a file named  inside the new package:

user:~/ros2_ws/src$ cd ros2_cpp_pkg/src user:~/ros2_ws/src/ros2_cpp_pkg/src$ touch ros2_cpp_code.cpp user:~/ros2_ws/src/ros2_cpp_pkg/src$

Pick the IDE from the Tools menu, locate the C++ file and paste in the following code:

#include "rclcpp/rclcpp.hpp" int main(int argc, char *argv[]) { rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("ObiWan"); RCLCPP_INFO(node->get_logger(), "Help me Obi-Wan Kenobi, you're my only hope"); rclcpp::shutdown(); return 0; }

In the IDE, open up the  and paste the following line at the bottom of the file. We are doing this to ensure the C++ file will be properly detected and compiled.

add_executable(cpp_code src/ros2_cpp_code.cpp) ament_target_dependencies(cpp_code rclcpp) install(TARGETS cpp_code DESTINATION lib/${PROJECT_NAME} )

Step 5: Compile and test-run the package

Now your package is ready to compile…so compile it and source the workspace!

user:~/ros2_ws/src/ros2_cpp_pkg/src$ cd /home/user/ros2_ws user:~/ros2_ws$ colcon build --symlink-install Starting >>> ros2_cpp_pkg Finished <<< ros2_cpp_pkg [21.9s] Summary: 1 package finished [22.0s] user:~/ros2_ws$ source install/setup.bash # source the workspace ROS_DISTRO was set to 'crystal' before. Please make sure that the environment does not mix paths from different distributions. ROS_DISTRO was set to 'melodic' before. Please make sure that the environment does not mix paths from different distributions. user:~/ros2_ws$

Great. Now test-run it.  You should have the string mentioned in the C++ code printed to the terminal output:

user:~/ros2_ws$ ros2 run ros2_cpp_pkg cpp_code [INFO] [ObiWan]: Help me Obi-Wan Kenobi, you're my only hope user:~/ros2_ws$

Done!

Extra 1: ROSject link

Get the ROSject containing all code used in the post in the following link: http://www.rosject.io/l/bce4ffd/!

Extra 2: Video

Prefer to watch a video demonstrating the steps above? We have one for you below!

Related Resources

Feedback

Did you like this post? Do you have questions about what is explained? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.

If you want to learn about other ROS topics, please let us know in the comments area and we will do a video or post about it 🙂

Sours: https://www.theconstructsim.com/ros2-tutorials-create-a-ros2-package-cpp/
ROS2 Tutorials #6: How to create a ROS2 Launch File [NEW]

Creating your first ROS 2 package

You're reading the documentation for an older, but still supported, version of ROS 2. For information on the latest version, please have a look at Galactic.

Goal: Create a new package using either CMake or Python, and run its executable.

Tutorial level: Beginner

Time: 15 minutes

Background

1 What is a ROS 2 package?

A package can be considered a container for your ROS 2 code. If you want to be able to install your code or share it with others, then you’ll need it organized in a package. With packages, you can release your ROS 2 work and allow others to build and use it easily.

Package creation in ROS 2 uses ament as its build system and colcon as its build tool. You can create a package using either CMake or Python, which are officially supported, though other build types do exist.

2 What makes up a ROS 2 package?

ROS 2 Python and CMake packages each have their own minimum required contents:

  • file containing meta information about the package

  • file that describes how to build the code within the package

  • file containing meta information about the package

  • containing instructions for how to install the package

  • is required when a package has executables, so can find them

  • - a directory with the same name as your package, used by ROS 2 tools to find your package, contains

The simplest possible package may have a file structure that looks like:

my_package/ CMakeLists.txt package.xml
my_package/ setup.py package.xml resource/my_package

3 Packages in a workspace

A single workspace can contain as many packages as you want, each in their own folder. You can also have packages of different build types in one workspace (CMake, Python, etc.). You cannot have nested packages.

Best practice is to have a folder within your workspace, and to create your packages in there. This keeps the top level of the workspace “clean”.

A trivial workspace might look like:

workspace_folder/ src/ package_1/ CMakeLists.txt package.xml package_2/ setup.py package.xml resource/package_2 ... package_n/ CMakeLists.txt package.xml

Prerequisites

You should have a ROS 2 workspace after following the instructions in the previous tutorial. You will create your package in this workspace.

Tasks

1 Create a package

First, source your ROS 2 installation.

Let’s use the workspace you created in the previous tutorial, , for your new package.`

Make sure you are in the folder before running the package creation command.

The command syntax for creating a new package in ROS 2 is:

ros2 pkg create --build-type ament_cmake <package_name>
ros2 pkg create --build-type ament_python <package_name>

For this tutorial, you will use the optional argument which creates a simple Hello World type executable in the package.

Enter the following command in your terminal:

ros2 pkg create --build-type ament_cmake --node-name my_node my_package
ros2 pkg create --build-type ament_python --node-name my_node my_package

You will now have a new folder within your workspace’s directory called .

After running the command, your terminal will return the message:

going to create a new packagepackage name: my_packagedestination directory: /home/user/dev_ws/srcpackage format: 3version: 0.0.0description: TODO: Package descriptionmaintainer: ['<name> <email>']licenses: ['TODO: License declaration']build type: ament_cmakedependencies: []node_name: my_nodecreating folder ./my_packagecreating ./my_package/package.xmlcreating source and include foldercreating folder ./my_package/srccreating folder ./my_package/include/my_packagecreating ./my_package/CMakeLists.txtcreating ./my_package/src/my_node.cpp
going to create a new packagepackage name: my_packagedestination directory: /home/user/dev_ws/srcpackage format: 3version: 0.0.0description: TODO: Package descriptionmaintainer: ['<name> <email>']licenses: ['TODO: License declaration']build type: ament_pythondependencies: []node_name: my_nodecreating folder ./my_packagecreating ./my_package/package.xmlcreating source foldercreating folder ./my_package/my_packagecreating ./my_package/setup.pycreating ./my_package/setup.cfgcreating folder ./my_package/resourcecreating ./my_package/resource/my_packagecreating ./my_package/my_package/__init__.pycreating folder ./my_package/testcreating ./my_package/test/test_copyright.pycreating ./my_package/test/test_flake8.pycreating ./my_package/test/test_pep257.pycreating ./my_package/my_package/my_node.py

You can see the automatically generated files for the new package.

2 Build a package

Putting packages in a workspace is especially valuable because you can build many packages at once by running in the workspace root. Otherwise, you would have to build each package individually.

Return to the root of your workspace:

Now you can build your packages:

colcon build --merge-install

Windows doesn’t allow long paths, so will combine all the paths into the directory.

Recall from the last tutorial that you also have the packages in your . You might’ve noticed that running also built the package. That’s fine when you only have a few packages in your workspace, but when there are many packages, can take a long time.

To build only the package next time, you can run:

colcon build --packages-select my_package

3 Source the setup file

To use your new package and executable, first open a new terminal and source your main ROS 2 installation.

Then, from inside the directory, run the following command to source your workspace:

call install/local_setup.bat

Now that your workspace has been added to your path, you will be able to use your new package’s executables.

4 Use the package

To run the executable you created using the argument during package creation, enter the command:

ros2 run my_package my_node

Which will return a message to your terminal:

hello world my_package package

5 Examine package contents

Inside , you will see the files and folders that automatically generated:

CMakeLists.txt include package.xml src

is inside the directory. This is where all your custom C++ nodes will go in the future.

my_package package.xml resource setup.cfg setup.py test

is inside the directory. This is where all your custom Python nodes will go in the future.

6 Customize package.xml

You may have noticed in the return message after creating your package that the fields and contain notes. That’s because the package description and license declaration are not automatically set, but are required if you ever want to release your package. The field may also need to be filled in.

From , open using your preferred text editor:

<?xml version="1.0"?><?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?><packageformat="3"><name>my_package</name><version>0.0.0</version><description>TODO: Package description</description><maintaineremail="[email protected]">user</maintainer><license>TODO: License declaration</license><buildtool_depend>ament_cmake</buildtool_depend><test_depend>ament_lint_auto</test_depend><test_depend>ament_lint_common</test_depend><export><build_type>ament_cmake</build_type></export></package>
<?xml version="1.0"?><?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?><packageformat="3"><name>my_package</name><version>0.0.0</version><description>TODO: Package description</description><maintaineremail="[email protected]">user</maintainer><license>TODO: License declaration</license><test_depend>ament_copyright</test_depend><test_depend>ament_flake8</test_depend><test_depend>ament_pep257</test_depend><test_depend>python3-pytest</test_depend><export><build_type>ament_python</build_type></export></package>

Input your name and email on the line if it hasn’t been automatically populated for you. Then, edit the line to summarize the package:

<description>Beginner client libraries tutorials practice package</description>

Then update the line. You can read more about open source licenses here. Since this package is only for practice, it’s safe to use any license. We use :

<license>Apache License 2.0</license>

Don’t forget to save once you’re done editing.

Below the license tag, you will see some tag names ending with . This is where your would list its dependencies on other packages, for colcon to search for. is simple and doesn’t have any dependencies, but you will see this space being utilized in upcoming tutorials.

The file contains the same description, maintainer and license fields as , so you need to set those as well. They need to match exactly in both files. The version and name () also need to match exactly, and should be automatically populated in both files.

Open with your preferred text editor.

fromsetuptoolsimportsetuppackage_name='my_py_pkg'setup(name=package_name,version='0.0.0',packages=[package_name],data_files=[('share/ament_index/resource_index/packages',['resource/'+package_name]),('share/'+package_name,['package.xml']),],install_requires=['setuptools'],zip_safe=True,maintainer='TODO',maintainer_email='TODO',description='TODO: Package description',license='TODO: License declaration',tests_require=['pytest'],entry_points={'console_scripts':['my_node = my_py_pkg.my_node:main'],},)

Edit the , , and lines to match .

Don’t forget to save the file.

Summary

You’ve created a package to organize your code and make it easy to use for others.

Your package was automatically populated with the necessary files, and then you used colcon to build it so you can use its executables in your local environment.

Next steps

Next, let’s add something meaningful to a package. You’ll start with a simple publisher/subscriber system, which you can choose to write in either C++ or Python.


© Copyright 2021, Open Robotics.

Built with Sphinx using a theme provided by Read the Docs.
Sours: https://docs.ros.org/en/foxy/Tutorials/Creating-Your-First-ROS2-Package.html

Package ros2 create

ROS2 Tutorials #5: How to create a ROS2 Package for Python

About

In this post, you will learn how to create a simple ROS2 package for Python. You don’t need a ROS2 installation for this as we will use the ROS Development Studio (ROSDS), an online platform that provides access to ROS (1 or 2) computers and other powerful ROS tools within a browser!

PS: If you have ROS2 installed locally on your machine, you can skip Step 1.

Step 1: Create a Project (ROSject) on ROSDS

Head to http://rosds.online and create a project with a similar configuration as the one shown below. You can change the details as you like, but please ensure you select “Ubuntu 18.04 + ROS2 Crystal” under “Configuration”.

Once done with that, open your ROSject. This might take a few moments, please be patient.

Step 2: Source the ROS2 workspace

Once the ROSject is open, head to the Tools menu and pick the Shell tool (if on your local PC just fire up a terminal) and run the following command to source the workspace:

user:~$ source /opt/ros/crystal/setup.bash ROS_DISTRO was set to 'melodic' before. Please make sure that the environment does not mix paths from different distributions. user:~$

If you get that  warning, just ignore it.

Step 3: Create a ROS2 Python package in your ROS2 workspace

The syntax for creating a ROS2 Python package is .

In the same terminal as in Step 2, change to your ROS2 workspace  directory and create a package there:

user:~$ cd ros2_ws/src user:~/ros2_ws/src$ ros2 pkg create ros2_demo_py going to create a new package package name: ros2_demo_py destination directory: /home/user/ros2_ws/src package format: 2 version: 0.0.0 description: TODO: Package description maintainer: ['user <[email protected]>'] licenses: ['TODO: License declaration'] build type: ament_cmake dependencies: [] creating folder ./ros2_demo_py creating ./ros2_demo_py/package.xml creating source and include folder creating folder ./ros2_demo_py/src creating folder ./ros2_demo_py/include/ros2_demo_py creating ./ros2_demo_py/CMakeLists.txt user:~/ros2_ws/src$

Step 4: Delete  , create  and  and edit

Unlike ROS1, ROS2 Python packages don’t use , but a new  file. Let’s create one here. In the Shell:

user:~/ros2_ws/src$ cd ros2_demo_py/ user:~/ros2_ws/src/ros2_demo_py$ rm CMakeLists.txt user:~/ros2_ws/src/ros2_demo_py$ touch setup.py user:~/ros2_ws/src/ros2_demo_py$ touch setup.cfg user:~/ros2_ws/src/ros2_demo_py$

Fire up the IDE, locate the  file and paste in the following code:

from setuptools import setup package_name = 'ros2_demo_py' setup( name=package_name, version='0.7.0', packages=[package_name], install_requires=['setuptools'], zip_safe=True, author='You', author_email='[email protected]', maintainer='YourFirstname Lastname', maintainer_email='[email protected]', keywords=['ROS'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Topic :: Software Development', ], description='A simple ROS2 Python package', license='Apache License, Version 2.0', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'demo = ros2_demo_py.demo:main' ], }, )

Locate the  file and paste in the following code:

[develop] script-dir=$base/lib/ros2_demo_py [install] install-scripts=$base/lib/ros2_demo_py

Locate  and replace the contents with this snippet:

<?xml version="1.0"?> <?xml-model href="http://download.ros.org/schema/package_format2.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?> <package format="2"> <name>ros2_demo_py</name> <version>0.7.3</version> <description>A simple ROS2 Python package</description> <maintainer email="[email protected]">Shane Loretz</maintainer> <license>Apache License 2.0</license> <exec_depend>rclpy</exec_depend> <exec_depend>std_msgs</exec_depend> <!-- These test dependencies are optional Their purpose is to make sure that the code passes the linters --> <test_depend>ament_copyright</test_depend> <test_depend>ament_flake8</test_depend> <test_depend>ament_pep257</test_depend> <test_depend>python3-pytest</test_depend> <export> <build_type>ament_python</build_type> </export> </package>

Step 5: Create the Python code

In the Shell, run the following commands:

user:~/ros2_ws/src/ros2_demo_py$ mkdir ros2_demo_py && cd ros2_demo_py user:~/ros2_ws/src/ros2_demo_py/ros2_demo_py$ touch demo.py user:~/ros2_ws/src/ros2_demo_py/ros2_demo_py$ touch __init__.py user:~/ros2_ws/src/ros2_demo_py/ros2_demo_py$

We created the  file so that the folder could be recognized as a python module directory.

Locate the  file, open it in the IDE and paste in the following code:

# Copyright 2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import rclpy from rclpy.node import Node from std_msgs.msg import String class MinimalPublisher(Node): def __init__(self): super().__init__('minimal_publisher') self.publisher_ = self.create_publisher(String, 'topic') timer_period = 0.5 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0 def timer_callback(self): msg = String() msg.data = 'Hello World: %d' % self.i self.publisher_.publish(msg) self.get_logger().info('Publishing: "%s"' % msg.data) self.i += 1 def main(args=None): rclpy.init(args=args) minimal_publisher = MinimalPublisher() rclpy.spin(minimal_publisher) # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) minimal_publisher.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()

Step 6: Compile the package and source the workspace

We have created all the files needed. Now let’s compile.

user:~/ros2_ws/src/ros2_demo_py/ros2_demo_py$ cd /home/user/ros2_ws/ user:~/ros2_ws$ colcon build --symlink-install Starting >>> ros2_demo_py Finished <<< ros2_demo_py [0.78s] Summary: 1 package finished [0.90s] user:~/ros2_ws$ source install/setup.bash # source the workspace user:~/ros2_ws$

Step 7: Test-run the package

Here comes the moment of truth…will it run?

user:~/ros2_ws$ ros2 run ros2_demo_py demo [INFO] [minimal_publisher]: Publishing: "Hello World: 0" [INFO] [minimal_publisher]: Publishing: "Hello World: 1" [INFO] [minimal_publisher]: Publishing: "Hello World: 2" [INFO] [minimal_publisher]: Publishing: "Hello World: 3" [INFO] [minimal_publisher]: Publishing: "Hello World: 4" ...

Great, it ran! We’re done here!!

Extra 1: ROSject link

Get the ROSject containing all code used in the post in the following link: http://www.rosject.io/l/bd0cfbd/

Extra 2: Video

Prefer to watch a video demonstrating the steps above? We have one for you below!

Related Resources

Feedback

Did you like this post? Do you have questions about what is explained? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.

If you want to learn about other ROS topics, please let us know in the comments area and we will do a video or post about it ?

 

Code edited by Bayode Aderinola

Sours: https://www.theconstructsim.com/ros2-tutorials-5-how-to-create-a-ros2-package-for-python-update/
ROS2 Tutorials #5: How to create a ROS2 Package for Python [UPDATE]

Quick start¶

This section gives a high-level overview of how to use the command.

TL;DR¶

The following is an example workflow and sequence of commands using default settings:

$ mkdir -p /tmp/workspace/src # Make a workspace directory with a src subdirectory $ cd /tmp/workspace # Change directory to the workspace root $ <...> # Populate the `src` directory with packages $ colcon list # List all packages in the workspace $ colcon graph # List all packages in the workspace in topological order# and visualize their dependencies $ colcon build # Build all packages in the workspace $ colcon test# Test all packages in the workspace $ colcon test-result --all # Enumerate all test results $ . install/local_setup.bash # Setup the environment to use the built packages $ <...> # Use the built packages

The most commonly used arguments for the and verbs are to only process a specific package or a specific package including all the recursive dependencies it needs.

$ colcon build --packages-select <name-of-pkg> $ colcon build --packages-up-to <name-of-pkg>

Note

The log files of the latest invocation can be found in the log directory which is by default in .

Note

If you want to see the output of each package after it finished you can pass the argument .

Build ROS 2 packages¶

The process of building ROS 2 packages is described in the ROS 2 building from source instructions. Using instead of the recommended tool only changes a couple of the steps.

Instead of invoking you can invoke .

In order to use the built packages you need to source the script mentioned in the instructions.

For detailed information how command line arguments of are mapped to please see the ament_tools migration guide.

Build ROS 1 packages¶

The process of building ROS 1 packages is described in the distro specific building from source instructions. Using instead of the recommended tool only changes a couple of the steps.

Note

requires at least version 0.7.13 of which provides a new CMake option the tool uses.

Instead of invoking you can invoke .

Note

does by design not support the concept of a “devel space” as it exists in ROS 1. Instead it requires each package to be installed so each package must declare an install step in order to work with .

In order to use the built packages you need to source the rather than the script mentioned in the instructions. For the command would be:

$ source install/local_setup.bash

For detailed information how command line arguments of are mapped to please see the catkin_make_isolated migration guide. For detailed information how command line arguments of are mapped to please see the catkin_tools migration guide.

Test ROS 1 packages¶

As of version 0.3.6 the verb builds the test targets for ROS 1 packages implicitly (when available).

In earlier versions you must build the custom target explicitly:

$ colcon build --cmake-target tests

Build Gazebo and the ignition packages¶

In more recent versions Gazebo has been refactored to split out a lot of the functionality into ignition libraries. While that makes the project more modular it also increases the effort necessary to build all these packages from source. can make this process easy again.

In order to build a specific Gazebo version you need the right versions of the ignition libraries. At the time of writing Gazebo 9 is the latest release so we will use that for the purpose of this example. The following steps use a to specify the various repositories with specific branches.

$ mkdir -p /tmp/gazebo/src &&cd /tmp/gazebo $ wget https://gist.githubusercontent.com/dirk-thomas/6c1ca2a7f5f8c70ce7d3e1ef10a9f678/raw/490aaba72321284af956c9db12f9ef1550ef88cf/Gazebo9.repos $ vcs import src < Gazebo9.repos

Note

The Gist containing the repository list should be replaced with an “official” URL coming from the Gazebo project.

Before building the workspace with the steps also fetch some additional metadata for Gazebo from a public repository.

$ colcon metadata add default https://raw.githubusercontent.com/colcon/colcon-metadata-repository/master/index.yaml $ colcon metadata update $ colcon build

To run Gazebo, which requires environment variables for e.g., the model paths, the same commands as for other packages can be used. Using the additional metadata the source script will also automatically source the Gazebo specific file which defines these environment variables.

$ . install/local_setup.bash $ gazebo
Sours: https://colcon.readthedocs.io/en/released/user/quick-start.html

You will also like:

You Will Need

In this post, we will learn how to create a package inROS 2 Foxy Fitzroy.

Software in ROS 2 is organized into packages. Each package might contain a mixture of code (e.g. ROS 2 nodes), data, libraries, images, documentation, etc. Every program you write in ROS 2 will need to be inside a package.

ROS 2 packages promote software reuse. The goal of a ROS 2 package is to be large enough to provide a specific useful functionality, but not so large and complicated that nobody wants to reuse it for their own project.

The official tutorial is located in the ROS 2 Foxy documentation, but we’ll run through the entire process step-by-step below.

In order to complete this tutorial, you will need:

You have already created a workspace.

Open a new terminal window, and navigate to the src directory of your workspace:

cd ~/dev_ws/src

Now let’s create a package named my_package.

Type this command to create a C++ package:

ros2 pkg create --build-type ament_cmake my_package

Type this command to create a Python package:

ros2 pkg create --build-type ament_python my_package

Your package named my_package has now been created.

create-a-new-package

We also could have added dependencies (i.e. other software packages our code might depend on) when we created our package:

ros2 pkg create --build-type ament_python my_package --dependencies rclpy image_transport cv_bridge sensor_msgs std_msgs opencv2

Return to the root of your workspace:

cd ~/dev_ws/

Build all packages in the workspace.

colcon build
2-package-build-successful

If you only want to build my_package and no other package in the workspace, you can type:

colcon build --packages-select my_package

That’s it! In the next tutorial, we will look at how to create publisher and subscriber nodes in ROS 2.

Sours: https://automaticaddison.com/how-to-create-a-package-ros-2-foxy-fitzroy/


1506 1507 1508 1509 1510