upload
This commit is contained in:
140
libs/vslam_drivers/src/clock_sync.cc
Normal file
140
libs/vslam_drivers/src/clock_sync.cc
Normal 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
|
||||
179
libs/vslam_drivers/src/mcu_protocol.cc
Normal file
179
libs/vslam_drivers/src/mcu_protocol.cc
Normal 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
|
||||
404
libs/vslam_drivers/src/realsense_driver.cc
Normal file
404
libs/vslam_drivers/src/realsense_driver.cc
Normal 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
|
||||
367
libs/vslam_drivers/src/record_format.cc
Normal file
367
libs/vslam_drivers/src/record_format.cc
Normal 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
|
||||
326
libs/vslam_drivers/src/record_io.cc
Normal file
326
libs/vslam_drivers/src/record_io.cc
Normal 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
|
||||
422
libs/vslam_drivers/src/replay_source.cc
Normal file
422
libs/vslam_drivers/src/replay_source.cc
Normal 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
|
||||
125
libs/vslam_drivers/src/scan_sanitizer.cc
Normal file
125
libs/vslam_drivers/src/scan_sanitizer.cc
Normal 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
|
||||
Reference in New Issue
Block a user