ROS-Note:编写简单的发布者和订阅者(C++)Writing Publisher Subscriber (c++)

编写发布者节点

节点Node”是连接到ROS网络的可执行文件。
在这里,将创建 publisher 发布者 (“talker”)节点,该节点将不断广播消息。

切换到之前的教程中创建的beginner_tutorials包

代码

创建src文件夹

src目录下创建talker.cpp文件并粘贴以下内容进去

#include "ros/ros.h"  // ros/ros.h包括了使用ROS系统中最常见的公共部分所需的全部头文件。
#include "std_msgs/String.h"//引用了位于std_msgs包里的std_msgs/String消息,从std_msgs包里的String.msg文件中自动生成的头文件

#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");//初始化ROS。这使得ROS可以通过命令行进行名称重映射——不过目前不重要。
  //这也是我们给节点指定名称的地方。节点名在运行的系统中必须是唯一的。
  //注意:名称必须是基本名称,例如不能包含任何斜杠/。

  /**
   * 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;//为这个进程的节点创建句柄。
  //创建的第一个NodeHandle实际上将执行节点的初始化,而最后一个被销毁的NodeHandle将清除节点所使用的任何资源。

  /**
   * 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);
//告诉主节点将要在chatter话题上发布一个类型为std_msgs/String的消息。
//这会让主节点告诉任何正在监听chatter的节点,我们将在这一话题上发布数据。
//第二个参数是发布队列的大小。在本例中,如果我们发布得太快,它将最多缓存1000条消息,不然就会丢弃旧消息。
//NodeHandle::advertise()返回一个ros::Publisher对象,它有2个目的:
//其一,它包含一个publish()方法,可以将消息发布到创建它的话题上;
//其二,当超出范围时,它将自动取消这一宣告操作。

  ros::Rate loop_rate(10);
//ros::Rate对象能让你指定循环的频率。
//它会记录从上次调用Rate::sleep()到现在已经有多长时间,并休眠正确的时间。在本例中,我们告诉它希望以10Hz运行。
  /**
   * 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())
  {
//  默认情况下,roscpp将安装一个SIGINT处理程序,它能够处理Ctrl+C操作,让ros::ok()返回false。
//  ros::ok()在以下情况会返回false:
//  1 收到SIGINT信号(Ctrl+C)
//  2 被另一个同名的节点踢出了网络
//  3 ros::shutdown()被程序的另一部分调用
//  4 所有的ros::NodeHandles都已被销毁
//  一旦ros::ok()返回false, 所有的ROS调用都会失败。
    /**
     * 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上广播消息,
//该类通常由msg文件生成。更复杂的数据类型也可以,不过我们现在将使用标准的String消息,
//它有一个成员:data
    ROS_INFO("%s", msg.data.c_str());//ROS_INFO和它的友类可用来取代printf/cout

    /**
     * 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();
    //此处调用ros::spinOnce()对于这个简单程序来说没必要,因为我们没有接收任何回调。
    //然而,如果要在这个程序中添加订阅,但此处没有ros::spinOnce()的话,回调函数将永远不会被调用。
    //所以还是加上

    loop_rate.sleep();//现在我们使用ros::Rate在剩下的时间内睡眠,以让我们达到10Hz的发布速率
    ++count;
  }


  return 0;
}

总结

1 初始化ROS系统
2 向主节点宣告我们将要在chatter话题上发布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());
}
//这是一个回调函数,当有新消息到达chatter话题时它就会被调用。
//该消息是用boost shared_ptr智能指针传递的,这意味着你可以根据需要存储它,
//即不用担心它在下面被删除,又不必复制底层(underlying)数据。

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);
//通过主节点订阅chatter话题。
//每当有新消息到达时,ROS将调用chatterCallback()函数。
//第二个参数是队列大小,以防我们处理消息的速度不够快。
//在本例中,如果队列达到1000条,再有新消息到达时旧消息会被丢弃。
//NodeHandle::subscribe()返回一个ros::Subscriber对象,你必须保持它,除非想取消订阅。
//当Subscriber对象被析构,它将自动从chatter话题取消订阅。
//还有另一些版本的NodeHandle::subscribe()函数,可以让你指定为类的成员函数,
//甚至是可以被Boost.Function对象调用的任何函数。请参见roscpp概览。
  /**
   * 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();
//ros::spin()启动了一个自循环,它会尽可能快地调用消息回调函数。
//如果没有什么事情,它就不会占用太多CPU。
//另外,一旦ros::ok()返回false,ros::spin()就会退出,这意味着ros::shutdown()被调用了,主节点让我们关闭(或是因为按下Ctrl+C,它被手动调用)。
//还有其他的方法可以进行回调,但是我们在这里不考虑这些。可以自己研究下roscpp_tutorials包中的一些示例程序,或看看roscpp概览。
  return 0;
}

总结
1 初始化ROS系统
2 订阅chatter话题
3 开始spin自循环,等待消息的到达
4 当消息到达后,调用chatterCallback()函数

构建节点

使用catkin_create_pkg创建的package.xml和CMakeLists.txt文件,
最后编写的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)

将创建两个可执行文件talkerlistener,默认情况下,它们将被放到软件包目录下的devel空间中,
即~/catkin_ws/devel/lib/。
必须为可执行目标添加依赖项到消息生成目标

add_dependencies(talker beginner_tutorials_generate_messages_cpp)

这确保了在使用此包之前生成了该包的消息头message headers。
如果使用来自catkin工作空间中的其他包中的消息,则还需要将依赖项添加到各自的生成目标中,因为catkin将所有项目并行构建。
在ROS Groovy及更新版本中,还可以使用以下变量来依赖所有必需的目标

target_link_libraries(talker ${catkin_LIBRARIES})

可以直接调用可执行文件,也可以使用rosrun来调用它们。
它们没有被放在/bin中,因为将软件包安装到系统时会污染PATH环境变量。
但如果希望在安装时将可执行文件放在PATH中,可以配置安装目标,参见CMakeLists.txt。
运行catkin_make
如果又添加了新的包,可能需要通过指定**–force-cmake**参数来让catkin强制生成

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值