使用rosdep
来管理依赖关系
what is rosdep
它经常在构建工作区之前被调用,用于在工作区中安装包的依赖。
package.xml
package.xml
文件是rosdep
查找依赖关系的关键。package.xml
文件中的依赖项通常被称为rosdep keys
。
<depend>
在构建时和运行时为包提供的依赖。<build_depend>
只在构建时使用,运行时不使用。- 有了这种依赖关系,您的软件包的已安装二进制文件不需要安装特定的软件包.但是,如果您的包导出的头文件包含来自此依赖项的头文件,则可能会产生问题。 在这种情况下,你还需要
<build_export_depend>
。 - 如果您导出的头文件包含依赖项中的头文件,那么依赖于您的包的其他包将需要
<build_depend>
,这主要适用于头文件和CMake配置文件。 引用您导出的库的库或包也需要指定<depend>
,因为在执行时需要。 <exec_depend>
这个标签声明了共享库、可执行文件、Python模块、启动脚本和运行包时所需的其他文件的依赖关系。<test_depend>
该标签声明仅测试需要的依赖项。 这里的依赖项不应该与<build_depend> <exec_depend>
或<depend>
重复。
rosdep how work
rosdep
将检查其路径中的package.xml
文件或特定包,并查找其中存储的rosdep
密钥。然后,根据中央索引(central index)进行交叉引用这些keys,以在各种包管理器中找到适当的ROS包或软件库。最后,一旦找到软件包,它们就会安装并准备就绪!central index 即 rosdistro
。
如何在package.xml
中使用keys
-
如果你想依赖一个非ROS包,通常称为“系统依赖关系”,你需要找到特定库的密钥。一般来说,有两个相关的文件:
-
rosdep/base.yaml
包含apt
系统依赖项。 -
rosdep/python.yaml
包含python依赖项
-
-
要查找密钥,请在这些文件中搜索您的库并找到名称。这是放入
package.xml
文件的关键。
how to use
install
# 使用 ROS
sudo apt-get install python3-rosdep
# 不使用 ROS
sudo pip install rosdep
use
# 初始化
sudo rosdep init
rosdep update
# 安装依赖项 (通常这是在一个包含多个子功能包的工作空间中运行的)
rosdep install --from-paths src -y --ignore-src

# --from-paths src 指定用于检查package.xml文件以解析密钥的路径
# -y 所有提示都选择是
# --ignore-src 表示忽略安装依赖项
创建 action
create pkg
mkdir -p ~/ros2_ws/src && cd ros2_ws/src
ros2 pkg create action_tutorials_interfaces
.action
动作定义在.action
文件中,由三个部分组成。
请求消息从动作客户端发送到动作服务器,以启动新目标。
当目标完成时,结果消息从动作服务器发送到动作客户端。
反馈消息定期从动作服务器发送到动作客户端,其中包含有关目标的更新。
一个动作的实例通常被称为goal
。
# Request
---
# Result
---
# Feedback
假设我们要定义一个名为Fibonacci
的新动作来计算斐波那契数列。
cd ~/ros2_ws/src/action_tutorials_interfaces && mkdir action && cd action && touch Fibonacci.action
- ~/ros2_ws/src/action_tutorials_interfaces/action/Fibonacci.action
int32 order
---
int32[] sequence
---
int32[] partial_sequence
CMakeLists.txt
- ~/ros2_ws/src/action_tutorials_interfaces/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(action_tutorials_interfaces)
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rosidl_default_generators REQUIRED)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
# the following line skips the linter which checks for copyrights
# comment the line when a copyright and license is added to all source files
set(ament_cmake_copyright_FOUND TRUE)
# the following line skips cpplint (only works in a git repo)
# comment the line when this package is in a git repo and when
# a copyright and license is added to all source files
set(ament_cmake_cpplint_FOUND TRUE)
ament_lint_auto_find_test_dependencies()
endif()
rosidl_generate_interfaces(${PROJECT_NAME}
"action/Fibonacci.action"
)
ament_package()
package.xml
- ~/ros2_ws/src/action_tutorials_interfaces/package.xml
<?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>action_tutorials_interfaces</name>
<version>0.0.0</version>
<description>TODO: Package description</description>
<maintainer email="2162368104@qq.com">yin</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>
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<depend>action_msgs</depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
build
cd ~/ros2_ws && colcon build
之后,当我们引用新动作,我们引用全名action_tutorials_interfaces/action/Fibonacci
即可。
. install/setup.bash
ros2 interface show action_tutorials_interfaces/action/Fibonacci # 您应该看到Fibonacci动作定义打印到屏幕上。
action server and client
crate pkg
cd ~/ros2_ws/src && ros2 pkg create --dependencies action_tutorials_interfaces rclcpp rclcpp_action rclcpp_components -- action_tutorials_cpp
-
加入可见度控制
-
~/ros2_ws/src/action_tutorials_cpp/include/action_tutorials_cpp/visibility_control.h
#ifndef ACTION_TUTORIALS_CPP__VISIBILITY_CONTROL_H_
#define ACTION_TUTORIALS_CPP__VISIBILITY_CONTROL_H_
#ifdef __cplusplus
extern "C"
{
#endif
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define ACTION_TUTORIALS_CPP_EXPORT __attribute__ ((dllexport))
#define ACTION_TUTORIALS_CPP_IMPORT __attribute__ ((dllimport))
#else
#define ACTION_TUTORIALS_CPP_EXPORT __declspec(dllexport)
#define ACTION_TUTORIALS_CPP_IMPORT __declspec(dllimport)
#endif
#ifdef ACTION_TUTORIALS_CPP_BUILDING_DLL
#define ACTION_TUTORIALS_CPP_PUBLIC ACTION_TUTORIALS_CPP_EXPORT
#else
#define ACTION_TUTORIALS_CPP_PUBLIC ACTION_TUTORIALS_CPP_IMPORT
#endif
#define ACTION_TUTORIALS_CPP_PUBLIC_TYPE ACTION_TUTORIALS_CPP_PUBLIC
#define ACTION_TUTORIALS_CPP_LOCAL
#else
#define ACTION_TUTORIALS_CPP_EXPORT __attribute__ ((visibility("default")))
#define ACTION_TUTORIALS_CPP_IMPORT
#if __GNUC__ >= 4
#define ACTION_TUTORIALS_CPP_PUBLIC __attribute__ ((visibility("default")))
#define ACTION_TUTORIALS_CPP_LOCAL __attribute__ ((visibility("hidden")))
#else
#define ACTION_TUTORIALS_CPP_PUBLIC
#define ACTION_TUTORIALS_CPP_LOCAL
#endif
#define ACTION_TUTORIALS_CPP_PUBLIC_TYPE
#endif
#ifdef __cplusplus
}
#endif
#endif // ACTION_TUTORIALS_CPP__VISIBILITY_CONTROL_H_
fibonacci_action_server.cpp
- ~/ros2_ws/src/action_tutorials_cpp/src/fibonacci_action_server.cpp
#include <functional>
#include <memory>
#include <thread>
#include "action_tutorials_interfaces/action/fibonacci.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_action/rclcpp_action.hpp"
#include "rclcpp_components/register_node_macro.hpp"
#include "action_tutorials_cpp/visibility_control.h"
namespace action_tutorials_cpp
{
class FibonacciActionServer : public rclcpp::Node
{
public:
using Fibonacci = action_tutorials_interfaces::action::Fibonacci;
using GoalHandleFibonacci = rclcpp_action::ServerGoalHandle<Fibonacci>;
ACTION_TUTORIALS_CPP_PUBLIC
// 通过类的构造函数初始化节点
explicit FibonacciActionServer(const rclcpp::NodeOptions & options = rclcpp::NodeOptions())
: Node("fibonacci_action_server", options)
{
using namespace std::placeholders;
// 实例新的动作服务器
this->action_server_ = rclcpp_action::create_server<Fibonacci>(
this,
"fibonacci",
std::bind(&FibonacciActionServer::handle_goal, this, _1, _2),
std::bind(&FibonacciActionServer::handle_cancel, this, _1),
std::bind(&FibonacciActionServer::handle_accepted, this, _1));
/*
action服务器需要满足6个条件
1. action类型 Fibonacci
2. 一个添加action的ros2节点 this
3. action名称 fibonacci
4. 处理action的回调函数 handle_goal
5. 处理cancellation(取消)的回调函数 handle_cancel
6. 处理goal accept(接收目标)的回调函数 handle_accept
*/
}
private:
rclcpp_action::Server<Fibonacci>::SharedPtr action_server_;
// 处理新目标的回调函数 这个实现只是接受所有的目标
rclcpp_action::GoalResponse handle_goal(
const rclcpp_action::GoalUUID & uuid,
std::shared_ptr<const Fibonacci::Goal> goal)
{
RCLCPP_INFO(this->get_logger(), "Received goal request with order %d", goal->order);
(void)uuid;
return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
}
// 处理取消的回调函数 这个实现只是告诉顾客它接受了取消
rclcpp_action::CancelResponse handle_cancel(
const std::shared_ptr<GoalHandleFibonacci> goal_handle)
{
RCLCPP_INFO(this->get_logger(), "Received request to cancel goal");
(void)goal_handle;
return rclcpp_action::CancelResponse::ACCEPT;
}
// 此回调函数 接受一个新目标并开始处理它
void handle_accepted(const std::shared_ptr<GoalHandleFibonacci> goal_handle)
{
using namespace std::placeholders;
// 由于执行是一个长时间运行的操作,我们生成一个线程来执行实际的工作,并快速从handle_accepted返回。
std::thread{std::bind(&FibonacciActionServer::execute, this, _1), goal_handle}.detach();
}
// 所有进一步的处理和更新都在新线程中的execute方法中完成:
// 此工作线程每秒处理一个斐波那契序列的序列号,并为每个步骤发布反馈更新。当它完成处理后,它将goal_handle标记为成功,并退出。
void execute(const std::shared_ptr<GoalHandleFibonacci> goal_handle)
{
RCLCPP_INFO(this->get_logger(), "Executing goal");
rclcpp::Rate loop_rate(1);
const auto goal = goal_handle->get_goal();
auto feedback = std::make_shared<Fibonacci::Feedback>();
auto & sequence = feedback->partial_sequence;
sequence.push_back(0);
sequence.push_back(1);
auto result = std::make_shared<Fibonacci::Result>();
for (int i = 1; (i < goal->order) && rclcpp::ok(); ++i) {
// 检查是否有取消请求
if (goal_handle->is_canceling()) {
result->sequence = sequence;
goal_handle->canceled(result);
RCLCPP_INFO(this->get_logger(), "Goal canceled");
return;
}
// 更新序列
sequence.push_back(sequence[i] + sequence[i - 1]);
// 发布反馈
goal_handle->publish_feedback(feedback);
RCLCPP_INFO(this->get_logger(), "Publish feedback");
loop_rate.sleep();
}
// 查看目标是否完成
if (rclcpp::ok()) {
result->sequence = sequence;
goal_handle->succeed(result);
RCLCPP_INFO(this->get_logger(), "Goal succeeded");
}
}
}; // class FibonacciActionServer
} // namespace action_tutorials_cpp
RCLCPP_COMPONENTS_REGISTER_NODE(action_tutorials_cpp::FibonacciActionServer)
fibonacci_action_client.cpp
- ~/ros2_ws/src/action_tutorials_cpp/src/fibonacci_action_client.cpp
#include <functional>
#include <future>
#include <memory>
#include <string>
#include <sstream>
#include "action_tutorials_interfaces/action/fibonacci.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_action/rclcpp_action.hpp"
#include "rclcpp_components/register_node_macro.hpp"
namespace action_tutorials_cpp
{
class FibonacciActionClient : public rclcpp::Node
{
public:
using Fibonacci = action_tutorials_interfaces::action::Fibonacci;
using GoalHandleFibonacci = rclcpp_action::ClientGoalHandle<Fibonacci>;
// 通过类的构造函数初始化节点
explicit FibonacciActionClient(const rclcpp::NodeOptions & options)
: Node("fibonacci_action_client", options)
{
// 实例新的动作客户端
this->client_ptr_ = rclcpp_action::create_client<Fibonacci>(
this,
"fibonacci");
/*
action客户端需要满足三个条件
1. action类型 Fibonacci
2. 一个添加action的ros2节点 this
3. action名称 fibonacci
*/
// 实例化一个ROS计时器,它将仅仅调用已次send_goal
this->timer_ = this->create_wall_timer(
std::chrono::milliseconds(500),
std::bind(&FibonacciActionClient::send_goal, this));
}
/* @brief 当计时器到期时,它将调用send_goal
整个函数有以下作用
1. 取消计时器 (只允许被调用一次)
2. 等待服务器启动
3. 实例化一个新的 Fibonacci::Goal
4. 设置相应、反馈、和回调结果
5. 将目标发送到服务器
*/
void send_goal()
{
using namespace std::placeholders;
this->timer_->cancel();
if (!this->client_ptr_->wait_for_action_server()) {
RCLCPP_ERROR(this->get_logger(), "Action server not available after waiting");
rclcpp::shutdown();
}
auto goal_msg = Fibonacci::Goal();
goal_msg.order = 10;
RCLCPP_INFO(this->get_logger(), "Sending goal");
auto send_goal_options = rclcpp_action::Client<Fibonacci>::SendGoalOptions();
send_goal_options.goal_response_callback =
std::bind(&FibonacciActionClient::goal_response_callback, this, _1);
send_goal_options.feedback_callback =
std::bind(&FibonacciActionClient::feedback_callback, this, _1, _2);
send_goal_options.result_callback =
std::bind(&FibonacciActionClient::result_callback, this, _1);
this->client_ptr_->async_send_goal(goal_msg, send_goal_options);
}
private:
rclcpp_action::Client<Fibonacci>::SharedPtr client_ptr_;
rclcpp::TimerBase::SharedPtr timer_;
// 当服务器接收并接受目标时,它将向客户端发送响应。该响应由goal_response_callback处理
void goal_response_callback(const GoalHandleFibonacci::SharedPtr & goal_handle)
{
if (!goal_handle) {
RCLCPP_ERROR(this->get_logger(), "Goal was rejected by server");
} else {
RCLCPP_INFO(this->get_logger(), "Goal accepted by server, waiting for result");
}
}
// 假设目标被服务器接受并开始处理。 对客户的任何反馈将由feedback_callback函数处理:
void feedback_callback(
GoalHandleFibonacci::SharedPtr,
const std::shared_ptr<const Fibonacci::Feedback> feedback)
{
std::stringstream ss;
ss << "Next number in sequence received: ";
for (auto number : feedback->partial_sequence) {
ss << number << " ";
}
RCLCPP_INFO(this->get_logger(), ss.str().c_str());
}
// 当服务器完成处理后,它将返回一个结果给客户端。 结果是由result_callback处理的。
void result_callback(const GoalHandleFibonacci::WrappedResult & result)
{
switch (result.code) {
case rclcpp_action::ResultCode::SUCCEEDED:
break;
case rclcpp_action::ResultCode::ABORTED:
RCLCPP_ERROR(this->get_logger(), "Goal was aborted");
return;
case rclcpp_action::ResultCode::CANCELED:
RCLCPP_ERROR(this->get_logger(), "Goal was canceled");
return;
default:
RCLCPP_ERROR(this->get_logger(), "Unknown result code");
return;
}
std::stringstream ss;
ss << "Result received: ";
for (auto number : result.result->sequence) {
ss << number << " ";
}
RCLCPP_INFO(this->get_logger(), ss.str().c_str());
rclcpp::shutdown();
}
}; // class FibonacciActionClient
} // namespace action_tutorials_cpp
RCLCPP_COMPONENTS_REGISTER_NODE(action_tutorials_cpp::FibonacciActionClient)
CMakeLists.txt
- ~/ros2_ws/src/action_tutorials_cpp/src/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(action_tutorials_cpp)
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# find dependencies
find_package(ament_cmake REQUIRED)
find_package(action_tutorials_interfaces REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rclcpp_action REQUIRED)
find_package(rclcpp_components REQUIRED)
add_library(action_server SHARED src/fibonacci_action_server.cpp)
target_include_directories(action_server PRIVATE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>)
target_compile_definitions(action_server
PRIVATE "ACTION_TUTORIALS_CPP_BUILDING_DLL")
ament_target_dependencies(action_server
"action_tutorials_interfaces"
"rclcpp"
"rclcpp_action"
"rclcpp_components")
rclcpp_components_register_node(action_server PLUGIN "action_tutorials_cpp::FibonacciActionServer" EXECUTABLE fibonacci_action_server)
install(TARGETS
action_server
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin)
add_library(action_client SHARED src/fibonacci_action_client.cpp)
target_include_directories(action_client PRIVATE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>)
target_compile_definitions(action_client
PRIVATE "ACTION_TUTORIALS_CPP_BUILDING_DLL")
ament_target_dependencies(action_client
"action_tutorials_interfaces"
"rclcpp"
"rclcpp_action"
"rclcpp_components")
rclcpp_components_register_node(action_client PLUGIN "action_tutorials_cpp::FibonacciActionClient" EXECUTABLE fibonacci_action_client)
install(TARGETS
action_client
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
# the following line skips the linter which checks for copyrights
# comment the line when a copyright and license is added to all source files
set(ament_cmake_copyright_FOUND TRUE)
# the following line skips cpplint (only works in a git repo)
# comment the line when this package is in a git repo and when
# a copyright and license is added to all source files
set(ament_cmake_cpplint_FOUND TRUE)
ament_lint_auto_find_test_dependencies()
endif()
ament_package()
run
colcon build
ros2 run action_tutorials_cpp fibonacci_action_server
. install/setup.bash
ros2 run action_tutorials_cpp fibonacci_action_client