我建立了reader和writer,reader文件写完了#include "rclcpp/rclcpp.hpp"
#include "geometry_msgs/msg/twist.hpp"
#include "rosbag2_cpp/writer.hpp"
class SimpleBagRecorder : public rclcpp::Node
{
public:
SimpleBagRecorder() : Node("simple_bag_recorder_node_cpp")
{
RCLCPP_INFO(this->get_logger(), "消息录制对象创建");
// 1.创建录制对象
writer_ = std::make_unique<rosbag2_cpp::Writer>();
rosbag2_cpp::StorageOptions storage_options;
storage_options.uri = "my_bag"; // 设置文件路径
writer_->open(storage_options,{});
// 3.写数据(创建速度订阅方,回调函数中执行写出操作)
// writer_->write()
sub_ = this->create_subscription<geometry_msgs::msg::Twist>(
"turtle1/cmd_vel", 10,
std::bind(&SimpleBagRecorder::do_write_msg, this, std::placeholders::_1));
}
private:
std::unique_ptr<rosbag2_cpp::Writer> writer_;
rclcpp::Subscription<rosbag2_storage::SerializedBagMessage>::SharedPtr sub_;
void do_write_msg(std::shared_ptr<rosbag2_storage::SerializedBagMessage> msg)
{
RCLCPP_INFO(this->get_logger(), "数据写出...");
writer_->write(msg);
// std::shared_ptr<rclcpp::SerializedMessage> message, // 被写出的消息
// const std::string & topic_name, // 话题名称
// const std::string & type_name, // 消息类型
// const rclcpp::Time & time); // 时间戳
}
};
int main(int argc, char const *argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<SimpleBagRecorder>());
rclcpp::shutdown();
return 0;
}
wirter文件一直在报错
#include "rclcpp/rclcpp.hpp"
#include "rosbag2_cpp/reader.hpp"
#include "geometry_msgs/msg/twist.hpp"
#include "rosbag2_cpp/converter.hpp"
class SimpleBagPlayer : public rclcpp::Node
{
public:
SimpleBagPlayer() : Node("simple_bag_play_node_cpp")
{
RCLCPP_INFO(this->get_logger(), "消息回放对象创建");
// 1.创建回放对象
reader_ = std::make_unique<rosbag2_cpp::Reader>();
// 2.设置被读取的文件
rosbag2_cpp::StorageOptions storage_options;
storage_options.uri = "my_bag"; // 设置文件路径
reader_->open(storage_options,{});
converter_ = std::make_unique<rosbag2_cpp::Converter>("rosbag2_cpp");
// 3.读消息
while (reader_->has_next())
{
auto msg = reader_->read_next();
auto twist_msg = converter_->deserialize<geometry_msgs::msg::Twist>(msg);
RCLCPP_INFO(this->get_logger(), "线速度:%.2f, 角速度:%.2f", twist.linear.x, twist.angular.z);
}
RCLCPP_INFO(this->get_logger(), "线速度:%.2f, 角速度:%.2f", twist_msg.linear.x, twist_msg.angular.z);
// 4.关闭文件
reader_->close();
}
private:
std::unique_ptr<rosbag2_cpp::Reader> reader_;
std::unique_ptr<rosbag2_cpp::Converter> converter_;
};
int main(int argc, char const *argv[])
{
rclcpp::init(argc, argv);
std::make_shared<SimpleBagPlayer>();
rclcpp::shutdown();
return 0;
}
因为我跟的教程是humble版本,但我用的是foxy,一直都没改好