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

23
.gitignore vendored Normal file
View File

@@ -0,0 +1,23 @@
build/
build-*/
install/
.cache/
compile_commands.json
Testing/
*.deb
*.so
*.so.*
*.a
*.o
# Ban ghi va ban do -- nang, khong commit
resources/records/*
!resources/records/.keep
resources/maps/*
!resources/maps/.keep
test/data/*.vsr
*.swp
.vscode/
.idea/
.DS_Store

151
CMakeLists.txt Normal file
View File

@@ -0,0 +1,151 @@
cmake_minimum_required(VERSION 3.16)
project(vslam VERSION 0.1.0 LANGUAGES CXX)
# ---------------------------------------------------------------------------
# Chuan chung cho moi target. Dat o day thay vi lap lai trong tung lib.
# ---------------------------------------------------------------------------
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
endif()
# RPATH: binary trong build tree chay duoc ngay, va sau khi install van tim
# duoc .so cua chinh minh. Can cho /opt/vslam tren Jetson.
set(CMAKE_SKIP_BUILD_RPATH OFF)
set(CMAKE_BUILD_WITH_INSTALL_RPATH OFF)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH ON)
set(CMAKE_INSTALL_RPATH "$ORIGIN")
include(GNUInstallDirs)
set(VSLAM_CMAKE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
list(APPEND CMAKE_MODULE_PATH ${VSLAM_CMAKE_DIR})
include(vslam_helpers)
# ---------------------------------------------------------------------------
# Cong tac tung lib. Tat vslam_slam van build duoc phan con lai -- day la lop
# phong thu truoc rui ro build RTAB-Map tren arm64 (xem ke hoach, muc Jetson).
# ---------------------------------------------------------------------------
# Mac dinh bat theo tung giai doan (P0..P8). Lib nao chua viet thi OFF, bat
# len khi giai doan tuong ung hoan thanh -- de `cmake` luon chay duoc tren cay
# nguon hien tai thay vi bao thieu thu muc.
option(VSLAM_BUILD_COMMON "Build vslam_common (P0)" ON)
option(VSLAM_BUILD_WEB "Build vslam_web (P1)" ON)
option(VSLAM_BUILD_DRIVERS "Build vslam_drivers (P2)" ON)
option(VSLAM_BUILD_ODOMETRY "Build vslam_odometry (P3)" ON)
option(VSLAM_BUILD_SAFETY "Build vslam_safety (P4)" ON)
option(VSLAM_BUILD_PERCEPTION "Build vslam_perception (P5)" ON)
option(VSLAM_BUILD_SLAM "Build vslam_slam (P6)" OFF)
option(VSLAM_BUILD_SIM "Build vslam_sim (thay Gazebo)" ON)
option(VSLAM_BUILD_APP "Build vslam_node executable" ON)
option(VSLAM_BUILD_TOOLS "Build tools/" ON)
option(VSLAM_BUILD_TESTS "Build test/" ON)
option(VSLAM_BUILD_EXAMPLES "Build examples/" OFF)
option(VSLAM_ENABLE_CPACK "Enable CPack DEB packaging" OFF)
# Canh bao nghiem. -Wall -Wextra tu dau, khong bat sau.
add_compile_options(-Wall -Wextra -Wpedantic)
# ---------------------------------------------------------------------------
# Bay moi truong cua may dev x86 nay: SDK Hikvision MVS chen mot ban libusb CU
# (thieu libusb_set_option) vao LD_LIBRARY_PATH, lam moi thu link voi
# libpcl_io that bai. Bat som o day thay vi de nguoi doc mot loi linker kho
# hieu. Jetson khong bi -- no khong co /opt/MVS. Xem tools/dev_env.sh.
# ---------------------------------------------------------------------------
if(DEFINED ENV{LD_LIBRARY_PATH} AND "$ENV{LD_LIBRARY_PATH}" MATCHES "/opt/MVS")
# FATAL chu khong WARNING khi co target nao thuc su keo PCL vao.
#
# Canh bao khong du: no hien o dau output configure roi troi mat giua 60
# dong nhieu cua PCL/VTK, con loi that chi no o buoc LINK vai phut sau --
# hoac te hon, o buoc CHAY test:
# symbol lookup error: libpcl_io.so.1.10:
# undefined symbol: libusb_set_option
# Da xay ra that, ca hai lan.
#
# Chi FATAL khi can: `-DVSLAM_BUILD_SLAM=OFF -DVSLAM_BUILD_PERCEPTION=OFF`
# thi khong co gi cham PCL, va chan o do la chan vo co.
if(VSLAM_BUILD_SLAM OR VSLAM_BUILD_PERCEPTION)
message(FATAL_ERROR
"/opt/MVS nam trong LD_LIBRARY_PATH. No chua mot libusb cu thieu "
"libusb_set_option, se lam link VA chay voi libpcl_io that bai:\n"
" undefined reference to `libusb_set_option'\n"
" symbol lookup error: ... undefined symbol: libusb_set_option\n"
"\n"
" source tools/dev_env.sh\n"
"\n"
"Phai source lai o MOI shell -- ~/.bashrc va ~/.profile deu chen lai "
"/opt/MVS. Hoac build khong co PCL: -DVSLAM_BUILD_SLAM=OFF "
"-DVSLAM_BUILD_PERCEPTION=OFF.")
else()
message(WARNING
"/opt/MVS nam trong LD_LIBRARY_PATH, nhung khong target nao dung PCL "
"nen bo qua. Xem tools/dev_env.sh.")
endif()
endif()
# Cac header POD khong duoc chua Eigen fixed-size, nhung moi target van phai
# cung mot EIGEN_MAX_ALIGN_BYTES neu Eigen loi vao qua PCL/RTAB-Map.
# Xem ke hoach, muc "Bay arm64".
if(NOT DEFINED VSLAM_EIGEN_MAX_ALIGN_BYTES)
set(VSLAM_EIGEN_MAX_ALIGN_BYTES 16)
endif()
add_subdirectory(libs)
if(VSLAM_BUILD_APP)
add_subdirectory(app)
endif()
if(VSLAM_BUILD_TOOLS)
add_subdirectory(tools)
endif()
if(VSLAM_BUILD_TESTS)
enable_testing()
add_subdirectory(test)
endif()
if(VSLAM_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
# ---------------------------------------------------------------------------
# Config va resource ra ngoai code.
#
# Dung duong dan TUONG DOI cua GNUInstallDirs, khong phai "/etc/vslam" tuyet
# doi: duong dan tuyet doi bo qua CMAKE_INSTALL_PREFIX, nen khong cai vao
# prefix tam de test duoc va doi quyen root ngay ca khi chi muon thu.
#
# GNUInstallDirs tu anh xa dung:
# prefix=/usr -> /etc/vslam va /var/lib/vslam (dung cho .deb)
# prefix=/opt/vslam -> /opt/vslam/etc/... va /opt/vslam/var/...
# prefix=/tmp/x -> /tmp/x/etc/... (test khong can root)
#
# Gia tri mac dinh luc CHAY nam o node_constants.h va ghi de duoc bang
# $VSLAM_CONFIG_DIR / $VSLAM_RESOURCE_DIR -- do la cach mot ban cai khong theo
# FHS van tim thay config cua no.
# ---------------------------------------------------------------------------
install(DIRECTORY configuration_files/
DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/vslam/configuration_files
FILES_MATCHING PATTERN "*.yaml")
install(DIRECTORY resources/
DESTINATION ${CMAKE_INSTALL_LOCALSTATEDIR}/lib/vslam/resources)
if(VSLAM_ENABLE_CPACK)
include(vslam_cpack)
endif()
# ---------------------------------------------------------------------------
message(STATUS "")
message(STATUS "vslam ${PROJECT_VERSION} -- ${CMAKE_BUILD_TYPE} -- ${CMAKE_SYSTEM_PROCESSOR}")
message(STATUS " libs: common=${VSLAM_BUILD_COMMON} odometry=${VSLAM_BUILD_ODOMETRY} "
"safety=${VSLAM_BUILD_SAFETY} drivers=${VSLAM_BUILD_DRIVERS}")
message(STATUS " perception=${VSLAM_BUILD_PERCEPTION} web=${VSLAM_BUILD_WEB} "
"slam=${VSLAM_BUILD_SLAM} sim=${VSLAM_BUILD_SIM}")
message(STATUS " app=${VSLAM_BUILD_APP} tools=${VSLAM_BUILD_TOOLS} tests=${VSLAM_BUILD_TESTS}")
message(STATUS "")

63
CMakePresets.json Normal file
View File

@@ -0,0 +1,63 @@
{
"version": 3,
"cmakeMinimumRequired": { "major": 3, "minor": 21, "patch": 0 },
"configurePresets": [
{
"name": "dev",
"displayName": "Dev (x86, P0 only)",
"description": "May phat trien. Chi vslam_common + test, khong can RTAB-Map hay PCL.",
"binaryDir": "${sourceDir}/build/dev",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "RelWithDebInfo",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON"
}
},
{
"name": "asan",
"displayName": "AddressSanitizer",
"description": "Bat buoc chay truoc moi lan dong giai doan: Channel va TransformTree deu la code da luong co con tro chia se.",
"binaryDir": "${sourceDir}/build/asan",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_CXX_FLAGS": "-fsanitize=address,undefined -fno-omit-frame-pointer",
"CMAKE_EXE_LINKER_FLAGS": "-fsanitize=address,undefined"
}
},
{
"name": "tsan",
"displayName": "ThreadSanitizer",
"description": "Kiem quy tac 'luong safety khong chia se mutex voi luong slam'.",
"binaryDir": "${sourceDir}/build/tsan",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_CXX_FLAGS": "-fsanitize=thread -fno-omit-frame-pointer",
"CMAKE_EXE_LINKER_FLAGS": "-fsanitize=thread"
}
},
{
"name": "jetson",
"displayName": "Jetson AGX release (arm64)",
"description": "Deps build tu nguon nam o /opt/vslam. Xem tools/build_deps.sh.",
"binaryDir": "${sourceDir}/build/jetson",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"CMAKE_PREFIX_PATH": "/opt/vslam",
"CMAKE_INSTALL_PREFIX": "/opt/vslam",
"VSLAM_ENABLE_CPACK": "ON"
}
}
],
"buildPresets": [
{ "name": "dev", "configurePreset": "dev" },
{ "name": "asan", "configurePreset": "asan" },
{ "name": "tsan", "configurePreset": "tsan" },
{ "name": "jetson", "configurePreset": "jetson", "jobs": 6 }
],
"testPresets": [
{
"name": "dev",
"configurePreset": "dev",
"output": { "outputOnFailure": true }
}
]
}

755
README.md Normal file
View File

@@ -0,0 +1,755 @@
# vslam_cpp
SLAM va dinh vi cho robot dich vu indoor, **C++ thuan, khong ROS**, chay tren
Jetson AGX / Ubuntu 22.04 arm64.
Day la ban viet lai cua `~/projects/vSLAM_ws` (ROS 1 Noetic + catkin). Repo cu
van giu lai lam nguon tham chieu va lam corpus test.
## Lenh
Moi lenh chay tu goc repo. Nap `dev_env.sh` truoc: no go `/opt/MVS` khoi
`LD_LIBRARY_PATH` -- SDK Hikvision chen mot libusb cu thieu `libusb_set_option`
va lam hong moi lien ket toi `libpcl_io`.
```sh
cd ~/projects/vslam_cpp
source tools/dev_env.sh
export VSLAM_CONFIG_DIR=$PWD/configuration_files
```
### Build
```sh
cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DVSLAM_BUILD_APP=ON -DVSLAM_BUILD_SLAM=ON
cmake --build build -j
```
`-DVSLAM_BUILD_SLAM=OFF` neu chua co RTAB-Map -- phan con lai van build va chay
day du. Them `-DVSLAM_WITH_REALSENSE=ON` khi co `librealsense2`.
### Kiem tra
```sh
(cd build && ctest) # 31 test
./tools/regress.sh # 12 kich ban hoi quy, ~3 s
./build/app/vslam_node --check # chi kiem cau hinh roi thoat
```
### Chay mo phong
```sh
./build/app/vslam_node --sim --token t
```
Mo **http://localhost:8080/?token=t** -- lai bang joystick tren trang web.
| nut tren trang | lam gi |
|---|---|
| **chia doi** | hai khung: TRAI = THE GIOI (su that, de lai) · PHAI = SLAM dang dung. Tuong duong mo ca Gazebo lan RViz. Hai khung dung chung pan/zoom nen thang hang |
| **3D** | toa nha 3D. Chay voi `--world`: do dac THAT cua Gazebo (giuong, ghe, tu, thang may), mau lay tu texture cua tung model. Chay voi `--map`: moi o bi chiem thanh mot khoi tuong, chieu cao va mau theo DO DAY vach. Ca hai deu co san, bong do, ba nguon sang. Robot day du: than, banh, tru LiDAR, camera + frustum, vanh cliff 1.10-2.50 m. Ban do SLAM la lop phu tren san, hien DAN khi quet. Chuot trai xoay, phai keo, cuon phong to |
| **ground truth** | hinh robot thu hai, mau xanh la trong suot, o vi tri THAT cua mo phong. Khong phai nhan ban loi -- tat duoc. Khoang cach giua no va hinh mau xanh duong chinh la sai so uoc luong (do duoc: < 1 cm). Neu thay chung tach han ra thi do la LOI hien thi, khong phai troi -- xem docs/RUNTIME.md |
| **bam robot** | camera 3D di theo robot. **Tat mac dinh** -- bat len thi robot dung yen giua man hinh con ca the gioi truot qua, trong y het loi dinh vi |
### Chay tren the gioi Gazebo (khuyen dung)
Doc THANG file `.world` cua Gazebo: mesh va cham duoc raster hoa thanh luoi
chiem dung cho mo phong, va mesh hien thi duoc gui cho khung 3D.
```sh
./build/app/vslam_node --sim --world ../vSLAM_ws/src/robot_sim/worlds/hospital.world \
--x 1.03 --y -25.07 --token t
```
⚠️ Lenh nay **khong bat SLAM**, nen khung phai (ban do SLAM) se trong va ghi
`SLAM dang TAT`. Do la dung -- khung phai la "RViz", no chi co gi khi SLAM chay.
Them `--slam` de quet, xem muc [Quet ban do](#quet-ban-do).
⚠️ **Chon cho xuat phat cho thoang.** The gioi nay co day du noi that, nen cho
trong rat it: goc (0, 0) co vat can ngay sat, va (-6, -3) chi thoang 0.45 m.
`(1.03, -25.07)` thoang **4.75 m** -- rong nhat ca tang.
Can bo model cua Gazebo. Khong co `$GAZEBO_MODEL_PATH` thi tim trong
`~/.gazebo/models`, `~/gazebo_models/aws_hospital_fuel`, `~/gazebo_models/aws_hospital`;
hoac chi ro bang `--models DIR` cua `vslam_world_export`.
**Vi sao doc `.world` chu khong doc `.db`:** luoi xuat tu `map_hospital.db` co
goc o cho robot BAT DAU phien quet, lech ~18 m theo y so voi he toa do cua
Gazebo. Doc thang `.world` thi luoi cho sim, mesh cho khung 3D va tu the do dac
deu o MOT he toa do, khong can mot phep can chinh nao.
Khung 3D lay hinh dang tu chinh mesh cua Gazebo (178 the hien, 67 hinh hoc,
189k tam giac, tai mot lan qua `GET /api/world.bin`). Mau lay tu TRUNG VI
texture cua tung model -- 149 file PNG cua bo model nay tong cong 74 MB, qua
lon de gui, nen chung duoc rut thanh mot bang mau tinh san:
```sh
python3 tools/gen_model_colors.py ~/gazebo_models > resources/model_colors.json
```
Chay tu cay nguon thi can `export VSLAM_RESOURCE_DIR=$PWD/resources`.
Xuat rieng luoi ra `.pgm` de xem hoac de dung lai:
```sh
./build/tools/vslam_world_export --world ../vSLAM_ws/src/robot_sim/worlds/hospital.world \
--out test/data/maps/hospital_world.pgm
# 543x1181 @ 0.05 m/o (27.2 x 59.1 m), 181 mesh, 78346 o bi chiem
```
`--bbox` liet ke model nao mot minh trai rong qua 60 m -- do la cach tim mesh
dat sai don vi hoac sai truc, thu lam bao loi ca the gioi phinh len hang tram
met ma khong mot canh bao nao.
### Chay tren ban do 2D tu .db
Bo mo phong cung nhan `map.yaml` + `map.pgm` (dinh dang ROS map_server). Xuat
mot ban do tu DB RTAB-Map co san:
```sh
./build/tools/vslam_slam_bench --db ../vSLAM_ws/maps/map_hospital.db \
--localize --export-only --export-map test/data/maps/hospital.pgm
```
`--export-only` bo qua viec phat lai: `Init()` da nap ca do thi va luoi tung
node tu DB, nen xuat ban do khong can chay lai khung nao. **21 giay** thay vi
10+ phut, ket qua giong het.
```sh
./build/app/vslam_node --sim --map test/data/maps/hospital.yaml --token t
```
⚠️ Day la luoi chiem dung **2D**: chi tuong va cho trong, khong vat lieu va
khong noi that -- khung 3D suy chieu cao/mau tu DO DAY vach, do la tat ca thong
tin co trong du lieu. San hoan toan phang: khong vuc, khong kinh, nen
`cliff_detect` se im va `US_BLOCKED` khong kich. Them `--sim-glass-at X` de thu.
⚠️ **Chon cho xuat phat cho thoang.** Goc (0, 0) cua `hospital.yaml` co tuong
cach 2.0 m -- robot dam vao va BUMPER chot. Dung `--x -5.99 --y -2.91`: thoang
4 m moi huong, 14 m theo +X.
### Quet ban do
```sh
./build/app/vslam_node --sim --world ../vSLAM_ws/src/robot_sim/worlds/hospital.world \
--x 1.03 --y -25.07 --max-speed 2.0 \
--slam --slam-db ~/hospital_scan.db --slam-mode mapping --token t
```
Bam **chia doi**, lai het khu vuc roi **Ctrl-C** -- ban do luu vao
`~/hospital_scan.db`.
Khung trai cho biet ban dang o dau trong toa nha; khung phai cho biet SLAM da
dung duoc bao nhieu. Cho nao khung phai con trong la cho chua quet.
⚠️ Thieu `--slam-db` thi ban do chi nam trong RAM va MAT khi thoat.
⚠️ **Khong quet TIEP vao mot DB da co.** RTAB-Map 0.21.13 nem
`UNIQUE constraint failed: Statistics.id` o moi khung va khong dung duoc ban do
nao -- do duoc: 60 giay lai, `map_version` dung yen o 0. Node **tu choi khoi
dong** trong truong hop nay thay vi chay roi hong am tham. Muon quet lai thi
dung mot duong dan DB MOI; muon dung ban do cu thi chay `localization`.
### Dinh vi lai
```sh
./build/app/vslam_node --sim --world ../vSLAM_ws/src/robot_sim/worlds/hospital.world \
--x 1.03 --y -25.07 --max-speed 2.0 \
--slam --slam-db ~/hospital_scan.db --slam-mode localization --token t
```
⚠️ Tren **robot that** phai them `--slam-init-pose x,y,yaw` (tuong duong
`/initialpose`, thu ma dock cung cap). RTAB-Map KHONG dinh vi toan cuc duoc
bang scan khong: thieu pose ban dau thi no khoi dong tu pose CUOI cua phien
quet va sai ~1 m trong khi van bao `localized`. Trong mo phong, vi tri xuat
phat duoc dung thay cho dock.
### Khi dam phai vat can (BUMPER)
Quat truoc cua LiDAR chi phu **+-28.6 do**, nen LUI khong co cam bien nao che --
do la huong de dam nhat. Bumper kich thi:
1. Lai **cham** ra khoi vat can. Khi dang chot, lui va xoay duoc phep o 0.10 m/s
va 0.4 rad/s; tien cung duoc, nhung chi khi LiDAR xac nhan phia truoc trong.
Bumper khong biet vat can o dau, nen phai thu huong.
2. Roi ra roi moi bam **RESET**.
⚠️ Bam RESET khi **van dang cham** thi chot dat lai ngay -- log se ghi
`bumper VAN dang cham`. Do la dung: va cham van dang dien ra.
### Phat lai ban ghi
```sh
./build/tools/vslam_record --list # xem kich ban
./build/tools/vslam_record --scenario glass --out-dir /tmp # ghi .vsr
./build/app/vslam_node --replay /tmp/glass.vsr --token t # phat lai
```
### Co huu ich
| co | lam gi |
|---|---|
| `--world FILE.world` | mo phong tren the gioi Gazebo: mesh va cham -> luoi, mesh hien thi -> khung 3D. Uu tien hon `--map` |
| `--map FILE.yaml` | mo phong tren luoi 2D thay vi the gioi tong hop |
| `--x --y --yaw` | vi tri xuat phat |
| `--sim-glass-at X` | dat buc KINH o x = X m: LiDAR/depth khong thay, chi sieu am |
| `--slam-init-pose x,y,yaw` | pose ban dau cho localization (xem tren) |
| `--max-speed V` | ghi de tran toc do (m/s). **CHI CHO MO PHONG** -- base that gioi han o `robot.yaml base.max_linear` = 0.35 |
| `--port N` `--token S` | ghi de `system.yaml` |
| `--live` | phan cung that (driver LiDAR chua viet) |
### Cong cu phan cung
```sh
./build/tools/vslam_lidar_probe --seconds 10 # suy ra byte layout goi UDP
# Do SLAM tren corpus .db co san (ATE, process_ms, hoi tu sau kidnap)
./build/tools/vslam_slam_bench --db ../vSLAM_ws/maps/map_house.db
# Xuat lieu chiem dung tu .db ra .pgm + .yaml, dung lam the gioi mo phong
./build/tools/vslam_slam_bench --db X.db --localize --export-only \
--export-map out.pgm
```
## Vi sao bo ROS
Muc tieu trien khai la Jetson AGX chay Ubuntu 22.04, tuc la phai roi ROS 1
Noetic. Thay vi port sang ROS 2, du an bo han middleware: phan lon thuat toan
trong repo cu von khong phu thuoc ROS, va thu vien SLAM dang dung
(`librtabmap_core`) da la thu vien C++ thuan -- da kiem bang `objdump -x` va
`nm -D`, khong co mot symbol `ros::` nao.
Doi lai, mat RViz va Gazebo. RViz duoc thay bang mot web UI mot trang phuc vu
tai `:8080`. Gazebo khong duoc thay -- xem muc "Kiem chung" ben duoi.
## Kien truc
Khuon mau lay tu hai project cung tac gia: `obstacle_detection_core` va
`xloc_cpp`. Nguyen tac:
- Lib la CMake thuan (`add_library(... SHARED)`), **khong co `package.xml`**
- **Khong mot dong ROS nao** trong `libs/`. Kieu ban tin la struct POD tu dinh
nghia (`vslam_common.h`), thoi gian la `UnixTime`, TF la `TransformTree`
- Interface truu tuong + factory; phan cai dat an sau `.so`
- Cau hinh o ngoai code: `/etc/vslam/configuration_files/*.yaml`
- Dong goi `.deb` bang CPack
Bay lib trong `libs/`, chia theo **tap dependency ngoai** chu khong theo chuc
nang -- do moi la thu ton tien khi build tren Jetson:
| Lib | Dep ngoai them vao | Giai doan |
|---|---|---|
| `vslam_common` | Eigen3, yaml-cpp | P0 |
| `vslam_web` | Boost (Beast, header-only) | P1 |
| `vslam_drivers` | librealsense2 | P2 |
| `vslam_odometry` | *(khong them gi)* | P3 |
| `vslam_safety` | *(khong them gi)* | P4 |
| `vslam_perception` | PCL | P5 |
| `vslam_slam` | RTAB-Map, g2o, OpenCV, PCL | P6 |
Tat `-DVSLAM_BUILD_SLAM=OFF` thi sau lib con lai van build. Do la lop phong thu
truoc rui ro build RTAB-Map tren arm64, va la ly do duy nhat de khong gop het
thanh mot lib nhu `obstacle_detection_core`.
## Thay the ROS bang gi
| ROS | O day | Ghi chu |
|---|---|---|
| pub/sub | `Channel<T>` | **chi qua bien luong**; cung luong thi goi ham truc tiep |
| nodelet manager | goi ham truc tiep | chuoi perception chay inline tren luong camera |
| `message_filters::ApproximateTime` | `ApproxTimeSync`, `PairSync` | dem rieng 3 loai drop |
| `tf2_ros::Buffer` | `TransformTree` | cay 9 frame, chi 3 canh dong |
| URDF | khoi `frames:` trong `robot.yaml` | xoa bug "hai cho phai giu dong bo" |
| `ros::Time` | `UnixTime` | stamp; timeout thi dung `steady_clock` |
| param server | `ConfigNode` | co `require()` va `UnknownKeys()` |
| `ROS_INFO` / `_THROTTLE` | `VSLAM_INFO` / `_THROTTLE` | throttle theo `steady_clock` |
| RViz | web UI canvas 2D | mot trang, `:8080` |
| `std_srvs/Trigger` | `POST /api/...` | e-stop tuong minh, khong toggle |
| rosbag | dinh dang `.vsr` | ghi tho, replay tat dinh |
| `move_base` / `costmap_2d` | **khong port** | ngoai pham vi dot nay |
## Quy tac khong duoc pha
1. **Moi canh TF co dung mot nguoi ghi.** Vi pham la lop bug TF kho debug nhat.
2. **Khong stage nao goi `UnixTime::now()` truc tiep** -- moi stage nhan
`Clock&` qua constructor. Bo qua tu dau thi replay tat dinh khong retrofit
duoc sau.
3. **Stamp dung `UnixTime`, timeout dung `steady_clock`.** Lan lon hai thu nay
la bug dang co trong `safety_monitor_node.cpp`: mot buoc NTP sau khi Jetson
bat WiFi lam robot dung dot ngot.
4. **Luong `safety` khong chia se mutex nao voi luong `slam`** (vi
`Rtabmap::process()` chan 100-600 ms). Trong ROS dieu nay duoc bao dam mien
phi boi process rieng + `respawn="true"`.
5. **`Publish()` khong bao gio chan.** Luong cam bien khong duoc phep doi
consumer.
6. **Struct POD khong chua kieu Eigen fixed-size.** Xoa ca mot lop bug
alignment qua bien `.so` tren arm64.
## Build: cac luu y
Lenh o muc [Lenh](#lenh). Vai diem de vap:
- `CMakePresets.json` can **cmake >= 3.21**. May phat trien co 3.16.3 (focal)
nen phai dung lenh day du; Jetson jammy co 3.22 thi dung preset duoc.
`ctest --test-dir` cung can >= 3.20 -- tren 3.16 thi `cd build` roi chay
`ctest` truc tiep.
- Preset co san: `dev`, `asan`, `tsan`, `jetson`.
- ASan/UBSan va TSan: xem [`docs/RUNTIME.md`](docs/RUNTIME.md). TSan can
`g++-10` va chay `ctest -LE condvar`.
- Xem `README_PACKAGING.md` cho `.deb` va cho viec build dependency tren Jetson.
## Kiem chung khi khong con Gazebo va rosbag
Ba tang:
1. **Unit test tong hop** (`test/`) -- khong can du lieu, khong can phan cung.
Chay tu P0.
2. **Replay `.vsr`** -- ghi tho toan bo luong cam bien, replay tat dinh. Replay
source **implement chinh cac interface driver**, nen `vslam_node` khong biet
minh dang chay live hay replay; khong co nhanh `if (replay)` nao trong logic.
3. **Corpus `.db` co san** -- `rtabmap::DBDriver::getNodeData()` doc lai
scan/depth/pose tung node, nghia la `../vSLAM_ws/maps/map_house.db` **da la
mot dataset replay duoc** truoc khi phan cung chay lan nao.
## Dieu khien tren web
Thay cho `roslaunch robot_bringup sim.launch` + Gazebo GUI + RViz. Lenh o muc
[Lenh](#lenh); mo `http://<may>:8080` roi lai bang **joystick** tren trang.
| Dieu khien | |
|---|---|
| keo joystick | lai |
| phim mui ten | lai (khop `SUPPORTED_KEYS` cua `TeleopModel`) |
| Space | dung |
| `+` `-` hoac `Q` `E`, hoac nut tren trang | chinh toc do NGAY KHI DANG CHAY |
Mo hinh teleop la ban port C++ cua `robot_bringup/scripts/teleop_model.py`
(BSD-3-Clause, goc: `virtual_joystick_teleop` cua duongtd). Trang web CHI gui
truc joystick da chuan hoa `[-1, 1]`; moi phep quy ra van toc, moi phep kep,
va thu tu uu tien ba nguon nhap (manual > joystick > phim) deu nam trong C++.
`test_teleop_model.cc` so ket qua voi **79 vector sinh tu chinh ban Python
goc** (`test/gen_teleop_vectors.py`), sai lech < 1e-9 -- do la cach duy nhat
kiem duoc loi hua "logic giu NGUYEN VEN" cua ban port.
Khong co `--map` thi dung the gioi tong hop: hanh lang chinh + phong hai ben.
### Vi sao khong phai Gazebo
Bo ROS la mat `gazebo_ros`. Nhung ke ca con ROS thi Gazebo cung khong hop:
`hospital_three_floors.world` co 541 instance model, va `gpu_ray` 1081 tia
@25 Hz duoc chon vi may dev co RTX 4060 -- Jetson AGX khong co thu do de tieu.
Cai thuc su can de kiem chung duong ong 2.5D chi la mot ban do 2D, mot robot
vi sai, va phep raycast. Do la ~450 dong, chay tren CPU, **325x nhanh hon thoi
gian thuc** khi bo phan ngu.
`SimSource` implement CHINH cac interface driver, y het `ReplaySource`. Nen
`vslam_node` khong phan biet duoc ba nguon: phan cung that, file `.vsr`, hay
mo phong. Khong co mot nhanh `if (sim)` nao trong logic -- day la "nguyen tac
parity sim <-> real" cua `docs/ARCHITECTURE.md` cu, nhung lan nay duoc bao dam
boi KIEU DU LIEU chu khong boi ky luat.
### Do duoc tren duong ong that (sim -> encoder -> wheel_odom -> EKF)
Duong vuong 6.7 m, tieu chi L2 cua repo cu la "lech < 2% quang duong":
| Kich ban | wheel_odom tho | EKF | Truot phat hien |
|---|---|---|---|
| Khong truot | 0.00% | **0.01%** | 0 |
| **Truot vi sai** (mot banh truot hon banh kia) | 6.68%, yaw lech **142 do** | **0.23%**, yaw dung | 649 |
| **Truot doi xung** (hai banh truot bang nhau) | 13.46% | 13.29% | **0** |
Hang giua la ca co che phat hien truot lam dung viec cua no: bat duoc chenh
lech `|omega_encoder - gyro_z|`, nang covariance, va EKF tu dong chuyen sang
tin gyro -- phuc hoi duoc huong tu cho lech 142 do.
Hang cuoi la mot **gioi han THAT cua phuong phap**, khong phai bug: hai banh
truot bang nhau thi khong sinh chenh lech quay nao, va gyro chi nhin thay phep
QUAY. Muon bat loai truot nay can nguon thu hai -- scan matching, tuc RTAB-Map
o P6. Da ghi lai bang test (`OdometryPipeline.TruotDoiXung_GYRO_KHONG_PHAT_HIEN_DUOC`)
de khong ai phai phat hien lai bang cach dieu tra mot robot di lech 13% ma
khong co canh bao nao.
### Lop an toan do tren duong ong that
| Tinh huong | Trang thai FSM | Ket qua |
|---|---|---|
| Chua co lenh teleop | `NO_CMD` | dung |
| Lai toi tuong | `OK` -> `SCAN_SLOW` (0.79 m) -> `SCAN_STOP` (0.35 m) | dung dung nguong |
| Tien khi `SCAN_STOP` | `SCAN_STOP` | **0.0000 m** |
| Lui khi `SCAN_STOP` | `OK` | 0.465 m -- duong thoat khong bi chan |
| E-stop | `ESTOP` | phanh trong **0.079 m** |
| Ngung gui lenh 1.5 s | `NO_CMD` | dung |
Con so 0.079 m la quang duong PHANH cua e-stop phan mem. `docs/HARDWARE.md`
cua repo cu ghi "ly tuong nhat la cat nguon motor bang phan cung, khong qua
ROS" -- day chinh la ly do.
Luong safety chay 20 Hz TREN LUONG RIENG, khong phai trong callback teleop.
Do la dieu kien de `NO_CMD`, `SCAN_TIMEOUT` va `cliff_hold` co y nghia:
chung ton tai chinh xac cho truong hop lenh NGUNG toi.
### Camera depth
Gazebo mo phong depth bang `libgazebo_ros_openni_kinect`. Bo mo phong nay lam
dieu tuong duong bang **raycast 2.5D**: ban do chiem dung duoc dung thanh tuong
cao `wall_height`, va moi o co mot **do cao san** rieng.
Hinh hoc da kiem bang tinh tay (camera z = 0.80, chuc 15 do, FOV 69 do):
| Do | Ly thuyet | Sim |
|---|---|---|
| San o hang giua | 0.80 / sin(15 do) = 3.09 m | 3.093 m |
| San o hang duoi (42.3 do) | 0.80 / sin(42.3 do) = 1.19 m | 1.208 m |
| Sau khi tao bac hut 0.5 m | (0.80+0.5) / sin(15 do) = 5.02 m | 5.017 m |
Hang cuoi chinh la dau hieu ma `cliff_detect` tim: depth **lon hon nhieu** so
voi mat phang san ky vong. `SetFloorHeight()` tao bac hut, nen **cliff_detect
kiem duoc bang mo phong** -- truoc do toi tuong la khong.
Chi phi: 14 ms moi khung 320x240, tuc 42% mot core o 30 Hz. Mo phong van chay
2.4x nhanh hon thoi gian thuc khi bat camera. `FastCfg()` trong test TAT camera
mac dinh vi mot khung la 76800 tia raycast.
### Nghieng than robot
Gia toc ke **KHONG phan biet duoc nghieng voi tang toc** -- no do TONG cua
trong luc chieu xuong ba truc va gia toc rieng cua robot. Logic cot loi cua
`gravity_align` la TU tach hai thanh phan do (`axc = ax - a_lin`,
`ayc = ay - v*w`). San phang va robot cung nhac thi ca hai so hang do bang 0,
va bo loc khong bao gio bi kiem tra.
Bo mo phong nay co he lo xo - giam chan bac hai cho than robot, cong voi
nghieng theo dia hinh:
| Tinh huong | Do duoc |
|---|---|
| Dung yen | pitch 0, `|a|` = 9.7993 (g = 9.8066) |
| Dang tang toc | pitch **-1.20 do** (mui ngoc len), accel x = +0.503 |
| Chay deu | pitch +0.08 do -- ve lai phang |
| Dang phanh | pitch **+1.22 do** (mui chui xuong), accel x = -0.515 |
| Vua chay vua quay | roll **+1.10 do** |
| Doc len 10% | pitch **-5.19 do** (ky vong 5.71, lech do san luong tu hoa theo o 5 cm) |
| Doc xuong 10% | pitch **+5.19 do** |
Bac hai chu khong phai gan truc tiep: robot that co quan tinh, no KHONG bat
dau nghieng tuc thoi, va do tre do chinh la thu lam `gravity_align` kho.
Camera gan cung vao than nen no nghieng theo -- mat phang san ky vong dich
theo tung khung, va do la ly do `cliff_detect` phai TU hieu chuan lai mat san.
`docs/SIM_VS_REAL.md` canh bao doc > 5 do lam LiDAR 2D thanh diem yeu. Bo mo
phong tao duoc dung muc do.
### Cai gi mo phong KHONG kiem duoc
| Khong mo phong | Hau qua |
|---|---|
| IR speckle, rolling shutter | depth qua "sach" so voi D410 that |
| Be mat den / guong / kinh | LiDAR va depth luon thay tuong; thuc te ca hai deu xuyen qua kinh, va do la ly do phai co sieu am |
| Vat can cao thap khac nhau | tuong la mot khoi dac tu san len `wall_height`; khong co mat ban nho ra |
| Rung tiep xuc banh-san | accel nhieu that manh hon nhieu Gauss |
`depth_dropout_rate` mo phong viec mat diem anh, nhung bang xac suat deu --
tho hon thuc te, noi dropout bam theo be mat.
Kiem duoc: dong hoc vi sai, tich phan odometry, truot banh (ca hai loai), EKF,
lop an toan theo scan, hinh hoc depth, phat hien vuc, **nghieng than va doc
san**, va toan bo duong ong du lieu.
## Chay web UI bang du lieu gia
Khong can phan cung, khong can RTAB-Map:
```
./build/tools/vslam_web_demo --port 8080 --map-w 2000 --map-h 2000
```
Roi mo `http://<may>:8080`. Them `--token <chuoi>` de bat xac thuc, khi do URL
la `http://<may>:8080/?token=<chuoi>`.
Tren may dev x86 phai `source tools/dev_env.sh` truoc -- xem file do de biet vi sao.
## Trang thai
| Giai doan | Trang thai |
|---|---|
| P0 `vslam_common` | xong (x86 dev; arm64 chua co may) |
| P1 `vslam_web` | xong (x86 dev) |
| P2 `vslam_drivers` | mot phan -- xem duoi |
| `vslam_sim` (thay Gazebo) | xong |
| P3 `vslam_odometry` | xong |
| P4 `vslam_safety` | xong |
| P5 `vslam_perception` | xong (x86 dev) -- xem `docs/PERCEPTION.md` |
| P6 `vslam_slam` | xong (x86 dev) -- xem `docs/SLAM.md` |
| P7 bo hoi quy | xong -- xem `docs/REGRESSION.md` |
| `vslam_node` + 6 file config | xong -- xem `docs/RUNTIME.md` |
| SLAM trong vong + ground truth | xong -- `--slam`, khoi `gt` tren web |
| Sieu am + bumper + KINH trong sim | xong -- 8/11 nhanh FSM chay end-to-end |
| P8 dong goi `.deb` | chua (chua can) |
343 test case / 24 nhom + 6 kiem cau hinh + 12 kich ban hoi quy (31 ctest),
0 warning, ASan + UBSan sach.
Tai lieu: [`docs/RUNTIME.md`](docs/RUNTIME.md) ·
[`docs/PERCEPTION.md`](docs/PERCEPTION.md) · [`docs/SLAM.md`](docs/SLAM.md) ·
[`docs/REGRESSION.md`](docs/REGRESSION.md)
### P5 lam duoc den dau
Chuoi `depth_to_cloud -> depth_filter -> gravity_align -> cliff_detect` chay
inline tren mot luong. **Khong phu thuoc PCL** (co y -- xem
`docs/PERCEPTION.md`), nen lib nay build va test duoc tren may chua co PCL.
| Do duoc | Gia tri |
|---|---|
| Chi `cliff_detect`, anh 320x240 | 0.215 ms/khung = **0.6%** mot core @30 Hz |
| `cliff` + duong cloud day du | 1.946 ms/khung = **5.8%** mot core @30 Hz |
| RSS qua 55 s chay | dung yen 10.9 MB |
| San phang trong sim (di thang) | **0** vuc gia, `lvl_mad` 0.0032 |
| Quay tai cho, hanh lang 1.6 / 2.0 / 2.5 / 3.0 / 4+ m | **0** vuc gia o moi be rong; phan xet duoc 77.6 / 81.0 / 81.4 / 90.5 / 100 % |
| Bac 0.35 m / vuc sau khong tra ve | deu phat hien, danh dau tai MEP |
Hai lo hong THAT tim ra o giai doan nay, ca hai deu duoc khoa bang test:
| Lo hong | O dau | Hau qua da do |
|---|---|---|
| Anh depth mo phong mang **cu ly Euclid** thay vi **Z-depth** | `vslam_sim` | Tia lech truc bi thoi phong toi 1.15x. Mat san khop thanh `z0 = -0.254 m` doc `+0.114`, 87/1903 tia bao vuc **tren san hoan toan phang** |
| Khop mat san vao pixel **TUONG** roi ngoai suy ra ca cua so | `cliff_detect` (co tu ban ROS) | Hanh lang 1.6 m, quay tai cho: `z0 = +0.34 m`, MAD 0.025 lot ca cong MAD, 69/500 mau bao vuc gia |
| Cung loi tren o be rong 2.5-3.0 m, noi chi ~9% tia bi che | `cliff_detect` | `max_obstructed_frac` KHONG bat duoc (quet 0.60 -> 0.20 deu cho dung 6/210 khung sai). Diem tuong keo doc len +0.19, vua du duoi tran 0.20. Sua bang `max_level_offset`: mat phang khop duoc phai di qua cho robot DANG DUNG |
### Mo phong: da VUOT ROS
Gazebo chi publish `scan_raw`, `imu/data_raw`, `ground_truth/odom`, camera va
diff_drive. Sim nay co du, cong them:
| | Gazebo cua repo cu | sim nay |
|---|---|---|
| Nghieng than (spring-damper bac 2) | khong | co |
| Ban do DO CAO SAN (vuc/bac thang) | khong | co |
| Depth dropout | khong | co |
| **Sieu am** | khong | co, 3 dau do, chum 30 do |
| **Bumper** | khong | co, nho ra 3 cm |
| **KINH** (LiDAR/depth xuyen qua) | khong | co |
| "Rut day" LiDAR | khong | co |
**8/11 nhanh FSM da chay END-TO-END.** Truoc do 5 nhanh an toan chi co unit
test -- duong tu cam bien -> FSM -> base chua bao gio duoc thu cho chung.
Hai lo hong AN TOAN tim ra khi dung cac kich ban nay:
| Lo hong | Hau qua |
|---|---|
| `US_TIMEOUT` **khong bat duoc** dan sieu am chet | FSM chi kiem stamp cu. Dan chet nhung MCU VAN gui thi stamp luon moi -> vo hinh. Te hon: toi loc bo NaN nen map thanh RONG, ma rong nghia la "khong lap sieu am". Sua: giu NaN, FSM dem so dau do TRA LOI |
| `BUMPER` **khong the kich** trong mo phong | Phep va cham cua sim TU CHOI chuyen dong khi vanh robot cham vat can, nen robot khong bao gio vao duoc vi tri ma bumper dat dung `robot_radius` nhin thay. Bumper that NHO RA ngoai vo -- them `bumper_reach = 0.03 m` |
**Kinh** la thu Gazebo khong mo phong duoc, va la ly do sieu am ton tai: kinh
gan nhu trong suot voi laser 940 nm va IR cua depth, nhung phan xa am rat tot.
Do duoc trong kich ban `glass`: LiDAR bao `min_front` 1.66 m (tuong ben hanh
lang) trong khi buc kinh o 0.34 m -- no hoan toan khong thay.
```
vslam_node --sim --sim-glass-at 3.0
```
### Mo phong: chi tiet
```
vslam_node --sim --slam --slam-db "" --slam-mode mapping
```
Phan cam bien da ngang Gazebo tu truoc: Gazebo chi publish `scan_raw`,
`imu/data_raw`, `ground_truth/odom`, camera va diff_drive. Sim nay co du, cong
them nghieng than bac hai, ban do do cao san (vuc) va depth dropout ma Gazebo
KHONG co.
Gio them not tang tren:
| | do duoc |
|---|---|
| `map->odom` correction | toi **0.048 m** -- that, khong phai 0 |
| `process_ms` | p50 2.0, p95 11.2, max 16.9 ms |
| Sai so vs ground truth | max 0.043 m |
| Bang thong tong | 73.4 kB/s |
**Ban do cua bo mo phong CHI hien khi SLAM chua co ban do cua no.** Hien ban do
goc ma khong noi gi la gian lan: no dep vi no la SU THAT, khong phai vi SLAM
lam tot. Chua bat SLAM thi web bao `slam.mode = "off"`.
**Ground truth len web.** Tuong duong `/ground_truth/odom` cua repo cu, va la
cach DUY NHAT nhin thay drift -- RViz ve duoc ca hai pose canh nhau. Khoi `gt`
co `x/y/yaw`, `roll/pitch` THAT, va `err` tinh o server. Do duoc voi EKF:
**0.1-3.8 mm** qua 15 s lai.
Hai lo hong tim ra khi noi SLAM:
| Lo hong | Hau qua |
|---|---|
| "Chi dung lai ban do khi do thi doi" la KHONG DU | O che do mapping do thi doi gan nhu MOI khung -> dung ban do **9 lan/giay**. Tren ban do that 2000x2000 la 221 kB/s, gan gap doi ca ngan sach 120 kB/s. Sua bang `web.map_rebuild_rate_hz` -> do lai 0.50/s |
| `localization` + DB rong chay IM LANG | `process_ms` 0.3-2.4 ms, `map->odom` luon 0 -- trong y het "SLAM dang chay tot". Gio bi tu choi khoi dong |
### Quy trinh: quet ban do roi dinh vi lai
```
vslam_node --sim --slam --slam-db ~/map.db --slam-mode mapping # Ctrl-C de luu
vslam_node --sim --slam --slam-db ~/map.db --slam-mode localization
```
Do duoc tren mot vong quet (283 node, DB 2.85 MB): `localized` 301/301 tu
0.08 s, `process_ms` p50 **1.0** p95 **2.2** ms, sai so vs ground truth trung
binh **1.1 cm** max **1.7 cm**.
Hai loi chan dung quy trinh nay, ca hai IM LANG:
| Loi | Hau qua |
|---|---|
| `Runtime` khong goi `slam_->Close()` | Destructor chay `Close(false)` -- **vut bo** ban do. Mot phien quet dai xong khong de lai gi, va KHONG co loi nao: file .db van ton tai, chi la trong |
| Dinh vi lai sai **1.08 m** ma van bao `localized` | O che do localization RTAB-Map khoi dong tu pose CUOI cua phien quet, khong phai tu goc. `--slam-init-pose x,y,yaw` (tuong duong `/initialpose` cua `dock_init.py`) dua sai so **108.4 cm -> 1.7 cm** |
### `vslam_node` -- tien trinh duy nhat
```
vslam_node --sim # bo mo phong (thay Gazebo)
vslam_node --replay X.vsr # phat lai ban ghi
vslam_node --live # phan cung that (driver CHUA viet)
vslam_node --check # nap va KIEM cau hinh roi thoat
```
Thay cho `roslaunch` + 20 file .launch + 14 file YAML + roscore. Doc
`app/src/wiring.cc` de hieu he thong -- do la NOI DUY NHAT noi nguon voi
stage.
**14 file YAML gop thanh 6.** Cai quan trong nhat: KHONG gia tri nao o hai
noi. `cliff_detect.nominal_tz` khong con trong file config -- no la HE QUA cua
`robot.yaml` (`camera_link.z + wheel_radius`). Hai so do TUNG lech that: 0.803
trong cliff_detect.h so voi 0.80 ma sim dung. Va phep dung `cam_to_base` tung
bi lap o BON file, gio di qua `RobotModel::StaticTransform()`.
`--check` kiem CHEO giua cac file, thu khong kiem duoc trong mot file don le:
| cong | vi sao |
|---|---|
| `safety.cmd_timeout > robot.base.cmd_timeout` | ngan hon thi base tu dung truoc, va nhanh `NO_CMD` cua FSM **khong bao gio chay** |
| `safety.limits <= robot.base` | lop an toan khong duoc cho phep nhieu hon phan cung chiu duoc |
| `safety_priority` cao nhat | dat nguoc lai la vo hieu hoa ca ly do dung SCHED_FIFO |
Ca bon cong deu co trong ctest, chay bang CHINH binary tren CHINH file YAML se
duoc cai len /etc/vslam.
Hai lo hong tim ra khi dung runtime:
| Lo hong | Hau qua |
|---|---|
| `ReplaySource` phat theo thoi gian that bang `SleepUntil(Steady() + nanoseconds(0))` -- **ngu 0 ns** | `speed` khong co tac dung gi; ban ghi 8 giay chay xong trong 0.4 giay. Tren web UI trong GIONG HET "replay bi treo o khung cuoi" |
| Web hien `cliff` tu so do da cu | Ban ghi het thi co ket lai va web bao "VUC PHIA TRUOC" mai mai, ke ca khi FSM da bo qua no tu lau |
### P7 lam duoc den dau
```
tools/regress.sh # chay va so voi ky vong
tools/regress.sh --record # ghi lai .vsr tu bo mo phong truoc
tools/regress.sh --bless # GHI DE ky vong
```
**12 kich ban, 3 giay** (chi tieu < 5 phut). Moi kich ban cham vao MOT duong
ma cac kich ban khac khong cham -- bang day du trong `docs/REGRESSION.md`.
`ReplaySource` implement CHINH cac interface driver, nen trong
`vslam_replay.cc` khong co mot nhanh `if (replay)` nao. Khi co phan cung,
`vslam_record --live` ghi cung dinh dang va ca bo hoi quy chay tren du lieu
that ma khong sua mot dong.
Da kiem rang bo hoi quy THUC SU bat duoc hoi quy, khong phai chi chay xanh:
| thay doi thu | ket qua |
|---|---|
| `cliff_margin` 0.05 -> 0.35 | `count_state_OK` lech 90, va phep DEM KHOA bao 21 vs 19 -- hai nhanh bien mat han |
| `min_cluster` 12 -> 20 | kich ban `cliff` (bac 0.40 m) **KHONG** bat duoc; kich ban `cliff_shallow` (bac 0.12 m, sat nguong) bat duoc: 14 vs 15 |
Dieu thu hai la ly do `cliff_shallow` ton tai: mot bo hoi quy chi chay XA
nguong thi khong bat duoc truot nguong.
Dung sai theo TIEN TO khoa: `n_`/`count_` phai khop **tuyet doi** (lech mot
khung = duong di qua code da doi), con `pose_`/`yaw_` thi 2 mm / 1 mrad. Da
kiem dung sai du: cung ban ghi chay duoi `-O0` va `-O2` deu khop.
### P6 lam duoc den dau
Boc `rtabmap::Rtabmap`, khong kieu nao cua RTAB-Map lot ra khoi `slam_types.h`.
Kiem bang corpus `.db` co san -- KHONG can phan cung.
| Do duoc tren `map_house.db` (240 node) | Gia tri |
|---|---|
| ATE so voi pose toi uu trong DB, mapping | **0.0146 m** (chi tieu < 0.10) |
| Doi chung `rtabmap-reprocess` cung tham so | 0.0074 m -- tuc chenh lech con lai la hao hut cua bench, khong phai cua lib |
| Localization co pose ban dau | **0.0051 m**, 194 lien ket, hoi tu ngay |
| g2o so voi GTSAM | ATE **giong het**, GTSAM cham **2.6x** (p95 3080 vs 1201 ms) |
Hai lo hong tim ra, ca hai deu khoa bang test:
| Lo hong | Hau qua da do |
|---|---|
| `RtabmapSlam` co bien `laser_to_base` nhung **quen setter** | Laser o (0.24, 0, 0.20) bi coi nhu o goc. ICP van hoi tu (chi thay the gioi dich di) nhung do thi tich luy sai so: **ATE 0.2378 m thay vi 0.0146 m**, khong mot loi nao |
| `rtabmap::LaserScan::init()` **nem UException** voi hinh hoc goc suy bien | Mot sweep thieu goi UDP (angle_max == angle_min) se giet luong SLAM. Da chan, tra scan rong |
**Gioi han da dinh luong:** RTAB-Map khong dinh vi toan cuc duoc bang scan
khong -- khong co pose ban dau thi ATE tho **9.80 m**, 0 lien ket. Gioi han
phuc hoi la `Icp/MaxCorrespondenceDistance`: sai 0.30 m thi hoi tu sau 18 s,
sai 0.50 m tro len thi **khong bao gio**. Noi len 1.0 m thi phuc hoi duoc tu
1 m / 20 do trong 19 s, doi lai ATE tut 0.005 -> 0.102 m.
**Chua dat:** `process_ms` p95 722-1008 ms tren x86 dev, chi tieu la < 700 ms
tren Jetson. Nhung `rtabmap-reprocess` cung tham so cung ton 600-1000 ms moi
node, nen day la phi ton cua CAU HINH chu khong phai cua wrapper.
### P2 lam duoc den dau
Xong (khong can phan cung):
| Phan | Ghi chu |
|---|---|
| `ScanSanitizer` | gop header-fix + sector mask lam MOT ham, xoa han bay "filter nao phai chay truoc" |
| `ClockSync` + `McuTimeUnwrapper` | kem sua bug tran `micros()` moi 71.58 phut ma ban Python khong co |
| Giao thuc MCU | I/B/P + ban ghi **E cho encoder** (moi) + `TickUnwrapper` |
| Dinh dang `.vsr` | ghi tho, CRC moi chunk, drop-khong-chan, tu mo ta lo hong cua chinh no |
| `ReplaySource` | implement CHINH cac interface driver; tinh tat dinh da duoc chung minh bang test |
**Driver RealSense D410: DA VIET** (`libs/vslam_drivers/src/realsense_driver.cc`).
Bat bang `-DVSLAM_WITH_REALSENSE=ON`; may dev co librealsense2 2.50.0 nen no
build va link duoc, chi CHUA KIEM CHUNG tren camera that. API la cong khai --
viet duoc ma khong can thiet bi, y het cach wrapper RTAB-Map duoc viet va do
bang corpus `.db`.
Ba cho danh dau ⚠️ CHUA XAC MINH trong driver, deu can dung camera de chot:
`RS2_OPTION_GLOBAL_TIME_ENABLED` tren FW 5.17.0.10, `depth_scale` that cua
thiet bi, va domain timestamp thuc su nhan duoc.
Chua lam duoc (can phan cung hoac thong tin chua co):
| Phan | Chan boi |
|---|---|
| Driver LakiBeam UDP | thieu DUNG MOT thu: byte layout cua goi. Moi thu khac da biet tu `richbeam.launch` (UDP, host 192.168.198.2, port 2368, `inverted`, `angle_offset`). Chay `build/tools/vslam_lidar_probe --seconds 10` tren may noi duoc voi LiDAR -- no TU SUY RA offset truong goc, vung mang range, va so goi moi vong quet |
| Huong 0 do cua LiDAR | chua do duoc (rui ro R5). Cat nham quat truoc -> `SCAN_SPARSE` -> robot dung im |
| Transport cua base | **phan cung CO encoder**, nhung giao thuc host doc chung thi khong co o dau trong repo cu. `BaseInterface` da tach khoi phep toan odometry nen khi biet giao thuc that chi phai them mot lop mong |
Da do tren du lieu that (`tools/probe_rtabmap` tren `../vSLAM_ws/maps/*.db`):
RTAB-Map dung occupancy grid duoc qua `LocalGridCache` + `OccupancyGrid`;
`map_hospital.db` 1990 node, dung grid 526x1162 trong 5.65 s, 690 MB RSS.
**ThreadSanitizer: da chay.** Can `g++-10`. Xem `docs/RUNTIME.md` muc
ThreadSanitizer.
No bat duoc mot race THAT ngay lan dau tren `vslam_node --sim`: luong `web_tx`
doc `GravityAlign::roll()` trong khi luong `source` ghi o 200 Hz. Sua bang ba
`std::atomic` o `Runtime` -- KHONG them khoa vao thu vien, vi `GravityAlign` co
hop dong la mot luong. Sau khi sua: **0 canh bao** duoi kich ban nang (lai 4
pha + e-stop 3 lan + reset + chinh teleop + client WS thu hai ngat dot ngot).
`test_channel` khong chay duoc duoi TSan: `condition_variable::wait_for` voi
predicate lam TSan cua gcc-10 bao gia. `test/tsan_condvar_repro.cc` tai lap
dung hai canh bao do voi KHONG MOT DONG NAO cua vslam. Gan nhan `condvar`,
chay `ctest -LE condvar` duoi TSan -- KHONG suppress, vi suppression du rong se
che luon moi race tren du lieu duoc bao ve boi mutex co dung condvar.

31
app/CMakeLists.txt Normal file
View File

@@ -0,0 +1,31 @@
# vslam_node: tien trinh duy nhat. So huu moi luong va moi Channel.
#
# Doc src/wiring.cc de hieu he thong: no la noi duy nhat noi channel voi stage,
# va la tuong duong cua toan bo 20 file .launch cua ban ROS.
add_executable(vslam_node
src/main.cc
src/runtime.cc
src/wiring.cc
src/app_config.cc
)
target_include_directories(vslam_node PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
${CMAKE_CURRENT_SOURCE_DIR}/src)
# Node la noi DUY NHAT phu thuoc vao tat ca. Cac lib khong biet nhau ngoai
# pham vi do thi dep da khai -- do la ly do tat mot lib van build duoc phan
# con lai.
target_link_libraries(vslam_node PRIVATE
vslam_sim vslam_web vslam_perception vslam_odometry vslam_safety
vslam_drivers vslam_common)
# SLAM la TUY CHON. Tren may chua build duoc RTAB-Map (hoac tren Jetson khi
# dang go loi phan khac), node van phai chay day du phan con lai -- do la ca
# ly do tach lib theo tap dependency.
if(VSLAM_BUILD_SLAM)
target_link_libraries(vslam_node PRIVATE vslam_slam)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_SLAM=1)
endif()
install(TARGETS vslam_node RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})

513
app/src/app_config.cc Normal file
View File

@@ -0,0 +1,513 @@
#include "app_config.h"
#include <cmath>
#include <vector>
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
constexpr double kPi = 3.14159265358979323846;
// Nap mot file, doi ngoai le thanh StatusResponse.
//
// ConfigNode::LoadFile nem ConfigError. Mot file config sai KHONG duoc phep
// lam sap tien trinh: nguoi van hanh phai doc duoc loi, khong phai mot
// backtrace.
StatusResponse Open(const std::string& dir, const char* name, ConfigNode* out) {
const std::string path = dir + "/" + name;
try {
*out = ConfigNode::LoadFile(path);
return StatusResponse::Ok();
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
std::string(name) + " (" + path + "): " + e.what());
}
}
// Tu choi khoi dong khi co khoa la.
//
// Go sai ten khoa hien tai roi ve mac dinh mot cach im lang. `stop_distence`
// thay vi `stop_distance` nghia la robot dung o 0.35 m mac dinh thay vi gia
// tri ban vua dat -- va ban se khong biet cho toi khi no khong dung.
StatusResponse Reject(const ConfigNode& n, const char* where,
const std::vector<std::string>& known) {
if (n.IsNull()) return StatusResponse::Ok();
const std::vector<std::string> unknown = n.UnknownKeys(known);
if (unknown.empty()) return StatusResponse::Ok();
std::string m = std::string(where) + ": khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
} // namespace
StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
// ---------- robot.yaml ----------
{
const StatusResponse st = out->robot.LoadFile(dir + "/" + kRobotConfigFile);
if (!st.ok()) return st;
}
const RobotGeometry& geom = out->robot.geometry();
// ---------- sensors.yaml ----------
{
ConfigNode root;
const StatusResponse st = Open(dir, kSensorsConfigFile, &root);
if (!st.ok()) return st;
{
const StatusResponse r = Reject(root, "sensors.yaml", {"lidar", "camera", "mcu"});
if (!r.ok()) return r;
}
const ConfigNode l = root["lidar"];
{
const StatusResponse r =
Reject(l, "sensors.yaml lidar",
{"host", "port", "expected_rate_hz", "range_min", "range_max",
"stamp_mismatch_warn", "sector_masks"});
if (!r.ok()) return r;
}
out->sanitizer.range_min = l.get<double>("range_min", 0.05);
out->sanitizer.range_max = l.get<double>("range_max", 40.0);
out->sensors.lidar_hz = l.get<double>("expected_rate_hz", 25.0);
// Sector mask ghi bang DO trong YAML (doc duoc bang mat), dung bang RAD.
// Doi mot lan o day, khong de moi noi tu doi.
const ConfigNode masks = l["sector_masks"];
out->sanitizer.sector_masks.clear();
if (!masks.IsNull()) {
if (!masks.IsSequence()) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"sensors.yaml lidar.sector_masks phai la chuoi");
}
for (size_t i = 0; i < masks.size(); ++i) {
const ConfigNode m = masks.at(i);
if (!m.IsSequence() || m.size() != 2) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"sensors.yaml lidar.sector_masks[" + std::to_string(i) +
"] phai la [bat_dau_do, ket_thuc_do]");
}
const double a = m.at(0).as<double>() * kPi / 180.0;
const double b = m.at(1).as<double>() * kPi / 180.0;
if (!(b > a)) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"sensors.yaml lidar.sector_masks[" + std::to_string(i) +
"]: ket thuc phai lon hon bat dau (quat rong 0 do khong che gi)");
}
out->sanitizer.sector_masks.push_back(SectorMask{a, b});
}
}
const ConfigNode c = root["camera"];
{
const StatusResponse r =
Reject(c, "sensors.yaml camera",
{"enable", "width", "height", "fps", "decimate", "enable_infra1",
"enable_infra2", "prefer_global_time"});
if (!r.ok()) return r;
}
out->sensors.camera_enable = c.get<bool>("enable", true);
out->sensors.camera_width = static_cast<uint32_t>(c.get<int>("width", 640));
out->sensors.camera_height = static_cast<uint32_t>(c.get<int>("height", 480));
out->sensors.camera_hz = c.get<double>("fps", 30.0);
out->sensors.camera_decimate = static_cast<uint32_t>(c.get<int>("decimate", 2));
const ConfigNode mc = root["mcu"];
{
const StatusResponse r =
Reject(mc, "sensors.yaml mcu",
{"port", "baud", "sync_window", "max_skew_warn",
"expected_imu_rate_hz", "ticks_per_rev"});
if (!r.ok()) return r;
}
out->sensors.imu_hz = mc.get<double>("expected_imu_rate_hz", 200.0);
}
// ---------- pipeline.yaml ----------
{
ConfigNode root;
const StatusResponse st = Open(dir, kPipelineConfigFile, &root);
if (!st.ok()) return st;
{
const StatusResponse r =
Reject(root, "pipeline.yaml",
{"ekf", "depth_filter", "gravity_align", "cliff_detect"});
if (!r.ok()) return r;
}
const ConfigNode e = root["ekf"];
{
const StatusResponse r =
Reject(e, "pipeline.yaml ekf",
{"q_x", "q_y", "q_yaw", "q_vx", "q_vyaw", "max_dt"});
if (!r.ok()) return r;
}
out->ekf.q_x = e.get<double>("q_x", out->ekf.q_x);
out->ekf.q_y = e.get<double>("q_y", out->ekf.q_y);
out->ekf.q_yaw = e.get<double>("q_yaw", out->ekf.q_yaw);
out->ekf.q_vx = e.get<double>("q_vx", out->ekf.q_vx);
out->ekf.q_vyaw = e.get<double>("q_vyaw", out->ekf.q_vyaw);
out->ekf.sensor_timeout = e.get<double>("max_dt", out->ekf.sensor_timeout);
const ConfigNode d = root["depth_filter"];
{
const StatusResponse r =
Reject(d, "pipeline.yaml depth_filter",
{"min_range", "max_range", "voxel_size", "max_rate",
"enable_temporal", "min_hits", "temporal_window"});
if (!r.ok()) return r;
}
DepthFilterConfig& df = out->perception.filter;
df.min_range = d.get<double>("min_range", df.min_range);
df.max_range = d.get<double>("max_range", df.max_range);
df.voxel_size = d.get<double>("voxel_size", df.voxel_size);
df.max_rate = d.get<double>("max_rate", df.max_rate);
df.enable_temporal = d.get<bool>("enable_temporal", df.enable_temporal);
df.min_hits = d.get<int>("min_hits", df.min_hits);
df.temporal_window = d.get<double>("temporal_window", df.temporal_window);
const ConfigNode ga = root["gravity_align"];
{
const StatusResponse r =
Reject(ga, "pipeline.yaml gravity_align",
{"alpha", "accel_lpf_alpha", "accel_gate", "use_odom_accel",
"odom_accel_alpha", "min_height", "max_height"});
if (!r.ok()) return r;
}
GravityAlignConfig& g = out->perception.gravity;
g.alpha = ga.get<double>("alpha", g.alpha);
g.accel_lpf_alpha = ga.get<double>("accel_lpf_alpha", g.accel_lpf_alpha);
g.accel_gate = ga.get<double>("accel_gate", g.accel_gate);
g.use_odom_accel = ga.get<bool>("use_odom_accel", g.use_odom_accel);
g.odom_accel_alpha = ga.get<double>("odom_accel_alpha", g.odom_accel_alpha);
g.min_height = ga.get<double>("min_height", g.min_height);
g.max_height = ga.get<double>("max_height", g.max_height);
// HE QUA cua robot.yaml, khong doc tu pipeline.yaml.
g.wheel_radius = geom.wheel_radius;
const ConfigNode cd = root["cliff_detect"];
{
// `nominal_tz` va `wheel_radius` CO Y khong nam trong danh sach nay:
// dat chung o pipeline.yaml se tao ra mot ban sao thu hai cua mot gia
// tri da co trong robot.yaml. Go chung vao file se bao "khoa la".
const StatusResponse r =
Reject(cd, "pipeline.yaml cliff_detect",
{"enabled", "min_dist", "max_dist", "cliff_margin",
"pitch_uncertainty_deg", "pixel_step", "min_neighbors",
"min_cluster", "imu_timeout", "require_accel_ok", "self_level",
"min_level_samples", "level_gate", "max_level_slope",
"max_level_residual", "max_obstructed_frac", "max_level_offset",
"max_tz_dev", "fail_safe", "fail_safe_after"});
if (!r.ok()) return r;
}
CliffDetectConfig& cf = out->perception.cliff;
cf.enabled = cd.get<bool>("enabled", cf.enabled);
cf.min_dist = cd.get<double>("min_dist", cf.min_dist);
cf.max_dist = cd.get<double>("max_dist", cf.max_dist);
cf.cliff_margin = cd.get<double>("cliff_margin", cf.cliff_margin);
cf.pitch_uncertainty_deg =
cd.get<double>("pitch_uncertainty_deg", cf.pitch_uncertainty_deg);
cf.pixel_step = cd.get<int>("pixel_step", cf.pixel_step);
cf.min_neighbors = cd.get<int>("min_neighbors", cf.min_neighbors);
cf.min_cluster = cd.get<int>("min_cluster", cf.min_cluster);
cf.imu_timeout = cd.get<double>("imu_timeout", cf.imu_timeout);
cf.require_accel_ok = cd.get<bool>("require_accel_ok", cf.require_accel_ok);
cf.self_level = cd.get<bool>("self_level", cf.self_level);
cf.min_level_samples = cd.get<int>("min_level_samples", cf.min_level_samples);
cf.level_gate = cd.get<double>("level_gate", cf.level_gate);
cf.max_level_slope = cd.get<double>("max_level_slope", cf.max_level_slope);
cf.max_level_residual =
cd.get<double>("max_level_residual", cf.max_level_residual);
cf.max_obstructed_frac =
cd.get<double>("max_obstructed_frac", cf.max_obstructed_frac);
cf.max_level_offset = cd.get<double>("max_level_offset", cf.max_level_offset);
cf.max_tz_dev = cd.get<double>("max_tz_dev", cf.max_tz_dev);
cf.fail_safe = cd.get<bool>("fail_safe", cf.fail_safe);
cf.fail_safe_after = cd.get<double>("fail_safe_after", cf.fail_safe_after);
// HE QUA cua robot.yaml.
cf.wheel_radius = geom.wheel_radius;
cf.nominal_tz = out->robot.camera_height_above_floor();
}
// ---------- wheel_odom: robot.yaml ----------
{
const WheelOdomNoise& w = out->robot.wheel_odom();
out->wheel_odom.wheel_radius = geom.wheel_radius;
out->wheel_odom.wheel_separation = geom.wheel_separation;
out->wheel_odom.sigma_x = w.sigma_x_per_m;
out->wheel_odom.sigma_y = w.sigma_y_per_m;
out->wheel_odom.sigma_yaw = w.sigma_yaw_per_rad;
out->wheel_odom.slip_omega_threshold = w.slip_threshold;
}
// ---------- safety.yaml ----------
{
ConfigNode root;
const StatusResponse st = Open(dir, kSafetyConfigFile, &root);
if (!st.ok()) return st;
{
const StatusResponse r =
Reject(root, "safety.yaml",
{"scan", "ultrasonic", "cliff", "timeouts", "limits", "bumper"});
if (!r.ok()) return r;
}
const ConfigNode sc = root["scan"];
{
const StatusResponse r =
Reject(sc, "safety.yaml scan",
{"stop_distance", "slow_distance", "slow_factor", "front_angle",
"min_valid_range", "min_front_rays"});
if (!r.ok()) return r;
}
SafetyConfig& sf = out->safety;
sf.stop_distance = sc.get<double>("stop_distance", sf.stop_distance);
sf.slow_distance = sc.get<double>("slow_distance", sf.slow_distance);
sf.slow_factor = sc.get<double>("slow_factor", sf.slow_factor);
sf.front_angle = sc.get<double>("front_angle", sf.front_angle);
sf.min_valid_range = sc.get<double>("min_valid_range", sf.min_valid_range);
sf.min_front_rays = sc.get<int>("min_front_rays", sf.min_front_rays);
const ConfigNode us = root["ultrasonic"];
{
const StatusResponse r = Reject(us, "safety.yaml ultrasonic", {"us_stop_distance"});
if (!r.ok()) return r;
}
sf.us_stop_distance = us.get<double>("us_stop_distance", sf.us_stop_distance);
const ConfigNode cl = root["cliff"];
{
const StatusResponse r = Reject(
cl, "safety.yaml cliff", {"enable_cliff_stop", "cliff_timeout", "cliff_hold"});
if (!r.ok()) return r;
}
sf.enable_cliff_stop = cl.get<bool>("enable_cliff_stop", sf.enable_cliff_stop);
sf.cliff_timeout = cl.get<double>("cliff_timeout", sf.cliff_timeout);
sf.cliff_hold = cl.get<double>("cliff_hold", sf.cliff_hold);
const ConfigNode to = root["timeouts"];
{
const StatusResponse r =
Reject(to, "safety.yaml timeouts", {"sensor_timeout", "cmd_timeout"});
if (!r.ok()) return r;
}
sf.sensor_timeout = to.get<double>("sensor_timeout", sf.sensor_timeout);
sf.cmd_timeout = to.get<double>("cmd_timeout", sf.cmd_timeout);
const ConfigNode li = root["limits"];
{
const StatusResponse r = Reject(li, "safety.yaml limits", {"max_linear", "max_angular"});
if (!r.ok()) return r;
}
sf.max_linear = li.get<double>("max_linear", sf.max_linear);
sf.max_angular = li.get<double>("max_angular", sf.max_angular);
const ConfigNode bu = root["bumper"];
{
const StatusResponse r = Reject(bu, "safety.yaml bumper",
{"escape_linear", "escape_angular"});
if (!r.ok()) return r;
}
sf.escape_linear = bu.get<double>("escape_linear", sf.escape_linear);
sf.escape_angular = bu.get<double>("escape_angular", sf.escape_angular);
// --- Kiem CHEO voi robot.yaml, khong tin mot trong hai ---
//
// safety.cmd_timeout phai DAI hon base.cmd_timeout. Neu ngan hon thi base
// da tu dung robot truoc, va nhanh NO_CMD cua FSM khong bao gio chay --
// tuc la mot nhanh an toan ton tai tren giay ma khong bao gio duoc thu.
if (sf.cmd_timeout <= out->robot.base().cmd_timeout) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"safety.yaml timeouts.cmd_timeout (" + std::to_string(sf.cmd_timeout) +
") phai LON HON robot.yaml base.cmd_timeout (" +
std::to_string(out->robot.base().cmd_timeout) +
") -- neu khong, base tu dung truoc va nhanh NO_CMD khong bao gio chay");
}
// Gioi han cua safety khong duoc VUOT gioi han co hoc cua base.
if (sf.max_linear > out->robot.base().max_linear + 1e-9 ||
sf.max_angular > out->robot.base().max_angular + 1e-9) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"safety.yaml limits vuot qua robot.yaml base -- lop an toan khong "
"duoc phep cho phep nhieu hon phan cung chiu duoc");
}
// Toc do thoat khi bumper dang chot khong duoc vuot gioi han thuong.
//
// Phia sau KHONG co cam bien nao che, va robot dang CHAM vao vat gi do --
// day la luc nguy hiem nhat, khong phai luc de di nhanh hon.
if (sf.escape_linear > sf.max_linear + 1e-9 ||
sf.escape_angular > sf.max_angular + 1e-9) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"safety.yaml bumper.escape_* vuot qua limits.max_* -- toc do THOAT "
"khi dang cham vat can khong duoc lon hon toc do binh thuong");
}
if (sf.escape_linear <= 0.0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"safety.yaml bumper.escape_linear phai > 0 -- bang 0 nghia la robot "
"dam roi nam vinh vien tai cho, khong lui ra duoc de reset");
}
// Vuc bien mat khoi tam nhin khi lai gan hon min_dist, nen cliff_hold
// phai du dai de phu quang duong do. Duoi 1 s la gan nhu chac chan lot.
if (sf.enable_cliff_stop && sf.cliff_hold < 1.0) {
VSLAM_WARN("safety.yaml cliff.cliff_hold = "
<< sf.cliff_hold
<< " s. Vuc bien mat khoi tam nhin camera khi lai gan hon "
<< out->perception.cliff.min_dist
<< " m; gia tri nay nhieu kha nang qua ngan.");
}
}
// ---------- cliff.min_dist co khop HINH HOC camera khong ----------
//
// `min_dist` KHONG phai mot tham so chinh duoc tuy y: no la vung mu HINH
// HOC. Tia duoi cung cua truong nhin cham san o
// d = z_camera / tan(pitch + vfov/2)
// va duoi d do khong mot tia nao cham san -- detector im lang hoan toan.
//
// Doi `camera_pitch` trong robot.yaml ma quen sua `min_dist` trong
// pipeline.yaml la mot kieu hong IM LANG: cliff_detect van chay, van bao
// "judged", chi la no dang nhin vao mot dai khong co du lieu.
//
// ⚠️ CANH BAO chu khong TU CHOI: `vfov` o day la mac dinh cua D410
// (42 do), CHUA doi chieu voi CameraInfo that. Tu choi khoi dong dua tren
// mot so chua xac minh la sai. Khi driver camera chay tren thiet bi that
// thi thay bang vfov do duoc va co the siet thanh loi.
{
constexpr double kD410VfovRad = 0.733; // 42 do, mac dinh -- CHUA XAC MINH
const double cam_h = out->robot.camera_height_above_floor();
const double drop = out->robot.camera_pitch() + kD410VfovRad / 2.0;
if (drop > 1e-3 && drop < 1.5 && cam_h > 0.0) {
const double geom_min = cam_h / std::tan(drop);
const double got = out->perception.cliff.min_dist;
if (std::fabs(got - geom_min) > 0.15) {
VSLAM_WARN("pipeline.yaml cliff_detect.min_dist = "
<< got << " m, nhung hinh hoc camera cho "
<< geom_min << " m (cao " << cam_h << " m, chuc "
<< out->robot.camera_pitch() * 180.0 / kPi << " do, vfov 42 do). "
<< "Dat THAP hon vung mu that thi detector nhin vao dai "
"khong co du lieu; dat CAO hon thi bo phi tam nhin.");
}
}
}
// ---------- slam.yaml ----------
#ifdef VSLAM_HAVE_SLAM
{
ConfigNode root;
const StatusResponse st = Open(dir, kSlamConfigFile, &root);
if (!st.ok()) return st;
// Ten key RTAB-Map duoc kiem trong BuildRtabmapParams (doi chieu voi bang
// mac dinh cua chinh RTAB-Map), nen o day khong kiem lai.
try {
out->slam = LoadRtabmapConfig(root);
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
std::string("slam.yaml: ") + e.what());
}
}
#endif
// ---------- system.yaml ----------
{
ConfigNode root;
const StatusResponse st = Open(dir, kSystemConfigFile, &root);
if (!st.ok()) return st;
{
const StatusResponse r =
Reject(root, "system.yaml",
{"web", "logging", "record", "threads", "watchdog"});
if (!r.ok()) return r;
}
const ConfigNode w = root["web"];
{
const StatusResponse r =
Reject(w, "system.yaml web",
{"port", "bind", "auth_token", "asset_dir", "status_rate_hz",
"scan_rate_hz", "cloud_rate_hz", "path_rate_hz",
"cloud_max_points", "cloud_quant_m", "map_rebuild_rate_hz"});
if (!r.ok()) return r;
}
out->web.port = static_cast<uint16_t>(w.get<int>("port", 8080));
out->web.bind_address = w.get<std::string>("bind", out->web.bind_address);
out->web.auth_token = w.get<std::string>("auth_token", "");
out->web.asset_dir = w.get<std::string>("asset_dir", "");
out->web.state_hz = w.get<double>("status_rate_hz", out->web.state_hz);
out->web.scan_hz = w.get<double>("scan_rate_hz", out->web.scan_hz);
out->web.cloud_hz = w.get<double>("cloud_rate_hz", out->web.cloud_hz);
out->web.path_hz = w.get<double>("path_rate_hz", out->web.path_hz);
out->web.cloud_max_points =
static_cast<uint32_t>(w.get<int>("cloud_max_points", 4000));
out->slam_runtime.map_rebuild_rate_hz =
w.get<double>("map_rebuild_rate_hz", out->slam_runtime.map_rebuild_rate_hz);
if (out->web.auth_token.empty()) {
// Khong tu choi khoi dong: mot robot trong phong lab khong can token.
// Nhung phai TO, vi bat doi xung cua lop xac thuc (go e-stop can token)
// tro nen vo nghia khi khong co token nao.
VSLAM_WARN("system.yaml web.auth_token DE TRONG -- bat ky ai vao duoc "
"mang deu GO duoc e-stop va reset duoc bumper.");
}
const ConfigNode lg = root["logging"];
{
const StatusResponse r = Reject(lg, "system.yaml logging", {"level"});
if (!r.ok()) return r;
}
out->log_level = lg.get<std::string>("level", "info");
const ConfigNode rc = root["record"];
{
const StatusResponse r =
Reject(rc, "system.yaml record",
{"enabled", "dir", "max_queue_bytes", "depth_rate_hz",
"record_infra1", "record_infra2", "compress"});
if (!r.ok()) return r;
}
out->record.enabled = rc.get<bool>("enabled", false);
out->record.dir = rc.get<std::string>("dir", out->record.dir);
out->record.max_queue_bytes =
static_cast<size_t>(rc.get<int>("max_queue_bytes", 67108864));
out->record.depth_rate_hz = rc.get<double>("depth_rate_hz", 10.0);
out->record.record_infra1 = rc.get<bool>("record_infra1", false);
out->record.record_infra2 = rc.get<bool>("record_infra2", false);
out->record.compress = rc.get<bool>("compress", false);
const ConfigNode th = root["threads"];
{
const StatusResponse r =
Reject(th, "system.yaml threads",
{"safety_priority", "driver_priority", "estimator_priority",
"use_realtime", "safety_rate_hz"});
if (!r.ok()) return r;
}
out->threads.safety_priority = th.get<int>("safety_priority", 50);
out->threads.driver_priority = th.get<int>("driver_priority", 45);
out->threads.estimator_priority = th.get<int>("estimator_priority", 40);
out->threads.use_realtime = th.get<bool>("use_realtime", true);
out->threads.safety_rate_hz = th.get<double>("safety_rate_hz", 20.0);
// Luong safety phai co uu tien CAO NHAT. Dat nguoc lai la vo hieu hoa ca
// ly do dung SCHED_FIFO.
if (out->threads.use_realtime &&
(out->threads.safety_priority <= out->threads.driver_priority ||
out->threads.safety_priority <= out->threads.estimator_priority)) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"system.yaml threads: safety_priority phai CAO HON moi uu tien khac");
}
}
return StatusResponse::Ok();
}
} // namespace vslam

112
app/src/app_config.h Normal file
View File

@@ -0,0 +1,112 @@
#ifndef VSLAM_APP_APP_CONFIG_H
#define VSLAM_APP_APP_CONFIG_H
// Nap sau file YAML thanh cac struct config ma tung lib da dinh nghia.
//
// ================== VI SAO O `app/` CHU KHONG O TUNG LIB ==================
// Thiet ke sach hon la "moi lib tu doc config cua no". Nhung lam vay bat moi
// lib phu thuoc yaml-cpp, ke ca `vslam_odometry` va `vslam_safety` -- hai lib
// ma ca ly do ton tai la KHONG co dep ngoai nao, de review duoc doc lap va
// build duoc truoc moi thu khac.
//
// Nen phep nap nam o day. Doi lai, moi khi them mot truong config thi phai
// sua hai cho. De giam cho do: MOI khoi deu goi `UnknownKeys()` va TU CHOI
// khoi dong khi co khoa la, nen mot truong duoc them vao YAML ma quen noi o
// day se bao loi ngay chu khong am tham bi bo qua.
//
// ================== KHONG CO GIA TRI NAO O HAI NOI ==================
// `cliff_detect.nominal_tz` KHONG doc tu pipeline.yaml -- no la he qua cua
// robot.yaml (camera_link.z + wheel_radius) va duoc dat tu `RobotModel`.
// Tuong tu, gioi han base trong safety.yaml duoc KIEM cheo voi robot.yaml
// thay vi tin mot trong hai.
#include <string>
#include "vslam/cliff_detect.h"
#include "vslam/depth_filter.h"
#include "vslam/ekf_se2.h"
#include "vslam/gravity_align.h"
#include "vslam/perception_pipeline.h"
#include "vslam/robot_model.h"
#include "vslam/safety_monitor.h"
#include "vslam/scan_sanitizer.h"
#include "vslam/vslam_common.h"
#include "vslam/web_server.h"
#include "vslam/wheel_odometry.h"
#ifdef VSLAM_HAVE_SLAM
#include "vslam/rtabmap_params.h"
#endif
namespace vslam {
// Tan so toi da dung lai occupancy grid tu do thi SLAM. Xem system.yaml.
struct SlamRuntimeConfig {
double map_rebuild_rate_hz = 0.5;
};
struct ThreadConfig {
int safety_priority = 50;
int driver_priority = 45;
int estimator_priority = 40;
bool use_realtime = true;
double safety_rate_hz = 20.0;
};
struct RecordConfig {
bool enabled = false;
std::string dir = "/var/lib/vslam/records";
size_t max_queue_bytes = 64u * 1024u * 1024u;
double depth_rate_hz = 10.0;
bool record_infra1 = false;
bool record_infra2 = false;
bool compress = false;
};
struct SensorRates {
double lidar_hz = 25.0;
double camera_hz = 30.0;
double imu_hz = 200.0;
bool camera_enable = true;
uint32_t camera_width = 640;
uint32_t camera_height = 480;
uint32_t camera_decimate = 2;
};
// Toan bo cau hinh cua mot lan chay.
struct AppConfig {
RobotModel robot; // robot.yaml -- nguon DUY NHAT cho hinh hoc
ScanSanitizerConfig sanitizer; // sensors.yaml
SensorRates sensors;
WheelOdometryConfig wheel_odom; // robot.yaml + pipeline.yaml
EkfSe2Config ekf; // pipeline.yaml
PerceptionConfig perception; // pipeline.yaml + robot.yaml
SafetyConfig safety; // safety.yaml
#ifdef VSLAM_HAVE_SLAM
RtabmapConfig slam; // slam.yaml
#endif
WebConfig web; // system.yaml
ThreadConfig threads;
SlamRuntimeConfig slam_runtime;
RecordConfig record;
std::string log_level = "info";
AppConfig() = default;
AppConfig(const AppConfig&) = delete;
AppConfig& operator=(const AppConfig&) = delete;
};
// Nap tat ca tu `dir` (mac dinh `ConfigDir()`).
//
// Tra loi dau tien gap phai, KHONG gom het: mot file config sai thi cac gia
// tri sau no khong con dang tin, va mot danh sach dai lam nguoi doc bo qua
// dong dau.
StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out);
} // namespace vslam
#endif // VSLAM_APP_APP_CONFIG_H

239
app/src/main.cc Normal file
View File

@@ -0,0 +1,239 @@
// vslam_node -- tien trinh duy nhat.
//
// Thay cho `roslaunch robot_bringup bringup.launch` + 20 file .launch + 14
// file YAML + roscore.
//
// vslam_node --sim chay voi bo mo phong
// vslam_node --sim --map nha.yaml mo phong tren ban do that
// vslam_node --replay X.vsr phat lai ban ghi
// vslam_node --live phan cung that (driver CHUA viet)
//
// Doc `src/wiring.cc` de hieu he thong: no la noi duy nhat noi nguon voi
// stage.
#include <atomic>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>
#include "app_config.h"
#include "runtime.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace {
std::atomic<bool> g_stop{false};
vslam::Runtime* g_runtime = nullptr;
void OnSignal(int) {
g_stop.store(true);
// Chi dat co va goi RequestStop -- ca hai deu an toan trong signal handler
// vi chung chi cham vao atomic. KHONG log, khong cap phat: hai thu do
// khong async-signal-safe va mot lan treo o day la mot lan phai rut dien.
if (g_runtime != nullptr) g_runtime->RequestStop();
}
void Usage(const char* argv0) {
std::printf(
"cach dung: %s [--sim | --replay FILE | --live] [tuy chon]\n"
"\n"
" --sim chay voi bo mo phong (thay Gazebo)\n"
" --replay FILE phat lai ban ghi .vsr\n"
" --live phan cung that (driver CHUA viet)\n"
"\n"
" --config DIR thu muc cau hinh (mac dinh: $VSLAM_CONFIG_DIR\n"
" hoac %s)\n"
" --map FILE.yaml ban do cho --sim; khong co thi dung the gioi\n"
" tong hop\n"
" --world FILE.world the gioi Gazebo cho --sim. Raster hoa mesh va\n"
" cham -> luoi; uu tien hon --map\n"
" --x X --y Y --yaw R vi tri xuat phat cho --sim\n"
" --port N ghi de system.yaml web.port\n"
" --token S ghi de system.yaml web.auth_token\n"
" --sim-glass-at X dat buc KINH ngang hanh lang o x = X m.\n"
" LiDAR/depth KHONG thay; chi sieu am + bumper.\n"
" --max-speed V ghi de tran toc do (m/s). CHI CHO MO PHONG --\n"
" base that gioi han o robot.yaml base.max_linear\n"
" --slam bat SLAM (ghi de slam.yaml enabled)\n"
" --slam-db PATH ghi de slam.yaml database_path;\n"
" \"\" = DB trong RAM, khong de lai gi tren dia\n"
" --slam-mode M mapping | localization (ghi de slam.yaml)\n"
" --slam-init-pose x,y,yaw\n"
" pose ban dau cho localization -- tuong duong\n"
" /initialpose. BAT BUOC tren robot that: RTAB-Map\n"
" khong dinh vi toan cuc duoc bang scan khong.\n"
" --check nap va KIEM cau hinh roi thoat, khong chay gi\n",
argv0, vslam::ConfigDir().c_str());
}
// Sau khi nap cau hinh that bai, CHI THANG cach sua neu doan duoc.
//
// Loi "khong mo duoc file" mot minh la vo ich: no noi cai gi hong nhung khong
// noi phai lam gi. Truong hop pho bien nhat la chay binary tu CAY NGUON trong
// khi `ConfigDir()` tro toi duong dan CAI DAT (/etc/vslam/...) -- va khi do
// thu muc dung dang nam ngay canh, trong thu muc hien tai.
//
// ⚠️ CHI GOI Y, khong tu nap. Am tham nap mot bo cau hinh khac voi cai nguoi
// van hanh tuong la dung lop bug ma ca du an nay chong: xem ghi chu "KHONG
// mac dinh sang --sim" ben duoi.
void SuggestConfigDir(const std::string& tried) {
// Thu muc da thu CO `robot.yaml` khong?
//
// Neu CO thi duong dan dung -- loi nam o NOI DUNG file (go sai khoa, cong
// kiem cheo khong qua...). Goi y doi thu muc luc do la nhieu, va con day
// nguoi doc di sai huong.
//
// Day cung la cach phan biet duy nhat dang tin: `LoadAppConfig` tra cung
// ma loi cho ca "khong mo duoc file" lan "gia tri sai".
{
std::ifstream at_tried(tried + "/" + vslam::kRobotConfigFile);
if (at_tried) return;
}
const std::string local = "configuration_files";
// Co `./configuration_files/robot.yaml` ngay canh khong?
std::ifstream probe(local + "/" + vslam::kRobotConfigFile);
if (!probe) return;
std::fprintf(stderr,
"\n Dang chay tu cay nguon? Thu muc cau hinh nam ngay canh:\n"
" export VSLAM_CONFIG_DIR=$PWD/%s\n"
" hoac chi cho lan chay nay:\n"
" --config %s\n",
local.c_str(), local.c_str());
if (std::getenv(vslam::kConfigDirEnv) == nullptr) {
std::fprintf(stderr, " (%s dang KHONG duoc dat)\n", vslam::kConfigDirEnv);
}
}
} // namespace
int main(int argc, char** argv) {
vslam::RuntimeOptions opts;
std::string config_dir = vslam::ConfigDir();
bool have_source = false;
bool check_only = false;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--sim") { opts.source = vslam::SourceKind::kSim; have_source = true; }
else if (a == "--replay") {
opts.source = vslam::SourceKind::kReplay;
opts.replay_path = next();
have_source = true;
} else if (a == "--live") {
opts.source = vslam::SourceKind::kLive;
have_source = true;
}
else if (a == "--config") config_dir = next();
else if (a == "--map") opts.map_yaml = next();
else if (a == "--world") opts.world_path = next();
else if (a == "--x") opts.sim_start_x = std::atof(next().c_str());
else if (a == "--y") opts.sim_start_y = std::atof(next().c_str());
else if (a == "--yaw") opts.sim_start_yaw = std::atof(next().c_str());
else if (a == "--port")
opts.port_override = static_cast<uint16_t>(std::atoi(next().c_str()));
else if (a == "--token") opts.token_override = next();
else if (a == "--sim-glass-at") opts.sim_glass_at = std::atof(next().c_str());
else if (a == "--max-speed") opts.max_speed_override = std::atof(next().c_str());
else if (a == "--slam") opts.force_slam = true;
else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; }
else if (a == "--slam-mode") opts.slam_mode_override = next();
else if (a == "--slam-init-pose") {
const std::string v = next();
if (std::sscanf(v.c_str(), "%lf,%lf,%lf", &opts.slam_init_pose.x,
&opts.slam_init_pose.y, &opts.slam_init_pose.theta) != 3) {
std::fprintf(stderr, "--slam-init-pose can dang x,y,yaw\n");
return 2;
}
opts.have_slam_init_pose = true;
}
else if (a == "--check") check_only = true;
else if (a == "--help" || a == "-h") { Usage(argv[0]); return 0; }
else {
std::fprintf(stderr, "tham so la: %s\n\n", a.c_str());
Usage(argv[0]);
return 2;
}
}
if (!have_source && !check_only) {
// KHONG mac dinh sang --sim. Mot node am tham chay mo phong trong khi
// nguoi van hanh tuong no dang doc cam bien that la kieu hong te nhat co
// the nghi ra.
std::fprintf(stderr,
"phai chon mot nguon: --sim, --replay FILE, hoac --live\n\n");
Usage(argv[0]);
return 2;
}
// --- Cau hinh ---
vslam::AppConfig cfg;
{
const vslam::StatusResponse st = vslam::LoadAppConfig(config_dir, &cfg);
if (!st.ok()) {
std::fprintf(stderr, "cau hinh (%s): %s\n", config_dir.c_str(),
st.message.c_str());
SuggestConfigDir(config_dir);
return 1;
}
}
if (cfg.log_level == "debug") vslam::SetLogLevel(vslam::LogLevel::kDebug);
else if (cfg.log_level == "warn") vslam::SetLogLevel(vslam::LogLevel::kWarn);
else if (cfg.log_level == "error") vslam::SetLogLevel(vslam::LogLevel::kError);
else vslam::SetLogLevel(vslam::LogLevel::kInfo);
if (check_only) {
std::printf("cau hinh OK: %s\n", config_dir.c_str());
std::printf(" banh : r=%.4f m, cach nhau %.4f m\n",
cfg.robot.geometry().wheel_radius,
cfg.robot.geometry().wheel_separation);
std::printf(" camera cao : %.4f m so voi san, chuc %.2f do\n",
cfg.robot.camera_height_above_floor(),
cfg.robot.camera_pitch() * 180.0 / 3.14159265358979323846);
std::printf(" safety dung : %.3f m, cham lai tu %.3f m\n",
cfg.safety.stop_distance, cfg.safety.slow_distance);
std::printf(" cliff cua so : %.2f - %.2f m (duoi %.2f m la VUNG MU)\n",
cfg.perception.cliff.min_dist, cfg.perception.cliff.max_dist,
cfg.perception.cliff.min_dist);
std::printf(" web : %s:%u%s\n", cfg.web.bind_address.c_str(),
cfg.web.port,
cfg.web.auth_token.empty() ? " (KHONG CO TOKEN)" : "");
return 0;
}
// --- Chay ---
vslam::Runtime runtime(&cfg, opts);
g_runtime = &runtime;
std::signal(SIGINT, OnSignal);
std::signal(SIGTERM, OnSignal);
{
const vslam::StatusResponse st = runtime.Start();
if (!st.ok()) {
std::fprintf(stderr, "khong khoi dong duoc: %s\n", st.message.c_str());
return 1;
}
}
std::printf("\n vslam_node dang chay\n");
std::printf(" nguon : %s\n",
opts.source == vslam::SourceKind::kSim ? "mo phong"
: opts.source == vslam::SourceKind::kReplay ? opts.replay_path.c_str()
: "phan cung");
std::printf(" web UI : http://localhost:%u\n",
opts.port_override != 0 ? opts.port_override : cfg.web.port);
std::printf(" cau hinh : %s\n", config_dir.c_str());
std::printf(" Ctrl-C de dung\n\n");
runtime.Join();
g_runtime = nullptr;
std::printf("da dung.\n");
return 0;
}

846
app/src/runtime.cc Normal file
View File

@@ -0,0 +1,846 @@
#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;
};
Runtime::Runtime(AppConfig* cfg, RuntimeOptions opts)
: cfg_(cfg), opts_(std::move(opts)), source_(new SourceHolder) {}
Runtime::~Runtime() {
RequestStop();
Join();
}
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 = cfg_->robot.base().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.");
}
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:
// Noi thang: driver LakiBeam / RealSense / base chua viet, va chung bi
// chan boi thong tin chua co (byte layout goi UDP, giao thuc encoder
// cua base), khong phai boi thoi gian.
return StatusResponse::Error(
StatusCode::kUnavailable,
"che do --live chua chay duoc: driver LakiBeam, RealSense va base "
"chua viet. Chung bi chan boi thong tin phan cung chua co -- xem "
"README muc \"P2 lam duoc den dau\". Dung --sim hoac --replay.");
}
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;
} else {
speed_limit_ = cfg_->robot.base().max_linear;
}
{
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;
}
if (lidar_ != nullptr) lidar_->Open();
if (mcu_ != nullptr) mcu_->Open();
if (base_ != nullptr) base_->Open();
if (camera_ != nullptr) camera_->Open();
// 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();
}
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_);
odom = wheel_odom_->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;
slam_localized_ = out.localized;
slam_process_ms_ = out.process_ms;
if (out.loop_closure_id > 0) slam_loops_++;
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;
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;
{
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();
}
{
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;
snap.ground_truth = 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.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).
{
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

255
app/src/runtime.h Normal file
View File

@@ -0,0 +1,255 @@
#ifndef VSLAM_APP_RUNTIME_H
#define VSLAM_APP_RUNTIME_H
// Tien trinh duy nhat. So huu moi luong va moi stage.
//
// ================== BAN DO LUONG ==================
// luong tan so uu tien lam gi
// ------------------------------------------------------------------
// safety 20 Hz SCHED_FIFO 50 DUONG DUY NHAT toi motor
// source theo nguon FIFO 45 driver / sim / replay
// web_tx 10 Hz CFS serialize va phat
//
// Cac stage con lai chay INLINE trong callback cua nguon, tren luong source.
// Do la co y: chuoi perception (depth -> cloud -> loc -> can trong luc ->
// cliff) tung la ba nodelet chung mot manager; o day no la ba loi goi ham
// trong mot ham. Khong intrusive_ptr, khong dispatch theo topic, va thu tu
// buoc la thu tu dong lenh.
//
// ================== QUY TAC SONG CON ==================
// Luong `safety` KHONG chia se mutex nao voi luong `slam`.
// `Rtabmap::process()` chan 100-600 ms; mot mutex chung la du de treo vong an
// toan trong ngan do.
//
// Trong ban ROS dieu nay duoc bao dam MIEN PHI boi tien trinh rieng +
// respawn="true". O day no la quy tac review, va chi ThreadSanitizer moi kiem
// duoc. Cac mutex duoi day duoc dat ten theo DU LIEU chung bao ve, khong
// theo luong, de review thay ngay cai nao cham vao cai nao.
#include <atomic>
#include <memory>
#include <map>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "app_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/ekf_se2.h"
#include "vslam/perception_pipeline.h"
#include "vslam/safety_monitor.h"
#include "vslam/scan_sanitizer.h"
#include "vslam/teleop_model.h"
#include "vslam/web_server.h"
#include "vslam/wheel_odometry.h"
#ifdef VSLAM_HAVE_SLAM
#include "vslam/rtabmap_slam.h"
#endif
namespace vslam {
// Nguon du lieu: sim, replay, hay phan cung that. `vslam_node` KHONG phan
// biet duoc -- do la ca ly do cac interface driver ton tai.
enum class SourceKind { kSim, kReplay, kLive };
struct RuntimeOptions {
SourceKind source = SourceKind::kSim;
std::string replay_path;
std::string map_yaml; // chi co nghia voi sim
std::string world_path; // .world cua Gazebo; uu tien hon map_yaml
double sim_start_x = 0.0, sim_start_y = 0.0, sim_start_yaw = 0.0;
uint16_t port_override = 0; // 0 = dung system.yaml
std::string token_override;
// Tran toc do, GHI DE ca robot.yaml lan safety.yaml. 0 = khong ghi de.
//
// ⚠️ CHO MO PHONG. `robot.yaml base.max_linear = 0.35` la gioi han CO HOC
// that cua base; co nay khong lam base that chay nhanh hon, no chi go tran
// trong mo phong de quet mot toa nha 58 m khong mat nua tieng.
//
// Phai ghi de CA HAI: lop safety kep lenh o `safety.yaml max_linear`, nen
// chi nang tran teleop thoi thi so tren man hinh len 2.0 con robot van chay
// 0.35 -- do dung la thu da xay ra truoc khi co co nay.
double max_speed_override = 0.0;
// Dat mot buc KINH chan ngang hanh lang o x = met nay. 0 = khong dat.
// Kinh vo hinh voi LiDAR va depth; chi sieu am thay. Dung de chay nhanh
// US_BLOCKED va BUMPER cua FSM -- hai nhanh chua bao gio chay end-to-end.
double sim_glass_at = 0.0;
bool force_slam = false; // --slam: ghi de slam.yaml enabled
bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM
std::string slam_db;
std::string slam_mode_override; // "mapping" | "localization"
// Pose ban dau cho che do localization -- tuong duong /initialpose cua ban
// ROS, thu ma `dock_init.py` phat tu dock.
bool have_slam_init_pose = false;
Pose2D slam_init_pose;
};
class Runtime {
public:
Runtime(AppConfig* cfg, RuntimeOptions opts);
~Runtime();
Runtime(const Runtime&) = delete;
Runtime& operator=(const Runtime&) = delete;
StatusResponse Start();
void RequestStop();
void Join();
private:
// wiring.cc -- noi duy nhat noi nguon voi stage. Tuong duong toan bo 20
// file .launch cua ban ROS.
StatusResponse Wire();
// runtime.cc
StatusResponse OpenSource();
void SafetyLoop();
void WebLoop();
void SlamLoop();
void ApplyThreadPriority(std::thread* t, int prio, const char* name);
AppConfig* cfg_;
RuntimeOptions opts_;
// --- Nguon ---
// Giu bang con tro kieu co so: node khong biet minh dang chay live, replay
// hay sim. Khong co nhanh `if (replay)` nao trong logic.
struct SourceHolder;
std::unique_ptr<SourceHolder> source_;
LidarInterface* lidar_ = nullptr;
CameraInterface* camera_ = nullptr;
McuInterface* mcu_ = nullptr;
BaseInterface* base_ = nullptr;
ClockPtr clock_;
// --- Stage ---
std::unique_ptr<ScanSanitizer> sanitizer_;
std::unique_ptr<WheelOdometry> wheel_odom_;
std::unique_ptr<EkfSe2> ekf_;
std::unique_ptr<PerceptionPipeline> perception_;
std::unique_ptr<SafetyMonitor> safety_;
std::unique_ptr<TeleopModel> teleop_;
std::unique_ptr<WebServer> web_;
#ifdef VSLAM_HAVE_SLAM
std::unique_ptr<RtabmapSlam> slam_;
#endif
// --- Du lieu chia se, moi mutex bao ve dung mot nhom ---
// scan_mu_: scan da ve sinh gan nhat. Luong source ghi, luong safety va
// web_tx doc.
mutable std::mutex scan_mu_;
LaserScanPtr latest_scan_;
// odom_mu_: wheel_odom_ va ekf_. CHI luong source cham vao chung; hai luong
// kia chi doc ban sao pose.
mutable std::mutex odom_mu_;
Odometry latest_odom_;
bool have_odom_ = false;
// perc_mu_: ket qua perception.
mutable std::mutex perc_mu_;
PointCloudXYZPtr latest_cloud_;
PointCloudXYZPtr latest_cliff_cloud_;
bool cliff_flag_ = false;
UnixTime cliff_stamp_;
bool have_cliff_ = false;
std::string cliff_detail_;
// mcu_mu_: sieu am va bumper.
//
// Hai cam bien nay o tren MCU vi ca hai deu la cam bien MUC THAP phai toi
// duoc vong an toan ke ca khi may tinh chinh dang ban. Luong source ghi,
// luong safety doc o 20 Hz.
mutable std::mutex mcu_mu_;
std::map<std::string, double> ultrasonic_;
UnixTime us_stamp_;
bool have_us_ = false;
bool bumper_ = false;
UnixTime bumper_stamp_;
bool have_bumper_ = false;
// cmd_mu_: lenh teleop THO, chua qua lop an toan.
//
// Luong web ghi, luong safety doc o 20 Hz. Luong web KHONG BAO GIO goi
// thang SetVelocity -- xem ghi chu trong wiring.cc.
mutable std::mutex cmd_mu_;
Twist raw_cmd_;
UnixTime raw_cmd_stamp_;
bool have_raw_cmd_ = false;
// teleop_mu_: TeleopModel co trang thai (toc do dieu chinh duoc luc chay).
mutable std::mutex teleop_mu_;
// safety_mu_: SafetyMonitor. KHONG duoc chia se voi bat ky mutex nao ma
// luong slam cham toi.
mutable std::mutex safety_mu_;
SafetyOutput last_safety_;
// Quy dao de ve len web.
mutable std::mutex traj_mu_;
std::vector<Pose2D> trajectory_;
UnixTime last_traj_stamp_;
// slam_mu_: ket qua cua SLAM.
//
// ⚠️ QUY TAC SONG CON: mutex nay KHONG duoc luong safety cham vao, va luong
// slam KHONG duoc giu bat ky mutex nao trong luc goi `Process()` --
// `Rtabmap::process()` chan 100-600 ms (p95 do duoc 722-1008 ms tren may
// nay). Xem SlamLoop().
//
// Luong slam chi cham `scan_mu_` va `odom_mu_` de COPY mot shared_ptr va
// mot Pose2D, roi nha ngay. Do la khuon mau `Channel::Latest()`: mot lan
// copy duoi mutex, khong bao gio giu lock khi goi code nang.
mutable std::mutex slam_mu_;
Pose2D map_correction_;
bool slam_localized_ = false;
uint64_t slam_map_version_ = 0;
uint64_t slam_published_version_ = 0;
// Thanh phan ban do lan truoc, de chi log KHI DOI. Xem ghi chu o cho log.
size_t last_map_occ_ = 0;
size_t last_map_free_ = 0;
OccupancyGridPtr slam_map_;
double slam_process_ms_ = 0.0;
int slam_loops_ = 0;
// Doc-only sau Start(), nen khong can mutex.
bool slam_enabled_ = false;
bool slam_should_save_ = false;
// Tran toc do dang dung (m/s): tu robot.yaml, hoac --max-speed ghi de.
double speed_limit_ = 0.35;
#ifdef VSLAM_HAVE_SLAM
SlamMode slam_mode_ = SlamMode::kMapping;
#endif
// Nghieng, CHI de hien thi. Luong source ghi o 200 Hz, luong web doc o
// 10 Hz.
//
// ⚠️ ThreadSanitizer da bat dung cho nay: truoc do WebLoop goi thang
// `perception_->gravity().roll()` trong khi luong source dang ghi bien do
// trong `FeedImu`. `GravityAlign` co hop dong la MOT LUONG -- sua bang
// cach them khoa vao thu vien se pha hop dong do va bat moi nguoi dung
// tra gia cho mot nhu cau chi cua rieng web UI.
//
// Ba atomic rieng, KHONG phai mot bo ba nguyen tu: doc co the lay roll cua
// mau N va pitch cua mau N+1. Voi mot so hien tren man hinh o 10 Hz thi
// dieu do vo hai, va noi ro o day con hon gia vo rang no nguyen tu.
std::atomic<double> tilt_roll_{0.0};
std::atomic<double> tilt_pitch_{0.0};
std::atomic<bool> tilt_accel_ok_{false};
std::atomic<bool> estop_{false};
std::atomic<bool> stop_{false};
std::thread source_thread_;
std::thread safety_thread_;
std::thread web_thread_;
std::thread slam_thread_;
};
} // namespace vslam
#endif // VSLAM_APP_RUNTIME_H

234
app/src/wiring.cc Normal file
View File

@@ -0,0 +1,234 @@
// NOI DUY NHAT noi nguon voi stage.
//
// Day la tuong duong cua toan bo 20 file `.launch` cua ban ROS, gom lai thanh
// mot ham doc duoc tu tren xuong. Muon biet du lieu di dau thi doc file nay,
// khong phai grep remap qua 20 file XML.
//
// ================== BON DUONG ==================
// LiDAR -> ScanSanitizer -> {safety, web}
// IMU -> {gravity_align, wheel_odom (gyro), ekf}
// Encoder -> wheel_odom -> {ekf, gravity_align (tru gia toc rieng)}
// Camera -> perception (INLINE) -> {safety (co vuc), web (cloud)}
//
// Lenh di NGUOC lai va chi mot duong:
// web -> teleop -> raw_cmd -> [luong safety] -> base
// Khong nhanh nao cho lenh di thang xuong base. Ke ca e-stop: no dat co, roi
// luong safety thay co va zero lenh trong vong mot chu ky.
#include "runtime.h"
#include "vslam/geometry.h"
#include "vslam/json_parse.h"
#include "vslam/log.h"
#include <cmath>
namespace vslam {
StatusResponse Runtime::Wire() {
// ---------------- LiDAR ----------------
if (lidar_ != nullptr) {
lidar_->SetCallback([this](LaserScanPtr s) {
// Ve sinh MOT lan, ngay tai bien. Moi nguoi doc phia sau nhan cung mot
// ban -- khong ai duoc ve sinh lai, va khong ai thay ban tho.
//
// ScanSanitizer gop header-fix va sector mask lam MOT ham: hai bo loc
// rieng thi "cai nao chay truoc" la mot bay co that.
auto copy = std::make_shared<LaserScan>(*s);
sanitizer_->Apply(copy.get());
std::lock_guard<std::mutex> lk(scan_mu_);
latest_scan_ = copy;
});
}
// ---------------- IMU ----------------
if (mcu_ != nullptr) {
mcu_->SetImuCallback([this](ImuPtr m) {
// gravity_align chay TRUOC: no o 200 Hz va re, va cliff_detect can
// nghieng moi nhat.
perception_->FeedImu(*m);
// Cong bo nghieng cho luong web. Phai qua atomic: `GravityAlign` thuoc
// ve luong nay va khong tu khoa -- doc thang tu luong khac la data
// race, va ThreadSanitizer da bat dung no.
tilt_roll_.store(perception_->gravity().roll(), std::memory_order_relaxed);
tilt_pitch_.store(perception_->gravity().pitch(), std::memory_order_relaxed);
tilt_accel_ok_.store(perception_->gravity().accel_ok(),
std::memory_order_relaxed);
std::lock_guard<std::mutex> lk(odom_mu_);
wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z);
ekf_->UpdateImuYawRate(m->header.stamp, m->angular_velocity.z,
m->angular_velocity_covariance[8] > 0.0
? m->angular_velocity_covariance[8]
: 2.4e-7);
});
}
// ---------------- Sieu am + bumper ----------------
if (mcu_ != nullptr) {
mcu_->SetUltrasonicCallback([this](const UltrasonicReading& u) {
std::lock_guard<std::mutex> lk(mcu_mu_);
ultrasonic_.clear();
for (size_t i = 0; i < u.count; ++i) {
// GIU CA NaN. Truoc day o day loc NaN di, va do la sai: map rong
// trong y het "khong lap sieu am", nen mot day cam bien DUT hoan
// toan vo hinh voi FSM. Chinh FSM phan biet ba ngu nghia (huu han /
// inf / NaN) -- day chi truyen nguyen ven.
ultrasonic_["us" + std::to_string(i)] = u.range[i];
}
us_stamp_ = u.stamp;
// `have_us_` van true ke ca khi moi dau do deu NaN: co cam bien lap
// dat, chi la chung khong tra loi -> dung la truong hop US_TIMEOUT.
have_us_ = true;
});
mcu_->SetBumperCallback([this](const BumperReading& b) {
std::lock_guard<std::mutex> lk(mcu_mu_);
bumper_ = b.any();
bumper_stamp_ = b.stamp;
have_bumper_ = true;
});
}
// ---------------- Encoder ----------------
if (base_ != nullptr) {
base_->SetEncoderCallback([this](const EncoderReading& e) {
if (!e.valid) return;
Odometry o;
{
std::lock_guard<std::mutex> lk(odom_mu_);
if (!wheel_odom_->Update(e.stamp, e.left_rad, e.right_rad, &o)) return;
// Truyen THANG twist.covariance vao EKF.
//
// Do chinh la cach wheel_odom bao "dang truot, dung tin toi". Thay
// bang hang so o day la vut bo toan bo co che phat hien truot -- va
// no im lang, vi EKF van chay va van cho ra mot pose trong nhu that.
ekf_->UpdateOdomTwist(e.stamp, o.twist.twist.linear.x,
o.twist.twist.angular.z, o.twist.covariance[0],
o.twist.covariance[35]);
latest_odom_ = o;
have_odom_ = true;
}
// gravity_align phai TRU gia toc rieng cua robot truoc khi coi phan con
// lai la trong luc. Khong co duong nay, moi lan tang toc bi hieu thanh
// mot cu nghieng -- da do tren robot that: bien do pitch 11.23 do thay
// vi 1.32 do, va cliff_detect bao vuc gia 1625/1832 mau.
//
// Goi NGOAI odom_mu_: PerceptionPipeline thuoc ve luong nay, khong can
// mutex, va giu lock khi goi code khac la cach tao ra deadlock.
perception_->FeedOdom(e.stamp, o.twist.twist.linear.x,
o.twist.twist.angular.z);
});
}
// ---------------- Camera ----------------
if (camera_ != nullptr) {
camera_->SetCallback([this](const CameraFrame& f) {
if (!f.depth) return;
// Ca chuoi perception chay INLINE o day: depth -> cloud -> loc ->
// can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong
// camera.
const PerceptionOutput po = perception_->Process(*f.depth, f.depth_info);
std::lock_guard<std::mutex> lk(perc_mu_);
latest_cloud_ = po.cloud_aligned;
latest_cliff_cloud_ = po.cloud_cliff;
cliff_flag_ = po.cliff_detected;
cliff_stamp_ = po.stamp;
cliff_detail_ = po.cliff_detail;
have_cliff_ = true;
});
}
// ---------------- Web ----------------
WebConfig wc = cfg_->web;
if (opts_.port_override != 0) wc.port = opts_.port_override;
if (!opts_.token_override.empty()) wc.auth_token = opts_.token_override;
web_.reset(new WebServer(
wc,
// --- Lenh POST /api/* ---
[this](const std::string& cmd, const std::string& body) -> StatusResponse {
if (cmd == "safety/estop") {
bool on = false;
if (!JsonGetBool(body, "on", &on)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"can truong bool \"on\"");
}
estop_.store(on);
{
std::lock_guard<std::mutex> lk(safety_mu_);
safety_->SetEstop(on);
}
// KHONG tu goi SetVelocity: luong safety thay co va zero lenh trong
// vong mot chu ky (50 ms). Mot duong duy nhat toi base, ke ca o
// duong khan cap -- hai duong nghia la hai cho de sai.
return StatusResponse::Ok();
}
if (cmd == "safety/reset") {
estop_.store(false);
std::lock_guard<std::mutex> lk(safety_mu_);
safety_->SetEstop(false);
safety_->Reset();
return StatusResponse::Ok();
}
if (cmd == "teleop/adjust") {
std::string axis;
double dir = 0.0;
if (!JsonGetString(body, "axis", &axis) ||
!JsonGetNumber(body, "dir", &dir)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"can \"axis\" va \"dir\"");
}
std::lock_guard<std::mutex> lk(teleop_mu_);
if (axis == "lin") teleop_->AdjustLinearSpeed(dir);
else if (axis == "ang") teleop_->AdjustAngularSpeed(dir);
else {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"axis phai la \"lin\" hoac \"ang\"");
}
return StatusResponse::Ok();
}
return StatusResponse::Error(StatusCode::kNotFound, "lenh la");
},
// --- Joypad qua WebSocket ---
[this](double vx_norm, double wz_norm) {
if (estop_.load()) {
std::lock_guard<std::mutex> lk(teleop_mu_);
teleop_->ClearMotion();
return;
}
// Truc joystick cua trang web dung quy uoc cua TeleopModel:
// vertical duong = keo XUONG = lui
// horizontal duong = keo PHAI = quay phai
// app.js gui theo chieu NGUOI LAI (duong = tien/trai), nen doi dau o
// day. Doi dau o MOT cho, khong rai rac hai phia.
std::pair<double, double> c;
{
std::lock_guard<std::mutex> lk(teleop_mu_);
teleop_->SetJoystick(-wz_norm, -vx_norm);
c = teleop_->Command();
}
// CHI ghi lai lenh THO. Viec danh gia an toan do LUONG SAFETY lam, o
// 20 Hz tren dong ho cua no.
//
// Goi Step() ngay o day la sai: FSM se chi chay khi CO lenh toi, ma
// NO_CMD / SCAN_TIMEOUT / cliff_hold ton tai chinh xac cho truong hop
// lenh NGUNG toi. Da mac loi nay mot lan.
std::lock_guard<std::mutex> lk(cmd_mu_);
raw_cmd_.linear.x = c.first;
raw_cmd_.angular.z = c.second;
raw_cmd_stamp_ = clock_->Now();
have_raw_cmd_ = true;
}));
return StatusResponse::Ok();
}
} // namespace vslam

View File

@@ -0,0 +1,16 @@
@PACKAGE_INIT@
# Sinh boi vslam_add_library() cho goi @VSLAM_PKG_NAME@.
#
# Day la file ma ca obstacle_detection_core lan xloc_cpp deu thieu: khong co
# no thi find_package() that bai du da co Targets.cmake, vi Targets.cmake
# tham chieu cac target import (Eigen3::Eigen, PCL, ...) ma chua ai
# find_dependency() ra ca.
include(CMakeFindDependencyMacro)
@VSLAM_FIND_DEPS_BLOCK@
include("${CMAKE_CURRENT_LIST_DIR}/@VSLAM_PKG_NAME@Targets.cmake")
check_required_components(@VSLAM_PKG_NAME@)

234
cmake/vslam_helpers.cmake Normal file
View File

@@ -0,0 +1,234 @@
# ---------------------------------------------------------------------------
# vslam_helpers.cmake
#
# Ham dung chung cho 7 lib trong libs/. Muc tieu: moi CMakeLists.txt cua lib
# chi con khai bao NGUON PHU THUOC va DANH SACH HEADER CONG KHAI, khong lap
# lai boilerplate install/export.
#
# Khuon mau lay tu /home/quangtrung/obstacle_detection_core/CMakeLists.txt,
# co ba khac biet co y:
# 1. Sinh <name>Config.cmake -- ca obstacle_detection_core lan xloc_cpp deu
# thieu file nay, nen find_package() ma README cua chung hua hen hien
# KHONG chay duoc (chi co Targets.cmake, va Targets.cmake tham chieu
# ${PCL_LIBRARIES} dang duong dan tuyet doi ma khong find_dependency).
# 2. Header cai vao include/vslam/ chu khong phai include/<ten_lib>/, vi
# voi 7 lib thi header cua lib nay phai #include header cua lib kia --
# duong dan in-tree va duong dan da cai buoc phai giong nhau.
# 3. GLOB_RECURSE co CONFIGURE_DEPENDS: khong co no thi them file .cc moi
# se khong duoc build cho toi khi chay lai cmake bang tay.
# ---------------------------------------------------------------------------
include(CMakePackageConfigHelpers)
# ---------------------------------------------------------------------------
# vslam_add_library(<NAME>
# [PUBLIC_HDRS <header ...>] # ten file trong include/vslam/, se duoc cai
# [PUBLIC_DEPS <target ...>] # lan sang consumer
# [PRIVATE_DEPS <target ...>] # khong lan
# [DEFINES <def ...>] # PRIVATE compile definitions
# [PUBLIC_DEFINES <def ...>] # PUBLIC compile definitions
# [FIND_DEPS <pkg ...>] # sinh find_dependency() trong Config.cmake
# )
#
# Header nao KHONG liet ke trong PUBLIC_HDRS thi la noi bo: van compile duoc
# trong cay nguon nhung khong phat hanh. Day la quy tac 8 cua khuon mau
# (xloc_cpp/CMakeLists.txt dong 232-253 dung list(REMOVE_ITEM) cho cung viec).
# ---------------------------------------------------------------------------
function(vslam_add_library NAME)
cmake_parse_arguments(A
""
""
"PUBLIC_HDRS;PUBLIC_DEPS;PRIVATE_DEPS;DEFINES;PUBLIC_DEFINES;FIND_DEPS"
${ARGN})
file(GLOB_RECURSE _srcs CONFIGURE_DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cc
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp)
if(NOT _srcs)
message(FATAL_ERROR "vslam_add_library(${NAME}): khong tim thay nguon nao trong src/")
endif()
add_library(${NAME} SHARED ${_srcs})
add_library(vslam::${NAME} ALIAS ${NAME})
# KHONG dat CXX_VISIBILITY_PRESET hidden. Ca obstacle_detection_core lan
# xloc_cpp deu export mac dinh va chi gan visibility("default") tuong minh
# len rieng C API; lam khac di thi moi ky hieu C++ bi an va khong link duoc
# tu ngoai. Neu sau nay muon thu nho .so thi phai them mot macro VSLAM_API
# tren tung lop cong khai TRUOC, khong phai bat co nay truoc.
set_target_properties(${NAME} PROPERTIES
VERSION ${PROJECT_VERSION}
SOVERSION ${PROJECT_VERSION_MAJOR})
target_include_directories(${NAME}
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src)
if(A_PUBLIC_DEPS)
target_link_libraries(${NAME} PUBLIC ${A_PUBLIC_DEPS})
endif()
if(A_PRIVATE_DEPS)
target_link_libraries(${NAME} PRIVATE ${A_PRIVATE_DEPS})
endif()
if(A_DEFINES)
target_compile_definitions(${NAME} PRIVATE ${A_DEFINES})
endif()
if(A_PUBLIC_DEFINES)
target_compile_definitions(${NAME} PUBLIC ${A_PUBLIC_DEFINES})
endif()
# --- Header cong khai ----------------------------------------------------
foreach(_h ${A_PUBLIC_HDRS})
if(NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/include/vslam/${_h})
message(FATAL_ERROR
"vslam_add_library(${NAME}): PUBLIC_HDRS liet ke '${_h}' nhung "
"${CMAKE_CURRENT_SOURCE_DIR}/include/vslam/${_h} khong ton tai")
endif()
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/include/vslam/${_h}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/vslam)
endforeach()
# --- Install + export ----------------------------------------------------
install(TARGETS ${NAME}
EXPORT ${NAME}Targets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(EXPORT ${NAME}Targets
FILE ${NAME}Targets.cmake
NAMESPACE vslam::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${NAME})
# --- <name>Config.cmake --------------------------------------------------
# Sinh tu template chung. Danh sach FIND_DEPS duoc noi thanh cac dong
# find_dependency() -- day la thu ma ca hai project mau deu thieu.
set(_find_deps_block "")
foreach(_d ${A_FIND_DEPS})
string(APPEND _find_deps_block "find_dependency(${_d})\n")
endforeach()
set(VSLAM_PKG_NAME ${NAME})
set(VSLAM_FIND_DEPS_BLOCK "${_find_deps_block}")
configure_package_config_file(
${VSLAM_CMAKE_DIR}/templates/vslamConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/${NAME}Config.cmake
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${NAME})
write_basic_package_version_file(
${CMAKE_CURRENT_BINARY_DIR}/${NAME}ConfigVersion.cmake
VERSION ${PROJECT_VERSION}
COMPATIBILITY SameMajorVersion)
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/${NAME}Config.cmake
${CMAKE_CURRENT_BINARY_DIR}/${NAME}ConfigVersion.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${NAME})
endfunction()
# ---------------------------------------------------------------------------
# vslam_link_pcl(<target> <PUBLIC|PRIVATE> <component ...>)
#
# PCL bom -march=native -msse4.2 -mfpmath=sse vao PCL_DEFINITIONS. Tren arm64
# may co SSE nay lam compile fail thang; -march=native con la hazard ODR khi
# mot phan cay nguon build voi no va phan kia thi khong.
#
# xloc_cpp/CMakeLists.txt:104-111 co block loc nhung KHONG chay: bien
# BLACKLISTED_PCL_DEFINITIONS o do la MOT CHUOI " -march=native -msse4.2 ... "
# chu khong phai list, nen list(FIND ...) so sanh ca chuoi voi tung phan tu va
# khong bao gio khop. Ban nay dung list that.
# ---------------------------------------------------------------------------
function(vslam_link_pcl TARGET SCOPE)
set(_components ${ARGN})
find_package(PCL REQUIRED COMPONENTS ${_components})
target_include_directories(${TARGET} SYSTEM ${SCOPE} ${PCL_INCLUDE_DIRS})
target_link_libraries(${TARGET} ${SCOPE} ${PCL_LIBRARIES})
target_link_directories(${TARGET} ${SCOPE} ${PCL_LIBRARY_DIRS})
set(_blacklist -march=native -msse4.2 -mfpmath=sse -mavx -mavx2 -msse3 -msse4.1)
set(_kept "")
foreach(_def ${PCL_DEFINITIONS})
# PCL_DEFINITIONS co the la " -DFOO -march=native " (mot chuoi nhieu co),
# nen phai tach ra truoc khi loc.
string(REPLACE " " ";" _parts "${_def}")
foreach(_p ${_parts})
if(_p STREQUAL "")
continue()
endif()
list(FIND _blacklist "${_p}" _idx)
if(_idx GREATER -1)
message(STATUS "vslam_link_pcl(${TARGET}): bo co PCL '${_p}'")
continue()
endif()
list(APPEND _kept "${_p}")
endforeach()
endforeach()
if(_kept)
list(REMOVE_DUPLICATES _kept)
target_compile_options(${TARGET} ${SCOPE} ${_kept})
endif()
endfunction()
# ---------------------------------------------------------------------------
# vslam_embed_assets(<target> <OUT_VAR> <asset_dir> <file ...>)
#
# Nhung file tinh (html/js/css) thanh mang unsigned char trong .so, de Jetson
# ngoai hien truong phuc vu duoc web UI ke ca khi /var/lib chua duoc .deb dien,
# va de khong bao gio lech phien ban giua .so va UI.
#
# CMake thuan, khong can Python hay tool ngoai.
# ---------------------------------------------------------------------------
function(vslam_embed_assets TARGET OUT_VAR ASSET_DIR)
set(_files ${ARGN})
set(_gen ${CMAKE_CURRENT_BINARY_DIR}/web_assets_generated.cc)
set(_body "// Sinh tu dong boi vslam_embed_assets(). Dung sua bang tay.\n")
string(APPEND _body "#include <cstddef>\n#include <map>\n#include <string>\n\n")
string(APPEND _body "namespace vslam {\nnamespace {\n\n")
set(_registry "")
set(_idx 0)
foreach(_f ${_files})
set(_path ${ASSET_DIR}/${_f})
if(NOT EXISTS ${_path})
message(FATAL_ERROR "vslam_embed_assets: khong tim thay ${_path}")
endif()
# Bat CMake chay lai khi file asset doi.
#
# file(READ) chay o thi CONFIGURE, nen neu khong khai bao phu thuoc nay
# thi sua www/app.js roi build lai se VAN phuc vu ban cu -- khong loi,
# khong canh bao, chi la trinh duyet nhan noi dung tu lan configure truoc.
# Da mac phai mot lan; mat thoi gian vi no trong nhu loi o phia JS.
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${_path})
file(READ ${_path} _hex HEX)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," _carr "${_hex}")
string(LENGTH "${_hex}" _hexlen)
math(EXPR _len "${_hexlen} / 2")
string(APPEND _body "const unsigned char kAsset${_idx}[] = {${_carr}};\n")
string(APPEND _registry
" {\"${_f}\", {kAsset${_idx}, ${_len}}},\n")
math(EXPR _idx "${_idx} + 1")
endforeach()
string(APPEND _body "\n} // namespace\n\n")
string(APPEND _body "struct EmbeddedAsset { const unsigned char* data; std::size_t size; };\n\n")
string(APPEND _body "const std::map<std::string, EmbeddedAsset>& EmbeddedAssets() {\n")
string(APPEND _body " static const std::map<std::string, EmbeddedAsset> kMap = {\n")
string(APPEND _body "${_registry}")
string(APPEND _body " };\n return kMap;\n}\n\n")
string(APPEND _body "} // namespace vslam\n")
file(GENERATE OUTPUT ${_gen} CONTENT "${_body}")
set(${OUT_VAR} ${_gen} PARENT_SCOPE)
endfunction()

View File

@@ -0,0 +1,88 @@
# Cau hinh duong ong uoc luong + perception.
# MOT file cho hai lib: vslam_odometry va vslam_perception.
# ============ EKF SE(2) ============
# Chi fuse vx + vyaw, two_d_mode. Khop ekf_odom.yaml cua ban ROS.
ekf:
# Nhieu qua trinh. ⚠️ Deu la uoc luong tu datasheet -- allan_variance CHUA
# chay tren robot nay.
q_x: 0.001
q_y: 0.001
q_yaw: 0.003
q_vx: 0.01
q_vyaw: 0.02
# Bo qua mau cach mau truoc qua lau: ban ghi bi cat, hoac cam bien vua cam
# lai. Tich phan qua mot lo hong 2 giay la bia them sai so.
max_dt: 0.5
# ============ depth -> cloud -> loc ============
depth_filter:
min_range: 0.22 # Min-Z cua D410. Duoi nguong nay camera KHONG
# THAY GI -- do la vung mu ma bumper phai bit,
# khong phai vat can o khoang cach do.
max_range: 4.0
voxel_size: 0.03
max_rate: 10.0 # Hz. 30 Hz vao, 10 Hz ra.
enable_temporal: false
min_hits: 3
temporal_window: 0.5
# ============ Can trong luc ============
gravity_align:
alpha: 0.98 # 1 = chi tin gyro, 0 = chi tin accel
accel_lpf_alpha: 0.05
accel_gate: 1.0 # |a| lech khoi g duoi nguong nay moi hieu chinh
# ⚠️ TAT cai nay la moi lan tang toc bi hieu thanh mot cu nghieng. Gia toc
# ke do LUC RIENG, khong phan biet duoc nghieng voi tang toc: tang toc
# 1 m/s^2 cho ra sai so pitch atan(1/9.81) = 5.8 do. Da do tren robot that:
# bien do pitch 11.23 do truoc khi tru, 1.32 do sau khi tru.
use_odom_accel: true
odom_accel_alpha: 0.3
min_height: 0.06 # cat dai SAU khi xoay ve base_footprint
max_height: 1.20
# ============ Phat hien vuc ============
# Xem docs/PERCEPTION.md truoc khi doi bat ky so nao o day.
cliff_detect:
enabled: true
# ⚠️ min_dist la VUNG MU HINH HOC, khong phai lua chon tuy y. Camera cao
# 0.80 m chuc xuong 15 do: tia cham san gan nhat o ~1.07 m. Ha xuong duoi
# nguong do thi khong tia nao cham san va detector im lang hoan toan.
min_dist: 1.10
max_dist: 2.50
cliff_margin: 0.05
pitch_uncertainty_deg: 2.0
pixel_step: 4
min_neighbors: 3
min_cluster: 12
imu_timeout: 0.5
require_accel_ok: true
# --- Tu hieu chuan mat san ---
self_level: true
min_level_samples: 40
level_gate: 0.25
# ⚠️ 0.20 duoc chon de HAP THU dao dong pitch +-8.5 do do duoc tren robot
# that. Ha xuong se vo hieu hoa co che bu va tat phat hien vuc khi robot
# dang chay. Ban ROS da suyt mac loi nay.
max_level_slope: 0.20
max_level_residual: 0.05
# Hai cong nay KHONG co trong ban ROS. Chung bit lo hong "khop mat san vao
# pixel TUONG roi ngoai suy ra ca cua so", thu tung bao 69/500 mau co vuc
# giua hanh lang phang. Xem docs/PERCEPTION.md.
max_obstructed_frac: 0.60
max_level_offset: 0.15
# ⚠️ `nominal_tz` KHONG o day. No la HE QUA cua robot.yaml
# (camera_link.z + wheel_radius) va duoc dat tu RobotModel.
max_tz_dev: 0.08
fail_safe: true
fail_safe_after: 1.0

View File

@@ -0,0 +1,113 @@
# Hinh hoc robot + cay frame. THAY CHO URDF.
#
# ============ VI SAO BO URDF ============
# Ban ROS giu hinh hoc o HAI cho: `robot_bringup/urdf/*.xacro` cho TF, va cac
# khoi <param> trong launch cho code doc truc tiep. Hai cho do phai giu dong
# bo bang tay, va PROJECT_CONTEXT.md:71 da ghi nhan dung lop bug do.
#
# O day chi co MOT cho. `RobotModel` doc file nay, dung `TransformTree`, va
# moi stage lay phep bien doi tu cay do -- khong stage nao duoc phep tu dung
# lai mot phep bien doi tu cac so trong file nay.
#
# ============ CAY FRAME ============
# map -> odom -> base_footprint -> base_link -> {laser_link, imu_link,
# camera_link}
# camera_link -> camera_depth_optical_frame
# camera_link -> camera_infra1_optical_frame / infra2
#
# BA canh la DONG, khong khai bao o day:
# map -> odom luong slam, ~1 Hz
# odom -> base_footprint luong ekf, 50 Hz
# base_footprint -> base_link gravity_align, roll/pitch DO duoc
# Moi canh dung mot writer duy nhat. Xem transform_tree.h.
# ============ KICH THUOC ============
geometry:
wheel_radius: 0.075 # m. base_link o tam truc, cao ngan nay so voi san.
wheel_separation: 0.36 # m, khoang cach hai banh chu dong
# Ban kinh bao than robot. Dung de che quat LiDAR nhin vao chinh than.
robot_radius: 0.24
# Nua rong than. Cong voi vi tri laser cho ra goc quat bi che.
body_half_width: 0.17
# ============ FRAME TINH ============
# xyz met, rpy radian, so voi frame CHA.
#
# Quy uoc: +X truoc, +Y trai, +Z len (REP-103). Frame quang hoc cua camera
# theo quy uoc anh: +Z toi truoc, +X phai, +Y xuong -- do la ly do
# camera_depth_optical_frame co rpy = (-pi/2, 0, -pi/2) so voi camera_link.
frames:
- parent: base_link
child: laser_link
# LakiBeam gan truoc, tren nap. z do tu TAM TRUC banh, khong phai tu san.
xyz: [0.24, 0.0, 0.125]
rpy: [0.0, 0.0, 0.0]
- parent: base_link
child: imu_link
# MCU nam trong than, gan tam quay de giam gia toc huong tam gia.
xyz: [0.0, 0.0, 0.06]
rpy: [0.0, 0.0, 0.0]
- parent: base_link
child: camera_link
# D410 tren cot. z = 0.725 so voi tam truc => 0.800 so voi san
# (0.725 + wheel_radius 0.075). `cliff_detect.nominal_tz` PHAI bang tong
# do; RobotModel tu tinh va kiem, khong de nguoi dung go lai hai lan.
xyz: [0.19, 0.0, 0.725]
# Chuc xuong 15 do de nhin duoc san o 1.1-2.5 m. Doi goc nay la doi ca
# vung mu cua cliff_detect -- xem docs/PERCEPTION.md.
rpy: [0.0, 0.2618, 0.0]
- parent: camera_link
child: camera_depth_optical_frame
xyz: [0.0, 0.0, 0.0]
# Than -> quang hoc: +Z_quang = +X_than, +X_quang = -Y_than,
# +Y_quang = -Z_than.
rpy: [-1.5707963267948966, 0.0, -1.5707963267948966]
- parent: camera_link
child: camera_infra1_optical_frame
xyz: [0.0, 0.0, 0.0]
rpy: [-1.5707963267948966, 0.0, -1.5707963267948966]
- parent: camera_link
child: camera_infra2_optical_frame
# D410: hai mat IR cach nhau 50 mm (baseline). infra2 lech sang PHAI,
# tuc -Y trong frame than.
xyz: [0.0, -0.050, 0.0]
rpy: [-1.5707963267948966, 0.0, -1.5707963267948966]
# ============ BASE ============
base:
max_linear: 0.35 # m/s
max_angular: 0.80 # rad/s
accel_limit: 0.30 # m/s^2
# Base tu dung robot neu khong co lenh trong ngan nay. Phai NGAN hon
# safety.cmd_timeout, neu khong thi FSM khong bao gio thay trang thai
# NO_CMD -- base da dung truoc roi.
cmd_timeout: 0.30
# ============ ODOMETRY BANH XE ============
# ⚠️ MOI covariance o day la CONFIG, khong hardcode. Chung hien la uoc luong
# tu datasheet: UMBmark va allan_variance CHUA chay tren robot nay. Khi chay
# roi thi sua o day, khong sua trong code.
wheel_odom:
# Sai so ti le theo QUANG DUONG DI, khong theo thoi gian. Robot dung yen
# khong tich luy sai so vi tri.
sigma_x_per_m: 0.02 # m sai lech tren moi met di duoc
sigma_y_per_m: 0.02
sigma_yaw_per_rad: 0.05 # rad tren moi rad quay
# Phat hien truot: |omega_encoder - gyro_z|.
#
# ⚠️ GIOI HAN DA BIET: truot DOI XUNG (ca hai banh truot deu) KHONG phat
# hien duoc bang cach nay -- khong co chenh lech quay nao de thay. Do duoc
# trong mo phong: truot vi sai -> 649 su kien, sai so EKF 0.23%; truot doi
# xung -> 0 su kien, sai so 13.29%. Xem kich ban hoi quy `slip_sym`.
slip_threshold: 0.20 # rad/s
# Khi truot, sigma yaw-rate dat bang chinh slip_metric DO DUOC, khong phai
# mot hang so. Da do tren robot that: omega encoder -3.635 vs gyro -1.377
# = lech 2.26 rad/s, trong khi sigma khai bao la 0.2 -> EKF nhan mot diem
# 11-sigma ma van tin.
slip_sigma_is_measured: true

View File

@@ -0,0 +1,84 @@
# Cau hinh lop an toan. MOT file cho lib vslam_safety.
#
# ============ DOC KY TRUOC KHI DOI ============
# FSM nay la thu duy nhat dung giua lenh va motor. Moi so o day da co ly do,
# va vai cai trong do da tra gia bang phan cung.
#
# ⚠️ E-stop PHAN MEM co quang duong ham 0.079 m (do duoc o 0.35 m/s voi
# accel_limit 0.30). Do la ly do docs/HARDWARE.md noi cat nguon motor bang
# PHAN CUNG van la bat buoc -- lop nay khong thay the duoc no.
# ============ Quat truoc theo LiDAR ============
scan:
# Duoi khoang cach nay thi chan TIEN han.
stop_distance: 0.35
# Trong dai [stop, slow] thi giam toc theo slow_factor.
slow_distance: 0.80
slow_factor: 0.4
# Nua goc quat truoc, RADIAN (~28.6 do). Rong qua thi tuong ben canh hanh
# lang lam robot bo ca hanh lang; hep qua thi bo lot chan ban.
front_angle: 0.5
min_valid_range: 0.05
# ⚠️ BA NGU NGHIA CUA TIA, khong duoc gop:
# NaN = khong do duoc
# inf = khong co phan xa -> hanh lang RONG, KHONG phai loi
# range_max + 1 = bi sector mask cat (sentinel)
# `min_front_rays` dem tia THUC SU DUNG DUOC. Duoi nguong nay nghia la
# khong du thong tin de phan xet -> SCAN_SPARSE.
#
# Mot quat toan `inf` (giua phong rong) la HOP LE va KHONG phai loi -- day
# la cho de nham nhat trong ca FSM.
min_front_rays: 20
# ============ Cam bien khac ============
ultrasonic:
us_stop_distance: 0.30
cliff:
enable_cliff_stop: true
cliff_timeout: 1.0
# ⚠️ GIU CHAN them ngan nay sau lan bao vuc CUOI, khong chi khi co dang bat.
# Vuc BIEN MAT khoi tam nhin camera khi lai gan hon 1.10 m (vung mu), va
# CLIFF_STOP chi kich dung khoanh khac co lenh tien -- robot xoay roi tien
# tung dot ngan nen lot qua duoc khe do.
#
# DA TRA GIA BANG MOT LAN DI THANG VAO BAC THANG.
cliff_hold: 3.0
# ============ Watchdog ============
timeouts:
# Mat scan lau hon ngan nay -> SCAN_TIMEOUT.
sensor_timeout: 1.0
# Khong co lenh lau hon ngan nay -> NO_CMD.
#
# ⚠️ PHAI DAI hon robot.yaml base.cmd_timeout (0.30). Neu ngan hon thi base
# da tu dung truoc, va FSM khong bao gio thay trang thai nay.
cmd_timeout: 0.5
# ============ Gioi han dau ra ============
# Kep cuoi cung truoc khi ra motor. Trung voi robot.yaml base -- o day la lop
# thu hai, co y: mot loi trong duong teleop khong duoc phep vuot qua gioi han
# co hoc cua base.
# Toc do THOAT khi bumper dang chot.
#
# ⚠️ Chot bumper doi nguoi xac nhan la dung, nhung phep do bumper kiem vanh
# robot o vi tri HIEN TAI: robot dang ti vao vat can thi no chot lai ngay sau
# moi lan reset. Cam het chuyen dong thi khong bao gio lui ra duoc, ma khong
# lui ra duoc thi khong bao gio reset duoc.
#
# Khi dang chot: TIEN bi ep ve 0 tuyet doi; LUI va XOAY duoc phep o toc do
# duoi day. Phia sau khong co cam bien nao che, nen phai cham.
#
# escape_linear = 0 lam node TU CHOI khoi dong -- do la be tac, khong phai
# cau hinh an toan hon.
bumper:
escape_linear: 0.10
escape_angular: 0.4
limits:
max_linear: 0.35
max_angular: 0.8

View File

@@ -0,0 +1,77 @@
# Cau hinh cam bien. MOT file cho lib vslam_drivers.
#
# Vi tri cam bien tren robot KHONG o day -- chung o `robot.yaml` khoi `frames:`.
# File nay chi noi ve giao thuc, tan so va cach ve sinh du lieu.
# ============ LiDAR ============
lidar:
# LakiBeam 1L, giao thuc UDP.
#
# ⚠️ CHUA XAC MINH byte layout cua goi -- day la thu DUY NHAT con thieu de
# viet driver. Chay `vslam_lidar_probe --seconds 10` tren may noi duoc voi
# LiDAR: no tu suy ra offset truong goc, vung mang range va so goi moi vong.
host: 0.0.0.0
port: 2368
expected_rate_hz: 25.0
# --- Ve sinh scan ---
# ScanSanitizer gop header-fix va sector mask lam MOT ham. Hai bo loc rieng
# thi thu tu chay giua chung la mot bay: mask truoc hay sua header truoc cho
# ra ket qua khac nhau.
range_min: 0.05
range_max: 40.0
# Bo phat hien mat goi mien phi: canh bao neu
# |(t_cuoi - t_dau) - scan_time| > nguong nay.
stamp_mismatch_warn: 0.005
# Quat bi than robot che, don vi DO. Laser o x=0.24, than nua rong 0.17
# => +-118 do la phan nhin ra ngoai.
#
# ⚠️ Huong 0 do THAT cua LiDAR chua do duoc. Cat nham quat truoc thi safety
# thay SCAN_SPARSE va robot dung im. Chay `vslam_scan_check` TRUOC khi bat
# safety tren phan cung that.
sector_masks:
- [118.0, 180.0]
- [-180.0, -118.0]
# ============ Camera depth ============
camera:
# RealSense D410. Driver DA VIET (realsense_driver.cc), bat bang
# -DVSLAM_WITH_REALSENSE=ON. Chua kiem chung tren camera that.
enable: true
width: 640
height: 480
fps: 30
# image_proc/crop_decimate: giao anh nho hon NHUNG CameraInfo van mang K cua
# do phan giai goc va bao muc gop qua binning_x/y. Moi consumer phai tu bu
# (fx_binned()...). Quen bu la moi diem lech theo he so decimate.
decimate: 2
# D410 KHONG CO RGB. Anh IR trai dong vai kenh "rgb" khi SLAM can anh.
enable_infra1: true
enable_infra2: false
# RS2_OPTION_GLOBAL_TIME_ENABLED tren FW 5.17.0.10 chua kiem. Khong co thi
# lui ve TIME_OF_ARRIVAL, va stamp se kem chinh xac hon vai ms.
prefer_global_time: true
# ============ MCU ============
mcu:
port: /dev/ttyACM0
baud: 921600
# ClockSync khop micros() cua MCU voi dong ho host bang fit tuyen tinh.
#
# ⚠️ McuTimeUnwrapper BAT BUOC: `micros()` la uint32 nen tran moi 71.58
# phut. Ban Python cu KHONG unwrap, nen sau moc do fit tuyen tinh vo va moi
# stamp IMU sai hang nghin giay.
sync_window: 200 # so mau giu de fit
max_skew_warn: 1.0e-4 # |skew - 1| vuot nguong nay thi canh bao
expected_imu_rate_hz: 200.0
# Ban ghi encoder `E,<micros>,<ticks_l>,<ticks_r>` la MO RONG moi -- giao
# thuc cu chi co I/B/P. Firmware that chua xac nhan co ban ghi nay.
ticks_per_rev: 1024

View File

@@ -0,0 +1,93 @@
# Cau hinh cho vslam_slam.
#
# ============ VI SAO KHOI `rtabmap:` NAM O DAY ============
# Ban ROS rai 26 tham so RTAB-Map thanh <param> trong rtabmap.launch, tron
# lan voi remap va arg. Ket qua la khong the tra loi "he dang chay voi tham so
# gi" ma khong doc het 380 dong XML.
#
# ============ GO SAI TEN KEY LA LOI KHOI DONG ============
# RTAB-Map bo qua IM LANG moi key no khong biet. `Reg/Force3DoF` go thanh
# `Reg/Force3Dof` nghia la pose thanh 6-DoF ma khong ai biet, cho toi khi ban
# do bat dau nghieng. `BuildRtabmapParams` doi chieu moi key voi bang mac
# dinh cua RTAB-Map va TU CHOI KHOI DONG neu co key la.
# Bat SLAM. Mac dinh TAT: tren may chua build RTAB-Map thi node van chay day
# du phan con lai, va `--slam` tren dong lenh ghi de duoc.
enabled: false
# mapping | localization
mode: localization
# Bat buoc (require<>): khong co mac dinh. Mot mac dinh im lang se ghi ban do
# vao cho khong ai tim thay.
#
# De RONG ("") nghia la DB trong RAM -- dung khi quet thu voi bo mo phong,
# khong de lai gi tren dia.
database_path: /var/lib/vslam/maps/map.db
# ============ OPTIMIZER ============
# "0"=TORO "1"=g2o "2"=GTSAM "3"=Ceres
#
# CHOT g2o. Voi Reg/Force3DoF=true va do thi 2D thi g2o du, va `libg2o-dev` co
# trong apt jammy arm64 -- GTSAM thi khong, va PPA borglab khong publish
# arm64.
#
# DB da quet (map_house.db) NHO Optimizer/Strategy=2. RtabmapSlam::Init() goi
# init(..., loadDatabaseParameters=false), ep lai gia tri nay, roi ASSERT sau
# init. Ba lop, vi mot lop khong du: chinh ham init() la cho de lot.
#
# Do duoc tren map_house.db (240 node): xem docs/SLAM.md.
optimizer_strategy: "1"
# ============ THI GIAC ============
# Kp/MaxFeatures: -1 khi false, 400 khi true.
#
# Co nay phai KHOP voi luc quet ban do. Bat tren mot DB quet khong co tu vung
# se ton CPU trich dac trung ma khong bao gio dong duoc vong nao. Init() kiem
# `Word` trong DB va tu choi khoi dong neu lech.
#
# Da do tren robot nay: 42/43 vong dong thi giac bi loai voi 0/20 inlier --
# camera dong gop 0 cho dinh vi. Bat len chi ton CPU.
visual_loop: false
camera_3d: false
# ============ KHOI RTAB-MAP ============
# Ghi de len mac dinh cua du an (xem BuildRtabmapParams). De trong thi dung
# mac dinh -- do la lua chon dung cho hau het truong hop.
#
# Mode va visual_loop o tren GHI DE len khoi nay, khong nguoc lai.
rtabmap:
# --- Dang ky: LiDAR la trong tai ---
# Reg/Strategy=1 = ICP. Ke ca khi tui tu thi giac bat, viec TINH phep bien
# doi van do ICP tren LiDAR lam. Thi giac chi mo rong PHAM VI tim kiem.
Reg/Strategy: "1"
Reg/Force3DoF: "true" # 2.5D: pose la SE(2), khong uoc luong 6-DoF
Icp/PointToPlane: "false" # scan 2D khong co phap tuyen
Icp/VoxelSize: "0.05"
Icp/MaxCorrespondenceDistance: "0.15"
Icp/Iterations: "30"
Icp/Epsilon: "0.001"
Icp/CorrespondenceRatio: "0.3"
Icp/MaxTranslation: "0.5"
# --- Vong dong va lien ket lan can ---
RGBD/NeighborLinkRefining: "true"
RGBD/ProximityBySpace: "true"
RGBD/ProximityPathMaxNeighbors: "10"
RGBD/OptimizeFromGraphEnd: "false"
RGBD/LinearUpdate: "0.1"
RGBD/AngularUpdate: "0.1"
# --- Occupancy grid ---
Grid/Sensor: "false" # dung scan, khong dung camera
Grid/CellSize: "0.05"
Grid/RangeMax: "12.0"
Grid/RayTracing: "true"
Grid/3D: "false"
Grid/DepthDecimation: "4"
# --- Nhip ---
Rtabmap/TimeThr: "0"
Rtabmap/MemoryThr: "0"
Rtabmap/DetectionRate: "1"

View File

@@ -0,0 +1,93 @@
# Cau hinh he thong: web, log, ghi ban ghi, luong.
# ============ Web UI ============
# Thay cho RViz. Boost.Beast, mot WebSocket, hai loai khung (JSON + nhi phan).
web:
port: 8080
bind: 0.0.0.0
# ⚠️ BAT DOI XUNG CO Y:
# BAT e-stop -> LUON duoc phep, khong can token (fail-safe)
# GO e-stop -> BAT BUOC co token
# reset bumper -> BAT BUOC co token
# De trong thi log WARN to luc khoi dong. Mot lo hong fail-open o day da
# tung ton tai: `CommandNeedsAuth` doc body khac voi handler doc cung body.
auth_token: ""
# Cua hau cho dev: doc asset tu thu muc thay vi tu binary, de sua CSS khong
# phai build lai. De trong thi dung asset da nhung.
asset_dir: ""
# Tan so phat. `web_tx` AP dat cac tan so nay; khong de moi nguon tu gui,
# vi lan do dau tien da ra 109 kB/s chi vi PATH gui o 9.8 Hz thay vi 1 Hz.
status_rate_hz: 10.0
scan_rate_hz: 10.0
cloud_rate_hz: 2.0
path_rate_hz: 1.0
cloud_max_points: 4000
cloud_quant_m: 0.01
# Tan so toi da DUNG lai ban do tu do thi SLAM.
#
# ⚠️ KHONG phai tan so gui. Ban do chi gui khi no DOI; day la gioi han cho
# viec DUNG no, vi `OccupancyGrid::update()` quet lai toan bo cache moi lan
# (do duoc: 5.65 s cho 1990 node tren map_hospital.db).
#
# O che do mapping, do thi doi o gan nhu MOI khung, nen khong gioi han thi
# SlamLoop dung ban do ~9 lan/giay. Da do trong mo phong. Tren mot ban do
# that 2000x2000 (24.6 kB moi ban sau RLE) do la 221 kB/s -- gan gap doi
# ca ngan sach 120 kB/s cua toan bo web UI.
# Day la TRAN, khong phai tan so co dinh. Nhip that duoc tinh tu CHI PHI
# DO DUOC cua moi lan dung ban do: `nghi = chi_phi * (1/duty - 1)` voi
# duty = 0.25, tuc viec dung ban do khong chiem qua 1/4 luong slam.
#
# Do thi nho (~20 ms/lan) -> cap nhat gan nhu realtime, khung SLAM day dan
# ngay truoc mat. Do thi lon (5.65 s cho 1990 node) -> tu dong lui ra.
# Mot tan so CO DINH sai o ca hai dau.
map_rebuild_rate_hz: 4.0
# ============ Log ============
logging:
level: info # debug | info | warn | error
# ============ Ghi ban ghi ============
record:
enabled: false
dir: /var/lib/vslam/records
# ⚠️ Writer chay luong rieng va DROP chu khong CHAN. Ghi log tuyet doi
# khong duoc nghen vong an toan. Moi lan drop duoc ghi vao stream EVENT,
# nen ban ghi tu mo ta lo hong cua chinh no.
max_queue_bytes: 67108864
depth_rate_hz: 10.0
record_infra1: false
record_infra2: false
compress: false
# ============ Luong ============
# ⚠️ QUY TAC SONG CON: luong `safety` KHONG chia se mutex nao voi luong
# `slam`. `Rtabmap::process()` chan 100-600 ms; mot mutex chung la du de treo
# vong an toan trong ngan do.
#
# Trong ban ROS dieu nay duoc bao dam MIEN PHI boi tien trinh rieng +
# respawn="true". O day no la quy tac review, va chi ThreadSanitizer moi kiem
# duoc.
#
# SCHED_FIFO can CAP_SYS_NICE. Khong co quyen thi node van chay, chi log WARN
# va dung uu tien mac dinh -- khong duoc tu choi khoi dong vi chuyen do.
threads:
safety_priority: 50 # cao nhat
driver_priority: 45 # mcu_rx, base_io
estimator_priority: 40 # lidar_rx, ekf
# camera_rx, slam, web, recorder chay CFS (uu tien 0) -- chung khong o
# trong vong an toan.
use_realtime: true
safety_rate_hz: 20.0
# ============ Watchdog tien trinh ============
watchdog:
# Mot stage khong nhip trong ngan nay -> log ERROR va (neu la stage trong
# vong an toan) buoc e-stop.
stage_timeout: 2.0

315
docs/PERCEPTION.md Normal file
View File

@@ -0,0 +1,315 @@
# vslam_perception — camera depth, nghiêng thân, phát hiện vực
Thay cho ba nodelet `perception_3d` của bản ROS. Cả chuỗi chạy **inline trong
một lời gọi** trên chính luồng camera, không qua nodelet manager, không
`intrusive_ptr`, không dispatch theo topic.
```
depth image ──┬─> depth_to_cloud ─> depth_filter ─> gravity_align ─> cloud (base_footprint)
└─> cliff_detect ──────────────────────────────────> cờ vực + đám mây mép
IMU 200 Hz ──────> gravity_align (bộ lọc bù)
odom 50 Hz ──────> gravity_align (trừ gia tốc riêng)
```
Nhánh `cliff_detect` chạy **trước** nhánh cloud vì nó là đường an toàn: nếu
nhánh cloud chậm hay ném, cliff vẫn đã chạy xong.
## Không phụ thuộc PCL — có chủ ý
Bản ROS dùng `pcl::PassThrough` + `pcl::VoxelGrid` + `pcl::StatisticalOutlier`.
Ba cái đó cộng lại ~100 dòng thuật toán đã biết rõ. Đổi lại:
- lib này build và test được trên máy **không có PCL** (cùng lý do với
`vslam_odometry`);
- không dính bẫy `-march=native -msse4.2` mà PCL bơm vào, thứ vô hiệu thẳng
trên arm64;
- `VoxelGrid` tự viết dùng khóa `int64` 3×21 bit, không có giới hạn 2³¹ điểm
của `pcl::VoxelGrid`.
PCL chỉ còn cần ở `vslam_slam`, nơi RTAB-Map đã kéo nó vào sẵn.
## Vì sao `cliff_detect` chạy trên ảnh depth chứ không phải point cloud
1. **Bậc thang tối trả về LỖ (NaN/0), không trả về điểm thấp.**
`pcl::PassThrough` loại NaN — tức là chính tín hiệu cần tìm bị xóa sạch.
Trên ảnh depth, một pixel *lẽ ra phải thấy sàn* mà không có số đo **là**
bằng chứng của vực.
2. **Tia biết mình đi hướng nào.** Với mỗi pixel tính được "sàn lẽ ra phải ở
depth bao nhiêu" (giao tia với mặt phẳng sàn). Cloud đã mất thông tin đó.
3. **Đánh dấu tại `P_floor` = giao tia × mặt sàn, tức là MÉP vực**, không phải
tại điểm trả về (nằm sâu dưới đáy vực — hoặc không tồn tại).
## Vùng mù 0 – 1.10 m là hình học, không phải lựa chọn tùy ý
Camera cao 0.803 m chúc xuống: tia chạm sàn gần nhất ở ~1.07 m. Dưới ngưỡng đó
**không tia nào chạm sàn**, detector không thể biết gì. Đó là lý do bắt buộc
phải có cảm biến khác (cliff IR / bumper) cho vùng gần. Có test khóa việc này
(`CliffDetect.VungMuGanKhongTheThayGi`).
## Ba trạng thái, không được gộp
| Trạng thái | Nghĩa |
|---|---|
| `detected = false, judged = true` | Nhìn thấy sàn, không có vực |
| `detected = true, judged = true` | Có vực |
| `judged = false` (bail) | **Không biết** — không nhìn thấy sàn |
Gộp "không biết" vào "không có vực" đúng là thứ làm robot đi thẳng vào bậc
thang. Web UI hiện ba trạng thái này tách bạch ở khối `perception`.
Lý do bail (`CliffBailName`): `accel_gated`, `bad_geometry`, `tz_deviation`,
`few_samples`, `slope_clamped`, `residual_large`, `obstructed`, `offset_large`,
`bad_encoding`.
Bail có hai mức:
- **immediate** (`tz_deviation`, `bad_geometry`) — một khung đủ để báo nguy.
- **không immediate** — một khung xấu là nhiễu; nhưng mù **liên tục** quá
`fail_safe_after` (mặc định 1.0 s) thì báo nguy.
FSM an toàn chỉ chặn **tiến**, vẫn cho **lùi và xoay** — nên không có deadlock
kiểu "mù → dừng → không xoay ra được".
## Cổng `max_obstructed_frac` — không có trong bản ROS
Bản ROS có một lỗ hổng thật ở đây. Trong hành lang hẹp hơn `2 × min_dist`,
tường nằm **gần hơn vùng mù 1.10 m**: hầu hết tia đập vào tường chứ không tới
sàn. Một số ít điểm tường thấp vẫn lọt cổng `level_gate`, và mặt sàn tham
chiếu bị kéo **lên** theo chúng. Sau đó sàn THẬT ở xa hơn bị đo với mặt phẳng
bị kéo lên đó → rơi dưới ngưỡng → **báo vực giả giữa hành lang phẳng**.
Đo được trong mô phỏng (hành lang 1.6 m, robot quay tại chỗ, trước khi có
cổng):
| Đại lượng | Giá trị |
|---|---|
| `lvl_z0` khớp được | **+0.34 m** (sàn thật ở 0) |
| `lvl_mad` | 0.025 — **lọt cả cổng MAD** 0.05 |
| Tia sàn thật rơi dưới ngưỡng | 46 |
| Mẫu báo vực giả trên đường chạy 50 s | 69 / 500 |
Hỏng kiểu này là hỏng **không an toàn**: nó báo *có* vực chứ không báo *không
biết*.
Cổng đếm tia trả về điểm **CAO** hơn `level_gate`. Vì sao đếm điểm cao chứ
không phải bề rộng dải mẫu: bề rộng là proxy yếu (đã đo — dải mẫu vẫn trải 50%
cửa sổ mà vẫn báo giả). Còn đếm điểm cao thì **không bao giờ che được vực
thật**: vực làm điểm THẤP hoặc MẤT HẲN, không bao giờ làm điểm cao. Cổng này
chỉ có thể biến "có vực" thành "không biết", không bao giờ biến thành "không
có vực". Tính chất đó có test khóa
(`CliffDetect.CongVatCanKhongCheDuocVucThat`).
## Cổng `max_level_offset` — cũng không có trong bản ROS
`max_obstructed_frac` **không đủ**. Quét theo bề rộng hành lang (robot quay
tại chỗ một vòng, 210 khung mỗi bề rộng) cho thấy một dải mà cổng đó không
chạm tới:
| bề rộng | tường cách | che % | vực giả (chỉ có cổng obstructed) |
|---|---|---|---|
| 1.6 m | 0.85 m | 22.4 | 0 |
| 2.0 m | 1.00 m | 5.2 | 0 |
| **2.5 m** | 1.25 m | **0.0** | **4** |
| **3.0 m** | 1.50 m | **0.0** | **6** |
| ≥4.0 m | ≥2.0 m | 0.0 | 0 |
Hạ ngưỡng **không** sửa được: quét `max_obstructed_frac` từ 0.60 xuống 0.20
cho **đúng** 4 và 6 khung sai ở 2.5/3.0 m, trong khi khả dụng ở 1.6 m tụt từ
77.6% xuống 26.2%. Nên giữ 0.60.
Nguyên nhân là khác: phép khớp chỉ theo **bán kính** (`z = z0 + dốc·r`) nên
gộp mất chiều phương vị — tường ở **một bên** làm lệch cả vành. Ở 3.0 m chỉ
~9% tia trả về điểm cao hơn `level_gate` (xa cổng 0.60), nhưng điểm tường ở
`r` lớn vẫn lọt cổng và **kéo dốc** đường khớp lên `+0.19` — vừa đủ dưới trần
`max_level_slope = 0.20`. Sàn thật ở `r ≈ 2 m` rồi bị đo với `z_ref = +0.13`.
Cổng bắt được nó là một mệnh đề **vật lý**, không phải một ngưỡng chỉnh tay:
> Mặt phẳng sàn khớp được, ngoại suy về `r = 0`, phải đi qua chính chỗ robot
> đang đứng — vì robot **đang đứng trên nó**.
Các khung sai có `z0 = −0.17 … −0.26`: phép khớp nói "sàn dưới bánh xe tôi
thấp hơn 25 cm". Ramp thật 8% bắt đầu ở 1.5 m cho `z0 = −0.096`, vẫn lọt
`max_level_offset = 0.15`. Có test khóa cả hai chiều
(`MatPhangKhongDiQuaChoRobotDungThiKhongPhanXet`, `RampThatVanLotCongOffset`).
**Vì sao không hạ `max_level_slope` thay vì thế:** 0.20 được chọn để *hấp
thụ* dao động pitch ±8.5° đo được trên robot thật; hạ xuống sẽ vô hiệu hóa cơ
chế bù và tắt phát hiện vực khi robot đang chạy. Bản ROS đã suýt mắc lỗi này.
Thêm một **lượt loại ngoại lai rồi khớp lại** (`3 × MAD`) trước hai cổng trên.
Nó không thể làm vực thật biến mất: điểm vực cũng bị loại khỏi phép khớp, mà
loại chúng ra thì mặt sàn tham chiếu càng đúng → vực **càng dễ** thấy ở lượt 2.
Kết quả cuối, cả ba cơ chế cùng bật:
| bề rộng | che % | phán xét được % | **vực giả** |
|---|---|---|---|
| 1.6 m | 22.4 | 77.6 | **0** |
| 2.0 m | 5.2 | 81.0 | **0** |
| 2.5 m | 0.0 | 81.4 | **0** |
| 3.0 m | 0.0 | 90.5 | **0** |
| ≥4.0 m | 0.0 | 100.0 | **0** |
## Số đo
Trên x86 dev, ảnh depth 320×240, build Release:
| Cấu hình | ms/khung | % một core @30 Hz |
|---|---|---|
| Chỉ `cliff_detect` | 0.215 | 0.6 % |
| `cliff` + cloud đầy đủ | 1.946 | 5.8 % |
(Chỉ tiêu P5: < 60 % một core Jetson. Đo với `max_rate = 0` tức trường hợp xấu
nhất; mặc định 10 Hz thì nhánh cloud chỉ chạy 1/3 số khung.)
RSS đứng yên 10.9 MB qua 55 s chạy — không rò theo khung.
## Cái gì chưa kiểm được
- Chưa chạy trên phần cứng thật: `nominal_tz`, `pitch_uncertainty_deg`,
`level_gate` vẫn là số của bản ROS, chưa hiệu chuẩn lại trên robot này.
- `max_obstructed_frac` và `max_level_offset` hiệu chỉnh bằng mô phỏng, trên
bản đồ tổng hợp hai tường song song. Môi trường thật có góc, cửa, đồ đạc —
chưa đo.
- Không có ô kính/gương trong mô phỏng (trong suốt với cả LiDAR lẫn depth).
- Không có vật cản nhô ra (mép bàn) — thứ LiDAR ở 0.24 m không thấy mà camera
thấy.
## Nhiễu depth trong mô phỏng: mô hình stereo
D410 không **đo** khoảng cách — nó đo độ lệch pixel giữa hai mắt IR rồi suy ra
`d = f·B / disparity`. Sai số khớp pixel gần như cố định (~0.1 px), nhưng `d`
tỉ lệ **nghịch** với disparity, nên khi lan sai số:
```
σ_d = √( floor² + (d²·σ_disp / (f·B))² )
```
Sai số tăng theo **bình phương** khoảng cách. Xa gấp đôi → sai gấp bốn.
Bản trước dùng một **hằng số 7 mm**. Sai ở *dạng*, không chỉ ở trị:
| khoảng cách | hằng số cũ | mô hình stereo | |
|---|---|---|---|
| 1.0 m | 7 mm | 4 mm | sim bi quan |
| 2.5 m | 7 mm | **27 mm** | sim **lạc quan 3.8×** |
| 4.0 m | 7 mm | **69 mm** | sim **lạc quan 9.8×** |
2.5 m là **mép xa** của cửa sổ `cliff_detect`, nên sai số ở đó quyết định trực
tiếp ngưỡng có chịu được trên phần cứng thật hay không. Một bộ mô phỏng **dễ
hơn** thực tế là loại tệ nhất: nó cho qua những ngưỡng sẽ hỏng ngoài hiện
trường.
Đo lại sau khi sửa (tường phẳng ở cự ly biết trước, đo σ của dải pixel giữa):
| tường ở | σ đo được | mô hình |
|---|---|---|
| 0.96 m | 4.5 mm | 4.4 mm |
| 1.96 m | 16.8 mm | 16.6 mm |
| 2.96 m | 37.3 mm | 37.7 mm |
| 3.96 m | 66.7 mm | 67.4 mm |
### `fx` phải là độ phân giải GỐC
Lần đầu σ đo được **gấp đúng 2.0×** mô hình ở mọi cự ly. Nguyên nhân: công
thức dùng `fx` đã chia cho `decimate` (=2).
Khớp stereo xảy ra ở độ phân giải **đầy đủ** của cảm biến; `decimate` (tương
đương `image_proc/crop_decimate`) chỉ **lấy mẫu thưa** một ảnh depth đã tính
xong — nó không làm từng điểm ảnh kém chính xác đi. Dùng `fx` đã decimate thổi
phồng nhiễu đúng bằng `dec` lần.
Tỉ lệ *sạch* 2.00 là dấu hiệu sai hằng số, không phải sai mô hình — đáng nhớ
khi gỡ lỗi loại này.
### Ngưỡng vẫn chịu được
Ngưỡng báo vực **nở theo tầm** (`cliff_margin + r·tan(pitch_unc)`), nên nó lớn
dần cùng nhiễu:
| tầm | ngưỡng | 3σ nhiễu | còn lại |
|---|---|---|---|
| 1.10 m | 88 mm | 16 mm | 73 mm |
| 2.50 m | 137 mm | 81 mm | **57 mm** |
Đo bằng thí nghiệm có đối chứng (sàn phẳng, đứng yên, 360 khung, chỉ khác
bật/tắt nhiễu): **0 báo vực giả ở cả hai**. `min_cluster = 12` làm nhiễu độc
lập từng pixel rất khó gom cụm.
Trong 12 kịch bản hồi quy, **chỉ `cliff_shallow` đổi** — bậc 0.12 m sát ngưỡng,
số lần báo 16 → 19. Đúng kịch bản dựng ra để nhạy ngưỡng, và là kịch bản duy
nhất *nên* đổi.
### ⚠️ Hai hằng số chưa xác minh
`depth_baseline = 50 mm` là **ước lượng** — không có trong bản ghi datasheet
nào. `depth_disparity_noise_px = 0.1` là giá trị điển hình của stereo
block-matching, không phải thông số đo được của D410. Sai 20% thì mọi con số
nhiễu sai 20%. Đo bằng `rs-enumerate-devices -c` khi cắm camera.
## Fail-safe: `obstructed` KHÔNG còn báo vực
`cliff_detect` bail vì nhiều lý do. Trước đây **mọi** lý do đều kích fail-safe:
```cpp
detected = fail_safe && (immediate || held > fail_safe_after);
```
Đo trên bản đồ bệnh viện thật, robot đứng cách tường 2.0 m — cửa sổ nhìn sàn
1.1–2.5 m bị bức tường lấp kín:
| vị trí | khung | báo vực | lý do bail |
|---|---|---|---|
| (0.0, 0) | 240 | 0 | `judged` |
| **(0.5, 0)** | 240 | **209** | `slope_clamped` |
| **(1.0, 0)** | 240 | **209** | `obstructed` |
| **(1.5, 0)** | 240 | **209** | `few_samples` |
Hậu quả: `CLIFF_STOP` chặn tiến vĩnh viễn. Robot **không bao giờ lại gần tường
dưới ~2.5 m được** — tức không đi được trong bất kỳ toà nhà thật nào. Bản đồ
SLAM kẹt ở 1.55 × 1.05 m sau 50 giây lái.
### Sửa: `obstructed` là quan sát KHẲNG ĐỊNH
```cpp
const bool blind_for_unknown_reason = (why != CliffBail::kObstructed);
detected = fail_safe && blind_for_unknown_reason && (immediate || held > ...);
```
Fail-safe tồn tại cho *"tôi không thấy sàn và **không biết vì sao**"*.
`kObstructed` khác hẳn: cửa sổ bị một vật **đặc** lấp kín. Vật đặc không phải
vực, và LiDAR đã lo nó qua `SCAN_SLOW`/`SCAN_STOP`.
`few_samples` và `slope_clamped` **vẫn** kích fail-safe — một cái vực thật cũng
cho ít mẫu và mặt phẳng nghiêng gắt, nên chúng không phân biệt được.
### Và: mù ĐÃ GIẢI THÍCH ĐƯỢC, trong FSM
Hai lý do còn lại vẫn chặn robot khi tường ở rất gần (0.5 m — cửa sổ 1.1–2.5 m
nằm **sau** tường, không thấy gì thật). Nhưng lớp safety có thêm **LiDAR**:
```cpp
const bool blind_explained_by_obstacle =
!in.cliff_judged && std::isfinite(out.min_front) &&
out.min_front < in.cliff_window_min;
```
Nếu detector **không phán được** *và* LiDAR thấy vật cản **gần hơn** điểm bắt
đầu cửa sổ, thì sự mù đã có lời giải — và chính vật cản đó đã kích
`SCAN_SLOW`/`SCAN_STOP`.
⚠️ Chỉ áp khi `!cliff_judged`. Nếu detector **thấy vực thật** thì vật cản không
giải thích được gì: vực và vật cản có thể cùng tồn tại, và `CLIFF_STOP` thắng.
### Đo lại
| | trước | sau |
|---|---|---|
| `CLIFF_STOP` (chạy 40 s trên bản đồ bệnh viện) | 209 mẫu | **2** |
| Bản đồ SLAM sau 40 s (chỗ thoáng) | 1.55 × 1.05 m | **1.3 → 7.1 m** |
| FSM | `CLIFF_STOP` áp đảo | **400/400 `OK`** |
Hồi quy: chỉ `spin` đổi — `count_cliff_detected` 8 → 1, còn **cả ba `count_bail_*`
giữ nguyên** (28 `obstructed`, 1 `residual_large`, 1 `offset_large`). Đúng ý
đồ: vẫn báo cáo detector đang mù, chỉ không biến cái mù đã giải thích được
thành một lệnh dừng.

129
docs/REGRESSION.md Normal file
View File

@@ -0,0 +1,129 @@
# Bộ hồi quy
Thay cho 18 script Python trong `slam_eval/`. Ba phần:
| | |
|---|---|
| `tools/vslam_record` | ghi `.vsr` từ bộ mô phỏng theo kịch bản có tên |
| `tools/vslam_replay` | phát lại `.vsr` qua **toàn bộ** đường ống, xuất JSON phẳng |
| `tools/regress.sh` | chạy mọi bản ghi, so với kỳ vọng theo **dung sai** |
```
tools/regress.sh # chạy và so
tools/regress.sh --record # ghi lại .vsr trước khi chạy
tools/regress.sh --bless # GHI ĐÈ kỳ vọng bằng kết quả hiện tại
```
Cả bộ chạy trong **2 giây** (chỉ tiêu P7: < 5 phút).
## Nguồn không phân biệt được
`ReplaySource` implement **chính** các interface driver mà `SimSource` và phần
cứng thật implement. Trong `vslam_replay.cc` không có một nhánh `if (replay)`
nào. Đó là lợi ích kiến trúc lớn nhất của interface + factory — và nó có nghĩa
là khi có phần cứng, `vslam_record --live` ghi cùng định dạng và toàn bộ bộ
hồi quy chạy trên dữ liệu thật mà không sửa một dòng nào.
## Kịch bản
Mỗi kịch bản chạm vào **một đường mà các kịch bản khác không chạm**:
| kịch bản | đường được kiểm | dấu hiệu |
|---|---|---|
| `straight` | tích phân odometry, EKF, ScanSanitizer | `pose_ekf_x` 2.795 m sau 8 s @ 0.35 m/s |
| `outback` | sai số góc tích luỹ | về đúng gốc (< 1 mm), `yaw_ekf` −0.271 rad sau hai vòng 180° |
| `slip_diff` | phát hiện trượt bằng gyro | `metric_slip_max` 0.144, EKF lệch bánh xe 0.268 m |
| `slip_sym` | **giới hạn đã biết**: trượt đối xứng không phát hiện được | `metric_slip_max` 0.0018 — bằng hệt lúc không trượt |
| `cliff` | `cliff_detect` + nhánh `CLIFF_STOP` | 20 khung báo vực, 90 bước `CLIFF_STOP` |
| `cliff_shallow` | **sát ngưỡng**: bậc 0.12 m | 15/104 khung báo vực |
| `wall` | chặn theo LiDAR | `SCAN_SLOW` 64, `SCAN_STOP` 56 |
| `spin` | cổng `max_obstructed_frac` trong hành lang hẹp | 28 khung `obstructed`, 0 vực giả từ phép khớp |
| `glass` | **`US_BLOCKED`** — kính vô hình với LiDAR | 292 mẫu |
| `us_dead` | **`US_TIMEOUT`** — dàn siêu âm đứt | 398 mẫu |
| `glass_blind` | **`BUMPER`** — kính + không lắp siêu âm | 387 mẫu |
| `lidar_cut` | **`SCAN_TIMEOUT`** — "rút dây" LiDAR 3 s | 102 mẫu |
## Nhánh FSM: 8/11 đã chạy end-to-end
Trước bốn kịch bản trên, **5 nhánh an toàn chỉ có unit test** — đường từ cảm
biến → FSM → base chưa bao giờ được thử cho chúng.
Đã phủ: `OK`, `SCAN_SLOW`, `SCAN_STOP`, `SCAN_TIMEOUT`, `CLIFF_STOP`,
`US_BLOCKED`, `US_TIMEOUT`, `BUMPER`.
Chưa phủ, và lý do:
| nhánh | vì sao |
|---|---|
| `ESTOP` | là **lệnh**, không phải cảm biến. Đã chạy end-to-end trong bài TSan (bật/tắt 3 lần qua `/api/safety/estop`), nhưng `.vsr` chưa mang stream lệnh |
| `NO_CMD` | `vslam_replay` gọi FSM từ callback encoder nên `si.cmd` **luôn** có. Nhánh này *có* chạy trong `vslam_node --replay` (luồng safety 20 Hz độc lập, không ai lái) — chỉ là công cụ hồi quy không dựng được |
| `SCAN_SPARSE` | cần một cảnh mà quạt trước **toàn tia bị che** nhưng scan vẫn tới. Chưa dựng được cảnh nào tự nhiên ra thế |
## Kính: thứ Gazebo không mô phỏng được
`kUsBlocked` ghi trong FSM: *"siêu âm thấy vật gần — có thể là KÍNH"*. Siêu âm
tồn tại **chỉ vì** lý do đó: kính gần như trong suốt với laser 940 nm và với IR
của depth camera, nhưng phản xạ âm rất tốt.
`SimSource::SetGlass()` đánh dấu ô là kính: LiDAR và depth **xuyên qua**, siêu
âm và bumper **thấy**. Đo được trong `glass`: LiDAR báo `min_front` 1.66 m
(tường bên hành lang) trong khi bức kính ở 0.34 m — nó hoàn toàn không thấy.
`docs/SIM_VS_REAL.md` của repo cũ phải ghi "kính kiểm bằng dữ liệu thật"; giờ
kiểm được trong mô phỏng.
`slip_sym` tồn tại để **khoá một giới hạn**, không phải để chứng minh hệ chạy
đúng. Nếu một ngày nó bắt đầu phát hiện được trượt, đó cũng là thay đổi cần
review.
## Vì sao cần `cliff_shallow`
Bậc 0.40 m của `cliff` cho hàng trăm điểm mỗi khung, nên nó **không nhạy cảm
với ngưỡng**: đã thử đổi `min_cluster` 12 → 20, cả bộ hồi quy vẫn xanh. Một bộ
hồi quy chỉ chạy xa ngưỡng thì không bắt được trượt ngưỡng.
Bậc 0.12 m nằm giữa hai đầu của ngưỡng nở ra theo tầm
(`thr = z_ref − (cliff_margin + r·tan θ)` = 0.089 m ở r = 1.1, 0.137 m ở
r = 2.5), nên nó chỉ bị phát hiện khi robot lại đủ gần. Cùng phép thử
`min_cluster` 12 → 20 giờ báo `count_cliff_detected` 14 thay vì 15.
## Dung sai theo tiền tố khoá
Một dung sai duy nhất cho mọi thứ là sai:
| tiền tố | dung sai | lý do |
|---|---|---|
| `n_`, `count_` | **0** | lệch một khung = đường đi qua code đã đổi |
| `pose_`, `dist_` | 2 mm | không bao giờ khớp bit-for-bit qua các mức tối ưu / phiên bản libm |
| `yaw_` | 1 mrad | |
| `metric_` | 0.01 | |
Ngoài so từng khoá, harness còn **đếm số khoá**: một khoá biến mất nghĩa là
một nhánh đã ngừng chạy, và so theo từng khoá không bắt được điều đó. Đã kiểm:
đổi `cliff_margin` 0.05 → 0.35 làm `count_cliff_detected` và
`count_state_CLIFF_STOP` biến mất hẳn, và phép đếm khoá báo `21` vs `19`.
## Bản ghi không vào git
55 MB, và chúng **sinh lại được tất định** (`SimConfig::seed` cố định) bằng
`tools/regress.sh --record`. Cái vào git là `test/expected/*.json` — 36 kB,
đọc được bằng mắt, và mỗi thay đổi của chúng là một thay đổi hành vi cần
review.
## Git hook
`tools/pre-push`, cài bằng:
```
ln -s ../../tools/pre-push .git/hooks/pre-push
```
## Ba lỗi tìm ra khi dựng bộ hồi quy
| Lỗi | Bài học |
|---|---|
| `Encode*Payload` **nối thêm** vào `out`, tôi dùng chung một bộ đệm cho bốn stream và không `clear()` | Mỗi bản ghi to hơn bản trước: **17 GB cho một kịch bản 9 giây**, làm đầy ổ đĩa. Header đã ghi rõ "Nối thêm vào `out`" — tôi đọc danh sách hàm mà không đọc hợp đồng ngay phía trên nó. |
| Base của sim có watchdog 0.3 s; recorder đặt vận tốc **một lần** rồi chạy 8 giây | Robot chỉ đi được 0.026 m thay vì 2.8 m, và **không có lỗi nào** — vì đó là hành vi ĐÚNG của base. Phải phát lại lệnh theo lát 50 ms, y như luồng safety làm trên robot thật. |
| Bộ tích luỹ lấy mẫu thưa trong `SimSource::RunFor` là **biến cục bộ** | Gọi nhiều lát ngắn làm chúng reset: với lát 50 ms và camera 10 Hz, **không một khung ảnh nào** được sinh, im lặng. Đã chuyển thành trạng thái của sim để `RunFor` gọi nối tiếp được. |
| `US_TIMEOUT` **không bắt được** dàn siêu âm chết | FSM chỉ kiểm `stamp` cũ. Một dàn chết nhưng MCU **vẫn gửi** bản ghi thì stamp luôn mới → vô hình. Tệ hơn: tôi lọc bỏ NaN nên map thành **rỗng**, mà rỗng nghĩa là "không lắp siêu âm". Kịch bản `us_dead` phát hiện; sửa: giữ NaN nguyên vẹn, FSM đếm số đầu dò *trả lời* và báo `US_TIMEOUT` khi bằng 0. |
| `BUMPER` **không thể kích** trong mô phỏng | Phép va chạm của sim **từ chối chuyển động** khi vành robot (`robot_radius`) chạm vật cản, nên robot không bao giờ vào được vị trí mà bumper đặt đúng `robot_radius` nhìn thấy. Bumper thật **nhô ra ngoài vỏ** — thêm `bumper_reach = 0.03 m`. Sau đó `BUMPER` kích 387 mẫu. |

710
docs/RUNTIME.md Normal file
View File

@@ -0,0 +1,710 @@
# `vslam_node` — tiến trình duy nhất
Thay cho `roslaunch robot_bringup bringup.launch` + 20 file `.launch` + 14 file
YAML + `roscore`.
```
vslam_node --sim # bộ mô phỏng (thay Gazebo)
vslam_node --sim --map nha.yaml # mô phỏng trên bản đồ thật
vslam_node --replay X.vsr # phát lại bản ghi
vslam_node --live # phần cứng thật (driver CHƯA viết)
vslam_node --check # nạp và KIỂM cấu hình rồi thoát
```
**Không có mặc định cho nguồn.** Một node âm thầm chạy mô phỏng trong khi
người vận hành tưởng nó đọc cảm biến thật là kiểu hỏng tệ nhất có thể nghĩ ra,
nên nguồn phải chọn tường minh.
Đọc [`app/src/wiring.cc`](../app/src/wiring.cc) để hiểu hệ thống: đó là **nơi
duy nhất** nối nguồn với stage, và là tương đương của toàn bộ 20 file XML.
## Luồng
| luồng | tần số | ưu tiên | làm gì |
|---|---|---|---|
| `safety` | 20 Hz | SCHED_FIFO 50 | **đường duy nhất** tới motor |
| `source` | theo nguồn | SCHED_FIFO 45 | driver / sim / replay |
| `slam` | theo scan | CFS | RTAB-Map — chặn 100–600 ms |
| `web_tx` | 10 Hz | CFS | serialize và phát |
Các stage còn lại chạy **inline** trong callback của nguồn. Chuỗi perception
(depth → cloud → lọc → căn trọng lực → cliff) từng là ba nodelet chung một
manager; ở đây nó là ba lời gọi hàm trong một hàm — không `intrusive_ptr`,
không dispatch theo topic, và thứ tự bước là thứ tự dòng lệnh.
Thiếu `CAP_SYS_NICE` thì node **vẫn chạy**, chỉ log WARN và dùng ưu tiên mặc
định. Từ chối khởi động ở đó sẽ khiến mọi người chạy bằng `sudo`, và đó mới là
thứ nguy hiểm.
**Quy tắc sống còn:** luồng `safety` không chia sẻ mutex nào với luồng `slam`.
`Rtabmap::process()` chặn 100–600 ms. Trong bản ROS điều này được bảo đảm miễn
phí bởi tiến trình riêng + `respawn="true"`; ở đây nó là quy tắc review, và
**chỉ ThreadSanitizer mới kiểm được**.
## ThreadSanitizer
```
cmake -S . -B build-tsan -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_C_COMPILER=gcc-10 -DCMAKE_CXX_COMPILER=g++-10 \
-DVSLAM_BUILD_APP=ON -DVSLAM_BUILD_SLAM=OFF \
-DCMAKE_CXX_FLAGS="-fsanitize=thread -fno-omit-frame-pointer -g" \
-DCMAKE_EXE_LINKER_FLAGS="-fsanitize=thread -pthread" \
-DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=thread -pthread"
ctest --test-dir build-tsan -LE condvar
```
`-DVSLAM_BUILD_SLAM=OFF`: RTAB-Map và PCL không build kèm TSan nên sẽ sinh báo
giả. SLAM chưa nối vào runtime nên không mất gì.
**TSan bắt được một race THẬT ngay lần chạy đầu** trên `vslam_node --sim`:
luồng `web_tx` đọc `GravityAlign::roll()` trong khi luồng `source` ghi nó ở
200 Hz. `GravityAlign` có hợp đồng là **một luồng**; sửa bằng cách thêm khoá
vào thư viện sẽ phá hợp đồng đó và bắt mọi người dùng trả giá cho một nhu cầu
chỉ của riêng web UI. Sửa ở `Runtime`: ba `std::atomic`, luồng source publish,
web đọc.
Sau khi sửa, chạy lại với kịch bản nặng hơn (lái 4 pha + bật/tắt e-stop 3 lần
+ reset + chỉnh teleop + client WebSocket thứ hai ngắt đột ngột giữa chừng):
**0 cảnh báo**.
### Với SLAM bật
RTAB-Map tự sinh luồng riêng (`UThread::start()`) và các luồng đó tranh chấp
trên dữ liệu của **chính nó**. TSan báo hết, và `called_from_lib:` không bịt
được: nó lọc theo thư viện **gọi**, còn đây là race giữa hai luồng **bên
trong** thư viện trên heap mà thư viện tự cấp phát.
Thay vì giấu, [`tools/tsan_check.sh`](../tools/tsan_check.sh) **tách** chúng ra
và trả lời đúng một câu hỏi:
```
tools/tsan_check.sh 25 --slam --slam-db "" --slam-mode mapping
```
```
tổng cảnh báo : 9
chạm mutex CỦA TA : 0 <-- phải là 0
quy về RTAB-Map/OpenCV : 36
```
Đo được: từ **1737** cảnh báo xuống **9** sau khi suppress bốn thư viện thực sự
báo, và **0** trong số đó chạm `scan_mu_`, `odom_mu_`, `safety_mu_`,
`slam_mu_`, `perc_mu_`, `cmd_mu_`, `teleop_mu_`. Xác minh được: các heap block
tranh chấp đều do `UThread::start()` cấp phát.
**Quy tắc `safety` ↔ `slam` giữ được.** Cách giữ: `SlamLoop` copy `shared_ptr`
của scan và `Pose2D` odom **dưới mutex rồi nhả ngay**, sau đó mới gọi
`Process()`. Luồng safety đọc cùng những mutex đó nên không bao giờ chờ quá một
phép copy con trỏ.
⚠️ `called_from_lib:` phải khớp **đúng một** thư viện. Một tiền tố khớp nhiều
cái (ví dụ `libpcl_`) làm TSan **tự thoát** ngay lúc khởi động — không phải
cảnh báo, là lỗi chết người.
### `test_channel` không chạy được dưới TSan — và đó không phải lỗi của ta
`Channel<T>::Read` dùng `condition_variable::wait_for(lk, timeout, pred)`. TSan
của gcc-10 không mô hình được khuôn mẫu đó với libstdc++: nó báo *"double lock
of a mutex"* rồi một data race **suy ra** từ lockset đã hỏng.
[`test/tsan_condvar_repro.cc`](../test/tsan_condvar_repro.cc) tái lập **đúng
hai cảnh báo đó với không một dòng nào của vslam** — chỉ một `std::mutex`, một
`condition_variable`, một luồng chờ có predicate.
**Không suppress.** Suppression đủ rộng để bịt nó sẽ che luôn mọi race trên dữ
liệu được bảo vệ bởi một mutex có dùng condvar — tức gần hết trạng thái chia sẻ
của hệ. (`deadlock:__gthread_mutex_lock` cũng không khớp vì hàm bị inline.) Nên
gắn nhãn `condvar` và chạy `ctest -LE condvar` dưới TSan; ở build thường nó vẫn
chạy bình thường.
Chưa kiểm clang — máy dev không có. Nếu cài được thì thử lại, nhiều khả năng
không cần nhãn.
## Một đường duy nhất tới motor
```
web → teleop → raw_cmd → [luồng safety] → base
```
Không nhánh nào cho lệnh đi thẳng xuống base. **Kể cả e-stop**: nó đặt cờ, rồi
luồng safety thấy cờ và zero lệnh trong vòng một chu kỳ (50 ms). Hai đường
nghĩa là hai chỗ để sai.
FSM cũng **không** chạy trong callback teleop. Gọi `Step()` ở đó nghĩa là nó
chỉ chạy khi *có* lệnh tới — mà `NO_CMD`, `SCAN_TIMEOUT` và `cliff_hold` tồn
tại chính xác cho trường hợp lệnh **ngừng** tới. Đã mắc lỗi này một lần.
## Sáu file cấu hình
14 file YAML của bản ROS gộp thành sáu. Một file cho một lib, cộng
`robot.yaml`.
| file | cho |
|---|---|
| `robot.yaml` | hình học + **cây frame (thay URDF)** + base + nhiễu wheel_odom |
| `sensors.yaml` | LiDAR, camera, MCU — giao thức và tần số |
| `pipeline.yaml` | EKF, depth_filter, gravity_align, cliff_detect |
| `slam.yaml` | mode, DB, optimizer, **khối `rtabmap:` 26 key** |
| `safety.yaml` | FSM |
| `system.yaml` | web, log, ghi bản ghi, luồng |
### Không giá trị nào ở hai nơi
`cliff_detect.nominal_tz` **không** có trong `pipeline.yaml`. Nó là **hệ quả**
của `robot.yaml`: `camera_link.z + wheel_radius`. Gõ tay lần thứ hai là cho
một trong hai được phép lệch — và chúng **đã** lệch thật: `0.803` trong
`cliff_detect.h` so với `0.80` mà bộ mô phỏng dùng. Đặt nó vào `pipeline.yaml`
giờ báo "khoá lạ".
Tương tự, phép dựng `camera_depth_optical_frame → base_link` từng bị lặp ở
**bốn file** (hai tool, hai file test), mỗi chỗ một bản chép của cùng một chuỗi
`QuaternionMultiply`. Giờ nó đi qua `RobotModel::StaticTransform()`, và bộ mô
phỏng cũng lấy hình học từ đó — nếu sim dùng một bộ số còn đường ống dùng bộ
khác thì mọi phép đo đều đo nhầm.
### Gõ sai tên khoá là lỗi khởi động
Mọi khối đều gọi `UnknownKeys()` và **từ chối khởi động**. `stop_distence` thay
vì `stop_distance` hiện tại sẽ âm thầm về mặc định 0.35 — và bạn không biết
cho tới khi robot không dừng.
### Kiểm chéo giữa các file
`--check` không chỉ nạp, nó còn kiểm những thứ **không** kiểm được trong một
file đơn lẻ:
| cổng | vì sao |
|---|---|
| `safety.cmd_timeout > robot.base.cmd_timeout` | ngắn hơn thì base tự dừng trước, và nhánh `NO_CMD` của FSM **không bao giờ chạy** — một nhánh an toàn tồn tại trên giấy mà chưa bao giờ được thử |
| `safety.limits ≤ robot.base` | lớp an toàn không được phép cho phép nhiều hơn phần cứng chịu được |
| `safety_priority` cao nhất | đặt ngược lại là vô hiệu hoá cả lý do dùng `SCHED_FIFO` |
| `cliff_hold ≥ 1.0` (WARN) | vực biến mất khỏi tầm nhìn khi lại gần hơn `min_dist` |
Cả bốn đều có trong `ctest` (`config_tu_choi_*`), chạy bằng **chính binary**
trên **chính** file YAML sẽ được cài lên `/etc/vslam`.
#### `WILL_FAIL` là cái bẫy
Bảy test này ban đầu dùng `WILL_FAIL TRUE`, chỉ đảo ngược **mã thoát**. Một
binary **crash** cũng là "thất bại", nên chúng xanh kể cả khi `vslam_node`
không chạy nổi.
Đã gặp thật: `/opt/MVS` trong `LD_LIBRARY_PATH` gây
`symbol lookup error: libpcl_io.so.1.10: undefined symbol: libusb_set_option`,
và **cả sáu** test `WILL_FAIL` báo PASS trong khi binary không in nổi một dòng.
Chỉ `config_that_nap_duoc` (kỳ vọng *thành công*) là đỏ — tức 6/7 test ở khối
đó vô dụng đúng lúc cần chúng nhất.
Giờ dùng `PASS_REGULAR_EXPRESSION` khớp vào **nội dung** từng cổng
(`cmd_timeout .* phai LON HON`, `limits vuot qua`, …). Mạnh hơn hai bậc: không
chỉ đòi test thất bại, mà đòi **đúng cái cổng đó** kích. Kiểm lại bằng cách cố
tình làm hỏng `LD_LIBRARY_PATH` — cả 6 giờ đỏ với `Required regular expression
not found`.
## Đo được
`vslam_node --sim`, lái qua ba pha (tiến / quay / lùi), 20 giây:
| | |
|---|---|
| Băng thông web | 99.0 kB/s (chỉ tiêu < 120) |
| Khung JSON / nhị phân | 200 / 767 |
| Tilt bám được | pitch −3.16° … +1.99° |
| Vực giả trên sàn phẳng | **0** |
| FSM | 200/200 `OK` |
`vslam_node --replay cliff.vsr`: phát đúng nhịp thật, pose tiến 0.777 → 2.247 m,
báo rõ khi hết bản ghi.
## Hai lỗi tìm ra khi dựng runtime
| Lỗi | Hậu quả |
|---|---|
| `ReplaySource` phát theo thời gian thật bằng `SleepUntil(Steady() + nanoseconds(0))` — **ngủ 0 ns** | `speed` và `deterministic=false` không có tác dụng gì; bản ghi 8 giây chạy xong trong 0.4 giây. Trên web UI nó trông **giống hệt** "replay bị treo ở khung cuối". |
| Web hiện `cliff` từ số đo đã cũ | Bản ghi phát hết thì cờ kẹt lại và web báo "VỰC PHÍA TRƯỚC" mãi mãi, kể cả khi FSM đã bỏ qua nó từ lâu (`cliff_timeout`). Giờ dùng **chính** ngưỡng FSM dùng — web và FSM không được nói hai chuyện khác nhau. |
## SLAM trong vòng
```
vslam_node --sim --slam --slam-db "" --slam-mode mapping
```
| | |
|---|---|
| `map→odom` correction | tới **0.048 m** — thật, không phải 0 |
| `process_ms` | p50 2.0, p95 11.2, max 16.9 ms (sim đơn giản, đồ thị nhỏ) |
| Sai số vs ground truth | max 0.043 m |
| Băng thông tổng | 73.4 kB/s |
**Bản đồ của bộ mô phỏng chỉ hiện khi SLAM chưa có bản đồ của nó.** Hiện bản đồ
gốc mà không nói gì là gian lận: nó đẹp vì nó là sự thật, không phải vì SLAM
làm tốt. Khi chưa bật SLAM, web báo `slam.mode = "off"`.
### Nhịp dựng bản đồ: theo CHI PHÍ ĐO ĐƯỢC, không theo hằng số
Một tần số cố định sai ở **cả hai** đầu:
- **0.5 Hz** (bản đầu): đồ thị còn nhỏ, xuất hết 20 ms, mà vẫn bắt người dùng
đợi 2 giây mỗi lần — khung SLAM trông như treo đúng lúc họ muốn nhìn nó đầy
dần.
- **2 Hz cố định**: khi đồ thị lên 1990 node thì `OccupancyGrid::update()` mất
5.65 s, và luồng slam không còn làm gì khác được.
Nên nhịp theo chi phí thật: sau mỗi lần xuất, chờ
```
nghỉ = thời_gian_xuất × (1/duty − 1) duty = 0.25
```
để việc dựng bản đồ không chiếm quá 1/4 luồng slam. `map_rebuild_rate_hz` giờ
là **trần**, không phải tần số cố định.
Đo được, cùng một binary:
| đồ thị | cập nhật | băng thông |
|---|---|---|
| nhỏ (đang quét, ~6 m) | **3.4 lần/s** | 56.5 kB/s |
| 2716 node (`map_hospital.db`) | **0.07 lần/s** | 39.8 kB/s |
Tự động lùi ra khi bản đồ lớn, gần như realtime khi còn nhỏ — mà không ai phải
chỉnh tham số.
### `map_rebuild_rate_hz` — một lỗi suýt lọt
Ở chế độ mapping đồ thị đổi ở **gần như mọi khung**, nên điều kiện "chỉ dựng
lại bản đồ khi đồ thị đổi" là **không đủ**: đo được `SlamLoop` dựng bản đồ
**9 lần/giây**. `OccupancyGrid::update()` quét lại toàn bộ cache mỗi lần (5.65 s
cho 1990 node trên `map_hospital.db`), và trên một bản đồ thật 2000×2000
(24.6 kB sau RLE) thì 9 lần/giây là **221 kB/s** — gần gấp đôi cả ngân sách
120 kB/s của toàn bộ web UI.
Đây đúng là lớp lỗi mà kế hoạch đã cảnh báo ("để mỗi nguồn tự gửi" từng cho ra
109 kB/s vì PATH gửi ở 9.8 Hz thay vì 1 Hz). `system.yaml
web.map_rebuild_rate_hz: 0.5` — đo lại: **0.50 lần/giây**, băng thông 73.4 kB/s.
### Quy trình: quét bản đồ rồi định vị lại
```
# 1. Quét. Ctrl-C khi xong -- bản đồ được LƯU.
vslam_node --sim --slam --slam-db ~/map.db --slam-mode mapping
# 2. Định vị lại vào chính nó.
vslam_node --sim --slam --slam-db ~/map.db --slam-mode localization
```
Đo được trên một vòng quét (283 node, DB 2.85 MB):
| | |
|---|---|
| `localized` | 301/301 mẫu, từ 0.08 s |
| `process_ms` | p50 **1.0**, p95 **2.2** ms |
| Sai số vs ground truth | trung bình **1.1 cm**, max **1.7 cm** |
### Hai lỗi chặn đúng quy trình này, cả hai im lặng
**1. Bản đồ không bao giờ được lưu.** `Runtime` không gọi `slam_->Close()`, nên
destructor chạy `Close(false)` — **vứt bỏ**. Một phiên quét dài xong không để
lại gì, và **không có lỗi nào**: file `.db` vẫn tồn tại, chỉ là trống. Giờ
`Join()` gọi `Close(save)` với `save` chỉ đúng ở chế độ mapping *và* khi có
đường dẫn thật — chế độ localization **không** lưu, vì ghi phiên định vị vào
bản đồ đã quét sẽ làm nó phình dần mà không ai có ý đó.
**2. Định vị lại sai 1.08 m mà vẫn báo `localized`.** Ở chế độ localization
RTAB-Map khởi động từ pose **cuối cùng** của phiên quét, không phải từ gốc. Nên
robot vật lý ở (0,0) còn RTAB-Map tưởng nó ở cuối quỹ đạo. `map→odom` bằng đúng
sai số — SLAM đang *đẩy* pose đi sai chỗ, và cờ `localized` vẫn true.
Đây đúng là điều đã đo ở `SLAM.md`: **RTAB-Map không định vị toàn cục được bằng
scan-only.** Hệ thật giải quyết bằng `dock_init.py` phát `/initialpose` từ dock
— robot **luôn** biết nó bắt đầu ở đâu.
`--slam-init-pose x,y,yaw` là tương đương. Trong mô phỏng nó mặc định lấy vị
trí xuất phát, và log nói rõ đó là *"thay cho dock"* — một tiện nghi của mô
phỏng, không phải thứ robot thật có miễn phí. Không có nó thì log cảnh báo to
thay vì chạy im lặng.
> **108.4 cm → 1.7 cm** chỉ bằng việc đặt pose ban đầu.
### Localization cần bản đồ — cổng đã siết
`--slam-mode localization` với `database_path` rỗng (DB trong RAM) từng **chạy
im lặng**: `process_ms` 0.3–2.4 ms và `map→odom` luôn bằng 0, trông y hệt "SLAM
đang chạy tốt". Giờ bị từ chối khởi động với thông báo chỉ thẳng vào cách sửa.
## Ground truth
Chỉ có khi mô phỏng. Đi **thẳng** từ nguồn lên web — không stage nào được đọc,
đó là điều kiện để nó dùng làm thước đo. JSON có khối `gt` với `x/y/yaw`,
`roll/pitch` **thật**, và `err` (sai số vị trí, tính ở server để client không
trừ nhầm khi map và gt khác gốc toạ độ).
Web vẽ tam giác xanh lá mờ cho ground truth, tam giác đặc cho pose ước lượng —
cùng một hàm `drawRobot()`, vì hai bản chép của cùng một hình sẽ lệch nhau ngay
lần sửa đầu tiên và lúc đó không so sánh được nữa.
Đo được với EKF (chưa SLAM): sai số **0.1–3.8 mm** qua 15 s lái. Con số đó
trước đây không nhìn thấy được.
## Chưa có
- **`--live`** — driver LakiBeam / RealSense / base chưa viết, bị chặn bởi
thông tin phần cứng chưa có.
- **Ghi bản ghi trong node** — `system.yaml` có khối `record:` nhưng
`Runtime` chưa nối `RecordWriter` vào. Hiện dùng `tools/vslam_record`.
- **Watchdog tiến trình** — `system.yaml` có `watchdog.stage_timeout` nhưng
chưa có stage nào báo nhịp.
## Gieo pose xuất phát khi chạy mô phỏng
Odometry luôn khởi tạo ở **gốc**. Trên robot thật đó là đúng: frame `odom` có
gốc ở chỗ robot vừa khởi động, và SLAM kéo nó về khớp bản đồ qua `map→odom`.
Trong mô phỏng thì khác. Bản đồ (ví dụ `hospital.yaml`) ở một hệ toạ độ **cố
định**, và `--x --y` đặt robot vào một chỗ cụ thể trong đó. Nếu odometry vẫn
bắt đầu ở (0,0):
```
pose (ước lượng): x=0.00 y=0.00
ground truth : x=-5.99 y=-2.91
```
Hậu quả: robot ước lượng vẽ ở (0,0) — **một phòng khác hẳn** chỗ nó đang
đứng; và bản đồ SLAM cũng dựng từ gốc nên **lệch** với bản đồ thế giới đúng
bằng vị trí xuất phát, khiến hai khung ở chế độ "chia đôi" không chồng khớp
được.
`Runtime::Start()` giờ gieo `sim_start_*` vào `WheelOdometry`, `EkfSe2` và
`RtabmapSlam::SetInitialPose()` — kể cả ở chế độ **mapping**, không chỉ
localization. Đó là tương đương mô phỏng của *"robot biết nó khởi động ở đâu"*;
trên phần cứng thật đó là việc của dock (`--slam-init-pose`).
Đo lại với `--x -5.99 --y -2.91`:
| | |
|---|---|
| pose ước lượng | (−1.83, −2.91) |
| ground truth | (−1.82, −2.91) |
| sai số | **0.014 m** |
| gốc bản đồ SLAM | (−6.51, −3.44) — đúng quanh chỗ xuất phát |
⚠️ Chỉ gieo khi **thực sự có** `--x/--y/--yaw`. Mặc định (0,0,0) giữ nguyên
hành vi cũ, nên các kịch bản hồi quy không đổi baseline.
## The gioi Gazebo lam nguon su that (2026-09-18)
`--world X.world` doc thang file world cua Gazebo. Mesh **va cham** duoc raster
hoa thanh luoi chiem dung cho mo phong; mesh **hien thi** duoc gui cho khung 3D
qua `GET /api/world.bin`. Ca hai va tu the do dac deu o MOT he toa do.
Truoc do the gioi mo phong den tu `map_hospital.db`. Luoi do co goc o cho robot
BAT DAU phien quet -- lech **~18 m theo y** so voi he toa do Gazebo, nen khong
the dan do dac cua world len no.
| | do duoc |
|---|---|
| Luoi hospital.world | 543x1181 @ 0.05 m (27.2 x 59.1 m), 78346 o bi chiem |
| Model | 181 doc duoc, 3 bi bo vi pose hong |
| Hinh hoc 3D | 67 hinh hoc / 178 the hien / 189k tam giac, 6.5 MB |
| Mau | 65/67 lay tu texture, 2 con lai la men su mac dinh |
| Cho xuat phat thoang nhat | (1.03, -25.07), ban kinh 4.75 m |
### Nam quy uoc phai ton trong, khong cai nao co the doan
Mot toa nha 25 x 51 m da lan luot raster ra **262 x 297 m**, roi **263 x 146 m**,
roi **25 x 3 m cao 56 m** -- moi lan vi mot ly do khac, va **khong lan nao co
loi hay canh bao**. Ca nam deu la loi im lang.
| # | Quy uoc | Trieu chung khi bo qua |
|---|---|---|
| 1 | `.obj` cua bo nay la **Z-up, met**; `.dae` la **Y-up, cm** | Ap mot quy uoc chung: 262 x 297 m |
| 2 | `<scale>` nam trong `<mesh>` cua **model.sdf** | Xe day 2.4 m thanh 236 m; the gioi 263 x 146 m |
| 3 | `<rotate>` cua node COLLADA **da bao gom** phep doi Y-up -> Z-up | Ap ca `<up_axis>` lan node: tuong ra 25 x 3 m, **cao 56 m** |
| 4 | `<matrix>` la mot cach viet node transform khac | Sofa ra 24.4 m, buc tranh ra 5 cm -- ca hai trong file khai `meter="0.01"` |
| 5 | Duoi file co the VIET HOA (`.DAE`) | 15 model roi vao bo doc OBJ va bien mat khoi ca luoi lan khung 3D |
Quy uoc 3 duoc quyet dinh bang cach **hoi chinh ma tran** chu khong tin the
`<up_axis>`: quay vector Y don vi, ra +-Z thi node da doi truc roi. Ba file
khong co phep xoay nao van duoc lat -- dung nhu chung can.
`<unit meter>` **khong dang tin**: ba file cung khai `0.01` nhung thuc te la
mm, mm va met. Ti le that nam trong `<matrix>`.
### Pose hong co san trong file world
`hospital.world` co ba model mang `z = -7.57769e+08` (`StorageRack_1`,
`WhiteChipChair_1`, `TrolleyBed_1`): vat roi xuyen san trong mot phien Gazebo
nao do roi world duoc luu lai. Gazebo cung khong hien chung. Chung bi bo o khau
nap, kem canh bao.
### Mau lay tu texture, khong tu `<diffuse>`
`<diffuse>` cua DAE tro toi texture, va `Kd` cua MTL tra ve `0.8 0.8 0.8` xam --
mau that nam TRONG anh. 149 texture PNG tong cong 74 MB, qua lon de gui cho
trinh duyet, nen `tools/gen_model_colors.py` rut chung thanh mot bang
`resources/model_colors.json` (2.3 kB).
Lay **trung vi** chu khong trung binh: nhieu texture co vien alpha va vet logo
sam mau keo trung binh lech. `thumbnails/` phai bo qua -- do la anh chup ca
model tren nen xam.
### Bai kiem
`test_gazebo_world` (8 case) chay tren fixture rieng `test/data/world/` -- BA
hop cung kich thuoc that (2.0 x 1.0 x 0.5 m) khai bao theo ba cach khac nhau,
cong mot pose hong. **Khong can bo model AWS 3 GB.**
Da kiem bang cach co tinh pha tung quy uoc mot: bo `<scale>`, bo `<matrix>`,
lam so duoi phan biet hoa thuong, bo loc pose -- moi lan deu co test do.
Phep kiem manh nhat la `BaQuyUocChoCungKetQua`: tung hop dung kich thuoc van co
the do nhieu loi bu tru nhau, nhung bat ba hop **bang nhau** thi khong the bu.
`www_world_mesh` chay bo giai ma JavaScript tren chinh khoi C++ sinh ra. Hai ban
cai dat cua mot dinh dang, lech nhau mot byte thi khung 3D ra rong -- ma mot
khung 3D rong co dung moi chi so van hanh voi mot khung dung: HTTP 200, dung so
byte, khong ngoai le.
### `<up_axis>` phai bi BO QUA hoan toan (2026-09-18, sua)
Ban dau toi quyet dinh co lat truc bang cach **hoi ma tran node**: quay vector
Y don vi, ra +-Z thi node da doi truc roi, khong thi lat. Quy tac do **sai**.
Cung mot buc tuong, hai file, hai cach:
| file | dinh (m) | node |
|---|---|---|
| `..._walls_collision.dae` geom ID3 | (56.12, **3.00**, 25.12) -- Y-up that | `0 1 0 90` + `0 0 1 -270` |
| `..._walls_visual.dae` geom ID43 | (25.12, 56.12, **3.00**) -- DA la Z-up | **rong** |
Node rong o day nghia la *"khong can doi"*, khong phai *"chua doi"*. Phep doan
hieu nham thanh cai thu hai va lat ID43: buc tuong 3 m thanh mot **thanh dung
dung cao 56 m** giua san. Mat bang van dung 25 x 56 m, va luoi chiem dung cung
van dung -- `RasterizeGazeboWorld` chi lay dai z [0.05, 1.20] nen no **khong bao
gio nhin thay chieu cao**.
Do la ly do bai kiem cu khong bat duoc: no do tren LUOI. Da them
`ChieuCaoHinhHocDung` do tren HINH HOC, cong fixture `box_zup` (khai Y_UP, du
lieu da Z-up, node rong) tai hien dung ID43.
Quy tac dung: **chi ap node transform va `<unit>`, khong bao gio ap
`<up_axis>`.** The do noi ve he toa do cua bo XUAT, khong phai cua du lieu.
### Khung SLAM trong: phai noi ra vi sao
`vslam_node --sim --world ...` khong bat SLAM. Do WebSocket xac nhan: khong
`--slam` thi **0 khung `MAP_FULL`**, `slam.mode = "off"`, `map_version = 0`;
co `--slam` thi 25 khung trong 8 giay, `map_version = 182`.
Nhung khung phai chi hien mot man DEN, con nhan ghi *"SLAM dang dung"* -- ke ca
khi `slam.mode === 'off'`. Nguoi van hanh di tim loi trong SLAM trong khi su
that la lenh thieu mot co.
Cung lop loi voi chuyen web hien `cliff` tu so do da cu 10 giay trong khi FSM da
bo qua no: **nguoi van hanh tin cai ho nhin thay**. Gio nhan doc `slam.mode`, va
chinh khung do viet ra `SLAM dang TAT -- them --slam vao lenh`.
Da them log dem NOI DUNG ban do moi lan no doi:
```
slam: ban do 254x167 -- 356 bi chiem, 10305 trong, 31757 chua biet
```
0 o trong = tia khong duoc truy (`Grid/RayTracing`). 0 o bi chiem = khong cam
bien nao nap vao (`Grid/Sensor`). Ca hai bang 0 = ban do rong. Truoc day khong
co gi dem noi dung, nen `RGBD/CreateOccupancyGrid` mac dinh `false` da mat nhieu
lan do moi tim ra.
## Bumper chot lai thanh BE TAC (2026-09-18)
Nguoi van hanh bao: dam vao vat can, bumper kich, bam RESET khong chay tiep
duoc. Dung lai duoc bang `vslam_node --sim --world ...` roi LUI het toc do vao
tuong:
```
1) LUI het toc do -> dam pose=( -6.18, -3.00) state=BUMPER
POST /api/safety/reset HTTP 200
2) ngay sau reset, khong ra lenh pose=( -6.18, -3.00) state=BUMPER
3) ra lenh LUI pose=( -6.18, -3.00) state=BUMPER
POST /api/safety/reset HTTP 200
4) reset roi ra lenh XOAY pose=( -6.18, -3.00) state=BUMPER
di chuyen duoc sau khi dam: 0.000 m => BE TAC
```
Hai nguyen nhan chong nhau:
1. `Step()` tra ve som o nhanh bumper voi `out.cmd` bang 0 **tuyet doi**.
2. Phep do bumper kiem vanh robot o vi tri **HIEN TAI**. Robot dang ti vao vat
can van bao cham, nen chot dat lai ngay o buoc sau khi reset.
Khong lui ra duoc thi khong reset duoc, khong reset duoc thi khong lui ra duoc.
Reset van tra `HTTP 200` va **khong noi gi**, nen nguoi van hanh bam lai nhieu
lan ma khong hieu.
### "Chan tien, cho lui" KHONG phai loi giai
Do la thu dau tien toi lam, va no **sai**. `BumperReading` chi mang mot mat na
cong tac (`b.mask = hit ? 1u : 0u`); mo phong dung dung mot bit va robot that
cung khong hua se noi duoc huong va cham.
Lan dam that su trong bai dung lai la robot **LUI** vao tuong -- duong thoat
chinh la **TIEN**, dung chieu vua bi chan. Chay lai voi ban sua do: van 0.000 m.
Bumper khong biet vat can o dau. Thu BIET la LiDAR.
### Cach lam dung
Khi bumper dang chot:
| chieu | xu ly |
|---|---|
| tien | di qua **dung cong quat truoc** nhu luc binh thuong (`min_front >= stop_distance`, `front_usable >= min_front_rays`, co scan), chi ha toc do xuong `escape_linear` |
| lui | cho, gioi han `escape_linear` |
| xoay | cho, gioi han `escape_angular` |
Khong co scan thi **chan tien** -- khong xac nhan duoc thi khong doan.
`escape_linear = 0.10` m/s, `escape_angular = 0.4` rad/s trong `safety.yaml`.
Cong kiem cheo: `escape_* <= limits.max_*` (dang cham vat can khong phai luc di
nhanh hon), va `escape_linear > 0` lam node **tu choi khoi dong** -- bang 0 la
be tac, khong phai cau hinh an toan hon.
E-STOP van duoc kiem **truoc** bumper, nen no van dung tat ca.
Sau khi sua, dung kich ban do:
```
3) thu LUI (vao sau vat can) pose=( -6.18, -3.00) state=BUMPER
4) thu TIEN (huong thoat that) pose=( -6.04, -3.00) state=BUMPER
POST /api/safety/reset HTTP 200
5) reset sau khi da roi ra pose=( -6.02, -3.00) state=OK
```
`Reset()` gio canh bao khi bumper van dang cham, va `out.detail` phan biet
"bumper DANG cham -- lai cham de thoat roi reset" voi "bumper da cham -- can
reset": hai cai doi hoi hai hanh dong khac nhau.
Sau khoa bang 6 bai trong `test_safety_monitor`. Da kiem bang cach khoi phuc
hanh vi cu: 3 bai do.
## Scan ve lech 24 cm -- trong nhu robot bi troi (2026-09-18)
Nguoi van hanh bao: vanh quet LiDAR khong nam tren tuong, va "robot co mot
nhan ban o canh".
### Do truoc, doan sau
Sai so uoc luong vs ground truth, do qua 5 doan lai (tien, xoay, di vong):
```
1) tien 5 s lech=0.006 m / -0.07 deg
4) xoay nguoc 4 s lech=0.009 m / +0.06 deg
6) dung lai lech=0.009 m / -0.07 deg
```
**Duoi 1 cm, khong tang dan.** Khong co troi that. Nen lech phai o khau VE.
Chieu diem quet len luoi the gioi va dem:
| | diem roi trung tuong |
|---|---|
| dat thang vao pose BASE (nhu cu) | 754/944 (**79.9 %**) |
| bu `laser_x = 0.24` truoc | **944/944 (100 %)** |
### Nguyen nhan
Khung `SCAN` di qua day o dang **POLAR trong frame LASER**. Trinh duyet doi sang
Descartes (`r·cos a`, `r·sin a`) roi ap **pose cua BASE** -- bo qua hoan toan
`base_link -> laser_link` = `[0.24, 0, 0.125]` trong `robot.yaml`.
Ca vanh quet bi lui 24 cm. Comment trong `v3dSetScan()` con ghi *"trong frame
BASE"*, tuc la gia dinh sai da duoc VIET RA va khong ai kiem lai.
Loi nay khong lam gi hong theo nghia van hanh: dung so tia, dung nhip, dung tam
nhin, khong mot ngoai le nao. No chi khien nguoi van hanh di tim loi trong
odometry va SLAM -- cho khong co loi.
`laser_x`/`laser_y` **da duoc gui san** trong JSON `robot` (`json_writer.cc`);
chi co dieu ca hai khung deu chi dung `laser_z`.
### Cloud camera thi DUNG
Do cung cach: **3491/3491 diem (100 %)** roi trung tuong khi coi la
`base_footprint`. `GravityAlign::Align()` ghep `TiltLift × cam_to_base` nen
extrinsic camera (ke ca tinh tien) da duoc ap o tang perception. Khong sua gi.
### "Nhan ban" la ground truth
`lyGt` bat mac dinh, va `v3dBuildRobot()` duoc goi lan hai cho GT roi to lai
`0x00c853` voi `opacity 0.25`. Do la mot lop hien thi co chu y, tat duoc bang
o "ground truth". Voi sai so 9 mm hai hinh gan nhu trung nhau; cai trong nhu
lech la phan than trong suot lo ra sau qua phoi canh.
### Bai kiem
`www_scan_frame` chay **chinh** `v3dSetScan()` cua app3d.js tren mot hanh lang
dung san, roi kiem diem quet co roi trung tuong khong. Phep kiem that nam o
**tia cheo 45 do**: tia thang ben (±90°) khong doi y khi bu `laser_x` nen chung
mot minh khong phan biet duoc co bu hay khong.
Da kiem bang cach bo lai phep bu: bai kiem do va in dung thu pham --
`LECH 0.240 m theo x == dung bang laser_x!`
### "Nhan ban o canh": cau truc nhom lech mot tang (2026-09-18)
Bao cao ban dau toi giai thich la phoi canh. **Sai.** Co mot lech THAT, va no
nam o cau truc:
```
robotGroup = new Group() <- y = 0
└ v3dBuildRobot() <- y = wheel_radius (phep nang than)
gtGroup = v3dBuildRobot() <- y = wheel_radius, KHONG co lop boc
```
`v3dSetPose()` viet `position.set(p.x, 0, -p.y)`, xoa y cua nhom **NGOAI**. Voi
`robotGroup` phep nang nam o tang trong nen song sot; voi `gtGroup` no nam dung
tang bi xoa.
Hinh ground truth tut xuong **0.075 m**. O goc camera nhin nghieng, chenh lech
do chieu ra thanh mot khoang cach **NGANG** nhin thay duoc -- trong y het mot
hinh robot thu hai dat canh, trong khi sai so uoc luong that chi 9 mm.
`base_link` nam o TAM TRUC banh chu khong o san, nen phep nang la bat buoc;
comment giai thich dieu do da co san ngay trong `v3dBuildRobot()`.
Sua hai cho:
- `gtGroup` duoc boc y het `robotGroup`.
- `v3dSetPose()` chi dat `x` va `z`, khong dung toi `y`.
Bai kiem `www_robot_marker` khoa lai bon dieu, trong do manh nhat la: **tru
LiDAR tren hinh robot va diem quet phai o CUNG cao do**. Do la hai duong code
doc lap (`v3dBuildRobot()` va `v3dSetScan()`), nen chung chi khop khi ca hai
cung dung.
Da kiem bang cach khoi phuc tung loi mot: bo lop boc -> `khoang cach ve` va
`cao do than ground truth` do; khoi phuc `position.set(p.x, 0, -p.y)` ->
`v3dSetPose giu cao do san co` do.
### Quy dao dong bang o goc the gioi (2026-09-18)
`WebLoop()` doc `snap.pose_map` de thua hoa quy dao **TRUOC** khi tinh no:
```cpp
const Pose2D p = snap.pose_map; // <- dong 765, van la (0, 0, 0)
...
snap.pose_map = Pose2DCompose(map_correction_, ekf_pose); // <- dong 789
```
`WebSnapshot snap;` la bien moi moi vong, nen lan doc do luon lay gia tri khoi
tao mac dinh. Lan dau no day **goc the gioi** vao quy dao; tu do
`Distance2D(back, (0,0)) == 0` nen khong bao gio them diem nao nua.
Lop "duong di" vinh vien la MOT diem dung yen o (0, 0), 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**, va con so do da nam san trong phep do bang thong o
P1 ma khong ai thac mac.
Do sau khi sua: **21 diem sau 25 giay lai**.
⚠️ **Khoang trong con lai:** `Runtime::WebLoop()` khong co bai kiem nao.
`tools/vslam_replay` (nen cua `regress.sh`) chay duong ong cam bien chu khong
chay vong web, nen ca lop bug "thu tu trong snapshot" nay khong duoc phu. Loi
tren chi tim ra khi doc code de tra loi mot cau hoi khac.

194
docs/SLAM.md Normal file
View File

@@ -0,0 +1,194 @@
# vslam_slam — bọc RTAB-Map
Thay cho `rtabmap_ros`. Không có kiểu dữ liệu nào của RTAB-Map lọt ra khỏi
`slam_types.h`, nên `app/` và `vslam_web` không phải biên với RTAB-Map, và
tắt hẳn bằng `-DVSLAM_BUILD_SLAM=OFF` thì sáu lib kia vẫn build.
## Ba điều phải nhớ
1. **`Process()` chặn 100–600 ms.** Luồng gọi nó không được chia sẻ mutex nào
với luồng safety. Trong bản ROS điều này được bảo đảm miễn phí bởi tiến
trình riêng + `respawn="true"`; ở đây nó là quy tắc review, và
`RtabmapSlamImpl` có **mutex riêng** chỉ bảo vệ bốn giá trị đầu ra —
`rtabmap` không nằm dưới nó.
2. **RTAB-Map lưu dữ liệu nén.** `gridGroundCellsRaw()` trả ma trận rỗng, im
lặng, cho tới khi gọi `uncompressData()`. Đã mắc lỗi này một lần khi đo
`probe_rtabmap` trên `map_hospital.db` — "1990 node, 0 ô".
3. **Ba lớp phòng thủ cho `Optimizer/Strategy`.** DB hiện có nhớ `"2"`
(GTSAM). Trên Jetson build `-DWITH_GTSAM=OFF` mà để RTAB-Map đọc tham số
từ DB thì nó chọn lại GTSAM và crash thiếu symbol. Nên:
`init(..., loadDatabaseParameters=false)` + ghi đè tường minh + **assert
sau init**. Một lớp không đủ: chính hàm `init()` là chỗ dễ lọt.
## Đo trên `map_house.db` (240 node, 196 pose tối ưu, 62920 từ vựng)
### g2o so với GTSAM — rủi ro R2, đã đóng
| Optimizer | p95 ms | max ms | ATE (căn chỉnh) |
|---|---|---|---|
| `1` g2o | 1201 | 1577 | **0.2378 m** |
| `2` GTSAM | **3080** | **4545** | **0.2378 m** |
ATE **giống hệt**, GTSAM chậm 2.6×. Bỏ GTSAM không mất gì về độ chính xác —
và nó là mục khó nhất khi build trên arm64 (không có trong apt Ubuntu, PPA
`borglab` không publish arm64).
### Đối chứng với công cụ chính thức
Phép kiểm quan trọng nhất của P6: chạy `rtabmap-reprocess` — công cụ replay
chính thức của RTAB-Map — với **đúng** bộ tham số, rồi so cả hai với DB gốc.
Nó tách "wrapper gọi sai API" ra khỏi "cấu hình này vốn không đạt".
| | ATE thô | ATE căn chỉnh |
|---|---|---|
| `rtabmap-reprocess` (chính thức) | 0.0104 m | **0.0074 m** |
| wrapper, extrinsic **sai** | 0.3176 m | 0.2378 m |
| wrapper, extrinsic **đúng** | 0.0207 m | **0.0146 m** |
Phần còn lại giữa 0.0146 và 0.0074 là hao hụt của việc dựng lại tia từ DB
(`vslam_slam_bench` bin 945 điểm XYI vào 1081 tia), không phải của thư viện.
Phần cứng thật cho tia trực tiếp.
### Lỗi đã tìm ra: quên setter cho extrinsic
`RtabmapSlam` có biến `laser_to_base` nhưng **không có setter** — nó mặc định
là đồng nhất. Laser trên robot này ở `xyz = (0.24, 0, 0.20)`. Mọi scan bị đặt
lệch 24 cm so với pose. ICP vẫn hội tụ (nó chỉ thấy cả thế giới dịch đi) nhưng
đồ thị tích lũy sai số:
> **ATE 0.2378 m → 0.0146 m** chỉ bằng việc gọi `SetExtrinsics()`.
Không có gì báo lỗi. Có test khóa
(`SensorDataBuilder.FrameLaserSaiLamMoiDiemLechDungBangNo`).
## Định vị lại: giới hạn là `Icp/MaxCorrespondenceDistance`
RTAB-Map **không định vị toàn cục được bằng scan không**. Vòng đóng toàn cục
đi qua túi từ thị giác; `RGBD/ProximityBySpace` chỉ tìm quanh ước lượng hiện
tại. Không có pose ban đầu thì ở chế độ localization nó không bao giờ bắt được
vào bản đồ cũ — đo được: ATE thô **9.80 m**, 0 liên kết.
Hệ thật giải quyết đúng như vậy: `dock_init.py` phát `/initialpose` từ dock.
Robot **luôn** biết nó bắt đầu ở đâu.
Với pose ban đầu đúng: ATE **0.0051 m**, 194 liên kết lân cận, hội tụ ngay.
Bài kidnapped-robot (pose ban đầu **sai** đi N mét / M độ):
| kidnap | `Icp/MaxCorrespondenceDistance` | liên kết | ATE thô | hội tụ |
|---|---|---|---|---|
| 0.10 m / 3° | 0.15 (mặc định) | 90 | 0.0118 m | **ngay** |
| 0.30 m / 5° | 0.15 | 90 | 0.0321 m | 18.1 s |
| 0.50 m / 10° | 0.15 | **0** | 1.2990 m | **không** |
| 1.00 m / 20° | 0.15 | **0** | 2.5012 m | **không** |
| 1.00 m / 20° | **1.0** | 164 | 0.1028 m | **19.1 s** |
Cơ chế rõ ràng: ICP chỉ ghép được điểm cách nhau dưới
`Icp/MaxCorrespondenceDistance`. Đặt 0.15 m nghĩa là **pose ban đầu phải đúng
trong khoảng 15 cm**; quá 0.5 m thì không còn tương ứng nào, ICP thất bại,
`Icp/CorrespondenceRatio = 0.3` không đạt, liên kết bị loại.
**Đánh đổi:** nới lên 1.0 m cho phép phục hồi từ 1 m / 20° nhưng ATE tụt từ
0.005 m xuống 0.102 m. Nên dùng **hai bộ tham số**: bộ lỏng cho pha định vị
lại, rồi siết lại khi đã bắt được. Đó là chỗ của `reloc_gicp` trong kế hoạch.
## `process_ms` chưa đạt chỉ tiêu
Chỉ tiêu P6 là p95 < 700 ms **trên Jetson**. Đo trên x86 dev: **p95 722–1008
ms**, max 1155 ms.
Nhưng `rtabmap-reprocess` với **cùng** bộ tham số cũng tốn 600–1000 ms mỗi
node. Nên đây **không** phải phí tổn của wrapper — nó là phí tổn của cấu hình:
`RGBD/NeighborLinkRefining=true` cộng `RGBD/ProximityBySpace=true` chạy ICP
trên scan 1081 tia mỗi khung.
Chưa tinh chỉnh. Các nút để thử khi có Jetson: `Icp/VoxelSize` (0.05 → 0.10),
`RGBD/ProximityPathMaxNeighbors` (10 → 5), `Rtabmap/DetectionRate`.
## Chưa kiểm được
- Chưa chạy trên Jetson arm64. OpenCV đôi (JetPack 4.8 vs apt 4.5.4) vẫn là
rủi ro **CAO** chưa gỡ.
- `--with-images`: `map_house.db` có 62920 từ vựng nhưng `getNodeData` trả 0
ảnh — ảnh không được lưu trong DB này, nên không so được scan-only với
scan+ảnh trên chính corpus này.
- `reloc_gicp` chưa viết.
- `ExportOccupancyGrid` từ một `Rtabmap` đang chạy chưa đo (mới đo đường đọc
thẳng từ DB, qua `probe_rtabmap`).
## `RGBD/CreateOccupancyGrid` — mặc định `false`
RTAB-Map **không** dựng lưới occupancy cho từng node trừ khi bật tham số này.
Mặc định của nó là `false`, và wrapper này không đặt nó trong một thời gian
dài.
Triệu chứng: đồ thị vẫn lớn, vòng đóng vẫn chạy, `map_version` vẫn tăng — và
`ExportMap()` trả về một lưới **toàn ô chưa biết**. Đo được: quét 25 giây rồi
xuất ra 94×21 ô với **0 bị chiếm, 0 trống, 1974 chưa biết**.
Trên web UI nó hiện thành một tấm xám đặc lớn dần mà không bao giờ có nội
dung — trông **hệt như "khung SLAM không realtime"**, và đó là hướng đã đi sai
một lúc trước khi tìm ra chỗ này: tôi đã sửa nhịp cập nhật bản đồ (0.5 → 3.4
lần/s) trong khi vấn đề là *chẳng có gì để cập nhật*.
`map_hospital.db` có lưới vì `rtabmap_ros` đặt tham số này; wrapper tự viết
phải tự đặt.
```cpp
{"RGBD/CreateOccupancyGrid", "true"},
```
Sau khi sửa, cùng một lộ trình:
| t (s) | lưới | bị chiếm | trống | chưa biết |
|---|---|---|---|---|
| 0 | 353×421 | 697 | 57070 | 90846 |
| 24 | 398×421 | **1489** | **64388** | 101681 |
### Bài học
Một tham số mặc định `false` của thư viện bên thứ ba làm cả một tính năng im
lặng không hoạt động, trong khi **mọi chỉ số khác đều khoẻ**: node tăng,
`map_version` tăng, `process_ms` hợp lý, không một dòng lỗi nào.
Cách duy nhất phát hiện là **đếm nội dung**, không phải đếm sự kiện. Kiểm
`ExportMap()` trả về bao nhiêu ô *đã biết* — nếu là 0 thì SLAM đang chạy mà
không dựng gì.
## Khong quet TIEP vao mot DB da co (2026-09-18)
`--slam-mode mapping --slam-db <DB da co node>` lam RTAB-Map 0.21.13 nem o **moi
khung**:
```
DBDriverSqlite3.cpp:4854::addStatisticsQuery() Condition (rc == SQLITE_DONE)
not met! [DB error (0.21.13): UNIQUE constraint failed: Statistics.id]
```
Do duoc: 60 giay lai, `map_version` **dung yen o 0**, khong mot khung ban do nao
duoc dung. Tien trinh khong chet -- moi loi goi vao RTAB-Map deu boc try/catch
theo bai hoc UASSERT -- nen tu ngoai nhin vao SLAM "dang chay". Nguoi van hanh
lai het ca tang roi moi biet khong co gi duoc luu.
**Khong phai loi cua DB.** Localization tren CHINH DB do chay sach: 0 ngoai le,
`map_version` len den v11 trong 20 giay, sai so vs ground truth **0.004 m**.
Da loai hai gia thuyet:
- `SetInitialPose()` trong che do mapping: RTAB-Map **bo qua** no khi
`_memory->isIncremental()`, nen no khong the la nguyen nhan.
- Tat `Rtabmap/PublishStats`: khong lam vi `proximity_id` doc tu chinh bang
statistics do, va id trung nghia la **node id bi dung lai** -- hong hon nhieu
so voi chuyen ghi thong ke.
`RtabmapSlam::Init()` gio **tu choi khoi dong** va chi ro hai duong di:
```
mapping vao DB da co 877 node: ...
- Quet lai tu dau : --slam-db <duong dan MOI>
- Dung ban do nay : --slam-mode localization --slam-init-pose x,y,yaw
```
Ba truong hop hop le van chay, da kiem: mapping vao DB moi (0 ngoai le), mapping
trong RAM (0), localization tren DB da co (0).

View File

@@ -0,0 +1,18 @@
# Project DOC LAP, khong phai subdirectory cua vslam_cpp.
#
# Ly do ton tai: chung minh rang `find_package(vslam_common)` thuc su chay --
# dieu ma README cua ca obstacle_detection_core lan xloc_cpp deu hua nhung
# khong lam duoc, vi ca hai chi cai <name>Targets.cmake ma khong cai
# <name>Config.cmake.
#
# Day la tieu chi nghiem thu cua P0, khong phai vi du cho vui.
cmake_minimum_required(VERSION 3.16)
project(find_package_smoke LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(vslam_common REQUIRED)
add_executable(find_package_smoke main.cc)
target_link_libraries(find_package_smoke PRIVATE vslam::vslam_common)

View File

@@ -0,0 +1,64 @@
// Dung moi thu qua header DA CAI (include/vslam/...), khong phai qua cay nguon.
// Neu duong include bi sai giua in-tree va installed thi file nay se khong
// compile -- do dung la lop bug ma bo cuc include/vslam/ sinh ra de tranh.
#include <cstdio>
#include "vslam/channel.h"
#include "vslam/clock.h"
#include "vslam/config.h"
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
#include "vslam/transform_tree.h"
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
int main() {
// 1. Thoi gian
const vslam::UnixTime t = vslam::UnixTime::fromSec(1737000000.5);
std::printf("UnixTime: %s\n", t.toString().c_str());
// 2. Hinh hoc
const vslam::Quaternion q = vslam::QuaternionFromYaw(1.0);
std::printf("yaw round-trip: %.9f\n", vslam::YawFromQuaternion(q));
// 3. Cay TF -- dung ten frame that tu node_constants.h
vslam::TransformTree tree;
const vslam::FrameId bl = tree.Resolve(vslam::kBaseLinkFrame);
const vslam::FrameId laser = tree.Resolve(vslam::kLaserFrame);
vslam::Transform tf;
tf.translation = vslam::Vector3{0.24, 0.0, 0.125}; // laser_joint cua URDF cu
tree.SetStatic(bl, laser, tf);
vslam::Transform out;
if (!tree.LookupLatest(bl, laser, &out, nullptr)) {
std::fprintf(stderr, "lookup that bai\n");
return 1;
}
std::printf("base_link -> laser_link: x=%.3f z=%.3f\n", out.translation.x,
out.translation.z);
// 4. Channel
vslam::Channel<vslam::LaserScan> ch(4, "scan");
auto reader = ch.MakeReader("smoke");
ch.Freeze();
ch.Publish(std::make_shared<const vslam::LaserScan>(), t);
vslam::LaserScanPtr got;
if (!reader.TryRead(&got, nullptr)) {
std::fprintf(stderr, "channel that bai\n");
return 1;
}
// 5. Config
const vslam::ConfigNode cfg =
vslam::ConfigNode::LoadString("a:\n b: 1.5\n", "smoke");
std::printf("config a.b = %.1f\n", cfg["a"].require<double>("b"));
// 6. Log va duong dan
vslam::SetLogLevel(vslam::LogLevel::kInfo);
VSLAM_INFO("config dir = " << vslam::ConfigDir());
std::printf("\nfind_package(vslam_common) CHAY DUOC.\n");
return 0;
}

47
libs/CMakeLists.txt Normal file
View File

@@ -0,0 +1,47 @@
# Thu tu o day phan anh dung do thi phu thuoc:
#
# vslam_common
# |-- vslam_odometry (khong them dep ngoai)
# |-- vslam_safety (khong them dep ngoai)
# |-- vslam_drivers (+ librealsense2)
# |-- vslam_perception (+ PCL)
# |-- vslam_web (+ Boost.Beast, header-only)
# `-- vslam_slam (+ RTAB-Map, g2o, OpenCV, PCL)
#
# vslam_slam dung cuoi vi no la cai kho build nhat tren arm64. Tat no bang
# -DVSLAM_BUILD_SLAM=OFF thi sau lib con lai van build -- do la ca ly do de
# tach lib theo tap dependency thay vi theo chuc nang.
if(VSLAM_BUILD_COMMON)
add_subdirectory(vslam_common)
endif()
if(VSLAM_BUILD_ODOMETRY)
add_subdirectory(vslam_odometry)
endif()
if(VSLAM_BUILD_SAFETY)
add_subdirectory(vslam_safety)
endif()
if(VSLAM_BUILD_DRIVERS)
add_subdirectory(vslam_drivers)
endif()
if(VSLAM_BUILD_PERCEPTION)
add_subdirectory(vslam_perception)
endif()
if(VSLAM_BUILD_WEB)
add_subdirectory(vslam_web)
endif()
if(VSLAM_BUILD_SLAM)
add_subdirectory(vslam_slam)
endif()
# Thay Gazebo. Phu thuoc vslam_drivers vi no implement chinh cac interface
# driver -- y het ReplaySource.
if(VSLAM_BUILD_SIM)
add_subdirectory(vslam_sim)
endif()

View File

@@ -0,0 +1,67 @@
# Nen tang cua ca he. Dep ngoai: Eigen3 (chi header, dung trong geometry) va
# yaml-cpp (config). Khong gi khac -- moi lib kia phu thuoc lib nay nen giu no
# nhe la dieu kien de P0 build duoc truoc khi co RTAB-Map hay PCL.
find_package(Eigen3 REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(Threads REQUIRED)
vslam_add_library(vslam_common
PUBLIC_HDRS
vslam_common.h
unix_time.h
clock.h
log.h
config.h
node_constants.h
geometry.h
stats.h
json_parse.h
robot_model.h
teleop_model.h
channel.h
approx_sync.h
buffer_pool.h
transform_tree.h
# FIND_DEPS chi liet ke dep PUBLIC -- tuc la dep co mat trong
# INTERFACE_LINK_LIBRARIES cua target da cai, nen nguoi dung thu vien PHAI
# co chung. yaml-cpp link PRIVATE nen khong nam trong do: dua no vao day se
# bat nguoi dung phai cai yaml-cpp mot cach vo co.
#
# Nguoc lai, thieu mot dep PUBLIC o day thi find_package() that bai voi thong
# bao "links to target Threads::Threads but the target was not found" --
# dung loai loi ma file Config.cmake nay sinh ra de chan.
FIND_DEPS
Eigen3
Threads
)
# yaml-cpp: ten target khac nhau theo phien ban va theo cach cai.
# 0.6 (focal, apt) -> bien yaml-cpp_LIBRARIES, doi khi target `yaml-cpp`
# 0.7 (jammy, apt) -> target `yaml-cpp`
# >=0.8 / vcpkg -> target `yaml-cpp::yaml-cpp`
# Dung sai ten o day la loi link kho doc tren Jetson, nen do het truong hop.
if(TARGET yaml-cpp::yaml-cpp)
target_link_libraries(vslam_common PRIVATE yaml-cpp::yaml-cpp)
elseif(TARGET yaml-cpp)
target_link_libraries(vslam_common PRIVATE yaml-cpp)
else()
target_include_directories(vslam_common SYSTEM PRIVATE ${YAML_CPP_INCLUDE_DIR})
target_link_libraries(vslam_common PRIVATE ${YAML_CPP_LIBRARIES})
endif()
if(TARGET Eigen3::Eigen)
target_link_libraries(vslam_common PUBLIC Eigen3::Eigen)
else()
target_include_directories(vslam_common SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR})
endif()
# Moi target trong cay phai cung mot EIGEN_MAX_ALIGN_BYTES. Dat PUBLIC o day
# de no lan sang moi lib phu thuoc vslam_common -- do la toan bo cay.
# Xem ke hoach, muc "Bay arm64": hai phia compile voi gia tri khac nhau sinh
# loi alignment chi hien ra luc chay, tren arm64, khong tai lap on dinh.
target_compile_definitions(vslam_common
PUBLIC EIGEN_MAX_ALIGN_BYTES=${VSLAM_EIGEN_MAX_ALIGN_BYTES})
# PUBLIC: Channel va TransformTree deu co std::mutex trong header cong khai.
target_link_libraries(vslam_common PUBLIC Threads::Threads)

View File

@@ -0,0 +1,345 @@
#ifndef VSLAM_APPROX_SYNC_H
#define VSLAM_APPROX_SYNC_H
// Thay message_filters::Synchronizer<ApproximateTime<...>>.
//
// Cau hinh hien tai can khop lai: rtabmap.launch:235-237 dat approx_sync=true,
// sync_queue_size=30, dong bo scan + odom + depth + rgb.
// cliff_detect_nodelet.cpp:101-102 dong bo depth + camera_info.
//
// Thuat toan o day DON GIAN VA DE DOAN HON ApproximateTime cua ROS. ROS dung
// mot thuat toan toi uu cua so co the giu ban tin lai kha lau va rat kho suy
// luan khi mot nguon tut. O day:
//
// 1. Moi ban tin moi o stream PIVOT (scan, 25 Hz -- cham nhat) tao mot moc.
// 2. Voi moi stream khac, chon ban tin co |stamp - pivot| nho nhat, yeu cau
// <= max_slop_sec.
// 3. Phat khi:
// (a) du moi stream REQUIRED, va moi stream TUY CHON hoac da co hoac ban
// tin moi nhat cua no DA VUOT pivot (khong the khop hon duoc nua); hoac
// (b) now - pivot > wait_timeout_sec -- phat voi stream tuy chon de trong.
// 4. Pivot cu hon queue_size bi bo, dem vao dropped_queue.
//
// Nhanh (b) khong lam mat tin hieu: RTAB-Map chay duoc voi scan + odom ma
// khong can depth (subscribe_depth la tuy chon), chi mat visual word.
//
// SyncStats dem RIENG ba loai drop -- slop, timeout, queue -- vi ba nguyen
// nhan nay can ba cach sua khac han nhau:
// slop -> lech dong ho giua hai nguon, hoac max_slop_sec qua chat
// timeout -> mot nguon cham hon du kien hoac da chet
// queue -> consumer khong theo kip producer
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <tuple>
#include <utility>
#include <vector>
#include "vslam/stats.h"
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
template <typename... Ts>
class ApproxTimeSync {
public:
static constexpr size_t kN = sizeof...(Ts);
using Tuple = std::tuple<std::shared_ptr<const Ts>...>;
using Callback = std::function<void(UnixTime pivot_stamp, const Tuple&)>;
struct Options {
size_t queue_size = 30; // khop sync_queue_size=30 hien tai
double max_slop_sec = 0.05; // ~1.5 khung camera o 30 Hz
double wait_timeout_sec = 0.20; // het han cho input tuy chon
size_t pivot_index = 0; // stream cham nhat lam moc (scan)
std::array<bool, kN> required{}; // scan+odom = true; depth+infra = false
};
ApproxTimeSync(Options opt, Callback cb)
: opt_(std::move(opt)), cb_(std::move(cb)) {
if (opt_.queue_size == 0) opt_.queue_size = 1;
if (opt_.pivot_index >= kN) opt_.pivot_index = 0;
}
// Them ban tin vao stream thu I.
template <size_t I>
void Add(UnixTime stamp,
std::shared_ptr<const std::tuple_element_t<I, std::tuple<Ts...>>> msg) {
static_assert(I < kN, "chi so stream vuot so stream");
std::vector<std::pair<UnixTime, Tuple>> emit;
{
std::lock_guard<std::mutex> lk(mu_);
auto& q = queues_[I];
if (!q.empty() && stamp < q.back().stamp) {
// Stamp lui: ban ghi bi xao tron hoac hai nguon ghi cung stream.
stats_.dropped_queue++;
return;
}
q.push_back(Slot{stamp, std::static_pointer_cast<const void>(std::move(msg))});
while (q.size() > opt_.queue_size) {
q.pop_front();
if (I == opt_.pivot_index) stats_.dropped_queue++;
}
CollectLocked(kTimeZero, false, &emit);
}
Fire(emit);
}
// Lai nhanh wait_timeout. Goi tu vong lap cua luong so huu sync.
void Tick(UnixTime now) {
std::vector<std::pair<UnixTime, Tuple>> emit;
{
std::lock_guard<std::mutex> lk(mu_);
CollectLocked(now, true, &emit);
}
Fire(emit);
}
SyncStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
void Reset() {
std::lock_guard<std::mutex> lk(mu_);
for (auto& q : queues_) q.clear();
stats_ = SyncStats{};
}
private:
struct Slot {
UnixTime stamp;
std::shared_ptr<const void> msg;
};
// Goi khi da giu mu_. Khong goi callback o day -- chi gom vao `emit`.
void CollectLocked(UnixTime now, bool allow_timeout,
std::vector<std::pair<UnixTime, Tuple>>* emit) {
auto& pivot_q = queues_[opt_.pivot_index];
while (!pivot_q.empty()) {
const UnixTime pivot = pivot_q.front().stamp;
std::array<size_t, kN> pick{};
std::array<bool, kN> have{};
bool all_required = true;
bool all_settled = true;
double worst_slop = 0.0;
for (size_t s = 0; s < kN; ++s) {
if (s == opt_.pivot_index) {
pick[s] = 0;
have[s] = true;
continue;
}
const auto& q = queues_[s];
if (q.empty()) {
all_settled = false;
if (opt_.required[s]) all_required = false;
continue;
}
size_t best = 0;
double best_d = std::abs(SecondsBetween(q[0].stamp, pivot));
for (size_t i = 1; i < q.size(); ++i) {
const double d = std::abs(SecondsBetween(q[i].stamp, pivot));
if (d < best_d) { best_d = d; best = i; }
}
if (best_d <= opt_.max_slop_sec) {
pick[s] = best;
have[s] = true;
worst_slop = std::max(worst_slop, best_d);
} else {
if (opt_.required[s]) all_required = false;
// Ban tin moi nhat cua stream nay DA VUOT pivot: khong the khop hon
// duoc nua, nen stream coi nhu da chot (du la chot rong).
if (q.back().stamp <= pivot) all_settled = false;
}
}
const bool timed_out =
allow_timeout && !now.isZero() &&
SecondsBetween(now, pivot) > opt_.wait_timeout_sec;
if (!all_required) {
if (!timed_out) break; // con co the cho them
// Het gio ma van thieu stream bat buoc -> bo pivot nay.
stats_.dropped_timeout++;
pivot_q.pop_front();
continue;
}
if (!all_settled && !timed_out) break; // cho stream tuy chon
Tuple t;
FillTuple(t, pick, have, std::index_sequence_for<Ts...>{});
emit->emplace_back(pivot, std::move(t));
stats_.matched++;
stats_.last_slop_sec = worst_slop;
if (timed_out && !all_settled) stats_.dropped_timeout++;
// Bo moi ban tin da dung va moi ban tin cu hon no.
for (size_t s = 0; s < kN; ++s) {
if (s == opt_.pivot_index || !have[s]) continue;
auto& q = queues_[s];
q.erase(q.begin(), q.begin() + static_cast<long>(pick[s]) + 1);
}
pivot_q.pop_front();
}
}
template <size_t... Is>
void FillTuple(Tuple& t, const std::array<size_t, kN>& pick,
const std::array<bool, kN>& have, std::index_sequence<Is...>) {
(void)std::initializer_list<int>{
(std::get<Is>(t) =
have[Is] ? std::static_pointer_cast<
const std::tuple_element_t<Is, std::tuple<Ts...>>>(
queues_[Is][pick[Is]].msg)
: nullptr,
0)...};
}
// Goi callback NGOAI khoa. Callback cua SLAM chan 100-600 ms; giu khoa
// trong do se chan luong lidar_rx.
void Fire(const std::vector<std::pair<UnixTime, Tuple>>& emit) {
for (const auto& e : emit) cb_(e.first, e.second);
}
Options opt_;
Callback cb_;
mutable std::mutex mu_;
std::array<std::deque<Slot>, kN> queues_;
SyncStats stats_;
};
// --- Bien the hai luong ----------------------------------------------------
// Truong hop hai nguon pho bien den muc dang co ban rieng: de doc hon, compile
// nhanh hon, va khong phai dien std::array<bool,2> cho moi lan dung.
// Dung boi cliff_detect (depth + camera_info).
//
// HEADER-ONLY, khong pimpl. Ban dau viet pimpl + khoi tao tuong minh cho
// PairSync<Image, CameraInfo>, nhung nhu the thi khong ai dung duoc no voi
// kieu khac -- ke ca unit test voi struct gia. Voi mot lop nho nhu nay thi
// cai gia cua pimpl (mot ban khoi tao tuong minh cho moi cap kieu) lon hon
// cai loi.
template <typename A, typename B>
class PairSync {
public:
using Callback = std::function<void(UnixTime, std::shared_ptr<const A>,
std::shared_ptr<const B>)>;
PairSync(size_t queue_size, double max_slop_sec, Callback cb)
: queue_size_(queue_size == 0 ? 1 : queue_size),
max_slop_sec_(max_slop_sec),
cb_(std::move(cb)) {}
void AddFirst(UnixTime stamp, std::shared_ptr<const A> msg) {
std::vector<Emit> emit;
{
std::lock_guard<std::mutex> lk(mu_);
qa_.push_back(SlotA{stamp, std::move(msg)});
TrimLocked();
MatchLocked(&emit);
}
Fire(emit);
}
void AddSecond(UnixTime stamp, std::shared_ptr<const B> msg) {
std::vector<Emit> emit;
{
std::lock_guard<std::mutex> lk(mu_);
qb_.push_back(SlotB{stamp, std::move(msg)});
TrimLocked();
MatchLocked(&emit);
}
Fire(emit);
}
SyncStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
void Reset() {
std::lock_guard<std::mutex> lk(mu_);
qa_.clear();
qb_.clear();
stats_ = SyncStats{};
}
private:
struct SlotA { UnixTime stamp; std::shared_ptr<const A> msg; };
struct SlotB { UnixTime stamp; std::shared_ptr<const B> msg; };
struct Emit {
UnixTime stamp;
std::shared_ptr<const A> a;
std::shared_ptr<const B> b;
};
// Goi khi da giu mu_. Chi gom vao `emit`, khong goi callback o day.
void MatchLocked(std::vector<Emit>* emit) {
while (!qa_.empty() && !qb_.empty()) {
const SlotA& a = qa_.front();
size_t best = 0;
double best_d = std::abs(SecondsBetween(qb_[0].stamp, a.stamp));
for (size_t i = 1; i < qb_.size(); ++i) {
const double d = std::abs(SecondsBetween(qb_[i].stamp, a.stamp));
if (d < best_d) { best_d = d; best = i; }
}
if (best_d <= max_slop_sec_) {
emit->push_back(Emit{a.stamp, a.msg, qb_[best].msg});
stats_.matched++;
stats_.last_slop_sec = best_d;
// Bo moi phan tu b cu hon phan tu vua khop: chung khong con co hoi
// khop voi bat ky a nao ve sau (a chi tien len).
qb_.erase(qb_.begin(), qb_.begin() + static_cast<long>(best) + 1);
qa_.pop_front();
continue;
}
// Chua khop duoc. Neu a da cu hon MOI phan tu b thi no khong bao gio
// khop nua -> bo. Nguoc lai thi cho them b.
if (a.stamp < qb_.back().stamp) {
stats_.dropped_slop++;
qa_.pop_front();
continue;
}
break;
}
}
void TrimLocked() {
while (qa_.size() > queue_size_) { qa_.pop_front(); stats_.dropped_queue++; }
while (qb_.size() > queue_size_) { qb_.pop_front(); stats_.dropped_queue++; }
}
// Goi callback NGOAI khoa. Callback cua cliff_detect lam viec nang
// (ray-cast toan anh depth); giu khoa trong do se chan luong camera.
void Fire(const std::vector<Emit>& emit) {
for (const auto& e : emit) cb_(e.stamp, e.a, e.b);
}
size_t queue_size_;
double max_slop_sec_;
Callback cb_;
mutable std::mutex mu_;
std::deque<SlotA> qa_;
std::deque<SlotB> qb_;
SyncStats stats_;
};
} // namespace vslam
#endif // VSLAM_APPROX_SYNC_H

View File

@@ -0,0 +1,92 @@
#ifndef VSLAM_BUFFER_POOL_H
#define VSLAM_BUFFER_POOL_H
// Pool tai su dung buffer, de chuoi perception khong cap phat gi o trang thai
// on dinh.
//
// Chuoi hien tai moi khung sinh: cloud_raw (320x240 = 76800 diem) ->
// cloud_filtered -> cloud_aligned. Neu moi buoc malloc mot vector moi thi o
// 10 Hz la ~9 MB/s di qua allocator, va tren Jetson dieu do the hien thanh
// jitter chu khong phai thong luong.
//
// Cach dung: hai buffer luan phien, 0 malloc o trang thai on dinh.
// Acquire() tra shared_ptr co deleter tu tra ve pool. Neu pool da bi huy
// truoc object thi deleter xoa that -- an toan khi tat may.
//
// allocated() ra /api/status: con so nay khong duoc tang sau khi he chay on
// dinh. Tang nghia la co cho giu shared_ptr lau hon can (ro ri thuc su, hoac
// mot Channel capacity qua lon).
#include <atomic>
#include <cstddef>
#include <memory>
#include <mutex>
#include <vector>
namespace vslam {
template <typename T>
class BufferPool : public std::enable_shared_from_this<BufferPool<T>> {
public:
// max_idle: giu toi da bao nhieu buffer roi. Vuot qua thi tra buffer se xoa
// that thay vi giu -- tranh pool phinh vinh vien sau mot dot tai cao.
static std::shared_ptr<BufferPool<T>> Create(size_t max_idle = 4) {
return std::shared_ptr<BufferPool<T>>(new BufferPool<T>(max_idle));
}
std::shared_ptr<T> Acquire() {
std::unique_ptr<T> obj;
{
std::lock_guard<std::mutex> lk(mu_);
if (!idle_.empty()) {
obj = std::move(idle_.back());
idle_.pop_back();
}
}
if (!obj) {
obj = std::make_unique<T>();
allocated_.fetch_add(1, std::memory_order_relaxed);
}
// weak_ptr: neu pool chet truoc object thi deleter xoa that.
std::weak_ptr<BufferPool<T>> weak = this->shared_from_this();
T* raw = obj.release();
return std::shared_ptr<T>(raw, [weak](T* p) {
if (auto pool = weak.lock()) {
pool->Release(std::unique_ptr<T>(p));
} else {
delete p;
}
});
}
size_t idle() const {
std::lock_guard<std::mutex> lk(mu_);
return idle_.size();
}
size_t allocated() const { return allocated_.load(std::memory_order_relaxed); }
void Clear() {
std::lock_guard<std::mutex> lk(mu_);
idle_.clear();
}
private:
explicit BufferPool(size_t max_idle) : max_idle_(max_idle) {}
void Release(std::unique_ptr<T> obj) {
std::lock_guard<std::mutex> lk(mu_);
if (idle_.size() >= max_idle_) return; // xoa that
idle_.push_back(std::move(obj));
}
const size_t max_idle_;
mutable std::mutex mu_;
std::vector<std::unique_ptr<T>> idle_;
std::atomic<size_t> allocated_{0};
};
} // namespace vslam
#endif // VSLAM_BUFFER_POOL_H

View File

@@ -0,0 +1,247 @@
#ifndef VSLAM_CHANNEL_H
#define VSLAM_CHANNEL_H
// Thay pub/sub cua ROS.
//
// QUY TAC RANH GIOI -- doc truoc khi dung:
//
// Channel<T> CHI dung khi du lieu di QUA BIEN LUONG.
// Trong cung mot luong: goi ham truc tiep.
//
// Day la cach giu nguyen loi the "3 nodelet chung 1 manager" cua ban ROS.
// Chuoi depth_to_cloud -> depth_filter -> gravity_align -> cliff_detect chay
// inline tren chinh luong camera trong mot loi goi PerceptionPipeline::Process().
// Tot hon nodelet manager: khong intrusive_ptr, khong dispatch theo topic,
// khong nodelet loader.
//
// Don vi du lieu duy nhat la std::shared_ptr<const T>. Publish() copy mot
// con tro (mot atomic increment), khong bao gio copy cloud/anh/scan.
//
// KHAC BIET QUAN TRONG SO VOI QUEUE CUA ROS: so ban tin bi bo duoc DEM va bao
// cao ra /api/status. Queue cua ROS drop im lang, va do la ly do repo cu phai
// doan mo ve viec costmap co nhan du cloud hay khong.
//
// AN TOAN LUONG:
// * Publish() khong bao gio chan. Day la bat buoc: luong lidar_rx hay
// camera_rx khong duoc phep dung cho luong slam (Rtabmap::process() chan
// 100-600 ms).
// * Latest() la duong doc cua luong safety: mot lan copy shared_ptr duoi
// khoa, khong bao gio giu khoa khi goi code nguoi dung.
// * Tap Reader co dinh truoc khi chay. MakeReader() phai goi xong trong
// giai doan wiring, khong duoc goi khi he dang chay.
#include <atomic>
#include <cassert>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "vslam/stats.h"
#include "vslam/unix_time.h"
namespace vslam {
template <typename T>
class Channel {
public:
using Ptr = std::shared_ptr<const T>;
struct Item {
Ptr msg;
UnixTime stamp;
uint64_t seq = 0;
};
Channel(size_t capacity, std::string name)
: capacity_(capacity), name_(std::move(name)), ring_(capacity) {
assert(capacity > 0 && "Channel capacity phai > 0");
}
Channel(const Channel&) = delete;
Channel& operator=(const Channel&) = delete;
// Khong bao gio chan. Tra ve false neu phai ghi de mot phan tu ma con reader
// chua doc toi -- goi co the dung gia tri nay de dem hoac de canh bao.
bool Publish(Ptr msg, UnixTime stamp) {
bool overwrote = false;
{
std::lock_guard<std::mutex> lk(mu_);
const uint64_t seq = head_++;
// Ghi de o cu nhat neu vong da day.
if (seq >= capacity_) {
const uint64_t evicted = seq - capacity_;
for (const auto& r : readers_) {
if (r->cursor.load(std::memory_order_relaxed) <= evicted) {
overwrote = true;
break;
}
}
}
Item& slot = ring_[seq % capacity_];
slot.msg = std::move(msg);
slot.stamp = stamp;
slot.seq = seq;
latest_ = slot;
published_++;
if (overwrote) overwritten_++;
}
rate_.Tick();
cv_.notify_all();
return !overwrote;
}
// Con tro doc rieng cua tung consumer. Khong sao chep duoc -- moi consumer
// giu mot Reader va chi minh no dung.
class Reader {
public:
// Chan toi khi co ban tin moi hoac het `timeout`. Tra false neu het gio
// hoac channel da dong.
bool Read(Ptr* out, UnixTime* stamp, std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lk(ch_->mu_);
const bool got = ch_->cv_.wait_for(lk, timeout, [this] {
return ch_->closed_ || state_->cursor.load(std::memory_order_relaxed) < ch_->head_;
});
if (!got || ch_->closed_) return false;
return PopLocked(out, stamp);
}
// Khong chan.
bool TryRead(Ptr* out, UnixTime* stamp) {
std::lock_guard<std::mutex> lk(ch_->mu_);
if (state_->cursor.load(std::memory_order_relaxed) >= ch_->head_) return false;
return PopLocked(out, stamp);
}
// So ban tin reader nay KHONG BAO GIO nhin thay vi bi ghi de.
uint64_t dropped() const { return state_->dropped.load(std::memory_order_relaxed); }
// So ban tin dang cho doc.
uint64_t lag() const {
std::lock_guard<std::mutex> lk(ch_->mu_);
const uint64_t c = state_->cursor.load(std::memory_order_relaxed);
return ch_->head_ > c ? ch_->head_ - c : 0;
}
const std::string& name() const { return state_->name; }
private:
friend class Channel<T>;
struct State {
std::atomic<uint64_t> cursor{0};
std::atomic<uint64_t> dropped{0};
std::string name;
};
Reader(Channel<T>* ch, State* st) : ch_(ch), state_(st) {}
// Goi khi da giu mu_.
bool PopLocked(Ptr* out, UnixTime* stamp) {
uint64_t c = state_->cursor.load(std::memory_order_relaxed);
const uint64_t oldest = ch_->head_ > ch_->capacity_ ? ch_->head_ - ch_->capacity_ : 0;
if (c < oldest) {
// Reader da bi nhay qua. Dem phan mat roi tua toi o cu nhat con song.
state_->dropped.fetch_add(oldest - c, std::memory_order_relaxed);
c = oldest;
}
const Item& slot = ch_->ring_[c % ch_->capacity_];
*out = slot.msg;
if (stamp) *stamp = slot.stamp;
state_->cursor.store(c + 1, std::memory_order_relaxed);
return true;
}
Channel<T>* ch_ = nullptr;
State* state_ = nullptr;
};
// Phai goi xong trong giai doan wiring, truoc khi bat ky luong nao chay.
// `name` chi de bao cao so lieu.
Reader MakeReader(std::string name) {
std::lock_guard<std::mutex> lk(mu_);
assert(!started_ && "MakeReader() sau khi he da chay");
auto st = std::make_unique<typename Reader::State>();
st->name = std::move(name);
st->cursor.store(head_, std::memory_order_relaxed); // bat dau tu hien tai
auto* raw = st.get();
readers_.push_back(std::move(st));
return Reader(this, raw);
}
// Danh dau ket thuc wiring. Sau loi goi nay MakeReader() se assert.
void Freeze() {
std::lock_guard<std::mutex> lk(mu_);
started_ = true;
}
// O(1), khong dung cursor. Day la duong doc cua luong safety va web_tx:
// chung khong quan tam lich su, chi can ban moi nhat.
bool Latest(Ptr* out, UnixTime* stamp = nullptr) const {
std::lock_guard<std::mutex> lk(mu_);
if (!latest_.msg) return false;
*out = latest_.msg;
if (stamp) *stamp = latest_.stamp;
return true;
}
// Danh thuc moi reader dang cho.
void Close() {
{
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
}
cv_.notify_all();
}
bool closed() const {
std::lock_guard<std::mutex> lk(mu_);
return closed_;
}
ChannelStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
ChannelStats s;
s.name = name_;
s.capacity = capacity_;
s.published = published_;
s.overwritten = overwritten_;
s.readers = readers_.size();
s.hz = rate_.hz();
for (const auto& r : readers_) {
const uint64_t c = r->cursor.load(std::memory_order_relaxed);
const uint64_t lag = head_ > c ? head_ - c : 0;
if (lag > s.max_reader_lag) s.max_reader_lag = lag;
s.total_reader_drops += r->dropped.load(std::memory_order_relaxed);
}
return s;
}
const std::string& name() const { return name_; }
size_t capacity() const { return capacity_; }
private:
mutable std::mutex mu_;
std::condition_variable cv_;
const size_t capacity_;
const std::string name_;
std::vector<Item> ring_;
uint64_t head_ = 0; // seq se cap cho lan Publish ke tiep
Item latest_;
bool closed_ = false;
bool started_ = false;
uint64_t published_ = 0;
uint64_t overwritten_ = 0;
mutable RateMonitor rate_{2.0};
std::vector<std::unique_ptr<typename Reader::State>> readers_;
};
} // namespace vslam
#endif // VSLAM_CHANNEL_H

View File

@@ -0,0 +1,92 @@
#ifndef VSLAM_CLOCK_H
#define VSLAM_CLOCK_H
// QUY TAC TU NGAY DAU, KHONG RETROFIT DUOC SAU:
//
// Khong stage nao duoc goi UnixTime::now() hay steady_clock::now() truc tiep.
// Moi stage nhan mot `std::shared_ptr<Clock>` qua constructor.
//
// Ly do: replay tat dinh. Neu mot stage doc dong ho that thi chay lai cung mot
// file .vsr se cho ket qua khac, va toan bo tang 2 cua chien luoc kiem chung
// (regress.sh so JSON voi expected/) sup do. Bo qua quy tac nay bay gio nghia
// la khong bao gio lam duoc replay tat dinh sau.
//
// Clock tach LAM HAI ham khong phai ngau nhien -- day la quy tac hai dong ho
// noi o unix_time.h:
//
// Now() -> UnixTime, tu system_clock. Dung DONG DAU du lieu. Co the nhay
// khi NTP dieu chinh.
// Steady() -> steady_clock. Dung do THOI LUONG va tinh TIMEOUT. Khong bao gio
// nhay, khong bao gio lui.
//
// safety_monitor_node.cpp hien dung ros::Time::now() cho ca hai. 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. Day la bug that
// dang nam trong repo, va viec tach hai ham o day la cach sua no.
#include <chrono>
#include <memory>
#include "vslam/unix_time.h"
namespace vslam {
class Clock {
public:
using SteadyPoint = std::chrono::steady_clock::time_point;
virtual ~Clock() = default;
// Dong dau du lieu.
virtual UnixTime Now() const = 0;
// Do thoi luong va tinh timeout.
virtual SteadyPoint Steady() const = 0;
// Ngu toi mot moc steady. Ban replay khong ngu that.
virtual void SleepUntil(SteadyPoint tp) = 0;
// true neu day la dong ho ao (replay). Chi dung de log, khong duoc dung de
// re nhanh logic -- neu can re nhanh thi thiet ke da sai.
virtual bool is_virtual() const = 0;
void SleepFor(std::chrono::nanoseconds d) { SleepUntil(Steady() + d); }
};
using ClockPtr = std::shared_ptr<Clock>;
// Dong ho that: system_clock cho Now(), steady_clock cho Steady().
ClockPtr MakeSystemClock();
// Dong ho ao cho replay. Thoi gian chi tien khi co nguoi goi Advance() hoac
// SleepUntil(). Trong che do --deterministic thi replay source lai no theo
// dung thu tu stamp cua ban ghi.
class ReplayClock : public Clock {
public:
explicit ReplayClock(UnixTime start);
~ReplayClock() override;
UnixTime Now() const override;
SteadyPoint Steady() const override;
void SleepUntil(SteadyPoint tp) override;
bool is_virtual() const override { return true; }
// Dat thoi gian ao. Chi lui neu `allow_backward` -- lui thoi gian la dau
// hieu ban ghi bi xao tron thu tu, mac dinh phai bao loi.
void SetNow(UnixTime t, bool allow_backward = false);
void Advance(Duration d);
// He so toc do doi voi thoi gian tuong that khi SleepUntil() thuc su ngu.
// 0 = chay nhanh nhat co the (khong ngu). 1 = thoi gian that.
void SetSpeed(double speed);
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
std::shared_ptr<ReplayClock> MakeReplayClock(UnixTime start);
} // namespace vslam
#endif // VSLAM_CLOCK_H

View File

@@ -0,0 +1,134 @@
#ifndef VSLAM_CONFIG_H
#define VSLAM_CONFIG_H
// Doc cau hinh YAML. Bao yaml-cpp de khong ro kieu cua no ra API cong khai.
//
// HAI THU MA BAN ROS THIEU, va ca hai deu da gay ton that that:
//
// 1. require<T>() -- nem loi kem TEN KEY DAY DU khi thieu.
// Hien tai pnh_.param("stop_distance", stop_distance_, 0.35) khien mot key
// go sai AM THAM roi ve default C++ va khong ai biet. Voi tham so an toan
// (stop_distance, min_front_rays) hay hinh hoc (wheel_separation) thi day
// la kieu loi im lang nguy hiem nhat: he van chay, chi la chay sai.
//
// 2. UnknownKeys() -- liet ke key CO trong file nhung KHONG co trong danh
// sach biet truoc. Bat duoc "stop_distence". Kiem o startup, log ERROR.
//
// Quy tac: dung require() cho moi thu lien quan an toan, hinh hoc, va duong
// dan. Dung get(key, fallback) chi cho tuy chon thuc su co default hop ly.
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
namespace vslam {
class ConfigError : public std::runtime_error {
public:
explicit ConfigError(const std::string& msg) : std::runtime_error(msg) {}
};
class ConfigNode {
public:
ConfigNode();
ConfigNode(const ConfigNode&);
ConfigNode(ConfigNode&&) noexcept;
ConfigNode& operator=(const ConfigNode&);
ConfigNode& operator=(ConfigNode&&) noexcept;
~ConfigNode();
// Nem ConfigError neu file khong doc duoc hoac YAML sai cu phap.
static ConfigNode LoadFile(const std::string& path);
static ConfigNode LoadString(const std::string& yaml, std::string origin = "<string>");
// Key thieu tra ve node Null thay vi nem -- de chuoi a["b"]["c"] khong no
// giua chung. Cho phep kiem IsNull() o cuoi.
ConfigNode operator[](const std::string& key) const;
ConfigNode at(size_t index) const; // cho chuoi (sequence)
bool IsNull() const;
bool IsMap() const;
bool IsSequence() const;
bool IsScalar() const;
size_t size() const;
// Duong dan day du toi node nay, vd "safety.scan.stop_distance".
// Dung trong moi thong bao loi.
const std::string& path() const;
// Ten file goc, de thong bao loi noi ro key nam o dau.
const std::string& origin() const;
// --- Doc gia tri --------------------------------------------------------
// Thieu key -> tra `fallback`. Sai kieu -> nem ConfigError (khac han voi
// thieu key: sai kieu luon la loi cua nguoi viet config).
template <typename T>
T get(const std::string& key, const T& fallback) const;
// Thieu key hoac sai kieu -> nem ConfigError kem duong dan day du.
template <typename T>
T require(const std::string& key) const;
// Doc chinh node nay (khi da di toi la).
template <typename T>
T as() const;
template <typename T>
T as(const T& fallback) const;
// --- Kiem key la ---------------------------------------------------------
// Tra ve cac key CO trong node nay nhung KHONG nam trong `known`.
// Rong nghia la khong co typo.
std::vector<std::string> UnknownKeys(const std::vector<std::string>& known) const;
// Tien loi: goi UnknownKeys() roi log ERROR cho tung key la.
// Tra ve false neu co key la.
bool WarnUnknownKeys(const std::vector<std::string>& known) const;
// Danh sach moi key cua node map nay.
std::vector<std::string> Keys() const;
// Cac cap key/value dang chuoi, giu nguyen van. Dung cho khoi `rtabmap:`
// trong slam.yaml -- 26 key cua RTAB-Map di thang vao ParametersMap ma
// khong qua kiem kieu nao o day.
std::vector<std::pair<std::string, std::string>> AsStringMap() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
explicit ConfigNode(std::unique_ptr<Impl> impl);
};
// Khai bao tuong minh cac kieu duoc ho tro. Dinh nghia o config.cc.
// Them kieu moi thi phai them ca o day va o .cc -- co y, de khong ai vo tinh
// doc mot kieu ma yaml-cpp chuyen doi theo cach bat ngo.
#define VSLAM_CONFIG_DECLARE(T) \
extern template T ConfigNode::get<T>(const std::string&, const T&) const; \
extern template T ConfigNode::require<T>(const std::string&) const; \
extern template T ConfigNode::as<T>() const; \
extern template T ConfigNode::as<T>(const T&) const;
VSLAM_CONFIG_DECLARE(bool)
VSLAM_CONFIG_DECLARE(int)
VSLAM_CONFIG_DECLARE(unsigned int)
VSLAM_CONFIG_DECLARE(float)
VSLAM_CONFIG_DECLARE(double)
VSLAM_CONFIG_DECLARE(std::string)
#undef VSLAM_CONFIG_DECLARE
// Chuoi thi khai bao rieng vi khong dung duoc trong macro (co dau phay).
extern template std::vector<double> ConfigNode::get<std::vector<double>>(
const std::string&, const std::vector<double>&) const;
extern template std::vector<double> ConfigNode::require<std::vector<double>>(
const std::string&) const;
extern template std::vector<std::string> ConfigNode::get<std::vector<std::string>>(
const std::string&, const std::vector<std::string>&) const;
extern template std::vector<std::string> ConfigNode::require<std::vector<std::string>>(
const std::string&) const;
} // namespace vslam
#endif // VSLAM_CONFIG_H

View File

@@ -0,0 +1,108 @@
#ifndef VSLAM_GEOMETRY_H
#define VSLAM_GEOMETRY_H
// Phep bien doi hinh hoc tren cac kieu POD cua vslam_common.h.
//
// Eigen chi xuat hien trong PHAN CAI DAT (.cc), khong o chu ky ham. Ly do o
// vslam_common.h: kieu Eigen fixed-size di qua bien .so la nguon loi alignment
// tren arm64. Ai can Eigen thi tu chuyen o phia minh bang ToEigen()/FromEigen()
// khai bao trong geometry_eigen.h (header noi bo, khong phat hanh).
#include <cmath>
#include "vslam/vslam_common.h"
namespace vslam {
// --- Goc -------------------------------------------------------------------
// Dua goc ve [-pi, pi). Port tu wheel_odom_node.cpp:45-50 va
// slam_core_node.cpp:39-44 (hai ban giong het nhau trong repo cu).
double NormalizeAngle(double a);
// Hieu hai goc, da chuan hoa.
inline double AngleDiff(double a, double b) { return NormalizeAngle(a - b); }
// --- Quaternion <-> Euler --------------------------------------------------
Quaternion QuaternionFromYaw(double yaw);
Quaternion QuaternionFromRPY(double roll, double pitch, double yaw);
double YawFromQuaternion(const Quaternion& q);
void RPYFromQuaternion(const Quaternion& q, double* roll, double* pitch, double* yaw);
Quaternion QuaternionNormalized(const Quaternion& q);
Quaternion QuaternionInverse(const Quaternion& q);
Quaternion QuaternionMultiply(const Quaternion& a, const Quaternion& b);
// Noi suy cau. t kep ve [0,1]. Tu dong lat dau de di duong ngan.
Quaternion QuaternionSlerp(const Quaternion& a, const Quaternion& b, double t);
// --- Vector ----------------------------------------------------------------
inline Vector3 operator+(const Vector3& a, const Vector3& b) {
return Vector3{a.x + b.x, a.y + b.y, a.z + b.z};
}
inline Vector3 operator-(const Vector3& a, const Vector3& b) {
return Vector3{a.x - b.x, a.y - b.y, a.z - b.z};
}
inline Vector3 operator*(const Vector3& v, double s) {
return Vector3{v.x * s, v.y * s, v.z * s};
}
inline double Norm(const Vector3& v) {
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
inline Vector3 Lerp(const Vector3& a, const Vector3& b, double t) {
return Vector3{a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t};
}
// Xoay vector bang quaternion.
Vector3 RotateVector(const Quaternion& q, const Vector3& v);
// --- Transform -------------------------------------------------------------
Transform TransformIdentity();
// Ghep: ket qua bien doi tu frame cua `b` sang frame cua `a`.
// Tuong duong phep nhan ma tran a * b.
Transform TransformCompose(const Transform& a, const Transform& b);
Transform TransformInverse(const Transform& t);
// Ap bien doi len mot diem.
Point TransformPoint(const Transform& t, const Point& p);
Vector3 TransformVector(const Transform& t, const Vector3& v);
// Noi suy giua hai transform: LERP tinh tien + SLERP quay.
// Day la phep TransformTree dung khi lookup o mot stamp nam giua hai mau.
Transform TransformInterpolate(const Transform& a, const Transform& b, double t);
// --- SE(2) -----------------------------------------------------------------
// Pose cua he nay la SE(2): x, y, yaw. Roll/pitch duoc DO tu IMU chu khong
// bao gio uoc luong, va z gia dinh bang 0. Xem docs/ARCHITECTURE.md cua repo cu.
Pose2D Pose2DFromPose(const Pose& p);
Pose PoseFromPose2D(const Pose2D& p, double z = 0.0);
Pose2D Pose2DCompose(const Pose2D& a, const Pose2D& b);
Pose2D Pose2DInverse(const Pose2D& p);
// b trong he toa do cua a: a^-1 * b. Dung khi tinh delta giua hai keyframe.
Pose2D Pose2DBetween(const Pose2D& a, const Pose2D& b);
Transform TransformFromPose2D(const Pose2D& p, double z = 0.0);
Pose2D Pose2DFromTransform(const Transform& t);
inline double Distance2D(const Pose2D& a, const Pose2D& b) {
const double dx = a.x - b.x, dy = a.y - b.y;
return std::sqrt(dx * dx + dy * dy);
}
// --- Chuyen doi tien loi --------------------------------------------------
Transform TransformFromPose(const Pose& p);
Pose PoseFromTransform(const Transform& t);
} // namespace vslam
#endif // VSLAM_GEOMETRY_H

View File

@@ -0,0 +1,40 @@
#ifndef VSLAM_JSON_PARSE_H
#define VSLAM_JSON_PARSE_H
// Trich truong tu body JSON cua POST /api/*.
//
// PHAT HANH co y: ai viet mot WebServer::CommandHandler deu PHAI dung chinh
// cac ham nay de doc body. Neu handler doc body theo mot cach khac voi lop
// xac thuc thi khoang cach giua hai cach doc la mot lo hong -- da tung nhu
// vay o ban dau, khi handler tim chuoi "true" con lop xac thuc goi
// JsonGetBool, va mot body hong lam hai ben hieu nguoc nhau.
//
// CO Y KHONG phai mot parser JSON day du. Body ma server nhan chi co dang
// {"on":true} hoac {"x":1.0,"y":2.0,"yaw":0.5} -- vai truong phang, khong
// long nhau, khong mang.
//
// Viet mot parser day du o day nghia la them mot be mat tan cong tren mot
// endpoint khong xac thuc. Ham trich truong theo ten thi khong co trang thai
// de pha hong.
#include <string>
// Nam o vslam_common chu khong o vslam_web: lop XAC THUC cua web va cac
// handler PHAI dung CHUNG mot ham parse (khoang cach giua hai cach doc cung
// mot body tung la lo hong fail-open cho e-stop), va `tools/vslam_replay`
// cung can doc lai JSON ky vong ma khong duoc phep keo theo Boost.
namespace vslam {
// Tim "key": <so> va tra ve gia tri. false neu khong thay hoac khong parse duoc.
bool JsonGetNumber(const std::string& body, const std::string& key, double* out);
// Tim "key": true|false.
bool JsonGetBool(const std::string& body, const std::string& key, bool* out);
// Tim "key": "<chuoi>". Xu ly escape \" va \\.
bool JsonGetString(const std::string& body, const std::string& key, std::string* out);
} // namespace vslam
#endif // VSLAM_JSON_PARSE_H

View File

@@ -0,0 +1,98 @@
#ifndef VSLAM_LOG_H
#define VSLAM_LOG_H
// Thay ROS_DEBUG / ROS_INFO / ROS_WARN / ROS_ERROR va cac bien the _THROTTLE.
//
// Yeu cau tu hien trang:
// * _THROTTLE la bat buoc, khong phai tien nghi. Nhieu cho trong repo hien
// tai log o tan so cam bien (200 Hz IMU, 30 Hz camera); khong bop lai thi
// journald tren Jetson day o va I/O tro thanh nut co chai that.
// * Throttle phai dung steady_clock, khong phai stamp du lieu. Neu dung
// stamp thi khi replay nhanh (speed=0) moi dong se bi bop nham.
// * Ghi log tuyet doi khong duoc chan vong an toan. Sink mac dinh ghi
// thang ra stderr co khoa; neu sau nay can sink ton kem (file, mang) thi
// phai la sink bat dong bo co hang doi va DROP chu khong block.
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <sstream>
#include <string>
namespace vslam {
enum class LogLevel : int { kDebug = 0, kInfo = 1, kWarn = 2, kError = 3, kOff = 4 };
const char* LogLevelName(LogLevel l);
bool ParseLogLevel(const std::string& s, LogLevel* out);
// Sink nhan dong da dinh dang san (khong co newline).
using LogSink = std::function<void(LogLevel, const char* file, int line,
const std::string& msg)>;
void SetLogLevel(LogLevel l);
LogLevel GetLogLevel();
void SetLogSink(LogSink sink);
// Bat/tat mau ANSI. Mac dinh: tu dong theo isatty(stderr).
void SetLogColor(bool on);
namespace detail {
void EmitLog(LogLevel level, const char* file, int line, const std::string& msg);
// Tra ve true neu da du `period_sec` ke tu lan cuoi cho diem goi nay.
// `state` la bien tinh rieng cua tung diem goi.
bool ThrottlePass(std::atomic<int64_t>* state, double period_sec);
} // namespace detail
#define VSLAM_LOG_AT(level, ...) \
do { \
if (static_cast<int>(level) >= static_cast<int>(::vslam::GetLogLevel())) { \
std::ostringstream _vslam_oss; \
_vslam_oss << __VA_ARGS__; \
::vslam::detail::EmitLog((level), __FILE__, __LINE__, _vslam_oss.str()); \
} \
} while (0)
#define VSLAM_DEBUG(...) VSLAM_LOG_AT(::vslam::LogLevel::kDebug, __VA_ARGS__)
#define VSLAM_INFO(...) VSLAM_LOG_AT(::vslam::LogLevel::kInfo, __VA_ARGS__)
#define VSLAM_WARN(...) VSLAM_LOG_AT(::vslam::LogLevel::kWarn, __VA_ARGS__)
#define VSLAM_ERROR(...) VSLAM_LOG_AT(::vslam::LogLevel::kError, __VA_ARGS__)
// Bien the throttle. `period` tinh bang giay, theo steady_clock.
#define VSLAM_LOG_THROTTLE_AT(level, period, ...) \
do { \
static std::atomic<int64_t> _vslam_throttle_state{0}; \
if (::vslam::detail::ThrottlePass(&_vslam_throttle_state, (period))) { \
VSLAM_LOG_AT(level, __VA_ARGS__); \
} \
} while (0)
#define VSLAM_DEBUG_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kDebug, period, __VA_ARGS__)
#define VSLAM_INFO_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kInfo, period, __VA_ARGS__)
#define VSLAM_WARN_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kWarn, period, __VA_ARGS__)
#define VSLAM_ERROR_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kError, period, __VA_ARGS__)
// Chi log mot lan duy nhat cho diem goi nay.
#define VSLAM_LOG_ONCE_AT(level, ...) \
do { \
static std::atomic<bool> _vslam_once{false}; \
bool _vslam_expected = false; \
if (_vslam_once.compare_exchange_strong(_vslam_expected, true)) { \
VSLAM_LOG_AT(level, __VA_ARGS__); \
} \
} while (0)
#define VSLAM_INFO_ONCE(...) VSLAM_LOG_ONCE_AT(::vslam::LogLevel::kInfo, __VA_ARGS__)
#define VSLAM_WARN_ONCE(...) VSLAM_LOG_ONCE_AT(::vslam::LogLevel::kWarn, __VA_ARGS__)
} // namespace vslam
#endif // VSLAM_LOG_H

View File

@@ -0,0 +1,98 @@
#ifndef VSLAM_NODE_CONSTANTS_H
#define VSLAM_NODE_CONSTANTS_H
// Duong dan va hang so toan he, tap trung mot cho.
// Khuon mau: xloc_cpp/include/node_constants.h, voi mot sua loi quan trong.
//
// xloc_cpp/include/node_constants.h:30-31 hardcode
// kMapDirectory = "/home/robotics/.local/share/xloc/resources/maps/"
// kPoseDirectory = "/home/robotics/.local/share/xloc/resources/poses/"
// nen goi .deb cua no khong chay duoc tren may co username khac, va lech han
// voi dich install() o CMakeLists.txt:269-273 (/var/lib/xloc/resources).
//
// O day: mac dinh theo FHS, va co the ghi de bang bien moi truong -- can cho
// viec chay tu build tree khi phat trien va cho test chay song song.
#include <string>
namespace vslam {
// --- Duong dan mac dinh ----------------------------------------------------
constexpr char kConfigurationDirectory[] = "/etc/vslam/configuration_files";
constexpr char kResourceDirectory[] = "/var/lib/vslam/resources";
constexpr char kMapDirectory[] = "/var/lib/vslam/resources/maps";
constexpr char kRecordDirectory[] = "/var/lib/vslam/resources/records";
constexpr char kWebAssetDirectory[] = "/var/lib/vslam/www";
// --- Bien moi truong ghi de ------------------------------------------------
constexpr char kConfigDirEnv[] = "VSLAM_CONFIG_DIR";
constexpr char kResourceDirEnv[] = "VSLAM_RESOURCE_DIR";
constexpr char kCorpusDirEnv[] = "VSLAM_CORPUS_DIR"; // ../vSLAM_ws/maps khi test
// --- Ten file cau hinh -----------------------------------------------------
// Mot file cho mot lib, cong robot.yaml. 14 file YAML cua ban ROS gop lai
// thanh sau file nay.
constexpr char kRobotConfigFile[] = "robot.yaml";
constexpr char kSensorsConfigFile[] = "sensors.yaml";
constexpr char kPipelineConfigFile[] = "pipeline.yaml";
constexpr char kSlamConfigFile[] = "slam.yaml";
constexpr char kSafetyConfigFile[] = "safety.yaml";
constexpr char kSystemConfigFile[] = "system.yaml";
// --- Ten frame -------------------------------------------------------------
// Cay TF: map -> odom -> base_footprint -> base_link -> {laser, camera, imu}
// va camera_link -> camera_depth_optical_frame -> camera_infra1/2.
// Chi BA canh la dong (xem transform_tree.h); con lai tinh, nap tu robot.yaml.
constexpr char kMapFrame[] = "map";
constexpr char kOdomFrame[] = "odom";
constexpr char kBaseFootprintFrame[] = "base_footprint";
constexpr char kBaseLinkFrame[] = "base_link";
constexpr char kLaserFrame[] = "laser_link";
constexpr char kImuFrame[] = "imu_link";
constexpr char kCameraFrame[] = "camera_link";
constexpr char kCameraDepthOpticalFrame[] = "camera_depth_optical_frame";
constexpr char kCameraInfra1OpticalFrame[] = "camera_infra1_optical_frame";
constexpr char kCameraInfra2OpticalFrame[] = "camera_infra2_optical_frame";
// --- Tan so danh dinh ------------------------------------------------------
// Gia tri that nam trong config; nhung hang so nay la mac dinh va la moc de
// RateMonitor canh bao khi lech.
constexpr double kLidarRateHz = 25.0;
constexpr double kCameraRateHz = 30.0;
constexpr double kImuRateHz = 200.0;
constexpr double kEkfRateHz = 50.0;
constexpr double kBaseIoRateHz = 50.0;
constexpr double kSafetyRateHz = 20.0;
constexpr double kWebStateRateHz = 10.0;
// --- Hang so vat ly --------------------------------------------------------
constexpr double kGravity = 9.80665; // m/s^2, khop voi gravity_align_nodelet
// --- Ham tra ve duong dan (co ghi de bang env) -----------------------------
// Thu muc cau hinh: $VSLAM_CONFIG_DIR neu co, khong thi kConfigurationDirectory.
std::string ConfigDir();
// Thu muc tai nguyen: $VSLAM_RESOURCE_DIR neu co, khong thi kResourceDirectory.
std::string ResourceDir();
// ConfigDir() + "/" + file_name
std::string ConfigPath(const std::string& file_name);
// ResourceDir() + "/" + rel
std::string ResourcePath(const std::string& rel);
// Thu muc ban do: ResourceDir() + "/maps"
std::string MapDir();
// Thu muc ban ghi .vsr: ResourceDir() + "/records"
std::string RecordDir();
// Corpus .db de test: $VSLAM_CORPUS_DIR neu co, khong thi MapDir().
// Trong luc port, tro sang ../vSLAM_ws/maps de dung lai map_house.db va
// map_hospital.db ma khong phai copy 3.8 GB.
std::string CorpusDir();
} // namespace vslam
#endif // VSLAM_NODE_CONSTANTS_H

View File

@@ -0,0 +1,112 @@
#ifndef VSLAM_ROBOT_MODEL_H
#define VSLAM_ROBOT_MODEL_H
// Hinh hoc robot + cay frame, nap tu `robot.yaml`. THAY CHO URDF.
//
// ================== VI SAO LOP NAY TON TAI ==================
// Truoc khi co no, phep dung `camera_depth_optical_frame -> base_link` bi
// LAP LAI o bon file (hai tool va hai file test), moi cho mot ban chep cua
// cung mot chuoi QuaternionMultiply. Va `cliff_detect.nominal_tz = 0.803` da
// lech voi `sim.camera_z = 0.80` -- hai con so le ra phai la MOT.
//
// Do dung la lop bug "hai cho phai giu dong bo" ma `PROJECT_CONTEXT.md:71`
// cua repo cu da ghi nhan giua URDF va launch param.
//
// Quy tac: KHONG stage nao duoc tu dung lai mot phep bien doi tu cac so trong
// robot.yaml. Moi stage goi `RobotModel::StaticTransform()` hoac lay tu
// `tree()`.
#include <memory>
#include <string>
#include <vector>
#include "vslam/config.h"
#include "vslam/transform_tree.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct RobotGeometry {
double wheel_radius = 0.075;
double wheel_separation = 0.36;
double robot_radius = 0.24;
double body_half_width = 0.17;
};
struct BaseLimits {
double max_linear = 0.35;
double max_angular = 0.80;
double accel_limit = 0.30;
double cmd_timeout = 0.30;
};
struct WheelOdomNoise {
double sigma_x_per_m = 0.02;
double sigma_y_per_m = 0.02;
double sigma_yaw_per_rad = 0.05;
double slip_threshold = 0.20;
bool slip_sigma_is_measured = true;
};
class RobotModel {
public:
RobotModel();
~RobotModel();
RobotModel(const RobotModel&) = delete;
RobotModel& operator=(const RobotModel&) = delete;
// Nap tu node goc cua robot.yaml. Tra loi thay vi nem: nguoi goi quyet dinh
// dung han hay chay voi mac dinh.
//
// Kiem, va TU CHOI neu sai:
// - canh trung lap (hai dong cung `child`) -- cai sau se am tham thang;
// - canh tao chu trinh;
// - `child` mo coi (parent khong ton tai va khong phai base_link);
// - khoa la trong `geometry:` / `base:` / `wheel_odom:` (go sai ten).
StatusResponse Load(const ConfigNode& root);
// Nap tu duong dan file. Tien loi cho tool.
StatusResponse LoadFile(const std::string& path);
const RobotGeometry& geometry() const { return geometry_; }
const BaseLimits& base() const { return base_; }
const WheelOdomNoise& wheel_odom() const { return wheel_odom_; }
// Cay frame, DA nap moi canh tinh. Ba canh dong (map->odom,
// odom->base_footprint, base_footprint->base_link) do cac stage tuong ung
// ghi vao, moi canh dung mot writer.
TransformTree& tree() { return *tree_; }
const TransformTree& tree() const { return *tree_; }
// Phep bien doi TINH giua hai frame. Chi di qua cac canh tinh, nen khong
// can dau thoi gian va khong bao gio "chua co du lieu".
//
// Tra false neu mot trong hai frame khong ton tai hoac duong di di qua mot
// canh dong -- truong hop do phai dung tree().Lookup() voi stamp.
bool StaticTransform(const std::string& target, const std::string& source,
Transform* out) const;
// Chieu cao camera so voi MAT SAN (khong phai so voi tam truc).
//
// Day chinh la `tz` ma cliff_detect mong doi, va la ly do
// `cliff_detect.nominal_tz` KHONG duoc go tay: no la
// camera_link.z + wheel_radius, tinh tu cung mot nguon.
double camera_height_above_floor() const;
// Goc chuc xuong cua camera (rad), lay tu canh base_link -> camera_link.
double camera_pitch() const;
private:
RobotGeometry geometry_;
BaseLimits base_;
WheelOdomNoise wheel_odom_;
std::unique_ptr<TransformTree> tree_;
double camera_z_in_base_link_ = 0.0;
double camera_pitch_ = 0.0;
bool have_camera_ = false;
};
} // namespace vslam
#endif // VSLAM_ROBOT_MODEL_H

View File

@@ -0,0 +1,125 @@
#ifndef VSLAM_STATS_H
#define VSLAM_STATS_H
// Do dac runtime. Khong phai tien nghi -- day la thu ROS khong cho va vi vay
// repo cu phai doan mo:
// * khong biet mot subscriber bo lo bao nhieu ban tin (queue ROS drop im lang)
// * khong biet mot chuoi nodelet tre bao nhieu
// Moi Channel va moi stage deu phai bao cao duoc so lieu nay ra /api/status.
#include <atomic>
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
#include "vslam/clock.h"
namespace vslam {
// Do tan so bang cua so truot, dung steady_clock.
// An toan cho mot nguoi ghi + nhieu nguoi doc.
class RateMonitor {
public:
explicit RateMonitor(double window_sec = 2.0);
// Goi moi lan co su kien.
void Tick(std::chrono::steady_clock::time_point now);
void Tick(); // dung steady_clock::now(), chi cho main/tool
// Hz uoc luong trong cua so. 0 neu chua du mau.
double hz() const;
// Giay ke tu su kien cuoi. +inf neu chua co su kien nao.
double age_sec(std::chrono::steady_clock::time_point now) const;
uint64_t count() const { return count_.load(std::memory_order_relaxed); }
void Reset();
private:
const double window_sec_;
std::atomic<uint64_t> count_{0};
std::atomic<int64_t> first_ns_{0}; // moc cua so hien tai
std::atomic<int64_t> last_ns_{0};
std::atomic<uint64_t> window_count_{0};
std::atomic<double> hz_{0.0};
};
// Dem su kien bi bo. Chia hai loai vi chung co nguyen nhan khac han nhau.
struct DropCounter {
std::atomic<uint64_t> total{0};
void Add(uint64_t n = 1) { total.fetch_add(n, std::memory_order_relaxed); }
uint64_t get() const { return total.load(std::memory_order_relaxed); }
void Reset() { total.store(0, std::memory_order_relaxed); }
};
// So lieu cua mot Channel.
struct ChannelStats {
std::string name;
uint64_t capacity = 0;
uint64_t published = 0; // tong so ban tin da Publish()
uint64_t overwritten = 0; // so ban tin bi ghi de truoc khi moi reader doc xong
uint64_t readers = 0;
uint64_t max_reader_lag = 0; // reader tut hau nhat, tinh bang so ban tin
uint64_t total_reader_drops = 0;
double hz = 0.0;
};
// So lieu cua ApproxTimeSync.
struct SyncStats {
uint64_t matched = 0;
uint64_t dropped_slop = 0; // co ban tin nhung lech thoi gian qua max_slop
uint64_t dropped_timeout = 0; // het han cho, phat voi input tuy chon de trong
uint64_t dropped_queue = 0; // pivot bi day ra khoi hang doi truoc khi khop
double last_slop_sec = 0.0;
};
// So lieu cua mot driver phan cung.
struct DriverStats {
double hz = 0.0;
uint64_t frames = 0;
uint64_t errors = 0;
uint64_t packets_lost = 0; // LiDAR: suy ra tu do dai sweep
uint64_t short_sweeps = 0; // sweep thieu tia
double stamp_skew_ms = 0.0; // MCU: lech dong ho host <-> thiet bi
double clock_skew_ppm = 0.0; // MCU: he so skew cua ClockSync, tinh theo ppm
bool connected = false;
std::string last_error;
};
// Do thoi luong mot doan code, giu p50/p95/max.
// Dung cho process_ms cua SLAM va cho vong perception.
class LatencyMonitor {
public:
explicit LatencyMonitor(size_t window = 128);
~LatencyMonitor();
void Add(double ms);
double p50() const;
double p95() const;
double max() const;
double last() const;
uint64_t count() const;
void Reset();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
// RAII: do thoi gian song cua object roi day vao LatencyMonitor.
class ScopedLatency {
public:
ScopedLatency(LatencyMonitor* m, const Clock* clock);
~ScopedLatency();
private:
LatencyMonitor* m_;
std::chrono::steady_clock::time_point t0_;
};
} // namespace vslam
#endif // VSLAM_STATS_H

View File

@@ -0,0 +1,144 @@
#ifndef VSLAM_TELEOP_MODEL_H
#define VSLAM_TELEOP_MODEL_H
// Mo hinh trang thai teleop.
//
// ============ NGUON GOC ============
// Port tu robot_bringup/scripts/teleop_model.py cua vSLAM_ws, ma ban than no
// duoc port tu package `virtual_joystick_teleop` (BSD-3-Clause), tac gia
// duongtd, https://git.pnkr.asia/DuongTD/virtual_joystick_teleop.git
//
// LOGIC GIU NGUYEN VEN. Day la ban dich sang C++, khong phai ban viet lai:
// moi nguong, moi thu tu uu tien, moi phep kep deu giong het ban Python.
// test_teleop_model.cc so ket qua voi vector sinh tu chinh ban Python do.
//
// ============ VI SAO KHONG VIET LAI BANG JS ============
// Ban dau toi viet mot joystick moi hoan toan trong app.js va bo qua file
// nay. Do la sai: mo hinh nay da chay that, da duoc chinh theo cam giac lai
// that, va co nhung thu mot ban viet voi khong co -- nhat la toc do chinh
// duoc khi dang chay.
//
// Trang web chi gui truc joystick da chuan hoa [-1, 1] va su kien phim.
// TOAN BO viec quy ra van toc nam o day, trong C++.
//
// ============ BA NGUON NHAP, CO THU TU UU TIEN ============
// manual (thanh truot kieu rqt) -- cao nhat
// joystick (truc analog)
// phim mui ten -- thap nhat
// Dat mot nguon se GIAI PHONG cac nguon khac. Khong bao gio tron hai nguon.
//
// LUU Y: mo hinh nay KHONG co ramp gia toc. Ramp nam o tang duoi (gioi han
// gia toc cua base). Do la dung: teleop noi "muon di bao nhanh", con base noi
// "den do nhanh duoc bao nhieu".
#include <set>
#include <string>
#include <utility>
namespace vslam {
enum class TeleopKey { kUp, kDown, kLeft, kRight };
// Tra ve false neu ten phim khong duoc ho tro. Ten khop ban Python:
// "Up", "Down", "Left", "Right".
bool ParseTeleopKey(const std::string& name, TeleopKey* out);
const char* TeleopKeyName(TeleopKey k);
struct TeleopConfig {
double linear_speed = 0.30; // scale hien tai, chinh duoc luc chay
double angular_speed = 0.70;
double linear_step = 0.05; // buoc chinh
double angular_step = 0.10;
double min_linear_speed = 0.05; // gioi han cua scale
double max_linear_speed = 2.00;
double min_angular_speed = 0.10;
double max_angular_speed = 2.00;
// Gioi han duoi cua LENH (co dau). Mac dinh = -max_*_speed.
// Tach rieng de gioi han lui khac gioi han tien duoc.
bool has_min_linear_command = false;
double min_linear_command = 0.0;
bool has_min_angular_command = false;
double min_angular_command = 0.0;
};
class TeleopModel {
public:
// Nem std::invalid_argument neu cau hinh vo ly, giong ban Python nem
// ValueError. Kiem o day chu khong im lang roi ve default: mot gioi han
// van toc sai la mot robot chay nhanh hon nguoi lai nghi.
explicit TeleopModel(TeleopConfig cfg = TeleopConfig());
// --- Nguon nhap ----------------------------------------------------------
// Dat trang thai mot phim. Tra false neu phim khong ho tro.
bool SetKey(TeleopKey key, bool pressed);
void ClearKeys();
// Truc analog trong [-1, 1] tu joystick chuot/cham.
void SetJoystick(double horizontal, double vertical);
void ReleaseJoystick();
// Lenh co dau ben vung, kieu thanh truot rqt.
// Truyen nullptr cho truc khong muon doi.
std::pair<double, double> SetManualCommand(const double* linear_x,
const double* angular_z);
void ReleaseManualControl();
// Nha het moi nguon -> lenh ve 0.
void ClearMotion();
// --- Ket qua -------------------------------------------------------------
// (linear_x m/s, angular_z rad/s).
std::pair<double, double> Command() const;
// Truc hien thi [-1, 1] cho knob tren trang. Phim mui ten cung lam knob
// dich -- de nguoi lai thay duoc minh dang bam gi.
std::pair<double, double> JoystickPosition() const;
// --- Chinh toc do luc dang chay -----------------------------------------
double AdjustLinearSpeed(double direction);
double AdjustAngularSpeed(double direction);
double SetLinearSpeed(double value);
double SetAngularSpeed(double value);
double SetMaxLinearSpeed(double value);
double SetMaxAngularSpeed(double value);
double SetMinLinearCommand(double value);
double SetMinAngularCommand(double value);
// --- Truy van ------------------------------------------------------------
double linear_speed() const { return linear_speed_; }
double angular_speed() const { return angular_speed_; }
double max_linear_speed() const { return max_linear_speed_; }
double max_angular_speed() const { return max_angular_speed_; }
double min_linear_command() const { return min_linear_command_; }
double min_angular_command() const { return min_angular_command_; }
bool joystick_active() const { return joystick_active_; }
bool manual_control_active() const { return manual_active_; }
bool key_pressed(TeleopKey k) const { return keys_.count(k) != 0; }
private:
std::pair<double, double> ClampCommand(double linear_x, double angular_z) const;
void ClampManualCommand();
double linear_step_, angular_step_;
double min_linear_speed_, max_linear_speed_;
double min_angular_speed_, max_angular_speed_;
double min_linear_command_, min_angular_command_;
double linear_speed_, angular_speed_;
std::set<TeleopKey> keys_;
bool joystick_active_ = false;
double joy_h_ = 0.0, joy_v_ = 0.0;
bool manual_active_ = false;
double manual_lin_ = 0.0, manual_ang_ = 0.0;
};
} // namespace vslam
#endif // VSLAM_TELEOP_MODEL_H

View File

@@ -0,0 +1,169 @@
#ifndef VSLAM_TRANSFORM_TREE_H
#define VSLAM_TRANSFORM_TREE_H
// Thay tf2_ros::Buffer.
//
// Khong dung tf3 (github.com/Huandaotien/tf3, cai ma xloc_cpp dung) vi:
// submodule third_party/tf3 chua bao gio duoc checkout nen khong kiem chung
// duoc, license cua fork ca nhan chua ro, va no la thu vien TONG QUAT cho cay
// tuy y voi re-parent va da publisher. Bai toan o day hep hon nhieu.
//
// BE MAT API van giu tuong thich tf3 (lookupTransform / setTransform) de sau
// nay muon doi sang tf3 chi la thay header.
//
// CAY TF CUA HE NAY -- 9 frame, va chi BA canh la dong:
//
// map
// | <- slam, ~1 Hz, tu getMapCorrection()
// odom
// | <- ekf, 50 Hz
// base_footprint
// | <- gravity_align, 50 Hz (roll/pitch DO duoc)
// base_link
// |-- laser_link tinh
// |-- imu_link tinh
// `-- camera_link tinh
// `-- camera_depth_optical_frame tinh
// |-- camera_infra1_optical_frame tinh
// `-- camera_infra2_optical_frame tinh
//
// Moi canh tinh nap tu robot.yaml. Day chinh la thu THAY URDF, va no xoa luon
// bug "hai cho phai giu dong bo" ma PROJECT_CONTEXT.md ghi: hien gia tri hinh
// hoc nam ca trong robot.urdf.xacro lan robot.yaml.
//
// QUY TAC BAT BUOC: MOI CANH CO DUNG MOT NGUOI GHI.
// Vi pham quy tac nay la lop bug TF kho debug nhat. localization.launch cua
// repo cu da phai canh bao dieu nay bang mot khoi comment o dau file.
//
// Vi cha cua moi frame co dinh luc khoi tao, duong di child->root duoc tinh
// truoc thanh mot mang: vong lookup khong tra map, khong cap phat.
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
using FrameId = uint16_t;
constexpr FrameId kInvalidFrame = 0xFFFF;
class TransformTree {
public:
// history_sec: giu bao lau lich su canh dong.
// slots_per_edge: so mau moi canh dong (ring buffer).
// 50 Hz * 10 s = 500, nen 512 la du cho canh nhanh nhat.
explicit TransformTree(double history_sec = 10.0, size_t slots_per_edge = 512);
~TransformTree();
TransformTree(const TransformTree&) = delete;
TransformTree& operator=(const TransformTree&) = delete;
// --- Dang ky frame ------------------------------------------------------
// Tra ve id on dinh cho ten frame. Goi nhieu lan cung ten tra cung id.
// Chuoi chi bam MOT LAN o day; moi thao tac sau deu dung FrameId.
FrameId Resolve(const std::string& name);
// kInvalidFrame neu chua dang ky.
FrameId Find(const std::string& name) const;
const std::string& Name(FrameId id) const;
size_t frame_count() const;
// --- Canh tinh ----------------------------------------------------------
// Dat canh tinh parent -> child. Goi lai voi cung cap se GHI DE (cho phep,
// vi nap lai config la thao tac hop le).
// Nem ConfigError neu tao vong.
StatusResponse SetStatic(FrameId parent, FrameId child, const Transform& tf);
StatusResponse SetStatic(const std::string& parent, const std::string& child,
const Transform& tf);
// --- Canh dong ----------------------------------------------------------
// Dat mau moi cho canh dong parent -> child.
//
// Tra false neu:
// * stamp lui ve qua khu so voi mau moi nhat (du hieu ban ghi bi xao tron
// thu tu, hoac hai nguoi cung ghi mot canh -- vi pham quy tac tren)
// * canh nay da duoc khai la tinh
//
// Lan goi dau tien tren mot cap (parent, child) se dang ky canh do la dong.
bool SetTransform(FrameId parent, FrameId child, UnixTime stamp,
const Transform& tf);
// --- Tra cuu ------------------------------------------------------------
// Bien doi dua diem tu `source` sang `target` tai thoi diem `stamp`.
//
// Noi suy: LERP tinh tien + SLERP quay giua hai mau kep `stamp`.
// Ngoai suy: TU CHOI neu stamp > mau moi nhat + extrapolation_limit.
// Day la khac biet co y voi tf2: tf2 nem TransformExtrapolationException va
// rat nhieu code goi bat roi bo qua im lang. O day tra false va dien `err`.
bool Lookup(FrameId target, FrameId source, UnixTime stamp, Transform* out,
std::string* err = nullptr) const;
bool Lookup(const std::string& target, const std::string& source, UnixTime stamp,
Transform* out, std::string* err = nullptr) const;
// Dung mau moi nhat cua tung canh, khong noi suy. Tuong duong
// lookupTransform(..., ros::Time(0), ...) cua tf2.
bool LookupLatest(FrameId target, FrameId source, Transform* out,
std::string* err = nullptr) const;
// Thoi diem moi nhat ma CA HAI nhanh deu co du lieu. kTimeZero neu khong co.
UnixTime LatestCommonTime(FrameId a, FrameId b) const;
// Co du lieu de tra cuu tai `stamp` khong, khong thuc su tinh.
bool CanTransform(FrameId target, FrameId source, UnixTime stamp) const;
// --- Cau hinh -----------------------------------------------------------
void SetExtrapolationLimit(double sec);
double extrapolation_limit() const;
// Danh sach canh dong kem tan so va tuoi mau moi nhat -- ra /api/status.
struct EdgeStatus {
std::string parent;
std::string child;
bool is_static = false;
uint64_t samples = 0;
UnixTime latest;
double hz = 0.0;
};
std::vector<EdgeStatus> EdgeStatuses() const;
// In cay ra chuoi nhieu dong, dung de chan doan. Thay rqt_tf_tree.
std::string DumpTree() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
using TransformTreePtr = std::shared_ptr<TransformTree>;
// Tuong duong xloc_cpp/include/tf_bridge.h: thu hep be mat xuong dung mot
// thao tac ma cac stage can -- dua mot frame ve frame theo doi.
class TfBridge {
public:
TfBridge(std::string tracking_frame, double lookup_timeout_sec,
std::shared_ptr<const TransformTree> tree);
bool LookupToTracking(UnixTime time, FrameId frame, Transform* out) const;
bool LookupToTracking(UnixTime time, const std::string& frame, Transform* out) const;
const std::string& tracking_frame() const { return tracking_frame_; }
private:
std::string tracking_frame_;
double lookup_timeout_sec_;
std::shared_ptr<const TransformTree> tree_;
};
} // namespace vslam
#endif // VSLAM_TRANSFORM_TREE_H

View File

@@ -0,0 +1,197 @@
#ifndef VSLAM_UNIX_TIME_H
#define VSLAM_UNIX_TIME_H
// Thay ros::Time / ros::Duration.
//
// Dua tren xloc_cpp/include/unix_time.h, giu nguyen layout {uint32 sec, nsec}
// de tuong thich API voi xloc. Ba sua loi so voi ban goc:
//
// 1. fromSec() voi input am: ban goc lam static_cast<uint32_t>(std::floor(s))
// -> tran im lang. Ban nay kep ve 0 va co fromSecChecked() de goi biet.
// 2. So hoc noi bo lam bang int64_t nanoseconds. Ban goc ep hieu hai UnixTime
// sang int32_t; nam 2038 se tran, va ngay bay gio thi sec ~1.7e9 da sat
// gioi han 2.1e9 cua int32_t.
// 3. TIME_MAX: ban goc dat trong anonymous namespace TRONG HEADER, nen moi
// translation unit co mot ban sao rieng (va sinh canh bao unused). Ban nay
// dung `inline constexpr` cua C++17.
//
// QUY TAC HAI DONG HO -- doc ky truoc khi dung:
// * UnixTime dung de DONG DAU du lieu (stamp). Nguon la system_clock, co the
// nhay khi NTP dieu chinh.
// * Timeout, chu ky, do thoi luong PHAI dung std::chrono::steady_clock.
// Lan lon hai thu nay la lop bug dang co trong safety_monitor_node.cpp: no
// dung ros::Time::now() cho ca hai, nen 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.
// Xem clock.h: moi stage nhan Clock& thay vi goi UnixTime::now() truc tiep.
#include <cstdint>
#include <cstdlib>
#include <cmath>
#include <chrono>
#include <limits>
#include <string>
#include <thread>
namespace vslam {
class Duration;
constexpr int64_t kNsPerSec = 1000000000LL;
class UnixTime {
public:
uint32_t sec;
uint32_t nsec;
constexpr UnixTime() : sec(0), nsec(0) {}
constexpr UnixTime(uint32_t s, uint32_t ns) : sec(s), nsec(ns) {}
static UnixTime now() {
using namespace std::chrono;
const auto ns =
duration_cast<nanoseconds>(system_clock::now().time_since_epoch()).count();
return fromNSec(ns);
}
static constexpr UnixTime fromNSec(int64_t ns) {
return ns <= 0 ? UnixTime()
: UnixTime(static_cast<uint32_t>(ns / kNsPerSec),
static_cast<uint32_t>(ns % kNsPerSec));
}
// Input am bi kep ve 0. Ban goc tran im lang o day.
static UnixTime fromSec(double s) {
if (!(s > 0.0)) return UnixTime(); // bat ca NaN
return fromNSec(static_cast<int64_t>(std::llround(s * 1e9)));
}
// Nhu fromSec() nhung bao cho goi biet input co hop le khong.
static bool fromSecChecked(double s, UnixTime* out) {
if (!(s >= 0.0) || s > static_cast<double>(std::numeric_limits<uint32_t>::max())) {
return false;
}
*out = fromNSec(static_cast<int64_t>(std::llround(s * 1e9)));
return true;
}
constexpr int64_t toNSec() const {
return static_cast<int64_t>(sec) * kNsPerSec + static_cast<int64_t>(nsec);
}
constexpr double toSec() const {
return static_cast<double>(sec) + static_cast<double>(nsec) * 1e-9;
}
constexpr bool isZero() const { return sec == 0 && nsec == 0; }
constexpr bool operator==(const UnixTime& o) const {
return sec == o.sec && nsec == o.nsec;
}
constexpr bool operator!=(const UnixTime& o) const { return !(*this == o); }
constexpr bool operator<(const UnixTime& o) const {
return sec < o.sec || (sec == o.sec && nsec < o.nsec);
}
constexpr bool operator>(const UnixTime& o) const { return o < *this; }
constexpr bool operator<=(const UnixTime& o) const { return !(*this > o); }
constexpr bool operator>=(const UnixTime& o) const { return !(*this < o); }
friend Duration operator-(const UnixTime& a, const UnixTime& b);
friend UnixTime operator+(const UnixTime& t, const Duration& d);
friend UnixTime operator-(const UnixTime& t, const Duration& d);
// Giu lai dang ham de tuong thich voi ma goi theo kieu xloc.
static constexpr UnixTime TIME_MAX() {
return UnixTime(std::numeric_limits<uint32_t>::max(),
static_cast<uint32_t>(kNsPerSec - 1));
}
// "1737000000.123456789" -- dung cho log va JSON, khong mat do chinh xac
// nhu khi in double.
std::string toString() const;
};
inline constexpr UnixTime kTimeMax = UnixTime::TIME_MAX();
inline constexpr UnixTime kTimeZero = UnixTime();
class Duration {
public:
int32_t sec;
int32_t nsec;
constexpr Duration() : sec(0), nsec(0) {}
Duration(int32_t s, int32_t ns) : sec(s), nsec(ns) { normalize(); }
explicit Duration(double seconds) { *this = fromNSec(static_cast<int64_t>(std::llround(seconds * 1e9))); }
static Duration fromSec(double s) { return Duration(s); }
static Duration fromNSec(int64_t ns_total) {
Duration d;
d.sec = static_cast<int32_t>(ns_total / kNsPerSec);
d.nsec = static_cast<int32_t>(ns_total % kNsPerSec);
d.normalize();
return d;
}
constexpr int64_t toNSec() const {
return static_cast<int64_t>(sec) * kNsPerSec + static_cast<int64_t>(nsec);
}
constexpr double toSec() const {
return static_cast<double>(sec) + static_cast<double>(nsec) * 1e-9;
}
constexpr bool isZero() const { return sec == 0 && nsec == 0; }
void normalize() {
if (nsec >= kNsPerSec) {
sec += static_cast<int32_t>(nsec / kNsPerSec);
nsec = static_cast<int32_t>(nsec % kNsPerSec);
} else if (nsec < 0) {
const int32_t borrow = (std::abs(nsec) / static_cast<int32_t>(kNsPerSec)) + 1;
sec -= borrow;
nsec += borrow * static_cast<int32_t>(kNsPerSec);
}
}
Duration operator+(const Duration& o) const { return fromNSec(toNSec() + o.toNSec()); }
Duration operator-(const Duration& o) const { return fromNSec(toNSec() - o.toNSec()); }
Duration operator-() const { return fromNSec(-toNSec()); }
Duration& operator+=(const Duration& o) { *this = *this + o; return *this; }
Duration& operator-=(const Duration& o) { *this = *this - o; return *this; }
constexpr bool operator==(const Duration& o) const { return sec == o.sec && nsec == o.nsec; }
constexpr bool operator!=(const Duration& o) const { return !(*this == o); }
bool operator<(const Duration& o) const { return toNSec() < o.toNSec(); }
bool operator>(const Duration& o) const { return o < *this; }
bool operator<=(const Duration& o) const { return !(*this > o); }
bool operator>=(const Duration& o) const { return !(*this < o); }
// Chi dung o main/tool. Trong stage phai dung Clock::SleepUntil() de replay
// tat dinh chay duoc.
void sleep() const {
const int64_t ns = toNSec();
if (ns <= 0) return;
std::this_thread::sleep_for(std::chrono::nanoseconds(ns));
}
};
inline Duration operator-(const UnixTime& a, const UnixTime& b) {
return Duration::fromNSec(a.toNSec() - b.toNSec());
}
inline UnixTime operator+(const UnixTime& t, const Duration& d) {
return UnixTime::fromNSec(t.toNSec() + d.toNSec());
}
inline UnixTime operator-(const UnixTime& t, const Duration& d) {
return UnixTime::fromNSec(t.toNSec() - d.toNSec());
}
// Giay troi qua giua hai stamp. Dung cho moi phep so sanh timeout theo stamp
// du lieu (khong phai timeout tuong doi -- cai do dung steady_clock).
inline double SecondsBetween(const UnixTime& later, const UnixTime& earlier) {
return static_cast<double>(later.toNSec() - earlier.toNSec()) * 1e-9;
}
} // namespace vslam
#endif // VSLAM_UNIX_TIME_H

View File

@@ -0,0 +1,272 @@
#ifndef VSLAM_VSLAM_COMMON_H
#define VSLAM_VSLAM_COMMON_H
// Dinh nghia lai cac kieu ban tin thuong dung, thay cho sensor_msgs /
// geometry_msgs / nav_msgs. Khuon mau: xloc_cpp/include/xloc_common.h.
//
// HAI QUY TAC BAT BUOC cho moi struct trong file nay:
//
// 1. KHONG chua kieu Eigen fixed-size (Eigen::Vector3d, Matrix4d, ...).
// Dung double x, y, z. Eigen fixed-size co yeu cau can chinh 16/32 byte;
// dat chung trong struct di qua bien .so la nguon loi alignment kinh dien
// tren arm64 khi hai phia compile voi EIGEN_MAX_ALIGN_BYTES khac nhau.
// Chuyen sang Eigen o trong ham, khong o trong kieu du lieu.
//
// 2. KHONG include header cua ROS, PCL, OpenCV hay RTAB-Map. File nay phai
// compile duoc voi mot Eigen-less, PCL-less toolchain. Cac lib phia tren
// tu chuyen doi sang kieu cua ho o bien cua minh.
//
// Vung du lieu lon (anh, point cloud, scan) luon di qua he thong duoi dang
// std::shared_ptr<const T>. Khong bao gio copy. Xem channel.h.
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "vslam/unix_time.h"
namespace vslam {
// ---------------------------------------------------------------------------
// Trang thai tra ve
// ---------------------------------------------------------------------------
enum class StatusCode : int32_t {
kOk = 0,
kInvalidArgument = 1,
kNotFound = 2,
kFailedPrecondition = 3,
kUnavailable = 4,
kTimeout = 5,
kInternal = 6,
kUnauthenticated = 7,
};
struct StatusResponse {
StatusCode code = StatusCode::kOk;
std::string message;
bool ok() const { return code == StatusCode::kOk; }
explicit operator bool() const { return ok(); }
static StatusResponse Ok() { return {}; }
static StatusResponse Error(StatusCode c, std::string m) {
return StatusResponse{c, std::move(m)};
}
};
// ---------------------------------------------------------------------------
// std_msgs
// ---------------------------------------------------------------------------
struct Header {
uint32_t seq = 0;
UnixTime stamp;
std::string frame_id;
};
// ---------------------------------------------------------------------------
// geometry_msgs
// ---------------------------------------------------------------------------
struct Point {
double x = 0.0, y = 0.0, z = 0.0;
};
struct Vector3 {
double x = 0.0, y = 0.0, z = 0.0;
};
struct Quaternion {
double x = 0.0, y = 0.0, z = 0.0, w = 1.0;
};
struct Pose {
Point position;
Quaternion orientation;
};
struct Pose2D {
double x = 0.0, y = 0.0, theta = 0.0;
};
struct PoseStamped {
Header header;
Pose pose;
};
struct PoseWithCovariance {
Pose pose;
double covariance[36] = {}; // row-major 6x6: x y z roll pitch yaw
};
struct PoseWithCovarianceStamped {
Header header;
PoseWithCovariance pose;
};
struct Twist {
Vector3 linear;
Vector3 angular;
};
struct TwistWithCovariance {
Twist twist;
double covariance[36] = {};
};
// Phep bien doi cung. Dung trong TransformTree.
struct Transform {
Vector3 translation;
Quaternion rotation;
};
struct TransformStamped {
Header header; // header.frame_id = frame CHA
std::string child_frame_id;
Transform transform;
};
// ---------------------------------------------------------------------------
// nav_msgs
// ---------------------------------------------------------------------------
struct Odometry {
Header header; // header.frame_id = frame tham chieu (vd "odom")
std::string child_frame_id; // vd "base_footprint"
PoseWithCovariance pose;
TwistWithCovariance twist;
};
// value: -1 = chua biet, 0..100 = xac suat bi chiem.
// Bo cuc giong nav_msgs/OccupancyGrid: hang chinh, goc o (origin), o (0,0)
// nam o phan tu data[0].
struct OccupancyGrid {
Header header;
float resolution = 0.05f; // met / o
uint32_t width = 0;
uint32_t height = 0;
Pose origin; // goc duoi-trai cua o (0,0), trong frame header
std::vector<int8_t> data; // size = width * height
};
// ---------------------------------------------------------------------------
// sensor_msgs
// ---------------------------------------------------------------------------
struct Imu {
Header header;
Quaternion orientation;
double orientation_covariance[9] = {}; // [0] < 0 nghia la khong co orientation
Vector3 angular_velocity; // rad/s
double angular_velocity_covariance[9] = {};
Vector3 linear_acceleration; // m/s^2
double linear_acceleration_covariance[9] = {};
};
struct FluidPressure {
Header header;
double fluid_pressure = 0.0; // Pa
double variance = 0.0;
};
struct Temperature {
Header header;
double temperature = 0.0; // do C
double variance = 0.0;
};
// BA NGU NGHIA CUA MOT TIA -- doc truoc khi cham vao bat cu code nao doc scan.
// Duoc dinh nghia o scan_sanitizer va safety_monitor dua vao dung ba thu nay:
//
// NaN : khong do duoc (duoi range_min, hoac driver tra 0).
// +inf : do duoc nhung khong co phan xa (vuot range_max).
// range_max + 1.0 : SENTINEL -- tia bi che boi than robot, da bi cat co
// y boi sector mask. KHAC HAN voi hai truong hop tren:
// day khong phai "khong thay gi", ma la "khong duoc
// phep nhin". safety_monitor dem rieng so tia nay
// (front_blanked) va khong tinh vao front_usable.
//
// Nham ba thu nay lai lam robot hoac dung im (SCAN_SPARSE) hoac dam vao tuong.
struct LaserScan {
Header header;
float angle_min = 0.0f; // rad
float angle_max = 0.0f;
float angle_increment = 0.0f;
float time_increment = 0.0f; // giay giua hai tia
float scan_time = 0.0f; // giay giua hai sweep
float range_min = 0.0f; // met
float range_max = 0.0f;
std::vector<float> ranges;
std::vector<float> intensities; // co the rong
};
struct CameraInfo {
Header header;
uint32_t width = 0;
uint32_t height = 0;
double k[9] = {}; // ma tran noi 3x3, hang chinh
double d[5] = {}; // meo anh (plumb bob)
uint32_t binning_x = 1;
uint32_t binning_y = 1;
double fx() const { return k[0]; }
double fy() const { return k[4]; }
double cx() const { return k[2]; }
double cy() const { return k[5]; }
// Noi suy sau khi decimate: crop_decimate cua image_proc cap nhat binning
// chu KHONG chia lai K. Consumer phai tu bu, dung nhu image_geometry lam.
double fx_binned() const { return k[0] / static_cast<double>(binning_x); }
double fy_binned() const { return k[4] / static_cast<double>(binning_y); }
double cx_binned() const { return k[2] / static_cast<double>(binning_x); }
double cy_binned() const { return k[5] / static_cast<double>(binning_y); }
};
enum class PixelFormat : uint8_t {
kMono8 = 0, // 8UC1 -- infra1 / infra2
kMono16 = 1, // 16UC1 -- depth thang do theo depth_scale
kFloat32 = 2, // 32FC1 -- depth met
};
// Anh KHONG so huu bo nho khi den tu librealsense: `data` tro vao buffer cua
// SDK va `keep_alive` giu rs2::frame song. Xem realsense_driver.
struct Image {
Header header;
uint32_t width = 0;
uint32_t height = 0;
uint32_t step = 0; // byte moi hang
PixelFormat format = PixelFormat::kMono8;
float depth_scale = 0.001f; // met moi don vi, chi co nghia voi kMono16
const uint8_t* data = nullptr;
std::shared_ptr<void> keep_alive; // giu nguon buffer song
size_t size_bytes() const { return static_cast<size_t>(step) * height; }
};
struct PointXYZ {
float x = 0.0f, y = 0.0f, z = 0.0f;
};
// Cloud phang (khong to chuc theo anh). Cac buoc loc tra ve kieu nay.
struct PointCloudXYZ {
Header header;
std::vector<PointXYZ> points;
bool is_dense = false; // false nghia la co the co NaN
};
// ---------------------------------------------------------------------------
// Bi danh cho con tro chia se -- moi thu di qua Channel deu la kieu nay.
// ---------------------------------------------------------------------------
using LaserScanPtr = std::shared_ptr<const LaserScan>;
using ImuPtr = std::shared_ptr<const Imu>;
using ImagePtr = std::shared_ptr<const Image>;
using PointCloudXYZPtr = std::shared_ptr<const PointCloudXYZ>;
using OccupancyGridPtr = std::shared_ptr<const OccupancyGrid>;
using OdometryPtr = std::shared_ptr<const Odometry>;
} // namespace vslam
#endif // VSLAM_VSLAM_COMMON_H

View File

@@ -0,0 +1,101 @@
#include "vslam/clock.h"
#include <mutex>
#include <thread>
#include "vslam/log.h"
namespace vslam {
namespace {
class SystemClock : public Clock {
public:
UnixTime Now() const override { return UnixTime::now(); }
SteadyPoint Steady() const override { return std::chrono::steady_clock::now(); }
void SleepUntil(SteadyPoint tp) override {
std::this_thread::sleep_until(tp);
}
bool is_virtual() const override { return false; }
};
} // namespace
ClockPtr MakeSystemClock() { return std::make_shared<SystemClock>(); }
// ---------------------------------------------------------------------------
struct ReplayClock::Impl {
mutable std::mutex mu;
UnixTime now;
SteadyPoint steady_origin;
std::chrono::nanoseconds steady_offset{0};
double speed = 0.0; // 0 = chay nhanh nhat, khong ngu that
};
ReplayClock::ReplayClock(UnixTime start) : impl_(std::make_unique<Impl>()) {
impl_->now = start;
impl_->steady_origin = std::chrono::steady_clock::now();
}
ReplayClock::~ReplayClock() = default;
UnixTime ReplayClock::Now() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->now;
}
Clock::SteadyPoint ReplayClock::Steady() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->steady_origin + impl_->steady_offset;
}
void ReplayClock::SleepUntil(SteadyPoint tp) {
double speed;
SteadyPoint current;
{
std::lock_guard<std::mutex> lk(impl_->mu);
speed = impl_->speed;
current = impl_->steady_origin + impl_->steady_offset;
if (tp > current) {
// Thoi gian ao luon tien toi moc yeu cau, ke ca khi khong ngu that.
impl_->steady_offset += (tp - current);
}
}
if (speed > 0.0 && tp > current) {
const auto wall = std::chrono::duration_cast<std::chrono::nanoseconds>(
(tp - current) / speed);
std::this_thread::sleep_for(wall);
}
}
void ReplayClock::SetNow(UnixTime t, bool allow_backward) {
std::lock_guard<std::mutex> lk(impl_->mu);
if (!allow_backward && t < impl_->now) {
// Lui thoi gian la dau hieu ban ghi bi xao tron thu tu. Bao chu khong
// im lang chap nhan -- neu im lang thi moi phep timeout sau do deu sai.
VSLAM_WARN("ReplayClock: tu choi lui thoi gian " << impl_->now.toString()
<< " -> " << t.toString());
return;
}
impl_->now = t;
}
void ReplayClock::Advance(Duration d) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->now = impl_->now + d;
impl_->steady_offset += std::chrono::nanoseconds(d.toNSec());
}
void ReplayClock::SetSpeed(double speed) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->speed = speed < 0.0 ? 0.0 : speed;
}
std::shared_ptr<ReplayClock> MakeReplayClock(UnixTime start) {
return std::make_shared<ReplayClock>(start);
}
} // namespace vslam

View File

@@ -0,0 +1,234 @@
#include "vslam/config.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <sstream>
#include "vslam/log.h"
namespace vslam {
struct ConfigNode::Impl {
YAML::Node node;
std::string path; // "safety.scan.stop_distance"
std::string origin; // ten file
Impl() = default;
Impl(YAML::Node n, std::string p, std::string o)
: node(std::move(n)), path(std::move(p)), origin(std::move(o)) {}
};
namespace {
std::string JoinPath(const std::string& base, const std::string& key) {
return base.empty() ? key : base + "." + key;
}
// Thong bao loi luon co ba manh: file, duong dan key day du, va ly do.
// Thieu bat cu manh nao la nguoi doc phai di tim, va do chinh la thu lam
// viec sua config trong ban ROS ton thoi gian.
//
// Nhan chuoi chu khong nhan ConfigNode::Impl: Impl la kieu private, ham tu do
// trong namespace vo danh khong goi ten no duoc.
std::string Where(const std::string& origin, const std::string& path,
const std::string& key) {
std::ostringstream oss;
oss << origin << ": " << JoinPath(path, key);
return oss.str();
}
} // namespace
ConfigNode::ConfigNode() : impl_(std::make_unique<Impl>()) {}
ConfigNode::ConfigNode(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
ConfigNode::ConfigNode(const ConfigNode& o) : impl_(std::make_unique<Impl>(*o.impl_)) {}
ConfigNode::ConfigNode(ConfigNode&&) noexcept = default;
ConfigNode& ConfigNode::operator=(const ConfigNode& o) {
if (this != &o) impl_ = std::make_unique<Impl>(*o.impl_);
return *this;
}
ConfigNode& ConfigNode::operator=(ConfigNode&&) noexcept = default;
ConfigNode::~ConfigNode() = default;
ConfigNode ConfigNode::LoadFile(const std::string& path) {
try {
YAML::Node root = YAML::LoadFile(path);
return ConfigNode(std::make_unique<Impl>(std::move(root), "", path));
} catch (const YAML::BadFile&) {
throw ConfigError("khong mo duoc file cau hinh: " + path);
} catch (const YAML::Exception& e) {
throw ConfigError("YAML sai cu phap trong " + path + ": " + e.what());
}
}
ConfigNode ConfigNode::LoadString(const std::string& yaml, std::string origin) {
try {
YAML::Node root = YAML::Load(yaml);
return ConfigNode(std::make_unique<Impl>(std::move(root), "", std::move(origin)));
} catch (const YAML::Exception& e) {
throw ConfigError("YAML sai cu phap trong " + origin + ": " + e.what());
}
}
ConfigNode ConfigNode::operator[](const std::string& key) const {
// Key thieu tra node Null thay vi nem, de chuoi a["b"]["c"] khong no giua
// chung. Nguoi goi kiem IsNull() hoac dung require() o buoc cuoi.
if (!impl_->node || !impl_->node.IsMap()) {
return ConfigNode(std::make_unique<Impl>(YAML::Node(YAML::NodeType::Undefined),
JoinPath(impl_->path, key), impl_->origin));
}
return ConfigNode(std::make_unique<Impl>(impl_->node[key],
JoinPath(impl_->path, key), impl_->origin));
}
ConfigNode ConfigNode::at(size_t index) const {
std::ostringstream oss;
oss << impl_->path << "[" << index << "]";
if (!impl_->node || !impl_->node.IsSequence() || index >= impl_->node.size()) {
return ConfigNode(std::make_unique<Impl>(YAML::Node(YAML::NodeType::Undefined),
oss.str(), impl_->origin));
}
return ConfigNode(std::make_unique<Impl>(impl_->node[index], oss.str(), impl_->origin));
}
bool ConfigNode::IsNull() const {
return !impl_->node || impl_->node.IsNull() ||
impl_->node.Type() == YAML::NodeType::Undefined;
}
bool ConfigNode::IsMap() const { return impl_->node && impl_->node.IsMap(); }
bool ConfigNode::IsSequence() const { return impl_->node && impl_->node.IsSequence(); }
bool ConfigNode::IsScalar() const { return impl_->node && impl_->node.IsScalar(); }
size_t ConfigNode::size() const { return impl_->node ? impl_->node.size() : 0; }
const std::string& ConfigNode::path() const { return impl_->path; }
const std::string& ConfigNode::origin() const { return impl_->origin; }
// --- Doc gia tri -----------------------------------------------------------
template <typename T>
T ConfigNode::get(const std::string& key, const T& fallback) const {
const ConfigNode child = (*this)[key];
if (child.IsNull()) return fallback;
try {
return child.impl_->node.template as<T>();
} catch (const YAML::Exception&) {
// Sai KIEU luon la loi, khac han voi THIEU key. Thieu key co the co y
// (dung default); sai kieu thi khong bao gio co y.
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::require(const std::string& key) const {
const ConfigNode child = (*this)[key];
if (child.IsNull()) {
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": thieu key bat buoc");
}
try {
return child.impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::as() const {
if (IsNull()) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": thieu gia tri");
}
try {
return impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::as(const T& fallback) const {
if (IsNull()) return fallback;
try {
return impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": sai kieu du lieu");
}
}
// --- Kiem key la -----------------------------------------------------------
std::vector<std::string> ConfigNode::Keys() const {
std::vector<std::string> out;
if (!IsMap()) return out;
for (const auto& kv : impl_->node) {
out.push_back(kv.first.as<std::string>());
}
return out;
}
std::vector<std::string> ConfigNode::UnknownKeys(
const std::vector<std::string>& known) const {
std::vector<std::string> out;
for (const auto& k : Keys()) {
if (std::find(known.begin(), known.end(), k) == known.end()) {
out.push_back(JoinPath(impl_->path, k));
}
}
return out;
}
bool ConfigNode::WarnUnknownKeys(const std::vector<std::string>& known) const {
const auto unknown = UnknownKeys(known);
for (const auto& k : unknown) {
// ERROR chu khong phai WARN: mot key la gan nhu luon la go sai ten cua
// mot key that, nghia la gia tri nguoi dung DINH dat dang khong co tac
// dung. "stop_distence" thay vi "stop_distance" van cho robot chay, chi
// la chay voi khoang cach dung mac dinh.
VSLAM_ERROR(impl_->origin << ": key khong nhan ra: " << k);
}
return unknown.empty();
}
std::vector<std::pair<std::string, std::string>> ConfigNode::AsStringMap() const {
std::vector<std::pair<std::string, std::string>> out;
if (!IsMap()) return out;
for (const auto& kv : impl_->node) {
// Giu nguyen van ca khoa lan gia tri. Khoi `rtabmap:` trong slam.yaml di
// thang vao rtabmap::ParametersMap, noi moi gia tri deu la chuoi -- kiem
// kieu o day se lam hong "true"/"0.05" thanh bool/double roi in lai khac.
out.emplace_back(kv.first.as<std::string>(), kv.second.as<std::string>());
}
return out;
}
// --- Khoi tao tuong minh ---------------------------------------------------
#define VSLAM_CONFIG_DEFINE(T) \
template T ConfigNode::get<T>(const std::string&, const T&) const; \
template T ConfigNode::require<T>(const std::string&) const; \
template T ConfigNode::as<T>() const; \
template T ConfigNode::as<T>(const T&) const;
VSLAM_CONFIG_DEFINE(bool)
VSLAM_CONFIG_DEFINE(int)
VSLAM_CONFIG_DEFINE(unsigned int)
VSLAM_CONFIG_DEFINE(float)
VSLAM_CONFIG_DEFINE(double)
VSLAM_CONFIG_DEFINE(std::string)
#undef VSLAM_CONFIG_DEFINE
template std::vector<double> ConfigNode::get<std::vector<double>>(
const std::string&, const std::vector<double>&) const;
template std::vector<double> ConfigNode::require<std::vector<double>>(
const std::string&) const;
template std::vector<std::string> ConfigNode::get<std::vector<std::string>>(
const std::string&, const std::vector<std::string>&) const;
template std::vector<std::string> ConfigNode::require<std::vector<std::string>>(
const std::string&) const;
} // namespace vslam

View File

@@ -0,0 +1,235 @@
#include "vslam/geometry.h"
#include <algorithm>
namespace vslam {
namespace {
constexpr double kPi = 3.14159265358979323846;
constexpr double kTwoPi = 2.0 * kPi;
} // namespace
// --- Goc -------------------------------------------------------------------
double NormalizeAngle(double a) {
// Port tu wheel_odom_node.cpp:45-50. Ban goc dung vong while; std::fmod
// nhanh hon va khong treo khi input la mot so rat lon (vd NaN lan vao tu
// encoder hong -> vong while chay vo han).
if (!std::isfinite(a)) return 0.0;
a = std::fmod(a + kPi, kTwoPi);
if (a < 0.0) a += kTwoPi;
return a - kPi;
}
// --- Quaternion ------------------------------------------------------------
Quaternion QuaternionFromYaw(double yaw) {
const double h = yaw * 0.5;
return Quaternion{0.0, 0.0, std::sin(h), std::cos(h)};
}
Quaternion QuaternionFromRPY(double roll, double pitch, double yaw) {
const double cr = std::cos(roll * 0.5), sr = std::sin(roll * 0.5);
const double cp = std::cos(pitch * 0.5), sp = std::sin(pitch * 0.5);
const double cy = std::cos(yaw * 0.5), sy = std::sin(yaw * 0.5);
Quaternion q;
q.w = cr * cp * cy + sr * sp * sy;
q.x = sr * cp * cy - cr * sp * sy;
q.y = cr * sp * cy + sr * cp * sy;
q.z = cr * cp * sy - sr * sp * cy;
return q;
}
double YawFromQuaternion(const Quaternion& q) {
const double siny = 2.0 * (q.w * q.z + q.x * q.y);
const double cosy = 1.0 - 2.0 * (q.y * q.y + q.z * q.z);
return std::atan2(siny, cosy);
}
void RPYFromQuaternion(const Quaternion& q, double* roll, double* pitch, double* yaw) {
const double sinr = 2.0 * (q.w * q.x + q.y * q.z);
const double cosr = 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
if (roll) *roll = std::atan2(sinr, cosr);
// Kep truoc khi asin: sai so lam tron co the day gia tri ra ngoai [-1,1]
// va asin tra NaN. NaN o pitch lan vao gravity_align roi vao TF la mot
// trong nhung duong lan truyen loi kho truy nhat.
double sinp = 2.0 * (q.w * q.y - q.z * q.x);
sinp = std::max(-1.0, std::min(1.0, sinp));
if (pitch) *pitch = std::asin(sinp);
if (yaw) *yaw = YawFromQuaternion(q);
}
Quaternion QuaternionNormalized(const Quaternion& q) {
const double n = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
if (n < 1e-12) return Quaternion{0.0, 0.0, 0.0, 1.0};
const double inv = 1.0 / n;
return Quaternion{q.x * inv, q.y * inv, q.z * inv, q.w * inv};
}
Quaternion QuaternionInverse(const Quaternion& q) {
// Gia dinh q da chuan hoa -> nghich dao = lien hop.
return Quaternion{-q.x, -q.y, -q.z, q.w};
}
Quaternion QuaternionMultiply(const Quaternion& a, const Quaternion& b) {
Quaternion r;
r.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
r.x = a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y;
r.y = a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x;
r.z = a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w;
return r;
}
Quaternion QuaternionSlerp(const Quaternion& a, const Quaternion& b, double t) {
t = std::max(0.0, std::min(1.0, t));
double dot = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
// Lat dau de di duong ngan. Thieu buoc nay thi noi suy qua mot goc gan 360
// do thay vi goc nho -- TF se "quay nguoc" mot cach ngoan muc.
Quaternion bb = b;
if (dot < 0.0) {
bb = Quaternion{-b.x, -b.y, -b.z, -b.w};
dot = -dot;
}
// Gan trung nhau: LERP roi chuan hoa, tranh chia cho sin(theta) ~ 0.
if (dot > 0.9995) {
Quaternion r{a.x + (bb.x - a.x) * t, a.y + (bb.y - a.y) * t,
a.z + (bb.z - a.z) * t, a.w + (bb.w - a.w) * t};
return QuaternionNormalized(r);
}
const double theta_0 = std::acos(dot);
const double theta = theta_0 * t;
const double sin_theta_0 = std::sin(theta_0);
const double s0 = std::cos(theta) - dot * std::sin(theta) / sin_theta_0;
const double s1 = std::sin(theta) / sin_theta_0;
return Quaternion{a.x * s0 + bb.x * s1, a.y * s0 + bb.y * s1,
a.z * s0 + bb.z * s1, a.w * s0 + bb.w * s1};
}
Vector3 RotateVector(const Quaternion& q, const Vector3& v) {
// v' = v + 2w(u x v) + 2(u x (u x v)), voi u la phan vector cua q.
// Re hon chuyen sang ma tran quay khi chi xoay mot vai vector.
const double ux = q.x, uy = q.y, uz = q.z, w = q.w;
const double cx = uy * v.z - uz * v.y;
const double cy = uz * v.x - ux * v.z;
const double cz = ux * v.y - uy * v.x;
const double ccx = uy * cz - uz * cy;
const double ccy = uz * cx - ux * cz;
const double ccz = ux * cy - uy * cx;
return Vector3{v.x + 2.0 * (w * cx + ccx),
v.y + 2.0 * (w * cy + ccy),
v.z + 2.0 * (w * cz + ccz)};
}
// --- Transform -------------------------------------------------------------
Transform TransformIdentity() {
Transform t;
t.translation = Vector3{0.0, 0.0, 0.0};
t.rotation = Quaternion{0.0, 0.0, 0.0, 1.0};
return t;
}
Transform TransformCompose(const Transform& a, const Transform& b) {
Transform r;
r.rotation = QuaternionMultiply(a.rotation, b.rotation);
const Vector3 rb = RotateVector(a.rotation, b.translation);
r.translation = a.translation + rb;
return r;
}
Transform TransformInverse(const Transform& t) {
Transform r;
r.rotation = QuaternionInverse(t.rotation);
const Vector3 neg{-t.translation.x, -t.translation.y, -t.translation.z};
r.translation = RotateVector(r.rotation, neg);
return r;
}
Point TransformPoint(const Transform& t, const Point& p) {
const Vector3 v{p.x, p.y, p.z};
const Vector3 r = RotateVector(t.rotation, v) + t.translation;
return Point{r.x, r.y, r.z};
}
Vector3 TransformVector(const Transform& t, const Vector3& v) {
return RotateVector(t.rotation, v) + t.translation;
}
Transform TransformInterpolate(const Transform& a, const Transform& b, double t) {
Transform r;
r.translation = Lerp(a.translation, b.translation, t);
r.rotation = QuaternionSlerp(a.rotation, b.rotation, t);
return r;
}
// --- SE(2) -----------------------------------------------------------------
Pose2D Pose2DFromPose(const Pose& p) {
return Pose2D{p.position.x, p.position.y, YawFromQuaternion(p.orientation)};
}
Pose PoseFromPose2D(const Pose2D& p, double z) {
Pose out;
out.position = Point{p.x, p.y, z};
out.orientation = QuaternionFromYaw(p.theta);
return out;
}
Pose2D Pose2DCompose(const Pose2D& a, const Pose2D& b) {
const double c = std::cos(a.theta), s = std::sin(a.theta);
return Pose2D{a.x + c * b.x - s * b.y,
a.y + s * b.x + c * b.y,
NormalizeAngle(a.theta + b.theta)};
}
Pose2D Pose2DInverse(const Pose2D& p) {
const double c = std::cos(p.theta), s = std::sin(p.theta);
return Pose2D{-(c * p.x + s * p.y),
-(-s * p.x + c * p.y),
NormalizeAngle(-p.theta)};
}
Pose2D Pose2DBetween(const Pose2D& a, const Pose2D& b) {
// a^-1 * b, viet truc tiep thay vi ghep hai ham -- it phep tinh hon va
// day la duong nong khi tinh delta giua hai keyframe.
const double c = std::cos(a.theta), s = std::sin(a.theta);
const double dx = b.x - a.x, dy = b.y - a.y;
return Pose2D{c * dx + s * dy,
-s * dx + c * dy,
NormalizeAngle(b.theta - a.theta)};
}
Transform TransformFromPose2D(const Pose2D& p, double z) {
Transform t;
t.translation = Vector3{p.x, p.y, z};
t.rotation = QuaternionFromYaw(p.theta);
return t;
}
Pose2D Pose2DFromTransform(const Transform& t) {
return Pose2D{t.translation.x, t.translation.y, YawFromQuaternion(t.rotation)};
}
Transform TransformFromPose(const Pose& p) {
Transform t;
t.translation = Vector3{p.position.x, p.position.y, p.position.z};
t.rotation = p.orientation;
return t;
}
Pose PoseFromTransform(const Transform& t) {
Pose p;
p.position = Point{t.translation.x, t.translation.y, t.translation.z};
p.orientation = t.rotation;
return p;
}
} // namespace vslam

View File

@@ -0,0 +1,65 @@
#include "vslam/json_parse.h"
#include <cctype>
#include <cstdlib>
namespace vslam {
namespace {
// Tra ve vi tri ngay sau dau ':' cua "key", hoac npos.
size_t FindValue(const std::string& body, const std::string& key) {
const std::string pat = "\"" + key + "\"";
size_t p = body.find(pat);
if (p == std::string::npos) return std::string::npos;
p += pat.size();
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
if (p >= body.size() || body[p] != ':') return std::string::npos;
++p;
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
return p < body.size() ? p : std::string::npos;
}
} // namespace
bool JsonGetNumber(const std::string& body, const std::string& key, double* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos) return false;
char* end = nullptr;
const double v = std::strtod(body.c_str() + p, &end);
if (end == body.c_str() + p) return false;
*out = v;
return true;
}
bool JsonGetBool(const std::string& body, const std::string& key, bool* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos) return false;
if (body.compare(p, 4, "true") == 0) { *out = true; return true; }
if (body.compare(p, 5, "false") == 0) { *out = false; return true; }
return false;
}
bool JsonGetString(const std::string& body, const std::string& key, std::string* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos || body[p] != '"') return false;
out->clear();
for (size_t i = p + 1; i < body.size(); ++i) {
if (body[i] == '\\' && i + 1 < body.size()) {
++i;
switch (body[i]) {
case 'n': out->push_back('\n'); break;
case 't': out->push_back('\t'); break;
case 'r': out->push_back('\r'); break;
default: out->push_back(body[i]); break;
}
continue;
}
if (body[i] == '"') return true;
out->push_back(body[i]);
}
return false; // chuoi khong dong
}
} // namespace vslam

View File

@@ -0,0 +1,141 @@
#include "vslam/log.h"
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <mutex>
namespace vslam {
namespace {
std::atomic<int> g_level{static_cast<int>(LogLevel::kInfo)};
std::atomic<bool> g_color{false};
std::atomic<bool> g_color_init{false};
std::mutex& SinkMutex() {
static std::mutex m;
return m;
}
LogSink& SinkRef() {
static LogSink sink; // rong = dung sink mac dinh ra stderr
return sink;
}
const char* ColorFor(LogLevel l) {
switch (l) {
case LogLevel::kDebug: return "\033[2m"; // mo
case LogLevel::kInfo: return "";
case LogLevel::kWarn: return "\033[33m"; // vang
case LogLevel::kError: return "\033[31m"; // do
default: return "";
}
}
// Chi lay ten file, bo duong dan. __FILE__ trong build tree rat dai.
const char* BaseName(const char* path) {
const char* slash = std::strrchr(path, '/');
return slash != nullptr ? slash + 1 : path;
}
bool ColorEnabled() {
if (!g_color_init.load(std::memory_order_relaxed)) {
g_color.store(::isatty(STDERR_FILENO) != 0, std::memory_order_relaxed);
g_color_init.store(true, std::memory_order_relaxed);
}
return g_color.load(std::memory_order_relaxed);
}
} // namespace
const char* LogLevelName(LogLevel l) {
switch (l) {
case LogLevel::kDebug: return "DEBUG";
case LogLevel::kInfo: return "INFO";
case LogLevel::kWarn: return "WARN";
case LogLevel::kError: return "ERROR";
case LogLevel::kOff: return "OFF";
}
return "?";
}
bool ParseLogLevel(const std::string& s, LogLevel* out) {
if (s == "debug" || s == "DEBUG") { *out = LogLevel::kDebug; return true; }
if (s == "info" || s == "INFO") { *out = LogLevel::kInfo; return true; }
if (s == "warn" || s == "WARN") { *out = LogLevel::kWarn; return true; }
if (s == "error" || s == "ERROR") { *out = LogLevel::kError; return true; }
if (s == "off" || s == "OFF") { *out = LogLevel::kOff; return true; }
return false;
}
void SetLogLevel(LogLevel l) { g_level.store(static_cast<int>(l), std::memory_order_relaxed); }
LogLevel GetLogLevel() {
return static_cast<LogLevel>(g_level.load(std::memory_order_relaxed));
}
void SetLogSink(LogSink sink) {
std::lock_guard<std::mutex> lk(SinkMutex());
SinkRef() = std::move(sink);
}
void SetLogColor(bool on) {
g_color.store(on, std::memory_order_relaxed);
g_color_init.store(true, std::memory_order_relaxed);
}
namespace detail {
void EmitLog(LogLevel level, const char* file, int line, const std::string& msg) {
{
std::lock_guard<std::mutex> lk(SinkMutex());
if (SinkRef()) {
SinkRef()(level, file, line, msg);
return;
}
}
// Sink mac dinh: stderr, mot lan fwrite co khoa. Dinh dang:
// HH:MM:SS.mmm WARN scan_sanitizer.cc:88 noi dung
using namespace std::chrono;
const auto now = system_clock::now();
const auto t = system_clock::to_time_t(now);
const auto ms = duration_cast<milliseconds>(now.time_since_epoch()).count() % 1000;
std::tm tm_buf{};
::localtime_r(&t, &tm_buf);
char stamp[32];
std::snprintf(stamp, sizeof(stamp), "%02d:%02d:%02d.%03d", tm_buf.tm_hour,
tm_buf.tm_min, tm_buf.tm_sec, static_cast<int>(ms));
const bool color = ColorEnabled();
const char* c_on = color ? ColorFor(level) : "";
const char* c_off = (color && c_on[0] != '\0') ? "\033[0m" : "";
static std::mutex out_mu;
std::lock_guard<std::mutex> lk(out_mu);
std::fprintf(stderr, "%s%s %-5s %s:%d %s%s\n", c_on, stamp,
LogLevelName(level), BaseName(file), line, msg.c_str(), c_off);
}
bool ThrottlePass(std::atomic<int64_t>* state, double period_sec) {
// steady_clock, KHONG phai stamp du lieu. Neu dung stamp thi khi replay
// nhanh (speed=0) moi dong se bi bop nham.
const auto now = std::chrono::steady_clock::now().time_since_epoch();
const int64_t now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
const int64_t period_ns = static_cast<int64_t>(period_sec * 1e9);
int64_t last = state->load(std::memory_order_relaxed);
if (last != 0 && now_ns - last < period_ns) return false;
// CAS: neu hai luong cung toi day thi chi mot luong duoc in.
return state->compare_exchange_strong(last, now_ns, std::memory_order_relaxed);
}
} // namespace detail
} // namespace vslam

View File

@@ -0,0 +1,43 @@
#include "vslam/node_constants.h"
#include <cstdlib>
namespace vslam {
namespace {
// Tra ve $name neu co va khong rong, khong thi `fallback`.
std::string EnvOr(const char* name, const char* fallback) {
const char* v = std::getenv(name);
if (v != nullptr && v[0] != '\0') return std::string(v);
return std::string(fallback);
}
std::string Join(const std::string& dir, const std::string& rel) {
if (dir.empty()) return rel;
if (dir.back() == '/') return dir + rel;
return dir + "/" + rel;
}
} // namespace
std::string ConfigDir() { return EnvOr(kConfigDirEnv, kConfigurationDirectory); }
std::string ResourceDir() { return EnvOr(kResourceDirEnv, kResourceDirectory); }
std::string ConfigPath(const std::string& file_name) {
return Join(ConfigDir(), file_name);
}
std::string ResourcePath(const std::string& rel) { return Join(ResourceDir(), rel); }
std::string MapDir() { return Join(ResourceDir(), "maps"); }
std::string RecordDir() { return Join(ResourceDir(), "records"); }
std::string CorpusDir() {
const char* v = std::getenv(kCorpusDirEnv);
if (v != nullptr && v[0] != '\0') return std::string(v);
return MapDir();
}
} // namespace vslam

View File

@@ -0,0 +1,222 @@
#include "vslam/robot_model.h"
#include <algorithm>
#include <cmath>
#include <set>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Doc mot chuoi 3 so tu node YAML. Tra false kem duong day du khi hong --
// mot phep bien doi sai im lang la ca ban do lech.
bool ReadVec3(const ConfigNode& n, double out[3], std::string* err) {
if (n.IsNull()) {
*err = "thieu";
return false;
}
if (!n.IsSequence() || n.size() != 3) {
*err = "phai la chuoi 3 so, " + n.path();
return false;
}
for (size_t i = 0; i < 3; ++i) {
out[i] = n.at(i).as<double>();
}
return true;
}
} // namespace
RobotModel::RobotModel() : tree_(new TransformTree) {}
RobotModel::~RobotModel() = default;
StatusResponse RobotModel::LoadFile(const std::string& path) {
// ConfigNode::LoadFile nem ConfigError khi file thieu hoac YAML hong. Mot
// file config sai khong duoc phep lam sap tien trinh -- doi thanh loi doc
// duoc de nguoi goi quyet dinh.
try {
return Load(ConfigNode::LoadFile(path));
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml (" + path + "): " + e.what());
}
}
StatusResponse RobotModel::Load(const ConfigNode& root) {
// --- geometry ---
const ConfigNode g = root["geometry"];
if (!g.IsNull()) {
// Go sai ten khoa hien tai roi ve mac dinh mot cach im lang. `wheel_base`
// thay vi `wheel_separation` nghia la moi phep quay sai ti le, va khong
// co gi bao.
const std::vector<std::string> unknown = g.UnknownKeys(
{"wheel_radius", "wheel_separation", "robot_radius", "body_half_width"});
if (!unknown.empty()) {
std::string m = "robot.yaml geometry: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
geometry_.wheel_radius = g.get<double>("wheel_radius", geometry_.wheel_radius);
geometry_.wheel_separation =
g.get<double>("wheel_separation", geometry_.wheel_separation);
geometry_.robot_radius = g.get<double>("robot_radius", geometry_.robot_radius);
geometry_.body_half_width =
g.get<double>("body_half_width", geometry_.body_half_width);
}
if (!(geometry_.wheel_radius > 0.0) || !(geometry_.wheel_separation > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml: wheel_radius va wheel_separation "
"phai duong");
}
// --- base ---
const ConfigNode b = root["base"];
if (!b.IsNull()) {
const std::vector<std::string> unknown = b.UnknownKeys(
{"max_linear", "max_angular", "accel_limit", "cmd_timeout"});
if (!unknown.empty()) {
std::string m = "robot.yaml base: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
base_.max_linear = b.get<double>("max_linear", base_.max_linear);
base_.max_angular = b.get<double>("max_angular", base_.max_angular);
base_.accel_limit = b.get<double>("accel_limit", base_.accel_limit);
base_.cmd_timeout = b.get<double>("cmd_timeout", base_.cmd_timeout);
}
// --- wheel_odom ---
const ConfigNode w = root["wheel_odom"];
if (!w.IsNull()) {
const std::vector<std::string> unknown =
w.UnknownKeys({"sigma_x_per_m", "sigma_y_per_m", "sigma_yaw_per_rad",
"slip_threshold", "slip_sigma_is_measured"});
if (!unknown.empty()) {
std::string m = "robot.yaml wheel_odom: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
wheel_odom_.sigma_x_per_m =
w.get<double>("sigma_x_per_m", wheel_odom_.sigma_x_per_m);
wheel_odom_.sigma_y_per_m =
w.get<double>("sigma_y_per_m", wheel_odom_.sigma_y_per_m);
wheel_odom_.sigma_yaw_per_rad =
w.get<double>("sigma_yaw_per_rad", wheel_odom_.sigma_yaw_per_rad);
wheel_odom_.slip_threshold =
w.get<double>("slip_threshold", wheel_odom_.slip_threshold);
wheel_odom_.slip_sigma_is_measured =
w.get<bool>("slip_sigma_is_measured", wheel_odom_.slip_sigma_is_measured);
}
// --- frames ---
const ConfigNode frames = root["frames"];
if (frames.IsNull() || !frames.IsSequence() || frames.size() == 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml: thieu khoi `frames:` -- khong co "
"no thi khong stage nao dat duoc cam bien vao "
"dau");
}
// Mot `child` chi duoc xuat hien MOT lan. Hai dong cung child thi dong sau
// am tham thang, va nua so doc file se tin dong dau.
std::set<std::string> seen_children;
for (size_t i = 0; i < frames.size(); ++i) {
const ConfigNode f = frames.at(i);
const std::vector<std::string> unknown =
f.UnknownKeys({"parent", "child", "xyz", "rpy"});
if (!unknown.empty()) {
std::string m = "robot.yaml frames[" + std::to_string(i) + "]: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
const std::string parent = f.require<std::string>("parent");
const std::string child = f.require<std::string>("child");
if (parent == child) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"]: parent trung child (" + parent + ")");
}
if (!seen_children.insert(child).second) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"robot.yaml: frame `" + child +
"` duoc khai hai lan -- lan sau am tham thang, va do la lop bug "
"ma file nay sinh ra de xoa");
}
double xyz[3] = {0, 0, 0}, rpy[3] = {0, 0, 0};
std::string err;
if (!ReadVec3(f["xyz"], xyz, &err)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"].xyz: " + err);
}
if (!ReadVec3(f["rpy"], rpy, &err)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"].rpy: " + err);
}
Transform tf = TransformIdentity();
tf.translation = Vector3{xyz[0], xyz[1], xyz[2]};
tf.rotation = QuaternionFromRPY(rpy[0], rpy[1], rpy[2]);
// SetStatic nem ConfigError khi tao vong -- bat lai va tra ve loi doc
// duoc, vi mot file config sai khong duoc phep lam sap tien trinh.
try {
const StatusResponse st = tree_->SetStatic(parent, child, tf);
if (!st.ok()) return st;
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"] " + parent + " -> " + child + ": " +
e.what());
}
if (parent == kBaseLinkFrame && child == kCameraFrame) {
camera_z_in_base_link_ = xyz[2];
camera_pitch_ = rpy[1];
have_camera_ = true;
}
}
VSLAM_INFO("robot: " << frames.size() << " canh tinh, banh r="
<< geometry_.wheel_radius << " d=" << geometry_.wheel_separation
<< (have_camera_
? ", camera cao " + std::to_string(camera_height_above_floor()) +
" m so voi san"
: ", KHONG co camera_link"));
return StatusResponse::Ok();
}
bool RobotModel::StaticTransform(const std::string& target,
const std::string& source, Transform* out) const {
// Canh tinh khong co dau thoi gian, nen LookupLatest la dung: no dung mau
// moi nhat cua tung canh, va voi canh tinh thi chi co mot mau.
//
// `Find` chu khong `Resolve`: tra cuu mot frame chua ton tai phai TRA FALSE
// chu khong duoc am tham tao ra no. Resolve() tao frame moi, va mot frame
// go sai ten se thanh mot nhanh roi ma khong ai bao.
const FrameId t = tree_->Find(target);
const FrameId s = tree_->Find(source);
if (t == kInvalidFrame || s == kInvalidFrame) return false;
return tree_->LookupLatest(t, s, out);
}
double RobotModel::camera_height_above_floor() const {
// base_link o tam truc, cach san dung bang ban kinh banh.
//
// Day la ly do `cliff_detect.nominal_tz` KHONG duoc go tay: no la mot HE
// QUA cua hai so khac, va go tay lan thu hai la cho mot trong hai duoc
// phep lech.
return camera_z_in_base_link_ + geometry_.wheel_radius;
}
double RobotModel::camera_pitch() const { return camera_pitch_; }
} // namespace vslam

View File

@@ -0,0 +1,150 @@
#include "vslam/stats.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <mutex>
#include <vector>
namespace vslam {
namespace {
int64_t ToNs(std::chrono::steady_clock::time_point tp) {
return std::chrono::duration_cast<std::chrono::nanoseconds>(tp.time_since_epoch())
.count();
}
} // namespace
// --- RateMonitor -----------------------------------------------------------
RateMonitor::RateMonitor(double window_sec) : window_sec_(window_sec) {}
void RateMonitor::Tick(std::chrono::steady_clock::time_point now) {
const int64_t ns = ToNs(now);
count_.fetch_add(1, std::memory_order_relaxed);
last_ns_.store(ns, std::memory_order_relaxed);
const int64_t first = first_ns_.load(std::memory_order_relaxed);
if (first == 0) {
first_ns_.store(ns, std::memory_order_relaxed);
window_count_.store(1, std::memory_order_relaxed);
return;
}
const uint64_t wc = window_count_.fetch_add(1, std::memory_order_relaxed) + 1;
const double elapsed = static_cast<double>(ns - first) * 1e-9;
if (elapsed >= window_sec_) {
hz_.store(elapsed > 0.0 ? static_cast<double>(wc) / elapsed : 0.0,
std::memory_order_relaxed);
// Mo cua so moi. Khong dung cua so truot that (deque timestamp) vi o
// 200 Hz thi chi phi bo nho va khoa khong dang -- sai so cua cua so nhay
// la chap nhan duoc cho muc dich chan doan.
first_ns_.store(ns, std::memory_order_relaxed);
window_count_.store(0, std::memory_order_relaxed);
}
}
void RateMonitor::Tick() { Tick(std::chrono::steady_clock::now()); }
double RateMonitor::hz() const { return hz_.load(std::memory_order_relaxed); }
double RateMonitor::age_sec(std::chrono::steady_clock::time_point now) const {
const int64_t last = last_ns_.load(std::memory_order_relaxed);
if (last == 0) return std::numeric_limits<double>::infinity();
return static_cast<double>(ToNs(now) - last) * 1e-9;
}
void RateMonitor::Reset() {
count_.store(0, std::memory_order_relaxed);
first_ns_.store(0, std::memory_order_relaxed);
last_ns_.store(0, std::memory_order_relaxed);
window_count_.store(0, std::memory_order_relaxed);
hz_.store(0.0, std::memory_order_relaxed);
}
// --- LatencyMonitor --------------------------------------------------------
struct LatencyMonitor::Impl {
mutable std::mutex mu;
std::vector<double> ring;
size_t head = 0;
size_t filled = 0;
double max_seen = 0.0;
double last = 0.0;
uint64_t count = 0;
explicit Impl(size_t window) : ring(window, 0.0) {}
// Goi khi da giu mu.
double PercentileLocked(double p) const {
if (filled == 0) return 0.0;
std::vector<double> tmp(ring.begin(), ring.begin() + static_cast<long>(filled));
const size_t idx = static_cast<size_t>(p * static_cast<double>(filled - 1));
std::nth_element(tmp.begin(), tmp.begin() + static_cast<long>(idx), tmp.end());
return tmp[idx];
}
};
LatencyMonitor::LatencyMonitor(size_t window)
: impl_(std::make_unique<Impl>(window == 0 ? 1 : window)) {}
LatencyMonitor::~LatencyMonitor() = default;
void LatencyMonitor::Add(double ms) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->ring[impl_->head] = ms;
impl_->head = (impl_->head + 1) % impl_->ring.size();
if (impl_->filled < impl_->ring.size()) impl_->filled++;
if (ms > impl_->max_seen) impl_->max_seen = ms;
impl_->last = ms;
impl_->count++;
}
double LatencyMonitor::p50() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->PercentileLocked(0.50);
}
double LatencyMonitor::p95() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->PercentileLocked(0.95);
}
double LatencyMonitor::max() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->max_seen;
}
double LatencyMonitor::last() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->last;
}
uint64_t LatencyMonitor::count() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->count;
}
void LatencyMonitor::Reset() {
std::lock_guard<std::mutex> lk(impl_->mu);
std::fill(impl_->ring.begin(), impl_->ring.end(), 0.0);
impl_->head = 0;
impl_->filled = 0;
impl_->max_seen = 0.0;
impl_->last = 0.0;
impl_->count = 0;
}
// --- ScopedLatency ---------------------------------------------------------
ScopedLatency::ScopedLatency(LatencyMonitor* m, const Clock* clock)
: m_(m), t0_(clock != nullptr ? clock->Steady() : std::chrono::steady_clock::now()) {}
ScopedLatency::~ScopedLatency() {
if (m_ == nullptr) return;
const auto dt = std::chrono::steady_clock::now() - t0_;
m_->Add(std::chrono::duration<double, std::milli>(dt).count());
}
} // namespace vslam

View File

@@ -0,0 +1,262 @@
#include "vslam/teleop_model.h"
#include <algorithm>
#include <cmath>
#include <stdexcept>
namespace vslam {
namespace {
double Clamp(double v, double lo, double hi) { return std::max(lo, std::min(v, hi)); }
void ValidateFinite(const char* name, double v) {
if (!std::isfinite(v)) {
throw std::invalid_argument(std::string(name) + " must be a finite number");
}
}
void ValidateRange(const char* name, double minimum, double maximum, double step) {
ValidateFinite(name, minimum);
ValidateFinite(name, maximum);
ValidateFinite(name, step);
if (minimum < 0.0) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be non-negative");
}
if (maximum < minimum) {
throw std::invalid_argument(std::string("maximum ") + name +
" must not be less than its minimum");
}
if (step <= 0.0) {
throw std::invalid_argument(std::string(name) + " step must be positive");
}
}
void ValidateCommandRange(const char* name, double minimum, double maximum) {
ValidateFinite(name, minimum);
ValidateFinite(name, maximum);
if (minimum > 0.0) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be zero or negative");
}
if (maximum < 0.0) {
throw std::invalid_argument(std::string("maximum ") + name +
" must be zero or positive");
}
if (minimum >= maximum) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be less than its maximum");
}
}
} // namespace
bool ParseTeleopKey(const std::string& name, TeleopKey* out) {
if (name == "Up") { *out = TeleopKey::kUp; return true; }
if (name == "Down") { *out = TeleopKey::kDown; return true; }
if (name == "Left") { *out = TeleopKey::kLeft; return true; }
if (name == "Right") { *out = TeleopKey::kRight; return true; }
return false;
}
const char* TeleopKeyName(TeleopKey k) {
switch (k) {
case TeleopKey::kUp: return "Up";
case TeleopKey::kDown: return "Down";
case TeleopKey::kLeft: return "Left";
case TeleopKey::kRight: return "Right";
}
return "?";
}
TeleopModel::TeleopModel(TeleopConfig cfg) {
ValidateRange("linear speed", cfg.min_linear_speed, cfg.max_linear_speed,
cfg.linear_step);
ValidateRange("angular speed", cfg.min_angular_speed, cfg.max_angular_speed,
cfg.angular_step);
ValidateFinite("linear_speed", cfg.linear_speed);
ValidateFinite("angular_speed", cfg.angular_speed);
// Mac dinh: gioi han duoi doi xung voi gioi han tren.
const double min_lin_cmd =
cfg.has_min_linear_command ? cfg.min_linear_command : -cfg.max_linear_speed;
const double min_ang_cmd =
cfg.has_min_angular_command ? cfg.min_angular_command : -cfg.max_angular_speed;
ValidateCommandRange("linear command", min_lin_cmd, cfg.max_linear_speed);
ValidateCommandRange("angular command", min_ang_cmd, cfg.max_angular_speed);
linear_step_ = cfg.linear_step;
angular_step_ = cfg.angular_step;
min_linear_speed_ = cfg.min_linear_speed;
max_linear_speed_ = cfg.max_linear_speed;
min_angular_speed_ = cfg.min_angular_speed;
max_angular_speed_ = cfg.max_angular_speed;
min_linear_command_ = min_lin_cmd;
min_angular_command_ = min_ang_cmd;
linear_speed_ = Clamp(cfg.linear_speed, min_linear_speed_, max_linear_speed_);
angular_speed_ = Clamp(cfg.angular_speed, min_angular_speed_, max_angular_speed_);
}
// --- Nguon nhap ------------------------------------------------------------
bool TeleopModel::SetKey(TeleopKey key, bool pressed) {
if (pressed) {
// Bam phim GIAI PHONG lenh manual. Khong bao gio tron hai nguon.
ReleaseManualControl();
keys_.insert(key);
} else {
keys_.erase(key);
}
return true;
}
void TeleopModel::ClearKeys() { keys_.clear(); }
void TeleopModel::SetJoystick(double horizontal, double vertical) {
ValidateFinite("joystick horizontal axis", horizontal);
ValidateFinite("joystick vertical axis", vertical);
joy_h_ = Clamp(horizontal, -1.0, 1.0);
joy_v_ = Clamp(vertical, -1.0, 1.0);
joystick_active_ = true;
ReleaseManualControl();
}
void TeleopModel::ReleaseJoystick() { joystick_active_ = false; }
void TeleopModel::ClearMotion() {
ClearKeys();
ReleaseJoystick();
ReleaseManualControl();
}
std::pair<double, double> TeleopModel::SetManualCommand(const double* linear_x,
const double* angular_z) {
double cur_lin, cur_ang;
if (!manual_active_) {
const auto c = Command();
cur_lin = c.first;
cur_ang = c.second;
} else {
cur_lin = manual_lin_;
cur_ang = manual_ang_;
}
if (linear_x != nullptr) {
ValidateFinite("manual linear command", *linear_x);
cur_lin = *linear_x;
}
if (angular_z != nullptr) {
ValidateFinite("manual angular command", *angular_z);
cur_ang = *angular_z;
}
ClearKeys();
ReleaseJoystick();
const auto clamped = ClampCommand(cur_lin, cur_ang);
manual_lin_ = clamped.first;
manual_ang_ = clamped.second;
manual_active_ = true;
return clamped;
}
void TeleopModel::ReleaseManualControl() { manual_active_ = false; }
// --- Ket qua ---------------------------------------------------------------
std::pair<double, double> TeleopModel::ClampCommand(double linear_x,
double angular_z) const {
return {Clamp(linear_x, min_linear_command_, max_linear_speed_),
Clamp(angular_z, min_angular_command_, max_angular_speed_)};
}
void TeleopModel::ClampManualCommand() {
if (!manual_active_) return;
const auto c = ClampCommand(manual_lin_, manual_ang_);
manual_lin_ = c.first;
manual_ang_ = c.second;
}
std::pair<double, double> TeleopModel::Command() const {
// Thu tu uu tien: manual > joystick > phim.
if (manual_active_) return {manual_lin_, manual_ang_};
if (joystick_active_) {
return ClampCommand(-joy_v_ * linear_speed_, -joy_h_ * angular_speed_);
}
const int linear_axis = static_cast<int>(keys_.count(TeleopKey::kUp)) -
static_cast<int>(keys_.count(TeleopKey::kDown));
const int angular_axis = static_cast<int>(keys_.count(TeleopKey::kLeft)) -
static_cast<int>(keys_.count(TeleopKey::kRight));
return ClampCommand(linear_axis * linear_speed_, angular_axis * angular_speed_);
}
std::pair<double, double> TeleopModel::JoystickPosition() const {
if (joystick_active_) return {joy_h_, joy_v_};
const int h = static_cast<int>(keys_.count(TeleopKey::kRight)) -
static_cast<int>(keys_.count(TeleopKey::kLeft));
const int v = static_cast<int>(keys_.count(TeleopKey::kDown)) -
static_cast<int>(keys_.count(TeleopKey::kUp));
return {static_cast<double>(h), static_cast<double>(v)};
}
// --- Chinh toc do ----------------------------------------------------------
double TeleopModel::AdjustLinearSpeed(double direction) {
return SetLinearSpeed(linear_speed_ + direction * linear_step_);
}
double TeleopModel::AdjustAngularSpeed(double direction) {
return SetAngularSpeed(angular_speed_ + direction * angular_step_);
}
double TeleopModel::SetLinearSpeed(double value) {
ValidateFinite("linear speed", value);
linear_speed_ = Clamp(value, min_linear_speed_, max_linear_speed_);
return linear_speed_;
}
double TeleopModel::SetAngularSpeed(double value) {
ValidateFinite("angular speed", value);
angular_speed_ = Clamp(value, min_angular_speed_, max_angular_speed_);
return angular_speed_;
}
double TeleopModel::SetMaxLinearSpeed(double value) {
ValidateFinite("maximum linear speed", value);
max_linear_speed_ = std::max(min_linear_speed_, value);
linear_speed_ = std::min(linear_speed_, max_linear_speed_);
ClampManualCommand();
return max_linear_speed_;
}
double TeleopModel::SetMaxAngularSpeed(double value) {
ValidateFinite("maximum angular speed", value);
max_angular_speed_ = std::max(min_angular_speed_, value);
angular_speed_ = std::min(angular_speed_, max_angular_speed_);
ClampManualCommand();
return max_angular_speed_;
}
double TeleopModel::SetMinLinearCommand(double value) {
ValidateFinite("minimum linear command", value);
min_linear_command_ = std::min(0.0, value);
if (min_linear_command_ >= max_linear_speed_) {
min_linear_command_ = std::min(0.0, max_linear_speed_ - linear_step_);
}
ClampManualCommand();
return min_linear_command_;
}
double TeleopModel::SetMinAngularCommand(double value) {
ValidateFinite("minimum angular command", value);
min_angular_command_ = std::min(0.0, value);
if (min_angular_command_ >= max_angular_speed_) {
min_angular_command_ = std::min(0.0, max_angular_speed_ - angular_step_);
}
ClampManualCommand();
return min_angular_command_;
}
} // namespace vslam

View File

@@ -0,0 +1,485 @@
#include "vslam/transform_tree.h"
#include <algorithm>
#include <functional>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/stats.h"
namespace vslam {
namespace {
constexpr size_t kMaxDepth = 32; // cay that co 5 muc; 32 la chan an toan
struct Sample {
UnixTime stamp;
Transform tf;
};
} // namespace
// Mot canh = quan he cha-con. Canh tinh giu mot Transform; canh dong giu ring
// buffer cac mau theo thoi gian.
struct Edge {
FrameId parent = kInvalidFrame;
bool is_static = false;
Transform static_tf; // chi co nghia khi is_static
std::vector<Sample> ring;
size_t head = 0; // vi tri se ghi tiep
size_t filled = 0;
uint64_t samples = 0;
RateMonitor rate{2.0};
const Sample& at(size_t i) const { return ring[i % ring.size()]; }
// Mau moi nhat. Goi phai bao dam filled > 0.
const Sample& newest() const { return ring[(head + ring.size() - 1) % ring.size()]; }
// Mau cu nhat con song.
const Sample& oldest() const {
return filled < ring.size() ? ring[0] : ring[head % ring.size()];
}
};
struct TransformTree::Impl {
mutable std::mutex mu;
std::unordered_map<std::string, FrameId> name_to_id;
std::vector<std::string> id_to_name;
// Chi muc theo frame CON: moi frame co dung mot cha, nen mot canh la du.
// Day chinh la gia dinh cho phep bo toan bo may tra cuu tong quat cua tf2.
std::unordered_map<FrameId, Edge> edges;
double history_sec;
size_t slots_per_edge;
double extrapolation_limit = 0.1;
std::string empty_name;
// Duong di tu `frame` len goc. Tra ve so muc, hoac 0 neu vuot kMaxDepth.
size_t PathToRoot(FrameId frame, FrameId* out) const {
size_t n = 0;
FrameId cur = frame;
while (n < kMaxDepth) {
out[n++] = cur;
auto it = edges.find(cur);
if (it == edges.end()) return n; // toi goc
cur = it->second.parent;
}
return 0; // vong hoac qua sau
}
// To tien chung gan nhat cua a va b. kInvalidFrame neu hai frame khong noi.
bool CommonAncestor(FrameId a, FrameId b, FrameId* pa, size_t* na, FrameId* pb,
size_t* nb, FrameId* lca) const {
*na = PathToRoot(a, pa);
*nb = PathToRoot(b, pb);
if (*na == 0 || *nb == 0) return false;
for (size_t i = 0; i < *na; ++i) {
for (size_t j = 0; j < *nb; ++j) {
if (pa[i] == pb[j]) {
*lca = pa[i];
*na = i; // so canh phai di tu a len lca
*nb = j;
return true;
}
}
}
return false;
}
// Bien doi canh don parent<-child tai `stamp`, noi suy neu can.
bool EdgeAt(const Edge& e, UnixTime stamp, bool latest, Transform* out,
std::string* err) const {
if (e.is_static) {
*out = e.static_tf;
return true;
}
if (e.filled == 0) {
if (err) *err = "canh chua co mau nao";
return false;
}
const Sample& newest = e.newest();
if (latest) {
*out = newest.tf;
return true;
}
// Ngoai suy ve tuong lai: tu choi neu vuot gioi han.
// tf2 nem ExtrapolationException o day va rat nhieu code goi bat roi bo
// qua im lang; tra false + dien err de goi khong the lo.
if (stamp > newest.stamp) {
const double ahead = SecondsBetween(stamp, newest.stamp);
if (ahead > extrapolation_limit) {
if (err) {
std::ostringstream oss;
oss << "ngoai suy " << ahead << " s vuot gioi han "
<< extrapolation_limit << " s";
*err = oss.str();
}
return false;
}
*out = newest.tf;
return true;
}
const Sample& oldest = e.oldest();
if (stamp < oldest.stamp) {
if (err) {
std::ostringstream oss;
oss << "stamp cu hon lich su " << SecondsBetween(oldest.stamp, stamp) << " s";
*err = oss.str();
}
return false;
}
// Tim hai mau kep stamp. Ring nho (512) va truy van gan dau moi nen quet
// nguoc tu moi nhat nhanh hon tim nhi phan tren bo dem vong.
const size_t n = e.filled;
const size_t base = e.filled < e.ring.size() ? 0 : e.head;
for (size_t k = n; k-- > 1;) {
const Sample& hi = e.at(base + k);
const Sample& lo = e.at(base + k - 1);
if (stamp >= lo.stamp && stamp <= hi.stamp) {
const int64_t span = hi.stamp.toNSec() - lo.stamp.toNSec();
if (span <= 0) {
*out = hi.tf;
return true;
}
const double t =
static_cast<double>(stamp.toNSec() - lo.stamp.toNSec()) /
static_cast<double>(span);
*out = TransformInterpolate(lo.tf, hi.tf, t);
return true;
}
}
*out = newest.tf;
return true;
}
};
// ---------------------------------------------------------------------------
TransformTree::TransformTree(double history_sec, size_t slots_per_edge)
: impl_(std::make_unique<Impl>()) {
impl_->history_sec = history_sec;
impl_->slots_per_edge = slots_per_edge == 0 ? 1 : slots_per_edge;
}
TransformTree::~TransformTree() = default;
FrameId TransformTree::Resolve(const std::string& name) {
std::lock_guard<std::mutex> lk(impl_->mu);
auto it = impl_->name_to_id.find(name);
if (it != impl_->name_to_id.end()) return it->second;
const FrameId id = static_cast<FrameId>(impl_->id_to_name.size());
impl_->id_to_name.push_back(name);
impl_->name_to_id.emplace(name, id);
return id;
}
FrameId TransformTree::Find(const std::string& name) const {
std::lock_guard<std::mutex> lk(impl_->mu);
auto it = impl_->name_to_id.find(name);
return it == impl_->name_to_id.end() ? kInvalidFrame : it->second;
}
const std::string& TransformTree::Name(FrameId id) const {
std::lock_guard<std::mutex> lk(impl_->mu);
if (id >= impl_->id_to_name.size()) return impl_->empty_name;
return impl_->id_to_name[id];
}
size_t TransformTree::frame_count() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->id_to_name.size();
}
StatusResponse TransformTree::SetStatic(FrameId parent, FrameId child,
const Transform& tf) {
std::lock_guard<std::mutex> lk(impl_->mu);
// Kiem vong truoc khi ghi: di tu `parent` len goc, neu gap `child` thi viec
// dat canh nay se tao vong va moi lookup sau do se treo.
FrameId cur = parent;
for (size_t i = 0; i < kMaxDepth; ++i) {
if (cur == child) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"SetStatic tao vong trong cay TF: " + impl_->id_to_name[child]);
}
auto it = impl_->edges.find(cur);
if (it == impl_->edges.end()) break;
cur = it->second.parent;
}
Edge& e = impl_->edges[child];
if (!e.is_static && e.samples > 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"canh " + impl_->id_to_name[child] + " da la canh dong, khong the dat tinh");
}
e.parent = parent;
e.is_static = true;
e.static_tf = tf;
return StatusResponse::Ok();
}
StatusResponse TransformTree::SetStatic(const std::string& parent,
const std::string& child,
const Transform& tf) {
return SetStatic(Resolve(parent), Resolve(child), tf);
}
bool TransformTree::SetTransform(FrameId parent, FrameId child, UnixTime stamp,
const Transform& tf) {
std::lock_guard<std::mutex> lk(impl_->mu);
Edge& e = impl_->edges[child];
if (e.is_static) {
VSLAM_WARN_THROTTLE(5.0, "SetTransform tren canh tinh "
<< impl_->id_to_name[child] << ", bo qua");
return false;
}
if (e.parent != kInvalidFrame && e.parent != parent) {
// Doi cha giua chung la dau hieu hai nguoi cung ghi mot canh -- vi pham
// quy tac "moi canh dung mot nguoi ghi". Bao to, dung im lang.
VSLAM_ERROR_THROTTLE(5.0, "canh " << impl_->id_to_name[child]
<< " doi cha tu " << impl_->id_to_name[e.parent]
<< " sang " << impl_->id_to_name[parent]);
return false;
}
e.parent = parent;
if (e.ring.empty()) e.ring.resize(impl_->slots_per_edge);
if (e.filled > 0 && stamp < e.newest().stamp) {
// Lui thoi gian: ban ghi bi xao tron thu tu, hoac hai nguoi ghi. Noi suy
// tren ring khong con don dieu nua nen moi lookup sau do se sai.
VSLAM_WARN_THROTTLE(5.0, "canh " << impl_->id_to_name[child]
<< ": stamp lui " << e.newest().stamp.toString()
<< " -> " << stamp.toString() << ", bo qua");
return false;
}
e.ring[e.head] = Sample{stamp, tf};
e.head = (e.head + 1) % e.ring.size();
if (e.filled < e.ring.size()) e.filled++;
e.samples++;
e.rate.Tick();
return true;
}
bool TransformTree::Lookup(FrameId target, FrameId source, UnixTime stamp,
Transform* out, std::string* err) const {
std::lock_guard<std::mutex> lk(impl_->mu);
if (target == source) {
*out = TransformIdentity();
return true;
}
FrameId pa[kMaxDepth], pb[kMaxDepth], lca = kInvalidFrame;
size_t na = 0, nb = 0;
if (!impl_->CommonAncestor(source, target, pa, &na, pb, &nb, &lca)) {
if (err) {
*err = "khong co duong noi " + impl_->id_to_name[source] + " -> " +
impl_->id_to_name[target];
}
return false;
}
const bool latest = stamp.isZero();
// source -> lca: ghep xuoi cac canh child->parent.
Transform src_to_lca = TransformIdentity();
for (size_t i = 0; i < na; ++i) {
auto it = impl_->edges.find(pa[i]);
if (it == impl_->edges.end()) break;
Transform e;
if (!impl_->EdgeAt(it->second, stamp, latest, &e, err)) {
if (err) *err = impl_->id_to_name[pa[i]] + ": " + *err;
return false;
}
src_to_lca = TransformCompose(e, src_to_lca);
}
// target -> lca, roi lay nghich dao.
Transform tgt_to_lca = TransformIdentity();
for (size_t i = 0; i < nb; ++i) {
auto it = impl_->edges.find(pb[i]);
if (it == impl_->edges.end()) break;
Transform e;
if (!impl_->EdgeAt(it->second, stamp, latest, &e, err)) {
if (err) *err = impl_->id_to_name[pb[i]] + ": " + *err;
return false;
}
tgt_to_lca = TransformCompose(e, tgt_to_lca);
}
*out = TransformCompose(TransformInverse(tgt_to_lca), src_to_lca);
return true;
}
bool TransformTree::Lookup(const std::string& target, const std::string& source,
UnixTime stamp, Transform* out, std::string* err) const {
const FrameId t = Find(target), s = Find(source);
if (t == kInvalidFrame || s == kInvalidFrame) {
if (err) *err = "frame chua dang ky: " + (t == kInvalidFrame ? target : source);
return false;
}
return Lookup(t, s, stamp, out, err);
}
bool TransformTree::LookupLatest(FrameId target, FrameId source, Transform* out,
std::string* err) const {
return Lookup(target, source, kTimeZero, out, err);
}
UnixTime TransformTree::LatestCommonTime(FrameId a, FrameId b) const {
std::lock_guard<std::mutex> lk(impl_->mu);
FrameId pa[kMaxDepth], pb[kMaxDepth], lca = kInvalidFrame;
size_t na = 0, nb = 0;
if (!impl_->CommonAncestor(a, b, pa, &na, pb, &nb, &lca)) return kTimeZero;
// Thoi diem chung moi nhat = MIN cua cac mau moi nhat tren duong di.
// Canh tinh khong gioi han gi nen bo qua.
UnixTime best = kTimeMax;
bool any_dynamic = false;
auto scan = [&](const FrameId* path, size_t n) {
for (size_t i = 0; i < n; ++i) {
auto it = impl_->edges.find(path[i]);
if (it == impl_->edges.end() || it->second.is_static) continue;
if (it->second.filled == 0) {
best = kTimeZero;
return;
}
any_dynamic = true;
const UnixTime s = it->second.newest().stamp;
if (s < best) best = s;
}
};
scan(pa, na);
if (best.isZero()) return kTimeZero;
scan(pb, nb);
if (!any_dynamic) return kTimeZero; // toan canh tinh: moi luc deu hop le
return best.isZero() ? kTimeZero : best;
}
bool TransformTree::CanTransform(FrameId target, FrameId source,
UnixTime stamp) const {
Transform tmp;
return Lookup(target, source, stamp, &tmp, nullptr);
}
void TransformTree::SetExtrapolationLimit(double sec) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->extrapolation_limit = sec;
}
double TransformTree::extrapolation_limit() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->extrapolation_limit;
}
std::vector<TransformTree::EdgeStatus> TransformTree::EdgeStatuses() const {
std::lock_guard<std::mutex> lk(impl_->mu);
std::vector<EdgeStatus> out;
out.reserve(impl_->edges.size());
for (const auto& kv : impl_->edges) {
EdgeStatus s;
s.child = impl_->id_to_name[kv.first];
s.parent = kv.second.parent < impl_->id_to_name.size()
? impl_->id_to_name[kv.second.parent]
: "?";
s.is_static = kv.second.is_static;
s.samples = kv.second.samples;
s.hz = kv.second.rate.hz();
if (kv.second.filled > 0) s.latest = kv.second.newest().stamp;
out.push_back(std::move(s));
}
std::sort(out.begin(), out.end(),
[](const EdgeStatus& a, const EdgeStatus& b) { return a.child < b.child; });
return out;
}
std::string TransformTree::DumpTree() const {
// Thay rqt_tf_tree. In ra dang cay, danh dau canh tinh/dong kem tan so.
const auto edges = EdgeStatuses();
std::lock_guard<std::mutex> lk(impl_->mu);
std::unordered_map<std::string, std::vector<const EdgeStatus*>> children;
std::vector<std::string> roots;
for (const auto& e : edges) children[e.parent].push_back(&e);
for (const auto& name : impl_->id_to_name) {
if (impl_->edges.find(impl_->name_to_id.at(name)) == impl_->edges.end()) {
roots.push_back(name);
}
}
std::ostringstream oss;
std::function<void(const std::string&, int)> walk = [&](const std::string& node,
int depth) {
oss << std::string(static_cast<size_t>(depth) * 2, ' ') << node;
if (depth > 0) {
for (const auto& e : edges) {
if (e.child != node) continue;
if (e.is_static) {
oss << " [tinh]";
} else {
oss << " [dong " << e.hz << " Hz, " << e.samples << " mau]";
}
break;
}
}
oss << "\n";
auto it = children.find(node);
if (it == children.end()) return;
for (const auto* c : it->second) walk(c->child, depth + 1);
};
for (const auto& r : roots) walk(r, 0);
return oss.str();
}
// --- TfBridge --------------------------------------------------------------
TfBridge::TfBridge(std::string tracking_frame, double lookup_timeout_sec,
std::shared_ptr<const TransformTree> tree)
: tracking_frame_(std::move(tracking_frame)),
lookup_timeout_sec_(lookup_timeout_sec),
tree_(std::move(tree)) {}
bool TfBridge::LookupToTracking(UnixTime time, FrameId frame, Transform* out) const {
const FrameId tracking = tree_->Find(tracking_frame_);
if (tracking == kInvalidFrame) return false;
std::string err;
if (tree_->Lookup(tracking, frame, time, out, &err)) return true;
VSLAM_DEBUG_THROTTLE(2.0, "TfBridge: " << err);
return false;
}
bool TfBridge::LookupToTracking(UnixTime time, const std::string& frame,
Transform* out) const {
const FrameId id = tree_->Find(frame);
if (id == kInvalidFrame) return false;
return LookupToTracking(time, id, out);
}
} // namespace vslam

View File

@@ -0,0 +1,15 @@
#include "vslam/unix_time.h"
#include <cstdio>
namespace vslam {
std::string UnixTime::toString() const {
// In nguyen ven sec.nsec thay vi qua double: double chi co 53 bit mantissa,
// khong du de giu ca 1.7e9 giay lan do phan giai nanosecond.
char buf[32];
std::snprintf(buf, sizeof(buf), "%u.%09u", sec, nsec);
return std::string(buf);
}
} // namespace vslam

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,14 @@
# Odometry banh xe + EKF SE(2).
#
# KHONG them dep ngoai nao: Eigen da den qua vslam_common. Do la co y -- lib
# nay phai build duoc truoc khi co PCL, OpenCV hay RTAB-Map, de P3 chay som.
vslam_add_library(vslam_odometry
PUBLIC_HDRS
wheel_odometry.h
ekf_se2.h
PUBLIC_DEPS
vslam_common
FIND_DEPS
vslam_common
)

View File

@@ -0,0 +1,124 @@
#ifndef VSLAM_EKF_SE2_H
#define VSLAM_EKF_SE2_H
// EKF cho pose SE(2). Thay robot_localization/ekf_localization_node.
//
// ================== VI SAO CHI 5 TRANG THAI ==================
// robot_localization mang 15 trang thai. Cau hinh that trong ekf_odom.yaml
// dat two_d_mode=true (khoa z/roll/pitch va dao ham cua chung) va chi bat
// DUNG BA phep do:
// odom0 -> vx (chi so 6), vyaw (chi so 11)
// imu0 -> vyaw (chi so 11)
// Nghia la 10/15 trang thai khong bao gio duoc quan sat va chi bi mang theo.
//
// O day giu dung 5 trang thai co that: [x, y, yaw, vx, vyaw].
//
// ================== HAI QUYET DINH BE NGUYEN TU BAN CU ==================
//
// 1. FUSE VAN TOC, KHONG FUSE POSE TUYET DOI.
// Tich phan pose hai lan trong filter (mot lan o wheel_odom, mot lan nua
// trong EKF) lam sai so cong don nhanh hon han. wheel_odom van xuat pose
// de hien thi, nhung EKF chi an twist.
//
// 2. KHONG FUSE GIA TOC TUYEN TINH tu IMU.
// Tren robot banh, accel nhieu manh do rung (san gach + banh cung) va co
// bias troi. Dua vao thuong lam ket qua TE HON chu khong tot hon. Chi lay
// gyro Z.
//
// ================== Z, ROLL, PITCH DI DAU ==================
// Pose la SE(2): z gia dinh 0, roll/pitch duoc DO tu IMU chu khong bao gio
// uoc luong. Chung khong nam trong filter nay. GravityAlign lo phan do.
#include <cstdint>
#include <memory>
#include <string>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct EkfSe2Config {
double rate_hz = 50.0;
// Khong nhan phep do nao trong bao lau thi coi la khong lanh manh.
double sensor_timeout = 0.2;
// Nhieu qua trinh, duong cheo. Lay tu process_noise_covariance cua
// ekf_odom.yaml tai cac chi so tuong ung:
// x=0 y=1 yaw=5 vx=6 vyaw=11
// MOI gia tri o day la doan tu datasheet, cho hieu chuan that. Dung tin
// chung nhu so do.
double q_x = 0.05;
double q_y = 0.05;
double q_yaw = 0.06;
double q_vx = 0.025;
double q_vyaw = 0.02;
// Hiep phuong sai ban dau.
double p0_pose = 1e-3;
double p0_vel = 1e-2;
// Bo phep do lech qua nhieu so voi du doan (kiem Mahalanobis).
// 0 = tat. Gia tri ~5 nghia la bo diem lech qua 5 sigma.
//
// Bat cai nay chi an toan KHI covariance dau vao dung. Voi bug yaw-rate cu
// (thieu 2 bac, xem wheel_odometry.cc) thi moi phep do deu trong nhu 11
// sigma va cong nay se bo HET -- nen mac dinh la TAT.
double mahalanobis_threshold = 0.0;
};
struct EkfSe2Stats {
uint64_t predicts = 0;
uint64_t odom_updates = 0;
uint64_t imu_updates = 0;
uint64_t rejected_outliers = 0;
uint64_t time_resets = 0;
double last_mahalanobis = 0.0;
};
class EkfSe2 {
public:
explicit EkfSe2(EkfSe2Config cfg = EkfSe2Config());
~EkfSe2();
EkfSe2(const EkfSe2&) = delete;
EkfSe2& operator=(const EkfSe2&) = delete;
// Day trang thai toi `now`. An toan goi nhieu lan.
void Predict(UnixTime now);
// Van toc tu encoder. `var_*` lay tu twist.covariance cua Odometry --
// day chinh la cho wheel_odom bao "dang truot, dung tin toi".
void UpdateOdomTwist(UnixTime stamp, double vx, double vyaw, double var_vx,
double var_vyaw);
// Van toc goc tu gyro Z.
void UpdateImuYawRate(UnixTime stamp, double vyaw, double var);
Pose2D pose() const;
double vx() const;
double vyaw() const;
// Odometry day du, gom ca covariance -- de xuat ra web va cho SLAM.
Odometry State(const std::string& odom_frame, const std::string& base_frame) const;
// Canh odom -> base_footprint. EkfSe2 la NGUOI GHI DUY NHAT cua canh nay.
Transform OdomToBase() const;
// false neu chua nhan phep do nao trong `sensor_timeout`.
bool Healthy(UnixTime now) const;
void SetPose(const Pose2D& p);
void Reset();
EkfSe2Stats stats() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace vslam
#endif // VSLAM_EKF_SE2_H

View File

@@ -0,0 +1,113 @@
#ifndef VSLAM_WHEEL_ODOMETRY_H
#define VSLAM_WHEEL_ODOMETRY_H
// Odometry banh xe + phat hien truot.
//
// Port tu robot_drivers/src/wheel_odom_node.cpp cua vSLAM_ws.
// TOAN BO mo hinh covariance duoc BE NGUYEN: no da duoc chinh bang so do thuc
// tren robot that, va cac con so trong comment o wheel_odometry.cc la do
// duoc chu khong phai doan.
//
// ================== VI SAO CAN PHAT HIEN TRUOT ==================
// San nha hang co nuoc va dau mo. Banh truot thi encoder NOI DOI: no bao robot
// da di, thuc te robot dung yen hoac truot ngang.
//
// Gyro Z khong bi anh huong boi truot banh. So hai nguon:
// omega_encoder = (v_phai - v_trai) / wheel_separation
// omega_gyro = imu.angular_velocity.z
// Lech nhieu => dang truot => NANG covariance de back-end tu dong tin encoder
// it di. Khong vut bo du lieu, chi ha do tin cay.
//
// ================== KHONG PHAT TF ==================
// Lop nay KHONG ghi canh odom->base_footprint. Viec do la cua EkfSe2, noi
// encoder va IMU duoc fuse dung cach. Moi canh TF co dung mot nguoi ghi.
#include <cstdint>
#include <string>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct WheelOdometryConfig {
// Hinh hoc. PHAI khop robot.yaml -- day la gia tri duy nhat, khong con ban
// sao trong URDF nua.
double wheel_radius = 0.075;
double wheel_separation = 0.36;
// Truot: lech omega vuot nguong nay thi coi la dang truot.
double slip_omega_threshold = 0.15;
double slip_cov_multiplier = 100.0;
// IMU cu hon nguong nay thi coi nhu khong co gyro.
double imu_timeout = 0.5;
// Sigma co ban, nhan voi QUANG DUONG (khong phai thoi gian).
double sigma_x = 0.02;
double sigma_y = 0.02;
double sigma_yaw = 0.02;
// Xem khoi comment lon trong wheel_odometry.cc -- hai gia tri nay la ket
// qua cua mot bug da do duoc, khong phai tham so tuy chinh.
double yaw_rate_sigma_floor = 0.02;
double yaw_rate_sigma_no_imu = 0.50;
std::string odom_frame = "odom";
std::string base_frame = "base_footprint";
};
struct WheelOdometryStats {
uint64_t updates = 0;
uint64_t slip_events = 0;
uint64_t time_resets = 0; // dt <= 0: reset sim hoac replay nhay lui
uint64_t no_imu_updates = 0; // chay "mu", khong phat hien duoc truot
double last_slip_metric = 0.0;
double total_distance = 0.0;
};
class WheelOdometry {
public:
explicit WheelOdometry(WheelOdometryConfig cfg);
// Gyro Z tu IMU. Goi truoc Update() de phat hien truot hoat dong.
void FeedGyroZ(UnixTime stamp, double wz);
// left_rad / right_rad: goc quay TICH LUY cua tung banh.
//
// Tra false khi chua du du lieu de tich phan (mau dau tien, hoac dt <= 0).
// Khi do `out` khong duoc ghi.
bool Update(UnixTime stamp, double left_rad, double right_rad, Odometry* out);
// |omega_encoder - gyro_z| cua lan cap nhat gan nhat.
double slip_metric() const { return slip_metric_; }
bool slipping() const { return slipping_; }
Pose2D pose() const { return Pose2D{x_, y_, theta_}; }
void SetPose(const Pose2D& p);
void Reset();
const WheelOdometryStats& stats() const { return stats_; }
private:
WheelOdometryConfig cfg_;
bool initialized_ = false;
double prev_pos_l_ = 0.0, prev_pos_r_ = 0.0;
UnixTime prev_time_;
double x_ = 0.0, y_ = 0.0, theta_ = 0.0;
bool have_imu_ = false;
double gyro_z_ = 0.0;
UnixTime last_imu_time_;
double slip_metric_ = 0.0;
bool slipping_ = false;
WheelOdometryStats stats_;
};
} // namespace vslam
#endif // VSLAM_WHEEL_ODOMETRY_H

View File

@@ -0,0 +1,255 @@
#include "vslam/ekf_se2.h"
#include <Eigen/Cholesky>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <cmath>
#include <mutex>
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
namespace {
// Chi so trang thai: [x, y, yaw, vx, vyaw]
constexpr int kX = 0, kY = 1, kYaw = 2, kVx = 3, kVyaw = 4, kN = 5;
using Vec5 = Eigen::Matrix<double, kN, 1>;
using Mat5 = Eigen::Matrix<double, kN, kN>;
} // namespace
struct EkfSe2::Impl {
EkfSe2Config cfg;
mutable std::mutex mu;
Vec5 x = Vec5::Zero();
Mat5 P = Mat5::Identity();
Mat5 Q = Mat5::Zero();
bool have_time = false;
UnixTime last_predict;
UnixTime last_measurement;
EkfSe2Stats stats;
explicit Impl(EkfSe2Config c) : cfg(std::move(c)) {
Q(kX, kX) = cfg.q_x;
Q(kY, kY) = cfg.q_y;
Q(kYaw, kYaw) = cfg.q_yaw;
Q(kVx, kVx) = cfg.q_vx;
Q(kVyaw, kVyaw) = cfg.q_vyaw;
P = Mat5::Zero();
P(kX, kX) = P(kY, kY) = P(kYaw, kYaw) = cfg.p0_pose;
P(kVx, kVx) = P(kVyaw, kVyaw) = cfg.p0_vel;
}
// Goi khi da giu mu.
void PredictLocked(double dt) {
if (dt <= 0.0) return;
const double yaw = x(kYaw);
const double vx = x(kVx);
const double c = std::cos(yaw), s = std::sin(yaw);
// Mo hinh van toc khong doi trong he than robot.
// x' = x + vx*cos(yaw)*dt
// y' = y + vx*sin(yaw)*dt
// yaw' = yaw + vyaw*dt
// vx' = vx
// vyaw' = vyaw
//
// KHONG co vy: robot vi sai khong truot ngang duoc. Do la ly do
// odom0_config dat vy = false trong ban cu.
x(kX) += vx * c * dt;
x(kY) += vx * s * dt;
x(kYaw) = NormalizeAngle(x(kYaw) + x(kVyaw) * dt);
Mat5 F = Mat5::Identity();
F(kX, kYaw) = -vx * s * dt;
F(kX, kVx) = c * dt;
F(kY, kYaw) = vx * c * dt;
F(kY, kVx) = s * dt;
F(kYaw, kVyaw) = dt;
// Nhieu qua trinh ty le voi dt: bo qua dt se lam filter qua tu tin khi
// chay o tan so cao va qua bao thu khi chay cham.
P = F * P * F.transpose() + Q * dt;
stats.predicts++;
}
// Cap nhat vo huong. Tra false neu bi bo vi lech qua nhieu.
bool UpdateScalarLocked(int state_idx, double z, double var) {
if (!(var > 0.0) || !std::isfinite(z)) return false;
Eigen::Matrix<double, 1, kN> H = Eigen::Matrix<double, 1, kN>::Zero();
H(0, state_idx) = 1.0;
const double y = z - x(state_idx); // phan du
const double S = (H * P * H.transpose())(0, 0) + var;
if (!(S > 0.0)) return false;
const double mahalanobis = std::sqrt(y * y / S);
stats.last_mahalanobis = mahalanobis;
if (cfg.mahalanobis_threshold > 0.0 &&
mahalanobis > cfg.mahalanobis_threshold) {
stats.rejected_outliers++;
VSLAM_WARN_THROTTLE(2.0, "ekf: bo phep do lech " << mahalanobis
<< " sigma o trang thai "
<< state_idx);
return false;
}
const Vec5 K = P * H.transpose() / S;
x += K * y;
x(kYaw) = NormalizeAngle(x(kYaw));
// Dang Joseph: giu P doi xung xac dinh duong ke ca khi co sai so lam tron.
// Dang don gian (I-KH)P mat tinh chat do sau vai nghin buoc, va khi P mat
// xac dinh duong thi filter phan ky ma khong co dau hieu gi.
const Mat5 IKH = Mat5::Identity() - K * H;
P = IKH * P * IKH.transpose() + K * var * K.transpose();
return true;
}
};
EkfSe2::EkfSe2(EkfSe2Config cfg) : impl_(std::make_unique<Impl>(std::move(cfg))) {}
EkfSe2::~EkfSe2() = default;
void EkfSe2::Predict(UnixTime now) {
std::lock_guard<std::mutex> lk(impl_->mu);
if (!impl_->have_time) {
impl_->last_predict = now;
impl_->have_time = true;
return;
}
const double dt = SecondsBetween(now, impl_->last_predict);
if (dt < 0.0) {
// Thoi gian lui: reset mo phong hoac phat lai ban ghi.
VSLAM_WARN("ekf: thoi gian lui " << dt << " s -- reset moc thoi gian");
impl_->last_predict = now;
impl_->stats.time_resets++;
return;
}
impl_->PredictLocked(dt);
impl_->last_predict = now;
}
void EkfSe2::UpdateOdomTwist(UnixTime stamp, double vx, double vyaw,
double var_vx, double var_vyaw) {
Predict(stamp);
std::lock_guard<std::mutex> lk(impl_->mu);
// var_* den tu twist.covariance cua wheel_odom -- day chinh la cho no bao
// "dang truot, dung tin toi".
const bool a = impl_->UpdateScalarLocked(kVx, vx, var_vx);
const bool b = impl_->UpdateScalarLocked(kVyaw, vyaw, var_vyaw);
if (a || b) {
impl_->stats.odom_updates++;
impl_->last_measurement = stamp;
}
}
void EkfSe2::UpdateImuYawRate(UnixTime stamp, double vyaw, double var) {
Predict(stamp);
std::lock_guard<std::mutex> lk(impl_->mu);
if (impl_->UpdateScalarLocked(kVyaw, vyaw, var)) {
impl_->stats.imu_updates++;
impl_->last_measurement = stamp;
}
}
Pose2D EkfSe2::pose() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return Pose2D{impl_->x(kX), impl_->x(kY), impl_->x(kYaw)};
}
double EkfSe2::vx() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->x(kVx);
}
double EkfSe2::vyaw() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->x(kVyaw);
}
Odometry EkfSe2::State(const std::string& odom_frame,
const std::string& base_frame) const {
std::lock_guard<std::mutex> lk(impl_->mu);
Odometry o;
o.header.stamp = impl_->last_predict;
o.header.frame_id = odom_frame;
o.child_frame_id = base_frame;
o.pose.pose.position.x = impl_->x(kX);
o.pose.pose.position.y = impl_->x(kY);
o.pose.pose.position.z = 0.0;
o.pose.pose.orientation = QuaternionFromYaw(impl_->x(kYaw));
for (int i = 0; i < 36; ++i) o.pose.covariance[i] = 0.0;
o.pose.covariance[0] = impl_->P(kX, kX);
o.pose.covariance[1] = impl_->P(kX, kY);
o.pose.covariance[6] = impl_->P(kY, kX);
o.pose.covariance[7] = impl_->P(kY, kY);
o.pose.covariance[14] = 1e6; // z khong quan sat duoc
o.pose.covariance[21] = 1e6; // roll -> do tu IMU, khong uoc luong
o.pose.covariance[28] = 1e6; // pitch -> do tu IMU, khong uoc luong
o.pose.covariance[35] = impl_->P(kYaw, kYaw);
o.twist.twist.linear.x = impl_->x(kVx);
o.twist.twist.angular.z = impl_->x(kVyaw);
for (int i = 0; i < 36; ++i) o.twist.covariance[i] = 0.0;
o.twist.covariance[0] = impl_->P(kVx, kVx);
o.twist.covariance[14] = 1e6;
o.twist.covariance[21] = 1e6;
o.twist.covariance[28] = 1e6;
o.twist.covariance[35] = impl_->P(kVyaw, kVyaw);
return o;
}
Transform EkfSe2::OdomToBase() const {
std::lock_guard<std::mutex> lk(impl_->mu);
Transform t;
t.translation = Vector3{impl_->x(kX), impl_->x(kY), 0.0};
t.rotation = QuaternionFromYaw(impl_->x(kYaw));
return t;
}
bool EkfSe2::Healthy(UnixTime now) const {
std::lock_guard<std::mutex> lk(impl_->mu);
if (impl_->last_measurement.isZero()) return false;
return SecondsBetween(now, impl_->last_measurement) < impl_->cfg.sensor_timeout;
}
void EkfSe2::SetPose(const Pose2D& p) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->x(kX) = p.x;
impl_->x(kY) = p.y;
impl_->x(kYaw) = NormalizeAngle(p.theta);
// Dat lai pose = biet chac vi tri -> ha hiep phuong sai pose ve gia tri dau.
// Van toc KHONG dat lai: robot co the dang chay khi bi dat lai pose.
impl_->P(kX, kX) = impl_->P(kY, kY) = impl_->P(kYaw, kYaw) = impl_->cfg.p0_pose;
impl_->P(kX, kY) = impl_->P(kY, kX) = 0.0;
}
void EkfSe2::Reset() {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->x = Vec5::Zero();
impl_->P = Mat5::Zero();
impl_->P(kX, kX) = impl_->P(kY, kY) = impl_->P(kYaw, kYaw) = impl_->cfg.p0_pose;
impl_->P(kVx, kVx) = impl_->P(kVyaw, kVyaw) = impl_->cfg.p0_vel;
impl_->have_time = false;
impl_->last_measurement = UnixTime();
impl_->stats = EkfSe2Stats{};
}
EkfSe2Stats EkfSe2::stats() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->stats;
}
} // namespace vslam

View File

@@ -0,0 +1,177 @@
#include "vslam/wheel_odometry.h"
#include <algorithm>
#include <cmath>
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
WheelOdometry::WheelOdometry(WheelOdometryConfig cfg) : cfg_(std::move(cfg)) {}
void WheelOdometry::FeedGyroZ(UnixTime stamp, double wz) {
gyro_z_ = wz;
last_imu_time_ = stamp;
have_imu_ = true;
}
void WheelOdometry::SetPose(const Pose2D& p) {
x_ = p.x;
y_ = p.y;
theta_ = NormalizeAngle(p.theta);
}
void WheelOdometry::Reset() {
initialized_ = false;
x_ = y_ = theta_ = 0.0;
slip_metric_ = 0.0;
slipping_ = false;
stats_ = WheelOdometryStats{};
}
bool WheelOdometry::Update(UnixTime stamp, double pos_l, double pos_r,
Odometry* out) {
if (!initialized_) {
prev_pos_l_ = pos_l;
prev_pos_r_ = pos_r;
prev_time_ = stamp;
initialized_ = true;
VSLAM_INFO("wheel_odom: da nhan encoder dau tien, bat dau tich phan");
return false;
}
const double dt = SecondsBetween(stamp, prev_time_);
if (dt <= 0.0) {
// Nhay lui thoi gian: xay ra khi reset mo phong hoac phat lai ban ghi.
// Reset trang thai thay vi tich phan mot dt am -- tich phan dt am se day
// pose di GIAT LUI, va EKF phia sau khong co cach nao biet.
VSLAM_WARN("wheel_odom: dt <= 0 (" << dt << " s) -- reset trang thai tich phan");
prev_pos_l_ = pos_l;
prev_pos_r_ = pos_r;
prev_time_ = stamp;
stats_.time_resets++;
return false;
}
// Quang duong tung banh. Chuan hoa DELTA de an toan voi ca hai kieu bao cao
// vi tri: tich luy khong gioi han, hoac cuon ve [-pi, pi].
const double d_l = NormalizeAngle(pos_l - prev_pos_l_) * cfg_.wheel_radius;
const double d_r = NormalizeAngle(pos_r - prev_pos_r_) * cfg_.wheel_radius;
const double d_center = 0.5 * (d_l + d_r);
const double d_theta = (d_r - d_l) / cfg_.wheel_separation;
// --------- Phat hien truot ---------
const double omega_encoder = d_theta / dt;
slip_metric_ = 0.0;
slipping_ = false;
const bool imu_fresh =
have_imu_ && (SecondsBetween(stamp, last_imu_time_) < cfg_.imu_timeout);
if (imu_fresh) {
slip_metric_ = std::fabs(omega_encoder - gyro_z_);
slipping_ = slip_metric_ > cfg_.slip_omega_threshold;
if (slipping_) {
stats_.slip_events++;
VSLAM_WARN_THROTTLE(2.0, "wheel_odom: nghi TRUOT BANH -- omega encoder "
<< omega_encoder << " vs gyro " << gyro_z_
<< " rad/s (lech " << slip_metric_
<< "). Nang covariance.");
}
} else {
stats_.no_imu_updates++;
VSLAM_WARN_THROTTLE(10.0,
"wheel_odom: khong co IMU moi -> KHONG phat hien duoc "
"truot banh. Odometry dang chay 'mu'.");
}
// --------- Tich phan Runge-Kutta bac 2 ---------
// Dung goc GIUA doan thay vi goc dau doan. Voi mot robot xoay 0.8 rad/s va
// chu ky 20 ms, khac biet giua hai cach la ~0.008 rad moi buoc -- nho, nhung
// no tich luy theo mot chieu va thanh troi yaw sau vai phut.
const double theta_mid = theta_ + 0.5 * d_theta;
x_ += d_center * std::cos(theta_mid);
y_ += d_center * std::sin(theta_mid);
theta_ = NormalizeAngle(theta_ + d_theta);
stats_.updates++;
stats_.total_distance += std::fabs(d_center);
stats_.last_slip_metric = slip_metric_;
// --------- Dong goi ---------
out->header.stamp = stamp;
out->header.frame_id = cfg_.odom_frame;
out->child_frame_id = cfg_.base_frame;
out->pose.pose.position.x = x_;
out->pose.pose.position.y = y_;
out->pose.pose.position.z = 0.0; // 2.5D: robot o tren mat phang
out->pose.pose.orientation = QuaternionFromYaw(theta_);
out->twist.twist.linear.x = d_center / dt;
out->twist.twist.angular.z = omega_encoder;
// Covariance ty le voi QUANG DUONG, khong phai thoi gian: sai so odometry
// tich luy theo quang duong di duoc. Mot robot dung yen khong tich them sai
// so, du dung bao lau.
const double mult = slipping_ ? cfg_.slip_cov_multiplier : 1.0;
const double travel = std::max(std::fabs(d_center), 1e-4);
const double turn = std::max(std::fabs(d_theta), 1e-4);
const double cov_x = std::pow(cfg_.sigma_x * travel, 2) * mult;
const double cov_y = std::pow(cfg_.sigma_y * travel, 2) * mult;
const double cov_yaw = std::pow(cfg_.sigma_yaw * turn, 2) * mult;
// Chi so: 0=x, 7=y, 14=z, 21=roll, 28=pitch, 35=yaw
for (int i = 0; i < 36; ++i) out->pose.covariance[i] = 0.0;
out->pose.covariance[0] = cov_x;
out->pose.covariance[7] = cov_y;
out->pose.covariance[14] = 1e6; // z khong quan sat duoc
out->pose.covariance[21] = 1e6; // roll -> IMU lo
out->pose.covariance[28] = 1e6; // pitch -> IMU lo
out->pose.covariance[35] = cov_yaw;
for (int i = 0; i < 36; ++i) out->twist.covariance[i] = 0.0;
out->twist.covariance[0] = cov_x / (dt * dt);
out->twist.covariance[7] = cov_y / (dt * dt);
out->twist.covariance[14] = 1e6;
out->twist.covariance[21] = 1e6;
out->twist.covariance[28] = 1e6;
// ======================================================================
// YAW-RATE: KHAI BAO DO BAT DINH DA DO, KHONG PHAI DOAN
//
// Khac cac thanh phan o tren: chung dung cov ty le quang duong roi nhan mot
// he so co dinh khi truot. Yaw-rate thi KHONG.
//
// Ly do: slip_metric = |omega_encoder - gyro_z| CHINH LA sai so cua phep do
// banh xe, do duoc tung chu ky. Lay no lam sigma la khai bao do bat dinh DA
// DO, thay vi mot he so doan truoc.
//
// Cach cu (cov_yaw/dt^2 voi he so co dinh 100) THIEU ~2 BAC. Da do khi robot
// xoay tai cho tren robot that:
// sai so that : omega encoder -3.635 vs gyro -1.377 = 2.26 rad/s
// sigma khai bao: (0.02*0.02)^2 * 100 / 0.02^2 = 0.04 -> 0.2 rad/s
// EKF nhan mot diem 11-sigma ma van tin -> yaw troi.
//
// Hau qua da do o tang tren: global_scan_init ghep scan bang odom, nen sau
// khi xoay 301 do no khop ra HUONG SAI 40.8 do (vi tri van dung 0.17 m).
// Khong xoay thi huong DUNG -- vi khong tich luy sai so odom nao.
//
// San khi KHONG co gyro: luc do slip_metric = 0, va neu dung thang thi
// sigma = 0 -> EKF tin banh xe TUYET DOI, te hon ca truoc khi sua. Vi vay
// co yaw_rate_sigma_no_imu.
// ======================================================================
const double sigma_wr = imu_fresh
? std::max(slip_metric_, cfg_.yaw_rate_sigma_floor)
: cfg_.yaw_rate_sigma_no_imu;
out->twist.covariance[35] = sigma_wr * sigma_wr;
prev_pos_l_ = pos_l;
prev_pos_r_ = pos_r;
prev_time_ = stamp;
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,26 @@
# Co y KHONG phu thuoc PCL.
#
# Ban ROS dung pcl::PassThrough + pcl::VoxelGrid + pcl::StatisticalOutlier.
# Ba cai do cong lai ~100 dong thuat toan da biet ro. Doi lai:
# - lib nay build va test duoc tren may KHONG co PCL (cung ly do voi
# vslam_odometry);
# - khong dinh bay -march=native/-msse4.2 ma PCL bom vao, thu vo hieu thang
# tren arm64 (xem vslam_link_pcl trong cmake/vslam_helpers.cmake);
# - VoxelGrid tu viet dung khoa int64 3x21-bit, khong co gioi han
# 2^31 diem cua pcl::VoxelGrid.
#
# PCL chi con can o vslam_slam, noi RTAB-Map da keo no vao san.
vslam_add_library(vslam_perception
PUBLIC_HDRS
perception_types.h
depth_to_cloud.h
depth_filter.h
gravity_align.h
cliff_detect.h
perception_pipeline.h
FIND_DEPS
vslam_common
)
target_link_libraries(vslam_perception PUBLIC vslam_common)

View File

@@ -0,0 +1,223 @@
#ifndef VSLAM_CLIFF_DETECT_H
#define VSLAM_CLIFF_DETECT_H
// Phat hien vuc / bac thang xuong bang anh DEPTH.
//
// Port tu perception_3d/src/cliff_detect_nodelet.cpp (~450 dong, doan thuat
// toan day nhat cua repo cu).
//
// ============ VI SAO CHAY TREN ANH DEPTH CHU KHONG PHAI POINT CLOUD ============
// 1. Bac thang TOI tra ve LO (NaN / 0), khong tra ve diem thap.
// pcl::PassThrough loai NaN => chinh cai tin hieu can tim bi xoa sach.
// Tren anh depth, mot pixel le ra phai thay san ma khong co so do LA bang
// chung cua vuc.
// 2. Tia biet minh di huong nao. Voi moi pixel tinh duoc "san LE RA phai o
// depth bao nhieu" (giao tia voi mat phang san). Cloud da mat thong tin do.
// 3. Danh dau tai P_floor = giao tia voi mat san, tuc la MEP vuc, chu khong
// phai tai diem tra ve (nam sau duoi day vuc, hoac khong ton tai).
//
// ============ VUNG MU 0 - 1.1 m ============
// Camera cao 0.803 m nghieng xuong: tia cham san gan nhat o ~1.07 m. Duoi
// nguong do khong tia nao cham san, detector khong the biet gi. Do la ly do
// min_dist mac dinh 1.10 m, va la ly do BAT BUOC phai co cam bien khac (cliff
// IR / bumper) cho vung gan.
#include <cstdint>
#include <string>
#include <vector>
#include "vslam/perception_types.h"
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct CliffDetectConfig {
bool enabled = true;
// Cua so xet, tinh theo ban kinh tren mat san (m). Duoi min_dist la vung mu
// hinh hoc, khong phai lua chon tuy y.
double min_dist = 1.10;
double max_dist = 2.50;
// Be mat phai thap hon san tham chieu bao nhieu moi tinh la vuc (m).
double cliff_margin = 0.05;
// Sai so pitch con lai sau tu hieu chuan. Nguong no ra theo tam:
// thr = z_ref - (cliff_margin + r * tan(pitch_uncertainty))
double pitch_uncertainty_deg = 2.0;
int pixel_step = 4; // lay mau thua: 1/16 so pixel
int min_neighbors = 3; // trong 8 lang gieng, de loai pixel le
int min_cluster = 12; // so diem toi thieu de bao vuc
double imu_timeout = 0.5;
// Bail khi gravity_align dang khong neo duoc vao trong luc. Pitch luc do la
// gyro thuan va dang troi -> hinh hoc cat tia x san khong dung tin.
bool require_accel_ok = true;
// --- Tu hieu chuan mat san ---
bool self_level = true;
int min_level_samples = 40;
// Cong nay loai CA vat the (mat ban 0.7 m) LAN vuc that (z ~ -1 m) khoi phep
// khop. Nho ve thu hai ma khop duoc tren TOAN cua so ma khong nuot mat chinh
// cai vuc dang can tim.
double level_gate = 0.25;
// Doc vuot tran = dau hieu phep khop hong, KHONG phai san doc that. Ramp la
// san doc THAT va robot phai di duoc -- cong phan biet ramp/vuc la MAD.
double max_level_slope = 0.20;
double max_level_residual = 0.05;
// Mat phang san khop duoc, NGOAI SUY ve r = 0, phai di qua chinh cho robot
// dang dung -- vi robot DANG DUNG TREN no. Mot phep khop noi "san duoi banh
// xe toi thap hon 25 cm" la mot menh de vat ly sai, khong phai mot nguong
// can chinh.
//
// Day la cong bat duoc kieu hong ma `max_obstructed_frac` KHONG bat duoc:
// hanh lang 2.5-3.0 m, tuong cach 1.25-1.5 m. Chi ~9% tia tra ve diem cao
// hon level_gate (xa cong 0.60), nhung diem tuong o r lon van lot cong va
// KEO DOC duong khop len +0.19 -- vua du duoi tran max_level_slope 0.20.
// Sau do san THAT o r ~ 2 m bi do voi z_ref = +0.13 -> roi duoi nguong ->
// vuc gia. Do duoc: 6/210 khung o be rong 3.0 m.
//
// Vi sao KHONG ha max_level_slope thay vi the: 0.20 duoc chon de HAP THU
// dao dong pitch +-8.5 do do duoc tren robot that; ha xuong se vo hieu hoa
// co che bu va tat phat hien vuc khi robot dang chay. Xem ghi chu trong
// depth_filter.yaml cua repo cu.
//
// Vi sao 0.15: sai so cua z_ref(0) chi den tu sai so pitch va sai so chieu
// cao camera, ma ca hai deu da bi chan boi max_tz_dev = 0.08. Mot ramp that
// 8% bat dau o 1.5 m cho z0 = -0.096 -- van lot.
double max_level_offset = 0.15;
// Camera lech khoi chieu cao danh dinh => robot dang nghieng / da nhoai len
// vat gi do. Luc do phep khop mat san se bam theo TANG DUOI va bao "khong co
// vuc" -- nguy hiem hon la im lang.
// ⚠️ PHAI dat tu `RobotModel::camera_height_above_floor()`, khong go tay.
// No la camera_link.z CONG wheel_radius -- mot he qua, khong phai mot so
// doc lap. Mac dinh 0.803 o day tung LECH voi 0.80 ma bo mo phong dung, va
// khong co gi bao. Gio mac dinh khop, nhung van phai dat tu RobotModel vi
// robot.yaml moi la nguon.
double nominal_tz = 0.80;
double max_tz_dev = 0.08;
// Ti le toi da tia trong cua so duoc phep tra ve diem CAO hon level_gate
// truoc khi coi nhu "dang nhin vao vat can, khong nhin thay san".
//
// KHONG co trong ban ROS goc, va no bit mot lo hong THAT cua ban do.
// Trong hanh lang hep hon 2 x min_dist, tuong nam GAN HON vung mu 1.10 m:
// hau het tia dap vao tuong chu khong toi san. Mot so it diem tuong co
// z < level_gate van duoc nhan vao phep khop, va mat san tham chieu bi keo
// LEN theo chung. Sau do san THAT o xa hon bi do voi mat phang bi keo len
// do -> roi duoi nguong -> BAO VUC GIA giua hanh lang phang.
//
// Do duoc trong mo phong (hanh lang 1.6 m, robot quay tai cho): z0 khop
// thanh +0.24 m, MAD chi 0.046 nen lot ca cong MAD, roi 46 tia san that
// roi duoi nguong. Hong kieu nay la hong KHONG AN TOAN -- no bao CO vuc
// chu khong bao "khong biet".
//
// Vi sao dem diem CAO chu khong phai be rong dai mau: be rong la proxy yeu
// (da do: dai mau van trai 50% cua so ma van bao gia). Con dem diem cao thi
// KHONG BAO GIO che duoc vuc that: vuc lam diem THAP hoac MAT HAN, khong
// bao gio lam diem cao. Cong nay chi co the bien "co vuc" thanh "khong
// biet", khong bao gio bien thanh "khong co vuc".
double max_obstructed_frac = 0.60;
bool fail_safe = true;
double fail_safe_after = 1.0; // mu LIEN TUC bao lau thi bao nguy
double wheel_radius = 0.075;
};
// Vi sao khung nay khong phan xet duoc. Gia tri duoc dua ra ngoai de web UI
// hien duoc -- bao "khong biet" khac han bao "khong co vuc".
enum class CliffBail : uint8_t {
kNone = 0,
kDisabled,
kNoRollPitch,
kAccelGated, // robot dang tang/giam toc
kBadGeometry, // tz <= 0
kTzDeviation, // robot khong bang phang
kFewSamples, // khong du mau san de khop
kSlopeClamped, // doc cham tran -> khop hong
kResidualLarge, // MAD lon -> khung nhin khong phai mot mat phang
kBadEncoding,
kObstructed, // phan lon tia dap vao vat can, khong thay san
kOffsetLarge, // mat phang khop duoc khong di qua cho robot dang dung
};
const char* CliffBailName(CliffBail b);
struct CliffResult {
bool detected = false;
bool judged = false; // false = khong phan xet duoc (bail)
CliffBail bail = CliffBail::kNone;
double bail_held = 0.0; // da mu lien tuc bao lau (s)
// Mep vuc trong base_footprint. z giu AM co y (xem ghi chu trong .cc).
PointCloudXYZ edge_cloud;
// Chan doan -- lam nen cho khoi debug throttle cua ban ROS.
int64_t n_total = 0, n_up = 0, n_zneg = 0, n_range = 0, n_inwin = 0;
int64_t n_hole = 0, n_drop = 0;
int n_cliff = 0;
double r_min = 0.0, r_max = 0.0, z_lowest = 0.0;
double lvl_z0 = 0.0, lvl_slope = 0.0, lvl_slope_raw = 0.0, lvl_mad = 0.0;
int64_t lvl_samples = 0; // so mau vao phep khop mat san
int64_t lvl_high = 0; // tia trong cua so tra ve diem CAO hon level_gate
int64_t lvl_window = 0; // tong tia trong cua so o luot do muc san
double lvl_r_lo = 0.0; // ban kinh nho nhat / lon nhat trong so mau do
double lvl_r_hi = 0.0;
bool leveled = false;
double tz = 0.0;
};
struct CliffDetectStats {
uint64_t frames = 0;
uint64_t judged = 0;
uint64_t detected = 0;
uint64_t bailed = 0;
uint64_t bail_by[12] = {0};
};
class CliffDetect {
public:
explicit CliffDetect(CliffDetectConfig cfg);
// roll/pitch tu GravityAlign. accel_ok = bo loc co dang neo duoc vao trong
// luc khong, hay chi dang tich phan gyro.
void SetTilt(UnixTime stamp, double roll, double pitch, bool accel_ok);
// `cam_to_base` la phep bien doi TINH camera -> base_link (tu robot.yaml);
// nghieng do duoc se duoc ap them, giong het GravityAlign.
CliffResult Process(const Image& depth, const CameraInfo& info,
const Transform& cam_to_base, UnixTime now);
void Reset();
const CliffDetectStats& stats() const { return stats_; }
private:
CliffResult Bail(CliffBail why, bool immediate, UnixTime now);
CliffDetectConfig cfg_;
bool have_rp_ = false;
double roll_ = 0.0, pitch_ = 0.0;
bool accel_ok_ = true;
UnixTime last_rp_;
bool bailing_ = false;
UnixTime bail_since_;
// Bo dem tai su dung giua cac khung: 30 Hz x 4800 o, cap phat moi khung la
// lang phi va la nguon jitter.
std::vector<uint8_t> cand_;
std::vector<double> pos_x_, pos_y_;
std::vector<std::pair<double, double>> rz_;
CliffDetectStats stats_;
};
} // namespace vslam
#endif // VSLAM_CLIFF_DETECT_H

View File

@@ -0,0 +1,81 @@
#ifndef VSLAM_DEPTH_FILTER_H
#define VSLAM_DEPTH_FILTER_H
// Loc point cloud tu camera depth.
//
// Port tu perception_3d/src/depth_filter_nodelet.cpp. Chuoi:
// PassThrough(z) -> VoxelGrid -> (tuy chon) xac nhan theo thoi gian
//
// KHONG dung PCL. Ba bo loc nay cong lai khoang 100 dong, va giu
// vslam_perception khong phu thuoc PCL nghia la P5 build va test duoc trên
// may chua co PCL -- cung ly do voi vslam_odometry.
#include <cstdint>
#include <unordered_map>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct DepthFilterConfig {
double min_range = 0.22; // Min-Z cua D410
double max_range = 4.0;
double voxel_size = 0.03;
double max_rate = 10.0; // gioi han tan so dau ra, Hz
// Xac nhan theo thoi gian: mot voxel phai duoc thay `min_hits` lan trong
// `temporal_window` giay moi duoc xuat. Loc nhieu nhap nhay cua depth.
bool enable_temporal = false;
int min_hits = 3;
double temporal_window = 0.5;
};
struct DepthFilterStats {
uint64_t frames_in = 0;
uint64_t frames_out = 0;
uint64_t frames_rate_limited = 0;
uint64_t points_in = 0;
uint64_t points_after_range = 0;
uint64_t points_after_voxel = 0;
uint64_t points_out = 0;
};
class DepthFilter {
public:
explicit DepthFilter(DepthFilterConfig cfg);
// Tra false neu khung bi bo vi gioi han tan so. `out` khong duoc ghi.
//
// `stamp` dung STAMP CUA BAN TIN, khong phai dong ho tuong: gioi han tan so
// theo dong ho tuong se bop nham khi phat lai ban ghi nhanh.
bool Apply(const PointCloudXYZ& in, UnixTime stamp, PointCloudXYZ* out);
void Reset();
const DepthFilterStats& stats() const { return stats_; }
private:
struct VoxelHit {
int hits = 0;
UnixTime last_seen;
PointXYZ centroid;
int count = 0;
};
DepthFilterConfig cfg_;
UnixTime last_output_;
bool have_output_ = false;
std::unordered_map<int64_t, VoxelHit> voxels_;
DepthFilterStats stats_;
};
// Khoa voxel: goi ba chi so 21 bit vao mot int64.
//
// 21 bit moi truc -> dai +-1048575 voxel. Voi voxel 3 cm do la +-31 km, thua
// xa moi ban do trong nha. Goi vao mot int64 cho phep dung unordered_map ma
// khong phai bam mot tuple.
int64_t VoxelKey(double x, double y, double z, double size);
} // namespace vslam
#endif // VSLAM_DEPTH_FILTER_H

View File

@@ -0,0 +1,41 @@
#ifndef VSLAM_DEPTH_TO_CLOUD_H
#define VSLAM_DEPTH_TO_CLOUD_H
// Anh depth -> point cloud. Thay depth_image_proc/point_cloud_xyz.
//
// Cong thuc da XAC MINH tu
// /opt/ros/noetic/include/depth_image_proc/depth_conversions.h:52-100:
//
// constant_x = unit_scaling / fx (uint16 -> 0.001 m moi don vi)
// constant_y = unit_scaling / fy
// x = (u - cx) * depth * constant_x
// y = (v - cy) * depth * constant_y
// z = depth
// depth khong hop le (0 voi uint16, NaN voi float) -> diem = NaN
//
// fx/cx lay TU CameraInfo DA BU BINNING. crop_decimate cap nhat binning chu
// khong chia lai K, nen quen bu la moi diem lech theo he so decimate -- va
// cloud van "trong nhu that", chi la sai ti le.
#include "vslam/vslam_common.h"
namespace vslam {
// `out` duoc ghi de. Diem khong hop le duoc giu lai duoi dang NaN de cloud
// van TO CHUC THEO ANH (width x height) -- buoc sau can dieu do.
// Doc mot diem anh depth ra met. Tra NaN neu khong do duoc.
// Cong khai vi CliffDetect phai doc CHINH cung mot cach -- no lam viec trong
// khong gian anh chu khong qua cloud, va hai cach doc lech nhau (nhat la quy
// uoc 0 = khong do duoc) se sinh vuc gia.
double DepthAtMeters(const Image& img, uint32_t u, uint32_t v);
void DepthToCloud(const Image& depth, const CameraInfo& info, PointCloudXYZ* out);
// Ban KHONG to chuc: bo luon diem khong hop le. Nhanh hon va nho hon khi
// buoc sau khong can cau truc anh.
void DepthToCloudDense(const Image& depth, const CameraInfo& info,
PointCloudXYZ* out);
} // namespace vslam
#endif // VSLAM_DEPTH_TO_CLOUD_H

View File

@@ -0,0 +1,128 @@
#ifndef VSLAM_GRAVITY_ALIGN_H
#define VSLAM_GRAVITY_ALIGN_H
// Uoc luong roll/pitch tu IMU va xoay point cloud ve mat phang ngang.
//
// Port tu perception_3d/src/gravity_align_nodelet.cpp.
//
// ================== VAN DE COT LOI ==================
// Gia toc ke KHONG phan biet duoc nghieng voi tang toc. No do TONG cua:
// 1. trong luc chieu xuong ba truc cua than (phu thuoc roll/pitch)
// 2. gia toc rieng cua robot (tinh tien + huong tam)
//
// Mot robot tang toc 0.3 m/s^2 tren san phang cho ra doc cung gia toc ke nhu
// mot robot dung yen nghieng 1.75 do. Khong co cach nao tach hai truong hop
// bang rieng gia toc ke.
//
// Cach lam: TRU gia toc rieng truoc khi coi phan con lai la trong luc.
// axc = ax - a_lin (gia toc tinh tien, tu dao ham van toc odom)
// ayc = ay - v * omega (gia toc huong tam khi quay)
// Roi chi hieu chinh khi |a| con lai gan g -- tuc la dang gan trang thai tinh.
//
// ================== VI SAO PHAI LOC THONG THAP TRUOC ==================
// Gia toc ke tho dao dong manh do rung tiep xuc banh-san (san gach + banh
// cung). Ap cong |a| ~ g len mau tho se tu choi gan nhu moi mau, va bo loc
// chi con lai phan tich phan gyro -- tuc la troi tu do.
#include <cstdint>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
// base_footprint <- base_link voi nghieng da do. Ca GravityAlign lan
// CliffDetect deu phai dung CHINH ham nay -- hai ban sao hinh hoc lech nhau
// la lop loi da co trong repo cu (URDF vs base_tilt_tf.py).
Transform TiltLift(double roll, double pitch, double wheel_radius);
struct GravityAlignConfig {
// He so bo loc bu: 1 = chi tin gyro, 0 = chi tin accel.
// 0.98 nghia la gyro cho ngan han, accel keo ve dai han.
double alpha = 0.98;
// LPF cho gia toc ke truoc khi dung. Nho = loc manh.
double accel_lpf_alpha = 0.05;
// |a| duoc coi la "gan tinh" khi lech khoi g duoi nguong nay (m/s^2).
double accel_gate = 1.0;
double imu_timeout = 0.5;
double odom_timeout = 0.2;
// Tru gia toc rieng cua robot truoc khi hieu chinh. TAT cai nay la bo loc
// se hieu moi lan tang toc thanh mot cu nghieng.
bool use_odom_accel = true;
double odom_accel_alpha = 0.3; // LPF cho dao ham van toc
// Cat dai chieu cao sau khi xoay ve base_footprint.
double min_height = 0.06;
double max_height = 1.20;
// Chieu cao banh xe: base_footprint o mat dat, base_link o tam truc.
double wheel_radius = 0.075;
};
struct GravityAlignStats {
uint64_t imu_samples = 0;
uint64_t accel_accepted = 0; // so lan cong |a| ~ g mo
uint64_t accel_rejected = 0;
uint64_t clouds_in = 0;
uint64_t clouds_out = 0;
uint64_t points_in = 0;
uint64_t points_out = 0;
double last_accel_norm = 0.0;
};
class GravityAlign {
public:
explicit GravityAlign(GravityAlignConfig cfg);
// Goi moi mau IMU (200 Hz).
void FeedImu(const Imu& imu);
// Goi moi ban tin odometry. Dung de tinh gia toc rieng cua robot.
void FeedOdom(UnixTime stamp, double vx, double vyaw);
// Xoay cloud tu frame quang hoc cua camera ve base_footprint, da bu nghieng.
//
// `cam_to_base` la phep bien doi TINH tu camera toi base_link (tu robot.yaml).
// Nghieng do bo loc uoc luong duoc ap THEM vao.
//
// Tra false neu chua co uoc luong nghieng nao.
bool Align(const PointCloudXYZ& in, const Transform& cam_to_base,
UnixTime stamp, PointCloudXYZ* out) const;
double roll() const { return roll_; }
double pitch() const { return pitch_; }
bool valid() const { return initialized_; }
// true neu mau accel gan nhat duoc chap nhan (dang gan trang thai tinh).
bool accel_ok() const { return accel_ok_; }
void Reset();
const GravityAlignStats& stats() const { return stats_; }
private:
GravityAlignConfig cfg_;
bool initialized_ = false;
double roll_ = 0.0, pitch_ = 0.0;
UnixTime last_imu_;
bool lpf_init_ = false;
double ax_f_ = 0.0, ay_f_ = 0.0, az_f_ = 0.0;
bool accel_ok_ = false;
bool have_odom_ = false;
UnixTime last_odom_;
double v_prev_ = 0.0, w_ = 0.0, a_lin_ = 0.0;
// mutable: Align() la const ve mat logic (khong doi uoc luong nghieng)
// nhung van phai dem. const_cast o day se la mot loi cho, khong phai giai
// phap.
mutable GravityAlignStats stats_;
};
} // namespace vslam
#endif // VSLAM_GRAVITY_ALIGN_H

View File

@@ -0,0 +1,89 @@
#ifndef VSLAM_PERCEPTION_PIPELINE_H
#define VSLAM_PERCEPTION_PIPELINE_H
// Chuoi depth_to_cloud -> depth_filter -> gravity_align -> cliff_detect,
// chay INLINE trong mot loi goi tren chinh luong camera.
//
// Thay cho ba nodelet chung mot manager trong ban ROS. Tot hon: khong
// intrusive_ptr, khong dispatch theo topic, khong nodelet loader, va thu tu
// cac buoc la thu tu dong lenh -- khong con phu thuoc vao thu tu remap trong
// launch file.
//
// Doi tuong nay KHONG tu khoa. No thuoc ve dung mot luong (camera_rx). Ket
// qua di ra ngoai bang shared_ptr<const> qua Channel.
#include <memory>
#include <string>
#include "vslam/cliff_detect.h"
#include "vslam/clock.h"
#include "vslam/depth_filter.h"
#include "vslam/gravity_align.h"
#include "vslam/perception_types.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct PerceptionConfig {
DepthFilterConfig filter;
GravityAlignConfig gravity;
CliffDetectConfig cliff;
// Bo qua buoc dung cloud va loc -- chi chay cliff_detect. Cliff chay tren
// anh depth nen khong can cloud; tren Jetson day la cach ha tai khi chi can
// an toan chu khong can cloud cho SLAM.
bool enable_cloud = true;
bool enable_cliff = true;
};
struct PerceptionStats {
uint64_t frames_in = 0;
uint64_t frames_out = 0;
double last_ms = 0.0;
double max_ms = 0.0;
double avg_ms = 0.0;
};
class PerceptionPipeline {
public:
// `clock` chi dung cho do thoi gian xu ly va cho timeout cua cliff_detect.
// Moi dau thoi gian tren du lieu lay tu stamp cua ban tin -- day la dieu
// kien de phat lai ban ghi cho ket qua y het chay that.
PerceptionPipeline(PerceptionConfig cfg, const Clock& clock);
// Dat phep bien doi TINH camera_depth_optical_frame -> base_link, doc tu
// robot.yaml. Goi mot lan luc khoi tao.
void SetCameraExtrinsic(const Transform& cam_to_base);
// IMU 200 Hz. Goi truc tiep tu luong mcu_rx.
void FeedImu(const Imu& imu);
// Odometry 50 Hz -- can de TRU gia toc rieng cua robot khoi gia toc ke.
void FeedOdom(UnixTime stamp, double vx, double vyaw);
// Mot khung depth. Tra ve ket qua day du; nguoi goi quyet dinh publish gi.
PerceptionOutput Process(const Image& depth, const CameraInfo& info);
const GravityAlign& gravity() const { return gravity_; }
const CliffDetect& cliff() const { return cliff_; }
const PerceptionStats& stats() const { return stats_; }
void Reset();
private:
PerceptionConfig cfg_;
const Clock& clock_;
Transform cam_to_base_;
GravityAlign gravity_;
DepthFilter filter_;
CliffDetect cliff_;
// Tai su dung giua cac khung. 30 Hz x ~300k diem: cap phat moi khung la
// nguon jitter lon hon ban than phep tinh.
PointCloudXYZ buf_raw_, buf_filt_, buf_align_;
PerceptionStats stats_;
};
} // namespace vslam
#endif // VSLAM_PERCEPTION_PIPELINE_H

View File

@@ -0,0 +1,35 @@
#ifndef VSLAM_PERCEPTION_TYPES_H
#define VSLAM_PERCEPTION_TYPES_H
#include <cstdint>
#include <memory>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
// Ket qua cua mot vong perception. Moi truong deu co the null/rong neu buoc
// tuong ung khong chay hoac khong co du lieu.
struct PerceptionOutput {
UnixTime stamp;
PointCloudXYZPtr cloud_raw; // sau depth_to_cloud
PointCloudXYZPtr cloud_filtered; // sau depth_filter
PointCloudXYZPtr cloud_aligned; // sau gravity_align, trong base_footprint
PointCloudXYZPtr cloud_cliff; // diem danh dau mep vuc
// gravity_align
double roll = 0.0;
double pitch = 0.0;
bool tilt_valid = false;
bool accel_ok = false; // accel co dang gan trang thai tinh khong
// cliff_detect
bool cliff_detected = false;
std::string cliff_detail;
};
} // namespace vslam
#endif // VSLAM_PERCEPTION_TYPES_H

View File

@@ -0,0 +1,482 @@
#include "vslam/cliff_detect.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "vslam/depth_to_cloud.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Trung vi cua z tren mot khoang da sap xep theo r; tra ve luon r tai giua
// khoang. Hai trung vi -> mot duong thang. Ben vung hon binh phuong toi thieu:
// mot vet vat can sot lai khong duoc phep keo ca duong.
void MedianOf(std::vector<std::pair<double, double>>::iterator b,
std::vector<std::pair<double, double>>::iterator e, double* r_out,
double* z_out) {
const size_t m = static_cast<size_t>(std::distance(b, e));
std::vector<double> zs;
zs.reserve(m);
for (auto it = b; it != e; ++it) zs.push_back(it->second);
std::nth_element(zs.begin(), zs.begin() + m / 2, zs.end());
*z_out = zs[m / 2];
*r_out = (b + static_cast<long>(m / 2))->first; // da sap xep theo r
}
// Khop BEN VUNG bang hai trung vi, khong dung binh phuong toi thieu: mot vet
// vat can sot lai khong duoc phep keo ca duong thang.
// Tra ve true neu doc bi kep (dau hieu phep khop hong).
bool FitFloorLine(std::vector<std::pair<double, double>>& rz, double* z0,
double* slope, double* slope_raw, double* mad,
double max_slope) {
const size_t n = rz.size(), h = n / 2;
double r1, z1, r2, z2;
MedianOf(rz.begin(), rz.begin() + static_cast<long>(h), &r1, &z1);
MedianOf(rz.begin() + static_cast<long>(h), rz.end(), &r2, &z2);
bool clamped = false;
if (r2 - r1 > 0.15) { // du duong day de uoc luong doc
double sl = (z2 - z1) / (r2 - r1);
*slope_raw = sl; // giu doc TRUOC khi kep, de in ra hieu chuan
// Doc vuot tran = dau hieu phep khop hong, KHONG phai san doc that.
// Ramp la san doc THAT va robot phai di duoc; cong phan biet ramp/vuc la
// MAD, khong phai do lon cua doc.
if (std::fabs(sl) > max_slope) {
clamped = true;
sl = (sl > 0 ? max_slope : -max_slope);
}
*slope = sl;
*z0 = z1 - *slope * r1;
} else {
*slope = 0.0;
*z0 = z1;
}
// MAD cua phan du: duong khop co THUC SU ta duoc mat san khong?
std::vector<double> resid;
resid.reserve(n);
for (const auto& pr : rz) {
resid.push_back(std::fabs(pr.second - (*z0 + *slope * pr.first)));
}
std::nth_element(resid.begin(), resid.begin() + static_cast<long>(n / 2),
resid.end());
*mad = resid[n / 2];
return clamped;
}
} // namespace
const char* CliffBailName(CliffBail b) {
switch (b) {
case CliffBail::kNone: return "none";
case CliffBail::kDisabled: return "disabled";
case CliffBail::kNoRollPitch: return "no_roll_pitch";
case CliffBail::kAccelGated: return "accel_gated";
case CliffBail::kBadGeometry: return "bad_geometry";
case CliffBail::kTzDeviation: return "tz_deviation";
case CliffBail::kFewSamples: return "few_samples";
case CliffBail::kSlopeClamped: return "slope_clamped";
case CliffBail::kResidualLarge: return "residual_large";
case CliffBail::kBadEncoding: return "bad_encoding";
case CliffBail::kObstructed: return "obstructed";
case CliffBail::kOffsetLarge: return "offset_large";
}
return "?";
}
CliffDetect::CliffDetect(CliffDetectConfig cfg) : cfg_(std::move(cfg)) {
if (cfg_.pixel_step < 1) cfg_.pixel_step = 1;
}
void CliffDetect::Reset() {
have_rp_ = false;
bailing_ = false;
stats_ = CliffDetectStats{};
}
void CliffDetect::SetTilt(UnixTime stamp, double roll, double pitch, bool accel_ok) {
roll_ = roll;
pitch_ = pitch;
accel_ok_ = accel_ok;
last_rp_ = stamp;
have_rp_ = true;
}
CliffResult CliffDetect::Bail(CliffBail why, bool immediate, UnixTime now) {
if (!bailing_) {
bailing_ = true;
bail_since_ = now;
}
const double held = SecondsBetween(now, bail_since_);
CliffResult r;
r.judged = false;
r.bail = why;
r.bail_held = held;
// immediate = true -> mot khung du de bao nguy (hinh hoc vo nghia, robot
// dang nghieng / nhoai len vat)
// immediate = false -> mot khung xau la nhieu nhat thoi; nhung mu LIEN TUC
// qua fail_safe_after giay thi bao nguy.
//
// ============ TRU `kObstructed` RA KHOI FAIL-SAFE ============
//
// Fail-safe ton tai cho truong hop "toi khong thay san va KHONG BIET vi
// sao": khong du mau, khop hong, mat phang vo nghia. Luc do khong loai tru
// duoc mot cai vuc, nen phai dung.
//
// `kObstructed` khac han. No la mot quan sat KHANG DINH: cua so nhin san bi
// mot vat DAC lap kin. Vat dac khong phai vuc, va da co nguoi lo -- LiDAR
// thay no va FSM dung robot qua SCAN_SLOW/SCAN_STOP.
//
// Do duoc tren ban do benh vien that: dung o (0.5, 0) cach tuong 2.0 m --
// cua so nhin san 1.1-2.5 m bi buc tuong lap kin -- ra 209/240 khung "bao
// vuc" voi ly do `obstructed`. Hau qua: robot KHONG BAO GIO lai gan tuong
// duoi ~2.5 m duoc, tuc khong di duoc trong bat ky toa nha that nao. Ban do
// SLAM ket o 1.55 x 1.05 m sau 50 giay lai.
//
// ⚠️ Van BAO CAO bail nhu cu (`judged = false`): nguoi van hanh phai thay
// detector dang mu. Chi khong bien cai mu DA GIAI THICH DUOC thanh lenh
// dung.
const bool blind_for_unknown_reason = (why != CliffBail::kObstructed);
r.detected = cfg_.fail_safe && blind_for_unknown_reason &&
(immediate || held > cfg_.fail_safe_after);
stats_.bailed++;
stats_.bail_by[static_cast<size_t>(why)]++;
if (r.detected) stats_.detected++;
return r;
}
CliffResult CliffDetect::Process(const Image& depth, const CameraInfo& info,
const Transform& cam_to_base, UnixTime now) {
stats_.frames++;
if (!cfg_.enabled) {
CliffResult r;
r.judged = false;
r.bail = CliffBail::kDisabled;
return r;
}
if (depth.data == nullptr ||
(depth.format != PixelFormat::kMono16 && depth.format != PixelFormat::kFloat32)) {
return Bail(CliffBail::kBadEncoding, false, now);
}
const bool rp_fresh =
have_rp_ && SecondsBetween(now, last_rp_) < cfg_.imu_timeout;
double roll = 0.0, pitch = 0.0;
if (rp_fresh) {
roll = roll_;
pitch = pitch_;
}
// Khong co roll/pitch moi -> gia dinh phang va di tiep. Ket qua KHONG dang
// tin khi robot nghieng, nhung mot camera gan chac phang van tot hon la
// khong phan xet gi.
// gravity_align dang khong neo duoc vao trong luc -> pitch la gyro thuan va
// dang troi. Hinh hoc cat tia x san khong dung tin o trang thai nay.
if (cfg_.require_accel_ok && rp_fresh && !accel_ok_) {
return Bail(CliffBail::kAccelGated, false, now);
}
// Cung mot hinh hoc voi GravityAlign -- dung chung TiltLift().
const Transform T = TransformCompose(TiltLift(roll, pitch, cfg_.wheel_radius),
cam_to_base);
// Hang thu 3 cua ma tran quay: lay bang cach quay ba vector co so.
const double r20 = RotateVector(T.rotation, Vector3{1, 0, 0}).z;
const double r21 = RotateVector(T.rotation, Vector3{0, 1, 0}).z;
const double r22 = RotateVector(T.rotation, Vector3{0, 0, 1}).z;
const double tz = T.translation.z;
// Tia chi cham san khi no chuc XUONG trong base_footprint, va camera phai o
// TREN san.
if (tz <= 0.0) return Bail(CliffBail::kBadGeometry, true, now);
// Camera lech khoi chieu cao danh dinh => robot dang nghieng / da nhoai len
// vat gi do. Dung luc do phep khop mat san se bam theo TANG DUOI va bao
// "khong co vuc" -- im lang khi that su co vuc la kieu hong nguy hiem nhat.
if (std::fabs(tz - cfg_.nominal_tz) > cfg_.max_tz_dev) {
return Bail(CliffBail::kTzDeviation, true, now);
}
// KHONG duoc doc thang info.K. crop_decimate giao anh 320x240 nhung
// CameraInfo van mang K cua 640x480 va bao muc gop qua binning_x/y = 2.
// Doc thang K thi moi tia bi coi nhu nam ngang -> r_floor [3.5, 134] m thay
// vi [1.07, 3.18] -> khong tia nao roi vao cua so -> detector im lang hoan
// toan MA KHONG BAO LOI GI.
const double fx = info.fx_binned(), fy = info.fy_binned();
const double cx = info.cx_binned(), cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return Bail(CliffBail::kBadGeometry, true, now);
const double tan_unc = std::tan(cfg_.pitch_uncertainty_deg * M_PI / 180.0);
const int W = static_cast<int>(depth.width);
const int H = static_cast<int>(depth.height);
const int step = cfg_.pixel_step;
const int gw = (W + step - 1) / step;
const int gh = (H + step - 1) / step;
const size_t ncell = static_cast<size_t>(gw) * static_cast<size_t>(gh);
cand_.assign(ncell, 0);
pos_x_.assign(ncell, 0.0);
pos_y_.assign(ncell, 0.0);
CliffResult res;
res.judged = true;
res.tz = tz;
double r_min = 1e9, r_max = -1e9, z_lowest = 1e9;
// ============ LUOT 1: DO MUC SAN THAM CHIEU ============
// Tru di muc nay bien phep do thanh VI SAI -> sai so pitch, sai so chieu cao
// camera va lun caster deu la common-mode va bi triet.
// z_ref(r) = lvl_z0 + lvl_slope * r
double lvl_z0 = 0.0, lvl_slope = 0.0, lvl_mad = 0.0, lvl_slope_raw = 0.0;
bool leveled = false;
int64_t n_high = 0, n_window = 0;
if (cfg_.self_level) {
rz_.clear();
rz_.reserve(2048);
for (int gy = 0; gy < gh; ++gy) {
const int v = gy * step;
if (v >= H) break;
for (int gx = 0; gx < gw; ++gx) {
const int u = gx * step;
if (u >= W) break;
const double a = (u - cx) / fx;
const double b = (v - cy) / fy;
const double denom = r20 * a + r21 * b + r22;
if (denom > -1e-6) continue;
const double z_exp = -tz / denom;
if (z_exp <= 0.0) continue;
const Point pf = TransformPoint(T, Point{z_exp * a, z_exp * b, z_exp});
const double rf = std::hypot(pf.x, pf.y);
if (rf < cfg_.min_dist || rf > cfg_.max_dist) continue;
const double d = DepthAtMeters(depth, static_cast<uint32_t>(u),
static_cast<uint32_t>(v));
if (!std::isfinite(d) || d <= 0.0) continue;
const Point po = TransformPoint(T, Point{d * a, d * b, d});
// Cong nay lam CA HAI viec: loai vat the (mat ban 0.7 m, mat ghe
// 0.45 m) VA loai vuc that (z ~ -1 m) khoi phep khop. Nho ve thu hai
// ma khop duoc tren TOAN cua so ma khong nuot mat chinh cai vuc dang
// can tim.
n_window++;
if (po.z > cfg_.level_gate) {
n_high++; // diem CAO: vat can che mat san (tuong, ban, ghe)
continue;
}
if (po.z < -cfg_.level_gate) continue; // diem THAP: co the la vuc
rz_.emplace_back(rf, po.z);
}
}
res.lvl_high = n_high;
res.lvl_window = n_window;
// Phan lon cua so bi vat can che -> khong nhin thay san -> KHONG phan xet.
// Phai kiem TRUOC min_level_samples: mot buc tuong gan van de lai du 40
// mau z thap de "khop duoc" mot mat phang khong co that.
if (n_window > 0 &&
static_cast<double>(n_high) > cfg_.max_obstructed_frac * n_window) {
return Bail(CliffBail::kObstructed, false, now);
}
if (static_cast<int>(rz_.size()) < cfg_.min_level_samples) {
// Khong du mau -> khong biet san o dau -> KHONG phan xet. Im lang con
// hon bao gia: bao gia se chan duong robot giua nha hang va nguoi van
// hanh se tat han node di.
return Bail(CliffBail::kFewSamples, false, now);
}
res.lvl_samples = static_cast<int64_t>(rz_.size());
std::sort(rz_.begin(), rz_.end(),
[](const std::pair<double, double>& p, const std::pair<double, double>& q) {
return p.first < q.first;
});
res.lvl_r_lo = rz_.front().first;
res.lvl_r_hi = rz_.back().first;
bool slope_clamped = FitFloorLine(rz_, &lvl_z0, &lvl_slope, &lvl_slope_raw,
&lvl_mad, cfg_.max_level_slope);
// --- LOAI NGOAI LAI ROI KHOP LAI ---
//
// Phep khop hai-trung-vi chi theo BAN KINH: z = z0 + doc*r. No gop mat
// chieu phuong vi, nen mot buc tuong o MOT BEN lam lech ca vanh.
//
// Do duoc: hanh lang 3.0 m (tuong cach 1.5 m) -> tia nham r > 1.5 dap vao
// tuong o z = 0.8*(1 - 1.5/r); tai r = 2.0 cho z = 0.20, VUA DU lot cong
// level_gate 0.25. Duong khop bi keo len o giua cua so, roi tia san THAT
// o 2.5 m bi do voi mat phang do -> roi duoi nguong -> vuc gia.
// Cong `max_obstructed_frac` KHONG bat duoc: quet ngưỡng tu 0.60 xuong
// 0.20 deu cho dung 6/210 khung sai o be rong 3.0 m, va che% = 0.0 o moi
// nguong -- tuc la vat can chua du nhieu de kich cong.
//
// Mot luot loai ngoai lai giai quyet dung goc: diem tuong la THIEU SO nen
// bi loai, con neu chung la DA SO thi MAD phinh ra va cong
// max_level_residual kich. Khong the lam vuc that bien mat: diem vuc cung
// bi loai khoi phep khop, ma loai chung ra thi mat san tham chieu cang
// dung -> vuc CANG de thay o luot 2.
if (lvl_mad > 1e-6 && rz_.size() >= 8) {
const double cut = std::max(3.0 * lvl_mad, 0.01);
size_t keep = 0;
for (size_t i = 0; i < rz_.size(); ++i) {
if (std::fabs(rz_[i].second - (lvl_z0 + lvl_slope * rz_[i].first)) <= cut) {
rz_[keep++] = rz_[i];
}
}
if (static_cast<int>(keep) >= cfg_.min_level_samples && keep < rz_.size()) {
rz_.resize(keep);
slope_clamped = FitFloorLine(rz_, &lvl_z0, &lvl_slope, &lvl_slope_raw,
&lvl_mad, cfg_.max_level_slope);
}
}
res.lvl_z0 = lvl_z0;
res.lvl_slope = lvl_slope;
res.lvl_mad = lvl_mad;
if (slope_clamped) return Bail(CliffBail::kSlopeClamped, false, now);
if (std::fabs(lvl_z0) > cfg_.max_level_offset) {
// Mat phang khop duoc khong di qua cho robot dang dung -> no khong phai
// mat san. Xem ghi chu o max_level_offset.
return Bail(CliffBail::kOffsetLarge, false, now);
}
if (lvl_mad > cfg_.max_level_residual) {
// Khung nhin khong phai mot mat phang san -> khong co goc quy chieu dang
// tin -> KHONG phan xet.
return Bail(CliffBail::kResidualLarge, false, now);
}
leveled = true;
}
// ============ LUOT 2: PHAN XET TUNG TIA ============
for (int gy = 0; gy < gh; ++gy) {
const int v = gy * step;
if (v >= H) break;
for (int gx = 0; gx < gw; ++gx) {
const int u = gx * step;
if (u >= W) break;
res.n_total++;
const double a = (u - cx) / fx;
const double b = (v - cy) / fy;
const double denom = r20 * a + r21 * b + r22;
if (denom > -1e-6) {
res.n_up++; // tia khong chuc xuong -> khong cham san
continue;
}
const double z_exp = -tz / denom; // depth ma san LE RA phai o do
if (z_exp <= 0.0) {
res.n_zneg++;
continue;
}
const Point p_floor = TransformPoint(T, Point{z_exp * a, z_exp * b, z_exp});
const double r_floor = std::hypot(p_floor.x, p_floor.y);
r_min = std::min(r_min, r_floor);
r_max = std::max(r_max, r_floor);
if (r_floor < cfg_.min_dist || r_floor > cfg_.max_dist) {
res.n_range++;
continue;
}
res.n_inwin++;
const double d_obs = DepthAtMeters(depth, static_cast<uint32_t>(u),
static_cast<uint32_t>(v));
// Nguong no ra theo tam: bu sai so pitch con lai sau tu hieu chuan.
const double z_ref = lvl_z0 + lvl_slope * r_floor;
const double thr = z_ref - (cfg_.cliff_margin + r_floor * tan_unc);
bool is_cand = false;
if (!std::isfinite(d_obs) || d_obs <= 0.0) {
// LO: le ra phai thay san o day ma khong co so do nao. Day la ca cau
// thang TOI, va la ly do phai chay tren anh depth.
is_cand = true;
res.n_hole++;
} else {
const Point p_obs = TransformPoint(T, Point{d_obs * a, d_obs * b, d_obs});
z_lowest = std::min(z_lowest, p_obs.z);
if (p_obs.z < thr) {
is_cand = true; // SUT: be mat thap hon san qua nguong
res.n_drop++;
}
}
if (is_cand) {
const size_t idx = static_cast<size_t>(gy) * static_cast<size_t>(gw) + gx;
cand_[idx] = 1;
// MARK TAI MEP (giao tia x mat san), khong tai diem tra ve. Diem tra
// ve nam duoi day vuc -- hoac khong ton tai.
pos_x_[idx] = p_floor.x;
pos_y_[idx] = p_floor.y;
}
}
}
// ============ DOI CUM: LOAI PIXEL LE ============
res.edge_cloud.header = depth.header;
res.edge_cloud.header.frame_id = kBaseFootprintFrame;
res.edge_cloud.points.clear();
res.edge_cloud.is_dense = true;
const float mark_z = static_cast<float>(-(cfg_.cliff_margin + 0.05));
for (int gy = 0; gy < gh; ++gy) {
for (int gx = 0; gx < gw; ++gx) {
const size_t idx = static_cast<size_t>(gy) * static_cast<size_t>(gw) + gx;
if (!cand_[idx]) continue;
int neigh = 0;
for (int dy = -1; dy <= 1; ++dy) {
const int ny = gy + dy;
if (ny < 0 || ny >= gh) continue;
for (int dx = -1; dx <= 1; ++dx) {
const int nx = gx + dx;
if (nx < 0 || nx >= gw) continue;
if (dx == 0 && dy == 0) continue;
neigh += cand_[static_cast<size_t>(ny) * static_cast<size_t>(gw) + nx];
}
}
if (neigh < cfg_.min_neighbors) continue;
// GIU z AM, khong nang len. Trong costmap cu, vat can ao dat o z duong
// bi chinh tia clearing cua camera xoa ngay frame sau. Khong con costmap
// nua nhung giu nguyen quy uoc de doc lai log cu van khop.
res.edge_cloud.points.push_back(PointXYZ{static_cast<float>(pos_x_[idx]),
static_cast<float>(pos_y_[idx]), mark_z});
res.n_cliff++;
}
}
res.detected = (res.n_cliff >= cfg_.min_cluster);
res.r_min = (r_min > 1e8 ? 0.0 : r_min);
res.r_max = (r_max < -1e8 ? 0.0 : r_max);
res.z_lowest = (z_lowest > 1e8 ? 0.0 : z_lowest);
res.lvl_z0 = lvl_z0;
res.lvl_slope = lvl_slope;
res.lvl_slope_raw = lvl_slope_raw;
res.lvl_mad = lvl_mad;
res.leveled = leveled;
// Den day nghia la da phan xet duoc -> chuoi "khong biet" ket thuc.
bailing_ = false;
stats_.judged++;
if (res.detected) stats_.detected++;
return res;
}
} // namespace vslam

View File

@@ -0,0 +1,123 @@
#include "vslam/depth_filter.h"
#include <cmath>
#include <cstdint>
#include "vslam/log.h"
namespace vslam {
int64_t VoxelKey(double x, double y, double z, double size) {
const int64_t ix = static_cast<int64_t>(std::floor(x / size));
const int64_t iy = static_cast<int64_t>(std::floor(y / size));
const int64_t iz = static_cast<int64_t>(std::floor(z / size));
// Doi sang khong dau 21 bit roi goi. Khong kiem tran o day: voi voxel 3 cm
// thi dai la +-31 km, va mot diem ngoai dai do da la rac tu truoc.
constexpr int64_t kBias = 1 << 20;
const int64_t ux = (ix + kBias) & 0x1FFFFF;
const int64_t uy = (iy + kBias) & 0x1FFFFF;
const int64_t uz = (iz + kBias) & 0x1FFFFF;
return (ux << 42) | (uy << 21) | uz;
}
DepthFilter::DepthFilter(DepthFilterConfig cfg) : cfg_(std::move(cfg)) {}
void DepthFilter::Reset() {
voxels_.clear();
have_output_ = false;
stats_ = DepthFilterStats{};
}
bool DepthFilter::Apply(const PointCloudXYZ& in, UnixTime stamp,
PointCloudXYZ* out) {
stats_.frames_in++;
stats_.points_in += in.points.size();
// Gioi han tan so theo STAMP CUA BAN TIN, khong phai dong ho tuong.
// Dung dong ho tuong se bop nham khi phat lai ban ghi nhanh hon thoi gian
// that -- va bai regression se cho ket qua khac live.
if (cfg_.max_rate > 0.0 && have_output_) {
const double dt = SecondsBetween(stamp, last_output_);
if (dt >= 0.0 && dt < 1.0 / cfg_.max_rate) {
stats_.frames_rate_limited++;
return false;
}
}
// --- 1. PassThrough theo z (khoang cach toi camera) ---
// Duoi Min-Z la vung mu cua D410, khong phai vat can o khoang cach do.
// Tren max_range thi do chinh xac cua stereo giam nhanh theo binh phuong.
std::unordered_map<int64_t, VoxelHit> frame_voxels;
frame_voxels.reserve(in.points.size() / 4 + 16);
size_t after_range = 0;
for (const PointXYZ& p : in.points) {
if (!std::isfinite(p.z)) continue; // NaN cua cloud to chuc theo anh
if (p.z < cfg_.min_range || p.z > cfg_.max_range) continue;
if (!std::isfinite(p.x) || !std::isfinite(p.y)) continue;
after_range++;
// --- 2. VoxelGrid: gop diem trong cung o ---
const int64_t key = VoxelKey(p.x, p.y, p.z, cfg_.voxel_size);
VoxelHit& h = frame_voxels[key];
h.centroid.x += p.x;
h.centroid.y += p.y;
h.centroid.z += p.z;
h.count++;
}
stats_.points_after_range += after_range;
stats_.points_after_voxel += frame_voxels.size();
out->header = in.header;
out->header.stamp = stamp;
out->points.clear();
out->points.reserve(frame_voxels.size());
out->is_dense = true;
if (!cfg_.enable_temporal) {
for (auto& kv : frame_voxels) {
VoxelHit& h = kv.second;
const float inv = 1.0f / static_cast<float>(h.count);
out->points.push_back(PointXYZ{h.centroid.x * inv, h.centroid.y * inv,
h.centroid.z * inv});
}
} else {
// --- 3. Xac nhan theo thoi gian ---
// Mot voxel phai duoc thay `min_hits` lan trong `temporal_window` moi
// duoc xuat. Loc nhieu nhap nhay cua depth, doi lai mot do tre bang
// (min_hits - 1) khung.
for (auto& kv : frame_voxels) {
VoxelHit& cur = kv.second;
VoxelHit& acc = voxels_[kv.first];
if (acc.hits > 0 &&
SecondsBetween(stamp, acc.last_seen) > cfg_.temporal_window) {
acc.hits = 0; // qua cu -> bat dau dem lai
}
acc.hits++;
acc.last_seen = stamp;
const float inv = 1.0f / static_cast<float>(cur.count);
acc.centroid = PointXYZ{cur.centroid.x * inv, cur.centroid.y * inv,
cur.centroid.z * inv};
if (acc.hits >= cfg_.min_hits) {
out->points.push_back(acc.centroid);
}
}
// Don voxel qua han. Khong don thi map phinh vo han khi robot di xa.
for (auto it = voxels_.begin(); it != voxels_.end();) {
if (SecondsBetween(stamp, it->second.last_seen) > cfg_.temporal_window * 2.0) {
it = voxels_.erase(it);
} else {
++it;
}
}
}
stats_.points_out += out->points.size();
stats_.frames_out++;
last_output_ = stamp;
have_output_ = true;
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,93 @@
#include "vslam/depth_to_cloud.h"
#include <cmath>
#include <cstring>
#include <limits>
namespace vslam {
// Doc mot diem anh depth ra met. Tra NaN neu khong hop le.
//
// Quy uoc cua RealSense va cua depth_image_proc:
// uint16 : 0 = khong do duoc
// float32: NaN = khong do duoc
double DepthAtMeters(const Image& img, uint32_t u, uint32_t v) {
const size_t row = static_cast<size_t>(v) * img.step;
if (img.format == PixelFormat::kMono16) {
const size_t off = row + static_cast<size_t>(u) * 2;
const uint16_t raw = static_cast<uint16_t>(img.data[off]) |
(static_cast<uint16_t>(img.data[off + 1]) << 8);
if (raw == 0) return std::numeric_limits<double>::quiet_NaN();
return raw * static_cast<double>(img.depth_scale);
}
if (img.format == PixelFormat::kFloat32) {
float f;
std::memcpy(&f, img.data + row + static_cast<size_t>(u) * 4, 4);
return f;
}
return std::numeric_limits<double>::quiet_NaN();
}
void DepthToCloud(const Image& depth, const CameraInfo& info, PointCloudXYZ* out) {
out->header = depth.header;
out->points.assign(static_cast<size_t>(depth.width) * depth.height, PointXYZ{});
out->is_dense = false;
if (depth.data == nullptr) return;
// fx/cx DA BU BINNING. crop_decimate cap nhat binning chu khong chia lai K;
// quen bu la moi diem lech theo he so decimate, va cloud van "trong nhu
// that" -- chi la sai ti le.
const double fx = info.fx_binned();
const double fy = info.fy_binned();
const double cx = info.cx_binned();
const double cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return;
const float nan_v = std::numeric_limits<float>::quiet_NaN();
for (uint32_t v = 0; v < depth.height; ++v) {
for (uint32_t u = 0; u < depth.width; ++u) {
PointXYZ& p = out->points[static_cast<size_t>(v) * depth.width + u];
const double d = DepthAtMeters(depth, u, v);
if (!std::isfinite(d) || d <= 0.0) {
p.x = p.y = p.z = nan_v;
continue;
}
p.x = static_cast<float>((u - cx) * d / fx);
p.y = static_cast<float>((v - cy) * d / fy);
p.z = static_cast<float>(d);
}
}
}
void DepthToCloudDense(const Image& depth, const CameraInfo& info,
PointCloudXYZ* out) {
out->header = depth.header;
out->points.clear();
out->is_dense = true;
if (depth.data == nullptr) return;
const double fx = info.fx_binned();
const double fy = info.fy_binned();
const double cx = info.cx_binned();
const double cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return;
out->points.reserve(static_cast<size_t>(depth.width) * depth.height / 2);
for (uint32_t v = 0; v < depth.height; ++v) {
for (uint32_t u = 0; u < depth.width; ++u) {
const double d = DepthAtMeters(depth, u, v);
if (!std::isfinite(d) || d <= 0.0) continue;
PointXYZ p;
p.x = static_cast<float>((u - cx) * d / fx);
p.y = static_cast<float>((v - cy) * d / fy);
p.z = static_cast<float>(d);
out->points.push_back(p);
}
}
}
} // namespace vslam

View File

@@ -0,0 +1,167 @@
#include "vslam/gravity_align.h"
#include <cmath>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
GravityAlign::GravityAlign(GravityAlignConfig cfg) : cfg_(std::move(cfg)) {}
void GravityAlign::Reset() {
initialized_ = false;
roll_ = pitch_ = 0.0;
lpf_init_ = false;
have_odom_ = false;
accel_ok_ = false;
stats_ = GravityAlignStats{};
}
void GravityAlign::FeedOdom(UnixTime stamp, double vx, double vyaw) {
if (have_odom_) {
const double dt = SecondsBetween(stamp, last_odom_);
if (dt > 0.0 && dt < 1.0) {
// Dao ham van toc, loc thong thap. Dao ham tho qua nhieu de tru truc
// tiep khoi gia toc ke.
const double a = (vx - v_prev_) / dt;
a_lin_ = cfg_.odom_accel_alpha * a + (1.0 - cfg_.odom_accel_alpha) * a_lin_;
}
}
v_prev_ = vx;
w_ = vyaw;
last_odom_ = stamp;
have_odom_ = true;
}
void GravityAlign::FeedImu(const Imu& imu) {
const UnixTime now = imu.header.stamp;
stats_.imu_samples++;
if (!initialized_) {
last_imu_ = now;
initialized_ = true;
return;
}
const double dt = SecondsBetween(now, last_imu_);
last_imu_ = now;
if (dt <= 0.0 || dt > 1.0) {
// Nhay thoi gian (reset mo phong / phat lai ban ghi) -> bo qua mau nay.
return;
}
// --- Du doan bang gyro ---
roll_ += imu.angular_velocity.x * dt;
pitch_ += imu.angular_velocity.y * dt;
// --- Loc thong thap accel TRUOC khi dung ---
// Accel tho dao dong manh do rung tiep xuc banh-san; ap cong |a| ~ g len
// mau tho se tu choi gan nhu moi mau, va bo loc chi con lai tich phan gyro
// -- tuc la troi tu do.
const double ax_raw = imu.linear_acceleration.x;
const double ay_raw = imu.linear_acceleration.y;
const double az_raw = imu.linear_acceleration.z;
if (!lpf_init_) {
ax_f_ = ax_raw;
ay_f_ = ay_raw;
az_f_ = az_raw;
lpf_init_ = true;
} else {
const double a = cfg_.accel_lpf_alpha;
ax_f_ = a * ax_raw + (1.0 - a) * ax_f_;
ay_f_ = a * ay_raw + (1.0 - a) * ay_f_;
az_f_ = a * az_raw + (1.0 - a) * az_f_;
}
// --- Hieu chinh bang accel, CHI khi dang gan trang thai tinh ---
const double ax = ax_f_, ay = ay_f_, az = az_f_;
// TRU gia toc cua CHINH ROBOT truoc khi coi phan con lai la trong luc.
// axc: gia toc tinh tien (dv/dt)
// ayc: gia toc huong tam khi quay (v * omega)
double axc = ax, ayc = ay;
const bool odom_fresh =
have_odom_ && SecondsBetween(now, last_odom_) < cfg_.odom_timeout;
if (cfg_.use_odom_accel && odom_fresh) {
axc = ax - a_lin_;
ayc = ay - v_prev_ * w_;
}
const double norm = std::sqrt(axc * axc + ayc * ayc + az * az);
stats_.last_accel_norm = norm;
if (std::fabs(norm - kGravity) < cfg_.accel_gate && norm > 1e-3) {
const double roll_acc = std::atan2(ayc, az);
const double pitch_acc = std::atan2(-axc, std::sqrt(ayc * ayc + az * az));
// Bo loc bu: gyro cho ngan han, accel keo ve dai han.
roll_ = cfg_.alpha * roll_ + (1.0 - cfg_.alpha) * roll_acc;
pitch_ = cfg_.alpha * pitch_ + (1.0 - cfg_.alpha) * pitch_acc;
accel_ok_ = true;
stats_.accel_accepted++;
} else {
// Dang tang toc / phanh / va cham -> khong biet dau la trong luc ->
// chi tich phan gyro. Troi cham con hon nghieng sai.
accel_ok_ = false;
stats_.accel_rejected++;
}
}
Transform TiltLift(double roll, double pitch, double wheel_radius) {
// Ghep hai phep bien doi:
// tilt : Ry(pitch) * Rx(roll) -- DUNG dau duong.
// Bo loc bu cho ra pitch = atan2(-ax, |a_yz|); voi robot tinh
// nghieng goc theta quanh +Y, gia toc ke doc ax = -g sin(theta),
// az = g cos(theta) => pitch = theta. Do la phep quay body->the
// gioi, tuc dung chieu de dua diem tu base_link ve mat phang ngang.
// Phu dinh o day se lam nghieng GAP DOI thay vi trie^t tieu.
// lift : base_link (tam truc) -> base_footprint (mat dat).
Transform tilt = TransformIdentity();
tilt.rotation = QuaternionFromRPY(roll, pitch, 0.0);
Transform lift = TransformIdentity();
lift.translation = Vector3{0.0, 0.0, wheel_radius};
return TransformCompose(lift, tilt);
}
bool GravityAlign::Align(const PointCloudXYZ& in, const Transform& cam_to_base,
UnixTime stamp, PointCloudXYZ* out) const {
if (!initialized_) return false;
stats_.clouds_in++;
stats_.points_in += in.points.size();
// Ghep ba phep bien doi:
// lift : base_link -> base_footprint (nang len chieu cao banh xe)
// tilt : bu nghieng DO duoc (nghich dao cua nghieng than)
// cam : camera -> base_link (tinh, tu robot.yaml)
const Transform total =
TransformCompose(TiltLift(roll_, pitch_, cfg_.wheel_radius), cam_to_base);
out->header = in.header;
out->header.stamp = stamp;
out->header.frame_id = kBaseFootprintFrame;
out->points.clear();
out->points.reserve(in.points.size());
out->is_dense = true;
for (const PointXYZ& p : in.points) {
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
const Point q = TransformPoint(total, Point{p.x, p.y, p.z});
// Cat dai chieu cao SAU khi xoay: duoi min_height la san, tren max_height
// la tran va den.
if (q.z < cfg_.min_height || q.z > cfg_.max_height) continue;
out->points.push_back(PointXYZ{static_cast<float>(q.x), static_cast<float>(q.y),
static_cast<float>(q.z)});
}
stats_.clouds_out++;
stats_.points_out += out->points.size();
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,89 @@
#include "vslam/perception_pipeline.h"
#include <algorithm>
#include <chrono>
#include "vslam/depth_to_cloud.h"
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
PerceptionPipeline::PerceptionPipeline(PerceptionConfig cfg, const Clock& clock)
: cfg_(std::move(cfg)),
clock_(clock),
cam_to_base_(TransformIdentity()),
gravity_(cfg_.gravity),
filter_(cfg_.filter),
cliff_(cfg_.cliff) {}
void PerceptionPipeline::SetCameraExtrinsic(const Transform& cam_to_base) {
cam_to_base_ = cam_to_base;
}
void PerceptionPipeline::FeedImu(const Imu& imu) { gravity_.FeedImu(imu); }
void PerceptionPipeline::FeedOdom(UnixTime stamp, double vx, double vyaw) {
gravity_.FeedOdom(stamp, vx, vyaw);
}
void PerceptionPipeline::Reset() {
gravity_.Reset();
filter_.Reset();
cliff_.Reset();
stats_ = PerceptionStats{};
}
PerceptionOutput PerceptionPipeline::Process(const Image& depth, const CameraInfo& info) {
// steady_clock cho do thoi gian -- KHONG dung UnixTime. Mot buoc NTP giua
// hai moc se cho ra "khung xu ly het -3 giay".
const auto t0 = std::chrono::steady_clock::now();
stats_.frames_in++;
PerceptionOutput out;
out.stamp = depth.header.stamp;
out.roll = gravity_.roll();
out.pitch = gravity_.pitch();
out.tilt_valid = gravity_.valid();
out.accel_ok = gravity_.accel_ok();
// --- Duong cliff: chay tren ANH DEPTH, khong qua cloud ---
// Dat TRUOC duong cloud vi no la duong an toan. Neu duong cloud nem hay
// cham, cliff van da chay xong.
if (cfg_.enable_cliff) {
cliff_.SetTilt(depth.header.stamp, gravity_.roll(), gravity_.pitch(),
gravity_.accel_ok());
CliffResult cr = cliff_.Process(depth, info, cam_to_base_, clock_.Now());
out.cliff_detected = cr.detected;
out.cliff_detail = cr.judged ? "judged" : CliffBailName(cr.bail);
if (!cr.edge_cloud.points.empty()) {
out.cloud_cliff = std::make_shared<const PointCloudXYZ>(std::move(cr.edge_cloud));
}
}
// --- Duong cloud: cho SLAM va cho hien thi ---
if (cfg_.enable_cloud) {
DepthToCloudDense(depth, info, &buf_raw_);
out.cloud_raw = std::make_shared<const PointCloudXYZ>(buf_raw_);
if (filter_.Apply(buf_raw_, depth.header.stamp, &buf_filt_)) {
out.cloud_filtered = std::make_shared<const PointCloudXYZ>(buf_filt_);
if (gravity_.Align(buf_filt_, cam_to_base_, depth.header.stamp, &buf_align_)) {
out.cloud_aligned = std::make_shared<const PointCloudXYZ>(buf_align_);
}
}
}
const double ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - t0)
.count();
stats_.frames_out++;
stats_.last_ms = ms;
stats_.max_ms = std::max(stats_.max_ms, ms);
// Trung binh truot: du de bao cao, khong giu lich su.
stats_.avg_ms += (ms - stats_.avg_ms) * 0.05;
return out;
}
} // namespace vslam

View File

@@ -0,0 +1,15 @@
# Lop an toan.
#
# KHONG them dep ngoai nao, va do la co y: cang it phu thuoc, cang it thu co
# the keo no chet theo. Ban ROS chay rieng mot process voi respawn="true" vi
# ly do do; o day khong con process rieng, nen phai giu dep toi thieu de
# review duoc doc lap.
vslam_add_library(vslam_safety
PUBLIC_HDRS
safety_monitor.h
PUBLIC_DEPS
vslam_common
FIND_DEPS
vslam_common
)

View File

@@ -0,0 +1,196 @@
#ifndef VSLAM_SAFETY_MONITOR_H
#define VSLAM_SAFETY_MONITOR_H
// Lop an toan. Port tu robot_safety/src/safety_monitor_node.cpp cua vSLAM_ws.
//
// ================== PHU THUOC TOI THIEU LA CO Y ==================
// Lop nay CHI can: scan, cmd_vel, bumper, sieu am, co bao vuc.
// KHONG dung: TF, point cloud, ban do, SLAM.
//
// Cang it phu thuoc, cang it thu co the keo no chet theo. Neu no can TF thi
// TF hong se lam hong an toan -- dung dieu ta muon tranh.
//
// ================== KHAC BIET SO VOI BAN ROS ==================
// Ban ROS chay trong mot process rieng voi respawn="true", va do la cach no
// song sot khi slam_core segfault.
//
// Bo ROS thi khong con process rieng nua. Bu lai bang HAI thu:
// 1. Step() la HAM THUAN: khong I/O, khong doc dong ho, khong khoa. Cung
// dau vao cho cung dau ra. Vi vay kiem thu duoc TOAN BO 10 nhanh FSM --
// dieu ban ROS khong lam duoc.
// 2. Luong safety chay SCHED_FIFO cao nhat va KHONG chia se mutex nao voi
// luong slam (Rtabmap::process() chan 100-600 ms). Day la quy tac review,
// compiler khong bat duoc.
//
// ================== 3 LOP BAO VE ==================
// 1. Sieu am -> KINH va GUONG. LiDAR ToF 940nm va depth IR deu XUYEN QUA
// kinh. Day la cach duy nhat phat hien cua kinh.
// 2. LiDAR -> vat can phia truoc trong tam quet
// 3. Bumper -> chan cuoi, bit vung mu Min-Z ~22 cm ma camera khong thay
#include <cstdint>
#include <map>
#include <string>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
// Thu tu o day CHINH LA thu tu uu tien trong FSM. Nhanh nao khop truoc thi
// tra ve ngay, khong xet tiep.
enum class SafetyState : uint8_t {
kEstop = 0, // chot cung, can reset
kBumper = 1, // chot cung, can reset
kNoCmd = 2, // watchdog lenh dieu khien
kUsTimeout = 3, // mat du lieu sieu am
kUsBlocked = 4, // sieu am thay vat gan -- co the la KINH
kCliffStop = 5, // vuc phia truoc: chan TIEN, cho lui va xoay
kScanTimeout = 6, // mat du lieu LiDAR
kScanSparse = 7, // scan van toi nhung quat truoc khong con tia dung duoc
kScanStop = 8, // vat can gan -- chan tien
kScanSlow = 9, // vat can vua -- giam toc
kOk = 10,
};
const char* SafetyStateName(SafetyState s);
struct SafetyConfig {
// --- LiDAR ---
double stop_distance = 0.35;
double slow_distance = 0.80;
double slow_factor = 0.4;
double front_angle = 0.5; // nua goc quat truoc, rad (~28.6 do)
// Nguong duoi lay MAX cua hai nguon: cai driver khai, va cai ta biet la
// dung. Driver LakiBeam khai range_min = 0.0 (bug), ta van dung 0.05.
double min_valid_range = 0.05;
// So tia DUNG DUOC toi thieu trong quat truoc. Duoi nguong nay thi scan
// khong dang tin, du ban tin van toi dung nhip.
int min_front_rays = 20;
// --- Sieu am ---
double us_stop_distance = 0.30;
// --- Vuc ---
bool enable_cliff_stop = true;
double cliff_timeout = 1.0;
// Giu chan them bao lau sau lan bao vuc CUOI. Xem khoi comment lon trong
// safety_monitor.cc -- con so nay da tra gia bang mot lan di vao bac thang.
double cliff_hold = 3.0;
// --- Thoat khi bumper dang chot ---
//
// ⚠️ Chot bumper la dung -- va cham DA xay ra nen phai co nguoi xac nhan.
// Nhung chot khong duoc bien thanh BE TAC.
//
// Phep do bumper (ca that lan mo phong) kiem vanh robot o vi tri HIEN TAI.
// Robot dang ti vao vat can thi bumper van cham, nen no chot lai ngay sau
// moi lan reset. Cam het chuyen dong thi khong bao gio lui ra duoc, ma
// khong lui ra duoc thi khong bao gio reset duoc -- do la mot vong kin.
//
// Da do: sau khi lui vao tuong, robot khong nhuc nhich duoc 0.000 m theo
// BAT KY huong nao, qua 2 lan reset deu tra HTTP 200.
//
// Nen khi dang chot: TIEN bi ep ve 0 tuyet doi, con LUI va XOAY duoc phep o
// toc do thoat. Phia sau KHONG co cam bien nao che (quat LiDAR chi phu
// +-front_angle phia truoc), nen toc do nay phai cham.
double escape_linear = 0.10; // m/s, CHI cho chieu lui
double escape_angular = 0.4; // rad/s
// --- Chung ---
double sensor_timeout = 1.0;
double cmd_timeout = 0.5;
double max_linear = 0.35;
double max_angular = 0.8;
};
// Moi thu FSM can, dua vao tuong minh. KHONG co con tro toi driver, khong co
// dong ho -- do la ly do Step() kiem thu duoc.
struct SafetyInputs {
UnixTime now;
// Scan da qua ScanSanitizer. nullptr = chua co scan nao.
const LaserScan* scan = nullptr;
UnixTime scan_stamp;
const Twist* cmd = nullptr; // nullptr = chua co lenh nao
UnixTime cmd_stamp;
bool have_bumper = false;
bool bumper = false;
UnixTime bumper_stamp;
bool have_cliff = false;
bool cliff = false;
UnixTime cliff_stamp;
// Detector co THUC SU phan xet duoc khong, hay day la fail-safe luc mu.
//
// Hai thu nay khac nhau VE CHAT: "toi THAY mot cai vuc" so voi "toi khong
// thay san nen gia dinh co vuc". Chi cai thu hai moi co the duoc mot vat
// can gan GIAI THICH -- xem nhanh 4 trong Step().
bool cliff_judged = true;
// Tam gan nhat cua cua so nhin san (`cliff_detect.min_dist`). Duoi tam do
// camera khong thay gi -- vung mu HINH HOC, khong phai lua chon tham so.
double cliff_window_min = 1.10;
// Ten cam bien -> khoang cach (m). Rong = khong co sieu am nao lap dat.
std::map<std::string, double> ultrasonic;
UnixTime us_stamp;
};
struct SafetyOutput {
Twist cmd; // lenh DA loc, gui thang xuong base
SafetyState state = SafetyState::kOk;
std::string detail;
// So lieu quat truoc -- de hien thi va chan doan.
double min_front = 0.0; // INFINITY neu khong do duoc gi
int front_rays = 0; // tong so tia PHU song quat truoc
int front_blanked = 0; // so tia mang sentinel range_max + 1
int front_usable = 0; // front_rays - front_blanked
double us_min = 0.0;
};
struct SafetyStats {
uint64_t steps = 0;
uint64_t blocked_steps = 0; // so buoc lenh bi thay doi
std::map<SafetyState, uint64_t> state_counts;
};
class SafetyMonitor {
public:
explicit SafetyMonitor(SafetyConfig cfg = SafetyConfig());
// HAM THUAN: cung dau vao -> cung dau ra. Khong I/O, khong doc dong ho.
//
// Trang thai duy nhat mang qua cac lan goi la hai cai CHOT (e-stop, bumper)
// va moc thoi gian bao vuc cuoi -- ba thu do la ban chat co trang thai.
SafetyOutput Step(const SafetyInputs& in);
// Thay service std_srvs/Trigger cua ban ROS.
void Reset(); // bo chot bumper
void SetEstop(bool on);
bool estop() const { return estop_; }
bool bumper_latched() const { return bumper_latched_; }
const SafetyStats& stats() const { return stats_; }
private:
// Quet quat truoc. Tach rieng de kiem duoc doc lap voi FSM.
void ScanFan(const LaserScan& scan, SafetyOutput* out) const;
SafetyConfig cfg_;
bool estop_ = false;
bool bumper_latched_ = false;
// Lan doc bumper gan nhat, de Reset() noi duoc rang chot se dat lai ngay.
bool last_bumper_ = false;
UnixTime last_cliff_true_;
bool have_cliff_true_ = false;
SafetyStats stats_;
};
} // namespace vslam
#endif // VSLAM_SAFETY_MONITOR_H

View File

@@ -0,0 +1,323 @@
#include "vslam/safety_monitor.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "vslam/log.h"
namespace vslam {
const char* SafetyStateName(SafetyState s) {
switch (s) {
case SafetyState::kEstop: return "ESTOP";
case SafetyState::kBumper: return "BUMPER";
case SafetyState::kNoCmd: return "NO_CMD";
case SafetyState::kUsTimeout: return "US_TIMEOUT";
case SafetyState::kUsBlocked: return "US_BLOCKED";
case SafetyState::kCliffStop: return "CLIFF_STOP";
case SafetyState::kScanTimeout: return "SCAN_TIMEOUT";
case SafetyState::kScanSparse: return "SCAN_SPARSE";
case SafetyState::kScanStop: return "SCAN_STOP";
case SafetyState::kScanSlow: return "SCAN_SLOW";
case SafetyState::kOk: return "OK";
}
return "?";
}
SafetyMonitor::SafetyMonitor(SafetyConfig cfg) : cfg_(std::move(cfg)) {}
void SafetyMonitor::Reset() {
// ⚠️ Reset thanh cong KHONG co nghia la robot chay tiep duoc.
//
// Neu bumper van dang cham, chot se dat lai ngay o buoc sau. Truoc day reset
// tra ve am tham va nguoi van hanh bam lai nhieu lan ma khong hieu vi sao --
// cung lop loi voi chuyen nhan web noi "SLAM dang chay" khi no dang tat.
if (last_bumper_) {
VSLAM_WARN("safety: da bo chot bumper NHUNG bumper VAN dang cham -- no se "
"chot lai ngay. Lui ra khoi vat can truoc (lenh lui va xoay van "
"duoc phep khi dang chot).");
} else {
VSLAM_INFO("safety: da bo chot bumper");
}
bumper_latched_ = false;
}
void SafetyMonitor::SetEstop(bool on) {
if (on != estop_) {
VSLAM_WARN("safety: e-stop " << (on ? "BAT" : "GO"));
}
estop_ = on;
}
void SafetyMonitor::ScanFan(const LaserScan& scan, SafetyOutput* out) const {
double min_front = std::numeric_limits<double>::infinity();
int front_rays = 0;
int front_blanked = 0;
// Nguong duoi lay MAX cua hai nguon: cai driver khai, va cai ta biet la
// dung. Driver LakiBeam khai range_min = 0.0, ta van dung 0.05.
const double rmin = std::max(cfg_.min_valid_range,
static_cast<double>(scan.range_min));
for (size_t i = 0; i < scan.ranges.size(); ++i) {
const double a = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
if (std::fabs(a) > cfg_.front_angle) continue;
++front_rays;
const double r = scan.ranges[i];
// ==================================================================
// PHAN BIET "BI BLANK" VOI "KHONG CO GI TRONG TAM".
//
// Sector mask blank tia bang range_max + 1.0 -- tuc HUU HAN va LON HON
// range_max. Tia khong co phan xa that thi la inf, con tia khong do duoc
// thi la NaN.
//
// Neu dem nham hai thu nay lam mot thi robot dung giua sanh trong:
// khong vat nao trong 40 m -> moi tia inf -> "khong tia nao hop le" ->
// SCAN_SPARSE -> dung vinh vien giua mot can phong trong khong.
// ==================================================================
if (std::isfinite(r) && r > scan.range_max) {
++front_blanked;
continue;
}
if (!std::isfinite(r) || r < rmin) {
continue; // khong co phan xa, hoac qua gan -> khong dung de do
}
min_front = std::min(min_front, static_cast<double>(r));
}
out->front_rays = front_rays;
out->front_blanked = front_blanked;
out->front_usable = front_rays - front_blanked;
out->min_front = min_front;
}
SafetyOutput SafetyMonitor::Step(const SafetyInputs& in) {
SafetyOutput out; // cmd mac dinh = dung yen
out.us_min = std::numeric_limits<double>::infinity();
out.min_front = std::numeric_limits<double>::infinity();
stats_.steps++;
// Cap nhat chot bumper. Bumper la va cham DA XAY RA nen phai co nguoi xac
// nhan moi bo chot.
if (in.have_bumper) last_bumper_ = in.bumper;
if (in.have_bumper && in.bumper && !bumper_latched_) {
bumper_latched_ = true;
VSLAM_ERROR("safety: BUMPER KICH HOAT -- dung va chot. Goi reset de bo chot.");
}
// Ghi moc lan bao vuc cuoi. Xem khoi comment o nhanh CLIFF_STOP.
if (in.have_cliff && in.cliff) {
last_cliff_true_ = in.cliff_stamp;
have_cliff_true_ = true;
}
if (in.scan != nullptr) ScanFan(*in.scan, &out);
auto finish = [&](SafetyState s, std::string detail) {
out.state = s;
out.detail = std::move(detail);
stats_.state_counts[s]++;
if (s != SafetyState::kOk) stats_.blocked_steps++;
return out;
};
// --- 1. Chot cung ---------------------------------------------------
if (estop_) return finish(SafetyState::kEstop, "dung khan cap");
if (bumper_latched_) {
// ⚠️ Bumper KHONG BIET vat can o dau.
//
// `BumperReading` chi mang mot mat na cong tac; mo phong dung dung mot bit,
// va robot that cung khong hua se noi duoc huong. Nen "chan tien, cho lui"
// la an toan GIA: da do mot lan robot LUI vao tuong, va luc do duong thoat
// chinh la TIEN -- dung chieu bi chan.
//
// Thu biet huong la LiDAR. Nen giu nguyen cong quat truoc cho chieu tien,
// y het luc binh thuong, chi ha toc do xuong muc thoat. Chieu lui va phep
// xoay mo, dung bang phoi nhiem cua luc binh thuong (phia sau von khong co
// cam bien nao che).
out.cmd = Twist{};
if (in.cmd != nullptr) {
out.cmd.linear.x = std::max(-cfg_.escape_linear,
std::min(cfg_.escape_linear, in.cmd->linear.x));
out.cmd.angular.z =
std::max(-cfg_.escape_angular,
std::min(cfg_.escape_angular, in.cmd->angular.z));
// Tien chi duoc phep khi LiDAR XAC NHAN phia truoc trong. Khong co scan
// thi khong xac nhan duoc -> chan, khong doan.
if (out.cmd.linear.x > 0.0 &&
(in.scan == nullptr || out.front_usable < cfg_.min_front_rays ||
out.min_front < cfg_.stop_distance)) {
out.cmd.linear.x = 0.0;
}
}
// Chi tiet phai phan biet "DANG cham" voi "da cham roi roi ra": hai cai
// doi hoi hai hanh dong khac nhau cua nguoi van hanh.
return finish(SafetyState::kBumper,
(in.have_bumper && in.bumper)
? "bumper DANG cham -- lai cham de thoat roi reset"
: "bumper da cham -- can reset");
}
// --- 2. Watchdog lenh dieu khien ------------------------------------
if (in.cmd == nullptr ||
SecondsBetween(in.now, in.cmd_stamp) > cfg_.cmd_timeout) {
return finish(SafetyState::kNoCmd, "khong co lenh dieu khien");
}
// --- 3. Sieu am: KINH va GUONG --------------------------------------
// LiDAR ToF 940 nm va depth IR deu XUYEN QUA kinh. Day la cach duy nhat
// phat hien cua kinh -- khong thuat toan SLAM nao giai duoc viec nay.
// BA NGU NGHIA cua mot lan doc, y het tia laser:
// huu han = khoang cach do duoc
// inf = khong co tieng vong -> hanh lang RONG, HOP LE
// NaN = cam bien KHONG TRA LOI
// Gop NaN voi inf la xoa mat mot nhanh an toan.
int us_answering = 0;
for (const auto& kv : in.ultrasonic) {
if (std::isnan(kv.second)) continue; // khong tra loi, khong tinh
us_answering++;
out.us_min = std::min(out.us_min, kv.second);
}
if (!in.ultrasonic.empty()) {
// Hai kieu HONG KHAC NHAU, deu phai ra US_TIMEOUT:
//
// (a) MCU NGUNG gui ban ghi -> stamp cu dan.
// (b) MCU VAN gui nhung KHONG dau do nao tra loi -> stamp luon moi,
// nhung du lieu vo dung. Day la day cam bien bi dut, hoac ca cum
// chet. Truoc khi co nhanh nay, (b) HOAN TOAN VO HINH: map rong
// trong y het "khong lap sieu am", va robot chay tiep nhu khong co
// chuyen gi. Da phat hien bang kich ban hoi quy `us_dead`.
if (SecondsBetween(in.now, in.us_stamp) > cfg_.sensor_timeout) {
VSLAM_ERROR_THROTTLE(2.0, "safety: mat du lieu sieu am -> dung");
return finish(SafetyState::kUsTimeout, "mat du lieu sieu am");
}
if (us_answering == 0) {
VSLAM_ERROR_THROTTLE(2.0,
"safety: co " << in.ultrasonic.size()
<< " dau do sieu am nhung KHONG cai nao tra loi "
"-> dung. Kiem day cam bien.");
return finish(SafetyState::kUsTimeout, "sieu am khong tra loi");
}
}
if (out.us_min < cfg_.us_stop_distance) {
VSLAM_WARN_THROTTLE(1.0, "safety: sieu am " << out.us_min << " m (< "
<< cfg_.us_stop_distance
<< ") -- co the la KINH. Dung.");
return finish(SafetyState::kUsBlocked, "sieu am chan -- co the la kinh");
}
// --- 4. VUC / BAC THANG ----------------------------------------------
// KHONG chot (khong latch) nhu bumper: bumper la va cham DA XAY RA nen phai
// co nguoi xac nhan; vuc la thu robot co the tu lui ra khoi. Chot lai se lam
// robot ket cung truoc mep ma khong ai cuu.
//
// Chi chan TIEN, cho phep LUI va XOAY -- do la duong thoat duy nhat.
//
// Giu chan them cliff_hold giay sau lan bao vuc CUOI, khong chi khi co dang
// bat. Vuc bien mat khoi tam nhin cua camera khi lai gan hon 1.10 m, va
// CLIFF_STOP chi kich hoat dung khoanh khac co lenh tien -- robot xoay roi
// tien tung dot ngan nen lot qua duoc khe do.
// DA TRA GIA BANG MOT LAN DI THANG VAO BAC THANG.
const bool cliff_recent =
have_cliff_true_ &&
SecondsBetween(in.now, last_cliff_true_) <= cfg_.cliff_hold &&
SecondsBetween(in.now, in.cliff_stamp) <= cfg_.cliff_timeout + cfg_.cliff_hold;
const bool cliff_now = in.have_cliff && in.cliff &&
SecondsBetween(in.now, in.cliff_stamp) <= cfg_.cliff_timeout;
// ============ MU DA GIAI THICH DUOC ============
//
// Neu detector KHONG phan xet duoc (fail-safe) VA LiDAR thay mot vat can
// GAN HON diem bat dau cua so nhin san, thi su mu do da co loi giai: cua so
// nhin san nam SAU vat can, nen tat nhien camera khong thay san.
//
// Luc do dung robot vi "co the co vuc" la thua: chinh vat can do da kich
// SCAN_SLOW/SCAN_STOP o nhanh 6-7, tuc robot van duoc xu ly dung.
//
// ⚠️ Chi ap khi `!cliff_judged`. Neu detector THAY vuc that thi vat can
// khong giai thich duoc gi ca -- vuc va vat can co the cung ton tai, va
// CLIFF_STOP phai thang.
//
// Do duoc tren ban do benh vien that: robot cach tuong 0.5 m, cua so
// 1.1-2.5 m nam hoan toan sau tuong -> `few_samples` -> fail-safe -> robot
// ket cung. Khong co nhanh nay thi khong di duoc trong bat ky toa nha nao.
const bool blind_explained_by_obstacle =
!in.cliff_judged && std::isfinite(out.min_front) &&
out.min_front < in.cliff_window_min;
if (cfg_.enable_cliff_stop && (cliff_recent || cliff_now) &&
!blind_explained_by_obstacle && in.cmd->linear.x > 0.0) {
out.cmd = *in.cmd;
out.cmd.linear.x = 0.0; // chan tien, GIU angular de con xoay ra
out.cmd.angular.z = std::max(-cfg_.max_angular,
std::min(cfg_.max_angular, out.cmd.angular.z));
VSLAM_ERROR_THROTTLE(1.0,
"safety: VUC phia truoc -- chan tien. Lui hoac xoay de "
"thoat. Cam bien nay MU duoi ~1.1 m.");
return finish(SafetyState::kCliffStop, "vuc phia truoc -- chan tien");
}
// --- 5. LiDAR --------------------------------------------------------
if (in.scan != nullptr &&
SecondsBetween(in.now, in.scan_stamp) > cfg_.sensor_timeout) {
VSLAM_ERROR_THROTTLE(2.0, "safety: mat du lieu LiDAR -> dung");
return finish(SafetyState::kScanTimeout, "mat du lieu LiDAR");
}
// --- 6. Scan den deu nhung QUAT TRUOC BI CAT MAT ---------------------
// Khac han SCAN_TIMEOUT: ban tin van toi dung nhip, chi la quat truoc khong
// con tia dung duoc. Hai nguyen nhan:
// front_rays thap -> angle_min/max khong phu quat truoc
// blanked ~ toan bo -> sector mask cat nham bounds
//
// Sanh trong (moi tia inf) KHONG duoc tinh la loi: tia van phu song, chi la
// khong co phan xa. Do la ly do phai tru rieng phan bi blank.
if (in.scan != nullptr && out.front_usable < cfg_.min_front_rays) {
VSLAM_ERROR_THROTTLE(2.0,
"safety: quat truoc chi con "
<< out.front_usable << " tia dung duoc ("
<< out.front_rays << " tia phu song, "
<< out.front_blanked << " bi blank; can >= "
<< cfg_.min_front_rays
<< ") -- KHONG TIN DUOC, dung.");
return finish(SafetyState::kScanSparse, "quat truoc khong du tia dung duoc");
}
// --- 7. Vat can phia truoc -------------------------------------------
out.cmd = *in.cmd;
SafetyState state = SafetyState::kOk;
std::string detail;
if (in.scan != nullptr && out.cmd.linear.x > 0.0) { // chi xet khi dang tien
if (out.min_front < cfg_.stop_distance) {
out.cmd.linear.x = 0.0;
state = SafetyState::kScanStop;
detail = "vat can gan -- dung tien";
VSLAM_WARN_THROTTLE(1.0, "safety: vat can " << out.min_front
<< " m phia truoc -- dung tien");
} else if (out.min_front < cfg_.slow_distance) {
out.cmd.linear.x *= cfg_.slow_factor;
state = SafetyState::kScanSlow;
detail = "vat can vua -- giam toc";
}
}
// --- 8. Chan van toc --------------------------------------------------
out.cmd.linear.x = std::max(-cfg_.max_linear,
std::min(cfg_.max_linear, out.cmd.linear.x));
out.cmd.angular.z = std::max(-cfg_.max_angular,
std::min(cfg_.max_angular, out.cmd.angular.z));
return finish(state, std::move(detail));
}
} // namespace vslam

View File

@@ -0,0 +1,29 @@
# Bo mo phong -- thay Gazebo.
#
# Dep ngoai: chi yaml-cpp (doc map.yaml). Khong OpenGL, khong vat ly 3D,
# khong model database. Do la ca diem: Jetson AGX khong co gi de chay Gazebo,
# ma thu can kiem chung cho duong ong 2.5D chi la ban do 2D + raycast.
find_package(yaml-cpp REQUIRED)
vslam_add_library(vslam_sim
PUBLIC_HDRS
sim_source.h
occupancy_map_io.h
gazebo_world.h
PUBLIC_DEPS
vslam_common
vslam_drivers
FIND_DEPS
vslam_common
vslam_drivers
)
if(TARGET yaml-cpp::yaml-cpp)
target_link_libraries(vslam_sim PRIVATE yaml-cpp::yaml-cpp)
elseif(TARGET yaml-cpp)
target_link_libraries(vslam_sim PRIVATE yaml-cpp)
else()
target_include_directories(vslam_sim SYSTEM PRIVATE ${YAML_CPP_INCLUDE_DIR})
target_link_libraries(vslam_sim PRIVATE ${YAML_CPP_LIBRARIES})
endif()

View File

@@ -0,0 +1,152 @@
#ifndef VSLAM_GAZEBO_WORLD_H
#define VSLAM_GAZEBO_WORLD_H
// Doc file `.world` cua Gazebo va dung the gioi mo phong tu no.
//
// ================== VI SAO DOC WORLD CHU KHONG DOC .db ==================
// Luoi chiem dung xuat tu `map_hospital.db` co goc o cho robot BAT DAU phien
// quet, con file world o he toa do RIENG cua Gazebo. Do duoc: world trai rong
// x -12.4..12.4, y -31.9..19.5; luoi tu .db la x -17.1..9.2, y -49.6..8.5 --
// lech ~18 m theo y.
//
// Nen khong the "dan do dac cua world len luoi tu .db". Doc THANG world lam
// nguon su that thi ca ba thu -- luoi cho sim, mesh cho khung 3D, va tu the
// do dac -- deu o MOT he toa do, va khong can mot phep can chinh nao.
//
// ================== KHONG CAN PARSER XML DAY DU ==================
// Cau truc `.world` cua Gazebo rat deu:
//
// <model name="X">
// <include>
// <uri>model://Ten</uri>
// <static>true</static>
// <pose>x y z roll pitch yaw</pose>
// </include>
// </model>
//
// va `model.sdf` cua tung model chi tro toi mot file `.obj`. Mot bo quet the
// ~100 dong doc duoc ca hai, va tranh keo them mot dep XML vao `vslam_sim` --
// lib nay hien chi phu thuoc `vslam_common`.
#include <cstdint>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
// Mot the hien model trong world.
struct WorldModel {
std::string name; // ten the hien, vd "MetalCabinet_3"
std::string model_name; // ten model, vd "MetalCabinet"
// Duong dan tuyet doi toi mesh va chat lieu; rong neu khong tim thay.
std::string visual_obj;
std::string collision_obj;
// Tu the trong he toa do WORLD.
double x = 0.0, y = 0.0, z = 0.0;
double roll = 0.0, pitch = 0.0, yaw = 0.0;
// ⚠️ He so ti le cua `<mesh><scale>` trong model.sdf.
//
// File OBJ khong khai don vi, nen Gazebo lay ti le TU SDF. Trong bo model
// nay 27 model dung `<scale>`, phan lon la 0.01 (mesh ve bang CENTIMET) va
// co ca 0.00817 va `1 1 0.95`.
//
// Bo qua the nay lam mot chiec xe day 2.4 m thanh 236 m -- da do:
// `CGMClassic` mot minh ra bao loi 239 x 111 m, va ca the gioi phinh tu
// 25x51 m len 263x146 m.
double sx = 1.0, sy = 1.0, sz = 1.0;
};
struct GazeboWorld {
std::string world_path;
std::vector<WorldModel> models;
// Thu muc goc chua cac model da phan giai, de web phuc vu file tinh.
std::vector<std::string> model_roots;
};
// Doc `.world` va phan giai `model://` qua `model_paths`.
//
// `model_paths`: danh sach thu muc, moi cai chua cac thu muc model con (giong
// GAZEBO_MODEL_PATH). Rong thi thu $GAZEBO_MODEL_PATH roi ~/.gazebo/models.
//
// Model khong phan giai duoc KHONG lam ham that bai -- `ground_plane` va `sun`
// la built-in cua Gazebo, khong co tren dia, va mot the gioi thieu hai cai do
// van dung duoc. Chung duoc bo qua va dem vao `skipped`.
StatusResponse LoadGazeboWorld(const std::string& world_path,
const std::vector<std::string>& model_paths,
GazeboWorld* out, size_t* skipped = nullptr);
// Raster hoa mesh VA CHAM cua world thanh luoi chiem dung 2D.
//
// Chi lay tam giac nam trong dai do cao [z_min, z_max] so voi SAN: do la dai
// ma LiDAR 2D thuc su quet. Lay het moi do cao se bien ca mat san thanh vat
// can, va lay qua cao se bo lot ban ghe.
//
// `resolution` met/o. `pad` la vien trong them quanh bao loi, tinh bang met.
struct WorldRasterOptions {
double resolution = 0.05;
double z_min = 0.05; // tren mat san mot chut, de khong quet trung san
double z_max = 1.20; // duoi tran, tren dinh phan lon do dac
double pad = 1.0;
};
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out);
// ---------------------------------------------------------------------------
// Xuat hinh hoc cho khung 3D
// ---------------------------------------------------------------------------
//
// Khung 3D khong tai duoc file mesh goc: trinh duyet khong co bo doc COLLADA
// offline, va 149 texture PNG cua bo model nay tong cong 74 MB -- gui tung ay
// moi lan mo trang la khong chap nhan duoc.
//
// Nen phia C++ (von DA co bo doc) gui thang TAM GIAC. Hinh hoc duoc gop theo
// TEN MODEL chu khong theo the hien: world co 181 the hien nhung chi ~69 model
// khac nhau, nen 42 chiec ghe chi ton mot ban hinh hoc.
struct WorldMeshGeom {
std::string model_name;
// Mau than vat the, lay tu TEXTURE cua chinh model (xem
// tools/gen_model_colors.py). Mac dinh la xam men su -- dung cho
// KitchenSink va Toilet, hai model duy nhat trong world khong co texture.
uint8_t r = 214, g = 214, b = 210;
// 9 float moi tam giac (x,y,z) x 3, trong he MODEL: da ap `<scale>` nhung
// CHUA ap yaw/tinh tien cua the hien -- do la viec cua instance.
std::vector<float> tri;
};
struct WorldMeshInstance {
uint32_t geom = 0;
float x = 0, y = 0, z = 0, yaw = 0;
};
struct WorldMeshes {
std::vector<WorldMeshGeom> geoms;
std::vector<WorldMeshInstance> instances;
};
// `visual = true` lay mesh HIEN THI (nhieu tam giac, dep hon); false lay mesh
// VA CHAM, von it tam giac va khop chinh xac voi luoi chiem dung.
StatusResponse ExportWorldMeshes(const GazeboWorld& world, bool visual,
WorldMeshes* out);
// Gan mau cho tung hinh hoc tu bang `model_colors.json`.
//
// Thieu file hoac thieu model trong file KHONG phai loi: vat the do giu mau
// mac dinh. Tra ve so hinh hoc da duoc gan mau.
size_t ApplyModelColors(const std::string& json_path, WorldMeshes* io);
// Dong goi `WorldMeshes` thanh khoi nhi phan cho trinh duyet.
//
// "VSLW" | u32 version | u32 n_geom | u32 n_inst
// moi geom : u32 name_len | name | u8 r,g,b | u32 n_tri | n_tri*9 f32
// moi inst : u32 geom | f32 x,y,z,yaw
void EncodeWorldMeshes(const WorldMeshes& in, std::string* out);
} // namespace vslam
#endif // VSLAM_GAZEBO_WORLD_H

View File

@@ -0,0 +1,49 @@
#ifndef VSLAM_OCCUPANCY_MAP_IO_H
#define VSLAM_OCCUPANCY_MAP_IO_H
// Doc/ghi occupancy grid dang PGM + YAML -- dung dinh dang cua map_server ROS.
//
// Giu dinh dang cu co y: nguoi dung da quen no, `rtabmap-export` sinh ra no,
// va moi map cu trong vSLAM_ws/maps/ deu o dang nay. Bo ROS khong co nghia la
// phai bo moi thu ROS cham vao.
//
// map.yaml:
// image: map.pgm
// resolution: 0.05
// origin: [-5.0, -13.0, 0.0]
// negate: 0
// occupied_thresh: 0.65
// free_thresh: 0.196
//
// PGM P5 (nhi phan, 8 bit): 0 = den = bi chiem, 255 = trang = trong.
// Quy uoc nay NGUOC voi truc quan, va dao nguoc no la mot trong nhung loi
// hay gap nhat khi doc map -- ket qua la robot coi tuong la duong di.
#include <string>
#include "vslam/vslam_common.h"
namespace vslam {
struct MapLoadResult {
OccupancyGrid grid;
std::string image_path;
double occupied_thresh = 0.65;
double free_thresh = 0.196;
};
// Doc map.yaml va file PGM di kem. Duong dan anh trong YAML duoc hieu la
// tuong doi so voi thu muc chua YAML.
StatusResponse LoadOccupancyMap(const std::string& yaml_path, MapLoadResult* out);
// Ghi ra PGM + YAML. Dung cho tools/vslam_map_export.
StatusResponse SaveOccupancyMap(const OccupancyGrid& grid,
const std::string& yaml_path);
// Sinh mot the gioi tong hop: hanh lang chinh + phong hai ben.
// Dung khi chua co map that, de chay thu duong ong ngay lap tuc.
OccupancyGrid MakeSyntheticWorld(uint32_t width, uint32_t height, float resolution);
} // namespace vslam
#endif // VSLAM_OCCUPANCY_MAP_IO_H

View File

@@ -0,0 +1,339 @@
#ifndef VSLAM_SIM_SOURCE_H
#define VSLAM_SIM_SOURCE_H
// Bo mo phong -- thay Gazebo.
//
// ================== VI SAO KHONG PHAI GAZEBO ==================
// Bo ROS la mat gazebo_ros. Nhung ke ca con ROS thi Gazebo cung khong hop:
// world `hospital_three_floors.world` co 541 instance model, va `gpu_ray`
// 1081 tia @25 Hz duoc chon vi may dev co RTX 4060 -- Jetson AGX khong co thu
// do de tieu.
//
// Cai thuc su can de kiem chung duong ong 2.5D chi la: mot ban do 2D, mot
// robot vi sai, va phep raycast. Do la vai tram dong, chay duoc tren CPU, va
// KHONG can card do hoa.
//
// ================== VI SAO NO VUA VAN VAO KIEN TRUC ==================
// SimSource implement CHINH cac interface driver, y het ReplaySource. Nen
// vslam_node khong phan biet duoc ba nguon: phan cung that, file .vsr, hay mo
// phong. Khong co mot nhanh `if (sim)` nao trong logic -- day dung la dieu ma
// docs/ARCHITECTURE.md cua repo cu goi la "nguyen tac parity sim <-> real",
// nhung lan nay no duoc bao dam boi kieu du lieu chu khong boi ky luat.
//
// ================== CAI GI KHONG DUOC MO PHONG ==================
// docs/SIM_VS_REAL.md cua repo cu liet ke chinh xac nhung cho Gazebo "noi
// doi". Bo mo phong nay con noi doi NHIEU HON, va phai noi ro:
// * Khong co IR speckle, khong rolling shutter. Depth dropout CO mo phong
// nhung bang xac suat deu, tho hon nhieu so voi that (that thi tap trung
// o be mat toi, be mat bong va mep vat the).
// * Khong co anh infra1/infra2 -- stereo_odometry khong kiem duoc o day.
// * LiDAR khong bi nhieu boi be mat den hay guong. Khong co o kinh/guong
// (trong suot voi LiDAR VA voi depth), khong co vat can nho ra (mep ban).
// * Bien dang anh (distortion) khong mo phong: K la pinhole hoan hao.
// Nhung gi mo phong duoc KIEM CHUNG: dong hoc vi sai, tich phan odometry,
// EKF, SLAM 2D, lop an toan theo scan, camera depth (raycast 2.5D, Z-depth,
// co ban do do cao san nen cliff_detect kiem duoc), nghieng than bac hai, va
// toan bo duong ong du lieu.
#include <memory>
#include <string>
#include <vector>
#include "vslam/clock.h"
#include "vslam/gazebo_world.h"
#include "vslam/driver_interfaces.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct SimConfig {
// Ban do. Rong = dung MakeSyntheticWorld().
std::string map_yaml;
// File `.world` cua Gazebo. Uu tien hon `map_yaml`: luoi duoc raster hoa
// THANG tu mesh va cham, nen luoi cua sim, mesh cua khung 3D va tu the do
// dac deu o MOT he toa do -- xem `vslam/gazebo_world.h`.
std::string world_path;
std::vector<std::string> world_model_paths;
uint32_t synthetic_width = 600;
uint32_t synthetic_height = 400;
float synthetic_resolution = 0.05f;
// Vi tri xuat phat trong frame map.
double start_x = 0.0;
double start_y = 0.0;
double start_yaw = 0.0;
// Hat giong RNG. Co dinh => cung mot kich ban cho cung mot file .vsr, byte
// giong byte. Do la dieu kien de `tools/regress.sh` so ket qua duoc: neu
// ban ghi doi moi lan sinh thi moi khac biet deu la nhieu.
uint32_t seed = 1234;
// Hinh hoc robot. PHAI khop robot.yaml.
double wheel_radius = 0.075;
double wheel_separation = 0.36;
// LiDAR -- khop cau hinh LakiBeam 1L that.
double lidar_rate_hz = 25.0;
uint32_t lidar_samples = 1081;
double lidar_fov_rad = 4.712389; // 270 do
double lidar_range_min = 0.05;
double lidar_range_max = 40.0;
double lidar_x = 0.24; // vi tri tren robot, khop laser_joint
double lidar_z = 0.125;
double lidar_noise_stddev = 0.01;
// ================== CAMERA DEPTH ==================
// Gazebo mo phong depth bang libgazebo_ros_openni_kinect. Bo mo phong nay
// lam dieu tuong duong bang raycast 2.5D: ban do chiem dung duoc DUNG THANH
// tuong cao `wall_height`, va moi o co mot DO CAO SAN rieng.
//
// Do cao san la thu cho phep kiem `cliff_detect` -- o nao co floor_height
// AM la mot bac hut xuong. Khong co lop nay thi san tuyet doi phang va
// cliff_detect khong co gi de phat hien.
bool enable_depth_camera = true;
double camera_rate_hz = 30.0;
uint32_t depth_width = 640;
uint32_t depth_height = 480;
double depth_hfov_rad = 1.204; // 69 do, khop D410 that
double depth_near = 0.22; // Min-Z: vung mu truoc mui robot
double depth_far = 10.0;
// ============ NHIEU DEPTH: MO HINH STEREO ============
// sigma_d = sqrt(floor^2 + (d^2 * sigma_disp / (f*B))^2)
//
// Sai so tang theo BINH PHUONG khoang cach, vi depth stereo suy tu DO LECH
// PIXEL chu khong do truc tiep. Mot hang so (ban cu: 7 mm) sai o DANG chu
// khong chi o tri -- gan thi bi quan, xa thi lac quan gap 10 lan.
//
// `f` KHONG khai o day: no suy ra tu `depth_hfov_rad` va `depth_width`, de
// khong co hai nguon cho cung mot so.
//
// ⚠️ CA HAI so duoi CHUA XAC MINH tren thiet bi that:
// * `depth_baseline` 50 mm la UOC LUONG, khong co trong ban ghi datasheet
// nao. Sai 20% thi moi con so nhieu sai 20%.
// * `depth_disparity_noise_px` 0.1 px la gia tri DIEN HINH cua stereo
// block-matching, khong phai thong so do duoc cua D410.
// Do bang `rs-enumerate-devices -c` khi cam camera roi sua o day.
double depth_disparity_noise_px = 0.1;
double depth_baseline = 0.050; // m, khoang cach hai mat IR
// San nhieu gan: dien tu cam bien va luong tu hoa, khong mat khi d -> 0.
double depth_noise_floor = 0.002;
// Ty le diem anh KHONG co gia tri tra ve, mo phong depth dropout cua D410.
// Camera that mat diem o be mat toi, be mat bong, va o mep vat the.
double depth_dropout_rate = 0.0;
// Mo phong RUT DAY LiDAR: ngung phat scan tu giay `lidar_cut_at` trong
// bao lau. 0 = khong cat.
//
// Day la cach duy nhat chay duoc nhanh SCAN_TIMEOUT end-to-end. Tieu chi
// P4 ghi "rut day LiDAR -> SCAN_TIMEOUT < 1.1 s" nhung truoc kich ban nay
// khong co cach nao DO duoc no ngoai viec rut day that.
double lidar_cut_at = 0.0;
double lidar_cut_for = 0.0;
uint32_t depth_decimate = 2; // 640x480 -> 320x240, nhu crop_decimate
// Vi tri camera tren robot. Khop camera_joint cua robot.urdf.xacro.
double camera_x = 0.19;
double camera_z = 0.80;
double camera_pitch = 0.2618; // 15 do chuc xuong
double wall_height = 2.0; // tuong cao bao nhieu, tinh tu san
// ============ SIEU AM ============
// Dan cam bien phia truoc, goc tinh tu +X cua than (rad).
//
// ⚠️ Sieu am ton tai CHI vi mot ly do: KINH. Kinh vo hinh voi LiDAR (tia
// xuyen qua) va voi depth camera (IR xuyen qua), nhung phan xa am rat tot.
// Khong mo phong kinh thi nhanh US_BLOCKED cua FSM khong bao gio chay, va
// ca cam bien do tro thanh do trang tri.
bool enable_ultrasonic = true;
double us_rate_hz = 20.0;
double us_max_range = 2.0; // HC-SR04 thuc te ~4 m, nhung nhieu
double us_min_range = 0.03;
double us_beam_half_angle = 0.26; // ~15 do nua goc -- chum RAT rong
double us_noise_stddev = 0.005;
double us_z = 0.12; // cao bao nhieu so voi tam truc
// Goc cua tung dau do, rad, 0 = thang truoc.
std::vector<double> us_angles = {-0.35, 0.0, 0.35};
// Ti le mot lan doc bi mat (cam bien khong tra loi) -> NaN -> US_TIMEOUT.
double us_dropout_rate = 0.0;
// ============ BUMPER ============
// Cong tac va cham, chot cung. Kich khi than robot cham vat can.
bool enable_bumper = true;
double bumper_rate_hz = 50.0;
// Cong tac bumper NHO RA ngoai vo bao nhieu (m).
//
// ⚠️ PHAI > 0. Phep va cham cua bo mo phong TU CHOI chuyen dong khi vanh
// robot (ban kinh `robot_radius`) cham vat can, nen robot khong bao gio
// vao duoc vi tri ma mot bumper dat DUNG `robot_radius` nhin thay. Ket qua:
// nhanh BUMPER cua FSM khong bao gio chay.
//
// Bumper that cung nho ra that: no la mot cong tac gan tren vanh nhua, kich
// khi CHAM chu khong khi da lun vao. 3 cm la kich thuoc dien hinh.
double bumper_reach = 0.03;
// ============ KINH / GUONG ============
// O danh dau la kinh: LiDAR va depth XUYEN QUA (nhu khong co gi), sieu am
// THAY binh thuong. Dat bang SetGlass().
//
// Day la thu Gazebo cua repo cu KHONG mo phong duoc, va la ly do
// docs/SIM_VS_REAL.md cu phai ghi "kinh phai kiem bang du lieu that".
double glass_lidar_pass_rate = 1.0; // 1.0 = xuyen hoan toan
double imu_rate_hz = 200.0;
double gyro_noise_stddev = 4.9e-4;
double accel_noise_stddev = 6.9e-3;
// ================== NGHIENG THAN ROBOT ==================
// Robot that co giam xoc: tang toc lam no NGOC LEN, phanh lam no CHUI XUONG,
// quay gap lam no NGHIENG ra ngoai. Gazebo mo phong dieu nay qua vat ly
// tiep xuc; o day mo phong bang mot he lo xo - giam chan bac hai.
//
// KHONG CO NGHIENG THI KHONG THU THACH DUOC `gravity_align`. Logic cot loi
// cua no la TRU gia toc rieng cua robot truoc khi coi phan con lai la trong
// luc (axc = ax - a_lin, ayc = ay - v*w). San phang va robot cung nhac thi
// ca hai so hang do bang 0 va bo loc khong bao gio bi kiem tra.
//
// Gia tri mac dinh chon de dat ~2 do khi tang toc 0.3 m/s^2 -- do la muc
// docs/SIM_VS_REAL.md cua repo cu goi la "mon no chua tra ve tilt trong TF".
double tilt_pitch_per_accel = 0.12; // rad tren (m/s^2)
double tilt_roll_per_centrip = 0.08; // rad tren (m/s^2)
double tilt_natural_freq = 4.0; // rad/s, lo xo giam xoc
double tilt_damping = 0.7; // he so giam chan
// San doc: robot NGHIENG THEO dia hinh. Do cao san da co trong ban do do
// cao; do doc tinh tu chenh lech giua truoc va sau robot.
bool follow_terrain_slope = true;
double wheelbase_for_slope = 0.44; // khoang cach truoc-sau de do doc
double encoder_rate_hz = 50.0;
// ================== HAI LOAI TRUOT, RAT KHAC NHAU ==================
//
// slip_factor -- truot DOI XUNG: ca hai banh truot bang nhau.
// Encoder bao di xa hon thuc te, nhung KHONG sinh chenh lech quay.
// => slip_metric = |omega_encoder - gyro_z| KHONG PHAT HIEN DUOC.
// Day la mot gioi han THAT cua phuong phap so gyro, khong phai thieu sot
// cai dat. Muon bat loai nay can nguon thu hai (vd visual odometry).
//
// slip_differential -- truot VI SAI: mot banh truot nhieu hon banh kia.
// Sinh mot phep quay GIA ma gyro khong thay => slip_metric bat duoc.
// Day la loai ma wheel_odom duoc thiet ke de phat hien, va la loai da do
// duoc tren robot that o bai L6 (slip_metric 0.170 > nguong 0.15).
//
// San nha hang co nuoc va dau mo thi thuong la truot vi sai: mot banh vao
// vet dau truoc banh kia.
double slip_factor = 0.0;
double slip_differential = 0.0;
double slip_accel_threshold = 0.3; // m/s^2
// Gioi han dong hoc, khop diff_drive_controller cu.
double max_linear = 0.35;
double max_angular = 0.8;
double accel_limit = 0.3;
// DEADMAN: khong nhan lenh trong bao lau thi tu dung.
//
// Phai NGAN hon deadman phia JS (500 ms), de base dung truoc khi lop tren
// kip phan ung. Tab trinh duyet dong giua luc dang lai, hoac wifi rot, deu
// dan toi cung mot chuyen: khong con ai gui lenh nua.
double cmd_timeout_sec = 0.3;
// Va cham: robot dung lai khi cham tuong.
bool enable_collision = true;
double robot_radius = 0.24;
// 1.0 = thoi gian that. 0 = chay nhanh nhat co the (cho bai regression).
double speed = 1.0;
};
// So huu ca bon nguon, y het ReplaySource.
class SimSource {
public:
explicit SimSource(SimConfig cfg);
~SimSource();
SimSource(const SimSource&) = delete;
SimSource& operator=(const SimSource&) = delete;
StatusResponse Open();
ClockPtr clock() const;
LidarInterface* lidar();
McuInterface* mcu();
BaseInterface* base();
// Camera depth mo phong bang raycast 2.5D. Tra nullptr khi tat
// (enable_depth_camera = false) chu khong tra mot camera khong co anh.
CameraInterface* camera();
// Ban do do cao san, cung kich thuoc voi map(). Gia tri AM la mot bac hut
// xuong -- do la thu cliff_detect phai phat hien.
//
// Mac dinh phang (toan 0). Dung AddCliff() de tao bac.
const std::vector<float>& floor_height() const;
// Dat mot vung hinh chu nhat (toa do THE GIOI, met) thanh do cao `z`.
// z am = bac hut xuong / cau thang di xuong.
void SetFloorHeight(double x0, double y0, double x1, double y1, float z);
// Danh dau mot vung hinh chu nhat (toa do THE GIOI, met) la KINH.
//
// O kinh phai la o BI CHIEM trong ban do (data >= 50) -- kinh la vat can
// that, chi la vat can ma hai cam bien kia khong thay. Danh dau mot o
// trong la kinh khong co y nghia gi va bi bo qua.
void SetGlass(double x0, double y0, double x1, double y1, bool is_glass);
// Thay ban do sau khi Open(). CHI dung de dung kich ban thu nghiem -- no
// khong dong bo voi bat ky thu gi dang chay, nen goi truoc khi Run().
void SetMapForTest(const OccupancyGrid& m);
// Model doc duoc tu `.world`; rong neu khong chay tu world. Khung 3D dung
// no de ve do dac that thay vi khoi hop dung tu luoi.
const GazeboWorld& world() const;
const std::vector<uint8_t>& glass_mask() const;
// Cham vao vat can chua (bumper THAT dang bi nhan).
bool true_bumper() const;
// Ban do dung de raycast. Cung la ban do "that" ma SLAM se phai dung lai.
const OccupancyGrid& map() const;
// Do nghieng THAT cua than robot (rad). CHI dung de danh gia -- khong
// estimator nao duoc doc. `gravity_align` phai TU uoc luong hai so nay tu
// IMU, va day la dap an de cham diem.
void true_tilt(double* roll, double* pitch) const;
// Pose that cua robot. CHI dung de danh gia -- khong estimator nao duoc
// doc ham nay. Day la tuong duong cua /ground_truth/odom trong repo cu.
Pose2D ground_truth() const;
// Chay mo phong. Chan cho toi khi RequestStop().
void Run();
// Chay dung `seconds` thoi gian mo phong roi dung. Dung cho test.
void RunFor(double seconds);
void RequestStop();
struct Stats {
uint64_t scans = 0;
uint64_t imu = 0;
uint64_t encoder = 0;
uint64_t camera_frames = 0;
uint64_t collisions = 0;
double sim_time_sec = 0.0;
double distance_travelled = 0.0;
};
Stats stats() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace vslam
#endif // VSLAM_SIM_SOURCE_H

View File

@@ -0,0 +1,863 @@
#include "vslam/gazebo_world.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <map>
#include <sstream>
#include <sys/stat.h>
#include <yaml-cpp/yaml.h>
#include "vslam/log.h"
namespace vslam {
namespace {
bool FileExists(const std::string& p) {
struct stat st;
return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISREG(st.st_mode);
}
bool DirExists(const std::string& p) {
struct stat st;
return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
std::string ReadFile(const std::string& p) {
std::ifstream f(p);
if (!f) return "";
std::ostringstream o;
o << f.rdbuf();
return o.str();
}
// Lay noi dung cua the <tag> DAU TIEN tu vi tri `from`. Tra chuoi rong neu
// khong co. `end_out` nhan vi tri ngay sau the dong.
//
// Du cho cau truc rat deu cua SDF; khong nham lam mot parser XML tong quat.
std::string Tag(const std::string& s, const std::string& tag, size_t from,
size_t* end_out = nullptr) {
const std::string open = "<" + tag + ">";
const std::string close = "</" + tag + ">";
const size_t a = s.find(open, from);
if (a == std::string::npos) return "";
const size_t b = s.find(close, a);
if (b == std::string::npos) return "";
if (end_out) *end_out = b + close.size();
return s.substr(a + open.size(), b - a - open.size());
}
std::string Trim(const std::string& s) {
const size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) return "";
const size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
// "x y z roll pitch yaw" -> sau so. Thieu thi de 0.
void ParsePose(const std::string& s, WorldModel* m) {
std::istringstream in(s);
double v[6] = {0, 0, 0, 0, 0, 0};
for (int i = 0; i < 6 && (in >> v[i]); ++i) {}
m->x = v[0]; m->y = v[1]; m->z = v[2];
m->roll = v[3]; m->pitch = v[4]; m->yaw = v[5];
}
std::vector<std::string> DefaultModelPaths() {
std::vector<std::string> out;
if (const char* env = std::getenv("GAZEBO_MODEL_PATH")) {
std::string s(env), cur;
std::istringstream in(s);
while (std::getline(in, cur, ':')) if (!cur.empty()) out.push_back(cur);
}
if (const char* home = std::getenv("HOME")) {
// Cho mac dinh cua Gazebo, va cho ma repo nay that su de model.
out.push_back(std::string(home) + "/.gazebo/models");
out.push_back(std::string(home) + "/gazebo_models/aws_hospital_fuel");
out.push_back(std::string(home) + "/gazebo_models/aws_hospital");
}
return out;
}
// `model://Ten` hoac `model://Ten/meshes/x.obj` -> duong dan tuyet doi.
std::string ResolveModelUri(const std::string& uri,
const std::vector<std::string>& roots,
std::string* root_used) {
const std::string prefix = "model://";
if (uri.compare(0, prefix.size(), prefix) != 0) return "";
const std::string rel = uri.substr(prefix.size());
for (const std::string& r : roots) {
const std::string p = r + "/" + rel;
if (FileExists(p) || DirExists(p)) {
if (root_used) *root_used = r;
return p;
}
}
return "";
}
} // namespace
StatusResponse LoadGazeboWorld(const std::string& world_path,
const std::vector<std::string>& model_paths,
GazeboWorld* out, size_t* skipped) {
const std::string src = ReadFile(world_path);
if (src.empty()) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong doc duoc file world: " + world_path);
}
std::vector<std::string> roots = model_paths;
if (roots.empty()) roots = DefaultModelPaths();
// Bo cac thu muc khong ton tai -- de thong bao loi ben duoi khong liet ke
// mot dong duong dan vo nghia.
roots.erase(std::remove_if(roots.begin(), roots.end(),
[](const std::string& p) { return !DirExists(p); }),
roots.end());
if (roots.empty()) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong tim thay thu muc model nao. Dat GAZEBO_MODEL_PATH, hoac de "
"model o ~/.gazebo/models.");
}
out->world_path = world_path;
out->models.clear();
size_t skip = 0;
// Quet tung the <model name="...">.
size_t pos = 0;
const std::string kModelOpen = "<model name=";
while ((pos = src.find(kModelOpen, pos)) != std::string::npos) {
const size_t name_a = src.find('"', pos);
const size_t name_b = name_a == std::string::npos
? std::string::npos : src.find('"', name_a + 1);
if (name_b == std::string::npos) break;
WorldModel m;
m.name = src.substr(name_a + 1, name_b - name_a - 1);
// Khoi cua model nay ket thuc o </model> gan nhat.
const size_t block_end = src.find("</model>", name_b);
if (block_end == std::string::npos) break;
const std::string block = src.substr(name_b, block_end - name_b);
const std::string uri = Trim(Tag(block, "uri", 0));
ParsePose(Tag(block, "pose", 0), &m);
pos = block_end + 8;
if (uri.empty()) { skip++; continue; }
m.model_name = uri.substr(uri.rfind('/') + 1);
std::string root;
const std::string dir = ResolveModelUri(uri, roots, &root);
if (dir.empty()) {
// `ground_plane` va `sun` la built-in cua Gazebo, khong co tren dia.
// Bo qua chung la DUNG, khong phai loi.
skip++;
continue;
}
if (std::find(out->model_roots.begin(), out->model_roots.end(), root) ==
out->model_roots.end()) {
out->model_roots.push_back(root);
}
// model.sdf tro toi mesh. Lay ca visual lan collision: chung thuong la
// cung mot file, nhung khi khac nhau thi collision la ban da giam da
// giac -- dung cai do de raster hoa se nhanh hon nhieu.
const std::string sdf = ReadFile(dir + "/model.sdf");
if (!sdf.empty()) {
size_t vp = sdf.find("<visual");
if (vp != std::string::npos) {
const std::string u = Trim(Tag(sdf, "uri", vp));
m.visual_obj = ResolveModelUri(u, roots, nullptr);
}
size_t cp = sdf.find("<collision");
if (cp != std::string::npos) {
const std::string u = Trim(Tag(sdf, "uri", cp));
m.collision_obj = ResolveModelUri(u, roots, nullptr);
}
// `<scale>` nam trong khoi <mesh>. Lay cua collision truoc, khong co
// thi cua visual -- hai cai hau nhu luon giong nhau.
{
size_t sp = (cp != std::string::npos) ? cp : vp;
if (sp != std::string::npos) {
const std::string sc = Trim(Tag(sdf, "scale", sp));
std::istringstream in(sc);
double v[3] = {1, 1, 1};
int n = 0;
while (n < 3 && (in >> v[n])) n++;
if (n == 3) { m.sx = v[0]; m.sy = v[1]; m.sz = v[2]; }
else if (n == 1) { m.sx = m.sy = m.sz = v[0]; }
}
}
}
// Khong co collision rieng thi dung visual -- van tot hon la bo qua han
// mot buc tuong.
if (m.collision_obj.empty()) m.collision_obj = m.visual_obj;
if (m.visual_obj.empty()) m.visual_obj = m.collision_obj;
// ⚠️ File world nay co san pose HONG.
//
// `StorageRack_1` mang `<pose>9.07 -10.36 -7.57769e+08 ...>`: mot vat da
// roi xuyen san trong mot phien Gazebo nao do roi world duoc luu lai.
// Gazebo cung khong hien chung -- chung o cach mat dat 757 nghin km.
//
// Khong loc thi luoi van dung (tam giac roi ngoai dai z) nhung khung 3D
// cap phat instance cho vat khong bao gio thay duoc, va moi phep tinh bao
// loi deu vo nghia.
if (std::fabs(m.x) > 1000.0 || std::fabs(m.y) > 1000.0 ||
std::fabs(m.z) > 1000.0) {
VSLAM_WARN("world: bo model " << m.name << " -- pose vo ly ("
<< m.x << ", " << m.y << ", " << m.z << ")");
skip++;
continue;
}
out->models.push_back(std::move(m));
}
if (skipped) *skipped = skip;
VSLAM_INFO("world " << world_path << ": " << out->models.size()
<< " model phan giai duoc"
<< (skip ? ", bo qua " + std::to_string(skip) +
" (ground_plane/sun la built-in)"
: ""));
if (out->models.empty()) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
world_path + ": khong phan giai duoc model nao");
}
return StatusResponse::Ok();
}
// ---------------------------------------------------------------------------
// Raster hoa
// ---------------------------------------------------------------------------
namespace {
struct Tri { double x[3], y[3], z[3]; };
// Ma tran 4x4 hang-chinh, chi dung cho phep bien doi affine cua COLLADA.
struct Mat4 {
double m[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
};
Mat4 MatMul(const Mat4& a, const Mat4& b) {
Mat4 r;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j) {
double s = 0;
for (int k = 0; k < 4; ++k) s += a.m[i * 4 + k] * b.m[k * 4 + j];
r.m[i * 4 + j] = s;
}
return r;
}
void MatApply(const Mat4& t, double* x, double* y, double* z) {
const double px = *x, py = *y, pz = *z;
*x = t.m[0] * px + t.m[1] * py + t.m[2] * pz + t.m[3];
*y = t.m[4] * px + t.m[5] * py + t.m[6] * pz + t.m[7];
*z = t.m[8] * px + t.m[9] * py + t.m[10] * pz + t.m[11];
}
Mat4 MakeTranslate(double x, double y, double z) {
Mat4 t;
t.m[3] = x; t.m[7] = y; t.m[11] = z;
return t;
}
// Quay quanh truc (ax,ay,az) mot goc `deg` DO -- COLLADA dung do, khong radian.
Mat4 MakeRotate(double ax, double ay, double az, double deg) {
const double n = std::sqrt(ax * ax + ay * ay + az * az);
Mat4 t;
if (n < 1e-12) return t;
ax /= n; ay /= n; az /= n;
const double a = deg * M_PI / 180.0, c = std::cos(a), s = std::sin(a), k = 1 - c;
t.m[0] = c + ax*ax*k; t.m[1] = ax*ay*k - az*s; t.m[2] = ax*az*k + ay*s;
t.m[4] = ay*ax*k + az*s; t.m[5] = c + ay*ay*k; t.m[6] = ay*az*k - ax*s;
t.m[8] = az*ax*k - ay*s; t.m[9] = az*ay*k + ax*s; t.m[10] = c + az*az*k;
return t;
}
Mat4 MakeScale(double x, double y, double z) {
Mat4 t;
t.m[0] = x; t.m[5] = y; t.m[10] = z;
return t;
}
std::vector<double> ParseFloats(const std::string& s) {
std::vector<double> v;
std::istringstream in(s);
double d;
while (in >> d) v.push_back(d);
return v;
}
// Lay gia tri thuoc tinh `attr` cua the bat dau tai `tag_pos`.
std::string Attr(const std::string& s, size_t tag_pos, const std::string& attr) {
const size_t end = s.find('>', tag_pos);
if (end == std::string::npos) return "";
const size_t a = s.find(attr + "=\"", tag_pos);
if (a == std::string::npos || a > end) return "";
const size_t b = a + attr.size() + 2;
const size_t c = s.find('"', b);
if (c == std::string::npos) return "";
return s.substr(b, c - b);
}
// Doc tam giac tu file COLLADA (.dae).
//
// ⚠️ QUY UOC NAM TRONG TUNG FILE, KHONG PHAI TOAN CUC.
//
// Cac mesh `.obj` cua bo model nay la Z-UP, don vi MET. Nhung `.dae` cua
// tuong/san lai la:
// <unit meter="0.01" name="centimeter"/>
// <up_axis>Y_UP</up_axis>
// Ap mot quy uoc chung cho ca hai lam luoi ra la RAC ma van "trong nhu co du
// lieu": da do mot lan ra luoi 5235x5942 o (262 x 297 m) cho mot toa nha chi
// rong 25 x 51 m.
//
// Ho tro tap con thuc su xuat hien trong bo model AWS: <polylist> va
// <triangles>, input co offset, va phep bien doi cua <node> (translate /
// rotate truc-goc theo DO / scale).
// So duoi file KHONG phan biet hoa thuong.
//
// ⚠️ Bo model nay tron ca `.dae` lan `.DAE`: 15 model `aws_robomaker_
// residential_*` va `warehouse_*` dung chu hoa. So phan biet hoa thuong lam
// chung roi vao bo doc OBJ va HONG IM LANG -- khong loi, khong canh bao, chi
// la sofa/tu lanh/tranh tuong bien mat khoi ca khung 3D LAN luoi chiem dung.
bool IsDae(const std::string& p) {
if (p.size() < 4) return false;
const std::string e = p.substr(p.size() - 4);
return (e[0] == '.') && (e[1] == 'd' || e[1] == 'D') &&
(e[2] == 'a' || e[2] == 'A') && (e[3] == 'e' || e[3] == 'E');
}
bool ReadDaeTriangles(const std::string& path, std::vector<Tri>* out) {
const std::string s = ReadFile(path);
if (s.empty()) return false;
// --- don vi va truc len ---
double unit = 1.0;
{
const size_t u = s.find("<unit");
if (u != std::string::npos) {
const std::string v = Attr(s, u, "meter");
if (!v.empty()) unit = std::atof(v.c_str());
}
}
// --- source id -> mang float ---
std::map<std::string, std::vector<double>> sources;
for (size_t p = 0; (p = s.find("<source", p)) != std::string::npos;) {
const std::string id = Attr(s, p, "id");
size_t fa = s.find("<float_array", p);
const size_t next_src = s.find("<source", p + 1);
if (fa != std::string::npos && (next_src == std::string::npos || fa < next_src)) {
const size_t open_end = s.find('>', fa);
const size_t close = s.find("</float_array>", open_end);
if (open_end != std::string::npos && close != std::string::npos && !id.empty()) {
sources[id] = ParseFloats(s.substr(open_end + 1, close - open_end - 1));
}
}
p += 7;
}
// --- vertices id -> source id cua POSITION ---
std::map<std::string, std::string> vert_to_src;
for (size_t p = 0; (p = s.find("<vertices", p)) != std::string::npos;) {
const std::string id = Attr(s, p, "id");
const size_t in = s.find("<input", p);
const size_t close = s.find("</vertices>", p);
if (in != std::string::npos && close != std::string::npos && in < close) {
std::string src = Attr(s, in, "source");
if (!src.empty() && src[0] == '#') src.erase(0, 1);
if (!id.empty()) vert_to_src[id] = src;
}
p += 9;
}
// --- phep bien doi cua node, theo id geometry duoc instance ben trong ---
std::map<std::string, Mat4> geom_xform;
for (size_t p = 0; (p = s.find("<node", p)) != std::string::npos;) {
const size_t node_end = s.find("</node>", p);
const size_t limit = node_end == std::string::npos ? s.size() : node_end;
Mat4 t;
// Thu tu ap la thu tu XUAT HIEN trong file -- COLLADA quy dinh vay.
//
// ⚠️ `<matrix>` KHONG the bo qua. Bo model nay co hai ho file: ho xuat tu
// Blender dung translate/rotate/scale, ho xuat tu 3ds Max dung MOT the
// `<matrix>`. Bo qua the do lam ti le sai tu 10x den 100x ma khong mot
// canh bao nao -- da do sofa ra 24.4 m va buc tranh ra 5 cm, ca hai trong
// file khai `<unit meter="0.01">` y het cac file dung.
for (size_t q = p; q < limit;) {
const size_t tr = s.find("<translate", q), ro = s.find("<rotate", q),
sc = s.find("<scale", q), mx = s.find("<matrix", q);
size_t nxt = std::min({tr == std::string::npos ? limit : tr,
ro == std::string::npos ? limit : ro,
sc == std::string::npos ? limit : sc,
mx == std::string::npos ? limit : mx});
if (nxt >= limit) break;
const size_t oe = s.find('>', nxt), ce = s.find('<', oe + 1);
const std::vector<double> v = ParseFloats(s.substr(oe + 1, ce - oe - 1));
if (nxt == tr && v.size() >= 3) t = MatMul(t, MakeTranslate(v[0], v[1], v[2]));
else if (nxt == ro && v.size() >= 4) t = MatMul(t, MakeRotate(v[0], v[1], v[2], v[3]));
else if (nxt == sc && v.size() >= 3) t = MatMul(t, MakeScale(v[0], v[1], v[2]));
else if (nxt == mx && v.size() >= 16) {
// COLLADA ghi ma tran theo HANG, cung quy uoc voi Mat4 o day.
Mat4 mm;
for (int i = 0; i < 16; ++i) mm.m[i] = v[static_cast<size_t>(i)];
t = MatMul(t, mm);
}
q = ce;
}
for (size_t g = p; (g = s.find("<instance_geometry", g)) != std::string::npos &&
g < limit;) {
std::string url = Attr(s, g, "url");
if (!url.empty() && url[0] == '#') url.erase(0, 1);
if (!url.empty()) geom_xform[url] = t;
g += 18;
}
p += 5;
}
// --- geometry -> tam giac ---
size_t before = out->size();
for (size_t p = 0; (p = s.find("<geometry", p)) != std::string::npos;) {
const std::string gid = Attr(s, p, "id");
const size_t gend = s.find("</geometry>", p);
const size_t limit = gend == std::string::npos ? s.size() : gend;
Mat4 xf;
auto it = geom_xform.find(gid);
if (it != geom_xform.end()) xf = it->second;
// ⚠️ `<up_axis>` cua bo model nay PHAI BI BO QUA.
//
// Moi file deu khai `<up_axis>Y_UP`, nhung do la noi ve he toa do cua bo
// XUAT, khong phai cua du lieu trong file. Bo xuat nay da nuong phep doi
// truc vao node goc, va chi nuong KHI CAN:
//
// walls_collision ID3 : dinh (56.12, 3.00, 25.12) -- Y-up that
// node co `0 1 0 90` + `0 0 1 -270` de doi truc
// walls_visual ID43: dinh (25.12, 56.12, 3.00) -- DA la Z-up
// node RONG, khong can doi gi
//
// Cung mot buc tuong, hai file, hai cach. Ap them `<up_axis>` lam cai thu
// hai bi lat: buc tuong 3 m thanh mot thanh DUNG DUNG cao 56 m giua san.
//
// Tung thu doan theo ma tran node ("node don vi thi lat") -- sai chinh o
// ID43. Node don vi o day nghia la "khong can doi", khong phai "chua doi".
for (size_t q = p; q < limit;) {
const size_t pl = s.find("<polylist", q), trg = s.find("<triangles", q);
size_t prim = std::min(pl == std::string::npos ? limit : pl,
trg == std::string::npos ? limit : trg);
if (prim >= limit) break;
const bool is_poly = (prim == pl);
const size_t pend = s.find(is_poly ? "</polylist>" : "</triangles>", prim);
if (pend == std::string::npos) break;
// Tim input VERTEX va stride (offset lon nhat + 1).
int vert_off = -1, stride = 1;
std::string vsrc;
for (size_t i = prim; (i = s.find("<input", i)) != std::string::npos && i < pend;) {
const std::string off = Attr(s, i, "offset");
if (!off.empty()) stride = std::max(stride, std::atoi(off.c_str()) + 1);
if (Attr(s, i, "semantic") == "VERTEX") {
vert_off = off.empty() ? 0 : std::atoi(off.c_str());
vsrc = Attr(s, i, "source");
if (!vsrc.empty() && vsrc[0] == '#') vsrc.erase(0, 1);
}
i += 6;
}
if (vert_off < 0) { q = pend; continue; }
auto vt = vert_to_src.find(vsrc);
const std::string psrc = vt != vert_to_src.end() ? vt->second : vsrc;
auto ps = sources.find(psrc);
if (ps == sources.end()) { q = pend; continue; }
const std::vector<double>& pos = ps->second;
std::vector<double> vcount;
if (is_poly) {
const size_t vc = s.find("<vcount>", prim);
if (vc != std::string::npos && vc < pend) {
const size_t e = s.find("</vcount>", vc);
vcount = ParseFloats(s.substr(vc + 8, e - vc - 8));
}
}
const size_t pp = s.find("<p>", prim);
if (pp == std::string::npos || pp > pend) { q = pend; continue; }
const size_t pe = s.find("</p>", pp);
const std::vector<double> idx = ParseFloats(s.substr(pp + 3, pe - pp - 3));
auto vertex = [&](size_t n, double* x, double* y, double* z) {
const size_t vi = static_cast<size_t>(idx[n * stride + vert_off]) * 3;
if (vi + 2 >= pos.size()) return false;
// ⚠️ THU TU: ap ma tran node TRUOC, roi moi doi don vi.
//
// `<translate>` cua node nam trong CUNG don vi cua file (o day la
// centimet). Nhan `unit` vao dinh truoc roi ap mot translate tinh
// bang cm se coi 5000 cm thanh 5000 MET -- da do mot lan ra luoi
// 263 x 146 m cho mot toa nha 25 x 51 m.
double px = pos[vi], py = pos[vi + 1], pz = pos[vi + 2];
MatApply(xf, &px, &py, &pz);
px *= unit; py *= unit; pz *= unit;
// Y_UP -> Z_UP cua ROS: (x, y, z)_dae -> (x, -z, y)
*x = px; *y = py; *z = pz;
return true;
};
const size_t nvert = stride > 0 ? idx.size() / stride : 0;
if (is_poly && !vcount.empty()) {
size_t base = 0;
for (double cd : vcount) {
const size_t c = static_cast<size_t>(cd);
for (size_t k = 2; k < c && base + k < nvert; ++k) {
Tri t;
bool ok = vertex(base, &t.x[0], &t.y[0], &t.z[0]) &&
vertex(base + k - 1, &t.x[1], &t.y[1], &t.z[1]) &&
vertex(base + k, &t.x[2], &t.y[2], &t.z[2]);
if (ok) out->push_back(t);
}
base += c;
}
} else {
for (size_t k = 0; k + 2 < nvert; k += 3) {
Tri t;
bool ok = vertex(k, &t.x[0], &t.y[0], &t.z[0]) &&
vertex(k + 1, &t.x[1], &t.y[1], &t.z[1]) &&
vertex(k + 2, &t.x[2], &t.y[2], &t.z[2]);
if (ok) out->push_back(t);
}
}
q = pend;
}
p = limit;
}
return out->size() > before;
}
// Doc tam giac tu file OBJ. Chi can `v` va `f`; bo qua vt/vn/usemtl.
//
// OBJ danh chi so tu 1 va cho phep chi so AM (tinh nguoc tu cuoi). Bo qua
// chi so am se lam mot so mesh mat mat -- xu ly ca hai.
bool ReadObjTriangles(const std::string& path, std::vector<Tri>* out) {
std::ifstream f(path);
if (!f) return false;
std::vector<std::array<double, 3>> v;
std::string line;
while (std::getline(f, line)) {
if (line.size() < 2) continue;
if (line[0] == 'v' && line[1] == ' ') {
std::istringstream in(line.substr(2));
std::array<double, 3> p{0, 0, 0};
in >> p[0] >> p[1] >> p[2];
v.push_back(p);
} else if (line[0] == 'f' && line[1] == ' ') {
std::istringstream in(line.substr(2));
std::string tok;
std::vector<int> idx;
while (in >> tok) {
// "a", "a/b", "a//c", "a/b/c" -- chi lay phan truoc dau '/'.
const size_t slash = tok.find('/');
const std::string num = slash == std::string::npos ? tok : tok.substr(0, slash);
if (num.empty()) continue;
int i = std::atoi(num.c_str());
if (i > 0) i -= 1;
else if (i < 0) i = static_cast<int>(v.size()) + i;
else continue;
if (i >= 0 && i < static_cast<int>(v.size())) idx.push_back(i);
}
// Quat va n-giac: chia thanh quat tam giac.
for (size_t k = 2; k < idx.size(); ++k) {
Tri t;
const int a = idx[0], b = idx[k - 1], c = idx[k];
t.x[0] = v[a][0]; t.y[0] = v[a][1]; t.z[0] = v[a][2];
t.x[1] = v[b][0]; t.y[1] = v[b][1]; t.z[1] = v[b][2];
t.x[2] = v[c][0]; t.y[2] = v[c][1]; t.z[2] = v[c][2];
out->push_back(t);
}
}
}
return true;
}
} // namespace
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out) {
if (!(opt.resolution > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"resolution phai duong");
}
// --- Luot 1: bao loi ---
double minx = 1e18, maxx = -1e18, miny = 1e18, maxy = -1e18;
size_t n_tri = 0, n_mesh = 0;
struct Loaded { const WorldModel* m; std::vector<Tri> tris; };
std::vector<Loaded> loaded;
loaded.reserve(world.models.size());
for (const WorldModel& m : world.models) {
if (m.collision_obj.empty()) continue;
Loaded L;
L.m = &m;
// Chon bo doc theo DUOI FILE: bo model nay tron ca .obj lan .dae, va moi
// dinh dang mang quy uoc rieng (xem ghi chu o ReadDaeTriangles).
const std::string& cp = m.collision_obj;
const bool ok = IsDae(cp) ? ReadDaeTriangles(cp, &L.tris)
: ReadObjTriangles(cp, &L.tris);
if (!ok) {
VSLAM_WARN("world: khong doc duoc mesh " << cp << " cua model "
<< m.model_name << " -- vat the nay VANG MAT khoi luoi");
continue;
}
if (L.tris.empty()) continue;
n_mesh++;
n_tri += L.tris.size();
const double cy = std::cos(m.yaw), sny = std::sin(m.yaw);
for (Tri& t : L.tris) {
for (int k = 0; k < 3; ++k) {
// Ti le TRUOC khi quay va tinh tien -- `<scale>` la cua mesh, khong
// phai cua the gioi.
t.x[k] *= m.sx; t.y[k] *= m.sy; t.z[k] *= m.sz;
// Bo doc da tra ve he ROS (Z-len, met) roi -- KHONG doi truc them o
// day. Quy uoc nam trong TUNG FILE (.obj Z-up met, .dae Y-up cm), va
// ap them mot phep doi chung se lam hong dung mot nua so mesh.
const double wx = t.x[k], wy = t.y[k], wz = t.z[k];
// Chi xet yaw: roll/pitch cua do dac dat tren san gan nhu luon 0, va
// xoay day du se lam ham nay dai gap doi ma khong doi ket qua.
const double rx = wx * cy - wy * sny;
const double ry = wx * sny + wy * cy;
t.x[k] = rx + m.x;
t.y[k] = ry + m.y;
t.z[k] = wz + m.z;
minx = std::min(minx, t.x[k]); maxx = std::max(maxx, t.x[k]);
miny = std::min(miny, t.y[k]); maxy = std::max(maxy, t.y[k]);
}
}
loaded.push_back(std::move(L));
}
if (loaded.empty()) {
return StatusResponse::Error(StatusCode::kNotFound,
"khong doc duoc mesh va cham nao tu world");
}
minx -= opt.pad; maxx += opt.pad;
miny -= opt.pad; maxy += opt.pad;
const double res = opt.resolution;
const uint32_t w = static_cast<uint32_t>(std::ceil((maxx - minx) / res));
const uint32_t h = static_cast<uint32_t>(std::ceil((maxy - miny) / res));
out->resolution = static_cast<float>(res);
out->width = w;
out->height = h;
out->origin = Pose{};
out->origin.position.x = minx;
out->origin.position.y = miny;
// Bat dau la TRONG, khong phai chua biet: the gioi nay do ta dung nen moi
// o deu da biet -- cai chua duoc quet la chuyen cua ban do SLAM.
out->data.assign(static_cast<size_t>(w) * h, 0);
// --- Luot 2: to tam giac trong dai do cao ---
size_t n_used = 0;
for (const Loaded& L : loaded) {
for (const Tri& t : L.tris) {
// Tam giac nam hoan toan ngoai dai thi bo. Cat dung tam giac la thua:
// mesh day dac nen mot tam giac bien bi bo van con hang xom phu.
const double tz0 = std::min({t.z[0], t.z[1], t.z[2]});
const double tz1 = std::max({t.z[0], t.z[1], t.z[2]});
if (tz1 < opt.z_min || tz0 > opt.z_max) continue;
n_used++;
// Bao loi cua tam giac, roi kiem tung o bang toa do trong tam.
const double bx0 = std::min({t.x[0], t.x[1], t.x[2]});
const double bx1 = std::max({t.x[0], t.x[1], t.x[2]});
const double by0 = std::min({t.y[0], t.y[1], t.y[2]});
const double by1 = std::max({t.y[0], t.y[1], t.y[2]});
const int cx0 = std::max(0, static_cast<int>((bx0 - minx) / res));
const int cx1 = std::min(static_cast<int>(w) - 1,
static_cast<int>((bx1 - minx) / res));
const int cy0 = std::max(0, static_cast<int>((by0 - miny) / res));
const int cy1 = std::min(static_cast<int>(h) - 1,
static_cast<int>((by1 - miny) / res));
const double ax = t.x[0], ay = t.y[0];
const double bx = t.x[1], by = t.y[1];
const double cx = t.x[2], cy = t.y[2];
const double den = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
const bool degenerate = std::fabs(den) < 1e-12;
for (int gy = cy0; gy <= cy1; ++gy) {
for (int gx = cx0; gx <= cx1; ++gx) {
const double px = minx + (gx + 0.5) * res;
const double py = miny + (gy + 0.5) * res;
bool inside;
if (degenerate) {
// Tam giac suy bien (canh rat mong) van phai to, neu khong mot
// buc tuong mong se thung lo.
inside = true;
} else {
const double l1 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / den;
const double l2 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / den;
const double l3 = 1.0 - l1 - l2;
inside = l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9;
}
if (inside) {
out->data[static_cast<size_t>(gy) * w + gx] = 100;
}
}
}
}
}
size_t occ = 0;
for (int8_t v : out->data) if (v >= 50) occ++;
VSLAM_INFO("world -> luoi: " << w << "x" << h << " @ " << res << " m/o, goc ("
<< minx << ", " << miny << "), " << n_mesh << " mesh, " << n_tri
<< " tam giac (" << n_used << " trong dai z ["
<< opt.z_min << ", " << opt.z_max << "]), " << occ << " o bi chiem");
return StatusResponse::Ok();
}
// ---------------------------------------------------------------------------
StatusResponse ExportWorldMeshes(const GazeboWorld& world, bool visual,
WorldMeshes* out) {
if (out == nullptr) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null");
}
out->geoms.clear();
out->instances.clear();
std::map<std::string, uint32_t> by_model;
for (const WorldModel& m : world.models) {
const std::string& path = visual && !m.visual_obj.empty() ? m.visual_obj
: m.collision_obj;
if (path.empty()) continue;
// Gop theo TEN MODEL, khong theo duong dan mesh: `<scale>` den tu
// model.sdf nen hai model dung chung mot file mesh van co the khac ti le.
uint32_t gid = 0;
auto it = by_model.find(m.model_name);
if (it != by_model.end()) {
gid = it->second;
} else {
std::vector<Tri> tris;
const bool ok = IsDae(path) ? ReadDaeTriangles(path, &tris)
: ReadObjTriangles(path, &tris);
if (!ok || tris.empty()) {
VSLAM_WARN("world: khong doc duoc mesh " << path << " cua model "
<< m.model_name << " -- vat the nay VANG MAT khoi khung 3D");
continue;
}
WorldMeshGeom g;
g.model_name = m.model_name;
g.tri.reserve(tris.size() * 9);
for (const Tri& t : tris) {
for (int k = 0; k < 3; ++k) {
g.tri.push_back(static_cast<float>(t.x[k] * m.sx));
g.tri.push_back(static_cast<float>(t.y[k] * m.sy));
g.tri.push_back(static_cast<float>(t.z[k] * m.sz));
}
}
gid = static_cast<uint32_t>(out->geoms.size());
by_model[m.model_name] = gid;
out->geoms.push_back(std::move(g));
}
WorldMeshInstance inst;
inst.geom = gid;
inst.x = static_cast<float>(m.x);
inst.y = static_cast<float>(m.y);
inst.z = static_cast<float>(m.z);
inst.yaw = static_cast<float>(m.yaw);
out->instances.push_back(inst);
}
if (out->geoms.empty()) {
return StatusResponse::Error(StatusCode::kNotFound,
"khong doc duoc mesh nao tu world");
}
return StatusResponse::Ok();
}
size_t ApplyModelColors(const std::string& json_path, WorldMeshes* io) {
if (io == nullptr) return 0;
// JSON la tap con cua YAML, nen yaml-cpp doc duoc thang -- khong keo them
// mot bo doc JSON vao `vslam_sim` chi vi mot bang 69 dong.
YAML::Node root;
try {
root = YAML::LoadFile(json_path);
} catch (const std::exception& e) {
VSLAM_WARN("world: khong doc duoc bang mau " << json_path << " (" << e.what()
<< ") -- moi vat the se mang mau mac dinh");
return 0;
}
size_t n = 0;
for (WorldMeshGeom& g : io->geoms) {
const YAML::Node c = root[g.model_name];
if (!c || !c.IsSequence() || c.size() < 3) continue;
g.r = static_cast<uint8_t>(c[0].as<int>());
g.g = static_cast<uint8_t>(c[1].as<int>());
g.b = static_cast<uint8_t>(c[2].as<int>());
n++;
}
return n;
}
namespace {
void PutU32(std::string* o, uint32_t v) {
// Little-endian tuong minh: trinh duyet doc bang DataView voi littleEndian
// = true, nen khong duoc phu thuoc endianness cua may chu.
o->push_back(static_cast<char>(v & 0xFF));
o->push_back(static_cast<char>((v >> 8) & 0xFF));
o->push_back(static_cast<char>((v >> 16) & 0xFF));
o->push_back(static_cast<char>((v >> 24) & 0xFF));
}
void PutF32(std::string* o, float f) {
uint32_t u = 0;
std::memcpy(&u, &f, 4);
PutU32(o, u);
}
} // namespace
void EncodeWorldMeshes(const WorldMeshes& in, std::string* out) {
if (out == nullptr) return;
out->clear(); // ⚠️ ghi de, KHONG noi them -- xem EncodeScanPayload
out->append("VSLW");
PutU32(out, 1);
PutU32(out, static_cast<uint32_t>(in.geoms.size()));
PutU32(out, static_cast<uint32_t>(in.instances.size()));
for (const WorldMeshGeom& g : in.geoms) {
PutU32(out, static_cast<uint32_t>(g.model_name.size()));
out->append(g.model_name);
out->push_back(static_cast<char>(g.r));
out->push_back(static_cast<char>(g.g));
out->push_back(static_cast<char>(g.b));
PutU32(out, static_cast<uint32_t>(g.tri.size() / 9));
for (float v : g.tri) PutF32(out, v);
}
for (const WorldMeshInstance& i : in.instances) {
PutU32(out, i.geom);
PutF32(out, i.x); PutF32(out, i.y); PutF32(out, i.z); PutF32(out, i.yaw);
}
}
} // namespace vslam

View File

@@ -0,0 +1,248 @@
#include "vslam/occupancy_map_io.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <vector>
#include "vslam/log.h"
namespace vslam {
namespace {
std::string DirName(const std::string& path) {
const size_t slash = path.find_last_of('/');
return slash == std::string::npos ? std::string(".") : path.substr(0, slash);
}
// Doc PGM P5 (nhi phan 8 bit). Bo qua comment bat dau bang '#'.
bool ReadPgm(const std::string& path, uint32_t* w, uint32_t* h,
std::vector<uint8_t>* pixels, std::string* err) {
std::ifstream f(path, std::ios::binary);
if (!f) {
*err = "khong mo duoc " + path;
return false;
}
auto next_token = [&f]() -> std::string {
std::string tok;
while (f) {
const int c = f.get();
if (c == EOF) break;
if (c == '#') {
while (f && f.get() != '\n') {
}
continue;
}
if (std::isspace(c)) {
if (!tok.empty()) break;
continue;
}
tok.push_back(static_cast<char>(c));
}
return tok;
};
if (next_token() != "P5") {
*err = path + ": chi ho tro PGM P5 (nhi phan)";
return false;
}
*w = static_cast<uint32_t>(std::stoul(next_token()));
*h = static_cast<uint32_t>(std::stoul(next_token()));
const unsigned long maxval = std::stoul(next_token());
if (maxval > 255) {
*err = path + ": chi ho tro PGM 8 bit";
return false;
}
pixels->resize(static_cast<size_t>(*w) * (*h));
f.read(reinterpret_cast<char*>(pixels->data()),
static_cast<std::streamsize>(pixels->size()));
if (static_cast<size_t>(f.gcount()) != pixels->size()) {
*err = path + ": file anh cut";
return false;
}
return true;
}
} // namespace
StatusResponse LoadOccupancyMap(const std::string& yaml_path, MapLoadResult* out) {
// Kiem TON TAI truoc khi giao cho yaml-cpp.
//
// `YAML::LoadFile` tren mot file khong co nem `BadFile`, va `what()` cua no
// dung la chuoi "bad file" -- khong noi file nao, khong phan biet thieu voi
// hong, khong goi y gi. Nguoi dung go sai duong dan chi nhan duoc
// "hospital.yaml: bad file" roi dung do.
{
std::ifstream probe(yaml_path);
if (!probe) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong mo duoc ban do: " + yaml_path +
" (khong ton tai hoac khong co quyen doc). Xuat mot ban do tu DB "
"RTAB-Map bang: vslam_slam_bench --db X.db --localize "
"--export-only --export-map out.pgm");
}
}
YAML::Node node;
try {
node = YAML::LoadFile(yaml_path);
} catch (const YAML::Exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
yaml_path + ": YAML hong: " + e.what());
}
if (!node["image"] || !node["resolution"]) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
yaml_path + ": thieu 'image' hoac 'resolution'");
}
std::string image = node["image"].as<std::string>();
if (!image.empty() && image[0] != '/') image = DirName(yaml_path) + "/" + image;
out->image_path = image;
const double resolution = node["resolution"].as<double>();
double ox = 0.0, oy = 0.0;
if (node["origin"] && node["origin"].size() >= 2) {
ox = node["origin"][0].as<double>();
oy = node["origin"][1].as<double>();
}
const bool negate = node["negate"] ? node["negate"].as<int>() != 0 : false;
out->occupied_thresh =
node["occupied_thresh"] ? node["occupied_thresh"].as<double>() : 0.65;
out->free_thresh = node["free_thresh"] ? node["free_thresh"].as<double>() : 0.196;
uint32_t w = 0, h = 0;
std::vector<uint8_t> pixels;
std::string err;
if (!ReadPgm(image, &w, &h, &pixels, &err)) {
return StatusResponse::Error(StatusCode::kNotFound, err);
}
out->grid.width = w;
out->grid.height = h;
out->grid.resolution = static_cast<float>(resolution);
out->grid.origin.position.x = ox;
out->grid.origin.position.y = oy;
out->grid.data.resize(static_cast<size_t>(w) * h);
for (uint32_t y = 0; y < h; ++y) {
for (uint32_t x = 0; x < w; ++x) {
// PGM hang 0 o TREN CUNG; occupancy grid hang 0 o DUOI CUNG (goc o
// origin). Quen lat truc y la loi kinh dien khi doc map, va hau qua la
// ban do bi lat nguoc ma van "trong nhu that".
const uint8_t px = pixels[static_cast<size_t>(h - 1 - y) * w + x];
double occ = (255.0 - static_cast<double>(px)) / 255.0;
if (negate) occ = 1.0 - occ;
int8_t v;
if (occ > out->occupied_thresh) {
v = 100;
} else if (occ < out->free_thresh) {
v = 0;
} else {
v = -1; // chua biet
}
out->grid.data[static_cast<size_t>(y) * w + x] = v;
}
}
VSLAM_INFO("map: nap " << image << " -- " << w << "x" << h << " @ "
<< resolution << " m/o, goc (" << ox << ", " << oy << ")");
return StatusResponse::Ok();
}
StatusResponse SaveOccupancyMap(const OccupancyGrid& grid,
const std::string& yaml_path) {
std::string base = yaml_path;
const size_t dot = base.find_last_of('.');
if (dot != std::string::npos) base = base.substr(0, dot);
const std::string pgm_path = base + ".pgm";
std::ofstream img(pgm_path, std::ios::binary);
if (!img) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong ghi duoc " + pgm_path);
}
img << "P5\n# sinh boi vslam\n" << grid.width << " " << grid.height << "\n255\n";
for (uint32_t y = 0; y < grid.height; ++y) {
for (uint32_t x = 0; x < grid.width; ++x) {
const int8_t v = grid.data[static_cast<size_t>(grid.height - 1 - y) * grid.width + x];
const uint8_t px = v < 0 ? 205 : (v >= 50 ? 0 : 254);
img.put(static_cast<char>(px));
}
}
img.close();
std::ofstream y(yaml_path);
if (!y) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong ghi duoc " + yaml_path);
}
const size_t slash = pgm_path.find_last_of('/');
y << "image: " << (slash == std::string::npos ? pgm_path : pgm_path.substr(slash + 1))
<< "\nresolution: " << grid.resolution << "\norigin: [" << grid.origin.position.x
<< ", " << grid.origin.position.y << ", 0.0]\nnegate: 0\n"
<< "occupied_thresh: 0.65\nfree_thresh: 0.196\n";
VSLAM_INFO("map: da ghi " << yaml_path << " va " << pgm_path);
return StatusResponse::Ok();
}
OccupancyGrid MakeSyntheticWorld(uint32_t w, uint32_t h, float res) {
OccupancyGrid m;
m.width = w;
m.height = h;
m.resolution = res;
m.origin.position.x = -static_cast<double>(w) * res / 2.0;
m.origin.position.y = -static_cast<double>(h) * res / 2.0;
m.data.assign(static_cast<size_t>(w) * h, -1);
auto put = [&](uint32_t x, uint32_t y, int8_t v) {
if (x < w && y < h) m.data[static_cast<size_t>(y) * w + x] = v;
};
const uint32_t cy = h / 2;
const uint32_t half = std::max<uint32_t>(6, h / 24);
for (uint32_t x = w / 10; x < w - w / 10; ++x) {
for (uint32_t y = cy - half; y <= cy + half; ++y) put(x, y, 0);
put(x, cy - half - 1, 100);
put(x, cy + half + 1, 100);
}
// Bit hai dau hanh lang, neu khong thi raycast chay ra vo tan.
for (uint32_t y = cy - half - 1; y <= cy + half + 1; ++y) {
put(w / 10, y, 100);
put(w - w / 10 - 1, y, 100);
}
const uint32_t room = half * 3;
for (uint32_t rx = w / 6; rx + room < w - w / 10; rx += room + room / 2) {
for (int side = 0; side < 2; ++side) {
const uint32_t y0 = side == 0 ? cy + half + 2 : cy - half - 2 - room;
for (uint32_t x = rx; x < rx + room; ++x) {
for (uint32_t y = y0; y < y0 + room; ++y) put(x, y, 0);
}
for (uint32_t x = rx - 1; x <= rx + room; ++x) {
put(x, y0 - 1, 100);
put(x, y0 + room, 100);
}
for (uint32_t y = y0 - 1; y <= y0 + room; ++y) {
put(rx - 1, y, 100);
put(rx + room, y, 100);
}
const uint32_t door = rx + room / 2;
for (uint32_t x = door - 2; x <= door + 2; ++x) {
put(x, side == 0 ? y0 - 1 : y0 + room, 0);
}
}
}
return m;
}
} // namespace vslam

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,25 @@
# Lib kho build nhat tren arm64. Tat bang -DVSLAM_BUILD_SLAM=OFF thi sau lib
# kia van build -- do la ca ly do tach lib theo tap dependency thay vi theo
# chuc nang.
#
# OpenCV: tren Jetson PHAI dung ban cua JetPack, KHONG cai libopencv-dev.
# Hai ban OpenCV cung luc la nguon loi link/runtime kinh dien. Pin OpenCV_DIR.
find_package(RTABMap REQUIRED)
find_package(OpenCV REQUIRED)
vslam_add_library(vslam_slam
PUBLIC_HDRS
slam_types.h
rtabmap_params.h
rtabmap_slam.h
sensor_data_builder.h
occupancy_export.h
FIND_DEPS
vslam_common
RTABMap
OpenCV
)
target_link_libraries(vslam_slam PUBLIC vslam_common rtabmap::core ${OpenCV_LIBS})
target_include_directories(vslam_slam SYSTEM PUBLIC ${OpenCV_INCLUDE_DIRS})

View File

@@ -0,0 +1,43 @@
#ifndef VSLAM_OCCUPANCY_EXPORT_H
#define VSLAM_OCCUPANCY_EXPORT_H
// Dung occupancy grid 2D tu do thi RTAB-Map, xuat ra struct POD.
//
// ================== BAY DA MAC MOT LAN ==================
// RTAB-Map luu du lieu NEN trong SensorData. `gridGroundCellsRaw()` va
// `gridObstacleCellsRaw()` tra ve ma tran RONG -- im lang, khong loi, khong
// canh bao -- cho toi khi goi `uncompressDataConst()`. Do dung la ly do
// `tools/probe_rtabmap` lan dau chay ra "1990 node, 0 o".
#include <string>
#include "vslam/vslam_common.h"
namespace rtabmap {
class Rtabmap;
}
namespace vslam {
// Nhung gi doc duoc tu DB TRUOC khi init. Dung de kiem dieu kien tien quyet
// ma khong phai mo ca do thi.
struct DbFacts {
bool exists = false;
int nodes = 0;
int words = 0; // 0 = ban do quet KHONG co tu vung
std::string optimizer_strategy; // tham so DB nho, co the khac cai ta ep
};
DbFacts InspectDatabase(const std::string& path);
StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out);
// Doc thang tu DB, khong can Rtabmap dang chay. Dung cho
// `tools/vslam_slam_bench` va cho viec doi DB cu sang PGM.
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
double cell_size, double range_max,
OccupancyGrid* out);
} // namespace vslam
#endif // VSLAM_OCCUPANCY_EXPORT_H

View File

@@ -0,0 +1,64 @@
#ifndef VSLAM_RTABMAP_PARAMS_H
#define VSLAM_RTABMAP_PARAMS_H
// 26 key cua RTAB-Map tro thanh DU LIEU YAML thay vi <param> rai rac trong
// rtabmap.launch.
//
// ================== VI SAO PHAI KIEM TEN KEY ==================
// Go sai ten mot key RTAB-Map hien tai KHONG bao loi gi -- no bi bo qua im
// lang va he chay bang gia tri mac dinh. `Reg/Force3DoF` go thanh
// `Reg/Force3Dof` nghia la pose thanh 6-DoF ma khong ai biet, cho toi khi
// ban do bat dau nghieng.
//
// `BuildRtabmapParams` doi chieu MOI key voi
// `rtabmap::Parameters::getDefaultParameters()` va tra loi neu co key la.
#include <map>
#include <string>
#include <vector>
#include "vslam/config.h"
#include "vslam/slam_types.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct RtabmapConfig {
// TAT mac dinh: tren may chua build RTAB-Map thi node van phai chay duoc
// day du phan con lai.
bool enabled = false;
SlamMode mode = SlamMode::kMapping;
std::string database_path;
// Bat tui tu thi giac. Keo theo yeu cau co anh -- xem ghi chu trong
// rtabmap.launch: Kp/MaxFeatures dieu khien viec PHAT HIEN, con
// Reg/Strategy=1 (ICP tren LiDAR) van la thu TINH phep bien doi. Nen bat
// thi giac khong danh doi do chinh xac.
bool visual_loop = false;
bool camera_3d = false;
// Optimizer. "1" = g2o. KHONG dung "2" (GTSAM): apt jammy arm64 khong co
// GTSAM va PPA borglab khong publish arm64.
std::string optimizer_strategy = "1";
// Cac key RTAB-Map doc tu khoi `rtabmap:` cua slam.yaml. Ghi de len mac
// dinh, va bi ghi de boi cac suy dien tu mode/visual_loop o tren.
std::map<std::string, std::string> overrides;
};
// Tra ve tap tham so day du. `unknown` nhan ten cac key khong co trong bang
// mac dinh cua RTAB-Map -- nguoi goi PHAI coi do la loi khoi dong, khong
// duoc chi log.
std::map<std::string, std::string> BuildRtabmapParams(
const RtabmapConfig& cfg, std::vector<std::string>* unknown);
// Doc khoi `rtabmap:` + cac key cap cao tu ConfigNode.
RtabmapConfig LoadRtabmapConfig(const ConfigNode& node);
// Tra ve true neu RTAB-Map duoc build kem optimizer nay.
bool OptimizerAvailable(const std::string& strategy);
} // namespace vslam
#endif // VSLAM_RTABMAP_PARAMS_H

View File

@@ -0,0 +1,89 @@
#ifndef VSLAM_RTABMAP_SLAM_H
#define VSLAM_RTABMAP_SLAM_H
// Boc `rtabmap::Rtabmap`.
//
// ================== BA DIEU PHAI NHO ==================
//
// 1. `Process()` CHAN 100-600 ms. Luong goi no KHONG duoc chia se mutex nao
// voi luong safety. Trong ban ROS dieu nay duoc bao dam mien phi boi tien
// trinh rieng + respawn="true"; o day no la quy tac review.
//
// 2. RTAB-Map luu du lieu NEN. `gridGroundCellsRaw()` tra ma tran RONG, im
// lang, cho toi khi goi `uncompressDataConst()`. Da mac loi nay mot lan
// khi do `tools/probe_rtabmap` tren map_hospital.db.
//
// 3. DB hien co luu `Optimizer/Strategy=2` (GTSAM). Tren Jetson build voi
// -DWITH_GTSAM=OFF ma de RTAB-Map doc tham so tu DB thi no chon lai GTSAM
// va crash thieu symbol. `Init()` luon goi
// `init(params, db, loadDatabaseParameters=false)` VA assert sau do.
#include <memory>
#include <string>
#include "vslam/rtabmap_params.h"
#include "vslam/slam_types.h"
#include "vslam/vslam_common.h"
namespace vslam {
class RtabmapSlamImpl; // o namespace scope, KHONG long trong class
// (pimpl long private khong goi duoc tu .cc -- da
// mac loi nay o ConfigNode va WebServer)
class RtabmapSlam {
public:
RtabmapSlam();
~RtabmapSlam();
RtabmapSlam(const RtabmapSlam&) = delete;
RtabmapSlam& operator=(const RtabmapSlam&) = delete;
// Mo DB va khoi tao. Tra loi (khong nem) de nguoi goi quyet dinh chay tiep
// o che do khong-SLAM hay dung han.
//
// Kiem truoc khi chay, KHONG phai sau:
// - optimizer da yeu cau co duoc build vao khong;
// - visual_loop=true ma DB khong co tu vung (SELECT COUNT(*) FROM Word
// = 0) -> tra FAILED_PRECONDITION thay vi am tham ton CPU ma khong bao
// gio dong duoc vong nao;
// - localization ma DB rong -> khong co gi de dinh vi vao.
StatusResponse Init(const RtabmapConfig& cfg);
// Phep bien doi TINH tu cam bien ve base_footprint, doc tu robot.yaml.
//
// PHAI goi truoc Process(). Mac dinh la dong nhat, va dong nhat la SAI:
// laser tren robot nay o xyz = (0.24, 0, 0.20). Bo qua no thi 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.0074 m
// tren map_house.db. Khong co gi bao loi.
void SetExtrinsics(const Transform& laser_to_base, const Transform& camera_to_base);
// Mot khung. Tra `processed=false` neu RTAB-Map bo qua (chua du chuyen dong
// theo RGBD/LinearUpdate) -- do KHONG phai loi.
SlamOutput Process(const SlamInput& in);
// map -> odom gan nhat. An toan goi tu luong khac (doc duoi mutex rieng,
// khong phai mutex ma Process() giu).
Pose2D map_correction() const;
bool localized() const;
uint64_t map_version() const;
// Dat lai pose (thay cho /initialpose). Chi co nghia o che do localization.
StatusResponse SetInitialPose(const Pose2D& pose);
// Xuat occupancy grid hien tai. Dat, goi khi map_version doi.
StatusResponse ExportMap(OccupancyGrid* out);
StatusResponse Close(bool save_database);
const SlamStats& stats() const;
SlamMode mode() const;
private:
std::unique_ptr<RtabmapSlamImpl> impl_;
};
} // namespace vslam
#endif // VSLAM_RTABMAP_SLAM_H

Some files were not shown because too many files have changed in this diff Show More