#include <memory>
#include "rclcpp/rclcpp.hpp"
#include "hbm_img_msgs/msg/hbm_msg1080_p.hpp"

class MinimalHbmemSubscriber : public rclcpp::Node
{
public:
  MinimalHbmemSubscriber()
  : Node("qr_detection")
  {
    // 创建 subscription_hbmem，topic 为 "hbmem_img"
    // 消息回调函数为 topic_callback
    subscription_ =
      this->create_subscription_hbmem<hbm_img_msgs::msg::HbmMsg1080P>(
        "hbmem_img",
        10,
        std::bind(&MinimalHbmemSubscriber::topic_callback, this, std::placeholders::_1));
  }

private:
  // 消息回调函数
  void topic_callback(
    const hbm_img_msgs::msg::HbmMsg1080P::SharedPtr msg) const
  {
    // 创建 Clock 对象并获取当前时间
    auto clock = std::make_shared<rclcpp::Clock>(RCL_SYSTEM_TIME);
    auto now = clock->now();

    // 转换消息时间戳为 ROS 时间
    auto msg_time = rclcpp::Time(msg->time_stamp.sec, msg->time_stamp.nanosec);

    // 计算延时（单位：微秒）
    auto duration = now - msg_time;
    auto delay_us = duration.nanoseconds() / 1000; // 转换为微秒

    // 打印延迟
    RCLCPP_INFO(this->get_logger(), "msg index: %d, time cost %dus", msg->index, delay_us);
  }

  // hbmem subscription
  rclcpp::SubscriptionHbmem<hbm_img_msgs::msg::HbmMsg1080P>::SharedPtr subscription_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<MinimalHbmemSubscriber>());
  rclcpp::shutdown();
  return 0;
}
