ROS学习笔记之——编写一个简单的发布者和订阅者
// src/talker.cpp
#include "ros/ros.h"
#include "std_msgs/String.h"
#include
/**
* 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("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;
}
代码说明:
ros/ros.h 头文件中包含了ros系统中绝大部分公用部分的所有必需的headers
std_msgs/String 消息在std_msgs包中,该头文件由std_msgs功能包中的String.msg文件自动生成
在使用ROS系统的其他部分之前,必须先调用ros::init()函数,用于初始化ROS,而且允许ROS通过命令行进行名称重映射。第3个参数为节点的名字,必须是一个base name,即不能含有/
ros::NodeHandle n;
为此进程的节点创建句柄。第一个创建的NodeHandle用于初始化节点,最后一个NodeHandle被毁时会清除节点所占用的任何资源
ros::Publisher chatter_pub = n.advertise < std_msgs::String > (“chatter”, 1000);
告诉master,该节点要在chatter话题上发布std_msgs/String类型的消息。第2个参数用来设定分布队列的大小,如果消息分布得太快,最多存储1000个消息,之后会扔掉最先存储的消息来容纳最新发布的消息。NodeHandle::advertise()返回一个ros::Publisher对象,有两个作用:1.包含一个publish()方法用于发布消息;2.当离开作用域时会自动停止广播(unadvertise)
ros::Rate loop_rate(10);
使用ros::Rate对象可以指定要循环的频率。它将跟踪自上次调用Rate::sleep()以来的持续时间,并在正确的时间内休眠。
默认情况下,roscpp将安装一个SIGINT处理程序,该处理程序提供Ctrl-C处理,如果发生这种情况,将导致ros::ok()返回false。
当以下情况之一发生时,ros::ok()将返回false,
1.接受到一个SIGINT(Ctrl+C)
2.该节点已被另一个具有相同名称的节点踢出ROS网络
3.程序的任何其他部分已将调用了ros::shutdown()
4.所有的ros::NodeHandles已经被销毁
一旦ros::ok()返回false,所有的ROS调用都会失败
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();
我们使用消息适配类在ROS上广播消息,它通常从msg文件生成。
chatter_pub.publish(msg);
向任何已经连接的节点广播消息
ROS_INFO和类似的函数用于替代 printf/cout
ros::spinOnce();
在此例中调用ros::spinOnce()并不是必须的,因为没有接受任何回调函数。但是,如果您要在此应用程序中添加了订阅,并且此处没有ros::spinOnce(),那么回调函数将永远不会得到调用。
loop_rate.sleep();
现在我们使用ros::Rate对象在剩余时间内休眠,让我们达到10Hz的发布速度。
总结:
1.初始化ROS系统
2.广播该节点将在chatter话题上向master发布std_msgs/String 类型的消息
3.循环发布消息,每10Hz一次向chatter发布消息
// 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;
}
代码说明:
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO(“I heard: [%s]”, msg->data.c_str());
}
这是一个回调函数,当一个新消息到达chatter话题时将被调用。 消息在boost shared_ptr中传递,这意味
着您可以根据需要将其存储起来,而不必担心它会被删除,并且不会复制基础数据。
ros::Subscriber sub = n.subscribe(“chatter”, 1000, chatterCallback);
向matser订阅chatter话题。每当有新消息到达时,ROS都会调用chatterCallback()函数。第二个参数是队列大小,以防我们无法足够快地处理消息。在这种情况下,如果队列达到1000条消息,我们将在新消息到达时开始丢弃旧消息。NodeHandle::subscribe()返回一个ros::Subscriber对象,您必须保留该对象,直到您想取消订阅为止。订阅者对象被销毁后,它将自动取消订阅chatter话题。
ros::spin();
ros::spin()进入一个循环,尽可能快地调用消息回调函数。不过不用担心,如果没有什么可以做的话就不会占用太多的CPU。一旦ros::ok()返回false,ros::spin()将会退出,这意味着已经调用了ros::shutdown(),可以是默认的Ctrl-C处理程序,或master告诉我们关闭,或者手动调用它。
总结:
1.初始化ROS
2.订阅chatter话题
3.循环,等待消息到达
4.当消息到达时,调用回调函数chatterCallback()
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)
注意:最后add_dependencies选项也可以写为下面这种形式
add_dependencies(talker ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
add_dependencies(listener ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
推荐采用后面一种写法,新的ROS版本普遍采用这种形式。
<package format="2">
<name>beginner_tutorialsname>
<version>0.0.0version>
<description>The beginner_tutorials packagedescription>
<license>TODOlicense>
<buildtool_depend>catkinbuildtool_depend>
<build_depend>roscppbuild_depend>
<build_depend>rospybuild_depend>
<build_depend>std_msgsbuild_depend>
<build_export_depend>roscppbuild_export_depend>
<build_export_depend>rospybuild_export_depend>
<build_export_depend>std_msgsbuild_export_depend>
<build_depend>message_generationbuild_depend>
<exec_depend>roscppexec_depend>
<exec_depend>rospyexec_depend>
<exec_depend>std_msgsexec_depend>
<exec_depend>message_runtimeexec_depend>
<export>
export>
package>
参考资料:http://wiki.ros.org/cn/ROS/Tutorials/WritingPublisherSubscriber(c%2B%2B)