ROS入门教程-1.1.11 编写简单的消息发布器和订阅器 (C++ catkin)
一. 编写发布器节点talker
-
"节点(Node)" 是ROS中指代连接到ROS网络的可执行文件的术语。
1.在beginner_tutorials package路径下创建src目录:
mkdir -p ~/catkin_ws/src/beginner_tutorials/src
-
这个目录将会存储beginner_tutorials package的所有源代码.
2.在beginner_tutorials package里创建src/talker.cpp文件,并粘贴如下代码:
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
/**
* This tutorial demonstrates simple sending of messages over the ROS system.
*/
int main(int argc, char **argv)
{
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line. For programmatic
* remappings you can use a different version of init() which takes remappings
* directly, but for most command-line programs, passing argc and argv is the easiest
* way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "talker");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
/**
* The advertise() function is how you tell ROS that you want to
* publish on a given topic name. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. After this advertise() call is made, the master
* node will notify anyone who is trying to subscribe to this topic name,
* and they will in turn negotiate a peer-to-peer connection with this
* node. advertise() returns a Publisher object which allows you to
* publish messages on that topic through a call to publish(). Once
* all copies of the returned Publisher object are destroyed, the topic
* will be automatically unadvertised.
*
* The second parameter to advertise() is the size of the message queue
* used for publishing messages. If messages are published more quickly
* than we can send them, the number here specifies how many messages to
* buffer up before throwing some away.
*/
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
ros::Rate loop_rate(10);
/**
* A count of how many messages we have sent. This is used to create
* a unique string for each message.
*/
int count = 0;
while (ros::ok())
{
/**
* This is a message object. You stuff it with data, and then publish it.
*/
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
/**
* The publish() function is how you send messages. The parameter
* is the message object. The type of this object must agree with the type
* given as a template parameter to the advertise<>() call, as was done
* in the constructor above.
*/
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
3.代码解释
//引用了ROS系统中大部分常用的头文件,使用它会使得编程很简便
#include "ros/ros.h"
//引用std_msgs/String 消息, 它存放在std_msgs package里,是由String.msg文件自动生成的头文件。
#include "std_msgs/String.h"
#include <sstream>
int main(int argc, char **argv)
{
//1.初始化ROS
ros::init(argc, argv, "talker");
//为这个进程的节点创建一个句柄
//第一个创建的NodeHandle会为节点进行初始化,最后一个销毁的会清理节点使用的所有资源
ros::NodeHandle n;
/**
* 2.在ROS网络内广播我们将要在chatter topic上发布std_msgs/String消息
*告诉master我们将要在chatter topic上发布一个std_msgs/String的消息。
*这样master就会告诉所有订阅了chatter topic的节点,将要有数据发布。
*第二个参数是发布序列的大小。
*在这样的情况下,如果我们发布的消息太快,缓冲区中的消息在大于1000个的时候就会开始丢弃先前发布的消*息。
*NodeHandle::advertise() ,返回一个 ros::Publisher对象,它有两个作用:
*1.它有一个publish()成员函数可以让你在topic上发布消息;2.如果消息类型不对,它会拒绝发布
*/
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
//自循环的频率,我们让它以10hz的频率运行
ros::Rate loop_rate(10);
/**
*roscpp会默认安装一个SIGINT句柄,它负责处理Ctrl-C键盘操作——使得ros::ok()返回FALSE。
*ros::ok()返回false,如果下列条件之一发生:
* SIGINT接收到(Ctrl-C)
* 被另一同名节点踢出ROS网络
* ros::shutdown()被程序的另一部分调用
* 所有的ros::NodeHandles都已经被销毁
*/
int count = 0;
while (ros::ok())
{
//现在我们使用标准的String消息,它只有一个数据成员"data"
std_msgs::String msg;
std::stringstream ss;
//把hello world 加上count的值一起给ss
ss << "hello world " << count;
//返回临时的string对象,而因为是临时的对象,所以它在整个表达式结束后将会被析构
msg.data = ss.str();
//用ROS_INFO输出
ROS_INFO("%s", msg.data.c_str());
//3.现在我们已经向所有连接到chatter topic的节点发送了消息
chatter_pub.publish(msg);
//在这个例子中并不是一定要调用ros::spinOnce(),因为我们不接受回调
ros::spinOnce();
//这条语句是调用ros::Rate对象来休眠一段时间以使得发布频率为10hz。
loop_rate.sleep();
++count;
}
return 0;
}
二. 编写订阅器节点
- 在beginner_tutorials package目录下创建src/listener.cpp文件,并粘贴如下代码:
#include "ros/ros.h"
#include "std_msgs/String.h"
/**
* This tutorial demonstrates simple receipt of messages over the ROS system.
*/
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
}
int main(int argc, char **argv)
{
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line. For programmatic
* remappings you can use a different version of init() which takes remappings
* directly, but for most command-line programs, passing argc and argv is the easiest
* way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "listener");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
/**
* The subscribe() call is how you tell ROS that you want to receive messages
* on a given topic. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. Messages are passed to a callback function, here
* called chatterCallback. subscribe() returns a Subscriber object that you
* must hold on to until you want to unsubscribe. When all copies of the Subscriber
* object go out of scope, this callback will automatically be unsubscribed from
* this topic.
*
* The second parameter to the subscribe() function is the size of the message
* queue. If messages are arriving faster than they are being processed, this
* is the number of messages that will be buffered up before beginning to throw
* away the oldest ones.
*/
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
/**
* ros::spin() will enter a loop, pumping callbacks. With this version, all
* callbacks will be called from within this thread (the main one). ros::spin()
* will exit when Ctrl-C is pressed, or the node is shutdown by the master.
*/
ros::spin();
return 0;
}
代码解释
#include "ros/ros.h"
#include "std_msgs/String.h"
//回调函数
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
}
int main(int argc, char **argv)
{
// 1.初始化Ros
ros::init(argc, argv, "listener");
ros::NodeHandle n;
/**
*2.订阅chatter topic
*告诉master我们要订阅chatter topic上的消息。
*当有消息到达topic时,ROS就会调用chatterCallback()函数。
*第二个参数是队列大小,以防我们处理消息的速度不够快,在缓存了1000个消息后,再有新的消息到来就将开
*始丢弃先前接收的消息
*NodeHandle::subscribe()返回ros::Subscriber对象,你必须让它处于活动状态直到你不再想订阅该消息。
*当这个对象销毁时,它将自动退订上的消息。
*/
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
//进入自循环,等待消息的到达,抽取回调
//按下Ctrl-C时将退出,或者主节点关闭节点。
ros::spin();
return 0;
}
三.编译节点
- 之前教程中使用catkin_create_pkg创建了package.xml 和 CMakeLists.txt 文件。
- 生成的CMakeLists.txt看起来应该是这样(在Creating Msgs and Srvs教程中的修改和未被使用的注释和例子都被移除了):
cmake_minimum_required(VERSION 2.8.3)
project(beginner_tutorials)
## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)
## Declare ROS messages and services
add_message_files(DIRECTORY msg FILES Num.msg)
add_service_files(DIRECTORY srv FILES AddTwoInts.srv)
## Generate added messages and services
generate_messages(DEPENDENCIES std_msgs)
## Declare a catkin package
catkin_package()
-
在CMakeLists.txt文件末尾加入8条语句,结果,CMakeLists.txt文件看起来像这样:
cmake_minimum_required(VERSION 2.8.3)
project(beginner_tutorials)
## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)
## Declare ROS messages and services
add_message_files(FILES Num.msg)
add_service_files(FILES AddTwoInts.srv)
## Generate added messages and services
generate_messages(DEPENDENCIES std_msgs)
## Declare a catkin package
catkin_package()
## Build talker and listener
include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
add_dependencies(talker beginner_tutorials_generate_messages_cpp)
add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})
add_dependencies(listener beginner_tutorials_generate_messages_cpp)
-
这会生成两个可执行文件, talker 和 listener, 默认存储到devel space目录
-
具体是在~/catkin_ws/devel/lib/中.
解释代码:
为可执行文件添加对生成的消息文件的依赖:
add_dependencies(talker beginner_tutorials_generate_messages_cpp)
这样就可以确保自定义消息的头文件在被使用之前已经被生成。因为catkin把所有的package并行的编译,所以如果你要使用其他catkin工作空间中其他package的消息,你同样也需要添加对他们各自生成的消息文件的依赖。
-
现在运行 catkin_make:
# In your catkin workspace
$ catkin_make
出现Built target........才算编译成功,以下只是一个样例
四.测试
启动发布器
- 确保roscore可用,并运行:
$ roscore
- catkin specific 如果使用catkin,确保你在调用catkin_make后,在运行你自己的程序前,已经source了catkin工作空间下的setup.sh文件:
# In your catkin workspace
$ cd ~/catkin_ws
$ source ./devel/setup.bash
- 上个教程开发了发布节点"talker". 现在运行它:
$ rosrun beginner_tutorials talker (C++)
- 你将看到如下的输出信息:
[INFO] [WallTime: 1314931831.774057] hello world 1314931831.77
[INFO] [WallTime: 1314931832.775497] hello world 1314931832.77
[INFO] [WallTime: 1314931833.778937] hello world 1314931833.78
[INFO] [WallTime: 1314931834.782059] hello world 1314931834.78
[INFO] [WallTime: 1314931835.784853] hello world 1314931835.78
[INFO] [WallTime: 1314931836.788106] hello world 1314931836.79
- 发布器节点已经启动运行。现在需要一个订阅器节点来接受发布的消息。
启动订阅器
- 上一教程,我们编写了一个名为"listener"的订阅器节点。现在运行它:
$ rosrun beginner_tutorials listener (C++)
你将会看到如下的输出信息:
[INFO] [WallTime: 1314931969.258941] /listener_17657_1314931968795I heard hello world 1314931969.26
[INFO] [WallTime: 1314931970.262246] /listener_17657_1314931968795I heard hello world 1314931970.26
[INFO] [WallTime: 1314931971.266348] /listener_17657_1314931968795I heard hello world 1314931971.26
[INFO] [WallTime: 1314931972.270429] /listener_17657_1314931968795I heard hello world 1314931972.27
[INFO] [WallTime: 1314931973.274382] /listener_17657_1314931968795I heard hello world 1314931973.27
[INFO] [WallTime: 1314931974.277694] /listener_17657_1314931968795I heard hello world 1314931974.28
[INFO] [WallTime: 1314931975.283708] /listener_17657_1314931968795I heard hello world 1314931975.28
五.编译没有生成可执行文件
catkin_ws/src/beginner_tutorials 文件夹下的package.xml文件没有写好,解决样例:
<package>
<name>beginner_tutorials</name>
<version>2.2.4</version>
<description>beginner_tutorials</description>
<maintainer email="111@qq.com">cc</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/beginner_tutorials</url>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>std_msgs</build_depend>
<build_depend>rospy</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>message_generation</build_depend>
<run_depend>message_runtime</run_depend>
</package>
自己生产的包里面没有package.xml文件,而是mainfest.xml文件,要把这个文件删了,改为package.xml文件