2 ROS2话题通讯基础(1)

2.1 ROS2话题通讯介绍

话题通信是一种单向通信模型,一方发布数据,一方订阅数据,适用于连续不间断的通讯场景,如小车SLAM导航过程中的位姿信息等等。话题是一个通讯的管道,ROS2的话题发布方和接收方无论是C/C++还是Python都可以发布/订阅相同的话题实现通讯,一个话题的发布方,可以有多个订阅方,如下图所示:

在这里插入图片描述

Tips:节点(Node)的概念

ROS的通信对象的构建都依赖于节点(回想之前快速体验的 rclcpp::Node 或者是 from rclpy.node import Node 都是为了创建一个节点所导入的父类),一般情况下一个节点都对应某一个功能模块(例如一个节点负责持续发布SLAM位姿数据等),一个C/C++ 或者Python的文件代码,可以包括多个节点。

2.2 ROS2常用的消息类型介绍

2.2.1 std_msgs消息类型

参考内容

官方文档 std_msgs Msg/Srv Documentation

详解常用的ROS内置消息类型

ROS中geometry_msgs消息类型、nav_msg消息

std_msgs 属于ROS的标准数据类型库,主要包括的消息类型有:

ROS typeC++ type
boolbool
byteuint8_t
charchar
float32float
float64double
int8int8_t
uint8uint8_t
int16int16
uint16uint16
int32int32
uint32uint32
int64int64
uint64uint64_t
stringstd::string
static arraystd::array<T, N>

数组和有条件的字符串的映射

ROS typeC++ type
unbounded dynamic arraystd::vector
bounded dynamic arraycustom_class<T, N>
bounded stringstd::string

2.2.2 geometry_msgs消息类型

参考内容

官方文档 geometry_msgs Msg/Srv Documentation

ROS中geometry_msgs常用消息类型

ROS2 humble的接口官方API

geometry_msgs:常见的几何信息(如点、向量和姿势)提供ROS消息,其中包括的内容有,具体的话题参数,例如在使用乌龟节点控制乌龟运动的cmd_vel话题就是采用geometry_msgs/Twist编写的,具体的用法,可以去查阅官网。

Accel
AccelStamped
AccelWithCovariance
AccelWithCovarianceStamped
Inertia
InertiaStamped
Point
Point32
PointStamped
Polygon
PolygonStamped
Pose
Pose2D
PoseArray
PoseStamped
PoseWithCovariance
PoseWithCovarianceStamped
Quaternion
QuaternionStamped
Transform
TransformStamped
Twist
TwistStamped
TwistWithCovariance
TwistWithCovarianceStamped
Vector3
Vector3Stamped
Wrench
WrenchStamped

2.3 使用C/C++创建基础消息类型的话题通讯

参考内容:

Writing a simple publisher and subscriber (C++)

2.2.2_话题通信_原生消息(C++)_01发布方01源码分析

2.3.1 创建C/C++发布话题信息的功能包并配置VSCode环境

创建发布者功能包时,不添加任何依赖项,回顾之前的项目配置

  1. 创建ROS2 C/C++功能包,其中包名为 cppBaseMsgPub :ros2 pkg create cppBaseMsgPub --build-type ament_cmake

Tips:这里补充还是推荐采用下划线割开的命名方式,否则容易出错
在这里插入图片描述

如果尝试命名节点和依赖项,可以直接采用这种方式,节点名为 cppBaseMsgPubNode ,依赖 rclcppstd_msgsros2 pkg create cppBaseMsgPub --build-type ament_cmake --node-name cppBaseMsgPubNode --dependencies rclcpp std_msgs

pldz@pldz-pc:~/share/ROS2_DEMO/2_Chapter/code$ ros2 pkg create cppBaseMsgPub --build-type ament_cmake
going to create a new package
... 手动省略
creating ./cppBaseMsgPub/CMakeLists.txt

[WARNING]: Unknown license 'TODO: License declaration'.  This has been set in the package.xml, but no LICENSE file has been created.
It is recommended to use one of the ament license identitifers:
... 手动省略
MIT-0
  1. 在工作空间(这个是vscode的概念)下创建.vsocde文件夹和settings.json文件,配置VSCode的settings.json文件,添加路径
{
    "C_Cpp.default.includePath": ["/opt/ros/humble/include/**"],
    "python.analysis.extraPaths": ["/opt/ros/humble/local/lib/python3.10/dist-packages/"],
}

此时的文件结构如下:可以看到,如果单纯的指定了包名但是没有指定节点名,不会在src目录下创建.cpp文件

pldz@pldz-pc:~/share/ROS2_DEMO/2_Chapter/code$ tree -a
.(注释:这个就是工作空间)
├── cppBaseMsgPub
│   ├── CMakeLists.txt
│   ├── include
│   │   └── cppBaseMsgPub
│   ├── package.xml
│   └── src
└── .vscode
    └── settings.json

5 directories, 3 files

完成之后配置VSCode环境

2.3.2 编写ROS2发布话题节点CPP文件

  1. 编写发布者代码:根据官网提供的案例,在包的src目录下,创建cppBaseMsgPubNode.cpp文件,对cppBaseMsgPubNode.cpp进行发布者内容编写:总的来说,主要包括创建构造发布节点,计数属性,然后绑定发布函数到定时器上
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

// C++14中的时间库
using namespace std::chrono_literals;

class CppBaseMsgPub: public rclcpp::Node
{
  public:
      /* 1. ROS2节点的构造函数,其中包括一个node对象(初始化时候没有给出节点的名称),
      * 和属性count_(默认初始化为0) */
      CppBaseMsgPub(const char* nodeName):Node(nodeName), count_(0)
      {
        // 2. 创建发布者,参数分别为话题名称myTopicName,和发布队列的长队为10
        publisher_ = this->create_publisher<std_msgs::msg::String>("myTopicName", 10);
        // 3. 创建定时器,设置发布的频率,并绑定定时执行的事件,这里给到的是CppBaseMsgPub类的函数
        timer_ = this->create_wall_timer(500ms, std::bind(&CppBaseMsgPub::timer_callback, this));
      }

  private:
     // 4. 定义回调函数
    void timer_callback()
    {
      auto message = std_msgs::msg::String();
      message.data = "Hello, world! " + std::to_string(count_++);
      RCLCPP_INFO(this->get_logger(), "Cpp Publish: '%s'", message.data.c_str());
      publisher_->publish(message);
    }

    // 5. 计时器、发布者和计数器字段的声明
    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);
  // 创建节点,给出构造的节点名为cppBaseMsgPubNode
  rclcpp::spin(std::make_shared<CppBaseMsgPub>("cppBaseMsgPubNode"));
  rclcpp::shutdown();
  return 0;
}

2.3.3 配置C/C++发布话题功能包并编译

  1. 配置package.xmlpackage.xml主要对C/C++的功能包依赖项和发布信息进行配置,由于在节点cppBaseMsgPubNode.cpp中主要用到了rclcppstd_msgs两个依赖,因此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>cppBaseMsgPub</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="pldz@R7000.com">pldz</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>

  <!-- 添加依赖项 -->
  <depend>rclcpp</depend>
  <depend>std_msgs</depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>
  1. 配置CmakeLists.txt:主要包括的内容有五部分,并且需要按照顺序进行配置好
find_package()                  // 1. 列出依赖项,通俗的说是项目编译所需要的全部依赖项名称,节点和项目是两个概念,一个项目可以有多个节点
add_executable()                // 2. 可执行文件的路径,通俗来说是编译节点的main函数入口
target_include_directories()    // 3. 编译节点所需要的include的位置
ament_target_dependencies()     // 4. 编译节点所需要的依赖项,这一步的目的是连接编译该节点所需要的依赖项
install()                       // 5. 通俗来说,是将编译好的节点给拷贝到ROS功能包的目录,使得能够通过指令ros2 run <包名> <节点名>的配置,默认这一步的目的就是将build文件夹的内容拷贝到install的lib文件夹下
ament_package()                 // 6. 生成ament工具的环境,缺少这一步,无法在install文件夹下生成setup.bash文件等等

因此该项目的CmakeLists.txt如下所示:

cmake_minimum_required(VERSION 3.8)
project(cppBaseMsgPub)

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)

# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)

# 1. 添加依赖项列表
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)

# 2. 生成节点的主函数入口和节点名称
add_executable(cppBaseMsgPubNode src/cppBaseMsgPubNode.cpp)


# 3. Include路径配置,这里其实没有用上,可以不用配置
target_include_directories(cppBaseMsgPubNode PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
  $<INSTALL_INTERFACE:include>)

# 4. ament工具的编译所需要的依赖
ament_target_dependencies(
  cppBaseMsgPubNode
  "rclcpp"
  "std_msgs"
)

# 5. 安装规则
install(TARGETS cppBaseMsgPubNode
  DESTINATION lib/${PROJECT_NAME})

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()

# 6. 配置ament环境,生成功能包
ament_package()

  1. 编译功能包:colcon build
pldz@pldz-pc:~/share/ROS2_DEMO/2_Chapter/code$ colcon build
WARNING: Package name "cppBaseMsgPub" does not follow the naming conventions. It should start with a lower case letter and only contain lower case letters, digits, underscores, and dashes.
Starting >>> cppBaseMsgPub
... 手动省略
Summary: 1 package finished [4.44s]
  1 package had stderr output: cppBaseMsgPub
  1. 运行节点:激活功能包环境source ./install/setup.bash,然后运行ros2 run cppBaseMsgPub cppBaseMsgPubNode
pldz@pldz-pc:~/share/ROS2_DEMO/2_Chapter/code$ source ./install/setup.bash 
pldz@pldz-pc:~/share/ROS2_DEMO/2_Chapter/code$ ros2 run cppBaseMsgPub cppBaseMsgPubNode 
[INFO] [1683015931.213646661] [cppBaseMsgPubNode]: Cpp Publish: 'Hello, world! 0'
[INFO] [1683015931.713349843] [cppBaseMsgPubNode]: Cpp Publish: 'Hello, world! 1'
[INFO] [1683015932.213429705] [cppBaseMsgPubNode]: Cpp Publish: 'Hello, world! 2'
^C[INFO] [1683015932.588202160] [rclcpp]: signal_handler(signum=2)
pldz@pldz-pc:~/share/ROS2_DEMO/2_Chapter/code$ 

2.3.4 创建C/C++订阅话题的功能包

  1. 由于上面操作过一遍从功能包开始的配置节点依赖项,这里直接提前在创建功能包的时候直接指定依赖项,省去后续的配置,取名订阅话题的功能包为cppBaseMsgSub,节点名称为cppBaseMsgSubNode,如ros2 pkg create cppBaseMsgSub --build-type ament_cmake --node-name cppBaseMsgSubNode --dependencies rclcpp std_msgs

Tips:这里补充还是推荐采用下划线割开的命名方式,否则容易出错
在这里插入图片描述

pldz@pldz-pc:~/share/ROS2_DEMO/2_Chapter/code$ ros2 pkg create cppBaseMsgSub --build-type ament_cmake --node-name cppBaseMsgSubNode --dependencies rclcpp std_msgs
going to create a new package
package name: cppBaseMsgSub
... 手动省略
MIT
MIT-0
  1. 2.3.1节在工作空间下配置过vscode的settings.json这里就不再配置vscode了

2.3.5 编写ROS2订阅话题节点CPP文件

  1. 直接在cppBaseMsgSubNode.cpp文件进行编辑,创建订阅节点,订阅话题myTopicName与之前的发布话题类型和名称一致即可:
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

// 占位符,结合std::bind函数的绑定使用
using std::placeholders::_1;

class CppBaseMsgSub: public rclcpp::Node
{
  public:
    /* 1. ROS2节点的构造函数 */
    CppBaseMsgSub(const char* nodeName):Node(nodeName)
    {
      // 2.声明订阅话题类型,并绑定回调函数
      subscription_ = this->create_subscription<std_msgs::msg::String>(
      "myTopicName", 10, std::bind(&CppBaseMsgSub::topic_callback, this, _1));
    }

  private:
    // 3. 定义订阅到消息的回调函数
    void topic_callback(const std_msgs::msg::String & msg) const
    {
      RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg.data.c_str());
    }

    // 4. 计时器、发布者和计数器字段的声明
    rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  // 初始化订阅节点
  rclcpp::spin(std::make_shared<CppBaseMsgSub>("cppBaseMsgSubNode"));
  rclcpp::shutdown();
  return 0;
}

2.3.6 配置C/C++订阅话题功能包并编译

  1. 由于是直接在创建包的时候指定了依赖项,可以直接编译colcon build,运行查看效果:

在这里插入图片描述

2.4 使用Python创建基础消息类型的话题通讯

2.4.1 创建Python发布话题功能包并编写节点文件

  1. 创建Python发布者功能包,其中功能包名称为pythonBaseMsgPub,不指定节点名和依赖项,后续手动配置packages.xmlsetup.pyros2 pkg create pythonBaseMsgPub --build-type ament_python,目前文件结构如下所示:

在这里插入图片描述

Tips:这里补充还是推荐采用下划线割开的命名方式,否则容易出错
在这里插入图片描述

  1. pythonBaseMsgPub/pythonBaseMsgPub文件夹下创建pythonBaseMsgPubNode.py文件,内容如下所示
import rclpy
from rclpy.node import Node

from std_msgs.msg import String


class PythonBaseMsgPub(Node):

    def __init__(self, nodeName):
        # 1. 初始化父类构造函数,其中节点名需要创建时候指定,计数属性count_从0开始
        super().__init__(nodeName)
        self.count_ = 0
        # 2. 声明发布者,发布消息类型为String,话题名为myTopicName,队列大小为10
        self.publisher_ = self.create_publisher(String, 'myTopicName', 10)
        # 3. 创建定时器,其中更新频率为0.5秒,并绑定回调函数
        self.timer = self.create_timer(0.5, self.timer_callback)
        
    # 4. 定义回调函数
    def timer_callback(self):
        msg = String()
        msg.data = 'Hello World: %d' % self.count_
        self.publisher_.publish(msg)
        self.get_logger().info('Publishing: "%s"' % msg.data)
        self.count_ += 1


def main(args=None):
    rclpy.init(args=args)
    pythonBaseMsgPubNode = PythonBaseMsgPub("pythonBaseMsgPubNode")
    rclpy.spin(pythonBaseMsgPubNode)
    # 销毁节点
    pythonBaseMsgPubNode.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()

2.4.2 配置Python项目并运行

  1. 配置Python项目的packages.xml:主要是添加可执行的依赖项rclpystd_msgs
<?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>pythonBaseMsgPub</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="pldz@R7000.com">pldz</maintainer>
  <license>TODO: License declaration</license>

  <!-- 与C/C++不同的是,Python文件是一个可执行的脚本,因此依赖项的关键字为exec_depend -->
  <exec_depend>rclpy</exec_depend>
  <exec_depend>std_msgs</exec_depend>

  <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>

  1. 配置setup.py文件指定节点的main函数入口:
from setuptools import setup

package_name = 'pythonBaseMsgPub'

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='pldz',
    maintainer_email='pldz@R7000.com',
    description='TODO: Package description',
    license='TODO: License declaration',
    tests_require=['pytest'],
    # 指定编译节点的main函数入口
    entry_points={
        'console_scripts': [
            'pythonBaseMsgPubNode = pythonBaseMsgPub.pythonBaseMsgPubNode:main',
        ],
    },
)

  1. 编译:colcon build

2.4.3 创建Python订阅话题功能包并编写节点

  1. 创建功能包pythonBaseMsgSub,并直接给出节点名pythonBaseMsgSubNode和依赖项rclpystd_msgs,如下所示:ros2 pkg create pythonBaseMsgSub --build-type ament_python --node-name pythonBaseMsgSubNode --dependencies rclpy std_msgs

Tips:这里补充还是推荐采用下划线割开的命名方式,否则容易出错
在这里插入图片描述

  1. 编写订阅者节点:
import rclpy
from rclpy.node import Node

from std_msgs.msg import String


class PythonBaseMsgSub(Node):

    def __init__(self, nodeName):
        # 1. 构造函数,初始化node节点
        super().__init__(nodeName)
        # 2. 声明订阅者,订阅话题`myTopicNmae`,并绑定回调函数
        self.subscription = self.create_subscription(String,'myTopicName',self.listener_callback,10)

    # 3. 定义回调函数
    def listener_callback(self, msg):
        self.get_logger().info('I heard: "%s"' % msg.data)


def main(args=None):
    rclpy.init(args=args)
    pythonBaseMsgSubNode = PythonBaseMsgSub("pythonBaseMsgSubNode")
    rclpy.spin(pythonBaseMsgSubNode)
    pythonBaseMsgSubNode.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()

2.4.4 编译运行节点

  1. 由于指定了依赖项和节点名,不需要多余的进行packages.xmlsetup.py的配置

  2. 编译colcon build,联合C/C++的一起运行,可以看到话题通讯是多对多的

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值