本教程將介紹如何用 C++ 編寫發佈器節點和訂閱器節點。
內容
編寫發佈器節點
源代碼
代碼說明
編寫訂閱器節點
源代碼
代碼說明
編譯節點
測試
編寫發佈器節點
『節點』(Node) 是指 ROS 網絡中可執行文件。接下來,我們將會創建一個發佈器節點(“talker”),它將不斷的在 ROS 網絡中廣播消息。
切換到之前創建的 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 會爲節點進行初始化,最後一個銷燬的 NodeHandle 則會釋放該節點所佔用的所有資源。
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
告訴 master 我們將要在 chatter(話題名) 上發佈 std_msgs/String 消息類型的消息。這樣 master 就會告訴所有訂閱了 chatter 話題的節點,將要有數據發佈。第二個參數是發佈序列的大小。如果我們發佈的消息的頻率太高,緩衝區中的消息在大於 1000 個的時候就會開始丟棄先前發佈的消息。
NodeHandle::advertise() 返回一個 ros::Publisher 對象,它有兩個作用: 1) 它有一個 publish() 成員函數可以讓你在topic上發佈消息; 2) 如果消息類型不對,它會拒絕發佈。
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 話題的節點發送消息。
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 話題上發佈 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 話題的時候就會被調用。消息是以 boost shared_ptr 指針的形式傳輸,這就意味着你可以存儲它而又不需要複製數據。
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
告訴 master 我們要訂閱 chatter 話題上的消息。當有消息發佈到這個話題時,ROS 就會調用 chatterCallback() 函數。第二個參數是隊列大小,以防我們處理消息的速度不夠快,當緩存達到 1000 條消息後,再有新的消息到來就將開始丟棄先前接收的消息。
NodeHandle::subscribe() 返回 ros::Subscriber 對象,你必須讓它處於活動狀態直到你不再想訂閱該消息。當這個對象銷燬時,它將自動退訂 chatter 話題的消息。
有各種不同的 NodeHandle::subscribe() 函數,允許你指定類的成員函數,甚至是 Boost.Function 對象可以調用的任何數據類型。roscpp overview 提供了更爲詳盡的信息。
ros::spin();
ros::spin() 進入自循環,可以儘可能快的調用消息回調函數。如果沒有消息到達,它不會佔用很多 CPU,所以不用擔心。一旦 ros::ok() 返回 false,ros::spin() 就會立刻跳出自循環。這有可能是 ros::shutdown() 被調用,或者是用戶按下了 Ctrl-C,使得 master 告訴節點要終止運行。也有可能是節點被人爲關閉的。
還有其他的方法進行回調,但在這裏我們不涉及。想要了解,可以參考 roscpp_tutorials package 裏的一些 demo 應用。需要更爲詳盡的信息,可以參考 roscpp overview。
下邊,我們來總結一下:
初始化ROS系統
訂閱 chatter 話題
進入自循環,等待消息的到達
當消息到達,調用 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。
測試
既然已經編寫好了發佈器和訂閱器,下面讓我們來測試消息發佈器和訂閱器。
啓動發佈器
確保roscore可用,並運行:
$ roscore
catkin specific 如果使用catkin,確保你在調用catkin_make後,在運行你自己的程序前,已經source了catkin工作空間下的setup.sh文件:
# In your catkin workspace
$ cd ~/catkin_ws
$ source ./devel/setup.bash
In the last tutorial we made a publisher called "talker". Let's run it:
$ rosrun beginner_tutorials talker (C++)
$ rosrun beginner_tutorials talker.py (Python)
你將看到如下的輸出信息:
[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++)
$ rosrun beginner_tutorials listener.py (Python)
你將會看到如下的輸出信息:
[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
你已經測試完了發佈器和訂閱器