[ros2学习]-Client Libraries – 写一个简单的发布和订阅(C++)

142
0
2021年2月4日 09时09分

文章目录

 

    • ① 背景
    • ② 前提
    • ③ 任务
      • Ⅰ 创建一个包
      • Ⅱ 写发布节点
        • 代码解析
        • 修改 package.xml
        • 修改 CMakeLists.txt
      • Ⅲ 写订阅节点
        • 代码解析
        • 修改 package.xml
        • 修改 CMakeLists.txt
      • Ⅳ 编译和运行
    • ④ 总结

 

① 背景

 

节点是通过ROS graph 进行通信的可执行程序。在本教程中,节点将通过主题以字符串消息的形式相互传递信息。这里使用的示例是一个简单的“talker”和“listener”系统。一个节点发布数据,另一个节点订阅该主题,以便它可以接收该数据

 

② 前提

 

创建好工作空间

 

③ 任务

 

Ⅰ 创建一个包

 

创建一个pubsub的包

 

ros2 pkg create --build-type ament_cmake cpp_pubsub

 

改 xml文件里的邮箱别忘了
切换到dev_ws/src/cpp_pubsub/src 路径下

 

Ⅱ 写发布节点

 

通过命令下载实例文件

 

wget -O publisher_member_function.cpp https://raw.githubusercontent.com/ros2/examples/master/rclcpp/minimal_publisher/member_function.cpp

 

很大概率失败。。。这这这

 

还是直接贴代码吧
就算失败也会有个空文件

 

#include <chrono>
#include <memory>

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

using namespace std::chrono_literals;

/* This example creates a subclass of Node and uses std::bind() to register a
* member function as a callback from the timer. */

class MinimalPublisher : public rclcpp::Node
{
  public:
    MinimalPublisher()
    : Node("minimal_publisher"), count_(0)
    {
      publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
      timer_ = this->create_wall_timer(
      500ms, std::bind(&MinimalPublisher::timer_callback, this));
    }

  private:
    void timer_callback()
    {
      auto message = std_msgs::msg::String();
      message.data = "Hello, world! " + std::to_string(count_++);
      RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
      publisher_->publish(message);
    }
    rclcpp::TimerBase::SharedPtr timer_;
    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
    size_t count_;
  };

  int main(int argc, char * argv[])
  {
    rclcpp::init(argc, argv);
    rclcpp::spin(std::make_shared<MinimalPublisher>());
    rclcpp::shutdown();
    return 0;
  }

 

代码解析

 

在这里插入图片描述

 

修改 package.xml

 

添加几行在里面

 

<depend>rclcpp</depend>
<depend>std_msgs</depend>

 

在这里插入图片描述

 

修改 CMakeLists.txt

 

  • 在 find_package(ament_cmake REQUIRED)下面添加

 

find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)

 

  • 接着添加可执行文件的名字为 talker 一会用ros2 run 来运行

 

add_executable(talker src/publisher_member_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)

 

  • 最后添加 install(TARGETS…) 把可执行文件安装到install去

 

install(TARGETS
  talker
  DESTINATION lib/${PROJECT_NAME})

 

最后这个样子

 

cmake_minimum_required(VERSION 3.5)
project(cpp_pubsub)

# Default to C99
if(NOT CMAKE_C_STANDARD)
  set(CMAKE_C_STANDARD 99)
endif()

# Default to C++14
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 dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)

add_executable(talker src/publisher_member_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # uncomment the line when a copyright and license is not present in all source files
  #set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # uncomment the line when this package is not in a git repo
  #set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

install(TARGETS
  talker
  DESTINATION lib/${PROJECT_NAME})

ament_package()

 

可以尝试编译执行一下

 

在这里插入图片描述

 

Ⅲ 写订阅节点

 

通过命令下载实例文件,也是在dev_ws/src/cpp_pubsub/src路径下

 

wget -O subscriber_member_function.cpp https://raw.githubusercontent.com/ros2/examples/master/rclcpp/minimal_subscriber/member_function.cpp

 

很大概率失败。。。这这这

还是直接贴代码吧
就算失败也会有个空文件

 

#include <memory>

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using std::placeholders::_1;

class MinimalSubscriber : public rclcpp::Node
{
  public:
    MinimalSubscriber()
    : Node("minimal_subscriber")
    {
      subscription_ = this->create_subscription<std_msgs::msg::String>(
      "topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1));
    }

  private:
    void topic_callback(const std_msgs::msg::String::SharedPtr msg) const
    {
      RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg->data.c_str());
    }
    rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<MinimalSubscriber>());
  rclcpp::shutdown();
  return 0;
}

 

代码解析

 

在这里插入图片描述

 

修改 package.xml

 

基于前面的pub没有新增依赖,所以不用修改

 

修改 CMakeLists.txt

 

增加可执行文件和Taeget

 

add_executable(listener src/subscriber_member_function.cpp)
ament_target_dependencies(listener rclcpp std_msgs)

install(TARGETS
  talker
  listener
  DESTINATION lib/${PROJECT_NAME})

 

最后应是这样:

 

cmake_minimum_required(VERSION 3.5)
project(cpp_pubsub)

# Default to C99
if(NOT CMAKE_C_STANDARD)
  set(CMAKE_C_STANDARD 99)
endif()

# Default to C++14
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 dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)

add_executable(talker src/publisher_member_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)
add_executable(listener src/subscriber_member_function.cpp)
ament_target_dependencies(listener rclcpp std_msgs)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # uncomment the line when a copyright and license is not present in all source files
  #set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # uncomment the line when this package is not in a git repo
  #set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

install(TARGETS
  talker
  listener
  DESTINATION lib/${PROJECT_NAME})

ament_package()

 

Ⅳ 编译和运行

 

  • 养成好习惯,编译前先解决依赖,切换到dev_ws

 

sudo rosdep install -i --from-path src --rosdistro eloquent -y

 

  • 只编译新增的包

 

colcon build --packages-select cpp_pubsub

 

  • 安装环境

 

. install/setup.bash

 

  • 运行两个节点

 

ros2 run cpp_pubsub talker
ros2 run cpp_pubsub listener

 

在这里插入图片描述

 

④ 总结

 

您创建了两个节点来发布和订阅主题上的数据。在编译和运行它们之前,您已将它们的依赖项和可执行文件添加到包配置文件中。
这些例子中使用的代码可以在这里找到。

发表评论

后才能评论