C++で簡単な購読者を書く

7985 ワード

端末を開き、beginnerに入ります.tutorialsパッケージの下:
cd ~/catkin_ws/src/beginner_tutorials

ファイルを作成するcpp:
vim 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トピックに到達すると、このコールバック関数が呼び出されます.
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

chatterトピックを購読し、新しいメッセージが到着すると、ROSはchatterCallback()関数を呼び出します.2番目のパラメータは列の長さで、受信したメッセージがバッファリングされ、合計1000個のメッセージがバッファリングされ、1000個未満になると、後の到着メッセージが前のメッセージを上書きします.
NodeHandle::subscribe()はros::Subscriberタイプのオブジェクトを返し、サブスクリプションオブジェクトが破棄されると自動的にchatterトピックから取り消されます.
ros::spin();

ros::spin()はループに入り、メッセージのコールバック関数を非常に速く呼び出します.心配しないでください.何かできることがなければ、CPUを無駄にしません.
ros::ok()がfalseを返すと、ros::spin()は終了します.
これはros::shutdown()が呼び出されたり、CTRL+Cが押されたりした場合に終了できることを意味する.
次に,(1)ROSシステムを初期化(2)chatterトピックを購読(3)Spinし,メッセージの到来を待つ(4)メッセージが到着するとchatterCallback()関数が呼び出される.
ノードの構築方法を見てみましょう.前にcatkinを使ったことがありますcreate_pkgはpackageを作成した.xmlとCMakeLists.txt(ディレクトリ:catkin_ws/src/beginner_tutorials/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(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の最後.最終的にあなたの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)

構築が完了すると、2つの実行可能ファイル、talker、listenerが作成されます.それらは~/catkin_で生成されますws/devel/lib/share/ディレクトリの下、つまり構築されたものはdevelのディレクトリに置かれ、元のものはsrcファイルに残ります.
次に、ワークスペースのルートディレクトリに次のように入力します.
catkin_make

これにより,ある話題におけるメッセージのパブリッシャとサブスクライバの実行可能モジュールの作成が完了する.