16 Commits

Author SHA1 Message Date
c6e70b7dc5 config(move_base_common): add costmap_ready_timeout
Sim tree copy of the key PlannerRunner reads: how long a goal waits for every enabled global layer to be current before planning (default 10 s, 0 = legacy behaviour).
2026-11-04 13:23:48 +07:00
6decd8db32 feat(move_base2): wait for a ready global costmap and replay maps in host order
- Replay static maps in arrival order instead of topic order, so a
  direction grid can no longer be replayed before its static map (F3).
- PlannerRunner checks every enabled global layer under the same lock as
  the snapshot; while not current it keeps the goal, reports
  waiting_for_costmap, logs the stale layers (throttled) and does not
  spend planner_patience or watchdog budget. After costmap_ready_timeout
  [s] (default 10, 0 = legacy behaviour) the attempt fails as before.
- Test fixture destroys the server before its fake ports; the control
  thread could call a destroyed port (race existed before this change).
2026-11-04 11:14:15 +07:00
7bfb3c362d fix(sensor_gateway): give static maps to the directional layer first
With a same-geometry map, StaticLayer could be written and report current
between the two dispatches while the old direction field was still READY,
so a plan could pair the new map with the old zones. The directional
layer only needs the map topic to go PENDING, and direction grids are
ignored by StaticLayer, so dispatching it first needs no lock.
2026-11-04 11:14:15 +07:00
f85d89ef8c feat(sensor_gateway): deliver static map grids to the directional layer
pushStaticMap now also dispatches to DIRECTIONAL_LAYER on the global costmap, after STATIC_LAYER so the master is already resized to the new map when the directional layer checks a direction grid against it. The layer filters by topic: map_topic resets it to PENDING, direction_topic carries the direction grid.
2026-11-03 16:57:01 +07:00
75af8ccf12 feat(planner_runner): bind dock_face_offset and dock_pivot_safety_margin per marker
Two new DockPlanner keys, valid only with dock_anchor: mating_edge, are copied from
docking_marker_profiles/<marker> into the planner namespace like footprint_dock and
dock_anchor.

Unlike those two, the new keys are optional. A marker that does not declare one would keep
the value bound by the previous marker, so the charger's smaller pivot margin could leak
into a later trolley docking. When the marker lacks a key that the planner namespace still
holds, the binder writes a YAML null, which DockPlanner reads as unset, and counts it as a
change so that the instance is rebuilt. footprint_dock and dock_anchor keep their old
behaviour.
2026-10-29 16:54:02 +07:00
c3c64919d3 feat(control_loop): reserve backup_global_planner for the position profile
A failed primary global planner on a docking, go_straight or rotate request no longer swaps to backup_global_planner. It goes straight to the planning_failed recovery route and aborts. Only the position profile may use the backup planner. Update STATE_MACHINE.md and add test NonPositionPlannerFailureSkipsBackup.
2026-10-27 13:09:30 +07:00
ea7f9659b8 feat(sensor_gateway): feed DepthCameraObstacleLayer through its own LayerType
robot_costmap_2d has LayerType::DEPTH_CAMERA_LAYER for
DepthCameraObstacleLayer. The gateway now pushes PointCloud2 to that type
as well as to VOXEL_LAYER, in both the local and the global costmap.
LaserScan, PointCloud and DepthCameraData stay VOXEL_LAYER only: the layer
marks and clears from the filtered camera cloud and does not use the depth
image.

Needs robot_costmap_2d main 64974d4 or later (the enum value).

Squashed from feature/depth-camera-layer-type (c280a0a..d3a9208).
2026-10-21 14:21:53 +07:00
8977e5ec14 docs: trỏ EnvMonitor sang Test/docs/move_base2/, xoá PLAN_LIFECYCLE đã chuyển, priest num_obs_proj 200
- Comment trong include/move_base2 (config, control_loop, core/env_monitor, core/grid_analysis,
  io/env_logger, ports/environment_port), src/control_loop.cpp và test/walking_skeleton_test.cpp:
  đường dẫn ENV_MONITOR_PLAN.md đổi từ Test/ sang Test/docs/move_base2/. Không đổi dòng code nào.
- docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md: xoá, bản plan đã nằm ở Test/docs/move_base2/.
- config/runtime/priest_local_planner_params.yaml: num_obs_proj 90 -> 200 (số vật cản gần nhất
  đưa vào phép chiếu ADMM), giữ theo quyết định của người dùng.
2026-10-03 15:36:15 +07:00
490f48becb Revert "feat: tiep nhan route graph (Voronoi) cho global planner + anytime ARA* schema, don doc EnvMonitor"
This reverts commit f4f99650df.
2026-10-03 15:30:15 +07:00
f4f99650df feat: tiep nhan route graph (Voronoi) cho global planner + anytime ARA* schema, don doc EnvMonitor
- navigation_server: them addRouteGraph(topic, RouteGraph), day vao sensor_store cung namespace
  addStaticMap; consumer (SBPLLatticePlanner) tu doi chieu map_hash.
- PlannerRunner: them setSensorReader()/attachSensors() - trao SensorReader cho global planner
  nao ke thua robot_sensor_ports::SensorConsumer, goi TRUOC initialize() (dynamic_cast, giong co
  che ControllerRunner dang dung).
- sensor_store_params.yaml: khai topic /route_graph (data_type RouteGraph, capacity 1).
- sbpl_global_params.yaml (config/runtime): dong bo schema initial_epsilon/final_epsilon/
  eps_step/repair_time/return_first_solution + khoi voronoi_corridor (xem pnkx_nav_core
  c52cbe5, Test/sbpl_lattice_planner cho code doc cac khoa nay).
- launch: them arg launch_prefix (vd "stdbuf -oL" - robot::log_* dung printf khong flush, qua
  `| tee` bi block-buffer 8 KB lam log dung o dong cu du node con chay); them
  route_graph_maps_dir/route_graph_topic cho amr_node doc file voronoi.json theo map dang kich hoat.
- docs: xoa PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md (don sang Test/docs/move_base2/), sua duong dan
  ENV_MONITOR_PLAN.md trong comment cac header EnvMonitor lien quan.
2026-09-22 15:31:43 +07:00
1e8abf2ce4 perf: global planner doc snapshot costmap thay vi giu mutex het luot makePlan
PlannerRunner truoc gio giu Costmap2D mutex suot makePlan() (giao thuc gen-1) - SBPL search
6-14s la costmap update thread bi block het tung do. Them capability boost::dll
"<alias>ExternalGrid" (cung mau sbpl_recovery dang dung) de planner nhan ban chup thay vi
lock song. threadBody(): planner co setter + costmap bat snapshot_for_readers thi
refreshSnapshot() + dua ban chup vao, khong lock; khong thi rot ve giu mutex nhu cu (rollback
khong build lai). SBPLLatticePlanner them setExternalGrid()/activeGrid(); sua luon check
size external_grid_ so voi grid (grid = activeGrid() nen so voi chinh no, khong bao gio bat
duoc lech) - so dung costmap_robot_->getCostmap() (luoi song).

Test: ReportsExternalGridCapabilityPerPlanner, ExternalGridIsNotCalledWhileTheCostmapLockIsDisabled.
config/runtime: bat snapshot_for_readers: true (cay sim). docs/THREADING.md: bang so sanh khoa
dai vs ban chup.
2026-09-18 13:32:52 +07:00
0d333212b1 config: go schema hybrid path-tracking khoi priest params (revert)
priest_local_planner da reset ve 28e0636 (bo feat hybrid path-tracking
PathTrackerCore/HybridArbiter). Khoa hybrid_mode/tracker_*/blend_*/
debug_hybrid khong con duoc code doc nua, go theo cho khop schema -
noi dung file khop dung dc35900^ (bb64511), giu nguyen cac tune khac
(goal_tolerance, max_velocity...).
2026-09-17 13:43:58 +07:00
9f504ee50e config: bat hybrid_mode 1 -> 2 (cay sim runtime)
SHADOW (1, chi log doi chieu) -> muc ke tiep trong plan hybrid
path-tracking (xem README priest_local_planner).
2026-09-17 13:37:37 +07:00
b205cf41bc config(priest): blend_dev_noise/avoid 0.05/0.20 -> 0.15/0.30 + blend_dev_gate_obstacles (do 17/9) 2026-09-17 09:45:50 +07:00
dc359007b8 config: them khoa hybrid_mode + tracker/blend cho priest_local_planner (cay sim)
hybrid_mode: 1 (shadow) de thu log [DBG-PRIEST-HYB] doi chieu tracker voi
solver truoc khi chuyen 2. Xem doc/HYBRID_TRACK_AVOID_PLAN.md va commit
tuong ung o priest_local_planner (nhanh feature/hybrid-track-avoid).
2026-09-16 18:51:07 +07:00
bb645111f7 tune: xy/yaw_goal_tolerance 0.02/0.01 -> 0.04/0.04 (P4)
Dung sai cu bat kha thi ve vat ly: dung tu 0.15 m/s trong 2 cm can a=0.56
m/s^2 > decel_comfort 0.35 (do 15/9: dist=0.06 ma vmeas=0.17), robot BAT
BUOC vuot goal. yaw 0.01 rad (0.57 deg) nam duoi nhieu odometry, robot san
diem dung. Vanh nha latch (= tolerance x xy_latch_release_factor) theo do
nghi 0.10 -> 0.20 m: do 16/9 latch o 0.093 roi nha o 0.100 vi xoay tai cho
troi 7mm, 0.10 qua sat.
2026-09-16 18:31:30 +07:00
36 changed files with 931 additions and 959 deletions

View File

@@ -14,10 +14,20 @@ global_costmap:
# 0 = giữ nguyên output cũ; 1 = thêm dòng lock_wait/lock_hold (tranh chấp mutex với planner), # 0 = giữ nguyên output cũ; 1 = thêm dòng lock_wait/lock_hold (tranh chấp mutex với planner),
# kích thước window update [cells] và số cycle rỗng; 2 = thêm per-layer: layer nào nở bounds bao nhiêu [m^2]. # kích thước window update [cells] và số cycle rỗng; 2 = thêm per-layer: layer nào nở bounds bao nhiêu [m^2].
debug_level: 0 debug_level: 0
# [bool] Reader tính toán trên BẢN COPY (snapshot) của costmap thay vì lưới live — xem giải thích # [bool] Global planner tính toán trên BẢN COPY (snapshot) của costmap thay vì lưới live.
# ở costmap_local_params.yaml. Global costmap để false: global planner chưa chuyển sang snapshot # true: đầu mỗi lượt makePlan, PlannerRunner copy lưới global dưới lock (~0.3 ms cho 1397x777,
# (planner_runner vẫn dùng khoá dài), và global đang idle nên không có tranh chấp đáng kể. # ~5 ms cho 3060x3060) rồi đưa bản copy cho planner qua capability "<alias>ExternalGrid" —
snapshot_for_readers: false # thread update global costmap không còn bị chặn suốt lượt search. Đo 2026-09-17: SBPL cạn
# search 6-14 s/lượt, thread costmap đứng đúng chừng ấy, log "Map update global_costmap loop
# missed its desired rate". Planner vẫn thấy lưới "đông cứng" suốt lượt tính; kết quả plan
# KHÔNG đổi so với khoá dài (cùng cost/số state với cùng goal).
# Chỉ có tác dụng với plugin export capability đó — hiện là SBPLLatticePlanner. CustomPlanner /
# DockPlanner / TwoPointsPlanner không có, tự rơi về khoá dài (chúng chạy vài ms, vô hại).
# Dòng boot "[move_base2] global planner '...' reads the costmap via SNAPSHOT|LONG LOCK" cho biết
# đang ở nhánh nào.
# false: hành vi cũ — giữ mutex suốt makePlan. Công tắc rollback, không cần build lại.
# ► Chỉnh: cây sim bật để đo; cây robot thật giữ false tới khi có số trên robot.
snapshot_for_readers: true
raytrace_range: 3.0 raytrace_range: 3.0
resolution: 0.05 resolution: 0.05
z_resolution: 0.2 z_resolution: 0.2

View File

@@ -125,6 +125,16 @@ sensor_patience: 2.0
# Chỉ bật (0.5–1.0) nếu sau này global planner vừa tránh được vật cản vừa đủ nhanh (~30 ms). # Chỉ bật (0.5–1.0) nếu sau này global planner vừa tránh được vật cản vừa đủ nhanh (~30 ms).
planner_frequency: 0.0 planner_frequency: 0.0
# [s] Thời gian tối đa giữ goal để chờ global costmap sẵn sàng trước khi lập plan. "Sẵn sàng" là
# mọi layer đang bật đều current: StaticLayer đã ghi map mới vào master, DirectionalLayer đã nhận
# grid hướng sau static map mới nhất. Trong lúc chờ, goal được giữ, không tính vào
# `planner_patience`, log ghi tên layer chưa sẵn sàng.
# ► Tăng: chờ được map/grid đến chậm (đổi map lớn, app gửi grid hướng muộn).
# ► Giảm: báo lỗi sớm hơn khi host quên gửi dữ liệu; quá thấp thì mission fail giả lúc đổi map.
# ► 0: tắt kiểm tra, quay về hành vi cũ — planner có thể lập plan trên map dở dang hoặc bị SBPL
# từ chối ngay khi direction còn PENDING.
costmap_ready_timeout: 10.0
# [s] Ở PLANNING quá lâu mà chưa có plan -> recovery. Mất pose ngay trong PLANNING dùng ngân sách # [s] Ở PLANNING quá lâu mà chưa có plan -> recovery. Mất pose ngay trong PLANNING dùng ngân sách
# `controlling_failed` (xem recovery_behaviors_params.yaml). # `controlling_failed` (xem recovery_behaviors_params.yaml).
# ► Chỉnh: đặt > thời gian lập plan xấu nhất của global planner. SBPL `allocated_time: 10.0` ở # ► Chỉnh: đặt > thời gian lập plan xấu nhất của global planner. SBPL `allocated_time: 10.0` ở

View File

@@ -140,8 +140,13 @@ PriestLocalPlanner:
# sát. 0 = tắt (một sàn duy nhất như cũ) # sát. 0 = tắt (một sàn duy nhất như cũ)
# ================= Goal / plan ================= # ================= Goal / plan =================
xy_goal_tolerance: 0.02 # [m] sai số vị trí chấp nhận là đã tới goal xy_goal_tolerance: 0.04 # [m] sai số vị trí chấp nhận là đã tới goal. [16/9] 0.02 -> 0.04 (P4 plan
yaw_goal_tolerance: 0.01 # [rad] sai số góc chấp nhận là đã tới goal # 28/8): dừng từ 0.15 m/s trong 2 cm cần a=0.56 > decel_comfort 0.35, robot
# BẮT BUỘC vượt goal (đo 15/9: dist=0.06 mà vmeas=0.17). Vành nhả latch
# = tolerance x xy_latch_release_factor cũng nới 0.10 -> 0.20 m: đo 16/9
# latch ở 0.093 rồi nhả ở 0.100 vì xoay tại chỗ trôi 7 mm — 0.10 quá sát.
yaw_goal_tolerance: 0.04 # [rad] sai số góc chấp nhận là đã tới goal. [16/9] 0.01 -> 0.04 (2.3 deg):
# 0.01 rad (0.57 deg) nằm dưới nhiễu odometry, robot săn điểm dừng.
xy_latch_release_factor: 5.0 # chốt XY: vào trong xy_goal_tolerance là coi phần vị trí XONG, chỉ xy_latch_release_factor: 5.0 # chốt XY: vào trong xy_goal_tolerance là coi phần vị trí XONG, chỉ
# [19/8] 2.0 với tolerance 0.02 = vành nhả 0.04 m — robot latch lúc # [19/8] 2.0 với tolerance 0.02 = vành nhả 0.04 m — robot latch lúc
# còn trôi 0.2 m/s (phanh cần 4-6 cm) là văng khỏi vành ngay, xoay # còn trôi 0.2 m/s (phanh cần 4-6 cm) là văng khỏi vành ngay, xoay
@@ -250,7 +255,7 @@ PriestLocalPlanner:
num_obs: 200 # số vật cản đưa vào hàm chi phí CEM. TRẦN CỨNG trong code là 200 — num_obs: 200 # số vật cản đưa vào hàm chi phí CEM. TRẦN CỨNG trong code là 200 —
# đặt lớn hơn thì clampWarn hạ xuống 200 lúc nạp, nên con số 250 trước # đặt lớn hơn thì clampWarn hạ xuống 200 lúc nạp, nên con số 250 trước
# đây chỉ là ảo: đọc YAML tưởng 250 mà thực chạy 200. # đây chỉ là ảo: đọc YAML tưởng 250 mà thực chạy 200.
num_obs_proj: 90 # số vật cản gần nhất đưa vào phép chiếu (ADMM). num_obs_proj: 200 # số vật cản gần nhất đưa vào phép chiếu (ADMM).
# ĐÂY LÀ NÚT THẮT THỜI GIAN GIẢI: chi phí phép chiếu tỉ lệ THẲNG với # ĐÂY LÀ NÚT THẮT THỜI GIAN GIẢI: chi phí phép chiếu tỉ lệ THẲNG với
# số này (đo 29/8 bãi dày, num_obs_proj=200: proj 16-24 ms trên tổng # số này (đo 29/8 bãi dày, num_obs_proj=200: proj 16-24 ms trên tổng
# 30-37 ms, vượt trần 30 ms nên chu kỳ điều khiển trượt nhịp và lệnh # 30-37 ms, vượt trần 30 ms nên chu kỳ điều khiển trượt nhịp và lệnh

View File

@@ -10,6 +10,29 @@ SBPLLatticePlanner:
# (turn_around_priority) nên không cần SBPL vẽ cung quay đầu khi goal ở phía sau. # (turn_around_priority) nên không cần SBPL vẽ cung quay đầu khi goal ở phía sau.
# Nếu không ra nghiệm, planner tự retry một lần với heading thật của robot. # Nếu không ra nghiệm, planner tự retry một lần với heading thật của robot.
free_start_heading: true free_start_heading: true
# [bool] Ô UNKNOWN (chưa scan) có đi được không. Khai TƯỜNG MINH — thiếu khoá thì code rơi về true
# và log cảnh báo lúc boot.
# true : unknown = free. Goal ngoài vùng đã map vẫn có "đường điểm" qua vùng trống ngoài nhà ->
# ARA* quét toàn bộ free + unknown (6-7 s trên map 70x39 m, đo máy dev 2026-09-17) rồi
# mới báo không có đường. Sim có tường hở mới cần true.
# false: unknown = tường. Goal ngoài vùng đã map bị từ chối ngay ở bước "2D reachability: h=INF"
# (~0.1 s). Robot thật nên false — không lập plan xuyên chỗ chưa nhìn thấy.
allow_unknown: true
# ===== Chẩn đoán lập plan (2026-09-18) =====
# Dòng LỖI KHÔNG tắt được bằng khoá nào: "goal REJECTED ..." (goal đứng trên ô >= 253 hoặc footprint
# đè tường/mép lưới), "2D reachability: h=INF ..." (goal bị bịt kín), "NO SOLUTION ... reason=
# EXHAUSTED|TIMEOUT expands=... phase_elapsed=..." (search chạy mà không ra). Đọc reason:
# EXHAUSTED + h_2d hữu hạn = có đường cho ĐIỂM, không có đường cho FOOTPRINT (khe hẹp, hoặc goal
# hợp lệ nhưng không action nào kết thúc đúng (x,y,theta) đó).
# TIMEOUT = hết allocated_time -> nới allocated_time hoặc tăng initial_epsilon.
# [bool] Nhóm log thông tin: "audit: start cell ... goal cell ...", "2D reachability: h=<số>",
# "solved: ... expands= h_2d= phase=". Mặc định BẬT; tắt khi log robot thật quá dày.
debug_plan: true
# [ô] Bán kính cửa sổ lưới in ASCII quanh goal VÀ start khi goal bị từ chối / không có đường.
# 0 = tắt. 15 = 31x31 ô = 1.5 m @ 5 cm mỗi cửa sổ (62 dòng log mỗi lần fail). Trần 60.
# Ký hiệu: . free - preferred : inflated/unpreferred i inscribed # lethal ? unknown S G.
# Bật khi cần thấy VÁCH nào chặn mà không cần dump costmap; rất nặng log, tắt lại sau khi xong.
debug_grid_window: 0
nominalvel_mpersecs: 0.3 nominalvel_mpersecs: 0.3
timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s
# Bộ sinh bởi `Test/mprim_gen` (configs/differential.py), thay `unicycle_highcost_5cm.mprim` # Bộ sinh bởi `Test/mprim_gen` (configs/differential.py), thay `unicycle_highcost_5cm.mprim`

View File

@@ -1,885 +0,0 @@
# 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.

View File

@@ -11,7 +11,7 @@ Khi cần đổi hành vi: sửa tài liệu này trước, sửa test, rồi m
| State | Ai phát cmd_vel | Vào state khi | Ra khi | | State | Ai phát cmd_vel | Vào state khi | Ra khi |
|---|---|---|---| |---|---|---|---|
| `IDLE` | không ai (0) | khởi động; cycle ngay sau một state terminal | có `NavigationRequest` đang chờ → `PLANNING`; yêu cầu chỉ-có-action (`has_goal == false`, D8) → `EXECUTING_ACTIONS`; yêu cầu không có goal lẫn action → `ABORTED` (tự vệ) | | `IDLE` | không ai (0) | khởi động; cycle ngay sau một state terminal | có `NavigationRequest` đang chờ → `PLANNING`; yêu cầu chỉ-có-action (`has_goal == false`, D8) → `EXECUTING_ACTIONS`; yêu cầu không có goal lẫn action → `ABORTED` (tự vệ) |
| `PLANNING` | không ai (0) | nhận yêu cầu; 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" | | `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, chặng là profile `position` 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ỗ | | `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` | | `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()` → `PAUSING` → `PAUSED` (không huỷ action) | | `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) |
@@ -103,7 +103,11 @@ Từ 2026-08-04, replan trong lúc chạy và recovery là **hai cơ chế tách
`backup_global_planner` là một alias tùy chọn ở root config. Khi global planner active trả `false` `backup_global_planner` là một alias tùy chọn ở root config. Khi global planner active trả `false`
hoặc plan rỗng, `ControlLoop` đổi sang alias này **một lần duy nhất cho mỗi request**, giữ nguyên hoặc plan rỗng, `ControlLoop` đổi sang alias này **một lần duy nhất cho mỗi request**, giữ nguyên
local planner và state `PLANNING`. Lượt backup thành công đi bình thường vào `CONTROLLING`; lượt local planner và state `PLANNING`. **Chỉ áp cho profile `position`**: `docking`, `go_straight`,
`rotate` fail thì không đổi planner mà đi thẳng `PlannerFeedback::kFailed` (log WARN `backup '...'
is reserved for profile position`). Lý do (robot KIT 26/10): DockPlanner fail vì robot đứng quá gần
dock, SBPL dựng đường thẳng tới pose tiếp xúc và robot bám đường đó vào dock, bỏ qua cusp và đoạn
lùi thẳng. Lượt backup thành công đi bình thường vào `CONTROLLING`; lượt
backup fail mới được đưa vào `PlannerFeedback::kFailed`, nên state machine đi theo recovery hiện có. backup fail mới được đưa vào `PlannerFeedback::kFailed`, nên state machine đi theo recovery hiện có.
Backup dùng overload `makePlan(start, goal, plan)` (không mang VDA5050 `Order`) để Backup dùng overload `makePlan(start, goal, plan)` (không mang VDA5050 `Order`) để

View File

@@ -38,6 +38,24 @@ Bất biến này được củng cố ở hai chỗ, độc lập nhau:
`ControlLoop` và `StateMachine` **không** có mutex nào và cố ý như vậy: chúng chỉ chạy trên control `ControlLoop` và `StateMachine` **không** có mutex nào và cố ý như vậy: chúng chỉ chạy trên control
thread. Thêm mutex vào đó sẽ che mất việc có ai đó gọi sai thread. thread. Thêm mutex vào đó sẽ che mất việc có ai đó gọi sai thread.
### Global planner: khoá dài hay bản chụp (2026-09-18)
Thread `planner` phải thấy lưới global **đông cứng** suốt `makePlan` (`updateMap` ghi, `resizeMap`
realloc, cùng `Costmap2D::getMutex()`). Hai cách, chọn lúc boot:
| Điều kiện | Cách đọc | Map-update thread global |
|---|---|---|
| `global_costmap.snapshot_for_readers: true` **và** plugin export alias `"<alias>ExternalGrid"` | `refreshSnapshot()` (mutex chỉ trong memcpy) rồi planner đọc bản copy qua capability | chạy tiếp, chỉ chờ ~0.3 ms (1397×777) / ~5 ms (3060²) mỗi lượt |
| còn lại | khoá dài, gen-1 | đứng chờ hết lượt search — SBPL cạn search là 6–14 s (đo 2026-09-17) |
Hôm nay chỉ `SBPLLatticePlanner` export capability (cùng alias `sbpl_recovery` dùng cho lưới gộp).
`CustomPlanner` / `DockPlanner` / `TwoPointsPlanner` chạy vài ms nên khoá dài với chúng vô hại.
Dòng boot `global planner '<tên>' reads the costmap via SNAPSHOT|LONG LOCK` nói rõ đang ở nhánh nào.
**Single-consumer:** bản chụp global chỉ có **một** reader là thread `planner`. Exporter và recovery
đọc lưới sống dưới khoá ngắn, `EnvMonitor` gắn local costmap. Thêm reader global trên control thread
qua `getCostmapForRead()` là race với thread này — dùng lưới sống + khoá ngắn thay vì snapshot.
### Ngoại lệ có chủ đích: dừng khẩn ghi đè trên thread host (2026-09-14) ### Ngoại lệ có chủ đích: dừng khẩn ghi đè trên thread host (2026-09-14)
`NavigationServer::emergency_latched_` là **atomic duy nhất mà thread host đọc để ghi đè output của `NavigationServer::emergency_latched_` là **atomic duy nhất mà thread host đọc để ghi đè output của

View File

@@ -53,6 +53,9 @@ struct MoveBase2Config
*/ */
double planner_timeout = 5.0; double planner_timeout = 5.0;
/// [s] Continuous global-costmap readiness wait; 0 disables the check (legacy behavior).
double costmap_ready_timeout = 10.0;
/** /**
* Watchdog (2026-09-11): thread riêng đọc bảng trạng thái thành phần, kết luận "treo" theo ngân * 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. * sách từng hàng. `watchdog.planner_timeout` được chép từ @ref planner_timeout khi nạp.
@@ -157,7 +160,7 @@ struct MoveBase2Config
/// Lỗi schema của `docking_marker_profiles`, giữ lại để @ref validate chặn boot an toàn. /// Lỗi schema của `docking_marker_profiles`, giữ lại để @ref validate chặn boot an toàn.
std::string docking_marker_profiles_error; std::string docking_marker_profiles_error;
// --- EnvMonitor (Test/ENV_MONITOR_PLAN.md) — namespace con `env_monitor` ------------------------ // --- EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — namespace con `env_monitor` ------------------------
EnvMonitorConfig env_monitor; ///< lõi quyết định (stall / unreachable / contact / ngân sách). EnvMonitorConfig env_monitor; ///< lõi quyết định (stall / unreachable / contact / ngân sách).
EnvSamplingConfig env_sampling; ///< lấy mẫu ở cổng (nhịp, thân, hình học, quỹ đạo). EnvSamplingConfig env_sampling; ///< lấy mẫu ở cổng (nhịp, thân, hình học, quỹ đạo).
EnvLoggerConfig env_logger; ///< ghi JSONL cho replay/ML. Tắt mặc định. EnvLoggerConfig env_logger; ///< ghi JSONL cho replay/ML. Tắt mặc định.

View File

@@ -67,7 +67,7 @@ struct ControlLoopDeps
/** /**
* Nguồn dữ liệu của EnvMonitor (Test/ENV_MONITOR_PLAN.md). **Có thể null** — null thì EnvMonitor tắt * Nguồn dữ liệu của EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md). **Có thể null** — null thì EnvMonitor tắt
* hoàn toàn, mọi bộ test dùng cổng giả rơi vào nhánh này. * hoàn toàn, mọi bộ test dùng cổng giả rơi vào nhánh này.
*/ */
EnvironmentPort* environment = nullptr; EnvironmentPort* environment = nullptr;
@@ -109,6 +109,9 @@ struct ControlLoopConfig
/// [s] Chu kỳ danh nghĩa, chỉ dùng cho dt của cycle ĐẦU TIÊN khi chưa có mốc thời gian trước đó. /// [s] Chu kỳ danh nghĩa, chỉ dùng cho dt của cycle ĐẦU TIÊN khi chưa có mốc thời gian trước đó.
double nominal_control_period = 0.05; double nominal_control_period = 0.05;
/// [s] Maximum continuous global-costmap wait; 0 disables the readiness check.
double costmap_ready_timeout = 10.0;
/// Công tắc log chẩn đoán. Xem `MoveBase2Config::debug_*` để biết từng nhóm in cái gì. /// Công tắc log chẩn đoán. Xem `MoveBase2Config::debug_*` để biết từng nhóm in cái gì.
bool debug_state = true; bool debug_state = true;
bool debug_plan = true; bool debug_plan = true;
@@ -159,7 +162,7 @@ struct ControlLoopConfig
DockingMarkerProfiles docking_marker_profiles; DockingMarkerProfiles docking_marker_profiles;
// --- EnvMonitor (Test/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 ---------- // --- EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 ----------
EnvMonitorConfig env_monitor; EnvMonitorConfig env_monitor;
EnvSamplingConfig env_sampling; EnvSamplingConfig env_sampling;
EnvLoggerConfig env_logger; EnvLoggerConfig env_logger;

View File

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

View File

@@ -2,7 +2,7 @@
* *
* Software License Agreement (BSD License) * Software License Agreement (BSD License)
* *
* move_base2 — lõi quyết định của EnvMonitor (Test/ENV_MONITOR_PLAN.md §2.3, P2). * move_base2 — lõi quyết định của EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md §2.3, P2).
* *
* Thuần: không costmap, không TF, không log, không cấp phát sau `configure`. Vào là một @ref EnvSample * Thuần: không costmap, không TF, không log, không cấp phát sau `configure`. Vào là một @ref EnvSample
* mỗi control cycle (feature đã tính ở cổng bằng `grid_analysis`), ra là một @ref EnvVerdict: các cờ * mỗi control cycle (feature đã tính ở cổng bằng `grid_analysis`), ra là một @ref EnvVerdict: các cờ
@@ -33,7 +33,7 @@ namespace move_base2
/** /**
* @struct EnvMonitorConfig * @struct EnvMonitorConfig
* @brief Tham số lõi. Đơn vị trong tên hoặc comment. Mọi ngưỡng số là GIÁ TRỊ KHỞI ĐIỂM rút từ hai bag * @brief Tham số lõi. Đơn vị trong tên hoặc comment. Mọi ngưỡng số là GIÁ TRỊ KHỞI ĐIỂM rút từ hai bag
* sim 5/9/2026 (ENV_MONITOR_PLAN.md §4.4); chốt lại bằng shadow/replay, không bằng tay. * sim 5/9/2026 (Test/docs/move_base2/ENV_MONITOR_PLAN.md §4.4); chốt lại bằng shadow/replay, không bằng tay.
*/ */
struct EnvMonitorConfig struct EnvMonitorConfig
{ {

View File

@@ -2,7 +2,7 @@
* *
* Software License Agreement (BSD License) * Software License Agreement (BSD License)
* *
* move_base2 — phân tích hình học trên local costmap cho EnvMonitor (Test/ENV_MONITOR_PLAN.md, P1). * move_base2 — phân tích hình học trên local costmap cho EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md, P1).
* *
* Hàm thuần trên `robot_costmap_2d::Costmap2D`, không giữ trạng thái ngoài @ref GridScratch (bộ đệm * Hàm thuần trên `robot_costmap_2d::Costmap2D`, không giữ trạng thái ngoài @ref GridScratch (bộ đệm
* tái dùng để không cấp phát trong control loop). Không log, không TF, không quyết định gì — người * tái dùng để không cấp phát trong control loop). Không log, không TF, không quyết định gì — người
@@ -156,7 +156,7 @@ struct CostToGoParams
/** /**
* @struct CostToGoResult * @struct CostToGoResult
* @brief Kết quả @ref costToGo — thước đo tiến độ địa trắc (v1 trong ENV_MONITOR_PLAN.md §4.4). * @brief Kết quả @ref costToGo — thước đo tiến độ địa trắc (v1 trong Test/docs/move_base2/ENV_MONITOR_PLAN.md §4.4).
*/ */
struct CostToGoResult struct CostToGoResult
{ {

View File

@@ -28,6 +28,7 @@ enum class PlannerFeedback
{ {
kIdle, ///< Chưa có tin gì mới kể từ cycle trước. kIdle, ///< Chưa có tin gì mới kể từ cycle trước.
kBusy, ///< Đang lập plan, chưa có kết quả. kBusy, ///< Đang lập plan, chưa có kết quả.
kWaitingForCostmap, ///< Goal retained while the global costmap becomes current.
kPlanReady, ///< Có plan mới, không rỗng, sẵn sàng đẩy xuống controller. kPlanReady, ///< Có plan mới, không rỗng, sẵn sàng đẩy xuống controller.
kFailed ///< Lần lập plan gần nhất thất bại. kFailed ///< Lần lập plan gần nhất thất bại.
}; };
@@ -190,6 +191,7 @@ struct StateMachineInput
bool emergency = false; bool emergency = false;
PlannerFeedback planner = PlannerFeedback::kIdle; PlannerFeedback planner = PlannerFeedback::kIdle;
bool planner_costmap_wait_finished = false;
ControllerFeedback controller = ControllerFeedback::kIdle; ControllerFeedback controller = ControllerFeedback::kIdle;
RecoveryFeedback recovery = RecoveryFeedback::kIdle; RecoveryFeedback recovery = RecoveryFeedback::kIdle;
ActionFeedback action = ActionFeedback::kIdle; ActionFeedback action = ActionFeedback::kIdle;

View File

@@ -2,7 +2,7 @@
* *
* Software License Agreement (BSD License) * Software License Agreement (BSD License)
* *
* move_base2 — ghi feature + verdict của EnvMonitor ra JSONL (Test/ENV_MONITOR_PLAN.md §2.6). * move_base2 — ghi feature + verdict của EnvMonitor ra JSONL (Test/docs/move_base2/ENV_MONITOR_PLAN.md §2.6).
* *
* Mục đích: replay offline để chỉnh ngưỡng không cần sim, và là dữ liệu huấn luyện ML sau này. Mỗi * Mục đích: replay offline để chỉnh ngưỡng không cần sim, và là dữ liệu huấn luyện ML sau này. Mỗi
* dòng là một tick nặng (5 Hz) hoặc một sườn sự kiện. Tắt mặc định; khi tắt không cấp phát, không mở * dòng là một tick nặng (5 Hz) hoặc một sườn sự kiện. Tắt mặc định; khi tắt không cấp phát, không mở

View File

@@ -112,6 +112,9 @@ struct SensorGatewayStats
* *
* ## Khác biệt có chủ đích so với `move_base` cũ * ## Khác biệt có chủ đích so với `move_base` cũ
* *
* - **`DEPTH_CAMERA_LAYER` chỉ nhận `PointCloud2`** (không nhận `LaserScan`, `PointCloud`,
* `DepthCameraData`), song song với `VOXEL_LAYER`: `DepthCameraObstacleLayer` có loại riêng và
* chỉ dùng cloud đã lọc của camera.
* - **Lọc layer chỉ theo `getType()`.** Bản cũ dùng `getType() == type || getName() == name`. Vế * - **Lọc layer chỉ theo `getType()`.** Bản cũ dùng `getType() == type || getName() == name`. Vế
* tên là code chết trong thực tế (tên layer là `obstacles`/`inflation`, tên sensor là * tên là code chết trong thực tế (tên layer là `obstacles`/`inflation`, tên sensor là
* `/b_scan`/`/map` — hai tập không giao nhau) nhưng lại là một cái bẫy: đặt tên một layer trùng * `/b_scan`/`/map` — hai tập không giao nhau) nhưng lại là một cái bẫy: đặt tên một layer trùng

View File

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

View File

@@ -4,7 +4,7 @@
* *
* move_base2 — cổng môi trường cho EnvMonitor: "quanh robot lúc này trông thế nào". * move_base2 — cổng môi trường cho EnvMonitor: "quanh robot lúc này trông thế nào".
* *
* Kế thừa vai trò của `PathCheckPort` (Test/ENV_MONITOR_PLAN.md §2.5): lõi hỏi, hạ tầng trả lời. * Kế thừa vai trò của `PathCheckPort` (Test/docs/move_base2/ENV_MONITOR_PLAN.md §2.5): lõi hỏi, hạ tầng trả lời.
* Cổng lo costmap + TF; toán nằm ở `core/grid_analysis`; quyết định nằm ở `core/env_monitor`. Nhờ vậy * Cổng lo costmap + TF; toán nằm ở `core/grid_analysis`; quyết định nằm ở `core/env_monitor`. Nhờ vậy
* `ControlLoop` kiểm được bằng cổng giả (mặc định = "không kết luận được"). * `ControlLoop` kiểm được bằng cổng giả (mặc định = "không kết luận được").
* *

View File

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

View File

@@ -11,6 +11,7 @@
#define MOVE_BASE2_RUNNERS_PLANNER_RUNNER_H_ #define MOVE_BASE2_RUNNERS_PLANNER_RUNNER_H_
#include <condition_variable> #include <condition_variable>
#include <chrono>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <functional> #include <functional>
@@ -31,12 +32,22 @@
namespace robot_costmap_2d namespace robot_costmap_2d
{ {
class Costmap2D;
class Costmap2DROBOT; class Costmap2DROBOT;
} }
namespace move_base2 namespace move_base2
{ {
/// Decision for a continuous readiness wait. A zero timeout preserves legacy planning behavior.
enum class CostmapReadyDecision { kPlan, kWait, kTimeout };
inline CostmapReadyDecision costmapReadyDecision(bool ready, double elapsed, double timeout)
{
if (timeout == 0.0 || ready)
return CostmapReadyDecision::kPlan;
return elapsed >= timeout ? CostmapReadyDecision::kTimeout : CostmapReadyDecision::kWait;
}
/** /**
* @class PlannerRunner * @class PlannerRunner
* @brief Nạp và chạy global planner thế hệ 1 (`robot_nav_core::BaseGlobalPlanner`) qua Boost.DLL, * @brief Nạp và chạy global planner thế hệ 1 (`robot_nav_core::BaseGlobalPlanner`) qua Boost.DLL,
@@ -76,6 +87,24 @@ namespace move_base2
* giữ **cả hai**. Cache cũng **không bao giờ xoá** entry — nhờ đó con trỏ planner mà thread đang * giữ **cả hai**. Cache cũng **không bao giờ xoá** entry — nhờ đó con trỏ planner mà thread đang
* dùng vẫn hợp lệ kể cả khi @ref swapPlanner đổi sang planner khác giữa chừng. * dùng vẫn hợp lệ kể cả khi @ref swapPlanner đổi sang planner khác giữa chừng.
* *
* ## Khoá dài hay bản chụp costmap
*
* `LayeredCostmap::updateMap` ghi lưới global dưới `Costmap2D::getMutex()`, và `resizeMap` realloc
* cả mảng dưới đúng mutex đó. Thread lập plan vì thế có hai cách đọc lưới an toàn:
*
* - **Khoá dài** (gen-1, mặc định khi `global_costmap.snapshot_for_readers: false`): giữ mutex
* suốt `makePlan`. Map-update thread đứng chờ hết lượt search — với SBPL cạn search trên map lớn
* là 6-14 s mỗi lượt, đo 2026-09-17.
* - **Bản chụp** (`snapshot_for_readers: true` VÀ plugin export capability
* `"<alias>ExternalGrid"`): `refreshSnapshot()` giữ mutex đúng bằng một memcpy, rồi planner đọc
* bản copy suốt lượt. Capability tra qua alias Boost.DLL thứ hai trong CÙNG `.so` — cùng cơ chế
* `sbpl_recovery` dùng cho lưới gộp. Plugin không export thì rơi về khoá dài, không đổi hành vi.
*
* Bản chụp global là **single-consumer**: chỉ thread lập plan gọi `refreshSnapshot()` /
* `getCostmapForRead()` trên global costmap. Exporter và recovery đọc lưới sống dưới khoá ngắn,
* EnvMonitor gắn local costmap. Thêm reader global trên control thread qua `getCostmapForRead()`
* là mở race với thread này.
*
* @note Các hàm public gọi từ control thread. Thread nội bộ chỉ chạm dữ liệu dưới mutex. * @note Các hàm public gọi từ control thread. Thread nội bộ chỉ chạm dữ liệu dưới mutex.
* @warning Destructor **chờ** lượt đang chạy kết thúc: plugin là hộp đen, không có đường cắt ngang. * @warning Destructor **chờ** lượt đang chạy kết thúc: plugin là hộp đen, không có đường cắt ngang.
*/ */
@@ -134,20 +163,32 @@ public:
/** /**
* @brief Tắt việc khoá costmap mutex quanh makePlan — CHỈ dành cho unit test. * @brief Tắt việc khoá costmap mutex quanh makePlan — CHỈ dành cho unit test.
* *
* Mặc định BẬT: thread lập plan giữ `Costmap2D::getMutex()` suốt makePlan, cùng giao thức với * Mặc định BẬT: thread lập plan giữ `Costmap2D::getMutex()` suốt makePlan (hoặc chụp bản copy khi
* map-update thread (gen-1 làm y hệt). Unit test truyền costmap placeholder không dereference * `snapshot_for_readers` bật — xem doc lớp), cùng giao thức với map-update thread. Unit test
* được thì phải tắt trước khi startPlan, nếu không sẽ crash ngay lần lấy mutex. * truyền costmap placeholder không dereference được thì phải tắt trước khi startPlan, nếu không sẽ
* crash ngay lần lấy mutex / lần hỏi isSnapshotEnabled(). Tắt = không khoá, không chụp, không gọi
* capability ExternalGrid.
*/ */
void disableCostmapLockForTesting() void disableCostmapLockForTesting()
{ {
costmap_lock_enabled_ = false; costmap_lock_enabled_ = false;
} }
/**
* @brief Planner đang active có export capability `"<alias>ExternalGrid"` không.
*
* Chỉ nói lên plugin CÓ THỂ nhận bản chụp; có dùng hay không còn tuỳ `snapshot_for_readers` của
* global costmap. Dành cho test và dòng tóm tắt lúc boot. Gọi từ control thread.
*/
bool activePlannerSupportsExternalGrid() const;
bool startPlan(const robot_geometry_msgs::PoseStamped& start, bool startPlan(const robot_geometry_msgs::PoseStamped& start,
const robot_geometry_msgs::PoseStamped& goal, const robot_geometry_msgs::PoseStamped& goal,
const robot_protocol_msgs::Order* order, std::uint64_t tag) override; const robot_protocol_msgs::Order* order, std::uint64_t tag) override;
bool isPlanning() const override; bool isPlanning() const override;
void setCostmapReadyTimeout(double seconds) override;
bool costmapWaitState(bool& finished) override;
bool pollPlan(PlanResult& result) override; bool pollPlan(PlanResult& result) override;
@@ -162,12 +203,25 @@ public:
} }
private: private:
/// @brief Chữ ký capability `"<alias>ExternalGrid"`: đưa planner một lưới ngoài để đọc thay lưới
/// sống (`nullptr` = quay về lưới sống). Cùng chữ ký với `sbpl_lattice_planner::setExternalGridOn`.
using ExternalGridSetter =
std::function<void(robot_nav_core::BaseGlobalPlanner*, const robot_costmap_2d::Costmap2D*)>;
/// @brief Một plugin đã nạp: factory phải sống cùng instance, xem doc của lớp. /// @brief Một plugin đã nạp: factory phải sống cùng instance, xem doc của lớp.
struct Loaded struct Loaded
{ {
std::function<robot_nav_core::BaseGlobalPlanner::Ptr()> factory; std::function<robot_nav_core::BaseGlobalPlanner::Ptr()> factory;
robot_nav_core::BaseGlobalPlanner::Ptr instance; robot_nav_core::BaseGlobalPlanner::Ptr instance;
/**
* Capability tuỳ chọn, rỗng = plugin không export. Tra một lần lúc nạp, theo CÙNG `.so` với
* factory nên áp được cho mọi instance của entry này (kể cả instance dựng lại khi đổi marker):
* `dynamic_cast` xuống lớp cụ thể chạy bên trong `.so`. `std::function` giữ tham chiếu `.so`,
* cùng cơ chế giữ-sống với factory.
*/
ExternalGridSetter set_external_grid;
/** /**
* Instance đã bị thay khi marker đổi, giữ lại chứ KHÔNG huỷ. * Instance đã bị thay khi marker đổi, giữ lại chứ KHÔNG huỷ.
* *
@@ -226,8 +280,23 @@ private:
bool running_ = false; ///< Thread đang chạy plugin. bool running_ = false; ///< Thread đang chạy plugin.
bool discard_ = false; ///< Lượt đang chạy đã bị huỷ — vứt kết quả khi nó về. bool discard_ = false; ///< Lượt đang chạy đã bị huỷ — vứt kết quả khi nó về.
bool has_result_ = false; bool has_result_ = false;
double costmap_ready_timeout_ = 10.0; ///< [s], protected by mutex_.
bool waiting_for_costmap_ = false;
bool costmap_wait_finished_ = false;
// Written only by the planner thread; throttle a persistent outage across failed attempts.
bool costmap_wait_problem_active_ = false;
std::chrono::steady_clock::time_point last_costmap_wait_log_;
std::chrono::steady_clock::time_point last_costmap_timeout_log_;
std::string costmap_stale_names_;
bool costmap_stale_names_reserved_ = false;
robot_nav_core::BaseGlobalPlanner* active_ = nullptr; ///< Non-owning, trỏ vào @ref planners_. robot_nav_core::BaseGlobalPlanner* active_ = nullptr; ///< Non-owning, trỏ vào @ref planners_.
/**
* Capability ExternalGrid của planner active (non-owning, trỏ vào @ref planners_; null = plugin
* không export). Đi cặp với `active_`: đổi cùng lúc dưới `mutex_`, thread chụp cả hai trước khi
* nhả mutex. Hợp lệ mãi vì cache không xoá entry và `std::map` không dời node.
*/
const ExternalGridSetter* active_external_grid_ = nullptr;
/** /**
* Instance mà thread lập plan ĐANG ở trong `makePlan` (non-owning, chỉ khác null khi `running_`). * Instance mà thread lập plan ĐANG ở trong `makePlan` (non-owning, chỉ khác null khi `running_`).
* *

View File

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

View File

@@ -146,6 +146,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
readDouble(nh, "controller_frequency", config.controller_frequency); readDouble(nh, "controller_frequency", config.controller_frequency);
readDouble(nh, "planner_frequency", config.planner_frequency); readDouble(nh, "planner_frequency", config.planner_frequency);
readDouble(nh, "planner_timeout", config.planner_timeout); readDouble(nh, "planner_timeout", config.planner_timeout);
readDouble(nh, "costmap_ready_timeout", config.costmap_ready_timeout);
readDouble(nh, "runtime_stats_period", config.runtime_stats_period); readDouble(nh, "runtime_stats_period", config.runtime_stats_period);
readDouble(nh, "watchdog_period", config.watchdog.period); readDouble(nh, "watchdog_period", config.watchdog.period);
readDouble(nh, "local_planner_call_budget", config.watchdog.local_planner_call_budget); readDouble(nh, "local_planner_call_budget", config.watchdog.local_planner_call_budget);
@@ -435,6 +436,11 @@ bool MoveBase2Config::validate(std::string& error) const
error = "planner_timeout is not finite [s]"; error = "planner_timeout is not finite [s]";
return false; return false;
} }
if (!std::isfinite(costmap_ready_timeout) || costmap_ready_timeout < 0.0)
{
error = "costmap_ready_timeout must be finite and >= 0 [s] (0 = legacy behavior)";
return false;
}
if (!watchdog.validate(error)) if (!watchdog.validate(error))
{ {
return false; return false;
@@ -536,6 +542,8 @@ std::string MoveBase2Config::describe() const
out << " controller_frequency: " << controller_frequency << " Hz\n"; out << " controller_frequency: " << controller_frequency << " Hz\n";
out << " planner_frequency: " << planner_frequency << " Hz\n"; out << " planner_frequency: " << planner_frequency << " Hz\n";
out << " planner_timeout: " << planner_timeout << " s\n"; out << " planner_timeout: " << planner_timeout << " s\n";
out << " costmap_ready_timeout: " << costmap_ready_timeout << " s"
<< (costmap_ready_timeout == 0.0 ? " (readiness check off)\n" : "\n");
out << " runtime_stats_period: " << runtime_stats_period << " s" out << " runtime_stats_period: " << runtime_stats_period << " s"
<< (runtime_stats_period > 0.0 ? "\n" : " (off)\n"); << (runtime_stats_period > 0.0 ? "\n" : " (off)\n");
out << watchdog.describe(); out << watchdog.describe();
@@ -582,6 +590,7 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
readDouble(nh, "controller_frequency", controller_frequency); readDouble(nh, "controller_frequency", controller_frequency);
readDouble(nh, "planner_frequency", planner_frequency); readDouble(nh, "planner_frequency", planner_frequency);
readDouble(nh, "costmap_ready_timeout", costmap_ready_timeout);
// Khoá này không có trong schema gen-1 — nó là công cụ chẩn đoán của move_base2. Vẫn đọc ở đây // 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. // để 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); readDouble(nh, "runtime_stats_period", runtime_stats_period);
@@ -731,6 +740,7 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
config.debug_plan = debug_plan; config.debug_plan = debug_plan;
config.debug_skip = debug_skip; config.debug_skip = debug_skip;
config.state_machine = state_machine; config.state_machine = state_machine;
config.costmap_ready_timeout = costmap_ready_timeout;
config.velocity = velocity; config.velocity = velocity;
config.nominal_control_period = config.nominal_control_period =
controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s] controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s]

View File

@@ -48,6 +48,8 @@ const char* toString(PlannerFeedback feedback)
return "idle"; return "idle";
case PlannerFeedback::kBusy: case PlannerFeedback::kBusy:
return "busy"; return "busy";
case PlannerFeedback::kWaitingForCostmap:
return "waiting_for_costmap";
case PlannerFeedback::kPlanReady: case PlannerFeedback::kPlanReady:
return "plan_ready"; return "plan_ready";
case PlannerFeedback::kFailed: case PlannerFeedback::kFailed:
@@ -96,6 +98,11 @@ const char* toString(RecoveryFeedback feedback)
bool ControlLoopConfig::validate(std::string& error) const bool ControlLoopConfig::validate(std::string& error) const
{ {
if (!std::isfinite(costmap_ready_timeout) || costmap_ready_timeout < 0.0)
{
error = "costmap_ready_timeout must be finite and >= 0 [s]";
return false;
}
if (!state_machine.validate(error)) if (!state_machine.validate(error))
{ {
return false; return false;
@@ -239,9 +246,10 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
config_ = config; config_ = config;
deps_ = deps; deps_ = deps;
deps_.planner->setCostmapReadyTimeout(config_.costmap_ready_timeout);
// EnvMonitor (Test/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 (PathMonitor cũ đã // EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 (PathMonitor cũ đã
// xoá). Không có cổng thì tắt, nhưng phải kêu nếu config bảo bật. // xoá). Không có cổng thì tắt, nhưng phải kêu nếu config bảo bật.
env_logger_.reset(); env_logger_.reset();
if (config_.env_monitor.enabled) if (config_.env_monitor.enabled)
@@ -655,10 +663,27 @@ void ControlLoop::collectPlannerResult()
// Fallback thuộc policy của control loop, không phải recovery: planner chính đã kết thúc nên // Fallback thuộc policy của control loop, không phải recovery: planner chính đã kết thúc nên
// worker rảnh để nạp/chạy SBPL ngay cycle này. Chỉ thử một lần cho cả request; backup fail thì // worker rảnh để nạp/chạy SBPL ngay cycle này. Chỉ thử một lần cho cả request; backup fail thì
// giữ kFailed để state machine đi đúng đường recovery hiện có. // giữ kFailed để state machine đi đúng đường recovery hiện có.
//
// Backup CHỈ dành cho profile position: goal trần không có edge làm CustomPlanner fail, và SBPL
// là đường lùi hợp lệ cho một chặng đi tới pose. Docking/go_straight/rotate thì SBPL không giữ
// được hình học của chặng — đo 26/10 trên robot KIT: DockPlanner fail vì robot đứng quá gần
// dock, SBPL dựng đường thẳng tới pose tiếp xúc, robot bám đường đó vào dock không qua cusp và
// đoạn lùi thẳng. Ba profile đó fail thì đi thẳng route planning_failed như khi không có backup.
if (!backup_global_planner_active_ && !config_.backup_global_planner_name.empty()) if (!backup_global_planner_active_ && !config_.backup_global_planner_name.empty())
{ {
const std::string failed_planner = deps_.planner->activePlanner(); const std::string failed_planner = deps_.planner->activePlanner();
if (deps_.planner->swapPlanner(config_.backup_global_planner_name)) if (active_request_.profile != MotionProfile::kPosition)
{
// Không gắn [debug], không tắt được: đây là bằng chứng duy nhất trong log rằng lỗi planner
// của chặng này cố ý không được cứu bằng backup.
robot::log_warning("[move_base2] global planner '%s' failed for mission %llu (profile %s); "
"backup '%s' is reserved for profile position; starting recovery.\n",
failed_planner.c_str(),
static_cast<unsigned long long>(active_request_.mission_sequence_id),
toString(active_request_.profile),
config_.backup_global_planner_name.c_str());
}
else if (deps_.planner->swapPlanner(config_.backup_global_planner_name))
{ {
backup_global_planner_active_ = true; backup_global_planner_active_ = true;
planner_feedback_ = PlannerFeedback::kIdle; planner_feedback_ = PlannerFeedback::kIdle;
@@ -669,11 +694,13 @@ void ControlLoop::collectPlannerResult()
config_.backup_global_planner_name.c_str()); config_.backup_global_planner_name.c_str());
return; return;
} }
else
// Không có backup chạy được thì failure gốc vẫn phải đi recovery, không được để robot chờ. {
robot::log_error("[move_base2] global planner '%s' failed and backup '%s' could not be " // Không có backup chạy được thì failure gốc vẫn phải đi recovery, không được để robot chờ.
"loaded; starting recovery.\n", robot::log_error("[move_base2] global planner '%s' failed and backup '%s' could not be "
failed_planner.c_str(), config_.backup_global_planner_name.c_str()); "loaded; starting recovery.\n",
failed_planner.c_str(), config_.backup_global_planner_name.c_str());
}
} }
planner_feedback_ = PlannerFeedback::kFailed; planner_feedback_ = PlannerFeedback::kFailed;
return; return;
@@ -1016,6 +1043,9 @@ bool ControlLoop::step()
input.cancel_requested = cancel_requested_; input.cancel_requested = cancel_requested_;
input.emergency = emergency_; input.emergency = emergency_;
input.planner = planner_feedback_; input.planner = planner_feedback_;
const bool planner_waiting = deps_.planner->costmapWaitState(input.planner_costmap_wait_finished);
if (planner_running_ && planner_waiting && planner_feedback_ == PlannerFeedback::kBusy)
input.planner = PlannerFeedback::kWaitingForCostmap;
input.controller = controller_feedback_; input.controller = controller_feedback_;
input.recovery = recovery_feedback_; input.recovery = recovery_feedback_;
input.action = action_feedback_; input.action = action_feedback_;
@@ -1045,7 +1075,7 @@ bool ControlLoop::step()
} }
} }
input.travelled_since_oscillation_reset = travelled; 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 // Bốn cổng của state machine do EnvMonitor cấp (Test/docs/move_base2/ENV_MONITOR_PLAN.md): cờ chỉ khác false khi
// verdict tương ứng có `action: recover`. `off_path` không còn nguồn nào (phép đo cũ đã bỏ 6/9/2026). // verdict tương ứng có `action: recover`. `off_path` không còn nguồn nào (phép đo cũ đã bỏ 6/9/2026).
input.path_blocked = env_verdict_.path_blocked; input.path_blocked = env_verdict_.path_blocked;
input.collision = env_verdict_.collision; input.collision = env_verdict_.collision;

View File

@@ -44,6 +44,8 @@ const char* toString(robot_costmap_2d::LayerType type)
return "PreferredLayer"; return "PreferredLayer";
case robot_costmap_2d::LayerType::UNPREFERRED_LAYER: case robot_costmap_2d::LayerType::UNPREFERRED_LAYER:
return "UnpreferredLayer"; return "UnpreferredLayer";
case robot_costmap_2d::LayerType::DEPTH_CAMERA_LAYER:
return "DepthCameraObstacleLayer";
case robot_costmap_2d::LayerType::UNKNOWN: case robot_costmap_2d::LayerType::UNKNOWN:
break; break;
} }
@@ -274,6 +276,12 @@ void SensorGateway::pushStaticMap(const std::string& name, const robot_nav_msgs:
} }
ScopedSection timer(telemetry_, section_static_map_); ScopedSection timer(telemetry_, section_static_map_);
// DirectionalLayer TRƯỚC StaticLayer, có chủ đích. Layer tự lọc theo topic: map_topic chỉ đưa nó về
// PENDING (không cần geometry), direction_topic là grid hướng (StaticLayer bỏ qua, nên trong cùng
// lần gọi không có resize nào). Nếu StaticLayer nhận map trước, giữa hai lần dispatch updateMap có
// thể ghi xong map mới và StaticLayer báo current trong khi field hướng cũ vẫn READY — planner kiểm
// readiness đúng lúc đó sẽ plan theo map mới với zone cũ. Chỉ global costmap có layer này.
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::DIRECTIONAL_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::STATIC_LAYER, name, stats_); dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::STATIC_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::PREFERRED_LAYER, name, stats_); dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::PREFERRED_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::UNPREFERRED_LAYER, name, stats_); dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::UNPREFERRED_LAYER, name, stats_);
@@ -331,6 +339,9 @@ void SensorGateway::pushPointCloud2(const std::string& name,
ScopedSection timer(telemetry_, section_cloud_); ScopedSection timer(telemetry_, section_cloud_);
dispatchTo(local_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_); dispatchTo(local_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
dispatchTo(global_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_); dispatchTo(global_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
// DepthCameraObstacleLayer has its own type and marks from the camera's PointCloud2.
dispatchTo(local_costmap_, cloud, robot_costmap_2d::LayerType::DEPTH_CAMERA_LAYER, name, stats_);
dispatchTo(global_costmap_, cloud, robot_costmap_2d::LayerType::DEPTH_CAMERA_LAYER, name, stats_);
} }
void SensorGateway::pushDepthCameraData(const std::string& topic, void SensorGateway::pushDepthCameraData(const std::string& topic,

View File

@@ -529,6 +529,19 @@ bool NavigationRuntime::buildRunners(std::string& error)
} }
robot::log_info("[move_base2] NavigationRuntime built:\n%s", config_.describe().c_str()); robot::log_info("[move_base2] NavigationRuntime built:\n%s", config_.describe().c_str());
// Global planner đọc lưới kiểu gì — in một lần ở boot vì đây là thứ quyết định map-update thread
// có bị chặn 6-14 s mỗi lượt SBPL hay không. Hai điều kiện phải cùng đúng mới ra "snapshot":
// khoá YAML global_costmap.snapshot_for_readers và capability ExternalGrid của plugin active.
{
const bool snapshot_on = global_costmap_->isSnapshotEnabled();
const bool planner_can = planner_.activePlannerSupportsExternalGrid();
robot::log_info("[move_base2] global planner '%s' reads the costmap via %s "
"(global_costmap.snapshot_for_readers=%s, plugin ExternalGrid=%s).\n",
planner_.activePlanner().c_str(),
(snapshot_on && planner_can) ? "SNAPSHOT (mutex held only for the copy)"
: "LONG LOCK (map-update waits for makePlan)",
snapshot_on ? "true" : "false", planner_can ? "yes" : "no");
}
built_ = true; built_ = true;
return true; return true;

View File

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

View File

@@ -8,7 +8,9 @@
*********************************************************************/ *********************************************************************/
#include <move_base2/runners/planner_runner.h> #include <move_base2/runners/planner_runner.h>
#include <algorithm>
#include <cmath> #include <cmath>
#include <chrono>
#include <exception> #include <exception>
#include <utility> #include <utility>
@@ -19,12 +21,51 @@
#include <robot/plugin_loader_helper.h> #include <robot/plugin_loader_helper.h>
#include <robot/robot.h> #include <robot/robot.h>
#include <robot_costmap_2d/costmap_2d_robot.h> #include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_costmap_2d/direction_field.h>
#include <robot_costmap_2d/layer.h>
#include <robot_costmap_2d/layered_costmap.h>
namespace move_base2 namespace move_base2
{ {
namespace namespace
{ {
// Called with the master mutex held. Direction providers own a separate mutex, so their
// snapshot is the race-free equivalent of Layer::isCurrent() for those layers.
bool costmapReady(robot_costmap_2d::LayeredCostmap& costmap, std::string* stale_names)
{
const auto& layers = *costmap.getPlugins();
std::size_t providers = 0;
for (const auto& layer : layers)
if (layer && layer->isEnabled() &&
dynamic_cast<const robot_costmap_2d::DirectionFieldProvider*>(layer.get()))
++providers;
bool ready = true;
if (stale_names)
stale_names->clear();
for (const auto& layer : layers)
{
if (!layer || !layer->isEnabled())
continue;
const auto* provider = dynamic_cast<const robot_costmap_2d::DirectionFieldProvider*>(layer.get());
const bool current = provider
? providers == 1 && provider->directionSnapshot().state != robot_costmap_2d::DirectionFieldState::kPending
: layer->getType() != robot_costmap_2d::LayerType::DIRECTIONAL_LAYER && layer->isCurrent();
if (!current)
{
ready = false;
if (stale_names)
{
if (!stale_names->empty())
stale_names->append(", ");
stale_names->append(layer->getName());
}
}
}
return ready;
}
/// @brief Pose có dùng được để lập plan không — NaN/Inf lọt vào SBPL là hỏng ở tầng khó truy nhất. /// @brief Pose có dùng được để lập plan không — NaN/Inf lọt vào SBPL là hỏng ở tầng khó truy nhất.
bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose) bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose)
{ {
@@ -43,14 +84,22 @@ bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose)
/// hai công thức khác nhau, trùng tên là mời gọi đặt nhầm giá trị. /// hai công thức khác nhau, trùng tên là mời gọi đặt nhầm giá trị.
/// ///
/// `dock_anchor` khai goal pose của marker nằm ở tâm footprint dock (`center`) hay ngay trên mặt /// `dock_anchor` khai goal pose của marker nằm ở tâm footprint dock (`center`) hay ngay trên mặt
/// tiếp cận (`face`). `face` thì DockPlanner bỏ qua `footprint_dock` hoàn toàn. /// tiếp cận (`face`). `mating_edge` dùng goal đã offset tới pose base_link lúc dock xong;
/// `face` và `mating_edge` khiến DockPlanner bỏ qua `footprint_dock` hoàn toàn.
/// `dock_face_offset` và `dock_pivot_safety_margin` là override DockPlanner chỉ có tác dụng với
/// `dock_anchor: mating_edge`; khai với `center` hoặc `face` khiến DockPlanner từ chối khởi tạo.
/// Nếu marker sau không khai, giá trị cũ được đặt YAML null để plugin trở về mặc định.
/// ///
/// KHÔNG có `terminal_direction` ở đây, và cố ý như vậy: chiều chạy của đoạn thẳng cuối được SUY RA /// KHÔNG có `terminal_direction` ở đây, và cố ý như vậy: chiều chạy của đoạn thẳng cuối được SUY RA
/// từ phía robot đứng so với goal (`dock_calc.cpp`), vì tầng trên đã offset goal sao cho base_link /// từ phía robot đứng so với goal (`dock_calc.cpp`), vì tầng trên đã offset goal sao cho base_link
/// dừng đúng tại đó khi manơ hoàn tất. Một khoá cho phép marker ép chiều khác sẽ mâu thuẫn với /// dừng đúng tại đó khi manơ hoàn tất. Một khoá cho phép marker ép chiều khác sẽ mâu thuẫn với
/// chính vị trí goal, nên khoá đó đã được gỡ thay vì hiện thực. /// chính vị trí goal, nên khoá đó đã được gỡ thay vì hiện thực.
constexpr const char* kMarkerPlannerParams[] = { constexpr const char* kMarkerPlannerParams[] = {
"footprint_dock", "dock_anchor" "footprint_dock", "dock_anchor", "dock_face_offset", "dock_pivot_safety_margin"
};
constexpr const char* kOptionalMarkerPlannerParams[] = {
"dock_face_offset", "dock_pivot_safety_margin"
}; };
/** /**
@@ -229,6 +278,28 @@ robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& nam
return nullptr; return nullptr;
} }
// Capability lưới ngoài, TUỲ CHỌN: alias thứ hai "<alias>ExternalGrid" trong cùng .so (cùng mẫu
// với sbpl_recovery cho lưới gộp). Thiếu là bình thường — CustomPlanner, DockPlanner,
// TwoPointsPlanner không có — và không phải lỗi: planner đó chỉ không nhận được bản chụp, thread
// lập plan giữ khoá dài như gen-1. Mấy planner đó chạy vài ms nên khoá dài với chúng vô hại;
// capability này sinh ra cho SBPL, thứ cạn search 6-14 s trên map lớn.
try
{
loaded.set_external_grid =
boost::dll::import_alias<void(robot_nav_core::BaseGlobalPlanner*,
const robot_costmap_2d::Costmap2D*)>(
library_path, name + "ExternalGrid", boost::dll::load_mode::append_decorations);
robot::log_info("[move_base2] PlannerRunner: '%s' exports ExternalGrid — planner will read a "
"costmap snapshot when global_costmap.snapshot_for_readers is on.\n",
name.c_str());
}
catch (const std::exception&)
{
// Không log ở mức warning: đây là đường bình thường của đa số plugin. Dòng tóm tắt lúc boot
// (navigation_runtime) nói rõ planner active đang khoá dài hay chụp.
loaded.set_external_grid = nullptr;
}
try try
{ {
loaded.instance = loaded.factory(); loaded.instance = loaded.factory();
@@ -290,36 +361,54 @@ bool PlannerRunner::bindDockingMarker(const std::string& marker, const std::stri
} }
const std::string profile_ns = "docking_marker_profiles/" + marker; const std::string profile_ns = "docking_marker_profiles/" + marker;
if (!nh_.hasParam(profile_ns)) const bool has_profile = nh_.hasParam(profile_ns);
{
// Marker hợp lệ nhưng không có profile riêng: cặp planner mặc định, không có gì để chép. Không
// phải lỗi — `maker_sources` mới là allow-list, bảng profile chỉ là override.
return true;
}
// Namespace phải được kiểm TRƯỚC khi dựng NodeHandle: `robot::NodeHandle` không báo lỗi khi // Namespace phải được kiểm TRƯỚC khi dựng NodeHandle: `robot::NodeHandle` không báo lỗi khi
// namespace không resolve được mà lặng lẽ rơi về namespace cha. Bỏ qua bước này thì marker gõ sai // namespace không resolve được mà lặng lẽ rơi về namespace cha. Bỏ qua bước này thì marker gõ sai
// sẽ đọc `footprint` ở ROOT — tức footprint ROBOT — rồi dùng nó làm kích thước trạm dock. // sẽ đọc `footprint` ở ROOT — tức footprint ROBOT — rồi dùng nó làm kích thước trạm dock.
robot::NodeHandle marker_nh(nh_, profile_ns); robot::NodeHandle marker_nh(nh_, profile_ns);
robot::NodeHandle planner_nh(nh_, planner_name); robot::NodeHandle planner_nh(nh_, planner_name);
if (marker_nh.getNamespace() == nh_.getNamespace() || const bool marker_namespace_invalid =
planner_nh.getNamespace() == nh_.getNamespace()) has_profile && marker_nh.getNamespace() == nh_.getNamespace();
const bool planner_namespace_invalid =
planner_nh.getNamespace() == nh_.getNamespace();
if (marker_namespace_invalid || (has_profile && planner_namespace_invalid))
{ {
robot::log_error("[move_base2] PlannerRunner: namespace '%s' or '%s' does not resolve in the " robot::log_error("[move_base2] PlannerRunner: namespace '%s' or '%s' does not resolve in the "
"param tree; refusing to bind marker '%s'.\n", "param tree; refusing to bind marker '%s'.\n",
profile_ns.c_str(), planner_name.c_str(), marker.c_str()); profile_ns.c_str(), planner_name.c_str(), marker.c_str());
return false; return false;
} }
if (!has_profile && planner_namespace_invalid)
{
// Marker hợp lệ nhưng không có profile riêng: giữ nguyên hành vi cũ nếu planner namespace
// chưa tồn tại; không có nơi an toàn để xoá override per-marker.
return true;
}
bool copied = false; bool copied = false;
for (const char* key : kMarkerPlannerParams) if (has_profile)
{ {
copied = copyParamNode(marker_nh, planner_nh, key) || copied; for (const char* key : kMarkerPlannerParams)
{
copied = copyParamNode(marker_nh, planner_nh, key) || copied;
}
}
for (const char* key : kOptionalMarkerPlannerParams)
{
if ((!has_profile || !marker_nh.hasParam(key)) && planner_nh.hasParam(key))
{
// Không để override rò sang marker trước: DockPlannerConfig đọc YAML null như chưa khai.
// footprint_dock và dock_anchor giữ nguyên cách xử lý cũ.
planner_nh.setParam(key, YAML::Node(YAML::NodeType::Null));
copied = true;
}
} }
if (!copied) if (!copied)
{ {
return true; // Profile có tồn tại nhưng không khai khoá nào của planner — giữ nguyên cấu hình. return true; // Không có khoá planner mới hoặc override tuỳ chọn nào cần xoá.
} }
// Dựng lại instance CHỈ khi marker nối vào planner này thực sự đổi. Dock lại đúng marker cũ thì // Dựng lại instance CHỈ khi marker nối vào planner này thực sự đổi. Dock lại đúng marker cũ thì
@@ -369,6 +458,9 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
// trạng thái "không có planner" ở đây sẽ làm hỏng luôn cả yêu cầu đang chạy dở. // trạng thái "không có planner" ở đây sẽ làm hỏng luôn cả yêu cầu đang chạy dở.
return false; return false;
} }
// acquire() vừa trả instance của entry này, nên entry chắc chắn tồn tại. Con trỏ vào node của
// std::map ổn định suốt đời cache (không xoá entry) — thread chụp nó cùng với active_.
const ExternalGridSetter& external_grid = planners_.at(planner_name).set_external_grid;
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
@@ -379,6 +471,9 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
// Thread chưa nhận: rút yêu cầu ra, kẻo nó chạy yêu cầu của planner cũ trên instance mới rồi // 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. // vứt — tốn một lượt makePlan vô ích.
pending_ = false; pending_ = false;
waiting_for_costmap_ = false;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
request_order_.reset(); request_order_.reset();
} }
else if (running_) else if (running_)
@@ -393,6 +488,8 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
} }
} }
active_ = planner; active_ = planner;
active_external_grid_ = external_grid ? &external_grid : nullptr;
cv_.notify_all();
} }
active_name_ = planner_name; active_name_ = planner_name;
@@ -407,6 +504,12 @@ std::string PlannerRunner::activePlanner() const
return active_ != nullptr ? active_name_ : std::string(); return active_ != nullptr ? active_name_ : std::string();
} }
bool PlannerRunner::activePlannerSupportsExternalGrid() const
{
std::lock_guard<std::mutex> lock(mutex_);
return active_ != nullptr && active_external_grid_ != nullptr;
}
// ================================================================================================ // ================================================================================================
// Vòng đời một lượt lập plan // Vòng đời một lượt lập plan
// ================================================================================================ // ================================================================================================
@@ -452,6 +555,9 @@ bool PlannerRunner::startPlan(const robot_geometry_msgs::PoseStamped& start,
pending_ = true; pending_ = true;
discard_ = false; discard_ = false;
has_result_ = false; has_result_ = false;
waiting_for_costmap_ = costmap_lock_enabled_ && costmap_ready_timeout_ > 0.0;
if (waiting_for_costmap_ && status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kWaitingForCostmap);
cv_.notify_one(); cv_.notify_one();
return true; return true;
@@ -463,6 +569,20 @@ bool PlannerRunner::isPlanning() const
return pending_ || running_; return pending_ || running_;
} }
void PlannerRunner::setCostmapReadyTimeout(double seconds)
{
std::lock_guard<std::mutex> lock(mutex_);
costmap_ready_timeout_ = seconds;
}
bool PlannerRunner::costmapWaitState(bool& finished)
{
std::lock_guard<std::mutex> lock(mutex_);
finished = costmap_wait_finished_;
costmap_wait_finished_ = false;
return waiting_for_costmap_;
}
bool PlannerRunner::pollPlan(PlanResult& result) bool PlannerRunner::pollPlan(PlanResult& result)
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
@@ -509,6 +629,9 @@ void PlannerRunner::cancelPlan()
// sẽ nhận job này NGAY SAU cancel, chạy trọn allocated_time cho một plan không ai cần (bắt được // 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). // bằng test CancelPreemptsAPreemptablePlannerWithinMilliseconds, 2026-09-11).
pending_ = false; pending_ = false;
waiting_for_costmap_ = false;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
request_order_.reset(); request_order_.reset();
} }
else if (pending_ || running_) else if (pending_ || running_)
@@ -530,6 +653,7 @@ void PlannerRunner::cancelPlan()
// Kết quả đã nằm sẵn trong hộp thư cũng bỏ luôn: bên gọi vừa nói nó không còn cần plan này. // 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; has_result_ = false;
handoff_.clear(); handoff_.clear();
cv_.notify_all();
} }
// ================================================================================================ // ================================================================================================
@@ -558,15 +682,17 @@ 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: // 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. // control thread không bao giờ phải chờ một lượt lập plan.
robot_nav_core::BaseGlobalPlanner* planner = active_; robot_nav_core::BaseGlobalPlanner* planner = active_;
running_planner_ = planner; const ExternalGridSetter* external_grid = active_external_grid_;
running_planner_ = nullptr;
const robot_geometry_msgs::PoseStamped start = request_start_; const robot_geometry_msgs::PoseStamped start = request_start_;
const robot_geometry_msgs::PoseStamped goal = request_goal_; const robot_geometry_msgs::PoseStamped goal = request_goal_;
const std::shared_ptr<robot_protocol_msgs::Order> order = request_order_; const std::shared_ptr<robot_protocol_msgs::Order> order = request_order_;
const std::uint64_t tag = request_tag_; const std::uint64_t tag = request_tag_;
const double ready_timeout = costmap_ready_timeout_;
pending_ = false; pending_ = false;
running_ = true; running_ = true;
if (status_board_ != nullptr) if (status_board_ != nullptr && !waiting_for_costmap_)
{ {
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy); status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
} }
@@ -575,25 +701,134 @@ void PlannerRunner::threadBody()
planning_.clear(); planning_.clear();
bool ok = false; bool ok = false;
bool waited = false;
try try
{ {
ScopedSection timer(stats_, section_make_plan_); // Planner phải thấy một lưới ĐÔNG CỨNG suốt makePlan: LayeredCostmap::updateMap ghi lưới, và
// Khoá lưới costmap suốt makePlan — cùng giao thức với gen-1 (move_base.cpp:1921,1959): // resizeMap REALLOC cả mảng, dưới Costmap2D::getMutex(). Hai cách đạt được điều đó:
// LayeredCostmap::updateMap ghi lưới, và resizeMap REALLOC cả mảng, dưới đúng mutex này. //
// Không khoá thì planner đọc cost đang bị ghi dở, hoặc tệ hơn là đọc vào vùng nhớ vừa bị // (a) Bản chụp — global_costmap.snapshot_for_readers bật VÀ plugin export ExternalGrid:
// resize giải phóng khi static map được nhận lại. Lấy getCostmap() mỗi lượt, không cache — // refreshSnapshot() giữ mutex đúng bằng một memcpy (~0.3 ms cho 1397x777, ~5 ms cho
// con trỏ đó có thể bị thay (bài học double-free của workspace). // 3060x3060), rồi planner đọc bản copy, map-update thread chạy tiếp. Cùng khuôn với
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock; // controller_runner cho local costmap (P0b). Bản chụp global là single-consumer: chỉ
if (costmap_lock_enabled_) // thread này gọi refreshSnapshot()/getCostmapForRead() trên nó — xem doc lớp.
// (b) Khoá dài — gen-1 (move_base.cpp:1921,1959): giữ mutex suốt makePlan. Map-update thread
// đứng chờ hết lượt search; với SBPL cạn search trên map lớn là 6-14 s (đo 2026-09-17).
// Đây là đường rơi về khi tắt snapshot hoặc plugin không nhận lưới ngoài.
//
// Kiểm "costmap đã sẵn sàng" (P4, Test/docs/DIRECTION_ZONE_PLAN.md mục 7.3) chạy dưới CÙNG lần
// khoá đó, nên lưới planner đọc chính là lưới vừa được xác nhận current. Chưa current thì nhả
// khoá, chờ có hạn `costmap_ready_timeout` rồi kiểm lại; không gọi makePlan trên map dở dang.
//
// Lấy getCostmap() mỗi lượt, không cache — con trỏ đó có thể bị thay (bài học double-free của
// workspace). Với capability có mà snapshot TẮT, vẫn gọi setter với nullptr: xoá lưới ngoài
// còn sót từ cấu hình trước, để planner đọc lưới sống dưới khoá dài đúng như (b).
using Clock = std::chrono::steady_clock;
Clock::time_point wait_started;
std::string& stale_names = costmap_stale_names_;
while (true)
{ {
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>( boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
*(costmap_->getCostmap()->getMutex())); const bool has_setter = external_grid != nullptr && static_cast<bool>(*external_grid);
const bool use_snapshot = costmap_lock_enabled_ && has_setter && costmap_->isSnapshotEnabled();
if (costmap_lock_enabled_)
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*costmap_->getCostmap()->getMutex());
// updateMap and StaticLayer callbacks use this same master mutex. For a snapshot, the
// recursive mutex remains held across both readiness and refreshSnapshot's copy. For a
// live grid it stays held through makePlan. Direction providers use their own snapshot lock.
if (costmap_lock_enabled_ && ready_timeout > 0.0 && !costmap_stale_names_reserved_)
{
std::size_t capacity = 0;
for (const auto& layer : *costmap_->getLayeredCostmap()->getPlugins())
if (layer) capacity += layer->getName().size() + 2;
stale_names.reserve(capacity);
costmap_stale_names_reserved_ = true;
}
const bool ready = !costmap_lock_enabled_ || ready_timeout == 0.0 ||
costmapReady(*costmap_->getLayeredCostmap(), &stale_names);
const auto now = Clock::now();
if (!ready && !waited)
{
waited = true;
wait_started = now;
if (!costmap_wait_problem_active_)
{
costmap_wait_problem_active_ = true;
last_costmap_wait_log_ = now;
robot::log_warning("[move_base2] PlannerRunner: waiting for global costmap; not current: %s\n",
stale_names.c_str());
}
}
const double elapsed = waited ? std::chrono::duration<double>(now - wait_started).count() : 0.0;
const CostmapReadyDecision decision = costmapReadyDecision(ready, elapsed, ready_timeout);
if (decision == CostmapReadyDecision::kTimeout)
{
if (last_costmap_timeout_log_ == Clock::time_point{} ||
std::chrono::duration<double>(now - last_costmap_timeout_log_).count() >= 5.0)
{
robot::log_error("[move_base2] PlannerRunner: global costmap readiness timed out after %.2f s; not current: %s\n",
elapsed, stale_names.c_str());
last_costmap_timeout_log_ = now;
}
break;
}
if (decision == CostmapReadyDecision::kWait)
{
if (std::chrono::duration<double>(now - last_costmap_wait_log_).count() >= 5.0)
{
robot::log_warning("[move_base2] PlannerRunner: still waiting for global costmap (%.2f s); not current: %s\n",
elapsed, stale_names.c_str());
last_costmap_wait_log_ = now;
}
costmap_lock.unlock();
lock.lock();
const double poll_seconds = std::min(0.05, ready_timeout - elapsed);
cv_.wait_for(lock, std::chrono::duration<double>(poll_seconds),
[this] { return shutdown_ || discard_; });
const bool cancelled = shutdown_ || discard_;
lock.unlock();
if (cancelled)
break;
continue;
}
if (use_snapshot)
{
costmap_->refreshSnapshot();
(*external_grid)(planner, costmap_->getCostmapForRead());
}
else if (costmap_lock_enabled_ && has_setter)
(*external_grid)(planner, nullptr);
lock.lock();
const bool cancelled = shutdown_ || discard_;
waiting_for_costmap_ = false;
costmap_wait_finished_ = costmap_wait_finished_ || waited;
if (!cancelled)
{
running_planner_ = planner;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
}
lock.unlock();
if (cancelled)
break;
if (use_snapshot)
costmap_lock.unlock();
if (costmap_wait_problem_active_)
{
robot::log_info("[move_base2] PlannerRunner: global costmap is ready; planning resumes.\n");
costmap_wait_problem_active_ = false;
last_costmap_timeout_log_ = Clock::time_point{};
}
ScopedSection timer(stats_, section_make_plan_);
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
break;
} }
// Hai overload của interface gốc gộp lại: "có Order hay không" là một nhánh, không phải hai
// contract. Plugin nào không hiểu Order thì overload mặc định của nó tự lo.
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
} }
catch (const std::exception& ex) catch (const std::exception& ex)
{ {
@@ -619,6 +854,9 @@ void PlannerRunner::threadBody()
} }
lock.lock(); lock.lock();
if (waiting_for_costmap_ && waited)
costmap_wait_finished_ = true;
waiting_for_costmap_ = false;
running_ = false; running_ = false;
running_planner_ = nullptr; running_planner_ = nullptr;
if (status_board_ != nullptr) if (status_board_ != nullptr)

View File

@@ -540,6 +540,13 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
break; break;
} }
// Waiting for input is not planning time and must not consume the retry budget.
// The completion event also covers a wait which began and ended between control cycles.
if (in.planner_costmap_wait_finished || in.planner == PlannerFeedback::kWaitingForCostmap)
last_valid_plan_ = in.now;
if (in.planner == PlannerFeedback::kWaitingForCostmap)
break;
if (in.planner == PlannerFeedback::kPlanReady) if (in.planner == PlannerFeedback::kPlanReady)
{ {
out.apply_plan = true; out.apply_plan = true;

View File

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

View File

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

View File

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

View File

@@ -73,6 +73,14 @@ robot_geometry_msgs::PoseStamped makePose(double x, double y)
return pose; return pose;
} }
/// @brief Số lần capability `TestPlannerOkExternalGrid` đã được gọi trong thư viện test.
std::size_t pluginExternalGridCalls()
{
return boost::dll::import_alias<std::size_t()>(
"libmove_base2_test_global_planner", "TestPlannerExternalGridCalls",
boost::dll::load_mode::append_decorations | boost::dll::load_mode::search_system_folders)();
}
/// @brief Runner đã configure với planner @p name; ASSERT nếu không nạp được. /// @brief Runner đã configure với planner @p name; ASSERT nếu không nạp được.
class Fixture class Fixture
{ {
@@ -188,6 +196,40 @@ TEST(PlannerRunner, SwapsBetweenPlannersAndReusesLoadedLibraries)
"reloaded the library"; "reloaded the library";
} }
// ================================================================================================
// Capability lưới ngoài ("<alias>ExternalGrid")
// ================================================================================================
TEST(PlannerRunner, ReportsExternalGridCapabilityPerPlanner)
{
// Capability tra theo alias phụ trong cùng .so. TestPlannerOk export, TestPlannerEmptyPlan cố ý
// không — runner phải phân biệt được hai cái, và đổi qua lại không được "dính" cờ của planner cũ.
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
EXPECT_TRUE(fixture.runner_.activePlannerSupportsExternalGrid());
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerEmptyPlan"));
EXPECT_FALSE(fixture.runner_.activePlannerSupportsExternalGrid());
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_TRUE(fixture.runner_.activePlannerSupportsExternalGrid());
}
TEST(PlannerRunner, ExternalGridIsNotCalledWhileTheCostmapLockIsDisabled)
{
// Test này chạy với costmap GIẢ (disableCostmapLockForTesting). Nhánh snapshot phải hỏi
// isSnapshotEnabled() trên costmap thật — nên khi khoá tắt, runner không được chạm capability,
// kể cả để truyền nullptr. Đường "snapshot thật" thuộc kiểm thử sim (xem docs/THREADING.md).
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
const std::size_t before = pluginExternalGridCalls();
move_base2::PlanResult result;
ASSERT_TRUE(runOnePlan(fixture.runner_, makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, result));
EXPECT_TRUE(result.succeeded);
EXPECT_EQ(pluginExternalGridCalls(), before);
}
TEST(PlannerRunner, FailedSwapKeepsThePreviousPlannerActive) TEST(PlannerRunner, FailedSwapKeepsThePreviousPlannerActive)
{ {
// Bên gọi từ chối yêu cầu dựa trên giá trị trả về. Chuyển sang trạng thái "không có planner" sẽ // Bên gọi từ chối yêu cầu dựa trên giá trị trả về. Chuyển sang trạng thái "không có planner" sẽ
@@ -732,6 +774,51 @@ TEST(PlannerRunnerDockingMarker, ProfileWithoutFootprintDockIsAcceptedAndChanges
EXPECT_EQ(pluginInitializeCount(), before); EXPECT_EQ(pluginInitializeCount(), before);
} }
TEST(PlannerRunnerDockingMarker, CopiesAndClearsOptionalDockOverridesPerMarker)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
robot::NodeHandle nh;
// Create isolated profiles in the shared test parameter tree so this test does not alter the
// checked-in fixture or affect the existing dock_a/dock_b footprint tests.
nh.setParam("docking_marker_profiles/dock_override/dock_face_offset", 0.40);
nh.setParam("docking_marker_profiles/dock_override/dock_pivot_safety_margin", 0.10);
nh.setParam("docking_marker_profiles/dock_no_override/global_planner",
YAML::Node("TestPlannerOk"));
const std::size_t before = pluginInitializeCount();
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_override", "TestPlannerOk"));
YAML::Node copied_face_offset;
YAML::Node copied_margin;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_face_offset", copied_face_offset));
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_pivot_safety_margin", copied_margin));
EXPECT_DOUBLE_EQ(copied_face_offset.as<double>(), 0.40);
EXPECT_DOUBLE_EQ(copied_margin.as<double>(), 0.10);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 1);
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_no_override", "TestPlannerOk"));
YAML::Node cleared_face_offset;
YAML::Node cleared_margin;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_face_offset", cleared_face_offset));
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_pivot_safety_margin", cleared_margin));
EXPECT_TRUE(cleared_face_offset.IsNull());
EXPECT_TRUE(cleared_margin.IsNull());
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 2);
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_override", "TestPlannerOk"));
YAML::Node restored_face_offset;
YAML::Node restored_margin;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_face_offset", restored_face_offset));
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_pivot_safety_margin", restored_margin));
EXPECT_DOUBLE_EQ(restored_face_offset.as<double>(), 0.40);
EXPECT_DOUBLE_EQ(restored_margin.as<double>(), 0.10);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 3);
}
TEST(PlannerRunnerDockingMarker, EmptyMarkerOrPlannerNameIsANoOp) TEST(PlannerRunnerDockingMarker, EmptyMarkerOrPlannerNameIsANoOp)
{ {
Fixture fixture; Fixture fixture;

View File

@@ -12,8 +12,13 @@
* planner: chúng mở cửa sổ quan sát vào việc `initialize()` chạy mấy lần và đọc được param nào — * planner: chúng mở cửa sổ quan sát vào việc `initialize()` chạy mấy lần và đọc được param nào —
* thứ mà `bindDockingMarker` phải làm đúng và không có đường nào khác để kiểm từ ngoài. * thứ mà `bindDockingMarker` phải làm đúng và không có đường nào khác để kiểm từ ngoài.
* *
* `TestPlannerOkExternalGrid` + `TestPlannerExternalGridCalls`: capability lưới ngoài đúng chữ ký
* `sbpl_lattice_planner::setExternalGridOn`, export CHỈ cho `TestPlannerOk`. Nhờ đó test kiểm được
* PlannerRunner tra alias phụ đúng tên và không gọi nó khi khoá costmap bị tắt (costmap giả).
*
* Không alias nào chạm vào con trỏ costmap — đó là điều kiện để test truyền vào một con trỏ giả * Không alias nào chạm vào con trỏ costmap — đó là điều kiện để test truyền vào một con trỏ giả
* thay vì phải dựng `Costmap2DROBOT` thật (cần tf3::BufferCore và cây config đầy đủ). * thay vì phải dựng `Costmap2DROBOT` thật (cần tf3::BufferCore và cây config đầy đủ). Setter lưới
* ngoài chỉ ĐẾM và ghi lại con trỏ, không dereference.
* *
* Author: DuongTD * Author: DuongTD
*********************************************************************/ *********************************************************************/
@@ -34,6 +39,11 @@
#include <robot_nav_core/base_global_planner.h> #include <robot_nav_core/base_global_planner.h>
#include <robot_nav_core/preemptable.h> #include <robot_nav_core/preemptable.h>
namespace robot_costmap_2d
{
class Costmap2D; // chỉ cần con trỏ cho chữ ký capability, không dereference
}
namespace move_base2 namespace move_base2
{ {
namespace testing namespace testing
@@ -244,6 +254,26 @@ std::string lastFootprintDock()
return g_last_footprint_dock; return g_last_footprint_dock;
} }
/// Số lần capability ExternalGrid được gọi trên thư viện này — kể cả với `nullptr`.
std::size_t g_external_grid_calls = 0;
/**
* @brief Capability lưới ngoài của `TestPlannerOk` — cùng chữ ký `sbpl_lattice_planner::setExternalGridOn`.
*
* Chỉ đếm. Không dereference @p grid (test dùng costmap giả) và không đổi hành vi planner: thứ cần
* kiểm là PlannerRunner có TÌM và GỌI đúng alias hay không, không phải planner làm gì với lưới.
*/
void setExternalGridOnOk(robot_nav_core::BaseGlobalPlanner* /*planner*/,
const robot_costmap_2d::Costmap2D* /*grid*/)
{
++g_external_grid_calls;
}
std::size_t externalGridCalls()
{
return g_external_grid_calls;
}
} // namespace testing } // namespace testing
} // namespace move_base2 } // namespace move_base2
@@ -255,3 +285,7 @@ BOOST_DLL_ALIAS(move_base2::testing::createSlowPreemptable, TestPlannerSlowPreem
BOOST_DLL_ALIAS(move_base2::testing::createSlowStubborn, TestPlannerSlowStubborn) BOOST_DLL_ALIAS(move_base2::testing::createSlowStubborn, TestPlannerSlowStubborn)
BOOST_DLL_ALIAS(move_base2::testing::initializeCount, TestPlannerInitializeCount) BOOST_DLL_ALIAS(move_base2::testing::initializeCount, TestPlannerInitializeCount)
BOOST_DLL_ALIAS(move_base2::testing::lastFootprintDock, TestPlannerLastFootprintDock) BOOST_DLL_ALIAS(move_base2::testing::lastFootprintDock, TestPlannerLastFootprintDock)
// Capability "<alias>ExternalGrid" — CHỈ cho TestPlannerOk; các alias khác cố ý không có để test
// đường "plugin không export -> khoá dài".
BOOST_DLL_ALIAS(move_base2::testing::setExternalGridOnOk, TestPlannerOkExternalGrid)
BOOST_DLL_ALIAS(move_base2::testing::externalGridCalls, TestPlannerExternalGridCalls)

View File

@@ -152,6 +152,27 @@ TEST(SensorGateway, StaticMapArrivesWithOccupancyGridType)
EXPECT_TRUE(*layer->records()[0].type == typeid(robot_nav_msgs::OccupancyGrid)); EXPECT_TRUE(*layer->records()[0].type == typeid(robot_nav_msgs::OccupancyGrid));
} }
TEST(SensorGateway, DirectionalLayerSeesAStaticMapBeforeTheStaticLayer)
{
// A same-geometry map must invalidate the old direction field before StaticLayer can be written
// and report current; otherwise a plan could pair the new map with the old zones (DIRECTION_ZONE_PLAN 5.3).
Bench bench;
std::vector<std::string> order;
SpyPtr static_layer = bench.addGlobal(LayerType::STATIC_LAYER, "navigation_map");
SpyPtr directional = bench.addGlobal(LayerType::DIRECTIONAL_LAYER, "direction_zones");
static_layer->setObserver([&](const void*, const std::type_info&, const std::string&) {
order.push_back("static");
});
directional->setObserver([&](const void*, const std::type_info&, const std::string&) {
order.push_back("directional");
});
bench.attach();
bench.gateway().pushStaticMap("/map", robot_nav_msgs::OccupancyGrid());
EXPECT_EQ(order, (std::vector<std::string>{"directional", "static"}));
}
TEST(SensorGateway, PointCloudAndPointCloud2AreDistinctTypes) TEST(SensorGateway, PointCloudAndPointCloud2AreDistinctTypes)
{ {
Bench bench; Bench bench;
@@ -220,6 +241,27 @@ TEST(SensorGateway, ObstacleDataGoesOnlyToVoxelLayers)
EXPECT_EQ(inflation->count(), 0U); EXPECT_EQ(inflation->count(), 0U);
} }
TEST(SensorGateway, DepthCameraLayerGetsPointCloud2Only)
{
// DepthCameraObstacleLayer has its own LayerType: it must get the camera cloud, and neither the
// depth image (it does not use it) nor anything meant for the lidar layers.
Bench bench;
SpyPtr depth_layer = bench.addLocal(LayerType::DEPTH_CAMERA_LAYER, "depth_obstacles");
SpyPtr global_depth = bench.addGlobal(LayerType::DEPTH_CAMERA_LAYER, "depth_obstacles");
SpyPtr voxel = bench.addLocal(LayerType::VOXEL_LAYER, "lidar_obstacles");
bench.attach();
bench.gateway().pushLaserScan("/f_scan", makeScan());
bench.gateway().pushPointCloud("/pc", robot_sensor_msgs::PointCloud());
bench.gateway().pushPointCloud2("/camera/depth/points_proc", robot_sensor_msgs::PointCloud2());
bench.gateway().pushDepthCameraData("/camera/depth/data", makeDepth());
ASSERT_EQ(depth_layer->count(), 1U);
EXPECT_TRUE(*depth_layer->records()[0].type == typeid(robot_sensor_msgs::PointCloud2));
EXPECT_EQ(global_depth->count(), 1U);
EXPECT_EQ(voxel->count(), 4U); // the voxel layers keep getting everything, as before
}
TEST(SensorGateway, LayerNamedAfterATopicDoesNotReceiveTheSample) TEST(SensorGateway, LayerNamedAfterATopicDoesNotReceiveTheSample)
{ {
// Hồi quy cho C5. Bản `move_base` cũ lọc bằng // Hồi quy cho C5. Bản `move_base` cũ lọc bằng

View File

@@ -393,6 +393,31 @@ TEST(StateMachinePlanning, PlannerPatienceEscalatesToRecovery)
EXPECT_TRUE(out.stop_planner); EXPECT_TRUE(out.stop_planner);
} }
TEST(StateMachinePlanning, CostmapWaitDoesNotSpendPatienceOrRetries)
{
StateMachineConfig config = baseConfig();
config.max_planning_retries = 0;
Driver driver(config);
StateMachineInput request;
request.has_pending_request = true;
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
StateMachineInput waiting;
waiting.planner = PlannerFeedback::kWaitingForCostmap;
for (int i = 0; i < 20; ++i)
{
driver.advance(0.6);
EXPECT_EQ(driver.tick(waiting).state, NavigationState::kPlanning);
}
StateMachineInput busy;
busy.planner = PlannerFeedback::kBusy;
busy.planner_costmap_wait_finished = true;
driver.advance(0.6);
EXPECT_EQ(driver.tick(busy).state, NavigationState::kPlanning);
driver.advance(0.6);
EXPECT_EQ(driver.tick(StateMachineInput()).state, NavigationState::kPlanning);
EXPECT_EQ(driver.tick(plannerFailed()).state, NavigationState::kRecovering);
}
TEST(StateMachinePlanning, MaxRetriesEscalatesBeforePatienceExpires) TEST(StateMachinePlanning, MaxRetriesEscalatesBeforePatienceExpires)
{ {
StateMachineConfig config = baseConfig(); StateMachineConfig config = baseConfig();

View File

@@ -596,6 +596,39 @@ TEST(ControlLoop, BackupPlannerFailureEscalatesToRecovery)
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed); EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed);
} }
// Backup chỉ dành cho position. Docking/go_straight/rotate fail thì đi thẳng recovery, planner chính
// giữ nguyên — robot KIT 26/10: SBPL thay DockPlanner dựng đường thẳng vào dock, bỏ qua cusp.
TEST(ControlLoop, NonPositionPlannerFailureSkipsBackup)
{
for (const MotionProfile profile :
{MotionProfile::kDocking, MotionProfile::kGoStraight, MotionProfile::kRotate})
{
SCOPED_TRACE(toString(profile));
ControlLoopConfig config = baseConfig();
config.backup_global_planner_name = "FakeBackupGlobalPlanner";
config.state_machine.max_planning_retries = 0;
Fixture fixture(config);
fixture.planner_.setScript({PlannerScript::kFail, PlannerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning});
std::string reason;
NavigationRequest request = makeRequest(3.0, 73);
request.profile = profile;
ASSERT_TRUE(fixture.loop_.submit(request, reason)) << reason;
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
{
fixture.stepOnce();
}
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeGlobalPlanner");
EXPECT_EQ(fixture.planner_.makePlanCount(), 1u);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
EXPECT_EQ(fixture.recovery_.startCount(), 1u);
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed);
}
}
TEST(ControlLoop, PlannerFailureDrivesRecoveryThenSucceeds) TEST(ControlLoop, PlannerFailureDrivesRecoveryThenSucceeds)
{ {
// Kịch bản thật: planner bế tắc cho tới khi recovery gỡ được thế, sau đó lập plan bình thường. // Kịch bản thật: planner bế tắc cho tới khi recovery gỡ được thế, sau đó lập plan bình thường.
@@ -2059,7 +2092,7 @@ int main(int argc, char** argv)
// ================================================================================================= // =================================================================================================
// EnvMonitor kContact — phanh theo quỹ đạo thật, cờ collision, leo thang khi route khoá (P4, 2026-09-05). // EnvMonitor kContact — phanh theo quỹ đạo thật, cờ collision, leo thang khi route khoá (P4, 2026-09-05).
// PathMonitor cũ (4 phép đo, PathCheckPort) đã xoá 6/9/2026 — xem Test/ENV_MONITOR_PLAN.md §4.19. // PathMonitor cũ (4 phép đo, PathCheckPort) đã xoá 6/9/2026 — xem Test/docs/move_base2/ENV_MONITOR_PLAN.md §4.19.
// ================================================================================================= // =================================================================================================
namespace namespace
{ {

View File

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