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

211
test/CMakeLists.txt Normal file
View File

@@ -0,0 +1,211 @@
# Tang 1 cua chien luoc kiem chung: unit test tong hop, KHONG can du lieu va
# KHONG can phan cung. Chay duoc tu P0, truoc khi co LiDAR hay camera.
#
# Tang 2 (replay .vsr) va tang 3 (corpus .db co san) den o P3 va P6.
find_package(GTest REQUIRED)
# vslam_add_test(<ten> [LIBS ...])
function(vslam_add_test NAME)
cmake_parse_arguments(A "" "" "LIBS" ${ARGN})
add_executable(${NAME} ${NAME}.cc)
target_link_libraries(${NAME} PRIVATE
${A_LIBS} GTest::GTest GTest::Main Threads::Threads)
add_test(NAME ${NAME} COMMAND ${NAME})
# Test doc corpus qua $VSLAM_CORPUS_DIR; tro sang repo cu de dung lai
# map_house.db va map_hospital.db ma khong phai copy 3.8 GB.
# LSAN_OPTIONS: bo qua ro bo nho o static initializer cua BEN THU BA
# (octomap, VTK, librtabmap_core). Loc o muc THU VIEN chu khong tat han
# detect_leaks -- moi ro trong libvslam_* van bi bat. Xem
# test/lsan_suppressions.txt de biet tung muc den tu stack trace nao.
set_tests_properties(${NAME} PROPERTIES
ENVIRONMENT "VSLAM_CORPUS_DIR=${CMAKE_SOURCE_DIR}/../vSLAM_ws/maps;VSLAM_TEST_DATA_DIR=${CMAKE_CURRENT_SOURCE_DIR}/data;VSLAM_CONFIG_SRC_DIR=${CMAKE_SOURCE_DIR}/configuration_files;LSAN_OPTIONS=suppressions=${CMAKE_CURRENT_SOURCE_DIR}/lsan_suppressions.txt")
endfunction()
if(VSLAM_BUILD_COMMON)
vslam_add_test(test_unix_time LIBS vslam_common)
vslam_add_test(test_geometry LIBS vslam_common)
vslam_add_test(test_transform_tree LIBS vslam_common)
vslam_add_test(test_channel LIBS vslam_common)
# ⚠️ KHONG chay duoc duoi ThreadSanitizer cua gcc-10.
#
# `Channel<T>::Read` dung `condition_variable::wait_for(lk, timeout, pred)`.
# TSan cua gcc-10 khong mo hinh duoc khuon mau do voi libstdc++: no bao
# "double lock of a mutex" roi mot data race SUY RA tu lockset da hong.
#
# KHONG phai loi cua Channel<T>. `test/tsan_condvar_repro.cc` tai lap y het
# hai canh bao do voi KHONG MOT DONG NAO cua vslam -- chi std::mutex +
# condition_variable.
#
# Khong suppress: suppression du rong de bit no se che luon moi race tren
# du lieu duoc bao ve boi mot mutex co dung condvar, tuc la gan het trang
# thai chia se cua he. Thay vao do gan NHAN, va duoi TSan thi chay
# ctest -LE condvar
set_tests_properties(test_channel PROPERTIES LABELS condvar)
vslam_add_test(test_config LIBS vslam_common)
vslam_add_test(test_approx_sync LIBS vslam_common)
vslam_add_test(test_teleop_model LIBS vslam_common)
vslam_add_test(test_robot_model LIBS vslam_common)
endif()
if(VSLAM_BUILD_ODOMETRY)
vslam_add_test(test_wheel_odometry LIBS vslam_odometry vslam_common)
vslam_add_test(test_ekf_se2 LIBS vslam_odometry vslam_common)
endif()
if(VSLAM_BUILD_SAFETY)
vslam_add_test(test_safety_monitor LIBS vslam_safety vslam_common)
endif()
if(VSLAM_BUILD_DRIVERS)
vslam_add_test(test_scan_sanitizer LIBS vslam_drivers vslam_common)
vslam_add_test(test_clock_sync LIBS vslam_drivers vslam_common)
vslam_add_test(test_mcu_protocol LIBS vslam_drivers vslam_common)
vslam_add_test(test_record_io LIBS vslam_drivers vslam_common)
vslam_add_test(test_replay_source LIBS vslam_drivers vslam_common)
endif()
if(VSLAM_BUILD_PERCEPTION)
vslam_add_test(test_perception LIBS vslam_perception vslam_common)
if(VSLAM_BUILD_SIM)
# Test TICH HOP sim -> perception. Khoa quy uoc Z-depth cua anh mo phong
# va bai "san phang thi khong duoc bao vuc" -- thu ma ban ROS chi kiem
# duoc bang cach chay tay va nhin log, vi Gazebo o tien trinh khac.
vslam_add_test(test_perception_sim
LIBS vslam_sim vslam_perception vslam_drivers vslam_common)
endif()
endif()
if(VSLAM_BUILD_SIM)
vslam_add_test(test_sim_source LIBS vslam_sim vslam_drivers vslam_common)
# Doc `.world` cua Gazebo. Fixture rieng trong test/data/world -- KHONG can
# bo model 3 GB cua AWS, nen bai kiem nay chay duoc tren may sach.
vslam_add_test(test_gazebo_world LIBS vslam_sim vslam_common)
if(VSLAM_BUILD_ODOMETRY)
# Test TICH HOP: sim -> encoder -> wheel_odom -> EKF, do sai so so voi
# ground truth. Day la bai L2 cua repo cu viet lai khong ROS.
vslam_add_test(test_odometry_pipeline
LIBS vslam_sim vslam_odometry vslam_drivers vslam_common)
endif()
endif()
if(VSLAM_BUILD_SLAM)
vslam_add_test(test_slam LIBS vslam_slam vslam_common)
endif()
if(VSLAM_BUILD_WEB)
vslam_add_test(test_rle LIBS vslam_web vslam_common)
vslam_add_test(test_binary_codec LIBS vslam_web vslam_common)
# Test tich hop: dung server that tren cong tuy y roi goi HTTP vao.
# Giu lo hong fail-open da tung co o lop xac thuc e-stop.
find_package(Boost REQUIRED COMPONENTS system)
vslam_add_test(test_web_auth LIBS vslam_web vslam_common Boost::system)
target_include_directories(test_web_auth SYSTEM PRIVATE ${Boost_INCLUDE_DIRS})
endif()
# ============ Kiem cau hinh bang CHINH binary ============
#
# Manh hon unit test: no chay dung duong ma nguoi van hanh chay, tren dung
# file YAML se duoc cai len /etc/vslam. Mot file config hong phai bi TU CHOI
# KHOI DONG, khong phai am tham ve mac dinh.
if(VSLAM_BUILD_APP)
# Cac test nay goi THANG binary, khong qua vslam_add_test(), nen phai tu
# dat LSAN_OPTIONS. Thieu no thi duoi ASan chung do vi ro o static
# initializer cua octomap/VTK -- ro cua BEN THU BA, khong phai cua ta.
set(VSLAM_NODE_TEST_ENV
"VSLAM_CONFIG_DIR=${CMAKE_SOURCE_DIR}/configuration_files;LSAN_OPTIONS=suppressions=${CMAKE_CURRENT_SOURCE_DIR}/lsan_suppressions.txt")
add_test(NAME config_that_nap_duoc
COMMAND vslam_node --check --config ${CMAKE_SOURCE_DIR}/configuration_files)
set_tests_properties(config_that_nap_duoc PROPERTIES ENVIRONMENT "${VSLAM_NODE_TEST_ENV}")
# ============ VI SAO KHONG DUNG `WILL_FAIL` ============
# `WILL_FAIL TRUE` chi dao nguoc MA THOAT. Mot binary CRASH cung la "that
# bai", nen test se XANH ke ca khi `vslam_node` khong chay noi.
#
# Da gap that: `/opt/MVS` trong LD_LIBRARY_PATH gay
# symbol lookup error: libpcl_io.so.1.10:
# undefined symbol: libusb_set_option
# va ca SAU test WILL_FAIL o khoi nay deu bao PASS -- trong khi binary
# khong in noi mot dong. Chi `config_that_nap_duoc` (ky vong THANH CONG) la
# do. Tuc la 6/7 test o day vo dung dung luc can chung nhat.
#
# `PASS_REGULAR_EXPRESSION` manh hon hai bac: no khong chi doi test that
# bai, no doi DUNG CAI CONG DO kich. Mot config bi tu choi vi ly do KHAC
# gio cung la fail.
#
# Luu y: khi dat PASS_REGULAR_EXPRESSION thi CMake BO QUA ma thoat, nen
# khong can -- va khong duoc -- dat WILL_FAIL kem.
# Bon cong kiem CHEO giua cac file. Regex khop vao PHAN NOI DUNG cua tung
# cong, khong phai vao tien to chung "cau hinh (...)".
set(re_cmd_timeout "cmd_timeout .* phai LON HON")
set(re_limits "limits vuot qua")
set(re_threads "safety_priority phai CAO HON")
set(re_unknown_key "khoa la: scan\\.stop_distence")
foreach(case cmd_timeout limits threads unknown_key)
add_test(NAME config_tu_choi_${case}
COMMAND vslam_node --check
--config ${CMAKE_CURRENT_SOURCE_DIR}/data/badconfig/${case})
set_tests_properties(config_tu_choi_${case} PROPERTIES
PASS_REGULAR_EXPRESSION "${re_${case}}"
ENVIRONMENT "${VSLAM_NODE_TEST_ENV}")
endforeach()
# Nguon phai duoc chon TUONG MINH. Mot node am tham chay mo phong trong khi
# nguoi van hanh tuong no doc cam bien that la kieu hong te nhat co the
# nghi ra.
add_test(NAME node_doi_chon_nguon COMMAND vslam_node)
set_tests_properties(node_doi_chon_nguon PROPERTIES
PASS_REGULAR_EXPRESSION "phai chon mot nguon"
ENVIRONMENT "${VSLAM_NODE_TEST_ENV}")
# `--live` phai noi RO la chua chay duoc, khong duoc im lang chay thu gi do.
add_test(NAME node_live_bao_chua_co_driver
COMMAND vslam_node --live --config ${CMAKE_SOURCE_DIR}/configuration_files)
set_tests_properties(node_live_bao_chua_co_driver PROPERTIES
PASS_REGULAR_EXPRESSION "driver LakiBeam"
ENVIRONMENT "${VSLAM_NODE_TEST_ENV}")
endif()
# ---------------------------------------------------------------------------
# Frontend
# ---------------------------------------------------------------------------
#
# Bo ma hoa o C++ va bo giai ma o JavaScript la hai ban cai dat cua MOT dinh
# dang; khong bai kiem C++ nao cham toi ban thu hai. Ba lan lien tiep loi nam
# o tang hien thi trong khi build sach va ctest xanh.
#
# `node` la tuy chon: khong co thi bo qua, khong lam hong build.
find_program(VSLAM_NODE_EXE NAMES node nodejs)
if(VSLAM_NODE_EXE AND TARGET vslam_world_export)
add_test(NAME www_world_mesh
COMMAND ${VSLAM_NODE_EXE}
${CMAKE_CURRENT_SOURCE_DIR}/www/test_world_mesh.js
$<TARGET_FILE:vslam_world_export>
${CMAKE_CURRENT_SOURCE_DIR}/data
${CMAKE_CURRENT_BINARY_DIR}/www_world_mesh.bin)
# ⚠️ Khong dung WILL_FAIL cho nghich dao: mot binary CRASH cung tinh la pass.
set_tests_properties(www_world_mesh PROPERTIES
PASS_REGULAR_EXPRESSION "=> DAT")
# Scan di qua day tren dinh dang POLAR trong frame LASER; trinh duyet doi
# sang Descartes roi ap pose BASE. Quen khoang gan LiDAR lam ca vanh quet
# lui 24 cm ma khong mot chi so van hanh nao doi.
add_test(NAME www_scan_frame
COMMAND ${VSLAM_NODE_EXE}
${CMAKE_CURRENT_SOURCE_DIR}/www/test_scan_frame.js)
set_tests_properties(www_scan_frame PROPERTIES
PASS_REGULAR_EXPRESSION "=> DAT")
# Hai hinh robot (uoc luong + ground truth) va cao do cua chung. Cau truc
# lech mot tang lam hinh GT tut xuong 0.075 m, va o goc camera nghieng no
# chieu ra thanh khoang cach NGANG -- trong y het "robot bi nhan ban".
add_test(NAME www_robot_marker
COMMAND ${VSLAM_NODE_EXE}
${CMAKE_CURRENT_SOURCE_DIR}/www/test_robot_marker.js)
set_tests_properties(www_robot_marker PROPERTIES
PASS_REGULAR_EXPRESSION "=> DAT")
else()
message(STATUS "vslam: khong tim thay `node` -- bo qua bai kiem frontend")
endif()

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,68 @@
# 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.2
# ============ 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.
limits:
max_linear: 0.35
max_angular: 0.8

View File

@@ -0,0 +1,75 @@
# 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. Can `tcpdump -i eth0 udp port 2368`
# 5 giay tren LiDAR that roi phan tich. Driver chua viet.
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. Chua co driver -- can librealsense2 va 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,86 @@
# 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.
# 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.
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,74 @@
# 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
# ============ 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

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,68 @@
# 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.
limits:
max_linear: 1.50
max_angular: 0.8

View File

@@ -0,0 +1,75 @@
# 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. Can `tcpdump -i eth0 udp port 2368`
# 5 giay tren LiDAR that roi phan tich. Driver chua viet.
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. Chua co driver -- can librealsense2 va 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,86 @@
# 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.
# 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.
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,74 @@
# 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
# ============ 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

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,68 @@
# 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.
limits:
max_linear: 0.35
max_angular: 0.8

View File

@@ -0,0 +1,75 @@
# 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. Can `tcpdump -i eth0 udp port 2368`
# 5 giay tren LiDAR that roi phan tich. Driver chua viet.
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. Chua co driver -- can librealsense2 va 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,86 @@
# 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.
# 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.
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,74 @@
# 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
# ============ 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: 30 # 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

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,68 @@
# 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_distence: 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.
limits:
max_linear: 0.35
max_angular: 0.8

View File

@@ -0,0 +1,75 @@
# 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. Can `tcpdump -i eth0 udp port 2368`
# 5 giay tren LiDAR that roi phan tich. Driver chua viet.
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. Chua co driver -- can librealsense2 va 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,86 @@
# 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.
# 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.
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,74 @@
# 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
# ============ 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

BIN
test/data/maps/hospital.pgm Normal file

Binary file not shown.

View File

@@ -0,0 +1,6 @@
image: hospital.pgm
resolution: 0.05
origin: [-17.0893, -49.6094, 0.0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.196

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
image: hospital_world.pgm
resolution: 0.05
origin: [-13.5721, -36.0715, 0.0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.196

View File

@@ -0,0 +1,81 @@
# sinh boi gen_teleop_vectors.py tu teleop_model.py goc
# tag linear angular joy_h joy_v linear_speed angular_speed
init 0.000000000 0.000000000 0.000000000 0.000000000 0.300000000 0.700000000
key_down_Up 0.300000000 0.000000000 0.000000000 -1.000000000 0.300000000 0.700000000
key_up_Up 0.000000000 0.000000000 0.000000000 0.000000000 0.300000000 0.700000000
key_down_Down -0.300000000 0.000000000 0.000000000 1.000000000 0.300000000 0.700000000
key_up_Down 0.000000000 0.000000000 0.000000000 0.000000000 0.300000000 0.700000000
key_down_Left 0.000000000 0.700000000 -1.000000000 0.000000000 0.300000000 0.700000000
key_up_Left 0.000000000 0.000000000 0.000000000 0.000000000 0.300000000 0.700000000
key_down_Right 0.000000000 -0.700000000 1.000000000 0.000000000 0.300000000 0.700000000
key_up_Right 0.000000000 0.000000000 0.000000000 0.000000000 0.300000000 0.700000000
up_left 0.300000000 0.700000000 -1.000000000 -1.000000000 0.300000000 0.700000000
up_left_down 0.000000000 0.700000000 -1.000000000 0.000000000 0.300000000 0.700000000
clear_keys 0.000000000 0.000000000 0.000000000 0.000000000 0.300000000 0.700000000
joy_0.0_-1.0 0.300000000 -0.000000000 0.000000000 -1.000000000 0.300000000 0.700000000
joy_0.0_1.0 -0.300000000 -0.000000000 0.000000000 1.000000000 0.300000000 0.700000000
joy_-1.0_0.0 -0.000000000 0.700000000 -1.000000000 0.000000000 0.300000000 0.700000000
joy_1.0_0.0 -0.000000000 -0.700000000 1.000000000 0.000000000 0.300000000 0.700000000
joy_0.5_-0.5 0.150000000 -0.350000000 0.500000000 -0.500000000 0.300000000 0.700000000
joy_-0.3_0.7 -0.210000000 0.210000000 -0.300000000 0.700000000 0.300000000 0.700000000
joy_2.0_-2.0 0.300000000 -0.700000000 1.000000000 -1.000000000 0.300000000 0.700000000
joy_-2.0_2.0 -0.300000000 0.700000000 -1.000000000 1.000000000 0.300000000 0.700000000
joy_release 0.000000000 0.000000000 0.000000000 0.000000000 0.300000000 0.700000000
key_then 0.300000000 0.000000000 0.000000000 -1.000000000 0.300000000 0.700000000
joy_over_key 0.300000000 -0.000000000 0.000000000 -1.000000000 0.300000000 0.700000000
joy_released_key_remains 0.300000000 0.000000000 0.000000000 -1.000000000 0.300000000 0.700000000
lin_up 0.000000000 0.000000000 0.000000000 0.000000000 0.350000000 0.700000000
lin_up 0.000000000 0.000000000 0.000000000 0.000000000 0.400000000 0.700000000
lin_up 0.000000000 0.000000000 0.000000000 0.000000000 0.450000000 0.700000000
lin_up 0.000000000 0.000000000 0.000000000 0.000000000 0.500000000 0.700000000
lin_up 0.000000000 0.000000000 0.000000000 0.000000000 0.550000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.500000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.450000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.400000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.350000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.300000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.250000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.200000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.150000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.100000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.700000000
lin_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.700000000
ang_up 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.800000000
ang_up 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.900000000
ang_up 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 1.000000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.900000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.800000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.700000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.600000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.500000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.400000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.300000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.200000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
ang_down 0.000000000 0.000000000 0.000000000 0.000000000 0.050000000 0.100000000
set_lin_1.5 0.000000000 0.000000000 0.000000000 0.000000000 1.500000000 0.100000000
set_lin_99 0.000000000 0.000000000 0.000000000 0.000000000 2.000000000 0.100000000
set_ang_-5 0.000000000 0.000000000 0.000000000 0.000000000 2.000000000 0.100000000
manual_lin 0.250000000 0.000000000 0.000000000 0.000000000 2.000000000 0.100000000
manual_ang 0.250000000 -0.400000000 0.000000000 0.000000000 2.000000000 0.100000000
joy_clears_manual 2.000000000 -0.000000000 0.000000000 -1.000000000 2.000000000 0.100000000
manual_over_joy 0.100000000 0.100000000 0.000000000 0.000000000 2.000000000 0.100000000
key_clears_manual 2.000000000 0.000000000 0.000000000 -1.000000000 2.000000000 0.100000000
clear_motion 0.000000000 0.000000000 0.000000000 0.000000000 2.000000000 0.100000000
max_lin_0.5 0.000000000 0.000000000 0.000000000 0.000000000 0.500000000 0.100000000
max_ang_0.3 0.000000000 0.000000000 0.000000000 0.000000000 0.500000000 0.100000000
min_lin_cmd 0.000000000 0.000000000 0.000000000 0.000000000 0.500000000 0.100000000
min_ang_cmd 0.000000000 0.000000000 0.000000000 0.000000000 0.500000000 0.100000000
joy_at_limits -0.200000000 -0.100000000 1.000000000 1.000000000 0.500000000 0.100000000
manual_clamped -0.200000000 0.300000000 0.000000000 0.000000000 0.500000000 0.100000000

6
test/data/vsr/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
# Ban ghi .vsr KHONG vao git: 54 MB, va chung SINH LAI DUOC tat dinh bang
# tools/regress.sh --record
# Hat giong co dinh (SimConfig::seed) nen cung ma nguon cho cung file. Cai
# PHAI vao git la test/expected/*.json -- chung nho, doc duoc bang mat, va
# moi thay doi cua chung la mot thay doi hanh vi can review.
*.vsr

View File

@@ -0,0 +1,36 @@
<?xml version="1.0"?>
<!-- The gioi toi thieu cho bai kiem: BA hop giong het nhau ve kich thuoc
that (2.0 x 1.0 x 0.5 m) nhung khai bao don vi va ti le theo BA cach
khac nhau. Ca ba phai raster ra CUNG mot dau vet.
Moi bien the khoa lai mot loi da tung mac phai tren hospital.world. -->
<sdf version="1.6"><world name="mini">
<model name="box_m_1"><include>
<uri>model://box_m</uri><static>true</static>
<pose>0 0 0 0 0 0</pose>
</include></model>
<model name="box_cm_1"><include>
<uri>model://box_cm</uri><static>true</static>
<pose>5 0 0 0 0 0</pose>
</include></model>
<model name="box_mtx_1"><include>
<uri>model://box_mtx</uri><static>true</static>
<pose>10 0 0 0 0 0</pose>
</include></model>
<!-- Khai Y_UP nhung du lieu DA o Z-up, node khong xoay. Ap <up_axis> len
no lam hop 0.5 m cao thanh hop DUNG DUNG cao 1.0 m. -->
<model name="box_zup_1"><include>
<uri>model://box_zup</uri><static>true</static>
<pose>15 0 0 0 0 0</pose>
</include></model>
<!-- Quay 90 do: khoa lai phep xoay yaw. -->
<model name="box_m_2"><include>
<uri>model://box_m</uri><static>true</static>
<pose>0 6 0 0 0 1.5707963</pose>
</include></model>
<!-- Pose hong nhu StorageRack_1 trong hospital.world: phai bi BO. -->
<model name="box_m_roi"><include>
<uri>model://box_m</uri><static>true</static>
<pose>2 2 -7.57769e+08 0 0 0</pose>
</include></model>
</world></sdf>

View File

@@ -0,0 +1,17 @@
# CUNG hop do, nhung ve bang CENTIMET -- ti le den tu <scale> trong SDF
v -100 -50 0
v 100 -50 0
v 100 50 0
v -100 50 0
v -100 -50 50
v 100 -50 50
v 100 50 50
v -100 50 50
f 1 2 3
f 1 3 4
f 5 6 7
f 5 7 8
f 1 2 6
f 1 6 5
f 3 4 8
f 3 8 7

View File

@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<sdf version="1.6"><model name="box_cm"><static>true</static><link name="l">
<visual name="visual"><geometry><mesh>
<uri>model://box_cm/meshes/box.obj</uri>
<scale>0.01 0.01 0.01</scale></mesh></geometry></visual>
<collision name="collision"><geometry><mesh>
<uri>model://box_cm/meshes/box.obj</uri>
<scale>0.01 0.01 0.01</scale></mesh></geometry></collision>
</link></model></sdf>

View File

@@ -0,0 +1,17 @@
# hop 2.0 x 1.0 x 0.5 m, don vi MET
v -1.0 -0.5 0.0
v 1.0 -0.5 0.0
v 1.0 0.5 0.0
v -1.0 0.5 0.0
v -1.0 -0.5 0.5
v 1.0 -0.5 0.5
v 1.0 0.5 0.5
v -1.0 0.5 0.5
f 1 2 3
f 1 3 4
f 5 6 7
f 5 7 8
f 1 2 6
f 1 6 5
f 3 4 8
f 3 8 7

View File

@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<sdf version="1.6"><model name="box_m"><static>true</static><link name="l">
<visual name="visual"><geometry><mesh>
<uri>model://box_m/meshes/box.obj</uri>
</mesh></geometry></visual>
<collision name="collision"><geometry><mesh>
<uri>model://box_m/meshes/box.obj</uri>
</mesh></geometry></collision>
</link></model></sdf>

View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
<!-- CUNG hop 2.0 x 1.0 x 0.5 m, nhung bay ba tang:
1. duoi file viet HOA (.DAE) -- so duoi phan biet hoa thuong se roi
vao bo doc OBJ va hong im lang
2. <unit meter="0.01"> NOI DOI: dinh ve bang MILIMET
3. ti le that nam trong <matrix> (0.1), khong phai trong <scale>
0.1 * 0.01 = 0.001 => milimet. -->
<asset>
<unit meter="0.01" name="centimeter"/>
<up_axis>Z_UP</up_axis>
</asset>
<library_geometries>
<geometry id="G" name="G">
<mesh>
<source id="G-pos">
<float_array id="G-pos-array" count="24">
-1000 -500 0 1000 -500 0 1000 500 0 -1000 500 0
-1000 -500 500 1000 -500 500 1000 500 500 -1000 500 500
</float_array>
<technique_common>
<accessor source="#G-pos-array" count="8" stride="3">
<param name="X" type="float"/>
<param name="Y" type="float"/>
<param name="Z" type="float"/>
</accessor>
</technique_common>
</source>
<vertices id="G-vtx"><input semantic="POSITION" source="#G-pos"/></vertices>
<polylist count="8" material="M">
<input semantic="VERTEX" source="#G-vtx" offset="0"/>
<vcount>3 3 3 3 3 3 3 3</vcount>
<p>0 1 2 0 2 3 4 5 6 4 6 7 0 1 5 0 5 4 2 3 7 2 7 6</p>
</polylist>
</mesh>
</geometry>
</library_geometries>
<library_visual_scenes>
<visual_scene id="S" name="S">
<node name="N" id="N">
<matrix sid="matrix">0.1 0 0 0 0 0.1 0 0 0 0 0.1 0 0 0 0 1</matrix>
<instance_geometry url="#G"/>
</node>
</visual_scene>
</library_visual_scenes>
<scene><instance_visual_scene url="#S"/></scene>
</COLLADA>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<sdf version="1.6"><model name="box_mtx"><static>true</static><link name="l">
<visual name="visual"><geometry><mesh>
<uri>model://box_mtx/meshes/Box.DAE</uri>
</mesh></geometry></visual>
<collision name="collision"><geometry><mesh>
<uri>model://box_mtx/meshes/Box.DAE</uri>
</mesh></geometry></collision>
</link></model></sdf>

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
<!-- CUNG hop 2.0 x 1.0 x 0.5 m. Bay o day la thu tinh nhat trong ca bo:
File khai <up_axis>Y_UP</up_axis> NHUNG du lieu da o Z-up san, va node
KHONG co phep xoay nao. `<up_axis>` noi ve he toa do cua bo XUAT, khong
phai cua du lieu trong file.
Day dung la truong hop cua aws_robomaker_hospital_floor_01_walls_visual
(geometry ID43): ban va cham cua CUNG buc tuong do la Y-up that va co
node xoay de doi truc, con ban hien thi thi da o Z-up voi node rong.
Ap `<up_axis>` len file nay lam buc tuong 3 m thanh mot thanh DUNG DUNG
cao 56 m giua san. -->
<asset>
<unit meter="0.01" name="centimeter"/>
<up_axis>Y_UP</up_axis>
</asset>
<library_geometries>
<geometry id="G" name="G">
<mesh>
<source id="G-pos">
<float_array id="G-pos-array" count="24">
-100 -50 0 100 -50 0 100 50 0 -100 50 0
-100 -50 50 100 -50 50 100 50 50 -100 50 50
</float_array>
<technique_common>
<accessor source="#G-pos-array" count="8" stride="3">
<param name="X" type="float"/>
<param name="Y" type="float"/>
<param name="Z" type="float"/>
</accessor>
</technique_common>
</source>
<vertices id="G-vtx"><input semantic="POSITION" source="#G-pos"/></vertices>
<polylist count="8" material="M">
<input semantic="VERTEX" source="#G-vtx" offset="0"/>
<vcount>3 3 3 3 3 3 3 3</vcount>
<p>0 1 2 0 2 3 4 5 6 4 6 7 0 1 5 0 5 4 2 3 7 2 7 6</p>
</polylist>
</mesh>
</geometry>
</library_geometries>
<library_visual_scenes>
<visual_scene id="S" name="S">
<node name="N" id="N"><instance_geometry url="#G"/></node>
</visual_scene>
</library_visual_scenes>
<scene><instance_visual_scene url="#S"/></scene>
</COLLADA>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<sdf version="1.6"><model name="box_zup"><static>true</static><link name="l">
<visual name="visual"><geometry><mesh>
<uri>model://box_zup/meshes/box.dae</uri>
</mesh></geometry></visual>
<collision name="collision"><geometry><mesh>
<uri>model://box_zup/meshes/box.dae</uri>
</mesh></geometry></collision>
</link></model></sdf>

25
test/expected/cliff.json Normal file
View File

@@ -0,0 +1,25 @@
{
"scenario": "cliff",
"n_imu": 1600,
"n_encoder": 400,
"n_bumper": 400,
"count_state_OK": 309,
"n_safety_step": 399,
"n_scan": 200,
"n_ultrasonic": 159,
"n_camera": 80,
"count_cliff_judged": 80,
"count_cliff_detected": 20,
"count_state_CLIFF_STOP": 90,
"n_chunks": 2919,
"n_truncated": 0,
"dist_duration_sec": 7.995,
"pose_ekf_x": 2.24717,
"pose_ekf_y": -9.21099e-05,
"yaw_ekf": -0.00011068,
"pose_wheel_x": 2.25067,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 0.00350731,
"metric_slip_max": 0.00150737
}

View File

@@ -0,0 +1,26 @@
{
"scenario": "cliff_shallow",
"n_imu": 2399,
"n_encoder": 599,
"n_bumper": 599,
"count_state_OK": 414,
"n_safety_step": 598,
"n_scan": 299,
"n_ultrasonic": 239,
"n_camera": 119,
"count_cliff_judged": 104,
"count_cliff_detected": 19,
"count_state_CLIFF_STOP": 184,
"count_bail_slope_clamped": 15,
"n_chunks": 4373,
"n_truncated": 0,
"dist_duration_sec": 11.99,
"pose_ekf_x": 2.89225,
"pose_ekf_y": 0.000105499,
"yaw_ekf": 6.18578e-05,
"pose_wheel_x": 2.89138,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 0.000877884,
"metric_slip_max": 0.00143618
}

23
test/expected/glass.json Normal file
View File

@@ -0,0 +1,23 @@
{
"scenario": "glass",
"n_imu": 2799,
"n_encoder": 699,
"n_bumper": 699,
"count_state_OK": 406,
"n_safety_step": 698,
"n_scan": 349,
"n_ultrasonic": 279,
"count_state_US_BLOCKED": 5,
"count_state_BUMPER": 287,
"n_chunks": 4825,
"n_truncated": 0,
"dist_duration_sec": 13.99,
"pose_ekf_x": 2.70954,
"pose_ekf_y": -0.000219445,
"yaw_ekf": -0.000198316,
"pose_wheel_x": 2.70992,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 0.000442772,
"metric_slip_max": 0.0014535
}

View File

@@ -0,0 +1,21 @@
{
"scenario": "glass_blind",
"n_imu": 3199,
"n_encoder": 799,
"n_bumper": 799,
"count_state_OK": 411,
"n_safety_step": 798,
"n_scan": 399,
"count_state_BUMPER": 387,
"n_chunks": 5196,
"n_truncated": 0,
"dist_duration_sec": 15.99,
"pose_ekf_x": 2.70954,
"pose_ekf_y": -5.30248e-05,
"yaw_ekf": -4.79404e-05,
"pose_wheel_x": 2.70992,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 0.000388193,
"metric_slip_max": 0.00144762
}

View File

@@ -0,0 +1,22 @@
{
"scenario": "lidar_cut",
"n_imu": 1999,
"n_encoder": 499,
"n_bumper": 499,
"count_state_OK": 396,
"n_safety_step": 498,
"n_scan": 174,
"n_ultrasonic": 199,
"count_state_SCAN_TIMEOUT": 102,
"n_chunks": 3370,
"n_truncated": 0,
"dist_duration_sec": 9.99,
"pose_ekf_x": 2.84567,
"pose_ekf_y": -4.65795e-05,
"yaw_ekf": -4.05326e-05,
"pose_wheel_x": 2.84468,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 0.000994997,
"metric_slip_max": 0.00142555
}

View File

@@ -0,0 +1,21 @@
{
"scenario": "outback",
"n_imu": 5794,
"n_encoder": 1448,
"n_bumper": 1448,
"count_state_OK": 1447,
"n_safety_step": 1447,
"n_scan": 724,
"n_ultrasonic": 579,
"n_chunks": 9993,
"n_truncated": 0,
"dist_duration_sec": 28.965,
"pose_ekf_x": 0.000408514,
"pose_ekf_y": -0.000695077,
"yaw_ekf": -0.270756,
"pose_wheel_x": 0.000161902,
"pose_wheel_y": -0.000106963,
"yaw_wheel": -0.27466,
"dist_ekf_vs_wheel": 0.000637726,
"metric_slip_max": 0.00799072
}

View File

@@ -0,0 +1,21 @@
{
"scenario": "slip_diff",
"n_imu": 1999,
"n_encoder": 499,
"n_bumper": 499,
"count_state_OK": 498,
"n_safety_step": 498,
"n_scan": 249,
"n_ultrasonic": 199,
"n_chunks": 3445,
"n_truncated": 0,
"dist_duration_sec": 9.99,
"pose_ekf_x": 3.29075,
"pose_ekf_y": 3.56171e-05,
"yaw_ekf": 0.000124109,
"pose_wheel_x": 3.27845,
"pose_wheel_y": -0.268241,
"yaw_wheel": -0.0842656,
"dist_ekf_vs_wheel": 0.268559,
"metric_slip_max": 0.144034
}

View File

@@ -0,0 +1,21 @@
{
"scenario": "slip_sym",
"n_imu": 1999,
"n_encoder": 499,
"n_bumper": 499,
"count_state_OK": 498,
"n_safety_step": 498,
"n_scan": 249,
"n_ultrasonic": 199,
"n_chunks": 3445,
"n_truncated": 0,
"dist_duration_sec": 9.99,
"pose_ekf_x": 3.30591,
"pose_ekf_y": 3.96651e-05,
"yaw_ekf": 0.000125319,
"pose_wheel_x": 3.3048,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 0.00111098,
"metric_slip_max": 0.00153427
}

27
test/expected/spin.json Normal file
View File

@@ -0,0 +1,27 @@
{
"scenario": "spin",
"n_imu": 1400,
"n_encoder": 350,
"n_bumper": 350,
"count_state_OK": 349,
"n_safety_step": 349,
"n_scan": 175,
"n_ultrasonic": 139,
"n_camera": 70,
"count_cliff_judged": 40,
"count_bail_residual_large": 1,
"count_bail_obstructed": 28,
"count_cliff_detected": 1,
"count_bail_offset_large": 1,
"n_chunks": 2554,
"n_truncated": 0,
"dist_duration_sec": 6.995,
"pose_ekf_x": 0,
"pose_ekf_y": 0,
"yaw_ekf": -1.04077,
"pose_wheel_x": 0,
"pose_wheel_y": 0,
"yaw_wheel": -1.03697,
"dist_ekf_vs_wheel": 0,
"metric_slip_max": 0.00750205
}

View File

@@ -0,0 +1,21 @@
{
"scenario": "straight",
"n_imu": 1799,
"n_encoder": 449,
"n_bumper": 449,
"count_state_OK": 448,
"n_safety_step": 448,
"n_scan": 224,
"n_ultrasonic": 179,
"n_chunks": 3100,
"n_truncated": 0,
"dist_duration_sec": 8.99,
"pose_ekf_x": 2.79521,
"pose_ekf_y": -1.03652e-05,
"yaw_ekf": 9.18786e-05,
"pose_wheel_x": 2.79484,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 0.000375294,
"metric_slip_max": 0.00153427
}

View File

@@ -0,0 +1,22 @@
{
"scenario": "us_dead",
"n_imu": 1600,
"n_encoder": 400,
"n_bumper": 400,
"count_state_OK": 1,
"n_safety_step": 399,
"n_scan": 200,
"n_ultrasonic": 159,
"count_state_US_TIMEOUT": 398,
"n_chunks": 2759,
"n_truncated": 0,
"dist_duration_sec": 7.995,
"pose_ekf_x": 2.5925,
"pose_ekf_y": -7.62883e-05,
"yaw_ekf": -7.89196e-05,
"pose_wheel_x": 2.59663,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 0.0041349,
"metric_slip_max": 0.00172492
}

25
test/expected/wall.json Normal file
View File

@@ -0,0 +1,25 @@
{
"scenario": "wall",
"n_imu": 2799,
"n_encoder": 699,
"n_bumper": 699,
"count_state_OK": 369,
"n_safety_step": 698,
"n_scan": 349,
"n_ultrasonic": 279,
"count_state_SCAN_SLOW": 66,
"count_state_SCAN_STOP": 44,
"count_state_US_BLOCKED": 4,
"count_state_BUMPER": 215,
"n_chunks": 4825,
"n_truncated": 0,
"dist_duration_sec": 13.99,
"pose_ekf_x": 3.20984,
"pose_ekf_y": 1.64295e-05,
"yaw_ekf": 0.000105779,
"pose_wheel_x": 3.20992,
"pose_wheel_y": 0,
"yaw_wheel": 0,
"dist_ekf_vs_wheel": 8.00033e-05,
"metric_slip_max": 0.00157986
}

View File

@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Sinh vector kiem tu CHINH ban Python goc.
Chay mot chuoi thao tac tren teleop_model.py cua vSLAM_ws roi ghi ket qua ra
test/data/teleop_vectors.txt. test_teleop_model.cc doc file do va bat ban C++
cho ket qua giong het.
Day la cach duy nhat kiem duoc loi hua "logic giu NGUYEN VEN" cua ban port --
doc hai file roi gat dau thi khong phai kiem chung.
"""
import sys, os
sys.path.insert(0, os.path.expanduser(
"~/projects/vSLAM_ws/src/robot_bringup/scripts"))
from teleop_model import TeleopModel
out = []
def emit(tag, m):
lin, ang = m.command()
h, v = m.joystick_position()
out.append("%s %.9f %.9f %.9f %.9f %.9f %.9f" %
(tag, lin, ang, h, v, m.linear_speed, m.angular_speed))
m = TeleopModel()
emit("init", m)
# Phim mui ten, tung phim va to hop
for k in ("Up", "Down", "Left", "Right"):
m.set_key(k, True); emit("key_down_" + k, m)
m.set_key(k, False); emit("key_up_" + k, m)
m.set_key("Up", True); m.set_key("Left", True); emit("up_left", m)
m.set_key("Down", True); emit("up_left_down", m) # Up + Down triet tieu
m.clear_keys(); emit("clear_keys", m)
# Joystick
for hv in [(0.0,-1.0), (0.0,1.0), (-1.0,0.0), (1.0,0.0),
(0.5,-0.5), (-0.3,0.7), (2.0,-2.0), (-2.0,2.0)]:
m.set_joystick(*hv); emit("joy_%.1f_%.1f" % hv, m)
m.release_joystick(); emit("joy_release", m)
# Joystick de len phim
m.set_key("Up", True); emit("key_then", m)
m.set_joystick(0.0, -1.0); emit("joy_over_key", m)
m.release_joystick(); emit("joy_released_key_remains", m)
m.clear_keys()
# Chinh toc do
for _ in range(5):
m.adjust_linear_speed(+1); emit("lin_up", m)
for _ in range(12):
m.adjust_linear_speed(-1); emit("lin_down", m) # cham day min
for _ in range(3):
m.adjust_angular_speed(+1); emit("ang_up", m)
for _ in range(20):
m.adjust_angular_speed(-1); emit("ang_down", m)
m.set_linear_speed(1.5); emit("set_lin_1.5", m)
m.set_linear_speed(99.0); emit("set_lin_99", m) # kep ve max
m.set_angular_speed(-5.0); emit("set_ang_-5", m) # kep ve min
# Lenh manual + thu tu uu tien
m.set_manual_command(linear_x=0.25); emit("manual_lin", m)
m.set_manual_command(angular_z=-0.4); emit("manual_ang", m)
m.set_joystick(0.0, -1.0); emit("joy_clears_manual", m)
m.set_manual_command(linear_x=0.1, angular_z=0.1); emit("manual_over_joy", m)
m.set_key("Up", True); emit("key_clears_manual", m)
m.clear_motion(); emit("clear_motion", m)
# Gioi han
m.set_max_linear_speed(0.5); emit("max_lin_0.5", m)
m.set_max_angular_speed(0.3); emit("max_ang_0.3", m)
m.set_min_linear_command(-0.2); emit("min_lin_cmd", m)
m.set_min_angular_command(-0.1); emit("min_ang_cmd", m)
m.set_joystick(1.0, 1.0); emit("joy_at_limits", m)
m.set_manual_command(linear_x=-99.0, angular_z=99.0); emit("manual_clamped", m)
os.makedirs("data", exist_ok=True)
with open("data/teleop_vectors.txt", "w") as f:
f.write("# sinh boi gen_teleop_vectors.py tu teleop_model.py goc\n")
f.write("# tag linear angular joy_h joy_v linear_speed angular_speed\n")
f.write("\n".join(out) + "\n")
print("da ghi %d vector vao data/teleop_vectors.txt" % len(out))

View File

@@ -0,0 +1,19 @@
# Ro bo nho o BEN THU BA, ro tu static initializer, khong phai tu code cua ta.
#
# Dung `leak:<ten thu vien>` chu khong tat han detect_leaks: bo loc o muc thu
# vien van bat duoc moi ro trong libvslam_*, tuc la van giu nguyen gia tri cua
# phep kiem. Tat han thi test_slam thanh mot bai kiem khong con kiem gi.
#
# Da xac minh tung muc bang stack trace, khong doan:
# octomap::ColorOcTree::StaticMemberInitializer -- so do dang ky kieu toan
# cuc, co y song den khi tien trinh chet.
leak:liboctomap
# VTK: vtkCellArray::New, vtkIdTypeArray::New, vtkAOSDataArrayTemplate --
# singleton cua VTK. RTAB-Map keo VTK vao qua PCL visualization.
leak:libvtk
# librtabmap_core: std::vector<double>::_M_default_append va
# std::vector<octomap::KeyRay> -- bo dem noi bo giu den khi thoat.
leak:librtabmap_core

166
test/test_approx_sync.cc Normal file
View File

@@ -0,0 +1,166 @@
#include "vslam/approx_sync.h"
#include <gtest/gtest.h>
#include <vector>
using namespace vslam;
namespace {
struct A { int v = 0; };
struct B { int v = 0; };
std::shared_ptr<const A> MakeA(int v) { return std::make_shared<const A>(A{v}); }
std::shared_ptr<const B> MakeB(int v) { return std::make_shared<const B>(B{v}); }
UnixTime T(double s) { return UnixTime::fromSec(1000.0 + s); }
} // namespace
// --- PairSync: truong hop cliff_detect (depth + camera_info) ---------------
TEST(PairSync, KhopCapGanNhau) {
std::vector<std::pair<int, int>> got;
PairSync<A, B> sync(30, 0.05, [&](UnixTime, std::shared_ptr<const A> a,
std::shared_ptr<const B> b) {
got.emplace_back(a->v, b->v);
});
sync.AddFirst(T(0.00), MakeA(1));
sync.AddSecond(T(0.01), MakeB(1)); // lech 10 ms, trong dung sai
ASSERT_EQ(got.size(), 1u);
EXPECT_EQ(got[0].first, 1);
EXPECT_EQ(got[0].second, 1);
EXPECT_EQ(sync.stats().matched, 1u);
}
TEST(PairSync, BoCapLechQuaDungSai) {
std::vector<std::pair<int, int>> got;
PairSync<A, B> sync(30, 0.05, [&](UnixTime, std::shared_ptr<const A> a,
std::shared_ptr<const B> b) {
got.emplace_back(a->v, b->v);
});
sync.AddFirst(T(0.00), MakeA(1));
sync.AddSecond(T(0.50), MakeB(1)); // lech 500 ms
EXPECT_TRUE(got.empty());
// a khong the khop voi bat ky b nao ve sau (b chi tien len) -> bo.
EXPECT_EQ(sync.stats().dropped_slop, 1u);
}
TEST(PairSync, ChonPhanTuGanNhatChuKhongPhaiDauTien) {
std::vector<std::pair<int, int>> got;
PairSync<A, B> sync(30, 0.05, [&](UnixTime, std::shared_ptr<const A> a,
std::shared_ptr<const B> b) {
got.emplace_back(a->v, b->v);
});
sync.AddSecond(T(0.00), MakeB(10));
sync.AddSecond(T(0.04), MakeB(20)); // gan T(0.045) hon
sync.AddFirst(T(0.045), MakeA(1));
ASSERT_EQ(got.size(), 1u);
EXPECT_EQ(got[0].second, 20);
}
TEST(PairSync, CatHangDoiTheoQueueSize) {
PairSync<A, B> sync(3, 0.001, [](UnixTime, std::shared_ptr<const A>,
std::shared_ptr<const B>) {});
for (int i = 0; i < 10; ++i) sync.AddFirst(T(i * 1.0), MakeA(i));
EXPECT_GT(sync.stats().dropped_queue, 0u);
}
// --- ApproxTimeSync: truong hop SLAM (scan + odom + depth) -----------------
TEST(ApproxSync, PhatKhiDuMoiStreamBatBuoc) {
using Sync = ApproxTimeSync<A, B>;
Sync::Options opt;
opt.pivot_index = 0;
opt.required = {true, true};
opt.max_slop_sec = 0.05;
int fired = 0;
Sync sync(opt, [&](UnixTime, const Sync::Tuple& t) {
ASSERT_NE(std::get<0>(t), nullptr);
ASSERT_NE(std::get<1>(t), nullptr);
EXPECT_EQ(std::get<0>(t)->v, 1);
EXPECT_EQ(std::get<1>(t)->v, 2);
fired++;
});
sync.Add<0>(T(0.00), MakeA(1));
EXPECT_EQ(fired, 0); // con thieu stream 1
sync.Add<1>(T(0.01), MakeB(2));
EXPECT_EQ(fired, 1);
}
TEST(ApproxSync, StreamTuyChonHetHanThiVanPhat) {
// RTAB-Map chay duoc voi scan + odom ma khong can depth. Nhanh timeout nay
// la thu giu cho SLAM khong dung han khi camera cham hoac chet.
using Sync = ApproxTimeSync<A, B>;
Sync::Options opt;
opt.pivot_index = 0;
opt.required = {true, false}; // stream 1 la tuy chon
opt.wait_timeout_sec = 0.20;
int fired = 0;
bool optional_was_null = false;
Sync sync(opt, [&](UnixTime, const Sync::Tuple& t) {
fired++;
if (std::get<1>(t) == nullptr) optional_was_null = true;
});
sync.Add<0>(T(0.00), MakeA(1));
EXPECT_EQ(fired, 0); // van cho stream tuy chon
sync.Tick(T(0.10));
EXPECT_EQ(fired, 0); // chua het han
sync.Tick(T(0.30)); // het 200 ms
EXPECT_EQ(fired, 1);
EXPECT_TRUE(optional_was_null);
EXPECT_EQ(sync.stats().dropped_timeout, 1u);
}
TEST(ApproxSync, BoPivotKhiThieuStreamBatBuocQuaLau) {
using Sync = ApproxTimeSync<A, B>;
Sync::Options opt;
opt.pivot_index = 0;
opt.required = {true, true};
opt.wait_timeout_sec = 0.20;
int fired = 0;
Sync sync(opt, [&](UnixTime, const Sync::Tuple&) { fired++; });
sync.Add<0>(T(0.00), MakeA(1));
sync.Tick(T(0.30));
EXPECT_EQ(fired, 0);
EXPECT_EQ(sync.stats().dropped_timeout, 1u);
}
TEST(ApproxSync, TuChoiStampLui) {
using Sync = ApproxTimeSync<A, B>;
Sync::Options opt;
opt.required = {true, true};
Sync sync(opt, [](UnixTime, const Sync::Tuple&) {});
sync.Add<0>(T(1.0), MakeA(1));
sync.Add<0>(T(0.5), MakeA(2)); // lui
EXPECT_EQ(sync.stats().dropped_queue, 1u);
}
TEST(ApproxSync, NhieuCapLienTiep) {
using Sync = ApproxTimeSync<A, B>;
Sync::Options opt;
opt.required = {true, true};
opt.max_slop_sec = 0.05;
int fired = 0;
Sync sync(opt, [&](UnixTime, const Sync::Tuple&) { fired++; });
for (int i = 0; i < 10; ++i) {
sync.Add<0>(T(i * 0.1), MakeA(i));
sync.Add<1>(T(i * 0.1 + 0.01), MakeB(i));
}
EXPECT_EQ(fired, 10);
EXPECT_EQ(sync.stats().matched, 10u);
}

237
test/test_binary_codec.cc Normal file
View File

@@ -0,0 +1,237 @@
#include "vslam/binary_codec.h"
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
using namespace vslam;
namespace {
LaserScan MakeScan() {
LaserScan s;
s.angle_min = -2.356194f;
s.angle_max = 2.356194f;
s.angle_increment = static_cast<float>(2.0 * 2.356194 / 1080.0);
s.range_min = 0.05f;
s.range_max = 40.0f;
s.ranges.resize(1081, 3.0f);
return s;
}
} // namespace
TEST(BinaryCodec, HeaderDungDinhDang) {
const LaserScan s = MakeScan();
std::string buf;
const UnixTime t = UnixTime::fromNSec(1737000000123456789LL);
EncodeScan(s, t, &buf);
ASSERT_GE(buf.size(), kBinaryHeaderSize);
EXPECT_EQ(buf.compare(0, 4, "VSL1"), 0);
BinaryHeader h;
ASSERT_TRUE(DecodeHeader(buf, 0, &h));
EXPECT_EQ(h.type, BinaryType::kScan);
EXPECT_EQ(h.version, kBinaryVersion);
EXPECT_EQ(h.stamp_ns, 1737000000123456789ULL);
}
TEST(BinaryCodec, ScanKichThuocDungDuKien) {
const LaserScan s = MakeScan();
std::string buf;
EncodeScan(s, UnixTime::fromSec(1.0), &buf);
// 16 header + 16 (4 float) + 4 (n) + 1081*2 = 2198
EXPECT_EQ(buf.size(), 16u + 16u + 4u + 1081u * 2u);
EXPECT_EQ(buf.size(), 2198u);
}
TEST(BinaryCodec, ScanGiuDungBaNguNghiaCuaTia) {
// Day la test quan trong nhat cua file. Ba gia tri nay KHAC NHAU:
// NaN = khong do duoc (duoi range_min)
// inf = do duoc nhung khong co phan xa
// range_max+1.0 = bi sector mask cat vi than robot che
// Lan lon chung lam robot hoac dung im (SCAN_SPARSE) hoac dam vao tuong.
LaserScan s = MakeScan();
s.ranges[0] = std::numeric_limits<float>::quiet_NaN();
s.ranges[1] = std::numeric_limits<float>::infinity();
s.ranges[2] = s.range_max + 1.0f; // sentinel
s.ranges[3] = 12.345f;
std::string buf;
EncodeScan(s, UnixTime::fromSec(1.0), &buf);
LaserScan out;
ASSERT_TRUE(DecodeScan(buf, &out));
ASSERT_EQ(out.ranges.size(), s.ranges.size());
EXPECT_TRUE(std::isnan(out.ranges[0]));
EXPECT_TRUE(std::isinf(out.ranges[1]));
EXPECT_FALSE(std::isinf(out.ranges[2]));
EXPECT_NEAR(out.ranges[2], s.range_max + 1.0f, 1e-3); // van la sentinel
EXPECT_NEAR(out.ranges[3], 12.345f, 0.001f); // sai so luong tu 1 mm
}
TEST(BinaryCodec, ScanKepGiaTriQuaLon) {
LaserScan s = MakeScan();
s.range_max = 70000.0f; // vo ly, nhung khong duoc lam tran im lang
s.ranges[0] = 66000.0f;
std::string buf;
EncodeScan(s, UnixTime::fromSec(1.0), &buf);
LaserScan out;
ASSERT_TRUE(DecodeScan(buf, &out));
EXPECT_LE(out.ranges[0], 65.6f); // kep ve kRangeMaxValid, khong quay vong
}
TEST(BinaryCodec, MapFullRoundTrip) {
OccupancyGrid m;
m.width = 40;
m.height = 30;
m.resolution = 0.05f;
m.origin.position.x = -1.25;
m.origin.position.y = -2.5;
m.data.assign(static_cast<size_t>(m.width) * m.height, -1);
for (uint32_t x = 5; x < 35; ++x) m.data[10 * m.width + x] = 100;
for (uint32_t x = 5; x < 35; ++x) m.data[11 * m.width + x] = 0;
std::string buf;
EncodeMapFull(m, UnixTime::fromSec(2.0), &buf);
OccupancyGrid out;
ASSERT_TRUE(DecodeMapFull(buf, &out));
EXPECT_EQ(out.width, m.width);
EXPECT_EQ(out.height, m.height);
EXPECT_NEAR(out.resolution, m.resolution, 1e-6);
EXPECT_NEAR(out.origin.position.x, m.origin.position.x, 1e-5);
EXPECT_NEAR(out.origin.position.y, m.origin.position.y, 1e-5);
EXPECT_EQ(out.data, m.data);
}
TEST(BinaryCodec, MapFullNenTotTrenBanDoThua) {
OccupancyGrid m;
m.width = 2000;
m.height = 2000;
m.resolution = 0.05f;
m.data.assign(4000000u, -1);
// Mot hanh lang: dieu nay giong ban do that hon la toan -1.
for (uint32_t y = 990; y < 1010; ++y) {
for (uint32_t x = 200; x < 1800; ++x) m.data[y * m.width + x] = 0;
}
std::string buf;
EncodeMapFull(m, UnixTime::fromSec(1.0), &buf);
// Tho la 4 MB. RLE phai dua xuong duoi 100 kB.
EXPECT_LT(buf.size(), 100u * 1024u);
OccupancyGrid out;
ASSERT_TRUE(DecodeMapFull(buf, &out));
EXPECT_EQ(out.data, m.data);
}
TEST(BinaryCodec, MapPatchChiGuiVungDoi) {
OccupancyGrid a;
a.width = 100;
a.height = 100;
a.resolution = 0.05f;
a.data.assign(10000u, -1);
OccupancyGrid b = a;
for (uint32_t y = 50; y < 55; ++y) {
for (uint32_t x = 20; x < 30; ++x) b.data[y * b.width + x] = 100;
}
std::string patch;
ASSERT_TRUE(EncodeMapPatch(b, a, UnixTime::fromSec(1.0), &patch));
BinaryHeader h;
ASSERT_TRUE(DecodeHeader(patch, 0, &h));
EXPECT_EQ(h.type, BinaryType::kMapPatch);
// Vung bao la 10x5 = 50 o, nen patch phai nho hon nhieu so voi full.
std::string full;
EncodeMapFull(b, UnixTime::fromSec(1.0), &full);
EXPECT_LT(patch.size(), full.size());
}
TEST(BinaryCodec, MapPatchTuChoiKhiKichThuocDoi) {
OccupancyGrid a;
a.width = 10; a.height = 10; a.resolution = 0.05f;
a.data.assign(100u, -1);
OccupancyGrid b = a;
b.width = 20; b.height = 10;
b.data.assign(200u, -1);
std::string patch;
// Kich thuoc doi -> khong va duoc, phai gui MAP_FULL.
EXPECT_FALSE(EncodeMapPatch(b, a, UnixTime::fromSec(1.0), &patch));
}
TEST(BinaryCodec, MapPatchTuChoiKhiKhongCoGiDoi) {
OccupancyGrid a;
a.width = 10; a.height = 10; a.resolution = 0.05f;
a.data.assign(100u, -1);
std::string patch;
EXPECT_FALSE(EncodeMapPatch(a, a, UnixTime::fromSec(1.0), &patch));
}
TEST(BinaryCodec, CloudGiamMauVaBoNaN) {
PointCloudXYZ c;
for (int i = 0; i < 10000; ++i) {
c.points.push_back(PointXYZ{static_cast<float>(i) * 0.001f, 0.0f, 0.5f});
}
c.points[5] = PointXYZ{std::numeric_limits<float>::quiet_NaN(), 0.0f, 0.0f};
std::string buf;
EncodeCloud(c, UnixTime::fromSec(1.0), /*max_points=*/1000, 0.01f, &buf);
// 16 header + 20 (origin3 + scale + n) + n*6
ASSERT_GE(buf.size(), 36u);
const size_t n = (buf.size() - 36u) / 6u;
EXPECT_LE(n, 1000u);
EXPECT_GT(n, 900u);
}
TEST(BinaryCodec, CloudRongVanHopLe) {
PointCloudXYZ c;
std::string buf;
EncodeCloud(c, UnixTime::fromSec(1.0), 1000, 0.01f, &buf);
EXPECT_EQ(buf.size(), 36u);
BinaryHeader h;
ASSERT_TRUE(DecodeHeader(buf, 0, &h));
EXPECT_EQ(h.type, BinaryType::kCloud);
}
TEST(BinaryCodec, PathThuaHoa) {
std::vector<Pose2D> path;
for (int i = 0; i < 1000; ++i) {
path.push_back(Pose2D{static_cast<double>(i) * 0.01, 0.0, 0.0}); // buoc 1 cm
}
std::string buf;
EncodePath(path, UnixTime::fromSec(1.0), /*min_step_m=*/0.1, &buf);
const size_t n = (buf.size() - 16u - 4u) / 8u;
// Buoc 1 cm, loc 10 cm -> khoang 100 diem thay vi 1000.
EXPECT_LE(n, 110u);
EXPECT_GE(n, 90u);
}
TEST(BinaryCodec, PathLuonGiuDiemCuoi) {
// Diem cuoi la vi tri hien tai. Mat no thi duong di trong nhu dang tut hau.
std::vector<Pose2D> path = {{0.0, 0.0, 0.0}, {0.01, 0.0, 0.0}, {0.02, 0.0, 0.0}};
std::string buf;
EncodePath(path, UnixTime::fromSec(1.0), 1.0, &buf);
const size_t n = (buf.size() - 20u) / 8u;
EXPECT_EQ(n, 2u); // diem dau + diem cuoi
}
TEST(BinaryCodec, KhungHongBiTuChoi) {
BinaryHeader h;
EXPECT_FALSE(DecodeHeader("", 0, &h));
EXPECT_FALSE(DecodeHeader("XXXX123456789012", 0, &h)); // sai magic
LaserScan s;
EXPECT_FALSE(DecodeScan("VSL1", &s)); // cut
}

216
test/test_channel.cc Normal file
View File

@@ -0,0 +1,216 @@
#include "vslam/channel.h"
#include <gtest/gtest.h>
#include <atomic>
#include <thread>
#include <vector>
using namespace vslam;
namespace {
struct Msg {
int value = 0;
};
using MsgPtr = std::shared_ptr<const Msg>;
MsgPtr Make(int v) { return std::make_shared<const Msg>(Msg{v}); }
} // namespace
TEST(Channel, DocTheoThuTu) {
Channel<Msg> ch(8, "test");
auto r = ch.MakeReader("r");
ch.Freeze();
for (int i = 0; i < 5; ++i) ch.Publish(Make(i), UnixTime::fromSec(i + 1));
for (int i = 0; i < 5; ++i) {
MsgPtr out;
UnixTime stamp;
ASSERT_TRUE(r.TryRead(&out, &stamp));
EXPECT_EQ(out->value, i);
EXPECT_NEAR(stamp.toSec(), i + 1, 1e-9);
}
MsgPtr out;
EXPECT_FALSE(r.TryRead(&out, nullptr));
}
TEST(Channel, ReaderBatDauTuHienTai) {
Channel<Msg> ch(8, "test");
ch.Publish(Make(99), UnixTime::fromSec(1.0));
// Reader tao SAU khi da publish thi khong thay ban tin cu -- giong subscriber
// cua ROS, va la dieu dung: mot stage khoi dong muon khong nen xu ly lai
// lich su.
auto r = ch.MakeReader("r");
ch.Freeze();
MsgPtr out;
EXPECT_FALSE(r.TryRead(&out, nullptr));
}
TEST(Channel, DemDropKhiProducerNhanhHon) {
// Day la thu queue cua ROS KHONG cho: so ban tin bi bo.
// Producer nhanh gap 10 lan capacity -> reader phai thay dung so da mat.
constexpr size_t kCap = 4;
Channel<Msg> ch(kCap, "test");
auto r = ch.MakeReader("slow");
ch.Freeze();
for (int i = 0; i < 40; ++i) ch.Publish(Make(i), UnixTime::fromSec(i + 1));
MsgPtr out;
ASSERT_TRUE(r.TryRead(&out, nullptr));
// Ring giu 4 phan tu cuoi (36..39); reader bi nhay qua 36 ban tin dau.
EXPECT_EQ(out->value, 36);
EXPECT_EQ(r.dropped(), 36u);
// Doc het phan con lai.
int seen = 1;
while (r.TryRead(&out, nullptr)) seen++;
EXPECT_EQ(seen, static_cast<int>(kCap));
}
TEST(Channel, PublishTraFalseKhiGhiDe) {
Channel<Msg> ch(2, "test");
// Reader ton tai de co nguoi "chua doc" -- do la dieu kien de Publish() bao
// ghi de. Khong doc gi tu no.
auto r = ch.MakeReader("r");
(void)r;
ch.Freeze();
EXPECT_TRUE(ch.Publish(Make(1), UnixTime::fromSec(1)));
EXPECT_TRUE(ch.Publish(Make(2), UnixTime::fromSec(2)));
// Phan tu thu 3 ghi de phan tu 1 ma reader chua doc -> bao false.
EXPECT_FALSE(ch.Publish(Make(3), UnixTime::fromSec(3)));
}
TEST(Channel, LatestKhongDungCursor) {
Channel<Msg> ch(4, "test");
auto r = ch.MakeReader("r");
ch.Freeze();
MsgPtr out;
EXPECT_FALSE(ch.Latest(&out));
ch.Publish(Make(1), UnixTime::fromSec(1));
ch.Publish(Make(2), UnixTime::fromSec(2));
UnixTime stamp;
ASSERT_TRUE(ch.Latest(&out, &stamp));
EXPECT_EQ(out->value, 2);
EXPECT_NEAR(stamp.toSec(), 2.0, 1e-9);
// Latest() khong tieu thu: reader van doc duoc tu dau.
ASSERT_TRUE(r.TryRead(&out, nullptr));
EXPECT_EQ(out->value, 1);
}
TEST(Channel, NhieuReaderCoCursorRieng) {
Channel<Msg> ch(8, "test");
auto a = ch.MakeReader("a");
auto b = ch.MakeReader("b");
ch.Freeze();
ch.Publish(Make(1), UnixTime::fromSec(1));
ch.Publish(Make(2), UnixTime::fromSec(2));
MsgPtr out;
ASSERT_TRUE(a.TryRead(&out, nullptr));
EXPECT_EQ(out->value, 1);
// b chua doc gi nen van bat dau tu dau.
ASSERT_TRUE(b.TryRead(&out, nullptr));
EXPECT_EQ(out->value, 1);
EXPECT_EQ(a.lag(), 1u);
EXPECT_EQ(b.lag(), 1u);
}
TEST(Channel, ReadChanRoiHetGio) {
Channel<Msg> ch(4, "test");
auto r = ch.MakeReader("r");
ch.Freeze();
MsgPtr out;
const auto t0 = std::chrono::steady_clock::now();
EXPECT_FALSE(r.Read(&out, nullptr, std::chrono::milliseconds(50)));
const auto dt = std::chrono::steady_clock::now() - t0;
EXPECT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(dt).count(), 45);
}
TEST(Channel, CloseDanhThucReader) {
Channel<Msg> ch(4, "test");
auto r = ch.MakeReader("r");
ch.Freeze();
std::atomic<bool> returned{false};
std::thread th([&] {
MsgPtr out;
r.Read(&out, nullptr, std::chrono::seconds(10));
returned = true;
});
std::this_thread::sleep_for(std::chrono::milliseconds(20));
EXPECT_FALSE(returned.load());
ch.Close();
th.join();
EXPECT_TRUE(returned.load());
}
TEST(Channel, PublisherKhongBaoGioChan) {
// Yeu cau song con: luong lidar_rx khong duoc phep dung cho luong slam.
// Reader khong doc gi ca; producer van chay het.
Channel<Msg> ch(4, "test");
auto r = ch.MakeReader("never_reads");
ch.Freeze();
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < 10000; ++i) ch.Publish(Make(i), UnixTime::fromSec(i + 1));
const auto dt = std::chrono::steady_clock::now() - t0;
EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(dt).count(), 2000);
(void)r;
}
TEST(Channel, StatsBaoCaoDuSoLieu) {
Channel<Msg> ch(2, "scan");
auto r = ch.MakeReader("slam");
ch.Freeze();
for (int i = 0; i < 6; ++i) ch.Publish(Make(i), UnixTime::fromSec(i + 1));
const ChannelStats s = ch.stats();
EXPECT_EQ(s.name, "scan");
EXPECT_EQ(s.capacity, 2u);
EXPECT_EQ(s.published, 6u);
EXPECT_EQ(s.readers, 1u);
EXPECT_GT(s.overwritten, 0u);
EXPECT_EQ(s.max_reader_lag, 6u);
(void)r;
}
TEST(Channel, MotProducerNhieuConsumerDongThoi) {
constexpr int kN = 2000;
Channel<Msg> ch(64, "test");
auto a = ch.MakeReader("a");
auto b = ch.MakeReader("b");
ch.Freeze();
std::atomic<int> count_a{0}, count_b{0};
auto drain = [&ch](Channel<Msg>::Reader* r, std::atomic<int>* count) {
MsgPtr out;
while (!ch.closed()) {
if (r->Read(&out, nullptr, std::chrono::milliseconds(10))) count->fetch_add(1);
}
while (r->TryRead(&out, nullptr)) count->fetch_add(1);
};
std::thread ta(drain, &a, &count_a);
std::thread tb(drain, &b, &count_b);
for (int i = 0; i < kN; ++i) ch.Publish(Make(i), UnixTime::fromSec(i + 1));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
ch.Close();
ta.join();
tb.join();
// Moi consumer thay <= kN ban tin; phan khong thay phai bang dropped().
EXPECT_EQ(count_a.load() + static_cast<int>(a.dropped()), kN);
EXPECT_EQ(count_b.load() + static_cast<int>(b.dropped()), kN);
}

228
test/test_clock_sync.cc Normal file
View File

@@ -0,0 +1,228 @@
#include "vslam/clock_sync.h"
#include <gtest/gtest.h>
#include <cmath>
#include <random>
using namespace vslam;
// --- McuTimeUnwrapper: BUG TRAN 71.58 PHUT --------------------------------
TEST(McuTimeUnwrapper, KhongTranThiDiThang) {
McuTimeUnwrapper u;
EXPECT_NEAR(u.UnwrapSeconds(0), 0.0, 1e-9);
EXPECT_NEAR(u.UnwrapSeconds(1000000), 1.0, 1e-9);
EXPECT_NEAR(u.UnwrapSeconds(2500000), 2.5, 1e-9);
EXPECT_EQ(u.wrap_count(), 0u);
}
TEST(McuTimeUnwrapper, BuDungMotLanTran) {
// DAY LA TEST HOI QUY CHO BUG CUA BAN PYTHON.
//
// micros() la uint32_t, tran moi 2^32 us = 4294.967296 s = 71.58 phut.
// Ban Python khong unwrap: sau moc do, fit tuyen tinh vo, kiem tra skew tu
// choi ket qua, va fallback la rac -> MOI stamp IMU sai hang nghin giay.
//
// Trieu chung tren robot that: sau hon mot gio chay, moi lookup TF bi tu
// choi vi stamp o tuong lai xa, robot dung im, khong co gi trong log noi tai
// sao. Loai bug chi hien ra khi chay lau -- tuc la khi dang trinh dien.
McuTimeUnwrapper u;
constexpr uint32_t kMax = 0xFFFFFFFFu;
// kMax = 2^32 - 1, nen moc nay la 4293.967295 s chu khong phai .967296.
const double t_before = u.UnwrapSeconds(kMax - 1000000);
EXPECT_NEAR(t_before, 4293.967295, 1e-6);
const double t_after = u.UnwrapSeconds(1000000); // 1 s sau khi tran
EXPECT_EQ(u.wrap_count(), 1u);
// Thoi gian phai TIEN LEN ~2 giay, khong phai LUI 4292 giay.
// Chinh xac la 2.000001 s vi chu ky la 2^32 con kMax la 2^32 - 1.
EXPECT_NEAR(t_after - t_before, 2.000001, 1e-6);
EXPECT_GT(t_after, t_before);
}
TEST(McuTimeUnwrapper, NhieuLanTranLienTiep) {
// 3 lan tran = hon 3.5 gio chay lien tuc.
//
// Buoc nhay phai NHO so voi chu ky. Bo dem tran chi phan biet duoc "tran"
// voi "nhay lui" khi khoang cach giua hai lan goi < nua chu ky; buoc dung
// nua chu ky la mo ho theo dung dinh nghia. MCU that tang deu tung mili
// giay nen dieu nay khong bao gio xay ra, va test phai mo phong nhu vay.
McuTimeUnwrapper u;
constexpr uint64_t kPeriodUs = 1ULL << 32;
constexpr uint64_t kStepUs = 100000; // 0.1 s, giong nhip ping that
double prev = -1.0;
uint64_t t_true = 0;
for (uint64_t i = 0; i < 3 * kPeriodUs / kStepUs + 10; ++i) {
const double t = u.UnwrapSeconds(static_cast<uint32_t>(t_true & 0xFFFFFFFFu));
EXPECT_GT(t, prev) << "thoi gian lui o buoc " << i;
prev = t;
t_true += kStepUs;
}
EXPECT_EQ(u.wrap_count(), 3u);
EXPECT_NEAR(prev, static_cast<double>(t_true - kStepUs) * 1e-6, 1e-6);
}
TEST(McuTimeUnwrapper, BanTinLechThuTuKhongBiHieuNhamLaTran) {
// Ban tin den lech thu tu chi lui vai mili giay; tran thi lui gan 71 phut.
// Nguong nua dai phan biet duoc hai truong hop.
McuTimeUnwrapper u;
const double t1 = u.UnwrapSeconds(10000000); // 10 s
const double t2 = u.UnwrapSeconds(9999000); // lui 1 ms
EXPECT_EQ(u.wrap_count(), 0u) << "lui 1 ms bi hieu nham la tran";
EXPECT_LT(t2, t1);
}
TEST(McuTimeUnwrapper, ResetXoaTrangThai) {
McuTimeUnwrapper u;
u.UnwrapSeconds(0xFFFFFFFFu);
u.UnwrapSeconds(1000);
EXPECT_EQ(u.wrap_count(), 1u);
u.Reset();
EXPECT_EQ(u.wrap_count(), 0u);
EXPECT_NEAR(u.UnwrapSeconds(5000000), 5.0, 1e-9);
}
// --- ClockSync -------------------------------------------------------------
TEST(ClockSync, ChuaCoMauThiChuaSanSang) {
ClockSync cs;
double h = 0.0;
EXPECT_FALSE(cs.ready());
EXPECT_FALSE(cs.ToHost(1.0, &h));
}
TEST(ClockSync, DongHoKhopHoanToan) {
// MCU va host cung nhip, lech hang so 1000 s, RTT 1 ms doi xung.
ClockSync cs;
for (int i = 0; i < 40; ++i) {
const double mcu = static_cast<double>(i) * 0.1;
const double host_true = mcu + 1000.0;
cs.Add(mcu, host_true - 0.0005, host_true + 0.0005);
}
ASSERT_TRUE(cs.ready());
EXPECT_NEAR(cs.skew(), 1.0, 1e-9);
double h = 0.0;
ASSERT_TRUE(cs.ToHost(5.0, &h));
EXPECT_NEAR(h, 1005.0, 1e-6);
}
TEST(ClockSync, UocLuongDuocSkew30ppm) {
// Thach anh lech vai chuc ppm la binh thuong. Phai uoc luong duoc, khong
// phai lam tron ve 1.0.
constexpr double kSkew = 1.0 + 30e-6;
ClockSync cs;
for (int i = 0; i < 64; ++i) {
const double mcu = static_cast<double>(i) * 1.0; // trai dai 64 s
const double host_true = kSkew * mcu + 500.0;
cs.Add(mcu, host_true - 0.0005, host_true + 0.0005);
}
ASSERT_TRUE(cs.ready());
EXPECT_NEAR(cs.skew(), kSkew, 1e-7);
EXPECT_NEAR(cs.skew_ppm(), 30.0, 0.5);
}
TEST(ClockSync, MauRTTLonBiLoaiBo) {
// Gia dinh "host = (t_send + t_recv)/2" chi dung khi do tre doi xung.
// RTT lon gan nhu luon bat doi xung (lich CPU, buffer serial), nen mau do
// phai bi loai -- neu khong thi uoc luong bi keo lech.
ClockSync cs;
std::mt19937 rng(7);
std::uniform_real_distribution<double> jitter(0.0, 0.2);
for (int i = 0; i < 64; ++i) {
const double mcu = static_cast<double>(i) * 0.5;
const double host_true = mcu + 100.0;
if (i % 3 == 0) {
// Mau tot: RTT 1 ms, doi xung.
cs.Add(mcu, host_true - 0.0005, host_true + 0.0005);
} else {
// Mau xau: RTT lon va BAT DOI XUNG -- toan bo do tre o chieu ve.
const double d = jitter(rng);
cs.Add(mcu, host_true - 0.001, host_true + d);
}
}
ASSERT_TRUE(cs.ready());
double h = 0.0;
ASSERT_TRUE(cs.ToHost(10.0, &h));
// Neu mau xau lot vao thi offset se bi keo len toi ~0.1 s.
EXPECT_NEAR(h, 110.0, 0.01);
}
TEST(ClockSync, SkewVoLyBiTuChoi) {
// Skew lech 50% = du lieu rac (giao thuc sai, hoac micros() tran ma khong
// unwrap). Phai tu choi ket qua fit va dem lai, khong dung bua.
ClockSync cs;
for (int i = 0; i < 40; ++i) {
const double mcu = static_cast<double>(i);
cs.Add(mcu, 1.5 * mcu, 1.5 * mcu + 0.001);
}
EXPECT_GT(cs.rejected_fits(), 0u);
EXPECT_NEAR(cs.skew(), 1.0, 1e-12) << "phai roi ve skew=1 khi tu choi";
}
TEST(ClockSync, MauTrungThoiDiemVanUocLuongDuocOffset) {
// Moi mau cung mot mcu_s -> khong the uoc luong skew, nhung offset thi co.
ClockSync cs;
for (int i = 0; i < 10; ++i) cs.Add(5.0, 100.0 - 0.001, 100.0 + 0.001);
ASSERT_TRUE(cs.ready());
EXPECT_NEAR(cs.skew(), 1.0, 1e-12);
double h = 0.0;
ASSERT_TRUE(cs.ToHost(5.0, &h));
EXPECT_NEAR(h, 100.0, 0.01);
}
TEST(ClockSync, CuaSoGioiHanSoMau) {
ClockSync::Config c;
c.window = 10;
ClockSync cs(c);
for (int i = 0; i < 100; ++i) {
cs.Add(static_cast<double>(i), 1000.0 + i, 1000.0 + i + 0.001);
}
EXPECT_EQ(cs.sample_count(), 10u);
}
TEST(ClockSync, ChayQuaMocTranVanGiuStampDungDan) {
// Bai tich hop: 90 phut chay lien tuc, di qua moc tran 71.58 phut.
// Day la tieu chi nghiem thu P2 duoc viet thanh test.
McuTimeUnwrapper u;
ClockSync cs;
constexpr double kHostStart = 1737000000.0;
double prev_host = 0.0;
bool first = true;
int checked = 0;
// Ping moi giay trong 90 phut = 5400 mau.
for (int sec = 0; sec < 5400; ++sec) {
// MCU khoi dong truoc host 4000 s, nen no tran o khoang phut 5 cua bai do.
const uint64_t mcu_us_true = 4000ULL * 1000000ULL + static_cast<uint64_t>(sec) * 1000000ULL;
const uint32_t mcu_raw = static_cast<uint32_t>(mcu_us_true & 0xFFFFFFFFu);
const double mcu_s = u.UnwrapSeconds(mcu_raw);
const double host = kHostStart + static_cast<double>(sec);
cs.Add(mcu_s, host - 0.0005, host + 0.0005);
if (cs.ready()) {
double h = 0.0;
ASSERT_TRUE(cs.ToHost(mcu_s, &h));
// Stamp phai bam sat host that, va phai DON DIEU TANG.
EXPECT_NEAR(h, host, 0.05) << "giay " << sec;
if (!first) {
EXPECT_GT(h, prev_host) << "stamp lui o giay " << sec;
}
prev_host = h;
first = false;
checked++;
}
}
EXPECT_GT(u.wrap_count(), 0u) << "bai test phai thuc su di qua moc tran";
EXPECT_GT(checked, 5000);
EXPECT_LT(std::abs(cs.skew_ppm()), 100.0);
}

133
test/test_config.cc Normal file
View File

@@ -0,0 +1,133 @@
#include "vslam/config.h"
#include <gtest/gtest.h>
#include <string>
using namespace vslam;
namespace {
const char* kSafetyYaml = R"(
safety:
scan:
stop_distance: 0.35
slow_distance: 0.80
min_front_rays: 20
enabled: true
ultrasonic_topics: []
cliff_topics:
- /perception/cliff_detected
robot:
wheel_radius: 0.075
wheel_separation: 0.36
)";
} // namespace
TEST(Config, DocGiaTriCoBan) {
const ConfigNode cfg = ConfigNode::LoadString(kSafetyYaml, "test.yaml");
EXPECT_NEAR(cfg["safety"]["scan"].require<double>("stop_distance"), 0.35, 1e-12);
EXPECT_EQ(cfg["safety"]["scan"].require<int>("min_front_rays"), 20);
EXPECT_TRUE(cfg["safety"]["scan"].require<bool>("enabled"));
EXPECT_NEAR(cfg["robot"].require<double>("wheel_separation"), 0.36, 1e-12);
}
TEST(Config, RequireNemKemDuongDanDayDu) {
const ConfigNode cfg = ConfigNode::LoadString(kSafetyYaml, "safety.yaml");
try {
cfg["safety"]["scan"].require<double>("stop_distence"); // go sai
FAIL() << "require() phai nem khi thieu key";
} catch (const ConfigError& e) {
const std::string msg = e.what();
// Thong bao phai co ba manh: file, duong dan key day du, ly do.
EXPECT_NE(msg.find("safety.yaml"), std::string::npos) << msg;
EXPECT_NE(msg.find("safety.scan.stop_distence"), std::string::npos) << msg;
EXPECT_NE(msg.find("thieu key"), std::string::npos) << msg;
}
}
TEST(Config, GetTraFallbackKhiThieu) {
const ConfigNode cfg = ConfigNode::LoadString(kSafetyYaml, "test.yaml");
EXPECT_NEAR(cfg["safety"]["scan"].get<double>("khong_co", 1.25), 1.25, 1e-12);
}
TEST(Config, SaiKieuLaLoiKeCaKhiCoFallback) {
// Thieu key co the co y (dung default). Sai kieu thi khong bao gio co y.
const ConfigNode cfg = ConfigNode::LoadString("a: khong_phai_so", "test.yaml");
EXPECT_THROW(cfg.get<double>("a", 0.0), ConfigError);
EXPECT_THROW(cfg.require<double>("a"), ConfigError);
}
TEST(Config, ChuoiKeyThieuKhongNoGiuaChung) {
const ConfigNode cfg = ConfigNode::LoadString(kSafetyYaml, "test.yaml");
// a["khong_co"]["cung_khong_co"] phai tra node Null chu khong duoc nem.
EXPECT_TRUE(cfg["khong_co"]["cung_khong_co"].IsNull());
EXPECT_NO_THROW((void)cfg["khong_co"]["cung_khong_co"]["sau_nua"]);
}
TEST(Config, UnknownKeysBatDuocTypo) {
const ConfigNode cfg = ConfigNode::LoadString(
"scan:\n stop_distance: 0.35\n stop_distence: 0.50\n", "safety.yaml");
const auto unknown = cfg["scan"].UnknownKeys({"stop_distance", "slow_distance"});
ASSERT_EQ(unknown.size(), 1u);
EXPECT_EQ(unknown[0], "scan.stop_distence");
}
TEST(Config, UnknownKeysRongKhiDungHet) {
const ConfigNode cfg = ConfigNode::LoadString(
"scan:\n stop_distance: 0.35\n", "safety.yaml");
EXPECT_TRUE(cfg["scan"].UnknownKeys({"stop_distance", "slow_distance"}).empty());
}
TEST(Config, DocChuoiVaMang) {
const ConfigNode cfg = ConfigNode::LoadString(kSafetyYaml, "test.yaml");
const auto cliff = cfg["safety"].require<std::vector<std::string>>("cliff_topics");
ASSERT_EQ(cliff.size(), 1u);
EXPECT_EQ(cliff[0], "/perception/cliff_detected");
// ultrasonic_topics la mang RONG, khong phai thieu key. Phan biet duoc hai
// thu nay la quan trong: mang rong nghia la "co cam bien nhung chua noi",
// thieu key nghia la "chua ai cau hinh".
const auto us = cfg["safety"].get<std::vector<std::string>>("ultrasonic_topics", {"x"});
EXPECT_TRUE(us.empty());
}
TEST(Config, AsStringMapGiuNguyenVan) {
// Khoi rtabmap: di thang vao ParametersMap, noi moi gia tri la chuoi.
// Kiem kieu o day se lam hong "true"/"0.05" thanh bool/double roi in lai khac.
const ConfigNode cfg = ConfigNode::LoadString(
"rtabmap:\n"
" Reg/Force3DoF: \"true\"\n"
" Icp/VoxelSize: \"0.05\"\n"
" Vis/MinInliers: \"20\"\n",
"slam.yaml");
const auto kv = cfg["rtabmap"].AsStringMap();
ASSERT_EQ(kv.size(), 3u);
bool found = false;
for (const auto& p : kv) {
if (p.first == "Icp/VoxelSize") {
EXPECT_EQ(p.second, "0.05");
found = true;
}
}
EXPECT_TRUE(found);
}
TEST(Config, FileKhongTonTaiNemRoRang) {
try {
ConfigNode::LoadFile("/khong/ton/tai/abc.yaml");
FAIL() << "phai nem";
} catch (const ConfigError& e) {
EXPECT_NE(std::string(e.what()).find("abc.yaml"), std::string::npos);
}
}
TEST(Config, YamlSaiCuPhapNemKemTenFile) {
try {
ConfigNode::LoadString("a: [1, 2\nb: 3", "hong.yaml");
FAIL() << "phai nem";
} catch (const ConfigError& e) {
EXPECT_NE(std::string(e.what()).find("hong.yaml"), std::string::npos);
}
}

254
test/test_ekf_se2.cc Normal file
View File

@@ -0,0 +1,254 @@
#include "vslam/ekf_se2.h"
#include <gtest/gtest.h>
#include <cmath>
#include "vslam/geometry.h"
using namespace vslam;
namespace {
constexpr double kPi = 3.14159265358979323846;
}
TEST(EkfSe2, KhoiTaoVeKhong) {
EkfSe2 ekf;
const Pose2D p = ekf.pose();
EXPECT_NEAR(p.x, 0.0, 1e-12);
EXPECT_NEAR(p.y, 0.0, 1e-12);
EXPECT_NEAR(p.theta, 0.0, 1e-12);
EXPECT_FALSE(ekf.Healthy(UnixTime::fromSec(1.0)));
}
// ===========================================================================
// SO VOI TICH PHAN GIAI TICH -- tieu chi nghiem thu cua P3.
// ===========================================================================
TEST(EkfSe2, DiThangKhopNghiemGiaiTich) {
EkfSe2 ekf;
constexpr double kV = 0.35;
constexpr double kDt = 0.02;
constexpr int kN = 500; // 10 giay
for (int i = 1; i <= kN; ++i) {
const UnixTime t = UnixTime::fromSec(1.0 + i * kDt);
ekf.UpdateOdomTwist(t, kV, 0.0, 1e-6, 1e-6);
ekf.UpdateImuYawRate(t, 0.0, 1e-8);
}
// (kN - 1) buoc, KHONG phai kN.
//
// Truoc phep do dau tien, filter khong biet van toc, nen khoang thoi gian
// truoc do khong tich phan duoc. Day la hanh vi DUNG: tich phan mot van toc
// chua biet la bia ra quang duong.
const Pose2D p = ekf.pose();
EXPECT_NEAR(p.x, kV * (kN - 1) * kDt, 1e-3);
EXPECT_NEAR(p.y, 0.0, 1e-6);
EXPECT_NEAR(p.theta, 0.0, 1e-6);
}
TEST(EkfSe2, CungTronKhopNghiemGiaiTich) {
// Robot chay tron ban kinh R = v/omega. Sau thoi gian T, pose giai tich:
// theta = omega*T
// x = R*sin(theta), y = R*(1 - cos(theta))
//
// Day la bai kiem duoc ke hoach P3 neu ra: "so voi tich phan giai tich
// duong tron ban kinh 2 m, sai lech < 1e-6".
EkfSe2Config c;
c.q_x = c.q_y = c.q_yaw = 1e-12; // tat nhieu qua trinh de so thuan tich phan
c.q_vx = c.q_vyaw = 1e-12;
EkfSe2 ekf(c);
constexpr double kV = 0.4;
constexpr double kW = 0.2; // R = 2 m
constexpr double kDt = 0.001; // buoc nho: so voi NGHIEM, khong voi Euler
constexpr int kN = 5000; // 5 giay
for (int i = 1; i <= kN; ++i) {
const UnixTime t = UnixTime::fromSec(1.0 + i * kDt);
ekf.UpdateOdomTwist(t, kV, kW, 1e-10, 1e-10);
}
// (kN - 1) buoc: xem ghi chu o DiThangKhopNghiemGiaiTich.
const double T = (kN - 1) * kDt;
const double R = kV / kW;
const double theta = kW * T;
const double gx = R * std::sin(theta);
const double gy = R * (1.0 - std::cos(theta));
const Pose2D p = ekf.pose();
EXPECT_NEAR(p.theta, theta, 1e-6);
EXPECT_NEAR(p.x, gx, 1e-3) << "x giai tich = " << gx;
EXPECT_NEAR(p.y, gy, 1e-3) << "y giai tich = " << gy;
}
TEST(EkfSe2, QuayTaiChoKhongDiChuyen) {
EkfSe2 ekf;
for (int i = 1; i <= 200; ++i) {
const UnixTime t = UnixTime::fromSec(1.0 + i * 0.01);
ekf.UpdateOdomTwist(t, 0.0, 0.8, 1e-8, 1e-8);
}
const Pose2D p = ekf.pose();
EXPECT_NEAR(p.x, 0.0, 1e-6);
EXPECT_NEAR(p.y, 0.0, 1e-6);
EXPECT_NEAR(p.theta, NormalizeAngle(0.8 * 199 * 0.01), 1e-4);
}
// --- Fuse hai nguon --------------------------------------------------------
TEST(EkfSe2, GyroChinhXacHonThiKeoKetQuaVePhiaGyro) {
// Encoder noi 2.0 rad/s (dang truot), gyro noi 0.5 rad/s va tin cay hon.
// Filter phai nghieng han ve gyro.
EkfSe2 ekf;
for (int i = 1; i <= 200; ++i) {
const UnixTime t = UnixTime::fromSec(1.0 + i * 0.01);
ekf.UpdateOdomTwist(t, 0.0, 2.0, 1e-6, /*var_vyaw=*/4.0); // sigma 2 rad/s
ekf.UpdateImuYawRate(t, 0.5, /*var=*/2.4e-7); // gyro rat tin
}
EXPECT_NEAR(ekf.vyaw(), 0.5, 0.02) << "phai tin gyro, khong tin banh truot";
}
TEST(EkfSe2, CovarianceLonThiPhepDoBiTinIT) {
// Day dung la co che ma wheel_odom dung de bao "dang truot".
auto final_vyaw = [](double var_vyaw) {
EkfSe2 ekf;
for (int i = 1; i <= 100; ++i) {
const UnixTime t = UnixTime::fromSec(1.0 + i * 0.01);
ekf.UpdateOdomTwist(t, 0.0, 1.0, 1e-6, var_vyaw);
}
return ekf.vyaw();
};
const double trusted = final_vyaw(1e-8); // tin tuyet doi
const double doubted = final_vyaw(100.0); // sigma 10 rad/s
EXPECT_NEAR(trusted, 1.0, 0.01);
EXPECT_LT(doubted, trusted * 0.9) << "covariance lon phai lam filter tin it hon";
}
TEST(EkfSe2, HealthyTheoSensorTimeout) {
EkfSe2Config c;
c.sensor_timeout = 0.2;
EkfSe2 ekf(c);
EXPECT_FALSE(ekf.Healthy(UnixTime::fromSec(1.0)));
ekf.UpdateOdomTwist(UnixTime::fromSec(1.0), 0.1, 0.0, 1e-6, 1e-6);
EXPECT_TRUE(ekf.Healthy(UnixTime::fromSec(1.1)));
EXPECT_FALSE(ekf.Healthy(UnixTime::fromSec(1.5)));
}
TEST(EkfSe2, ThoiGianLuiThiResetMocChuKhongTichPhanAm) {
EkfSe2 ekf;
ekf.UpdateOdomTwist(UnixTime::fromSec(10.0), 0.3, 0.0, 1e-6, 1e-6);
ekf.UpdateOdomTwist(UnixTime::fromSec(10.1), 0.3, 0.0, 1e-6, 1e-6);
const double x1 = ekf.pose().x;
ekf.Predict(UnixTime::fromSec(5.0)); // lui 5 giay
EXPECT_EQ(ekf.stats().time_resets, 1u);
EXPECT_NEAR(ekf.pose().x, x1, 1e-12) << "khong duoc day pose lui";
}
TEST(EkfSe2, PDoiXungVaXacDinhDuongSauNhieuBuoc) {
// 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.
EkfSe2 ekf;
for (int i = 1; i <= 20000; ++i) {
const UnixTime t = UnixTime::fromSec(1.0 + i * 0.005);
ekf.UpdateOdomTwist(t, 0.3, 0.1, 4e-4, 4e-4);
if (i % 4 == 0) ekf.UpdateImuYawRate(t, 0.1, 2.4e-7);
}
const Odometry o = ekf.State("odom", "base_footprint");
// Duong cheo phai duong.
EXPECT_GT(o.pose.covariance[0], 0.0);
EXPECT_GT(o.pose.covariance[7], 0.0);
EXPECT_GT(o.pose.covariance[35], 0.0);
// Doi xung.
EXPECT_NEAR(o.pose.covariance[1], o.pose.covariance[6], 1e-12);
// Va khong phan ky.
EXPECT_LT(o.pose.covariance[0], 1e6);
EXPECT_TRUE(std::isfinite(ekf.pose().x));
}
TEST(EkfSe2, YawLuonNamTrongDaiChuanHoa) {
EkfSe2 ekf;
for (int i = 1; i <= 2000; ++i) {
const UnixTime t = UnixTime::fromSec(1.0 + i * 0.01);
ekf.UpdateOdomTwist(t, 0.0, 2.0, 1e-8, 1e-8); // quay lien tuc nhieu vong
}
const double yaw = ekf.pose().theta;
EXPECT_LE(yaw, kPi);
EXPECT_GE(yaw, -kPi);
}
TEST(EkfSe2, OdomToBaseKhopPose) {
EkfSe2 ekf;
ekf.SetPose(Pose2D{1.5, -2.5, 0.7});
const Transform t = ekf.OdomToBase();
EXPECT_NEAR(t.translation.x, 1.5, 1e-12);
EXPECT_NEAR(t.translation.y, -2.5, 1e-12);
EXPECT_NEAR(t.translation.z, 0.0, 1e-12) << "SE(2): z luon 0";
EXPECT_NEAR(YawFromQuaternion(t.rotation), 0.7, 1e-12);
}
TEST(EkfSe2, SetPoseHaHiepPhuongSaiNhungGiuVanToc) {
EkfSe2 ekf;
for (int i = 1; i <= 500; ++i) {
ekf.UpdateOdomTwist(UnixTime::fromSec(1.0 + i * 0.02), 0.35, 0.0, 4e-4, 4e-4);
}
const double v_before = ekf.vx();
const double cov_before = ekf.State("o", "b").pose.covariance[0];
ekf.SetPose(Pose2D{0.0, 0.0, 0.0});
const double cov_after = ekf.State("o", "b").pose.covariance[0];
EXPECT_LT(cov_after, cov_before) << "biet chac vi tri -> ha hiep phuong sai";
EXPECT_NEAR(ekf.vx(), v_before, 1e-12)
<< "van toc KHONG duoc dat lai: robot co the dang chay khi bi dat lai pose";
}
TEST(EkfSe2, ZRollPitchDanhDauKhongQuanSatDuoc) {
EkfSe2 ekf;
ekf.UpdateOdomTwist(UnixTime::fromSec(1.0), 0.1, 0.0, 1e-6, 1e-6);
const Odometry o = ekf.State("odom", "base_footprint");
EXPECT_GE(o.pose.covariance[14], 1e5) << "z";
EXPECT_GE(o.pose.covariance[21], 1e5) << "roll -> do tu IMU";
EXPECT_GE(o.pose.covariance[28], 1e5) << "pitch -> do tu IMU";
}
TEST(EkfSe2, BoPhepDoVoLy) {
EkfSe2 ekf;
const Pose2D before = ekf.pose();
ekf.UpdateOdomTwist(UnixTime::fromSec(1.0), std::nan(""), 0.0, 1e-6, 1e-6);
ekf.UpdateOdomTwist(UnixTime::fromSec(1.1), 0.1, 0.0, -1.0, 1e-6); // var am
EXPECT_TRUE(std::isfinite(ekf.pose().x));
EXPECT_NEAR(ekf.pose().y, before.y, 1e-9);
}
TEST(EkfSe2, MahalanobisBoDiemLechKhiDuocBat) {
EkfSe2Config c;
c.mahalanobis_threshold = 3.0;
EkfSe2 ekf(c);
for (int i = 1; i <= 100; ++i) {
ekf.UpdateOdomTwist(UnixTime::fromSec(1.0 + i * 0.01), 0.3, 0.0, 1e-6, 1e-6);
}
const double v_before = ekf.vx();
// Mot diem vo ly voi covariance nho -> lech hang nghin sigma.
ekf.UpdateOdomTwist(UnixTime::fromSec(2.5), 100.0, 0.0, 1e-6, 1e-6);
EXPECT_GT(ekf.stats().rejected_outliers, 0u);
EXPECT_NEAR(ekf.vx(), v_before, 0.05) << "diem lech phai bi bo";
}
TEST(EkfSe2, MacDinhTatMahalanobis) {
// Bat cai nay chi an toan KHI covariance dau vao dung. Voi bug yaw-rate cu
// (thieu 2 bac) thi moi phep do deu trong nhu 11 sigma va cong nay se bo HET.
EkfSe2 ekf;
for (int i = 1; i <= 50; ++i) {
ekf.UpdateOdomTwist(UnixTime::fromSec(1.0 + i * 0.01), 0.3, 0.0, 1e-6, 1e-6);
}
ekf.UpdateOdomTwist(UnixTime::fromSec(2.0), 100.0, 0.0, 1e-6, 1e-6);
EXPECT_EQ(ekf.stats().rejected_outliers, 0u);
}

271
test/test_gazebo_world.cc Normal file
View File

@@ -0,0 +1,271 @@
// Doc `.world` cua Gazebo -> luoi chiem dung + hinh hoc 3D.
//
// ================== VI SAO BAI KIEM NAY TON TAI ==================
// Moi loi tim ra khi dung duong nay deu IM LANG: khong ngoai le, khong log,
// chi la kich thuoc sai. Va chung khong bu tru nhau -- mot toa nha 25 x 51 m
// da lan luot 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.
//
// Fixture `test/data/world/mini.world` co BA hop CUNG kich thuoc that
// (2.0 x 1.0 x 0.5 m) khai bao theo ba cach khac nhau. Ca ba phai cho cung
// mot dau vet tren luoi. Neu mot quy uoc bi bo qua, chi rieng hop do sai --
// va bai kiem chi ra ngay thu pham, khac han mot phep do tong.
#include <gtest/gtest.h>
#include <cmath>
#include <cstdlib>
#include <string>
#include <vector>
#include "vslam/gazebo_world.h"
namespace {
std::string DataDir() {
const char* e = std::getenv("VSLAM_TEST_DATA_DIR");
return e != nullptr ? std::string(e) : std::string("test/data");
}
vslam::GazeboWorld LoadMini(size_t* skipped) {
vslam::GazeboWorld w;
const std::string dir = DataDir() + "/world";
const vslam::StatusResponse st =
vslam::LoadGazeboWorld(dir + "/mini.world", {dir + "/models"}, &w,
skipped);
EXPECT_TRUE(st.ok()) << st.message;
return w;
}
// Bao loi cua cac o bi chiem thuoc mot vung x, tinh bang met.
struct Extent {
double x0 = 0, x1 = 0, y0 = 0, y1 = 0;
size_t cells = 0;
bool empty() const { return cells == 0; }
double w() const { return x1 - x0; }
double h() const { return y1 - y0; }
};
Extent OccupiedIn(const vslam::OccupancyGrid& g, double xlo, double xhi,
double ylo = -1e18, double yhi = 1e18) {
Extent e;
const double res = g.resolution;
double x0 = 1e18, x1 = -1e18, y0 = 1e18, y1 = -1e18;
for (uint32_t cy = 0; cy < g.height; ++cy) {
for (uint32_t cx = 0; cx < g.width; ++cx) {
if (g.data[static_cast<size_t>(cy) * g.width + cx] < 50) continue;
const double wx = g.origin.position.x + (cx + 0.5) * res;
const double wy = g.origin.position.y + (cy + 0.5) * res;
if (wx < xlo || wx > xhi) continue;
if (wy < ylo || wy > yhi) continue;
x0 = std::min(x0, wx); x1 = std::max(x1, wx);
y0 = std::min(y0, wy); y1 = std::max(y1, wy);
e.cells++;
}
}
if (e.cells > 0) { e.x0 = x0; e.x1 = x1; e.y0 = y0; e.y1 = y1; }
return e;
}
vslam::OccupancyGrid Raster(const vslam::GazeboWorld& w) {
vslam::OccupancyGrid g;
vslam::WorldRasterOptions o;
o.z_min = 0.05;
o.z_max = 1.20;
o.pad = 1.0;
EXPECT_TRUE(vslam::RasterizeGazeboWorld(w, o, &g).ok());
return g;
}
} // namespace
// Pose vo ly phai bi BO, khong phai duoc raster ra ngoai vu tru.
//
// `hospital.world` co san ba model mang z = -7.57769e+08: vat roi xuyen san
// trong mot phien Gazebo nao do roi world duoc luu lai. Giu chung lai khong
// lam luoi sai (tam giac roi ngoai dai z) nhung lam moi phep tinh bao loi vo
// nghia va cap phat instance 3D cho vat khong bao gio thay duoc.
TEST(GazeboWorld, BoPoseVoLy) {
size_t skipped = 0;
const vslam::GazeboWorld w = LoadMini(&skipped);
ASSERT_EQ(w.models.size(), 5u);
EXPECT_EQ(skipped, 1u);
for (const auto& m : w.models) {
EXPECT_LT(std::fabs(m.z), 1000.0) << m.name;
}
}
// `<scale>` cua model.sdf phai duoc ap.
//
// Bo qua the nay bien mot chiec xe day 2.4 m thanh 236 m. Hop `box_cm` ve
// bang centimet va mang <scale>0.01</scale>; khong ap thi no ra 200 x 100 m.
TEST(GazeboWorld, ApScaleCuaSdf) {
const vslam::OccupancyGrid g = Raster(LoadMini(nullptr));
const Extent e = OccupiedIn(g, 3.0, 7.0);
ASSERT_FALSE(e.empty());
EXPECT_NEAR(e.w(), 2.0, 0.15);
EXPECT_NEAR(e.h(), 1.0, 0.15);
}
// `<matrix>` cua node COLLADA phai duoc ap, va duoi `.DAE` VIET HOA phai doc
// duoc.
//
// Hai bay nay cung nam tren mot hop: bo qua duoi hoa thi file roi vao bo doc
// OBJ va bien mat hoan toan (0 o bi chiem); doc duoc nhung bo qua <matrix>
// thi ti le sai 10 lan.
TEST(GazeboWorld, ApMatrixVaDuoiFileVietHoa) {
const vslam::OccupancyGrid g = Raster(LoadMini(nullptr));
const Extent e = OccupiedIn(g, 8.0, 12.0);
ASSERT_FALSE(e.empty()) << "hop .DAE bien mat -- kiem so duoi file";
EXPECT_NEAR(e.w(), 2.0, 0.15);
EXPECT_NEAR(e.h(), 1.0, 0.15);
}
// Ba cach khai bao khac nhau phai cho CUNG mot ket qua.
//
// Day moi la phep kiem that su: tung hop dung kich thuoc van co the do ba loi
// khac nhau bu tru nhau. Bat chung phai bang nhau thi khong the bu tru.
TEST(GazeboWorld, BaQuyUocChoCungKetQua) {
const vslam::OccupancyGrid g = Raster(LoadMini(nullptr));
// ⚠️ Phai chan CA y: hop thu tu nam o (0, 6), cung dai x voi hop dau. Cua
// so chi theo x om ca hai va cho h() = 7.5 -- phep do khong con la cua
// MOT hop nua.
const Extent met = OccupiedIn(g, -2.0, 2.0, -2.0, 2.0);
const Extent cm = OccupiedIn(g, 3.0, 7.0);
const Extent mtx = OccupiedIn(g, 8.0, 12.0);
const Extent zup = OccupiedIn(g, 13.0, 17.0);
ASSERT_FALSE(met.empty());
ASSERT_FALSE(cm.empty());
ASSERT_FALSE(mtx.empty());
ASSERT_FALSE(zup.empty());
for (const Extent& e : {cm, mtx, zup}) {
EXPECT_NEAR(met.w(), e.w(), 0.1);
EXPECT_NEAR(met.h(), e.h(), 0.1);
}
}
// Yaw cua the hien phai duoc ap: hop thu tu quay 90 do nen dai va rong doi
// cho nhau.
TEST(GazeboWorld, ApYawCuaTheHien) {
const vslam::OccupancyGrid g = Raster(LoadMini(nullptr));
const Extent thang = OccupiedIn(g, -2.0, 2.0, -2.0, 2.0); // (0, 0), yaw 0
const Extent quay = OccupiedIn(g, -2.0, 2.0, 4.0, 8.0); // (0, 6), yaw 90
ASSERT_FALSE(thang.empty());
ASSERT_FALSE(quay.empty());
// Cung mot hop 2.0 x 1.0 m: quay 90 do thi dai va rong DOI CHO nhau.
EXPECT_NEAR(thang.w(), 2.0, 0.15);
EXPECT_NEAR(thang.h(), 1.0, 0.15);
EXPECT_NEAR(quay.w(), 1.0, 0.15);
EXPECT_NEAR(quay.h(), 2.0, 0.15);
// Va no phai nam dung cho: tam o y = 6.
EXPECT_NEAR((quay.y0 + quay.y1) / 2.0, 6.0, 0.1);
}
// `<up_axis>` phai bi BO QUA: no noi ve he toa do cua bo XUAT, khong phai cua
// du lieu trong file.
//
// `box_zup` khai Y_UP nhung du lieu da o Z-up va node khong xoay gi. Day dung
// la truong hop `..._walls_visual` geometry ID43, con ban VA CHAM cua chinh
// buc tuong do lai la Y-up that co node xoay. Cung mot buc tuong, hai file,
// hai cach -- nen khong the quyet dinh bang mot co chung cho ca file, va cung
// khong the doan tu ma tran node ("node don vi thi lat" sai chinh o day: node
// don vi nghia la KHONG CAN doi, khong phai CHUA doi).
//
// Ap nham lam buc tuong 3 m thanh thanh dung cao 56 m giua san.
TEST(GazeboWorld, BoQuaUpAxis) {
const vslam::OccupancyGrid g = Raster(LoadMini(nullptr));
const Extent e = OccupiedIn(g, 13.0, 17.0);
ASSERT_FALSE(e.empty());
EXPECT_NEAR(e.w(), 2.0, 0.15);
EXPECT_NEAR(e.h(), 1.0, 0.15);
}
// Chieu cao phai dung, khong chi mat bang.
//
// Mot hop bi lat truc van co the co mat bang dung ma cao gap hang chuc lan --
// va `RasterizeGazeboWorld` chi lay dai z [0.05, 1.20] nen no khong bao gio
// thay chieu cao. Phai do tren HINH HOC, khong tren luoi.
TEST(GazeboWorld, ChieuCaoHinhHocDung) {
vslam::WorldMeshes wm;
ASSERT_TRUE(vslam::ExportWorldMeshes(LoadMini(nullptr), true, &wm).ok());
for (const auto& g : wm.geoms) {
double zlo = 1e18, zhi = -1e18, xlo = 1e18, xhi = -1e18;
for (size_t i = 0; i + 2 < g.tri.size(); i += 3) {
xlo = std::min<double>(xlo, g.tri[i]);
xhi = std::max<double>(xhi, g.tri[i]);
zlo = std::min<double>(zlo, g.tri[i + 2]);
zhi = std::max<double>(zhi, g.tri[i + 2]);
}
EXPECT_NEAR(zhi - zlo, 0.5, 0.05) << g.model_name << ": cao sai";
EXPECT_NEAR(xhi - xlo, 2.0, 0.05) << g.model_name << ": rong sai";
}
}
// Hinh hoc 3D phai gop theo TEN MODEL: 5 the hien nhung chi 4 model khac nhau.
TEST(GazeboWorld, GopHinhHocTheoTenModel) {
vslam::WorldMeshes wm;
const vslam::StatusResponse st =
vslam::ExportWorldMeshes(LoadMini(nullptr), /*visual=*/true, &wm);
ASSERT_TRUE(st.ok()) << st.message;
EXPECT_EQ(wm.geoms.size(), 4u);
EXPECT_EQ(wm.instances.size(), 5u);
for (const auto& g : wm.geoms) {
EXPECT_EQ(g.tri.size() % 9, 0u);
EXPECT_GT(g.tri.size(), 0u);
}
}
// Khoi nhi phan phai giai ma lai duoc dung y nguyen.
//
// Dem NOI DUNG chu khong dem su kien: mot bo ma hoa tra ve khoi RONG co cung
// moi chi so van hanh voi mot bo dung.
TEST(GazeboWorld, MaHoaGiaiMaKhoiNhiPhan) {
vslam::WorldMeshes wm;
ASSERT_TRUE(vslam::ExportWorldMeshes(LoadMini(nullptr), true, &wm).ok());
std::string blob;
vslam::EncodeWorldMeshes(wm, &blob);
ASSERT_GE(blob.size(), 16u);
EXPECT_EQ(blob.compare(0, 4, "VSLW"), 0);
auto u32 = [&blob](size_t o) {
return static_cast<uint32_t>(
(static_cast<unsigned char>(blob[o])) |
(static_cast<unsigned char>(blob[o + 1]) << 8) |
(static_cast<unsigned char>(blob[o + 2]) << 16) |
(static_cast<unsigned char>(blob[o + 3]) << 24));
};
EXPECT_EQ(u32(4), 1u); // version
EXPECT_EQ(u32(8), wm.geoms.size());
EXPECT_EQ(u32(12), wm.instances.size());
// Duyet het khoi: kich thuoc phai khop chinh xac den byte cuoi.
size_t o = 16;
for (const auto& g : wm.geoms) {
const uint32_t name_len = u32(o); o += 4;
EXPECT_EQ(blob.compare(o, name_len, g.model_name), 0);
o += name_len + 3; // + r, g, b
const uint32_t n_tri = u32(o); o += 4;
EXPECT_EQ(n_tri, g.tri.size() / 9);
o += static_cast<size_t>(n_tri) * 36;
}
o += wm.instances.size() * 20;
EXPECT_EQ(o, blob.size()) << "kich thuoc khoi khong khop -- bo ma hoa va "
"bo giai ma da lech nhau";
}
// `EncodeWorldMeshes` phai GHI DE `out`, khong noi them.
//
// ⚠️ Chinh loi nay tung sinh mot file `.vsr` 17 GB va lam day o dia: bon bo
// ma hoa dung chung mot bo dem ma khong `clear()`.
TEST(GazeboWorld, MaHoaGhiDeKhongNoiThem) {
vslam::WorldMeshes wm;
ASSERT_TRUE(vslam::ExportWorldMeshes(LoadMini(nullptr), true, &wm).ok());
std::string blob;
vslam::EncodeWorldMeshes(wm, &blob);
const size_t once = blob.size();
vslam::EncodeWorldMeshes(wm, &blob);
EXPECT_EQ(blob.size(), once);
}

129
test/test_geometry.cc Normal file
View File

@@ -0,0 +1,129 @@
#include "vslam/geometry.h"
#include <gtest/gtest.h>
#include <cmath>
using namespace vslam;
namespace {
constexpr double kPi = 3.14159265358979323846;
constexpr double kEps = 1e-12;
} // namespace
TEST(Geometry, NormalizeAngle) {
EXPECT_NEAR(NormalizeAngle(0.0), 0.0, kEps);
EXPECT_NEAR(NormalizeAngle(kPi - 0.1), kPi - 0.1, 1e-12);
EXPECT_NEAR(NormalizeAngle(3.0 * kPi), -kPi, 1e-12);
EXPECT_NEAR(NormalizeAngle(-3.0 * kPi), -kPi, 1e-12);
EXPECT_NEAR(NormalizeAngle(2.0 * kPi + 0.5), 0.5, 1e-12);
}
TEST(Geometry, NormalizeAngleKhongTreoVoiNaN) {
// Ban ROS dung vong `while (a > pi) a -= 2pi;`. Mot NaN lan vao tu encoder
// hong lam vong do chay vo han va treo ca luong.
EXPECT_EQ(NormalizeAngle(std::nan("")), 0.0);
EXPECT_EQ(NormalizeAngle(std::numeric_limits<double>::infinity()), 0.0);
}
TEST(Geometry, YawRoundTrip) {
for (double yaw = -3.1; yaw < 3.1; yaw += 0.37) {
const Quaternion q = QuaternionFromYaw(yaw);
EXPECT_NEAR(YawFromQuaternion(q), yaw, 1e-12) << "yaw=" << yaw;
}
}
TEST(Geometry, RPYRoundTrip) {
const double r0 = 0.11, p0 = -0.23, y0 = 1.77;
const Quaternion q = QuaternionFromRPY(r0, p0, y0);
double r, p, y;
RPYFromQuaternion(q, &r, &p, &y);
EXPECT_NEAR(r, r0, 1e-12);
EXPECT_NEAR(p, p0, 1e-12);
EXPECT_NEAR(y, y0, 1e-12);
}
TEST(Geometry, PitchKepTruocAsin) {
// pitch = +-90 do la diem sai so lam tron day |sinp| vuot 1 va asin tra NaN.
// NaN o pitch lan vao gravity_align roi vao TF la duong lan truyen loi kho
// truy nhat -- phai kep, khong duoc de lot.
const Quaternion q = QuaternionFromRPY(0.0, kPi / 2.0, 0.0);
double r, p, y;
RPYFromQuaternion(q, &r, &p, &y);
EXPECT_FALSE(std::isnan(p));
EXPECT_NEAR(std::abs(p), kPi / 2.0, 1e-9);
}
TEST(Geometry, TransformComposeVaInverse) {
Transform a;
a.translation = Vector3{1.0, 2.0, 0.5};
a.rotation = QuaternionFromYaw(0.5);
Transform b;
b.translation = Vector3{-0.3, 0.7, 0.0};
b.rotation = QuaternionFromYaw(-1.2);
const Transform ab = TransformCompose(a, b);
const Transform back = TransformCompose(ab, TransformInverse(b));
EXPECT_NEAR(back.translation.x, a.translation.x, 1e-12);
EXPECT_NEAR(back.translation.y, a.translation.y, 1e-12);
EXPECT_NEAR(back.translation.z, a.translation.z, 1e-12);
EXPECT_NEAR(YawFromQuaternion(back.rotation), YawFromQuaternion(a.rotation), 1e-12);
}
TEST(Geometry, TransformPointQuaHaiBuoc) {
// Diem (1,0,0) trong frame quay 90 do quanh z va tinh tien (0,0,0)
// -> (0,1,0) trong frame cha.
Transform t;
t.translation = Vector3{0.0, 0.0, 0.0};
t.rotation = QuaternionFromYaw(kPi / 2.0);
const Point p = TransformPoint(t, Point{1.0, 0.0, 0.0});
EXPECT_NEAR(p.x, 0.0, 1e-12);
EXPECT_NEAR(p.y, 1.0, 1e-12);
EXPECT_NEAR(p.z, 0.0, 1e-12);
}
TEST(Geometry, SlerpDiDuongNgan) {
// a o 0 do, b o 350 do. Duong ngan la -10 do, khong phai +350 do.
const Quaternion a = QuaternionFromYaw(0.0);
const Quaternion b = QuaternionFromYaw(-10.0 * kPi / 180.0);
const Quaternion m = QuaternionSlerp(a, b, 0.5);
EXPECT_NEAR(YawFromQuaternion(m), -5.0 * kPi / 180.0, 1e-9);
}
TEST(Geometry, SlerpKhopGiaTriTinhTay) {
// Quay quanh z tu 0 den 90 do, t = 1/3 -> dung 30 do.
const Quaternion a = QuaternionFromYaw(0.0);
const Quaternion b = QuaternionFromYaw(kPi / 2.0);
const Quaternion m = QuaternionSlerp(a, b, 1.0 / 3.0);
EXPECT_NEAR(YawFromQuaternion(m), kPi / 6.0, 1e-9);
}
TEST(Geometry, Pose2DBetween) {
const Pose2D a{1.0, 2.0, kPi / 2.0};
const Pose2D b{1.0, 5.0, kPi / 2.0};
// b nam thang truoc a 3 m (vi a quay 90 do, truc x cua a huong theo +y toan cuc).
const Pose2D d = Pose2DBetween(a, b);
EXPECT_NEAR(d.x, 3.0, 1e-12);
EXPECT_NEAR(d.y, 0.0, 1e-12);
EXPECT_NEAR(d.theta, 0.0, 1e-12);
}
TEST(Geometry, Pose2DComposeLaNghichDaoCuaBetween) {
const Pose2D a{0.3, -1.2, 0.77};
const Pose2D b{2.5, 4.1, -2.0};
const Pose2D d = Pose2DBetween(a, b);
const Pose2D b2 = Pose2DCompose(a, d);
EXPECT_NEAR(b2.x, b.x, 1e-12);
EXPECT_NEAR(b2.y, b.y, 1e-12);
EXPECT_NEAR(b2.theta, NormalizeAngle(b.theta), 1e-12);
}
TEST(Geometry, Pose2DInverse) {
const Pose2D a{1.5, -0.5, 0.9};
const Pose2D id = Pose2DCompose(a, Pose2DInverse(a));
EXPECT_NEAR(id.x, 0.0, 1e-12);
EXPECT_NEAR(id.y, 0.0, 1e-12);
EXPECT_NEAR(id.theta, 0.0, 1e-12);
}

164
test/test_mcu_protocol.cc Normal file
View File

@@ -0,0 +1,164 @@
#include "vslam/mcu_protocol.h"
#include <gtest/gtest.h>
#include <string>
using namespace vslam;
// --- Ban ghi hop le --------------------------------------------------------
TEST(McuProtocol, ParseImu) {
McuRecord r;
ASSERT_TRUE(ParseMcuLine("I,123456,0.01,-0.02,0.03,0.1,-0.2,9.81", &r));
EXPECT_EQ(r.type, McuRecordType::kImu);
EXPECT_EQ(r.micros, 123456u);
EXPECT_DOUBLE_EQ(r.gx, 0.01);
EXPECT_DOUBLE_EQ(r.gy, -0.02);
EXPECT_DOUBLE_EQ(r.gz, 0.03);
EXPECT_DOUBLE_EQ(r.ax, 0.1);
EXPECT_DOUBLE_EQ(r.ay, -0.2);
EXPECT_DOUBLE_EQ(r.az, 9.81);
}
TEST(McuProtocol, ParseBaro) {
McuRecord r;
ASSERT_TRUE(ParseMcuLine("B,500,101325.5,24.3", &r));
EXPECT_EQ(r.type, McuRecordType::kBaro);
EXPECT_DOUBLE_EQ(r.pressure_pa, 101325.5);
EXPECT_DOUBLE_EQ(r.temp_c, 24.3);
}
TEST(McuProtocol, ParseEncoder) {
// Ban ghi MOI. Giao thuc cu chi co I/B/P, khong co encoder, du phan cung
// co encoder -- ban ROS gia dinh mot firmware chua ton tai.
McuRecord r;
ASSERT_TRUE(ParseMcuLine("E,700,12345,-6789", &r));
EXPECT_EQ(r.type, McuRecordType::kEncoder);
EXPECT_EQ(r.micros, 700u);
EXPECT_EQ(r.ticks_l, 12345);
EXPECT_EQ(r.ticks_r, -6789);
}
TEST(McuProtocol, ParsePong) {
McuRecord r;
ASSERT_TRUE(ParseMcuLine("P,900,42", &r));
EXPECT_EQ(r.type, McuRecordType::kPong);
EXPECT_EQ(r.seq, 42u);
}
TEST(McuProtocol, BuildPingCoNewline) {
EXPECT_EQ(BuildPing(7), "p,7\n");
EXPECT_EQ(BuildPing(0), "p,0\n");
}
// --- Dong hong phai bi TU CHOI, khong duoc coi la du lieu 0 ---------------
TEST(McuProtocol, TuChoiDongHong) {
McuRecord r;
// Mot dong hong bi coi la du lieu 0 nghia la mot mau IMU gia voi gia toc 0
// lot vao bo loc -- va bo loc thi khong co cach nao biet.
EXPECT_FALSE(ParseMcuLine("", &r));
EXPECT_FALSE(ParseMcuLine("I", &r));
EXPECT_FALSE(ParseMcuLine("I,", &r));
EXPECT_FALSE(ParseMcuLine("X,1,2,3", &r)) << "ky tu loai la";
EXPECT_FALSE(ParseMcuLine("II,1,2,3", &r)) << "ky tu loai 2 ky tu";
EXPECT_FALSE(ParseMcuLine("I,abc,1,2,3,4,5,6", &r))<< "micros khong phai so";
EXPECT_FALSE(ParseMcuLine("I,1,2,3", &r)) << "IMU thieu truong";
EXPECT_FALSE(ParseMcuLine("I,1,2,3,4,5,6,7,8", &r))<< "IMU thua truong";
EXPECT_FALSE(ParseMcuLine("B,1,2", &r)) << "baro thieu truong";
EXPECT_FALSE(ParseMcuLine("E,1,2", &r)) << "encoder thieu truong";
EXPECT_FALSE(ParseMcuLine("E,1,2,3,4", &r)) << "encoder thua truong";
EXPECT_FALSE(ParseMcuLine("P,1", &r)) << "pong thieu seq";
EXPECT_FALSE(ParseMcuLine("E,1,1.5,2", &r)) << "tick phai la so nguyen";
EXPECT_FALSE(ParseMcuLine("I,1,x,0,0,0,0,0", &r)) << "gyro khong phai so";
}
TEST(McuProtocol, TuChoiSoVuotDai) {
McuRecord r;
EXPECT_FALSE(ParseMcuLine("E,1,99999999999,0", &r));
EXPECT_FALSE(ParseMcuLine("I,99999999999,0,0,0,0,0,0", &r));
}
TEST(McuProtocol, ChapNhanSoAmVaKhoaHoc) {
McuRecord r;
ASSERT_TRUE(ParseMcuLine("I,1,-1.5e-3,0,0,0,0,-9.81", &r));
EXPECT_DOUBLE_EQ(r.gx, -1.5e-3);
EXPECT_DOUBLE_EQ(r.az, -9.81);
}
// --- TickUnwrapper ---------------------------------------------------------
TEST(TickUnwrapper, DemTangBinhThuong) {
TickUnwrapper u;
EXPECT_EQ(u.Unwrap(0), 0);
EXPECT_EQ(u.Unwrap(1000), 1000);
EXPECT_EQ(u.Unwrap(2000), 2000);
EXPECT_EQ(u.wrap_count(), 0u);
}
TEST(TickUnwrapper, DemGiamKhiRobotLui) {
TickUnwrapper u;
u.Unwrap(5000);
EXPECT_EQ(u.Unwrap(4000), 4000);
EXPECT_EQ(u.Unwrap(-1000), -1000);
EXPECT_EQ(u.wrap_count(), 0u) << "lui binh thuong bi hieu nham la tran";
}
TEST(TickUnwrapper, TranLen) {
TickUnwrapper u;
constexpr int32_t kMax = 2147483647;
const int64_t a = u.Unwrap(kMax - 100);
const int64_t b = u.Unwrap(kMax);
const int64_t c = u.Unwrap(-2147483648 + 100); // vua tran
EXPECT_EQ(u.wrap_count(), 1u);
EXPECT_GT(b, a);
EXPECT_GT(c, b) << "sau khi tran, so tick tich luy phai TIEP TUC tang";
EXPECT_EQ(c - b, 101);
}
TEST(TickUnwrapper, TranXuongKhiLuiLau) {
TickUnwrapper u;
constexpr int32_t kMin = -2147483647 - 1;
const int64_t a = u.Unwrap(kMin + 100);
const int64_t b = u.Unwrap(2147483647 - 100); // tran xuong
EXPECT_EQ(u.wrap_count(), 1u);
EXPECT_LT(b, a) << "lui qua moc tran phai tiep tuc GIAM";
EXPECT_EQ(a - b, 201);
}
TEST(TickUnwrapper, QuangDuongDaiKhongMat) {
// Ban ghi E gui tick TICH LUY chu khong gui delta. Ly do: mat mot dong
// serial thi delta mat vinh vien mot doan quang duong va khong the phat
// hien; con tich luy thi dong ke tiep tu no sua lai.
//
// Bai nay chay qua 3 lan tran.
TickUnwrapper u;
int64_t expected = 0;
int64_t raw = 0;
int64_t last = 0;
for (int i = 0; i < 300000; ++i) {
raw += 50000;
expected += 50000;
last = u.Unwrap(static_cast<int32_t>(raw & 0xFFFFFFFF));
}
EXPECT_EQ(last, expected);
EXPECT_GT(u.wrap_count(), 2u);
}
TEST(TickUnwrapper, MatDongVanTuSuaDuoc) {
// Bo qua vai ban ghi (mat dong serial) roi tiep tuc: gia tri tich luy van
// dung, khong tich luy sai so.
TickUnwrapper a, b;
int64_t last_a = 0, last_b = 0;
for (int i = 1; i <= 100; ++i) {
const int32_t raw = static_cast<int32_t>(i * 1000);
last_a = a.Unwrap(raw);
if (i % 3 == 0) last_b = b.Unwrap(raw); // chi nhan 1/3 so dong
}
EXPECT_EQ(last_a, 100000);
EXPECT_EQ(last_b, 99000); // dong cuoi nhan duoc la i=99
}

View File

@@ -0,0 +1,170 @@
// Test TICH HOP duong odometry: sim -> encoder -> wheel_odom -> EKF.
//
// Khac cac test don vi o test_wheel_odometry.cc va test_ekf_se2.cc: bai nay
// chay CA CHUOI tren mot robot ao co truot banh that, va do sai so so voi
// ground truth. Day la bai L2 cua repo cu ("odometry lech < 2% so voi
// /ground_truth/odom"), viet lai khong ROS.
#include <gtest/gtest.h>
#include <cmath>
#include "vslam/ekf_se2.h"
#include "vslam/geometry.h"
#include "vslam/sim_source.h"
#include "vslam/wheel_odometry.h"
using namespace vslam;
namespace {
struct Result {
Pose2D ground_truth, ekf, wheel_raw;
double distance = 0.0;
uint64_t slip_events = 0;
double ekf_error() const { return Distance2D(ekf, ground_truth); }
double raw_error() const { return Distance2D(wheel_raw, ground_truth); }
double ekf_error_pct() const { return 100.0 * ekf_error() / distance; }
double ekf_yaw_error() const {
return std::fabs(AngleDiff(ekf.theta, ground_truth.theta));
}
double raw_yaw_error() const {
return std::fabs(AngleDiff(wheel_raw.theta, ground_truth.theta));
}
};
// Chay duong vuong (giong UMBmark): thang -- quay 90 -- lap.
Result RunSquare(double slip_sym, double slip_diff, int laps = 2) {
SimConfig sc;
sc.speed = 0.0; // chay nhanh nhat co the
// Bai nay khong dung depth. Mot khung 320x240 la 76800 tia raycast, va bai
// nay chay hang tram giay mo phong -- de bat se cham gap hang chuc lan.
sc.enable_depth_camera = false;
sc.slip_factor = slip_sym;
sc.slip_differential = slip_diff;
sc.slip_accel_threshold = 0.05;
SimSource sim(sc);
EXPECT_TRUE(sim.Open().ok());
WheelOdometryConfig wc;
wc.wheel_radius = sc.wheel_radius;
wc.wheel_separation = sc.wheel_separation;
WheelOdometry wo(wc);
EkfSe2 ekf;
sim.mcu()->SetImuCallback([&](ImuPtr m) {
wo.FeedGyroZ(m->header.stamp, m->angular_velocity.z);
ekf.UpdateImuYawRate(m->header.stamp, m->angular_velocity.z, 2.4e-7);
});
sim.base()->SetEncoderCallback([&](const EncoderReading& e) {
Odometry o;
if (!wo.Update(e.stamp, e.left_rad, e.right_rad, &o)) return;
// Truyen THANG covariance tu wheel_odom vao EKF -- day chinh la cach
// wheel_odom bao "dang truot, dung tin toi".
ekf.UpdateOdomTwist(e.stamp, o.twist.twist.linear.x, o.twist.twist.angular.z,
o.twist.covariance[0], o.twist.covariance[35]);
});
sim.mcu()->Open();
sim.base()->Open();
for (int lap = 0; lap < laps; ++lap) {
for (int side = 0; side < 4; ++side) {
for (int k = 0; k < 20; ++k) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.4); }
for (int k = 0; k < 20; ++k) { sim.base()->SetVelocity(0.0, 0.7); sim.RunFor(0.11); }
}
}
for (int k = 0; k < 10; ++k) { sim.base()->SetVelocity(0.0, 0.0); sim.RunFor(0.1); }
Result r;
r.ground_truth = sim.ground_truth();
r.ekf = ekf.pose();
r.wheel_raw = wo.pose();
r.distance = sim.stats().distance_travelled;
r.slip_events = wo.stats().slip_events;
return r;
}
} // namespace
TEST(OdometryPipeline, KhongTruotThiSaiSoGanKhong) {
// Tieu chi L2 cua repo cu: lech < 2% quang duong. Khong truot thi phai tot
// hon han nguong do.
const Result r = RunSquare(0.0, 0.0);
EXPECT_GT(r.distance, 5.0) << "bai test phai thuc su di duoc mot doan";
EXPECT_LT(r.ekf_error_pct(), 0.5)
<< "sai so " << r.ekf_error() << " m tren " << r.distance << " m";
EXPECT_LT(r.ekf_yaw_error(), 0.02);
EXPECT_EQ(r.slip_events, 0u);
}
// ===========================================================================
// TRUOT VI SAI -- day la thu ca co che duoc thiet ke de xu ly.
//
// Mot banh truot nhieu hon banh kia sinh mot phep quay GIA ma gyro khong thay.
// wheel_odom bat duoc bang |omega_encoder - gyro_z|, nang covariance, va EKF
// tu dong chuyen sang tin gyro.
// ===========================================================================
TEST(OdometryPipeline, TruotViSai_EKF_PhucHoiDuocHuong) {
const Result r = RunSquare(0.0, 0.5);
EXPECT_GT(r.slip_events, 100u) << "phai phat hien duoc truot vi sai";
// wheel_odom THO bi hong nang: huong lech hang chuc do.
EXPECT_GT(r.raw_yaw_error(), 1.0)
<< "bai test chua tao du truot de co y nghia";
// EKF phai phuc hoi duoc huong nho gyro.
EXPECT_LT(r.ekf_yaw_error(), 0.05)
<< "EKF lech yaw " << r.ekf_yaw_error() * 180.0 / 3.14159 << " do";
// Va vi tri phai tot hon han ban tho.
EXPECT_LT(r.ekf_error(), r.raw_error() * 0.2)
<< "EKF " << r.ekf_error() << " m vs tho " << r.raw_error() << " m";
EXPECT_LT(r.ekf_error_pct(), 2.0) << "van phai dat tieu chi L2 < 2%";
}
// ===========================================================================
// TRUOT DOI XUNG -- GIOI HAN THAT CUA PHUONG PHAP, khong phai bug.
//
// Ca hai banh truot bang nhau thi KHONG sinh chenh lech quay, nen
// slip_metric = |omega_encoder - gyro_z| bang 0 va khong co gi de phat hien.
// Gyro chi nhin thay phep QUAY.
//
// Bai nay ton tai de ghi lai gioi han do bang code, thay vi de ai do sau nay
// phat hien lai bang cach dieu tra mot robot di lech 13% ma khong co canh bao.
// Muon bat loai truot nay can mot nguon thu hai: visual odometry, hoac scan
// matching -- tuc la RTAB-Map o P6.
// ===========================================================================
TEST(OdometryPipeline, TruotDoiXung_GYRO_KHONG_PHAT_HIEN_DUOC) {
const Result r = RunSquare(2.0, 0.0);
EXPECT_EQ(r.slip_events, 0u)
<< "truot doi xung khong sinh chenh lech quay -- gyro khong the thay";
// Va hau qua: sai so lon ma khong co canh bao nao.
EXPECT_GT(r.ekf_error_pct(), 5.0)
<< "neu sai so nho thi bai test chua tao du truot";
// Huong VAN dung -- chi co quang duong bi thoi phong.
EXPECT_LT(r.ekf_yaw_error(), 0.05)
<< "truot doi xung khong lam sai huong, chi lam sai quang duong";
}
TEST(OdometryPipeline, EKF_BamSatWheelOdomKhiKhongCoTruot) {
// Khong truot thi EKF khong duoc "sua" gi ca -- no chi lam muot.
const Result r = RunSquare(0.0, 0.0);
EXPECT_LT(Distance2D(r.ekf, r.wheel_raw), 0.05)
<< "EKF lech khoi wheel_odom qua nhieu khi khong co ly do gi";
}
TEST(OdometryPipeline, ChayLaiChoKetQuaGiongHET) {
// Toan bo duong ong phai tat dinh: khong stage nao doc dong ho he thong.
const Result a = RunSquare(0.0, 0.3);
const Result b = RunSquare(0.0, 0.3);
EXPECT_NEAR(a.ekf.x, b.ekf.x, 1e-12);
EXPECT_NEAR(a.ekf.y, b.ekf.y, 1e-12);
EXPECT_NEAR(a.ekf.theta, b.ekf.theta, 1e-12);
EXPECT_EQ(a.slip_events, b.slip_events);
}

717
test/test_perception.cc Normal file
View File

@@ -0,0 +1,717 @@
// Test cho vslam_perception.
//
// Cach dung cua cac test hinh hoc: dung mot anh depth TONG HOP bang cach
// chieu nguoc -- voi moi pixel, tinh giao tia x mat phang san roi ghi dung
// depth do. Anh sinh ra la cai ma mot camera that nhin san phang HOAN HAO se
// thay, nen bat ky vuc nao bi phat hien deu la duong tinh gia.
#include <gtest/gtest.h>
#include <cmath>
#include <vector>
#include "vslam/cliff_detect.h"
#include "vslam/clock.h"
#include "vslam/depth_filter.h"
#include "vslam/depth_to_cloud.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/node_constants.h"
#include "vslam/perception_pipeline.h"
using namespace vslam;
namespace {
constexpr int kW = 320, kH = 240;
CameraInfo MakeInfo() {
CameraInfo info;
info.width = kW;
info.height = kH;
info.binning_x = 1;
info.binning_y = 1;
// D410 640x480 -> giam mau 2 lan. K la cua do phan giai LUC HIEU CHUAN.
info.k[0] = 465.7; // fx
info.k[2] = 160.5; // cx
info.k[4] = 465.7; // fy
info.k[5] = 120.5; // cy
info.k[8] = 1.0;
return info;
}
// Camera nghieng xuong `pitch_deg` do, cao `height` m, tai base_link.
// Frame quang hoc: +Z toi truoc, +X phai, +Y xuong.
Transform MakeCamExtrinsic(double height_above_axle, double pitch_deg) {
Transform t = TransformIdentity();
t.translation = Vector3{0.10, 0.0, height_above_axle};
// optical -> base: xoay de +Z_optical thanh +X_base, +Y_optical thanh -Z_base
const Quaternion optical_to_base = QuaternionFromRPY(-M_PI / 2, 0.0, -M_PI / 2);
const Quaternion down = QuaternionFromRPY(0.0, pitch_deg * M_PI / 180.0, 0.0);
t.rotation = QuaternionMultiply(down, optical_to_base);
return t;
}
struct DepthImage {
std::vector<float> px;
Image img;
};
// Chieu nguoc: moi pixel nhan dung depth ma mot mat phang o do cao `floor_z`
// (trong base_footprint) se cho. `hole_test` tra true tai pixel can dat NaN,
// `drop_z` tra do cao san thuc te tai (x,y) neu muon tao vuc that.
template <typename FloorFn>
DepthImage RenderFloor(const CameraInfo& info, const Transform& cam_to_base,
double roll, double pitch, double wheel_radius,
FloorFn floor_z_at) {
DepthImage d;
d.px.assign(static_cast<size_t>(kW) * kH, std::numeric_limits<float>::quiet_NaN());
const Transform T = TransformCompose(TiltLift(roll, pitch, wheel_radius), cam_to_base);
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;
const double fx = info.fx_binned(), fy = info.fy_binned();
const double cx = info.cx_binned(), cy = info.cy_binned();
for (int v = 0; v < kH; ++v) {
for (int u = 0; u < kW; ++u) {
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; // tia khong chuc xuong -> khong cham san
// Lan 1: giao voi mat phang z=0 de biet diem cham o dau
const double z0 = -tz / denom;
if (z0 <= 0.0) continue;
const Point p0 = TransformPoint(T, Point{z0 * a, z0 * b, z0});
// Lan 2: san that o do cao floor_z tai (x,y) do
const double fz = floor_z_at(p0.x, p0.y);
if (!std::isfinite(fz)) continue; // LO: khong co gi tra ve
const double z1 = (fz - tz) / denom;
if (z1 <= 0.0 || z1 > 12.0) continue;
d.px[static_cast<size_t>(v) * kW + u] = static_cast<float>(z1);
}
}
d.img.header.frame_id = kCameraDepthOpticalFrame;
d.img.header.stamp = UnixTime::fromSec(1000.0);
d.img.width = kW;
d.img.height = kH;
d.img.step = kW * sizeof(float);
d.img.format = PixelFormat::kFloat32;
d.img.data = reinterpret_cast<const uint8_t*>(d.px.data());
return d;
}
CliffDetectConfig CliffCfg(double nominal_tz) {
CliffDetectConfig c;
c.nominal_tz = nominal_tz;
return c;
}
Imu MakeImu(double t, double ax, double ay, double az, double wx, double wy) {
Imu m;
m.header.stamp = UnixTime::fromSec(t);
m.linear_acceleration = Vector3{ax, ay, az};
m.angular_velocity = Vector3{wx, wy, 0.0};
return m;
}
} // namespace
// ==================== GravityAlign ====================
TEST(GravityAlign, DungYenThiHoiTuVeKhong) {
GravityAlign g(GravityAlignConfig{});
for (int i = 0; i < 2000; ++i) {
g.FeedImu(MakeImu(100.0 + i * 0.005, 0.0, 0.0, kGravity, 0.0, 0.0));
}
EXPECT_TRUE(g.valid());
EXPECT_NEAR(g.roll(), 0.0, 1e-6);
EXPECT_NEAR(g.pitch(), 0.0, 1e-6);
EXPECT_TRUE(g.accel_ok());
}
TEST(GravityAlign, NghiengTinhThiHoiTuVeGocThat) {
// Robot dung yen nghieng 10 do quanh +Y (mui chuc xuong theo quy uoc ROS).
const double th = 10.0 * M_PI / 180.0;
GravityAlign g(GravityAlignConfig{});
for (int i = 0; i < 4000; ++i) {
g.FeedImu(MakeImu(100.0 + i * 0.005, -kGravity * std::sin(th), 0.0,
kGravity * std::cos(th), 0.0, 0.0));
}
EXPECT_NEAR(g.pitch(), th, 1e-3);
EXPECT_NEAR(g.roll(), 0.0, 1e-3);
}
TEST(GravityAlign, DauTiltDungChieu) {
// Day la test khoa DAU. Bo loc cho pitch = theta; TiltLift(theta) phai
// dua mot diem do trong base_link ve dung do cao that trong base_footprint.
// Phu dinh dau se lam nghieng GAP DOI thay vi triet tieu -- loi im lang,
// chi hien ra khi robot len doc.
const double th = 10.0 * M_PI / 180.0;
// Diem nam tren san thuc te, cach truc banh 2 m phia truoc, z = -wheel_radius
// (tuc la tren mat dat) khi robot PHANG.
// Khi robot nghieng mui xuong th, cung diem san do do duoc trong base_link
// tai toa do quay -th.
const double r = 2.0, z_axle = -0.075;
// p_body = R_y(theta)^T * p_world. Nham chieu o day chinh la loi ma test
// nay sinh ra de bat -- hai lan nham chieu se trie^t tieu nhau va test se
// xanh trong khi code sai.
const double x_body = r * std::cos(th) - z_axle * std::sin(th);
const double z_body = r * std::sin(th) + z_axle * std::cos(th);
const Transform T = TiltLift(th, 0.0, 0.075);
// Nhap nham: TiltLift dung RPY nen pitch la tham so thu 2.
const Transform Tp = TiltLift(0.0, th, 0.075);
const Point q = TransformPoint(Tp, Point{x_body, 0.0, z_body});
EXPECT_NEAR(q.z, 0.0, 1e-9) << "nghieng khong bi triet tieu -> sai dau";
EXPECT_NEAR(q.x, r, 1e-9);
(void)T;
}
TEST(GravityAlign, TangTocKhongBiHieuNhamThanhNghieng) {
// Robot tang toc 2.0 m/s^2 tren san PHANG. Gia toc ke doc ax = -2.0.
// Khong tru gia toc rieng, bo loc se hieu thanh nghieng ~11.7 do -- day
// dung la loi da tung lam cliff_detect bao vuc gia (xem MEMORY).
const double a_lin = 2.0;
GravityAlignConfig cfg;
GravityAlign g_on(cfg);
cfg.use_odom_accel = false;
GravityAlign g_off(cfg);
double v = 0.0;
for (int i = 0; i < 4000; ++i) {
const double t = 100.0 + i * 0.005;
v += a_lin * 0.005;
// Gia toc ke do LUC RIENG (specific force): dung yen doc +g huong len,
// tang toc a ve truoc doc +a theo +X. Khong phai luc quan tinh -a.
const Imu m = MakeImu(t, a_lin, 0.0, kGravity, 0.0, 0.0);
g_on.FeedOdom(UnixTime::fromSec(t), v, 0.0);
g_on.FeedImu(m);
g_off.FeedImu(m);
}
EXPECT_NEAR(g_on.pitch(), 0.0, 0.02) << "tru gia toc rieng khong hieu qua";
EXPECT_GT(std::fabs(g_off.pitch()), 0.15)
<< "khong tru gia toc rieng ma van khong nghieng -- test khong do dung cai gi";
}
TEST(GravityAlign, VaChamThiCongDongVaChiTichPhanGyro) {
GravityAlignConfig cfg;
cfg.use_odom_accel = false;
GravityAlign g(cfg);
for (int i = 0; i < 400; ++i) {
g.FeedImu(MakeImu(100.0 + i * 0.005, 0.0, 0.0, kGravity, 0.0, 0.0));
}
const uint64_t acc0 = g.stats().accel_accepted;
// Soc 5 g
for (int i = 0; i < 100; ++i) {
g.FeedImu(MakeImu(102.0 + i * 0.005, 0.0, 0.0, 5 * kGravity, 0.0, 0.0));
}
EXPECT_EQ(g.stats().accel_accepted, acc0) << "cong |a|~g khong dong khi bi soc";
EXPECT_GT(g.stats().accel_rejected, 0u);
EXPECT_FALSE(g.accel_ok());
}
TEST(GravityAlign, CatDaiChieuCaoSauKhiXoay) {
GravityAlign g(GravityAlignConfig{});
g.FeedImu(MakeImu(100.0, 0, 0, kGravity, 0, 0));
g.FeedImu(MakeImu(100.005, 0, 0, kGravity, 0, 0));
PointCloudXYZ in, out;
in.points = {
PointXYZ{0.0f, 0.0f, 1.0f}, // truoc mat, ngang tam camera
PointXYZ{0.0f, 2.0f, 1.0f}, // rat thap (+Y quang hoc la XUONG)
PointXYZ{0.0f, -2.0f, 1.0f}, // rat cao
PointXYZ{std::numeric_limits<float>::quiet_NaN(), 0.0f, 1.0f},
};
const Transform cam = MakeCamExtrinsic(0.728, 10.0);
ASSERT_TRUE(g.Align(in, cam, UnixTime::fromSec(100.0), &out));
EXPECT_EQ(out.header.frame_id, std::string(kBaseFootprintFrame));
EXPECT_LT(out.points.size(), in.points.size()) << "khong cat dai gi ca";
for (const PointXYZ& p : out.points) {
EXPECT_GE(p.z, 0.06f);
EXPECT_LE(p.z, 1.20f);
}
}
// ==================== CliffDetect ====================
TEST(CliffDetect, SanPhangKhongBaoVuc) {
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double, double) { return 0.0; });
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_TRUE(r.judged) << "bail: " << CliffBailName(r.bail);
EXPECT_FALSE(r.detected);
EXPECT_GT(r.n_inwin, 100) << "khong tia nao roi vao cua so -- hinh hoc test sai";
EXPECT_EQ(r.n_cliff, 0);
EXPECT_TRUE(r.leveled);
EXPECT_LT(r.lvl_mad, 1e-6) << "san hoan hao ma MAD khac 0";
}
TEST(CliffDetect, VucThatBiPhatHien) {
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
// Bac thang xuong 0.30 m bat dau tu x = 1.6 m; be mat duoi VAN tra ve so do
// (bac thang sang, thay duoc day).
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075,
[](double x, double) { return x > 1.6 ? -0.30 : 0.0; });
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_TRUE(r.judged) << "bail: " << CliffBailName(r.bail);
EXPECT_TRUE(r.detected);
EXPECT_GT(r.n_drop, 0);
EXPECT_GE(r.n_cliff, 12);
}
TEST(CliffDetect, VucToiTraVeLoVanBiPhatHien) {
// Day la ly do CA detector chay tren anh depth chu khong phai cloud.
// Bac thang TOI khong tra ve gi -> pcl::PassThrough se xoa sach tin hieu.
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double x, double) {
return x > 1.6 ? std::numeric_limits<double>::quiet_NaN() : 0.0;
});
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_TRUE(r.judged) << "bail: " << CliffBailName(r.bail);
EXPECT_TRUE(r.detected);
EXPECT_GT(r.n_hole, 0) << "khong dem duoc lo nao";
EXPECT_EQ(r.n_drop, 0);
}
TEST(CliffDetect, DanhDauTaiMepChuKhongTaiDiemTraVe) {
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
// Vuc SAU 2 m: diem tra ve o rat xa, nhung mep van o x ~ 1.6 m.
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075,
[](double x, double) { return x > 1.6 ? -2.0 : 0.0; });
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
ASSERT_TRUE(r.detected) << "bail: " << CliffBailName(r.bail);
ASSERT_FALSE(r.edge_cloud.points.empty());
double x_max = -1e9;
for (const PointXYZ& p : r.edge_cloud.points) x_max = std::max(x_max, double(p.x));
EXPECT_LT(x_max, 2.6) << "danh dau o day vuc thay vi o mep -- robot se dung MUON";
// z giu am co y, xem ghi chu trong cliff_detect.cc
EXPECT_LT(r.edge_cloud.points[0].z, 0.0f);
}
TEST(CliffDetect, NghiengKhongBuThiBaoVucGia) {
// Hoi quy cho loi da co that trong repo cu (1625/1832 mau bao vuc gia).
// Robot nghieng mui xuong 4 do; neu KHONG bao nghieng cho detector, phep
// khop mat san se lech va tia xa se roi duoi nguong.
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tilt = 4.0 * M_PI / 180.0;
const double tz_ok = TransformCompose(TiltLift(0, tilt, 0.075), cam).translation.z;
// Anh duoc chup khi robot DANG nghieng, san van phang.
DepthImage d =
RenderFloor(info, cam, 0, tilt, 0.075, [](double, double) { return 0.0; });
CliffDetectConfig cfg = CliffCfg(tz_ok);
cfg.max_tz_dev = 0.20; // cho qua cong tz de test rieng phan hinh hoc
CliffDetect good(cfg);
good.SetTilt(UnixTime::fromSec(1000.0), 0.0, tilt, true);
CliffResult rg = good.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_TRUE(rg.judged) << "bail: " << CliffBailName(rg.bail);
EXPECT_FALSE(rg.detected) << "bu nghieng dung ma van bao vuc";
// Cung anh do nhung bao "phang". Tu hieu chuan se bat phan LON sai lech
// (day la cong dung cua no); cai con lai phai the hien o MAD hoac o so diem.
CliffDetect bad(cfg);
bad.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
CliffResult rb = bad.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_GT(rb.lvl_mad, rg.lvl_mad)
<< "khong bu nghieng ma mat san van khop dep -- tu hieu chuan dang nuot "
"mat ca sai lech lan tin hieu";
}
TEST(CliffDetect, AccelBiGateThiKhongPhanXet) {
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, /*accel_ok=*/false);
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double, double) { return 0.0; });
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_FALSE(r.judged);
EXPECT_EQ(r.bail, CliffBail::kAccelGated);
EXPECT_FALSE(r.detected) << "mot khung mu khong duoc bao nguy ngay";
}
TEST(CliffDetect, MuLienTucQuaNguongThiBaoNguy) {
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double, double) { return 0.0; });
bool danger = false;
for (int i = 0; i < 60; ++i) {
const double t = 1000.0 + i * 0.05; // 20 Hz -> 3 s
det.SetTilt(UnixTime::fromSec(t), 0.0, 0.0, false);
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(t));
if (r.detected) danger = true;
}
EXPECT_TRUE(danger) << "mu 3 s ma fail_safe khong kich";
}
TEST(CliffDetect, TzLechDanhDinhThiBaoNguyNgay) {
// Robot nhoai len vat gi do -> camera khong con o chieu cao danh dinh.
// Neu van phan xet, phep khop mat san se bam theo TANG DUOI va bao
// "khong co vuc" -- kieu hong nguy hiem nhat.
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
CliffDetectConfig cfg = CliffCfg(0.30); // danh dinh sai xa thuc te
CliffDetect det(cfg);
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double, double) { return 0.0; });
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_FALSE(r.judged);
EXPECT_EQ(r.bail, CliffBail::kTzDeviation);
EXPECT_TRUE(r.detected) << "immediate bail phai bao nguy ngay tu khung dau";
}
TEST(CliffDetect, RampDocKhongBiBaoLaVuc) {
// Ramp la san doc THAT va robot phai di duoc. Cong phan biet ramp/vuc la
// MAD, khong phai do lon cua doc.
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
// Doc 8% -- trong gioi han max_level_slope 0.20
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075,
[](double x, double) { return -0.08 * x; });
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_TRUE(r.judged) << "bail: " << CliffBailName(r.bail);
EXPECT_FALSE(r.detected) << "ramp bi bao la vuc -> robot khong len duoc doc";
EXPECT_LT(r.lvl_slope, -0.01) << "khong bat duoc doc";
}
TEST(CliffDetect, KhongDuMauThiKhongPhanXet) {
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
// Toan bo anh la NaN -> khong mau san nao
std::vector<float> px(static_cast<size_t>(kW) * kH,
std::numeric_limits<float>::quiet_NaN());
Image img;
img.width = kW;
img.height = kH;
img.step = kW * 4;
img.format = PixelFormat::kFloat32;
img.data = reinterpret_cast<const uint8_t*>(px.data());
img.header.stamp = UnixTime::fromSec(1000.0);
CliffResult r = det.Process(img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_FALSE(r.judged);
EXPECT_EQ(r.bail, CliffBail::kFewSamples);
}
TEST(CliffDetect, VungMuGanKhongTheThayGi) {
// Ghi lai bang test rang 0 - min_dist la vung mu HINH HOC, khong phai lua
// chon tuy y. Bat ky ai ha min_dist xuong 0.3 se thay test nay noi ro vi sao
// khong duoc lam the.
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetectConfig cfg = CliffCfg(tz);
cfg.min_dist = 0.20;
cfg.max_dist = 1.00; // toan bo cua so nam trong vung mu
CliffDetect det(cfg);
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double, double) { return 0.0; });
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_FALSE(r.judged) << "cua so 0.2-1.0 m ma van phan xet duoc?";
EXPECT_EQ(r.bail, CliffBail::kFewSamples);
}
// ==================== DepthFilter / DepthToCloud ====================
TEST(DepthToCloud, KhopTinhTay) {
CameraInfo info = MakeInfo();
std::vector<float> px(static_cast<size_t>(kW) * kH, 2.0f);
Image img;
img.width = kW;
img.height = kH;
img.step = kW * 4;
img.format = PixelFormat::kFloat32;
img.data = reinterpret_cast<const uint8_t*>(px.data());
PointCloudXYZ out;
DepthToCloud(img, info, &out);
ASSERT_EQ(out.points.size(), static_cast<size_t>(kW) * kH);
const size_t c = static_cast<size_t>(120) * kW + 160;
EXPECT_NEAR(out.points[c].z, 2.0f, 1e-6);
EXPECT_NEAR(out.points[c].x, (160 - 160.5) * 2.0 / 465.7, 1e-6);
}
TEST(DepthToCloud, BinningDuocBu) {
// crop_decimate giao anh 320x240 nhung CameraInfo van mang K cua 640x480 va
// bao muc gop qua binning_x/y = 2. Quen bu la moi diem lech he so decimate.
CameraInfo info;
info.width = 640;
info.height = 480;
info.binning_x = 2;
info.binning_y = 2;
info.k[0] = 465.7;
info.k[2] = 320.5;
info.k[4] = 465.7;
info.k[5] = 240.5;
info.k[8] = 1.0;
EXPECT_NEAR(info.fx_binned(), 465.7 / 2, 1e-9);
EXPECT_NEAR(info.cx_binned(), 320.5 / 2, 1e-9);
}
TEST(DepthFilter, VoxelGridGomDiemTrongCungO) {
DepthFilterConfig cfg;
cfg.voxel_size = 0.05;
cfg.max_rate = 0.0;
cfg.enable_temporal = false;
DepthFilter f(cfg);
PointCloudXYZ in, out;
for (int i = 0; i < 100; ++i) {
in.points.push_back(PointXYZ{1.0f + 0.0001f * i, 0.5f, 0.3f});
}
ASSERT_TRUE(f.Apply(in, UnixTime::fromSec(1.0), &out));
EXPECT_EQ(out.points.size(), 1u) << "100 diem trong cung mot o 5 cm phai gom lai 1";
}
TEST(DepthFilter, KhoaVoxelKhongDungNhamOAmVaDuong) {
DepthFilterConfig cfg;
cfg.voxel_size = 0.05;
cfg.max_rate = 0.0;
cfg.enable_temporal = false;
cfg.min_range = 0.0;
DepthFilter f(cfg);
PointCloudXYZ in, out;
// z phai NAM TRONG dai range, neu khong PassThrough loai truoc va test
// khong cham toi khoa voxel chut nao. x/y am moi la thu dang kiem.
in.points = {PointXYZ{0.02f, 0.02f, 1.0f}, PointXYZ{-0.02f, -0.02f, 1.0f}};
ASSERT_TRUE(f.Apply(in, UnixTime::fromSec(1.0), &out));
EXPECT_EQ(out.points.size(), 2u) << "o am va o duong dung nham khoa";
}
TEST(DepthFilter, GioiHanTanSoTheoStampKhongTheoDongHoTuong) {
// Phat lai ban ghi nhanh hon thoi gian that phai cho ra DUNG so khung nhu
// chay that. Dung dong ho tuong se bop nham.
DepthFilterConfig cfg;
cfg.max_rate = 10.0;
cfg.enable_temporal = false;
DepthFilter f(cfg);
PointCloudXYZ in, out;
in.points = {PointXYZ{1.0f, 0.0f, 0.3f}};
int passed = 0;
for (int i = 0; i < 90; ++i) { // 3 s tai 30 Hz, khong ngu ti nao
if (f.Apply(in, UnixTime::fromSec(100.0 + i / 30.0), &out)) passed++;
}
EXPECT_GE(passed, 29);
EXPECT_LE(passed, 31) << "so khung qua duoc phu thuoc toc do CPU -> dang dung "
"dong ho tuong";
}
// ==================== Pipeline ====================
TEST(PerceptionPipeline, ChayHetChuoiVaGiuNguyenStamp) {
auto clock = MakeSystemClock();
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
PerceptionConfig cfg;
cfg.cliff = CliffCfg(tz);
cfg.filter.max_rate = 0.0;
cfg.filter.enable_temporal = false;
PerceptionPipeline pipe(cfg, *clock);
pipe.SetCameraExtrinsic(cam);
for (int i = 0; i < 400; ++i) {
pipe.FeedImu(MakeImu(999.0 + i * 0.005, 0.0, 0.0, kGravity, 0.0, 0.0));
pipe.FeedOdom(UnixTime::fromSec(999.0 + i * 0.005), 0.0, 0.0);
}
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double, double) { return 0.0; });
PerceptionOutput out = pipe.Process(d.img, info);
EXPECT_EQ(out.stamp.toSec(), d.img.header.stamp.toSec());
EXPECT_TRUE(out.tilt_valid);
EXPECT_TRUE(out.accel_ok);
EXPECT_FALSE(out.cliff_detected);
EXPECT_EQ(out.cliff_detail, "judged");
ASSERT_NE(out.cloud_raw, nullptr);
ASSERT_NE(out.cloud_filtered, nullptr);
ASSERT_NE(out.cloud_aligned, nullptr);
EXPECT_EQ(out.cloud_aligned->header.frame_id, std::string(kBaseFootprintFrame));
EXPECT_LT(out.cloud_filtered->points.size(), out.cloud_raw->points.size());
}
TEST(PerceptionPipeline, TatDuongCloudVanChayCliff) {
auto clock = MakeSystemClock();
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
PerceptionConfig cfg;
cfg.cliff = CliffCfg(tz);
cfg.enable_cloud = false;
PerceptionPipeline pipe(cfg, *clock);
pipe.SetCameraExtrinsic(cam);
pipe.FeedImu(MakeImu(999.0, 0, 0, kGravity, 0, 0));
pipe.FeedImu(MakeImu(999.005, 0, 0, kGravity, 0, 0));
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075,
[](double x, double) { return x > 1.6 ? -0.4 : 0.0; });
PerceptionOutput out = pipe.Process(d.img, info);
EXPECT_TRUE(out.cliff_detected);
EXPECT_EQ(out.cloud_raw, nullptr);
EXPECT_NE(out.cloud_cliff, nullptr);
}
TEST(CliffDetect, VatCanCheCuaSoThiBaoKhongBietChuKhongBaoVuc) {
// Lo hong THAT cua ban ROS goc, do duoc trong mo phong: hanh lang 1.6 m
// nghia la tuong cach 0.85 m -- GAN HON vung mu 1.10 m. Moi tia dap vao
// tuong. Vai diem tuong thap van lot cong level_gate, mat san tham chieu bi
// keo len z0 = +0.34 m, MAD 0.025 lot ca cong MAD, roi san THAT o xa bi do
// voi mat phang bi keo len do -> BAO VUC GIA giua hanh lang phang.
//
// O day mo hinh bang mot BE cao 0.5 m tu 0.85 m tro ra: RenderFloor chi
// dung duoc mat nam ngang, khong dung duoc mat tuong thang dung. Ve mat
// cong `max_obstructed_frac` thi hai truong hop giong nhau -- deu la "phan
// lon cua so tra ve diem CAO hon level_gate". Truong hop tuong that duoc
// phu trong test_perception_sim.
//
// Phai ra "khong biet", khong duoc ra "co vuc".
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double x, double) {
return x > 0.85 ? 0.5 : 0.0;
});
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_FALSE(r.judged) << "phan xet duoc trong khi khong nhin thay san";
EXPECT_EQ(r.bail, CliffBail::kObstructed)
<< "bail=" << CliffBailName(r.bail) << " cao=" << r.lvl_high << "/"
<< r.lvl_window;
EXPECT_FALSE(r.detected) << "mot khung bi che khong duoc bao nguy ngay";
}
TEST(CliffDetect, CongVatCanKhongCheDuocVucThat) {
// Cong `max_obstructed_frac` dem diem CAO. Vuc lam diem THAP hoac MAT HAN,
// khong bao gio lam diem cao -- nen cong nay KHONG THE bien "co vuc" thanh
// "khong co vuc". Khoa tinh chat do bang test.
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
for (double obstruct_frac : {0.0, 0.5, 0.9}) {
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
// Vuc 0.5 m ke tu x = 1.6 m, CONG voi mot vat cao chan mot phan cua so.
// Du bi che bao nhieu, ket qua chi duoc la "co vuc" hoac "khong biet".
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075,
[obstruct_frac](double x, double y) {
if (y > 1.5 - 3.0 * obstruct_frac) return 1.0;
return x > 1.6 ? -0.5 : 0.0;
});
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
const bool safe = r.detected || !r.judged;
EXPECT_TRUE(safe) << "che " << obstruct_frac
<< ": bao KHONG CO VUC trong khi co vuc that";
}
}
TEST(CliffDetect, MatPhangKhongDiQuaChoRobotDungThiKhongPhanXet) {
// Robot DANG DUNG tren san. Mot phep khop noi "san duoi banh xe toi thap
// hon 25 cm" la menh de vat ly sai, khong phai mot nguong can chinh.
//
// Day la kieu hong ma `max_obstructed_frac` khong bat duoc: hanh lang
// 2.5-3.0 m, chi ~9% tia tra ve diem cao hon level_gate (xa cong 0.60),
// nhung diem tuong o r lon van keo doc duong khop len +0.19 -- vua du duoi
// tran max_level_slope 0.20. Do duoc: z0 = -0.25, va 6/210 khung bao vuc
// giua hanh lang phang.
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
// "San" doc deu 19% -- duoi tran max_level_slope 0.20 nen cong doc khong
// kich, nhung ngoai suy ve r = 0 cho z0 xa 0.
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075,
[](double x, double) { return 0.19 * (x - 1.8); });
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_FALSE(r.judged) << "z0=" << r.lvl_z0 << " doc=" << r.lvl_slope;
EXPECT_EQ(r.bail, CliffBail::kOffsetLarge) << "bail=" << CliffBailName(r.bail);
}
TEST(CliffDetect, RampThatVanLotCongOffset) {
// Cong `max_level_offset` khong duoc giet ramp that. Ramp 8% bat dau o
// 1.5 m cho z0 ~ -0.10, phai van lot cong 0.15.
//
// Neu test nay do, tuc la cong dang tat phat hien vuc tren moi san doc --
// dung cai loi ma ghi chu trong depth_filter.yaml cua repo cu canh bao.
const CameraInfo info = MakeInfo();
const Transform cam = MakeCamExtrinsic(0.728, 25.0);
const double tz = TransformCompose(TiltLift(0, 0, 0.075), cam).translation.z;
CliffDetect det(CliffCfg(tz));
det.SetTilt(UnixTime::fromSec(1000.0), 0.0, 0.0, true);
DepthImage d = RenderFloor(info, cam, 0, 0, 0.075, [](double x, double) {
return x > 1.5 ? -0.08 * (x - 1.5) : 0.0;
});
CliffResult r = det.Process(d.img, info, cam, UnixTime::fromSec(1000.0));
EXPECT_TRUE(r.judged) << "bail=" << CliffBailName(r.bail)
<< " z0=" << r.lvl_z0;
EXPECT_FALSE(r.detected) << "ramp 8% bi bao la vuc";
EXPECT_LT(std::fabs(r.lvl_z0), 0.15);
}

329
test/test_perception_sim.cc Normal file
View File

@@ -0,0 +1,329 @@
// Test TICH HOP: SimSource -> PerceptionPipeline.
//
// Day la bai kiem ma repo cu KHONG the co: Gazebo chay trong tien trinh khac,
// nen "san phang thi cliff_detect co im lang khong" chi tra loi duoc bang
// cach chay tay va nhin log. O day no la mot assert.
//
// Hai thu duoc khoa o day, ca hai deu tu loi THAT da mac:
// 1. Anh depth phai theo quy uoc Z-DEPTH chu khong phai cu ly Euclid.
// 2. San phang tuyet doi thi KHONG duoc bao vuc.
#include <gtest/gtest.h>
#include <cmath>
#include <thread>
#include "vslam/cliff_detect.h"
#include "vslam/depth_to_cloud.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/node_constants.h"
#include "vslam/perception_pipeline.h"
#include "vslam/sim_source.h"
using namespace vslam;
namespace {
constexpr double kPi = 3.14159265358979323846;
Transform CamToBase(const SimConfig& cfg) {
// CHINH quy uoc ma sim_source dung khi ban tia:
// +Z_quang = +X_than, +X_quang = -Y_than, +Y_quang = -Z_than
Transform t = TransformIdentity();
t.translation = Vector3{cfg.camera_x, 0.0, cfg.camera_z - cfg.wheel_radius};
t.rotation = QuaternionMultiply(QuaternionFromRPY(0.0, cfg.camera_pitch, 0.0),
QuaternionFromRPY(-kPi / 2, 0.0, -kPi / 2));
return t;
}
SimConfig QuietSim() {
SimConfig cfg;
// Tat HET nhieu depth: mo hinh stereo co ba thanh phan, tat mot cai
// khong du.
cfg.depth_disparity_noise_px = 0.0;
cfg.depth_noise_floor = 0.0;
cfg.depth_dropout_rate = 0.0;
return cfg;
}
// Lay N khung camera dau tien, chay qua CliffDetect, tra ket qua cuoi.
struct GrabResult {
int frames = 0;
CliffResult last;
ImagePtr last_depth;
CameraInfo last_info;
};
GrabResult GrabFrames(SimSource& sim, CliffDetect& det, const Transform& cam, int n) {
GrabResult g;
sim.camera()->SetCallback([&](const CameraFrame& f) {
if (!f.depth || g.frames >= n) return;
det.SetTilt(f.depth->header.stamp, 0.0, 0.0, true);
g.last = det.Process(*f.depth, f.depth_info, cam, f.depth->header.stamp);
g.last_depth = f.depth;
g.last_info = f.depth_info;
g.frames++;
});
sim.camera()->Open();
sim.RunFor(n / 30.0 + 0.2);
return g;
}
double DepthMm(const Image& img, uint32_t u, uint32_t v) {
const size_t off = static_cast<size_t>(v) * img.step + static_cast<size_t>(u) * 2;
return static_cast<double>(img.data[off] | (img.data[off + 1] << 8));
}
} // namespace
TEST(SimPerception, AnhDepthLaZDepthKhongPhaiCuLyEuclid) {
// Loi da mac: RaycastDepth tra cu ly Euclid doc theo tia, roi ghi thang vao
// anh depth. Moi tia lech truc bi thoi phong theo 1/cos -- toi ~1.15 o goc
// anh. Hau qua: cliff_detect khop mat san thanh z0 = -0.254 m doc +0.114 va
// bao vuc gia tren san hoan toan phang.
//
// Kiem bang cach so hai diem anh cung nhin vao MOT mat phang: neu la
// Z-depth thi ti so bang 1; neu la Euclid thi ti so bang norm cua tia.
SimConfig cfg = QuietSim();
cfg.start_x = 0.0;
cfg.start_y = 0.0;
cfg.start_yaw = 0.0;
SimSource sim(cfg);
ASSERT_TRUE(sim.Open().ok());
ASSERT_NE(sim.camera(), nullptr);
CliffDetectConfig cc;
cc.nominal_tz = cfg.camera_z;
CliffDetect det(cc);
GrabResult g = GrabFrames(sim, det, CamToBase(cfg), 2);
ASSERT_GT(g.frames, 0);
ASSERT_NE(g.last_depth, nullptr);
const Image& img = *g.last_depth;
const CameraInfo& info = g.last_info;
const double fx = info.fx_binned(), fy = info.fy_binned();
const double cx = info.cx_binned(), cy = info.cy_binned();
// Hai diem anh o CUNG mot hang gan day anh (cung nhin xuong san), mot o
// giua mot o lech sang canh. San phang => Z-depth cua hai diem chi khac
// nhau do goc chuc, khong khac do lech NGANG.
const uint32_t v = img.height - 6;
const uint32_t u_mid = static_cast<uint32_t>(cx);
const uint32_t u_edge = 6;
const double d_mid = DepthMm(img, u_mid, v) * 0.001;
const double d_edge = DepthMm(img, u_edge, v) * 0.001;
ASSERT_GT(d_mid, 0.0) << "diem giua khong co so do";
ASSERT_GT(d_edge, 0.0) << "diem canh khong co so do";
// Voi mat phang san, Z-depth phu thuoc b=(v-cy)/fy va KHONG phu thuoc
// a=(u-cx)/fx theo cong thuc z = -tz / (R20*a + R21*b + R22). Voi yaw=0 va
// khong roll thi R21 = 0 nen a chi vao qua R20 -- ma R20 = 0 khi camera chi
// chuc xuong (khong xoay quanh Z). Nen hai diem cung hang phai cho gan bang
// nhau.
const double a_edge = (u_edge - cx) / fx;
const double ray_norm = std::sqrt(a_edge * a_edge +
std::pow((v - cy) / fy, 2.0) + 1.0);
const double ratio = d_edge / d_mid;
EXPECT_NEAR(ratio, 1.0, 0.02)
<< "ti so " << ratio << " -- ky vong Euclid la "
<< ray_norm / std::sqrt(std::pow((v - cy) / fy, 2.0) + 1.0)
<< ". Anh dang mang cu ly Euclid chu khong phai Z-depth.";
}
TEST(SimPerception, SanPhangThiKhongBaoVuc) {
SimConfig cfg = QuietSim();
SimSource sim(cfg);
ASSERT_TRUE(sim.Open().ok());
CliffDetectConfig cc;
cc.nominal_tz = cfg.camera_z;
CliffDetect det(cc);
GrabResult g = GrabFrames(sim, det, CamToBase(cfg), 10);
ASSERT_GE(g.frames, 5);
EXPECT_TRUE(g.last.judged) << "bail: " << CliffBailName(g.last.bail);
EXPECT_FALSE(g.last.detected);
EXPECT_EQ(g.last.n_cliff, 0);
EXPECT_GT(g.last.n_inwin, 500) << "khong tia nao vao cua so -- hinh hoc lech";
// San phang tuyet doi, khong nhieu: mat san phai khop gan nhu hoan hao.
EXPECT_NEAR(g.last.lvl_z0, 0.0, 0.02);
EXPECT_NEAR(g.last.lvl_slope, 0.0, 0.02);
EXPECT_LT(g.last.lvl_mad, 0.01);
EXPECT_EQ(det.stats().detected, 0u) << "co khung bao vuc gia";
}
TEST(SimPerception, BacThangXuongBiPhatHien) {
SimConfig cfg = QuietSim();
SimSource sim(cfg);
ASSERT_TRUE(sim.Open().ok());
// Bac hut xuong 0.35 m bat dau tu x = 1.8 m -- nam trong cua so 1.10-2.50 m.
sim.SetFloorHeight(1.8, -3.0, 6.0, 3.0, -0.35f);
CliffDetectConfig cc;
cc.nominal_tz = cfg.camera_z;
CliffDetect det(cc);
GrabResult g = GrabFrames(sim, det, CamToBase(cfg), 10);
ASSERT_GE(g.frames, 5);
EXPECT_TRUE(g.last.judged) << "bail: " << CliffBailName(g.last.bail);
EXPECT_TRUE(g.last.detected) << "vuc 0.35 m truoc mat ma khong phat hien";
EXPECT_GE(g.last.n_cliff, 12);
// Danh dau phai o MEP (x ~ 1.8 m), khong phai o day vuc.
ASSERT_FALSE(g.last.edge_cloud.points.empty());
double x_min = 1e9, x_max = -1e9;
for (const PointXYZ& p : g.last.edge_cloud.points) {
x_min = std::min(x_min, static_cast<double>(p.x));
x_max = std::max(x_max, static_cast<double>(p.x));
}
EXPECT_GT(x_min, 1.3) << "danh dau truoc ca mep";
EXPECT_LT(x_max, 2.8) << "danh dau sau mep -- robot se dung MUON";
}
TEST(SimPerception, VucSauKhongTraVeGiVanBiPhatHien) {
// Vuc sau hon tam camera (depth_far) -> khong tia nao tra ve -> toan LO.
// Day dung la ca cau thang toi, va la ly do detector chay tren anh depth.
//
// Ho phai DAI hon tam camera. Mot ho chi 4.2 m (1.8 -> 6.0) thi tia van
// cham duoc BO BEN KIA o ~9.5 m va tra ve so do -- dung ve vat ly, va la
// ly do bai test nay tung that bai voi n_hole = 0 trong khi
// detected = true. Ke thua nham "khong tra ve gi" voi "co vuc" la cach bo
// sot ca cau thang toi that.
SimConfig cfg = QuietSim();
SimSource sim(cfg);
ASSERT_TRUE(sim.Open().ok());
sim.SetFloorHeight(1.8, -10.0, 15.0, 10.0, -20.0f);
CliffDetectConfig cc;
cc.nominal_tz = cfg.camera_z;
CliffDetect det(cc);
GrabResult g = GrabFrames(sim, det, CamToBase(cfg), 10);
ASSERT_GE(g.frames, 5);
EXPECT_TRUE(g.last.judged) << "bail: " << CliffBailName(g.last.bail);
EXPECT_TRUE(g.last.detected);
EXPECT_GT(g.last.n_hole, 0) << "vuc sau ma khong dem duoc lo nao";
}
TEST(SimPerception, ChuoiDayDuChayDuocVaCloudNamTrongBaseFootprint) {
SimConfig cfg = QuietSim();
SimSource sim(cfg);
ASSERT_TRUE(sim.Open().ok());
auto clock = MakeSystemClock();
PerceptionConfig pc;
pc.cliff.nominal_tz = cfg.camera_z;
pc.gravity.wheel_radius = cfg.wheel_radius;
pc.cliff.wheel_radius = cfg.wheel_radius;
pc.filter.max_rate = 0.0;
PerceptionPipeline pipe(pc, *clock);
pipe.SetCameraExtrinsic(CamToBase(cfg));
sim.mcu()->SetImuCallback([&](ImuPtr m) { pipe.FeedImu(*m); });
int n = 0;
PerceptionOutput last;
sim.camera()->SetCallback([&](const CameraFrame& f) {
if (!f.depth) return;
last = pipe.Process(*f.depth, f.depth_info);
n++;
});
sim.mcu()->Open();
sim.camera()->Open();
sim.RunFor(1.0);
ASSERT_GT(n, 10);
EXPECT_TRUE(last.tilt_valid);
EXPECT_FALSE(last.cliff_detected) << "detail: " << last.cliff_detail;
EXPECT_EQ(last.cliff_detail, "judged");
ASSERT_NE(last.cloud_aligned, nullptr);
EXPECT_EQ(last.cloud_aligned->header.frame_id, std::string(kBaseFootprintFrame));
EXPECT_GT(last.cloud_aligned->points.size(), 50u);
// Da can trong luc: moi diem phai nam trong dai chieu cao da cat.
for (const PointXYZ& p : last.cloud_aligned->points) {
EXPECT_GE(p.z, static_cast<float>(pc.gravity.min_height));
EXPECT_LE(p.z, static_cast<float>(pc.gravity.max_height));
}
}
TEST(SimPerception, HoHepThiNhinThayBoBenKiaNhungVanLaVuc) {
// Doi ngau voi bai tren: ho chi 4.2 m thi tia cham duoc bo ben kia, nen
// khong co LO nao -- nhung be mat tra ve VAN thap hon nguong, nen phai bao
// vuc qua nhanh SUT chu khong qua nhanh LO. Hai duong nay phai cung song.
SimConfig cfg = QuietSim();
SimSource sim(cfg);
ASSERT_TRUE(sim.Open().ok());
sim.SetFloorHeight(1.8, -3.0, 6.0, 3.0, -20.0f);
CliffDetectConfig cc;
cc.nominal_tz = cfg.camera_z;
CliffDetect det(cc);
GrabResult g = GrabFrames(sim, det, CamToBase(cfg), 10);
ASSERT_GE(g.frames, 5);
EXPECT_TRUE(g.last.judged) << "bail: " << CliffBailName(g.last.bail);
EXPECT_TRUE(g.last.detected);
EXPECT_GT(g.last.n_drop, 0) << "nhanh SUT khong bat duoc";
EXPECT_EQ(g.last.n_hole, 0) << "ho hep ma van co lo -- tia khong cham bo ben kia";
}
TEST(SimPerception, QuayTaiChoTrongHanhLangHepKhongBaoVucGia) {
// Hanh lang cua the gioi tong hop rong 1.6 m -> tuong cach 0.85 m, GAN HON
// vung mu 1.10 m cua detector. Quay tai cho lam camera quet qua tuong do.
//
// Truoc khi co cong `max_obstructed_frac`, do duoc: mat san tham chieu bi
// khop len z0 = +0.34 m (MAD 0.025, lot ca cong MAD) va 46 tia san THAT roi
// duoi nguong -> bao VUC giua hanh lang hoan toan phang. Hong KHONG AN
// TOAN: bao CO vuc chu khong bao "khong biet".
//
// Cai duoc khoa o day la: KHONG khung nao vua `judged` vua `detected`.
// Leo thang fail-safe khi bi che LIEN TUC (bail -> nguy sau
// fail_safe_after) la co y va duoc dem rieng -- do la lua chon "im lang
// khong du an toan khi mu keo dai", va no khong khoa robot lai vi FSM chi
// chan TIEN chu van cho XOAY thoat.
SimConfig cfg = QuietSim();
SimSource sim(cfg);
ASSERT_TRUE(sim.Open().ok());
CliffDetectConfig cc;
cc.nominal_tz = cfg.camera_z;
CliffDetect det(cc);
const Transform cam = CamToBase(cfg);
int frames = 0, false_pos = 0, obstructed = 0, judged = 0, escalated = 0;
sim.camera()->SetCallback([&](const CameraFrame& f) {
if (!f.depth) return;
det.SetTilt(f.depth->header.stamp, 0.0, 0.0, true);
CliffResult r = det.Process(*f.depth, f.depth_info, cam, f.depth->header.stamp);
frames++;
if (r.judged) {
judged++;
if (r.detected) false_pos++;
} else {
if (r.bail == CliffBail::kObstructed) obstructed++;
if (r.detected) escalated++;
}
});
sim.camera()->Open();
sim.base()->Open();
std::thread runner([&] { sim.RunFor(6.0); });
for (int i = 0; i < 60; ++i) {
sim.base()->SetVelocity(0.0, 1.0); // quay tai cho 1 rad/s -> hon mot vong
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
runner.join();
ASSERT_GT(frames, 50);
EXPECT_GT(obstructed, 0) << "quet het mot vong trong hanh lang 1.6 m ma "
"khong khung nao bi che -- canh test sai";
EXPECT_GT(judged, 0) << "khong khung nao phan xet duoc -- cong qua chat";
EXPECT_EQ(false_pos, 0) << false_pos << "/" << frames
<< " khung PHAN XET DUOC ma bao vuc giua hanh lang "
"phang (leo thang: " << escalated << ")";
}

441
test/test_record_io.cc Normal file
View File

@@ -0,0 +1,441 @@
#include "vslam/record_io.h"
#include <gtest/gtest.h>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <limits>
#include <string>
#include <vector>
#include <unistd.h>
#include "vslam/record_format.h"
using namespace vslam;
namespace {
std::string TempPath(const char* name) {
return std::string("/tmp/vslam_test_") + name + "_" +
std::to_string(::getpid()) + ".vsr";
}
LaserScan MakeScan() {
LaserScan s;
s.header.frame_id = "laser_link";
s.header.stamp = UnixTime::fromNSec(1737000000123456789LL);
s.header.seq = 7;
s.angle_min = -2.356194f;
s.angle_max = 2.356194f;
s.angle_increment = static_cast<float>(2.0 * 2.356194 / 1080.0);
s.scan_time = 0.04f;
s.time_increment = s.scan_time / 1081.0f;
s.range_min = 0.05f;
s.range_max = 40.0f;
s.ranges.resize(1081);
for (size_t i = 0; i < s.ranges.size(); ++i) {
s.ranges[i] = 1.0f + static_cast<float>(i) * 0.001f;
}
// Ba ngu nghia phai song sot qua vong ghi/doc.
s.ranges[0] = std::numeric_limits<float>::quiet_NaN();
s.ranges[1] = std::numeric_limits<float>::infinity();
s.ranges[2] = s.range_max + 1.0f;
return s;
}
} // namespace
TEST(RecordIo, RoundTripScan) {
const std::string path = TempPath("scan");
const LaserScan orig = MakeScan();
{
RecordWriterConfig c;
c.path = path;
c.config_json = R"({"test":true})";
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
std::string payload;
EncodeScanPayload(orig, &payload);
EXPECT_TRUE(w.Write(VsrStream::kScanRaw, orig.header.stamp, payload));
w.Close();
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
EXPECT_EQ(r.info().version, kVsrVersion);
EXPECT_EQ(r.info().config_json, R"({"test":true})");
VsrChunkHeader h;
std::string payload;
ASSERT_TRUE(r.Next(&h, &payload));
EXPECT_EQ(h.stream, VsrStream::kScanRaw);
EXPECT_EQ(h.stamp_ns, 1737000000123456789ULL);
LaserScan back;
ASSERT_TRUE(DecodeScanPayload(payload, &back));
EXPECT_EQ(back.header.frame_id, orig.header.frame_id);
EXPECT_EQ(back.header.seq, orig.header.seq);
EXPECT_EQ(back.header.stamp, orig.header.stamp);
EXPECT_FLOAT_EQ(back.angle_min, orig.angle_min);
EXPECT_FLOAT_EQ(back.time_increment, orig.time_increment);
ASSERT_EQ(back.ranges.size(), orig.ranges.size());
// Ba ngu nghia: NaN / inf / sentinel phai giu NGUYEN VEN.
EXPECT_TRUE(std::isnan(back.ranges[0]));
EXPECT_TRUE(std::isinf(back.ranges[1]));
EXPECT_FLOAT_EQ(back.ranges[2], orig.range_max + 1.0f);
for (size_t i = 3; i < orig.ranges.size(); ++i) {
EXPECT_FLOAT_EQ(back.ranges[i], orig.ranges[i]) << "tia " << i;
}
EXPECT_FALSE(r.Next(&h, &payload));
EXPECT_FALSE(r.truncated()) << "het file binh thuong khong phai la cut";
r.Close();
std::remove(path.c_str());
}
TEST(RecordIo, RoundTripImuVaEncoder) {
const std::string path = TempPath("imu");
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
Imu imu;
imu.header.frame_id = "imu_link";
imu.header.stamp = UnixTime::fromSec(100.5);
imu.angular_velocity = Vector3{0.01, -0.02, 0.03};
imu.linear_acceleration = Vector3{0.1, -0.2, 9.81};
imu.angular_velocity_covariance[0] = 2.4e-7;
std::string p1;
EncodeImuPayload(imu, &p1);
w.Write(VsrStream::kImu, imu.header.stamp, p1);
std::string p2;
EncodeEncoderPayload(12.345, -6.789, &p2);
w.Write(VsrStream::kEncoder, UnixTime::fromSec(100.6), p2);
w.Close();
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
VsrChunkHeader h;
std::string payload;
ASSERT_TRUE(r.Next(&h, &payload));
EXPECT_EQ(h.stream, VsrStream::kImu);
Imu imu;
ASSERT_TRUE(DecodeImuPayload(payload, &imu));
EXPECT_DOUBLE_EQ(imu.angular_velocity.z, 0.03);
EXPECT_DOUBLE_EQ(imu.linear_acceleration.z, 9.81);
EXPECT_DOUBLE_EQ(imu.angular_velocity_covariance[0], 2.4e-7);
// MCU khong gui orientation -> phai danh dau theo quy uoc sensor_msgs.
EXPECT_LT(imu.orientation_covariance[0], 0.0);
ASSERT_TRUE(r.Next(&h, &payload));
EXPECT_EQ(h.stream, VsrStream::kEncoder);
double l = 0.0, rr = 0.0;
ASSERT_TRUE(DecodeEncoderPayload(payload, &l, &rr));
EXPECT_DOUBLE_EQ(l, 12.345);
EXPECT_DOUBLE_EQ(rr, -6.789);
r.Close();
std::remove(path.c_str());
}
TEST(RecordIo, RoundTripImage) {
const std::string path = TempPath("img");
std::vector<uint8_t> pixels(320 * 240 * 2);
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = static_cast<uint8_t>(i & 0xFF);
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
Image img;
img.header.stamp = UnixTime::fromSec(50.0);
img.header.frame_id = "camera_depth_optical_frame";
img.width = 320;
img.height = 240;
img.step = 320 * 2;
img.format = PixelFormat::kMono16;
img.depth_scale = 0.001f;
img.data = pixels.data();
std::string p;
EncodeImagePayload(img, &p);
w.Write(VsrStream::kDepth, img.header.stamp, p);
w.Close();
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
VsrChunkHeader h;
std::string payload;
ASSERT_TRUE(r.Next(&h, &payload));
Image back;
std::vector<uint8_t> storage;
ASSERT_TRUE(DecodeImagePayload(payload, &back, &storage));
EXPECT_EQ(back.width, 320u);
EXPECT_EQ(back.height, 240u);
EXPECT_EQ(back.step, 640u);
EXPECT_EQ(back.format, PixelFormat::kMono16);
EXPECT_FLOAT_EQ(back.depth_scale, 0.001f);
ASSERT_EQ(storage.size(), pixels.size());
EXPECT_EQ(std::memcmp(back.data, pixels.data(), pixels.size()), 0);
r.Close();
std::remove(path.c_str());
}
TEST(RecordIo, NhieuChunkGiuDungThuTu) {
const std::string path = TempPath("order");
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
for (int i = 0; i < 500; ++i) {
std::string p;
EncodeEncoderPayload(static_cast<double>(i), 0.0, &p);
w.Write(VsrStream::kEncoder, UnixTime::fromSec(1.0 + i * 0.02), p);
}
w.Close();
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
VsrChunkHeader h;
std::string payload;
int n = 0;
double prev_stamp = -1.0;
while (r.Next(&h, &payload)) {
double l = 0.0, rr = 0.0;
ASSERT_TRUE(DecodeEncoderPayload(payload, &l, &rr));
EXPECT_DOUBLE_EQ(l, static_cast<double>(n));
const double st = static_cast<double>(h.stamp_ns) * 1e-9;
EXPECT_GT(st, prev_stamp);
prev_stamp = st;
n++;
}
EXPECT_EQ(n, 500);
EXPECT_FALSE(r.truncated());
EXPECT_EQ(r.chunks_read(), 500u);
r.Close();
std::remove(path.c_str());
}
// --- File hong -------------------------------------------------------------
TEST(RecordIo, CrcSaiThiDungLaiChuKhongDocTiep) {
// 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.
const std::string path = TempPath("crc");
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
for (int i = 0; i < 5; ++i) {
std::string p;
EncodeEncoderPayload(static_cast<double>(i), 0.0, &p);
w.Write(VsrStream::kEncoder, UnixTime::fromSec(1.0 + i), p);
}
w.Close();
}
// Lat mot bit trong payload cua chunk thu ba.
{
std::fstream f(path, std::ios::binary | std::ios::in | std::ios::out);
ASSERT_TRUE(f.good());
// header co dinh + config rong, roi 2 chunk (20 + 16 payload + 4 crc)
const long off = static_cast<long>(kVsrHeaderFixedSize) + 2 * (20 + 16 + 4) + 25;
f.seekg(off);
char byte = 0;
f.read(&byte, 1);
byte ^= 0x01;
f.seekp(off);
f.write(&byte, 1);
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
VsrChunkHeader h;
std::string payload;
int n = 0;
while (r.Next(&h, &payload)) n++;
EXPECT_LT(n, 5) << "phai dung truoc chunk hong";
EXPECT_TRUE(r.truncated()) << "phai bao la cut, khong im lang";
r.Close();
std::remove(path.c_str());
}
TEST(RecordIo, FileCutGiuaChung) {
const std::string path = TempPath("trunc");
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
for (int i = 0; i < 10; ++i) {
std::string p;
EncodeEncoderPayload(static_cast<double>(i), 0.0, &p);
w.Write(VsrStream::kEncoder, UnixTime::fromSec(1.0 + i), p);
}
w.Close();
}
// Cat mat 10 byte cuoi -- giong the USB rut ra dot ngot.
{
std::ifstream in(path, std::ios::binary | std::ios::ate);
const long size = static_cast<long>(in.tellg());
in.close();
ASSERT_EQ(::truncate(path.c_str(), size - 10), 0);
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
VsrChunkHeader h;
std::string payload;
int n = 0;
while (r.Next(&h, &payload)) n++;
EXPECT_EQ(n, 9) << "9 chunk dau van doc duoc";
EXPECT_TRUE(r.truncated());
r.Close();
std::remove(path.c_str());
}
TEST(RecordIo, TuChoiFileKhongPhaiVsr) {
const std::string path = TempPath("bad");
{
std::ofstream f(path, std::ios::binary);
f << "day khong phai file vsr, chi la text thuong thoi";
}
RecordReader r;
const StatusResponse st = r.Open(path);
EXPECT_FALSE(st.ok());
EXPECT_NE(st.message.find("magic"), std::string::npos);
std::remove(path.c_str());
}
TEST(RecordIo, TuChoiPhienBanKhacRoRang) {
// Doi schema lam moi file expected/*.json cu vo gia tri. Tu choi ro rang
// thay vi co doc va sinh du lieu vo nghia.
const std::string path = TempPath("ver");
{
std::ofstream f(path, std::ios::binary);
f.write(kVsrMagic, sizeof(kVsrMagic));
const uint32_t bad_ver = 999;
for (int i = 0; i < 4; ++i) f.put(static_cast<char>((bad_ver >> (8 * i)) & 0xFF));
for (int i = 0; i < 4 + 8 + 4; ++i) f.put(0);
}
RecordReader r;
const StatusResponse st = r.Open(path);
EXPECT_FALSE(st.ok());
EXPECT_NE(st.message.find("999"), std::string::npos);
std::remove(path.c_str());
}
TEST(RecordIo, KhongMoDuocDuongDanXauThiBao) {
RecordWriterConfig c;
c.path = "/khong/ton/tai/abc.vsr";
RecordWriter w(c);
EXPECT_FALSE(w.Open().ok());
}
// --- Drop chu khong chan ---------------------------------------------------
TEST(RecordIo, HangDoiDayThiDropChuKhongChan) {
// GHI LOG TUYET DOI KHONG DUOC NGHEN VONG AN TOAN. Mot the USB cham khong
// duoc phep lam luong lidar_rx dung lai.
const std::string path = TempPath("drop");
RecordWriterConfig c;
c.path = path;
// Nho hon MOT chunk, nen moi chunk lon deu drop -- tat dinh, khong phu
// thuoc vao viec luong ghi tieu thu nhanh hay cham.
c.max_queue_bytes = 512;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
std::string big(2000, 'x');
int dropped = 0;
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < 2000; ++i) {
if (!w.Write(VsrStream::kEvent, UnixTime::fromSec(1.0 + i), big)) dropped++;
}
const auto dt = std::chrono::steady_clock::now() - t0;
EXPECT_EQ(dropped, 2000) << "chunk lon hon ca hang doi ma khong drop";
// Khong duoc chan: 2000 lan ghi phai xong rat nhanh du hang doi day.
EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(dt).count(), 3000);
w.Close();
const RecordWriterStats s = w.Stats();
EXPECT_EQ(s.chunks_dropped, static_cast<uint64_t>(dropped));
std::remove(path.c_str());
}
TEST(RecordIo, BanGhiTuMoTaLoHongCuaChinhNo) {
// Moi dot drop phai de lai mot su kien trong stream kEvent, de doc lai sau
// sau thang van biet doan nao thieu du lieu va thieu bao nhieu.
const std::string path = TempPath("selfdesc");
{
RecordWriterConfig c;
c.path = path;
// Chunk lon (1500 B) luon vuot hang doi 512 B -> drop tat dinh.
// Chunk nho (10 B) thi lot -> no keo theo su kien tom tat so lan drop.
c.max_queue_bytes = 512;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
const std::string big(1500, 'y');
for (int i = 0; i < 50; ++i) {
ASSERT_FALSE(w.Write(VsrStream::kEvent, UnixTime::fromSec(1.0 + i), big));
}
const std::string small(10, 'z');
ASSERT_TRUE(w.Write(VsrStream::kEvent, UnixTime::fromSec(100.0), small));
w.Close();
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
VsrChunkHeader h;
std::string payload;
bool saw_drop_event = false;
while (r.Next(&h, &payload)) {
if (h.stream == VsrStream::kEvent &&
payload.find("\"t\":\"drop\"") != std::string::npos) {
saw_drop_event = true;
// So lan drop phai duoc ghi lai chinh xac, khong phai chi "co drop".
EXPECT_NE(payload.find("\"chunks\":50"), std::string::npos) << payload;
}
}
EXPECT_TRUE(saw_drop_event) << "dot drop khong de lai dau vet nao";
r.Close();
std::remove(path.c_str());
}
// --- crc32 -----------------------------------------------------------------
TEST(Crc32, KhopGiaTriChuan) {
// Gia tri chuan cua CRC-32 IEEE cho "123456789".
const std::string s = "123456789";
EXPECT_EQ(Crc32(s.data(), s.size()), 0xCBF43926u);
}
TEST(Crc32, DoiMotBitThiDoiKetQua) {
std::string a(100, 'a');
std::string b = a;
b[50] ^= 0x01;
EXPECT_NE(Crc32(a.data(), a.size()), Crc32(b.data(), b.size()));
}

351
test/test_replay_source.cc Normal file
View File

@@ -0,0 +1,351 @@
#include "vslam/replay_source.h"
#include <fstream>
#include <gtest/gtest.h>
#include <cmath>
#include <cstdio>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>
#include "vslam/record_io.h"
using namespace vslam;
namespace {
std::string TempPath(const char* name) {
return std::string("/tmp/vslam_replay_") + name + "_" +
std::to_string(::getpid()) + ".vsr";
}
// Sinh mot ban ghi giong nhip that: scan 25 Hz, imu 200 Hz, encoder 50 Hz.
void MakeRecording(const std::string& path, int seconds) {
RecordWriterConfig c;
c.path = path;
c.config_json = R"({"lidar":{"range_max":40.0},"note":"ban ghi test"})";
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
const double t0 = 1737000000.0;
const int imu_n = seconds * 200;
for (int i = 0; i < imu_n; ++i) {
const double t = t0 + static_cast<double>(i) / 200.0;
const UnixTime stamp = UnixTime::fromSec(t);
Imu imu;
imu.header.stamp = stamp;
imu.header.frame_id = "imu_link";
imu.angular_velocity.z = 0.1 * std::sin(static_cast<double>(i) * 0.01);
imu.linear_acceleration.z = 9.81;
std::string p;
EncodeImuPayload(imu, &p);
w.Write(VsrStream::kImu, stamp, p);
if (i % 8 == 0) { // 25 Hz
LaserScan s;
s.header.stamp = stamp;
s.header.frame_id = "laser_link";
s.angle_min = -2.356194f;
s.angle_increment = static_cast<float>(2.0 * 2.356194 / 1080.0);
s.scan_time = 0.04f;
// Gia tri THO tu driver: header noi doi, va co tia 0.0.
s.range_min = 0.0f;
s.range_max = 100.0f;
s.ranges.assign(1081, 2.5f);
s.ranges[0] = 0.0f;
std::string sp;
EncodeScanPayload(s, &sp);
w.Write(VsrStream::kScanRaw, stamp, sp);
}
if (i % 4 == 0) { // 50 Hz
std::string ep;
EncodeEncoderPayload(static_cast<double>(i) * 0.001,
static_cast<double>(i) * 0.0011, &ep);
w.Write(VsrStream::kEncoder, stamp, ep);
}
}
w.Close();
}
ScanSanitizerConfig SanCfg() {
ScanSanitizerConfig c;
c.range_min = 0.05;
c.range_max = 40.0;
return c;
}
// Ghi lai toan bo dau ra thanh mot chuoi, de so hai lan chay voi nhau.
struct Recorder {
std::ostringstream out;
int scans = 0, imu = 0, enc = 0;
void Attach(ReplaySource* rs) {
rs->lidar()->SetCallback([this](LaserScanPtr s) {
scans++;
out << "S " << s->header.stamp.toString() << " " << s->range_min << " "
<< s->ranges.size() << " " << (std::isnan(s->ranges[0]) ? "nan" : "num")
<< "\n";
});
rs->mcu()->SetImuCallback([this](ImuPtr m) {
imu++;
out << "I " << m->header.stamp.toString() << " " << m->angular_velocity.z << "\n";
});
rs->base()->SetEncoderCallback([this](const EncoderReading& e) {
enc++;
out << "E " << e.stamp.toString() << " " << e.left_rad << " " << e.right_rad << "\n";
});
rs->lidar()->Open();
rs->mcu()->Open();
rs->base()->Open();
}
};
} // namespace
TEST(ReplaySource, PhatLaiDuMoiStream) {
const std::string path = TempPath("basic");
MakeRecording(path, 2);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
Recorder rec;
rec.Attach(&rs);
rs.Run();
EXPECT_EQ(rec.imu, 400); // 2 s x 200 Hz
EXPECT_EQ(rec.scans, 50); // 2 s x 25 Hz
EXPECT_EQ(rec.enc, 100); // 2 s x 50 Hz
const auto s = rs.stats();
EXPECT_FALSE(s.truncated);
EXPECT_NEAR(s.duration_sec, 1.995, 0.01);
std::remove(path.c_str());
}
TEST(ReplaySource, ChayLaiHaiLanChoKetQuaGiongHET) {
// DAY LA LOI HUA KIEN TRUC QUAN TRONG NHAT CUA P2.
//
// Khong con Gazebo va khong con rosbag thi tang 2 cua chien luoc kiem chung
// (regress.sh so JSON voi expected/) la thu duy nhat bat duoc hoi quy. No
// chi co gia tri neu replay TAT DINH.
//
// Tinh tat dinh do phu thuoc vao quy tac o clock.h: khong stage nao goi
// UnixTime::now() truc tiep. Vi pham mot cho thoi la test nay do.
const std::string path = TempPath("determ");
MakeRecording(path, 2);
std::string first, second;
for (int run = 0; run < 2; ++run) {
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
Recorder rec;
rec.Attach(&rs);
rs.Run();
(run == 0 ? first : second) = rec.out.str();
}
EXPECT_FALSE(first.empty());
EXPECT_EQ(first, second) << "hai lan chay cho ket qua khac nhau";
EXPECT_EQ(first.size(), second.size());
std::remove(path.c_str());
}
TEST(ReplaySource, ApSanitizerLenDuLieuTho) {
// Ban ghi luu SCAN_RAW -- truoc sanitizer. Day chinh la de doi nguong roi
// chay lai tren cung mot file.
const std::string path = TempPath("san");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.apply_sanitizer = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
float seen_min = -1.0f, seen_max = -1.0f;
bool zero_became_nan = false;
rs.lidar()->SetCallback([&](LaserScanPtr s) {
seen_min = s->range_min;
seen_max = s->range_max;
if (std::isnan(s->ranges[0])) zero_became_nan = true;
});
rs.lidar()->Open();
rs.Run();
// Header noi doi cua driver (0.0 / 100.0) phai da bi ep ve gia tri that.
EXPECT_FLOAT_EQ(seen_min, 0.05f);
EXPECT_FLOAT_EQ(seen_max, 40.0f);
EXPECT_TRUE(zero_became_nan) << "tia 0.0 phai thanh NaN";
std::remove(path.c_str());
}
TEST(ReplaySource, TatSanitizerThiThayDuLieuTho) {
const std::string path = TempPath("raw");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.apply_sanitizer = false;
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
float seen_max = -1.0f;
rs.lidar()->SetCallback([&](LaserScanPtr s) { seen_max = s->range_max; });
rs.lidar()->Open();
rs.Run();
EXPECT_FLOAT_EQ(seen_max, 100.0f) << "phai thay gia tri THO cua driver";
std::remove(path.c_str());
}
TEST(ReplaySource, CuaSoStartVaDuration) {
const std::string path = TempPath("window");
MakeRecording(path, 4);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.start_sec = 1.0;
cfg.duration_sec = 1.0;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
Recorder rec;
rec.Attach(&rs);
rs.Run();
// ~1 giay du lieu thay vi 4.
EXPECT_GE(rec.imu, 180);
EXPECT_LE(rec.imu, 220);
EXPECT_GT(rs.stats().skipped, 0u);
std::remove(path.c_str());
}
TEST(ReplaySource, DongHoAoTienTheoStampCuaBanGhi) {
const std::string path = TempPath("clock");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
// Moi stage phai doc dong ho NAY, khong phai dong ho he thong. Kiem rang no
// that su chay theo thoi gian trong file chu khong phai thoi gian that.
ClockPtr clk = rs.clock();
ASSERT_TRUE(clk != nullptr);
EXPECT_TRUE(clk->is_virtual());
std::vector<double> clock_at_scan;
rs.lidar()->SetCallback([&](LaserScanPtr s) {
clock_at_scan.push_back(clk->Now().toSec());
// Dong ho ao phai khop stamp cua ban tin dang xu ly.
EXPECT_NEAR(clk->Now().toSec(), s->header.stamp.toSec(), 1e-6);
});
rs.lidar()->Open();
rs.Run();
ASSERT_GE(clock_at_scan.size(), 2u);
EXPECT_NEAR(clock_at_scan.front(), 1737000000.0, 0.01);
EXPECT_GT(clock_at_scan.back(), clock_at_scan.front());
}
TEST(ReplaySource, ConfigLucGhiDocLaiDuoc) {
// Ban ghi phai TU MO TA: doc lai sau sau thang van biet no chay voi nguong
// nao, khong phai doan.
const std::string path = TempPath("cfg");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
EXPECT_NE(rs.recorded_config_json().find("range_max"), std::string::npos);
EXPECT_NE(rs.recorded_config_json().find("ban ghi test"), std::string::npos);
std::remove(path.c_str());
}
TEST(ReplaySource, LenhMotorKhiReplayDiVaoHuKhong) {
// Khong co banh xe nao quay, nhung lenh phai den duoc BaseInterface: bai
// regression can kiem rang he thong DA ra lenh dung.
const std::string path = TempPath("cmd");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
rs.base()->Open();
rs.base()->SetVelocity(0.25, -0.1);
rs.Run();
// Khong nem, khong sap. Gia tri duoc giu lai de kiem.
SUCCEED();
std::remove(path.c_str());
}
TEST(ReplaySource, FileKhongTonTaiThiBaoLoi) {
ReplayConfig cfg;
cfg.path = "/khong/ton/tai/abc.vsr";
ReplaySource rs(cfg);
EXPECT_FALSE(rs.Open().ok());
}
TEST(ReplaySource, FileCutGiuaChungBiBao) {
const std::string path = TempPath("cut");
MakeRecording(path, 1);
{
std::ifstream in(path, std::ios::binary | std::ios::ate);
const long size = static_cast<long>(in.tellg());
in.close();
ASSERT_EQ(::truncate(path.c_str(), size - 50), 0);
}
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
rs.Run();
EXPECT_TRUE(rs.stats().truncated) << "file cut phai duoc bao, khong im lang";
std::remove(path.c_str());
}

122
test/test_rle.cc Normal file
View File

@@ -0,0 +1,122 @@
#include "vslam/rle.h"
#include <gtest/gtest.h>
#include <random>
#include <vector>
using namespace vslam;
TEST(Rle, RoundTripDonGian) {
const std::vector<int8_t> in = {0, 0, 0, 100, 100, -1, -1, -1, -1};
std::string buf;
const size_t runs = RleEncode(in, &buf);
EXPECT_EQ(runs, 3u);
EXPECT_EQ(buf.size(), runs * 3);
std::vector<int8_t> out;
ASSERT_TRUE(RleDecode(buf, 0, runs, in.size(), &out));
EXPECT_EQ(out, in);
}
TEST(Rle, GridToanChuaBiet) {
// Truong hop tot nhat: 4 trieu o cung gia tri.
// count la u16 nen run > 65535 phai TACH -- de quen cho nay la bug im lang
// tren ban do lon.
const std::vector<int8_t> in(4000000, -1);
std::string buf;
const size_t runs = RleEncode(in, &buf);
EXPECT_EQ(runs, (4000000u + 65534u) / 65535u); // 62 run
std::vector<int8_t> out;
ASSERT_TRUE(RleDecode(buf, 0, runs, in.size(), &out));
EXPECT_EQ(out.size(), in.size());
EXPECT_EQ(out[0], -1);
EXPECT_EQ(out.back(), -1);
}
TEST(Rle, RunDungBang65535) {
const std::vector<int8_t> in(65535, 7);
std::string buf;
EXPECT_EQ(RleEncode(in, &buf), 1u);
std::vector<int8_t> out;
ASSERT_TRUE(RleDecode(buf, 0, 1, in.size(), &out));
EXPECT_EQ(out, in);
}
TEST(Rle, RunVuotMotDonVi) {
const std::vector<int8_t> in(65536, 7);
std::string buf;
EXPECT_EQ(RleEncode(in, &buf), 2u);
std::vector<int8_t> out;
ASSERT_TRUE(RleDecode(buf, 0, 2, in.size(), &out));
EXPECT_EQ(out, in);
}
TEST(Rle, TruongHopXauNhatKhongLamHongDuLieu) {
// Xen ke tung o: RLE PHINH len 3x. Van phai dung.
std::vector<int8_t> in(1000);
for (size_t i = 0; i < in.size(); ++i) in[i] = static_cast<int8_t>(i % 2 ? 100 : 0);
std::string buf;
const size_t runs = RleEncode(in, &buf);
EXPECT_EQ(runs, in.size());
EXPECT_EQ(buf.size(), in.size() * 3);
std::vector<int8_t> out;
ASSERT_TRUE(RleDecode(buf, 0, runs, in.size(), &out));
EXPECT_EQ(out, in);
}
TEST(Rle, NgauNhien) {
std::mt19937 rng(1234);
std::uniform_int_distribution<int> pick(0, 2);
const int8_t vals[3] = {-1, 0, 100};
for (int trial = 0; trial < 20; ++trial) {
std::vector<int8_t> in;
in.reserve(5000);
// Sinh theo doan de giong ban do that hon la nhieu trang.
while (in.size() < 5000) {
const int8_t v = vals[pick(rng)];
const size_t len = 1 + (rng() % 200);
for (size_t i = 0; i < len && in.size() < 5000; ++i) in.push_back(v);
}
std::string buf;
const size_t runs = RleEncode(in, &buf);
std::vector<int8_t> out;
ASSERT_TRUE(RleDecode(buf, 0, runs, in.size(), &out)) << "trial " << trial;
EXPECT_EQ(out, in) << "trial " << trial;
}
}
TEST(Rle, Rong) {
std::string buf;
EXPECT_EQ(RleEncode({}, &buf), 0u);
EXPECT_TRUE(buf.empty());
EXPECT_EQ(RleEncodedSize({}), 0u);
}
TEST(Rle, EncodedSizeKhopVoiEncode) {
const std::vector<int8_t> in = {0, 0, 1, 1, 1, 2};
std::string buf;
const size_t runs = RleEncode(in, &buf);
EXPECT_EQ(RleEncodedSize(in), runs * 3);
EXPECT_EQ(RleEncodedSize(in), buf.size());
}
TEST(Rle, DuLieuCutBiTuChoi) {
std::string buf = "ab"; // khong du mot run
std::vector<int8_t> out;
EXPECT_FALSE(RleDecode(buf, 0, 1, 10, &out));
}
TEST(Rle, KichThuocKhongKhopBiTuChoi) {
const std::vector<int8_t> in = {5, 5, 5};
std::string buf;
const size_t runs = RleEncode(in, &buf);
std::vector<int8_t> out;
// Noi doi ve kich thuoc mong doi -> phai tu choi, khong duoc phinh bo nho.
EXPECT_FALSE(RleDecode(buf, 0, runs, 2, &out));
EXPECT_FALSE(RleDecode(buf, 0, runs, 100, &out));
}

207
test/test_robot_model.cc Normal file
View File

@@ -0,0 +1,207 @@
// Test cho RobotModel -- lop THAY CHO URDF.
//
// Cai duoc khoa o day khong phai phep toan (TransformTree da co test rieng),
// ma la cac CONG CHAN CONFIG SAI. Moi loi trong robot.yaml deu la loi im
// lang: mot phep bien doi lech 24 cm van cho ra ban do "trong nhu that", chi
// la sai cho.
#include <gtest/gtest.h>
#include <cmath>
#include "vslam/geometry.h"
#include "vslam/node_constants.h"
#include "vslam/robot_model.h"
using namespace vslam;
namespace {
// robot.yaml toi thieu ma hop le.
const char* kGood = R"(
geometry:
wheel_radius: 0.075
wheel_separation: 0.36
frames:
- parent: base_link
child: laser_link
xyz: [0.24, 0.0, 0.125]
rpy: [0.0, 0.0, 0.0]
- parent: base_link
child: camera_link
xyz: [0.19, 0.0, 0.725]
rpy: [0.0, 0.2618, 0.0]
- parent: camera_link
child: camera_depth_optical_frame
xyz: [0.0, 0.0, 0.0]
rpy: [-1.5707963267948966, 0.0, -1.5707963267948966]
)";
StatusResponse LoadYaml(RobotModel* m, const std::string& yaml) {
return m->Load(ConfigNode::LoadString(yaml, "<test>"));
}
} // namespace
TEST(RobotModel, NapDuocFileHopLe) {
RobotModel m;
const StatusResponse st = LoadYaml(&m, kGood);
ASSERT_TRUE(st.ok()) << st.message;
EXPECT_NEAR(m.geometry().wheel_radius, 0.075, 1e-12);
EXPECT_NEAR(m.geometry().wheel_separation, 0.36, 1e-12);
}
TEST(RobotModel, ChieuCaoCameraLaHEQUACuaHaiSoKhac) {
// `cliff_detect.nominal_tz` KHONG duoc go tay: no la
// camera_link.z + wheel_radius. Go tay lan thu hai la cho mot trong hai
// duoc phep lech -- va chung DA lech that: 0.803 trong cliff_detect.h so
// voi 0.80 trong sim.
RobotModel m;
ASSERT_TRUE(LoadYaml(&m, kGood).ok());
EXPECT_NEAR(m.camera_height_above_floor(), 0.725 + 0.075, 1e-12);
EXPECT_NEAR(m.camera_pitch(), 0.2618, 1e-12);
}
TEST(RobotModel, FrameQuangHocDungChieu) {
// Day la phep dung tung bi LAP LAI o bon file. Neu no sai o day thi no sai
// o dung mot cho, va test nay bat duoc.
//
// Quy uoc: +Z_quang = +X_than, +X_quang = -Y_than, +Y_quang = -Z_than.
RobotModel m;
ASSERT_TRUE(LoadYaml(&m, kGood).ok());
Transform cam_to_base;
ASSERT_TRUE(m.StaticTransform(kBaseLinkFrame, kCameraDepthOpticalFrame,
&cam_to_base));
// Mot diem cach camera 2 m theo TRUC QUANG (+Z_quang) phai nam phia TRUOC
// robot, va thap hon camera vi camera chuc xuong 15 do.
const Point p = TransformPoint(cam_to_base, Point{0.0, 0.0, 2.0});
EXPECT_GT(p.x, 1.8) << "truc quang khong tro ve phia truoc";
EXPECT_NEAR(p.y, 0.0, 1e-9) << "lech ngang -- sai phep quay quanh Z";
EXPECT_LT(p.z, 0.725) << "camera chuc xuong ma diem lai cao hon";
// Mot diem lech sang PHAI trong anh (+X_quang) phai nam ben PHAI robot,
// tuc -Y.
const Point q = TransformPoint(cam_to_base, Point{1.0, 0.0, 2.0});
EXPECT_LT(q.y, -0.5) << "+X_quang phai la -Y_than";
}
TEST(RobotModel, FrameLaserDungChoDaKhai) {
RobotModel m;
ASSERT_TRUE(LoadYaml(&m, kGood).ok());
Transform t;
ASSERT_TRUE(m.StaticTransform(kBaseLinkFrame, kLaserFrame, &t));
EXPECT_NEAR(t.translation.x, 0.24, 1e-12);
EXPECT_NEAR(t.translation.z, 0.125, 1e-12);
}
// ==================== Cac cong chan config sai ====================
TEST(RobotModel, FrameKhaiHaiLanBiTuChoi) {
// Hai dong cung `child`: dong sau am tham thang, va nua so nguoi doc file
// se tin dong dau. Day la lop bug ma ca file robot.yaml sinh ra de xoa,
// nen no phai la LOI chu khong phai canh bao.
RobotModel m;
const std::string y = std::string(kGood) + R"(
- parent: base_link
child: laser_link
xyz: [9.9, 0.0, 0.0]
rpy: [0.0, 0.0, 0.0]
)";
const StatusResponse st = LoadYaml(&m, y);
EXPECT_FALSE(st.ok());
EXPECT_NE(st.message.find("laser_link"), std::string::npos) << st.message;
}
TEST(RobotModel, GoSaiTenKhoaLaLoiChuKhongPhaiVeMacDinh) {
// `wheel_base` thay vi `wheel_separation` nghia la MOI phep quay sai ti le,
// va bang mac dinh im lang thi khong co gi bao.
RobotModel m;
const char* y = R"(
geometry:
wheel_radius: 0.075
wheel_base: 0.36
frames:
- parent: base_link
child: laser_link
xyz: [0.24, 0.0, 0.125]
rpy: [0.0, 0.0, 0.0]
)";
const StatusResponse st = LoadYaml(&m, y);
EXPECT_FALSE(st.ok());
EXPECT_NE(st.message.find("wheel_base"), std::string::npos) << st.message;
}
TEST(RobotModel, ThieuKhoiFramesLaLoi) {
RobotModel m;
const StatusResponse st = LoadYaml(&m, "geometry:\n wheel_radius: 0.075\n");
EXPECT_FALSE(st.ok());
EXPECT_NE(st.message.find("frames"), std::string::npos) << st.message;
}
TEST(RobotModel, XyzSaiSoPhanTuLaLoi) {
// `xyz: [0.24, 0.0]` doc bang mat trong nhu that. Thieu mot phan tu nghia
// la z = 0 -- laser tut xuong ngang san.
RobotModel m;
const char* y = R"(
frames:
- parent: base_link
child: laser_link
xyz: [0.24, 0.0]
rpy: [0.0, 0.0, 0.0]
)";
const StatusResponse st = LoadYaml(&m, y);
EXPECT_FALSE(st.ok());
EXPECT_NE(st.message.find("xyz"), std::string::npos) << st.message;
}
TEST(RobotModel, ParentTrungChildLaLoi) {
RobotModel m;
const char* y = R"(
frames:
- parent: base_link
child: base_link
xyz: [0.0, 0.0, 0.0]
rpy: [0.0, 0.0, 0.0]
)";
EXPECT_FALSE(LoadYaml(&m, y).ok());
}
TEST(RobotModel, FrameKhongTonTaiTraFalseChuKhongTaoMoi) {
// `Find` chu khong `Resolve`: tra cuu mot frame go sai ten phai TRA FALSE.
// Neu no am tham tao ra frame moi thi mot cai ten go sai se thanh mot nhanh
// roi, va loi chi hien ra khi ai do thac mac vi sao cloud rong.
RobotModel m;
ASSERT_TRUE(LoadYaml(&m, kGood).ok());
Transform t;
EXPECT_FALSE(m.StaticTransform(kBaseLinkFrame, "camera_dept_optical_frame", &t));
EXPECT_FALSE(m.StaticTransform("khong_ton_tai", kLaserFrame, &t));
}
TEST(RobotModel, FileKhongTonTaiTraLoiChuKhongNem) {
// Mot duong dan config go sai khong duoc phep lam sap tien trinh.
RobotModel m;
StatusResponse st = StatusResponse::Ok();
EXPECT_NO_THROW({ st = m.LoadFile("/khong/co/robot.yaml"); });
EXPECT_FALSE(st.ok());
}
TEST(RobotModel, FileThatTrongConfigurationFilesNapDuoc) {
// File that duoc cai len /etc/vslam phai luon nap duoc. Neu test nay do,
// ban vua lam hong cau hinh se giao cho robot.
const char* dir = std::getenv("VSLAM_CONFIG_SRC_DIR");
if (dir == nullptr) GTEST_SKIP() << "khong co VSLAM_CONFIG_SRC_DIR";
RobotModel m;
const StatusResponse st = m.LoadFile(std::string(dir) + "/robot.yaml");
ASSERT_TRUE(st.ok()) << st.message;
// Va no phai khop voi cac gia tri ma phan con lai cua he dang gia dinh.
EXPECT_NEAR(m.camera_height_above_floor(), 0.80, 1e-9)
<< "chieu cao camera doi -> cliff_detect.nominal_tz phai doi theo";
EXPECT_NEAR(m.geometry().wheel_radius, 0.075, 1e-9);
Transform t;
ASSERT_TRUE(m.StaticTransform(kBaseLinkFrame, kLaserFrame, &t));
EXPECT_NEAR(t.translation.x, 0.24, 1e-9);
}

630
test/test_safety_monitor.cc Normal file
View File

@@ -0,0 +1,630 @@
#include "vslam/safety_monitor.h"
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <vector>
using namespace vslam;
namespace {
constexpr double kPi = 3.14159265358979323846;
constexpr double kInf = std::numeric_limits<double>::infinity();
const float kNaN = std::numeric_limits<float>::quiet_NaN();
// Scan giong LakiBeam that sau khi qua ScanSanitizer.
LaserScan MakeScan(float range_all = 5.0f) {
LaserScan s;
s.angle_min = -2.356194f;
s.angle_max = 2.356194f;
s.angle_increment = static_cast<float>(2.0 * 2.356194 / 1080.0);
s.range_min = 0.05f;
s.range_max = 40.0f;
s.ranges.assign(1081, range_all);
return s;
}
// Dat mot gia tri cho MOI tia trong quat truoc.
void SetFrontRays(LaserScan* s, float value, double front_angle = 0.5) {
for (size_t i = 0; i < s->ranges.size(); ++i) {
const double a = s->angle_min + static_cast<double>(i) * s->angle_increment;
if (std::fabs(a) <= front_angle) s->ranges[i] = value;
}
}
Twist Cmd(double vx, double wz = 0.0) {
Twist t;
t.linear.x = vx;
t.angular.z = wz;
return t;
}
// Dau vao "binh thuong": dang tien, scan sach, moi thu tuoi.
struct Fixture {
LaserScan scan = MakeScan();
Twist cmd = Cmd(0.3);
SafetyInputs in;
Fixture() {
in.now = UnixTime::fromSec(100.0);
in.scan = &scan;
in.scan_stamp = in.now;
in.cmd = &cmd;
in.cmd_stamp = in.now;
}
};
} // namespace
// ===========================================================================
// THU TU UU TIEN -- moi nhanh phai de len TAT CA cac nhanh sau no.
// ===========================================================================
TEST(SafetyMonitor, EstopDeLenMoiThu) {
Fixture f;
SafetyMonitor m;
m.SetEstop(true);
// Them moi ly do khac de robot dung luon: bumper, vuc, sieu am gan.
f.in.have_bumper = true;
f.in.bumper = true;
f.in.have_cliff = true;
f.in.cliff = true;
f.in.cliff_stamp = f.in.now;
f.in.ultrasonic["front"] = 0.05;
f.in.us_stamp = f.in.now;
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kEstop);
EXPECT_EQ(o.cmd.linear.x, 0.0);
EXPECT_EQ(o.cmd.angular.z, 0.0);
}
TEST(SafetyMonitor, BumperDeLenMoiThuTruNoiEstop) {
Fixture f;
SafetyMonitor m;
f.in.have_bumper = true;
f.in.bumper = true;
f.in.bumper_stamp = f.in.now;
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kBumper);
// Trang thai de len moi thu, nhung lenh KHONG con bi ep ve 0 tuyet doi --
// xem khoi BumperPhaiThoatDuoc ben duoi.
EXPECT_LE(std::fabs(o.cmd.linear.x), 0.10 + 1e-9);
}
// ===========================================================================
// THOAT KHI BUMPER DANG CHOT
// ===========================================================================
//
// ⚠️ Chot bumper KHONG duoc bien thanh be tac.
//
// Phep do bumper kiem vanh robot o vi tri HIEN TAI, nen robot dang ti vao vat
// can van bao cham va se chot lai ngay sau moi lan reset. Da do: sau khi lui
// vao tuong, robot khong nhuc nhich duoc 0.000 m theo BAT KY huong nao, qua
// hai lan reset deu tra HTTP 200.
//
// ⚠️ Va "chan tien, cho lui" KHONG phai loi giai: `BumperReading` chi mang mot
// mat na cong tac, khong noi vat can o dau. Lan do that su la robot LUI vao
// tuong -- duong thoat chinh la TIEN, dung chieu bi chan.
//
// Thu BIET huong la LiDAR. Nen chieu tien van di qua dung cong quat truoc,
// chi ha toc do xuong muc thoat.
TEST(SafetyMonitor, BumperChoTienKhiLiDARXacNhanPhiaTruocTrong) {
Fixture f;
SafetyMonitor m;
f.in.have_bumper = true;
f.in.bumper = true;
f.in.bumper_stamp = f.in.now;
f.cmd = Cmd(1.0); // doi tien het co
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kBumper);
EXPECT_NEAR(o.cmd.linear.x, 0.10, 1e-9); // escape_linear, khong phai 1.0
}
TEST(SafetyMonitor, BumperCHAN_TIEN_khiLiDARThayVatCan) {
Fixture f;
SafetyMonitor m;
f.in.have_bumper = true;
f.in.bumper = true;
f.in.bumper_stamp = f.in.now;
SetFrontRays(&f.scan, 0.20f); // gan hon stop_distance 0.35
f.cmd = Cmd(1.0);
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kBumper);
EXPECT_EQ(o.cmd.linear.x, 0.0);
}
// Khong co scan thi khong XAC NHAN duoc phia truoc trong -> chan, khong doan.
TEST(SafetyMonitor, BumperCHAN_TIEN_khiKhongCoScan) {
Fixture f;
SafetyMonitor m;
f.in.have_bumper = true;
f.in.bumper = true;
f.in.bumper_stamp = f.in.now;
f.in.scan = nullptr;
f.cmd = Cmd(1.0);
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kBumper);
EXPECT_EQ(o.cmd.linear.x, 0.0);
}
TEST(SafetyMonitor, BumperChoLuiVaXoayODungTocDoThoat) {
Fixture f;
SafetyMonitor m;
f.in.have_bumper = true;
f.in.bumper = true;
f.in.bumper_stamp = f.in.now;
f.cmd = Cmd(-1.0, 3.0); // lui + xoay het co
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kBumper);
EXPECT_NEAR(o.cmd.linear.x, -0.10, 1e-9); // escape_linear
EXPECT_NEAR(o.cmd.angular.z, 0.4, 1e-9); // escape_angular
}
// Reset khi VAN dang cham: chot dat lai ngay. Do la dung -- va cham van dang
// dien ra -- nhung phai giu duoc duong thoat.
TEST(SafetyMonitor, ResetKhiVanChamThiChotLaiNhungVanThoatDuoc) {
Fixture f;
SafetyMonitor m;
f.in.have_bumper = true;
f.in.bumper = true;
f.in.bumper_stamp = f.in.now;
ASSERT_EQ(m.Step(f.in).state, SafetyState::kBumper);
m.Reset();
const SafetyOutput o = m.Step(f.in); // van dang cham
EXPECT_EQ(o.state, SafetyState::kBumper);
f.cmd = Cmd(1.0);
EXPECT_NEAR(m.Step(f.in).cmd.linear.x, 0.10, 1e-9);
}
// Reset SAU khi da roi ra: tro lai OK. Day la ket thuc cua vong phuc hoi.
TEST(SafetyMonitor, ResetSauKhiDaRoiRaThiTroLaiOK) {
Fixture f;
SafetyMonitor m;
f.in.have_bumper = true;
f.in.bumper = true;
f.in.bumper_stamp = f.in.now;
ASSERT_EQ(m.Step(f.in).state, SafetyState::kBumper);
f.in.bumper = false; // da lui ra khoi vat can
EXPECT_EQ(m.Step(f.in).state, SafetyState::kBumper); // van chot
m.Reset();
EXPECT_EQ(m.Step(f.in).state, SafetyState::kOk);
}
TEST(SafetyMonitor, NoCmdKhiChuaCoLenh) {
Fixture f;
f.in.cmd = nullptr;
SafetyMonitor m;
EXPECT_EQ(m.Step(f.in).state, SafetyState::kNoCmd);
}
TEST(SafetyMonitor, NoCmdKhiLenhQuaCu) {
Fixture f;
SafetyConfig c;
c.cmd_timeout = 0.5;
SafetyMonitor m(c);
f.in.cmd_stamp = UnixTime::fromSec(99.4); // cu 0.6 s
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kNoCmd);
EXPECT_EQ(o.cmd.linear.x, 0.0);
}
TEST(SafetyMonitor, UsTimeoutChiKhiCO_sieu_am) {
Fixture f;
SafetyMonitor m;
// Khong lap sieu am -> khong bao gio US_TIMEOUT. `ultrasonic_topics: []`
// trong cau hinh cu nghia la chua mua cam bien, khong phai cam bien hong.
f.in.us_stamp = UnixTime::fromSec(0.0);
EXPECT_NE(m.Step(f.in).state, SafetyState::kUsTimeout);
// Co lap thi du lieu cu la loi.
f.in.ultrasonic["front"] = 2.0;
EXPECT_EQ(m.Step(f.in).state, SafetyState::kUsTimeout);
}
TEST(SafetyMonitor, UsBlockedPhatHienKINH) {
// LiDAR ToF 940 nm va depth IR deu XUYEN QUA kinh. Sieu am la cach duy nhat.
Fixture f;
SafetyConfig c;
c.us_stop_distance = 0.30;
SafetyMonitor m(c);
f.in.ultrasonic["front"] = 0.20; // gan hon nguong
f.in.us_stamp = f.in.now;
// Scan bao khong co gi -- dung nhu khi truoc mat la cua kinh.
SetFrontRays(&f.scan, 20.0f);
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kUsBlocked);
EXPECT_EQ(o.cmd.linear.x, 0.0);
EXPECT_NEAR(o.us_min, 0.20, 1e-9);
}
// ===========================================================================
// VUC -- nhanh tinh te nhat
// ===========================================================================
TEST(SafetyMonitor, CliffChanTienNhungCHO_LUI_VA_XOAY) {
// Vuc la thu robot co the TU LUI RA KHOI. Chan het moi huong se lam robot
// ket cung truoc mep ma khong ai cuu.
Fixture f;
SafetyMonitor m;
f.in.have_cliff = true;
f.in.cliff = true;
f.in.cliff_stamp = f.in.now;
f.cmd = Cmd(0.3, 0.5); // dang tien VA xoay
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kCliffStop);
EXPECT_EQ(o.cmd.linear.x, 0.0) << "phai chan TIEN";
EXPECT_NEAR(o.cmd.angular.z, 0.5, 1e-9) << "phai GIU xoay de con thoat ra";
}
TEST(SafetyMonitor, CliffKhongChanKhiDangLUI) {
Fixture f;
SafetyMonitor m;
f.in.have_cliff = true;
f.in.cliff = true;
f.in.cliff_stamp = f.in.now;
f.cmd = Cmd(-0.2); // dang lui -- duong thoat
const SafetyOutput o = m.Step(f.in);
EXPECT_NE(o.state, SafetyState::kCliffStop);
EXPECT_NEAR(o.cmd.linear.x, -0.2, 1e-9) << "lui la duong thoat, khong duoc chan";
}
TEST(SafetyMonitor, CliffKHONG_CHOT_nhu_bumper) {
// Bumper la va cham DA XAY RA -> phai co nguoi xac nhan.
// Vuc thi robot tu lui ra duoc -> khong chot.
SafetyConfig c;
c.cliff_hold = 0.0; // tat giu de kiem rieng tinh chat khong chot
c.cliff_timeout = 1.0;
SafetyMonitor m(c);
Fixture f;
f.in.have_cliff = true;
f.in.cliff = true;
f.in.cliff_stamp = f.in.now;
EXPECT_EQ(m.Step(f.in).state, SafetyState::kCliffStop);
// Co tat VA da qua cliff_hold -> khong con chan nua, KHONG can reset.
//
// Phai tien thoi gian: voi hold = 0 va hai moc TRUNG NHAU thi `0 <= 0` van
// dung, nen buoc do van bi chan. Do la hanh vi cua ban goc, khong phai bug.
f.in.cliff = false;
f.in.now = UnixTime::fromSec(100.1);
f.in.cliff_stamp = f.in.now;
f.in.cmd_stamp = f.in.now;
f.in.scan_stamp = f.in.now;
EXPECT_NE(m.Step(f.in).state, SafetyState::kCliffStop);
// Doi lap voi bumper: bumper chot vinh vien cho toi khi Reset().
SafetyMonitor mb;
Fixture g;
g.in.have_bumper = true;
g.in.bumper = true;
g.in.bumper_stamp = g.in.now;
ASSERT_EQ(mb.Step(g.in).state, SafetyState::kBumper);
g.in.bumper = false;
g.in.now = UnixTime::fromSec(200.0); // rat lau sau
g.in.cmd_stamp = g.in.now;
g.in.scan_stamp = g.in.now;
EXPECT_EQ(mb.Step(g.in).state, SafetyState::kBumper) << "bumper PHAI chot";
}
// ===========================================================================
// cliff_hold -- "DA TRA GIA BANG MOT LAN DI THANG VAO BAC THANG"
//
// 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.
// ===========================================================================
TEST(SafetyMonitor, CliffHoldGiuChanSauKhiCoDaTat) {
SafetyConfig c;
c.cliff_hold = 3.0;
c.cliff_timeout = 1.0;
SafetyMonitor m(c);
Fixture f;
f.in.have_cliff = true;
f.in.cliff = true;
f.in.cliff_stamp = f.in.now;
ASSERT_EQ(m.Step(f.in).state, SafetyState::kCliffStop);
// Co tat NGAY (vuc lot khoi tam nhin camera), nhung phai van chan.
f.in.cliff = false;
for (double dt : {0.5, 1.5, 2.5}) {
f.in.now = UnixTime::fromSec(100.0 + dt);
f.in.cliff_stamp = f.in.now;
f.in.cmd_stamp = f.in.now;
f.in.scan_stamp = f.in.now;
EXPECT_EQ(m.Step(f.in).state, SafetyState::kCliffStop)
<< "sau " << dt << " s -- van trong cliff_hold";
}
// Qua cliff_hold thi moi cho di tiep.
f.in.now = UnixTime::fromSec(100.0 + 3.5);
f.in.cliff_stamp = f.in.now;
f.in.cmd_stamp = f.in.now;
f.in.scan_stamp = f.in.now;
EXPECT_NE(m.Step(f.in).state, SafetyState::kCliffStop);
}
TEST(SafetyMonitor, TatCliffStopThiBoQuaHan) {
SafetyConfig c;
c.enable_cliff_stop = false;
SafetyMonitor m(c);
Fixture f;
f.in.have_cliff = true;
f.in.cliff = true;
f.in.cliff_stamp = f.in.now;
EXPECT_NE(m.Step(f.in).state, SafetyState::kCliffStop);
}
// ===========================================================================
// BA NGU NGHIA CUA MOT TIA -- phan de sai nhat
// ===========================================================================
TEST(SafetyMonitor, SANH_TRONG_khong_duoc_tinh_la_loi) {
// MOI tia inf = khong vat nao trong 40 m. Tia VAN phu song, chi la khong co
// phan xa. Dem nham thanh "khong tia nao hop le" se lam robot dung vinh vien
// giua mot can phong trong khong.
Fixture f;
SetFrontRays(&f.scan, kInf);
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
EXPECT_NE(o.state, SafetyState::kScanSparse) << "sanh trong bi coi la loi scan";
EXPECT_EQ(o.state, SafetyState::kOk);
EXPECT_GT(o.front_usable, 20);
EXPECT_EQ(o.front_blanked, 0);
EXPECT_TRUE(std::isinf(o.min_front));
}
TEST(SafetyMonitor, TIA_BLANK_bi_tru_ra_khoi_so_tia_dung_duoc) {
// Sector mask blank tia bang range_max + 1.0 -- HUU HAN va LON HON
// range_max. Khac han inf.
Fixture f;
SetFrontRays(&f.scan, f.scan.range_max + 1.0f);
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kScanSparse);
EXPECT_GT(o.front_blanked, 20);
EXPECT_EQ(o.front_usable, 0);
EXPECT_EQ(o.front_rays, o.front_blanked);
}
TEST(SafetyMonitor, TIA_NAN_khong_dung_de_do_nhung_van_tinh_la_phu_song) {
Fixture f;
SetFrontRays(&f.scan, kNaN);
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
// NaN khong bi tinh la blank, nen front_usable van cao -> KHONG SCAN_SPARSE.
EXPECT_NE(o.state, SafetyState::kScanSparse);
EXPECT_EQ(o.front_blanked, 0);
EXPECT_TRUE(std::isinf(o.min_front)) << "NaN khong duoc dung de do khoang cach";
}
TEST(SafetyMonitor, BaNguNghiaLanLonSeChoKetQuaKHAC_NHAU) {
// Bai nay ton tai de chung minh ba thu do THUC SU khac nhau, khong phai
// ba cach viet cua cung mot y.
SafetyMonitor m;
Fixture a; SetFrontRays(&a.scan, kInf);
Fixture b; SetFrontRays(&b.scan, b.scan.range_max + 1.0f);
Fixture c; SetFrontRays(&c.scan, kNaN);
const SafetyOutput oa = m.Step(a.in);
const SafetyOutput ob = m.Step(b.in);
const SafetyOutput oc = m.Step(c.in);
EXPECT_EQ(oa.front_blanked, 0);
EXPECT_GT(ob.front_blanked, 0);
EXPECT_EQ(oc.front_blanked, 0);
EXPECT_NE(oa.state, ob.state) << "inf va sentinel phai cho ket qua khac nhau";
EXPECT_EQ(oa.state, SafetyState::kOk);
EXPECT_EQ(ob.state, SafetyState::kScanSparse);
}
TEST(SafetyMonitor, TiaGanHonRangeMinKhongDungDeDo) {
Fixture f;
SetFrontRays(&f.scan, 0.01f); // duoi min_valid_range
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
EXPECT_TRUE(std::isinf(o.min_front));
}
TEST(SafetyMonitor, NguongDuoiLayMaxCuaHaiNguon) {
// Driver LakiBeam khai range_min = 0.0 (bug). Ta van dung 0.05.
Fixture f;
f.scan.range_min = 0.0f; // driver noi doi
SetFrontRays(&f.scan, 0.02f); // duoi 0.05 nhung tren 0.0
SafetyConfig c;
c.min_valid_range = 0.05;
SafetyMonitor m(c);
const SafetyOutput o = m.Step(f.in);
EXPECT_TRUE(std::isinf(o.min_front))
<< "tia 0.02 m lot qua -> robot thay vat can ngay duoi bung va dung mai";
}
// ===========================================================================
// SCAN_TIMEOUT / SCAN_SPARSE / SCAN_STOP / SCAN_SLOW
// ===========================================================================
TEST(SafetyMonitor, ScanTimeoutKhiBanTinQuaCu) {
Fixture f;
SafetyConfig c;
c.sensor_timeout = 1.0;
SafetyMonitor m(c);
f.in.scan_stamp = UnixTime::fromSec(98.5); // cu 1.5 s
EXPECT_EQ(m.Step(f.in).state, SafetyState::kScanTimeout);
}
TEST(SafetyMonitor, ScanSparseKhacHanScanTimeout) {
// Ban tin van toi DUNG NHIP, chi la quat truoc khong con tia dung duoc.
Fixture f;
SetFrontRays(&f.scan, f.scan.range_max + 1.0f);
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kScanSparse);
EXPECT_NE(o.state, SafetyState::kScanTimeout);
}
TEST(SafetyMonitor, ScanStopChanTienKhiVatCanGan) {
Fixture f;
SetFrontRays(&f.scan, 0.20f); // gan hon stop_distance 0.35
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kScanStop);
EXPECT_EQ(o.cmd.linear.x, 0.0);
EXPECT_NEAR(o.min_front, 0.20, 1e-6);
}
TEST(SafetyMonitor, ScanSlowGiamTocKhiVatCanVua) {
Fixture f;
SetFrontRays(&f.scan, 0.60f); // giua stop 0.35 va slow 0.80
SafetyConfig c;
c.slow_factor = 0.4;
SafetyMonitor m(c);
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kScanSlow);
EXPECT_NEAR(o.cmd.linear.x, 0.3 * 0.4, 1e-9);
}
TEST(SafetyMonitor, VatCanKhongChanKhiDangLUI) {
// Chi xet khi dang TIEN. Vat can phia truoc khong ngan robot lui ra.
Fixture f;
SetFrontRays(&f.scan, 0.10f);
f.cmd = Cmd(-0.2);
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kOk);
EXPECT_NEAR(o.cmd.linear.x, -0.2, 1e-9);
}
// ===========================================================================
// Chan van toc va chot
// ===========================================================================
TEST(SafetyMonitor, ChanVanTocVuotGioiHan) {
Fixture f;
f.cmd = Cmd(99.0, -99.0);
SafetyConfig c;
c.max_linear = 0.35;
c.max_angular = 0.8;
c.slow_distance = 0.0; // tat giam toc de kiem rieng phep chan
c.stop_distance = 0.0;
SafetyMonitor m(c);
const SafetyOutput o = m.Step(f.in);
EXPECT_NEAR(o.cmd.linear.x, 0.35, 1e-9);
EXPECT_NEAR(o.cmd.angular.z, -0.8, 1e-9);
}
TEST(SafetyMonitor, BumperCHOT_caN_reset) {
Fixture f;
SafetyMonitor m;
f.in.have_bumper = true;
f.in.bumper = true;
f.in.bumper_stamp = f.in.now;
ASSERT_EQ(m.Step(f.in).state, SafetyState::kBumper);
// Bumper nha ra nhung VAN chot.
f.in.bumper = false;
EXPECT_EQ(m.Step(f.in).state, SafetyState::kBumper)
<< "va cham DA XAY RA -- phai co nguoi xac nhan";
EXPECT_TRUE(m.bumper_latched());
m.Reset();
EXPECT_FALSE(m.bumper_latched());
EXPECT_EQ(m.Step(f.in).state, SafetyState::kOk);
}
TEST(SafetyMonitor, EstopBatVaGo) {
Fixture f;
SafetyMonitor m;
EXPECT_EQ(m.Step(f.in).state, SafetyState::kOk);
m.SetEstop(true);
EXPECT_EQ(m.Step(f.in).state, SafetyState::kEstop);
m.SetEstop(false);
EXPECT_EQ(m.Step(f.in).state, SafetyState::kOk);
}
TEST(SafetyMonitor, DuongDiBinhThuongKhongDoiLenh) {
Fixture f;
SetFrontRays(&f.scan, 5.0f); // xa hon slow_distance
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kOk);
EXPECT_NEAR(o.cmd.linear.x, 0.3, 1e-9);
}
TEST(SafetyMonitor, KhongCoScanThiKhongChanVaCungKhongKiemScan) {
// Chua co LiDAR: khong duoc bao SCAN_TIMEOUT hay SCAN_SPARSE, vi khong co
// gi de timeout ca.
Fixture f;
f.in.scan = nullptr;
SafetyMonitor m;
const SafetyOutput o = m.Step(f.in);
EXPECT_EQ(o.state, SafetyState::kOk);
EXPECT_NEAR(o.cmd.linear.x, 0.3, 1e-9);
}
TEST(SafetyMonitor, StepLaHamTHUAN) {
// Cung dau vao -> cung dau ra. Day la thu ban ROS khong lam duoc, vi no doc
// ros::Time::now() ngay trong FSM.
Fixture f;
SetFrontRays(&f.scan, 0.60f);
SafetyMonitor m;
const SafetyOutput a = m.Step(f.in);
const SafetyOutput b = m.Step(f.in);
const SafetyOutput c = m.Step(f.in);
EXPECT_EQ(a.state, b.state);
EXPECT_EQ(b.state, c.state);
EXPECT_NEAR(a.cmd.linear.x, c.cmd.linear.x, 1e-15);
EXPECT_NEAR(a.min_front, c.min_front, 1e-15);
}
TEST(SafetyMonitor, ThongKeDemDungSoBuocBiChan) {
Fixture f;
SetFrontRays(&f.scan, 0.10f); // SCAN_STOP
SafetyMonitor m;
for (int i = 0; i < 5; ++i) m.Step(f.in);
EXPECT_EQ(m.stats().steps, 5u);
EXPECT_EQ(m.stats().blocked_steps, 5u);
EXPECT_EQ(m.stats().state_counts.at(SafetyState::kScanStop), 5u);
}
TEST(SafetyMonitor, TenTrangThaiDayDu) {
// Moi trang thai phai co ten -- chung hien tren web va trong log.
const SafetyState all[] = {
SafetyState::kEstop, SafetyState::kBumper, SafetyState::kNoCmd,
SafetyState::kUsTimeout, SafetyState::kUsBlocked, SafetyState::kCliffStop,
SafetyState::kScanTimeout, SafetyState::kScanSparse, SafetyState::kScanStop,
SafetyState::kScanSlow, SafetyState::kOk};
for (const SafetyState s : all) {
EXPECT_STRNE(SafetyStateName(s), "?") << static_cast<int>(s);
}
}

263
test/test_scan_sanitizer.cc Normal file
View File

@@ -0,0 +1,263 @@
#include "vslam/scan_sanitizer.h"
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <stdexcept>
using namespace vslam;
namespace {
constexpr double kPi = 3.14159265358979323846;
// Cau hinh LakiBeam 1L that: 270 do, 1081 tia, 25 Hz.
LaserScan MakeRawScan() {
LaserScan s;
s.angle_min = -2.356194f;
s.angle_max = 2.356194f;
s.angle_increment = static_cast<float>(2.0 * 2.356194 / 1080.0);
s.scan_time = 0.04f;
// Driver noi doi ba thu nay -- do la ly do lop nay ton tai.
s.range_min = 0.0f;
s.range_max = 100.0f;
s.time_increment = s.scan_time / 1081.0f / 2.0f; // thua phep chia 2
s.ranges.assign(1081, 3.0f);
return s;
}
ScanSanitizerConfig DefaultCfg() {
ScanSanitizerConfig c;
c.range_min = 0.05;
c.range_max = 40.0;
c.fix_time_increment = true;
c.zero_is = "nan";
return c;
}
} // namespace
// --- Ba bug cua driver LakiBeam -------------------------------------------
TEST(ScanSanitizer, EpHeaderVeGiaTriThat) {
ScanSanitizer san(DefaultCfg());
LaserScan s = MakeRawScan();
san.Apply(&s);
EXPECT_FLOAT_EQ(s.range_min, 0.05f);
EXPECT_FLOAT_EQ(s.range_max, 40.0f);
}
TEST(ScanSanitizer, RangeMinBangKhongLaBugNguyHiemNhat) {
// Phep loc chuan cua moi consumer la `if (r < range_min) continue`.
// Voi range_min = 0.0 thi `0.0 < 0.0` sai, nen tia 0.0 -- nghia la "khong
// do duoc" -- bi CHAP NHAN thanh vat can ngay goc LiDAR. Hau qua: robot
// thay vat can 0.0 m va dung vinh vien.
ScanSanitizer san(DefaultCfg());
LaserScan s = MakeRawScan();
s.ranges[100] = 0.0f;
san.Apply(&s);
EXPECT_GT(s.range_min, 0.0f) << "range_min = 0 se cho tia 0.0 lot qua";
EXPECT_TRUE(std::isnan(s.ranges[100])) << "tia 0.0 phai thanh NaN";
}
TEST(ScanSanitizer, BoPhepChia2ThuaCuaTimeIncrement) {
ScanSanitizer san(DefaultCfg());
LaserScan s = MakeRawScan();
const float before = s.time_increment;
san.Apply(&s);
EXPECT_FLOAT_EQ(s.time_increment, s.scan_time / 1081.0f);
EXPECT_NEAR(s.time_increment / before, 2.0f, 1e-3)
<< "phai gap doi gia tri cua driver";
}
// --- Ba ngu nghia cua mot tia ---------------------------------------------
TEST(ScanSanitizer, KhongDoDuocThanhNaNChuKhongPhaiInf) {
// LiDAR tra 0.0 cho CA HAI truong hop "khong co vat" VA "be mat den nuot
// het xung". Map sang inf thi robot clear free space XUYEN QUA ghe da den.
// Map sang NaN thi hong ve phia an toan.
ScanSanitizer san(DefaultCfg());
LaserScan s = MakeRawScan();
s.ranges[0] = 0.0f;
san.Apply(&s);
EXPECT_TRUE(std::isnan(s.ranges[0]));
EXPECT_FALSE(std::isinf(s.ranges[0]));
}
TEST(ScanSanitizer, ZeroIsInfDoiHanhViKhiCauHinh) {
ScanSanitizerConfig c = DefaultCfg();
c.zero_is = "inf";
ScanSanitizer san(c);
LaserScan s = MakeRawScan();
s.ranges[0] = 0.0f;
san.Apply(&s);
EXPECT_TRUE(std::isinf(s.ranges[0]));
}
TEST(ScanSanitizer, DuoiRangeMinThanhNaNKhongPhaiInf) {
// Cho nay CO THE dang co vat that, chi la qua gan de do duoc. Map sang inf
// se cho phep clear free space ngay truoc mui robot.
ScanSanitizer san(DefaultCfg());
LaserScan s = MakeRawScan();
s.ranges[10] = 0.02f;
san.Apply(&s);
EXPECT_TRUE(std::isnan(s.ranges[10]));
}
TEST(ScanSanitizer, TrenRangeMaxThanhInf) {
// "Khong co gi trong tam" -> duoc phep clear free space.
ScanSanitizer san(DefaultCfg());
LaserScan s = MakeRawScan();
s.ranges[20] = 55.0f;
s.ranges[21] = std::numeric_limits<float>::infinity();
san.Apply(&s);
EXPECT_TRUE(std::isinf(s.ranges[20]));
EXPECT_TRUE(std::isinf(s.ranges[21]));
}
TEST(ScanSanitizer, GiaTriHopLeGiuNguyen) {
ScanSanitizer san(DefaultCfg());
LaserScan s = MakeRawScan();
s.ranges[30] = 12.345f;
san.Apply(&s);
EXPECT_FLOAT_EQ(s.ranges[30], 12.345f);
}
TEST(ScanSanitizer, NaNSanCoGiuNguyen) {
ScanSanitizer san(DefaultCfg());
LaserScan s = MakeRawScan();
s.ranges[40] = std::numeric_limits<float>::quiet_NaN();
san.Apply(&s);
EXPECT_TRUE(std::isnan(s.ranges[40]));
}
// --- Sector mask -----------------------------------------------------------
TEST(ScanSanitizer, SectorMaskDungSentinelRangeMaxCong1) {
// Gia tri sentinel PHAI la range_max + 1.0 sau khi header da duoc sua.
// Ban ROS phai ghi mot khoi comment canh bao rang filter header BAT BUOC
// chay truoc filter goc, vi neu nguoc lai thi sentinel thanh 101.0 thay vi
// 41.0 va safety_monitor dem sai. Gop lam mot ham thi khong sai duoc nua.
ScanSanitizerConfig c = DefaultCfg();
c.sector_masks.push_back(SectorMask{118.0 * kPi / 180.0, kPi});
c.sector_masks.push_back(SectorMask{-kPi, -118.0 * kPi / 180.0});
ScanSanitizer san(c);
LaserScan s = MakeRawScan();
san.Apply(&s);
EXPECT_FLOAT_EQ(san.blank_value(), 41.0f);
int blanked = 0;
for (size_t i = 0; i < s.ranges.size(); ++i) {
const double a = s.angle_min + static_cast<double>(i) * s.angle_increment;
if (std::abs(a) > 118.0 * kPi / 180.0) {
EXPECT_FLOAT_EQ(s.ranges[i], 41.0f) << "tia " << i << " goc " << a;
blanked++;
}
}
EXPECT_GT(blanked, 0);
EXPECT_EQ(san.stats().rays_blanked, static_cast<uint64_t>(blanked));
}
TEST(ScanSanitizer, SentinelKhacHanInfVaNaN) {
// Ba thu nay khac nhau va safety_monitor dua vao dung su khac biet do:
// blanked -> khong duoc phep nhin (than robot che)
// inf -> nhin duoc, khong co gi
// NaN -> khong do duoc
ScanSanitizerConfig c = DefaultCfg();
c.sector_masks.push_back(SectorMask{2.0, 2.4});
ScanSanitizer san(c);
LaserScan s = MakeRawScan();
san.Apply(&s);
bool saw_blank = false;
for (const float r : s.ranges) {
if (r == 41.0f) {
saw_blank = true;
EXPECT_FALSE(std::isinf(r));
EXPECT_FALSE(std::isnan(r));
}
}
EXPECT_TRUE(saw_blank);
}
TEST(ScanSanitizer, MaskApTruocMoiPhepLocKhac) {
// Tia bi che thi gia tri do duoc cua no khong co y nghia gi, ke ca khi no
// la 0.0 hay vuot range_max.
ScanSanitizerConfig c = DefaultCfg();
c.sector_masks.push_back(SectorMask{-kPi, kPi}); // che het
ScanSanitizer san(c);
LaserScan s = MakeRawScan();
s.ranges[0] = 0.0f;
s.ranges[1] = 999.0f;
s.ranges[2] = std::numeric_limits<float>::quiet_NaN();
san.Apply(&s);
for (const float r : s.ranges) EXPECT_FLOAT_EQ(r, 41.0f);
EXPECT_EQ(san.stats().rays_zero, 0u);
EXPECT_EQ(san.stats().rays_above_max, 0u);
}
TEST(ScanSanitizer, AngleOffsetXoayCaScan) {
ScanSanitizerConfig c = DefaultCfg();
c.angle_offset_rad = 0.5;
ScanSanitizer san(c);
LaserScan s = MakeRawScan();
const float amin = s.angle_min;
san.Apply(&s);
EXPECT_NEAR(s.angle_min, amin + 0.5f, 1e-5);
}
// --- Cau hinh sai phai bao, khong im lang ---------------------------------
TEST(ScanSanitizer, TuChoiCauHinhVoLy) {
// Mot LiDAR cau hinh sai la mot robot dam vao tuong. Bao ngay luc khoi tao
// chu khong im lang roi ve default.
ScanSanitizerConfig c = DefaultCfg();
c.range_min = 0.0;
EXPECT_THROW(ScanSanitizer{c}, std::invalid_argument);
c = DefaultCfg();
c.range_max = 0.01; // < range_min
EXPECT_THROW(ScanSanitizer{c}, std::invalid_argument);
c = DefaultCfg();
c.zero_is = "khong biet";
EXPECT_THROW(ScanSanitizer{c}, std::invalid_argument);
c = DefaultCfg();
c.sector_masks.push_back(SectorMask{1.0, 0.5}); // upper < lower
EXPECT_THROW(ScanSanitizer{c}, std::invalid_argument);
}
TEST(ScanSanitizer, ScanRongKhongLamSap) {
ScanSanitizer san(DefaultCfg());
LaserScan s;
san.Apply(&s); // khong nem, khong sap
san.Apply(nullptr);
EXPECT_EQ(san.stats().scans, 0u);
}
TEST(ScanSanitizer, ThongKeCongDuTongSoTia) {
ScanSanitizerConfig c = DefaultCfg();
c.sector_masks.push_back(SectorMask{2.0, kPi});
ScanSanitizer san(c);
LaserScan s = MakeRawScan();
s.ranges[0] = 0.0f;
s.ranges[1] = 0.01f;
s.ranges[2] = 999.0f;
san.Apply(&s);
const auto& st = san.stats();
EXPECT_EQ(st.rays_total, 1081u);
EXPECT_EQ(st.rays_zero + st.rays_below_min + st.rays_above_max +
st.rays_blanked + st.rays_valid,
st.rays_total);
}

796
test/test_sim_source.cc Normal file
View File

@@ -0,0 +1,796 @@
#include "vslam/sim_source.h"
#include <cstdio>
#include <unistd.h>
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/node_constants.h"
#include "vslam/occupancy_map_io.h"
using namespace vslam;
namespace {
SimConfig FastCfg() {
SimConfig c;
c.speed = 0.0; // khong ngu -- test phai chay nhanh
// Tat camera cho cac bai KHONG lien quan camera: mot khung depth la 76800
// tia raycast, va cac bai lai xe chay hang chuc giay mo phong. Bai nao can
// camera thi bat lai tuong minh.
c.enable_depth_camera = false;
return c;
}
} // namespace
TEST(SimSource, MoDuocVaSinhDuBaLuong) {
SimSource sim(FastCfg());
ASSERT_TRUE(sim.Open().ok());
int scans = 0, imu = 0, enc = 0;
sim.lidar()->SetCallback([&](LaserScanPtr) { scans++; });
sim.mcu()->SetImuCallback([&](ImuPtr) { imu++; });
sim.base()->SetEncoderCallback([&](const EncoderReading&) { enc++; });
sim.lidar()->Open();
sim.mcu()->Open();
sim.base()->Open();
sim.RunFor(2.0);
EXPECT_EQ(imu, 400); // 2 s x 200 Hz
EXPECT_EQ(scans, 50); // 2 s x 25 Hz
EXPECT_EQ(enc, 100); // 2 s x 50 Hz
}
TEST(SimSource, ScanKhopCauHinhLakiBeamThat) {
SimSource sim(FastCfg());
ASSERT_TRUE(sim.Open().ok());
LaserScanPtr got;
sim.lidar()->SetCallback([&](LaserScanPtr s) { got = s; });
sim.lidar()->Open();
sim.RunFor(0.2);
ASSERT_TRUE(got != nullptr);
EXPECT_EQ(got->ranges.size(), 1081u);
EXPECT_NEAR(got->angle_max - got->angle_min, 4.712389, 1e-5); // 270 do
EXPECT_NEAR(got->scan_time, 0.04f, 1e-5); // 25 Hz
EXPECT_FLOAT_EQ(got->range_min, 0.05f);
EXPECT_FLOAT_EQ(got->range_max, 40.0f);
EXPECT_EQ(got->header.frame_id, "laser_link");
}
TEST(SimSource, RaycastTraInfKhiKhongCoPhanXa) {
// "Khong co phan xa" KHAC "khong do duoc". ScanSanitizer va safety_monitor
// dua vao dung su khac biet nay.
SimConfig c = FastCfg();
c.synthetic_width = 100;
c.synthetic_height = 100;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
LaserScanPtr got;
sim.lidar()->SetCallback([&](LaserScanPtr s) { got = s; });
sim.lidar()->Open();
sim.RunFor(0.2);
ASSERT_TRUE(got != nullptr);
bool any_finite = false;
for (const float r : got->ranges) {
EXPECT_FALSE(std::isnan(r)) << "raycast khong bao gio sinh NaN";
if (std::isfinite(r)) {
any_finite = true;
EXPECT_GT(r, 0.0f);
}
}
EXPECT_TRUE(any_finite) << "trong hanh lang phai co tia cham tuong";
}
TEST(SimSource, LaiThangThiDiThang) {
SimSource sim(FastCfg());
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
const Pose2D p0 = sim.ground_truth();
// Gui lenh lien tuc: deadman se dung robot neu ngung gui.
for (int i = 0; i < 20; ++i) {
sim.base()->SetVelocity(0.35, 0.0);
sim.RunFor(0.15);
}
const Pose2D p1 = sim.ground_truth();
EXPECT_GT(p1.x - p0.x, 0.5) << "phai tien theo truc x";
EXPECT_NEAR(p1.y, p0.y, 1e-6) << "khong duoc lech ngang";
EXPECT_NEAR(p1.theta, p0.theta, 1e-6) << "khong duoc quay";
}
TEST(SimSource, QuayTaiChoThiKhongDiChuyen) {
SimSource sim(FastCfg());
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
const Pose2D p0 = sim.ground_truth();
for (int i = 0; i < 20; ++i) {
sim.base()->SetVelocity(0.0, 0.8);
sim.RunFor(0.15);
}
const Pose2D p1 = sim.ground_truth();
EXPECT_NEAR(p1.x, p0.x, 1e-6);
EXPECT_NEAR(p1.y, p0.y, 1e-6);
EXPECT_GT(std::abs(AngleDiff(p1.theta, p0.theta)), 1.0);
}
TEST(SimSource, DEADMAN_NgungGuiLenhThiTuDung) {
// DAY LA TEST AN TOAN QUAN TRONG NHAT CUA BO MO PHONG.
//
// Tab trinh duyet dong giua luc dang lai, hoac wifi rot -> khong con ai gui
// lenh. Khong co deadman thi robot giu nguyen van toc cuoi VINH VIEN.
SimConfig c = FastCfg();
c.cmd_timeout_sec = 0.3;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
// Chay 2 giay, gui lenh deu dan.
for (int i = 0; i < 20; ++i) {
sim.base()->SetVelocity(0.35, 0.0);
sim.RunFor(0.1);
}
const Pose2D moving = sim.ground_truth();
// NGUNG GUI. Chi chay tiep, khong goi SetVelocity nua.
sim.RunFor(2.0);
const Pose2D after_ramp = sim.ground_truth();
sim.RunFor(2.0);
const Pose2D stopped = sim.ground_truth();
EXPECT_GT(Distance2D(after_ramp, moving), 0.0) << "phai con da theo quan tinh";
EXPECT_LT(Distance2D(stopped, after_ramp), 1e-6)
<< "sau khi het han lenh, robot phai DUNG HAN";
}
TEST(SimSource, GuiLaiLenhThiChayTiep) {
SimConfig c = FastCfg();
c.cmd_timeout_sec = 0.3;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
sim.RunFor(1.0); // het han
const Pose2D a = sim.ground_truth();
for (int i = 0; i < 10; ++i) {
sim.base()->SetVelocity(0.35, 0.0);
sim.RunFor(0.1);
}
const Pose2D b = sim.ground_truth();
EXPECT_GT(Distance2D(b, a), 0.05);
}
TEST(SimSource, VaChamThiDungLai) {
SimConfig c = FastCfg();
c.enable_collision = true;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
// Lai thang rat lau -- hanh lang co tuong o hai dau.
for (int i = 0; i < 400; ++i) {
sim.base()->SetVelocity(0.35, 0.0);
sim.RunFor(0.1);
}
EXPECT_GT(sim.stats().collisions, 0u) << "phai dam vao tuong cuoi hanh lang";
// Va sau khi dam, robot khong duoc di xuyen tuong.
const Pose2D p = sim.ground_truth();
const OccupancyGrid& m = sim.map();
const int cx = static_cast<int>((p.x - m.origin.position.x) / m.resolution);
const int cy = static_cast<int>((p.y - m.origin.position.y) / m.resolution);
ASSERT_GE(cx, 0);
ASSERT_GE(cy, 0);
ASSERT_LT(cx, static_cast<int>(m.width));
ASSERT_LT(cy, static_cast<int>(m.height));
EXPECT_LT(m.data[static_cast<size_t>(cy) * m.width + cx], 50)
<< "robot ket trong o bi chiem";
}
TEST(SimSource, TuChoiXuatPhatTrongTuong) {
// Bao NGAY thay vi de robot ket tu khung dau tien roi nguoi dung ngoi doan
// tai sao no khong nhuc nhich.
SimConfig c = FastCfg();
c.start_x = 1e6; // chac chan ngoai ban do
c.start_y = 1e6;
SimSource sim(c);
const StatusResponse st = sim.Open();
EXPECT_FALSE(st.ok());
EXPECT_NE(st.message.find("tuong"), std::string::npos);
}
TEST(SimSource, EncoderKhopQuangDuongThat) {
// Khong bat truot banh -> encoder phai khop quang duong that.
SimConfig c = FastCfg();
c.slip_factor = 0.0;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
EncoderReading last;
sim.base()->SetEncoderCallback([&](const EncoderReading& e) { last = e; });
sim.base()->Open();
const Pose2D p0 = sim.ground_truth();
for (int i = 0; i < 30; ++i) {
sim.base()->SetVelocity(0.3, 0.0);
sim.RunFor(0.1);
}
const Pose2D p1 = sim.ground_truth();
ASSERT_TRUE(last.valid);
// Di thang: hai banh quay bang nhau, quang duong = goc x ban kinh.
const double from_encoder = 0.5 * (last.left_rad + last.right_rad) * c.wheel_radius;
const double actual = Distance2D(p1, p0);
EXPECT_NEAR(from_encoder, actual, 0.02) << "encoder lech quang duong that";
}
TEST(SimSource, TruotBanhLamEncoderBaoXaHONThucTe) {
// Mo phong dung CHIEU cua hien tuong: banh quay, xe khong di, nen odometry
// bao di XA HON thuc te. Dung nhu bai L6 cua repo cu, noi odometry noi
// 2.05 m con thuc te 1.74 m.
SimConfig c = FastCfg();
c.slip_factor = 2.0;
c.slip_accel_threshold = 0.05;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
EncoderReading last;
sim.base()->SetEncoderCallback([&](const EncoderReading& e) { last = e; });
sim.base()->Open();
const Pose2D p0 = sim.ground_truth();
// Tang toc va giam toc lien tuc -- do la luc banh truot.
for (int i = 0; i < 40; ++i) {
sim.base()->SetVelocity(i % 2 == 0 ? 0.35 : 0.05, 0.0);
sim.RunFor(0.1);
}
const Pose2D p1 = sim.ground_truth();
const double from_encoder = 0.5 * (last.left_rad + last.right_rad) * c.wheel_radius;
const double actual = Distance2D(p1, p0);
EXPECT_GT(from_encoder, actual * 1.02)
<< "encoder=" << from_encoder << " that=" << actual
<< " -- truot phai lam odometry bao XA HON";
}
TEST(SimSource, GroundTruthChiDeDanhGia) {
// Tuong duong /ground_truth/odom cua repo cu: khong estimator nao duoc doc.
SimSource sim(FastCfg());
ASSERT_TRUE(sim.Open().ok());
const Pose2D p = sim.ground_truth();
EXPECT_NEAR(p.x, 0.0, 1e-9);
EXPECT_NEAR(p.y, 0.0, 1e-9);
}
// --- Ban do ----------------------------------------------------------------
TEST(OccupancyMapIo, TheGioiTongHopCoTuongVaLoiDi) {
const OccupancyGrid m = MakeSyntheticWorld(200, 150, 0.05f);
EXPECT_EQ(m.width, 200u);
EXPECT_EQ(m.height, 150u);
int occ = 0, free_c = 0, unknown = 0;
for (const int8_t v : m.data) {
if (v >= 50) occ++;
else if (v == 0) free_c++;
else unknown++;
}
EXPECT_GT(occ, 0) << "phai co tuong";
EXPECT_GT(free_c, 0) << "phai co loi di";
EXPECT_GT(unknown, 0) << "phai co vung chua biet";
}
TEST(OccupancyMapIo, GhiRoiDocLaiKhopNhau) {
const std::string yaml = "/tmp/vslam_test_map_" + std::to_string(::getpid()) + ".yaml";
const OccupancyGrid orig = MakeSyntheticWorld(120, 80, 0.05f);
ASSERT_TRUE(SaveOccupancyMap(orig, yaml).ok());
MapLoadResult r;
ASSERT_TRUE(LoadOccupancyMap(yaml, &r).ok());
EXPECT_EQ(r.grid.width, orig.width);
EXPECT_EQ(r.grid.height, orig.height);
EXPECT_NEAR(r.grid.resolution, orig.resolution, 1e-6);
EXPECT_NEAR(r.grid.origin.position.x, orig.origin.position.x, 1e-4);
EXPECT_NEAR(r.grid.origin.position.y, orig.origin.position.y, 1e-4);
// PGM hang 0 o TREN CUNG, occupancy grid hang 0 o DUOI CUNG. Quen lat truc
// y la loi kinh dien, va hau qua la ban do lat nguoc ma van "trong nhu that".
ASSERT_EQ(r.grid.data.size(), orig.data.size());
int mismatch = 0;
for (size_t i = 0; i < orig.data.size(); ++i) {
if (r.grid.data[i] != orig.data[i]) mismatch++;
}
EXPECT_EQ(mismatch, 0) << "ban do bi lat hoac bien dang khi ghi/doc";
std::remove(yaml.c_str());
std::remove((yaml.substr(0, yaml.size() - 5) + ".pgm").c_str());
}
TEST(OccupancyMapIo, FileKhongTonTaiThiBao) {
MapLoadResult r;
EXPECT_FALSE(LoadOccupancyMap("/khong/ton/tai/map.yaml", &r).ok());
}
// ===========================================================================
// 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,
// va moi o co mot do cao san rieng.
//
// Lop do cao san la thu cho phep kiem cliff_detect -- khong co no thi san
// tuyet doi phang va cliff_detect khong co gi de phat hien.
// ===========================================================================
namespace {
double DepthAt(const CameraFrame& f, uint32_t u, uint32_t v) {
const size_t i = (static_cast<size_t>(v) * f.depth->width + u) * 2;
const uint16_t mm = static_cast<uint16_t>(f.depth->data[i]) |
(static_cast<uint16_t>(f.depth->data[i + 1]) << 8);
return mm == 0 ? 0.0 : mm * 0.001;
}
// Cau hinh cho cac bai CAMERA. FastCfg() tat camera de cac bai khac chay
// nhanh; bai nao can camera thi dung ham nay.
SimConfig CamCfg() {
SimConfig c = FastCfg();
c.enable_depth_camera = true;
return c;
}
CameraFrame GrabFrame(SimSource* sim) {
// Kiem nullptr thay vi de segfault. camera() tra nullptr khi
// enable_depth_camera = false, va quen bat co la loi de mac.
EXPECT_NE(sim->camera(), nullptr) << "camera chua duoc bat trong SimConfig";
CameraFrame empty;
if (sim->camera() == nullptr) return empty;
CameraFrame got;
bool have = false;
sim->camera()->SetCallback([&](const CameraFrame& f) { got = f; have = true; });
sim->camera()->Open();
sim->RunFor(0.1);
EXPECT_TRUE(have);
return got;
}
} // namespace
TEST(SimCamera, SinhKhungDepthDungKichThuoc) {
SimConfig c = CamCfg();
c.enable_depth_camera = true;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
ASSERT_NE(sim.camera(), nullptr);
const CameraFrame f = GrabFrame(&sim);
ASSERT_TRUE(f.depth != nullptr);
EXPECT_EQ(f.depth->width, 320u) << "640 / decimate 2";
EXPECT_EQ(f.depth->height, 240u);
EXPECT_EQ(f.depth->step, 640u) << "16UC1: 2 byte moi diem";
EXPECT_EQ(f.depth->format, PixelFormat::kMono16);
EXPECT_FLOAT_EQ(f.depth->depth_scale, 0.001f);
EXPECT_EQ(f.depth->header.frame_id, kCameraDepthOpticalFrame);
}
TEST(SimCamera, TatCameraThiTraNullptr) {
SimConfig c = FastCfg();
c.enable_depth_camera = false;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
EXPECT_EQ(sim.camera(), nullptr)
<< "tra nullptr chu khong tra camera khong co anh";
}
TEST(SimCamera, CameraInfoGiuKGocVaBaoBinning) {
// crop_decimate cua image_proc cap nhat binning chu KHONG chia lai K.
// Consumer tu bu, dung nhu image_geometry lam. Lam khac di la ep moi
// consumer phai biet minh dang nhan anh da giam mau hay chua.
SimConfig c = CamCfg();
c.depth_decimate = 2;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const CameraFrame f = GrabFrame(&sim);
EXPECT_EQ(f.depth_info.binning_x, 2u);
EXPECT_EQ(f.depth_info.binning_y, 2u);
EXPECT_EQ(f.depth_info.width, 320u);
// K la cua anh GOC 640 rong.
EXPECT_NEAR(f.depth_info.cx(), 320.0, 1.0);
// Sau khi bu binning thi khop anh 320.
EXPECT_NEAR(f.depth_info.cx_binned(), 160.0, 1.0);
// fx = (w/2) / tan(hfov/2) cho anh goc.
const double expect_fx = (640.0 / 2.0) / std::tan(1.204 / 2.0);
EXPECT_NEAR(f.depth_info.fx(), expect_fx, 5.0);
}
TEST(SimCamera, HinhHocSanKhopTinhTay) {
// Camera o z = 0.80, chuc xuong 15 do. Tia o HANG GIUA di dung 15 do xuong,
// nen cham san phang o khoang cach 0.80 / sin(15 do) = 3.09 m.
//
// Day la bai kiem hinh hoc: sai mot dau trong phep xoay se cho con so khac
// han, va khong co cach nao phat hien bang mat thuong khi nhin anh depth.
SimConfig c = CamCfg();
c.camera_z = 0.80;
c.camera_pitch = 0.2618; // 15 do
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const CameraFrame f = GrabFrame(&sim);
const uint32_t w = f.depth->width, h = f.depth->height;
const double expect = c.camera_z / std::sin(c.camera_pitch);
EXPECT_NEAR(DepthAt(f, w / 2, h / 2), expect, 0.05)
<< "ky vong " << expect << " m";
}
TEST(SimCamera, HangDuoiNhinXuongGanHon) {
SimConfig c = CamCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const CameraFrame f = GrabFrame(&sim);
const uint32_t w = f.depth->width, h = f.depth->height;
const double mid = DepthAt(f, w / 2, h / 2);
const double bottom = DepthAt(f, w / 2, h - 1);
EXPECT_GT(mid, bottom) << "hang duoi nhin xuong gan hon hang giua";
EXPECT_GT(bottom, 0.0);
}
// ===========================================================================
// VUC -- day la thu truoc day KHONG kiem duoc bang mo phong
// ===========================================================================
TEST(SimCamera, BAC_HUT_XUONG_lam_depth_LON_HON_ky_vong) {
// Dau hieu ma cliff_detect tim: depth LON HON nhieu so voi mat phang san
// ky vong. Tia di qua mep bac roi cham san thap hon o xa hon.
SimConfig c = CamCfg();
c.camera_z = 0.80;
c.camera_pitch = 0.2618;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const CameraFrame before = GrabFrame(&sim);
const uint32_t w = before.depth->width, h = before.depth->height;
const double flat = DepthAt(before, w / 2, h / 2);
// Bac hut 0.5 m, bat dau 1.5 m truoc robot.
sim.SetFloorHeight(1.5, -2.0, 6.0, 2.0, -0.5f);
const CameraFrame after = GrabFrame(&sim);
const double with_cliff = DepthAt(after, w / 2, h / 2);
// (0.80 + 0.50) / sin(15 do) = 5.02 m
const double expect = (c.camera_z + 0.5) / std::sin(c.camera_pitch);
EXPECT_NEAR(with_cliff, expect, 0.1) << "ky vong " << expect << " m";
EXPECT_GT(with_cliff, flat * 1.5)
<< "bac hut phai lam depth LON HON han mat phang san";
}
TEST(SimCamera, BAC_NHO_LEN_lam_depth_NHO_HON) {
// Chieu nguoc lai: bac cao len thi tia cham som hon.
SimConfig c = CamCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const CameraFrame before = GrabFrame(&sim);
const uint32_t w = before.depth->width, h = before.depth->height;
const double flat = DepthAt(before, w / 2, h / 2);
sim.SetFloorHeight(1.0, -2.0, 6.0, 2.0, 0.3f);
const CameraFrame after = GrabFrame(&sim);
const double with_step = DepthAt(after, w / 2, h / 2);
EXPECT_LT(with_step, flat) << "san cao len thi tia cham som hon";
EXPECT_GT(with_step, 0.0);
}
TEST(SimCamera, DUOI_MinZ_thi_KHONG_THAY_GI) {
// Min-Z ~0.22 m la VUNG MU truoc mui robot ma bumper phai bit. Diem anh o
// do phai la 0 (khong do duoc), khong phai mot khoang cach nho.
//
// Tra ve khoang cach nho o day se lam robot "thay" mot vat can ngay truoc
// mui va dung mai -- trong khi that ra no chi dang khong nhin duoc.
SimConfig c = CamCfg();
c.depth_near = 0.22;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const CameraFrame f = GrabFrame(&sim);
const uint32_t w = f.depth->width, h = f.depth->height;
for (uint32_t v = 0; v < h; ++v) {
for (uint32_t u = 0; u < w; ++u) {
const double d = DepthAt(f, u, v);
if (d > 0.0) {
EXPECT_GE(d, c.depth_near - 0.02)
<< "diem (" << u << "," << v << ") bao " << d
<< " m -- duoi Min-Z phai la 0";
}
}
}
}
TEST(SimCamera, VUOT_depth_far_thi_la_KHONG_DO_DUOC) {
SimConfig c = CamCfg();
c.depth_far = 10.0;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const CameraFrame f = GrabFrame(&sim);
for (uint32_t v = 0; v < f.depth->height; ++v) {
for (uint32_t u = 0; u < f.depth->width; ++u) {
const double d = DepthAt(f, u, v);
EXPECT_LE(d, c.depth_far + 0.05);
}
}
}
TEST(SimCamera, TanSoKhung30Hz) {
SimConfig c = CamCfg();
c.camera_rate_hz = 30.0;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
int n = 0;
sim.camera()->SetCallback([&](const CameraFrame&) { n++; });
sim.camera()->Open();
sim.RunFor(1.0);
EXPECT_GE(n, 28);
EXPECT_LE(n, 32);
EXPECT_EQ(sim.stats().camera_frames, static_cast<uint64_t>(n));
}
// ===========================================================================
// 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.
//
// `gravity_align` phai TU tach hai thanh phan do (`axc = ax - a_lin`,
// `ayc = ay - v*w`). Neu mo phong chi tra trong luc thuan thi phep tru do
// khong bao gio bi kiem tra, va do la ly do lop nghieng nay ton tai.
// ===========================================================================
TEST(SimTilt, DungYenThiKhongNghiengVaAccelBangG) {
SimConfig c = FastCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
ImuPtr last;
sim.mcu()->SetImuCallback([&](ImuPtr m) { last = m; });
sim.mcu()->Open();
sim.base()->Open();
for (int i = 0; i < 20; ++i) { sim.base()->SetVelocity(0.0, 0.0); sim.RunFor(0.1); }
double r, p;
sim.true_tilt(&r, &p);
EXPECT_NEAR(r, 0.0, 0.01);
EXPECT_NEAR(p, 0.0, 0.01);
ASSERT_TRUE(last != nullptr);
const double n = std::sqrt(
last->linear_acceleration.x * last->linear_acceleration.x +
last->linear_acceleration.y * last->linear_acceleration.y +
last->linear_acceleration.z * last->linear_acceleration.z);
EXPECT_NEAR(n, kGravity, 0.05) << "dung yen thi |a| phai bang g";
}
TEST(SimTilt, TangTocThiMuiNGOC_LEN_phanhThiCHUI_XUONG) {
SimConfig c = FastCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
// Tang toc
for (int i = 0; i < 4; ++i) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.1); }
double r, p_accel;
sim.true_tilt(&r, &p_accel);
// Chay deu -> nghieng ve 0
for (int i = 0; i < 25; ++i) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.1); }
double p_steady;
sim.true_tilt(&r, &p_steady);
// Phanh
for (int i = 0; i < 4; ++i) { sim.base()->SetVelocity(0.0, 0.0); sim.RunFor(0.1); }
double p_brake;
sim.true_tilt(&r, &p_brake);
EXPECT_LT(p_accel, -0.005) << "tang toc -> mui ngoc len (pitch am)";
EXPECT_NEAR(p_steady, 0.0, 0.01) << "chay deu -> ve lai phang";
EXPECT_GT(p_brake, 0.005) << "phanh -> mui chui xuong (pitch duong)";
EXPECT_NEAR(p_accel, -p_brake, 0.01) << "hai chieu phai doi xung";
}
TEST(SimTilt, QuayGapThiNGHIENG_NGANG) {
SimConfig c = FastCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
for (int i = 0; i < 25; ++i) { sim.base()->SetVelocity(0.3, 0.8); sim.RunFor(0.1); }
double r, p;
sim.true_tilt(&r, &p);
EXPECT_GT(std::abs(r), 0.005) << "vua chay vua quay phai nghieng ngang";
}
TEST(SimTilt, GIA_TOC_KE_do_TONG_cua_trong_luc_VA_gia_toc_rieng) {
// DAY LA BAI QUAN TRONG NHAT CHO `gravity_align`.
//
// Khi tang toc, thanh phan x cua gia toc ke gom CA HAI:
// - trong luc chieu xuong truc x do mui ngoc len
// - gia toc tinh tien cua robot
// Neu mo phong chi tra mot trong hai thi phep tru cua gravity_align khong
// co gi de tru.
SimConfig c = FastCfg();
c.accel_noise_stddev = 0.0; // tat nhieu de doc duoc con so sach
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
ImuPtr last;
sim.mcu()->SetImuCallback([&](ImuPtr m) { last = m; });
sim.mcu()->Open();
sim.base()->Open();
for (int i = 0; i < 4; ++i) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.1); }
double r, p;
sim.true_tilt(&r, &p);
ASSERT_TRUE(last != nullptr);
// Thanh phan trong luc theo truc x: -g * sin(pitch)
const double gravity_x = -kGravity * std::sin(p);
const double total_x = last->linear_acceleration.x;
const double robot_accel = total_x - gravity_x;
EXPECT_GT(std::abs(gravity_x), 0.05) << "phai co thanh phan trong luc";
EXPECT_GT(robot_accel, 0.05) << "phai co gia toc rieng cua robot";
// Hai thanh phan phai CUNG DAU khi tang toc -- do la ly do gravity_align
// khong the chi nhin |a| de biet minh co dang tinh hay khong.
EXPECT_GT(gravity_x * robot_accel, 0.0);
}
TEST(SimTilt, GYRO_do_van_toc_goc_THAT_tren_ca_ba_truc) {
SimConfig c = FastCfg();
c.gyro_noise_stddev = 0.0;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
ImuPtr last;
sim.mcu()->SetImuCallback([&](ImuPtr m) { last = m; });
sim.mcu()->Open();
sim.base()->Open();
// Dang tang toc -> than dang xoay quanh truc y -> gyro y khac 0.
for (int i = 0; i < 2; ++i) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.05); }
ASSERT_TRUE(last != nullptr);
EXPECT_GT(std::abs(last->angular_velocity.y), 1e-4)
<< "than dang ngoc len ma gyro y = 0";
}
// --- San doc ---------------------------------------------------------------
TEST(SimTilt, SAN_DOC_len_thi_mui_NGOC_LEN) {
SimConfig c = FastCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
// Doc 10%: cao 0.10 m moi met, tu x = 1 den x = 5.
for (double xx = 1.0; xx < 5.0; xx += 0.1) {
sim.SetFloorHeight(xx, -3, xx + 0.1, 3, static_cast<float>((xx - 1.0) * 0.10));
}
for (int i = 0; i < 60; ++i) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.1); }
double r, p;
sim.true_tilt(&r, &p);
// atan(0.10) = 5.71 do. San bi luong tu hoa theo o 5 cm nen do duoc hoi
// thap hon, khoang 5.2 do.
EXPECT_LT(p, -0.07) << "len doc phai ngoc mui len, do duoc " << p * 180 / 3.14159;
EXPECT_GT(p, -0.12);
}
TEST(SimTilt, SAN_DOC_xuong_thi_mui_CHUI_XUONG) {
SimConfig c = FastCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
for (double xx = 1.0; xx < 5.0; xx += 0.1) {
sim.SetFloorHeight(xx, -3, xx + 0.1, 3, static_cast<float>(-(xx - 1.0) * 0.10));
}
for (int i = 0; i < 60; ++i) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.1); }
double r, p;
sim.true_tilt(&r, &p);
EXPECT_GT(p, 0.07);
EXPECT_LT(p, 0.12);
}
TEST(SimTilt, TatFollowTerrainThiKhongNghiengTheoDoc) {
SimConfig c = FastCfg();
c.follow_terrain_slope = false;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
for (double xx = 1.0; xx < 5.0; xx += 0.1) {
sim.SetFloorHeight(xx, -3, xx + 0.1, 3, static_cast<float>((xx - 1.0) * 0.10));
}
for (int i = 0; i < 60; ++i) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.1); }
double r, p;
sim.true_tilt(&r, &p);
EXPECT_NEAR(p, 0.0, 0.02);
}
TEST(SimCamera, CAMERA_NGHIENG_THEO_THAN) {
// Camera gan cung vao than. Than ngoc len thi camera nhin xa hon tren san.
// Day la thu lam `cliff_detect` kho: mat phang san ky vong dich theo tung
// khung, va do la ly do no phai TU hieu chuan lai mat san.
SimConfig c = CamCfg();
// Tat HET nhieu depth -- mo hinh stereo co ba thanh phan.
c.depth_disparity_noise_px = 0.0;
c.depth_noise_floor = 0.0;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
const CameraFrame flat = GrabFrame(&sim);
const uint32_t w = flat.depth->width, h = flat.depth->height;
const double d_flat = DepthAt(flat, w / 2, h / 2);
// Tang toc -> mui ngoc len -> camera nhin xa hon.
CameraFrame tilted;
sim.camera()->SetCallback([&](const CameraFrame& f) { tilted = f; });
for (int i = 0; i < 3; ++i) { sim.base()->SetVelocity(0.35, 0.0); sim.RunFor(0.05); }
double r, p;
sim.true_tilt(&r, &p);
ASSERT_LT(p, -0.005) << "than phai dang ngoc len";
ASSERT_TRUE(tilted.depth != nullptr);
const double d_tilt = DepthAt(tilted, w / 2, h / 2);
EXPECT_GT(d_tilt, d_flat)
<< "mui ngoc len thi tia cham san xa hon: " << d_tilt << " vs " << d_flat;
}
TEST(SimCamera, DEPTH_DROPOUT_tao_lo_hong) {
// D410 that mat diem o be mat toi, be mat bong, va mep vat the.
// `depth_filter` va `cliff_detect` phai chiu duoc lo hong.
SimConfig c = CamCfg();
c.depth_dropout_rate = 0.3;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const CameraFrame f = GrabFrame(&sim);
int zero = 0, total = 0;
for (uint32_t v = 0; v < f.depth->height; ++v) {
for (uint32_t u = 0; u < f.depth->width; ++u) {
total++;
if (DepthAt(f, u, v) == 0.0) zero++;
}
}
const double rate = static_cast<double>(zero) / total;
EXPECT_GT(rate, 0.25) << "dropout 30% ma chi mat " << rate * 100 << "%";
EXPECT_LT(rate, 0.45);
}

272
test/test_slam.cc Normal file
View File

@@ -0,0 +1,272 @@
// Test cho vslam_slam KHONG can DB va khong can chay RTAB-Map.
//
// Ba thu duoc khoa o day, ca ba deu la loi IM LANG neu sai:
// 1. Ten key RTAB-Map go sai bi bo qua khong mot tieng dong.
// 2. Che do (mapping/localization) phai ghi de len ca YAML.
// 3. Ba ngu nghia cua tia laser phai bi BO het khi dung SensorData; bien
// `inf` thanh mot diem se dung buc tuong ao quanh robot.
#include <gtest/gtest.h>
#include <rtabmap/core/Parameters.h>
#include <cmath>
#include <limits>
#include "vslam/geometry.h"
#include "vslam/occupancy_export.h"
#include "vslam/rtabmap_params.h"
#include "vslam/sensor_data_builder.h"
using namespace vslam;
namespace {
LaserScan MakeScan(int n = 360) {
LaserScan s;
s.angle_min = -M_PI;
s.angle_max = M_PI;
s.angle_increment = 2.0 * M_PI / n;
s.range_min = 0.05;
s.range_max = 40.0;
s.ranges.assign(static_cast<size_t>(n), 2.0f);
return s;
}
} // namespace
// ==================== rtabmap_params ====================
TEST(RtabmapParams, GoSaiTenKeyLaLoiChuKhongPhaiCanhBao) {
// Day la ly do ton tai cua ca ham kiem. `Reg/Force3DoF` go thanh
// `Reg/Force3Dof` hien tai bi RTAB-Map bo qua IM LANG, va pose thanh 6-DoF
// ma khong ai biet cho toi khi ban do bat dau nghieng.
RtabmapConfig cfg;
cfg.overrides["Reg/Force3Dof"] = "true"; // go sai chu D
cfg.overrides["Icp/VoxelSize"] = "0.10"; // dung
std::vector<std::string> unknown;
const auto p = BuildRtabmapParams(cfg, &unknown);
ASSERT_EQ(unknown.size(), 1u);
EXPECT_EQ(unknown[0], "Reg/Force3Dof");
EXPECT_EQ(p.at("Icp/VoxelSize"), "0.10") << "key dung bi bo qua theo";
EXPECT_EQ(p.at("Reg/Force3DoF"), "true") << "key go sai da ghi de len key that";
}
TEST(RtabmapParams, MacDinhDuAnDeLenMacDinhRtabmap) {
RtabmapConfig cfg;
std::vector<std::string> unknown;
const auto p = BuildRtabmapParams(cfg, &unknown);
EXPECT_TRUE(unknown.empty());
// 2.5D: pose la SE(2). Mat key nay nghia la uoc luong 6-DoF.
EXPECT_EQ(p.at("Reg/Force3DoF"), "true");
// LiDAR la trong tai, ke ca khi thi giac bat.
EXPECT_EQ(p.at("Reg/Strategy"), "1");
EXPECT_EQ(p.at("Icp/PointToPlane"), "false"); // scan 2D khong co phap tuyen
EXPECT_EQ(p.at("Grid/3D"), "false");
// Va toan bo bang mac dinh cua RTAB-Map van co mat.
const auto def = rtabmap::Parameters::getDefaultParameters();
EXPECT_EQ(p.size(), def.size()) << "them/bot key so voi bang mac dinh";
}
TEST(RtabmapParams, CheDoGhiDeLenCaYaml) {
// Mot file YAML dat Mem/IncrementalMemory=true trong khi goi chay o che do
// localization se GHI THEM vao ban do da quet. Suy dien tu mode phai thang.
RtabmapConfig cfg;
cfg.mode = SlamMode::kLocalization;
cfg.overrides["Mem/IncrementalMemory"] = "true"; // YAML co gang bat
std::vector<std::string> unknown;
const auto p = BuildRtabmapParams(cfg, &unknown);
EXPECT_TRUE(unknown.empty());
EXPECT_EQ(p.at("Mem/IncrementalMemory"), "false") << "YAML ghi de duoc mode";
EXPECT_EQ(p.at("Mem/InitWMWithAllNodes"), "true")
<< "localization ma khong nap het node -> vung chua tung den khong duoc xet";
}
TEST(RtabmapParams, OptimizerLuonDuocEpTuongMinh) {
// map_house.db luu Optimizer/Strategy=2 (GTSAM). Tren Jetson build
// -DWITH_GTSAM=OFF ma de RTAB-Map doc tham so tu DB thi no chon GTSAM va
// crash thieu symbol. Day la lop thu hai trong ba lop phong thu.
RtabmapConfig cfg;
cfg.optimizer_strategy = "1";
cfg.overrides["Optimizer/Strategy"] = "2"; // YAML co gang doi
std::vector<std::string> unknown;
const auto p = BuildRtabmapParams(cfg, &unknown);
EXPECT_EQ(p.at("Optimizer/Strategy"), "1");
}
TEST(RtabmapParams, VisualLoopBatTatTuiTu) {
RtabmapConfig cfg;
std::vector<std::string> unknown;
cfg.visual_loop = false;
EXPECT_EQ(BuildRtabmapParams(cfg, &unknown).at("Kp/MaxFeatures"), "-1");
cfg.visual_loop = true;
EXPECT_EQ(BuildRtabmapParams(cfg, &unknown).at("Kp/MaxFeatures"), "400");
}
TEST(RtabmapParams, G2oPhaiCoMat) {
// Ca kien truc chot g2o. Neu librtabmap_core khong co no thi phai biet
// NGAY chu khong phai luc chay tren Jetson.
EXPECT_TRUE(OptimizerAvailable("1")) << "librtabmap_core khong co g2o";
EXPECT_FALSE(OptimizerAvailable("khong-phai-so"));
EXPECT_FALSE(OptimizerAvailable("9"));
}
// ==================== sensor_data_builder ====================
TEST(SensorDataBuilder, Pose2DDiVaVeKhongMatGi) {
const Pose2D in{1.25, -3.5, 1.1};
const Pose2D out = FromRtabmap(ToRtabmap(in));
EXPECT_NEAR(out.x, in.x, 1e-5);
EXPECT_NEAR(out.y, in.y, 1e-5);
EXPECT_NEAR(AngleDiff(out.theta, in.theta), 0.0, 1e-5);
}
TEST(SensorDataBuilder, BaNguNghiaCuaTiaDeuBiBo) {
// NaN = khong do duoc; inf = khong co phan xa; >= range_max = sentinel do
// sector mask cat. Bien `inf` thanh mot diem o range_max se dung mot BUC
// TUONG AO quanh robot va ICP se khop vao no thay vi vao tuong that.
LaserScan s = MakeScan(8);
s.ranges[0] = std::numeric_limits<float>::quiet_NaN();
s.ranges[1] = std::numeric_limits<float>::infinity();
s.ranges[2] = static_cast<float>(s.range_max + 1.0); // sentinel
s.ranges[3] = 0.01f; // duoi range_min
// con lai 4 tia hop le
const rtabmap::LaserScan out = BuildLaserScan(s, TransformIdentity());
EXPECT_EQ(out.size(), 4) << "so diem giu lai khong dung";
}
TEST(SensorDataBuilder, ScanRongTraVeScanRongChuKhongNem) {
LaserScan s = MakeScan(8);
for (float& r : s.ranges) r = std::numeric_limits<float>::infinity();
const rtabmap::LaserScan out = BuildLaserScan(s, TransformIdentity());
EXPECT_TRUE(out.isEmpty());
}
TEST(SensorDataBuilder, ToaDoDiemDungTrongFrameLaser) {
LaserScan s;
s.angle_min = 0.0;
s.angle_max = M_PI / 2;
s.angle_increment = M_PI / 2;
s.range_min = 0.05;
s.range_max = 40.0;
s.ranges = {2.0f, 3.0f}; // 0 do va 90 do
const rtabmap::LaserScan out = BuildLaserScan(s, TransformIdentity());
ASSERT_EQ(out.size(), 2);
const cv::Mat& d = out.data();
const float* p0 = d.ptr<float>(0, 0);
const float* p1 = d.ptr<float>(0, 1);
EXPECT_NEAR(p0[0], 2.0f, 1e-4); // (2, 0)
EXPECT_NEAR(p0[1], 0.0f, 1e-4);
EXPECT_NEAR(p1[0], 0.0f, 1e-4); // (0, 3)
EXPECT_NEAR(p1[1], 3.0f, 1e-4);
}
TEST(SensorDataBuilder, FrameCucBoCuaLaserDuocGiuLai) {
// laser o x = 0.24 tren than robot. Mat phep bien doi nay thi ca ban do
// lech 24 cm, va khong co gi bao loi.
Transform t = TransformIdentity();
t.translation = Vector3{0.24, 0.0, 0.18};
const rtabmap::LaserScan out = BuildLaserScan(MakeScan(8), t);
EXPECT_NEAR(out.localTransform().x(), 0.24f, 1e-5);
EXPECT_NEAR(out.localTransform().z(), 0.18f, 1e-5);
}
TEST(OccupancyExport, DuongDanRongKhongBiCoiLaDbTonTai) {
// `openConnection("")` van THANH CONG (tao DB tam). Khong chan thi moi kiem
// dieu kien tien quyet deu chay tren mot DB rong va bao nham.
const DbFacts f = InspectDatabase("");
EXPECT_FALSE(f.exists);
EXPECT_EQ(f.nodes, 0);
}
TEST(OccupancyExport, DbKhongTonTaiThiBaoKhongTonTai) {
const DbFacts f = InspectDatabase("/khong/co/duong/dan/nay.db");
EXPECT_FALSE(f.exists);
}
TEST(SensorDataBuilder, FrameLaserSaiLamMoiDiemLechDungBangNo) {
// Loi da mac: `RtabmapSlam` co bien `laser_to_base` nhung KHONG co setter.
// Moi scan bi dat o goc toa do thay vi o (0.24, 0, 0.20). ICP van hoi tu --
// no chi thay ca the gioi dich di -- nhung do thi tich luy sai so, va
// khong co gi bao loi.
//
// Do duoc tren map_house.db: ATE 0.2378 m voi frame dong nhat, 0.0146 m
// voi frame dung. Cong cu chinh thuc rtabmap-reprocess cung tham so cho
// 0.0074 m -- tuc la chenh lech KHONG phai do cau hinh.
LaserScan s;
s.angle_min = 0.0;
s.angle_max = 1.0;
s.angle_increment = 1.0;
s.range_min = 0.05;
s.range_max = 40.0;
s.ranges = {2.0f};
Transform laser = TransformIdentity();
laser.translation = Vector3{0.24, 0.0, 0.20};
const rtabmap::LaserScan a = BuildLaserScan(s, TransformIdentity());
const rtabmap::LaserScan b = BuildLaserScan(s, laser);
// Toa do DIEM giong nhau -- chung nam trong frame laser.
ASSERT_EQ(a.size(), 1);
ASSERT_EQ(b.size(), 1);
EXPECT_NEAR(a.data().ptr<float>(0, 0)[0], b.data().ptr<float>(0, 0)[0], 1e-6);
// Nhung frame cuc bo thi KHAC. Do la thu RTAB-Map dung de dat scan vao do
// thi, va do cung la thu bi mat khi quen setter.
EXPECT_NEAR(a.localTransform().x(), 0.0f, 1e-6);
EXPECT_NEAR(b.localTransform().x(), 0.24f, 1e-6);
EXPECT_NEAR(b.localTransform().z(), 0.20f, 1e-6);
}
TEST(SensorDataBuilder, TransformDiVaVeKhongMatGi) {
Transform t = TransformIdentity();
t.translation = Vector3{0.24, -0.1, 0.20};
t.rotation = QuaternionFromRPY(0.1, -0.2, 0.3);
const Transform back = TransformFromRtabmap(ToRtabmap(t));
EXPECT_NEAR(back.translation.x, t.translation.x, 1e-5);
EXPECT_NEAR(back.translation.z, t.translation.z, 1e-5);
double r0, p0, y0, r1, p1, y1;
RPYFromQuaternion(t.rotation, &r0, &p0, &y0);
RPYFromQuaternion(back.rotation, &r1, &p1, &y1);
EXPECT_NEAR(AngleDiff(r1, r0), 0.0, 1e-5);
EXPECT_NEAR(AngleDiff(p1, p0), 0.0, 1e-5);
EXPECT_NEAR(AngleDiff(y1, y0), 0.0, 1e-5);
}
TEST(SensorDataBuilder, HinhHocGocSuyBienKhongLamSapTienTrinh) {
// rtabmap::LaserScan::init() NEM UException khi angleIncrement <= 0 hoac
// angleMax <= angleMin. Mot sweep thieu goi UDP co the cho ra dung the, va
// ngoai le do se giet luong SLAM.
//
// Phai tra scan RONG (RTAB-Map bo qua khung khong co scan) chu khong nem.
LaserScan s;
s.range_min = 0.05;
s.range_max = 40.0;
s.ranges = {1.0f, 2.0f, 3.0f};
s.angle_min = 0.0; s.angle_max = 0.0; s.angle_increment = 0.01;
EXPECT_NO_THROW({ EXPECT_TRUE(BuildLaserScan(s, TransformIdentity()).isEmpty()); });
s.angle_min = 0.0; s.angle_max = 1.0; s.angle_increment = 0.0;
EXPECT_NO_THROW({ EXPECT_TRUE(BuildLaserScan(s, TransformIdentity()).isEmpty()); });
s.angle_min = 0.0; s.angle_max = 1.0; s.angle_increment = -0.01;
EXPECT_NO_THROW({ EXPECT_TRUE(BuildLaserScan(s, TransformIdentity()).isEmpty()); });
// range suy bien cung vay
s.angle_increment = 0.01; s.range_min = 40.0; s.range_max = 0.05;
EXPECT_NO_THROW({ EXPECT_TRUE(BuildLaserScan(s, TransformIdentity()).isEmpty()); });
}

301
test/test_teleop_model.cc Normal file
View File

@@ -0,0 +1,301 @@
#include "vslam/teleop_model.h"
#include <gtest/gtest.h>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace vslam;
namespace {
struct Vector {
std::string tag;
double lin, ang, joy_h, joy_v, lin_speed, ang_speed;
};
std::vector<Vector> LoadVectors() {
// Duong dan do CMake truyen vao, khong hardcode.
const char* dir = std::getenv("VSLAM_TEST_DATA_DIR");
const std::string path =
std::string(dir != nullptr ? dir : "data") + "/teleop_vectors.txt";
std::vector<Vector> out;
std::ifstream f(path);
if (!f) return out;
std::string line;
while (std::getline(f, line)) {
if (line.empty() || line[0] == '#') continue;
std::istringstream ss(line);
Vector v;
ss >> v.tag >> v.lin >> v.ang >> v.joy_h >> v.joy_v >> v.lin_speed >> v.ang_speed;
out.push_back(v);
}
return out;
}
// Chay CUNG mot chuoi thao tac nhu gen_teleop_vectors.py.
// Hai ham nay phai giu dong bo voi nhau -- do la toan bo y nghia cua bai test.
std::vector<Vector> RunCppSequence() {
std::vector<Vector> out;
TeleopModel m;
auto emit = [&](const char* tag) {
const auto c = m.Command();
const auto j = m.JoystickPosition();
out.push_back(Vector{tag, c.first, c.second, j.first, j.second,
m.linear_speed(), m.angular_speed()});
};
emit("init");
const TeleopKey keys[] = {TeleopKey::kUp, TeleopKey::kDown, TeleopKey::kLeft,
TeleopKey::kRight};
const char* down_tags[] = {"key_down_Up", "key_down_Down", "key_down_Left",
"key_down_Right"};
const char* up_tags[] = {"key_up_Up", "key_up_Down", "key_up_Left", "key_up_Right"};
for (int i = 0; i < 4; ++i) {
m.SetKey(keys[i], true);
emit(down_tags[i]);
m.SetKey(keys[i], false);
emit(up_tags[i]);
}
m.SetKey(TeleopKey::kUp, true);
m.SetKey(TeleopKey::kLeft, true);
emit("up_left");
m.SetKey(TeleopKey::kDown, true);
emit("up_left_down");
m.ClearKeys();
emit("clear_keys");
const double hv[][2] = {{0.0, -1.0}, {0.0, 1.0}, {-1.0, 0.0}, {1.0, 0.0},
{0.5, -0.5}, {-0.3, 0.7}, {2.0, -2.0}, {-2.0, 2.0}};
const char* joy_tags[] = {"joy_0.0_-1.0", "joy_0.0_1.0", "joy_-1.0_0.0",
"joy_1.0_0.0", "joy_0.5_-0.5", "joy_-0.3_0.7",
"joy_2.0_-2.0", "joy_-2.0_2.0"};
for (int i = 0; i < 8; ++i) {
m.SetJoystick(hv[i][0], hv[i][1]);
emit(joy_tags[i]);
}
m.ReleaseJoystick();
emit("joy_release");
m.SetKey(TeleopKey::kUp, true);
emit("key_then");
m.SetJoystick(0.0, -1.0);
emit("joy_over_key");
m.ReleaseJoystick();
emit("joy_released_key_remains");
m.ClearKeys();
for (int i = 0; i < 5; ++i) { m.AdjustLinearSpeed(+1); emit("lin_up"); }
for (int i = 0; i < 12; ++i) { m.AdjustLinearSpeed(-1); emit("lin_down"); }
for (int i = 0; i < 3; ++i) { m.AdjustAngularSpeed(+1); emit("ang_up"); }
for (int i = 0; i < 20; ++i) { m.AdjustAngularSpeed(-1); emit("ang_down"); }
m.SetLinearSpeed(1.5); emit("set_lin_1.5");
m.SetLinearSpeed(99.0); emit("set_lin_99");
m.SetAngularSpeed(-5.0); emit("set_ang_-5");
{
const double lin = 0.25;
m.SetManualCommand(&lin, nullptr);
emit("manual_lin");
}
{
const double ang = -0.4;
m.SetManualCommand(nullptr, &ang);
emit("manual_ang");
}
m.SetJoystick(0.0, -1.0);
emit("joy_clears_manual");
{
const double lin = 0.1, ang = 0.1;
m.SetManualCommand(&lin, &ang);
emit("manual_over_joy");
}
m.SetKey(TeleopKey::kUp, true);
emit("key_clears_manual");
m.ClearMotion();
emit("clear_motion");
m.SetMaxLinearSpeed(0.5); emit("max_lin_0.5");
m.SetMaxAngularSpeed(0.3); emit("max_ang_0.3");
m.SetMinLinearCommand(-0.2); emit("min_lin_cmd");
m.SetMinAngularCommand(-0.1);emit("min_ang_cmd");
m.SetJoystick(1.0, 1.0); emit("joy_at_limits");
{
const double lin = -99.0, ang = 99.0;
m.SetManualCommand(&lin, &ang);
emit("manual_clamped");
}
return out;
}
} // namespace
// ===========================================================================
// DAY LA BAI KIEM QUAN TRONG NHAT CUA FILE.
//
// teleop_model.py ghi o dau file: "Logic giu NGUYEN VEN, khong sua mot dong
// nao." Doc hai file roi gat dau thi khong phai kiem chung. Bai nay chay CUNG
// mot chuoi thao tac tren ca hai ban va so tung so.
//
// Vector duoc sinh boi test/gen_teleop_vectors.py tu chinh ban Python goc.
// Doi mo hinh -> chay lai script -> diff se chi ra dung cho doi.
// ===========================================================================
TEST(TeleopModel, KhopTungSoVoiBanPythonGoc) {
const std::vector<Vector> want = LoadVectors();
ASSERT_FALSE(want.empty())
<< "khong nap duoc teleop_vectors.txt -- chay test/gen_teleop_vectors.py";
const std::vector<Vector> got = RunCppSequence();
ASSERT_EQ(got.size(), want.size()) << "chuoi thao tac hai ben da lech nhau";
for (size_t i = 0; i < want.size(); ++i) {
EXPECT_EQ(got[i].tag, want[i].tag) << "buoc " << i;
EXPECT_NEAR(got[i].lin, want[i].lin, 1e-9) << "buoc " << i << " (" << want[i].tag << ") linear";
EXPECT_NEAR(got[i].ang, want[i].ang, 1e-9) << "buoc " << i << " (" << want[i].tag << ") angular";
EXPECT_NEAR(got[i].joy_h, want[i].joy_h, 1e-9) << "buoc " << i << " joy_h";
EXPECT_NEAR(got[i].joy_v, want[i].joy_v, 1e-9) << "buoc " << i << " joy_v";
EXPECT_NEAR(got[i].lin_speed, want[i].lin_speed, 1e-9) << "buoc " << i << " linear_speed";
EXPECT_NEAR(got[i].ang_speed, want[i].ang_speed, 1e-9) << "buoc " << i << " angular_speed";
}
}
// --- Hanh vi rieng le ------------------------------------------------------
TEST(TeleopModel, ThuTuUuTienManualJoystickPhim) {
TeleopModel m;
m.SetKey(TeleopKey::kUp, true);
EXPECT_NEAR(m.Command().first, 0.30, 1e-9);
// Joystick de len phim.
m.SetJoystick(0.0, -1.0);
EXPECT_TRUE(m.joystick_active());
EXPECT_NEAR(m.Command().first, 0.30, 1e-9);
// Manual de len ca hai, VA xoa chung.
const double lin = 0.1;
m.SetManualCommand(&lin, nullptr);
EXPECT_TRUE(m.manual_control_active());
EXPECT_FALSE(m.joystick_active());
EXPECT_FALSE(m.key_pressed(TeleopKey::kUp));
EXPECT_NEAR(m.Command().first, 0.1, 1e-9);
// Bam phim xoa manual.
m.SetKey(TeleopKey::kDown, true);
EXPECT_FALSE(m.manual_control_active());
EXPECT_NEAR(m.Command().first, -0.30, 1e-9);
}
TEST(TeleopModel, UpVaDownTrietTieuNhau) {
TeleopModel m;
m.SetKey(TeleopKey::kUp, true);
m.SetKey(TeleopKey::kDown, true);
EXPECT_NEAR(m.Command().first, 0.0, 1e-12);
}
TEST(TeleopModel, JoystickKepVaoDaiDonVi) {
TeleopModel m;
m.SetJoystick(5.0, -5.0);
const auto p = m.JoystickPosition();
EXPECT_NEAR(p.first, 1.0, 1e-12);
EXPECT_NEAR(p.second, -1.0, 1e-12);
}
TEST(TeleopModel, ChinhTocDoKepGiuaMinVaMax) {
TeleopModel m;
for (int i = 0; i < 100; ++i) m.AdjustLinearSpeed(+1);
EXPECT_NEAR(m.linear_speed(), m.max_linear_speed(), 1e-12);
for (int i = 0; i < 200; ++i) m.AdjustLinearSpeed(-1);
EXPECT_NEAR(m.linear_speed(), 0.05, 1e-12); // min_linear_speed
}
TEST(TeleopModel, GiamMaxThiKeoTocDoHienTaiXuongTheo) {
TeleopModel m;
m.SetLinearSpeed(1.5);
m.SetMaxLinearSpeed(0.4);
EXPECT_NEAR(m.linear_speed(), 0.4, 1e-12);
}
TEST(TeleopModel, GioiHanLuiKhacGioiHanTien) {
// min_linear_command tach rieng de gioi han lui chat hon tien.
TeleopModel m;
m.SetMaxLinearSpeed(1.0);
m.SetMinLinearCommand(-0.2);
m.SetLinearSpeed(1.0);
m.SetKey(TeleopKey::kUp, true);
EXPECT_NEAR(m.Command().first, 1.0, 1e-9);
m.SetKey(TeleopKey::kUp, false);
m.SetKey(TeleopKey::kDown, true);
EXPECT_NEAR(m.Command().first, -0.2, 1e-9) << "lui phai bi kep chat hon";
}
TEST(TeleopModel, ClearMotionDuaVeKhong) {
TeleopModel m;
m.SetKey(TeleopKey::kUp, true);
m.SetJoystick(1.0, -1.0);
m.ClearMotion();
EXPECT_NEAR(m.Command().first, 0.0, 1e-12);
EXPECT_NEAR(m.Command().second, 0.0, 1e-12);
EXPECT_FALSE(m.joystick_active());
EXPECT_FALSE(m.manual_control_active());
}
TEST(TeleopModel, PhimMuiTenCungLamKnobDich) {
// De nguoi lai thay duoc minh dang bam gi.
TeleopModel m;
m.SetKey(TeleopKey::kUp, true);
EXPECT_NEAR(m.JoystickPosition().second, -1.0, 1e-12);
m.SetKey(TeleopKey::kUp, false);
m.SetKey(TeleopKey::kRight, true);
EXPECT_NEAR(m.JoystickPosition().first, 1.0, 1e-12);
}
TEST(TeleopModel, TuChoiCauHinhVoLy) {
// Mot gioi han van toc sai la mot robot chay nhanh hon nguoi lai nghi.
TeleopConfig c;
c.linear_step = 0.0;
EXPECT_THROW(TeleopModel{c}, std::invalid_argument);
c = TeleopConfig();
c.min_linear_speed = -1.0;
EXPECT_THROW(TeleopModel{c}, std::invalid_argument);
c = TeleopConfig();
c.max_linear_speed = 0.01; // < min
EXPECT_THROW(TeleopModel{c}, std::invalid_argument);
c = TeleopConfig();
c.has_min_linear_command = true;
c.min_linear_command = 0.5; // phai <= 0
EXPECT_THROW(TeleopModel{c}, std::invalid_argument);
}
TEST(TeleopModel, TuChoiGiaTriKhongHuuHan) {
TeleopModel m;
EXPECT_THROW(m.SetJoystick(std::nan(""), 0.0), std::invalid_argument);
EXPECT_THROW(m.SetLinearSpeed(std::nan("")), std::invalid_argument);
const double bad = std::nan("");
EXPECT_THROW(m.SetManualCommand(&bad, nullptr), std::invalid_argument);
}
TEST(TeleopModel, ParseTenPhim) {
TeleopKey k;
EXPECT_TRUE(ParseTeleopKey("Up", &k));
EXPECT_EQ(k, TeleopKey::kUp);
EXPECT_TRUE(ParseTeleopKey("Right", &k));
EXPECT_EQ(k, TeleopKey::kRight);
EXPECT_FALSE(ParseTeleopKey("Space", &k));
EXPECT_FALSE(ParseTeleopKey("w", &k));
EXPECT_STREQ(TeleopKeyName(TeleopKey::kDown), "Down");
}

207
test/test_transform_tree.cc Normal file
View File

@@ -0,0 +1,207 @@
#include "vslam/transform_tree.h"
#include <gtest/gtest.h>
#include <cmath>
#include "vslam/geometry.h"
#include "vslam/node_constants.h"
using namespace vslam;
namespace {
constexpr double kPi = 3.14159265358979323846;
Transform MakeTf(double x, double y, double z, double yaw) {
Transform t;
t.translation = Vector3{x, y, z};
t.rotation = QuaternionFromYaw(yaw);
return t;
}
// Cay that cua he: map -> odom -> base_footprint -> base_link -> laser_link
// Nhan tham chieu chu khong tra ve theo gia tri: TransformTree co destructor
// tuong minh nen move ctor bi an, va copy thi da xoa.
void MakeRobotTree(TransformTree* tree, FrameId* map, FrameId* odom, FrameId* bf,
FrameId* bl, FrameId* laser) {
*map = tree->Resolve(kMapFrame);
*odom = tree->Resolve(kOdomFrame);
*bf = tree->Resolve(kBaseFootprintFrame);
*bl = tree->Resolve(kBaseLinkFrame);
*laser = tree->Resolve(kLaserFrame);
// laser_joint cua robot.urdf.xacro: x=0.24, z=0.125
tree->SetStatic(*bl, *laser, MakeTf(0.24, 0.0, 0.125, 0.0));
}
} // namespace
TEST(TransformTree, FrameIdOnDinh) {
TransformTree tree;
const FrameId a = tree.Resolve("map");
const FrameId b = tree.Resolve("map");
EXPECT_EQ(a, b);
EXPECT_EQ(tree.Name(a), "map");
EXPECT_EQ(tree.Find("map"), a);
EXPECT_EQ(tree.Find("khong_ton_tai"), kInvalidFrame);
}
TEST(TransformTree, CanhTinh) {
FrameId map, odom, bf, bl, laser;
TransformTree tree(10.0, 512);
MakeRobotTree(&tree, &map, &odom, &bf, &bl, &laser);
Transform out;
std::string err;
ASSERT_TRUE(tree.LookupLatest(bl, laser, &out, &err)) << err;
EXPECT_NEAR(out.translation.x, 0.24, 1e-12);
EXPECT_NEAR(out.translation.z, 0.125, 1e-12);
}
TEST(TransformTree, TuChoiTaoVong) {
TransformTree tree;
const FrameId a = tree.Resolve("a");
const FrameId b = tree.Resolve("b");
EXPECT_TRUE(tree.SetStatic(a, b, TransformIdentity()).ok());
// b -> a se tao vong a->b->a; moi lookup sau do se treo.
EXPECT_FALSE(tree.SetStatic(b, a, TransformIdentity()).ok());
}
TEST(TransformTree, NoiSuyKhopGiaTriTinhTay) {
FrameId map, odom, bf, bl, laser;
TransformTree tree(10.0, 512);
MakeRobotTree(&tree, &map, &odom, &bf, &bl, &laser);
const UnixTime t0 = UnixTime::fromSec(1000.0);
const UnixTime t1 = UnixTime::fromSec(1001.0);
ASSERT_TRUE(tree.SetTransform(odom, bf, t0, MakeTf(0.0, 0.0, 0.0, 0.0)));
ASSERT_TRUE(tree.SetTransform(odom, bf, t1, MakeTf(2.0, 4.0, 0.0, kPi / 2.0)));
Transform out;
std::string err;
// Giua chung: LERP tinh tien -> (1, 2); SLERP quay -> 45 do.
ASSERT_TRUE(tree.Lookup(odom, bf, UnixTime::fromSec(1000.5), &out, &err)) << err;
EXPECT_NEAR(out.translation.x, 1.0, 1e-9);
EXPECT_NEAR(out.translation.y, 2.0, 1e-9);
EXPECT_NEAR(YawFromQuaternion(out.rotation), kPi / 4.0, 1e-9);
// 1/4 duong: (0.5, 1.0), 22.5 do.
ASSERT_TRUE(tree.Lookup(odom, bf, UnixTime::fromSec(1000.25), &out, &err)) << err;
EXPECT_NEAR(out.translation.x, 0.5, 1e-9);
EXPECT_NEAR(out.translation.y, 1.0, 1e-9);
EXPECT_NEAR(YawFromQuaternion(out.rotation), kPi / 8.0, 1e-9);
}
TEST(TransformTree, TuChoiNgoaiSuyVuotGioiHan) {
FrameId map, odom, bf, bl, laser;
TransformTree tree(10.0, 512);
MakeRobotTree(&tree, &map, &odom, &bf, &bl, &laser);
tree.SetExtrapolationLimit(0.1);
const UnixTime t0 = UnixTime::fromSec(1000.0);
ASSERT_TRUE(tree.SetTransform(odom, bf, t0, MakeTf(1.0, 0.0, 0.0, 0.0)));
Transform out;
std::string err;
// Trong gioi han: chap nhan, dung mau moi nhat.
EXPECT_TRUE(tree.Lookup(odom, bf, UnixTime::fromSec(1000.05), &out, &err));
// Vuot gioi han: TU CHOI va dien err. tf2 nem exception o day va rat nhieu
// code goi bat roi bo qua im lang.
err.clear();
EXPECT_FALSE(tree.Lookup(odom, bf, UnixTime::fromSec(1000.5), &out, &err));
EXPECT_FALSE(err.empty());
}
TEST(TransformTree, TuChoiStampLui) {
FrameId map, odom, bf, bl, laser;
TransformTree tree(10.0, 512);
MakeRobotTree(&tree, &map, &odom, &bf, &bl, &laser);
ASSERT_TRUE(tree.SetTransform(odom, bf, UnixTime::fromSec(1001.0),
TransformIdentity()));
// Stamp lui la dau hieu hai nguoi cung ghi mot canh, hoac ban ghi bi xao
// tron thu tu. Noi suy tren ring khong con don dieu -> moi lookup sau sai.
EXPECT_FALSE(tree.SetTransform(odom, bf, UnixTime::fromSec(1000.0),
TransformIdentity()));
}
TEST(TransformTree, TuChoiGhiDongLenCanhTinh) {
FrameId map, odom, bf, bl, laser;
TransformTree tree(10.0, 512);
MakeRobotTree(&tree, &map, &odom, &bf, &bl, &laser);
// base_link -> laser_link da la canh tinh.
EXPECT_FALSE(tree.SetTransform(bl, laser, UnixTime::fromSec(1.0),
TransformIdentity()));
}
TEST(TransformTree, GhepQuaNhieuCanh) {
FrameId map, odom, bf, bl, laser;
TransformTree tree(10.0, 512);
MakeRobotTree(&tree, &map, &odom, &bf, &bl, &laser);
const UnixTime t = UnixTime::fromSec(1000.0);
tree.SetStatic(bf, bl, MakeTf(0.0, 0.0, 0.075, 0.0)); // base_joint z=0.075
ASSERT_TRUE(tree.SetTransform(map, odom, t, MakeTf(10.0, 0.0, 0.0, 0.0)));
ASSERT_TRUE(tree.SetTransform(odom, bf, t, MakeTf(1.0, 2.0, 0.0, 0.0)));
Transform out;
std::string err;
// map <- laser: 10 + 1 + 0.24 = 11.24 theo x; z = 0.075 + 0.125 = 0.2
ASSERT_TRUE(tree.Lookup(map, laser, t, &out, &err)) << err;
EXPECT_NEAR(out.translation.x, 11.24, 1e-9);
EXPECT_NEAR(out.translation.y, 2.0, 1e-9);
EXPECT_NEAR(out.translation.z, 0.2, 1e-9);
}
TEST(TransformTree, LookupChinhNoLaIdentity) {
TransformTree tree;
const FrameId a = tree.Resolve("a");
Transform out;
ASSERT_TRUE(tree.Lookup(a, a, kTimeZero, &out, nullptr));
EXPECT_NEAR(out.translation.x, 0.0, 1e-15);
EXPECT_NEAR(out.rotation.w, 1.0, 1e-15);
}
TEST(TransformTree, FrameKhongNoiThiThatBai) {
TransformTree tree;
const FrameId a = tree.Resolve("a");
const FrameId b = tree.Resolve("b");
Transform out;
std::string err;
EXPECT_FALSE(tree.Lookup(a, b, kTimeZero, &out, &err));
EXPECT_FALSE(err.empty());
}
TEST(TransformTree, LookupNguocChieu) {
FrameId map, odom, bf, bl, laser;
TransformTree tree(10.0, 512);
MakeRobotTree(&tree, &map, &odom, &bf, &bl, &laser);
Transform fwd, rev;
ASSERT_TRUE(tree.LookupLatest(bl, laser, &fwd, nullptr));
ASSERT_TRUE(tree.LookupLatest(laser, bl, &rev, nullptr));
const Transform id = TransformCompose(fwd, rev);
EXPECT_NEAR(id.translation.x, 0.0, 1e-12);
EXPECT_NEAR(id.translation.z, 0.0, 1e-12);
}
TEST(TransformTree, EdgeStatusesBaoCaoTinhVaDong) {
FrameId map, odom, bf, bl, laser;
TransformTree tree(10.0, 512);
MakeRobotTree(&tree, &map, &odom, &bf, &bl, &laser);
tree.SetTransform(odom, bf, UnixTime::fromSec(1.0), TransformIdentity());
const auto st = tree.EdgeStatuses();
ASSERT_EQ(st.size(), 2u);
bool found_static = false, found_dynamic = false;
for (const auto& e : st) {
if (e.child == kLaserFrame) { EXPECT_TRUE(e.is_static); found_static = true; }
if (e.child == kBaseFootprintFrame) {
EXPECT_FALSE(e.is_static);
EXPECT_EQ(e.samples, 1u);
found_dynamic = true;
}
}
EXPECT_TRUE(found_static);
EXPECT_TRUE(found_dynamic);
}

96
test/test_unix_time.cc Normal file
View File

@@ -0,0 +1,96 @@
#include "vslam/unix_time.h"
#include <gtest/gtest.h>
#include <limits>
using vslam::Duration;
using vslam::UnixTime;
// --- Ba sua loi so voi xloc_cpp/include/unix_time.h ------------------------
TEST(UnixTime, FromSecAmKhongTran) {
// Ban goc: static_cast<uint32_t>(std::floor(-1.5)) = 4294967295 -> tran
// im lang, va moi phep so sanh thoi gian sau do deu sai.
EXPECT_TRUE(UnixTime::fromSec(-1.5).isZero());
EXPECT_TRUE(UnixTime::fromSec(-0.001).isZero());
EXPECT_TRUE(UnixTime::fromSec(0.0).isZero());
EXPECT_TRUE(UnixTime::fromSec(std::numeric_limits<double>::quiet_NaN()).isZero());
}
TEST(UnixTime, FromSecCheckedBaoLoi) {
UnixTime t;
EXPECT_FALSE(UnixTime::fromSecChecked(-1.0, &t));
EXPECT_TRUE(UnixTime::fromSecChecked(1.5, &t));
EXPECT_EQ(t.sec, 1u);
EXPECT_EQ(t.nsec, 500000000u);
}
TEST(UnixTime, SoHocBangInt64) {
// Hai stamp cach nhau 100 s o gia tri unix epoch that (~1.7e9). Ban goc ep
// sang int32_t -- van chay o day nhung sat gioi han va se vo nam 2038.
const UnixTime a = UnixTime::fromNSec(1737000000LL * 1000000000LL);
const UnixTime b = UnixTime::fromNSec(1737000100LL * 1000000000LL);
EXPECT_NEAR((b - a).toSec(), 100.0, 1e-9);
EXPECT_NEAR(vslam::SecondsBetween(b, a), 100.0, 1e-9);
EXPECT_NEAR(vslam::SecondsBetween(a, b), -100.0, 1e-9);
}
TEST(UnixTime, TimeMaxLaConstexprKhongPhaiBanSaoMoiTU) {
// Chi can compile duoc la du -- kTimeMax phai la inline constexpr.
static_assert(vslam::kTimeMax.sec == std::numeric_limits<uint32_t>::max(), "");
static_assert(vslam::kTimeZero.isZero(), "");
EXPECT_GT(vslam::kTimeMax, UnixTime::fromSec(1e9));
}
// --- Hanh vi co ban --------------------------------------------------------
TEST(UnixTime, RoundTripNSec) {
const int64_t ns = 1737000123LL * 1000000000LL + 456789012LL;
const UnixTime t = UnixTime::fromNSec(ns);
EXPECT_EQ(t.toNSec(), ns);
EXPECT_EQ(t.sec, 1737000123u);
EXPECT_EQ(t.nsec, 456789012u);
}
TEST(UnixTime, ToStringKhongMatDoChinhXac) {
// In qua double se mat cac chu so cuoi: double chi co 53 bit mantissa.
const UnixTime t = UnixTime::fromNSec(1737000123LL * 1000000000LL + 456789012LL);
EXPECT_EQ(t.toString(), "1737000123.456789012");
}
TEST(UnixTime, SoSanh) {
const UnixTime a(10, 500);
const UnixTime b(10, 600);
const UnixTime c(11, 0);
EXPECT_LT(a, b);
EXPECT_LT(b, c);
EXPECT_NE(a, b);
EXPECT_EQ(a, UnixTime(10, 500));
EXPECT_GE(c, a);
}
TEST(DurationTest, ChuanHoaNsecAm) {
const Duration d(1, -500000000);
EXPECT_EQ(d.sec, 0);
EXPECT_EQ(d.nsec, 500000000);
EXPECT_NEAR(d.toSec(), 0.5, 1e-9);
}
TEST(DurationTest, AmVaCongTru) {
const Duration d = Duration::fromSec(-2.25);
EXPECT_NEAR(d.toSec(), -2.25, 1e-9);
EXPECT_NEAR((-d).toSec(), 2.25, 1e-9);
const Duration a = Duration::fromSec(1.75);
EXPECT_NEAR((a + d).toSec(), -0.5, 1e-9);
EXPECT_NEAR((a - d).toSec(), 4.0, 1e-9);
}
TEST(UnixTime, CongTruDuration) {
const UnixTime t = UnixTime::fromSec(100.0);
EXPECT_NEAR((t + Duration::fromSec(1.5)).toSec(), 101.5, 1e-9);
EXPECT_NEAR((t - Duration::fromSec(1.5)).toSec(), 98.5, 1e-9);
// Tru qua 0 bi kep, khong quay vong.
EXPECT_TRUE((t - Duration::fromSec(1000.0)).isZero());
}

221
test/test_web_auth.cc Normal file
View File

@@ -0,0 +1,221 @@
// Test tich hop cho lop xac thuc cua WebServer.
//
// Vi sao khong phai unit test: lo hong ma file nay giu khong nam trong mot ham
// nao ca, no nam o CHO GIAP giua lop xac thuc va handler. Ban dau
// CommandNeedsAuth() mac dinh coi body khong parse duoc la "bat e-stop" nen bo
// qua xac thuc, trong khi handler doc cung body do theo cach khac va hieu la
// "go e-stop". Khong unit test nao cua hai phia bat duoc dieu do.
//
// Quy tac duoc giu o day: KHI KHONG CHAC Y DINH LA GI THI DOI TOKEN.
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <gtest/gtest.h>
#include <atomic>
#include <memory>
#include <string>
#include "vslam/json_parse.h"
#include "vslam/web_server.h"
namespace {
namespace beast = boost::beast;
namespace http = beast::http;
namespace asio = boost::asio;
using tcp = asio::ip::tcp;
constexpr const char* kToken = "bimat123";
// Gui mot POST va tra ve ma trang thai HTTP.
int Post(uint16_t port, const std::string& target, const std::string& body,
const std::string& token) {
asio::io_context ioc;
tcp::resolver resolver(ioc);
beast::tcp_stream stream(ioc);
stream.connect(resolver.resolve("127.0.0.1", std::to_string(port)));
http::request<http::string_body> req(http::verb::post, target, 11);
req.set(http::field::host, "127.0.0.1");
req.set(http::field::content_type, "application/json");
if (!token.empty()) req.set("X-Auth-Token", token);
req.body() = body;
req.prepare_payload();
http::write(stream, req);
beast::flat_buffer buf;
http::response<http::string_body> res;
http::read(stream, buf, res);
beast::error_code ec;
stream.socket().shutdown(tcp::socket::shutdown_both, ec);
return static_cast<int>(res.result_int());
}
class WebAuthTest : public ::testing::Test {
protected:
void SetUp() override {
vslam::WebConfig cfg;
cfg.bind_address = "127.0.0.1";
cfg.port = 0; // cong tuy y, de test chay song song duoc
cfg.auth_token = kToken;
server_ = std::make_unique<vslam::WebServer>(
cfg,
[this](const std::string& cmd, const std::string& body) -> vslam::StatusResponse {
if (cmd == "safety/estop") {
// Handler dung CHINH ham parse ma lop xac thuc dung.
bool on = false;
if (!vslam::JsonGetBool(body, "on", &on)) {
return vslam::StatusResponse::Error(vslam::StatusCode::kInvalidArgument,
"can truong bool on");
}
estop_.store(on);
return vslam::StatusResponse::Ok();
}
if (cmd == "safety/reset") {
estop_.store(false);
return vslam::StatusResponse::Ok();
}
return vslam::StatusResponse::Error(vslam::StatusCode::kNotFound, "la");
},
[](double, double) {});
ASSERT_TRUE(server_->Start().ok());
port_ = server_->port();
ASSERT_NE(port_, 0);
}
void TearDown() override {
if (server_) server_->Stop();
}
std::unique_ptr<vslam::WebServer> server_;
std::atomic<bool> estop_{false};
uint16_t port_ = 0;
};
} // namespace
TEST_F(WebAuthTest, BatEstopKhongCanToken) {
// Fail-safe: bat ky ai trong LAN cung phai dung duoc robot.
EXPECT_EQ(Post(port_, "/api/safety/estop", R"({"on":true})", ""), 200);
EXPECT_TRUE(estop_.load());
}
TEST_F(WebAuthTest, GoEstopBatBuocCoToken) {
// Ai cung e-stop duoc thi chap nhan. Ai cung GO duoc e-stop cua nguoi khac
// thi khong.
Post(port_, "/api/safety/estop", R"({"on":true})", "");
ASSERT_TRUE(estop_.load());
EXPECT_EQ(Post(port_, "/api/safety/estop", R"({"on":false})", ""), 401);
EXPECT_TRUE(estop_.load()) << "e-stop bi go ma khong co token";
EXPECT_EQ(Post(port_, "/api/safety/estop", R"({"on":false})", kToken), 200);
EXPECT_FALSE(estop_.load());
}
TEST_F(WebAuthTest, TokenSaiBiTuChoi) {
Post(port_, "/api/safety/estop", R"({"on":true})", "");
EXPECT_EQ(Post(port_, "/api/safety/estop", R"({"on":false})", "sai"), 401);
EXPECT_TRUE(estop_.load());
}
TEST_F(WebAuthTest, BodyHongPhaiFailClosed) {
// DAY LA TEST HOI QUY CHO LO HONG DA TUNG CO.
// Body khong parse duoc -> khong biet y dinh la gi -> PHAI doi token.
// Ban co lo hong tra 200 o day va con go duoc e-stop that su.
Post(port_, "/api/safety/estop", R"({"on":true})", "");
ASSERT_TRUE(estop_.load());
for (const char* bad : {R"({"on":xxx})", R"({"on":)", "{}", "", "khong phai json",
R"({"onn":false})"}) {
EXPECT_EQ(Post(port_, "/api/safety/estop", bad, ""), 401)
<< "body hong duoc cho qua ma khong can token: " << bad;
EXPECT_TRUE(estop_.load()) << "e-stop bi go boi body hong: " << bad;
}
}
TEST_F(WebAuthTest, BodyHongCoTokenThiLa400KhongPhai401) {
// Co token nhung body vo nghia: loi cua nguoi goi, khong phai loi xac thuc.
// Phan biet 400 va 401 la de nguoi debug biet minh sai o dau.
EXPECT_EQ(Post(port_, "/api/safety/estop", R"({"on":xxx})", kToken), 400);
}
TEST_F(WebAuthTest, ResetLuonDoiToken) {
EXPECT_EQ(Post(port_, "/api/safety/reset", "{}", ""), 401);
EXPECT_EQ(Post(port_, "/api/safety/reset", "{}", kToken), 200);
}
TEST_F(WebAuthTest, LenhLaTra400) {
EXPECT_EQ(Post(port_, "/api/khong/ton/tai", "{}", kToken), 400);
}
TEST_F(WebAuthTest, KhongCoTokenCauHinhThiMoiThuDuocPhep) {
// Khong dat auth_token = che do mo. Server da log WARN to luc khoi dong.
vslam::WebConfig cfg;
cfg.bind_address = "127.0.0.1";
cfg.port = 0;
std::atomic<bool> es{false};
vslam::WebServer open_server(
cfg,
[&es](const std::string& cmd, const std::string& body) -> vslam::StatusResponse {
if (cmd == "safety/estop") {
bool on = false;
if (!vslam::JsonGetBool(body, "on", &on)) {
return vslam::StatusResponse::Error(vslam::StatusCode::kInvalidArgument, "x");
}
es.store(on);
}
return vslam::StatusResponse::Ok();
},
[](double, double) {});
ASSERT_TRUE(open_server.Start().ok());
EXPECT_EQ(Post(open_server.port(), "/api/safety/estop", R"({"on":false})", ""), 200);
open_server.Stop();
}
// --- Parse: cac truong hop bien ma lop xac thuc dua vao -------------------
TEST(JsonParse, BoolDungVaSai) {
bool v = false;
EXPECT_TRUE(vslam::JsonGetBool(R"({"on":true})", "on", &v));
EXPECT_TRUE(v);
EXPECT_TRUE(vslam::JsonGetBool(R"({"on": false})", "on", &v));
EXPECT_FALSE(v);
EXPECT_FALSE(vslam::JsonGetBool(R"({"on":xxx})", "on", &v));
EXPECT_FALSE(vslam::JsonGetBool(R"({"on":})", "on", &v));
EXPECT_FALSE(vslam::JsonGetBool("{}", "on", &v));
EXPECT_FALSE(vslam::JsonGetBool("", "on", &v));
// Ten khoa gan giong nhung khong dung.
EXPECT_FALSE(vslam::JsonGetBool(R"({"onn":true})", "on", &v));
// Escape lam hong cau truc: day chinh la body da lam lo lo hong ban dau.
EXPECT_FALSE(vslam::JsonGetBool(R"({\"on\":false})", "on", &v));
}
TEST(JsonParse, Number) {
double d = 0.0;
EXPECT_TRUE(vslam::JsonGetNumber(R"({"x":1.5})", "x", &d));
EXPECT_DOUBLE_EQ(d, 1.5);
EXPECT_TRUE(vslam::JsonGetNumber(R"({"x": -2})", "x", &d));
EXPECT_DOUBLE_EQ(d, -2.0);
EXPECT_FALSE(vslam::JsonGetNumber(R"({"x":abc})", "x", &d));
EXPECT_FALSE(vslam::JsonGetNumber("{}", "x", &d));
}
TEST(JsonParse, String) {
std::string s;
EXPECT_TRUE(vslam::JsonGetString(R"({"t":"cmd"})", "t", &s));
EXPECT_EQ(s, "cmd");
EXPECT_TRUE(vslam::JsonGetString(R"({"t":"a\"b"})", "t", &s));
EXPECT_EQ(s, "a\"b");
EXPECT_FALSE(vslam::JsonGetString(R"({"t":"khong dong)", "t", &s));
EXPECT_FALSE(vslam::JsonGetString(R"({"t":5})", "t", &s));
}

339
test/test_wheel_odometry.cc Normal file
View File

@@ -0,0 +1,339 @@
#include "vslam/wheel_odometry.h"
#include <gtest/gtest.h>
#include <cmath>
#include "vslam/geometry.h"
using namespace vslam;
namespace {
constexpr double kPi = 3.14159265358979323846;
WheelOdometryConfig Cfg() {
WheelOdometryConfig c;
c.wheel_radius = 0.075;
c.wheel_separation = 0.36;
return c;
}
// Quay banh de robot di THANG `dist` met.
double WheelRadForDistance(double dist, double radius) { return dist / radius; }
} // namespace
TEST(WheelOdometry, MauDauTienKhongSinhOdometry) {
WheelOdometry wo(Cfg());
Odometry o;
EXPECT_FALSE(wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o));
}
TEST(WheelOdometry, DiThangThiChiTangX) {
WheelOdometry wo(Cfg());
Odometry o;
const double r = 0.075;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
double pos = 0.0;
for (int i = 1; i <= 50; ++i) {
pos += WheelRadForDistance(0.02, r); // 2 cm moi buoc
ASSERT_TRUE(wo.Update(UnixTime::fromSec(1.0 + i * 0.02), pos, pos, &o));
}
const Pose2D p = wo.pose();
EXPECT_NEAR(p.x, 1.0, 1e-9) << "50 x 2 cm = 1 m";
EXPECT_NEAR(p.y, 0.0, 1e-12);
EXPECT_NEAR(p.theta, 0.0, 1e-12);
EXPECT_NEAR(wo.stats().total_distance, 1.0, 1e-9);
}
TEST(WheelOdometry, QuayTaiChoThiChiDoiYaw) {
WheelOdometry wo(Cfg());
Odometry o;
const double r = 0.075, sep = 0.36;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
// Hai banh nguoc chieu, cung do lon -> quay tai cho.
// d_theta = (d_r - d_l) / sep; muon quay pi/2 thi d_r = -d_l = sep*pi/4.
const double d_wheel = sep * kPi / 4.0;
const double rad = d_wheel / r;
const int n = 50;
for (int i = 1; i <= n; ++i) {
const double f = static_cast<double>(i) / n;
ASSERT_TRUE(wo.Update(UnixTime::fromSec(1.0 + i * 0.02), -rad * f, rad * f, &o));
}
const Pose2D p = wo.pose();
EXPECT_NEAR(p.x, 0.0, 1e-9);
EXPECT_NEAR(p.y, 0.0, 1e-9);
EXPECT_NEAR(p.theta, kPi / 2.0, 1e-9);
}
TEST(WheelOdometry, RK2ChinhXacHonEulerTrenCungTron) {
// Tich phan RK2 dung goc GIUA doan. Tren mot cung tron, Euler (goc dau
// doan) luon lech VE MOT PHIA va sai so tich luy theo mot chieu.
WheelOdometry wo(Cfg());
Odometry o;
const double r = 0.075, sep = 0.36;
const double R = 1.0; // ban kinh cung tron 1 m
const double arc = kPi / 2.0; // quay 90 do
const int n = 100;
const double d_center = R * arc / n;
const double d_theta = arc / n;
const double d_l = d_center - d_theta * sep / 2.0;
const double d_r = d_center + d_theta * sep / 2.0;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
double pl = 0.0, pr = 0.0;
for (int i = 1; i <= n; ++i) {
pl += d_l / r;
pr += d_r / r;
ASSERT_TRUE(wo.Update(UnixTime::fromSec(1.0 + i * 0.02), pl, pr, &o));
}
// Cung tron ban kinh 1 quay 90 do tu goc (0,0,0): tam o (0, 1), diem cuoi
// o (1, 1), huong pi/2.
const Pose2D p = wo.pose();
EXPECT_NEAR(p.theta, arc, 1e-9);
EXPECT_NEAR(p.x, 1.0, 2e-4) << "RK2 phai bam sat nghiem giai tich";
EXPECT_NEAR(p.y, 1.0, 2e-4);
}
TEST(WheelOdometry, DtAmThiResetChuKhongTichPhanLui) {
// Nhay lui thoi gian: reset mo phong hoac phat lai ban ghi. Tich phan mot
// dt am se day pose GIAT LUI, va EKF phia sau khong co cach nao biet.
WheelOdometry wo(Cfg());
Odometry o;
wo.Update(UnixTime::fromSec(10.0), 0.0, 0.0, &o);
wo.Update(UnixTime::fromSec(10.02), 1.0, 1.0, &o);
const Pose2D before = wo.pose();
EXPECT_FALSE(wo.Update(UnixTime::fromSec(5.0), 2.0, 2.0, &o));
EXPECT_EQ(wo.stats().time_resets, 1u);
const Pose2D after = wo.pose();
EXPECT_NEAR(after.x, before.x, 1e-12) << "pose khong duoc doi khi dt <= 0";
}
// --- Phat hien truot -------------------------------------------------------
TEST(WheelOdometry, KhongTruotThiSlipMetricGanKhong) {
WheelOdometry wo(Cfg());
Odometry o;
const double r = 0.075, sep = 0.36;
const double omega = 0.5; // rad/s
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
double pl = 0.0, pr = 0.0;
for (int i = 1; i <= 20; ++i) {
const double t = 1.0 + i * 0.02;
const double d_theta = omega * 0.02;
pl += (-d_theta * sep / 2.0) / r;
pr += (d_theta * sep / 2.0) / r;
wo.FeedGyroZ(UnixTime::fromSec(t), omega); // gyro DONG Y voi encoder
ASSERT_TRUE(wo.Update(UnixTime::fromSec(t), pl, pr, &o));
}
EXPECT_LT(wo.slip_metric(), 1e-9);
EXPECT_FALSE(wo.slipping());
}
TEST(WheelOdometry, TruotThiSlipMetricBangDoLechThat) {
// slip_metric CHINH LA |omega_encoder - gyro_z|, do duoc tung chu ky.
WheelOdometry wo(Cfg());
Odometry o;
const double r = 0.075, sep = 0.36;
const double omega_enc = 2.0; // banh bao quay 2 rad/s
const double omega_gyro = 0.5; // gyro noi chi 0.5 -> dang truot
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
double pl = 0.0, pr = 0.0;
for (int i = 1; i <= 10; ++i) {
const double t = 1.0 + i * 0.02;
const double d_theta = omega_enc * 0.02;
pl += (-d_theta * sep / 2.0) / r;
pr += (d_theta * sep / 2.0) / r;
wo.FeedGyroZ(UnixTime::fromSec(t), omega_gyro);
ASSERT_TRUE(wo.Update(UnixTime::fromSec(t), pl, pr, &o));
}
EXPECT_NEAR(wo.slip_metric(), 1.5, 1e-9);
EXPECT_TRUE(wo.slipping());
EXPECT_GT(wo.stats().slip_events, 0u);
}
TEST(WheelOdometry, TruotThiNangCovariancePose) {
WheelOdometryConfig c = Cfg();
c.slip_cov_multiplier = 100.0;
auto run = [&](double gyro) {
WheelOdometry wo(c);
Odometry o;
const double r = 0.075;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
double pos = 0.0;
for (int i = 1; i <= 10; ++i) {
const double t = 1.0 + i * 0.02;
pos += WheelRadForDistance(0.02, r);
wo.FeedGyroZ(UnixTime::fromSec(t), gyro);
wo.Update(UnixTime::fromSec(t), pos, pos, &o);
}
return o;
};
const Odometry clean = run(0.0); // di thang, gyro dong y
const Odometry slip = run(5.0); // gyro noi dang quay manh -> truot
EXPECT_NEAR(slip.pose.covariance[0] / clean.pose.covariance[0], 100.0, 1e-6)
<< "truot phai nang covariance dung bang slip_cov_multiplier";
}
// ===========================================================================
// YAW-RATE COVARIANCE -- BAI KIEM QUAN TRONG NHAT CUA FILE
//
// Cach cu (cov_yaw/dt^2 voi he so co dinh) THIEU ~2 BAC. Da do tren robot
// that khi xoay tai cho:
// sai so that : omega encoder -3.635 vs gyro -1.377 = 2.26 rad/s
// sigma khai bao: 0.2 rad/s
// EKF nhan mot diem 11-sigma ma van tin -> yaw troi -> global_scan_init khop
// ra huong sai 40.8 do sau khi xoay 301 do.
// ===========================================================================
TEST(WheelOdometry, YawRateSigmaBangSaiSoDaDo) {
WheelOdometry wo(Cfg());
Odometry o;
const double r = 0.075, sep = 0.36;
// Tai lap dung con so da do: encoder -3.635, gyro -1.377.
const double omega_enc = -3.635;
const double omega_gyro = -1.377;
const double dt = 0.02;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
double pl = 0.0, pr = 0.0;
for (int i = 1; i <= 5; ++i) {
const double t = 1.0 + i * dt;
const double d_theta = omega_enc * dt;
pl += (-d_theta * sep / 2.0) / r;
pr += (d_theta * sep / 2.0) / r;
wo.FeedGyroZ(UnixTime::fromSec(t), omega_gyro);
ASSERT_TRUE(wo.Update(UnixTime::fromSec(t), pl, pr, &o));
}
const double expected_slip = std::fabs(omega_enc - omega_gyro); // 2.258
EXPECT_NEAR(wo.slip_metric(), expected_slip, 1e-6);
const double sigma_wr = std::sqrt(o.twist.covariance[35]);
EXPECT_NEAR(sigma_wr, expected_slip, 1e-6)
<< "sigma yaw-rate PHAI bang sai so da do, khong phai he so doan truoc";
// Cach cu cho ~0.2 rad/s. Cach moi phai lon hon HANG CHUC lan.
EXPECT_GT(sigma_wr, 2.0);
EXPECT_GT(sigma_wr / 0.2, 10.0) << "phai sua duoc do lech 2 bac cua ban cu";
}
TEST(WheelOdometry, KhongCoGyroThiSigmaKhongDuocBangKhong) {
// San khi KHONG co gyro: slip_metric = 0, va neu dung thang thi sigma = 0
// -> EKF tin banh xe TUYET DOI, te hon ca truoc khi sua.
WheelOdometryConfig c = Cfg();
c.yaw_rate_sigma_no_imu = 0.50;
WheelOdometry wo(c);
Odometry o;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
double pos = 0.0;
for (int i = 1; i <= 5; ++i) {
pos += WheelRadForDistance(0.02, 0.075);
ASSERT_TRUE(wo.Update(UnixTime::fromSec(1.0 + i * 0.02), pos, pos, &o));
}
EXPECT_NEAR(std::sqrt(o.twist.covariance[35]), 0.50, 1e-9);
EXPECT_GT(wo.stats().no_imu_updates, 0u);
}
TEST(WheelOdometry, CoGyroNhungKhongTruotVanCoSanNguong) {
// slip_metric = 0 khi khop hoan hao. Dung thang thi sigma = 0 -> EKF tin
// tuyet doi. yaw_rate_sigma_floor chan dieu do.
WheelOdometryConfig c = Cfg();
c.yaw_rate_sigma_floor = 0.02;
WheelOdometry wo(c);
Odometry o;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
double pos = 0.0;
for (int i = 1; i <= 5; ++i) {
const double t = 1.0 + i * 0.02;
pos += WheelRadForDistance(0.02, 0.075);
wo.FeedGyroZ(UnixTime::fromSec(t), 0.0);
ASSERT_TRUE(wo.Update(UnixTime::fromSec(t), pos, pos, &o));
}
EXPECT_NEAR(std::sqrt(o.twist.covariance[35]), 0.02, 1e-9);
}
TEST(WheelOdometry, GyroCuThiCoiNhuKhongCo) {
WheelOdometryConfig c = Cfg();
c.imu_timeout = 0.5;
WheelOdometry wo(c);
Odometry o;
wo.FeedGyroZ(UnixTime::fromSec(1.0), 0.0);
wo.Update(UnixTime::fromSec(10.0), 0.0, 0.0, &o); // gyro cu 9 giay
double pos = WheelRadForDistance(0.02, 0.075);
ASSERT_TRUE(wo.Update(UnixTime::fromSec(10.02), pos, pos, &o));
EXPECT_NEAR(std::sqrt(o.twist.covariance[35]), c.yaw_rate_sigma_no_imu, 1e-9);
}
TEST(WheelOdometry, ZRollPitchDanhDauKhongQuanSatDuoc) {
WheelOdometry wo(Cfg());
Odometry o;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
ASSERT_TRUE(wo.Update(UnixTime::fromSec(1.02), 0.1, 0.1, &o));
EXPECT_GE(o.pose.covariance[14], 1e5) << "z";
EXPECT_GE(o.pose.covariance[21], 1e5) << "roll -> IMU lo";
EXPECT_GE(o.pose.covariance[28], 1e5) << "pitch -> IMU lo";
}
TEST(WheelOdometry, CovarianceTyLeVoiQuangDuongKhongPhaiThoiGian) {
// Robot dung yen khong duoc tich them sai so, du dung bao lau.
WheelOdometry wo(Cfg());
Odometry o;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
ASSERT_TRUE(wo.Update(UnixTime::fromSec(1.02), 0.0, 0.0, &o));
const double cov_still = o.pose.covariance[0];
ASSERT_TRUE(wo.Update(UnixTime::fromSec(11.02), 0.0, 0.0, &o));
EXPECT_NEAR(o.pose.covariance[0], cov_still, 1e-15)
<< "dung yen 10 giay khong duoc lam covariance tang";
const double pos = WheelRadForDistance(0.5, 0.075);
ASSERT_TRUE(wo.Update(UnixTime::fromSec(11.04), pos, pos, &o));
EXPECT_GT(o.pose.covariance[0], cov_still * 100.0) << "di 0.5 m thi phai tang";
}
TEST(WheelOdometry, DeltaCuonVeGiuaHaiDauVanDung) {
// Chuan hoa DELTA de an toan voi ca hai kieu bao cao vi tri: tich luy khong
// gioi han, hoac cuon ve [-pi, pi].
WheelOdometry wo(Cfg());
Odometry o;
wo.Update(UnixTime::fromSec(1.0), kPi - 0.01, kPi - 0.01, &o);
// Vi tri cuon qua bien: pi-0.01 -> -pi+0.01, thuc te chi quay 0.02 rad.
ASSERT_TRUE(wo.Update(UnixTime::fromSec(1.02), -kPi + 0.01, -kPi + 0.01, &o));
EXPECT_NEAR(wo.pose().x, 0.02 * 0.075, 1e-9)
<< "cuon bien bi hieu thanh mot vong quay nguoc";
}
TEST(WheelOdometry, SetPoseVaReset) {
WheelOdometry wo(Cfg());
Odometry o;
wo.Update(UnixTime::fromSec(1.0), 0.0, 0.0, &o);
wo.Update(UnixTime::fromSec(1.02), 1.0, 1.0, &o);
wo.SetPose(Pose2D{5.0, -3.0, 1.2});
EXPECT_NEAR(wo.pose().x, 5.0, 1e-12);
EXPECT_NEAR(wo.pose().theta, 1.2, 1e-12);
wo.Reset();
EXPECT_NEAR(wo.pose().x, 0.0, 1e-12);
EXPECT_EQ(wo.stats().updates, 0u);
}

View File

@@ -0,0 +1,22 @@
// Khong mot dong nao cua vslam. Chi std::mutex + condition_variable, dung
// khuon mau y het Channel<T>: mot luong cho co vi ngu, mot luong dat co.
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <thread>
std::mutex mu;
std::condition_variable cv;
bool flag = false;
int main() {
{ std::lock_guard<std::mutex> lk(mu); } // giong MakeReader: khoa roi tha
std::thread th([]{
std::unique_lock<std::mutex> lk(mu);
cv.wait_for(lk, std::chrono::seconds(5), []{ return flag; });
});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
{ std::lock_guard<std::mutex> lk(mu); flag = true; } // giong Close
cv.notify_all();
th.join();
std::puts("xong");
return 0;
}

View File

@@ -0,0 +1,18 @@
# ThreadSanitizer: bo qua thu vien BEN THU BA khong duoc build kem TSan.
#
# Chi liet ke nhung thu vien THUC SU bao, do duoc tu mot lan chay 40 giay
# (1737 canh bao, KHONG cai nao tu code cua ta). Khong doan truoc: PCL,
# OpenCV, VTK, g2o co trong duong lien ket nhung khong bao gi, nen khong co
# mat o day.
#
# ⚠️ `called_from_lib:` phai khop DUNG MOT thu vien. Mot tien to khop nhieu
# cai (vd `libpcl_`) lam TSan TU THOAT ngay luc khoi dong voi thong bao
# "matched against 2 libraries" -- khong phai canh bao, la loi chet nguoi.
#
# ⚠️ Loc o muc THU VIEN, KHONG tat han. Quy tac song con
# "luong safety KHONG chia se mutex nao voi luong slam"
# van duoc kiem day du: ca hai luong deu nam trong vslam_node va libvslam_*.
called_from_lib:librtabmap_core.so.0.21
called_from_lib:librtabmap_utilite.so.0.21
called_from_lib:libgdal.so.26
called_from_lib:libOpenNI2.so.0

View File

@@ -0,0 +1,147 @@
// Hai hinh robot (uoc luong + ground truth) va cao do cua chung.
//
// ================== VI SAO CAN BAI KIEM NAY ==================
// Nguoi van hanh bao "robot co mot nhan ban o canh" trong khi sai so uoc luong
// do duoc chi 9 mm. Nguyen nhan la 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, va o goc camera nghieng
// chenh lech do chieu ra thanh khoang cach NGANG nhin thay duoc.
//
// Khong mot chi so nao doi. Ca hai hinh van duoc ve, van cap nhat, van dung
// mau. Chi la chung o hai cao do.
const fs = require('fs');
const path = require('path');
const vm = require('vm');
class V3 {
constructor(x, y, z) { this.x = x; this.y = y; this.z = z; }
copy(o) { this.x = o.x; this.y = o.y; this.z = o.z; return this; }
set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }
}
const node = () => ({ position: new V3(0, 0, 0), rotation: { x: 0, y: 0, z: 0 },
userData: {} });
class Grp {
constructor() { Object.assign(this, node()); this.children = []; }
add(c) { this.children.push(c); }
remove(c) { this.children = this.children.filter((x) => x !== c); }
traverse(f) { f(this); this.children.forEach((c) => (c.traverse ? c.traverse(f) : f(c))); }
}
const leaf = (extra) => class {
constructor(g, m) { Object.assign(this, node()); this.geometry = g; this.material = m;
Object.assign(this, extra || {}); }
};
const mat = () => class {
constructor(o) { Object.assign(this, o); this.color = { set() {} }; }
clone() { const c = Object.create(Object.getPrototypeOf(this));
Object.assign(c, this); c.color = { set() {} }; return c; }
dispose() {}
};
global.THREE = {
Group: Grp, Mesh: leaf(), Line: leaf(), LineLoop: leaf(), LineSegments: leaf(),
Points: leaf(), Vector3: V3,
MeshLambertMaterial: mat(), MeshStandardMaterial: mat(), LineBasicMaterial: mat(),
PointsMaterial: mat(),
CylinderGeometry: class {}, ConeGeometry: class {}, BoxGeometry: class { dispose() {} },
PlaneGeometry: class { dispose() {} }, GridHelper: class { constructor() { Object.assign(this, node()); } },
BufferGeometry: class {
constructor() { this.attributes = {}; }
setAttribute(n, a) { this.attributes[n] = a; }
setFromPoints() { return this; }
computeVertexNormals() {} dispose() {}
},
BufferAttribute: class { constructor(a, n) { this.array = a; this.itemSize = n; } },
InstancedMesh: class { constructor() { Object.assign(this, node()); this.instanceMatrix = {}; }
setMatrixAt() {} dispose() {} },
Matrix4: class { compose() {} }, Quaternion: class { setFromAxisAngle() {} },
Color: class { constructor() { this.set = () => {}; } },
};
const www = '/home/quangtrung/projects/vslam_cpp/libs/vslam_web/www';
const sb = { THREE: global.THREE, console, window: {}, document: {} };
vm.createContext(sb);
vm.runInContext(fs.readFileSync(path.join(www, 'app3d.js'), 'utf8') +
'\n;this.__V3D = V3D; this.__shape = v3dSetShape; this.__pose = v3dSetPose;' +
'\n;this.__scan = v3dSetScan;', sb);
const V3D = sb.__V3D;
V3D.ready = true;
V3D.root = new Grp();
const r = { radius: 0.17, wheel_radius: 0.075, wheel_sep: 0.30,
laser_x: 0.24, laser_y: 0.0, laser_z: 0.125, cam_x: 0.10 };
sb.__shape(r);
// Sai so thuc do duoc giua uoc luong va ground truth: 9 mm.
const pose = { x: 5.000, y: 2.000, yaw: 0.0 };
const gt = { x: 5.009, y: 2.000, yaw: 0.0 };
sb.__pose(V3D.robotGroup, pose);
sb.__pose(V3D.gtGroup, gt);
// Cao do TUYET DOI cua mot nut: cong y qua tung tang.
function absY(root, pred) {
let found = null;
(function walk(n, acc) {
const y = acc + (n.position ? n.position.y : 0);
if (found === null && pred(n)) found = y;
(n.children || []).forEach((c) => walk(c, y));
})(root, 0);
return found;
}
const isLidar = (n) => n.material && n.material.color !== undefined &&
n.geometry instanceof THREE.CylinderGeometry &&
n.position && Math.abs(n.position.x - r.laser_x) < 1e-9;
const bad = [];
const say = (label, got, want, tol) => {
// Diem quet luu trong Float32Array -- 0.125 + 0.075 khong tron duoc.
const ok = Math.abs(got - want) <= (tol === undefined ? 1e-6 : tol);
console.log(` ${label.padEnd(36)} ${got.toFixed(4)}${ok ? '' : ' != ' + want.toFixed(4)}`);
if (!ok) bad.push(label);
};
// 1. Khoang cach ve phai DUNG BANG khoang cach du lieu -- khong them gi.
const A = V3D.robotGroup.position, B = V3D.gtGroup.position;
say('khoang cach ve (m)', Math.hypot(A.x - B.x, A.y - B.y, A.z - B.z), 0.009, 1e-6);
// 2. Hai hinh phai o CUNG cao do. Day la thu bi hong.
const yRobot = absY(V3D.robotGroup, (n) => n !== V3D.robotGroup && n.children &&
n.children.length > 0);
const yGt = absY(V3D.gtGroup, (n) => n !== V3D.gtGroup && n.children &&
n.children.length > 0);
say('cao do than robot (m)', yRobot, r.wheel_radius);
say('cao do than ground truth (m)', yGt, r.wheel_radius);
// 3. ⚠️ Phep kiem MANH nhat: tru LiDAR tren robot va diem quet phai CUNG cao
// do. Hai duong code doc lap -- v3dBuildRobot() va v3dSetScan() -- nen
// chung chi khop khi ca hai deu dung.
sb.__scan(new Float32Array([2.0, 0.0]), pose, r);
const scanY = V3D.scanPts.geometry.attributes.position.array[1];
const lidarY = absY(V3D.robotGroup, isLidar);
say('cao do diem quet (m)', scanY, r.laser_z + r.wheel_radius);
if (lidarY === null) {
console.log(' khong tim thay tru LiDAR tren hinh robot');
bad.push('tru LiDAR');
} else {
say('cao do tru LiDAR tren robot (m)', lidarY, scanY);
}
// 4. Hop dong cua v3dSetPose(): no dat VI TRI TREN MAT PHANG, khong dung
// toi cao do. Mot nhom mang san phep nang phai giu duoc phep nang do.
//
// Khong co rang buoc nay thi `position.set(p.x, 0, -p.y)` quay lai luc nao
// cung duoc, va lan sau ai them mot lop boc co nang se lai mat no am tham.
const lifted = new Grp();
lifted.position.y = 0.5;
sb.__pose(lifted, { x: 1.0, y: 2.0, yaw: 0.3 });
say('v3dSetPose giu cao do san co (m)', lifted.position.y, 0.5);
say('v3dSetPose dat x', lifted.position.x, 1.0);
say('v3dSetPose dat z (= -y ROS)', lifted.position.z, -2.0);
console.log(bad.length ? '\n => HONG: ' + bad.join(', ') : '\n => DAT');
process.exit(bad.length ? 1 : 0);

125
test/www/test_scan_frame.js Normal file
View File

@@ -0,0 +1,125 @@
// Scan co duoc dat DUNG CHO trong khong gian khong?
//
// ================== VI SAO CAN BAI KIEM NAY ==================
// Scan di qua day tren dinh dang POLAR trong frame LASER. Trinh duyet doi sang
// Descartes roi ap pose cua BASE. Bo qua khoang gan LiDAR (0.24 m ve truoc)
// lam ca vanh quet lui 24 cm -- cac tia khong con nam tren tuong.
//
// 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 thay robot
// "troi" va di tim loi trong odometry/SLAM -- cho khong co loi.
//
// Nen bai kiem do THU DUNG: dung phep bien doi CUA CHINH app3d.js tren mot
// canh dung san, roi kiem diem quet co roi trung tuong khong.
//
// node test_scan_frame.js
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
// --- THREE gia ---
class V3 { constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } }
class BufAttr { constructor(a, n) { this.array = a; this.itemSize = n; } }
class BufGeom {
constructor() { this.attributes = {}; }
setAttribute(n, a) { this.attributes[n] = a; }
computeVertexNormals() {}
dispose() {}
}
class Grp {
constructor() { this.children = []; }
add(c) { this.children.push(c); }
remove(c) { this.children = this.children.filter((x) => x !== c); }
traverse(f) { this.children.forEach(f); }
}
global.THREE = {
Vector3: V3, Color: class { constructor(r, g, b) { Object.assign(this, { r, g, b }); } },
Quaternion: class { setFromAxisAngle() {} }, Matrix4: class { compose() {} },
BufferAttribute: BufAttr, BufferGeometry: BufGeom, Group: Grp,
Points: class { constructor(g, m) { this.geometry = g; this.material = m; } },
PointsMaterial: class { constructor(o) { Object.assign(this, o); } },
MeshStandardMaterial: class { constructor(o) { Object.assign(this, o); } dispose() {} },
InstancedMesh: class { constructor(g, m, n) { this.geometry = g; this.count = n;
this.userData = {}; this.instanceMatrix = {}; } setMatrixAt() {} dispose() {} },
Mesh: class { constructor(g, m) { this.geometry = g; this.material = m;
this.position = { set: () => {} }; this.rotation = { x: 0 }; } },
PlaneGeometry: class { dispose() {} }, GridHelper: class {},
BoxGeometry: class { dispose() {} },
};
const wwwDir = path.resolve(__dirname, '../../libs/vslam_web/www');
const sandbox = { THREE: global.THREE, console, window: {}, document: {} };
vm.createContext(sandbox);
vm.runInContext(
fs.readFileSync(path.join(wwwDir, 'app3d.js'), 'utf8') +
'\n;this.__V3D = V3D; this.__setScan = v3dSetScan;',
sandbox);
const V3D = sandbox.__V3D;
V3D.ready = true;
V3D.root = new Grp();
// --- Canh dung san: hanh lang rong 4 m, robot o giua, quay 0 rad ---
//
// Tuong o y = +2 va y = -2, keo dai theo x. LiDAR o 0.24 m truoc base.
const LASER_X = 0.24, WALL = 2.0;
const robot = { laser_x: LASER_X, laser_y: 0, laser_z: 0.125, wheel_radius: 0.075 };
const pose = { x: 5.0, y: 1.0, yaw: 0.0 };
// Tia trong frame LASER, moi tia cham dung mot buc tuong.
// LiDAR o world y = pose.y = 1.0 (vi laser_y = 0 va yaw = 0).
// Tuong tren cach 1.0 m, tuong duoi cach 3.0 m.
const rays = [];
for (const [ang, dist] of [[Math.PI / 2, 1.0], [-Math.PI / 2, 3.0]]) {
rays.push(dist * Math.cos(ang), dist * Math.sin(ang));
}
// Them mot tia cheo 45 do len tuong tren: cham o khoang cach 1.0/sin(45).
rays.push(Math.SQRT2 * Math.cos(Math.PI / 4), Math.SQRT2 * Math.sin(Math.PI / 4));
sandbox.__setScan(new Float32Array(rays), pose, robot);
const pos = V3D.scanPts.geometry.attributes.position.array;
let bad = 0;
const rows = [];
for (let i = 0; i < pos.length / 3; ++i) {
const wx = pos[i * 3];
const wy = -pos[i * 3 + 2]; // three z = -ROS y
const wz = pos[i * 3 + 1];
// Moi diem phai nam tren mot trong hai buc tuong.
const onWall = Math.abs(Math.abs(wy - pose.y) - 0) < 1e6; // tinh o duoi
const dTop = Math.abs(wy - (pose.y + 1.0));
const dBot = Math.abs(wy - (pose.y - 3.0));
const hit = Math.min(dTop, dBot) < 1e-3;
if (!hit) bad++;
rows.push(` tia ${i}: world (${wx.toFixed(3)}, ${wy.toFixed(3)}, ${wz.toFixed(3)})` +
` ${hit ? 'tren tuong' : 'TRUOT ' + Math.min(dTop, dBot).toFixed(3) + ' m'}`);
}
rows.forEach((r) => console.log(r));
// ⚠️ Phep kiem THAT: diem quet phai dich len truoc DUNG bang laser_x.
//
// Tia thang ben (+-90 do) khong doi y khi bu laser_x, nen chung mot minh
// KHONG phan biet duoc co bu hay khong. Tia CHEO thi co.
const cheo = { x: pos[6], y: -pos[8] };
const mongDoi = {
x: pose.x + LASER_X + 1.0, // 0.24 tu laser_x + 1.0 tu tia cheo
y: pose.y + 1.0,
};
console.log(`\n tia cheo: duoc (${cheo.x.toFixed(3)}, ${cheo.y.toFixed(3)})`);
console.log(` mong (${mongDoi.x.toFixed(3)}, ${mongDoi.y.toFixed(3)})`);
const dx = Math.abs(cheo.x - mongDoi.x);
if (dx > 1e-3) {
bad++;
console.log(` LECH ${dx.toFixed(3)} m theo x` +
(Math.abs(dx - LASER_X) < 1e-3 ? ' == dung bang laser_x!' : ''));
}
// Do cao: scan phai o do cao LiDAR, khong phai o san.
const zMongDoi = robot.laser_z + robot.wheel_radius;
if (Math.abs(pos[1] - zMongDoi) > 1e-6) {
bad++;
console.log(` do cao scan ${pos[1]} != ${zMongDoi}`);
}
console.log(bad ? '\n => HONG' : '\n => DAT');
process.exit(bad ? 1 : 0);

163
test/www/test_world_mesh.js Normal file
View File

@@ -0,0 +1,163 @@
// Bo giai ma `world.bin` cua trinh duyet, chay bang CHINH khoi do C++ sinh ra.
//
// ================== VI SAO CAN BAI KIEM NAY ==================
// Bo ma hoa o C++ va bo giai ma o JavaScript la hai ban cai dat cua MOT dinh
// dang. Chung lech nhau mot byte thi khung 3D ra rac hoac rong -- va mot khung
// 3D rong co dung moi chi so van hanh voi mot khung dung: HTTP 200, dung so
// byte, khong ngoai le nao.
//
// Nen bai kiem nay DEM NOI DUNG: bao nhieu hinh hoc, bao nhieu the hien, bao
// nhieu tam giac, va do dac nam o dau trong khong gian.
//
// Khong can bo model AWS 3 GB: khoi duoc sinh tu test/data/world/mini.world.
//
// node test_world_mesh.js <vslam_world_export> <thu_muc_data> <file_tam>
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const [exporter, dataDir, tmpBin] = process.argv.slice(2);
const wwwDir = path.resolve(__dirname, '../../libs/vslam_web/www');
// --- THREE gia: chi du de dung hinh, khong ve gi ---
class Vector3 { constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } }
class Color { constructor(r, g, b) { this.r = r; this.g = g; this.b = b; } }
class Quaternion { setFromAxisAngle(a, ang) { this.ang = ang; } }
class Matrix4 { compose(p, q, s) { this.p = p; this.q = q; } }
class BufferAttribute { constructor(a, n) { this.array = a; this.itemSize = n; } }
class BufferGeometry {
constructor() { this.attributes = {}; }
setAttribute(n, a) { this.attributes[n] = a; }
computeVertexNormals() { this.normals = true; }
dispose() { this.disposed = true; }
}
class Group {
constructor() { this.children = []; }
add(c) { this.children.push(c); }
traverse(f) { this.children.forEach(f); }
remove(c) { this.children = this.children.filter((x) => x !== c); }
}
class MeshStandardMaterial { constructor(o) { Object.assign(this, o); } dispose() {} }
class InstancedMesh {
constructor(g, m, n) {
this.geometry = g; this.material = m; this.count = n;
this.mats = []; this.userData = {}; this.instanceMatrix = {};
}
setMatrixAt(i, m) { this.mats[i] = { p: m.p, q: m.q }; }
dispose() {}
}
class Mesh {
constructor(g, m) {
this.geometry = g; this.material = m;
this.position = { set: (x, y, z) => { this.pos = [x, y, z]; } };
this.rotation = { x: 0, y: 0, z: 0 };
}
}
global.THREE = {
Vector3, Color, Quaternion, Matrix4, BufferAttribute, BufferGeometry, Group,
MeshStandardMaterial, InstancedMesh, Mesh,
PlaneGeometry: class { constructor(w, h) { this.w = w; this.h = h; } dispose() {} },
GridHelper: class { constructor(s) { this.size = s; } },
BoxGeometry: class { dispose() {} },
};
// --- nap app3d.js trong pham vi rieng ---
const vm = require('vm');
const sandbox = { THREE: global.THREE, console, window: {}, document: {} };
vm.createContext(sandbox);
vm.runInContext(
fs.readFileSync(path.join(wwwDir, 'app3d.js'), 'utf8') +
'\n;this.__V3D = V3D; this.__setMeshes = v3dSetWorldMeshes;' +
'\n;this.__setWorld = v3dSetWorld;',
sandbox);
const V3D = sandbox.__V3D;
V3D.ready = true;
V3D.root = new Group();
V3D.scene = { fog: { near: 0, far: 0 } };
// --- sinh khoi tu mini.world bang chinh bo ma hoa C++ ---
execFileSync(exporter, [
'--world', path.join(dataDir, 'world/mini.world'),
'--models', path.join(dataDir, 'world/models'),
'--meshes', tmpBin, '--meshes-visual',
], { stdio: ['ignore', 'ignore', 'inherit'] });
const raw = fs.readFileSync(tmpBin);
const ab = raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength);
const bad = [];
const check = (name, got, want) => {
const ok = JSON.stringify(got) === JSON.stringify(want);
console.log(` ${name.padEnd(28)} ${JSON.stringify(got)}${ok ? '' : ' != ' + JSON.stringify(want)}`);
if (!ok) bad.push(name);
};
if (!sandbox.__setMeshes(ab)) {
console.log(' => HONG: khong giai ma duoc khoi');
process.exit(1);
}
const g = V3D.meshWorld;
let nInst = 0, nMat = 0, nTri = 0;
const centers = [];
for (const im of g.children) {
nInst += im.count;
nMat += im.mats.length;
nTri += im.geometry.attributes.position.array.length / 9;
for (const m of im.mats) centers.push(m.p);
}
// mini.world: 4 model khac nhau, 5 the hien (the thu sau co pose hong, bi bo).
check('hinh hoc', g.children.length, 4);
check('the hien', nInst, 5);
check('ma tran da dat', nMat, 5);
// Moi hop 8 tam giac; box_m dung cho 2 the hien nen van chi 1 ban hinh hoc.
check('tam giac (duy nhat)', nTri, 32);
// Tam cac the hien, trong he three (x, y, z) = ROS (x, z, -y).
const xs = centers.map((p) => +p.x.toFixed(2)).sort((a, b) => a - b);
const zs = centers.map((p) => +p.z.toFixed(2)).sort((a, b) => a - b);
check('tam theo x', xs, [0, 0, 5, 10, 15]);
check('tam theo z (= -y ROS)', zs, [-6, 0, 0, 0, 0]);
// Hop dau tien khong quay: dinh phai o +-1.0 theo x, +-0.5 theo z.
const first = g.children[0].geometry.attributes.position.array;
let xmin = 1e9, xmax = -1e9, ymin = 1e9, ymax = -1e9, zmin = 1e9, zmax = -1e9;
for (let i = 0; i < first.length; i += 3) {
xmin = Math.min(xmin, first[i]); xmax = Math.max(xmax, first[i]);
ymin = Math.min(ymin, first[i + 1]); ymax = Math.max(ymax, first[i + 1]);
zmin = Math.min(zmin, first[i + 2]); zmax = Math.max(zmax, first[i + 2]);
}
check('hop 1: rong x', +(xmax - xmin).toFixed(2), 2);
check('hop 1: cao y', +(ymax - ymin).toFixed(2), 0.5);
check('hop 1: sau z', +(zmax - zmin).toFixed(2), 1);
// ⚠️ MOI hop phai cao 0.5 m, khong rieng hop dau.
//
// `..._walls_visual` khai Y_UP nhung du lieu da o Z-up: ap `<up_axis>` len no
// lam buc tuong 3 m thanh mot thanh DUNG DUNG cao 56 m. Mat bang van dung, nen
// chi do chieu cao moi thay.
let tallest = 0;
for (const im of g.children) {
const a = im.geometry.attributes.position.array;
let lo = 1e9, hi = -1e9;
for (let i = 1; i < a.length; i += 3) { lo = Math.min(lo, a[i]); hi = Math.max(hi, a[i]); }
tallest = Math.max(tallest, hi - lo);
}
check('hop cao nhat', +tallest.toFixed(2), 0.5);
// ⚠️ HOI QUY: san nam trong v3dSetWorld(), ma ham do THOAT SOM khi da co mesh
// that. Mot lan da lam ca toa nha lo lung tren nen den ma khong loi nao.
const grid = { w: 400, h: 400, res: 0.05, ox: -10, oy: -10,
cells: new Int8Array(400 * 400) };
sandbox.__setWorld(grid, 2.0);
check('san sau khi co mesh', !!V3D.floorMesh, true);
check('luoi san', !!V3D.gridHelper, true);
check('khoi hop da bo', V3D.worldMesh, null);
// Suong mu phai phu het bao, khong thi toa nha tan vao nen.
check('suong mu >= bao', V3D.scene.fog.far >= 400 * 0.05, true);
console.log(bad.length ? '\n => HONG: ' + bad.join(', ') : '\n => DAT');
process.exit(bad.length ? 1 : 0);