Files
vslam_cpp/app/src/runtime.cc
trung09122002 b4b9f7ec7c update
2026-09-20 15:26:39 +07:00

1193 lines
48 KiB
C++

#include "runtime.h"
#include <pthread.h>
#include <sched.h>
#include <chrono>
#include <cstring>
#include "vslam/clock.h"
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
#include "vslam/replay_source.h"
#include "vslam/sim_source.h"
namespace vslam {
// Giu nguon song. Mot trong hai con tro khac null; `vslam_node` chi cham vao
// cac interface, khong cham vao kieu cu the.
struct Runtime::SourceHolder {
std::unique_ptr<SimSource> sim;
std::unique_ptr<ReplaySource> replay;
// --live: bon driver roi, khong co object "LiveSource" bao chung. Co y --
// SimSource va ReplaySource ton tai vi chung phai DONG BO bon luong voi
// nhau tu mot dong ho ao. Phan cung that khong can dieu do: moi thiet bi
// tu chay tren luong rieng va tu dong dau theo dong ho he thong.
std::unique_ptr<LidarInterface> live_lidar;
std::unique_ptr<CameraInterface> live_camera;
std::unique_ptr<McuInterface> live_mcu;
std::unique_ptr<BaseInterface> live_base;
};
Runtime::Runtime(AppConfig* cfg, RuntimeOptions opts)
: cfg_(cfg), opts_(std::move(opts)), source_(new SourceHolder) {}
Runtime::~Runtime() {
RequestStop();
Join();
}
namespace {
// Tren muc nay thi canh bao rang odometry se kem chinh xac di. Lay tu PHEP DO
// chu khong tu mot nguong vat ly nao: accel 0.60 cho sai so 0.015 m, accel
// 0.86 cho 0.093 m -- dau goi nam giua hai gia tri do.
//
// Chi de CANH BAO, khong dieu khien gi.
constexpr double kFastAccelWarn = 0.7;
} // namespace
StatusResponse Runtime::OpenSource() {
switch (opts_.source) {
case SourceKind::kSim: {
SimConfig sc;
sc.map_yaml = opts_.map_yaml;
sc.world_path = opts_.world_path;
sc.start_x = opts_.sim_start_x;
sc.start_y = opts_.sim_start_y;
sc.start_yaw = opts_.sim_start_yaw;
// Hinh hoc lay tu robot.yaml, KHONG go tay. Neu sim dung mot bo so va
// duong ong dung bo khac thi moi phep do deu do nham.
const RobotGeometry& g = cfg_->robot.geometry();
sc.wheel_radius = g.wheel_radius;
sc.wheel_separation = g.wheel_separation;
sc.robot_radius = g.robot_radius;
sc.camera_z = cfg_->robot.camera_height_above_floor();
sc.camera_pitch = cfg_->robot.camera_pitch();
sc.max_linear = speed_limit_;
sc.max_angular = cfg_->robot.base().max_angular;
sc.accel_limit = accel_limit_;
sc.lidar_rate_hz = cfg_->sensors.lidar_hz;
sc.camera_rate_hz = cfg_->sensors.camera_hz;
sc.imu_rate_hz = cfg_->sensors.imu_hz;
sc.enable_depth_camera = cfg_->sensors.camera_enable;
Transform t;
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) {
sc.lidar_x = t.translation.x;
}
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) {
sc.camera_x = t.translation.x;
}
source_->sim.reset(new SimSource(sc));
const StatusResponse st = source_->sim->Open();
if (!st.ok()) return st;
if (opts_.sim_glass_at != 0.0) {
// Buc kinh chan ngang hanh lang. Phai danh dau o DA BI CHIEM, nen
// chen tuong truoc roi moi danh dau la kinh.
const double gx = opts_.sim_glass_at;
OccupancyGrid m = source_->sim->map();
const double res = m.resolution;
const int cx = static_cast<int>((gx - m.origin.position.x) / res);
for (int cy = 0; cy < static_cast<int>(m.height); ++cy) {
if (cx >= 0 && cx < static_cast<int>(m.width)) {
const size_t i = static_cast<size_t>(cy) * m.width + cx;
if (m.data[i] == 0) m.data[i] = 100; // chi lap cho TRONG
}
}
source_->sim->SetMapForTest(m);
source_->sim->SetGlass(gx - res, -50.0, gx + res, 50.0, true);
VSLAM_WARN("sim: dat buc KINH o x = " << gx
<< " m. LiDAR va depth se KHONG thay no -- chi sieu am va "
"bumper thay.");
}
// Ham lay ground truth, de `wiring.cc` chot no cung luc voi EKF.
gt_fn_ = [this]() { return source_->sim->ground_truth(); };
lidar_ = source_->sim->lidar();
camera_ = source_->sim->camera();
mcu_ = source_->sim->mcu();
base_ = source_->sim->base();
clock_ = source_->sim->clock();
return StatusResponse::Ok();
}
case SourceKind::kReplay: {
ReplayConfig rc;
rc.path = opts_.replay_path;
// KHONG tat dinh o day, khac voi `tools/vslam_replay`: node nay chay
// voi web UI va nguoi dung dang nhin, nen phat theo thoi gian that.
rc.deterministic = false;
rc.apply_sanitizer = false; // node tu ve sinh, dung CHINH mot doi tuong
source_->replay.reset(new ReplaySource(rc));
const StatusResponse st = source_->replay->Open();
if (!st.ok()) return st;
lidar_ = source_->replay->lidar();
camera_ = source_->replay->camera();
mcu_ = source_->replay->mcu();
base_ = source_->replay->base();
clock_ = source_->replay->clock();
return StatusResponse::Ok();
}
case SourceKind::kLive: {
#ifndef VSLAM_HAVE_CANOPEN
// Tu choi o day thay vi de linker bao thieu CreateDiffDriveBase: thong
// bao nay noi duoc phai LAM GI, con loi link thi khong.
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"--live can base ZLAC, ma build nay khong co CANopen. Build lai voi "
"-DVSLAM_WITH_CANOPEN=ON (can liblely-coapp). Khong co base thi "
"khong co encoder va khong dieu khien duoc motor -- day khong phai "
"thu bo qua duoc nhu camera.");
#else
// Dong ho HE THONG, khong phai dong ho ao. Day la nhanh DUY NHAT dung
// no -- sim va replay deu cap dong ho cua rieng chung, va do la thu giu
// cho ca hai tat dinh.
clock_ = MakeSystemClock();
// ⚠️ CHI DUNG, KHONG Open() O DAY.
//
// driver_interfaces.h noi ro: "Callback duoc goi tren luong RIENG cua
// driver. Dat truoc khi mo thiet bi." Cac driver that bat luong ngay
// trong Open(), con Wire() -- noi dat callback -- chay SAU ham nay.
// Mo som la de luong driver doc `cb_` trong khi luong chinh dang gan
// vao chinh no: `std::function` khong an toan da luong, va ket qua la
// segfault ngay lan chay dau tren robot.
//
// Start() da co san buoc mo thiet bi NGAY SAU Wire(). Sim va replay
// khong lo dieu nay vi chung chi day du lieu tu Run(), khong tu Open().
source_->live_base = CreateDiffDriveBase(cfg_->base_driver, clock_);
base_ = source_->live_base.get();
source_->live_lidar = CreateLakiBeamDriver(cfg_->lidar_driver, clock_);
lidar_ = source_->live_lidar.get();
source_->live_mcu = CreateMcuBridge(cfg_->mcu_driver, clock_);
mcu_ = source_->live_mcu.get();
// Camera la thu DUY NHAT duoc phep vang mat: EKF chay bang encoder +
// gyro, va safety chay bang LiDAR. Mat camera la mat phat hien vuc va
// vat can thap -- kem di that, nhung van dung duoc va van lai duoc.
// Mat LiDAR hay mat base thi khong.
#ifdef VSLAM_HAVE_REALSENSE
if (cfg_->sensors.camera_enable) {
source_->live_camera = CreateRealSenseD410(cfg_->camera_driver, clock_);
camera_ = source_->live_camera.get();
} else {
VSLAM_WARN("--live: camera bi tat trong sensors.yaml -- cliff_detect "
"va vat can thap se KHONG hoat dong");
}
#else
VSLAM_WARN("--live: build khong co -DVSLAM_WITH_REALSENSE=ON, chay KHONG "
"co camera -- cliff_detect va vat can thap se KHONG hoat dong");
#endif
return StatusResponse::Ok();
#endif // VSLAM_HAVE_CANOPEN
}
}
return StatusResponse::Error(StatusCode::kInvalidArgument, "nguon la");
}
void Runtime::ApplyThreadPriority(std::thread* t, int prio, const char* name) {
if (!cfg_->threads.use_realtime) return;
sched_param sp{};
sp.sched_priority = prio;
const int rc = pthread_setschedparam(t->native_handle(), SCHED_FIFO, &sp);
if (rc != 0) {
// KHONG tu choi khoi dong. Thieu CAP_SYS_NICE la chuyen binh thuong khi
// chay tu terminal cua nguoi phat trien; robot van chay dung, chi la
// jitter cao hon. Tu choi khoi dong o day se khien moi nguoi chay bang
// sudo, va do moi la thu nguy hiem.
VSLAM_WARN("luong " << name << ": khong dat duoc SCHED_FIFO " << prio << " ("
<< std::strerror(rc)
<< "). Chay voi uu tien mac dinh -- can CAP_SYS_NICE hoac "
"/etc/security/limits.conf.");
}
}
StatusResponse Runtime::Start() {
// Ghi de tran toc do TRUOC khi mo nguon: `OpenSource()` chep gioi han base
// sang `SimConfig`, nen sua sau do se khong toi duoc bo mo phong.
//
// Ghi de CA BA cho, vi lenh di qua ca ba:
// teleop (tran scale) -> safety (kep) -> base cua sim (kep lan nua)
// Bo sot mot cho la so tren man hinh len 2.0 con robot van chay 0.35.
if (opts_.max_speed_override > 0.0) {
const double v = opts_.max_speed_override;
VSLAM_WARN("toc do: ghi de tran len " << v
<< " m/s (robot.yaml co " << cfg_->robot.base().max_linear
<< "). ⚠️ CHI CHO MO PHONG -- base that khong chay nhanh hon "
"duoc, day chi la de quet nhanh.");
cfg_->safety.max_linear = v;
// `RobotModel` khong cho sua truc tiep (co y: no la nguon su that tu
// robot.yaml). Gia tri cho sim va teleop lay tu bien duoi day.
speed_limit_ = v;
// ⚠️ Noi tran ma khong noi GIA TOC thi tran moi khong voi toi duoc.
//
// `accel_limit` 0.30 m/s^2 can 6.7 giay va ~6.7 m duong chay de len toi
// 2 m/s. Cho rong nhat trong toa nha benh vien chi 4.75 m, nen robot
// KHONG BAO GIO cham toi toc do da dat: do duoc 0.983 m/s khi dat 2.00.
// Nguoi van hanh keo thanh truot len het roi van thay cham, va khong co
// gi giai thich.
//
// Giu nguyen ti le giua gia toc va tran, dung nhu robot that.
const double base_v = cfg_->robot.base().max_linear;
accel_limit_ = base_v > 1e-9
? cfg_->robot.base().accel_limit * (v / base_v)
: cfg_->robot.base().accel_limit;
VSLAM_WARN("toc do: gia toc cung noi theo, " << cfg_->robot.base().accel_limit
<< " -> " << accel_limit_ << " m/s^2. Khong noi thi tran "
<< v << " m/s can " << (v / cfg_->robot.base().accel_limit)
<< " s va ~" << (v * v / (2 * cfg_->robot.base().accel_limit))
<< " m duong chay -- dai hon moi cho trong toa nha.");
// ⚠️ NOI GIA TOC LAM ODOMETRY KEM CHINH XAC HON.
//
// Do duoc tren the gioi benh vien, sai so uoc luong vs ground truth khi
// lai lien tuc (SLAM bat):
// --max-speed 0.35 (accel 0.30) -> 0.026 m
// --max-speed 0.7 (accel 0.60) -> 0.015 m
// --max-speed 1.0 (accel 0.86) -> 0.093 m
// --max-speed 2.0 (accel 1.71) -> 0.118 m
//
// ⚠️ KHONG phai do truot banh. Toi da doan vay va SAI: `slip_factor` va
// `slip_differential` mac dinh bang 0, va `vslam_node` KHONG BAO GIO dat
// chung -- mo hinh truot chi duoc bat trong `vslam_record` va
// `vslam_sim_run`. Trong duong chay cua node, banh khong he truot.
//
// Nguyen nhan la sai so ROI RAC cua wheel odometry: encoder lay mau o 50
// Hz, nen o 2 m/s moi buoc di 4 cm va do cong trong buoc do bi bo qua.
//
// ⚠️ Sai so nay CO GIOI HAN, khong tich luy: do qua 170 giay lai lien tuc
// o toc do toi da, no dao dong 0.026-0.057 m va dinh 0.100 m. Ke ca khi
// dam vao vat can, hay lai giat cuc kieu tay, hay dung DB that -- van duoi
// 0.10 m. Neu thay hinh ground truth tach ra XA HON the thi do la chuyen
// khac, va o `gap` tren web se noi ro la loi du lieu hay loi ve.
if (accel_limit_ > kFastAccelWarn) {
VSLAM_WARN("toc do: chay nhanh lam wheel odometry kem chinh xac hon -- "
"encoder lay mau 50 Hz nen do cong trong moi buoc bi bo qua. "
"Do duoc: sai so vs ground truth 0.015 m o --max-speed 0.7, "
"0.118 m o 2.0 (co gioi han, khong tich luy). Quet ban do thi "
"dung 0.7.");
}
} else {
speed_limit_ = cfg_->robot.base().max_linear;
accel_limit_ = cfg_->robot.base().accel_limit;
}
{
const StatusResponse st = OpenSource();
if (!st.ok()) return st;
}
sanitizer_.reset(new ScanSanitizer(cfg_->sanitizer));
wheel_odom_.reset(new WheelOdometry(cfg_->wheel_odom));
ekf_.reset(new EkfSe2(cfg_->ekf));
safety_.reset(new SafetyMonitor(cfg_->safety));
// ============ GIEO POSE XUAT PHAT KHI CHAY MO PHONG ============
//
// Odometry luon khoi tao o GOC. Tren robot that do la dung: frame `odom` co
// goc o cho robot vua khoi dong, va SLAM keo no ve khop ban do qua
// `map->odom`.
//
// Trong mo phong thi KHAC: ban do (vd hospital.yaml) o mot he toa do CO
// DINH, va `--x --y` dat robot vao mot cho cu the trong do. Neu odometry
// van bat dau o (0,0) thi:
// * robot uoc luong ve o (0,0) -- mot phong khac han cho no dang dung;
// * ban do SLAM dung ra cung o goc (0,0), nen LECH voi ban do the gioi
// dung bang vi tri xuat phat.
// Da do: pose (0.00, 0.00) trong khi ground truth (-5.99, -2.91).
//
// Gieo pose xuat phat la tuong duong mo phong cua "robot biet no khoi dong
// o dau" -- tren phan cung that do la viec cua dock, xem --slam-init-pose.
if (opts_.source == SourceKind::kSim &&
(opts_.sim_start_x != 0.0 || opts_.sim_start_y != 0.0 ||
opts_.sim_start_yaw != 0.0)) {
Pose2D start;
start.x = opts_.sim_start_x;
start.y = opts_.sim_start_y;
start.theta = opts_.sim_start_yaw;
wheel_odom_->SetPose(start);
ekf_->SetPose(start);
VSLAM_INFO("sim: gieo pose xuat phat (" << start.x << ", " << start.y << ", "
<< start.theta << ") vao odometry va EKF -- de uoc luong nam "
"dung cho tren ban do the gioi.");
}
// Gioi han tren cua scale teleop lay tu robot.yaml: nguoi lai khong duoc
// chinh len qua gioi han co hoc cua base. Lop safety van kep lan nua --
// hai lop, co y.
TeleopConfig tc;
tc.max_linear_speed = speed_limit_;
tc.max_angular_speed = cfg_->robot.base().max_angular;
teleop_.reset(new TeleopModel(tc));
perception_.reset(new PerceptionPipeline(cfg_->perception, *clock_));
{
Transform cam_to_base;
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraDepthOpticalFrame,
&cam_to_base)) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"robot.yaml: khong co duong camera_depth_optical_frame -> base_link");
}
perception_->SetCameraExtrinsic(cam_to_base);
}
#ifdef VSLAM_HAVE_SLAM
if (cfg_->slam.enabled || opts_.force_slam) {
RtabmapConfig sc = cfg_->slam;
if (opts_.have_slam_db) sc.database_path = opts_.slam_db;
if (opts_.slam_mode_override == "mapping") sc.mode = SlamMode::kMapping;
else if (opts_.slam_mode_override == "localization") sc.mode = SlamMode::kLocalization;
slam_.reset(new RtabmapSlam);
const StatusResponse st = slam_->Init(sc);
if (!st.ok()) {
// KHONG chay tiep im lang. Nguoi van hanh bat SLAM len va phai biet no
// khong len duoc -- chay tiep ma khong co SLAM trong khi ho tuong co la
// dung kieu hong `--sim` mac dinh sinh ra de tranh.
return StatusResponse::Error(st.code, "slam: " + st.message);
}
slam_enabled_ = true;
slam_mode_ = sc.mode;
// Chi LUU o che do mapping va khi co duong dan that.
//
// ⚠️ `RtabmapSlam::~RtabmapSlam()` goi `Close(false)` -- VUT BO ban do.
// Khong goi Close(true) tuong minh thi mot phien quet dai xong se khong
// de lai gi, va khong co loi nao: file .db van ton tai, chi la trong.
//
// O che do localization thi KHONG luu: ghi phien dinh vi vao ban do da
// quet se lam ban do phinh dan moi lan chay, va khong ai co y do do.
slam_should_save_ =
(sc.mode == SlamMode::kMapping) && !sc.database_path.empty();
if (slam_should_save_) {
VSLAM_INFO("slam: che do mapping, se LUU vao " << sc.database_path
<< " khi thoat (Ctrl-C).");
} else if (sc.mode == SlamMode::kMapping) {
VSLAM_WARN("slam: che do mapping nhung database_path de RONG -- ban do "
"chi nam trong RAM va se MAT khi thoat. Dat --slam-db PATH "
"de luu.");
}
// --- Pose ban dau cho localization ---
//
// ⚠️ RTAB-Map KHONG dinh vi toan cuc duoc bang scan khong. Vong dong toan
// cuc di qua tui tu thi giac; `RGBD/ProximityBySpace` chi tim trong mot
// ban kinh quanh uoc luong HIEN TAI. Va o che do localization no khoi
// dong tu pose CUOI CUNG cua phien quet, khong phai tu goc.
//
// Khong dat pose ban dau thi robot vat ly o (0,0) con RTAB-Map tuong no o
// cuoi quy dao da quet. Do duoc: sai so 1.08 m, va `localized` VAN bao
// true -- mot kieu hong trong y het "dang chay tot".
//
// He that giai quyet dung nhu vay: `dock_init.py` phat /initialpose tu
// dock. Robot LUON biet no bat dau o dau.
// Ca MAPPING lan LOCALIZATION deu can pose ban dau khi chay mo phong tren
// mot ban do co san.
//
// Mapping: RTAB-Map dung ban do trong frame rieng, goc o pose ban dau. De
// no o (0,0) trong khi robot dang o (-5.99, -2.91) thi ban do SLAM LECH
// voi ban do the gioi dung bang vi tri xuat phat -- hai khung o che do
// "chia doi" khong con chong khop duoc.
if (sc.mode == SlamMode::kLocalization || opts_.have_slam_init_pose ||
opts_.source == SourceKind::kSim) {
Pose2D init;
const char* src = nullptr;
if (opts_.have_slam_init_pose) {
init = opts_.slam_init_pose;
src = "--slam-init-pose";
} else if (opts_.source == SourceKind::kSim) {
// Trong mo phong, "dock" la vi tri xuat phat. Noi RO day la mot
// tien nghi cua mo phong, khong phai thu robot that co mien phi.
init.x = opts_.sim_start_x;
init.y = opts_.sim_start_y;
init.theta = opts_.sim_start_yaw;
src = "vi tri xuat phat cua mo phong (thay cho dock)";
}
if (src != nullptr) {
slam_->SetInitialPose(init);
VSLAM_INFO("slam: pose ban dau (" << init.x << ", " << init.y << ", "
<< init.theta << ") tu " << src);
} else {
VSLAM_WARN("slam: che do localization nhung KHONG co pose ban dau. "
"RTAB-Map khong dinh vi toan cuc duoc bang scan khong -- "
"no se khoi dong tu pose CUOI cua phien quet va gan nhu "
"chac chan sai. Dung --slam-init-pose x,y,yaw.");
}
}
Transform laser_to_base = TransformIdentity();
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &laser_to_base)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml: khong co duong laser -> base_link");
}
// Quen cai nay la moi scan bi dat lech 24 cm so voi pose. ICP van hoi tu
// (no chi thay ca the gioi dich di) nhung do thi tich luy sai so: da do
// ATE 0.2378 m thay vi 0.0146 m tren map_house.db, khong mot loi nao.
Transform cam_to_base = TransformIdentity();
cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraDepthOpticalFrame, &cam_to_base);
slam_->SetExtrinsics(laser_to_base, cam_to_base);
}
#else
if (opts_.force_slam) {
return StatusResponse::Error(
StatusCode::kUnavailable,
"--slam: binary nay build KHONG kem vslam_slam. Build lai voi "
"-DVSLAM_BUILD_SLAM=ON.");
}
#endif
{
const StatusResponse st = Wire();
if (!st.ok()) return st;
}
// Mo thiet bi SAU Wire(), vi Wire() la noi dat callback va driver that bat
// luong ngay trong Open() -- xem ghi chu o nhanh kLive cua OpenSource().
//
// Base TRUOC: no la thu duy nhat lam robot DI CHUYEN. Mo cam bien truoc roi
// that bai o base nghia la co mot node dang chay, co web UI, co du lieu --
// va khong co cach nao dung xe.
//
// Loi o day KHONG duoc bo qua. Truoc day ba dong nay vut gia tri tra ve, va
// voi sim/replay thi vo hai (Open() la no-op). Voi phan cung that thi
// "khong mo duoc base" ma van chay tiep la kieu hong te nhat.
if (base_ != nullptr) {
const StatusResponse st = base_->Open();
if (!st.ok()) return StatusResponse::Error(st.code, "base: " + st.message);
}
if (lidar_ != nullptr) {
const StatusResponse st = lidar_->Open();
if (!st.ok()) return StatusResponse::Error(st.code, "lidar: " + st.message);
}
if (mcu_ != nullptr) {
const StatusResponse st = mcu_->Open();
if (!st.ok()) return StatusResponse::Error(st.code, "mcu: " + st.message);
}
// Camera la ngoai le co y: mat no thi mat cliff_detect va vat can thap,
// nhung EKF van chay bang encoder + gyro va safety van chay bang LiDAR.
if (camera_ != nullptr) {
const StatusResponse st = camera_->Open();
if (!st.ok()) {
VSLAM_WARN("camera khong mo duoc, chay TIEP khong co camera: "
<< st.message
<< " -- cliff_detect va vat can thap se KHONG hoat dong");
camera_ = nullptr;
}
}
// Hinh hoc 3D cua the gioi -- chi co khi chay tu file `.world`.
//
// Dung mesh HIEN THI chu khong phai mesh va cham: khung 3D de nguoi van hanh
// NHAN RA cho dung, va mesh va cham cua bo model nay la khoi hop tho. 6.7 MB
// tho (~1.4 MB sau nen) tai MOT lan luc mo trang.
if (source_->sim != nullptr && !opts_.world_path.empty()) {
WorldMeshes wm;
const StatusResponse st = ExportWorldMeshes(source_->sim->world(),
/*visual=*/true, &wm);
if (st.ok()) {
const size_t n_col = ApplyModelColors(ResourcePath("model_colors.json"),
&wm);
std::string blob;
EncodeWorldMeshes(wm, &blob);
VSLAM_INFO("web: hinh hoc 3D " << wm.geoms.size() << " hinh hoc ("
<< n_col << " co mau), " << wm.instances.size()
<< " the hien, " << (blob.size() / 1048576.0) << " MB");
web_->SetWorldMesh(std::move(blob));
} else {
VSLAM_WARN("web: khong xuat duoc hinh hoc 3D (" << st.message
<< ") -- khung 3D se dung khoi hop dung tu luoi");
}
}
{
const StatusResponse st = web_->Start();
if (!st.ok()) return st;
}
// --- Luong ---
source_thread_ = std::thread([this] {
if (source_->sim) source_->sim->Run();
else if (source_->replay) {
source_->replay->Run();
// Ban ghi het la mot su kien, khong phai mot trang thai im lang. Khong
// noi ra thi no giong het "replay bi treo o khung cuoi".
const ReplaySource::Stats st = source_->replay->stats();
VSLAM_INFO("replay: het ban ghi -- " << st.chunks << " chunk trong "
<< st.duration_sec << " s"
<< (st.truncated ? " (FILE BI CAT GIUA CHUNG)" : "")
<< ". Node van chay; Ctrl-C de dung.");
}
});
ApplyThreadPriority(&source_thread_, cfg_->threads.driver_priority, "source");
safety_thread_ = std::thread([this] { SafetyLoop(); });
ApplyThreadPriority(&safety_thread_, cfg_->threads.safety_priority, "safety");
if (slam_enabled_) {
slam_thread_ = std::thread([this] { SlamLoop(); });
// CFS, KHONG realtime. Luong nay chan hang tram ms; cho no uu tien cao la
// cach chac chan nhat de treo vong an toan.
}
web_thread_ = std::thread([this] { WebLoop(); });
// web_tx chay CFS: no khong o trong vong an toan, va nang no len se lay mat
// CPU cua luong dang giu robot khong dam vao tuong.
return StatusResponse::Ok();
}
void Runtime::RequestStop() {
stop_.store(true);
if (source_->sim) source_->sim->RequestStop();
if (source_->replay) source_->replay->RequestStop();
}
void Runtime::Join() {
if (safety_thread_.joinable()) safety_thread_.join();
if (web_thread_.joinable()) web_thread_.join();
if (slam_thread_.joinable()) slam_thread_.join();
if (source_thread_.joinable()) source_thread_.join();
// Dung base TRUOC khi dong web: neu dong web truoc thi trong khoang giua,
// khong con ai gui lenh nhung robot van con van toc cuoi cung.
if (base_ != nullptr) base_->SetVelocity(0.0, 0.0);
#ifdef VSLAM_HAVE_SLAM
if (slam_) {
const StatusResponse st = slam_->Close(slam_should_save_);
if (!st.ok()) {
VSLAM_ERROR("slam: dong that bai: " << st.message);
} else if (slam_should_save_) {
VSLAM_INFO("slam: da luu ban do.");
}
}
#endif
if (web_) web_->Stop();
// ⚠️ DONG THIET BI O DAY, truoc khi ham nay tra ve.
//
// Driver that chay luong RIENG va goi callback vao ekf_, safety_, web_...
// Nhung `source_` (chu so huu driver) duoc khai bao TRUOC cac stage trong
// runtime.h, ma C++ huy thanh vien theo thu tu NGUOC -- tuc stage chet
// truoc, driver chet sau. Trong khoang do luong driver van dang goi vao bo
// nho vua duoc giai phong.
//
// Da xay ra that tren robot: `malloc(): unsorted double linked list
// corrupted` moi lan Ctrl-C.
//
// Sim va replay khong lo dieu nay vi RequestStop() dung vong Run() cua
// chung truoc; driver that khong co vong Run() nao de dung.
if (camera_ != nullptr) camera_->Close();
if (mcu_ != nullptr) mcu_->Close();
if (lidar_ != nullptr) lidar_->Close();
// Base DONG CUOI: SetVelocity(0) o tren vua gui lenh dung, va Close() cua
// no con tat power stage. Dong no truoc cac driver kia khong sai, nhung de
// cuoi thi cua so "da dung nhung chua tat dien" ngan nhat.
if (base_ != nullptr) base_->Close();
}
// Do do lech giua dam may camera va scan LiDAR. Xem khai bao o runtime.h.
//
// ============ CACH DO ============
// Ca hai cam bien nhin cung mot buc tuong. Quy ca hai ve he BASE roi so ban
// kinh theo tung huong:
//
// Neu camera bi dat lech mot doan (dx, dy) so voi thuc te thi moi tia deu
// lech mot luong PHU THUOC HUONG:
// dr(theta) = -(dx*cos(theta) + dy*sin(theta))
//
// Khop binh phuong toi thieu dr theo cos va sin cho ra thang dx, dy -- tuc
// chinh so can sua trong robot.yaml. Mot do lech DEU theo moi huong thi la
// sai ti le range (depth_scale), khong phai sai vi tri.
//
// Chi lay diem cloud o GAN DO CAO cua mat phang quet LiDAR: tuong thang dung
// thi hai cam bien moi thay cung mot khoang cach.
void Runtime::ReportCloudScanAlign(const PointCloudXYZ& cloud) {
LaserScanPtr scan;
{
std::lock_guard<std::mutex> lk(scan_mu_);
scan = latest_scan_;
}
if (!scan || scan->ranges.empty() || cloud.points.empty()) return;
Transform laser_tf;
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &laser_tf)) return;
const double lx = laser_tf.translation.x;
const double ly = laser_tf.translation.y;
const double lz = laser_tf.translation.z;
constexpr int kBins = 180; // 2 do moi o
constexpr double kSlab = 0.06; // +-6 cm quanh mat phang quet
std::vector<double> r_cam(kBins, 0.0), r_lid(kBins, 0.0);
std::vector<int> n_cam(kBins, 0), n_lid(kBins, 0);
auto bin_of = [](double th) {
int b = static_cast<int>((th + M_PI) / (2.0 * M_PI) * kBins);
return (b < 0) ? 0 : (b >= kBins ? kBins - 1 : b);
};
for (const PointXYZ& p : cloud.points) {
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
if (std::fabs(p.z - lz) > kSlab) continue;
const double r = std::hypot(p.x, p.y);
if (r < 0.2 || r > 8.0) continue;
const int b = bin_of(std::atan2(p.y, p.x));
r_cam[b] += r;
n_cam[b]++;
}
for (size_t i = 0; i < scan->ranges.size(); ++i) {
const float rr = scan->ranges[i];
if (!std::isfinite(rr) || rr <= 0.0f) continue;
const double a = scan->angle_min + static_cast<double>(i) * scan->angle_increment;
// Tia o frame LASER -> diem o frame BASE.
const double x = lx + rr * std::cos(a);
const double y = ly + rr * std::sin(a);
const double r = std::hypot(x, y);
if (r < 0.2 || r > 8.0) continue;
const int b = bin_of(std::atan2(y, x));
r_lid[b] += r;
n_lid[b]++;
}
// Khop dr = a*cos + b*sin tren nhung o CA HAI ben deu co du lieu.
double saa = 0, sab = 0, sbb = 0, sad = 0, sbd = 0;
int used = 0;
double sum_d = 0.0;
for (int b = 0; b < kBins; ++b) {
if (n_cam[b] < 3 || n_lid[b] < 1) continue;
const double th = -M_PI + (b + 0.5) * (2.0 * M_PI / kBins);
const double d = r_cam[b] / n_cam[b] - r_lid[b] / n_lid[b];
if (std::fabs(d) > 1.0) continue; // khac qua nhieu -> hai ben nhin hai vat
const double ca = std::cos(th), sa = std::sin(th);
saa += ca * ca; sab += ca * sa; sbb += sa * sa;
sad += ca * d; sbd += sa * d;
sum_d += d;
used++;
}
if (used < 8) {
VSLAM_INFO_THROTTLE(10.0,
"align: chi " << used << " huong co ca cloud lan scan -- chua du de do. "
"Dua robot doi dien mot buc tuong phang, cach 1-3 m.");
return;
}
const double det = saa * sbb - sab * sab;
if (std::fabs(det) < 1e-9) return;
const double a_fit = (sad * sbb - sbd * sab) / det;
const double b_fit = (sbd * saa - sad * sab) / det;
const double mean_d = sum_d / used;
VSLAM_INFO_THROTTLE(10.0,
"align: cloud vs scan tren " << used << " huong, lech trung binh "
<< mean_d << " m.\n"
" Khop dr = a*cos + b*sin -> a=" << a_fit << " b=" << b_fit << "\n"
" => camera_link dang lech dx=" << -a_fit << " m, dy=" << -b_fit << " m\n"
" => thu xyz: [" << (0.0 - a_fit) << ", " << (0.0 - b_fit)
<< ", <giu nguyen>] cong voi gia tri hien tai trong robot.yaml\n"
" (lech DEU moi huong, a~b~0 ma mean lon => sai ti le range, khong phai vi tri)");
}
void Runtime::SafetyLoop() {
// Chu ky theo STEADY CLOCK, khong theo UnixTime.
//
// `safety_monitor_node.cpp` cua ban ROS dung ros::Time::now() cho ca dau
// thoi gian lan chu ky. Mot buoc NTP sau khi Jetson bat WiFi lam
// (now - last_cmd_time) nhay vot -> NO_CMD dung robot dot ngot, hoac nhay
// lui -> watchdog khong bao gio kich.
const auto period = std::chrono::duration<double>(
cfg_->threads.safety_rate_hz > 0.0 ? 1.0 / cfg_->threads.safety_rate_hz : 0.05);
auto next = std::chrono::steady_clock::now();
while (!stop_.load()) {
SafetyInputs si;
si.now = clock_->Now();
Twist cmd_copy;
{
std::lock_guard<std::mutex> lk(cmd_mu_);
if (have_raw_cmd_) {
cmd_copy = raw_cmd_;
si.cmd = &cmd_copy;
si.cmd_stamp = raw_cmd_stamp_;
}
}
LaserScanPtr scan_copy;
{
std::lock_guard<std::mutex> lk(scan_mu_);
scan_copy = latest_scan_;
}
if (scan_copy) {
si.scan = scan_copy.get();
si.scan_stamp = scan_copy->header.stamp;
}
{
std::lock_guard<std::mutex> lk(mcu_mu_);
if (have_us_) {
si.ultrasonic = ultrasonic_;
si.us_stamp = us_stamp_;
}
if (have_bumper_) {
si.have_bumper = true;
si.bumper = bumper_;
si.bumper_stamp = bumper_stamp_;
}
}
{
std::lock_guard<std::mutex> lk(perc_mu_);
if (have_cliff_) {
si.have_cliff = true;
si.cliff = cliff_flag_;
si.cliff_stamp = cliff_stamp_;
// "judged" = detector THUC SU phan xet duoc; con lai la fail-safe
// luc mu. FSM xu ly hai truong hop nay khac nhau -- xem nhanh 4.
si.cliff_judged = (cliff_detail_ == "judged");
si.cliff_window_min = cfg_->perception.cliff.min_dist;
}
}
SafetyOutput so;
{
std::lock_guard<std::mutex> lk(safety_mu_);
so = safety_->Step(si);
last_safety_ = so;
}
// DUONG DUY NHAT lenh toi duoc base. Khong co nhanh nao cho lenh di thang
// xuong, ke ca teleop, ke ca e-stop.
if (base_ != nullptr) base_->SetVelocity(so.cmd.linear.x, so.cmd.angular.z);
next += std::chrono::duration_cast<std::chrono::steady_clock::duration>(period);
std::this_thread::sleep_until(next);
}
if (base_ != nullptr) base_->SetVelocity(0.0, 0.0);
}
void Runtime::SlamLoop() {
#ifdef VSLAM_HAVE_SLAM
// ============ QUY TAC SONG CON ============
// `Rtabmap::process()` chan 100-600 ms (p95 do duoc 722-1008 ms tren may
// dev). Vong nay KHONG duoc giu bat ky mutex nao trong luc goi no.
//
// Cach lam: copy dau vao duoi mutex (mot shared_ptr + mot Pose2D, vai chuc
// nano giay), NHA, roi moi goi. Luong safety doc cung nhung mutex do va vi
// the khong bao gio cho qua mot phep copy con tro.
//
// Trong ban ROS dieu nay duoc bao dam MIEN PHI boi tien trinh rieng. O day
// no la quy tac review, va ThreadSanitizer la thu duy nhat kiem duoc.
UnixTime last_used;
bool have_last = false;
// Chi phi lan xuat ban do gan nhat (trung binh truot). Dung de nhip theo
// TAI THAT chu khong theo mot hang so -- xem khoi ben duoi.
double map_export_cost_s_ = 0.0;
constexpr double kMapExportDuty = 0.25; // toi da 25% luong slam
auto last_map_build = std::chrono::steady_clock::time_point{};
while (!stop_.load()) {
// --- Lay dau vao, KHONG giu lock lau ---
LaserScanPtr scan;
{
std::lock_guard<std::mutex> lk(scan_mu_);
scan = latest_scan_; // chi copy shared_ptr
}
Pose2D odom;
bool have_odom = false;
{
std::lock_guard<std::mutex> lk(odom_mu_);
// ⚠️ Dua cho SLAM pose cua EKF, KHONG phai cua wheel_odom.
//
// `map_correction` ma RTAB-Map tra ve la phep bien doi
// `map <- frame_cua_odometry_ma_no_nhan`. Web ghep phep do voi
// `ekf_->pose()`. Nen neu o day dua `wheel_odom_->pose()` thi hai ve
// cua phep ghep nam o HAI KHUNG khac nhau, va ket qua sai dung bang
// chenh lech giua chung.
//
// Do duoc o 0.7 m/s: wheel odom lech 0.000 m so voi ground truth, EKF
// mot minh lech 0.009 m, nhung `map_correction x ekf_pose` lech
// 0.090 m -- SLAM lam TE HON 10 lan thay vi tot hon.
//
// Ban ROS1 khong gap loi nay vi ROS khong cho ghep tay: EKF phat
// `odom -> base_link`, rtabmap doc chinh canh do qua TF, va cay TF bat
// buoc hai ve cung khung. O day toi ghep tay hai nguon nen mat rang
// buoc do -- dung lop bug ma quy tac "mot writer cho mot canh TF" sinh
// ra de chan.
odom = ekf_->pose();
have_odom = have_odom_;
}
if (!scan || !have_odom ||
(have_last && scan->header.stamp.toSec() <= last_used.toSec())) {
// Chua co scan MOI. Ngu ngan roi thu lai -- khong ban chay vong.
std::this_thread::sleep_for(std::chrono::milliseconds(20));
continue;
}
last_used = scan->header.stamp;
have_last = true;
SlamInput in;
in.stamp = scan->header.stamp;
in.odom = odom;
in.scan = scan.get();
// --- KHONG MOT MUTEX NAO duoc giu qua dong nay ---
const SlamOutput out = slam_->Process(in);
bool need_map = false;
{
std::lock_guard<std::mutex> lk(slam_mu_);
map_correction_ = out.map_correction;
{
// Do lon cua phep nan, de dong log gop ben duoi dung. Voi odometry
// tot thi con so nay phai NHO va ON DINH -- tang deu nghia la SLAM
// dang troi chu khong dang nan.
mc_now_ = std::hypot(out.map_correction.x, out.map_correction.y);
mc_deg_ = out.map_correction.theta * 180.0 / M_PI;
}
slam_localized_ = out.localized;
slam_process_ms_ = out.process_ms;
if (out.loop_closure_id > 0) slam_loops_++;
slam_prox_id_ = out.proximity_id;
if (out.proximity_id > 0) slam_prox_total_++;
need_map = out.map_version != slam_map_version_;
slam_map_version_ = out.map_version;
}
// Xuat ban do CHI khi do thi doi, VA khong qua `map_rebuild_rate_hz`.
//
// Chi kiem "do thi doi" la khong du: o che do mapping do thi doi o gan
// nhu MOI khung, nen SlamLoop se dung lai ban do ~9 lan/giay. Da do
// trong mo phong. `OccupancyGrid::update()` quet lai toan bo cache moi
// lan (5.65 s cho 1990 node tren map_hospital.db), va tren ban do that
// 2000x2000 thi 9 lan/giay la 221 kB/s -- gan gap doi ca ngan sach
// 120 kB/s cua toan bo web UI.
//
// ============ NHIP THEO CHI PHI DO DUOC, KHONG THEO HANG SO ============
//
// Mot tan so co dinh sai o CA HAI dau:
// * 0.5 Hz (ban truoc): do thi con nho, xuat het 20 ms, ma van bat nguoi
// dung doi 2 giay moi lan -- khung SLAM trong nhu treo dung luc ho
// muon nhin no day dan.
// * 2 Hz co dinh: khi do thi len 1990 node thi `OccupancyGrid::update()`
// mat 5.65 s, va luong slam khong con lam gi khac duoc.
//
// Nen nhip theo CHI PHI THAT: sau moi lan xuat, cho
// nghi = thoi_gian_xuat * (1/duty - 1)
// de viec dung ban do khong chiem qua `duty` phan luong slam. Do thi nho
// -> gan nhu realtime; do thi lon -> tu dong lui ra.
//
// `map_rebuild_rate_hz` gio la TRAN, khong phai tan so co dinh.
const auto now_wall = std::chrono::steady_clock::now();
if (need_map) {
const double since =
std::chrono::duration<double>(now_wall - last_map_build).count();
double wait = map_export_cost_s_ * (1.0 / kMapExportDuty - 1.0);
if (cfg_->slam_runtime.map_rebuild_rate_hz > 0.0) {
wait = std::max(wait, 1.0 / cfg_->slam_runtime.map_rebuild_rate_hz);
}
if (since < wait) need_map = false;
}
if (need_map) {
last_map_build = now_wall;
OccupancyGrid grid;
const auto t_export = std::chrono::steady_clock::now();
const StatusResponse st = slam_->ExportMap(&grid);
const double cost =
std::chrono::duration<double>(std::chrono::steady_clock::now() - t_export)
.count();
// Trung binh truot: mot lan xuat cham bat thuong khong duoc lam nhip
// giat cuc, va chi phi that thi tang dan chu khong nhay.
map_export_cost_s_ = 0.7 * map_export_cost_s_ + 0.3 * cost;
if (st.ok()) {
// Dem NOI DUNG ban do, khong dem so lan xuat.
//
// Mot ban do TOAN O CHUA BIET co dung moi chi so van hanh voi mot ban
// do dung: `ExportMap` tra ve ok, `map_version` tang deu, khung gui di
// dung kich thuoc. Da mat nhieu lan do de tim ra `RGBD/CreateOccupancy
// Grid` mac dinh la false, vi khong co gi dem noi dung ca.
//
// Ba con so nay noi ngay dieu do: 0 o trong nghia la tia khong duoc
// truy (`Grid/RayTracing`), 0 o bi chiem nghia la khong co cam bien
// nao nap vao (`Grid/Sensor`), va ca hai bang 0 nghia la ban do rong.
size_t occ = 0, fre = 0, unk = 0;
for (int8_t v : grid.data) {
if (v < 0) unk++;
else if (v >= 50) occ++;
else fre++;
}
if (occ != last_map_occ_ || fre != last_map_free_) {
VSLAM_INFO("slam: ban do " << grid.width << "x" << grid.height
<< " -- " << occ << " bi chiem, " << fre << " trong, "
<< unk << " chua biet");
last_map_occ_ = occ;
last_map_free_ = fre;
}
auto ptr = std::make_shared<const OccupancyGrid>(std::move(grid));
std::lock_guard<std::mutex> lk(slam_mu_);
slam_map_ = ptr;
slam_published_version_ = slam_map_version_;
}
// Loi o day khong phai chuyen la: do thi co the chua co pose toi uu nao
// o nhung khung dau. Khong log moi lan de khong lap day log.
}
}
#endif
}
void Runtime::WebLoop() {
const auto period = std::chrono::duration<double>(
cfg_->web.state_hz > 0.0 ? 1.0 / cfg_->web.state_hz : 0.1);
auto next = std::chrono::steady_clock::now();
OccupancyGridPtr map_ptr;
if (source_->sim) {
map_ptr = std::make_shared<const OccupancyGrid>(source_->sim->map());
}
// Hinh hoc robot cho trinh ve 3D. Dung MOT lan -- `robot.yaml` khong doi
// luc chay, va dung lai moi khung la 10 lan/giay lang phi.
//
// ⚠️ Moi so o day lay tu `RobotModel`, KHONG go tay. Truoc khoi nay app.js
// hardcode `L = 0.30, W = 0.17` -- khong khop voi bat ky gia tri nao trong
// robot.yaml, va khong ai phat hien vi mot tam giac sai kich thuoc van
// trong "nhu that".
RobotShape shape;
{
const RobotGeometry& g = cfg_->robot.geometry();
shape.radius = g.robot_radius;
shape.wheel_radius = g.wheel_radius;
shape.wheel_separation = g.wheel_separation;
shape.body_half_width = g.body_half_width;
shape.body_length = g.body_length;
shape.body_width = g.body_width;
shape.body_height = g.body_height;
shape.body_offset_x = g.body_offset_x;
shape.ground_clearance = g.ground_clearance;
Transform t;
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) {
shape.laser_x = t.translation.x;
shape.laser_y = t.translation.y;
shape.laser_z = t.translation.z;
}
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) {
shape.camera_x = t.translation.x;
shape.camera_y = t.translation.y;
shape.camera_z = t.translation.z;
}
shape.camera_pitch = cfg_->robot.camera_pitch();
shape.cliff_min = cfg_->perception.cliff.min_dist;
shape.cliff_max = cfg_->perception.cliff.max_dist;
shape.valid = true;
// `camera_hfov`/`vfov` giu mac dinh D410 cho toi khi co CameraInfo THAT:
// chung la thong so ONG KINH, khong suy ra duoc tu robot.yaml. Cap nhat
// trong vong lap khi khung dau tien toi.
}
while (!stop_.load()) {
WebSnapshot snap;
snap.robot = shape;
snap.stamp = clock_->Now();
Pose2D ekf_pose;
Pose2D gt_latched;
bool have_gt_latched = false;
{
std::lock_guard<std::mutex> lk(odom_mu_);
snap.pose_odom = wheel_odom_->pose();
snap.slip_metric = wheel_odom_->slip_metric();
if (have_odom_) {
snap.vx = latest_odom_.twist.twist.linear.x;
snap.vyaw = latest_odom_.twist.twist.angular.z;
}
snap.pose_odom = wheel_odom_->pose();
ekf_pose = ekf_->pose();
gt_latched = gt_at_ekf_;
have_gt_latched = have_gt_at_ekf_;
}
{
std::lock_guard<std::mutex> lk(scan_mu_);
snap.scan = latest_scan_;
}
{
std::lock_guard<std::mutex> lk(perc_mu_);
snap.cloud = latest_cloud_;
// So do CU khong duoc hien nhu so do MOI.
//
// Da mac: khi ban ghi phat het, `cliff_flag_` ket lai o gia tri cuoi va
// web hien "VUC PHIA TRUOC" mai mai tu mot so do da 10 giay tuoi -- ke
// ca khi FSM da bo qua no tu lau (cliff_timeout). Dung CHINH nguong ma
// FSM dung, neu khong thi web va FSM noi hai chuyen khac nhau.
const bool fresh =
have_cliff_ &&
SecondsBetween(snap.stamp, cliff_stamp_) <= cfg_->safety.cliff_timeout;
snap.safety.cliff = fresh && cliff_flag_;
if (!fresh) {
snap.safety.detail = "cliff:stale";
} else if (!cliff_detail_.empty() && cliff_detail_ != "judged") {
snap.safety.detail = "cliff:" + cliff_detail_;
}
}
// Doc tu atomic, KHONG goi thang vao GravityAlign: doi tuong do thuoc ve
// luong source va dang duoc ghi o 200 Hz. Xem ghi chu o runtime.h.
snap.roll = tilt_roll_.load(std::memory_order_relaxed);
snap.pitch = tilt_pitch_.load(std::memory_order_relaxed);
snap.accel_ok = tilt_accel_ok_.load(std::memory_order_relaxed);
{
std::lock_guard<std::mutex> lk(safety_mu_);
snap.safety.state = SafetyStateName(last_safety_.state);
if (snap.safety.detail.empty()) snap.safety.detail = last_safety_.detail;
snap.safety.min_front = last_safety_.min_front;
snap.safety.front_rays = last_safety_.front_rays;
snap.safety.front_blanked = last_safety_.front_blanked;
snap.safety.front_usable = last_safety_.front_usable;
snap.safety.estop = estop_.load();
}
// Ground truth, CHI khi mo phong. Di THANG tu nguon len web -- khong
// stage nao duoc doc no, do la ca dieu kien de no dung lam thuoc do.
if (source_->sim) {
snap.have_ground_truth = true;
// ⚠️ Dung ban CHOT cung luc voi EKF, khong doc tuoi.
//
// Doc tuoi roi dem voi `ekf_pose` (cu hon mot chu ky cam bien) bien do
// TRE thanh "sai so dinh vi": do duoc 0.118 m o 2 m/s va 0.0000 m khi
// dung yen -- ti le thang voi van toc, dung chu ky cua do tre chu khong
// phai cua sai so.
snap.ground_truth = have_gt_latched ? gt_latched
: source_->sim->ground_truth();
source_->sim->true_tilt(&snap.gt_roll, &snap.gt_pitch);
}
// pose_map = map_correction * pose_odom.
//
// Khong co SLAM thi map_correction la dong nhat, tuc map == odom -- va
// noi ro dieu do tren web (`slam.mode = "off"`) thay vi de nguoi xem
// tuong dang nhin mot pose da duoc SLAM sua.
{
std::lock_guard<std::mutex> lk(slam_mu_);
if (slam_map_version_ > 0) {
snap.pose_map = Pose2DCompose(map_correction_, ekf_pose);
snap.slam.localized = slam_localized_;
snap.slam.map_version = static_cast<uint32_t>(slam_published_version_);
snap.slam.proximity_id = slam_prox_id_;
snap.slam.proximity_total = slam_prox_total_;
snap.slam.process_ms = slam_process_ms_;
#ifdef VSLAM_HAVE_SLAM
snap.slam.mode = SlamModeName(slam_mode_);
#endif
if (slam_map_) snap.map = slam_map_;
} else {
snap.pose_map = ekf_pose;
snap.slam.mode = slam_enabled_ ? "dang cho" : "off";
}
}
// ⚠️ Quy dao phai lay SAU khi `pose_map` da duoc tinh.
//
// Khoi nay truoc day nam TRUOC phep tinh pose_map, nen no doc mot
// `snap.pose_map` vua moi khoi tao mac dinh -- tuc la (0, 0, 0). Lan dau
// no day goc toa do vao quy dao, va tu do `Distance2D(back, (0,0)) == 0`
// nen khong bao gio them diem nao nua.
//
// Hau qua: lop `duong di` chi la MOT diem dung yen o goc the gioi, trong
// khi robot chay di cho khac. Khong mot loi nao: khung PATH van gui dung
// nhip, chi la no luon mang dung 1 diem (28 byte).
// ⚠️ Ghi dinh ky SAI SO vs ground truth vao log.
//
// Cau hoi "hinh xanh la lech that hay lech do ve" da mat nhieu luot trao
// doi, vi no chi tra loi duoc bang MOT con so ma con so do truoc day chi
// hien thoang qua tren man hinh. Gio no nam trong log, nen mot file
// `tee` la du de tra loi.
//
// `err` tinh o server tu `pose_map` va `ground_truth`. Neu no nho ma
// nguoi dung van thay hai hinh tach xa thi loi nam o tang HIEN THI, khong
// o uoc luong.
if (snap.have_ground_truth) {
const double err = Distance2D(snap.pose_map, snap.ground_truth);
if (err > gt_err_max_) gt_err_max_ = err;
// ⚠️ Nhip theo dong ho TUONG (`steady_clock`), khong theo dong ho mo
// phong. Ban truoc dung `snap.stamp` -- thoi gian SIM -- nen dong nay
// chi ra 2 lan trong 32 giay thuc thay vi 6, va nguoi van hanh bao
// "khong thay dong nao".
const auto now = std::chrono::steady_clock::now();
if (gt_log_next_ == std::chrono::steady_clock::time_point{}) {
gt_log_next_ = now + std::chrono::seconds(5);
} else if (now >= gt_log_next_) {
gt_log_next_ = now + std::chrono::seconds(5);
// MOT dong, ca hai con so. Tach lam hai dong thi chung nam cach nhau
// hang chuc dong khac va rat de troi mat.
VSLAM_INFO("CHECK sai so vs ground truth " << err << " m (lon nhat "
<< gt_err_max_ << ") map_correction " << mc_now_ << " m / "
<< mc_deg_ << " do ke can " << slam_prox_total_
<< " -- hai so dau phai NHO va ON DINH");
gt_err_max_ = 0.0;
}
}
{
std::lock_guard<std::mutex> lk(traj_mu_);
// Thua hoa: chi them diem khi da di du xa. Gui lai ca quy dao moi khung
// la 8 kB/s vo ich.
const Pose2D p = snap.pose_map;
if (trajectory_.empty() ||
Distance2D(trajectory_.back(), p) > cfg_->web.path_min_step_m) {
trajectory_.push_back(p);
}
snap.trajectory = trajectory_;
}
// Ban do THE GIOI di rieng, LUON gui khi chay mo phong -- do la khung
// nhin "Gazebo" de lai cho chuan.
//
// ⚠️ KHONG gan no vao `snap.map`. `snap.map` la ban do SLAM DUNG; tron
// hai thu lam nguoi xem tuong SLAM da dung xong ca tang trong khi no moi
// thay mot hanh lang. Trinh duyet ve chung o hai khung rieng.
snap.world_map = map_ptr;
// Chua bat SLAM thi khong co ban do SLAM nao -- de trong va bao mode
// "off", chu KHONG muon ban do the gioi roi goi no la ban do SLAM.
if (!snap.map && map_ptr && !slam_enabled_) {
snap.slam.map_version = 0;
}
snap.health.lidar_hz = cfg_->sensors.lidar_hz;
snap.health.camera_hz = camera_ != nullptr ? cfg_->sensors.camera_hz : 0.0;
snap.health.imu_hz = cfg_->sensors.imu_hz;
{
std::lock_guard<std::mutex> lk(teleop_mu_);
snap.teleop.linear_speed = teleop_->linear_speed();
snap.teleop.angular_speed = teleop_->angular_speed();
snap.teleop.max_linear_speed = teleop_->max_linear_speed();
snap.teleop.max_angular_speed = teleop_->max_angular_speed();
}
web_->Publish(snap);
next += std::chrono::duration_cast<std::chrono::steady_clock::duration>(period);
std::this_thread::sleep_until(next);
}
}
} // namespace vslam