feat: add the 4-leg trolley detection action

TrolleyDetectionActionHandler finds a 4-leg trolley in a raw LaserScan with
dock_pattern_detector's LegPatternMatcher, filters the detections and writes a
static dock_target frame for the docking leg that drives under the trolley.

- entry_direction forward/backward sets the goal heading; a lidar that faces
  the wrong way fails the action instead of writing a reversed goal
- an upside-down lidar (roll pi in TF) is detected from TF and its bearings
  are mirrored; a scan plane tilted more than 5 deg fails the action
- profiles validated at boot; optional prior, reflective tape (all/entry)
- gtest (11 tests) incl. a recorded Gazebo scan from a roll-pi lidar
- sim models trolley_4legs (+ taped variants) the robot can drive under,
  spawn launch and generator script
- doc/MEASURE_AND_CONFIGURE.md: how to measure a trolley and fill the profile
This commit is contained in:
2026-10-28 13:33:52 +07:00
commit bfdcac512f
20 changed files with 9137 additions and 0 deletions

194
CMakeLists.txt Normal file
View File

@@ -0,0 +1,194 @@
cmake_minimum_required(VERSION 3.0.2)
project(trolley_detection_action VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# ==================================================================================================
# Phát hiện chế độ build — theo mẫu dock_pattern_action, giữ cả hai:
# - catkin (`catkin_make` trong workspace phát triển)
# - standalone (root CMakeLists của pnkx_nav_core, không có catkin)
# ==================================================================================================
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
set(BUILDING_WITH_CATKIN TRUE)
message(STATUS "Building trolley_detection_action with Catkin")
else()
set(BUILDING_WITH_CATKIN FALSE)
message(STATUS "Building trolley_detection_action with Standalone CMake")
endif()
find_package(Boost REQUIRED)
find_package(Threads REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(Eigen3 REQUIRED)
# tf3 không được build bởi workspace này (cài sẵn ở /usr/local/lib/libtf3.so).
find_library(TF3_LIBRARY
NAMES tf3
PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu
)
if(NOT TF3_LIBRARY)
message(FATAL_ERROR "tf3 not found — install tf3 (/usr/local/lib/libtf3.so) before building")
endif()
if(BUILDING_WITH_CATKIN)
find_package(catkin REQUIRED COMPONENTS
action_core
dock_pattern_detector
robot_line_extraction
robot_sensor_ports
robot_cpp
robot_sensor_msgs
)
catkin_package(
CATKIN_DEPENDS
action_core
dock_pattern_detector
robot_line_extraction
robot_sensor_ports
robot_cpp
robot_sensor_msgs
)
else()
# Root CMakeLists của pnkx_nav_core đã `add_subdirectory` mọi gói trước gói này, nên chỉ cần NÊU
# TÊN TARGET: include của chúng tự lan sang qua interface PUBLIC.
set(TROLLEY_DETECTION_ACTION_STANDALONE_LIBRARIES
action_core
dock_pattern_detector
robot_line_extraction
robot_sensor_ports
robot_cpp
robot_sensor_msgs
)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
endif()
# Handler là plugin Boost.DLL, nạp theo khoá `library_path` trong YAML — KHÔNG link thẳng vào ai.
add_library(trolley_detection_action_handler SHARED
plugins/trolley_detection_action_handler.cpp
)
target_compile_options(trolley_detection_action_handler PRIVATE -Wall -Wextra)
# Header của dependency vào dạng SYSTEM: robot_cpp sinh hàng trăm warning riêng của nó — để lẫn vào
# thì warning của chính gói này vô hình. Gắn vào TARGET, không `include_directories()` toàn thư mục.
target_include_directories(trolley_detection_action_handler SYSTEM
PRIVATE
${Boost_INCLUDE_DIRS}
${EIGEN3_INCLUDE_DIRS}
)
if(BUILDING_WITH_CATKIN)
target_include_directories(trolley_detection_action_handler SYSTEM
PRIVATE ${catkin_INCLUDE_DIRS})
add_dependencies(trolley_detection_action_handler ${catkin_EXPORTED_TARGETS})
target_link_libraries(trolley_detection_action_handler
PUBLIC
${catkin_LIBRARIES}
PRIVATE
Boost::boost
yaml-cpp
Threads::Threads
${CMAKE_DL_LIBS}
${TF3_LIBRARY}
)
# Model + launch để dựng xe 4 chân có dải phản quang trong Gazebo. Launch tra đường dẫn qua
# $(find trolley_detection_action) nên phải có mặt sau khi install.
install(DIRECTORY sim/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/sim
)
install(TARGETS trolley_detection_action_handler
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
)
else()
target_link_libraries(trolley_detection_action_handler
PUBLIC
${TROLLEY_DETECTION_ACTION_STANDALONE_LIBRARIES}
PRIVATE
Boost::boost
yaml-cpp
Threads::Threads
${CMAKE_DL_LIBS}
${TF3_LIBRARY}
)
# Plugin được nạp bằng boost::dll theo TÊN FILE, và `PluginLoaderHelper` tra trong thư mục build.
set_target_properties(trolley_detection_action_handler PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
BUILD_RPATH "${CMAKE_BINARY_DIR}"
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
)
include(GNUInstallDirs)
install(TARGETS trolley_detection_action_handler
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
install(DIRECTORY sim/
DESTINATION ${CMAKE_INSTALL_DATADIR}/${PROJECT_NAME}/sim
)
endif()
# Test chạy qua `catkin_add_gtest` và cần `CATKIN_DEVEL_PREFIX` để biết plugin nằm ở đâu, nên chỉ
# có ở nhánh catkin. Ở standalone, plugin vẫn build — chỉ không có test.
if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN)
if(NOT COMMAND catkin_add_gtest)
message(FATAL_ERROR "catkin_add_gtest NOT FOUND")
endif()
catkin_add_gtest(trolley_detection_action_test test/trolley_detection_action_test.cpp)
if(TARGET trolley_detection_action_test)
# catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make` thường.
set_target_properties(trolley_detection_action_test PROPERTIES EXCLUDE_FROM_ALL FALSE)
target_compile_options(trolley_detection_action_test PRIVATE -Wall -Wextra)
target_include_directories(trolley_detection_action_test SYSTEM
PRIVATE ${catkin_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIRS}
)
# Plugin KHÔNG được link thẳng: nó chỉ export alias Boost.DLL và được nạp qua ActionRegistry,
# đúng đường mà runtime đi.
target_link_libraries(trolley_detection_action_test
${catkin_LIBRARIES}
${Boost_LIBRARIES}
yaml-cpp
pthread
${CMAKE_DL_LIBS}
${TF3_LIBRARY}
)
add_dependencies(trolley_detection_action_test trolley_detection_action_handler)
# ctest không mang theo PNKX_NAV_CORE_CONFIG_DIR hay LD_LIBRARY_PATH của shell.
target_compile_definitions(trolley_detection_action_test PRIVATE
TROLLEY_DETECTION_ACTION_TEST_CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/config"
TROLLEY_DETECTION_ACTION_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/data"
TROLLEY_DETECTION_ACTION_TEST_LIBRARY_DIR="${CATKIN_DEVEL_PREFIX}/lib"
)
endif()
endif()

81
README.md Normal file
View File

@@ -0,0 +1,81 @@
# trolley_detection_action
Handler `action_core::ActionHandler` dò xe hàng 4 chân từ một LaserScan THÔ, khi robot đứng yên ở
pose chuẩn bị trước xe. Kết quả: một TF tĩnh `output_frame` (thường `dock_target`) = pose robot phải
đạt dưới gầm xe, cho chặng `move_to` sau nó. Plugin Boost.DLL, symbol `TrolleyDetectionActionHandler`,
thư viện `libtrolley_detection_action_handler`.
Lõi hình học nằm ở `dock_pattern_detector` (`LegPatternMatcher`, `LegPoseFit`, `LegProfile`); gói này
chỉ là adapter: kho cảm biến, TF, chọn profile, lọc nhiều scan, ghi kết quả.
## Hợp đồng đầu ra
- **Vị trí** = tâm hình chữ nhật tâm 4 chân + `offset_x/y` của profile (cùng công thức với
`dock_pattern`).
- **Heading** theo `entry_direction`:
| `entry_direction` | Lidar dò | Heading của `output_frame` |
|---|---|---|
| `forward` | lidar trước | trỏ **VÀO** xe — robot tiến thẳng vào gầm |
| `backward` | lidar sau | trỏ **RA** cạnh vào — robot lùi thẳng vào gầm |
Lidar của `scan_topic` phải nhìn đúng hướng với `entry_direction`; lệch thì action fail ngay ở scan
đầu (khai lệch là goal ngược 180°).
**Lidar gắn lộn ngược** (hook_150: roll π) tự xử lý từ TF `prior_frame` ← frame scan, không có khoá
cấu hình: trục z của frame scan chỉ xuống thì góc tia được đảo dấu trước khi dò. Driver không lật dữ
liệu; nếu sau này driver lật thì URDF phải bỏ roll π (costmap cũng đọc TF đó). Mặt quét nghiêng quá
5° so với `prior_frame` → action fail (mô hình chân là 2D).
## Các bước dò (mỗi scan)
1. Lọc tia + lọc điểm kéo đuôi.
2. Tách cụm theo thứ tự tia; giữ cụm đứng tự do có bề rộng của một chân.
3. Ghép cặp chân theo `cart_opening` / `cart_depth` / đường chéo → giả thuyết xe.
4. Khớp tư thế trên mọi điểm chân theo mô hình biên chân; kiểm khoảng cách từng cặp chân.
5. Tia đi xuyên qua chỗ một chân phải đứng → loại. Một chân bị che vẫn nhận (`min_legs: 3`).
6. Chọn cạnh vào (dải `entry` → prior yaw → cạnh quay về robot), cổng prior, điểm tin.
7. Hai xe điểm sát nhau ở hai chỗ → từ chối cả lượt (dãy xe đỗ sát) — đặt prior để chọn.
Sau đó `PoseSampleFilter` gom nhiều scan trong `global_frame` và chốt khi đủ ổn định.
## Giới hạn đã biết
- **Xe đỗ ngược chiều**: 4 chân không dải đối xứng hoàn toàn. Bản không dải không phát hiện được;
dán dải ở 2 chân đầu cần vào và bật `tape_legs: entry`.
- **Chân dính vật khác ở độ cao lidar** (tường, thanh giằng, hàng chạm sàn): mép cụm "dính", chân bị
loại. Hai chân như vậy là không dò được.
- **Mặt chân bóng** (nhôm/inox): phản xạ gương làm tia "xuyên qua" chỗ chân → xe thật bị loại. Sơn
mờ hoặc dán băng mờ ở độ cao lidar.
## Config
**Đo xe thật và điền profile: [doc/MEASURE_AND_CONFIGURE.md](doc/MEASURE_AND_CONFIGURE.md)** (hình
sinh bằng `doc/gen_fig.py`).
Khoá handler và profile: xem khối `detect_trolley` trong
`move_base2/config/runtime/action_handlers_params.yaml` (comment tiếng Việt từng khoá) và
`test/config/action_handlers_params.yaml`. Plan đầy đủ (quy ước frame, thuật toán, ngân sách sai
số, đo xe thật): `Test/docs/trolley_detection_action/TROLLEY_LEG_DETECTION_PLAN.md` của workspace
phát triển.
## Sim
- **Chạy thử chui gầm: dùng model đơn giản của gói** (`sim/models`, sinh bằng
`sim/gen_trolley_models.py`): `roslaunch trolley_detection_action spawn_trolley.launch` —
`model:=trolley_4legs` (không dải, mặc định), `trolley_4legs_tape_entry`, `trolley_4legs_tape_all`.
Gốc model ở tâm 4 chân, `z = 0`; sàn xe cao 0.380 m nên `hook_150` chui lọt.
- `tci_trolley` của gói `factory_ss_demo` chỉ dùng để **dò**, không chui được trong Gazebo: mesh có
tấm đáy 0.78 × 0.613 × 0.01 m sát sàn và mặt dưới sàn xe 0.352 m (thấp hơn nóc robot 0.3595 m).
Spawn ở `z = 0.3497`; tâm 4 chân = pose model + R(yaw)·(0.509, 0.5275).
## Build và test
```bash
cd /home/duongtd/T800_ws
source devel/setup.bash
catkin_make --pkg dock_pattern_detector trolley_detection_action
./devel/lib/dock_pattern_detector/leg_pose_fit_test
./devel/lib/dock_pattern_detector/leg_pattern_matcher_test
./devel/lib/trolley_detection_action/trolley_detection_action_test
```

View File

@@ -0,0 +1,414 @@
# Đo xe hàng 4 chân và cấu hình profile
Tài liệu cho người đứng cạnh robot: đo một xe hàng thật, kiểm robot có chui lọt không, rồi điền số
vào profile của `TrolleyDetectionActionHandler`. Mọi số trong profile là **số đo trên xe thật**. Giá
trị mặc định trong code chỉ để test chạy được.
Luật khớp chi tiết nằm ở README của gói này và của `dock_pattern_detector` (`LegPatternMatcher`).
Tài liệu này chỉ trả lời: đo cái gì, đo thế nào, điền vào đâu, và kiểm ra sao.
## Config nằm ở đâu
Profile nằm trong `action_handlers_params.yaml`, dưới đúng action dùng handler này:
```yaml
actions:
handlers:
- {name: detect_trolley, type: TrolleyDetectionActionHandler}
detect_trolley: # tên action, tuỳ cây config
action_types: [DetectTrolley]
output_frame: dock_target
scan_topic: /f_scan
entry_direction: forward
...
default_profile: tci_trolley
profiles:
<tên_xe>: # một profile cho MỘT loại xe
cart_opening: 0.517
...
```
- Mỗi loại xe một profile. Order chọn profile qua `actionParameters` (khoá `profile_param_key`, mặc
định `trolley_profile`). Không gửi thì handler dùng `default_profile`. Gửi tên không có thì action
**thất bại**, không âm thầm dùng profile khác.
- Handler đọc và **kiểm mọi profile lúc boot**. Sửa YAML xong phải khởi động lại nav, nếu không nav
vẫn chạy với config cũ. Một profile sai miền giá trị làm handler từ chối nạp và log rõ khoá nào sai.
- Hai chỗ khác phải khớp với profile: `footprint_dock` của marker trong `maker_sources.yaml` (mục 3),
và chuỗi `dockTo` trong `compound_actions_params.yaml` (`{action: DetectTrolley}` rồi
`{move_to: dock_target, profile: docking, marker: trolley}`).
## Thứ tự làm
1. Chọn cạnh vào, đo tâm–tâm chân: `cart_opening`, `cart_depth`.
2. Đo tiết diện chân ở độ cao lidar: `leg_shape`, `leg_width`, `leg_depth`.
3. Kiểm robot chui lọt: khe hai bên, khe gầm, sàn trống. Không có khoá config, đây là ràng buộc cơ khí.
4. Chọn `entry_direction` và `scan_topic`; kiểm cách gắn lidar.
5. Pose đích: `offset_x`, `offset_y`, `offset_yaw` (thường để 0).
6. Tuỳ chọn: dán dải phản quang, đo `tape_min_intensity`.
7. Tuỳ chọn: prior, khi xe đỗ thành dãy sát nhau.
8. Chỉnh các khoá theo cảm biến (tầm, nhiễu, bộ lọc).
9. Bật, chạy, đọc log, đo sai số dưới gầm.
Dụng cụ: thước dây, thước kẹp. Thông tin cần tra trước: frame của cảm biến trong `scan_topic`, TF
`base_link → <frame cảm biến>`, bước tia của cảm biến (`angle_increment`), chiều cao mặt quét
`h_sensor` (từ sàn tới tâm cửa sổ quang của lidar, không phải đỉnh vỏ).
```bash
rostopic echo -n1 /f_scan/header/frame_id
rostopic echo -n1 /f_scan/angle_increment
rosrun tf tf_echo base_link front_laser_link
```
## 1. Tâm–tâm chân: `cart_opening`, `cart_depth`
![Xe hàng 4 chân nhìn từ trên xuống: kích thước, cạnh vào, dock_target](fig/cart_top.svg)
**Chọn cạnh vào trước.** Cạnh vào là cạnh robot chui qua. Hai chân của cạnh đó phải cách nhau đủ rộng
cho thân robot (mục 3). Xe chữ nhật có hai cạnh dài, hai cạnh ngắn; thường chỉ một cặp cạnh lọt robot.
| Khoá | Đơn vị | Đo gì |
|---|---|---|
| `cart_opening` | m | Tâm–tâm hai chân của **cạnh vào**, ngang hướng chui. |
| `cart_depth` | m | Tâm–tâm hai chân **dọc** hướng chui (chân cạnh vào → chân cạnh xa). |
Đo ở **độ cao lidar**, không đo ở sàn: bánh xe, bát bánh, chân đế làm tiết diện gần sàn khác hẳn.
![Đo tâm–tâm bằng hai lần đo mép](fig/leg_measure.svg)
Tâm chân không chấm được thì đo mép ngoài–mép ngoài `a` và mép trong–mép trong `b`:
```
tâm–tâm = (a + b) / 2
bề rộng chân = (a − b) / 2 (dùng luôn cho mục 2)
```
Đo cả hai cặp chân của mỗi chiều. Rồi đo **hai đường chéo** tâm–tâm và so với
```
đường chéo = √( cart_opening² + cart_depth² ) tci_trolley: √(0.517² + 0.720²) = 0.886 m
```
Hai cặp lệch nhau, hoặc đường chéo lệch số tính, quá 1–2 cm nghĩa là xe méo. Ghi lại và nới
`cart_dim_tolerance`.
| Khoá | Đơn vị | Mặc định | Chỉnh khi |
|---|---|---|---|
| `cart_dim_tolerance` | m | 0.04 | Xe méo. Phải < min(`cart_opening`, `cart_depth`) / 4. Xem ràng buộc xe đỗ thành dãy bên dưới. |
**Xe đỗ thành dãy sát nhau.** Đo khoảng tâm–tâm `g` giữa hai chân **kề nhau của hai xe cạnh nhau**.
Phải giữ
```
cart_dim_tolerance < | g − cart_opening | và < | g − cart_depth |
```
nếu không, hai chân của hai xe khác nhau ghép thành một "xe" giả. Ví dụ dãy xe trong world
`factory_ss_demo`: `g = 0.453 m`, `cart_opening = 0.517 m` → tolerance phải < 0.064, nên giữ 0.04.
**Xe gần vuông** (`|cart_opening − cart_depth| < 2 · cart_dim_tolerance`): hình học không phân biệt
được cạnh vào với cạnh bên. Handler từ chối nạp, trừ khi có prior với `prior_yaw_tolerance < π/4`
(mục 7) hoặc dải `tape_legs: entry` (mục 6).
## 2. Tiết diện chân: `leg_shape`, `leg_width`, `leg_depth`
Đo ở đúng `h_sensor`, bằng thước kẹp.
| Khoá | Giá trị | Đo gì |
|---|---|---|
| `leg_shape` | `box` / `round` | Ống vuông/chữ nhật: `box`. Ống tròn: `round`. |
| `leg_width` | m | `box`: cạnh **ngang** hướng chui (dọc `cart_opening`). `round`: đường kính. |
| `leg_depth` | m | Chỉ `box`: cạnh **dọc** hướng chui. 0 = bằng `leg_width` (chân vuông). |
| `leg_yaw_offset` | rad | Chỉ `box`: ống lắp xoay so với cạnh xe (lắp chéo 45° → 0.785). Thường 0. |
| `leg_width_tolerance` | m | Mặc định 0.02. Nới khi chân móp, dán băng dày. |
Chân `round` mà khai `leg_depth` hoặc `leg_yaw_offset` khác 0 thì handler từ chối nạp.
**Số tia trúng một chân** quyết định dò xa được bao nhiêu:
```
n ≈ leg_width / (tầm · angle_increment)
```
| Cảm biến | angle_increment | chân 30 mm: 1 m / 2 m / 3 m | chân 50 mm: 1 m / 2 m / 3 m |
|---|---|---|---|
| S300 (sim hook_150) | 0.337° (0.00588 rad) | 5.1 / 2.6 / 1.7 | 8.5 / 4.3 / 2.8 |
| 1440 tia / 360° | 0.25° (0.004363 rad) | 6.9 / 3.4 / 2.3 | 11.5 / 5.7 / 3.8 |
| 0.5° | 0.00873 rad | 3.4 / 1.7 / 1.1 | 5.7 / 2.9 / 1.9 |
Mỗi chân cần ít nhất `min_leg_points` tia (mặc định 2). **Chân xa** là chân giới hạn: nó cách lidar
khoảng (cạnh vào → lidar) + `cart_depth`. Với S300 sim và chân 30 mm, chân xa phải trong ~2.5 m, tức
cạnh vào cách lidar không quá ~1.8 m. Đứng xa hơn thì chân xa mất, chỉ còn 2 chân, không đủ
`min_legs: 3`.
**Không được có gì khác ở độ cao lidar** giữa và sát các chân: thanh giằng, tấm chắn, hàng thòng xuống.
Chân dính vào vật khác thành mép "dính", cụm đó bị loại. Mặt chân bóng (nhôm, inox) phản xạ gương làm
tia đi xuyên chỗ chân, xe thật bị loại: sơn mờ hoặc dán băng mờ ở `h_sensor ± 5 cm`.
## 3. Robot có chui lọt không
![Nhìn dọc hướng chui: khe hai bên, khe gầm, mặt quét lidar](fig/cart_section.svg)
Không có khoá config cho phần này. Sai ở đây thì không chỉnh phần mềm được.
**Khe hai bên:**
```
khe = (cart_opening − leg_width − bề_rộng_robot) / 2
còn cho controller = khe − sai_số_ngang − (dài_robot / 2) · sin(sai_số_yaw)
```
`tci_trolley` + `hook_150`: khe = (0.517 − 0.030 − 0.390) / 2 = **48.5 mm** mỗi bên. Với sai số dò
±1.5 cm, ±1°: còn 48.5 − 15 − 9 = **24.5 mm** cho controller. Dưới ~15 mm thì không nên chạy.
**Khe gầm:** đo `h_gầm` là điểm **thấp nhất** dưới sàn xe trên toàn bộ lối robot đi qua (tấm giữa,
thanh ngang, đầu bulông, hàng thòng xuống), không phải chỉ ở giữa xe. Phải cao hơn nóc robot ít nhất
~1 cm, trừ khi xe có khe dẫn hướng thiết kế riêng cho phần gồ trên nóc robot.
**Sàn trong lòng xe phải trống:** tấm đáy, ray, dây cáp giữa 4 chân sát sàn đều chặn robot. (Mesh
`tci_trolley` trong sim có một tấm đáy 0.78 × 0.613 × 0.01 m: robot đâm vào ở mép chân. Chạy thử chui
gầm trong sim bằng model `trolley_4legs` của gói.)
**`footprint_dock`** của marker trong `maker_sources.yaml` là hình chữ nhật **mép ngoài** 4 chân:
```
x = ±(cart_depth + leg_depth) / 2 y = ±(cart_opening + leg_width) / 2
tci_trolley: [[0.375,-0.2735],[0.375,0.2735],[-0.375,0.2735],[-0.375,-0.2735]]
```
Giữ `dock_anchor: center` cho marker xe hàng: đích nằm ở tâm xe.
## 4. Chiều chui và lidar: `entry_direction`, `scan_topic`
| `entry_direction` | Lidar dò (`scan_topic`) | Heading của `dock_target` |
|---|---|---|
| `forward` | lidar **trước** | trỏ **VÀO** xe: robot tiến thẳng vào gầm |
| `backward` | lidar **sau** | trỏ **RA** cạnh vào: robot lùi thẳng vào gầm |
- Lidar phải nhìn đúng hướng với `entry_direction`. Khai lệch thì action thất bại ngay ở scan đầu,
log `entry_direction forward but '/b_scan' ... faces backward`. Không bao giờ ghi một goal ngược.
- **Lidar gắn lộn ngược** (URDF có roll π, ví dụ hook_150) handler tự đọc từ TF, không cần khai gì.
Log lúc start: `mounted upside down: bearings mirrored`. Nếu driver tự lật dữ liệu về chiều thường thì
URDF phải bỏ roll π, không thì cả costmap cũng sai.
- Mặt quét nghiêng quá 5° so với `base_link` thì action thất bại (`scan plane ... is tilted`): mô hình
chân là 2D. Kiểm lại URDF hoặc giá lidar.
- Không có prior và không có dải `entry`, robot chui qua cạnh `cart_opening` **quay về phía nó**. Xe có
đầu/đuôi cố định thì điểm dò trên server phải nằm đúng phía cạnh vào. Đứng nhầm phía là robot chui
nhầm đầu xe mà không biết. Muốn chặn: dải `tape_legs: entry` (mục 6) hoặc prior yaw (mục 7).
## 5. Pose đích: `offset_x`, `offset_y`, `offset_yaw`
Mặc định `dock_target` = **tâm hình chữ nhật tâm 4 chân**, heading theo `entry_direction`. Để 0 cả ba
nếu robot cần dừng ở tâm xe (đúng với `dock_anchor: center`).
Robot cần dừng lệch tâm (chốt nâng, móc kéo không nằm giữa xe) thì đo từ tâm 4 chân tới điểm
`base_link` phải đứng, trong **hệ của xe**:
| Khoá | Đơn vị | Dương là |
|---|---|---|
| `offset_x` | m | dịch về phía **cạnh vào** (ra ngoài, về phía robot đứng dò). Âm = vào sâu hơn. |
| `offset_y` | m | sang **trái** khi đứng giữa xe nhìn ra cạnh vào. Robot tiến vào (`forward`) thì đó là bên **phải** của robot. |
| `offset_yaw` | rad | Bù xe lắp lệch nhỏ. Không dùng để lật hướng chui; việc đó là của `entry_direction`. |
## 6. Dải phản quang (tuỳ chọn)
Hình học 4 chân đối xứng: không biết đầu nào là đầu xe, và giá kệ, bàn 4 chân cùng kích thước cũng
khớp. Dải phản quang trên chân cho xe một "chữ ký".
| `tape_legs` | Dán ở | Được gì |
|---|---|---|
| `all` | cả 4 chân | Chỉ nhận vật có dải: loại bàn, kệ lẫn. Chân không đủ tia sáng bị loại ngay từ bước tách cụm. |
| `entry` | 2 chân **cạnh vào** | Như trên, cộng biết đầu nào là cạnh vào. Thấy dải ở cả hai đầu, hoặc không thấy dải nào, thì từ chối. |
- Băng phản quang **lăng kính**. Dán **quấn quanh chân**: tuỳ góc nhìn, lidar thấy một hoặc hai mặt
của chân.
- Phủ ít nhất `h_sensor ± 5 cm` theo chiều đứng (robot chúi 1° làm mặt quét lệch ~2.6 cm ở 1.5 m).
- `tape_min_points` [tia], mặc định 1: số tia sáng tối thiểu để một chân được coi là có dải.
- `tape_legs: entry` mà `tape_enabled: false` thì handler từ chối nạp.
**`tape_min_intensity`**: thang **riêng của từng cảm biến** (Gazebo trả `laser_retro`). Phải đo, không
chép từ profile khác:
1. Bật `tape_enabled: true` với một ngưỡng thử, đứng ở các chỗ sẽ bấm dò (gần, xa nhất, chếch ~30°).
2. Mỗi lượt dò handler in một dòng số tia sáng từng chân (khi `debug/detect: true`):
`bright rays per leg (entry-left, entry-right, far-left, far-right): 4 3 0 0 (tape_min_intensity 1000)`.
Đọc thêm cường độ thô: `rostopic echo -n1 /f_scan/intensities`.
3. Đặt ngưỡng ở **khoảng giữa** cường độ nền cao nhất (chân không dải, tường, kệ) và cường độ dải thấp
nhất. Khoảng cách quá hẹp thì đổi băng mạnh hơn.
## 7. Prior (tuỳ chọn): chọn đúng xe khi xe đỗ thành dãy
Mặc định **tắt**: robot đứng ở đâu cũng dò được, miễn thấy ≥ `min_legs` chân trong `max_range`. Handler
lấy xe điểm tin cao nhất. Hai xe điểm sát nhau ở hai chỗ thì từ chối cả lượt (`ambiguous`), không
đoán. Xe đỗ thành dãy sát nhau trong tầm lidar thì cần prior.
Prior khai trong `prior_frame` (mặc định `base_link`): xe **kỳ vọng** ở đâu khi robot đứng ở điểm dò.
| Khoá | Đơn vị | Ý nghĩa |
|---|---|---|
| `has_prior` | bool | Bật prior. |
| `prior_x`, `prior_y` | m | Tâm xe kỳ vọng trong `base_link`. Lùi vào: `prior_x` âm. |
| `prior_yaw` | rad | Hướng pháp tuyến cạnh vào **trỏ về robot**. Tiến vào ≈ 3.14159, lùi vào ≈ 0. |
| `prior_yaw_tolerance` | rad | Dung sai quanh `prior_yaw`. < π/2 thì còn dùng để chọn cạnh vào. π = không dùng yaw. |
| `search_radius` | m | Tâm xe xa prior hơn ngần này thì loại. |
| `search_fov` | rad | Nửa góc quạt quanh trục x của `prior_frame`. 0 = không giới hạn. |
**Cách đo prior**: lái robot tới đúng điểm dò trên server, để `has_prior: false`, `debug/detect: true`,
dò một lần. Log cho hai dòng:
```text
scan frame 'front_laser_link' in 'base_link': (0.454, 0.000) yaw 0.000 rad, ... ← (lx, ly, lψ)
cart at (1.218, 0.010) yaw -3.091 in 'front_laser_link' (upright view), ... ← (x, y, ψ)
```
```
prior_x = lx + x · cos lψ − y · sin lψ
prior_y = ly + x · sin lψ + y · cos lψ
prior_yaw = ψ + lψ (đưa về [−π, π])
```
Ví dụ trên: `prior_x = 1.672`, `prior_y = 0.010`, `prior_yaw = −3.091`.
**`search_radius`** phải lớn hơn sai số đặt điểm dò + độ xê dịch của xe khi người đẩy vào chỗ, và
**nhỏ hơn nửa khoảng tâm–tâm hai xe kề nhau**. Dãy bước 0.97 m → < 0.48 m. Hai điều kiện không cùng
thoả thì phải đặt điểm dò chính xác hơn.
`min_legs: 2` chỉ được khi bật prior: hai chân có nhiều cách ghép thành xe.
## 8. Khoá theo cảm biến và bộ lọc
Các khoá này nằm ngay dưới action, áp cho mọi profile.
| Khoá | Đơn vị | Mặc định code | Gợi ý chui gầm | Dùng khi |
|---|---|---|---|---|
| `scan_topic` | — | — | `/f_scan` | Topic `LaserScan` có trong sensor store của nav core; sai tên thì boot báo lỗi kèm danh sách topic. |
| `prior_frame` | — | `base_link` | `base_link` | Frame của `prior_*` và `search_fov`. |
| `min_range` | m | 0.10 | 0.10 | Bỏ tia trúng chính thân robot. |
| `max_range` | m | 3.0 | 3.0 | Tia xa hơn bị bỏ. Phải ≥ khoảng cách lidar → chân xa ở điểm dò xa nhất. Tăng không làm dò xa hơn (mục 2), chỉ thêm vật nhiễu. |
| `range_sigma` | m | 0.01 | đo | σ nhiễu range, làm trọng số khớp. Đo bên dưới. |
| `settle_delay` | s | 0.4 | 0.4 | Chờ xe đứng yên trước khi lấy mẫu. |
| `timeout` | s | 15.0 | 15.0 | Phải > `settle_delay + sample_window + hold_time`. |
| `sample_window` | s | 1.0 | 3.0 | Cửa sổ trượt của bộ lọc mẫu. |
| `min_samples` | mẫu | 5 | 5 | ≈ tần số scan × `sample_window` × 0.7, nhưng không cần lớn hơn ~10. |
| `max_spread_xy` | m | 0.03 | 0.02 | Độ tản tối đa của vị trí đích. Chặt hơn dock sạc vì khe hai bên chỉ vài cm. |
| `max_spread_yaw` | rad | 0.05 | 0.03 | Như trên, cho góc. |
| `jump_threshold` | m | 0.0 | 0.0 | Bật lọc cụm khi localization hay nhảy. 0 = tắt. |
| `debug/detect` | bool | true | true | Log `[debug]`: lý do chưa dò ra, kết quả khớp (1 Hz), tóm tắt lúc start. Log lỗi luôn in. |
Khoá trong profile, thường giữ mặc định:
| Khoá | Đơn vị | Mặc định | Chỉnh khi |
|---|---|---|---|
| `min_legs` | chân | 3 | 3 = chịu 1 chân bị che. 4 = khắt khe nhất. 2 chỉ với prior. |
| `min_leg_points` | tia | 2 | Hạ là dò xa hơn nhưng dễ nhận nhầm vật mảnh. |
| `min_confidence` | [0, 1] | 0.5 | Điểm = ½ · chân thấy / 4 + ½ · mức khớp. Nâng là khắt khe hơn. |
| `max_interior_points` | điểm | −1 (tắt) | Bật (ví dụ 3) khi lòng xe ở độ cao lidar chắc chắn trống: loại vật 4 chân có gì ở giữa. |
| `interior_margin` | m | 0.10 | Thu hình chữ nhật tâm chân trước khi đếm điểm lòng xe. |
| `ambiguity_margin` | [0, 1) | 0.15 | Hạng hai đạt ≥ (1 − số này) × điểm hạng nhất ở chỗ khác → từ chối. |
| `leg_assoc_radius` | m | 0.06 | Bán kính gán cụm vào góc dự đoán. |
| `shadow_min_angle`, `leg_cluster_gap`, `leg_min_depth_gap` | | 0.17 rad, 0.05 m, 0.15 m | Tách cụm; xem comment ở `leg_profile.h`. |
**Đo `range_sigma`**: robot đứng yên, lidar nhìn thẳng một tường phẳng cách 1–2 m. Lấy một tia trúng
tường (ví dụ tia giữa) trong 200 scan, tính độ lệch chuẩn:
```bash
rostopic echo -p -n 200 /f_scan/ranges[270] > /tmp/r.csv
LC_ALL=C awk -F, 'NR>1 {s+=$2; q+=$2*$2; n++} END {m=s/n; print "sigma =", sqrt(q/n-m*m), "m"}' /tmp/r.csv
```
`LC_ALL=C` là bắt buộc trên máy để locale tiếng Việt: không có nó `awk` đọc dấu chấm thập phân sai và
in `sigma = 0`. S300 sim cho ~0.0085 m.
## 9. Mẫu profile
```yaml
<tên_xe>:
# [m] Tâm–tâm hai chân của CẠNH VÀO (ngang hướng chui) — mục 1
cart_opening: 0.517
# [m] Tâm–tâm hai chân DỌC hướng chui
cart_depth: 0.720
# [m] Dung sai cạnh/đường chéo. Phải < |g − cart_opening| khi xe đỗ thành dãy
cart_dim_tolerance: 0.04
leg_shape: box # box | round — mục 2
leg_width: 0.030 # [m] đo ở đúng h_sensor
leg_width_tolerance: 0.02 # [m]
min_legs: 3 # 3 = chịu 1 chân bị che; 2 chỉ khi has_prior
max_interior_points: -1 # [điểm] -1 = tắt cổng lòng xe trống
min_confidence: 0.5 # [-] trong [0, 1]
tape_enabled: false # bật SAU khi đã đo tape_min_intensity — mục 6
tape_min_intensity: 1000.0 # [-] thang riêng của cảm biến, PHẢI ĐO
has_prior: false # bật khi xe đỗ thành dãy sát nhau — mục 7
prior_x: 1.70 # [m] tâm xe kỳ vọng trong base_link
prior_y: 0.0 # [m]
prior_yaw: 3.14159 # [rad] pháp tuyến cạnh vào trỏ về robot; tiến vào ≈ π
prior_yaw_tolerance: 0.35 # [rad]
search_radius: 0.40 # [m] < nửa khoảng tâm–tâm hai xe kề nhau
offset_x: 0.0 # [m] dương = về phía cạnh vào — mục 5
offset_y: 0.0 # [m]
offset_yaw: 0.0 # [rad]
```
Số trong mẫu là của `tci_trolley` + `hook_150`. Comment trong YAML viết tiếng Việt, ghi đơn vị và hệ
quả khi tăng/giảm.
## 10. Kiểm trên robot
Sau khi sửa YAML, khởi động lại nav rồi dò một lần. Log của handler:
```text
[trolley_detection] 'detect_trolley': 1 profile(s), default 'tci_trolley', scan '/f_scan', entry_direction forward, prior_frame 'base_link', range [0.10, 3.00] m, sigma 0.010 m, debug/detect on.
[trolley_detection][debug] 'detect_trolley': detecting profile 'tci_trolley' (cart 0.517 x 0.720 m, leg box 0.030 m, min_legs 3, tape off/all, offset_yaw 0.000, prior off in 'base_link') on '/f_scan', entry forward -> 'dock_target'.
[trolley_detection][debug] 'detect_trolley': scan frame 'front_laser_link' in 'base_link': (0.454, 0.000) yaw 0.000 rad, tilt 0.000 rad, mounted upside down: bearings mirrored.
[trolley_detection][debug] 'detect_trolley': cart at (1.218, 0.010) yaw -3.091 in 'front_laser_link' (upright view), legs seen 4 (partial 0, occluded 0, out of view 0), measured 0.516 x 0.731 m, fit rms 0.0078 m, confidence 1.00.
[move_base2] action '...-DetectTrolley': 'dock_target' from 5 detection(s) of profile 'tci_trolley' after 0.85 s
```
- Dòng đầu (lúc boot) xác nhận số đã nạp. Dòng thứ hai xác nhận profile được chọn.
- Dòng `scan frame` cho vị trí lidar trong `base_link` và cách gắn: đúng URDF chưa, có lộn ngược không.
- Dòng `cart at` cho kích thước robot **đo được** (`measured`). Lệch số khai quá ~1 cm ở nhiều vị trí
dò khác nhau thì đo lại xe. `fit rms` cỡ `range_sigma` là bình thường.
Khi dò không ra, lý do trong log chỉ đúng cổng đã chặn:
| Log chứa | Nghĩa là | Xử trí |
|---|---|---|
| `leg-like cluster(s) — ... attached to a surface, ... wrong width, ... too few rays` | không đủ cụm giống chân | `wrong width`: sai `leg_width`/`leg_shape` (log in độ lệch gần nhất). `too few rays`: đứng quá xa (mục 2). `attached`: chân dính vật khác. |
| `no pair spaced like the cart (... closest pair misses by ...)` | có chân, không cặp nào đúng kích thước | Sai `cart_opening`/`cart_depth`, hoặc xe ngoài tầm. Log in độ lệch của cặp gần đúng nhất. |
| `too few legs`: `N leg(s) seen, ... occluded, ... out of view (min_legs 3)` | thấy chưa đủ chân | Chân xa ngoài `max_range` hoặc ngoài góc quét; vật che. Tiến lại gần hoặc đứng thẳng hơn. |
| `leg position(s) seen straight through (leg_missing)` | tia đi xuyên chỗ một chân phải đứng | Không phải xe (vật có 3 chân + tường), hoặc chân bóng phản xạ gương. |
| `two legs ... apart where the cart has ...` | sau khi khớp, một cặp chân sai khoảng cách | Chân của hai xe kề nhau ghép nhầm; giảm `cart_dim_tolerance` hoặc bật prior. |
| `scan point(s) inside the cart` | lòng xe có vật | Chỉ khi bật `max_interior_points`. |
| `entry_tape_not_seen` / `entry_tape_ambiguous` | dải `entry` không thấy / thấy cả hai đầu | Dải bẩn, ngưỡng cao, dán nhầm chân. |
| `requires reflective tape but the scan has no intensity data` | profile đòi dải, scan không có cường độ | Driver không publish `intensities`. |
| `outside the search gate` / `from the prior` | đúng xe, ngoài vùng prior | Robot không đứng ở điểm dò như lúc đo prior; nới `search_radius` hoặc đo lại prior. |
| `ambiguous: two carts score ...` | hai xe điểm sát nhau | Bật prior (mục 7). |
| `confidence ... < min_confidence` | khớp kém | Xe méo, số đo sai, hoặc vật khác. |
| `entry_direction ... faces ...` | lidar nhìn ngược chiều chui | Sửa `scan_topic` hoặc `entry_direction`. |
| `scan plane ... is tilted` | mặt quét nghiêng > 5° | Kiểm URDF / giá lidar. |
| `detections unstable` / `detected the trolley only N time(s)` | mẫu không chụm / dò quá thưa | Robot còn rung, vật thứ hai giống xe trong tầm, hoặc `min_samples` quá lớn so với tần số scan. |
**Đo sai số thật dưới gầm.** Sau `Goal reached`, đo khe từ hông robot tới mặt trong từng chân: trái
trước `L_t`, trái sau `L_s`, phải trước `R_t`, phải sau `R_s` ("trước" là cặp chân phía đầu robot):
```
lệch ngang (dương = robot lệch TRÁI) = ((R_t + R_s) − (L_t + L_s)) / 4
lệch yaw (dương = đầu robot quay TRÁI) = ((R_t − R_s) − (L_t − L_s)) / (2 · cart_depth) [rad]
```
Lệch dọc: đo từ mép đầu robot tới đường tâm cặp chân trước, so với (dài_robot − `cart_depth`) / 2
(hook_150: 0.156 m). Mục tiêu: ngang ±1.5 cm, yaw ±1°, dọc ±3 cm.
Robot hay dừng **thiếu** một chút vì controller dừng ngay khi vào `xy_goal_tolerance` của planner
docking (sim: 1–1.5 cm với 0.015). Lệch dọc luôn cùng dấu thì đó là nguyên nhân, không phải bộ dò.
## Checklist
- [ ] Cạnh vào đã chọn; `cart_opening`, `cart_depth` đo tâm–tâm ở `h_sensor`, đường chéo khớp.
- [ ] `leg_shape`, `leg_width` (`leg_depth`) đo bằng thước kẹp ở `h_sensor`.
- [ ] Khe hai bên còn ≥ ~15 mm sau khi trừ sai số; khe gầm ≥ ~1 cm; lòng xe sát sàn trống.
- [ ] `footprint_dock` trong `maker_sources.yaml` = mép ngoài 4 chân.
- [ ] `entry_direction` khớp lidar trong `scan_topic`; log `scan frame` đúng URDF.
- [ ] Điểm dò trên server ở đúng phía cạnh vào, cạnh vào cách lidar ≤ tầm cho phép (mục 2).
- [ ] Xe đỗ thành dãy: `cart_dim_tolerance < |g − cart_opening|`, prior đã đo và bật.
- [ ] Dải phản quang (nếu dùng): đúng chân, phủ `h_sensor ± 5 cm`, `tape_min_intensity` đo bằng cảm biến thật.
- [ ] Khởi động lại nav; log `cart at ... measured` khớp số đo trong ~1 cm.
- [ ] Đo khe dưới gầm: ngang ±1.5 cm, yaw ±1°, dọc ±3 cm.

2115
doc/fig/cart_section.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 68 KiB

2260
doc/fig/cart_top.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 70 KiB

1766
doc/fig/leg_measure.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 55 KiB

166
doc/gen_fig.py Normal file
View File

@@ -0,0 +1,166 @@
# -*- coding: utf-8 -*-
"""Sinh hinh cho doc/MEASURE_AND_CONFIGURE.md. Moi hinh ve tu SO THAT cua tci_trolley + hook_150.
Chay: python3 doc/gen_fig.py (ghi ra doc/fig/*.svg)
"""
import math
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch, Rectangle
plt.rcParams['font.family'] = 'DejaVu Sans'
plt.rcParams['font.size'] = 9
plt.rcParams['svg.fonttype'] = 'path' # nhung chu thanh duong -> khong phu thuoc font may in
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fig')
INK, ACC, WARN, MUT = '#1b2733', '#1f6feb', '#c9401a', '#7d8996'
GRID, TAPE = '#dfe4ea', '#e0b000'
# tci_trolley (factory_ss_demo) + hook_150, [m]
D, O, W = 0.720, 0.517, 0.030 # cart_depth, cart_opening, leg_width
RW, RL, RTOP = 0.390, 1.031, 0.3595 # robot width, length, top
LIDAR_X, H_SENSOR = 0.454, 0.184 # lidar ahead of base_link, scan plane height
H_DECK = 0.380 # example deck underside (sim model trolley_4legs)
def save(fig, name):
os.makedirs(OUT, exist_ok=True)
fig.savefig(os.path.join(OUT, name), format='svg', bbox_inches='tight', transparent=True)
plt.close(fig)
print(' ', name)
def frame(ax, xlim, ylim, title=None):
ax.set_xlim(*xlim)
ax.set_ylim(*ylim)
ax.set_aspect('equal')
ax.grid(True, color=GRID, lw=0.5, zorder=0)
for s in ('top', 'right'):
ax.spines[s].set_visible(False)
for s in ('left', 'bottom'):
ax.spines[s].set_color(MUT)
ax.tick_params(colors=MUT, labelsize=7)
if title:
ax.set_title(title, color=INK, fontsize=10, pad=8)
def arrow(ax, p, q, color=ACC, lw=1.4, style='-|>', ms=9):
ax.add_patch(FancyArrowPatch(p, q, arrowstyle=style, mutation_scale=ms, color=color, lw=lw,
zorder=6, shrinkA=0, shrinkB=0))
def dim(ax, p, q, text, offset=(0, 0), color=INK, rot=0):
arrow(ax, p, q, color=color, lw=0.9, style='<|-|>', ms=7)
mx, my = (p[0] + q[0]) / 2 + offset[0], (p[1] + q[1]) / 2 + offset[1]
ax.text(mx, my, text, color=color, fontsize=8, ha='center', va='center', rotation=rot,
bbox=dict(fc='white', ec='none', alpha=0.85, pad=1.2), zorder=7)
def leg(ax, x, y, taped=False, w=W):
ax.add_patch(Rectangle((x - w / 2, y - w / 2), w, w, fc=TAPE if taped else INK, ec=INK, lw=0.6,
zorder=5))
def cart_top():
"""Nhin tu tren xuong: kich thuoc, canh vao, dich ra va heading."""
fig, ax = plt.subplots(figsize=(9.4, 4.4))
frame(ax, (-0.75, 2.40), (-0.62, 0.62), 'Xe hàng 4 chân nhìn từ trên xuống (số của tci_trolley)')
corners = [(D / 2, O / 2), (D / 2, -O / 2), (-D / 2, O / 2), (-D / 2, -O / 2)]
for x, y in corners:
leg(ax, x, y)
# sàn xe (mờ)
ax.add_patch(Rectangle((-D / 2 - 0.03, -O / 2 - 0.03), D + 0.06, O + 0.06, fc='none', ec=MUT,
lw=0.8, ls=':', zorder=2))
# cạnh vào
ax.plot([D / 2, D / 2], [-O / 2, O / 2], color=ACC, lw=2.2, alpha=0.35, zorder=3)
ax.text(D / 2 + 0.03, 0.0, 'CẠNH VÀO', color=ACC, fontsize=8, rotation=90, ha='left',
va='center')
# kích thước
dim(ax, (D / 2 + 0.17, -O / 2), (D / 2 + 0.17, O / 2), 'cart_opening\n0.517', offset=(0.12, 0))
dim(ax, (-D / 2, -O / 2 - 0.12), (D / 2, -O / 2 - 0.12), 'cart_depth 0.720')
ax.plot([-D / 2, D / 2], [O / 2, -O / 2], color=MUT, lw=0.8, ls='--', zorder=3)
ax.text(-0.17, 0.16, 'đường chéo 0.886', color=MUT, fontsize=7.5, rotation=-35)
# tâm + heading
ax.plot([0], [0], marker='+', ms=12, mew=2, color=WARN, zorder=7)
arrow(ax, (0, 0), (-0.30, 0), color=WARN)
ax.text(-0.30, 0.05, 'forward:\nheading VÀO xe', color=WARN, fontsize=7.5, ha='center',
va='bottom')
arrow(ax, (0, 0), (0.25, 0), color=WARN, lw=1.0)
ax.text(0.20, 0.05, 'backward:\nRA cạnh vào', color=WARN, fontsize=7.5, ha='center',
va='bottom')
ax.text(0.0, -0.09, 'dock_target = tâm 4 chân + offset', color=WARN, fontsize=7.5,
ha='center', va='top', bbox=dict(fc='white', ec='none', alpha=0.85, pad=1.0))
# robot đứng dò, tiến vào (forward)
rc = D / 2 + 1.00 + LIDAR_X # cạnh vào cách lidar 1.0 m
ax.add_patch(Rectangle((rc - RL / 2, -RW / 2), RL, RW, fc='none', ec=INK, lw=1.0, zorder=4))
ax.plot([rc - LIDAR_X], [0], marker='o', ms=6, color=ACC, zorder=6)
ax.text(rc - LIDAR_X, 0.06, 'lidar trước', color=ACC, fontsize=7.5, ha='center')
ax.plot([rc], [0], marker='+', ms=8, color=INK)
ax.text(rc, -0.07, 'base_link', color=INK, fontsize=7.5, ha='center')
arrow(ax, (rc + 0.35, 0.30), (rc - 0.25, 0.30), color=INK, lw=1.0)
ax.text(rc + 0.05, 0.36, 'robot tiến vào', color=INK, fontsize=7.5, ha='center')
ax.set_xlabel('[m]', color=MUT, fontsize=7)
save(fig, 'cart_top.svg')
def leg_measure():
"""Đo tâm–tâm chân bằng hai lần đo mép."""
fig, ax = plt.subplots(figsize=(6.4, 3.2))
frame(ax, (-0.42, 0.42), (-0.16, 0.16), 'Đo tâm–tâm hai chân: không chấm được tâm thì đo hai mép')
big = 0.06 # vẽ chân to gấp đôi cho dễ nhìn; số ghi là số thật
for y in (-O / 2, O / 2):
ax.add_patch(Rectangle((y - big / 2, -big / 2), big, big, fc=INK, ec=INK, zorder=5))
dim(ax, (-O / 2 - big / 2, 0.10), (O / 2 + big / 2, 0.10), 'a = mép NGOÀI – mép ngoài')
dim(ax, (-O / 2 + big / 2, -0.10), (O / 2 - big / 2, -0.10), 'b = mép TRONG – mép trong')
dim(ax, (-O / 2, 0.0), (O / 2, 0.0), 'tâm–tâm = (a + b) / 2', color=WARN)
ax.text(0, -0.145, 'chân vẽ phóng to; cùng công thức cho chân tròn. bề rộng chân = (a − b) / 2',
color=MUT, fontsize=7.5, ha='center')
ax.set_yticks([])
save(fig, 'leg_measure.svg')
def cart_section():
"""Nhìn dọc hướng chui: khe hai bên, khe gầm, mặt quét lidar, dải phản quang."""
fig, ax = plt.subplots(figsize=(8.4, 4.8))
frame(ax, (-0.62, 0.62), (-0.03, 0.52), 'Nhìn dọc hướng chui (cạnh vào) — robot hook_150 dưới gầm')
ax.plot([-0.62, 0.62], [0, 0], color=INK, lw=1.4)
ax.text(0.60, 0.008, 'sàn', color=MUT, fontsize=7.5, ha='right', va='bottom')
for y in (-O / 2, O / 2):
ax.add_patch(Rectangle((y - W / 2, 0), W, H_DECK, fc=INK, ec=INK, zorder=4))
ax.add_patch(Rectangle((y - W / 2 - 0.004, H_SENSOR - 0.05), W + 0.008, 0.10, fc=TAPE,
ec='none', zorder=5))
ax.add_patch(Rectangle((-O / 2 - 0.03, H_DECK), O + 0.06, 0.02, fc=MUT, ec=INK, lw=0.6,
zorder=4))
ax.text(-0.30, H_DECK + 0.035, 'sàn xe — mặt dưới thấp nhất trên lối robot: h_gầm', color=INK,
fontsize=7.5, ha='left')
# robot: thân + gồ trên nóc
ax.add_patch(Rectangle((-RW / 2, 0.02), RW, 0.31, fc='#eef2f6', ec=INK, lw=1.0, zorder=3))
ax.add_patch(Rectangle((-0.12, 0.33), 0.24, RTOP - 0.33, fc='#eef2f6', ec=INK, lw=1.0,
zorder=3))
ax.text(0, 0.10, 'robot\nrộng 0.390', color=INK, fontsize=8, ha='center')
ax.text(0.13, RTOP - 0.012, 'nóc 0.3595', color=INK, fontsize=7, ha='left', va='top')
# mặt quét
ax.plot([-0.62, 0.62], [H_SENSOR, H_SENSOR], color=ACC, lw=1.0, ls='--', zorder=6)
ax.text(-0.61, H_SENSOR + 0.008, 'mặt quét lidar\nh_sensor = 0.184', color=ACC, fontsize=7.5)
ax.text(O / 2 + 0.03, H_SENSOR, 'dải phản quang\nh_sensor ± 5 cm', color='#8a6d00',
fontsize=7, va='center')
# khe hai bên
gap = (O - W - RW) / 2
dim(ax, (RW / 2, 0.26), (O / 2 - W / 2, 0.26), '', color=WARN)
ax.text(RW / 2 - 0.005, 0.26, 'khe hai bên %.1f mm' % (gap * 1000), color=WARN, fontsize=7.5,
ha='right', va='center')
dim(ax, (0.0, RTOP), (0.0, H_DECK), '', color=WARN)
ax.annotate('khe gầm = h_gầm − nóc robot', xy=(0.005, (RTOP + H_DECK) / 2), xytext=(0.30, 0.47),
color=WARN, fontsize=7.5, arrowprops=dict(arrowstyle='-', color=WARN, lw=0.7))
ax.set_xlabel('[m] ngang hướng chui', color=MUT, fontsize=7)
save(fig, 'cart_section.svg')
if __name__ == '__main__':
print('fig ->', OUT)
cart_top()
leg_measure()
cart_section()

45
package.xml Normal file
View File

@@ -0,0 +1,45 @@
<package>
<name>trolley_detection_action</name>
<version>0.1.0</version>
<description>
Handler dò xe hàng 4 chân từ scan LiDAR THÔ, nạp qua Boost.DLL như mọi action handler khác
(`action_core::ActionHandler`).
Đây là tầng ADAPTER: chỗ duy nhất trong chuỗi dò được biết tới TF, action và kho cảm biến. Lõi
hình học (`dock_pattern_detector::LegPatternMatcher`) không biết gì về chúng, nên test được bằng
scan dựng sẵn.
Cùng hợp đồng đầu ra với `DockPatternActionHandler`: ghi một TF tĩnh vào `output_frame`, nên
chặng `move_to` sau nó, `DockPlanner` và `mission_adapters` không phải sửa. Heading của đích
theo cách robot chui gầm (`entry_direction`: tiến hoặc lùi).
</description>
<author>DuongTD</author>
<maintainer email="tdd@gmail.com">DuongTD</maintainer>
<license>BSD</license>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>action_core</build_depend>
<run_depend>action_core</run_depend>
<build_depend>dock_pattern_detector</build_depend>
<run_depend>dock_pattern_detector</run_depend>
<build_depend>robot_line_extraction</build_depend>
<run_depend>robot_line_extraction</run_depend>
<build_depend>robot_sensor_ports</build_depend>
<run_depend>robot_sensor_ports</run_depend>
<build_depend>robot_cpp</build_depend>
<run_depend>robot_cpp</run_depend>
<build_depend>robot_sensor_msgs</build_depend>
<run_depend>robot_sensor_msgs</run_depend>
<build_depend>tf3</build_depend>
<run_depend>tf3</run_depend>
<build_depend>yaml-cpp</build_depend>
<run_depend>yaml-cpp</run_depend>
</package>

View File

@@ -0,0 +1,916 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* trolley_detection_action — handler dò xe hàng 4 chân từ LiDAR: scan thô -> tư thế xe -> frame
* đích ổn định cho robot chui gầm.
*
* Author: DuongTD
*********************************************************************/
#include <action_core/action_handler.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <action_core/action_abi.h>
#include <yaml-cpp/yaml.h>
#include <robot/robot.h>
#include <robot_sensor_msgs/LaserScan.h>
#include <tf3/buffer_core.h>
#include <action_core/pose_sample_filter.h>
#include <dock_pattern_detector/leg_pattern_matcher.h>
#include <robot_sensor_ports/sensor_reader.h>
#include <robot_sensor_ports/sensor_types.h>
// ================================================================================================
// NGUỒN GỐC: phần kiểm lúc boot, chọn profile, update/pause/resume/cancel, bộ lọc, đọc scan theo
// cursor, giữ phép dò chờ TF, noteReason/failOnTimeout/publish được CHÉP từ
// `dock_pattern_action/plugins/dock_pattern_action_handler.cpp` (commit 5bbcf37). Sửa lỗi ở phần
// chung bên nào thì xem lại bên kia — hai handler lệch nhau âm thầm là thứ khó bắt nhất.
// ================================================================================================
namespace action_core
{
namespace
{
constexpr double kDefaultSettleDelay = 0.4; // [s]
constexpr double kDefaultTimeout = 15.0; // [s]
constexpr double kDefaultMinRange = 0.10; // [m]
constexpr double kDefaultMaxRange = 3.0; // [m]
constexpr double kDefaultRangeSigma = 0.01; // [m]
/// Chu kỳ in lý do chưa dò ra / kết quả khớp. Control loop ~30 Hz; log mỗi cycle sẽ ngập log và làm
/// chậm chính vòng điều khiển. 1 Hz đủ để đọc xem đang hỏng ở cổng nào.
constexpr double kReasonLogPeriod = 1.0; // [s]
/// Mặt phẳng quét được nghiêng tối đa bao nhiêu so với mặt sàn của `prior_frame`. Bộ dò coi scan là
/// 2D: nghiêng t làm cự ly ngang sai r·(1 − cos t) — 5° ở 2.3 m là 9 mm, đã sát D6 (±1.5 cm). Quá
/// ngưỡng nghĩa là URDF sai hoặc lidar gắn lệch; dừng thay vì ghi một đích lệch.
constexpr double kMaxScanTilt = 0.0873; // [rad] 5°
/// @brief Hướng trục x của frame (atan2(R10, R00)). Đúng cả khi frame lộn ngược: lật quanh trục x
/// giữ nguyên trục x.
double yawOf(const tf3::QuaternionMsg& q)
{
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
}
/// @brief R22 của phép quay: trục z của frame chiếu lên trục z của frame cha. Âm = lộn ngược.
double upAxisZ(const tf3::QuaternionMsg& q)
{
return 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
}
double wrapAngle(double a)
{
return std::atan2(std::sin(a), std::cos(a));
}
/// @brief Robot chui gầm bằng đầu nào — quyết heading của goal.
enum class EntryDirection
{
kForward, ///< tiến vào: lidar trước dò, heading goal trỏ VÀO xe
kBackward ///< lùi vào: lidar sau dò, heading goal trỏ RA cạnh vào
};
const char* toString(EntryDirection d)
{
return d == EntryDirection::kForward ? "forward" : "backward";
}
} // namespace
/**
* @class TrolleyDetectionActionHandler
* @brief Dò xe hàng 4 chân trong scan LiDAR thô, lọc, ghi ra một frame đích ổn định.
*
* Cùng hợp đồng đầu ra với `DockPatternActionHandler` và `FrameSamplerActionHandler`: ghi một TF
* TĨNH vào `output_frame`, nên chặng `move_to` sau nó, `DockPlanner` và `mission_adapters` không
* đổi dòng nào. Khác ở bộ dò: `LegPatternMatcher` tìm 4 chân thay vì một biên dạng.
*
* ## Đích ghi ra
*
* Vị trí = tâm hình chữ nhật tâm chân + offset của profile. Heading theo `entry_direction`:
* - `forward`: pháp tuyến cạnh vào + π — trỏ VÀO xe, robot tiến thẳng vào.
* - `backward`: pháp tuyến cạnh vào — trỏ RA cạnh vào, robot lùi thẳng vào.
*
* Lidar của `scan_topic` phải nhìn đúng hướng với `entry_direction` (kiểm ở scan đầu mỗi lượt).
* Khai lệch hai khoá là goal ngược 180°, robot chui sai đầu xe — nên lệch thì `kFailed` ngay.
*
* ## Lidar gắn lộn ngược
*
* Tự suy từ TF `prior_frame` <- frame scan, không có khoá cấu hình: trục z của frame scan chỉ xuống
* (hook_150: roll π) thì tia ở góc θ trong frame lidar nằm ở góc −θ khi nhìn từ trên xuống. Handler
* đảo dấu `angle_min`/`angle_increment` trước khi dò, nên matcher làm việc trong frame "đứng thẳng"
* cùng gốc, cùng trục x với lidar. Driver không lật dữ liệu; nếu sau này driver lật thì URDF phải bỏ
* roll π — không thì costmap cũng sai — nên TF luôn là nguồn đúng. Mặt quét nghiêng quá
* `kMaxScanTilt` thì `kFailed`.
*
* ## Cấu hình
*
* - `action_types`, `output_frame`, `scan_topic`, `settle_delay`, `timeout`, `default_profile`,
* `profile_param_key` — cùng nghĩa với `dock_pattern`.
* - `prior_frame` [string] frame của `prior_*` và `search_fov` (mặc định `base_link`)
* - `entry_direction` [string] `forward` / `backward`
* - `min_range`, `max_range` [m], `range_sigma` [m]
* - `debug/detect` [bool] log lý do chưa dò ra, kết quả khớp, tóm tắt lúc start
* - `profiles/<tên>/...` khoá của `LegProfile`
* - cộng toàn bộ khoá của @ref PoseSampleFilterConfig
*/
class TrolleyDetectionActionHandler final : public ActionHandler
{
public:
TrolleyDetectionActionHandler() = default;
static ActionHandler::Ptr create()
{
return std::make_shared<TrolleyDetectionActionHandler>();
}
bool configure(const std::string& name, const ActionContext& ctx,
robot::NodeHandle& nh) override
{
name_ = name;
ctx_ = ctx;
if (ctx_.tf == nullptr)
{
robot::log_error("[trolley_detection] '%s': needs a TF buffer but the context has none.",
name_.c_str());
return false;
}
if (ctx_.sensors == nullptr)
{
// Handler này đọc scan THÔ. Không có kho thì nó vô nghĩa — từ chối lúc nạp để lỗi lộ khi
// khởi động, không phải khi order đầu tiên tới giữa ca.
robot::log_error("[trolley_detection] '%s': needs the shared sensor store but the context "
"has none. Declare sensor_store/sensors in the runtime config.",
name_.c_str());
return false;
}
nh.param("action_types", action_types_, std::vector<std::string>{});
nh.param("output_frame", output_frame_, std::string());
nh.param("scan_topic", scan_topic_, std::string());
nh.param("settle_delay", settle_delay_, kDefaultSettleDelay);
nh.param("timeout", timeout_, kDefaultTimeout);
nh.param("default_profile", default_profile_, std::string());
nh.param("profile_param_key", profile_param_key_, std::string("trolley_profile"));
nh.param("prior_frame", prior_frame_, std::string("base_link"));
nh.param("min_range", limits_.min_range, kDefaultMinRange);
nh.param("max_range", limits_.max_range, kDefaultMaxRange);
nh.param("range_sigma", limits_.range_sigma, kDefaultRangeSigma);
std::string direction = "forward";
nh.param("entry_direction", direction, direction);
robot::NodeHandle debug_nh(nh, "debug");
debug_nh.param("detect", debug_detect_, true);
if (action_types_.empty())
{
robot::log_error("[trolley_detection] '%s': action_types is empty — never called.",
name_.c_str());
return false;
}
if (output_frame_.empty())
{
robot::log_error("[trolley_detection] '%s': output_frame is empty — the result would go "
"nowhere.",
name_.c_str());
return false;
}
if (scan_topic_.empty())
{
robot::log_error("[trolley_detection] '%s': scan_topic is empty.", name_.c_str());
return false;
}
if (prior_frame_.empty())
{
robot::log_error("[trolley_detection] '%s': prior_frame is empty.", name_.c_str());
return false;
}
if (direction == "forward")
{
entry_direction_ = EntryDirection::kForward;
}
else if (direction == "backward")
{
entry_direction_ = EntryDirection::kBackward;
}
else
{
robot::log_error("[trolley_detection] '%s': entry_direction '%s' is not 'forward' or "
"'backward'.",
name_.c_str(), direction.c_str());
return false;
}
// Gõ sai tên topic là lỗi phổ biến nhất, và triệu chứng của nó GIỐNG HỆT cảm biến chết: dò mãi
// không ra. Bắt lúc boot và in ra danh sách topic có thật.
if (!robot_sensor_ports::has<robot_sensor_msgs::LaserScan>(*ctx_.sensors, scan_topic_))
{
std::string known;
for (const robot_sensor_ports::SensorInfo& info : ctx_.sensors->inventory())
{
known += (known.empty() ? "" : ", ") + info.topic + " (" + info.data_type + ")";
}
robot::log_error("[trolley_detection] '%s': scan_topic '%s' is not a LaserScan in the "
"sensor store. Declared topics: %s",
name_.c_str(), scan_topic_.c_str(),
known.empty() ? "(none)" : known.c_str());
return false;
}
if (!std::isfinite(settle_delay_) || settle_delay_ < 0.0)
{
robot::log_error("[trolley_detection] '%s': settle_delay=%.3f must be finite and >= 0.",
name_.c_str(), settle_delay_);
return false;
}
if (!std::isfinite(limits_.min_range) || !std::isfinite(limits_.max_range) ||
limits_.min_range < 0.0 || limits_.max_range <= limits_.min_range)
{
robot::log_error("[trolley_detection] '%s': need 0 <= min_range < max_range [m] (got %.3f, "
"%.3f).",
name_.c_str(), limits_.min_range, limits_.max_range);
return false;
}
if (!std::isfinite(limits_.range_sigma) || limits_.range_sigma <= 0.0)
{
robot::log_error("[trolley_detection] '%s': range_sigma=%.4f must be finite and > 0 [m].",
name_.c_str(), limits_.range_sigma);
return false;
}
if (!loadProfiles(nh) || !loadFilter(nh))
{
return false;
}
// Dòng tóm tắt lúc boot: chỗ duy nhất xác nhận được giá trị đã nạp mà không mở YAML trên robot.
robot::log_info("[trolley_detection] '%s': %zu profile(s), default '%s', scan '%s', "
"entry_direction %s, prior_frame '%s', range [%.2f, %.2f] m, sigma %.3f m, "
"debug/detect %s.",
name_.c_str(), profiles_.size(), default_profile_.c_str(),
scan_topic_.c_str(), toString(entry_direction_), prior_frame_.c_str(),
limits_.min_range, limits_.max_range, limits_.range_sigma,
debug_detect_ ? "on" : "off");
return true;
}
std::vector<std::string> supportedActionTypes() const override
{
return action_types_;
}
bool start(const robot_protocol_msgs::Action& action, const robot::Time& now) override
{
started_at_ = now;
paused_ = false;
action_id_ = action.actionId;
scan_cursor_ = 0;
pending_valid_ = false;
last_reason_.clear();
have_reason_log_ = false;
have_match_log_ = false;
detections_ = 0;
tape_reported_ = false;
prior_tf_valid_ = false;
prior_tf_frame_.clear();
scan_flipped_ = false;
mount_error_.clear();
std::string profile_name = default_profile_;
const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(),
[this](const robot_protocol_msgs::ActionParameter& p) {
return p.key == profile_param_key_;
});
if (it != action.actionParameters.end() && !it->value.empty())
{
profile_name = it->value;
}
const auto found = profiles_.find(profile_name);
if (found == profiles_.end())
{
// KHÔNG âm thầm rơi về default: dùng nhầm hình học là chui vào sai chỗ.
std::string known;
for (const auto& entry : profiles_)
{
known += (known.empty() ? "" : ", ") + entry.first;
}
robot::log_error("[trolley_detection] '%s': action '%s' asked for profile '%s' which does "
"not exist. Known profiles: %s",
name_.c_str(), action.actionId.c_str(), profile_name.c_str(),
known.empty() ? "(none)" : known.c_str());
return false;
}
std::string error;
if (!matcher_.configure(found->second, error))
{
robot::log_error("[trolley_detection] '%s': profile '%s' is invalid: %s", name_.c_str(),
profile_name.c_str(), error.c_str());
return false;
}
profile_name_ = profile_name;
filter_.reset();
filter_.setLabels(scan_topic_, ctx_.global_frame);
if (debug_detect_)
{
const dock_pattern_detector::LegProfile& p = found->second;
robot::log_info("[trolley_detection][debug] '%s': detecting profile '%s' (cart %.3f x %.3f m, "
"leg %s %.3f m, min_legs %d, tape %s/%s, offset_yaw %.3f, prior %s in '%s') "
"on '%s', entry %s -> '%s'.",
name_.c_str(), profile_name.c_str(), p.cart_opening, p.cart_depth,
dock_pattern_detector::toString(p.leg_shape), p.leg_width, p.min_legs,
p.tape_enabled ? "on" : "off", dock_pattern_detector::toString(p.tape_legs),
p.offset_yaw, p.has_prior ? "on" : "off", prior_frame_.c_str(),
scan_topic_.c_str(), toString(entry_direction_), output_frame_.c_str());
}
return true;
}
ActionTick update(const robot::Time& now) override
{
ActionTick tick;
const double elapsed = (now - started_at_).toSec(); // [s]
// Robot vừa dừng vẫn còn dao động cơ khí; scan lúc này mang theo dao động đó.
if (elapsed >= settle_delay_)
{
processNewScan(now);
}
if (!mount_error_.empty())
{
tick.status = ActionStatus::kFailed;
tick.message = "action '" + action_id_ + "': " + mount_error_;
return tick;
}
if (filter_.holdSatisfied(now))
{
if (!publish(filter_.holdPose(), now))
{
tick.status = ActionStatus::kFailed;
tick.message = "action '" + action_id_ + "': could not publish '" + output_frame_ + "'";
return tick;
}
tick.status = ActionStatus::kSucceeded;
tick.message = "action '" + action_id_ + "': '" + output_frame_ + "' from " +
std::to_string(filter_.windowSize()) + " detection(s) of profile '" +
profile_name_ + "' after " + formatSeconds(elapsed) + " s";
return tick;
}
if (timeout_ > 0.0 && elapsed >= timeout_)
{
return failOnTimeout(elapsed);
}
tick.status = ActionStatus::kRunning;
return tick;
}
/// @brief Tạm dừng: ghi mốc để resume() dịch started_at_ — quãng đứng không tính vào timeout.
void pause(const robot::Time& now) override
{
if (!paused_)
{
paused_ = true;
paused_at_ = now;
}
}
void resume(const robot::Time& now) override
{
if (paused_)
{
started_at_ += (now - paused_at_);
paused_ = false;
}
}
void cancel() override
{
filter_.reset();
scan_cursor_ = 0;
pending_valid_ = false;
}
private:
// ==============================================================================================
// Nạp cấu hình
// ==============================================================================================
bool loadProfiles(robot::NodeHandle& nh)
{
YAML::Node node;
if (!nh.getParam("profiles", node) || !node.IsMap() || node.size() == 0)
{
robot::log_error("[trolley_detection] '%s': no 'profiles' map — nothing to detect.",
name_.c_str());
return false;
}
profiles_.clear();
for (const auto& entry : node)
{
const std::string profile_name = entry.first.as<std::string>();
robot::NodeHandle p_nh(nh, "profiles/" + profile_name);
dock_pattern_detector::LegProfile profile;
std::string error;
nh_param(p_nh, "cart_opening", profile.cart_opening);
nh_param(p_nh, "cart_depth", profile.cart_depth);
nh_param(p_nh, "cart_dim_tolerance", profile.cart_dim_tolerance);
std::string shape_name = dock_pattern_detector::toString(profile.leg_shape);
nh_param(p_nh, "leg_shape", shape_name);
if (!dock_pattern_detector::legShapeFromString(shape_name, profile.leg_shape, error))
{
robot::log_error("[trolley_detection] '%s': profile '%s': %s", name_.c_str(),
profile_name.c_str(), error.c_str());
return false;
}
nh_param(p_nh, "leg_width", profile.leg_width);
nh_param(p_nh, "leg_width_tolerance", profile.leg_width_tolerance);
nh_param(p_nh, "leg_depth", profile.leg_depth);
nh_param(p_nh, "leg_yaw_offset", profile.leg_yaw_offset);
int min_leg_points = static_cast<int>(profile.min_leg_points);
nh_param(p_nh, "min_leg_points", min_leg_points);
profile.min_leg_points = static_cast<std::size_t>(std::max(0, min_leg_points));
nh_param(p_nh, "shadow_min_angle", profile.shadow_min_angle);
nh_param(p_nh, "leg_cluster_gap", profile.leg_cluster_gap);
nh_param(p_nh, "leg_min_depth_gap", profile.leg_min_depth_gap);
nh_param(p_nh, "min_legs", profile.min_legs);
nh_param(p_nh, "leg_assoc_radius", profile.leg_assoc_radius);
nh_param(p_nh, "max_interior_points", profile.max_interior_points);
nh_param(p_nh, "interior_margin", profile.interior_margin);
nh_param(p_nh, "ambiguity_margin", profile.ambiguity_margin);
nh_param(p_nh, "min_confidence", profile.min_confidence);
nh_param(p_nh, "tape_enabled", profile.tape_enabled);
std::string tape_legs_name = dock_pattern_detector::toString(profile.tape_legs);
nh_param(p_nh, "tape_legs", tape_legs_name);
if (!dock_pattern_detector::tapeLegsFromString(tape_legs_name, profile.tape_legs, error))
{
robot::log_error("[trolley_detection] '%s': profile '%s': %s", name_.c_str(),
profile_name.c_str(), error.c_str());
return false;
}
nh_param(p_nh, "tape_min_intensity", profile.tape_min_intensity);
int tape_min_points = static_cast<int>(profile.tape_min_points);
nh_param(p_nh, "tape_min_points", tape_min_points);
profile.tape_min_points = static_cast<std::size_t>(std::max(0, tape_min_points));
nh_param(p_nh, "has_prior", profile.has_prior);
nh_param(p_nh, "prior_x", profile.prior_x);
nh_param(p_nh, "prior_y", profile.prior_y);
nh_param(p_nh, "prior_yaw", profile.prior_yaw);
nh_param(p_nh, "prior_yaw_tolerance", profile.prior_yaw_tolerance);
nh_param(p_nh, "search_radius", profile.search_radius);
nh_param(p_nh, "search_fov", profile.search_fov);
nh_param(p_nh, "offset_x", profile.offset_x);
nh_param(p_nh, "offset_y", profile.offset_y);
nh_param(p_nh, "offset_yaw", profile.offset_yaw);
// Kiểm MỌI profile lúc boot, không chỉ profile mặc định. Gõ sai ở profile thứ năm mà bốn giờ
// chiều mới lộ là kiểu lỗi tệ nhất.
if (!profile.validate(error))
{
robot::log_error("[trolley_detection] '%s': profile '%s': %s", name_.c_str(),
profile_name.c_str(), error.c_str());
return false;
}
profiles_[profile_name] = profile;
}
if (default_profile_.empty())
{
default_profile_ = profiles_.begin()->first;
}
if (profiles_.find(default_profile_) == profiles_.end())
{
robot::log_error("[trolley_detection] '%s': default_profile '%s' is not among the declared "
"profiles.",
name_.c_str(), default_profile_.c_str());
return false;
}
return true;
}
bool loadFilter(robot::NodeHandle& nh)
{
PoseSampleFilterConfig config;
nh.param("filter_enabled", config.enabled, true);
nh.param("sample_window", config.sample_window, 1.0);
nh.param("min_samples", config.min_samples, 5);
nh.param("max_spread_xy", config.max_spread_xy, 0.03);
nh.param("max_spread_yaw", config.max_spread_yaw, 0.05);
nh.param("hold_time", config.hold_time, 0.0);
nh.param("jump_threshold", config.jump_threshold, 0.0);
nh.param("cluster_recency", config.cluster_recency, 0.3);
nh.param("min_cluster_fraction", config.min_cluster_fraction, 0.6);
nh.param("min_cluster_samples", config.min_cluster_samples, 3);
if (!filter_.configure(config, name_))
{
return false;
}
if (config.enabled && timeout_ > 0.0 &&
timeout_ <= settle_delay_ + config.sample_window + config.hold_time)
{
robot::log_error("[trolley_detection] '%s': timeout=%.3f s <= "
"settle_delay+sample_window+hold_time=%.3f s; the action would always fail.",
name_.c_str(), timeout_,
settle_delay_ + config.sample_window + config.hold_time);
return false;
}
return true;
}
/// @brief `robot::NodeHandle::param` nhưng không cần biến tạm ở chỗ gọi.
template <typename T>
static void nh_param(robot::NodeHandle& nh, const std::string& key, T& value)
{
nh.param(key, value, value);
}
// ==============================================================================================
// Vòng dò
// ==============================================================================================
/**
* @brief Pose 2D của frame scan trong `prior_frame`, tra một lần mỗi lượt rồi cache.
*
* Lidar gắn cứng vào thân robot nên phép biến đổi này không đổi trong một lượt; tra lại mỗi scan
* chỉ tốn công. Đồng thời suy lidar có lộn ngược không, kiểm mặt quét nằm ngang và hướng lidar
* khớp `entry_direction`.
*
* @return false nếu chưa có TF (thử lại scan sau) hoặc cách gắn lidar không dùng được (đã ghi
* `mount_error_`).
*/
bool ensurePriorTransform(const std::string& scan_frame, const robot::Time& now)
{
if (prior_tf_valid_ && prior_tf_frame_ == scan_frame)
{
return true;
}
tf3::TransformStampedMsg tf;
try
{
tf = ctx_.tf->lookupTransform(prior_frame_, scan_frame, tf3::Time());
}
catch (const std::exception& ex)
{
noteReason(now, "no transform '" + prior_frame_ + "' <- '" + scan_frame + "' yet: " +
ex.what());
return false;
}
// Yaw = hướng trục x của lidar, giống nhau ở frame lidar và frame "đứng thẳng" của nó, nên
// `scan_in_prior_` dùng được cho cả hai.
const double up = upAxisZ(tf.transform.rotation);
const double tilt = std::acos(std::min(1.0, std::fabs(up))); // [rad]
scan_in_prior_.x = tf.transform.translation.x;
scan_in_prior_.y = tf.transform.translation.y;
scan_in_prior_.yaw = yawOf(tf.transform.rotation);
scan_flipped_ = up < 0.0;
prior_tf_frame_ = scan_frame;
prior_tf_valid_ = true;
if (debug_detect_)
{
robot::log_info("[trolley_detection][debug] '%s': scan frame '%s' in '%s': (%.3f, %.3f) yaw "
"%.3f rad, tilt %.3f rad%s.",
name_.c_str(), scan_frame.c_str(), prior_frame_.c_str(), scan_in_prior_.x,
scan_in_prior_.y, scan_in_prior_.yaw, tilt,
scan_flipped_ ? ", mounted upside down: bearings mirrored" : "");
}
char buffer[256];
if (tilt > kMaxScanTilt)
{
std::snprintf(buffer, sizeof(buffer),
"scan plane of '%s' (frame '%s') is tilted %.3f rad from '%s' (limit %.3f); "
"the leg model is 2D, check the lidar mount in the URDF",
scan_topic_.c_str(), scan_frame.c_str(), tilt, prior_frame_.c_str(),
kMaxScanTilt);
mount_error_ = buffer;
robot::log_error("[trolley_detection] '%s': %s.", name_.c_str(), buffer);
return false;
}
// Lidar nhìn về trước (cos > 0) thì chỉ dò được xe phía trước: phải là `forward`, và ngược lại.
// Lidar góc của T800 (±π/4, ±3π/4) vẫn qua đúng phép kiểm này.
const bool looks_forward = std::cos(scan_in_prior_.yaw) > 0.0;
const bool wants_forward = entry_direction_ == EntryDirection::kForward;
if (looks_forward != wants_forward)
{
std::snprintf(buffer, sizeof(buffer),
"entry_direction %s but '%s' (frame '%s') faces %s in '%s' (yaw %.2f rad); "
"the goal heading would be reversed",
toString(entry_direction_), scan_topic_.c_str(), scan_frame.c_str(),
looks_forward ? "forward" : "backward", prior_frame_.c_str(),
scan_in_prior_.yaw);
mount_error_ = buffer;
robot::log_error("[trolley_detection] '%s': %s.", name_.c_str(), buffer);
return false;
}
return true;
}
/**
* @brief Lấy scan MỚI (nếu có), dò, quy sang global frame, đẩy vào bộ lọc.
*
* Chỉ chạy khi cursor cho biết có scan mới: dò lại trên đúng scan cũ là đốt CPU của vòng điều
* khiển và đếm hai lần cùng một phép đo.
*/
void processNewScan(const robot::Time& now)
{
// Trước hết giải quyết phép dò còn treo vì TF chưa kịp. Không dò lại: hình đã khớp rồi, chỉ
// thiếu phép quy đổi.
if (pending_valid_ && resolvePending(now))
{
pending_valid_ = false;
}
auto scan = robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(*ctx_.sensors, scan_topic_,
scan_cursor_);
if (!scan)
{
return;
}
if (!ensurePriorTransform(scan->header.frame_id, now))
{
return;
}
// Lidar lộn ngược: tia ở góc θ trong frame lidar nằm ở góc −θ trong frame đứng thẳng. Từ đây
// matcher và resolvePending() làm việc trong frame đứng thẳng đó; matcher nhận được bước góc âm.
const double bearing_sign = scan_flipped_ ? -1.0 : 1.0;
robot_line_extraction::ScanGeometry geometry;
geometry.angle_min = bearing_sign * scan->angle_min;
geometry.angle_increment = bearing_sign * scan->angle_increment;
geometry.size = scan->ranges.size();
// `ranges` là float trong message, double trong lõi. Đổi một lần ở đây, dùng lại buffer để
// không cấp phát mỗi scan. `intensities` đi thẳng: rỗng khi driver không gửi cường độ, và
// matcher tự nói ra điều đó nếu profile đang đòi dải.
ranges_.assign(scan->ranges.begin(), scan->ranges.end());
const dock_pattern_detector::LegDetection detection =
matcher_.match(geometry, ranges_, scan->intensities, limits_, scan_in_prior_);
if (!detection.valid)
{
noteReason(now, detection.reason);
return;
}
pending_ = detection;
pending_frame_ = scan->header.frame_id;
logMatch(now, detection); // sau khi gán pending_frame_: dòng log in tên frame đó
pending_stamp_ = tf3::Time(scan->header.stamp.sec, scan->header.stamp.nsec);
pending_valid_ = true;
last_reason_.clear();
if (resolvePending(now))
{
pending_valid_ = false;
}
}
/**
* @brief Quy phép dò đang treo sang global frame và đẩy vào bộ lọc.
*
* @return false nếu TF chưa có ở stamp đó — khi ấy phép dò **được giữ lại** để tick sau thử tiếp,
* và KHÔNG rơi về transform mới nhất (trộn hai thời điểm vào một phép đo).
*/
bool resolvePending(const robot::Time& now)
{
tf3::TransformStampedMsg sensor_to_global;
try
{
sensor_to_global =
ctx_.tf->lookupTransform(ctx_.global_frame, pending_frame_, pending_stamp_);
}
catch (const std::exception& ex)
{
noteReason(now, std::string("no transform at the scan stamp yet: ") + ex.what());
return false;
}
// `pending_` nằm trong frame đứng thẳng của lidar (xem processNewScan). Trục x của frame đó là
// trục x của lidar, nên yawOf() của TF lidar cũng là yaw của frame đứng thẳng — lật hay không.
const double base_yaw = yawOf(sensor_to_global.transform.rotation);
const double c = std::cos(base_yaw);
const double s = std::sin(base_yaw);
// Heading của goal theo cách robot chui: tiến vào thì trỏ VÀO xe (ngược pháp tuyến cạnh vào),
// lùi vào thì trỏ RA cạnh vào (đúng pháp tuyến).
const double heading =
pending_.yaw + (entry_direction_ == EntryDirection::kForward ? M_PI : 0.0);
PoseSample sample;
sample.x = sensor_to_global.transform.translation.x + c * pending_.x - s * pending_.y;
sample.y = sensor_to_global.transform.translation.y + s * pending_.x + c * pending_.y;
sample.yaw = wrapAngle(base_yaw + heading);
sample.taken_at = now;
++detections_;
last_reason_.clear();
filter_.addSample(sample);
filter_.pruneExpired(now);
filter_.evaluate(now);
return true;
}
/// @brief Ghi lại vì sao chưa dò ra, in tối đa một dòng mỗi `kReasonLogPeriod` giây.
void noteReason(const robot::Time& now, const std::string& reason)
{
last_reason_ = reason;
if (!debug_detect_ || (have_reason_log_ && (now - last_reason_log_).toSec() < kReasonLogPeriod))
{
return;
}
last_reason_log_ = now;
have_reason_log_ = true;
robot::log_info("[trolley_detection][debug] '%s': %s", name_.c_str(), reason.c_str());
}
/// @brief Kết quả khớp, tối đa 1 Hz. Kích thước đo lệch profile là dấu hiệu sớm của khai sai số.
void logMatch(const robot::Time& now, const dock_pattern_detector::LegDetection& d)
{
if (d.legs_seen > 0 && matcher_.profile().tape_enabled && !tape_reported_ && debug_detect_)
{
// Một dòng mỗi lượt: số người lắp xe cần để đặt ngưỡng cường độ.
tape_reported_ = true;
robot::log_info("[trolley_detection][debug] '%s': bright rays per leg (entry-left, "
"entry-right, far-left, far-right): %zu %zu %zu %zu (tape_min_intensity "
"%.0f).",
name_.c_str(), d.tape_bright_rays[0], d.tape_bright_rays[1],
d.tape_bright_rays[2], d.tape_bright_rays[3],
matcher_.profile().tape_min_intensity);
}
if (!debug_detect_ || (have_match_log_ && (now - last_match_log_).toSec() < kReasonLogPeriod))
{
return;
}
last_match_log_ = now;
have_match_log_ = true;
robot::log_info("[trolley_detection][debug] '%s': cart at (%.3f, %.3f) yaw %.3f in '%s'%s, "
"legs seen %d (partial %d, occluded %d, out of view %d), measured %.3f x %.3f "
"m, fit rms %.4f m, confidence %.2f.",
name_.c_str(), d.center_x, d.center_y, d.center_yaw, pending_frame_.c_str(),
scan_flipped_ ? " (upright view)" : "", d.legs_seen, d.legs_partial,
d.legs_occluded, d.legs_out_of_view, d.measured_opening, d.measured_depth, d.fit_rms, d.confidence);
}
ActionTick failOnTimeout(double elapsed)
{
ActionTick tick;
tick.status = ActionStatus::kFailed;
if (detections_ == 0)
{
// Chưa lần nào khớp được. `last_reason_` từ matcher nói rõ hỏng ở CỔNG NÀO.
tick.message = "action '" + action_id_ + "': no '" + profile_name_ + "' trolley on '" +
scan_topic_ + "' in " + formatSeconds(elapsed) + " s" +
(last_reason_.empty() ? "" : " — " + last_reason_);
return tick;
}
if (!filter_.hasBest())
{
// Có khớp, nhưng chưa cửa sổ nào đủ `min_samples`: dò được quá thưa so với `sample_window`.
tick.message = "action '" + action_id_ + "': detected the trolley only " +
std::to_string(detections_) + " time(s) in " + formatSeconds(elapsed) +
" s, need " + std::to_string(filter_.config().min_samples) + " within any " +
formatSeconds(filter_.config().sample_window) + " s window";
return tick;
}
robot::log_error("[trolley_detection] '%s': no window converged in %.2f s. Best window (%.0f%% "
"of the tolerance): %s\n",
name_.c_str(), elapsed, filter_.bestScore() * 100.0,
filter_.bestDescription().c_str());
tick.message = "action '" + action_id_ + "': detections unstable (best spread xy=" +
std::to_string(filter_.bestSpreadXy()) +
" m, yaw=" + std::to_string(filter_.bestSpreadYaw()) + " rad in " +
formatSeconds(elapsed) + " s)";
return tick;
}
static std::string formatSeconds(double seconds)
{
char buffer[32];
std::snprintf(buffer, sizeof(buffer), "%.2f", seconds);
return buffer;
}
bool publish(const PoseSample& s, const robot::Time& now)
{
tf3::TransformStampedMsg out;
out.header.stamp = tf3::Time(now.sec, now.nsec);
out.header.frame_id = ctx_.global_frame;
out.child_frame_id = output_frame_;
out.transform.translation.x = s.x;
out.transform.translation.y = s.y;
out.transform.translation.z = 0.0;
out.transform.rotation.x = 0.0;
out.transform.rotation.y = 0.0;
out.transform.rotation.z = std::sin(s.yaw * 0.5);
out.transform.rotation.w = std::cos(s.yaw * 0.5);
// static = true: kết quả đã chốt, không có hạn dùng. Chặng sau tra lúc nào cũng thấy, kể cả khi
// cảm biến đã mất dấu vì robot đã ở dưới gầm xe.
return ctx_.tf->setTransform(out, "trolley_detection/" + name_, /*is_static=*/true);
}
std::string name_;
ActionContext ctx_;
std::vector<std::string> action_types_;
std::string output_frame_;
std::string scan_topic_;
std::string prior_frame_ = "base_link";
EntryDirection entry_direction_ = EntryDirection::kForward;
double settle_delay_ = kDefaultSettleDelay;
double timeout_ = kDefaultTimeout;
dock_pattern_detector::ScanLimits limits_;
bool debug_detect_ = true;
std::string default_profile_;
std::string profile_param_key_ = "trolley_profile";
std::map<std::string, dock_pattern_detector::LegProfile> profiles_;
dock_pattern_detector::LegPatternMatcher matcher_;
PoseSampleFilter filter_;
robot::Time started_at_;
robot::Time paused_at_; ///< Mốc pause() gần nhất; chỉ có nghĩa khi paused_.
bool paused_ = false;
std::string action_id_;
std::string profile_name_;
/// Pose của frame scan trong prior_frame, cache cho cả lượt.
dock_pattern_detector::Pose2D scan_in_prior_;
std::string prior_tf_frame_;
bool prior_tf_valid_ = false;
/// Trục z của frame scan chỉ xuống: góc tia phải đảo dấu trước khi dò. Suy từ TF, cùng lúc với
/// scan_in_prior_.
bool scan_flipped_ = false;
/// Rỗng = ổn; khác rỗng = lidar nhìn ngược `entry_direction` hoặc mặt quét nghiêng, lượt này phải
/// fail.
std::string mount_error_;
/// Con trỏ đọc của kho cảm biến. Đây là thứ phân biệt "scan mới" với "cùng scan đọc lại".
uint64_t scan_cursor_ = 0;
/// Số lần khớp được cả lượt. Phân biệt "chưa lần nào khớp" với "khớp nhưng quá thưa".
std::size_t detections_ = 0;
/// Phép dò đã khớp nhưng chưa quy được sang global frame vì TF chưa tới stamp đó.
dock_pattern_detector::LegDetection pending_;
std::string pending_frame_;
tf3::Time pending_stamp_;
bool pending_valid_ = false;
bool tape_reported_ = false;
std::string last_reason_;
robot::Time last_reason_log_;
bool have_reason_log_ = false;
robot::Time last_match_log_;
bool have_match_log_ = false;
/// Buffer dùng lại: chạy mỗi khi có scan mới.
std::vector<double> ranges_;
};
} // namespace action_core
ACTION_CORE_EXPORT_HANDLER(action_core::TrolleyDetectionActionHandler::create,
TrolleyDetectionActionHandler)

116
sim/gen_trolley_models.py Normal file
View File

@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Generate the simple 4-leg trolley SDF models in sim/models.
Run from anywhere: python3 sim/gen_trolley_models.py sim/models
Edit the numbers here and regenerate; do not hand-edit the .sdf files.
"""
import os
import sys
OUT = sys.argv[1]
DEPTH, OPENING, LEG = 0.720, 0.517, 0.030 # [m] leg centres and leg section, same as tci_trolley
# [m] Underside of the deck. The real tci_trolley sits at 0.352 m and relies on a guide slot for the
# 0.3595 m hump of hook_150; these models have no slot, so the deck is raised to leave 20 mm.
DECK_Z = 0.380
DECK_T = 0.020 # [m] deck thickness
BAND = (0.14, 0.24) # [m] reflective band around the lidar plane (0.184)
CORNERS = [("entry_left", DEPTH / 2, OPENING / 2), ("entry_right", DEPTH / 2, -OPENING / 2),
("far_left", -DEPTH / 2, OPENING / 2), ("far_right", -DEPTH / 2, -OPENING / 2)]
def box(name, x, y, z0, z1, retro):
h = z1 - z0
colour = '0.9 0.9 0.2 1' if retro else '0.3 0.3 0.3 1'
return f""" <collision name="{name}">
<pose>{x:.4f} {y:.4f} {z0 + h / 2:.4f} 0 0 0</pose>
<laser_retro>{retro}</laser_retro>
<geometry><box><size>{LEG} {LEG} {h:.4f}</size></box></geometry>
</collision>
<visual name="{name}_visual">
<pose>{x:.4f} {y:.4f} {z0 + h / 2:.4f} 0 0 0</pose>
<geometry><box><size>{LEG} {LEG} {h:.4f}</size></box></geometry>
<material><ambient>{colour}</ambient><diffuse>{colour}</diffuse></material>
</visual>
"""
HEADER = """<?xml version="1.0"?>
<!--
Xe hàng 4 chân ĐƠN GIẢN cho trolley_detection_action trong Gazebo. Sinh bằng
sim/gen_trolley_models.py — sửa số ở script rồi sinh lại, đừng sửa tay file này.
Kích thước chân khớp xe `tci_trolley` của world factory_ss_demo:
cart_depth = {depth:.3f} m (trục X của model) cart_opening = {opening:.3f} m (trục Y)
chân hộp {leg:.3f} x {leg:.3f} m, cao tới mặt dưới sàn xe {deck:.3f} m
KHÁC tci_trolley, cố ý:
- gốc model ĐÚNG TÂM 4 chân, chân chạm sàn ở z = 0 → spawn z = 0, ground truth = pose model;
- KHÔNG có tấm đáy 0.78 x 0.613 x 0.01 m sát sàn mà mesh tci_trolley mang theo (robot đâm vào
nó khi chui gầm);
- mặt dưới sàn xe ở {deck:.3f} m thay vì 0.352 m: không có khe dẫn hướng cho phần gồ 0.3595 m
trên nóc hook_150, nên nâng sàn để chừa 20 mm;
- không bánh xe, tay đẩy, thanh mảnh — chỉ chân + mặt sàn. Lidar (0.184 m) chỉ thấy 4 chân.
{which}
-->
<sdf version="1.6">
<model name="{name}">
<static>true</static>
<link name="frame">
"""
FOOTER = f""" <collision name="deck">
<pose>0 0 {DECK_Z + DECK_T / 2:.3f} 0 0 0</pose>
<geometry><box><size>{DEPTH + LEG + 0.03:.3f} {OPENING + LEG + 0.03:.3f} {DECK_T:.3f}</size></box></geometry>
</collision>
<visual name="deck_visual">
<pose>0 0 {DECK_Z + DECK_T / 2:.3f} 0 0 0</pose>
<geometry><box><size>{DEPTH + LEG + 0.03:.3f} {OPENING + LEG + 0.03:.3f} {DECK_T:.3f}</size></box></geometry>
</visual>
</link>
</model>
</sdf>
"""
def model(name, taped, which, summary):
text = HEADER.format(depth=DEPTH, opening=OPENING, leg=LEG, deck=DECK_Z, which=which, name=name)
for leg, x, y in CORNERS:
if leg in taped:
text += box(f"{leg}_low", x, y, 0.0, BAND[0], 0)
text += box(f"{leg}_band", x, y, BAND[0], BAND[1], 2000)
text += box(f"{leg}_high", x, y, BAND[1], DECK_Z, 0)
else:
text += box(leg, x, y, 0.0, DECK_Z, 0)
text += FOOTER
d = os.path.join(OUT, name)
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "model.sdf"), "w") as f:
f.write(text)
with open(os.path.join(d, "model.config"), "w") as f:
f.write(f"""<?xml version="1.0"?>
<model>
<name>{name}</name>
<version>1.1</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>DuongTD</name>
<email>tdd@gmail.com</email>
</author>
<description>
Xe hàng 4 chân 0.720 x 0.517 m, chân hộp 30 mm, sàn xe cao {DECK_Z:.3f} m, {summary}. Gốc model ở
tâm 4 chân. Dùng chạy thử trolley_detection_action + chui gầm trong Gazebo.
</description>
</model>
""")
model("trolley_4legs", set(),
"Bản này: KHÔNG dải phản quang — dò bằng hình học (`tape_enabled: false`).",
"không dải phản quang")
model("trolley_4legs_tape_all", {"entry_left", "entry_right", "far_left", "far_right"},
"Bản này: dải trên CẢ 4 chân (`tape_legs: all`), collision 0.14–0.24 m khai laser_retro 2000.",
"dải phản quang cả 4 chân")
model("trolley_4legs_tape_entry", {"entry_left", "entry_right"},
"Bản này: dải chỉ trên 2 chân ở đầu +X (`tape_legs: entry`) — đầu +X là cạnh vào.",
"dải phản quang 2 chân đầu +X")
print("ok")

View File

@@ -0,0 +1,33 @@
<!--
Dựng một xe hàng 4 chân ĐƠN GIẢN vào world Gazebo đang chạy (model trong sim/models, sinh bằng
sim/gen_trolley_models.py).
Chạy SAU khi world đã lên:
roslaunch trolley_detection_action spawn_trolley.launch x:=7.009 y:=34.5275 yaw:=0.0
`model`:
trolley_4legs (mặc định) không dải phản quang — dò bằng hình học;
trolley_4legs_tape_entry dải ở 2 chân đầu +X của model (= cạnh vào);
trolley_4legs_tape_all dải cả 4 chân.
Gốc model ở TÂM 4 chân và chân chạm sàn ở z = 0, nên ground truth chính là pose spawn (x, y, yaw).
Robot chui gầm được: sàn xe cao 0.380 m (nóc hook_150 0.3595 m), không có tấm đáy. Model
`tci_trolley` của factory_ss_demo thì KHÔNG chui được trong Gazebo: mesh của nó có tấm đáy
0.78 x 0.613 x 0.01 m sát sàn và mặt dưới sàn xe 0.352 m (ngoài đời là khe dẫn hướng).
⚠ Gazebo TỪ CHỐI spawn đè lên model cùng tên ("entity already exists"). Xoá trước, ví dụ:
rosservice call /gazebo/delete_model "model_name: 'trolley'"
-->
<launch>
<arg name="model" default="trolley_4legs" />
<arg name="name" default="trolley" />
<arg name="x" default="3.0" />
<arg name="y" default="0.0" />
<arg name="z" default="0.0" />
<arg name="yaw" default="3.14159" />
<node name="spawn_$(arg name)" pkg="gazebo_ros" type="spawn_model" output="screen"
args="-sdf -file $(find trolley_detection_action)/sim/models/$(arg model)/model.sdf
-model $(arg name)
-x $(arg x) -y $(arg y) -z $(arg z) -Y $(arg yaw)" />
</launch>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0"?>
<model>
<name>trolley_4legs</name>
<version>1.1</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>DuongTD</name>
<email>tdd@gmail.com</email>
</author>
<description>
Xe hàng 4 chân 0.720 x 0.517 m, chân hộp 30 mm, sàn xe cao 0.380 m, không dải phản quang. Gốc model ở
tâm 4 chân. Dùng chạy thử trolley_detection_action + chui gầm trong Gazebo.
</description>
</model>

View File

@@ -0,0 +1,73 @@
<?xml version="1.0"?>
<!--
Xe hàng 4 chân ĐƠN GIẢN cho trolley_detection_action trong Gazebo. Sinh bằng
sim/gen_trolley_models.py — sửa số ở script rồi sinh lại, đừng sửa tay file này.
Kích thước chân khớp xe `tci_trolley` của world factory_ss_demo:
cart_depth = 0.720 m (trục X của model) cart_opening = 0.517 m (trục Y)
chân hộp 0.030 x 0.030 m, cao tới mặt dưới sàn xe 0.380 m
KHÁC tci_trolley, cố ý:
- gốc model ĐÚNG TÂM 4 chân, chân chạm sàn ở z = 0 → spawn z = 0, ground truth = pose model;
- KHÔNG có tấm đáy 0.78 x 0.613 x 0.01 m sát sàn mà mesh tci_trolley mang theo (robot đâm vào
nó khi chui gầm);
- mặt dưới sàn xe ở 0.380 m thay vì 0.352 m: không có khe dẫn hướng cho phần gồ 0.3595 m
trên nóc hook_150, nên nâng sàn để chừa 20 mm;
- không bánh xe, tay đẩy, thanh mảnh — chỉ chân + mặt sàn. Lidar (0.184 m) chỉ thấy 4 chân.
Bản này: KHÔNG dải phản quang — dò bằng hình học (`tape_enabled: false`).
-->
<sdf version="1.6">
<model name="trolley_4legs">
<static>true</static>
<link name="frame">
<collision name="entry_left">
<pose>0.3600 0.2585 0.1900 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
</collision>
<visual name="entry_left_visual">
<pose>0.3600 0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="entry_right">
<pose>0.3600 -0.2585 0.1900 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
</collision>
<visual name="entry_right_visual">
<pose>0.3600 -0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="far_left">
<pose>-0.3600 0.2585 0.1900 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
</collision>
<visual name="far_left_visual">
<pose>-0.3600 0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="far_right">
<pose>-0.3600 -0.2585 0.1900 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
</collision>
<visual name="far_right_visual">
<pose>-0.3600 -0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="deck">
<pose>0 0 0.390 0 0 0</pose>
<geometry><box><size>0.780 0.577 0.020</size></box></geometry>
</collision>
<visual name="deck_visual">
<pose>0 0 0.390 0 0 0</pose>
<geometry><box><size>0.780 0.577 0.020</size></box></geometry>
</visual>
</link>
</model>
</sdf>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0"?>
<model>
<name>trolley_4legs_tape_all</name>
<version>1.1</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>DuongTD</name>
<email>tdd@gmail.com</email>
</author>
<description>
Xe hàng 4 chân 0.720 x 0.517 m, chân hộp 30 mm, sàn xe cao 0.380 m, dải phản quang cả 4 chân. Gốc model ở
tâm 4 chân. Dùng chạy thử trolley_detection_action + chui gầm trong Gazebo.
</description>
</model>

View File

@@ -0,0 +1,153 @@
<?xml version="1.0"?>
<!--
Xe hàng 4 chân ĐƠN GIẢN cho trolley_detection_action trong Gazebo. Sinh bằng
sim/gen_trolley_models.py — sửa số ở script rồi sinh lại, đừng sửa tay file này.
Kích thước chân khớp xe `tci_trolley` của world factory_ss_demo:
cart_depth = 0.720 m (trục X của model) cart_opening = 0.517 m (trục Y)
chân hộp 0.030 x 0.030 m, cao tới mặt dưới sàn xe 0.380 m
KHÁC tci_trolley, cố ý:
- gốc model ĐÚNG TÂM 4 chân, chân chạm sàn ở z = 0 → spawn z = 0, ground truth = pose model;
- KHÔNG có tấm đáy 0.78 x 0.613 x 0.01 m sát sàn mà mesh tci_trolley mang theo (robot đâm vào
nó khi chui gầm);
- mặt dưới sàn xe ở 0.380 m thay vì 0.352 m: không có khe dẫn hướng cho phần gồ 0.3595 m
trên nóc hook_150, nên nâng sàn để chừa 20 mm;
- không bánh xe, tay đẩy, thanh mảnh — chỉ chân + mặt sàn. Lidar (0.184 m) chỉ thấy 4 chân.
Bản này: dải trên CẢ 4 chân (`tape_legs: all`), collision 0.14–0.24 m khai laser_retro 2000.
-->
<sdf version="1.6">
<model name="trolley_4legs_tape_all">
<static>true</static>
<link name="frame">
<collision name="entry_left_low">
<pose>0.3600 0.2585 0.0700 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="entry_left_low_visual">
<pose>0.3600 0.2585 0.0700 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="entry_left_band">
<pose>0.3600 0.2585 0.1900 0 0 0</pose>
<laser_retro>2000</laser_retro>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
</collision>
<visual name="entry_left_band_visual">
<pose>0.3600 0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
<material><ambient>0.9 0.9 0.2 1</ambient><diffuse>0.9 0.9 0.2 1</diffuse></material>
</visual>
<collision name="entry_left_high">
<pose>0.3600 0.2585 0.3100 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="entry_left_high_visual">
<pose>0.3600 0.2585 0.3100 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="entry_right_low">
<pose>0.3600 -0.2585 0.0700 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="entry_right_low_visual">
<pose>0.3600 -0.2585 0.0700 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="entry_right_band">
<pose>0.3600 -0.2585 0.1900 0 0 0</pose>
<laser_retro>2000</laser_retro>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
</collision>
<visual name="entry_right_band_visual">
<pose>0.3600 -0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
<material><ambient>0.9 0.9 0.2 1</ambient><diffuse>0.9 0.9 0.2 1</diffuse></material>
</visual>
<collision name="entry_right_high">
<pose>0.3600 -0.2585 0.3100 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="entry_right_high_visual">
<pose>0.3600 -0.2585 0.3100 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="far_left_low">
<pose>-0.3600 0.2585 0.0700 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="far_left_low_visual">
<pose>-0.3600 0.2585 0.0700 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="far_left_band">
<pose>-0.3600 0.2585 0.1900 0 0 0</pose>
<laser_retro>2000</laser_retro>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
</collision>
<visual name="far_left_band_visual">
<pose>-0.3600 0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
<material><ambient>0.9 0.9 0.2 1</ambient><diffuse>0.9 0.9 0.2 1</diffuse></material>
</visual>
<collision name="far_left_high">
<pose>-0.3600 0.2585 0.3100 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="far_left_high_visual">
<pose>-0.3600 0.2585 0.3100 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="far_right_low">
<pose>-0.3600 -0.2585 0.0700 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="far_right_low_visual">
<pose>-0.3600 -0.2585 0.0700 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="far_right_band">
<pose>-0.3600 -0.2585 0.1900 0 0 0</pose>
<laser_retro>2000</laser_retro>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
</collision>
<visual name="far_right_band_visual">
<pose>-0.3600 -0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
<material><ambient>0.9 0.9 0.2 1</ambient><diffuse>0.9 0.9 0.2 1</diffuse></material>
</visual>
<collision name="far_right_high">
<pose>-0.3600 -0.2585 0.3100 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="far_right_high_visual">
<pose>-0.3600 -0.2585 0.3100 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="deck">
<pose>0 0 0.390 0 0 0</pose>
<geometry><box><size>0.780 0.577 0.020</size></box></geometry>
</collision>
<visual name="deck_visual">
<pose>0 0 0.390 0 0 0</pose>
<geometry><box><size>0.780 0.577 0.020</size></box></geometry>
</visual>
</link>
</model>
</sdf>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0"?>
<model>
<name>trolley_4legs_tape_entry</name>
<version>1.1</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>DuongTD</name>
<email>tdd@gmail.com</email>
</author>
<description>
Xe hàng 4 chân 0.720 x 0.517 m, chân hộp 30 mm, sàn xe cao 0.380 m, dải phản quang 2 chân đầu +X. Gốc model ở
tâm 4 chân. Dùng chạy thử trolley_detection_action + chui gầm trong Gazebo.
</description>
</model>

View File

@@ -0,0 +1,113 @@
<?xml version="1.0"?>
<!--
Xe hàng 4 chân ĐƠN GIẢN cho trolley_detection_action trong Gazebo. Sinh bằng
sim/gen_trolley_models.py — sửa số ở script rồi sinh lại, đừng sửa tay file này.
Kích thước chân khớp xe `tci_trolley` của world factory_ss_demo:
cart_depth = 0.720 m (trục X của model) cart_opening = 0.517 m (trục Y)
chân hộp 0.030 x 0.030 m, cao tới mặt dưới sàn xe 0.380 m
KHÁC tci_trolley, cố ý:
- gốc model ĐÚNG TÂM 4 chân, chân chạm sàn ở z = 0 → spawn z = 0, ground truth = pose model;
- KHÔNG có tấm đáy 0.78 x 0.613 x 0.01 m sát sàn mà mesh tci_trolley mang theo (robot đâm vào
nó khi chui gầm);
- mặt dưới sàn xe ở 0.380 m thay vì 0.352 m: không có khe dẫn hướng cho phần gồ 0.3595 m
trên nóc hook_150, nên nâng sàn để chừa 20 mm;
- không bánh xe, tay đẩy, thanh mảnh — chỉ chân + mặt sàn. Lidar (0.184 m) chỉ thấy 4 chân.
Bản này: dải chỉ trên 2 chân ở đầu +X (`tape_legs: entry`) — đầu +X là cạnh vào.
-->
<sdf version="1.6">
<model name="trolley_4legs_tape_entry">
<static>true</static>
<link name="frame">
<collision name="entry_left_low">
<pose>0.3600 0.2585 0.0700 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="entry_left_low_visual">
<pose>0.3600 0.2585 0.0700 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="entry_left_band">
<pose>0.3600 0.2585 0.1900 0 0 0</pose>
<laser_retro>2000</laser_retro>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
</collision>
<visual name="entry_left_band_visual">
<pose>0.3600 0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
<material><ambient>0.9 0.9 0.2 1</ambient><diffuse>0.9 0.9 0.2 1</diffuse></material>
</visual>
<collision name="entry_left_high">
<pose>0.3600 0.2585 0.3100 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="entry_left_high_visual">
<pose>0.3600 0.2585 0.3100 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="entry_right_low">
<pose>0.3600 -0.2585 0.0700 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="entry_right_low_visual">
<pose>0.3600 -0.2585 0.0700 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="entry_right_band">
<pose>0.3600 -0.2585 0.1900 0 0 0</pose>
<laser_retro>2000</laser_retro>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
</collision>
<visual name="entry_right_band_visual">
<pose>0.3600 -0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1000</size></box></geometry>
<material><ambient>0.9 0.9 0.2 1</ambient><diffuse>0.9 0.9 0.2 1</diffuse></material>
</visual>
<collision name="entry_right_high">
<pose>0.3600 -0.2585 0.3100 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
</collision>
<visual name="entry_right_high_visual">
<pose>0.3600 -0.2585 0.3100 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.1400</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="far_left">
<pose>-0.3600 0.2585 0.1900 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
</collision>
<visual name="far_left_visual">
<pose>-0.3600 0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="far_right">
<pose>-0.3600 -0.2585 0.1900 0 0 0</pose>
<laser_retro>0</laser_retro>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
</collision>
<visual name="far_right_visual">
<pose>-0.3600 -0.2585 0.1900 0 0 0</pose>
<geometry><box><size>0.03 0.03 0.3800</size></box></geometry>
<material><ambient>0.3 0.3 0.3 1</ambient><diffuse>0.3 0.3 0.3 1</diffuse></material>
</visual>
<collision name="deck">
<pose>0 0 0.390 0 0 0</pose>
<geometry><box><size>0.780 0.577 0.020</size></box></geometry>
</collision>
<visual name="deck_visual">
<pose>0 0 0.390 0 0 0</pose>
<geometry><box><size>0.780 0.577 0.020</size></box></geometry>
</visual>
</link>
</model>
</sdf>

View File

@@ -0,0 +1,93 @@
# Config CHỈ cho trolley_detection_action_test — không phải config chạy robot.
# Ba instance cùng plugin: tiến (lidar trước), lùi (lidar sau), và một instance khai SAI hướng để
# kiểm đường từ chối.
actions_trolley:
handlers:
- {name: detect_trolley, type: TrolleyDetectionActionHandler}
- {name: detect_trolley_back, type: TrolleyDetectionActionHandler}
- {name: detect_trolley_wrong, type: TrolleyDetectionActionHandler}
detect_trolley:
action_types: [DetectTrolley]
output_frame: dock_target
scan_topic: /f_scan
entry_direction: forward
prior_frame: base_link
settle_delay: 0.0 # [s] test tự điều khiển đồng hồ
timeout: 5.0 # [s]
default_profile: tci_trolley
min_range: 0.10 # [m]
max_range: 3.0 # [m]
range_sigma: 0.01 # [m]
sample_window: 1.0 # [s]
min_samples: 3
max_spread_xy: 0.05 # [m]
max_spread_yaw: 0.10 # [rad]
debug:
detect: true
profiles:
tci_trolley:
cart_opening: 0.517 # [m]
cart_depth: 0.720 # [m]
leg_shape: box
leg_width: 0.030 # [m]
min_legs: 3
tci_trolley_prior:
cart_opening: 0.517
cart_depth: 0.720
leg_shape: box
leg_width: 0.030
min_legs: 3
has_prior: true
# [m] Tâm xe trong base_link = 0.454 (lidar) + 1.26. Trong frame lidar xe ở 1.26, lệch
# 0.454 > search_radius: test chỉ qua khi prior được tính trong base_link.
prior_x: 1.714
prior_y: 0.0
prior_yaw: 3.14159
prior_yaw_tolerance: 0.35
search_radius: 0.30
detect_trolley_back:
action_types: [DetectTrolleyBackward]
output_frame: dock_target
scan_topic: /b_scan
entry_direction: backward
prior_frame: base_link
settle_delay: 0.0
timeout: 5.0
default_profile: tci_trolley
sample_window: 1.0
min_samples: 3
max_spread_xy: 0.05
max_spread_yaw: 0.10
profiles:
tci_trolley:
cart_opening: 0.517
cart_depth: 0.720
leg_shape: box
leg_width: 0.030
# Khai `forward` nhưng đọc lidar SAU: phải fail ngay ở scan đầu, không được ghi goal ngược.
detect_trolley_wrong:
action_types: [DetectTrolleyWrong]
output_frame: dock_target
scan_topic: /b_scan
entry_direction: forward
prior_frame: base_link
settle_delay: 0.0
timeout: 5.0
default_profile: tci_trolley
sample_window: 1.0
min_samples: 3
max_spread_xy: 0.05
max_spread_yaw: 0.10
profiles:
tci_trolley:
cart_opening: 0.517
cart_depth: 0.720
leg_shape: box
leg_width: 0.030
# Bảng symbol -> thư viện cho Boost.DLL.
TrolleyDetectionActionHandler:
library_path: libtrolley_detection_action_handler

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,539 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm handler dò xe hàng — chạy ĐÚNG chuỗi mà runtime chạy: kho cảm biến thật + buffer tf3 thật +
* plugin nạp qua Boost.DLL. Chỉ scan là dựng sẵn (chiếu tia lên 4 chân hộp), nên đáp án biết trước.
*
* Trọng tâm là những chỗ chỉ HỎNG KHI GHÉP, mà test lõi không thấy: heading theo `entry_direction`,
* lidar nhìn ngược hướng chui, lidar gắn lộn ngược (roll π), prior tính trong base_link chứ không
* trong frame lidar, quy TF tại đúng stamp, và các đường từ chối lúc boot. Một test chạy trên scan
* Gazebo thật (test/data) để chốt cách đọc lidar lộn ngược bằng dữ liệu, không chỉ bằng mô hình.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <string>
#include <vector>
#include <yaml-cpp/yaml.h>
#include <robot/node_handle.h>
#include <tf3/buffer_core.h>
#include <action_core/action_registry.h>
#include <robot_sensor_ports/sensor_store.h>
#include <robot_sensor_ports/sensor_types.h>
namespace
{
using action_core::ActionContext;
using action_core::ActionHandler;
using action_core::ActionRegistry;
using action_core::ActionStatus;
constexpr const char* kNamespace = "actions_trolley";
constexpr const char* kGlobalFrame = "map";
constexpr const char* kBaseFrame = "base_link";
constexpr const char* kFrontFrame = "front_laser";
constexpr const char* kBackFrame = "back_laser";
/// Lidar trước gắn lộn ngược (roll π) như hook_150 trong sim.
constexpr const char* kFlippedFrame = "front_laser_flipped";
/// Lidar trước gắn chúi xuống quá giới hạn của handler.
constexpr const char* kTiltedFrame = "front_laser_tilted";
constexpr const char* kFrontTopic = "/f_scan";
constexpr const char* kBackTopic = "/b_scan";
constexpr const char* kOutFrame = "dock_target";
constexpr double kInf = std::numeric_limits<double>::infinity();
/// Lidar của hook_150 cách tâm robot 0.454 m dọc trục x.
constexpr double kLaserX = 0.454; // [m]
/// Xe `tci_trolley` (mô hình sim).
constexpr double kOpening = 0.517; // [m]
constexpr double kDepth = 0.720; // [m]
constexpr double kLeg = 0.030; // [m]
/// Tâm xe trong frame lidar khi cạnh vào cách lidar 0.9 m.
constexpr double kCartInLaser = 0.9 + kDepth / 2.0; // [m]
/// @brief Quy giây thành tf3::Time QUA robot::Time — cùng một hàm đổi thì stamp khớp từng bit.
tf3::Time toTf3Time(double t)
{
const robot::Time rt(t);
return tf3::Time(rt.sec, rt.nsec);
}
struct Segment
{
double ax, ay, bx, by; // [m]
};
/// @brief 4 chân hộp của xe: tâm (cx, cy) trong frame lidar, trục x của xe theo @p axis.
std::vector<Segment> cartLegs(double cx, double cy, double axis)
{
std::vector<Segment> out;
const double lx[4] = { kDepth / 2.0, kDepth / 2.0, -kDepth / 2.0, -kDepth / 2.0 };
const double ly[4] = { kOpening / 2.0, -kOpening / 2.0, kOpening / 2.0, -kOpening / 2.0 };
const double c = std::cos(axis);
const double s = std::sin(axis);
for (int k = 0; k < 4; ++k)
{
const double x = cx + c * lx[k] - s * ly[k];
const double y = cy + s * lx[k] + c * ly[k];
const double h = kLeg / 2.0;
const double qx[4] = { h, -h, -h, h };
const double qy[4] = { h, h, -h, -h };
double px[4], py[4];
for (int i = 0; i < 4; ++i)
{
px[i] = x + c * qx[i] - s * qy[i];
py[i] = y + s * qx[i] + c * qy[i];
}
for (int i = 0; i < 4; ++i)
{
out.push_back({ px[i], py[i], px[(i + 1) % 4], py[(i + 1) % 4] });
}
}
return out;
}
/// @brief Cảnh nhìn từ lidar lộn ngược (roll π): mọi điểm đối dấu y so với frame đứng thẳng.
std::vector<Segment> mirrorY(std::vector<Segment> world)
{
for (Segment& s : world)
{
s.ay = -s.ay;
s.by = -s.by;
}
return world;
}
/// @brief Scan Gazebo đã chụp sẵn trong test/data. Đọc range qua strtof vì rostopic echo in `inf`,
/// thứ yaml-cpp không đổi thẳng sang số.
bool loadRecordedScan(const std::string& path, robot_sensor_msgs::LaserScan& scan)
{
YAML::Node node;
try
{
node = YAML::LoadFile(path);
}
catch (const YAML::Exception&)
{
return false;
}
scan.header.frame_id = node["frame_id"].as<std::string>();
scan.angle_min = node["angle_min"].as<float>();
scan.angle_max = node["angle_max"].as<float>();
scan.angle_increment = node["angle_increment"].as<float>();
scan.range_min = node["range_min"].as<float>();
scan.range_max = node["range_max"].as<float>();
scan.ranges.clear();
for (const YAML::Node& r : node["ranges"])
{
scan.ranges.push_back(std::strtof(r.Scalar().c_str(), nullptr));
}
return !scan.ranges.empty();
}
/// @brief Scan kiểu SICK S300 sim (541 tia, ±1.588 rad) chiếu lên @p world.
robot_sensor_msgs::LaserScan makeScan(const std::vector<Segment>& world, const char* frame,
double stamp_s)
{
constexpr std::size_t kRays = 541;
robot_sensor_msgs::LaserScan scan;
scan.header.frame_id = frame;
scan.header.stamp = robot::Time(stamp_s);
scan.angle_min = -1.588249619f;
scan.angle_max = 1.588249619f;
scan.angle_increment = (scan.angle_max - scan.angle_min) / static_cast<float>(kRays - 1);
scan.range_min = 0.05f;
scan.range_max = 29.0f;
scan.ranges.assign(kRays, static_cast<float>(kInf));
for (std::size_t i = 0; i < kRays; ++i)
{
const double bearing = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
const double dx = std::cos(bearing);
const double dy = std::sin(bearing);
for (const Segment& s : world)
{
const double ex = s.bx - s.ax;
const double ey = s.by - s.ay;
const double det = dx * (-ey) - dy * (-ex);
if (std::fabs(det) < 1e-12)
{
continue;
}
const double t = (s.ax * (-ey) - s.ay * (-ex)) / det;
const double u = (dx * s.ay - dy * s.ax) / det;
if (t > 0.0 && u >= 0.0 && u <= 1.0 && t < scan.ranges[i])
{
scan.ranges[i] = static_cast<float>(t);
}
}
}
return scan;
}
robot_protocol_msgs::Action makeAction(const std::string& type, const std::string& profile = "")
{
robot_protocol_msgs::Action action;
action.actionType = type;
action.actionId = "trolley-1";
if (!profile.empty())
{
robot_protocol_msgs::ActionParameter p;
p.key = "trolley_profile";
p.value = profile;
action.actionParameters.push_back(p);
}
return action;
}
double yawOf(const tf3::TransformStampedMsg& t)
{
const auto& q = t.transform.rotation;
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
}
double yawError(double a, double b)
{
return std::fabs(std::atan2(std::sin(a - b), std::cos(a - b)));
}
/// @brief Rig: kho thật + tf3 thật + plugin nạp qua đúng đường Boost.DLL.
class Rig
{
public:
Rig()
{
robot_sensor_ports::SensorStoreConfig store_config;
for (const char* topic : { kFrontTopic, kBackTopic })
{
robot_sensor_ports::SensorEntryConfig entry;
entry.topic = topic;
entry.data_type = "robot_sensor_msgs/LaserScan";
entry.capacity = 1;
entry.max_age = 0.5; // [s]
store_config.sensors.push_back(entry);
}
std::string error;
store_ok = store.configure(store_config, error);
// Lidar gắn cứng: trước ở +0.454 m nhìn về trước, sau ở −0.454 m nhìn về sau — như hook_150.
setStatic(kFrontFrame, kLaserX, 0.0);
setStatic(kBackFrame, -kLaserX, M_PI);
ctx.tf = &tf;
ctx.sensors = &store;
ctx.global_frame = kGlobalFrame;
registry.setContext(ctx);
loaded = registry.loadFromConfig(nh, kNamespace);
}
/// @brief Lidar gắn cứng trong base_link. Góc theo quy ước URDF: R = Rz(yaw)·Ry(pitch)·Rx(roll).
void setStatic(const char* child, double x, double yaw, double roll = 0.0, double pitch = 0.0,
double z = 0.0)
{
const double cr = std::cos(roll * 0.5), sr = std::sin(roll * 0.5);
const double cp = std::cos(pitch * 0.5), sp = std::sin(pitch * 0.5);
const double cy = std::cos(yaw * 0.5), sy = std::sin(yaw * 0.5);
tf3::TransformStampedMsg t;
t.header.stamp = tf3::Time();
t.header.frame_id = kBaseFrame;
t.child_frame_id = child;
t.transform.translation.x = x;
t.transform.translation.z = z;
t.transform.rotation.w = cr * cp * cy + sr * sp * sy;
t.transform.rotation.x = sr * cp * cy - cr * sp * sy;
t.transform.rotation.y = cr * sp * cy + sr * cp * sy;
t.transform.rotation.z = cr * cp * sy - sr * sp * cy;
tf.setTransform(t, "test", /*is_static=*/true);
}
void setRobotPose(double x, double y, double yaw, double stamp_s)
{
tf3::TransformStampedMsg t;
t.header.stamp = toTf3Time(stamp_s);
t.header.frame_id = kGlobalFrame;
t.child_frame_id = kBaseFrame;
t.transform.translation.x = x;
t.transform.translation.y = y;
t.transform.rotation.z = std::sin(yaw * 0.5);
t.transform.rotation.w = std::cos(yaw * 0.5);
tf.setTransform(t, "test", /*is_static=*/false);
}
/// @brief Bơm @p count scan rồi tick, đúng nhịp control loop. Robot đứng yên ở (rx, ry, ryaw).
ActionStatus feed(ActionHandler* handler, const std::vector<Segment>& world, const char* topic,
const char* frame, int count, double rx = 0.0, double ry = 0.0,
double ryaw = 0.0)
{
return feedScan(handler, makeScan(world, frame, 0.0), topic, count, rx, ry, ryaw);
}
/// @brief Như feed() nhưng với một scan dựng sẵn; mỗi lần bơm chỉ đổi stamp.
ActionStatus feedScan(ActionHandler* handler, robot_sensor_msgs::LaserScan scan,
const char* topic, int count, double rx = 0.0, double ry = 0.0,
double ryaw = 0.0)
{
ActionStatus status = ActionStatus::kRunning;
for (int i = 0; i < count; ++i)
{
const double t = 10.0 + 0.1 * i;
setRobotPose(rx, ry, ryaw, t);
scan.header.stamp = robot::Time(t);
robot_sensor_ports::put(store, topic, scan, robot::Time(t));
const action_core::ActionTick tick = handler->update(robot::Time(t));
status = tick.status;
last_message = tick.message;
if (status != ActionStatus::kRunning)
{
break;
}
}
return status;
}
tf3::TransformStampedMsg goal()
{
return tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
}
std::string last_message;
bool store_ok = false;
bool loaded = false;
robot::NodeHandle nh;
tf3::BufferCore tf;
robot_sensor_ports::SensorStore store;
ActionContext ctx;
ActionRegistry registry;
};
// ================================================================================================
// 1. Đường chạy đủ + heading theo entry_direction
// ================================================================================================
TEST(TrolleyDetectionAction, ForwardEntryGoalPointsIntoTheCart)
{
Rig rig;
ASSERT_TRUE(rig.store_ok);
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolley");
ASSERT_NE(h, nullptr);
ASSERT_TRUE(h->start(makeAction("DetectTrolley"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(h, cartLegs(kCartInLaser, 0.0, M_PI), kFrontTopic, kFrontFrame, 10),
ActionStatus::kSucceeded)
<< rig.last_message;
// Tâm xe trong base_link = 0.454 + 1.26; robot ở gốc map. Tiến vào: heading trỏ VÀO xe (+x).
const tf3::TransformStampedMsg out = rig.goal();
EXPECT_NEAR(out.transform.translation.x, kLaserX + kCartInLaser, 0.01);
EXPECT_NEAR(out.transform.translation.y, 0.0, 0.01);
EXPECT_LT(yawError(yawOf(out), 0.0), 0.02);
}
TEST(TrolleyDetectionAction, BackwardEntryGoalPointsOutOfTheEntry)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolleyBackward");
ASSERT_NE(h, nullptr);
ASSERT_TRUE(h->start(makeAction("DetectTrolleyBackward"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(h, cartLegs(kCartInLaser, 0.0, M_PI), kBackTopic, kBackFrame, 10),
ActionStatus::kSucceeded)
<< rig.last_message;
// Xe ở SAU robot: tâm tại −(0.454 + 1.26). Lùi vào: heading trỏ RA cạnh vào, về phía robot
// đứng lúc dò (+x) — robot lùi thẳng vào gầm, đầu robot vẫn hướng +x.
const tf3::TransformStampedMsg out = rig.goal();
EXPECT_NEAR(out.transform.translation.x, -(kLaserX + kCartInLaser), 0.01);
EXPECT_NEAR(out.transform.translation.y, 0.0, 0.01);
EXPECT_LT(yawError(yawOf(out), 0.0), 0.02);
}
TEST(TrolleyDetectionAction, TheGoalFollowsTheRobotPose)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolley");
ASSERT_NE(h, nullptr);
const double rx = 2.0, ry = 1.0, ryaw = 0.5;
ASSERT_TRUE(h->start(makeAction("DetectTrolley"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(h, cartLegs(kCartInLaser, 0.0, M_PI), kFrontTopic, kFrontFrame, 10, rx, ry,
ryaw),
ActionStatus::kSucceeded)
<< rig.last_message;
const double d = kLaserX + kCartInLaser;
const tf3::TransformStampedMsg out = rig.goal();
EXPECT_NEAR(out.transform.translation.x, rx + d * std::cos(ryaw), 0.01);
EXPECT_NEAR(out.transform.translation.y, ry + d * std::sin(ryaw), 0.01);
EXPECT_LT(yawError(yawOf(out), ryaw), 0.02);
}
TEST(TrolleyDetectionAction, PriorIsDeclaredInBaseLinkNotInTheLidarFrame)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolley");
ASSERT_NE(h, nullptr);
// Profile `tci_trolley_prior`: prior_x = 1.714 trong base_link, search_radius 0.30. Trong frame
// lidar tâm xe ở 1.26 — lệch 0.454 > 0.30. Chỉ qua khi prior được tính trong base_link.
ASSERT_TRUE(h->start(makeAction("DetectTrolley", "tci_trolley_prior"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(h, cartLegs(kCartInLaser, 0.0, M_PI), kFrontTopic, kFrontFrame, 10),
ActionStatus::kSucceeded)
<< rig.last_message;
}
// ================================================================================================
// 2. Lidar lộn ngược
// ================================================================================================
TEST(TrolleyDetectionAction, UpsideDownLidarIsReadThroughItsTf)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolley");
ASSERT_NE(h, nullptr);
// Lidar trước gắn roll π như hook_150. Nhìn từ trên xuống xe lệch TRÁI 0.15 m và xoay 0.1 rad;
// trong frame của chính lidar mọi thứ đối dấu y. Đọc TF chỉ lấy yaw thì đích lệch 0.30 m sang
// phải và yaw đổi dấu — robot chui vào chân xe.
rig.setStatic(kFlippedFrame, kLaserX, 0.0, M_PI);
const double cy = 0.15, axis = M_PI + 0.1;
ASSERT_TRUE(h->start(makeAction("DetectTrolley"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(h, mirrorY(cartLegs(kCartInLaser, cy, axis)), kFrontTopic, kFlippedFrame, 10),
ActionStatus::kSucceeded)
<< rig.last_message;
const tf3::TransformStampedMsg out = rig.goal();
EXPECT_NEAR(out.transform.translation.x, kLaserX + kCartInLaser, 0.01);
EXPECT_NEAR(out.transform.translation.y, cy, 0.01);
EXPECT_LT(yawError(yawOf(out), axis + M_PI), 0.02);
}
TEST(TrolleyDetectionAction, FindsTheTrolleyInARecordedGazeboScan)
{
// Scan /f_scan thật của Gazebo, lidar roll π, robot KHÔNG đứng ở pose chuẩn bị: tâm xe cách
// base_link 2.30 m, lệch ngang 0.22 m, xoay 17.7°. Đáp án lấy từ pose model trong Gazebo — xem
// đầu file data. Profile `tci_trolley` không có prior, đúng như config sim.
robot_sensor_msgs::LaserScan scan;
ASSERT_TRUE(loadRecordedScan(std::string(TROLLEY_DETECTION_ACTION_TEST_DATA_DIR) +
"/f_scan_tci_trolley_roll_pi.yaml",
scan));
ASSERT_EQ(scan.ranges.size(), 541u);
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolley");
ASSERT_NE(h, nullptr);
// base_link -> front_laser_link của hook_150 trong URDF sim.
rig.setStatic(scan.header.frame_id.c_str(), kLaserX, 0.0, M_PI, 0.0, 0.184);
ASSERT_TRUE(h->start(makeAction("DetectTrolley"), robot::Time(10.0)));
EXPECT_EQ(rig.feedScan(h, scan, kFrontTopic, 10), ActionStatus::kSucceeded) << rig.last_message;
// Robot ở gốc map nên map = base_link. Tiến vào: heading = trục +x của xe.
const tf3::TransformStampedMsg out = rig.goal();
EXPECT_NEAR(out.transform.translation.x, 2.301, 0.02);
EXPECT_NEAR(out.transform.translation.y, 0.216, 0.02);
EXPECT_LT(yawError(yawOf(out), 0.309), 0.02);
}
TEST(TrolleyDetectionAction, FailsWhenTheScanPlaneIsTilted)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolley");
ASSERT_NE(h, nullptr);
// Chúi xuống 0.2 rad (11.5°): mô hình chân 2D không còn đúng. Phải fail, không được ghi đích.
rig.setStatic(kTiltedFrame, kLaserX, 0.0, 0.0, 0.2);
ASSERT_TRUE(h->start(makeAction("DetectTrolley"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(h, cartLegs(kCartInLaser, 0.0, M_PI), kFrontTopic, kTiltedFrame, 3),
ActionStatus::kFailed);
EXPECT_NE(rig.last_message.find("tilted"), std::string::npos) << rig.last_message;
}
// ================================================================================================
// 3. Đường từ chối
// ================================================================================================
TEST(TrolleyDetectionAction, FailsWhenTheLidarFacesAgainstTheEntryDirection)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolleyWrong");
ASSERT_NE(h, nullptr);
// `forward` khai với lidar sau: goal sẽ ngược 180°. Phải fail ngay, không được ghi đích.
ASSERT_TRUE(h->start(makeAction("DetectTrolleyWrong"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(h, cartLegs(kCartInLaser, 0.0, M_PI), kBackTopic, kBackFrame, 3),
ActionStatus::kFailed);
EXPECT_NE(rig.last_message.find("entry_direction"), std::string::npos) << rig.last_message;
}
TEST(TrolleyDetectionAction, TimesOutWithTheMatcherReasonWhenNoCartIsThere)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolley");
ASSERT_NE(h, nullptr);
ASSERT_TRUE(h->start(makeAction("DetectTrolley"), robot::Time(10.0)));
// Chỉ một bức tường: không có chân nào. timeout = 5 s → cần hơn 50 tick 0.1 s.
const std::vector<Segment> wall = { { 2.0, -3.0, 2.0, 3.0 } };
EXPECT_EQ(rig.feed(h, wall, kFrontTopic, kFrontFrame, 60), ActionStatus::kFailed);
EXPECT_NE(rig.last_message.find("no 'tci_trolley' trolley"), std::string::npos)
<< rig.last_message;
}
TEST(TrolleyDetectionAction, RefusesAnUnknownProfile)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ActionHandler* h = rig.registry.find("DetectTrolley");
ASSERT_NE(h, nullptr);
// KHÔNG âm thầm rơi về default: dùng nhầm hình học là chui vào sai chỗ.
EXPECT_FALSE(h->start(makeAction("DetectTrolley", "khong_co_profile_nay"), robot::Time(10.0)));
}
TEST(TrolleyDetectionAction, RefusesToLoadWithoutASensorStore)
{
robot::NodeHandle nh;
tf3::BufferCore tf;
ActionContext ctx;
ctx.tf = &tf;
ctx.sensors = nullptr;
ctx.global_frame = kGlobalFrame;
ActionRegistry registry;
registry.setContext(ctx);
registry.loadFromConfig(nh, kNamespace);
EXPECT_EQ(registry.find("DetectTrolley"), nullptr);
}
} // namespace
int main(int argc, char** argv)
{
#ifdef TROLLEY_DETECTION_ACTION_TEST_CONFIG_DIR
setenv("PNKX_NAV_CORE_CONFIG_DIR", TROLLEY_DETECTION_ACTION_TEST_CONFIG_DIR, 0);
#endif
#ifdef TROLLEY_DETECTION_ACTION_TEST_LIBRARY_DIR
setenv("PNKX_NAV_CORE_LIBRARY_PATH", TROLLEY_DETECTION_ACTION_TEST_LIBRARY_DIR, 0);
#endif
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}