This commit is contained in:
trung09122002
2026-09-18 18:14:42 +07:00
commit 48bd5377dc
224 changed files with 37685 additions and 0 deletions

View File

@@ -0,0 +1,105 @@
#ifndef VSLAM_CLOCK_SYNC_H
#define VSLAM_CLOCK_SYNC_H
// Dong bo dong ho MCU <-> host: host_time = skew * mcu_time + offset.
//
// Port tu robot_drivers/scripts/imu_bridge_node.py:51-111, kem MOT SUA LOI
// quan trong ma ban Python khong co.
//
// ================== BUG TRAN micros() ==================
// micros() tren MCU la uint32_t: no TRAN moi 71.58 phut (2^32 us).
//
// Ban Python khong unwrap. Sau 71 phut, mcu_time nhay tu ~4295 giay ve 0,
// fit tuyen tinh vo, kiem tra |skew - 1| > 1e-3 tu choi ket qua, va fallback
// `offset = (sy - sx) / n` la rac -> MOI stamp IMU sai hang nghin giay.
//
// Trieu chung tren robot that: sau hon mot gio chay, TransformTree tu choi moi
// lookup vi stamp o tuong lai xa, robot dung im, va khong co gi trong log noi
// tai sao. Day dung la loai bug chi hien ra khi chay lau -- tuc la chi hien ra
// khi dang trinh dien.
//
// McuTimeUnwrapper o duoi xu ly viec do. PHAI goi theo dung thu tu ban tin den.
//
// ================== VI SAO CHI GIU MAU RTT NHO ==================
// RTT lon nghia la ban tin bi tre boi lich CPU hoac buffer serial, va do tre
// do gan nhu luon BAT DOI XUNG. Gia dinh `host = (t_send + t_recv) / 2` chi
// dung khi do tre doi xung, nen mau RTT lon lam hong uoc luong. Giu 16 mau
// nho nhat trong cua so 64.
#include <cstddef>
#include <cstdint>
#include <deque>
#include <memory>
namespace vslam {
// Go tran uint32_t cua micros(). PHAI goi theo thu tu ban tin den.
class McuTimeUnwrapper {
public:
// Tra ve thoi gian MCU tinh bang giay, da cong phan tran.
double UnwrapSeconds(uint32_t micros);
void Reset();
uint64_t wrap_count() const { return wraps_; }
private:
uint32_t prev_us_ = 0;
uint64_t high_ = 0; // tong phan da tran, tinh bang micro giay
uint64_t wraps_ = 0;
bool first_ = true;
};
// O pham vi namespace chu khong long trong ClockSync: mot struct long co
// default member initializer khong dung lam DOI SO MAC DINH cho ham thanh vien
// cua chinh lop bao duoc -- NSDMI chua hoan chinh cho toi het lop bao.
struct ClockSyncConfig {
size_t window = 64; // so mau giu lai
size_t keep_best = 16; // so mau RTT nho nhat dung de fit
double max_skew_dev = 1e-3; // |skew - 1| vuot nguong nay = du lieu rac
};
class ClockSync {
public:
using Config = ClockSyncConfig;
explicit ClockSync(ClockSyncConfig cfg = ClockSyncConfig());
// mcu_s: thoi gian MCU DA UNWRAP (giay).
// t_send, t_recv: thoi gian host luc gui ping va nhan pong (giay).
void Add(double mcu_s, double t_send, double t_recv);
// Doi thoi gian MCU sang thoi gian host. Chua san sang thi tra false.
bool ToHost(double mcu_s, double* host_s) const;
bool ready() const { return ready_; }
double skew() const { return skew_; }
double offset() const { return offset_; }
// Sai so ppm cua skew so voi 1.0. Thach anh thuong lech vai chuc ppm;
// vai nghin ppm nghia la giao thuc sai chu khong phai thach anh te.
double skew_ppm() const { return (skew_ - 1.0) * 1e6; }
uint64_t rejected_fits() const { return rejected_; }
size_t sample_count() const { return samples_.size(); }
void Reset();
private:
struct Sample {
double rtt;
double mcu_s;
double host_s;
};
void Fit();
ClockSyncConfig cfg_;
std::deque<Sample> samples_;
double skew_ = 1.0;
double offset_ = 0.0;
bool ready_ = false;
uint64_t rejected_ = 0;
};
} // namespace vslam
#endif // VSLAM_CLOCK_SYNC_H

View File

@@ -0,0 +1,138 @@
#ifndef VSLAM_DRIVER_CONFIG_H
#define VSLAM_DRIVER_CONFIG_H
#include <cstdint>
#include <string>
#include "vslam/scan_sanitizer.h"
namespace vslam {
// --- LiDAR LakiBeam 1L -----------------------------------------------------
enum class LidarStampMode {
// stamp = luc nhan goi DAU cua sweep. Dung quy uoc LaserScan (stamp = tia
// dau tien) va la mac dinh.
kFirstPacket,
// stamp = luc nhan goi CUOI tru scan_time. Dung khi muon bam theo thoi diem
// ket thuc sweep.
kLastPacketMinusScanTime,
};
struct LidarConfig {
std::string host_ip = "0.0.0.0"; // dia chi de bind, KHONG phai IP cua LiDAR
uint16_t port = 2368; // UDP, theo datasheet
std::string frame_id = "laser_link";
// Cau hinh thiet bi. 25 Hz / 0.25 do -> 1081 tia tren 270 do.
double scan_freq_hz = 25.0;
uint32_t samples = 1081;
double fov_rad = 4.712389; // 270 do
LidarStampMode stamp_mode = LidarStampMode::kFirstPacket;
// Bu do tre da do duoc, cong vao stamp. Chua do -> 0.
double stamp_offset_sec = 0.0;
// Canh bao neu do dai sweep lech qua nhieu so voi scan_time du kien. Day la
// bo phat hien mat goi UDP mien phi ma driver goc khong co.
double sweep_duration_tolerance_sec = 0.005;
double recv_timeout_sec = 1.0;
ScanSanitizerConfig sanitizer;
};
// --- Camera RealSense D410 -------------------------------------------------
struct CameraConfig {
std::string serial; // rong = lay thiet bi dau tien
uint32_t depth_width = 640;
uint32_t depth_height = 480;
uint32_t fps = 30;
bool enable_infra1 = true;
bool enable_infra2 = true;
// D410 khong co RGB (chi co Stereo Module) va khong co IMU tich hop.
// Emitter co dinh o 1 (Laser), KHONG bao gio 2 (Laser Auto): che do auto
// lam depth nhap nhay giua cac khung.
int emitter_mode = 1;
// Giam mau ngay tai driver, tuong duong image_proc/crop_decimate.
// 2 -> 320x240. Cap nhat binning_x/y trong CameraInfo chu KHONG chia lai K;
// consumer tu bu, dung nhu image_geometry lam.
uint32_t decimate = 2;
// Bat RS2_OPTION_GLOBAL_TIME_ENABLED de get_timestamp() tra ve dong ho host.
// Neu D410 FW 5.17.0.10 khong ho tro thi fallback sang TIME_OF_ARRIVAL --
// kem chinh xac hon, va driver se log WARN mot lan.
bool use_global_time = true;
std::string depth_frame_id = "camera_depth_optical_frame";
};
// --- MCU: IMU + barometer --------------------------------------------------
struct McuConfig {
std::string port = "/dev/ttyACM0";
uint32_t baud = 921600;
std::string imu_frame_id = "imu_link";
double ping_period_sec = 1.0; // chu ky ping de dong bo dong ho
// Datasheet ICM-42688-P / BMP390. TAT CA deu la doan tu datasheet cho toi
// khi chay allan_variance -- xem docs cua repo cu.
double gyro_variance = 2.4e-7;
double accel_variance = 4.8e-5;
double baro_variance = 9.0;
double read_timeout_sec = 1.0;
};
// --- Base: encoder + motor -------------------------------------------------
// Giao thuc host <-> base. Phan cung CO encoder (xac nhan tu nguoi dung va
// docs/HARDWARE.md muc 4), nhung giao thuc host doc chung thi CHUA XAC DINH
// o bat ky dau trong repo cu -- ban ROS gia dinh "firmware MCU publish
// /joint_states" ma firmware do chua ton tai.
//
// Vi vay transport duoc tach hoan toan khoi phep toan odometry: khi biet giao
// thuc that thi chi them mot lop mong, khong dung toi WheelOdometry.
enum class BaseProtocol {
// Mo rong giao thuc text san co cua MCU bang mot ban ghi:
// E,<micros>,<ticks_l>,<ticks_r>
// Tai dung ClockSync da co, va do la phan kho nhat -- nen day la lua chon
// re nhat neu firmware sua duoc.
kMcuTextEncoder,
// Serial rieng voi giao thuc nhi phan cua nha san xuat base.
kVendorSerial,
// Khong co base that: doc tu ban ghi .vsr.
kReplay,
};
struct BaseConfig {
BaseProtocol protocol = BaseProtocol::kMcuTextEncoder;
// Dung khi protocol = kVendorSerial.
std::string port = "/dev/ttyUSB0";
uint32_t baud = 115200;
// Hinh hoc. PHAI khop robot.yaml -- day la gia tri duy nhat, khong con ban
// sao trong URDF nua.
double wheel_radius = 0.075;
double wheel_separation = 0.36;
uint32_t ticks_per_rev = 0; // 0 = chua biet, PHAI dat truoc khi chay that
// Gioi han gui xuong motor. Lop safety da kep roi; day la chan cuoi.
double max_linear = 0.35;
double max_angular = 0.8;
// Khong nhan duoc lenh trong bao lau thi tu dung. Phai NGAN hon deadman cua
// teleop, de base dung truoc khi lop tren kip phan ung.
double cmd_timeout_sec = 0.3;
double rate_hz = 50.0;
};
} // namespace vslam
#endif // VSLAM_DRIVER_CONFIG_H

View File

@@ -0,0 +1,146 @@
#ifndef VSLAM_DRIVER_INTERFACES_H
#define VSLAM_DRIVER_INTERFACES_H
// Interface truu tuong + factory cho moi nguon du lieu phan cung.
//
// DAY LA DIEM TUA CUA TOAN BO CHIEN LUOC KIEM CHUNG.
//
// Replay source implement CHINH cac interface nay (xem replay_source.h), nen
// vslam_node khong biet minh dang chay live hay dang phat lai mot file .vsr.
// Khong co mot nhanh `if (replay)` nao trong logic. Doi lai: moi thu nhan
// duoc tu replay di qua dung nhung duong ma du lieu that di qua.
//
// Khong con Gazebo va khong con rosbag thi day la cach duy nhat con lai de
// chay lai mot kich ban hong ma khong phai dung ra hanh lang.
#include <functional>
#include <memory>
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/stats.h"
#include "vslam/vslam_common.h"
namespace vslam {
// --- LiDAR -----------------------------------------------------------------
class LidarInterface {
public:
using ScanCallback = std::function<void(LaserScanPtr)>;
virtual ~LidarInterface() = default;
// Callback duoc goi tren luong RIENG cua driver. Dat truoc khi mo thiet bi.
virtual void SetCallback(ScanCallback cb) = 0;
virtual StatusResponse Open() = 0;
virtual void Close() = 0;
virtual DriverStats Stats() const = 0;
};
std::unique_ptr<LidarInterface> CreateLakiBeamDriver(const LidarConfig& cfg,
ClockPtr clock);
// --- Camera ----------------------------------------------------------------
struct CameraFrame {
Header header; // stamp da quy ve dong ho host
ImagePtr depth; // kMono16, depth_scale met/don vi
ImagePtr infra1; // kMono8, co the null
ImagePtr infra2; // kMono8, co the null
CameraInfo depth_info; // fx/fy/cx/cy + binning sau khi decimate
};
class CameraInterface {
public:
using FrameCallback = std::function<void(const CameraFrame&)>;
virtual ~CameraInterface() = default;
virtual void SetCallback(FrameCallback cb) = 0;
virtual StatusResponse Open() = 0;
virtual void Close() = 0;
virtual DriverStats Stats() const = 0;
};
std::unique_ptr<CameraInterface> CreateRealSenseD410(const CameraConfig& cfg,
ClockPtr clock);
// --- MCU: IMU + barometer --------------------------------------------------
// Mot lan doc cua dan sieu am.
//
// ⚠️ BA NGU NGHIA, y het tia laser, va KHONG duoc gop:
// gia tri huu han = khoang cach do duoc
// inf = khong co tieng vong -> hanh lang RONG, HOP LE
// NaN = cam bien khong tra loi -> US_TIMEOUT
// Bien inf thanh 0 se lam FSM tuong co vat cham vao mat cam bien va dung
// robot giua phong trong.
struct UltrasonicReading {
UnixTime stamp;
size_t count = 0;
double range[8] = {};
};
struct BumperReading {
UnixTime stamp;
uint32_t mask = 0; // bit i = cong tac thu i dang bi nhan
bool any() const { return mask != 0; }
};
class McuInterface {
public:
using UltrasonicCallback = std::function<void(const UltrasonicReading&)>;
using BumperCallback = std::function<void(const BumperReading&)>;
using ImuCallback = std::function<void(ImuPtr)>;
using BaroCallback = std::function<void(const FluidPressure&, const Temperature&)>;
virtual ~McuInterface() = default;
virtual void SetImuCallback(ImuCallback cb) = 0;
virtual void SetBaroCallback(BaroCallback cb) = 0;
// Sieu am va bumper deu nam tren MCU: ca hai la cam bien MUC THAP phai toi
// duoc vong an toan ke ca khi may tinh chinh dang ban.
virtual void SetUltrasonicCallback(UltrasonicCallback cb) = 0;
virtual void SetBumperCallback(BumperCallback cb) = 0;
virtual StatusResponse Open() = 0;
virtual void Close() = 0;
virtual DriverStats Stats() const = 0;
};
std::unique_ptr<McuInterface> CreateMcuBridge(const McuConfig& cfg, ClockPtr clock);
// --- Base: encoder vao, lenh motor ra --------------------------------------
// Doc thang tu encoder. CO Y khong tra ve odometry: phep toan odometry
// (tich phan RK2, mo hinh covariance theo slip) nam o vslam_odometry va duoc
// kiem chung rieng, khong phu thuoc transport nao.
struct EncoderReading {
UnixTime stamp;
double left_rad = 0.0; // goc quay tich luy, radian
double right_rad = 0.0;
bool valid = false;
};
class BaseInterface {
public:
using EncoderCallback = std::function<void(const EncoderReading&)>;
virtual ~BaseInterface() = default;
virtual void SetEncoderCallback(EncoderCallback cb) = 0;
// Gui lenh xuong motor. An toan goi tu bat ky luong nao.
// Base PHAI tu dung neu khong nhan duoc lenh trong cmd_timeout_sec -- day la
// chan cuoi cung, doc lap voi lop safety va voi deadman cua teleop.
virtual void SetVelocity(double linear, double angular) = 0;
virtual StatusResponse Open() = 0;
virtual void Close() = 0;
virtual DriverStats Stats() const = 0;
};
std::unique_ptr<BaseInterface> CreateDiffDriveBase(const BaseConfig& cfg, ClockPtr clock);
} // namespace vslam
#endif // VSLAM_DRIVER_INTERFACES_H

View File

@@ -0,0 +1,118 @@
#ifndef VSLAM_MCU_PROTOCOL_H
#define VSLAM_MCU_PROTOCOL_H
// Giao thuc serial text giua host va MCU.
//
// PHAT HANH co y: file nay la DAC TA ma firmware phai khop. Ai viet firmware
// doc file nay, va test trong test_mcu_protocol.cc la bai kiem cho ca hai phia.
//
// ================== KHUNG BAN TIN ==================
// Text, mot ban ghi mot dong, ket thuc bang '\n'. Truong cach nhau bang ','.
//
// MCU -> host:
// I,<micros>,<gx>,<gy>,<gz>,<ax>,<ay>,<az> IMU (rad/s, m/s^2)
// B,<micros>,<pressure_pa>,<temp_c> Baro
// E,<micros>,<ticks_l>,<ticks_r> Encoder <-- MOI
// P,<micros>,<seq> Pong (tra loi ping)
//
// host -> MCU:
// p,<seq> Ping
//
// ================== BAN GHI E ==================
// Ban ROS gia dinh "firmware MCU publish /joint_states", nhung giao thuc cu
// chi co I/B/P -- KHONG co encoder. Phan cung co encoder (xac nhan tu nguoi
// dung va docs/HARDWARE.md muc 4), nen ban ghi E duoc them vao day.
//
// Lam theo huong nay vi no DUNG LAI ClockSync -- phan kho nhat va da duoc
// kiem chung. Mot serial thu hai cho encoder se phai dong bo dong ho lan nua,
// va hai dong ho lech nhau lam slip_metric (so gyro_z voi yaw_rate suy tu
// encoder) vo nghia.
//
// ticks la SO NGUYEN CO DAU, TICH LUY, va duoc phep tran: host tu unwrap.
// Dung gui delta -- mat mot dong serial la mat vinh vien mot doan quang duong,
// va khong co cach nao phat hien.
//
// ================== micros() TRAN ==================
// micros() la uint32_t, tran moi 71.58 phut. Host unwrap bang
// McuTimeUnwrapper (clock_sync.h). Firmware KHONG can lam gi ca.
#include <cstdint>
#include <string>
#include "vslam/vslam_common.h"
namespace vslam {
enum class McuRecordType : char {
kUnknown = '?',
kImu = 'I',
kBaro = 'B',
kEncoder = 'E',
// MO RONG moi, cung nguyen ly voi kEncoder: giao thuc goc chi co I/B/P.
//
// Sieu am va bumper nam tren MCU vi ca hai deu la cam bien MUC THAP phai
// doc o tan so cao va phai toi duoc vong an toan ke ca khi may tinh chinh
// dang ban. Dua chung qua USB rieng la them mot duong co the chet.
kUltrasonic = 'U', // U,<micros>,<mm_0>,<mm_1>,... 0 = khong do duoc
kBumper = 'K', // K,<micros>,<bitmask> bit i = cong tac i
kPong = 'P',
};
struct McuRecord {
McuRecordType type = McuRecordType::kUnknown;
uint32_t micros = 0;
// kImu
double gx = 0.0, gy = 0.0, gz = 0.0; // rad/s
double ax = 0.0, ay = 0.0, az = 0.0; // m/s^2
// kBaro
double pressure_pa = 0.0;
double temp_c = 0.0;
// kEncoder -- tich luy, co dau, duoc phep tran
int32_t ticks_l = 0;
int32_t ticks_r = 0;
// kUltrasonic -- met. INFINITY = ngoai tam; NaN = cam bien khong tra loi.
//
// ⚠️ Phan biet hai thu do la BAT BUOC: "khong thay gi" (hop le, hanh lang
// rong) khac han "cam bien chet" (phai bao US_TIMEOUT). Gop chung lai la
// xoa mat mot nhanh an toan.
static constexpr size_t kMaxUltrasonic = 8;
size_t us_count = 0;
double us_range[kMaxUltrasonic] = {};
// kBumper -- bit i = cong tac thu i dang bi nhan.
uint32_t bumper_mask = 0;
// kPong
uint32_t seq = 0;
};
// Phan tich mot dong (khong gom '\n'). Tra false neu dong hong -- goi nen dem
// va log throttle, KHONG duoc coi dong hong la du lieu 0.
bool ParseMcuLine(const std::string& line, McuRecord* out);
// Dung ban tin ping de gui xuong MCU (da gom '\n').
std::string BuildPing(uint32_t seq);
// Go tran cua bo dem tick uint32 cua encoder. Cung nguyen ly voi
// McuTimeUnwrapper nhung cho so CO DAU va co the chay ca hai chieu.
class TickUnwrapper {
public:
// Tra ve so tick tich luy da unwrap.
int64_t Unwrap(int32_t raw);
void Reset();
uint64_t wrap_count() const { return wraps_; }
private:
int32_t prev_ = 0;
int64_t high_ = 0;
uint64_t wraps_ = 0;
bool first_ = true;
};
} // namespace vslam
#endif // VSLAM_MCU_PROTOCOL_H

View File

@@ -0,0 +1,125 @@
#ifndef VSLAM_RECORD_FORMAT_H
#define VSLAM_RECORD_FORMAT_H
// Dinh dang ghi `.vsr` -- thay rosbag.
//
// ================== VI SAO CAN ==================
// Bo ROS la mat rosbag; bo Gazebo la mat kha nang dung lai mot kich ban hong.
// Khong co ca hai thi cach duy nhat de tai lap mot loi la day robot ra hanh
// lang lan nua va hy vong no hong giong lan truoc.
//
// ================== GHI THO ==================
// Ghi du lieu THO NHAT co the, truoc moi phep bien doi:
// SCAN_RAW ghi TRUOC ScanSanitizer, de doi nguong sanitizer cung test lai
// duoc tren cung mot ban ghi.
// Day dung nguyen tac cua topics_to_record.yaml trong ban ROS: chi ghi topic
// tho, khong ghi dau ra, de thuat toan chay lai duoc tren dung dau vao cu.
//
// ================== CAU TRUC ==================
// File = FileHeader + ChunkRecord*
//
// FileHeader (kHeaderSize byte):
// char[8] magic = "VSREC\0\0\0"
// u32 version
// u32 reserved
// u64 start_stamp_ns
// u32 config_json_len
// u8 config_json[config_json_len] <- toan bo config dang chay
//
// ChunkRecord:
// u32 magic = 0x43525356 ('VSRC')
// u8 stream_id
// u8 flags bit0 = payload nen bang zstd
// u16 reserved
// u64 stamp_ns
// u32 payload_len
// u8 payload[payload_len]
// u32 crc32(payload)
//
// config_json duoc nhung vao de mot ban ghi TU MO TA duoc: doc lai sau sau
// thang van biet no chay voi nguong nao.
//
// crc32 moi chunk de phat hien hong: mot file .vsr tren USB rut ra giua chung
// thi hong o cuoi, va replay phai dung lai o do chu khong doc rac.
#include <cstdint>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
constexpr char kVsrMagic[8] = {'V', 'S', 'R', 'E', 'C', '\0', '\0', '\0'};
constexpr uint32_t kVsrChunkMagic = 0x43525356u; // 'VSRC' little-endian
constexpr uint32_t kVsrVersion = 1;
constexpr size_t kVsrHeaderFixedSize = 28; // truoc config_json
constexpr size_t kVsrChunkHeaderSize = 20; // truoc payload
enum class VsrStream : uint8_t {
kScanRaw = 1, // TRUOC sanitizer
kImu = 2,
kBaro = 3,
kEncoder = 4,
kDepth = 5,
kInfra1 = 6,
kInfra2 = 7,
kCameraInfo = 8,
kCmdVel = 9, // dau vao cua safety, khong phai dau ra
kEvent = 10, // JSON: drop, doi config, lenh operator, mat goi
// Hai stream nay la MO RONG moi. Chung phai co trong ban ghi vi lop an
// toan TIEU THU chung: mot ban ghi thieu sieu am/bumper thi khi phat lai,
// hai nhanh US_BLOCKED va BUMPER khong bao gio chay -- va bo hoi quy se
// bao "xanh" cho mot he da mat hai nhanh an toan.
kUltrasonic = 11,
kBumper = 12,
};
const char* VsrStreamName(VsrStream s);
struct VsrChunkHeader {
VsrStream stream = VsrStream::kEvent;
bool compressed = false;
uint64_t stamp_ns = 0;
uint32_t payload_len = 0;
};
// --- Ma hoa tung loai ban tin ---------------------------------------------
// Noi them vao `out`. Chi la payload, khong gom chunk header.
void EncodeScanPayload(const LaserScan& scan, std::string* out);
bool DecodeScanPayload(const std::string& buf, LaserScan* out);
void EncodeImuPayload(const Imu& imu, std::string* out);
bool DecodeImuPayload(const std::string& buf, Imu* out);
void EncodeEncoderPayload(double left_rad, double right_rad, std::string* out);
bool DecodeEncoderPayload(const std::string& buf, double* left_rad, double* right_rad);
void EncodeBaroPayload(const FluidPressure& p, const Temperature& t, std::string* out);
bool DecodeBaroPayload(const std::string& buf, FluidPressure* p, Temperature* t);
void EncodeTwistPayload(const Twist& tw, std::string* out);
bool DecodeTwistPayload(const std::string& buf, Twist* out);
void EncodeUltrasonicPayload(const double* range, size_t count, std::string* out);
bool DecodeUltrasonicPayload(const std::string& buf, double* range, size_t* count,
size_t max_count);
void EncodeBumperPayload(uint32_t mask, std::string* out);
bool DecodeBumperPayload(const std::string& buf, uint32_t* mask);
void EncodeCameraInfoPayload(const CameraInfo& info, std::string* out);
bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* out);
// Anh: header nho + du lieu pixel tho. Khong nen o day -- nen lam o tang
// chunk de doi thuat toan nen khong phai doi dinh dang ban tin.
void EncodeImagePayload(const Image& img, std::string* out);
bool DecodeImagePayload(const std::string& buf, Image* out, std::vector<uint8_t>* storage);
// --- crc32 (IEEE 802.3, giong zlib) ---------------------------------------
uint32_t Crc32(const void* data, size_t len, uint32_t seed = 0);
} // namespace vslam
#endif // VSLAM_RECORD_FORMAT_H

View File

@@ -0,0 +1,120 @@
#ifndef VSLAM_RECORD_IO_H
#define VSLAM_RECORD_IO_H
// Doc/ghi file .vsr.
//
// ================== NGUYEN TAC CUA WRITER ==================
// GHI LOG TUYET DOI KHONG DUOC NGHEN VONG AN TOAN.
//
// Writer chay tren LUONG RIENG voi hang doi co chan tren. Khi hang doi day
// thi no DROP chu khong bao gio chan nguoi goi. Mot the USB cham khong duoc
// phep lam luong lidar_rx dung lai.
//
// Moi lan drop duoc dem VA ghi vao stream kEvent, nen mot ban ghi TU MO TA
// duoc cac lo hong cua chinh no. Doc lai sau sau thang van biet doan nao
// thieu du lieu va thieu bao nhieu -- thay vi ngoi doan tai sao thuat toan
// cu xu la o giay thu 412.
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include "vslam/record_format.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct RecordWriterConfig {
std::string path;
// Chan tren cua hang doi, tinh bang byte. Vuot thi drop chunk moi.
size_t max_queue_bytes = 64u * 1024u * 1024u;
// Nen payload bang zstd neu co. Chua bat -- can libzstd, va do thi de sau.
bool compress = false;
// Giam tai cho anh depth. Tho: 640x480x2 x 30 Hz x 3 luong = 37 MB/s
// ~ 133 GB/gio, khong dung duoc. Voi decimate=2 va 10 Hz thi xuong duoi
// 5 MB/s, tuc 18 GB/gio -- mot USB 64 GB chua duoc 3.5 gio.
double depth_rate_hz = 10.0;
bool record_infra1 = false;
bool record_infra2 = false;
// Toan bo config dang chay, nhung vao header de ban ghi tu mo ta duoc.
std::string config_json;
};
struct RecordWriterStats {
uint64_t chunks_written = 0;
uint64_t bytes_written = 0;
uint64_t chunks_dropped = 0; // hang doi day
uint64_t queue_bytes = 0;
uint64_t write_errors = 0;
};
class RecordWriter {
public:
explicit RecordWriter(RecordWriterConfig cfg);
~RecordWriter();
RecordWriter(const RecordWriter&) = delete;
RecordWriter& operator=(const RecordWriter&) = delete;
StatusResponse Open();
void Close();
// KHONG BAO GIO CHAN. Tra false neu chunk bi drop vi hang doi day.
bool Write(VsrStream stream, UnixTime stamp, std::string payload);
// Ghi mot su kien JSON vao stream kEvent.
void WriteEvent(UnixTime stamp, const std::string& json);
RecordWriterStats Stats() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
// --- Reader ----------------------------------------------------------------
struct RecordFileInfo {
uint32_t version = 0;
UnixTime start_stamp;
std::string config_json;
};
class RecordReader {
public:
RecordReader();
~RecordReader();
RecordReader(const RecordReader&) = delete;
RecordReader& operator=(const RecordReader&) = delete;
StatusResponse Open(const std::string& path);
void Close();
const RecordFileInfo& info() const;
// Doc chunk ke tiep. Tra false khi het file HOAC khi gap chunk hong.
//
// Chunk hong KHONG duoc bo qua de doc tiep: mot file .vsr tren USB rut ra
// giua chung thi hong o cuoi, va doc tiep chi cho ra rac. Dung lai va bao
// qua `truncated()`.
bool Next(VsrChunkHeader* header, std::string* payload);
// true neu dung vi CRC sai hoac chunk cut, false neu den cuoi file binh thuong.
bool truncated() const;
uint64_t chunks_read() const;
uint64_t bytes_read() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace vslam
#endif // VSLAM_RECORD_IO_H

View File

@@ -0,0 +1,109 @@
#ifndef VSLAM_REPLAY_SOURCE_H
#define VSLAM_REPLAY_SOURCE_H
// Phat lai mot file .vsr qua CHINH cac interface driver.
//
// ================== VI SAO DAY LA MANH KHOA ==================
// ReplaySources tra ve nhung LidarInterface / CameraInterface / McuInterface /
// BaseInterface that -- cung kieu ma driver phan cung tra ve.
//
// Hau qua: vslam_node KHONG BIET minh dang chay live hay dang phat lai. Khong
// co mot nhanh `if (replay)` nao trong logic. Moi thu doc tu file di qua dung
// nhung duong ma du lieu that di qua: cung ScanSanitizer, cung EKF, cung
// safety, cung SLAM.
//
// Day la loi ich kien truc lon nhat cua viec dung interface truu tuong +
// factory, va la thu thay the cho ca Gazebo lan rosbag cung mot luc.
//
// ================== CHE DO TAT DINH ==================
// Voi `deterministic = true`: MOT luong duy nhat, day moi ban ghi theo dung
// thu tu stamp, dung ReplayClock. Chay lai cung mot file cho ra ket qua giong
// het den tung byte.
//
// Dieu do CHI kha thi neu quy tac o clock.h duoc giu tu ngay dau: khong stage
// nao goi UnixTime::now() truc tiep, moi stage nhan Clock& qua constructor.
// Vi pham mot cho thoi la mat tinh tat dinh, va khong the sua bang cach sua
// rieng replay.
#include <memory>
#include <string>
#include "vslam/clock.h"
#include "vslam/driver_interfaces.h"
namespace vslam {
struct ReplayConfig {
std::string path;
// 1.0 = thoi gian that. 0 = chay nhanh nhat co the (khong ngu).
double speed = 1.0;
// Bo qua bao nhieu giay dau file, va chay bao lau. 0 = toan bo.
double start_sec = 0.0;
double duration_sec = 0.0;
// Mot luong, day theo thu tu stamp. Bo qua `speed`.
bool deterministic = false;
// Lap lai tu dau khi het file. Dung khi debug UI.
bool loop = false;
// Ap ScanSanitizer len SCAN_RAW. Mac dinh true: ban ghi luu du lieu THO
// (truoc sanitizer) chinh la de doi nguong roi test lai duoc.
bool apply_sanitizer = true;
ScanSanitizerConfig sanitizer;
};
// So huu ca bon nguon. Huy object nay se dung viec phat lai.
class ReplaySource {
public:
explicit ReplaySource(ReplayConfig cfg);
~ReplaySource();
ReplaySource(const ReplaySource&) = delete;
ReplaySource& operator=(const ReplaySource&) = delete;
StatusResponse Open();
// Dong ho ao. Moi stage phai dung dong ho NAY, khong phai dong ho he thong.
ClockPtr clock() const;
// Bon nguon nay la interface driver that. Dat callback nhu voi phan cung.
LidarInterface* lidar();
CameraInterface* camera();
McuInterface* mcu();
BaseInterface* base();
// Chay het file (hoac het `duration_sec`). Chan cho toi khi xong.
// Trong che do tat dinh, day la vong lap don luong duy nhat.
void Run();
// Yeu cau dung som. An toan goi tu luong khac.
void RequestStop();
// Config luc ghi, lay tu header cua file. Cho biet ban ghi chay voi nguong
// nao -- mot ban ghi tu mo ta duoc.
const std::string& recorded_config_json() const;
struct Stats {
uint64_t chunks = 0;
uint64_t scans = 0;
uint64_t imu = 0;
uint64_t encoder = 0;
uint64_t camera_frames = 0;
uint64_t events = 0;
uint64_t skipped = 0; // ngoai cua so start/duration
bool truncated = false; // file hong giua chung
double duration_sec = 0.0;
};
Stats stats() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace vslam
#endif // VSLAM_REPLAY_SOURCE_H

View File

@@ -0,0 +1,115 @@
#ifndef VSLAM_SCAN_SANITIZER_H
#define VSLAM_SCAN_SANITIZER_H
// Ve sinh LaserScan tho tu LiDAR truoc khi bat ky ai dung no.
//
// Gop hai thu cua ban ROS lam mot:
// 1. robot_drivers/ScanHeaderFixFilter -- sua ba bug cua driver LakiBeam
// 2. hai laser_filters/LaserScanAngularBoundsFilterInPlace -- cat quat bi
// than robot che
//
// GOP LAI LA CO Y. Ban ROS phai ghi mot khoi comment canh bao rang filter 1
// BAT BUOC chay truoc filter 2, vi filter 2 blank tia bang `range_max + 1.0`:
// neu chay truoc thi sentinel thanh 101.0 thay vi 41.0, va safety_monitor doc
// sai so tia bi che. Gop vao mot ham thi thu tu do khong the sai duoc nua.
//
// ================== BA BUG CUA DRIVER LAKIBEAM ==================
// Da doc source de xac nhan (xem docs/HARDWARE.md cua repo cu):
// range_min = 0.0 <- thiet bi that: 0.05
// range_max = 100.0 <- thiet bi that: 40.0
// time_increment = duration / n / 2 <- thua phep chia 2
//
// `range_min = 0.0` la cai nguy hiem nhat. Phep loc chuan cua MOI consumer la
// `if (r < range_min) continue;`. Voi range_min = 0.0 thi `0.0 < 0.0` la sai,
// nen mot tia bao 0.0 -- von nghia la "khong do duoc" -- duoc CHAP NHAN thanh
// vat can ngay goc LiDAR. Hau qua: safety_monitor thay vat can 0.0 m va dung
// vinh vien.
//
// ================== BA NGU NGHIA CUA MOT TIA ==================
// Phan biet ba thu KHAC NHAU, khong duoc gop:
//
// NaN "khong do duoc" consumer bo qua, KHONG clear free space
// inf "khong co gi trong tam" duoc phep clear free space
// range_max+1.0 "khong duoc phep nhin" bi than robot che; safety_monitor
// dem rieng (front_blanked) va khong
// tinh vao front_usable
//
// Vi sao 0.0 -> NaN chu khong phai inf: LiDAR tra 0.0 cho CA HAI truong hop
// "khong co vat trong tam" VA "be mat den nuot het xung". Map sang inf thi
// robot se clear free space XUYEN QUA ghe da den. Map sang NaN thi hong ve
// phia "coi nhu co vat", tuc an toan.
#include <cstddef>
#include <string>
#include <vector>
#include "vslam/stats.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct SectorMask {
double lower_rad = 0.0; // cat cac tia co goc trong [lower, upper]
double upper_rad = 0.0;
};
struct ScanSanitizerConfig {
// Ep header ve gia tri that cua thiet bi.
double range_min = 0.05;
double range_max = 40.0;
// true = bo phep chia 2 thua cua driver.
bool fix_time_increment = true;
// "nan" hoac "inf". Mac dinh "nan" -- xem khoi comment tren.
std::string zero_is = "nan";
// Quat bi than robot che. Voi cau hinh hien tai: laser o x=0.24, than robot
// nua rong 0.17 va mat truoc x=0.14 -> tu che ngoai +-120.5 do, cat o +-118
// de co bien an toan. Con lai ~236 do huu dung tren 270 do.
std::vector<SectorMask> sector_masks;
// Xoay toan bo scan. Dung khi huong 0 do vat ly cua LiDAR khong trung voi
// truc x cua robot. GIA TRI THAT CHUA DO DUOC -- xem tools/vslam_scan_check.
double angle_offset_rad = 0.0;
};
struct ScanSanitizerStats {
uint64_t scans = 0;
uint64_t rays_total = 0;
uint64_t rays_zero = 0; // driver tra 0.0
uint64_t rays_below_min = 0;
uint64_t rays_above_max = 0;
uint64_t rays_blanked = 0; // bi sector mask cat
uint64_t rays_valid = 0;
};
class ScanSanitizer {
public:
explicit ScanSanitizer(ScanSanitizerConfig cfg);
// Nem std::invalid_argument neu cau hinh vo ly (range_min <= 0, range_max
// <= range_min). Kiem o day chu khong im lang roi ve default: mot LiDAR
// cau hinh sai la mot robot dam vao tuong.
static void Validate(const ScanSanitizerConfig& cfg);
// Sua TAI CHO. Giu nguyen stamp, angle_*, va so luong tia.
void Apply(LaserScan* scan);
const ScanSanitizerStats& stats() const { return stats_; }
void ResetStats() { stats_ = ScanSanitizerStats{}; }
// Gia tri sentinel ma sector mask dung, theo cau hinh hien tai.
float blank_value() const { return static_cast<float>(cfg_.range_max) + 1.0f; }
private:
bool InMaskedSector(double angle) const;
ScanSanitizerConfig cfg_;
bool zero_to_inf_ = false;
ScanSanitizerStats stats_;
};
} // namespace vslam
#endif // VSLAM_SCAN_SANITIZER_H