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,38 @@
# Driver phan cung. Dep ngoai: librealsense2 (tuy chon).
#
# librealsense2 la TUY CHON co y: ba phan kiem chung duoc ma khong can phan
# cung -- ScanSanitizer, ClockSync, giao thuc MCU -- phai build va test duoc
# tren may khong co RealSense SDK, ke ca trong CI.
option(VSLAM_WITH_REALSENSE "Build driver RealSense (can librealsense2)" OFF)
vslam_add_library(vslam_drivers
PUBLIC_HDRS
driver_config.h
driver_interfaces.h
scan_sanitizer.h
clock_sync.h
mcu_protocol.h
record_format.h
record_io.h
replay_source.h
PUBLIC_DEPS
vslam_common
FIND_DEPS
vslam_common
)
# Driver RealSense la file rieng, chi bien dich khi co SDK. GLOB_RECURSE gom
# het src/ nen phai loai no ra khi tat -- neu khong thi `#include <rs.hpp>`
# lam hong build tren may khong co librealsense2, tuc dung cai ma cai
# `option()` nay sinh ra de tranh.
get_target_property(_vslam_drv_srcs vslam_drivers SOURCES)
list(FILTER _vslam_drv_srcs EXCLUDE REGEX "realsense_driver\\.cc$")
set_target_properties(vslam_drivers PROPERTIES SOURCES "${_vslam_drv_srcs}")
if(VSLAM_WITH_REALSENSE)
target_sources(vslam_drivers PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/realsense_driver.cc)
find_package(realsense2 REQUIRED)
target_link_libraries(vslam_drivers PRIVATE ${realsense2_LIBRARY})
target_include_directories(vslam_drivers SYSTEM PRIVATE ${realsense2_INCLUDE_DIR})
target_compile_definitions(vslam_drivers PRIVATE VSLAM_HAVE_REALSENSE=1)
endif()

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

View File

@@ -0,0 +1,140 @@
#include "vslam/clock_sync.h"
#include <algorithm>
#include <cmath>
#include <vector>
#include "vslam/log.h"
namespace vslam {
namespace {
constexpr uint64_t kWrapPeriodUs = 1ULL << 32; // 4294967296 us = 71.58 phut
constexpr uint32_t kHalfRange = 1U << 31;
} // namespace
// --- McuTimeUnwrapper ------------------------------------------------------
double McuTimeUnwrapper::UnwrapSeconds(uint32_t micros) {
if (first_) {
first_ = false;
prev_us_ = micros;
return static_cast<double>(micros) * 1e-6;
}
// Tran khi gia tri moi NHO HON gia tri truoc mot khoang lon. Nguong nua dai
// (2^31) phan biet duoc "tran" voi "ban tin den khong dung thu tu": ban tin
// lech thu tu chi lui vai mili giay, con tran thi lui gan 71 phut.
//
// GIA DINH: khoang cach giua hai lan goi < nua chu ky (35.79 phut). Neu goi
// thua hon nua chu ky thi khong the phan biet "tran" voi "nhay lui" -- day
// la gioi han co ban cua moi bo dem tran, khong phai thieu sot cai dat.
// O 200 Hz (IMU) hay 50 Hz (encoder) thi gia dinh nay du xa an toan; neu
// sau nay co nguon nao goi thua hon 35 phut mot lan thi nguon do can dong
// ho rieng chu khong dung duoc lop nay.
if (micros < prev_us_ && (prev_us_ - micros) > kHalfRange) {
high_ += kWrapPeriodUs;
wraps_++;
VSLAM_INFO("clock_sync: micros() tran lan thu " << wraps_
<< " (moi 71.58 phut) -- da bu");
}
prev_us_ = micros;
return static_cast<double>(high_ + micros) * 1e-6;
}
void McuTimeUnwrapper::Reset() {
prev_us_ = 0;
high_ = 0;
wraps_ = 0;
first_ = true;
}
// --- ClockSync -------------------------------------------------------------
ClockSync::ClockSync(ClockSyncConfig cfg) : cfg_(cfg) {
if (cfg_.window == 0) cfg_.window = 1;
if (cfg_.keep_best == 0) cfg_.keep_best = 1;
}
void ClockSync::Add(double mcu_s, double t_send, double t_recv) {
const double rtt = t_recv - t_send;
if (!(rtt >= 0.0)) return; // bat ca NaN
// Gia dinh do tre doi xung: thoi diem MCU tra loi nam giua luc gui va luc
// nhan. Chi dung khi RTT nho -- do la ly do chi giu mau RTT nho nhat.
const double host_s = 0.5 * (t_send + t_recv);
samples_.push_back(Sample{rtt, mcu_s, host_s});
while (samples_.size() > cfg_.window) samples_.pop_front();
Fit();
}
void ClockSync::Fit() {
if (samples_.size() < 2) return;
std::vector<Sample> best(samples_.begin(), samples_.end());
const size_t k = std::min(cfg_.keep_best, best.size());
std::partial_sort(best.begin(), best.begin() + static_cast<long>(k), best.end(),
[](const Sample& a, const Sample& b) { return a.rtt < b.rtt; });
best.resize(k);
if (best.size() < 2) return;
const double n = static_cast<double>(best.size());
double sx = 0.0, sy = 0.0, sxx = 0.0, sxy = 0.0;
for (const auto& s : best) {
sx += s.mcu_s;
sy += s.host_s;
sxx += s.mcu_s * s.mcu_s;
sxy += s.mcu_s * s.host_s;
}
const double denom = n * sxx - sx * sx;
if (std::abs(denom) < 1e-12) {
// Cac mau qua gan nhau ve thoi gian -> chua uoc luong duoc skew, nhung
// offset thi van uoc luong duoc.
offset_ = (sy - sx) / n;
skew_ = 1.0;
ready_ = true;
return;
}
const double skew = (n * sxy - sx * sy) / denom;
const double offset = (sy - skew * sx) / n;
// Skew phai rat gan 1.0 -- thach anh lech vai chuc ppm. Lech nhieu nghia la
// du lieu rac (giao thuc sai, hoac micros() tran ma khong unwrap).
if (std::abs(skew - 1.0) > cfg_.max_skew_dev) {
rejected_++;
VSLAM_WARN_THROTTLE(30.0, "clock_sync: skew bat thuong ("
<< skew << ", lech " << (skew - 1.0) * 1e6
<< " ppm), bo qua ket qua fit. Kiem giao thuc MCU"
" va viec unwrap micros().");
skew_ = 1.0;
offset_ = (sy - sx) / n;
ready_ = true;
return;
}
skew_ = skew;
offset_ = offset;
ready_ = true;
}
bool ClockSync::ToHost(double mcu_s, double* host_s) const {
if (!ready_) return false;
*host_s = skew_ * mcu_s + offset_;
return true;
}
void ClockSync::Reset() {
samples_.clear();
skew_ = 1.0;
offset_ = 0.0;
ready_ = false;
rejected_ = 0;
}
} // namespace vslam

View File

@@ -0,0 +1,179 @@
#include "vslam/mcu_protocol.h"
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <limits>
#include <vector>
namespace vslam {
namespace {
// Tach theo ',' khong cap phat trung gian.
size_t SplitFields(const std::string& line, std::vector<const char*>* starts,
std::string* buf) {
*buf = line;
starts->clear();
bool in_field = false;
for (size_t i = 0; i < buf->size(); ++i) {
if ((*buf)[i] == ',') {
(*buf)[i] = '\0';
in_field = false;
continue;
}
if (!in_field) {
starts->push_back(buf->c_str() + i);
in_field = true;
}
}
return starts->size();
}
bool ToDouble(const char* s, double* out) {
char* end = nullptr;
const double v = std::strtod(s, &end);
if (end == s || *end != '\0') return false;
*out = v;
return true;
}
bool ToU32(const char* s, uint32_t* out) {
char* end = nullptr;
const unsigned long v = std::strtoul(s, &end, 10);
if (end == s || *end != '\0') return false;
if (v > std::numeric_limits<uint32_t>::max()) return false;
*out = static_cast<uint32_t>(v);
return true;
}
bool ToI32(const char* s, int32_t* out) {
char* end = nullptr;
const long v = std::strtol(s, &end, 10);
if (end == s || *end != '\0') return false;
if (v > std::numeric_limits<int32_t>::max() ||
v < std::numeric_limits<int32_t>::min()) {
return false;
}
*out = static_cast<int32_t>(v);
return true;
}
} // namespace
bool ParseMcuLine(const std::string& line, McuRecord* out) {
if (line.empty() || out == nullptr) return false;
std::string buf;
std::vector<const char*> f;
const size_t n = SplitFields(line, &f, &buf);
if (n < 2) return false;
// Ky tu loai phai dung mot ky tu. "II" hay "I " deu la dong hong.
if (std::strlen(f[0]) != 1) return false;
const char tag = f[0][0];
if (!ToU32(f[1], &out->micros)) return false;
switch (tag) {
case 'I': {
if (n != 8) return false;
if (!ToDouble(f[2], &out->gx) || !ToDouble(f[3], &out->gy) ||
!ToDouble(f[4], &out->gz) || !ToDouble(f[5], &out->ax) ||
!ToDouble(f[6], &out->ay) || !ToDouble(f[7], &out->az)) {
return false;
}
out->type = McuRecordType::kImu;
return true;
}
case 'B': {
if (n != 4) return false;
if (!ToDouble(f[2], &out->pressure_pa) || !ToDouble(f[3], &out->temp_c)) {
return false;
}
out->type = McuRecordType::kBaro;
return true;
}
case 'E': {
if (n != 4) return false;
if (!ToI32(f[2], &out->ticks_l) || !ToI32(f[3], &out->ticks_r)) return false;
out->type = McuRecordType::kEncoder;
return true;
}
case 'U': {
// U,<micros>,<mm_0>,<mm_1>,... So cam bien BIEN THIEN theo cau hinh
// phan cung, nen khong chot so truong.
if (n < 3) return false;
const size_t k = std::min<size_t>(n - 2, McuRecord::kMaxUltrasonic);
for (size_t i = 0; i < k; ++i) {
int32_t mm = 0;
if (!ToI32(f[i + 2], &mm)) return false;
// Quy uoc cua module HC-SR04 va ho hang:
// 0 = khong co tieng vong -> KHONG PHAI 0 met, ma la "khong thay
// gi" -> inf. Doi 0 thanh 0.0 m se lam FSM tuong co vat cham
// vao mat cam bien va dung robot giua hanh lang rong.
// <0 = cam bien khong tra loi -> NaN, de US_TIMEOUT co the kich.
if (mm == 0) out->us_range[i] = std::numeric_limits<double>::infinity();
else if (mm < 0) out->us_range[i] = std::numeric_limits<double>::quiet_NaN();
else out->us_range[i] = mm * 0.001;
}
out->us_count = k;
out->type = McuRecordType::kUltrasonic;
return true;
}
case 'K': {
if (n != 3) return false;
if (!ToU32(f[2], &out->bumper_mask)) return false;
out->type = McuRecordType::kBumper;
return true;
}
case 'P': {
if (n != 3) return false;
if (!ToU32(f[2], &out->seq)) return false;
out->type = McuRecordType::kPong;
return true;
}
default:
return false;
}
}
std::string BuildPing(uint32_t seq) {
char buf[32];
const int len = std::snprintf(buf, sizeof(buf), "p,%u\n", seq);
return std::string(buf, static_cast<size_t>(len));
}
int64_t TickUnwrapper::Unwrap(int32_t raw) {
if (first_) {
first_ = false;
prev_ = raw;
return raw;
}
// Bo dem tran khi hieu vuot nua dai int32. Nguong nua dai phan biet duoc
// "tran" voi "robot lui": lui thi delta nho, tran thi delta gan 2^32.
constexpr int64_t kRange = 1LL << 32;
constexpr int64_t kHalf = 1LL << 31;
const int64_t delta = static_cast<int64_t>(raw) - static_cast<int64_t>(prev_);
if (delta < -kHalf) {
high_ += kRange; // tran len
wraps_++;
} else if (delta > kHalf) {
high_ -= kRange; // tran xuong (robot lui lau)
wraps_++;
}
prev_ = raw;
return high_ + static_cast<int64_t>(raw);
}
void TickUnwrapper::Reset() {
prev_ = 0;
high_ = 0;
wraps_ = 0;
first_ = true;
}
} // namespace vslam

View File

@@ -0,0 +1,404 @@
// Driver RealSense D410.
//
// ================== D410 KHAC GI CAC DONG KIA ==================
// D410 chi co Stereo Module: KHONG RGB, KHONG IMU tich hop. Nen:
// - Kenh "rgb" ma SLAM can duoc lap bang anh IR TRAI (infra1, mono8).
// - Nghieng phai lay tu IMU cua MCU, khong phai tu camera.
//
// ================== BA BAY DA BIET TRUOC ==================
// 1. `decimate` cap nhat `binning_x/y` chu KHONG chia lai K. Do la dung quy
// uoc sensor_msgs/CameraInfo, va moi consumer phai tu bu bang
// `fx_binned()`. Chia lai K o day se lam MOI consumer bu HAI LAN.
//
// 2. `RS2_OPTION_GLOBAL_TIME_ENABLED` chua xac minh tren FW 5.17.0.10. Khong
// co thi `get_timestamp()` tra ve dong ho CUA THIET BI, khong phai dong ho
// host -- va moi phep dong bo voi LiDAR/IMU sai hang chuc nam. Driver kiem
// tra domain THAT SU nhan duoc chu khong tin option da set.
//
// 3. Emitter phai co dinh o 1 (Laser), KHONG BAO GIO 2 (Laser Auto): che do
// auto lam depth nhap nhay giua cac khung, va `cliff_detect` doc su nhap
// nhay do thanh lo hong tren san.
//
// ================== VIET DUOC MA CHUA CO CAMERA ==================
// librealsense2 la API cong khai; cai chua lam duoc la KIEM CHUNG tren thiet
// bi that. Nhung thu chi biet duoc khi cam camera vao duoc danh dau ⚠️ CHUA
// XAC MINH ngay tai cho.
#include <librealsense2/rs.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstring>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Giu rs2::frameset song chung voi Image tro vao buffer cua no.
//
// `Image` KHONG so huu bo nho (xem vslam_common.h): `data` tro thang vao
// buffer cua SDK. Khong giu frameset thi SDK tai su dung buffer do ngay khung
// sau, va consumer doc phai anh MOI trong khi tuong minh doc anh CU -- mot
// loi khong bao gio crash, chi lam moi phep do lech mot khung.
struct FrameKeepAlive {
rs2::frameset fs;
};
class RealSenseDriver : public CameraInterface {
public:
RealSenseDriver(CameraConfig cfg, ClockPtr clock)
: cfg_(std::move(cfg)), clock_(std::move(clock)) {}
~RealSenseDriver() override { Close(); }
void SetCallback(FrameCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override {
if (running_.load()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da mo roi");
}
if (cfg_.decimate == 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"camera.decimate = 0");
}
try {
rs2::config rc;
if (!cfg_.serial.empty()) rc.enable_device(cfg_.serial);
rc.enable_stream(RS2_STREAM_DEPTH, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Z16,
static_cast<int>(cfg_.fps));
if (cfg_.enable_infra1) {
rc.enable_stream(RS2_STREAM_INFRARED, 1, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Y8,
static_cast<int>(cfg_.fps));
}
if (cfg_.enable_infra2) {
rc.enable_stream(RS2_STREAM_INFRARED, 2, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Y8,
static_cast<int>(cfg_.fps));
}
pipe_.reset(new rs2::pipeline);
profile_.reset(new rs2::pipeline_profile(pipe_->start(rc)));
const StatusResponse st = Configure();
if (!st.ok()) {
pipe_->stop();
pipe_.reset();
profile_.reset();
return st;
}
} catch (const rs2::error& e) {
pipe_.reset();
profile_.reset();
return StatusResponse::Error(
StatusCode::kUnavailable,
std::string("realsense: ") + e.get_failed_function() + ": " + e.what());
} catch (const std::exception& e) {
pipe_.reset();
profile_.reset();
return StatusResponse::Error(StatusCode::kUnavailable,
std::string("realsense: ") + e.what());
}
running_.store(true);
thread_ = std::thread([this] { Loop(); });
return StatusResponse::Ok();
}
void Close() override {
if (!running_.exchange(false)) return;
if (thread_.joinable()) thread_.join();
try {
if (pipe_) pipe_->stop();
} catch (const std::exception&) {
// Dong thiet bi da rut day thi nem; khong co gi de lam va khong duoc
// phep nem tiep tu destructor.
}
pipe_.reset();
profile_.reset();
}
DriverStats Stats() const override {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
private:
StatusResponse Configure() {
rs2::device dev = profile_->get_device();
auto sensors = dev.query_sensors();
for (rs2::sensor& s : sensors) {
// --- Emitter: co dinh o Laser, KHONG BAO GIO Laser Auto ---
if (s.supports(RS2_OPTION_EMITTER_ENABLED)) {
s.set_option(RS2_OPTION_EMITTER_ENABLED,
static_cast<float>(cfg_.emitter_mode));
}
// --- Dong ho ---
// Dat option la MOT chuyen; thiet bi co thuc su doi domain khong lai la
// chuyen khac. Kiem o Loop() bang domain THAT nhan duoc.
if (cfg_.use_global_time && s.supports(RS2_OPTION_GLOBAL_TIME_ENABLED)) {
s.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, 1.0f);
} else if (cfg_.use_global_time) {
VSLAM_WARN("realsense: thiet bi khong ho tro GLOBAL_TIME_ENABLED -- "
"stamp se theo dong ho THIET BI, khong phai host.");
}
}
// --- depth_scale: met moi don vi ---
// KHONG hardcode 0.001. D4xx mac dinh la vay nhung tuy chinh duoc, va mot
// camera da bi chinh se cho ra do sau sai ti le ma khong co gi bao.
try {
depth_scale_ = profile_->get_device()
.first<rs2::depth_sensor>()
.get_depth_scale();
} catch (const std::exception&) {
depth_scale_ = 0.001f;
VSLAM_WARN("realsense: khong doc duoc depth_scale, dung 0.001 m/don vi");
}
if (!(depth_scale_ > 0.0f)) {
return StatusResponse::Error(StatusCode::kInternal,
"realsense: depth_scale khong duong");
}
// --- Noi suy: doc tu profile, KHONG doan ---
const auto vsp = profile_->get_stream(RS2_STREAM_DEPTH)
.as<rs2::video_stream_profile>();
const rs2_intrinsics in = vsp.get_intrinsics();
info_ = CameraInfo{};
// width/height/K la cua do phan giai LUC HIEU CHUAN, con binning noi anh
// that nho hon bao nhieu lan. Do la dung quy uoc sensor_msgs/CameraInfo.
info_.width = static_cast<uint32_t>(in.width);
info_.height = static_cast<uint32_t>(in.height);
info_.k[0] = in.fx; info_.k[2] = in.ppx;
info_.k[4] = in.fy; info_.k[5] = in.ppy;
info_.k[8] = 1.0;
for (int i = 0; i < 5; ++i) info_.d[i] = in.coeffs[i];
info_.binning_x = cfg_.decimate;
info_.binning_y = cfg_.decimate;
info_.header.frame_id = cfg_.depth_frame_id;
VSLAM_INFO("realsense: " << in.width << "x" << in.height << " @ " << cfg_.fps
<< " Hz, fx=" << in.fx << " cx=" << in.ppx
<< ", depth_scale=" << depth_scale_
<< ", decimate=" << cfg_.decimate);
return StatusResponse::Ok();
}
// Giam mau NEAREST, khong lay trung binh.
//
// Trung binh tren anh depth la SAI: trung binh cua mot diem o 1 m va mot
// diem o 5 m cho ra 3 m, tuc mot be mat KHONG TON TAI lo lung giua. Tren
// mep vat the dieu do sinh ra ca mot vien gia. Lay diem goc la cach
// image_proc/crop_decimate lam, va la ly do no dung `decimate` chu khong
// phai `resize`.
void Decimate16(const uint16_t* src, int sw, int sh, int step,
std::vector<uint8_t>* dst, uint32_t* ow, uint32_t* oh) {
const int w = sw / step, h = sh / step;
dst->resize(static_cast<size_t>(w) * h * 2);
auto* out = reinterpret_cast<uint16_t*>(dst->data());
for (int y = 0; y < h; ++y) {
const uint16_t* row = src + static_cast<size_t>(y) * step * sw;
for (int x = 0; x < w; ++x) out[static_cast<size_t>(y) * w + x] = row[x * step];
}
*ow = static_cast<uint32_t>(w);
*oh = static_cast<uint32_t>(h);
}
void Decimate8(const uint8_t* src, int sw, int sh, int step,
std::vector<uint8_t>* dst, uint32_t* ow, uint32_t* oh) {
const int w = sw / step, h = sh / step;
dst->resize(static_cast<size_t>(w) * h);
for (int y = 0; y < h; ++y) {
const uint8_t* row = src + static_cast<size_t>(y) * step * sw;
for (int x = 0; x < w; ++x) (*dst)[static_cast<size_t>(y) * w + x] = row[x * step];
}
*ow = static_cast<uint32_t>(w);
*oh = static_cast<uint32_t>(h);
}
void Loop() {
bool warned_domain = false;
bool warned_drop = false;
uint64_t last_frame_number = 0;
while (running_.load()) {
rs2::frameset fs;
try {
// Timeout co gioi han: `wait_for_frames()` mac dinh 5 s va se treo ca
// luong neu camera bi rut day. 200 ms cho phep vong kiem `running_`.
if (!pipe_->try_wait_for_frames(&fs, 200)) {
std::lock_guard<std::mutex> lk(mu_);
stats_.errors++; // het gio = mat khung, dem chung o day
continue;
}
} catch (const std::exception& e) {
std::lock_guard<std::mutex> lk(mu_);
stats_.errors++;
VSLAM_ERROR_THROTTLE(5.0, "realsense: " << e.what());
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
rs2::depth_frame depth = fs.get_depth_frame();
if (!depth) continue;
// --- Dau thoi gian ---
//
// Kiem DOMAIN THAT SU nhan duoc, khong tin option da set. Neu khong
// phai HARDWARE_CLOCK/SYSTEM_TIME thi stamp la dong ho CUA THIET BI --
// mot so hoan toan khong lien quan toi dong ho host, va moi phep dong
// bo voi LiDAR/IMU sai hang chuc nam.
const rs2_timestamp_domain dom = depth.get_frame_timestamp_domain();
UnixTime stamp;
if (dom == RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME ||
dom == RS2_TIMESTAMP_DOMAIN_GLOBAL_TIME) {
// get_timestamp() tra milli giay.
stamp = UnixTime::fromSec(depth.get_timestamp() * 1e-3);
} else {
if (!warned_domain) {
warned_domain = true;
VSLAM_WARN("realsense: timestamp domain = "
<< rs2_timestamp_domain_to_string(dom)
<< " (khong phai dong ho host). Dung thoi diem NHAN"
" thay the -- jitter cao hon, nhung it nhat cung mot"
" goc thoi gian voi LiDAR va IMU.");
}
stamp = clock_->Now();
}
// --- Dem khung roi ---
// SDK khong bao khi ta xu ly cham hon camera; so hieu khung thi co.
const uint64_t fn = depth.get_frame_number();
if (last_frame_number != 0 && fn > last_frame_number + 1) {
std::lock_guard<std::mutex> lk(mu_);
stats_.packets_lost += fn - last_frame_number - 1;
if (!warned_drop) {
warned_drop = true;
VSLAM_WARN("realsense: bo lo khung (so hieu nhay " << last_frame_number
<< " -> " << fn << "). Duong camera dang cham hon "
<< cfg_.fps << " Hz.");
}
}
last_frame_number = fn;
if (!cb_) continue;
auto keep = std::make_shared<FrameKeepAlive>();
keep->fs = fs;
CameraFrame out;
out.header.stamp = stamp;
out.header.frame_id = cfg_.depth_frame_id;
auto depth_img = std::make_shared<Image>();
depth_img->header = out.header;
depth_img->format = PixelFormat::kMono16;
depth_img->depth_scale = depth_scale_;
const int sw = depth.get_width(), sh = depth.get_height();
const auto* praw = static_cast<const uint16_t*>(depth.get_data());
if (cfg_.decimate <= 1) {
depth_img->width = static_cast<uint32_t>(sw);
depth_img->height = static_cast<uint32_t>(sh);
depth_img->step = static_cast<uint32_t>(sw) * 2;
depth_img->data = static_cast<const uint8_t*>(depth.get_data());
depth_img->keep_alive = keep; // KHONG copy: giu frameset song
} else {
Decimate16(praw, sw, sh, static_cast<int>(cfg_.decimate), &depth_buf_,
&depth_img->width, &depth_img->height);
depth_img->step = depth_img->width * 2;
depth_img->data = depth_buf_.data();
// Bo dem cua ta: hop le toi lan goi Loop() sau. Consumer chay INLINE
// trong callback (xem PerceptionPipeline) nen dieu do la du.
}
out.depth = depth_img;
if (cfg_.enable_infra1) {
rs2::video_frame ir = fs.get_infrared_frame(1);
if (ir) out.infra1 = WrapIr(ir, out.header, keep, &ir1_buf_);
}
if (cfg_.enable_infra2) {
rs2::video_frame ir = fs.get_infrared_frame(2);
if (ir) out.infra2 = WrapIr(ir, out.header, keep, &ir2_buf_);
}
out.depth_info = info_;
out.depth_info.header = out.header;
{
std::lock_guard<std::mutex> lk(mu_);
stats_.frames++;
stats_.connected = true;
}
cb_(out);
}
}
ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr,
const std::shared_ptr<FrameKeepAlive>& keep,
std::vector<uint8_t>* buf) {
auto img = std::make_shared<Image>();
img->header = hdr;
img->format = PixelFormat::kMono8;
const int w = ir.get_width(), h = ir.get_height();
if (cfg_.decimate <= 1) {
img->width = static_cast<uint32_t>(w);
img->height = static_cast<uint32_t>(h);
img->step = static_cast<uint32_t>(w);
img->data = static_cast<const uint8_t*>(ir.get_data());
img->keep_alive = keep;
} else {
Decimate8(static_cast<const uint8_t*>(ir.get_data()), w, h,
static_cast<int>(cfg_.decimate), buf, &img->width, &img->height);
img->step = img->width;
img->data = buf->data();
}
return img;
}
CameraConfig cfg_;
ClockPtr clock_;
FrameCallback cb_;
std::unique_ptr<rs2::pipeline> pipe_;
std::unique_ptr<rs2::pipeline_profile> profile_;
float depth_scale_ = 0.001f;
CameraInfo info_;
std::vector<uint8_t> depth_buf_, ir1_buf_, ir2_buf_;
std::atomic<bool> running_{false};
std::thread thread_;
mutable std::mutex mu_;
DriverStats stats_;
};
} // namespace
std::unique_ptr<CameraInterface> CreateRealSenseD410(const CameraConfig& cfg,
ClockPtr clock) {
return std::unique_ptr<CameraInterface>(
new RealSenseDriver(cfg, std::move(clock)));
}
} // namespace vslam

View File

@@ -0,0 +1,367 @@
#include "vslam/record_format.h"
#include <cstring>
namespace vslam {
namespace {
// --- Ghi/doc so nguyen little-endian, khong phu thuoc endian cua may -------
// Khong memcpy thang struct: ban ghi phai doc duoc tren may khac, va x86 dev
// voi arm64 Jetson la hai may khac nhau.
void PutU8(std::string* o, uint8_t v) { o->push_back(static_cast<char>(v)); }
void PutU16(std::string* o, uint16_t v) {
for (int i = 0; i < 2; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutU32(std::string* o, uint32_t v) {
for (int i = 0; i < 4; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutU64(std::string* o, uint64_t v) {
for (int i = 0; i < 8; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutF32(std::string* o, float v) {
uint32_t b;
std::memcpy(&b, &v, 4);
PutU32(o, b);
}
void PutF64(std::string* o, double v) {
uint64_t b;
std::memcpy(&b, &v, 8);
PutU64(o, b);
}
struct Reader {
const std::string& b;
size_t o = 0;
bool ok = true;
explicit Reader(const std::string& buf) : b(buf) {}
bool Need(size_t n) {
if (!ok || o + n > b.size()) {
ok = false;
return false;
}
return true;
}
uint8_t U8() { return Need(1) ? static_cast<uint8_t>(b[o++]) : 0; }
uint16_t U16() {
if (!Need(2)) return 0;
uint16_t v = 0;
for (int i = 0; i < 2; ++i) v |= static_cast<uint16_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
o += 2;
return v;
}
uint32_t U32() {
if (!Need(4)) return 0;
uint32_t v = 0;
for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
o += 4;
return v;
}
uint64_t U64() {
if (!Need(8)) return 0;
uint64_t v = 0;
for (int i = 0; i < 8; ++i) v |= static_cast<uint64_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
o += 8;
return v;
}
float F32() {
const uint32_t bits = U32();
float f = 0.0f;
std::memcpy(&f, &bits, 4);
return f;
}
double F64() {
const uint64_t bits = U64();
double d = 0.0;
std::memcpy(&d, &bits, 8);
return d;
}
std::string Str() {
const uint32_t n = U32();
if (!Need(n)) return {};
std::string s = b.substr(o, n);
o += n;
return s;
}
};
void PutStr(std::string* o, const std::string& s) {
PutU32(o, static_cast<uint32_t>(s.size()));
o->append(s);
}
void PutHeader(std::string* o, const Header& h) {
PutU32(o, h.seq);
PutU64(o, static_cast<uint64_t>(h.stamp.toNSec()));
PutStr(o, h.frame_id);
}
void GetHeader(Reader* r, Header* h) {
h->seq = r->U32();
h->stamp = UnixTime::fromNSec(static_cast<int64_t>(r->U64()));
h->frame_id = r->Str();
}
} // namespace
const char* VsrStreamName(VsrStream s) {
switch (s) {
case VsrStream::kScanRaw: return "scan_raw";
case VsrStream::kImu: return "imu";
case VsrStream::kBaro: return "baro";
case VsrStream::kEncoder: return "encoder";
case VsrStream::kDepth: return "depth";
case VsrStream::kInfra1: return "infra1";
case VsrStream::kInfra2: return "infra2";
case VsrStream::kCameraInfo: return "camera_info";
case VsrStream::kCmdVel: return "cmd_vel";
case VsrStream::kEvent: return "event";
case VsrStream::kUltrasonic: return "ultrasonic";
case VsrStream::kBumper: return "bumper";
}
return "?";
}
// --- LaserScan -------------------------------------------------------------
void EncodeScanPayload(const LaserScan& s, std::string* o) {
PutHeader(o, s.header);
PutF32(o, s.angle_min);
PutF32(o, s.angle_max);
PutF32(o, s.angle_increment);
PutF32(o, s.time_increment);
PutF32(o, s.scan_time);
PutF32(o, s.range_min);
PutF32(o, s.range_max);
PutU32(o, static_cast<uint32_t>(s.ranges.size()));
// float32 tho, KHONG luong tu hoa: day la ban ghi de chay lai thuat toan,
// khong phai de hien thi. Mat mat lam tron o day se lam replay khong con
// tat dinh so voi live.
for (const float r : s.ranges) PutF32(o, r);
PutU32(o, static_cast<uint32_t>(s.intensities.size()));
for (const float v : s.intensities) PutF32(o, v);
}
bool DecodeScanPayload(const std::string& buf, LaserScan* s) {
Reader r(buf);
GetHeader(&r, &s->header);
s->angle_min = r.F32();
s->angle_max = r.F32();
s->angle_increment = r.F32();
s->time_increment = r.F32();
s->scan_time = r.F32();
s->range_min = r.F32();
s->range_max = r.F32();
const uint32_t n = r.U32();
if (!r.ok || !r.Need(static_cast<size_t>(n) * 4)) return false;
s->ranges.resize(n);
for (uint32_t i = 0; i < n; ++i) s->ranges[i] = r.F32();
const uint32_t m = r.U32();
if (!r.ok || !r.Need(static_cast<size_t>(m) * 4)) return false;
s->intensities.resize(m);
for (uint32_t i = 0; i < m; ++i) s->intensities[i] = r.F32();
return r.ok;
}
// --- Imu -------------------------------------------------------------------
void EncodeImuPayload(const Imu& v, std::string* o) {
PutHeader(o, v.header);
PutF64(o, v.angular_velocity.x);
PutF64(o, v.angular_velocity.y);
PutF64(o, v.angular_velocity.z);
PutF64(o, v.linear_acceleration.x);
PutF64(o, v.linear_acceleration.y);
PutF64(o, v.linear_acceleration.z);
for (int i = 0; i < 9; ++i) PutF64(o, v.angular_velocity_covariance[i]);
for (int i = 0; i < 9; ++i) PutF64(o, v.linear_acceleration_covariance[i]);
}
bool DecodeImuPayload(const std::string& buf, Imu* v) {
Reader r(buf);
GetHeader(&r, &v->header);
v->angular_velocity.x = r.F64();
v->angular_velocity.y = r.F64();
v->angular_velocity.z = r.F64();
v->linear_acceleration.x = r.F64();
v->linear_acceleration.y = r.F64();
v->linear_acceleration.z = r.F64();
for (int i = 0; i < 9; ++i) v->angular_velocity_covariance[i] = r.F64();
for (int i = 0; i < 9; ++i) v->linear_acceleration_covariance[i] = r.F64();
// D410 khong co IMU tich hop va MCU khong gui orientation -> danh dau
// "khong co orientation" theo dung quy uoc sensor_msgs.
v->orientation_covariance[0] = -1.0;
return r.ok;
}
// --- Encoder ---------------------------------------------------------------
void EncodeUltrasonicPayload(const double* range, size_t count, std::string* o) {
PutU32(o, static_cast<uint32_t>(count));
// f64 chu khong f32: inf va NaN phai di qua nguyen ven. Ba ngu nghia cua
// mot lan doc sieu am (huu han / inf / NaN) la thong tin an toan, khong
// phai chi tiet lam tron duoc.
for (size_t i = 0; i < count; ++i) PutF64(o, range[i]);
}
bool DecodeUltrasonicPayload(const std::string& buf, double* range, size_t* count,
size_t max_count) {
Reader r(buf);
const uint32_t n = r.U32();
if (!r.ok || n > max_count) return false;
for (uint32_t i = 0; i < n; ++i) range[i] = r.F64();
*count = n;
return r.ok;
}
void EncodeBumperPayload(uint32_t mask, std::string* o) { PutU32(o, mask); }
bool DecodeBumperPayload(const std::string& buf, uint32_t* mask) {
Reader r(buf);
*mask = r.U32();
return r.ok;
}
void EncodeEncoderPayload(double l, double rr, std::string* o) {
PutF64(o, l);
PutF64(o, rr);
}
bool DecodeEncoderPayload(const std::string& buf, double* l, double* rr) {
Reader r(buf);
*l = r.F64();
*rr = r.F64();
return r.ok;
}
// --- Baro ------------------------------------------------------------------
void EncodeBaroPayload(const FluidPressure& p, const Temperature& t, std::string* o) {
PutHeader(o, p.header);
PutF64(o, p.fluid_pressure);
PutF64(o, p.variance);
PutF64(o, t.temperature);
PutF64(o, t.variance);
}
bool DecodeBaroPayload(const std::string& buf, FluidPressure* p, Temperature* t) {
Reader r(buf);
GetHeader(&r, &p->header);
p->fluid_pressure = r.F64();
p->variance = r.F64();
t->header = p->header;
t->temperature = r.F64();
t->variance = r.F64();
return r.ok;
}
// --- Twist -----------------------------------------------------------------
void EncodeTwistPayload(const Twist& t, std::string* o) {
PutF64(o, t.linear.x);
PutF64(o, t.linear.y);
PutF64(o, t.linear.z);
PutF64(o, t.angular.x);
PutF64(o, t.angular.y);
PutF64(o, t.angular.z);
}
bool DecodeTwistPayload(const std::string& buf, Twist* t) {
Reader r(buf);
t->linear.x = r.F64();
t->linear.y = r.F64();
t->linear.z = r.F64();
t->angular.x = r.F64();
t->angular.y = r.F64();
t->angular.z = r.F64();
return r.ok;
}
// --- CameraInfo ------------------------------------------------------------
void EncodeCameraInfoPayload(const CameraInfo& c, std::string* o) {
PutHeader(o, c.header);
PutU32(o, c.width);
PutU32(o, c.height);
for (int i = 0; i < 9; ++i) PutF64(o, c.k[i]);
for (int i = 0; i < 5; ++i) PutF64(o, c.d[i]);
PutU32(o, c.binning_x);
PutU32(o, c.binning_y);
}
bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* c) {
Reader r(buf);
GetHeader(&r, &c->header);
c->width = r.U32();
c->height = r.U32();
for (int i = 0; i < 9; ++i) c->k[i] = r.F64();
for (int i = 0; i < 5; ++i) c->d[i] = r.F64();
c->binning_x = r.U32();
c->binning_y = r.U32();
if (c->binning_x == 0) c->binning_x = 1;
if (c->binning_y == 0) c->binning_y = 1;
return r.ok;
}
// --- Image -----------------------------------------------------------------
void EncodeImagePayload(const Image& img, std::string* o) {
PutHeader(o, img.header);
PutU32(o, img.width);
PutU32(o, img.height);
PutU32(o, img.step);
PutU8(o, static_cast<uint8_t>(img.format));
PutU16(o, 0); // reserved, giu can chinh
PutF32(o, img.depth_scale);
const uint32_t n = static_cast<uint32_t>(img.size_bytes());
PutU32(o, n);
if (img.data != nullptr && n > 0) {
o->append(reinterpret_cast<const char*>(img.data), n);
}
}
bool DecodeImagePayload(const std::string& buf, Image* img,
std::vector<uint8_t>* storage) {
Reader r(buf);
GetHeader(&r, &img->header);
img->width = r.U32();
img->height = r.U32();
img->step = r.U32();
img->format = static_cast<PixelFormat>(r.U8());
r.U16();
img->depth_scale = r.F32();
const uint32_t n = r.U32();
if (!r.ok || !r.Need(n)) return false;
// Image khong so huu bo nho (no tro vao buffer cua librealsense khi chay
// that). Khi replay thi `storage` dong vai tro do, va goi phai giu storage
// song it nhat bang Image.
storage->assign(buf.begin() + static_cast<long>(r.o),
buf.begin() + static_cast<long>(r.o) + static_cast<long>(n));
img->data = storage->data();
return true;
}
// --- crc32 -----------------------------------------------------------------
uint32_t Crc32(const void* data, size_t len, uint32_t seed) {
static uint32_t table[256];
static bool init = false;
if (!init) {
for (uint32_t i = 0; i < 256; ++i) {
uint32_t c = i;
for (int k = 0; k < 8; ++k) c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
table[i] = c;
}
init = true;
}
uint32_t c = seed ^ 0xFFFFFFFFu;
const uint8_t* p = static_cast<const uint8_t*>(data);
for (size_t i = 0; i < len; ++i) c = table[(c ^ p[i]) & 0xFF] ^ (c >> 8);
return c ^ 0xFFFFFFFFu;
}
} // namespace vslam

View File

@@ -0,0 +1,326 @@
#include "vslam/record_io.h"
#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <cstring>
#include <deque>
#include <fstream>
#include <mutex>
#include <thread>
#include "vslam/log.h"
namespace vslam {
namespace {
void PutU32(std::string* o, uint32_t v) {
for (int i = 0; i < 4; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutU64(std::string* o, uint64_t v) {
for (int i = 0; i < 8; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
uint32_t GetU32(const char* p) {
uint32_t v = 0;
for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(static_cast<uint8_t>(p[i])) << (8 * i);
return v;
}
uint64_t GetU64(const char* p) {
uint64_t v = 0;
for (int i = 0; i < 8; ++i) v |= static_cast<uint64_t>(static_cast<uint8_t>(p[i])) << (8 * i);
return v;
}
} // namespace
// ---------------------------------------------------------------------------
// Writer
// ---------------------------------------------------------------------------
struct RecordWriter::Impl {
RecordWriterConfig cfg;
std::ofstream file;
mutable std::mutex mu;
std::condition_variable cv;
std::deque<std::string> queue; // chunk da dong goi san
size_t queue_bytes = 0;
bool running = false;
std::thread thread;
mutable std::mutex stats_mu;
RecordWriterStats stats;
// Dem drop giua hai lan ghi su kien, de mot dot drop dai khong sinh hang
// nghin dong su kien.
uint64_t pending_drops = 0;
UnixTime last_drop_stamp;
explicit Impl(RecordWriterConfig c) : cfg(std::move(c)) {}
void Loop() {
while (true) {
std::string chunk;
{
std::unique_lock<std::mutex> lk(mu);
cv.wait(lk, [this] { return !queue.empty() || !running; });
if (queue.empty()) {
if (!running) return;
continue;
}
chunk = std::move(queue.front());
queue.pop_front();
queue_bytes -= chunk.size();
}
file.write(chunk.data(), static_cast<std::streamsize>(chunk.size()));
std::lock_guard<std::mutex> lk(stats_mu);
if (!file) {
stats.write_errors++;
} else {
stats.chunks_written++;
stats.bytes_written += chunk.size();
}
}
}
};
RecordWriter::RecordWriter(RecordWriterConfig cfg)
: impl_(std::make_unique<Impl>(std::move(cfg))) {}
RecordWriter::~RecordWriter() { Close(); }
StatusResponse RecordWriter::Open() {
if (impl_->running) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da mo roi");
}
impl_->file.open(impl_->cfg.path, std::ios::binary | std::ios::trunc);
if (!impl_->file) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong mo duoc de ghi: " + impl_->cfg.path);
}
std::string header;
header.append(kVsrMagic, sizeof(kVsrMagic));
PutU32(&header, kVsrVersion);
PutU32(&header, 0); // reserved
PutU64(&header, static_cast<uint64_t>(UnixTime::now().toNSec()));
PutU32(&header, static_cast<uint32_t>(impl_->cfg.config_json.size()));
header.append(impl_->cfg.config_json);
impl_->file.write(header.data(), static_cast<std::streamsize>(header.size()));
if (!impl_->file) {
return StatusResponse::Error(StatusCode::kInternal, "khong ghi duoc header");
}
impl_->running = true;
impl_->thread = std::thread([this] { impl_->Loop(); });
VSLAM_INFO("record: dang ghi " << impl_->cfg.path);
return StatusResponse::Ok();
}
void RecordWriter::Close() {
if (!impl_ || !impl_->running) return;
{
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->running = false;
}
impl_->cv.notify_all();
if (impl_->thread.joinable()) impl_->thread.join();
impl_->file.flush();
impl_->file.close();
const RecordWriterStats s = Stats();
VSLAM_INFO("record: dong. " << s.chunks_written << " chunk, "
<< s.bytes_written / 1024 / 1024 << " MB, " << s.chunks_dropped
<< " chunk bi drop");
}
bool RecordWriter::Write(VsrStream stream, UnixTime stamp, std::string payload) {
const uint32_t crc = Crc32(payload.data(), payload.size());
std::string chunk;
chunk.reserve(kVsrChunkHeaderSize + payload.size() + 4);
PutU32(&chunk, kVsrChunkMagic);
chunk.push_back(static_cast<char>(stream));
chunk.push_back(static_cast<char>(0)); // flags: chua nen
chunk.push_back(0);
chunk.push_back(0); // reserved
PutU64(&chunk, static_cast<uint64_t>(stamp.toNSec()));
PutU32(&chunk, static_cast<uint32_t>(payload.size()));
chunk.append(payload);
PutU32(&chunk, crc);
{
std::lock_guard<std::mutex> lk(impl_->mu);
if (!impl_->running) return false;
// DROP CHU KHONG CHAN. Mot the USB cham khong duoc phep lam luong
// lidar_rx dung lai -- do la ca ly do writer nam o luong rieng.
if (impl_->queue_bytes + chunk.size() > impl_->cfg.max_queue_bytes) {
impl_->pending_drops++;
impl_->last_drop_stamp = stamp;
std::lock_guard<std::mutex> slk(impl_->stats_mu);
impl_->stats.chunks_dropped++;
return false;
}
// Da tung drop -> ghi mot su kien tom tat TRUOC chunk nay, de ban ghi tu
// mo ta duoc lo hong cua chinh no.
if (impl_->pending_drops > 0) {
const uint64_t n = impl_->pending_drops;
impl_->pending_drops = 0;
std::string ev = "{\"t\":\"drop\",\"chunks\":" + std::to_string(n) + "}";
std::string ev_chunk;
const uint32_t ev_crc = Crc32(ev.data(), ev.size());
PutU32(&ev_chunk, kVsrChunkMagic);
ev_chunk.push_back(static_cast<char>(VsrStream::kEvent));
ev_chunk.push_back(0);
ev_chunk.push_back(0);
ev_chunk.push_back(0);
PutU64(&ev_chunk, static_cast<uint64_t>(impl_->last_drop_stamp.toNSec()));
PutU32(&ev_chunk, static_cast<uint32_t>(ev.size()));
ev_chunk.append(ev);
PutU32(&ev_chunk, ev_crc);
impl_->queue_bytes += ev_chunk.size();
impl_->queue.push_back(std::move(ev_chunk));
}
impl_->queue_bytes += chunk.size();
impl_->queue.push_back(std::move(chunk));
{
std::lock_guard<std::mutex> slk(impl_->stats_mu);
impl_->stats.queue_bytes = impl_->queue_bytes;
}
}
impl_->cv.notify_one();
return true;
}
void RecordWriter::WriteEvent(UnixTime stamp, const std::string& json) {
Write(VsrStream::kEvent, stamp, json);
}
RecordWriterStats RecordWriter::Stats() const {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
return impl_->stats;
}
// ---------------------------------------------------------------------------
// Reader
// ---------------------------------------------------------------------------
struct RecordReader::Impl {
std::ifstream file;
RecordFileInfo info;
bool truncated = false;
uint64_t chunks = 0;
uint64_t bytes = 0;
};
RecordReader::RecordReader() : impl_(std::make_unique<Impl>()) {}
RecordReader::~RecordReader() = default;
StatusResponse RecordReader::Open(const std::string& path) {
impl_->file.open(path, std::ios::binary);
if (!impl_->file) {
return StatusResponse::Error(StatusCode::kNotFound, "khong mo duoc: " + path);
}
char fixed[kVsrHeaderFixedSize];
impl_->file.read(fixed, sizeof(fixed));
if (impl_->file.gcount() != static_cast<std::streamsize>(sizeof(fixed))) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "file qua ngan");
}
if (std::memcmp(fixed, kVsrMagic, sizeof(kVsrMagic)) != 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"khong phai file .vsr (sai magic)");
}
impl_->info.version = GetU32(fixed + 8);
if (impl_->info.version != kVsrVersion) {
// TU CHOI ro rang thay vi co doc. Doi schema lam moi file expected/*.json
// cu vo gia tri, va doc nham mot phien ban khac chi sinh du lieu vo nghia.
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"phien ban .vsr khong khop: file la " + std::to_string(impl_->info.version) +
", chuong trinh doc duoc " + std::to_string(kVsrVersion));
}
impl_->info.start_stamp = UnixTime::fromNSec(static_cast<int64_t>(GetU64(fixed + 16)));
const uint32_t cfg_len = GetU32(fixed + 24);
if (cfg_len > 0) {
impl_->info.config_json.resize(cfg_len);
impl_->file.read(&impl_->info.config_json[0], cfg_len);
if (impl_->file.gcount() != static_cast<std::streamsize>(cfg_len)) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "header cut");
}
}
return StatusResponse::Ok();
}
void RecordReader::Close() { impl_->file.close(); }
const RecordFileInfo& RecordReader::info() const { return impl_->info; }
bool RecordReader::Next(VsrChunkHeader* header, std::string* payload) {
char hdr[kVsrChunkHeaderSize];
impl_->file.read(hdr, sizeof(hdr));
const std::streamsize got = impl_->file.gcount();
if (got == 0) return false; // het file binh thuong
if (got != static_cast<std::streamsize>(sizeof(hdr))) {
impl_->truncated = true;
return false;
}
if (GetU32(hdr) != kVsrChunkMagic) {
impl_->truncated = true;
return false;
}
header->stream = static_cast<VsrStream>(static_cast<uint8_t>(hdr[4]));
header->compressed = (static_cast<uint8_t>(hdr[5]) & 0x01) != 0;
header->stamp_ns = GetU64(hdr + 8);
header->payload_len = GetU32(hdr + 16);
payload->resize(header->payload_len);
if (header->payload_len > 0) {
impl_->file.read(&(*payload)[0], header->payload_len);
if (impl_->file.gcount() != static_cast<std::streamsize>(header->payload_len)) {
impl_->truncated = true;
return false;
}
}
char crc_buf[4];
impl_->file.read(crc_buf, 4);
if (impl_->file.gcount() != 4) {
impl_->truncated = true;
return false;
}
const uint32_t want = GetU32(crc_buf);
const uint32_t got_crc = Crc32(payload->data(), payload->size());
if (want != got_crc) {
// DUNG LAI, khong bo qua de doc tiep. Mot the USB rut ra giua chung lam
// file hong tu diem nao do tro di; doc tiep chi cho ra rac, va rac do se
// di vao thuat toan ma khong ai biet.
VSLAM_ERROR("record: CRC sai o chunk " << impl_->chunks << " (stream "
<< VsrStreamName(header->stream) << "), dung doc");
impl_->truncated = true;
return false;
}
impl_->chunks++;
impl_->bytes += kVsrChunkHeaderSize + header->payload_len + 4;
return true;
}
bool RecordReader::truncated() const { return impl_->truncated; }
uint64_t RecordReader::chunks_read() const { return impl_->chunks; }
uint64_t RecordReader::bytes_read() const { return impl_->bytes; }
} // namespace vslam

View File

@@ -0,0 +1,422 @@
#include <chrono>
#include <thread>
#include "vslam/replay_source.h"
#include <atomic>
#include <memory>
#include <mutex>
#include <vector>
#include "vslam/log.h"
#include "vslam/record_io.h"
#include "vslam/scan_sanitizer.h"
namespace vslam {
namespace {
// Bon lop duoi day la interface driver THAT, chi khac o cho nguon du lieu la
// file chu khong phai socket. vslam_node khong phan biet duoc -- do la muc
// dich.
//
// Chung khong tu chay: ReplaySource::Run() day du lieu vao chung. Open()/
// Close() chi bat/tat co, vi vong doi thuc do ReplaySource quan.
class ReplayLidar : public LidarInterface {
public:
void SetCallback(ScanCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
void Close() override { open_ = false; }
DriverStats Stats() const override { return stats_; }
void Push(LaserScanPtr scan) {
if (!open_ || !cb_) return;
stats_.frames++;
stats_.connected = true;
cb_(std::move(scan));
}
private:
ScanCallback cb_;
bool open_ = false;
DriverStats stats_;
};
class ReplayCamera : public CameraInterface {
public:
void SetCallback(FrameCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
void Close() override { open_ = false; }
DriverStats Stats() const override { return stats_; }
void Push(const CameraFrame& f) {
if (!open_ || !cb_) return;
stats_.frames++;
stats_.connected = true;
cb_(f);
}
private:
FrameCallback cb_;
bool open_ = false;
DriverStats stats_;
};
class ReplayMcu : public McuInterface {
public:
void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); }
void SetBaroCallback(BaroCallback cb) override { baro_cb_ = std::move(cb); }
void SetUltrasonicCallback(UltrasonicCallback cb) override { us_cb_ = std::move(cb); }
void SetBumperCallback(BumperCallback cb) override { bumper_cb_ = std::move(cb); }
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
void Close() override { open_ = false; }
DriverStats Stats() const override { return stats_; }
void PushImu(ImuPtr imu) {
if (!open_ || !imu_cb_) return;
stats_.frames++;
stats_.connected = true;
imu_cb_(std::move(imu));
}
void PushBaro(const FluidPressure& p, const Temperature& t) {
if (!open_ || !baro_cb_) return;
baro_cb_(p, t);
}
private:
ImuCallback imu_cb_;
BaroCallback baro_cb_;
UltrasonicCallback us_cb_;
BumperCallback bumper_cb_;
public:
void PushUltrasonic(const UltrasonicReading& u) { if (us_cb_) us_cb_(u); }
void PushBumper(const BumperReading& b) { if (bumper_cb_) bumper_cb_(b); }
private:
bool open_ = false;
DriverStats stats_;
};
class ReplayBase : public BaseInterface {
public:
void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); }
// Lenh motor khi replay di vao hu khong -- KHONG co banh xe nao quay.
// Dem lai de bai regression kiem duoc rang he thong DA ra lenh dung, du
// khong co gi de thuc thi.
void SetVelocity(double linear, double angular) override {
std::lock_guard<std::mutex> lk(mu_);
last_linear_ = linear;
last_angular_ = angular;
cmds_++;
}
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
void Close() override { open_ = false; }
DriverStats Stats() const override { return stats_; }
void Push(const EncoderReading& e) {
if (!open_ || !cb_) return;
stats_.frames++;
stats_.connected = true;
cb_(e);
}
void LastCommand(double* lin, double* ang, uint64_t* n) const {
std::lock_guard<std::mutex> lk(mu_);
*lin = last_linear_;
*ang = last_angular_;
*n = cmds_;
}
private:
EncoderCallback cb_;
bool open_ = false;
DriverStats stats_;
mutable std::mutex mu_;
double last_linear_ = 0.0;
double last_angular_ = 0.0;
uint64_t cmds_ = 0;
};
} // namespace
// ---------------------------------------------------------------------------
struct ReplaySource::Impl {
ReplayConfig cfg;
RecordReader reader;
ReplayLidar lidar;
ReplayCamera camera;
ReplayMcu mcu;
ReplayBase base;
std::shared_ptr<ReplayClock> clock;
std::unique_ptr<ScanSanitizer> sanitizer;
std::atomic<bool> stop{false};
mutable std::mutex stats_mu;
Stats stats;
// Khung camera duoc rap tu nhieu chunk (depth, infra1, infra2, camera_info)
// roi phat mot lan khi thay chunk depth ke tiep hoac khi het file.
CameraFrame pending_frame;
bool have_pending = false;
std::vector<uint8_t> depth_storage;
std::vector<uint8_t> infra1_storage;
std::vector<uint8_t> infra2_storage;
CameraInfo last_info;
bool have_info = false;
explicit Impl(ReplayConfig c) : cfg(std::move(c)) {}
void FlushCameraFrame() {
if (!have_pending) return;
if (have_info) pending_frame.depth_info = last_info;
camera.Push(pending_frame);
{
std::lock_guard<std::mutex> lk(stats_mu);
stats.camera_frames++;
}
have_pending = false;
pending_frame = CameraFrame{};
}
};
ReplaySource::ReplaySource(ReplayConfig cfg)
: impl_(std::make_unique<Impl>(std::move(cfg))) {}
ReplaySource::~ReplaySource() { RequestStop(); }
StatusResponse ReplaySource::Open() {
const StatusResponse st = impl_->reader.Open(impl_->cfg.path);
if (!st.ok()) return st;
impl_->clock = MakeReplayClock(impl_->reader.info().start_stamp);
impl_->clock->SetSpeed(impl_->cfg.deterministic ? 0.0 : impl_->cfg.speed);
if (impl_->cfg.apply_sanitizer) {
try {
impl_->sanitizer = std::make_unique<ScanSanitizer>(impl_->cfg.sanitizer);
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
std::string("sanitizer: ") + e.what());
}
}
VSLAM_INFO("replay: mo " << impl_->cfg.path << ", bat dau tu "
<< impl_->reader.info().start_stamp.toString()
<< (impl_->cfg.deterministic ? " (che do tat dinh)" : ""));
return StatusResponse::Ok();
}
ClockPtr ReplaySource::clock() const { return impl_->clock; }
LidarInterface* ReplaySource::lidar() { return &impl_->lidar; }
CameraInterface* ReplaySource::camera() { return &impl_->camera; }
McuInterface* ReplaySource::mcu() { return &impl_->mcu; }
BaseInterface* ReplaySource::base() { return &impl_->base; }
const std::string& ReplaySource::recorded_config_json() const {
return impl_->reader.info().config_json;
}
void ReplaySource::RequestStop() { impl_->stop.store(true); }
void ReplaySource::Run() {
VsrChunkHeader h;
std::string payload;
const UnixTime file_start = impl_->reader.info().start_stamp;
UnixTime first_stamp;
bool have_first = false;
// Moc de dong bo thoi gian tuong khi phat theo thoi gian that.
bool have_play_origin = false;
std::chrono::steady_clock::time_point play_origin_wall;
UnixTime play_origin_stamp;
UnixTime last_stamp;
while (!impl_->stop.load() && impl_->reader.Next(&h, &payload)) {
const UnixTime stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
if (!have_first) {
first_stamp = stamp;
have_first = true;
// Dat dong ho ao theo chunk DAU TIEN, khong theo start_stamp cua header.
//
// start_stamp la thoi diem writer MO FILE, do dong ho tuong cua may ghi.
// No khong nhat thiet trung voi moc thoi gian cua du lieu: mot ban ghi
// chuyen doi tu nguon khac, hoac mot may co dong ho sai, se lech han.
// Neu lay theo header thi SetNow() tu choi lui va dong ho ao ket o thoi
// gian that -- moi phep timeout theo stamp sau do deu sai.
//
// allow_backward chi o DUNG lan dau nay.
impl_->clock->SetNow(stamp, /*allow_backward=*/true);
}
last_stamp = stamp;
// Cua so start/duration.
const double rel = SecondsBetween(stamp, first_stamp);
if (rel < impl_->cfg.start_sec) {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.skipped++;
continue;
}
if (impl_->cfg.duration_sec > 0.0 &&
rel > impl_->cfg.start_sec + impl_->cfg.duration_sec) {
break;
}
// Lai dong ho ao TRUOC khi day du lieu, de moi stage nhin thay thoi gian
// dung luc ban tin nay den.
impl_->clock->SetNow(stamp);
if (!impl_->cfg.deterministic && impl_->cfg.speed > 0.0) {
// Ngu cho toi khi thoi gian TUONG bat kip stamp cua chunk nay.
//
// ⚠️ Ban truoc viet `SleepUntil(Steady() + nanoseconds(0))` -- tuc la
// ngu KHONG giay nao. `speed` va `deterministic=false` khong co tac
// dung gi, va ban ghi luon chay het toc. Triong chung danh lua: ca
// duong ong van dung, chi la mot ban ghi 8 giay chay xong trong 0.4
// giay, va tren web UI thi no giong het nhu "replay bi treo o khung
// cuoi".
//
// Moc la chunk DAU TIEN duoc phat (sau cua so start_sec), khong phai
// chunk dau file: neu khong thi voi --start 60 no se ngu 60 giay truoc
// khi phat gi.
if (!have_play_origin) {
play_origin_wall = std::chrono::steady_clock::now();
play_origin_stamp = stamp;
have_play_origin = true;
}
const double elapsed = SecondsBetween(stamp, play_origin_stamp) /
impl_->cfg.speed;
const auto target =
play_origin_wall +
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::duration<double>(elapsed));
// Cho phep tut lai: neu may qua cham thi phat tiep ngay, khong don no
// thanh mot cu ngu bu.
if (target > std::chrono::steady_clock::now()) {
std::this_thread::sleep_until(target);
}
}
{
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.chunks++;
}
switch (h.stream) {
case VsrStream::kScanRaw: {
auto scan = std::make_shared<LaserScan>();
if (!DecodeScanPayload(payload, scan.get())) break;
// Ban ghi luu du lieu THO (truoc sanitizer) chinh la de cho nay: doi
// nguong sanitizer roi chay lai tren cung mot file.
if (impl_->sanitizer) impl_->sanitizer->Apply(scan.get());
impl_->lidar.Push(std::move(scan));
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.scans++;
break;
}
case VsrStream::kImu: {
auto imu = std::make_shared<Imu>();
if (!DecodeImuPayload(payload, imu.get())) break;
impl_->mcu.PushImu(std::move(imu));
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.imu++;
break;
}
case VsrStream::kBaro: {
FluidPressure p;
Temperature t;
if (!DecodeBaroPayload(payload, &p, &t)) break;
impl_->mcu.PushBaro(p, t);
break;
}
case VsrStream::kEncoder: {
EncoderReading e;
if (!DecodeEncoderPayload(payload, &e.left_rad, &e.right_rad)) break;
e.stamp = stamp;
e.valid = true;
impl_->base.Push(e);
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.encoder++;
break;
}
case VsrStream::kUltrasonic: {
UltrasonicReading u;
if (!DecodeUltrasonicPayload(payload, u.range, &u.count, 8)) break;
u.stamp = stamp;
impl_->mcu.PushUltrasonic(u);
break;
}
case VsrStream::kBumper: {
BumperReading b;
if (!DecodeBumperPayload(payload, &b.mask)) break;
b.stamp = stamp;
impl_->mcu.PushBumper(b);
break;
}
case VsrStream::kDepth: {
// Chunk depth moi = khung truoc da day du -> phat khung truoc.
impl_->FlushCameraFrame();
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->depth_storage)) break;
impl_->pending_frame.header = img->header;
impl_->pending_frame.depth = img;
impl_->have_pending = true;
break;
}
case VsrStream::kInfra1: {
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->infra1_storage)) break;
impl_->pending_frame.infra1 = img;
break;
}
case VsrStream::kInfra2: {
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->infra2_storage)) break;
impl_->pending_frame.infra2 = img;
break;
}
case VsrStream::kCameraInfo: {
if (DecodeCameraInfoPayload(payload, &impl_->last_info)) {
impl_->have_info = true;
}
break;
}
case VsrStream::kCmdVel:
// Lenh dieu khien DA GHI la dau vao cua lop safety, khong phai dau ra.
// Replay khong tu dong ap chung: viec do do wiring quyet dinh.
break;
case VsrStream::kEvent: {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.events++;
VSLAM_DEBUG("replay: su kien tai " << stamp.toString() << ": " << payload);
break;
}
}
}
impl_->FlushCameraFrame();
{
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.truncated = impl_->reader.truncated();
if (have_first) impl_->stats.duration_sec = SecondsBetween(last_stamp, first_stamp);
}
const Stats s = stats();
VSLAM_INFO("replay: xong. " << s.chunks << " chunk trong " << s.duration_sec
<< " s -- " << s.scans << " scan, " << s.imu << " imu, "
<< s.encoder << " encoder, " << s.camera_frames << " khung camera"
<< (s.truncated ? " [FILE CUT GIUA CHUNG]" : ""));
(void)file_start;
}
ReplaySource::Stats ReplaySource::stats() const {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
return impl_->stats;
}
} // namespace vslam

View File

@@ -0,0 +1,125 @@
#include "vslam/scan_sanitizer.h"
#include <cmath>
#include <limits>
#include <stdexcept>
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
void ScanSanitizer::Validate(const ScanSanitizerConfig& cfg) {
// Kiem o day chu khong im lang roi ve default. Mot LiDAR cau hinh sai la
// mot robot dam vao tuong, va `range_min = 0` chinh la bug cua driver goc
// ma lop nay ton tai de sua.
if (!(cfg.range_min > 0.0)) {
throw std::invalid_argument("scan_sanitizer: range_min phai > 0 (dang la " +
std::to_string(cfg.range_min) + ")");
}
if (!(cfg.range_max > cfg.range_min)) {
throw std::invalid_argument("scan_sanitizer: range_max phai > range_min");
}
if (cfg.zero_is != "nan" && cfg.zero_is != "inf") {
throw std::invalid_argument("scan_sanitizer: zero_is phai la \"nan\" hoac \"inf\"");
}
for (const auto& m : cfg.sector_masks) {
if (m.upper_rad < m.lower_rad) {
throw std::invalid_argument("scan_sanitizer: sector mask co upper < lower");
}
}
}
ScanSanitizer::ScanSanitizer(ScanSanitizerConfig cfg) : cfg_(std::move(cfg)) {
Validate(cfg_);
zero_to_inf_ = (cfg_.zero_is == "inf");
VSLAM_INFO("scan_sanitizer: ep header ve [" << cfg_.range_min << ", "
<< cfg_.range_max << "] m, 0.0 -> " << (zero_to_inf_ ? "inf" : "NaN")
<< ", " << cfg_.sector_masks.size() << " quat bi cat"
<< (cfg_.angle_offset_rad != 0.0
? ", offset " + std::to_string(cfg_.angle_offset_rad * 180.0 / 3.14159265358979323846) + " do"
: ""));
}
bool ScanSanitizer::InMaskedSector(double angle) const {
for (const auto& m : cfg_.sector_masks) {
if (angle >= m.lower_rad && angle <= m.upper_rad) return true;
}
return false;
}
void ScanSanitizer::Apply(LaserScan* scan) {
if (scan == nullptr || scan->ranges.empty()) return;
const float range_min = static_cast<float>(cfg_.range_min);
const float range_max = static_cast<float>(cfg_.range_max);
// 1. Ep header ve gia tri that cua thiet bi.
scan->range_min = range_min;
scan->range_max = range_max;
// 2. Bo phep chia 2 thua cua driver. Bat ky ai deskew theo truong nay ma
// doc gia tri goc thi chi bu duoc mot nua.
if (cfg_.fix_time_increment) {
scan->time_increment = scan->scan_time / static_cast<float>(scan->ranges.size());
}
// 3. Xoay neu huong 0 do cua LiDAR khong trung truc x cua robot.
if (cfg_.angle_offset_rad != 0.0) {
scan->angle_min += static_cast<float>(cfg_.angle_offset_rad);
scan->angle_max += static_cast<float>(cfg_.angle_offset_rad);
}
const float nan_v = std::numeric_limits<float>::quiet_NaN();
const float inf_v = std::numeric_limits<float>::infinity();
const float zero_v = zero_to_inf_ ? inf_v : nan_v;
const float blank_v = blank_value();
stats_.scans++;
stats_.rays_total += scan->ranges.size();
for (size_t i = 0; i < scan->ranges.size(); ++i) {
// Sector mask ap TRUOC moi thu khac: mot tia bi than robot che thi gia
// tri do duoc cua no khong co y nghia gi ca.
const double angle =
static_cast<double>(scan->angle_min) + static_cast<double>(i) * scan->angle_increment;
if (InMaskedSector(NormalizeAngle(angle))) {
scan->ranges[i] = blank_v;
stats_.rays_blanked++;
continue;
}
const float r = scan->ranges[i];
if (std::isnan(r)) continue; // da la "khong do duoc"
if (r <= 0.0f) {
// 0.0 = khong do duoc HOAC be mat den nuot het xung. Xem khoi comment
// dau header: map sang NaN la hong ve phia an toan.
scan->ranges[i] = zero_v;
stats_.rays_zero++;
continue;
}
if (r < range_min) {
// Gan hon nguong tin cay cua thiet bi. KHONG map sang inf: cho nay co
// the dang co vat that, chi la qua gan de do.
scan->ranges[i] = nan_v;
stats_.rays_below_min++;
continue;
}
if (r > range_max) {
// Ke ca inf san co. "Khong co gi trong tam" -> giu inf de consumer
// duoc phep clear free space.
scan->ranges[i] = inf_v;
stats_.rays_above_max++;
continue;
}
stats_.rays_valid++;
}
}
} // namespace vslam