ROS2教程(6) - rosdep、创建action、动作服务端和客户端 - Linux

使用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
  • 17
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ROS系统中,服务端客户端的概念可以理解为提供服务和请求服务的节点。服务端节点提供服务,客户端节点请求服务,它们之间通过消息传递进行通信。 下面是一个简单的服务端客户端的Python编程示例: 服务端代码: ```python #!/usr/bin/env python import rospy from std_srvs.srv import Empty def my_service_callback(request): print("My service has been called!") #实现服务功能 return [] rospy.init_node('my_service_server') my_service = rospy.Service('/my_service', Empty, my_service_callback) print("My service is ready to receive requests!") rospy.spin() #保持节点运行状态 ``` 客户端代码: ```python #!/usr/bin/env python import rospy from std_srvs.srv import Empty rospy.init_node('my_service_client') rospy.wait_for_service('/my_service') #等待服务启动 my_service_proxy = rospy.ServiceProxy('/my_service', Empty) response = my_service_proxy() #发送请求 ``` 上述代码中,服务端使用`rospy.Service`函数创建一个服务节点,指定服务名称为`/my_service`,服务类型为`Empty`,并指定回调函数`my_service_callback`用于处理服务请求。 客户端使用`rospy.ServiceProxy`函数创建一个服务代理,指定服务名称为`/my_service`,服务类型为`Empty`,并通过调用`my_service_proxy()`方法发送请求,最终获得服务的响应结果。 需要注意的是,服务端客户端的节点名称应该相互独立,避免节点名称冲突。同时,在ROS系统中,服务端客户端节点的启动顺序也很重要,需要确保服务端节点在客户端节点之前启动。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值