From bfdcac512fe37acfba267fb2608ddc4bfaa70745 Mon Sep 17 00:00:00 2001 From: duongtd Date: Wed, 28 Oct 2026 13:33:52 +0700 Subject: [PATCH] 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 --- CMakeLists.txt | 194 ++ README.md | 81 + doc/MEASURE_AND_CONFIGURE.md | 414 +++ doc/fig/cart_section.svg | 2115 +++++++++++++++ doc/fig/cart_top.svg | 2260 +++++++++++++++++ doc/fig/leg_measure.svg | 1766 +++++++++++++ doc/gen_fig.py | 166 ++ package.xml | 45 + plugins/trolley_detection_action_handler.cpp | 916 +++++++ sim/gen_trolley_models.py | 116 + sim/launch/spawn_trolley.launch | 33 + sim/models/trolley_4legs/model.config | 14 + sim/models/trolley_4legs/model.sdf | 73 + .../trolley_4legs_tape_all/model.config | 14 + sim/models/trolley_4legs_tape_all/model.sdf | 153 ++ .../trolley_4legs_tape_entry/model.config | 14 + sim/models/trolley_4legs_tape_entry/model.sdf | 113 + test/config/action_handlers_params.yaml | 93 + test/data/f_scan_tci_trolley_roll_pi.yaml | 18 + test/trolley_detection_action_test.cpp | 539 ++++ 20 files changed, 9137 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 doc/MEASURE_AND_CONFIGURE.md create mode 100644 doc/fig/cart_section.svg create mode 100644 doc/fig/cart_top.svg create mode 100644 doc/fig/leg_measure.svg create mode 100644 doc/gen_fig.py create mode 100644 package.xml create mode 100644 plugins/trolley_detection_action_handler.cpp create mode 100644 sim/gen_trolley_models.py create mode 100644 sim/launch/spawn_trolley.launch create mode 100644 sim/models/trolley_4legs/model.config create mode 100644 sim/models/trolley_4legs/model.sdf create mode 100644 sim/models/trolley_4legs_tape_all/model.config create mode 100644 sim/models/trolley_4legs_tape_all/model.sdf create mode 100644 sim/models/trolley_4legs_tape_entry/model.config create mode 100644 sim/models/trolley_4legs_tape_entry/model.sdf create mode 100644 test/config/action_handlers_params.yaml create mode 100644 test/data/f_scan_tci_trolley_roll_pi.yaml create mode 100644 test/trolley_detection_action_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..349e842 --- /dev/null +++ b/CMakeLists.txt @@ -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() diff --git a/README.md b/README.md new file mode 100644 index 0000000..cb35897 --- /dev/null +++ b/README.md @@ -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 +``` diff --git a/doc/MEASURE_AND_CONFIGURE.md b/doc/MEASURE_AND_CONFIGURE.md new file mode 100644 index 0000000..91b9da2 --- /dev/null +++ b/doc/MEASURE_AND_CONFIGURE.md @@ -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: + : # 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 → `, 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 + : + # [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. diff --git a/doc/fig/cart_section.svg b/doc/fig/cart_section.svg new file mode 100644 index 0000000..9ff23e5 --- /dev/null +++ b/doc/fig/cart_section.svg @@ -0,0 +1,2115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/doc/fig/cart_top.svg b/doc/fig/cart_top.svg new file mode 100644 index 0000000..0317f1a --- /dev/null +++ b/doc/fig/cart_top.svg @@ -0,0 +1,2260 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/doc/fig/leg_measure.svg b/doc/fig/leg_measure.svg new file mode 100644 index 0000000..8cede4e --- /dev/null +++ b/doc/fig/leg_measure.svg @@ -0,0 +1,1766 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/doc/gen_fig.py b/doc/gen_fig.py new file mode 100644 index 0000000..935beb1 --- /dev/null +++ b/doc/gen_fig.py @@ -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() diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..0b4c7b7 --- /dev/null +++ b/package.xml @@ -0,0 +1,45 @@ + + trolley_detection_action + 0.1.0 + + 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). + + DuongTD + DuongTD + BSD + + catkin + + action_core + action_core + + dock_pattern_detector + dock_pattern_detector + + robot_line_extraction + robot_line_extraction + + robot_sensor_ports + robot_sensor_ports + + robot_cpp + robot_cpp + + robot_sensor_msgs + robot_sensor_msgs + + tf3 + tf3 + + yaml-cpp + yaml-cpp + diff --git a/plugins/trolley_detection_action_handler.cpp b/plugins/trolley_detection_action_handler.cpp new file mode 100644 index 0000000..ab1837a --- /dev/null +++ b/plugins/trolley_detection_action_handler.cpp @@ -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 + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +// ================================================================================================ +// 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//...` 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(); + } + + 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{}); + 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(*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 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(); + 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(profile.min_leg_points); + nh_param(p_nh, "min_leg_points", min_leg_points); + profile.min_leg_points = static_cast(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(profile.tape_min_points); + nh_param(p_nh, "tape_min_points", tape_min_points); + profile.tape_min_points = static_cast(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 + 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(*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 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 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 ranges_; +}; + +} // namespace action_core + +ACTION_CORE_EXPORT_HANDLER(action_core::TrolleyDetectionActionHandler::create, + TrolleyDetectionActionHandler) diff --git a/sim/gen_trolley_models.py b/sim/gen_trolley_models.py new file mode 100644 index 0000000..88c5dcb --- /dev/null +++ b/sim/gen_trolley_models.py @@ -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""" + {x:.4f} {y:.4f} {z0 + h / 2:.4f} 0 0 0 + {retro} + {LEG} {LEG} {h:.4f} + + + {x:.4f} {y:.4f} {z0 + h / 2:.4f} 0 0 0 + {LEG} {LEG} {h:.4f} + {colour}{colour} + +""" + + +HEADER = """ + + + + true + +""" + +FOOTER = f""" + 0 0 {DECK_Z + DECK_T / 2:.3f} 0 0 0 + {DEPTH + LEG + 0.03:.3f} {OPENING + LEG + 0.03:.3f} {DECK_T:.3f} + + + 0 0 {DECK_Z + DECK_T / 2:.3f} 0 0 0 + {DEPTH + LEG + 0.03:.3f} {OPENING + LEG + 0.03:.3f} {DECK_T:.3f} + + + + +""" + + +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""" + + {name} + 1.1 + model.sdf + + DuongTD + tdd@gmail.com + + + 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. + + +""") + + +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") diff --git a/sim/launch/spawn_trolley.launch b/sim/launch/spawn_trolley.launch new file mode 100644 index 0000000..4edba07 --- /dev/null +++ b/sim/launch/spawn_trolley.launch @@ -0,0 +1,33 @@ + + + + + + + + + + + diff --git a/sim/models/trolley_4legs/model.config b/sim/models/trolley_4legs/model.config new file mode 100644 index 0000000..37f047b --- /dev/null +++ b/sim/models/trolley_4legs/model.config @@ -0,0 +1,14 @@ + + + trolley_4legs + 1.1 + model.sdf + + DuongTD + tdd@gmail.com + + + 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. + + diff --git a/sim/models/trolley_4legs/model.sdf b/sim/models/trolley_4legs/model.sdf new file mode 100644 index 0000000..f726920 --- /dev/null +++ b/sim/models/trolley_4legs/model.sdf @@ -0,0 +1,73 @@ + + + + + true + + + 0.3600 0.2585 0.1900 0 0 0 + 0 + 0.03 0.03 0.3800 + + + 0.3600 0.2585 0.1900 0 0 0 + 0.03 0.03 0.3800 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0.3600 -0.2585 0.1900 0 0 0 + 0 + 0.03 0.03 0.3800 + + + 0.3600 -0.2585 0.1900 0 0 0 + 0.03 0.03 0.3800 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + -0.3600 0.2585 0.1900 0 0 0 + 0 + 0.03 0.03 0.3800 + + + -0.3600 0.2585 0.1900 0 0 0 + 0.03 0.03 0.3800 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + -0.3600 -0.2585 0.1900 0 0 0 + 0 + 0.03 0.03 0.3800 + + + -0.3600 -0.2585 0.1900 0 0 0 + 0.03 0.03 0.3800 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0 0 0.390 0 0 0 + 0.780 0.577 0.020 + + + 0 0 0.390 0 0 0 + 0.780 0.577 0.020 + + + + diff --git a/sim/models/trolley_4legs_tape_all/model.config b/sim/models/trolley_4legs_tape_all/model.config new file mode 100644 index 0000000..a480515 --- /dev/null +++ b/sim/models/trolley_4legs_tape_all/model.config @@ -0,0 +1,14 @@ + + + trolley_4legs_tape_all + 1.1 + model.sdf + + DuongTD + tdd@gmail.com + + + 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. + + diff --git a/sim/models/trolley_4legs_tape_all/model.sdf b/sim/models/trolley_4legs_tape_all/model.sdf new file mode 100644 index 0000000..fd5eed8 --- /dev/null +++ b/sim/models/trolley_4legs_tape_all/model.sdf @@ -0,0 +1,153 @@ + + + + + true + + + 0.3600 0.2585 0.0700 0 0 0 + 0 + 0.03 0.03 0.1400 + + + 0.3600 0.2585 0.0700 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0.3600 0.2585 0.1900 0 0 0 + 2000 + 0.03 0.03 0.1000 + + + 0.3600 0.2585 0.1900 0 0 0 + 0.03 0.03 0.1000 + 0.9 0.9 0.2 10.9 0.9 0.2 1 + + + 0.3600 0.2585 0.3100 0 0 0 + 0 + 0.03 0.03 0.1400 + + + 0.3600 0.2585 0.3100 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0.3600 -0.2585 0.0700 0 0 0 + 0 + 0.03 0.03 0.1400 + + + 0.3600 -0.2585 0.0700 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0.3600 -0.2585 0.1900 0 0 0 + 2000 + 0.03 0.03 0.1000 + + + 0.3600 -0.2585 0.1900 0 0 0 + 0.03 0.03 0.1000 + 0.9 0.9 0.2 10.9 0.9 0.2 1 + + + 0.3600 -0.2585 0.3100 0 0 0 + 0 + 0.03 0.03 0.1400 + + + 0.3600 -0.2585 0.3100 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + -0.3600 0.2585 0.0700 0 0 0 + 0 + 0.03 0.03 0.1400 + + + -0.3600 0.2585 0.0700 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + -0.3600 0.2585 0.1900 0 0 0 + 2000 + 0.03 0.03 0.1000 + + + -0.3600 0.2585 0.1900 0 0 0 + 0.03 0.03 0.1000 + 0.9 0.9 0.2 10.9 0.9 0.2 1 + + + -0.3600 0.2585 0.3100 0 0 0 + 0 + 0.03 0.03 0.1400 + + + -0.3600 0.2585 0.3100 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + -0.3600 -0.2585 0.0700 0 0 0 + 0 + 0.03 0.03 0.1400 + + + -0.3600 -0.2585 0.0700 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + -0.3600 -0.2585 0.1900 0 0 0 + 2000 + 0.03 0.03 0.1000 + + + -0.3600 -0.2585 0.1900 0 0 0 + 0.03 0.03 0.1000 + 0.9 0.9 0.2 10.9 0.9 0.2 1 + + + -0.3600 -0.2585 0.3100 0 0 0 + 0 + 0.03 0.03 0.1400 + + + -0.3600 -0.2585 0.3100 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0 0 0.390 0 0 0 + 0.780 0.577 0.020 + + + 0 0 0.390 0 0 0 + 0.780 0.577 0.020 + + + + diff --git a/sim/models/trolley_4legs_tape_entry/model.config b/sim/models/trolley_4legs_tape_entry/model.config new file mode 100644 index 0000000..33e56db --- /dev/null +++ b/sim/models/trolley_4legs_tape_entry/model.config @@ -0,0 +1,14 @@ + + + trolley_4legs_tape_entry + 1.1 + model.sdf + + DuongTD + tdd@gmail.com + + + 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. + + diff --git a/sim/models/trolley_4legs_tape_entry/model.sdf b/sim/models/trolley_4legs_tape_entry/model.sdf new file mode 100644 index 0000000..45f92c8 --- /dev/null +++ b/sim/models/trolley_4legs_tape_entry/model.sdf @@ -0,0 +1,113 @@ + + + + + true + + + 0.3600 0.2585 0.0700 0 0 0 + 0 + 0.03 0.03 0.1400 + + + 0.3600 0.2585 0.0700 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0.3600 0.2585 0.1900 0 0 0 + 2000 + 0.03 0.03 0.1000 + + + 0.3600 0.2585 0.1900 0 0 0 + 0.03 0.03 0.1000 + 0.9 0.9 0.2 10.9 0.9 0.2 1 + + + 0.3600 0.2585 0.3100 0 0 0 + 0 + 0.03 0.03 0.1400 + + + 0.3600 0.2585 0.3100 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0.3600 -0.2585 0.0700 0 0 0 + 0 + 0.03 0.03 0.1400 + + + 0.3600 -0.2585 0.0700 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0.3600 -0.2585 0.1900 0 0 0 + 2000 + 0.03 0.03 0.1000 + + + 0.3600 -0.2585 0.1900 0 0 0 + 0.03 0.03 0.1000 + 0.9 0.9 0.2 10.9 0.9 0.2 1 + + + 0.3600 -0.2585 0.3100 0 0 0 + 0 + 0.03 0.03 0.1400 + + + 0.3600 -0.2585 0.3100 0 0 0 + 0.03 0.03 0.1400 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + -0.3600 0.2585 0.1900 0 0 0 + 0 + 0.03 0.03 0.3800 + + + -0.3600 0.2585 0.1900 0 0 0 + 0.03 0.03 0.3800 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + -0.3600 -0.2585 0.1900 0 0 0 + 0 + 0.03 0.03 0.3800 + + + -0.3600 -0.2585 0.1900 0 0 0 + 0.03 0.03 0.3800 + 0.3 0.3 0.3 10.3 0.3 0.3 1 + + + 0 0 0.390 0 0 0 + 0.780 0.577 0.020 + + + 0 0 0.390 0 0 0 + 0.780 0.577 0.020 + + + + diff --git a/test/config/action_handlers_params.yaml b/test/config/action_handlers_params.yaml new file mode 100644 index 0000000..ac0278f --- /dev/null +++ b/test/config/action_handlers_params.yaml @@ -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 diff --git a/test/data/f_scan_tci_trolley_roll_pi.yaml b/test/data/f_scan_tci_trolley_roll_pi.yaml new file mode 100644 index 0000000..9a18d47 --- /dev/null +++ b/test/data/f_scan_tci_trolley_roll_pi.yaml @@ -0,0 +1,18 @@ +# Một scan /f_scan THẬT của Gazebo (rostopic echo -n 1, 28/10/2026), dùng làm dữ liệu cho +# trolley_detection_action_test. Chỉ giữ hình học + ranges; intensities toàn 0 nên bỏ. +# +# Cảnh lúc chụp (world factory_ss_demo + spawn_trolley.launch), robot hook_150 đứng yên: +# - robot (base_link) trong world: (4.751, 35.021), yaw -0.309 rad +# - xe tci_trolley: model pose (6.5, 34.0, yaw 0) -> tâm 4 chân (7.009, 34.528) +# - tâm xe trong base_link: (2.301, 0.216), trục +x của xe (đầu tay đẩy) yaw +0.309 rad +# - base_link -> front_laser_link: (0.454, 0, 0.184), roll pi — lidar LỘN NGƯỢC, driver Gazebo +# không lật dữ liệu, nên 4 cụm chân nằm ở y đối dấu so với cách đọc chỉ theo yaw. +# Khớp offline (Python, cùng phần dư dọc tia với fitCartPose) sau khi đảo dấu góc tia: +# tâm (2.305, 0.221), heading 0.300 rad — lệch Gazebo 4–5 mm, 0.009 rad. +frame_id: front_laser_link +angle_min: -1.5882500410079956 +angle_max: 1.5882500410079956 +angle_increment: 0.005882407538592815 +range_min: 0.05000000074505806 +range_max: 29.0 +ranges: [15.125274658203125, 15.150546073913574, 15.185410499572754, 15.208866119384766, 15.263744354248047, 15.279812812805176, 15.326094627380371, 15.326067924499512, 15.36370849609375, 15.396552085876465, 12.689069747924805, 12.498387336730957, 12.29025936126709, 12.103754997253418, 11.926145553588867, 11.754026412963867, 11.587566375732422, 11.403573989868164, 11.249706268310547, 11.079050064086914, 10.92706298828125, 10.798961639404297, 10.667864799499512, 10.524938583374023, 10.372163772583008, 10.25019645690918, 10.129642486572266, 9.995819091796875, 9.869987487792969, 9.76936149597168, 9.651198387145996, 9.528088569641113, 9.422293663024902, 9.32686710357666, 9.217950820922852, 9.119080543518066, 9.033449172973633, 8.900473594665527, 8.839761734008789, 8.747269630432129, 8.649674415588379, 8.579972267150879, 8.491202354431152, 8.413658142089844, 8.33331298828125, 8.262343406677246, 8.233652114868164, 8.275256156921387, 8.303202629089355, 8.339621543884277, 8.348563194274902, 8.40923023223877, 8.444099426269531, 8.476513862609863, 8.51766586303711, 8.53529167175293, 8.552206039428711, 8.602558135986328, 8.659000396728516, 8.675546646118164, 8.705349922180176, 8.761495590209961, 8.806449890136719, 8.827065467834473, 8.878225326538086, 8.928638458251953, 8.968944549560547, 9.018550872802734, 9.08025074005127, 9.088199615478516, 9.142634391784668, 9.191244125366211, 9.237550735473633, 9.272567749023438, 9.345795631408691, 9.391139030456543, 9.431541442871094, 10.429391860961914, 10.372170448303223, 10.287919998168945, 10.22807502746582, 10.152524948120117, 10.093589782714844, 10.033902168273926, 10.103500366210938, 10.12427806854248, 10.199834823608398, 10.267254829406738, 10.33838176727295, 11.653353691101074, 11.685627937316895, 11.76777458190918, 13.600934982299805, 12.748566627502441, 12.68835163116455, 12.639899253845215, 12.5657958984375, 12.493792533874512, 12.438591957092285, 12.425661087036133, 12.515389442443848, 13.319783210754395, 11.891016006469727, 11.823391914367676, 11.91181468963623, 11.9948148727417, 12.10097599029541, 12.959375381469727, 12.90539836883545, 12.540627479553223, 12.490367889404297, 12.560050010681152, 12.679043769836426, 12.800292015075684, 12.902789115905762, 13.00754451751709, 13.11718463897705, 16.174991607666016, 16.101858139038086, 16.05902099609375, 15.999405860900879, 15.919600486755371, 15.870686531066895, 15.811039924621582, 15.736006736755371, 15.695985794067383, 14.415472984313965, 14.371819496154785, 14.314678192138672, 14.273612022399902, 14.332547187805176, 14.462952613830566, 14.636913299560547, 14.790173530578613, 15.225072860717773, 16.700237274169922, 16.67120933532715, 15.596040725708008, 15.642069816589355, 15.825906753540039, 16.01112937927246, 16.227914810180664, inf, inf, 28.512454986572266, 28.411314010620117, 28.343170166015625, 28.269426345825195, 28.179180145263672, 28.141372680664062, 28.32905387878418, inf, inf, inf, 21.630386352539062, 21.578168869018555, 21.51899528503418, 21.474517822265625, 21.72771453857422, 22.09821319580078, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, 26.12798309326172, 26.09819984436035, 26.073760986328125, 26.071788787841797, 26.045759201049805, 26.043493270874023, 26.0152530670166, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, 20.180084228515625, 19.626869201660156, 19.618867874145508, inf, inf, 2.177748441696167, 2.198274612426758, 2.1742641925811768, inf, 1.4566364288330078, 1.471392035484314, 1.4524986743927002, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, 27.79194450378418, inf, inf, inf, inf, 23.97160530090332, inf, inf, inf, 21.415145874023438, 20.146034240722656, 20.352659225463867, inf, inf, inf, 2.263207197189331, 2.2537500858306885, 2.238976001739502, 17.400447845458984, 17.080570220947266, 16.751178741455078, 16.419418334960938, 16.11258888244629, 15.826362609863281, 15.56047248840332, 15.577118873596191, 15.591734886169434, 15.633524894714355, 15.674528121948242, 5.990453243255615, 5.9375481605529785, 5.905572891235352, 5.903517723083496, 5.9033355712890625, 5.895660400390625, 5.494470596313477, 1.565724492073059, 1.5963528156280518, 1.5868083238601685, 5.3174729347229, 5.319922924041748, 5.309248447418213, 5.331012725830078, 5.338742733001709, 4.801239490509033, 4.794313907623291, 4.763574600219727, 4.763350486755371, 4.729177951812744, 4.747926712036133, 4.736950397491455, 4.7654571533203125, 4.758882999420166, 4.786961555480957, 4.3063154220581055, 4.238432884216309, 4.227863788604736, 4.204345226287842, 4.20133638381958, 4.1843037605285645, 4.190874099731445, 4.214629173278809, 4.205724239349365, 4.209419250488281, 4.219412803649902, 4.249765396118164, 4.275709629058838, 3.806727409362793, 3.730234384536743, 3.71000599861145, 3.706984758377075, 3.670616388320923, 3.6548948287963867, 3.6560075283050537, 3.660980224609375, 3.660745859146118, 3.667405605316162, 3.671442747116089, 3.6764817237854004, 3.686836004257202, 3.727994918823242, 3.7316346168518066, inf, 7.31005859375, 7.199386119842529, 3.2800755500793457, 3.22991943359375, 3.1935527324676514, 3.203883171081543, 3.182525157928467, 3.165379524230957, 3.1601760387420654, 3.1651387214660645, 3.1652843952178955, 3.1524040699005127, 3.1483733654022217, 3.1698215007781982, 3.1723473072052, 3.1840322017669678, 3.207927703857422, 3.2442924976348877, 3.253797769546509, 7.62278413772583, 13.464298248291016, 13.43019962310791, inf, inf, 6.254202842712402, 2.8242602348327637, 2.8210928440093994, 2.7752866744995117, 2.7734978199005127, 2.7346079349517822, 2.75992751121521, 2.739470958709717, 2.7361161708831787, 2.726456642150879, 2.7161262035369873, 2.748530149459839, 2.726562738418579, 2.7329671382904053, 2.7316856384277344, 2.7560389041900635, 2.759728193283081, 2.7610349655151367, 2.7856531143188477, 2.812556266784668, 2.8617656230926514, 5.938336372375488, 5.975382328033447, 6.042203426361084, 6.074085235595703, 6.1497883796691895, 6.1831135749816895, 6.238567352294922, 6.2963385581970215, 6.338898658752441, 6.398306369781494, 2.548734188079834, 2.463038444519043, 2.4317030906677246, 2.443005084991455, 2.4372804164886475, 2.3901357650756836, 2.3882453441619873, 2.383451223373413, 2.409623146057129, 2.3825061321258545, 2.3697357177734375, 2.3907110691070557, 2.3704581260681152, 2.391026496887207, 2.3844921588897705, 2.3830275535583496, 2.4027037620544434, 2.3837881088256836, 2.3997793197631836, 2.4071576595306396, 2.420729160308838, 2.445827007293701, 2.5131032466888428, 6.464375972747803, 6.476678371429443, 6.413737773895264, 6.418389320373535, 6.398654460906982, 6.377237796783447, 6.477107524871826, 6.578064918518066, 6.658166885375977, 6.751020431518555, 6.8704352378845215, 6.95804500579834, 7.050070285797119, 7.175622940063477, 7.293141841888428, 7.3951239585876465, 7.600884914398193, 7.580080986022949, 7.695852756500244, 7.811177730560303, 7.9525299072265625, 8.083815574645996, 8.203407287597656, 8.370820045471191, 8.523558616638184, 8.680453300476074, 8.931424140930176, 9.133475303649902, 9.307877540588379, 9.508557319641113, 9.712273597717285, 9.936345100402832, 10.169140815734863, 10.402667999267578, 10.651567459106445, 10.88205623626709, 11.16058349609375, 6.945870399475098, 6.892714977264404, 6.8473663330078125, 6.866583824157715, 6.849597930908203, 6.839140892028809, 6.838578224182129, 6.825396537780762, 6.821080207824707, 6.799269676208496, 6.8038835525512695, 6.796494483947754, 6.7919392585754395, 6.771730422973633, 6.785391330718994, 6.790872097015381, 6.756748676300049, 6.776483058929443, 6.734973430633545, 6.738811016082764, 6.74718713760376, 6.746816635131836, 6.738222122192383, 6.7336907386779785, 6.739088535308838, 6.713690280914307, 6.748056411743164, 6.735966205596924, 6.721977233886719, 6.718607425689697, 6.736966609954834, 6.70856237411499, 6.735860347747803, 6.716898441314697, 6.716060161590576, 6.715165615081787, 6.702150821685791, 6.708162307739258, 6.710867881774902, 6.709833145141602, 6.707076549530029, 6.716832637786865, 6.693012237548828, 6.702276706695557, 6.709875583648682, 6.71188497543335, 6.730398654937744, 6.717901229858398, 6.717051982879639, 6.730804920196533, 6.709015846252441, 6.732855796813965, 6.7286481857299805, 6.7396135330200195, 6.740046977996826, 6.74324369430542, 6.742472171783447, 6.80005407333374, 6.823938846588135, 12.993891716003418, inf, inf, inf, inf, 13.076289176940918, 13.048653602600098, 13.02476978302002, 13.076284408569336, inf, inf, inf, 13.264623641967773, 13.149445533752441, 13.140326499938965, 13.166290283203125, 13.229671478271484, 20.608545303344727, inf, inf, 13.366365432739258, 13.305100440979004, 13.282632827758789, 13.318052291870117, inf, inf, inf, inf, 13.469935417175293, 13.456972122192383, 12.909279823303223, 12.879064559936523, 12.407270431518555, 12.326444625854492, 12.290238380432129, 12.33171272277832] diff --git a/test/trolley_detection_action_test.cpp b/test/trolley_detection_action_test.cpp new file mode 100644 index 0000000..e508160 --- /dev/null +++ b/test/trolley_detection_action_test.cpp @@ -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 + +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include + +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::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 cartLegs(double cx, double cy, double axis) +{ + std::vector 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 mirrorY(std::vector 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(); + scan.angle_min = node["angle_min"].as(); + scan.angle_max = node["angle_max"].as(); + scan.angle_increment = node["angle_increment"].as(); + scan.range_min = node["range_min"].as(); + scan.range_max = node["range_max"].as(); + 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& 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(kRays - 1); + scan.range_min = 0.05f; + scan.range_max = 29.0f; + scan.ranges.assign(kRays, static_cast(kInf)); + + for (std::size_t i = 0; i < kRays; ++i) + { + const double bearing = scan.angle_min + static_cast(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(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& 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 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(); +}