update
This commit is contained in:
@@ -214,6 +214,7 @@ add_library(move_base2_core SHARED
|
||||
src/navigation_state.cpp
|
||||
src/state_machine.cpp
|
||||
src/velocity_arbiter.cpp
|
||||
src/plan_inspector.cpp
|
||||
src/control_loop.cpp
|
||||
src/config/move_base2_config.cpp
|
||||
src/runners/recovery_runner.cpp
|
||||
@@ -429,6 +430,7 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
|
||||
set(MOVE_BASE2_TESTS
|
||||
state_machine_test
|
||||
velocity_arbiter_test
|
||||
plan_inspector_test
|
||||
walking_skeleton_test
|
||||
config_validation_test
|
||||
action_runner_test
|
||||
|
||||
@@ -33,7 +33,7 @@ actions:
|
||||
# PHẢI tắt trước khi chạy robot thật để handler lấy frame do perception publish.
|
||||
use_simulated_goal: true
|
||||
simulated_parent_frame: base_link
|
||||
simulated_offset_x: 1.5 # [m]
|
||||
simulated_offset_x: -1.5 # [m]
|
||||
simulated_offset_y: 0.2 # [m]
|
||||
simulated_offset_yaw: 0.0 # [rad]
|
||||
settle_delay: 1.0 # [s] chờ robot đứng hẳn — pose lúc vừa dừng còn dao động cơ khí
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# `robot_nav_core2::LocalPlanner`; không dùng LocalPlannerAdapter (bridge chỉ dành cho move_base cũ).
|
||||
position:
|
||||
global_planner: CustomPlanner
|
||||
local_planner: HybridLocalPlanner
|
||||
local_planner: PriestLocalPlanner
|
||||
|
||||
docking:
|
||||
# goal_frame đã được ControlLoop quy thành pose tuyệt đối. DockPlanner dùng đúng contract
|
||||
@@ -32,14 +32,58 @@ docking_requires_marker: false
|
||||
# local planner nằm trong các YAML runtime đồng hành (symlink từ pnkx_nav_core/config/). Không lặp
|
||||
# lại chúng ở đây để tránh hai nguồn cấu hình cho cùng một plugin.
|
||||
|
||||
### replanning
|
||||
controller_frequency: 30.0 # run controller at 30.0 Hz
|
||||
controller_patience: 0.033333333 # [s] giữ hành vi cũ: fail controller -> recovery sau một cycle 30 Hz
|
||||
planner_frequency: 0.0 # don't continually replan (only when controller failed)
|
||||
planner_patience: 2.0 # if the first planning attempt failed, abort planning retries after 5.0 s...
|
||||
max_planning_retries: 0 # ... or after 10 attempts (whichever happens first)
|
||||
oscillation_timeout: -1 # abort controller and trigger recovery behaviors after 30.0 s
|
||||
oscillation_distance: 0.5
|
||||
### replanning (contract 2026-08-04 — tách replan nền khỏi recovery)
|
||||
controller_frequency: 30.0 # [Hz] nhịp control loop
|
||||
# [s] Controller không ra lệnh (kể cả mất pose) thì robot DỪNG TẠI CHỖ và vẫn ở CONTROLLING;
|
||||
# quá controller_patience mới vào RECOVERING(controlling_failed). Không còn nhánh "hỏng một cycle
|
||||
# là nhảy về PLANNING" — replan trong lúc chạy là việc của planner_frequency bên dưới.
|
||||
controller_patience: 0.033333333
|
||||
# [s] Trần cho chuỗi cycle costmap STALE liên tục ở CONTROLLING (2026-08-05). Costmap quá hạn thì
|
||||
# controller bị SKIP — data outage, không phải controller bất lực, nên controller_patience bị ĐÓNG
|
||||
# BĂNG trong lúc đó (33 ms đo outage là đo sai thứ: sim ABORT sau một cycle stale trong khi costmap
|
||||
# chỉ cần ~0.5 s để hồi). Stale liên tục quá trần này mới controlling_failed. 0 = tắt (hành vi cũ).
|
||||
sensor_patience: 2.0
|
||||
# [Hz] Replan NỀN khi đang CONTROLLING: lập plan bất đồng bộ trên thread planner, plan mới về thì
|
||||
# thay ngay mà không đổi state, không dừng robot. Replan nền thất bại thì giữ plan cũ, không kích
|
||||
# backup planner, không vào recovery. 0 = tắt (chỉ lập plan khi state machine yêu cầu).
|
||||
planner_frequency: 0.0
|
||||
planner_patience: 2.0 # [s] ở PLANNING quá lâu không có plan -> recovery (mất pose ở PLANNING
|
||||
# dùng ngân sách controlling_failed, xem recovery_behaviors_params)
|
||||
max_planning_retries: 0 # số lần lập plan HỎNG liên tiếp được phép; 0 = hỏng một lượt là leo thang
|
||||
oscillation_timeout: -1 # [s] <= 0: tắt phát hiện quẩn
|
||||
oscillation_distance: 0.5 # [m] đi quá quãng này: hết bị coi là quẩn VÀ reset ngân sách recovery
|
||||
|
||||
### giám sát tuyến (2026-08-04d)
|
||||
#
|
||||
# Hai phép đo chạy trong lúc robot bám plan, cùng một kết cục: robot DỪNG rồi chạy recovery của
|
||||
# trigger tương ứng (`path_blocked` / `off_path` trong recovery_behaviors_params.yaml).
|
||||
# - tuyến phía trước bị chắn -> khai hoả `path_blocked`
|
||||
# - robot đã lệch khỏi plan -> khai hoả `off_path`
|
||||
#
|
||||
# Hai nút tắt độc lập, cố ý: `enabled: false` ở đây, HOẶC route tương ứng rỗng bên recovery. Cả hai
|
||||
# đều đưa hành vi về đúng như trước khi có cơ chế này.
|
||||
path_monitor:
|
||||
enabled: true # công tắc CHUNG; tắt cái này là tắt cả hai phép đo bên dưới
|
||||
# Công tắc RIÊNG từng phép đo (2026-08-06). Trước đây chỉ tắt được bằng cách đặt ngưỡng về 0 —
|
||||
# giá trị ma, lẫn với "quên khai". Mỗi phép đo giờ có ba nút độc lập và phải đủ CẢ BA mới sống:
|
||||
# cờ này, ngưỡng của nó (horizon / max_cross_track > 0), và route tương ứng khác rỗng.
|
||||
path_blocked_enabled: true
|
||||
off_path_enabled: false # tắt tường minh: max_cross_track chưa đo được nên chưa có ngưỡng thật
|
||||
check_period: 0.2 # [s] nhịp quét; KHÔNG quét mỗi control cycle (30 Hz) — quá phí
|
||||
confirm_time: 0.5 # [s] điều kiện phải đúng liên tục chừng này mới khai hoả
|
||||
profiles: [position] # docking/go_straight/rotate KHÔNG được detour: đường cong vào dock là
|
||||
# một thể thống nhất, cắt ghép nó là phá chính hình học đó
|
||||
|
||||
# -- Phép đo 1: tuyến phía trước bị chắn --
|
||||
horizon: 3.0 # [m] quét trên costmap local (cửa sổ 8x8 m) nên phải <= ~4 m
|
||||
min_detour_distance: 0.5 # [m] vật cản gần hơn thì KHÔNG khai hoả: detour từ sát nách hầu như
|
||||
# không ra nghiệm, và ca đó đã có controller_patience lo
|
||||
|
||||
# -- Phép đo 2: robot lệch khỏi plan --
|
||||
# 0 = TẮT. Bật sau khi đo sai số bám cua thật của HybridController trên sim: khúc cua gắt làm
|
||||
# cross-track tăng tự nhiên, đặt số mò là robot dừng oan giữa đường cong.
|
||||
max_cross_track: 0.0 # [m]
|
||||
grace_after_new_plan: 1.0 # [s] bỏ qua ngay sau khi đổi plan (lúc preempt pose có thể lệch nhất thời)
|
||||
|
||||
### telemetry
|
||||
#
|
||||
|
||||
@@ -11,9 +11,9 @@ Khi cần đổi hành vi: sửa tài liệu này trước, sửa test, rồi m
|
||||
| State | Ai phát cmd_vel | Vào state khi | Ra khi |
|
||||
|---|---|---|---|
|
||||
| `IDLE` | không ai (0) | khởi động; cycle ngay sau một state terminal | có `NavigationRequest` đang chờ → `PLANNING`; yêu cầu chỉ-có-action (`has_goal == false`, D8) → `EXECUTING_ACTIONS`; yêu cầu không có goal lẫn action → `ABORTED` (tự vệ) |
|
||||
| `PLANNING` | không ai (0) | nhận yêu cầu; controller không sinh được lệnh mà chưa hết kiên nhẫn; recovery vừa chạy xong; tiếp tục sau tạm dừng | có plan hợp lệ → `CONTROLLING`; global planner chính fail/plan rỗng và có backup chưa dùng → đổi sang backup, lập plan lại; backup fail (hoặc không có backup) / quá `planner_patience` / quá `max_planning_retries` → `RECOVERING(planning_failed)` |
|
||||
| `CONTROLLING` | **local planner** | có plan hợp lệ; tiếp tục sau tạm dừng | `isGoalReached` → `SUCCEEDED` (hết action) hoặc `EXECUTING_ACTIONS` (còn action — D8); quá `controller_patience` → `RECOVERING(controlling_failed)`; quá `oscillation_timeout` → `RECOVERING(oscillation)`; không sinh được lệnh (còn kiên nhẫn, còn pose) → `PLANNING` |
|
||||
| `RECOVERING` | **recovery behavior** | ba trigger ở trên | tick trả `succeeded`/`failed` → `PLANNING`, cursor của **route thuộc trigger đó** tăng 1; hết route khi định vào → `ABORTED` |
|
||||
| `PLANNING` | không ai (0) | nhận yêu cầu; recovery của `planning_failed` (hoặc lượt leo thang từ chính `PLANNING`) vừa chạy xong; tiếp tục sau tạm dừng | có plan hợp lệ → `CONTROLLING`; global planner chính fail/plan rỗng và có backup chưa dùng → đổi sang backup, lập plan lại; backup fail (hoặc không có backup) / quá `planner_patience` / quá `max_planning_retries` → còn pose thì `RECOVERING(planning_failed)`, **mất pose thì `RECOVERING(controlling_failed)`** — mất dữ liệu dùng ngân sách dữ liệu, không phải ngân sách "không tìm được đường" |
|
||||
| `CONTROLLING` | **local planner** | có plan hợp lệ; recovery leo thang từ `CONTROLLING` vừa xong (bám tiếp plan cũ, hoặc áp path detour); tiếp tục sau tạm dừng | `isGoalReached` → `SUCCEEDED` (hết action) hoặc `EXECUTING_ACTIONS` (còn action — D8); quá `controller_patience` → `RECOVERING(controlling_failed)`; quá `oscillation_timeout` → `RECOVERING(oscillation)`. **Không sinh được lệnh (kể cả mất pose) thì KHÔNG đổi state** (contract 2026-08-04): robot dừng tại chỗ, ở nguyên `CONTROLLING` chờ đồng hồ kiên nhẫn; plan mới trong lúc chạy đến từ replan nền theo `planner_frequency` và được thay tại chỗ |
|
||||
| `RECOVERING` | **recovery behavior** | ba trigger ở trên | tick trả `succeeded`/`failed` → cursor của **route thuộc trigger đó** tăng 1, rồi (2026-08-04b): behavior nộp path detour (`kPath`) → `CONTROLLING` áp path đó; trigger `planning_failed` hoặc leo thang từ `PLANNING` → `PLANNING` lập plan lại; còn lại (controlling/oscillation từ `CONTROLLING`) → `CONTROLLING` bám tiếp plan cũ, KHÔNG replan; hết route khi định vào → `ABORTED` |
|
||||
| `EXECUTING_ACTIONS` | không ai (0) — **D8** | tới goal mà yêu cầu còn action; nhận yêu cầu `has_goal == false` | action xong mà còn action kế → start action kế (ở nguyên state); action cuối `succeeded` → `SUCCEEDED`; một action `failed` → `ABORTED` (không qua recovery); quá `action_patience` (nếu bật) → cancel action + `ABORTED`; `cancel()` → `CANCELLING`; `pause()` → `PAUSED` (không huỷ action) |
|
||||
| `PAUSED` | không ai (0) | `pause()` từ `PLANNING`/`CONTROLLING`/`RECOVERING`/`EXECUTING_ACTIONS` | `resume()` → về state trước đó; `cancel()` → `CANCELLING` |
|
||||
| `CANCELLING` | không ai (0) | `cancel()` từ mọi state đang chạy | robot đã dừng → `CANCELLED` |
|
||||
@@ -76,13 +76,25 @@ Khi cần đổi hành vi: sửa tài liệu này trước, sửa test, rồi m
|
||||
| `planning_retries_` (đếm `max_planning_retries`) | như trên | — |
|
||||
| `last_valid_control_` (đo `controller_patience`) | nhận yêu cầu mới; tiếp tục sau tạm dừng; recovery chạy xong; controller sinh được lệnh hợp lệ | **có plan mới** |
|
||||
| `last_oscillation_reset_` (đo `oscillation_timeout`) | nhận yêu cầu mới; tiếp tục sau tạm dừng; robot đi được quá `oscillation_distance` | **có plan mới** |
|
||||
| cursor các recovery route | nhận yêu cầu mới | route của trigger khác; cursor chỉ tăng sau lượt recovery của chính trigger đó |
|
||||
| cursor các recovery route | nhận yêu cầu mới; **robot đi được quá `oscillation_distance`** (tiến độ thật thì ngân sách recovery đầy lại — 2026-08-04) | route của trigger khác; cursor chỉ tăng sau lượt recovery của chính trigger đó |
|
||||
| `action_started_at_` (đo `action_patience`, D8) | start một action (trần tính cho TỪNG action); tiếp tục sau tạm dừng (quãng dừng không tính vào trần) | — |
|
||||
|
||||
Hai ô "không đặt lại khi có plan mới" là điểm dễ sai nhất và đã từng sai trong lúc thi công: nếu làm
|
||||
mới hai đồng hồ đó mỗi lần có plan, vòng lặp `CONTROLLING → PLANNING → CONTROLLING` sẽ liên tục gia
|
||||
hạn, và một controller hỏng vĩnh viễn sẽ không bao giờ chạm `controller_patience`. Test
|
||||
`ControllerPatienceSurvivesReplanLoop` giữ tính chất này.
|
||||
mới hai đồng hồ đó mỗi lần có plan, replan nền sẽ liên tục gia hạn, và một controller hỏng vĩnh viễn
|
||||
sẽ không bao giờ chạm `controller_patience`. Test `PersistentNoValidCommandEscalatesAfterPatience`
|
||||
giữ tính chất này.
|
||||
|
||||
## Replan nền (`planner_frequency`)
|
||||
|
||||
Từ 2026-08-04, replan trong lúc chạy và recovery là **hai cơ chế tách bạch**:
|
||||
|
||||
- `planner_frequency > 0` [Hz]: khi đang `CONTROLLING`, control loop khởi động một lượt lập plan
|
||||
bất đồng bộ theo nhịp này (bỏ qua nhịp nếu một lượt còn đang bay). Plan mới về được thay ngay
|
||||
trong `CONTROLLING` — không đổi state, không dừng robot. Replan nền **thất bại** thì giữ plan cũ,
|
||||
không kích backup planner, không vào recovery (test
|
||||
`BackgroundReplanFailureKeepsTheCurrentPlanAndSkipsBackup`).
|
||||
- Controller không sinh được lệnh: robot dừng tại chỗ trong `CONTROLLING`; quá `controller_patience`
|
||||
mới vào `RECOVERING(controlling_failed)`. Không còn nhánh "hỏng một cycle là quay về `PLANNING`".
|
||||
|
||||
## Global planner dự phòng
|
||||
|
||||
@@ -111,11 +123,17 @@ recovery:
|
||||
- {name: rotate, type: RotateRecovery}
|
||||
- {name: back_up, type: BackUpRecovery}
|
||||
routes:
|
||||
planning_failed: [wait, clear, rotate, back_up]
|
||||
controlling_failed: [wait, clear, detour_path, rotate, back_up]
|
||||
oscillation: [detour_path, rotate, back_up]
|
||||
planning_failed: [wait, clear]
|
||||
controlling_failed: [wait]
|
||||
oscillation: [wait]
|
||||
```
|
||||
|
||||
`controlling_failed` từ 2026-08-04 mang nghĩa **mất dữ liệu/lệnh** (controller câm quá
|
||||
`controller_patience`, hoặc mất pose ngay trong `PLANNING`). Route chỉ có `[wait]` là chủ đích:
|
||||
đứng yên một nhịp chờ dữ liệu quay lại; hết wait mà dữ liệu vẫn chưa về thì cursor cạn →
|
||||
`ABORTED`, robot dừng hẳn và outcome được báo; dữ liệu về thì lập plan chạy tiếp.
|
||||
`planning_failed` giữ đúng nghĩa "planner CÓ dữ liệu nhưng không tìm được đường".
|
||||
|
||||
Khi dựng runtime, `RecoveryRunner` nạp registry trước rồi resolve tên route thành index thật; chỉ
|
||||
sau đó `NavigationRuntime` mới gán `recovery_behavior_count` và các route này vào
|
||||
`StateMachineConfig`. Route phải khai đủ cả ba trigger, không rỗng sau resolve, không lặp tên và
|
||||
@@ -124,16 +142,28 @@ theo thứ tự nạp.
|
||||
|
||||
`DetourPathRecovery` hiện chưa có plugin/library. Vì vậy entry `detour_path` có thể được commit trước:
|
||||
registry báo plugin thiếu, `RecoveryRunner` cảnh báo và bỏ riêng tên đó khỏi route; không bao giờ
|
||||
đưa index giả vào state machine. Với config hiện tại, trước khi plugin được thêm, route hữu hiệu là
|
||||
`planning=[wait, clear, rotate, back_up]`, `controlling=[wait, clear, rotate, back_up]`,
|
||||
`oscillation=[rotate, back_up]`. Khi plugin SBPL được nạp thành công, hai route sau tự có
|
||||
`detour_path`, không cần sửa move_base2.
|
||||
đưa index giả vào state machine. Với config hiện tại route không khai `detour_path` nên không có
|
||||
entry nào bị bỏ; khi tuyến đường nào cần detour thì thêm tên vào route và nạp plugin SBPL, không
|
||||
cần sửa move_base2.
|
||||
|
||||
Mỗi request giữ ba cursor độc lập. Một lượt behavior `succeeded` **hoặc** `failed` luôn quay về
|
||||
`PLANNING` để lập đường mới và tiêu thụ một phần tử của route đã kích hoạt; lần lỗi kế tiếp cùng
|
||||
trigger thử phần tử sau. Lỗi bởi trigger khác dùng cursor của route khác. Log runner ghi `registry
|
||||
index`, không phải vị trí trong route, để không đánh lừa vận hành khi một behavior bị dùng ở nhiều
|
||||
route.
|
||||
Mỗi request giữ ba cursor độc lập. Một lượt behavior `succeeded` **hoặc** `failed` tiêu thụ một
|
||||
phần tử của route đã kích hoạt; lần lỗi kế tiếp cùng trigger thử phần tử sau. Lỗi bởi trigger khác
|
||||
dùng cursor của route khác. Log runner ghi `registry index`, không phải vị trí trong route, để
|
||||
không đánh lừa vận hành khi một behavior bị dùng ở nhiều route.
|
||||
|
||||
Đường quay về sau behavior (contract 2026-08-04b — recovery không kéo theo replan):
|
||||
|
||||
- behavior họ **detour** nộp path mới (`kPath`, cùng cycle kết thúc) → `CONTROLLING` với
|
||||
`apply_plan`: path đó được bám ngay, không lượt lập plan nào đè lên nó — cách duy nhất một
|
||||
recovery được thay plan;
|
||||
- trigger `planning_failed`, hoặc lượt leo thang xảy ra từ `PLANNING` (mất pose lúc lập plan —
|
||||
chưa từng có plan) → `PLANNING` lập plan lại;
|
||||
- còn lại (`controlling_failed`/`oscillation` leo thang từ `CONTROLLING`) → `CONTROLLING` bám
|
||||
tiếp **global path cũ**, không replan; controller được trọn một cửa `controller_patience` (đồng
|
||||
hồ và mốc chống quẩn gieo lại) trước khi lượt leo thang kế tiếp dùng behavior sau của route.
|
||||
Thay plan trong lúc chạy là việc riêng của replan nền `planner_frequency`; nhịp replan nền cũng
|
||||
đếm lại mỗi lần (tái) vào `CONTROLLING` để plan cũ/detour sống trọn một chu kỳ trước lượt replan
|
||||
nền đầu tiên.
|
||||
|
||||
## Mất pose (TF thiếu hoặc quá hạn)
|
||||
|
||||
@@ -142,11 +172,15 @@ Không biết robot đang ở đâu thì không được cho nó chạy. Cụ th
|
||||
- Nguồn vận tốc bị ép về `kNone` ở **mọi** state, kể cả `RECOVERING`.
|
||||
- Controller không được gọi.
|
||||
- Recovery **vẫn** được tick, để behavior tự báo lỗi theo contract của nó; lệnh nó sinh ra bị chặn.
|
||||
- Ở `CONTROLLING`, mất pose được tính là "không sinh được lệnh" nhưng **không** chuyển sang
|
||||
`PLANNING`: lập lại plan không giúp gì khi vấn đề là định vị, và nhảy sang `PLANNING` sẽ khiến lý
|
||||
do vào recovery bị ghi nhận sai thành "lập plan hỏng".
|
||||
- Ở `CONTROLLING`, mất pose được tính là "không sinh được lệnh": robot dừng tại chỗ, ở nguyên
|
||||
state cho tới khi `controller_patience` đưa vào `RECOVERING(controlling_failed)`.
|
||||
- Ở `PLANNING`, mất pose chặn `startPlan`; hết `planner_patience` cũng leo thang bằng
|
||||
`controlling_failed` — mất dữ liệu dùng ngân sách dữ liệu, để `planning_failed` giữ đúng nghĩa.
|
||||
- Các đồng hồ kiên nhẫn vẫn chạy, nên mất TF kéo dài cuối cùng vẫn dẫn tới `RECOVERING` rồi
|
||||
`ABORTED` — không treo im lặng.
|
||||
`ABORTED` — không treo im lặng. Với route `controlling_failed: [wait]`: mất pose → wait một
|
||||
nhịp → pose vẫn chưa về thì `ABORTED` và robot dừng hẳn; pose về thì chạy tiếp — mất pose lúc
|
||||
đang bám plan thì quay lại `CONTROLLING` bám tiếp plan cũ, mất pose lúc còn `PLANNING` thì lập
|
||||
plan lại (2026-08-04b).
|
||||
|
||||
## Bất biến
|
||||
|
||||
|
||||
@@ -95,6 +95,11 @@ struct MoveBase2Config
|
||||
/// Giữ marker cho docking planner legacy; false cho profile docking dựa hoàn toàn vào goal_frame.
|
||||
bool docking_requires_marker = true;
|
||||
|
||||
// --- Giám sát tuyến ---------------------------------------------------------------------------
|
||||
|
||||
/// Đọc từ namespace con `path_monitor`. Tắt mặc định — bật bằng config, không bật ngầm.
|
||||
ControlLoopConfig::PathMonitorConfig path_monitor;
|
||||
|
||||
// --- Namespace cho các thành phần nạp plugin ---------------------------------------------------
|
||||
|
||||
/// Namespace chứa danh sách recovery behavior (`<ns>/behaviors`) trong YAML.
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
#include <move_base2/ports/clock_port.h>
|
||||
#include <move_base2/ports/controller_port.h>
|
||||
#include <move_base2/ports/mission_port.h>
|
||||
#include <move_base2/ports/path_check_port.h>
|
||||
#include <move_base2/ports/planner_port.h>
|
||||
#include <move_base2/ports/pose_port.h>
|
||||
#include <move_base2/ports/costmap_status_port.h>
|
||||
@@ -57,6 +58,13 @@ struct ControlLoopDeps
|
||||
*/
|
||||
CostmapStatusPort* costmap_status = nullptr;
|
||||
ActionPort* action = nullptr; ///< Có thể null (D8) — null thì yêu cầu có action bị từ chối.
|
||||
|
||||
/**
|
||||
* Nguồn trả lời "tuyến này còn đi được không". **Có thể null** — null thì `PathMonitor` và luật
|
||||
* lọc plan bẩn đều tắt, hành vi y hệt trước 2026-08-04d. Mọi bộ test dùng cổng giả rơi vào nhánh
|
||||
* này.
|
||||
*/
|
||||
PathCheckPort* path_check = nullptr;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -109,6 +117,17 @@ struct ControlLoopConfig
|
||||
ProfileBinding go_straight;
|
||||
ProfileBinding rotate;
|
||||
|
||||
/**
|
||||
* [Hz] Tần suất replan NỀN khi đang bám plan (kControlling). 0 = tắt.
|
||||
*
|
||||
* Đây là cơ chế thay plan duy nhất trong lúc chạy (contract 2026-08-04): controller hỏng một
|
||||
* cycle KHÔNG kéo máy về kPlanning nữa — robot dừng tại chỗ chờ `controller_patience` rồi vào
|
||||
* recovery. Replan nền chạy bất đồng bộ trên thread planner; plan mới sẵn sàng thì được thay
|
||||
* ngay trong kControlling, không đổi state, không dừng robot. Replan nền THẤT BẠI thì bỏ qua —
|
||||
* plan cũ vẫn còn hiệu lực, và thất bại này không kích backup planner hay recovery.
|
||||
*/
|
||||
double planner_frequency = 0.0;
|
||||
|
||||
/**
|
||||
* Global planner dự phòng dùng một lần cho mỗi request sau khi planner chính trả failure/plan rỗng.
|
||||
* Chuỗi rỗng = tắt, giữ nguyên hành vi recovery hiện tại. Backup luôn nhận overload
|
||||
@@ -127,6 +146,58 @@ struct ControlLoopConfig
|
||||
*/
|
||||
bool docking_requires_marker = true;
|
||||
|
||||
/**
|
||||
* @struct PathMonitorConfig
|
||||
* @brief Giám sát tuyến trong lúc bám plan (contract 2026-08-04d).
|
||||
*
|
||||
* Hai phép đo độc lập, cùng một kết cục: robot **dừng** rồi chạy recovery của trigger tương ứng.
|
||||
* - tuyến phía trước bị chắn → `path_blocked`
|
||||
* - robot đã lệch khỏi plan → `off_path`
|
||||
*
|
||||
* Mỗi phép đo tắt riêng được, và route rỗng cũng là tắt — có hai nút để đảm bảo đường lùi.
|
||||
*/
|
||||
struct PathMonitorConfig
|
||||
{
|
||||
bool enabled = false; ///< Công tắc CHUNG. Tắt mặc định: bật bằng config, không bật ngầm.
|
||||
|
||||
/**
|
||||
* Công tắc RIÊNG cho từng phép đo, nằm dưới @ref enabled (tắt cái chung là tắt cả hai).
|
||||
*
|
||||
* Trước 2026-08-06 chỉ tắt được bằng cách đặt `horizon`/`max_cross_track` về 0 — một giá trị
|
||||
* ma, đọc config không thấy ý định, và lẫn với "quên khai". Hai cờ này nói thẳng. Ngưỡng 0 vẫn
|
||||
* còn tác dụng tắt để config cũ không đổi hành vi.
|
||||
*/
|
||||
bool path_blocked_enabled = true;
|
||||
bool off_path_enabled = true;
|
||||
|
||||
double check_period = 0.2; ///< [s] nhịp quét. KHÔNG quét mỗi control cycle — quá phí.
|
||||
double confirm_time = 0.5; ///< [s] điều kiện phải đúng liên tục chừng này mới khai hoả.
|
||||
|
||||
/// [m] Quãng tuyến phía trước cần quét. Phải <= nửa cửa sổ costmap local, ngoài đó không có dữ
|
||||
/// liệu. 0 = tắt phép đo "tuyến bị chắn" (cách cũ; ưu tiên @ref path_blocked_enabled).
|
||||
double horizon = 3.0;
|
||||
|
||||
/// [m] Vật cản gần hơn mức này thì KHÔNG khai hoả: detour từ sát nách vật cản hầu như không ra
|
||||
/// nghiệm, và tình huống đó đã có `controller_patience` lo.
|
||||
double min_detour_distance = 0.5;
|
||||
|
||||
/// [m] Lệch khỏi plan quá mức này thì khai hoả. 0 = tắt phép đo "lệch tuyến" (cách cũ; ưu tiên
|
||||
/// @ref off_path_enabled). Để 0 nghĩa là bật cờ thôi vẫn chưa đủ — phải cho một ngưỡng thật.
|
||||
double max_cross_track = 0.0;
|
||||
|
||||
/// [s] Bỏ qua phép đo lệch tuyến ngay sau khi nhận plan mới — lúc preempt/đổi chặng pose robot
|
||||
/// có thể lệch nhất thời so với plan vừa tới.
|
||||
double grace_after_new_plan = 1.0;
|
||||
|
||||
/// Profile được giám sát. Docking/go_straight/rotate KHÔNG bao giờ nên có mặt: đường cong vào
|
||||
/// dock là một thể thống nhất, cắt ghép nó là phá chính hình học đó.
|
||||
std::vector<MotionProfile> profiles{ MotionProfile::kPosition };
|
||||
|
||||
bool monitors(MotionProfile profile) const;
|
||||
};
|
||||
|
||||
PathMonitorConfig path_monitor;
|
||||
|
||||
bool validate(std::string& error) const;
|
||||
std::string describe() const;
|
||||
};
|
||||
@@ -205,6 +276,19 @@ public:
|
||||
return latest_plan_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Tuyến THAM CHIẾU của chặng: plan gần nhất do PLANNER sinh ra.
|
||||
*
|
||||
* Khác @ref latestPlan ở chỗ recovery KHÔNG thay được nó. Đây là tuyến mà fleet đã duyệt, nên nó
|
||||
* là mốc đúng cho hai việc: điểm nối của detour (robot tự quay về tuyến order thay vì trôi dần
|
||||
* theo từng đường vòng chồng lên nhau) và hành lang `max_deviation`. Rỗng khi chưa lập được plan
|
||||
* nào cho request hiện tại.
|
||||
*/
|
||||
const std::vector<robot_geometry_msgs::PoseStamped>& orderPlan() const
|
||||
{
|
||||
return order_plan_;
|
||||
}
|
||||
|
||||
/// @brief Lệnh vận tốc phát ra ở cycle gần nhất.
|
||||
const robot_geometry_msgs::Twist& lastCommand() const
|
||||
{
|
||||
@@ -301,6 +385,26 @@ private:
|
||||
/// @brief Gọi controller và lấy lệnh ứng viên.
|
||||
void runController(robot_geometry_msgs::Twist& candidate);
|
||||
|
||||
/**
|
||||
* @brief Chạy PathMonitor và cập nhật hai cờ khai hoả.
|
||||
*
|
||||
* Gọi ở đầu cycle, TRƯỚC state machine — hai cờ là dữ liệu vào của nó.
|
||||
*
|
||||
* @param now Thời điểm cycle này.
|
||||
* @param robot_pose Pose robot; chỉ dùng khi @p pose_available.
|
||||
* @param pose_available Mất pose thì không đo được gì cả.
|
||||
* @param costmap_stale Costmap quá hạn thì mọi kết luận về vật cản đều là quá khứ.
|
||||
*/
|
||||
void updatePathMonitor(const robot::Time& now, const robot_geometry_msgs::PoseStamped& robot_pose,
|
||||
bool pose_available, bool costmap_stale);
|
||||
|
||||
/// @brief Đặt lại toàn bộ trạng thái debounce của monitor (đổi chặng, rời kControlling, tắt).
|
||||
void resetPathMonitor();
|
||||
|
||||
/// @brief Plan này có bị chắn không. false = không kết luận được (thiếu cổng/TF/costmap).
|
||||
bool planIsBlocked(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index) const;
|
||||
|
||||
/// @brief Quaternion có chuẩn hoá được không — goal hỏng phải bị từ chối ngay tại cửa.
|
||||
static bool isQuaternionValid(const robot_geometry_msgs::PoseStamped& pose);
|
||||
|
||||
@@ -327,6 +431,8 @@ private:
|
||||
ActionFeedback action_feedback_ = ActionFeedback::kIdle;
|
||||
|
||||
std::vector<robot_geometry_msgs::PoseStamped> latest_plan_;
|
||||
/// 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;
|
||||
|
||||
/// True sau khi planner chính của request đã fail và backup được kích hoạt; không thử lại lần hai.
|
||||
@@ -344,6 +450,32 @@ private:
|
||||
robot::Time last_cycle_time_;
|
||||
bool has_last_cycle_time_ = false;
|
||||
|
||||
/// Mốc của lượt lập plan gần nhất ĐÃ khởi động được — nhịp đếm của replan nền
|
||||
/// (@ref ControlLoopConfig::planner_frequency). Đặt lại khi nhận yêu cầu mới.
|
||||
robot::Time last_plan_started_;
|
||||
|
||||
// --- PathMonitor -----------------------------------------------------------------------------
|
||||
//
|
||||
// Hai cờ này là KẾT QUẢ ĐÃ DEBOUNCE, không phải phép đo thô: chúng chỉ bật sau khi điều kiện đúng
|
||||
// liên tục đủ `confirm_time`. Người/xe đi ngang qua đúng một lượt quét không được làm robot dừng.
|
||||
bool path_blocked_ = false;
|
||||
bool off_path_ = false;
|
||||
/// [m] Chỗ chắn gần nhất đo được. `mutable` vì nó chỉ phục vụ log — `planIsBlocked` vẫn là phép
|
||||
/// hỏi thuần, không đổi quyết định nào của loop.
|
||||
mutable double last_block_distance_ = 0.0;
|
||||
|
||||
robot::Time last_path_check_; ///< Mốc nhịp quét.
|
||||
bool has_last_path_check_ = false;
|
||||
|
||||
robot::Time blocked_since_; ///< Lần đầu thấy tuyến bẩn trong chuỗi hiện tại.
|
||||
bool blocked_seen_ = false;
|
||||
robot::Time off_path_since_; ///< Lần đầu thấy lệch quá ngưỡng trong chuỗi hiện tại.
|
||||
bool off_path_seen_ = false;
|
||||
|
||||
/// Mốc nhận plan mới — dùng cho `grace_after_new_plan`.
|
||||
robot::Time last_plan_applied_;
|
||||
bool has_last_plan_applied_ = false;
|
||||
|
||||
robot_geometry_msgs::PoseStamped oscillation_origin_;
|
||||
bool has_oscillation_origin_ = false;
|
||||
|
||||
|
||||
109
include/move_base2/core/plan_inspector.h
Normal file
109
include/move_base2/core/plan_inspector.h
Normal file
@@ -0,0 +1,109 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — đo đạc trên global plan: tuyến phía trước có sạch không, robot cách plan bao xa.
|
||||
*
|
||||
* Hàm thuần, không giữ trạng thái, không quyết định gì. Người dùng duy nhất là `PathMonitor` của
|
||||
* `ControlLoop` (và luật lọc plan trong `collectPlannerResult`).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef MOVE_BASE2_CORE_PLAN_INSPECTOR_H_
|
||||
#define MOVE_BASE2_CORE_PLAN_INSPECTOR_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
|
||||
namespace robot_costmap_2d { class Costmap2D; }
|
||||
namespace tf3 { class BufferCore; }
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
/**
|
||||
* @struct PlanBlockResult
|
||||
* @brief Kết quả quét tuyến phía trước.
|
||||
*/
|
||||
struct PlanBlockResult
|
||||
{
|
||||
bool blocked = false; ///< Có ô nào trên tuyến không đặt được robot vào không.
|
||||
std::size_t index = 0; ///< Index pose bẩn đầu tiên. Chỉ có nghĩa khi @ref blocked.
|
||||
double distance = 0.0; ///< [m] Quãng đường dọc plan từ pose bắt đầu tới đó.
|
||||
std::size_t scanned = 0; ///< Số pose đã quét — 0 nghĩa là không kết luận được gì.
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct PlanarTransform
|
||||
* @brief Phép biến đổi 2D phẳng: `p_out = R(yaw) * p_in + t`.
|
||||
*
|
||||
* Tra TF **một lần** cho cả lượt quét rồi áp cho từng pose. Tra TF cho từng pose là hàng chục lời
|
||||
* gọi mỗi lượt, ngay trong nhịp điều khiển.
|
||||
*/
|
||||
struct PlanarTransform
|
||||
{
|
||||
double x = 0.0; ///< [m]
|
||||
double y = 0.0; ///< [m]
|
||||
double cos_yaw = 1.0;
|
||||
double sin_yaw = 0.0;
|
||||
|
||||
void apply(double in_x, double in_y, double& out_x, double& out_y) const
|
||||
{
|
||||
out_x = cos_yaw * in_x - sin_yaw * in_y + x;
|
||||
out_y = sin_yaw * in_x + cos_yaw * in_y + y;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Dựng phép biến đổi phẳng @p from → @p to từ TF.
|
||||
* @return false nếu không tra được (frame thiếu, TF quá hạn). Frame trùng nhau → identity + true.
|
||||
*/
|
||||
bool planarTransform(const tf3::BufferCore& tf, const std::string& from, const std::string& to,
|
||||
PlanarTransform& out);
|
||||
|
||||
/**
|
||||
* @brief Index pose gần @p pose nhất trên @p plan.
|
||||
*
|
||||
* Chiếu lên **đoạn**, không phải đo khoảng cách tới đỉnh: một plan vòng lại gần chính nó sẽ cho
|
||||
* index sai nếu chỉ so khoảng cách tới từng pose. Trả về index đầu của đoạn gần nhất.
|
||||
*/
|
||||
std::size_t nearestIndex(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
const robot_geometry_msgs::PoseStamped& pose);
|
||||
|
||||
/**
|
||||
* @brief [m] Khoảng cách vuông góc từ @p pose tới polyline của @p plan.
|
||||
*
|
||||
* @p pose và @p plan phải **cùng frame** — bên gọi dùng pose robot trong global frame, cùng frame
|
||||
* với plan. Plan rỗng → 0.
|
||||
*/
|
||||
double crossTrackError(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
const robot_geometry_msgs::PoseStamped& pose);
|
||||
|
||||
/**
|
||||
* @brief Quét tuyến phía trước xem có ô nào không đặt được robot vào không.
|
||||
*
|
||||
* @param plan Tuyến cần quét, trong frame của plan.
|
||||
* @param from_index Bắt đầu quét từ đây (thường là @ref nearestIndex của pose robot).
|
||||
* @param horizon [m] Quãng đường dọc plan tối đa cần quét.
|
||||
* @param grid Lưới cost. Bên gọi phải giữ mutex của nó.
|
||||
* @param plan_to_grid Phép quy đổi frame plan → frame lưới.
|
||||
*
|
||||
* Ngữ nghĩa cost, cả ba đều cố ý:
|
||||
* - `>= INSCRIBED_INFLATED_OBSTACLE` = **bị chắn**: đặt tâm robot ở đây thì footprint đã đệm chạm
|
||||
* vật cản.
|
||||
* - `NO_INFORMATION` = **KHÔNG** bị chắn. Vùng chưa quét mà tính là chắn thì robot dừng suốt ở mọi
|
||||
* tuyến đi vào chỗ chưa thấy.
|
||||
* - Pose ra ngoài lưới = **dừng quét**, không phải bị chắn. Cửa sổ costmap lăn theo robot nên phần
|
||||
* xa luôn nằm ngoài; coi đó là bị chắn thì mọi plan đều bẩn.
|
||||
*/
|
||||
PlanBlockResult checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index, double horizon,
|
||||
const robot_costmap_2d::Costmap2D& grid,
|
||||
const PlanarTransform& plan_to_grid);
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
#endif // MOVE_BASE2_CORE_PLAN_INSPECTOR_H_
|
||||
@@ -74,6 +74,19 @@ struct StateMachineConfig
|
||||
/// [s] Thời gian tối đa không sinh được lệnh hợp lệ trước khi vào recovery. <= 0 = tắt.
|
||||
double controller_patience = 15.0;
|
||||
|
||||
/**
|
||||
* [s] Trần cho chuỗi cycle costmap STALE liên tục ở kControlling. 0 = tắt cơ chế (stale ăn vào
|
||||
* controller_patience như trước 2026-08-05).
|
||||
*
|
||||
* Costmap quá hạn thì controller bị control loop SKIP — đó là DATA OUTAGE, không phải controller
|
||||
* bất lực, nên không được đo bằng controller_patience (0.033 s = một cycle; sim: detour xong ->
|
||||
* stale do chính SBPL giữ mutex -> controlling_failed sau 33 ms -> detour rác trên map cũ ->
|
||||
* ABORT, trong khi costmap chỉ cần ~0.5 s để hồi). Trong lúc stale, đồng hồ controller_patience
|
||||
* bị ĐÓNG BĂNG; stale liên tục quá trần này mới escalate controlling_failed đúng nghĩa "mất
|
||||
* dữ liệu" (contract 2026-08-04).
|
||||
*/
|
||||
double sensor_patience = 2.0;
|
||||
|
||||
/// [s] Thời gian tối đa được quẩn trong bán kính @ref oscillation_distance. <= 0 = tắt.
|
||||
double oscillation_timeout = 0.0;
|
||||
|
||||
@@ -149,9 +162,30 @@ struct StateMachineInput
|
||||
*/
|
||||
bool pose_available = true;
|
||||
|
||||
/**
|
||||
* Costmap còn hạn không (control loop đọc từ CostmapStatusPort, đã gộp `require_current_costmap`).
|
||||
*
|
||||
* false = dữ liệu quan sát quá hạn: control loop SKIP controller và chặn phát vận tốc (guard
|
||||
* "không đi mù"). Ở kControlling, cờ này đóng băng controller_patience và chạy đồng hồ
|
||||
* `sensor_patience` riêng — xem StateMachineConfig::sensor_patience.
|
||||
*/
|
||||
bool costmap_current = true;
|
||||
|
||||
/// Robot đã dừng hẳn chưa (|v| <= ngưỡng). Dùng để rời kCancelling.
|
||||
bool robot_stopped = true;
|
||||
|
||||
/**
|
||||
* Tuyến phía trước bị chắn (PathMonitor của control loop đã xác nhận đủ `confirm_time`).
|
||||
*
|
||||
* 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ờ.
|
||||
*/
|
||||
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.
|
||||
bool off_path = false;
|
||||
|
||||
/**
|
||||
* Họ output của behavior sẽ chạy / đang chạy ở cycle này.
|
||||
*
|
||||
@@ -205,6 +239,22 @@ struct StateMachineOutput
|
||||
std::size_t recovery_index = 0;
|
||||
RecoveryTrigger recovery_trigger = RecoveryTrigger::kPlanningFailed;
|
||||
|
||||
/**
|
||||
* Debug route recovery tại cycle này. Có nghĩa khi @ref start_recovery hoặc khi terminal reason là
|
||||
* "no recovery behavior left". Không ảnh hưởng điều khiển; dùng để log đúng trigger/cursor thay
|
||||
* vì chỉ thấy ABORTED chung chung.
|
||||
*/
|
||||
std::size_t recovery_route_cursor = 0;
|
||||
std::size_t recovery_route_size = 0;
|
||||
|
||||
/**
|
||||
* Cycle này vừa KHOÁ một trigger giám sát tuyến: hết đường vòng nên robot bám tiếp plan cũ thay
|
||||
* vì ABORT (contract 2026-08-05e). Bật đúng MỘT cycle, để bên gọi log một dòng — sau đó trigger
|
||||
* im lặng cho tới khi robot đi được quá `oscillation_distance`. @ref recovery_trigger nói trigger
|
||||
* nào bị khoá.
|
||||
*/
|
||||
bool monitor_trigger_suppressed = false;
|
||||
|
||||
/// Nguồn được phép phát vận tốc ở cycle này. Luôn có đúng một nguồn.
|
||||
VelocitySource velocity_source = VelocitySource::kNone;
|
||||
|
||||
@@ -297,6 +347,12 @@ 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.
|
||||
*/
|
||||
/// @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);
|
||||
|
||||
@@ -339,10 +395,34 @@ private:
|
||||
robot::Time last_valid_plan_; ///< Mốc đo planner_patience.
|
||||
robot::Time last_valid_control_; ///< Mốc đo controller_patience.
|
||||
robot::Time last_oscillation_reset_;
|
||||
robot::Time sensor_stale_since_; ///< Mốc bắt đầu chuỗi costmap stale liên tục.
|
||||
bool sensor_stale_active_ = false; ///< Đang trong chuỗi stale (sensor_stale_since_ có nghĩa).
|
||||
|
||||
std::size_t recovery_index_ = 0;
|
||||
RecoveryTrigger active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
std::array<std::size_t, 3> recovery_route_cursors_{{ 0, 0, 0 }};
|
||||
|
||||
/**
|
||||
* State đã leo thang vào recovery — quyết định đường quay về khi behavior kết thúc (contract
|
||||
* 2026-08-04b): từ kControlling thì bám tiếp plan cũ, từ kPlanning (mất pose lúc lập plan) thì
|
||||
* chưa từng có plan nào nên phải quay về kPlanning. Không bao giờ là kRecovering hay terminal.
|
||||
*/
|
||||
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, 5> recovery_route_cursors_{{ 0, 0, 0, 0, 0 }};
|
||||
|
||||
/**
|
||||
* 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ỉ hai ô kPathBlocked/kOffPath 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à
|
||||
* local planner + costmap (không cho đâm) rồi `controller_patience` (controlling_failed). Khoá
|
||||
* 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, 5> monitor_trigger_suppressed_{{ false, false, false, false, false }};
|
||||
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.
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <move_base2/control_loop.h>
|
||||
#include <move_base2/io/costmap_exporter.h>
|
||||
#include <move_base2/ports/clock_port.h>
|
||||
#include <move_base2/ports/path_check_port.h>
|
||||
#include <move_base2/ports/pose_port.h>
|
||||
#include <move_base2/runners/action_runner.h>
|
||||
#include <move_base2/runners/controller_runner.h>
|
||||
@@ -81,6 +82,43 @@ private:
|
||||
std::shared_ptr<tf3::BufferCore> tf_;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class CostmapPathCheck
|
||||
* @brief Hiện thực @ref PathCheckPort trên costmap ĐIỀU KHIỂN (local).
|
||||
*
|
||||
* Local chứ không global, hai lý do và cả hai đều quan trọng:
|
||||
* - **Độ tươi**: local chạy ở `update_frequency: 6.0` Hz, global chỉ `1.0` Hz. Vật cản vừa xuất
|
||||
* hiện có mặt ở local trước.
|
||||
* - **Đồng thuận với detour**: `DetourPathRecovery` lập đường vòng trên chính local costmap.
|
||||
* Monitor báo "bẩn" trên một lưới mà planner detour lại thấy "sạch" là vòng lặp vô nghĩa.
|
||||
*
|
||||
* Plan ở frame global (`map`) còn lưới ở `odom`, nên phải quy đổi — tra TF **một lần** cho cả lượt
|
||||
* quét (xem @ref PlanarTransform), không phải mỗi pose.
|
||||
*
|
||||
* @note Con trỏ costmap **non-owning và có thể bị thay** — lấy lại mỗi lần dùng, không cache
|
||||
* `Costmap2D*` bên trong.
|
||||
*/
|
||||
class CostmapPathCheck final : public PathCheckPort
|
||||
{
|
||||
public:
|
||||
void setCostmap(robot_costmap_2d::Costmap2DROBOT* costmap)
|
||||
{
|
||||
costmap_ = costmap;
|
||||
}
|
||||
|
||||
void setTf(const std::shared_ptr<tf3::BufferCore>& tf)
|
||||
{
|
||||
tf_ = tf;
|
||||
}
|
||||
|
||||
bool checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index, double horizon, PlanBlockResult& out) const override;
|
||||
|
||||
private:
|
||||
robot_costmap_2d::Costmap2DROBOT* costmap_ = nullptr;
|
||||
std::shared_ptr<tf3::BufferCore> tf_;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class CostmapStatusAdapter
|
||||
* @brief Cổng "costmap còn hạn không" lấy từ costmap thật.
|
||||
@@ -258,6 +296,12 @@ public:
|
||||
return controller_;
|
||||
}
|
||||
|
||||
/// @brief Runner recovery — server nối `setPlanSource` cho behavior họ path qua đây.
|
||||
RecoveryRunner& recoveryRunner()
|
||||
{
|
||||
return recovery_;
|
||||
}
|
||||
|
||||
/// @brief Bộ kết xuất costmap cho host publish lên rviz.
|
||||
CostmapExporter& globalExporter()
|
||||
{
|
||||
@@ -306,6 +350,7 @@ private:
|
||||
*/
|
||||
CostmapPosePort global_pose_; ///< frame `map` — planner, chống quẩn, pose báo về host.
|
||||
CostmapPosePort local_pose_; ///< frame `odom` — controller và recovery.
|
||||
CostmapPathCheck path_check_; ///< quét tuyến trên costmap local (PathMonitor + lọc plan).
|
||||
CostmapExporter global_exporter_;
|
||||
CostmapExporter local_exporter_;
|
||||
|
||||
|
||||
50
include/move_base2/ports/path_check_port.h
Normal file
50
include/move_base2/ports/path_check_port.h
Normal file
@@ -0,0 +1,50 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — cổng kiểm tra tuyến trên costmap.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef MOVE_BASE2_PORTS_PATH_CHECK_PORT_H_
|
||||
#define MOVE_BASE2_PORTS_PATH_CHECK_PORT_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
|
||||
#include <move_base2/core/plan_inspector.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
/**
|
||||
* @class PathCheckPort
|
||||
* @brief "Tuyến này có đi được không" — lõi hỏi, hạ tầng trả lời.
|
||||
*
|
||||
* Tách thành cổng vì phép kiểm cần **costmap + TF**, hai thứ `ControlLoop` cố ý không giữ. Nhờ vậy
|
||||
* lõi vẫn kiểm được bằng cổng giả, còn hiện thực thật (`CostmapPathCheck`) sống cạnh costmap trong
|
||||
* `NavigationRuntime`.
|
||||
*
|
||||
* @note Chỉ control thread được gọi: hiện thực thật giữ mutex costmap trong lúc quét.
|
||||
*/
|
||||
class PathCheckPort
|
||||
{
|
||||
public:
|
||||
virtual ~PathCheckPort() = default;
|
||||
|
||||
/**
|
||||
* @brief Quét @p plan từ @p from_index về phía trước tối đa @p horizon [m].
|
||||
*
|
||||
* @param[out] out Kết quả; chỉ được ghi khi hàm trả true.
|
||||
* @return false = **không kết luận được** (thiếu TF, chưa có costmap). Bên gọi phải coi đó là
|
||||
* "không biết" và KHÔNG khai hoả — không được suy thành "sạch" hay "bẩn".
|
||||
*/
|
||||
virtual bool checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index, double horizon, PlanBlockResult& out) const = 0;
|
||||
};
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
#endif // MOVE_BASE2_PORTS_PATH_CHECK_PORT_H_
|
||||
@@ -29,7 +29,14 @@ enum class RecoveryTrigger
|
||||
{
|
||||
kPlanningFailed, ///< Không lập được plan trong thời gian cho phép.
|
||||
kControllingFailed, ///< Không sinh được lệnh vận tốc hợp lệ trong thời gian cho phép.
|
||||
kOscillation ///< Robot quẩn tại chỗ quá lâu.
|
||||
kOscillation, ///< Robot quẩn tại chỗ quá lâu.
|
||||
|
||||
/// Tuyến phía trước bị vật cản chắn. Khác ba trigger trên: **chưa có gì hỏng cả** — controller
|
||||
/// vẫn ra lệnh, plan vẫn hợp lệ. Đây là dự báo, phát hiện trước khi robot tới nơi.
|
||||
kPathBlocked,
|
||||
|
||||
/// Robot đã lệch khỏi plan đang chạy quá ngưỡng (thường do local planner tự né vật cản).
|
||||
kOffPath
|
||||
};
|
||||
|
||||
const char* toString(RecoveryTrigger trigger);
|
||||
@@ -52,7 +59,14 @@ struct RecoveryRoutes
|
||||
std::vector<std::size_t> controlling_failed;
|
||||
std::vector<std::size_t> oscillation;
|
||||
|
||||
/// Hai route giám sát tuyến. **Rỗng = tắt hẳn cơ chế tương ứng** — đó là mặc định, và cũng là
|
||||
/// đường lùi: config không khai chúng thì runtime chạy y như trước khi có PathMonitor.
|
||||
std::vector<std::size_t> path_blocked;
|
||||
std::vector<std::size_t> off_path;
|
||||
|
||||
const std::vector<std::size_t>& forTrigger(RecoveryTrigger trigger) 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;
|
||||
};
|
||||
|
||||
|
||||
@@ -136,6 +136,18 @@ public:
|
||||
/// @brief Gắn bộ telemetry (non-owning, có thể null = tắt đo). Gọi trước @ref configure.
|
||||
void attachStats(RuntimeStats* stats);
|
||||
|
||||
/**
|
||||
* @brief Tắt việc khoá costmap mutex quanh các lời gọi plugin — CHỈ dành cho unit test.
|
||||
*
|
||||
* Mặc định BẬT: computeVelocityCommands/isGoalReached/setPlan giữ `Costmap2D::getMutex()` của
|
||||
* local costmap trong lúc plugin chạy, cùng giao thức với map-update thread (gen-1 làm y hệt).
|
||||
* Unit test truyền costmap placeholder không dereference được thì phải tắt trước khi dùng.
|
||||
*/
|
||||
void disableCostmapLockForTesting()
|
||||
{
|
||||
costmap_lock_enabled_ = false;
|
||||
}
|
||||
|
||||
bool computeVelocityCommands(robot_geometry_msgs::Twist& cmd) override;
|
||||
bool isGoalReached() override;
|
||||
void getLocalPlan(robot_nav_2d_msgs::Path2D& plan) override;
|
||||
@@ -173,6 +185,9 @@ private:
|
||||
const PosePort* pose_ = nullptr; ///< Non-owning.
|
||||
bool configured_ = false;
|
||||
|
||||
/// Khoá costmap mutex quanh lời gọi plugin. Chỉ unit test với costmap placeholder mới được tắt.
|
||||
bool costmap_lock_enabled_ = true;
|
||||
|
||||
/// Telemetry non-owning, null = tắt đo. Chỉ đọc sau khi @ref attachStats.
|
||||
RuntimeStats* stats_ = nullptr;
|
||||
RuntimeStats::SectionId section_compute_ = RuntimeStats::kInvalidSection;
|
||||
|
||||
@@ -118,6 +118,18 @@ public:
|
||||
*/
|
||||
void attachStats(RuntimeStats* stats);
|
||||
|
||||
/**
|
||||
* @brief Tắt việc khoá costmap mutex quanh makePlan — CHỈ dành cho unit test.
|
||||
*
|
||||
* Mặc định BẬT: thread lập plan giữ `Costmap2D::getMutex()` suốt makePlan, cùng giao thức với
|
||||
* map-update thread (gen-1 làm y hệt). Unit test truyền costmap placeholder không dereference
|
||||
* được thì phải tắt trước khi startPlan, nếu không sẽ crash ngay lần lấy mutex.
|
||||
*/
|
||||
void disableCostmapLockForTesting()
|
||||
{
|
||||
costmap_lock_enabled_ = false;
|
||||
}
|
||||
|
||||
bool startPlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
const robot_geometry_msgs::PoseStamped& goal,
|
||||
const robot_protocol_msgs::Order* order, std::uint64_t tag) override;
|
||||
@@ -155,6 +167,9 @@ private:
|
||||
robot_costmap_2d::Costmap2DROBOT* costmap_ = nullptr;
|
||||
bool configured_ = false;
|
||||
|
||||
/// Khoá costmap mutex quanh makePlan. Chỉ unit test với costmap placeholder mới được tắt.
|
||||
bool costmap_lock_enabled_ = true;
|
||||
|
||||
/// Telemetry non-owning, null = tắt đo. Chỉ đọc sau khi @ref attachStats.
|
||||
RuntimeStats* stats_ = nullptr;
|
||||
RuntimeStats::SectionId section_make_plan_ = RuntimeStats::kInvalidSection;
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <move_base2/ports/recovery_port.h>
|
||||
|
||||
namespace robot_costmap_2d { class Costmap2DROBOT; }
|
||||
namespace tf3 { class BufferCore; }
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
@@ -66,6 +67,9 @@ public:
|
||||
PosePort* pose = nullptr;
|
||||
robot_costmap_2d::Costmap2DROBOT* local_costmap = nullptr;
|
||||
robot_costmap_2d::Costmap2DROBOT* global_costmap = nullptr;
|
||||
|
||||
/// TF buffer dùng chung của runtime, cho behavior cần đổi frame (họ path). Có thể null.
|
||||
tf3::BufferCore* tf = nullptr;
|
||||
};
|
||||
|
||||
RecoveryRunner() = default;
|
||||
@@ -83,6 +87,14 @@ public:
|
||||
/// @brief Nguồn plan cho behavior họ path. Không đặt = không có plan.
|
||||
void setPlanSource(PlanSource source);
|
||||
|
||||
/**
|
||||
* @brief Nguồn TUYẾN THAM CHIẾU của chặng (plan do planner sinh, recovery không thay được).
|
||||
*
|
||||
* Không khai thì `RecoveryContext::reference_plan` để null và behavior tự quay về dùng plan hiện
|
||||
* hành. Xem `RecoveryContext::reference_plan` cho lý do tách hai nguồn.
|
||||
*/
|
||||
void setReferencePlanSource(PlanSource source);
|
||||
|
||||
/**
|
||||
* @copydoc RecoveryPort::configure
|
||||
*
|
||||
@@ -168,11 +180,16 @@ private:
|
||||
recovery_core::CostmapCollisionChecker collision_;
|
||||
PoseBridge pose_bridge_;
|
||||
PlanBridge plan_bridge_;
|
||||
PlanBridge reference_plan_bridge_;
|
||||
|
||||
RecoveryRoutes routes_;
|
||||
|
||||
bool configured_ = false;
|
||||
recovery_core::RecoveryBehavior* active_ = nullptr; ///< non-owning, thuộc registry_
|
||||
|
||||
/// Tên + trigger của lượt đang chạy, giữ để log được sườn KẾT THÚC (active_ bị xoá ở đó).
|
||||
std::string active_name_;
|
||||
RecoveryTrigger active_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
};
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
@@ -136,6 +136,62 @@ void readDockingMarkerProfiles(robot::NodeHandle& nh, DockingMarkerProfiles& pro
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Đọc khối `path_monitor`.
|
||||
*
|
||||
* Khối vắng mặt = giám sát tuyến TẮT, hành vi y hệt trước 2026-08-04d. Đây là đường lùi thứ nhất
|
||||
* (thứ hai là route `path_blocked`/`off_path` rỗng) — hai nút độc lập, cố ý.
|
||||
*/
|
||||
void readPathMonitor(robot::NodeHandle& nh, ControlLoopConfig::PathMonitorConfig& monitor)
|
||||
{
|
||||
robot::NodeHandle monitor_nh(nh, "path_monitor");
|
||||
|
||||
readBool(monitor_nh, "enabled", monitor.enabled);
|
||||
readBool(monitor_nh, "path_blocked_enabled", monitor.path_blocked_enabled);
|
||||
readBool(monitor_nh, "off_path_enabled", monitor.off_path_enabled);
|
||||
readDouble(monitor_nh, "check_period", monitor.check_period);
|
||||
readDouble(monitor_nh, "confirm_time", monitor.confirm_time);
|
||||
readDouble(monitor_nh, "horizon", monitor.horizon);
|
||||
readDouble(monitor_nh, "min_detour_distance", monitor.min_detour_distance);
|
||||
readDouble(monitor_nh, "max_cross_track", monitor.max_cross_track);
|
||||
readDouble(monitor_nh, "grace_after_new_plan", monitor.grace_after_new_plan);
|
||||
|
||||
std::vector<std::string> names;
|
||||
monitor_nh.param("profiles", names, std::vector<std::string>{});
|
||||
if (names.empty())
|
||||
{
|
||||
return; // Giữ mặc định: chỉ profile position.
|
||||
}
|
||||
|
||||
monitor.profiles.clear();
|
||||
for (const std::string& name : names)
|
||||
{
|
||||
if (name == "position")
|
||||
{
|
||||
monitor.profiles.push_back(MotionProfile::kPosition);
|
||||
}
|
||||
else if (name == "docking")
|
||||
{
|
||||
monitor.profiles.push_back(MotionProfile::kDocking);
|
||||
}
|
||||
else if (name == "go_straight")
|
||||
{
|
||||
monitor.profiles.push_back(MotionProfile::kGoStraight);
|
||||
}
|
||||
else if (name == "rotate")
|
||||
{
|
||||
monitor.profiles.push_back(MotionProfile::kRotate);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Không đoán: tên lạ mà im lặng bỏ qua thì người vận hành tưởng đã bật giám sát cho profile
|
||||
// đó. Cảnh báo rồi bỏ — profile lạ không thể tự sinh ra hành vi nào.
|
||||
robot::log_warning("[move_base2] path_monitor/profiles: unknown profile '%s', ignored.\n",
|
||||
name.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
{
|
||||
@@ -146,6 +202,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
|
||||
readDouble(nh, "planner_patience", config.state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", config.state_machine.controller_patience);
|
||||
readDouble(nh, "sensor_patience", config.state_machine.sensor_patience);
|
||||
readDouble(nh, "oscillation_timeout", config.state_machine.oscillation_timeout);
|
||||
readDouble(nh, "oscillation_distance", config.state_machine.oscillation_distance);
|
||||
readDouble(nh, "action_patience", config.state_machine.action_patience);
|
||||
@@ -159,6 +216,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
readDouble(nh, "acc_lim_theta", config.velocity.max_accel_theta);
|
||||
|
||||
readSensors(nh, config.sensors);
|
||||
readPathMonitor(nh, config.path_monitor);
|
||||
readBool(nh, "docking_requires_marker", config.docking_requires_marker);
|
||||
|
||||
readString(nh, "recovery_namespace", config.recovery_namespace);
|
||||
@@ -253,6 +311,54 @@ bool MoveBase2Config::validate(std::string& error) const
|
||||
error = "planner_timeout is not finite [s]";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (path_monitor.enabled)
|
||||
{
|
||||
// Chỉ kiểm khi BẬT: tham số vô nghĩa trong một khối đang tắt không có lý do gì để chặn boot.
|
||||
if (!std::isfinite(path_monitor.check_period) || path_monitor.check_period <= 0.0)
|
||||
{
|
||||
error = "path_monitor/check_period must be > 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(path_monitor.confirm_time) || path_monitor.confirm_time < 0.0)
|
||||
{
|
||||
error = "path_monitor/confirm_time must be >= 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(path_monitor.horizon) || path_monitor.horizon < 0.0)
|
||||
{
|
||||
error = "path_monitor/horizon must be >= 0 [m] (0 = the blocked-path check is off)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(path_monitor.min_detour_distance) || path_monitor.min_detour_distance < 0.0)
|
||||
{
|
||||
error = "path_monitor/min_detour_distance must be >= 0 [m]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(path_monitor.max_cross_track) || path_monitor.max_cross_track < 0.0)
|
||||
{
|
||||
error = "path_monitor/max_cross_track must be >= 0 [m] (0 = the off-path check is off)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(path_monitor.grace_after_new_plan) ||
|
||||
path_monitor.grace_after_new_plan < 0.0)
|
||||
{
|
||||
error = "path_monitor/grace_after_new_plan must be >= 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (!(path_monitor.horizon > 0.0) && !(path_monitor.max_cross_track > 0.0))
|
||||
{
|
||||
// Bật khối mà tắt cả hai phép đo là mâu thuẫn: người khai tưởng giám sát đang chạy.
|
||||
error = "path_monitor is enabled but both checks are off; set horizon > 0 [m] and/or "
|
||||
"max_cross_track > 0 [m], or set enabled: false";
|
||||
return false;
|
||||
}
|
||||
if (path_monitor.profiles.empty())
|
||||
{
|
||||
error = "path_monitor/profiles is empty; no leg would ever be monitored";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0)
|
||||
{
|
||||
error = "runtime_stats_period must be >= 0 [s] (0 = telemetry off)";
|
||||
@@ -370,6 +476,7 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
readDouble(nh, "runtime_stats_period", runtime_stats_period);
|
||||
readDouble(nh, "planner_patience", state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", state_machine.controller_patience);
|
||||
readDouble(nh, "sensor_patience", state_machine.sensor_patience);
|
||||
readDouble(nh, "oscillation_timeout", state_machine.oscillation_timeout);
|
||||
readDouble(nh, "oscillation_distance", state_machine.oscillation_distance);
|
||||
readInt(nh, "max_planning_retries", state_machine.max_planning_retries);
|
||||
@@ -505,6 +612,7 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
|
||||
config.velocity = velocity;
|
||||
config.nominal_control_period =
|
||||
controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s]
|
||||
config.planner_frequency = planner_frequency; // [Hz] replan nền khi kControlling
|
||||
config.robot_base_frame = robot_base_frame;
|
||||
config.require_current_costmap = require_current_costmap;
|
||||
config.position = position;
|
||||
@@ -514,6 +622,7 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
|
||||
config.rotate = rotate;
|
||||
config.backup_global_planner_name = backup_global_planner_name;
|
||||
config.docking_requires_marker = docking_requires_marker;
|
||||
config.path_monitor = path_monitor;
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
*********************************************************************/
|
||||
#include <move_base2/control_loop.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
|
||||
#include <robot/console.h>
|
||||
@@ -25,6 +27,58 @@ constexpr double kQuaternionNormTolerance = 1e-2;
|
||||
/// điều khiển — log mỗi cycle sẽ nhấn chìm mọi dòng khác.
|
||||
constexpr double kStaleCostmapLogThrottle = 5.0;
|
||||
|
||||
/// [s] Log debug tạm phục vụ test đường recovery/controller. Ngắn hơn throttle runtime mặc định để
|
||||
/// 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;
|
||||
|
||||
const char* toString(PlannerFeedback feedback)
|
||||
{
|
||||
switch (feedback)
|
||||
{
|
||||
case PlannerFeedback::kIdle:
|
||||
return "idle";
|
||||
case PlannerFeedback::kBusy:
|
||||
return "busy";
|
||||
case PlannerFeedback::kPlanReady:
|
||||
return "plan_ready";
|
||||
case PlannerFeedback::kFailed:
|
||||
return "failed";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const char* toString(ControllerFeedback feedback)
|
||||
{
|
||||
switch (feedback)
|
||||
{
|
||||
case ControllerFeedback::kIdle:
|
||||
return "idle";
|
||||
case ControllerFeedback::kCommandValid:
|
||||
return "command_valid";
|
||||
case ControllerFeedback::kNoValidCommand:
|
||||
return "no_valid_command";
|
||||
case ControllerFeedback::kGoalReached:
|
||||
return "goal_reached";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const char* toString(RecoveryFeedback feedback)
|
||||
{
|
||||
switch (feedback)
|
||||
{
|
||||
case RecoveryFeedback::kIdle:
|
||||
return "idle";
|
||||
case RecoveryFeedback::kRunning:
|
||||
return "running";
|
||||
case RecoveryFeedback::kSucceeded:
|
||||
return "succeeded";
|
||||
case RecoveryFeedback::kFailed:
|
||||
return "failed";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ================================================================================================
|
||||
@@ -46,6 +100,11 @@ bool ControlLoopConfig::validate(std::string& error) const
|
||||
error = "nominal_control_period must be > 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(planner_frequency) || planner_frequency < 0.0)
|
||||
{
|
||||
error = "planner_frequency must be >= 0 [Hz] (0 = no background replanning)";
|
||||
return false;
|
||||
}
|
||||
if (position.local_planner_name.empty())
|
||||
{
|
||||
error = "profile 'position' must have local_planner_name";
|
||||
@@ -77,6 +136,8 @@ std::string ControlLoopConfig::describe() const
|
||||
out << velocity.describe();
|
||||
out << "ControlLoop:\n";
|
||||
out << " nominal_control_period: " << nominal_control_period << " s\n";
|
||||
out << " planner_frequency : " << planner_frequency << " Hz"
|
||||
<< (planner_frequency > 0.0 ? "" : " (no background replanning)") << '\n';
|
||||
out << " robot_base_frame : " << robot_base_frame << '\n';
|
||||
out << " profile position : " << position.global_planner_name << " / "
|
||||
<< position.local_planner_name << '\n';
|
||||
@@ -89,6 +150,11 @@ std::string ControlLoopConfig::describe() const
|
||||
return out.str();
|
||||
}
|
||||
|
||||
bool ControlLoopConfig::PathMonitorConfig::monitors(MotionProfile profile) const
|
||||
{
|
||||
return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// ControlLoop
|
||||
// ================================================================================================
|
||||
@@ -119,6 +185,54 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
|
||||
|
||||
config_ = config;
|
||||
deps_ = deps;
|
||||
|
||||
// Bật giám sát mà không có đường xử lý nào là cấu hình vô nghĩa — và trước đây nó im lặng. Không
|
||||
// chặn boot (navigation vẫn phải chạy), nhưng phải hét lên: người vận hành khai `enabled: true`
|
||||
// thì tin rằng cơ chế đang chạy.
|
||||
if (config_.path_monitor.enabled)
|
||||
{
|
||||
if (deps_.path_check == nullptr)
|
||||
{
|
||||
robot::log_error("[move_base2] path_monitor is enabled but no PathCheckPort is wired — path "
|
||||
"monitoring stays OFF.\n");
|
||||
}
|
||||
else if (!config_.path_monitor.path_blocked_enabled && !config_.path_monitor.off_path_enabled)
|
||||
{
|
||||
robot::log_warning("[move_base2] path_monitor/enabled is true but BOTH sub-monitors are off "
|
||||
"(path_blocked_enabled=false, off_path_enabled=false) — path monitoring "
|
||||
"does nothing.\n");
|
||||
}
|
||||
else if (config_.state_machine.recovery_routes.path_blocked.empty() &&
|
||||
config_.state_machine.recovery_routes.off_path.empty())
|
||||
{
|
||||
robot::log_error("[move_base2] path_monitor is enabled but BOTH recovery routes "
|
||||
"'path_blocked' and 'off_path' are empty (behaviors failed to load?) — path "
|
||||
"monitoring stays OFF.\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
// In trạng thái THẬT của từng phép đo, đã gộp cả ba nút: đọc một dòng là biết cái nào sống.
|
||||
const bool blocked_on = config_.path_monitor.path_blocked_enabled &&
|
||||
config_.path_monitor.horizon > 0.0 &&
|
||||
!config_.state_machine.recovery_routes.path_blocked.empty();
|
||||
const bool off_path_on = config_.path_monitor.off_path_enabled &&
|
||||
config_.path_monitor.max_cross_track > 0.0 &&
|
||||
!config_.state_machine.recovery_routes.off_path.empty();
|
||||
robot::log_info("[move_base2] path monitor ON (confirm=%.2f s, check=%.2f s):\n"
|
||||
" path_blocked: %s (flag=%s, horizon=%.2f m, route=%zu)\n"
|
||||
" off_path : %s (flag=%s, max_cross_track=%.2f m, route=%zu)\n",
|
||||
config_.path_monitor.confirm_time, config_.path_monitor.check_period,
|
||||
blocked_on ? "ON" : "OFF",
|
||||
config_.path_monitor.path_blocked_enabled ? "on" : "off",
|
||||
config_.path_monitor.horizon,
|
||||
config_.state_machine.recovery_routes.path_blocked.size(),
|
||||
off_path_on ? "ON" : "OFF",
|
||||
config_.path_monitor.off_path_enabled ? "on" : "off",
|
||||
config_.path_monitor.max_cross_track,
|
||||
config_.state_machine.recovery_routes.off_path.size());
|
||||
}
|
||||
}
|
||||
|
||||
initialized_ = true;
|
||||
reset();
|
||||
return true;
|
||||
@@ -153,6 +267,9 @@ void ControlLoop::reset()
|
||||
|
||||
has_last_cycle_time_ = false;
|
||||
has_oscillation_origin_ = false;
|
||||
last_plan_started_ = robot::Time();
|
||||
resetPathMonitor();
|
||||
has_last_plan_applied_ = false;
|
||||
|
||||
has_outcome_ = false;
|
||||
outcome_report_count_ = 0;
|
||||
@@ -394,6 +511,18 @@ void ControlLoop::collectPlannerResult()
|
||||
// rỗng lọt xuống sẽ thành front()/back() trên vector rỗng ở tầng dưới.
|
||||
if (!result.succeeded || result.plan.empty())
|
||||
{
|
||||
// Replan NỀN hỏng (đang kControlling): bỏ qua, plan cũ vẫn hiệu lực và robot đang bám nó bình
|
||||
// thường. Không kích backup planner ở đây — một lượt replan nền hụt (robot đi qua vùng hẹp,
|
||||
// costmap tạm bít) mà đổi hẳn sang SBPL là mất quỹ đạo NURBS của order cho phần còn lại của
|
||||
// chặng. Backup chỉ dành cho lúc THẬT SỰ cần plan mà không có (kPlanning).
|
||||
if (state_machine_.state() == NavigationState::kControlling)
|
||||
{
|
||||
robot::log_warning_throttle(5.0, "[move_base2] background replan failed; keeping the "
|
||||
"current plan.\n");
|
||||
planner_feedback_ = PlannerFeedback::kFailed;
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback thuộc policy của control loop, không phải recovery: planner chính đã kết thúc nên
|
||||
// worker rảnh để nạp/chạy SBPL ngay cycle này. Chỉ thử một lần cho cả request; backup fail thì
|
||||
// giữ kFailed để state machine đi đúng đường recovery hiện có.
|
||||
@@ -421,10 +550,172 @@ void ControlLoop::collectPlannerResult()
|
||||
return;
|
||||
}
|
||||
|
||||
// Luật "không thay plan sạch bằng plan bẩn" (contract 2026-08-04d).
|
||||
//
|
||||
// Không có luật này thì cơ chế detour tự phá chính nó: `CustomPlanner` mù costmap nên mỗi nhịp
|
||||
// `planner_frequency` nó trả lại đúng đường thẳng xuyên vật cản, ghi đè đường vòng vừa lập, rồi
|
||||
// PathMonitor lại khai hoả — robot dừng-detour-chạy-dừng mỗi giây và ngân sách route cạn rất
|
||||
// nhanh.
|
||||
//
|
||||
// Chỉ áp ở kControlling, nơi ĐANG có một plan để giữ. Ở kPlanning vẫn nhận plan bẩn như cũ:
|
||||
// PathMonitor sẽ khai hoả ngay khi vào kControlling, nên mọi tình huống tuyến-bị-chắn đi qua đúng
|
||||
// MỘT đường xử lý thay vì hai.
|
||||
//
|
||||
// Hệ quả đẹp: khi robot đã đi qua vật cản, plan thẳng của planner chính hết bị chắn nên được nhận
|
||||
// lại — robot tự quay về đúng tuyến/NURBS của order, không cần cơ chế nào để "kết thúc detour".
|
||||
if (state_machine_.state() == NavigationState::kControlling && !latest_plan_.empty() &&
|
||||
planIsBlocked(result.plan, 0))
|
||||
{
|
||||
robot::log_warning_throttle(5.0, "[move_base2] a fresh plan runs into an obstacle; keeping the "
|
||||
"current plan.\n");
|
||||
planner_feedback_ = PlannerFeedback::kFailed;
|
||||
return;
|
||||
}
|
||||
|
||||
latest_plan_.swap(result.plan);
|
||||
// Tuyến THAM CHIẾU của chặng = plan do PLANNER sinh, không phải plan đã bị recovery thay
|
||||
// (contract 2026-08-05e). Detour nối lại vào nó nên robot tự quay về tuyến order thay vì trôi
|
||||
// dần theo từng đường vòng, và `max_deviation` đo đúng hành lang mà fleet đã duyệt.
|
||||
order_plan_ = latest_plan_;
|
||||
planner_feedback_ = PlannerFeedback::kPlanReady;
|
||||
}
|
||||
|
||||
void ControlLoop::resetPathMonitor()
|
||||
{
|
||||
path_blocked_ = false;
|
||||
off_path_ = false;
|
||||
has_last_path_check_ = false;
|
||||
blocked_seen_ = false;
|
||||
off_path_seen_ = false;
|
||||
}
|
||||
|
||||
bool ControlLoop::planIsBlocked(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index) const
|
||||
{
|
||||
if (deps_.path_check == nullptr || !(config_.path_monitor.horizon > 0.0) || plan.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
PlanBlockResult result;
|
||||
if (!deps_.path_check->checkPlan(plan, from_index, config_.path_monitor.horizon, result))
|
||||
{
|
||||
// Không kết luận được (thiếu TF/costmap). "Không biết" KHÔNG được suy thành "bẩn": làm vậy là
|
||||
// robot dừng mỗi lần TF trễ một nhịp.
|
||||
return false;
|
||||
}
|
||||
|
||||
if (result.blocked)
|
||||
{
|
||||
last_block_distance_ = result.distance; // [m] chỉ để log; không tham gia quyết định.
|
||||
}
|
||||
return result.blocked && result.distance >= config_.path_monitor.min_detour_distance;
|
||||
}
|
||||
|
||||
void ControlLoop::updatePathMonitor(const robot::Time& now,
|
||||
const robot_geometry_msgs::PoseStamped& robot_pose,
|
||||
bool pose_available, bool costmap_stale)
|
||||
{
|
||||
const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor;
|
||||
|
||||
// Cổng vào: chỉ giám sát khi thực sự đang bám một plan của một profile được phép, với dữ liệu còn
|
||||
// dùng được. Thiếu bất kỳ điều kiện nào thì XOÁ luôn trạng thái debounce — nếu chỉ bỏ qua, chuỗi
|
||||
// "đúng liên tục" sẽ được nối lại qua một quãng gián đoạn và `confirm_time` mất ý nghĩa.
|
||||
const bool monitorable = cfg.enabled && deps_.path_check != nullptr && has_active_request_ &&
|
||||
pose_available && !costmap_stale && !latest_plan_.empty() &&
|
||||
state_machine_.state() == NavigationState::kControlling &&
|
||||
cfg.monitors(active_request_.profile);
|
||||
|
||||
if (!monitorable)
|
||||
{
|
||||
resetPathMonitor();
|
||||
return;
|
||||
}
|
||||
|
||||
// Route rỗng = KHÔNG có đường xử lý cho trigger đó. Khai hoả trong tình trạng này là biến một cơ
|
||||
// chế đang tắt thành ABORT tức thì: state machine thấy cờ, gọi escalateToRecovery, route cạn ngay
|
||||
// từ phần tử đầu, và chặng chết ngay lần đầu thấy vật cản. Giám sát cái mà không ai xử lý được
|
||||
// thì thà đừng giám sát — để `controller_patience` lo như trước khi có cơ chế này.
|
||||
//
|
||||
// Ba nút độc lập cho mỗi phép đo, cố ý: cờ riêng (`path_blocked_enabled`/`off_path_enabled`,
|
||||
// 2026-08-06 — nói thẳng ý định thay vì đặt ngưỡng về 0), ngưỡng của chính nó, và route.
|
||||
const bool blocked_route_ready = cfg.path_blocked_enabled &&
|
||||
!config_.state_machine.recovery_routes.path_blocked.empty();
|
||||
const bool off_path_route_ready = cfg.off_path_enabled &&
|
||||
!config_.state_machine.recovery_routes.off_path.empty();
|
||||
|
||||
// Nhịp quét riêng: đọc vài chục ô costmap mỗi control cycle 30 Hz là phí, mà vật cản cũng không
|
||||
// xuất hiện nhanh hơn chu kỳ cập nhật costmap (6 Hz).
|
||||
if (has_last_path_check_ && (now - last_path_check_).toSec() < cfg.check_period)
|
||||
{
|
||||
return;
|
||||
}
|
||||
last_path_check_ = now;
|
||||
has_last_path_check_ = true;
|
||||
|
||||
const std::size_t from = nearestIndex(latest_plan_, robot_pose);
|
||||
|
||||
// --- Phép đo 1: tuyến phía trước có bị chắn không -------------------------------------------
|
||||
const bool blocked_now = blocked_route_ready && planIsBlocked(latest_plan_, from);
|
||||
if (blocked_now)
|
||||
{
|
||||
if (!blocked_seen_)
|
||||
{
|
||||
blocked_since_ = now;
|
||||
blocked_seen_ = true;
|
||||
}
|
||||
if (!path_blocked_ && (now - blocked_since_).toSec() >= cfg.confirm_time)
|
||||
{
|
||||
path_blocked_ = true;
|
||||
robot::log_warning("[move_base2] PathMonitor: the path ahead is blocked at %.2f m (horizon "
|
||||
"%.2f m) — stopping to plan a detour.\n",
|
||||
last_block_distance_, cfg.horizon);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
blocked_seen_ = false;
|
||||
path_blocked_ = false;
|
||||
}
|
||||
|
||||
// --- Phép đo 2: robot đã lệch khỏi plan bao xa ----------------------------------------------
|
||||
//
|
||||
// Đo so với PLAN ĐANG CHẠY, không phải tuyến gốc của order: sau một lượt detour hợp lệ, plan đang
|
||||
// chạy CHÍNH LÀ đường vòng và robot nằm trên nó, nên không khai hoả oan. Ràng buộc "lệch bao
|
||||
// nhiêu so với tuyến fleet" là việc của `max_deviation` bên trong behavior detour.
|
||||
const bool grace = has_last_plan_applied_ &&
|
||||
(now - last_plan_applied_).toSec() < cfg.grace_after_new_plan;
|
||||
|
||||
if (off_path_route_ready && cfg.max_cross_track > 0.0 && !grace)
|
||||
{
|
||||
const double error = crossTrackError(latest_plan_, robot_pose); // [m]
|
||||
if (error > cfg.max_cross_track)
|
||||
{
|
||||
if (!off_path_seen_)
|
||||
{
|
||||
off_path_since_ = now;
|
||||
off_path_seen_ = true;
|
||||
}
|
||||
if (!off_path_ && (now - off_path_since_).toSec() >= cfg.confirm_time)
|
||||
{
|
||||
off_path_ = true;
|
||||
robot::log_warning("[move_base2] PathMonitor: the robot is %.2f m off the plan (limit "
|
||||
"%.2f m) — stopping.\n", error, cfg.max_cross_track);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
off_path_seen_ = false;
|
||||
off_path_ = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
off_path_seen_ = false;
|
||||
off_path_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
|
||||
{
|
||||
candidate = robot_geometry_msgs::Twist();
|
||||
@@ -486,6 +777,15 @@ bool ControlLoop::step()
|
||||
travelled = std::hypot(dx, dy);
|
||||
}
|
||||
|
||||
// Costmap còn hạn không — hỏi ở ĐÂY chứ không ở mục 3.5 như trước: PathMonitor 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();
|
||||
|
||||
// --- 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.
|
||||
updatePathMonitor(now, robot_pose, pose_available, costmap_stale);
|
||||
|
||||
// --- 2. State machine -----------------------------------------------------------------------
|
||||
StateMachineInput input;
|
||||
input.now = now;
|
||||
@@ -500,8 +800,11 @@ bool ControlLoop::step()
|
||||
input.recovery = recovery_feedback_;
|
||||
input.action = action_feedback_;
|
||||
input.pose_available = pose_available;
|
||||
input.costmap_current = !costmap_stale;
|
||||
input.robot_stopped = arbiter_.stopped();
|
||||
input.travelled_since_oscillation_reset = travelled;
|
||||
input.path_blocked = path_blocked_;
|
||||
input.off_path = off_path_;
|
||||
|
||||
// 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
|
||||
@@ -516,6 +819,11 @@ bool ControlLoop::step()
|
||||
if (output.state_changed)
|
||||
{
|
||||
last_reason_ = output.reason;
|
||||
robot::log_info("[move_base2][debug] state -> %s: %s "
|
||||
"(planner=%s controller=%s recovery=%s pose=%s active_request=%s).\n",
|
||||
toString(output.state), output.reason != nullptr ? output.reason : "",
|
||||
toString(input.planner), toString(input.controller), toString(input.recovery),
|
||||
pose_available ? "yes" : "no", has_active_request_ ? "yes" : "no");
|
||||
}
|
||||
|
||||
// Cờ một-lần đã được state machine tiêu thụ xong ở lời gọi trên.
|
||||
@@ -542,6 +850,7 @@ bool ControlLoop::step()
|
||||
has_active_request_ = true;
|
||||
has_pending_request_ = false;
|
||||
latest_plan_.clear();
|
||||
order_plan_.clear();
|
||||
has_outcome_ = false;
|
||||
|
||||
// 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.
|
||||
@@ -563,6 +872,10 @@ bool ControlLoop::step()
|
||||
++plan_tag_;
|
||||
deps_.planner->cancelPlan();
|
||||
planner_running_ = false;
|
||||
|
||||
// Nhịp replan nền đếm lại từ đầu chặng — lượt plan đầu tiên của chặng do state machine yêu
|
||||
// cầu, replan nền chỉ bắt đầu sau đó một chu kỳ đầy đủ.
|
||||
last_plan_started_ = now;
|
||||
}
|
||||
|
||||
if (output.reset_oscillation_origin && pose_available)
|
||||
@@ -585,6 +898,28 @@ bool ControlLoop::step()
|
||||
{
|
||||
// Controller từ chối plan: coi như lần lập plan này hỏng, để chu kỳ kiên nhẫn tiếp tục chạy.
|
||||
planner_feedback_ = PlannerFeedback::kFailed;
|
||||
robot::log_error("[move_base2][debug] controller rejected plan with %zu pose(s); "
|
||||
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
|
||||
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
||||
latest_plan_.front().pose.position.y,
|
||||
latest_plan_.front().header.frame_id.c_str(),
|
||||
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
||||
latest_plan_.back().header.frame_id.c_str());
|
||||
}
|
||||
else
|
||||
{
|
||||
// Mốc cho `grace_after_new_plan`: ngay sau khi đổi plan, pose robot có thể còn lệch so với
|
||||
// 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;
|
||||
|
||||
robot::log_info("[move_base2][debug] controller accepted plan with %zu pose(s); "
|
||||
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
|
||||
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
||||
latest_plan_.front().pose.position.y,
|
||||
latest_plan_.front().header.frame_id.c_str(),
|
||||
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
||||
latest_plan_.back().header.frame_id.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,6 +928,19 @@ bool ControlLoop::step()
|
||||
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
|
||||
// robot vẫn tiến về phía vật cản.
|
||||
if (output.monitor_trigger_suppressed)
|
||||
{
|
||||
robot::log_warning("[move_base2] %s: no detour left — continuing on the current plan. From "
|
||||
"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);
|
||||
}
|
||||
|
||||
robot_geometry_msgs::Twist candidate;
|
||||
|
||||
if (output.start_recovery)
|
||||
@@ -628,6 +976,13 @@ 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;
|
||||
planner_feedback_ = PlannerFeedback::kPlanReady;
|
||||
robot::log_info("[move_base2][debug] recovery produced path with %zu pose(s); "
|
||||
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
|
||||
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
||||
latest_plan_.front().pose.position.y,
|
||||
latest_plan_.front().header.frame_id.c_str(),
|
||||
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
||||
latest_plan_.back().header.frame_id.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -677,8 +1032,6 @@ bool ControlLoop::step()
|
||||
// nó đi là bịt mất lối phục hồi duy nhất còn tác dụng. Behavior họ velocity không bị thiệt vì
|
||||
// chúng đo tiến độ bằng POSE: robot không nhúc nhích thì chúng tự hết giờ và báo hỏng, chứ không
|
||||
// báo thành công nhầm.
|
||||
const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr &&
|
||||
!deps_.costmap_status->isCurrent();
|
||||
if (costmap_stale)
|
||||
{
|
||||
// Throttle: đây là vòng lặp điều khiển, và tình trạng này kéo dài hàng giây.
|
||||
@@ -687,12 +1040,67 @@ bool ControlLoop::step()
|
||||
"costmap is describing a past world).\n");
|
||||
}
|
||||
|
||||
if (output.state == NavigationState::kControlling && !pose_available)
|
||||
{
|
||||
robot::log_warning_throttle(
|
||||
kDebugControlLogThrottle,
|
||||
"[move_base2][debug] controller skipped while CONTROLLING: pose unavailable "
|
||||
"(reason=%s, controller_feedback_in=%s, recovery_cursor=%zu/%zu).\n",
|
||||
output.reason != nullptr ? output.reason : "", toString(input.controller),
|
||||
output.recovery_route_cursor, output.recovery_route_size);
|
||||
}
|
||||
|
||||
if (output.run_controller && costmap_stale)
|
||||
{
|
||||
robot::log_warning_throttle(
|
||||
kDebugControlLogThrottle,
|
||||
"[move_base2][debug] controller skipped while CONTROLLING: costmap stale "
|
||||
"(reason=%s, controller_feedback_in=%s, recovery_cursor=%zu/%zu).\n",
|
||||
output.reason != nullptr ? output.reason : "", toString(input.controller),
|
||||
output.recovery_route_cursor, output.recovery_route_size);
|
||||
}
|
||||
|
||||
if (output.run_controller && !costmap_stale)
|
||||
{
|
||||
runController(candidate);
|
||||
if (controller_feedback_ == ControllerFeedback::kNoValidCommand)
|
||||
{
|
||||
robot::log_warning_throttle(
|
||||
kDebugControlLogThrottle,
|
||||
"[move_base2][debug] controller returned no valid command "
|
||||
"(reason=%s, planner_in=%s, controller_in=%s, recovery_in=%s, pose=%s, "
|
||||
"recovery_cursor=%zu/%zu).\n",
|
||||
output.reason != nullptr ? output.reason : "", toString(input.planner),
|
||||
toString(input.controller), toString(input.recovery), pose_available ? "yes" : "no",
|
||||
output.recovery_route_cursor, output.recovery_route_size);
|
||||
}
|
||||
// else if (controller_feedback_ == ControllerFeedback::kCommandValid)
|
||||
// {
|
||||
// robot::log_info_throttle(kDebugControlLogThrottle,
|
||||
// "[move_base2][debug] controller command valid: v=%.3f wz=%.3f.\n",
|
||||
// candidate.linear.x, candidate.angular.z);
|
||||
// }
|
||||
}
|
||||
|
||||
if (output.start_planner && pose_available && !planner_running_)
|
||||
// Replan nền (contract 2026-08-04): đang bám plan và tới nhịp `planner_frequency` thì khởi động
|
||||
// một lượt lập plan mới trên thread planner. Plan mới về được kControlling nhận ngay (apply_plan)
|
||||
// mà KHÔNG đổi state — controller không dừng một cycle nào. Đây là cơ chế thay plan duy nhất
|
||||
// trong lúc chạy, vì controller hỏng không còn kéo máy về kPlanning nữa.
|
||||
//
|
||||
// Nhịp đếm lại mỗi lần (TÁI) vào kControlling: sau recovery bám tiếp plan cũ — hoặc nhận path
|
||||
// detour — plan đó phải sống được trọn một chu kỳ planner_frequency trước khi lượt replan nền
|
||||
// đầu tiên có quyền thay nó. Không đếm lại thì đồng hồ vẫn mang cả quãng thời gian nằm trong
|
||||
// recovery và replan nền nổ ngay cycle đầu sau khi quay lại, đè mất path detour vừa nộp.
|
||||
if (output.state_changed && output.state == NavigationState::kControlling)
|
||||
{
|
||||
last_plan_started_ = now;
|
||||
}
|
||||
|
||||
const bool periodic_replan_due =
|
||||
config_.planner_frequency > 0.0 && output.state == NavigationState::kControlling &&
|
||||
(now - last_plan_started_).toSec() >= 1.0 / config_.planner_frequency;
|
||||
|
||||
if ((output.start_planner || periodic_replan_due) && pose_available && !planner_running_)
|
||||
{
|
||||
// `start_planner` là tín hiệu MỨC ("hãy đang lập plan"), bật lại mỗi cycle chừng nào state
|
||||
// machine còn ở kPlanning — không phải sườn. Kick lại một lượt đang chạy sẽ vừa bị cổng từ
|
||||
@@ -702,10 +1110,15 @@ bool ControlLoop::step()
|
||||
const robot_protocol_msgs::Order* order =
|
||||
backup_global_planner_active_ ? nullptr : active_request_.order.get();
|
||||
planner_running_ = deps_.planner->startPlan(robot_pose, active_request_.goal, order, plan_tag_);
|
||||
if (!planner_running_)
|
||||
if (planner_running_)
|
||||
{
|
||||
last_plan_started_ = now;
|
||||
}
|
||||
else if (output.start_planner)
|
||||
{
|
||||
// Không khởi động được (chưa có planner, pose hỏng...). Coi như một lượt hỏng để đồng hồ
|
||||
// kiên nhẫn tiếp tục chạy, thay vì đứng im ở kPlanning vô hạn.
|
||||
// kiên nhẫn tiếp tục chạy, thay vì đứng im ở kPlanning vô hạn. Riêng replan NỀN không khởi
|
||||
// động được thì bỏ qua — plan cũ vẫn hiệu lực, nhịp sau thử lại.
|
||||
planner_feedback_ = PlannerFeedback::kFailed;
|
||||
}
|
||||
}
|
||||
@@ -737,6 +1150,17 @@ bool ControlLoop::step()
|
||||
static_cast<unsigned long long>(outgoing_mission_id));
|
||||
break;
|
||||
case NavigationOutcome::kFailed:
|
||||
if (output.reason != nullptr &&
|
||||
std::strcmp(output.reason, "no recovery behavior left") == 0)
|
||||
{
|
||||
robot::log_error("[move_base2][debug] 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,
|
||||
output.recovery_route_size, toString(input.planner),
|
||||
toString(input.controller), toString(input.recovery),
|
||||
pose_available ? "yes" : "no", costmap_stale ? "no" : "yes");
|
||||
}
|
||||
robot::log_error("[move_base2] Navigation failed (mission %llu: ABORTED): %s\n",
|
||||
static_cast<unsigned long long>(outgoing_mission_id),
|
||||
last_reason_ != nullptr ? last_reason_ : "");
|
||||
|
||||
@@ -10,8 +10,11 @@
|
||||
|
||||
#include <exception>
|
||||
|
||||
#include <boost/thread/locks.hpp>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/robot.h>
|
||||
#include <robot_costmap_2d/costmap_2d.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
@@ -54,6 +57,36 @@ bool CostmapPosePort::lookupPose(const std::string& frame,
|
||||
}
|
||||
}
|
||||
|
||||
bool CostmapPathCheck::checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index, double horizon,
|
||||
PlanBlockResult& out) const
|
||||
{
|
||||
if (costmap_ == nullptr || !tf_ || plan.empty() || from_index >= plan.size())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
robot_costmap_2d::Costmap2D* grid = costmap_->getCostmap();
|
||||
if (grid == nullptr)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
PlanarTransform plan_to_grid;
|
||||
if (!planarTransform(*tf_, plan[from_index].header.frame_id, costmap_->getGlobalFrameID(),
|
||||
plan_to_grid))
|
||||
{
|
||||
// Không quy đổi được frame thì mọi kết luận đều vô nghĩa. Trả false = "không biết".
|
||||
return false;
|
||||
}
|
||||
|
||||
// Cùng giao thức khoá với map-update thread và planner: lượt quét chỉ đọc vài chục ô nên giữ
|
||||
// mutex trọn lượt là rẻ, còn đọc lưới trong lúc nó đang được ghi thì kết luận không đáng tin.
|
||||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()));
|
||||
out = move_base2::checkPlan(plan, from_index, horizon, *grid, plan_to_grid);
|
||||
return true;
|
||||
}
|
||||
|
||||
NavigationRuntime::NavigationRuntime() = default;
|
||||
|
||||
NavigationRuntime::~NavigationRuntime()
|
||||
@@ -131,6 +164,10 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf
|
||||
// Costmap ĐIỀU KHIỂN (local) là nguồn của guard "không đi mù" — xem doc của CostmapStatusAdapter.
|
||||
costmap_status_.setCostmap(local_costmap_.get());
|
||||
|
||||
// PathMonitor quét tuyến trên chính costmap local — cùng lưới mà detour lập đường vòng trên đó.
|
||||
path_check_.setCostmap(local_costmap_.get());
|
||||
path_check_.setTf(tf_);
|
||||
|
||||
// Gắn ngay: host có thể hỏi dữ liệu hiển thị bất cứ lúc nào sau initialize(), kể cả trước khi
|
||||
// costmap có nội dung. Exporter tự trả về "chưa có gì" thay vì lưới rỗng.
|
||||
global_exporter_.attach(global_costmap_.get(), config_.global_frame);
|
||||
@@ -189,6 +226,9 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
||||
recovery_deps.pose = &local_pose_;
|
||||
recovery_deps.local_costmap = local_costmap_.get();
|
||||
recovery_deps.global_costmap = global_costmap_.get();
|
||||
// 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_.setDeps(recovery_deps);
|
||||
recovery_.setNamespace(config_.recovery_namespace);
|
||||
|
||||
@@ -370,6 +410,7 @@ ControlLoopDeps NavigationRuntime::deps()
|
||||
deps.mission = &mission_;
|
||||
deps.action = &action_;
|
||||
deps.costmap_status = &costmap_status_;
|
||||
deps.path_check = &path_check_;
|
||||
return deps;
|
||||
}
|
||||
|
||||
|
||||
@@ -436,6 +436,34 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
|
||||
// vòng ngược lên xoá hàng đợi của nó.
|
||||
runtime_->mission().setCancelCallback([this]() { requestLoopCancel(); });
|
||||
|
||||
// Behavior recovery họ path (DetourPathRecovery) cần plan hiện hành để chọn điểm nối lại tuyến.
|
||||
// Callback chạy trên CONTROL THREAD — recovery chỉ được start/tick từ đó — cùng thread với
|
||||
// latestPlan(), nên không cần lock.
|
||||
runtime_->recoveryRunner().setPlanSource(
|
||||
[this](std::vector<robot_geometry_msgs::PoseStamped>& out) {
|
||||
const std::vector<robot_geometry_msgs::PoseStamped>& plan = loop_.latestPlan();
|
||||
if (plan.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
out = plan;
|
||||
return true;
|
||||
});
|
||||
|
||||
// Tuyến THAM CHIẾU: plan gần nhất do PLANNER sinh, recovery không thay được. Detour nối lại vào
|
||||
// nó nên robot tự quay về tuyến order thay vì trôi dần theo từng đường vòng chồng lên nhau, và
|
||||
// hành lang `max_deviation` được đo với đúng tuyến mà fleet đã duyệt (contract 2026-08-05e).
|
||||
runtime_->recoveryRunner().setReferencePlanSource(
|
||||
[this](std::vector<robot_geometry_msgs::PoseStamped>& out) {
|
||||
const std::vector<robot_geometry_msgs::PoseStamped>& plan = loop_.orderPlan();
|
||||
if (plan.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
out = plan;
|
||||
return true;
|
||||
});
|
||||
|
||||
// start() sau cùng: cho thread cập nhật costmap chạy khi mọi thứ khác đã lắp xong.
|
||||
runtime_->start();
|
||||
|
||||
|
||||
@@ -100,6 +100,10 @@ const char* toString(RecoveryTrigger trigger)
|
||||
return "controlling_failed";
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return "oscillation";
|
||||
case RecoveryTrigger::kPathBlocked:
|
||||
return "path_blocked";
|
||||
case RecoveryTrigger::kOffPath:
|
||||
return "off_path";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
@@ -114,12 +118,19 @@ const std::vector<std::size_t>& RecoveryRoutes::forTrigger(RecoveryTrigger trigg
|
||||
return controlling_failed;
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return oscillation;
|
||||
case RecoveryTrigger::kPathBlocked:
|
||||
return path_blocked;
|
||||
case RecoveryTrigger::kOffPath:
|
||||
return off_path;
|
||||
}
|
||||
return planning_failed;
|
||||
}
|
||||
|
||||
bool RecoveryRoutes::empty() const
|
||||
{
|
||||
// CHỈ xét ba route gốc: `empty()` là câu hỏi "config có dùng schema legacy không", và schema
|
||||
// legacy không biết tới hai route giám sát tuyến. Hai route mới rỗng là trạng thái bình thường
|
||||
// (cơ chế giám sát tắt), không phải dấu hiệu của legacy.
|
||||
return planning_failed.empty() && controlling_failed.empty() && oscillation.empty();
|
||||
}
|
||||
|
||||
|
||||
194
src/plan_inspector.cpp
Normal file
194
src/plan_inspector.cpp
Normal file
@@ -0,0 +1,194 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — cài đặt plan_inspector.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/core/plan_inspector.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
|
||||
#include <robot_costmap_2d/costmap_2d.h>
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
/// [m] Dưới ngưỡng này thì một đoạn plan coi như suy biến thành điểm.
|
||||
constexpr double kDegenerateSegment = 1e-9;
|
||||
|
||||
/// @brief [m] Khoảng cách từ điểm (px,py) tới đoạn thẳng (ax,ay)-(bx,by).
|
||||
double pointToSegment(double px, double py, double ax, double ay, double bx, double by)
|
||||
{
|
||||
const double dx = bx - ax;
|
||||
const double dy = by - ay;
|
||||
const double len_sq = dx * dx + dy * dy;
|
||||
|
||||
if (len_sq <= kDegenerateSegment)
|
||||
{
|
||||
return std::hypot(px - ax, py - ay);
|
||||
}
|
||||
|
||||
double t = ((px - ax) * dx + (py - ay) * dy) / len_sq;
|
||||
t = std::max(0.0, std::min(1.0, t));
|
||||
return std::hypot(px - (ax + t * dx), py - (ay + t * dy));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool planarTransform(const tf3::BufferCore& tf, const std::string& from, const std::string& to,
|
||||
PlanarTransform& out)
|
||||
{
|
||||
out = PlanarTransform();
|
||||
|
||||
if (from.empty() || to.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (from == to)
|
||||
{
|
||||
return true; // Identity — không cần chạm tới TF.
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
const tf3::TransformStampedMsg tf_msg =
|
||||
const_cast<tf3::BufferCore&>(tf).lookupTransform(to, from, tf3::Time());
|
||||
|
||||
const auto& q = tf_msg.transform.rotation;
|
||||
const double yaw =
|
||||
std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)); // [rad]
|
||||
|
||||
out.x = tf_msg.transform.translation.x;
|
||||
out.y = tf_msg.transform.translation.y;
|
||||
out.cos_yaw = std::cos(yaw);
|
||||
out.sin_yaw = std::sin(yaw);
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception&)
|
||||
{
|
||||
// Không log ở đây: hàm này chạy theo nhịp monitor. Bên gọi quyết định có báo hay không.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t nearestIndex(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
const robot_geometry_msgs::PoseStamped& pose)
|
||||
{
|
||||
if (plan.size() < 2)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
const double px = pose.pose.position.x;
|
||||
const double py = pose.pose.position.y;
|
||||
|
||||
std::size_t best = 0;
|
||||
double best_distance = std::numeric_limits<double>::max();
|
||||
|
||||
for (std::size_t i = 0; i + 1 < plan.size(); ++i)
|
||||
{
|
||||
const double distance =
|
||||
pointToSegment(px, py, plan[i].pose.position.x, plan[i].pose.position.y,
|
||||
plan[i + 1].pose.position.x, plan[i + 1].pose.position.y);
|
||||
if (distance < best_distance)
|
||||
{
|
||||
best_distance = distance;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
double crossTrackError(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
const robot_geometry_msgs::PoseStamped& pose)
|
||||
{
|
||||
if (plan.empty())
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
const double px = pose.pose.position.x;
|
||||
const double py = pose.pose.position.y;
|
||||
|
||||
if (plan.size() == 1)
|
||||
{
|
||||
return std::hypot(px - plan.front().pose.position.x, py - plan.front().pose.position.y);
|
||||
}
|
||||
|
||||
double best = std::numeric_limits<double>::max();
|
||||
for (std::size_t i = 0; i + 1 < plan.size(); ++i)
|
||||
{
|
||||
best = std::min(best, pointToSegment(px, py, plan[i].pose.position.x, plan[i].pose.position.y,
|
||||
plan[i + 1].pose.position.x, plan[i + 1].pose.position.y));
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
PlanBlockResult checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index, double horizon,
|
||||
const robot_costmap_2d::Costmap2D& grid,
|
||||
const PlanarTransform& plan_to_grid)
|
||||
{
|
||||
PlanBlockResult result;
|
||||
|
||||
if (plan.empty() || from_index >= plan.size() || !(horizon > 0.0))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
double travelled = 0.0; // [m]
|
||||
|
||||
for (std::size_t i = from_index; i < plan.size(); ++i)
|
||||
{
|
||||
if (i > from_index)
|
||||
{
|
||||
travelled += std::hypot(plan[i].pose.position.x - plan[i - 1].pose.position.x,
|
||||
plan[i].pose.position.y - plan[i - 1].pose.position.y);
|
||||
if (travelled > horizon)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
double gx = 0.0;
|
||||
double gy = 0.0;
|
||||
plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, gx, gy);
|
||||
|
||||
unsigned int mx = 0;
|
||||
unsigned int my = 0;
|
||||
if (!grid.worldToMap(gx, gy, mx, my))
|
||||
{
|
||||
// Ra ngoài cửa sổ lưới: phần còn lại của tuyến cũng nằm ngoài (lưới lăn theo robot), nên
|
||||
// dừng hẳn thay vì quét tiếp cho tới hết horizon.
|
||||
break;
|
||||
}
|
||||
|
||||
++result.scanned;
|
||||
|
||||
const unsigned char cost = grid.getCost(mx, my);
|
||||
if (cost == robot_costmap_2d::NO_INFORMATION)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)
|
||||
{
|
||||
result.blocked = true;
|
||||
result.index = i;
|
||||
result.distance = travelled;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
#include <boost/dll/import.hpp>
|
||||
#include <boost/system/system_error.hpp>
|
||||
#include <boost/thread/locks.hpp>
|
||||
|
||||
#include <robot/plugin_loader_helper.h>
|
||||
#include <robot/robot.h>
|
||||
@@ -331,6 +332,13 @@ bool ControllerRunner::setPlan(const std::vector<robot_geometry_msgs::PoseStampe
|
||||
|
||||
try
|
||||
{
|
||||
// Plugin có thể chiếu plan lên costmap ngay trong setPlan — khoá như hai đường gọi còn lại.
|
||||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
|
||||
if (costmap_lock_enabled_)
|
||||
{
|
||||
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
|
||||
*(costmap_->getCostmap()->getMutex()));
|
||||
}
|
||||
// Gen-2 tách goal khỏi plan: `setGoalPose` phải gọi TRƯỚC `setPlan`, đúng như
|
||||
// `LocalPlannerAdapter` làm. Goal là pose CUỐI của plan.
|
||||
const robot_nav_2d_msgs::Path2D path = robot_nav_2d_utils::posesToPath2D(plan);
|
||||
@@ -475,6 +483,15 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
|
||||
// Đo đúng lời gọi vào plugin, không đo cả hàm: phần còn lại (tra pose, kiểm NaN) là chi phí của
|
||||
// move_base2, còn đây mới là chi phí của local planner đang cấu hình.
|
||||
ScopedSection timer(stats_, section_compute_);
|
||||
// Khoá lưới local costmap trong lúc plugin tính lệnh — gen-1 giữ đúng lock này quanh mọi
|
||||
// computeVelocityCommands (move_base.cpp:1078). Thread cập nhật costmap ghi lưới dưới cùng
|
||||
// mutex; không khoá thì cost function đọc dữ liệu đang bị ghi dở.
|
||||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
|
||||
if (costmap_lock_enabled_)
|
||||
{
|
||||
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
|
||||
*(costmap_->getCostmap()->getMutex()));
|
||||
}
|
||||
// Gen-2 trả THẲNG lệnh (không có cờ thành công/thất bại) và ném exception khi không tính được —
|
||||
// ngược với gen-1. Vì vậy nhánh "không có lệnh hợp lệ" ở đây là nhánh catch.
|
||||
const robot_nav_2d_msgs::Twist2DStamped cmd_2d =
|
||||
@@ -524,6 +541,13 @@ bool ControllerRunner::isGoalReached()
|
||||
|
||||
try
|
||||
{
|
||||
// Cùng lý do với computeVelocityCommands: plugin có thể dò costmap khi kiểm đích.
|
||||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
|
||||
if (costmap_lock_enabled_)
|
||||
{
|
||||
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
|
||||
*(costmap_->getCostmap()->getMutex()));
|
||||
}
|
||||
const bool reached =
|
||||
active_->isGoalReached(pose, robot_nav_2d_utils::twist3Dto2D(measured_velocity_));
|
||||
if (reached)
|
||||
|
||||
@@ -14,9 +14,11 @@
|
||||
|
||||
#include <boost/dll/import.hpp>
|
||||
#include <boost/system/system_error.hpp>
|
||||
#include <boost/thread/locks.hpp>
|
||||
|
||||
#include <robot/plugin_loader_helper.h>
|
||||
#include <robot/robot.h>
|
||||
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
@@ -364,6 +366,17 @@ void PlannerRunner::threadBody()
|
||||
try
|
||||
{
|
||||
ScopedSection timer(stats_, section_make_plan_);
|
||||
// Khoá lưới costmap suốt makePlan — cùng giao thức với gen-1 (move_base.cpp:1921,1959):
|
||||
// LayeredCostmap::updateMap ghi lưới, và resizeMap REALLOC cả mảng, dưới đúng mutex này.
|
||||
// Không khoá thì planner đọc cost đang bị ghi dở, hoặc tệ hơn là đọc vào vùng nhớ vừa bị
|
||||
// resize giải phóng khi static map được nhận lại. 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).
|
||||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
|
||||
if (costmap_lock_enabled_)
|
||||
{
|
||||
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
|
||||
*(costmap_->getCostmap()->getMutex()));
|
||||
}
|
||||
// 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_)
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
#include <move_base2/runners/recovery_runner.h>
|
||||
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
|
||||
#include <robot/robot.h>
|
||||
@@ -29,6 +28,10 @@ recovery_core::RecoveryTrigger toCoreTrigger(RecoveryTrigger trigger)
|
||||
return recovery_core::RecoveryTrigger::kControllingFailed;
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return recovery_core::RecoveryTrigger::kOscillation;
|
||||
case RecoveryTrigger::kPathBlocked:
|
||||
return recovery_core::RecoveryTrigger::kPathBlocked;
|
||||
case RecoveryTrigger::kOffPath:
|
||||
return recovery_core::RecoveryTrigger::kOffPath;
|
||||
}
|
||||
return recovery_core::RecoveryTrigger::kUnspecified;
|
||||
}
|
||||
@@ -69,6 +72,11 @@ void RecoveryRunner::setNamespace(const std::string& ns)
|
||||
namespace_ = ns;
|
||||
}
|
||||
|
||||
void RecoveryRunner::setReferencePlanSource(PlanSource source)
|
||||
{
|
||||
reference_plan_bridge_.setSource(std::move(source));
|
||||
}
|
||||
|
||||
void RecoveryRunner::setPlanSource(PlanSource source)
|
||||
{
|
||||
plan_bridge_.setSource(std::move(source));
|
||||
@@ -84,8 +92,10 @@ void RecoveryRunner::refreshContext()
|
||||
ctx_.pose = &pose_bridge_;
|
||||
ctx_.collision = &collision_;
|
||||
ctx_.plan = &plan_bridge_;
|
||||
ctx_.reference_plan = &reference_plan_bridge_;
|
||||
ctx_.local_costmap = deps_.local_costmap;
|
||||
ctx_.global_costmap = deps_.global_costmap;
|
||||
ctx_.tf = deps_.tf;
|
||||
}
|
||||
|
||||
bool RecoveryRunner::configure(robot::NodeHandle& nh)
|
||||
@@ -178,13 +188,20 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ba route GỐC bắt buộc phải có; hai route giám sát tuyến là TUỲ CHỌN — thiếu chúng nghĩa là
|
||||
// cơ chế giám sát tắt, và mọi config đang chạy (viết trước 2026-08-04d) vẫn boot được.
|
||||
const std::pair<const char*, RecoveryTrigger> expected_routes[] = {
|
||||
{"planning_failed", RecoveryTrigger::kPlanningFailed},
|
||||
{"controlling_failed", RecoveryTrigger::kControllingFailed},
|
||||
{"oscillation", RecoveryTrigger::kOscillation},
|
||||
};
|
||||
|
||||
const auto is_expected_key = [&expected_routes](const std::string& key) {
|
||||
const std::pair<const char*, RecoveryTrigger> optional_routes[] = {
|
||||
{"path_blocked", RecoveryTrigger::kPathBlocked},
|
||||
{"off_path", RecoveryTrigger::kOffPath},
|
||||
};
|
||||
|
||||
const auto is_expected_key = [&expected_routes, &optional_routes](const std::string& key) {
|
||||
for (const auto& expected : expected_routes)
|
||||
{
|
||||
if (key == expected.first)
|
||||
@@ -192,6 +209,13 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (const auto& optional : optional_routes)
|
||||
{
|
||||
if (key == optional.first)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -210,32 +234,36 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& expected : expected_routes)
|
||||
{
|
||||
const std::string trigger_name(expected.first);
|
||||
const YAML::Node route_node = configured_routes[trigger_name];
|
||||
if (!route_node || !route_node.IsSequence())
|
||||
{
|
||||
error = routes_key + "/" + trigger_name + " must be a YAML sequence";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::size_t>* resolved = nullptr;
|
||||
switch (expected.second)
|
||||
const auto route_for = [this](RecoveryTrigger trigger) -> std::vector<std::size_t>* {
|
||||
switch (trigger)
|
||||
{
|
||||
case RecoveryTrigger::kPlanningFailed:
|
||||
resolved = &routes_.planning_failed;
|
||||
break;
|
||||
return &routes_.planning_failed;
|
||||
case RecoveryTrigger::kControllingFailed:
|
||||
resolved = &routes_.controlling_failed;
|
||||
break;
|
||||
return &routes_.controlling_failed;
|
||||
case RecoveryTrigger::kOscillation:
|
||||
resolved = &routes_.oscillation;
|
||||
break;
|
||||
return &routes_.oscillation;
|
||||
case RecoveryTrigger::kPathBlocked:
|
||||
return &routes_.path_blocked;
|
||||
case RecoveryTrigger::kOffPath:
|
||||
return &routes_.off_path;
|
||||
}
|
||||
return &routes_.planning_failed;
|
||||
};
|
||||
|
||||
// Resolve tên instance -> index registry cho MỘT route. Trả false kèm `error` khi schema sai;
|
||||
// tên không nạp được thì bỏ qua kèm cảnh báo (cho phép commit schema trước plugin).
|
||||
//
|
||||
// Một behavior ĐƯỢC PHÉP xuất hiện nhiều lần trong cùng route: mỗi lần xuất hiện là một lượt thử.
|
||||
// Đây là cách duy nhất cấp ngân sách cho vòng "thử detour — chờ — nhích lại gần — thử lại"
|
||||
// (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 YAML::Node& route_node) {
|
||||
std::vector<std::size_t>* resolved = route_for(trigger);
|
||||
resolved->clear();
|
||||
|
||||
std::set<std::size_t> seen;
|
||||
for (const YAML::Node& behavior_node : route_node)
|
||||
{
|
||||
if (!behavior_node.IsScalar())
|
||||
@@ -248,33 +276,75 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
const auto found = loaded.find(behavior_name);
|
||||
if (found == loaded.end())
|
||||
{
|
||||
// Đây là điểm cho phép commit schema trước plugin. Không tạo index giả: StateMachine chỉ
|
||||
// được thấy những index registry thực sự nạp được.
|
||||
// Không tạo index giả: StateMachine chỉ được thấy index registry thực sự nạp được.
|
||||
robot::log_warning("[move_base2] RecoveryRunner: route '%s' skips '%s' because that "
|
||||
"behavior was not loaded.",
|
||||
trigger_name.c_str(), behavior_name.c_str());
|
||||
trigger_name, behavior_name.c_str());
|
||||
continue;
|
||||
}
|
||||
if (!seen.insert(found->second).second)
|
||||
{
|
||||
error = routes_key + "/" + trigger_name + " repeats behavior '" + behavior_name + "'";
|
||||
return false;
|
||||
}
|
||||
resolved->push_back(found->second);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
if (resolved->empty())
|
||||
for (const auto& expected : expected_routes)
|
||||
{
|
||||
const std::string trigger_name(expected.first);
|
||||
const YAML::Node route_node = configured_routes[trigger_name];
|
||||
if (!route_node || !route_node.IsSequence())
|
||||
{
|
||||
error = routes_key + "/" + trigger_name +
|
||||
" has no behavior that was successfully loaded";
|
||||
error = routes_key + "/" + trigger_name + " must be a YAML sequence";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!resolve_route(expected.first, expected.second, route_node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (route_for(expected.second)->empty())
|
||||
{
|
||||
error = routes_key + "/" + trigger_name + " has no behavior that was successfully loaded";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& optional : optional_routes)
|
||||
{
|
||||
const std::string trigger_name(optional.first);
|
||||
const YAML::Node route_node = configured_routes[trigger_name];
|
||||
|
||||
if (!route_node)
|
||||
{
|
||||
// Không khai = cơ chế giám sát tuyến tắt. Đây là mặc định và là đường lùi.
|
||||
continue;
|
||||
}
|
||||
if (!route_node.IsSequence())
|
||||
{
|
||||
error = routes_key + "/" + trigger_name + " must be a YAML sequence";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!resolve_route(optional.first, optional.second, route_node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (route_for(optional.second)->empty())
|
||||
{
|
||||
// Khai route nhưng không behavior nào nạp được: KHÔNG chặn khởi động (navigation vẫn phải
|
||||
// chạy), nhưng phải hét lên — im lặng ở đây là người vận hành tưởng giám sát đang bật.
|
||||
robot::log_error("[move_base2] RecoveryRunner: route '%s' was configured but none of its "
|
||||
"behaviors loaded — that monitor stays DISABLED.",
|
||||
trigger_name.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
robot::log_info("[move_base2] RecoveryRunner: routes resolved: planning=%zu controlling=%zu "
|
||||
"oscillation=%zu.",
|
||||
"oscillation=%zu path_blocked=%zu off_path=%zu.",
|
||||
routes_.planning_failed.size(), routes_.controlling_failed.size(),
|
||||
routes_.oscillation.size());
|
||||
routes_.oscillation.size(), routes_.path_blocked.size(),
|
||||
routes_.off_path.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -333,6 +403,8 @@ bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
|
||||
}
|
||||
|
||||
active_ = behavior;
|
||||
active_name_ = registry_.nameAt(index);
|
||||
active_trigger_ = trigger;
|
||||
|
||||
// Log tại SƯỜN (một dòng cho mỗi lượt khởi động, không nằm trên đường tick). Không có dòng này
|
||||
// thì trên robot/sim không cách nào biết đang chạy behavior nào: các plugin chỉ log khi chúng TỪ
|
||||
@@ -358,7 +430,30 @@ RecoveryTick RecoveryRunner::update()
|
||||
}
|
||||
|
||||
refreshContext();
|
||||
return toTick(active_->update(deps_.clock->now()));
|
||||
const RecoveryTick result = toTick(active_->update(deps_.clock->now()));
|
||||
|
||||
// Log tại SƯỜN KẾT THÚC, một dòng cho mỗi lượt (không nằm trên đường tick: kRunning không log).
|
||||
//
|
||||
// Không có nó thì một behavior CHẠY RỒI HỎNG hoàn toàn im lặng: bên gọi chỉ thấy state machine
|
||||
// ghi `recovery=failed` lẫn giữa dòng chuyển state, còn `message` mà behavior đặt sẵn (vd
|
||||
// "no reachable rejoin point on the plan after 3 attempt(s)") thì không ai in ra. Sim 2026-08-05:
|
||||
// detour hỏng cả 3 attempt -> route cạn -> ABORTED, và trong log không có chữ "fail" nào của
|
||||
// recovery. Nhánh TỪ CHỐI KHỞI ĐỘNG đã có log riêng ở start().
|
||||
if (result.status == RecoveryTick::Status::kFailed)
|
||||
{
|
||||
robot::log_warning("[move_base2] RecoveryRunner: behavior '%s' FAILED (trigger %s): %s",
|
||||
active_name_.c_str(), toString(active_trigger_),
|
||||
result.message.empty() ? "no reason given" : result.message.c_str());
|
||||
}
|
||||
else if (result.status == RecoveryTick::Status::kSucceeded)
|
||||
{
|
||||
robot::log_info("[move_base2] RecoveryRunner: behavior '%s' succeeded (trigger %s)%s: %s",
|
||||
active_name_.c_str(), toString(active_trigger_),
|
||||
result.has_path ? " with a new path" : "",
|
||||
result.message.empty() ? "done" : result.message.c_str());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void RecoveryRunner::cancel()
|
||||
|
||||
@@ -22,6 +22,11 @@ bool StateMachineConfig::validate(std::string& error) const
|
||||
{
|
||||
// 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)
|
||||
{
|
||||
error = "sensor_patience must be >= 0 [s] (0 = disabled)";
|
||||
return false;
|
||||
}
|
||||
if (oscillation_distance < 0.0)
|
||||
{
|
||||
error = "oscillation_distance must be >= 0 [m]";
|
||||
@@ -52,13 +57,15 @@ bool StateMachineConfig::validate(std::string& error) const
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto indices_valid = [this](const std::vector<std::size_t>& route) {
|
||||
return std::all_of(route.begin(), route.end(),
|
||||
[this](std::size_t index) { return index < recovery_behavior_count; });
|
||||
};
|
||||
|
||||
if (!recovery_routes.empty())
|
||||
{
|
||||
const auto valid_route = [this](const std::vector<std::size_t>& route) {
|
||||
return !route.empty() &&
|
||||
std::all_of(route.begin(), route.end(), [this](std::size_t index) {
|
||||
return index < recovery_behavior_count;
|
||||
});
|
||||
const auto valid_route = [&indices_valid](const std::vector<std::size_t>& route) {
|
||||
return !route.empty() && indices_valid(route);
|
||||
};
|
||||
|
||||
if (!valid_route(recovery_routes.planning_failed) ||
|
||||
@@ -69,6 +76,15 @@ bool StateMachineConfig::validate(std::string& error) const
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Hai route giám sát tuyến được phép RỖNG (= tắt cơ chế tương ứng), nhưng index đã khai thì phải
|
||||
// trỏ vào behavior có thật: index giả sẽ thành `start()` vào một behavior không tồn tại lúc chạy.
|
||||
if (!indices_valid(recovery_routes.path_blocked) || !indices_valid(recovery_routes.off_path))
|
||||
{
|
||||
error = "recovery route 'path_blocked'/'off_path' references a behavior that was not loaded";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -80,6 +96,8 @@ std::string StateMachineConfig::describe() const
|
||||
<< (planner_patience > 0.0 ? "" : " (off)") << '\n';
|
||||
out << " controller_patience : " << controller_patience << " s"
|
||||
<< (controller_patience > 0.0 ? "" : " (off)") << '\n';
|
||||
out << " sensor_patience : " << sensor_patience << " s"
|
||||
<< (sensor_patience > 0.0 ? "" : " (off)") << '\n';
|
||||
out << " oscillation_timeout : " << oscillation_timeout << " s"
|
||||
<< (oscillation_timeout > 0.0 ? "" : " (off)") << '\n';
|
||||
out << " action_patience : " << action_patience << " s"
|
||||
@@ -142,9 +160,12 @@ void StateMachine::reset()
|
||||
last_valid_plan_ = robot::Time();
|
||||
last_valid_control_ = robot::Time();
|
||||
last_oscillation_reset_ = robot::Time();
|
||||
sensor_stale_active_ = false;
|
||||
recovery_index_ = 0;
|
||||
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
state_before_recovery_ = NavigationState::kPlanning;
|
||||
recovery_route_cursors_.fill(0);
|
||||
monitor_trigger_suppressed_.fill(false);
|
||||
planning_retries_ = 0;
|
||||
request_has_goal_ = true;
|
||||
action_count_ = 0;
|
||||
@@ -176,32 +197,48 @@ void StateMachine::beginPlanningCycle(const robot::Time& now)
|
||||
planning_retries_ = 0;
|
||||
}
|
||||
|
||||
std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger)
|
||||
namespace
|
||||
{
|
||||
/// @brief Chỉ số cursor của một trigger. `switch` đầy đủ để compiler bắt khi enum thêm giá trị.
|
||||
std::size_t cursorSlot(RecoveryTrigger trigger)
|
||||
{
|
||||
switch (trigger)
|
||||
{
|
||||
case RecoveryTrigger::kPlanningFailed:
|
||||
return recovery_route_cursors_[0];
|
||||
return 0;
|
||||
case RecoveryTrigger::kControllingFailed:
|
||||
return recovery_route_cursors_[1];
|
||||
return 1;
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return recovery_route_cursors_[2];
|
||||
return 2;
|
||||
case RecoveryTrigger::kPathBlocked:
|
||||
return 3;
|
||||
case RecoveryTrigger::kOffPath:
|
||||
return 4;
|
||||
}
|
||||
return recovery_route_cursors_[0];
|
||||
return 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger)
|
||||
{
|
||||
return recovery_route_cursors_[cursorSlot(trigger)];
|
||||
}
|
||||
|
||||
const std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger) const
|
||||
{
|
||||
switch (trigger)
|
||||
{
|
||||
case RecoveryTrigger::kPlanningFailed:
|
||||
return recovery_route_cursors_[0];
|
||||
case RecoveryTrigger::kControllingFailed:
|
||||
return recovery_route_cursors_[1];
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return recovery_route_cursors_[2];
|
||||
}
|
||||
return recovery_route_cursors_[0];
|
||||
return recovery_route_cursors_[cursorSlot(trigger)];
|
||||
}
|
||||
|
||||
bool StateMachine::isMonitorTrigger(RecoveryTrigger trigger)
|
||||
{
|
||||
return trigger == RecoveryTrigger::kPathBlocked || trigger == RecoveryTrigger::kOffPath;
|
||||
}
|
||||
|
||||
void StateMachine::suppressMonitorTrigger(RecoveryTrigger trigger, StateMachineOutput& out)
|
||||
{
|
||||
monitor_trigger_suppressed_[cursorSlot(trigger)] = true;
|
||||
out.recovery_trigger = trigger;
|
||||
out.monitor_trigger_suppressed = true;
|
||||
}
|
||||
|
||||
void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time& now,
|
||||
@@ -210,18 +247,41 @@ void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time
|
||||
const std::vector<std::size_t>& route = config_.recovery_routes.forTrigger(trigger);
|
||||
const std::size_t cursor = recoveryRouteCursor(trigger);
|
||||
|
||||
out.recovery_trigger = trigger;
|
||||
out.recovery_route_cursor = cursor;
|
||||
out.recovery_route_size = route.size();
|
||||
|
||||
if (!config_.recovery_enabled || cursor >= route.size())
|
||||
{
|
||||
// Trigger giám sát tuyến là DỰ BÁO, không phải báo hỏng (contract 2026-08-05e): plan vẫn hợp
|
||||
// lệ, controller vẫn ra lệnh được. Hết đường vòng thì bám tiếp plan cũ, KHÔNG kết thúc chặng —
|
||||
// sim 2026-08-05 ABORT đúng lúc `controller=command_valid, costmap_current=yes`, tức vứt một
|
||||
// chặng mà robot hoàn toàn khoẻ. Lưới an toàn thật vẫn nguyên: local planner + costmap không
|
||||
// cho đâm, rồi controller_patience đưa vào controlling_failed với ngân sách riêng của nó — và
|
||||
// ĐÓ mới là đường ABORT hợp lệ.
|
||||
//
|
||||
// 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))
|
||||
{
|
||||
suppressMonitorTrigger(trigger, out);
|
||||
return;
|
||||
}
|
||||
|
||||
finish(NavigationState::kAborted, NavigationOutcome::kFailed, now,
|
||||
"no recovery behavior left", out);
|
||||
return;
|
||||
}
|
||||
|
||||
active_recovery_trigger_ = trigger;
|
||||
|
||||
// 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.
|
||||
state_before_recovery_ = state_;
|
||||
|
||||
recovery_index_ = route[cursor];
|
||||
out.start_recovery = true;
|
||||
out.recovery_index = recovery_index_;
|
||||
out.recovery_trigger = trigger;
|
||||
enter(NavigationState::kRecovering, now, reason, out);
|
||||
}
|
||||
|
||||
@@ -241,6 +301,7 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
|
||||
out.accept_request = true;
|
||||
recovery_index_ = 0;
|
||||
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
state_before_recovery_ = NavigationState::kPlanning;
|
||||
recovery_route_cursors_.fill(0);
|
||||
request_has_goal_ = in.pending_request_has_goal;
|
||||
action_count_ = in.pending_request_action_count;
|
||||
@@ -268,6 +329,8 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
|
||||
beginPlanningCycle(in.now);
|
||||
last_valid_control_ = in.now;
|
||||
last_oscillation_reset_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
monitor_trigger_suppressed_.fill(false);
|
||||
out.reset_oscillation_origin = true;
|
||||
enter(NavigationState::kPlanning, in.now, "new request accepted", out);
|
||||
}
|
||||
@@ -392,6 +455,21 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
if (retries_exhausted || patience_exhausted)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
|
||||
if (!in.pose_available)
|
||||
{
|
||||
// Hết kiên nhẫn mà nguyên nhân là KHÔNG CÓ POSE: planner còn chưa được khởi động (control
|
||||
// loop chặn startPlan khi mất pose), nên đây là sự cố DỮ LIỆU chứ không phải "không tìm
|
||||
// được đường". Leo thang bằng ngân sách controlling_failed — cùng ngân sách với mất
|
||||
// pose lúc đang bám plan. Hệ quả với route `controlling_failed: [wait]`: mất pose →
|
||||
// wait một lượt → quay lại đây kiểm tra; pose vẫn chưa về thì cursor đã cạn → ABORTED
|
||||
// và robot dừng hẳn; pose về thì lập plan chạy tiếp. Route planning_failed nhờ vậy giữ
|
||||
// đúng nghĩa "planner có dữ liệu nhưng không tìm được đường".
|
||||
escalateToRecovery(RecoveryTrigger::kControllingFailed, in.now,
|
||||
"pose unavailable, cannot plan", out);
|
||||
break;
|
||||
}
|
||||
|
||||
escalateToRecovery(RecoveryTrigger::kPlanningFailed, in.now,
|
||||
retries_exhausted ? "planning retries exhausted" : "planning timed "
|
||||
"out", out);
|
||||
@@ -430,6 +508,9 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
out.apply_plan = true;
|
||||
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);
|
||||
}
|
||||
|
||||
// Đ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.
|
||||
@@ -438,6 +519,17 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
last_oscillation_reset_ = in.now;
|
||||
out.reset_oscillation_origin = true;
|
||||
|
||||
// Tiến độ thật thì ngân sách recovery đầy lại (2026-08-04). Không reset thì một chặng dài
|
||||
// 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);
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
if (controller == ControllerFeedback::kGoalReached)
|
||||
@@ -459,6 +551,36 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
break;
|
||||
}
|
||||
|
||||
// Giám sát tuyến (contract 2026-08-04d). Đặt SAU nhánh goal_reached — đã tới đích thì không
|
||||
// vòng đi đâu nữa — và TRƯỚC nhánh sinh lệnh: đã biết tuyến tắc thì không chạy thêm một cycle
|
||||
// nào về phía vật cản.
|
||||
//
|
||||
// `path_blocked` thắng `off_path` khi cả hai cùng đúng: tuyến bị chắn là NGUYÊN NHÂN, còn
|
||||
// lệch tuyến thường là HỆ QUẢ của việc local planner tự né chính vật cản đó.
|
||||
//
|
||||
// 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ó.
|
||||
if ((in.path_blocked && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kPathBlocked)]) ||
|
||||
(in.off_path && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kOffPath)]))
|
||||
{
|
||||
const bool use_blocked =
|
||||
in.path_blocked && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kPathBlocked)];
|
||||
const RecoveryTrigger trigger =
|
||||
use_blocked ? RecoveryTrigger::kPathBlocked : RecoveryTrigger::kOffPath;
|
||||
out.stop_planner = true;
|
||||
escalateToRecovery(trigger, in.now,
|
||||
use_blocked ? "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)
|
||||
{
|
||||
break;
|
||||
}
|
||||
out.stop_planner = false;
|
||||
}
|
||||
|
||||
if (controller == ControllerFeedback::kCommandValid)
|
||||
{
|
||||
last_valid_control_ = in.now;
|
||||
@@ -476,7 +598,41 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
break;
|
||||
}
|
||||
|
||||
// Còn lại: kIdle (cycle đầu sau khi vào state) hoặc kNoValidCommand.
|
||||
// Còn lại: kIdle (cycle đầu sau khi vào state) hoặc kNoValidCommand — gồm cả mất pose.
|
||||
//
|
||||
// KHÔNG nhảy sang kPlanning ở đây (contract 2026-08-04, tách replan khỏi recovery): controller
|
||||
// không ra lệnh thì robot DỪNG TẠI CHỖ và vẫn ở kControlling — candidate rỗng nên arbiter tự
|
||||
// đưa lệnh về 0. Lập plan lại là việc của replan nền theo `planner_frequency`, không phải phản
|
||||
// xạ của một cycle hỏng; nhờ vậy controller_patience đo đúng "mất lệnh liên tục bao lâu" thay
|
||||
// vì bị vòng CONTROLLING→PLANNING→CONTROLLING chen vào trước khi đồng hồ kịp chạy. Hết kiên
|
||||
// nhẫn thì vào recovery với đúng lý do controlling_failed.
|
||||
|
||||
// Costmap stale = DATA OUTAGE (2026-08-05): controller bị control loop SKIP chứ không phải
|
||||
// bất lực, nên controller_patience bị ĐÓNG BĂNG (33 ms patience đo outage là đo sai thứ —
|
||||
// sim: detour xong -> stale do chính SBPL giữ mutex -> controlling_failed sau MỘT cycle ->
|
||||
// detour rác trên map cũ -> ABORT, trong khi costmap chỉ cần ~0.5 s để hồi). Chuỗi stale
|
||||
// liên tục có trần riêng `sensor_patience`; quá trần mới là "mất dữ liệu" thật.
|
||||
if (!in.costmap_current && config_.sensor_patience > 0.0)
|
||||
{
|
||||
if (!sensor_stale_active_)
|
||||
{
|
||||
sensor_stale_active_ = true;
|
||||
sensor_stale_since_ = in.now;
|
||||
}
|
||||
last_valid_control_ = in.now; // đóng băng controller_patience trong lúc outage
|
||||
|
||||
if ((in.now - sensor_stale_since_).toSec() > config_.sensor_patience)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
escalateToRecovery(RecoveryTrigger::kControllingFailed, in.now,
|
||||
"sensor data stayed stale for too long", out);
|
||||
break;
|
||||
}
|
||||
out.run_controller = true; // control loop tự skip khi stale; giữ nguyên hợp đồng output
|
||||
break;
|
||||
}
|
||||
sensor_stale_active_ = false;
|
||||
|
||||
if (config_.controller_patience > 0.0 &&
|
||||
(in.now - last_valid_control_).toSec() > config_.controller_patience)
|
||||
{
|
||||
@@ -486,21 +642,6 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
break;
|
||||
}
|
||||
|
||||
if (controller == ControllerFeedback::kNoValidCommand && in.pose_available)
|
||||
{
|
||||
// Chưa hết kiên nhẫn: quay lại lập plan. Cố ý KHÔNG reset last_valid_control_ ở đây, nếu
|
||||
// không thì vòng lặp lập-plan-rồi-lại-hỏng sẽ không bao giờ chạm controller_patience.
|
||||
out.start_planner = true;
|
||||
beginPlanningCycle(in.now);
|
||||
enter(NavigationState::kPlanning, in.now, "controller produced no command, replanning",
|
||||
out);
|
||||
break;
|
||||
}
|
||||
|
||||
// Mất pose thì ở nguyên kControlling (vận tốc đã bị ép về 0 ở phần chốt bất biến) cho tới khi
|
||||
// controller_patience hết hạn. Lập lại plan không giúp được gì khi vấn đề là định vị, và
|
||||
// nhảy sang kPlanning chỉ làm lý do vào recovery bị ghi nhận sai thành "lập plan hỏng".
|
||||
|
||||
out.run_controller = true;
|
||||
break;
|
||||
}
|
||||
@@ -533,16 +674,75 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
|
||||
if (in.recovery == RecoveryFeedback::kSucceeded || in.recovery == RecoveryFeedback::kFailed)
|
||||
{
|
||||
// Behavior chạy xong (thành công hay không) thì thử lập plan lại. Lỗi kế tiếp sẽ dùng
|
||||
// behavior kế tiếp; hết behavior thì ABORTED.
|
||||
// Behavior chạy xong. Lỗi kế tiếp sẽ dùng behavior kế tiếp trong route; hết behavior thì
|
||||
// ABORTED.
|
||||
//
|
||||
// NGOẠI LỆ (2026-08-05): behavior THÀNH CÔNG và NỘP PATH MỚI (detour) thì cursor của
|
||||
// trigger đó reset NGAY — sự cố này đã được giải quyết bằng một đường đi mới, lần chắn
|
||||
// kế tiếp là sự cố MỚI với ngân sách đầy. Không chờ mốc oscillation_distance: sim đo
|
||||
// robot bám detour 1.1 s (~0.45 m) rồi gặp vật cản thứ hai và ABORT vì thiếu 5 cm.
|
||||
// Chỉ reset cho ca "thành công + path mới": `wait` thành công trivially sau N giây, reset
|
||||
// theo nó là route không bao giờ cạn — robot đứng chờ vô hạn thay vì ABORT báo fail.
|
||||
const bool recovered_with_new_path = in.recovery == RecoveryFeedback::kSucceeded &&
|
||||
in.planner == PlannerFeedback::kPlanReady;
|
||||
std::size_t& cursor = recoveryRouteCursor(active_recovery_trigger_);
|
||||
++cursor;
|
||||
if (recovered_with_new_path)
|
||||
{
|
||||
cursor = 0;
|
||||
}
|
||||
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):
|
||||
//
|
||||
// 1. Behavior họ detour vừa nộp một PATH MỚI (control loop đã cất vào latest_plan_ và báo
|
||||
// kPlanReady): áp path đó và bám tiếp. Đây là đường thay plan DUY NHẤT mà recovery được
|
||||
// phép thực hiện.
|
||||
// 2. Trigger planning_failed — vào recovery vì KHÔNG lập được plan: không có plan nào để
|
||||
// bám nên phải quay về kPlanning thử lập lại.
|
||||
// 3. Trigger controlling/oscillation leo thang từ kControlling: global path cũ vẫn là
|
||||
// đường hợp lệ — quay lại bám tiếp nó, KHÔNG lập plan lại. Thay plan trong lúc chạy là
|
||||
// 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 old_plan_valid =
|
||||
active_recovery_trigger_ != RecoveryTrigger::kPlanningFailed &&
|
||||
state_before_recovery_ == NavigationState::kControlling;
|
||||
|
||||
if (has_detour_path || old_plan_valid)
|
||||
{
|
||||
if (has_detour_path)
|
||||
{
|
||||
out.apply_plan = true;
|
||||
beginPlanningCycle(in.now);
|
||||
}
|
||||
|
||||
// Controller được trọn một cửa controller_patience để thử lại trên plan (cũ hoặc detour);
|
||||
// vẫn bế tắc thì lượt leo thang kế tiếp dùng behavior tiếp theo của route. Đồng hồ stale
|
||||
// cũng đo lại từ đầu — recovery (nhất là SBPL giữ mutex) có thể chính là thủ phạm làm
|
||||
// costmap trễ, cho nó trọn một cửa sensor_patience để hồi.
|
||||
last_valid_control_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
last_oscillation_reset_ = in.now;
|
||||
out.reset_oscillation_origin = true;
|
||||
out.run_controller = true;
|
||||
enter(NavigationState::kControlling, in.now,
|
||||
has_detour_path ? "recovery produced a detour path"
|
||||
: "recovery finished, resuming the current plan",
|
||||
out);
|
||||
break;
|
||||
}
|
||||
|
||||
out.start_planner = true;
|
||||
beginPlanningCycle(in.now);
|
||||
last_valid_control_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
enter(NavigationState::kPlanning, in.now,
|
||||
in.recovery == RecoveryFeedback::kSucceeded ? "recovery finished, replanning"
|
||||
: "recovery failed, replanning",
|
||||
@@ -644,6 +844,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
beginPlanningCycle(in.now);
|
||||
last_valid_control_ = in.now;
|
||||
last_oscillation_reset_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
out.reset_oscillation_origin = true;
|
||||
|
||||
if (state_before_pause_ == NavigationState::kControlling)
|
||||
@@ -672,8 +873,9 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// --------------------------------------------------------------------------------------
|
||||
case NavigationState::kCancelling:
|
||||
{
|
||||
// Nguồn vận tốc đã là kNone nên bộ trọng tài đang giảm tốc về 0 theo trần gia tốc; trạng thái
|
||||
// này vì vậy luôn kết thúc sau hữu hạn cycle, không cần thêm timeout.
|
||||
// Nguồn vận tốc đã là kNone nên bộ trọng tài phát lệnh 0 NGAY (arbiter cố ý không ramp khi
|
||||
// nguồn là kNone — xem VelocityArbiter::arbitrate); trạng thái này vì vậy kết thúc ngay cycle
|
||||
// robot_stopped bật, không cần thêm timeout.
|
||||
if (in.robot_stopped)
|
||||
{
|
||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||
|
||||
@@ -117,6 +117,9 @@ recovery:
|
||||
planning_failed: [wait_short]
|
||||
controlling_failed: [wait_long, wait_short]
|
||||
oscillation: [wait_long]
|
||||
# Lặp behavior trong một route là HỢP LỆ (2026-08-05): mỗi lần xuất hiện là một lượt thử —
|
||||
# ngân sách cho vòng "thử — chờ — nhích lại gần — thử lại" của giám sát tuyến.
|
||||
path_blocked: [wait_short, wait_long, wait_short]
|
||||
|
||||
wait_short:
|
||||
wait_duration: 1.0 # [s]
|
||||
|
||||
@@ -96,6 +96,7 @@ public:
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
std::string error;
|
||||
runner_.disableCostmapLockForTesting(); // costmap placeholder
|
||||
ok_ = runner_.configure(nh, nullptr, dummyCostmap(), &fixedPose(), name, error);
|
||||
error_ = error;
|
||||
}
|
||||
@@ -127,6 +128,7 @@ TEST(ControllerRunner, RefusesNullCostmap)
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
ControllerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
|
||||
EXPECT_FALSE(runner.configure(nh, nullptr, nullptr, &fixedPose(), "TestControllerOk", error));
|
||||
@@ -140,6 +142,7 @@ TEST(ControllerRunner, RefusesNullPosePort)
|
||||
// thì không gọi được hàm nào trong hai hàm đó.
|
||||
robot::NodeHandle nh;
|
||||
ControllerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
|
||||
EXPECT_FALSE(runner.configure(nh, nullptr, dummyCostmap(), nullptr, "TestControllerOk", error));
|
||||
@@ -150,6 +153,7 @@ TEST(ControllerRunner, ConfigureFailsWhenTheInitialControllerCannotBeLoaded)
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
ControllerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
|
||||
EXPECT_FALSE(runner.configure(nh, nullptr, dummyCostmap(), &fixedPose(), "TestControllerMissing", error));
|
||||
@@ -194,6 +198,7 @@ TEST(ControllerRunner, FailedSwapKeepsThePreviousControllerActive)
|
||||
TEST(ControllerRunner, SwapBeforeConfigureIsRefused)
|
||||
{
|
||||
ControllerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
EXPECT_FALSE(runner.swapPlanner("TestControllerOk"));
|
||||
}
|
||||
|
||||
@@ -238,6 +243,7 @@ TEST(ControllerRunner, LimitSetBeforeAControllerExistsIsAppliedOnceItIsLoaded)
|
||||
// Thứ tự khởi tạo không do move_base2 quyết: host có thể đặt trần trước khi controller được nạp.
|
||||
robot::NodeHandle nh;
|
||||
ControllerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
ASSERT_TRUE(runner.configure(nh, nullptr, dummyCostmap(), &fixedPose(), "", error)) << error;
|
||||
|
||||
@@ -360,6 +366,7 @@ TEST(ControllerRunner, SetPlanWithoutAControllerFails)
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
ControllerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
ASSERT_TRUE(runner.configure(nh, nullptr, dummyCostmap(), &fixedPose(), "", error)) << error;
|
||||
|
||||
@@ -370,6 +377,7 @@ TEST(ControllerRunner, ComputeWithoutAControllerYieldsNoCommand)
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
ControllerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
ASSERT_TRUE(runner.configure(nh, nullptr, dummyCostmap(), &fixedPose(), "", error)) << error;
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
#include <move_base2/ports/controller_port.h>
|
||||
#include <move_base2/ports/costmap_status_port.h>
|
||||
#include <move_base2/ports/mission_port.h>
|
||||
#include <move_base2/ports/path_check_port.h>
|
||||
#include <move_base2/ports/planner_port.h>
|
||||
#include <move_base2/ports/pose_port.h>
|
||||
#include <move_base2/ports/recovery_port.h>
|
||||
@@ -854,6 +855,59 @@ private:
|
||||
mutable std::size_t query_count_ = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class FakePathCheckPort
|
||||
* @brief Cổng kiểm tuyến giả: kịch bản quyết định tuyến sạch hay bẩn, không cần costmap thật.
|
||||
*
|
||||
* `available_ = false` mô phỏng "không kết luận được" (thiếu TF/costmap) — bên gọi phải coi đó là
|
||||
* không biết, KHÔNG được suy thành sạch hay bẩn.
|
||||
*/
|
||||
class FakePathCheckPort final : public PathCheckPort
|
||||
{
|
||||
public:
|
||||
bool checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index, double horizon, PlanBlockResult& out) const override
|
||||
{
|
||||
(void)from_index;
|
||||
(void)horizon;
|
||||
++query_count_;
|
||||
|
||||
if (!available_)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
out = PlanBlockResult();
|
||||
out.blocked = blocked_;
|
||||
out.distance = distance_;
|
||||
out.scanned = plan.size();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @param distance [m] khoảng cách tới vật cản — bên gọi so với `min_detour_distance`.
|
||||
void setBlocked(bool blocked, double distance = 1.5)
|
||||
{
|
||||
blocked_ = blocked;
|
||||
distance_ = distance;
|
||||
}
|
||||
|
||||
void setAvailable(bool available)
|
||||
{
|
||||
available_ = available;
|
||||
}
|
||||
|
||||
std::size_t queryCount() const
|
||||
{
|
||||
return query_count_;
|
||||
}
|
||||
|
||||
private:
|
||||
bool blocked_ = false;
|
||||
bool available_ = true;
|
||||
double distance_ = 1.5; // [m]
|
||||
mutable std::size_t query_count_ = 0;
|
||||
};
|
||||
|
||||
class FakeMissionPort final : public MissionPort
|
||||
{
|
||||
public:
|
||||
|
||||
282
test/plan_inspector_test.cpp
Normal file
282
test/plan_inspector_test.cpp
Normal file
@@ -0,0 +1,282 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Kiểm plan_inspector: quét tuyến phía trước, chiếu pose lên plan, đo lệch tuyến, quy đổi frame.
|
||||
*
|
||||
* Dùng `nav_test_harness::FakeCostmap` (sở hữu một `Costmap2D` thật) nên ngữ nghĩa cost là ngữ
|
||||
* nghĩa thật của workspace — kể cả `FREE_SPACE = 60` của fork này.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <nav_test_harness/fake_costmap.h>
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
#include <move_base2/core/plan_inspector.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using move_base2::checkPlan;
|
||||
using move_base2::crossTrackError;
|
||||
using move_base2::nearestIndex;
|
||||
using move_base2::PlanarTransform;
|
||||
using move_base2::PlanBlockResult;
|
||||
using move_base2::planarTransform;
|
||||
|
||||
robot_geometry_msgs::PoseStamped makePose(double x, double y, const std::string& frame = "map")
|
||||
{
|
||||
robot_geometry_msgs::PoseStamped pose;
|
||||
pose.header.frame_id = frame;
|
||||
pose.pose.position.x = x;
|
||||
pose.pose.position.y = y;
|
||||
pose.pose.orientation.w = 1.0;
|
||||
return pose;
|
||||
}
|
||||
|
||||
/// Plan thẳng dọc trục x, bước @p step, y cố định.
|
||||
std::vector<robot_geometry_msgs::PoseStamped> linePlan(double from_x, double to_x, double step,
|
||||
double y = 0.0)
|
||||
{
|
||||
std::vector<robot_geometry_msgs::PoseStamped> plan;
|
||||
for (double x = from_x; x <= to_x + 1e-9; x += step)
|
||||
{
|
||||
plan.push_back(makePose(x, y));
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
/// Lưới 10 x 10 m, gốc tại (-5, -5), ô 0.05 m — cùng resolution với local costmap runtime.
|
||||
nav_test_harness::FakeCostmap makeGrid()
|
||||
{
|
||||
return nav_test_harness::FakeCostmap::centered(10.0, 0.05);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, CleanPlanIsNotBlocked)
|
||||
{
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
|
||||
const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform());
|
||||
|
||||
EXPECT_FALSE(result.blocked);
|
||||
EXPECT_GT(result.scanned, 0u);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, FreeSpaceValueIsNotBlocked)
|
||||
{
|
||||
// Bẫy của fork này: FREE_SPACE = 60, không phải 0. Đặt tường minh giá trị đó lên tuyến để khoá
|
||||
// lại bất biến "so sánh phải dùng hằng số có tên".
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
ASSERT_TRUE(grid.setCostAt(1.0, 0.0, robot_costmap_2d::FREE_SPACE));
|
||||
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform());
|
||||
|
||||
EXPECT_FALSE(result.blocked);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, LethalCellOnThePlanBlocks)
|
||||
{
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
ASSERT_TRUE(grid.setLethalAt(1.5, 0.0));
|
||||
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform());
|
||||
|
||||
ASSERT_TRUE(result.blocked);
|
||||
EXPECT_NEAR(plan[result.index].pose.position.x, 1.5, 0.06);
|
||||
EXPECT_NEAR(result.distance, 1.5, 0.06);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, InscribedInflatedCountsAsBlocked)
|
||||
{
|
||||
// Ngưỡng là INSCRIBED_INFLATED_OBSTACLE chứ không phải LETHAL: ở đó tâm robot đặt vào là footprint
|
||||
// đã đệm chạm vật cản.
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
ASSERT_TRUE(grid.setCostAt(1.0, 0.0, robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE));
|
||||
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform());
|
||||
|
||||
EXPECT_TRUE(result.blocked);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, UnknownCellIsNotBlocked)
|
||||
{
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
ASSERT_TRUE(grid.setCostAt(1.0, 0.0, robot_costmap_2d::NO_INFORMATION));
|
||||
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform());
|
||||
|
||||
// Vùng chưa quét mà tính là chắn thì robot dừng ở mọi tuyến đi vào chỗ chưa thấy.
|
||||
EXPECT_FALSE(result.blocked);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, HorizonCutsTheScanShort)
|
||||
{
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
ASSERT_TRUE(grid.setLethalAt(2.5, 0.0));
|
||||
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
|
||||
EXPECT_FALSE(checkPlan(plan, 0, 1.0, *grid.costmap(), PlanarTransform()).blocked);
|
||||
EXPECT_TRUE(checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()).blocked);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, ScanStartsAtFromIndex)
|
||||
{
|
||||
// Vật cản NẰM SAU lưng (phần plan đã đi qua) không được tính.
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
ASSERT_TRUE(grid.setLethalAt(0.5, 0.0));
|
||||
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
|
||||
EXPECT_TRUE(checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()).blocked);
|
||||
EXPECT_FALSE(checkPlan(plan, 15, 3.0, *grid.costmap(), PlanarTransform()).blocked);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, OutOfGridStopsTheScanInsteadOfBlocking)
|
||||
{
|
||||
nav_test_harness::FakeCostmap grid = makeGrid(); // ±5 m
|
||||
const auto plan = linePlan(0.0, 20.0, 0.5);
|
||||
|
||||
const PlanBlockResult result = checkPlan(plan, 0, 20.0, *grid.costmap(), PlanarTransform());
|
||||
|
||||
EXPECT_FALSE(result.blocked);
|
||||
EXPECT_LT(result.scanned, plan.size()); // dừng ở rìa lưới, không quét hết
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, EmptyPlanAndBadArgumentsAreSafe)
|
||||
{
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
|
||||
EXPECT_FALSE(checkPlan({}, 0, 3.0, *grid.costmap(), PlanarTransform()).blocked);
|
||||
EXPECT_FALSE(checkPlan(plan, 999, 3.0, *grid.costmap(), PlanarTransform()).blocked);
|
||||
EXPECT_FALSE(checkPlan(plan, 0, 0.0, *grid.costmap(), PlanarTransform()).blocked);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCheck, TransformIsAppliedToEveryPose)
|
||||
{
|
||||
// Plan ở "map", lưới ở "odom" lệch (2, 1): vật cản đặt theo toạ độ LƯỚI.
|
||||
nav_test_harness::FakeCostmap grid = makeGrid();
|
||||
ASSERT_TRUE(grid.setLethalAt(-0.5, -1.0)); // = map (1.5, 0.0) sau khi trừ offset
|
||||
|
||||
PlanarTransform to_grid;
|
||||
to_grid.x = -2.0;
|
||||
to_grid.y = -1.0;
|
||||
|
||||
const auto plan = linePlan(0.0, 3.0, 0.1);
|
||||
|
||||
EXPECT_TRUE(checkPlan(plan, 0, 3.0, *grid.costmap(), to_grid).blocked);
|
||||
EXPECT_FALSE(checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()).blocked);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorNearest, ProjectsOntoSegmentsNotVertices)
|
||||
{
|
||||
const auto plan = linePlan(0.0, 3.0, 1.0); // pose tại x = 0,1,2,3
|
||||
|
||||
EXPECT_EQ(nearestIndex(plan, makePose(0.1, 0.0)), 0u);
|
||||
EXPECT_EQ(nearestIndex(plan, makePose(1.5, 0.4)), 1u);
|
||||
EXPECT_EQ(nearestIndex(plan, makePose(2.9, 0.0)), 2u);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorNearest, PlanFoldingBackOnItselfPicksTheNearerLeg)
|
||||
{
|
||||
// Plan đi ra rồi vòng lại: đo tới đỉnh sẽ cho index sai, chiếu lên đoạn thì không.
|
||||
std::vector<robot_geometry_msgs::PoseStamped> plan{
|
||||
makePose(0.0, 0.0), makePose(2.0, 0.0), makePose(2.0, 1.0), makePose(0.0, 1.0)
|
||||
};
|
||||
|
||||
EXPECT_EQ(nearestIndex(plan, makePose(1.0, 0.05)), 0u);
|
||||
EXPECT_EQ(nearestIndex(plan, makePose(1.0, 0.95)), 2u);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorNearest, ShortPlansAreSafe)
|
||||
{
|
||||
EXPECT_EQ(nearestIndex({}, makePose(0.0, 0.0)), 0u);
|
||||
EXPECT_EQ(nearestIndex({ makePose(5.0, 5.0) }, makePose(0.0, 0.0)), 0u);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCrossTrack, MeasuresPerpendicularDistance)
|
||||
{
|
||||
const auto plan = linePlan(0.0, 3.0, 0.5);
|
||||
|
||||
EXPECT_NEAR(crossTrackError(plan, makePose(1.0, 0.0)), 0.0, 1e-9);
|
||||
EXPECT_NEAR(crossTrackError(plan, makePose(1.0, 0.6)), 0.6, 1e-9);
|
||||
EXPECT_NEAR(crossTrackError(plan, makePose(1.0, -0.6)), 0.6, 1e-9);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCrossTrack, DiagonalSegmentUsesTruePerpendicular)
|
||||
{
|
||||
// Đoạn 45°: điểm (1,0) cách đoạn sqrt(2)/2, KHÔNG phải 1.0 (khoảng cách tới đỉnh gần nhất).
|
||||
std::vector<robot_geometry_msgs::PoseStamped> plan{ makePose(0.0, 0.0), makePose(2.0, 2.0) };
|
||||
|
||||
EXPECT_NEAR(crossTrackError(plan, makePose(1.0, 0.0)), std::sqrt(2.0) / 2.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCrossTrack, BeyondTheEndClampsToTheEndpoint)
|
||||
{
|
||||
const auto plan = linePlan(0.0, 2.0, 1.0);
|
||||
|
||||
EXPECT_NEAR(crossTrackError(plan, makePose(3.0, 0.0)), 1.0, 1e-9);
|
||||
EXPECT_NEAR(crossTrackError(plan, makePose(-1.0, 0.0)), 1.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorCrossTrack, EmptyPlanIsZero)
|
||||
{
|
||||
EXPECT_NEAR(crossTrackError({}, makePose(1.0, 1.0)), 0.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorTransform, LooksUpTfOnceAndConvertsBothWays)
|
||||
{
|
||||
tf3::BufferCore tf;
|
||||
tf3::TransformStampedMsg map_to_odom;
|
||||
map_to_odom.header.frame_id = "map";
|
||||
map_to_odom.child_frame_id = "odom";
|
||||
map_to_odom.transform.translation.x = 2.0; // odom gốc tại map (2, 1)
|
||||
map_to_odom.transform.translation.y = 1.0;
|
||||
map_to_odom.transform.rotation.w = 1.0;
|
||||
ASSERT_TRUE(tf.setTransform(map_to_odom, "test", /*is_static=*/true));
|
||||
|
||||
PlanarTransform map_to_grid;
|
||||
ASSERT_TRUE(planarTransform(tf, "map", "odom", map_to_grid));
|
||||
|
||||
double x = 0.0;
|
||||
double y = 0.0;
|
||||
map_to_grid.apply(3.0, 2.0, x, y); // map (3,2) -> odom (1,1)
|
||||
EXPECT_NEAR(x, 1.0, 1e-9);
|
||||
EXPECT_NEAR(y, 1.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(PlanInspectorTransform, SameFrameIsIdentityAndUnknownFrameFails)
|
||||
{
|
||||
tf3::BufferCore tf;
|
||||
|
||||
PlanarTransform same;
|
||||
EXPECT_TRUE(planarTransform(tf, "map", "map", same));
|
||||
EXPECT_NEAR(same.x, 0.0, 1e-9);
|
||||
EXPECT_NEAR(same.cos_yaw, 1.0, 1e-9);
|
||||
|
||||
PlanarTransform missing;
|
||||
EXPECT_FALSE(planarTransform(tf, "map", "odom", missing));
|
||||
EXPECT_FALSE(planarTransform(tf, "", "odom", missing));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -77,6 +77,7 @@ public:
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
std::string error;
|
||||
runner_.disableCostmapLockForTesting(); // costmap placeholder
|
||||
ok_ = runner_.configure(nh, dummyCostmap(), name, error);
|
||||
error_ = error;
|
||||
}
|
||||
@@ -110,6 +111,7 @@ TEST(PlannerRunner, RefusesNullCostmap)
|
||||
// định "sập hay không" cho từng plugin tự lo.
|
||||
robot::NodeHandle nh;
|
||||
PlannerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
|
||||
EXPECT_FALSE(runner.configure(nh, nullptr, "TestPlannerOk", error));
|
||||
@@ -121,6 +123,7 @@ TEST(PlannerRunner, ConfiguresWithoutAnInitialPlanner)
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
PlannerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
|
||||
ASSERT_TRUE(runner.configure(nh, dummyCostmap(), "", error)) << error;
|
||||
@@ -143,6 +146,7 @@ TEST(PlannerRunner, ConfigureFailsWhenTheInitialPlannerCannotBeLoaded)
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
PlannerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
|
||||
EXPECT_FALSE(runner.configure(nh, dummyCostmap(), "TestPlannerMissingLibrary", error));
|
||||
@@ -200,6 +204,7 @@ TEST(PlannerRunner, PlannerReportingInitializeFailureIsRejected)
|
||||
// Bản cũ chỉ log rồi đi tiếp với planner chưa khởi tạo xong.
|
||||
robot::NodeHandle nh;
|
||||
PlannerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
|
||||
EXPECT_FALSE(runner.configure(nh, dummyCostmap(), "TestPlannerInitFails", error));
|
||||
@@ -227,6 +232,7 @@ TEST(PlannerRunner, RefusesEmptyPlannerName)
|
||||
TEST(PlannerRunner, SwapBeforeConfigureIsRefused)
|
||||
{
|
||||
PlannerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
EXPECT_FALSE(runner.swapPlanner("TestPlannerOk"));
|
||||
}
|
||||
|
||||
@@ -326,6 +332,7 @@ TEST(PlannerRunner, StartPlanWithoutAnActivePlannerFails)
|
||||
{
|
||||
robot::NodeHandle nh;
|
||||
PlannerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
std::string error;
|
||||
ASSERT_TRUE(runner.configure(nh, dummyCostmap(), "", error)) << error;
|
||||
|
||||
@@ -408,6 +415,7 @@ TEST(PlannerRunner, DestructorJoinsWhileAPlanIsInFlight)
|
||||
std::string error;
|
||||
{
|
||||
PlannerRunner runner;
|
||||
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
|
||||
ASSERT_TRUE(runner.configure(nh, dummyCostmap(), "TestPlannerOk", error)) << error;
|
||||
EXPECT_TRUE(runner.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
}
|
||||
|
||||
@@ -82,6 +82,21 @@ TEST(RecoveryRunner, ResolvesPerTriggerRoutesByBehaviorName)
|
||||
EXPECT_EQ(routes.oscillation[0], 1u); // wait_long
|
||||
}
|
||||
|
||||
TEST(RecoveryRunner, RouteMayRepeatABehavior)
|
||||
{
|
||||
// Lặp behavior = cấp thêm lượt thử cho vòng "thử — chờ — nhích lại gần — thử lại" (2026-08-05):
|
||||
// cursor chỉ reset khi robot đi đủ oscillation_distance, nên route không lặp thì cạn ngay sau
|
||||
// một cặp [detour, wait] dù chỗ nối sắp vào tầm.
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.load("recovery"));
|
||||
|
||||
const move_base2::RecoveryRoutes& routes = rig.runner.routes();
|
||||
ASSERT_EQ(routes.path_blocked.size(), 3u);
|
||||
EXPECT_EQ(routes.path_blocked[0], 0u); // wait_short
|
||||
EXPECT_EQ(routes.path_blocked[1], 1u); // wait_long
|
||||
EXPECT_EQ(routes.path_blocked[2], 0u); // wait_short lần hai — cùng behavior, lượt thử mới
|
||||
}
|
||||
|
||||
TEST(RecoveryRunner, SkipsFuturePluginFromRoutesWithoutCreatingInvalidIndexes)
|
||||
{
|
||||
Rig rig;
|
||||
|
||||
@@ -151,6 +151,12 @@ public:
|
||||
case RecoveryTrigger::kOscillation:
|
||||
goal.trigger = recovery_core::RecoveryTrigger::kOscillation;
|
||||
break;
|
||||
case RecoveryTrigger::kPathBlocked:
|
||||
goal.trigger = recovery_core::RecoveryTrigger::kPathBlocked;
|
||||
break;
|
||||
case RecoveryTrigger::kOffPath:
|
||||
goal.trigger = recovery_core::RecoveryTrigger::kOffPath;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!active_->start(goal, clock_->now()))
|
||||
|
||||
@@ -480,42 +480,297 @@ TEST(StateMachineControlling, ValidCommandKeepsControlling)
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kController);
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, NoValidCommandGoesBackToPlanning)
|
||||
TEST(StateMachineControlling, NoValidCommandStopsInPlaceAndStaysControlling)
|
||||
{
|
||||
// Contract 2026-08-04: controller không ra lệnh thì robot DỪNG TẠI CHỖ và ở nguyên kControlling —
|
||||
// không nhảy về kPlanning nữa. Replan trong lúc chạy là việc của replan nền (planner_frequency),
|
||||
// không phải phản xạ của một cycle hỏng.
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
const StateMachineOutput out = driver.tick(controller(ControllerFeedback::kNoValidCommand));
|
||||
|
||||
EXPECT_EQ(out.state, NavigationState::kPlanning);
|
||||
EXPECT_TRUE(out.start_planner);
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.run_controller);
|
||||
EXPECT_FALSE(out.start_planner);
|
||||
// Nguồn vẫn là controller: candidate của cycle hỏng là twist rỗng nên lệnh phát ra tự về 0.
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kController);
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, ControllerPatienceSurvivesReplanLoop)
|
||||
TEST(StateMachineControlling, PersistentNoValidCommandEscalatesAfterPatience)
|
||||
{
|
||||
// Vòng lặp CONTROLLING -> PLANNING -> CONTROLLING không được làm mới đồng hồ controller_patience,
|
||||
// nếu không thì controller hỏng vĩnh viễn sẽ không bao giờ dẫn tới recovery.
|
||||
// controller_patience đo "mất lệnh LIÊN TỤC bao lâu" rồi mới vào recovery với đúng lý do
|
||||
// controlling_failed. Trước 2026-08-04 nhánh nhảy về kPlanning chen vào trước khi đồng hồ kịp
|
||||
// chạy, khiến patience gần như không bao giờ có tác dụng.
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
for (int i = 0; i < 20; ++i)
|
||||
for (int i = 0; i < 40; ++i)
|
||||
{
|
||||
driver.advance(0.15);
|
||||
const NavigationState state = driver.tick(controller(ControllerFeedback::kNoValidCommand)).state;
|
||||
if (state == NavigationState::kRecovering)
|
||||
driver.advance(0.1);
|
||||
const StateMachineOutput out = driver.tick(controller(ControllerFeedback::kNoValidCommand));
|
||||
if (out.state == NavigationState::kRecovering)
|
||||
{
|
||||
EXPECT_EQ(driver.last().recovery_trigger, RecoveryTrigger::kControllingFailed);
|
||||
SUCCEED();
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kControllingFailed);
|
||||
return;
|
||||
}
|
||||
ASSERT_EQ(state, NavigationState::kPlanning) << "round " << i;
|
||||
|
||||
driver.advance(0.05);
|
||||
ASSERT_EQ(driver.tick(planReady()).state, NavigationState::kControlling) << "round " << i;
|
||||
ASSERT_EQ(out.state, NavigationState::kControlling) << "round " << i;
|
||||
}
|
||||
|
||||
FAIL() << "controller_patience never expires — the replanning loop kept refreshing the clock";
|
||||
FAIL() << "controller_patience never expired — a dead controller would stall forever";
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, StaleCostmapFreezesControllerPatience)
|
||||
{
|
||||
// Costmap stale = DATA OUTAGE (2026-08-05): control loop skip controller, nên "không có lệnh"
|
||||
// trong lúc đó không được tính vào controller_patience — sim đã ABORT sau MỘT cycle stale (33 ms
|
||||
// patience) trong khi costmap chỉ cần ~0.5 s để hồi.
|
||||
Driver driver; // controller_patience = 2.0 s, sensor_patience default 2.0 s
|
||||
driver.driveToControlling();
|
||||
|
||||
// 1.5 s stale liên tục: dưới sensor_patience, và controller_patience phải bị đóng băng.
|
||||
StateMachineInput stale;
|
||||
stale.costmap_current = false;
|
||||
for (int i = 0; i < 15; ++i)
|
||||
{
|
||||
driver.advance(0.1);
|
||||
ASSERT_EQ(driver.tick(stale).state, NavigationState::kControlling) << "round " << i;
|
||||
}
|
||||
|
||||
// Costmap hồi: controller được TRỌN một cửa controller_patience mới, không bị nợ thời gian stale.
|
||||
driver.advance(0.1);
|
||||
StateMachineInput idle_current;
|
||||
ASSERT_EQ(driver.tick(idle_current).state, NavigationState::kControlling);
|
||||
driver.advance(1.5); // 1.5 s < controller_patience 2.0 tính từ lúc hết stale
|
||||
ASSERT_EQ(driver.tick(idle_current).state, NavigationState::kControlling);
|
||||
driver.advance(1.0); // giờ mới quá patience
|
||||
const StateMachineOutput out = driver.tick(idle_current);
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kControllingFailed);
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, StaleBeyondSensorPatienceEscalates)
|
||||
{
|
||||
// Outage kéo dài quá sensor_patience là "mất dữ liệu" thật (contract 2026-08-04) — phải vào
|
||||
// recovery controlling_failed chứ không đứng im vô hạn.
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.sensor_patience = 1.0; // [s]
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput stale;
|
||||
stale.costmap_current = false;
|
||||
for (int i = 0; i < 30; ++i)
|
||||
{
|
||||
driver.advance(0.1);
|
||||
const StateMachineOutput out = driver.tick(stale);
|
||||
if (out.state == NavigationState::kRecovering)
|
||||
{
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kControllingFailed);
|
||||
EXPECT_GE(0.1 * (i + 1), 1.0); // không được escalate TRƯỚC khi hết sensor_patience
|
||||
return;
|
||||
}
|
||||
ASSERT_EQ(out.state, NavigationState::kControlling) << "round " << i;
|
||||
}
|
||||
FAIL() << "sensor_patience never expired — a permanently stale costmap would stall forever";
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, SensorPatienceZeroKeepsLegacyBehaviour)
|
||||
{
|
||||
// sensor_patience = 0: tắt cơ chế — stale ăn vào controller_patience như trước 2026-08-05.
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.sensor_patience = 0.0;
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput stale;
|
||||
stale.costmap_current = false;
|
||||
for (int i = 0; i < 40; ++i)
|
||||
{
|
||||
driver.advance(0.1);
|
||||
const StateMachineOutput out = driver.tick(stale);
|
||||
if (out.state == NavigationState::kRecovering)
|
||||
{
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kControllingFailed);
|
||||
return;
|
||||
}
|
||||
}
|
||||
FAIL() << "legacy path: controller_patience should still expire while stale";
|
||||
}
|
||||
|
||||
TEST(StateMachinePlanning, PoseLossWhilePlanningUsesTheControllingBudget)
|
||||
{
|
||||
// Mất pose thì planner không thể khởi động — đây là sự cố DỮ LIỆU, không phải "không tìm được
|
||||
// đường". Hết planner_patience phải leo thang bằng ngân sách controlling_failed để route
|
||||
// planning_failed giữ đúng nghĩa của nó (2026-08-04).
|
||||
Driver driver;
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput no_pose;
|
||||
no_pose.pose_available = false;
|
||||
driver.advance(1.1); // > planner_patience (1.0 s)
|
||||
const StateMachineOutput out = driver.tick(no_pose);
|
||||
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kControllingFailed);
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone); // mất pose: không nguồn nào được phát
|
||||
}
|
||||
|
||||
TEST(StateMachinePlanning, PoseStillMissingAfterTheWaitAborts)
|
||||
{
|
||||
// Q2 (2026-08-04), route controlling chỉ có MỘT behavior (wait): hết wait mà dữ liệu vẫn chưa về
|
||||
// thì cursor cạn -> ABORTED, robot dừng hẳn và outcome được báo — không lặp recovery vô hạn.
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.recovery_routes.planning_failed = {0, 1};
|
||||
config.recovery_routes.controlling_failed = {0};
|
||||
config.recovery_routes.oscillation = {0};
|
||||
Driver driver(config);
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput no_pose;
|
||||
no_pose.pose_available = false;
|
||||
driver.advance(1.1);
|
||||
ASSERT_EQ(driver.tick(no_pose).state, NavigationState::kRecovering);
|
||||
|
||||
// "wait" kết thúc -> quay lại PLANNING để kiểm tra dữ liệu.
|
||||
StateMachineInput recovery_done;
|
||||
recovery_done.pose_available = false;
|
||||
recovery_done.recovery = RecoveryFeedback::kSucceeded;
|
||||
ASSERT_EQ(driver.tick(recovery_done).state, NavigationState::kPlanning);
|
||||
|
||||
// Dữ liệu vẫn chưa về, ngân sách controlling đã cạn -> dừng hẳn và báo fail.
|
||||
driver.advance(1.1);
|
||||
const StateMachineOutput out = driver.tick(no_pose);
|
||||
EXPECT_EQ(out.state, NavigationState::kAborted);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kFailed);
|
||||
}
|
||||
|
||||
TEST(StateMachinePlanning, PoseReturningAfterTheWaitContinuesTheLeg)
|
||||
{
|
||||
// Nửa còn lại của Q2: dữ liệu quay lại trong/ngay sau lượt wait thì chặng chạy tiếp bình thường.
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput no_pose;
|
||||
no_pose.pose_available = false;
|
||||
driver.advance(1.1);
|
||||
ASSERT_EQ(driver.tick(no_pose).state, NavigationState::kRecovering);
|
||||
|
||||
StateMachineInput recovery_done;
|
||||
recovery_done.recovery = RecoveryFeedback::kSucceeded; // pose đã về (mặc định true)
|
||||
ASSERT_EQ(driver.tick(recovery_done).state, NavigationState::kPlanning);
|
||||
|
||||
EXPECT_EQ(driver.tick(planReady()).state, NavigationState::kControlling);
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, ProgressRestoresTheRecoveryBudget)
|
||||
{
|
||||
// Q1-C (2026-08-04): đi được quá oscillation_distance thì mọi cursor route được reset. Không có
|
||||
// nó, một chặng dài gặp hai sự cố cách nhau nửa giờ sẽ ABORT thẳng ở sự cố thứ hai vì ngân sách
|
||||
// đã cạn từ sự cố đầu.
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.recovery_routes.planning_failed = {0, 1};
|
||||
config.recovery_routes.controlling_failed = {1}; // một suất duy nhất; index 1 để phân biệt
|
||||
config.recovery_routes.oscillation = {0};
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
// Sự cố 1 tiêu hết route controlling.
|
||||
driver.advance(2.1);
|
||||
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kNoValidCommand)).state,
|
||||
NavigationState::kRecovering);
|
||||
ASSERT_EQ(driver.last().recovery_index, 1u);
|
||||
|
||||
// Contract 2026-08-04b: recovery leo thang từ kControlling quay THẲNG về kControlling và bám
|
||||
// tiếp plan cũ — không qua kPlanning.
|
||||
StateMachineInput recovery_done;
|
||||
recovery_done.recovery = RecoveryFeedback::kSucceeded;
|
||||
ASSERT_EQ(driver.tick(recovery_done).state, NavigationState::kControlling);
|
||||
|
||||
// Robot chạy tốt trở lại và đi quá oscillation_distance (0.5 m) -> ngân sách đầy lại.
|
||||
StateMachineInput progress = controller(ControllerFeedback::kCommandValid);
|
||||
progress.travelled_since_oscillation_reset = 0.6; // [m]
|
||||
ASSERT_EQ(driver.tick(progress).state, NavigationState::kControlling);
|
||||
|
||||
// Sự cố 2 phải được thử lại từ đầu route, không ABORT.
|
||||
driver.advance(2.1);
|
||||
const StateMachineOutput out = driver.tick(controller(ControllerFeedback::kNoValidCommand));
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(out.recovery_index, 1u);
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, RecoveryFromControllingResumesTheCurrentPlan)
|
||||
{
|
||||
// Contract 2026-08-04b: recovery do controlling_failed kết thúc thì bám TIẾP plan cũ — không
|
||||
// lập plan lại. Thay plan trong lúc chạy là việc riêng của replan nền theo planner_frequency.
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
driver.advance(2.1);
|
||||
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kNoValidCommand)).state,
|
||||
NavigationState::kRecovering);
|
||||
|
||||
StateMachineInput recovery_done;
|
||||
recovery_done.recovery = RecoveryFeedback::kSucceeded;
|
||||
const StateMachineOutput out = driver.tick(recovery_done);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_FALSE(out.start_planner); // không lập plan lại
|
||||
EXPECT_FALSE(out.apply_plan); // không có plan mới nào để áp
|
||||
EXPECT_TRUE(out.run_controller); // bám tiếp plan cũ ngay cycle này
|
||||
EXPECT_TRUE(out.reset_oscillation_origin);
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, DetourPathFromRecoveryIsAppliedWithoutReplanning)
|
||||
{
|
||||
// Behavior họ detour (output kPath) nộp path mới: control loop cất path vào latest_plan_ và báo
|
||||
// kPlanReady cùng cycle behavior kết thúc. Path đó phải được áp và bám tiếp — KHÔNG khởi động
|
||||
// một lượt lập plan mới đè lên nó.
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
driver.advance(2.1);
|
||||
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kNoValidCommand)).state,
|
||||
NavigationState::kRecovering);
|
||||
|
||||
StateMachineInput recovery_done;
|
||||
recovery_done.recovery = RecoveryFeedback::kSucceeded;
|
||||
recovery_done.planner = PlannerFeedback::kPlanReady;
|
||||
const StateMachineOutput out = driver.tick(recovery_done);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.apply_plan);
|
||||
EXPECT_FALSE(out.start_planner);
|
||||
EXPECT_TRUE(out.run_controller);
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, OscillationRecoveryResumesTheCurrentPlan)
|
||||
{
|
||||
// Oscillation cùng nhóm với controlling: plan cũ vẫn hợp lệ, recovery xong bám tiếp nó và mốc
|
||||
// chống quẩn được gieo lại để không leo thang ngay lập tức lần nữa.
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.oscillation_timeout = 1.0; // [s]
|
||||
config.oscillation_distance = 0.5; // [m]
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
driver.advance(1.1);
|
||||
ASSERT_EQ(driver.tick(controller(ControllerFeedback::kCommandValid)).state,
|
||||
NavigationState::kRecovering);
|
||||
|
||||
StateMachineInput recovery_done;
|
||||
recovery_done.recovery = RecoveryFeedback::kSucceeded;
|
||||
const StateMachineOutput out = driver.tick(recovery_done);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_FALSE(out.start_planner);
|
||||
EXPECT_TRUE(out.reset_oscillation_origin);
|
||||
}
|
||||
|
||||
TEST(StateMachineControlling, OscillationTimeoutEscalatesToRecovery)
|
||||
@@ -1159,9 +1414,12 @@ TEST(StateMachineInvariants, NeverRunsControllerRecoveryOrActionSimultaneously)
|
||||
requestWithActions(1),
|
||||
planReady(),
|
||||
controller(ControllerFeedback::kCommandValid),
|
||||
// 4 cycle mất lệnh liên tục (mỗi cycle cách nhau 0.6 s) vượt controller_patience 2.0 s —
|
||||
// contract 2026-08-04: đứng yên tại kControlling cho tới khi patience đưa vào recovery.
|
||||
controller(ControllerFeedback::kNoValidCommand),
|
||||
controller(ControllerFeedback::kNoValidCommand),
|
||||
controller(ControllerFeedback::kNoValidCommand),
|
||||
controller(ControllerFeedback::kNoValidCommand),
|
||||
plannerFailed(),
|
||||
plannerFailed(),
|
||||
recovery(RecoveryFeedback::kRunning),
|
||||
recovery(RecoveryFeedback::kSucceeded),
|
||||
planReady(),
|
||||
@@ -1309,6 +1567,312 @@ TEST(StateMachineConfigTest, RejectsDisablingEveryHungPlannerDetector)
|
||||
EXPECT_NE(error.find("hung planner"), std::string::npos) << error;
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// Giám sát tuyến (contract 2026-08-04d)
|
||||
// ================================================================================================
|
||||
|
||||
namespace
|
||||
{
|
||||
/// Config có đủ hai route giám sát tuyến; mỗi trigger một behavior riêng để phân biệt được index.
|
||||
StateMachineConfig monitorConfig()
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.recovery_behavior_count = 4;
|
||||
config.recovery_routes.planning_failed = { 0 };
|
||||
config.recovery_routes.controlling_failed = { 1 };
|
||||
config.recovery_routes.oscillation = { 0 };
|
||||
config.recovery_routes.path_blocked = { 2 };
|
||||
config.recovery_routes.off_path = { 3 };
|
||||
return config;
|
||||
}
|
||||
|
||||
StateMachineInput blockedInput()
|
||||
{
|
||||
StateMachineInput input;
|
||||
input.controller = ControllerFeedback::kCommandValid;
|
||||
input.path_blocked = true;
|
||||
// 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;
|
||||
return input;
|
||||
}
|
||||
|
||||
StateMachineInput offPathInput()
|
||||
{
|
||||
StateMachineInput input;
|
||||
input.controller = ControllerFeedback::kCommandValid;
|
||||
input.off_path = true;
|
||||
input.active_recovery_output = RecoveryOutputKind::kPath;
|
||||
return input;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(StateMachinePathMonitor, BlockedPathStopsTheRobotAndEntersRecovery)
|
||||
{
|
||||
Driver driver(monitorConfig());
|
||||
driver.driveToControlling();
|
||||
|
||||
const StateMachineOutput out = driver.tick(blockedInput());
|
||||
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kPathBlocked);
|
||||
EXPECT_EQ(out.recovery_index, 2u);
|
||||
EXPECT_TRUE(out.start_recovery);
|
||||
EXPECT_TRUE(out.stop_planner);
|
||||
// Bất biến: kRecovering với behavior họ kNone thì không nguồn nào được phát vận tốc.
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||
EXPECT_FALSE(out.run_controller);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, OffPathUsesItsOwnRoute)
|
||||
{
|
||||
Driver driver(monitorConfig());
|
||||
driver.driveToControlling();
|
||||
|
||||
const StateMachineOutput out = driver.tick(offPathInput());
|
||||
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kOffPath);
|
||||
EXPECT_EQ(out.recovery_index, 3u);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, BlockedPathWinsWhenBothFire)
|
||||
{
|
||||
// Tuyến bị chắn là NGUYÊN NHÂN; lệch tuyến thường là HỆ QUẢ của việc né chính vật cản đó.
|
||||
Driver driver(monitorConfig());
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput both;
|
||||
both.controller = ControllerFeedback::kCommandValid;
|
||||
both.path_blocked = true;
|
||||
both.off_path = true;
|
||||
|
||||
EXPECT_EQ(driver.tick(both).recovery_trigger, RecoveryTrigger::kPathBlocked);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, GoalReachedWinsOverABlockedPath)
|
||||
{
|
||||
// Đã tới đích thì không còn gì để vòng qua — nhánh goal phải đứng trước.
|
||||
Driver driver(monitorConfig());
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput input = blockedInput();
|
||||
input.controller = ControllerFeedback::kGoalReached;
|
||||
|
||||
const StateMachineOutput out = driver.tick(input);
|
||||
EXPECT_EQ(out.state, NavigationState::kSucceeded);
|
||||
EXPECT_FALSE(out.start_recovery);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, EmptyRouteMutesTheTriggerInsteadOfAborting)
|
||||
{
|
||||
// Route rỗng = cơ chế tắt. Cờ vẫn tới đây thì KHÔNG được kết thúc chặng (contract 2026-08-05e):
|
||||
// path_blocked là DỰ BÁO, plan vẫn hợp lệ và controller vẫn ra lệnh được. Khoá trigger, bám tiếp.
|
||||
StateMachineConfig config = monitorConfig();
|
||||
config.recovery_routes.path_blocked.clear();
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
const StateMachineOutput out = driver.tick(blockedInput());
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.monitor_trigger_suppressed);
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kPathBlocked);
|
||||
EXPECT_FALSE(out.report_outcome);
|
||||
EXPECT_TRUE(out.run_controller); // không mất nhịp điều khiển nào
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, DetourPathIsAppliedAndDrivingResumes)
|
||||
{
|
||||
// Detour trả kPath: control loop cất path vào latest_plan_ và báo kPlanReady cùng lượt behavior
|
||||
// kết thúc; state machine áp path đó rồi bám tiếp, KHÔNG lập plan lại (contract 08-04b).
|
||||
Driver driver(monitorConfig());
|
||||
driver.driveToControlling();
|
||||
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
|
||||
|
||||
StateMachineInput detour_done;
|
||||
detour_done.recovery = RecoveryFeedback::kSucceeded;
|
||||
detour_done.planner = PlannerFeedback::kPlanReady;
|
||||
|
||||
const StateMachineOutput out = driver.tick(detour_done);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.apply_plan);
|
||||
EXPECT_FALSE(out.start_planner);
|
||||
EXPECT_TRUE(out.run_controller);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, ExhaustingTheRouteMutesTheTriggerAndKeepsDriving)
|
||||
{
|
||||
// Contract 2026-08-05e: hết đường vòng thì bám tiếp plan cũ, KHÔNG ABORT. Sim 2026-08-05 kết
|
||||
// thúc chặng đúng lúc controller=command_valid, costmap_current=yes — vứt một chặng mà robot
|
||||
// hoàn toàn khoẻ, chỉ vì một DỰ BÁO.
|
||||
Driver driver(monitorConfig()); // route path_blocked có đúng 1 behavior
|
||||
driver.driveToControlling();
|
||||
|
||||
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
|
||||
|
||||
StateMachineInput failed;
|
||||
failed.recovery = RecoveryFeedback::kFailed;
|
||||
ASSERT_EQ(driver.tick(failed).state, NavigationState::kControlling);
|
||||
|
||||
// Vẫn tắc, route đã cạn: khoá trigger và đi tiếp.
|
||||
const StateMachineOutput out = driver.tick(blockedInput());
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.monitor_trigger_suppressed);
|
||||
EXPECT_FALSE(out.report_outcome);
|
||||
EXPECT_TRUE(out.run_controller);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, MutedTriggerStaysQuietUntilTheRobotMakesProgress)
|
||||
{
|
||||
// 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à tình hình không đổi. Mở khoá đúng ở mốc tiến độ đã reset cursor (Q1-C).
|
||||
Driver driver(monitorConfig());
|
||||
driver.driveToControlling();
|
||||
|
||||
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
|
||||
StateMachineInput failed;
|
||||
failed.recovery = RecoveryFeedback::kFailed;
|
||||
ASSERT_EQ(driver.tick(failed).state, NavigationState::kControlling);
|
||||
ASSERT_TRUE(driver.tick(blockedInput()).monitor_trigger_suppressed);
|
||||
|
||||
// Đang bị khoá: cờ tới cũng không leo thang, và KHÔNG log lại (chỉ một dòng ở sườn khoá).
|
||||
const StateMachineOutput muted = driver.tick(blockedInput());
|
||||
EXPECT_EQ(muted.state, NavigationState::kControlling);
|
||||
EXPECT_FALSE(muted.monitor_trigger_suppressed);
|
||||
EXPECT_FALSE(muted.start_recovery);
|
||||
EXPECT_TRUE(muted.run_controller);
|
||||
|
||||
// Đi được quá oscillation_distance -> mở khoá + ngân sách route đầy lại.
|
||||
StateMachineInput progress;
|
||||
progress.controller = ControllerFeedback::kCommandValid;
|
||||
progress.travelled_since_oscillation_reset = 0.6; // [m] > 0.5
|
||||
ASSERT_EQ(driver.tick(progress).state, NavigationState::kControlling);
|
||||
|
||||
const StateMachineOutput retried = driver.tick(blockedInput());
|
||||
EXPECT_EQ(retried.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(retried.recovery_index, 2u);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, ControllingFailedIsStillTheWayToAbort)
|
||||
{
|
||||
// Bỏ ABORT khỏi nhánh monitor KHÔNG được làm mất khả năng kết thúc chặng: robot dừng sát vật cản
|
||||
// -> controller hết ra lệnh -> controller_patience -> controlling_failed -> route riêng -> ABORT.
|
||||
StateMachineConfig config = monitorConfig();
|
||||
config.recovery_routes.path_blocked.clear(); // monitor tắt hẳn
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
// Route controlling_failed của monitorConfig() có đúng 1 behavior.
|
||||
for (int i = 0; i < 40; ++i)
|
||||
{
|
||||
driver.advance(0.1);
|
||||
const StateMachineOutput out = driver.tick(controller(ControllerFeedback::kNoValidCommand));
|
||||
if (out.state == NavigationState::kRecovering)
|
||||
{
|
||||
ASSERT_EQ(out.recovery_trigger, RecoveryTrigger::kControllingFailed);
|
||||
StateMachineInput failed;
|
||||
failed.recovery = RecoveryFeedback::kFailed;
|
||||
ASSERT_EQ(driver.tick(failed).state, NavigationState::kControlling);
|
||||
|
||||
// Lượt controlling_failed thứ hai: route cạn -> ABORT, đúng như trước.
|
||||
for (int j = 0; j < 40; ++j)
|
||||
{
|
||||
driver.advance(0.1);
|
||||
const StateMachineOutput second =
|
||||
driver.tick(controller(ControllerFeedback::kNoValidCommand));
|
||||
if (second.state == NavigationState::kAborted)
|
||||
{
|
||||
EXPECT_EQ(second.outcome, NavigationOutcome::kFailed);
|
||||
return;
|
||||
}
|
||||
}
|
||||
FAIL() << "controlling_failed route never exhausted into ABORTED";
|
||||
}
|
||||
}
|
||||
FAIL() << "controller_patience never expired";
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, SuccessfulDetourRefillsTheBudgetImmediately)
|
||||
{
|
||||
// 2026-08-05: detour THÀNH CÔNG + nộp path mới = sự cố đã giải quyết, cursor reset NGAY — không
|
||||
// chờ mốc oscillation_distance (sim: bám detour 0.45 m, gặp vật cản thứ hai, ABORT vì thiếu 5 cm
|
||||
// dù route mới chạy đúng một behavior thành công).
|
||||
Driver driver(monitorConfig()); // route path_blocked có đúng 1 behavior
|
||||
driver.driveToControlling();
|
||||
|
||||
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
|
||||
|
||||
StateMachineInput detour_done;
|
||||
detour_done.recovery = RecoveryFeedback::kSucceeded;
|
||||
detour_done.planner = PlannerFeedback::kPlanReady;
|
||||
ASSERT_EQ(driver.tick(detour_done).state, NavigationState::kControlling);
|
||||
|
||||
// Chắn lần hai ngay sau đó (chưa đi đủ oscillation_distance): detour vẫn phải được chạy lại.
|
||||
const StateMachineOutput out = driver.tick(blockedInput());
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(out.recovery_index, 2u);
|
||||
EXPECT_TRUE(out.start_recovery);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, SucceededWithoutANewPathStillConsumesTheBudget)
|
||||
{
|
||||
// `wait` thành công trivially sau N giây mà KHÔNG nộp path: nếu nó cũng reset cursor thì ngân
|
||||
// sách route không bao giờ cạn và robot thử vòng vô hạn. Chỉ "thành công + path mới" được reset.
|
||||
Driver driver(monitorConfig()); // route path_blocked có đúng 1 behavior
|
||||
driver.driveToControlling();
|
||||
|
||||
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
|
||||
|
||||
StateMachineInput wait_done;
|
||||
wait_done.recovery = RecoveryFeedback::kSucceeded; // không có kPlanReady
|
||||
ASSERT_EQ(driver.tick(wait_done).state, NavigationState::kControlling);
|
||||
|
||||
// Cursor đã bị tiêu: lượt sau không còn behavior nào -> khoá trigger (không ABORT, 08-05e).
|
||||
const StateMachineOutput out = driver.tick(blockedInput());
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.monitor_trigger_suppressed);
|
||||
EXPECT_FALSE(out.start_recovery);
|
||||
}
|
||||
|
||||
TEST(StateMachinePathMonitor, ProgressRefillsTheMonitorBudget)
|
||||
{
|
||||
// Q1-C áp cho cả trigger mới: đi được quá oscillation_distance thì ngân sách đầy lại, nên một
|
||||
// tuyến dài gặp nhiều vật cản vẫn xử lý được từng cái một.
|
||||
Driver driver(monitorConfig());
|
||||
driver.driveToControlling();
|
||||
|
||||
ASSERT_EQ(driver.tick(blockedInput()).state, NavigationState::kRecovering);
|
||||
StateMachineInput failed;
|
||||
failed.recovery = RecoveryFeedback::kFailed;
|
||||
ASSERT_EQ(driver.tick(failed).state, NavigationState::kControlling);
|
||||
|
||||
StateMachineInput progress;
|
||||
progress.controller = ControllerFeedback::kCommandValid;
|
||||
progress.travelled_since_oscillation_reset = 0.6; // [m] > oscillation_distance
|
||||
ASSERT_EQ(driver.tick(progress).state, NavigationState::kControlling);
|
||||
|
||||
const StateMachineOutput out = driver.tick(blockedInput());
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(out.recovery_index, 2u);
|
||||
}
|
||||
|
||||
TEST(StateMachineConfigValidation, MonitorRoutesMayBeEmptyButIndicesMustExist)
|
||||
{
|
||||
StateMachineConfig config = monitorConfig();
|
||||
std::string error;
|
||||
EXPECT_TRUE(config.validate(error)) << error;
|
||||
|
||||
// Rỗng là hợp lệ: cơ chế tắt.
|
||||
config.recovery_routes.path_blocked.clear();
|
||||
config.recovery_routes.off_path.clear();
|
||||
EXPECT_TRUE(config.validate(error)) << error;
|
||||
|
||||
// Index trỏ vào behavior không tồn tại thì không: lúc chạy sẽ start() vào hư không.
|
||||
config.recovery_routes.off_path = { 99 };
|
||||
EXPECT_FALSE(config.validate(error));
|
||||
EXPECT_NE(error.find("path_blocked"), std::string::npos) << error;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
@@ -33,6 +33,7 @@ using move_base2::testing::FakeClockPort;
|
||||
using move_base2::testing::FakeControllerPort;
|
||||
using move_base2::testing::FakeCostmapStatusPort;
|
||||
using move_base2::testing::FakeMissionPort;
|
||||
using move_base2::testing::FakePathCheckPort;
|
||||
using move_base2::testing::FakePlannerPort;
|
||||
using move_base2::testing::FakePosePort;
|
||||
using move_base2::testing::FakeRecoveryPort;
|
||||
@@ -128,6 +129,7 @@ public:
|
||||
deps_.mission = &mission_;
|
||||
deps_.action = &action_;
|
||||
deps_.costmap_status = &costmap_status_;
|
||||
deps_.path_check = &path_check_;
|
||||
|
||||
std::string error;
|
||||
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
|
||||
@@ -176,6 +178,7 @@ public:
|
||||
FakeMissionPort mission_;
|
||||
FakeActionPort action_;
|
||||
FakeCostmapStatusPort costmap_status_;
|
||||
FakePathCheckPort path_check_;
|
||||
ControlLoopDeps deps_;
|
||||
|
||||
private:
|
||||
@@ -1058,6 +1061,56 @@ TEST(ControlLoopAsyncPlanner, KeepsFollowingTheOldPlanWhileReplanningInBackgroun
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ControlLoopAsyncPlanner, BackgroundReplanSwapsThePlanWithoutLeavingControlling)
|
||||
{
|
||||
// Contract 2026-08-04: `planner_frequency` là cơ chế thay plan duy nhất trong lúc chạy — plan
|
||||
// mới được lập nền theo nhịp và thay ngay trong kControlling, không đổi state, không dừng robot.
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.planner_frequency = 2.0; // [Hz] -> chu kỳ 0.5 s = 10 cycle @ kControlPeriod 0.05 s
|
||||
Fixture fx(config);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fx.loop_.submit(makeRequest(5.0), reason)) << reason;
|
||||
|
||||
// 1.5 s: lượt plan đầu (kPlanning) + ít nhất 2 nhịp replan nền.
|
||||
for (int i = 0; i < 30; ++i)
|
||||
{
|
||||
fx.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fx.loop_.state(), NavigationState::kControlling);
|
||||
EXPECT_GE(fx.planner_.makePlanCount(), 3u); // 1 lượt đầu + >= 2 replan nền
|
||||
EXPECT_GE(fx.controller_.setPlanCount(), 3u); // mỗi plan mới đều tới controller
|
||||
EXPECT_EQ(join(fx.states()), "[PLANNING, CONTROLLING]") << "replan nền không được đổi state";
|
||||
}
|
||||
|
||||
TEST(ControlLoopAsyncPlanner, BackgroundReplanFailureKeepsTheCurrentPlanAndSkipsBackup)
|
||||
{
|
||||
// Replan nền hỏng thì plan cũ vẫn hiệu lực: không recovery, và nhất là KHÔNG kích backup
|
||||
// planner — một lượt replan hụt mà đổi hẳn sang SBPL là mất quỹ đạo Order cho phần còn lại.
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.planner_frequency = 2.0; // [Hz]
|
||||
config.backup_global_planner_name = "FakeBackupPlanner";
|
||||
Fixture fx(config);
|
||||
|
||||
// Lượt đầu thành công; mọi lượt sau (toàn replan nền) đều fail.
|
||||
fx.planner_.setScript({PlannerScript::kOk, PlannerScript::kFail});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fx.loop_.submit(makeRequest(5.0), reason)) << reason;
|
||||
|
||||
for (int i = 0; i < 30; ++i)
|
||||
{
|
||||
fx.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fx.loop_.state(), NavigationState::kControlling);
|
||||
EXPECT_GE(fx.planner_.makePlanCount(), 2u); // replan nền có chạy thật và có fail thật
|
||||
EXPECT_EQ(fx.planner_.activePlanner(), "FakeGlobalPlanner");
|
||||
EXPECT_EQ(fx.planner_.swapCount(), 1u) << "backup planner must not be engaged by a background "
|
||||
"replan failure";
|
||||
}
|
||||
|
||||
TEST(ControlLoopAsyncPlanner, CancelWhilePlanningCancelsTheRunningPlan)
|
||||
{
|
||||
// Không huỷ thì lượt đang bay vẫn về và chiếm chỗ hộp thư, rồi bị nhận nhầm cho yêu cầu kế tiếp.
|
||||
@@ -1346,6 +1399,372 @@ TEST(StaleCostmap, NullPortMeansNoGuard)
|
||||
"asked it";
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// PathMonitor (contract 2026-08-04d)
|
||||
// ================================================================================================
|
||||
|
||||
namespace
|
||||
{
|
||||
/// @brief Nộp yêu cầu và trả true nếu lõi nhận — gọn hơn việc mỗi ca tự khai biến `reason`.
|
||||
bool submitOk(Fixture& fixture, const NavigationRequest& request)
|
||||
{
|
||||
std::string reason;
|
||||
const bool accepted = fixture.loop_.submit(request, reason);
|
||||
EXPECT_TRUE(accepted) << reason;
|
||||
return accepted;
|
||||
}
|
||||
|
||||
/// Config có giám sát tuyến BẬT, ngưỡng ngắn để test không phải tua thời gian dài.
|
||||
ControlLoopConfig monitorConfig()
|
||||
{
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.recovery_routes.planning_failed = { 0 };
|
||||
config.state_machine.recovery_routes.controlling_failed = { 0 };
|
||||
config.state_machine.recovery_routes.oscillation = { 0 };
|
||||
config.state_machine.recovery_routes.path_blocked = { 1 };
|
||||
config.state_machine.recovery_routes.off_path = { 1 };
|
||||
|
||||
config.path_monitor.enabled = true;
|
||||
config.path_monitor.check_period = 0.0; // quét mỗi cycle: test điều khiển thời gian bằng advance
|
||||
config.path_monitor.confirm_time = 0.2; // [s]
|
||||
config.path_monitor.horizon = 3.0; // [m]
|
||||
config.path_monitor.min_detour_distance = 0.5; // [m]
|
||||
// Phép đo lệch tuyến TẮT ở config cơ sở: pose giả đứng yên tại gốc còn plan giả nằm ở goal, nên
|
||||
// cross-track luôn lớn và sẽ át hết mọi ca về "tuyến bị chắn". Ca lệch tuyến có config riêng.
|
||||
config.path_monitor.max_cross_track = 0.0; // [m]
|
||||
config.path_monitor.grace_after_new_plan = 0.0; // tắt để test khai hoả được ngay
|
||||
return config;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, BlockedPathStopsTheRobotAfterConfirmTime)
|
||||
{
|
||||
Fixture fixture(monitorConfig());
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
// Recovery chạy dài để test quan sát được trạng thái DỪNG, thay vì thấy nó thoáng qua trong một
|
||||
// cycle rồi quay lại kControlling.
|
||||
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce(); // kPlanning
|
||||
fixture.stepOnce(); // kControlling
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
fixture.path_check_.setBlocked(true, 1.5);
|
||||
|
||||
// Chưa đủ confirm_time: robot vẫn chạy.
|
||||
fixture.stepOnce();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
for (int i = 0; i < 6; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||||
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, PathBlockedCanBeDisabledOnItsOwn)
|
||||
{
|
||||
// Công tắc riêng (2026-08-06): tắt phép đo "tuyến bị chắn" mà không phải đặt `horizon` về 0 —
|
||||
// ngưỡng giữ nguyên để bật lại chỉ cần đổi một cờ, và đọc config thấy rõ ý định.
|
||||
ControlLoopConfig config = monitorConfig();
|
||||
config.path_monitor.path_blocked_enabled = false;
|
||||
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
fixture.path_check_.setBlocked(true, 1.5);
|
||||
for (int i = 0; i < 10; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, FlickeringObstacleDoesNotStopTheRobot)
|
||||
{
|
||||
// Người đi ngang qua đúng một lượt quét không được làm robot dừng — đó là cả lý do có debounce.
|
||||
Fixture fixture(monitorConfig());
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
fixture.path_check_.setBlocked(i % 2 == 0, 1.5);
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, ObstacleTooCloseIsLeftToTheControllerPath)
|
||||
{
|
||||
// Vật cản sát nách: detour hầu như không ra nghiệm, và ca đó đã có controller_patience lo.
|
||||
Fixture fixture(monitorConfig());
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
fixture.path_check_.setBlocked(true, 0.2); // [m] < min_detour_distance
|
||||
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, StaleCostmapSuppressesTheMonitor)
|
||||
{
|
||||
// Costmap quá hạn thì mọi kết luận về vật cản đều là quá khứ — không được khai hoả dựa vào nó.
|
||||
Fixture fixture(monitorConfig());
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
|
||||
fixture.path_check_.setBlocked(true, 1.5);
|
||||
fixture.costmap_status_.setCurrent(false);
|
||||
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, UnavailableCheckIsTreatedAsUnknown)
|
||||
{
|
||||
// Cổng trả false = "không kết luận được". Không được suy thành bẩn (robot dừng oan mỗi lần TF trễ).
|
||||
Fixture fixture(monitorConfig());
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
|
||||
fixture.path_check_.setBlocked(true, 1.5);
|
||||
fixture.path_check_.setAvailable(false);
|
||||
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, DockingLegIsNeverMonitored)
|
||||
{
|
||||
// Đường cong vào dock là một thể thống nhất; cắt ghép nó là phá chính hình học đó.
|
||||
ControlLoopConfig config = monitorConfig();
|
||||
config.docking_requires_marker = false;
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
|
||||
NavigationRequest request = makeRequest(3.0);
|
||||
request.profile = MotionProfile::kDocking;
|
||||
ASSERT_TRUE(submitOk(fixture, request));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
fixture.path_check_.setBlocked(true, 1.5);
|
||||
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, DriftingOffThePlanStopsTheRobot)
|
||||
{
|
||||
// Local planner tự né vật cản nhỏ (tầng 0) có thể kéo robot ra xa tuyến mà plan vẫn "sạch" và
|
||||
// controller vẫn ra lệnh — không trigger nào khác nhìn thấy tình huống này.
|
||||
ControlLoopConfig config = monitorConfig();
|
||||
config.path_monitor.max_cross_track = 0.4; // [m]
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
// Plan giả chỉ có pose goal (3, 0); robot bám sát nó thì cross-track nhỏ.
|
||||
fixture.pose_.setPosition(3.0, 0.1);
|
||||
fixture.stepOnce();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
// Dạt sang bên quá ngưỡng: sau `confirm_time` thì dừng.
|
||||
fixture.pose_.setPosition(3.0, 0.9);
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||||
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, OffPathCanBeDisabledOnItsOwn)
|
||||
{
|
||||
// Đối xứng với `PathBlockedCanBeDisabledOnItsOwn`: ngưỡng `max_cross_track` vẫn để nguyên 0.4 m,
|
||||
// chỉ hạ cờ — cấu hình đã đo được giữ lại, bật lại là một dòng.
|
||||
ControlLoopConfig config = monitorConfig();
|
||||
config.path_monitor.max_cross_track = 0.4; // [m] ngưỡng thật, giữ nguyên
|
||||
config.path_monitor.off_path_enabled = false;
|
||||
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
fixture.pose_.setPosition(3.0, 5.0); // lệch rất xa
|
||||
for (int i = 0; i < 10; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, GracePeriodSuppressesTheOffPathCheck)
|
||||
{
|
||||
// Ngay sau khi đổi plan, pose robot có thể lệch nhất thời so với plan vừa tới (rõ nhất lúc
|
||||
// preempt/đổi chặng). Đo lệch tuyến lúc đó là khai hoả oan.
|
||||
ControlLoopConfig config = monitorConfig();
|
||||
config.path_monitor.max_cross_track = 0.4; // [m]
|
||||
config.path_monitor.grace_after_new_plan = 5.0; // [s] dài hơn hẳn kịch bản
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
fixture.pose_.setPosition(3.0, 5.0); // lệch rất xa
|
||||
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, EmptyRouteDisablesTheMonitorInsteadOfAborting)
|
||||
{
|
||||
// Route rỗng nghĩa là behavior detour không nạp được (hoặc chưa khai). Giám sát mà không có
|
||||
// đường xử lý sẽ biến một cơ chế đang tắt thành ABORT ngay lần đầu thấy vật cản — đúng lỗi đã
|
||||
// gặp trên sim 2026-08-05. Đúng: không khai hoả, để controller_patience lo như trước.
|
||||
ControlLoopConfig config = monitorConfig();
|
||||
config.state_machine.recovery_routes.path_blocked.clear();
|
||||
config.state_machine.recovery_routes.off_path.clear();
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
fixture.path_check_.setBlocked(true, 1.5);
|
||||
|
||||
for (int i = 0; i < 10; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, OffPathRouteEmptyDisablesOnlyThatCheck)
|
||||
{
|
||||
// Hai phép đo độc lập: thiếu route của cái này không được làm câm cái kia.
|
||||
ControlLoopConfig config = monitorConfig();
|
||||
config.path_monitor.max_cross_track = 0.4; // [m]
|
||||
config.state_machine.recovery_routes.off_path.clear();
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
|
||||
// Lệch rất xa nhưng route off_path rỗng -> không khai hoả.
|
||||
fixture.pose_.setPosition(3.0, 5.0);
|
||||
for (int i = 0; i < 6; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
// Còn path_blocked vẫn còn route thì vẫn phải chạy bình thường.
|
||||
fixture.path_check_.setBlocked(true, 1.5);
|
||||
for (int i = 0; i < 8; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||||
}
|
||||
|
||||
TEST(WalkingSkeletonPathMonitor, BlockedFreshPlanDoesNotReplaceACleanOne)
|
||||
{
|
||||
// Luật "không thay plan sạch bằng plan bẩn": không có nó thì planner mù ghi đè đường vòng mỗi
|
||||
// nhịp replan nền và robot dừng-detour-chạy-dừng liên tục.
|
||||
ControlLoopConfig config = monitorConfig();
|
||||
config.planner_frequency = 1000.0; // ép replan nền nổ mỗi cycle
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setScript(std::vector<PlannerScript>(20, PlannerScript::kOk));
|
||||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||||
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
const std::size_t accepted_before = fixture.controller_.setPlanCount();
|
||||
|
||||
// Plan mới về đều đặn nhưng đều bị chắn -> controller không được nhận thêm plan nào.
|
||||
fixture.path_check_.setBlocked(true, 1.5);
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
fixture.stepOnce();
|
||||
}
|
||||
|
||||
EXPECT_EQ(fixture.controller_.setPlanCount(), accepted_before);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
Reference in New Issue
Block a user