14 Commits

Author SHA1 Message Date
ab9ed67f97 feat: resume driving during a stationary recovery; host intrusion detector
- recovery_resume: while an allowed stationary behavior (detour_path)
  runs, probe the local planner; its command never reaches the arbiter;
  after N moving cycles cancel the recovery and resume the current plan,
  capped per leg
- host the env_monitor_core IntrusionDetector (EnvContext, footprint)
- runtime config: recovery_resume keys, priest_fallback keys, evade
  max_tf_gap / view_loss_timeout, SBPL detour options, env_monitor tuning
2026-11-27 22:06:59 +07:00
6c0b9e110a wip(env_monitor): raw scan sampling for intrusion detector, env brake blocks controller only
- CostmapEnvironment::sampleScans: raw LaserScan + fixed-frame poses for detectors
  that need scans (EnvNeeds.scans); recovery deps carry SensorReader for EvadeRecovery
- EnvMonitor brake now blocks only VelocitySource::kController; a latched kContact
  brake no longer zeroes the evade back-up command in RECOVERING (sim 27/11 14:21)
- test: LatchedBrakeDoesNotZeroTheRecoveryVelocity
- config/runtime: env_monitor, recovery_behaviors, priest_mpcc, lane_route,
  global costmap plugin keys in progress

Not built or tested yet.
2026-11-27 15:11:21 +07:00
1aa2a07469 refactor: host EnvMonitor from env_monitor_core, route per detector
EnvMonitor and its detectors now live in env_monitor_core. NavigationRuntime owns
the monitor; StateMachine runs each detector's own route (step or sequence,
lock or abort on exhaustion) with a cursor per detector. RecoveryRunner accepts
named routes for detectors outside the six built-in triggers.
2026-11-27 10:08:52 +07:00
605dbc8e22 config(runtime): PRIEST footprint_padding 0.05 -> 0.03 2026-11-20 16:46:02 +07:00
9efcb6db15 config(runtime): zone layers, zero_is_valid, PRIEST rectangle/crawl, lane route keys
- costmap: zero_is_valid (off) for both laser sources; forbidden zones in the local
  costmap; global keeps forbidden + preferred, direction_zones and unpreferred off.
- PRIEST: rectangle footprint model, obstacle threshold 254, smaller margins and the
  crawl-along-PRIEST settings with their debug switch.
- lane_route_planner: detour upgrade keys and allow_unknown (false).
2026-11-20 16:30:39 +07:00
168af1ceec fix(state_machine): keep travel toward recovery_reset_min_travel across origin resets
The travel mark was reset to 0 whenever the oscillation origin was reset by a
recovery without a new path or by resume, so distance driven before a clear
recovery was lost and the next detour was denied a budget refill (robot 19/11:
0.245 m driven before clear). The mark now moves to the new origin, so travel
before and after the reset adds up. Tests cover the split-travel cases.
2026-11-20 16:30:39 +07:00
0788bc666e build: tests off by default, nav_test_harness only for tests
BUILD_MOVE_BASE2_TESTS now defaults to OFF in both build modes.

nav_test_harness is a test-only package that exists only on the
development machine. It was a catkin component and a build/run
dependency, so configuring move_base2 failed on any machine without it,
even with the tests off. It is now found inside the test block only and
declared as test_depend. The scenario directory comes from the harness
package config instead of a guessed ../nav_test_harness path, and the
stale standalone include path is gone.
2026-11-17 20:36:12 +07:00
ee3657fefb config(runtime): drop prior_frame and the wall core threshold keys
Both detectors now use robot_base_frame. sim_wall_pair keeps only
tape_min_intensity; core threshold and plateau fraction take their defaults.
2026-11-12 17:01:54 +07:00
154fb7d091 feat(planner_runner): bind dock_maximum_cusp_distance per docking marker
Copies the per-marker cusp-to-goal cap to the DockPlanner namespace and clears it
with YAML null when the next marker does not declare it. dock_global_params.yaml
gets the default maneuver/maximum_cusp_distance: 0.0 (no cap).
2026-11-12 16:28:15 +07:00
dd0a657947 config(runtime): wall reflector station for the Gazebo test (detect + GoToWallStation)
- action_handlers: detect_wall_reflector (WallReflectorDetectionActionHandler,
  rear /b_scan, backward entry) with the sim profile sim_wall_pair: strips
  0.03 m wide, 0.09 m apart, Gazebo laser_retro intensity, offset_x 0.85.
  SIM-ONLY numbers; the robot profile lives in rb_ws.
- compound_actions: GoToWallStation = DetectWallReflectors, then move_to
  wall_reflector_target with profile docking and marker wall_station.
- maker_sources: wall_station in the allow-list and its profile
  (DockPlanner + HybridDockingLocalPlanner, dock_anchor mating_edge,
  dock_face_offset 0.85 = offset_x, dock_straight_length 0.3).
2026-11-12 15:44:27 +07:00
0d00c22fe8 feat(planner_runner): bind dock_straight_length per docking marker
A docking marker profile can now override DockPlanner's
terminal/straight_length with dock_straight_length (dock_planner c94c5b2).
It goes through the same path as dock_face_offset and
dock_pivot_safety_margin: copied into the planner namespace when the marker
declares it, written as YAML null when the next marker does not, so one
marker's value never leaks into another and the global default stays
untouched. Valid for every dock_anchor.

- Test: copied for the marker that declares it, null and rebuilt for the
  next marker, restored when the first marker comes back, and
  terminal/straight_length is never written.
- maker_sources.yaml / dock_global_params.yaml: document the key.
2026-11-12 15:44:14 +07:00
5882082172 fix(env_monitor): ignore relocalization pose jumps, veto confined gate on proven progress
Sim 6/11 20:34: AMCL "Setting pose" pulled the map pose back 1.2 m while the
robot drove straight. EnvMonitor counted the jump as travel, the 20 s position
window folded onto itself and the confined gate fired a false stall.

- env_monitor/pose_jump_reject [m] (default 0.5, 0 = off): a pose step larger
  than this plus the reachable distance since the last valid pose is a reset,
  not travel. Stall windows restart at most once per longest position window;
  repeated jumps are reported but keep the windows. The jump distance is added
  to the cost_jump allowance. The control loop passes NaN when there is no pose
  and logs each jump as a warning.
- env_monitor/stall/progress_veto (default true): the confined gate does not
  fire while every eff measured in confine_window_s is >= eff_off. The idle gate
  is not vetoed; a cost jump breaks the proof.
- Tests: env_monitor_test 66 (3 new cases fail on the old code),
  config_validation_test 37.

Config runtime: the two keys above; lane_route_planner zone_deviation_weight and
output_endpoint_spins (R2.12), route_too_long_* marked as compatibility keys;
DirectionalLayer type unquoted in the no-virtual-walls global plugin list.
2026-11-12 10:23:23 +07:00
42b03e0d78 config(runtime): lane route planner, zone layers, trolley detection, MPCC profiles
- Position profile uses LaneRoutePlanner with PriestMpccLocalPlanner; new
  lane_route_planner_params.yaml, mpcc_local_planner_params.yaml and
  priest_mpcc_local_planner_params.yaml.
- Global costmap: DirectionalLayer plus forbidden/preferred/unpreferred zone
  layers (directional_layer_params.yaml) and the reference graph keys; the
  local costmap keeps the reference graph off.
- TrolleyDetectionActionHandler and a DetectTrolley compound action.
- Dock global planner notes (mating_edge, dock_face_offset), priest planner
  tuning, sbpl primitive path moved to pnkx_nav_core.
- Sim launch defaults to robot_type hook_150.
2026-11-10 16:38:10 +07:00
051e18f989 feat(move_base2): direction zone delivery and costmap readiness wait
- SensorGateway::pushStaticMap also dispatches to DIRECTIONAL_LAYER on
  the global costmap, before STATIC_LAYER: with a same-geometry map the
  directional layer goes PENDING before StaticLayer can report current,
  so a plan cannot pair the new map with the old zones.
- Static maps are replayed in arrival order instead of topic order, so a
  direction grid is never replayed before its static map.
- PlannerRunner checks every enabled global layer under the same lock as
  the snapshot. While a layer is not current it keeps the goal, reports
  waiting_for_costmap, logs the stale layers (throttled) and spends no
  planner_patience or watchdog budget. After costmap_ready_timeout [s]
  (default 10, 0 = legacy behaviour) the attempt fails as before. The
  key is added to config/runtime/move_base_common_params.yaml.
- Test fixture destroys the server before its fake ports (the control
  thread could call a destroyed port).

Full history: branch feature/direction-zone.
2026-11-04 13:24:22 +07:00
60 changed files with 3566 additions and 2704 deletions

View File

@@ -90,7 +90,6 @@ if(NOT BUILDING_WITH_CATKIN)
${CMAKE_CURRENT_SOURCE_DIR}/../action_core/include
${CMAKE_CURRENT_SOURCE_DIR}/../mission_adapters/include
${CMAKE_CURRENT_SOURCE_DIR}/../robot_sensor_ports/include
${CMAKE_CURRENT_SOURCE_DIR}/../nav_test_harness/include
/usr/local/include
)
@@ -109,6 +108,9 @@ if(NOT BUILDING_WITH_CATKIN)
action_core
mission_adapters
# Lõi EnvMonitor. Nhánh standalone cần `add_subdirectory` của gói này ở pnkx_nav_core/CMakeLists.txt.
env_monitor_core
# Kho cảm biến thô dùng chung. NavigationServer ghi vào, runner phát cổng đọc ra plugin.
robot_sensor_ports
@@ -161,6 +163,9 @@ else()
# ActionRunner include thẳng action_core: chỗ duy nhất trong gói này biết tới nó.
action_core
# ControlLoop giữ EnvMonitor (lõi giám sát môi trường) và nối verdict vào state machine.
env_monitor_core
# Kho cảm biến thô dùng chung. NavigationServer ghi vào, runner phát cổng đọc ra plugin.
robot_sensor_ports
@@ -168,8 +173,8 @@ else()
# (MissionAdapterBridge dịch contract, MissionLayer lắp ráp framework).
mission_adapters
# scenario_test chạy kịch bản khai báo qua khung của nav_test_harness.
nav_test_harness
# nav_test_harness KHÔNG nằm ở đây: gói chỉ có trên máy dev, chỉ test dùng. Nó được
# find_package riêng trong khối test, để máy không có gói này vẫn build được move_base2.
)
find_library(TF3_LIBRARY
@@ -235,7 +240,6 @@ add_library(move_base2_core SHARED
src/velocity_arbiter.cpp
src/plan_inspector.cpp
src/grid_analysis.cpp
src/env_monitor.cpp
src/control_loop.cpp
src/config/move_base2_config.cpp
src/runners/recovery_runner.cpp
@@ -415,14 +419,29 @@ endif()
# ========================================================
# Tests
# ========================================================
option(BUILD_MOVE_BASE2_TESTS "Build move_base2 tests" ON)
# Tests are OFF by default in both build modes; enable with -DBUILD_MOVE_BASE2_TESTS=ON.
option(BUILD_MOVE_BASE2_TESTS "Build move_base2 tests" OFF)
if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN AND CATKIN_ENABLE_TESTING)
if(NOT COMMAND catkin_add_gtest)
message(FATAL_ERROR "catkin_add_gtest NOT FOUND")
endif()
# Bộ fake và scenario runner dùng chung cho test. Chỉ tìm khi bật test: gói này chỉ có trên máy dev.
find_package(nav_test_harness REQUIRED)
# Kịch bản là DỮ LIỆU nằm ở nav_test_harness; test không được đoán đường dẫn tới nó.
# devel space: thư mục nguồn của gói; install space: share/nav_test_harness/scenarios.
if(nav_test_harness_SOURCE_PREFIX)
set(MOVE_BASE2_SCENARIO_DIR "${nav_test_harness_SOURCE_PREFIX}/scenarios")
else()
get_filename_component(MOVE_BASE2_SCENARIO_DIR "${nav_test_harness_DIR}/../scenarios" ABSOLUTE)
endif()
if(NOT EXISTS "${MOVE_BASE2_SCENARIO_DIR}")
message(FATAL_ERROR "move_base2: nav_test_harness scenarios not found at '${MOVE_BASE2_SCENARIO_DIR}'")
endif()
# Plugin global planner chỉ dùng cho test — nạp qua Boost.DLL đúng đường runtime đi, không link
# thẳng. Đặt trong nhánh test để không bao giờ lọt vào bản cài đặt.
foreach(test_plugin move_base2_test_global_planner move_base2_test_local_planner)
@@ -458,7 +477,6 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
velocity_arbiter_test
plan_inspector_test
grid_analysis_test
env_monitor_test
walking_skeleton_test
config_validation_test
action_runner_test
@@ -494,12 +512,14 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
target_include_directories(${test_name} SYSTEM
PRIVATE
${catkin_INCLUDE_DIRS}
${nav_test_harness_INCLUDE_DIRS}
)
# catkin_add_gtest đã dùng target_link_libraries dạng plain, nên phần bổ sung cũng phải plain.
target_link_libraries(${test_name}
move_base2_core
${catkin_LIBRARIES}
${nav_test_harness_LIBRARIES}
${Boost_LIBRARIES}
yaml-cpp
${CMAKE_DL_LIBS}
@@ -510,8 +530,7 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
target_compile_definitions(${test_name} PRIVATE
MOVE_BASE2_TEST_CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/config"
MOVE_BASE2_TEST_LIBRARY_DIR="${CATKIN_DEVEL_PREFIX}/lib"
# Kịch bản là DỮ LIỆU nằm ở nav_test_harness; test không được đoán đường dẫn tới nó.
MOVE_BASE2_SCENARIO_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../nav_test_harness/scenarios"
MOVE_BASE2_SCENARIO_DIR="${MOVE_BASE2_SCENARIO_DIR}"
)
endif()
endforeach()

View File

@@ -77,6 +77,13 @@ cây nav core.
cấu hình đang có hiệu lực sẽ nằm trong cây config của nav core, không nằm trong gói này — bản trong
`test/` nếu có chỉ phục vụ test và phải chạy kèm biến môi trường trỏ vào đúng thư mục đó.
EnvMonitor (giám sát môi trường: contact / stall / unreachable) nằm ở gói riêng `env_monitor_core` từ 26/11/2026.
`NavigationRuntime` gọi `EnvMonitor::initialize(root_nh)` và đưa con trỏ vào `ControlLoopDeps::env_monitor`;
`ControlLoop` chỉ gom feature (`EnvironmentPort`), nối `fired_mask` vào state machine và áp
`brake_applied`/`v_cap_applied`. Mỗi detector tự chọn route recovery (`route`, `route_mode: step|sequence`,
`on_exhausted: lock|abort`); `ControlLoop::configure` dựng `StateMachineConfig::detector_routes` theo đúng thứ tự
detector. Xem README của `env_monitor_core` và `Test/docs/move_base2/ENV_DETECTOR_PLUGINS_PROMPT.md`.
## Trạng thái
Runtime thật đã chạy trọn trên sim: costmap, planner/controller/recovery/action nạp qua boost::dll,

View File

@@ -38,6 +38,10 @@ actions:
- {name: detect, type: FrameSamplerActionHandler}
- {name: detect_lidar, type: DockPatternActionHandler}
# Dò xe hàng 4 chân từ scan LiDAR THÔ (gói trolley_detection_action), ghi cùng `dock_target`
# như hai bộ dò trên. Xem khối `detect_trolley` bên dưới; plan ở Test/docs/trolley_detection_action.
- {name: detect_trolley, type: TrolleyDetectionActionHandler}
# Hai handler THẬT, chạy được cả trên robot: chúng không điều khiển thiết bị nào vì chính action
# đó không yêu cầu thiết bị nào.
- {name: waiter, type: WaitActionHandler}
@@ -50,6 +54,122 @@ actions:
# PLC/băng tải/càng nâng) trước khi chạy ngoài hiện trường.
- {name: sim_noop, type: NoopActionHandler}
# SIM-ONLY: dùng lidar sau để xác định trạm dừng trên tường.
- {name: detect_wall_reflector, type: WallReflectorDetectionActionHandler}
# --- detect_wall_reflector — SIM-ONLY: tường phẳng và hai dải, KHÔNG dùng cho robot thật -------
detect_wall_reflector:
# [-] Loại action nội bộ; đổi phải khớp bước action trong compound, sai tên sẽ không định tuyến.
action_types: [DetectWallReflectors]
# [frame] Đích base_link; đổi phải đồng bộ move_to, sai frame có thể dùng nhầm TF cũ.
output_frame: wall_reflector_target
# [frame] Tâm/pháp tuyến; để "" tắt, đổi tên phải đổi công cụ quan sát.
marker_frame: wall_reflector_frame
# [topic] Lidar sau sim hook_150; đổi chỉ khi sensor store khai topic và lidar đúng phía.
scan_topic: /b_scan
# [-] Lùi vào tường; đổi forward phải đổi lidar và kiểm lại heading.
entry_direction: backward
# [-] Profile mô hình sim; đổi phải chọn profile đã khai, không dùng số này cho robot thật.
default_profile: sim_wall_pair
# [-] Khóa trong actionParameters để chọn profile; đổi phải đồng bộ phía gửi order.
profile_param_key: reflector_profile
# [s] Chờ robot hết rung; tăng an toàn hơn nhưng chậm dò.
settle_delay: 0.4
# [s] Hạn action; tăng chờ lâu hơn, phải lớn hơn settle + window + hold.
timeout: 15.0
# [s] Tuổi scan tối đa; tăng chịu jitter nhưng dễ dùng dữ liệu cũ.
max_scan_age: 0.5
# [s] Cho phép stamp tương lai; tăng chịu lệch đồng hồ nhưng che lỗi đồng bộ.
max_future_skew: 0.05
# [s] Hạn giữ detection chờ TF; tăng chịu TF trễ, không vượt max_scan_age.
pending_tf_timeout: 0.2
# [m] Khoảng tia được xử lý. Dải 3 cm với S300 sim (bước 0.337°) chỉ còn ~3.4 tia ở 1.5 m,
# sát `tape_min_points: 3`: max_range 1.6 giữ phép dò trong tầm đó. Tăng max thì dải xa thiếu
# tia và bị loại; giảm quá khoảng cách lidar–tường cộng nửa baseline tường thì mất support.
min_range: 0.1
max_range: 1.6
# [-] Range 0 coi là không echo; P1 vẫn loại range 0 khỏi support ở cả hai chế độ.
zero_range_is_no_echo: true
# [số] Giới hạn tải; tăng cho cảnh phức tạp tốn CPU, vượt hạn thì loại scan chứ không cắt.
max_candidates: 16
max_pairs: 120
max_scan_rays: 4096
# [s, mẫu] Cửa sổ và số scan độc lập; tăng giảm nhiễu nhưng làm chậm chốt.
sample_window: 1.0
min_samples: 5
# [m, rad] Trần độ tản; tăng dễ chốt hơn nhưng không bảo đảm độ chính xác thật.
max_spread_xy: 0.03
max_spread_yaw: 0.05
# [s] Thời gian giữ ổn định; tăng giảm chốt nhất thời nhưng tăng latency.
hold_time: 0.0
# [m] Ngưỡng gom cụm; 0 tắt, nếu bật phải > max_spread_xy.
jump_threshold: 0.0
# [s, tỉ lệ, mẫu] Giới hạn cụm khi bật gom; recency lớn giữ cụm cũ lâu hơn.
cluster_recency: 0.3
min_cluster_fraction: 0.6
min_cluster_samples: 3
debug:
# [-] Log theo nhóm mặc định bật; tắt từng nhóm để giảm log, lỗi không bị tắt.
state: true
detect: true
skip: true
profiles:
sim_wall_pair:
# [m] Dải rộng 0.03, tâm cách 0.09 (khe tường giữa 0.06) — đúng kích thước người dùng đang
# thử ngày 12/11/2026; model sim sinh theo cùng số. Đổi dải thật thì đo lại cả hai số.
tape_width: 0.03
tape_spacing: 0.09
# [m] Dung sai kích thước = 2 × sai số lượng tử một mép ở tầm xa nhất (S300 sim 1.5 m:
# 1.5 × 0.0059 / 2 ≈ 4.4 mm) cộng dư. Tăng chịu góc xiên/tầm xa hơn nhưng dễ ghép nhầm một
# vật sáng khác; giảm dưới ~0.009 thì cặp thật ở 1.5 m bị loại vì `width`/`spacing`.
width_tolerance: 0.010
spacing_tolerance: 0.010
# [đơn vị Gazebo] Ngưỡng duy nhất của dải: tape 2000, tường 0; tăng quá 2000 mất dải.
# Khi lidar có bloom giữa hai mức, có thể thêm tape_core_intensity (mặc định bằng
# tape_min_intensity) và tape_plateau_min_fraction (mặc định 1.0).
tape_min_intensity: 1000.0
# [tia] Ít nhất 3 tia core; tăng chống nhiễu nhưng dải 30 mm ở xa (S300 sim > ~1.5 m,
# nhìn xiên 30° > ~1.3 m) không đủ tia.
tape_min_points: 3
# [rad] Sim không mô hình bloom; 0 không mask thêm; KHÔNG suy ra KIT.
tape_bloom_max_angle: 0.0
# [m] SIM-ONLY: bound mép và trần lượng tử; tăng trần nhận góc xấu hơn nhưng sai số lớn hơn.
edge_bias_bound: 0.002
max_edge_uncertainty: 0.03
# [-] Cos tối thiểu tia/tường; tăng loại góc xiên sớm hơn.
min_ray_wall_cos: 0.35
# [tia, m] Support mỗi bên và baseline; tăng giúp fit bền nhưng khó dò gần mép tường.
wall_min_points_each_side: 5
wall_min_span: 0.65
# [m] S300 sim sigma 0.01: RMS 2.5 sigma, residual 6 sigma; tăng dễ lọt tường/vật sai.
wall_max_rms: 0.025
wall_max_residual: 0.06
# [m] Khoảng hở tối đa giữa hai tia tường liên tiếp: phải bao một dải (0.03) + một bước tia
# ở tầm xa + nhiễu chiếu dọc tường. Sim không có bloom nên khe 0.06 giữa hai dải vẫn là
# support. Với lidar thật có bloom che kín khe, phải ≥ cả cặp (0.12) + hai skirt bloom.
# Tăng có thể che lỗ hoặc vật chắn trong cửa sổ tường.
wall_max_gap: 0.08
# [m] 0 không ngoại suy mép khỏi support; tăng nhận được gần mép nhưng kém tin cậy.
wall_max_extrapolation: 0.0
# [m] Chênh residual nhóm; 0.025 theo sigma sim 0.01, tăng dễ gộp hai mặt khác nhau.
wall_merge_distance: 0.025
# [-, m, rad] Prior tắt trong sim; bật phải đo tâm/yaw trong base_link, dung sai lớn dễ nhầm.
has_prior: false
prior_x: 0.0
prior_y: 0.0
prior_yaw: 0.0
prior_position_tolerance: 0.5
prior_yaw_tolerance: 0.5
# [rad] Quạt quanh phía sau; tăng nửa góc thấy rộng hơn nhưng dễ có nhiều cặp.
search_center_yaw: 3.141592653589793
search_fov: 1.570796326794897
# [m] Gốc base_link cách mặt tường 0.85. Nửa thân 1.031/2=0.5155 m → dư 0.3345 m;
# tape nhô 0.002 m còn ~0.3325 m. Giảm khoảng dừng làm giảm clearance: nguy hiểm.
offset_x: 0.85
# [m, rad] Dịch ngang và hiệu chỉnh yaw; đổi phải kiểm lại footprint và chiều lùi.
offset_y: 0.0
offset_yaw: 0.0
# --- detect: lấy mẫu frame đích rồi ghi ra một frame TF ổn định ---------------------------------
#
# BỐN NHÓM KHOÁ, đọc từ trên xuống:
@@ -191,6 +311,9 @@ actions:
# PHẢI khớp một `topic` đã khai trong sensor_store_params.yaml. Gõ sai là handler TỪ CHỐI NẠP
# lúc boot kèm danh sách topic có thật — không để nó thành một lượt dò hết giờ.
scan_topic: /b_scan
# backward: lùi vào, heading goal hướng RA khỏi trạm; forward: tiến vào, heading hướng VÀO.
# Đổi hướng phải đổi scan_topic sang lidar cùng phía; lidar lộn ngược được tự nhận qua TF.
entry_direction: backward
# [s] Chờ robot đứng hẳn trước khi lấy mẫu — pose lúc vừa dừng còn dao động cơ khí.
settle_delay: 0.4
@@ -263,6 +386,18 @@ actions:
# song nào cũng có giao điểm, nhưng chỉ chữ V mới có hai đoạn KẾT THÚC tại đó.
vertex_gap: 0.05
# Lòng V phải mở về hướng nào so với cảm biến: any | concave | convex.
#
# `any` (mặc định) = nhận cả hai hướng, giống hành vi trước khi có khoá này. Góc đỉnh +
# chiều dài cánh KHÔNG đủ phân biệt trạm thật với góc lồi cùng kích thước (tủ, pallet) —
# cả hai đều là một chữ V hợp lệ với hai cổng đó.
#
# ► Chỉnh: đặt `concave` hoặc `convex` SAU KHI đã xác nhận bằng scan thật — so khoảng cách
# từ cảm biến tới đỉnh với khoảng cách tới hai đầu mút cánh. Mút GẦN cảm biến hơn đỉnh =
# concave (tấm ôm lấy robot); mút XA hơn đỉnh = convex. Đoán sai hướng ở đây loại luôn
# trạm thật, triệu chứng giống hệt "dò mãi không ra".
v_shape: any
# Số tia đỡ tối thiểu cho MỘT cánh.
#
# ► Khoá này quyết định GÓC NHÌN CHO PHÉP nhiều hơn là tầm xa. Nhìn tấm chếch thì cánh xa
@@ -299,7 +434,8 @@ actions:
# quên nửa thân xe ở đây là robot lùi xuyên qua tấm rồi kẹt, bánh quay mà xe không đi.
#
# Công thức:
# offset_x >= |footprint sau| + footprint_padding
# offset_x >= |footprint sau| (backward) hoặc |footprint trước| (forward)
# + footprint_padding
# + wing_length * sin((pi - vertex_angle)/2) <-- đầu cánh nhô về phía robot
# + khe hở
#
@@ -320,6 +456,7 @@ actions:
# ► Chỉnh: đổi xe, đổi padding hoặc đổi tấm thì PHẢI tính lại — con số này gắn với CẢ xe
# lẫn tấm, không phải chỉ tấm.
offset_x: 0.95
# offset_y dương sang trái trong hệ hình; forward quay mặt vào trạm nên là bên PHẢI robot.
offset_y: 0.0 # [m] bù tấm lắp lệch NGANG so với đầu cắm
offset_yaw: 0.0 # [rad] bù tấm lắp XOAY so với đầu cắm
@@ -347,6 +484,7 @@ actions:
angle_tolerance: 0.20
length_tolerance: 0.06
vertex_gap: 0.05
v_shape: any # any | concave | convex — xem ghi chú ở v_std
min_wing_points: 5 # xem ghi chú ở v_std
min_confidence: 0.4
search_fov: 0.0 # [rad] xem ghi chú ở v_std
@@ -369,6 +507,7 @@ actions:
angle_tolerance: 0.20 # [rad]
length_tolerance: 0.06 # [m]
vertex_gap: 0.05 # [m]
v_shape: any # any | concave | convex — xem ghi chú ở v_std
min_wing_points: 5
min_confidence: 0.4
search_fov: 0.0 # [rad]
@@ -490,7 +629,8 @@ actions:
# R - R*cos(arc_span/2) = 0.4 - 0.4*cos(1.0) = 0.1839 m
#
# Công thức:
# offset_x >= |footprint sau| + footprint_padding + (mép miệng nhô ra) + khe hở
# offset_x >= |footprint sau| (backward) hoặc |footprint trước| (forward)
# + footprint_padding + (mép miệng nhô ra) + khe hở
# = 0.583 + 0.070 + 0.184 + 0.08 = 0.917
#
# ► Lấy 0.583 và 0.070 ở đâu: xem ghi chú dài trong `v_std`, đó là chỗ dễ tìm nhầm file nhất.
@@ -502,6 +642,181 @@ actions:
# tape_enabled KHÔNG khai được cho biên dạng arc: handler từ chối ngay lúc boot. `findTape`
# quét theo chỉ số tia của một ĐOẠN THẲNG, mà cung tròn không sinh ra đoạn nào.
# --- detect_trolley: dò xe hàng 4 chân từ scan LiDAR THÔ -----------------------------------------
#
# Robot đứng yên ở pose chuẩn bị trước cạnh vào của xe, handler tìm 4 chân trong scan, khớp tư thế
# xe, lọc nhiều scan, rồi ghi TF tĩnh `dock_target` = pose robot phải đạt dưới gầm xe. Chặng
# `move_to: dock_target` (marker `trolley`) sau nó đọc frame này.
#
# Số trong khối này theo MÔ HÌNH SIM: xe `tci_trolley` (world factory_ss_demo) + robot `hook_150`
# (SICK S300 sim). Xe thật phải đo lại (plan mục 12) — chỉ sửa YAML, không sửa code.
detect_trolley:
# actionType nào vào handler này. Phải khớp CHÍNH XÁC chuỗi trong order / compound.
action_types: [DetectTrolley]
# Frame TF ghi ra; chặng docking trỏ `move_to` vào đây.
output_frame: dock_target
# Lidar dùng để dò. PHẢI khớp tên trong sensor_store/sensors (sensor_store_params.yaml), và phải
# nhìn đúng hướng với `entry_direction` — lệch thì action fail ngay, không ghi goal ngược.
# Lidar gắn lộn ngược (roll π trong URDF) handler tự đọc từ TF, không cần khai gì thêm.
scan_topic: /b_scan
# Robot chui gầm bằng đầu nào: forward = tiến vào (lidar trước, heading goal trỏ VÀO xe);
# backward = lùi vào (lidar sau, heading goal trỏ RA cạnh vào). Đổi cái này thì đổi `scan_topic`
# và dấu `prior_x`/`prior_yaw` theo.
entry_direction: backward
# [s] Chờ robot đứng hẳn trước khi lấy mẫu. Tăng nếu thân robot còn rung khi vừa dừng.
settle_delay: 0.4
# [s] Hết giờ mà chưa chốt -> kFailed. Phải > settle_delay + sample_window + hold_time.
timeout: 15.0
# Profile dùng khi order không mang khoá `trolley_profile`.
default_profile: tci_trolley
profile_param_key: trolley_profile
# [m] Tia ngắn/dài hơn thì bỏ. max_range: chân xa nhất (chân sau) phải còn >= 3 tia — S300 sim
# ở 1.8 m chỉ còn ~3 tia trên chân 30 mm. Tăng không làm dò xa hơn, chỉ thêm vật nhiễu.
min_range: 0.10
max_range: 3.0
# [m] Sigma nhiễu range của lidar, làm trọng số khớp tư thế và mẫu số của điểm tin. S300 sim = 0.01.
# Lidar thật: ĐO (đứng yên nhìn thẳng tường phẳng, tính độ lệch chuẩn của một tia qua ~100 scan);
# thường 0.015–0.03.
# ► Chỉnh: đặt thấp hơn nhiễu thật thì điểm tin tụt dù xe đúng, log báo `confidence < min_confidence`.
# Đặt cao quá thì cổng điểm tin mất tác dụng phân biệt — chỉ đặt theo số đo được.
range_sigma: 0.01
# Driver lidar báo tia KHÔNG có phản hồi bằng range 0 (thay vì inf). Tính chất của driver, không
# phải tham số chỉnh: xem `rostopic echo -n 1 /f_scan/ranges`, thấy nhiều số 0.0 xen giữa các vật
# thì là true. Lidar KIT /f_scan: true (~500/1600 tia là 0). Gazebo trả inf: để false.
# ► Sai thành false với lidar trả 0: mọi chân bị coi là "bị che một phần" (dung sai ghép cặp nới
# thêm một bề rộng chân, dễ ghép nhầm), và tia 0 ở chỗ chân thiếu luôn bị coi là "bị che".
# Sai thành true với lidar trả 0 cho vật SÁT cảm biến (< min_range): vật đó không còn được
# tính là che chân.
zero_range_is_no_echo: false
debug:
# Log `[debug]`: lý do chưa dò ra (1 Hz), kết quả khớp (1 Hz), tóm tắt lúc start. Lỗi thật
# (topic sai, hướng lidar sai, hết giờ) luôn in, không tắt được.
detect: true
# Bộ lọc nhiều scan (cùng khoá với detect_lidar). Spread chặt hơn detect_lidar vì khe hở hai bên
# khi chui gầm chỉ 4.85 cm (D6: ngang ±1.5 cm, yaw ±1°).
filter_enabled: true
# [s] S300 12.5 Hz → ~37 scan trong 3 s.
sample_window: 3.0
min_samples: 5
max_spread_xy: 0.02 # [m]
max_spread_yaw: 0.03 # [rad]
hold_time: 0.0 # [s]
jump_threshold: 0.0 # [m] 0 = tắt lọc cụm.
cluster_recency: 0.3 # [s]
min_cluster_fraction: 0.51
min_cluster_samples: 3
profiles:
tci_trolley:
# [m] Tâm–tâm hai chân của CẠNH VÀO (ngang hướng chui). Robot chui qua cạnh NGẮN (D10).
# Đo bằng thước giữa tâm chân. Sai số này đẩy cả bộ dò lệch — đo kỹ.
cart_opening: 0.517
# [m] Tâm–tâm hai chân DỌC hướng chui.
cart_depth: 0.720
# [m] Mức lệch kích thước tối đa giữa xe thật và số cart_opening/cart_depth ở trên: sai số gia
# công giữa các xe CÙNG LOẠI, xe méo. Dùng ở hai nơi: (1) ghép cặp chân và kiểm khoảng cách
# chân; (2) điểm tin — mỗi chân được lệch tới tolerance/2 khỏi góc mô hình mà không bị trừ
# điểm (nếu không, xe lệch 3 cm đã rớt vì lidar đo chính xác tới vài mm).
# ► Chỉnh: đo 3–5 xe thật, lấy số trung bình làm cart_opening/cart_depth, độ lệch lớn nhất so
# với trung bình cộng ~0.5 cm làm dung sai. Tăng: chịu xe lệch nhiều hơn, nhưng dễ ghép chân
# của hai xe đỗ sát nhau — phải < 0.06 với dãy xe bước 0.97 m (khe chân 0.453 m). Không bù
# được số đo SAI: phải là tâm–tâm chân (không phải mép ngoài) ở độ cao lidar.
cart_dim_tolerance: 0.04
# Tiết diện chân ở ĐÚNG độ cao lidar (0.184 m): box hoặc round.
leg_shape: box
# [m] box: cạnh dọc cart_opening; round: đường kính.
leg_width: 0.030
# [m] Dung sai bề rộng cụm chân.
leg_width_tolerance: 0.02
# Số chân phải THẤY. 3 = chịu 1 chân bị che. 2 chỉ được khi có prior (D7), dễ nhầm hơn.
min_legs: 3
# Nhận chân DÍNH vật khác cùng tầm (tường, kệ, xe bên cạnh cách sau chân < 15 cm) làm chân
# YẾU: được tính vào min_legs và vào phép khớp, nhưng không tự lập giả thuyết — mỗi xe vẫn
# phải có 2 chân đứng tự do đúng khoảng cách.
# ► Bật (true) khi xe đỗ sát tường/kệ: chân sát vật phía sau không bao giờ "tự do", nên che
# thêm 1 chân là chỉ còn 2 chân → `too few legs`. Tắt (false): an toàn hơn trước vật lồi trên
# tường, nhưng xe đỗ sát vật thì gần như không chịu được chân bị che.
# Bật làm tăng nhẹ "xe ma" (chân thật + vật dính tường đúng góc thứ ba); cổng mơ hồ và bộ
# lọc min_samples chặn phần lớn. Log khớp in `attached N` để biết chân nào là chân yếu.
accept_attached_legs: true
# [điểm] Cổng lòng xe trống: > ngần này điểm scan trong lòng xe thì không chui. -1 = tắt.
# Bật sau khi xác nhận xe rỗng ở độ cao lidar không có gì (hàng thòng xuống, thanh đáy).
max_interior_points: -1
# [-] Điểm tin tối thiểu (0..1): nửa từ số chân thấy, nửa từ mức khớp.
min_confidence: 0.5
# Dải phản quang: TẮT — dò không dải trước (D9). Muốn phát hiện xe đỗ ngược (D5): dán dải ở
# 2 chân đầu cần vào, đặt tape_enabled: true + tape_legs: entry, đo tape_min_intensity.
# (tape_legs: entry khi tape_enabled: false bị từ chối lúc boot — khai thừa.)
tape_enabled: false
# Khi bật tape_bloom_max_angle, ngưỡng này cũng là ranh giới lõi sáng (core).
# Phần dưới ngưỡng có thể là vệt bloom; lidar KIT cần khoảng 8000.
# Lõi gương khoảng 13k–27k, vùng chuyển bloom 2k–10k; hạ ngưỡng làm lõi quá rộng.
tape_min_intensity: 1000.0 # [đơn vị cảm biến] Gazebo trả thẳng laser_retro; lidar thật: đo
# Chân nào mang dải (chỉ có nghĩa khi tape_enabled: true):
# all = cả 4 chân có dải; cụm không đủ tia sáng thì KHÔNG thành chân (chống nhầm vật khác).
# entry = chỉ 2 chân cạnh vào có dải; cạnh có dải LUÔN là cạnh vào (biết đầu/đuôi xe, D5).
# Robot đứng phía chân trần thì goal bị lật, robot phải vào từ phía có dải.
# ⚠ entry khi tape_enabled: false → handler từ chối lúc boot (khai thừa). Mặc định all.
tape_legs: all
# [tia] Số tia sáng (>= tape_min_intensity) tối thiểu để một chân được coi là có dải. Mặc định 1.
# ► Tăng (2–3) để một điểm sáng lẻ (mép vật bóng, nhiễu) không biến chân trần thành "có dải";
# giảm khi robot đứng xa và chân dán chỉ còn vài tia. Lidar KIT 29/10: chân dán ở 0.7 m có
# 12–20 tia >= 2500, chân trần 0 tia.
tape_min_points: 1
# [rad] Góc tối đa nhận vệt bloom; tăng nếu loang rộng, nhưng quá lớn có thể nuốt vật cạnh chân.
# Băng gương KIT: tape_enabled: true, tape_min_intensity: 8000, tape_bloom_max_angle: 0.10,
# tape_range_bias_sigma: 0.05. Khi tape_enabled: false, khoá bị bỏ qua và cảnh báo lúc boot liệt kê khoá; có thể giữ giá trị đã chỉnh khi tháo dải.
# 0 tắt bộ lọc.
tape_bloom_max_angle: 0.0
# [-] Tỷ lệ plateau liên tiếp gần nhất trong run sáng bị trải cự ly; 0 tắt, cần bật tape và bloom.
# Tăng giúp loại lõi bloom dốc, nhưng dễ mất chân thật; giảm cứu thêm chân nhưng có thể nhận lõi méo.
# Ngưỡng quá thấp nguy hiểm vì pose sai; phải nhỏ hơn 1. KIT dán băng gương dùng 0.65 để giữ
# chân có dốc ở mép và loại lõi bị bloom; chỉ dùng sau khi kiểm chứng trên scan của lidar.
tape_plateau_min_fraction: 0.0
# [m] σ tiên nghiệm cho bias cự ly chung; tăng cho phép bù bias lớn hơn nhưng có thể kéo pose sai.
# Băng gương KIT: tape_enabled: true, tape_min_intensity: 8000, tape_bloom_max_angle: 0.10,
# tape_range_bias_sigma: 0.05. Khi tape_enabled: false, khoá bị bỏ qua và cảnh báo lúc boot liệt kê khoá; có thể giữ giá trị đã chỉnh khi tháo dải.
# 0 tắt ước lượng bias.
tape_range_bias_sigma: 0.0
# [m] σ hậu nghiệm tối đa để nhận bias khi tất cả góc thấy đều có dải; 0 tắt.
# Tăng nhận xa hơn nhưng dễ bù sai pose; giảm từ chối nhiều hơn, giữ bias kéo goal gần lidar.
# Giá trị lớn nguy hiểm vì bias và tịnh tiến khó phân biệt ở xa; hợp lệ 0–0.1, cần tape và sigma > 0.
# KIT băng gương cả 4 chân: 0.02. Replay 3 bag 30/10: detect bình thường có σ 0.0076 (0.6 m, 4 chân)
# tới ~0.015 (1.6 m, 3 chân); ca hình học yếu 0.021–0.05 bị loại và giữ kết quả cũ.
# Cập nhật: phép tính σ theo từng chân dùng 0.02 m thử nghiệm trong test/replay; cần xác nhận trước khi dùng KIT.
tape_range_bias_all_max_std: 0.0
# Prior (D3): vùng tìm xe so với robot, trong frame thân robot (`robot_base_frame` của move_base2, `base_link` trên robot này). TẮT: robot dò ở điểm do server
# đặt, không cố định so với xe — prior chặt loại luôn xe thật (log 28/10: robot đứng cách tâm
# xe 2.30 m, xoay 17.7° → "too few legs"). Tắt prior thì lấy xe điểm tin cao nhất trong
# `max_range`; robot phải thấy >= `min_legs` chân, tức tâm xe cách lidar <= ~2.5 m. Hai xe
# điểm sát nhau (dãy xe đỗ sát) → từ chối "ambiguous", KHÔNG đoán.
# ► Bật lại khi xe đỗ thành dãy sát nhau: điểm dò trên server phải đặt đủ chuẩn để xe đích nằm
# trong `search_radius` quanh prior, xe bên cạnh nằm ngoài. Khi bật: cạnh vào cách lidar
# 0.8–1.0 m → tâm xe cách base_link 1.61–1.81 m. Lùi vào: prior_x âm.
has_prior: false
prior_x: 1.70 # [m]
prior_y: 0.0 # [m]
# [rad] Hướng pháp tuyến cạnh vào (trỏ về robot) trong base_link: tiến vào = 3.14159, lùi = 0.
prior_yaw: 3.14159
# [rad] Dung sai yaw quanh prior_yaw. 0.35 ≈ 20°.
prior_yaw_tolerance: 0.35
# [m] Tâm xe xa prior quá ngần này thì loại. Giảm khi xe đỗ thành dãy sát nhau.
search_radius: 0.40
# [m, m, rad] Dịch đích so với tâm xe. 0 = robot dừng đúng tâm xe (dock_anchor: center).
offset_x: 0.0
offset_y: 0.0
offset_yaw: 0.0
# Mẫu instance LÙI VÀO — chưa bật. Bật: thêm `{name: detect_trolley_back, type:
# TrolleyDetectionActionHandler}` vào `handlers:` rồi bỏ comment khối dưới (giữ nguyên profile như
# trên, chỉ đổi prior_x: -1.70, prior_yaw: 0.0).
# detect_trolley_back:
# action_types: [DetectTrolleyBackward]
# output_frame: dock_target
# scan_topic: /b_scan
# entry_direction: backward
# --- waiter: đứng chờ một khoảng thời gian ------------------------------------------------------
waiter:
action_types: [wait]
@@ -568,3 +883,11 @@ NoopActionHandler:
# Bộ dò biên dạng từ LiDAR thô. Gói riêng (`dock_pattern_action`), không thuộc action_core.
DockPatternActionHandler:
library_path: libdock_pattern_action_handler
# Bộ dò xe hàng 4 chân từ LiDAR thô. Gói riêng (`trolley_detection_action`).
TrolleyDetectionActionHandler:
library_path: libtrolley_detection_action_handler
# SIM-ONLY: thư viện plugin; không phải tham số hiệu chỉnh robot thật.
WallReflectorDetectionActionHandler:
library_path: libwall_reflector_detection_action_handler

View File

@@ -41,6 +41,15 @@
vda5050_src:
compound_actions:
# SIM-ONLY: dò xong mới lùi tới target; thất bại phải giữ clear_queue_on_failure=true.
GoToWallStation:
steps:
- {action: DetectWallReflectors}
# Marker `wall_station` (maker_sources.yaml): DockPlanner mating_edge, mặt tường sau đuôi
# robot đúng dock_face_offset. Thiếu marker thì DockPlanner đòi footprint_dock và
# không khởi tạo được (sim 12/11: 'footprint_dock must contain at least three points').
- {move_to: wall_reflector_target, profile: docking, marker: wall_station}
# --- charge: vào trạm sạc ---------------------------------------------------------------------
charge:
steps:
@@ -71,8 +80,8 @@ vda5050_src:
dockTo:
steps:
- {action: DetectCharger}
- {move_to: dock_target, profile: docking, marker: charger}
- {action: DetectTrolley}
- {move_to: dock_target, profile: docking, marker: trolley}
# - {move: -1.0, profile: go_straight}
# - {action: LiftFork}
# Lùi ra khỏi khe kệ. Quãng đường tương đối được quy ra pose tuyệt đối tại `submit`, từ pose

View File

@@ -3,6 +3,8 @@ robot_costmap_2d:
robot_base_frame: base_link
rolling_window: false
track_unknown_space: false
# [bool] Mặc định tắt đồ thị tham chiếu: không có luồng nền. Từng costmap ghi đè trong file của nó.
reference_graph_enabled: false
plugins:
- name: static_layer

View File

@@ -0,0 +1,20 @@
# Cấu hình DirectionalLayer cho global costmap trong mô phỏng move_base2.
directional_layer:
# Bật ràng buộc hướng; SBPL từ chối lập đường cho tới khi host gửi grid hướng
# sau static map mới nhất. Tắt để bỏ kiểm hướng; map không có zone gửi data rỗng.
enabled: true
# Topic static map; đổi cho khớp tên host gửi để nhận biết mỗi lần đổi map.
map_topic: "map"
# Topic grid hướng; đổi đồng thời với topic host gửi, khác map_topic.
direction_topic: "direction_map"
# [deg] Góc lệch tối đa giữa hướng di chuyển và hướng zone, tính cả biên.
# Áp chung cho mọi zone. 90 = được đi mọi hướng có thành phần cùng chiều zone
# (đi ngang zone được, đi ngược bị cấm).
# Giảm: robot phải đi sát hướng zone hơn, cấm cắt ngang làn, phải căn hướng
# trước khi vào zone; quay tại chỗ luôn được phép. Dưới 22.5 (bước heading của
# mprim 16 hướng) SBPL có thể không tìm được đường.
# Tăng quá 90: cho phép cả hướng hơi ngược chiều zone, zone một chiều yếu đi.
# Phạm vi hợp lệ: 0 < giá trị < 180; ngoài phạm vi nav core từ chối khởi động.
max_deviation_deg: 45.0
# Bật log chuyển trạng thái PENDING/READY; tắt để giảm log bình thường.
debug_state: true

View File

@@ -12,14 +12,37 @@ navigation_map:
map_pkg: managerments
map_file: maze
virtual_walls_map:
map_topic: /map
namespace: /virtual_walls
# Vùng cấm (plugin StaticLayer tên forbidden). Grid: 100 trong polygon = lethal, -1 ngoài polygon =
# không ghi gì. map_topic phải trùng topic bridge đẩy vào (/forbidden; có hay không dấu / đều khớp).
# use_maximum: true = lấy max với master, nên ô cấm luôn lethal dù layer khác khai báo sau.
# Đặt false thì layer khai báo sau (preferred/unpreferred) ghi đè và làm ô cấm đi được.
# Giữ track_unknown_space mặc định (true): đặt false thì ô -1 thành free và xoá tường của static map.
forbidden:
map_topic: forbidden
map_pkg: managerments
map_file: maze
use_maximum: true
lethal_cost_threshold: 100
# Vùng ưu tiên (PreferredLayer): ô 100 trong polygon thành cost 20, thấp hơn ô free (60), nên
# planner thích đi qua. Ô 0 ngoài polygon = không ghi gì.
# use_maximum: true = chỉ ghi lên ô có cost < 253, tường và unknown giữ nguyên. Đặt false thì
# polygon phủ lên tường sẽ xoá tường (cost 20 thay lethal) — nguy hiểm.
# track_unknown_space không có tác dụng với PreferredLayer (layer tự đọc 0 = không ghi).
preferred:
map_topic: preferred
use_maximum: true
lethal_cost_threshold: 100
track_unknown_space: false
# Vùng hạn chế (UnPreferredLayer): ô 100 trong polygon thành cost 100, cao hơn ô free (60), nên
# planner tránh nếu có đường khác. Chồng với preferred thì layer khai báo sau trong plugins thắng.
# use_maximum và track_unknown_space: như khối preferred ở trên.
unpreferred:
map_topic: unpreferred
use_maximum: true
lethal_cost_threshold: 100
track_unknown_space: false
obstacles:
observation_sources: f_scan b_scan #pc_marking pc_clearing pc_r_marking pc_r_clearing
f_scan:
@@ -28,6 +51,10 @@ obstacles:
clearing: true
marking: true
inf_is_valid: true
zero_is_valid: false
# [bool, không đơn vị] true: tia trả 0 là không có tín hiệu dội về, dùng đường trống để xoá vết cũ
# tới tối đa raytrace_range; điểm cuối không đánh dấu nếu range_max - 0.0001 m >= obstacle_range.
# Chỉ bật sau khi kiểm tra lidar KHÔNG trả 0 cho vật gần hơn range_min, nếu không sẽ xoá vật thật sát mũi xe.
frustum_clearing_enabled: false
min_obstacle_height: 0.0
max_obstacle_height: 0.25
@@ -38,6 +65,10 @@ obstacles:
clearing: true
marking: true
inf_is_valid: true
zero_is_valid: false
# [bool, không đơn vị] true: tia trả 0 là không có tín hiệu dội về, dùng đường trống để xoá vết cũ
# tới tối đa raytrace_range; điểm cuối không đánh dấu nếu range_max - 0.0001 m >= obstacle_range.
# Chỉ bật sau khi kiểm tra lidar KHÔNG trả 0 cho vật gần hơn range_min, nếu không sẽ xoá vật thật sát mũi xe.
frustum_clearing_enabled: false
min_obstacle_height: 0.0
max_obstacle_height: 0.25

View File

@@ -4,6 +4,23 @@ global_costmap:
global_frame: map
update_frequency: 1.0
publish_frequency: 1.0
# [bool] Tính sẵn đồ thị tham chiếu (Voronoi và làn một chiều) khi đổi map, cho LaneRoutePlanner.
# Chạy trên luồng nền, ưu tiên thấp, không chặn update costmap. Tắt thì không có luồng và LaneRoutePlanner luôn báo fail.
# Không được bật cùng rolling_window: true (từ chối khởi tạo costmap). Bật tốn thêm vài chục MB RAM khi map lớn.
reference_graph_enabled: true
# [m] Ô ridge gần vật cản hơn mức này thì bỏ. Tăng: mất các lối hẹp khỏi đồ thị.
# Giảm: thêm cạnh sát tường, planner vẫn tự kiểm footprint nên không nguy hiểm.
# 0.335 là số đã đánh giá offline với footprint vuông 0.30 m, robot KIT dùng 0.36.
# Sim đang chạy hook_150 (nửa rộng 0.1955 m) nên có thể bỏ sót lối hẹp mà robot này đi lọt.
reference_graph_min_clearance_m: 0.335
# [m] Hai vật cản gần hơn mức này coi là một. Tăng: ít nhánh hơn, dễ mất lối hẹp.
reference_graph_ridge_min_separation_m: 0.7
# [m] Nhánh cụt ngắn hơn mức này thì bỏ. Giảm: nhiều nhánh nhỏ, tra đường chậm hơn.
reference_graph_spur_min_length_m: 1.0
# [m] Khoảng cách các làn song song trong một zone. Giảm: nhiều làn dự phòng hơn, đồ thị lớn hơn.
reference_graph_lane_offset_step_m: 0.5
# [bool] Log một dòng [debug] mỗi lần tính xong (số nút, cạnh, làn, thời gian). Log lỗi không tắt được.
reference_graph_debug_log: true
# [bool] Bật log thống kê thời gian update costmap (avg/p95/p99 mỗi cycle + per-layer).
# Chỉ dùng khi đo đạc/tối ưu; log in mỗi performance_metrics_period giây, tắt đi khi chạy thật.
# Lưu ý: key này phải nằm TRONG namespace local_costmap/global_costmap — đặt ở root file common là key chết.

View File

@@ -2,9 +2,17 @@ global_costmap:
frame_id: map
plugins:
- {name: navigation_map, type: "StaticLayer" }
# - {name: virtual_walls_map, type: "StaticLayer" }
# - {name: obstacles, type: "VoxelLayer" }
# Kiểm chiều di chuyển trong global planner sau khi nhận grid hướng từ host.
# - {name: direction_zones, type: DirectionalLayer}
# Vùng cấm / vùng ưu tiên / vùng hạn chế, grid do direction_zone_publisher phát và bridge
# SensorConverter đẩy vào (topic /forbidden, /preferred, /unpreferred). Param ở khối
# forbidden:/preferred:/unpreferred: trong costmap_common_params.yaml.
# Bật layer nào thì publisher phải chạy: layer chưa nhận grid thì global costmap không
# bao giờ "current" và planner chờ mãi. Không dùng zone thì comment lại cả ba dòng.
- {name: forbidden, type: "StaticLayer" }
# - {name: preferred, type: "PreferredLayer" }
# - {name: unpreferred, type: "UnPreferredLayer" }
- {name: inflation, type: "InflationLayer" }
obstacles:
enabled: false
footprint_clearing_enabled: true
footprint_clearing_enabled: truegửi tôi

View File

@@ -7,6 +7,8 @@ local_costmap:
# sensor); nâng cao hơn nữa chỉ tốn CPU, không thêm thông tin.
update_frequency: 10.0
publish_frequency: 6.0
# [bool] Local costmap không tính đồ thị tham chiếu. Giữ false: local là rolling_window, bật sẽ bị từ chối khởi tạo.
reference_graph_enabled: false
# [bool] Bật log thống kê thời gian update costmap (avg/p95/p99 mỗi cycle + per-layer).
# Chỉ dùng khi đo đạc/tối ưu; log in mỗi performance_metrics_period giây, tắt đi khi chạy thật.
# Lưu ý: key này phải nằm TRONG namespace local_costmap/global_costmap — đặt ở root file common là key chết.

View File

@@ -3,6 +3,7 @@ local_costmap:
plugins:
# - {name: virtual_walls_map, type: "StaticLayer" }
- {name: obstacles, type: "VoxelLayer" }
- {name: forbidden, type: "StaticLayer" }
- {name: inflation, type: "InflationLayer" }
obstacles:
enabled: true

View File

@@ -1,18 +1,21 @@
# DockPlanner — global planner sinh đường vào dock.
#
# Ba kiểu đường. Planner thử theo thứ tự và lấy kiểu ĐẦU TIÊN dựng được; kiểu nào
# Bốn kiểu đường. Planner thử theo ladder cấu hình và lấy kiểu ĐẦU TIÊN dựng được; kiểu nào
# không dựng được thì rơi xuống kiểu kế tiếp, KHÔNG bao giờ biến thành lỗi:
# 1. direct_entry — một cung hội tụ vào trục goal rồi đi thẳng vào. Một chiều
# chạy, không dừng, không xoay. Rẻ nhất khi chạy.
# 2. single_cusp — cua rời XA dock tới điểm đổi chiều (cusp) rồi lùi thẳng vào.
# Lấn thêm chỗ về phía xa dock đúng bằng quãng phải đi ra.
# 3. straight_pivot_straight — một đoạn thẳng, một cú XOAY TẠI CHỖ ghi tường
# 2. straight_pivot_straight — một đoạn thẳng, một cú XOAY TẠI CHỖ ghi tường
# minh vào path (một khối pose cùng vị trí, yaw tăng dần), rồi một đoạn
# thẳng vào goal. Điểm xoay nằm GIỮA robot và dock nên KHÔNG lấn thêm một
# mét nào, đổi lại có thêm một lần dừng để xoay.
# 3. single_cusp — cua rời XA dock tới điểm đổi chiều (cusp) rồi lùi thẳng vào.
# Lấn thêm chỗ về phía xa dock đúng bằng quãng phải đi ra.
# 4. backoff_pivot_straight — chỉ cho differential, lùi/tiến thẳng theo hướng
# thân xe hiện tại tới khi đủ chỗ xoay, rồi dùng hình học pivot ở trên.
# Chỉ thử sau khi mọi kiểu cũ đều thất bại; mặc định bị tắt.
# Thứ tự ưu tiên giữa 2 và 3 do `kinematics/model` và `maneuver/*` quyết định —
# xem comment của từng khoá.
# Đoạn cuối của cả ba kiểu luôn THẲNG và trùng hướng yaw của goal: robot phải đạt
# Đoạn cuối của cả bốn kiểu luôn THẲNG và trùng hướng yaw của goal: robot phải đạt
# đúng hướng trước khi chui vào dock — đi cong vào gầm trolley rất dễ va.
#
# Mép nào của robot áp vào dock được SUY RA theo từng lần lập plan, dựa vào phía
@@ -24,9 +27,8 @@
# Suy được như vậy vì goal đã được offset sẵn từ tầng trên, sao cho base_link
# dừng đúng tại goal khi manơ hoàn tất.
#
# Kiểm tra va chạm / vùng trống CỐ Ý chưa cấu hình ở đây: DockPlanner hiện chỉ
# sinh hình học. Đừng thêm cost_threshold, allow_unknown hay check_free_space
# cho tới khi phần kiểm va chạm được hiện thực.
# Kiểm tra costmap chỉ áp dụng cho các kiểu pivot khi bật `pivot_check_costmap`;
# các kiểu direct_entry và single_cusp vẫn chỉ kiểm tra hình học.
DockPlanner:
# Thư viện Boost.DLL chứa symbol export tên "DockPlanner".
library_path: libdock_planner
@@ -73,11 +75,11 @@ DockPlanner:
# [m] Bán kính cua nhỏ nhất, khai trực tiếp vì robot vi sai không có góc lái.
# 0 — CHO PHÉP xoay tại chỗ. Đây là giá trị bình thường của robot vi sai,
# và nó bật kiểu đường 3 (thẳng + xoay + thẳng) làm kiểu CHÍNH: kiểu
# và nó bật kiểu đường 2 (thẳng + xoay + thẳng) làm kiểu CHÍNH: kiểu
# này không lấn thêm một mét nào về phía xa dock.
# > 0 — CẤM xoay tại chỗ (ví dụ đang chở tải cao, xoay tại chỗ dễ đổ).
# Planner quay về dùng cung y như ackermann, bán kính tối thiểu đúng
# bằng số này, và kiểu 3 chỉ còn bật qua pivot_fallback_extension.
# bằng số này, và kiểu 2 chỉ còn bật qua pivot_fallback_extension.
minimum_turning_radius: 0.0
maneuver:
@@ -86,13 +88,19 @@ DockPlanner:
# trùng ngay vị trí robot.
minimum_forward_distance: 0.25
# [m] Cusp phải nằm xa hơn khoảng này so với điểm xuất phát thì kiểu 2 bị
# [m] Cusp phải nằm xa hơn khoảng này so với điểm xuất phát thì kiểu 3 bị
# LOẠI (không phải fail): planner chuyển sang kiểu khác, chỉ khi không kiểu
# nào dựng được mới trả lỗi.
# Tăng lên nếu robot đứng lệch nhiều mà vẫn muốn giữ đường có cusp; giảm
# xuống để đẩy sớm sang kiểu 3.
# xuống để đẩy sớm sang kiểu 2.
maximum_forward_extension: 0.9
# [m] Trần đoạn thẳng từ cusp tới goal của single_cusp (khoảng xuất phát dọc trục + phần tiến thêm).
# 0 = không giới hạn; vượt trần thì bỏ hình cusp và thử hình xoay, hết hình khả dụng thì báo fail.
# Giảm giúp tránh lùi thẳng quá dài nhưng dễ fail khi robot xuất phát xa goal.
# Marker có thể ghi đè bằng dock_maximum_cusp_distance trong maker_sources.yaml.
maximum_cusp_distance: 0.0
# [m] Bật kiểu 1 (direct_entry — một cung hội tụ vào trục goal rồi đi thẳng
# vào, giữ nguyên một chiều chạy) khi khoảng chỗ còn lại cho cung — khoảng
# cách dọc trục từ robot tới goal trừ độ dài đoạn thẳng cuối — vượt số này.
@@ -101,21 +109,21 @@ DockPlanner:
# 0 = tắt hẳn kiểu 1.
direct_entry_min_curve_room: 0.3
# [m] Chuyển từ kiểu 2 (cusp) sang kiểu 3 (thẳng + xoay + thẳng) khi cusp bắt
# [m] Chuyển từ kiểu 3 (cusp) sang kiểu 2 (thẳng + xoay + thẳng) khi cusp bắt
# robot chạy RA XA dock thêm quá số này, đo từ chỗ robot ĐANG ĐỨNG.
# So sánh cố ý là TƯƠNG ĐỐI. Lấy một con số tuyệt đối kiểu "chiều sâu lối đi"
# rồi so với vị trí robot là tính cả chỗ robot đang đứng vào phần "cần thêm",
# và mọi manơ xuất phát từ khoảng cách bình thường đều bị loại sạch.
# 0 — TẮT hẳn kiểu 3 (hành vi cũ, luôn lập đường có cusp).
# 0 — TẮT hẳn chuyển sang kiểu 2 (hành vi cũ, ưu tiên đường cusp).
# nhỏ hơn — chuyển sang xoay tại chỗ sớm hơn: tiết kiệm lối đi, thêm 1 lần dừng.
# lớn hơn — ưu tiên cusp: chạy mượt hơn, chiếm nhiều lối đi hơn.
# ⚠ Chỉ khai > 0 khi CHẮC robot xoay tại chỗ được quanh base_link.
# KHÔNG có tác dụng khi model=differential VÀ minimum_turning_radius=0 — lúc
# đó kiểu 3 đã là kiểu chính rồi, không cần ngưỡng nào bật nó.
# đó kiểu 2 đã là kiểu chính rồi, không cần ngưỡng nào bật nó.
pivot_fallback_extension: 1.2
# [m] Khoảng hở giữa vòng tròn thân robot quét khi xoay tại chỗ và mặt gần
# của dock. Áp dụng cho CẢ HAI model, mỗi khi kiểu 3 được dùng.
# của dock. Áp dụng cho CẢ HAI model, mỗi khi kiểu 2 được dùng.
# Xoay tại chỗ quay MỌI điểm footprint quanh base_link, nên kích thước phải
# tính là BÁN KÍNH NGOẠI TIẾP, luôn lớn hơn phần nhô mép dùng cho đoạn thẳng
# cuối. Ví dụ footprint 1.65/0.35 x ±0.40: ngoại tiếp 1.698 m trong khi mép
@@ -123,9 +131,20 @@ DockPlanner:
# Điểm xoay đặt tại: max(độ dài đoạn thẳng cuối, ngoại tiếp + nửa thân dock
# phía tiếp cận + số này).
# Tăng lên: điểm xoay lùi ra xa dock hơn, an toàn hơn. Tăng quá thì điểm xoay
# vượt qua chỗ robot đứng, kiểu 3 bị loại và planner quay về cusp.
# vượt qua chỗ robot đứng, kiểu 2 bị loại và planner quay về cusp.
pivot_safety_margin: 0.15
# [m] Quãng back-off tối đa cho kiểu backoff_pivot_straight cuối cùng, chỉ dùng khi model=differential.
# Tăng lên cho phép cứu robot đang đứng gần điểm xoay; giảm xuống hoặc 0 sẽ làm ít trường hợp được cứu hơn.
# ⚠ Đặt quá lớn có thể lấn vào lối đi phía sau robot.
pivot_backoff_max_distance: 1.0
# Bật kiểm tra LETHAL trên các đoạn tiếp cận (back-off, tới đỉnh pivot) và vòng quét tại điểm xoay.
# Không kiểm tra terminal vào dock: cell LETHAL gần charger/chân trolley có thể là tiếp xúc dự kiến.
# NO_INFORMATION được xem là trống; LETHAL và ngoài bản đồ chặn các phần được kiểm tra.
# false bỏ qua vật cản costmap, có thể sinh đường đâm vào chướng ngại vật.
pivot_check_costmap: true
terminal:
# [m] Khoảng hở CỘNG THÊM cho đoạn thẳng cuối, ngoài phần thân robot nhô ra ở
# mép áp dock (rear_extent khi đoạn cuối đi lùi, front_extent khi đi tiến) và,
@@ -139,6 +158,8 @@ DockPlanner:
# Tăng lên thì robot có quãng thẳng dài hơn để chỉnh hết sai số hướng trước
# khi vào dock, ĐỔI LẠI ăn vào chỗ dành cho cung, nên đặt lớn quá sẽ đẩy plan
# sang kiểu có cusp hoặc kiểu xoay tại chỗ.
# Với mating_edge + dock_face_offset, terminal floor không còn là rear_extent nên straight_length (ví dụ 0.2 m) quyết định độ dài terminal.
# Marker có thể ghi đè bằng dock_straight_length trong maker_sources.yaml.
straight_length: 0.4
sampling:

View File

@@ -14,6 +14,11 @@
# src/config/move_base2_config.cpp). NodeHandle merge MỌI .yaml trong thư mục này, nên khoá top-level
# `env_monitor:` phải xuất hiện ở đúng MỘT file.
#
# Từ 26/11/2026: phần chung (enabled, grace_after_new_plan, pose_jump_reject, replan_budget, detectors) và tham số
# từng detector do gói env_monitor_core đọc (EnvMonitor::initialize, mỗi detector một plugin .so). move_base2 chỉ còn
# đọc phần lấy mẫu: enabled, profiles, check_period, body, geometry, contact/use_local_plan|local_plan_start_tol|lookahead,
# logger. Mỗi detector tự chọn route recovery (`route`, `route_mode`, `on_exhausted` trong khối của nó).
#
# Triết lý (chốt 5/9): local planner được TỰ DO NÉ; recovery chỉ chạy khi BẾ TẮC THẬT. Không có phép đo
# "plan phía trước bị chắn" ở đây — đó là thứ làm bản cũ nổ oan và phải tắt. Ba verdict:
# stall lệnh đi mà cost_to_go (đường vòng tới điểm thoát + phần plan còn lại) không giảm -> no_progress
@@ -25,7 +30,7 @@
# =================================================================================================
env_monitor:
# Công tắc chung. false = không lấy mẫu, không in, không ghi — hành vi y như không có EnvMonitor.
enabled: true
enabled: true
# Profile được giám sát. docking / go_straight / rotate KHÔNG: đường cong vào dock là một thể thống nhất.
profiles: [position]
@@ -37,6 +42,28 @@ env_monitor:
# [s] Sau khi nhận plan mới (planner hay detour) không kết luận gì: mẫu cũ thuộc plan cũ.
grace_after_new_plan: 1.0
# [m] Pose dời quá (đây + tốc độ lớn nhất trong khoảng mất pose x thời gian từ pose hợp lệ trước) = pose bị ĐẶT LẠI
# (AMCL "Setting pose", /initialpose, TF đứng rồi chạy lại). Cú dời không cộng vào quãng đường (replan_budget,
# standdown). Cửa sổ stall đo lại tối đa một lần mỗi khoảng dài nhất của idle_window_s, confine_window_s và
# disp_window_s; cú nhảy lặp vẫn được báo nhưng giữ cửa sổ để robot kẹt thật còn được phát hiện.
# Sim 6/11 20:34: AMCL kéo pose lùi 1.2 m lúc robot chạy thẳng 0.3 m/s -> quỹ đạo 20 s gấp lên chính nó -> cổng giam
# vùng nổ oan -> detour_path vô ích. 0 = TẮT (cú dời tính như quãng đi, như bản cũ).
# ► Chỉnh: phải lớn hơn bước sửa pose bình thường của localization (AMCL vài cm). HẠ (0.3) nếu localization hay giật
# 0.3–0.5 m mà vẫn thấy stall oan; ĐỪNG hạ dưới 0.2 — bước sửa thường sẽ bị coi là nhảy và làm giảm quãng đường đo.
pose_jump_reject: 0.5
# --- Danh sách detector (gói env_monitor_core, 26/11/2026) ---------------------------------------
# Mỗi dòng một detector: plugin Boost.DLL nạp theo `type` (thư viện khai ở cuối file, `<Type>/library_path`), tham số
# đọc ở khối cùng `name` bên dưới. Thứ tự = thứ tự chạy mỗi cycle VÀ thứ tự ưu tiên khi nhiều cờ cùng nổ (trong
# nhóm lock, rồi nhóm abort); detector sau ghi đè sự kiện log của detector trước trong cùng cycle.
# ► Chỉnh: bỏ một dòng = tắt hẳn detector đó (không nạp). Thiếu cả khoá này = nạp đúng ba dòng dưới, đúng thứ tự này.
# Type sai / thiếu thư viện / lệch ABI = log LỖI lúc boot, detector đó không chạy, các detector khác vẫn chạy.
detectors:
- {name: intrusion, type: IntrusionDetector} # thêm 27/11; không nằm trong bộ mặc định khi thiếu khoá detectors
- {name: contact, type: ContactDetector}
- {name: stall, type: StallDetector}
- {name: unreachable, type: UnreachableDetector}
# --- Thân robot và ngữ nghĩa vật cản --------------------------------------------------------------
body:
# [m] mũi / đuôi / nửa bề rộng từ base_link. CẢ BA = 0 = lấy footprint KHÔNG đệm của costmap mỗi lượt
@@ -78,6 +105,17 @@ env_monitor:
# --- stall: "planner đòi đi mà không tới gần lối ra" -> cờ no_progress -> route oscillation ----------
# oscillation là trigger GỐC: cạn route = ABORT chặng, nổ oan là MẤT CHẶNG -> bật "recover" SAU CÙNG.
stall:
# --- Route recovery của detector này (gói env_monitor_core, 26/11/2026) ---
# Tên route trong recovery_behaviors_params.yaml (recovery/routes). Route không tồn tại = detector bị GỠ lúc boot
# (log LỖI): không cờ, không phanh, không bao tốc độ.
route: oscillation
# step = mỗi lần nổ chạy 1 behavior rồi về CONTROLLING, lần nổ sau mới chạy behavior kế (như trước 26/11);
# sequence = một lần nổ chạy liền cả route (behavior hỏng / nộp path giữa chừng vẫn chạy tiếp, path mới nhất áp
# khi xong), cả chuỗi tính một lượt. Giữa các behavior của chuỗi EnvMonitor KHÔNG canh: behavior tự lo va chạm.
route_mode: step
# Cạn route thì làm gì: abort = huỷ chặng; lock = khoá detector, bám tiếp plan. Mặc định ở đây: huỷ chặng, báo lỗi lên fleet (trigger GỐC: thử hết route vẫn kẹt thì robot không tự gỡ được).
# lock còn được xét TRƯỚC controller (dự báo); abort chỉ xét khi controller ra lệnh hợp lệ.
on_exhausted: abort
enabled: true
action: recover # "recover" = giơ cờ no_progress (bật 5/9 23:45); "log" = chỉ ghi/in (shadow).
window_s: 4.0 # [s] cửa sổ đo eff_geo = (cost_to_go giảm) / (lệnh tích luỹ)
@@ -102,7 +140,7 @@ env_monitor:
disp_window_s: 12.0 # [s] cửa sổ đo dịch chuyển. GIẢM (8) nếu muốn nổ sớm hơn, TĂNG (20) nếu còn nổ khi né chậm trong đám đông.
disp_min: 0.6 # [m] dịch chuyển thực dưới đây = không đi được đâu. 0 = TẮT cổng, dùng lại ngân sách replan như cũ.
disp_min_commanded: 1.5 # [m] lệnh tích luỹ trong cửa sổ phải >= đây mới xét (đứng chờ không phải kẹt).
idle_window_s: 25.0 # [s] cổng ĐỨNG YÊN: dịch chuyển thực < disp_min suốt chừng này giây thì là kẹt, KHÔNG cần lệnh đủ và không
idle_window_s: 20.0 # [s] (27/11: 25 -> 8, như "long time motionless" của Athena: PRIEST giữ máy câm 19.5 s) cổng ĐỨNG YÊN: dịch chuyển thực < disp_min suốt chừng này giây thì là kẹt, KHÔNG cần lệnh đủ và không
# cần geodesic đo được. Run 10:59: PRIEST bò 0.03–0.15 m/s tại chỗ 30 s (blocked_ahead cost 253, res 1.6
# chưa tới ngưỡng bất khả thi) -> lệnh 12 s chỉ 0.1–0.4 m -> cổng trên câm, kUnreachable mới gỡ ở 75 s.
# Thử trên 7 lượt: bắt đúng 2 ca quần tại chỗ (~40 s và ~125 s thay vì 75 s / 206 s), 0 lần ở 3 lượt
@@ -116,11 +154,29 @@ env_monitor:
confine_window_s: 20.0 # [s] GIẢM (15) để nổ sớm hơn; TĂNG (30) nếu thấy nổ khi robot né vòng rộng hợp lý.
confine_radius: 1.2 # [m] vùng lớn hơn đây không gọi là giam. TĂNG (1.5) nếu local minimum của bãi rộng hơn.
confine_cmd_factor: 1.5 # [-] lệnh phải gấp chừng này lần đường kính vùng. GIẢM (1.2) nếu thấy quần chậm mà không nổ.
# Sim chạy chậm hơn thời gian thực (RTF < 1) thì lệnh tích luỹ bị phóng to 1/RTF so với quãng đi
# thật: RTF 0.66 (sim 6/11) là hệ số 1.5 mất tác dụng — chỉ còn confine_radius chặn ca đi thẳng.
progress_veto: true # true = cổng giam vùng KHÔNG nổ khi tiến độ đã chứng minh: mọi eff đo được trong
# confine_window_s gần nhất đều >= eff_off (và eff gần nhất mới hơn window_s). Plan có vòng quay đầu
# (planner chỉ đi tiến) giữ robot trong vòng nhỏ mà cost_to_go vẫn giảm đều -> không phải kẹt.
# Cost nhảy sẽ huỷ bằng chứng trong confine_window_s; cổng đứng yên không bị phủ quyết.
# false = giam vùng xét hình học vị trí bất kể cost_to_go.
retry_backoff: 3.0 # [s] sau một lượt recovery HỎNG không tích bằng chứng (thay cho behavior wait).
# --- unreachable: không còn đường trong cửa sổ tới điểm thoát -> cờ path_blocked -> route path_blocked --
# Cạn route chỉ KHOÁ trigger (contract 05e), an toàn để bật trước stall. Bag 5/9: 0/3278 khung — hiếm.
unreachable:
# --- Route recovery của detector này (gói env_monitor_core, 26/11/2026) ---
# Tên route trong recovery_behaviors_params.yaml (recovery/routes). Route không tồn tại = detector bị GỠ lúc boot
# (log LỖI): không cờ, không phanh, không bao tốc độ.
route: path_blocked
# step = mỗi lần nổ chạy 1 behavior rồi về CONTROLLING, lần nổ sau mới chạy behavior kế (như trước 26/11);
# sequence = một lần nổ chạy liền cả route (behavior hỏng / nộp path giữa chừng vẫn chạy tiếp, path mới nhất áp
# khi xong), cả chuỗi tính một lượt. Giữa các behavior của chuỗi EnvMonitor KHÔNG canh: behavior tự lo va chạm.
route_mode: step
# Cạn route thì làm gì: abort = huỷ chặng; lock = khoá detector, bám tiếp plan. Mặc định ở đây: khoá detector, bám tiếp plan cũ; đi đủ oscillation_distance thì mở khoá (dự báo, plan vẫn hợp lệ).
# lock còn được xét TRƯỚC controller (dự báo); abort chỉ xét khi controller ra lệnh hợp lệ.
on_exhausted: lock
enabled: true
action: recover # 6/9 10:35: BẬT LẠI cùng geometry/target_snap. Run 10:15 (ở log) nó báo trước 2/2 lần PRIEST kẹt sát vật
# (sớm 6,1 s và 8,9 s, edt 0.87/0.78) và 1 lần thừa — lần thừa là plan ôm tường, snap xử. Lịch sử: 00:05 nổ 4
@@ -130,11 +186,56 @@ env_monitor:
clean_start_margin: 0.20 # [m] thân còn cách vật ít nhất chừng này mới gọi replan (SBPL cần chỗ bắt đầu).
retry_backoff: 2.0 # [s]
# --- intrusion: vật LẠ vừa đi vào sát thân (điểm lidar mới trong zone_distance từ mép thân thật) -> cờ ------------
# Phản xạ né kiểu Athena. Đọc scan thô của `topics` (không qua costmap: costmap đệm mất vùng 10 cm sát thân), giữ
# khoảng 1 s lịch sử mỗi topic. Điểm chỉ tính là MỚI khi scan cùng lidar cũ hơn `compare_age` từng nhìn XUYÊN qua chỗ
# đó (phép thử tia) — nên tường khe hẹp, khung cửa lộ ra khi vào khe, người đứng im hay robot tự chạy tới vật đều KHÔNG
# nổ; những ca đó vẫn là việc của costmap + local planner. Không phanh, không bao tốc độ: chỉ giơ cờ cho route.
intrusion:
# --- Route recovery của detector này ---
route: intrusion # route trong recovery_behaviors_params.yaml (recovery/routes/intrusion).
route_mode: step # mỗi lần nổ chạy một behavior của route (evade), lần nổ sau chạy behavior kế.
on_exhausted: lock # cạn route = khoá detector, bám tiếp plan; không huỷ chặng.
enabled: true
action: recover # log = chỉ ghi "phát hiện", KHÔNG giơ cờ (đang thử sim). recover = giơ cờ, chạy route intrusion.
# ► Chỉ chuyển recover khi sim qua khe hẹp có 0 lần nổ nhầm.
topics: [/f_scan, /b_scan] # LaserScan phải có trong sensor_store; thiếu topic nào thì detector chỉ mù phía đó.
zone_distance: 0.10 # [m] tính từ mép footprint KHÔNG đệm. TĂNG = né sớm hơn nhưng dễ nổ khi đi sát người/kệ đang động;
# GIẢM = vật phải vào sát hơn mới né. Trần 0.5.
compare_age: 0.3 # [s] scan tham chiếu phải cũ hơn scan mới ít nhất chừng này. GIẢM = vật đi chậm cũng bắt được
# nhưng nhiễu lidar dễ thành "điểm mới"; TĂNG = chỉ bắt vật đủ nhanh. Phải < history_max_age.
free_margin: 0.05 # [m] tia tham chiếu phải đi XA hơn điểm mới ít nhất chừng này mới coi chỗ đó từng trống.
# TĂNG nếu nhiễu range làm nổ nhầm cạnh mặt phẳng; GIẢM làm nhạy với vật mỏng.
min_points: 3 # [điểm] số điểm mới tối thiểu trong MỘT scan (tính riêng từng topic). TĂNG = bỏ qua vật nhỏ/nhiễu.
confirm_scans: 2 # [scan] số scan mới LIÊN TIẾP cùng đạt min_points mới giơ cờ. 1 = nổ ngay scan đầu (dễ nhầm).
history_max_age: 1.0 # [s] lịch sử scan mỗi topic giữ bao lâu. Phải > compare_age.
max_scan_age: 0.7 # [s] scan cũ hơn mức này so với đồng hồ control loop thì bỏ (lidar chết/lệch đồng hồ = mù, không nổ).
max_check_speed: 0.15 # [m/s] chỉ xét khi lidar tự đi chậm hơn mức này giữa 2 scan so sánh. Robot chạy/quay thì
# phép thử tia ở mép vật tĩnh dễ rơi sang tia bên cạnh -> nổ nhầm (replay bag 27/11: tắt cổng
# thêm 1 lần nổ nhầm + 9 lần không rõ; bật cổng 0 lần nhầm, vẫn bắt 2/2 vật động; cổng chặn 66%
# cặp scan). TĂNG = bắt cả lúc đang chạy nhưng dễ nổ nhầm; GIẢM = chỉ bắt khi gần đứng yên.
max_check_yaw_rate: 0.3 # [rad/s] như trên cho tốc độ quay.
max_tf_gap: 0.1 # [s] TF lidar đúng stamp scan chưa có thì nhận TF mới nhất nếu cách stamp không quá mức này;
# quá thì bỏ scan đó (không đoán). TĂNG nếu log báo "scan or TF unavailable" dù lidar vẫn chạy.
debug:
events: true # log một dòng mỗi lần nổ: số điểm, khoảng cách nhỏ nhất tới mép thân, phía (trước/sau/trái/phải).
# --- contact: thân sắp chạm trên quỹ đạo thật -> phanh; kề mũi đứng yên -> cờ collision -----------
contact:
# --- Route recovery của detector này (gói env_monitor_core, 26/11/2026) ---
# Tên route trong recovery_behaviors_params.yaml (recovery/routes). Route không tồn tại = detector bị GỠ lúc boot
# (log LỖI): không cờ, không phanh, không bao tốc độ.
route: collision
# step = mỗi lần nổ chạy 1 behavior rồi về CONTROLLING, lần nổ sau mới chạy behavior kế (như trước 26/11);
# sequence = một lần nổ chạy liền cả route (behavior hỏng / nộp path giữa chừng vẫn chạy tiếp, path mới nhất áp
# khi xong), cả chuỗi tính một lượt. Giữa các behavior của chuỗi EnvMonitor KHÔNG canh: behavior tự lo va chạm.
route_mode: step
# Cạn route thì làm gì: abort = huỷ chặng; lock = khoá detector, bám tiếp plan. Mặc định ở đây: khoá detector, bám tiếp plan cũ; phanh vẫn giữ, controller_patience leo thang nếu kẹt thật.
# lock còn được xét TRƯỚC controller (dự báo); abort chỉ xét khi controller ra lệnh hợp lệ.
on_exhausted: lock
enabled: true
action: recover # cờ collision (route collision). P4 bước 1: bật thật.
apply_command: true # true = phanh + bao tốc độ thật (P4). false = SHADOW: chỉ ghi "sẽ phanh/kẹp bao nhiêu", KHÔNG đụng lệnh.
apply_command: false # true = phanh + bao tốc độ thật (P4). false = SHADOW: chỉ ghi "sẽ phanh/kẹp bao nhiêu", KHÔNG đụng lệnh.
# Chủ thể phanh duy nhất trong move_base2 (guard cũ đã xoá); cổng dừng trong PRIEST vẫn phải để tắt.
# Phanh mà cờ collision đã giơ nhưng route khoá -> controller bị báo "không có lệnh" -> controller_patience
# -> controlling_failed (cùng luật guard cũ), robot không đứng chết im lặng.
@@ -183,3 +284,20 @@ env_monitor:
# đọc profile phanh/bao tốc độ; tắt khi lên robot nếu không cần replay).
log_dir: /tmp/env_monitor
flush_period: 1.0 # [s]
# =================================================================================================
# Thư viện của từng detector (gói env_monitor_core) — bảng nạp Boost.DLL, cùng cách action_core / recovery_core.
# Khối `env_monitor` không có `detectors` thì lõi nạp contact, stall, unreachable theo đúng thứ tự đó.
# Thiếu khoá của một type thì detector đó KHÔNG chạy (log LỖI lúc boot). Đây không phải số tinh chỉnh.
# =================================================================================================
ContactDetector:
library_path: libenv_monitor_core_contact_detector
StallDetector:
library_path: libenv_monitor_core_stall_detector
UnreachableDetector:
library_path: libenv_monitor_core_unreachable_detector
IntrusionDetector:
library_path: libenv_monitor_core_intrusion_detector

View File

@@ -0,0 +1,190 @@
# Cấu hình LaneRoutePlanner; chỉ có hiệu lực nếu planner được chọn riêng.
LaneRoutePlanner:
# [bật/tắt] true cho phép đi qua ô unknown; false coi unknown là vật cản. Chỉ có tác dụng khi global costmap bật track_unknown_space: true; hiện false nên unknown của map thành ô trống.
allow_unknown: false
library_path: liblane_route_planner
# [m] Bán kính cua nhỏ nhất mà mọi tầng được dùng; kiểm tra cuối loại đường cua gắt hơn. Không phải bán kính ưu tiên:
# planner luôn thử bán kính lớn trước, chỉ xuống tới mức này khi bán kính lớn không đủ chỗ.
# 0.4 = v_des 0.4 m/s chia omega_max 1.0 rad/s của MPCC: nhỏ hơn thì xe phải giảm tốc khi cua, gần như quay tại chỗ.
# Tăng: đường ít cua gắt nhưng chỗ chật phải đi vòng xa hoặc không có đường. Không nhỏ hơn 0.4 nếu chưa đo MPCC.
min_turn_radius_m: 0.4
# [m] Các bán kính góc cua thử theo thứ tự, lớn trước; góc nào không vừa mới thử bán kính kế tiếp nhỏ hơn.
# Không đặt phần tử nhỏ hơn min_turn_radius_m. Bỏ các phần tử < 1.06 thì quay về hành vi cũ (chỉ cua rộng).
corner_radii_m: [1.9, 1.75, 1.6, 1.45, 1.3, 1.18, 1.08, 0.9, 0.75, 0.6, 0.5, 0.4]
# [m] Bậc thang bán kính. Lượt 1 của graph, lattice và bước làm mượt chỉ dùng bán kính >= giá trị này (giống hành vi cũ).
# Khi min_turn_radius_m nhỏ hơn, graph chạy thêm lượt 2 với mọi corner_radii_m nếu lượt 1 thất bại hoặc ra đường vòng
# dài hơn suspicious_ratio x khoảng cách thẳng + suspicious_margin_m; đường lượt 2 chỉ được nhận khi ngắn hơn ít nhất 20%.
# Giảm: cua gắt xuất hiện cả khi đủ chỗ cua rộng. Đặt bằng min_turn_radius_m: tắt bậc thang.
regular_turn_radius_m: 1.06
# [độ] Góc gãy lớn nhất cho phép giữa path: hai đoạn thẳng nối nhau tại một đỉnh, không quay tại chỗ. Là bậc cuối của
# thang bán kính: chỉ dùng ở lượt 2 của graph, chỉ ở góc mà không bán kính nào vừa, và chỉ khi thân xe xoay tại đỉnh
# không chạm vật cản. Tăng: thêm đường ở chỗ chật nhưng robot phải xoay gắt ở đỉnh; trên ~69 độ (align_enter_angle
# 1.2 rad của MPCC) MPCC có thể dừng xoay tại chỗ. 0: tắt góc gãy. Trong [0, 90].
# Góc gãy = góc đổi hướng tại đỉnh (hướng đoạn ra so với hướng đoạn vào kéo dài), không phải góc trong giữa hai đoạn:
# 90 = góc vuông. Chọn 90 (27/11/2026): không bắt buộc bo cung; góc nào không bo được cung thì gãy, tại đỉnh chỉ có
# một pose (không xuất quạt pose quay). Robot thật (rb_ws) vẫn để 45 tới khi chạy thử.
max_kink_deg: 90.0
# [m] Biên bắt buộc cộng vào inscribed radius; tăng an toàn hơn nhưng giảm khả năng có đường.
# Giảm dưới khoảng hở thực tế có thể làm thân xe chạm vật cản.
clearance_min_margin_m: 0.035
# [m] Biên ưu tiên cộng vào inscribed radius; tăng chọn đường thoáng hơn, giảm dễ qua chỗ hẹp.
clearance_preferred_margin_m: 0.30
# [m] Biên cộng vào bán kính ngoại tiếp hình chữ nhật để quyết định kiểm footprint đầy đủ.
# Tăng tốn thời gian hơn; giảm quá thấp có thể bỏ qua kiểm tra sát vật cản.
collision_check_margin_m: 0.056
# [m] Khoảng hở bắt buộc từ footprint đến ô lethal; tăng an toàn hơn nhưng giảm số đường hợp lệ.
# Giảm sát 0 có nguy cơ va chạm khi có sai số cảm biến hoặc định vị.
footprint_min_gap_m: 0.03
# [m] Cho thân xe chạm zone sai hướng khi tâm đi vào/ra cùng zone trong khoảng chiều dài đường này; tăng giúp chuyển tiếp
# dễ hơn nhưng có thể đi sát zone sai hướng lâu hơn. Giảm tăng độ chặt; 0 tắt ngoại lệ chuyển tiếp, không được âm.
zone_transition_m: 1.0
# [m chi phí/m tại lệch 45 độ] Phạt đường đi lệch hướng zone; tăng để xe ưu tiên đi dọc zone hơn,
# giảm để chấp nhận đường chéo ngắn hơn; 0 giữ hành vi cũ.
zone_deviation_weight: 2.0
# [bool] Có xuất chuỗi pose quay tại chỗ ở đầu và cuối path hay không. false: path bắt đầu từ pose chạy
# đầu tiên và kết thúc bằng một pose goal; local planner tự quay tại chỗ lúc đầu và tự quay về yaw goal.
# Planner vẫn kiểm hai lần quay này không va chạm, dù true hay false. true: hiện lại các "quạt" pose quay như cũ.
output_endpoint_spins: false
# [m] Mức tăng clearance khi thử lại đường thiếu khoảng hở; thêm mức tăng thời gian khi thất bại.
# Danh sách rỗng chỉ kiểm tra, không thử tăng clearance.
footprint_gap_shortcut_raise_m: [0.05, 0.10]
# [độ] Bậc lệch nghiêm ngặt thử trước giới hạn của direction field; thêm bậc có thể tăng thời gian.
# Không dùng danh sách này để vượt giới hạn direction field.
deviation_ladder_deg: [0.0]
# [tỷ lệ] Khoá cũ giữ để tương thích; planner không còn dùng tỷ lệ này để loại đường đã kiểm chứng.
route_too_long_ratio: 1.5
# [m] Khoá cũ giữ để tương thích; không còn dùng để loại đường đã kiểm chứng.
route_too_long_margin_m: 2.0
# [tỷ lệ] Ngưỡng kích hoạt kiểm tra đường vòng; tăng giảm số lần kiểm tra, không đổi giới hạn cuối.
suspicious_ratio: 1.3
# [m] Biên cộng của ngưỡng kích hoạt kiểm tra; tăng giảm số lần kiểm tra.
suspicious_margin_m: 2.0
# [lần] Số lần thử tuyến mỗi lượt; tăng có thể tìm thêm đường nhưng lâu hơn, tối thiểu 1.
max_route_attempts: 24
# [s] Giới hạn thời gian chung; tăng có thể tìm thêm đường nhưng làm backup chờ lâu hơn.
time_limit_s: 20.0
# [m] Khoảng cách các pose đầu ra; tăng giảm số điểm nhưng có thể mất chi tiết đường cong.
# Giảm quá nhỏ làm tăng bộ nhớ và thời gian xử lý.
output_step_m: 0.04
# [m] Biên cửa sổ dựng lại ridge quanh start và goal; tăng bao phủ nhiều hơn nhưng tốn thời gian.
live_ridge_pad_m: 6.0
# [ô] Số ô tối đa trong cửa sổ ridge; tăng tốn bộ nhớ và thời gian, 0 bỏ qua dựng lại.
live_ridge_max_cells: 1500000
# [bật/tắt] Thử lattice khi graph có đường vòng đáng ngờ; bật tìm đường ngắn hơn, tắt giảm thời gian lập kế hoạch.
detour_upgrade_enabled: true
# [s] Ngân sách tối đa cho lần thử, không vượt deadline chung; tăng có thể tìm được nhiều đường hơn nhưng tăng độ trễ, giảm thì ngược lại.
detour_upgrade_time_limit_s: 2.0
# [tỷ lệ 0..1) Mức tiết kiệm chi phí chiều dài và lệch hướng tối thiểu để nhận lattice; tăng đòi hỏi cải thiện lớn hơn, giảm chấp nhận cải thiện nhỏ hơn.
detour_upgrade_min_saving: 0.15
# [m] Chiều dài lệch hướng trong zone được phép tăng so với graph; tăng cho phép đi chéo nhiều hơn, giảm giữ đường thẳng hơn.
detour_upgrade_max_extra_zone_deviation_m: 0.5
# [bool] Bật tìm SE(2) sau khi graph không tìm được đường; tăng thời gian tìm, vẫn giữ các ràng buộc cứng.
# false bỏ tầng này; profile sim/dev bật để thử, không suy ra đã kiểm chứng trên robot.
lattice_enabled: true
# [bool] true cho lattice dùng thêm cung gắt ở min_turn_radius_m. Đo 9/11 với sàn 0.4: lattice duyệt quá nhiều trạng
# thái, mất 38–84 ca regress7 vì hết giờ. Để false: góc gắt chỉ đến từ lượt 2 của graph.
lattice_tight_arcs: false
# [m] Phí cộng thêm cho mỗi 5 độ quay trên cung gắt của lattice; chỉ có tác dụng khi lattice_tight_arcs: true.
lattice_tight_turn_cost_m: 0.15
# [m] Khe ưu tiên từ footprint đến ô lethal/unknown; sau khi tìm được đường khe tối thiểu, lattice thử nâng lên khe này.
# Trong lattice_end_relax_radius_m quanh start/goal vẫn dùng khe của chính pose đó để xe đỗ sát kệ vẫn ra được.
# Tăng: đường có thể xa kệ/tường hơn nhưng thử nâng cấp lâu hơn. 0 hoặc <= footprint_min_gap_m: tắt nâng cấp.
lattice_preferred_gap_m: 0.15
# [tỷ lệ] Tối đa phần thời gian của một bậc fallback dành tìm đường ưu tiên thay thế sau khi kiểm tra đường đã tìm; trong (0, 1].
# Bước kiểm tra và lượt tìm đều không vượt hạn thời gian còn lại của bậc.
# Tăng có thể tìm được đường rộng hơn nhưng làm chậm trả đường; đặt gần 1 có thể dùng hết thời gian còn lại.
# Hết giờ nâng cấp vẫn trả đường khe tối thiểu đã kiểm tra, không làm giảm coverage.
lattice_preferred_time_fraction: 0.25
# [bool] true làm mượt path lattice trong ngân sách fallback; false giữ path thô, có thể gấp khúc hơn.
# Bật có thể tăng thời gian xử lý; path sau làm mượt vẫn phải qua kiểm tra bắt buộc.
lattice_smooth_enabled: true
# [lần kiểm tra] Ngân sách làm mượt tối đa; tăng có thể làm mượt nhiều hơn nhưng chậm hơn; 0 giữ path thô.
# Giá trị quá lớn có thể dùng hết thời gian fallback; phải không âm và vừa số nguyên 32 bit.
lattice_smooth_max_checks: 450000
# [bins/vòng] Số hướng rời rạc; tăng chi tiết nhưng tốn thời gian/bộ nhớ; phải chẵn trong [8, 1024].
lattice_heading_bins: 72
# [m] Kích thước ô tìm kiếm x/y tối đa; giảm tăng chi tiết và chi phí, phải > 0.
lattice_closed_resolution_m: 0.10
# [hệ số] Trọng số heuristic A*; tăng thường tìm nhanh hơn nhưng có thể chọn đường kém tối ưu; phải >= 1.
lattice_heuristic_weight: 3.0
# [m] Bề rộng nhóm ưu tiên FIFO; tăng giảm chi phí hàng đợi nhưng giảm độ chính xác thứ tự; 0 dùng heap chính xác.
lattice_bucket_width_m: 0.25
# [m] Trọng số khoảng hở trong trường heuristic; tăng ưu tiên xa vật cản, giảm có thể tìm sát hơn; không âm.
lattice_field_clearance_weight_m: 0.25
# [m] Trọng số khoảng hở trong chi phí tìm đường; tăng ưu tiên xa vật cản, giảm có thể tìm sát hơn; không âm.
lattice_wall_weight_m: 0.25
# [m] Phạt đổi dấu lái khác 0; tăng giảm ngoặt qua lại nhưng có thể tạo đường vòng; không âm.
lattice_switch_cost_m: 0.35
# [m/bước] Phạt bước cong; tăng ưu tiên đi thẳng nhưng có thể tạo đường vòng; không âm.
lattice_steer_cost_m: 0.012
# [bước] Bội số primitive thứ nhất; phải là 1 để giữ bước cơ bản.
lattice_primitive_multiple_1: 1
# [bước] Bội số primitive thứ hai; tăng đi xa hơn mỗi lần mở rộng nhưng giảm độ linh hoạt; >= 1.
lattice_primitive_multiple_2: 3
# [bước] Bội số primitive thứ ba; tăng mở rộng nhanh hơn nhưng giảm độ linh hoạt; >= bội thứ hai và <= 64.
lattice_primitive_multiple_3: 6
# [m] Bán kính nối analytic; tăng cần nhiều chỗ hơn, giảm bị chặn dưới bởi min_turn_radius_m; phải > 0.
lattice_analytic_radius_m: 1.08
# [trạng thái] Khoảng cách giữa các lần thử nối analytic; giảm thử nhiều hơn nhưng tốn thời gian; tối thiểu 1.
lattice_analytic_interval: 20000
# [m] Gần goal trong khoảng này sẽ thử nối analytic; tăng thử nhiều hơn, giảm tiết kiệm thời gian; không âm.
lattice_analytic_near_goal_m: 2.0
# [hướng] Số hướng đến goal cho tập nối analytic; tăng thử nhiều hơn nhưng chậm hơn; 0 tắt tập này, tối đa 360.
lattice_analytic_goal_headings: 16
# [m] Khoảng hở cộng thêm để một ô được coi là đi qua được trong trường heuristic của lattice (chỉ heuristic, không đổi
# luật kiểm tra đường). Tăng: heuristic không còn kéo lattice vào khe chỉ vừa bằng thân xe (ví dụ khe giữa hai cột), tìm
# nhanh hơn ở map nhiều cột. Nếu biên chặn mất lối duy nhất tới điểm đầu, lattice tự dựng lại heuristic không biên.
# Đo 9/11: 0.1 sửa 3/4 ca hết giờ trong sim; 0.15 làm kit mất 21 ca regress7 ở map maze. 0: luật cũ.
lattice_field_extra_clearance_m: 0.1
# [m] Nới kiểm tra footprint trong field heuristic lattice bằng cách giảm mỗi nửa kích thước đã cộng gap;
# không đổi kiểm tra an toàn khi tìm hoặc xác minh đường. Tăng có thể mở lại lối sát ô, giảm giữ field chặt hơn.
# Giá trị quá lớn dễ dẫn tìm kiếm vào khe xe không lọt và gây hết giờ; phải không âm, 0 tắt nới.
# Đo 10/11 (cùng lattice_field_extra_clearance_m 0.1): 0.035 giữ nguyên hook_150 và 3 ca khe cột trong sim,
# kit thêm 1 ca regress7. Với extra_clearance 0 thì mọi mức nới (0.035-0.093) làm 3 ca khe cột sim hết giờ: đừng
# hạ extra_clearance về 0 khi đang nới.
lattice_field_standability_relax_m: 0.035
# [độ] Biên góc zone chỉ cho field heuristic: field chỉ bước CHÉO qua ô có zone khi hướng bước lệch hướng zone không
# quá (max_deviation_deg - biên); bước ngang/dọc giữ đủ max_deviation_deg. Lưới chỉ có bước 45°, nên với
# max_deviation_deg đúng 45 field đi chéo sát mép luật, xe phải quay vào/ra không bám được, lattice tìm tới hết giờ
# (sim M4, M7: 1 s ở 0-30°, hết giờ ở 45° cả khi cho 10 s). Tìm và kiểm tra đường vẫn dùng đủ max_deviation_deg.
# 0: không biên. Trong [0, 45).
# Đo 10/11: 15 giải 3 ca sim M4, M7, 4a ở 45° (~1 s), regress7 không mất ca nào so với 0.
lattice_field_zone_margin_deg: 15.0
# Field heuristic thứ hai. Một field 2D không hợp cả hai loại lối hẹp: field chặt (có extra_clearance, không nới) chặn
# lối xe chỉ lọt khi lệch tâm ô; field nới lại kéo tìm kiếm vào khe giữa cột mà không hướng nào lọt. Bật: nếu tìm trên
# field thứ nhất chưa xong khi hết lattice_alt_field_switch_fraction thời gian fallback, tìm lại một lần trên field
# không extra_clearance và nới lattice_alt_field_relax_m. Luật kiểm tra đường không đổi. Tắt: chỉ dùng field thứ nhất.
# Đo 10/11 với fallback_time_limit_s 10: hook_150 1719/1757, kit 1718/1757, không mất ca nào so với tắt. Với
# fallback 3 s field thứ nhất chỉ còn ~1 s nên kit mất 6 ca: giảm fallback_time_limit_s thì tắt khoá này.
lattice_alt_field_enabled: true
# [m] Mức nới của field thứ hai. 0.035 ≈ nửa đường chéo ô 0.05 m (xe đứng lệch tâm ô). Lớn hơn mở thêm lối nhưng dễ
# kéo vào khe xe không lọt; không âm.
lattice_alt_field_relax_m: 0.035
# [tỷ lệ] Phần thời gian fallback dành cho field thứ nhất (gồm dựng field và tìm) trước khi chuyển; trong (0, 1).
# Tăng: ca cần lâu trên field thứ nhất ít bị cắt, nhưng field thứ hai còn ít thời gian. Giảm: ngược lại.
lattice_alt_field_switch_fraction: 0.35
# [tỷ lệ] Phần thời gian mỗi bậc fallback dành dựng field; tăng có thể cải thiện field nhưng bớt thời gian tìm; trong [0, 1].
lattice_field_time_fraction: 0.4
# [lần] Hệ số gộp ô field; tăng giảm số ô nhưng mất chi tiết; 0 tự chọn, 1 giữ độ phân giải gốc.
lattice_field_cell_factor: 0
# [ô] Giới hạn ô để tự chọn độ phân giải field; tăng chi tiết nhưng tốn bộ nhớ/thời gian; từ 1 đến 2147483647.
lattice_field_max_cells: 1000000
# [s] Ngân sách chung cho các bậc fallback và smoothing; tăng có thể tìm thêm đường nhưng chờ lâu hơn.
# Phải > 0 và <= 86400; vẫn bị giới hạn bởi time_limit_s chung.
fallback_time_limit_s: 10.0
# [m] Bán kính nới khoảng hở C-space gần start/goal; tăng mở rộng vùng nới, 0 tắt; kiểm khoảng hở cuối vẫn bắt buộc.
lattice_end_relax_radius_m: 1.0
# [MiB] Giới hạn bộ nhớ lattice được theo dõi; tăng cho phép tìm lớn hơn nhưng chiếm RAM; trong [1, 1048576].
lattice_max_memory_mb: 512
debug:
# [bool] true ghi một dòng debug khi lattice đã chạy; false giảm log, không tắt dòng lỗi.
fallback: true
# [đường dẫn] Thư mục ghi lại đầu vào của mỗi lần plan thất bại (costmap tĩnh, master, zone, start/goal) để
# chạy lại offline bằng lane_route_eval. Rỗng: không ghi. Mỗi lần ghi vài MB; chỉ bật ở sim/dev, không bật trên robot.
dump_dir: /tmp/lane_route_dumps
# [file] Số lần ghi tối đa mỗi phiên planner; chặn đầy đĩa khi một goal hỏng bị plan lại liên tục. 0: không ghi.
dump_max_files: 20
# [bool] true ghi thông tin lập plan; false giảm log, không tắt lỗi.
debug_plan: true
# [bool] true ghi trạng thái planner; false giảm log, không tắt lỗi.
debug_state: true

View File

@@ -17,7 +17,7 @@
# ► Chỉnh: chỉ thêm/bớt TÊN, cách nhau bằng khoảng trắng. Giữ danh sách tối thiểu — mỗi tên thừa là
# một đường vào chưa được kiểm chứng. Sẽ bỏ hẳn khi `dockTo` được chuyển sang dock_sequences khai
# báo trong compound_actions_params.yaml.
maker_sources: trolley charger dock_station pallet
maker_sources: trolley charger dock_station pallet wall_station
# Marker có entry ở đây dùng CẶP PLANNER RIÊNG. Marker rỗng, hoặc chỉ có trong `maker_sources` mà
# không nằm trong bảng này, sẽ dùng cặp `docking` mặc định của move_base_common_params.yaml.
@@ -44,22 +44,62 @@ maker_sources: trolley charger dock_station pallet
# (lấy từ footprint_dock). Mặc định khi không khai — giữ nguyên hành vi cũ.
# face — goal đã nằm ngay tâm MẶT tiếp cận; dock không đóng góp vào khoảng dừng,
# footprint_dock bị bỏ qua hoàn toàn (DockPlanner log info nếu vẫn khai).
# mating_edge — goal là vị trí base_link LÚC ĐÃ DOCK XONG, đã được tầng trên offset sẵn (ví dụ bộ
# dò cộng `offset_x`), và mặt dock nằm sát MÉP robot đi vào tại đó (mép sau khi lùi vào).
# Giống face, nhưng khoảng hở khi XOAY TẠI CHỖ đo từ mặt dock thật (sau goal đúng
# rear/front_extent của robot) thay vì từ goal. footprint_dock bị bỏ qua.
# ► Dùng cho trạm sạc dò bằng lidar (kit_charger, offset_x 0.40): face coi mặt trạm nằm
# ngay tại goal nên bắt robot ra xa thêm ~0.40 m mới cho xoay; mating_edge thì điểm
# xoay chỉ còn max(straight_length, bán kính quét − extent mép + pivot_safety_margin).
# ⚠ Chỉ đúng khi goal THẬT SỰ là vị trí base_link lúc dock. Goal teach ngay trên mặt dock
# thì phải dùng face, nếu không robot xoay sát dock hơn dự tính đúng extent mép robot.
#
# ── dock_face_offset ──────────────────────────────────────────────────────────────────────────────
# [m] Khoảng cách từ goal lùi về mặt dock thật theo trục tiếp cận; chỉ có nghĩa khi dock_anchor=mating_edge.
# Không khai thì dùng rear_extent/front_extent của robot làm face offset.
# Tăng số này làm giảm khoảng hở tối thiểu và đưa điểm xoay gần dock hơn; giảm số này giữ robot xa hơn.
# Công thức pivot: Xv=max(straight_distance,circumscribed_radius-dock_face_offset+margin_eff); terminal floor=max(max(mating_extent-dock_face_offset,0)+padding,path_point_spacing).
# ⚠ Khai lớn hơn khoảng cách thật có thể cho robot xoay quá sát hoặc chạm dock. Phải khớp offset của bộ dò.
# Marker kế tiếp không khai khoá này thì move_base2 ghi YAML null để xoá override của marker trước.
# Chỉ có tác dụng khi `dock_anchor: mating_edge`. Khai với `center` hoặc `face` thì DockPlanner từ chối khởi động.
#
# ── dock_pivot_safety_margin ──────────────────────────────────────────────────────────────────────
# [m] Override pivot_safety_margin riêng cho marker; cộng vào bán kính quét và điểm xoay của DockPlanner.
# Không khai thì dùng maneuver/pivot_safety_margin.
# Tăng số này đẩy điểm xoay xa dock hơn; giảm số này cho phép xoay gần hơn.
# ⚠ Quá nhỏ có thể làm thân robot quét vào dock; quá lớn có thể khiến planner không tìm được điểm xoay. Miền [0, 1].
# Marker kế tiếp không khai khoá này thì move_base2 ghi YAML null để xoá override của marker trước.
# Chỉ có tác dụng khi `dock_anchor: mating_edge`. Khai với `center` hoặc `face` thì DockPlanner từ chối khởi động.
#
# ── dock_straight_length ──────────────────────────────────────────────────────────────────────────
# [m] Ghi đè terminal/straight_length của DockPlanner chỉ cho marker này; không khai thì dùng mặc định.
# Tăng thì đoạn lùi/tiến thẳng cuối dài hơn nhưng cần robot xuất phát xa goal hơn; nếu không planner
# có thể chuyển sang hình có cusp hoặc xoay. Hợp lệ với mọi dock_anchor, trong [0, 2] m.
#
# ── dock_maximum_cusp_distance ─────────────────────────────────────────────────────────────────────
# [m] Ghi đè maneuver/maximum_cusp_distance chỉ cho marker này; không khai thì dùng mặc định.
# 0 = không giới hạn; giảm trần giúp tránh đoạn cusp tới goal quá dài nhưng có thể khiến planner fail.
# Khi vượt trần, planner bỏ single_cusp và thử hình khác; hợp lệ với mọi dock_anchor, giá trị >= 0.
#
# KHÔNG có khoá nào override chiều chạy của đoạn thẳng cuối. Chiều đó được SUY RA từ phía robot
# đứng so với goal, vì goal đã được offset sẵn từ tầng trên cho đúng manơ định làm — ép chiều bằng
# tham số sẽ mâu thuẫn với chính vị trí goal.
# Hai khoá này là các khoá DUY NHẤT trong bảng được rót xuống plugin:
# Các khoá DUY NHẤT trong bảng được rót xuống plugin: `footprint_dock`, `dock_anchor`,
# `dock_face_offset`, `dock_pivot_safety_margin`, `dock_straight_length`, `dock_maximum_cusp_distance`.
# `PlannerRunner::bindDockingMarker()` chép chúng sang namespace của `global_planner` khai ngay bên
# trên, TRƯỚC khi instance được dựng, rồi dựng lại instance khi marker đổi.
# trên, TRƯỚC khi instance được dựng, rồi dựng lại instance khi marker đổi. Bốn khoá override cuối
# mà marker sau không khai thì bị ghi YAML null, plugin quay về mặc định của dock_global_params.yaml.
# `dock_straight_length` và `dock_maximum_cusp_distance` dùng được với MỌI `dock_anchor`;
# hai khoá override còn lại chỉ với mating_edge.
#
# ⚠ Chỉ `DockPlanner` đọc hai khoá này. Marker nào khai `global_planner: TwoPointsPlanner` thì giá
# ⚠ Chỉ `DockPlanner` đọc các khoá này. Marker nào khai `global_planner: TwoPointsPlanner` thì giá
# trị vẫn được chép sang namespace đó nhưng không ai đọc — không lỗi, không log, chỉ là không có
# tác dụng.
#
# ► Chỉnh: đo kích thước THẬT của từng loại kệ/trạm — chúng khác nhau, để trùng số là mất tác dụng
# của việc khai theo marker. Trục x là hướng robot tiến vào. Chọn `dock_anchor` theo cách teach
# goal của từng loại: goal teach ở mặt (pallet, charger) → face; goal teach ở tâm (trolley chui
# gầm) → center.
# goal của từng loại: goal teach ở mặt (pallet) → face; goal teach ở tâm (trolley chui gầm) →
# center; goal do bộ dò offset sẵn thành vị trí base_link lúc dock (charger) → mating_edge.
docking_marker_profiles:
# Mọi profile marker dùng HybridDockingLocalPlanner: CÙNG plugin hybrid nhưng là instance RIÊNG,
# đọc block `HybridDockingLocalPlanner` trong hybrid_local_planner_params.yaml (bản sao ĐẦY ĐỦ của
@@ -70,14 +110,30 @@ docking_marker_profiles:
local_planner: HybridDockingLocalPlanner
# Goal ở trọng tâm xe trolley (robot chui gầm) → cộng extent tâm→mặt từ footprint_dock.
dock_anchor: center
footprint_dock: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]]
# [m] Mép NGOÀI 4 chân của xe `tci_trolley` (world factory_ss_demo), robot chui qua cạnh ngắn:
# x = ±(cart_depth 0.720 + chân 0.030)/2 = ±0.375 (dọc hướng chui)
# y = ±(cart_opening 0.517 + chân 0.030)/2 = ±0.2735 (ngang hướng chui)
# Cùng số với profile `tci_trolley` của bộ dò `detect_trolley` (action_handlers_params.yaml).
# Lấy theo CHÂN, không theo mặt sàn/tay đẩy: chỉ chân nằm ở độ cao thân robot (sàn xe từ
# 0.352 m trở lên, tay đẩy 0.97–1.01 m).
# ► Chỉnh: đổi xe thì đo lại tâm–tâm chân + tiết diện chân, giữ khớp với profile của bộ dò. Số
# lớn hơn thật → đoạn căn thẳng bắt đầu xa hơn (tốn đường, vẫn an toàn); nhỏ hơn thật → robot
# bắt đầu căn thẳng khi đầu đã sát chân xe.
footprint_dock: [[0.375,-0.2735],[0.375,0.2735],[-0.375,0.2735],[-0.375,-0.2735]]
charger:
global_planner: DockPlanner
local_planner: HybridDockingLocalPlanner
# Goal teach ngay tâm mặt trạm sạc. Chỉ có tác dụng nếu đổi sang DockPlanner.
dock_anchor: face
# Goal = vị trí base_link lúc đã dock: kit_charger cộng offset_x 0.40 từ đỉnh V. Mặt trạm nằm
# sát đuôi robot tại goal → mating_edge (xem ghi chú dock_anchor ở trên).
dock_anchor: mating_edge
footprint_dock: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]]
# Chỉ có tác dụng khi `dock_anchor: mating_edge`. Khai với `center` hoặc `face` thì DockPlanner từ chối khởi động.
# [m] Bằng kit_charger/offset_x: khoảng cách từ goal base_link tới mặt sạc thật.
dock_face_offset: 0.40
# Chỉ có tác dụng khi `dock_anchor: mating_edge`. Khai với `center` hoặc `face` thì DockPlanner từ chối khởi động.
# [m] Khe hở thêm cho vòng quét khi xoay tại chỗ; giới hạn khoảng cách xoay gần mặt sạc.
dock_pivot_safety_margin: 0.10
dock_station:
global_planner: TwoPointsPlanner
@@ -91,3 +147,24 @@ docking_marker_profiles:
# Goal teach ở tâm mặt pallet → dock không đóng góp khoảng dừng, footprint_dock bị bỏ qua.
dock_anchor: center
footprint_dock: [[0.5,-0.5],[0.5,0.5],[-0.5,0.5],[-0.5,-0.5]]
# Trạm dừng trước tường có hai dải phản quang (DetectWallReflectors → `wall_reflector_target`).
# Goal = pose base_link lúc đã dừng (bộ dò cộng sẵn offset_x của profile tường), mặt tường nằm
# sau đuôi robot đúng `dock_face_offset` → cùng ngữ nghĩa với `charger`: mating_edge, nên
# DockPlanner bỏ qua footprint_dock (khai cho đủ khoá, không vào công thức).
wall_station:
global_planner: DockPlanner
local_planner: HybridDockingLocalPlanner
dock_anchor: mating_edge
footprint_dock: [[0.05,-1.0],[0.05,1.0],[-0.05,1.0],[-0.05,-1.0]]
# [m] PHẢI bằng `offset_x` của profile tường đang dùng (detect_wall_reflector, sim_wall_pair:
# 0.85): khoảng từ goal base_link tới mặt tường. Lệch thì planner tính sai chỗ còn được xoay.
# ► Chỉnh: đổi offset_x của profile thì đổi số này theo; trong (0, 2.0] m.
dock_face_offset: 0.85
# [m] Khe hở thêm cho vòng quét khi xoay tại chỗ gần tường. Tăng an toàn hơn nhưng có thể cấm
# xoay khi robot đã gần trạm.
dock_pivot_safety_margin: 0.10
# [m] Ghi đè terminal/straight_length chỉ cho marker này; không khai thì dùng mặc định.
# Tăng thì đoạn lùi/tiến thẳng cuối dài hơn, nhưng cần xuất phát xa goal hơn; nếu không planner
# có thể chuyển sang hình có cusp hoặc xoay.
dock_straight_length: 0.3

View File

@@ -21,10 +21,10 @@
# của planner đó nằm ở YAML riêng của nó (symlink từ pnkx_nav_core/config/), và phải có khoá
# `library_path` tương ứng, nếu không runtime báo "không tìm thấy plugin".
position:
global_planner: CustomPlanner # vật chất hoá tuyến NURBS từ edge của VDA5050 Order.
global_planner: LaneRoutePlanner # vật chất hoá tuyến NURBS từ edge của VDA5050 Order.
# MÙ VẬT CẢN theo thiết kế — nó là route materializer, không
# phải search planner. Chỉ có bản makePlan(Order, ...).
local_planner: PriestLocalPlanner
local_planner: PriestMpccLocalPlanner
docking:
# goal_frame đã được ControlLoop quy thành pose tuyệt đối. DockPlanner dùng đúng contract
@@ -125,6 +125,16 @@ sensor_patience: 2.0
# Chỉ bật (0.5–1.0) nếu sau này global planner vừa tránh được vật cản vừa đủ nhanh (~30 ms).
planner_frequency: 0.0
# [s] Thời gian tối đa giữ goal để chờ global costmap sẵn sàng trước khi lập plan. "Sẵn sàng" là
# mọi layer đang bật đều current: StaticLayer đã ghi map mới vào master, DirectionalLayer đã nhận
# grid hướng sau static map mới nhất. Trong lúc chờ, goal được giữ, không tính vào
# `planner_patience`, log ghi tên layer chưa sẵn sàng.
# ► Tăng: chờ được map/grid đến chậm (đổi map lớn, app gửi grid hướng muộn).
# ► Giảm: báo lỗi sớm hơn khi host quên gửi dữ liệu; quá thấp thì mission fail giả lúc đổi map.
# ► 0: tắt kiểm tra, quay về hành vi cũ — planner có thể lập plan trên map dở dang hoặc bị SBPL
# từ chối ngay khi direction còn PENDING.
costmap_ready_timeout: 10.0
# [s] Ở PLANNING quá lâu mà chưa có plan -> recovery. Mất pose ngay trong PLANNING dùng ngân sách
# `controlling_failed` (xem recovery_behaviors_params.yaml).
# ► Chỉnh: đặt > thời gian lập plan xấu nhất của global planner. SBPL `allocated_time: 10.0` ở
@@ -334,6 +344,23 @@ require_current_costmap: true
# debug; trên hiện trường để true.
recovery_behavior_enabled: true
# --- Thử tiếp tục khi recovery đứng yên -----------------------------------------------------------
# [không đơn vị] Bật thử local planner khi recovery đang chạy. true có thể giúp đi tiếp sớm hơn;
# false để recovery chạy tới cùng. Bật trên robot khi chưa kiểm chứng side effect của planner là nguy hiểm.
recovery_resume_enabled: true
# [tên behavior] Danh sách được thử: thêm tên làm nhiều recovery có thể bị huỷ, bớt tên làm ít hơn.
# Chỉ thêm behavior giữ robot đứng yên; không thêm clear, evade hoặc backup: huỷ sai có thể gây nguy hiểm.
recovery_resume_behaviors: [detour_path]
# [cycle] Số lệnh tiến/lùi hợp lệ liên tiếp để huỷ; tăng làm chờ lâu hơn, giảm giúp đi tiếp sớm hơn.
# Giá trị 1 dễ huỷ nhầm do một lệnh tức thời; phải >= 1.
recovery_resume_confirm_cycles: 3
# [m/s] Độ lớn tốc độ tiến/lùi tối thiểu của lệnh thử; tăng làm khó xác nhận hơn, giảm giúp nhạy hơn.
# Quá thấp dễ nhầm lệnh bò là đường đã thông; phải > 0.
recovery_resume_min_speed: 0.05
# [lần/leg] Số lần huỷ recovery tối đa trong một chặng; tăng cho phép thử lại nhiều hơn, giảm hạn chế lặp.
# Quá lớn dễ gây vòng lặp bị chặn rồi huỷ; 0 = không bao giờ huỷ.
recovery_resume_max_per_leg: 3
# Mission layer LUÔN chạy (2026-09-06, bỏ khoá `mission_layer_enabled`): VDA5050 Order đi qua
# `mission_adapters` — order được cắt thành từng chặng tại mỗi node có action, chỉ phần `released`
# được chạy, `orderUpdateId` nối tiếp thay vì chạy lại từ đầu, và có `mission_timeout` làm lưới cuối.

View File

@@ -0,0 +1,165 @@
# MpccLocalPlanner — CÂY CONFIG CHẠY THỬ MÁY DEV (sim/Gazebo) của move_base2.
#
# robot::NodeHandle đọc file này qua PNKX_NAV_CORE_CONFIG_DIR. Bản mặc định đóng gói nằm ở
# Test/mpcc_local_planner/config/mpcc_local_planner_params.yaml; hai file phải cùng tập khoá
# (so bằng script). Giá trị ở đây là giá trị thử trên sim, chưa chạy robot thật.
#
# Plugin làm gì: local planner MPCC (bám đường theo contour/lag, chỉ chạy tiến) có bốn chế độ:
# ALIGN — đứng yên, xoay tại chỗ về hướng path khi path chĩa ra sau robot
# TRACK — tối ưu quỹ đạo, tránh vật cản tĩnh (costmap) và động (tracker)
# WAIT — phanh và đứng chờ khi người/vật động chắn đường
# TERMINAL / ROTATE_GOAL — giảm tốc vào đích rồi xoay về yaw đích
# Tracker đọc /f_scan từ SensorStore và TF có stamp về odom.
MpccLocalPlanner:
library_path: libmpcc_local_planner
# ---------------- Horizon ----------------
# [bước] Tổng số bước dự đoán. Bước 0 dài đúng chu kỳ control đo được, các bước sau dài `dt`.
# Tăng: nhìn xa hơn, thấy vật cản sớm hơn, tốn CPU hơn. Giảm quá: không thấy hết quãng phanh
# (plugin từ chối khởi động nếu horizon*dt < max_speed/max_decel + 0.5 s).
horizon: 15
# [s] Độ dài các bước dự đoán 1..N-1. 15 x 0.2 = ~2.85 s nhìn trước.
dt: 0.2
# [s] Độ dài bước 0 khi chưa đo được chu kỳ control (lần gọi đầu, sau khi dừng lâu).
nominal_control_period: 0.05
# ---------------- Giới hạn chuyển động (chỉ chạy tiến, v >= 0) ----------------
# [m/s] Tốc độ tiến tối đa của mô hình. Trần runtime từ host (setTwistLinear) chỉ hạ thấp hơn.
max_speed: 1.2
# [rad/s] Tốc độ quay tối đa. Trần góc từ host (setTwistAngular) chỉ hạ thấp hơn.
max_yaw_rate: 0.6
# [m/s^2] Gia tốc tăng tốc. Lệnh đầu luôn bị kẹp theo max_accel * chu kỳ control thật.
max_accel: 0.6
# [m/s^2] Gia tốc giảm tốc; cũng quyết định hồ sơ giảm tốc vào đích. Tăng: phanh gấp hơn.
max_decel: 0.6
# [rad/s^2] Gia tốc góc.
max_yaw_accel: 1.5
# [m/s^2] Giới hạn gia tốc ngang. Áp cho cả cua theo path (v <= sqrt(max_lateral_accel / độ cong))
# lẫn mọi lệnh khi lách vật (v * |ω| <= max_lateral_accel): cần ngoặt gắt thì robot tự giảm tốc.
# Giảm: vào cua và lách chậm hơn, êm hơn. Tăng: lách nhanh hơn nhưng lắc ngang mạnh hơn.
max_lateral_accel: 0.5
# ---------------- Va chạm ----------------
# [m] Bán kính hình tròn dự phòng, CHỈ dùng khi costmap không có footprint.
robot_radius: 0.35
# [m] Khoảng hở luôn giữ giữa mọi đĩa phủ footprint và ô vật cản (khoảng cách tính tâm ô tới
# tâm ô như InflationLayer). Gánh luôn sai số rời rạc nửa ô (~0.035 m ở 0.05 m/ô).
# Tăng: an toàn hơn nhưng không qua được khe hẹp. Giảm dưới 0.03: nguy cơ quẹt.
collision_margin: 0.05
# [đĩa] Số đĩa phủ footprint dọc thân. Nhiều đĩa ôm sát hình chữ nhật hơn: thân 1.166 x 0.96 m
# cần hành lang ~1.75 m với 1 đĩa, ~1.15 m với 6 đĩa (margin 0.05).
footprint_discs: 6
# Ô costmap có cost >= ngưỡng là vật cản cứng. 254 = LETHAL. Đặt 253 để coi cả vành
# inscribed (do inflation_radius của local costmap quyết) là vật cản — bảo thủ hơn nhiều.
cost_threshold: 254
# true: ô chưa biết (255) là vật cản. false nguy hiểm: robot có thể lao vào vùng chưa quét.
unknown_is_obstacle: true
# Coi mép cửa sổ local costmap là vật cản (true) hay vùng chưa quan sát (false).
# true (hành vi v1): mọi quỹ đạo vươn quá nửa cửa sổ đều bị loại. Với costmap 8 m, horizon 3 s
# thì chạy trên ~1 m/s robot mất khả năng lách và đứng im báo static_blocked.
# false: ngoài cửa sổ coi là trống; bù lại tốc độ bị kẹp sao cho quãng phanh + footprint luôn
# nằm trong cửa sổ (8 m, max_decel 0.6 → kẹp ~1.9 m/s). Bị kẹp sẽ có cảnh báo trong log.
map_edge_is_obstacle: false
# Phạt mềm khi khoảng hở trên margin nhỏ hơn clearance_soft_distance [m]: robot có xu hướng đi
# giữa hành lang. Đặt clearance_weight * soft_distance^2 lớn hơn speed_weight * max_speed^2 thì
# robot thà đứng yên còn hơn chui vào khe hẹp.
clearance_weight: 1.0
clearance_soft_distance: 0.2
# ---------------- Trọng số cost (nhân với độ dài bước, đơn vị theo giây) ----------------
contour_weight: 3.0 # sai lệch ngang so với path (đã dịch ngang nếu path bị chặn). Tăng: bám sát hơn
lag_weight: 2.0 # sai lệch dọc so với điểm tham chiếu
heading_weight: 0.3 # lệch hướng so với tiếp tuyến path
speed_weight: 2.0 # (v - v_ref)^2 — động lực duy nhất để robot tiếp tục chạy; giảm nhiều thì robot lười
yaw_rate_weight: 0.05 # omega^2. Tăng: ít quay hơn
smooth_weight: 0.05 # gia tốc thẳng và góc. Tăng: lệnh êm hơn, phản ứng chậm hơn
terminal_lag_weight: 3.0 # sai lệch dọc ở cuối horizon
# ---------------- Path tham chiếu ----------------
# [m] Mỗi chu kỳ tiến độ s chỉ được lùi tối đa / tiến tối đa bấy nhiêu. Giữ s liên tục trên path
# đi-về cùng hành lang; tăng quá thì s có thể nhảy sang nhánh về.
projection_back_window: 0.5
projection_forward_window: 2.0
# [m] Khoảng nhìn trước của bộ sinh quỹ đạo mồi (pure pursuit). Giảm: rẽ gắt hơn.
lookahead_distance: 0.6
# [m] Nửa cửa sổ làm mượt độ cong path lưới.
curvature_window: 0.2
# ---------------- Bộ tìm nghiệm ----------------
# Số quỹ đạo mồi tối đa mỗi chu kỳ (warm, nominal, brake, slow, lệch trái/phải).
max_seeds: 9
# [m] Độ lệch ngang của các quỹ đạo mồi lách vật cản, áp cả hai bên.
seed_lateral_offsets: [0.5, 1.0]
# Số vòng tinh chỉnh coordinate descent. 0 = chỉ chọn mồi tốt nhất.
sweeps: 3
# Ngân sách mỗi chu kỳ: số lần rollout và thời gian [ms]. Hết ngân sách thì dùng nghiệm tốt nhất
# đã có. Chu kỳ control 20 Hz = 50 ms; giữ solver_budget_ms dưới ~15 ms trên NUC i3.
max_evaluations: 400
# Sim 1.0 m/s chỗ đông vật: p95 ~8.6 ms, 8 ms hết ngân sách ~1/3 chu kỳ -> nâng 15 ms.
solver_budget_ms: 15.0
# [m] Tiến độ dọc path tối thiểu phải đạt trong progress_check_time [s] đầu. Quỹ đạo "đứng
# bây giờ, đi sau" bị loại, nếu không robot đứng mãi mà không báo lỗi.
minimum_progress: 0.025
progress_check_time: 1.0
# [m] Khi đường tâm path bị chặn phía trước, tham chiếu được dịch ngang tối đa max_lateral_shift
# theo bước lateral_shift_step để robot lách. 0 = tắt lách (bị chặn là báo lỗi ngay).
max_lateral_shift: 1.2
lateral_shift_step: 0.2
# ---------------- Chế độ (supervisor) ----------------
# [rad] Lệch hướng so với path lớn hơn align_enter_angle khi ĐANG ĐỨNG YÊN thì xoay tại chỗ;
# xoay tới khi lệch < align_exit_angle. align_enter_angle phải > align_exit_angle.
align_enter_angle: 1.2
align_exit_angle: 0.35
# [1/s] omega = gain * lệch hướng khi xoay tại chỗ (còn bị kẹp bởi trần góc và gia tốc góc).
# Tăng: đoạn cuối lúc ω giảm dần trước khi thoát ALIGN ngắn hơn. Không vọt lố khi
# gain^2 * lệch <= 2 * max_yaw_accel ở vùng ω chưa chạm trần (2.5 với 1.5 rad/s^2: an toàn).
align_yaw_gain: 2.5
# [s] Thời gian chờ tối đa khi người/vật động chắn đường. Phải nhỏ hơn idle_window_s của
# EnvMonitor (25 s) để MPCC tự báo lỗi trước khi EnvMonitor coi là kẹt.
wait_timeout: 10.0
# [chu kỳ] Số chu kỳ liên tiếp có quỹ đạo khả thi mới rời WAIT (chống nhấp nháy đi/dừng).
resume_cycles: 3
# [m] Ô costmap chặn đường nằm trong bán kính này quanh một track đang di chuyển thì coi là
# người (WAIT) thay vì vật tĩnh (báo lỗi cho recovery).
wait_track_association_radius: 0.6
# ---------------- Đích ----------------
xy_goal_tolerance: 0.10 # [m]
yaw_goal_tolerance: 0.10 # [rad]
stopped_speed: 0.05 # [m/s] và [rad/s] — dưới mức này coi là đứng yên
goal_settle_cycles: 2 # [chu kỳ] đứng trong cả hai tolerance bấy nhiêu chu kỳ mới báo tới đích
# [m] Robot chỉ chạy tiến: dừng ở cuối path mà lệch goal (đi quá goal, cua cuối đi rộng, path
# kết thúc lệch goal) thì không lùi lại được. Trong khoảng này vẫn chấp nhận: quay tại chỗ về yaw
# goal rồi báo tới đích. 0 (hoặc <= xy_goal_tolerance) = tắt, chỉ dùng xy_goal_tolerance.
# Tăng: ít replan hơn nhưng điểm dừng có thể xa goal hơn.
goal_overshoot_tolerance: 0.5
# [s] Đứng yên ở cuối path mà xa goal hơn mức trên quá thời gian này -> báo lỗi
# stalled_before_goal để move_base2 replan, thay vì giữ lệnh 0 mãi.
goal_stall_timeout: 3.0
# ---------------- Tracker vật cản động ----------------
# Công tắc gói tracker vật cản động (robot_dynamic_obstacle_tracker).
# true — bật: chạy worker đọc /f_scan, người/vật động được dự đoán, robot có thể WAIT.
# Tracker thiếu dữ liệu / hết hạn / lỗi TF là lỗi: robot dừng an toàn (fail-closed).
# false — tắt hẳn: không chạy worker, không đọc tracker_config_file. Vật động chỉ được thấy qua
# costmap như vật tĩnh: robot lách hoặc báo static_blocked cho recovery, KHÔNG có WAIT
# chờ người đi qua. Dùng khi nghi tracker sinh track ma.
# (Khoá cũ `require_tracker` vẫn được đọc làm giá trị mặc định nếu thiếu `use_tracker`.)
use_tracker: false
# Đường dẫn YAML tracker. Đường dẫn tương đối được tìm trong PNKX_NAV_CORE_CONFIG_DIR rồi
# PNKX_NAV_CORE_DIR/config; không thấy thì plugin báo rõ các chỗ đã tìm.
# Máy dev: đường dẫn tuyệt đối tới YAML của gói tracker (không chép YAML tracker vào cây runtime).
tracker_config_file: /home/duongtd/T800_ws/src/AMR_T800/Test/robot_dynamic_obstacle_tracker/robot_dynamic_obstacle_tracker/config/tracker_params_olei.yaml
tracker_max_age: 0.45 # [s] snapshot tracker cũ hơn thì dừng an toàn
tracker_uncertainty_scale: 2.0 # hệ số sigma nở bán kính vật động theo bất định
max_dynamic_obstacles: 32 # vượt số này là lỗi (không bỏ track âm thầm)
# ---------------- Log chẩn đoán ----------------
# Mặc định BẬT. Log lỗi không có khoá tắt. stats_period [s]: chu kỳ in thống kê, 0 = tắt in định kỳ.
stats_period: 2.0
debug:
solve: true # thời gian tính p50/p95/max, số rollout, quỹ đạo mồi thắng
mode: true # mỗi lần đổi chế độ ALIGN/TRACK/WAIT/TERMINAL/ROTATE_GOAL/FAIL
reject: true # số mồi bị loại theo lý do, phân bố lý do thất bại, khoảng hở nhỏ nhất
tracker: true # số track thô / đủ điều kiện / đang dùng, tuổi lớn nhất

View File

@@ -54,7 +54,7 @@ PriestLocalPlanner:
# sự dài thì khoảng hụt kéo dài qua ngưỡng này và horizon vẫn bung.
# 0 = bung ngay (hành vi cũ)
# --- Solver tự khai bất khả thi (2026-09-04) ---
# Mọi cổng va chạm của planner này đã chuyển sang env_monitor/contact (guard cũ path_monitor/collision đã xoá 6/9/2026) của move_base2 (LETHAL +
# Mọi cổng va chạm của planner này đã chuyển sang path_monitor/collision của move_base2 (LETHAL +
# chu vi footprint đệm); planner không còn tự dò costmap để dừng. Thứ duy nhất nó còn giữ là tín
# hiệu không ai khác có: best_res_norm — chuẩn vi phạm ràng buộc của CẢ batch. Thang đo thực tế:
# bám đường sạch 0–0.3, né bình thường 1–2, mọi ca ngõ cụt đã đọc 4–7. Đo 4/9: res treo 4.5–7.0
@@ -64,7 +64,7 @@ PriestLocalPlanner:
# CỔNG sv > 0 (2026-09-04): res tính trên CẢ horizon, nên hàng người cách 1.7 m — solver còn 5 s
# để xử — đọc y hệt ngõ cụt (đo 15:21: khai 10 lần, cả 10 lần sv=0, gần nhất 1.3 m). Chỉ khai khi
# start_violations > 0, tức thân đã lấn vành ellipse của ít nhất một vật cản THẬT (với ngưỡng 254).
infeasible_residual: 3.0 # [-] res >= mức này coi là bất khả thi. Hạ (2.0) = khai sớm hơn,
infeasible_residual: 3.5 # [-] res >= mức này coi là bất khả thi. Hạ (2.0) = khai sớm hơn,
# dễ khai oan ở bãi dày mà vẫn lách được; nâng (4–5) = chỉ khai khi
# đã bế tắc rõ. 0 = TẮT.
infeasible_streak_cycles: 20 # [chu kỳ] treo liên tục ngần này mới khai (20 @20 Hz = 1 s) —
@@ -75,8 +75,9 @@ PriestLocalPlanner:
# 0 = không cool-down.
# ================= Giới hạn robot (dẫn động vi sai) =================
max_velocity: 1.2 # [m/s] trần vận tốc tiến
max_angular_velocity: 0.5 # [rad/s] đồng thời được ép bên trong bộ tối ưu dưới dạng
max_velocity: 1.2 # [m/s] trần vận tốc tiến. Cũng là trần của tốc độ host gửi xuống
# (setTwistLinear: VDA5050 maxSpeed, tầng an toàn): chạy = min(max_velocity, host).
max_angular_velocity: 1.0 # [rad/s] đồng thời được ép bên trong bộ tối ưu dưới dạng
# chặn gia tốc ngang |a_n| <= max_angular_velocity * v
max_acceleration: 0.5 # [m/s^2] dùng trong phép chiếu quỹ đạo
# ---- Bao êm ái của LỆNH xuất ra (S1/P2). Bộ tối ưu vẫn dùng max_acceleration
@@ -94,16 +95,9 @@ PriestLocalPlanner:
# omega nhảy 0 -> ±0.5 trong MỘT chu kỳ, chính là cú giật
# lúc chốt XY rồi bật sang pha xoay)
angular_jerk_limit: 3.0 # [rad/s^3] trần biến thiên gia tốc góc; 0 = tắt
slew_reseed_gap: 0.3 # [s] hai lệnh phát ra cách nhau quá chừng này (hoặc vừa nhận plan mới) thì
# bộ trượt tốc độ KHỞI ĐỘNG LẠI từ vận tốc ĐO ĐƯỢC của base, không mang theo
# lệnh cũ. Đo 6/9 21:57, 4 lần recovery: move_base2 giữ base ở 0.00 m/s
# 1.1-1.5 s trong lúc replan, nhưng bộ trượt vẫn tưởng đang chạy 0.20-0.43
# (không ai reset nó, và dt bị kẹp 0.1 s nên cả quãng dừng thành "một chu
# kỳ"). Lệnh đầu tiên trên plan mới = tốc độ ma đó -> robot nhích 0.07-0.33 m
# rồi mới xoay, mất tới 1.55 s phanh từ một tốc độ nó không hề có.
# 0.3 s = 6 chu kỳ @20 Hz: một lượt giải chậm không bao giờ dài tới thế.
# 0 = TẮT (hành vi cũ).
reference_velocity: 0.4 # [m/s] tốc độ hành trình mong muốn dọc path
reference_velocity: 0.4 # [m/s] tốc độ hành trình KHI HOST CHƯA GỬI TRẦN NÀO. Host gửi trần x > 0 qua
# setTwistLinear thì tốc độ chạy = min(max_velocity, x), không còn dùng số này
# (đo 14/9: order 1.0 mà robot kẹt 0.4 theo YAML). Host gửi 0 = dừng tại chỗ.
v_eps: 0.05 # [m/s] chậm hơn ngưỡng này thì bỏ qua phần chặn/phạt độ cong,
# tránh chia cho số gần 0 khi robot gần đứng yên
v_min_seed: 0.05 # [m/s] vận tốc mồi theo hướng yaw khi robot đang đứng yên,
@@ -140,13 +134,8 @@ PriestLocalPlanner:
# sát. 0 = tắt (một sàn duy nhất như cũ)
# ================= Goal / plan =================
xy_goal_tolerance: 0.04 # [m] sai số vị trí chấp nhận là đã tới goal. [16/9] 0.02 -> 0.04 (P4 plan
# 28/8): dừng từ 0.15 m/s trong 2 cm cần a=0.56 > decel_comfort 0.35, robot
# BẮT BUỘC vượt goal (đo 15/9: dist=0.06 mà vmeas=0.17). Vành nhả latch
# = tolerance x xy_latch_release_factor cũng nới 0.10 -> 0.20 m: đo 16/9
# latch ở 0.093 rồi nhả ở 0.100 vì xoay tại chỗ trôi 7 mm — 0.10 quá sát.
yaw_goal_tolerance: 0.04 # [rad] sai số góc chấp nhận là đã tới goal. [16/9] 0.01 -> 0.04 (2.3 deg):
# 0.01 rad (0.57 deg) nằm dưới nhiễu odometry, robot săn điểm dừng.
xy_goal_tolerance: 0.02 # [m] sai số vị trí chấp nhận là đã tới goal
yaw_goal_tolerance: 0.01 # [rad] sai số góc chấp nhận là đã tới goal
xy_latch_release_factor: 5.0 # chốt XY: vào trong xy_goal_tolerance là coi phần vị trí XONG, chỉ
# [19/8] 2.0 với tolerance 0.02 = vành nhả 0.04 m — robot latch lúc
# còn trôi 0.2 m/s (phanh cần 4-6 cm) là văng khỏi vành ngay, xoay
@@ -198,7 +187,7 @@ PriestLocalPlanner:
# omega_ff = cross/v^2 — bò chậm trên đoạn CONG là nó kịch trần và lật
# dấu theo nhiễu (lắc đầu; đoạn thẳng tử số ~0 nên không lắc). Feedback
# heading vẫn lái. 0 = tắt (feedforward đầy đủ mọi tốc độ như cũ)
omega_ff_filter_tau: 0.35 # [s] E1b — hằng số thời gian lọc thông thấp cho FEEDFORWARD độ cong,
omega_ff_filter_tau: 0.35 # [s] E1b — hằng số thời gian lọc thông thấp cho FEEDFORWARD độ cong,
# CHỈ áp khi lời giải sạch (residual < clear_residual). Trên đoạn
# thẳng trống độ cong THẬT bằng 0, nhưng CEM vẽ lại quỹ đạo mỗi chu
# kỳ và độ cong ngẫu nhiên nhỏ của nó, chia cho v^2, làm omega ngoáy
@@ -206,7 +195,20 @@ PriestLocalPlanner:
# -0.06/-0.15/+0.16 liên tiếp, omega bám theo gần như y hệt).
# Vật cản vừa ràng buộc lời giải là BỎ QUA bộ lọc ngay — né vật cản
# giữ nguyên toàn quyền phản ứng tức thì. 0 = tắt
max_global_plan_lookahead_dist: 3.0 # [m] chỉ lấy phần path toàn cục trong tầm này để bám
max_global_plan_lookahead_dist: 4.0 # [m] chỉ lấy phần path toàn cục trong tầm này để bám. Đây
# cũng là tầm xa nhất mà L1 trượt TIẾN điểm ghim cuối được: core chỉ
# thấy đoạn path này, và cửa sổ đi theo robot nên robot chạy cũng không
# làm nó dài thêm. Ghim còn có ích tới min(max_velocity*t_fin, obstacle_range
# + 0.65): xa hơn thì không kịp tới trong t_fin, hoặc "sạch" chỉ vì solver
# không thấy vật. Với sim (0.5*7 = 3.5, 2.8+0.65 = 3.45) cần >= 3.75.
# Cửa sổ 3.0 m chỉ chừa 0.18 m sau ghim: trượt lùi bật thì ghim ra TRƯỚC
# vật -> đánh lái về phía vật rồi bẻ ngược (đo 5/10: tslide -0.75/-1.12
# rồi +0.22); trượt lùi tắt thì ghim kẹt TRONG vật -> res 4.7-9.0 nhiều
# giây, cũng đánh lái về phía vật rồi bẻ ngược (đo 6/10).
# Khi terminal_slide_max_dist > 0 và terminal_slide_backward = false,
# planner TỰ NÂNG giá trị này lên mức cần lúc boot (log cảnh báo, dòng
# init in window=...). Lớn hơn chỉ tốn thêm điểm hành lang.
# Đo 5/10 cùng mission, 3.0 -> 5.0: body_hit 6 -> 0, recovery 9 -> 4.
hold_timeout: 10.0 # [s] đứng chờ (pivot bị chặn ở goal / fallback bị chặn) quá chừng
# này thì trả fail cho move_base2 leo thang (recovery/abort báo fleet).
# Trước đây chờ VÔ HẠN: obs tĩnh đè goal + planner_frequency 0 = treo
@@ -231,25 +233,12 @@ PriestLocalPlanner:
omega_ff_curvature_margin: 1.5 # [-] hệ số nới so với độ cong đường tham chiếu. 1.0 = bám đúng
# độ cong path; lớn hơn = cho solver cắt cua thoải mái hơn.
# 0 = TẮT trần này.
omega_ff_curvature_floor: 0.04 # [rad/s] sàn của trần, để path thẳng tuyệt đối vẫn còn quyền
omega_ff_curvature_floor: 0.12 # [rad/s] sàn của trần, để path thẳng tuyệt đối vẫn còn quyền
# lái nhẹ giữ line. Thấp quá = trôi khỏi đường thẳng;
# cao quá = lắc quay lại.
omega_ff_curvature_window: 1.5 # [m] quãng đường phía trước dùng để đo độ cong tham chiếu.
# Ngắn = vào cua rồi mới nới trần (phản ứng trễ);
# dài = khúc cua còn xa đã nới trần trên đoạn vẫn đang thẳng.
zeta_from_start_tangent: false # [bool] ĐÃ THỬ VÀ TẮT (sim 7/9, boot 1788745971). Bật = đo sai số
# hướng so với tangent quỹ đạo NGAY TẠI ROBOT thay vì tangent trung
# bình cửa sổ lệnh. KHÔNG dùng được: ràng buộc start ghim vận tốc
# đầu quỹ đạo vào đúng yaw robot, nên tangent tại mẫu đầu LUÔN trùng
# yaw và zeta = 0 theo định nghĩa (đo được 109/111 mẫu đang chạy =
# 98 %). Feedback heading chết hẳn: cross-track error lên 2.00 m cả
# hai mission, 57/172 mẫu có vật cản gần dưới 0.45 m (inscribed
# 0.53), robot quệt rồi kẹt cứng 48 s.
# Bài học: heading feedback ở đây KHÔNG phải PID cross-track mà là
# bộ khuếch đại độ cong — nó đẩy omega qua trần để luật giữ độ cong
# cắt v, giữ nguyên bán kính cua đã lập. Cú sụt tốc khi thoát khe
# (0.50 -> 0.24 m/s) là CÁI GIÁ của việc giữ bán kính, không phải
# lỗi. Muốn giảm sụt thì nâng max_angular_velocity, đừng tắt feedback.
# ================= Vật cản (lấy từ local costmap) =================
num_obs: 200 # số vật cản đưa vào hàm chi phí CEM. TRẦN CỨNG trong code là 200 —
@@ -266,10 +255,9 @@ PriestLocalPlanner:
# Tăng lên chỉ cần khi robot phải lách giữa RẤT nhiều vật cản rời rạc
# cùng lúc mà thấy nó cắt góc quá sát.
obstacle_range: 2.8 # [m] bán kính quét costmap quanh robot
robot_radius: 0.50 # [m] bán kính robot dùng cho phép kiểm va chạm
obstacle_point_radius: 0.08 # [m] bán kính quy ước cho mỗi điểm vật cản
footprint_padding: 0.05 # [m] nới footprint thêm để có biên an toàn
obstacle_cost_threshold: 253 # ô costmap có cost >= ngưỡng này mới coi là ĐIỂM VẬT CẢN cho solver.
footprint_padding: 0.0 # [m] nới footprint thêm để có biên an toàn
obstacle_cost_threshold: 254 # ô costmap có cost >= ngưỡng này mới coi là ĐIỂM VẬT CẢN cho solver.
# 2026-09-04: 253 -> 254. Ở 253 điểm vật cản gồm cả vành INSCRIBED (dày
# inflation_radius 0.30 m quanh mỗi ô LETHAL) rồi lại bọc ellipse a_obs 0.65
# lên đó — đệm HAI LẦN: tâm circle phải cách bề mặt vật cản 0.95 m, khe hai
@@ -278,7 +266,7 @@ PriestLocalPlanner:
# khả thi" ở hàng người/bãi trụ. 254 = chỉ ô LETHAL thật; ellipse 0.65 giữ
# nguyên làm biên mềm -> mép thân cách vật cản 0.13 m, khe lọt 1.30 m.
# Hệ quả phụ: mất blob 0.3 m quanh mỗi ô -> ít điểm hơn, solve nhẹ hơn.
obstacle_cell_step: 2 # bước nhảy khi quét ô costmap. Lớn = nhanh hơn, bỏ sót nhiều hơn.
obstacle_cell_step: 1 # bước nhảy khi quét ô costmap. Lớn = nhanh hơn, bỏ sót nhiều hơn.
# L3 — đo 29/8 bãi dày với step 2: `points=200/299`, tức 299 điểm nằm
# trong tầm mà chỉ nạp được 200; 99 điểm còn lại VÔ HÌNH với solver, và
# không có gì bảo đảm chúng là những điểm xa nhất. Step 3 lấy mẫu mỗi
@@ -289,16 +277,22 @@ PriestLocalPlanner:
# Bị hạ xuống bằng num_obs lúc nạp (giữ thêm điểm chỉ tốn sort/copy mà
# solver không bao giờ nhìn tới), nên để bằng cho khớp thực tế.
# Footprint phủ bằng nhiều circle dọc thân robot thay cho một disc tại base_link.
# Robot 1.166x0.96 m: disc robot_radius 0.50 hụt mũi/đuôi ~0.13 m (bán kính ngoại tiếp 0.755) —
# lách là quệt góc; phình disc che đủ thì khe ~1.8 m mới qua. 3 circle r=0.52 tâm {-0.39, 0, +0.39}
# che kín chữ nhật mà khe ~1.3 m vẫn lách được. Mỗi cặp (vật cản, circle) là một virtual obstacle
# dịch theo heading quỹ đạo; nhờ sparse gating chi phí chỉ nhân vào cặp va chạm.
footprint_circle_count: 3 # số circle. 1 = disc cũ tại base_link (dùng robot_radius, bỏ qua
# hai khoá dưới)
footprint_circle_spacing: 0.39 # [m] khoảng cách tâm hai circle kề nhau, xếp đối xứng quanh base_link
footprint_circle_radius: 0.52 # [m] bán kính mỗi circle khi count > 1; cộng obstacle_point_radius
# + footprint_padding thành ellipse va chạm mỗi circle
# THÂN ROBOT trong bộ tối ưu = một hàng circle dọc trục x của thân, TỰ TÍNH từ footprint của
# costmap (bản chưa padding — cùng nguồn với path-first và move_base2) lúc khởi động và mỗi khi
# footprint đổi (gắn xe đẩy). Không còn khoá nhập tay. Cách tính: chia chiều dài thân thành
# footprint_circle_count đoạn bằng nhau, mỗi circle ôm một đoạn:
# spacing = dài / count, radius = căn((spacing/2)^2 + nửa_rộng^2), tâm hàng = giữa thân.
# Tâm hàng lấy từ footprint nên robot có base_link KHÔNG nằm giữa thân (APM: thân x từ -0.35 tới
# 1.65, tâm +0.65) vẫn được phủ kín mũi. Mỗi circle cộng obstacle_point_radius + footprint_padding
# thành ellipse va chạm. Dòng boot "PriestControl body (from costmap footprint):" in số đang dùng.
# Footprint costmap hỏng (< 3 điểm, NaN, không có dài/rộng) thì planner KHÔNG khởi động; hỏng giữa
# chừng thì giữ thân cũ và log lỗi. Các khoá cũ robot_radius, footprint_circle_spacing/_radius/
# _center, footprint_from_costmap, collision_check_front/rear/side_offset còn sót trong YAML thì
# bị BỎ QUA (có cảnh báo lúc boot).
footprint_circle_count: 5 # số circle. Nhiều circle = ôm sát thân hơn (lách khe hẹp hơn) nhưng
# tốn CPU hơn (mỗi cặp vật cản x circle là một ràng buộc). 1 = một disc
# ngoại tiếp cả thân (rộng nhất). T800 1.166x0.96 m: 3 circle r~0.52
# lách được khe ~1.3 m; 1 disc r~0.76 cần khe ~1.8 m
start_violation_ramp_time: 1.5 # [s] > 0 = BẬT ramp cho vật cản mà robot ĐANG vi phạm ellipse ngay
# tại điểm xuất phát (đỗ cách tường 0.5-0.6 m là dính, vì ellipse
# mô hình 0.65 m phóng đại hơn thân thật): không ramp thì phép chiếu
@@ -321,31 +315,36 @@ PriestLocalPlanner:
# Dùng ĐÚNG ellipse mà phép chiếu dùng, nên "bị chặn" ở đây nghĩa
# là "ràng buộc solver không thể thoả". 0 = tắt.
# Dòng SOLVE in tslide=<khoảng cách đã trượt, + tiến / - lùi>
terminal_slide_backward: false # cho ghim TRƯỢT LÙI (về phía robot) khi phía trước không có chỗ
# sạch. Ghim lùi nằm ngay TRƯỚC MẶT vật cản -> cả batch lập kế hoạch đi
# tới đó thay vì vòng qua: robot đánh lái VỀ PHÍA vật rồi bẻ ngược khi
# ghim nhảy qua vật (đo 5/10: tslide -0.45/-0.53 đầu leg, chu kỳ sau
# +0.67, omega -0.5 -> +0.5). false = giữa tuyến chỉ trượt tiến, phía
# trước không sạch thì giữ ghim cũ; RIÊNG khi path kết thúc tại goal
# trong tầm trượt (phía trước hết đường) vẫn cho lùi để dừng trước vật —
# cấm lùi cả ở đó thì ghim nằm lại trong vật, batch bất khả thi (đo 5/10:
# res 4-7 suốt 14 s gần goal, omega lật +-0.5). true = dò xen kẽ
# tiến/lùi ở mọi nơi như cũ.
# Chỉ có tác dụng khi terminal_slide_max_dist > 0
# Chọn điểm theo HÀNH LANG dọc plan thay vì gần robot nhất: lọc điểm trong bán kính
# corridor_radius quanh polyline plan (đã cắt lookahead) + vị trí robot, và chia đều trần
# num_obs dọc hành lang (round-robin) — hết cảnh một bức tường sát robot nuốt trọn budget
# trong khi vật cản 2 m phía trước trên tuyến thì vô hình.
obstacle_corridor_enabled: true # bật trên cây sim để đánh giá; tắt = chọn gần robot nhất như cũ
corridor_radius: 1.2 # [m] nửa bề rộng hành lang chọn điểm. Sàn tự động = robot_radius +
# obstacle_point_radius + footprint_padding; rộng hơn = nhìn xa hai
# bên hơn nhưng tốn suất điểm hơn
corridor_radius: 1.2 # [m] nửa bề rộng hành lang chọn điểm. Sàn tự động = bán kính circle
# (tự tính từ footprint) + obstacle_point_radius + footprint_padding;
# rộng hơn = nhìn xa hai bên hơn nhưng tốn suất điểm hơn
corridor_sample_spacing: 0.3 # [m] bước lấy mẫu plan làm xương hành lang. Nhỏ = bucket mịn,
# chia suất đều hơn dọc tuyến; không cần nhỏ hơn nhiều so với
# resolution costmap (0.05)
# ================= Hình học thân cho các probe còn lại =================
# Cổng va chạm của planner này (dò quỹ đạo / dò cung lệnh / chốt thân-trong-vành) đã CHUYỂN sang
# env_monitor/contact (guard cũ path_monitor/collision đã xoá 6/9/2026) của move_base2 (2026-09-03): LETHAL + chu vi footprint đệm, planner-agnostic.
# Planner không còn tự dừng vì va chạm. Bốn khoá dưới đây chỉ còn là HÌNH HỌC THÂN cho ba phép dò
# mềm còn lại: head_slowdown, quét pivot trước khi xoay tại chỗ, đĩa kiểm goal bị đè. Giữ tên khoá
# để không đổi schema.
collision_check_front_offset: 0.583 # [m] tầm mũi robot tính từ base_link (theo footprint T800
# trong move_base2_control.launch: nửa dài 0.583)
collision_check_rear_offset: 0.583 # [m] tầm đuôi robot tính từ base_link
collision_check_side_offset: 0.48 # [m] thêm 2 probe HÔNG trái/phải cách trục dọc chừng này (nửa bề
# rộng robot 0.48) — 3 probe trục dọc chỉ che chiều dài, cú quệt
# hông đầu mission 4 (sim 18/8) lách đúng chỗ này. 0 = 3 probe cũ
# path_monitor/collision của move_base2 (2026-09-03): LETHAL + chu vi footprint đệm, planner-agnostic.
# Planner không còn tự dừng vì va chạm. Ba phép dò mềm còn lại (head_slowdown, quét pivot trước khi
# xoay tại chỗ, đĩa kiểm goal bị đè) dò costmap ở mép thân, với hình học thân TỰ TÍNH từ footprint
# costmap: mũi = x lớn nhất, đuôi = -x nhỏ nhất, hông = |y| lớn nhất (5 điểm: tâm, mũi, đuôi, hai hông).
collision_check_cost_threshold: 253 # cost costmap >= ngưỡng này coi là chạm (253 =
# INSCRIBED_INFLATED_OBSTACLE, 254 = LETHAL; ô NO_INFORMATION
# được bỏ qua). Chỉ còn phục vụ head_slowdown/pivot/goal.
@@ -436,33 +435,86 @@ PriestLocalPlanner:
# flip ở sv=10, res 2.9-3.9, sv vọt 54, quệt thật). Bị chặn thì ở lại
# bên cũ; đếm trong log sblk=. Margin + hold vẫn áp bình thường.
# Bên cũ hết elite thì guard tự nhường. 0 = tắt
# ================= Elite blend (B2, 8/9) =================
# Trên đoạn THOÁNG (không vật cản ràng buộc), nhiều elite của CEM gần đồng cost — batch được vẽ
# lại NGẪU NHIÊN mỗi chu kỳ nên elite thắng (hard-argmin) đổi qua đổi lại, độ cong đầu quỹ đạo
# đổi theo -> omega đảo dấu liên tục dù đường thẳng, không vật cản (đo sim 7-8/9: res=0.00,
# omega nhảy dấu ~50% số chu kỳ). Bật blend: trộn top-N elite theo trọng số softmax thay vì lấy
# đúng 1 elite. KHÔNG đụng cost(k)/obstacle penalty/cập nhật phân phối CEM — chỉ đổi bước chọn
# nghiệm cuối cùng, và có bộ kiểm chứng: quỹ đạo trộn không tốt bằng elite thắng (dùng đúng công
# thức cost đã có) thì tự động dùng lại elite thắng, y hệt hôm nay.
elite_blend_enabled: true # [bool] BẬT trên cây sim (8/9) để đo thực địa. Cây robot thật vẫn tắt.
# Bật = kích hoạt trộn elite mọi chu kỳ (bộ kiểm chứng tự thu hẹp
# phạm vi khi có vật cản, không cần công tắc riêng theo obs)
elite_blend_topn: 10 # số elite tham gia trộn, cắt về [1, ellite_num]. ĐO 8/9 (30 chu kỳ,
# đường thẳng thoáng): topn 2-5 làm phương sai omega TĂNG 75-180%
# (trộn nửa vời chỉ thêm nguồn nhiễu mà không trung bình được gì);
# topn=10 giảm 48% VÀ cross-track 0.037 -> 0.009 m; topn 20/40 lợi
# ít dần rồi mất hẳn (kéo cả elite hạng thấp vào). 1 = tắt hiệu quả
elite_blend_lambda: 0.5 # [-] nhiệt độ softmax RIÊNG cho blend, không dùng chung cem_lamda để
# không vô tình đổi tốc độ hội tụ phân phối CEM. Thấp = trọng số sập
# gần về elite thắng ngay khi cost tách biệt (đúng lúc có vật cản);
# cao = san đều trọng số hơn, dễ mượt quá tay
elite_blend_validate_margin: 0.01 # ngưỡng chấp nhận của bộ kiểm chứng, đơn vị cost (giống thang
# cost(k) trừ phần res_norm). Quỹ đạo trộn tệ hơn elite thắng quá
# ngưỡng này thì bị từ chối, dùng lại elite thắng như cũ. 0 = trộn
# phải tốt bằng hoặc hơn elite thắng, không có dung sai
side_commit_divergence: 0.20 # [m] > 0 = chỉ CHỐT bên khi việc chọn bên làm robot chạy khác đi.
# Đo khoảng cách tại mốc 1/4 horizon (1.75 s với t_fin 7) giữa quỹ
# đạo rẻ nhất bên trái và rẻ nhất bên phải path; chỉ có một bên thì
# đo độ lệch của nó khỏi path. In ra là sdiv= trong [DBG-PRIEST-SOLVE].
# Dưới ngưỡng: hai bên còn đi gần như nhau, để ngỏ không gây lắc. Chốt
# sớm ở đó là chốt theo nhiễu CEM rồi bị side_hold_cycles khoá, robot
# đánh lái về phía vật cản tới khi hết khoá (đo sim 6/10 mission 8:
# chốt lúc res 0, vật còn cách 2.4 m, 3.1 s sau mới đổi bên).
# Đã chốt, hết khoá, CẢ HAI bên đều có quỹ đạo và sdiv dưới một nửa
# ngưỡng liên tục side_hold_cycles chu kỳ -> NHẢ bên (đã qua vật, chỉ
# còn tường). Chỉ còn một bên thì không nhả: đang né dở.
# Tăng = chốt muộn hơn, ít chốt nhầm, nhưng trước lúc chốt CEM có thể
# chọn bên khác nhau giữa các chu kỳ; giảm = chốt sớm như cũ.
# 0 = luật cũ (có cặp va chạm nào trong batch là chốt)
# Sim 7/10: lúc chưa chốt sdiv tới 0.13; 5 lần chốt ở 0.15-0.19 lúc
# res ~0 (nhiễu) -> nâng 0.15 lên 0.20. Chốt thật: 0.21-0.31 khi cả hai
# bên có quỹ đạo; ca chỉ một bên 0.16-0.19 rồi lên 0.3-0.4 chu kỳ sau.
# ================= Debug =================
# ---------------------------------------------------------------------------
# Lớp bám path (Test/priest_local_planner/doc/CLEAR_PATH_TRACKING_PLAN.md).
# PRIEST vẫn giải mọi chu kỳ y như cũ; lớp này chỉ chọn lệnh nào ra bánh xe.
# Khi PRIEST có BẤT KỲ điểm vật cản nào trong tầm (điểm đã gom cho solver, hoặc
# vật cản động) thì lệnh luôn là lệnh PRIEST — kết quả né vật cản không đổi.
# Chỉ trên đoạn thật sự trống, tracker LQ (tất định, không nhiễu CEM) mới lái,
# để robot không lắc khi đi trên path.
# ---------------------------------------------------------------------------
tracking_mode: 3 # 0 = tắt (lệnh y hệt bản cũ từng bit). 1 = chỉ đo: in dòng tổng kết
# [DBG-PRIEST-TRACK] mỗi leg cho lệnh PRIEST hiện tại. 2 = shadow: chạy
# thêm tracker + trọng tài, log lệnh tracker SẼ phát, vẫn phát lệnh
# PRIEST. 3 = lái: tracker phát lệnh khi không có vật cản trong tầm.
track_path_smoothing: 0.3 # [m] sigma làm mượt bản sao path cho tracker. Tăng = độ cong mượt hơn
# nhưng góc cua bị kéo vào trong ~sigma^2/(2R). 0 = không làm mượt.
track_horizon: 2.0 # [s] tầm nhìn trước của tracker. Tăng = vào cua sớm và êm hơn, tốn CPU hơn.
track_model_dt: 0.05 # [s] bước mô hình tracker.
track_lateral_weight: 15.0 # [1/m^2] phạt lệch ngang. Tăng = về path gắt hơn, dễ vọt lố hơn.
track_heading_weight: 5.0 # [s^2/m^2] phạt vận tốc ngang v*theta. Tăng = ít vọt lố, về path chậm hơn.
track_turn_weight: 0.5 # [s^2/rad^2] phạt omega lệch khỏi v*kappa. Tăng = quay sát độ cong path hơn.
track_turn_rate_weight: 0.2 # [s^4/rad^2] phạt tốc độ đổi omega. Tăng = êm hơn nhưng phản ứng trễ hơn.
track_curve_margin: 0.9 # [-] trần tốc độ vào cua = max_angular_velocity * margin / |kappa|.
# Giảm = vào cua chậm hơn, còn dư omega để sửa lệch.
track_release_hold: 0.5 # [s] hết vật cản LIÊN TỤC bấy lâu mới bắt đầu giao lệnh cho tracker.
# Quay lại PRIEST thì luôn tức thì, ngay chu kỳ thấy vật.
track_release_tau: 0.7 # [s] hằng số thời gian chuyển dần lệnh PRIEST -> tracker. 0 = chuyển ngay.
# Luật "bám path trước, chỉ né khi bị chặn" (Test/priest_local_planner/doc/PATH_FIRST_AVOID_ON_BLOCK_PLAN.md).
# Đo (tracking_mode >= 2): kéo footprint thật dọc path đã làm mượt, đo khoảng hở tới ô LETHAL (254),
# in trong dòng tổng kết leg [DBG-PRIEST-TRACK] (đoạn "rule1:").
# track_arbiter_rule chọn AI LÁI: 0 = luật cũ (PRIEST lái khi có BẤT KỲ vật nào trong hành lang 1.2 m,
# phần khoảng hở chỉ đo); 1 = PRIEST chỉ lái khi thân robot đi theo path sẽ chạm/gần chạm vật
# (dưới track_block_clearance), còn lại tracker bám path kể cả khi path đi sát vật.
track_arbiter_rule: 1 # 0 = luật cũ; 1 = bám path trước. 1 cần tracking_mode >= 2 (mode 3 mới lái thật).
track_block_clearance: 0.10 # [m] khoảng hở thân-vật dọc path dưới mức này = path BỊ CHẶN (PRIEST phải né).
# Tăng = né sớm hơn, ít dám đi sát; giảm = dám bám path sát vật hơn.
# Phải lớn hơn sai số định vị + sai số bám, đừng đặt 0.
track_pass_clearance: 0.11 # [m] path đã bị chặn thì khoảng hở phải về >= mức này mới coi là THOÁNG lại.
# >= track_block_clearance, tối đa 0.5. Để SÁT block: việc chống nháy đã có
# track_release_hold (theo thời gian). Đo 8/10: để 0.15 thì path chạy sát vật
# 0.10-0.15 m làm PRIEST giữ lái 16 s và lệch 0.3-0.45 m dù thân vẫn lọt.
track_block_lookahead: 3.6 # [m] quãng path phía trước được dò. Tăng = thấy chỗ chặn sớm hơn, tốn CPU hơn.
# Cần >= max_velocity^2 / (2*decel_comfort) + 1.5 m (host có thể cho chạy tới
# max_velocity; 1.2 m/s, decel 0.35 -> 3.56 m); không vượt
# max_global_plan_lookahead_dist (cửa sổ path chỉ dài chừng đó).
track_block_confirm_distance: 1.5 # [m] chỗ chặn XA hơn mức này dọc path phải thấy liên tục vài chu kỳ
# (~0.15 s) mới tính — chống nháy ở mép tầm laser/costmap. Gần hơn: tính ngay.
# 0 = không chờ. Tăng = ít nháy hơn nhưng phản ứng chậm hơn với vật mới xuất hiện.
track_slow_clearance: 0.30 # [m] luật 1: khoảng hở dọc path dưới mức này thì tracker giảm tốc dần, về
# track_close_speed tại track_block_clearance (tự phanh trước chỗ hẹp).
# 0 = tắt. Phải >= track_pass_clearance, tối đa 0.5.
track_close_speed: 0.25 # [m/s] tốc độ tracker khi đi qua chỗ hẹp nhất còn cho phép (khoảng hở = block).
# Giảm = qua khe chậm và an toàn hơn; tăng = nhanh hơn, ít biên phản ứng hơn.
track_rejoin_max_heading: 0.40 # [rad] trần góc tracker lao về path khi đang lệch xa (sau khi né xong).
# Đo 8/10: lệch 0.9 m, không trần thì góc lên 0.95 rad (54 độ). Giảm = về
# path êm hơn nhưng lâu hơn. 0 = tắt (luật LQ thuần).
track_takeover_max_heading: 0.80 # [rad] luật 1: tracker chỉ được BẮT ĐẦU nhận lái từ PRIEST khi robot lệch
# hướng path không quá mức này; đã lái rồi thì không bị giật lại. Đo 8/10:
# mission bị thay giữa chừng lúc chạy 0.39 m/s, lệch 1.19 rad, tracker nhận
# ngay. Giảm = nhận lái muộn hơn, PRIEST quay đầu trước. 0 = tắt.
debug_tracking: true # log [DBG-PRIEST-TRACK]: sự kiện giao lệnh (debug_level >= 1), dòng 1 Hz
# (>= 2), tổng kết mỗi leg (luôn in khi tracking_mode >= 1). Tắt = false.
# Nhóm log chẩn đoán [DBG-PRIEST-*]. debug_level là công tắc tổng; ba cờ dưới chọn nhóm.
# Mức 3 in mỗi chu kỳ (~30 dòng/giây @ 30 Hz) — chỉ dùng khi truy lỗi, xong trả về 0.
debug_level: 2 # 0=tắt 1=chỉ log khi sự kiện đổi (solve fail/hồi, điểm vật cản chạm trần)
@@ -496,4 +548,4 @@ PriestLocalPlanner:
# Rẻ: một lần dò costmap mỗi plan + một lần mỗi giây. Tắt = false.
# LƯU Ý: cảnh báo "reference path crosses N LETHAL cell(s)" KHÔNG tắt
# được bằng khoá này — path xuyên ô lethal là lỗi của global planner,
# không phải thông tin chẩn đoán.
# không phải thông tin chẩn đoán.

View File

@@ -0,0 +1,254 @@
# Plugin PriestMpccLocalPlanner (gói priest_mpcc_local_planner) — cây config chạy test máy dev (sim), nạp
# qua launch của move_base2. Bản mặc định đóng gói (executor priest, tính năng mới tắt):
# Test/priest_mpcc_local_planner/config/priest_mpcc_local_planner_params.yaml; hai file cùng tập khoá.
# PRIEST đề xuất quỹ đạo né; executor (nhóm hybrid) ra lệnh. Cây dev chạy executor mpcc: MPCC là nguồn
# lệnh duy nhất, bám global path khi thoáng, bám quỹ đạo PRIEST khi path bị chặn.
#
# File chỉ ghi các khoá hay chỉnh. Khoảng 130 khoá còn lại có default trong code bằng đúng giá trị đã
# tune (bản YAML đầy đủ trước khi thu gọn); danh sách, default và cách ghi đè:
# Test/priest_mpcc_local_planner/config/HIDDEN_KEYS.md. Muốn đổi khoá ẩn thì thêm nó vào đúng nhóm
# (gốc / priest / hybrid / wheel / mpcc) ở file này. Lý do chọn từng số (số đo, ngày, lượt sim) nằm trong bản
# đầy đủ: git -C Test/priest_mpcc_local_planner show 96e55f8:config/priest_mpcc_local_planner_params.yaml
# Plan: Test/docs/priest_mpcc_local_planner/PRIEST_MPCC_HYBRID_PLAN.md.
PriestMpccLocalPlanner:
library_path: libpriest_mpcc_local_planner
# ================= Chung cho PRIEST và MPCC: tốc độ và giới hạn vận động =================
# Một bộ số cho cả hai: PRIEST lập quỹ đạo và MPCC bám quỹ đạo đó trong cùng giới hạn của robot.
# MPCC không có khoá tốc độ/gia tốc riêng (mpcc/max_speed, max_yaw_rate, max_accel, max_decel,
# max_yaw_accel còn trong YAML thì boot cảnh báo và bỏ qua).
max_velocity: 1.2 # [m/s] trần tốc độ tiến. Host gửi trần x (setTwistLinear, VDA5050 maxSpeed)
# thì chạy min(max_velocity, x). MPCC từ chối boot (chạy executor priest) nếu
# mpcc horizon*dt < max_velocity/max_acceleration + 0.5 s.
reference_velocity: 0.7 # [m/s] tốc độ hành trình của PRIEST và MPCC khi host CHƯA gọi setTwistLinear.
# Host gửi x > 0: chạy min(max_velocity, x), số này thôi dùng. Host gửi 0 = dừng.
max_angular_velocity: 1.0 # [rad/s] trần tốc độ quay khi đang chạy: PRIEST ép |a_n| <= số này x v, MPCC
# kẹp omega (còn bị kẹp bởi mpcc max_lateral_accel, khoá ẩn 0.5 m/s^2).
# Giảm = cua rộng và chậm hơn.
max_acceleration: 0.5 # [m/s^2] tăng VÀ giảm tốc khi lập kế hoạch: phép chiếu PRIEST, rollout và phanh
# MPCC (kiểm va chạm giả định đúng số này). Giảm = êm hơn, phanh dài hơn.
max_angular_accel: 1.0 # [rad/s^2] gia tốc góc: rollout MPCC và slew lệnh host/PRIEST. Giảm = omega đổi
# chậm, êm hơn. 0 = PRIEST không giới hạn (omega nhảy bậc), MPCC giữ default 1.5.
decel_emergency: 1.0 # [m/s^2] giảm tốc khi host giữ (hold) hoặc PRIEST phải dừng. MPCC tự phanh theo
# max_acceleration. Giảm = phanh dài hơn.
in_place_yawrate_max: 1.2 # [rad/s] trần tốc độ quay TẠI CHỖ (đầu path, về yaw đích; PRIEST và MPCC).
# 0 = dùng max_angular_velocity. Đế không xoay tại chỗ được thì để 0.
min_in_place_yawrate: 0.2 # [rad/s] sàn tốc độ quay tại chỗ. Phải lớn hơn mép vùng chết bánh (KIT
# 0.058): dưới đó bánh bị phanh điện, robot đứng im.
# ================= Goal / plan (host, mọi executor) =================
xy_goal_tolerance: 0.02 # [m] sai số vị trí coi là tới goal. Giảm = đỗ chính xác hơn, chốt lâu hơn.
yaw_goal_tolerance: 0.01 # [rad] sai số góc coi là tới goal.
# Luật đích (như hybrid_local_planner): đạt XY trước rồi mới quay về yaw goal; tới ngang hoặc đi quá
# goal là dừng tiến ngay rồi quay, không quay lại tìm goal.
goal_pass_radius: 0.10 # [m] vòng tiếp cận goal. Trong vòng: goal không còn trước mũi quá xy_goal_tolerance
# (đã tới ngang/qua goal), hoặc robot đứng yên mà không gần thêm 5 mm suốt
# goal_settle_time, thì chốt XY, dừng tiến, quay về yaw. Sai số XY cuối <= số này:
# để <= allowedDeviationXY của fleet (VDA5050). 0 = luật cũ (chỉ chốt khi goal sau lưng).
goal_settle_time: 0.5 # [s] trong vòng tiếp cận, robot đứng yên mà không gần goal thêm chừng này thì chốt XY
# (MPCC dừng ngắn khi goal nằm ngang hông). Giảm = chốt sớm hơn. 0 = tắt.
xy_latch_release_factor: 5.0 # > 1 = bật chốt XY: bị đẩy xa hơn xy_goal_tolerance x số này (và đã dừng) thì nhả,
# chạy lại vị trí. <= 1 = tắt chốt (đế không xoay tại chỗ được).
goal_regression_watch_dist: 0.5 # [m] trong bán kính này nhớ khoảng cách gần nhất tới goal; khoảng cách tăng lại quá
# goal_regression_margin = đã đi quá goal: chốt XY, dừng, quay. 0 = tắt.
goal_regression_margin: 0.01 # [m] khoảng tăng coi là đi ra xa. Nhỏ = dừng ngay khi vượt goal (như
# hybrid); quá nhỏ thì rung định vị cắt ngang lần tiếp cận đang tốt.
goal_brake_decel: 0.35 # [m/s^2] trần tốc độ theo quãng còn lại: v <= sqrt(2 a (dist - xy_goal_tolerance)).
# Nhỏ = vào goal êm và lâu hơn; lớn = phanh muộn, gắt hơn. 0 = tắt.
hold_timeout: 10.0 # [s] đứng chờ (goal bị che, pivot bị chặn) quá chừng này thì báo fail cho
# move_base2 (recovery/abort). 0 = chờ vô hạn (nguy hiểm: treo câm).
max_global_plan_lookahead_dist: 4.0 # [m] chỉ lấy phần global path trong tầm này. Planner tự nâng lúc boot
# nếu trượt ghim cuối cần xa hơn (log cảnh báo). Lớn hơn chỉ tốn CPU hơn.
# ================= PRIEST (lập quỹ đạo né, mọi executor) =================
# Bộ tối ưu, mô hình vật cản/thân và trọng số của PRIEST. Tốc độ và gia tốc lấy từ mục Chung ở trên.
priest:
# ---- Vật cản và thân robot
obstacle_range: 2.8 # [m] bán kính lấy điểm vật cản từ costmap quanh robot. Tăng = thấy xa hơn,
# tốn CPU hơn.
footprint_padding: 0.03 # [m] nới thân thêm trong PRIEST. Tăng = né xa hơn, khó qua khe hơn.
obstacle_point_radius: 0.025 # [m] bán kính quy ước của mỗi điểm vật cản trong PRIEST.
footprint_circle_count: 3 # số circle phủ thân trong PRIEST (tự tính từ footprint costmap). Nhiều = ôm
# sát thân, lách khe hẹp hơn, tốn CPU hơn. 1 = một disc ngoại tiếp (rộng nhất).
footprint_model: rectangle # circles = phủ bằng nhiều hình tròn; rectangle = thân chữ nhật sát footprint hơn,
# mỗi điểm vật chỉ xét một hình nên có thể giảm CPU.
obstacle_cost_threshold: 254 # ô costmap cost >= ngưỡng này là điểm vật cản cho PRIEST. 253 = tính cả vành
# inscribed (né xa hơn); 254 = chỉ ô LETHAL (lách khe hẹp hơn).
obstacle_cell_step: 1 # bước nhảy khi quét ô costmap lấy điểm vật (1 = mọi ô). Lớn = nhanh hơn, bỏ sót
# vật nhỏ/mỏng hơn.
max_obstacle_points: 200 # trần số điểm vật cản lấy từ costmap; bị hạ bằng num_obs lúc nạp nên để bằng
# num_obs. Giảm = nhẹ CPU, nhưng điểm xa có thể vô hình với solver.
num_obs: 200 # số điểm vật cản trong hàm chi phí CEM. Trần cứng 200: lớn hơn bị hạ lúc nạp.
# Giảm = nhẹ CPU, quỹ đạo có thể cắt qua vật ngoài tập điểm.
num_obs_proj: 200 # số điểm gần nhất đưa vào phép chiếu (ADMM), <= num_obs. NÚT THẮT thời gian giải:
# chi phí phép chiếu tỉ lệ thẳng với số này. Giảm = giải nhanh hơn, quỹ đạo dễ sát
# vật hơn khi nhiều vật rời rạc. MPCC vẫn kiểm va chạm thẳng trên costmap.
corridor_radius: 1.2 # [m] nửa bề rộng hành lang chọn điểm vật quanh path. Rộng = nhìn xa hai bên,
# tốn suất điểm hơn.
corridor_follow_trajectory: true # true = hành lang bám cả quỹ đạo PRIEST chu kỳ trước:
# né xa path vẫn thấy vật dọc đường vòng. false = chỉ quanh global path.
# ---- Bộ tối ưu
t_fin: 7.0 # [s] tầm nhìn dự báo. Dài = né sớm hơn, tốn CPU hơn.
t_fin_min: 1.0 # [s] sàn của horizon co theo path còn lại gần goal; định hình cú phanh cuối
# (1.0 -> phanh trên ~0.4 m cuối). 0 = horizon cố định.
num_steps: 30 # số điểm mẫu trên mỗi quỹ đạo trong t_fin. Tăng = quỹ đạo mịn, kiểm vật dày hơn,
# tốn CPU hơn (mọi phép chiếu tỉ lệ theo số này).
num_batch: 60 # số quỹ đạo mỗi vòng CEM. Tăng = tìm kỹ hơn, tốn CPU hơn.
ellite_num: 40 # số quỹ đạo elite (residual nhỏ nhất) dùng cập nhật CEM, < num_batch và >=
# hybrid/priest_candidates. Tăng = phân bố đổi chậm, ổn định; giảm = hội tụ gắt hơn.
max_cem_iter: 3 # số vòng CEM mỗi chu kỳ điều khiển. Tăng = nghiệm tốt hơn, chậm hơn.
max_proj_iter: 8 # số vòng chiếu (ADMM) tối đa mỗi vòng CEM; thoát sớm khi residual đã nhỏ. Tăng =
# quỹ đạo khả thi hơn sát vật, tốn CPU hơn ở bãi vật dày.
optimizer_threads: 4 # số thread của solver. Đừng lấy hết số core: overhead nuốt lợi ích.
lateral_std: 0.8 # [m] độ lệch chuẩn nhiễu ngang của waypoint. Lớn = khám phá rộng, dễ tìm đường
# vòng; nhỏ = bám sát global path.
terminal_slide_max_dist: 1.5 # [m] điểm ghim cuối quỹ đạo được trượt dọc path tối đa chừng này để ra khỏi
# vật nó rơi vào (ghim trong vật = cả batch bất khả thi, robot lết). Planner tự nâng
# max_global_plan_lookahead_dist cho đủ chỗ trượt. 0 = tắt.
# ---- Trọng số hàm chi phí: "tính cách" của PRIEST. Tăng một cái = giảm tương đối các cái còn lại.
weight_smoothness: 0.1 # phạt quỹ đạo gãy khúc. Tăng = quỹ đạo êm hơn, né muộn hơn.
weight_track: 0.2 # phạt lệch khỏi global path. Tăng = bám path, ít vòng xa; giảm = dễ đi vòng.
weight_obs: 1.2 # phạt tiến gần vật cản. Tăng = né xa hơn, khó qua khe hơn.
weight_clearance: 3.0 # thưởng giữ khoảng hở (1 tại tâm vật, 0.5 tại biên va chạm, 0 ngoài tầm). Tăng =
# đi giữa lối hơn.
weight_angular: 0.5 # phạt khi |omega| vượt max_angular_velocity. Tăng = quỹ đạo ít quay gắt.
weight_velocity_deficit: 2.0 # phạt hụt tốc ở 1/4 horizon đầu. Tăng = không chịu bò ở đầu quỹ đạo cạnh bãi
# vật; 0 = tắt (nghiệm chậm ở đầu dễ thắng khi vật dày).
# ---- Chọn bên né (vật nằm giữa tuyến: hai nghiệm trái/phải cost gần bằng nhau)
side_switch_margin: 0.2 # bên kia phải rẻ hơn ít nhất tỉ lệ này mới được đổi bên (0.2 = 20%). Tăng = lì
# hơn, ít lật bên; 0 = mất tác dụng chống lật.
side_hold_cycles: 60 # [chu kỳ] khoá bên vừa chọn chừng này. Tăng = ít lật bên ở bãi vật dày, chậm nhận
# đường tốt hơn khi map đổi; 0 = tắt.
# ================= Giới hạn từng bánh (lọc mọi lệnh ở cửa ra) =================
# Base vi sai: v_phai = v + omega*L/2, v_trai = v - omega*L/2. separation 0 = TẮT bộ lọc.
# Sim không có vùng chết nên tắt. Robot KIT (đo 8/10): 0.517 / 0.906 / 0.015.
wheel:
separation: 0.0 # [m] L mà driver dùng đổi lệnh ra rpm (KIT 0.517, KHÔNG phải 0.503 của odom).
max_speed: 0.0 # [m/s] trần mỗi bánh (KIT 0.906 = 3000 rpm). Vượt thì giảm v, giữ omega.
# 0 = không trần.
deadband_speed: 0.0 # [m/s] bánh chậm hơn mức này bị driver gán 0 và phanh điện (KIT 0.015 = 50 rpm).
# 0 = không xử lý vùng chết.
# ================= MPCC (chỉ đọc khi hybrid/executor = mpcc) =================
# Lệnh MPCC phát thẳng, KHÔNG qua bao êm ái của PRIEST. Tốc độ và gia tốc lấy từ mục Chung ở trên.
mpcc:
horizon: 16 # [bước] số bước dự đoán. Boot từ chối nếu 0.05 + (horizon-1)*dt < max_velocity /
# max_acceleration + 0.5 s (không đủ quãng phanh): 1.2 / 0.5 cần >= 16 bước.
# Tăng = thấy vật sớm hơn, tốn CPU hơn.
dt: 0.2 # [s] độ dài bước 1..N-1 (0.05 + 15 x 0.2 = 3.05 s nhìn trước).
collision_margin: 0.03 # [m] khoảng hở luôn giữ giữa thân và ô vật cản, gánh cả sai số nửa ô. Tăng = an
# toàn hơn, khó qua khe; dưới 0.03 dễ quẹt.
footprint_perimeter_spacing: 0.1 # [m] > 0 = phủ VIỀN footprint bằng đĩa rộng tối đa chừng này
# (sát thân, ~43 đĩa với 0.1, tốn CPU hơn). 0 = 6 đĩa dọc trục (nhô ~0.39 m trước mũi).
exact_body_clearance: true # true = đĩa nào đọc dưới ngưỡng thì đo lại đúng thân đa giác tới tâm ô vật cản
# (cùng thước PRIEST): rollout, phát hiện chạm, quay tại chỗ, F3, S1. Bỏ báo hụt
# tới ~8 cm của đĩa ở khe; vẫn giữ thân >= collision_margin tới tâm ô, nên xe đi sát
# vật hơn trước. false = chỉ đĩa như cũ. Tốn thêm ~3 ms/chu kỳ ở chỗ hẹp.
slow_clearance: 0.30 # [m] (S1) khoảng hở thân-vật dọc tham chiếu dưới mức này thì giảm tốc, tuyến
# tính tới slow_speed tại slow_min_clearance; phanh TRƯỚC chỗ hẹp. 0 = tắt.
slow_min_clearance: 0.1 # [m] (S1) khoảng hở tại đó (và gần hơn) tốc độ bằng slow_speed. < slow_clearance.
slow_speed: 0.25 # [m/s] (S1) tốc độ qua chỗ hẹp nhất. Giảm = chậm và an toàn hơn.
slow_by_body: true # (S1b) hạ tốc cả theo khoảng hở của CHÍNH THÂN dọc từng rollout (cùng ngưỡng
# slow_*): cắt góc sát vật cũng phải chậm. Cần slow_clearance > 0. false = chỉ S1.
slow_directional: true # (S1/S1b) true = chỉ hạ tốc khi qua khe (CẢ HAI bên dưới slow_clearance) hoặc khi
# thân đang LẠI GẦN vật; sát vật một bên, bên kia thoáng, đi dọc hay rời xa thì không
# hạ tốc (vẫn giữ collision_margin). Cần footprint_perimeter_spacing > 0. false = như cũ.
# Cũng áp cho F3: biên rollout hạ (narrow_*) chỉ kèm slow_speed khi là khe thật.
solver_budget_ms: 15.0 # [ms] trần thời gian giải; hết thì dùng nghiệm tốt nhất đã có. NUC i3: <= ~15.
max_seeds: 12 # số mồi tối đa mỗi chu kỳ (warm, PRIEST, nominal, brake, slow, lệch trái/phải).
seed_lateral_offsets: [0.5, 1.0] # [m] độ lệch ngang của mồi lách, áp hai bên.
warm_seed_bonus: 0.1 # [-] mồi warm được giảm cost chừng này, chống nghiệm lật qua lại. 0 = tắt;
# lớn quá = bám nghiệm cũ khi đã có đường tốt hơn.
align_enter_angle: 1.2 # [rad] đứng yên mà lệch hướng tham chiếu hơn mức này thì quay tại chỗ trước khi
# chạy (cung quét kiểm trên viền thân). Phải > align_exit_angle.
align_exit_angle: 0.35 # [rad] quay tới khi lệch dưới mức này rồi trả lại cho MPCC.
align_fine_angle: 0.10 # [rad] (F11) đứng yên mà MPCC không có plan (static_blocked / no_progress), lệch
# hướng tham chiếu hơn mức này (dù dưới align_exit_angle) thì quay tại chỗ tới mức
# này rồi thử MPCC lại: thân ép xiên cạnh tường không lái ra được nhưng xoay ra được.
# 0 = tắt (dưới align_exit_angle không quay). Phải < align_exit_angle.
align_yaw_gain: 2.5 # [1/s] omega = gain x lệch hướng khi quay tại chỗ (cả quay về yaw đích).
# Tăng = quay nhanh hơn ở đoạn cuối.
# ================= Executor (hybrid) =================
# lq và mpcc cần tracking_mode 3 và track_arbiter_rule 1 (default trong code, khoá ẩn); sai điều kiện
# thì log lỗi và chạy priest.
hybrid:
executor: mpcc # priest = luật lệnh của PRIEST. lq = LQ bám quỹ đạo PRIEST khi path bị chặn.
# mpcc = MPCC là nguồn lệnh duy nhất: bám global path khi qua cổng khả thi trên
# viền thân, không thì bám quỹ đạo PRIEST tốt nhất qua cổng, nối về global path.
crawl_enabled: true # false = tắt; true = cho phép bò theo PRIEST khi MPCC không có lệnh.
crawl_speed: 0.12 # [m/s] trần tốc độ bò; tăng = qua nhanh hơn, quãng phanh dài hơn.
crawl_entry_cycles: 2 # [chu kỳ] số lần MPCC không có lệnh trước khi bò; giảm = vào sớm hơn.
crawl_progress_speed: 0.06 # [m/s] tốc độ tối thiểu để MPCC được tính là tiến; tăng = giữ bò lâu hơn.
crawl_entry_window: 1.0 # [s] khoảng cách tối đa giữa hai lần không có lệnh; tăng = nhớ lâu hơn.
crawl_exit_cycles: 3 # [chu kỳ] số lần MPCC tiến liên tiếp trước khi trả quyền; tăng = bò lâu hơn.
crawl_margin: 0.02 # [m] khoảng hở tối thiểu của thân dọc quỹ đạo; tăng = khó vào hơn.
# Chỉ dùng khi gate_body_clearance false (true: ngưỡng thân suy từ r_o).
crawl_check_length: 1.5 # [m] chiều dài đầu quỹ đạo phải kiểm; tăng = nhìn xa hơn, tốn CPU hơn.
crawl_stop_margin: 0.01 # [m] khoảng hở tối thiểu khi dự đoán dừng; tăng = dừng sớm hơn.
crawl_stop_horizon: 0.3 # [s] giữ lệnh trong dự đoán trước khi phanh; tăng = dừng sớm hơn. Thân dài
# trong khe hẹp: 1.0 làm lệnh có quay (|omega| >= 0.15) bị chặn hết (sim 20/11).
crawl_max_distance: 2.0 # [m] quãng đường tối đa mỗi lượt bò; tăng = bò xa hơn.
crawl_max_time: 20.0 # [s] thời gian tối đa mỗi lượt bò; tăng = chờ lâu hơn trước recovery.
reference_hold_time: 1.0 # [s] (mpcc) thời gian cam kết với quỹ đạo vừa nhận khi nó còn qua cổng. Tăng =
# ít đổi tham chiếu, ít lật bên né; giảm = theo phương án mới sớm hơn.
global_max_offset: 0.5 # [m] (mpcc) robot cách global path xa hơn mức này thì bám quỹ đạo PRIEST dẫn về
# thay vì bám thẳng path. Tăng = về path sớm, dễ bám xuyên vật đang né.
gate_hysteresis: 0.03 # [m] (mpcc) tham chiếu đang bám vẫn qua cổng tới khi khoảng hở xuống dưới
# collision_margin trừ chừng này (chống nháy ô costmap ở khe). 0 = tắt. Trần 0.05.
# gate_body_clearance true: trừ từ ngưỡng thân, áp cả cho tham chiếu của chế độ bò.
gate_body_clearance: true # (mpcc + bò) true = cổng tham chiếu đo thân đa giác tới tâm ô vật cản, cùng thước PRIEST,
# cần >= r_o (priest/obstacle_point_radius + footprint_padding) - gate_body_tolerance.
# Bỏ báo hụt 6-9 cm của thước EDT ở khe hẹp. false = cổng EDT + collision_margin như cũ.
gate_body_tolerance: 0.01 # [m] tham chiếu mới được thấp hơn r_o chừng này (PRIEST ràng buộc mềm). Tăng = dễ qua
# cổng hơn, sát vật hơn; giảm = chặt hơn, dễ nháy. Trần 0.05 và nửa r_o.
gate_partial_min_ahead: 0.6 # [m] (mpcc) tham chiếu chỉ bị chặn ở XA vẫn được bám: robot chậm lại, đứng
# chờ cách chỗ chặn chừng này. Tăng = chờ xa vật hơn; đừng dưới ~0.3. 0 = tắt.
mpcc_blocked_timeout: 0.05 # [s] (mpcc) không có lệnh an toàn mà phanh vẫn an toàn: đứng chờ tối đa chừng
# này rồi báo lỗi cho move_base2 (recovery). 0 = báo ngay. Phanh không an
# toàn thì luôn báo lỗi ngay.
mpcc_priest_wait_timeout: 0.0 # [s] (mpcc) như trên nhưng khi PRIEST VẪN có quỹ đạo, chỗ chặn ở phía trước
# (thường là người). Tăng = chờ người đi qua lâu hơn. 0 = dùng mpcc_blocked_timeout.
mpcc_priest_wait_static_time: 0.0 # [s] (mpcc, F5) chờ ở trên dừng sớm khi đường đi (global path)
# không thoáng ra suốt chừng này: khoảng hở cổng của nó không tăng quá 2 cm. Vật
# tĩnh, ô ma costmap không tự đi; ô nháy hay người đứng cạnh path không tính. Giảm =
# báo sớm hơn (người đứng im trên path cũng bị coi là vật tĩnh). 0 = luôn chờ đủ.
turn_min_clearance: 0.02 # [m] (mpcc, F1) quay tại chỗ có vòng quét cách vật dưới collision_margin
# nhưng >= chừng này thì vẫn quay, chậm (turn_slow_yawrate). Đừng 0.0 khi costmap
# còn nhiễu. 0 = tắt (dưới margin là từ chối quay).
turn_slow_yawrate: 0.3 # [rad/s] (mpcc, F1) trần tốc độ quay khi quay sát vật. Tăng = nhanh hơn, phanh
# kịp kém hơn nếu vật dịch vào.
narrow_min_clearance: 0.02 # [m] (mpcc, F3) sàn khoảng hở rollout giữ ở chỗ hẹp; rollout giữ
# min(collision_margin, khoảng hở tham chiếu 1 m tới - narrow_tracking_error),
# tốc độ kẹp ở mpcc/slow_speed. Giảm = lách khe hẹp hơn, sát vật hơn. 0 = tắt.
narrow_tracking_error: 0.03 # [m] (mpcc, F3) rollout được lệch khỏi tham chiếu về phía vật tới chừng này.
contact_escape_depth: 0.03 # [m] (mpcc, F4) thân lấn vào ô vật cản tối đa chừng này (chỉ viền) thì
# LÁI RA thay vì đứng giữ, tốc độ <= mpcc/slow_speed. Tăng = thoát cả khi lấn sâu
# hơn (vật thật thì nguy hiểm hơn). 0 = tắt (chạm là giữ).
contact_escape_time: 1.5 # [s] (mpcc, F4) phải ra khỏi chỗ chạm trong chừng này; quá thì giữ rồi recovery.
priest_candidates: 4 # (mpcc) số quỹ đạo PRIEST dự phòng ngoài quỹ đạo tốt nhất. Tăng = nhiều phương án
# khi quỹ đạo tốt nhất cắt vật (~0.1 ms mỗi quỹ đạo). 0 = chỉ tốt nhất. Trần 16.
priest_fallback_enabled: true # [bool] MPCC hết lệnh thì chạy lệnh PRIEST có bao tốc độ theo khoảng hở thân
priest_fallback_min_clearance: 0.015 # [m] khoảng hở tối thiểu thân tới tâm ô; giảm = sát hơn, quệt nhiều hơn
priest_fallback_check_length: 1.5 # [m] đoạn quỹ đạo PRIEST được kiểm phía trước
debug: true # log nhóm debug/hybrid: đổi bên lái, đổi tham chiếu và lý do, đổi mode MPCC,
# tổng kết mỗi leg. Công tắc còn lại ở mục Debug ngay dưới. Log lỗi không tắt được.
# ================= Debug =================
# Nhóm log chẩn đoán [DBG-PRIEST-*]. debug_level là công tắc tổng; các cờ chọn nhóm. Log lỗi không phụ
# thuộc mục này (vd cảnh báo "reference path crosses N LETHAL cell(s)" luôn in).
debug:
crawl: true # true = log một dòng khi bắt đầu/kết thúc bò; false = tắt nhóm log này.
debug_level: 2 # 0 = tắt; 1 = chỉ khi sự kiện đổi; 2 = định kỳ 1 Hz; 3 = mọi chu kỳ (~30 dòng/s,
# chỉ dùng khi truy lỗi).
debug_solve: true # [DBG-PRIEST-SOLVE] thời gian từng stage solver [ms], residual, cost, warm start.
debug_obstacles: true # [DBG-PRIEST-OBS] số điểm vật cản so với trần; chạm trần = solver mù vật xa.
debug_command: true # [DBG-PRIEST-CMD] lệnh phát ra + trạng thái (state, v, omega, vmeas, dist, res...).
# Ồn nhất ở mức 3.
debug_plan: true # [DBG-PRIEST-PLAN] đường tham chiếu solver được giao: plan mới, ô bị chặn dọc path.
debug_tracking: true # [DBG-PRIEST-TRACK] giao lệnh tracker / executor, dòng 1 Hz, tổng kết mỗi leg.
solve_time_warn_ms: 30.0 # [ms] cảnh báo khi solver giải lâu hơn ngưỡng này (chừa biên trong chu kỳ 30 Hz).

View File

@@ -15,7 +15,7 @@
# BỐ CỤC FILE:
# 1. behaviors — registry mọi behavior CÓ THỂ dùng (khai ở đây chưa làm nó chạy).
# 2. routes — trigger nào chạy chuỗi behavior nào. Đây là chỗ bốn phép đo gặp nhau.
# 3. tham số behavior — wait / clear / rotate / back_up / detour_path.
# 3. tham số behavior — wait / clear / rotate / back_up / detour_path / evade.
# 4. symbol -> library — bảng nạp Boost.DLL.
# 5. SBPLDetourPlanner — instance SBPL riêng mà detour_path dùng.
# =================================================================================================
@@ -32,6 +32,7 @@ recovery:
# rotate : quay tại chỗ cho sensor quét lại xung quanh.
# detour_path : LẬP LẠI CẢ ĐƯỜNG tới đích chặng bằng SBPL (từ 2/9 không còn vá đường vòng).
# back_up : LÙI — hướng robot không có sensor, rủi ro cao nhất.
# evade : NÉ vật sát thân — lùi 0.2 m, không lùi được thì xoay về phía trống.
#
# ► Chỉnh: khai ở đây KHÔNG làm behavior chạy — phải đưa tên nó vào một `route` bên dưới. Một
# `type` được phép khai nhiều `name` khác nhau để có nhiều instance khác tuning (vd một
@@ -45,6 +46,7 @@ recovery:
- {name: detour_path, type: DetourPathRecovery}
- {name: rotate, type: RotateRecovery}
- {name: back_up, type: BackUpRecovery}
- {name: evade, type: EvadeRecovery}
# ===============================================================================================
# 2. ROUTES — trigger nào chạy chuỗi behavior nào
@@ -69,6 +71,19 @@ recovery:
# `replan_budget`, stand-down); file này quyết định giơ cờ rồi thì LÀM GÌ (behavior nào, thứ tự,
# bao nhiêu lượt). Muốn tắt một verdict thì đặt `action: log` bên kia, không xoá route bên này.
#
# ROUTE THEO DETECTOR (gói env_monitor_core, 26/11/2026): bảng trên là MẶC ĐỊNH. Mỗi detector của EnvMonitor tự
# chọn route trong khối của nó ở `env_monitor_params.yaml`:
# route: <tên> một khoá bất kỳ của `routes` dưới đây — sáu tên cũ hoặc tên mới (ví dụ `intrusion: [...]`).
# Tên không có ở đây = detector bị GỠ lúc boot (log LỖI). Log ghi `trigger (detector)`,
# route tên mới ghi `detector (<tên detector>)`.
# route_mode: step mỗi lần nổ chạy MỘT behavior (cursor bên dưới) — như bảng trên.
# sequence một lần nổ chạy LIỀN cả route; behavior hỏng hay nộp path giữa chừng vẫn chạy tiếp, path
# mới nhất được áp khi xong; cả chuỗi tính MỘT lượt (lần nổ sau coi như cạn, trừ khi chuỗi
# ra path mới và robot đã đi >= `recovery_reset_min_travel`).
# on_exhausted: lock | abort cột "Cạn route thì..." ở trên, nay là khoá của detector chứ không của tên trigger.
# Mỗi detector có cursor RIÊNG, kể cả khi hai detector trỏ cùng một route. `planning_failed`/`controlling_failed` không
# do detector nào giơ nên luôn chạy kiểu step.
#
# HỢP ĐỒNG CHUNG cho mọi route (đọc một lần, áp cho cả sáu):
#
# - Cursor: lần lỗi kế tiếp CÙNG trigger mới tiến tới phần tử tiếp theo của route đó. Mỗi trigger
@@ -108,7 +123,7 @@ recovery:
# chấp nhận cho robot tự lùi khi bế tắc — lập lại đường từ đúng pose đang kẹt thường trả lại
# cùng một path (sim 4/9), muốn thoát phải ĐỔI POSE trước. back_up có kiểm costmap sau lưng
# nhưng phía sau là vùng mù sensor: đó là đánh đổi an toàn, không phải mặc định.
controlling_failed: [detour_path]
controlling_failed: [evade, detour_path]
# Hai nguồn cùng đổ vào đây:
# - `oscillation_timeout` gốc: quẩn trong bán kính `oscillation_distance` quá lâu (đang TẮT,
@@ -132,12 +147,12 @@ recovery:
# tuyến trước mặt tắc thật chứ không phải PRIEST đang né. Nổ khi thân còn cách vật ít nhất
# `clean_start_margin` (0.2 m) nên lập lại đường là đủ, không cần lùi.
# ► Chỉnh: ngưỡng và cổng nằm ở `env_monitor_params.yaml` mục `unreachable`; ở đây chỉ đổi behavior.
path_blocked: [detour_path]
path_blocked: [evade, detour_path]
# off_path: KHÔNG CÒN NGUỒN từ 6/9/2026 — phép đo lệch plan của PathMonitor đã xoá, EnvMonitor
# không đo cross-track vì lệch plan là việc local planner né, không phải lỗi. Route giữ cho đủ sáu
# trigger của StateMachine; sẽ không nổ cho tới khi có verdict mới cấp cờ này.
off_path: [detour_path]
off_path: [evade, detour_path]
# kContact (`contact/action: recover`): QUỸ ĐẠO THẬT của local planner quét vào ô LETHAL. EnvMonitor
# đã tự bao tốc độ và phanh trước (`apply_command: true`, `brake_decel`, `envelope_margin`); cờ chỉ
@@ -150,7 +165,13 @@ recovery:
# chạy vì phanh thuộc `apply_command`, không thuộc route — và quy tắc A vẫn leo thang.
# ► Chỉnh: `[back_up, detour_path]` khi chấp nhận lùi trước rồi mới lập lại đường — đây là lối
# ra thật của ngõ cụt sát vật; giữ `[detour_path]` nếu chưa muốn robot tự lùi.
collision: [detour_path]
collision: [evade, detour_path] # TẠM 26/11 thử sim evade — KHÔNG commit, trả về [detour_path]
# intrusion: route của IntrusionDetector (`env_monitor_params.yaml` mục `intrusion`, route_mode step,
# on_exhausted lock): vật lạ vừa đi vào trong 0.10 m quanh thân. Mỗi lần nổ chạy một lượt evade (lùi 0.2 m,
# không được thì xoay ra phía trống); ba lượt mà vật vẫn bám thì khoá detector, robot bám tiếp plan.
# ► Chỉnh: thêm `detour_path` ở cuối nếu muốn lập lại đường sau khi né không thoát.
intrusion: [evade, evade, evade]
# ===============================================================================================
# 3. THAM SỐ TỪNG BEHAVIOR — xếp từ RẺ/AN TOÀN tới ĐẮT/RỦI RO
@@ -303,6 +324,67 @@ recovery:
# ► Chỉnh: phải > backup_distance_max / linear_speed (1.0/0.1 = 10 s) cộng dư địa ramp.
timeout: 15.0
# --- evade: phản xạ né vật sát thân ------------------------------------------------------------
#
# Có vật lạ (chân người...) vào sát thân thì lùi thẳng `backup_distance`; phía sau không đủ chỗ thì
# xoay tại chỗ cho đầu hướng ra phía trống nhất (hướng tính từ dữ liệu, không phải góc cố định).
# Không động tác nào khả thi thì trả lỗi như mọi recovery. Vật cản = điểm lidar thô của
# `scan_topics` + ô LETHAL của local costmap, kiểm bằng footprint THẬT (không padding), nên vẫn lùi
# ra được khe hở 3 cm mà `back_up` từ chối. Route `intrusion` (IntrusionDetector, gói env_monitor_core)
# chạy nó; đưa vào route khác cũng được.
evade:
# Topic LaserScan, phải có trong sensor_store (`sensor_store_params.yaml`). Thiếu scan hoặc scan
# quá tuổi thì evade từ chối chạy — không né mù.
scan_topics: [/f_scan, /b_scan]
# [s] Scan cũ hơn mức này = coi như không thấy gì.
# ► Chỉnh: TĂNG nếu log báo "is stale" dù lidar vẫn chạy (lidar chậm, lệch đồng hồ). GIẢM làm
# evade hay từ chối hơn. Đừng vượt ~0.5 s: robot đang xoay thì điểm cũ lệch chỗ.
max_scan_age: 0.5 # sim chạy chậm hơn thời gian thực: lidar 12.5 Hz về thưa, tuổi scan tới 0.32 s (27/11). Robot thật giữ 0.3.
# [s] TF tại đúng stamp scan chưa có thì nhận TF mới nhất nếu cách stamp không quá mức này. 0.1 s ở
# 0.15 m/s = 1.5 cm sai lệch điểm. ► TĂNG nếu log báo "TF ... s away from the scan stamp" dù TF vẫn chạy.
max_tf_gap: 0.2 # sim 27/11: TF lệch 0.134 s làm dừng lùi. Robot thật 0.1.
# [s] Mất dữ liệu ngắn (scan quá tuổi, TF lệch) thì đứng yên (lệnh 0) chờ dữ liệu mới tối đa chừng này rồi
# mới báo hỏng; có lại thì lùi/xoay tiếp. Không bao giờ chạy theo dữ liệu cũ. 0 = báo hỏng ngay như trước.
# ► Phải < timeout. TĂNG nếu sim chậm hay báo "lost the obstacle view" giữa chừng.
view_loss_timeout: 1.0
# [m] Quãng lùi.
# ► Chỉnh: TĂNG để ra xa vật hơn, đổi lại cần phía sau trống dài hơn nên hay phải xoay hơn.
backup_distance: 0.20
# [m/s] ĐỘ LỚN tốc độ lùi; dấu âm do plugin đặt. Trần 1.0.
# ► Chỉnh: GIẢM nếu lùi giật; TĂNG làm né nhanh hơn nhưng quãng phanh dài hơn.
backup_speed: 0.15
# [rad/s] ĐỘ LỚN tốc độ xoay. Trần 2.0.
# ► Chỉnh: GIẢM nếu góc thân quét quá nhanh cạnh người đứng gần.
rotate_speed: 0.5
# [m/s^2] Ramp gia tốc khi lùi.
# ► Chỉnh: GIẢM khi chở tải dễ đổ.
acc_lim_x: 0.3
# [rad/s^2] Ramp gia tốc khi xoay.
acc_lim_theta: 0.8
# [deg] Bước lấy mẫu hướng ứng viên khi tìm phía trống, trong (0, 90]. Hướng thắng lệch hướng
# hiện tại < 10 deg thì coi như đã quay ra phía trống: không xoay, trả thành công.
# ► Chỉnh: GIẢM (5) để chọn hướng mịn hơn, tốn CPU hơn lúc start.
heading_step_deg: 10.0
# [m] Biên an toàn, CHỈ cộng theo chiều chuyển động (cuối quãng lùi, cuối cung xoay), không nở
# ngang thân.
# ► Chỉnh: TĂNG cho dư hơn khi vật cản động; GIẢM để dễ lùi/xoay trong chỗ chật hơn.
motion_margin: 0.05
# [m] Một hướng chỉ được coi là "trống" khi đẩy footprint thẳng tới trước được ít nhất quãng này.
# ► Chỉnh: TĂNG để chỉ quay về chỗ thật thoáng (dễ trả lỗi hơn); GIẢM để chấp nhận khe hẹp hơn.
# Phải <= max_probe_distance.
min_free_distance: 0.30
# [m] Trần khi đo quãng trống của một hướng. Mọi hướng trống quá mức này là hoà nhau; khi hoà
# (chênh <= 0.05 m) evade chọn hướng phải xoay ít nhất.
# ► Chỉnh: TĂNG để phân biệt hành lang dài với chỗ chỉ trống vừa đủ (tốn CPU hơn lúc start).
max_probe_distance: 1.0
# [s] Lưới cuối, base ép. Xoay xa nhất ~pi / rotate_speed = 6.3 s; 2 lần + 2 s ≈ 15 s.
# ► Chỉnh: TĂNG nếu GIẢM rotate_speed hoặc backup_speed.
timeout: 15.0
debug:
# Log lựa chọn mỗi lần start: lùi, xoay (góc, hướng, quãng trống) hay đã quay ra phía trống.
# Lý do KHÔNG né được luôn được log; công tắc này không tắt được nó.
decision: true
# =================================================================================================
# 4. Bảng symbol -> thư viện cho Boost.DLL
#
@@ -321,6 +403,9 @@ RotateRecovery:
BackUpRecovery:
library_path: librecovery_core_back_up_recovery
EvadeRecovery:
library_path: librecovery_core_evade_recovery
DetourPathRecovery:
library_path: libsbpl_recovery
@@ -384,7 +469,13 @@ SBPLDetourPlanner:
# một lượt "realign"). Đặt `false` cho detour để tiết kiệm — detour chạy khi robot ĐANG BÁM plan
# nên heading thật đã xuôi theo tuyến. Chỉ để `true` nếu local planner có bước xoay tại chỗ đầu
# path (turn_around_priority).
free_start_heading: true
free_start_heading: false
# [bool] Gộp "quạt" xoay tại chỗ: chuỗi pose liên tiếp trùng vị trí (primitive xoay tại chỗ trong mprim) còn
# đúng MỘT pose. Đầu path giữ pose theo hướng đi; giữa path giữ một pose tại đỉnh với hướng đến (như góc gãy
# của lane_route); cuối path giữ pose cuối vì PRIEST lấy goal yaw từ pose cuối. Path chỉ quay tại chỗ giữ nguyên.
# ► true: controller không nhận chồng pose quay dần tại một điểm. false: path SBPL nguyên bản (mặc định C++ false).
collapse_inplace_turns: true
# [m/s] và [s] — dùng để quy quãng đường/góc thành CHI PHÍ thời gian, không phải giới hạn vận tốc
# thật của robot (giới hạn thật nằm ở local planner).
@@ -411,4 +502,4 @@ SBPLDetourPlanner:
# - Bỏ bước tiến 1 cell: 0.05 m tại góc 22.5 độ làm tròn thành (1,0) cell, tức hướng đi 0 độ
# trong khi heading 22.5 độ. `test_mprim_gen.py` chặn đúng ca này.
# ► Quay lại bộ cũ: đổi đúng dòng dưới về `unicycle_highcost_5cm.mprim`. File cũ vẫn nằm cạnh.
primitive_filename: /home/duongtd/T800_ws/src/AMR_T800/Test/sbpl_lattice_planner/matlab/mprim/diff_r106_tip3_5cm.mprim
primitive_filename: /home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/src/Algorithms/Packages/global_planners/sbpl_lattice_planner/matlab/mprim/diff_r106_tip3_5cm.mprim

View File

@@ -47,4 +47,4 @@ SBPLLatticePlanner:
# - Bỏ bước tiến 1 cell: 0.05 m tại góc 22.5 độ làm tròn thành (1,0) cell, tức hướng đi 0 độ
# trong khi heading 22.5 độ. `test_mprim_gen.py` chặn đúng ca này.
# ► Quay lại bộ cũ: đổi đúng dòng dưới về `unicycle_highcost_5cm.mprim`. File cũ vẫn nằm cạnh.
primitive_filename: /home/duongtd/T800_ws/src/AMR_T800/Test/sbpl_lattice_planner/matlab/mprim/diff_r106_tip3_5cm.mprim
primitive_filename: /home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/src/Algorithms/Packages/global_planners/sbpl_lattice_planner/matlab/mprim/diff_r106_tip3_5cm.mprim

View File

@@ -53,6 +53,9 @@ struct MoveBase2Config
*/
double planner_timeout = 5.0;
/// [s] Continuous global-costmap readiness wait; 0 disables the check (legacy behavior).
double costmap_ready_timeout = 10.0;
/**
* Watchdog (2026-09-11): thread riêng đọc bảng trạng thái thành phần, kết luận "treo" theo ngân
* sách từng hàng. `watchdog.planner_timeout` được chép từ @ref planner_timeout khi nạp.
@@ -158,7 +161,9 @@ struct MoveBase2Config
std::string docking_marker_profiles_error;
// --- EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — namespace con `env_monitor` ------------------------
EnvMonitorConfig env_monitor; ///< lõi quyết định (stall / unreachable / contact / ngân sách).
/// `env_monitor/enabled`. Lõi (phần chung + detector) do env_monitor_core::EnvMonitor::initialize() tự đọc; cờ này chỉ
/// để biết có phải kiểm env_sampling / env_logger hay không.
bool env_monitor_enabled = true;
EnvSamplingConfig env_sampling; ///< lấy mẫu ở cổng (nhịp, thân, hình học, quỹ đạo).
EnvLoggerConfig env_logger; ///< ghi JSONL cho replay/ML. Tắt mặc định.
/// Nhóm log `debug/env`: một dòng tóm tắt feature mỗi giây khi đang giám sát. Mặc định bật.

View File

@@ -25,7 +25,7 @@
#include <move_base2/core/navigation_request.h>
#include <move_base2/core/state_machine.h>
#include <move_base2/core/velocity_arbiter.h>
#include <move_base2/core/env_monitor.h>
#include <env_monitor_core/env_monitor.h>
#include <move_base2/io/env_logger.h>
#include <move_base2/ports/action_port.h>
#include <move_base2/ports/clock_port.h>
@@ -72,6 +72,12 @@ struct ControlLoopDeps
*/
EnvironmentPort* environment = nullptr;
/**
* Lõi EnvMonitor (gói env_monitor_core), đã `initialize()` từ YAML bởi host (NavigationRuntime) — non-owning.
* **Có thể null** — null, `enabled() == false` hoặc @ref environment null thì EnvMonitor tắt hoàn toàn.
*/
env_monitor_core::EnvMonitor* env_monitor = nullptr;
/**
* Bảng trạng thái thành phần (2026-09-11). **Có thể null** — null thì quiescence của
* CANCELLING/PAUSING chỉ dựa vào `PlannerPort::isPlanning()` và odom (hành vi pha 1a), recovery/
@@ -109,6 +115,9 @@ struct ControlLoopConfig
/// [s] Chu kỳ danh nghĩa, chỉ dùng cho dt của cycle ĐẦU TIÊN khi chưa có mốc thời gian trước đó.
double nominal_control_period = 0.05;
/// [s] Maximum continuous global-costmap wait; 0 disables the readiness check.
double costmap_ready_timeout = 10.0;
/// Công tắc log chẩn đoán. Xem `MoveBase2Config::debug_*` để biết từng nhóm in cái gì.
bool debug_state = true;
bool debug_plan = true;
@@ -160,7 +169,7 @@ struct ControlLoopConfig
// --- EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 ----------
EnvMonitorConfig env_monitor;
// Tham số lõi (phần chung + từng detector) do env_monitor_core đọc từ YAML; ở đây chỉ phần lấy mẫu của host.
EnvSamplingConfig env_sampling;
EnvLoggerConfig env_logger;
bool debug_env = true; ///< nhóm log `debug/env`: một dòng tóm tắt feature mỗi giây khi đang giám sát.
@@ -387,6 +396,14 @@ private:
* @brief EnvMonitor: lấy mẫu môi trường (nặng theo `check_period`, quỹ đạo mỗi cycle), chạy lõi, giữ
* verdict cho state machine và trọng tài của CYCLE NÀY. Gọi trước state machine.
*/
/// Báo EnvMonitor (nếu có) một lượt recovery vừa kết thúc.
void envRecoveryFinished(const robot::Time& now, env_monitor_core::EnvRecoveryOutcome outcome);
/// Nhãn trigger cho log: `collision (contact)`, `detector (intrusion)`; trigger riêng thì chỉ tên trigger.
std::string triggerLabel(const StateMachineOutput& output) const;
/// Behavior đang chạy thuộc một chuỗi `route_mode: sequence` của detector.
bool runningChain() const;
void updateEnvMonitor(const robot::Time& now, double dt, const robot_geometry_msgs::PoseStamped& robot_pose,
bool pose_available, bool costmap_stale);
/// @brief Quaternion có chuẩn hoá được không — goal hỏng phải bị từ chối ngay tại cửa.
@@ -417,7 +434,7 @@ private:
/// Trigger của behavior đang chạy. `StateMachineOutput::recovery_trigger` chỉ được điền ở cycle khởi động
/// (và khi trừ ngân sách), ở cycle tick nó là giá trị mặc định — đọc nó lúc kết thúc recovery là sai
/// (stand-down của kContact không bao giờ được vũ trang, run 6/9 16:30: 4 detour collision cùng chỗ → ABORT).
RecoveryTrigger running_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
int running_recovery_detector_ = -1; ///< detector (index detector_routes) có route đang chạy; -1 = trigger riêng
ActionFeedback action_feedback_ = ActionFeedback::kIdle;
/// Lý do action handler đưa ra cho lần tick vừa rồi; chỉ giữ khi tick đó HỎNG, xem
@@ -425,6 +442,8 @@ private:
std::string action_message_;
std::vector<robot_geometry_msgs::PoseStamped> latest_plan_;
/// Path mới nhất do một behavior trong chuỗi sequence nộp; áp khi cả chuỗi xong.
std::vector<robot_geometry_msgs::PoseStamped> chain_path_;
/// Tuyến tham chiếu của chặng — xem @ref orderPlan. Chỉ ghi từ kết quả của PlannerRunner.
std::vector<robot_geometry_msgs::PoseStamped> order_plan_;
bool planner_running_ = false;
@@ -453,8 +472,9 @@ private:
bool has_last_plan_applied_ = false;
// --- EnvMonitor -------------------------------------------------------------------------------
EnvMonitor env_monitor_;
EnvVerdict env_verdict_; ///< verdict của cycle này (vào state machine + trọng tài).
env_monitor_core::EnvNeeds env_needs_;
std::vector<std::pair<double, double>> env_footprint_scratch_;
env_monitor_core::EnvVerdict env_verdict_; ///< verdict của cycle này (vào state machine + trọng tài).
EnvGeometry env_geometry_; ///< mẫu nặng gần nhất (giữ giữa hai tick 5 Hz để log/ghi).
robot::Time last_env_heavy_;
bool has_last_env_heavy_ = false;

View File

@@ -48,7 +48,8 @@ enum class ComponentPhase : std::uint8_t
kBusy, ///< Đang làm việc.
kStopping, ///< Đã được bảo dừng (preempt/cancel) nhưng chưa thoát.
kPaused, ///< Đã xác nhận tạm dừng (chỉ action, pha 3).
kHung ///< Watchdog kết luận: bận quá ngân sách mà không nhích (pha 4).
kHung, ///< Watchdog kết luận: bận quá ngân sách mà không nhích (pha 4).
kWaitingForCostmap ///< Retaining the request until global costmap data is ready.
};
const char* toString(Component component);

View File

@@ -1,377 +0,0 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — lõi quyết định của EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md §2.3, P2).
*
* Thuần: không costmap, không TF, không log, không cấp phát sau `configure`. Vào là một @ref EnvSample
* mỗi control cycle (feature đã tính ở cổng bằng `grid_analysis`), ra là một @ref EnvVerdict: các cờ
* cho state machine đúng như PathMonitor cũ (`no_progress`, `path_blocked`, `collision`), lệnh phanh và
* bao tốc độ. Nhờ thuần nên kiểm được bằng bảng và replay được trên feature ghi lại.
*
* Triết lý (chốt 5/9/2026): local planner tự do né, recovery chỉ khi BẾ TẮC THẬT. Không có verdict
* "plan bị chắn". Ba verdict:
* - kStall — lệnh ≠ 0 mà `cost_to_go` (địa trắc tới điểm thoát + phần plan còn lại) không giảm.
* - kUnreachable — không còn đường trong cửa sổ tới điểm thoát, tĩnh, và xấu hơn lúc nhận plan.
* - kContact — thân sắp chạm trên quỹ đạo thật: phanh ngay, cờ chỉ khi tiếp xúc đứng yên.
*
* Author: DuongTD
*********************************************************************/
#ifndef MOVE_BASE2_CORE_ENV_MONITOR_H_
#define MOVE_BASE2_CORE_ENV_MONITOR_H_
#include <array>
#include <cstddef>
#include <limits>
#include <string>
#include <robot/time.h>
namespace move_base2
{
/**
* @struct EnvMonitorConfig
* @brief Tham số lõi. Đơn vị trong tên hoặc comment. Mọi ngưỡng số là GIÁ TRỊ KHỞI ĐIỂM rút từ hai bag
* sim 5/9/2026 (Test/docs/move_base2/ENV_MONITOR_PLAN.md §4.4); chốt lại bằng shadow/replay, không bằng tay.
*/
struct EnvMonitorConfig
{
bool enabled = true;
/// [s] Sau khi nhận plan mới (planner hoặc detour) không kết luận gì: mẫu cũ thuộc plan cũ.
double grace_after_new_plan = 1.0;
/**
* kStall — "planner đòi đi mà cost_to_go không giảm". Đi cờ `no_progress` -> trigger oscillation
* (trigger GỐC: cạn route là ABORT chặng), nên `action` mặc định "log" cho tới khi shadow đủ dài.
*/
struct Stall
{
bool enabled = true;
std::string action = "log"; ///< "log" = chỉ báo trong verdict; "recover" = giơ cờ.
double window_s = 4.0; ///< [s] cửa sổ đo eff.
/// [m] Hai mẫu nặng liên tiếp mà cost_to_go đổi quá (đây + quãng robot dịch) = mặt nạ free đổi liên thông (ô
/// nhấp nháy ở mép khe), không phải tiến/lùi: xoá cửa sổ đo, bắt đầu lại. Run 5/9 23:37: geo nhảy +3,2 m trong
/// 0,2 s, eff −2,7, detour oan. 0 = tắt.
double jump_reject = 1.0;
/// Cổng DỊCH CHUYỂN THỰC (6/9): "bế tắc thật" = robot không đi được đâu, không phải "không tiến theo plan".
/// Chỉ giơ cờ khi trong disp_window_s gần nhất robot dịch chuyển thực (khoảng cách đầu-cuối) < disp_min dù đã
/// lệnh >= disp_min_commanded. Né tự do luôn dịch chuyển -> không nổ; quần trong hộp 0,9 m (run 5/9 00:05,
/// 97 s) -> nổ sau ~window. Cửa sổ vị trí bắt đầu lại ở mỗi plan mới, thay cho ngân sách replan R3/R5 (đo
/// theo quãng đường nên đi vòng đốt ngân sách rất chậm, câm cờ đúng 97 s). disp_min = 0 -> tắt cổng, dùng lại
/// ngân sách replan như cũ.
double disp_window_s = 12.0;
double disp_min = 0.6; ///< [m]
double disp_min_commanded = 1.5; ///< [m]
/// [s] Cổng ĐỨNG YÊN: robot dịch chuyển thực < disp_min trong chừng này giây (không cần lệnh đủ) -> kẹt, kể cả
/// khi geodesic không đo được. Run 6/9 10:59: PRIEST bò 0,03–0,15 m/s tại chỗ 30 s (blocked_ahead cost 253, res
/// 1,6 chưa tới ngưỡng khai bất khả thi), lệnh tích luỹ 12 s chỉ 0,1–0,4 m nên cổng dịch chuyển câm; kUnreachable
/// mới gỡ ở 75 s. Thử trên 7 lượt: bắt đúng 2 ca quần tại chỗ, 0 lần ở 3 lượt sạch. 0 = tắt.
double idle_window_s = 25.0;
/// Cổng GIAM VÙNG: trong confine_window_s mọi vị trí nằm trong vòng bán kính < confine_radius quanh tâm của chúng,
/// và lệnh tích luỹ >= confine_cmd_factor x max(2 x bán kính đo được, disp_min) — đi nhiều mà không ra khỏi vùng
/// nhỏ = loanh quanh trong local minimum. Cổng dịch chuyển đo đầu–cuối nên mù với vòng bán kính > 0,3 m; cổng
/// đứng yên chỉ bắt gần như đứng. Replay 8 lượt 5–6/9: bắt 00:05 (101 s thay vì 206), 10:57 (27 s thay vì 75),
/// 23:37; 0 lần ở 5 lượt sạch. Hệ số lệnh chặn ca bò thẳng chậm sau người (2 m/20 s: bán kính 1 m, lệnh 2 m
/// < 1,5 x 2 m). confine_radius = 0 -> tắt. Chỉ hoạt động khi disp_min > 0.
double confine_window_s = 20.0;
double confine_radius = 1.2; ///< [m]
double confine_cmd_factor = 1.5; ///< [-]
double window_m = 1.5; ///< [m] hoặc theo lệnh tích luỹ — cái tới trước.
double min_commanded = 0.30; ///< [m] lệnh trong cửa sổ ít hơn = đang chờ, không đo.
double eff_on = 0.20; ///< [-] eff dưới đây là kẹt.
double eff_off = 0.50; ///< [-] trên đây mới xoá (hysteresis).
double confirm = 1.0; ///< [s] kẹt liên tục chừng này mới nổ.
double goal_zone = 0.6; ///< [m] gần goal hơn đây không đo.
double slip_on = 0.15; ///< [m/s] |v_cmd| - |v_meas| liên tục = kẹt vật lý. 0 = tắt.
double slip_time = 1.0; ///< [s]
double min_commanded_since_goal = 1.0; ///< [m] cổng đầu chặng (cắt nổ sớm 13,0 / 145,6 bag 1).
double retry_backoff = 3.0; ///< [s] sau một lượt recovery HỎNG không tích bằng chứng.
} stall;
/// kUnreachable — cờ `path_blocked` -> route path_blocked (cạn route chỉ KHOÁ, an toàn để bật).
struct Unreachable
{
bool enabled = true;
std::string action = "recover";
double static_on = 1.0; ///< [s] mất liên thông liên tục chừng này mới nổ.
double clean_start_margin = 0.20; ///< [m] edt_body_min tối thiểu để còn gọi replan được.
double retry_backoff = 2.0; ///< [s]
} unreachable;
/// kContact — phanh theo quỹ đạo thật; cờ `collision` -> route collision.
struct Contact
{
bool enabled = true;
std::string action = "recover";
int confirm_cycles = 2; ///< [cycle] chạm liên tục chừng này thì phanh.
double trigger_static_time = 1.0; ///< [s] phanh mà tiếp xúc còn đó chừng này mới giơ cờ.
double clean_start_margin = 0.20; ///< [m] dừng với thân còn cách vật ít nhất chừng này.
double brake_decel = 0.35; ///< [m/s^2] decel dùng cho quãng phanh và bao tốc độ.
double min_speed = 0.05; ///< [m/s] bao tốc độ không kẹp thấp hơn đây (thấp hơn = dừng).
/// [m/s] |v_cmd| và |v_đo| đều dưới đây mà monitor CHƯA phanh = robot đang xoay tại chỗ hoặc bò: đó là
/// chuyển động của controller, không phải bài toán quãng phanh -> không phanh, không cờ (cùng vai
/// `path_monitor/collision_min_speed` cũ). Shadow 5/9: ba lần "braking to zero" ngay đầu chặng khi
/// robot xoay ra khỏi vật kề mũi (v 0.00–0.07 m/s) đều là nổ oan kiểu này.
double min_check_speed = 0.10;
/// [m] Hysteresis cho "kề mũi": đã kề (d <= margin) thì còn kề tới khi d > margin + đây. Local planner
/// đổi quỹ đạo mỗi cycle nên d nhảy 0,08 <-> 0,25 m quanh margin (run 5/9 22:35): không có nó thì phanh
/// bật/nhả 4 lần/s và đồng hồ giơ cờ bị reset liên tục.
double release_hysteresis = 0.10;
/// [cycle] Nhả phanh (quỹ đạo sạch hoặc lùi xa) chỉ sau chừng này cycle liên tiếp không còn "sắp chạm".
int release_confirm_cycles = 4;
/// [m] Dư của bao tốc độ so với ngưỡng phanh: v_cap = sqrt(2a(d - margin - đây)), tối thiểu min_speed cho
/// tới d <= margin (= 0). 0 = bao đặt đúng biên phanh -> cứ kẹp xong là chớm "sắp chạm" (rung tiếp cận run
/// 5/9 22:58: 9/28 lần phanh < 0,3 s).
double envelope_margin = 0.10;
/// [m] Detour do CHÍNH cờ collision vừa xong mà robot dịch chưa tới đây và lại "sắp chạm" -> kContact ĐỨNG RA
/// (không phanh, không cờ, không bao) tới khi đi được standdown_travel hoặc quỹ đạo sạch: detour từ trong khe
/// là vô nghĩa, xoay là chạm (m1/m8 run 5/9 22:58 churn 3 detour rồi ABORT); mission 6 cùng lượt thoát được
/// đúng lúc guard "nhường controller". 0 = tắt.
double standdown_min_travel = 0.10;
double standdown_travel = 0.30; ///< [m] đứng ra chừng này quãng đường rồi vũ trang lại.
bool envelope = true; ///< bật bao tốc độ theo tiếp xúc trên quỹ đạo.
/// false = SHADOW: `brake`/`v_cap` chỉ được báo trong verdict, ControlLoop không đụng lệnh.
/// true = phanh và bao tốc độ tác động thật lên lệnh trước trọng tài. Lõi không dùng cờ này.
bool apply_command = false;
} contact;
/// Ngân sách replan theo quãng đường (R3 + R5) cho kStall và kUnreachable.
struct ReplanBudget
{
double min_travel = 1.5; ///< [m] sau detour thành công, im tới khi đi chừng này.
double escalate_factor = 2.0; ///< [-] replan lặp trong escalate_window_m thì nhân ngân sách.
double escalate_window_m = 10.0; ///< [m] đi chừng này không replan thì về min_travel.
/// [m] Trần của leo thang; 0 = không trần. Run 5/9 22:35: 4 detour PRIEST trong 10 m -> 1,5 -> 3 -> 6 -> 12 m,
/// kStall câm gần hết chặng.
double escalate_max = 6.0;
} replan;
bool validate(std::string& error) const;
std::string describe() const;
};
/**
* @struct EnvSample
* @brief Dữ liệu vào của một cycle. Phần "nặng" chỉ có nghĩa khi @ref geometry_valid (nhịp 5 Hz).
* NaN / +inf = không có; lõi không suy diễn từ giá trị thiếu.
*/
struct EnvSample
{
robot::Time now;
double dt = 0.0; ///< [s] từ cycle trước; 0 ở cycle đầu.
bool costmap_current = true; ///< costmap stale -> mọi kết luận hình học là quá khứ.
bool has_plan = false;
double robot_x = 0.0; ///< [m] pose robot, frame bất kỳ nhưng cố định (đo quãng đường).
double robot_y = 0.0;
double v_cmd = 0.0; ///< [m/s] lệnh SAU trọng tài của cycle trước.
double w_cmd = 0.0; ///< [rad/s]
double v_meas = std::numeric_limits<double>::quiet_NaN(); ///< [m/s] đo được; NaN = không có.
/// [m/s] lệnh controller MUỐN ở cycle trước, TRƯỚC bao tốc độ / phanh / trọng tài; NaN = không biết.
/// Cần cho cổng xoay của kContact: bao kẹp lệnh về 0 trong margin làm v_cmd = 0 dù controller vẫn đòi
/// đi — không có số này, cổng xoay coi đó là "đứng yên" và robot dừng câm không cờ.
double v_controller = std::numeric_limits<double>::quiet_NaN();
bool controller_valid = true; ///< controller cycle trước có ra lệnh không.
double d_goal = std::numeric_limits<double>::infinity(); ///< [m] Euclid tới goal.
bool geometry_valid = false; ///< các trường dưới đây vừa được tính ở tick này.
bool cost_conclusive = false; ///< costToGo kết luận được.
bool reachable = false; ///< có đường địa trắc tới T.
double cost_to_go = std::numeric_limits<double>::infinity(); ///< [m]
double edt_body_min = std::numeric_limits<double>::quiet_NaN(); ///< [m]
bool contact_conclusive = false; ///< sweep quỹ đạo kết luận được (mỗi cycle).
double traj_contact_dist = std::numeric_limits<double>::infinity(); ///< [m] dọc quỹ đạo.
};
/// Kết quả một lượt recovery mà lõi cần biết (không include recovery_core: chỉ ba ý nghĩa).
enum class EnvRecoveryOutcome
{
kSucceededWithPath, ///< detour_path nộp path mới -> ngân sách theo quãng đường.
kSucceeded, ///< behavior khác thành công (không đổi plan).
kFailed ///< hỏng -> retry_backoff.
};
/**
* @struct EnvVerdict
* @brief Kết quả một cycle. Cờ đầu là cái đưa vào `StateMachineInput` (đã qua action + cổng +
* ngân sách); phần chẩn đoán là số thô để log / ghi JSONL.
*/
struct EnvVerdict
{
bool no_progress = false; ///< kStall hiệu lực.
bool path_blocked = false; ///< kUnreachable hiệu lực.
bool collision = false; ///< kContact hiệu lực (cờ, không phải phanh).
bool brake = false; ///< Cycle này lệnh ra phải bằng 0.
double v_cap = std::numeric_limits<double>::infinity(); ///< [m/s] trần |v| cycle này; +inf = không kẹp.
bool stall_detected = false; ///< điều kiện kẹt đã đủ confirm, chưa xét action/cổng.
bool unreachable_detected = false;
bool contact_imminent = false; ///< chạm trong quãng phanh ở cycle này.
bool contact_standdown = false; ///< kContact đang đứng ra sau detour từ chính chỗ này (nhường controller).
bool cost_jump = false; ///< tick này cost_to_go nhảy quá jump_reject: cửa sổ stall vừa bị xoá.
bool stall_muted = false; ///< detected nhưng bị cổng/ngân sách/backoff/grace giữ lại.
double net_disp = std::numeric_limits<double>::quiet_NaN(); ///< [m] dịch chuyển thực trong disp_window_s (NaN = chưa đủ mẫu).
bool wandering = false; ///< cổng dịch chuyển đã mở: lệnh đủ mà không đi được đâu.
bool idle = false; ///< cổng đứng yên đã mở: không dịch chuyển suốt idle_window_s.
bool confined = false; ///< cổng giam vùng đã mở: đi nhiều mà ở trong vòng nhỏ suốt confine_window_s.
double region_radius = std::numeric_limits<double>::quiet_NaN(); ///< [m] bán kính vùng đã ở trong confine_window_s.
bool unreachable_muted = false;
double eff_geo = std::numeric_limits<double>::quiet_NaN(); ///< [-] eff của cửa sổ gần nhất.
double cmd_window = 0.0; ///< [m] lệnh tích luỹ trong cửa sổ đó.
double brake_dist = 0.0; ///< [m]
double replan_budget_left = 0.0; ///< [m] còn phải đi bao xa mới hết mute sau replan (0 = không mute).
const char* event = ""; ///< Sườn sự kiện của cycle này ("" = không có). Dùng để log một lần.
};
/**
* @class EnvMonitor
* @brief Lõi thuần. Không thread-safe; chỉ control thread gọi.
*/
class EnvMonitor
{
public:
EnvMonitor() = default;
bool configure(const EnvMonitorConfig& config, std::string& error);
bool configured() const
{
return configured_;
}
const EnvMonitorConfig& config() const
{
return config_;
}
/// @brief Về trạng thái ban đầu (rời kControlling, huỷ chặng). Giữ config.
void reset();
/// @brief Chặng mới được nhận: đặt lại mọi ngân sách, mốc lệnh đầu chặng.
void onGoalAccepted(const robot::Time& now);
/// @brief Plan mới được áp (planner hay detour): xoá cửa sổ, bắt đầu grace, chờ baseline liên thông.
void onPlanApplied(const robot::Time& now);
/// @brief Một lượt recovery vừa kết thúc (trước khi plan mới, nếu có, được áp).
/// @param from_contact recovery này do cờ collision của chính monitor gọi (trigger kCollision).
void onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome, bool from_contact = false);
/// @brief Một cycle. Gọi SAU khi các feature của cycle đã có, TRƯỚC state machine.
EnvVerdict update(const EnvSample& sample);
// --- soi trạng thái (test, log) ---
double commandedTotal() const
{
return cmd_accum_;
}
double travelledTotal() const
{
return travel_total_;
}
double replanBudget() const
{
return budget_travel_;
}
private:
struct HeavySample
{
robot::Time t;
double cost = 0.0; ///< [m]
double cmd = 0.0; ///< [m] cmd_accum_ lúc lấy mẫu.
};
/// 64 mẫu x 0,2 s = 12,8 s lịch sử, dư cho window_s 4 s kể cả khi nhịp nặng chậm lại.
static constexpr std::size_t kRing = 64;
struct PosSample
{
robot::Time t;
double x = 0.0;
double y = 0.0;
double cmd = 0.0; ///< [m] cmd_accum_ lúc lấy mẫu.
};
/// 128 mẫu x 0,2 s = 25,6 s, dư cho disp_window_s 12 s.
static constexpr std::size_t kPosRing = 192; ///< 192 x 0,2 s = 38 s, đủ idle_window_s 25 s.
bool oldestPos(const robot::Time& now, double window_s, PosSample& out) const;
void clearWindow();
void clearPosWindow();
bool oldestInWindow(const robot::Time& now, HeavySample& out) const;
void updateStall(const EnvSample& s, EnvVerdict& v);
void updateUnreachable(const EnvSample& s, EnvVerdict& v);
void updateContact(const EnvSample& s, EnvVerdict& v);
EnvMonitorConfig config_;
bool configured_ = false;
// Tích luỹ
double cmd_accum_ = 0.0; ///< [m] Σ|v_cmd|·dt
double travel_total_ = 0.0; ///< [m] odometer từ pose
bool has_last_pose_ = false;
double last_x_ = 0.0;
double last_y_ = 0.0;
// Mốc chặng / plan
bool has_goal_ = false;
double cmd_at_goal_ = 0.0;
bool has_plan_time_ = false;
robot::Time plan_time_;
// Cửa sổ mẫu nặng
std::array<HeavySample, kRing> ring_{};
std::size_t ring_head_ = 0;
std::size_t ring_count_ = 0;
std::array<PosSample, kPosRing> pos_ring_{};
std::size_t pos_head_ = 0;
std::size_t pos_count_ = 0;
bool wandering_ = false;
bool idle_ = false; ///< cổng đứng yên đang mở (xem Stall::idle_window_s).
bool confined_ = false; ///< cổng giam vùng đang mở (xem Stall::confine_radius).
double region_radius_ = std::numeric_limits<double>::quiet_NaN();
double net_disp_ = std::numeric_limits<double>::quiet_NaN();
// kStall
bool stall_seen_ = false;
robot::Time stall_since_;
bool stall_fired_ = false;
bool slip_seen_ = false;
robot::Time slip_since_;
bool has_stall_backoff_ = false;
robot::Time stall_backoff_until_;
// kUnreachable
bool baseline_pending_ = true; ///< chưa có mẫu kết luận nào từ plan hiện tại.
bool baseline_unreachable_ = false; ///< plan đã không liên thông ngay từ lúc nhận (R2: không cãi SBPL).
bool unreach_seen_ = false;
robot::Time unreach_since_;
bool unreach_fired_ = false;
bool has_unreach_backoff_ = false;
robot::Time unreach_backoff_until_;
// kContact
int contact_streak_ = 0;
int release_streak_ = 0; ///< cycle liên tiếp không "sắp chạm" trong khi đang phanh.
bool has_prev_heavy_ = false; ///< mẫu nặng trước cho bộ lọc nhảy cost_to_go.
double prev_heavy_cost_ = 0.0;
double prev_heavy_travel_ = 0.0;
bool braking_ = false;
bool contact_close_ = false; ///< tiếp xúc trong clean_start_margin (bất kể tốc độ).
robot::Time close_since_;
bool contact_fired_ = false;
bool detour_from_contact_ = false; ///< detour gần nhất là do cờ collision; mốc quãng đường ở dưới.
double detour_mark_travel_ = 0.0; ///< [m]
bool standdown_ = false; ///< đang đứng ra (xem Contact::standdown_min_travel).
double standdown_mark_travel_ = 0.0; ///< [m]
int standdown_clean_streak_ = 0; ///< cycle quỹ đạo sạch liên tiếp trong khi đứng ra.
// Ngân sách replan (R3/R5)
bool has_replan_mark_ = false;
double replan_mark_travel_ = 0.0; ///< odometer tại lần detour thành công gần nhất.
double budget_travel_ = 0.0; ///< [m] ngân sách hiện hành (= min_travel, nhân factor khi lặp).
bool has_prev_replan_ = false;
double prev_replan_travel_ = 0.0;
};
} // namespace move_base2
#endif // MOVE_BASE2_CORE_ENV_MONITOR_H_

View File

@@ -11,6 +11,7 @@
#include <array>
#include <cstddef>
#include <cstdint>
#include <string>
#include <robot/time.h>
@@ -28,6 +29,7 @@ enum class PlannerFeedback
{
kIdle, ///< Chưa có tin gì mới kể từ cycle trước.
kBusy, ///< Đang lập plan, chưa có kết quả.
kWaitingForCostmap, ///< Goal retained while the global costmap becomes current.
kPlanReady, ///< Có plan mới, không rỗng, sẵn sàng đẩy xuống controller.
kFailed ///< Lần lập plan gần nhất thất bại.
};
@@ -60,6 +62,19 @@ enum class ActionFeedback
kCancelled ///< Handler đã dừng thiết bị an toàn sau cancel (pha 3). Chỉ gặp trong CANCELLING/PAUSING.
};
/**
* @struct DetectorRoute
* @brief Route recovery của một detector EnvMonitor (Test/docs/move_base2/ENV_DETECTOR_PLUGINS_PROMPT.md §4).
*/
struct DetectorRoute
{
std::string name; ///< tên detector: log, và báo lại EnvMonitor route của ai vừa chạy xong.
std::vector<std::size_t> route; ///< index behavior trong registry. Rỗng = cờ không được vũ trang.
bool lock_on_exhausted = true; ///< cạn route: true = khoá, bám tiếp plan (dự báo); false = ABORT chặng.
bool sequence = false; ///< `route_mode: sequence` — một lần nổ chạy cả route.
RecoveryTrigger trigger = RecoveryTrigger::kDetector; ///< nhãn cho log và recovery_core (tên route cũ -> trigger cũ).
};
/**
* @struct StateMachineConfig
* @brief Tham số điều khiển hành vi chuyển state.
@@ -146,9 +161,19 @@ struct StateMachineConfig
/// Cho phép chạy recovery hay không. false = mọi lỗi dẫn thẳng tới ABORTED.
bool recovery_enabled = true;
bool recovery_resume_enabled = false; ///< [bool] Bật thử controller trong recovery đứng yên.
std::vector<std::string> recovery_resume_behaviors = {"detour_path"}; ///< [tên] Behavior được thử.
int recovery_resume_confirm_cycles = 3; ///< [cycle] Số lệnh chuyển động liên tiếp cần xác nhận.
double recovery_resume_min_speed = 0.05; ///< [m/s] Độ lớn tốc độ tiến/lùi tối thiểu của lệnh thử.
int recovery_resume_max_per_leg = 3; ///< [lần/leg] Trần số lần huỷ recovery trong một chặng.
/// Route đã resolve của từng @ref RecoveryTrigger. Rỗng = mọi trigger dùng list legacy chung.
RecoveryRoutes recovery_routes;
/// Một route cho MỖI detector EnvMonitor, đúng thứ tự detector (bit i của StateMachineInput::detector_fired).
/// Tối đa 32. Rỗng = không detector nào leo thang được recovery.
std::vector<DetectorRoute> detector_routes;
/**
* @brief Kiểm miền giá trị.
* @param[out] error Mô tả tham số sai; chỉ được ghi khi hàm trả false.
@@ -190,8 +215,10 @@ struct StateMachineInput
bool emergency = false;
PlannerFeedback planner = PlannerFeedback::kIdle;
bool planner_costmap_wait_finished = false;
ControllerFeedback controller = ControllerFeedback::kIdle;
RecoveryFeedback recovery = RecoveryFeedback::kIdle;
bool recovery_probe_moving = false; ///< Lệnh thử hợp lệ có |linear.x| đạt ngưỡng [m/s].
ActionFeedback action = ActionFeedback::kIdle;
/**
@@ -252,28 +279,15 @@ struct StateMachineInput
bool action_terminal = true;
/**
* Tuyến phía trước bị chắn (EnvMonitor kUnreachable: không còn đường trong cửa sổ tới điểm thoát, đã
* tĩnh đủ `static_on`).
* Bit i = detector thứ i của @ref StateMachineConfig::detector_routes (thứ tự `env_monitor/detectors`) đòi
* recovery cycle này. Thay cho bốn cờ cố định cũ (`collision`, `path_blocked`, `off_path`, `no_progress`).
*
* Khác mọi cờ khác trong struct này: nó là **dự báo**, không phải báo hỏng. Controller vẫn ra
* lệnh bình thường, plan vẫn hợp lệ — chỉ là đi tiếp thì sẽ tắc. Bên gọi chịu trách nhiệm mọi
* guard (profile, costmap còn hạn, debounce, route có tồn tại không); state machine chỉ tin cờ.
* Detector `on_exhausted: lock` là **dự báo**: controller vẫn ra lệnh, plan vẫn hợp lệ — xét TRƯỚC controller,
* theo thứ tự danh sách (mặc định contact > unreachable, như collision > path_blocked cũ); cạn route thì khoá
* tới khi robot đi được `oscillation_distance`. Detector `abort` (stall) chỉ xét khi controller ra lệnh hợp lệ;
* cạn route là ABORT. Bên gọi chịu debounce/mode/profile; state machine chỉ tin bit.
*/
bool path_blocked = false;
/// Robot đã lệch khỏi plan đang chạy quá ngưỡng. Cùng quy ước với @ref path_blocked. Từ 6/9/2026 không
/// còn nguồn cấp (phép đo 2 của PathMonitor cũ đã xoá); giữ cổng cho hợp đồng route/khoá và test.
bool off_path = false;
/// EnvMonitor kContact: thân sắp chạm vật cản thật trên quỹ đạo local planner, kề mũi tĩnh đủ lâu.
/// Cùng quy ước với @ref path_blocked (dự báo, route riêng `collision`, cạn route thì khoá).
/// Thắng cả path_blocked lẫn off_path khi cùng đúng: gần nhất thì xử lý trước.
bool collision = false;
/// EnvMonitor kStall: planner đòi đi mà robot không đi được đâu (cổng dịch chuyển thực mở).
/// Đi đường kOscillation — trigger GỐC — nên cạn route là ABORT hợp lệ, không rơi vào bẫy trigger
/// giám sát bị khoá rồi đứng im. Bên gọi chịu debounce/route/mode; state machine chỉ tin cờ.
bool no_progress = false;
std::uint32_t detector_fired = 0;
/**
* Họ output của behavior sẽ chạy / đang chạy ở cycle này.
@@ -311,6 +325,7 @@ struct StateMachineOutput
bool start_recovery = false; ///< Khởi động behavior @ref recovery_index với @ref recovery_trigger.
bool tick_recovery = false; ///< Gọi update() của behavior đang chạy.
bool cancel_recovery = false; ///< Yêu cầu behavior đang chạy dừng.
bool recovery_resumed = false; ///< Huỷ recovery vì controller có lệnh trở lại.
bool start_action = false; ///< D8: khởi động action thứ @ref action_index của yêu cầu hiện tại.
bool tick_action = false; ///< D8: gọi update() của action đang chạy.
@@ -329,6 +344,16 @@ struct StateMachineOutput
/// Chỉ có nghĩa khi @ref start_recovery — behavior nào cần khởi động và vì lý do gì.
std::size_t recovery_index = 0;
RecoveryTrigger recovery_trigger = RecoveryTrigger::kPlanningFailed;
/// Index trong StateMachineConfig::detector_routes của detector có route vừa khởi động / bị khoá; -1 = trigger
/// riêng của state machine (planning_failed, controlling_failed, oscillation_timeout).
int recovery_detector = -1;
/// `route_mode: sequence`: behavior vừa start là phần TIẾP của chuỗi đang chạy (không phải một lượt mới).
bool recovery_chain_continues = false;
/// Chuỗi sequence vừa chạy xong ở cycle này (không bị huỷ); ba cờ dưới là kết cục của CẢ chuỗi.
bool recovery_chain_finished = false;
bool recovery_chain_has_path = false; ///< ít nhất một behavior trong chuỗi nộp path mới.
bool recovery_chain_last_failed = false; ///< behavior cuối của chuỗi trả kFailed.
/**
* Debug route recovery tại cycle này. Có nghĩa khi @ref start_recovery hoặc khi terminal reason là
@@ -421,6 +446,12 @@ public:
return config_;
}
/// @brief Cho phép thử resume khi tính năng bật và quota [lần/leg] còn.
bool recoveryResumeAvailable() const
{
return config_.recovery_resume_enabled && recovery_resumes_this_leg_ < config_.recovery_resume_max_per_leg;
}
/// @brief Index behavior đang chạy / sẽ chạy ở lần recovery kế tiếp. Dùng để assert trong test.
std::size_t nextRecoveryIndex() const
{
@@ -458,17 +489,21 @@ private:
/**
* @brief Vào recovery nếu còn behavior, ngược lại kết thúc bằng kAborted.
* @param trigger Lý do vào recovery.
* @param trigger Trigger riêng của state machine (planning_failed, controlling_failed, oscillation).
*/
/// @brief Trigger này thuộc nhóm GIÁM SÁT TUYẾN (dự báo) chứ không phải báo hỏng?
static bool isMonitorTrigger(RecoveryTrigger trigger);
/// @brief Khoá một trigger giám sát tuyến tới khi có tiến độ; báo cho bên gọi log một dòng.
void suppressMonitorTrigger(RecoveryTrigger trigger, StateMachineOutput& out);
void escalateToRecovery(RecoveryTrigger trigger, const robot::Time& now, const char* reason,
StateMachineOutput& out);
/// @brief Leo thang bằng route của detector @p index (StateMachineConfig::detector_routes).
void escalateDetector(std::size_t index, const robot::Time& now, StateMachineOutput& out);
/// @brief Chung cho hai đường trên: cursor ô @p slot; cạn route thì khoá ô (@p lock, dự báo) hoặc ABORT.
void escalate(std::size_t slot, const std::vector<std::size_t>& route, RecoveryTrigger trigger, bool lock,
int detector, const robot::Time& now, const char* reason, StateMachineOutput& out);
/// @brief Route của lượt recovery đang chạy.
const std::vector<std::size_t>& activeRoute() const;
/// @brief Vào state terminal và bật cờ báo kết quả đúng một lần.
/**
* @brief Nhận yêu cầu đang chờ và đưa máy vào state chạy tương ứng.
@@ -512,10 +547,6 @@ private:
/// Mọi đường ra của @ref update đều phải đi qua đây.
void applyInvariants(const StateMachineInput& in, StateMachineOutput& out);
/// Cursor của route cho @p trigger trong request hiện hành.
std::size_t& recoveryRouteCursor(RecoveryTrigger trigger);
const std::size_t& recoveryRouteCursor(RecoveryTrigger trigger) const;
StateMachineConfig config_;
bool initialized_ = false;
@@ -531,6 +562,8 @@ private:
bool sensor_stale_active_ = false; ///< Đang trong chuỗi stale (sensor_stale_since_ có nghĩa).
std::size_t recovery_index_ = 0;
int recovery_resume_cycles_ = 0;
int recovery_resumes_this_leg_ = 0;
RecoveryTrigger active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
/**
@@ -550,13 +583,19 @@ private:
*/
NavigationState state_before_recovery_ = NavigationState::kPlanning;
/// Một cursor cho MỖI trigger: mỗi nguyên nhân có ngân sách recovery riêng. Thứ tự khớp
/// @ref RecoveryTrigger.
std::array<std::size_t, 6> recovery_route_cursors_{{ 0, 0, 0, 0, 0, 0 }};
/// Một cursor cho MỖI nguyên nhân: mỗi nguyên nhân có ngân sách recovery riêng. Ô 0..2 = planning_failed,
/// controlling_failed, oscillation (trigger riêng của state machine); ô 3 + i = detector i.
std::vector<std::size_t> recovery_route_cursors_;
/// Ô của lượt recovery đang chạy (cùng đánh số với @ref recovery_route_cursors_).
std::size_t active_slot_ = 0;
/// Lượt recovery đang chạy là một chuỗi `route_mode: sequence`: vị trí trong route, và đã có path mới chưa.
bool chain_active_ = false;
std::size_t chain_pos_ = 0;
bool chain_has_path_ = false;
/**
* Trigger GIÁM SÁT TUYẾN đang bị khoá (contract 2026-08-05e). Cùng thứ tự với
* @ref recovery_route_cursors_; chỉ ba ô kPathBlocked/kOffPath/kCollision từng được bật.
* @ref recovery_route_cursors_; chỉ ô của detector `on_exhausted: lock` từng được bật.
*
* `path_blocked`/`off_path` là DỰ BÁO, không phải báo hỏng: plan vẫn hợp lệ và controller vẫn ra
* lệnh được. Hết đường vòng thì robot BÁM TIẾP plan cũ chứ không ABORT — lưới an toàn thật là
@@ -564,15 +603,15 @@ private:
* lại để monitor không bắn liên tục: mỗi lượt detour tốn vài trăm ms SBPL trên control thread.
* Mở khoá khi robot đi được quá `oscillation_distance` — cùng mốc tiến độ đã reset cursor (Q1-C).
*/
std::array<bool, 6> monitor_trigger_suppressed_{{ false, false, false, false, false, false }};
std::vector<char> monitor_trigger_suppressed_;
/**
* Mốc của `recovery_reset_min_travel`. Ghi tại lần recovery thành công + path mới gần nhất; xoá
* khi origin đo quãng đường được đặt lại (yêu cầu mới, hoặc đi quá oscillation_distance) vì lúc
* đó `travelled_since_oscillation_reset` về 0 và hiệu số với mốc cũ sẽ âm.
* Mốc của `recovery_reset_min_travel`, ghi khi recovery có path mới được nạp lại ngân sách. Xoá
* khi nhận yêu cầu mới hoặc đi đủ `oscillation_distance`; khi reset origin do recovery hoặc
* resume thì chuyển mốc sang origin mới để giữ quãng đã đi. Mốc có thể âm sau khi chuyển.
*/
bool has_path_reset_mark_ = false;
double travel_at_last_path_reset_ = 0.0; ///< [m] travelled_since_oscillation_reset tại mốc đó.
double travel_at_last_path_reset_ = 0.0; ///< [m] mốc theo origin hiện tại, có thể âm.
int planning_retries_ = 0;
/// D8 — hình dạng của yêu cầu hiện tại, chốt tại cycle nhận yêu cầu từ StateMachineInput.

View File

@@ -22,7 +22,7 @@
#include <robot/time.h>
#include <move_base2/core/env_monitor.h>
#include <env_monitor_core/env_monitor.h>
#include <move_base2/ports/environment_port.h>
namespace move_base2
@@ -57,7 +57,7 @@ public:
}
/// @brief Một dòng JSON. @p geometry có thể null (tick nhẹ). @p state là tên state machine.
void record(const robot::Time& now, const EnvSample& sample, const EnvVerdict& verdict,
void record(const robot::Time& now, const env_monitor_core::EnvSample& sample, const env_monitor_core::EnvVerdict& verdict,
const EnvGeometry* geometry, const char* state, std::uint64_t mission_id,
bool used_local_plan);

View File

@@ -107,6 +107,7 @@ public:
tf_ = tf;
}
bool sampleFootprint(std::vector<std::pair<double, double>>& out) override;
void refresh() override;
bool sampleGeometry(const EnvGeometryRequest& request, EnvGeometry& out) override;
bool sweepTrajectory(const EnvTrajectoryRequest& request, SweepResult& out,
@@ -396,6 +397,8 @@ private:
PlannerRunner planner_;
ControllerRunner controller_;
RecoveryRunner recovery_;
/// Lõi EnvMonitor + detector plugin, nạp từ YAML ở @ref buildRunners. ControlLoop giữ con trỏ (non-owning).
env_monitor_core::EnvMonitor env_monitor_;
ActionRunner action_;
MissionAdapterBridge mission_;

View File

@@ -10,6 +10,7 @@
#define MOVE_BASE2_NAVIGATION_SERVER_H_
#include <atomic>
#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
@@ -60,6 +61,8 @@ public:
/**
* @brief Nạp cấu hình và các cổng cho control loop.
* @warning Các cổng trong deps là non-owning: bên cấp phải giữ chúng sống tới khi control
* thread đã được dừng và join, kể cả khi dựa vào destructor của NavigationServer.
* @param[out] error Lý do không cấu hình được.
*/
bool configureLoop(const ControlLoopConfig& config, const ControlLoopDeps& deps,
@@ -423,6 +426,10 @@ private:
/// Bảo vệ dữ liệu sensor và footprint: host ghi từ thread của nó, control loop đọc.
mutable std::mutex data_mutex_;
/// Latest arrival order per stored static-map topic; guarded by data_mutex_.
std::map<std::string, std::uint64_t> static_map_sequences_;
std::uint64_t next_static_map_sequence_ = 0;
std::vector<robot_geometry_msgs::Point> footprint_;
bool footprint_pending_ = false;
std::map<std::string, robot_sensor_msgs::DepthCameraData::ConstPtr> depth_camera_data_;

View File

@@ -24,6 +24,7 @@
#include <robot_geometry_msgs/PoseStamped.h>
#include <robot_nav_2d_msgs/Path2D.h>
#include <env_monitor_core/env_types.h>
#include <move_base2/core/grid_analysis.h>
#include <move_base2/core/navigation_request.h>
@@ -132,6 +133,13 @@ public:
return false;
}
/// @brief Unpadded footprint in the base frame; false means unavailable.
virtual bool sampleFootprint(std::vector<std::pair<double, double>>& out)
{
(void)out;
return false;
}
/// @brief Thân robot từ footprint KHÔNG đệm của costmap. false = không có.
virtual bool robotBodyExtents(double& front, double& rear, double& side) const
{

View File

@@ -108,6 +108,12 @@ public:
/// @brief Có lượt lập plan nào đang chạy không.
virtual bool isPlanning() const = 0;
/// Configure the global readiness wait before accepting requests. Zero keeps legacy behavior.
virtual void setCostmapReadyTimeout(double /*seconds*/) {}
/// Atomically sample the wait and consume the completion event since the previous sample.
virtual bool costmapWaitState(bool& finished) { finished = false; return false; }
/**
* @brief Lấy kết quả nếu đã có. Không chặn.
*

View File

@@ -11,6 +11,8 @@
#include <cstddef>
#include <string>
#include <map>
#include <string>
#include <vector>
#include <robot_geometry_msgs/PoseStamped.h>
@@ -42,7 +44,10 @@ enum class RecoveryTrigger
/// local planner, trong `collision_stop_distance`. Cùng họ dự báo với kPathBlocked nhưng là một
/// ngăn riêng: nổ khi đã sát vật (0.2 m) chứ không phải 3 m trước, nên cách xử lý (lùi trước
/// khi lập lại đường) và ngân sách route phải tách khỏi kPathBlocked.
kCollision
kCollision,
/// Route của một detector EnvMonitor có tên route không thuộc bốn tên cũ ở trên (ví dụ `intrusion`). Detector dùng
/// tên cũ (`oscillation`, `path_blocked`, `off_path`, `collision`) vẫn báo trigger cũ để log không đổi.
kDetector
};
const char* toString(RecoveryTrigger trigger);
@@ -72,10 +77,19 @@ struct RecoveryRoutes
/// Route của kCollision (Phép đo 3). Rỗng = guard va chạm KHÔNG được vũ trang (cùng quy ước).
std::vector<std::size_t> collision;
/// Route khai thêm trong `recovery/routes` ngoài sáu tên trên (route theo detector, ví dụ `intrusion`).
std::map<std::string, std::vector<std::size_t>> named;
const std::vector<std::size_t>& forTrigger(RecoveryTrigger trigger) const;
/// @brief Route theo tên: sáu tên cố định hoặc @ref named. nullptr = không có route tên đó.
const std::vector<std::size_t>* find(const std::string& name) const;
/// @brief Ba route GỐC đều rỗng — dấu hiệu config dùng schema legacy (không có khoá `routes`).
bool empty() const;
/// @brief Schema legacy (@ref empty): ba route gốc thử toàn bộ @p behavior_count behavior theo thứ tự registry.
void fillLegacy(std::size_t behavior_count);
};
/**

View File

@@ -11,6 +11,7 @@
#define MOVE_BASE2_RUNNERS_PLANNER_RUNNER_H_
#include <condition_variable>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
@@ -38,6 +39,15 @@ class Costmap2DROBOT;
namespace move_base2
{
/// Decision for a continuous readiness wait. A zero timeout preserves legacy planning behavior.
enum class CostmapReadyDecision { kPlan, kWait, kTimeout };
inline CostmapReadyDecision costmapReadyDecision(bool ready, double elapsed, double timeout)
{
if (timeout == 0.0 || ready)
return CostmapReadyDecision::kPlan;
return elapsed >= timeout ? CostmapReadyDecision::kTimeout : CostmapReadyDecision::kWait;
}
/**
* @class PlannerRunner
* @brief Nạp và chạy global planner thế hệ 1 (`robot_nav_core::BaseGlobalPlanner`) qua Boost.DLL,
@@ -177,6 +187,8 @@ public:
const robot_protocol_msgs::Order* order, std::uint64_t tag) override;
bool isPlanning() const override;
void setCostmapReadyTimeout(double seconds) override;
bool costmapWaitState(bool& finished) override;
bool pollPlan(PlanResult& result) override;
@@ -268,6 +280,15 @@ private:
bool running_ = false; ///< Thread đang chạy plugin.
bool discard_ = false; ///< Lượt đang chạy đã bị huỷ — vứt kết quả khi nó về.
bool has_result_ = false;
double costmap_ready_timeout_ = 10.0; ///< [s], protected by mutex_.
bool waiting_for_costmap_ = false;
bool costmap_wait_finished_ = false;
// Written only by the planner thread; throttle a persistent outage across failed attempts.
bool costmap_wait_problem_active_ = false;
std::chrono::steady_clock::time_point last_costmap_wait_log_;
std::chrono::steady_clock::time_point last_costmap_timeout_log_;
std::string costmap_stale_names_;
bool costmap_stale_names_reserved_ = false;
robot_nav_core::BaseGlobalPlanner* active_ = nullptr; ///< Non-owning, trỏ vào @ref planners_.
/**

View File

@@ -24,6 +24,7 @@
namespace robot_costmap_2d { class Costmap2DROBOT; }
namespace tf3 { class BufferCore; }
namespace robot_sensor_ports { class SensorReader; }
namespace move_base2
{
@@ -71,6 +72,9 @@ public:
/// TF buffer dùng chung của runtime, cho behavior cần đổi frame (họ path). Có thể null.
tf3::BufferCore* tf = nullptr;
/// Kho sensor dùng chung, cho behavior đọc scan thô (EvadeRecovery). Có thể null.
const robot_sensor_ports::SensorReader* sensors = nullptr;
};
RecoveryRunner() = default;

View File

@@ -16,7 +16,7 @@
-->
<launch>
<arg name="world" default="maze" doc="maze | warehouse | sehc | empty" />
<arg name="robot_type" default="T800" />
<arg name="robot_type" default="hook_150" />
<arg name="gui" default="true" doc="false = chạy gzserver headless" />
<arg name="rviz" default="true" />
<!-- Node robot_depth_image_proc. KHÔNG cần khi `use_depth_image_input: true` (mặc định):

View File

@@ -69,9 +69,9 @@
<build_depend>yaml-cpp</build_depend>
<run_depend>yaml-cpp</run_depend>
<!-- Chỉ dùng cho test: bộ fake và scenario runner dùng chung. -->
<build_depend>nav_test_harness</build_depend>
<run_depend>nav_test_harness</run_depend>
<!-- Chỉ dùng cho test: bộ fake và scenario runner dùng chung. Gói chỉ có trên máy dev, nên chỉ
là test_depend; CMake chỉ find_package nó khi bật BUILD_MOVE_BASE2_TESTS. -->
<test_depend>nav_test_harness</test_depend>
<build_depend>recovery_core</build_depend>
<run_depend>recovery_core</run_depend>
@@ -86,6 +86,10 @@
<build_depend>action_core</build_depend>
<run_depend>action_core</run_depend>
<!-- Lõi EnvMonitor: ControlLoop gom feature, gọi lõi và nối verdict vào state machine. -->
<build_depend>env_monitor_core</build_depend>
<run_depend>env_monitor_core</run_depend>
<!-- Kho cảm biến THÔ dùng chung: action handler và local planner đọc qua cổng của gói này. -->
<build_depend>robot_sensor_ports</build_depend>
<run_depend>robot_sensor_ports</run_depend>

View File

@@ -49,6 +49,8 @@ const char* toString(ComponentPhase phase)
return "paused";
case ComponentPhase::kHung:
return "hung";
case ComponentPhase::kWaitingForCostmap:
return "waiting_for_costmap";
}
return "unknown";
}

View File

@@ -59,6 +59,31 @@ void readString(robot::NodeHandle& nh, const std::string& key, std::string& valu
nh.param(key, value, value);
}
void readRecoveryResume(robot::NodeHandle& nh, StateMachineConfig& config)
{
const StateMachineConfig defaults;
readBool(nh, "recovery_resume_enabled", config.recovery_resume_enabled);
nh.param("recovery_resume_behaviors", config.recovery_resume_behaviors, defaults.recovery_resume_behaviors);
readInt(nh, "recovery_resume_confirm_cycles", config.recovery_resume_confirm_cycles);
readDouble(nh, "recovery_resume_min_speed", config.recovery_resume_min_speed);
readInt(nh, "recovery_resume_max_per_leg", config.recovery_resume_max_per_leg);
if (config.recovery_resume_confirm_cycles < 1)
{
robot::log_warning("[move_base2] recovery_resume_confirm_cycles must be >= 1; using default 3");
config.recovery_resume_confirm_cycles = defaults.recovery_resume_confirm_cycles;
}
if (!std::isfinite(config.recovery_resume_min_speed) || config.recovery_resume_min_speed <= 0.0)
{
robot::log_warning("[move_base2] recovery_resume_min_speed must be > 0; using default 0.05 m/s");
config.recovery_resume_min_speed = defaults.recovery_resume_min_speed;
}
if (config.recovery_resume_max_per_leg < 0)
{
robot::log_warning("[move_base2] recovery_resume_max_per_leg must be >= 0; using default 3");
config.recovery_resume_max_per_leg = defaults.recovery_resume_max_per_leg;
}
}
/// Đọc một binding profile từ namespace con cùng tên.
void readBinding(robot::NodeHandle& nh, const std::string& ns, ProfileBinding& binding)
{
@@ -143,9 +168,11 @@ void readDockingMarkerProfiles(robot::NodeHandle& nh, DockingMarkerProfiles& pro
/// Các tham số chung của move_base2, dùng chung cho schema namespace và schema root-profile.
void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
{
readRecoveryResume(nh, config.state_machine);
readDouble(nh, "controller_frequency", config.controller_frequency);
readDouble(nh, "planner_frequency", config.planner_frequency);
readDouble(nh, "planner_timeout", config.planner_timeout);
readDouble(nh, "costmap_ready_timeout", config.costmap_ready_timeout);
readDouble(nh, "runtime_stats_period", config.runtime_stats_period);
readDouble(nh, "watchdog_period", config.watchdog.period);
readDouble(nh, "local_planner_call_budget", config.watchdog.local_planner_call_budget);
@@ -247,11 +274,11 @@ void readDebug(robot::NodeHandle& nh, MoveBase2Config& config)
void readEnvMonitor(robot::NodeHandle& nh, MoveBase2Config& config)
{
robot::NodeHandle env_nh(nh, "env_monitor");
EnvMonitorConfig& m = config.env_monitor;
EnvSamplingConfig& s = config.env_sampling;
readBool(env_nh, "enabled", m.enabled);
readDouble(env_nh, "grace_after_new_plan", m.grace_after_new_plan);
// Phần chung và từng detector (stall / unreachable / contact / replan_budget / detectors) do
// env_monitor_core::EnvMonitor::initialize() đọc. Ở đây chỉ phần lấy mẫu của move_base2.
readBool(env_nh, "enabled", config.env_monitor_enabled);
readDouble(env_nh, "check_period", s.check_period);
robot::NodeHandle body_nh(env_nh, "body");
@@ -272,61 +299,11 @@ void readEnvMonitor(robot::NodeHandle& nh, MoveBase2Config& config)
readDouble(geo_nh, "exit_ahead", s.exit_ahead);
readDouble(geo_nh, "target_snap", s.target_snap);
robot::NodeHandle stall_nh(env_nh, "stall");
readBool(stall_nh, "enabled", m.stall.enabled);
readString(stall_nh, "action", m.stall.action);
readDouble(stall_nh, "window_s", m.stall.window_s);
readDouble(stall_nh, "window_m", m.stall.window_m);
readDouble(stall_nh, "min_commanded", m.stall.min_commanded);
readDouble(stall_nh, "eff_on", m.stall.eff_on);
readDouble(stall_nh, "eff_off", m.stall.eff_off);
readDouble(stall_nh, "confirm", m.stall.confirm);
readDouble(stall_nh, "goal_zone", m.stall.goal_zone);
readDouble(stall_nh, "slip_on", m.stall.slip_on);
readDouble(stall_nh, "slip_time", m.stall.slip_time);
readDouble(stall_nh, "min_commanded_since_goal", m.stall.min_commanded_since_goal);
readDouble(stall_nh, "retry_backoff", m.stall.retry_backoff);
readDouble(stall_nh, "jump_reject", m.stall.jump_reject);
readDouble(stall_nh, "disp_window_s", m.stall.disp_window_s);
readDouble(stall_nh, "disp_min", m.stall.disp_min);
readDouble(stall_nh, "disp_min_commanded", m.stall.disp_min_commanded);
readDouble(stall_nh, "idle_window_s", m.stall.idle_window_s);
readDouble(stall_nh, "confine_window_s", m.stall.confine_window_s);
readDouble(stall_nh, "confine_radius", m.stall.confine_radius);
readDouble(stall_nh, "confine_cmd_factor", m.stall.confine_cmd_factor);
robot::NodeHandle unreach_nh(env_nh, "unreachable");
readBool(unreach_nh, "enabled", m.unreachable.enabled);
readString(unreach_nh, "action", m.unreachable.action);
readDouble(unreach_nh, "static_on", m.unreachable.static_on);
readDouble(unreach_nh, "clean_start_margin", m.unreachable.clean_start_margin);
readDouble(unreach_nh, "retry_backoff", m.unreachable.retry_backoff);
// Khối `contact` mang cả cách lấy quỹ đạo để sweep (của move_base2) lẫn tham số detector (của env_monitor_core).
robot::NodeHandle contact_nh(env_nh, "contact");
readBool(contact_nh, "enabled", m.contact.enabled);
readString(contact_nh, "action", m.contact.action);
readBool(contact_nh, "apply_command", m.contact.apply_command);
readString(contact_nh, "use_local_plan", s.use_local_plan);
readDouble(contact_nh, "local_plan_start_tol", s.local_plan_start_tol);
readDouble(contact_nh, "lookahead", s.contact_lookahead);
readInt(contact_nh, "confirm_cycles", m.contact.confirm_cycles);
readDouble(contact_nh, "trigger_static_time", m.contact.trigger_static_time);
readDouble(contact_nh, "clean_start_margin", m.contact.clean_start_margin);
readDouble(contact_nh, "brake_decel", m.contact.brake_decel);
readDouble(contact_nh, "min_speed", m.contact.min_speed);
readDouble(contact_nh, "min_check_speed", m.contact.min_check_speed);
readDouble(contact_nh, "release_hysteresis", m.contact.release_hysteresis);
readInt(contact_nh, "release_confirm_cycles", m.contact.release_confirm_cycles);
readDouble(contact_nh, "envelope_margin", m.contact.envelope_margin);
readDouble(contact_nh, "standdown_min_travel", m.contact.standdown_min_travel);
readDouble(contact_nh, "standdown_travel", m.contact.standdown_travel);
readBool(contact_nh, "envelope", m.contact.envelope);
robot::NodeHandle budget_nh(env_nh, "replan_budget");
readDouble(budget_nh, "min_travel", m.replan.min_travel);
readDouble(budget_nh, "escalate_factor", m.replan.escalate_factor);
readDouble(budget_nh, "escalate_window_m", m.replan.escalate_window_m);
readDouble(budget_nh, "escalate_max", m.replan.escalate_max);
robot::NodeHandle logger_nh(env_nh, "logger");
readBool(logger_nh, "enabled", config.env_logger.enabled);
@@ -435,6 +412,11 @@ bool MoveBase2Config::validate(std::string& error) const
error = "planner_timeout is not finite [s]";
return false;
}
if (!std::isfinite(costmap_ready_timeout) || costmap_ready_timeout < 0.0)
{
error = "costmap_ready_timeout must be finite and >= 0 [s] (0 = legacy behavior)";
return false;
}
if (!watchdog.validate(error))
{
return false;
@@ -483,9 +465,9 @@ bool MoveBase2Config::validate(std::string& error) const
return false;
}
if (env_monitor.enabled)
if (env_monitor_enabled)
{
if (!env_monitor.validate(error) || !env_sampling.validate(error) || !env_logger.validate(error))
if (!env_sampling.validate(error) || !env_logger.validate(error))
{
return false;
}
@@ -536,6 +518,8 @@ std::string MoveBase2Config::describe() const
out << " controller_frequency: " << controller_frequency << " Hz\n";
out << " planner_frequency: " << planner_frequency << " Hz\n";
out << " planner_timeout: " << planner_timeout << " s\n";
out << " costmap_ready_timeout: " << costmap_ready_timeout << " s"
<< (costmap_ready_timeout == 0.0 ? " (readiness check off)\n" : "\n");
out << " runtime_stats_period: " << runtime_stats_period << " s"
<< (runtime_stats_period > 0.0 ? "\n" : " (off)\n");
out << watchdog.describe();
@@ -577,11 +561,13 @@ std::string MoveBase2Config::describe() const
void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
{
readRecoveryResume(nh, state_machine);
// Schema gen-1 dùng base_footprint; giữ frame cũ để không đổi hành vi của hệ đang chạy.
robot_base_frame = "base_footprint";
readDouble(nh, "controller_frequency", controller_frequency);
readDouble(nh, "planner_frequency", planner_frequency);
readDouble(nh, "costmap_ready_timeout", costmap_ready_timeout);
// Khoá này không có trong schema gen-1 — nó là công cụ chẩn đoán của move_base2. Vẫn đọc ở đây
// để bật được telemetry mà không phải chuyển cả cây config sang schema mới.
readDouble(nh, "runtime_stats_period", runtime_stats_period);
@@ -731,6 +717,7 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
config.debug_plan = debug_plan;
config.debug_skip = debug_skip;
config.state_machine = state_machine;
config.costmap_ready_timeout = costmap_ready_timeout;
config.velocity = velocity;
config.nominal_control_period =
controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s]
@@ -743,7 +730,6 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
config.go_straight = go_straight;
config.rotate = rotate;
config.backup_global_planner_name = backup_global_planner_name;
config.env_monitor = env_monitor;
config.env_sampling = env_sampling;
config.env_logger = env_logger;
config.debug_env = debug_env;

View File

@@ -40,6 +40,19 @@ constexpr double kStaleCostmapLogThrottle = 5.0;
/// không bị mất dấu trong các fail diễn ra trong vài trăm ms sau detour.
constexpr double kDebugControlLogThrottle = 0.2;
struct LocalPlannerBusyScope
{
explicit LocalPlannerBusyScope(ComponentStatusBoard* board) : board_(board)
{
if (board_ != nullptr) board_->enter(Component::kLocalPlanner, ComponentPhase::kBusy);
}
~LocalPlannerBusyScope()
{
if (board_ != nullptr) board_->enter(Component::kLocalPlanner, ComponentPhase::kIdle);
}
ComponentStatusBoard* board_;
};
const char* toString(PlannerFeedback feedback)
{
switch (feedback)
@@ -48,6 +61,8 @@ const char* toString(PlannerFeedback feedback)
return "idle";
case PlannerFeedback::kBusy:
return "busy";
case PlannerFeedback::kWaitingForCostmap:
return "waiting_for_costmap";
case PlannerFeedback::kPlanReady:
return "plan_ready";
case PlannerFeedback::kFailed:
@@ -96,6 +111,11 @@ const char* toString(RecoveryFeedback feedback)
bool ControlLoopConfig::validate(std::string& error) const
{
if (!std::isfinite(costmap_ready_timeout) || costmap_ready_timeout < 0.0)
{
error = "costmap_ready_timeout must be finite and >= 0 [s]";
return false;
}
if (!state_machine.validate(error))
{
return false;
@@ -213,6 +233,64 @@ bool EnvSamplingConfig::validate(std::string& error) const
// ControlLoop
// ================================================================================================
namespace
{
/// Nhãn trigger cho log và recovery_core: tên route cũ giữ trigger cũ, route khác là kDetector.
RecoveryTrigger triggerForRoute(const std::string& route)
{
if (route == "oscillation")
{
return RecoveryTrigger::kOscillation;
}
if (route == "path_blocked")
{
return RecoveryTrigger::kPathBlocked;
}
if (route == "off_path")
{
return RecoveryTrigger::kOffPath;
}
if (route == "collision")
{
return RecoveryTrigger::kCollision;
}
return RecoveryTrigger::kDetector;
}
/// Một DetectorRoute cho mỗi detector đã nạp, đúng thứ tự (bit i của fired_mask). Detector trỏ tới route không có
/// trong `recovery/routes` bị GỠ khỏi monitor (log LỖI): chốt 26/11, giống type sai.
void resolveDetectorRoutes(env_monitor_core::EnvMonitor& monitor, StateMachineConfig& config)
{
if (config.recovery_routes.empty())
{
config.recovery_routes.fillLegacy(config.recovery_behavior_count);
}
config.detector_routes.clear();
const std::vector<env_monitor_core::EnvDetectorInfo> detectors = monitor.detectors(); // copy: remove() sửa list
for (const env_monitor_core::EnvDetectorInfo& d : detectors)
{
const std::vector<std::size_t>* route = config.recovery_routes.find(d.route.route);
if (route == nullptr)
{
robot::log_error("[move_base2] EnvMonitor: detector '%s' points to route '%s', which is not in recovery/routes — "
"the detector is REMOVED (no flag, no brake, no speed cap).\n",
d.name.c_str(), d.route.route.c_str());
monitor.remove(d.name);
continue;
}
DetectorRoute r;
r.name = d.name;
r.route = *route;
r.lock_on_exhausted = d.route.lock_on_exhausted;
r.sequence = d.route.sequence;
r.trigger = triggerForRoute(d.route.route);
config.detector_routes.push_back(r);
}
}
} // namespace
bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDeps& deps,
std::string& error)
{
@@ -228,7 +306,14 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
{
return false;
}
if (!state_machine_.configure(config.state_machine, error))
// Route theo detector: mỗi detector EnvMonitor trỏ tới một route theo tên (Test/docs/move_base2/
// ENV_DETECTOR_PLUGINS_PROMPT.md §4). Chỉ khi monitor thật sự chạy — không có cổng môi trường thì không bit nào bật.
StateMachineConfig state_machine_config = config.state_machine;
if (deps.env_monitor != nullptr && deps.env_monitor->enabled() && deps.environment != nullptr)
{
resolveDetectorRoutes(*deps.env_monitor, state_machine_config);
}
if (!state_machine_.configure(state_machine_config, error))
{
return false;
}
@@ -238,13 +323,16 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
}
config_ = config;
config_.state_machine = state_machine_config;
deps_ = deps;
env_needs_ = deps_.env_monitor ? deps_.env_monitor->needs() : env_monitor_core::EnvNeeds();
deps_.planner->setCostmapReadyTimeout(config_.costmap_ready_timeout);
// EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 (PathMonitor cũ đã
// xoá). Không có cổng thì tắt, nhưng phải kêu nếu config bảo bật.
env_logger_.reset();
if (config_.env_monitor.enabled)
if (deps_.env_monitor != nullptr && deps_.env_monitor->enabled())
{
if (deps_.environment == nullptr)
{
@@ -253,21 +341,19 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
}
else
{
if (!config_.env_sampling.validate(error) || !env_monitor_.configure(config_.env_monitor, error))
// Lõi đã initialize() từ YAML ở host (NavigationRuntime); ở đây chỉ kiểm phần lấy mẫu của chính vòng điều khiển.
if (!config_.env_sampling.validate(error))
{
return false;
}
robot::log_info("[move_base2] %s\n sampling : check=%.2f s lethal>=%d padding=%.2f m horizon=%.1f m "
"corridor_margin=%.2f m use_local_plan=%s lookahead=%.1f m body=%s\n",
config_.env_monitor.describe().c_str(), config_.env_sampling.check_period,
deps_.env_monitor->describe().c_str(), config_.env_sampling.check_period,
config_.env_sampling.lethal_threshold, config_.env_sampling.padding,
config_.env_sampling.horizon, config_.env_sampling.corridor_margin,
config_.env_sampling.use_local_plan.c_str(), config_.env_sampling.contact_lookahead,
config_.env_sampling.body_front > 0.0 ? "config" : "costmap footprint");
const bool shadow = config_.env_monitor.stall.action != "recover" &&
config_.env_monitor.unreachable.action != "recover" &&
config_.env_monitor.contact.action != "recover" &&
!config_.env_monitor.contact.apply_command;
const bool shadow = !deps_.env_monitor->armed();
robot::log_info("[move_base2] EnvMonitor mode: %s\n",
shadow ? "SHADOW (log only; no flags, no braking, no speed cap)"
: "ACTIVE on at least one verdict or on the command");
@@ -312,6 +398,8 @@ void ControlLoop::reset()
action_message_.clear();
latest_plan_.clear();
chain_path_.clear();
running_recovery_detector_ = -1;
planner_running_ = false;
backup_global_planner_active_ = false;
@@ -327,8 +415,11 @@ void ControlLoop::reset()
last_plan_started_ = robot::Time();
has_last_plan_applied_ = false;
env_monitor_.reset();
env_verdict_ = EnvVerdict();
if (deps_.env_monitor != nullptr)
{
deps_.env_monitor->reset();
}
env_verdict_ = env_monitor_core::EnvVerdict();
env_geometry_ = EnvGeometry();
has_last_env_heavy_ = false;
has_last_env_debug_ = false;
@@ -724,20 +815,52 @@ bool ControlLoop::robotStopped() const
return arbiter_.stopped();
}
bool ControlLoop::runningChain() const
{
const auto& routes = config_.state_machine.detector_routes;
return running_recovery_detector_ >= 0 && static_cast<std::size_t>(running_recovery_detector_) < routes.size() &&
routes[running_recovery_detector_].sequence;
}
std::string ControlLoop::triggerLabel(const StateMachineOutput& output) const
{
const auto& routes = config_.state_machine.detector_routes;
std::string label = toString(output.recovery_trigger);
if (output.recovery_detector >= 0 && static_cast<std::size_t>(output.recovery_detector) < routes.size())
{
label += " (" + routes[output.recovery_detector].name + ")"; // detector nào: kDetector tự nó không nói
}
return label;
}
void ControlLoop::envRecoveryFinished(const robot::Time& now, env_monitor_core::EnvRecoveryOutcome outcome)
{
if (deps_.env_monitor == nullptr)
{
return;
}
// Báo tên detector có route vừa chạy: detector đó biết lượt recovery là của chính nó (contact: stand-down).
const auto& routes = config_.state_machine.detector_routes;
const bool by_detector =
running_recovery_detector_ >= 0 && static_cast<std::size_t>(running_recovery_detector_) < routes.size();
deps_.env_monitor->onRecoveryFinished(now, outcome,
by_detector ? routes[running_recovery_detector_].name : std::string());
}
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
bool costmap_stale)
{
env_brake_ = false;
if (!config_.env_monitor.enabled || deps_.environment == nullptr || !env_monitor_.configured())
if (deps_.env_monitor == nullptr || !deps_.env_monitor->enabled() || deps_.environment == nullptr)
{
return;
}
if (!has_active_request_)
{
// Không có chặng: mọi ngân sách/mốc thuộc chặng cũ. Verdict rỗng.
env_monitor_.reset();
env_verdict_ = EnvVerdict();
deps_.env_monitor->reset();
env_verdict_ = env_monitor_core::EnvVerdict();
env_geometry_ = EnvGeometry();
has_last_env_heavy_ = false;
env_plan_index_valid_ = false;
@@ -748,13 +871,14 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
const bool monitorable = state_machine_.state() == NavigationState::kControlling && pose_available &&
!latest_plan_.empty() && sampling.monitors(active_request_.profile);
EnvSample s;
env_monitor_core::EnvSample s;
s.now = now;
s.dt = dt;
s.costmap_current = !costmap_stale;
s.has_plan = monitorable;
s.robot_x = robot_pose.pose.position.x;
s.robot_y = robot_pose.pose.position.y;
// Không có pose thì báo NaN: robot_pose giữ giá trị mặc định (0, 0), lõi sẽ coi đó là cú dời về gốc.
s.robot_x = pose_available ? robot_pose.pose.position.x : std::numeric_limits<double>::quiet_NaN();
s.robot_y = pose_available ? robot_pose.pose.position.y : std::numeric_limits<double>::quiet_NaN();
const robot_geometry_msgs::Twist& last_cmd = arbiter_.lastCommand();
s.v_cmd = last_cmd.linear.x;
s.w_cmd = last_cmd.angular.z;
@@ -773,6 +897,11 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
if (monitorable)
{
if (env_needs_.footprint)
{
s.footprint.swap(env_footprint_scratch_);
s.footprint_valid = deps_.environment->sampleFootprint(s.footprint);
}
double front = sampling.body_front;
double rear = sampling.body_rear;
double side = sampling.body_side;
@@ -827,7 +956,7 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
has_last_env_heavy_ = true;
}
if (config_.env_monitor.contact.enabled)
if (env_needs_.sweep) // chỉ khi có detector cần quỹ đạo (contact)
{
EnvTrajectoryRequest treq;
treq.robot_pose = robot_pose;
@@ -855,8 +984,21 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
}
}
env_verdict_ = env_monitor_.update(s);
env_brake_ = env_verdict_.brake && config_.env_monitor.contact.apply_command;
env_verdict_ = deps_.env_monitor->update(s);
if (monitorable && env_needs_.footprint)
s.footprint.swap(env_footprint_scratch_);
env_brake_ = env_verdict_.brake_applied; // chỉ phanh của detector có apply_command
if (env_verdict_.pose_jump)
{
// Bất thường (localization đặt lại pose / TF đứng rồi chạy lại), không phải đường đi bình thường: không công tắc.
// Throttle chỉ chặn trường hợp localization lật liên tục mỗi cycle.
const char* status = env_verdict_.pose_jump_restart ? "stall windows restarted"
: "repeated jump: stall windows kept";
robot::log_warning_throttle(1.0, "[move_base2] EnvMonitor: robot pose jumped %.2f m (relocalization?) "
"— %s, the jump is not counted as travel (mission %llu).\n",
env_verdict_.pose_jump_dist, status,
static_cast<unsigned long long>(active_request_.mission_sequence_id));
}
if (env_verdict_.cost_jump && config_.debug_env)
{
robot::log_info_throttle(1.0, "[move_base2][debug] EnvMonitor: cost_to_go jumped to %.2f m in one tick — free mask "
@@ -896,10 +1038,13 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
env_verdict_.unreachable_detected ? 1 : 0, env_verdict_.unreachable_muted ? "(muted)" : "",
env_verdict_.brake ? 1 : 0, env_verdict_.contact_standdown ? 1 : 0,
env_verdict_.replan_budget_left, env_verdict_.net_disp,
env_verdict_.wandering ? " WANDERING"
: (env_verdict_.idle ? " IDLE" : (env_verdict_.confined ? " CONFINED" : "")));
env_verdict_.wandering
? " WANDERING"
: (!env_verdict_.idle && env_verdict_.confined_vetoed
? " CONFINED vetoed: progress proven"
: (env_verdict_.idle ? " IDLE" : (env_verdict_.confined ? " CONFINED" : ""))));
}
if (env_logger_ && (s.geometry_valid || env_verdict_.event[0] != '\0'))
if (env_logger_ && (s.geometry_valid || env_verdict_.event[0] != '\0' || env_verdict_.pose_jump))
{
env_logger_->record(now, s, env_verdict_, s.geometry_valid ? &env_geometry_ : nullptr,
toString(state_machine_.state()), active_request_.mission_sequence_id,
@@ -914,24 +1059,7 @@ void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
// Hàng local_planner của bảng trạng thái: bận trong suốt lượt gọi plugin (đồng bộ, cùng thread),
// rảnh khi ra. Watchdog (pha 4) dùng nó để bắt local planner treo — control thread không tự bắt
// được chính mình. RAII để mọi đường thoát (kể cả exception từ plugin) đều trả về idle.
struct LocalPlannerBusyScope
{
explicit LocalPlannerBusyScope(ComponentStatusBoard* board) : board_(board)
{
if (board_ != nullptr)
{
board_->enter(Component::kLocalPlanner, ComponentPhase::kBusy);
}
}
~LocalPlannerBusyScope()
{
if (board_ != nullptr)
{
board_->enter(Component::kLocalPlanner, ComponentPhase::kIdle);
}
}
ComponentStatusBoard* board_;
} local_planner_busy(deps_.components);
LocalPlannerBusyScope local_planner_busy(deps_.components);
// Giữ nguyên thứ tự của interface được bọc: hỏi đã tới đích trước, chỉ khi chưa mới tính lệnh.
if (deps_.controller->isGoalReached())
@@ -1012,8 +1140,12 @@ bool ControlLoop::step()
// Costmap còn hạn không — hỏi ở ĐÂY chứ không ở mục 3.5 như trước: EnvMonitor cần nó, mà monitor
// phải chạy xong trước state machine. Vẫn là một lời gọi mỗi cycle, chỉ đổi vị trí.
const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr &&
!deps_.costmap_status->isCurrent();
const bool check_probe_costmap = state_machine_.state() == NavigationState::kRecovering &&
state_machine_.recoveryResumeAvailable();
const bool costmap_not_current = deps_.costmap_status != nullptr &&
(config_.require_current_costmap || check_probe_costmap) &&
!deps_.costmap_status->isCurrent();
const bool costmap_stale = config_.require_current_costmap && costmap_not_current;
// --- 1b. Giám sát tuyến ---------------------------------------------------------------------
// Chạy TRƯỚC state machine: hai cờ nó sinh ra là dữ liệu vào của state machine ngay cycle này.
@@ -1035,6 +1167,9 @@ bool ControlLoop::step()
input.cancel_requested = cancel_requested_;
input.emergency = emergency_;
input.planner = planner_feedback_;
const bool planner_waiting = deps_.planner->costmapWaitState(input.planner_costmap_wait_finished);
if (planner_running_ && planner_waiting && planner_feedback_ == PlannerFeedback::kBusy)
input.planner = PlannerFeedback::kWaitingForCostmap;
input.controller = controller_feedback_;
input.recovery = recovery_feedback_;
input.action = action_feedback_;
@@ -1064,12 +1199,8 @@ bool ControlLoop::step()
}
}
input.travelled_since_oscillation_reset = travelled;
// Bốn cổng của state machine do EnvMonitor cấp (Test/docs/move_base2/ENV_MONITOR_PLAN.md): cờ chỉ khác false khi
// verdict tương ứng có `action: recover`. `off_path` không còn nguồn nào (phép đo cũ đã bỏ 6/9/2026).
input.path_blocked = env_verdict_.path_blocked;
input.collision = env_verdict_.collision;
input.off_path = false;
input.no_progress = env_verdict_.no_progress;
// Bit i = detector i đòi recovery (đã qua action/cổng/ngân sách), cùng thứ tự với detector_routes.
input.detector_fired = env_verdict_.fired_mask;
// Cùng một chỉ số dùng cho cả cycle khởi động recovery lẫn các cycle tick: state machine chỉ tăng
// chỉ số khi behavior kết thúc, nên `nextRecoveryIndex()` chính là behavior sắp chạy hoặc đang
@@ -1079,6 +1210,25 @@ bool ControlLoop::step()
? deps_.recovery->outputKind(state_machine_.nextRecoveryIndex())
: RecoveryOutputKind::kNone;
// Probe only a running, explicitly allowed behavior. Its command never enters the arbiter.
std::string probed_recovery;
if (state_machine_.state() == NavigationState::kRecovering && state_machine_.recoveryResumeAvailable() &&
input.recovery == RecoveryFeedback::kRunning && deps_.recovery != nullptr && !latest_plan_.empty() &&
pose_available && !costmap_not_current && !input.emergency && !input.has_pending_request &&
!input.cancel_requested && !input.pause_requested)
{
probed_recovery = deps_.recovery->behaviorName(state_machine_.nextRecoveryIndex());
const auto& allowed = config_.state_machine.recovery_resume_behaviors;
if (std::find(allowed.begin(), allowed.end(), probed_recovery) != allowed.end())
{
robot_geometry_msgs::Twist probe;
LocalPlannerBusyScope local_planner_busy(deps_.components);
input.recovery_probe_moving = deps_.controller->computeVelocityCommands(probe) &&
std::isfinite(probe.linear.x) && std::isfinite(probe.angular.z) &&
std::fabs(probe.linear.x) >= config_.state_machine.recovery_resume_min_speed;
}
}
const StateMachineOutput output = state_machine_.update(input);
if (output.state_changed)
@@ -1136,7 +1286,10 @@ bool ControlLoop::step()
latest_plan_.clear();
order_plan_.clear();
has_outcome_ = false;
env_monitor_.onGoalAccepted(now);
if (deps_.env_monitor != nullptr)
{
deps_.env_monitor->onGoalAccepted(now);
}
// Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop.
if (active_request_.has_goal)
@@ -1179,6 +1332,32 @@ bool ControlLoop::step()
planner_running_ = false;
}
// Chuỗi `route_mode: sequence` vừa xong: path mới nhất của chuỗi (nếu có) là plan được áp ngay dưới, và EnvMonitor
// nghe kết cục của CẢ chuỗi đúng một lần (chốt 26/11).
if (output.recovery_chain_finished)
{
if (!chain_path_.empty())
{
latest_plan_ = chain_path_;
}
envRecoveryFinished(now, output.recovery_chain_has_path ? env_monitor_core::EnvRecoveryOutcome::kSucceededWithPath
: output.recovery_chain_last_failed ? env_monitor_core::EnvRecoveryOutcome::kFailed
: env_monitor_core::EnvRecoveryOutcome::kSucceeded);
chain_path_.clear();
}
if (output.cancel_recovery)
{
deps_.recovery->cancel();
if (output.recovery_resumed)
{
robot::log_info("[move_base2] recovery '%s' cancelled: controller has a command again (%d cycles)",
probed_recovery.c_str(), config_.state_machine.recovery_resume_confirm_cycles);
chain_path_.clear();
envRecoveryFinished(now, env_monitor_core::EnvRecoveryOutcome::kSucceeded);
}
}
if (output.apply_plan && !latest_plan_.empty())
{
if (!deps_.controller->setPlan(latest_plan_))
@@ -1202,7 +1381,10 @@ bool ControlLoop::step()
// plan vừa tới (rõ nhất lúc preempt/đổi chặng). Đo lệch tuyến ngay lúc đó là khai hoả oan.
last_plan_applied_ = now;
has_last_plan_applied_ = true;
env_monitor_.onPlanApplied(now);
if (deps_.env_monitor != nullptr)
{
deps_.env_monitor->onPlanApplied(now);
}
env_plan_index_valid_ = false;
if (config_.debug_plan)
@@ -1221,11 +1403,6 @@ bool ControlLoop::step()
}
}
if (output.cancel_recovery)
{
deps_.recovery->cancel();
}
// Giám sát tuyến hết đường vòng (contract 2026-08-05e): KHÔNG kết thúc chặng — robot bám tiếp
// plan cũ và trigger bị khoá tới khi đi được quá `oscillation_distance`. Log đúng MỘT dòng ở
// sườn khoá, vì sau đó nhánh monitor im lặng hoàn toàn và người vận hành sẽ không hiểu vì sao
@@ -1236,7 +1413,7 @@ bool ControlLoop::step()
"here the controller is the only safety net: it stops at the obstacle and "
"controller_patience escalates to controlling_failed. This trigger stays "
"muted until the robot travels %.2f m.\n",
toString(output.recovery_trigger), config_.state_machine.oscillation_distance);
triggerLabel(output).c_str(), config_.state_machine.oscillation_distance);
}
// Recovery vừa nộp path mới nhưng robot chưa dịch chuyển kể từ path mới trước đó: state machine
@@ -1248,7 +1425,7 @@ bool ControlLoop::step()
"the previous one (%.2f m, need %.2f m) — counting it against the %s route "
"budget instead of refilling it.\n",
output.recovery_reset_travel, config_.state_machine.recovery_reset_min_travel,
toString(output.recovery_trigger));
triggerLabel(output).c_str());
}
robot_geometry_msgs::Twist candidate;
@@ -1256,13 +1433,20 @@ bool ControlLoop::step()
if (output.start_recovery)
{
running_recovery_trigger_ = output.recovery_trigger;
running_recovery_detector_ = output.recovery_detector;
if (!output.recovery_chain_continues)
{
chain_path_.clear(); // lượt mới: path của chuỗi trước (nếu bị huỷ giữa chừng) không còn giá trị
}
if (!deps_.recovery->start(output.recovery_index, output.recovery_trigger))
{
// Behavior từ chối khởi động (ví dụ đã va chạm ngay tại chỗ) — báo hỏng để state machine
// chuyển sang behavior kế tiếp thay vì tick một behavior chưa start.
recovery_feedback_ = RecoveryFeedback::kFailed;
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
if (!runningChain())
{
envRecoveryFinished(now, env_monitor_core::EnvRecoveryOutcome::kFailed);
}
}
}
else if (output.tick_recovery)
@@ -1275,14 +1459,19 @@ bool ControlLoop::step()
break;
case RecoveryTick::Status::kSucceeded:
recovery_feedback_ = RecoveryFeedback::kSucceeded;
env_monitor_.onRecoveryFinished(now,
tick.has_path && !tick.path.empty() ? EnvRecoveryOutcome::kSucceededWithPath
: EnvRecoveryOutcome::kSucceeded,
running_recovery_trigger_ == RecoveryTrigger::kCollision);
if (!runningChain()) // chuỗi sequence: báo một lần khi cả chuỗi xong (recovery_chain_finished)
{
envRecoveryFinished(now, tick.has_path && !tick.path.empty()
? env_monitor_core::EnvRecoveryOutcome::kSucceededWithPath
: env_monitor_core::EnvRecoveryOutcome::kSucceeded);
}
break;
case RecoveryTick::Status::kFailed:
recovery_feedback_ = RecoveryFeedback::kFailed;
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
if (!runningChain())
{
envRecoveryFinished(now, env_monitor_core::EnvRecoveryOutcome::kFailed);
}
break;
}
if (tick.has_velocity)
@@ -1293,6 +1482,10 @@ bool ControlLoop::step()
{
// Họ recovery sinh lại đường đi: coi kết quả như một plan mới, chờ state machine đẩy xuống.
latest_plan_ = tick.path;
if (runningChain())
{
chain_path_ = tick.path; // giữ path MỚI NHẤT của chuỗi tới khi cả chuỗi xong
}
planner_feedback_ = PlannerFeedback::kPlanReady;
if (config_.debug_plan)
{
@@ -1428,9 +1621,9 @@ bool ControlLoop::step()
// (P4); ở shadow chỉ có dòng log "would cap". Giữ omega/v để cung không đổi khi kẹp.
if (std::isfinite(env_verdict_.v_cap) && std::fabs(candidate.linear.x) > env_verdict_.v_cap)
{
if (config_.env_monitor.contact.apply_command)
if (std::isfinite(env_verdict_.v_cap_applied) && std::fabs(candidate.linear.x) > env_verdict_.v_cap_applied)
{
const double scale = env_verdict_.v_cap / std::fabs(candidate.linear.x);
const double scale = env_verdict_.v_cap_applied / std::fabs(candidate.linear.x);
candidate.linear.x *= scale;
candidate.angular.z *= scale;
}
@@ -1535,7 +1728,10 @@ bool ControlLoop::step()
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
// Sắp chạm vật cản thật cũng là "không ai được phát": lệnh 0 tức thì, không giảm dần.
arbiter_.arbitrate((costmap_stale || env_brake_) ? VelocitySource::kNone : output.velocity_source,
// Phanh EnvMonitor chỉ chặn controller: recovery tự kiểm va chạm của nó. Trong RECOVERING kContact không có quỹ
// đạo để nhả phanh, nên phanh treo từ cycle trước sẽ ép lệnh lùi của evade về 0 tới hết timeout (sim 27/11 14:21).
const bool env_brake_blocks = env_brake_ && output.velocity_source == VelocitySource::kController;
arbiter_.arbitrate((costmap_stale || env_brake_blocks) ? VelocitySource::kNone : output.velocity_source,
candidate, dt);
if (config_.debug_plan && output.run_controller)
@@ -1586,7 +1782,7 @@ bool ControlLoop::step()
robot::log_error("[move_base2] abort detail: recovery route exhausted "
"(trigger=%s cursor=%zu size=%zu, planner_in=%s, controller_in=%s, "
"recovery_in=%s, pose=%s, costmap_current=%s).\n",
toString(output.recovery_trigger), output.recovery_route_cursor,
triggerLabel(output).c_str(), output.recovery_route_cursor,
output.recovery_route_size, toString(input.planner),
toString(input.controller), toString(input.recovery),
pose_available ? "yes" : "no", costmap_stale ? "no" : "yes");

View File

@@ -1,841 +0,0 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — cài đặt lõi EnvMonitor (xem header).
*
* Author: DuongTD
*********************************************************************/
#include <move_base2/core/env_monitor.h>
#include <algorithm>
#include <cmath>
#include <sstream>
namespace move_base2
{
namespace
{
bool validAction(const std::string& action)
{
return action == "log" || action == "recover";
}
bool finitePositive(double v)
{
return std::isfinite(v) && v > 0.0;
}
bool finiteNonNegative(double v)
{
return std::isfinite(v) && v >= 0.0;
}
} // namespace
// ------------------------------------------------------------------------------------------ config
bool EnvMonitorConfig::validate(std::string& error) const
{
if (!finiteNonNegative(grace_after_new_plan))
{
error = "env_monitor/grace_after_new_plan must be >= 0 [s]";
return false;
}
if (!validAction(stall.action) || !validAction(unreachable.action) || !validAction(contact.action))
{
error = "env_monitor/*/action must be \"log\" or \"recover\"";
return false;
}
if (!finitePositive(stall.window_s) || !finitePositive(stall.window_m))
{
error = "env_monitor/stall/window_s and window_m must be > 0";
return false;
}
if (!finitePositive(stall.min_commanded))
{
error = "env_monitor/stall/min_commanded must be > 0 [m] (0 would turn waiting into stalling)";
return false;
}
if (!std::isfinite(stall.eff_on) || !std::isfinite(stall.eff_off) || stall.eff_off <= stall.eff_on)
{
error = "env_monitor/stall/eff_off must be > eff_on (hysteresis)";
return false;
}
if (!finiteNonNegative(stall.confirm) || !finiteNonNegative(stall.goal_zone) ||
!finiteNonNegative(stall.slip_on) || !finiteNonNegative(stall.slip_time) ||
!finiteNonNegative(stall.min_commanded_since_goal) || !finiteNonNegative(stall.retry_backoff) ||
!finiteNonNegative(stall.jump_reject) || !finitePositive(stall.disp_window_s) ||
!finiteNonNegative(stall.disp_min) || !finiteNonNegative(stall.disp_min_commanded) ||
!finiteNonNegative(stall.idle_window_s) || !finiteNonNegative(stall.confine_radius) ||
!finitePositive(stall.confine_window_s) || !std::isfinite(stall.confine_cmd_factor) ||
stall.confine_cmd_factor < 1.0)
{
error = "env_monitor/stall: confirm, goal_zone, slip_on, slip_time, min_commanded_since_goal, "
"retry_backoff must be >= 0";
return false;
}
if (!finiteNonNegative(unreachable.static_on) || !finitePositive(unreachable.clean_start_margin) ||
!finiteNonNegative(unreachable.retry_backoff))
{
error = "env_monitor/unreachable: static_on >= 0 [s], clean_start_margin > 0 [m], retry_backoff >= 0";
return false;
}
if (contact.confirm_cycles < 1)
{
error = "env_monitor/contact/confirm_cycles must be >= 1";
return false;
}
if (!finiteNonNegative(contact.trigger_static_time) || !finitePositive(contact.clean_start_margin) ||
!finitePositive(contact.brake_decel) || !finiteNonNegative(contact.min_speed) ||
!finiteNonNegative(contact.min_check_speed) || !finiteNonNegative(contact.release_hysteresis) ||
contact.release_confirm_cycles < 1 || !finiteNonNegative(contact.envelope_margin) ||
!finiteNonNegative(contact.standdown_min_travel) || !finiteNonNegative(contact.standdown_travel))
{
error = "env_monitor/contact: trigger_static_time >= 0, clean_start_margin > 0, brake_decel > 0, "
"min_speed >= 0, min_check_speed >= 0, release_hysteresis >= 0, release_confirm_cycles >= 1, "
"envelope_margin >= 0, standdown_min_travel >= 0, standdown_travel >= 0";
return false;
}
if (!finiteNonNegative(replan.min_travel) || !std::isfinite(replan.escalate_factor) ||
replan.escalate_factor < 1.0 || !finiteNonNegative(replan.escalate_window_m) ||
!finiteNonNegative(replan.escalate_max) || (replan.escalate_max > 0.0 && replan.escalate_max < replan.min_travel))
{
error = "env_monitor/replan_budget: min_travel >= 0, escalate_factor >= 1, escalate_window_m >= 0, "
"escalate_max = 0 or >= min_travel";
return false;
}
return true;
}
std::string EnvMonitorConfig::describe() const
{
std::ostringstream out;
out << "env_monitor " << (enabled ? "ON" : "OFF") << " (grace " << grace_after_new_plan << " s):\n";
out << " stall : " << (stall.enabled ? "on" : "off") << " action=" << stall.action
<< " window=" << stall.window_s << " s/" << stall.window_m << " m min_cmd=" << stall.min_commanded
<< " m eff<" << stall.eff_on << " ket / >=" << stall.eff_off << " xoa confirm=" << stall.confirm
<< " s goal_zone=" << stall.goal_zone << " m slip>=" << stall.slip_on << " m/s " << stall.slip_time
<< " s cmd_since_goal>=" << stall.min_commanded_since_goal << " m backoff=" << stall.retry_backoff
<< " s jump_reject=" << stall.jump_reject << " m disp_gate=" << stall.disp_min << " m/"
<< stall.disp_window_s << " s (cmd>=" << stall.disp_min_commanded << " m) idle=" << stall.idle_window_s
<< " s confine=" << stall.confine_radius << " m/" << stall.confine_window_s << " s x" << stall.confine_cmd_factor
<< "\n";
out << " unreachable : " << (unreachable.enabled ? "on" : "off") << " action=" << unreachable.action
<< " static_on=" << unreachable.static_on << " s clean_margin=" << unreachable.clean_start_margin
<< " m backoff=" << unreachable.retry_backoff << " s\n";
out << " contact : " << (contact.enabled ? "on" : "off") << " action=" << contact.action
<< " confirm=" << contact.confirm_cycles << " cycles trigger_static=" << contact.trigger_static_time
<< " s clean_margin=" << contact.clean_start_margin << " m decel=" << contact.brake_decel
<< " m/s^2 envelope=" << (contact.envelope ? "on" : "off") << " min_speed=" << contact.min_speed
<< " m/s min_check_speed=" << contact.min_check_speed << " m/s release=" << contact.release_hysteresis
<< " m/" << contact.release_confirm_cycles << " cycles envelope_margin=" << contact.envelope_margin
<< " m standdown=" << contact.standdown_min_travel << "/" << contact.standdown_travel
<< " m apply_command=" << (contact.apply_command ? "YES" : "no (shadow)") << "\n";
out << " replan : min_travel=" << replan.min_travel << " m x" << replan.escalate_factor
<< " within " << replan.escalate_window_m << " m, max " << replan.escalate_max << " m";
return out.str();
}
// ----------------------------------------------------------------------------------------- lifecycle
bool EnvMonitor::configure(const EnvMonitorConfig& config, std::string& error)
{
if (!config.validate(error))
{
configured_ = false;
return false;
}
config_ = config;
configured_ = true;
reset();
return true;
}
void EnvMonitor::reset()
{
cmd_accum_ = 0.0;
travel_total_ = 0.0;
has_last_pose_ = false;
has_goal_ = false;
cmd_at_goal_ = 0.0;
has_plan_time_ = false;
clearWindow();
stall_seen_ = false;
stall_fired_ = false;
slip_seen_ = false;
has_stall_backoff_ = false;
baseline_pending_ = true;
baseline_unreachable_ = false;
unreach_seen_ = false;
unreach_fired_ = false;
has_unreach_backoff_ = false;
contact_streak_ = 0;
release_streak_ = 0;
has_prev_heavy_ = false;
clearPosWindow();
braking_ = false;
contact_close_ = false;
contact_fired_ = false;
detour_from_contact_ = false;
detour_mark_travel_ = 0.0;
standdown_ = false;
standdown_mark_travel_ = 0.0;
standdown_clean_streak_ = 0;
has_replan_mark_ = false;
replan_mark_travel_ = 0.0;
budget_travel_ = config_.replan.min_travel;
has_prev_replan_ = false;
prev_replan_travel_ = 0.0;
}
void EnvMonitor::onGoalAccepted(const robot::Time& now)
{
(void)now;
const double cmd = cmd_accum_;
const double travel = travel_total_;
const bool had_pose = has_last_pose_;
const double lx = last_x_;
const double ly = last_y_;
reset();
// Odometer và lệnh tích luỹ là đơn điệu, chỉ dùng qua hiệu số: giữ lại để mốc không nhảy.
cmd_accum_ = cmd;
travel_total_ = travel;
has_last_pose_ = had_pose;
last_x_ = lx;
last_y_ = ly;
has_goal_ = true;
cmd_at_goal_ = cmd_accum_;
}
void EnvMonitor::onPlanApplied(const robot::Time& now)
{
has_plan_time_ = true;
plan_time_ = now;
clearWindow();
clearPosWindow(); // cửa sổ dịch chuyển bắt đầu lại: plan mới là một lượt thử mới
has_prev_heavy_ = false;
stall_seen_ = false;
stall_fired_ = false;
// Plan mới có baseline riêng: chỉ nổ "mất liên thông" vì thứ xảy ra SAU khi plan được lập (R2).
baseline_pending_ = true;
baseline_unreachable_ = false;
unreach_seen_ = false;
unreach_fired_ = false;
}
void EnvMonitor::onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome, bool from_contact)
{
switch (outcome)
{
case EnvRecoveryOutcome::kSucceededWithPath:
{
// Detour do chính cờ collision: nếu robot không rời chỗ mà lại "sắp chạm" thì lần sau đứng ra.
detour_from_contact_ = from_contact;
detour_mark_travel_ = travel_total_;
// R3/R5: im tới khi đi đủ budget_travel_ kể từ đây; lặp trong escalate_window_m thì nhân lên.
if (has_prev_replan_ && travel_total_ - prev_replan_travel_ < config_.replan.escalate_window_m)
{
budget_travel_ *= config_.replan.escalate_factor;
if (config_.replan.escalate_max > 0.0)
{
budget_travel_ = std::min(budget_travel_, config_.replan.escalate_max);
}
}
else
{
budget_travel_ = config_.replan.min_travel;
}
has_prev_replan_ = true;
prev_replan_travel_ = travel_total_;
has_replan_mark_ = true;
replan_mark_travel_ = travel_total_;
break;
}
case EnvRecoveryOutcome::kSucceeded:
break;
case EnvRecoveryOutcome::kFailed:
has_stall_backoff_ = true;
stall_backoff_until_ = now + robot::Duration(config_.stall.retry_backoff);
has_unreach_backoff_ = true;
unreach_backoff_until_ = now + robot::Duration(config_.unreachable.retry_backoff);
break;
}
// Mọi kết cục đều kết thúc một pha dừng: chuỗi xác nhận cũ không còn giá trị.
stall_seen_ = false;
stall_fired_ = false;
unreach_seen_ = false;
unreach_fired_ = false;
contact_streak_ = 0;
release_streak_ = 0;
braking_ = false;
contact_close_ = false;
contact_fired_ = false;
}
// -------------------------------------------------------------------------------------------- window
void EnvMonitor::clearWindow()
{
ring_head_ = 0;
ring_count_ = 0;
}
void EnvMonitor::clearPosWindow()
{
pos_head_ = 0;
pos_count_ = 0;
wandering_ = false;
idle_ = false;
confined_ = false;
region_radius_ = std::numeric_limits<double>::quiet_NaN();
net_disp_ = std::numeric_limits<double>::quiet_NaN();
}
bool EnvMonitor::oldestPos(const robot::Time& now, double window_s, PosSample& out) const
{
// Mẫu MỚI NHẤT đã đủ tuổi window_s — cùng lý do với oldestInWindow.
for (std::size_t k = 1; k <= pos_count_; ++k)
{
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
if ((now - p.t).toSec() >= window_s)
{
out = p;
return true;
}
}
return false;
}
bool EnvMonitor::oldestInWindow(const robot::Time& now, HeavySample& out) const
{
// Mẫu MỚI NHẤT đã đủ tuổi window_s hoặc đủ xa window_m lệnh — cửa sổ sát ngưỡng nhất, không phải
// mẫu cũ nhất trong ring (cửa sổ giãn ra làm eff mượt giả).
for (std::size_t k = 1; k <= ring_count_; ++k)
{
const HeavySample& s = ring_[(ring_head_ + kRing - k) % kRing];
const bool old_enough = (now - s.t).toSec() >= config_.stall.window_s;
const bool far_enough = cmd_accum_ - s.cmd >= config_.stall.window_m;
if (old_enough || far_enough)
{
out = s;
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------------------- update
EnvVerdict EnvMonitor::update(const EnvSample& s)
{
EnvVerdict v;
if (!configured_ || !config_.enabled)
{
return v;
}
// Tích luỹ lệnh và quãng đường — mọi cửa sổ, cổng, ngân sách đều đo bằng hai con số này.
if (s.dt > 0.0 && std::isfinite(s.v_cmd))
{
cmd_accum_ += std::fabs(s.v_cmd) * s.dt;
}
if (std::isfinite(s.robot_x) && std::isfinite(s.robot_y))
{
if (has_last_pose_)
{
travel_total_ += std::hypot(s.robot_x - last_x_, s.robot_y - last_y_);
}
last_x_ = s.robot_x;
last_y_ = s.robot_y;
has_last_pose_ = true;
}
if (has_replan_mark_)
{
v.replan_budget_left = std::max(0.0, budget_travel_ - (travel_total_ - replan_mark_travel_));
}
updateContact(s, v);
if (!s.has_plan || !s.costmap_current)
{
// Không có gì để đo tiến độ; xoá chuỗi để không nối "đúng liên tục" qua quãng gián đoạn.
stall_seen_ = false;
stall_fired_ = false;
unreach_seen_ = false;
unreach_fired_ = false;
return v;
}
updateStall(s, v);
updateUnreachable(s, v);
return v;
}
void EnvMonitor::updateStall(const EnvSample& s, EnvVerdict& v)
{
const EnvMonitorConfig::Stall& c = config_.stall;
if (!c.enabled)
{
return;
}
// Cửa sổ dịch chuyển thực: lấy mẫu vị trí mỗi tick nặng, không phụ thuộc cost/plan/mặt nạ.
if (s.geometry_valid && std::isfinite(s.robot_x) && std::isfinite(s.robot_y))
{
pos_ring_[pos_head_] = PosSample{ s.now, s.robot_x, s.robot_y, cmd_accum_ };
pos_head_ = (pos_head_ + 1) % kPosRing;
pos_count_ = std::min(pos_count_ + 1, kPosRing);
PosSample old;
if (oldestPos(s.now, c.disp_window_s, old))
{
net_disp_ = std::hypot(s.robot_x - old.x, s.robot_y - old.y);
wandering_ = (cmd_accum_ - old.cmd >= c.disp_min_commanded) && net_disp_ < c.disp_min;
}
else
{
net_disp_ = std::numeric_limits<double>::quiet_NaN();
wandering_ = false;
}
// Cổng đứng yên: không cần lệnh đủ — PRIEST bò 0,05 m/s tại chỗ 30 s cũng là kẹt.
idle_ = false;
PosSample older;
if (c.idle_window_s > 0.0 && c.disp_min > 0.0 && oldestPos(s.now, c.idle_window_s, older))
{
idle_ = std::hypot(s.robot_x - older.x, s.robot_y - older.y) < c.disp_min;
}
// Cổng giam vùng: bán kính của tập vị trí trong confine_window_s quanh tâm của chúng, so với lệnh tích luỹ.
confined_ = false;
region_radius_ = std::numeric_limits<double>::quiet_NaN();
if (c.confine_radius > 0.0 && c.disp_min > 0.0)
{
double sx = 0.0;
double sy = 0.0;
std::size_t n = 0;
double oldest_cmd = cmd_accum_;
double oldest_age = 0.0;
for (std::size_t k = 1; k <= pos_count_; ++k)
{
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
const double age = (s.now - p.t).toSec();
if (age > c.confine_window_s)
{
break;
}
sx += p.x;
sy += p.y;
++n;
oldest_cmd = p.cmd;
oldest_age = age;
}
if (n >= 2 && oldest_age >= c.confine_window_s - 0.5)
{
const double cx = sx / static_cast<double>(n);
const double cy = sy / static_cast<double>(n);
double radius = 0.0;
for (std::size_t k = 1; k <= n; ++k)
{
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
radius = std::max(radius, std::hypot(p.x - cx, p.y - cy));
}
region_radius_ = radius;
const double cmd = cmd_accum_ - oldest_cmd;
confined_ = radius < c.confine_radius &&
cmd >= c.confine_cmd_factor * std::max(2.0 * radius, c.disp_min);
}
}
}
v.net_disp = net_disp_;
v.wandering = wandering_;
v.idle = idle_;
v.confined = confined_;
v.region_radius = region_radius_;
// Mẫu nặng mới: ghi vào ring nếu có cost hữu hạn. +inf (mất liên thông tạm) không ghi — không kết
// luận từ mẫu thiếu.
if (s.geometry_valid && s.cost_conclusive && s.reachable && std::isfinite(s.cost_to_go))
{
// Lật liên thông: cost đổi nhiều hơn robot có thể đã đi trong một tick -> mặt nạ free vừa đóng/mở một khe,
// không phải tiến độ. Bắt đầu đo lại; kết luận kẹt cũ (nếu có) cũng không còn cơ sở.
if (c.jump_reject > 0.0 && has_prev_heavy_ &&
std::fabs(s.cost_to_go - prev_heavy_cost_) > c.jump_reject + (travel_total_ - prev_heavy_travel_))
{
clearWindow();
stall_seen_ = false;
stall_fired_ = false;
v.cost_jump = true;
}
has_prev_heavy_ = true;
prev_heavy_cost_ = s.cost_to_go;
prev_heavy_travel_ = travel_total_;
ring_[ring_head_] = HeavySample{ s.now, s.cost_to_go, cmd_accum_ };
ring_head_ = (ring_head_ + 1) % kRing;
ring_count_ = std::min(ring_count_ + 1, kRing);
HeavySample old;
if (oldestInWindow(s.now, old))
{
const double cmd = cmd_accum_ - old.cmd;
v.cmd_window = cmd;
if (cmd >= c.min_commanded)
{
v.eff_geo = (old.cost - s.cost_to_go) / cmd;
}
}
}
// Trượt: lệnh đi mà bánh không quay (vật thấp, bumper). Chỉ khi có v_meas.
bool slipping = false;
if (c.slip_on > 0.0 && std::isfinite(s.v_meas))
{
const bool slip_now = std::fabs(s.v_cmd) - std::fabs(s.v_meas) >= c.slip_on;
if (slip_now)
{
if (!slip_seen_)
{
slip_seen_ = true;
slip_since_ = s.now;
}
slipping = (s.now - slip_since_).toSec() >= c.slip_time;
}
else
{
slip_seen_ = false;
}
}
const bool grace = has_plan_time_ && (s.now - plan_time_).toSec() < config_.grace_after_new_plan;
const bool near_goal = std::isfinite(s.d_goal) && s.d_goal < c.goal_zone;
if (grace || near_goal)
{
stall_seen_ = false;
stall_fired_ = false;
return;
}
const bool eff_known = !std::isnan(v.eff_geo);
const bool stalled = (eff_known && v.eff_geo < c.eff_on) || slipping;
const bool cleared = eff_known && v.eff_geo >= c.eff_off && !slipping;
if (stalled)
{
if (!stall_seen_)
{
stall_seen_ = true;
stall_since_ = s.now;
}
if (!stall_fired_ && (s.now - stall_since_).toSec() >= c.confirm)
{
stall_fired_ = true;
v.event = slipping ? "stall: wheels slip against the command" : "stall: cost_to_go not decreasing";
}
}
else if (cleared)
{
if (stall_fired_)
{
v.event = "stall cleared: progress resumed";
}
stall_seen_ = false;
stall_fired_ = false;
}
// Còn lại (không đo được, hoặc eff trong vùng chết): giữ trạng thái — không kết luận ≠ hết kẹt.
// Đứng yên suốt idle_window_s, hoặc đi nhiều mà bị giam trong vùng nhỏ suốt confine_window_s, là kẹt kể cả
// khi geodesic không đo được (lệnh quá ít để có eff) hoặc đang lật dấu vì robot đi tới đi lui.
if ((idle_ || confined_) && !stall_fired_)
{
stall_fired_ = true;
stall_seen_ = true;
stall_since_ = s.now;
v.event = idle_ ? "stall: no net displacement for the idle window"
: "stall: confined to a small region while commanded";
}
v.stall_detected = stall_fired_;
if (!stall_fired_)
{
return;
}
// Cổng đầu chặng, ngân sách replan, backoff sau lượt hỏng.
bool muted = false;
if (has_goal_ && cmd_accum_ - cmd_at_goal_ < c.min_commanded_since_goal)
{
muted = true;
}
if (c.disp_min > 0.0)
{
// Cổng dịch chuyển thực thay ngân sách replan: cửa sổ vị trí đã bắt đầu lại ở plan mới, nên "sau detour
// vẫn quần tại chỗ disp_window_s" mới được nổ lại; né tự do (dịch chuyển >= disp_min) không bao giờ nổ.
if (!wandering_ && !idle_ && !confined_)
{
muted = true;
}
}
else if (has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_)
{
muted = true;
}
if (has_stall_backoff_ && s.now < stall_backoff_until_)
{
muted = true;
}
v.stall_muted = muted;
v.no_progress = !muted && c.action == "recover";
}
void EnvMonitor::updateUnreachable(const EnvSample& s, EnvVerdict& v)
{
const EnvMonitorConfig::Unreachable& c = config_.unreachable;
if (!c.enabled)
{
return;
}
// Trạng thái chỉ đổi ở tick nặng có kết luận; verdict thì phải ra MỖI cycle từ trạng thái, nếu
// không cờ nhấp nháy giữa hai tick 5 Hz và state machine 20 Hz thấy cờ bật/tắt.
if (s.geometry_valid && s.cost_conclusive)
{
// Baseline của plan: mẫu kết luận đầu tiên sau khi nhận plan. Plan đã không liên thông ngay từ
// đầu thì đó là chuyện của SBPL/planner đã lập nó — monitor không cãi trên cùng snapshot (R2).
if (baseline_pending_)
{
baseline_pending_ = false;
baseline_unreachable_ = !s.reachable;
}
if (s.reachable)
{
if (unreach_fired_)
{
v.event = "unreachable cleared: the exit is connected again";
}
unreach_seen_ = false;
unreach_fired_ = false;
baseline_unreachable_ = false; // từ đây mất liên thông là chuyện mới
}
else
{
const bool grace = has_plan_time_ && (s.now - plan_time_).toSec() < config_.grace_after_new_plan;
const bool clean = std::isfinite(s.edt_body_min) && s.edt_body_min >= c.clean_start_margin;
if (baseline_unreachable_ || grace || !clean)
{
// Không tích: chưa phải "xấu đi", hoặc robot đã lọt vành (SBPL không có chỗ bắt đầu — việc
// của kContact + controller_patience).
unreach_seen_ = false;
}
else
{
if (!unreach_seen_)
{
unreach_seen_ = true;
unreach_since_ = s.now;
}
if (!unreach_fired_ && (s.now - unreach_since_).toSec() >= c.static_on)
{
unreach_fired_ = true;
v.event = "unreachable: no path to the plan exit inside the window";
}
}
}
}
v.unreachable_detected = unreach_fired_;
if (!unreach_fired_)
{
return;
}
bool muted = false;
if (has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_)
{
muted = true;
}
if (has_unreach_backoff_ && s.now < unreach_backoff_until_)
{
muted = true;
}
v.unreachable_muted = muted;
v.path_blocked = !muted && c.action == "recover";
}
void EnvMonitor::updateContact(const EnvSample& s, EnvVerdict& v)
{
const EnvMonitorConfig::Contact& c = config_.contact;
if (!c.enabled)
{
return;
}
double v_ref = std::fabs(s.v_cmd);
if (std::isfinite(s.v_meas))
{
v_ref = std::max(v_ref, std::fabs(s.v_meas));
}
v.brake_dist = v_ref * v_ref / (2.0 * c.brake_decel);
if (!s.contact_conclusive || !s.costmap_current)
{
// Không biết thì không dừng, cũng không xoá chuỗi (cùng hợp đồng với guard cũ).
v.brake = braking_; // đang phanh thì giữ phanh tới khi có bằng chứng ngược lại
return;
}
if (standdown_)
{
// Đang đứng ra: không phanh, không cờ, không bao. Chỉ theo dõi điều kiện vũ trang lại.
v.contact_standdown = true;
if (std::isfinite(s.traj_contact_dist))
{
standdown_clean_streak_ = 0;
}
else
{
++standdown_clean_streak_;
}
const bool travelled = travel_total_ - standdown_mark_travel_ >= c.standdown_travel;
if (travelled || standdown_clean_streak_ >= c.release_confirm_cycles)
{
standdown_ = false;
standdown_clean_streak_ = 0;
v.contact_standdown = false;
v.event = travelled ? "contact: re-armed after moving on" : "contact: re-armed, the trajectory is clear";
}
return;
}
if (!std::isfinite(s.traj_contact_dist))
{
contact_streak_ = 0;
if (braking_ && ++release_streak_ < c.release_confirm_cycles)
{
// Một mẫu sạch chưa là sạch: local planner đổi quỹ đạo mỗi cycle, sạch 1 cycle rồi chạm lại là
// chuyện thường (run 5/9 22:35: 4 lần nhả/phanh trong 3 s). Giữ phanh và cờ tới khi sạch liên tiếp.
v.brake = true;
v.collision = contact_fired_ && c.action == "recover";
return;
}
if (braking_ || contact_fired_)
{
v.event = "contact cleared: the trajectory is free again";
}
braking_ = false;
release_streak_ = 0;
contact_close_ = false;
contact_fired_ = false;
return;
}
// Bao tốc độ: |v| <= sqrt(2 a (d - margin)) để luôn còn dừng được trên đất sạch.
// Bao giữ thêm envelope_margin so với ngưỡng phanh: lệnh nằm trên bao thì quãng phanh còn dư đúng chừng
// đó, nhiễu quỹ đạo vài cm không đẩy sang "sắp chạm". Trong margin thì 0; giữa margin và margin+dư thì bò
// min_speed.
if (c.envelope)
{
if (s.traj_contact_dist <= c.clean_start_margin)
{
v.v_cap = 0.0;
}
else
{
const double room = s.traj_contact_dist - c.clean_start_margin - c.envelope_margin;
v.v_cap = std::max(c.min_speed, room > 0.0 ? std::sqrt(2.0 * c.brake_decel * room) : 0.0);
}
}
// Xoay tại chỗ / bò mà monitor chưa phanh: quỹ đạo local planner lúc này là một cú xoay, góc thân
// quét vào ô kề bên là chuyện của controller (nó tự kiểm footprint), không phải bài toán quãng phanh.
// Phanh ở đây là chặn robot xoay ra khỏi vật đang kề mũi, rồi 1 s sau giơ cờ và gọi detour từ đúng
// chỗ đứng — vòng churn đầu chặng của guard cũ (mission 5/6 shadow 5/9). Đã phanh rồi thì vẫn xét
// tiếp để "kề mũi đứng yên" còn nổ được.
double v_intent = v_ref;
if (std::isfinite(s.v_controller))
{
v_intent = std::max(v_intent, std::fabs(s.v_controller));
}
if (v_intent < c.min_check_speed && !braking_)
{
contact_streak_ = 0;
release_streak_ = 0;
contact_close_ = false;
contact_fired_ = false;
return;
}
// Hai câu hỏi khác nhau:
// - "sắp chạm" = còn dừng kịp không (theo quãng phanh) -> PHANH. Đứng lại rồi thì quãng phanh về 0
// và câu này tự hết đúng, robot được bò tiếp dưới bao tốc độ.
// - "đang kề vật" = tiếp xúc trong đúng clean_start_margin bất kể tốc độ -> nếu còn đó đủ
// trigger_static_time thì vật đứng yên trước mũi, không phải người đi qua -> giơ CỜ.
// Bao tốc độ đặt lệnh đúng lên biên v_cap = sqrt(2a(d - margin)), tức d - quãng phanh == margin: nếu
// "sắp chạm" là <= thì mỗi lần bao kẹp xong là phanh, nhả, kẹp, phanh (chattering 4 cycle). Chỉ phanh
// khi vượt bao quá 1 mm — lệnh nằm trên bao là đang giảm tốc đúng luật, không phải sắp chạm.
// Trong margin thì bao đã là 0: đó là một cú dừng của monitor dù quãng phanh bằng 0 — phải được gọi
// là phanh để có sự kiện, để giữ 0 tức thì qua trọng tài và để cổng xoay không nuốt nó.
constexpr double kEnvelopeTol = 1e-3; // [m]
// Đã kề thì còn kề tới margin + release_hysteresis: quỹ đạo nhảy 0,08 <-> 0,25 m quanh margin không
// được reset đồng hồ giơ cờ, cũng không được nhả phanh.
const double close_limit = c.clean_start_margin + (contact_close_ ? c.release_hysteresis : 0.0);
const bool close = s.traj_contact_dist <= close_limit;
const bool imminent = close || s.traj_contact_dist - v.brake_dist < c.clean_start_margin - kEnvelopeTol;
v.contact_imminent = imminent;
if (imminent)
{
release_streak_ = 0;
++contact_streak_;
if (!braking_ && contact_streak_ >= c.confirm_cycles)
{
if (c.standdown_min_travel > 0.0 && detour_from_contact_ &&
travel_total_ - detour_mark_travel_ < c.standdown_min_travel)
{
// Vừa detour từ đúng chỗ này vì chính cú chạm này, robot chưa rời chỗ: phanh + cờ lần nữa chỉ lặp
// lại churn (3 detour rồi ABORT). Nhường controller — nó là lưới an toàn duy nhất tới khi robot đi
// được standdown_travel hoặc quỹ đạo sạch.
standdown_ = true;
standdown_mark_travel_ = travel_total_;
standdown_clean_streak_ = 0;
detour_from_contact_ = false;
contact_streak_ = 0;
release_streak_ = 0;
contact_close_ = false;
contact_fired_ = false;
v.contact_standdown = true;
v.contact_imminent = false;
v.v_cap = std::numeric_limits<double>::infinity();
v.event = "contact: standing down — the detour from this spot did not move the robot, the controller "
"is the only safety net until it travels on";
return;
}
braking_ = true;
v.event = "contact: braking to zero";
}
}
else
{
contact_streak_ = 0;
if (braking_ && ++release_streak_ >= c.release_confirm_cycles)
{
braking_ = false;
release_streak_ = 0;
v.event = "contact receded: releasing the brake";
}
}
v.brake = braking_;
if (close)
{
if (!contact_close_)
{
contact_close_ = true;
close_since_ = s.now;
}
if (!contact_fired_ && (s.now - close_since_).toSec() >= c.trigger_static_time)
{
contact_fired_ = true;
v.event = "contact persists while stopped: asking for a replan";
}
}
else
{
if (contact_fired_)
{
v.event = "contact cleared: the obstacle moved away";
}
contact_close_ = false;
contact_fired_ = false;
}
v.collision = contact_fired_ && c.action == "recover";
}
} // namespace move_base2

View File

@@ -121,7 +121,7 @@ bool EnvLogger::open(const EnvLoggerConfig& config, std::string& error)
return true;
}
void EnvLogger::record(const robot::Time& now, const EnvSample& s, const EnvVerdict& v,
void EnvLogger::record(const robot::Time& now, const env_monitor_core::EnvSample& s, const env_monitor_core::EnvVerdict& v,
const EnvGeometry* g, const char* state, std::uint64_t mission_id,
bool used_local_plan)
{
@@ -174,6 +174,10 @@ void EnvLogger::record(const robot::Time& now, const EnvSample& s, const EnvVerd
appendField(o, "brake", v.brake);
appendField(o, "contact_standdown", v.contact_standdown);
appendField(o, "cost_jump", v.cost_jump);
appendField(o, "pose_jump", v.pose_jump);
appendField(o, "pose_jump_restart", v.pose_jump_restart);
appendField(o, "pose_jump_dist", v.pose_jump_dist);
appendField(o, "progress_proven", v.progress_proven);
appendField(o, "no_progress", v.no_progress);
appendField(o, "path_blocked", v.path_blocked);
appendField(o, "collision", v.collision);

View File

@@ -276,6 +276,12 @@ void SensorGateway::pushStaticMap(const std::string& name, const robot_nav_msgs:
}
ScopedSection timer(telemetry_, section_static_map_);
// DirectionalLayer TRƯỚC StaticLayer, có chủ đích. Layer tự lọc theo topic: map_topic chỉ đưa nó về
// PENDING (không cần geometry), direction_topic là grid hướng (StaticLayer bỏ qua, nên trong cùng
// lần gọi không có resize nào). Nếu StaticLayer nhận map trước, giữa hai lần dispatch updateMap có
// thể ghi xong map mới và StaticLayer báo current trong khi field hướng cũ vẫn READY — planner kiểm
// readiness đúng lúc đó sẽ plan theo map mới với zone cũ. Chỉ global costmap có layer này.
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::DIRECTIONAL_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::STATIC_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::PREFERRED_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::UNPREFERRED_LAYER, name, stats_);

View File

@@ -78,6 +78,20 @@ double yawOfPose(const robot_geometry_msgs::PoseStamped& pose)
}
} // namespace
bool CostmapEnvironment::sampleFootprint(std::vector<std::pair<double, double>>& out)
{
if (!costmap_ || !costmap_->getCostmap()) return false;
const auto& footprint = costmap_->getUnpaddedRobotFootprint();
if (footprint.size() < 3) return false;
out.clear();
for (const auto& point : footprint)
{
if (!std::isfinite(point.x) || !std::isfinite(point.y)) return false;
out.emplace_back(point.x, point.y);
}
return true;
}
robot_costmap_2d::Costmap2D* CostmapEnvironment::gridForRead(bool& live) const
{
live = true;
@@ -453,6 +467,7 @@ bool NavigationRuntime::buildRunners(std::string& error)
// Behavior họ path (DetourPathRecovery) lập đường vòng trên local costmap (frame odom) trong khi
// plan ở frame map — cần TF để quy đổi hai chiều.
recovery_deps.tf = tf_.get();
recovery_deps.sensors = sensors_; // setSensorReader() chạy trước buildRunners() (navigation_server.cpp)
recovery_.setDeps(recovery_deps);
recovery_.setNamespace(config_.recovery_namespace);
@@ -482,6 +497,23 @@ bool NavigationRuntime::buildRunners(std::string& error)
// Ràng buộc thứ tự khởi tạo — xem doc của lớp. Con số này KHÔNG đến từ YAML.
config_.state_machine.recovery_behavior_count = recovery_.behaviorCount();
// --- 4b. EnvMonitor ----------------------------------------------------------------------------
//
// Lõi và các detector plugin tự đọc khối `env_monitor` dưới root_nh (gói env_monitor_core). Detector không nạp
// được (thiếu library_path, lệch ABI) đã được log LỖI và bỏ qua bên trong; tham số sai thì từ chối khởi động,
// như trước khi tách gói.
if (!env_monitor_.initialize(root_nh, error))
{
error = "invalid env_monitor parameters: " + error;
return false;
}
env_monitor_core::EnvContext env_context;
env_context.tf = tf_.get();
env_context.sensors = sensors_;
env_context.fixed_frame = local_costmap_->getGlobalFrameID();
env_context.base_frame = local_costmap_->getBaseFrameID();
env_monitor_.setContext(env_context);
// --- 5. Action ---------------------------------------------------------------------------------
action_.setClock(&clock_);
action_.setNamespace(config_.action_namespace);
@@ -642,6 +674,7 @@ ControlLoopDeps NavigationRuntime::deps()
deps.action = &action_;
deps.costmap_status = &costmap_status_;
deps.environment = &environment_;
deps.env_monitor = &env_monitor_;
deps.components = &components_;
return deps;
}

View File

@@ -11,6 +11,7 @@
#include <move_base2/io/sensor_store_types.h>
#include <robot_sensor_ports/sensor_writer.h>
#include <algorithm>
#include <cmath>
#include <mission_adapters/mission_request.h>
@@ -181,23 +182,41 @@ void NavigationServer::attachCostmaps(robot_costmap_2d::LayeredCostmap* global,
// Phát lại static map đã nhận trước khi costmap tồn tại. Chỉ static map, cố ý: một laser scan cũ
// phát lại vào costmap là dựng vật cản ở chỗ robot có thể đã rời khỏi từ lâu — im lặng và nguy
// hiểm hơn hẳn việc chờ mẫu kế tiếp, vốn chỉ cách vài chục ms.
std::map<std::string, robot_nav_msgs::OccupancyGrid> maps;
using ReplayEntry = std::pair<std::uint64_t,
std::pair<std::string, robot_nav_msgs::OccupancyGrid>>;
std::vector<ReplayEntry> maps;
std::pair<std::string, robot_nav_msgs::OccupancyGrid> legacy_map;
bool has_legacy_map = false;
{
std::lock_guard<std::mutex> lock(data_mutex_);
maps = static_maps_;
maps.reserve(static_maps_.size());
for (const auto& entry : static_maps_)
{
maps.push_back({ static_map_sequences_.at(entry.first), entry });
}
// `map_save_`/`map_name_save_` là cặp biến PUBLIC của BaseNavigation mà host tự gán (đường bù
// của bản cũ cho đúng vấn đề này). Tôn trọng nó để host không phải sửa gì, nhưng không để nó
// ghi đè bản đã đi qua addStaticMap.
if (!map_name_save_.empty() && maps.find(map_name_save_) == maps.end())
if (!map_name_save_.empty() && static_maps_.find(map_name_save_) == static_maps_.end())
{
maps[map_name_save_] = map_save_;
legacy_map = { map_name_save_, map_save_ };
has_legacy_map = true;
}
}
// The static map must precede its direction grid: the app must resend the direction grid
// immediately after every static map. Replaying by topic name would reverse that order.
std::sort(maps.begin(), maps.end(), [](const ReplayEntry& a, const ReplayEntry& b) {
return a.first < b.first;
});
if (has_legacy_map)
{
sensors_.pushStaticMap(legacy_map.first, legacy_map.second);
}
for (const auto& entry : maps)
{
sensors_.pushStaticMap(entry.first, entry.second);
sensors_.pushStaticMap(entry.second.first, entry.second.second);
}
}
@@ -693,6 +712,7 @@ void NavigationServer::addStaticMap(const std::string& topic, robot_nav_msgs::Oc
{
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_[topic] = map;
static_map_sequences_[topic] = ++next_static_map_sequence_;
}
sensors_.pushStaticMap(topic, map);
}
@@ -825,6 +845,7 @@ bool NavigationServer::removeStaticMap(const std::string& topic)
sensor_store_.clearTopic(topic);
std::lock_guard<std::mutex> lock(data_mutex_);
static_map_sequences_.erase(topic);
return static_maps_.erase(topic) > 0;
}
@@ -866,6 +887,7 @@ bool NavigationServer::removeAllStaticMaps()
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_.clear();
static_map_sequences_.clear();
return true;
}
@@ -906,6 +928,7 @@ bool NavigationServer::removeAllData()
{
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_.clear();
static_map_sequences_.clear();
laser_scans_.clear();
point_clouds_.clear();
point_cloud2s_.clear();

View File

@@ -111,6 +111,8 @@ const char* toString(RecoveryTrigger trigger)
return "off_path";
case RecoveryTrigger::kCollision:
return "collision";
case RecoveryTrigger::kDetector:
return "detector";
}
return "unknown";
}
@@ -131,8 +133,51 @@ const std::vector<std::size_t>& RecoveryRoutes::forTrigger(RecoveryTrigger trigg
return off_path;
case RecoveryTrigger::kCollision:
return collision;
case RecoveryTrigger::kDetector:
break; // route của detector đi theo tên (find), không theo trigger
}
static const std::vector<std::size_t> kNone;
return kNone;
}
const std::vector<std::size_t>* RecoveryRoutes::find(const std::string& name) const
{
if (name == "planning_failed")
{
return &planning_failed;
}
if (name == "controlling_failed")
{
return &controlling_failed;
}
if (name == "oscillation")
{
return &oscillation;
}
if (name == "path_blocked")
{
return &path_blocked;
}
if (name == "off_path")
{
return &off_path;
}
if (name == "collision")
{
return &collision;
}
const auto it = named.find(name);
return it == named.end() ? nullptr : &it->second;
}
void RecoveryRoutes::fillLegacy(std::size_t behavior_count)
{
for (std::size_t index = 0; index < behavior_count; ++index)
{
planning_failed.push_back(index);
controlling_failed.push_back(index);
oscillation.push_back(index);
}
return planning_failed;
}
bool RecoveryRoutes::empty() const

View File

@@ -8,7 +8,9 @@
*********************************************************************/
#include <move_base2/runners/planner_runner.h>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <exception>
#include <utility>
@@ -19,12 +21,51 @@
#include <robot/plugin_loader_helper.h>
#include <robot/robot.h>
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_costmap_2d/direction_field.h>
#include <robot_costmap_2d/layer.h>
#include <robot_costmap_2d/layered_costmap.h>
namespace move_base2
{
namespace
{
// Called with the master mutex held. Direction providers own a separate mutex, so their
// snapshot is the race-free equivalent of Layer::isCurrent() for those layers.
bool costmapReady(robot_costmap_2d::LayeredCostmap& costmap, std::string* stale_names)
{
const auto& layers = *costmap.getPlugins();
std::size_t providers = 0;
for (const auto& layer : layers)
if (layer && layer->isEnabled() &&
dynamic_cast<const robot_costmap_2d::DirectionFieldProvider*>(layer.get()))
++providers;
bool ready = true;
if (stale_names)
stale_names->clear();
for (const auto& layer : layers)
{
if (!layer || !layer->isEnabled())
continue;
const auto* provider = dynamic_cast<const robot_costmap_2d::DirectionFieldProvider*>(layer.get());
const bool current = provider
? providers == 1 && provider->directionSnapshot().state != robot_costmap_2d::DirectionFieldState::kPending
: layer->getType() != robot_costmap_2d::LayerType::DIRECTIONAL_LAYER && layer->isCurrent();
if (!current)
{
ready = false;
if (stale_names)
{
if (!stale_names->empty())
stale_names->append(", ");
stale_names->append(layer->getName());
}
}
}
return ready;
}
/// @brief Pose có dùng được để lập plan không — NaN/Inf lọt vào SBPL là hỏng ở tầng khó truy nhất.
bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose)
{
@@ -48,17 +89,22 @@ bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose)
/// `dock_face_offset` và `dock_pivot_safety_margin` là override DockPlanner chỉ có tác dụng với
/// `dock_anchor: mating_edge`; khai với `center` hoặc `face` khiến DockPlanner từ chối khởi tạo.
/// Nếu marker sau không khai, giá trị cũ được đặt YAML null để plugin trở về mặc định.
/// `dock_straight_length` overrides the terminal straight length for any dock anchor; it is
/// likewise cleared with YAML null when the next marker does not declare it.
/// `dock_maximum_cusp_distance` also applies to any anchor and is cleared the same way.
///
/// KHÔNG có `terminal_direction` ở đây, và cố ý như vậy: chiều chạy của đoạn thẳng cuối được SUY RA
/// từ phía robot đứng so với goal (`dock_calc.cpp`), vì tầng trên đã offset goal sao cho base_link
/// dừng đúng tại đó khi manơ hoàn tất. Một khoá cho phép marker ép chiều khác sẽ mâu thuẫn với
/// chính vị trí goal, nên khoá đó đã được gỡ thay vì hiện thực.
constexpr const char* kMarkerPlannerParams[] = {
"footprint_dock", "dock_anchor", "dock_face_offset", "dock_pivot_safety_margin"
"footprint_dock", "dock_anchor", "dock_face_offset", "dock_pivot_safety_margin",
"dock_straight_length", "dock_maximum_cusp_distance"
};
constexpr const char* kOptionalMarkerPlannerParams[] = {
"dock_face_offset", "dock_pivot_safety_margin"
"dock_face_offset", "dock_pivot_safety_margin", "dock_straight_length",
"dock_maximum_cusp_distance"
};
/**
@@ -430,6 +476,9 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
// Thread chưa nhận: rút yêu cầu ra, kẻo nó chạy yêu cầu của planner cũ trên instance mới rồi
// vứt — tốn một lượt makePlan vô ích.
pending_ = false;
waiting_for_costmap_ = false;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
request_order_.reset();
}
else if (running_)
@@ -445,6 +494,7 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
}
active_ = planner;
active_external_grid_ = external_grid ? &external_grid : nullptr;
cv_.notify_all();
}
active_name_ = planner_name;
@@ -510,6 +560,9 @@ bool PlannerRunner::startPlan(const robot_geometry_msgs::PoseStamped& start,
pending_ = true;
discard_ = false;
has_result_ = false;
waiting_for_costmap_ = costmap_lock_enabled_ && costmap_ready_timeout_ > 0.0;
if (waiting_for_costmap_ && status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kWaitingForCostmap);
cv_.notify_one();
return true;
@@ -521,6 +574,20 @@ bool PlannerRunner::isPlanning() const
return pending_ || running_;
}
void PlannerRunner::setCostmapReadyTimeout(double seconds)
{
std::lock_guard<std::mutex> lock(mutex_);
costmap_ready_timeout_ = seconds;
}
bool PlannerRunner::costmapWaitState(bool& finished)
{
std::lock_guard<std::mutex> lock(mutex_);
finished = costmap_wait_finished_;
costmap_wait_finished_ = false;
return waiting_for_costmap_;
}
bool PlannerRunner::pollPlan(PlanResult& result)
{
std::lock_guard<std::mutex> lock(mutex_);
@@ -567,6 +634,9 @@ void PlannerRunner::cancelPlan()
// sẽ nhận job này NGAY SAU cancel, chạy trọn allocated_time cho một plan không ai cần (bắt được
// bằng test CancelPreemptsAPreemptablePlannerWithinMilliseconds, 2026-09-11).
pending_ = false;
waiting_for_costmap_ = false;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
request_order_.reset();
}
else if (pending_ || running_)
@@ -588,6 +658,7 @@ void PlannerRunner::cancelPlan()
// Kết quả đã nằm sẵn trong hộp thư cũng bỏ luôn: bên gọi vừa nói nó không còn cần plan này.
has_result_ = false;
handoff_.clear();
cv_.notify_all();
}
// ================================================================================================
@@ -617,15 +688,16 @@ void PlannerRunner::threadBody()
// control thread không bao giờ phải chờ một lượt lập plan.
robot_nav_core::BaseGlobalPlanner* planner = active_;
const ExternalGridSetter* external_grid = active_external_grid_;
running_planner_ = planner;
running_planner_ = nullptr;
const robot_geometry_msgs::PoseStamped start = request_start_;
const robot_geometry_msgs::PoseStamped goal = request_goal_;
const std::shared_ptr<robot_protocol_msgs::Order> order = request_order_;
const std::uint64_t tag = request_tag_;
const double ready_timeout = costmap_ready_timeout_;
pending_ = false;
running_ = true;
if (status_board_ != nullptr)
if (status_board_ != nullptr && !waiting_for_costmap_)
{
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
}
@@ -634,10 +706,10 @@ void PlannerRunner::threadBody()
planning_.clear();
bool ok = false;
bool waited = false;
try
{
ScopedSection timer(stats_, section_make_plan_);
// Planner phải thấy một lưới ĐÔNG CỨNG suốt makePlan: LayeredCostmap::updateMap ghi lưới, và
// resizeMap REALLOC cả mảng, dưới Costmap2D::getMutex(). Hai cách đạt được điều đó:
//
@@ -650,32 +722,118 @@ void PlannerRunner::threadBody()
// đứng chờ hết lượt search; với SBPL cạn search trên map lớn là 6-14 s (đo 2026-09-17).
// Đây là đường rơi về khi tắt snapshot hoặc plugin không nhận lưới ngoài.
//
// Kiểm "costmap đã sẵn sàng" (P4, Test/docs/DIRECTION_ZONE_PLAN.md mục 7.3) chạy dưới CÙNG lần
// khoá đó, nên lưới planner đọc chính là lưới vừa được xác nhận current. Chưa current thì nhả
// khoá, chờ có hạn `costmap_ready_timeout` rồi kiểm lại; không gọi makePlan trên map dở dang.
//
// Lấy getCostmap() mỗi lượt, không cache — con trỏ đó có thể bị thay (bài học double-free của
// workspace). Với capability có mà snapshot TẮT, vẫn gọi setter với nullptr: xoá lưới ngoài
// còn sót từ cấu hình trước, để planner đọc lưới sống dưới khoá dài đúng như (b).
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
if (costmap_lock_enabled_)
using Clock = std::chrono::steady_clock;
Clock::time_point wait_started;
std::string& stale_names = costmap_stale_names_;
while (true)
{
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
const bool has_setter = external_grid != nullptr && static_cast<bool>(*external_grid);
if (has_setter && costmap_->isSnapshotEnabled())
const bool use_snapshot = costmap_lock_enabled_ && has_setter && costmap_->isSnapshotEnabled();
if (costmap_lock_enabled_)
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*costmap_->getCostmap()->getMutex());
// updateMap and StaticLayer callbacks use this same master mutex. For a snapshot, the
// recursive mutex remains held across both readiness and refreshSnapshot's copy. For a
// live grid it stays held through makePlan. Direction providers use their own snapshot lock.
if (costmap_lock_enabled_ && ready_timeout > 0.0 && !costmap_stale_names_reserved_)
{
std::size_t capacity = 0;
for (const auto& layer : *costmap_->getLayeredCostmap()->getPlugins())
if (layer) capacity += layer->getName().size() + 2;
stale_names.reserve(capacity);
costmap_stale_names_reserved_ = true;
}
const bool ready = !costmap_lock_enabled_ || ready_timeout == 0.0 ||
costmapReady(*costmap_->getLayeredCostmap(), &stale_names);
const auto now = Clock::now();
if (!ready && !waited)
{
waited = true;
wait_started = now;
if (!costmap_wait_problem_active_)
{
costmap_wait_problem_active_ = true;
last_costmap_wait_log_ = now;
robot::log_warning("[move_base2] PlannerRunner: waiting for global costmap; not current: %s\n",
stale_names.c_str());
}
}
const double elapsed = waited ? std::chrono::duration<double>(now - wait_started).count() : 0.0;
const CostmapReadyDecision decision = costmapReadyDecision(ready, elapsed, ready_timeout);
if (decision == CostmapReadyDecision::kTimeout)
{
if (last_costmap_timeout_log_ == Clock::time_point{} ||
std::chrono::duration<double>(now - last_costmap_timeout_log_).count() >= 5.0)
{
robot::log_error("[move_base2] PlannerRunner: global costmap readiness timed out after %.2f s; not current: %s\n",
elapsed, stale_names.c_str());
last_costmap_timeout_log_ = now;
}
break;
}
if (decision == CostmapReadyDecision::kWait)
{
if (std::chrono::duration<double>(now - last_costmap_wait_log_).count() >= 5.0)
{
robot::log_warning("[move_base2] PlannerRunner: still waiting for global costmap (%.2f s); not current: %s\n",
elapsed, stale_names.c_str());
last_costmap_wait_log_ = now;
}
costmap_lock.unlock();
lock.lock();
const double poll_seconds = std::min(0.05, ready_timeout - elapsed);
cv_.wait_for(lock, std::chrono::duration<double>(poll_seconds),
[this] { return shutdown_ || discard_; });
const bool cancelled = shutdown_ || discard_;
lock.unlock();
if (cancelled)
break;
continue;
}
if (use_snapshot)
{
costmap_->refreshSnapshot();
(*external_grid)(planner, costmap_->getCostmapForRead());
}
else
else if (costmap_lock_enabled_ && has_setter)
(*external_grid)(planner, nullptr);
lock.lock();
const bool cancelled = shutdown_ || discard_;
waiting_for_costmap_ = false;
costmap_wait_finished_ = costmap_wait_finished_ || waited;
if (!cancelled)
{
if (has_setter)
{
(*external_grid)(planner, nullptr);
}
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
running_planner_ = planner;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
}
lock.unlock();
if (cancelled)
break;
if (use_snapshot)
costmap_lock.unlock();
if (costmap_wait_problem_active_)
{
robot::log_info("[move_base2] PlannerRunner: global costmap is ready; planning resumes.\n");
costmap_wait_problem_active_ = false;
last_costmap_timeout_log_ = Clock::time_point{};
}
ScopedSection timer(stats_, section_make_plan_);
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
break;
}
// Hai overload của interface gốc gộp lại: "có Order hay không" là một nhánh, không phải hai
// contract. Plugin nào không hiểu Order thì overload mặc định của nó tự lo.
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
}
catch (const std::exception& ex)
{
@@ -701,6 +859,9 @@ void PlannerRunner::threadBody()
}
lock.lock();
if (waiting_for_costmap_ && waited)
costmap_wait_finished_ = true;
waiting_for_costmap_ = false;
running_ = false;
running_planner_ = nullptr;
if (status_board_ != nullptr)

View File

@@ -32,6 +32,9 @@ recovery_core::RecoveryTrigger toCoreTrigger(RecoveryTrigger trigger)
return recovery_core::RecoveryTrigger::kPathBlocked;
case RecoveryTrigger::kOffPath:
return recovery_core::RecoveryTrigger::kOffPath;
case RecoveryTrigger::kCollision:
case RecoveryTrigger::kDetector:
break; // recovery_core chưa có hai lý do này: kUnspecified (chỉ dùng để log)
}
return recovery_core::RecoveryTrigger::kUnspecified;
}
@@ -96,6 +99,7 @@ void RecoveryRunner::refreshContext()
ctx_.local_costmap = deps_.local_costmap;
ctx_.global_costmap = deps_.global_costmap;
ctx_.tf = deps_.tf;
ctx_.sensors = deps_.sensors;
}
bool RecoveryRunner::configure(robot::NodeHandle& nh)
@@ -220,6 +224,7 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
return false;
};
std::vector<std::string> named_keys;
for (const auto& entry : configured_routes)
{
if (!entry.first.IsScalar())
@@ -230,8 +235,7 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
const std::string key = entry.first.as<std::string>();
if (!is_expected_key(key))
{
error = routes_key + " has unsupported trigger '" + key + "'";
return false;
named_keys.push_back(key); // route theo detector (ví dụ `intrusion`): detector trỏ tới theo tên
}
}
@@ -250,6 +254,8 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
return &routes_.off_path;
case RecoveryTrigger::kCollision:
return &routes_.collision;
case RecoveryTrigger::kDetector:
break;
}
return &routes_.planning_failed;
};
@@ -262,9 +268,8 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
// (2026-08-05): cursor chỉ reset khi robot đi được quá oscillation_distance, nhưng giữa hai lần
// monitor bắn robot chỉ nhích được ~0.1-0.15 m, nên route không lặp thì cạn ngay sau một cặp
// [detour, wait] dù vật cản sắp vào tầm. Route vẫn hữu hạn — bế tắc thật vẫn ABORT được.
const auto resolve_route = [&](const char* trigger_name, RecoveryTrigger trigger,
const auto resolve_route = [&](const char* trigger_name, std::vector<std::size_t>* resolved,
const YAML::Node& route_node) {
std::vector<std::size_t>* resolved = route_for(trigger);
resolved->clear();
for (const YAML::Node& behavior_node : route_node)
@@ -300,7 +305,7 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
return false;
}
if (!resolve_route(expected.first, expected.second, route_node))
if (!resolve_route(expected.first, route_for(expected.second), route_node))
{
return false;
}
@@ -328,7 +333,7 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
return false;
}
if (!resolve_route(optional.first, optional.second, route_node))
if (!resolve_route(optional.first, route_for(optional.second), route_node))
{
return false;
}
@@ -343,6 +348,22 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
}
}
for (const std::string& key : named_keys)
{
const YAML::Node route_node = configured_routes[key];
if (!route_node.IsSequence())
{
error = routes_key + "/" + key + " must be a YAML sequence";
return false;
}
if (!resolve_route(key.c_str(), &routes_.named[key], route_node))
{
return false;
}
robot::log_info("[move_base2] RecoveryRunner: detector route '%s' resolved with %zu behavior(s).", key.c_str(),
routes_.named[key].size());
}
robot::log_info("[move_base2] RecoveryRunner: routes resolved: planning=%zu controlling=%zu "
"oscillation=%zu path_blocked=%zu off_path=%zu collision=%zu.",
routes_.planning_failed.size(), routes_.controlling_failed.size(),
@@ -509,6 +530,7 @@ RecoveryTick RecoveryRunner::toTick(const recovery_core::RecoveryResult& result)
// Nhánh này KHÔNG đạt tới được với state machine hiện tại: sau cancel() nó chuyển sang
// CANCELLING, nơi tick_recovery bị ép false. Giữ nhánh lại làm hàng rào nếu sau này ai đó nới
// điều kiện tick — bỏ đi thì kCancelled sẽ rơi vào default và im lặng thành kRunning.
// Recovery resume chuyển sang CONTROLLING cũng không tick lại behavior đã huỷ.
tick.status = RecoveryTick::Status::kFailed;
break;
case recovery_core::RecoveryStatus::kFailed:

View File

@@ -9,10 +9,16 @@
#include <move_base2/core/state_machine.h>
#include <algorithm>
#include <cmath>
#include <sstream>
namespace move_base2
{
namespace
{
/// Ô cursor 0..2 = trigger riêng của state machine (planning_failed, controlling_failed, oscillation); 3 + i = detector i.
constexpr std::size_t kOwnSlots = 3;
} // namespace
// ================================================================================================
// StateMachineConfig
@@ -20,6 +26,12 @@ namespace move_base2
bool StateMachineConfig::validate(std::string& error) const
{
if (recovery_resume_confirm_cycles < 1 || !std::isfinite(recovery_resume_min_speed) ||
recovery_resume_min_speed <= 0.0 || recovery_resume_max_per_leg < 0)
{
error = "invalid recovery resume confirmation, speed or leg quota";
return false;
}
// Các ngưỡng thời gian được phép <= 0 với nghĩa "tắt", nên không kiểm dấu ở đây. Thứ phải chặn là
// giá trị vô nghĩa: khoảng cách chống quẩn âm, và bật chống quẩn mà không cho khoảng cách nào.
if (sensor_patience < 0.0)
@@ -110,6 +122,20 @@ bool StateMachineConfig::validate(std::string& error) const
return false;
}
if (detector_routes.size() > 32)
{
error = "at most 32 detector routes (StateMachineInput::detector_fired is 32 bits)";
return false;
}
for (const DetectorRoute& d : detector_routes)
{
if (d.name.empty() || !indices_valid(d.route))
{
error = "detector route '" + d.name + "' has no name or references a behavior that was not loaded";
return false;
}
}
return true;
}
@@ -143,6 +169,10 @@ std::string StateMachineConfig::describe() const
: " (off — 'stopped' judged from the issued command)")
<< '\n';
out << " recovery_enabled : " << (recovery_enabled ? "true" : "false") << '\n';
out << " recovery_resume : enabled=" << recovery_resume_enabled << " behaviors=";
for (const auto& name : recovery_resume_behaviors) out << name << ' ';
out << "confirm=" << recovery_resume_confirm_cycles << " min_speed=" << recovery_resume_min_speed
<< " m/s max_per_leg=" << recovery_resume_max_per_leg << '\n';
out << " recovery_behavior_cnt : " << recovery_behavior_count << '\n';
if (recovery_routes.empty())
{
@@ -157,6 +187,11 @@ std::string StateMachineConfig::describe() const
<< " off_path=" << recovery_routes.off_path.size()
<< " collision=" << recovery_routes.collision.size() << '\n';
}
for (const DetectorRoute& d : detector_routes)
{
out << " detector " << d.name << " : route=" << toString(d.trigger) << " size=" << d.route.size()
<< (d.sequence ? " sequence" : " step") << (d.lock_on_exhausted ? " lock" : " abort") << '\n';
}
return out.str();
}
@@ -173,12 +208,7 @@ bool StateMachine::configure(const StateMachineConfig& config, std::string& erro
// chỉ xử lý route đã resolve.
if (config_.recovery_routes.empty())
{
for (std::size_t index = 0; index < config_.recovery_behavior_count; ++index)
{
config_.recovery_routes.planning_failed.push_back(index);
config_.recovery_routes.controlling_failed.push_back(index);
config_.recovery_routes.oscillation.push_back(index);
}
config_.recovery_routes.fillLegacy(config_.recovery_behavior_count);
}
if (!config_.validate(error))
@@ -187,6 +217,8 @@ bool StateMachine::configure(const StateMachineConfig& config, std::string& erro
return false;
}
recovery_route_cursors_.assign(kOwnSlots + config_.detector_routes.size(), 0);
monitor_trigger_suppressed_.assign(kOwnSlots + config_.detector_routes.size(), 0);
initialized_ = true;
reset();
return true;
@@ -202,10 +234,14 @@ void StateMachine::reset()
last_oscillation_reset_ = robot::Time();
sensor_stale_active_ = false;
recovery_index_ = 0;
recovery_resume_cycles_ = 0;
recovery_resumes_this_leg_ = 0;
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
state_before_recovery_ = NavigationState::kPlanning;
recovery_route_cursors_.fill(0);
monitor_trigger_suppressed_.fill(false);
std::fill(recovery_route_cursors_.begin(), recovery_route_cursors_.end(), 0);
std::fill(monitor_trigger_suppressed_.begin(), monitor_trigger_suppressed_.end(), 0);
active_slot_ = 0;
chain_active_ = false;
has_path_reset_mark_ = false;
travel_at_last_path_reset_ = 0.0;
planning_retries_ = 0;
@@ -242,6 +278,7 @@ void StateMachine::beginPlanningCycle(const robot::Time& now)
namespace
{
/// @brief Chỉ số cursor của một trigger. `switch` đầy đủ để compiler bắt khi enum thêm giá trị.
/// Ô cursor của trigger riêng của state machine. Detector i dùng ô kOwnSlots + i.
std::size_t cursorSlot(RecoveryTrigger trigger)
{
switch (trigger)
@@ -253,46 +290,63 @@ std::size_t cursorSlot(RecoveryTrigger trigger)
case RecoveryTrigger::kOscillation:
return 2;
case RecoveryTrigger::kPathBlocked:
return 3;
case RecoveryTrigger::kOffPath:
return 4;
case RecoveryTrigger::kCollision:
return 5;
case RecoveryTrigger::kDetector:
break; // chỉ detector giơ các lý do này; chúng đi escalateDetector với ô riêng
}
return 0;
}
/// Lý do chuyển state (chuỗi hằng, sống suốt chương trình) theo nhãn route của detector — giữ nguyên chữ cũ.
const char* detectorReason(RecoveryTrigger trigger)
{
switch (trigger)
{
case RecoveryTrigger::kCollision:
return "the body is about to hit an obstacle";
case RecoveryTrigger::kPathBlocked:
return "the path ahead is blocked";
case RecoveryTrigger::kOffPath:
return "the robot drifted off the plan";
case RecoveryTrigger::kOscillation:
return "no progress along the plan";
case RecoveryTrigger::kPlanningFailed:
case RecoveryTrigger::kControllingFailed:
case RecoveryTrigger::kDetector:
break;
}
return "a detector asked for recovery";
}
} // namespace
std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger)
const std::vector<std::size_t>& StateMachine::activeRoute() const
{
return recovery_route_cursors_[cursorSlot(trigger)];
}
const std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger) const
{
return recovery_route_cursors_[cursorSlot(trigger)];
}
bool StateMachine::isMonitorTrigger(RecoveryTrigger trigger)
{
return trigger == RecoveryTrigger::kPathBlocked || trigger == RecoveryTrigger::kOffPath ||
trigger == RecoveryTrigger::kCollision;
}
void StateMachine::suppressMonitorTrigger(RecoveryTrigger trigger, StateMachineOutput& out)
{
monitor_trigger_suppressed_[cursorSlot(trigger)] = true;
out.recovery_trigger = trigger;
out.monitor_trigger_suppressed = true;
return active_slot_ >= kOwnSlots ? config_.detector_routes[active_slot_ - kOwnSlots].route
: config_.recovery_routes.forTrigger(active_recovery_trigger_);
}
void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time& now,
const char* reason, StateMachineOutput& out)
{
const std::vector<std::size_t>& route = config_.recovery_routes.forTrigger(trigger);
const std::size_t cursor = recoveryRouteCursor(trigger);
escalate(cursorSlot(trigger), config_.recovery_routes.forTrigger(trigger), trigger, false, -1, now, reason, out);
}
void StateMachine::escalateDetector(std::size_t index, const robot::Time& now, StateMachineOutput& out)
{
const DetectorRoute& d = config_.detector_routes[index];
escalate(kOwnSlots + index, d.route, d.trigger, d.lock_on_exhausted, static_cast<int>(index), now,
detectorReason(d.trigger), out);
}
void StateMachine::escalate(std::size_t slot, const std::vector<std::size_t>& route, RecoveryTrigger trigger,
bool lock, int detector, const robot::Time& now, const char* reason,
StateMachineOutput& out)
{
const std::size_t cursor = recovery_route_cursors_[slot];
out.recovery_trigger = trigger;
out.recovery_detector = detector;
out.recovery_route_cursor = cursor;
out.recovery_route_size = route.size();
@@ -307,9 +361,11 @@ void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time
//
// Khoá trigger lại cho tới khi có tiến độ thật: không khoá thì monitor bắn lại sau mỗi
// confirm_time và mỗi lượt đốt vài trăm ms SBPL trên control thread mà không đổi được gì.
if (isMonitorTrigger(trigger))
// Từ 26/11 "dự báo" là thuộc tính của detector (`on_exhausted: lock`), không của tên trigger.
if (lock)
{
suppressMonitorTrigger(trigger, out);
monitor_trigger_suppressed_[slot] = 1;
out.monitor_trigger_suppressed = true;
return;
}
@@ -319,6 +375,11 @@ void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time
}
active_recovery_trigger_ = trigger;
recovery_resume_cycles_ = 0;
active_slot_ = slot;
chain_active_ = detector >= 0 && config_.detector_routes[static_cast<std::size_t>(detector)].sequence;
chain_pos_ = cursor;
chain_has_path_ = false;
// Nhớ state đã leo thang: nó quyết định đường quay về khi behavior kết thúc. Phải chụp TRƯỚC
// enter() bên dưới — sau đó state_ đã là kRecovering.
@@ -344,10 +405,13 @@ void StateMachine::finish(NavigationState terminal, NavigationOutcome outcome,
void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachineOutput& out)
{
out.accept_request = true;
recovery_resume_cycles_ = 0;
recovery_resumes_this_leg_ = 0;
recovery_index_ = 0;
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
state_before_recovery_ = NavigationState::kPlanning;
recovery_route_cursors_.fill(0);
std::fill(recovery_route_cursors_.begin(), recovery_route_cursors_.end(), 0);
chain_active_ = false;
request_has_goal_ = in.pending_request_has_goal;
action_count_ = in.pending_request_action_count;
action_index_ = 0;
@@ -375,7 +439,7 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
last_valid_control_ = in.now;
last_oscillation_reset_ = in.now;
sensor_stale_active_ = false;
monitor_trigger_suppressed_.fill(false);
std::fill(monitor_trigger_suppressed_.begin(), monitor_trigger_suppressed_.end(), 0);
has_path_reset_mark_ = false; // origin đo quãng đường đặt lại ngay dưới -> mốc cũ vô nghĩa
travel_at_last_path_reset_ = 0.0;
out.reset_oscillation_origin = true;
@@ -419,7 +483,8 @@ void StateMachine::resumeFromPause(const StateMachineInput& in, StateMachineOutp
last_oscillation_reset_ = in.now;
sensor_stale_active_ = false;
out.reset_oscillation_origin = true;
travel_at_last_path_reset_ = 0.0; // origin đặt lại -> mốc recovery_reset_min_travel về 0
// Giữ quãng đã đi từ lần nạp trước khi origin bắt đầu đếm lại từ 0.
travel_at_last_path_reset_ -= in.travelled_since_oscillation_reset;
if (state_before_pause_ == NavigationState::kControlling)
{
@@ -540,6 +605,13 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
break;
}
// Waiting for input is not planning time and must not consume the retry budget.
// The completion event also covers a wait which began and ended between control cycles.
if (in.planner_costmap_wait_finished || in.planner == PlannerFeedback::kWaitingForCostmap)
last_valid_plan_ = in.now;
if (in.planner == PlannerFeedback::kWaitingForCostmap)
break;
if (in.planner == PlannerFeedback::kPlanReady)
{
out.apply_plan = true;
@@ -624,7 +696,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
beginPlanningCycle(in.now);
// Tuyến khác thì hình thế khác — trigger giám sát tuyến được thử lại ngay, không phải chờ
// đủ oscillation_distance.
monitor_trigger_suppressed_.fill(false);
std::fill(monitor_trigger_suppressed_.begin(), monitor_trigger_suppressed_.end(), 0);
}
// Đi đủ xa thì không còn bị coi là quẩn — đặt lại cả đồng hồ lẫn mốc đo quãng đường.
@@ -638,12 +710,12 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
// gặp hai sự cố cách nhau nửa giờ sẽ ABORT thẳng ở sự cố thứ hai vì route đã cạn từ sự cố
// đầu. Mốc "đi được quá oscillation_distance" là thứ vòng lặp kẹt-recovery-nhích-kẹt không
// làm giả được, nên tính hữu hạn của chuỗi recovery vẫn giữ nguyên.
recovery_route_cursors_.fill(0);
std::fill(recovery_route_cursors_.begin(), recovery_route_cursors_.end(), 0);
// Cùng mốc tiến độ mở khoá trigger giám sát tuyến (2026-08-05e): robot đã đi được nửa mét
// nghĩa là hình thế đã khác, thử vòng lại là đáng. Đứng im vì bị chắn thì không bao giờ tới
// đây — đúng ý đồ: không đốt SBPL vào một tình huống chưa đổi.
monitor_trigger_suppressed_.fill(false);
std::fill(monitor_trigger_suppressed_.begin(), monitor_trigger_suppressed_.end(), 0);
// Origin vừa đặt lại nên travelled_since_oscillation_reset sẽ về 0 ở cycle sau; mốc của
// recovery_reset_min_travel phải đi theo, nếu không hiệu số âm sẽ khoá nạp lại vĩnh viễn.
@@ -682,42 +754,54 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
//
// Trigger đang bị KHOÁ (lượt trước đã hết đường vòng, robot chưa đi đủ oscillation_distance)
// thì bỏ qua hẳn nhánh này: bám tiếp plan cũ, để controller_patience làm việc của nó.
const bool collision_open =
in.collision && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kCollision)];
const bool blocked_open =
in.path_blocked && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kPathBlocked)];
const bool off_path_open =
in.off_path && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kOffPath)];
if (collision_open || blocked_open || off_path_open)
// Từ 26/11: nhóm này là các detector `on_exhausted: lock`, xét theo thứ tự danh sách detector (mặc định
// contact > unreachable — đúng collision > path_blocked ở trên). Chỉ detector mở đầu tiên được xét mỗi cycle.
bool forecast_escalated = false;
for (std::size_t i = 0; i < config_.detector_routes.size(); ++i)
{
const RecoveryTrigger trigger = collision_open ? RecoveryTrigger::kCollision
: blocked_open ? RecoveryTrigger::kPathBlocked
: RecoveryTrigger::kOffPath;
out.stop_planner = true;
escalateToRecovery(trigger, in.now,
collision_open ? "the body is about to hit an obstacle"
: blocked_open ? "the path ahead is blocked"
: "the robot drifted off the plan",
out);
// Hết đường vòng: escalateToRecovery đã khoá trigger thay vì ABORT — không đổi state, chạy
// tiếp xuống nhánh sinh lệnh của cycle này để robot không mất một nhịp điều khiển.
if (!out.monitor_trigger_suppressed)
const bool open = config_.detector_routes[i].lock_on_exhausted && ((in.detector_fired >> i) & 1u) != 0 &&
!monitor_trigger_suppressed_[kOwnSlots + i];
if (!open)
{
break;
continue;
}
out.stop_planner = false;
out.stop_planner = true;
escalateDetector(i, in.now, out);
// Hết đường vòng: escalate đã khoá trigger thay vì ABORT — không đổi state, chạy tiếp xuống nhánh sinh
// lệnh của cycle này để robot không mất một nhịp điều khiển.
if (out.monitor_trigger_suppressed)
{
out.stop_planner = false;
}
else
{
forecast_escalated = true;
}
break;
}
if (forecast_escalated)
{
break;
}
if (controller == ControllerFeedback::kCommandValid)
{
last_valid_control_ = in.now;
// kStall (EnvMonitor): controller vẫn ra lệnh hợp lệ nhưng robot không đi được đâu.
if (in.no_progress)
// kStall (EnvMonitor) và mọi detector `on_exhausted: abort`: controller vẫn ra lệnh hợp lệ nhưng robot
// không đi được đâu. Theo thứ tự danh sách detector; cạn route là ABORT.
bool escalated = false;
for (std::size_t i = 0; i < config_.detector_routes.size() && !escalated; ++i)
{
if (!config_.detector_routes[i].lock_on_exhausted && ((in.detector_fired >> i) & 1u) != 0)
{
out.stop_planner = true;
escalateDetector(i, in.now, out);
escalated = true;
}
}
if (escalated)
{
out.stop_planner = true;
escalateToRecovery(RecoveryTrigger::kOscillation, in.now, "no progress along the plan",
out);
break;
}
@@ -808,8 +892,58 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
break;
}
if (in.recovery == RecoveryFeedback::kRunning && recoveryResumeAvailable() &&
in.pose_available && in.costmap_current && in.recovery_probe_moving)
++recovery_resume_cycles_;
else
recovery_resume_cycles_ = 0;
if (recovery_resume_cycles_ >= config_.recovery_resume_confirm_cycles)
{
recovery_resume_cycles_ = 0;
++recovery_resumes_this_leg_;
recovery_route_cursors_[active_slot_] = 0;
chain_active_ = false;
last_valid_control_ = in.now;
sensor_stale_active_ = false;
last_oscillation_reset_ = in.now;
travel_at_last_path_reset_ -= in.travelled_since_oscillation_reset;
out.reset_oscillation_origin = true;
out.cancel_recovery = true;
out.recovery_resumed = true;
out.apply_plan = true;
enter(NavigationState::kControlling, in.now, "blockage cleared during recovery", out);
break;
}
if (in.recovery == RecoveryFeedback::kSucceeded || in.recovery == RecoveryFeedback::kFailed)
{
// route_mode sequence (chốt 26/11): một lần nổ chạy HẾT route. Behavior hỏng hay nộp path giữa chừng thì
// vẫn chạy tiếp behavior kế; path mới nhất được áp khi cả chuỗi xong (ControlLoop giữ nó tới lúc đó).
if (chain_active_)
{
chain_has_path_ = chain_has_path_ || (in.recovery == RecoveryFeedback::kSucceeded &&
in.planner == PlannerFeedback::kPlanReady);
const std::vector<std::size_t>& chain_route = activeRoute();
if (chain_pos_ + 1 < chain_route.size())
{
++chain_pos_;
recovery_index_ = chain_route[chain_pos_];
out.start_recovery = true;
out.recovery_index = recovery_index_;
out.recovery_trigger = active_recovery_trigger_;
out.recovery_detector = static_cast<int>(active_slot_ - kOwnSlots);
out.recovery_chain_continues = true;
break;
}
out.recovery_chain_finished = true;
out.recovery_chain_has_path = chain_has_path_;
out.recovery_chain_last_failed = in.recovery == RecoveryFeedback::kFailed;
}
// Từ đây cả chuỗi tính như MỘT behavior vừa xong: một lượt cursor, cùng ngoại lệ nạp lại khi có path mới.
const bool chain = chain_active_;
chain_active_ = false;
// Behavior chạy xong. Lỗi kế tiếp sẽ dùng behavior kế tiếp trong route; hết behavior thì
// ABORTED.
//
@@ -828,9 +962,10 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
// đó không giải quyết sự cố gì, nên nó ăn vào ngân sách như một lần thất bại: route cạn ->
// mute (05e) -> guard vẫn báo no_valid_command -> controller_patience -> controlling_failed
// -> cạn -> ABORT có lý do. Có dịch chuyển thật (0.45 m của ca 08-05) thì vẫn nạp lại như cũ.
const bool recovered_with_new_path = in.recovery == RecoveryFeedback::kSucceeded &&
in.planner == PlannerFeedback::kPlanReady;
std::size_t& cursor = recoveryRouteCursor(active_recovery_trigger_);
const bool recovered_with_new_path =
chain ? chain_has_path_
: in.recovery == RecoveryFeedback::kSucceeded && in.planner == PlannerFeedback::kPlanReady;
std::size_t& cursor = recovery_route_cursors_[active_slot_];
bool refill = false;
if (recovered_with_new_path)
{
@@ -847,18 +982,22 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
out.recovery_reset_denied = true;
out.recovery_reset_travel = std::max(0.0, travelled);
out.recovery_trigger = active_recovery_trigger_; // để bên gọi log đúng route bị trừ
out.recovery_detector = active_slot_ >= kOwnSlots ? static_cast<int>(active_slot_ - kOwnSlots) : -1;
}
}
const std::vector<std::size_t>& route = activeRoute();
if (refill)
{
cursor = 0;
}
else if (chain)
{
cursor = route.size(); // cả chuỗi là một lượt: lần nổ sau coi như route đã cạn
}
else
{
++cursor;
}
const std::vector<std::size_t>& route =
config_.recovery_routes.forTrigger(active_recovery_trigger_);
recovery_index_ = cursor < route.size() ? route[cursor] : config_.recovery_behavior_count;
// Đường quay về (contract 2026-08-04b — tách replan khỏi recovery hoàn toàn):
@@ -873,7 +1012,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
// việc riêng của replan nền theo `planner_frequency`.
// Riêng khi leo thang từ kPlanning (mất pose lúc lập plan) thì chưa từng có plan —
// quay về kPlanning như nhóm 2.
const bool has_detour_path = in.planner == PlannerFeedback::kPlanReady;
const bool has_detour_path = chain ? chain_has_path_ : in.planner == PlannerFeedback::kPlanReady;
const bool old_plan_valid =
active_recovery_trigger_ != RecoveryTrigger::kPlanningFailed &&
state_before_recovery_ == NavigationState::kControlling;
@@ -894,11 +1033,9 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
sensor_stale_active_ = false;
last_oscillation_reset_ = in.now;
out.reset_oscillation_origin = true;
// Origin đo quãng đường đặt lại ngay tại đây, nên từ cycle sau travelled đếm từ 0 kể từ
// đúng lúc path mới được áp — chính là quãng mà recovery_reset_min_travel muốn đo. Mốc phải
// về 0 theo (GIỮ has_path_reset_mark_): sim 4/9 mission 3 robot đi 0.18 m sau path mới mà
// vẫn bị tính "0.00 m" vì mốc còn giữ giá trị của origin cũ.
travel_at_last_path_reset_ = 0.0;
// Chuyển mốc sang origin mới để giữ quãng đã đi qua recovery không tạo path; nếu vừa
// nạp lại thì mốc vừa bằng travelled, phép chuyển đưa mốc về 0.
travel_at_last_path_reset_ -= in.travelled_since_oscillation_reset;
out.run_controller = true;
enter(NavigationState::kControlling, in.now,
has_detour_path ? "recovery produced a detour path"

View File

@@ -94,7 +94,8 @@ TEST(ComponentStatusBoard, EveryComponentAndPhaseHasAName)
EXPECT_NE(name, "unknown");
}
for (const ComponentPhase p : {ComponentPhase::kIdle, ComponentPhase::kBusy, ComponentPhase::kStopping,
ComponentPhase::kPaused, ComponentPhase::kHung})
ComponentPhase::kPaused, ComponentPhase::kHung,
ComponentPhase::kWaitingForCostmap})
{
const std::string name = move_base2::toString(p);
EXPECT_FALSE(name.empty());

View File

@@ -207,6 +207,17 @@ BackUpRecovery:
# GhostRecovery cố ý KHÔNG khai library_path.
# --- Detector của EnvMonitor (gói env_monitor_core) -------------------------------------------
# File này không có khối `env_monitor`: lõi dùng tham số mặc định và nạp 3 detector có sẵn, như trước khi tách gói.
ContactDetector:
library_path: libenv_monitor_core_contact_detector
StallDetector:
library_path: libenv_monitor_core_stall_detector
UnreachableDetector:
library_path: libenv_monitor_core_unreachable_detector
# --- Action handler cho action_runner_test -----------------------------------------------------
actions:
handlers:

View File

@@ -11,6 +11,7 @@
#include <gtest/gtest.h>
#include <cstdlib>
#include <limits>
#include <string>
#include <robot/node_handle.h>
@@ -55,6 +56,35 @@ TEST(MoveBase2Config, DefaultsAreValid)
EXPECT_TRUE(config.validate(error)) << error;
}
TEST(MoveBase2Config, CostmapReadyTimeoutValidation)
{
MoveBase2Config config = minimalValid();
std::string error;
EXPECT_DOUBLE_EQ(config.costmap_ready_timeout, 10.0);
EXPECT_DOUBLE_EQ(config.toControlLoopConfig().costmap_ready_timeout, 10.0);
EXPECT_NE(config.describe().find("costmap_ready_timeout"), std::string::npos);
config.costmap_ready_timeout = 0.0;
EXPECT_TRUE(config.validate(error));
for (double invalid : {-1.0, std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::quiet_NaN()})
{
config.costmap_ready_timeout = invalid;
EXPECT_FALSE(config.validate(error));
EXPECT_NE(error.find("costmap_ready_timeout"), std::string::npos);
}
}
TEST(MoveBase2Config, ReadsCostmapReadyTimeout)
{
robot::NodeHandle root;
robot::NodeHandle nh(root, "costmap_ready_timeout_test");
nh.setParam("costmap_ready_timeout", 3.5);
MoveBase2Config config;
config.fromNodeHandle(nh);
EXPECT_DOUBLE_EQ(config.costmap_ready_timeout, 3.5);
EXPECT_DOUBLE_EQ(config.toControlLoopConfig().costmap_ready_timeout, 3.5);
}
TEST(MoveBase2Config, CancelSettleKeysFallBackToDefaultsWhenAbsent)
{
// Cây config cũ (trước 2026-09-11) không có ba khoá này: phải giữ default BẬT (2 s, 0.02) chứ

View File

@@ -22,6 +22,7 @@
#include <move_base2/control_loop.h>
#include "env_monitor_fixture.h"
#include "fake_ports.h"
using move_base2::ControlLoop;
@@ -99,8 +100,11 @@ public:
deps_.action = &action_;
deps_.costmap_status = &costmap_status_;
deps_.environment = &environment_;
deps_.env_monitor = &env_monitor_;
std::string error;
EXPECT_TRUE(move_base2::testing::initEnvMonitor(env_monitor_, env_monitor_core::EnvMonitorConfig(), error))
<< error;
EXPECT_TRUE(loop_.configure(baseConfig(), deps_, error)) << error;
}
@@ -145,6 +149,7 @@ public:
}
private:
env_monitor_core::EnvMonitor env_monitor_; ///< trước loop_: loop_ giữ con trỏ tới nó
ControlLoop loop_;
ControlLoopDeps deps_;
FakeClockPort clock_;

View File

@@ -0,0 +1,57 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 tests — an EnvMonitor (env_monitor_core) built from an EnvMonitorConfig through the real YAML path:
* the struct becomes the `env_monitor` block under a fresh namespace, the three built-in detectors are loaded as
* .so from devel/lib, exactly as NavigationRuntime does.
*
* Author: DuongTD
*********************************************************************/
#ifndef MOVE_BASE2_TEST_ENV_MONITOR_FIXTURE_H_
#define MOVE_BASE2_TEST_ENV_MONITOR_FIXTURE_H_
#include <cstdlib>
#include <string>
#include <yaml-cpp/yaml.h>
#include <robot/node_handle.h>
#include <env_monitor_core/env_monitor.h>
#ifndef MOVE_BASE2_TEST_LIBRARY_DIR
#error "MOVE_BASE2_TEST_LIBRARY_DIR must be defined by CMake"
#endif
namespace move_base2
{
namespace testing
{
inline bool initEnvMonitor(env_monitor_core::EnvMonitor& monitor, const env_monitor_core::EnvMonitorConfig& config,
std::string& error)
{
static int counter = 0;
// devel/lib must win over a PNKX_NAV_CORE_LIBRARY_PATH left in the user's shell.
setenv("PNKX_NAV_CORE_LIBRARY_PATH", MOVE_BASE2_TEST_LIBRARY_DIR, 1);
robot::NodeHandle nh("move_base2_env_monitor_test_" + std::to_string(++counter));
const char* const kLibraries[][2] = {
{ "ContactDetector", "libenv_monitor_core_contact_detector" },
{ "StallDetector", "libenv_monitor_core_stall_detector" },
{ "UnreachableDetector", "libenv_monitor_core_unreachable_detector" },
};
for (const auto& lib : kLibraries)
{
YAML::Node node;
node["library_path"] = lib[1];
nh.setParam(lib[0], node);
}
nh.setParam("env_monitor", env_monitor_core::toYaml(config));
return monitor.initialize(nh, error);
}
} // namespace testing
} // namespace move_base2
#endif // MOVE_BASE2_TEST_ENV_MONITOR_FIXTURE_H_

File diff suppressed because it is too large Load Diff

View File

@@ -13,6 +13,7 @@
#include <chrono>
#include <cmath>
#include <cstddef>
#include <future>
#include <limits>
#include <string>
#include <thread>
@@ -195,7 +196,6 @@ public:
server_.attachCostmaps(&global_, &local_);
}
NavigationServer server_;
FakeClockPort clock_;
FakePosePort pose_;
FakePlannerPort planner_;
@@ -208,6 +208,10 @@ public:
robot_costmap_2d::LayeredCostmap global_;
robot_costmap_2d::LayeredCostmap local_;
// The server joins its control thread in its destructor. Declare it last so all borrowed
// ports, status data and costmaps outlive that join.
NavigationServer server_;
};
} // namespace
@@ -611,6 +615,74 @@ TEST(NavigationServerSensors, StaticMapReceivedBeforeAttachIsReplayed)
EXPECT_EQ(static_layer->records()[0].topic, "/map");
}
TEST(CostmapReadyDecision, ReadyWaitTimeoutAndLegacy)
{
using move_base2::CostmapReadyDecision;
using move_base2::costmapReadyDecision;
EXPECT_EQ(costmapReadyDecision(false, 0.0, 10.0), CostmapReadyDecision::kWait);
EXPECT_EQ(costmapReadyDecision(false, 9.99, 10.0), CostmapReadyDecision::kWait);
EXPECT_EQ(costmapReadyDecision(false, 10.0, 10.0), CostmapReadyDecision::kTimeout);
EXPECT_EQ(costmapReadyDecision(true, 3.0, 10.0), CostmapReadyDecision::kPlan);
EXPECT_EQ(costmapReadyDecision(false, 0.0, 0.0), CostmapReadyDecision::kPlan);
}
TEST(NavigationServerSensors, ReplayUsesLatestArrivalOrder)
{
Fixture fixture;
fixture.configure();
const robot_nav_msgs::OccupancyGrid grid;
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
SpyPtr layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "replay_spy");
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 2U);
EXPECT_EQ(layer->records()[0].topic, "/map");
EXPECT_EQ(layer->records()[1].topic, "/direction_map");
// The live pushes are followed by a second replay after both latest arrivals.
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 6U);
EXPECT_EQ(layer->records()[4].topic, "/map");
EXPECT_EQ(layer->records()[5].topic, "/direction_map");
}
TEST(NavigationServerSensors, ReplayForgetsErasedAndClearedSequences)
{
Fixture fixture;
fixture.configure();
const robot_nav_msgs::OccupancyGrid grid;
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
ASSERT_TRUE(fixture.server_.removeStaticMap("/map"));
fixture.server_.addStaticMap("/map", grid);
SpyPtr layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "replay_spy");
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 2U);
EXPECT_EQ(layer->records()[0].topic, "/direction_map");
EXPECT_EQ(layer->records()[1].topic, "/map");
ASSERT_TRUE(fixture.server_.removeAllStaticMaps());
fixture.server_.addStaticMap("/direction_map", grid);
const std::size_t before_clear_replay = layer->count();
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), before_clear_replay + 1U);
EXPECT_EQ(layer->records()[before_clear_replay].topic, "/direction_map");
ASSERT_TRUE(fixture.server_.removeAllData());
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
fixture.server_.map_name_save_ = "/legacy";
const std::size_t before_replay = layer->count();
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), before_replay + 3U);
EXPECT_EQ(layer->records()[before_replay].topic, "/legacy");
EXPECT_EQ(layer->records()[before_replay + 1].topic, "/map");
EXPECT_EQ(layer->records()[before_replay + 2].topic, "/direction_map");
}
TEST(NavigationServerSensors, LegacyMapSavePublicMemberIsAlsoReplayed)
{
// `map_save_`/`map_name_save_` là biến PUBLIC của BaseNavigation mà host tự gán
@@ -1203,12 +1275,33 @@ TEST(NavigationServerControlThread, SecondStartIsRefusedAndStopIsIdempotent)
TEST(NavigationServerControlThread, DestructorStopsTheThread)
{
// Thread chạm loop_, runtime_ và sensors_ mỗi cycle; huỷ chúng khi thread còn sống là hỏng ở chỗ
// không truy được.
Fixture fixture;
fixture.configure();
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
SUCCEED(); // destructor của fixture phải join, không treo
// Wait until a real cycle has begun; fixture destruction must join before its borrowed ports die.
class SignallingClock final : public move_base2::ClockPort
{
public:
explicit SignallingClock(std::promise<void>& started) : started_(started) {}
robot::Time now() const override
{
if (!signalled_.exchange(true))
started_.set_value();
return robot::Time(kClockStart);
}
private:
std::promise<void>& started_;
mutable std::atomic<bool> signalled_{false};
};
std::promise<void> started;
auto first_cycle = started.get_future();
SignallingClock clock(started);
{
Fixture fixture;
fixture.deps_.clock = &clock;
fixture.configure();
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
ASSERT_EQ(first_cycle.wait_for(std::chrono::seconds(2)), std::future_status::ready);
}
}
// ================================================================================================

View File

@@ -819,6 +819,86 @@ TEST(PlannerRunnerDockingMarker, CopiesAndClearsOptionalDockOverridesPerMarker)
EXPECT_EQ(pluginInitializeCount(), before + 3);
}
TEST(PlannerRunnerDockingMarker, CopiesAndClearsDockStraightLengthPerMarker)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
robot::NodeHandle nh;
nh.setParam("docking_marker_profiles/straight_override/dock_straight_length", 0.30);
nh.setParam("docking_marker_profiles/straight_default/global_planner",
YAML::Node("TestPlannerOk"));
nh.setParam("TestPlannerOk/terminal/straight_length", 0.40);
const std::size_t before = pluginInitializeCount();
ASSERT_TRUE(fixture.runner_.bindDockingMarker("straight_override", "TestPlannerOk"));
YAML::Node copied;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_straight_length", copied));
EXPECT_DOUBLE_EQ(copied.as<double>(), 0.30);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 1);
ASSERT_TRUE(fixture.runner_.bindDockingMarker("straight_default", "TestPlannerOk"));
YAML::Node cleared;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_straight_length", cleared));
EXPECT_TRUE(cleared.IsNull());
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 2);
ASSERT_TRUE(fixture.runner_.bindDockingMarker("straight_override", "TestPlannerOk"));
YAML::Node restored;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_straight_length", restored));
EXPECT_DOUBLE_EQ(restored.as<double>(), 0.30);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 3);
YAML::Node default_length;
ASSERT_TRUE(nh.getParam("TestPlannerOk/terminal/straight_length", default_length));
EXPECT_DOUBLE_EQ(default_length.as<double>(), 0.40);
}
TEST(PlannerRunnerDockingMarker, CopiesAndClearsDockMaximumCuspDistancePerMarker)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
robot::NodeHandle nh;
nh.setParam("docking_marker_profiles/cusp_override/dock_maximum_cusp_distance", 2.0);
nh.setParam("docking_marker_profiles/cusp_override/maneuver/maximum_cusp_distance", 9.0);
nh.setParam("docking_marker_profiles/cusp_default/global_planner", YAML::Node("TestPlannerOk"));
nh.setParam("TestPlannerOk/maneuver/maximum_cusp_distance", 3.0);
const auto check_default = [&nh]()
{
YAML::Node value;
ASSERT_TRUE(nh.getParam("TestPlannerOk/maneuver/maximum_cusp_distance", value));
EXPECT_DOUBLE_EQ(value.as<double>(), 3.0);
};
const std::size_t before = pluginInitializeCount();
ASSERT_TRUE(fixture.runner_.bindDockingMarker("cusp_override", "TestPlannerOk"));
YAML::Node copied;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_maximum_cusp_distance", copied));
EXPECT_DOUBLE_EQ(copied.as<double>(), 2.0);
check_default();
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 1);
ASSERT_TRUE(fixture.runner_.bindDockingMarker("cusp_default", "TestPlannerOk"));
YAML::Node cleared;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_maximum_cusp_distance", cleared));
EXPECT_TRUE(cleared.IsNull());
check_default();
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 2);
ASSERT_TRUE(fixture.runner_.bindDockingMarker("cusp_override", "TestPlannerOk"));
YAML::Node restored;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_maximum_cusp_distance", restored));
EXPECT_DOUBLE_EQ(restored.as<double>(), 2.0);
check_default();
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 3);
}
TEST(PlannerRunnerDockingMarker, EmptyMarkerOrPlannerNameIsANoOp)
{
Fixture fixture;

View File

@@ -152,6 +152,27 @@ TEST(SensorGateway, StaticMapArrivesWithOccupancyGridType)
EXPECT_TRUE(*layer->records()[0].type == typeid(robot_nav_msgs::OccupancyGrid));
}
TEST(SensorGateway, DirectionalLayerSeesAStaticMapBeforeTheStaticLayer)
{
// A same-geometry map must invalidate the old direction field before StaticLayer can be written
// and report current; otherwise a plan could pair the new map with the old zones (DIRECTION_ZONE_PLAN 5.3).
Bench bench;
std::vector<std::string> order;
SpyPtr static_layer = bench.addGlobal(LayerType::STATIC_LAYER, "navigation_map");
SpyPtr directional = bench.addGlobal(LayerType::DIRECTIONAL_LAYER, "direction_zones");
static_layer->setObserver([&](const void*, const std::type_info&, const std::string&) {
order.push_back("static");
});
directional->setObserver([&](const void*, const std::type_info&, const std::string&) {
order.push_back("directional");
});
bench.attach();
bench.gateway().pushStaticMap("/map", robot_nav_msgs::OccupancyGrid());
EXPECT_EQ(order, (std::vector<std::string>{"directional", "static"}));
}
TEST(SensorGateway, PointCloudAndPointCloud2AreDistinctTypes)
{
Bench bench;

View File

@@ -11,6 +11,8 @@
*********************************************************************/
#include <gtest/gtest.h>
#include <cstdint>
#include <string>
#include <move_base2/core/state_machine.h>
@@ -32,6 +34,38 @@ using move_base2::VelocitySource;
namespace
{
/// Bit của bốn detector mà các test dưới dùng, cùng nghĩa với bốn cờ cố định trước 26/11.
enum LegacyDetector : std::uint32_t
{
kCollisionBit = 1u << 0, ///< contact -> route collision, khoá
kBlockedBit = 1u << 1, ///< unreachable -> route path_blocked, khoá
kOffPathBit = 1u << 2, ///< off_path -> route off_path, khoá
kNoProgressBit = 1u << 3, ///< stall -> route oscillation, ABORT
};
/// Bốn detector theo đúng thứ tự ưu tiên cũ (collision > path_blocked > off_path; stall riêng nhánh controller).
void addLegacyDetectors(move_base2::StateMachineConfig& config)
{
if (config.recovery_routes.empty())
{
config.recovery_routes.fillLegacy(config.recovery_behavior_count);
}
const auto route = [](const char* name, const std::vector<std::size_t>& indices, bool lock, RecoveryTrigger trigger) {
move_base2::DetectorRoute r;
r.name = name;
r.route = indices;
r.lock_on_exhausted = lock;
r.trigger = trigger;
return r;
};
config.detector_routes = {
route("contact", config.recovery_routes.collision, true, RecoveryTrigger::kCollision),
route("unreachable", config.recovery_routes.path_blocked, true, RecoveryTrigger::kPathBlocked),
route("off_path", config.recovery_routes.off_path, true, RecoveryTrigger::kOffPath),
route("stall", config.recovery_routes.oscillation, false, RecoveryTrigger::kOscillation),
};
}
/// @brief Cấu hình cơ sở cho test: ngưỡng ngắn để không phải tua thời gian dài.
StateMachineConfig baseConfig()
{
@@ -53,9 +87,13 @@ StateMachineConfig baseConfig()
class Driver
{
public:
explicit Driver(const StateMachineConfig& config = baseConfig())
explicit Driver(StateMachineConfig config = baseConfig())
{
std::string error;
if (config.detector_routes.empty())
{
addLegacyDetectors(config);
}
configured_ = machine_.configure(config, error);
EXPECT_TRUE(configured_) << error;
now_ = 1000.0;
@@ -166,6 +204,112 @@ StateMachineInput requestWithActions(std::size_t action_count, bool has_goal = t
// Cấu hình
// ================================================================================================
TEST(StateMachineRecoveryResume, RejectsInvalidConfig)
{
auto config = baseConfig();
std::string error;
config.recovery_resume_confirm_cycles = 0;
EXPECT_FALSE(config.validate(error));
config.recovery_resume_confirm_cycles = 3;
config.recovery_resume_min_speed = 0.0;
EXPECT_FALSE(config.validate(error));
config.recovery_resume_min_speed = 0.05;
config.recovery_resume_max_per_leg = -1;
EXPECT_FALSE(config.validate(error));
}
TEST(StateMachineRecoveryResume, ConfirmsAndResetsOnStaleAndNoMotion)
{
auto config = baseConfig();
config.recovery_resume_enabled = true;
Driver driver(config);
driver.driveToControlling();
driver.advance(2.1);
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kNoValidCommand)).state, NavigationState::kRecovering);
StateMachineInput probe = recovery(RecoveryFeedback::kRunning);
probe.recovery_probe_moving = true;
EXPECT_FALSE(driver.tick(probe).cancel_recovery);
probe.costmap_current = false;
EXPECT_FALSE(driver.tick(probe).cancel_recovery);
probe.costmap_current = true;
EXPECT_FALSE(driver.tick(probe).cancel_recovery);
probe.recovery_probe_moving = false;
EXPECT_FALSE(driver.tick(probe).cancel_recovery);
probe.recovery_probe_moving = true;
EXPECT_FALSE(driver.tick(probe).cancel_recovery);
EXPECT_FALSE(driver.tick(probe).cancel_recovery);
const auto out = driver.tick(probe);
EXPECT_EQ(out.state, NavigationState::kControlling);
EXPECT_TRUE(out.cancel_recovery);
EXPECT_TRUE(out.apply_plan);
EXPECT_TRUE(out.recovery_resumed);
EXPECT_FALSE(out.report_outcome);
}
TEST(StateMachineRecoveryResume, QuotaResetsOnNewRequest)
{
auto config = baseConfig();
config.recovery_resume_enabled = true;
config.recovery_resume_confirm_cycles = 1;
config.recovery_resume_max_per_leg = 1;
Driver driver(config);
driver.driveToControlling();
driver.advance(2.1);
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kNoValidCommand)).state, NavigationState::kRecovering);
StateMachineInput probe = recovery(RecoveryFeedback::kRunning);
probe.recovery_probe_moving = true;
ASSERT_TRUE(driver.tick(probe).recovery_resumed);
driver.advance(2.1);
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kNoValidCommand)).state, NavigationState::kRecovering);
EXPECT_FALSE(driver.tick(probe).cancel_recovery);
StateMachineInput request;
request.has_pending_request = true;
EXPECT_EQ(driver.tick(request).state, NavigationState::kPlanning);
ASSERT_EQ(driver.tick(planReady()).state, NavigationState::kControlling);
driver.advance(2.1);
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kNoValidCommand)).state, NavigationState::kRecovering);
EXPECT_TRUE(driver.tick(probe).recovery_resumed);
}
TEST(StateMachineRecoveryResume, DetectorSequenceRefillsItsOwnRoute)
{
auto config = baseConfig();
config.recovery_resume_enabled = true;
config.recovery_resume_confirm_cycles = 1;
move_base2::DetectorRoute route;
route.name = "intrusion";
route.route = {0, 1};
route.sequence = true;
config.detector_routes = {route};
Driver driver(config);
driver.driveToControlling();
StateMachineInput fire;
fire.detector_fired = 1;
ASSERT_EQ(driver.tick(fire).recovery_index, 0u);
StateMachineInput done = recovery(RecoveryFeedback::kSucceeded);
auto next = driver.tick(done);
ASSERT_TRUE(next.recovery_chain_continues);
ASSERT_EQ(next.recovery_index, 1u);
StateMachineInput probe = recovery(RecoveryFeedback::kRunning);
probe.recovery_probe_moving = true;
ASSERT_TRUE(driver.tick(probe).recovery_resumed);
next = driver.tick(fire);
EXPECT_TRUE(next.start_recovery);
EXPECT_EQ(next.recovery_index, 0u);
}
TEST(StateMachineRecoveryResume, DisabledIgnoresProbe)
{
Driver driver;
driver.driveToControlling();
driver.advance(2.1);
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kNoValidCommand)).state, NavigationState::kRecovering);
StateMachineInput probe = recovery(RecoveryFeedback::kRunning);
probe.recovery_probe_moving = true;
for (int i = 0; i < 5; ++i) EXPECT_FALSE(driver.tick(probe).cancel_recovery);
}
TEST(StateMachineConfig, RejectsOscillationTimeoutWithoutDistance)
{
StateMachineConfig config = baseConfig();
@@ -393,6 +537,31 @@ TEST(StateMachinePlanning, PlannerPatienceEscalatesToRecovery)
EXPECT_TRUE(out.stop_planner);
}
TEST(StateMachinePlanning, CostmapWaitDoesNotSpendPatienceOrRetries)
{
StateMachineConfig config = baseConfig();
config.max_planning_retries = 0;
Driver driver(config);
StateMachineInput request;
request.has_pending_request = true;
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
StateMachineInput waiting;
waiting.planner = PlannerFeedback::kWaitingForCostmap;
for (int i = 0; i < 20; ++i)
{
driver.advance(0.6);
EXPECT_EQ(driver.tick(waiting).state, NavigationState::kPlanning);
}
StateMachineInput busy;
busy.planner = PlannerFeedback::kBusy;
busy.planner_costmap_wait_finished = true;
driver.advance(0.6);
EXPECT_EQ(driver.tick(busy).state, NavigationState::kPlanning);
driver.advance(0.6);
EXPECT_EQ(driver.tick(StateMachineInput()).state, NavigationState::kPlanning);
EXPECT_EQ(driver.tick(plannerFailed()).state, NavigationState::kRecovering);
}
TEST(StateMachinePlanning, MaxRetriesEscalatesBeforePatienceExpires)
{
StateMachineConfig config = baseConfig();
@@ -859,7 +1028,7 @@ TEST(StateMachineControlling, NoProgressFlagEscalatesToOscillationRecovery)
driver.driveToControlling();
StateMachineInput input = controller(ControllerFeedback::kCommandValid);
input.no_progress = true;
input.detector_fired |= kNoProgressBit;
const StateMachineOutput out = driver.tick(input);
EXPECT_EQ(out.state, NavigationState::kRecovering);
@@ -2172,7 +2341,7 @@ StateMachineInput collisionInput()
{
StateMachineInput input;
input.controller = ControllerFeedback::kCommandValid;
input.collision = true;
input.detector_fired |= kCollisionBit;
input.active_recovery_output = RecoveryOutputKind::kPath;
return input;
}
@@ -2181,7 +2350,7 @@ StateMachineInput blockedInput()
{
StateMachineInput input;
input.controller = ControllerFeedback::kCommandValid;
input.path_blocked = true;
input.detector_fired |= kBlockedBit;
// Cả hai route giám sát tuyến đều trỏ vào detour, họ kPath: nó KHÔNG lái robot, chỉ trả đường đi
// mới. Khai đúng họ ở đây để test kiểm được bất biến "robot đứng yên suốt lúc detour".
input.active_recovery_output = RecoveryOutputKind::kPath;
@@ -2192,7 +2361,7 @@ StateMachineInput offPathInput()
{
StateMachineInput input;
input.controller = ControllerFeedback::kCommandValid;
input.off_path = true;
input.detector_fired |= kOffPathBit;
input.active_recovery_output = RecoveryOutputKind::kPath;
return input;
}
@@ -2235,8 +2404,8 @@ TEST(StateMachinePathMonitor, BlockedPathWinsWhenBothFire)
StateMachineInput both;
both.controller = ControllerFeedback::kCommandValid;
both.path_blocked = true;
both.off_path = true;
both.detector_fired |= kBlockedBit;
both.detector_fired |= kOffPathBit;
EXPECT_EQ(driver.tick(both).recovery_trigger, RecoveryTrigger::kPathBlocked);
}
@@ -2278,8 +2447,8 @@ TEST(StateMachineCollisionTrigger, WinsOverPathBlockedAndOffPath)
driver.driveToControlling();
StateMachineInput all = collisionInput();
all.path_blocked = true;
all.off_path = true;
all.detector_fired |= kBlockedBit;
all.detector_fired |= kOffPathBit;
const StateMachineOutput out = driver.tick(all);
EXPECT_EQ(out.state, NavigationState::kRecovering);
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kCollision);
@@ -2469,24 +2638,138 @@ TEST(StateMachineRecoveryBudget, NewPathAfterTravelRefillsTheRoute)
EXPECT_EQ(driver.tick(moved).state, NavigationState::kRecovering);
}
TEST(StateMachineRecoveryBudget, TravelAcrossClearCountsTowardTheNextDetour)
{
struct Case
{
double before_clear;
double after_clear;
bool refill;
};
const Case cases[] = {
{ 0.245, 0.0, true }, // robot 19/11: đã đi trước clear
{ 0.0, 0.0, false }, // sim 4/9: đứng yên
{ 0.06, 0.05, true }, // quãng đường chia qua clear, đủ ngưỡng
{ 0.04, 0.05, false }, // tổng chưa đủ ngưỡng
};
for (const Case& test : cases)
{
SCOPED_TRACE(::testing::Message() << test.before_clear << " + " << test.after_clear);
StateMachineConfig config = baseConfig();
config.recovery_reset_min_travel = 0.1;
config.recovery_routes.planning_failed = { 0 };
config.recovery_routes.controlling_failed = { 0, 1 }; // clear, detour_path
config.recovery_routes.oscillation = { 0 };
Driver driver(config);
driver.driveToControlling();
auto fail_controller = [&](double travelled) {
driver.advance(2.1);
StateMachineInput input = controller(ControllerFeedback::kNoValidCommand);
input.travelled_since_oscillation_reset = travelled;
return driver.tick(input);
};
auto clear_done = [&](double travelled) {
StateMachineInput input = recovery(RecoveryFeedback::kSucceeded);
input.travelled_since_oscillation_reset = travelled;
return driver.tick(input);
};
StateMachineOutput out = fail_controller(0.0);
ASSERT_EQ(out.state, NavigationState::kRecovering);
ASSERT_EQ(out.recovery_index, 0u);
ASSERT_TRUE(clear_done(0.0).reset_oscillation_origin);
out = fail_controller(0.0);
ASSERT_EQ(out.state, NavigationState::kRecovering);
ASSERT_EQ(out.recovery_index, 1u);
ASSERT_FALSE(driver.tick(detourDone(0.0)).recovery_reset_denied);
ASSERT_EQ(driver.machine().nextRecoveryIndex(), 0u);
out = fail_controller(test.before_clear);
ASSERT_EQ(out.state, NavigationState::kRecovering);
ASSERT_EQ(out.recovery_index, 0u);
out = clear_done(test.before_clear);
ASSERT_EQ(out.state, NavigationState::kControlling);
ASSERT_TRUE(out.reset_oscillation_origin);
ASSERT_FALSE(out.apply_plan);
out = fail_controller(test.after_clear);
ASSERT_EQ(out.state, NavigationState::kRecovering);
ASSERT_EQ(out.recovery_index, 1u);
out = driver.tick(detourDone(test.after_clear));
EXPECT_EQ(out.recovery_reset_denied, !test.refill);
if (!test.refill)
{
EXPECT_NEAR(out.recovery_reset_travel, test.before_clear + test.after_clear, 1e-9);
}
EXPECT_EQ(driver.machine().nextRecoveryIndex(), test.refill ? 0u : 2u);
out = fail_controller(0.0);
EXPECT_EQ(out.state, test.refill ? NavigationState::kRecovering : NavigationState::kAborted);
if (test.refill)
{
EXPECT_EQ(out.recovery_route_cursor, 0u);
EXPECT_EQ(out.recovery_index, 0u);
}
}
}
TEST(StateMachineRecoveryBudget, TravelBeforePauseSurvivesResume)
{
Driver driver(monitorConfig());
driver.driveToControlling();
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
ASSERT_FALSE(driver.tick(detourDone(0.0)).recovery_reset_denied);
StateMachineInput pause;
pause.pause_requested = true;
pause.travelled_since_oscillation_reset = 0.07;
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
StateMachineInput resume;
resume.resume_requested = true;
resume.travelled_since_oscillation_reset = 0.07;
const StateMachineOutput resumed = driver.tick(resume);
ASSERT_EQ(resumed.state, NavigationState::kControlling);
ASSERT_TRUE(resumed.reset_oscillation_origin);
StateMachineInput blocked = blockedInput();
blocked.travelled_since_oscillation_reset = 0.04;
ASSERT_EQ(driver.tick(blocked).state, NavigationState::kRecovering);
EXPECT_FALSE(driver.tick(detourDone(0.04)).recovery_reset_denied);
}
TEST(StateMachineRecoveryBudget, NewRequestClearsTheTravelMark)
{
Driver driver(monitorConfig());
driver.driveToControlling();
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
ASSERT_FALSE(driver.tick(detourDone(0.0)).recovery_reset_denied);
StateMachineInput request;
request.has_pending_request = true;
const StateMachineOutput accepted = driver.tick(request);
ASSERT_EQ(accepted.state, NavigationState::kPlanning);
ASSERT_TRUE(accepted.reset_oscillation_origin);
ASSERT_EQ(driver.tick(planReady()).state, NavigationState::kControlling);
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
EXPECT_FALSE(driver.tick(detourDone(0.0)).recovery_reset_denied);
}
TEST(StateMachineRecoveryBudget, OscillationOriginResetClearsTheTravelMark)
{
// Đi quá oscillation_distance: origin đặt lại, travelled về 0 ở cycle sau. Mốc cũ (ghi ở giá trị
// travelled lớn) phải bị xoá, nếu không hiệu số âm khoá nạp lại vĩnh viễn.
// Đi quá oscillation_distance xoá mốc: detour kế tiếp được nạp lại dù chưa đi từ origin mới.
Driver driver(monitorConfig());
driver.driveToControlling();
StateMachineInput far = blockedInput();
far.travelled_since_oscillation_reset = 0.45;
ASSERT_EQ(driver.tick(far).state, NavigationState::kRecovering);
ASSERT_FALSE(driver.tick(detourDone(0.45)).recovery_reset_denied); // mốc = 0.45
ASSERT_FALSE(driver.tick(detourDone(0.45)).recovery_reset_denied);
StateMachineInput progress;
progress.controller = ControllerFeedback::kCommandValid;
progress.travelled_since_oscillation_reset = 0.6; // >= 0.5 -> origin reset
ASSERT_TRUE(driver.tick(progress).reset_oscillation_origin);
// Sau origin reset travelled đếm lại từ 0: 0.0 - 0.45 < 0 mà vẫn phải được nạp lại.
// Sau origin reset travelled đếm lại từ 0, nhưng mốc đã xoá nên vẫn phải được nạp lại.
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
EXPECT_FALSE(driver.tick(detourDone(0.0)).recovery_reset_denied);
}
@@ -2899,6 +3182,134 @@ TEST(StateMachineEmergency, IsNotTerminalAndMustBeStopped)
EXPECT_STREQ(move_base2::toString(NavigationState::kEmergency), "EMERGENCY");
}
// ------------------------------------------------------------------------------------------------
// route_mode: sequence (chốt 26/11, Test/docs/move_base2/ENV_DETECTOR_PLUGINS_PROMPT.md §4.5)
// ------------------------------------------------------------------------------------------------
namespace
{
/// Một detector `contact` chạy route [0, 1, 2] kiểu sequence, cạn thì khoá.
StateMachineConfig sequenceConfig()
{
StateMachineConfig config = baseConfig();
config.recovery_behavior_count = 3;
config.recovery_routes.planning_failed = { 0 };
config.recovery_routes.controlling_failed = { 0 };
config.recovery_routes.oscillation = { 0 };
move_base2::DetectorRoute contact;
contact.name = "contact";
contact.route = { 0, 1, 2 };
contact.lock_on_exhausted = true;
contact.sequence = true;
contact.trigger = RecoveryTrigger::kCollision;
config.detector_routes = { contact };
return config;
}
StateMachineInput sequenceFire()
{
StateMachineInput input;
input.controller = ControllerFeedback::kCommandValid;
input.detector_fired = 1u;
input.active_recovery_output = RecoveryOutputKind::kPath;
return input;
}
StateMachineInput behaviorDone(RecoveryFeedback result, bool with_path = false)
{
StateMachineInput input;
input.recovery = result;
input.planner = with_path ? PlannerFeedback::kPlanReady : PlannerFeedback::kIdle;
input.active_recovery_output = RecoveryOutputKind::kPath;
return input;
}
} // namespace
TEST(StateMachineSequence, OneFiringRunsTheWholeRouteEvenWhenABehaviorFails)
{
Driver driver(sequenceConfig());
driver.driveToControlling();
StateMachineOutput out = driver.tick(sequenceFire());
ASSERT_EQ(out.state, NavigationState::kRecovering);
EXPECT_TRUE(out.start_recovery);
EXPECT_EQ(out.recovery_index, 0u);
EXPECT_FALSE(out.recovery_chain_continues);
EXPECT_EQ(out.recovery_detector, 0);
out = driver.tick(behaviorDone(RecoveryFeedback::kFailed));
EXPECT_EQ(out.state, NavigationState::kRecovering) << "a failed behavior does not end a sequence";
EXPECT_TRUE(out.start_recovery);
EXPECT_TRUE(out.recovery_chain_continues);
EXPECT_EQ(out.recovery_index, 1u);
out = driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
EXPECT_TRUE(out.recovery_chain_continues);
EXPECT_EQ(out.recovery_index, 2u);
out = driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
EXPECT_TRUE(out.recovery_chain_finished);
EXPECT_FALSE(out.recovery_chain_has_path);
EXPECT_FALSE(out.recovery_chain_last_failed);
EXPECT_FALSE(out.apply_plan);
EXPECT_EQ(out.state, NavigationState::kControlling);
// Cả chuỗi là MỘT lượt: lần nổ sau route đã cạn -> khoá (lock), robot bám tiếp plan.
out = driver.tick(sequenceFire());
EXPECT_TRUE(out.monitor_trigger_suppressed);
EXPECT_FALSE(out.start_recovery);
EXPECT_EQ(out.state, NavigationState::kControlling);
}
TEST(StateMachineSequence, APathInTheMiddleIsHeldAppliedAtTheEndAndRefillsTheRoute)
{
Driver driver(sequenceConfig());
driver.driveToControlling();
driver.tick(sequenceFire());
StateMachineOutput out = driver.tick(behaviorDone(RecoveryFeedback::kSucceeded, true));
EXPECT_TRUE(out.recovery_chain_continues) << "a new path does not end a sequence";
EXPECT_FALSE(out.apply_plan) << "the path waits for the end of the chain";
EXPECT_EQ(out.state, NavigationState::kRecovering);
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
out = driver.tick(behaviorDone(RecoveryFeedback::kFailed));
EXPECT_TRUE(out.recovery_chain_finished);
EXPECT_TRUE(out.recovery_chain_has_path);
EXPECT_TRUE(out.recovery_chain_last_failed);
EXPECT_TRUE(out.apply_plan);
EXPECT_EQ(out.state, NavigationState::kControlling);
EXPECT_STREQ(out.reason, "recovery produced a detour path");
// Chuỗi có path mới và đây là lần nạp đầu: route nạp lại, lần nổ sau chạy lại cả chuỗi.
out = driver.tick(sequenceFire());
EXPECT_FALSE(out.monitor_trigger_suppressed);
EXPECT_TRUE(out.start_recovery);
EXPECT_EQ(out.recovery_index, 0u);
}
TEST(StateMachineSequence, ANewPathWithoutTravelDoesNotRefillTheRoute)
{
StateMachineConfig config = sequenceConfig();
config.recovery_reset_min_travel = 0.10; // [m]
Driver driver(config);
driver.driveToControlling();
// Lượt 1: có path -> nạp lại (lần đầu luôn được), mốc quãng đường đặt ở 0.
driver.tick(sequenceFire());
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded, true));
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
ASSERT_TRUE(driver.tick(behaviorDone(RecoveryFeedback::kSucceeded)).recovery_chain_finished);
// Lượt 2: lại có path nhưng robot chưa đi được 0.10 m -> tính như một lượt, route cạn.
driver.tick(sequenceFire());
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded, true));
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
const StateMachineOutput end = driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
ASSERT_TRUE(end.recovery_chain_finished);
EXPECT_TRUE(end.recovery_reset_denied);
EXPECT_TRUE(driver.tick(sequenceFire()).monitor_trigger_suppressed);
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);

View File

@@ -17,6 +17,7 @@
#include <move_base2/control_loop.h>
#include "env_monitor_fixture.h"
#include "fake_ports.h"
using move_base2::ControlLoop;
@@ -117,7 +118,9 @@ NavigationRequest makeActionOnlyRequest(std::size_t count, std::uint64_t sequenc
class Fixture
{
public:
explicit Fixture(const ControlLoopConfig& config = baseConfig()) : recovery_(2)
explicit Fixture(const ControlLoopConfig& config = baseConfig(),
const env_monitor_core::EnvMonitorConfig& env = env_monitor_core::EnvMonitorConfig())
: recovery_(2)
{
pose_.setPosition(0.0, 0.0);
@@ -130,12 +133,14 @@ public:
deps_.action = &action_;
deps_.costmap_status = &costmap_status_;
deps_.environment = &environment_;
deps_.env_monitor = &env_monitor_;
deps_.components = &components_;
planner_.attachStatusBoard(&components_);
recovery_.attachStatusBoard(&components_);
action_.attachStatusBoard(&components_);
std::string error;
EXPECT_TRUE(move_base2::testing::initEnvMonitor(env_monitor_, env, error)) << error;
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
}
@@ -173,6 +178,7 @@ public:
return hit_limit_;
}
env_monitor_core::EnvMonitor env_monitor_; ///< trước loop_: loop_ giữ con trỏ tới nó
ControlLoop loop_;
FakeClockPort clock_;
FakePosePort pose_;
@@ -220,6 +226,159 @@ std::string join(const std::vector<std::string>& items)
// Cấu hình và cửa vào
// ================================================================================================
// Enters recovery after a valid plan, then lets the fake controller answer probes.
void enterProbeRecovery(Fixture& fixture)
{
fixture.controller_.setScript({ControllerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
for (int i = 0; i < 100 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
fixture.stepOnce();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
fixture.controller_.setScript({ControllerScript::kOk});
fixture.controller_.isGoalReached(); // prime the fake without involving the control loop
fixture.stepOnce(); // first recovery tick establishes kRunning
}
TEST(ControlLoopRecoveryResume, ProbeCommandIsDiscardedAndStaleResetsConfirmation)
{
auto config = baseConfig();
config.state_machine.recovery_resume_enabled = true;
config.state_machine.recovery_resume_behaviors = {"fake_behavior_0"};
config.state_machine.recovery_resume_confirm_cycles = 3;
Fixture fixture(config);
fixture.recovery_.setRecoveryVelocity(true, -0.15);
enterProbeRecovery(fixture);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
fixture.stepOnce();
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, -0.15, 1e-9);
const auto calls = fixture.controller_.computeCount();
fixture.costmap_status_.setCurrent(false);
fixture.stepOnce();
EXPECT_EQ(fixture.controller_.computeCount(), calls);
fixture.costmap_status_.setCurrent(true);
fixture.stepOnce();
fixture.stepOnce();
EXPECT_EQ(fixture.recovery_.cancelCount(), 0u);
fixture.stepOnce();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
EXPECT_EQ(fixture.recovery_.cancelCount(), 1u);
EXPECT_EQ(fixture.controller_.setPlanCount(), 2u);
}
TEST(ControlLoopRecoveryResume, ZeroAndUnlistedBehaviorNeverCancel)
{
for (bool allowed : {false, true})
{
auto config = baseConfig();
config.state_machine.recovery_resume_enabled = true;
config.state_machine.recovery_resume_behaviors = {allowed ? "fake_behavior_0" : "other"};
Fixture fixture(config);
enterProbeRecovery(fixture);
fixture.controller_.setNominalSpeed(0.0);
const auto calls = fixture.controller_.computeCount();
for (int i = 0; i < 5; ++i) fixture.stepOnce();
EXPECT_EQ(fixture.recovery_.cancelCount(), 0u);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
if (!allowed) EXPECT_EQ(fixture.controller_.computeCount(), calls);
}
}
TEST(ControlLoopRecoveryResume, ReverseCountsAsMovement)
{
auto config = baseConfig();
config.state_machine.recovery_resume_enabled = true;
config.state_machine.recovery_resume_behaviors = {"fake_behavior_0"};
config.state_machine.recovery_resume_confirm_cycles = 1;
Fixture fixture(config);
enterProbeRecovery(fixture);
fixture.controller_.setNominalSpeed(-0.1);
fixture.stepOnce();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
EXPECT_EQ(fixture.recovery_.cancelCount(), 1u);
}
TEST(ControlLoopRecoveryResume, PlannerFailureResetsConfirmation)
{
auto config = baseConfig();
config.state_machine.recovery_resume_enabled = true;
config.state_machine.recovery_resume_behaviors = {"fake_behavior_0"};
config.state_machine.recovery_resume_confirm_cycles = 2;
Fixture fixture(config);
enterProbeRecovery(fixture);
fixture.stepOnce();
fixture.controller_.setScript({ControllerScript::kFail});
fixture.controller_.isGoalReached();
fixture.stepOnce();
fixture.controller_.setScript({ControllerScript::kOk});
fixture.controller_.isGoalReached();
fixture.stepOnce();
EXPECT_EQ(fixture.recovery_.cancelCount(), 0u);
fixture.stepOnce();
EXPECT_EQ(fixture.recovery_.cancelCount(), 1u);
}
TEST(ControlLoopRecoveryResume, StaleSkipsProbeEvenIfNormalCostmapGuardIsDisabled)
{
auto config = baseConfig();
config.require_current_costmap = false;
config.state_machine.recovery_resume_enabled = true;
config.state_machine.recovery_resume_behaviors = {"fake_behavior_0"};
Fixture fixture(config);
enterProbeRecovery(fixture);
fixture.costmap_status_.setCurrent(false);
const auto calls = fixture.controller_.computeCount();
for (int i = 0; i < 5; ++i) fixture.stepOnce();
EXPECT_EQ(fixture.controller_.computeCount(), calls);
EXPECT_EQ(fixture.recovery_.cancelCount(), 0u);
}
TEST(ControlLoopRecoveryResume, MissingPoseSkipsProbeAndResetsConfirmation)
{
auto config = baseConfig();
config.state_machine.recovery_resume_enabled = true;
config.state_machine.recovery_resume_behaviors = {"fake_behavior_0"};
config.state_machine.recovery_resume_confirm_cycles = 2;
Fixture fixture(config);
enterProbeRecovery(fixture);
fixture.stepOnce();
const auto calls = fixture.controller_.computeCount();
fixture.pose_.setAvailable(false);
fixture.stepOnce();
EXPECT_EQ(fixture.controller_.computeCount(), calls);
fixture.pose_.setAvailable(true);
fixture.stepOnce();
EXPECT_EQ(fixture.recovery_.cancelCount(), 0u);
fixture.stepOnce();
EXPECT_EQ(fixture.recovery_.cancelCount(), 1u);
}
TEST(ControlLoopRecoveryResume, AngularVelocityAloneDoesNotCountAsMovement)
{
auto config = baseConfig();
config.state_machine.recovery_resume_enabled = true;
config.state_machine.recovery_resume_behaviors = {"fake_behavior_0"};
Fixture fixture(config);
enterProbeRecovery(fixture);
fixture.controller_.setNominalSpeed(0.0);
fixture.controller_.setNominalTurnRate(0.2);
for (int i = 0; i < 5; ++i) fixture.stepOnce();
EXPECT_EQ(fixture.recovery_.cancelCount(), 0u);
}
TEST(ControlLoopRecoveryResume, DisabledNeverCallsProbe)
{
auto config = baseConfig();
config.state_machine.recovery_resume_behaviors = {"fake_behavior_0"};
Fixture fixture(config);
enterProbeRecovery(fixture);
const auto calls = fixture.controller_.computeCount();
for (int i = 0; i < 5; ++i) fixture.stepOnce();
EXPECT_EQ(fixture.controller_.computeCount(), calls);
EXPECT_EQ(fixture.recovery_.cancelCount(), 0u);
}
TEST(ControlLoop, RefusesToConfigureWithMissingPorts)
{
ControlLoop loop;
@@ -2122,22 +2281,29 @@ ControlLoopConfig envContactConfig()
config.state_machine.recovery_routes.oscillation = { 0 };
config.state_machine.recovery_routes.path_blocked = { 1 };
config.state_machine.recovery_routes.collision = { 1 };
config.env_monitor.enabled = true;
config.env_monitor.stall.action = "log";
config.env_monitor.unreachable.action = "log";
config.env_monitor.contact.action = "recover";
config.env_monitor.contact.apply_command = true;
config.env_monitor.contact.confirm_cycles = 2;
config.env_monitor.contact.trigger_static_time = 0.3; // [s] = 6 cycle, đủ ngắn cho test
config.env_monitor.contact.clean_start_margin = 0.2; // [m]
config.env_sampling.check_period = 0.01; // [s] < chu kỳ 0.05 -> tick nặng mỗi cycle
return config;
}
/// Tham số lõi EnvMonitor của bộ test kContact (nạp qua YAML như runtime).
env_monitor_core::EnvMonitorConfig envContactMonitor()
{
env_monitor_core::EnvMonitorConfig env;
env.enabled = true;
env.stall.action = "log";
env.unreachable.action = "log";
env.contact.action = "recover";
env.contact.apply_command = true;
env.contact.confirm_cycles = 2;
env.contact.trigger_static_time = 0.3; // [s] = 6 cycle, đủ ngắn cho test
env.contact.clean_start_margin = 0.2; // [m]
return env;
}
} // namespace
TEST(WalkingSkeletonEnvContact, BrakesAfterConfirmThenRaisesCollisionAfterStaticTime)
{
Fixture fixture(envContactConfig());
Fixture fixture(envContactConfig(), envContactMonitor());
driveToControlling(fixture);
// Tiếp xúc 0.10 m trên quỹ đạo, trong clean_start_margin: cycle 1 đếm, cycle 2 phanh -> lệnh 0.
@@ -2161,12 +2327,36 @@ TEST(WalkingSkeletonEnvContact, BrakesAfterConfirmThenRaisesCollisionAfterStatic
EXPECT_GE(held, 4) << "cờ phải chờ đủ trigger_static_time, không nổ cùng nhịp với phanh";
}
TEST(WalkingSkeletonEnvContact, LatchedBrakeDoesNotZeroTheRecoveryVelocity)
{
// Sim 27/11 14:21: kContact phanh ngay trước khi evade chạy; trong RECOVERING không có quỹ đạo để nhả phanh, phanh
// treo ép lệnh lùi về 0 suốt 15 s rồi evade hết timeout. Phanh chỉ được chặn controller.
Fixture fixture(envContactConfig(), envContactMonitor());
driveToControlling(fixture);
fixture.recovery_.setRecoveryVelocity(true, -0.15); // [m/s], âm = lùi
fixture.environment_.setContact(true, 0.10);
for (int i = 0; i < 12 && fixture.loop_.state() == NavigationState::kControlling; ++i)
{
fixture.stepOnce();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
bool saw_reverse = false;
for (int i = 0; i < 6 && fixture.loop_.state() == NavigationState::kRecovering; ++i)
{
fixture.stepOnce();
saw_reverse = saw_reverse || fixture.loop_.lastCommand().linear.x < -1e-6;
}
EXPECT_TRUE(saw_reverse) << "the contact brake swallowed the recovery's reverse command";
}
TEST(WalkingSkeletonEnvContact, HeldWithTheRouteSpentEscalatesToControllingFailed)
{
// Cùng chuỗi bắt buộc như guard cũ: cạn route collision -> khoá -> brake giữ 0 nhưng controller
// phải bị báo no_valid_command -> controller_patience -> controlling_failed. Không có bước này
// robot đứng chết vô hạn với controller "ổn".
Fixture fixture(envContactConfig());
Fixture fixture(envContactConfig(), envContactMonitor());
driveToControlling(fixture);
fixture.recovery_.setScript({ RecoveryScript::kFailed });
@@ -2207,7 +2397,7 @@ TEST(WalkingSkeletonEnvContact, DetourFromContactThatDidNotMoveTheRobotArmsTheSt
// Run 6/9 16:30 (đám đông): người đứng 7 cm trước mũi -> cờ collision -> detour -> chạm lại ngay -> cờ -> detour ...
// 4 lần rồi ABORT, vì stand-down không được vũ trang (trigger đọc ở cycle tick là mặc định). Chuỗi đúng: sau
// detour do cờ collision mà robot không dịch, chạm lại thì kContact ĐỨNG RA — không phanh, không cờ thứ hai.
Fixture fixture(envContactConfig());
Fixture fixture(envContactConfig(), envContactMonitor());
driveToControlling(fixture);
std::vector<robot_geometry_msgs::PoseStamped> detour{ makeRequest(0.0).goal, makeRequest(3.0).goal };
fixture.recovery_.setScript({ RecoveryScript::kSucceeded });
@@ -2245,7 +2435,7 @@ TEST(WalkingSkeletonEnvContact, DetourFromContactThatDidNotMoveTheRobotArmsTheSt
TEST(WalkingSkeletonEnvContact, ContactBeyondTheStoppingDistanceCapsSpeedWithoutBraking)
{
Fixture fixture(envContactConfig());
Fixture fixture(envContactConfig(), envContactMonitor());
driveToControlling(fixture);
const double v_free = fixture.loop_.lastCommand().linear.x;
ASSERT_GT(v_free, 0.27);

View File

@@ -72,6 +72,20 @@ TEST(Watchdog, IdleRowsAreNeverHung)
EXPECT_FALSE(dog.anyHung()) << "idle for a long time is not 'hung'";
}
TEST(Watchdog, WaitingForCostmapDoesNotConsumePlannerBudget)
{
ComponentStatusBoard board;
Watchdog dog;
std::string error;
WatchdogConfig c = fastConfig();
c.period = 0.0;
ASSERT_TRUE(dog.start(&board, c, error)) << error;
board.enter(Component::kGlobalPlanner, ComponentPhase::kWaitingForCostmap);
sleepMs(80);
dog.checkOnce();
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner));
}
TEST(Watchdog, BusyWithoutProgressBecomesHungAndRecoversOnProgress)
{
ComponentStatusBoard board;