• ROS 消息订阅 节点发布 通信方式


     

    1、节点(node)


        节点是进行运算任务的进程。一个系统可以由很多节点组成,节点也可以称为软件模块。

        ROS是以节点的形式开发的,节点是根据其目的,可以细分的可执行程序的最小单位。节点使基于ROS的系统在运行时更加形象化,当许多节点同时进行时,

        可以将不同节点的通讯绘制成下图。

     

     

    3、 话题(topic)

            话题本质是对套接字的一种封装,一个节点可以向一个给定的话题发布消息,另一个节点可以订阅给定话题中特定消息类型的消息。在实现上,消息是序列化的

           消息通过一个GlobalCallbackQueue和一个TopicManager管理

          需要注意的是,在ROS中,话题必须是唯一的,否则消息路由就会产生错误。

          查看工具 : 可视化工具rqt_graph、命令行工具rostopic

    4、服务(service)


          基于主题 发布/订阅 的通信方法是一种异步方法,该 发布/订阅 模型是一种很灵活的通讯模式。但在某些情况下,需要一种同时使用请求和响应的同步消息交换方案,ROS提供了叫做服务的消息同步方法,是一种一对一的机制。

          一个服务被分成服务服务器和服务客户端,其中服务服务器只在有请求(request)的时候才响应(response),而服务客户端会在发送请求后接收响应。与话题不同,服务是一次性消息通信。

           因此,当服务的请求和响应完成时,两个连接的节点将被断开。

           服务通常被用作请求机器人执行特定操作时使用的命令,或者用于根据特定条件需要产生事件的节点。

          由于它是一次性的通信方式,在网络上的负载很小,所以它也被用作代替 基于主题 发布/订阅 的通信手段。
     

    PS:查看列表topic列表

    rostopic常用命令  topic的名字全局唯一

     查看话题 rostopic info [话题名]

     获得话题列表 rostopic list

     获得话题列表 rostopic list -v

     发布数据 rostopic pub [话题名] [消息类型] [参数]

    三、发布模式:rostopic的发布模式有:

    闩锁模式(latch mode)、速率模式(rate mode)、单次模式(once mode)、文件模式(file mode)。

     闩锁模式(latch mode) 默认模式,只发布一次,确保收到,选项为-l。

     速率模式(rate mode) 以特定速率发布消息,默认10Hz,选项为-r。

     单次模式(once mode) 以闩锁模式发布消息,执行3秒,然后结束发布,选项为-1。

     文件模式(file mode) 从YAML文件中读取消息,文件模式的发布速度也为10Hz,选项为-f。

    1. 示例
    2. rostopic pub /turtle1/cmd_vel geometry_msgs/Twist -r 1 -- '[2.0, 0.0, 0.0]' '[0.0, 0.0, -1.8]'
    3. “-”短划线代表参数是可选参数, “-- ”代表参数是非可选参数

    5、消息(message)


        节点之间通过传送消息进行通讯。每一个消息都是一种数据结构。

        ROS的消息支持标准的数据类型(整型、浮点型、布尔型等),

        还包括数组、结构体、自定义的数据类型等等。

    四、查看消息:

     查看消息类型 rosmsg info [消息类型]

     消息列表 rosmsg list

     程序包消息 rosmsg package [程序包名] 查看消息常用用法

    五、消息的组织:

    消息类型的命名方式为:程序包名/消息名

    消息类型每行的声明必须包含两部分:域、常量,域定义了消息的数据类型,

    常量定义了域的名称。域可以是独立域也可以是复合域。

    特别的消息类型Header来提供一些通用信息如时间戳、序列号、帧ID等

    std_msgs/Header中的消息头内容如下:

    #序列号 uint32 seq #时间戳 time stamp #坐标系ID string frame_id

    六、常见消息类型:

    std_msgs支持字符串、布尔、整型、浮点型、数组等多种数据类型。


     标准消息

    std_msgs/Char char data

     几何消息

    1. geometry_msgs/Twist geometry_msgs/Vector3 linear
    2. float64 x
    3. float64 y
    4. float64 z
    5. geometry_msgs/Vector3 angular
    6. float64 x
    7. float64 y
    8. float64 z

     传感消息senser_msgs/PointCloud(复合域)

    1. std_msgs/Header header
    2. uint32 seq
    3. time stamp
    4. string frame_id
    5. geometry_msgs/Point32[] points
    6. float32 x
    7. float32 y
    8. float32 z
    9. sensor_msgs/ChannelFloat32[] channelsstring name
    10. float32[] values

    示例 查看小海龟的话题、消息。

     启动小海龟 启动节点rosrun turtlesim turtlesim_node

     启动键盘控制rosrun turtlesim turtle_teleop_key

     查看消息 rosrun rqt_console rqt_console

      过滤消息 rosrun rqt_logger_level rqt_logger_level

     查看网络拓扑 rosrun rqt_graph rqt_graph

     

    创建发布订阅

     发布消息 //配置话题、队列大小、发布模式

    template Publisher advertise(const std::string& topic, uint32_t queue_size, bool latch=false)

    //发布消息

    1. template void publish(const boost::shared_ptr& message) const{
    2. ......
    3. SerializedMessage m;
    4. m.type_info = &typeid(M);
    5. m.message = message;
    6. publish(boost::bind(serializeMessage, boost::ref(*message)), m);
    7. }

    监听消息回调

    spinOnce(监听到后继续往下运行,用于设置发布频率)

    spin(监听到后调回调函数执行,继续循环监听)

    自定义消息步骤

     步骤1:创建自定义消息.msg 文件

    1. Header header
    2. string first_name
    3. string last_name
    4. uint8 age
    5. uint32 score

     步骤2编写消息发布文件   talker

    1. #include "ros/ros.h"
    2. #include "std_msgs/String.h"
    3. #include "example_3/Info.h"
    4. #include
    5. #include
    6. int main(int argc, char **argv)
    7. {
    8. ros::init(argc, argv, "talker"); //talk 节点
    9. ros::NodeHandle nh;
    10. rosbag::Bag bag;
    11. ros::Publisher chatter_pub = nh.advertise("chatter", 1000); // 队列长度1000
    12. bag.open("/home/miaozl/catkin_ws/bagfiles/test.bag",rosbag::bagmode::Write);
    13. bag.setCompression(rosbag::CompressionType::LZ4);
    14. ros::Rate loop_rate(10);
    15. while (ros::ok())
    16. {
    17. example_3::Info msg;
    18. msg.header.stamp=ros::Time::now();
    19. msg.header.frame_id="info_msg";
    20. msg.first_name = "Fabio";
    21. msg.last_name = "Miao";
    22. msg.age =36;
    23. msg.score = 100;
    24. chatter_pub.publish(msg); // 发布消息
    25. ROS_INFO("publish message");
    26. bag.write("chatter",msg.header.stamp,msg);
    27. ros::spinOnce(); // 监听回调
    28. loop_rate.sleep();
    29. }
    30. bag.close();
    31. return 0;
    32. }

     

    步骤3 编写消息订阅文件 listener

    1. #include "ros/ros.h"
    2. #include "std_msgs/String.h"
    3. #include "example_3/Info.h"
    4. void chatterCallback(const example_3::Info::ConstPtr& msg)
    5. {
    6. //ROS_INFO("I heard: [%s]", msg->data.c_str());
    7. //ROS_INFO("I heard: %s %s,his age is %d,his score is %d",msg->first_name.c_str(),msg->last_name.c_str(),msg->age,msg->score);
    8. ROS_INFO("I heard: header frame id is %s, %s %s,his age is %d,his score is %d",msg->header.frame_id.c_str(),
    9. msg->first_name.c_str(),msg->last_name.c_str(),msg->age,msg->score);
    10. }
    11. int main(int argc, char **argv)
    12. {
    13. ros::init(argc, argv, "listener");
    14. ros::NodeHandle nh;
    15. ros::Subscriber sub = nh.subscribe("chatter", 1000, chatterCallback);
    16. ros::spin();
    17. return 0;
    18. }

    步骤3 package.xml、CMakeLists.txt配置

    1. cmake_minimum_required(VERSION 3.0.2)
    2. project(example_3)
    3. ## Compile as C++11, supported in ROS Kinetic and newer
    4. # add_compile_options(-std=c++11)
    5. ## Find catkin macros and libraries
    6. ## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
    7. ## is used, also find other catkin packages
    8. find_package(catkin REQUIRED COMPONENTS
    9. roscpp
    10. rospy
    11. rosbag
    12. std_msgs
    13. message_generation
    14. )
    15. ## System dependencies are found with CMake's conventions
    16. # find_package(Boost REQUIRED COMPONENTS system)
    17. ## Uncomment this if the package has a setup.py. This macro ensures
    18. ## modules and global scripts declared therein get installed
    19. ## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html
    20. # catkin_python_setup()
    21. ################################################
    22. ## Declare ROS messages, services and actions ##
    23. ################################################
    24. ## To declare and build messages, services or actions from within this
    25. ## package, follow these steps:
    26. ## * Let MSG_DEP_SET be the set of packages whose message types you use in
    27. ## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).
    28. ## * In the file package.xml:
    29. ## * add a build_depend tag for "message_generation"
    30. ## * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET
    31. ## * If MSG_DEP_SET isn't empty the following dependency has been pulled in
    32. ## but can be declared for certainty nonetheless:
    33. ## * add a exec_depend tag for "message_runtime"
    34. ## * In this file (CMakeLists.txt):
    35. ## * add "message_generation" and every package in MSG_DEP_SET to
    36. ## find_package(catkin REQUIRED COMPONENTS ...)
    37. ## * add "message_runtime" and every package in MSG_DEP_SET to
    38. ## catkin_package(CATKIN_DEPENDS ...)
    39. ## * uncomment the add_*_files sections below as needed
    40. ## and list every .msg/.srv/.action file to be processed
    41. ## * uncomment the generate_messages entry below
    42. ## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)
    43. ## Generate messages in the 'msg' folder
    44. add_message_files(
    45. FILES
    46. Info.msg
    47. )
    48. ## Generate services in the 'srv' folder
    49. # add_service_files(
    50. # FILES
    51. # Service1.srv
    52. # Service2.srv
    53. # )
    54. ## Generate actions in the 'action' folder
    55. # add_action_files(
    56. # FILES
    57. # Action1.action
    58. # Action2.action
    59. # )
    60. ## Generate added messages and services with any dependencies listed here
    61. generate_messages(
    62. DEPENDENCIES
    63. std_msgs
    64. )
    65. ################################################
    66. ## Declare ROS dynamic reconfigure parameters ##
    67. ################################################
    68. ## To declare and build dynamic reconfigure parameters within this
    69. ## package, follow these steps:
    70. ## * In the file package.xml:
    71. ## * add a build_depend and a exec_depend tag for "dynamic_reconfigure"
    72. ## * In this file (CMakeLists.txt):
    73. ## * add "dynamic_reconfigure" to
    74. ## find_package(catkin REQUIRED COMPONENTS ...)
    75. ## * uncomment the "generate_dynamic_reconfigure_options" section below
    76. ## and list every .cfg file to be processed
    77. ## Generate dynamic reconfigure parameters in the 'cfg' folder
    78. # generate_dynamic_reconfigure_options(
    79. # cfg/DynReconf1.cfg
    80. # cfg/DynReconf2.cfg
    81. # )
    82. ###################################
    83. ## catkin specific configuration ##
    84. ###################################
    85. ## The catkin_package macro generates cmake config files for your package
    86. ## Declare things to be passed to dependent projects
    87. ## INCLUDE_DIRS: uncomment this if your package contains header files
    88. ## LIBRARIES: libraries you create in this project that dependent projects also need
    89. ## CATKIN_DEPENDS: catkin_packages dependent projects also need
    90. ## DEPENDS: system dependencies of this project that dependent projects also need
    91. catkin_package(
    92. # INCLUDE_DIRS include
    93. # LIBRARIES example_3
    94. CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
    95. # DEPENDS system_lib
    96. )
    97. ###########
    98. ## Build ##
    99. ###########
    100. ## Specify additional locations of header files
    101. ## Your package locations should be listed before other locations
    102. include_directories(
    103. # include
    104. ${catkin_INCLUDE_DIRS}
    105. )
    106. ## Declare a C++ library
    107. # add_library(${PROJECT_NAME}
    108. # src/${PROJECT_NAME}/example_3.cpp
    109. # )
    110. ## Add cmake target dependencies of the library
    111. ## as an example, code may need to be generated before libraries
    112. ## either from message generation or dynamic reconfigure
    113. # add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
    114. ## Declare a C++ executable
    115. ## With catkin_make all packages are built within a single CMake context
    116. ## The recommended prefix ensures that target names across packages don't collide
    117. ## Rename C++ executable without prefix
    118. ## The above recommended prefix causes long target names, the following renames the
    119. ## target back to the shorter version for ease of user use
    120. ## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
    121. # set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")
    122. ## Add cmake target dependencies of the executable
    123. ## same as for the library above
    124. # add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
    125. ## Specify libraries to link a library or executable target against
    126. if(CMAKE_BUILD_TYPE STREQUAL DEBUG)
    127. add_executable(talker src/talker.cpp)
    128. add_executable(listener src/listener.cpp)
    129. target_link_libraries(talker
    130. ${catkin_LIBRARIES}
    131. )
    132. target_link_libraries(listener
    133. ${catkin_LIBRARIES}
    134. )
    135. endif()
    136. #############
    137. ## Install ##
    138. #############
    139. # all install targets should use catkin DESTINATION variables
    140. # See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html
    141. ## Mark executable scripts (Python etc.) for installation
    142. ## in contrast to setup.py, you can choose the destination
    143. # catkin_install_python(PROGRAMS
    144. # scripts/my_python_script
    145. # DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    146. # )
    147. ## Mark executables for installation
    148. ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html
    149. # install(TARGETS ${PROJECT_NAME}_node
    150. # RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    151. # )
    152. ## Mark libraries for installation
    153. ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
    154. # install(TARGETS ${PROJECT_NAME}
    155. # ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    156. # LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    157. # RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
    158. # )
    159. ## Mark cpp header files for installation
    160. # install(DIRECTORY include/${PROJECT_NAME}/
    161. # DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
    162. # FILES_MATCHING PATTERN "*.h"
    163. # PATTERN ".svn" EXCLUDE
    164. # )
    165. ## Mark other files for installation (e.g. launch and bag files, etc.)
    166. # install(FILES
    167. # # myfile1
    168. # # myfile2
    169. # DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
    170. # )
    171. #############
    172. ## Testing ##
    173. #############
    174. ## Add gtest based cpp test target and link libraries
    175. # catkin_add_gtest(${PROJECT_NAME}-test test/test_example_3.cpp)
    176. # if(TARGET ${PROJECT_NAME}-test)
    177. # target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
    178. # endif()
    179. ## Add folders to be run by python nosetests
    180. # catkin_add_nosetests(test)

     步骤4 生成消息文件  编译执行

     

  • 相关阅读:
    优秀的 OKR 案例参考
    字符串匹配DP问题合集
    Codeforces Round 889 (Div. 2)A~C1题解
    Prometheus+Grafana 部署
    JavaParse入门
    SpringCloudAlibaba【四】Nacos Config 多环境切换与公共配置
    Win11启动修复无效怎么办
    nodejs+vue音乐网站与分享平台
    wav格式如何转mp3?
    算法--排序算法效率比较
  • 原文地址:https://blog.csdn.net/weixin_44025389/article/details/126469610