1
This commit is contained in:
@@ -18,22 +18,22 @@ ChatterPublisher::ChatterPublisher(const rclcpp::NodeOptions & options)
|
||||
: rclcpp::Node("chatter_publisher", options), publish_count_(0)
|
||||
{
|
||||
// 1) 声明参数(类型模板版 + 描述符)
|
||||
this->declare_parameter<int>(
|
||||
"publish_rate_hz", 2,
|
||||
this->declare_parameter<double>(
|
||||
"publish_rate_hz", 2.0,
|
||||
rcl_interfaces::msg::ParameterDescriptor().set__description("发布频率 (Hz)"));
|
||||
this->declare_parameter<std::string>(
|
||||
"topic_name", "chatter",
|
||||
rcl_interfaces::msg::ParameterDescriptor().set__description("发布话题名"));
|
||||
|
||||
// 2) 读参数
|
||||
const int publish_rate_hz = this->get_parameter("publish_rate_hz").as_int();
|
||||
const double publish_rate_hz = this->get_parameter("publish_rate_hz").as_double();
|
||||
const std::string topic_name = this->get_parameter("topic_name").as_string();
|
||||
|
||||
// 3) 构造发布者 + 定时器
|
||||
publisher_ = this->create_publisher<std_msgs::msg::String>(topic_name, 10);
|
||||
|
||||
const auto period = (publish_rate_hz > 0) ?
|
||||
std::chrono::milliseconds(1000 / publish_rate_hz) :
|
||||
const auto period = (publish_rate_hz > 0.0) ?
|
||||
std::chrono::milliseconds(static_cast<int>(1000.0 / publish_rate_hz)) :
|
||||
std::chrono::milliseconds(1000);
|
||||
|
||||
timer_ = this->create_wall_timer(
|
||||
@@ -41,7 +41,7 @@ ChatterPublisher::ChatterPublisher(const rclcpp::NodeOptions & options)
|
||||
|
||||
RCLCPP_INFO(
|
||||
this->get_logger(),
|
||||
"ChatterPublisher started: rate=%d Hz, topic=\"%s\"",
|
||||
"ChatterPublisher started: rate=%.2f Hz, topic=\"%s\"",
|
||||
publish_rate_hz, topic_name.c_str());
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ TEST_F(PubsubTest, PublisherConstructsWithDefaults)
|
||||
{
|
||||
auto node = std::make_shared<cpp_pubsub::ChatterPublisher>();
|
||||
EXPECT_EQ(node->get_name(), std::string("chatter_publisher"));
|
||||
EXPECT_EQ(node->get_parameter("publish_rate_hz").as_int(), 2);
|
||||
EXPECT_DOUBLE_EQ(node->get_parameter("publish_rate_hz").as_double(), 2.0);
|
||||
EXPECT_EQ(node->get_parameter("topic_name").as_string(), std::string("chatter"));
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user