編寫簡單的消息發佈器和訂閱器(C ++ catkin)
編寫發佈器節點
-
"節點(Node)" 是ROS中指代連接到ROS網絡的可執行文件的術語。
-
接下來,我們將會創建一個發佈器節點("talker"),它將不斷的在ROS網絡中廣播消息。
-
轉移到之前教程在catkin工作空間所創建的beginner_tutorials package路徑下:
cd ~/catkin_ws/src/beginner_tutorials
源代碼
- 在beginner_tutorials package路徑下創建src目錄:
mkdir -p ~/catkin_ws/src/beginner_tutorials/src
-
這個目錄將會存儲beginner_tutorials package的所有源代碼.
-
在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;
}
代碼解釋
-
現在,我們來分段解釋代碼.
#include "ros/ros.h"
-
ros/ros.h是一個實用的頭文件,它引用了ROS系統中大部分常用的頭文件,使用它會使得編程很簡便。
#include "std_msgs/String.h"
- 這引用了std_msgs/String 消息, 它存放在std_msgs package裏,是由String.msg文件自動生成的頭文件。
- 需要更詳細的消息定義,參考msg頁面.
ros::init(argc, argv, "talker");
- 初始化ROS。它允許ROS通過命令行進行名稱重映射——目前,這不是重點。
- 同樣,我們也在這裏指定我們節點的名稱——必須唯一。
- 這裏的名稱必須是一個base name,不能包含/。
ros::NodeHandle n;
- 爲這個進程的節點創建一個句柄。
- 第一個創建的NodeHandle會爲節點進行初始化,最後一個銷燬的會清理節點使用的所有資源。
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
- 告訴master我們將要在chatter topic上發佈一個std_msgs/String的消息。
- 這樣master就會告訴所有訂閱了chatter topic的節點,將要有數據發佈。
- 第二個參數是發佈序列的大小。
- 在這樣的情況下,如果我們發佈的消息太快,緩衝區中的消息在大於1000個的時候就會開始丟棄先前發佈的消息。
NodeHandle::advertise()
-
返回一個 ros::Publisher對象,它有兩個作用:
-
- 它有一個publish()成員函數可以讓你在topic上發佈消息;
-
- 如果消息類型不對,它會拒絕發佈。
-
ros::Rate loop_rate(10);
- ros::Rate對象可以允許你指定自循環的頻率。
- 它會追蹤記錄自上一次調用Rate::sleep()後時間的流逝,並休眠直到一個頻率週期的時間。
- 在這個例子中,我們讓它以10hz的頻率運行。
int count = 0;
while (ros::ok())
{
-
roscpp會默認安裝一個SIGINT句柄,它負責處理Ctrl-C鍵盤操作——使得ros::ok()返回FALSE。
-
ros::ok()返回false,如果下列條件之一發生:
- SIGINT接收到(Ctrl-C)
- 被另一同名節點踢出ROS網絡
- ros::shutdown()被程序的另一部分調用
- 所有的ros::NodeHandles都已經被銷燬
- 一旦ros::ok()返回false, 所有的ROS調用都會失效。
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();
- 我們使用一個由msg file文件產生的‘消息自適應’類在ROS網絡中廣播消息。
- 現在我們使用標準的String消息,它只有一個數據成員"data"。
- 當然你也可以發佈更復雜的消息類型。
chatter_pub.publish(msg);
- 現在我們已經向所有連接到chatter topic的節點發送了消息。
ROS_INFO("%s", msg.data.c_str());
- ROS_INFO和類似的函數用來替代printf/cout.
- 參考rosconsole documentation以獲得更詳細的信息。
ros::spinOnce();
- 在這個例子中並不是一定要調用ros::spinOnce(),因爲我們不接受回調。
- 然而,如果你想拓展這個程序,卻又沒有在這調用ros::spinOnce(),你的回調函數就永遠也不會被調用。
- 所以,在這裏最好還是加上這一語句。
loop_rate.sleep();
-
這條語句是調用ros::Rate對象來休眠一段時間以使得發佈頻率爲10hz。
-
對上邊的內容進行一下總結:
-
初始化ROS系統
-
在ROS網絡內廣播我們將要在chatter topic上發佈std_msgs/String消息
-
以每秒10次的頻率在chatter上發佈消息
-
接下來我們要編寫一個節點來接收消息。
-
編寫訂閱器節點
源代碼
- 在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;
}
代碼解釋
- 下面我們將逐條解釋代碼,當然,之前解釋過的代碼就不再贅述了。
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
}
- 這是一個回調函數,當消息到達chatter topic的時候就會被調用。
- 消息是以 boost shared_ptr指針的形式傳輸,這就意味着你可以存儲它而又不需要複製數據
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
- 告訴master我們要訂閱chatter topic上的消息。
- 當有消息到達topic時,ROS就會調用chatterCallback()函數。
- 第二個參數是隊列大小,以防我們處理消息的速度不夠快,在緩存了1000個消息後,再有新的消息到來就將開始丟棄先前接收的消息。
- NodeHandle::subscribe()返回ros::Subscriber對象,你必須讓它處於活動狀態直到你不再想訂閱該消息。
- 當這個對象銷燬時,它將自動退訂上的消息。
- 有各種不同的NodeHandle::subscribe()函數,允許你指定類的成員函數,甚至是Boost.Function對象可以調用的任何數據類型。roscpp overview 提供了更爲詳盡的信息。
ros::spin();
-
ros::spin()進入自循環,可以儘可能快的調用消息回調函數。
-
如果沒有消息到達,它不會佔用很多CPU,所以不用擔心。一旦ros::ok()返回FALSE,ros::spin()就會立刻跳出自循環。
-
這有可能是ros::shutdown()被調用,或者是用戶按下了Ctrl-C,使得master告訴節點要shutdown。
-
也有可能是節點被人爲的關閉。
-
還有其他的方法進行回調,但在這裏我們不涉及。
-
想要了解,可以參考roscpp_tutorials package裏的一些demo應用。
-
需要更爲詳盡的信息,參考roscpp overview。
-
下邊,我們來總結一下:
- 初始化ROS系統
- 訂閱chatter topic
- 進入自循環,等待消息的到達
- 當消息到達,調用chatterCallback()函數
編譯節點
- 之前教程中使用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文件末尾加入幾條語句:
include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES}) -
結果,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的消息,你同樣也需要添加對他們各自生成的消息文件的依賴。
- 當然,如果在Groovy版本下,你可以使用下邊的這個變量來添加對所有必須的文件依賴:
add_dependencies(talker ${catkin_EXPORTED_TARGETS})
-
你可以直接調用可執行文件,也可以使用rosrun來調用他們。他們不會被安裝到'/bin'路徑下,因爲那樣會改變系統的PATH環境變量。如果你確定要將可執行文件安裝到該路徑下,你需要設置安裝目標,請參考catkin/CMakeLists.txt
-
需要關於CMakeLists.txt更詳細的信息,請參考catkin/CMakeLists.txt
-
現在運行 catkin_make:
# In your catkin workspace
$ catkin_make
- 注意:如果你是添加了新的package,你需要通過--force-cmake選項告訴catkin進行強制編譯。
- 參考catkin/Tutorials/using_a_workspace#With_catkin_make.