feat: lifecycle contract — cancel/pause must reach true quiescence before reporting done
Root cause (from a C++ host log, 2026-09-11): cancel during PLANNING only set a discard flag on the planner thread, which ran to allocated_time before CANCELLED could be reported; a queued next mission landed on a still-busy planner and timed out too. Same class of bug existed for pause, recovery, and implicitly for a legitimate ABORTED read while a component was still unwinding. Full audit, decisions, and phased design in docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md; old-vs-new behaviour per state in docs/LIFECYCLE_BEHAVIOUR_MATRIX.md. Runtime quiescence, not just "command sent": - kPausing (new state) mirrors kCancelling: PAUSED/CANCELLED is only entered once planner and recovery are idle, the action reports terminal, and the robot is stopped per odometry (robot_stopped, stopped_measured_linear/ angular_eps) — not merely "the command we sent was zero". settle_timeout bounds the wait; exceeding it still finishes but logs an ungated error naming which component was still busy, so a plugin that doesn't honour cancel/pause is visible instead of silently swallowed. - PlannerRunner::running_planner_ (new): the instance the planner thread is actually inside makePlan() with, tracked separately from active_ — active_ can already point at a different instance after swapPlanner() while the old attempt is still running. cancelPlan(), swapPlanner() (when a job is running_ or only pending_ and not yet picked up), and the destructor all preempt through this pointer now; the old code preempted through active_ and could silently preempt the wrong (idle) instance after a profile swap. - ComponentStatusBoard + per-component ComponentPhase (idle/busy/stopping/ paused/hung), read by PlannerRunner, RecoveryRunner, ActionRunner and ControlLoop instead of ad hoc bools — this is what makes "did everything actually stop" answerable at all, and what the new Watchdog thread reads to flag a component busy-without-progress as hung (logged once at the edge) without the control loop needing to detect its own stall. - Resume: PLANNING replans from the current pose. CONTROLLING re-issues setPlan() with the plan already in hand (decided: setPlan again, not a fresh plan) — the local planner needs nothing else since it already runs once per control cycle; a fresh plan on resume was considered and rejected as unnecessary work for a plan that's still valid. - Command-to-zero on cancel/pause stays immediate (no deceleration ramp) — existing VelocityArbiter behaviour, left as is per a scoped decision. Depends on: Test/sbpl (bd89924), pnkx_nav_core (2b0993b, robot_nav_core:: Preemptable + component_status_probe.h), Test/sbpl_lattice_planner (7456e99), Test/recovery_core (254c7fc, onCancelRequested + ABI guard), Test/ sbpl_recovery (ea79686, worker-thread cancel), Test/action_core (669c3f7, pause/resume + kCancelled), Test/dock_pattern_action (cc1ea74). Verified: 13 gtest binaries / 528 tests, 0 failures. Runtime on the dev machine (Gazebo + real ROS host + VDA5050 over MQTT), 6 scenarios — cancel during PLANNING, pause/resume during PLANNING and CONTROLLING (incl. submit-while-still-winding-down), pause-then-cancel during PLANNING and CONTROLLING: no ABORTED/RECOVERING in any run, preempt lands within hundredths of a millisecond of entering CANCELLING/PAUSING, PAUSED/CANCELLED only reported once the robot is actually stopped per odometry. Full numbers in the plan doc section 6. Excluded from this commit (pre-existing, unrelated): config/runtime/recovery_behaviors_params.yaml (allocated_time 1.0->2.0, SBPLDetourPlanner tuning predating this work). Not yet done (see plan doc "Trạng thái"): config tuning (phase 0, pending per a scoping decision); runtime scenarios for cancel mid-detour and a 30 s pause mid-action; commit to rb_ws is a separate step, not done here. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -230,6 +230,7 @@ endif()
|
||||
# ========================================================
|
||||
add_library(move_base2_core SHARED
|
||||
src/navigation_state.cpp
|
||||
src/component_status.cpp
|
||||
src/state_machine.cpp
|
||||
src/velocity_arbiter.cpp
|
||||
src/plan_inspector.cpp
|
||||
@@ -242,6 +243,7 @@ add_library(move_base2_core SHARED
|
||||
src/runners/planner_runner.cpp
|
||||
src/runners/controller_runner.cpp
|
||||
src/io/runtime_stats.cpp
|
||||
src/io/watchdog.cpp
|
||||
src/io/sensor_gateway.cpp
|
||||
src/io/sensor_store_types.cpp
|
||||
src/io/costmap_exporter.cpp
|
||||
@@ -450,6 +452,8 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
|
||||
endforeach()
|
||||
|
||||
set(MOVE_BASE2_TESTS
|
||||
component_status_test
|
||||
watchdog_test
|
||||
state_machine_test
|
||||
velocity_arbiter_test
|
||||
plan_inspector_test
|
||||
|
||||
@@ -112,7 +112,7 @@ planner_frequency: 0.0
|
||||
# ► Chỉnh: đặt > thời gian lập plan xấu nhất của global planner. SBPL `allocated_time: 10.0` ở
|
||||
# sbpl_global_params.yaml ⇒ 2.0 s là NGẮN HƠN trần của chính planner: nếu thấy leo thang trong khi
|
||||
# planner vẫn đang chạy, tăng giá trị này lên trên trần đó.
|
||||
planner_patience: 2.0
|
||||
planner_patience: 25.0
|
||||
|
||||
# Số lần lập plan HỎNG liên tiếp được phép trước khi leo thang. 0 = hỏng một lượt là leo thang ngay.
|
||||
# ► Chỉnh: TĂNG (1–3) nếu planner thỉnh thoảng fail do costmap chưa kịp cập nhật lúc vừa nhận goal.
|
||||
@@ -120,6 +120,28 @@ planner_patience: 2.0
|
||||
# ai phát hiện (config validate chặn ca tắt cả hai).
|
||||
max_planning_retries: 0
|
||||
|
||||
# [s] Trần chờ ở CANCELLING và PAUSING cho tới khi runtime IM HẲN rồi mới báo CANCELLED/PREEMPTED
|
||||
# hoặc PAUSED ra host (trong lúc PAUSING host vẫn thấy tên state cũ + feed_back_str "pausing…").
|
||||
# "Im hẳn" = ba điều kiện cùng đúng: (1) lệnh vận tốc = 0 VÀ odom đọc ≈ 0 (xem hai khoá dưới),
|
||||
# (2) thread global planner rảnh và recovery đã dừng — kể cả lượt makePlan đã bị huỷ mà plugin không cắt được (SBPL
|
||||
# hiện chạy tới hết `allocated_time`), (3) action đang chạy đã trả terminal. Host đọc PREEMPTED là
|
||||
# "xong rồi, gửi goal kế được" — báo sớm thì goal kế bị `startPlan()` từ chối vì thread còn bận.
|
||||
# ► Chỉnh: mặc định 2.0. TĂNG (5–10) nếu SBPL `allocated_time` lớn và chưa có preempt (pha 2) — quá
|
||||
# trần vẫn CANCELLED nhưng runtime in LỖI "cancel settle timeout", không tắt được. 0 = TẮT: kết
|
||||
# thúc ngay khi lệnh = 0 như trước 11/9/2026 (host dễ gửi goal kế lúc planner còn bận).
|
||||
settle_timeout: 2.0
|
||||
|
||||
# [m/s] Ngưỡng coi robot ĐÃ DỪNG theo vận tốc ĐO ĐƯỢC (odom), dùng cho điều kiện (1) ở trên.
|
||||
# Lệnh về 0 không có nghĩa bánh xe đã đứng — driver còn giảm tốc; PREEMPTED báo lúc đó là báo cho
|
||||
# một robot đang trượt. Chỉ có tác dụng khi host đẩy odom vào (`addOdometry`); không có odom thì
|
||||
# tự lùi về đo bằng lệnh đã phát.
|
||||
# ► Chỉnh: TĂNG (0.05) nếu odom nhiễu giữ CANCELLING tới tận `settle_timeout` dù robot đã
|
||||
# đứng (xem log lỗi settle timeout với robot_stopped=no). 0 = bỏ odom, chỉ nhìn lệnh.
|
||||
stopped_measured_linear_eps: 0.02
|
||||
|
||||
# [rad/s] Như trên cho trục quay.
|
||||
stopped_measured_angular_eps: 0.02
|
||||
|
||||
# [s] Ở trong bán kính `oscillation_distance` quá lâu = coi là quẩn -> recovery `oscillation`.
|
||||
# ► Chỉnh: <= 0 là TẮT (giá trị hiện tại). Bật (vd 10–20 s) khi thấy robot lắc qua lắc lại tại chỗ
|
||||
# mà không trigger nào khác bắt được. Bật thì `oscillation_distance` bắt buộc phải > 0.
|
||||
@@ -220,6 +242,41 @@ acc_lim_theta: 1.20
|
||||
# chạy thường trực trên robot thật.
|
||||
runtime_stats_period: 0.0
|
||||
|
||||
# =================================================================================================
|
||||
# Watchdog thành phần (2026-09-11) — thread riêng đọc bảng trạng thái, kết luận "TREO"
|
||||
#
|
||||
# Mỗi thành phần (global planner, local planner, recovery, action, control loop) tự khai nó đang
|
||||
# bận/dừng/rảnh và "nhích" mỗi nhịp. Watchdog chạy trên thread riêng — control thread treo thì
|
||||
# không tự phát hiện được chính nó — và kết luận treo khi một hàng BẬN mà KHÔNG NHÍCH quá ngân sách.
|
||||
# Treo → in LỖI một lần (không tắt được); control loop treo → host đọc navigation_state = LOST và
|
||||
# phải tự đưa cmd_vel về 0. Đây là chẩn đoán, không phải điều khiển: state machine không đổi gì.
|
||||
# =================================================================================================
|
||||
|
||||
# [s] Chu kỳ kiểm của watchdog. 0 = TẮT watchdog (không có thread, không phát hiện treo).
|
||||
watchdog_period: 0.1
|
||||
|
||||
# [s] Trần MỘT lượt makePlan trên thread planner trước khi kết luận global planner TREO. Từ 11/9/2026
|
||||
# khoá này mới có tác dụng (trước đó đọc mà không dùng). PHẢI LỚN HƠN thời gian một lượt hợp lệ dài
|
||||
# nhất: với SBPL là `allocated_time` trong sbpl_global_params.yaml (đã là trần chung cho cả 3 lượt
|
||||
# replan nội bộ). ► Chỉnh: đặt ≈ allocated_time + 1. 0 = không giám sát hàng này.
|
||||
planner_timeout: 15.0
|
||||
|
||||
# [s] Trần MỘT lời gọi computeVelocityCommands của local planner. Priest 30–48 ms, Hybrid < 10 ms;
|
||||
# 0.5 s là "chắc chắn có gì đó hỏng" chứ không phải chậm. 0 = không giám sát.
|
||||
local_planner_call_budget: 0.5
|
||||
|
||||
# [s] Recovery behavior bận mà không nhích (không tick, worker detour không về) quá đây = treo.
|
||||
recovery_stall_budget: 5.0
|
||||
|
||||
# [s] Action handler bận mà không nhích quá đây = treo. 0 = TẮT (mặc định): handler tự timeout
|
||||
# theo thiết bị của nó (tầng 1), `action_patience` là tầng 2 — không cần tầng thứ ba.
|
||||
action_stall_budget: 0.0
|
||||
|
||||
# [s] Control thread không kết thúc được một cycle nào trong quãng này = TREO → host thấy LOST.
|
||||
# 0.5 s = 15 cycle @ 30 Hz. GIẢM (0.2) nếu host cần phản ứng nhanh hơn; không đặt < 3 cycle vì
|
||||
# một lượt detour/solve dài hợp lệ sẽ bị báo nhầm.
|
||||
control_loop_stall_budget: 0.5
|
||||
|
||||
# Bật/tắt toàn bộ recovery. Danh sách behavior và route nằm ở `recovery_behaviors_params.yaml`,
|
||||
# namespace `recovery`.
|
||||
# ► Chỉnh: false = mọi lỗi đi thẳng tới ABORTED, không thử phục hồi. Chỉ dùng khi cô lập lỗi lúc
|
||||
|
||||
190
docs/LIFECYCLE_BEHAVIOUR_MATRIX.md
Normal file
190
docs/LIFECYCLE_BEHAVIOUR_MATRIX.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# Ma trận hành vi pause / resume / cancel theo từng state — bản cũ và sau plan
|
||||
|
||||
Ngày lập: 2026-09-11. Mục đích: đối chiếu hành vi **đang chạy** (bản cũ) với hành vi **sau plan**
|
||||
`PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md`, từng state một, để soát plan có đi đúng hướng.
|
||||
|
||||
## 0. Phiên bản được gọi là "cũ"
|
||||
|
||||
`pnkx_nav_core` commit `bd026b94c8` (2026-09-09, nhánh `dev_recovery_and_manager_mission`) nạp
|
||||
runtime qua submodule `src/Navigations/Packages/move_base2` ở commit **`180c0e1c`**. Đây cũng là
|
||||
con trỏ `rb_ws/pnkx_nav_core` đang giữ. `move_base2` HEAD hiện tại (`7d00c5a`) chỉ khác `180c0e1c`
|
||||
một commit về `rotate`/`relative_yaw` trong `control_loop.cpp` — **state machine và mọi đường
|
||||
lifecycle giống hệt**. Nên "cũ" dưới đây = code `state_machine.cpp` / `control_loop.cpp` /
|
||||
`navigation_server.cpp` trước các sửa pha 1 (chưa commit) của 2026-09-11. Số dòng trích theo bản cũ.
|
||||
|
||||
Runtime này **không có** `move_base` thế hệ 1 nữa (không có state `CLEARING` thật; `CLEARING` chỉ
|
||||
còn là tên host-facing của `RECOVERING`).
|
||||
|
||||
## 1. Lệnh đi vào lõi như thế nào (cả cũ lẫn mới)
|
||||
|
||||
```
|
||||
host (thread bất kỳ) navigation_cancel() / _pause() / _resume()
|
||||
→ NavigationServer::cancel()/pause()/resume() chỉ ghi cờ dưới data_mutex_, TRẢ VỀ NGAY
|
||||
→ control thread, spinOnce() kế: drainLifecycleRequests() (navigation_server.cpp:1010-1047)
|
||||
cancel thắng mọi thứ; pause và resume: lệnh gọi SAU thắng (mỗi lệnh xoá cờ đối nghịch)
|
||||
→ ControlLoop::requestCancel()/requestPause()/requestResume() đặt cờ một-lần
|
||||
→ ControlLoop::step() → StateMachine::update(input) cờ được tiêu thụ đúng một cycle
|
||||
```
|
||||
|
||||
Thứ tự ưu tiên trong một cycle ở mọi state đang chạy (`STATE_MACHINE.md`):
|
||||
`cancel` → `pause` → goal mới (preempt) → plan mới → phản hồi controller/recovery/action → ngưỡng.
|
||||
|
||||
Độ trễ danh nghĩa: ≤ 1 cycle (33 ms @ 30 Hz). **Độ trễ thật = thời gian control thread đang bị
|
||||
chặn** — quan trọng ở mục 3.4 (detour) và 2.2 (local planner solve dài).
|
||||
|
||||
`cancel()` từ host còn gọi `missionLayer().cancel()` → `MissionManager::cancel()` → xoá hàng đợi,
|
||||
state mission `CANCELLED` **ngay tại lời gọi**, không chờ lõi. `pause()`/`resume()` **không** lan
|
||||
xuống mission layer (cố ý, `navigation_server.cpp:1050-1054`).
|
||||
|
||||
Host nhìn thấy (`NavFeedback.navigation_state`, `toHostState` `navigation_server.cpp:266-298`):
|
||||
|
||||
| Lõi | Host |
|
||||
|---|---|
|
||||
| `kIdle` | `PENDING` (hoặc kết quả đã chốt: `SUCCEEDED`/`ABORTED`/`PREEMPTED`) |
|
||||
| `kPlanning` | `PLANNING` |
|
||||
| `kControlling` | `CONTROLLING` |
|
||||
| `kRecovering` | `CLEARING` |
|
||||
| `kExecutingActions` | `ACTIVE` |
|
||||
| `kPaused` | `PAUSED` |
|
||||
| `kCancelling` | `PREEMPTING` |
|
||||
| `kSucceeded` / `kAborted` / `kCancelled` | `SUCCEEDED` / `ABORTED` / `PREEMPTED` (chốt tới yêu cầu kế) |
|
||||
|
||||
---
|
||||
|
||||
## 2. Ma trận theo state
|
||||
|
||||
Quy ước cột: **Cũ** = `180c0e1c`; **Pha 1** = đã code 2026-09-11, chờ build; **Pha 2/3** = trong
|
||||
plan, chưa làm. Ô để trống = không đổi so với cột trái.
|
||||
|
||||
### 2.1 `IDLE` (không có yêu cầu) và các state terminal (`SUCCEEDED`/`ABORTED`/`CANCELLED`)
|
||||
|
||||
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||
|---|---|---|---|
|
||||
| pause | Lõi bỏ qua (không nhánh nào đọc `pause_requested` ở `kIdle`, `state_machine.cpp:423-431`). Host vẫn thấy `PENDING` | | |
|
||||
| resume | Bỏ qua | | |
|
||||
| cancel | Lõi bỏ qua (`CancelWithoutRequestIsIgnored`). **Nhưng** `missionLayer().cancel()` vẫn xoá hàng đợi mission và đặt `MissionState::CANCELLED` | | |
|
||||
| goal mới | Nhận ngay → `PLANNING` (hoặc `EXECUTING_ACTIONS` nếu chỉ có action) | | |
|
||||
|
||||
Terminal chỉ sống một cycle rồi về `IDLE`; lệnh tới trong cycle đó bị bỏ qua như `IDLE`.
|
||||
|
||||
### 2.2 `PLANNING` — global planner đang lập plan trên thread `planner`
|
||||
|
||||
Bối cảnh plugin: `CustomPlanner` fail 100 % với mission qua REST (`makePlan(start, goal)` không hỗ
|
||||
trợ) → rơi xuống backup `SBPLLatticePlanner`; một lượt SBPL tối đa `allocated_time × 3` (10 s × 3
|
||||
với cây config trên máy chạy log). `PlannerRunner::cancelPlan()` chỉ đặt `discard_`
|
||||
(`planner_runner.cpp:466-477`), **không cắt được** `makePlan` đang chạy.
|
||||
|
||||
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||
|---|---|---|---|
|
||||
| **pause** | `stop_planner` → `cancelPlan()` (chỉ discard, SBPL chạy tiếp) → `PAUSED`, `state_before_pause_ = kPlanning` (`:441-446`). Lệnh 0 tức thì. Host: `PAUSED` | | Pha 2: `cancelPlan()` → `preempt()` → SBPL thoát trong vài ms |
|
||||
| **resume** (từ pause ở đây) | → `PLANNING`, `start_planner` (`:948-952`). `startPlan()` bị từ chối vì thread còn bận → control loop dịch thành **`kFailed`** (`control_loop.cpp:1361-1372`) → `max_planning_retries: 0` → `RECOVERING(planning_failed)` ngay → `wait` → `clear` → **`ABORTED`** nếu thread còn bận quá ~11 s (cây dev) / ~27 s (máy log). **Cùng bug với cancel** | `startPlan()` từ chối khi `isPlanning()` → **`kBusy`**: giữ `PLANNING`, không đếm retry, thử lại mỗi cycle, log throttle 5 s. `planner_patience` vẫn là trần | Pha 2: thread đã rảnh từ lúc pause → `startPlan()` OK ngay |
|
||||
| **cancel** | `stop_planner` (discard) → `CANCELLING` (`:435-439`) → cycle kế `robot_stopped` (lệnh = 0) → **`CANCELLED` sau 33 ms** trong khi SBPL còn chạy nhiều giây. Host thấy `PREEMPTED`, gửi goal kế → goal kế `kFailed` → `ABORTED` (log `robot_app.log` 893.444→896.911) | `CANCELLING` giữ tới khi **quiescent**: lệnh/odom = 0 **và** `!isPlanning()` **và** action terminal; trần `settle_timeout` 2 s, quá trần vẫn `CANCELLED` + `log_error`. Host thấy `PREEMPTING` suốt lúc chờ. Goal kế gửi sớm → `kBusy`, không abort | Pha 2: SBPL thoát trong ms → `CANCELLED` sau 1–2 cycle, lần này là thật |
|
||||
| **goal mới** (preempt) | `preemptIfRequested` (`:450`): `stop_planner` (discard), báo `PREEMPTED` cho goal cũ, nhận goal mới → `PLANNING` → `startPlan()` từ chối → `kFailed` → như resume. **`MissionManager::submit()` tự huỷ mission đang chạy** nên host không cần cancel vẫn dính | `kBusy` → chờ thread rảnh rồi lập plan | Pha 2: thread rảnh ngay |
|
||||
|
||||
### 2.3 `CONTROLLING` — local planner phát lệnh mỗi cycle
|
||||
|
||||
Bối cảnh plugin: local planner (`Priest`, `Hybrid`, `HybridDocking`) chạy **đồng bộ** trên control
|
||||
thread mỗi cycle (`computeVelocityCommands`); Priest solve 30–48 ms/cycle 33 ms. Không có
|
||||
`pause()/resume()/reset()` trong `robot_nav_core2::LocalPlanner`. Replan nền (`planner_frequency`)
|
||||
có thể có một lượt đang bay trên thread planner.
|
||||
|
||||
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||
|---|---|---|---|
|
||||
| **pause** | `stop_planner` (discard lượt replan nền nếu có) → `PAUSED`, `state_before_pause_ = kControlling` (`:518-523`). Controller **không được gọi nữa**; arbiter phát **0 tức thì, không ramp** (`velocity_arbiter.cpp:256-266`). Trạng thái nội bộ của plugin (warm-start, slew, latch) đóng băng nguyên trạng. Host: `PAUSED` | | |
|
||||
| **resume** | → `CONTROLLING` với `run_controller` (`:938-942`), **không `setPlan` lại**, không hook nào cho plugin. Đồng hồ `controller_patience`/`oscillation` gieo lại. Plugin bám tiếp với warm-start của lúc robot còn chạy 0.4 m/s; arbiter ramp từ 0 theo `max_accel_x` nên không giật, nhưng plugin có thể tính infeasible vài cycle. Nếu robot bị đẩy đi trong lúc pause thì plan cũ lỗi thời | **(b) đang code:** thêm `apply_plan` → `setPlan(plan cũ)` → Priest reset `core_`, warm, latch, slew theo pose hiện tại (`priest_controller.cpp:534-553`) rồi bám tiếp | **(a) đề xuất, chưa chốt:** resume → `PLANNING`, lập plan **mới** từ pose hiện tại → `setPlan(plan mới)` → `CONTROLLING`. Một lượt planner (0.3–4 s) đổi lấy plan luôn khớp vị trí thật; đồng nhất với resume từ `PLANNING`/`RECOVERING` |
|
||||
| **cancel** | `stop_planner` → `CANCELLING` (`:512-516`) → lệnh 0 tức thì → cycle kế `CANCELLED`. `robot_stopped` lấy từ **lệnh đã phát** (`control_loop.cpp:951`), bánh xe còn lăn theo giảm tốc của driver. Host thấy `PREEMPTED` khi robot còn trượt | `robot_stopped` ưu tiên **odom** (`stopped_measured_*_eps` 0.02): `CANCELLING` giữ tới khi bánh xe đứng thật (trần 2 s). Replan nền còn bay → `!isPlanning()` cũng phải chờ | Pha 2: replan nền bị preempt ngay |
|
||||
| **goal mới** | preempt: `stop_planner`, `PREEMPTED` cho goal cũ, → `PLANNING` goal mới. Nếu replan nền đang bay → `startPlan()` từ chối → `kFailed` → nguy cơ như 2.2 | `kBusy` | Pha 2 |
|
||||
| Local planner đang solve (30–48 ms) khi lệnh tới | Lệnh chờ solve xong (control thread bận) — trễ ≤ 1 cycle thêm | | |
|
||||
|
||||
### 2.4 `RECOVERING` — behavior được tick từ control thread
|
||||
|
||||
Hai họ behavior khác nhau về mức độ dừng được:
|
||||
|
||||
**(i) `wait`, `clear`, `rotate`, `back_up`** — tick ngắn, không chặn control thread.
|
||||
|
||||
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||
|---|---|---|---|
|
||||
| **pause** | `cancel_recovery` → `RecoveryRunner::cancel()` → `RecoveryBehavior::cancel()` **chỉ đặt `cancel_requested_`** (`recovery_behavior.cpp:169-172`); `onCancel()` không bao giờ chạy (tick kế không tới — `recovery_runner.cpp:492`). Nguồn vận tốc `kNone` → arbiter 0 tức thì. Recovery **bị huỷ**, `state_before_pause_ = kPlanning` (`:713-720`) — cố ý: behavior dead-reckon theo thời gian, không được để dở qua quãng dừng | | Pha 2: `cancel()` gọi thêm hook đồng bộ `onCancelRequested()` (no-op với họ này) |
|
||||
| **resume** | → `PLANNING`, lập plan lại từ đầu (`:948-952`). Cursor route giữ nguyên | (nếu planner thread bận vì lượt trước — `kBusy`) | |
|
||||
| **cancel** | `cancel_recovery` → `CANCELLING` (`:707-711`) → cycle kế `CANCELLED`. `rotate` 0.4 rad/s → 0 trong 33 ms (12 rad/s² lệnh), `back_up` 0.1 m/s → 0 (3 m/s²). Doc `onCancel()` hứa "plugin ramp về 0" nhưng không chạy — **chọn giữ 0 tức thì (quyết định A)**, sửa doc ở pha 2 | odom phải về 0 mới `CANCELLED` | |
|
||||
| **goal mới** | preempt: `cancel_recovery` + `stop_planner`, `PREEMPTED` cho goal cũ → `PLANNING` | | |
|
||||
|
||||
**(ii) `detour_path` (`DetourPathRecovery`, sbpl_recovery)** — `makePlan` SBPL **đồng bộ trong
|
||||
`onUpdate`** trên control thread (`detour_path_recovery.cpp:451-501`), `allocated_time 0.4` × tới
|
||||
3 lượt replan = **1.2 s treo/tick**, lặp `attempts_per_run 3`. Route dùng nó: `controlling_failed`,
|
||||
`path_blocked`, `off_path`, `collision` (+ `oscillation` cây dev).
|
||||
|
||||
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||
|---|---|---|---|
|
||||
| **pause / cancel / goal mới** tới trong lúc `makePlan` đang chạy | **Không được xử lý** cho tới khi `makePlan` trả về: `spinOnce()` không chạy → `drainLifecycleRequests()` không chạy → cờ nằm trong `cancel_requested_` tới 1.2 s. Robot đứng yên (kPath → `kNone`, lệnh 0 đã phát trước đó) nên không chạy tự do, nhưng **cancel trễ tới 1.2 s** | (không đổi — pha 1 không chạm) | Pha 2: `makePlan` sang worker thread, `onUpdate` chỉ poll → control thread không bao giờ kẹt; `onCancelRequested()` → `planner_->preempt()` → worker thoát trong ms. Sau đó hành vi như (i) |
|
||||
| sau khi `makePlan` trả về | như (i) | | |
|
||||
|
||||
### 2.5 `EXECUTING_ACTIONS` — action của mission (D8), robot đứng yên
|
||||
|
||||
Bối cảnh: handler tick từ control thread, không block, tự timeout theo `elapsed = now - started_at_`
|
||||
(wall). `ActionHandler` **không có** `pause()/resume()`; `cancel()` trả `void`;
|
||||
`ActionRunner::cancel()` gọi `handler->cancel()` rồi **quên handler ngay** (`action_runner.cpp:159-166`).
|
||||
|
||||
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||
|---|---|---|---|
|
||||
| **pause** | `PAUSED`, **không huỷ action** (`:853-862`) — cố ý: action thiết bị không idempotent. Chỉ ngừng tick. Host: `PAUSED`. **Nhưng** đồng hồ `timeout` của handler vẫn chạy theo wall time | | Pha 3: `ActionHandler::pause(now)` → handler ghi `paused_at_` |
|
||||
| **resume** | → `EXECUTING_ACTIONS`, tick tiếp đúng action đó, **không `start()` lại** (`:943-947`); `action_started_at_` (cho `action_patience`) gieo lại. Handler thấy `elapsed` gồm cả quãng dừng → pause 30 s giữa `detect_pallet` (`timeout 15 s`) → tick đầu `kFailed` → **`ABORTED` thẳng, không qua recovery**, `clear_queue_on_failure` xoá cả order | | Pha 3: `resume(now)` → `started_at_ += now - paused_at_` → không tính thời gian đứng |
|
||||
| **cancel** | `cancel_action` → `ActionRunner::cancel()` → `handler->cancel()` + `active_ = nullptr` → `CANCELLING` (`:847-851`) → cycle kế `CANCELLED`. Với 5 handler hiện có (perception/no-op) là đúng. Handler thiết bị tương lai: `PREEMPTED` báo trong lúc thiết bị còn đang về vị trí an toàn | `action_terminal` control loop truyền `true` — với port hiện tại là giá trị đúng duy nhất (runner đã quên handler). State machine đã sẵn nhánh `tick_action` khi `!action_terminal` | Pha 3: `ActionStatus::kCancelled`; runner giữ handler, tick tới khi terminal; control loop truyền `action_terminal` thật; `CANCELLING` chờ nó |
|
||||
| **goal mới** | preempt: `cancel_action`, `PREEMPTED` cho mission cũ → `PLANNING` mission mới | | |
|
||||
|
||||
### 2.6 `PAUSED`
|
||||
|
||||
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||
|---|---|---|---|
|
||||
| pause (lần nữa) | Bỏ qua | | |
|
||||
| **resume** | Về `state_before_pause_`: `kControlling` → `CONTROLLING` (2.3); `kExecutingActions` → tick tiếp (2.5); `kPlanning` (gồm cả pause từ `RECOVERING`) → `PLANNING` + `start_planner` (`:927-955`). Mọi đồng hồ kiên nhẫn gieo lại | 2.3 (b) hoặc (a) | |
|
||||
| **cancel** | → `CANCELLING` (`:922-925`) → cycle kế `CANCELLED`. Nếu pause tới từ `PLANNING`, thread planner có thể còn bận lượt cũ — `CANCELLED` vẫn báo ngay (nói dối) | `CANCELLING` chờ `!isPlanning()` (test `CancelFromPausedAlsoWaitsForThePlannerThread`) | |
|
||||
| **goal mới** | preempt được từ `PAUSED` (`:917-920`): `stop_planner`/`cancel_recovery`/`cancel_action` theo state trước đó, `PREEMPTED` cho goal cũ → `PLANNING` goal mới (không cần resume). Thread bận → `kFailed` | `kBusy` | |
|
||||
|
||||
### 2.7 `CANCELLING`
|
||||
|
||||
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||
|---|---|---|---|
|
||||
| pause / resume | Bỏ qua (không nhánh nào đọc) | | |
|
||||
| cancel (lần nữa) | Bỏ qua | | |
|
||||
| **goal mới** | **Không preempt** (`kCancelling` không gọi `preemptIfRequested`): yêu cầu nằm chờ ở `pending_request_`, được nhận khi về `IDLE` sau `CANCELLED` | Chờ lâu hơn (tới khi quiescent) rồi mới được nhận → sang `PLANNING` với thread đã rảnh | |
|
||||
| kết thúc | `robot_stopped` (lệnh = 0) → `CANCELLED` sau 1 cycle | quiescent hoặc `settle_timeout` | |
|
||||
|
||||
### 2.8 Profile `docking` / `rotate` / `go_straight`
|
||||
|
||||
Cùng state machine, chỉ khác planner được nạp (`DockPlanner` + `HybridDockingLocalPlanner`,
|
||||
`TwoPointsPlanner`). Mọi ô trên áp dụng nguyên. Riêng resume từ `CONTROLLING` với
|
||||
`HybridDockingLocalPlanner`: chưa đọc `setPlan` của nó — với (a) sẽ là `DockPlanner` lập lại từ
|
||||
pose hiện tại tới marker, với (b) là `setPlan(plan cũ)`; cả hai cần chạy thử.
|
||||
|
||||
---
|
||||
|
||||
## 3. Điểm plan cố ý khác bản cũ — soát ở đây
|
||||
|
||||
| # | Hành vi cũ | Plan đổi thành | Lý do | Pha |
|
||||
|---|---|---|---|---|
|
||||
| 1 | `startPlan()` từ chối = `kFailed` | `kBusy` khi `isPlanning()` | "bận" ≠ "hỏng"; gốc của ABORTED oan | 1 (đã code) |
|
||||
| 2 | `CANCELLED` sau 1 cycle khi lệnh = 0 | `CANCELLING` chờ quiescent (odom = 0, planner idle, action terminal), trần `settle_timeout` | host đọc `PREEMPTED` là "xong" | 1 (đã code) |
|
||||
| 3 | `robot_stopped` từ lệnh | từ odom, lùi về lệnh khi không có odom; `eps = 0` = tắt | bánh xe còn lăn sau lệnh 0 | 1 (đã code) |
|
||||
| 4 | resume từ `CONTROLLING` không `setPlan` | (b) `setPlan(plan cũ)` — đã code; **hoặc (a) về `PLANNING` lập plan mới — chờ chốt** | plugin reset warm-start; (a) còn khớp pose thật sau pause dài | 1 |
|
||||
| 5 | `cancelPlan()` chỉ discard | `Preemptable::preempt()` → SBPL thoát trong ms | "dừng ở đó" thật | 2 |
|
||||
| 6 | `onCancel()` recovery là dead code; detour treo control thread | `onCancelRequested()` đồng bộ; detour worker thread + preempt | cancel/pause tới được trong lúc detour | 2 |
|
||||
| 7 | Cancel = 0 tức thì, không ramp | **giữ nguyên** (quyết định A); sửa doc `onCancel()` | đúng nghĩa "dừng hết luôn"; giảm tốc là việc của driver | 2 (doc) |
|
||||
| 8 | Action: pause không báo handler; cancel không handshake | `pause/resume(now)` + `kCancelled` | pause dài → ABORTED oan; thiết bị tương lai | 3 |
|
||||
| 9 | Plugin `.so` cũ nạp vào runtime mới → crash vtable | ABI guard `_abi` symbol, registry từ chối | đổi vtable ở 2 và 3 | 2, 3 |
|
||||
| 10 | `MissionState::CANCELLED` ngay tại lời gọi | **giữ nguyên**; host nhìn `NavigationState::PREEMPTING` (đã có sẵn) | C API không lộ `MissionState`; không thêm enum | 1 |
|
||||
|
||||
Không đổi: pause huỷ recovery (2.4), pause đóng băng action (2.5), cancel từ mọi state về
|
||||
`CANCELLING`, preempt từ mọi state đang chạy trừ `CANCELLING`, thứ tự ưu tiên cancel > pause > goal
|
||||
mới, `pause`/`resume` không lan xuống mission layer, lệnh 0 tức thì.
|
||||
|
||||
## 4. Yêu cầu của bạn đối chiếu
|
||||
|
||||
| Yêu cầu | Trạng thái (cập nhật 2026-09-12) |
|
||||
|---|---|
|
||||
| Đang planning / setPlan / recovery / action → cancel hoặc pause **dừng ở đó** | setPlan, recovery (i), action: có sẵn. Planning: **pha 2 xong, đo runtime** — cancel/pause @ PLANNING → `preempted after` +0.03 ms, `CANCELLED`/`PAUSED` trong 1–2 tick (R1, R2, R4). Detour: code + unit test xong, **runtime chưa chạy** |
|
||||
| Pause rồi resume → **set plan lại và gọi planning lại** | Resume từ `PLANNING`: gọi planning lại — đo R2 (`PLANNING: resume planning` +27 ms, SBPL chạy lại). Resume từ `CONTROLLING`: **đã chốt (b)** `setPlan(plan cũ)` — đo R3 (`setPlan: 1423 poses`, Priest reseed từ vận tốc đo, không giật) |
|
||||
| Local planner chạy theo chu kỳ → chỉ chạy tiếp | Đo R3: pause → lệnh 0 tức thì, `PAUSED` sau khi odom < 0.02 m/s (538 ms từ 0.115 m/s); resume → `setPlan` + chạy tiếp cùng cycle |
|
||||
| Báo đúng: `CANCELLED`/`PAUSED` chỉ khi mọi thứ thật sự im | Đo R1–R5: mọi `CANCELLED`/`PAUSED` đều kèm `planner=idle controller=idle recovery=idle` + robot đứng theo odom; R5 cancel lúc còn `PAUSING` (bánh chưa dừng) → `CANCELLING: cancelled while pausing` → `CANCELLED` chỉ khi đứng (+250 ms) |
|
||||
|
||||
Bảng số đo đầy đủ: `PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md` mục 6, "Kết quả runtime đã chạy".
|
||||
885
docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md
Normal file
885
docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md
Normal file
@@ -0,0 +1,885 @@
|
||||
# Kế hoạch: lifecycle thống nhất — cancel / pause / resume / preempt phải dừng thật ở mọi tầng
|
||||
|
||||
Ngày lập: 2026-09-11. Thay thế bản `PLAN_CANCEL_PREEMPT.md` (chỉ xét global planner) bằng bản
|
||||
audit toàn bộ nguồn có thể gây cùng triệu chứng.
|
||||
|
||||
Trạng thái (2026-09-12): **pha 1a, 1b, 2, 3, 4 đã code, build, unit test (13 binary, 528 test,
|
||||
0 fail) và chạy thử runtime kịch bản cancel-giữa-SBPL trên máy dev 2 lần (09:52, 09:57): cancel →
|
||||
`preempted after` +0.03 ms, `CANCELLED` +50 ms, mission kế `CONTROLLING` +0.95 s, không
|
||||
`settle timeout`, không `planner thread still busy`.** Pha 0 (config tuning) **pending** theo yêu
|
||||
cầu người dùng. Quyết định đã chốt: 4.1 mixin (B); 4.8 resume = `setPlan` lại (b); 4.5
|
||||
`PREEMPTING` có sẵn; 4.7 hook + worker; luật 5 không ramp (A); pha 3 sau 1–2; ABI guard pha 2+3.
|
||||
|
||||
Runtime đã chạy thêm 2026-09-12 21:11–21:21 (mục 6, bảng R1–R5): pause/resume @ PLANNING và
|
||||
@ CONTROLLING, pause→cancel @ PLANNING và @ CONTROLLING, submit-đè không cancel — tất cả đúng
|
||||
contract, không ABORTED/RECOVERING/settle timeout.
|
||||
|
||||
Còn lại: (1) pha 0; (2) runtime chưa chạy: cancel giữa detour, pause 30 s giữa action, treo cưỡng
|
||||
bức; (3) commit 8 repo + `nav_test_harness`;
|
||||
(4) `rb_ws` chưa đụng; (5) mục 8 chưa xác nhận: driver có clamp giảm tốc không, `ClearCostmap`
|
||||
khoá gì, `HybridDockingLocalPlanner` với `setPlan` giữa đường. Điều kiện máy chạy: **phải gỡ
|
||||
`ros-noetic-sbpl` + `ros-noetic-sbpl-lattice-planner`** (soname `libsbpl.so` trùng, apt thắng qua
|
||||
`LD_LIBRARY_PATH`) rồi rebuild `sbpl_lattice_planner`; boot log phải có
|
||||
`libsbpl abort flag: supported`.
|
||||
|
||||
Repo đã chạm (mỗi gói repo riêng, chưa commit): `Test/move_base2`, `Test/sbpl`,
|
||||
`Test/sbpl_lattice_planner`, `Test/recovery_core`, `Test/sbpl_recovery`, `Test/action_core`,
|
||||
`Test/dock_pattern_action`, `Test/nav_test_harness` (1 yaml), `pnkx_nav_core` (`robot_nav_core`
|
||||
header mới, `move_base_core` header mới, c_api, config). Chưa đưa gì sang `rb_ws`.
|
||||
|
||||
Nguồn bằng chứng: `~/Downloads/robot_app.log` (host C++ thuần, máy dev khác) + đọc source
|
||||
`move_base2`, `mission_adapters`, `sbpl_lattice_planner`, `sbpl`, `sbpl_recovery`, `action_core`,
|
||||
`dock_pattern_action`, `priest_local_planner`, `robot_nav_core`, `robot_nav_core2`.
|
||||
|
||||
---
|
||||
|
||||
## 1. Triệu chứng gốc và cơ chế
|
||||
|
||||
Mission 3 bị cancel lúc SBPL đang chạy → nav core báo `CANCELLED` ngay → host dequeue mission 4 →
|
||||
mission 4 `ABORTED` sau 3.2 s dù chưa lập plan lần nào. Cả log chỉ có một `ABORTED`, mission 5 thoát
|
||||
được vì `wait` recovery 3 s dài hơn phần còn lại của lượt SBPL cũ.
|
||||
|
||||
```
|
||||
890.118 SBPL bắt đầu (mission 3)
|
||||
893.444 cancel mission 3 → discard_=true, SBPL VẪN CHẠY
|
||||
893.677 mission 4 → PLANNING → startPlan()=false → kFailed → RECOVERING 'wait'
|
||||
894.556 SBPL solve #1 xong (4438 ms) → "initial segment curved" → solve #2 chạy tiếp
|
||||
896.744 'wait' xong → PLANNING → kFailed → RECOVERING 'clear'
|
||||
896.911 PLANNING → kFailed → ABORTED (route planning_failed cursor=2/2)
|
||||
898.537 "Plan has 756 points" — plan CỦA MISSION 3 mới xong, running_=false
|
||||
```
|
||||
|
||||
Ba tầng đều có phần:
|
||||
|
||||
1. **Plugin không có đường preempt.** `BaseGlobalPlanner`, `SBPLPlanner`, `ARAPlanner` không có cờ
|
||||
dừng; điều kiện thoát vòng lặp duy nhất là `clock() - TimeStarted < MaxNumofSecs`
|
||||
(`Test/sbpl/src/planners/araplanner.cpp:372-375`, `:935-938`).
|
||||
2. **Runtime coi "bận" là "hỏng".** `PlannerRunner::startPlan()` trả `false` khi
|
||||
`pending_ || running_` (`src/runners/planner_runner.cpp:419-422`); `control_loop.cpp:1361-1372`
|
||||
dịch thành `PlannerFeedback::kFailed`; `max_planning_retries: 0` → cạn retry ngay cycle đầu.
|
||||
3. **Ba lớp báo "đã huỷ" ở ba thời điểm khác nhau, không lớp nào chờ lớp dưới.**
|
||||
`MissionManager::cancel()` → `CANCELLED` tức thì, đồng bộ (`mission_manager.cpp:256-267`);
|
||||
state machine `CANCELLING → CANCELLED` sau một cycle vì `robot_stopped` lấy từ lệnh đã phát
|
||||
(`control_loop.cpp:951 arbiter_.stopped()`); thread planner còn chiếm nhiều giây nữa.
|
||||
|
||||
---
|
||||
|
||||
## 2. Bảng audit: mọi nguồn có thể gây cùng triệu chứng
|
||||
|
||||
Mức: **P0** = đã gây lỗi thật trong log / chắc chắn gây abort oan; **P1** = gây abort oan hoặc dừng
|
||||
không an toàn trong tình huống dễ gặp; **P2** = latency hoặc lệch hành vi, chưa gây abort; **P3** =
|
||||
vệ sinh.
|
||||
|
||||
### 2.1 Global planner (thread `planner`)
|
||||
|
||||
| Lệnh | Hiện trạng | Bằng chứng | Mức |
|
||||
|---|---|---|---|
|
||||
| cancel khi PLANNING | Chỉ đặt `discard_`; `makePlan` chạy tới hết ngân sách. Mission kế → `kFailed` → recovery → abort | `planner_runner.cpp:466-477`, `:562`; log 893.444–898.537 | **P0** |
|
||||
| pause khi PLANNING → resume | `stop_planner` lúc pause (`state_machine.cpp:441-445`) = cùng đường `cancelPlan()`; resume → `PLANNING` → `startPlan()` → bận → `kFailed`. **Cùng bug, chưa có log nhưng chắc chắn** | `state_machine.cpp:441-445`, `:927-955` | **P0** |
|
||||
| goal mới chen ngang khi PLANNING (preempt) | `preemptIfRequested` → `stop_planner` → nhận goal mới → `PLANNING` → bận → `kFailed` | `state_machine.cpp:364-389` | **P0** |
|
||||
| `submit()` ở mission layer | `MissionManager::submit()` tự huỷ mission đang chạy (`requestCancelOfCurrentLocked`) → preempt ở trên. Host **không cần** gọi cancel vẫn dính | `mission_manager.cpp:121` | **P0** |
|
||||
| Một `makePlan` = tối đa 3 lượt ARA* full | `:454` luôn; `:464` nếu lượt 1 fail + `free_start_heading`; `:558` nếu đoạn đầu cong. `set_start()` đặt `bReinitializeSearchStateSpace` → search lại từ 0. Mỗi lượt cấp lại nguyên `allocated_time` → trần 30 s | `sbpl_lattice_planner.cpp:454,464,558`; `araplanner.cpp:665-675`; log 4438 ms + 3981 ms | **P1** |
|
||||
| Costmap mutex giữ suốt `makePlan` | Global costmap update loop bị chặn 7.9 s; global costmap không cập nhật trong lúc planner chạy | `planner_runner.cpp:516-520`; log dòng 509 | **P1** |
|
||||
| `initial_epsilon: 1.0` + `set_search_mode(false)` | ARA* mất tính anytime — không có nghiệm trung gian để trả sớm. 4.4 s thay vì ~0.3 s | `sbpl_lattice_planner.cpp:446-447`; config | **P2** |
|
||||
| `clock()` là CPU time cả process | Priest 4 thread + costmap + xloc → ngân sách 10 s cháy nhanh hơn wall, không dự đoán được | `araplanner.cpp:373` | **P2** |
|
||||
| shutdown | `~PlannerRunner` → `thread_.join()` chờ `makePlan` xong, tối đa 30 s | `planner_runner.cpp:96-101` | **P2** |
|
||||
| Đổi sang backup planner | `swapPlanner` + `initialize()` SBPL trên **control thread**: 182 ms một lần (build lattice 1331×844) | log 880.662→880.844 | **P3** |
|
||||
|
||||
### 2.2 Local planner (đồng bộ trên thread `control`)
|
||||
|
||||
| Lệnh | Hiện trạng | Bằng chứng | Mức |
|
||||
|---|---|---|---|
|
||||
| cancel | Không gọi controller nữa, arbiter phát 0. Không có `reset()` nhưng `setPlan` của mission kế reset toàn bộ (Priest: `core_.reset()`, warm, latch, streak…) | `priest_controller.cpp:534-553` | OK |
|
||||
| pause → resume từ CONTROLLING | Resume vào thẳng `run_controller`, **không** `setPlan` lại, không hook nào cho plugin. Warm-start trajectory / `last_a_*` / slew state của Priest là của trước khi dừng (robot đang 0.4 m/s), giờ robot đứng yên. Arbiter ramp từ 0 nên không giật, nhưng plugin có thể tính infeasible vài cycle | `state_machine.cpp:937-941`; `LocalPlanner` interface không có pause/resume | **P1** (cần chạy thử) |
|
||||
| Solve vượt ngân sách | Priest 30–48 ms / cycle 33 ms → cancel/pause trễ 1–2 cycle | log 903–939 `solve took … (limit 30.00 ms)` | **P2** |
|
||||
| `controller_patience: 0.0333 s` | = 1 cycle. Một lượt solve hỏng là vào `RECOVERING(controlling_failed)` → `detour_path`. Ngoài phạm vi lifecycle nhưng nhân đôi mọi vấn đề ở 2.3 | log dòng 205 | **P2** (tuning) |
|
||||
|
||||
### 2.3 Recovery (tick từ thread `control`)
|
||||
|
||||
| Lệnh | Hiện trạng | Bằng chứng | Mức |
|
||||
|---|---|---|---|
|
||||
| cancel | `RecoveryRunner::cancel()` → `active_->cancel()` chỉ đặt `cancel_requested_` (`recovery_behavior.cpp:169-172`, **không virtual**). `onCancel()` chỉ chạy ở `update()` tick kế (`:150-155`) — tick đó **không bao giờ tới** vì CANCELLING ép `tick_recovery=false` (`recovery_runner.cpp:492` đã ghi nhận). `onCancel()` của MỌI behavior hiện là dead code. Velocity behaviors vẫn dừng đúng nhờ arbiter `kNone`; chỉ behavior có việc chạy dài (detour) mới hỏng | `recovery_behavior.cpp:150-177`; `recovery_runner.cpp:462-468, 492` | OK cho wait/clear/rotate/back_up; **P0** cho detour |
|
||||
| pause | Recovery bị huỷ (dead-reckon theo thời gian), resume → `PLANNING`. Đúng thiết kế | `state_machine.cpp:713-719` | OK |
|
||||
| `DetourPathRecovery` — `makePlan` **đồng bộ trong `onUpdate`** | Mỗi tick chạy một lượt SBPL trên control thread: `allocated_time 0.4` × tới 3 lượt replan (`free_start_heading: true` ở instance detour, `recovery_behaviors_params.yaml:282`) = **1.2 s treo control thread một tick**, × `attempts_per_run 3`. Trong lúc treo `spinOnce()` không chạy → `drainLifecycleRequests()` không chạy → cancel/pause của host nằm trong `cancel_requested_` tới 1.2 s; arbiter không tick. Robot đứng yên (kPath → kNone) nên không chạy tự do. Route dùng detour: `controlling_failed`, `path_blocked`, `off_path`, `collision` (+ `oscillation` ở cây runtime) — với `controller_patience` 1 cycle, một lượt solve hỏng là vào detour. **Chưa có log tái hiện — kết luận từ code** | `detour_path_recovery.cpp:451-501`; `recovery_behaviors_params.yaml:65-79, 243-282` | **P0** |
|
||||
| SBPL instance của detour không preempt được | Cùng `.so`, cùng lỗ hổng 2.1 | — | P1 (fix chung) |
|
||||
|
||||
### 2.4 Action (tick từ thread `control`)
|
||||
|
||||
| Lệnh | Hiện trạng | Bằng chứng | Mức |
|
||||
|---|---|---|---|
|
||||
| cancel | `cancel()` đồng bộ, state machine ngừng tick. Handler perception (`FrameSampler`, `DockPattern`) không có gì phải dừng → OK. Handler điều khiển thiết bị (nâng kệ, sạc — chưa có) **không có handshake** `cancelling → cancelled`: `ActionTick::Status` chỉ có Running/Succeeded/Failed | `action_port.h:20-46`, `action_handler.h:83` | **P2** (thiết kế) |
|
||||
| pause → resume | **Không có hook pause/resume** trong `ActionHandler`. Handler đo `elapsed = now - started_at_` (wall). Pause 30 s giữa một lượt dò `timeout` 10 s → resume → tick đầu `elapsed >= timeout_` → `kFailed` → **`ABORTED` thẳng, không qua recovery** | `frame_sampler_action_handler.cpp:341,370,405`; `dock_pattern_action_handler.cpp:253,276`; state machine chỉ gieo lại `action_started_at_` của chính nó (`state_machine.cpp:948`) | **P1** |
|
||||
| preempt | = cancel | — | như trên |
|
||||
|
||||
### 2.5 State machine / ControlLoop
|
||||
|
||||
| Vấn đề | Hiện trạng | Bằng chứng | Mức |
|
||||
|---|---|---|---|
|
||||
| `startPlan()==false` → `kFailed` | "Bận" và "hỏng" cùng một mã | `control_loop.cpp:1361-1372` | **P0** (gốc) |
|
||||
| `CANCELLING` không chờ planner idle | Kết thúc ngay khi `robot_stopped` | `state_machine.cpp:962-972` | **P0** (gốc) |
|
||||
| `robot_stopped` từ lệnh, không từ odom | `CANCELLED` báo ra khi cmd=0, robot còn đang giảm tốc. Doc đã ghi nhận là việc chờ nối dây | `control_loop.cpp:951`; `STATE_MACHINE.md` mục "Vì sao CANCELLING luôn kết thúc" | **P1** |
|
||||
| `max_planning_retries: 0` | Khuếch đại: một `kFailed` là vào recovery, `planner_patience 25 s` không bao giờ được chạy | `state_machine.cpp:475-476`; config | **P1** (config) |
|
||||
| `PlannerFeedback::kBusy` có trong enum nhưng không ai đặt | — | `core/state_machine.h:30` | P3 |
|
||||
|
||||
### 2.6 NavigationServer / host API
|
||||
|
||||
| Vấn đề | Hiện trạng | Bằng chứng | Mức |
|
||||
|---|---|---|---|
|
||||
| cancel/pause/resume bất đồng bộ | Ghi cờ dưới `data_mutex_`, xử lý ở `spinOnce()` kế. Đúng thiết kế; **latency = thời gian control thread đang treo** (xem 2.3) | `navigation_server.cpp:974-1047` | OK (phụ thuộc 2.3) |
|
||||
| Host thấy `PREEMPTING → PREEMPTED` trong 1 cycle | Vocabulary đúng (`toHostState`: kCancelling→PREEMPTING, kCancelled→PREEMPTED), nhưng thời điểm sai vì 2.5 | `navigation_server.cpp:289-296` | theo 2.5 |
|
||||
| `is_ready` không phản ánh planner thread còn bận | Host không có cách nào biết | `navigation_server.cpp:139` | P2 |
|
||||
|
||||
### 2.7 Mission layer (`mission_adapters`)
|
||||
|
||||
| Vấn đề | Hiện trạng | Bằng chứng | Mức |
|
||||
|---|---|---|---|
|
||||
| `MissionManager::cancel()` → `CANCELLED` tức thì | Đồng bộ, không chờ nav core. Host app đọc state này để dequeue → gửi mission kế trong lúc nav core chưa dừng. **Đây là chỗ host bị "lừa"** | `mission_manager.cpp:256-267`; log 893.444625 (mission) vs 893.477 (nav CANCELLED) vs 898.537 (planner rảnh) | **P0** |
|
||||
| `submit()` tự preempt mission đang chạy | Không cần cancel trước — gửi mission mới là đủ để dính 2.1 | `mission_manager.cpp:121` | P0 (cùng fix) |
|
||||
| `pause()` mission layer không nối với nav | Cố ý, có lý do ghi ở `navigation_server.cpp:1050-1054`. Giữ nguyên | — | OK |
|
||||
| Outcome trễ của mission đã huỷ | `onNavigationDone` bỏ nếu `state_ != RUNNING`. Đúng | `mission_manager.cpp:203-210` | OK |
|
||||
|
||||
### 2.8 Config / vệ sinh liên quan
|
||||
|
||||
| Vấn đề | Chỗ | Mức |
|
||||
|---|---|---|
|
||||
| `primitive_filename: /home/duongtd/rl_ws/mir_robot/...` hard-code đường dẫn máy dev trong cây config nav core | `pnkx_nav_core/config/recovery_behaviors_params.yaml:~250` | P3 |
|
||||
| `free_start_heading: true` ở cả planner chính lẫn detour — nhân 3 thời gian ở cả hai chỗ | `sbpl_global_params.yaml:12`, `recovery_behaviors_params.yaml:282` | P2 |
|
||||
| `THREADING.md` còn ghi "chưa có thread planner" | `docs/THREADING.md` mục "Trạng thái hiện tại" | P3 (docs) |
|
||||
|
||||
---
|
||||
|
||||
## 3. Contract lifecycle (nguyên tắc thiết kế)
|
||||
|
||||
Bốn luật, áp cho mọi port và mọi plugin. Viết vào `docs/STATE_MACHINE.md` và `docs/THREADING.md`
|
||||
khi thi công.
|
||||
|
||||
1. **Lệnh lifecycle không bao giờ chờ plugin.** `cancel/pause/resume/preempt` từ host phải được
|
||||
state machine xử lý ở cycle kế tiếp. Plugin nào chạy dài hơn một cycle phải (a) chạy trên thread
|
||||
riêng và (b) có cờ preempt được kiểm trong vòng lặp tính toán.
|
||||
2. **"Bận" khác "hỏng".** Port trả "không khởi động được vì còn lượt cũ" là `kBusy`, không phải
|
||||
`kFailed`. Ngân sách kiên nhẫn (`planner_patience`) là hàng rào cho "bận quá lâu"; ngân sách
|
||||
retry (`max_planning_retries`) chỉ đếm thất bại thật.
|
||||
3. **Trạng thái báo ra ngoài phản ánh quiescence thật — cho CẢ cancel lẫn pause.** (Mở rộng
|
||||
2026-09-11 theo yêu cầu "dừng tất cả mới được coi là hoàn thành, pause cũng vậy".)
|
||||
`CANCELLED`/`PREEMPTED` và `PAUSED` chỉ được báo khi **mọi thành phần** đã im: thread global
|
||||
planner idle, recovery idle, action đã xác nhận dừng/tạm dừng, vận tốc **đo được** ≈ 0. "Im"
|
||||
không suy từ state machine mà đọc từ **bảng trạng thái thành phần** (4.10) — nơi mỗi thread/
|
||||
plugin tự khai nó đang làm gì. Có trần thời gian (`settle_timeout`); quá trần thì vẫn kết thúc
|
||||
nhưng log **lỗi** (không tắt được) và thành phần chưa im bị đánh dấu **treo**.
|
||||
4. **Pause đóng băng đồng hồ của plugin, không chỉ của state machine.** Handler nào có timeout
|
||||
riêng phải nhận `pause(now)/resume(now)` để dịch mốc.
|
||||
5. **Lệnh lifecycle = lệnh 0 tức thì, không ramp.** (Quyết định 2026-09-11, phương án A.) Ở mọi
|
||||
state phải dừng (CANCELLING/PAUSED/IDLE…) `VelocityArbiter` phát `zeroTwist()` ngay cycle đó
|
||||
(`velocity_arbiter.cpp:256-266`, ba lý do ghi tại chỗ). Không plugin nào — controller hay
|
||||
recovery — được ramp về 0 khi bị huỷ; giảm tốc theo động học là việc của driver bánh xe.
|
||||
Hệ quả về gia tốc lệnh: Priest 0.5 m/s → 0 trong 33 ms = 15 m/s²; `back_up` 0.1 m/s → 0 =
|
||||
3 m/s²; `rotate` 0.4 rad/s → 0 = 12 rad/s². Chấp nhận có chủ đích. Phương án B
|
||||
(`kStopping` + ramp trong arbiter) bị loại vì vi phạm lý do 1 và 2 của arbiter.
|
||||
|
||||
---
|
||||
|
||||
## 4. Thiết kế API
|
||||
|
||||
### 4.0 Pha 0 — chỉ config, không code, không build: thu hẹp cửa sổ lỗi trong lúc chờ pha 1–3
|
||||
|
||||
Pha 0 **không sửa bug**. Nó làm lượt SBPL ngắn lại và làm "planner bận" không leo thang ngay,
|
||||
để xác suất trúng cửa sổ lỗi giảm trong lúc pha 1–3 chưa xong. Chỉ đụng **cây dev**
|
||||
(`Test/move_base2/config/runtime/`, `pnkx_nav_core/config/`); không đụng `<package>/cfg/` và
|
||||
`rb_ws` (đó là giá trị đã tune trên robot thật — chỉ mang comment/khoá sang, không mang số).
|
||||
|
||||
| # | Khoá | File (cây dev) | Hiện | Đề xuất | Tác dụng | Rủi ro |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 1 | `max_planning_retries` | `move_base2/config/runtime/move_base_common_params.yaml:121`, `pnkx_nav_core/config/move_base_common_params.yaml:29` | 0 | 2 | Một `kFailed` không leo thang ngay; planner bận 2 cycle nữa vẫn được thử lại. `planner_patience` (25 s trên máy log, 2 s cây dev) vẫn là trần | Không có — chỉ trì hoãn recovery 2 cycle (66 ms) |
|
||||
| 2 | `allocated_time` | `sbpl_global_params.yaml:5` (cả hai cây, cả bản `mprim/`) | 10.0 | 3.0 | Cửa sổ "thread bận sau cancel" từ tối đa 30 s (3 lượt) xuống 9 s. Sau pha 2 (chia ngân sách) đây là trần thật của một `makePlan` | Goal xa/khó có thể không tìm được đường trong 3 s → `Solution not found` → recovery. Phải chạy thử với goal xa nhất của map |
|
||||
| 3 | `initial_epsilon` | cùng file, `:6` | 1.0 | 3.0 | Trả lại tính anytime cho ARA*: nghiệm đầu về sau ~0.3 s thay vì 4.4 s (log 396), phần ngân sách còn lại dùng để tinh chỉnh về eps=1.0 | Path có thể kém tối ưu hơn nếu hết giờ trước khi về eps=1.0. **Phải nhìn path thật**, đặc biệt đoạn cua hẹp |
|
||||
| 4 | `primitive_filename` | `pnkx_nav_core/config/sbpl_global_params.yaml:15`, `recovery_behaviors_params.yaml:297` | `/home/duongtd/rl_ws/mir_robot/mir_navigation/mprim/unicycle_highcost_5cm.mprim` — **ngoài workspace, đường dẫn máy cá nhân** | trỏ vào bản in-tree `pnkx_nav_core/config/mprim/unicycle_highcost_5cm.mprim` | Cây `pnkx_nav_core/config` chạy được trên máy khác | Không. Sửa gốc (resolve đường dẫn tương đối theo `PNKX_NAV_CORE_CONFIG_DIR`) là code trong `sbpl_lattice_planner:114` — gộp vào pha 2 |
|
||||
|
||||
**Phát hiện thêm khi rà pha 0 — comment YAML sai nghĩa, phải sửa ở mọi cây (kể cả `rb_ws`, hỏi trước):**
|
||||
|
||||
`pnkx_nav_core/config/move_base_common_params.yaml:29`:
|
||||
```yaml
|
||||
max_planning_retries: 0 # ... 0 = không giới hạn số lần
|
||||
```
|
||||
Code nói ngược lại (`state_machine.cpp:475-476`, `:122-123`): **0 = hỏng một lượt là leo thang
|
||||
ngay; -1 mới là không giới hạn**; default C++ là -1. Bản `move_base2/config/runtime:117-121` ghi
|
||||
đúng. Người vận hành chép từ cây `pnkx_nav_core/config` sẽ đặt 0 vì tin là "không giới hạn" và
|
||||
nhận đúng hành vi ngược lại — nhiều khả năng là chuyện đã xảy ra trên máy chạy log
|
||||
(`max_planning_retries : 0` ở dòng 211). Đây là lỗi tài liệu, sửa cùng pha 0.
|
||||
|
||||
Verify pha 0 (người dùng chạy, không cần build): chạy lại kịch bản mục 6 với config mới; kỳ vọng
|
||||
`[sbpl_lattice_planner] solved: eps=… (init 3.00) … ms of 3.00 s allowed` với thời gian < 1 s cho
|
||||
goal mission 3; và cancel + gửi ngay vẫn **có thể** abort (pha 0 không sửa gốc) nhưng cửa sổ ≤ 9 s
|
||||
thay vì 30 s.
|
||||
|
||||
### 4.1 Global planner — `robot_nav_core::Preemptable` (mixin, không đổi vtable `BaseGlobalPlanner`) — **đã chốt**
|
||||
|
||||
`pnkx_nav_core/src/Navigations/Cores/robot_nav_core/include/robot_nav_core/preemptable.h`:
|
||||
|
||||
```cpp
|
||||
namespace robot_nav_core {
|
||||
/// Plugin chạy dài (global planner, detour planner) implement thêm interface này để runtime cắt
|
||||
/// được một lượt makePlan đang chạy. preempt() gọi từ thread KHÁC thread đang chạy makePlan;
|
||||
/// hiện thực phải là atomic, không lock, không alloc.
|
||||
class Preemptable {
|
||||
public:
|
||||
virtual ~Preemptable() = default;
|
||||
virtual void preempt() = 0;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Lý do chọn mixin thay vì thêm virtual vào `BaseGlobalPlanner`: đổi vtable base là **mọi** plugin
|
||||
global planner phải rebuild (`CustomPlanner`, `TwoPointsPlanner`, `DockPlanner`, detour); thiếu một
|
||||
cái là crash lúc `dlopen`. Mixin + `dynamic_cast` chỉ chạm plugin nào chọn hỗ trợ.
|
||||
|
||||
### 4.2 `sbpl` — cờ abort trong `SBPLPlanner`
|
||||
|
||||
`Test/sbpl/src/include/sbpl/planners/planner.h`, class `SBPLPlanner`:
|
||||
|
||||
```cpp
|
||||
public:
|
||||
void set_abort_flag(const std::atomic<bool>* flag) { abort_flag_ = flag; }
|
||||
protected:
|
||||
bool aborted() const
|
||||
{ return abort_flag_ != nullptr && abort_flag_->load(std::memory_order_relaxed); }
|
||||
const std::atomic<bool>* abort_flag_ = nullptr;
|
||||
```
|
||||
|
||||
`araplanner.cpp`: thêm `&& !aborted()` vào `while` ở `:372` và `:935`; sau `Search()` nếu
|
||||
`aborted()` thì trả 0 (không ghi solution). Tách commit riêng nếu đổi `clock()` sang
|
||||
`std::chrono::steady_clock`.
|
||||
|
||||
### 4.3 `sbpl_lattice_planner`
|
||||
|
||||
- `SBPLLatticePlanner : public BaseGlobalPlanner, public robot_nav_core::Preemptable`.
|
||||
- `std::atomic<bool> preempt_{false}`; `preempt()` đặt `true`.
|
||||
- Đầu `makePlan`: `preempt_ = false; planner_->set_abort_flag(&preempt_);`.
|
||||
- Kiểm `preempt_` trước lượt 2 (`:464`) và lượt 3 (`:558`); đã preempt → `return false` + log
|
||||
`"[sbpl_lattice_planner] preempted after %.0f ms"`.
|
||||
- **Chia ngân sách chung**: `deadline = plan_started + allocated_time_`; lượt 2/3 chỉ chạy nếu
|
||||
còn ≥ `kMinReplanBudget = 0.5 s`, và truyền phần còn lại chứ không truyền nguyên
|
||||
`allocated_time_`. Trần một `makePlan` về đúng `allocated_time`.
|
||||
- Instance `SBPLDetourPlanner` dùng cùng class → tự có.
|
||||
|
||||
### 4.4 `move_base2` — PlannerRunner / ControlLoop / StateMachine
|
||||
|
||||
**PlannerRunner** (`src/runners/planner_runner.cpp`):
|
||||
|
||||
```cpp
|
||||
void PlannerRunner::cancelPlan()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (pending_ || running_)
|
||||
{
|
||||
discard_ = true;
|
||||
if (auto* p = dynamic_cast<robot_nav_core::Preemptable*>(active_)) { p->preempt(); }
|
||||
}
|
||||
has_result_ = false;
|
||||
handoff_.clear();
|
||||
}
|
||||
```
|
||||
|
||||
Lifetime: `active_` chỉ bị thay ở `swapPlanner`, và instance cũ được GIỮ (`:187`), nên con trỏ
|
||||
còn hợp lệ suốt lượt `makePlan` đang chạy. Cờ atomic sống trong plugin instance.
|
||||
|
||||
**Sửa sau log 2026-09-11 22:44 (`/tmp/abort.log`):** thứ tự thật khi host gửi mission kế trong
|
||||
lúc CANCELLING là `swapPlanner('CustomPlanner')` (áp profile mission 2, 1491.004) **trước**
|
||||
`accept_request → cancelPlan` (1491.204), trong khi thread vẫn ở trong `makePlan` của
|
||||
SBPL (về lúc 1493.059). `dynamic_cast<Preemptable*>(active_)` khi đó trỏ vào instance MỚI, rảnh —
|
||||
lượt đang chạy không bị cắt. Đã đổi: thread ghi `running_planner_` lúc chụp yêu cầu; mọi đường cắt
|
||||
(`cancelPlan`, `swapPlanner` khi `running_`, destructor) preempt qua `running_planner_`.
|
||||
`swapPlanner` khi job còn `pending_ && !running_` thì rút job, như `cancelPlan`. Lượt đó chỉ thoát
|
||||
được nhờ cancel ở 1489.104 (trước swap) đã preempt đúng instance.
|
||||
|
||||
**ControlLoop** (`src/control_loop.cpp:1361-1372`):
|
||||
|
||||
```cpp
|
||||
else if (output.start_planner)
|
||||
{
|
||||
planner_feedback_ = deps_.planner->isPlanning() ? PlannerFeedback::kBusy
|
||||
: PlannerFeedback::kFailed;
|
||||
if (planner_feedback_ == PlannerFeedback::kBusy)
|
||||
robot::log_warning_throttle(5.0, "[move_base2] planner still busy with a cancelled attempt; "
|
||||
"waiting (planner_patience %.1f s).\n", ...);
|
||||
}
|
||||
```
|
||||
|
||||
Thêm vào `StateMachineInput`: `bool planner_busy` (= `deps_.planner->isPlanning()`),
|
||||
`bool action_terminal` (= action port đã trả Succeeded/Failed/Cancelled sau cancel, hoặc không
|
||||
có action). `robot_stopped` đổi nguồn:
|
||||
|
||||
```cpp
|
||||
// Ưu tiên vận tốc ĐO ĐƯỢC; chưa có odom thì lùi về lệnh đã phát như cũ.
|
||||
robot_geometry_msgs::Twist measured;
|
||||
input.robot_stopped = deps_.controller->measuredVelocity(measured)
|
||||
? (std::fabs(measured.linear.x) < config_.state_machine.stopped_measured_linear_eps &&
|
||||
std::fabs(measured.angular.z) < config_.state_machine.stopped_measured_angular_eps)
|
||||
: arbiter_.stopped();
|
||||
```
|
||||
|
||||
**StateMachine** `kCancelling` (`src/state_machine.cpp:962-972`):
|
||||
|
||||
```cpp
|
||||
const bool quiescent = in.robot_stopped && !in.planner_busy && in.action_terminal;
|
||||
const double settling = (in.now - cancelling_since_).toSec();
|
||||
if (quiescent)
|
||||
finish(kCancelled, kCancelled, in.now, "robot stopped, planner idle", out);
|
||||
else if (config_.cancel_settle_timeout > 0.0 && settling > config_.cancel_settle_timeout)
|
||||
{
|
||||
// LỖI, không tắt được: có một cấu hình/plugin khiến cancel không dừng được thật.
|
||||
robot::log_error("[move_base2] cancel settle timeout %.1f s: planner_busy=%d action_terminal=%d "
|
||||
"robot_stopped=%d — finishing CANCELLED anyway.\n", ...);
|
||||
finish(kCancelled, kCancelled, in.now, "cancel settle timeout", out);
|
||||
}
|
||||
```
|
||||
|
||||
Trong `kCancelling`, `tick_action = true` chừng nào `!action_terminal` (để handler thiết bị có
|
||||
cơ hội báo `kCancelled`). Vận tốc vẫn `kNone` (bất biến 3 không đổi).
|
||||
|
||||
**Resume từ CONTROLLING** (`state_machine.cpp:937-941`): đặt thêm `out.apply_plan = true`.
|
||||
ControlLoop gọi `setPlan(latest_plan_)` lại → Priest/Hybrid reset warm-start theo pose hiện tại.
|
||||
Không cần thêm hook vào `LocalPlanner`. Phải chạy thử với cả `HybridDockingLocalPlanner`.
|
||||
|
||||
**Pause/resume tới action** (xem 4.6): `out.pause_action` khi pause từ `kExecutingActions`,
|
||||
`out.resume_action` khi resume về đó.
|
||||
|
||||
**Config mới** (struct `StateMachineConfig`, đọc qua `robot::NodeHandle`, validate, in ở dòng tóm
|
||||
tắt lúc boot, comment tiếng Việt trong YAML):
|
||||
|
||||
| Khoá | Đơn vị | Mặc định | Ý nghĩa |
|
||||
|---|---|---|---|
|
||||
| `cancel_settle_timeout` | [s] | 2.0 | Trần chờ quiescence ở CANCELLING. 0 = tắt (hành vi cũ) |
|
||||
| `stopped_measured_linear_eps` | [m/s] | 0.02 | Ngưỡng coi robot đã dừng theo odom. Đặt 0 = luôn dùng lệnh đã phát |
|
||||
| `stopped_measured_angular_eps` | [rad/s] | 0.02 | Như trên, trục quay |
|
||||
|
||||
Đồng bộ schema + comment (không đồng bộ giá trị) sang `Test/move_base2/config/runtime/`,
|
||||
`pnkx_nav_core/config/`, và (hỏi trước) `rb_ws/pnkx_nav_core/config/runtime/`.
|
||||
|
||||
### 4.5 Host nhìn thấy "đang huỷ" — dùng `State::PREEMPTING` đã có, không thêm enum, không đổi `MissionState`
|
||||
|
||||
**Quyết định (2026-09-11): làm ở tầng `NavFeedback.navigation_state`, không ở `mission_adapters`.**
|
||||
|
||||
`robot::move_base_core::State` (`move_base_core/navigation.h:38-54`) và bản C
|
||||
`NavigationState` (`nav_c_api.h:36-52`) đã có sẵn cặp `PREEMPTING` / `PREEMPTED`, và
|
||||
`NavigationServer::toHostState` đã map `kCancelling → PREEMPTING`, `kCancelled → PREEMPTED`
|
||||
(`navigation_server.cpp:289-296`). Vocabulary đúng; chỉ **thời điểm** sai vì `kCancelling` kết thúc
|
||||
sau một cycle. Sửa `kCancelling` chờ quiescence (4.4) là host tự thấy đúng — **không thêm giá trị
|
||||
enum, không đổi ABI, không đổi chuỗi `toString`**.
|
||||
|
||||
Contract host sau khi sửa:
|
||||
|
||||
```
|
||||
navigation_cancel()
|
||||
cycle kế → PREEMPTING (kCancelling)
|
||||
giữ PREEMPTING chừng nào: planner thread còn bận
|
||||
|| action chưa trả terminal
|
||||
|| |v_odom| > stopped_measured_*_eps
|
||||
→ PREEMPTED khi quiescent, hoặc khi quá cancel_settle_timeout (kèm log_error)
|
||||
→ PREEMPTED được chốt (latched_result_) suốt lúc idle, tới khi có yêu cầu mới
|
||||
```
|
||||
|
||||
Luật cho host (ghi vào `nav_c_api_2.h` mục "What changed" số 4 và `NAV_C_API_2_GUIDE.md`):
|
||||
sau `navigation_cancel()`, poll `navigation_get_state()`; chỉ gửi yêu cầu kế khi state
|
||||
**không còn** `PREEMPTING`. Không branch theo `feed_back_str`.
|
||||
|
||||
Vì sao không dùng `RECALLING`/`RECALLED` (cancel lúc chưa ACTIVE, theo actionlib): host phải
|
||||
branch hai giá trị cho cùng một việc "đợi dừng xong". Giữ một cặp `PREEMPTING/PREEMPTED` cho mọi
|
||||
state bị huỷ.
|
||||
|
||||
`mission_adapters::MissionState` **giữ nguyên**: `CANCELLED` ở đó nghĩa là "hàng đợi đã xoá, đã
|
||||
xin huỷ chặng" — là trạng thái của queue, không phải của robot. C API không lộ `MissionState`
|
||||
ra host, nên không có gì để sửa ở đó. Nếu sau này host ROS (`amr_control`) đọc `MissionState` để
|
||||
quyết định gửi tiếp thì mới xét thêm `MissionState::CANCELLING`.
|
||||
|
||||
Không cần chặn ở `pumpPendingRequest()` nữa: host gửi sớm (không tuân luật trên) thì chặng mới
|
||||
vào `PLANNING` với `kBusy` (4.4) và tự chờ planner rảnh — host thấy `PLANNING`, đúng sự thật.
|
||||
Một cơ chế, không hai.
|
||||
|
||||
### 4.6 `action_core::ActionHandler` — pause/resume + handshake cancel — **đã chốt, làm sau pha 1 và 2**
|
||||
|
||||
Hai lỗi riêng, một API sửa chung.
|
||||
|
||||
**Lỗi 1 — pause/resume làm action tự timeout → ABORTED oan.** Handler đo
|
||||
`elapsed = now - started_at_` (`frame_sampler_action_handler.cpp:341`,
|
||||
`dock_pattern_action_handler.cpp:253`, `wait_action_handler.cpp:118`). State machine lúc pause chỉ
|
||||
ngừng gọi `update()`; lúc resume gieo lại `action_started_at_` của chính nó, không báo handler.
|
||||
Ví dụ `detect_pallet`, `timeout: 15.0` (`action_handlers_params.yaml:127`):
|
||||
|
||||
```
|
||||
t=0 start handler started_at_ = 0
|
||||
t=5 pause update() ngừng
|
||||
t=25 resume SM action_started_at_ = 25; handler started_at_ VẪN = 0
|
||||
t=25 update(now=25) elapsed = 25 ≥ 15 → kFailed → ABORTED (action không qua recovery)
|
||||
→ MissionManager FAILED, clear_queue_on_failure → xoá cả order
|
||||
```
|
||||
|
||||
`wait` (`duration: 2.0`) sai chiều ngược: pause 10 s → resume → `elapsed 12 ≥ 2` → `kSucceeded`
|
||||
tức thì dù chưa chờ đủ.
|
||||
|
||||
**Lỗi 2 — cancel không có handshake.** `cancel()` trả `void`; sau đó CANCELLING không tick nữa;
|
||||
`ActionStatus` không có giá trị "đã dừng xong". 5 handler hiện có đều perception/no-op nên chưa
|
||||
lộ; handler thiết bị (nâng kệ, sạc) sẽ báo `PREEMPTED` trong lúc càng còn chạy — vi phạm luật 3.
|
||||
|
||||
**API** — `action_core/include/action_core/action_handler.h`, thêm sau `cancel()`:
|
||||
|
||||
```cpp
|
||||
/// Tạm dừng. KHÔNG dừng thiết bị (pause = đóng băng, không huỷ). Handler có timeout riêng phải
|
||||
/// ghi mốc để resume() dịch started_at_. Default no-op.
|
||||
virtual void pause(const robot::Time& /*now*/) {}
|
||||
/// Tiếp tục. Cộng quãng dừng vào mốc timeout để thời gian đứng không bị tính. Default no-op.
|
||||
virtual void resume(const robot::Time& /*now*/) {}
|
||||
```
|
||||
|
||||
`ActionStatus` thêm `kCancelled`. Contract mới cho `cancel()`: sau `cancel()`, caller **tiếp tục
|
||||
tick `update()`** tới khi status terminal. Handler perception trả `kCancelled` ở tick kế; handler
|
||||
thiết bị trả `kRunning` trong lúc về vị trí an toàn, rồi `kCancelled`.
|
||||
|
||||
Thân handler, mỗi cái 4 dòng (`FrameSampler`, `DockPattern`, `Wait`; `Noop`/`LogReport` chỉ cần
|
||||
trả `kCancelled`):
|
||||
|
||||
```cpp
|
||||
void pause(const robot::Time& now) override { paused_at_ = now; }
|
||||
void resume(const robot::Time& now) override { started_at_ += (now - paused_at_); }
|
||||
```
|
||||
|
||||
**Nối dây `move_base2`:** `ActionPort` thêm `pause()/resume()`; `ActionTick::Status` thêm
|
||||
`kCancelled`; `ActionRunner` forward + map. `StateMachineOutput` thêm `pause_action`,
|
||||
`resume_action`: pause từ `kExecutingActions` → `pause_action`; resume về đó → `resume_action`.
|
||||
`kCancelling`: `tick_action = true` chừng nào `!in.action_terminal` (input đã có ở 4.4). Vận tốc
|
||||
vẫn `kNone`.
|
||||
|
||||
**Vì sao không mixin như 4.1:** 5/5 handler đều cần (3 có đồng hồ, 2 no-op cũng phải trả
|
||||
`kCancelled`), và `kCancelled` vào enum dùng chung — mixin không tránh được rebuild. Thêm thẳng
|
||||
vào `ActionHandler` + ABI guard (4.9).
|
||||
|
||||
### 4.7 `sbpl_recovery::DetourPathRecovery` — không treo control thread, cancel cắt được
|
||||
|
||||
**Sửa so với bản đầu:** "onCancel() gọi preempt()" KHÔNG chạy được — `onCancel()` chỉ chạy ở tick
|
||||
kế, tick đó không tới sau CANCELLING; và `cancel()` chạy trên control thread, thread đang kẹt
|
||||
trong `makePlan`. Cơ chế đúng gồm ba phần, làm cùng nhau:
|
||||
|
||||
1. **`recovery_core` — hook đồng bộ khi xin huỷ** (`recovery_behavior.h`):
|
||||
```cpp
|
||||
void cancel() { cancel_requested_ = true; onCancelRequested(); }
|
||||
/// Gọi NGAY trong cancel(), trước tick kế, trên thread gọi cancel(). Plugin có việc chạy dài
|
||||
/// (thread riêng, planner) cắt nó ở đây. Default no-op. Không được phát vận tốc ở đây —
|
||||
/// onCancel() vẫn là chỗ ramp về 0 nếu tick kế có tới.
|
||||
virtual void onCancelRequested() {}
|
||||
```
|
||||
Thêm virtual vào `RecoveryBehavior` → 5 plugin recovery (`wait`, `clear`, `rotate`, `back_up`
|
||||
trong `recovery_core/plugins`, `detour_path` trong `sbpl_recovery`) rebuild cùng lúc. Đều
|
||||
in-tree.
|
||||
|
||||
Cùng commit: **sửa doc `onCancel()`** (`recovery_behavior.h:158-165`). Câu hiện tại — "plugin
|
||||
họ velocity nên override để ramp về 0 thay vì nhảy bậc" — sai hai lần: (a) với state machine
|
||||
hiện tại `onCancel()` không bao giờ được gọi (CANCELLING ép `tick_recovery=false`); (b) kể cả
|
||||
được gọi, arbiter đè `zeroTwist()` ở mọi state phải dừng (luật 5, mục 3). Viết lại: "Chỉ chạy
|
||||
khi bên gọi còn tick sau `cancel()` — move_base2 không làm vậy. Không dùng để ramp: lệnh
|
||||
lifecycle là 0 tức thì theo thiết kế của `VelocityArbiter`. Dọn state nội bộ ở
|
||||
`onCancelRequested()`." `rotate`/`back_up` giữ override hiện có (chỉ `current_speed_ = 0`),
|
||||
không thêm ramp.
|
||||
|
||||
2. **`DetourPathRecovery` — `makePlan` sang worker thread.** `onStart` khởi động worker;
|
||||
`onUpdate` chỉ poll kết quả (`kRunning` khi chưa có), nộp path qua tick như hiện tại.
|
||||
`onCancelRequested()` → `planner_->preempt()` (mixin 4.1, cùng class `SBPLLatticePlanner`) →
|
||||
worker thoát trong vài ms; kết quả (nếu có) bị vứt. `onStart` phải join/discard worker cũ nếu
|
||||
còn sống. Hợp lệ với `THREADING.md`: behavior họ `kPath` **không phát vận tốc**, bất biến
|
||||
"chỉ control thread phát cmd_vel" không bị chạm. Ghi vào README `recovery_core`: `kVelocity`
|
||||
không được có thread; `kPath` được, kết quả bàn giao qua tick.
|
||||
|
||||
3. **Chia ngân sách 4.3** áp cho instance detour: trần một attempt về đúng `allocated_time 0.4 s`.
|
||||
|
||||
Đường thay thế nếu chưa làm worker thread: preempt từ **host thread** trong
|
||||
`NavigationServer::cancel()/pause()` qua `std::atomic<robot_nav_core::Preemptable*>` giữ trong
|
||||
`RecoveryRunner` (đặt ở `start()`, xoá khi behavior kết thúc). Chạy được nhưng host thread chọc
|
||||
vào runner — trái với "chỉ control thread chạm runner". Không khuyến nghị.
|
||||
|
||||
### 4.8 Local planner — không đổi interface — **đã chốt**; resume từ CONTROLLING = `setPlan(plan cũ)` (b) — **đã chốt**
|
||||
|
||||
Không thêm `pause/resume` vào `robot_nav_core2::LocalPlanner`: plugin chạy đồng bộ theo cycle,
|
||||
không gọi = dừng, gọi lại = chạy. Hai cách resume từ CONTROLLING còn treo (2026-09-11):
|
||||
|
||||
- (b) — đang code ở pha 1: `apply_plan` → `setPlan(plan cũ)` → plugin reset warm-start theo pose
|
||||
hiện tại → bám tiếp. 0 s, nhưng plan cũ có thể lỗi thời nếu robot bị đẩy đi trong lúc pause.
|
||||
- (a): resume → `PLANNING` → global planner lập plan mới từ pose hiện tại → `setPlan(plan mới)`.
|
||||
Một lượt planner (0.3–4 s), plan luôn khớp vị trí thật, đồng nhất với resume từ
|
||||
`PLANNING`/`RECOVERING`.
|
||||
|
||||
**Đã chốt (b)** (người dùng, 2026-09-11). Đổi sang (a) sau này là một nhánh ở `state_machine.cpp`
|
||||
+ 2 test, không ảnh hưởng phần còn lại.
|
||||
|
||||
### 4.9 ABI version guard cho plugin `.so` — **đã chốt, gộp vào pha 2 (recovery) và pha 3 (action)**
|
||||
|
||||
Vì sao cần: `ActionHandler` và `RecoveryBehavior` nạp qua `boost::dll::import_alias` = `dlsym` +
|
||||
`reinterpret_cast` (`action_registry.cpp:117`; header tự cảnh báo ở `action_handler.h:33-37`).
|
||||
Thêm virtual là đổi layout vtable: runtime mới gọi slot 7 (`pause`) trên plugin build với header cũ
|
||||
(vtable kết thúc ở slot 6) → nhảy vào byte rác → SIGSEGV, đúng lúc người vận hành bấm pause. Trên
|
||||
máy dev `catkin_make` rebuild hết cùng lúc nên không lộ; trên robot thật, cập nhật thiếu một
|
||||
`.so` (ví dụ giữ `libdock_pattern_action_handler.so` cũ) là chạy bình thường tới lần pause đầu.
|
||||
|
||||
Cơ chế, giống nhau cho hai gói:
|
||||
|
||||
```cpp
|
||||
// action_core/include/action_core/action_abi.h (tương tự recovery_core/recovery_abi.h)
|
||||
namespace action_core {
|
||||
/// Tăng mỗi lần đổi chữ ký/vtable của ActionHandler hoặc layout struct qua biên .so.
|
||||
constexpr int kActionCoreAbiVersion = 2; // 1 = trước pha 3
|
||||
}
|
||||
```
|
||||
|
||||
Mỗi plugin export thêm một symbol qua macro của gói (đặt cạnh `BOOST_DLL_ALIAS` factory):
|
||||
|
||||
```cpp
|
||||
ACTION_CORE_EXPORT_HANDLER(create_frame_sampler, FrameSamplerActionHandler)
|
||||
// mở rộng thành: BOOST_DLL_ALIAS(create_frame_sampler, FrameSamplerActionHandler)
|
||||
// BOOST_DLL_ALIAS(action_core::abiVersion, FrameSamplerActionHandler_abi)
|
||||
```
|
||||
|
||||
`ActionRegistry` / `RecoveryRegistry` khi nạp: tra symbol `<Name>_abi` **trước** factory; thiếu
|
||||
symbol hoặc giá trị ≠ hằng của runtime → `log_error` đường dẫn `.so` + version hai bên + từ chối
|
||||
nạp instance đó, không crash. Đây là log lỗi, không có khoá tắt.
|
||||
|
||||
Rebuild cùng lần: 5 handler (`libaction_core_{frame_sampler,wait,log_report,noop}_action_handler.so`,
|
||||
`libdock_pattern_action_handler.so`) ở pha 3; 5 recovery (`wait`, `clear`, `rotate`, `back_up` trong
|
||||
`recovery_core/plugins`, `detour_path` trong `sbpl_recovery`) ở pha 2.
|
||||
|
||||
Test: registry test nạp một `.so` giả export version cũ → bị từ chối, log đúng tên file; nạp thiếu
|
||||
symbol `_abi` → bị từ chối.
|
||||
|
||||
---
|
||||
|
||||
### 4.10 Bảng trạng thái thành phần + `PAUSING` + watchdog treo — **mới (2026-09-11), đáp ứng "báo đúng phải biết từng phần đang làm gì"**
|
||||
|
||||
#### Vấn đề
|
||||
|
||||
Pha 1 hỏi quiescence bằng ba câu rời: `PlannerPort::isPlanning()`, `robot_stopped`, `action_terminal`
|
||||
(hard-code `true`). Thiếu: recovery (detour worker sau pha 2), costmap update threads, chính control
|
||||
thread. Và **không có cách nào biết một thành phần đang "bận" hay đã "treo"** — `isPlanning()` trả
|
||||
true cả khi SBPL còn 0.3 s nữa xong lẫn khi plugin deadlock vĩnh viễn. `PAUSED` cũng đang nói dối
|
||||
như `CANCELLED` cũ: vào sau 1 cycle trong khi thread planner còn chạy lượt đã huỷ.
|
||||
|
||||
Yêu cầu: **một nguồn sự thật duy nhất** về từng thành phần, do chính thành phần đó ghi, để
|
||||
(1) CANCELLING/PAUSING quyết định "đã im chưa" từ đó, (2) phát hiện treo và báo lên host, kể cả khi
|
||||
control thread là thứ bị treo.
|
||||
|
||||
#### Thiết kế — `ComponentStatusBoard` (`include/move_base2/core/component_status.h`)
|
||||
|
||||
```cpp
|
||||
namespace move_base2 {
|
||||
|
||||
enum class Component : std::uint8_t {
|
||||
kGlobalPlanner, // PlannerRunner thread
|
||||
kLocalPlanner, // lời gọi computeVelocityCommands trên control thread
|
||||
kRecovery, // behavior đang chạy (+ worker detour sau pha 2)
|
||||
kAction, // handler đang chạy
|
||||
kCostmapGlobal, // map-update thread của global costmap
|
||||
kCostmapLocal, // map-update thread của local costmap
|
||||
kControlLoop, // chính control thread (step())
|
||||
kCount
|
||||
};
|
||||
|
||||
enum class Phase : std::uint8_t { kIdle, kBusy, kStopping, kPaused, kHung };
|
||||
|
||||
struct ComponentStatus { // mọi field atomic, ghi relaxed, không lock, không alloc
|
||||
std::atomic<Phase> phase{Phase::kIdle};
|
||||
std::atomic<std::int64_t> phase_since_ns{0}; // mốc vào phase hiện tại (steady clock)
|
||||
std::atomic<std::int64_t> last_progress_ns{0}; // heartbeat: lần cuối thành phần "nhích"
|
||||
std::atomic<std::uint64_t> progress_ticks{0}; // đếm nhịp (expand ARA*, cycle, tick…)
|
||||
};
|
||||
|
||||
class ComponentStatusBoard {
|
||||
public:
|
||||
void enter(Component c, Phase p, std::int64_t now_ns); // owner gọi khi đổi phase
|
||||
void progress(Component c, std::int64_t now_ns); // owner gọi mỗi nhịp, rẻ
|
||||
ComponentStatus& at(Component c);
|
||||
const ComponentStatus& at(Component c) const;
|
||||
bool allIdle(std::initializer_list<Component> cs) const;
|
||||
bool anyHung() const;
|
||||
private:
|
||||
std::array<ComponentStatus, static_cast<std::size_t>(Component::kCount)> rows_;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Ai ghi cái gì (owner = thread của thành phần; mọi lời ghi đều đang có sẵn điểm móc):
|
||||
|
||||
| Component | `kBusy` từ | `kStopping` từ | `kIdle` từ | `progress()` |
|
||||
|---|---|---|---|---|
|
||||
| `kGlobalPlanner` | `PlannerRunner::threadBody` trước `makePlan` | `cancelPlan()` khi `running_` (đã gọi `preempt()`) | sau `makePlan` trả về | plugin `Preemptable` gọi qua callback mỗi N expand (pha 2); không có thì heartbeat = chính `kBusy` |
|
||||
| `kLocalPlanner` | `ControllerRunner::computeVelocityCommands` vào | — | ra | ra |
|
||||
| `kRecovery` | `RecoveryRunner::start()` | `cancel()` | tick trả terminal / detour worker xong | mỗi `update()`; worker detour mỗi expand |
|
||||
| `kAction` | `ActionRunner::start()` | `cancel()` (pha 3: tới khi `kCancelled`) | tick terminal | mỗi `update()` |
|
||||
| `kCostmapGlobal/Local` | — | — | — | `Costmap2DROBOT::mapUpdateLoop` mỗi vòng (móc qua `CostmapStatusPort`, không sửa gói costmap: đọc `getLastUpdateStamp()` có sẵn/thêm) |
|
||||
| `kControlLoop` | — | — | — | cuối mỗi `step()` |
|
||||
|
||||
`kPaused` chỉ dùng cho `kAction` (pha 3: handler xác nhận `pause()`).
|
||||
|
||||
#### Quiescence — một định nghĩa, hai chỗ dùng
|
||||
|
||||
```cpp
|
||||
// ControlLoop, đầu mỗi cycle, thay cho input.planner_busy / action_terminal của pha 1
|
||||
input.components_quiescent =
|
||||
board_.allIdle({Component::kGlobalPlanner, Component::kRecovery}) &&
|
||||
(board_.at(Component::kAction).phase == Phase::kIdle ||
|
||||
board_.at(Component::kAction).phase == Phase::kPaused /* chỉ khi PAUSING */) &&
|
||||
robotStopped();
|
||||
```
|
||||
|
||||
`kLocalPlanner` không cần hỏi: cùng thread với state machine, không thể đang chạy lúc này.
|
||||
`kCostmap*` không thuộc quiescence (costmap không "chạy hộ" robot) — chỉ thuộc watchdog.
|
||||
|
||||
State machine:
|
||||
|
||||
- `kCancelling` (pha 1 đã có) chờ `components_quiescent`, trần `settle_timeout`.
|
||||
- **`kPausing` — state mới** giữa state đang chạy và `kPaused`. Vào `kPausing` = làm đúng những gì
|
||||
pha 1 làm khi pause (stop_planner / cancel_recovery / pause_action); sang `kPaused` khi
|
||||
`components_quiescent`; quá `settle_timeout` → `kPaused` + cờ `settle_timed_out` (bên gọi log
|
||||
lỗi). `cancel` và goal mới trong `kPausing` xử lý như trong `kPaused`. Host map:
|
||||
`kPausing → PAUSED`? **Không** — nói thật: giữ tên host của state trước (`PLANNING`/
|
||||
`CONTROLLING`/`CLEARING`/`ACTIVE`) và `feed_back_str = "pausing: waiting for <component>"`;
|
||||
`PAUSED` chỉ khi đã im. `resume` tới trong `kPausing` → về thẳng state trước (chưa kịp dừng gì).
|
||||
- Khoá YAML `cancel_settle_timeout` của pha 1 **đổi tên** thành `settle_timeout` (dùng cho cả hai)
|
||||
trước khi commit pha 1 — chưa build, chưa deploy, đổi rẻ. `stopped_measured_*_eps` giữ.
|
||||
|
||||
#### Watchdog treo
|
||||
|
||||
Phát hiện "bận quá lâu" phải làm ở thread **khác** thành phần bị nghi — control thread treo thì
|
||||
không tự phát hiện được. Thêm `Watchdog` (thread riêng trong `NavigationServer`, 10 Hz, chỉ đọc
|
||||
atomics, không lock, không đụng runner):
|
||||
|
||||
| Component | Điều kiện treo | Ngân sách từ đâu |
|
||||
|---|---|---|
|
||||
| `kGlobalPlanner` | `kBusy`/`kStopping` và `now - last_progress > budget` | `planner_timeout` (khoá đang **chết** — đọc, in, không ai dùng: `move_base2_config.cpp:148,528`) — hồi sinh với nghĩa "trần một lượt makePlan"; phải > `allocated_time × 3` của SBPL |
|
||||
| `kLocalPlanner` | `kBusy` quá `local_planner_call_budget` (mới, mặc định 3 × chu kỳ) | mới, [s] |
|
||||
| `kRecovery` | `kBusy`/`kStopping` quá `timeout` của behavior + dư | recovery_core đã có `timeout` |
|
||||
| `kAction` | quá `action_patience` nếu bật, không thì handler tự lo | có sẵn |
|
||||
| `kCostmapGlobal/Local` | `now - last_progress > N × (1/update_frequency)` | N = 3, khoá mới `costmap_stall_factor` |
|
||||
| `kControlLoop` | `now - last_progress > control_loop_stall_budget` (mới, mặc định 5 × chu kỳ = 167 ms @ 30 Hz) | mới |
|
||||
|
||||
Khi phát hiện: `enter(c, kHung)` + **`log_error` đúng một lần ở sườn** (không khoá tắt), kèm phase
|
||||
trước, thời gian bận, tên thành phần. Hết treo (progress quay lại) → về phase thật + `log_warning`
|
||||
"recovered after X s".
|
||||
|
||||
Hậu quả điều khiển của treo:
|
||||
|
||||
| Treo | Lõi làm gì | Host thấy |
|
||||
|---|---|---|
|
||||
| `kControlLoop` | không làm gì được từ bên trong. Watchdog ghi cờ atomic `control_loop_hung_`; `getFeedback()` (host thread) đọc cờ → `navigation_state = LOST` (giá trị có sẵn trong `move_base_core::State`, chưa ai dùng), `feed_back_str` nêu thời gian. Host phải tự zero cmd_vel — contract `nav_c_api_2.h` mục 6 đã bắt host kiểm stamp | `LOST` |
|
||||
| `kGlobalPlanner` | CANCELLING/PAUSING → `settle_timeout` kết thúc như cũ; PLANNING → `planner_patience`. Thêm: sau pha 2, treo dù đã `preempt()` = plugin không tuân cancel → `is_ready` giữ true nhưng `feed_back_str` nêu | state thật + `feed_back_str` |
|
||||
| `kRecovery` / `kAction` | như trên qua `settle_timeout`; ngoài lifecycle, `timeout`/`action_patience` có sẵn | như trên |
|
||||
| `kCostmap*` | `costmap_stale` đã chặn vận tốc; thêm log_error sườn | `feed_back_str` |
|
||||
|
||||
#### Lộ ra host — `nav_c_api_2.h` (pha 4)
|
||||
|
||||
```c
|
||||
typedef struct { uint8_t phase; double seconds_in_phase; double seconds_since_progress; } NavComponentStatus;
|
||||
/* n = NAV_COMPONENT_COUNT; trả số phần tử ghi. Đọc atomics, gọi được từ thread bất kỳ. */
|
||||
size_t navigation_get_component_status(NavigationHandle h, NavComponentStatus* out, size_t n);
|
||||
```
|
||||
|
||||
Cùng cơ chế cho `move_base_main` (in bảng theo chu kỳ) và host ROS (`amr_control` publish
|
||||
diagnostics). `RuntimeStats` (`io/runtime_stats.h`) **không** dùng cho việc này: nó đo thời gian
|
||||
trung bình/max để profiling, tắt mặc định, có mutex — không phải bảng liveness.
|
||||
|
||||
#### Chi phí
|
||||
|
||||
Mỗi `enter()`/`progress()` = 1–2 store relaxed. Watchdog 10 Hz đọc `7 × 4` atomics. Không alloc,
|
||||
không lock trên đường control. Bảng sống trong `NavigationServer`, runner giữ con trỏ non-owning
|
||||
(cùng vòng đời với `RuntimeStats`).
|
||||
|
||||
#### Test
|
||||
|
||||
| Test | Kịch bản |
|
||||
|---|---|
|
||||
| `component_status_test` (mới) | `enter/progress/allIdle/anyHung` thuần; thread-safety bằng 2 thread ghi/đọc 10⁶ lần không crash |
|
||||
| `state_machine_test` | `PAUSING` giữ khi `!components_quiescent`; sang `PAUSED` khi im; quá `settle_timeout` → `PAUSED` + cờ; `resume` trong `PAUSING` → về state trước; `cancel` trong `PAUSING` → `CANCELLING` |
|
||||
| `walking_skeleton_test` | pause lúc planner bận → state `kPausing`, host name giữ `PLANNING`, `feed_back_str` nêu; planner rảnh → `PAUSED` |
|
||||
| `navigation_server_test` | fake planner treo (latency 10⁶) + `planner_timeout` 0.2 s → watchdog đánh `kHung`, log_error một lần, `navigation_get_component_status` trả `hung`; fake control loop stall (không gọi spinOnce 1 s) → `getFeedback()` = `LOST` |
|
||||
| `planner_runner_test` | phase `kBusy` trong lúc makePlan, `kStopping` sau cancel, `kIdle` sau khi trả về |
|
||||
|
||||
## 5. Phân pha và thứ tự commit
|
||||
|
||||
| Pha | Nội dung | Repo | Đổi ABI plugin? | Đổi host API? |
|
||||
|---|---|---|---|---|
|
||||
| **0** | Chỉ config, không code (4.0): `max_planning_retries 0→2`, `allocated_time 10→3`, `initial_epsilon 1.0→3.0` (chạy thử), `primitive_filename` trỏ bản in-tree; sửa comment sai "0 = không giới hạn" | `move_base2/config/runtime`, `pnkx_nav_core/config` (comment sai: mọi cây, hỏi trước với `rb_ws`) | không | không |
|
||||
| **1a** | `kBusy`; CANCELLING chờ quiescence + `cancel_settle_timeout`; `robot_stopped` theo odom; resume → `apply_plan` (b, đã chốt); 3 khoá YAML mới; cập nhật contract `PREEMPTING` trong `nav_c_api_2.h` + `NAV_C_API_2_GUIDE.md`. **Xong, đã verify runtime** | `move_base2`, `pnkx_nav_core` (docs c_api) | không | không (chỉ siết nghĩa `PREEMPTING`) |
|
||||
| **1b** | `ComponentStatusBoard` (4.10) thay cho `planner_busy`/`action_terminal` rời; state `kPausing` + `PAUSED` chỉ khi im; đổi tên `cancel_settle_timeout` → `settle_timeout`; host giữ tên state cũ + `feed_back_str` lúc pausing. Làm **trước khi commit 1a** để không đổi tên khoá hai lần | `move_base2` | không | `PAUSED` tới muộn hơn (≤ `settle_timeout`) |
|
||||
| **2** | Preempt xuyên tầng: `Preemptable` → `sbpl` abort flag → `sbpl_lattice_planner` (preempt + chia ngân sách) → `PlannerRunner::cancelPlan`; `recovery_core::onCancelRequested()` + sửa doc `onCancel()`; `DetourPathRecovery` worker thread + preempt (4.7); **ABI guard `recovery_core` (4.9)** | `pnkx_nav_core`, `sbpl`, `sbpl_lattice_planner`, `move_base2`, `recovery_core`, `sbpl_recovery` | global planner: chỉ plugin chọn implement; **recovery: có** — `RecoveryBehavior` thêm virtual, 5 plugin rebuild, registry từ chối `.so` lệch version | không |
|
||||
| **3** | Action pause/resume + `kCancelled`; state machine `pause_action/resume_action`, tick action trong CANCELLING; **ABI guard `action_core` (4.9)**. **Làm sau khi pha 1 và 2 đã xong và verify** | `action_core`, `dock_pattern_action`, `move_base2` | **có** (`ActionHandler` thêm virtual — 5 handler rebuild, registry từ chối `.so` lệch version) | không |
|
||||
| **4** | Watchdog thread (4.10): treo theo `planner_timeout` (hồi sinh khoá chết), `local_planner_call_budget`, `control_loop_stall_budget`, `costmap_stall_factor`; `kHung` + log_error sườn; control thread treo → host `LOST`; C API `navigation_get_component_status()` | `move_base2`, `pnkx_nav_core` (c_api) | không | **có**: hàm C mới, `LOST` bắt đầu được dùng |
|
||||
|
||||
Thứ tự thi công **đã chốt: 0 → 1a → 1b → 2 → 3 → 4, tuần tự, pha sau chỉ bắt đầu khi pha trước đã
|
||||
build + test + chạy thử xong.** 1b đi trước commit của 1a vì đổi tên khoá YAML. Pha 1 + 2 hết
|
||||
triệu chứng trong log. Pha 3 chặn abort oan khi pause giữa action (tái hiện được ngay: pause > 15 s
|
||||
giữa `detect_pallet`). Pha 4 là phần "biết thằng nào đang treo" — detour worker thread đã gộp vào 2.
|
||||
|
||||
Thứ tự commit trong pha 2 (mỗi gói repo riêng, push xong mới bump con trỏ):
|
||||
`Test/sbpl` → `pnkx_nav_core` (robot_nav_core) → `Test/sbpl_lattice_planner` → `Test/recovery_core`
|
||||
→ `Test/sbpl_recovery` → `Test/move_base2`.
|
||||
|
||||
Map sang `rb_ws` (hỏi trước, `pull --ff-only`, không chép file):
|
||||
|
||||
| `T800_ws/src/AMR_T800/…` | `rb_ws/pnkx_nav_core/…` |
|
||||
|---|---|
|
||||
| `Test/sbpl` | `src/Libraries/sbpl` |
|
||||
| `Test/sbpl_lattice_planner` | `src/Algorithms/Packages/global_planners/sbpl_lattice_planner` |
|
||||
| `Test/sbpl_recovery` | `src/Algorithms/Packages/recoveries/sbpl_recovery` |
|
||||
| `Test/recovery_core` | `src/Libraries/recovery_core` |
|
||||
| `Test/move_base2` | `src/Navigations/Packages/move_base2` |
|
||||
| `Test/action_core` | `src/Libraries/action_core` |
|
||||
| `Test/mission_adapters` | `src/Libraries/mission_adapters` |
|
||||
| `pnkx_nav_core/src/Navigations/Cores/robot_nav_core` | `src/Navigations/Cores/robot_nav_core` |
|
||||
|
||||
---
|
||||
|
||||
## 6. Test
|
||||
|
||||
### Đơn vị (`catkin_add_gtest`, `./devel/lib/move_base2/<test>`)
|
||||
|
||||
| Test | Kịch bản | Pha |
|
||||
|---|---|---|
|
||||
| `state_machine_test` | PLANNING + `planner=kBusy` liên tiếp → giữ PLANNING, không tăng `planning_retries_`; quá `planner_patience` → RECOVERING | 1 |
|
||||
| `state_machine_test` | CANCELLING với `planner_busy=true` → giữ CANCELLING; `planner_busy=false` → CANCELLED; quá `cancel_settle_timeout` → CANCELLED + reason "settle timeout" | 1 |
|
||||
| `state_machine_test` | PAUSED từ CONTROLLING → resume → `apply_plan == true` | 1 |
|
||||
| `state_machine_test` | PAUSED từ EXECUTING_ACTIONS → `pause_action`; resume → `resume_action`, không `start_action` | 3 |
|
||||
| `planner_runner_test` | Fake planner block bằng cv + implement `Preemptable`; `cancelPlan()` → `isPlanning()` false trong < 50 ms | 2 |
|
||||
| `planner_runner_test` | Fake planner **không** `Preemptable` → `cancelPlan()` chỉ discard, `isPlanning()` vẫn true tới khi fake nhả (hành vi cũ giữ nguyên) | 2 |
|
||||
| `move_base2_scenario_test` | Goal → planner bận 20 cycle → cancel → goal mới ngay → không RECOVERING/ABORTED; CONTROLLING sau khi fake nhả | 1 |
|
||||
| `move_base2_scenario_test` | Goal → planner bận → pause → resume → như trên | 1 |
|
||||
| `move_base2_scenario_test` | Goal → planner bận → submit goal khác (preempt) → như trên | 1 |
|
||||
| `navigation_server_test` | Cancel khi planner bận → `NavFeedback.navigation_state` giữ `PREEMPTING` tới khi fake planner nhả, rồi `PREEMPTED` và chốt | 1 |
|
||||
| `action_runner_test` | Handler timeout 1 s; start → pause 5 s → resume → tick → vẫn kRunning | 3 |
|
||||
| `action_runner_test` | `cancel()` → tick kế trả `kCancelled` (fake perception); fake thiết bị trả `kRunning` 3 tick rồi `kCancelled` | 3 |
|
||||
| `state_machine_test` | CANCELLING với `action_terminal=false` → giữ CANCELLING + `tick_action=true`, velocity `kNone`; `action_terminal=true` → CANCELLED | 3 |
|
||||
| `action_core` registry test | `.so` giả export `_abi` = 1 → từ chối nạp, log tên file; `.so` thiếu symbol `_abi` → từ chối | 3 |
|
||||
| `recovery_core` registry test | như trên cho `RecoveryRegistry` | 2 |
|
||||
| `sbpl_lattice_planner` test (mới) | `preempt()` giữa `makePlan` → trả false trong < 100 ms; 3 lượt replan tổng ≤ `allocated_time` | 2 |
|
||||
| `recovery_core` test | `cancel()` gọi `onCancelRequested()` đồng bộ, đúng một lần | 2 |
|
||||
| `detour_path_recovery_test` | `onStart` → worker chạy → `cancel()` → worker thoát < 50 ms, `onUpdate` kế không nộp path; `onStart` lại ngay sau cancel không kẹt | 2 |
|
||||
| `detour_path_recovery_test` | `onUpdate` không bao giờ block quá 1 ms khi worker đang chạy | 2 |
|
||||
|
||||
### Runtime (máy dev, host C++ thuần, đúng kịch bản log gốc)
|
||||
|
||||
1. Goal xa (`x=11.769 y=-26.969`) để SBPL chạy > 2 s.
|
||||
2. Cancel khi log đang ở `[sbpl_lattice_planner] run planner`.
|
||||
3. Gửi goal kế trong < 0.5 s.
|
||||
|
||||
Kỳ vọng:
|
||||
|
||||
- `[sbpl_lattice_planner] preempted after N ms`, N < 100.
|
||||
- `state -> CANCELLED` xuất hiện **sau** dòng preempted.
|
||||
- Mission kế: `PLANNING → CONTROLLING`, không `RECOVERING` / `ABORTED` / `planning retries exhausted`.
|
||||
- Không còn `Map update global_costmap loop missed its desired rate`.
|
||||
|
||||
Lặp lại với pause/resume thay cho cancel, và với submit-đè thay cho cancel. Thêm kịch bản detour:
|
||||
chặn đường lúc CONTROLLING → `path_blocked` → `[sbpl_recovery] ... attempt 1/3` → cancel giữa lúc đó →
|
||||
đo từ lúc gọi `navigation_cancel()` tới `PREEMPTING` trong log: kỳ vọng ≤ 2 cycle (~70 ms), không
|
||||
phải 0.4–1.2 s. Thêm kịch bản: pause
|
||||
30 s giữa action `detect_pallet` (timeout 10 s) → resume → action vẫn chạy tiếp, không ABORTED.
|
||||
|
||||
#### Kết quả runtime đã chạy (2026-09-12, máy dev, Gazebo, host ROS `amr_node`, VDA5050 qua MQTT)
|
||||
|
||||
Điều kiện: `ros-noetic-sbpl` + `ros-noetic-sbpl-lattice-planner` đã gỡ; `libsbpl_lattice_planner.so`
|
||||
rebuild, `ldd` → `/usr/local/lib/libsbpl.so`; boot log `libsbpl abort flag: supported`. Script
|
||||
`Controllers/Packages/amr_comunication/scripts/reproduce_cancel_race_2dnavgoal.py` và
|
||||
`reproduce_pause_cancel_2dnavgoal.py` (goal 1: `x=-55.282 y=14.560`, ~52 m, SBPL 2.8–9 s; goal 2:
|
||||
`x=-0.665 y=13.164`). Config máy dev lúc chạy: `settle_timeout 2 s`, `planner_patience 25 s`,
|
||||
`max_planning_retries 0`, `allocated_time 10`, `initial_epsilon 1.0`, eps đứng 0.02.
|
||||
Không lần nào có `RECOVERING`, `ABORTED`, `settle timeout`, `planner thread still busy`.
|
||||
|
||||
| # | Kịch bản | Lệnh → state đầu | Preempt | → im (CANCELLED/PAUSED) | Mission kế → CONTROLLING | Ghi chú |
|
||||
|---|---|---|---|---|---|---|
|
||||
| R1 | cancel @ PLANNING, goal kế sau 0.23 s (09:52, 09:57 — lặp 2 lần) | `CANCELLING` +36 ms | `preempted after 2844 ms` +0.03 ms sau CANCELLING | `CANCELLED` +86 ms, `IDLE` +136 ms | +0.95 s sau cancel (SBPL 635 ms) | Goal kế tới khi đã `IDLE`; không qua `kBusy` |
|
||||
| R2 | pause @ PLANNING → 2 s → resume → 0.23 s → goal kế đè (pc1, 21:11) | `PAUSING` +30 ms | +0.03 ms | `PAUSED` +80 ms | resume → `PLANNING` +27 ms, SBPL chạy lại; goal đè → `preempted after 192 ms` **trước** `active global planner is 'CustomPlanner'` → `PREEMPTED` → `CONTROLLING` +0.79 s | Cover luôn kịch bản submit-đè không cancel: `swapPlanner` cắt `running_planner_` (fix 2026-09-11 22:50) |
|
||||
| R3 | pause @ CONTROLLING (v 0.115 m/s) → 2 s → resume → goal kế đè (pc2, 21:16) | `PAUSING` +38 ms | — | `PAUSED` +538 ms (chờ odom < 0.02 m/s — robot giảm tốc thật) | resume → `CONTROLLING` +35 ms, `setPlan: 1423 poses` (plan cũ, 4.8-b), Priest `slew reseeded … v 0.115 -> 0.000`, không giật; goal đè → `PREEMPTED` → `CONTROLLING` +0.9 s | Lo ngại "warm-start của trước lúc dừng" không xảy ra |
|
||||
| R4 | pause @ PLANNING → 0.23 s → cancel (lúc đã PAUSED) → goal kế (pc3, 21:18) | `PAUSING` +44 ms, `PAUSED` +94 ms | +0.03 ms | cancel → `CANCELLING: cancelled while paused` → `CANCELLED` +50 ms (1 tick) | +0.78 s sau cancel | Planner đã idle từ lúc pause, không preempt lần hai |
|
||||
| R5 | pause @ CONTROLLING (v 0.39 m/s) → 0.2 s → cancel (lúc còn PAUSING) → goal kế (pc4, 21:21) | `PAUSING` +45 ms | — | cancel → `CANCELLING: cancelled while pausing` → `CANCELLED` +250 ms (robot đứng sau 450 ms từ pause) | goal tới lúc còn CANCELLING, giữ tới `CANCELLED`, `PLANNING` +50 ms sau đó → `CONTROLLING` +1.25 s sau cancel | Đường `kPausing → kCancelling` giữ đúng điều kiện im |
|
||||
|
||||
Đối chiếu bản trước fix (log 2026-09-11 22:44 và 2026-09-12 09:19, `kBusy` có nhưng chưa abort
|
||||
flag): cancel @ PLANNING → `CANCELLING` 2 s → `settle timeout … planner_busy=yes` (log_error) →
|
||||
mission kế chờ `planner thread still busy` 4 s → tổng 5.05 s. Bản gốc (`robot_app.log`): ABORTED
|
||||
ngay + mission kế ABORTED.
|
||||
|
||||
Còn tồn tại (không thuộc lifecycle): `Map update global_costmap loop missed its desired rate … took
|
||||
2.3 s` — planner giữ costmap mutex suốt `makePlan` (giao thức gen-1, P3 mục 2.1). Search goal 52 m
|
||||
mất 8.96–9.05 s / trần 10 s với `initial_epsilon 1.0` — chỗ pha 0 có ích thật.
|
||||
|
||||
**Chưa chạy:** cancel giữa detour recovery (`sbpl_recovery` worker thread); pause 30 s giữa action
|
||||
`detect_pallet`; treo cưỡng bức để thấy `kHung`/`LOST` (cần plugin cố ý treo, chưa có trong harness).
|
||||
|
||||
### Lệnh build (người dùng chạy, Claude đọc log)
|
||||
|
||||
```bash
|
||||
cd /home/duongtd/T800_ws
|
||||
catkin_make --pkg sbpl 2>&1 | tee /tmp/build_sbpl.log
|
||||
catkin_make --pkg robot_nav_core 2>&1 | tee /tmp/build_nav_core.log
|
||||
catkin_make --pkg sbpl_lattice_planner 2>&1 | tee /tmp/build_sbpl_lp.log
|
||||
catkin_make --pkg action_core 2>&1 | tee /tmp/build_action_core.log
|
||||
catkin_make --pkg dock_pattern_action 2>&1 | tee /tmp/build_dock_pattern.log
|
||||
catkin_make --pkg recovery_core 2>&1 | tee /tmp/build_recovery_core.log
|
||||
catkin_make --pkg sbpl_recovery 2>&1 | tee /tmp/build_sbpl_recovery.log
|
||||
catkin_make --pkg mission_adapters 2>&1 | tee /tmp/build_mission_adapters.log
|
||||
catkin_make --pkg move_base2 2>&1 | tee /tmp/build_mb2.log
|
||||
source devel/setup.bash
|
||||
./devel/lib/move_base2/state_machine_test
|
||||
./devel/lib/move_base2/planner_runner_test
|
||||
./devel/lib/move_base2/move_base2_scenario_test
|
||||
./devel/lib/move_base2/mission_layer_test
|
||||
./devel/lib/move_base2/action_runner_test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Rủi ro robotics
|
||||
|
||||
- **Safety stop không đổi đường.** Preempt chỉ cắt planner/detour. Vận tốc vẫn đi qua arbiter,
|
||||
nguồn `kNone` ở mọi state phải dừng. Bất biến 1–4 của `STATE_MACHINE.md` giữ nguyên; tick action
|
||||
trong CANCELLING không cấp vận tốc.
|
||||
- **Costmap mutex nhả sớm** khi preempt → global costmap update hết bị treo. Tác dụng phụ tích cực.
|
||||
- **Plan cũ không lọt sang mission kế**: `discard_` + `plan_tag_` giữ nguyên, hai lớp chặn.
|
||||
- **`robot_stopped` theo odom**: odom nhiễu có thể giữ CANCELLING lâu hơn → `cancel_settle_timeout`
|
||||
là trần; đặt eps 0 để lùi về hành vi cũ.
|
||||
- **Resume → `setPlan` lại**: reset `infeasible_streak_`, `goal_xy_latched_` của Priest. Với goal
|
||||
đã latch (đang ở sát đích) rồi pause/resume, planner có thể bám lại một đoạn ngắn. Chạy thử với
|
||||
docking.
|
||||
- **Thread/atomic**: cờ preempt là `std::atomic<bool>` relaxed, không lock, không alloc trong vòng
|
||||
expand. Không đổi determinism của ARA*.
|
||||
- **ABI pha 2 (recovery)**: `RecoveryBehavior` thêm virtual `onCancelRequested()` → 5 plugin recovery
|
||||
rebuild cùng lúc. Không có guard thì plugin cũ nạp vào runtime mới crash ở vtable; với guard 4.9
|
||||
registry từ chối nạp + log_error tên file, robot chạy tiếp thiếu behavior đó (route resolve đã
|
||||
biết bỏ tên thiếu — `STATE_MACHINE.md` mục Recovery routes).
|
||||
- **Worker thread trong detour**: kết quả về sau cancel phải bị vứt (tag theo lượt `onStart`); `onStart`
|
||||
join worker cũ có trần (preempt làm nó thoát trong ms, nhưng vẫn đặt trần 100 ms + log_error).
|
||||
- **ABI pha 3**: `ActionHandler` thêm virtual → 5 handler hiện có rebuild cùng lúc, ghi rõ trong
|
||||
commit. Với guard 4.9, handler `.so` cũ bị từ chối nạp có log; mission mang actionType đó sẽ bị
|
||||
từ chối ở `start()` (không có handler) thay vì crash. Không có đường tương thích ngược.
|
||||
- **Guard 4.9 chỉ bắt lệch header của gói plugin**, không bắt lệch của thư viện dùng chung bên dưới
|
||||
(`robot_cpp`, `robot_geometry_msgs`…). Đủ cho hai lần đổi vtable ở pha 2/3; không phải cơ chế
|
||||
ABI toàn workspace.
|
||||
- **Host thấy `PREEMPTING` lâu hơn** (tối đa `cancel_settle_timeout`). Host nào coi `PREEMPTING` là
|
||||
"đã xong" phải sửa — contract cũ đã nói rõ đợi state, không đợi lời gọi trả về.
|
||||
|
||||
---
|
||||
|
||||
## 8. Chưa chắc / cần xác nhận trước khi làm
|
||||
|
||||
- **Driver bánh xe có giới hạn giảm tốc riêng không?** Luật 5 giao việc giảm tốc cho driver. Nếu
|
||||
driver không clamp thì mọi cancel/pause là phanh gấp (15 m/s² lệnh với Priest 0.5 m/s) — tải
|
||||
cao/dễ đổ sẽ thấy. Cần xác nhận từ firmware; nếu không có, cân nhắc lại phương án B như một pha
|
||||
riêng, không gộp vào lifecycle.
|
||||
- `/opt/pnkx_nav_core/lib/libsbpl.so` trên máy chạy log có build từ `Test/sbpl` không. Nếu là bản
|
||||
cài sẵn khác, pha 2 không ăn cho tới khi cài lại.
|
||||
- `clock()` vs wall time: **đã đo** (log 2026-09-12 09:19, chưa abort flag): ngân sách 10 s CPU
|
||||
cạn sau 8.85–9.01 s wall khi Priest chạy — nhanh hơn ~11 %. Không đáng kể; không đổi.
|
||||
- `ClearCostmapRecovery` xong trong 35 ms **trong lúc** planner giữ global costmap mutex (log
|
||||
896.811→896.846) — nó khoá gì? Nếu không khoá master mutex thì có race với planner đang đọc.
|
||||
- `HybridDockingLocalPlanner` phản ứng thế nào với `setPlan` giữa đường (resume). Chưa đọc.
|
||||
- `ControllerRunner::swapPlanner` khi profile đổi giữa lúc planner thread còn bận (docking sau
|
||||
cancel position): instance global planner cũ được giữ, nhưng `DockPlanner::initialize()` có khoá
|
||||
global costmap không — chưa đọc.
|
||||
- Host app hiện có poll `navigation_get_state()` sau `navigation_cancel()` không, hay gửi tiếp
|
||||
ngay? Nếu gửi ngay thì vẫn chạy đúng nhờ `kBusy`, nhưng host nên sửa để chờ hết `PREEMPTING`.
|
||||
- `controller_patience: 0.0333 s` và `initial_epsilon: 1.0` là cố ý hay sót? Không đổi trong kế
|
||||
hoạch này ngoài đề xuất chạy thử ở pha 0.
|
||||
- `CustomPlanner` fail 100 % với mission qua REST (`makePlan(start, goal) is not supported — use the
|
||||
Order overload`) → SBPL thực chất là planner chính. Vấn đề riêng, ngoài phạm vi.
|
||||
@@ -14,9 +14,10 @@ Khi cần đổi hành vi: sửa tài liệu này trước, sửa test, rồi m
|
||||
| `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` |
|
||||
| `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()` → `PAUSING` → `PAUSED` (không huỷ action) |
|
||||
| `PAUSING` | không ai (0) | `pause()` từ `PLANNING`/`CONTROLLING`/`RECOVERING`/`EXECUTING_ACTIONS` (2026-09-11). Ngay cycle vào: `stop_planner` / `cancel_recovery` / (pha 3) `pause_action`, lệnh = 0 | **quiescent** (`robot_stopped` **và** `!planner_busy` **và** `!recovery_busy` **và** `action_terminal`) → `PAUSED`; quá `settle_timeout` → `PAUSED` + cờ `settle_timed_out`; `settle_timeout = 0` → chỉ chờ `robot_stopped`. `resume()` → về state trước (chưa kịp dừng gì cũng không sao); `cancel()` → `CANCELLING`; goal mới → preempt như `PAUSED`. Host **không** thấy `PAUSED` ở đây — thấy tên state trước + `feed_back_str` "pausing…" |
|
||||
| `PAUSED` | không ai (0) | `PAUSING` đã im hẳn | `resume()` → về state trước đó (về `CONTROLLING` thì kèm `apply_plan`: nạp lại plan để local planner reset warm-start — 2026-09-11, phương án (b) đã chốt); `cancel()` → `CANCELLING` |
|
||||
| `CANCELLING` | không ai (0) | `cancel()` từ mọi state đang chạy | **quiescent** (2026-09-11): `robot_stopped` **và** `!planner_busy` **và** `!recovery_busy` **và** `action_terminal` → `CANCELLED`; quá `settle_timeout` → `CANCELLED` + cờ `settle_timed_out` (bên gọi log lỗi). `settle_timeout = 0` → chỉ chờ `robot_stopped` như trước. Chừng nào `!action_terminal` thì `tick_action` để handler dừng thiết bị an toàn, không cấp vận tốc |
|
||||
| `SUCCEEDED` / `ABORTED` / `CANCELLED` | không ai (0) | như trên | terminal; báo kết quả rồi về `IDLE` ở cycle kế tiếp |
|
||||
|
||||
## Thứ tự ưu tiên trong một cycle
|
||||
@@ -35,7 +36,7 @@ Khi cần đổi hành vi: sửa tài liệu này trước, sửa test, rồi m
|
||||
một lời gọi blocking. Bắt buộc như vậy vì recovery thế hệ 2 trả kết quả từng tick và có thể phát
|
||||
vận tốc — nghĩa là quyền phát cmd_vel phải chuyển tay từ local planner sang recovery và ngược lại.
|
||||
|
||||
2. **`PAUSED` và `CANCELLING` là state thật**, không phải cờ đọc rải rác trong vòng lặp. Đường huỷ ở
|
||||
2. **`PAUSING`/`PAUSED` và `CANCELLING` là state thật**, không phải cờ đọc rải rác trong vòng lặp. Đường huỷ ở
|
||||
bản cũ được viết hai lần, ở nhánh `try` và nhánh `catch`, gần 80 dòng giống hệt nhau.
|
||||
|
||||
3. **`SUCCEEDED`/`ABORTED`/`CANCELLED` là state**, không phải `return` giữa hàm. Đây là cơ chế giữ
|
||||
@@ -193,12 +194,37 @@ Bốn tính chất sau được chốt lại ở cuối mỗi lần chuyển sta
|
||||
4. `report_outcome` bật đúng một lần cho mỗi yêu cầu — kể cả yêu cầu có action: chỉ báo sau action
|
||||
cuối (D8).
|
||||
|
||||
## Vì sao `CANCELLING` luôn kết thúc
|
||||
## Vì sao `CANCELLING` luôn kết thúc — và vì sao nó phải chờ (2026-09-11)
|
||||
|
||||
`CANCELLING` chờ `robot_stopped`. Vì nguồn vận tốc ở state này đã là `kNone` và bộ trọng tài phát
|
||||
lệnh 0 tức thì, `robot_stopped` thành true ngay ở cycle kế tiếp. Do đó state này kết thúc sau hữu hạn
|
||||
cycle mà không cần thêm tham số timeout nào.
|
||||
Nguồn vận tốc ở state này là `kNone`, bộ trọng tài phát lệnh 0 **tức thì, không ramp**
|
||||
(`VelocityArbiter::arbitrate`, ba lý do ghi tại chỗ; giảm tốc theo động học là việc của driver bánh
|
||||
xe). Lệnh 0 là điều kiện cần. Trước 2026-09-11 nó cũng là điều kiện đủ, và đó là một lời nói dối với
|
||||
host: `CANCELLED`/`PREEMPTED` được báo trong lúc thread global planner còn chạy lượt `makePlan` đã
|
||||
huỷ (SBPL chạy tới hết `allocated_time`, `cancelPlan()` chỉ đặt cờ vứt kết quả). Host đọc PREEMPTED
|
||||
là "xong, gửi goal kế được"; goal kế bị `startPlan()` từ chối vì thread còn bận, control loop dịch
|
||||
thành `kFailed`, `max_planning_retries: 0` leo thang ngay → `ABORTED` sau 3 s dù chưa lập plan lần
|
||||
nào (`robot_app.log` 2026-09-11, mission 3 → 4).
|
||||
|
||||
Ở bước nối dây sau, `robot_stopped` nên được lấy từ vận tốc **đo được** (odometry) thay vì từ lệnh
|
||||
đã phát. Đó là lý do nó là một trường dữ liệu vào của state machine chứ không phải thứ state machine
|
||||
tự tính.
|
||||
Từ 2026-09-11 `CANCELLING` rời đi khi **quiescent** — ba điều kiện cùng đúng:
|
||||
|
||||
| Điều kiện | Nguồn | Nghĩa |
|
||||
|---|---|---|
|
||||
| `robot_stopped` | control loop: odom nếu có (`stopped_measured_*_eps`), không thì lệnh đã phát | bánh xe đã đứng, không chỉ lệnh = 0 |
|
||||
| `!planner_busy` | `PlannerPort::isPlanning()` **hoặc** hàng `kGlobalPlanner` của `ComponentStatusBoard` ≠ idle | thread planner rảnh, kể cả lượt đã huỷ |
|
||||
| `!recovery_busy` | hàng `kRecovery` của bảng (RecoveryRunner ghi; detour worker pha 2) | behavior và worker của nó đã thoát |
|
||||
| `action_terminal` | hàng `kAction` của bảng: idle hoặc paused (pha 3 mới có handshake; không có bảng → `true`) | handler đã dừng thiết bị xong |
|
||||
|
||||
`ComponentStatusBoard` (`core/component_status.h`, 2026-09-11) là nguồn sự thật: mỗi runner tự ghi
|
||||
hàng của mình (busy / stopping / idle / paused / hung) bằng atomic từ thread của nó; control loop
|
||||
ghi hàng `kLocalPlanner` (bọc quanh `computeVelocityCommands`) và heartbeat `kControlLoop` cuối
|
||||
mỗi `step()`. Watchdog (pha 4) đọc bảng từ thread riêng để bắt thành phần treo — kể cả chính
|
||||
control thread. Cùng bộ điều kiện dùng cho `PAUSING`.
|
||||
|
||||
`settle_timeout` [s] là trần: quá thì vẫn `CANCELLED` nhưng output mang
|
||||
`settle_timed_out` đúng một cycle và control loop **log lỗi, không có khoá tắt** — có plugin
|
||||
không cắt được lượt đang chạy hoặc odom không về 0. Đặt 0 = hành vi cũ. Host nhìn thấy đúng cặp
|
||||
`PREEMPTING`/`PREEMPTED` đã có trong `move_base_core::State`; chỉ thời điểm đổi.
|
||||
|
||||
Hệ quả cho tầng trên: `startPlan()` bị từ chối trong lúc `isPlanning()` là **`kBusy`, không phải
|
||||
`kFailed`** (`control_loop.cpp`, cùng ngày). `kBusy` giữ `PLANNING`, không tăng `planning_retries_`;
|
||||
`planner_patience` vẫn là trần cho "bận quá lâu" — một plugin treo thật vẫn bị phát hiện.
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
|
||||
| Thread | Sở hữu | Chu kỳ | Ghi chú |
|
||||
|---|---|---|---|
|
||||
| `control` | state machine, bộ trọng tài vận tốc, controller, recovery, **cmd_vel** | `controller_frequency` | **Thread duy nhất được phát cmd_vel.** Toàn bộ `ControlLoop::step()` chạy ở đây |
|
||||
| `planner` | global planner, bộ đệm plan | `planner_frequency` hoặc theo biến điều kiện | *Chưa có ở trạng thái hiện tại* — xem mục dưới |
|
||||
| `control` | state machine, bộ trọng tài vận tốc, controller, recovery, action, **cmd_vel** | `controller_frequency` | **Thread duy nhất được phát cmd_vel.** Toàn bộ `ControlLoop::step()` chạy ở đây; heartbeat `kControlLoop` cuối mỗi step |
|
||||
| `planner` | global planner (`PlannerRunner::threadBody`), hộp thư plan | theo biến điều kiện (`startPlan`) | Một lượt `makePlan` tại một thời điểm. `cancelPlan()` / `swapPlanner()` (khi còn lượt dở) / destructor đặt `discard_` **và** gọi `Preemptable::preempt()` trên `running_planner_` — instance thread đang ở trong `makePlan`, không phải `active_` (swap có thể đã đổi `active_`) — nếu plugin hỗ trợ (2026-09-11); SBPL thoát trong ms thay vì chạy hết `allocated_time` |
|
||||
| `detour worker` | một lượt `makePlan` của `DetourPathRecovery` | theo attempt | Thuộc plugin `sbpl_recovery` (2026-09-11). Hợp lệ vì behavior họ `kPath` không phát vận tốc; `onUpdate` chỉ khởi động/poll, `onCancelRequested()` preempt + join |
|
||||
| `watchdog` | đọc `ComponentStatusBoard`, kết luận treo | `watchdog_period` | Chỉ atomic load, không lock, không chạm runner. Control thread treo → `getFeedback()` báo `LOST` từ thread host (2026-09-11) |
|
||||
| `mission_event` | hàng đợi sự kiện mission | theo sự kiện | Thuộc mission framework, không thuộc gói này |
|
||||
| `mission_exec` | điều phối chặng mission | theo sự kiện | Thuộc mission framework. Chỉ gọi callback, **không được block** |
|
||||
| host (ROS / C#) | nhận dữ liệu sensor, gọi API `BaseNavigation` | tuỳ host | Ghi vào vùng dữ liệu sensor qua mutex |
|
||||
@@ -45,20 +47,30 @@ nguyên nhân lỗi double-free đã ghi nhận trong workspace. Quy tắc áp c
|
||||
- Không giữ tham chiếu qua nhiều cycle.
|
||||
- Không giữ tham chiếu qua ranh giới thread.
|
||||
|
||||
## Trạng thái hiện tại: một thread
|
||||
## Bảng trạng thái thành phần (2026-09-11)
|
||||
|
||||
`ControlLoop` hiện chạy đồng bộ, một thread, và lập plan ngay trong `step()`. Đây là lựa chọn có chủ
|
||||
đích cho bước dựng khung: phần quyết định kiểm được đầy đủ mà không cần thread nào, nên test chạy tất
|
||||
định và không có race.
|
||||
`ComponentStatusBoard` (`core/component_status.h`) là nguồn sự thật "ai đang bận / đang dừng / đã
|
||||
treo". Quyền ghi theo hàng, mỗi hàng đúng MỘT chủ:
|
||||
|
||||
Khi thêm thread planner ở bước sau:
|
||||
| Hàng | Chủ ghi | Thread ghi |
|
||||
|---|---|---|
|
||||
| `kGlobalPlanner` | `PlannerRunner` | planner (busy/idle) + control (`stopping` trong `cancelPlan`) — đều dưới `mutex_` |
|
||||
| `kLocalPlanner` | `ControlLoop` (bọc quanh `computeVelocityCommands`) | control |
|
||||
| `kRecovery` | `RecoveryRunner` | control |
|
||||
| `kAction` | `ActionRunner` | control |
|
||||
| `kControlLoop` | `ControlLoop` (heartbeat cuối `step()`) | control |
|
||||
|
||||
- Giữ nguyên mô hình bộ đệm plan ba lớp của bản cũ. Nó đang hoạt động tốt và là đoạn code tinh tế —
|
||||
bê nguyên si trước, không "cải tiến" cùng lúc với việc chuyển sang kiến trúc mới.
|
||||
- Điểm nối là `ControlLoop::runPlanner()`: thay lời gọi đồng bộ bằng việc đánh thức thread planner và
|
||||
đọc kết quả từ bộ đệm.
|
||||
- `PlannerFeedback` không đổi. Đó chính là mục đích của việc tách nó thành một enum: state machine
|
||||
không cần biết plan được tính đồng bộ hay bất đồng bộ.
|
||||
Đọc: `ControlLoop` mỗi cycle (quiescence cho `CANCELLING`/`PAUSING`), `Watchdog` từ thread riêng, host
|
||||
qua C API `navigation_get_component_status()`. Mọi field atomic, relaxed; không lock trên đường control.
|
||||
|
||||
Watchdog **không ghi** vào bảng (giữ luật một chủ): kết luận treo nằm trong cờ riêng của nó.
|
||||
|
||||
## Lịch sử: từ một thread tới bốn
|
||||
|
||||
Bản dựng khung chạy đồng bộ một thread. Thread planner đã được thêm với mô hình hộp thư
|
||||
(`startPlan`/`pollPlan`/`cancelPlan`); `PlannerFeedback` không đổi — state machine không biết plan
|
||||
được tính đồng bộ hay bất đồng bộ. Detour worker và watchdog thêm 2026-09-11 (xem
|
||||
`PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md`).
|
||||
|
||||
## Vòng đời
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
#include <move_base2/control_loop.h>
|
||||
#include <move_base2/io/sensor_gateway.h>
|
||||
#include <move_base2/io/watchdog.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
@@ -44,9 +45,20 @@ struct MoveBase2Config
|
||||
/// [Hz] Nhịp lập plan lại khi đang bám plan. 0 = chỉ lập khi cần (theo yêu cầu của state machine).
|
||||
double planner_frequency = 0.0;
|
||||
|
||||
/// [s] Trần thời gian chờ một lần lập plan trước khi coi là hỏng. <= 0 = không giới hạn.
|
||||
/**
|
||||
* [s] Trần một lượt makePlan trên thread planner TRƯỚC KHI watchdog kết luận planner TREO (2026-09-11
|
||||
* — trước đó khoá này được đọc, in ra, và không ai dùng). Phải LỚN hơn thời gian một lượt hợp lệ
|
||||
* dài nhất: với SBPL là `allocated_time` (đã chia ngân sách chung từ 2026-09-11). <= 0 = không
|
||||
* giám sát. Đây là chẩn đoán, không phải điều khiển: state machine vẫn dùng `planner_patience`.
|
||||
*/
|
||||
double planner_timeout = 5.0;
|
||||
|
||||
/**
|
||||
* Watchdog (2026-09-11): thread riêng đọc bảng trạng thái thành phần, kết luận "treo" theo ngân
|
||||
* sách từng hàng. `watchdog.planner_timeout` được chép từ @ref planner_timeout khi nạp.
|
||||
*/
|
||||
WatchdogConfig watchdog;
|
||||
|
||||
// --- Telemetry --------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
#include <robot_geometry_msgs/Twist.h>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/core/navigation_request.h>
|
||||
#include <move_base2/core/state_machine.h>
|
||||
#include <move_base2/core/velocity_arbiter.h>
|
||||
@@ -70,6 +71,14 @@ struct ControlLoopDeps
|
||||
* hoàn toàn, mọi bộ test dùng cổng giả rơi vào nhánh này.
|
||||
*/
|
||||
EnvironmentPort* environment = nullptr;
|
||||
|
||||
/**
|
||||
* Bảng trạng thái thành phần (2026-09-11). **Có thể null** — null thì quiescence của
|
||||
* CANCELLING/PAUSING chỉ dựa vào `PlannerPort::isPlanning()` và odom (hành vi pha 1a), recovery/
|
||||
* action coi như đã im. Có bảng thì runner ghi, control loop đọc thêm hàng recovery/action và tự
|
||||
* ghi hàng local_planner + control_loop (heartbeat cho watchdog).
|
||||
*/
|
||||
ComponentStatusBoard* components = nullptr;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -272,6 +281,12 @@ public:
|
||||
return state_machine_.state();
|
||||
}
|
||||
|
||||
/// @brief State sẽ quay về sau PAUSING/PAUSED — host giữ tên state này trong lúc PAUSING.
|
||||
NavigationState stateBeforePause() const
|
||||
{
|
||||
return state_machine_.stateBeforePause();
|
||||
}
|
||||
|
||||
/// @brief Đang có yêu cầu chạy dở (kể cả đang pause) — false ngay khi kết quả được báo.
|
||||
bool hasActiveRequest() const
|
||||
{
|
||||
@@ -340,6 +355,15 @@ private:
|
||||
*/
|
||||
void collectPlannerResult();
|
||||
|
||||
/**
|
||||
* @brief Robot đã dừng chưa — ưu tiên vận tốc ĐO ĐƯỢC, lùi về lệnh đã phát khi không có odom.
|
||||
*
|
||||
* Lệnh đã phát về 0 không có nghĩa là bánh xe đã đứng: driver còn giảm tốc. Host đọc CANCELLED
|
||||
* lúc đó rồi gửi goal kế là gửi cho một robot đang trượt. Ngưỡng và công tắc:
|
||||
* `StateMachineConfig::stopped_measured_*_eps` (0 = bỏ odom).
|
||||
*/
|
||||
bool robotStopped() const;
|
||||
|
||||
/// @brief Gọi controller và lấy lệnh ứng viên.
|
||||
void runController(robot_geometry_msgs::Twist& candidate);
|
||||
|
||||
|
||||
196
include/move_base2/core/component_status.h
Normal file
196
include/move_base2/core/component_status.h
Normal file
@@ -0,0 +1,196 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — bảng trạng thái thành phần: mỗi thread/plugin tự khai nó đang làm gì.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef MOVE_BASE2_CORE_COMPONENT_STATUS_H_
|
||||
#define MOVE_BASE2_CORE_COMPONENT_STATUS_H_
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <initializer_list>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
/**
|
||||
* @enum Component
|
||||
* @brief Các thành phần có thể "bận" độc lập với state machine.
|
||||
*
|
||||
* Thứ tự là chỉ số hàng trong @ref ComponentStatusBoard — thêm vào CUỐI, trước kCount, không xen
|
||||
* giữa (C API pha 4 phơi chỉ số này ra host).
|
||||
*/
|
||||
enum class Component : std::uint8_t
|
||||
{
|
||||
kGlobalPlanner = 0, ///< Thread lập plan của PlannerRunner (một lượt makePlan).
|
||||
kLocalPlanner, ///< Lời gọi computeVelocityCommands trên control thread.
|
||||
kRecovery, ///< Behavior đang chạy (và worker thread của detour, pha 2).
|
||||
kAction, ///< Handler đang chạy.
|
||||
kCostmapGlobal, ///< Map-update thread của global costmap (chỉ heartbeat).
|
||||
kCostmapLocal, ///< Map-update thread của local costmap (chỉ heartbeat).
|
||||
kControlLoop, ///< Chính control thread — heartbeat cuối mỗi step().
|
||||
kCount
|
||||
};
|
||||
|
||||
/**
|
||||
* @enum ComponentPhase
|
||||
* @brief Thành phần đang ở đâu trong vòng đời của một lượt việc.
|
||||
*/
|
||||
enum class ComponentPhase : std::uint8_t
|
||||
{
|
||||
kIdle = 0, ///< Không có việc.
|
||||
kBusy, ///< Đang làm việc.
|
||||
kStopping, ///< Đã được bảo dừng (preempt/cancel) nhưng chưa thoát.
|
||||
kPaused, ///< Đã xác nhận tạm dừng (chỉ action, pha 3).
|
||||
kHung ///< Watchdog kết luận: bận quá ngân sách mà không nhích (pha 4).
|
||||
};
|
||||
|
||||
const char* toString(Component component);
|
||||
const char* toString(ComponentPhase phase);
|
||||
|
||||
/**
|
||||
* @struct ComponentStatus
|
||||
* @brief Một hàng của bảng. Mọi field là atomic, ghi relaxed — không lock, không alloc.
|
||||
*
|
||||
* Mốc thời gian là `steady_clock` [ns]: bảng phải so sánh được giữa các thread mà không phụ thuộc
|
||||
* đồng hồ giả của control loop (ClockPort). Đọc `phase_since_ns` để biết bận bao lâu,
|
||||
* `last_progress_ns` để biết lần cuối "nhích" — hai thứ khác nhau: SBPL bận 4 s nhưng nhích mỗi
|
||||
* vài ms là bình thường; bận 4 s mà không nhích 4 s là treo.
|
||||
*/
|
||||
struct ComponentStatus
|
||||
{
|
||||
std::atomic<ComponentPhase> phase{ComponentPhase::kIdle};
|
||||
std::atomic<std::int64_t> phase_since_ns{0};
|
||||
std::atomic<std::int64_t> last_progress_ns{0};
|
||||
std::atomic<std::uint64_t> progress_ticks{0};
|
||||
|
||||
ComponentStatus() = default;
|
||||
ComponentStatus(const ComponentStatus&) = delete;
|
||||
ComponentStatus& operator=(const ComponentStatus&) = delete;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class ComponentStatusBoard
|
||||
* @brief Nguồn sự thật duy nhất về "thành phần nào đang bận / đang dừng / đã treo".
|
||||
*
|
||||
* Quyền ghi theo hàng, mỗi hàng đúng MỘT chủ: PlannerRunner ghi kGlobalPlanner (từ cả control
|
||||
* thread lẫn thread lập plan, nhưng đều trong code của nó), RecoveryRunner ghi kRecovery,
|
||||
* ActionRunner ghi kAction, ControlLoop ghi kLocalPlanner và kControlLoop. Cổng giả trong test ghi
|
||||
* đúng hàng mà runner thật sẽ ghi. Hai chủ cho một hàng là race — không được.
|
||||
*
|
||||
* Ai đọc: ControlLoop mỗi cycle (quiescence cho CANCELLING/PAUSING), Watchdog (pha 4) từ thread
|
||||
* riêng, host qua C API (pha 4). Đọc chỉ là load relaxed.
|
||||
*
|
||||
* Vòng đời: NavigationRuntime sở hữu, sống lâu hơn mọi runner; runner giữ con trỏ non-owning, null
|
||||
* = không khai (mọi lời gọi thành no-op).
|
||||
*/
|
||||
class ComponentStatusBoard
|
||||
{
|
||||
public:
|
||||
static constexpr std::size_t kRows = static_cast<std::size_t>(Component::kCount);
|
||||
|
||||
ComponentStatusBoard() = default;
|
||||
ComponentStatusBoard(const ComponentStatusBoard&) = delete;
|
||||
ComponentStatusBoard& operator=(const ComponentStatusBoard&) = delete;
|
||||
|
||||
/// @brief Mốc thời gian dùng cho mọi hàng [ns, steady_clock].
|
||||
static std::int64_t nowNs()
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Chủ hàng đổi phase. Đặt lại `phase_since_ns` và tính là một nhịp tiến độ.
|
||||
*
|
||||
* Không kiểm hợp lệ chuyển phase: bảng ghi lại sự thật do chủ hàng khai, không phải state
|
||||
* machine.
|
||||
*/
|
||||
void enter(Component component, ComponentPhase phase)
|
||||
{
|
||||
ComponentStatus& row = at(component);
|
||||
const std::int64_t now = nowNs();
|
||||
row.phase.store(phase, std::memory_order_relaxed);
|
||||
row.phase_since_ns.store(now, std::memory_order_relaxed);
|
||||
row.last_progress_ns.store(now, std::memory_order_relaxed);
|
||||
row.progress_ticks.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
/// @brief Chủ hàng báo "còn sống, đang nhích". Rẻ: hai store, một fetch_add.
|
||||
void progress(Component component)
|
||||
{
|
||||
ComponentStatus& row = at(component);
|
||||
row.last_progress_ns.store(nowNs(), std::memory_order_relaxed);
|
||||
row.progress_ticks.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
ComponentPhase phase(Component component) const
|
||||
{
|
||||
return at(component).phase.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
/// @brief [s] Đã ở phase hiện tại bao lâu, tính tới bây giờ.
|
||||
double secondsInPhase(Component component) const
|
||||
{
|
||||
return static_cast<double>(nowNs() - at(component).phase_since_ns.load(std::memory_order_relaxed)) * 1e-9;
|
||||
}
|
||||
|
||||
/// @brief [s] Từ lần "nhích" gần nhất tới bây giờ.
|
||||
double secondsSinceProgress(Component component) const
|
||||
{
|
||||
return static_cast<double>(nowNs() - at(component).last_progress_ns.load(std::memory_order_relaxed)) * 1e-9;
|
||||
}
|
||||
|
||||
bool isIdle(Component component) const
|
||||
{
|
||||
return phase(component) == ComponentPhase::kIdle;
|
||||
}
|
||||
|
||||
bool allIdle(std::initializer_list<Component> components) const
|
||||
{
|
||||
for (Component c : components)
|
||||
{
|
||||
if (!isIdle(c))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool anyHung() const
|
||||
{
|
||||
for (std::size_t i = 0; i < kRows; ++i)
|
||||
{
|
||||
if (rows_[i].phase.load(std::memory_order_relaxed) == ComponentPhase::kHung)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ComponentStatus& at(Component component)
|
||||
{
|
||||
return rows_[static_cast<std::size_t>(component)];
|
||||
}
|
||||
|
||||
const ComponentStatus& at(Component component) const
|
||||
{
|
||||
return rows_[static_cast<std::size_t>(component)];
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<ComponentStatus, kRows> rows_;
|
||||
};
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
#endif // MOVE_BASE2_CORE_COMPONENT_STATUS_H_
|
||||
@@ -40,7 +40,8 @@ enum class NavigationState
|
||||
kControlling, ///< Đang bám plan. Local planner là nguồn vận tốc.
|
||||
kRecovering, ///< Đang chạy một recovery behavior. Recovery là nguồn vận tốc.
|
||||
kExecutingActions, ///< Đang chạy action của mission tại chỗ (D8). Vận tốc = 0.
|
||||
kPaused, ///< Tạm dừng theo yêu cầu. Vận tốc = 0.
|
||||
kPausing, ///< Đã nhận pause, lệnh = 0, đang chờ mọi thành phần im (2026-09-11). Host vẫn thấy tên state trước.
|
||||
kPaused, ///< Tạm dừng theo yêu cầu, mọi thành phần đã im. Vận tốc = 0.
|
||||
kCancelling, ///< Đang giảm tốc để huỷ. Vận tốc = 0, chờ robot dừng hẳn.
|
||||
kSucceeded, ///< Terminal: đạt goal và mọi action đã xong.
|
||||
kAborted, ///< Terminal: hết cách, không đạt được goal hoặc action thất bại.
|
||||
|
||||
@@ -56,7 +56,8 @@ enum class ActionFeedback
|
||||
kIdle, ///< Chưa chạy action ở cycle này.
|
||||
kRunning,
|
||||
kSucceeded, ///< Action HIỆN TẠI xong; còn action kế tiếp hay không do state machine quyết.
|
||||
kFailed
|
||||
kFailed,
|
||||
kCancelled ///< Handler đã dừng thiết bị an toàn sau cancel (pha 3). Chỉ gặp trong CANCELLING/PAUSING.
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -117,6 +118,28 @@ struct StateMachineConfig
|
||||
/// Số lần lập plan hỏng liên tiếp tối đa. < 0 = không giới hạn (chỉ chặn bằng planner_patience).
|
||||
int max_planning_retries = -1;
|
||||
|
||||
/**
|
||||
* [s] Trần chờ ở kCancelling VÀ kPausing cho tới khi runtime QUIESCENT — thread global planner
|
||||
* idle, recovery idle, action đã trả terminal (cancel) / xác nhận tạm dừng (pause), robot đứng
|
||||
* yên theo vận tốc đo được. <= 0 = tắt: kết thúc ngay khi robot_stopped như trước 2026-09-11
|
||||
* (khi đó CANCELLED/PAUSED có thể được báo trong lúc một lượt makePlan đã huỷ vẫn còn chiếm thread
|
||||
* planner nhiều giây — host tin là xong và gửi goal kế, goal kế bị coi là hỏng).
|
||||
*
|
||||
* Quá trần thì vẫn kết thúc nhưng bên gọi phải log LỖI: có plugin/cấu hình khiến cancel/pause
|
||||
* không dừng được thật.
|
||||
*/
|
||||
double settle_timeout = 2.0;
|
||||
|
||||
/**
|
||||
* [m/s] Ngưỡng coi robot đã dừng theo vận tốc ĐO ĐƯỢC (odom). Chỉ dùng khi bên gọi có odom; đặt
|
||||
* 0 = bỏ qua odom, quay về đo bằng lệnh đã phát (arbiter). Odom nhiễu giữ CANCELLING lâu hơn thì
|
||||
* settle_timeout là trần.
|
||||
*/
|
||||
double stopped_measured_linear_eps = 0.02;
|
||||
|
||||
/// [rad/s] Như @ref stopped_measured_linear_eps cho trục quay.
|
||||
double stopped_measured_angular_eps = 0.02;
|
||||
|
||||
/// Số recovery behavior đã nạp được. 0 = không có đường phục hồi, lỗi là ABORTED ngay.
|
||||
std::size_t recovery_behavior_count = 0;
|
||||
|
||||
@@ -193,9 +216,33 @@ struct StateMachineInput
|
||||
*/
|
||||
bool costmap_current = true;
|
||||
|
||||
/// Robot đã dừng hẳn chưa (|v| <= ngưỡng). Dùng để rời kCancelling.
|
||||
/// Robot đã dừng hẳn chưa (|v| <= ngưỡng). Bên gọi ưu tiên vận tốc ĐO ĐƯỢC (odom), thiếu odom
|
||||
/// thì lấy lệnh đã phát. Một trong ba điều kiện rời kCancelling.
|
||||
bool robot_stopped = true;
|
||||
|
||||
/**
|
||||
* Thread planner còn đang chạy một lượt makePlan (kể cả lượt đã bị huỷ mà plugin không cắt được).
|
||||
*
|
||||
* Điều kiện thứ hai để rời kCancelling: CANCELLED chỉ được báo khi thread này rảnh, nếu không
|
||||
* host tin là xong và gửi goal kế trong lúc `startPlan()` còn bị từ chối. Bên gọi lấy từ
|
||||
* `PlannerPort::isPlanning()`.
|
||||
*/
|
||||
bool planner_busy = false;
|
||||
|
||||
/// Recovery behavior còn đang chạy hoặc đang dừng (kể cả worker thread của detour, pha 2). Bên gọi
|
||||
/// lấy từ bảng trạng thái thành phần. Điều kiện quiescent cùng nhóm với @ref planner_busy.
|
||||
bool recovery_busy = false;
|
||||
|
||||
/**
|
||||
* Action đang chạy đã trả trạng thái terminal sau khi bị `cancel_action` (hoặc không có action).
|
||||
*
|
||||
* Điều kiện thứ ba để rời kCancelling. Chừng nào còn false, state machine tiếp tục `tick_action`
|
||||
* trong kCancelling để handler thiết bị có cơ hội đưa thiết bị về vị trí an toàn rồi báo
|
||||
* `kCancelled` — không cấp vận tốc. Mặc định true: cổng action hiện chưa có handshake (pha 3),
|
||||
* bên gọi truyền true.
|
||||
*/
|
||||
bool action_terminal = true;
|
||||
|
||||
/**
|
||||
* Tuyến phía trước bị chắn (EnvMonitor kUnreachable: không còn đường trong cửa sổ tới điểm thoát, đã
|
||||
* tĩnh đủ `static_on`).
|
||||
@@ -260,6 +307,8 @@ struct StateMachineOutput
|
||||
bool start_action = false; ///< D8: khởi động action thứ @ref action_index của yêu cầu hiện tại.
|
||||
bool tick_action = false; ///< D8: gọi update() của action đang chạy.
|
||||
bool cancel_action = false; ///< D8: yêu cầu action đang chạy dừng an toàn.
|
||||
bool pause_action = false; ///< Báo handler tạm dừng (dịch đồng hồ timeout của nó) — 2026-09-11.
|
||||
bool resume_action = false; ///< Báo handler tiếp tục sau tạm dừng — 2026-09-11.
|
||||
|
||||
/// Chỉ có nghĩa khi @ref start_action — action nào trong danh sách của yêu cầu cần khởi động.
|
||||
std::size_t action_index = 0;
|
||||
@@ -298,6 +347,13 @@ struct StateMachineOutput
|
||||
bool recovery_reset_denied = false;
|
||||
double recovery_reset_travel = 0.0; ///< [m] chỉ có nghĩa khi @ref recovery_reset_denied.
|
||||
|
||||
/**
|
||||
* Cycle này kCancelling → kCancelled hoặc kPausing → kPaused xảy ra vì quá `settle_timeout` chứ
|
||||
* KHÔNG phải vì runtime đã quiescent. Bật đúng MỘT cycle. Bên gọi phải log LỖI (không có khoá
|
||||
* tắt): có plugin không cắt được lượt đang chạy, hoặc odom không bao giờ về 0.
|
||||
*/
|
||||
bool settle_timed_out = 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;
|
||||
|
||||
@@ -369,6 +425,12 @@ public:
|
||||
return action_index_;
|
||||
}
|
||||
|
||||
/// @brief State sẽ quay về sau kPausing/kPaused. Host dùng để giữ tên state cũ trong lúc PAUSING.
|
||||
NavigationState stateBeforePause() const
|
||||
{
|
||||
return state_before_pause_;
|
||||
}
|
||||
|
||||
/// @brief Số lần lập plan hỏng liên tiếp tính từ lần vào kPlanning gần nhất.
|
||||
int planningRetries() const
|
||||
{
|
||||
@@ -423,6 +485,9 @@ private:
|
||||
void finish(NavigationState terminal, NavigationOutcome outcome, const robot::Time& now,
|
||||
const char* reason, StateMachineOutput& out);
|
||||
|
||||
/// @brief Đường resume chung của kPausing và kPaused: gieo lại đồng hồ, về @ref state_before_pause_.
|
||||
void resumeFromPause(const StateMachineInput& in, StateMachineOutput& out);
|
||||
|
||||
/// Cursor của route cho @p trigger trong request hiện hành.
|
||||
std::size_t& recoveryRouteCursor(RecoveryTrigger trigger);
|
||||
const std::size_t& recoveryRouteCursor(RecoveryTrigger trigger) const;
|
||||
|
||||
110
include/move_base2/io/watchdog.h
Normal file
110
include/move_base2/io/watchdog.h
Normal file
@@ -0,0 +1,110 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — watchdog: thread riêng đọc bảng trạng thái thành phần và kết luận "treo".
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef MOVE_BASE2_IO_WATCHDOG_H_
|
||||
#define MOVE_BASE2_IO_WATCHDOG_H_
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
/**
|
||||
* @struct WatchdogConfig
|
||||
* @brief Ngân sách "bận mà không nhích" cho từng thành phần. <= 0 = không giám sát hàng đó.
|
||||
*
|
||||
* "Nhích" = `ComponentStatusBoard::progress()` của chủ hàng. Bận lâu nhưng vẫn nhích là bình thường
|
||||
* (SBPL 4 s vẫn nhích mỗi expand); bận mà không nhích quá ngân sách là treo.
|
||||
*/
|
||||
struct WatchdogConfig
|
||||
{
|
||||
double period = 0.1; ///< [s] chu kỳ kiểm; 0 = tắt watchdog.
|
||||
double planner_timeout = 5.0; ///< [s] kGlobalPlanner — phải > allocated_time × số lượt replan của SBPL.
|
||||
double local_planner_call_budget = 0.5; ///< [s] kLocalPlanner — một lời gọi computeVelocityCommands.
|
||||
double recovery_stall_budget = 5.0; ///< [s] kRecovery.
|
||||
double action_stall_budget = 0.0; ///< [s] kAction — mặc định tắt: handler tự timeout.
|
||||
double control_loop_stall_budget = 0.5; ///< [s] kControlLoop — heartbeat cuối step(); 15 cycle @ 30 Hz.
|
||||
|
||||
bool validate(std::string& error) const;
|
||||
std::string describe() const;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class Watchdog
|
||||
* @brief Phát hiện thành phần treo từ một thread KHÁC thành phần bị nghi.
|
||||
*
|
||||
* Control thread không tự phát hiện được chính nó treo — đó là lý do phải có thread này. Nó chỉ
|
||||
* đọc atomics của @ref ComponentStatusBoard, không lock, không chạm runner; kết luận "treo" giữ
|
||||
* trong cờ riêng của watchdog (một hàng của bảng chỉ có MỘT chủ ghi — watchdog không ghi vào đó).
|
||||
*
|
||||
* Log: `log_error` đúng một lần ở sườn treo (không có khoá tắt), `log_warning` khi hồi.
|
||||
*/
|
||||
class Watchdog
|
||||
{
|
||||
public:
|
||||
Watchdog() = default;
|
||||
~Watchdog();
|
||||
Watchdog(const Watchdog&) = delete;
|
||||
Watchdog& operator=(const Watchdog&) = delete;
|
||||
|
||||
/**
|
||||
* @brief Khởi động thread giám sát. @p board non-owning, phải sống lâu hơn watchdog.
|
||||
* @return false nếu config sai hoặc đã chạy.
|
||||
*/
|
||||
bool start(const ComponentStatusBoard* board, const WatchdogConfig& config, std::string& error);
|
||||
|
||||
void stop();
|
||||
|
||||
bool running() const
|
||||
{
|
||||
return running_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
/// @brief Thành phần @p c đang bị kết luận treo.
|
||||
bool hung(Component c) const
|
||||
{
|
||||
return hung_[static_cast<std::size_t>(c)].load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
bool anyHung() const;
|
||||
|
||||
/// @brief Control thread không nhích quá ngân sách — host phải thấy LOST và tự zero cmd_vel.
|
||||
bool controlLoopHung() const
|
||||
{
|
||||
return hung(Component::kControlLoop);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Chạy MỘT vòng kiểm ngay trên thread gọi (không cần thread riêng) — cho test và cho
|
||||
* host muốn tự tick. Cùng logic với thread nền.
|
||||
*/
|
||||
void checkOnce();
|
||||
|
||||
/// @brief Một dòng tóm tắt các thành phần đang treo, rỗng nếu không có.
|
||||
std::string report() const;
|
||||
|
||||
private:
|
||||
double budgetFor(Component c) const;
|
||||
void threadBody();
|
||||
|
||||
const ComponentStatusBoard* board_ = nullptr;
|
||||
WatchdogConfig config_;
|
||||
std::thread thread_;
|
||||
std::atomic<bool> running_{false};
|
||||
std::array<std::atomic<bool>, ComponentStatusBoard::kRows> hung_{};
|
||||
};
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
#endif // MOVE_BASE2_IO_WATCHDOG_H_
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <move_base2/bridges/mission_adapter_bridge.h>
|
||||
#include <move_base2/bridges/mission_layer.h>
|
||||
#include <move_base2/config/move_base2_config.h>
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/io/runtime_stats.h>
|
||||
#include <move_base2/control_loop.h>
|
||||
#include <move_base2/io/costmap_exporter.h>
|
||||
@@ -276,6 +277,16 @@ public:
|
||||
return stats_.get();
|
||||
}
|
||||
|
||||
/// @brief Bảng trạng thái thành phần — watchdog và host đọc từ đây (chỉ atomic load).
|
||||
const ComponentStatusBoard& components() const
|
||||
{
|
||||
return components_;
|
||||
}
|
||||
ComponentStatusBoard& components()
|
||||
{
|
||||
return components_;
|
||||
}
|
||||
|
||||
robot_costmap_2d::Costmap2DROBOT* globalCostmap()
|
||||
{
|
||||
return global_costmap_.get();
|
||||
@@ -342,6 +353,12 @@ private:
|
||||
/// Dựng trong buildCostmaps() ngay sau khi đọc config, vì nó phải chụp được thread mà costmap tạo.
|
||||
std::unique_ptr<RuntimeStats> stats_;
|
||||
|
||||
/**
|
||||
* Bảng trạng thái thành phần (2026-09-11). Khai TRƯỚC mọi runner để huỷ SAU chúng: runner giữ
|
||||
* con trỏ non-owning và thread lập plan có thể ghi vào bảng cho tới khi PlannerRunner join xong.
|
||||
*/
|
||||
ComponentStatusBoard components_;
|
||||
|
||||
/// Guard "không đi mù": hỏi costmap điều khiển xem observation buffer còn hạn không.
|
||||
CostmapStatusAdapter costmap_status_;
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include <move_base2/core/navigation_request.h>
|
||||
#include <move_base2/io/runtime_stats.h>
|
||||
#include <move_base2/io/sensor_gateway.h>
|
||||
#include <move_base2/io/watchdog.h>
|
||||
#include <robot_sensor_ports/sensor_store.h>
|
||||
#include <move_base2/navigation_runtime.h>
|
||||
|
||||
@@ -246,6 +247,29 @@ public:
|
||||
robot_nav_2d_msgs::Twist2DStamped getTwist() override;
|
||||
|
||||
robot::move_base_core::NavFeedback* getFeedback() override;
|
||||
|
||||
/**
|
||||
* @brief Bảng trạng thái thành phần của runtime (null khi chưa initialize / cổng bơm từ ngoài).
|
||||
*
|
||||
* Cho host (C API `navigation_get_component_status`) và watchdog. Chỉ atomic load — gọi được từ
|
||||
* thread bất kỳ.
|
||||
*/
|
||||
const ComponentStatusBoard* componentStatus() const;
|
||||
|
||||
const Watchdog& watchdog() const
|
||||
{
|
||||
return watchdog_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Khởi động watchdog trên bảng @p board với @p config — test seam (initialize() tự làm
|
||||
* việc này với bảng của runtime).
|
||||
*/
|
||||
bool startWatchdog(const ComponentStatusBoard* board, const WatchdogConfig& config,
|
||||
std::string& error)
|
||||
{
|
||||
return watchdog_.start(board, config, error);
|
||||
}
|
||||
robot::move_base_core::PlannerDataOutput getGlobalData() override;
|
||||
robot::move_base_core::PlannerDataOutput getLocalData() override;
|
||||
|
||||
@@ -367,6 +391,12 @@ private:
|
||||
std::atomic<bool> control_thread_running_{ false };
|
||||
robot::TFListenerPtr tf_;
|
||||
|
||||
/**
|
||||
* Watchdog (2026-09-11): thread riêng đọc bảng trạng thái thành phần của runtime, kết luận treo.
|
||||
* Khai SAU runtime_ (huỷ trước nó) — nó chỉ giữ con trỏ non-owning vào bảng của runtime.
|
||||
*/
|
||||
Watchdog watchdog_;
|
||||
|
||||
/// Bảo vệ dữ liệu sensor và footprint: host ghi từ thread của nó, control loop đọc.
|
||||
mutable std::mutex data_mutex_;
|
||||
|
||||
|
||||
@@ -40,7 +40,8 @@ struct ActionTick
|
||||
{
|
||||
kRunning,
|
||||
kSucceeded,
|
||||
kFailed
|
||||
kFailed,
|
||||
kCancelled ///< Handler đã dừng thiết bị an toàn sau cancel() (pha 3). Terminal.
|
||||
};
|
||||
|
||||
Status status = Status::kRunning;
|
||||
@@ -83,8 +84,25 @@ public:
|
||||
/// @brief Một control cycle. CHỈ được gọi sau khi @ref start trả true.
|
||||
virtual ActionTick update() = 0;
|
||||
|
||||
/// @brief Yêu cầu dừng an toàn action đang chạy (huỷ mission, emergency).
|
||||
/**
|
||||
* @brief Yêu cầu dừng an toàn action đang chạy (huỷ mission, emergency).
|
||||
*
|
||||
* Từ 2026-09-11 có hai kiểu: handler dừng xong ngay trong cancel() (port quên nó, hàng kAction về
|
||||
* idle) hoặc handler cần tick tới khi trả `kCancelled` (port giữ nó, hàng kAction = stopping,
|
||||
* state machine tiếp tục @ref update trong CANCELLING). Bên gọi phân biệt qua bảng trạng thái
|
||||
* thành phần, không qua giá trị trả về.
|
||||
*/
|
||||
virtual void cancel() = 0;
|
||||
|
||||
/// @brief Tạm dừng action đang chạy: handler dịch đồng hồ timeout, KHÔNG dừng thiết bị. Default no-op.
|
||||
virtual void pause()
|
||||
{
|
||||
}
|
||||
|
||||
/// @brief Tiếp tục sau @ref pause. Default no-op.
|
||||
virtual void resume()
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
#include <action_core/action_registry.h>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/ports/action_port.h>
|
||||
#include <move_base2/ports/clock_port.h>
|
||||
|
||||
@@ -86,6 +87,8 @@ public:
|
||||
bool start(const robot_protocol_msgs::Action& action) override;
|
||||
ActionTick update() override;
|
||||
void cancel() override;
|
||||
void pause() override;
|
||||
void resume() override;
|
||||
|
||||
/// @brief Số handler đã nạp.
|
||||
std::size_t handlerCount() const
|
||||
@@ -105,6 +108,18 @@ public:
|
||||
return registry_.find(action_type);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gắn bảng trạng thái thành phần (non-owning, null = không khai).
|
||||
*
|
||||
* Runner là CHỦ hàng `kAction`: kBusy từ @ref start thành công, `progress()` mỗi @ref update,
|
||||
* kIdle khi tick trả terminal hoặc khi @ref cancel (cổng hiện quên handler ngay trong cancel —
|
||||
* pha 3 đổi thành kStopping tới khi handler trả kCancelled).
|
||||
*/
|
||||
void attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
private:
|
||||
/// Dịch kết quả của framework sang kiểu của port.
|
||||
static ActionTick toTick(const action_core::ActionTick& tick);
|
||||
@@ -117,6 +132,7 @@ private:
|
||||
action_core::ActionRegistry registry_;
|
||||
|
||||
action_core::ActionHandler* active_ = nullptr; ///< non-owning, thuộc registry_
|
||||
ComponentStatusBoard* status_board_ = nullptr; ///< non-owning, null = không khai
|
||||
std::string active_action_id_;
|
||||
};
|
||||
|
||||
|
||||
@@ -23,7 +23,9 @@
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot_nav_core/base_global_planner.h>
|
||||
#include <robot_nav_core/preemptable.h>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/io/runtime_stats.h>
|
||||
#include <move_base2/ports/planner_port.h>
|
||||
|
||||
@@ -120,6 +122,15 @@ public:
|
||||
*/
|
||||
void attachStats(RuntimeStats* stats);
|
||||
|
||||
/**
|
||||
* @brief Gắn bảng trạng thái thành phần (non-owning, null = không khai). Gọi trước @ref configure.
|
||||
*
|
||||
* Runner là CHỦ hàng `kGlobalPlanner`: kBusy khi thread bắt đầu makePlan, kStopping khi
|
||||
* @ref cancelPlan tới mà lượt còn chạy, kIdle khi makePlan trả về. Mọi lời ghi đều dưới `mutex_`
|
||||
* nên dù từ hai thread vẫn tuần tự.
|
||||
*/
|
||||
void attachStatusBoard(ComponentStatusBoard* board);
|
||||
|
||||
/**
|
||||
* @brief Tắt việc khoá costmap mutex quanh makePlan — CHỈ dành cho unit test.
|
||||
*
|
||||
@@ -174,6 +185,9 @@ private:
|
||||
/// @brief Thân thread: ngủ tới khi có yêu cầu, chạy plugin, đặt kết quả vào hộp thư.
|
||||
void threadBody();
|
||||
|
||||
/// @brief Gọi `preempt()` trên instance đang ở trong makePlan (nếu nó Preemptable). Gọi dưới mutex_.
|
||||
void preemptRunningLocked();
|
||||
|
||||
// --- Chỉ control thread chạm ------------------------------------------------------------------
|
||||
robot::NodeHandle nh_;
|
||||
robot_costmap_2d::Costmap2DROBOT* costmap_ = nullptr;
|
||||
@@ -184,6 +198,7 @@ private:
|
||||
|
||||
/// Telemetry non-owning, null = tắt đo. Chỉ đọc sau khi @ref attachStats.
|
||||
RuntimeStats* stats_ = nullptr;
|
||||
ComponentStatusBoard* status_board_ = nullptr; ///< Non-owning, null = không khai.
|
||||
RuntimeStats::SectionId section_make_plan_ = RuntimeStats::kInvalidSection;
|
||||
|
||||
std::map<std::string, Loaded> planners_;
|
||||
@@ -213,6 +228,14 @@ private:
|
||||
bool has_result_ = false;
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner* active_ = nullptr; ///< Non-owning, trỏ vào @ref planners_.
|
||||
/**
|
||||
* Instance mà thread lập plan ĐANG ở trong `makePlan` (non-owning, chỉ khác null khi `running_`).
|
||||
*
|
||||
* Khác `active_`: swapPlanner() đổi `active_` ngay cả khi lượt cũ chưa về, nên preempt qua
|
||||
* `active_` sau một lần đổi planner sẽ cắt nhầm instance mới (rảnh) và bỏ sót instance cũ (đang
|
||||
* chạy). Mọi đường cắt — cancelPlan, swapPlanner, destructor — đều đi qua con trỏ này.
|
||||
*/
|
||||
robot_nav_core::BaseGlobalPlanner* running_planner_ = nullptr;
|
||||
robot_geometry_msgs::PoseStamped request_start_;
|
||||
robot_geometry_msgs::PoseStamped request_goal_;
|
||||
std::shared_ptr<robot_protocol_msgs::Order> request_order_;
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
#include <recovery_core/adapters/costmap_collision_checker.h>
|
||||
#include <recovery_core/recovery_registry.h>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/ports/clock_port.h>
|
||||
#include <move_base2/ports/pose_port.h>
|
||||
#include <move_base2/ports/recovery_port.h>
|
||||
@@ -125,6 +126,19 @@ public:
|
||||
void cancel() override;
|
||||
std::string behaviorName(std::size_t index) const override;
|
||||
|
||||
/**
|
||||
* @brief Gắn bảng trạng thái thành phần (non-owning, null = không khai).
|
||||
*
|
||||
* Runner là CHỦ hàng `kRecovery`: kBusy từ @ref start thành công, `progress()` mỗi @ref update,
|
||||
* kIdle khi tick trả terminal hoặc khi @ref cancel — behavior họ velocity/one-shot dừng ngay
|
||||
* trong cùng cycle (arbiter phát 0), behavior có việc chạy dài phải xong việc đó ngay trong
|
||||
* `cancel()` của nó (contract `onCancelRequested()`, pha 2) nên sau cancel() hàng về idle là đúng.
|
||||
*/
|
||||
void attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
private:
|
||||
/// Chuyển `PosePort` của lõi thành cổng pose của recovery_core.
|
||||
class PoseBridge final : public recovery_core::PoseProvider
|
||||
@@ -186,6 +200,7 @@ private:
|
||||
|
||||
bool configured_ = false;
|
||||
recovery_core::RecoveryBehavior* active_ = nullptr; ///< non-owning, thuộc registry_
|
||||
ComponentStatusBoard* status_board_ = nullptr; ///< non-owning, null = không khai
|
||||
|
||||
/// 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_;
|
||||
|
||||
56
src/component_status.cpp
Normal file
56
src/component_status.cpp
Normal file
@@ -0,0 +1,56 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — tên hiển thị cho bảng trạng thái thành phần.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/core/component_status.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
const char* toString(Component component)
|
||||
{
|
||||
switch (component)
|
||||
{
|
||||
case Component::kGlobalPlanner:
|
||||
return "global_planner";
|
||||
case Component::kLocalPlanner:
|
||||
return "local_planner";
|
||||
case Component::kRecovery:
|
||||
return "recovery";
|
||||
case Component::kAction:
|
||||
return "action";
|
||||
case Component::kCostmapGlobal:
|
||||
return "costmap_global";
|
||||
case Component::kCostmapLocal:
|
||||
return "costmap_local";
|
||||
case Component::kControlLoop:
|
||||
return "control_loop";
|
||||
case Component::kCount:
|
||||
break;
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const char* toString(ComponentPhase phase)
|
||||
{
|
||||
switch (phase)
|
||||
{
|
||||
case ComponentPhase::kIdle:
|
||||
return "idle";
|
||||
case ComponentPhase::kBusy:
|
||||
return "busy";
|
||||
case ComponentPhase::kStopping:
|
||||
return "stopping";
|
||||
case ComponentPhase::kPaused:
|
||||
return "paused";
|
||||
case ComponentPhase::kHung:
|
||||
return "hung";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -147,6 +147,12 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
readDouble(nh, "planner_frequency", config.planner_frequency);
|
||||
readDouble(nh, "planner_timeout", config.planner_timeout);
|
||||
readDouble(nh, "runtime_stats_period", config.runtime_stats_period);
|
||||
readDouble(nh, "watchdog_period", config.watchdog.period);
|
||||
readDouble(nh, "local_planner_call_budget", config.watchdog.local_planner_call_budget);
|
||||
readDouble(nh, "recovery_stall_budget", config.watchdog.recovery_stall_budget);
|
||||
readDouble(nh, "action_stall_budget", config.watchdog.action_stall_budget);
|
||||
readDouble(nh, "control_loop_stall_budget", config.watchdog.control_loop_stall_budget);
|
||||
config.watchdog.planner_timeout = config.planner_timeout;
|
||||
|
||||
readDouble(nh, "planner_patience", config.state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", config.state_machine.controller_patience);
|
||||
@@ -157,6 +163,9 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
readDouble(nh, "action_patience", config.state_machine.action_patience);
|
||||
readInt(nh, "max_planning_retries", config.state_machine.max_planning_retries);
|
||||
readBool(nh, "recovery_behavior_enabled", config.state_machine.recovery_enabled);
|
||||
readDouble(nh, "settle_timeout", config.state_machine.settle_timeout);
|
||||
readDouble(nh, "stopped_measured_linear_eps", config.state_machine.stopped_measured_linear_eps);
|
||||
readDouble(nh, "stopped_measured_angular_eps", config.state_machine.stopped_measured_angular_eps);
|
||||
|
||||
// Nghĩa của Twist đi qua arbiter — quyết định đơn vị của cả cụm giới hạn bên dưới. "steering"
|
||||
// (linear.x = tốc độ bánh steer, angular.z = GÓC lái) là convention của robot lái một bánh
|
||||
@@ -426,6 +435,10 @@ bool MoveBase2Config::validate(std::string& error) const
|
||||
error = "planner_timeout is not finite [s]";
|
||||
return false;
|
||||
}
|
||||
if (!watchdog.validate(error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0)
|
||||
{
|
||||
@@ -525,6 +538,7 @@ std::string MoveBase2Config::describe() const
|
||||
out << " planner_timeout: " << planner_timeout << " s\n";
|
||||
out << " runtime_stats_period: " << runtime_stats_period << " s"
|
||||
<< (runtime_stats_period > 0.0 ? "\n" : " (off)\n");
|
||||
out << watchdog.describe();
|
||||
out << " frames: global='" << global_frame << "' base='" << robot_base_frame << "'\n";
|
||||
out << " require_current_costmap: " << (require_current_costmap ? "true" : "false") << "\n";
|
||||
out << " namespaces: recovery='" << recovery_namespace << "' actions='" << action_namespace
|
||||
@@ -571,6 +585,13 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
// Khoá này không có trong schema gen-1 — nó là công cụ chẩn đoán của move_base2. Vẫn đọc ở đây
|
||||
// để bật được telemetry mà không phải chuyển cả cây config sang schema mới.
|
||||
readDouble(nh, "runtime_stats_period", runtime_stats_period);
|
||||
// Watchdog (2026-09-11) — không có trong schema gen-1; thiếu khoá thì default (bật, 0.1 s).
|
||||
readDouble(nh, "watchdog_period", watchdog.period);
|
||||
readDouble(nh, "local_planner_call_budget", watchdog.local_planner_call_budget);
|
||||
readDouble(nh, "recovery_stall_budget", watchdog.recovery_stall_budget);
|
||||
readDouble(nh, "action_stall_budget", watchdog.action_stall_budget);
|
||||
readDouble(nh, "control_loop_stall_budget", watchdog.control_loop_stall_budget);
|
||||
watchdog.planner_timeout = planner_timeout;
|
||||
readDouble(nh, "planner_patience", state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", state_machine.controller_patience);
|
||||
readDouble(nh, "sensor_patience", state_machine.sensor_patience);
|
||||
@@ -578,6 +599,11 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
readDouble(nh, "oscillation_distance", state_machine.oscillation_distance);
|
||||
readInt(nh, "max_planning_retries", state_machine.max_planning_retries);
|
||||
readBool(nh, "recovery_behavior_enabled", state_machine.recovery_enabled);
|
||||
// Không có trong schema gen-1 (bản cũ báo CANCELLED ngay khi lệnh về 0) — đọc để cây config cũ
|
||||
// vẫn bật được chờ quiescent; thiếu khoá thì dùng default (bật, 2 s).
|
||||
readDouble(nh, "settle_timeout", state_machine.settle_timeout);
|
||||
readDouble(nh, "stopped_measured_linear_eps", state_machine.stopped_measured_linear_eps);
|
||||
readDouble(nh, "stopped_measured_angular_eps", state_machine.stopped_measured_angular_eps);
|
||||
|
||||
readString(nh, "global_frame", global_frame);
|
||||
readString(nh, "robot_base_frame", robot_base_frame);
|
||||
|
||||
@@ -654,6 +654,23 @@ void ControlLoop::collectPlannerResult()
|
||||
planner_feedback_ = PlannerFeedback::kPlanReady;
|
||||
}
|
||||
|
||||
bool ControlLoop::robotStopped() const
|
||||
{
|
||||
const StateMachineConfig& sm = config_.state_machine;
|
||||
const bool use_measured = sm.stopped_measured_linear_eps > 0.0 || sm.stopped_measured_angular_eps > 0.0;
|
||||
|
||||
robot_geometry_msgs::Twist measured;
|
||||
if (use_measured && deps_.controller != nullptr && deps_.controller->measuredVelocity(measured))
|
||||
{
|
||||
// Odom đo được thì nó là sự thật về bánh xe; lệnh đã phát chỉ là ý định. NaN từ odom rơi vào
|
||||
// nhánh "chưa dừng" (so sánh với NaN luôn false) — an toàn: settle_timeout là trần.
|
||||
return std::fabs(measured.linear.x) <= sm.stopped_measured_linear_eps &&
|
||||
std::fabs(measured.linear.y) <= sm.stopped_measured_linear_eps &&
|
||||
std::fabs(measured.angular.z) <= sm.stopped_measured_angular_eps;
|
||||
}
|
||||
return arbiter_.stopped();
|
||||
}
|
||||
|
||||
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
|
||||
bool costmap_stale)
|
||||
@@ -841,6 +858,28 @@ void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
|
||||
{
|
||||
candidate = robot_geometry_msgs::Twist();
|
||||
|
||||
// Hàng local_planner của bảng trạng thái: bận trong suốt lượt gọi plugin (đồng bộ, cùng thread),
|
||||
// rảnh khi ra. Watchdog (pha 4) dùng nó để bắt local planner treo — control thread không tự bắt
|
||||
// được chính mình. RAII để mọi đường thoát (kể cả exception từ plugin) đều trả về idle.
|
||||
struct LocalPlannerBusyScope
|
||||
{
|
||||
explicit LocalPlannerBusyScope(ComponentStatusBoard* board) : board_(board)
|
||||
{
|
||||
if (board_ != nullptr)
|
||||
{
|
||||
board_->enter(Component::kLocalPlanner, ComponentPhase::kBusy);
|
||||
}
|
||||
}
|
||||
~LocalPlannerBusyScope()
|
||||
{
|
||||
if (board_ != nullptr)
|
||||
{
|
||||
board_->enter(Component::kLocalPlanner, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
ComponentStatusBoard* board_;
|
||||
} local_planner_busy(deps_.components);
|
||||
|
||||
// Giữ nguyên thứ tự của interface được bọc: hỏi đã tới đích trước, chỉ khi chưa mới tính lệnh.
|
||||
if (deps_.controller->isGoalReached())
|
||||
{
|
||||
@@ -948,7 +987,28 @@ bool ControlLoop::step()
|
||||
input.action_message = action_message_;
|
||||
input.pose_available = pose_available;
|
||||
input.costmap_current = !costmap_stale;
|
||||
input.robot_stopped = arbiter_.stopped();
|
||||
input.robot_stopped = robotStopped();
|
||||
// Điều kiện quiescent của kCancelling/kPausing (2026-09-11). `isPlanning()` là true cả khi lượt
|
||||
// đang chạy đã bị `cancelPlan()` — plugin không cắt được thì thread vẫn bận, và đó chính là thứ
|
||||
// host phải chờ. Bảng trạng thái thành phần (nếu có) bổ sung hàng recovery/action mà cổng không
|
||||
// hỏi được; hàng global_planner của bảng chỉ CỘNG thêm, cổng vẫn là câu hỏi gốc. Action: chưa có
|
||||
// handshake cancelling→cancelled ở cổng (pha 3) — không có bảng thì coi là terminal ngay.
|
||||
{
|
||||
const ComponentStatusBoard* board = deps_.components;
|
||||
input.planner_busy = deps_.planner->isPlanning() ||
|
||||
(board != nullptr && !board->isIdle(Component::kGlobalPlanner));
|
||||
input.recovery_busy = board != nullptr && !board->isIdle(Component::kRecovery);
|
||||
if (board != nullptr)
|
||||
{
|
||||
const ComponentPhase action_phase = board->phase(Component::kAction);
|
||||
input.action_terminal =
|
||||
action_phase == ComponentPhase::kIdle || action_phase == ComponentPhase::kPaused;
|
||||
}
|
||||
else
|
||||
{
|
||||
input.action_terminal = true;
|
||||
}
|
||||
}
|
||||
input.travelled_since_oscillation_reset = travelled;
|
||||
// Bốn cổng của state machine do EnvMonitor cấp (Test/ENV_MONITOR_PLAN.md): cờ chỉ khác false khi
|
||||
// verdict tương ứng có `action: recover`. `off_path` không còn nguồn nào (phép đo cũ đã bỏ 6/9/2026).
|
||||
@@ -980,6 +1040,21 @@ bool ControlLoop::step()
|
||||
}
|
||||
}
|
||||
|
||||
if (output.settle_timed_out)
|
||||
{
|
||||
// LỖI, không có khoá tắt: CANCELLED/PAUSED được báo ra mà runtime CHƯA im hẳn. Host sẽ tin và
|
||||
// gửi goal kế; goal kế chờ được nhờ kBusy, nhưng nguyên nhân gốc (plugin không cắt được
|
||||
// makePlan, odom không về 0, action không trả terminal) phải lộ ra ở đây, kèm thành phần nào.
|
||||
robot::log_error("[move_base2] settle timeout %.1f s while %s (mission %llu): finishing anyway — "
|
||||
"planner_busy=%s recovery_busy=%s action_terminal=%s robot_stopped=%s. A plugin "
|
||||
"is not honouring cancel/pause, or odometry never reads zero.\n",
|
||||
config_.state_machine.settle_timeout,
|
||||
output.state == NavigationState::kPaused ? "PAUSING" : "CANCELLING",
|
||||
static_cast<unsigned long long>(has_active_request_ ? active_request_.mission_sequence_id : 0),
|
||||
input.planner_busy ? "yes" : "no", input.recovery_busy ? "yes" : "no",
|
||||
input.action_terminal ? "yes" : "no", input.robot_stopped ? "yes" : "no");
|
||||
}
|
||||
|
||||
// Cờ một-lần đã được state machine tiêu thụ xong ở lời gọi trên.
|
||||
pause_requested_ = false;
|
||||
resume_requested_ = false;
|
||||
@@ -1182,6 +1257,14 @@ bool ControlLoop::step()
|
||||
{
|
||||
deps_.action->cancel();
|
||||
}
|
||||
if (output.pause_action && deps_.action != nullptr)
|
||||
{
|
||||
deps_.action->pause();
|
||||
}
|
||||
if (output.resume_action && deps_.action != nullptr)
|
||||
{
|
||||
deps_.action->resume();
|
||||
}
|
||||
|
||||
if (output.start_action)
|
||||
{
|
||||
@@ -1214,6 +1297,13 @@ bool ControlLoop::step()
|
||||
robot::log_info("[move_base2] %s\n", tick.message.c_str());
|
||||
}
|
||||
break;
|
||||
case ActionTick::Status::kCancelled:
|
||||
// Handler thiết bị đã về vị trí an toàn sau cancel (pha 3). Chỉ gặp trong CANCELLING/PAUSING;
|
||||
// hàng kAction về idle → quiescent. Một dòng info: đây là sườn kết thúc, không lặp.
|
||||
action_feedback_ = ActionFeedback::kCancelled;
|
||||
robot::log_info("[move_base2] action stopped safely after cancel%s%s\n",
|
||||
tick.message.empty() ? "" : ": ", tick.message.c_str());
|
||||
break;
|
||||
case ActionTick::Status::kFailed:
|
||||
action_feedback_ = ActionFeedback::kFailed;
|
||||
// Handler đã dựng sẵn lý do cụ thể ("thiếu mẫu", "tản quá", "không publish được"). Trước
|
||||
@@ -1365,10 +1455,27 @@ bool ControlLoop::step()
|
||||
}
|
||||
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. 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;
|
||||
// Không khởi động được. Hai nguyên nhân khác hẳn nhau, không được gộp (bài học log
|
||||
// 2026-09-11: cancel lúc SBPL đang chạy, goal kế bị coi là hỏng và ABORTED sau 3 s dù chưa
|
||||
// lập plan lần nào):
|
||||
// - thread planner còn chạy lượt CŨ đã bị cancelPlan() mà plugin không cắt được → BẬN,
|
||||
// cycle sau thử lại; planner_patience vẫn là trần nếu bận quá lâu;
|
||||
// - chưa có planner, pose hỏng... → HỎNG thật, đồng hồ kiên nhẫn/retry chạy như cũ.
|
||||
// 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.
|
||||
if (deps_.planner->isPlanning())
|
||||
{
|
||||
planner_feedback_ = PlannerFeedback::kBusy;
|
||||
robot::log_warning_throttle(5.0,
|
||||
"[move_base2] planner thread still busy with a cancelled attempt; "
|
||||
"waiting for it before planning mission %llu (planner_patience "
|
||||
"%.1f s is the ceiling).\n",
|
||||
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
||||
config_.state_machine.planner_patience);
|
||||
}
|
||||
else
|
||||
{
|
||||
planner_feedback_ = PlannerFeedback::kFailed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1452,6 +1559,14 @@ bool ControlLoop::step()
|
||||
cancel_requested_ = false;
|
||||
}
|
||||
|
||||
// Heartbeat của chính control thread — thứ duy nhất cho watchdog (thread khác) biết vòng điều
|
||||
// khiển còn quay. Đặt ở cuối step(): một cycle kẹt giữa chừng (detour SBPL, plugin treo) không
|
||||
// nhích được mốc này.
|
||||
if (deps_.components != nullptr)
|
||||
{
|
||||
deps_.components->progress(Component::kControlLoop);
|
||||
}
|
||||
|
||||
// false = "yêu cầu hiện tại vừa kết thúc, không còn gì để chạy". Preempt CŨNG báo kết quả (cho
|
||||
// chặng cũ) nhưng ngay lập tức nhận chặng mới — lúc đó runtime vẫn đang chạy, nên không được trả
|
||||
// false. Điều kiện đúng là "vào state terminal", không phải "có báo kết quả".
|
||||
|
||||
213
src/io/watchdog.cpp
Normal file
213
src/io/watchdog.cpp
Normal file
@@ -0,0 +1,213 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — watchdog thành phần treo.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/io/watchdog.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
|
||||
#include <robot/console.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
bool WatchdogConfig::validate(std::string& error) const
|
||||
{
|
||||
const double values[] = {period, planner_timeout, local_planner_call_budget,
|
||||
recovery_stall_budget, action_stall_budget, control_loop_stall_budget};
|
||||
for (double v : values)
|
||||
{
|
||||
if (!std::isfinite(v))
|
||||
{
|
||||
error = "watchdog budgets must be finite [s]";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (period < 0.0)
|
||||
{
|
||||
error = "watchdog_period must be >= 0 [s] (0 = watchdog off)";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string WatchdogConfig::describe() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "Watchdog:\n";
|
||||
out << " period : " << period << " s" << (period > 0.0 ? "" : " (off)") << '\n';
|
||||
const auto line = [&out](const char* name, double v) {
|
||||
out << " " << name << " : " << v << " s" << (v > 0.0 ? "" : " (not watched)") << '\n';
|
||||
};
|
||||
line("planner_timeout ", planner_timeout);
|
||||
line("local_planner_call_budget", local_planner_call_budget);
|
||||
line("recovery_stall_budget ", recovery_stall_budget);
|
||||
line("action_stall_budget ", action_stall_budget);
|
||||
line("control_loop_stall_budget", control_loop_stall_budget);
|
||||
return out.str();
|
||||
}
|
||||
|
||||
Watchdog::~Watchdog()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
bool Watchdog::start(const ComponentStatusBoard* board, const WatchdogConfig& config,
|
||||
std::string& error)
|
||||
{
|
||||
if (board == nullptr)
|
||||
{
|
||||
error = "watchdog needs a component status board";
|
||||
return false;
|
||||
}
|
||||
if (!config.validate(error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (running_.load())
|
||||
{
|
||||
error = "watchdog already running";
|
||||
return false;
|
||||
}
|
||||
board_ = board;
|
||||
config_ = config;
|
||||
for (auto& flag : hung_)
|
||||
{
|
||||
flag.store(false, std::memory_order_relaxed);
|
||||
}
|
||||
if (config_.period <= 0.0)
|
||||
{
|
||||
return true; // Tắt: không thread, checkOnce() vẫn dùng được nếu ai đó tự gọi.
|
||||
}
|
||||
running_.store(true);
|
||||
thread_ = std::thread(&Watchdog::threadBody, this);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Watchdog::stop()
|
||||
{
|
||||
running_.store(false);
|
||||
if (thread_.joinable())
|
||||
{
|
||||
thread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
bool Watchdog::anyHung() const
|
||||
{
|
||||
for (const auto& flag : hung_)
|
||||
{
|
||||
if (flag.load(std::memory_order_relaxed))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
double Watchdog::budgetFor(Component c) const
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case Component::kGlobalPlanner:
|
||||
return config_.planner_timeout;
|
||||
case Component::kLocalPlanner:
|
||||
return config_.local_planner_call_budget;
|
||||
case Component::kRecovery:
|
||||
return config_.recovery_stall_budget;
|
||||
case Component::kAction:
|
||||
return config_.action_stall_budget;
|
||||
case Component::kControlLoop:
|
||||
return config_.control_loop_stall_budget;
|
||||
case Component::kCostmapGlobal:
|
||||
case Component::kCostmapLocal:
|
||||
// Chưa có heartbeat từ map-update thread (cần móc vào gói costmap) — không giám sát ở pha này.
|
||||
return 0.0;
|
||||
case Component::kCount:
|
||||
break;
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
void Watchdog::checkOnce()
|
||||
{
|
||||
if (board_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||
{
|
||||
const Component c = static_cast<Component>(i);
|
||||
const double budget = budgetFor(c);
|
||||
if (budget <= 0.0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const ComponentPhase phase = board_->phase(c);
|
||||
// Hàng heartbeat-only (control loop) không có phase: luôn được coi là "đang chạy". Hàng khác chỉ
|
||||
// xét khi đang có việc — idle/paused không có gì để treo.
|
||||
const bool watched = c == Component::kControlLoop ||
|
||||
phase == ComponentPhase::kBusy || phase == ComponentPhase::kStopping;
|
||||
// Hàng chưa từng nhích (last_progress = 0): runtime mới lên, chưa có gì để so.
|
||||
const bool ever_progressed = board_->at(c).last_progress_ns.load(std::memory_order_relaxed) != 0;
|
||||
const double since = board_->secondsSinceProgress(c);
|
||||
const bool stalled = watched && ever_progressed && since > budget;
|
||||
|
||||
std::atomic<bool>& flag = hung_[i];
|
||||
const bool was_hung = flag.load(std::memory_order_relaxed);
|
||||
if (stalled && !was_hung)
|
||||
{
|
||||
flag.store(true, std::memory_order_relaxed);
|
||||
// LỖI, không có khoá tắt: đây là "một phần của runtime đã chết đứng". In một lần ở sườn.
|
||||
robot::log_error("[move_base2] watchdog: %s is HUNG — phase '%s', no progress for %.2f s "
|
||||
"(budget %.2f s). %s\n",
|
||||
toString(c), toString(phase), since, budget,
|
||||
c == Component::kControlLoop
|
||||
? "The control thread is not cycling: host must treat cmd_vel as stale."
|
||||
: "cancel/pause will hit settle_timeout; the plugin is not returning.");
|
||||
}
|
||||
else if (!stalled && was_hung)
|
||||
{
|
||||
flag.store(false, std::memory_order_relaxed);
|
||||
robot::log_warning("[move_base2] watchdog: %s recovered (phase '%s').\n", toString(c),
|
||||
toString(phase));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string Watchdog::report() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
bool any = false;
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||
{
|
||||
if (hung_[i].load(std::memory_order_relaxed))
|
||||
{
|
||||
const Component c = static_cast<Component>(i);
|
||||
out << (any ? ", " : "") << toString(c) << " hung for "
|
||||
<< (board_ != nullptr ? board_->secondsSinceProgress(c) : 0.0) << " s";
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
return out.str();
|
||||
}
|
||||
|
||||
void Watchdog::threadBody()
|
||||
{
|
||||
const auto period = std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
||||
std::chrono::duration<double>(config_.period));
|
||||
while (running_.load(std::memory_order_relaxed))
|
||||
{
|
||||
checkOnce();
|
||||
std::this_thread::sleep_for(period);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -6,10 +6,12 @@
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
|
||||
#include <move_base_core/component_status_probe.h>
|
||||
#include <move_base_core/navigation.h>
|
||||
|
||||
#include <move_base2/navigation_server.h>
|
||||
@@ -30,6 +32,39 @@ robot::move_base_core::BaseNavigation::Ptr createMoveBase2()
|
||||
return std::make_shared<NavigationServer>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Capability "MoveBaseComponentStatus" (2026-09-11): host dlsym alias này để đọc bảng trạng thái
|
||||
* thành phần + kết luận treo của watchdog, không cần thêm virtual vào BaseNavigation. Chỉ atomic
|
||||
* load — gọi được từ thread bất kỳ, kể cả khi control thread đang treo (đó chính là lúc cần nó).
|
||||
*/
|
||||
std::size_t componentStatusProbe(robot::move_base_core::BaseNavigation* navigation,
|
||||
robot::move_base_core::ComponentStatusEntry* out, std::size_t max)
|
||||
{
|
||||
auto* server = dynamic_cast<NavigationServer*>(navigation);
|
||||
if (server == nullptr)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
const ComponentStatusBoard* board = server->componentStatus();
|
||||
if (board == nullptr)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
const Watchdog& watchdog = server->watchdog();
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows && i < max && out != nullptr; ++i)
|
||||
{
|
||||
const Component c = static_cast<Component>(i);
|
||||
robot::move_base_core::ComponentStatusEntry& e = out[i];
|
||||
std::strncpy(e.name, toString(c), sizeof(e.name) - 1);
|
||||
e.name[sizeof(e.name) - 1] = '\0';
|
||||
e.phase = static_cast<unsigned char>(board->phase(c));
|
||||
e.hung = watchdog.hung(c) ? 1 : 0;
|
||||
e.seconds_in_phase = board->secondsInPhase(c);
|
||||
e.seconds_since_progress = board->secondsSinceProgress(c);
|
||||
}
|
||||
return ComponentStatusBoard::kRows;
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase2)
|
||||
@@ -46,3 +81,6 @@ BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase2)
|
||||
* host. `MoveBase2` giữ lại cho host nào muốn nạp tường minh bản mới.
|
||||
*/
|
||||
BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase)
|
||||
|
||||
// Capability đọc trạng thái thành phần (xem move_base_core/component_status_probe.h).
|
||||
BOOST_DLL_ALIAS(move_base2::componentStatusProbe, MoveBaseComponentStatus)
|
||||
|
||||
@@ -420,6 +420,9 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
||||
// và chính thread đó tự đăng ký nhãn của mình khi bắt đầu chạy.
|
||||
planner_.attachStats(stats_.get());
|
||||
controller_.attachStats(stats_.get());
|
||||
planner_.attachStatusBoard(&components_);
|
||||
recovery_.attachStatusBoard(&components_);
|
||||
action_.attachStatusBoard(&components_);
|
||||
|
||||
// Trước configure(): planner nạp trong configure() và có thể muốn đọc cảm biến ngay trong
|
||||
// initialize() của nó.
|
||||
@@ -626,6 +629,7 @@ ControlLoopDeps NavigationRuntime::deps()
|
||||
deps.action = &action_;
|
||||
deps.costmap_status = &costmap_status_;
|
||||
deps.environment = &environment_;
|
||||
deps.components = &components_;
|
||||
return deps;
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ NavigationServer::~NavigationServer()
|
||||
|
||||
void NavigationServer::shutdown()
|
||||
{
|
||||
watchdog_.stop();
|
||||
stopControlThread();
|
||||
if (runtime_ != nullptr)
|
||||
{
|
||||
@@ -60,6 +61,11 @@ void NavigationServer::shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
const ComponentStatusBoard* NavigationServer::componentStatus() const
|
||||
{
|
||||
return runtime_ != nullptr ? &runtime_->components() : nullptr;
|
||||
}
|
||||
|
||||
bool NavigationServer::startControlThread(double frequency)
|
||||
{
|
||||
if (!loop_.initialized())
|
||||
@@ -284,6 +290,10 @@ robot::move_base_core::State NavigationServer::toHostState(NavigationState state
|
||||
// VDA5050 đang suy `driving = true` từ CONTROLLING (amr_vda_5050_client_api.cpp:1233), mà
|
||||
// robot lúc này đứng yên làm action; báo "đang chạy" cho fleet master là báo sai.
|
||||
return HostState::ACTIVE;
|
||||
case NavigationState::kPausing:
|
||||
// Không tới được từ refreshFeedback(): PAUSING được thay bằng state TRƯỚC pause ở đó (host chỉ
|
||||
// thấy PAUSED khi runtime đã im hẳn — 2026-09-11). Giữ case để switch đủ nhánh.
|
||||
return HostState::PAUSED;
|
||||
case NavigationState::kPaused:
|
||||
return HostState::PAUSED;
|
||||
case NavigationState::kCancelling:
|
||||
@@ -344,7 +354,16 @@ void NavigationServer::reportSensorStore()
|
||||
|
||||
void NavigationServer::refreshFeedback()
|
||||
{
|
||||
robot::move_base_core::State host_state = toHostState(loop_.state());
|
||||
// PAUSING nói thật (2026-09-11): pause đã nhận, lệnh = 0, nhưng thread planner/recovery/action
|
||||
// chưa im — host vẫn thấy tên state trước (PLANNING/CONTROLLING/CLEARING/ACTIVE) kèm
|
||||
// feed_back_str "pausing…"; PAUSED chỉ khi đã im hẳn. Host đọc PAUSED là "dừng rồi, làm gì cũng
|
||||
// được" — báo sớm là nói dối cùng kiểu với PREEMPTED cũ.
|
||||
NavigationState core_state = loop_.state();
|
||||
if (core_state == NavigationState::kPausing)
|
||||
{
|
||||
core_state = loop_.stateBeforePause();
|
||||
}
|
||||
robot::move_base_core::State host_state = toHostState(core_state);
|
||||
|
||||
// Một order nhiều chặng: lõi về SUCCEEDED sau MỖI chặng, còn order thì chưa xong. Host suy "order
|
||||
// hoàn thành" thẳng từ SUCCEEDED (amr_vda_5050_client_api.cpp:1062, 1092), nên báo nguyên trạng
|
||||
@@ -588,6 +607,16 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
|
||||
return;
|
||||
}
|
||||
|
||||
// Watchdog sau control thread: hàng control_loop chỉ có nghĩa khi thread đó đã quay. Watchdog
|
||||
// hỏng không phải lý do từ chối runtime — log rồi chạy tiếp không có nó.
|
||||
{
|
||||
std::string watchdog_error;
|
||||
if (!watchdog_.start(&runtime_->components(), runtime_->config().watchdog, watchdog_error))
|
||||
{
|
||||
robot::log_error("[move_base2] watchdog not started: %s\n", watchdog_error.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
nav_feedback_->is_ready = true;
|
||||
nav_feedback_->feed_back_str = "ready";
|
||||
refreshFeedback();
|
||||
@@ -1179,6 +1208,16 @@ robot_nav_2d_msgs::Twist2DStamped NavigationServer::getTwist()
|
||||
|
||||
robot::move_base_core::NavFeedback* NavigationServer::getFeedback()
|
||||
{
|
||||
// Control thread treo thì refreshFeedback() không chạy nữa và host sẽ đọc mãi state cuối cùng —
|
||||
// một CONTROLLING đóng băng trông y hệt một CONTROLLING đang chạy. Watchdog (thread riêng) là
|
||||
// nguồn duy nhất còn nói được; ghi đè ở đây, trên thread host. `LOST` là giá trị có sẵn trong
|
||||
// move_base_core::State, chưa ai dùng, nghĩa đúng: "lõi không còn theo dõi được goal".
|
||||
// Host đọc LOST phải tự zero cmd_vel (nav_c_api_2.h mục 6 đã bắt kiểm stamp của twist).
|
||||
if (watchdog_.controlLoopHung())
|
||||
{
|
||||
nav_feedback_->navigation_state = robot::move_base_core::State::LOST;
|
||||
nav_feedback_->feed_back_str = "control thread stalled: " + watchdog_.report();
|
||||
}
|
||||
return nav_feedback_.get();
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ const char* toString(NavigationState state)
|
||||
return "RECOVERING";
|
||||
case NavigationState::kExecutingActions:
|
||||
return "EXECUTING_ACTIONS";
|
||||
case NavigationState::kPausing:
|
||||
return "PAUSING";
|
||||
case NavigationState::kPaused:
|
||||
return "PAUSED";
|
||||
case NavigationState::kCancelling:
|
||||
|
||||
@@ -52,6 +52,9 @@ ActionTick ActionRunner::toTick(const action_core::ActionTick& tick)
|
||||
case action_core::ActionStatus::kSucceeded:
|
||||
out.status = ActionTick::Status::kSucceeded;
|
||||
break;
|
||||
case action_core::ActionStatus::kCancelled:
|
||||
out.status = ActionTick::Status::kCancelled;
|
||||
break;
|
||||
case action_core::ActionStatus::kFailed:
|
||||
out.status = ActionTick::Status::kFailed;
|
||||
break;
|
||||
@@ -131,6 +134,10 @@ bool ActionRunner::start(const robot_protocol_msgs::Action& action)
|
||||
|
||||
active_ = handler;
|
||||
active_action_id_ = action.actionId;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kBusy);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -151,17 +158,74 @@ ActionTick ActionRunner::update()
|
||||
if (tick.status != ActionTick::Status::kRunning)
|
||||
{
|
||||
active_ = nullptr;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
else if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->progress(Component::kAction);
|
||||
}
|
||||
|
||||
return tick;
|
||||
}
|
||||
|
||||
void ActionRunner::cancel()
|
||||
{
|
||||
if (active_ == nullptr)
|
||||
{
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
active_->cancel();
|
||||
|
||||
if (active_->cancelNeedsTicks())
|
||||
{
|
||||
// Handler thiết bị (2026-09-11): cancel() mới RA LỆNH dừng; giữ handler, tick tiếp trong
|
||||
// CANCELLING/PAUSING tới khi nó trả kCancelled/terminal. Hàng kAction = stopping cho tới lúc đó
|
||||
// — CANCELLED/PAUSED không được báo ra host trong lúc thiết bị còn đang về vị trí an toàn.
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kStopping);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handler perception/no-op: dừng xong ngay trong cancel(), quên nó, hàng về idle.
|
||||
active_ = nullptr;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
void ActionRunner::pause()
|
||||
{
|
||||
if (active_ != nullptr)
|
||||
{
|
||||
active_->cancel();
|
||||
active_ = nullptr;
|
||||
active_->pause(clock_->now());
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
// kPaused là "đã xác nhận tạm dừng": điều kiện quiescent của PAUSING chấp nhận nó.
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kPaused);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ActionRunner::resume()
|
||||
{
|
||||
if (active_ != nullptr)
|
||||
{
|
||||
active_->resume(clock_->now());
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kBusy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ PlannerRunner::~PlannerRunner()
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
shutdown_ = true;
|
||||
discard_ = true;
|
||||
preemptRunningLocked(); // shutdown không phải chờ hết allocated_time của lượt dở
|
||||
}
|
||||
cv_.notify_all();
|
||||
|
||||
@@ -102,6 +103,11 @@ PlannerRunner::~PlannerRunner()
|
||||
}
|
||||
}
|
||||
|
||||
void PlannerRunner::attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
void PlannerRunner::attachStats(RuntimeStats* stats)
|
||||
{
|
||||
stats_ = stats;
|
||||
@@ -366,11 +372,25 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
// Lượt đang chạy thuộc về planner cũ — kết quả của nó không còn nghĩa. Không cắt ngang được
|
||||
// phép tính, chỉ đánh dấu vứt kết quả. Con trỏ planner cũ vẫn hợp lệ vì cache không xoá entry.
|
||||
if (running_ || pending_)
|
||||
// Lượt đang chạy thuộc về planner cũ — kết quả của nó không còn nghĩa: đánh dấu vứt, và cắt
|
||||
// nếu plugin Preemptable. Con trỏ planner cũ vẫn hợp lệ vì cache không xoá entry.
|
||||
if (pending_ && !running_)
|
||||
{
|
||||
// Thread chưa nhận: rút yêu cầu ra, kẻo nó chạy yêu cầu của planner cũ trên instance mới rồi
|
||||
// vứt — tốn một lượt makePlan vô ích.
|
||||
pending_ = false;
|
||||
request_order_.reset();
|
||||
}
|
||||
else if (running_)
|
||||
{
|
||||
discard_ = true;
|
||||
// Lượt cũ vẫn chiếm thread; cắt nó ngay để yêu cầu kế (dùng planner mới) không phải chờ
|
||||
// planner_patience. Phải cắt TRƯỚC khi đổi active_ — sau dòng dưới active_ đã là instance mới.
|
||||
preemptRunningLocked();
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||
}
|
||||
}
|
||||
active_ = planner;
|
||||
}
|
||||
@@ -463,12 +483,49 @@ bool PlannerRunner::pollPlan(PlanResult& result)
|
||||
return true;
|
||||
}
|
||||
|
||||
void PlannerRunner::preemptRunningLocked()
|
||||
{
|
||||
// Gọi dưới mutex_. `running_planner_` là instance thread đang ở trong makePlan — KHÔNG phải
|
||||
// `active_`, vì swapPlanner có thể đã trỏ active_ sang instance khác trong lúc lượt cũ chưa về.
|
||||
// Instance cũ được cache/retired giữ sống nên con trỏ còn hợp lệ suốt lượt; preempt() là một
|
||||
// atomic store, gọi được từ control thread. Plugin không Preemptable: không có gì để làm.
|
||||
if (running_planner_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (auto* preemptable = dynamic_cast<robot_nav_core::Preemptable*>(running_planner_))
|
||||
{
|
||||
preemptable->preempt();
|
||||
}
|
||||
}
|
||||
|
||||
void PlannerRunner::cancelPlan()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (pending_ || running_)
|
||||
if (pending_ && !running_)
|
||||
{
|
||||
// Lượt đã được xếp nhưng thread chưa kịp nhận (cửa sổ giữa startPlan() và lúc thread thức dậy).
|
||||
// Rút nó ra khỏi hàng đợi là đủ — không có gì để preempt, và nếu chỉ đặt discard_ thì thread
|
||||
// sẽ nhận job này NGAY SAU cancel, chạy trọn allocated_time cho một plan không ai cần (bắt được
|
||||
// bằng test CancelPreemptsAPreemptablePlannerWithinMilliseconds, 2026-09-11).
|
||||
pending_ = false;
|
||||
request_order_.reset();
|
||||
}
|
||||
else if (pending_ || running_)
|
||||
{
|
||||
discard_ = true;
|
||||
if (running_)
|
||||
{
|
||||
// Cắt thật (2026-09-11): plugin implement robot_nav_core::Preemptable thì lượt makePlan đang
|
||||
// chạy thoát trong vài ms thay vì đi tới hết allocated_time. Plugin cũ (không Preemptable)
|
||||
// thì chỉ còn discard_ như trước — kết quả về bị vứt, thread bận tới khi nó xong.
|
||||
preemptRunningLocked();
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
// Thread vẫn ở trong makePlan; từ giờ tới lúc nó trả về là "đang dừng", không phải "bận".
|
||||
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Kết quả đã nằm sẵn trong hộp thư cũng bỏ luôn: bên gọi vừa nói nó không còn cần plan này.
|
||||
has_result_ = false;
|
||||
@@ -501,6 +558,7 @@ void PlannerRunner::threadBody()
|
||||
// Chụp lại yêu cầu rồi NHẢ MUTEX trước khi gọi plugin. Đây là điểm mấu chốt của cả mô hình:
|
||||
// control thread không bao giờ phải chờ một lượt lập plan.
|
||||
robot_nav_core::BaseGlobalPlanner* planner = active_;
|
||||
running_planner_ = planner;
|
||||
const robot_geometry_msgs::PoseStamped start = request_start_;
|
||||
const robot_geometry_msgs::PoseStamped goal = request_goal_;
|
||||
const std::shared_ptr<robot_protocol_msgs::Order> order = request_order_;
|
||||
@@ -508,6 +566,10 @@ void PlannerRunner::threadBody()
|
||||
|
||||
pending_ = false;
|
||||
running_ = true;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||
}
|
||||
|
||||
lock.unlock();
|
||||
|
||||
@@ -558,6 +620,11 @@ void PlannerRunner::threadBody()
|
||||
|
||||
lock.lock();
|
||||
running_ = false;
|
||||
running_planner_ = nullptr;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
if (discard_)
|
||||
{
|
||||
|
||||
@@ -408,6 +408,10 @@ bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
|
||||
active_ = behavior;
|
||||
active_name_ = registry_.nameAt(index);
|
||||
active_trigger_ = trigger;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kRecovery, ComponentPhase::kBusy);
|
||||
}
|
||||
|
||||
// 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Ừ
|
||||
@@ -434,6 +438,17 @@ RecoveryTick RecoveryRunner::update()
|
||||
|
||||
refreshContext();
|
||||
const RecoveryTick result = toTick(active_->update(deps_.clock->now()));
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
if (result.status == RecoveryTick::Status::kRunning)
|
||||
{
|
||||
status_board_->progress(Component::kRecovery);
|
||||
}
|
||||
else
|
||||
{
|
||||
status_board_->enter(Component::kRecovery, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
// 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).
|
||||
//
|
||||
@@ -465,6 +480,13 @@ void RecoveryRunner::cancel()
|
||||
{
|
||||
active_->cancel();
|
||||
}
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
// Sau cancel() behavior không được tick nữa (CANCELLING ép tick_recovery=false): hàng phải về
|
||||
// idle ngay ở đây, không có tick nào sau để làm việc đó. Behavior có việc chạy dài (detour
|
||||
// worker) phải kết thúc việc đó bên trong cancel() của nó — xem RecoveryBehavior::onCancelRequested.
|
||||
status_board_->enter(Component::kRecovery, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
RecoveryTick RecoveryRunner::toTick(const recovery_core::RecoveryResult& result) const
|
||||
|
||||
@@ -49,6 +49,18 @@ bool StateMachineConfig::validate(std::string& error) const
|
||||
"route cursor is refilled anyway, so a larger value can never take effect";
|
||||
return false;
|
||||
}
|
||||
if (settle_timeout < 0.0)
|
||||
{
|
||||
error = "settle_timeout must be >= 0 [s] (0 = finish CANCELLING/PAUSING as soon as the command "
|
||||
"is zero, without waiting for the planner thread)";
|
||||
return false;
|
||||
}
|
||||
if (stopped_measured_linear_eps < 0.0 || stopped_measured_angular_eps < 0.0)
|
||||
{
|
||||
error = "stopped_measured_linear_eps [m/s] and stopped_measured_angular_eps [rad/s] must be "
|
||||
">= 0 (0 = ignore odometry, judge 'stopped' from the issued command)";
|
||||
return false;
|
||||
}
|
||||
if (planner_patience <= 0.0 && max_planning_retries < 0)
|
||||
{
|
||||
// Từ khi lập plan chạy trên thread riêng, hai tham số này là thứ DUY NHẤT phát hiện được planner
|
||||
@@ -121,6 +133,15 @@ std::string StateMachineConfig::describe() const
|
||||
<< '\n';
|
||||
out << " max_planning_retries : " << max_planning_retries
|
||||
<< (max_planning_retries < 0 ? " (unlimited)" : "") << '\n';
|
||||
out << " settle_timeout : " << settle_timeout << " s"
|
||||
<< (settle_timeout > 0.0 ? "" : " (off — CANCELLED/PAUSED as soon as the command is zero)")
|
||||
<< '\n';
|
||||
out << " stopped_measured_eps : " << stopped_measured_linear_eps << " m/s, "
|
||||
<< stopped_measured_angular_eps << " rad/s"
|
||||
<< (stopped_measured_linear_eps > 0.0 || stopped_measured_angular_eps > 0.0
|
||||
? ""
|
||||
: " (off — 'stopped' judged from the issued command)")
|
||||
<< '\n';
|
||||
out << " recovery_enabled : " << (recovery_enabled ? "true" : "false") << '\n';
|
||||
out << " recovery_behavior_cnt : " << recovery_behavior_count << '\n';
|
||||
if (recovery_routes.empty())
|
||||
@@ -389,6 +410,45 @@ bool StateMachine::preemptIfRequested(const StateMachineInput& in, StateMachineO
|
||||
return true;
|
||||
}
|
||||
|
||||
void StateMachine::resumeFromPause(const StateMachineInput& in, StateMachineOutput& out)
|
||||
{
|
||||
// Đặt lại toàn bộ đồng hồ kiên nhẫn: một lần tạm dừng dài không được tính là "planner chậm"
|
||||
// hay "controller hỏng", nếu không thì resume xong là rơi thẳng vào recovery.
|
||||
beginPlanningCycle(in.now);
|
||||
last_valid_control_ = in.now;
|
||||
last_oscillation_reset_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
out.reset_oscillation_origin = true;
|
||||
travel_at_last_path_reset_ = 0.0; // origin đặt lại -> mốc recovery_reset_min_travel về 0
|
||||
|
||||
if (state_before_pause_ == NavigationState::kControlling)
|
||||
{
|
||||
// Nạp lại plan cho controller trước khi bám tiếp (2026-09-11). Local planner giữ trạng
|
||||
// thái nội bộ theo thời gian (warm-start trajectory, slew, latch) từ lúc robot còn chạy;
|
||||
// sau một quãng đứng yên trạng thái đó là của một robot khác. `setPlan` là đường reset
|
||||
// duy nhất mà interface LocalPlanner có — plugin reset warm-start theo pose hiện tại ở
|
||||
// đó. Bên gọi giữ nguyên plan mới nhất (`latest_plan_`) suốt lúc tạm dừng.
|
||||
out.apply_plan = true;
|
||||
out.run_controller = true;
|
||||
enter(NavigationState::kControlling, in.now, "resume following the plan", out);
|
||||
}
|
||||
else if (state_before_pause_ == NavigationState::kExecutingActions)
|
||||
{
|
||||
// Action không bị huỷ khi tạm dừng nên không start lại — tick tiếp đúng action dở dang.
|
||||
// Mốc action_patience được gieo lại: một quãng dừng dài không được tính vào trần thời
|
||||
// gian của action, nếu không resume xong là ABORTED oan ngay lập tức.
|
||||
action_started_at_ = in.now;
|
||||
out.resume_action = true; // Handler cộng quãng dừng vào mốc timeout của nó.
|
||||
out.tick_action = true;
|
||||
enter(NavigationState::kExecutingActions, in.now, "resume running the action", out);
|
||||
}
|
||||
else
|
||||
{
|
||||
out.start_planner = true;
|
||||
enter(NavigationState::kPlanning, in.now, "resume planning", out);
|
||||
}
|
||||
}
|
||||
|
||||
StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
StateMachineOutput out;
|
||||
@@ -442,7 +502,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
state_before_pause_ = NavigationState::kPlanning;
|
||||
enter(NavigationState::kPaused, in.now, "paused while planning", out);
|
||||
enter(NavigationState::kPausing, in.now, "pausing while planning", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -519,7 +579,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
state_before_pause_ = NavigationState::kControlling;
|
||||
enter(NavigationState::kPaused, in.now, "paused while following the plan", out);
|
||||
enter(NavigationState::kPausing, in.now, "pausing while following the plan", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -716,7 +776,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// dài là không an toàn (nó dead-reckon theo thời gian). Resume sẽ lập plan lại từ đầu.
|
||||
out.cancel_recovery = true;
|
||||
state_before_pause_ = NavigationState::kPlanning;
|
||||
enter(NavigationState::kPaused, in.now, "paused while recovering", out);
|
||||
enter(NavigationState::kPausing, in.now, "pausing while recovering", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -856,12 +916,14 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// dead-reckon, còn chạy lại một action thiết bị (nâng/hạ, sạc) từ đầu thì không chắc an
|
||||
// toàn — action không idempotent. Tạm dừng chỉ ngừng tick; resume tick tiếp đúng action đó.
|
||||
state_before_pause_ = NavigationState::kExecutingActions;
|
||||
enter(NavigationState::kPaused, in.now, "paused while running an action", out);
|
||||
out.pause_action = true; // Handler dịch mốc timeout của nó; không dừng thiết bị.
|
||||
enter(NavigationState::kPausing, in.now, "pausing while running an action", out);
|
||||
break;
|
||||
}
|
||||
|
||||
if (in.action == ActionFeedback::kFailed)
|
||||
if (in.action == ActionFeedback::kFailed || in.action == ActionFeedback::kCancelled)
|
||||
{
|
||||
// kCancelled ở đây là lỗi thứ tự gọi (không ai cancel trong EXECUTING_ACTIONS) — xử như hỏng.
|
||||
// Action hỏng không có đường recovery: recovery behavior là công cụ phục hồi NAVIGATION
|
||||
// (dọn costmap, lùi, xoay), không giúp gì được một thiết bị đang hỏng. Kết thúc tường minh
|
||||
// để mission layer quyết định làm gì với phần còn lại của order.
|
||||
@@ -909,6 +971,58 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
break;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------
|
||||
case NavigationState::kPausing:
|
||||
{
|
||||
// Đã nhận pause: stop_planner / cancel_recovery / pause_action đã phát ở cycle vào state,
|
||||
// arbiter đang phát 0. Ở đây chỉ chờ mọi thành phần IM rồi mới sang kPaused — host đọc
|
||||
// PAUSED là "đã dừng hẳn, làm gì cũng được" (2026-09-11). Cùng ba điều kiện quiescent với
|
||||
// kCancelling; `settle_timeout` là trần.
|
||||
if (preemptIfRequested(in, out))
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (in.cancel_requested)
|
||||
{
|
||||
enter(NavigationState::kCancelling, in.now, "cancelled while pausing", out);
|
||||
break;
|
||||
}
|
||||
if (in.resume_requested)
|
||||
{
|
||||
// Chưa kịp dừng hẳn đã được bảo chạy tiếp: đi đúng đường resume của kPaused.
|
||||
resumeFromPause(in, out);
|
||||
break;
|
||||
}
|
||||
|
||||
if (config_.settle_timeout <= 0.0)
|
||||
{
|
||||
if (in.robot_stopped)
|
||||
{
|
||||
enter(NavigationState::kPaused, in.now, "paused: robot stopped", out);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const bool quiescent = in.robot_stopped && !in.planner_busy && !in.recovery_busy && in.action_terminal;
|
||||
if (quiescent)
|
||||
{
|
||||
enter(NavigationState::kPaused, in.now, "paused: runtime quiescent", out);
|
||||
break;
|
||||
}
|
||||
if (secondsInState(in.now) > config_.settle_timeout)
|
||||
{
|
||||
out.settle_timed_out = true;
|
||||
enter(NavigationState::kPaused, in.now, "paused: settle timeout", out);
|
||||
break;
|
||||
}
|
||||
// Action đã được bảo tạm dừng ở cycle vào state; tick tiếp cho handler thiết bị xác nhận.
|
||||
if (!in.action_terminal)
|
||||
{
|
||||
out.tick_action = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------
|
||||
case NavigationState::kPaused:
|
||||
{
|
||||
@@ -926,34 +1040,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
}
|
||||
if (in.resume_requested)
|
||||
{
|
||||
// Đặt lại toàn bộ đồng hồ kiên nhẫn: một lần tạm dừng dài không được tính là "planner chậm"
|
||||
// hay "controller hỏng", nếu không thì resume xong là rơi thẳng vào recovery.
|
||||
beginPlanningCycle(in.now);
|
||||
last_valid_control_ = in.now;
|
||||
last_oscillation_reset_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
out.reset_oscillation_origin = true;
|
||||
travel_at_last_path_reset_ = 0.0; // origin đặt lại -> mốc recovery_reset_min_travel về 0
|
||||
|
||||
if (state_before_pause_ == NavigationState::kControlling)
|
||||
{
|
||||
out.run_controller = true;
|
||||
enter(NavigationState::kControlling, in.now, "resume following the plan", out);
|
||||
}
|
||||
else if (state_before_pause_ == NavigationState::kExecutingActions)
|
||||
{
|
||||
// Action không bị huỷ khi tạm dừng nên không start lại — tick tiếp đúng action dở dang.
|
||||
// Mốc action_patience được gieo lại: một quãng dừng dài không được tính vào trần thời
|
||||
// gian của action, nếu không resume xong là ABORTED oan ngay lập tức.
|
||||
action_started_at_ = in.now;
|
||||
out.tick_action = true;
|
||||
enter(NavigationState::kExecutingActions, in.now, "resume running the action", out);
|
||||
}
|
||||
else
|
||||
{
|
||||
out.start_planner = true;
|
||||
enter(NavigationState::kPlanning, in.now, "resume planning", out);
|
||||
}
|
||||
resumeFromPause(in, out);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -962,12 +1049,44 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
case NavigationState::kCancelling:
|
||||
{
|
||||
// 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)
|
||||
// nguồn là kNone — xem VelocityArbiter::arbitrate). Lệnh 0 là điều kiện CẦN, chưa đủ để
|
||||
// báo CANCELLED (2026-09-11): host đọc CANCELLED/PREEMPTED là "đã xong, gửi goal kế được"
|
||||
// — mà goal kế bị `startPlan()` từ chối chừng nào thread planner còn chạy lượt cũ, và bị
|
||||
// tính là hỏng. Ba điều kiện quiescent: lệnh/odom về 0, thread planner rảnh, action đã trả
|
||||
// terminal. `settle_timeout` là trần: quá thì vẫn CANCELLED nhưng báo lỗi lên bên gọi.
|
||||
if (config_.settle_timeout <= 0.0)
|
||||
{
|
||||
// Tắt: hành vi trước 2026-09-11 — chỉ chờ lệnh về 0.
|
||||
if (in.robot_stopped)
|
||||
{
|
||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||
"robot came to a full stop", out);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const bool quiescent = in.robot_stopped && !in.planner_busy && !in.recovery_busy && in.action_terminal;
|
||||
if (quiescent)
|
||||
{
|
||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||
"robot came to a full stop", out);
|
||||
"robot stopped, planner and recovery idle, action terminal", out);
|
||||
break;
|
||||
}
|
||||
|
||||
if (secondsInState(in.now) > config_.settle_timeout)
|
||||
{
|
||||
out.settle_timed_out = true;
|
||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||
"cancel settle timeout", out);
|
||||
break;
|
||||
}
|
||||
|
||||
// Action đã bị bảo dừng ở cycle vào kCancelling; tick tiếp để handler thiết bị đưa thiết bị
|
||||
// về vị trí an toàn rồi báo terminal. Không cấp vận tốc — phần chốt bất biến cuối hàm ép
|
||||
// velocity_source về kNone cho mọi state phải dừng.
|
||||
if (!in.action_terminal)
|
||||
{
|
||||
out.tick_action = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <robot/node_handle.h>
|
||||
|
||||
#include <action_core/action_handler.h>
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/runners/action_runner.h>
|
||||
|
||||
#include "fake_ports.h"
|
||||
@@ -69,6 +70,17 @@ public:
|
||||
{
|
||||
++update_count;
|
||||
action_core::ActionTick tick;
|
||||
if (ticks_after_cancel_left >= 0)
|
||||
{
|
||||
if (ticks_after_cancel_left-- > 0)
|
||||
{
|
||||
tick.status = action_core::ActionStatus::kRunning;
|
||||
return tick;
|
||||
}
|
||||
tick.status = action_core::ActionStatus::kCancelled;
|
||||
tick.message = "device safe";
|
||||
return tick;
|
||||
}
|
||||
tick.status = next_status;
|
||||
return tick;
|
||||
}
|
||||
@@ -76,15 +88,46 @@ public:
|
||||
void cancel() override
|
||||
{
|
||||
++cancel_count;
|
||||
if (cancel_needs_ticks)
|
||||
{
|
||||
ticks_after_cancel_left = cancel_ticks;
|
||||
next_status = action_core::ActionStatus::kRunning;
|
||||
}
|
||||
}
|
||||
|
||||
bool cancelNeedsTicks() const override
|
||||
{
|
||||
return cancel_needs_ticks;
|
||||
}
|
||||
|
||||
void pause(const robot::Time& now) override
|
||||
{
|
||||
++pause_count;
|
||||
last_pause_at = now;
|
||||
}
|
||||
|
||||
void resume(const robot::Time& now) override
|
||||
{
|
||||
++resume_count;
|
||||
last_resume_at = now;
|
||||
}
|
||||
|
||||
bool configure_ok = true;
|
||||
bool start_ok = true;
|
||||
action_core::ActionStatus next_status = action_core::ActionStatus::kRunning;
|
||||
|
||||
/// Mô hình handler thiết bị: sau cancel() còn `cancel_ticks` lượt update() rồi mới kCancelled.
|
||||
bool cancel_needs_ticks = false;
|
||||
int cancel_ticks = 2;
|
||||
int ticks_after_cancel_left = -1;
|
||||
|
||||
int start_count = 0;
|
||||
int update_count = 0;
|
||||
int cancel_count = 0;
|
||||
int pause_count = 0;
|
||||
int resume_count = 0;
|
||||
robot::Time last_pause_at;
|
||||
robot::Time last_resume_at;
|
||||
std::string last_action_id;
|
||||
|
||||
private:
|
||||
@@ -248,6 +291,100 @@ TEST(ActionRunner, CancelReachesHandlerAndClearsActive)
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed);
|
||||
}
|
||||
|
||||
TEST(ActionRunner, DeviceHandlerKeepsBeingTickedAfterCancelUntilItReportsCancelled)
|
||||
{
|
||||
// Pha 3 (2026-09-11): handler khai cancelNeedsTicks → runner GIỮ nó sau cancel(), tick tiếp tới
|
||||
// khi trả kCancelled; hàng kAction = stopping trong lúc đó, idle khi xong.
|
||||
Rig rig;
|
||||
move_base2::ComponentStatusBoard board;
|
||||
rig.runner.attachStatusBoard(&board);
|
||||
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"lift"});
|
||||
handler->cancel_needs_ticks = true;
|
||||
handler->cancel_ticks = 2;
|
||||
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||
ASSERT_TRUE(rig.load("actions_empty"));
|
||||
ASSERT_TRUE(rig.runner.start(makeAction("lift")));
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kBusy);
|
||||
|
||||
rig.runner.cancel();
|
||||
EXPECT_EQ(handler->cancel_count, 1);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kStopping);
|
||||
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kStopping);
|
||||
const ActionTick done = rig.runner.update();
|
||||
EXPECT_EQ(done.status, ActionTick::Status::kCancelled);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kIdle);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed) << "handler was released";
|
||||
}
|
||||
|
||||
TEST(ActionRunner, PerceptionHandlerIsReleasedRightAwayOnCancel)
|
||||
{
|
||||
Rig rig;
|
||||
move_base2::ComponentStatusBoard board;
|
||||
rig.runner.attachStatusBoard(&board);
|
||||
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"detect"});
|
||||
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||
ASSERT_TRUE(rig.load("actions_empty"));
|
||||
ASSERT_TRUE(rig.runner.start(makeAction("detect")));
|
||||
|
||||
rig.runner.cancel();
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kIdle);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed) << "no handler active";
|
||||
}
|
||||
|
||||
TEST(ActionRunner, PauseAndResumeReachTheHandlerWithTheClockTime)
|
||||
{
|
||||
Rig rig;
|
||||
move_base2::ComponentStatusBoard board;
|
||||
rig.runner.attachStatusBoard(&board);
|
||||
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"});
|
||||
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||
ASSERT_TRUE(rig.load("actions_empty"));
|
||||
ASSERT_TRUE(rig.runner.start(makeAction("pick")));
|
||||
|
||||
rig.clock.advance(1.0);
|
||||
rig.runner.pause();
|
||||
EXPECT_EQ(handler->pause_count, 1);
|
||||
EXPECT_DOUBLE_EQ(handler->last_pause_at.toSec(), 1001.0);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kPaused);
|
||||
|
||||
rig.clock.advance(30.0);
|
||||
rig.runner.resume();
|
||||
EXPECT_EQ(handler->resume_count, 1);
|
||||
EXPECT_DOUBLE_EQ(handler->last_resume_at.toSec(), 1031.0);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kBusy);
|
||||
|
||||
// Không có action đang chạy thì pause/resume không tới handler nào.
|
||||
rig.runner.cancel();
|
||||
rig.runner.pause();
|
||||
rig.runner.resume();
|
||||
EXPECT_EQ(handler->pause_count, 1);
|
||||
EXPECT_EQ(handler->resume_count, 1);
|
||||
}
|
||||
|
||||
TEST(ActionRunner, LoadedNoopHandlerDoesNotCountPausedTimeTowardsItsDuration)
|
||||
{
|
||||
// Handler thật (noop, duration 2 s): pause 30 s giữa chừng, resume, phải còn chạy tiếp đúng phần
|
||||
// thời gian còn lại — không kết thúc sớm, không timeout oan.
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.load("actions"));
|
||||
ASSERT_TRUE(rig.runner.start(makeAction("wait", "w1"))); // duration: 2.0 s, timeout 10 s
|
||||
|
||||
rig.clock.advance(1.0);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||
|
||||
rig.runner.pause();
|
||||
rig.clock.advance(30.0); // đứng chờ lâu hơn cả timeout 10 s
|
||||
rig.runner.resume();
|
||||
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning)
|
||||
<< "the 30 s pause must not count: 1 s of 2 s elapsed, and the 10 s timeout must not fire";
|
||||
rig.clock.advance(1.0);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kSucceeded);
|
||||
}
|
||||
|
||||
TEST(ActionRunner, CancelWithoutActiveActionIsSafe)
|
||||
{
|
||||
Rig rig;
|
||||
|
||||
143
test/component_status_test.cpp
Normal file
143
test/component_status_test.cpp
Normal file
@@ -0,0 +1,143 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — test bảng trạng thái thành phần: nguồn sự thật cho quiescence và watchdog.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
|
||||
using move_base2::Component;
|
||||
using move_base2::ComponentPhase;
|
||||
using move_base2::ComponentStatusBoard;
|
||||
|
||||
TEST(ComponentStatusBoard, StartsIdleEverywhere)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||
{
|
||||
const Component c = static_cast<Component>(i);
|
||||
EXPECT_TRUE(board.isIdle(c)) << move_base2::toString(c);
|
||||
EXPECT_EQ(board.at(c).progress_ticks.load(), 0u);
|
||||
}
|
||||
EXPECT_FALSE(board.anyHung());
|
||||
EXPECT_TRUE(board.allIdle({Component::kGlobalPlanner, Component::kRecovery, Component::kAction}));
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, EnterChangesPhaseAndCountsAsProgress)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||
EXPECT_EQ(board.phase(Component::kGlobalPlanner), ComponentPhase::kBusy);
|
||||
EXPECT_FALSE(board.isIdle(Component::kGlobalPlanner));
|
||||
EXPECT_FALSE(board.allIdle({Component::kGlobalPlanner, Component::kRecovery}));
|
||||
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 1u);
|
||||
EXPECT_GT(board.at(Component::kGlobalPlanner).phase_since_ns.load(), 0);
|
||||
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||
EXPECT_EQ(board.phase(Component::kGlobalPlanner), ComponentPhase::kStopping);
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||
EXPECT_TRUE(board.isIdle(Component::kGlobalPlanner));
|
||||
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 3u);
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, ProgressDoesNotChangePhase)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
board.enter(Component::kRecovery, ComponentPhase::kBusy);
|
||||
const std::int64_t since = board.at(Component::kRecovery).phase_since_ns.load();
|
||||
board.progress(Component::kRecovery);
|
||||
board.progress(Component::kRecovery);
|
||||
EXPECT_EQ(board.phase(Component::kRecovery), ComponentPhase::kBusy);
|
||||
EXPECT_EQ(board.at(Component::kRecovery).phase_since_ns.load(), since)
|
||||
<< "progress must not restart the phase clock";
|
||||
EXPECT_EQ(board.at(Component::kRecovery).progress_ticks.load(), 3u);
|
||||
EXPECT_GE(board.at(Component::kRecovery).last_progress_ns.load(), since);
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, SecondsInPhaseAndSinceProgressGrowWithWallTime)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
board.enter(Component::kControlLoop, ComponentPhase::kBusy);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
EXPECT_GE(board.secondsInPhase(Component::kControlLoop), 0.015);
|
||||
EXPECT_GE(board.secondsSinceProgress(Component::kControlLoop), 0.015);
|
||||
board.progress(Component::kControlLoop);
|
||||
EXPECT_LT(board.secondsSinceProgress(Component::kControlLoop), 0.015);
|
||||
EXPECT_GE(board.secondsInPhase(Component::kControlLoop), 0.015) << "phase clock untouched";
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, AnyHungSeesASingleHungRow)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
board.enter(Component::kCostmapLocal, ComponentPhase::kHung);
|
||||
EXPECT_TRUE(board.anyHung());
|
||||
board.enter(Component::kCostmapLocal, ComponentPhase::kIdle);
|
||||
EXPECT_FALSE(board.anyHung());
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, EveryComponentAndPhaseHasAName)
|
||||
{
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||
{
|
||||
const std::string name = move_base2::toString(static_cast<Component>(i));
|
||||
EXPECT_FALSE(name.empty());
|
||||
EXPECT_NE(name, "unknown");
|
||||
}
|
||||
for (const ComponentPhase p : {ComponentPhase::kIdle, ComponentPhase::kBusy, ComponentPhase::kStopping,
|
||||
ComponentPhase::kPaused, ComponentPhase::kHung})
|
||||
{
|
||||
const std::string name = move_base2::toString(p);
|
||||
EXPECT_FALSE(name.empty());
|
||||
EXPECT_NE(name, "unknown");
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, ConcurrentWriterAndReaderDoNotTearOrCrash)
|
||||
{
|
||||
// Mô hình thật: thread planner ghi hàng của nó, control thread và watchdog đọc. Không lock — mọi
|
||||
// field atomic, đọc phải luôn thấy một phase hợp lệ.
|
||||
ComponentStatusBoard board;
|
||||
std::atomic<bool> stop{false};
|
||||
std::atomic<std::uint64_t> bad_reads{0};
|
||||
|
||||
std::thread writer([&] {
|
||||
for (int i = 0; i < 200000; ++i)
|
||||
{
|
||||
board.enter(Component::kGlobalPlanner, (i & 1) ? ComponentPhase::kBusy : ComponentPhase::kIdle);
|
||||
board.progress(Component::kGlobalPlanner);
|
||||
}
|
||||
stop = true;
|
||||
});
|
||||
std::thread reader([&] {
|
||||
while (!stop)
|
||||
{
|
||||
const ComponentPhase p = board.phase(Component::kGlobalPlanner);
|
||||
if (p != ComponentPhase::kBusy && p != ComponentPhase::kIdle)
|
||||
{
|
||||
++bad_reads;
|
||||
}
|
||||
(void)board.secondsInPhase(Component::kGlobalPlanner);
|
||||
(void)board.allIdle({Component::kGlobalPlanner, Component::kRecovery});
|
||||
}
|
||||
});
|
||||
writer.join();
|
||||
reader.join();
|
||||
EXPECT_EQ(bad_reads.load(), 0u);
|
||||
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 400000u);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -16,6 +16,14 @@ move_base2:
|
||||
action_patience: 0.0 # [s] 0 = tắt; lưới cuối, không phải cơ chế timeout chính
|
||||
max_planning_retries: -1 # < 0 = không giới hạn
|
||||
recovery_behavior_enabled: true
|
||||
settle_timeout: 3.5 # [s] chờ quiescent ở CANCELLING; 0 = tắt
|
||||
stopped_measured_linear_eps: 0.03 # [m/s] "đã dừng" theo odom; 0 = bỏ odom
|
||||
stopped_measured_angular_eps: 0.04 # [rad/s]
|
||||
watchdog_period: 0.25 # [s]
|
||||
local_planner_call_budget: 0.7 # [s]
|
||||
recovery_stall_budget: 6.0 # [s]
|
||||
action_stall_budget: 1.5 # [s]
|
||||
control_loop_stall_budget: 0.9 # [s]
|
||||
|
||||
max_vel_x: 0.5 # [m/s] tiến
|
||||
min_vel_x: -0.2 # [m/s] lùi, ÂM
|
||||
@@ -276,6 +284,10 @@ TestPlannerThrowing:
|
||||
library_path: libmove_base2_test_global_planner
|
||||
TestPlannerInitFails:
|
||||
library_path: libmove_base2_test_global_planner
|
||||
TestPlannerSlowPreemptable: # search 2 s, thoát khi preempt() — mô hình SBPL + abort flag
|
||||
library_path: libmove_base2_test_global_planner
|
||||
TestPlannerSlowStubborn: # search 0.4 s, KHÔNG nhìn preempt — mô hình plugin cũ
|
||||
library_path: libmove_base2_test_global_planner
|
||||
|
||||
# TestPlannerMissingLibrary cố ý KHÔNG khai library_path.
|
||||
|
||||
|
||||
@@ -55,6 +55,42 @@ TEST(MoveBase2Config, DefaultsAreValid)
|
||||
EXPECT_TRUE(config.validate(error)) << error;
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, CancelSettleKeysFallBackToDefaultsWhenAbsent)
|
||||
{
|
||||
// Cây config cũ (trước 2026-09-11) không có ba khoá này: phải giữ default BẬT (2 s, 0.02) chứ
|
||||
// không im lặng rơi về hành vi cũ "CANCELLED ngay khi lệnh = 0".
|
||||
const MoveBase2Config config = loadFrom("move_base2_no_planner");
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.settle_timeout, 2.0);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_linear_eps, 0.02);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_angular_eps, 0.02);
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, WatchdogKeysFallBackToDefaultsWhenAbsent)
|
||||
{
|
||||
const MoveBase2Config config = loadFrom("move_base2_no_planner");
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.period, 0.1);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.control_loop_stall_budget, 0.5);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.action_stall_budget, 0.0);
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, RejectsNegativeWatchdogPeriod)
|
||||
{
|
||||
MoveBase2Config config = minimalValid();
|
||||
config.watchdog.period = -1.0;
|
||||
std::string error;
|
||||
EXPECT_FALSE(config.validate(error));
|
||||
EXPECT_NE(error.find("watchdog_period"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, RejectsNegativeCancelSettleTimeout)
|
||||
{
|
||||
MoveBase2Config config = minimalValid();
|
||||
config.state_machine.settle_timeout = -0.5;
|
||||
std::string error;
|
||||
EXPECT_FALSE(config.validate(error));
|
||||
EXPECT_NE(error.find("settle_timeout"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, RejectsRecoveryEnabledWithNoBehaviorLoaded)
|
||||
{
|
||||
// Ràng buộc thứ tự khởi tạo: RecoveryRunner không nạp được behavior nào mà
|
||||
@@ -153,6 +189,16 @@ TEST(MoveBase2Config, ReadsEveryGroupFromYaml)
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.controller_patience, 15.0);
|
||||
EXPECT_EQ(config.state_machine.max_planning_retries, -1);
|
||||
EXPECT_TRUE(config.state_machine.recovery_enabled);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.settle_timeout, 3.5);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_linear_eps, 0.03);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_angular_eps, 0.04);
|
||||
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.period, 0.25);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.planner_timeout, 5.0) << "copied from planner_timeout";
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.local_planner_call_budget, 0.7);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.recovery_stall_budget, 6.0);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.action_stall_budget, 1.5);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.control_loop_stall_budget, 0.9);
|
||||
|
||||
EXPECT_DOUBLE_EQ(config.velocity.max_vel_x, 0.5);
|
||||
EXPECT_DOUBLE_EQ(config.velocity.min_vel_x, -0.2);
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
|
||||
#include <robot/time.h>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/ports/action_port.h>
|
||||
#include <move_base2/ports/clock_port.h>
|
||||
#include <move_base2/ports/controller_port.h>
|
||||
@@ -221,6 +222,7 @@ public:
|
||||
pending_goal_ = goal;
|
||||
cycles_left_ = latency_cycles_;
|
||||
pending_action_ = nextAction();
|
||||
report(ComponentPhase::kBusy);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -248,6 +250,14 @@ public:
|
||||
}
|
||||
|
||||
in_flight_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
if (discarded_)
|
||||
{
|
||||
// Lượt đã bị huỷ giữa chừng nhưng plugin không cắt được (SBPL thật): kết quả về thì vứt lặng
|
||||
// lẽ, đúng như PlannerRunner với discard_. Bên gọi chỉ thấy isPlanning() chuyển về false.
|
||||
discarded_ = false;
|
||||
return false;
|
||||
}
|
||||
result.tag = pending_tag_;
|
||||
result.plan.clear();
|
||||
|
||||
@@ -272,8 +282,23 @@ public:
|
||||
|
||||
void cancelPlan() override
|
||||
{
|
||||
in_flight_ = false;
|
||||
++cancel_count_;
|
||||
if (cancel_keeps_busy_ && in_flight_)
|
||||
{
|
||||
// Mô phỏng plugin KHÔNG preempt được: thread vẫn bận cho tới hết latency đã đặt, kết quả
|
||||
// về bị vứt. Đây là hành vi của PlannerRunner + SBPL trước pha 2.
|
||||
discarded_ = true;
|
||||
report(ComponentPhase::kStopping);
|
||||
return;
|
||||
}
|
||||
in_flight_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
/// @brief Ghi hàng `kGlobalPlanner` như PlannerRunner thật. Null = không khai.
|
||||
void attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
std::string activePlanner() const override
|
||||
@@ -281,6 +306,18 @@ public:
|
||||
return active_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sau cancelPlan(), lượt đang chạy vẫn chiếm thread cho tới hết latency (mặc định false:
|
||||
* cancel cắt ngay, như plugin có preempt).
|
||||
*
|
||||
* Bật để tái hiện log 2026-09-11: cancel lúc SBPL đang chạy, goal kế bị `startPlan()` từ chối
|
||||
* suốt mấy giây.
|
||||
*/
|
||||
void setCancelKeepsBusy(bool keeps_busy)
|
||||
{
|
||||
cancel_keeps_busy_ = keeps_busy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Số cycle mà một lượt lập plan "mất" trước khi có kết quả.
|
||||
*
|
||||
@@ -356,6 +393,17 @@ private:
|
||||
std::size_t latency_cycles_ = 0;
|
||||
std::size_t cycles_left_ = 0;
|
||||
std::size_t cancel_count_ = 0;
|
||||
bool cancel_keeps_busy_ = false;
|
||||
bool discarded_ = false;
|
||||
ComponentStatusBoard* status_board_ = nullptr;
|
||||
|
||||
void report(ComponentPhase phase)
|
||||
{
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kGlobalPlanner, phase);
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t make_plan_count_ = 0;
|
||||
std::size_t swap_count_ = 0;
|
||||
@@ -438,6 +486,28 @@ public:
|
||||
void setMeasuredVelocity(const robot_geometry_msgs::Twist& velocity) override
|
||||
{
|
||||
measured_velocity_ = velocity;
|
||||
has_measured_velocity_ = true;
|
||||
}
|
||||
|
||||
/// Cổng thật (ControllerRunner) trả false cho tới khi host đẩy odom vào; fake giữ đúng nghĩa đó
|
||||
/// để mọi test không đẩy odom vẫn đi đường "đo bằng lệnh đã phát" như trước.
|
||||
bool measuredVelocity(robot_geometry_msgs::Twist& out) const override
|
||||
{
|
||||
if (!has_measured_velocity_)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
out = measured_velocity_;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @brief Giả lập odom: robot đang lăn với @p linear_x [m/s], @p angular_z [rad/s].
|
||||
void setOdometry(double linear_x, double angular_z = 0.0)
|
||||
{
|
||||
robot_geometry_msgs::Twist twist;
|
||||
twist.linear.x = linear_x;
|
||||
twist.angular.z = angular_z;
|
||||
setMeasuredVelocity(twist);
|
||||
}
|
||||
|
||||
void getLocalPlan(robot_nav_2d_msgs::Path2D& plan) override
|
||||
@@ -546,6 +616,7 @@ public:
|
||||
private:
|
||||
robot_nav_2d_msgs::Path2D local_plan_;
|
||||
robot_geometry_msgs::Twist measured_velocity_;
|
||||
bool has_measured_velocity_ = false;
|
||||
double limit_forward_ = 0.0; ///< [m/s]
|
||||
double limit_backward_ = 0.0; ///< [m/s], âm
|
||||
double limit_angular_ = 0.0; ///< [rad/s]
|
||||
@@ -633,6 +704,7 @@ public:
|
||||
return false;
|
||||
}
|
||||
active_ = true;
|
||||
report(ComponentPhase::kBusy);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -647,6 +719,10 @@ public:
|
||||
tick.status = RecoveryTick::Status::kRunning;
|
||||
tick.has_velocity = emits_velocity_;
|
||||
tick.cmd.linear.x = recovery_speed_;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->progress(Component::kRecovery);
|
||||
}
|
||||
break;
|
||||
case RecoveryScript::kSucceeded:
|
||||
tick.status = RecoveryTick::Status::kSucceeded;
|
||||
@@ -656,15 +732,44 @@ public:
|
||||
tick.path = success_path_;
|
||||
}
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
break;
|
||||
case RecoveryScript::kFailed:
|
||||
tick.status = RecoveryTick::Status::kFailed;
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
break;
|
||||
}
|
||||
return tick;
|
||||
}
|
||||
|
||||
/// @brief Ghi hàng `kRecovery` như RecoveryRunner thật. Null = không khai.
|
||||
void attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sau cancel(), behavior vẫn "bận" thêm @p cycles tick — mô phỏng detour worker chưa thoát.
|
||||
* Hàng kRecovery giữ kStopping; test gọi @ref settleCancel để nhả.
|
||||
*/
|
||||
void setCancelKeepsBusy(bool keeps_busy)
|
||||
{
|
||||
cancel_keeps_busy_ = keeps_busy;
|
||||
}
|
||||
|
||||
/// @brief Worker giả đã thoát: hàng về idle.
|
||||
void settleCancel()
|
||||
{
|
||||
stopping_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
bool stopping() const
|
||||
{
|
||||
return stopping_;
|
||||
}
|
||||
|
||||
/// @brief Thành công thì kèm một detour path (như 'detour_path' thật) — cần cho stand-down của kContact.
|
||||
void setSucceedWithPath(std::vector<robot_geometry_msgs::PoseStamped> path)
|
||||
{
|
||||
@@ -675,7 +780,17 @@ public:
|
||||
void cancel() override
|
||||
{
|
||||
++cancel_count_;
|
||||
const bool was_active = active_;
|
||||
active_ = false;
|
||||
if (was_active && cancel_keeps_busy_)
|
||||
{
|
||||
stopping_ = true;
|
||||
report(ComponentPhase::kStopping);
|
||||
}
|
||||
else
|
||||
{
|
||||
report(ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
std::string behaviorName(std::size_t index) const override
|
||||
@@ -772,6 +887,18 @@ private:
|
||||
std::size_t last_start_index_ = 0;
|
||||
RecoveryTrigger last_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
std::vector<std::size_t> started_indices_;
|
||||
|
||||
bool cancel_keeps_busy_ = false;
|
||||
bool stopping_ = false;
|
||||
ComponentStatusBoard* status_board_ = nullptr;
|
||||
|
||||
void report(ComponentPhase phase)
|
||||
{
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kRecovery, phase);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
@@ -793,6 +920,7 @@ public:
|
||||
return false;
|
||||
}
|
||||
active_ = true;
|
||||
report(ComponentPhase::kBusy);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -801,19 +929,45 @@ public:
|
||||
++update_count_;
|
||||
|
||||
ActionTick tick;
|
||||
if (stopping_)
|
||||
{
|
||||
if (cancel_ticks_left_ > 0)
|
||||
{
|
||||
--cancel_ticks_left_;
|
||||
tick.status = ActionTick::Status::kRunning;
|
||||
tick.message = "moving the device to a safe position";
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->progress(Component::kAction);
|
||||
}
|
||||
return tick;
|
||||
}
|
||||
stopping_ = false;
|
||||
active_ = false;
|
||||
tick.status = ActionTick::Status::kCancelled;
|
||||
tick.message = "device safe";
|
||||
report(ComponentPhase::kIdle);
|
||||
return tick;
|
||||
}
|
||||
switch (nextAction())
|
||||
{
|
||||
case ActionScript::kRunning:
|
||||
tick.status = ActionTick::Status::kRunning;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->progress(Component::kAction);
|
||||
}
|
||||
break;
|
||||
case ActionScript::kSucceeded:
|
||||
tick.status = ActionTick::Status::kSucceeded;
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
break;
|
||||
case ActionScript::kFailed:
|
||||
tick.status = ActionTick::Status::kFailed;
|
||||
tick.message = "fake action failed";
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
break;
|
||||
}
|
||||
return tick;
|
||||
@@ -822,7 +976,56 @@ public:
|
||||
void cancel() override
|
||||
{
|
||||
++cancel_count_;
|
||||
if (active_ && cancel_ticks_needed_ > 0)
|
||||
{
|
||||
// Handler thiết bị (pha 3): giữ "đang dừng" thêm N tick rồi trả kCancelled.
|
||||
cancel_ticks_left_ = cancel_ticks_needed_;
|
||||
stopping_ = true;
|
||||
report(ComponentPhase::kStopping);
|
||||
return;
|
||||
}
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
void pause() override
|
||||
{
|
||||
++pause_count_;
|
||||
if (active_)
|
||||
{
|
||||
report(ComponentPhase::kPaused);
|
||||
}
|
||||
}
|
||||
|
||||
void resume() override
|
||||
{
|
||||
++resume_count_;
|
||||
if (active_)
|
||||
{
|
||||
report(ComponentPhase::kBusy);
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief Sau cancel() handler cần @p ticks lượt update() nữa mới trả kCancelled (0 = dừng ngay).
|
||||
void setCancelNeedsTicks(std::size_t ticks)
|
||||
{
|
||||
cancel_ticks_needed_ = ticks;
|
||||
}
|
||||
|
||||
std::size_t pauseCount() const
|
||||
{
|
||||
return pause_count_;
|
||||
}
|
||||
|
||||
std::size_t resumeCount() const
|
||||
{
|
||||
return resume_count_;
|
||||
}
|
||||
|
||||
/// @brief Ghi hàng `kAction` như ActionRunner thật. Null = không khai.
|
||||
void attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
void setScript(std::vector<ActionScript> script)
|
||||
@@ -885,7 +1088,21 @@ private:
|
||||
std::size_t start_count_ = 0;
|
||||
std::size_t update_count_ = 0;
|
||||
std::size_t cancel_count_ = 0;
|
||||
std::size_t pause_count_ = 0;
|
||||
std::size_t resume_count_ = 0;
|
||||
std::size_t cancel_ticks_needed_ = 0;
|
||||
std::size_t cancel_ticks_left_ = 0;
|
||||
bool stopping_ = false;
|
||||
std::vector<std::string> started_action_types_;
|
||||
ComponentStatusBoard* status_board_ = nullptr;
|
||||
|
||||
void report(ComponentPhase phase)
|
||||
{
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, phase);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -147,6 +147,10 @@ public:
|
||||
deps_.recovery = &recovery_;
|
||||
deps_.mission = &mission_;
|
||||
deps_.action = &action_;
|
||||
deps_.components = &components_;
|
||||
planner_.attachStatusBoard(&components_);
|
||||
recovery_.attachStatusBoard(&components_);
|
||||
action_.attachStatusBoard(&components_);
|
||||
}
|
||||
|
||||
void configure(const ControlLoopConfig& config = baseConfig())
|
||||
@@ -199,6 +203,7 @@ public:
|
||||
FakeRecoveryPort recovery_;
|
||||
FakeMissionPort mission_;
|
||||
FakeActionPort action_;
|
||||
move_base2::ComponentStatusBoard components_;
|
||||
ControlLoopDeps deps_;
|
||||
|
||||
robot_costmap_2d::LayeredCostmap global_;
|
||||
@@ -842,7 +847,11 @@ TEST(NavigationServerLifecycle, PauseTakesEffectOnTheNextCycleNotImmediately)
|
||||
<< "pause() goes straight into the core from the host thread";
|
||||
|
||||
fixture.spin(1);
|
||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPausing)
|
||||
<< "pause is taken in one cycle: command zero, waiting for the runtime to settle";
|
||||
fixture.spin(1);
|
||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused)
|
||||
<< "nothing is busy in this fixture, so PAUSED follows one cycle later";
|
||||
}
|
||||
|
||||
TEST(NavigationServerLifecycle, ResumeAfterPauseReturnsToControlling)
|
||||
@@ -856,7 +865,7 @@ TEST(NavigationServerLifecycle, ResumeAfterPauseReturnsToControlling)
|
||||
fixture.spin(2);
|
||||
|
||||
fixture.server_.pause();
|
||||
fixture.spin(1);
|
||||
fixture.spin(2);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
|
||||
fixture.server_.resume();
|
||||
@@ -901,6 +910,7 @@ TEST(NavigationServerLifecycle, CancelWinsOverAPauseRequestedInTheSameCycle)
|
||||
fixture.spin(1);
|
||||
|
||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused) << "pause won over cancel";
|
||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing) << "pause won over cancel";
|
||||
}
|
||||
|
||||
TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
|
||||
@@ -914,13 +924,14 @@ TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
|
||||
fixture.spin(2);
|
||||
|
||||
fixture.server_.pause();
|
||||
fixture.spin(1);
|
||||
fixture.spin(2);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
|
||||
// Không có lệnh mới: cờ đã bị tiêu thụ, các cycle sau không được tự tạm dừng lại lần nữa.
|
||||
fixture.server_.resume();
|
||||
fixture.spin(3);
|
||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
@@ -1149,6 +1160,169 @@ TEST(NavigationServerFeedback, NothingIsLatchedBeforeTheFirstRequest)
|
||||
<< "a freshly booted runtime reports a terminal result although no goal has ever been sent";
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// PREEMPTING phải nói thật (2026-09-11): host đọc PREEMPTED là "xong rồi, gửi goal kế được". Cancel
|
||||
// lúc SBPL đang chạy mà báo PREEMPTED sau 33 ms thì host gửi goal kế vào một runtime còn bận —
|
||||
// đúng chuỗi sự kiện trong log robot_app.log dẫn tới ABORTED oan.
|
||||
// ================================================================================================
|
||||
|
||||
TEST(NavigationServerFeedback, PreemptingIsHeldUntilTheCancelledPlannerAttemptReallyEnds)
|
||||
{
|
||||
Fixture fixture;
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.planner_patience = 5.0; // [s]
|
||||
config.state_machine.settle_timeout = 2.0; // [s]
|
||||
fixture.configure(config);
|
||||
fixture.planner_.setLatencyCycles(10);
|
||||
fixture.planner_.setCancelKeepsBusy(true); // SBPL trước pha 2: cancelPlan() không cắt được
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
fixture.spin(2);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPlanning);
|
||||
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||
|
||||
fixture.server_.cancel();
|
||||
fixture.spin(1);
|
||||
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::PREEMPTING);
|
||||
|
||||
// Host poll 100 ms một lần = 2 cycle @ 20 Hz: mỗi lần poll trong lúc thread còn bận phải vẫn
|
||||
// thấy PREEMPTING, không phải PREEMPTED.
|
||||
std::size_t polls_while_busy = 0;
|
||||
for (int i = 0; i < 20 && fixture.planner_.isPlanning(); ++i)
|
||||
{
|
||||
fixture.spin(2);
|
||||
if (fixture.planner_.isPlanning())
|
||||
{
|
||||
++polls_while_busy;
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::PREEMPTING)
|
||||
<< "poll " << i << ": PREEMPTED reported while the planner thread is still busy";
|
||||
}
|
||||
}
|
||||
EXPECT_GE(polls_while_busy, 2u);
|
||||
|
||||
fixture.spin(2);
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::PREEMPTED)
|
||||
<< "once the thread is idle the cancel must be reported (and latched) as PREEMPTED";
|
||||
}
|
||||
|
||||
TEST(NavigationServerFeedback, GoalSentWhilePreemptingIsAcceptedAndRunsOnceThePlannerIsFree)
|
||||
{
|
||||
// Host cũ không đợi PREEMPTED. Vẫn phải chạy đúng: goal kế xếp sau, không bị coi là hỏng.
|
||||
Fixture fixture;
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.planner_patience = 5.0; // [s]
|
||||
config.state_machine.max_planning_retries = 0; // như máy chạy log
|
||||
fixture.configure(config);
|
||||
fixture.planner_.setLatencyCycles(10);
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
fixture.controller_.setScript({ ControllerScript::kOk });
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
fixture.spin(2);
|
||||
fixture.server_.cancel();
|
||||
fixture.spin(1);
|
||||
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::PREEMPTING);
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(5.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
|
||||
bool saw_clearing_or_aborted = false;
|
||||
bool reached_controlling = false;
|
||||
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||
{
|
||||
fixture.spin(1);
|
||||
const auto host = fixture.server_.getFeedback()->navigation_state;
|
||||
saw_clearing_or_aborted = saw_clearing_or_aborted ||
|
||||
host == robot::move_base_core::State::CLEARING ||
|
||||
host == robot::move_base_core::State::ABORTED;
|
||||
reached_controlling = host == robot::move_base_core::State::CONTROLLING;
|
||||
}
|
||||
EXPECT_FALSE(saw_clearing_or_aborted) << "the second goal went through recovery/abort";
|
||||
EXPECT_TRUE(reached_controlling);
|
||||
}
|
||||
|
||||
TEST(NavigationServerFeedback, PausedIsReportedOnlyOnceTheRuntimeIsQuiescent)
|
||||
{
|
||||
// PAUSING nói thật (2026-09-11): pause lúc SBPL còn chạy → host vẫn thấy PLANNING (+ feed_back_str
|
||||
// "pausing…"), KHÔNG phải PAUSED; PAUSED chỉ khi thread planner đã nhả.
|
||||
Fixture fixture;
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.planner_patience = 5.0; // [s]
|
||||
fixture.configure(config);
|
||||
fixture.planner_.setLatencyCycles(10);
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
fixture.spin(2);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPlanning);
|
||||
|
||||
fixture.server_.pause();
|
||||
fixture.spin(1);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPausing);
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PLANNING)
|
||||
<< "while pausing the host must keep seeing the state that is still winding down";
|
||||
EXPECT_NE(fixture.server_.getFeedback()->feed_back_str.find("pausing"), std::string::npos);
|
||||
|
||||
std::size_t polls_while_busy = 0;
|
||||
for (int i = 0; i < 20 && fixture.planner_.isPlanning(); ++i)
|
||||
{
|
||||
fixture.spin(2);
|
||||
if (fixture.planner_.isPlanning())
|
||||
{
|
||||
++polls_while_busy;
|
||||
EXPECT_NE(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PAUSED)
|
||||
<< "poll " << i << ": PAUSED reported while the planner thread is still busy";
|
||||
}
|
||||
}
|
||||
EXPECT_GE(polls_while_busy, 2u);
|
||||
|
||||
fixture.spin(2);
|
||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PAUSED);
|
||||
}
|
||||
|
||||
TEST(NavigationServerFeedback, StalledControlThreadIsReportedAsLostByTheWatchdog)
|
||||
{
|
||||
// Pha 4 (2026-09-11): control thread treo thì refreshFeedback() không chạy nữa, host đọc mãi
|
||||
// state cuối. Watchdog (thread riêng) phải ghi đè thành LOST trong getFeedback() — trên thread host.
|
||||
Fixture fixture;
|
||||
fixture.configure();
|
||||
fixture.controller_.setScript({ ControllerScript::kOk });
|
||||
|
||||
move_base2::WatchdogConfig dog;
|
||||
dog.period = 0.01; // [s]
|
||||
dog.control_loop_stall_budget = 0.05; // [s]
|
||||
std::string error;
|
||||
ASSERT_TRUE(fixture.server_.startWatchdog(&fixture.components_, dog, error)) << error;
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
fixture.spin(3); // mỗi spinOnce() là một heartbeat của "control thread"
|
||||
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::CONTROLLING);
|
||||
|
||||
// Control thread "treo": không spinOnce nữa. Watchdog phải tự thấy sau ngân sách.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(150));
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::LOST)
|
||||
<< "a frozen CONTROLLING must not look like a running one";
|
||||
EXPECT_NE(fixture.server_.getFeedback()->feed_back_str.find("control thread stalled"),
|
||||
std::string::npos);
|
||||
|
||||
// Thread quay lại → hết LOST, state thật quay về.
|
||||
fixture.spin(2);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(30));
|
||||
fixture.spin(1);
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::CONTROLLING);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// executeInstantAction() — cửa duy nhất nhận một action lẻ
|
||||
//
|
||||
|
||||
@@ -385,6 +385,181 @@ TEST(PlannerRunner, CancelledPlanProducesNoResult)
|
||||
"nobody asks for anymore";
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, CancelPreemptsAPreemptablePlannerWithinMilliseconds)
|
||||
{
|
||||
// 2026-09-11: plugin implement robot_nav_core::Preemptable thì cancelPlan() cắt lượt đang chạy —
|
||||
// thread rảnh trong vài ms thay vì 2 s. Đây là thứ làm CANCELLED/PAUSED nói thật mà không phải chờ.
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||
|
||||
const auto before = std::chrono::steady_clock::now();
|
||||
fixture.runner_.cancelPlan();
|
||||
int waited_ms = 0;
|
||||
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
++waited_ms;
|
||||
}
|
||||
const double elapsed_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
EXPECT_LT(elapsed_ms, 200.0) << "preempt did not reach the planner; the thread ran to the end";
|
||||
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "a preempted attempt must not deliver a plan";
|
||||
|
||||
// Lượt kế phải khởi động được ngay và chạy bình thường (cờ preempt không dính sang lượt sau).
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
|
||||
EXPECT_TRUE(fixture.runner_.isPlanning());
|
||||
fixture.runner_.cancelPlan();
|
||||
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, SwapWhileAPreemptablePlannerIsRunningCutsTheOldAttempt)
|
||||
{
|
||||
// Đổi profile (mission kế dùng planner khác) trong lúc lượt cũ chưa về: swapPlanner phải cắt
|
||||
// instance ĐANG chạy, không chỉ đánh dấu vứt. Không cắt thì yêu cầu kế đứng ở kBusy tới hết
|
||||
// allocated_time của lượt cũ (2 s ở đây, 10-30 s với SBPL thật).
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||
|
||||
const auto before = std::chrono::steady_clock::now();
|
||||
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
|
||||
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
const double elapsed_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
EXPECT_LT(elapsed_ms, 200.0) << "swapPlanner did not preempt the running instance";
|
||||
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "the old planner's attempt must be discarded";
|
||||
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
|
||||
|
||||
// Planner mới chạy bình thường ngay sau đó.
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
|
||||
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
ASSERT_TRUE(fixture.runner_.pollPlan(result));
|
||||
EXPECT_TRUE(result.succeeded);
|
||||
EXPECT_EQ(result.tag, 2U);
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, CancelAfterSwapPreemptsTheInstanceThatIsActuallyRunning)
|
||||
{
|
||||
// Thứ tự thật trong log 2026-09-11 (mission 2 đổi profile TRƯỚC khi accept_request gọi
|
||||
// cancelPlan): active_ đã trỏ sang planner mới, nhưng thread vẫn ở trong makePlan của planner cũ.
|
||||
// cancelPlan phải cắt đúng instance đang chạy, không phải active_.
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||
|
||||
// Đổi sang planner "ngoan" (stubborn — không Preemptable) để chứng minh cancel không nhìn active_:
|
||||
// nếu cancel dynamic_cast trên active_ thì ra null và lượt Preemptable đang chạy KHÔNG bị cắt.
|
||||
// Lưu ý: swapPlanner nay cũng preempt; để tách bạch, test này chỉ khẳng định tổng thể thread rảnh
|
||||
// trong vài ms sau cặp swap+cancel, đúng như ControlLoop làm khi nhận goal mới.
|
||||
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowStubborn"));
|
||||
fixture.runner_.cancelPlan();
|
||||
int waited_ms = 0;
|
||||
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
++waited_ms;
|
||||
}
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
EXPECT_LT(waited_ms, 200) << "the running Preemptable instance was not the one preempted";
|
||||
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, SwapWhileTheJobIsQueuedButNotStartedDropsIt)
|
||||
{
|
||||
// Yêu cầu vừa được đặt, thread chưa kịp nhận: đổi planner phải rút yêu cầu đó ra, không để thread
|
||||
// chạy yêu cầu của planner cũ trên instance mới rồi vứt.
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
bool dropped_before_start = false;
|
||||
for (int attempt = 0; attempt < 50 && !dropped_before_start; ++attempt)
|
||||
{
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
|
||||
// Cả hai nhánh (rút trước khi thread nhận / cắt sau khi nó nhận) đều phải rảnh trong vài ms.
|
||||
int waited_ms = 0;
|
||||
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
++waited_ms;
|
||||
}
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
EXPECT_LT(waited_ms, 200);
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||
dropped_before_start = (waited_ms == 0);
|
||||
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowPreemptable"));
|
||||
}
|
||||
// Không ép nhánh "rút trước khi nhận" phải xảy ra (phụ thuộc scheduler), chỉ cần cả hai nhánh
|
||||
// đều đúng.
|
||||
SUCCEED();
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, DestructorPreemptsARunningPreemptablePlanner)
|
||||
{
|
||||
// Shutdown giữa một lượt search dài: destructor phải cắt lượt đó thay vì chờ hết allocated_time.
|
||||
const auto before = std::chrono::steady_clock::now();
|
||||
{
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||
}
|
||||
const double elapsed_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||
EXPECT_LT(elapsed_ms, 500.0) << "destructor waited for the whole 2 s search";
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, CancelOnAStubbornPlannerFallsBackToDiscardingTheResult)
|
||||
{
|
||||
// Plugin cũ (không Preemptable): hành vi trước 2026-09-11 giữ nguyên — thread bận tới hết lượt,
|
||||
// kết quả về bị vứt. isPlanning() phải nói thật suốt quãng đó.
|
||||
Fixture fixture("TestPlannerSlowStubborn");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
fixture.runner_.cancelPlan();
|
||||
EXPECT_TRUE(fixture.runner_.isPlanning()) << "a stubborn planner cannot be cut short";
|
||||
|
||||
for (int i = 0; i < 2000 && fixture.runner_.isPlanning(); ++i)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, ResultCarriesBackTheTagItWasStartedWith)
|
||||
{
|
||||
Fixture fixture;
|
||||
|
||||
@@ -17,7 +17,10 @@
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <thread>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -29,6 +32,7 @@
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot_nav_core/base_global_planner.h>
|
||||
#include <robot_nav_core/preemptable.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
@@ -129,6 +133,85 @@ private:
|
||||
bool saw_order_ = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class TestSlowPlanner
|
||||
* @brief Planner giả "search dài": ngủ từng lát 5 ms trong @p seconds. Bản Preemptable thoát khi
|
||||
* thấy cờ (mô hình ARA* + abort flag); bản "stubborn" không nhìn cờ (mô hình plugin cũ).
|
||||
*/
|
||||
class TestSlowPlannerBase : public robot_nav_core::BaseGlobalPlanner
|
||||
{
|
||||
public:
|
||||
explicit TestSlowPlannerBase(double seconds, bool honours_preempt)
|
||||
: seconds_(seconds), honours_preempt_(honours_preempt)
|
||||
{
|
||||
}
|
||||
|
||||
bool initialize(std::string /*name*/, robot_costmap_2d::Costmap2DROBOT* /*costmap_robot*/) override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool makePlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
const robot_geometry_msgs::PoseStamped& goal,
|
||||
std::vector<robot_geometry_msgs::PoseStamped>& plan) override
|
||||
{
|
||||
preempt_.store(false, std::memory_order_relaxed);
|
||||
const auto deadline = std::chrono::steady_clock::now() +
|
||||
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
||||
std::chrono::duration<double>(seconds_));
|
||||
while (std::chrono::steady_clock::now() < deadline)
|
||||
{
|
||||
if (honours_preempt_ && preempt_.load(std::memory_order_relaxed))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
}
|
||||
plan.clear();
|
||||
plan.push_back(start);
|
||||
plan.push_back(goal);
|
||||
return true;
|
||||
}
|
||||
|
||||
protected:
|
||||
std::atomic<bool> preempt_{false};
|
||||
|
||||
private:
|
||||
double seconds_;
|
||||
bool honours_preempt_;
|
||||
};
|
||||
|
||||
class TestSlowPreemptablePlanner final : public TestSlowPlannerBase,
|
||||
public robot_nav_core::Preemptable
|
||||
{
|
||||
public:
|
||||
TestSlowPreemptablePlanner() : TestSlowPlannerBase(2.0, true)
|
||||
{
|
||||
}
|
||||
void preempt() override
|
||||
{
|
||||
preempt_.store(true, std::memory_order_relaxed);
|
||||
}
|
||||
};
|
||||
|
||||
class TestSlowStubbornPlanner final : public TestSlowPlannerBase
|
||||
{
|
||||
public:
|
||||
TestSlowStubbornPlanner() : TestSlowPlannerBase(0.4, false)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr createSlowPreemptable()
|
||||
{
|
||||
return std::make_shared<TestSlowPreemptablePlanner>();
|
||||
}
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr createSlowStubborn()
|
||||
{
|
||||
return std::make_shared<TestSlowStubbornPlanner>();
|
||||
}
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr createOk()
|
||||
{
|
||||
return std::make_shared<TestGlobalPlanner>(TestGlobalPlanner::Behavior::kOk);
|
||||
@@ -168,5 +251,7 @@ BOOST_DLL_ALIAS(move_base2::testing::createOk, TestPlannerOk)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createEmptyPlan, TestPlannerEmptyPlan)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createThrowing, TestPlannerThrowing)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createInitFailing, TestPlannerInitFails)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createSlowPreemptable, TestPlannerSlowPreemptable)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createSlowStubborn, TestPlannerSlowStubborn)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::initializeCount, TestPlannerInitializeCount)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::lastFootprintDock, TestPlannerLastFootprintDock)
|
||||
|
||||
@@ -240,6 +240,39 @@ TEST(StateMachineConfig, RejectsResolvedRouteWithAnOutOfRangeBehavior)
|
||||
EXPECT_NE(error.find("loaded behavior"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(StateMachineConfig, RejectsNegativeCancelSettleTimeout)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = -1.0;
|
||||
std::string error;
|
||||
EXPECT_FALSE(config.validate(error));
|
||||
EXPECT_NE(error.find("settle_timeout"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(StateMachineConfig, RejectsNegativeStoppedMeasuredEps)
|
||||
{
|
||||
StateMachineConfig linear = baseConfig();
|
||||
linear.stopped_measured_linear_eps = -0.01;
|
||||
std::string error;
|
||||
EXPECT_FALSE(linear.validate(error));
|
||||
EXPECT_NE(error.find("stopped_measured_linear_eps"), std::string::npos);
|
||||
|
||||
StateMachineConfig angular = baseConfig();
|
||||
angular.stopped_measured_angular_eps = -0.01;
|
||||
EXPECT_FALSE(angular.validate(error));
|
||||
EXPECT_NE(error.find("stopped_measured_angular_eps"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(StateMachineConfig, ZeroCancelSettleTimeoutAndZeroEpsAreValidOffSwitches)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.0;
|
||||
config.stopped_measured_linear_eps = 0.0;
|
||||
config.stopped_measured_angular_eps = 0.0;
|
||||
std::string error;
|
||||
EXPECT_TRUE(config.validate(error)) << error;
|
||||
}
|
||||
|
||||
TEST(StateMachineConfig, DescribeMentionsEveryParameter)
|
||||
{
|
||||
const std::string text = baseConfig().describe();
|
||||
@@ -249,6 +282,8 @@ TEST(StateMachineConfig, DescribeMentionsEveryParameter)
|
||||
EXPECT_NE(text.find("action_patience"), std::string::npos);
|
||||
EXPECT_NE(text.find("max_planning_retries"), std::string::npos);
|
||||
EXPECT_NE(text.find("recovery_reset_min_travel"), std::string::npos);
|
||||
EXPECT_NE(text.find("settle_timeout"), std::string::npos);
|
||||
EXPECT_NE(text.find("stopped_measured_eps"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(StateMachine, RefusesToRunBeforeConfigure)
|
||||
@@ -444,7 +479,7 @@ TEST(StateMachinePlanning, PauseMovesToPausedAndResumeComesBack)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
@@ -903,7 +938,7 @@ TEST(StateMachineControlling, PauseThenResumeReturnsToControlling)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
@@ -921,7 +956,7 @@ TEST(StateMachineControlling, LongPauseDoesNotBlowControllerPatience)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
driver.advance(60.0);
|
||||
|
||||
@@ -1108,7 +1143,7 @@ TEST(StateMachineRecovering, PauseMidRecoveryCancelsBehaviorAndResumesToPlanning
|
||||
pause.pause_requested = true;
|
||||
const StateMachineOutput paused = driver.tick(pause);
|
||||
|
||||
EXPECT_EQ(paused.state, NavigationState::kPaused);
|
||||
EXPECT_EQ(paused.state, NavigationState::kPausing);
|
||||
EXPECT_TRUE(paused.cancel_recovery)
|
||||
<< "keeping a behavior half-finished across a long pause is unsafe";
|
||||
|
||||
@@ -1147,7 +1182,7 @@ TEST(StateMachinePaused, CancelFromPausedGoesToCancelling)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
@@ -1161,7 +1196,9 @@ TEST(StateMachinePaused, StaysPausedIndefinitelyWithoutResume)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
// Cycle kế: mọi thành phần im (input mặc định) → PAUSED thật.
|
||||
ASSERT_EQ(driver.idleTick().state, NavigationState::kPaused);
|
||||
|
||||
for (int i = 0; i < 50; ++i)
|
||||
{
|
||||
@@ -1194,6 +1231,430 @@ TEST(StateMachineCancelling, WaitsForRobotToStopBeforeCancelled)
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// kCancelling chờ QUIESCENT (2026-09-11): lệnh về 0 là điều kiện cần, chưa đủ. Host đọc
|
||||
// CANCELLED/PREEMPTED là "xong rồi, gửi goal kế được" — báo trong lúc thread planner còn chạy lượt
|
||||
// cũ thì goal kế bị startPlan() từ chối và bị coi là hỏng (log 2026-09-11: ABORTED sau 3 s).
|
||||
// ================================================================================================
|
||||
|
||||
TEST(StateMachineCancelling, HoldsWhilePlannerThreadIsStillBusy)
|
||||
{
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
cancel.planner_busy = true; // SBPL đang chạy, cancelPlan() không cắt được
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput still_busy;
|
||||
still_busy.robot_stopped = true;
|
||||
still_busy.planner_busy = true;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
{
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(still_busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelling) << "left CANCELLING at cycle " << i;
|
||||
EXPECT_FALSE(out.report_outcome);
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||
EXPECT_FALSE(out.start_planner);
|
||||
}
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
idle.planner_busy = false;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(idle);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||
EXPECT_FALSE(out.settle_timed_out);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, GivesUpAfterSettleTimeoutAndFlagsIt)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.5; // [s]
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
|
||||
// 0.45 s: chưa quá trần.
|
||||
driver.advance(0.45);
|
||||
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||
EXPECT_FALSE(driver.last().settle_timed_out);
|
||||
|
||||
// 0.55 s: quá trần → CANCELLED nhưng cờ lỗi bật đúng cycle báo kết quả.
|
||||
driver.advance(0.10);
|
||||
const StateMachineOutput out = driver.tick(busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||
EXPECT_TRUE(out.settle_timed_out);
|
||||
|
||||
// Cờ chỉ sống một cycle: cycle kế về kIdle không mang nó theo.
|
||||
EXPECT_FALSE(driver.idleTick().settle_timed_out);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, HoldsWhileOdometrySaysTheRobotIsStillMoving)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
// Lệnh đã về 0 (bên gọi tính vào robot_stopped) nhưng odom vẫn đọc 0.3 m/s → chưa xong.
|
||||
StateMachineInput rolling;
|
||||
rolling.robot_stopped = false;
|
||||
rolling.planner_busy = false;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(rolling).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput stopped;
|
||||
stopped.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(stopped).state, NavigationState::kCancelled);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, KeepsTickingTheActionUntilItReportsTerminal)
|
||||
{
|
||||
// Handler thiết bị cần vài tick sau cancel() để đưa thiết bị về vị trí an toàn. Trong lúc đó
|
||||
// state machine tick tiếp nhưng KHÔNG cấp vận tốc — bất biến 3 giữ nguyên.
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
request.pending_request_has_goal = false;
|
||||
request.pending_request_action_count = 1;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kExecutingActions);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
cancel.action_terminal = false;
|
||||
const StateMachineOutput entering = driver.tick(cancel);
|
||||
ASSERT_EQ(entering.state, NavigationState::kCancelling);
|
||||
EXPECT_TRUE(entering.cancel_action);
|
||||
|
||||
StateMachineInput settling;
|
||||
settling.robot_stopped = true;
|
||||
settling.planner_busy = false;
|
||||
settling.action_terminal = false;
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(settling);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelling);
|
||||
EXPECT_TRUE(out.tick_action) << "cycle " << i;
|
||||
EXPECT_FALSE(out.run_controller);
|
||||
EXPECT_FALSE(out.tick_recovery);
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||
}
|
||||
|
||||
StateMachineInput terminal = settling;
|
||||
terminal.action_terminal = true;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(terminal);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||
EXPECT_FALSE(out.tick_action);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, ZeroSettleTimeoutKeepsTheLegacyBehaviour)
|
||||
{
|
||||
// Tắt = hành vi trước 2026-09-11: chỉ chờ lệnh về 0, mặc kệ planner còn bận.
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.0;
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput stopped_but_busy;
|
||||
stopped_but_busy.robot_stopped = true;
|
||||
stopped_but_busy.planner_busy = true;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(stopped_but_busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||
EXPECT_FALSE(out.settle_timed_out);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, CancelFromPausedAlsoWaitsForThePlannerThread)
|
||||
{
|
||||
// Pause lúc PLANNING đã cancelPlan() nhưng thread có thể còn bận; cancel từ PAUSED phải chờ nốt.
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
cancel.planner_busy = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput idle = busy;
|
||||
idle.planner_busy = false;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||
}
|
||||
|
||||
TEST(StateMachinePaused, ResumeFromControllingReappliesThePlanToTheController)
|
||||
{
|
||||
// Local planner giữ warm-start/slew theo thời gian; sau một quãng đứng yên phải nạp lại plan để
|
||||
// plugin reset theo pose hiện tại. Resume từ CONTROLLING vì vậy mang apply_plan (2026-09-11).
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
driver.advance(30.0);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
const StateMachineOutput out = driver.tick(resume);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.apply_plan);
|
||||
EXPECT_TRUE(out.run_controller);
|
||||
}
|
||||
|
||||
TEST(StateMachinePaused, ResumeFromPlanningDoesNotReapplyAnyPlan)
|
||||
{
|
||||
// Chưa từng có plan nào → không có gì để nạp lại; resume chỉ khởi động lại planner.
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
const StateMachineOutput out = driver.tick(resume);
|
||||
EXPECT_EQ(out.state, NavigationState::kPlanning);
|
||||
EXPECT_FALSE(out.apply_plan);
|
||||
EXPECT_TRUE(out.start_planner);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// kPausing (2026-09-11): pause nhận xong là lệnh 0 ngay, nhưng PAUSED chỉ khi mọi thành phần im —
|
||||
// cùng ba điều kiện quiescent với kCancelling. Host đọc PAUSED là "dừng rồi, làm gì cũng được".
|
||||
// ================================================================================================
|
||||
|
||||
TEST(StateMachinePausing, HoldsWhilePlannerThreadIsStillBusyThenSettles)
|
||||
{
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
pause.planner_busy = true;
|
||||
const StateMachineOutput entering = driver.tick(pause);
|
||||
ASSERT_EQ(entering.state, NavigationState::kPausing);
|
||||
EXPECT_TRUE(entering.stop_planner);
|
||||
EXPECT_EQ(entering.velocity_source, VelocitySource::kNone);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
{
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kPausing) << "cycle " << i;
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||
EXPECT_FALSE(out.start_planner);
|
||||
EXPECT_FALSE(out.settle_timed_out);
|
||||
}
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(idle);
|
||||
EXPECT_EQ(out.state, NavigationState::kPaused);
|
||||
EXPECT_FALSE(out.settle_timed_out);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, HoldsWhileRecoveryIsStillStopping)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput recovering;
|
||||
recovering.robot_stopped = true;
|
||||
recovering.recovery_busy = true; // detour worker chưa thoát
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(recovering).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(idle).state, NavigationState::kPaused);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, GivesUpAfterSettleTimeoutAndFlagsIt)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.5; // [s]
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
driver.advance(0.45);
|
||||
EXPECT_EQ(driver.tick(busy).state, NavigationState::kPausing);
|
||||
driver.advance(0.10);
|
||||
const StateMachineOutput out = driver.tick(busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kPaused);
|
||||
EXPECT_TRUE(out.settle_timed_out);
|
||||
EXPECT_FALSE(driver.idleTick().settle_timed_out) << "one-cycle flag";
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, ResumeBeforeSettledReturnsToThePreviousState)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
resume.planner_busy = true; // chưa im mà đã được bảo chạy tiếp — không phải chờ
|
||||
const StateMachineOutput out = driver.tick(resume);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.apply_plan);
|
||||
EXPECT_TRUE(out.run_controller);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, CancelBeforeSettledGoesToCancellingAndKeepsWaiting)
|
||||
{
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
pause.planner_busy = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
cancel.planner_busy = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, NewGoalWhilePausingPreemptsLikePaused)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput new_goal;
|
||||
new_goal.has_pending_request = true;
|
||||
const StateMachineOutput out = driver.tick(new_goal);
|
||||
EXPECT_EQ(out.state, NavigationState::kPlanning);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kPreempted);
|
||||
EXPECT_TRUE(out.accept_request);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, ZeroSettleTimeoutSettlesOnRobotStoppedOnly)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.0;
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput stopped_but_busy;
|
||||
stopped_but_busy.robot_stopped = true;
|
||||
stopped_but_busy.planner_busy = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(stopped_but_busy).state, NavigationState::kPaused);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, HoldsWhileRecoveryIsStillStopping)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput recovering;
|
||||
recovering.robot_stopped = true;
|
||||
recovering.recovery_busy = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(recovering).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||
}
|
||||
|
||||
TEST(StateMachineTerminal, OutcomeIsReportedExactlyOnce)
|
||||
{
|
||||
Driver driver;
|
||||
@@ -1393,18 +1854,57 @@ TEST(StateMachineActions, PauseDuringActionFreezesWithoutCancelling)
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
const StateMachineOutput paused = driver.tick(pause);
|
||||
EXPECT_EQ(paused.state, NavigationState::kPaused);
|
||||
EXPECT_EQ(paused.state, NavigationState::kPausing);
|
||||
EXPECT_FALSE(paused.cancel_action) << "the action is not idempotent — pausing must not cancel it";
|
||||
EXPECT_FALSE(paused.tick_action);
|
||||
EXPECT_TRUE(paused.pause_action) << "the handler must be told, so its own timeout clock stops";
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
const StateMachineOutput resumed = driver.tick(resume);
|
||||
EXPECT_EQ(resumed.state, NavigationState::kExecutingActions);
|
||||
EXPECT_TRUE(resumed.tick_action) << "resume keeps ticking the unfinished action";
|
||||
EXPECT_TRUE(resumed.resume_action) << "the handler must be told the pause is over";
|
||||
EXPECT_FALSE(resumed.start_action) << "an action already in progress must not be started again";
|
||||
}
|
||||
|
||||
TEST(StateMachineActions, PausingWithAnActionWaitsForTheHandlerToAcknowledge)
|
||||
{
|
||||
// Handler chưa xác nhận pause (action_terminal=false) → PAUSING tick tiếp; xác nhận → PAUSED.
|
||||
Driver driver;
|
||||
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||
NavigationState::kExecutingActions);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
pause.action_terminal = false;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput not_yet;
|
||||
not_yet.robot_stopped = true;
|
||||
not_yet.action_terminal = false;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput held = driver.tick(not_yet);
|
||||
EXPECT_EQ(held.state, NavigationState::kPausing);
|
||||
EXPECT_TRUE(held.tick_action);
|
||||
EXPECT_EQ(held.velocity_source, VelocitySource::kNone);
|
||||
|
||||
StateMachineInput acked = not_yet;
|
||||
acked.action_terminal = true; // hàng kAction = paused
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(acked).state, NavigationState::kPaused);
|
||||
}
|
||||
|
||||
TEST(StateMachineActions, CancelledFeedbackInsideExecutingActionsIsTreatedAsFailure)
|
||||
{
|
||||
// Lỗi thứ tự gọi (không ai cancel trong EXECUTING_ACTIONS) — không được im lặng chạy tiếp.
|
||||
Driver driver;
|
||||
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||
NavigationState::kExecutingActions);
|
||||
const StateMachineOutput out = driver.tick(actionFb(ActionFeedback::kCancelled));
|
||||
EXPECT_EQ(out.state, NavigationState::kAborted);
|
||||
}
|
||||
|
||||
TEST(StateMachineActions, ActionPatienceIsDisabledByDefault)
|
||||
{
|
||||
Driver driver;
|
||||
@@ -1451,7 +1951,7 @@ TEST(StateMachineActions, PauseRearmsActionPatienceClock)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
// Dừng lâu hơn hẳn action_patience rồi mới resume — quãng dừng không được tính vào trần.
|
||||
driver.advance(30.0);
|
||||
@@ -1556,8 +2056,8 @@ TEST(StateMachineInvariants, EveryStateHasANonEmptyName)
|
||||
{
|
||||
const NavigationState states[] = {
|
||||
NavigationState::kIdle, NavigationState::kPlanning, NavigationState::kControlling,
|
||||
NavigationState::kRecovering, NavigationState::kExecutingActions, NavigationState::kPaused,
|
||||
NavigationState::kCancelling, NavigationState::kSucceeded, NavigationState::kAborted,
|
||||
NavigationState::kRecovering, NavigationState::kExecutingActions, NavigationState::kPausing,
|
||||
NavigationState::kPaused, NavigationState::kCancelling, NavigationState::kSucceeded, NavigationState::kAborted,
|
||||
NavigationState::kCancelled,
|
||||
};
|
||||
|
||||
|
||||
@@ -130,6 +130,10 @@ public:
|
||||
deps_.action = &action_;
|
||||
deps_.costmap_status = &costmap_status_;
|
||||
deps_.environment = &environment_;
|
||||
deps_.components = &components_;
|
||||
planner_.attachStatusBoard(&components_);
|
||||
recovery_.attachStatusBoard(&components_);
|
||||
action_.attachStatusBoard(&components_);
|
||||
|
||||
std::string error;
|
||||
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
|
||||
@@ -179,6 +183,7 @@ public:
|
||||
FakeActionPort action_;
|
||||
FakeCostmapStatusPort costmap_status_;
|
||||
FakeEnvironmentPort environment_;
|
||||
move_base2::ComponentStatusBoard components_;
|
||||
ControlLoopDeps deps_;
|
||||
|
||||
private:
|
||||
@@ -814,8 +819,11 @@ TEST(ControlLoop, PauseAndResumeMidControlling)
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPausing);
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
|
||||
// Dừng lâu rồi tiếp tục: không được vì thế mà rơi vào recovery.
|
||||
fixture.clock_.advance(30.0);
|
||||
@@ -826,6 +834,433 @@ TEST(ControlLoop, PauseAndResumeMidControlling)
|
||||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, ResumeMidControllingReappliesThePlanToTheController)
|
||||
{
|
||||
// Local planner giữ warm-start/slew theo thời gian; sau 30 s đứng yên phải nạp lại plan để
|
||||
// plugin reset theo pose hiện tại (2026-09-11).
|
||||
Fixture fixture;
|
||||
fixture.controller_.setScript({ControllerScript::kOk});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||||
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
const std::size_t set_plan_before = fixture.controller_.setPlanCount();
|
||||
ASSERT_EQ(set_plan_before, 1u);
|
||||
|
||||
fixture.loop_.requestPause();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.controller_.setPlanCount(), set_plan_before) << "pause must not touch the plan";
|
||||
|
||||
fixture.clock_.advance(30.0);
|
||||
fixture.loop_.requestResume();
|
||||
fixture.loop_.step();
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
EXPECT_EQ(fixture.controller_.setPlanCount(), set_plan_before + 1)
|
||||
<< "resume from CONTROLLING must call setPlan() again so the plugin resets its warm start";
|
||||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// Cancel phải dừng THẬT (2026-09-11): CANCELLED chỉ khi thread planner rảnh và odom về 0.
|
||||
// Tái hiện log: cancel lúc SBPL đang chạy → host thấy CANCELLED sau 33 ms → gửi goal kế →
|
||||
// startPlan() bị từ chối vì thread còn bận → bị coi là hỏng → recovery → ABORTED.
|
||||
// ================================================================================================
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
/// Fixture với planner "chậm" (10 cycle) và KHÔNG preempt được — đúng SBPL trước pha 2.
|
||||
ControlLoopConfig busyPlannerConfig()
|
||||
{
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.planner_patience = 5.0; // [s] đủ dài để kBusy không bị patience cắt
|
||||
config.state_machine.max_planning_retries = 0; // như config trên máy chạy log
|
||||
config.state_machine.settle_timeout = 2.0; // [s]
|
||||
return config;
|
||||
}
|
||||
|
||||
constexpr std::size_t kSlowPlannerCycles = 10;
|
||||
|
||||
/// Đưa fixture tới PLANNING với một lượt lập plan đang bay, chưa có kết quả.
|
||||
void driveToPlanningInFlight(Fixture& fixture, std::uint64_t mission_id)
|
||||
{
|
||||
fixture.planner_.setLatencyCycles(kSlowPlannerCycles);
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, mission_id), reason)) << reason;
|
||||
|
||||
fixture.loop_.step(); // accept → PLANNING, startPlan()
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step(); // pollPlan: chưa có
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||||
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(ControlLoop, CancelWhilePlannerStaysBusyHoldsCancellingUntilTheThreadIsIdle)
|
||||
{
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 7);
|
||||
// reset() lúc configure và accept_request đều gọi cancelPlan() (dọn lượt cũ) — đếm tương đối.
|
||||
const std::size_t cancels_before = fixture.planner_.cancelCount();
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
EXPECT_EQ(fixture.planner_.cancelCount(), cancels_before + 1);
|
||||
EXPECT_TRUE(fixture.planner_.isPlanning()) << "the fake models a planner that cannot be preempted";
|
||||
|
||||
// Chừng nào thread còn bận: giữ CANCELLING, lệnh = 0, KHÔNG báo kết quả. Cycle mà thread rảnh
|
||||
// (pollPlan thấy lượt cũ xong) cũng chính là cycle CANCELLED — không chậm thêm vòng nào.
|
||||
std::size_t cycles_held = 0;
|
||||
for (; cycles_held < 50; ++cycles_held)
|
||||
{
|
||||
const bool busy_before = fixture.planner_.isPlanning();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
if (fixture.loop_.state() == NavigationState::kCancelled)
|
||||
{
|
||||
EXPECT_TRUE(busy_before) << "must not finish before the very cycle the thread frees";
|
||||
EXPECT_FALSE(fixture.planner_.isPlanning());
|
||||
break;
|
||||
}
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << cycles_held;
|
||||
EXPECT_TRUE(fixture.planner_.isPlanning()) << "held CANCELLING although the thread is idle";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(7), 0u) << "CANCELLED reported while planner busy";
|
||||
}
|
||||
EXPECT_GE(cycles_held, 3u) << "the fake planner should have stayed busy for several cycles";
|
||||
EXPECT_LT(cycles_held, 50u) << "never reached CANCELLED";
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_STREQ(fixture.loop_.lastOutcome(), "CANCELLED");
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, GoalSentRightAfterCancelWaitsForTheBusyPlannerInsteadOfFailing)
|
||||
{
|
||||
// Đúng chuỗi sự kiện trong log: cancel mission 3, mission 4 tới 0.2 s sau. Không được có
|
||||
// RECOVERING/ABORTED; mission 4 phải tới CONTROLLING sau khi thread rảnh.
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 3);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
|
||||
// Host không đợi PREEMPTED (hành vi cũ của khung chương trình): gửi goal kế ngay.
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 4), reason)) << reason;
|
||||
|
||||
const std::size_t make_plan_before = fixture.planner_.makePlanCount();
|
||||
bool saw_recovering = false;
|
||||
bool saw_aborted = false;
|
||||
bool reached_controlling = false;
|
||||
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
const NavigationState s = fixture.loop_.state();
|
||||
saw_recovering = saw_recovering || s == NavigationState::kRecovering;
|
||||
saw_aborted = saw_aborted || s == NavigationState::kAborted;
|
||||
reached_controlling = s == NavigationState::kControlling;
|
||||
}
|
||||
|
||||
EXPECT_FALSE(saw_recovering) << "a busy planner thread was treated as a failed planning attempt";
|
||||
EXPECT_FALSE(saw_aborted);
|
||||
EXPECT_TRUE(reached_controlling);
|
||||
EXPECT_EQ(fixture.planner_.makePlanCount(), make_plan_before + 1)
|
||||
<< "exactly one new planning attempt once the thread was free";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(3), 1u) << "mission 3 reported once (CANCELLED)";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(4), 0u) << "mission 4 is still running";
|
||||
}
|
||||
|
||||
TEST(ControlLoop, PauseWhilePlanningThenResumeWaitsForTheBusyPlanner)
|
||||
{
|
||||
// pause lúc PLANNING đi cùng đường cancelPlan(); resume → PLANNING → startPlan() bị từ chối →
|
||||
// phải là kBusy, không phải kFailed.
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 8);
|
||||
|
||||
fixture.loop_.requestPause();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPausing)
|
||||
<< "planner thread still busy: PAUSED must not be reported yet";
|
||||
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||
|
||||
fixture.loop_.requestResume();
|
||||
bool saw_recovering = false;
|
||||
bool reached_controlling = false;
|
||||
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
saw_recovering = saw_recovering || fixture.loop_.state() == NavigationState::kRecovering;
|
||||
reached_controlling = fixture.loop_.state() == NavigationState::kControlling;
|
||||
}
|
||||
EXPECT_FALSE(saw_recovering);
|
||||
EXPECT_TRUE(reached_controlling);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(8), 0u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, NewGoalPreemptingABusyPlannerWaitsInsteadOfFailing)
|
||||
{
|
||||
// MissionManager::submit() tự huỷ mission đang chạy — không cần cancel vẫn dính cùng đường.
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 11);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(6.0, 12), reason)) << reason;
|
||||
|
||||
bool saw_recovering = false;
|
||||
bool reached_controlling = false;
|
||||
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
saw_recovering = saw_recovering || fixture.loop_.state() == NavigationState::kRecovering;
|
||||
reached_controlling = fixture.loop_.state() == NavigationState::kControlling;
|
||||
}
|
||||
EXPECT_FALSE(saw_recovering);
|
||||
EXPECT_TRUE(reached_controlling);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(11), 1u) << "mission 11 reported once (PREEMPTED)";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(12), 0u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, BusyPlannerStillCountsAgainstPlannerPatience)
|
||||
{
|
||||
// kBusy không phải vé miễn phí: plugin treo thật thì planner_patience vẫn phải leo thang.
|
||||
ControlLoopConfig config = busyPlannerConfig();
|
||||
config.state_machine.planner_patience = 0.2; // [s] = 4 cycle
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setLatencyCycles(100); // treo "vĩnh viễn" so với patience
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 20), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
|
||||
// Goal kế chen ngang (preempt) trong lúc thread treo: chờ bằng kBusy tối đa planner_patience rồi
|
||||
// mới recovery. Dùng preempt thay vì cancel để không phải đợi settle_timeout ở đây.
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 21), reason)) << reason;
|
||||
bool saw_recovering = false;
|
||||
for (int i = 0; i < 30 && !saw_recovering; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
saw_recovering = fixture.loop_.state() == NavigationState::kRecovering;
|
||||
}
|
||||
EXPECT_TRUE(saw_recovering) << "a planner that never returns must still hit planner_patience";
|
||||
}
|
||||
|
||||
TEST(ControlLoop, CancelSettleTimeoutFinishesCancelledEvenIfThePlannerNeverFrees)
|
||||
{
|
||||
ControlLoopConfig config = busyPlannerConfig();
|
||||
config.state_machine.settle_timeout = 0.2; // [s] = 4 cycle
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setLatencyCycles(1000);
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 30), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
std::size_t cycles = 0;
|
||||
bool running = true;
|
||||
while (running && cycles < 20)
|
||||
{
|
||||
running = fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
++cycles;
|
||||
}
|
||||
|
||||
EXPECT_FALSE(running);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_TRUE(fixture.planner_.isPlanning()) << "the thread is still busy — settle timeout fired";
|
||||
EXPECT_GE(cycles, 4u);
|
||||
EXPECT_LE(cycles, 7u) << "CANCELLED must arrive right after settle_timeout";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(30), 1u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, CancellingWaitsForMeasuredVelocityToReadZero)
|
||||
{
|
||||
// Lệnh về 0 ngay cycle đầu, nhưng odom còn 0.3 m/s (driver đang giảm tốc) → chưa CANCELLED.
|
||||
Fixture fixture;
|
||||
fixture.controller_.setScript({ControllerScript::kOk});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 40), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
fixture.controller_.setOdometry(0.3);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << i;
|
||||
}
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(40), 0u);
|
||||
|
||||
fixture.controller_.setOdometry(0.0);
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(40), 1u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, PauseWhilePlannerBusyHoldsPausingUntilTheThreadIsIdle)
|
||||
{
|
||||
// PAUSED nói thật (2026-09-11): pause nhận trong 1 cycle (lệnh 0), nhưng PAUSED chỉ khi thread
|
||||
// planner đã nhả — cùng cơ chế với CANCELLING.
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 50);
|
||||
|
||||
fixture.loop_.requestPause();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPausing);
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kGlobalPlanner),
|
||||
move_base2::ComponentPhase::kStopping)
|
||||
<< "the fake planner reports 'stopping' after a cancel it cannot honour";
|
||||
|
||||
std::size_t held = 0;
|
||||
for (; held < 50; ++held)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
if (fixture.loop_.state() == NavigationState::kPaused)
|
||||
{
|
||||
break;
|
||||
}
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPausing) << "cycle " << held;
|
||||
EXPECT_TRUE(fixture.planner_.isPlanning());
|
||||
}
|
||||
EXPECT_GE(held, 3u);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
EXPECT_FALSE(fixture.planner_.isPlanning());
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kGlobalPlanner),
|
||||
move_base2::ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, CancellingWaitsForARecoveryWorkerReportedThroughTheStatusBoard)
|
||||
{
|
||||
// Recovery có worker thread (detour, pha 2): cancel() không kết thúc được ngay → hàng kRecovery
|
||||
// giữ 'stopping' → CANCELLING phải chờ, dù cổng planner đã rảnh và lệnh đã 0.
|
||||
Fixture fixture;
|
||||
fixture.planner_.setScript({PlannerScript::kFail});
|
||||
fixture.recovery_.setScript({RecoveryScript::kRunning});
|
||||
fixture.recovery_.setCancelKeepsBusy(true);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 60), reason)) << reason;
|
||||
for (int i = 0; i < 40 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
}
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
ASSERT_TRUE(fixture.recovery_.stopping());
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << i;
|
||||
}
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(60), 0u);
|
||||
|
||||
fixture.recovery_.settleCancel(); // worker giả đã thoát
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(60), 1u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, StatusBoardTracksLocalPlannerAndControlLoopHeartbeat)
|
||||
{
|
||||
Fixture fixture;
|
||||
fixture.controller_.setScript({ControllerScript::kOk});
|
||||
|
||||
const std::uint64_t before =
|
||||
fixture.components_.at(move_base2::Component::kControlLoop).progress_ticks.load();
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
// Heartbeat nhích mỗi step(); local planner về idle sau mỗi lượt gọi (không để "bận" treo).
|
||||
EXPECT_GE(fixture.components_.at(move_base2::Component::kControlLoop).progress_ticks.load(),
|
||||
before + 2);
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kLocalPlanner),
|
||||
move_base2::ComponentPhase::kIdle);
|
||||
EXPECT_GT(fixture.components_.at(move_base2::Component::kLocalPlanner).progress_ticks.load(), 0u)
|
||||
<< "computeVelocityCommands must have been bracketed busy/idle at least once";
|
||||
}
|
||||
|
||||
TEST(ControlLoop, MeasuredVelocityIsIgnoredWhenTheEpsSwitchesAreZero)
|
||||
{
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.stopped_measured_linear_eps = 0.0;
|
||||
config.state_machine.stopped_measured_angular_eps = 0.0;
|
||||
Fixture fixture(config);
|
||||
fixture.controller_.setScript({ControllerScript::kOk});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 41), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
fixture.controller_.setOdometry(0.3); // odom nói còn chạy — nhưng công tắc tắt
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled)
|
||||
<< "with eps = 0 'stopped' is judged from the issued command, as before 2026-09-11";
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// Nhiều chặng liên tiếp
|
||||
// ================================================================================================
|
||||
@@ -926,6 +1361,77 @@ TEST(ControlLoopActions, ActionFailureAbortsAndReportsOnce)
|
||||
EXPECT_EQ(fixture.recovery_.startCount(), 0u) << "a failed action must not drag recovery in";
|
||||
}
|
||||
|
||||
TEST(ControlLoopActions, PauseAndResumeAreForwardedToTheActionPort)
|
||||
{
|
||||
// Pha 3 (2026-09-11): handler có timeout riêng phải biết pause để dịch mốc; không báo thì 20 s
|
||||
// đứng chờ bị tính vào timeout dò 15 s → kFailed → ABORTED oan ngay sau resume.
|
||||
Fixture fixture;
|
||||
fixture.action_.setScript({ActionScript::kRunning});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 14), reason)) << reason;
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||
const std::size_t updates_before_pause = fixture.action_.updateCount();
|
||||
|
||||
fixture.loop_.requestPause();
|
||||
fixture.stepOnce();
|
||||
EXPECT_EQ(fixture.action_.pauseCount(), 1u);
|
||||
EXPECT_EQ(fixture.action_.cancelCount(), 0u) << "pause must not cancel the action";
|
||||
fixture.stepOnce(); // hàng kAction = paused → quiescent
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.action_.updateCount(), updates_before_pause) << "no ticks while paused";
|
||||
|
||||
fixture.clock_.advance(30.0);
|
||||
fixture.loop_.requestResume();
|
||||
fixture.stepOnce();
|
||||
EXPECT_EQ(fixture.action_.resumeCount(), 1u);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||
EXPECT_GT(fixture.action_.updateCount(), updates_before_pause) << "ticking resumed";
|
||||
EXPECT_EQ(fixture.action_.startCount(), 1u) << "the action must not be restarted";
|
||||
}
|
||||
|
||||
TEST(ControlLoopActions, CancelWaitsForADeviceHandlerToReportCancelled)
|
||||
{
|
||||
// Handler thiết bị cần 3 tick sau cancel() để về vị trí an toàn: CANCELLING tick tiếp, không
|
||||
// cấp vận tốc, và CANCELLED chỉ được báo sau tick kCancelled.
|
||||
Fixture fixture;
|
||||
fixture.action_.setScript({ActionScript::kRunning});
|
||||
fixture.action_.setCancelNeedsTicks(3);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 15), reason)) << reason;
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
EXPECT_EQ(fixture.action_.cancelCount(), 1u);
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kAction),
|
||||
move_base2::ComponentPhase::kStopping);
|
||||
|
||||
std::size_t held = 0;
|
||||
for (; held < 10; ++held)
|
||||
{
|
||||
if (fixture.loop_.state() == NavigationState::kCancelled)
|
||||
{
|
||||
break;
|
||||
}
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << held;
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(15), 0u) << "CANCELLED reported before the device was safe";
|
||||
fixture.stepOnce();
|
||||
}
|
||||
EXPECT_GE(held, 3u) << "the handler asked for 3 ticks after cancel";
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(15), 1u);
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kAction),
|
||||
move_base2::ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
TEST(ControlLoopActions, SubmitRejectsActionRequestWhenActionPortMissing)
|
||||
{
|
||||
Fixture fixture;
|
||||
|
||||
195
test/watchdog_test.cpp
Normal file
195
test/watchdog_test.cpp
Normal file
@@ -0,0 +1,195 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — test watchdog: kết luận treo từ bảng trạng thái, trên thread riêng.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/io/watchdog.h>
|
||||
|
||||
using move_base2::Component;
|
||||
using move_base2::ComponentPhase;
|
||||
using move_base2::ComponentStatusBoard;
|
||||
using move_base2::Watchdog;
|
||||
using move_base2::WatchdogConfig;
|
||||
|
||||
namespace
|
||||
{
|
||||
WatchdogConfig fastConfig()
|
||||
{
|
||||
WatchdogConfig c;
|
||||
c.period = 0.01; // [s]
|
||||
c.planner_timeout = 0.05; // [s]
|
||||
c.local_planner_call_budget = 0.05;
|
||||
c.recovery_stall_budget = 0.05;
|
||||
c.action_stall_budget = 0.05;
|
||||
c.control_loop_stall_budget = 0.05;
|
||||
return c;
|
||||
}
|
||||
|
||||
void sleepMs(int ms)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(WatchdogConfig, RejectsNegativePeriodAndNonFiniteBudgets)
|
||||
{
|
||||
WatchdogConfig c;
|
||||
std::string error;
|
||||
c.period = -0.1;
|
||||
EXPECT_FALSE(c.validate(error));
|
||||
c = WatchdogConfig();
|
||||
c.planner_timeout = std::numeric_limits<double>::infinity();
|
||||
EXPECT_FALSE(c.validate(error));
|
||||
c = WatchdogConfig();
|
||||
c.period = 0.0; // tắt = hợp lệ
|
||||
EXPECT_TRUE(c.validate(error)) << error;
|
||||
EXPECT_NE(c.describe().find("planner_timeout"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(Watchdog, IdleRowsAreNeverHung)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0; // không thread — checkOnce() tay
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||
sleepMs(80);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.anyHung()) << "idle for a long time is not 'hung'";
|
||||
}
|
||||
|
||||
TEST(Watchdog, BusyWithoutProgressBecomesHungAndRecoversOnProgress)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0;
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "just started";
|
||||
|
||||
sleepMs(30);
|
||||
board.progress(Component::kGlobalPlanner); // vẫn nhích → không treo dù bận lâu
|
||||
sleepMs(30);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "busy but progressing";
|
||||
|
||||
sleepMs(80); // > 0.05 s không nhích
|
||||
dog.checkOnce();
|
||||
EXPECT_TRUE(dog.hung(Component::kGlobalPlanner));
|
||||
EXPECT_TRUE(dog.anyHung());
|
||||
EXPECT_NE(dog.report().find("global_planner"), std::string::npos);
|
||||
|
||||
board.progress(Component::kGlobalPlanner);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "recovered";
|
||||
}
|
||||
|
||||
TEST(Watchdog, StoppingCountsAsWatchedButPausedDoesNot)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0;
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
|
||||
board.enter(Component::kRecovery, ComponentPhase::kStopping);
|
||||
board.enter(Component::kAction, ComponentPhase::kPaused);
|
||||
sleepMs(80);
|
||||
dog.checkOnce();
|
||||
EXPECT_TRUE(dog.hung(Component::kRecovery)) << "told to stop and never returned = hung";
|
||||
EXPECT_FALSE(dog.hung(Component::kAction)) << "a paused handler is not expected to progress";
|
||||
}
|
||||
|
||||
TEST(Watchdog, ZeroBudgetDisablesThatRow)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0;
|
||||
c.action_stall_budget = 0.0;
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
|
||||
board.enter(Component::kAction, ComponentPhase::kBusy);
|
||||
sleepMs(80);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.hung(Component::kAction));
|
||||
}
|
||||
|
||||
TEST(Watchdog, ControlLoopHeartbeatStallIsDetectedFromTheWatchdogThread)
|
||||
{
|
||||
// Mô hình thật: control thread heartbeat cuối mỗi step(); ngừng heartbeat = treo. Watchdog chạy
|
||||
// thread riêng và phải tự thấy — đây là thứ control thread không tự làm được.
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
ASSERT_TRUE(dog.start(&board, fastConfig(), error)) << error;
|
||||
ASSERT_TRUE(dog.running());
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
board.progress(Component::kControlLoop);
|
||||
sleepMs(10);
|
||||
}
|
||||
EXPECT_FALSE(dog.controlLoopHung());
|
||||
|
||||
sleepMs(120); // không heartbeat
|
||||
EXPECT_TRUE(dog.controlLoopHung());
|
||||
|
||||
board.progress(Component::kControlLoop);
|
||||
sleepMs(40);
|
||||
EXPECT_FALSE(dog.controlLoopHung());
|
||||
|
||||
dog.stop();
|
||||
EXPECT_FALSE(dog.running());
|
||||
}
|
||||
|
||||
TEST(Watchdog, RowThatNeverProgressedIsNotHung)
|
||||
{
|
||||
// Runtime mới lên: control loop chưa chạy cycle nào, last_progress = 0 — không được báo treo ngay.
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0;
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
sleepMs(80);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.controlLoopHung());
|
||||
}
|
||||
|
||||
TEST(Watchdog, StartRequiresABoardAndRefusesDoubleStart)
|
||||
{
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
EXPECT_FALSE(dog.start(nullptr, fastConfig(), error));
|
||||
ComponentStatusBoard board;
|
||||
ASSERT_TRUE(dog.start(&board, fastConfig(), error)) << error;
|
||||
EXPECT_FALSE(dog.start(&board, fastConfig(), error)) << "already running";
|
||||
dog.stop();
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
Reference in New Issue
Block a user