Compare commits
21 Commits
180c0e1cd4
...
feature/di
| Author | SHA1 | Date | |
|---|---|---|---|
| c6e70b7dc5 | |||
| 6decd8db32 | |||
| 7bfb3c362d | |||
| f85d89ef8c | |||
| 75af8ccf12 | |||
| c3c64919d3 | |||
| ea7f9659b8 | |||
| 8977e5ec14 | |||
| 490f48becb | |||
| f4f99650df | |||
| 1e8abf2ce4 | |||
| 0d333212b1 | |||
| 9f504ee50e | |||
| b205cf41bc | |||
| dc359007b8 | |||
| bb645111f7 | |||
| 8d9932c905 | |||
| f42cff3510 | |||
| ac307b0358 | |||
| 8bc4895a60 | |||
| 7d00c5ab66 |
@@ -230,6 +230,7 @@ endif()
|
|||||||
# ========================================================
|
# ========================================================
|
||||||
add_library(move_base2_core SHARED
|
add_library(move_base2_core SHARED
|
||||||
src/navigation_state.cpp
|
src/navigation_state.cpp
|
||||||
|
src/component_status.cpp
|
||||||
src/state_machine.cpp
|
src/state_machine.cpp
|
||||||
src/velocity_arbiter.cpp
|
src/velocity_arbiter.cpp
|
||||||
src/plan_inspector.cpp
|
src/plan_inspector.cpp
|
||||||
@@ -242,6 +243,7 @@ add_library(move_base2_core SHARED
|
|||||||
src/runners/planner_runner.cpp
|
src/runners/planner_runner.cpp
|
||||||
src/runners/controller_runner.cpp
|
src/runners/controller_runner.cpp
|
||||||
src/io/runtime_stats.cpp
|
src/io/runtime_stats.cpp
|
||||||
|
src/io/watchdog.cpp
|
||||||
src/io/sensor_gateway.cpp
|
src/io/sensor_gateway.cpp
|
||||||
src/io/sensor_store_types.cpp
|
src/io/sensor_store_types.cpp
|
||||||
src/io/costmap_exporter.cpp
|
src/io/costmap_exporter.cpp
|
||||||
@@ -450,6 +452,8 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
|
|||||||
endforeach()
|
endforeach()
|
||||||
|
|
||||||
set(MOVE_BASE2_TESTS
|
set(MOVE_BASE2_TESTS
|
||||||
|
component_status_test
|
||||||
|
watchdog_test
|
||||||
state_machine_test
|
state_machine_test
|
||||||
velocity_arbiter_test
|
velocity_arbiter_test
|
||||||
plan_inspector_test
|
plan_inspector_test
|
||||||
@@ -466,6 +470,7 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
|
|||||||
controller_runner_test
|
controller_runner_test
|
||||||
mission_adapter_bridge_test
|
mission_adapter_bridge_test
|
||||||
mission_layer_test
|
mission_layer_test
|
||||||
|
deferred_goal_test
|
||||||
move_base2_scenario_test # tên có tiền tố gói: nav_test_harness đã có target scenario_test
|
move_base2_scenario_test # tên có tiền tố gói: nav_test_harness đã có target scenario_test
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
12
README.md
12
README.md
@@ -99,6 +99,18 @@ Order đi qua `mission_adapters`: cắt chặng tại mỗi node có action, ch
|
|||||||
bảng `compound_actions`: đẩy thẳng xuống lõi sẽ biến `PickUp` thành một chặng chỉ-action không có
|
bảng `compound_actions`: đẩy thẳng xuống lõi sẽ biến `PickUp` thành một chặng chỉ-action không có
|
||||||
bước dò và không có bước tiến vào — robot báo "đã nâng kệ" khi càng còn chưa tới gần kệ.
|
bước dò và không có bước tiến vào — robot báo "đã nâng kệ" khi càng còn chưa tới gần kệ.
|
||||||
|
|
||||||
|
### Bốn lệnh vòng đời: `pause` / `resume` / `cancel` / `emergency`
|
||||||
|
|
||||||
|
Ba lệnh đầu là **xung** ghi dưới `data_mutex_`, control thread áp ở cycle kế (`drainLifecycleRequests`).
|
||||||
|
`cancel` từ host huỷ cả order (xoá hàng đợi mission); `pause`/`resume` cố ý không lan xuống mission
|
||||||
|
layer. `CANCELLED`/`PAUSED` chỉ báo khi runtime im hẳn — xem `docs/STATE_MACHINE.md`.
|
||||||
|
|
||||||
|
`emergency()` / `clearEmergency()` (2026-09-14) là **mức có chốt**: lệnh 0 ngay, huỷ chặng, xoá
|
||||||
|
hàng đợi, vào `EMERGENCY`; từ chối mọi `moveTo`/`executeInstantActions`, bỏ qua ba lệnh kia, cho tới
|
||||||
|
khi host gỡ chốt — về `PENDING`, robot **không tự chạy lại**. Khác ba lệnh kia ở chỗ có hiệu lực
|
||||||
|
trên chính thread host trước khi trả về (`getTwist()` = 0, `getFeedback()` = `EMERGENCY`), không
|
||||||
|
chờ control thread — xem `docs/THREADING.md`.
|
||||||
|
|
||||||
### Bốn entry point đã bị gỡ
|
### Bốn entry point đã bị gỡ
|
||||||
|
|
||||||
`dockTo` ×2, `moveStraightTo`, `rotateTo` không còn trong contract host. Chúng submit thẳng vào lõi,
|
`dockTo` ×2, `moveStraightTo`, `rotateTo` không còn trong contract host. Chúng submit thẳng vào lõi,
|
||||||
|
|||||||
@@ -22,9 +22,12 @@
|
|||||||
# move_to_param: <key> chặng nav, frame lấy từ actionParameters[<key>] của action gốc
|
# move_to_param: <key> chặng nav, frame lấy từ actionParameters[<key>] của action gốc
|
||||||
# move: <mét> chặng nav tương đối; dương = tiến, âm = lùi
|
# move: <mét> chặng nav tương đối; dương = tiến, âm = lùi
|
||||||
#
|
#
|
||||||
# Tuỳ chọn cho step navigation: profile (position | docking | go_straight | rotate), marker.
|
# Tuỳ chọn cho step navigation: profile (position | docking | go_straight | rotate), marker,
|
||||||
|
# turn_param.
|
||||||
# `marker` chỉ hợp lệ với `profile: docking`: nó chọn override trong
|
# `marker` chỉ hợp lệ với `profile: docking`: nó chọn override trong
|
||||||
# maker_sources.yaml/docking_marker_profiles. Không khai = dùng cặp docking mặc định.
|
# maker_sources.yaml/docking_marker_profiles. Không khai = dùng cặp docking mặc định.
|
||||||
|
# `turn_param: <key>` chỉ hợp lệ với `profile: rotate`: góc quay [deg] lấy từ actionParameters[<key>]
|
||||||
|
# của chính order. Gắn nhầm profile thì node TRƯỢT LÚC BOOT, không phải bị bỏ qua lúc chạy.
|
||||||
# Tolerance thuộc YAML riêng của local planner đang được profile chọn, không khai ở đây.
|
# Tolerance thuộc YAML riêng của local planner đang được profile chọn, không khai ở đây.
|
||||||
#
|
#
|
||||||
# ── Ba quy tắc khi sửa ───────────────────────────────────────────────────────────────────────────
|
# ── Ba quy tắc khi sửa ───────────────────────────────────────────────────────────────────────────
|
||||||
@@ -101,7 +104,21 @@ vda5050_src:
|
|||||||
|
|
||||||
rotate:
|
rotate:
|
||||||
steps:
|
steps:
|
||||||
# ► Chỉnh: `move: 0.0` = không tịnh tiến; góc quay lấy từ actionParameters của order.
|
# `move: 0.0` = không tịnh tiến. Góc quay KHÔNG khai ở đây: `turn_param: angle_deg` nói rằng
|
||||||
# Profile `rotate` dùng PNKXRotateLocalPlanner, tham số ở YAML của plugin đó.
|
# góc lấy từ actionParameters['angle_deg'] của chính order, tính bằng ĐỘ, dương = ngược
|
||||||
- {move: 0.0, profile: rotate}
|
# chiều kim đồng hồ. Nhờ vậy đổi góc quay không phải sửa file này.
|
||||||
|
#
|
||||||
|
# ► Chỉnh: đổi `angle_deg` nếu fleet gửi khoá tên khác. Order thiếu khoá đó, hoặc gửi giá trị
|
||||||
|
# không phải số, hoặc vượt [-180, 180] độ -> adapter BỎ CẢ MESSAGE, robot không nhúc nhích.
|
||||||
|
#
|
||||||
|
# ⚠ Biên 180 độ không phải để cho đẹp: đích của chặng là một pose, mà pose chỉ nói hướng
|
||||||
|
# cuối chứ không nói quay bao nhiêu hay chiều nào. Xin 270 độ ngược kim đồng hồ thì robot
|
||||||
|
# sẽ quay 90 độ THUẬN kim đồng hồ — nên adapter từ chối thẳng thay vì quay ngược ý người gửi.
|
||||||
|
#
|
||||||
|
# ⚠ Chặng quay hiện KHÔNG kiểm va chạm: footprint quét qua vùng xung quanh mà không ai chặn.
|
||||||
|
# Chỉ dùng ở nơi biết là trống quanh robot.
|
||||||
|
#
|
||||||
|
# Profile `rotate` dùng HybridRotateLocalPlanner, tham số ở khối cùng tên trong
|
||||||
|
# hybrid_local_planner_params.yaml.
|
||||||
|
- {move: 0.0, profile: rotate, turn_param: angle_deg}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -538,3 +538,64 @@ HybridDockingLocalPlanner:
|
|||||||
# chiều đi của path), sai lệch hướng so với tiếp tuyến path, cự ly còn lại
|
# chiều đi của path), sai lệch hướng so với tiếp tuyến path, cự ly còn lại
|
||||||
# tới cuối chặng, và ngưỡng chuyển chặng. Đây là dòng để trả lời "robot có
|
# tới cuối chặng, và ngưỡng chuyển chặng. Đây là dòng để trả lời "robot có
|
||||||
# bám path không" và "chuyển chặng có đúng ở cusp không".
|
# bám path không" và "chuyển chặng có đúng ở cusp không".
|
||||||
|
|
||||||
|
# =================================================================================================
|
||||||
|
# HybridRotateLocalPlanner — quay tại chỗ, KHÔNG tịnh tiến.
|
||||||
|
#
|
||||||
|
# Ai đọc khối này: profile `rotate` của move_base2 (chặng sinh từ compound action `rotate`, khai
|
||||||
|
# trong compound_actions_params.yaml). Chặng đó có goal trùng vị trí robot và chỉ khác hướng.
|
||||||
|
#
|
||||||
|
# Planner này KHÔNG đọc các pose giữa của global plan: chặng quay có start trùng goal nên global
|
||||||
|
# planner không có gì để nội suy, hướng các pose giữa sinh ra từ jitter localization. Nó chỉ dùng
|
||||||
|
# pose hiện tại và pose đích. Vì vậy ở đây không có khoá nào về lookahead hay bám path.
|
||||||
|
#
|
||||||
|
# Vận tốc thẳng luôn bằng 0 trên mọi nhánh — không có khoá nào chỉnh được điều đó.
|
||||||
|
# =================================================================================================
|
||||||
|
HybridRotateLocalPlanner:
|
||||||
|
library_path: libhybrid_local_planner
|
||||||
|
|
||||||
|
# ===== Giới hạn vận tốc góc =====
|
||||||
|
# ► Chỉnh: [rad/s] trần tốc độ quay. Phải <= max_vel_theta của move_base2 (move_base_common_params.yaml),
|
||||||
|
# vì VelocityArbiter cắt phần vượt — mà lệnh bị cắt thì phá luôn đoạn giảm tốc tính ở đây.
|
||||||
|
# TĂNG = quay nhanh hơn, rung lắc và trượt bánh nhiều hơn; GIẢM = chậm và êm.
|
||||||
|
max_angular_velocity: 0.5
|
||||||
|
|
||||||
|
# ► Chỉnh: [rad/s] sàn tốc độ khi CHƯA vào tolerance, để thắng ma sát tĩnh.
|
||||||
|
# Quá THẤP: bánh kêu mà robot không nhúc nhích, chặng không bao giờ xong.
|
||||||
|
# Quá CAO: bước một chu kỳ rộng hơn dải tolerance, robot vọt qua rồi quay lại liên tục.
|
||||||
|
# Ràng buộc an toàn: min_angular_velocity * control_period phải NHỎ HƠN yaw_goal_tolerance;
|
||||||
|
# sai điều kiện này thì planner in lỗi lúc boot.
|
||||||
|
min_angular_velocity: 0.05
|
||||||
|
|
||||||
|
# ► Chỉnh: [rad/s^2] trần gia tốc góc mỗi chu kỳ, tính từ giá trị lớn hơn giữa tốc độ đo được
|
||||||
|
# và lệnh chu kỳ trước. GIẢM = khởi động mềm, lâu đạt tốc; TĂNG = giật khi bắt đầu quay.
|
||||||
|
angular_acceleration: 0.8
|
||||||
|
|
||||||
|
# ► Chỉnh: [rad/s^2] gia tốc hãm dùng để dựng đoạn giảm tốc (omega = sqrt(2 * decel * góc_còn_lại)).
|
||||||
|
# GIẢM = phanh sớm và tới đích chậm rãi, ít vọt qua; TĂNG = giữ tốc lâu rồi phanh gấp,
|
||||||
|
# dễ vọt qua tolerance nếu base không theo kịp.
|
||||||
|
angular_deceleration: 0.6
|
||||||
|
|
||||||
|
# ===== Điều kiện kết thúc chặng =====
|
||||||
|
# ► Chỉnh: [rad] sai số hướng chấp nhận là "đã tới". 0.02 rad ~ 1.15 độ.
|
||||||
|
# GIẢM = đích chính xác hơn nhưng dễ hunt quanh goal nếu base không quay được chậm như vậy.
|
||||||
|
yaw_goal_tolerance: 0.02
|
||||||
|
|
||||||
|
# ► Chỉnh: [rad/s] dưới ngưỡng này coi như thân robot đã dừng hẳn. Chặng chỉ báo xong khi
|
||||||
|
# VỪA vào tolerance VỪA dừng — báo xong lúc còn trôi theo quán tính là giao cho chặng sau
|
||||||
|
# một hướng vẫn đang đổi. TĂNG = kết thúc sớm hơn nhưng kém chính xác.
|
||||||
|
rot_stopped_velocity: 0.03
|
||||||
|
|
||||||
|
# ► Chỉnh: [s] chu kỳ điều khiển giả định khi không đo được thời gian giữa hai lần gọi (chu kỳ
|
||||||
|
# đầu, hoặc đồng hồ nhảy lùi lúc replay bag). Nên khớp controller_frequency của move_base2
|
||||||
|
# (20 Hz -> 0.05 s).
|
||||||
|
control_period: 0.05
|
||||||
|
|
||||||
|
# ===== Debug =====
|
||||||
|
# Hai nhóm log, mặc định BẬT. Log LỖI không nằm sau cờ nào — tắt được một dòng lỗi nghĩa là
|
||||||
|
# tồn tại cấu hình khiến robot hỏng trong im lặng.
|
||||||
|
debug_state: true # đổi trạng thái: nhận goal mới, tới đích, từ chối chặng
|
||||||
|
debug_command: true # lệnh đang phát: sai số góc, omega, tốc độ đo được, dt
|
||||||
|
debug_command_throttle_cycles: 20 # in tối đa 1 dòng debug_command mỗi ngần này chu kỳ
|
||||||
|
# (20 Hz -> 20 chu kỳ = 1 dòng/giây). Đặt 1 = in mọi chu kỳ,
|
||||||
|
# rất nặng I/O, chỉ dùng khi bắt lỗi ngắn.
|
||||||
|
|||||||
@@ -41,8 +41,10 @@ go_straight:
|
|||||||
local_planner: HybridDockingLocalPlanner # instance Stanley riêng, block cùng tên (path 2 điểm thẳng)
|
local_planner: HybridDockingLocalPlanner # instance Stanley riêng, block cùng tên (path 2 điểm thẳng)
|
||||||
|
|
||||||
rotate:
|
rotate:
|
||||||
global_planner: TwoPointsPlanner
|
global_planner: TwoPointsPlanner # chặng quay có start trùng goal: plan chỉ để hợp lệ, planner
|
||||||
local_planner: HybridDockingLocalPlanner # instance Stanley riêng: XY đã trong tolerance -> Phase B xoay về yaw goal
|
# dưới không đọc các pose giữa
|
||||||
|
local_planner: HybridRotateLocalPlanner # quay tại chỗ, v = 0 tuyệt đối; tham số ở khối cùng tên
|
||||||
|
# trong hybrid_local_planner_params.yaml
|
||||||
|
|
||||||
# Đường lùi chung cho mọi profile: planner chính trả false hoặc plan rỗng thì move_base2 đổi sang
|
# Đường lùi chung cho mọi profile: planner chính trả false hoặc plan rỗng thì move_base2 đổi sang
|
||||||
# planner này đúng MỘT lần cho request hiện tại. Backup cũng fail thì mới chạy recovery; request mới
|
# planner này đúng MỘT lần cho request hiện tại. Backup cũng fail thì mới chạy recovery; request mới
|
||||||
@@ -60,6 +62,24 @@ backup_global_planner: SBPLLatticePlanner
|
|||||||
# local planner nằm trong các YAML runtime đồng hành (symlink từ pnkx_nav_core/config/). Không lặp
|
# local planner nằm trong các YAML runtime đồng hành (symlink từ pnkx_nav_core/config/). Không lặp
|
||||||
# lại chúng ở đây để tránh hai nguồn cấu hình cho cùng một plugin.
|
# lại chúng ở đây để tránh hai nguồn cấu hình cho cùng một plugin.
|
||||||
|
|
||||||
|
# =================================================================================================
|
||||||
|
# Đường vào cảm biến — lọc trước khi vào costmap (khác kho `sensor_store` ở file riêng, xem
|
||||||
|
# `sensor_store_params.yaml`: kho giữ bản THÔ, khối dưới đây lọc bản đi vào costmap).
|
||||||
|
# =================================================================================================
|
||||||
|
sensors:
|
||||||
|
# Bật lọc statistical-outlier-removal cho LaserScan trước khi đưa vào costmap.
|
||||||
|
# ► Chỉnh: mặc định TẮT có chủ đích — bật là âm thầm xoá bớt điểm vật cản khỏi costmap, không
|
||||||
|
# phải thứ nên tự xảy ra. Chỉ bật khi lidar thật có nhiễu đo được (điểm bay lơ lửng ngoài vật
|
||||||
|
# cản thật) và đã xác nhận qua log/rviz, không bật để "chắc ăn".
|
||||||
|
laser_sor_enabled: false
|
||||||
|
|
||||||
|
# [điểm] Số láng giềng gần nhất dùng để ước lượng khoảng cách trung bình. Chỉ đọc khi bật lọc.
|
||||||
|
laser_sor_mean_k: 10
|
||||||
|
|
||||||
|
# [-] Ngưỡng outlier = mean + hệ_số * stddev. Chỉ đọc khi bật lọc.
|
||||||
|
# ► Chỉnh: GIẢM lọc mạnh tay hơn (dễ mất vật cản thật ở biên); TĂNG lọc lơi hơn (dễ để nhiễu lọt).
|
||||||
|
laser_sor_stddev_mul: 1.0
|
||||||
|
|
||||||
# =================================================================================================
|
# =================================================================================================
|
||||||
# Nhịp điều khiển và các đồng hồ kiên nhẫn (contract 2026-08-04 — tách replan nền khỏi recovery)
|
# Nhịp điều khiển và các đồng hồ kiên nhẫn (contract 2026-08-04 — tách replan nền khỏi recovery)
|
||||||
# =================================================================================================
|
# =================================================================================================
|
||||||
@@ -105,12 +125,22 @@ 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` ở
|
||||||
# sbpl_global_params.yaml ⇒ 2.0 s là NGẮN HƠN trần của chính planner: nếu thấy leo thang trong khi
|
# sbpl_global_params.yaml ⇒ 2.0 s là NGẮN HƠN trần của chính planner: nếu thấy leo thang trong khi
|
||||||
# planner vẫn đang chạy, tăng giá trị này lên trên trần đó.
|
# planner vẫn đang chạy, tăng giá trị này lên trên trần đó.
|
||||||
planner_patience: 2.0
|
planner_patience: 25.0
|
||||||
|
|
||||||
# Số lần lập plan HỎNG liên tiếp được phép trước khi leo thang. 0 = hỏng một lượt là leo thang ngay.
|
# Số lần lập plan HỎNG liên tiếp được phép trước khi leo thang. 0 = hỏng một lượt là leo thang ngay.
|
||||||
# ► Chỉnh: TĂNG (1–3) nếu planner thỉnh thoảng fail do costmap chưa kịp cập nhật lúc vừa nhận goal.
|
# ► Chỉnh: TĂNG (1–3) nếu planner thỉnh thoảng fail do costmap chưa kịp cập nhật lúc vừa nhận goal.
|
||||||
@@ -118,11 +148,42 @@ planner_patience: 2.0
|
|||||||
# ai phát hiện (config validate chặn ca tắt cả hai).
|
# ai phát hiện (config validate chặn ca tắt cả hai).
|
||||||
max_planning_retries: 0
|
max_planning_retries: 0
|
||||||
|
|
||||||
|
# [s] Trần chờ ở CANCELLING và PAUSING cho tới khi runtime IM HẲN rồi mới báo CANCELLED/PREEMPTED
|
||||||
|
# hoặc PAUSED ra host (trong lúc PAUSING host vẫn thấy tên state cũ + feed_back_str "pausing…").
|
||||||
|
# "Im hẳn" = ba điều kiện cùng đúng: (1) lệnh vận tốc = 0 VÀ odom đọc ≈ 0 (xem hai khoá dưới),
|
||||||
|
# (2) thread global planner rảnh và recovery đã dừng — kể cả lượt makePlan đã bị huỷ mà plugin không cắt được (SBPL
|
||||||
|
# hiện chạy tới hết `allocated_time`), (3) action đang chạy đã trả terminal. Host đọc PREEMPTED là
|
||||||
|
# "xong rồi, gửi goal kế được" — báo sớm thì goal kế bị `startPlan()` từ chối vì thread còn bận.
|
||||||
|
# ► Chỉnh: mặc định 2.0. TĂNG (5–10) nếu SBPL `allocated_time` lớn và chưa có preempt (pha 2) — quá
|
||||||
|
# trần vẫn CANCELLED nhưng runtime in LỖI "cancel settle timeout", không tắt được. 0 = TẮT: kết
|
||||||
|
# thúc ngay khi lệnh = 0 như trước 11/9/2026 (host dễ gửi goal kế lúc planner còn bận).
|
||||||
|
settle_timeout: 2.0
|
||||||
|
|
||||||
|
# [m/s] Ngưỡng coi robot ĐÃ DỪNG theo vận tốc ĐO ĐƯỢC (odom), dùng cho điều kiện (1) ở trên.
|
||||||
|
# Lệnh về 0 không có nghĩa bánh xe đã đứng — driver còn giảm tốc; PREEMPTED báo lúc đó là báo cho
|
||||||
|
# một robot đang trượt. Chỉ có tác dụng khi host đẩy odom vào (`addOdometry`); không có odom thì
|
||||||
|
# tự lùi về đo bằng lệnh đã phát.
|
||||||
|
# ► Chỉnh: TĂNG (0.05) nếu odom nhiễu giữ CANCELLING tới tận `settle_timeout` dù robot đã
|
||||||
|
# đứng (xem log lỗi settle timeout với robot_stopped=no). 0 = bỏ odom, chỉ nhìn lệnh.
|
||||||
|
stopped_measured_linear_eps: 0.02
|
||||||
|
|
||||||
|
# [rad/s] Như trên cho trục quay.
|
||||||
|
stopped_measured_angular_eps: 0.02
|
||||||
|
|
||||||
# [s] Ở trong bán kính `oscillation_distance` quá lâu = coi là quẩn -> recovery `oscillation`.
|
# [s] Ở trong bán kính `oscillation_distance` quá lâu = coi là quẩn -> recovery `oscillation`.
|
||||||
# ► Chỉnh: <= 0 là TẮT (giá trị hiện tại). Bật (vd 10–20 s) khi thấy robot lắc qua lắc lại tại chỗ
|
# ► Chỉnh: <= 0 là TẮT (giá trị hiện tại). Bật (vd 10–20 s) khi thấy robot lắc qua lắc lại tại chỗ
|
||||||
# mà không trigger nào khác bắt được. Bật thì `oscillation_distance` bắt buộc phải > 0.
|
# mà không trigger nào khác bắt được. Bật thì `oscillation_distance` bắt buộc phải > 0.
|
||||||
oscillation_timeout: -1
|
oscillation_timeout: -1
|
||||||
|
|
||||||
|
# [s] Trần thời gian cho MỘT action (EXECUTING_ACTIONS), tính từ lúc start. <= 0 = tắt.
|
||||||
|
# Lưới an toàn CUỐI CÙNG, không phải cơ chế timeout chính: (1) mỗi ActionHandler phải tự timeout
|
||||||
|
# theo hiểu biết thiết bị của nó ("nâng kệ quá 20 s là bất thường" khác "sạc 30 phút là bình
|
||||||
|
# thường") — đây là tầng chính; (2) khoá này là tầng 2, lưới cuối cho handler treo không tự thoát;
|
||||||
|
# (3) `mission_timeout` của mission layer đo cả chặng là tầng 3.
|
||||||
|
# ► Chỉnh: chỉ bật khi deployment biết chắc mọi action đều ngắn hơn một trần chung — bật sai với
|
||||||
|
# action hợp lệ chạy lâu (sạc) sẽ cancel action đó + ABORTED oan. Quá hạn -> cancel action.
|
||||||
|
action_patience: 0.0
|
||||||
|
|
||||||
# [m] Đi được quá quãng này thì: hết bị coi là quẩn, VÀ mọi cursor route recovery được reset, VÀ
|
# [m] Đi được quá quãng này thì: hết bị coi là quẩn, VÀ mọi cursor route recovery được reset, VÀ
|
||||||
# trigger giám sát tuyến đang bị khoá được mở lại (contract 2026-08-05e).
|
# trigger giám sát tuyến đang bị khoá được mở lại (contract 2026-08-05e).
|
||||||
# ► Chỉnh: đây là định nghĩa "có tiến độ thật". GIẢM (0.2–0.3) nếu robot ở khu chật ít khi đi nổi
|
# ► Chỉnh: đây là định nghĩa "có tiến độ thật". GIẢM (0.2–0.3) nếu robot ở khu chật ít khi đi nổi
|
||||||
@@ -218,6 +279,65 @@ acc_lim_theta: 1.20
|
|||||||
# chạy thường trực trên robot thật.
|
# chạy thường trực trên robot thật.
|
||||||
runtime_stats_period: 0.0
|
runtime_stats_period: 0.0
|
||||||
|
|
||||||
|
# =================================================================================================
|
||||||
|
# Watchdog thành phần (2026-09-11) — thread riêng đọc bảng trạng thái, kết luận "TREO"
|
||||||
|
#
|
||||||
|
# Mỗi thành phần (global planner, local planner, recovery, action, control loop) tự khai nó đang
|
||||||
|
# bận/dừng/rảnh và "nhích" mỗi nhịp. Watchdog chạy trên thread riêng — control thread treo thì
|
||||||
|
# không tự phát hiện được chính nó — và kết luận treo khi một hàng BẬN mà KHÔNG NHÍCH quá ngân sách.
|
||||||
|
# Treo → in LỖI một lần (không tắt được); control loop treo → host đọc navigation_state = LOST và
|
||||||
|
# phải tự đưa cmd_vel về 0. Đây là chẩn đoán, không phải điều khiển: state machine không đổi gì.
|
||||||
|
# =================================================================================================
|
||||||
|
|
||||||
|
# [s] Chu kỳ kiểm của watchdog. 0 = TẮT watchdog (không có thread, không phát hiện treo).
|
||||||
|
watchdog_period: 0.1
|
||||||
|
|
||||||
|
# [s] Trần MỘT lượt makePlan trên thread planner trước khi kết luận global planner TREO. Từ 11/9/2026
|
||||||
|
# khoá này mới có tác dụng (trước đó đọc mà không dùng). PHẢI LỚN HƠN thời gian một lượt hợp lệ dài
|
||||||
|
# nhất: với SBPL là `allocated_time` trong sbpl_global_params.yaml (đã là trần chung cho cả 3 lượt
|
||||||
|
# replan nội bộ). ► Chỉnh: đặt ≈ allocated_time + 1. 0 = không giám sát hàng này.
|
||||||
|
planner_timeout: 15.0
|
||||||
|
|
||||||
|
# [s] Trần MỘT lời gọi computeVelocityCommands của local planner. Priest 30–48 ms, Hybrid < 10 ms;
|
||||||
|
# 0.5 s là "chắc chắn có gì đó hỏng" chứ không phải chậm. 0 = không giám sát.
|
||||||
|
local_planner_call_budget: 0.5
|
||||||
|
|
||||||
|
# [s] Recovery behavior bận mà không nhích (không tick, worker detour không về) quá đây = treo.
|
||||||
|
recovery_stall_budget: 5.0
|
||||||
|
|
||||||
|
# [s] Action handler bận mà không nhích quá đây = treo. 0 = TẮT (mặc định): handler tự timeout
|
||||||
|
# theo thiết bị của nó (tầng 1), `action_patience` là tầng 2 — không cần tầng thứ ba.
|
||||||
|
action_stall_budget: 0.0
|
||||||
|
|
||||||
|
# [s] Control thread không kết thúc được một cycle nào trong quãng này = TREO → host thấy LOST.
|
||||||
|
# 0.5 s = 15 cycle @ 30 Hz. GIẢM (0.2) nếu host cần phản ứng nhanh hơn; không đặt < 3 cycle vì
|
||||||
|
# một lượt detour/solve dài hợp lệ sẽ bị báo nhầm.
|
||||||
|
control_loop_stall_budget: 0.5
|
||||||
|
|
||||||
|
# =================================================================================================
|
||||||
|
# Namespace cho các thành phần nạp plugin, và frame quy chiếu
|
||||||
|
# =================================================================================================
|
||||||
|
|
||||||
|
# Namespace chứa danh sách recovery behavior (`<ns>/behaviors`) trong YAML — xem
|
||||||
|
# `recovery_behaviors_params.yaml`.
|
||||||
|
recovery_namespace: recovery
|
||||||
|
|
||||||
|
# Namespace chứa danh sách action handler (`<ns>/handlers`) trong YAML — xem
|
||||||
|
# `action_handlers_params.yaml`.
|
||||||
|
action_namespace: actions
|
||||||
|
|
||||||
|
# Namespace chứa cấu hình mission layer — xem `mission_adapters_params.yaml`.
|
||||||
|
mission_namespace: mission_adapters
|
||||||
|
|
||||||
|
# Frame mà goal được quy về trước khi lập plan. Phải khác `robot_base_frame` (khai ở
|
||||||
|
# `costmap_common_params.yaml`), nếu không pose robot luôn là gốc toạ độ.
|
||||||
|
global_frame: map
|
||||||
|
|
||||||
|
# Chặn điều khiển bánh xe khi observation buffer của costmap điều khiển đã quá hạn.
|
||||||
|
# ► Chỉnh: default true = parity với move_base thế hệ 1. Tắt chỉ khi host tự đảm bảo costmap luôn
|
||||||
|
# mới — tắt sai nghĩa là controller có thể lái theo costmap cũ mà không ai chặn.
|
||||||
|
require_current_costmap: true
|
||||||
|
|
||||||
# Bật/tắt toàn bộ recovery. Danh sách behavior và route nằm ở `recovery_behaviors_params.yaml`,
|
# Bật/tắt toàn bộ recovery. Danh sách behavior và route nằm ở `recovery_behaviors_params.yaml`,
|
||||||
# namespace `recovery`.
|
# namespace `recovery`.
|
||||||
# ► Chỉnh: false = mọi lỗi đi thẳng tới ABORTED, không thử phục hồi. Chỉ dùng khi cô lập lỗi lúc
|
# ► Chỉnh: false = mọi lỗi đi thẳng tới ABORTED, không thử phục hồi. Chỉ dùng khi cô lập lỗi lúc
|
||||||
@@ -239,11 +359,11 @@ MoveBase:
|
|||||||
|
|
||||||
# --- Công tắc log chẩn đoán ----------------------------------------------------------------------
|
# --- Công tắc log chẩn đoán ----------------------------------------------------------------------
|
||||||
#
|
#
|
||||||
# Ba nhóm dưới đây gom toàn bộ dòng `[move_base2][debug]`. Trước đây chúng in VÔ ĐIỀU KIỆN, không
|
# Bốn nhóm dưới đây gom toàn bộ dòng `[move_base2][debug]`. Trước đây chúng in VÔ ĐIỀU KIỆN, không
|
||||||
# có cách nào tắt — trên robot chạy cả ca thì phần lớn là tiếng ồn, và tiếng ồn thường trực làm
|
# có cách nào tắt — trên robot chạy cả ca thì phần lớn là tiếng ồn, và tiếng ồn thường trực làm
|
||||||
# dòng thật sự bất thường trôi mất giữa hàng nghìn dòng giống hệt nhau.
|
# dòng thật sự bất thường trôi mất giữa hàng nghìn dòng giống hệt nhau.
|
||||||
#
|
#
|
||||||
# ► Mặc định BẬT cả ba. Tắt là lựa chọn có ý thức, không phải thứ đổi sau lưng người đang dựa vào
|
# ► Mặc định BẬT cả bốn. Tắt là lựa chọn có ý thức, không phải thứ đổi sau lưng người đang dựa vào
|
||||||
# log để debug.
|
# log để debug.
|
||||||
debug:
|
debug:
|
||||||
# Chuyển trạng thái của state machine: `state -> CONTROLLING: valid plan available (...)`.
|
# Chuyển trạng thái của state machine: `state -> CONTROLLING: valid plan available (...)`.
|
||||||
@@ -260,3 +380,8 @@ debug:
|
|||||||
# ► Nhóm ỒN NHẤT — có thể in mỗi chu kỳ khi có gì đó sai kéo dài. Nhưng cũng chính là nhóm trả
|
# ► Nhóm ỒN NHẤT — có thể in mỗi chu kỳ khi có gì đó sai kéo dài. Nhưng cũng chính là nhóm trả
|
||||||
# lời câu "robot đứng im mà không tầng nào báo lỗi", nên ĐỪNG tắt khi đang truy lỗi.
|
# lời câu "robot đứng im mà không tầng nào báo lỗi", nên ĐỪNG tắt khi đang truy lỗi.
|
||||||
skip: true
|
skip: true
|
||||||
|
|
||||||
|
# Một dòng tóm tắt feature của EnvMonitor mỗi giây khi đang giám sát (stall/unreachable/contact/
|
||||||
|
# ngân sách) — xem `env_monitor_params.yaml` cho tham số lõi của EnvMonitor.
|
||||||
|
# ► Rẻ, một dòng mỗi giây. Tắt khi không cần theo dõi EnvMonitor.
|
||||||
|
env: true
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ PriestLocalPlanner:
|
|||||||
# 0 = không cool-down.
|
# 0 = không cool-down.
|
||||||
|
|
||||||
# ================= Giới hạn robot (dẫn động vi sai) =================
|
# ================= Giới hạn robot (dẫn động vi sai) =================
|
||||||
max_velocity: 0.5 # [m/s] trần vận tốc tiến
|
max_velocity: 1.2 # [m/s] trần vận tốc tiến
|
||||||
max_angular_velocity: 0.5 # [rad/s] đồng thời được ép bên trong bộ tối ưu dưới dạng
|
max_angular_velocity: 0.5 # [rad/s] đồng thời được ép bên trong bộ tối ưu dưới dạng
|
||||||
# chặn gia tốc ngang |a_n| <= max_angular_velocity * v
|
# chặn gia tốc ngang |a_n| <= max_angular_velocity * v
|
||||||
max_acceleration: 0.5 # [m/s^2] dùng trong phép chiếu quỹ đạo
|
max_acceleration: 0.5 # [m/s^2] dùng trong phép chiếu quỹ đạo
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -176,7 +176,7 @@ recovery:
|
|||||||
invert_area_to_clear: false
|
invert_area_to_clear: false
|
||||||
# local | global | both — costmap nào bị xoá.
|
# local | global | both — costmap nào bị xoá.
|
||||||
# ► Chỉnh: `local` nếu chỉ muốn làm mới dữ liệu sensor mà không đụng bản đồ tích luỹ.
|
# ► Chỉnh: `local` nếu chỉ muốn làm mới dữ liệu sensor mà không đụng bản đồ tích luỹ.
|
||||||
affected_maps: both
|
affected_maps: local
|
||||||
# Phải khớp `plugins:` của costmap; sai tên -> log kèm tên layer thật.
|
# Phải khớp `plugins:` của costmap; sai tên -> log kèm tên layer thật.
|
||||||
# ► Chỉnh: thêm tên layer nếu costmap có nhiều layer vật cản (vd `[obstacles, voxel_layer]`).
|
# ► Chỉnh: thêm tên layer nếu costmap có nhiều layer vật cản (vd `[obstacles, voxel_layer]`).
|
||||||
# Đây KHÔNG phải số tinh chỉnh — sai tên là behavior không xoá gì cả.
|
# Đây KHÔNG phải số tinh chỉnh — sai tên là behavior không xoá gì cả.
|
||||||
@@ -350,7 +350,7 @@ SBPLDetourPlanner:
|
|||||||
# (2026-09-02), không còn vá một đoạn 2-4 m vào tuyến cũ.
|
# (2026-09-02), không còn vá một đoạn 2-4 m vào tuyến cũ.
|
||||||
# ► Robot đang đứng yên trong RECOVERING nên một cycle giãn ra không làm sai lệnh nào, nhưng TĂNG
|
# ► Robot đang đứng yên trong RECOVERING nên một cycle giãn ra không làm sai lệnh nào, nhưng TĂNG
|
||||||
# quá thì host không xử lý được cancel/pause trong khoảng đó.
|
# quá thì host không xử lý được cancel/pause trong khoảng đó.
|
||||||
allocated_time: 1.0
|
allocated_time: 2.0
|
||||||
|
|
||||||
# Hệ số nới heuristic của ARA*: nghiệm đầu được phép đắt gấp `initial_epsilon` lần tối ưu, rồi
|
# Hệ số nới heuristic của ARA*: nghiệm đầu được phép đắt gấp `initial_epsilon` lần tối ưu, rồi
|
||||||
# thuật toán siết dần trong thời gian còn lại.
|
# thuật toán siết dần trong thời gian còn lại.
|
||||||
|
|||||||
@@ -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`
|
||||||
|
|||||||
227
docs/LIFECYCLE_BEHAVIOUR_MATRIX.md
Normal file
227
docs/LIFECYCLE_BEHAVIOUR_MATRIX.md
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
# Ma trận hành vi pause / resume / cancel theo từng state — bản cũ và sau plan
|
||||||
|
|
||||||
|
Ngày lập: 2026-09-11. Mục đích: đối chiếu hành vi **đang chạy** (bản cũ) với hành vi **sau plan**
|
||||||
|
`PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md`, từng state một, để soát plan có đi đúng hướng.
|
||||||
|
|
||||||
|
## 0. Phiên bản được gọi là "cũ"
|
||||||
|
|
||||||
|
`pnkx_nav_core` commit `bd026b94c8` (2026-09-09, nhánh `dev_recovery_and_manager_mission`) nạp
|
||||||
|
runtime qua submodule `src/Navigations/Packages/move_base2` ở commit **`180c0e1c`**. Đây cũng là
|
||||||
|
con trỏ `rb_ws/pnkx_nav_core` đang giữ. `move_base2` HEAD hiện tại (`7d00c5a`) chỉ khác `180c0e1c`
|
||||||
|
một commit về `rotate`/`relative_yaw` trong `control_loop.cpp` — **state machine và mọi đường
|
||||||
|
lifecycle giống hệt**. Nên "cũ" dưới đây = code `state_machine.cpp` / `control_loop.cpp` /
|
||||||
|
`navigation_server.cpp` trước các sửa pha 1 (chưa commit) của 2026-09-11. Số dòng trích theo bản cũ.
|
||||||
|
|
||||||
|
Runtime này **không có** `move_base` thế hệ 1 nữa (không có state `CLEARING` thật; `CLEARING` chỉ
|
||||||
|
còn là tên host-facing của `RECOVERING`).
|
||||||
|
|
||||||
|
## 1. Lệnh đi vào lõi như thế nào (cả cũ lẫn mới)
|
||||||
|
|
||||||
|
```
|
||||||
|
host (thread bất kỳ) navigation_cancel() / _pause() / _resume()
|
||||||
|
→ NavigationServer::cancel()/pause()/resume() chỉ ghi cờ dưới data_mutex_, TRẢ VỀ NGAY
|
||||||
|
→ control thread, spinOnce() kế: drainLifecycleRequests() (navigation_server.cpp:1010-1047)
|
||||||
|
cancel thắng mọi thứ; pause và resume: lệnh gọi SAU thắng (mỗi lệnh xoá cờ đối nghịch)
|
||||||
|
→ ControlLoop::requestCancel()/requestPause()/requestResume() đặt cờ một-lần
|
||||||
|
→ ControlLoop::step() → StateMachine::update(input) cờ được tiêu thụ đúng một cycle
|
||||||
|
```
|
||||||
|
|
||||||
|
Thứ tự ưu tiên trong một cycle ở mọi state đang chạy (`STATE_MACHINE.md`):
|
||||||
|
`cancel` → `pause` → goal mới (preempt) → plan mới → phản hồi controller/recovery/action → ngưỡng.
|
||||||
|
|
||||||
|
Độ trễ danh nghĩa: ≤ 1 cycle (33 ms @ 30 Hz). **Độ trễ thật = thời gian control thread đang bị
|
||||||
|
chặn** — quan trọng ở mục 3.4 (detour) và 2.2 (local planner solve dài).
|
||||||
|
|
||||||
|
`cancel()` từ host còn gọi `missionLayer().cancel()` → `MissionManager::cancel()` → xoá hàng đợi,
|
||||||
|
state mission `CANCELLED` **ngay tại lời gọi**, không chờ lõi. `pause()`/`resume()` **không** lan
|
||||||
|
xuống mission layer (cố ý, `navigation_server.cpp:1050-1054`).
|
||||||
|
|
||||||
|
Host nhìn thấy (`NavFeedback.navigation_state`, `toHostState` `navigation_server.cpp:266-298`):
|
||||||
|
|
||||||
|
| Lõi | Host |
|
||||||
|
|---|---|
|
||||||
|
| `kIdle` | `PENDING` (hoặc kết quả đã chốt: `SUCCEEDED`/`ABORTED`/`PREEMPTED`) |
|
||||||
|
| `kPlanning` | `PLANNING` |
|
||||||
|
| `kControlling` | `CONTROLLING` |
|
||||||
|
| `kRecovering` | `CLEARING` |
|
||||||
|
| `kExecutingActions` | `ACTIVE` |
|
||||||
|
| `kPaused` | `PAUSED` |
|
||||||
|
| `kCancelling` | `PREEMPTING` |
|
||||||
|
| `kEmergency` | `EMERGENCY` (2026-09-14; ghi đè từ thread host ngay trong `emergency()`, trước cả khi lõi vào state) |
|
||||||
|
| `kSucceeded` / `kAborted` / `kCancelled` | `SUCCEEDED` / `ABORTED` / `PREEMPTED` (chốt tới yêu cầu kế) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Ma trận theo state
|
||||||
|
|
||||||
|
Quy ước cột: **Cũ** = `180c0e1c`; **Pha 1** = đã code 2026-09-11, chờ build; **Pha 2/3** = trong
|
||||||
|
plan, chưa làm. Ô để trống = không đổi so với cột trái.
|
||||||
|
|
||||||
|
### 2.1 `IDLE` (không có yêu cầu) và các state terminal (`SUCCEEDED`/`ABORTED`/`CANCELLED`)
|
||||||
|
|
||||||
|
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| pause | Lõi bỏ qua (không nhánh nào đọc `pause_requested` ở `kIdle`, `state_machine.cpp:423-431`). Host vẫn thấy `PENDING` | | |
|
||||||
|
| resume | Bỏ qua | | |
|
||||||
|
| cancel | Lõi bỏ qua (`CancelWithoutRequestIsIgnored`). **Nhưng** `missionLayer().cancel()` vẫn xoá hàng đợi mission và đặt `MissionState::CANCELLED` | | |
|
||||||
|
| goal mới | Nhận ngay → `PLANNING` (hoặc `EXECUTING_ACTIONS` nếu chỉ có action) | | |
|
||||||
|
|
||||||
|
Terminal chỉ sống một cycle rồi về `IDLE`; lệnh tới trong cycle đó bị bỏ qua như `IDLE`.
|
||||||
|
|
||||||
|
### 2.2 `PLANNING` — global planner đang lập plan trên thread `planner`
|
||||||
|
|
||||||
|
Bối cảnh plugin: `CustomPlanner` fail 100 % với mission qua REST (`makePlan(start, goal)` không hỗ
|
||||||
|
trợ) → rơi xuống backup `SBPLLatticePlanner`; một lượt SBPL tối đa `allocated_time × 3` (10 s × 3
|
||||||
|
với cây config trên máy chạy log). `PlannerRunner::cancelPlan()` chỉ đặt `discard_`
|
||||||
|
(`planner_runner.cpp:466-477`), **không cắt được** `makePlan` đang chạy.
|
||||||
|
|
||||||
|
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **pause** | `stop_planner` → `cancelPlan()` (chỉ discard, SBPL chạy tiếp) → `PAUSED`, `state_before_pause_ = kPlanning` (`:441-446`). Lệnh 0 tức thì. Host: `PAUSED` | | Pha 2: `cancelPlan()` → `preempt()` → SBPL thoát trong vài ms |
|
||||||
|
| **resume** (từ pause ở đây) | → `PLANNING`, `start_planner` (`:948-952`). `startPlan()` bị từ chối vì thread còn bận → control loop dịch thành **`kFailed`** (`control_loop.cpp:1361-1372`) → `max_planning_retries: 0` → `RECOVERING(planning_failed)` ngay → `wait` → `clear` → **`ABORTED`** nếu thread còn bận quá ~11 s (cây dev) / ~27 s (máy log). **Cùng bug với cancel** | `startPlan()` từ chối khi `isPlanning()` → **`kBusy`**: giữ `PLANNING`, không đếm retry, thử lại mỗi cycle, log throttle 5 s. `planner_patience` vẫn là trần | Pha 2: thread đã rảnh từ lúc pause → `startPlan()` OK ngay |
|
||||||
|
| **cancel** | `stop_planner` (discard) → `CANCELLING` (`:435-439`) → cycle kế `robot_stopped` (lệnh = 0) → **`CANCELLED` sau 33 ms** trong khi SBPL còn chạy nhiều giây. Host thấy `PREEMPTED`, gửi goal kế → goal kế `kFailed` → `ABORTED` (log `robot_app.log` 893.444→896.911) | `CANCELLING` giữ tới khi **quiescent**: lệnh/odom = 0 **và** `!isPlanning()` **và** action terminal; trần `settle_timeout` 2 s, quá trần vẫn `CANCELLED` + `log_error`. Host thấy `PREEMPTING` suốt lúc chờ. Goal kế gửi sớm → `kBusy`, không abort | Pha 2: SBPL thoát trong ms → `CANCELLED` sau 1–2 cycle, lần này là thật |
|
||||||
|
| **goal mới** (preempt) | `preemptIfRequested` (`:450`): `stop_planner` (discard), báo `PREEMPTED` cho goal cũ, nhận goal mới → `PLANNING` → `startPlan()` từ chối → `kFailed` → như resume. **`MissionManager::submit()` tự huỷ mission đang chạy** nên host không cần cancel vẫn dính | `kBusy` → chờ thread rảnh rồi lập plan | Pha 2: thread rảnh ngay |
|
||||||
|
|
||||||
|
### 2.3 `CONTROLLING` — local planner phát lệnh mỗi cycle
|
||||||
|
|
||||||
|
Bối cảnh plugin: local planner (`Priest`, `Hybrid`, `HybridDocking`) chạy **đồng bộ** trên control
|
||||||
|
thread mỗi cycle (`computeVelocityCommands`); Priest solve 30–48 ms/cycle 33 ms. Không có
|
||||||
|
`pause()/resume()/reset()` trong `robot_nav_core2::LocalPlanner`. Replan nền (`planner_frequency`)
|
||||||
|
có thể có một lượt đang bay trên thread planner.
|
||||||
|
|
||||||
|
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **pause** | `stop_planner` (discard lượt replan nền nếu có) → `PAUSED`, `state_before_pause_ = kControlling` (`:518-523`). Controller **không được gọi nữa**; arbiter phát **0 tức thì, không ramp** (`velocity_arbiter.cpp:256-266`). Trạng thái nội bộ của plugin (warm-start, slew, latch) đóng băng nguyên trạng. Host: `PAUSED` | | |
|
||||||
|
| **resume** | → `CONTROLLING` với `run_controller` (`:938-942`), **không `setPlan` lại**, không hook nào cho plugin. Đồng hồ `controller_patience`/`oscillation` gieo lại. Plugin bám tiếp với warm-start của lúc robot còn chạy 0.4 m/s; arbiter ramp từ 0 theo `max_accel_x` nên không giật, nhưng plugin có thể tính infeasible vài cycle. Nếu robot bị đẩy đi trong lúc pause thì plan cũ lỗi thời | **(b) đang code:** thêm `apply_plan` → `setPlan(plan cũ)` → Priest reset `core_`, warm, latch, slew theo pose hiện tại (`priest_controller.cpp:534-553`) rồi bám tiếp | **(a) đề xuất, chưa chốt:** resume → `PLANNING`, lập plan **mới** từ pose hiện tại → `setPlan(plan mới)` → `CONTROLLING`. Một lượt planner (0.3–4 s) đổi lấy plan luôn khớp vị trí thật; đồng nhất với resume từ `PLANNING`/`RECOVERING` |
|
||||||
|
| **cancel** | `stop_planner` → `CANCELLING` (`:512-516`) → lệnh 0 tức thì → cycle kế `CANCELLED`. `robot_stopped` lấy từ **lệnh đã phát** (`control_loop.cpp:951`), bánh xe còn lăn theo giảm tốc của driver. Host thấy `PREEMPTED` khi robot còn trượt | `robot_stopped` ưu tiên **odom** (`stopped_measured_*_eps` 0.02): `CANCELLING` giữ tới khi bánh xe đứng thật (trần 2 s). Replan nền còn bay → `!isPlanning()` cũng phải chờ | Pha 2: replan nền bị preempt ngay |
|
||||||
|
| **goal mới** | preempt: `stop_planner`, `PREEMPTED` cho goal cũ, → `PLANNING` goal mới. Nếu replan nền đang bay → `startPlan()` từ chối → `kFailed` → nguy cơ như 2.2 | `kBusy` | Pha 2 |
|
||||||
|
| Local planner đang solve (30–48 ms) khi lệnh tới | Lệnh chờ solve xong (control thread bận) — trễ ≤ 1 cycle thêm | | |
|
||||||
|
|
||||||
|
### 2.4 `RECOVERING` — behavior được tick từ control thread
|
||||||
|
|
||||||
|
Hai họ behavior khác nhau về mức độ dừng được:
|
||||||
|
|
||||||
|
**(i) `wait`, `clear`, `rotate`, `back_up`** — tick ngắn, không chặn control thread.
|
||||||
|
|
||||||
|
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **pause** | `cancel_recovery` → `RecoveryRunner::cancel()` → `RecoveryBehavior::cancel()` **chỉ đặt `cancel_requested_`** (`recovery_behavior.cpp:169-172`); `onCancel()` không bao giờ chạy (tick kế không tới — `recovery_runner.cpp:492`). Nguồn vận tốc `kNone` → arbiter 0 tức thì. Recovery **bị huỷ**, `state_before_pause_ = kPlanning` (`:713-720`) — cố ý: behavior dead-reckon theo thời gian, không được để dở qua quãng dừng | | Pha 2: `cancel()` gọi thêm hook đồng bộ `onCancelRequested()` (no-op với họ này) |
|
||||||
|
| **resume** | → `PLANNING`, lập plan lại từ đầu (`:948-952`). Cursor route giữ nguyên | (nếu planner thread bận vì lượt trước — `kBusy`) | |
|
||||||
|
| **cancel** | `cancel_recovery` → `CANCELLING` (`:707-711`) → cycle kế `CANCELLED`. `rotate` 0.4 rad/s → 0 trong 33 ms (12 rad/s² lệnh), `back_up` 0.1 m/s → 0 (3 m/s²). Doc `onCancel()` hứa "plugin ramp về 0" nhưng không chạy — **chọn giữ 0 tức thì (quyết định A)**, sửa doc ở pha 2 | odom phải về 0 mới `CANCELLED` | |
|
||||||
|
| **goal mới** | preempt: `cancel_recovery` + `stop_planner`, `PREEMPTED` cho goal cũ → `PLANNING` | | |
|
||||||
|
|
||||||
|
**(ii) `detour_path` (`DetourPathRecovery`, sbpl_recovery)** — `makePlan` SBPL **đồng bộ trong
|
||||||
|
`onUpdate`** trên control thread (`detour_path_recovery.cpp:451-501`), `allocated_time 0.4` × tới
|
||||||
|
3 lượt replan = **1.2 s treo/tick**, lặp `attempts_per_run 3`. Route dùng nó: `controlling_failed`,
|
||||||
|
`path_blocked`, `off_path`, `collision` (+ `oscillation` cây dev).
|
||||||
|
|
||||||
|
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **pause / cancel / goal mới** tới trong lúc `makePlan` đang chạy | **Không được xử lý** cho tới khi `makePlan` trả về: `spinOnce()` không chạy → `drainLifecycleRequests()` không chạy → cờ nằm trong `cancel_requested_` tới 1.2 s. Robot đứng yên (kPath → `kNone`, lệnh 0 đã phát trước đó) nên không chạy tự do, nhưng **cancel trễ tới 1.2 s** | (không đổi — pha 1 không chạm) | Pha 2: `makePlan` sang worker thread, `onUpdate` chỉ poll → control thread không bao giờ kẹt; `onCancelRequested()` → `planner_->preempt()` → worker thoát trong ms. Sau đó hành vi như (i) |
|
||||||
|
| sau khi `makePlan` trả về | như (i) | | |
|
||||||
|
|
||||||
|
### 2.5 `EXECUTING_ACTIONS` — action của mission (D8), robot đứng yên
|
||||||
|
|
||||||
|
Bối cảnh: handler tick từ control thread, không block, tự timeout theo `elapsed = now - started_at_`
|
||||||
|
(wall). `ActionHandler` **không có** `pause()/resume()`; `cancel()` trả `void`;
|
||||||
|
`ActionRunner::cancel()` gọi `handler->cancel()` rồi **quên handler ngay** (`action_runner.cpp:159-166`).
|
||||||
|
|
||||||
|
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **pause** | `PAUSED`, **không huỷ action** (`:853-862`) — cố ý: action thiết bị không idempotent. Chỉ ngừng tick. Host: `PAUSED`. **Nhưng** đồng hồ `timeout` của handler vẫn chạy theo wall time | | Pha 3: `ActionHandler::pause(now)` → handler ghi `paused_at_` |
|
||||||
|
| **resume** | → `EXECUTING_ACTIONS`, tick tiếp đúng action đó, **không `start()` lại** (`:943-947`); `action_started_at_` (cho `action_patience`) gieo lại. Handler thấy `elapsed` gồm cả quãng dừng → pause 30 s giữa `detect_pallet` (`timeout 15 s`) → tick đầu `kFailed` → **`ABORTED` thẳng, không qua recovery**, `clear_queue_on_failure` xoá cả order | | Pha 3: `resume(now)` → `started_at_ += now - paused_at_` → không tính thời gian đứng |
|
||||||
|
| **cancel** | `cancel_action` → `ActionRunner::cancel()` → `handler->cancel()` + `active_ = nullptr` → `CANCELLING` (`:847-851`) → cycle kế `CANCELLED`. Với 5 handler hiện có (perception/no-op) là đúng. Handler thiết bị tương lai: `PREEMPTED` báo trong lúc thiết bị còn đang về vị trí an toàn | `action_terminal` control loop truyền `true` — với port hiện tại là giá trị đúng duy nhất (runner đã quên handler). State machine đã sẵn nhánh `tick_action` khi `!action_terminal` | Pha 3: `ActionStatus::kCancelled`; runner giữ handler, tick tới khi terminal; control loop truyền `action_terminal` thật; `CANCELLING` chờ nó |
|
||||||
|
| **goal mới** | preempt: `cancel_action`, `PREEMPTED` cho mission cũ → `PLANNING` mission mới | | |
|
||||||
|
|
||||||
|
### 2.6 `PAUSED`
|
||||||
|
|
||||||
|
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| pause (lần nữa) | Bỏ qua | | |
|
||||||
|
| **resume** | Về `state_before_pause_`: `kControlling` → `CONTROLLING` (2.3); `kExecutingActions` → tick tiếp (2.5); `kPlanning` (gồm cả pause từ `RECOVERING`) → `PLANNING` + `start_planner` (`:927-955`). Mọi đồng hồ kiên nhẫn gieo lại | 2.3 (b) hoặc (a) | |
|
||||||
|
| **cancel** | → `CANCELLING` (`:922-925`) → cycle kế `CANCELLED`. Nếu pause tới từ `PLANNING`, thread planner có thể còn bận lượt cũ — `CANCELLED` vẫn báo ngay (nói dối) | `CANCELLING` chờ `!isPlanning()` (test `CancelFromPausedAlsoWaitsForThePlannerThread`) | |
|
||||||
|
| **goal mới** | preempt được từ `PAUSED` (`:917-920`): `stop_planner`/`cancel_recovery`/`cancel_action` theo state trước đó, `PREEMPTED` cho goal cũ → `PLANNING` goal mới (không cần resume). Thread bận → `kFailed` | `kBusy` | |
|
||||||
|
|
||||||
|
### 2.7 `CANCELLING`
|
||||||
|
|
||||||
|
| Lệnh | Cũ | Pha 1 | Pha 2/3 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| pause / resume | Bỏ qua (không nhánh nào đọc) | | |
|
||||||
|
| cancel (lần nữa) | Bỏ qua | | |
|
||||||
|
| **goal mới** | **Không preempt** (`kCancelling` không gọi `preemptIfRequested`): yêu cầu nằm chờ ở `pending_request_`, được nhận khi về `IDLE` sau `CANCELLED` | Chờ lâu hơn (tới khi quiescent) rồi mới được nhận → sang `PLANNING` với thread đã rảnh | |
|
||||||
|
| kết thúc | `robot_stopped` (lệnh = 0) → `CANCELLED` sau 1 cycle | quiescent hoặc `settle_timeout` | |
|
||||||
|
|
||||||
|
### 2.9 `EMERGENCY` — mức có chốt (2026-09-14)
|
||||||
|
|
||||||
|
Đường vào khác ba lệnh kia ở bước đầu:
|
||||||
|
|
||||||
|
```
|
||||||
|
host (thread bất kỳ) navigation_emergency()
|
||||||
|
→ NavigationServer::emergency() emergency_latched_ = true → getTwist() = 0, getFeedback() = EMERGENCY NGAY
|
||||||
|
+ cờ dưới data_mutex_, TRẢ VỀ
|
||||||
|
→ control thread, spinOnce() kế: drainLifecycleRequests() emergency xét TRƯỚC cancel
|
||||||
|
→ ControlLoop::requestEmergency() đặt MỨC emergency_, vứt pending_request_
|
||||||
|
→ StateMachine::update() in.emergency → kEmergency (trước switch, mọi state)
|
||||||
|
→ missionLayer().emergency() out-of-band: xoá hàng đợi, cancelActive, manager EMERGENCY
|
||||||
|
```
|
||||||
|
|
||||||
|
| Lệnh tới ở state | Hành vi |
|
||||||
|
|---|---|
|
||||||
|
| `IDLE` (có hoặc không goal chờ) | → `EMERGENCY`, không báo outcome; goal chờ bị **vứt** ở ControlLoop |
|
||||||
|
| `PLANNING` | `stop_planner` (preempt lượt đang chạy) → `EMERGENCY`, outcome `CANCELLED` một lần. Không chờ thread rảnh — `EMERGENCY` không có nghĩa "xong" |
|
||||||
|
| `CONTROLLING` | lệnh 0 tức thì (kNone, không ramp) → `EMERGENCY`, outcome `CANCELLED` |
|
||||||
|
| `RECOVERING` | `cancel_recovery` + `stop_planner` → `EMERGENCY`, outcome `CANCELLED` |
|
||||||
|
| `EXECUTING_ACTIONS` | `cancel_action` → `EMERGENCY`, outcome `CANCELLED`; `tick_action` tiếp tới khi handler trả terminal (pha 3) |
|
||||||
|
| `PAUSING` / `PAUSED` | → `EMERGENCY`; nếu pause đến từ action thì `cancel_action` (tạm dừng không huỷ action, dừng khẩn thì phải huỷ); outcome `CANCELLED` |
|
||||||
|
| `CANCELLING` | → `EMERGENCY`; outcome `CANCELLED` (chưa báo vì chưa tới `CANCELLED`); không phát `cancel_action` lần hai |
|
||||||
|
| `EMERGENCY` (lần nữa) | idempotent; ở NavigationServer chỉ làm mới mốc ân hạn stamp |
|
||||||
|
|
||||||
|
Trong lúc chốt: `pause`/`resume`/`cancel` bị bỏ qua; `moveTo`/`moveTo(order)`/`executeInstantActions`
|
||||||
|
trả **false** ngay tại NavigationServer (trước mission layer, để host nhận từ chối đồng bộ) với
|
||||||
|
`lastRejectReason()` = "emergency stop latched — call clearEmergency() first", `log_warning_throttle` 1 s.
|
||||||
|
|
||||||
|
`clearEmergency()`: cờ atomic hạ ngay (host thấy `PENDING` sau ≤ 1 cycle), control thread về `IDLE`
|
||||||
|
ở cycle kế, **không nhận goal trong cùng cycle**; mission layer `CLEAR_EMERGENCY`, hàng đợi trống.
|
||||||
|
Không gì tự chạy lại. `clear` rồi `emergency` trong cùng cửa sổ: lệnh sau thắng.
|
||||||
|
|
||||||
|
`getTwist()` trong lúc chốt: vận tốc luôn 0; stamp tươi (đồng hồ thread host) trong `kStopGraceSeconds`
|
||||||
|
= 0.5 s rồi đóng băng — host publish một loạt 0 tường minh rồi nhường `/cmd_vel`.
|
||||||
|
|
||||||
|
### 2.8 Profile `docking` / `rotate` / `go_straight`
|
||||||
|
|
||||||
|
Cùng state machine, chỉ khác planner được nạp (`DockPlanner` + `HybridDockingLocalPlanner`,
|
||||||
|
`TwoPointsPlanner`). Mọi ô trên áp dụng nguyên. Riêng resume từ `CONTROLLING` với
|
||||||
|
`HybridDockingLocalPlanner`: chưa đọc `setPlan` của nó — với (a) sẽ là `DockPlanner` lập lại từ
|
||||||
|
pose hiện tại tới marker, với (b) là `setPlan(plan cũ)`; cả hai cần chạy thử.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Điểm plan cố ý khác bản cũ — soát ở đây
|
||||||
|
|
||||||
|
| # | Hành vi cũ | Plan đổi thành | Lý do | Pha |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | `startPlan()` từ chối = `kFailed` | `kBusy` khi `isPlanning()` | "bận" ≠ "hỏng"; gốc của ABORTED oan | 1 (đã code) |
|
||||||
|
| 2 | `CANCELLED` sau 1 cycle khi lệnh = 0 | `CANCELLING` chờ quiescent (odom = 0, planner idle, action terminal), trần `settle_timeout` | host đọc `PREEMPTED` là "xong" | 1 (đã code) |
|
||||||
|
| 3 | `robot_stopped` từ lệnh | từ odom, lùi về lệnh khi không có odom; `eps = 0` = tắt | bánh xe còn lăn sau lệnh 0 | 1 (đã code) |
|
||||||
|
| 4 | resume từ `CONTROLLING` không `setPlan` | (b) `setPlan(plan cũ)` — đã code; **hoặc (a) về `PLANNING` lập plan mới — chờ chốt** | plugin reset warm-start; (a) còn khớp pose thật sau pause dài | 1 |
|
||||||
|
| 5 | `cancelPlan()` chỉ discard | `Preemptable::preempt()` → SBPL thoát trong ms | "dừng ở đó" thật | 2 |
|
||||||
|
| 6 | `onCancel()` recovery là dead code; detour treo control thread | `onCancelRequested()` đồng bộ; detour worker thread + preempt | cancel/pause tới được trong lúc detour | 2 |
|
||||||
|
| 7 | Cancel = 0 tức thì, không ramp | **giữ nguyên** (quyết định A); sửa doc `onCancel()` | đúng nghĩa "dừng hết luôn"; giảm tốc là việc của driver | 2 (doc) |
|
||||||
|
| 8 | Action: pause không báo handler; cancel không handshake | `pause/resume(now)` + `kCancelled` | pause dài → ABORTED oan; thiết bị tương lai | 3 |
|
||||||
|
| 9 | Plugin `.so` cũ nạp vào runtime mới → crash vtable | ABI guard `_abi` symbol, registry từ chối | đổi vtable ở 2 và 3 | 2, 3 |
|
||||||
|
| 10 | `MissionState::CANCELLED` ngay tại lời gọi | **giữ nguyên**; host nhìn `NavigationState::PREEMPTING` (đã có sẵn) | C API không lộ `MissionState`; không thêm enum | 1 |
|
||||||
|
|
||||||
|
Không đổi: pause huỷ recovery (2.4), pause đóng băng action (2.5), cancel từ mọi state về
|
||||||
|
`CANCELLING`, preempt từ mọi state đang chạy trừ `CANCELLING`, thứ tự ưu tiên cancel > pause > goal
|
||||||
|
mới, `pause`/`resume` không lan xuống mission layer, lệnh 0 tức thì.
|
||||||
|
|
||||||
|
## 4. Yêu cầu của bạn đối chiếu
|
||||||
|
|
||||||
|
| Yêu cầu | Trạng thái (cập nhật 2026-09-12) |
|
||||||
|
|---|---|
|
||||||
|
| Đang planning / setPlan / recovery / action → cancel hoặc pause **dừng ở đó** | setPlan, recovery (i), action: có sẵn. Planning: **pha 2 xong, đo runtime** — cancel/pause @ PLANNING → `preempted after` +0.03 ms, `CANCELLED`/`PAUSED` trong 1–2 tick (R1, R2, R4). Detour: code + unit test xong, **runtime chưa chạy** |
|
||||||
|
| Pause rồi resume → **set plan lại và gọi planning lại** | Resume từ `PLANNING`: gọi planning lại — đo R2 (`PLANNING: resume planning` +27 ms, SBPL chạy lại). Resume từ `CONTROLLING`: **đã chốt (b)** `setPlan(plan cũ)` — đo R3 (`setPlan: 1423 poses`, Priest reseed từ vận tốc đo, không giật) |
|
||||||
|
| Local planner chạy theo chu kỳ → chỉ chạy tiếp | Đo R3: pause → lệnh 0 tức thì, `PAUSED` sau khi odom < 0.02 m/s (538 ms từ 0.115 m/s); resume → `setPlan` + chạy tiếp cùng cycle |
|
||||||
|
| Báo đúng: `CANCELLED`/`PAUSED` chỉ khi mọi thứ thật sự im | Đo R1–R5: mọi `CANCELLED`/`PAUSED` đều kèm `planner=idle controller=idle recovery=idle` + robot đứng theo odom; R5 cancel lúc còn `PAUSING` (bánh chưa dừng) → `CANCELLING: cancelled while pausing` → `CANCELLED` chỉ khi đứng (+250 ms) |
|
||||||
|
|
||||||
|
Bảng số đo đầy đủ: `PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md` mục 6, "Kết quả runtime đã chạy".
|
||||||
@@ -11,18 +11,21 @@ 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()` → `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) |
|
||||||
| `PAUSED` | không ai (0) | `pause()` từ `PLANNING`/`CONTROLLING`/`RECOVERING`/`EXECUTING_ACTIONS` | `resume()` → về state trước đó; `cancel()` → `CANCELLING` |
|
| `PAUSING` | không ai (0) | `pause()` từ `PLANNING`/`CONTROLLING`/`RECOVERING`/`EXECUTING_ACTIONS` (2026-09-11). Ngay cycle vào: `stop_planner` / `cancel_recovery` / (pha 3) `pause_action`, lệnh = 0 | **quiescent** (`robot_stopped` **và** `!planner_busy` **và** `!recovery_busy` **và** `action_terminal`) → `PAUSED`; quá `settle_timeout` → `PAUSED` + cờ `settle_timed_out`; `settle_timeout = 0` → chỉ chờ `robot_stopped`. `resume()` → về state trước (chưa kịp dừng gì cũng không sao); `cancel()` → `CANCELLING`; goal mới → preempt như `PAUSED`. Host **không** thấy `PAUSED` ở đây — thấy tên state trước + `feed_back_str` "pausing…" |
|
||||||
| `CANCELLING` | không ai (0) | `cancel()` từ mọi state đang chạy | robot đã dừng → `CANCELLED` |
|
| `PAUSED` | không ai (0) | `PAUSING` đã im hẳn | `resume()` → về state trước đó (về `CONTROLLING` thì kèm `apply_plan`: nạp lại plan để local planner reset warm-start — 2026-09-11, phương án (b) đã chốt); `cancel()` → `CANCELLING` |
|
||||||
|
| `CANCELLING` | không ai (0) | `cancel()` từ mọi state đang chạy | **quiescent** (2026-09-11): `robot_stopped` **và** `!planner_busy` **và** `!recovery_busy` **và** `action_terminal` → `CANCELLED`; quá `settle_timeout` → `CANCELLED` + cờ `settle_timed_out` (bên gọi log lỗi). `settle_timeout = 0` → chỉ chờ `robot_stopped` như trước. Chừng nào `!action_terminal` thì `tick_action` để handler dừng thiết bị an toàn, không cấp vận tốc |
|
||||||
|
| `EMERGENCY` | không ai (0) | host giữ dừng khẩn (`emergency()`, 2026-09-14) — từ **mọi** state kể cả `IDLE`. Cycle vào: `stop_planner`; `cancel_recovery` nếu đang `RECOVERING`; `cancel_action` nếu có action đang chạy hoặc đang tạm dừng; chặng đang chạy (state ≠ `IDLE`) báo `CANCELLED` **một lần**. Lệnh = 0 tức thì | **chỉ** khi host gỡ chốt (`clearEmergency()`) → `IDLE`, không nhận goal trong cùng cycle. Trong lúc chốt: `pause`/`resume`/`cancel`/goal mới đều bị bỏ qua, `tick_action` chừng nào `!action_terminal` (handler thiết bị về vị trí an toàn). Host thấy `EMERGENCY` — không phải `PREEMPTED`, và không phải "xong" |
|
||||||
| `SUCCEEDED` / `ABORTED` / `CANCELLED` | không ai (0) | như trên | terminal; báo kết quả rồi về `IDLE` ở cycle kế tiếp |
|
| `SUCCEEDED` / `ABORTED` / `CANCELLED` | không ai (0) | như trên | terminal; báo kết quả rồi về `IDLE` ở cycle kế tiếp |
|
||||||
|
|
||||||
## Thứ tự ưu tiên trong một cycle
|
## Thứ tự ưu tiên trong một cycle
|
||||||
|
|
||||||
Ở mọi state đang chạy, sự kiện được xét theo đúng thứ tự sau. Thứ tự này là một phần của contract:
|
Ở mọi state đang chạy, sự kiện được xét theo đúng thứ tự sau. Thứ tự này là một phần của contract:
|
||||||
|
|
||||||
|
0. `emergency` (mức, không phải xung — xét trước `switch`, ở **mọi** state kể cả `IDLE`; 2026-09-14)
|
||||||
1. `cancel_requested`
|
1. `cancel_requested`
|
||||||
2. `pause_requested`
|
2. `pause_requested`
|
||||||
3. plan mới sẵn sàng
|
3. plan mới sẵn sàng
|
||||||
@@ -35,7 +38,7 @@ Khi cần đổi hành vi: sửa tài liệu này trước, sửa test, rồi m
|
|||||||
một lời gọi blocking. Bắt buộc như vậy vì recovery thế hệ 2 trả kết quả từng tick và có thể phát
|
một lời gọi blocking. Bắt buộc như vậy vì recovery thế hệ 2 trả kết quả từng tick và có thể phát
|
||||||
vận tốc — nghĩa là quyền phát cmd_vel phải chuyển tay từ local planner sang recovery và ngược lại.
|
vận tốc — nghĩa là quyền phát cmd_vel phải chuyển tay từ local planner sang recovery và ngược lại.
|
||||||
|
|
||||||
2. **`PAUSED` và `CANCELLING` là state thật**, không phải cờ đọc rải rác trong vòng lặp. Đường huỷ ở
|
2. **`PAUSING`/`PAUSED` và `CANCELLING` là state thật**, không phải cờ đọc rải rác trong vòng lặp. Đường huỷ ở
|
||||||
bản cũ được viết hai lần, ở nhánh `try` và nhánh `catch`, gần 80 dòng giống hệt nhau.
|
bản cũ được viết hai lần, ở nhánh `try` và nhánh `catch`, gần 80 dòng giống hệt nhau.
|
||||||
|
|
||||||
3. **`SUCCEEDED`/`ABORTED`/`CANCELLED` là state**, không phải `return` giữa hàm. Đây là cơ chế giữ
|
3. **`SUCCEEDED`/`ABORTED`/`CANCELLED` là state**, không phải `return` giữa hàm. Đây là cơ chế giữ
|
||||||
@@ -100,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`) để
|
||||||
@@ -188,17 +195,66 @@ Bốn tính chất sau được chốt lại ở cuối mỗi lần chuyển sta
|
|||||||
|
|
||||||
1. Mỗi cycle có **đúng một** nguồn vận tốc.
|
1. Mỗi cycle có **đúng một** nguồn vận tốc.
|
||||||
2. `run_controller`, `tick_recovery` và `tick_action` đôi một không bao giờ cùng bật.
|
2. `run_controller`, `tick_recovery` và `tick_action` đôi một không bao giờ cùng bật.
|
||||||
3. Ở state phải dừng (mọi state trừ `CONTROLLING` và `RECOVERING` — gồm cả `EXECUTING_ACTIONS`),
|
3. Ở state phải dừng (mọi state trừ `CONTROLLING` và `RECOVERING` — gồm cả `EXECUTING_ACTIONS` và
|
||||||
nguồn vận tốc luôn là `kNone`.
|
`EMERGENCY`), nguồn vận tốc luôn là `kNone`.
|
||||||
4. `report_outcome` bật đúng một lần cho mỗi yêu cầu — kể cả yêu cầu có action: chỉ báo sau action
|
4. `report_outcome` bật đúng một lần cho mỗi yêu cầu — kể cả yêu cầu có action: chỉ báo sau action
|
||||||
cuối (D8).
|
cuối (D8).
|
||||||
|
|
||||||
## Vì sao `CANCELLING` luôn kết thúc
|
## Vì sao `CANCELLING` luôn kết thúc — và vì sao nó phải chờ (2026-09-11)
|
||||||
|
|
||||||
`CANCELLING` chờ `robot_stopped`. Vì nguồn vận tốc ở state này đã là `kNone` và bộ trọng tài phát
|
Nguồn vận tốc ở state này là `kNone`, bộ trọng tài phát lệnh 0 **tức thì, không ramp**
|
||||||
lệnh 0 tức thì, `robot_stopped` thành true ngay ở cycle kế tiếp. Do đó state này kết thúc sau hữu hạn
|
(`VelocityArbiter::arbitrate`, ba lý do ghi tại chỗ; giảm tốc theo động học là việc của driver bánh
|
||||||
cycle mà không cần thêm tham số timeout nào.
|
xe). Lệnh 0 là điều kiện cần. Trước 2026-09-11 nó cũng là điều kiện đủ, và đó là một lời nói dối với
|
||||||
|
host: `CANCELLED`/`PREEMPTED` được báo trong lúc thread global planner còn chạy lượt `makePlan` đã
|
||||||
|
huỷ (SBPL chạy tới hết `allocated_time`, `cancelPlan()` chỉ đặt cờ vứt kết quả). Host đọc PREEMPTED
|
||||||
|
là "xong, gửi goal kế được"; goal kế bị `startPlan()` từ chối vì thread còn bận, control loop dịch
|
||||||
|
thành `kFailed`, `max_planning_retries: 0` leo thang ngay → `ABORTED` sau 3 s dù chưa lập plan lần
|
||||||
|
nào (`robot_app.log` 2026-09-11, mission 3 → 4).
|
||||||
|
|
||||||
Ở bước nối dây sau, `robot_stopped` nên được lấy từ vận tốc **đo được** (odometry) thay vì từ lệnh
|
Từ 2026-09-11 `CANCELLING` rời đi khi **quiescent** — ba điều kiện cùng đúng:
|
||||||
đã phát. Đó là lý do nó là một trường dữ liệu vào của state machine chứ không phải thứ state machine
|
|
||||||
tự tính.
|
| Điều kiện | Nguồn | Nghĩa |
|
||||||
|
|---|---|---|
|
||||||
|
| `robot_stopped` | control loop: odom nếu có (`stopped_measured_*_eps`), không thì lệnh đã phát | bánh xe đã đứng, không chỉ lệnh = 0 |
|
||||||
|
| `!planner_busy` | `PlannerPort::isPlanning()` **hoặc** hàng `kGlobalPlanner` của `ComponentStatusBoard` ≠ idle | thread planner rảnh, kể cả lượt đã huỷ |
|
||||||
|
| `!recovery_busy` | hàng `kRecovery` của bảng (RecoveryRunner ghi; detour worker pha 2) | behavior và worker của nó đã thoát |
|
||||||
|
| `action_terminal` | hàng `kAction` của bảng: idle hoặc paused (pha 3 mới có handshake; không có bảng → `true`) | handler đã dừng thiết bị xong |
|
||||||
|
|
||||||
|
`ComponentStatusBoard` (`core/component_status.h`, 2026-09-11) là nguồn sự thật: mỗi runner tự ghi
|
||||||
|
hàng của mình (busy / stopping / idle / paused / hung) bằng atomic từ thread của nó; control loop
|
||||||
|
ghi hàng `kLocalPlanner` (bọc quanh `computeVelocityCommands`) và heartbeat `kControlLoop` cuối
|
||||||
|
mỗi `step()`. Watchdog (pha 4) đọc bảng từ thread riêng để bắt thành phần treo — kể cả chính
|
||||||
|
control thread. Cùng bộ điều kiện dùng cho `PAUSING`.
|
||||||
|
|
||||||
|
`settle_timeout` [s] là trần: quá thì vẫn `CANCELLED` nhưng output mang
|
||||||
|
`settle_timed_out` đúng một cycle và control loop **log lỗi, không có khoá tắt** — có plugin
|
||||||
|
không cắt được lượt đang chạy hoặc odom không về 0. Đặt 0 = hành vi cũ. Host nhìn thấy đúng cặp
|
||||||
|
`PREEMPTING`/`PREEMPTED` đã có trong `move_base_core::State`; chỉ thời điểm đổi.
|
||||||
|
|
||||||
|
Hệ quả cho tầng trên: `startPlan()` bị từ chối trong lúc `isPlanning()` là **`kBusy`, không phải
|
||||||
|
`kFailed`** (`control_loop.cpp`, cùng ngày). `kBusy` giữ `PLANNING`, không tăng `planning_retries_`;
|
||||||
|
`planner_patience` vẫn là trần cho "bận quá lâu" — một plugin treo thật vẫn bị phát hiện.
|
||||||
|
|
||||||
|
## Vì sao `EMERGENCY` là mức, không phải xung — và vì sao nó không chờ gì (2026-09-14)
|
||||||
|
|
||||||
|
`cancel`/`pause`/`resume` là **xung**: cờ một-lần, tiêu thụ đúng cycle nó tới. Dừng khẩn là **mức**
|
||||||
|
(`StateMachineInput::emergency`): chừng nào host còn giữ thì cycle nào cũng ở `EMERGENCY`, kể cả
|
||||||
|
cycle `IDLE` có goal chờ. Một xung chỉ thắng được đúng cycle nó tới; dừng khẩn phải thắng cho tới khi
|
||||||
|
người vận hành gỡ chốt — nếu không, goal kế tới sau một cycle là robot chạy lại giữa tình huống khẩn.
|
||||||
|
|
||||||
|
Xét **trước `switch`**, trước cả `cancel`, vì nó áp cho mọi state như nhau và không state nào được
|
||||||
|
quyền xử lý gì khác khi nó đang bật. Hai đường về sớm của `update()` (đang chốt / vừa gỡ chốt) vẫn đi
|
||||||
|
qua `applyInvariants()` — hàng rào `mustBeStopped` không có ngoại lệ.
|
||||||
|
|
||||||
|
Khác `CANCELLING`, `EMERGENCY` **không chờ quiescence** để báo ra: `EMERGENCY` không có nghĩa "đã
|
||||||
|
xong, gửi tiếp được" nên không có gì để nói dối. Thread planner còn bận lượt đã cắt thì goal đầu tiên
|
||||||
|
sau khi gỡ chốt đi vào `PLANNING` với `kBusy` và tự chờ — một cơ chế, không hai.
|
||||||
|
|
||||||
|
Outcome của chặng bị cắt được báo **đúng một lần, ở cycle vào** (`report_outcome`, `kCancelled`),
|
||||||
|
không qua state terminal nào: `EMERGENCY` là nơi ở lại. `ControlLoop` xoá yêu cầu hiện hành như với
|
||||||
|
mọi outcome khác và vứt luôn yêu cầu đang chờ — mission layer đã xoá hàng đợi, nhưng một chặng đã
|
||||||
|
pump xuống loop mà chưa kịp accept thì chỉ loop biết.
|
||||||
|
|
||||||
|
Đường host-thread: `NavigationServer` còn giữ một cờ atomic riêng đọc ở `getTwist()`/`getFeedback()`
|
||||||
|
để host thấy 0/`EMERGENCY` **trước khi lời gọi trả về**, không chờ control thread — xem
|
||||||
|
`THREADING.md`. State machine không biết cờ đó; nó chỉ nhận mức qua `ControlLoop::requestEmergency()`.
|
||||||
|
|||||||
@@ -4,8 +4,10 @@
|
|||||||
|
|
||||||
| Thread | Sở hữu | Chu kỳ | Ghi chú |
|
| Thread | Sở hữu | Chu kỳ | Ghi chú |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `control` | state machine, bộ trọng tài vận tốc, controller, recovery, **cmd_vel** | `controller_frequency` | **Thread duy nhất được phát cmd_vel.** Toàn bộ `ControlLoop::step()` chạy ở đây |
|
| `control` | state machine, bộ trọng tài vận tốc, controller, recovery, action, **cmd_vel** | `controller_frequency` | **Thread duy nhất được phát cmd_vel.** Toàn bộ `ControlLoop::step()` chạy ở đây; heartbeat `kControlLoop` cuối mỗi step |
|
||||||
| `planner` | global planner, bộ đệm plan | `planner_frequency` hoặc theo biến điều kiện | *Chưa có ở trạng thái hiện tại* — xem mục dưới |
|
| `planner` | global planner (`PlannerRunner::threadBody`), hộp thư plan | theo biến điều kiện (`startPlan`) | Một lượt `makePlan` tại một thời điểm. `cancelPlan()` / `swapPlanner()` (khi còn lượt dở) / destructor đặt `discard_` **và** gọi `Preemptable::preempt()` trên `running_planner_` — instance thread đang ở trong `makePlan`, không phải `active_` (swap có thể đã đổi `active_`) — nếu plugin hỗ trợ (2026-09-11); SBPL thoát trong ms thay vì chạy hết `allocated_time` |
|
||||||
|
| `detour worker` | một lượt `makePlan` của `DetourPathRecovery` | theo attempt | Thuộc plugin `sbpl_recovery` (2026-09-11). Hợp lệ vì behavior họ `kPath` không phát vận tốc; `onUpdate` chỉ khởi động/poll, `onCancelRequested()` preempt + join |
|
||||||
|
| `watchdog` | đọc `ComponentStatusBoard`, kết luận treo | `watchdog_period` | Chỉ atomic load, không lock, không chạm runner. Control thread treo → `getFeedback()` báo `LOST` từ thread host (2026-09-11) |
|
||||||
| `mission_event` | hàng đợi sự kiện mission | theo sự kiện | Thuộc mission framework, không thuộc gói này |
|
| `mission_event` | hàng đợi sự kiện mission | theo sự kiện | Thuộc mission framework, không thuộc gói này |
|
||||||
| `mission_exec` | điều phối chặng mission | theo sự kiện | Thuộc mission framework. Chỉ gọi callback, **không được block** |
|
| `mission_exec` | điều phối chặng mission | theo sự kiện | Thuộc mission framework. Chỉ gọi callback, **không được block** |
|
||||||
| host (ROS / C#) | nhận dữ liệu sensor, gọi API `BaseNavigation` | tuỳ host | Ghi vào vùng dữ liệu sensor qua mutex |
|
| host (ROS / C#) | nhận dữ liệu sensor, gọi API `BaseNavigation` | tuỳ host | Ghi vào vùng dữ liệu sensor qua mutex |
|
||||||
@@ -36,6 +38,42 @@ 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)
|
||||||
|
|
||||||
|
`NavigationServer::emergency_latched_` là **atomic duy nhất mà thread host đọc để ghi đè output của
|
||||||
|
control thread**: chừng nào nó bật, `getTwist()` trả vận tốc 0 (bỏ qua `twist_` control thread đã
|
||||||
|
ghi) và `getFeedback()` trả `EMERGENCY` (bỏ qua `refreshFeedback()`), ngay trong lời gọi
|
||||||
|
`emergency()` — không chờ drain, không chờ cycle. Cùng khuôn với `LOST` của watchdog.
|
||||||
|
|
||||||
|
Vì sao chấp nhận phá luật "mọi lệnh lifecycle đi qua drain": drain chạy ở đầu `spinOnce()`, tức chờ
|
||||||
|
control thread **rảnh**. Control thread đang ở trong một lượt `makePlan` (detour tới ~1.2 s) thì
|
||||||
|
`cancel` cũng trễ chừng đó — chấp nhận được cho cancel, không chấp nhận được cho dừng khẩn. Cái giá
|
||||||
|
là stamp của `getTwist()` trong cửa ân hạn lấy theo đồng hồ ở thread host (`clock_->now()`), không
|
||||||
|
theo mốc cycle của control loop — chủ đích, và chỉ trong lúc chốt.
|
||||||
|
|
||||||
|
Cờ này **không** thay đường chính: control thread vẫn nhận mức qua `ControlLoop::requestEmergency()`
|
||||||
|
ở drain kế và làm phần dọn (planner/recovery/action/outcome/mission layer). Cờ chỉ bảo đảm host
|
||||||
|
không đọc được lệnh cũ trong khoảng trống đó. Bất biến "chỉ control thread phát cmd_vel" không bị
|
||||||
|
chạm: thread host không *phát* gì, nó chỉ *không trả lại* lệnh cũ.
|
||||||
|
|
||||||
## Con trỏ costmap
|
## Con trỏ costmap
|
||||||
|
|
||||||
Con trỏ lấy từ `getCostmap()` là **non-owning và có thể bị thay giữa hai cycle**. Cache lại chính là
|
Con trỏ lấy từ `getCostmap()` là **non-owning và có thể bị thay giữa hai cycle**. Cache lại chính là
|
||||||
@@ -45,20 +83,30 @@ nguyên nhân lỗi double-free đã ghi nhận trong workspace. Quy tắc áp c
|
|||||||
- Không giữ tham chiếu qua nhiều cycle.
|
- Không giữ tham chiếu qua nhiều cycle.
|
||||||
- Không giữ tham chiếu qua ranh giới thread.
|
- Không giữ tham chiếu qua ranh giới thread.
|
||||||
|
|
||||||
## Trạng thái hiện tại: một thread
|
## Bảng trạng thái thành phần (2026-09-11)
|
||||||
|
|
||||||
`ControlLoop` hiện chạy đồng bộ, một thread, và lập plan ngay trong `step()`. Đây là lựa chọn có chủ
|
`ComponentStatusBoard` (`core/component_status.h`) là nguồn sự thật "ai đang bận / đang dừng / đã
|
||||||
đích cho bước dựng khung: phần quyết định kiểm được đầy đủ mà không cần thread nào, nên test chạy tất
|
treo". Quyền ghi theo hàng, mỗi hàng đúng MỘT chủ:
|
||||||
định và không có race.
|
|
||||||
|
|
||||||
Khi thêm thread planner ở bước sau:
|
| Hàng | Chủ ghi | Thread ghi |
|
||||||
|
|---|---|---|
|
||||||
|
| `kGlobalPlanner` | `PlannerRunner` | planner (busy/idle) + control (`stopping` trong `cancelPlan`) — đều dưới `mutex_` |
|
||||||
|
| `kLocalPlanner` | `ControlLoop` (bọc quanh `computeVelocityCommands`) | control |
|
||||||
|
| `kRecovery` | `RecoveryRunner` | control |
|
||||||
|
| `kAction` | `ActionRunner` | control |
|
||||||
|
| `kControlLoop` | `ControlLoop` (heartbeat cuối `step()`) | control |
|
||||||
|
|
||||||
- Giữ nguyên mô hình bộ đệm plan ba lớp của bản cũ. Nó đang hoạt động tốt và là đoạn code tinh tế —
|
Đọc: `ControlLoop` mỗi cycle (quiescence cho `CANCELLING`/`PAUSING`), `Watchdog` từ thread riêng, host
|
||||||
bê nguyên si trước, không "cải tiến" cùng lúc với việc chuyển sang kiến trúc mới.
|
qua C API `navigation_get_component_status()`. Mọi field atomic, relaxed; không lock trên đường control.
|
||||||
- Điểm nối là `ControlLoop::runPlanner()`: thay lời gọi đồng bộ bằng việc đánh thức thread planner và
|
|
||||||
đọc kết quả từ bộ đệm.
|
Watchdog **không ghi** vào bảng (giữ luật một chủ): kết luận treo nằm trong cờ riêng của nó.
|
||||||
- `PlannerFeedback` không đổi. Đó chính là mục đích của việc tách nó thành một enum: state machine
|
|
||||||
không cần biết plan được tính đồng bộ hay bất đồng bộ.
|
## Lịch sử: từ một thread tới bốn
|
||||||
|
|
||||||
|
Bản dựng khung chạy đồng bộ một thread. Thread planner đã được thêm với mô hình hộp thư
|
||||||
|
(`startPlan`/`pollPlan`/`cancelPlan`); `PlannerFeedback` không đổi — state machine không biết plan
|
||||||
|
được tính đồng bộ hay bất đồng bộ. Detour worker và watchdog thêm 2026-09-11 (xem
|
||||||
|
`PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md`).
|
||||||
|
|
||||||
## Vòng đời
|
## Vòng đời
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
#include <move_base2/control_loop.h>
|
#include <move_base2/control_loop.h>
|
||||||
#include <move_base2/io/sensor_gateway.h>
|
#include <move_base2/io/sensor_gateway.h>
|
||||||
|
#include <move_base2/io/watchdog.h>
|
||||||
|
|
||||||
namespace move_base2
|
namespace move_base2
|
||||||
{
|
{
|
||||||
@@ -44,9 +45,23 @@ struct MoveBase2Config
|
|||||||
/// [Hz] Nhịp lập plan lại khi đang bám plan. 0 = chỉ lập khi cần (theo yêu cầu của state machine).
|
/// [Hz] Nhịp lập plan lại khi đang bám plan. 0 = chỉ lập khi cần (theo yêu cầu của state machine).
|
||||||
double planner_frequency = 0.0;
|
double planner_frequency = 0.0;
|
||||||
|
|
||||||
/// [s] Trần thời gian chờ một lần lập plan trước khi coi là hỏng. <= 0 = không giới hạn.
|
/**
|
||||||
|
* [s] Trần một lượt makePlan trên thread planner TRƯỚC KHI watchdog kết luận planner TREO (2026-09-11
|
||||||
|
* — trước đó khoá này được đọc, in ra, và không ai dùng). Phải LỚN hơn thời gian một lượt hợp lệ
|
||||||
|
* dài nhất: với SBPL là `allocated_time` (đã chia ngân sách chung từ 2026-09-11). <= 0 = không
|
||||||
|
* giám sát. Đây là chẩn đoán, không phải điều khiển: state machine vẫn dùng `planner_patience`.
|
||||||
|
*/
|
||||||
double planner_timeout = 5.0;
|
double planner_timeout = 5.0;
|
||||||
|
|
||||||
|
/// [s] Continuous global-costmap readiness wait; 0 disables the check (legacy behavior).
|
||||||
|
double costmap_ready_timeout = 10.0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Watchdog (2026-09-11): thread riêng đọc bảng trạng thái thành phần, kết luận "treo" theo ngân
|
||||||
|
* sách từng hàng. `watchdog.planner_timeout` được chép từ @ref planner_timeout khi nạp.
|
||||||
|
*/
|
||||||
|
WatchdogConfig watchdog;
|
||||||
|
|
||||||
// --- Telemetry --------------------------------------------------------------------------------
|
// --- Telemetry --------------------------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -145,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.
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
#include <robot_geometry_msgs/PoseStamped.h>
|
#include <robot_geometry_msgs/PoseStamped.h>
|
||||||
#include <robot_geometry_msgs/Twist.h>
|
#include <robot_geometry_msgs/Twist.h>
|
||||||
|
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
#include <move_base2/core/navigation_request.h>
|
#include <move_base2/core/navigation_request.h>
|
||||||
#include <move_base2/core/state_machine.h>
|
#include <move_base2/core/state_machine.h>
|
||||||
#include <move_base2/core/velocity_arbiter.h>
|
#include <move_base2/core/velocity_arbiter.h>
|
||||||
@@ -66,10 +67,18 @@ 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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bảng trạng thái thành phần (2026-09-11). **Có thể null** — null thì quiescence của
|
||||||
|
* CANCELLING/PAUSING chỉ dựa vào `PlannerPort::isPlanning()` và odom (hành vi pha 1a), recovery/
|
||||||
|
* action coi như đã im. Có bảng thì runner ghi, control loop đọc thêm hàng recovery/action và tự
|
||||||
|
* ghi hàng local_planner + control_loop (heartbeat cho watchdog).
|
||||||
|
*/
|
||||||
|
ComponentStatusBoard* components = nullptr;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -100,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;
|
||||||
@@ -150,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;
|
||||||
@@ -222,6 +234,22 @@ public:
|
|||||||
void requestResume();
|
void requestResume();
|
||||||
void requestCancel();
|
void requestCancel();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Giữ dừng khẩn (2026-09-14). Là MỨC: giữ tới @ref requestClearEmergency.
|
||||||
|
*
|
||||||
|
* Vứt luôn yêu cầu đang chờ: mission layer đã xoá hàng đợi và bridge đã rút chặng chưa giao,
|
||||||
|
* nhưng một chặng đã pump xuống đây mà chưa kịp accept thì chỉ chỗ này biết — để lại là sau khi
|
||||||
|
* gỡ chốt robot tự chạy tiếp một chặng của order đã bị huỷ.
|
||||||
|
*/
|
||||||
|
void requestEmergency();
|
||||||
|
void requestClearEmergency();
|
||||||
|
|
||||||
|
/// @brief Đang giữ dừng khẩn hay không (mức đã đặt, không phụ thuộc state machine đã tiêu thụ chưa).
|
||||||
|
bool emergencyActive() const
|
||||||
|
{
|
||||||
|
return emergency_;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Chạy một control cycle.
|
* @brief Chạy một control cycle.
|
||||||
* @return false khi state machine vừa bước vào state terminal ở cycle này.
|
* @return false khi state machine vừa bước vào state terminal ở cycle này.
|
||||||
@@ -272,6 +300,12 @@ public:
|
|||||||
return state_machine_.state();
|
return state_machine_.state();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @brief State sẽ quay về sau PAUSING/PAUSED — host giữ tên state này trong lúc PAUSING.
|
||||||
|
NavigationState stateBeforePause() const
|
||||||
|
{
|
||||||
|
return state_machine_.stateBeforePause();
|
||||||
|
}
|
||||||
|
|
||||||
/// @brief Đang có yêu cầu chạy dở (kể cả đang pause) — false ngay khi kết quả được báo.
|
/// @brief Đang có yêu cầu chạy dở (kể cả đang pause) — false ngay khi kết quả được báo.
|
||||||
bool hasActiveRequest() const
|
bool hasActiveRequest() const
|
||||||
{
|
{
|
||||||
@@ -340,6 +374,15 @@ private:
|
|||||||
*/
|
*/
|
||||||
void collectPlannerResult();
|
void collectPlannerResult();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Robot đã dừng chưa — ưu tiên vận tốc ĐO ĐƯỢC, lùi về lệnh đã phát khi không có odom.
|
||||||
|
*
|
||||||
|
* Lệnh đã phát về 0 không có nghĩa là bánh xe đã đứng: driver còn giảm tốc. Host đọc CANCELLED
|
||||||
|
* lúc đó rồi gửi goal kế là gửi cho một robot đang trượt. Ngưỡng và công tắc:
|
||||||
|
* `StateMachineConfig::stopped_measured_*_eps` (0 = bỏ odom).
|
||||||
|
*/
|
||||||
|
bool robotStopped() const;
|
||||||
|
|
||||||
/// @brief Gọi controller và lấy lệnh ứng viên.
|
/// @brief Gọi controller và lấy lệnh ứng viên.
|
||||||
void runController(robot_geometry_msgs::Twist& candidate);
|
void runController(robot_geometry_msgs::Twist& candidate);
|
||||||
|
|
||||||
@@ -367,6 +410,8 @@ private:
|
|||||||
bool pause_requested_ = false;
|
bool pause_requested_ = false;
|
||||||
bool resume_requested_ = false;
|
bool resume_requested_ = false;
|
||||||
bool cancel_requested_ = false;
|
bool cancel_requested_ = false;
|
||||||
|
/// Mức dừng khẩn (không phải xung): đưa vào `StateMachineInput::emergency` mỗi cycle tới khi gỡ.
|
||||||
|
bool emergency_ = false;
|
||||||
|
|
||||||
/// Phản hồi thu được ở cycle trước, dùng làm dữ liệu vào cho cycle này.
|
/// Phản hồi thu được ở cycle trước, dùng làm dữ liệu vào cho cycle này.
|
||||||
PlannerFeedback planner_feedback_ = PlannerFeedback::kIdle;
|
PlannerFeedback planner_feedback_ = PlannerFeedback::kIdle;
|
||||||
|
|||||||
197
include/move_base2/core/component_status.h
Normal file
197
include/move_base2/core/component_status.h
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* move_base2 — bảng trạng thái thành phần: mỗi thread/plugin tự khai nó đang làm gì.
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#ifndef MOVE_BASE2_CORE_COMPONENT_STATUS_H_
|
||||||
|
#define MOVE_BASE2_CORE_COMPONENT_STATUS_H_
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <initializer_list>
|
||||||
|
|
||||||
|
namespace move_base2
|
||||||
|
{
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @enum Component
|
||||||
|
* @brief Các thành phần có thể "bận" độc lập với state machine.
|
||||||
|
*
|
||||||
|
* Thứ tự là chỉ số hàng trong @ref ComponentStatusBoard — thêm vào CUỐI, trước kCount, không xen
|
||||||
|
* giữa (C API pha 4 phơi chỉ số này ra host).
|
||||||
|
*/
|
||||||
|
enum class Component : std::uint8_t
|
||||||
|
{
|
||||||
|
kGlobalPlanner = 0, ///< Thread lập plan của PlannerRunner (một lượt makePlan).
|
||||||
|
kLocalPlanner, ///< Lời gọi computeVelocityCommands trên control thread.
|
||||||
|
kRecovery, ///< Behavior đang chạy (và worker thread của detour, pha 2).
|
||||||
|
kAction, ///< Handler đang chạy.
|
||||||
|
kCostmapGlobal, ///< Map-update thread của global costmap (chỉ heartbeat).
|
||||||
|
kCostmapLocal, ///< Map-update thread của local costmap (chỉ heartbeat).
|
||||||
|
kControlLoop, ///< Chính control thread — heartbeat cuối mỗi step().
|
||||||
|
kCount
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @enum ComponentPhase
|
||||||
|
* @brief Thành phần đang ở đâu trong vòng đời của một lượt việc.
|
||||||
|
*/
|
||||||
|
enum class ComponentPhase : std::uint8_t
|
||||||
|
{
|
||||||
|
kIdle = 0, ///< Không có việc.
|
||||||
|
kBusy, ///< Đang làm việc.
|
||||||
|
kStopping, ///< Đã được bảo dừng (preempt/cancel) nhưng chưa thoát.
|
||||||
|
kPaused, ///< Đã xác nhận tạm dừng (chỉ action, pha 3).
|
||||||
|
kHung, ///< Watchdog kết luận: bận quá ngân sách mà không nhích (pha 4).
|
||||||
|
kWaitingForCostmap ///< Retaining the request until global costmap data is ready.
|
||||||
|
};
|
||||||
|
|
||||||
|
const char* toString(Component component);
|
||||||
|
const char* toString(ComponentPhase phase);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @struct ComponentStatus
|
||||||
|
* @brief Một hàng của bảng. Mọi field là atomic, ghi relaxed — không lock, không alloc.
|
||||||
|
*
|
||||||
|
* Mốc thời gian là `steady_clock` [ns]: bảng phải so sánh được giữa các thread mà không phụ thuộc
|
||||||
|
* đồng hồ giả của control loop (ClockPort). Đọc `phase_since_ns` để biết bận bao lâu,
|
||||||
|
* `last_progress_ns` để biết lần cuối "nhích" — hai thứ khác nhau: SBPL bận 4 s nhưng nhích mỗi
|
||||||
|
* vài ms là bình thường; bận 4 s mà không nhích 4 s là treo.
|
||||||
|
*/
|
||||||
|
struct ComponentStatus
|
||||||
|
{
|
||||||
|
std::atomic<ComponentPhase> phase{ComponentPhase::kIdle};
|
||||||
|
std::atomic<std::int64_t> phase_since_ns{0};
|
||||||
|
std::atomic<std::int64_t> last_progress_ns{0};
|
||||||
|
std::atomic<std::uint64_t> progress_ticks{0};
|
||||||
|
|
||||||
|
ComponentStatus() = default;
|
||||||
|
ComponentStatus(const ComponentStatus&) = delete;
|
||||||
|
ComponentStatus& operator=(const ComponentStatus&) = delete;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class ComponentStatusBoard
|
||||||
|
* @brief Nguồn sự thật duy nhất về "thành phần nào đang bận / đang dừng / đã treo".
|
||||||
|
*
|
||||||
|
* Quyền ghi theo hàng, mỗi hàng đúng MỘT chủ: PlannerRunner ghi kGlobalPlanner (từ cả control
|
||||||
|
* thread lẫn thread lập plan, nhưng đều trong code của nó), RecoveryRunner ghi kRecovery,
|
||||||
|
* ActionRunner ghi kAction, ControlLoop ghi kLocalPlanner và kControlLoop. Cổng giả trong test ghi
|
||||||
|
* đúng hàng mà runner thật sẽ ghi. Hai chủ cho một hàng là race — không được.
|
||||||
|
*
|
||||||
|
* Ai đọc: ControlLoop mỗi cycle (quiescence cho CANCELLING/PAUSING), Watchdog (pha 4) từ thread
|
||||||
|
* riêng, host qua C API (pha 4). Đọc chỉ là load relaxed.
|
||||||
|
*
|
||||||
|
* Vòng đời: NavigationRuntime sở hữu, sống lâu hơn mọi runner; runner giữ con trỏ non-owning, null
|
||||||
|
* = không khai (mọi lời gọi thành no-op).
|
||||||
|
*/
|
||||||
|
class ComponentStatusBoard
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static constexpr std::size_t kRows = static_cast<std::size_t>(Component::kCount);
|
||||||
|
|
||||||
|
ComponentStatusBoard() = default;
|
||||||
|
ComponentStatusBoard(const ComponentStatusBoard&) = delete;
|
||||||
|
ComponentStatusBoard& operator=(const ComponentStatusBoard&) = delete;
|
||||||
|
|
||||||
|
/// @brief Mốc thời gian dùng cho mọi hàng [ns, steady_clock].
|
||||||
|
static std::int64_t nowNs()
|
||||||
|
{
|
||||||
|
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||||
|
std::chrono::steady_clock::now().time_since_epoch())
|
||||||
|
.count();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Chủ hàng đổi phase. Đặt lại `phase_since_ns` và tính là một nhịp tiến độ.
|
||||||
|
*
|
||||||
|
* Không kiểm hợp lệ chuyển phase: bảng ghi lại sự thật do chủ hàng khai, không phải state
|
||||||
|
* machine.
|
||||||
|
*/
|
||||||
|
void enter(Component component, ComponentPhase phase)
|
||||||
|
{
|
||||||
|
ComponentStatus& row = at(component);
|
||||||
|
const std::int64_t now = nowNs();
|
||||||
|
row.phase.store(phase, std::memory_order_relaxed);
|
||||||
|
row.phase_since_ns.store(now, std::memory_order_relaxed);
|
||||||
|
row.last_progress_ns.store(now, std::memory_order_relaxed);
|
||||||
|
row.progress_ticks.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Chủ hàng báo "còn sống, đang nhích". Rẻ: hai store, một fetch_add.
|
||||||
|
void progress(Component component)
|
||||||
|
{
|
||||||
|
ComponentStatus& row = at(component);
|
||||||
|
row.last_progress_ns.store(nowNs(), std::memory_order_relaxed);
|
||||||
|
row.progress_ticks.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
ComponentPhase phase(Component component) const
|
||||||
|
{
|
||||||
|
return at(component).phase.load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief [s] Đã ở phase hiện tại bao lâu, tính tới bây giờ.
|
||||||
|
double secondsInPhase(Component component) const
|
||||||
|
{
|
||||||
|
return static_cast<double>(nowNs() - at(component).phase_since_ns.load(std::memory_order_relaxed)) * 1e-9;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief [s] Từ lần "nhích" gần nhất tới bây giờ.
|
||||||
|
double secondsSinceProgress(Component component) const
|
||||||
|
{
|
||||||
|
return static_cast<double>(nowNs() - at(component).last_progress_ns.load(std::memory_order_relaxed)) * 1e-9;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isIdle(Component component) const
|
||||||
|
{
|
||||||
|
return phase(component) == ComponentPhase::kIdle;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool allIdle(std::initializer_list<Component> components) const
|
||||||
|
{
|
||||||
|
for (Component c : components)
|
||||||
|
{
|
||||||
|
if (!isIdle(c))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool anyHung() const
|
||||||
|
{
|
||||||
|
for (std::size_t i = 0; i < kRows; ++i)
|
||||||
|
{
|
||||||
|
if (rows_[i].phase.load(std::memory_order_relaxed) == ComponentPhase::kHung)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ComponentStatus& at(Component component)
|
||||||
|
{
|
||||||
|
return rows_[static_cast<std::size_t>(component)];
|
||||||
|
}
|
||||||
|
|
||||||
|
const ComponentStatus& at(Component component) const
|
||||||
|
{
|
||||||
|
return rows_[static_cast<std::size_t>(component)];
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::array<ComponentStatus, kRows> rows_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace move_base2
|
||||||
|
|
||||||
|
#endif // MOVE_BASE2_CORE_COMPONENT_STATUS_H_
|
||||||
@@ -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
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -96,6 +96,20 @@ struct NavigationRequest
|
|||||||
*/
|
*/
|
||||||
double relative_distance = std::numeric_limits<double>::quiet_NaN();
|
double relative_distance = std::numeric_limits<double>::quiet_NaN();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Góc quay tương đối [rad] so với hướng hiện tại của robot; dương = ngược chiều kim đồng hồ
|
||||||
|
* (REP-103). NaN = không dùng, và khi đó orientation của @ref goal không bị đụng tới.
|
||||||
|
*
|
||||||
|
* Cũng được quy ra @ref goal tuyệt đối tại `submit`. Khác @ref relative_distance và
|
||||||
|
* @ref goal_frame — vốn loại trừ nhau — trường này ĐI KÈM được với cả hai: chặng quay tại chỗ
|
||||||
|
* chính là `relative_distance = 0` cộng một góc khác 0.
|
||||||
|
*
|
||||||
|
* Giới hạn của cách biểu diễn: @ref goal là một pose, mà pose chỉ nói hướng cuối chứ không nói
|
||||||
|
* quay bao nhiêu hay quay chiều nào. Mission layer vì thế chỉ nhận góc trong [-pi, pi]; quay
|
||||||
|
* nhiều vòng hay ép chiều quay cần một contract khác.
|
||||||
|
*/
|
||||||
|
double relative_yaw = std::numeric_limits<double>::quiet_NaN();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Số hiệu chặng do mission layer cấp. 0 = goal trực tiếp, không thuộc mission nào.
|
* Số hiệu chặng do mission layer cấp. 0 = goal trực tiếp, không thuộc mission nào.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -32,6 +32,11 @@ namespace move_base2
|
|||||||
* các action của mission (nâng/hạ, sạc, chờ…) rồi mới báo kết quả. Trong state này KHÔNG ai
|
* các action của mission (nâng/hạ, sạc, chờ…) rồi mới báo kết quả. Trong state này KHÔNG ai
|
||||||
* được phát vận tốc: action cần chuyển động phải được mô hình hoá thành motion profile của
|
* được phát vận tốc: action cần chuyển động phải được mô hình hoá thành motion profile của
|
||||||
* navigation, không phải action.
|
* navigation, không phải action.
|
||||||
|
*
|
||||||
|
* 5. `kEmergency` (2026-09-14) là state **giữ**, không phải terminal: host giữ dừng khẩn thì lõi
|
||||||
|
* ở đây, bỏ qua pause/resume/cancel/goal mới, chỉ `clearEmergency()` mới ra (về kIdle). Khác
|
||||||
|
* kCancelling ở chỗ không có "đã xong" — không ai được gửi goal kế cho tới khi người vận hành
|
||||||
|
* gỡ chốt.
|
||||||
*/
|
*/
|
||||||
enum class NavigationState
|
enum class NavigationState
|
||||||
{
|
{
|
||||||
@@ -40,8 +45,10 @@ enum class NavigationState
|
|||||||
kControlling, ///< Đang bám plan. Local planner là nguồn vận tốc.
|
kControlling, ///< Đang bám plan. Local planner là nguồn vận tốc.
|
||||||
kRecovering, ///< Đang chạy một recovery behavior. Recovery là nguồn vận tốc.
|
kRecovering, ///< Đang chạy một recovery behavior. Recovery là nguồn vận tốc.
|
||||||
kExecutingActions, ///< Đang chạy action của mission tại chỗ (D8). Vận tốc = 0.
|
kExecutingActions, ///< Đang chạy action của mission tại chỗ (D8). Vận tốc = 0.
|
||||||
kPaused, ///< Tạm dừng theo yêu cầu. Vận tốc = 0.
|
kPausing, ///< Đã nhận pause, lệnh = 0, đang chờ mọi thành phần im (2026-09-11). Host vẫn thấy tên state trước.
|
||||||
|
kPaused, ///< Tạm dừng theo yêu cầu, mọi thành phần đã im. Vận tốc = 0.
|
||||||
kCancelling, ///< Đang giảm tốc để huỷ. Vận tốc = 0, chờ robot dừng hẳn.
|
kCancelling, ///< Đang giảm tốc để huỷ. Vận tốc = 0, chờ robot dừng hẳn.
|
||||||
|
kEmergency, ///< Dừng khẩn đang chốt. Vận tốc = 0, từ chối mọi lệnh tới khi clearEmergency().
|
||||||
kSucceeded, ///< Terminal: đạt goal và mọi action đã xong.
|
kSucceeded, ///< Terminal: đạt goal và mọi action đã xong.
|
||||||
kAborted, ///< Terminal: hết cách, không đạt được goal hoặc action thất bại.
|
kAborted, ///< Terminal: hết cách, không đạt được goal hoặc action thất bại.
|
||||||
kCancelled ///< Terminal: đã huỷ theo yêu cầu và robot đã dừng.
|
kCancelled ///< Terminal: đã huỷ theo yêu cầu và robot đã dừng.
|
||||||
|
|||||||
@@ -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.
|
||||||
};
|
};
|
||||||
@@ -56,7 +57,8 @@ enum class ActionFeedback
|
|||||||
kIdle, ///< Chưa chạy action ở cycle này.
|
kIdle, ///< Chưa chạy action ở cycle này.
|
||||||
kRunning,
|
kRunning,
|
||||||
kSucceeded, ///< Action HIỆN TẠI xong; còn action kế tiếp hay không do state machine quyết.
|
kSucceeded, ///< Action HIỆN TẠI xong; còn action kế tiếp hay không do state machine quyết.
|
||||||
kFailed
|
kFailed,
|
||||||
|
kCancelled ///< Handler đã dừng thiết bị an toàn sau cancel (pha 3). Chỉ gặp trong CANCELLING/PAUSING.
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -117,6 +119,28 @@ struct StateMachineConfig
|
|||||||
/// Số lần lập plan hỏng liên tiếp tối đa. < 0 = không giới hạn (chỉ chặn bằng planner_patience).
|
/// Số lần lập plan hỏng liên tiếp tối đa. < 0 = không giới hạn (chỉ chặn bằng planner_patience).
|
||||||
int max_planning_retries = -1;
|
int max_planning_retries = -1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [s] Trần chờ ở kCancelling VÀ kPausing cho tới khi runtime QUIESCENT — thread global planner
|
||||||
|
* idle, recovery idle, action đã trả terminal (cancel) / xác nhận tạm dừng (pause), robot đứng
|
||||||
|
* yên theo vận tốc đo được. <= 0 = tắt: kết thúc ngay khi robot_stopped như trước 2026-09-11
|
||||||
|
* (khi đó CANCELLED/PAUSED có thể được báo trong lúc một lượt makePlan đã huỷ vẫn còn chiếm thread
|
||||||
|
* planner nhiều giây — host tin là xong và gửi goal kế, goal kế bị coi là hỏng).
|
||||||
|
*
|
||||||
|
* Quá trần thì vẫn kết thúc nhưng bên gọi phải log LỖI: có plugin/cấu hình khiến cancel/pause
|
||||||
|
* không dừng được thật.
|
||||||
|
*/
|
||||||
|
double settle_timeout = 2.0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [m/s] Ngưỡng coi robot đã dừng theo vận tốc ĐO ĐƯỢC (odom). Chỉ dùng khi bên gọi có odom; đặt
|
||||||
|
* 0 = bỏ qua odom, quay về đo bằng lệnh đã phát (arbiter). Odom nhiễu giữ CANCELLING lâu hơn thì
|
||||||
|
* settle_timeout là trần.
|
||||||
|
*/
|
||||||
|
double stopped_measured_linear_eps = 0.02;
|
||||||
|
|
||||||
|
/// [rad/s] Như @ref stopped_measured_linear_eps cho trục quay.
|
||||||
|
double stopped_measured_angular_eps = 0.02;
|
||||||
|
|
||||||
/// Số recovery behavior đã nạp được. 0 = không có đường phục hồi, lỗi là ABORTED ngay.
|
/// Số recovery behavior đã nạp được. 0 = không có đường phục hồi, lỗi là ABORTED ngay.
|
||||||
std::size_t recovery_behavior_count = 0;
|
std::size_t recovery_behavior_count = 0;
|
||||||
|
|
||||||
@@ -158,7 +182,16 @@ struct StateMachineInput
|
|||||||
bool resume_requested = false;
|
bool resume_requested = false;
|
||||||
bool cancel_requested = false;
|
bool cancel_requested = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Host đang GIỮ dừng khẩn (2026-09-14). Đây là MỨC, không phải xung như ba cờ trên: chừng nào
|
||||||
|
* còn true thì mọi cycle đều ở kEmergency, kể cả cycle kIdle có goal chờ — một xung chỉ thắng
|
||||||
|
* được đúng cycle nó tới, còn dừng khẩn phải thắng cho tới khi người vận hành gỡ chốt. Xét
|
||||||
|
* trước mọi thứ khác, kể cả cancel.
|
||||||
|
*/
|
||||||
|
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;
|
||||||
@@ -193,9 +226,33 @@ struct StateMachineInput
|
|||||||
*/
|
*/
|
||||||
bool costmap_current = true;
|
bool costmap_current = true;
|
||||||
|
|
||||||
/// Robot đã dừng hẳn chưa (|v| <= ngưỡng). Dùng để rời kCancelling.
|
/// Robot đã dừng hẳn chưa (|v| <= ngưỡng). Bên gọi ưu tiên vận tốc ĐO ĐƯỢC (odom), thiếu odom
|
||||||
|
/// thì lấy lệnh đã phát. Một trong ba điều kiện rời kCancelling.
|
||||||
bool robot_stopped = true;
|
bool robot_stopped = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thread planner còn đang chạy một lượt makePlan (kể cả lượt đã bị huỷ mà plugin không cắt được).
|
||||||
|
*
|
||||||
|
* Điều kiện thứ hai để rời kCancelling: CANCELLED chỉ được báo khi thread này rảnh, nếu không
|
||||||
|
* host tin là xong và gửi goal kế trong lúc `startPlan()` còn bị từ chối. Bên gọi lấy từ
|
||||||
|
* `PlannerPort::isPlanning()`.
|
||||||
|
*/
|
||||||
|
bool planner_busy = false;
|
||||||
|
|
||||||
|
/// Recovery behavior còn đang chạy hoặc đang dừng (kể cả worker thread của detour, pha 2). Bên gọi
|
||||||
|
/// lấy từ bảng trạng thái thành phần. Điều kiện quiescent cùng nhóm với @ref planner_busy.
|
||||||
|
bool recovery_busy = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action đang chạy đã trả trạng thái terminal sau khi bị `cancel_action` (hoặc không có action).
|
||||||
|
*
|
||||||
|
* Điều kiện thứ ba để rời kCancelling. Chừng nào còn false, state machine tiếp tục `tick_action`
|
||||||
|
* trong kCancelling để handler thiết bị có cơ hội đưa thiết bị về vị trí an toàn rồi báo
|
||||||
|
* `kCancelled` — không cấp vận tốc. Mặc định true: cổng action hiện chưa có handshake (pha 3),
|
||||||
|
* bên gọi truyền true.
|
||||||
|
*/
|
||||||
|
bool action_terminal = true;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tuyến phía trước bị chắn (EnvMonitor kUnreachable: không còn đường trong cửa sổ tới điểm thoát, đã
|
* Tuyến phía trước bị chắn (EnvMonitor kUnreachable: không còn đường trong cửa sổ tới điểm thoát, đã
|
||||||
* tĩnh đủ `static_on`).
|
* tĩnh đủ `static_on`).
|
||||||
@@ -260,6 +317,8 @@ struct StateMachineOutput
|
|||||||
bool start_action = false; ///< D8: khởi động action thứ @ref action_index của yêu cầu hiện tại.
|
bool start_action = false; ///< D8: khởi động action thứ @ref action_index của yêu cầu hiện tại.
|
||||||
bool tick_action = false; ///< D8: gọi update() của action đang chạy.
|
bool tick_action = false; ///< D8: gọi update() của action đang chạy.
|
||||||
bool cancel_action = false; ///< D8: yêu cầu action đang chạy dừng an toàn.
|
bool cancel_action = false; ///< D8: yêu cầu action đang chạy dừng an toàn.
|
||||||
|
bool pause_action = false; ///< Báo handler tạm dừng (dịch đồng hồ timeout của nó) — 2026-09-11.
|
||||||
|
bool resume_action = false; ///< Báo handler tiếp tục sau tạm dừng — 2026-09-11.
|
||||||
|
|
||||||
/// Chỉ có nghĩa khi @ref start_action — action nào trong danh sách của yêu cầu cần khởi động.
|
/// Chỉ có nghĩa khi @ref start_action — action nào trong danh sách của yêu cầu cần khởi động.
|
||||||
std::size_t action_index = 0;
|
std::size_t action_index = 0;
|
||||||
@@ -298,6 +357,13 @@ struct StateMachineOutput
|
|||||||
bool recovery_reset_denied = false;
|
bool recovery_reset_denied = false;
|
||||||
double recovery_reset_travel = 0.0; ///< [m] chỉ có nghĩa khi @ref recovery_reset_denied.
|
double recovery_reset_travel = 0.0; ///< [m] chỉ có nghĩa khi @ref recovery_reset_denied.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cycle này kCancelling → kCancelled hoặc kPausing → kPaused xảy ra vì quá `settle_timeout` chứ
|
||||||
|
* KHÔNG phải vì runtime đã quiescent. Bật đúng MỘT cycle. Bên gọi phải log LỖI (không có khoá
|
||||||
|
* tắt): có plugin không cắt được lượt đang chạy, hoặc odom không bao giờ về 0.
|
||||||
|
*/
|
||||||
|
bool settle_timed_out = false;
|
||||||
|
|
||||||
/// Nguồn được phép phát vận tốc ở cycle này. Luôn có đúng một nguồn.
|
/// Nguồn được phép phát vận tốc ở cycle này. Luôn có đúng một nguồn.
|
||||||
VelocitySource velocity_source = VelocitySource::kNone;
|
VelocitySource velocity_source = VelocitySource::kNone;
|
||||||
|
|
||||||
@@ -369,6 +435,12 @@ public:
|
|||||||
return action_index_;
|
return action_index_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @brief State sẽ quay về sau kPausing/kPaused. Host dùng để giữ tên state cũ trong lúc PAUSING.
|
||||||
|
NavigationState stateBeforePause() const
|
||||||
|
{
|
||||||
|
return state_before_pause_;
|
||||||
|
}
|
||||||
|
|
||||||
/// @brief Số lần lập plan hỏng liên tiếp tính từ lần vào kPlanning gần nhất.
|
/// @brief Số lần lập plan hỏng liên tiếp tính từ lần vào kPlanning gần nhất.
|
||||||
int planningRetries() const
|
int planningRetries() const
|
||||||
{
|
{
|
||||||
@@ -423,6 +495,25 @@ private:
|
|||||||
void finish(NavigationState terminal, NavigationOutcome outcome, const robot::Time& now,
|
void finish(NavigationState terminal, NavigationOutcome outcome, const robot::Time& now,
|
||||||
const char* reason, StateMachineOutput& out);
|
const char* reason, StateMachineOutput& out);
|
||||||
|
|
||||||
|
/// @brief Đường resume chung của kPausing và kPaused: gieo lại đồng hồ, về @ref state_before_pause_.
|
||||||
|
void resumeFromPause(const StateMachineInput& in, StateMachineOutput& out);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Vào kEmergency từ state hiện tại (2026-09-14).
|
||||||
|
*
|
||||||
|
* Dọn như preempt + cancel gộp lại: planner bị dừng, recovery/action đang chạy bị bảo dừng, và
|
||||||
|
* chặng đang chạy (state ≠ kIdle) được báo CANCELLED đúng một lần. Không có state terminal xen
|
||||||
|
* giữa: kEmergency là nơi ở lại cho tới khi host gỡ chốt.
|
||||||
|
*/
|
||||||
|
void enterEmergency(const StateMachineInput& in, StateMachineOutput& out);
|
||||||
|
|
||||||
|
/// @brief Có action của yêu cầu hiện hành đang chạy hoặc đang tạm dừng — thứ `cancel_action` phải nhắm tới.
|
||||||
|
bool actionInFlight() const;
|
||||||
|
|
||||||
|
/// @brief Chốt bất biến (một nguồn vận tốc, kNone ở state phải dừng, không chạy khi mất pose).
|
||||||
|
/// Mọi đường ra của @ref update đều phải đi qua đây.
|
||||||
|
void applyInvariants(const StateMachineInput& in, StateMachineOutput& out);
|
||||||
|
|
||||||
/// Cursor của route cho @p trigger trong request hiện hành.
|
/// Cursor của route cho @p trigger trong request hiện hành.
|
||||||
std::size_t& recoveryRouteCursor(RecoveryTrigger trigger);
|
std::size_t& recoveryRouteCursor(RecoveryTrigger trigger);
|
||||||
const std::size_t& recoveryRouteCursor(RecoveryTrigger trigger) const;
|
const std::size_t& recoveryRouteCursor(RecoveryTrigger trigger) const;
|
||||||
|
|||||||
@@ -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ở
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
110
include/move_base2/io/watchdog.h
Normal file
110
include/move_base2/io/watchdog.h
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* move_base2 — watchdog: thread riêng đọc bảng trạng thái thành phần và kết luận "treo".
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#ifndef MOVE_BASE2_IO_WATCHDOG_H_
|
||||||
|
#define MOVE_BASE2_IO_WATCHDOG_H_
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
|
|
||||||
|
namespace move_base2
|
||||||
|
{
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @struct WatchdogConfig
|
||||||
|
* @brief Ngân sách "bận mà không nhích" cho từng thành phần. <= 0 = không giám sát hàng đó.
|
||||||
|
*
|
||||||
|
* "Nhích" = `ComponentStatusBoard::progress()` của chủ hàng. Bận lâu nhưng vẫn nhích là bình thường
|
||||||
|
* (SBPL 4 s vẫn nhích mỗi expand); bận mà không nhích quá ngân sách là treo.
|
||||||
|
*/
|
||||||
|
struct WatchdogConfig
|
||||||
|
{
|
||||||
|
double period = 0.1; ///< [s] chu kỳ kiểm; 0 = tắt watchdog.
|
||||||
|
double planner_timeout = 5.0; ///< [s] kGlobalPlanner — phải > allocated_time × số lượt replan của SBPL.
|
||||||
|
double local_planner_call_budget = 0.5; ///< [s] kLocalPlanner — một lời gọi computeVelocityCommands.
|
||||||
|
double recovery_stall_budget = 5.0; ///< [s] kRecovery.
|
||||||
|
double action_stall_budget = 0.0; ///< [s] kAction — mặc định tắt: handler tự timeout.
|
||||||
|
double control_loop_stall_budget = 0.5; ///< [s] kControlLoop — heartbeat cuối step(); 15 cycle @ 30 Hz.
|
||||||
|
|
||||||
|
bool validate(std::string& error) const;
|
||||||
|
std::string describe() const;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class Watchdog
|
||||||
|
* @brief Phát hiện thành phần treo từ một thread KHÁC thành phần bị nghi.
|
||||||
|
*
|
||||||
|
* Control thread không tự phát hiện được chính nó treo — đó là lý do phải có thread này. Nó chỉ
|
||||||
|
* đọc atomics của @ref ComponentStatusBoard, không lock, không chạm runner; kết luận "treo" giữ
|
||||||
|
* trong cờ riêng của watchdog (một hàng của bảng chỉ có MỘT chủ ghi — watchdog không ghi vào đó).
|
||||||
|
*
|
||||||
|
* Log: `log_error` đúng một lần ở sườn treo (không có khoá tắt), `log_warning` khi hồi.
|
||||||
|
*/
|
||||||
|
class Watchdog
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
Watchdog() = default;
|
||||||
|
~Watchdog();
|
||||||
|
Watchdog(const Watchdog&) = delete;
|
||||||
|
Watchdog& operator=(const Watchdog&) = delete;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Khởi động thread giám sát. @p board non-owning, phải sống lâu hơn watchdog.
|
||||||
|
* @return false nếu config sai hoặc đã chạy.
|
||||||
|
*/
|
||||||
|
bool start(const ComponentStatusBoard* board, const WatchdogConfig& config, std::string& error);
|
||||||
|
|
||||||
|
void stop();
|
||||||
|
|
||||||
|
bool running() const
|
||||||
|
{
|
||||||
|
return running_.load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Thành phần @p c đang bị kết luận treo.
|
||||||
|
bool hung(Component c) const
|
||||||
|
{
|
||||||
|
return hung_[static_cast<std::size_t>(c)].load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool anyHung() const;
|
||||||
|
|
||||||
|
/// @brief Control thread không nhích quá ngân sách — host phải thấy LOST và tự zero cmd_vel.
|
||||||
|
bool controlLoopHung() const
|
||||||
|
{
|
||||||
|
return hung(Component::kControlLoop);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Chạy MỘT vòng kiểm ngay trên thread gọi (không cần thread riêng) — cho test và cho
|
||||||
|
* host muốn tự tick. Cùng logic với thread nền.
|
||||||
|
*/
|
||||||
|
void checkOnce();
|
||||||
|
|
||||||
|
/// @brief Một dòng tóm tắt các thành phần đang treo, rỗng nếu không có.
|
||||||
|
std::string report() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
double budgetFor(Component c) const;
|
||||||
|
void threadBody();
|
||||||
|
|
||||||
|
const ComponentStatusBoard* board_ = nullptr;
|
||||||
|
WatchdogConfig config_;
|
||||||
|
std::thread thread_;
|
||||||
|
std::atomic<bool> running_{false};
|
||||||
|
std::array<std::atomic<bool>, ComponentStatusBoard::kRows> hung_{};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace move_base2
|
||||||
|
|
||||||
|
#endif // MOVE_BASE2_IO_WATCHDOG_H_
|
||||||
@@ -18,6 +18,7 @@
|
|||||||
#include <move_base2/bridges/mission_adapter_bridge.h>
|
#include <move_base2/bridges/mission_adapter_bridge.h>
|
||||||
#include <move_base2/bridges/mission_layer.h>
|
#include <move_base2/bridges/mission_layer.h>
|
||||||
#include <move_base2/config/move_base2_config.h>
|
#include <move_base2/config/move_base2_config.h>
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
#include <move_base2/io/runtime_stats.h>
|
#include <move_base2/io/runtime_stats.h>
|
||||||
#include <move_base2/control_loop.h>
|
#include <move_base2/control_loop.h>
|
||||||
#include <move_base2/io/costmap_exporter.h>
|
#include <move_base2/io/costmap_exporter.h>
|
||||||
@@ -276,6 +277,16 @@ public:
|
|||||||
return stats_.get();
|
return stats_.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @brief Bảng trạng thái thành phần — watchdog và host đọc từ đây (chỉ atomic load).
|
||||||
|
const ComponentStatusBoard& components() const
|
||||||
|
{
|
||||||
|
return components_;
|
||||||
|
}
|
||||||
|
ComponentStatusBoard& components()
|
||||||
|
{
|
||||||
|
return components_;
|
||||||
|
}
|
||||||
|
|
||||||
robot_costmap_2d::Costmap2DROBOT* globalCostmap()
|
robot_costmap_2d::Costmap2DROBOT* globalCostmap()
|
||||||
{
|
{
|
||||||
return global_costmap_.get();
|
return global_costmap_.get();
|
||||||
@@ -342,6 +353,12 @@ private:
|
|||||||
/// Dựng trong buildCostmaps() ngay sau khi đọc config, vì nó phải chụp được thread mà costmap tạo.
|
/// Dựng trong buildCostmaps() ngay sau khi đọc config, vì nó phải chụp được thread mà costmap tạo.
|
||||||
std::unique_ptr<RuntimeStats> stats_;
|
std::unique_ptr<RuntimeStats> stats_;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bảng trạng thái thành phần (2026-09-11). Khai TRƯỚC mọi runner để huỷ SAU chúng: runner giữ
|
||||||
|
* con trỏ non-owning và thread lập plan có thể ghi vào bảng cho tới khi PlannerRunner join xong.
|
||||||
|
*/
|
||||||
|
ComponentStatusBoard components_;
|
||||||
|
|
||||||
/// Guard "không đi mù": hỏi costmap điều khiển xem observation buffer còn hạn không.
|
/// Guard "không đi mù": hỏi costmap điều khiển xem observation buffer còn hạn không.
|
||||||
CostmapStatusAdapter costmap_status_;
|
CostmapStatusAdapter costmap_status_;
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -23,6 +24,7 @@
|
|||||||
#include <move_base2/core/navigation_request.h>
|
#include <move_base2/core/navigation_request.h>
|
||||||
#include <move_base2/io/runtime_stats.h>
|
#include <move_base2/io/runtime_stats.h>
|
||||||
#include <move_base2/io/sensor_gateway.h>
|
#include <move_base2/io/sensor_gateway.h>
|
||||||
|
#include <move_base2/io/watchdog.h>
|
||||||
#include <robot_sensor_ports/sensor_store.h>
|
#include <robot_sensor_ports/sensor_store.h>
|
||||||
#include <move_base2/navigation_runtime.h>
|
#include <move_base2/navigation_runtime.h>
|
||||||
|
|
||||||
@@ -59,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,
|
||||||
@@ -237,6 +241,21 @@ public:
|
|||||||
void resume() override;
|
void resume() override;
|
||||||
void cancel() override;
|
void cancel() override;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Dừng khẩn (2026-09-14). Khác ba hàm trên ở chỗ có hiệu lực NGAY trên thread host:
|
||||||
|
* @ref emergency_latched_ được đặt trước khi trả về, nên @ref getTwist trả 0 và @ref getFeedback
|
||||||
|
* báo EMERGENCY kể cả khi control thread đang kẹt. Phần dọn (planner/recovery/action/mission
|
||||||
|
* layer) đi đường drain như mọi lệnh lifecycle, ở cycle kế.
|
||||||
|
*/
|
||||||
|
void emergency() override;
|
||||||
|
void clearEmergency() override;
|
||||||
|
|
||||||
|
/// @brief Host đang giữ dừng khẩn. Đọc được từ thread bất kỳ.
|
||||||
|
bool emergencyLatched() const
|
||||||
|
{
|
||||||
|
return emergency_latched_.load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
bool setTwistLinear(const robot_geometry_msgs::Vector3& linear) override;
|
bool setTwistLinear(const robot_geometry_msgs::Vector3& linear) override;
|
||||||
bool setTwistAngular(const robot_geometry_msgs::Vector3& angular) override;
|
bool setTwistAngular(const robot_geometry_msgs::Vector3& angular) override;
|
||||||
|
|
||||||
@@ -246,6 +265,29 @@ public:
|
|||||||
robot_nav_2d_msgs::Twist2DStamped getTwist() override;
|
robot_nav_2d_msgs::Twist2DStamped getTwist() override;
|
||||||
|
|
||||||
robot::move_base_core::NavFeedback* getFeedback() override;
|
robot::move_base_core::NavFeedback* getFeedback() override;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Bảng trạng thái thành phần của runtime (null khi chưa initialize / cổng bơm từ ngoài).
|
||||||
|
*
|
||||||
|
* Cho host (C API `navigation_get_component_status`) và watchdog. Chỉ atomic load — gọi được từ
|
||||||
|
* thread bất kỳ.
|
||||||
|
*/
|
||||||
|
const ComponentStatusBoard* componentStatus() const;
|
||||||
|
|
||||||
|
const Watchdog& watchdog() const
|
||||||
|
{
|
||||||
|
return watchdog_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Khởi động watchdog trên bảng @p board với @p config — test seam (initialize() tự làm
|
||||||
|
* việc này với bảng của runtime).
|
||||||
|
*/
|
||||||
|
bool startWatchdog(const ComponentStatusBoard* board, const WatchdogConfig& config,
|
||||||
|
std::string& error)
|
||||||
|
{
|
||||||
|
return watchdog_.start(board, config, error);
|
||||||
|
}
|
||||||
robot::move_base_core::PlannerDataOutput getGlobalData() override;
|
robot::move_base_core::PlannerDataOutput getGlobalData() override;
|
||||||
robot::move_base_core::PlannerDataOutput getLocalData() override;
|
robot::move_base_core::PlannerDataOutput getLocalData() override;
|
||||||
|
|
||||||
@@ -289,6 +331,14 @@ private:
|
|||||||
*/
|
*/
|
||||||
void drainLifecycleRequests();
|
void drainLifecycleRequests();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Từ chối một cửa vào (moveTo/order/instantActions/submit) khi đang giữ dừng khẩn.
|
||||||
|
* @param what Tên cửa, cho lý do từ chối và log.
|
||||||
|
* @return true nếu ĐÃ từ chối — bên gọi trả false ngay. Đặt trước mission layer để host nhận
|
||||||
|
* từ chối đồng bộ thay vì "đã vào hàng đợi" rồi bị manager gạt trên thread sự kiện.
|
||||||
|
*/
|
||||||
|
bool rejectIfEmergencyLatched(const char* what);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Huỷ CHỈ chặng đang chạy, không đụng hàng đợi mission.
|
* @brief Huỷ CHỈ chặng đang chạy, không đụng hàng đợi mission.
|
||||||
*
|
*
|
||||||
@@ -367,9 +417,19 @@ private:
|
|||||||
std::atomic<bool> control_thread_running_{ false };
|
std::atomic<bool> control_thread_running_{ false };
|
||||||
robot::TFListenerPtr tf_;
|
robot::TFListenerPtr tf_;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Watchdog (2026-09-11): thread riêng đọc bảng trạng thái thành phần của runtime, kết luận treo.
|
||||||
|
* Khai SAU runtime_ (huỷ trước nó) — nó chỉ giữ con trỏ non-owning vào bảng của runtime.
|
||||||
|
*/
|
||||||
|
Watchdog watchdog_;
|
||||||
|
|
||||||
/// Bảo vệ dữ liệu sensor và footprint: host ghi từ thread của nó, control loop đọc.
|
/// 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_;
|
||||||
@@ -420,6 +480,22 @@ private:
|
|||||||
*/
|
*/
|
||||||
bool mission_cancel_requested_ = false;
|
bool mission_cancel_requested_ = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dừng khẩn (2026-09-14) — hai lớp, cùng một sự thật:
|
||||||
|
*
|
||||||
|
* - @ref emergency_latched_ là MỨC đọc trên thread host, không lock: @ref getTwist ghi đè vận
|
||||||
|
* tốc về 0 và @ref getFeedback ghi đè state thành EMERGENCY ngay trong lời gọi. Đây là đường
|
||||||
|
* duy nhất phản ứng được khi control thread đang kẹt (detour SBPL tới 1.2 s) — mọi lệnh
|
||||||
|
* lifecycle khác đều chờ drain ở cycle kế. Đặt TRƯỚC cặp cờ dưới, xoá ngay khi host gỡ chốt.
|
||||||
|
* - Cặp cờ đối nghịch dưới `data_mutex_` (khuôn pause/resume: lệnh gọi sau thắng) là đường xuống
|
||||||
|
* lõi ở @ref drainLifecycleRequests, nơi ControlLoop nhận mức và mission layer nhận sự kiện.
|
||||||
|
*/
|
||||||
|
std::atomic<bool> emergency_latched_{ false };
|
||||||
|
bool emergency_requested_ = false;
|
||||||
|
bool clear_emergency_requested_ = false;
|
||||||
|
/// Mốc chốt, cho cửa ân hạn stamp của @ref getTwist (0 tươi trong `kStopGraceSeconds` rồi đóng băng).
|
||||||
|
robot::Time emergency_since_;
|
||||||
|
|
||||||
std::string last_reject_reason_;
|
std::string last_reject_reason_;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -40,7 +40,8 @@ struct ActionTick
|
|||||||
{
|
{
|
||||||
kRunning,
|
kRunning,
|
||||||
kSucceeded,
|
kSucceeded,
|
||||||
kFailed
|
kFailed,
|
||||||
|
kCancelled ///< Handler đã dừng thiết bị an toàn sau cancel() (pha 3). Terminal.
|
||||||
};
|
};
|
||||||
|
|
||||||
Status status = Status::kRunning;
|
Status status = Status::kRunning;
|
||||||
@@ -83,8 +84,25 @@ public:
|
|||||||
/// @brief Một control cycle. CHỈ được gọi sau khi @ref start trả true.
|
/// @brief Một control cycle. CHỈ được gọi sau khi @ref start trả true.
|
||||||
virtual ActionTick update() = 0;
|
virtual ActionTick update() = 0;
|
||||||
|
|
||||||
/// @brief Yêu cầu dừng an toàn action đang chạy (huỷ mission, emergency).
|
/**
|
||||||
|
* @brief Yêu cầu dừng an toàn action đang chạy (huỷ mission, emergency).
|
||||||
|
*
|
||||||
|
* Từ 2026-09-11 có hai kiểu: handler dừng xong ngay trong cancel() (port quên nó, hàng kAction về
|
||||||
|
* idle) hoặc handler cần tick tới khi trả `kCancelled` (port giữ nó, hàng kAction = stopping,
|
||||||
|
* state machine tiếp tục @ref update trong CANCELLING). Bên gọi phân biệt qua bảng trạng thái
|
||||||
|
* thành phần, không qua giá trị trả về.
|
||||||
|
*/
|
||||||
virtual void cancel() = 0;
|
virtual void cancel() = 0;
|
||||||
|
|
||||||
|
/// @brief Tạm dừng action đang chạy: handler dịch đồng hồ timeout, KHÔNG dừng thiết bị. Default no-op.
|
||||||
|
virtual void pause()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Tiếp tục sau @ref pause. Default no-op.
|
||||||
|
virtual void resume()
|
||||||
|
{
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace move_base2
|
} // namespace move_base2
|
||||||
|
|||||||
@@ -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").
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -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.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
|
|
||||||
#include <action_core/action_registry.h>
|
#include <action_core/action_registry.h>
|
||||||
|
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
#include <move_base2/ports/action_port.h>
|
#include <move_base2/ports/action_port.h>
|
||||||
#include <move_base2/ports/clock_port.h>
|
#include <move_base2/ports/clock_port.h>
|
||||||
|
|
||||||
@@ -86,6 +87,8 @@ public:
|
|||||||
bool start(const robot_protocol_msgs::Action& action) override;
|
bool start(const robot_protocol_msgs::Action& action) override;
|
||||||
ActionTick update() override;
|
ActionTick update() override;
|
||||||
void cancel() override;
|
void cancel() override;
|
||||||
|
void pause() override;
|
||||||
|
void resume() override;
|
||||||
|
|
||||||
/// @brief Số handler đã nạp.
|
/// @brief Số handler đã nạp.
|
||||||
std::size_t handlerCount() const
|
std::size_t handlerCount() const
|
||||||
@@ -105,6 +108,18 @@ public:
|
|||||||
return registry_.find(action_type);
|
return registry_.find(action_type);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Gắn bảng trạng thái thành phần (non-owning, null = không khai).
|
||||||
|
*
|
||||||
|
* Runner là CHỦ hàng `kAction`: kBusy từ @ref start thành công, `progress()` mỗi @ref update,
|
||||||
|
* kIdle khi tick trả terminal hoặc khi @ref cancel (cổng hiện quên handler ngay trong cancel —
|
||||||
|
* pha 3 đổi thành kStopping tới khi handler trả kCancelled).
|
||||||
|
*/
|
||||||
|
void attachStatusBoard(ComponentStatusBoard* board)
|
||||||
|
{
|
||||||
|
status_board_ = board;
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/// Dịch kết quả của framework sang kiểu của port.
|
/// Dịch kết quả của framework sang kiểu của port.
|
||||||
static ActionTick toTick(const action_core::ActionTick& tick);
|
static ActionTick toTick(const action_core::ActionTick& tick);
|
||||||
@@ -117,6 +132,7 @@ private:
|
|||||||
action_core::ActionRegistry registry_;
|
action_core::ActionRegistry registry_;
|
||||||
|
|
||||||
action_core::ActionHandler* active_ = nullptr; ///< non-owning, thuộc registry_
|
action_core::ActionHandler* active_ = nullptr; ///< non-owning, thuộc registry_
|
||||||
|
ComponentStatusBoard* status_board_ = nullptr; ///< non-owning, null = không khai
|
||||||
std::string active_action_id_;
|
std::string active_action_id_;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -23,18 +24,30 @@
|
|||||||
|
|
||||||
#include <robot/node_handle.h>
|
#include <robot/node_handle.h>
|
||||||
#include <robot_nav_core/base_global_planner.h>
|
#include <robot_nav_core/base_global_planner.h>
|
||||||
|
#include <robot_nav_core/preemptable.h>
|
||||||
|
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
#include <move_base2/io/runtime_stats.h>
|
#include <move_base2/io/runtime_stats.h>
|
||||||
#include <move_base2/ports/planner_port.h>
|
#include <move_base2/ports/planner_port.h>
|
||||||
|
|
||||||
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,
|
||||||
@@ -74,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.
|
||||||
*/
|
*/
|
||||||
@@ -120,23 +151,44 @@ public:
|
|||||||
*/
|
*/
|
||||||
void attachStats(RuntimeStats* stats);
|
void attachStats(RuntimeStats* stats);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Gắn bảng trạng thái thành phần (non-owning, null = không khai). Gọi trước @ref configure.
|
||||||
|
*
|
||||||
|
* Runner là CHỦ hàng `kGlobalPlanner`: kBusy khi thread bắt đầu makePlan, kStopping khi
|
||||||
|
* @ref cancelPlan tới mà lượt còn chạy, kIdle khi makePlan trả về. Mọi lời ghi đều dưới `mutex_`
|
||||||
|
* nên dù từ hai thread vẫn tuần tự.
|
||||||
|
*/
|
||||||
|
void attachStatusBoard(ComponentStatusBoard* board);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Tắt việc khoá costmap mutex quanh makePlan — CHỈ dành cho unit test.
|
* @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;
|
||||||
|
|
||||||
@@ -151,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ỷ.
|
||||||
*
|
*
|
||||||
@@ -174,6 +239,9 @@ private:
|
|||||||
/// @brief Thân thread: ngủ tới khi có yêu cầu, chạy plugin, đặt kết quả vào hộp thư.
|
/// @brief Thân thread: ngủ tới khi có yêu cầu, chạy plugin, đặt kết quả vào hộp thư.
|
||||||
void threadBody();
|
void threadBody();
|
||||||
|
|
||||||
|
/// @brief Gọi `preempt()` trên instance đang ở trong makePlan (nếu nó Preemptable). Gọi dưới mutex_.
|
||||||
|
void preemptRunningLocked();
|
||||||
|
|
||||||
// --- Chỉ control thread chạm ------------------------------------------------------------------
|
// --- Chỉ control thread chạm ------------------------------------------------------------------
|
||||||
robot::NodeHandle nh_;
|
robot::NodeHandle nh_;
|
||||||
robot_costmap_2d::Costmap2DROBOT* costmap_ = nullptr;
|
robot_costmap_2d::Costmap2DROBOT* costmap_ = nullptr;
|
||||||
@@ -184,6 +252,7 @@ private:
|
|||||||
|
|
||||||
/// Telemetry non-owning, null = tắt đo. Chỉ đọc sau khi @ref attachStats.
|
/// Telemetry non-owning, null = tắt đo. Chỉ đọc sau khi @ref attachStats.
|
||||||
RuntimeStats* stats_ = nullptr;
|
RuntimeStats* stats_ = nullptr;
|
||||||
|
ComponentStatusBoard* status_board_ = nullptr; ///< Non-owning, null = không khai.
|
||||||
RuntimeStats::SectionId section_make_plan_ = RuntimeStats::kInvalidSection;
|
RuntimeStats::SectionId section_make_plan_ = RuntimeStats::kInvalidSection;
|
||||||
|
|
||||||
std::map<std::string, Loaded> planners_;
|
std::map<std::string, Loaded> planners_;
|
||||||
@@ -211,8 +280,31 @@ 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_`).
|
||||||
|
*
|
||||||
|
* Khác `active_`: swapPlanner() đổi `active_` ngay cả khi lượt cũ chưa về, nên preempt qua
|
||||||
|
* `active_` sau một lần đổi planner sẽ cắt nhầm instance mới (rảnh) và bỏ sót instance cũ (đang
|
||||||
|
* chạy). Mọi đường cắt — cancelPlan, swapPlanner, destructor — đều đi qua con trỏ này.
|
||||||
|
*/
|
||||||
|
robot_nav_core::BaseGlobalPlanner* running_planner_ = nullptr;
|
||||||
robot_geometry_msgs::PoseStamped request_start_;
|
robot_geometry_msgs::PoseStamped request_start_;
|
||||||
robot_geometry_msgs::PoseStamped request_goal_;
|
robot_geometry_msgs::PoseStamped request_goal_;
|
||||||
std::shared_ptr<robot_protocol_msgs::Order> request_order_;
|
std::shared_ptr<robot_protocol_msgs::Order> request_order_;
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
#include <recovery_core/adapters/costmap_collision_checker.h>
|
#include <recovery_core/adapters/costmap_collision_checker.h>
|
||||||
#include <recovery_core/recovery_registry.h>
|
#include <recovery_core/recovery_registry.h>
|
||||||
|
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
#include <move_base2/ports/clock_port.h>
|
#include <move_base2/ports/clock_port.h>
|
||||||
#include <move_base2/ports/pose_port.h>
|
#include <move_base2/ports/pose_port.h>
|
||||||
#include <move_base2/ports/recovery_port.h>
|
#include <move_base2/ports/recovery_port.h>
|
||||||
@@ -125,6 +126,19 @@ public:
|
|||||||
void cancel() override;
|
void cancel() override;
|
||||||
std::string behaviorName(std::size_t index) const override;
|
std::string behaviorName(std::size_t index) const override;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Gắn bảng trạng thái thành phần (non-owning, null = không khai).
|
||||||
|
*
|
||||||
|
* Runner là CHỦ hàng `kRecovery`: kBusy từ @ref start thành công, `progress()` mỗi @ref update,
|
||||||
|
* kIdle khi tick trả terminal hoặc khi @ref cancel — behavior họ velocity/one-shot dừng ngay
|
||||||
|
* trong cùng cycle (arbiter phát 0), behavior có việc chạy dài phải xong việc đó ngay trong
|
||||||
|
* `cancel()` của nó (contract `onCancelRequested()`, pha 2) nên sau cancel() hàng về idle là đúng.
|
||||||
|
*/
|
||||||
|
void attachStatusBoard(ComponentStatusBoard* board)
|
||||||
|
{
|
||||||
|
status_board_ = board;
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/// Chuyển `PosePort` của lõi thành cổng pose của recovery_core.
|
/// Chuyển `PosePort` của lõi thành cổng pose của recovery_core.
|
||||||
class PoseBridge final : public recovery_core::PoseProvider
|
class PoseBridge final : public recovery_core::PoseProvider
|
||||||
@@ -186,6 +200,7 @@ private:
|
|||||||
|
|
||||||
bool configured_ = false;
|
bool configured_ = false;
|
||||||
recovery_core::RecoveryBehavior* active_ = nullptr; ///< non-owning, thuộc registry_
|
recovery_core::RecoveryBehavior* active_ = nullptr; ///< non-owning, thuộc registry_
|
||||||
|
ComponentStatusBoard* status_board_ = nullptr; ///< non-owning, null = không khai
|
||||||
|
|
||||||
/// Tên + trigger của lượt đang chạy, giữ để log được sườn KẾT THÚC (active_ bị xoá ở đó).
|
/// Tên + trigger của lượt đang chạy, giữ để log được sườn KẾT THÚC (active_ bị xoá ở đó).
|
||||||
std::string active_name_;
|
std::string active_name_;
|
||||||
|
|||||||
@@ -93,6 +93,8 @@ NavigationRequest MissionAdapterBridge::toRequest(const mission_adapters::Missio
|
|||||||
// Đích đến muộn đi qua nguyên vẹn; `ControlLoop::submit` mới là chỗ quy về pose tuyệt đối.
|
// Đích đến muộn đi qua nguyên vẹn; `ControlLoop::submit` mới là chỗ quy về pose tuyệt đối.
|
||||||
request.goal_frame = mission.goal_frame;
|
request.goal_frame = mission.goal_frame;
|
||||||
request.relative_distance = mission.relative_distance;
|
request.relative_distance = mission.relative_distance;
|
||||||
|
// [rad] Mission layer đã quy từ độ sang radian tại biên đọc payload; ở đây chỉ chở qua.
|
||||||
|
request.relative_yaw = mission.relative_yaw;
|
||||||
|
|
||||||
// Chặng của order PHẢI mang theo phần order của nó. Global planner cấu hình cho profile position
|
// Chặng của order PHẢI mang theo phần order của nó. Global planner cấu hình cho profile position
|
||||||
// là `CustomPlanner`, mà lớp này chỉ hiện thực nhánh `makePlan(Order, start, goal, plan)`; nhánh
|
// là `CustomPlanner`, mà lớp này chỉ hiện thực nhánh `makePlan(Order, start, goal, plan)`; nhánh
|
||||||
|
|||||||
58
src/component_status.cpp
Normal file
58
src/component_status.cpp
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* move_base2 — tên hiển thị cho bảng trạng thái thành phần.
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
|
|
||||||
|
namespace move_base2
|
||||||
|
{
|
||||||
|
|
||||||
|
const char* toString(Component component)
|
||||||
|
{
|
||||||
|
switch (component)
|
||||||
|
{
|
||||||
|
case Component::kGlobalPlanner:
|
||||||
|
return "global_planner";
|
||||||
|
case Component::kLocalPlanner:
|
||||||
|
return "local_planner";
|
||||||
|
case Component::kRecovery:
|
||||||
|
return "recovery";
|
||||||
|
case Component::kAction:
|
||||||
|
return "action";
|
||||||
|
case Component::kCostmapGlobal:
|
||||||
|
return "costmap_global";
|
||||||
|
case Component::kCostmapLocal:
|
||||||
|
return "costmap_local";
|
||||||
|
case Component::kControlLoop:
|
||||||
|
return "control_loop";
|
||||||
|
case Component::kCount:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* toString(ComponentPhase phase)
|
||||||
|
{
|
||||||
|
switch (phase)
|
||||||
|
{
|
||||||
|
case ComponentPhase::kIdle:
|
||||||
|
return "idle";
|
||||||
|
case ComponentPhase::kBusy:
|
||||||
|
return "busy";
|
||||||
|
case ComponentPhase::kStopping:
|
||||||
|
return "stopping";
|
||||||
|
case ComponentPhase::kPaused:
|
||||||
|
return "paused";
|
||||||
|
case ComponentPhase::kHung:
|
||||||
|
return "hung";
|
||||||
|
case ComponentPhase::kWaitingForCostmap:
|
||||||
|
return "waiting_for_costmap";
|
||||||
|
}
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace move_base2
|
||||||
@@ -146,7 +146,14 @@ 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, "local_planner_call_budget", config.watchdog.local_planner_call_budget);
|
||||||
|
readDouble(nh, "recovery_stall_budget", config.watchdog.recovery_stall_budget);
|
||||||
|
readDouble(nh, "action_stall_budget", config.watchdog.action_stall_budget);
|
||||||
|
readDouble(nh, "control_loop_stall_budget", config.watchdog.control_loop_stall_budget);
|
||||||
|
config.watchdog.planner_timeout = config.planner_timeout;
|
||||||
|
|
||||||
readDouble(nh, "planner_patience", config.state_machine.planner_patience);
|
readDouble(nh, "planner_patience", config.state_machine.planner_patience);
|
||||||
readDouble(nh, "controller_patience", config.state_machine.controller_patience);
|
readDouble(nh, "controller_patience", config.state_machine.controller_patience);
|
||||||
@@ -157,6 +164,9 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
|||||||
readDouble(nh, "action_patience", config.state_machine.action_patience);
|
readDouble(nh, "action_patience", config.state_machine.action_patience);
|
||||||
readInt(nh, "max_planning_retries", config.state_machine.max_planning_retries);
|
readInt(nh, "max_planning_retries", config.state_machine.max_planning_retries);
|
||||||
readBool(nh, "recovery_behavior_enabled", config.state_machine.recovery_enabled);
|
readBool(nh, "recovery_behavior_enabled", config.state_machine.recovery_enabled);
|
||||||
|
readDouble(nh, "settle_timeout", config.state_machine.settle_timeout);
|
||||||
|
readDouble(nh, "stopped_measured_linear_eps", config.state_machine.stopped_measured_linear_eps);
|
||||||
|
readDouble(nh, "stopped_measured_angular_eps", config.state_machine.stopped_measured_angular_eps);
|
||||||
|
|
||||||
// Nghĩa của Twist đi qua arbiter — quyết định đơn vị của cả cụm giới hạn bên dưới. "steering"
|
// Nghĩa của Twist đi qua arbiter — quyết định đơn vị của cả cụm giới hạn bên dưới. "steering"
|
||||||
// (linear.x = tốc độ bánh steer, angular.z = GÓC lái) là convention của robot lái một bánh
|
// (linear.x = tốc độ bánh steer, angular.z = GÓC lái) là convention của robot lái một bánh
|
||||||
@@ -426,6 +436,15 @@ 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))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0)
|
if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0)
|
||||||
{
|
{
|
||||||
@@ -523,8 +542,11 @@ 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 << " frames: global='" << global_frame << "' base='" << robot_base_frame << "'\n";
|
out << " frames: global='" << global_frame << "' base='" << robot_base_frame << "'\n";
|
||||||
out << " require_current_costmap: " << (require_current_costmap ? "true" : "false") << "\n";
|
out << " require_current_costmap: " << (require_current_costmap ? "true" : "false") << "\n";
|
||||||
out << " namespaces: recovery='" << recovery_namespace << "' actions='" << action_namespace
|
out << " namespaces: recovery='" << recovery_namespace << "' actions='" << action_namespace
|
||||||
@@ -568,9 +590,17 @@ 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);
|
||||||
|
// Watchdog (2026-09-11) — không có trong schema gen-1; thiếu khoá thì default (bật, 0.1 s).
|
||||||
|
readDouble(nh, "watchdog_period", watchdog.period);
|
||||||
|
readDouble(nh, "local_planner_call_budget", watchdog.local_planner_call_budget);
|
||||||
|
readDouble(nh, "recovery_stall_budget", watchdog.recovery_stall_budget);
|
||||||
|
readDouble(nh, "action_stall_budget", watchdog.action_stall_budget);
|
||||||
|
readDouble(nh, "control_loop_stall_budget", watchdog.control_loop_stall_budget);
|
||||||
|
watchdog.planner_timeout = planner_timeout;
|
||||||
readDouble(nh, "planner_patience", state_machine.planner_patience);
|
readDouble(nh, "planner_patience", state_machine.planner_patience);
|
||||||
readDouble(nh, "controller_patience", state_machine.controller_patience);
|
readDouble(nh, "controller_patience", state_machine.controller_patience);
|
||||||
readDouble(nh, "sensor_patience", state_machine.sensor_patience);
|
readDouble(nh, "sensor_patience", state_machine.sensor_patience);
|
||||||
@@ -578,6 +608,11 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
|||||||
readDouble(nh, "oscillation_distance", state_machine.oscillation_distance);
|
readDouble(nh, "oscillation_distance", state_machine.oscillation_distance);
|
||||||
readInt(nh, "max_planning_retries", state_machine.max_planning_retries);
|
readInt(nh, "max_planning_retries", state_machine.max_planning_retries);
|
||||||
readBool(nh, "recovery_behavior_enabled", state_machine.recovery_enabled);
|
readBool(nh, "recovery_behavior_enabled", state_machine.recovery_enabled);
|
||||||
|
// Không có trong schema gen-1 (bản cũ báo CANCELLED ngay khi lệnh về 0) — đọc để cây config cũ
|
||||||
|
// vẫn bật được chờ quiescent; thiếu khoá thì dùng default (bật, 2 s).
|
||||||
|
readDouble(nh, "settle_timeout", state_machine.settle_timeout);
|
||||||
|
readDouble(nh, "stopped_measured_linear_eps", state_machine.stopped_measured_linear_eps);
|
||||||
|
readDouble(nh, "stopped_measured_angular_eps", state_machine.stopped_measured_angular_eps);
|
||||||
|
|
||||||
readString(nh, "global_frame", global_frame);
|
readString(nh, "global_frame", global_frame);
|
||||||
readString(nh, "robot_base_frame", robot_base_frame);
|
readString(nh, "robot_base_frame", robot_base_frame);
|
||||||
@@ -705,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]
|
||||||
|
|||||||
@@ -25,6 +25,13 @@ namespace
|
|||||||
/// [-] Sai lệch chuẩn quaternion còn chấp nhận được trước khi coi goal là hỏng.
|
/// [-] Sai lệch chuẩn quaternion còn chấp nhận được trước khi coi goal là hỏng.
|
||||||
constexpr double kQuaternionNormTolerance = 1e-2;
|
constexpr double kQuaternionNormTolerance = 1e-2;
|
||||||
|
|
||||||
|
/// @brief Yaw [rad] của một pose. Robot chạy trên mặt phẳng nên chỉ z-w của quaternion có nghĩa.
|
||||||
|
double yawOf(const robot_geometry_msgs::PoseStamped& pose)
|
||||||
|
{
|
||||||
|
const auto& q = pose.pose.orientation;
|
||||||
|
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
|
||||||
|
}
|
||||||
|
|
||||||
/// [s] Giãn cách log cho guard "không đi mù". Tình trạng này kéo dài hàng giây, và đây là vòng lặp
|
/// [s] Giãn cách log cho guard "không đi mù". Tình trạng này kéo dài hàng giây, và đây là vòng lặp
|
||||||
/// điều khiển — log mỗi cycle sẽ nhấn chìm mọi dòng khác.
|
/// điều khiển — log mỗi cycle sẽ nhấn chìm mọi dòng khác.
|
||||||
constexpr double kStaleCostmapLogThrottle = 5.0;
|
constexpr double kStaleCostmapLogThrottle = 5.0;
|
||||||
@@ -41,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:
|
||||||
@@ -89,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;
|
||||||
@@ -232,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)
|
||||||
@@ -296,6 +311,7 @@ void ControlLoop::reset()
|
|||||||
pause_requested_ = false;
|
pause_requested_ = false;
|
||||||
resume_requested_ = false;
|
resume_requested_ = false;
|
||||||
cancel_requested_ = false;
|
cancel_requested_ = false;
|
||||||
|
emergency_ = false;
|
||||||
|
|
||||||
planner_feedback_ = PlannerFeedback::kIdle;
|
planner_feedback_ = PlannerFeedback::kIdle;
|
||||||
controller_feedback_ = ControllerFeedback::kIdle;
|
controller_feedback_ = ControllerFeedback::kIdle;
|
||||||
@@ -370,8 +386,11 @@ bool ControlLoop::resolveDeferredGoal(NavigationRequest& request, std::string& r
|
|||||||
{
|
{
|
||||||
const bool has_frame = !request.goal_frame.empty();
|
const bool has_frame = !request.goal_frame.empty();
|
||||||
const bool has_distance = std::isfinite(request.relative_distance);
|
const bool has_distance = std::isfinite(request.relative_distance);
|
||||||
|
// Góc quay ĐI KÈM được với hai nguồn đích kia, không loại trừ: chặng quay tại chỗ là
|
||||||
|
// relative_distance = 0 cộng một góc khác 0.
|
||||||
|
const bool has_yaw = std::isfinite(request.relative_yaw);
|
||||||
|
|
||||||
if (!has_frame && !has_distance)
|
if (!has_frame && !has_distance && !has_yaw)
|
||||||
{
|
{
|
||||||
return true; // Goal tuyệt đối, không có gì phải quy.
|
return true; // Goal tuyệt đối, không có gì phải quy.
|
||||||
}
|
}
|
||||||
@@ -389,6 +408,19 @@ bool ControlLoop::resolveDeferredGoal(NavigationRequest& request, std::string& r
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pose hiện tại: cần cho quãng tương đối, và cần cho góc tương đối kể cả khi vị trí đích tới từ
|
||||||
|
// một TF frame — góc luôn tính so với hướng robot đang quay về LÚC chặng được nhận.
|
||||||
|
robot_geometry_msgs::PoseStamped robot_pose;
|
||||||
|
const bool needs_robot_pose = has_distance || has_yaw;
|
||||||
|
if (needs_robot_pose && !deps_.pose->getRobotPose(robot_pose))
|
||||||
|
{
|
||||||
|
// Mất định vị thì không quy được quãng đường tương đối. Đoán ở đây là robot đi mù một đoạn.
|
||||||
|
reason = "a relative goal needs the robot pose, which is not available";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const double robot_yaw = needs_robot_pose ? yawOf(robot_pose) : 0.0;
|
||||||
|
|
||||||
if (has_frame)
|
if (has_frame)
|
||||||
{
|
{
|
||||||
if (!deps_.pose->lookupPose(request.goal_frame, request.goal))
|
if (!deps_.pose->lookupPose(request.goal_frame, request.goal))
|
||||||
@@ -396,23 +428,34 @@ bool ControlLoop::resolveDeferredGoal(NavigationRequest& request, std::string& r
|
|||||||
reason = "cannot resolve goal_frame '" + request.goal_frame + "'";
|
reason = "cannot resolve goal_frame '" + request.goal_frame + "'";
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
else if (has_distance)
|
||||||
robot_geometry_msgs::PoseStamped robot_pose;
|
|
||||||
if (!deps_.pose->getRobotPose(robot_pose))
|
|
||||||
{
|
{
|
||||||
// Mất định vị thì không quy được quãng đường tương đối. Đoán ở đây là robot đi mù một đoạn.
|
request.goal = robot_pose;
|
||||||
reason = "relative_distance needs the robot pose, which is not available";
|
request.goal.pose.position.x += request.relative_distance * std::cos(robot_yaw);
|
||||||
return false;
|
request.goal.pose.position.y += request.relative_distance * std::sin(robot_yaw);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Chỉ có góc: đích là chính chỗ robot đang đứng, chỉ khác hướng.
|
||||||
|
request.goal = robot_pose;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (has_yaw)
|
||||||
|
{
|
||||||
|
// Hướng đích = hướng HIỆN TẠI cộng góc yêu cầu. Ghi đè orientation của goal chứ không cộng dồn
|
||||||
|
// vào orientation vừa lấy ở trên: với has_frame, orientation của frame đích là hướng của trạm
|
||||||
|
// chứ không phải hướng robot, và chặng quay nói về robot.
|
||||||
|
//
|
||||||
|
// Không normalize góc tổng: mission layer đã chặn ở [-pi, pi], và quaternion tự bọc.
|
||||||
|
const double goal_yaw = robot_yaw + request.relative_yaw;
|
||||||
|
const double half = 0.5 * goal_yaw;
|
||||||
|
request.goal.pose.orientation.x = 0.0;
|
||||||
|
request.goal.pose.orientation.y = 0.0;
|
||||||
|
request.goal.pose.orientation.z = std::sin(half);
|
||||||
|
request.goal.pose.orientation.w = std::cos(half);
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto& q = robot_pose.pose.orientation;
|
|
||||||
const double yaw = std::atan2(2.0 * (q.w * q.z + q.x * q.y),
|
|
||||||
1.0 - 2.0 * (q.y * q.y + q.z * q.z)); // [rad]
|
|
||||||
request.goal = robot_pose;
|
|
||||||
request.goal.pose.position.x += request.relative_distance * std::cos(yaw);
|
|
||||||
request.goal.pose.position.y += request.relative_distance * std::sin(yaw);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -427,6 +470,14 @@ bool ControlLoop::submit(const NavigationRequest& incoming, std::string& reason)
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Hàng rào thứ hai (hàng rào một ở NavigationServer, trước cả mission layer): đang giữ dừng khẩn
|
||||||
|
// thì không có goal nào được xếp chờ — xếp chờ là sau khi gỡ chốt robot tự chạy mà không ai gửi.
|
||||||
|
if (emergency_)
|
||||||
|
{
|
||||||
|
reason = "emergency stop latched";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// D8: yêu cầu mang action cần có ActionPort; từ chối tại cửa thay vì kẹt sau khi tới goal.
|
// D8: yêu cầu mang action cần có ActionPort; từ chối tại cửa thay vì kẹt sau khi tới goal.
|
||||||
if (!request.actions.empty() && deps_.action == nullptr)
|
if (!request.actions.empty() && deps_.action == nullptr)
|
||||||
{
|
{
|
||||||
@@ -544,6 +595,31 @@ void ControlLoop::requestCancel()
|
|||||||
cancel_requested_ = true;
|
cancel_requested_ = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void ControlLoop::requestEmergency()
|
||||||
|
{
|
||||||
|
if (!emergency_)
|
||||||
|
{
|
||||||
|
// Sườn lên: LỖI mức vận hành, không gắn [debug], không có khoá tắt — dòng này là bằng chứng
|
||||||
|
// duy nhất trong log rằng robot dừng vì lệnh khẩn chứ không phải vì hỏng.
|
||||||
|
robot::log_warning("[move_base2] EMERGENCY STOP latched (mission %llu%s): command zero, planner/"
|
||||||
|
"recovery/action cancelled, mission queue wiped. Goals are rejected until "
|
||||||
|
"clearEmergency().\n",
|
||||||
|
static_cast<unsigned long long>(has_active_request_ ? active_request_.mission_sequence_id : 0),
|
||||||
|
has_pending_request_ ? ", pending request dropped" : "");
|
||||||
|
}
|
||||||
|
emergency_ = true;
|
||||||
|
has_pending_request_ = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlLoop::requestClearEmergency()
|
||||||
|
{
|
||||||
|
if (emergency_)
|
||||||
|
{
|
||||||
|
robot::log_info("[move_base2] emergency cleared: back to IDLE, waiting for a new goal.\n");
|
||||||
|
}
|
||||||
|
emergency_ = false;
|
||||||
|
}
|
||||||
|
|
||||||
void ControlLoop::collectPlannerResult()
|
void ControlLoop::collectPlannerResult()
|
||||||
{
|
{
|
||||||
PlanResult result;
|
PlanResult result;
|
||||||
@@ -587,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;
|
||||||
@@ -601,12 +694,14 @@ 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ờ.
|
// 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 "
|
robot::log_error("[move_base2] global planner '%s' failed and backup '%s' could not be "
|
||||||
"loaded; starting recovery.\n",
|
"loaded; starting recovery.\n",
|
||||||
failed_planner.c_str(), config_.backup_global_planner_name.c_str());
|
failed_planner.c_str(), config_.backup_global_planner_name.c_str());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
planner_feedback_ = PlannerFeedback::kFailed;
|
planner_feedback_ = PlannerFeedback::kFailed;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -620,6 +715,23 @@ void ControlLoop::collectPlannerResult()
|
|||||||
planner_feedback_ = PlannerFeedback::kPlanReady;
|
planner_feedback_ = PlannerFeedback::kPlanReady;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool ControlLoop::robotStopped() const
|
||||||
|
{
|
||||||
|
const StateMachineConfig& sm = config_.state_machine;
|
||||||
|
const bool use_measured = sm.stopped_measured_linear_eps > 0.0 || sm.stopped_measured_angular_eps > 0.0;
|
||||||
|
|
||||||
|
robot_geometry_msgs::Twist measured;
|
||||||
|
if (use_measured && deps_.controller != nullptr && deps_.controller->measuredVelocity(measured))
|
||||||
|
{
|
||||||
|
// Odom đo được thì nó là sự thật về bánh xe; lệnh đã phát chỉ là ý định. NaN từ odom rơi vào
|
||||||
|
// nhánh "chưa dừng" (so sánh với NaN luôn false) — an toàn: settle_timeout là trần.
|
||||||
|
return std::fabs(measured.linear.x) <= sm.stopped_measured_linear_eps &&
|
||||||
|
std::fabs(measured.linear.y) <= sm.stopped_measured_linear_eps &&
|
||||||
|
std::fabs(measured.angular.z) <= sm.stopped_measured_angular_eps;
|
||||||
|
}
|
||||||
|
return arbiter_.stopped();
|
||||||
|
}
|
||||||
|
|
||||||
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||||
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
|
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
|
||||||
bool costmap_stale)
|
bool costmap_stale)
|
||||||
@@ -807,10 +919,42 @@ void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
|
|||||||
{
|
{
|
||||||
candidate = robot_geometry_msgs::Twist();
|
candidate = robot_geometry_msgs::Twist();
|
||||||
|
|
||||||
|
// Hàng local_planner của bảng trạng thái: bận trong suốt lượt gọi plugin (đồng bộ, cùng thread),
|
||||||
|
// rảnh khi ra. Watchdog (pha 4) dùng nó để bắt local planner treo — control thread không tự bắt
|
||||||
|
// được chính mình. RAII để mọi đường thoát (kể cả exception từ plugin) đều trả về idle.
|
||||||
|
struct LocalPlannerBusyScope
|
||||||
|
{
|
||||||
|
explicit LocalPlannerBusyScope(ComponentStatusBoard* board) : board_(board)
|
||||||
|
{
|
||||||
|
if (board_ != nullptr)
|
||||||
|
{
|
||||||
|
board_->enter(Component::kLocalPlanner, ComponentPhase::kBusy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
~LocalPlannerBusyScope()
|
||||||
|
{
|
||||||
|
if (board_ != nullptr)
|
||||||
|
{
|
||||||
|
board_->enter(Component::kLocalPlanner, ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ComponentStatusBoard* board_;
|
||||||
|
} local_planner_busy(deps_.components);
|
||||||
|
|
||||||
// Giữ nguyên thứ tự của interface được bọc: hỏi đã tới đích trước, chỉ khi chưa mới tính lệnh.
|
// Giữ nguyên thứ tự của interface được bọc: hỏi đã tới đích trước, chỉ khi chưa mới tính lệnh.
|
||||||
if (deps_.controller->isGoalReached())
|
if (deps_.controller->isGoalReached())
|
||||||
{
|
{
|
||||||
controller_feedback_ = ControllerFeedback::kGoalReached;
|
controller_feedback_ = ControllerFeedback::kGoalReached;
|
||||||
|
if (config_.debug_plan)
|
||||||
|
{
|
||||||
|
// Nhánh này trả candidate RỖNG — không có lệnh nào được tính ở cycle này. Một planner báo
|
||||||
|
// "đã tới" ngay từ cycle đầu (trước khi computeVelocityCommands từng chạy lần nào) là triệu
|
||||||
|
// chứng ĐÚNG của "robot đứng im, không phát lệnh": không phải lệnh bị chặn, mà chưa bao giờ
|
||||||
|
// có lệnh nào được tính.
|
||||||
|
robot::log_info_throttle(kDebugControlLogThrottle,
|
||||||
|
"[move_base2][debug] runController: isGoalReached() = true -- "
|
||||||
|
"không tính lệnh cycle này (candidate = 0).\n");
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -819,6 +963,16 @@ void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
|
|||||||
{
|
{
|
||||||
controller_feedback_ = ControllerFeedback::kCommandValid;
|
controller_feedback_ = ControllerFeedback::kCommandValid;
|
||||||
candidate = cmd;
|
candidate = cmd;
|
||||||
|
if (config_.debug_plan)
|
||||||
|
{
|
||||||
|
// v/omega TRƯỚC VelocityArbiter — phân biệt "planner không phát lệnh" (giá trị ở đây đã là
|
||||||
|
// 0 hoặc gần 0) với "lệnh phát ra nhưng bị guard/arbiter cắt về 0 phía sau" (giá trị ở đây
|
||||||
|
// khác 0 nhưng /cmd_vel lại là 0 — xem log EnvMonitor / VelocityArbiter cho cycle này).
|
||||||
|
robot::log_info_throttle(kDebugControlLogThrottle,
|
||||||
|
"[move_base2][debug] runController: command_valid v=%.3f m/s "
|
||||||
|
"omega=%.4f rad/s (trước arbiter).\n",
|
||||||
|
cmd.linear.x, cmd.angular.z);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -887,16 +1041,41 @@ bool ControlLoop::step()
|
|||||||
input.pause_requested = pause_requested_;
|
input.pause_requested = pause_requested_;
|
||||||
input.resume_requested = resume_requested_;
|
input.resume_requested = resume_requested_;
|
||||||
input.cancel_requested = cancel_requested_;
|
input.cancel_requested = cancel_requested_;
|
||||||
|
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_;
|
||||||
input.action_message = action_message_;
|
input.action_message = action_message_;
|
||||||
input.pose_available = pose_available;
|
input.pose_available = pose_available;
|
||||||
input.costmap_current = !costmap_stale;
|
input.costmap_current = !costmap_stale;
|
||||||
input.robot_stopped = arbiter_.stopped();
|
input.robot_stopped = robotStopped();
|
||||||
|
// Điều kiện quiescent của kCancelling/kPausing (2026-09-11). `isPlanning()` là true cả khi lượt
|
||||||
|
// đang chạy đã bị `cancelPlan()` — plugin không cắt được thì thread vẫn bận, và đó chính là thứ
|
||||||
|
// host phải chờ. Bảng trạng thái thành phần (nếu có) bổ sung hàng recovery/action mà cổng không
|
||||||
|
// hỏi được; hàng global_planner của bảng chỉ CỘNG thêm, cổng vẫn là câu hỏi gốc. Action: chưa có
|
||||||
|
// handshake cancelling→cancelled ở cổng (pha 3) — không có bảng thì coi là terminal ngay.
|
||||||
|
{
|
||||||
|
const ComponentStatusBoard* board = deps_.components;
|
||||||
|
input.planner_busy = deps_.planner->isPlanning() ||
|
||||||
|
(board != nullptr && !board->isIdle(Component::kGlobalPlanner));
|
||||||
|
input.recovery_busy = board != nullptr && !board->isIdle(Component::kRecovery);
|
||||||
|
if (board != nullptr)
|
||||||
|
{
|
||||||
|
const ComponentPhase action_phase = board->phase(Component::kAction);
|
||||||
|
input.action_terminal =
|
||||||
|
action_phase == ComponentPhase::kIdle || action_phase == ComponentPhase::kPaused;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
input.action_terminal = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
input.travelled_since_oscillation_reset = travelled;
|
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;
|
||||||
@@ -926,6 +1105,21 @@ bool ControlLoop::step()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (output.settle_timed_out)
|
||||||
|
{
|
||||||
|
// LỖI, không có khoá tắt: CANCELLED/PAUSED được báo ra mà runtime CHƯA im hẳn. Host sẽ tin và
|
||||||
|
// gửi goal kế; goal kế chờ được nhờ kBusy, nhưng nguyên nhân gốc (plugin không cắt được
|
||||||
|
// makePlan, odom không về 0, action không trả terminal) phải lộ ra ở đây, kèm thành phần nào.
|
||||||
|
robot::log_error("[move_base2] settle timeout %.1f s while %s (mission %llu): finishing anyway — "
|
||||||
|
"planner_busy=%s recovery_busy=%s action_terminal=%s robot_stopped=%s. A plugin "
|
||||||
|
"is not honouring cancel/pause, or odometry never reads zero.\n",
|
||||||
|
config_.state_machine.settle_timeout,
|
||||||
|
output.state == NavigationState::kPaused ? "PAUSING" : "CANCELLING",
|
||||||
|
static_cast<unsigned long long>(has_active_request_ ? active_request_.mission_sequence_id : 0),
|
||||||
|
input.planner_busy ? "yes" : "no", input.recovery_busy ? "yes" : "no",
|
||||||
|
input.action_terminal ? "yes" : "no", input.robot_stopped ? "yes" : "no");
|
||||||
|
}
|
||||||
|
|
||||||
// Cờ một-lần đã được state machine tiêu thụ xong ở lời gọi trên.
|
// Cờ một-lần đã được state machine tiêu thụ xong ở lời gọi trên.
|
||||||
pause_requested_ = false;
|
pause_requested_ = false;
|
||||||
resume_requested_ = false;
|
resume_requested_ = false;
|
||||||
@@ -958,10 +1152,12 @@ bool ControlLoop::step()
|
|||||||
// Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop.
|
// Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop.
|
||||||
if (active_request_.has_goal)
|
if (active_request_.has_goal)
|
||||||
{
|
{
|
||||||
robot::log_info("[move_base2] Goal received (mission %llu): x=%.3f y=%.3f frame=%s.\n",
|
// yaw có mặt ở đây vì một chặng quay tại chỗ KHÁC chặng thường đúng ở con số này: x, y giữ
|
||||||
|
// nguyên và chỉ hướng đổi. Thiếu nó thì một chặng quay hỏng trông y hệt một chặng quay đúng.
|
||||||
|
robot::log_info("[move_base2] Goal received (mission %llu): x=%.3f y=%.3f yaw=%.4f frame=%s.\n",
|
||||||
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
||||||
active_request_.goal.pose.position.x, active_request_.goal.pose.position.y,
|
active_request_.goal.pose.position.x, active_request_.goal.pose.position.y,
|
||||||
active_request_.goal.header.frame_id.c_str());
|
yawOf(active_request_.goal), active_request_.goal.header.frame_id.c_str());
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -1022,13 +1218,16 @@ bool ControlLoop::step()
|
|||||||
|
|
||||||
if (config_.debug_plan)
|
if (config_.debug_plan)
|
||||||
{
|
{
|
||||||
|
// yaw của pose CUỐI: đây là thứ setGoalPose() thực sự trao cho local planner. Chặng quay
|
||||||
|
// tại chỗ có first/last CÙNG vị trí — không có yaw ở đây thì log không phân biệt được
|
||||||
|
// "goal đúng nhưng chưa quay tới" với "goal sai ngay từ khi lập plan".
|
||||||
robot::log_info("[move_base2][debug] controller accepted plan with %zu pose(s); "
|
robot::log_info("[move_base2][debug] controller accepted plan with %zu pose(s); "
|
||||||
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
|
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, yaw=%.4f, frame=%s).\n",
|
||||||
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
||||||
latest_plan_.front().pose.position.y,
|
latest_plan_.front().pose.position.y,
|
||||||
latest_plan_.front().header.frame_id.c_str(),
|
latest_plan_.front().header.frame_id.c_str(),
|
||||||
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
||||||
latest_plan_.back().header.frame_id.c_str());
|
yawOf(latest_plan_.back()), latest_plan_.back().header.frame_id.c_str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1123,6 +1322,14 @@ bool ControlLoop::step()
|
|||||||
{
|
{
|
||||||
deps_.action->cancel();
|
deps_.action->cancel();
|
||||||
}
|
}
|
||||||
|
if (output.pause_action && deps_.action != nullptr)
|
||||||
|
{
|
||||||
|
deps_.action->pause();
|
||||||
|
}
|
||||||
|
if (output.resume_action && deps_.action != nullptr)
|
||||||
|
{
|
||||||
|
deps_.action->resume();
|
||||||
|
}
|
||||||
|
|
||||||
if (output.start_action)
|
if (output.start_action)
|
||||||
{
|
{
|
||||||
@@ -1155,6 +1362,13 @@ bool ControlLoop::step()
|
|||||||
robot::log_info("[move_base2] %s\n", tick.message.c_str());
|
robot::log_info("[move_base2] %s\n", tick.message.c_str());
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
case ActionTick::Status::kCancelled:
|
||||||
|
// Handler thiết bị đã về vị trí an toàn sau cancel (pha 3). Chỉ gặp trong CANCELLING/PAUSING;
|
||||||
|
// hàng kAction về idle → quiescent. Một dòng info: đây là sườn kết thúc, không lặp.
|
||||||
|
action_feedback_ = ActionFeedback::kCancelled;
|
||||||
|
robot::log_info("[move_base2] action stopped safely after cancel%s%s\n",
|
||||||
|
tick.message.empty() ? "" : ": ", tick.message.c_str());
|
||||||
|
break;
|
||||||
case ActionTick::Status::kFailed:
|
case ActionTick::Status::kFailed:
|
||||||
action_feedback_ = ActionFeedback::kFailed;
|
action_feedback_ = ActionFeedback::kFailed;
|
||||||
// Handler đã dựng sẵn lý do cụ thể ("thiếu mẫu", "tản quá", "không publish được"). Trước
|
// Handler đã dựng sẵn lý do cụ thể ("thiếu mẫu", "tản quá", "không publish được"). Trước
|
||||||
@@ -1270,12 +1484,6 @@ bool ControlLoop::step()
|
|||||||
output.recovery_route_cursor, output.recovery_route_size);
|
output.recovery_route_cursor, output.recovery_route_size);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// else if (controller_feedback_ == ControllerFeedback::kCommandValid)
|
|
||||||
// {
|
|
||||||
// robot::log_info_throttle(kDebugControlLogThrottle,
|
|
||||||
// "[move_base2][debug] controller command valid: v=%.3f wz=%.3f.\n",
|
|
||||||
// candidate.linear.x, candidate.angular.z);
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replan nền (contract 2026-08-04): đang bám plan và tới nhịp `planner_frequency` thì khởi động
|
// Replan nền (contract 2026-08-04): đang bám plan và tới nhịp `planner_frequency` thì khởi động
|
||||||
@@ -1312,18 +1520,50 @@ bool ControlLoop::step()
|
|||||||
}
|
}
|
||||||
else if (output.start_planner)
|
else if (output.start_planner)
|
||||||
{
|
{
|
||||||
// Không khởi động được (chưa có planner, pose hỏng...). Coi như một lượt hỏng để đồng hồ
|
// Không khởi động được. Hai nguyên nhân khác hẳn nhau, không được gộp (bài học log
|
||||||
// kiên nhẫn tiếp tục chạy, thay vì đứng im ở kPlanning vô hạn. Riêng replan NỀN không khởi
|
// 2026-09-11: cancel lúc SBPL đang chạy, goal kế bị coi là hỏng và ABORTED sau 3 s dù chưa
|
||||||
// động được thì bỏ qua — plan cũ vẫn hiệu lực, nhịp sau thử lại.
|
// lập plan lần nào):
|
||||||
|
// - thread planner còn chạy lượt CŨ đã bị cancelPlan() mà plugin không cắt được → BẬN,
|
||||||
|
// cycle sau thử lại; planner_patience vẫn là trần nếu bận quá lâu;
|
||||||
|
// - chưa có planner, pose hỏng... → HỎNG thật, đồng hồ kiên nhẫn/retry chạy như cũ.
|
||||||
|
// Riêng replan NỀN không khởi động được thì bỏ qua — plan cũ vẫn hiệu lực, nhịp sau thử lại.
|
||||||
|
if (deps_.planner->isPlanning())
|
||||||
|
{
|
||||||
|
planner_feedback_ = PlannerFeedback::kBusy;
|
||||||
|
robot::log_warning_throttle(5.0,
|
||||||
|
"[move_base2] planner thread still busy with a cancelled attempt; "
|
||||||
|
"waiting for it before planning mission %llu (planner_patience "
|
||||||
|
"%.1f s is the ceiling).\n",
|
||||||
|
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
||||||
|
config_.state_machine.planner_patience);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
planner_feedback_ = PlannerFeedback::kFailed;
|
planner_feedback_ = PlannerFeedback::kFailed;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
|
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
|
||||||
// Sắp chạm vật cản thật cũng là "không ai được phát": lệnh 0 tức thì, không giảm dần.
|
// Sắp chạm vật cản thật cũng là "không ai được phát": lệnh 0 tức thì, không giảm dần.
|
||||||
arbiter_.arbitrate((costmap_stale || env_brake_) ? VelocitySource::kNone : output.velocity_source,
|
arbiter_.arbitrate((costmap_stale || env_brake_) ? VelocitySource::kNone : output.velocity_source,
|
||||||
candidate, dt);
|
candidate, dt);
|
||||||
|
|
||||||
|
if (config_.debug_plan && output.run_controller)
|
||||||
|
{
|
||||||
|
// Sau arbiter — thứ AmrPublisher thật sự lấy để phát /cmd_vel. Đối chiếu với dòng
|
||||||
|
// "runController: command_valid v=... omega=... (trước arbiter)" ở trên: hai dòng khác
|
||||||
|
// nhau nghĩa là VelocityArbiter (kẹp trần/gia tốc) hoặc EnvMonitor brake đã sửa lệnh; hai
|
||||||
|
// dòng giống hệt mà /cmd_vel vẫn đo được 0 thì lỗi nằm ngoài move_base2 (AmrPublisher, driver
|
||||||
|
// bánh xe, hoặc sim).
|
||||||
|
const robot_geometry_msgs::Twist& published = arbiter_.lastCommand();
|
||||||
|
robot::log_info_throttle(kDebugControlLogThrottle,
|
||||||
|
"[move_base2][debug] runController: sau arbiter v=%.3f m/s "
|
||||||
|
"omega=%.4f rad/s (nguồn=%s, source_in=%s).\n",
|
||||||
|
published.linear.x, published.angular.z,
|
||||||
|
toString(controller_feedback_), toString(output.velocity_source));
|
||||||
|
}
|
||||||
|
|
||||||
// --- 5. Báo kết quả -------------------------------------------------------------------------
|
// --- 5. Báo kết quả -------------------------------------------------------------------------
|
||||||
if (output.report_outcome)
|
if (output.report_outcome)
|
||||||
{
|
{
|
||||||
@@ -1384,6 +1624,14 @@ bool ControlLoop::step()
|
|||||||
cancel_requested_ = false;
|
cancel_requested_ = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Heartbeat của chính control thread — thứ duy nhất cho watchdog (thread khác) biết vòng điều
|
||||||
|
// khiển còn quay. Đặt ở cuối step(): một cycle kẹt giữa chừng (detour SBPL, plugin treo) không
|
||||||
|
// nhích được mốc này.
|
||||||
|
if (deps_.components != nullptr)
|
||||||
|
{
|
||||||
|
deps_.components->progress(Component::kControlLoop);
|
||||||
|
}
|
||||||
|
|
||||||
// false = "yêu cầu hiện tại vừa kết thúc, không còn gì để chạy". Preempt CŨNG báo kết quả (cho
|
// false = "yêu cầu hiện tại vừa kết thúc, không còn gì để chạy". Preempt CŨNG báo kết quả (cho
|
||||||
// chặng cũ) nhưng ngay lập tức nhận chặng mới — lúc đó runtime vẫn đang chạy, nên không được trả
|
// chặng cũ) nhưng ngay lập tức nhận chặng mới — lúc đó runtime vẫn đang chạy, nên không được trả
|
||||||
// false. Điều kiện đúng là "vào state terminal", không phải "có báo kết quả".
|
// false. Điều kiện đúng là "vào state terminal", không phải "có báo kết quả".
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
213
src/io/watchdog.cpp
Normal file
213
src/io/watchdog.cpp
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* move_base2 — watchdog thành phần treo.
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#include <move_base2/io/watchdog.h>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cmath>
|
||||||
|
#include <sstream>
|
||||||
|
|
||||||
|
#include <robot/console.h>
|
||||||
|
|
||||||
|
namespace move_base2
|
||||||
|
{
|
||||||
|
|
||||||
|
bool WatchdogConfig::validate(std::string& error) const
|
||||||
|
{
|
||||||
|
const double values[] = {period, planner_timeout, local_planner_call_budget,
|
||||||
|
recovery_stall_budget, action_stall_budget, control_loop_stall_budget};
|
||||||
|
for (double v : values)
|
||||||
|
{
|
||||||
|
if (!std::isfinite(v))
|
||||||
|
{
|
||||||
|
error = "watchdog budgets must be finite [s]";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (period < 0.0)
|
||||||
|
{
|
||||||
|
error = "watchdog_period must be >= 0 [s] (0 = watchdog off)";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string WatchdogConfig::describe() const
|
||||||
|
{
|
||||||
|
std::ostringstream out;
|
||||||
|
out << "Watchdog:\n";
|
||||||
|
out << " period : " << period << " s" << (period > 0.0 ? "" : " (off)") << '\n';
|
||||||
|
const auto line = [&out](const char* name, double v) {
|
||||||
|
out << " " << name << " : " << v << " s" << (v > 0.0 ? "" : " (not watched)") << '\n';
|
||||||
|
};
|
||||||
|
line("planner_timeout ", planner_timeout);
|
||||||
|
line("local_planner_call_budget", local_planner_call_budget);
|
||||||
|
line("recovery_stall_budget ", recovery_stall_budget);
|
||||||
|
line("action_stall_budget ", action_stall_budget);
|
||||||
|
line("control_loop_stall_budget", control_loop_stall_budget);
|
||||||
|
return out.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
Watchdog::~Watchdog()
|
||||||
|
{
|
||||||
|
stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Watchdog::start(const ComponentStatusBoard* board, const WatchdogConfig& config,
|
||||||
|
std::string& error)
|
||||||
|
{
|
||||||
|
if (board == nullptr)
|
||||||
|
{
|
||||||
|
error = "watchdog needs a component status board";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!config.validate(error))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (running_.load())
|
||||||
|
{
|
||||||
|
error = "watchdog already running";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
board_ = board;
|
||||||
|
config_ = config;
|
||||||
|
for (auto& flag : hung_)
|
||||||
|
{
|
||||||
|
flag.store(false, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
if (config_.period <= 0.0)
|
||||||
|
{
|
||||||
|
return true; // Tắt: không thread, checkOnce() vẫn dùng được nếu ai đó tự gọi.
|
||||||
|
}
|
||||||
|
running_.store(true);
|
||||||
|
thread_ = std::thread(&Watchdog::threadBody, this);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Watchdog::stop()
|
||||||
|
{
|
||||||
|
running_.store(false);
|
||||||
|
if (thread_.joinable())
|
||||||
|
{
|
||||||
|
thread_.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Watchdog::anyHung() const
|
||||||
|
{
|
||||||
|
for (const auto& flag : hung_)
|
||||||
|
{
|
||||||
|
if (flag.load(std::memory_order_relaxed))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
double Watchdog::budgetFor(Component c) const
|
||||||
|
{
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case Component::kGlobalPlanner:
|
||||||
|
return config_.planner_timeout;
|
||||||
|
case Component::kLocalPlanner:
|
||||||
|
return config_.local_planner_call_budget;
|
||||||
|
case Component::kRecovery:
|
||||||
|
return config_.recovery_stall_budget;
|
||||||
|
case Component::kAction:
|
||||||
|
return config_.action_stall_budget;
|
||||||
|
case Component::kControlLoop:
|
||||||
|
return config_.control_loop_stall_budget;
|
||||||
|
case Component::kCostmapGlobal:
|
||||||
|
case Component::kCostmapLocal:
|
||||||
|
// Chưa có heartbeat từ map-update thread (cần móc vào gói costmap) — không giám sát ở pha này.
|
||||||
|
return 0.0;
|
||||||
|
case Component::kCount:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Watchdog::checkOnce()
|
||||||
|
{
|
||||||
|
if (board_ == nullptr)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||||
|
{
|
||||||
|
const Component c = static_cast<Component>(i);
|
||||||
|
const double budget = budgetFor(c);
|
||||||
|
if (budget <= 0.0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ComponentPhase phase = board_->phase(c);
|
||||||
|
// Hàng heartbeat-only (control loop) không có phase: luôn được coi là "đang chạy". Hàng khác chỉ
|
||||||
|
// xét khi đang có việc — idle/paused không có gì để treo.
|
||||||
|
const bool watched = c == Component::kControlLoop ||
|
||||||
|
phase == ComponentPhase::kBusy || phase == ComponentPhase::kStopping;
|
||||||
|
// Hàng chưa từng nhích (last_progress = 0): runtime mới lên, chưa có gì để so.
|
||||||
|
const bool ever_progressed = board_->at(c).last_progress_ns.load(std::memory_order_relaxed) != 0;
|
||||||
|
const double since = board_->secondsSinceProgress(c);
|
||||||
|
const bool stalled = watched && ever_progressed && since > budget;
|
||||||
|
|
||||||
|
std::atomic<bool>& flag = hung_[i];
|
||||||
|
const bool was_hung = flag.load(std::memory_order_relaxed);
|
||||||
|
if (stalled && !was_hung)
|
||||||
|
{
|
||||||
|
flag.store(true, std::memory_order_relaxed);
|
||||||
|
// LỖI, không có khoá tắt: đây là "một phần của runtime đã chết đứng". In một lần ở sườn.
|
||||||
|
robot::log_error("[move_base2] watchdog: %s is HUNG — phase '%s', no progress for %.2f s "
|
||||||
|
"(budget %.2f s). %s\n",
|
||||||
|
toString(c), toString(phase), since, budget,
|
||||||
|
c == Component::kControlLoop
|
||||||
|
? "The control thread is not cycling: host must treat cmd_vel as stale."
|
||||||
|
: "cancel/pause will hit settle_timeout; the plugin is not returning.");
|
||||||
|
}
|
||||||
|
else if (!stalled && was_hung)
|
||||||
|
{
|
||||||
|
flag.store(false, std::memory_order_relaxed);
|
||||||
|
robot::log_warning("[move_base2] watchdog: %s recovered (phase '%s').\n", toString(c),
|
||||||
|
toString(phase));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Watchdog::report() const
|
||||||
|
{
|
||||||
|
std::ostringstream out;
|
||||||
|
bool any = false;
|
||||||
|
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||||
|
{
|
||||||
|
if (hung_[i].load(std::memory_order_relaxed))
|
||||||
|
{
|
||||||
|
const Component c = static_cast<Component>(i);
|
||||||
|
out << (any ? ", " : "") << toString(c) << " hung for "
|
||||||
|
<< (board_ != nullptr ? board_->secondsSinceProgress(c) : 0.0) << " s";
|
||||||
|
any = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Watchdog::threadBody()
|
||||||
|
{
|
||||||
|
const auto period = std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
||||||
|
std::chrono::duration<double>(config_.period));
|
||||||
|
while (running_.load(std::memory_order_relaxed))
|
||||||
|
{
|
||||||
|
checkOnce();
|
||||||
|
std::this_thread::sleep_for(period);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace move_base2
|
||||||
@@ -6,10 +6,12 @@
|
|||||||
*
|
*
|
||||||
* Author: DuongTD
|
* Author: DuongTD
|
||||||
*********************************************************************/
|
*********************************************************************/
|
||||||
|
#include <cstring>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
#include <boost/dll/alias.hpp>
|
#include <boost/dll/alias.hpp>
|
||||||
|
|
||||||
|
#include <move_base_core/component_status_probe.h>
|
||||||
#include <move_base_core/navigation.h>
|
#include <move_base_core/navigation.h>
|
||||||
|
|
||||||
#include <move_base2/navigation_server.h>
|
#include <move_base2/navigation_server.h>
|
||||||
@@ -30,6 +32,39 @@ robot::move_base_core::BaseNavigation::Ptr createMoveBase2()
|
|||||||
return std::make_shared<NavigationServer>();
|
return std::make_shared<NavigationServer>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Capability "MoveBaseComponentStatus" (2026-09-11): host dlsym alias này để đọc bảng trạng thái
|
||||||
|
* thành phần + kết luận treo của watchdog, không cần thêm virtual vào BaseNavigation. Chỉ atomic
|
||||||
|
* load — gọi được từ thread bất kỳ, kể cả khi control thread đang treo (đó chính là lúc cần nó).
|
||||||
|
*/
|
||||||
|
std::size_t componentStatusProbe(robot::move_base_core::BaseNavigation* navigation,
|
||||||
|
robot::move_base_core::ComponentStatusEntry* out, std::size_t max)
|
||||||
|
{
|
||||||
|
auto* server = dynamic_cast<NavigationServer*>(navigation);
|
||||||
|
if (server == nullptr)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const ComponentStatusBoard* board = server->componentStatus();
|
||||||
|
if (board == nullptr)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const Watchdog& watchdog = server->watchdog();
|
||||||
|
for (std::size_t i = 0; i < ComponentStatusBoard::kRows && i < max && out != nullptr; ++i)
|
||||||
|
{
|
||||||
|
const Component c = static_cast<Component>(i);
|
||||||
|
robot::move_base_core::ComponentStatusEntry& e = out[i];
|
||||||
|
std::strncpy(e.name, toString(c), sizeof(e.name) - 1);
|
||||||
|
e.name[sizeof(e.name) - 1] = '\0';
|
||||||
|
e.phase = static_cast<unsigned char>(board->phase(c));
|
||||||
|
e.hung = watchdog.hung(c) ? 1 : 0;
|
||||||
|
e.seconds_in_phase = board->secondsInPhase(c);
|
||||||
|
e.seconds_since_progress = board->secondsSinceProgress(c);
|
||||||
|
}
|
||||||
|
return ComponentStatusBoard::kRows;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace move_base2
|
} // namespace move_base2
|
||||||
|
|
||||||
BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase2)
|
BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase2)
|
||||||
@@ -46,3 +81,6 @@ BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase2)
|
|||||||
* host. `MoveBase2` giữ lại cho host nào muốn nạp tường minh bản mới.
|
* host. `MoveBase2` giữ lại cho host nào muốn nạp tường minh bản mới.
|
||||||
*/
|
*/
|
||||||
BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase)
|
BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase)
|
||||||
|
|
||||||
|
// Capability đọc trạng thái thành phần (xem move_base_core/component_status_probe.h).
|
||||||
|
BOOST_DLL_ALIAS(move_base2::componentStatusProbe, MoveBaseComponentStatus)
|
||||||
|
|||||||
@@ -420,6 +420,9 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
|||||||
// và chính thread đó tự đăng ký nhãn của mình khi bắt đầu chạy.
|
// và chính thread đó tự đăng ký nhãn của mình khi bắt đầu chạy.
|
||||||
planner_.attachStats(stats_.get());
|
planner_.attachStats(stats_.get());
|
||||||
controller_.attachStats(stats_.get());
|
controller_.attachStats(stats_.get());
|
||||||
|
planner_.attachStatusBoard(&components_);
|
||||||
|
recovery_.attachStatusBoard(&components_);
|
||||||
|
action_.attachStatusBoard(&components_);
|
||||||
|
|
||||||
// Trước configure(): planner nạp trong configure() và có thể muốn đọc cảm biến ngay trong
|
// Trước configure(): planner nạp trong configure() và có thể muốn đọc cảm biến ngay trong
|
||||||
// initialize() của nó.
|
// initialize() của nó.
|
||||||
@@ -526,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;
|
||||||
@@ -626,6 +642,7 @@ ControlLoopDeps NavigationRuntime::deps()
|
|||||||
deps.action = &action_;
|
deps.action = &action_;
|
||||||
deps.costmap_status = &costmap_status_;
|
deps.costmap_status = &costmap_status_;
|
||||||
deps.environment = &environment_;
|
deps.environment = &environment_;
|
||||||
|
deps.components = &components_;
|
||||||
return deps;
|
return deps;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -30,6 +31,16 @@ typename MapT::mapped_type lookupOrDefault(const MapT& container,
|
|||||||
return it == container.end() ? typename MapT::mapped_type() : it->second;
|
return it == container.end() ? typename MapT::mapped_type() : it->second;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [s] Cửa ân hạn sau khi yêu cầu kết thúc (hoặc dừng khẩn được chốt) mà stamp của getTwist() còn
|
||||||
|
* tiến, để lệnh 0 cuối cùng chắc chắn lọt qua cửa 0.05 s của host (~10 cửa sổ). Hết cửa thì stamp
|
||||||
|
* đóng băng: host thấy lệnh quá hạn và nhường /cmd_vel cho nguồn khác (teleop). Dùng ở
|
||||||
|
* publishCommand (control thread) và getTwist (thread host, khi dừng khẩn) — một số, một nghĩa.
|
||||||
|
*/
|
||||||
|
constexpr double kStopGraceSeconds = 0.5;
|
||||||
|
|
||||||
|
const char* const kEmergencyRejectReason = "emergency stop latched — call clearEmergency() first";
|
||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
NavigationServer::NavigationServer()
|
NavigationServer::NavigationServer()
|
||||||
@@ -53,6 +64,7 @@ NavigationServer::~NavigationServer()
|
|||||||
|
|
||||||
void NavigationServer::shutdown()
|
void NavigationServer::shutdown()
|
||||||
{
|
{
|
||||||
|
watchdog_.stop();
|
||||||
stopControlThread();
|
stopControlThread();
|
||||||
if (runtime_ != nullptr)
|
if (runtime_ != nullptr)
|
||||||
{
|
{
|
||||||
@@ -60,6 +72,11 @@ void NavigationServer::shutdown()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ComponentStatusBoard* NavigationServer::componentStatus() const
|
||||||
|
{
|
||||||
|
return runtime_ != nullptr ? &runtime_->components() : nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
bool NavigationServer::startControlThread(double frequency)
|
bool NavigationServer::startControlThread(double frequency)
|
||||||
{
|
{
|
||||||
if (!loop_.initialized())
|
if (!loop_.initialized())
|
||||||
@@ -165,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,8 +271,7 @@ void NavigationServer::publishCommand()
|
|||||||
// publishZeroVelocity(), tức chỉ khi đang điều khiển; đây là cùng ngữ nghĩa. Giữ thêm một cửa
|
// publishZeroVelocity(), tức chỉ khi đang điều khiển; đây là cùng ngữ nghĩa. Giữ thêm một cửa
|
||||||
// ân hạn sau khi yêu cầu kết thúc để lệnh dừng cuối cùng chắc chắn lọt qua cửa 0.05 s của host
|
// ân hạn sau khi yêu cầu kết thúc để lệnh dừng cuối cùng chắc chắn lọt qua cửa 0.05 s của host
|
||||||
// — kết thúc mà đóng băng ngay thì robot giữ nguyên vận tốc chót vì lệnh 0 không bao giờ được
|
// — kết thúc mà đóng băng ngay thì robot giữ nguyên vận tốc chót vì lệnh 0 không bao giờ được
|
||||||
// publish.
|
// publish. Cửa đó là `kStopGraceSeconds` (file-scope, dùng chung với getTwist lúc dừng khẩn).
|
||||||
constexpr double kStopGraceSeconds = 0.5; // [s] ~10 cửa sổ 0.05s của host
|
|
||||||
|
|
||||||
const robot_geometry_msgs::Twist& command = loop_.lastCommand();
|
const robot_geometry_msgs::Twist& command = loop_.lastCommand();
|
||||||
const robot::Time cycle_time = loop_.lastCycleTime();
|
const robot::Time cycle_time = loop_.lastCycleTime();
|
||||||
@@ -284,10 +318,18 @@ robot::move_base_core::State NavigationServer::toHostState(NavigationState state
|
|||||||
// VDA5050 đang suy `driving = true` từ CONTROLLING (amr_vda_5050_client_api.cpp:1233), mà
|
// VDA5050 đang suy `driving = true` từ CONTROLLING (amr_vda_5050_client_api.cpp:1233), mà
|
||||||
// robot lúc này đứng yên làm action; báo "đang chạy" cho fleet master là báo sai.
|
// robot lúc này đứng yên làm action; báo "đang chạy" cho fleet master là báo sai.
|
||||||
return HostState::ACTIVE;
|
return HostState::ACTIVE;
|
||||||
|
case NavigationState::kPausing:
|
||||||
|
// Không tới được từ refreshFeedback(): PAUSING được thay bằng state TRƯỚC pause ở đó (host chỉ
|
||||||
|
// thấy PAUSED khi runtime đã im hẳn — 2026-09-11). Giữ case để switch đủ nhánh.
|
||||||
|
return HostState::PAUSED;
|
||||||
case NavigationState::kPaused:
|
case NavigationState::kPaused:
|
||||||
return HostState::PAUSED;
|
return HostState::PAUSED;
|
||||||
case NavigationState::kCancelling:
|
case NavigationState::kCancelling:
|
||||||
return HostState::PREEMPTING;
|
return HostState::PREEMPTING;
|
||||||
|
case NavigationState::kEmergency:
|
||||||
|
// Giá trị mới trong contract (2026-09-14), đúng nghĩa: không phải "đã huỷ xong" (PREEMPTED —
|
||||||
|
// host sẽ gửi goal kế), mà là "đang bị chốt, gửi gì cũng bị từ chối".
|
||||||
|
return HostState::EMERGENCY;
|
||||||
case NavigationState::kSucceeded:
|
case NavigationState::kSucceeded:
|
||||||
return HostState::SUCCEEDED;
|
return HostState::SUCCEEDED;
|
||||||
case NavigationState::kAborted:
|
case NavigationState::kAborted:
|
||||||
@@ -344,7 +386,16 @@ void NavigationServer::reportSensorStore()
|
|||||||
|
|
||||||
void NavigationServer::refreshFeedback()
|
void NavigationServer::refreshFeedback()
|
||||||
{
|
{
|
||||||
robot::move_base_core::State host_state = toHostState(loop_.state());
|
// PAUSING nói thật (2026-09-11): pause đã nhận, lệnh = 0, nhưng thread planner/recovery/action
|
||||||
|
// chưa im — host vẫn thấy tên state trước (PLANNING/CONTROLLING/CLEARING/ACTIVE) kèm
|
||||||
|
// feed_back_str "pausing…"; PAUSED chỉ khi đã im hẳn. Host đọc PAUSED là "dừng rồi, làm gì cũng
|
||||||
|
// được" — báo sớm là nói dối cùng kiểu với PREEMPTED cũ.
|
||||||
|
NavigationState core_state = loop_.state();
|
||||||
|
if (core_state == NavigationState::kPausing)
|
||||||
|
{
|
||||||
|
core_state = loop_.stateBeforePause();
|
||||||
|
}
|
||||||
|
robot::move_base_core::State host_state = toHostState(core_state);
|
||||||
|
|
||||||
// Một order nhiều chặng: lõi về SUCCEEDED sau MỖI chặng, còn order thì chưa xong. Host suy "order
|
// Một order nhiều chặng: lõi về SUCCEEDED sau MỖI chặng, còn order thì chưa xong. Host suy "order
|
||||||
// hoàn thành" thẳng từ SUCCEEDED (amr_vda_5050_client_api.cpp:1062, 1092), nên báo nguyên trạng
|
// hoàn thành" thẳng từ SUCCEEDED (amr_vda_5050_client_api.cpp:1062, 1092), nên báo nguyên trạng
|
||||||
@@ -588,6 +639,16 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Watchdog sau control thread: hàng control_loop chỉ có nghĩa khi thread đó đã quay. Watchdog
|
||||||
|
// hỏng không phải lý do từ chối runtime — log rồi chạy tiếp không có nó.
|
||||||
|
{
|
||||||
|
std::string watchdog_error;
|
||||||
|
if (!watchdog_.start(&runtime_->components(), runtime_->config().watchdog, watchdog_error))
|
||||||
|
{
|
||||||
|
robot::log_error("[move_base2] watchdog not started: %s\n", watchdog_error.c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
nav_feedback_->is_ready = true;
|
nav_feedback_->is_ready = true;
|
||||||
nav_feedback_->feed_back_str = "ready";
|
nav_feedback_->feed_back_str = "ready";
|
||||||
refreshFeedback();
|
refreshFeedback();
|
||||||
@@ -651,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);
|
||||||
}
|
}
|
||||||
@@ -783,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -824,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -864,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();
|
||||||
@@ -879,8 +944,27 @@ bool NavigationServer::removeAllData()
|
|||||||
// đi qua `profile:` và `marker` của từng chặng trong order — xem MissionAdapterBridge::toProfile.
|
// đi qua `profile:` và `marker` của từng chặng trong order — xem MissionAdapterBridge::toProfile.
|
||||||
// ================================================================================================
|
// ================================================================================================
|
||||||
|
|
||||||
|
bool NavigationServer::rejectIfEmergencyLatched(const char* what)
|
||||||
|
{
|
||||||
|
if (!emergencyLatched())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
last_reject_reason_ = kEmergencyRejectReason;
|
||||||
|
nav_feedback_->feed_back_str = std::string(what) + " rejected: " + kEmergencyRejectReason;
|
||||||
|
// Throttle chứ không tắt: host poll-gửi-lại sẽ spam, nhưng im lặng hoàn toàn thì người vận hành
|
||||||
|
// không biết vì sao goal không chạy.
|
||||||
|
robot::log_warning_throttle(1.0, "[move_base2] %s rejected: %s\n", what, kEmergencyRejectReason);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
bool NavigationServer::submit(const NavigationRequest& request)
|
bool NavigationServer::submit(const NavigationRequest& request)
|
||||||
{
|
{
|
||||||
|
if (rejectIfEmergencyLatched("request"))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
std::string reason;
|
std::string reason;
|
||||||
if (loop_.submit(request, reason))
|
if (loop_.submit(request, reason))
|
||||||
{
|
{
|
||||||
@@ -907,6 +991,13 @@ bool NavigationServer::moveTo(const robot_geometry_msgs::PoseStamped& goal,
|
|||||||
//
|
//
|
||||||
// Fallback trực tiếp chỉ dành cho cấu hình tương thích cũ: mission layer bị tắt, chưa khởi động,
|
// Fallback trực tiếp chỉ dành cho cấu hình tương thích cũ: mission layer bị tắt, chưa khởi động,
|
||||||
// hoặc không nạp GoalSourceAdapter. Không được coi false là goal đã được layer nhận.
|
// hoặc không nạp GoalSourceAdapter. Không được coi false là goal đã được layer nhận.
|
||||||
|
//
|
||||||
|
// Dừng khẩn chặn TRƯỚC mission layer: `submitGoal` trả true chỉ nghĩa "đã vào hàng đợi sự kiện",
|
||||||
|
// manager mới gạt trên thread sự kiện — host sẽ tưởng goal được nhận. Từ chối đồng bộ ở đây.
|
||||||
|
if (rejectIfEmergencyLatched("moveTo"))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (runtime_ != nullptr && runtime_->missionLayer().submitGoal(goal))
|
if (runtime_ != nullptr && runtime_->missionLayer().submitGoal(goal))
|
||||||
{
|
{
|
||||||
last_reject_reason_.clear();
|
last_reject_reason_.clear();
|
||||||
@@ -931,6 +1022,10 @@ bool NavigationServer::moveTo(const robot_protocol_msgs::Order& msg,
|
|||||||
//
|
//
|
||||||
// `submitOrder` trả false khi layer tắt hoặc không có nguồn nhận schema `vda5050.order`; lúc đó
|
// `submitOrder` trả false khi layer tắt hoặc không có nguồn nhận schema `vda5050.order`; lúc đó
|
||||||
// rơi xuống đường trực tiếp bên dưới, đúng hành vi đã chạy được trên sim.
|
// rơi xuống đường trực tiếp bên dưới, đúng hành vi đã chạy được trên sim.
|
||||||
|
if (rejectIfEmergencyLatched("order"))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (runtime_ != nullptr && runtime_->missionLayer().submitOrder(msg))
|
if (runtime_ != nullptr && runtime_->missionLayer().submitOrder(msg))
|
||||||
{
|
{
|
||||||
last_reject_reason_.clear();
|
last_reject_reason_.clear();
|
||||||
@@ -951,6 +1046,10 @@ bool NavigationServer::executeInstantActions(
|
|||||||
// layer nở nó theo bảng compound: đẩy thẳng xuống lõi sẽ biến `PickUp` thành một chặng chỉ-action
|
// layer nở nó theo bảng compound: đẩy thẳng xuống lõi sẽ biến `PickUp` thành một chặng chỉ-action
|
||||||
// không có bước dò và không có bước tiến vào, tức robot báo "đã nâng kệ" khi càng còn chưa tới
|
// không có bước dò và không có bước tiến vào, tức robot báo "đã nâng kệ" khi càng còn chưa tới
|
||||||
// gần kệ. Layer tắt thì phải từ chối để host báo FAILED ngay, thay vì chờ một kết quả không đến.
|
// gần kệ. Layer tắt thì phải từ chối để host báo FAILED ngay, thay vì chờ một kết quả không đến.
|
||||||
|
if (rejectIfEmergencyLatched("instantActions"))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (runtime_ == nullptr || !runtime_->missionLayer().submitInstantActions(actions))
|
if (runtime_ == nullptr || !runtime_->missionLayer().submitInstantActions(actions))
|
||||||
{
|
{
|
||||||
const std::string first = actions.empty() ? std::string("<empty>") : actions.front().actionType;
|
const std::string first = actions.empty() ? std::string("<empty>") : actions.front().actionType;
|
||||||
@@ -1007,12 +1106,39 @@ void NavigationServer::requestLoopCancel()
|
|||||||
cancel_requested_ = true;
|
cancel_requested_ = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void NavigationServer::emergency()
|
||||||
|
{
|
||||||
|
// Chốt TRƯỚC khi lấy lock: từ dòng này getTwist()/getFeedback() đã trả 0/EMERGENCY cho host, kể
|
||||||
|
// cả khi control thread đang kẹt và mọi thứ bên dưới chưa chạy. Idempotent — gọi lại chỉ làm mới
|
||||||
|
// mốc ân hạn, không đổi gì khác.
|
||||||
|
emergency_latched_.store(true, std::memory_order_relaxed);
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||||
|
emergency_requested_ = true;
|
||||||
|
clear_emergency_requested_ = false; // Hai cờ đối nghịch, đặt cùng nhau dưới một lock.
|
||||||
|
emergency_since_ = clock_ != nullptr ? clock_->now() : robot::Time::now();
|
||||||
|
}
|
||||||
|
|
||||||
|
void NavigationServer::clearEmergency()
|
||||||
|
{
|
||||||
|
// Gỡ chốt ngay trên thread host là an toàn: state machine còn ở kEmergency (mustBeStopped) cho
|
||||||
|
// tới cycle nó nhận mức mới, nên lệnh vẫn 0; và submit vẫn bị chặn ở ControlLoop::submit chừng
|
||||||
|
// nào `emergency_` chưa hạ. Host thấy EMERGENCY → PENDING sau ≤ 1 cycle.
|
||||||
|
emergency_latched_.store(false, std::memory_order_relaxed);
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||||
|
clear_emergency_requested_ = true;
|
||||||
|
emergency_requested_ = false;
|
||||||
|
}
|
||||||
|
|
||||||
void NavigationServer::drainLifecycleRequests()
|
void NavigationServer::drainLifecycleRequests()
|
||||||
{
|
{
|
||||||
bool pause = false;
|
bool pause = false;
|
||||||
bool resume = false;
|
bool resume = false;
|
||||||
bool cancel = false;
|
bool cancel = false;
|
||||||
bool mission_cancel = false;
|
bool mission_cancel = false;
|
||||||
|
bool emergency = false;
|
||||||
|
bool clear_emergency = false;
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||||
@@ -1020,10 +1146,25 @@ void NavigationServer::drainLifecycleRequests()
|
|||||||
resume = resume_requested_;
|
resume = resume_requested_;
|
||||||
cancel = cancel_requested_;
|
cancel = cancel_requested_;
|
||||||
mission_cancel = mission_cancel_requested_;
|
mission_cancel = mission_cancel_requested_;
|
||||||
|
emergency = emergency_requested_;
|
||||||
|
clear_emergency = clear_emergency_requested_;
|
||||||
pause_requested_ = false;
|
pause_requested_ = false;
|
||||||
resume_requested_ = false;
|
resume_requested_ = false;
|
||||||
cancel_requested_ = false;
|
cancel_requested_ = false;
|
||||||
mission_cancel_requested_ = false;
|
mission_cancel_requested_ = false;
|
||||||
|
emergency_requested_ = false;
|
||||||
|
clear_emergency_requested_ = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dừng khẩn trước cả huỷ: là mức trong ControlLoop, nên cancel/pause/resume phát sau vô hại —
|
||||||
|
// state machine bỏ qua chúng chừng nào còn mức. Hai cờ loại trừ nhau (đặt dưới một lock ở trên).
|
||||||
|
if (emergency)
|
||||||
|
{
|
||||||
|
loop_.requestEmergency();
|
||||||
|
}
|
||||||
|
else if (clear_emergency)
|
||||||
|
{
|
||||||
|
loop_.requestClearEmergency();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Huỷ trước: nó thắng mọi thứ khác. Tạm dừng rồi huỷ và huỷ rồi tạm dừng phải cho cùng kết quả.
|
// Huỷ trước: nó thắng mọi thứ khác. Tạm dừng rồi huỷ và huỷ rồi tạm dừng phải cho cùng kết quả.
|
||||||
@@ -1047,6 +1188,21 @@ void NavigationServer::drainLifecycleRequests()
|
|||||||
runtime_->missionLayer().cancel();
|
runtime_->missionLayer().cancel();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dừng khẩn lan xuống mission layer: xoá hàng đợi, xin huỷ chặng qua bridge, và manager từ chối
|
||||||
|
// submit/append cho tới clear. `emergency()` của layer đi out-of-band (vượt hàng đợi sự kiện),
|
||||||
|
// `clearEmergency()` xếp FIFO — đúng thiết kế sẵn của mission_adapters.
|
||||||
|
if (runtime_ != nullptr)
|
||||||
|
{
|
||||||
|
if (emergency)
|
||||||
|
{
|
||||||
|
runtime_->missionLayer().emergency();
|
||||||
|
}
|
||||||
|
else if (clear_emergency)
|
||||||
|
{
|
||||||
|
runtime_->missionLayer().clearEmergency();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// `pause`/`resume` CỐ Ý không lan xuống mission layer. Chặng đang chạy đã bị chính control loop
|
// `pause`/`resume` CỐ Ý không lan xuống mission layer. Chặng đang chạy đã bị chính control loop
|
||||||
// giữ lại, nên hàng đợi không giao chặng mới trong lúc tạm dừng dù manager không biết gì.
|
// giữ lại, nên hàng đợi không giao chặng mới trong lúc tạm dừng dù manager không biết gì.
|
||||||
// Ngược lại, đẩy manager sang PAUSED mở ra một đường hỏng thật: `onNavigationDone` chỉ được nhận
|
// Ngược lại, đẩy manager sang PAUSED mở ra một đường hỏng thật: `onNavigationDone` chỉ được nhận
|
||||||
@@ -1174,11 +1330,50 @@ bool NavigationServer::getRobotPose(robot_geometry_msgs::Pose2D& pose)
|
|||||||
robot_nav_2d_msgs::Twist2DStamped NavigationServer::getTwist()
|
robot_nav_2d_msgs::Twist2DStamped NavigationServer::getTwist()
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||||
|
if (!emergencyLatched())
|
||||||
|
{
|
||||||
return twist_;
|
return twist_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dừng khẩn ghi đè trên thread host: `twist_` là lệnh cuối control thread đã phát — nếu thread
|
||||||
|
// đó đang kẹt thì nó còn giữ một lệnh khác 0 từ trước lúc bấm dừng. Vận tốc về 0 suốt lúc chốt.
|
||||||
|
// Stamp: tươi trong cửa ân hạn để host publish được lệnh 0 tường minh (không chỉ "ngừng publish"),
|
||||||
|
// rồi đóng băng như mọi lần kết thúc yêu cầu — nav core không giữ /cmd_vel vĩnh viễn, teleop phải
|
||||||
|
// lái được robot ra khỏi tình huống. E-stop phần cứng là tầng khác, không phải việc ở đây.
|
||||||
|
robot_nav_2d_msgs::Twist2DStamped zero = twist_;
|
||||||
|
zero.velocity = robot_nav_2d_msgs::Twist2D();
|
||||||
|
const robot::Time now = clock_ != nullptr ? clock_->now() : robot::Time::now();
|
||||||
|
if ((now - emergency_since_).toSec() < kStopGraceSeconds)
|
||||||
|
{
|
||||||
|
zero.header.stamp = now;
|
||||||
|
}
|
||||||
|
return zero;
|
||||||
}
|
}
|
||||||
|
|
||||||
robot::move_base_core::NavFeedback* NavigationServer::getFeedback()
|
robot::move_base_core::NavFeedback* NavigationServer::getFeedback()
|
||||||
{
|
{
|
||||||
|
// Control thread treo thì refreshFeedback() không chạy nữa và host sẽ đọc mãi state cuối cùng —
|
||||||
|
// một CONTROLLING đóng băng trông y hệt một CONTROLLING đang chạy. Watchdog (thread riêng) là
|
||||||
|
// nguồn duy nhất còn nói được; ghi đè ở đây, trên thread host. `LOST` là giá trị có sẵn trong
|
||||||
|
// move_base_core::State, chưa ai dùng, nghĩa đúng: "lõi không còn theo dõi được goal".
|
||||||
|
// Host đọc LOST phải tự zero cmd_vel (nav_c_api_2.h mục 6 đã bắt kiểm stamp của twist).
|
||||||
|
const bool hung = watchdog_.controlLoopHung();
|
||||||
|
if (hung)
|
||||||
|
{
|
||||||
|
nav_feedback_->navigation_state = robot::move_base_core::State::LOST;
|
||||||
|
nav_feedback_->feed_back_str = "control thread stalled: " + watchdog_.report();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dừng khẩn thắng cả LOST về STATE (host phải biết mình đang bị chốt, không phải "mất goal"),
|
||||||
|
// nhưng thông tin treo không được mất — nối vào chuỗi. Ghi đè ở đây, cùng thread host với
|
||||||
|
// emergency(), để host thấy EMERGENCY ngay trong lần đọc kế, không chờ refreshFeedback().
|
||||||
|
if (emergencyLatched())
|
||||||
|
{
|
||||||
|
nav_feedback_->navigation_state = robot::move_base_core::State::EMERGENCY;
|
||||||
|
nav_feedback_->feed_back_str =
|
||||||
|
hung ? "emergency stop latched; control thread stalled: " + watchdog_.report()
|
||||||
|
: std::string("emergency stop latched");
|
||||||
|
}
|
||||||
return nav_feedback_.get();
|
return nav_feedback_.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,10 +30,14 @@ const char* toString(NavigationState state)
|
|||||||
return "RECOVERING";
|
return "RECOVERING";
|
||||||
case NavigationState::kExecutingActions:
|
case NavigationState::kExecutingActions:
|
||||||
return "EXECUTING_ACTIONS";
|
return "EXECUTING_ACTIONS";
|
||||||
|
case NavigationState::kPausing:
|
||||||
|
return "PAUSING";
|
||||||
case NavigationState::kPaused:
|
case NavigationState::kPaused:
|
||||||
return "PAUSED";
|
return "PAUSED";
|
||||||
case NavigationState::kCancelling:
|
case NavigationState::kCancelling:
|
||||||
return "CANCELLING";
|
return "CANCELLING";
|
||||||
|
case NavigationState::kEmergency:
|
||||||
|
return "EMERGENCY";
|
||||||
case NavigationState::kSucceeded:
|
case NavigationState::kSucceeded:
|
||||||
return "SUCCEEDED";
|
return "SUCCEEDED";
|
||||||
case NavigationState::kAborted:
|
case NavigationState::kAborted:
|
||||||
@@ -54,7 +58,8 @@ bool mustBeStopped(NavigationState state)
|
|||||||
{
|
{
|
||||||
// Chỉ hai state được phép có vận tốc khác 0: kControlling (local planner lái) và kRecovering
|
// Chỉ hai state được phép có vận tốc khác 0: kControlling (local planner lái) và kRecovering
|
||||||
// (recovery behavior lái). Mọi state còn lại là hàng rào an toàn — kể cả kExecutingActions:
|
// (recovery behavior lái). Mọi state còn lại là hàng rào an toàn — kể cả kExecutingActions:
|
||||||
// theo D8 action chạy khi robot đứng yên, action cần chuyển động phải là motion profile.
|
// theo D8 action chạy khi robot đứng yên, action cần chuyển động phải là motion profile — và
|
||||||
|
// kEmergency, nơi hàng rào này là toàn bộ ý nghĩa của state.
|
||||||
return state != NavigationState::kControlling && state != NavigationState::kRecovering;
|
return state != NavigationState::kControlling && state != NavigationState::kRecovering;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ ActionTick ActionRunner::toTick(const action_core::ActionTick& tick)
|
|||||||
case action_core::ActionStatus::kSucceeded:
|
case action_core::ActionStatus::kSucceeded:
|
||||||
out.status = ActionTick::Status::kSucceeded;
|
out.status = ActionTick::Status::kSucceeded;
|
||||||
break;
|
break;
|
||||||
|
case action_core::ActionStatus::kCancelled:
|
||||||
|
out.status = ActionTick::Status::kCancelled;
|
||||||
|
break;
|
||||||
case action_core::ActionStatus::kFailed:
|
case action_core::ActionStatus::kFailed:
|
||||||
out.status = ActionTick::Status::kFailed;
|
out.status = ActionTick::Status::kFailed;
|
||||||
break;
|
break;
|
||||||
@@ -131,6 +134,10 @@ bool ActionRunner::start(const robot_protocol_msgs::Action& action)
|
|||||||
|
|
||||||
active_ = handler;
|
active_ = handler;
|
||||||
active_action_id_ = action.actionId;
|
active_action_id_ = action.actionId;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kAction, ComponentPhase::kBusy);
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,17 +158,74 @@ ActionTick ActionRunner::update()
|
|||||||
if (tick.status != ActionTick::Status::kRunning)
|
if (tick.status != ActionTick::Status::kRunning)
|
||||||
{
|
{
|
||||||
active_ = nullptr;
|
active_ = nullptr;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->progress(Component::kAction);
|
||||||
}
|
}
|
||||||
|
|
||||||
return tick;
|
return tick;
|
||||||
}
|
}
|
||||||
|
|
||||||
void ActionRunner::cancel()
|
void ActionRunner::cancel()
|
||||||
|
{
|
||||||
|
if (active_ == nullptr)
|
||||||
|
{
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
active_->cancel();
|
||||||
|
|
||||||
|
if (active_->cancelNeedsTicks())
|
||||||
|
{
|
||||||
|
// Handler thiết bị (2026-09-11): cancel() mới RA LỆNH dừng; giữ handler, tick tiếp trong
|
||||||
|
// CANCELLING/PAUSING tới khi nó trả kCancelled/terminal. Hàng kAction = stopping cho tới lúc đó
|
||||||
|
// — CANCELLED/PAUSED không được báo ra host trong lúc thiết bị còn đang về vị trí an toàn.
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kAction, ComponentPhase::kStopping);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handler perception/no-op: dừng xong ngay trong cancel(), quên nó, hàng về idle.
|
||||||
|
active_ = nullptr;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ActionRunner::pause()
|
||||||
{
|
{
|
||||||
if (active_ != nullptr)
|
if (active_ != nullptr)
|
||||||
{
|
{
|
||||||
active_->cancel();
|
active_->pause(clock_->now());
|
||||||
active_ = nullptr;
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
// kPaused là "đã xác nhận tạm dừng": điều kiện quiescent của PAUSING chấp nhận nó.
|
||||||
|
status_board_->enter(Component::kAction, ComponentPhase::kPaused);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ActionRunner::resume()
|
||||||
|
{
|
||||||
|
if (active_ != nullptr)
|
||||||
|
{
|
||||||
|
active_->resume(clock_->now());
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kAction, ComponentPhase::kBusy);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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"
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -90,6 +139,7 @@ PlannerRunner::~PlannerRunner()
|
|||||||
std::lock_guard<std::mutex> lock(mutex_);
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
shutdown_ = true;
|
shutdown_ = true;
|
||||||
discard_ = true;
|
discard_ = true;
|
||||||
|
preemptRunningLocked(); // shutdown không phải chờ hết allocated_time của lượt dở
|
||||||
}
|
}
|
||||||
cv_.notify_all();
|
cv_.notify_all();
|
||||||
|
|
||||||
@@ -102,6 +152,11 @@ PlannerRunner::~PlannerRunner()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void PlannerRunner::attachStatusBoard(ComponentStatusBoard* board)
|
||||||
|
{
|
||||||
|
status_board_ = board;
|
||||||
|
}
|
||||||
|
|
||||||
void PlannerRunner::attachStats(RuntimeStats* stats)
|
void PlannerRunner::attachStats(RuntimeStats* stats)
|
||||||
{
|
{
|
||||||
stats_ = stats;
|
stats_ = stats;
|
||||||
@@ -223,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();
|
||||||
@@ -284,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;
|
||||||
|
if (has_profile)
|
||||||
|
{
|
||||||
for (const char* key : kMarkerPlannerParams)
|
for (const char* key : kMarkerPlannerParams)
|
||||||
{
|
{
|
||||||
copied = copyParamNode(marker_nh, planner_nh, key) || copied;
|
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ì
|
||||||
@@ -363,16 +458,38 @@ 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_);
|
||||||
// Lượt đang chạy thuộc về planner cũ — kết quả của nó không còn nghĩa. Không cắt ngang được
|
// Lượt đang chạy thuộc về planner cũ — kết quả của nó không còn nghĩa: đánh dấu vứt, và cắt
|
||||||
// phép tính, chỉ đánh dấu vứt kết quả. Con trỏ planner cũ vẫn hợp lệ vì cache không xoá entry.
|
// nếu plugin Preemptable. Con trỏ planner cũ vẫn hợp lệ vì cache không xoá entry.
|
||||||
if (running_ || pending_)
|
if (pending_ && !running_)
|
||||||
|
{
|
||||||
|
// Thread chưa nhận: rút yêu cầu ra, kẻo nó chạy yêu cầu của planner cũ trên instance mới rồi
|
||||||
|
// vứt — tốn một lượt makePlan vô ích.
|
||||||
|
pending_ = false;
|
||||||
|
waiting_for_costmap_ = false;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||||
|
request_order_.reset();
|
||||||
|
}
|
||||||
|
else if (running_)
|
||||||
{
|
{
|
||||||
discard_ = true;
|
discard_ = true;
|
||||||
|
// Lượt cũ vẫn chiếm thread; cắt nó ngay để yêu cầu kế (dùng planner mới) không phải chờ
|
||||||
|
// planner_patience. Phải cắt TRƯỚC khi đổi active_ — sau dòng dưới active_ đã là instance mới.
|
||||||
|
preemptRunningLocked();
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
active_ = planner;
|
active_ = planner;
|
||||||
|
active_external_grid_ = external_grid ? &external_grid : nullptr;
|
||||||
|
cv_.notify_all();
|
||||||
}
|
}
|
||||||
|
|
||||||
active_name_ = planner_name;
|
active_name_ = planner_name;
|
||||||
@@ -387,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
|
||||||
// ================================================================================================
|
// ================================================================================================
|
||||||
@@ -432,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;
|
||||||
@@ -443,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_);
|
||||||
@@ -463,16 +603,57 @@ bool PlannerRunner::pollPlan(PlanResult& result)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void PlannerRunner::preemptRunningLocked()
|
||||||
|
{
|
||||||
|
// Gọi dưới mutex_. `running_planner_` là instance thread đang ở trong makePlan — KHÔNG phải
|
||||||
|
// `active_`, vì swapPlanner có thể đã trỏ active_ sang instance khác trong lúc lượt cũ chưa về.
|
||||||
|
// Instance cũ được cache/retired giữ sống nên con trỏ còn hợp lệ suốt lượt; preempt() là một
|
||||||
|
// atomic store, gọi được từ control thread. Plugin không Preemptable: không có gì để làm.
|
||||||
|
if (running_planner_ == nullptr)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (auto* preemptable = dynamic_cast<robot_nav_core::Preemptable*>(running_planner_))
|
||||||
|
{
|
||||||
|
preemptable->preempt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void PlannerRunner::cancelPlan()
|
void PlannerRunner::cancelPlan()
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
if (pending_ || running_)
|
if (pending_ && !running_)
|
||||||
|
{
|
||||||
|
// Lượt đã được xếp nhưng thread chưa kịp nhận (cửa sổ giữa startPlan() và lúc thread thức dậy).
|
||||||
|
// Rút nó ra khỏi hàng đợi là đủ — không có gì để preempt, và nếu chỉ đặt discard_ thì thread
|
||||||
|
// sẽ nhận job này NGAY SAU cancel, chạy trọn allocated_time cho một plan không ai cần (bắt được
|
||||||
|
// bằng test CancelPreemptsAPreemptablePlannerWithinMilliseconds, 2026-09-11).
|
||||||
|
pending_ = false;
|
||||||
|
waiting_for_costmap_ = false;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||||
|
request_order_.reset();
|
||||||
|
}
|
||||||
|
else if (pending_ || running_)
|
||||||
{
|
{
|
||||||
discard_ = true;
|
discard_ = true;
|
||||||
|
if (running_)
|
||||||
|
{
|
||||||
|
// Cắt thật (2026-09-11): plugin implement robot_nav_core::Preemptable thì lượt makePlan đang
|
||||||
|
// chạy thoát trong vài ms thay vì đi tới hết allocated_time. Plugin cũ (không Preemptable)
|
||||||
|
// thì chỉ còn discard_ như trước — kết quả về bị vứt, thread bận tới khi nó xong.
|
||||||
|
preemptRunningLocked();
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
// Thread vẫn ở trong makePlan; từ giờ tới lúc nó trả về là "đang dừng", không phải "bận".
|
||||||
|
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Kết quả đã nằm sẵn trong hộp thư cũng bỏ luôn: bên gọi vừa nói nó không còn cần plan này.
|
// 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();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================================================
|
// ================================================================================================
|
||||||
@@ -501,37 +682,153 @@ 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_;
|
||||||
|
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 && !waiting_for_costmap_)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||||
|
}
|
||||||
|
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
|
|
||||||
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)
|
||||||
{
|
{
|
||||||
|
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
|
||||||
|
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_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
|
||||||
*(costmap_->getCostmap()->getMutex()));
|
*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;
|
||||||
}
|
}
|
||||||
// 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
|
const bool ready = !costmap_lock_enabled_ || ready_timeout == 0.0 ||
|
||||||
// contract. Plugin nào không hiểu Order thì overload mặc định của nó tự lo.
|
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_)
|
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
|
||||||
: planner->makePlan(start, goal, planning_);
|
: planner->makePlan(start, goal, planning_);
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (const std::exception& ex)
|
catch (const std::exception& ex)
|
||||||
{
|
{
|
||||||
@@ -557,7 +854,15 @@ 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;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
|
||||||
if (discard_)
|
if (discard_)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -408,6 +408,10 @@ bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
|
|||||||
active_ = behavior;
|
active_ = behavior;
|
||||||
active_name_ = registry_.nameAt(index);
|
active_name_ = registry_.nameAt(index);
|
||||||
active_trigger_ = trigger;
|
active_trigger_ = trigger;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kRecovery, ComponentPhase::kBusy);
|
||||||
|
}
|
||||||
|
|
||||||
// Log tại SƯỜN (một dòng cho mỗi lượt khởi động, không nằm trên đường tick). Không có dòng này
|
// Log tại SƯỜN (một dòng cho mỗi lượt khởi động, không nằm trên đường tick). Không có dòng này
|
||||||
// thì trên robot/sim không cách nào biết đang chạy behavior nào: các plugin chỉ log khi chúng TỪ
|
// thì trên robot/sim không cách nào biết đang chạy behavior nào: các plugin chỉ log khi chúng TỪ
|
||||||
@@ -434,6 +438,17 @@ RecoveryTick RecoveryRunner::update()
|
|||||||
|
|
||||||
refreshContext();
|
refreshContext();
|
||||||
const RecoveryTick result = toTick(active_->update(deps_.clock->now()));
|
const RecoveryTick result = toTick(active_->update(deps_.clock->now()));
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
if (result.status == RecoveryTick::Status::kRunning)
|
||||||
|
{
|
||||||
|
status_board_->progress(Component::kRecovery);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kRecovery, ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Log tại SƯỜN KẾT THÚC, một dòng cho mỗi lượt (không nằm trên đường tick: kRunning không log).
|
// Log tại SƯỜN KẾT THÚC, một dòng cho mỗi lượt (không nằm trên đường tick: kRunning không log).
|
||||||
//
|
//
|
||||||
@@ -465,6 +480,13 @@ void RecoveryRunner::cancel()
|
|||||||
{
|
{
|
||||||
active_->cancel();
|
active_->cancel();
|
||||||
}
|
}
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
// Sau cancel() behavior không được tick nữa (CANCELLING ép tick_recovery=false): hàng phải về
|
||||||
|
// idle ngay ở đây, không có tick nào sau để làm việc đó. Behavior có việc chạy dài (detour
|
||||||
|
// worker) phải kết thúc việc đó bên trong cancel() của nó — xem RecoveryBehavior::onCancelRequested.
|
||||||
|
status_board_->enter(Component::kRecovery, ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
RecoveryTick RecoveryRunner::toTick(const recovery_core::RecoveryResult& result) const
|
RecoveryTick RecoveryRunner::toTick(const recovery_core::RecoveryResult& result) const
|
||||||
|
|||||||
@@ -49,6 +49,18 @@ bool StateMachineConfig::validate(std::string& error) const
|
|||||||
"route cursor is refilled anyway, so a larger value can never take effect";
|
"route cursor is refilled anyway, so a larger value can never take effect";
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
if (settle_timeout < 0.0)
|
||||||
|
{
|
||||||
|
error = "settle_timeout must be >= 0 [s] (0 = finish CANCELLING/PAUSING as soon as the command "
|
||||||
|
"is zero, without waiting for the planner thread)";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (stopped_measured_linear_eps < 0.0 || stopped_measured_angular_eps < 0.0)
|
||||||
|
{
|
||||||
|
error = "stopped_measured_linear_eps [m/s] and stopped_measured_angular_eps [rad/s] must be "
|
||||||
|
">= 0 (0 = ignore odometry, judge 'stopped' from the issued command)";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (planner_patience <= 0.0 && max_planning_retries < 0)
|
if (planner_patience <= 0.0 && max_planning_retries < 0)
|
||||||
{
|
{
|
||||||
// Từ khi lập plan chạy trên thread riêng, hai tham số này là thứ DUY NHẤT phát hiện được planner
|
// Từ khi lập plan chạy trên thread riêng, hai tham số này là thứ DUY NHẤT phát hiện được planner
|
||||||
@@ -121,6 +133,15 @@ std::string StateMachineConfig::describe() const
|
|||||||
<< '\n';
|
<< '\n';
|
||||||
out << " max_planning_retries : " << max_planning_retries
|
out << " max_planning_retries : " << max_planning_retries
|
||||||
<< (max_planning_retries < 0 ? " (unlimited)" : "") << '\n';
|
<< (max_planning_retries < 0 ? " (unlimited)" : "") << '\n';
|
||||||
|
out << " settle_timeout : " << settle_timeout << " s"
|
||||||
|
<< (settle_timeout > 0.0 ? "" : " (off — CANCELLED/PAUSED as soon as the command is zero)")
|
||||||
|
<< '\n';
|
||||||
|
out << " stopped_measured_eps : " << stopped_measured_linear_eps << " m/s, "
|
||||||
|
<< stopped_measured_angular_eps << " rad/s"
|
||||||
|
<< (stopped_measured_linear_eps > 0.0 || stopped_measured_angular_eps > 0.0
|
||||||
|
? ""
|
||||||
|
: " (off — 'stopped' judged from the issued command)")
|
||||||
|
<< '\n';
|
||||||
out << " recovery_enabled : " << (recovery_enabled ? "true" : "false") << '\n';
|
out << " recovery_enabled : " << (recovery_enabled ? "true" : "false") << '\n';
|
||||||
out << " recovery_behavior_cnt : " << recovery_behavior_count << '\n';
|
out << " recovery_behavior_cnt : " << recovery_behavior_count << '\n';
|
||||||
if (recovery_routes.empty())
|
if (recovery_routes.empty())
|
||||||
@@ -389,6 +410,45 @@ bool StateMachine::preemptIfRequested(const StateMachineInput& in, StateMachineO
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void StateMachine::resumeFromPause(const StateMachineInput& in, StateMachineOutput& out)
|
||||||
|
{
|
||||||
|
// Đặt lại toàn bộ đồng hồ kiên nhẫn: một lần tạm dừng dài không được tính là "planner chậm"
|
||||||
|
// hay "controller hỏng", nếu không thì resume xong là rơi thẳng vào recovery.
|
||||||
|
beginPlanningCycle(in.now);
|
||||||
|
last_valid_control_ = in.now;
|
||||||
|
last_oscillation_reset_ = in.now;
|
||||||
|
sensor_stale_active_ = false;
|
||||||
|
out.reset_oscillation_origin = true;
|
||||||
|
travel_at_last_path_reset_ = 0.0; // origin đặt lại -> mốc recovery_reset_min_travel về 0
|
||||||
|
|
||||||
|
if (state_before_pause_ == NavigationState::kControlling)
|
||||||
|
{
|
||||||
|
// Nạp lại plan cho controller trước khi bám tiếp (2026-09-11). Local planner giữ trạng
|
||||||
|
// thái nội bộ theo thời gian (warm-start trajectory, slew, latch) từ lúc robot còn chạy;
|
||||||
|
// sau một quãng đứng yên trạng thái đó là của một robot khác. `setPlan` là đường reset
|
||||||
|
// duy nhất mà interface LocalPlanner có — plugin reset warm-start theo pose hiện tại ở
|
||||||
|
// đó. Bên gọi giữ nguyên plan mới nhất (`latest_plan_`) suốt lúc tạm dừng.
|
||||||
|
out.apply_plan = true;
|
||||||
|
out.run_controller = true;
|
||||||
|
enter(NavigationState::kControlling, in.now, "resume following the plan", out);
|
||||||
|
}
|
||||||
|
else if (state_before_pause_ == NavigationState::kExecutingActions)
|
||||||
|
{
|
||||||
|
// Action không bị huỷ khi tạm dừng nên không start lại — tick tiếp đúng action dở dang.
|
||||||
|
// Mốc action_patience được gieo lại: một quãng dừng dài không được tính vào trần thời
|
||||||
|
// gian của action, nếu không resume xong là ABORTED oan ngay lập tức.
|
||||||
|
action_started_at_ = in.now;
|
||||||
|
out.resume_action = true; // Handler cộng quãng dừng vào mốc timeout của nó.
|
||||||
|
out.tick_action = true;
|
||||||
|
enter(NavigationState::kExecutingActions, in.now, "resume running the action", out);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
out.start_planner = true;
|
||||||
|
enter(NavigationState::kPlanning, in.now, "resume planning", out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||||
{
|
{
|
||||||
StateMachineOutput out;
|
StateMachineOutput out;
|
||||||
@@ -411,6 +471,34 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
enter(NavigationState::kIdle, in.now, "request finished", out);
|
enter(NavigationState::kIdle, in.now, "request finished", out);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dừng khẩn xét TRƯỚC mọi thứ, kể cả cancel (2026-09-14). Là mức chứ không phải xung: chừng nào
|
||||||
|
// host còn giữ thì không nhánh nào của switch bên dưới được chạy — pause/resume/cancel/goal chờ
|
||||||
|
// đều bị bỏ qua, và cả kIdle có goal chờ cũng không được nhận. Chỉ khi host gỡ chốt mới về kIdle.
|
||||||
|
if (in.emergency)
|
||||||
|
{
|
||||||
|
if (state_ != NavigationState::kEmergency)
|
||||||
|
{
|
||||||
|
enterEmergency(in, out);
|
||||||
|
}
|
||||||
|
else if (!in.action_terminal)
|
||||||
|
{
|
||||||
|
// Cùng lý do với kCancelling: handler thiết bị cần tick để đưa thiết bị về vị trí an toàn rồi
|
||||||
|
// báo terminal. Không cấp vận tốc — phần chốt bất biến cuối hàm ép kNone cho mọi state phải dừng.
|
||||||
|
out.tick_action = true;
|
||||||
|
}
|
||||||
|
applyInvariants(in, out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (state_ == NavigationState::kEmergency)
|
||||||
|
{
|
||||||
|
// Cố ý KHÔNG nhận goal trong cùng cycle: ControlLoop đã vứt yêu cầu chờ lúc vào dừng khẩn và
|
||||||
|
// NavigationServer từ chối submit khi còn chốt, nên không có gì hợp lệ để nhận ở đây. Cycle kế
|
||||||
|
// kIdle nhận bình thường — host phải gửi goal mới, robot không tự chạy lại.
|
||||||
|
enter(NavigationState::kIdle, in.now, "emergency cleared", out);
|
||||||
|
applyInvariants(in, out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
// Mất pose nghĩa là không biết robot ở đâu. Khi đó controller không được chạy, và không nguồn nào
|
// Mất pose nghĩa là không biết robot ở đâu. Khi đó controller không được chạy, và không nguồn nào
|
||||||
// được phát vận tốc — kể cả recovery. Recovery vẫn được tick để nó tự báo lỗi theo contract của
|
// được phát vận tốc — kể cả recovery. Recovery vẫn được tick để nó tự báo lỗi theo contract của
|
||||||
// nó, nhưng lệnh nó sinh ra bị chặn ở phần chốt bất biến cuối hàm.
|
// nó, nhưng lệnh nó sinh ra bị chặn ở phần chốt bất biến cuối hàm.
|
||||||
@@ -442,7 +530,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
{
|
{
|
||||||
out.stop_planner = true;
|
out.stop_planner = true;
|
||||||
state_before_pause_ = NavigationState::kPlanning;
|
state_before_pause_ = NavigationState::kPlanning;
|
||||||
enter(NavigationState::kPaused, in.now, "paused while planning", out);
|
enter(NavigationState::kPausing, in.now, "pausing while planning", out);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -452,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;
|
||||||
@@ -519,7 +614,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
{
|
{
|
||||||
out.stop_planner = true;
|
out.stop_planner = true;
|
||||||
state_before_pause_ = NavigationState::kControlling;
|
state_before_pause_ = NavigationState::kControlling;
|
||||||
enter(NavigationState::kPaused, in.now, "paused while following the plan", out);
|
enter(NavigationState::kPausing, in.now, "pausing while following the plan", out);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -716,7 +811,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
// dài là không an toàn (nó dead-reckon theo thời gian). Resume sẽ lập plan lại từ đầu.
|
// dài là không an toàn (nó dead-reckon theo thời gian). Resume sẽ lập plan lại từ đầu.
|
||||||
out.cancel_recovery = true;
|
out.cancel_recovery = true;
|
||||||
state_before_pause_ = NavigationState::kPlanning;
|
state_before_pause_ = NavigationState::kPlanning;
|
||||||
enter(NavigationState::kPaused, in.now, "paused while recovering", out);
|
enter(NavigationState::kPausing, in.now, "pausing while recovering", out);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -856,12 +951,14 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
// dead-reckon, còn chạy lại một action thiết bị (nâng/hạ, sạc) từ đầu thì không chắc an
|
// dead-reckon, còn chạy lại một action thiết bị (nâng/hạ, sạc) từ đầu thì không chắc an
|
||||||
// toàn — action không idempotent. Tạm dừng chỉ ngừng tick; resume tick tiếp đúng action đó.
|
// toàn — action không idempotent. Tạm dừng chỉ ngừng tick; resume tick tiếp đúng action đó.
|
||||||
state_before_pause_ = NavigationState::kExecutingActions;
|
state_before_pause_ = NavigationState::kExecutingActions;
|
||||||
enter(NavigationState::kPaused, in.now, "paused while running an action", out);
|
out.pause_action = true; // Handler dịch mốc timeout của nó; không dừng thiết bị.
|
||||||
|
enter(NavigationState::kPausing, in.now, "pausing while running an action", out);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (in.action == ActionFeedback::kFailed)
|
if (in.action == ActionFeedback::kFailed || in.action == ActionFeedback::kCancelled)
|
||||||
{
|
{
|
||||||
|
// kCancelled ở đây là lỗi thứ tự gọi (không ai cancel trong EXECUTING_ACTIONS) — xử như hỏng.
|
||||||
// Action hỏng không có đường recovery: recovery behavior là công cụ phục hồi NAVIGATION
|
// Action hỏng không có đường recovery: recovery behavior là công cụ phục hồi NAVIGATION
|
||||||
// (dọn costmap, lùi, xoay), không giúp gì được một thiết bị đang hỏng. Kết thúc tường minh
|
// (dọn costmap, lùi, xoay), không giúp gì được một thiết bị đang hỏng. Kết thúc tường minh
|
||||||
// để mission layer quyết định làm gì với phần còn lại của order.
|
// để mission layer quyết định làm gì với phần còn lại của order.
|
||||||
@@ -909,6 +1006,58 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --------------------------------------------------------------------------------------
|
||||||
|
case NavigationState::kPausing:
|
||||||
|
{
|
||||||
|
// Đã nhận pause: stop_planner / cancel_recovery / pause_action đã phát ở cycle vào state,
|
||||||
|
// arbiter đang phát 0. Ở đây chỉ chờ mọi thành phần IM rồi mới sang kPaused — host đọc
|
||||||
|
// PAUSED là "đã dừng hẳn, làm gì cũng được" (2026-09-11). Cùng ba điều kiện quiescent với
|
||||||
|
// kCancelling; `settle_timeout` là trần.
|
||||||
|
if (preemptIfRequested(in, out))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (in.cancel_requested)
|
||||||
|
{
|
||||||
|
enter(NavigationState::kCancelling, in.now, "cancelled while pausing", out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (in.resume_requested)
|
||||||
|
{
|
||||||
|
// Chưa kịp dừng hẳn đã được bảo chạy tiếp: đi đúng đường resume của kPaused.
|
||||||
|
resumeFromPause(in, out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config_.settle_timeout <= 0.0)
|
||||||
|
{
|
||||||
|
if (in.robot_stopped)
|
||||||
|
{
|
||||||
|
enter(NavigationState::kPaused, in.now, "paused: robot stopped", out);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool quiescent = in.robot_stopped && !in.planner_busy && !in.recovery_busy && in.action_terminal;
|
||||||
|
if (quiescent)
|
||||||
|
{
|
||||||
|
enter(NavigationState::kPaused, in.now, "paused: runtime quiescent", out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (secondsInState(in.now) > config_.settle_timeout)
|
||||||
|
{
|
||||||
|
out.settle_timed_out = true;
|
||||||
|
enter(NavigationState::kPaused, in.now, "paused: settle timeout", out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// Action đã được bảo tạm dừng ở cycle vào state; tick tiếp cho handler thiết bị xác nhận.
|
||||||
|
if (!in.action_terminal)
|
||||||
|
{
|
||||||
|
out.tick_action = true;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// --------------------------------------------------------------------------------------
|
// --------------------------------------------------------------------------------------
|
||||||
case NavigationState::kPaused:
|
case NavigationState::kPaused:
|
||||||
{
|
{
|
||||||
@@ -926,34 +1075,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
}
|
}
|
||||||
if (in.resume_requested)
|
if (in.resume_requested)
|
||||||
{
|
{
|
||||||
// Đặt lại toàn bộ đồng hồ kiên nhẫn: một lần tạm dừng dài không được tính là "planner chậm"
|
resumeFromPause(in, out);
|
||||||
// hay "controller hỏng", nếu không thì resume xong là rơi thẳng vào recovery.
|
|
||||||
beginPlanningCycle(in.now);
|
|
||||||
last_valid_control_ = in.now;
|
|
||||||
last_oscillation_reset_ = in.now;
|
|
||||||
sensor_stale_active_ = false;
|
|
||||||
out.reset_oscillation_origin = true;
|
|
||||||
travel_at_last_path_reset_ = 0.0; // origin đặt lại -> mốc recovery_reset_min_travel về 0
|
|
||||||
|
|
||||||
if (state_before_pause_ == NavigationState::kControlling)
|
|
||||||
{
|
|
||||||
out.run_controller = true;
|
|
||||||
enter(NavigationState::kControlling, in.now, "resume following the plan", out);
|
|
||||||
}
|
|
||||||
else if (state_before_pause_ == NavigationState::kExecutingActions)
|
|
||||||
{
|
|
||||||
// Action không bị huỷ khi tạm dừng nên không start lại — tick tiếp đúng action dở dang.
|
|
||||||
// Mốc action_patience được gieo lại: một quãng dừng dài không được tính vào trần thời
|
|
||||||
// gian của action, nếu không resume xong là ABORTED oan ngay lập tức.
|
|
||||||
action_started_at_ = in.now;
|
|
||||||
out.tick_action = true;
|
|
||||||
enter(NavigationState::kExecutingActions, in.now, "resume running the action", out);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
out.start_planner = true;
|
|
||||||
enter(NavigationState::kPlanning, in.now, "resume planning", out);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -962,8 +1084,14 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
case NavigationState::kCancelling:
|
case NavigationState::kCancelling:
|
||||||
{
|
{
|
||||||
// Nguồn vận tốc đã là kNone nên bộ trọng tài phát lệnh 0 NGAY (arbiter cố ý không ramp khi
|
// Nguồn vận tốc đã là kNone nên bộ trọng tài phát lệnh 0 NGAY (arbiter cố ý không ramp khi
|
||||||
// nguồn là kNone — xem VelocityArbiter::arbitrate); trạng thái này vì vậy kết thúc ngay cycle
|
// nguồn là kNone — xem VelocityArbiter::arbitrate). Lệnh 0 là điều kiện CẦN, chưa đủ để
|
||||||
// robot_stopped bật, không cần thêm timeout.
|
// báo CANCELLED (2026-09-11): host đọc CANCELLED/PREEMPTED là "đã xong, gửi goal kế được"
|
||||||
|
// — mà goal kế bị `startPlan()` từ chối chừng nào thread planner còn chạy lượt cũ, và bị
|
||||||
|
// tính là hỏng. Ba điều kiện quiescent: lệnh/odom về 0, thread planner rảnh, action đã trả
|
||||||
|
// terminal. `settle_timeout` là trần: quá thì vẫn CANCELLED nhưng báo lỗi lên bên gọi.
|
||||||
|
if (config_.settle_timeout <= 0.0)
|
||||||
|
{
|
||||||
|
// Tắt: hành vi trước 2026-09-11 — chỉ chờ lệnh về 0.
|
||||||
if (in.robot_stopped)
|
if (in.robot_stopped)
|
||||||
{
|
{
|
||||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||||
@@ -972,6 +1100,32 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const bool quiescent = in.robot_stopped && !in.planner_busy && !in.recovery_busy && in.action_terminal;
|
||||||
|
if (quiescent)
|
||||||
|
{
|
||||||
|
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||||
|
"robot stopped, planner and recovery idle, action terminal", out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (secondsInState(in.now) > config_.settle_timeout)
|
||||||
|
{
|
||||||
|
out.settle_timed_out = true;
|
||||||
|
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||||
|
"cancel settle timeout", out);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Action đã bị bảo dừng ở cycle vào kCancelling; tick tiếp để handler thiết bị đưa thiết bị
|
||||||
|
// về vị trí an toàn rồi báo terminal. Không cấp vận tốc — phần chốt bất biến cuối hàm ép
|
||||||
|
// velocity_source về kNone cho mọi state phải dừng.
|
||||||
|
if (!in.action_terminal)
|
||||||
|
{
|
||||||
|
out.tick_action = true;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// --------------------------------------------------------------------------------------
|
// --------------------------------------------------------------------------------------
|
||||||
case NavigationState::kSucceeded:
|
case NavigationState::kSucceeded:
|
||||||
case NavigationState::kAborted:
|
case NavigationState::kAborted:
|
||||||
@@ -980,8 +1134,15 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
applyInvariants(in, out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
void StateMachine::applyInvariants(const StateMachineInput& in, StateMachineOutput& out)
|
||||||
|
{
|
||||||
// ------------------------------------------------------------------------------------------
|
// ------------------------------------------------------------------------------------------
|
||||||
// Chốt bất biến trước khi trả ra. Ba dòng này là hàng rào an toàn cuối cùng của lõi.
|
// Chốt bất biến trước khi trả ra. Đây là hàng rào an toàn cuối cùng của lõi — MỌI đường ra của
|
||||||
|
// update() đều phải qua đây, kể cả hai đường về sớm của dừng khẩn.
|
||||||
// ------------------------------------------------------------------------------------------
|
// ------------------------------------------------------------------------------------------
|
||||||
out.state = state_;
|
out.state = state_;
|
||||||
|
|
||||||
@@ -1015,8 +1176,45 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
|||||||
out.run_controller = false;
|
out.run_controller = false;
|
||||||
out.tick_recovery = false;
|
out.tick_recovery = false;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return out;
|
bool StateMachine::actionInFlight() const
|
||||||
|
{
|
||||||
|
if (state_ == NavigationState::kExecutingActions)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Tạm dừng KHÔNG huỷ action (xem kExecutingActions): handler vẫn đang giữ thiết bị dở dang.
|
||||||
|
return (state_ == NavigationState::kPausing || state_ == NavigationState::kPaused) &&
|
||||||
|
state_before_pause_ == NavigationState::kExecutingActions;
|
||||||
|
}
|
||||||
|
|
||||||
|
void StateMachine::enterEmergency(const StateMachineInput& in, StateMachineOutput& out)
|
||||||
|
{
|
||||||
|
// Dọn như preempt + cancel gộp: mọi thứ đang chạy đều bị bảo dừng. Từng cờ theo state để test
|
||||||
|
// khẳng định được "chỉ dừng cái đang chạy" — runner tự no-op khi rảnh, nhưng output phải nói thật.
|
||||||
|
out.stop_planner = true;
|
||||||
|
if (state_ == NavigationState::kRecovering)
|
||||||
|
{
|
||||||
|
out.cancel_recovery = true;
|
||||||
|
}
|
||||||
|
// kCancelling đã phát cancel_action ở cycle vào nó — không phát lần hai.
|
||||||
|
if (actionInFlight())
|
||||||
|
{
|
||||||
|
out.cancel_action = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chặng đang chạy được báo CANCELLED đúng một lần, ngay tại đây (state ≠ kIdle ⇔ có yêu cầu đang
|
||||||
|
// chạy). kCancelling chưa báo (nó báo lúc vào kCancelled) nên vẫn phải báo. Không có state terminal
|
||||||
|
// xen giữa — kEmergency là nơi ở lại, và ControlLoop xoá yêu cầu hiện hành như với mọi outcome.
|
||||||
|
if (state_ != NavigationState::kIdle)
|
||||||
|
{
|
||||||
|
out.report_outcome = true;
|
||||||
|
out.outcome = NavigationOutcome::kCancelled;
|
||||||
|
}
|
||||||
|
|
||||||
|
state_before_pause_ = NavigationState::kIdle; // Không còn gì để quay về; dọn cho refreshFeedback.
|
||||||
|
enter(NavigationState::kEmergency, in.now, "emergency stop", out);
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace move_base2
|
} // namespace move_base2
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
#include <robot/node_handle.h>
|
#include <robot/node_handle.h>
|
||||||
|
|
||||||
#include <action_core/action_handler.h>
|
#include <action_core/action_handler.h>
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
#include <move_base2/runners/action_runner.h>
|
#include <move_base2/runners/action_runner.h>
|
||||||
|
|
||||||
#include "fake_ports.h"
|
#include "fake_ports.h"
|
||||||
@@ -69,6 +70,17 @@ public:
|
|||||||
{
|
{
|
||||||
++update_count;
|
++update_count;
|
||||||
action_core::ActionTick tick;
|
action_core::ActionTick tick;
|
||||||
|
if (ticks_after_cancel_left >= 0)
|
||||||
|
{
|
||||||
|
if (ticks_after_cancel_left-- > 0)
|
||||||
|
{
|
||||||
|
tick.status = action_core::ActionStatus::kRunning;
|
||||||
|
return tick;
|
||||||
|
}
|
||||||
|
tick.status = action_core::ActionStatus::kCancelled;
|
||||||
|
tick.message = "device safe";
|
||||||
|
return tick;
|
||||||
|
}
|
||||||
tick.status = next_status;
|
tick.status = next_status;
|
||||||
return tick;
|
return tick;
|
||||||
}
|
}
|
||||||
@@ -76,15 +88,46 @@ public:
|
|||||||
void cancel() override
|
void cancel() override
|
||||||
{
|
{
|
||||||
++cancel_count;
|
++cancel_count;
|
||||||
|
if (cancel_needs_ticks)
|
||||||
|
{
|
||||||
|
ticks_after_cancel_left = cancel_ticks;
|
||||||
|
next_status = action_core::ActionStatus::kRunning;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cancelNeedsTicks() const override
|
||||||
|
{
|
||||||
|
return cancel_needs_ticks;
|
||||||
|
}
|
||||||
|
|
||||||
|
void pause(const robot::Time& now) override
|
||||||
|
{
|
||||||
|
++pause_count;
|
||||||
|
last_pause_at = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
void resume(const robot::Time& now) override
|
||||||
|
{
|
||||||
|
++resume_count;
|
||||||
|
last_resume_at = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool configure_ok = true;
|
bool configure_ok = true;
|
||||||
bool start_ok = true;
|
bool start_ok = true;
|
||||||
action_core::ActionStatus next_status = action_core::ActionStatus::kRunning;
|
action_core::ActionStatus next_status = action_core::ActionStatus::kRunning;
|
||||||
|
|
||||||
|
/// Mô hình handler thiết bị: sau cancel() còn `cancel_ticks` lượt update() rồi mới kCancelled.
|
||||||
|
bool cancel_needs_ticks = false;
|
||||||
|
int cancel_ticks = 2;
|
||||||
|
int ticks_after_cancel_left = -1;
|
||||||
|
|
||||||
int start_count = 0;
|
int start_count = 0;
|
||||||
int update_count = 0;
|
int update_count = 0;
|
||||||
int cancel_count = 0;
|
int cancel_count = 0;
|
||||||
|
int pause_count = 0;
|
||||||
|
int resume_count = 0;
|
||||||
|
robot::Time last_pause_at;
|
||||||
|
robot::Time last_resume_at;
|
||||||
std::string last_action_id;
|
std::string last_action_id;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -248,6 +291,100 @@ TEST(ActionRunner, CancelReachesHandlerAndClearsActive)
|
|||||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed);
|
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(ActionRunner, DeviceHandlerKeepsBeingTickedAfterCancelUntilItReportsCancelled)
|
||||||
|
{
|
||||||
|
// Pha 3 (2026-09-11): handler khai cancelNeedsTicks → runner GIỮ nó sau cancel(), tick tiếp tới
|
||||||
|
// khi trả kCancelled; hàng kAction = stopping trong lúc đó, idle khi xong.
|
||||||
|
Rig rig;
|
||||||
|
move_base2::ComponentStatusBoard board;
|
||||||
|
rig.runner.attachStatusBoard(&board);
|
||||||
|
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"lift"});
|
||||||
|
handler->cancel_needs_ticks = true;
|
||||||
|
handler->cancel_ticks = 2;
|
||||||
|
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||||
|
ASSERT_TRUE(rig.load("actions_empty"));
|
||||||
|
ASSERT_TRUE(rig.runner.start(makeAction("lift")));
|
||||||
|
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kBusy);
|
||||||
|
|
||||||
|
rig.runner.cancel();
|
||||||
|
EXPECT_EQ(handler->cancel_count, 1);
|
||||||
|
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kStopping);
|
||||||
|
|
||||||
|
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||||
|
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||||
|
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kStopping);
|
||||||
|
const ActionTick done = rig.runner.update();
|
||||||
|
EXPECT_EQ(done.status, ActionTick::Status::kCancelled);
|
||||||
|
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kIdle);
|
||||||
|
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed) << "handler was released";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ActionRunner, PerceptionHandlerIsReleasedRightAwayOnCancel)
|
||||||
|
{
|
||||||
|
Rig rig;
|
||||||
|
move_base2::ComponentStatusBoard board;
|
||||||
|
rig.runner.attachStatusBoard(&board);
|
||||||
|
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"detect"});
|
||||||
|
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||||
|
ASSERT_TRUE(rig.load("actions_empty"));
|
||||||
|
ASSERT_TRUE(rig.runner.start(makeAction("detect")));
|
||||||
|
|
||||||
|
rig.runner.cancel();
|
||||||
|
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kIdle);
|
||||||
|
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed) << "no handler active";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ActionRunner, PauseAndResumeReachTheHandlerWithTheClockTime)
|
||||||
|
{
|
||||||
|
Rig rig;
|
||||||
|
move_base2::ComponentStatusBoard board;
|
||||||
|
rig.runner.attachStatusBoard(&board);
|
||||||
|
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"});
|
||||||
|
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||||
|
ASSERT_TRUE(rig.load("actions_empty"));
|
||||||
|
ASSERT_TRUE(rig.runner.start(makeAction("pick")));
|
||||||
|
|
||||||
|
rig.clock.advance(1.0);
|
||||||
|
rig.runner.pause();
|
||||||
|
EXPECT_EQ(handler->pause_count, 1);
|
||||||
|
EXPECT_DOUBLE_EQ(handler->last_pause_at.toSec(), 1001.0);
|
||||||
|
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kPaused);
|
||||||
|
|
||||||
|
rig.clock.advance(30.0);
|
||||||
|
rig.runner.resume();
|
||||||
|
EXPECT_EQ(handler->resume_count, 1);
|
||||||
|
EXPECT_DOUBLE_EQ(handler->last_resume_at.toSec(), 1031.0);
|
||||||
|
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kBusy);
|
||||||
|
|
||||||
|
// Không có action đang chạy thì pause/resume không tới handler nào.
|
||||||
|
rig.runner.cancel();
|
||||||
|
rig.runner.pause();
|
||||||
|
rig.runner.resume();
|
||||||
|
EXPECT_EQ(handler->pause_count, 1);
|
||||||
|
EXPECT_EQ(handler->resume_count, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ActionRunner, LoadedNoopHandlerDoesNotCountPausedTimeTowardsItsDuration)
|
||||||
|
{
|
||||||
|
// Handler thật (noop, duration 2 s): pause 30 s giữa chừng, resume, phải còn chạy tiếp đúng phần
|
||||||
|
// thời gian còn lại — không kết thúc sớm, không timeout oan.
|
||||||
|
Rig rig;
|
||||||
|
ASSERT_TRUE(rig.load("actions"));
|
||||||
|
ASSERT_TRUE(rig.runner.start(makeAction("wait", "w1"))); // duration: 2.0 s, timeout 10 s
|
||||||
|
|
||||||
|
rig.clock.advance(1.0);
|
||||||
|
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||||
|
|
||||||
|
rig.runner.pause();
|
||||||
|
rig.clock.advance(30.0); // đứng chờ lâu hơn cả timeout 10 s
|
||||||
|
rig.runner.resume();
|
||||||
|
|
||||||
|
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning)
|
||||||
|
<< "the 30 s pause must not count: 1 s of 2 s elapsed, and the 10 s timeout must not fire";
|
||||||
|
rig.clock.advance(1.0);
|
||||||
|
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
TEST(ActionRunner, CancelWithoutActiveActionIsSafe)
|
TEST(ActionRunner, CancelWithoutActiveActionIsSafe)
|
||||||
{
|
{
|
||||||
Rig rig;
|
Rig rig;
|
||||||
|
|||||||
144
test/component_status_test.cpp
Normal file
144
test/component_status_test.cpp
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* move_base2 — test bảng trạng thái thành phần: nguồn sự thật cho quiescence và watchdog.
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
|
|
||||||
|
using move_base2::Component;
|
||||||
|
using move_base2::ComponentPhase;
|
||||||
|
using move_base2::ComponentStatusBoard;
|
||||||
|
|
||||||
|
TEST(ComponentStatusBoard, StartsIdleEverywhere)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||||
|
{
|
||||||
|
const Component c = static_cast<Component>(i);
|
||||||
|
EXPECT_TRUE(board.isIdle(c)) << move_base2::toString(c);
|
||||||
|
EXPECT_EQ(board.at(c).progress_ticks.load(), 0u);
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(board.anyHung());
|
||||||
|
EXPECT_TRUE(board.allIdle({Component::kGlobalPlanner, Component::kRecovery, Component::kAction}));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ComponentStatusBoard, EnterChangesPhaseAndCountsAsProgress)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
board.enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||||
|
EXPECT_EQ(board.phase(Component::kGlobalPlanner), ComponentPhase::kBusy);
|
||||||
|
EXPECT_FALSE(board.isIdle(Component::kGlobalPlanner));
|
||||||
|
EXPECT_FALSE(board.allIdle({Component::kGlobalPlanner, Component::kRecovery}));
|
||||||
|
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 1u);
|
||||||
|
EXPECT_GT(board.at(Component::kGlobalPlanner).phase_since_ns.load(), 0);
|
||||||
|
|
||||||
|
board.enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||||
|
EXPECT_EQ(board.phase(Component::kGlobalPlanner), ComponentPhase::kStopping);
|
||||||
|
board.enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||||
|
EXPECT_TRUE(board.isIdle(Component::kGlobalPlanner));
|
||||||
|
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 3u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ComponentStatusBoard, ProgressDoesNotChangePhase)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
board.enter(Component::kRecovery, ComponentPhase::kBusy);
|
||||||
|
const std::int64_t since = board.at(Component::kRecovery).phase_since_ns.load();
|
||||||
|
board.progress(Component::kRecovery);
|
||||||
|
board.progress(Component::kRecovery);
|
||||||
|
EXPECT_EQ(board.phase(Component::kRecovery), ComponentPhase::kBusy);
|
||||||
|
EXPECT_EQ(board.at(Component::kRecovery).phase_since_ns.load(), since)
|
||||||
|
<< "progress must not restart the phase clock";
|
||||||
|
EXPECT_EQ(board.at(Component::kRecovery).progress_ticks.load(), 3u);
|
||||||
|
EXPECT_GE(board.at(Component::kRecovery).last_progress_ns.load(), since);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ComponentStatusBoard, SecondsInPhaseAndSinceProgressGrowWithWallTime)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
board.enter(Component::kControlLoop, ComponentPhase::kBusy);
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||||
|
EXPECT_GE(board.secondsInPhase(Component::kControlLoop), 0.015);
|
||||||
|
EXPECT_GE(board.secondsSinceProgress(Component::kControlLoop), 0.015);
|
||||||
|
board.progress(Component::kControlLoop);
|
||||||
|
EXPECT_LT(board.secondsSinceProgress(Component::kControlLoop), 0.015);
|
||||||
|
EXPECT_GE(board.secondsInPhase(Component::kControlLoop), 0.015) << "phase clock untouched";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ComponentStatusBoard, AnyHungSeesASingleHungRow)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
board.enter(Component::kCostmapLocal, ComponentPhase::kHung);
|
||||||
|
EXPECT_TRUE(board.anyHung());
|
||||||
|
board.enter(Component::kCostmapLocal, ComponentPhase::kIdle);
|
||||||
|
EXPECT_FALSE(board.anyHung());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ComponentStatusBoard, EveryComponentAndPhaseHasAName)
|
||||||
|
{
|
||||||
|
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||||
|
{
|
||||||
|
const std::string name = move_base2::toString(static_cast<Component>(i));
|
||||||
|
EXPECT_FALSE(name.empty());
|
||||||
|
EXPECT_NE(name, "unknown");
|
||||||
|
}
|
||||||
|
for (const ComponentPhase p : {ComponentPhase::kIdle, ComponentPhase::kBusy, ComponentPhase::kStopping,
|
||||||
|
ComponentPhase::kPaused, ComponentPhase::kHung,
|
||||||
|
ComponentPhase::kWaitingForCostmap})
|
||||||
|
{
|
||||||
|
const std::string name = move_base2::toString(p);
|
||||||
|
EXPECT_FALSE(name.empty());
|
||||||
|
EXPECT_NE(name, "unknown");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ComponentStatusBoard, ConcurrentWriterAndReaderDoNotTearOrCrash)
|
||||||
|
{
|
||||||
|
// Mô hình thật: thread planner ghi hàng của nó, control thread và watchdog đọc. Không lock — mọi
|
||||||
|
// field atomic, đọc phải luôn thấy một phase hợp lệ.
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
std::atomic<bool> stop{false};
|
||||||
|
std::atomic<std::uint64_t> bad_reads{0};
|
||||||
|
|
||||||
|
std::thread writer([&] {
|
||||||
|
for (int i = 0; i < 200000; ++i)
|
||||||
|
{
|
||||||
|
board.enter(Component::kGlobalPlanner, (i & 1) ? ComponentPhase::kBusy : ComponentPhase::kIdle);
|
||||||
|
board.progress(Component::kGlobalPlanner);
|
||||||
|
}
|
||||||
|
stop = true;
|
||||||
|
});
|
||||||
|
std::thread reader([&] {
|
||||||
|
while (!stop)
|
||||||
|
{
|
||||||
|
const ComponentPhase p = board.phase(Component::kGlobalPlanner);
|
||||||
|
if (p != ComponentPhase::kBusy && p != ComponentPhase::kIdle)
|
||||||
|
{
|
||||||
|
++bad_reads;
|
||||||
|
}
|
||||||
|
(void)board.secondsInPhase(Component::kGlobalPlanner);
|
||||||
|
(void)board.allIdle({Component::kGlobalPlanner, Component::kRecovery});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
writer.join();
|
||||||
|
reader.join();
|
||||||
|
EXPECT_EQ(bad_reads.load(), 0u);
|
||||||
|
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 400000u);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char** argv)
|
||||||
|
{
|
||||||
|
::testing::InitGoogleTest(&argc, argv);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
||||||
@@ -16,6 +16,14 @@ move_base2:
|
|||||||
action_patience: 0.0 # [s] 0 = tắt; lưới cuối, không phải cơ chế timeout chính
|
action_patience: 0.0 # [s] 0 = tắt; lưới cuối, không phải cơ chế timeout chính
|
||||||
max_planning_retries: -1 # < 0 = không giới hạn
|
max_planning_retries: -1 # < 0 = không giới hạn
|
||||||
recovery_behavior_enabled: true
|
recovery_behavior_enabled: true
|
||||||
|
settle_timeout: 3.5 # [s] chờ quiescent ở CANCELLING; 0 = tắt
|
||||||
|
stopped_measured_linear_eps: 0.03 # [m/s] "đã dừng" theo odom; 0 = bỏ odom
|
||||||
|
stopped_measured_angular_eps: 0.04 # [rad/s]
|
||||||
|
watchdog_period: 0.25 # [s]
|
||||||
|
local_planner_call_budget: 0.7 # [s]
|
||||||
|
recovery_stall_budget: 6.0 # [s]
|
||||||
|
action_stall_budget: 1.5 # [s]
|
||||||
|
control_loop_stall_budget: 0.9 # [s]
|
||||||
|
|
||||||
max_vel_x: 0.5 # [m/s] tiến
|
max_vel_x: 0.5 # [m/s] tiến
|
||||||
min_vel_x: -0.2 # [m/s] lùi, ÂM
|
min_vel_x: -0.2 # [m/s] lùi, ÂM
|
||||||
@@ -276,6 +284,10 @@ TestPlannerThrowing:
|
|||||||
library_path: libmove_base2_test_global_planner
|
library_path: libmove_base2_test_global_planner
|
||||||
TestPlannerInitFails:
|
TestPlannerInitFails:
|
||||||
library_path: libmove_base2_test_global_planner
|
library_path: libmove_base2_test_global_planner
|
||||||
|
TestPlannerSlowPreemptable: # search 2 s, thoát khi preempt() — mô hình SBPL + abort flag
|
||||||
|
library_path: libmove_base2_test_global_planner
|
||||||
|
TestPlannerSlowStubborn: # search 0.4 s, KHÔNG nhìn preempt — mô hình plugin cũ
|
||||||
|
library_path: libmove_base2_test_global_planner
|
||||||
|
|
||||||
# TestPlannerMissingLibrary cố ý KHÔNG khai library_path.
|
# TestPlannerMissingLibrary cố ý KHÔNG khai library_path.
|
||||||
|
|
||||||
|
|||||||
@@ -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,71 @@ 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)
|
||||||
|
{
|
||||||
|
// Cây config cũ (trước 2026-09-11) không có ba khoá này: phải giữ default BẬT (2 s, 0.02) chứ
|
||||||
|
// không im lặng rơi về hành vi cũ "CANCELLED ngay khi lệnh = 0".
|
||||||
|
const MoveBase2Config config = loadFrom("move_base2_no_planner");
|
||||||
|
EXPECT_DOUBLE_EQ(config.state_machine.settle_timeout, 2.0);
|
||||||
|
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_linear_eps, 0.02);
|
||||||
|
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_angular_eps, 0.02);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(MoveBase2Config, WatchdogKeysFallBackToDefaultsWhenAbsent)
|
||||||
|
{
|
||||||
|
const MoveBase2Config config = loadFrom("move_base2_no_planner");
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.period, 0.1);
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.control_loop_stall_budget, 0.5);
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.action_stall_budget, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(MoveBase2Config, RejectsNegativeWatchdogPeriod)
|
||||||
|
{
|
||||||
|
MoveBase2Config config = minimalValid();
|
||||||
|
config.watchdog.period = -1.0;
|
||||||
|
std::string error;
|
||||||
|
EXPECT_FALSE(config.validate(error));
|
||||||
|
EXPECT_NE(error.find("watchdog_period"), std::string::npos);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(MoveBase2Config, RejectsNegativeCancelSettleTimeout)
|
||||||
|
{
|
||||||
|
MoveBase2Config config = minimalValid();
|
||||||
|
config.state_machine.settle_timeout = -0.5;
|
||||||
|
std::string error;
|
||||||
|
EXPECT_FALSE(config.validate(error));
|
||||||
|
EXPECT_NE(error.find("settle_timeout"), std::string::npos);
|
||||||
|
}
|
||||||
|
|
||||||
TEST(MoveBase2Config, RejectsRecoveryEnabledWithNoBehaviorLoaded)
|
TEST(MoveBase2Config, RejectsRecoveryEnabledWithNoBehaviorLoaded)
|
||||||
{
|
{
|
||||||
// Ràng buộc thứ tự khởi tạo: RecoveryRunner không nạp được behavior nào mà
|
// Ràng buộc thứ tự khởi tạo: RecoveryRunner không nạp được behavior nào mà
|
||||||
@@ -153,6 +219,16 @@ TEST(MoveBase2Config, ReadsEveryGroupFromYaml)
|
|||||||
EXPECT_DOUBLE_EQ(config.state_machine.controller_patience, 15.0);
|
EXPECT_DOUBLE_EQ(config.state_machine.controller_patience, 15.0);
|
||||||
EXPECT_EQ(config.state_machine.max_planning_retries, -1);
|
EXPECT_EQ(config.state_machine.max_planning_retries, -1);
|
||||||
EXPECT_TRUE(config.state_machine.recovery_enabled);
|
EXPECT_TRUE(config.state_machine.recovery_enabled);
|
||||||
|
EXPECT_DOUBLE_EQ(config.state_machine.settle_timeout, 3.5);
|
||||||
|
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_linear_eps, 0.03);
|
||||||
|
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_angular_eps, 0.04);
|
||||||
|
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.period, 0.25);
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.planner_timeout, 5.0) << "copied from planner_timeout";
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.local_planner_call_budget, 0.7);
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.recovery_stall_budget, 6.0);
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.action_stall_budget, 1.5);
|
||||||
|
EXPECT_DOUBLE_EQ(config.watchdog.control_loop_stall_budget, 0.9);
|
||||||
|
|
||||||
EXPECT_DOUBLE_EQ(config.velocity.max_vel_x, 0.5);
|
EXPECT_DOUBLE_EQ(config.velocity.max_vel_x, 0.5);
|
||||||
EXPECT_DOUBLE_EQ(config.velocity.min_vel_x, -0.2);
|
EXPECT_DOUBLE_EQ(config.velocity.min_vel_x, -0.2);
|
||||||
|
|||||||
336
test/deferred_goal_test.cpp
Normal file
336
test/deferred_goal_test.cpp
Normal file
@@ -0,0 +1,336 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* move_base2 — quy đích đến muộn về pose tuyệt đối (ControlLoop::resolveDeferredGoal).
|
||||||
|
*
|
||||||
|
* Mission layer sinh chặng lúc robot còn chưa tới chỗ xuất phát, nên đích của chặng có thể tới dưới
|
||||||
|
* ba dạng chưa-phải-pose: một TF frame, một quãng đường tương đối, một góc quay tương đối. Cả ba
|
||||||
|
* được quy về pose tuyệt đối đúng một lần, tại `submit`, và test này khoá phép quy đó.
|
||||||
|
*
|
||||||
|
* Vì sao đáng test riêng: một chặng quay tại chỗ từng chạy suốt mà robot không quay độ nào, vì
|
||||||
|
* nhánh quãng-tương-đối chép NGUYÊN pose hiện tại (gồm cả orientation) rồi cộng 0 mét — goal trùng
|
||||||
|
* khít chỗ đang đứng nên goal checker báo đã tới ngay lập tức.
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include <cmath>
|
||||||
|
#include <limits>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include <move_base2/control_loop.h>
|
||||||
|
|
||||||
|
#include "fake_ports.h"
|
||||||
|
|
||||||
|
using move_base2::ControlLoop;
|
||||||
|
using move_base2::ControlLoopConfig;
|
||||||
|
using move_base2::ControlLoopDeps;
|
||||||
|
using move_base2::MotionProfile;
|
||||||
|
using move_base2::NavigationRequest;
|
||||||
|
using move_base2::testing::FakeActionPort;
|
||||||
|
using move_base2::testing::FakeClockPort;
|
||||||
|
using move_base2::testing::FakeControllerPort;
|
||||||
|
using move_base2::testing::FakeCostmapStatusPort;
|
||||||
|
using move_base2::testing::FakeEnvironmentPort;
|
||||||
|
using move_base2::testing::FakeMissionPort;
|
||||||
|
using move_base2::testing::FakePlannerPort;
|
||||||
|
using move_base2::testing::FakePosePort;
|
||||||
|
using move_base2::testing::FakeRecoveryPort;
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
|
||||||
|
|
||||||
|
ControlLoopConfig baseConfig()
|
||||||
|
{
|
||||||
|
ControlLoopConfig config;
|
||||||
|
|
||||||
|
config.state_machine.planner_patience = 0.5; // [s]
|
||||||
|
config.state_machine.controller_patience = 0.5; // [s]
|
||||||
|
config.state_machine.oscillation_timeout = 0.0; // tắt
|
||||||
|
config.state_machine.recovery_enabled = false;
|
||||||
|
|
||||||
|
config.velocity.max_vel_x = 0.5; // [m/s]
|
||||||
|
config.velocity.min_vel_x = -0.2; // [m/s]
|
||||||
|
config.velocity.max_vel_theta = 1.0; // [rad/s]
|
||||||
|
config.velocity.max_accel_x = 100.0; // [m/s^2]
|
||||||
|
config.velocity.max_accel_theta = 100.0; // [rad/s^2]
|
||||||
|
|
||||||
|
config.nominal_control_period = 0.05; // [s]
|
||||||
|
|
||||||
|
config.position.global_planner_name = "FakeGlobalPlanner";
|
||||||
|
config.position.local_planner_name = "FakeLocalPlanner";
|
||||||
|
config.docking = config.position;
|
||||||
|
config.go_straight = config.position;
|
||||||
|
config.rotate = config.position;
|
||||||
|
config.rotate.local_planner_name = "FakeRotatePlanner";
|
||||||
|
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Yaw [rad] của một pose, để đọc lại kết quả đã quy.
|
||||||
|
double yawOf(const robot_geometry_msgs::PoseStamped& pose)
|
||||||
|
{
|
||||||
|
const auto& q = pose.pose.orientation;
|
||||||
|
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class Fixture
|
||||||
|
* @brief Control loop nối cổng giả, đủ để `submit` chạy tới lượt lập plan đầu tiên.
|
||||||
|
*/
|
||||||
|
class Fixture
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
Fixture() : recovery_(0)
|
||||||
|
{
|
||||||
|
pose_.setPosition(2.0, 3.0); // [m]
|
||||||
|
pose_.setYaw(0.0); // [rad]
|
||||||
|
|
||||||
|
deps_.clock = &clock_;
|
||||||
|
deps_.pose = &pose_;
|
||||||
|
deps_.planner = &planner_;
|
||||||
|
deps_.controller = &controller_;
|
||||||
|
deps_.recovery = &recovery_;
|
||||||
|
deps_.mission = &mission_;
|
||||||
|
deps_.action = &action_;
|
||||||
|
deps_.costmap_status = &costmap_status_;
|
||||||
|
deps_.environment = &environment_;
|
||||||
|
|
||||||
|
std::string error;
|
||||||
|
EXPECT_TRUE(loop_.configure(baseConfig(), deps_, error)) << error;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Chặng quay tại chỗ: 0 m tịnh tiến cộng một góc.
|
||||||
|
static NavigationRequest rotationRequest(double relative_yaw)
|
||||||
|
{
|
||||||
|
NavigationRequest request;
|
||||||
|
request.profile = MotionProfile::kRotate;
|
||||||
|
request.goal.header.frame_id = "map";
|
||||||
|
request.goal.pose.orientation.w = 1.0;
|
||||||
|
request.relative_distance = 0.0; // [m]
|
||||||
|
request.relative_yaw = relative_yaw;
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Chặng đi thẳng, không góc — dạng đã chạy từ trước khi có relative_yaw.
|
||||||
|
static NavigationRequest straightRequest(double relative_distance)
|
||||||
|
{
|
||||||
|
NavigationRequest request;
|
||||||
|
request.profile = MotionProfile::kGoStraight;
|
||||||
|
request.goal.header.frame_id = "map";
|
||||||
|
request.goal.pose.orientation.w = 1.0;
|
||||||
|
request.relative_distance = relative_distance;
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool submit(const NavigationRequest& request, std::string& reason)
|
||||||
|
{
|
||||||
|
return loop_.submit(request, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Đích đã quy, đọc từ cổng planner sau khi lượt lập plan đầu tiên được phát đi.
|
||||||
|
const robot_geometry_msgs::PoseStamped& resolvedGoal()
|
||||||
|
{
|
||||||
|
loop_.step();
|
||||||
|
return planner_.pendingGoal();
|
||||||
|
}
|
||||||
|
|
||||||
|
FakePosePort& pose()
|
||||||
|
{
|
||||||
|
return pose_;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
ControlLoop loop_;
|
||||||
|
ControlLoopDeps deps_;
|
||||||
|
FakeClockPort clock_;
|
||||||
|
FakePosePort pose_;
|
||||||
|
FakePlannerPort planner_;
|
||||||
|
FakeControllerPort controller_;
|
||||||
|
FakeRecoveryPort recovery_;
|
||||||
|
FakeMissionPort mission_;
|
||||||
|
FakeActionPort action_;
|
||||||
|
FakeCostmapStatusPort costmap_status_;
|
||||||
|
FakeEnvironmentPort environment_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(DeferredGoal, RotationKeepsThePositionAndTurnsTheHeading)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(0.0);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.submit(Fixture::rotationRequest(M_PI_2), reason)) << reason;
|
||||||
|
|
||||||
|
const auto& goal = fixture.resolvedGoal();
|
||||||
|
EXPECT_NEAR(goal.pose.position.x, 2.0, 1e-9) << "[m] chặng quay không được dịch chuyển robot";
|
||||||
|
EXPECT_NEAR(goal.pose.position.y, 3.0, 1e-9);
|
||||||
|
EXPECT_NEAR(yawOf(goal), M_PI_2, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, RotationIsRelativeToTheHeadingTheRobotHasNow)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(1.0); // [rad]
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.submit(Fixture::rotationRequest(0.5), reason)) << reason;
|
||||||
|
|
||||||
|
// Góc là DELTA, không phải hướng tuyệt đối: cùng một yêu cầu gửi ở hai hướng khác nhau phải cho
|
||||||
|
// hai đích khác nhau.
|
||||||
|
EXPECT_NEAR(yawOf(fixture.resolvedGoal()), 1.5, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, ANegativeAngleTurnsTheOtherWay)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(0.0);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.submit(Fixture::rotationRequest(-M_PI_4), reason)) << reason;
|
||||||
|
EXPECT_NEAR(yawOf(fixture.resolvedGoal()), -M_PI_4, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, TheResolvedQuaternionIsNormalised)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(0.3);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
// submit() chạy isQuaternionValid() ngay sau khi quy; một quaternion dựng thiếu thành phần sẽ bị
|
||||||
|
// từ chối ở đó chứ không đi tiếp.
|
||||||
|
ASSERT_TRUE(fixture.submit(Fixture::rotationRequest(2.0), reason)) << reason;
|
||||||
|
|
||||||
|
const auto& q = fixture.resolvedGoal().pose.orientation;
|
||||||
|
EXPECT_NEAR(std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w), 1.0, 1e-9);
|
||||||
|
EXPECT_DOUBLE_EQ(q.x, 0.0) << "robot đi trên mặt phẳng: chỉ z-w được mang giá trị";
|
||||||
|
EXPECT_DOUBLE_EQ(q.y, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, AStraightLegWithoutAnAngleKeepsTheCurrentHeading)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(0.7); // [rad]
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.submit(Fixture::straightRequest(1.0), reason)) << reason;
|
||||||
|
|
||||||
|
// relative_yaw = NaN phải để orientation nguyên vẹn. Một giá trị 0 ở đây thay vì NaN sẽ ép mọi
|
||||||
|
// chặng go_straight phải kết thúc ở hướng 0 rad.
|
||||||
|
const auto& goal = fixture.resolvedGoal();
|
||||||
|
EXPECT_NEAR(yawOf(goal), 0.7, 1e-9);
|
||||||
|
EXPECT_NEAR(goal.pose.position.x, 2.0 + std::cos(0.7), 1e-9) << "[m] tiến theo trục thân robot";
|
||||||
|
EXPECT_NEAR(goal.pose.position.y, 3.0 + std::sin(0.7), 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, DistanceAndAngleCanBeAskedForTogether)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(0.0);
|
||||||
|
|
||||||
|
NavigationRequest request = Fixture::straightRequest(2.0);
|
||||||
|
request.relative_yaw = M_PI_2;
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.submit(request, reason)) << reason;
|
||||||
|
|
||||||
|
// Quãng đường tính theo hướng LÚC NHẬN chặng, không theo hướng sau khi quay.
|
||||||
|
const auto& goal = fixture.resolvedGoal();
|
||||||
|
EXPECT_NEAR(goal.pose.position.x, 4.0, 1e-9);
|
||||||
|
EXPECT_NEAR(goal.pose.position.y, 3.0, 1e-9);
|
||||||
|
EXPECT_NEAR(yawOf(goal), M_PI_2, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, AnAbsoluteGoalIsLeftAlone)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(0.0);
|
||||||
|
|
||||||
|
NavigationRequest request;
|
||||||
|
request.profile = MotionProfile::kPosition;
|
||||||
|
request.goal.header.frame_id = "map";
|
||||||
|
request.goal.pose.position.x = 9.0; // [m]
|
||||||
|
request.goal.pose.position.y = 8.0; // [m]
|
||||||
|
request.goal.pose.orientation.z = std::sin(0.5 * 1.2);
|
||||||
|
request.goal.pose.orientation.w = std::cos(0.5 * 1.2);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.submit(request, reason)) << reason;
|
||||||
|
|
||||||
|
const auto& goal = fixture.resolvedGoal();
|
||||||
|
EXPECT_NEAR(goal.pose.position.x, 9.0, 1e-9);
|
||||||
|
EXPECT_NEAR(goal.pose.position.y, 8.0, 1e-9);
|
||||||
|
EXPECT_NEAR(yawOf(goal), 1.2, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, AnAngleAppliesOnTopOfAGoalTakenFromAFrame)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(0.2); // [rad] hướng robot
|
||||||
|
fixture.pose().setFramePose("dock_target", 5.0, 6.0, 1.0); // [m], [rad] hướng của trạm
|
||||||
|
|
||||||
|
NavigationRequest request;
|
||||||
|
request.profile = MotionProfile::kRotate;
|
||||||
|
request.goal_frame = "dock_target";
|
||||||
|
request.relative_yaw = 0.1; // [rad]
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.submit(request, reason)) << reason;
|
||||||
|
|
||||||
|
const auto& goal = fixture.resolvedGoal();
|
||||||
|
EXPECT_NEAR(goal.pose.position.x, 5.0, 1e-9) << "[m] vị trí vẫn tới từ frame";
|
||||||
|
EXPECT_NEAR(goal.pose.position.y, 6.0, 1e-9);
|
||||||
|
// Góc quay nói về ROBOT, nên nền của nó là hướng robot (0.2), không phải hướng của trạm (1.0).
|
||||||
|
EXPECT_NEAR(yawOf(goal), 0.3, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, ARotationWithoutARobotPoseIsRefused)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setAvailable(false); // mất định vị
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
EXPECT_FALSE(fixture.submit(Fixture::rotationRequest(M_PI_2), reason))
|
||||||
|
<< "không có pose thì không có nền để cộng góc; đoán ở đây là quay mù";
|
||||||
|
EXPECT_FALSE(reason.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, AFrameAndADistanceTogetherAreStillRefused)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setFramePose("dock_target", 5.0, 6.0, 0.0);
|
||||||
|
|
||||||
|
NavigationRequest request;
|
||||||
|
request.profile = MotionProfile::kPosition;
|
||||||
|
request.goal_frame = "dock_target";
|
||||||
|
request.relative_distance = 1.0; // [m]
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
EXPECT_FALSE(fixture.submit(request, reason))
|
||||||
|
<< "hai nguồn VỊ TRÍ cùng lúc vẫn không có thứ tự nào hiển nhiên đúng; chỉ góc mới đi kèm được";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(DeferredGoal, ANonFiniteAngleIsTreatedAsNoAngle)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.pose().setYaw(0.4);
|
||||||
|
|
||||||
|
NavigationRequest request = Fixture::straightRequest(0.0);
|
||||||
|
request.relative_yaw = kNaN;
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.submit(request, reason)) << reason;
|
||||||
|
EXPECT_NEAR(yawOf(fixture.resolvedGoal()), 0.4, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char** argv)
|
||||||
|
{
|
||||||
|
testing::InitGoogleTest(&argc, argv);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
||||||
@@ -25,6 +25,7 @@
|
|||||||
|
|
||||||
#include <robot/time.h>
|
#include <robot/time.h>
|
||||||
|
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
#include <move_base2/ports/action_port.h>
|
#include <move_base2/ports/action_port.h>
|
||||||
#include <move_base2/ports/clock_port.h>
|
#include <move_base2/ports/clock_port.h>
|
||||||
#include <move_base2/ports/controller_port.h>
|
#include <move_base2/ports/controller_port.h>
|
||||||
@@ -132,12 +133,49 @@ public:
|
|||||||
pose_.pose.orientation.w = 1.0;
|
pose_.pose.orientation.w = 1.0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @param yaw [rad] hướng robot; cần cho mọi chặng quy từ pose tương đối.
|
||||||
|
void setYaw(double yaw)
|
||||||
|
{
|
||||||
|
pose_.header.frame_id = "map";
|
||||||
|
pose_.pose.orientation.x = 0.0;
|
||||||
|
pose_.pose.orientation.y = 0.0;
|
||||||
|
pose_.pose.orientation.z = std::sin(0.5 * yaw);
|
||||||
|
pose_.pose.orientation.w = std::cos(0.5 * yaw);
|
||||||
|
}
|
||||||
|
|
||||||
/// @brief false = mô phỏng TF thiếu/stale.
|
/// @brief false = mô phỏng TF thiếu/stale.
|
||||||
void setAvailable(bool available)
|
void setAvailable(bool available)
|
||||||
{
|
{
|
||||||
available_ = available;
|
available_ = available;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Đăng một frame mà @ref lookupPose tra được.
|
||||||
|
* @param x,y [m] ; @param yaw [rad] hướng của CHÍNH frame đó, không phải của robot.
|
||||||
|
*/
|
||||||
|
void setFramePose(const std::string& frame, double x, double y, double yaw)
|
||||||
|
{
|
||||||
|
robot_geometry_msgs::PoseStamped pose;
|
||||||
|
pose.header.frame_id = "map";
|
||||||
|
pose.pose.position.x = x;
|
||||||
|
pose.pose.position.y = y;
|
||||||
|
pose.pose.orientation.z = std::sin(0.5 * yaw);
|
||||||
|
pose.pose.orientation.w = std::cos(0.5 * yaw);
|
||||||
|
frames_[frame] = pose;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool lookupPose(const std::string& frame,
|
||||||
|
robot_geometry_msgs::PoseStamped& pose) const override
|
||||||
|
{
|
||||||
|
const auto it = frames_.find(frame);
|
||||||
|
if (it == frames_.end())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
pose = it->second;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
std::size_t callCount() const
|
std::size_t callCount() const
|
||||||
{
|
{
|
||||||
return call_count_;
|
return call_count_;
|
||||||
@@ -145,6 +183,7 @@ public:
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
robot_geometry_msgs::PoseStamped pose_;
|
robot_geometry_msgs::PoseStamped pose_;
|
||||||
|
std::map<std::string, robot_geometry_msgs::PoseStamped> frames_;
|
||||||
bool available_ = true;
|
bool available_ = true;
|
||||||
mutable std::size_t call_count_ = 0;
|
mutable std::size_t call_count_ = 0;
|
||||||
};
|
};
|
||||||
@@ -183,6 +222,7 @@ public:
|
|||||||
pending_goal_ = goal;
|
pending_goal_ = goal;
|
||||||
cycles_left_ = latency_cycles_;
|
cycles_left_ = latency_cycles_;
|
||||||
pending_action_ = nextAction();
|
pending_action_ = nextAction();
|
||||||
|
report(ComponentPhase::kBusy);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,6 +231,12 @@ public:
|
|||||||
return in_flight_;
|
return in_flight_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @brief Goal mà lõi đã trao cho lượt lập plan gần nhất — đích SAU khi đã quy từ dạng tương đối.
|
||||||
|
const robot_geometry_msgs::PoseStamped& pendingGoal() const
|
||||||
|
{
|
||||||
|
return pending_goal_;
|
||||||
|
}
|
||||||
|
|
||||||
bool pollPlan(PlanResult& result) override
|
bool pollPlan(PlanResult& result) override
|
||||||
{
|
{
|
||||||
if (!in_flight_)
|
if (!in_flight_)
|
||||||
@@ -204,6 +250,14 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
in_flight_ = false;
|
in_flight_ = false;
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
|
if (discarded_)
|
||||||
|
{
|
||||||
|
// Lượt đã bị huỷ giữa chừng nhưng plugin không cắt được (SBPL thật): kết quả về thì vứt lặng
|
||||||
|
// lẽ, đúng như PlannerRunner với discard_. Bên gọi chỉ thấy isPlanning() chuyển về false.
|
||||||
|
discarded_ = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
result.tag = pending_tag_;
|
result.tag = pending_tag_;
|
||||||
result.plan.clear();
|
result.plan.clear();
|
||||||
|
|
||||||
@@ -228,8 +282,23 @@ public:
|
|||||||
|
|
||||||
void cancelPlan() override
|
void cancelPlan() override
|
||||||
{
|
{
|
||||||
in_flight_ = false;
|
|
||||||
++cancel_count_;
|
++cancel_count_;
|
||||||
|
if (cancel_keeps_busy_ && in_flight_)
|
||||||
|
{
|
||||||
|
// Mô phỏng plugin KHÔNG preempt được: thread vẫn bận cho tới hết latency đã đặt, kết quả
|
||||||
|
// về bị vứt. Đây là hành vi của PlannerRunner + SBPL trước pha 2.
|
||||||
|
discarded_ = true;
|
||||||
|
report(ComponentPhase::kStopping);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
in_flight_ = false;
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Ghi hàng `kGlobalPlanner` như PlannerRunner thật. Null = không khai.
|
||||||
|
void attachStatusBoard(ComponentStatusBoard* board)
|
||||||
|
{
|
||||||
|
status_board_ = board;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string activePlanner() const override
|
std::string activePlanner() const override
|
||||||
@@ -237,6 +306,18 @@ public:
|
|||||||
return active_;
|
return active_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Sau cancelPlan(), lượt đang chạy vẫn chiếm thread cho tới hết latency (mặc định false:
|
||||||
|
* cancel cắt ngay, như plugin có preempt).
|
||||||
|
*
|
||||||
|
* Bật để tái hiện log 2026-09-11: cancel lúc SBPL đang chạy, goal kế bị `startPlan()` từ chối
|
||||||
|
* suốt mấy giây.
|
||||||
|
*/
|
||||||
|
void setCancelKeepsBusy(bool keeps_busy)
|
||||||
|
{
|
||||||
|
cancel_keeps_busy_ = keeps_busy;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Số cycle mà một lượt lập plan "mất" trước khi có kết quả.
|
* @brief Số cycle mà một lượt lập plan "mất" trước khi có kết quả.
|
||||||
*
|
*
|
||||||
@@ -312,6 +393,17 @@ private:
|
|||||||
std::size_t latency_cycles_ = 0;
|
std::size_t latency_cycles_ = 0;
|
||||||
std::size_t cycles_left_ = 0;
|
std::size_t cycles_left_ = 0;
|
||||||
std::size_t cancel_count_ = 0;
|
std::size_t cancel_count_ = 0;
|
||||||
|
bool cancel_keeps_busy_ = false;
|
||||||
|
bool discarded_ = false;
|
||||||
|
ComponentStatusBoard* status_board_ = nullptr;
|
||||||
|
|
||||||
|
void report(ComponentPhase phase)
|
||||||
|
{
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kGlobalPlanner, phase);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::size_t make_plan_count_ = 0;
|
std::size_t make_plan_count_ = 0;
|
||||||
std::size_t swap_count_ = 0;
|
std::size_t swap_count_ = 0;
|
||||||
@@ -394,6 +486,28 @@ public:
|
|||||||
void setMeasuredVelocity(const robot_geometry_msgs::Twist& velocity) override
|
void setMeasuredVelocity(const robot_geometry_msgs::Twist& velocity) override
|
||||||
{
|
{
|
||||||
measured_velocity_ = velocity;
|
measured_velocity_ = velocity;
|
||||||
|
has_measured_velocity_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cổng thật (ControllerRunner) trả false cho tới khi host đẩy odom vào; fake giữ đúng nghĩa đó
|
||||||
|
/// để mọi test không đẩy odom vẫn đi đường "đo bằng lệnh đã phát" như trước.
|
||||||
|
bool measuredVelocity(robot_geometry_msgs::Twist& out) const override
|
||||||
|
{
|
||||||
|
if (!has_measured_velocity_)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
out = measured_velocity_;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Giả lập odom: robot đang lăn với @p linear_x [m/s], @p angular_z [rad/s].
|
||||||
|
void setOdometry(double linear_x, double angular_z = 0.0)
|
||||||
|
{
|
||||||
|
robot_geometry_msgs::Twist twist;
|
||||||
|
twist.linear.x = linear_x;
|
||||||
|
twist.angular.z = angular_z;
|
||||||
|
setMeasuredVelocity(twist);
|
||||||
}
|
}
|
||||||
|
|
||||||
void getLocalPlan(robot_nav_2d_msgs::Path2D& plan) override
|
void getLocalPlan(robot_nav_2d_msgs::Path2D& plan) override
|
||||||
@@ -502,6 +616,7 @@ public:
|
|||||||
private:
|
private:
|
||||||
robot_nav_2d_msgs::Path2D local_plan_;
|
robot_nav_2d_msgs::Path2D local_plan_;
|
||||||
robot_geometry_msgs::Twist measured_velocity_;
|
robot_geometry_msgs::Twist measured_velocity_;
|
||||||
|
bool has_measured_velocity_ = false;
|
||||||
double limit_forward_ = 0.0; ///< [m/s]
|
double limit_forward_ = 0.0; ///< [m/s]
|
||||||
double limit_backward_ = 0.0; ///< [m/s], âm
|
double limit_backward_ = 0.0; ///< [m/s], âm
|
||||||
double limit_angular_ = 0.0; ///< [rad/s]
|
double limit_angular_ = 0.0; ///< [rad/s]
|
||||||
@@ -589,6 +704,7 @@ public:
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
active_ = true;
|
active_ = true;
|
||||||
|
report(ComponentPhase::kBusy);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -603,6 +719,10 @@ public:
|
|||||||
tick.status = RecoveryTick::Status::kRunning;
|
tick.status = RecoveryTick::Status::kRunning;
|
||||||
tick.has_velocity = emits_velocity_;
|
tick.has_velocity = emits_velocity_;
|
||||||
tick.cmd.linear.x = recovery_speed_;
|
tick.cmd.linear.x = recovery_speed_;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->progress(Component::kRecovery);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case RecoveryScript::kSucceeded:
|
case RecoveryScript::kSucceeded:
|
||||||
tick.status = RecoveryTick::Status::kSucceeded;
|
tick.status = RecoveryTick::Status::kSucceeded;
|
||||||
@@ -612,15 +732,44 @@ public:
|
|||||||
tick.path = success_path_;
|
tick.path = success_path_;
|
||||||
}
|
}
|
||||||
active_ = false;
|
active_ = false;
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
break;
|
break;
|
||||||
case RecoveryScript::kFailed:
|
case RecoveryScript::kFailed:
|
||||||
tick.status = RecoveryTick::Status::kFailed;
|
tick.status = RecoveryTick::Status::kFailed;
|
||||||
active_ = false;
|
active_ = false;
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
return tick;
|
return tick;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @brief Ghi hàng `kRecovery` như RecoveryRunner thật. Null = không khai.
|
||||||
|
void attachStatusBoard(ComponentStatusBoard* board)
|
||||||
|
{
|
||||||
|
status_board_ = board;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Sau cancel(), behavior vẫn "bận" thêm @p cycles tick — mô phỏng detour worker chưa thoát.
|
||||||
|
* Hàng kRecovery giữ kStopping; test gọi @ref settleCancel để nhả.
|
||||||
|
*/
|
||||||
|
void setCancelKeepsBusy(bool keeps_busy)
|
||||||
|
{
|
||||||
|
cancel_keeps_busy_ = keeps_busy;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Worker giả đã thoát: hàng về idle.
|
||||||
|
void settleCancel()
|
||||||
|
{
|
||||||
|
stopping_ = false;
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool stopping() const
|
||||||
|
{
|
||||||
|
return stopping_;
|
||||||
|
}
|
||||||
|
|
||||||
/// @brief Thành công thì kèm một detour path (như 'detour_path' thật) — cần cho stand-down của kContact.
|
/// @brief Thành công thì kèm một detour path (như 'detour_path' thật) — cần cho stand-down của kContact.
|
||||||
void setSucceedWithPath(std::vector<robot_geometry_msgs::PoseStamped> path)
|
void setSucceedWithPath(std::vector<robot_geometry_msgs::PoseStamped> path)
|
||||||
{
|
{
|
||||||
@@ -631,7 +780,17 @@ public:
|
|||||||
void cancel() override
|
void cancel() override
|
||||||
{
|
{
|
||||||
++cancel_count_;
|
++cancel_count_;
|
||||||
|
const bool was_active = active_;
|
||||||
active_ = false;
|
active_ = false;
|
||||||
|
if (was_active && cancel_keeps_busy_)
|
||||||
|
{
|
||||||
|
stopping_ = true;
|
||||||
|
report(ComponentPhase::kStopping);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string behaviorName(std::size_t index) const override
|
std::string behaviorName(std::size_t index) const override
|
||||||
@@ -728,6 +887,18 @@ private:
|
|||||||
std::size_t last_start_index_ = 0;
|
std::size_t last_start_index_ = 0;
|
||||||
RecoveryTrigger last_trigger_ = RecoveryTrigger::kPlanningFailed;
|
RecoveryTrigger last_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||||
std::vector<std::size_t> started_indices_;
|
std::vector<std::size_t> started_indices_;
|
||||||
|
|
||||||
|
bool cancel_keeps_busy_ = false;
|
||||||
|
bool stopping_ = false;
|
||||||
|
ComponentStatusBoard* status_board_ = nullptr;
|
||||||
|
|
||||||
|
void report(ComponentPhase phase)
|
||||||
|
{
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kRecovery, phase);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ------------------------------------------------------------------------------------------------
|
// ------------------------------------------------------------------------------------------------
|
||||||
@@ -749,6 +920,7 @@ public:
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
active_ = true;
|
active_ = true;
|
||||||
|
report(ComponentPhase::kBusy);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -757,19 +929,45 @@ public:
|
|||||||
++update_count_;
|
++update_count_;
|
||||||
|
|
||||||
ActionTick tick;
|
ActionTick tick;
|
||||||
|
if (stopping_)
|
||||||
|
{
|
||||||
|
if (cancel_ticks_left_ > 0)
|
||||||
|
{
|
||||||
|
--cancel_ticks_left_;
|
||||||
|
tick.status = ActionTick::Status::kRunning;
|
||||||
|
tick.message = "moving the device to a safe position";
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->progress(Component::kAction);
|
||||||
|
}
|
||||||
|
return tick;
|
||||||
|
}
|
||||||
|
stopping_ = false;
|
||||||
|
active_ = false;
|
||||||
|
tick.status = ActionTick::Status::kCancelled;
|
||||||
|
tick.message = "device safe";
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
|
return tick;
|
||||||
|
}
|
||||||
switch (nextAction())
|
switch (nextAction())
|
||||||
{
|
{
|
||||||
case ActionScript::kRunning:
|
case ActionScript::kRunning:
|
||||||
tick.status = ActionTick::Status::kRunning;
|
tick.status = ActionTick::Status::kRunning;
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->progress(Component::kAction);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case ActionScript::kSucceeded:
|
case ActionScript::kSucceeded:
|
||||||
tick.status = ActionTick::Status::kSucceeded;
|
tick.status = ActionTick::Status::kSucceeded;
|
||||||
active_ = false;
|
active_ = false;
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
break;
|
break;
|
||||||
case ActionScript::kFailed:
|
case ActionScript::kFailed:
|
||||||
tick.status = ActionTick::Status::kFailed;
|
tick.status = ActionTick::Status::kFailed;
|
||||||
tick.message = "fake action failed";
|
tick.message = "fake action failed";
|
||||||
active_ = false;
|
active_ = false;
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
return tick;
|
return tick;
|
||||||
@@ -778,7 +976,56 @@ public:
|
|||||||
void cancel() override
|
void cancel() override
|
||||||
{
|
{
|
||||||
++cancel_count_;
|
++cancel_count_;
|
||||||
|
if (active_ && cancel_ticks_needed_ > 0)
|
||||||
|
{
|
||||||
|
// Handler thiết bị (pha 3): giữ "đang dừng" thêm N tick rồi trả kCancelled.
|
||||||
|
cancel_ticks_left_ = cancel_ticks_needed_;
|
||||||
|
stopping_ = true;
|
||||||
|
report(ComponentPhase::kStopping);
|
||||||
|
return;
|
||||||
|
}
|
||||||
active_ = false;
|
active_ = false;
|
||||||
|
report(ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
|
||||||
|
void pause() override
|
||||||
|
{
|
||||||
|
++pause_count_;
|
||||||
|
if (active_)
|
||||||
|
{
|
||||||
|
report(ComponentPhase::kPaused);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void resume() override
|
||||||
|
{
|
||||||
|
++resume_count_;
|
||||||
|
if (active_)
|
||||||
|
{
|
||||||
|
report(ComponentPhase::kBusy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Sau cancel() handler cần @p ticks lượt update() nữa mới trả kCancelled (0 = dừng ngay).
|
||||||
|
void setCancelNeedsTicks(std::size_t ticks)
|
||||||
|
{
|
||||||
|
cancel_ticks_needed_ = ticks;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t pauseCount() const
|
||||||
|
{
|
||||||
|
return pause_count_;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t resumeCount() const
|
||||||
|
{
|
||||||
|
return resume_count_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Ghi hàng `kAction` như ActionRunner thật. Null = không khai.
|
||||||
|
void attachStatusBoard(ComponentStatusBoard* board)
|
||||||
|
{
|
||||||
|
status_board_ = board;
|
||||||
}
|
}
|
||||||
|
|
||||||
void setScript(std::vector<ActionScript> script)
|
void setScript(std::vector<ActionScript> script)
|
||||||
@@ -841,7 +1088,21 @@ private:
|
|||||||
std::size_t start_count_ = 0;
|
std::size_t start_count_ = 0;
|
||||||
std::size_t update_count_ = 0;
|
std::size_t update_count_ = 0;
|
||||||
std::size_t cancel_count_ = 0;
|
std::size_t cancel_count_ = 0;
|
||||||
|
std::size_t pause_count_ = 0;
|
||||||
|
std::size_t resume_count_ = 0;
|
||||||
|
std::size_t cancel_ticks_needed_ = 0;
|
||||||
|
std::size_t cancel_ticks_left_ = 0;
|
||||||
|
bool stopping_ = false;
|
||||||
std::vector<std::string> started_action_types_;
|
std::vector<std::string> started_action_types_;
|
||||||
|
ComponentStatusBoard* status_board_ = nullptr;
|
||||||
|
|
||||||
|
void report(ComponentPhase phase)
|
||||||
|
{
|
||||||
|
if (status_board_ != nullptr)
|
||||||
|
{
|
||||||
|
status_board_->enter(Component::kAction, phase);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ------------------------------------------------------------------------------------------------
|
// ------------------------------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
*********************************************************************/
|
*********************************************************************/
|
||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include <cmath>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
@@ -26,6 +27,7 @@ namespace
|
|||||||
using mission_adapters::Mission;
|
using mission_adapters::Mission;
|
||||||
using mission_adapters::MissionManager;
|
using mission_adapters::MissionManager;
|
||||||
using move_base2::MissionAdapterBridge;
|
using move_base2::MissionAdapterBridge;
|
||||||
|
using move_base2::MotionProfile;
|
||||||
using move_base2::NavigationOutcome;
|
using move_base2::NavigationOutcome;
|
||||||
using move_base2::NavigationRequest;
|
using move_base2::NavigationRequest;
|
||||||
|
|
||||||
@@ -161,6 +163,35 @@ TEST(MissionAdapterBridgeConversion, ActionOnlyLegCarriesNoOrder)
|
|||||||
EXPECT_EQ(request.order, nullptr);
|
EXPECT_EQ(request.order, nullptr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(MissionAdapterBridgeConversion, CarriesTheRelativeGoalAsItIs)
|
||||||
|
{
|
||||||
|
mission_adapters::Mission mission;
|
||||||
|
mission.id = 7;
|
||||||
|
mission.motion_hint = "rotate";
|
||||||
|
mission.relative_distance = 0.0; // [m]
|
||||||
|
mission.relative_yaw = M_PI / 2.0; // [rad], mission layer đã quy từ độ
|
||||||
|
|
||||||
|
const NavigationRequest request = MissionAdapterBridge::toRequest(mission);
|
||||||
|
|
||||||
|
EXPECT_EQ(request.profile, MotionProfile::kRotate);
|
||||||
|
EXPECT_DOUBLE_EQ(request.relative_distance, 0.0);
|
||||||
|
EXPECT_DOUBLE_EQ(request.relative_yaw, M_PI / 2.0)
|
||||||
|
<< "bridge chỉ chở qua; mọi phép quy đơn vị đã xong ở mission layer";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(MissionAdapterBridgeConversion, AnUnsetRelativeYawStaysUnset)
|
||||||
|
{
|
||||||
|
mission_adapters::Mission mission;
|
||||||
|
mission.id = 8;
|
||||||
|
mission.motion_hint = "go_straight";
|
||||||
|
mission.relative_distance = -1.0; // [m]
|
||||||
|
|
||||||
|
const NavigationRequest request = MissionAdapterBridge::toRequest(mission);
|
||||||
|
|
||||||
|
EXPECT_TRUE(std::isnan(request.relative_yaw))
|
||||||
|
<< "NaN = không dùng; đổi thành 0 sẽ ép chặng go_straight phải giữ nguyên hướng";
|
||||||
|
}
|
||||||
|
|
||||||
TEST(MissionAdapterBridgeConversion, LeavesToleranceAtProfileDefault)
|
TEST(MissionAdapterBridgeConversion, LeavesToleranceAtProfileDefault)
|
||||||
{
|
{
|
||||||
// Quy ước của NavigationRequest: sai số <= 0 nghĩa "dùng default của profile trong config".
|
// Quy ước của NavigationRequest: sai số <= 0 nghĩa "dùng default của profile trong config".
|
||||||
|
|||||||
@@ -270,6 +270,42 @@ TEST(MissionLayerTest, CancelStopsNavigationAndDropsTheQueue)
|
|||||||
EXPECT_EQ(1u, fixture.received_.size());
|
EXPECT_EQ(1u, fixture.received_.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(MissionLayerTest, EmergencyStopsNavigationWipesTheQueueAndBlocksSubmitUntilCleared)
|
||||||
|
{
|
||||||
|
// Đường 2026-09-14: NavigationServer::emergency() → drain → MissionLayer::emergency(). Layer đã có
|
||||||
|
// sẵn hàm này; test khoá ba tính chất host dựa vào: robot được bảo dừng, hàng đợi trống, và không
|
||||||
|
// order nào được nhận cho tới khi gỡ chốt.
|
||||||
|
Fixture fixture(3);
|
||||||
|
ASSERT_TRUE(fixture.layer_.submitGoal(makeGoal()));
|
||||||
|
ASSERT_TRUE(fixture.pumpUntilRequest());
|
||||||
|
|
||||||
|
fixture.layer_.emergency();
|
||||||
|
EXPECT_TRUE(fixture.waitForState(MissionState::EMERGENCY));
|
||||||
|
|
||||||
|
const auto deadline = std::chrono::steady_clock::now() + kTimeout;
|
||||||
|
while (fixture.cancel_calls_ == 0 && std::chrono::steady_clock::now() < deadline)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(kPollStep);
|
||||||
|
}
|
||||||
|
EXPECT_GE(fixture.cancel_calls_, 1) << "emergency must ask navigation to stop, not just forget the queue";
|
||||||
|
EXPECT_FALSE(fixture.layer_.hasMission()) << "the remaining legs are gone";
|
||||||
|
|
||||||
|
// Chốt: order mới bị manager gạt (trên thread sự kiện) — không có chặng nào xuống, state giữ nguyên.
|
||||||
|
ASSERT_TRUE(fixture.layer_.submitGoal(makeGoal())) << "submitGoal only means 'queued on the event bus'";
|
||||||
|
EXPECT_FALSE(fixture.pumpUntilRequest());
|
||||||
|
EXPECT_EQ(fixture.layer_.state(), MissionState::EMERGENCY);
|
||||||
|
EXPECT_EQ(1u, fixture.received_.size());
|
||||||
|
|
||||||
|
// Gỡ chốt: về CLEAR_EMERGENCY, KHÔNG tự chạy lại gì; order kế mới được nhận.
|
||||||
|
fixture.layer_.clearEmergency();
|
||||||
|
EXPECT_TRUE(fixture.waitForState(MissionState::CLEAR_EMERGENCY));
|
||||||
|
EXPECT_FALSE(fixture.pumpUntilRequest());
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.layer_.submitGoal(makeGoal()));
|
||||||
|
EXPECT_TRUE(fixture.pumpUntilRequest());
|
||||||
|
EXPECT_EQ(2u, fixture.received_.size());
|
||||||
|
}
|
||||||
|
|
||||||
TEST(MissionLayerTest, PausedLayerHoldsTheQueueUntilResume)
|
TEST(MissionLayerTest, PausedLayerHoldsTheQueueUntilResume)
|
||||||
{
|
{
|
||||||
Fixture fixture(2);
|
Fixture fixture(2);
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -147,6 +148,10 @@ public:
|
|||||||
deps_.recovery = &recovery_;
|
deps_.recovery = &recovery_;
|
||||||
deps_.mission = &mission_;
|
deps_.mission = &mission_;
|
||||||
deps_.action = &action_;
|
deps_.action = &action_;
|
||||||
|
deps_.components = &components_;
|
||||||
|
planner_.attachStatusBoard(&components_);
|
||||||
|
recovery_.attachStatusBoard(&components_);
|
||||||
|
action_.attachStatusBoard(&components_);
|
||||||
}
|
}
|
||||||
|
|
||||||
void configure(const ControlLoopConfig& config = baseConfig())
|
void configure(const ControlLoopConfig& config = baseConfig())
|
||||||
@@ -191,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_;
|
||||||
@@ -199,10 +203,15 @@ public:
|
|||||||
FakeRecoveryPort recovery_;
|
FakeRecoveryPort recovery_;
|
||||||
FakeMissionPort mission_;
|
FakeMissionPort mission_;
|
||||||
FakeActionPort action_;
|
FakeActionPort action_;
|
||||||
|
move_base2::ComponentStatusBoard components_;
|
||||||
ControlLoopDeps deps_;
|
ControlLoopDeps deps_;
|
||||||
|
|
||||||
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
|
||||||
@@ -606,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
|
||||||
@@ -842,7 +919,11 @@ TEST(NavigationServerLifecycle, PauseTakesEffectOnTheNextCycleNotImmediately)
|
|||||||
<< "pause() goes straight into the core from the host thread";
|
<< "pause() goes straight into the core from the host thread";
|
||||||
|
|
||||||
fixture.spin(1);
|
fixture.spin(1);
|
||||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPausing)
|
||||||
|
<< "pause is taken in one cycle: command zero, waiting for the runtime to settle";
|
||||||
|
fixture.spin(1);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused)
|
||||||
|
<< "nothing is busy in this fixture, so PAUSED follows one cycle later";
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST(NavigationServerLifecycle, ResumeAfterPauseReturnsToControlling)
|
TEST(NavigationServerLifecycle, ResumeAfterPauseReturnsToControlling)
|
||||||
@@ -856,7 +937,7 @@ TEST(NavigationServerLifecycle, ResumeAfterPauseReturnsToControlling)
|
|||||||
fixture.spin(2);
|
fixture.spin(2);
|
||||||
|
|
||||||
fixture.server_.pause();
|
fixture.server_.pause();
|
||||||
fixture.spin(1);
|
fixture.spin(2);
|
||||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||||
|
|
||||||
fixture.server_.resume();
|
fixture.server_.resume();
|
||||||
@@ -901,6 +982,7 @@ TEST(NavigationServerLifecycle, CancelWinsOverAPauseRequestedInTheSameCycle)
|
|||||||
fixture.spin(1);
|
fixture.spin(1);
|
||||||
|
|
||||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused) << "pause won over cancel";
|
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused) << "pause won over cancel";
|
||||||
|
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing) << "pause won over cancel";
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
|
TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
|
||||||
@@ -914,13 +996,219 @@ TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
|
|||||||
fixture.spin(2);
|
fixture.spin(2);
|
||||||
|
|
||||||
fixture.server_.pause();
|
fixture.server_.pause();
|
||||||
fixture.spin(1);
|
fixture.spin(2);
|
||||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||||
|
|
||||||
// Không có lệnh mới: cờ đã bị tiêu thụ, các cycle sau không được tự tạm dừng lại lần nữa.
|
// Không có lệnh mới: cờ đã bị tiêu thụ, các cycle sau không được tự tạm dừng lại lần nữa.
|
||||||
fixture.server_.resume();
|
fixture.server_.resume();
|
||||||
fixture.spin(3);
|
fixture.spin(3);
|
||||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused);
|
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||||
|
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================
|
||||||
|
// EMERGENCY (2026-09-14) — phản ứng trên thread host trước, control thread dọn sau
|
||||||
|
// ================================================================================================
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
/// @brief Đưa fixture tới CONTROLLING với lệnh khác 0 đang phát.
|
||||||
|
void driveToControllingWithSpeed(Fixture& fixture, double speed)
|
||||||
|
{
|
||||||
|
fixture.configure();
|
||||||
|
fixture.controller_.setNominalSpeed(speed);
|
||||||
|
fixture.controller_.setScript({ ControllerScript::kOk, ControllerScript::kOk, ControllerScript::kOk,
|
||||||
|
ControllerScript::kOk, ControllerScript::kOk });
|
||||||
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||||
|
<< fixture.server_.lastRejectReason();
|
||||||
|
fixture.spin(2);
|
||||||
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kControlling);
|
||||||
|
ASSERT_NEAR(fixture.server_.getTwist().velocity.x, speed, 1e-9);
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, ForcesZeroTwistAndEmergencyStateBeforeTheNextCycle)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
driveToControllingWithSpeed(fixture, 0.3);
|
||||||
|
const robot::Time before = fixture.server_.getTwist().header.stamp;
|
||||||
|
|
||||||
|
fixture.server_.emergency();
|
||||||
|
// KHÔNG spin: đây là điều khác biệt với pause/cancel — host phải thấy 0 ngay trong lời gọi kế.
|
||||||
|
const robot_nav_2d_msgs::Twist2DStamped twist = fixture.server_.getTwist();
|
||||||
|
EXPECT_NEAR(twist.velocity.x, 0.0, 1e-9) << "the last command must not leak past emergency()";
|
||||||
|
EXPECT_NEAR(twist.velocity.theta, 0.0, 1e-9);
|
||||||
|
EXPECT_GE(twist.header.stamp.toSec(), before.toSec()) << "the zero must be fresh so the host publishes it";
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::EMERGENCY);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kControlling)
|
||||||
|
<< "the core itself only learns about it on the next cycle";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, EntersTheCoreStateOnTheNextCycleAndReportsTheLegCancelled)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
driveToControllingWithSpeed(fixture, 0.3);
|
||||||
|
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.spin(1);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::EMERGENCY);
|
||||||
|
EXPECT_NEAR(fixture.server_.getTwist().velocity.x, 0.0, 1e-9);
|
||||||
|
ASSERT_EQ(fixture.server_.loop().outcomeReportCount(), 1u) << "the interrupted leg is reported exactly once";
|
||||||
|
EXPECT_STREQ(fixture.server_.loop().lastOutcome(), "CANCELLED");
|
||||||
|
|
||||||
|
fixture.spin(5);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency) << "it is a latch, not a state that expires";
|
||||||
|
EXPECT_EQ(fixture.server_.loop().outcomeReportCount(), 1u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, MoveToAndInstantActionsAreRejectedWhileLatched)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.configure();
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.spin(1);
|
||||||
|
|
||||||
|
EXPECT_FALSE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10));
|
||||||
|
EXPECT_NE(fixture.server_.lastRejectReason().find("emergency"), std::string::npos)
|
||||||
|
<< fixture.server_.lastRejectReason();
|
||||||
|
robot_protocol_msgs::Action action;
|
||||||
|
action.actionType = "PickUp";
|
||||||
|
action.actionId = "PickUp_1";
|
||||||
|
action.blockingType = "HARD";
|
||||||
|
EXPECT_FALSE(fixture.server_.executeInstantActions({ action }));
|
||||||
|
fixture.spin(3);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, DropsAGoalThatWasStillPending)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.configure();
|
||||||
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
||||||
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10));
|
||||||
|
|
||||||
|
// Goal đã vào ControlLoop (pending) nhưng chưa qua cycle nào — dừng khẩn tới trước.
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.spin(3);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().outcomeReportCount(), 0u) << "a leg that never started has no outcome";
|
||||||
|
|
||||||
|
// Gỡ chốt: goal cũ KHÔNG được tự chạy.
|
||||||
|
fixture.server_.clearEmergency();
|
||||||
|
fixture.spin(3);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kIdle);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, ClearReportsPendingAndAcceptsANewGoal)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
driveToControllingWithSpeed(fixture, 0.3);
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.spin(1);
|
||||||
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
|
||||||
|
fixture.server_.clearEmergency();
|
||||||
|
fixture.spin(1);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kIdle);
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PENDING)
|
||||||
|
<< "a clean slate, not a latched PREEMPTED: the host must send a new goal";
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||||
|
<< fixture.server_.lastRejectReason();
|
||||||
|
fixture.spin(2);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kControlling);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, WinsOverPauseAndCancelRequestedInTheSameDrain)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
driveToControllingWithSpeed(fixture, 0.3);
|
||||||
|
|
||||||
|
fixture.server_.pause();
|
||||||
|
fixture.server_.cancel();
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.spin(1);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
|
||||||
|
// Và ngược lại: dừng khẩn rồi mới pause/cancel cũng không đổi gì.
|
||||||
|
fixture.server_.pause();
|
||||||
|
fixture.server_.cancel();
|
||||||
|
fixture.server_.resume();
|
||||||
|
fixture.spin(2);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, ClearThenEmergencyInTheSameDrainStaysLatched)
|
||||||
|
{
|
||||||
|
// Hai cờ đối nghịch dưới một lock: lệnh gọi SAU thắng, như pause/resume.
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.configure();
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.spin(1);
|
||||||
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
|
||||||
|
fixture.server_.clearEmergency();
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.spin(2);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::EMERGENCY);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, TwistStampFreezesAfterTheGraceWindowWhileStillLatched)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
driveToControllingWithSpeed(fixture, 0.3);
|
||||||
|
|
||||||
|
fixture.server_.emergency();
|
||||||
|
const robot::Time fresh = fixture.server_.getTwist().header.stamp;
|
||||||
|
EXPECT_NEAR(fresh.toSec(), fixture.clock_.now().toSec(), 1e-9);
|
||||||
|
|
||||||
|
// Trong cửa ân hạn: stamp tiến theo đồng hồ (host publish 0 tường minh).
|
||||||
|
fixture.clock_.advance(0.2);
|
||||||
|
EXPECT_NEAR(fixture.server_.getTwist().header.stamp.toSec(), fixture.clock_.now().toSec(), 1e-9);
|
||||||
|
|
||||||
|
// Hết cửa: stamp đứng — host thấy lệnh quá hạn, nhường /cmd_vel; vận tốc vẫn 0.
|
||||||
|
fixture.clock_.advance(1.0);
|
||||||
|
const robot_nav_2d_msgs::Twist2DStamped late = fixture.server_.getTwist();
|
||||||
|
EXPECT_LT(late.header.stamp.toSec(), fixture.clock_.now().toSec() - 0.5);
|
||||||
|
EXPECT_NEAR(late.velocity.x, 0.0, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, OverridesTwistEvenWhenTheControlThreadNeverSpins)
|
||||||
|
{
|
||||||
|
// Mô phỏng control thread kẹt: không spin sau emergency(). Lệnh 0.3 m/s cuối cùng còn nằm
|
||||||
|
// trong twist_ của control loop — host không được thấy nó.
|
||||||
|
Fixture fixture;
|
||||||
|
driveToControllingWithSpeed(fixture, 0.3);
|
||||||
|
|
||||||
|
fixture.server_.emergency();
|
||||||
|
for (int i = 0; i < 5; ++i)
|
||||||
|
{
|
||||||
|
fixture.clock_.advance(0.01);
|
||||||
|
EXPECT_NEAR(fixture.server_.getTwist().velocity.x, 0.0, 1e-9) << "read " << i;
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::EMERGENCY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerEmergency, IsIdempotentAndClearWithoutLatchIsANoOp)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.configure();
|
||||||
|
|
||||||
|
fixture.server_.clearEmergency(); // chưa chốt gì — không được đổi state
|
||||||
|
fixture.spin(1);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kIdle);
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PENDING);
|
||||||
|
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.server_.emergency();
|
||||||
|
fixture.spin(2);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
|
||||||
|
fixture.server_.clearEmergency();
|
||||||
|
fixture.server_.clearEmergency();
|
||||||
|
fixture.spin(2);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kIdle);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================================================
|
// ================================================================================================
|
||||||
@@ -987,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
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit SignallingClock(std::promise<void>& started) : started_(started) {}
|
||||||
|
robot::Time now() const override
|
||||||
|
{
|
||||||
|
if (!signalled_.exchange(true))
|
||||||
|
started_.set_value();
|
||||||
|
return robot::Time(kClockStart);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::promise<void>& started_;
|
||||||
|
mutable std::atomic<bool> signalled_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
std::promise<void> started;
|
||||||
|
auto first_cycle = started.get_future();
|
||||||
|
SignallingClock clock(started);
|
||||||
|
{
|
||||||
Fixture fixture;
|
Fixture fixture;
|
||||||
|
fixture.deps_.clock = &clock;
|
||||||
fixture.configure();
|
fixture.configure();
|
||||||
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
|
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
|
||||||
SUCCEED(); // destructor của fixture phải join, không treo
|
ASSERT_EQ(first_cycle.wait_for(std::chrono::seconds(2)), std::future_status::ready);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================================================
|
// ================================================================================================
|
||||||
@@ -1149,6 +1458,169 @@ TEST(NavigationServerFeedback, NothingIsLatchedBeforeTheFirstRequest)
|
|||||||
<< "a freshly booted runtime reports a terminal result although no goal has ever been sent";
|
<< "a freshly booted runtime reports a terminal result although no goal has ever been sent";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ================================================================================================
|
||||||
|
// PREEMPTING phải nói thật (2026-09-11): host đọc PREEMPTED là "xong rồi, gửi goal kế được". Cancel
|
||||||
|
// lúc SBPL đang chạy mà báo PREEMPTED sau 33 ms thì host gửi goal kế vào một runtime còn bận —
|
||||||
|
// đúng chuỗi sự kiện trong log robot_app.log dẫn tới ABORTED oan.
|
||||||
|
// ================================================================================================
|
||||||
|
|
||||||
|
TEST(NavigationServerFeedback, PreemptingIsHeldUntilTheCancelledPlannerAttemptReallyEnds)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
ControlLoopConfig config = baseConfig();
|
||||||
|
config.state_machine.planner_patience = 5.0; // [s]
|
||||||
|
config.state_machine.settle_timeout = 2.0; // [s]
|
||||||
|
fixture.configure(config);
|
||||||
|
fixture.planner_.setLatencyCycles(10);
|
||||||
|
fixture.planner_.setCancelKeepsBusy(true); // SBPL trước pha 2: cancelPlan() không cắt được
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||||
|
<< fixture.server_.lastRejectReason();
|
||||||
|
fixture.spin(2);
|
||||||
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPlanning);
|
||||||
|
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||||
|
|
||||||
|
fixture.server_.cancel();
|
||||||
|
fixture.spin(1);
|
||||||
|
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||||
|
robot::move_base_core::State::PREEMPTING);
|
||||||
|
|
||||||
|
// Host poll 100 ms một lần = 2 cycle @ 20 Hz: mỗi lần poll trong lúc thread còn bận phải vẫn
|
||||||
|
// thấy PREEMPTING, không phải PREEMPTED.
|
||||||
|
std::size_t polls_while_busy = 0;
|
||||||
|
for (int i = 0; i < 20 && fixture.planner_.isPlanning(); ++i)
|
||||||
|
{
|
||||||
|
fixture.spin(2);
|
||||||
|
if (fixture.planner_.isPlanning())
|
||||||
|
{
|
||||||
|
++polls_while_busy;
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||||
|
robot::move_base_core::State::PREEMPTING)
|
||||||
|
<< "poll " << i << ": PREEMPTED reported while the planner thread is still busy";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EXPECT_GE(polls_while_busy, 2u);
|
||||||
|
|
||||||
|
fixture.spin(2);
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||||
|
robot::move_base_core::State::PREEMPTED)
|
||||||
|
<< "once the thread is idle the cancel must be reported (and latched) as PREEMPTED";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerFeedback, GoalSentWhilePreemptingIsAcceptedAndRunsOnceThePlannerIsFree)
|
||||||
|
{
|
||||||
|
// Host cũ không đợi PREEMPTED. Vẫn phải chạy đúng: goal kế xếp sau, không bị coi là hỏng.
|
||||||
|
Fixture fixture;
|
||||||
|
ControlLoopConfig config = baseConfig();
|
||||||
|
config.state_machine.planner_patience = 5.0; // [s]
|
||||||
|
config.state_machine.max_planning_retries = 0; // như máy chạy log
|
||||||
|
fixture.configure(config);
|
||||||
|
fixture.planner_.setLatencyCycles(10);
|
||||||
|
fixture.planner_.setCancelKeepsBusy(true);
|
||||||
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||||
|
<< fixture.server_.lastRejectReason();
|
||||||
|
fixture.spin(2);
|
||||||
|
fixture.server_.cancel();
|
||||||
|
fixture.spin(1);
|
||||||
|
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||||
|
robot::move_base_core::State::PREEMPTING);
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(5.0).goal, 0.15, 0.10))
|
||||||
|
<< fixture.server_.lastRejectReason();
|
||||||
|
|
||||||
|
bool saw_clearing_or_aborted = false;
|
||||||
|
bool reached_controlling = false;
|
||||||
|
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||||
|
{
|
||||||
|
fixture.spin(1);
|
||||||
|
const auto host = fixture.server_.getFeedback()->navigation_state;
|
||||||
|
saw_clearing_or_aborted = saw_clearing_or_aborted ||
|
||||||
|
host == robot::move_base_core::State::CLEARING ||
|
||||||
|
host == robot::move_base_core::State::ABORTED;
|
||||||
|
reached_controlling = host == robot::move_base_core::State::CONTROLLING;
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(saw_clearing_or_aborted) << "the second goal went through recovery/abort";
|
||||||
|
EXPECT_TRUE(reached_controlling);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerFeedback, PausedIsReportedOnlyOnceTheRuntimeIsQuiescent)
|
||||||
|
{
|
||||||
|
// PAUSING nói thật (2026-09-11): pause lúc SBPL còn chạy → host vẫn thấy PLANNING (+ feed_back_str
|
||||||
|
// "pausing…"), KHÔNG phải PAUSED; PAUSED chỉ khi thread planner đã nhả.
|
||||||
|
Fixture fixture;
|
||||||
|
ControlLoopConfig config = baseConfig();
|
||||||
|
config.state_machine.planner_patience = 5.0; // [s]
|
||||||
|
fixture.configure(config);
|
||||||
|
fixture.planner_.setLatencyCycles(10);
|
||||||
|
fixture.planner_.setCancelKeepsBusy(true);
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||||
|
<< fixture.server_.lastRejectReason();
|
||||||
|
fixture.spin(2);
|
||||||
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPlanning);
|
||||||
|
|
||||||
|
fixture.server_.pause();
|
||||||
|
fixture.spin(1);
|
||||||
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPausing);
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PLANNING)
|
||||||
|
<< "while pausing the host must keep seeing the state that is still winding down";
|
||||||
|
EXPECT_NE(fixture.server_.getFeedback()->feed_back_str.find("pausing"), std::string::npos);
|
||||||
|
|
||||||
|
std::size_t polls_while_busy = 0;
|
||||||
|
for (int i = 0; i < 20 && fixture.planner_.isPlanning(); ++i)
|
||||||
|
{
|
||||||
|
fixture.spin(2);
|
||||||
|
if (fixture.planner_.isPlanning())
|
||||||
|
{
|
||||||
|
++polls_while_busy;
|
||||||
|
EXPECT_NE(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PAUSED)
|
||||||
|
<< "poll " << i << ": PAUSED reported while the planner thread is still busy";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EXPECT_GE(polls_while_busy, 2u);
|
||||||
|
|
||||||
|
fixture.spin(2);
|
||||||
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PAUSED);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(NavigationServerFeedback, StalledControlThreadIsReportedAsLostByTheWatchdog)
|
||||||
|
{
|
||||||
|
// Pha 4 (2026-09-11): control thread treo thì refreshFeedback() không chạy nữa, host đọc mãi
|
||||||
|
// state cuối. Watchdog (thread riêng) phải ghi đè thành LOST trong getFeedback() — trên thread host.
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.configure();
|
||||||
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
||||||
|
|
||||||
|
move_base2::WatchdogConfig dog;
|
||||||
|
dog.period = 0.01; // [s]
|
||||||
|
dog.control_loop_stall_budget = 0.05; // [s]
|
||||||
|
std::string error;
|
||||||
|
ASSERT_TRUE(fixture.server_.startWatchdog(&fixture.components_, dog, error)) << error;
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||||
|
<< fixture.server_.lastRejectReason();
|
||||||
|
fixture.spin(3); // mỗi spinOnce() là một heartbeat của "control thread"
|
||||||
|
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||||
|
robot::move_base_core::State::CONTROLLING);
|
||||||
|
|
||||||
|
// Control thread "treo": không spinOnce nữa. Watchdog phải tự thấy sau ngân sách.
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(150));
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::LOST)
|
||||||
|
<< "a frozen CONTROLLING must not look like a running one";
|
||||||
|
EXPECT_NE(fixture.server_.getFeedback()->feed_back_str.find("control thread stalled"),
|
||||||
|
std::string::npos);
|
||||||
|
|
||||||
|
// Thread quay lại → hết LOST, state thật quay về.
|
||||||
|
fixture.spin(2);
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(30));
|
||||||
|
fixture.spin(1);
|
||||||
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||||
|
robot::move_base_core::State::CONTROLLING);
|
||||||
|
}
|
||||||
|
|
||||||
// ================================================================================================
|
// ================================================================================================
|
||||||
// executeInstantAction() — cửa duy nhất nhận một action lẻ
|
// executeInstantAction() — cửa duy nhất nhận một action lẻ
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -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ẽ
|
||||||
@@ -385,6 +427,181 @@ TEST(PlannerRunner, CancelledPlanProducesNoResult)
|
|||||||
"nobody asks for anymore";
|
"nobody asks for anymore";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(PlannerRunner, CancelPreemptsAPreemptablePlannerWithinMilliseconds)
|
||||||
|
{
|
||||||
|
// 2026-09-11: plugin implement robot_nav_core::Preemptable thì cancelPlan() cắt lượt đang chạy —
|
||||||
|
// thread rảnh trong vài ms thay vì 2 s. Đây là thứ làm CANCELLED/PAUSED nói thật mà không phải chờ.
|
||||||
|
Fixture fixture("TestPlannerSlowPreemptable");
|
||||||
|
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||||
|
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||||
|
|
||||||
|
const auto before = std::chrono::steady_clock::now();
|
||||||
|
fixture.runner_.cancelPlan();
|
||||||
|
int waited_ms = 0;
|
||||||
|
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
++waited_ms;
|
||||||
|
}
|
||||||
|
const double elapsed_ms =
|
||||||
|
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||||
|
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||||
|
EXPECT_LT(elapsed_ms, 200.0) << "preempt did not reach the planner; the thread ran to the end";
|
||||||
|
|
||||||
|
move_base2::PlanResult result;
|
||||||
|
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "a preempted attempt must not deliver a plan";
|
||||||
|
|
||||||
|
// Lượt kế phải khởi động được ngay và chạy bình thường (cờ preempt không dính sang lượt sau).
|
||||||
|
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
|
||||||
|
EXPECT_TRUE(fixture.runner_.isPlanning());
|
||||||
|
fixture.runner_.cancelPlan();
|
||||||
|
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(PlannerRunner, SwapWhileAPreemptablePlannerIsRunningCutsTheOldAttempt)
|
||||||
|
{
|
||||||
|
// Đổi profile (mission kế dùng planner khác) trong lúc lượt cũ chưa về: swapPlanner phải cắt
|
||||||
|
// instance ĐANG chạy, không chỉ đánh dấu vứt. Không cắt thì yêu cầu kế đứng ở kBusy tới hết
|
||||||
|
// allocated_time của lượt cũ (2 s ở đây, 10-30 s với SBPL thật).
|
||||||
|
Fixture fixture("TestPlannerSlowPreemptable");
|
||||||
|
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||||
|
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||||
|
|
||||||
|
const auto before = std::chrono::steady_clock::now();
|
||||||
|
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
|
||||||
|
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
}
|
||||||
|
const double elapsed_ms =
|
||||||
|
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||||
|
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||||
|
EXPECT_LT(elapsed_ms, 200.0) << "swapPlanner did not preempt the running instance";
|
||||||
|
|
||||||
|
move_base2::PlanResult result;
|
||||||
|
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "the old planner's attempt must be discarded";
|
||||||
|
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
|
||||||
|
|
||||||
|
// Planner mới chạy bình thường ngay sau đó.
|
||||||
|
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
|
||||||
|
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
}
|
||||||
|
ASSERT_TRUE(fixture.runner_.pollPlan(result));
|
||||||
|
EXPECT_TRUE(result.succeeded);
|
||||||
|
EXPECT_EQ(result.tag, 2U);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(PlannerRunner, CancelAfterSwapPreemptsTheInstanceThatIsActuallyRunning)
|
||||||
|
{
|
||||||
|
// Thứ tự thật trong log 2026-09-11 (mission 2 đổi profile TRƯỚC khi accept_request gọi
|
||||||
|
// cancelPlan): active_ đã trỏ sang planner mới, nhưng thread vẫn ở trong makePlan của planner cũ.
|
||||||
|
// cancelPlan phải cắt đúng instance đang chạy, không phải active_.
|
||||||
|
Fixture fixture("TestPlannerSlowPreemptable");
|
||||||
|
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||||
|
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||||
|
|
||||||
|
// Đổi sang planner "ngoan" (stubborn — không Preemptable) để chứng minh cancel không nhìn active_:
|
||||||
|
// nếu cancel dynamic_cast trên active_ thì ra null và lượt Preemptable đang chạy KHÔNG bị cắt.
|
||||||
|
// Lưu ý: swapPlanner nay cũng preempt; để tách bạch, test này chỉ khẳng định tổng thể thread rảnh
|
||||||
|
// trong vài ms sau cặp swap+cancel, đúng như ControlLoop làm khi nhận goal mới.
|
||||||
|
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowStubborn"));
|
||||||
|
fixture.runner_.cancelPlan();
|
||||||
|
int waited_ms = 0;
|
||||||
|
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
++waited_ms;
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||||
|
EXPECT_LT(waited_ms, 200) << "the running Preemptable instance was not the one preempted";
|
||||||
|
|
||||||
|
move_base2::PlanResult result;
|
||||||
|
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(PlannerRunner, SwapWhileTheJobIsQueuedButNotStartedDropsIt)
|
||||||
|
{
|
||||||
|
// Yêu cầu vừa được đặt, thread chưa kịp nhận: đổi planner phải rút yêu cầu đó ra, không để thread
|
||||||
|
// chạy yêu cầu của planner cũ trên instance mới rồi vứt.
|
||||||
|
Fixture fixture("TestPlannerSlowPreemptable");
|
||||||
|
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||||
|
|
||||||
|
bool dropped_before_start = false;
|
||||||
|
for (int attempt = 0; attempt < 50 && !dropped_before_start; ++attempt)
|
||||||
|
{
|
||||||
|
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||||
|
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
|
||||||
|
// Cả hai nhánh (rút trước khi thread nhận / cắt sau khi nó nhận) đều phải rảnh trong vài ms.
|
||||||
|
int waited_ms = 0;
|
||||||
|
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
++waited_ms;
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||||
|
EXPECT_LT(waited_ms, 200);
|
||||||
|
move_base2::PlanResult result;
|
||||||
|
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||||
|
dropped_before_start = (waited_ms == 0);
|
||||||
|
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowPreemptable"));
|
||||||
|
}
|
||||||
|
// Không ép nhánh "rút trước khi nhận" phải xảy ra (phụ thuộc scheduler), chỉ cần cả hai nhánh
|
||||||
|
// đều đúng.
|
||||||
|
SUCCEED();
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(PlannerRunner, DestructorPreemptsARunningPreemptablePlanner)
|
||||||
|
{
|
||||||
|
// Shutdown giữa một lượt search dài: destructor phải cắt lượt đó thay vì chờ hết allocated_time.
|
||||||
|
const auto before = std::chrono::steady_clock::now();
|
||||||
|
{
|
||||||
|
Fixture fixture("TestPlannerSlowPreemptable");
|
||||||
|
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||||
|
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||||
|
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||||
|
}
|
||||||
|
const double elapsed_ms =
|
||||||
|
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||||
|
EXPECT_LT(elapsed_ms, 500.0) << "destructor waited for the whole 2 s search";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(PlannerRunner, CancelOnAStubbornPlannerFallsBackToDiscardingTheResult)
|
||||||
|
{
|
||||||
|
// Plugin cũ (không Preemptable): hành vi trước 2026-09-11 giữ nguyên — thread bận tới hết lượt,
|
||||||
|
// kết quả về bị vứt. isPlanning() phải nói thật suốt quãng đó.
|
||||||
|
Fixture fixture("TestPlannerSlowStubborn");
|
||||||
|
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||||
|
fixture.runner_.cancelPlan();
|
||||||
|
EXPECT_TRUE(fixture.runner_.isPlanning()) << "a stubborn planner cannot be cut short";
|
||||||
|
|
||||||
|
for (int i = 0; i < 2000 && fixture.runner_.isPlanning(); ++i)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||||
|
move_base2::PlanResult result;
|
||||||
|
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||||
|
}
|
||||||
|
|
||||||
TEST(PlannerRunner, ResultCarriesBackTheTagItWasStartedWith)
|
TEST(PlannerRunner, ResultCarriesBackTheTagItWasStartedWith)
|
||||||
{
|
{
|
||||||
Fixture fixture;
|
Fixture fixture;
|
||||||
@@ -557,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;
|
||||||
|
|||||||
@@ -12,12 +12,20 @@
|
|||||||
* 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
|
||||||
*********************************************************************/
|
*********************************************************************/
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
#include <thread>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
@@ -29,6 +37,12 @@
|
|||||||
|
|
||||||
#include <robot/node_handle.h>
|
#include <robot/node_handle.h>
|
||||||
#include <robot_nav_core/base_global_planner.h>
|
#include <robot_nav_core/base_global_planner.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
|
||||||
{
|
{
|
||||||
@@ -129,6 +143,85 @@ private:
|
|||||||
bool saw_order_ = false;
|
bool saw_order_ = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class TestSlowPlanner
|
||||||
|
* @brief Planner giả "search dài": ngủ từng lát 5 ms trong @p seconds. Bản Preemptable thoát khi
|
||||||
|
* thấy cờ (mô hình ARA* + abort flag); bản "stubborn" không nhìn cờ (mô hình plugin cũ).
|
||||||
|
*/
|
||||||
|
class TestSlowPlannerBase : public robot_nav_core::BaseGlobalPlanner
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit TestSlowPlannerBase(double seconds, bool honours_preempt)
|
||||||
|
: seconds_(seconds), honours_preempt_(honours_preempt)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
bool initialize(std::string /*name*/, robot_costmap_2d::Costmap2DROBOT* /*costmap_robot*/) override
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool makePlan(const robot_geometry_msgs::PoseStamped& start,
|
||||||
|
const robot_geometry_msgs::PoseStamped& goal,
|
||||||
|
std::vector<robot_geometry_msgs::PoseStamped>& plan) override
|
||||||
|
{
|
||||||
|
preempt_.store(false, std::memory_order_relaxed);
|
||||||
|
const auto deadline = std::chrono::steady_clock::now() +
|
||||||
|
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
||||||
|
std::chrono::duration<double>(seconds_));
|
||||||
|
while (std::chrono::steady_clock::now() < deadline)
|
||||||
|
{
|
||||||
|
if (honours_preempt_ && preempt_.load(std::memory_order_relaxed))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||||
|
}
|
||||||
|
plan.clear();
|
||||||
|
plan.push_back(start);
|
||||||
|
plan.push_back(goal);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
std::atomic<bool> preempt_{false};
|
||||||
|
|
||||||
|
private:
|
||||||
|
double seconds_;
|
||||||
|
bool honours_preempt_;
|
||||||
|
};
|
||||||
|
|
||||||
|
class TestSlowPreemptablePlanner final : public TestSlowPlannerBase,
|
||||||
|
public robot_nav_core::Preemptable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
TestSlowPreemptablePlanner() : TestSlowPlannerBase(2.0, true)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
void preempt() override
|
||||||
|
{
|
||||||
|
preempt_.store(true, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
class TestSlowStubbornPlanner final : public TestSlowPlannerBase
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
TestSlowStubbornPlanner() : TestSlowPlannerBase(0.4, false)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
robot_nav_core::BaseGlobalPlanner::Ptr createSlowPreemptable()
|
||||||
|
{
|
||||||
|
return std::make_shared<TestSlowPreemptablePlanner>();
|
||||||
|
}
|
||||||
|
|
||||||
|
robot_nav_core::BaseGlobalPlanner::Ptr createSlowStubborn()
|
||||||
|
{
|
||||||
|
return std::make_shared<TestSlowStubbornPlanner>();
|
||||||
|
}
|
||||||
|
|
||||||
robot_nav_core::BaseGlobalPlanner::Ptr createOk()
|
robot_nav_core::BaseGlobalPlanner::Ptr createOk()
|
||||||
{
|
{
|
||||||
return std::make_shared<TestGlobalPlanner>(TestGlobalPlanner::Behavior::kOk);
|
return std::make_shared<TestGlobalPlanner>(TestGlobalPlanner::Behavior::kOk);
|
||||||
@@ -161,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
|
||||||
|
|
||||||
@@ -168,5 +281,11 @@ BOOST_DLL_ALIAS(move_base2::testing::createOk, TestPlannerOk)
|
|||||||
BOOST_DLL_ALIAS(move_base2::testing::createEmptyPlan, TestPlannerEmptyPlan)
|
BOOST_DLL_ALIAS(move_base2::testing::createEmptyPlan, TestPlannerEmptyPlan)
|
||||||
BOOST_DLL_ALIAS(move_base2::testing::createThrowing, TestPlannerThrowing)
|
BOOST_DLL_ALIAS(move_base2::testing::createThrowing, TestPlannerThrowing)
|
||||||
BOOST_DLL_ALIAS(move_base2::testing::createInitFailing, TestPlannerInitFails)
|
BOOST_DLL_ALIAS(move_base2::testing::createInitFailing, TestPlannerInitFails)
|
||||||
|
BOOST_DLL_ALIAS(move_base2::testing::createSlowPreemptable, TestPlannerSlowPreemptable)
|
||||||
|
BOOST_DLL_ALIAS(move_base2::testing::createSlowStubborn, TestPlannerSlowStubborn)
|
||||||
BOOST_DLL_ALIAS(move_base2::testing::initializeCount, TestPlannerInitializeCount)
|
BOOST_DLL_ALIAS(move_base2::testing::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)
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -240,6 +240,39 @@ TEST(StateMachineConfig, RejectsResolvedRouteWithAnOutOfRangeBehavior)
|
|||||||
EXPECT_NE(error.find("loaded behavior"), std::string::npos);
|
EXPECT_NE(error.find("loaded behavior"), std::string::npos);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineConfig, RejectsNegativeCancelSettleTimeout)
|
||||||
|
{
|
||||||
|
StateMachineConfig config = baseConfig();
|
||||||
|
config.settle_timeout = -1.0;
|
||||||
|
std::string error;
|
||||||
|
EXPECT_FALSE(config.validate(error));
|
||||||
|
EXPECT_NE(error.find("settle_timeout"), std::string::npos);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineConfig, RejectsNegativeStoppedMeasuredEps)
|
||||||
|
{
|
||||||
|
StateMachineConfig linear = baseConfig();
|
||||||
|
linear.stopped_measured_linear_eps = -0.01;
|
||||||
|
std::string error;
|
||||||
|
EXPECT_FALSE(linear.validate(error));
|
||||||
|
EXPECT_NE(error.find("stopped_measured_linear_eps"), std::string::npos);
|
||||||
|
|
||||||
|
StateMachineConfig angular = baseConfig();
|
||||||
|
angular.stopped_measured_angular_eps = -0.01;
|
||||||
|
EXPECT_FALSE(angular.validate(error));
|
||||||
|
EXPECT_NE(error.find("stopped_measured_angular_eps"), std::string::npos);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineConfig, ZeroCancelSettleTimeoutAndZeroEpsAreValidOffSwitches)
|
||||||
|
{
|
||||||
|
StateMachineConfig config = baseConfig();
|
||||||
|
config.settle_timeout = 0.0;
|
||||||
|
config.stopped_measured_linear_eps = 0.0;
|
||||||
|
config.stopped_measured_angular_eps = 0.0;
|
||||||
|
std::string error;
|
||||||
|
EXPECT_TRUE(config.validate(error)) << error;
|
||||||
|
}
|
||||||
|
|
||||||
TEST(StateMachineConfig, DescribeMentionsEveryParameter)
|
TEST(StateMachineConfig, DescribeMentionsEveryParameter)
|
||||||
{
|
{
|
||||||
const std::string text = baseConfig().describe();
|
const std::string text = baseConfig().describe();
|
||||||
@@ -249,6 +282,8 @@ TEST(StateMachineConfig, DescribeMentionsEveryParameter)
|
|||||||
EXPECT_NE(text.find("action_patience"), std::string::npos);
|
EXPECT_NE(text.find("action_patience"), std::string::npos);
|
||||||
EXPECT_NE(text.find("max_planning_retries"), std::string::npos);
|
EXPECT_NE(text.find("max_planning_retries"), std::string::npos);
|
||||||
EXPECT_NE(text.find("recovery_reset_min_travel"), std::string::npos);
|
EXPECT_NE(text.find("recovery_reset_min_travel"), std::string::npos);
|
||||||
|
EXPECT_NE(text.find("settle_timeout"), std::string::npos);
|
||||||
|
EXPECT_NE(text.find("stopped_measured_eps"), std::string::npos);
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST(StateMachine, RefusesToRunBeforeConfigure)
|
TEST(StateMachine, RefusesToRunBeforeConfigure)
|
||||||
@@ -358,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();
|
||||||
@@ -444,7 +504,7 @@ TEST(StateMachinePlanning, PauseMovesToPausedAndResumeComesBack)
|
|||||||
|
|
||||||
StateMachineInput pause;
|
StateMachineInput pause;
|
||||||
pause.pause_requested = true;
|
pause.pause_requested = true;
|
||||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
StateMachineInput resume;
|
StateMachineInput resume;
|
||||||
resume.resume_requested = true;
|
resume.resume_requested = true;
|
||||||
@@ -903,7 +963,7 @@ TEST(StateMachineControlling, PauseThenResumeReturnsToControlling)
|
|||||||
|
|
||||||
StateMachineInput pause;
|
StateMachineInput pause;
|
||||||
pause.pause_requested = true;
|
pause.pause_requested = true;
|
||||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
StateMachineInput resume;
|
StateMachineInput resume;
|
||||||
resume.resume_requested = true;
|
resume.resume_requested = true;
|
||||||
@@ -921,7 +981,7 @@ TEST(StateMachineControlling, LongPauseDoesNotBlowControllerPatience)
|
|||||||
|
|
||||||
StateMachineInput pause;
|
StateMachineInput pause;
|
||||||
pause.pause_requested = true;
|
pause.pause_requested = true;
|
||||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
driver.advance(60.0);
|
driver.advance(60.0);
|
||||||
|
|
||||||
@@ -1108,7 +1168,7 @@ TEST(StateMachineRecovering, PauseMidRecoveryCancelsBehaviorAndResumesToPlanning
|
|||||||
pause.pause_requested = true;
|
pause.pause_requested = true;
|
||||||
const StateMachineOutput paused = driver.tick(pause);
|
const StateMachineOutput paused = driver.tick(pause);
|
||||||
|
|
||||||
EXPECT_EQ(paused.state, NavigationState::kPaused);
|
EXPECT_EQ(paused.state, NavigationState::kPausing);
|
||||||
EXPECT_TRUE(paused.cancel_recovery)
|
EXPECT_TRUE(paused.cancel_recovery)
|
||||||
<< "keeping a behavior half-finished across a long pause is unsafe";
|
<< "keeping a behavior half-finished across a long pause is unsafe";
|
||||||
|
|
||||||
@@ -1147,7 +1207,7 @@ TEST(StateMachinePaused, CancelFromPausedGoesToCancelling)
|
|||||||
|
|
||||||
StateMachineInput pause;
|
StateMachineInput pause;
|
||||||
pause.pause_requested = true;
|
pause.pause_requested = true;
|
||||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
StateMachineInput cancel;
|
StateMachineInput cancel;
|
||||||
cancel.cancel_requested = true;
|
cancel.cancel_requested = true;
|
||||||
@@ -1161,7 +1221,9 @@ TEST(StateMachinePaused, StaysPausedIndefinitelyWithoutResume)
|
|||||||
|
|
||||||
StateMachineInput pause;
|
StateMachineInput pause;
|
||||||
pause.pause_requested = true;
|
pause.pause_requested = true;
|
||||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
// Cycle kế: mọi thành phần im (input mặc định) → PAUSED thật.
|
||||||
|
ASSERT_EQ(driver.idleTick().state, NavigationState::kPaused);
|
||||||
|
|
||||||
for (int i = 0; i < 50; ++i)
|
for (int i = 0; i < 50; ++i)
|
||||||
{
|
{
|
||||||
@@ -1194,6 +1256,430 @@ TEST(StateMachineCancelling, WaitsForRobotToStopBeforeCancelled)
|
|||||||
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ================================================================================================
|
||||||
|
// kCancelling chờ QUIESCENT (2026-09-11): lệnh về 0 là điều kiện cần, chưa đủ. Host đọc
|
||||||
|
// CANCELLED/PREEMPTED là "xong rồi, gửi goal kế được" — báo trong lúc thread planner còn chạy lượt
|
||||||
|
// cũ thì goal kế bị startPlan() từ chối và bị coi là hỏng (log 2026-09-11: ABORTED sau 3 s).
|
||||||
|
// ================================================================================================
|
||||||
|
|
||||||
|
TEST(StateMachineCancelling, HoldsWhilePlannerThreadIsStillBusy)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
|
||||||
|
StateMachineInput request;
|
||||||
|
request.has_pending_request = true;
|
||||||
|
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||||
|
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
cancel.planner_busy = true; // SBPL đang chạy, cancelPlan() không cắt được
|
||||||
|
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput still_busy;
|
||||||
|
still_busy.robot_stopped = true;
|
||||||
|
still_busy.planner_busy = true;
|
||||||
|
for (int i = 0; i < 10; ++i)
|
||||||
|
{
|
||||||
|
driver.advance(0.05);
|
||||||
|
const StateMachineOutput out = driver.tick(still_busy);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kCancelling) << "left CANCELLING at cycle " << i;
|
||||||
|
EXPECT_FALSE(out.report_outcome);
|
||||||
|
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||||
|
EXPECT_FALSE(out.start_planner);
|
||||||
|
}
|
||||||
|
|
||||||
|
StateMachineInput idle;
|
||||||
|
idle.robot_stopped = true;
|
||||||
|
idle.planner_busy = false;
|
||||||
|
driver.advance(0.05);
|
||||||
|
const StateMachineOutput out = driver.tick(idle);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||||
|
EXPECT_TRUE(out.report_outcome);
|
||||||
|
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||||
|
EXPECT_FALSE(out.settle_timed_out);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineCancelling, GivesUpAfterSettleTimeoutAndFlagsIt)
|
||||||
|
{
|
||||||
|
StateMachineConfig config = baseConfig();
|
||||||
|
config.settle_timeout = 0.5; // [s]
|
||||||
|
Driver driver(config);
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput busy;
|
||||||
|
busy.robot_stopped = true;
|
||||||
|
busy.planner_busy = true;
|
||||||
|
|
||||||
|
// 0.45 s: chưa quá trần.
|
||||||
|
driver.advance(0.45);
|
||||||
|
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||||
|
EXPECT_FALSE(driver.last().settle_timed_out);
|
||||||
|
|
||||||
|
// 0.55 s: quá trần → CANCELLED nhưng cờ lỗi bật đúng cycle báo kết quả.
|
||||||
|
driver.advance(0.10);
|
||||||
|
const StateMachineOutput out = driver.tick(busy);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||||
|
EXPECT_TRUE(out.report_outcome);
|
||||||
|
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||||
|
EXPECT_TRUE(out.settle_timed_out);
|
||||||
|
|
||||||
|
// Cờ chỉ sống một cycle: cycle kế về kIdle không mang nó theo.
|
||||||
|
EXPECT_FALSE(driver.idleTick().settle_timed_out);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineCancelling, HoldsWhileOdometrySaysTheRobotIsStillMoving)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
// Lệnh đã về 0 (bên gọi tính vào robot_stopped) nhưng odom vẫn đọc 0.3 m/s → chưa xong.
|
||||||
|
StateMachineInput rolling;
|
||||||
|
rolling.robot_stopped = false;
|
||||||
|
rolling.planner_busy = false;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(rolling).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput stopped;
|
||||||
|
stopped.robot_stopped = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(stopped).state, NavigationState::kCancelled);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineCancelling, KeepsTickingTheActionUntilItReportsTerminal)
|
||||||
|
{
|
||||||
|
// Handler thiết bị cần vài tick sau cancel() để đưa thiết bị về vị trí an toàn. Trong lúc đó
|
||||||
|
// state machine tick tiếp nhưng KHÔNG cấp vận tốc — bất biến 3 giữ nguyên.
|
||||||
|
Driver driver;
|
||||||
|
|
||||||
|
StateMachineInput request;
|
||||||
|
request.has_pending_request = true;
|
||||||
|
request.pending_request_has_goal = false;
|
||||||
|
request.pending_request_action_count = 1;
|
||||||
|
ASSERT_EQ(driver.tick(request).state, NavigationState::kExecutingActions);
|
||||||
|
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
cancel.action_terminal = false;
|
||||||
|
const StateMachineOutput entering = driver.tick(cancel);
|
||||||
|
ASSERT_EQ(entering.state, NavigationState::kCancelling);
|
||||||
|
EXPECT_TRUE(entering.cancel_action);
|
||||||
|
|
||||||
|
StateMachineInput settling;
|
||||||
|
settling.robot_stopped = true;
|
||||||
|
settling.planner_busy = false;
|
||||||
|
settling.action_terminal = false;
|
||||||
|
for (int i = 0; i < 3; ++i)
|
||||||
|
{
|
||||||
|
driver.advance(0.05);
|
||||||
|
const StateMachineOutput out = driver.tick(settling);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kCancelling);
|
||||||
|
EXPECT_TRUE(out.tick_action) << "cycle " << i;
|
||||||
|
EXPECT_FALSE(out.run_controller);
|
||||||
|
EXPECT_FALSE(out.tick_recovery);
|
||||||
|
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||||
|
}
|
||||||
|
|
||||||
|
StateMachineInput terminal = settling;
|
||||||
|
terminal.action_terminal = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
const StateMachineOutput out = driver.tick(terminal);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||||
|
EXPECT_FALSE(out.tick_action);
|
||||||
|
EXPECT_TRUE(out.report_outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineCancelling, ZeroSettleTimeoutKeepsTheLegacyBehaviour)
|
||||||
|
{
|
||||||
|
// Tắt = hành vi trước 2026-09-11: chỉ chờ lệnh về 0, mặc kệ planner còn bận.
|
||||||
|
StateMachineConfig config = baseConfig();
|
||||||
|
config.settle_timeout = 0.0;
|
||||||
|
Driver driver(config);
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput stopped_but_busy;
|
||||||
|
stopped_but_busy.robot_stopped = true;
|
||||||
|
stopped_but_busy.planner_busy = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
const StateMachineOutput out = driver.tick(stopped_but_busy);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||||
|
EXPECT_FALSE(out.settle_timed_out);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineCancelling, CancelFromPausedAlsoWaitsForThePlannerThread)
|
||||||
|
{
|
||||||
|
// Pause lúc PLANNING đã cancelPlan() nhưng thread có thể còn bận; cancel từ PAUSED phải chờ nốt.
|
||||||
|
Driver driver;
|
||||||
|
|
||||||
|
StateMachineInput request;
|
||||||
|
request.has_pending_request = true;
|
||||||
|
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
cancel.planner_busy = true;
|
||||||
|
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput busy;
|
||||||
|
busy.robot_stopped = true;
|
||||||
|
busy.planner_busy = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput idle = busy;
|
||||||
|
idle.planner_busy = false;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachinePaused, ResumeFromControllingReappliesThePlanToTheController)
|
||||||
|
{
|
||||||
|
// Local planner giữ warm-start/slew theo thời gian; sau một quãng đứng yên phải nạp lại plan để
|
||||||
|
// plugin reset theo pose hiện tại. Resume từ CONTROLLING vì vậy mang apply_plan (2026-09-11).
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
driver.advance(30.0);
|
||||||
|
|
||||||
|
StateMachineInput resume;
|
||||||
|
resume.resume_requested = true;
|
||||||
|
const StateMachineOutput out = driver.tick(resume);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||||
|
EXPECT_TRUE(out.apply_plan);
|
||||||
|
EXPECT_TRUE(out.run_controller);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachinePaused, ResumeFromPlanningDoesNotReapplyAnyPlan)
|
||||||
|
{
|
||||||
|
// Chưa từng có plan nào → không có gì để nạp lại; resume chỉ khởi động lại planner.
|
||||||
|
Driver driver;
|
||||||
|
|
||||||
|
StateMachineInput request;
|
||||||
|
request.has_pending_request = true;
|
||||||
|
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput resume;
|
||||||
|
resume.resume_requested = true;
|
||||||
|
const StateMachineOutput out = driver.tick(resume);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kPlanning);
|
||||||
|
EXPECT_FALSE(out.apply_plan);
|
||||||
|
EXPECT_TRUE(out.start_planner);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================
|
||||||
|
// kPausing (2026-09-11): pause nhận xong là lệnh 0 ngay, nhưng PAUSED chỉ khi mọi thành phần im —
|
||||||
|
// cùng ba điều kiện quiescent với kCancelling. Host đọc PAUSED là "dừng rồi, làm gì cũng được".
|
||||||
|
// ================================================================================================
|
||||||
|
|
||||||
|
TEST(StateMachinePausing, HoldsWhilePlannerThreadIsStillBusyThenSettles)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
|
||||||
|
StateMachineInput request;
|
||||||
|
request.has_pending_request = true;
|
||||||
|
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
pause.planner_busy = true;
|
||||||
|
const StateMachineOutput entering = driver.tick(pause);
|
||||||
|
ASSERT_EQ(entering.state, NavigationState::kPausing);
|
||||||
|
EXPECT_TRUE(entering.stop_planner);
|
||||||
|
EXPECT_EQ(entering.velocity_source, VelocitySource::kNone);
|
||||||
|
|
||||||
|
StateMachineInput busy;
|
||||||
|
busy.robot_stopped = true;
|
||||||
|
busy.planner_busy = true;
|
||||||
|
for (int i = 0; i < 10; ++i)
|
||||||
|
{
|
||||||
|
driver.advance(0.05);
|
||||||
|
const StateMachineOutput out = driver.tick(busy);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kPausing) << "cycle " << i;
|
||||||
|
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||||
|
EXPECT_FALSE(out.start_planner);
|
||||||
|
EXPECT_FALSE(out.settle_timed_out);
|
||||||
|
}
|
||||||
|
|
||||||
|
StateMachineInput idle;
|
||||||
|
idle.robot_stopped = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
const StateMachineOutput out = driver.tick(idle);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kPaused);
|
||||||
|
EXPECT_FALSE(out.settle_timed_out);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachinePausing, HoldsWhileRecoveryIsStillStopping)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput recovering;
|
||||||
|
recovering.robot_stopped = true;
|
||||||
|
recovering.recovery_busy = true; // detour worker chưa thoát
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(recovering).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput idle;
|
||||||
|
idle.robot_stopped = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(idle).state, NavigationState::kPaused);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachinePausing, GivesUpAfterSettleTimeoutAndFlagsIt)
|
||||||
|
{
|
||||||
|
StateMachineConfig config = baseConfig();
|
||||||
|
config.settle_timeout = 0.5; // [s]
|
||||||
|
Driver driver(config);
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput busy;
|
||||||
|
busy.robot_stopped = true;
|
||||||
|
busy.planner_busy = true;
|
||||||
|
driver.advance(0.45);
|
||||||
|
EXPECT_EQ(driver.tick(busy).state, NavigationState::kPausing);
|
||||||
|
driver.advance(0.10);
|
||||||
|
const StateMachineOutput out = driver.tick(busy);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kPaused);
|
||||||
|
EXPECT_TRUE(out.settle_timed_out);
|
||||||
|
EXPECT_FALSE(driver.idleTick().settle_timed_out) << "one-cycle flag";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachinePausing, ResumeBeforeSettledReturnsToThePreviousState)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput resume;
|
||||||
|
resume.resume_requested = true;
|
||||||
|
resume.planner_busy = true; // chưa im mà đã được bảo chạy tiếp — không phải chờ
|
||||||
|
const StateMachineOutput out = driver.tick(resume);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||||
|
EXPECT_TRUE(out.apply_plan);
|
||||||
|
EXPECT_TRUE(out.run_controller);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachinePausing, CancelBeforeSettledGoesToCancellingAndKeepsWaiting)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
|
||||||
|
StateMachineInput request;
|
||||||
|
request.has_pending_request = true;
|
||||||
|
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
pause.planner_busy = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
cancel.planner_busy = true;
|
||||||
|
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput busy;
|
||||||
|
busy.robot_stopped = true;
|
||||||
|
busy.planner_busy = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput idle;
|
||||||
|
idle.robot_stopped = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachinePausing, NewGoalWhilePausingPreemptsLikePaused)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput new_goal;
|
||||||
|
new_goal.has_pending_request = true;
|
||||||
|
const StateMachineOutput out = driver.tick(new_goal);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kPlanning);
|
||||||
|
EXPECT_TRUE(out.report_outcome);
|
||||||
|
EXPECT_EQ(out.outcome, NavigationOutcome::kPreempted);
|
||||||
|
EXPECT_TRUE(out.accept_request);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachinePausing, ZeroSettleTimeoutSettlesOnRobotStoppedOnly)
|
||||||
|
{
|
||||||
|
StateMachineConfig config = baseConfig();
|
||||||
|
config.settle_timeout = 0.0;
|
||||||
|
Driver driver(config);
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput stopped_but_busy;
|
||||||
|
stopped_but_busy.robot_stopped = true;
|
||||||
|
stopped_but_busy.planner_busy = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(stopped_but_busy).state, NavigationState::kPaused);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineCancelling, HoldsWhileRecoveryIsStillStopping)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput recovering;
|
||||||
|
recovering.robot_stopped = true;
|
||||||
|
recovering.recovery_busy = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(recovering).state, NavigationState::kCancelling);
|
||||||
|
|
||||||
|
StateMachineInput idle;
|
||||||
|
idle.robot_stopped = true;
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||||
|
}
|
||||||
|
|
||||||
TEST(StateMachineTerminal, OutcomeIsReportedExactlyOnce)
|
TEST(StateMachineTerminal, OutcomeIsReportedExactlyOnce)
|
||||||
{
|
{
|
||||||
Driver driver;
|
Driver driver;
|
||||||
@@ -1393,18 +1879,57 @@ TEST(StateMachineActions, PauseDuringActionFreezesWithoutCancelling)
|
|||||||
StateMachineInput pause;
|
StateMachineInput pause;
|
||||||
pause.pause_requested = true;
|
pause.pause_requested = true;
|
||||||
const StateMachineOutput paused = driver.tick(pause);
|
const StateMachineOutput paused = driver.tick(pause);
|
||||||
EXPECT_EQ(paused.state, NavigationState::kPaused);
|
EXPECT_EQ(paused.state, NavigationState::kPausing);
|
||||||
EXPECT_FALSE(paused.cancel_action) << "the action is not idempotent — pausing must not cancel it";
|
EXPECT_FALSE(paused.cancel_action) << "the action is not idempotent — pausing must not cancel it";
|
||||||
EXPECT_FALSE(paused.tick_action);
|
EXPECT_FALSE(paused.tick_action);
|
||||||
|
EXPECT_TRUE(paused.pause_action) << "the handler must be told, so its own timeout clock stops";
|
||||||
|
|
||||||
StateMachineInput resume;
|
StateMachineInput resume;
|
||||||
resume.resume_requested = true;
|
resume.resume_requested = true;
|
||||||
const StateMachineOutput resumed = driver.tick(resume);
|
const StateMachineOutput resumed = driver.tick(resume);
|
||||||
EXPECT_EQ(resumed.state, NavigationState::kExecutingActions);
|
EXPECT_EQ(resumed.state, NavigationState::kExecutingActions);
|
||||||
EXPECT_TRUE(resumed.tick_action) << "resume keeps ticking the unfinished action";
|
EXPECT_TRUE(resumed.tick_action) << "resume keeps ticking the unfinished action";
|
||||||
|
EXPECT_TRUE(resumed.resume_action) << "the handler must be told the pause is over";
|
||||||
EXPECT_FALSE(resumed.start_action) << "an action already in progress must not be started again";
|
EXPECT_FALSE(resumed.start_action) << "an action already in progress must not be started again";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineActions, PausingWithAnActionWaitsForTheHandlerToAcknowledge)
|
||||||
|
{
|
||||||
|
// Handler chưa xác nhận pause (action_terminal=false) → PAUSING tick tiếp; xác nhận → PAUSED.
|
||||||
|
Driver driver;
|
||||||
|
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||||
|
NavigationState::kExecutingActions);
|
||||||
|
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
pause.action_terminal = false;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
StateMachineInput not_yet;
|
||||||
|
not_yet.robot_stopped = true;
|
||||||
|
not_yet.action_terminal = false;
|
||||||
|
driver.advance(0.05);
|
||||||
|
const StateMachineOutput held = driver.tick(not_yet);
|
||||||
|
EXPECT_EQ(held.state, NavigationState::kPausing);
|
||||||
|
EXPECT_TRUE(held.tick_action);
|
||||||
|
EXPECT_EQ(held.velocity_source, VelocitySource::kNone);
|
||||||
|
|
||||||
|
StateMachineInput acked = not_yet;
|
||||||
|
acked.action_terminal = true; // hàng kAction = paused
|
||||||
|
driver.advance(0.05);
|
||||||
|
EXPECT_EQ(driver.tick(acked).state, NavigationState::kPaused);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineActions, CancelledFeedbackInsideExecutingActionsIsTreatedAsFailure)
|
||||||
|
{
|
||||||
|
// Lỗi thứ tự gọi (không ai cancel trong EXECUTING_ACTIONS) — không được im lặng chạy tiếp.
|
||||||
|
Driver driver;
|
||||||
|
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||||
|
NavigationState::kExecutingActions);
|
||||||
|
const StateMachineOutput out = driver.tick(actionFb(ActionFeedback::kCancelled));
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kAborted);
|
||||||
|
}
|
||||||
|
|
||||||
TEST(StateMachineActions, ActionPatienceIsDisabledByDefault)
|
TEST(StateMachineActions, ActionPatienceIsDisabledByDefault)
|
||||||
{
|
{
|
||||||
Driver driver;
|
Driver driver;
|
||||||
@@ -1451,7 +1976,7 @@ TEST(StateMachineActions, PauseRearmsActionPatienceClock)
|
|||||||
|
|
||||||
StateMachineInput pause;
|
StateMachineInput pause;
|
||||||
pause.pause_requested = true;
|
pause.pause_requested = true;
|
||||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
// Dừng lâu hơn hẳn action_patience rồi mới resume — quãng dừng không được tính vào trần.
|
// Dừng lâu hơn hẳn action_patience rồi mới resume — quãng dừng không được tính vào trần.
|
||||||
driver.advance(30.0);
|
driver.advance(30.0);
|
||||||
@@ -1556,9 +2081,9 @@ TEST(StateMachineInvariants, EveryStateHasANonEmptyName)
|
|||||||
{
|
{
|
||||||
const NavigationState states[] = {
|
const NavigationState states[] = {
|
||||||
NavigationState::kIdle, NavigationState::kPlanning, NavigationState::kControlling,
|
NavigationState::kIdle, NavigationState::kPlanning, NavigationState::kControlling,
|
||||||
NavigationState::kRecovering, NavigationState::kExecutingActions, NavigationState::kPaused,
|
NavigationState::kRecovering, NavigationState::kExecutingActions, NavigationState::kPausing,
|
||||||
NavigationState::kCancelling, NavigationState::kSucceeded, NavigationState::kAborted,
|
NavigationState::kPaused, NavigationState::kCancelling, NavigationState::kEmergency,
|
||||||
NavigationState::kCancelled,
|
NavigationState::kSucceeded, NavigationState::kAborted, NavigationState::kCancelled,
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const auto state : states)
|
for (const auto state : states)
|
||||||
@@ -2157,6 +2682,248 @@ TEST(StateMachineConfigValidation, MonitorRoutesMayBeEmptyButIndicesMustExist)
|
|||||||
EXPECT_NE(error.find("path_blocked"), std::string::npos) << error;
|
EXPECT_NE(error.find("path_blocked"), std::string::npos) << error;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ================================================================================================
|
||||||
|
// EMERGENCY (2026-09-14) — mức, không phải xung; thắng mọi thứ; chỉ ra khi host gỡ chốt
|
||||||
|
// ================================================================================================
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
StateMachineInput emergencyInput()
|
||||||
|
{
|
||||||
|
StateMachineInput input;
|
||||||
|
input.emergency = true;
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Các cách đưa máy vào từng state đang chạy, để một test quét được hết bảng.
|
||||||
|
void driveTo(Driver& driver, NavigationState target)
|
||||||
|
{
|
||||||
|
switch (target)
|
||||||
|
{
|
||||||
|
case NavigationState::kPlanning:
|
||||||
|
ASSERT_EQ(driver.tick(requestWithActions(0)).state, NavigationState::kPlanning);
|
||||||
|
return;
|
||||||
|
case NavigationState::kControlling:
|
||||||
|
driver.driveToControlling();
|
||||||
|
return;
|
||||||
|
case NavigationState::kRecovering:
|
||||||
|
ASSERT_EQ(driver.tick(requestWithActions(0)).state, NavigationState::kPlanning);
|
||||||
|
driver.advance(2.0);
|
||||||
|
ASSERT_EQ(driver.tick(plannerFailed()).state, NavigationState::kRecovering);
|
||||||
|
return;
|
||||||
|
case NavigationState::kExecutingActions:
|
||||||
|
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||||
|
NavigationState::kExecutingActions);
|
||||||
|
return;
|
||||||
|
case NavigationState::kPausing:
|
||||||
|
{
|
||||||
|
driver.driveToControlling();
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
pause.planner_busy = true; // giữ ở PAUSING
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case NavigationState::kPaused:
|
||||||
|
{
|
||||||
|
driver.driveToControlling();
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
StateMachineInput stopped;
|
||||||
|
stopped.robot_stopped = true;
|
||||||
|
ASSERT_EQ(driver.tick(stopped).state, NavigationState::kPaused);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case NavigationState::kCancelling:
|
||||||
|
{
|
||||||
|
driver.driveToControlling();
|
||||||
|
StateMachineInput cancel;
|
||||||
|
cancel.cancel_requested = true;
|
||||||
|
cancel.planner_busy = true; // giữ ở CANCELLING
|
||||||
|
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
FAIL() << "driveTo has no recipe for " << move_base2::toString(target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, FromEveryRunningStateStopsEverythingAndReportsCancelled)
|
||||||
|
{
|
||||||
|
const NavigationState running[] = {
|
||||||
|
NavigationState::kPlanning, NavigationState::kControlling, NavigationState::kRecovering,
|
||||||
|
NavigationState::kExecutingActions, NavigationState::kPausing, NavigationState::kPaused,
|
||||||
|
NavigationState::kCancelling,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const NavigationState from : running)
|
||||||
|
{
|
||||||
|
SCOPED_TRACE(move_base2::toString(from));
|
||||||
|
Driver driver;
|
||||||
|
driveTo(driver, from);
|
||||||
|
|
||||||
|
const StateMachineOutput out = driver.tick(emergencyInput());
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kEmergency);
|
||||||
|
EXPECT_TRUE(out.state_changed);
|
||||||
|
EXPECT_STREQ(out.reason, "emergency stop");
|
||||||
|
|
||||||
|
EXPECT_TRUE(out.stop_planner);
|
||||||
|
EXPECT_EQ(out.cancel_recovery, from == NavigationState::kRecovering)
|
||||||
|
<< "only a running behavior is told to stop";
|
||||||
|
EXPECT_EQ(out.cancel_action, from == NavigationState::kExecutingActions)
|
||||||
|
<< "only a running action is told to stop (pause from CONTROLLING has no action)";
|
||||||
|
|
||||||
|
EXPECT_TRUE(out.report_outcome) << "the interrupted leg must be reported exactly once";
|
||||||
|
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||||
|
|
||||||
|
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||||
|
EXPECT_FALSE(out.run_controller);
|
||||||
|
EXPECT_FALSE(out.tick_recovery);
|
||||||
|
EXPECT_FALSE(out.accept_request);
|
||||||
|
EXPECT_FALSE(out.start_planner);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, FromPausedActionCancelsTheActionThePauseKeptAlive)
|
||||||
|
{
|
||||||
|
// Tạm dừng KHÔNG huỷ action (handler vẫn giữ thiết bị dở dang) — dừng khẩn thì phải huỷ nó.
|
||||||
|
Driver driver;
|
||||||
|
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||||
|
NavigationState::kExecutingActions);
|
||||||
|
StateMachineInput pause;
|
||||||
|
pause.pause_requested = true;
|
||||||
|
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||||
|
|
||||||
|
const StateMachineOutput out = driver.tick(emergencyInput());
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kEmergency);
|
||||||
|
EXPECT_TRUE(out.cancel_action);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, FromIdleDoesNotReportAnOutcomeAndRefusesThePendingGoal)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
StateMachineInput input = emergencyInput();
|
||||||
|
input.has_pending_request = true;
|
||||||
|
|
||||||
|
const StateMachineOutput out = driver.tick(input);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kEmergency);
|
||||||
|
EXPECT_FALSE(out.report_outcome) << "nothing was running, there is no leg to report";
|
||||||
|
EXPECT_FALSE(out.accept_request) << "a goal waiting at IDLE must not start under emergency";
|
||||||
|
EXPECT_FALSE(out.start_planner);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, WinsOverCancelPauseAndANewGoalInTheSameCycle)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
|
||||||
|
StateMachineInput everything = emergencyInput();
|
||||||
|
everything.cancel_requested = true;
|
||||||
|
everything.pause_requested = true;
|
||||||
|
everything.has_pending_request = true;
|
||||||
|
everything.planner = PlannerFeedback::kPlanReady;
|
||||||
|
|
||||||
|
const StateMachineOutput out = driver.tick(everything);
|
||||||
|
EXPECT_EQ(out.state, NavigationState::kEmergency);
|
||||||
|
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled) << "not PREEMPTED: the goal is dropped, not replaced";
|
||||||
|
EXPECT_FALSE(out.accept_request);
|
||||||
|
EXPECT_FALSE(out.apply_plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, IgnoresEveryLifecycleRequestWhileLatched)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
ASSERT_EQ(driver.tick(emergencyInput()).state, NavigationState::kEmergency);
|
||||||
|
|
||||||
|
StateMachineInput noise = emergencyInput();
|
||||||
|
noise.pause_requested = true;
|
||||||
|
noise.resume_requested = true;
|
||||||
|
noise.cancel_requested = true;
|
||||||
|
noise.has_pending_request = true;
|
||||||
|
noise.planner = PlannerFeedback::kPlanReady;
|
||||||
|
noise.controller = ControllerFeedback::kGoalReached;
|
||||||
|
noise.robot_stopped = true;
|
||||||
|
|
||||||
|
for (int cycle = 0; cycle < 10; ++cycle)
|
||||||
|
{
|
||||||
|
driver.advance(0.5);
|
||||||
|
const StateMachineOutput out = driver.tick(noise);
|
||||||
|
ASSERT_EQ(out.state, NavigationState::kEmergency) << "cycle " << cycle;
|
||||||
|
ASSERT_FALSE(out.state_changed);
|
||||||
|
ASSERT_FALSE(out.report_outcome) << "cycle " << cycle << ": outcome must be reported once, at entry";
|
||||||
|
ASSERT_FALSE(out.accept_request);
|
||||||
|
ASSERT_FALSE(out.start_planner);
|
||||||
|
ASSERT_FALSE(out.apply_plan);
|
||||||
|
ASSERT_FALSE(out.run_controller);
|
||||||
|
ASSERT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, KeepsTickingTheActionUntilItReportsTerminal)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||||
|
NavigationState::kExecutingActions);
|
||||||
|
|
||||||
|
StateMachineInput enter = emergencyInput();
|
||||||
|
enter.action_terminal = false;
|
||||||
|
const StateMachineOutput entered = driver.tick(enter);
|
||||||
|
ASSERT_EQ(entered.state, NavigationState::kEmergency);
|
||||||
|
EXPECT_TRUE(entered.cancel_action);
|
||||||
|
|
||||||
|
StateMachineInput still_stopping = emergencyInput();
|
||||||
|
still_stopping.action_terminal = false;
|
||||||
|
const StateMachineOutput ticking = driver.tick(still_stopping);
|
||||||
|
EXPECT_TRUE(ticking.tick_action) << "the device handler needs ticks to reach its safe stop";
|
||||||
|
EXPECT_EQ(ticking.velocity_source, VelocitySource::kNone);
|
||||||
|
|
||||||
|
const StateMachineOutput done = driver.tick(emergencyInput()); // action_terminal mặc định true
|
||||||
|
EXPECT_FALSE(done.tick_action);
|
||||||
|
EXPECT_EQ(done.state, NavigationState::kEmergency) << "terminal action does not end the emergency";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, ClearReturnsToIdleAndOnlyTheNextCycleAcceptsAGoal)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
driver.driveToControlling();
|
||||||
|
ASSERT_EQ(driver.tick(emergencyInput()).state, NavigationState::kEmergency);
|
||||||
|
|
||||||
|
// Gỡ chốt đúng lúc có goal chờ: cycle này KHÔNG nhận — ControlLoop đã vứt yêu cầu chờ lúc vào
|
||||||
|
// dừng khẩn, thứ nằm ở đây không thể là yêu cầu hợp lệ.
|
||||||
|
StateMachineInput cleared;
|
||||||
|
cleared.has_pending_request = true;
|
||||||
|
const StateMachineOutput idle = driver.tick(cleared);
|
||||||
|
EXPECT_EQ(idle.state, NavigationState::kIdle);
|
||||||
|
EXPECT_STREQ(idle.reason, "emergency cleared");
|
||||||
|
EXPECT_FALSE(idle.accept_request);
|
||||||
|
EXPECT_FALSE(idle.report_outcome);
|
||||||
|
|
||||||
|
// Cycle kế: kIdle nhận goal như bình thường.
|
||||||
|
const StateMachineOutput planning = driver.tick(requestWithActions(0));
|
||||||
|
EXPECT_EQ(planning.state, NavigationState::kPlanning);
|
||||||
|
EXPECT_TRUE(planning.accept_request);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, ClearWithoutAnythingPendingStaysIdle)
|
||||||
|
{
|
||||||
|
Driver driver;
|
||||||
|
ASSERT_EQ(driver.tick(emergencyInput()).state, NavigationState::kEmergency);
|
||||||
|
EXPECT_EQ(driver.idleTick().state, NavigationState::kIdle);
|
||||||
|
EXPECT_EQ(driver.idleTick().state, NavigationState::kIdle);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(StateMachineEmergency, IsNotTerminalAndMustBeStopped)
|
||||||
|
{
|
||||||
|
EXPECT_FALSE(move_base2::isTerminal(NavigationState::kEmergency));
|
||||||
|
EXPECT_TRUE(move_base2::mustBeStopped(NavigationState::kEmergency));
|
||||||
|
EXPECT_STREQ(move_base2::toString(NavigationState::kEmergency), "EMERGENCY");
|
||||||
|
}
|
||||||
|
|
||||||
int main(int argc, char** argv)
|
int main(int argc, char** argv)
|
||||||
{
|
{
|
||||||
testing::InitGoogleTest(&argc, argv);
|
testing::InitGoogleTest(&argc, argv);
|
||||||
|
|||||||
@@ -130,6 +130,10 @@ public:
|
|||||||
deps_.action = &action_;
|
deps_.action = &action_;
|
||||||
deps_.costmap_status = &costmap_status_;
|
deps_.costmap_status = &costmap_status_;
|
||||||
deps_.environment = &environment_;
|
deps_.environment = &environment_;
|
||||||
|
deps_.components = &components_;
|
||||||
|
planner_.attachStatusBoard(&components_);
|
||||||
|
recovery_.attachStatusBoard(&components_);
|
||||||
|
action_.attachStatusBoard(&components_);
|
||||||
|
|
||||||
std::string error;
|
std::string error;
|
||||||
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
|
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
|
||||||
@@ -179,6 +183,7 @@ public:
|
|||||||
FakeActionPort action_;
|
FakeActionPort action_;
|
||||||
FakeCostmapStatusPort costmap_status_;
|
FakeCostmapStatusPort costmap_status_;
|
||||||
FakeEnvironmentPort environment_;
|
FakeEnvironmentPort environment_;
|
||||||
|
move_base2::ComponentStatusBoard components_;
|
||||||
ControlLoopDeps deps_;
|
ControlLoopDeps deps_;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -591,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.
|
||||||
@@ -814,8 +852,11 @@ TEST(ControlLoop, PauseAndResumeMidControlling)
|
|||||||
fixture.clock_.advance(kControlPeriod);
|
fixture.clock_.advance(kControlPeriod);
|
||||||
fixture.loop_.step();
|
fixture.loop_.step();
|
||||||
|
|
||||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPausing);
|
||||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||||
|
|
||||||
// Dừng lâu rồi tiếp tục: không được vì thế mà rơi vào recovery.
|
// Dừng lâu rồi tiếp tục: không được vì thế mà rơi vào recovery.
|
||||||
fixture.clock_.advance(30.0);
|
fixture.clock_.advance(30.0);
|
||||||
@@ -826,6 +867,574 @@ TEST(ControlLoop, PauseAndResumeMidControlling)
|
|||||||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, ResumeMidControllingReappliesThePlanToTheController)
|
||||||
|
{
|
||||||
|
// Local planner giữ warm-start/slew theo thời gian; sau 30 s đứng yên phải nạp lại plan để
|
||||||
|
// plugin reset theo pose hiện tại (2026-09-11).
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.controller_.setScript({ControllerScript::kOk});
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||||||
|
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||||
|
const std::size_t set_plan_before = fixture.controller_.setPlanCount();
|
||||||
|
ASSERT_EQ(set_plan_before, 1u);
|
||||||
|
|
||||||
|
fixture.loop_.requestPause();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||||
|
EXPECT_EQ(fixture.controller_.setPlanCount(), set_plan_before) << "pause must not touch the plan";
|
||||||
|
|
||||||
|
fixture.clock_.advance(30.0);
|
||||||
|
fixture.loop_.requestResume();
|
||||||
|
fixture.loop_.step();
|
||||||
|
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||||
|
EXPECT_EQ(fixture.controller_.setPlanCount(), set_plan_before + 1)
|
||||||
|
<< "resume from CONTROLLING must call setPlan() again so the plugin resets its warm start";
|
||||||
|
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================
|
||||||
|
// Cancel phải dừng THẬT (2026-09-11): CANCELLED chỉ khi thread planner rảnh và odom về 0.
|
||||||
|
// Tái hiện log: cancel lúc SBPL đang chạy → host thấy CANCELLED sau 33 ms → gửi goal kế →
|
||||||
|
// startPlan() bị từ chối vì thread còn bận → bị coi là hỏng → recovery → ABORTED.
|
||||||
|
// ================================================================================================
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Fixture với planner "chậm" (10 cycle) và KHÔNG preempt được — đúng SBPL trước pha 2.
|
||||||
|
ControlLoopConfig busyPlannerConfig()
|
||||||
|
{
|
||||||
|
ControlLoopConfig config = baseConfig();
|
||||||
|
config.state_machine.planner_patience = 5.0; // [s] đủ dài để kBusy không bị patience cắt
|
||||||
|
config.state_machine.max_planning_retries = 0; // như config trên máy chạy log
|
||||||
|
config.state_machine.settle_timeout = 2.0; // [s]
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr std::size_t kSlowPlannerCycles = 10;
|
||||||
|
|
||||||
|
/// Đưa fixture tới PLANNING với một lượt lập plan đang bay, chưa có kết quả.
|
||||||
|
void driveToPlanningInFlight(Fixture& fixture, std::uint64_t mission_id)
|
||||||
|
{
|
||||||
|
fixture.planner_.setLatencyCycles(kSlowPlannerCycles);
|
||||||
|
fixture.planner_.setCancelKeepsBusy(true);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, mission_id), reason)) << reason;
|
||||||
|
|
||||||
|
fixture.loop_.step(); // accept → PLANNING, startPlan()
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step(); // pollPlan: chưa có
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||||||
|
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(ControlLoop, CancelWhilePlannerStaysBusyHoldsCancellingUntilTheThreadIsIdle)
|
||||||
|
{
|
||||||
|
Fixture fixture(busyPlannerConfig());
|
||||||
|
driveToPlanningInFlight(fixture, 7);
|
||||||
|
// reset() lúc configure và accept_request đều gọi cancelPlan() (dọn lượt cũ) — đếm tương đối.
|
||||||
|
const std::size_t cancels_before = fixture.planner_.cancelCount();
|
||||||
|
|
||||||
|
fixture.loop_.requestCancel();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||||
|
EXPECT_EQ(fixture.planner_.cancelCount(), cancels_before + 1);
|
||||||
|
EXPECT_TRUE(fixture.planner_.isPlanning()) << "the fake models a planner that cannot be preempted";
|
||||||
|
|
||||||
|
// Chừng nào thread còn bận: giữ CANCELLING, lệnh = 0, KHÔNG báo kết quả. Cycle mà thread rảnh
|
||||||
|
// (pollPlan thấy lượt cũ xong) cũng chính là cycle CANCELLED — không chậm thêm vòng nào.
|
||||||
|
std::size_t cycles_held = 0;
|
||||||
|
for (; cycles_held < 50; ++cycles_held)
|
||||||
|
{
|
||||||
|
const bool busy_before = fixture.planner_.isPlanning();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
|
if (fixture.loop_.state() == NavigationState::kCancelled)
|
||||||
|
{
|
||||||
|
EXPECT_TRUE(busy_before) << "must not finish before the very cycle the thread frees";
|
||||||
|
EXPECT_FALSE(fixture.planner_.isPlanning());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << cycles_held;
|
||||||
|
EXPECT_TRUE(fixture.planner_.isPlanning()) << "held CANCELLING although the thread is idle";
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(7), 0u) << "CANCELLED reported while planner busy";
|
||||||
|
}
|
||||||
|
EXPECT_GE(cycles_held, 3u) << "the fake planner should have stayed busy for several cycles";
|
||||||
|
EXPECT_LT(cycles_held, 50u) << "never reached CANCELLED";
|
||||||
|
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||||
|
EXPECT_STREQ(fixture.loop_.lastOutcome(), "CANCELLED");
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, GoalSentRightAfterCancelWaitsForTheBusyPlannerInsteadOfFailing)
|
||||||
|
{
|
||||||
|
// Đúng chuỗi sự kiện trong log: cancel mission 3, mission 4 tới 0.2 s sau. Không được có
|
||||||
|
// RECOVERING/ABORTED; mission 4 phải tới CONTROLLING sau khi thread rảnh.
|
||||||
|
Fixture fixture(busyPlannerConfig());
|
||||||
|
driveToPlanningInFlight(fixture, 3);
|
||||||
|
|
||||||
|
fixture.loop_.requestCancel();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||||
|
|
||||||
|
// Host không đợi PREEMPTED (hành vi cũ của khung chương trình): gửi goal kế ngay.
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 4), reason)) << reason;
|
||||||
|
|
||||||
|
const std::size_t make_plan_before = fixture.planner_.makePlanCount();
|
||||||
|
bool saw_recovering = false;
|
||||||
|
bool saw_aborted = false;
|
||||||
|
bool reached_controlling = false;
|
||||||
|
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
const NavigationState s = fixture.loop_.state();
|
||||||
|
saw_recovering = saw_recovering || s == NavigationState::kRecovering;
|
||||||
|
saw_aborted = saw_aborted || s == NavigationState::kAborted;
|
||||||
|
reached_controlling = s == NavigationState::kControlling;
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPECT_FALSE(saw_recovering) << "a busy planner thread was treated as a failed planning attempt";
|
||||||
|
EXPECT_FALSE(saw_aborted);
|
||||||
|
EXPECT_TRUE(reached_controlling);
|
||||||
|
EXPECT_EQ(fixture.planner_.makePlanCount(), make_plan_before + 1)
|
||||||
|
<< "exactly one new planning attempt once the thread was free";
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(3), 1u) << "mission 3 reported once (CANCELLED)";
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(4), 0u) << "mission 4 is still running";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, EmergencyWhileControllingZeroesTheCommandAndLatches)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kOk, ControllerScript::kOk});
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 5), reason)) << reason;
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||||
|
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
|
|
||||||
|
fixture.loop_.requestEmergency();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
EXPECT_TRUE(fixture.loop_.step()) << "EMERGENCY is not terminal: the loop keeps running";
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kEmergency);
|
||||||
|
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "zero in the very cycle, no ramp";
|
||||||
|
EXPECT_STREQ(fixture.loop_.lastOutcome(), "CANCELLED");
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(5), 1u);
|
||||||
|
EXPECT_FALSE(fixture.loop_.hasActiveRequest());
|
||||||
|
|
||||||
|
// Chốt: goal mới bị từ chối tại cửa, pause/resume/cancel không đổi gì, lệnh vẫn 0.
|
||||||
|
EXPECT_FALSE(fixture.loop_.submit(makeRequest(5.0, 6), reason));
|
||||||
|
EXPECT_NE(reason.find("emergency"), std::string::npos) << reason;
|
||||||
|
fixture.loop_.requestPause();
|
||||||
|
fixture.loop_.requestResume();
|
||||||
|
fixture.loop_.requestCancel();
|
||||||
|
for (int i = 0; i < 5; ++i)
|
||||||
|
{
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kEmergency) << "cycle " << i;
|
||||||
|
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
|
}
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(5), 1u) << "reported exactly once";
|
||||||
|
|
||||||
|
// Gỡ chốt: IDLE, không tự chạy; goal kế được nhận bình thường.
|
||||||
|
fixture.loop_.requestClearEmergency();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kIdle);
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kIdle);
|
||||||
|
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 6), reason)) << reason;
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, EmergencyWhilePlannerIsBusyPreemptsItAndTheNextGoalWaitsInsteadOfFailing)
|
||||||
|
{
|
||||||
|
Fixture fixture(busyPlannerConfig());
|
||||||
|
driveToPlanningInFlight(fixture, 7);
|
||||||
|
const std::size_t cancels_before = fixture.planner_.cancelCount();
|
||||||
|
|
||||||
|
fixture.loop_.requestEmergency();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kEmergency)
|
||||||
|
<< "EMERGENCY is reported at once — it is a latch, not 'done'; nothing waits for quiescence";
|
||||||
|
EXPECT_EQ(fixture.planner_.cancelCount(), cancels_before + 1) << "the running makePlan is cut";
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
|
||||||
|
|
||||||
|
// Gỡ chốt trong lúc thread planner vẫn còn bận lượt đã huỷ, rồi gửi goal kế ngay: phải chờ
|
||||||
|
// (kBusy) chứ không được coi là hỏng.
|
||||||
|
fixture.loop_.requestClearEmergency();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kIdle);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 8), reason)) << reason;
|
||||||
|
bool saw_recovering = false;
|
||||||
|
bool saw_aborted = false;
|
||||||
|
bool reached_controlling = false;
|
||||||
|
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
const NavigationState s = fixture.loop_.state();
|
||||||
|
saw_recovering = saw_recovering || s == NavigationState::kRecovering;
|
||||||
|
saw_aborted = saw_aborted || s == NavigationState::kAborted;
|
||||||
|
reached_controlling = s == NavigationState::kControlling;
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(saw_recovering);
|
||||||
|
EXPECT_FALSE(saw_aborted);
|
||||||
|
EXPECT_TRUE(reached_controlling);
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(8), 0u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, EmergencyDropsAPendingRequestSoNothingRunsAfterClear)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.controller_.setScript({ControllerScript::kOk});
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 9), reason)) << reason;
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kIdle) << "still pending, no cycle ran";
|
||||||
|
|
||||||
|
fixture.loop_.requestEmergency();
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kEmergency);
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(9), 0u) << "never accepted, nothing to report";
|
||||||
|
|
||||||
|
fixture.loop_.requestClearEmergency();
|
||||||
|
for (int i = 0; i < 3; ++i)
|
||||||
|
{
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
}
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kIdle) << "the dropped goal must not start by itself";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, EmergencyDuringRecoveryStopsTheBehavior)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.planner_.setScript({PlannerScript::kFail});
|
||||||
|
fixture.recovery_.setScript({RecoveryScript::kRunning});
|
||||||
|
fixture.recovery_.setRecoveryVelocity(true, -0.15);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 10), reason)) << reason;
|
||||||
|
for (int i = 0; i < 40 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
}
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||||||
|
|
||||||
|
fixture.loop_.requestEmergency();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kEmergency);
|
||||||
|
EXPECT_EQ(fixture.recovery_.cancelCount(), 1u);
|
||||||
|
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "the behavior's -0.15 m/s must not survive";
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(10), 1u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, PauseWhilePlanningThenResumeWaitsForTheBusyPlanner)
|
||||||
|
{
|
||||||
|
// pause lúc PLANNING đi cùng đường cancelPlan(); resume → PLANNING → startPlan() bị từ chối →
|
||||||
|
// phải là kBusy, không phải kFailed.
|
||||||
|
Fixture fixture(busyPlannerConfig());
|
||||||
|
driveToPlanningInFlight(fixture, 8);
|
||||||
|
|
||||||
|
fixture.loop_.requestPause();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPausing)
|
||||||
|
<< "planner thread still busy: PAUSED must not be reported yet";
|
||||||
|
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||||
|
|
||||||
|
fixture.loop_.requestResume();
|
||||||
|
bool saw_recovering = false;
|
||||||
|
bool reached_controlling = false;
|
||||||
|
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
saw_recovering = saw_recovering || fixture.loop_.state() == NavigationState::kRecovering;
|
||||||
|
reached_controlling = fixture.loop_.state() == NavigationState::kControlling;
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(saw_recovering);
|
||||||
|
EXPECT_TRUE(reached_controlling);
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(8), 0u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, NewGoalPreemptingABusyPlannerWaitsInsteadOfFailing)
|
||||||
|
{
|
||||||
|
// MissionManager::submit() tự huỷ mission đang chạy — không cần cancel vẫn dính cùng đường.
|
||||||
|
Fixture fixture(busyPlannerConfig());
|
||||||
|
driveToPlanningInFlight(fixture, 11);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(6.0, 12), reason)) << reason;
|
||||||
|
|
||||||
|
bool saw_recovering = false;
|
||||||
|
bool reached_controlling = false;
|
||||||
|
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
saw_recovering = saw_recovering || fixture.loop_.state() == NavigationState::kRecovering;
|
||||||
|
reached_controlling = fixture.loop_.state() == NavigationState::kControlling;
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(saw_recovering);
|
||||||
|
EXPECT_TRUE(reached_controlling);
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(11), 1u) << "mission 11 reported once (PREEMPTED)";
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(12), 0u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, BusyPlannerStillCountsAgainstPlannerPatience)
|
||||||
|
{
|
||||||
|
// kBusy không phải vé miễn phí: plugin treo thật thì planner_patience vẫn phải leo thang.
|
||||||
|
ControlLoopConfig config = busyPlannerConfig();
|
||||||
|
config.state_machine.planner_patience = 0.2; // [s] = 4 cycle
|
||||||
|
Fixture fixture(config);
|
||||||
|
fixture.planner_.setLatencyCycles(100); // treo "vĩnh viễn" so với patience
|
||||||
|
fixture.planner_.setCancelKeepsBusy(true);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 20), reason)) << reason;
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
|
||||||
|
// Goal kế chen ngang (preempt) trong lúc thread treo: chờ bằng kBusy tối đa planner_patience rồi
|
||||||
|
// mới recovery. Dùng preempt thay vì cancel để không phải đợi settle_timeout ở đây.
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 21), reason)) << reason;
|
||||||
|
bool saw_recovering = false;
|
||||||
|
for (int i = 0; i < 30 && !saw_recovering; ++i)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
saw_recovering = fixture.loop_.state() == NavigationState::kRecovering;
|
||||||
|
}
|
||||||
|
EXPECT_TRUE(saw_recovering) << "a planner that never returns must still hit planner_patience";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, CancelSettleTimeoutFinishesCancelledEvenIfThePlannerNeverFrees)
|
||||||
|
{
|
||||||
|
ControlLoopConfig config = busyPlannerConfig();
|
||||||
|
config.state_machine.settle_timeout = 0.2; // [s] = 4 cycle
|
||||||
|
Fixture fixture(config);
|
||||||
|
fixture.planner_.setLatencyCycles(1000);
|
||||||
|
fixture.planner_.setCancelKeepsBusy(true);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 30), reason)) << reason;
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
|
||||||
|
fixture.loop_.requestCancel();
|
||||||
|
std::size_t cycles = 0;
|
||||||
|
bool running = true;
|
||||||
|
while (running && cycles < 20)
|
||||||
|
{
|
||||||
|
running = fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
++cycles;
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPECT_FALSE(running);
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||||
|
EXPECT_TRUE(fixture.planner_.isPlanning()) << "the thread is still busy — settle timeout fired";
|
||||||
|
EXPECT_GE(cycles, 4u);
|
||||||
|
EXPECT_LE(cycles, 7u) << "CANCELLED must arrive right after settle_timeout";
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(30), 1u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, CancellingWaitsForMeasuredVelocityToReadZero)
|
||||||
|
{
|
||||||
|
// Lệnh về 0 ngay cycle đầu, nhưng odom còn 0.3 m/s (driver đang giảm tốc) → chưa CANCELLED.
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.controller_.setScript({ControllerScript::kOk});
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 40), reason)) << reason;
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||||
|
fixture.controller_.setOdometry(0.3);
|
||||||
|
|
||||||
|
fixture.loop_.requestCancel();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||||
|
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
|
|
||||||
|
for (int i = 0; i < 5; ++i)
|
||||||
|
{
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << i;
|
||||||
|
}
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(40), 0u);
|
||||||
|
|
||||||
|
fixture.controller_.setOdometry(0.0);
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(40), 1u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, PauseWhilePlannerBusyHoldsPausingUntilTheThreadIsIdle)
|
||||||
|
{
|
||||||
|
// PAUSED nói thật (2026-09-11): pause nhận trong 1 cycle (lệnh 0), nhưng PAUSED chỉ khi thread
|
||||||
|
// planner đã nhả — cùng cơ chế với CANCELLING.
|
||||||
|
Fixture fixture(busyPlannerConfig());
|
||||||
|
driveToPlanningInFlight(fixture, 50);
|
||||||
|
|
||||||
|
fixture.loop_.requestPause();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPausing);
|
||||||
|
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
|
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kGlobalPlanner),
|
||||||
|
move_base2::ComponentPhase::kStopping)
|
||||||
|
<< "the fake planner reports 'stopping' after a cancel it cannot honour";
|
||||||
|
|
||||||
|
std::size_t held = 0;
|
||||||
|
for (; held < 50; ++held)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
if (fixture.loop_.state() == NavigationState::kPaused)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPausing) << "cycle " << held;
|
||||||
|
EXPECT_TRUE(fixture.planner_.isPlanning());
|
||||||
|
}
|
||||||
|
EXPECT_GE(held, 3u);
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||||
|
EXPECT_FALSE(fixture.planner_.isPlanning());
|
||||||
|
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kGlobalPlanner),
|
||||||
|
move_base2::ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, CancellingWaitsForARecoveryWorkerReportedThroughTheStatusBoard)
|
||||||
|
{
|
||||||
|
// Recovery có worker thread (detour, pha 2): cancel() không kết thúc được ngay → hàng kRecovery
|
||||||
|
// giữ 'stopping' → CANCELLING phải chờ, dù cổng planner đã rảnh và lệnh đã 0.
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.planner_.setScript({PlannerScript::kFail});
|
||||||
|
fixture.recovery_.setScript({RecoveryScript::kRunning});
|
||||||
|
fixture.recovery_.setCancelKeepsBusy(true);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 60), reason)) << reason;
|
||||||
|
for (int i = 0; i < 40 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
}
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||||||
|
|
||||||
|
fixture.loop_.requestCancel();
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||||
|
ASSERT_TRUE(fixture.recovery_.stopping());
|
||||||
|
|
||||||
|
for (int i = 0; i < 5; ++i)
|
||||||
|
{
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << i;
|
||||||
|
}
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(60), 0u);
|
||||||
|
|
||||||
|
fixture.recovery_.settleCancel(); // worker giả đã thoát
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(60), 1u);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, StatusBoardTracksLocalPlannerAndControlLoopHeartbeat)
|
||||||
|
{
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.controller_.setScript({ControllerScript::kOk});
|
||||||
|
|
||||||
|
const std::uint64_t before =
|
||||||
|
fixture.components_.at(move_base2::Component::kControlLoop).progress_ticks.load();
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||||
|
|
||||||
|
// Heartbeat nhích mỗi step(); local planner về idle sau mỗi lượt gọi (không để "bận" treo).
|
||||||
|
EXPECT_GE(fixture.components_.at(move_base2::Component::kControlLoop).progress_ticks.load(),
|
||||||
|
before + 2);
|
||||||
|
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kLocalPlanner),
|
||||||
|
move_base2::ComponentPhase::kIdle);
|
||||||
|
EXPECT_GT(fixture.components_.at(move_base2::Component::kLocalPlanner).progress_ticks.load(), 0u)
|
||||||
|
<< "computeVelocityCommands must have been bracketed busy/idle at least once";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoop, MeasuredVelocityIsIgnoredWhenTheEpsSwitchesAreZero)
|
||||||
|
{
|
||||||
|
ControlLoopConfig config = baseConfig();
|
||||||
|
config.state_machine.stopped_measured_linear_eps = 0.0;
|
||||||
|
config.state_machine.stopped_measured_angular_eps = 0.0;
|
||||||
|
Fixture fixture(config);
|
||||||
|
fixture.controller_.setScript({ControllerScript::kOk});
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 41), reason)) << reason;
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||||
|
fixture.controller_.setOdometry(0.3); // odom nói còn chạy — nhưng công tắc tắt
|
||||||
|
|
||||||
|
fixture.loop_.requestCancel();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
fixture.clock_.advance(kControlPeriod);
|
||||||
|
fixture.loop_.step();
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled)
|
||||||
|
<< "with eps = 0 'stopped' is judged from the issued command, as before 2026-09-11";
|
||||||
|
}
|
||||||
|
|
||||||
// ================================================================================================
|
// ================================================================================================
|
||||||
// Nhiều chặng liên tiếp
|
// Nhiều chặng liên tiếp
|
||||||
// ================================================================================================
|
// ================================================================================================
|
||||||
@@ -926,6 +1535,77 @@ TEST(ControlLoopActions, ActionFailureAbortsAndReportsOnce)
|
|||||||
EXPECT_EQ(fixture.recovery_.startCount(), 0u) << "a failed action must not drag recovery in";
|
EXPECT_EQ(fixture.recovery_.startCount(), 0u) << "a failed action must not drag recovery in";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoopActions, PauseAndResumeAreForwardedToTheActionPort)
|
||||||
|
{
|
||||||
|
// Pha 3 (2026-09-11): handler có timeout riêng phải biết pause để dịch mốc; không báo thì 20 s
|
||||||
|
// đứng chờ bị tính vào timeout dò 15 s → kFailed → ABORTED oan ngay sau resume.
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.action_.setScript({ActionScript::kRunning});
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 14), reason)) << reason;
|
||||||
|
fixture.stepOnce();
|
||||||
|
fixture.stepOnce();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||||
|
const std::size_t updates_before_pause = fixture.action_.updateCount();
|
||||||
|
|
||||||
|
fixture.loop_.requestPause();
|
||||||
|
fixture.stepOnce();
|
||||||
|
EXPECT_EQ(fixture.action_.pauseCount(), 1u);
|
||||||
|
EXPECT_EQ(fixture.action_.cancelCount(), 0u) << "pause must not cancel the action";
|
||||||
|
fixture.stepOnce(); // hàng kAction = paused → quiescent
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||||
|
EXPECT_EQ(fixture.action_.updateCount(), updates_before_pause) << "no ticks while paused";
|
||||||
|
|
||||||
|
fixture.clock_.advance(30.0);
|
||||||
|
fixture.loop_.requestResume();
|
||||||
|
fixture.stepOnce();
|
||||||
|
EXPECT_EQ(fixture.action_.resumeCount(), 1u);
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||||
|
EXPECT_GT(fixture.action_.updateCount(), updates_before_pause) << "ticking resumed";
|
||||||
|
EXPECT_EQ(fixture.action_.startCount(), 1u) << "the action must not be restarted";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ControlLoopActions, CancelWaitsForADeviceHandlerToReportCancelled)
|
||||||
|
{
|
||||||
|
// Handler thiết bị cần 3 tick sau cancel() để về vị trí an toàn: CANCELLING tick tiếp, không
|
||||||
|
// cấp vận tốc, và CANCELLED chỉ được báo sau tick kCancelled.
|
||||||
|
Fixture fixture;
|
||||||
|
fixture.action_.setScript({ActionScript::kRunning});
|
||||||
|
fixture.action_.setCancelNeedsTicks(3);
|
||||||
|
|
||||||
|
std::string reason;
|
||||||
|
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 15), reason)) << reason;
|
||||||
|
fixture.stepOnce();
|
||||||
|
fixture.stepOnce();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||||
|
|
||||||
|
fixture.loop_.requestCancel();
|
||||||
|
fixture.stepOnce();
|
||||||
|
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||||
|
EXPECT_EQ(fixture.action_.cancelCount(), 1u);
|
||||||
|
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kAction),
|
||||||
|
move_base2::ComponentPhase::kStopping);
|
||||||
|
|
||||||
|
std::size_t held = 0;
|
||||||
|
for (; held < 10; ++held)
|
||||||
|
{
|
||||||
|
if (fixture.loop_.state() == NavigationState::kCancelled)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << held;
|
||||||
|
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(15), 0u) << "CANCELLED reported before the device was safe";
|
||||||
|
fixture.stepOnce();
|
||||||
|
}
|
||||||
|
EXPECT_GE(held, 3u) << "the handler asked for 3 ticks after cancel";
|
||||||
|
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||||
|
EXPECT_EQ(fixture.mission_.reportCountFor(15), 1u);
|
||||||
|
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kAction),
|
||||||
|
move_base2::ComponentPhase::kIdle);
|
||||||
|
}
|
||||||
|
|
||||||
TEST(ControlLoopActions, SubmitRejectsActionRequestWhenActionPortMissing)
|
TEST(ControlLoopActions, SubmitRejectsActionRequestWhenActionPortMissing)
|
||||||
{
|
{
|
||||||
Fixture fixture;
|
Fixture fixture;
|
||||||
@@ -1412,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
|
||||||
{
|
{
|
||||||
|
|||||||
209
test/watchdog_test.cpp
Normal file
209
test/watchdog_test.cpp
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* move_base2 — test watchdog: kết luận treo từ bảng trạng thái, trên thread riêng.
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <limits>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
|
#include <move_base2/core/component_status.h>
|
||||||
|
#include <move_base2/io/watchdog.h>
|
||||||
|
|
||||||
|
using move_base2::Component;
|
||||||
|
using move_base2::ComponentPhase;
|
||||||
|
using move_base2::ComponentStatusBoard;
|
||||||
|
using move_base2::Watchdog;
|
||||||
|
using move_base2::WatchdogConfig;
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
WatchdogConfig fastConfig()
|
||||||
|
{
|
||||||
|
WatchdogConfig c;
|
||||||
|
c.period = 0.01; // [s]
|
||||||
|
c.planner_timeout = 0.05; // [s]
|
||||||
|
c.local_planner_call_budget = 0.05;
|
||||||
|
c.recovery_stall_budget = 0.05;
|
||||||
|
c.action_stall_budget = 0.05;
|
||||||
|
c.control_loop_stall_budget = 0.05;
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
void sleepMs(int ms)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(WatchdogConfig, RejectsNegativePeriodAndNonFiniteBudgets)
|
||||||
|
{
|
||||||
|
WatchdogConfig c;
|
||||||
|
std::string error;
|
||||||
|
c.period = -0.1;
|
||||||
|
EXPECT_FALSE(c.validate(error));
|
||||||
|
c = WatchdogConfig();
|
||||||
|
c.planner_timeout = std::numeric_limits<double>::infinity();
|
||||||
|
EXPECT_FALSE(c.validate(error));
|
||||||
|
c = WatchdogConfig();
|
||||||
|
c.period = 0.0; // tắt = hợp lệ
|
||||||
|
EXPECT_TRUE(c.validate(error)) << error;
|
||||||
|
EXPECT_NE(c.describe().find("planner_timeout"), std::string::npos);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Watchdog, IdleRowsAreNeverHung)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
Watchdog dog;
|
||||||
|
std::string error;
|
||||||
|
WatchdogConfig c = fastConfig();
|
||||||
|
c.period = 0.0; // không thread — checkOnce() tay
|
||||||
|
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||||
|
|
||||||
|
board.enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||||
|
sleepMs(80);
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_FALSE(dog.anyHung()) << "idle for a long time is not 'hung'";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Watchdog, WaitingForCostmapDoesNotConsumePlannerBudget)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
Watchdog dog;
|
||||||
|
std::string error;
|
||||||
|
WatchdogConfig c = fastConfig();
|
||||||
|
c.period = 0.0;
|
||||||
|
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||||
|
board.enter(Component::kGlobalPlanner, ComponentPhase::kWaitingForCostmap);
|
||||||
|
sleepMs(80);
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Watchdog, BusyWithoutProgressBecomesHungAndRecoversOnProgress)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
Watchdog dog;
|
||||||
|
std::string error;
|
||||||
|
WatchdogConfig c = fastConfig();
|
||||||
|
c.period = 0.0;
|
||||||
|
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||||
|
|
||||||
|
board.enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "just started";
|
||||||
|
|
||||||
|
sleepMs(30);
|
||||||
|
board.progress(Component::kGlobalPlanner); // vẫn nhích → không treo dù bận lâu
|
||||||
|
sleepMs(30);
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "busy but progressing";
|
||||||
|
|
||||||
|
sleepMs(80); // > 0.05 s không nhích
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_TRUE(dog.hung(Component::kGlobalPlanner));
|
||||||
|
EXPECT_TRUE(dog.anyHung());
|
||||||
|
EXPECT_NE(dog.report().find("global_planner"), std::string::npos);
|
||||||
|
|
||||||
|
board.progress(Component::kGlobalPlanner);
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "recovered";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Watchdog, StoppingCountsAsWatchedButPausedDoesNot)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
Watchdog dog;
|
||||||
|
std::string error;
|
||||||
|
WatchdogConfig c = fastConfig();
|
||||||
|
c.period = 0.0;
|
||||||
|
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||||
|
|
||||||
|
board.enter(Component::kRecovery, ComponentPhase::kStopping);
|
||||||
|
board.enter(Component::kAction, ComponentPhase::kPaused);
|
||||||
|
sleepMs(80);
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_TRUE(dog.hung(Component::kRecovery)) << "told to stop and never returned = hung";
|
||||||
|
EXPECT_FALSE(dog.hung(Component::kAction)) << "a paused handler is not expected to progress";
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Watchdog, ZeroBudgetDisablesThatRow)
|
||||||
|
{
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
Watchdog dog;
|
||||||
|
std::string error;
|
||||||
|
WatchdogConfig c = fastConfig();
|
||||||
|
c.period = 0.0;
|
||||||
|
c.action_stall_budget = 0.0;
|
||||||
|
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||||
|
|
||||||
|
board.enter(Component::kAction, ComponentPhase::kBusy);
|
||||||
|
sleepMs(80);
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_FALSE(dog.hung(Component::kAction));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Watchdog, ControlLoopHeartbeatStallIsDetectedFromTheWatchdogThread)
|
||||||
|
{
|
||||||
|
// Mô hình thật: control thread heartbeat cuối mỗi step(); ngừng heartbeat = treo. Watchdog chạy
|
||||||
|
// thread riêng và phải tự thấy — đây là thứ control thread không tự làm được.
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
Watchdog dog;
|
||||||
|
std::string error;
|
||||||
|
ASSERT_TRUE(dog.start(&board, fastConfig(), error)) << error;
|
||||||
|
ASSERT_TRUE(dog.running());
|
||||||
|
|
||||||
|
for (int i = 0; i < 5; ++i)
|
||||||
|
{
|
||||||
|
board.progress(Component::kControlLoop);
|
||||||
|
sleepMs(10);
|
||||||
|
}
|
||||||
|
EXPECT_FALSE(dog.controlLoopHung());
|
||||||
|
|
||||||
|
sleepMs(120); // không heartbeat
|
||||||
|
EXPECT_TRUE(dog.controlLoopHung());
|
||||||
|
|
||||||
|
board.progress(Component::kControlLoop);
|
||||||
|
sleepMs(40);
|
||||||
|
EXPECT_FALSE(dog.controlLoopHung());
|
||||||
|
|
||||||
|
dog.stop();
|
||||||
|
EXPECT_FALSE(dog.running());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Watchdog, RowThatNeverProgressedIsNotHung)
|
||||||
|
{
|
||||||
|
// Runtime mới lên: control loop chưa chạy cycle nào, last_progress = 0 — không được báo treo ngay.
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
Watchdog dog;
|
||||||
|
std::string error;
|
||||||
|
WatchdogConfig c = fastConfig();
|
||||||
|
c.period = 0.0;
|
||||||
|
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||||
|
sleepMs(80);
|
||||||
|
dog.checkOnce();
|
||||||
|
EXPECT_FALSE(dog.controlLoopHung());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Watchdog, StartRequiresABoardAndRefusesDoubleStart)
|
||||||
|
{
|
||||||
|
Watchdog dog;
|
||||||
|
std::string error;
|
||||||
|
EXPECT_FALSE(dog.start(nullptr, fastConfig(), error));
|
||||||
|
ComponentStatusBoard board;
|
||||||
|
ASSERT_TRUE(dog.start(&board, fastConfig(), error)) << error;
|
||||||
|
EXPECT_FALSE(dog.start(&board, fastConfig(), error)) << "already running";
|
||||||
|
dog.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char** argv)
|
||||||
|
{
|
||||||
|
::testing::InitGoogleTest(&argc, argv);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user