38 lines
1.2 KiB
C++
38 lines
1.2 KiB
C++
// chatter_subscriber.cpp - ChatterSubscriber 类实现(不含 main)
|
|
#include "cpp_pubsub/chatter_subscriber.hpp"
|
|
|
|
#include <string>
|
|
|
|
namespace cpp_pubsub
|
|
{
|
|
|
|
ChatterSubscriber::ChatterSubscriber(const rclcpp::NodeOptions & options)
|
|
: rclcpp::Node("chatter_subscriber", options), received_count_(0)
|
|
{
|
|
this->declare_parameter<std::string>(
|
|
"topic_name", "chatter",
|
|
rcl_interfaces::msg::ParameterDescriptor().set__description("订阅话题名"));
|
|
|
|
const std::string topic_name = this->get_parameter("topic_name").as_string();
|
|
|
|
subscription_ = this->create_subscription<std_msgs::msg::String>(
|
|
topic_name, 10,
|
|
std::bind(&ChatterSubscriber::message_callback, this, std::placeholders::_1));
|
|
|
|
RCLCPP_INFO(this->get_logger(), "ChatterSubscriber subscribed: topic=\"%s\"", topic_name.c_str());
|
|
}
|
|
|
|
void ChatterSubscriber::message_callback(const std_msgs::msg::String::SharedPtr msg)
|
|
{
|
|
try {
|
|
received_count_++;
|
|
if (received_count_ % 10 == 0) {
|
|
RCLCPP_INFO(this->get_logger(),
|
|
"recv #%zu: \"%s\"", received_count_, msg->data.c_str());
|
|
}
|
|
} catch (const std::exception & exc) {
|
|
RCLCPP_ERROR(this->get_logger(), "callback failed: %s", exc.what());
|
|
}
|
|
}
|
|
|
|
} // namespace cpp_pubsub
|