【ROS教程】話題通訊

UnderTurrets發表於2024-08-30

@

目錄
  • 1.流程
  • 2.自定義釋出資料
    • 2.1 std_msgs內建型別
    • 2.2 編寫.msg檔案
    • 2.3 修改package.xml檔案
      • 2.3.1 完整的package.xml檔案
    • 2.4 修改CMakeLists.txt檔案
      • 2.4.1 修改find_package指令
      • 2.4.2 新增add_message_files指令
      • 2.4.3 新增generate_messages指令
      • 2.4.4 修改catkin_package指令
    • 2.5 檢視標頭檔案
  • 3.編寫cpp檔案
    • 3.1 功能包目錄檔案樹
    • 3.2 修改CMakeLists.txt檔案
      • 3.2.1 新增add_executable指令
      • 3.2.2 新增add_dependencies指令
      • 3.2.3 新增target_link_libraries指令
      • 3.2.4 完整的CMakeLists.txt
    • 3.3 釋出方cpp
    • 3.4 訂閱方cpp
  • 4.效果


1.流程

話題通訊是ROS中使用頻率最高的一種通訊模式,話題通訊是基於釋出訂閱模式的,也即:一個節點發布訊息,另一個節點訂閱該訊息。在ROS中,實現話題通訊只需要如下幾步:

  1. 確定要釋出的資料型別,一般都需要自定義.msg檔案,修改好CMakeLists.txt檔案和package.xml檔案並重編譯
  2. 編寫釋出方和訂閱方的cpp檔案,修改好CMakeLists.txt檔案並重編譯
  3. 分別啟動釋出方節點和訂閱方節點,順序無所謂

2.自定義釋出資料

在 ROS 通訊協議中,資料載體是一個較為重要組成部分,ROS 中透過 std_msgs 封裝了一些原生的資料型別。但是,這些資料一般只包含一個 data 欄位,結構的單一意味著功能上的侷限性,當傳輸一些複雜的資料, std_msgs 由於描述性較差而顯得力不從心,這種場景下必須透過編寫.msg檔案來自定義訊息型別。

2.1 std_msgs內建型別

  • 內建型別與 C++ 和 Python 中的對應關係:
Primitive Type C++ Python
bool uint8_t bool
int8 int8_t int
uint8 uint8_t int
int16 int16_t int
uint16 uint16_t int
int32 uint32_t int
uint64 uint64_t long int
float32 float float
float64 double float
string std::string str bytes
time ros::Time rospy.Time
duration ros::Duration rospy.Duration
  • 內建型別的陣列與 C++ 和 Python 中的對應關係:
Primitive Type C++ Python
variable-length std::vector tuple
fixed-length boost::array<T, length>或std::vector tuple

2.2 編寫.msg檔案

示例如下:

#檔名Person.msg
string name
uint16 age
float64 height

2.3 修改package.xml檔案

  • 檢視是否存在如下編譯依賴
<build_depend>message_generation</build_depend>
  • 檢視是否存在如下執行依賴
<exec_depend>message_generation</exec_depend>

2.3.1 完整的package.xml檔案

<?xml version="1.0"?>
<package format="2">
  <name>chat</name>
  <version>0.0.0</version>
  <description>The chat package</description>

  <!-- One maintainer tag required, multiple allowed, one person per tag -->
  <!-- Example:  -->
  <!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
  <maintainer email="xu736946693@todo.todo">xu736946693</maintainer>


  <!-- One license tag required, multiple allowed, one license per tag -->
  <!-- Commonly used license strings: -->
  <!--   BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
  <license>TODO</license>


  <!-- Url tags are optional, but multiple are allowed, one per tag -->
  <!-- Optional attribute type can be: website, bugtracker, or repository -->
  <!-- Example: -->
  <!-- <url type="website">http://wiki.ros.org/chat</url> -->


  <!-- Author tags are optional, multiple are allowed, one per tag -->
  <!-- Authors do not have to be maintainers, but could be -->
  <!-- Example: -->
  <!-- <author email="jane.doe@example.com">Jane Doe</author> -->


  <!-- The *depend tags are used to specify dependencies -->
  <!-- Dependencies can be catkin packages or system dependencies -->
  <!-- Examples: -->
  <!-- Use depend as a shortcut for packages that are both build and exec dependencies -->
  <!--   <depend>roscpp</depend> -->
  <!--   Note that this is equivalent to the following: -->
  <!--   <build_depend>roscpp</build_depend> -->
  <!--   <exec_depend>roscpp</exec_depend> -->
  <!-- Use build_depend for packages you need at compile time: -->
  <!--   <build_depend>message_generation</build_depend> -->
  <!-- Use build_export_depend for packages you need in order to build against this package: -->
  <!--   <build_export_depend>message_generation</build_export_depend> -->
  <!-- Use buildtool_depend for build tool packages: -->
  <!--   <buildtool_depend>catkin</buildtool_depend> -->
  <!-- Use exec_depend for packages you need at runtime: -->
  <!--   <exec_depend>message_runtime</exec_depend> -->
  <!-- Use test_depend for packages you need only for testing: -->
  <!--   <test_depend>gtest</test_depend> -->
  <!-- Use doc_depend for packages you need only for building documentation: -->
  <!--   <doc_depend>doxygen</doc_depend> -->
  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>message_generation</build_depend>
  <build_depend>roscpp</build_depend>
  <build_depend>rospy</build_depend>
  <build_depend>std_msgs</build_depend>
  <build_export_depend>roscpp</build_export_depend>
  <build_export_depend>rospy</build_export_depend>
  <build_export_depend>std_msgs</build_export_depend>
  <exec_depend>message_generation</exec_depend>
  <exec_depend>roscpp</exec_depend>
  <exec_depend>rospy</exec_depend>
  <exec_depend>std_msgs</exec_depend>


  <!-- The export tag contains other, unspecified, tags -->
  <export>
    <!-- Other tools can request additional information be placed here -->

  </export>
</package>

2.4 修改CMakeLists.txt檔案

2.4.1 修改find_package指令

# 需要加入 message_generation,必須有 std_msgs
find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation
)

2.4.2 新增add_message_files指令

## 配置 msg 原始檔
add_message_files(
  FILES
  Person.msg
)

2.4.3 新增generate_messages指令

generate_messages(
  DEPENDENCIES
  std_msgs
)

2.4.4 修改catkin_package指令

#執行時依賴
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES demo02_talker_listener
  CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
#  DEPENDS system_lib
)

其中,add_message_files指令必須要在generate_messages指令的前面,然後在工作空間目錄編譯即可。

2.5 檢視標頭檔案

經過以上幾步,在${workspace}/devel/include/${package}/目錄下應該會出現一個標頭檔案,如圖:
在這裡插入圖片描述

  • 如果沒有出現,是無法進行接下來的步驟的。這時,只需要把${workspace}/目錄下的build目錄和devel目錄全部刪除,然後重新編譯即可。
rm -rf build/
rm -rf devel/
catkin_make

3.編寫cpp檔案

3.1 功能包目錄檔案樹

在這裡插入圖片描述

3.2 修改CMakeLists.txt檔案

3.2.1 新增add_executable指令

add_executable(publisher
        src/publisher.cpp)
add_executable(listener
        src/listener.cpp)

3.2.2 新增add_dependencies指令

add_dependencies(publisher ${PROJECT_NAME}_generate_messages_cpp)
add_dependencies(listener ${PROJECT_NAME}_generate_messages_cpp)
target_link_libraries(person_talker
  ${catkin_LIBRARIES}
)
target_link_libraries(person_listener
  ${catkin_LIBRARIES}
)

3.2.4 完整的CMakeLists.txt

  • 其中很多語句都是catkin_make自動生成的
cmake_minimum_required(VERSION 3.0.2)
project(chat)

## Compile as C++11, supported in ROS Kinetic and newer
# add_compile_options(-std=c++11)

## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation
)


## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)


## Uncomment this if the package has a setup.py. This macro ensures
## modules and global scripts declared therein get installed
## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html
# catkin_python_setup()

################################################
## Declare ROS messages, services and actions ##
################################################

## To declare and build messages, services or actions from within this
## package, follow these steps:
## * Let MSG_DEP_SET be the set of packages whose message types you use in
##   your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).
## * In the file package.xml:
##   * add a build_depend tag for "message_generation"
##   * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET
##   * If MSG_DEP_SET isn't empty the following dependency has been pulled in
##     but can be declared for certainty nonetheless:
##     * add a exec_depend tag for "message_runtime"
## * In this file (CMakeLists.txt):
##   * add "message_generation" and every package in MSG_DEP_SET to
##     find_package(catkin REQUIRED COMPONENTS ...)
##   * add "message_runtime" and every package in MSG_DEP_SET to
##     catkin_package(CATKIN_DEPENDS ...)
##   * uncomment the add_*_files sections below as needed
##     and list every .msg/.srv/.action file to be processed
##   * uncomment the generate_messages entry below
##   * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)

# Generate messages in the 'msg' folder
 add_message_files(
   FILES
   Person.msg
 )

## Generate services in the 'srv' folder
# add_service_files(
#   FILES
#   Service1.srv
#   Service2.srv
# )

## Generate actions in the 'action' folder
# add_action_files(
#   FILES
#   Action1.action
#   Action2.action
# )

## Generate added messages and services with any dependencies listed here
# 生成訊息時依賴於 std_msgs
generate_messages(
        DEPENDENCIES
        std_msgs
)


################################################
## Declare ROS dynamic reconfigure parameters ##
################################################

## To declare and build dynamic reconfigure parameters within this
## package, follow these steps:
## * In the file package.xml:
##   * add a build_depend and a exec_depend tag for "dynamic_reconfigure"
## * In this file (CMakeLists.txt):
##   * add "dynamic_reconfigure" to
##     find_package(catkin REQUIRED COMPONENTS ...)
##   * uncomment the "generate_dynamic_reconfigure_options" section below
##     and list every .cfg file to be processed

## Generate dynamic reconfigure parameters in the 'cfg' folder
# generate_dynamic_reconfigure_options(
#   cfg/DynReconf1.cfg
#   cfg/DynReconf2.cfg
# )

###################################
## catkin specific configuration ##
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
#執行時依賴
catkin_package(
        #  INCLUDE_DIRS include
        #  LIBRARIES demo02_talker_listener
        CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
        #  DEPENDS system_lib
)


###########
## Build ##
###########

## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
# include
  ${catkin_INCLUDE_DIRS}
)

## Declare a C++ library
# add_library(${PROJECT_NAME}
#   src/${PROJECT_NAME}/pkg1.cpp
# )

## Add cmake target dependencies of the library
## as an example, code may need to be generated before libraries
## either from message generation or dynamic reconfigure
# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})

## Declare a C++ executable
## With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
# add_executable(${PROJECT_NAME}_node src/pkg1_node.cpp)
add_executable(publisher
        src/publisher.cpp)
add_executable(listener
        src/listener.cpp)

## Rename C++ executable without prefix
## The above recommended prefix causes long target names, the following renames the
## target back to the shorter version for ease of user use
## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")

## Add cmake target dependencies of the executable
## same as for the library above
# add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
add_dependencies(publisher ${PROJECT_NAME}_generate_messages_cpp)
add_dependencies(listener ${PROJECT_NAME}_generate_messages_cpp)

## Specify libraries to link a library or executable target against
# target_link_libraries(${PROJECT_NAME}_node
#   ${catkin_LIBRARIES}
# )

#############
## Install ##
#############

# all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html

## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
# catkin_install_python(PROGRAMS
#   scripts/my_python_script
#   DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )

## Mark executables for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html
# install(TARGETS ${PROJECT_NAME}_node
#   RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )

## Mark libraries for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
# install(TARGETS ${PROJECT_NAME}
#   ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
# )

## Mark cpp header files for installation
# install(DIRECTORY include/${PROJECT_NAME}/
#   DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
#   FILES_MATCHING PATTERN "*.h"
#   PATTERN ".svn" EXCLUDE
# )

## Mark other files for installation (e.g. launch and bag files, etc.)
# install(FILES
#   # myfile1
#   # myfile2
#   DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
# )

#############
## Testing ##
#############

## Add gtest based cpp test target and link libraries
# catkin_add_gtest(${PROJECT_NAME}-test test/test_pkg1.cpp)
# if(TARGET ${PROJECT_NAME}-test)
#   target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
# endif()
target_link_libraries(publisher
        ${catkin_LIBRARIES}
        )

target_link_libraries(listener
        ${catkin_LIBRARIES}
        )

## Add folders to be run by python nosetests
# catkin_add_nosetests(test)

3.3 釋出方cpp

示例如下:

/*
    需求: 實現基本的話題通訊,一方釋出資料,一方接收資料,
         實現的關鍵點:
         1.傳送方
         2.接收方
         3.資料

         PS: 二者需要設定相同的話題


    訊息釋出方:
        迴圈釋出資訊:HelloWorld 字尾數字編號

    實現流程:
        1.包含標頭檔案
        2.初始化 ROS 節點:命名(唯一)
        3.例項化 ROS 控制代碼
        4.例項化 釋出者 物件
        5.組織被髮布的資料,並編寫邏輯釋出資料

*/
// 1.包含標頭檔案
#include "ros/ros.h"
#include "chat/Person.h"

int main(int argc, char  *argv[])
{
    //設定編碼
    setlocale(LC_ALL,"");

    //2.初始化 ROS 節點:命名(唯一)
    // 引數1和引數2 後期為節點傳值會使用
    // 引數3 是節點名稱,是一個識別符號,需要保證執行後,在 ROS 網路拓撲中唯一
    ros::init(argc,argv,"talker");
    //3.例項化 ROS 控制代碼
    ros::NodeHandle nh;//該類封裝了 ROS 中的一些常用功能

    //4.例項化 釋出者 物件
    //泛型: 釋出的訊息型別
    //引數1: 要釋出到的話題
    //引數2: 佇列中最大儲存的訊息數,超出此閥值時,先進的先銷燬(時間早的先銷燬)
    ros::Publisher pub = nh.advertise<chat::Person>("chatter",10);

    //5.組織被髮布的資料,並編寫邏輯釋出資料
    //資料(動態組織)
    chat::Person p;
    p.name = "sunwukong";
    p.age = 2000;
    p.height = 1.45;

    //邏輯(一秒1次)
    ros::Rate r(1);

    //節點不死
    while (ros::ok())
    {
        //釋出訊息
        pub.publish(p);
        //加入除錯,列印傳送的訊息
        ROS_INFO("我叫:%s,今年%d歲,高%.2f米", p.name.c_str(), p.age, p.height);p.age++;
        //根據前面制定的傳送貧頻率自動休眠 休眠時間 = 1/頻率;
        r.sleep();
        //暫無應用
        ros::spinOnce();
    }


    return 0;
}

3.4 訂閱方cpp

示例如下:

/*
    需求: 實現基本的話題通訊,一方釋出資料,一方接收資料,
         實現的關鍵點:
         1.傳送方
         2.接收方
         3.資料


    訊息訂閱方:
        訂閱話題並列印接收到的訊息

    實現流程:
        1.包含標頭檔案
        2.初始化 ROS 節點:命名(唯一)
        3.例項化 ROS 控制代碼
        4.例項化 訂閱者 物件
        5.處理訂閱的訊息(回撥函式)
        6.設定迴圈呼叫回撥函式

*/
// 1.包含標頭檔案
#include "ros/ros.h"
#include "chat/Person.h"

void doMsg(const chat::Person::ConstPtr& person_p){
    ROS_INFO("訂閱的人資訊:%s, %d, %.2f", person_p->name.c_str(), person_p->age, person_p->height);
}
int main(int argc, char  *argv[])
{
    //設定編碼
    setlocale(LC_ALL,"");
    //2.初始化 ROS 節點:命名(唯一)
    ros::init(argc,argv,"listener");
    //3.例項化 ROS 控制代碼
    ros::NodeHandle nh;

    //4.例項化 訂閱者 物件
    ros::Subscriber sub = nh.subscribe<chat::Person>("chatter",10,doMsg);
    //5.處理訂閱的訊息(回撥函式)

    //     6.設定迴圈呼叫回撥函式
    ros::spin();//迴圈讀取接收的資料,並呼叫回撥函式處理

    return 0;
}

4.效果

在這裡插入圖片描述

  • 如果找不到可執行檔案,就把工作目錄下的build資料夾和devel資料夾刪了重新編譯。

本文由部落格一文多發平臺 OpenWrite 釋出!

相關文章