机器人操作系统ROS Indigo 入门学习(12)——用C++语言写一个简单的发布者和订阅者

本文主要是介绍机器人操作系统ROS Indigo 入门学习(12)——用C++语言写一个简单的发布者和订阅者,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这个教程将会包含怎样用C++去写一个发布者和订阅者.

 

1.1写一个发布者Node

“Node”是连接在ROS网络中一个可执行单元的术语.这里我们创建一个会不断广播messages的发布者(“talker”)node.

改变目录到你之前创建的工作空间的beginner_tutorials package中:

cd ~/catkin_ws/src/beginner_tutorials

 

1.1.1代码

在beginner_tutorials packag目录中创建一个srv目录:

mkdir -p ~/catkin_ws/src/beginner_tutorials/src

这个目录会包含所有beginner_tutorials package中的源文件.

在beginner_tutorials package中创建一个src/talker.cpp文件.并且把下面的代码粘贴上去":

https://raw.github.com/ros/ros_tutorials/groovy-devel/roscpp_tutorials/talker/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;}


 

 

 

1.1.2代码解释

现在我们分解代码.

#include “ros/ros.h”

ros/ros.h是一个非常方便的头文件它包含了最常用的ROS系统部分所必须的一些头文件.

#include “std_msgs/String.h

这里包含了std_msgs package中的std_msgs/String message .这个头文件自动的从String.msg.file中产生.更多关于message的信息,请查看msg page.

 

 

Ros::init(argc,argv,”talker”);

初始化ROS.这个允许ROS通过命令行重新映射名字 –现在不重要.同样可以用来指定node的名字.在系统中Nodes的名字必须是唯一的.

名字必须是一个基本的名字(base name),比如,不能有/在里面.

 

Ros::NodesHandle n;

为这个node创建一个handle.创建的第一个NodeHandle用来初始化node,最后一个销毁的NodeHandle会清除所有node占有的资源.

 

 ros::Publisher chatter_pub = n.advertise<std_msgs::

String>("chatter", 1000);

告诉master我们将要在chatter topic中要发布一个std_msgs::String类型的message,这就会让master告诉所有的nodes听取chatter这个topic,在这个tpoic上在我们将要发布数据.第二个参数是发布队列的大小.这样的话如果我们发布的太快,在开始丢弃之前的message前,它会最大缓冲1000个messages.

 

NodeHandle::advertise()返回一个ros::Publisher的对象,它有两个作用:(1)它允许你发布message到它创建的topic上的publish()(2)当它超出范围时,会自动解除广播.

 

ros::Rate loop_rate(10);

ros::Rate对象会指定一个你想循环的频率.它会跟踪距离上次调用Rate::sleep(),有多长时间了,并且休眠正确长度的时间.

这里我们设置为10hz:

 

int count  =0;

while(ros::ok())

{}

默认roscpp会安装一个SIGINT信号处理函数提供对ctrl+c的处理,ctrl+c会导致ros::ok()返回错误.

 

ros::ok()会返回错误如果:

接受到SIGINT(ctrl+c)

我们通过用另一个有同样名字的node网络

ros::shutdown()被应用的另部分调用

所有的 ros::NodeHandles都被摧毁了

 

一旦ros::ok()返回错误,所有的ROS调用都会失败.

  87     std_msgs::String msg;

  88 

  89     std::stringstream ss;

  90     ss << "hello world " << count;

  91     msg.data = ss.str();

 

我们使用适应message的类在ROS上广播了一个message,通常从一个msg文件产生出来。其他复杂的数据类型也是是可以的,但是现在我们准备用标准的String message,它有一个成员:”data”。

chatter_pub.publish(msg);

现在实际上我们在向任何一个连接上的人广播这个message.

 

ROS_INFO("%s", msg.data.c_str());

 

ROS_INFO和它的友元类都是用来替代printf/cout的。更多信息请看rosconsole documentation

 

    ros::spinOnce();

 

对于这个程序调用ros::splinOnce()不是必要的,因为我们不会接受到任何回叫信号。然而,如果你打算为这个应用添加一个订阅,并且没有调用ros::splinOnce(),你绝不会得到回叫信号,所以还是添加的好。

loop_rate.sleep();

 

现在使用ros::Rate对象去空耗掉剩下的时间以满足10hz的发布速度。

 

这里是步骤的简要描叙:

初始化ROS系统

广告给master我们将要发布std_msgs/Stringmessage到chatter topic上

在发布message的时候循环以满足10次每秒钟

 

1.2写一个订阅者 Node

1.2.1代码

beginner_tutorials package中src目录下创建listener.cpp文件,并且把下面的代码粘贴进去:

https://raw.github.com/ros/ros_tutorials/groovy-devel/roscpp_tutorials/listener/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;}


 

 

 

1.2.2代码解释

现在,我们把代码打断成一段段的,忽略上面已经分析过的部分

 34 void chatterCallback(const std_msgs::String::ConstPtr& msg)

  35 {

  36   ROS_INFO("I heard: [%s]", msg->data.c_str());

  37 }

当一个新的message抵达chatter topic时这个回调函数会被调用.这个message以boost shared_ptr,的形式传递,这意味着你可以储存它,而不用担心它会在被删除,并且无需拷贝底层的数据.

 

 ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

在master启动的前提下订阅chatter topicROS会调用chatter Callback()函数只要一个新的message到达时.第二个参数是队列的大小,假设我们没有足够的能力去使发送message足够的快.这样的话,如果队列达到1000个messages,随着新的message的到来,我们会开始丢掉旧的message.

 

NodeHandle::subscribe()会返回一个ros::Subscriber 对象,你必须坚持这个订阅对象直到你想取消订阅.当订阅对象被摧毁时,它会自动取消订阅chatter topic.

 

这里有不同版本的NodeHandle::subscribe()函数允许你指定一个类的成员函数,或者甚至任何被BoostFunction对象调用的东西,roscpp overview包含更多的信息.

 

ros::spin();

 ros::spin()进入了一个循环,调用message回调尽可能的快.即使这样,但不用担心,如果没有什么要做就不会占用许多CPU资源,ros::spin()会退出一旦ros::ok()返回错误,这意味着ros::shutdown()被调用了,不是被默认的Ctrl+c处理函数然后master告诉我们去关机,就是被手动调用.

 

还有其他调用回调函数的方法,但是这里我们不关心它.roscpp_tutorials package有一些关于这个的应用演示roscpp overview 也包含更多的信息.

这里再一次简要的概括以上内容:

初始化ROS系统

订阅chatter topic

Spin,等待message到来

当一个message到来时,chatterCallback()函数被调用

 

 

1.3编译代码

在之前的教程中你用catkin_create_pkg去创建一个package.xml和一个CMakeLists.txt文件.

 

产生的这个CMakeLists.txt文件看起来应该像这样(保留了在Creating Msgs and Srvs中的修改和除去没有用的注释和例子):

https://raw.github.com/ros/catkin_tutorials/master/create_package_modified/catkin_ws/src/beginner_tutorials/CMakeLists.txt

 

   1 cmake_minimum_required(VERSION 2.8.3)

   2 project(beginner_tutorials)

   3 

   4 ## Find catkin and any catkin packages

   5 find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)

   6 

   7 ## Declare ROS messages and services

   8 add_message_files(DIRECTORY msg FILES Num.msg)

   9 add_service_files(DIRECTORY srv FILES AddTwoInts.srv)

  10 

  11 ## Generate added messages and services

  12 generate_messages(DEPENDENCIES std_msgs)

  13 

  14 ## Declare a catkin package

  15 catkin_package()

不要担心修改被注释掉的例子,只需要添加下面几行到你的CMakeLists.txt文件就好了:

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)


 

 

 

最后的CMakeLists.txt文件看起来应该像这样:

https://raw.github.com/ros/catkin_tutorials/master/create_package_pubsub/catkin_ws/src/beginner_tutorials/CMakeLists.txt
1 cmake_minimum_required(VERSION 2.8.3)2 project(beginner_tutorials)3 4 ## Find catkin and any catkin packages5 find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)6 7 ## Declare ROS messages and services8 add_message_files(FILES Num.msg)9 add_service_files(FILES AddTwoInts.srv)10 11 ## Generate added messages and services12 generate_messages(DEPENDENCIES std_msgs)13 14 ## Declare a catkin package15 catkin_package()16 17 ## Build talker and listener18 include_directories(include ${catkin_INCLUDE_DIRS})19 20 add_executable(talker src/talker.cpp)21 target_link_libraries(talker ${catkin_LIBRARIES})22 add_dependencies(talker beginner_tutorials_generate_messages_cpp)23 24 add_executable(listener src/listener.cpp)25 target_link_libraries(listener ${catkin_LIBRARIES})26 add_dependencies(listener beginner_tutorials_generate_messages_cpp)


 

这会创建两个可执行的文件,talker和listener,默认是在的devel的package目录中,默认是在~/catkin_ws/devel/lib/share/<package name>

 

注意你应该为可执行目标添加依赖到message generation 目标:

add_dependencies(talker beginner_tutorials_generate_messages_cpp)

 

这就可以保证package的message header在使用之前可以生成,如果你使用你工作空间的其他package产生的messages,你也需要为它们单独生成的目标添加依赖。

 

因为catkin平行编译所有的工程。如果是“Groovy”你可以用下面的变量去依靠所有必须的目标:

add_dependencies(talker ${catkin_EXPORTED_TARGETS})

 

如果你可以使用rosrun去调用他们,可以直接调用它们。他们不是放在'<prefix>/bin' 中因为在安装package到你的系统时会破坏PATH.如果你希望你的可执行文件安装的时候在PATH上,你可以建立一个安装目标,查看:catkin/CMakeLists.txt

 

 

catkin/CMakeLists.txt的更多详细的描叙请看:catkin/CMakeLists.txt

 

 

现在运行:

$ catkin_make

 

注意:如果你在添加一个新的pkg,也许需要告诉catkin去强制编译通过—force-cmake选项。参阅catkin/Tutorials/using_a_workspace#With_catkin_make.

这篇关于机器人操作系统ROS Indigo 入门学习(12)——用C++语言写一个简单的发布者和订阅者的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1001510

相关文章

MySQL DQL从入门到精通

《MySQLDQL从入门到精通》通过DQL,我们可以从数据库中检索出所需的数据,进行各种复杂的数据分析和处理,本文将深入探讨MySQLDQL的各个方面,帮助你全面掌握这一重要技能,感兴趣的朋友跟随小... 目录一、DQL 基础:SELECT 语句入门二、数据过滤:WHERE 子句的使用三、结果排序:ORDE

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

C++作用域和标识符查找规则详解

《C++作用域和标识符查找规则详解》在C++中,作用域(Scope)和标识符查找(IdentifierLookup)是理解代码行为的重要概念,本文将详细介绍这些规则,并通过实例来说明它们的工作原理,需... 目录作用域标识符查找规则1. 普通查找(Ordinary Lookup)2. 限定查找(Qualif

基于Python实现一个简单的题库与在线考试系统

《基于Python实现一个简单的题库与在线考试系统》在当今信息化教育时代,在线学习与考试系统已成为教育技术领域的重要组成部分,本文就来介绍一下如何使用Python和PyQt5框架开发一个名为白泽题库系... 目录概述功能特点界面展示系统架构设计类结构图Excel题库填写格式模板题库题目填写格式表核心数据结构

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Go语言中泄漏缓冲区的问题解决

《Go语言中泄漏缓冲区的问题解决》缓冲区是一种常见的数据结构,常被用于在不同的并发单元之间传递数据,然而,若缓冲区使用不当,就可能引发泄漏缓冲区问题,本文就来介绍一下问题的解决,感兴趣的可以了解一下... 目录引言泄漏缓冲区的基本概念代码示例:泄漏缓冲区的产生项目场景:Web 服务器中的请求缓冲场景描述代码