基于实战项目的ROS学习之topic实例(二)
本文章承接我的上一篇文章,《基于实战项目的ROS学习之topic_demo\publisher》https://zhuanlan.zhihu.com/p/61884815,此篇主要是listener的代码解析,以及cmakelist和package.xml的编写。
topic_demo是ROS 工程中的一个package,即程序写作的最基本单元,ROS文件架构可参照文章:https://blog.csdn.net/DXMARK/article/details/89019477。
本次学习的前置知识有ROS package文件结构、c++基础、cmake基础、linux基础、ROS基本命令及基本概念( 百度 or Google)
ps: 此专题为基于实战项目的ROS学习,基于中科院项目教学代码进行学习,代码地址:https://github.com/DroidAITech/ROS-Academy-for-Beginners跟着项目走是最好的学习方法。
另:知乎专栏:《致敬图灵(AI与机器人专栏)》
https://www.zhihu.com/people/li-zhi-hao-32-6/columns
微信公众号:< 致敬图灵 >。
//ROS头文件
#include <ros/ros.h>
//包含自定义ms*生的头文件
#include <topic_demo/gps.h>
//ROS标准msg头文件
#include <std_msgs/Float32.h>
void gpsCallback(const topic_demo::gps::ConstPtr &msg)//topic_demo::gps::ConstPtr为gps.msg文件编译生成的头文件中定义的数据类型,是一个常指针。
{
//计算离原点(0,0)的距离
std_msgs::Float32 distance;//std_msgs::Float32是std_msgs命名空间中的数据结构里面只有一个成员data
distance.data = sqrt(pow(msg->x,2)+pow(msg->y,2));//distance.data,才是真正的distance值。msg->x 是结构体指针访问成员变量的方法。
//float distance = sqrt(pow(msg->x,2)+pow(msg->y,2));
ROS_INFO("Listener: Distance to origin = %f, state: %s",distance.data,msg->state.c_str());
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener");//初始化,且节点名为listener
ros::NodeHandle n; //节点句柄为n
ros::Subscriber sub = n.subscribe("gps_info", 1, gpsCallback); //gpsCallback为回调函数,即当Subscriber接收到信息后,会调用回调函数进行处理。gps_info为接收到的msg,1为缓冲队列的长度。
ros::spin(); //ros::spin()用于调用所有可触发的回调函数。反复循环检测与调用,若缓存队列中含有msg,则会通过回调函数进行处理,而队列中没有msg,则不会进行回调。相当于一个循环。是阻塞的。类似于在循环里反复调用ros::spinOnce()。ros::spinOnce()是指检测并调用回调函数一次。
return 0;
}
接下来将介绍cmakelist.txt与package.xml的编写。#后面是注释,有解释内容,也有一些本工程中的cmakelist用不到的函数。更详细解释可见官方文档:http://wiki.ros.org/catkin/CMakeLists.txt>,中文翻译:https://blog.csdn.net/DXMARK/article/details/89290346
cmake_minimum_required(VERSION 2.8.3)
project(topic_demo)#指定工程名
## 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 #使catkin_INCLUDE_DIRS包含COMPONENTS后的库的路径。并且定义一些环境变量。
message_generation
roscpp
rospy
std_msgs #找到工程中所需要的,所依赖的库,有两个部分组成catkin REQUIRED 与 COMPONENTS xxxx ,REQUIRED前与COMPONENTS后,都是所依赖的库的名称。
)
## 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 接下来,进行ROS messages, services 与 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 run_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 run_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 ...)将message_generation等用到的package加入 find_package 的 COMPONENTS 中。
## * add "message_runtime" and every package in MSG_DEP_SET to
## catkin_package(CATKIN_DEPENDS ...) #将 message_runtime 等用到的package加入 find_package 的 COMPONENTS 中。
## * uncomment the add_*_files sections below as needed
## and list every .msg/.srv/.action file to be processed #使用add_*_files函数,将定义 的.msg/.srv/.action文件加入到FILES变量中。
## * uncomment the generate_messages entry below
## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...) #加入 函数generate_messages。
## Generate messages in the 'msg' folder
add_message_files(
FILES
gps.msg
# Message2.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
generate_messages( #使用了std_msgs头文件。
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 run_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 you 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( #指定catkin的配置,生成配置文件
INCLUDE_DIRS include#表示将产生的头文件放入目前文件夹中的include文件夹中。
# LIBRARIES publish_subscribe_demo
CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
# DEPENDS system_lib # system_lib是编译/运行此程序包时需要存在的系统依赖项(ROS packages有时会需要操作系统提供一些外部函数库,这些函数库就是所谓的“系统依赖项”)。
)
###########
## Build ##
###########
## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories( #include的路径应该是 find_package 中的依赖项的路径,因为使用find_package函数时,就已经将其赋值给catkin_INCLUDE_DIRS变量,因此直接使用变量即可。
include
${catkin_INCLUDE_DIRS}
)
## Declare a C++ library
## add_library(${PROJECT_NAME}
# src/${PROJECT_NAME}/publish_subscribe_demo.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/publish_subscribe_demo_node.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})
## Specify libraries to link a library or executable target against
## target_link_libraries(${PROJECT_NAME}_node
# ${catkin_LIBRARIES}
# )
add_executable(talker src/talker.cpp )#生成可执行文件
#必须添加add_dependencies,否则找不到自定义的ms*生的头文件
add_dependencies(talker topic_demo_generate_messages_cpp)
target_link_libraries(talker ${catkin_LIBRARIES})#catkin_LIBRARIES是一个隐式变量,不需要管。
add_executable(listener src/listener.cpp )#生成可执行文件
add_dependencies(listener topic_demo_generate_messages_cpp)
target_link_libraries(listener ${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
## install(PROGRAMS
# scripts/my_python_script
# DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )
## Mark executables and/or libraries for installation
## install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_node
# ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
# LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
# RUNTIME DESTINATION ${CATKIN_PACKAGE_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_publish_subscribe_demo.cpp)
## if(TARGET ${PROJECT_NAME}-test)
## target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
## endif()
## Add folders to be run by python nosetests
## catkin_add_nosetests(test)
package.xml的编写主要是为了构建依赖,比较简单。见官网:http://wiki.ros.org/catkin/package.xml
<?xml version="1.0"?>
<package>
<name>topic_demo</name>
<version>0.0.0</version>
<description>The publish_subscribe_demo package</description>
<!-- One maintainer tag required, multiple allowed, one person per tag -->
<!-- Example: -->
<!-- <maintainer email="[email protected]">Jane Doe</maintainer> -->
<maintainer email="[email protected]">davidhan</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>BSD</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/publish_subscribe_demo</url> -->
<!-- Author tags are optional, multiple are allowed, one per tag -->
<!-- Authors do not have to be maintainers, but could be -->
<!-- Example: -->
<!-- <author email="[email protected]">Jane Doe</author> -->
<!-- The *_depend tags are used to specify dependencies -->
<!-- Dependencies can be catkin packages or system dependencies -->
<!-- Examples: -->
<!-- Use build_depend for packages you need at compile time: -->
<!-- <build_depend>message_generation</build_depend> -->
<!-- Use buildtool_depend for build tool packages: -->
<!-- <buildtool_depend>catkin</buildtool_depend> -->
<!-- Use run_depend for packages you need at runtime: -->
<!-- <run_depend>message_runtime</run_depend> -->
<!-- Use test_depend for packages you need only for testing: -->
<!-- <test_depend>gtest</test_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>
<run_depend>roscpp</run_depend>
<run_depend>rospy</run_depend>
<run_depend>std_msgs</run_depend>
<run_depend>message_runtime</run_depend>
<!-- The export tag contains other, unspecified, tags -->
<export>
<!-- Other tools can request additional information be placed here -->
</export>
</package>