refactor: host EnvMonitor from env_monitor_core, route per detector
EnvMonitor and its detectors now live in env_monitor_core. NavigationRuntime owns the monitor; StateMachine runs each detector's own route (step or sequence, lock or abort on exhaustion) with a cursor per detector. RecoveryRunner accepts named routes for detectors outside the six built-in triggers.
This commit is contained in:
@@ -108,6 +108,9 @@ if(NOT BUILDING_WITH_CATKIN)
|
||||
action_core
|
||||
mission_adapters
|
||||
|
||||
# Lõi EnvMonitor. Nhánh standalone cần `add_subdirectory` của gói này ở pnkx_nav_core/CMakeLists.txt.
|
||||
env_monitor_core
|
||||
|
||||
# Kho cảm biến thô dùng chung. NavigationServer ghi vào, runner phát cổng đọc ra plugin.
|
||||
robot_sensor_ports
|
||||
|
||||
@@ -160,6 +163,9 @@ else()
|
||||
# ActionRunner include thẳng action_core: chỗ duy nhất trong gói này biết tới nó.
|
||||
action_core
|
||||
|
||||
# ControlLoop giữ EnvMonitor (lõi giám sát môi trường) và nối verdict vào state machine.
|
||||
env_monitor_core
|
||||
|
||||
# Kho cảm biến thô dùng chung. NavigationServer ghi vào, runner phát cổng đọc ra plugin.
|
||||
robot_sensor_ports
|
||||
|
||||
@@ -234,7 +240,6 @@ add_library(move_base2_core SHARED
|
||||
src/velocity_arbiter.cpp
|
||||
src/plan_inspector.cpp
|
||||
src/grid_analysis.cpp
|
||||
src/env_monitor.cpp
|
||||
src/control_loop.cpp
|
||||
src/config/move_base2_config.cpp
|
||||
src/runners/recovery_runner.cpp
|
||||
@@ -472,7 +477,6 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN AND CATKIN_ENABLE_TESTING)
|
||||
velocity_arbiter_test
|
||||
plan_inspector_test
|
||||
grid_analysis_test
|
||||
env_monitor_test
|
||||
walking_skeleton_test
|
||||
config_validation_test
|
||||
action_runner_test
|
||||
|
||||
@@ -77,6 +77,13 @@ cây nav core.
|
||||
cấu hình đang có hiệu lực sẽ nằm trong cây config của nav core, không nằm trong gói này — bản trong
|
||||
`test/` nếu có chỉ phục vụ test và phải chạy kèm biến môi trường trỏ vào đúng thư mục đó.
|
||||
|
||||
EnvMonitor (giám sát môi trường: contact / stall / unreachable) nằm ở gói riêng `env_monitor_core` từ 26/11/2026.
|
||||
`NavigationRuntime` gọi `EnvMonitor::initialize(root_nh)` và đưa con trỏ vào `ControlLoopDeps::env_monitor`;
|
||||
`ControlLoop` chỉ gom feature (`EnvironmentPort`), nối `fired_mask` vào state machine và áp
|
||||
`brake_applied`/`v_cap_applied`. Mỗi detector tự chọn route recovery (`route`, `route_mode: step|sequence`,
|
||||
`on_exhausted: lock|abort`); `ControlLoop::configure` dựng `StateMachineConfig::detector_routes` theo đúng thứ tự
|
||||
detector. Xem README của `env_monitor_core` và `Test/docs/move_base2/ENV_DETECTOR_PLUGINS_PROMPT.md`.
|
||||
|
||||
## Trạng thái
|
||||
|
||||
Runtime thật đã chạy trọn trên sim: costmap, planner/controller/recovery/action nạp qua boost::dll,
|
||||
|
||||
@@ -69,6 +69,19 @@ recovery:
|
||||
# `replan_budget`, stand-down); file này quyết định giơ cờ rồi thì LÀM GÌ (behavior nào, thứ tự,
|
||||
# bao nhiêu lượt). Muốn tắt một verdict thì đặt `action: log` bên kia, không xoá route bên này.
|
||||
#
|
||||
# ROUTE THEO DETECTOR (gói env_monitor_core, 26/11/2026): bảng trên là MẶC ĐỊNH. Mỗi detector của EnvMonitor tự
|
||||
# chọn route trong khối của nó ở `env_monitor_params.yaml`:
|
||||
# route: <tên> một khoá bất kỳ của `routes` dưới đây — sáu tên cũ hoặc tên mới (ví dụ `intrusion: [...]`).
|
||||
# Tên không có ở đây = detector bị GỠ lúc boot (log LỖI). Log ghi `trigger (detector)`,
|
||||
# route tên mới ghi `detector (<tên detector>)`.
|
||||
# route_mode: step mỗi lần nổ chạy MỘT behavior (cursor bên dưới) — như bảng trên.
|
||||
# sequence một lần nổ chạy LIỀN cả route; behavior hỏng hay nộp path giữa chừng vẫn chạy tiếp, path
|
||||
# mới nhất được áp khi xong; cả chuỗi tính MỘT lượt (lần nổ sau coi như cạn, trừ khi chuỗi
|
||||
# ra path mới và robot đã đi >= `recovery_reset_min_travel`).
|
||||
# on_exhausted: lock | abort cột "Cạn route thì..." ở trên, nay là khoá của detector chứ không của tên trigger.
|
||||
# Mỗi detector có cursor RIÊNG, kể cả khi hai detector trỏ cùng một route. `planning_failed`/`controlling_failed` không
|
||||
# do detector nào giơ nên luôn chạy kiểu step.
|
||||
#
|
||||
# HỢP ĐỒNG CHUNG cho mọi route (đọc một lần, áp cho cả sáu):
|
||||
#
|
||||
# - Cursor: lần lỗi kế tiếp CÙNG trigger mới tiến tới phần tử tiếp theo của route đó. Mỗi trigger
|
||||
|
||||
@@ -161,7 +161,9 @@ struct MoveBase2Config
|
||||
std::string docking_marker_profiles_error;
|
||||
|
||||
// --- EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — namespace con `env_monitor` ------------------------
|
||||
EnvMonitorConfig env_monitor; ///< lõi quyết định (stall / unreachable / contact / ngân sách).
|
||||
/// `env_monitor/enabled`. Lõi (phần chung + detector) do env_monitor_core::EnvMonitor::initialize() tự đọc; cờ này chỉ
|
||||
/// để biết có phải kiểm env_sampling / env_logger hay không.
|
||||
bool env_monitor_enabled = true;
|
||||
EnvSamplingConfig env_sampling; ///< lấy mẫu ở cổng (nhịp, thân, hình học, quỹ đạo).
|
||||
EnvLoggerConfig env_logger; ///< ghi JSONL cho replay/ML. Tắt mặc định.
|
||||
/// Nhóm log `debug/env`: một dòng tóm tắt feature mỗi giây khi đang giám sát. Mặc định bật.
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
#include <move_base2/core/navigation_request.h>
|
||||
#include <move_base2/core/state_machine.h>
|
||||
#include <move_base2/core/velocity_arbiter.h>
|
||||
#include <move_base2/core/env_monitor.h>
|
||||
#include <env_monitor_core/env_monitor.h>
|
||||
#include <move_base2/io/env_logger.h>
|
||||
#include <move_base2/ports/action_port.h>
|
||||
#include <move_base2/ports/clock_port.h>
|
||||
@@ -72,6 +72,12 @@ struct ControlLoopDeps
|
||||
*/
|
||||
EnvironmentPort* environment = nullptr;
|
||||
|
||||
/**
|
||||
* Lõi EnvMonitor (gói env_monitor_core), đã `initialize()` từ YAML bởi host (NavigationRuntime) — non-owning.
|
||||
* **Có thể null** — null, `enabled() == false` hoặc @ref environment null thì EnvMonitor tắt hoàn toàn.
|
||||
*/
|
||||
env_monitor_core::EnvMonitor* env_monitor = nullptr;
|
||||
|
||||
/**
|
||||
* Bảng trạng thái thành phần (2026-09-11). **Có thể null** — null thì quiescence của
|
||||
* CANCELLING/PAUSING chỉ dựa vào `PlannerPort::isPlanning()` và odom (hành vi pha 1a), recovery/
|
||||
@@ -163,7 +169,7 @@ struct ControlLoopConfig
|
||||
|
||||
|
||||
// --- EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 ----------
|
||||
EnvMonitorConfig env_monitor;
|
||||
// Tham số lõi (phần chung + từng detector) do env_monitor_core đọc từ YAML; ở đây chỉ phần lấy mẫu của host.
|
||||
EnvSamplingConfig env_sampling;
|
||||
EnvLoggerConfig env_logger;
|
||||
bool debug_env = true; ///< nhóm log `debug/env`: một dòng tóm tắt feature mỗi giây khi đang giám sát.
|
||||
@@ -390,6 +396,14 @@ private:
|
||||
* @brief EnvMonitor: lấy mẫu môi trường (nặng theo `check_period`, quỹ đạo mỗi cycle), chạy lõi, giữ
|
||||
* verdict cho state machine và trọng tài của CYCLE NÀY. Gọi trước state machine.
|
||||
*/
|
||||
/// Báo EnvMonitor (nếu có) một lượt recovery vừa kết thúc.
|
||||
void envRecoveryFinished(const robot::Time& now, env_monitor_core::EnvRecoveryOutcome outcome);
|
||||
|
||||
/// Nhãn trigger cho log: `collision (contact)`, `detector (intrusion)`; trigger riêng thì chỉ tên trigger.
|
||||
std::string triggerLabel(const StateMachineOutput& output) const;
|
||||
|
||||
/// Behavior đang chạy thuộc một chuỗi `route_mode: sequence` của detector.
|
||||
bool runningChain() const;
|
||||
void updateEnvMonitor(const robot::Time& now, double dt, const robot_geometry_msgs::PoseStamped& robot_pose,
|
||||
bool pose_available, bool costmap_stale);
|
||||
/// @brief Quaternion có chuẩn hoá được không — goal hỏng phải bị từ chối ngay tại cửa.
|
||||
@@ -420,7 +434,7 @@ private:
|
||||
/// Trigger của behavior đang chạy. `StateMachineOutput::recovery_trigger` chỉ được điền ở cycle khởi động
|
||||
/// (và khi trừ ngân sách), ở cycle tick nó là giá trị mặc định — đọc nó lúc kết thúc recovery là sai
|
||||
/// (stand-down của kContact không bao giờ được vũ trang, run 6/9 16:30: 4 detour collision cùng chỗ → ABORT).
|
||||
RecoveryTrigger running_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
int running_recovery_detector_ = -1; ///< detector (index detector_routes) có route đang chạy; -1 = trigger riêng
|
||||
ActionFeedback action_feedback_ = ActionFeedback::kIdle;
|
||||
|
||||
/// Lý do action handler đưa ra cho lần tick vừa rồi; chỉ giữ khi tick đó HỎNG, xem
|
||||
@@ -428,6 +442,8 @@ private:
|
||||
std::string action_message_;
|
||||
|
||||
std::vector<robot_geometry_msgs::PoseStamped> latest_plan_;
|
||||
/// Path mới nhất do một behavior trong chuỗi sequence nộp; áp khi cả chuỗi xong.
|
||||
std::vector<robot_geometry_msgs::PoseStamped> chain_path_;
|
||||
/// Tuyến tham chiếu của chặng — xem @ref orderPlan. Chỉ ghi từ kết quả của PlannerRunner.
|
||||
std::vector<robot_geometry_msgs::PoseStamped> order_plan_;
|
||||
bool planner_running_ = false;
|
||||
@@ -456,8 +472,7 @@ private:
|
||||
bool has_last_plan_applied_ = false;
|
||||
|
||||
// --- EnvMonitor -------------------------------------------------------------------------------
|
||||
EnvMonitor env_monitor_;
|
||||
EnvVerdict env_verdict_; ///< verdict của cycle này (vào state machine + trọng tài).
|
||||
env_monitor_core::EnvVerdict env_verdict_; ///< verdict của cycle này (vào state machine + trọng tài).
|
||||
EnvGeometry env_geometry_; ///< mẫu nặng gần nhất (giữ giữa hai tick 5 Hz để log/ghi).
|
||||
robot::Time last_env_heavy_;
|
||||
bool has_last_env_heavy_ = false;
|
||||
|
||||
@@ -1,408 +0,0 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — lõi quyết định của EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md §2.3, P2).
|
||||
*
|
||||
* Thuần: không costmap, không TF, không log, không cấp phát sau `configure`. Vào là một @ref EnvSample
|
||||
* mỗi control cycle (feature đã tính ở cổng bằng `grid_analysis`), ra là một @ref EnvVerdict: các cờ
|
||||
* cho state machine đúng như PathMonitor cũ (`no_progress`, `path_blocked`, `collision`), lệnh phanh và
|
||||
* bao tốc độ. Nhờ thuần nên kiểm được bằng bảng và replay được trên feature ghi lại.
|
||||
*
|
||||
* Triết lý (chốt 5/9/2026): local planner tự do né, recovery chỉ khi BẾ TẮC THẬT. Không có verdict
|
||||
* "plan bị chắn". Ba verdict:
|
||||
* - kStall — lệnh ≠ 0 mà `cost_to_go` (địa trắc tới điểm thoát + phần plan còn lại) không giảm.
|
||||
* - kUnreachable — không còn đường trong cửa sổ tới điểm thoát, tĩnh, và xấu hơn lúc nhận plan.
|
||||
* - kContact — thân sắp chạm trên quỹ đạo thật: phanh ngay, cờ chỉ khi tiếp xúc đứng yên.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef MOVE_BASE2_CORE_ENV_MONITOR_H_
|
||||
#define MOVE_BASE2_CORE_ENV_MONITOR_H_
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
|
||||
#include <robot/time.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
/**
|
||||
* @struct EnvMonitorConfig
|
||||
* @brief Tham số lõi. Đơn vị trong tên hoặc comment. Mọi ngưỡng số là GIÁ TRỊ KHỞI ĐIỂM rút từ hai bag
|
||||
* sim 5/9/2026 (Test/docs/move_base2/ENV_MONITOR_PLAN.md §4.4); chốt lại bằng shadow/replay, không bằng tay.
|
||||
*/
|
||||
struct EnvMonitorConfig
|
||||
{
|
||||
bool enabled = true;
|
||||
|
||||
/// [s] Sau khi nhận plan mới (planner hoặc detour) không kết luận gì: mẫu cũ thuộc plan cũ.
|
||||
double grace_after_new_plan = 1.0;
|
||||
|
||||
/// [m] Pose dời quá (đây + tốc độ lớn nhất trong khoảng mất pose nhân thời gian từ pose hợp lệ trước) = pose bị
|
||||
/// đặt lại. Cú dời không cộng vào odometer; cửa sổ kStall bắt đầu lại tối đa một lần mỗi cửa sổ vị trí dài nhất.
|
||||
/// Sim 6/11 20:34:34: AMCL "Setting pose" kéo pose lùi 1,2 m giữa lúc chạy thẳng 0,3 m/s -> quỹ đạo 20 s gấp đôi
|
||||
/// lên chính nó -> giam vùng nổ oan 8,65 s sau. 0 = tắt (cú dời được tính như quãng đi, như bản cũ).
|
||||
double pose_jump_reject = 0.5;
|
||||
|
||||
/**
|
||||
* kStall — "planner đòi đi mà cost_to_go không giảm". Đi cờ `no_progress` -> trigger oscillation
|
||||
* (trigger GỐC: cạn route là ABORT chặng), nên `action` mặc định "log" cho tới khi shadow đủ dài.
|
||||
*/
|
||||
struct Stall
|
||||
{
|
||||
bool enabled = true;
|
||||
std::string action = "log"; ///< "log" = chỉ báo trong verdict; "recover" = giơ cờ.
|
||||
double window_s = 4.0; ///< [s] cửa sổ đo eff.
|
||||
/// [m] Hai mẫu nặng liên tiếp mà cost_to_go đổi quá (đây + quãng robot dịch) = mặt nạ free đổi liên thông (ô
|
||||
/// nhấp nháy ở mép khe), không phải tiến/lùi: xoá cửa sổ đo, bắt đầu lại. Run 5/9 23:37: geo nhảy +3,2 m trong
|
||||
/// 0,2 s, eff −2,7, detour oan. 0 = tắt.
|
||||
double jump_reject = 1.0;
|
||||
/// Cổng DỊCH CHUYỂN THỰC (6/9): "bế tắc thật" = robot không đi được đâu, không phải "không tiến theo plan".
|
||||
/// Chỉ giơ cờ khi trong disp_window_s gần nhất robot dịch chuyển thực (khoảng cách đầu-cuối) < disp_min dù đã
|
||||
/// lệnh >= disp_min_commanded. Né tự do luôn dịch chuyển -> không nổ; quần trong hộp 0,9 m (run 5/9 00:05,
|
||||
/// 97 s) -> nổ sau ~window. Cửa sổ vị trí bắt đầu lại ở mỗi plan mới, thay cho ngân sách replan R3/R5 (đo
|
||||
/// theo quãng đường nên đi vòng đốt ngân sách rất chậm, câm cờ đúng 97 s). disp_min = 0 -> tắt cổng, dùng lại
|
||||
/// ngân sách replan như cũ.
|
||||
double disp_window_s = 12.0;
|
||||
double disp_min = 0.6; ///< [m]
|
||||
double disp_min_commanded = 1.5; ///< [m]
|
||||
/// [s] Cổng ĐỨNG YÊN: robot dịch chuyển thực < disp_min trong chừng này giây (không cần lệnh đủ) -> kẹt, kể cả
|
||||
/// khi geodesic không đo được. Run 6/9 10:59: PRIEST bò 0,03–0,15 m/s tại chỗ 30 s (blocked_ahead cost 253, res
|
||||
/// 1,6 chưa tới ngưỡng khai bất khả thi), lệnh tích luỹ 12 s chỉ 0,1–0,4 m nên cổng dịch chuyển câm; kUnreachable
|
||||
/// mới gỡ ở 75 s. Thử trên 7 lượt: bắt đúng 2 ca quần tại chỗ, 0 lần ở 3 lượt sạch. 0 = tắt.
|
||||
double idle_window_s = 25.0;
|
||||
/// Cổng GIAM VÙNG: trong confine_window_s mọi vị trí nằm trong vòng bán kính < confine_radius quanh tâm của chúng,
|
||||
/// và lệnh tích luỹ >= confine_cmd_factor x max(2 x bán kính đo được, disp_min) — đi nhiều mà không ra khỏi vùng
|
||||
/// nhỏ = loanh quanh trong local minimum. Cổng dịch chuyển đo đầu–cuối nên mù với vòng bán kính > 0,3 m; cổng
|
||||
/// đứng yên chỉ bắt gần như đứng. Replay 8 lượt 5–6/9: bắt 00:05 (101 s thay vì 206), 10:57 (27 s thay vì 75),
|
||||
/// 23:37; 0 lần ở 5 lượt sạch. Hệ số lệnh chặn ca bò thẳng chậm sau người (2 m/20 s: bán kính 1 m, lệnh 2 m
|
||||
/// < 1,5 x 2 m). confine_radius = 0 -> tắt. Chỉ hoạt động khi disp_min > 0.
|
||||
/// Cổng giam vùng KHÔNG nổ khi tiến độ đã được chứng minh: mọi eff đo được trong
|
||||
/// confine_window_s gần nhất đều >= eff_off, và eff gần nhất mới hơn window_s. Plan hợp lệ có vòng quay đầu (planner
|
||||
/// chỉ đi tiến) giữ robot trong vòng nhỏ mà cost_to_go vẫn giảm đều. Cổng đứng yên không bị phủ quyết.
|
||||
double confine_window_s = 20.0;
|
||||
double confine_radius = 1.2; ///< [m]
|
||||
double confine_cmd_factor = 1.5; ///< [-]
|
||||
/// Bật phủ quyết theo tiến độ cho cổng giam vùng (xem confine_window_s). false = giam vùng chỉ xét hình học.
|
||||
bool progress_veto = true;
|
||||
double window_m = 1.5; ///< [m] hoặc theo lệnh tích luỹ — cái tới trước.
|
||||
double min_commanded = 0.30; ///< [m] lệnh trong cửa sổ ít hơn = đang chờ, không đo.
|
||||
double eff_on = 0.20; ///< [-] eff dưới đây là kẹt.
|
||||
double eff_off = 0.50; ///< [-] trên đây mới xoá (hysteresis).
|
||||
double confirm = 1.0; ///< [s] kẹt liên tục chừng này mới nổ.
|
||||
double goal_zone = 0.6; ///< [m] gần goal hơn đây không đo.
|
||||
double slip_on = 0.15; ///< [m/s] |v_cmd| - |v_meas| liên tục = kẹt vật lý. 0 = tắt.
|
||||
double slip_time = 1.0; ///< [s]
|
||||
double min_commanded_since_goal = 1.0; ///< [m] cổng đầu chặng (cắt nổ sớm 13,0 / 145,6 bag 1).
|
||||
double retry_backoff = 3.0; ///< [s] sau một lượt recovery HỎNG không tích bằng chứng.
|
||||
} stall;
|
||||
|
||||
/// kUnreachable — cờ `path_blocked` -> route path_blocked (cạn route chỉ KHOÁ, an toàn để bật).
|
||||
struct Unreachable
|
||||
{
|
||||
bool enabled = true;
|
||||
std::string action = "recover";
|
||||
double static_on = 1.0; ///< [s] mất liên thông liên tục chừng này mới nổ.
|
||||
double clean_start_margin = 0.20; ///< [m] edt_body_min tối thiểu để còn gọi replan được.
|
||||
double retry_backoff = 2.0; ///< [s]
|
||||
} unreachable;
|
||||
|
||||
/// kContact — phanh theo quỹ đạo thật; cờ `collision` -> route collision.
|
||||
struct Contact
|
||||
{
|
||||
bool enabled = true;
|
||||
std::string action = "recover";
|
||||
int confirm_cycles = 2; ///< [cycle] chạm liên tục chừng này thì phanh.
|
||||
double trigger_static_time = 1.0; ///< [s] phanh mà tiếp xúc còn đó chừng này mới giơ cờ.
|
||||
double clean_start_margin = 0.20; ///< [m] dừng với thân còn cách vật ít nhất chừng này.
|
||||
double brake_decel = 0.35; ///< [m/s^2] decel dùng cho quãng phanh và bao tốc độ.
|
||||
double min_speed = 0.05; ///< [m/s] bao tốc độ không kẹp thấp hơn đây (thấp hơn = dừng).
|
||||
/// [m/s] |v_cmd| và |v_đo| đều dưới đây mà monitor CHƯA phanh = robot đang xoay tại chỗ hoặc bò: đó là
|
||||
/// chuyển động của controller, không phải bài toán quãng phanh -> không phanh, không cờ (cùng vai
|
||||
/// `path_monitor/collision_min_speed` cũ). Shadow 5/9: ba lần "braking to zero" ngay đầu chặng khi
|
||||
/// robot xoay ra khỏi vật kề mũi (v 0.00–0.07 m/s) đều là nổ oan kiểu này.
|
||||
double min_check_speed = 0.10;
|
||||
/// [m] Hysteresis cho "kề mũi": đã kề (d <= margin) thì còn kề tới khi d > margin + đây. Local planner
|
||||
/// đổi quỹ đạo mỗi cycle nên d nhảy 0,08 <-> 0,25 m quanh margin (run 5/9 22:35): không có nó thì phanh
|
||||
/// bật/nhả 4 lần/s và đồng hồ giơ cờ bị reset liên tục.
|
||||
double release_hysteresis = 0.10;
|
||||
/// [cycle] Nhả phanh (quỹ đạo sạch hoặc lùi xa) chỉ sau chừng này cycle liên tiếp không còn "sắp chạm".
|
||||
int release_confirm_cycles = 4;
|
||||
/// [m] Dư của bao tốc độ so với ngưỡng phanh: v_cap = sqrt(2a(d - margin - đây)), tối thiểu min_speed cho
|
||||
/// tới d <= margin (= 0). 0 = bao đặt đúng biên phanh -> cứ kẹp xong là chớm "sắp chạm" (rung tiếp cận run
|
||||
/// 5/9 22:58: 9/28 lần phanh < 0,3 s).
|
||||
double envelope_margin = 0.10;
|
||||
/// [m] Detour do CHÍNH cờ collision vừa xong mà robot dịch chưa tới đây và lại "sắp chạm" -> kContact ĐỨNG RA
|
||||
/// (không phanh, không cờ, không bao) tới khi đi được standdown_travel hoặc quỹ đạo sạch: detour từ trong khe
|
||||
/// là vô nghĩa, xoay là chạm (m1/m8 run 5/9 22:58 churn 3 detour rồi ABORT); mission 6 cùng lượt thoát được
|
||||
/// đúng lúc guard "nhường controller". 0 = tắt.
|
||||
double standdown_min_travel = 0.10;
|
||||
double standdown_travel = 0.30; ///< [m] đứng ra chừng này quãng đường rồi vũ trang lại.
|
||||
bool envelope = true; ///< bật bao tốc độ theo tiếp xúc trên quỹ đạo.
|
||||
/// false = SHADOW: `brake`/`v_cap` chỉ được báo trong verdict, ControlLoop không đụng lệnh.
|
||||
/// true = phanh và bao tốc độ tác động thật lên lệnh trước trọng tài. Lõi không dùng cờ này.
|
||||
bool apply_command = false;
|
||||
} contact;
|
||||
|
||||
/// Ngân sách replan theo quãng đường (R3 + R5) cho kStall và kUnreachable.
|
||||
struct ReplanBudget
|
||||
{
|
||||
double min_travel = 1.5; ///< [m] sau detour thành công, im tới khi đi chừng này.
|
||||
double escalate_factor = 2.0; ///< [-] replan lặp trong escalate_window_m thì nhân ngân sách.
|
||||
double escalate_window_m = 10.0; ///< [m] đi chừng này không replan thì về min_travel.
|
||||
/// [m] Trần của leo thang; 0 = không trần. Run 5/9 22:35: 4 detour PRIEST trong 10 m -> 1,5 -> 3 -> 6 -> 12 m,
|
||||
/// kStall câm gần hết chặng.
|
||||
double escalate_max = 6.0;
|
||||
} replan;
|
||||
|
||||
bool validate(std::string& error) const;
|
||||
std::string describe() const;
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct EnvSample
|
||||
* @brief Dữ liệu vào của một cycle. Phần "nặng" chỉ có nghĩa khi @ref geometry_valid (nhịp 5 Hz).
|
||||
* NaN / +inf = không có; lõi không suy diễn từ giá trị thiếu.
|
||||
*/
|
||||
struct EnvSample
|
||||
{
|
||||
robot::Time now;
|
||||
double dt = 0.0; ///< [s] từ cycle trước; 0 ở cycle đầu.
|
||||
bool costmap_current = true; ///< costmap stale -> mọi kết luận hình học là quá khứ.
|
||||
bool has_plan = false;
|
||||
/// [m] pose robot, frame bất kỳ nhưng cố định (đo quãng đường). NaN = không có pose cycle này. Frame `map` nhảy
|
||||
/// khi localization đặt lại pose: lõi tự nhận ra cú nhảy (EnvMonitorConfig::pose_jump_reject).
|
||||
double robot_x = 0.0;
|
||||
double robot_y = 0.0;
|
||||
double v_cmd = 0.0; ///< [m/s] lệnh SAU trọng tài của cycle trước.
|
||||
double w_cmd = 0.0; ///< [rad/s]
|
||||
double v_meas = std::numeric_limits<double>::quiet_NaN(); ///< [m/s] đo được; NaN = không có.
|
||||
/// [m/s] lệnh controller MUỐN ở cycle trước, TRƯỚC bao tốc độ / phanh / trọng tài; NaN = không biết.
|
||||
/// Cần cho cổng xoay của kContact: bao kẹp lệnh về 0 trong margin làm v_cmd = 0 dù controller vẫn đòi
|
||||
/// đi — không có số này, cổng xoay coi đó là "đứng yên" và robot dừng câm không cờ.
|
||||
double v_controller = std::numeric_limits<double>::quiet_NaN();
|
||||
bool controller_valid = true; ///< controller cycle trước có ra lệnh không.
|
||||
double d_goal = std::numeric_limits<double>::infinity(); ///< [m] Euclid tới goal.
|
||||
|
||||
bool geometry_valid = false; ///< các trường dưới đây vừa được tính ở tick này.
|
||||
bool cost_conclusive = false; ///< costToGo kết luận được.
|
||||
bool reachable = false; ///< có đường địa trắc tới T.
|
||||
double cost_to_go = std::numeric_limits<double>::infinity(); ///< [m]
|
||||
double edt_body_min = std::numeric_limits<double>::quiet_NaN(); ///< [m]
|
||||
|
||||
bool contact_conclusive = false; ///< sweep quỹ đạo kết luận được (mỗi cycle).
|
||||
double traj_contact_dist = std::numeric_limits<double>::infinity(); ///< [m] dọc quỹ đạo.
|
||||
};
|
||||
|
||||
/// Kết quả một lượt recovery mà lõi cần biết (không include recovery_core: chỉ ba ý nghĩa).
|
||||
enum class EnvRecoveryOutcome
|
||||
{
|
||||
kSucceededWithPath, ///< detour_path nộp path mới -> ngân sách theo quãng đường.
|
||||
kSucceeded, ///< behavior khác thành công (không đổi plan).
|
||||
kFailed ///< hỏng -> retry_backoff.
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct EnvVerdict
|
||||
* @brief Kết quả một cycle. Cờ đầu là cái đưa vào `StateMachineInput` (đã qua action + cổng +
|
||||
* ngân sách); phần chẩn đoán là số thô để log / ghi JSONL.
|
||||
*/
|
||||
struct EnvVerdict
|
||||
{
|
||||
bool no_progress = false; ///< kStall hiệu lực.
|
||||
bool path_blocked = false; ///< kUnreachable hiệu lực.
|
||||
bool collision = false; ///< kContact hiệu lực (cờ, không phải phanh).
|
||||
bool brake = false; ///< Cycle này lệnh ra phải bằng 0.
|
||||
double v_cap = std::numeric_limits<double>::infinity(); ///< [m/s] trần |v| cycle này; +inf = không kẹp.
|
||||
|
||||
bool stall_detected = false; ///< điều kiện kẹt đã đủ confirm, chưa xét action/cổng.
|
||||
bool unreachable_detected = false;
|
||||
bool contact_imminent = false; ///< chạm trong quãng phanh ở cycle này.
|
||||
bool contact_standdown = false; ///< kContact đang đứng ra sau detour từ chính chỗ này (nhường controller).
|
||||
bool cost_jump = false; ///< tick này cost_to_go nhảy quá jump_reject: cửa sổ stall vừa bị xoá.
|
||||
bool pose_jump = false; ///< cycle này pose dời quá ngưỡng có tính đến quãng có thể đi.
|
||||
bool pose_jump_restart = false; ///< cú nhảy này thực sự xoá các cửa sổ stall.
|
||||
double pose_jump_dist = std::numeric_limits<double>::quiet_NaN(); ///< [m] độ dời của cú nhảy đó (NaN = không nhảy).
|
||||
bool progress_proven = false; ///< bằng chứng eff còn hiệu lực: có thể phủ quyết cổng giam vùng.
|
||||
bool stall_muted = false; ///< detected nhưng bị cổng/ngân sách/backoff/grace giữ lại.
|
||||
double net_disp = std::numeric_limits<double>::quiet_NaN(); ///< [m] dịch chuyển thực trong disp_window_s (NaN = chưa đủ mẫu).
|
||||
bool wandering = false; ///< cổng dịch chuyển đã mở: lệnh đủ mà không đi được đâu.
|
||||
bool idle = false; ///< cổng đứng yên đã mở: không dịch chuyển suốt idle_window_s.
|
||||
bool confined = false; ///< cổng giam vùng đã mở: đi nhiều mà ở trong vòng nhỏ suốt confine_window_s.
|
||||
double region_radius = std::numeric_limits<double>::quiet_NaN(); ///< [m] bán kính vùng đã ở trong confine_window_s.
|
||||
bool unreachable_muted = false;
|
||||
double eff_geo = std::numeric_limits<double>::quiet_NaN(); ///< [-] eff của cửa sổ gần nhất.
|
||||
double cmd_window = 0.0; ///< [m] lệnh tích luỹ trong cửa sổ đó.
|
||||
double brake_dist = 0.0; ///< [m]
|
||||
double replan_budget_left = 0.0; ///< [m] còn phải đi bao xa mới hết mute sau replan (0 = không mute).
|
||||
const char* event = ""; ///< Sườn sự kiện của cycle này ("" = không có). Dùng để log một lần.
|
||||
};
|
||||
|
||||
/**
|
||||
* @class EnvMonitor
|
||||
* @brief Lõi thuần. Không thread-safe; chỉ control thread gọi.
|
||||
*/
|
||||
class EnvMonitor
|
||||
{
|
||||
public:
|
||||
EnvMonitor() = default;
|
||||
|
||||
bool configure(const EnvMonitorConfig& config, std::string& error);
|
||||
bool configured() const
|
||||
{
|
||||
return configured_;
|
||||
}
|
||||
const EnvMonitorConfig& config() const
|
||||
{
|
||||
return config_;
|
||||
}
|
||||
|
||||
/// @brief Về trạng thái ban đầu (rời kControlling, huỷ chặng). Giữ config.
|
||||
void reset();
|
||||
|
||||
/// @brief Chặng mới được nhận: đặt lại mọi ngân sách, mốc lệnh đầu chặng.
|
||||
void onGoalAccepted(const robot::Time& now);
|
||||
|
||||
/// @brief Plan mới được áp (planner hay detour): xoá cửa sổ, bắt đầu grace, chờ baseline liên thông.
|
||||
void onPlanApplied(const robot::Time& now);
|
||||
|
||||
/// @brief Một lượt recovery vừa kết thúc (trước khi plan mới, nếu có, được áp).
|
||||
/// @param from_contact recovery này do cờ collision của chính monitor gọi (trigger kCollision).
|
||||
void onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome, bool from_contact = false);
|
||||
|
||||
/// @brief Một cycle. Gọi SAU khi các feature của cycle đã có, TRƯỚC state machine.
|
||||
EnvVerdict update(const EnvSample& sample);
|
||||
|
||||
// --- soi trạng thái (test, log) ---
|
||||
double commandedTotal() const
|
||||
{
|
||||
return cmd_accum_;
|
||||
}
|
||||
double travelledTotal() const
|
||||
{
|
||||
return travel_total_;
|
||||
}
|
||||
double replanBudget() const
|
||||
{
|
||||
return budget_travel_;
|
||||
}
|
||||
|
||||
private:
|
||||
struct HeavySample
|
||||
{
|
||||
robot::Time t;
|
||||
double cost = 0.0; ///< [m]
|
||||
double cmd = 0.0; ///< [m] cmd_accum_ lúc lấy mẫu.
|
||||
};
|
||||
/// 64 mẫu x 0,2 s = 12,8 s lịch sử, dư cho window_s 4 s kể cả khi nhịp nặng chậm lại.
|
||||
static constexpr std::size_t kRing = 64;
|
||||
struct PosSample
|
||||
{
|
||||
robot::Time t;
|
||||
double x = 0.0;
|
||||
double y = 0.0;
|
||||
double cmd = 0.0; ///< [m] cmd_accum_ lúc lấy mẫu.
|
||||
};
|
||||
/// 128 mẫu x 0,2 s = 25,6 s, dư cho disp_window_s 12 s.
|
||||
static constexpr std::size_t kPosRing = 192; ///< 192 x 0,2 s = 38 s, đủ idle_window_s 25 s.
|
||||
bool oldestPos(const robot::Time& now, double window_s, PosSample& out) const;
|
||||
|
||||
void clearWindow();
|
||||
void clearPosWindow();
|
||||
bool oldestInWindow(const robot::Time& now, HeavySample& out) const;
|
||||
/// Tiến độ đã chứng minh: có eff >= eff_off trong window_s gần nhất và không có eff < eff_off nào trong
|
||||
/// confine_window_s gần nhất (xem Stall::confine_window_s).
|
||||
bool progressProven(const robot::Time& now) const;
|
||||
void updateStall(const EnvSample& s, EnvVerdict& v);
|
||||
void updateUnreachable(const EnvSample& s, EnvVerdict& v);
|
||||
void updateContact(const EnvSample& s, EnvVerdict& v);
|
||||
|
||||
EnvMonitorConfig config_;
|
||||
bool configured_ = false;
|
||||
|
||||
// Tích luỹ
|
||||
double cmd_accum_ = 0.0; ///< [m] Σ|v_cmd|·dt
|
||||
double travel_total_ = 0.0; ///< [m] odometer từ pose
|
||||
double jump_dist_total_ = 0.0; ///< [m] tổng độ dời pose bị loại, chỉ dùng cho bộ lọc cost jump.
|
||||
bool has_last_pose_ = false;
|
||||
double last_x_ = 0.0;
|
||||
double last_y_ = 0.0;
|
||||
robot::Time last_pose_t_;
|
||||
double v_gap_max_ = 0.0; ///< [m/s] tốc độ lớn nhất từ pose hữu hạn gần nhất.
|
||||
bool has_pose_jump_restart_ = false;
|
||||
robot::Time pose_jump_restart_t_;
|
||||
|
||||
// Mốc chặng / plan
|
||||
bool has_goal_ = false;
|
||||
double cmd_at_goal_ = 0.0;
|
||||
bool has_plan_time_ = false;
|
||||
robot::Time plan_time_;
|
||||
|
||||
// Cửa sổ mẫu nặng
|
||||
std::array<HeavySample, kRing> ring_{};
|
||||
std::size_t ring_head_ = 0;
|
||||
std::size_t ring_count_ = 0;
|
||||
std::array<PosSample, kPosRing> pos_ring_{};
|
||||
std::size_t pos_head_ = 0;
|
||||
std::size_t pos_count_ = 0;
|
||||
bool wandering_ = false;
|
||||
bool idle_ = false; ///< cổng đứng yên đang mở (xem Stall::idle_window_s).
|
||||
bool confined_ = false; ///< cổng giam vùng đang mở (xem Stall::confine_radius).
|
||||
double region_radius_ = std::numeric_limits<double>::quiet_NaN();
|
||||
double net_disp_ = std::numeric_limits<double>::quiet_NaN();
|
||||
// Lịch sử eff cho progressProven(): mốc thời gian của mẫu eff tốt/thấp gần nhất. Xoá cùng cửa sổ vị trí.
|
||||
bool has_eff_ok_ = false;
|
||||
robot::Time eff_ok_t_;
|
||||
bool has_eff_low_ = false;
|
||||
robot::Time eff_low_t_;
|
||||
|
||||
// kStall
|
||||
bool stall_seen_ = false;
|
||||
robot::Time stall_since_;
|
||||
bool stall_fired_ = false;
|
||||
bool slip_seen_ = false;
|
||||
robot::Time slip_since_;
|
||||
bool has_stall_backoff_ = false;
|
||||
robot::Time stall_backoff_until_;
|
||||
|
||||
// kUnreachable
|
||||
bool baseline_pending_ = true; ///< chưa có mẫu kết luận nào từ plan hiện tại.
|
||||
bool baseline_unreachable_ = false; ///< plan đã không liên thông ngay từ lúc nhận (R2: không cãi SBPL).
|
||||
bool unreach_seen_ = false;
|
||||
robot::Time unreach_since_;
|
||||
bool unreach_fired_ = false;
|
||||
bool has_unreach_backoff_ = false;
|
||||
robot::Time unreach_backoff_until_;
|
||||
|
||||
// kContact
|
||||
int contact_streak_ = 0;
|
||||
int release_streak_ = 0; ///< cycle liên tiếp không "sắp chạm" trong khi đang phanh.
|
||||
bool has_prev_heavy_ = false; ///< mẫu nặng trước cho bộ lọc nhảy cost_to_go.
|
||||
double prev_heavy_cost_ = 0.0;
|
||||
double prev_heavy_travel_ = 0.0;
|
||||
double prev_heavy_jump_dist_ = 0.0;
|
||||
bool braking_ = false;
|
||||
bool contact_close_ = false; ///< tiếp xúc trong clean_start_margin (bất kể tốc độ).
|
||||
robot::Time close_since_;
|
||||
bool contact_fired_ = false;
|
||||
bool detour_from_contact_ = false; ///< detour gần nhất là do cờ collision; mốc quãng đường ở dưới.
|
||||
double detour_mark_travel_ = 0.0; ///< [m]
|
||||
bool standdown_ = false; ///< đang đứng ra (xem Contact::standdown_min_travel).
|
||||
double standdown_mark_travel_ = 0.0; ///< [m]
|
||||
int standdown_clean_streak_ = 0; ///< cycle quỹ đạo sạch liên tiếp trong khi đứng ra.
|
||||
|
||||
// Ngân sách replan (R3/R5)
|
||||
bool has_replan_mark_ = false;
|
||||
double replan_mark_travel_ = 0.0; ///< odometer tại lần detour thành công gần nhất.
|
||||
double budget_travel_ = 0.0; ///< [m] ngân sách hiện hành (= min_travel, nhân factor khi lặp).
|
||||
bool has_prev_replan_ = false;
|
||||
double prev_replan_travel_ = 0.0;
|
||||
};
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
#endif // MOVE_BASE2_CORE_ENV_MONITOR_H_
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
#include <robot/time.h>
|
||||
@@ -61,6 +62,19 @@ enum class ActionFeedback
|
||||
kCancelled ///< Handler đã dừng thiết bị an toàn sau cancel (pha 3). Chỉ gặp trong CANCELLING/PAUSING.
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct DetectorRoute
|
||||
* @brief Route recovery của một detector EnvMonitor (Test/docs/move_base2/ENV_DETECTOR_PLUGINS_PROMPT.md §4).
|
||||
*/
|
||||
struct DetectorRoute
|
||||
{
|
||||
std::string name; ///< tên detector: log, và báo lại EnvMonitor route của ai vừa chạy xong.
|
||||
std::vector<std::size_t> route; ///< index behavior trong registry. Rỗng = cờ không được vũ trang.
|
||||
bool lock_on_exhausted = true; ///< cạn route: true = khoá, bám tiếp plan (dự báo); false = ABORT chặng.
|
||||
bool sequence = false; ///< `route_mode: sequence` — một lần nổ chạy cả route.
|
||||
RecoveryTrigger trigger = RecoveryTrigger::kDetector; ///< nhãn cho log và recovery_core (tên route cũ -> trigger cũ).
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct StateMachineConfig
|
||||
* @brief Tham số điều khiển hành vi chuyển state.
|
||||
@@ -150,6 +164,10 @@ struct StateMachineConfig
|
||||
/// Route đã resolve của từng @ref RecoveryTrigger. Rỗng = mọi trigger dùng list legacy chung.
|
||||
RecoveryRoutes recovery_routes;
|
||||
|
||||
/// Một route cho MỖI detector EnvMonitor, đúng thứ tự detector (bit i của StateMachineInput::detector_fired).
|
||||
/// Tối đa 32. Rỗng = không detector nào leo thang được recovery.
|
||||
std::vector<DetectorRoute> detector_routes;
|
||||
|
||||
/**
|
||||
* @brief Kiểm miền giá trị.
|
||||
* @param[out] error Mô tả tham số sai; chỉ được ghi khi hàm trả false.
|
||||
@@ -254,28 +272,15 @@ struct StateMachineInput
|
||||
bool action_terminal = true;
|
||||
|
||||
/**
|
||||
* Tuyến phía trước bị chắn (EnvMonitor kUnreachable: không còn đường trong cửa sổ tới điểm thoát, đã
|
||||
* tĩnh đủ `static_on`).
|
||||
* Bit i = detector thứ i của @ref StateMachineConfig::detector_routes (thứ tự `env_monitor/detectors`) đòi
|
||||
* recovery cycle này. Thay cho bốn cờ cố định cũ (`collision`, `path_blocked`, `off_path`, `no_progress`).
|
||||
*
|
||||
* Khác mọi cờ khác trong struct này: nó là **dự báo**, không phải báo hỏng. Controller vẫn ra
|
||||
* lệnh bình thường, plan vẫn hợp lệ — chỉ là đi tiếp thì sẽ tắc. Bên gọi chịu trách nhiệm mọi
|
||||
* guard (profile, costmap còn hạn, debounce, route có tồn tại không); state machine chỉ tin cờ.
|
||||
* Detector `on_exhausted: lock` là **dự báo**: controller vẫn ra lệnh, plan vẫn hợp lệ — xét TRƯỚC controller,
|
||||
* theo thứ tự danh sách (mặc định contact > unreachable, như collision > path_blocked cũ); cạn route thì khoá
|
||||
* tới khi robot đi được `oscillation_distance`. Detector `abort` (stall) chỉ xét khi controller ra lệnh hợp lệ;
|
||||
* cạn route là ABORT. Bên gọi chịu debounce/mode/profile; state machine chỉ tin bit.
|
||||
*/
|
||||
bool path_blocked = false;
|
||||
|
||||
/// Robot đã lệch khỏi plan đang chạy quá ngưỡng. Cùng quy ước với @ref path_blocked. Từ 6/9/2026 không
|
||||
/// còn nguồn cấp (phép đo 2 của PathMonitor cũ đã xoá); giữ cổng cho hợp đồng route/khoá và test.
|
||||
bool off_path = false;
|
||||
|
||||
/// EnvMonitor kContact: thân sắp chạm vật cản thật trên quỹ đạo local planner, kề mũi tĩnh đủ lâu.
|
||||
/// Cùng quy ước với @ref path_blocked (dự báo, route riêng `collision`, cạn route thì khoá).
|
||||
/// Thắng cả path_blocked lẫn off_path khi cùng đúng: gần nhất thì xử lý trước.
|
||||
bool collision = false;
|
||||
|
||||
/// EnvMonitor kStall: planner đòi đi mà robot không đi được đâu (cổng dịch chuyển thực mở).
|
||||
/// Đi đường kOscillation — trigger GỐC — nên cạn route là ABORT hợp lệ, không rơi vào bẫy trigger
|
||||
/// giám sát bị khoá rồi đứng im. Bên gọi chịu debounce/route/mode; state machine chỉ tin cờ.
|
||||
bool no_progress = false;
|
||||
std::uint32_t detector_fired = 0;
|
||||
|
||||
/**
|
||||
* Họ output của behavior sẽ chạy / đang chạy ở cycle này.
|
||||
@@ -331,6 +336,16 @@ struct StateMachineOutput
|
||||
/// Chỉ có nghĩa khi @ref start_recovery — behavior nào cần khởi động và vì lý do gì.
|
||||
std::size_t recovery_index = 0;
|
||||
RecoveryTrigger recovery_trigger = RecoveryTrigger::kPlanningFailed;
|
||||
/// Index trong StateMachineConfig::detector_routes của detector có route vừa khởi động / bị khoá; -1 = trigger
|
||||
/// riêng của state machine (planning_failed, controlling_failed, oscillation_timeout).
|
||||
int recovery_detector = -1;
|
||||
|
||||
/// `route_mode: sequence`: behavior vừa start là phần TIẾP của chuỗi đang chạy (không phải một lượt mới).
|
||||
bool recovery_chain_continues = false;
|
||||
/// Chuỗi sequence vừa chạy xong ở cycle này (không bị huỷ); ba cờ dưới là kết cục của CẢ chuỗi.
|
||||
bool recovery_chain_finished = false;
|
||||
bool recovery_chain_has_path = false; ///< ít nhất một behavior trong chuỗi nộp path mới.
|
||||
bool recovery_chain_last_failed = false; ///< behavior cuối của chuỗi trả kFailed.
|
||||
|
||||
/**
|
||||
* Debug route recovery tại cycle này. Có nghĩa khi @ref start_recovery hoặc khi terminal reason là
|
||||
@@ -460,17 +475,21 @@ private:
|
||||
|
||||
/**
|
||||
* @brief Vào recovery nếu còn behavior, ngược lại kết thúc bằng kAborted.
|
||||
* @param trigger Lý do vào recovery.
|
||||
* @param trigger Trigger riêng của state machine (planning_failed, controlling_failed, oscillation).
|
||||
*/
|
||||
/// @brief Trigger này thuộc nhóm GIÁM SÁT TUYẾN (dự báo) chứ không phải báo hỏng?
|
||||
static bool isMonitorTrigger(RecoveryTrigger trigger);
|
||||
|
||||
/// @brief Khoá một trigger giám sát tuyến tới khi có tiến độ; báo cho bên gọi log một dòng.
|
||||
void suppressMonitorTrigger(RecoveryTrigger trigger, StateMachineOutput& out);
|
||||
|
||||
void escalateToRecovery(RecoveryTrigger trigger, const robot::Time& now, const char* reason,
|
||||
StateMachineOutput& out);
|
||||
|
||||
/// @brief Leo thang bằng route của detector @p index (StateMachineConfig::detector_routes).
|
||||
void escalateDetector(std::size_t index, const robot::Time& now, StateMachineOutput& out);
|
||||
|
||||
/// @brief Chung cho hai đường trên: cursor ô @p slot; cạn route thì khoá ô (@p lock, dự báo) hoặc ABORT.
|
||||
void escalate(std::size_t slot, const std::vector<std::size_t>& route, RecoveryTrigger trigger, bool lock,
|
||||
int detector, const robot::Time& now, const char* reason, StateMachineOutput& out);
|
||||
|
||||
/// @brief Route của lượt recovery đang chạy.
|
||||
const std::vector<std::size_t>& activeRoute() const;
|
||||
|
||||
/// @brief Vào state terminal và bật cờ báo kết quả đúng một lần.
|
||||
/**
|
||||
* @brief Nhận yêu cầu đang chờ và đưa máy vào state chạy tương ứng.
|
||||
@@ -514,10 +533,6 @@ private:
|
||||
/// Mọi đường ra của @ref update đều phải đi qua đây.
|
||||
void applyInvariants(const StateMachineInput& in, StateMachineOutput& out);
|
||||
|
||||
/// Cursor của route cho @p trigger trong request hiện hành.
|
||||
std::size_t& recoveryRouteCursor(RecoveryTrigger trigger);
|
||||
const std::size_t& recoveryRouteCursor(RecoveryTrigger trigger) const;
|
||||
|
||||
StateMachineConfig config_;
|
||||
bool initialized_ = false;
|
||||
|
||||
@@ -552,13 +567,19 @@ private:
|
||||
*/
|
||||
NavigationState state_before_recovery_ = NavigationState::kPlanning;
|
||||
|
||||
/// Một cursor cho MỖI trigger: mỗi nguyên nhân có ngân sách recovery riêng. Thứ tự khớp
|
||||
/// @ref RecoveryTrigger.
|
||||
std::array<std::size_t, 6> recovery_route_cursors_{{ 0, 0, 0, 0, 0, 0 }};
|
||||
/// Một cursor cho MỖI nguyên nhân: mỗi nguyên nhân có ngân sách recovery riêng. Ô 0..2 = planning_failed,
|
||||
/// controlling_failed, oscillation (trigger riêng của state machine); ô 3 + i = detector i.
|
||||
std::vector<std::size_t> recovery_route_cursors_;
|
||||
/// Ô của lượt recovery đang chạy (cùng đánh số với @ref recovery_route_cursors_).
|
||||
std::size_t active_slot_ = 0;
|
||||
/// Lượt recovery đang chạy là một chuỗi `route_mode: sequence`: vị trí trong route, và đã có path mới chưa.
|
||||
bool chain_active_ = false;
|
||||
std::size_t chain_pos_ = 0;
|
||||
bool chain_has_path_ = false;
|
||||
|
||||
/**
|
||||
* Trigger GIÁM SÁT TUYẾN đang bị khoá (contract 2026-08-05e). Cùng thứ tự với
|
||||
* @ref recovery_route_cursors_; chỉ ba ô kPathBlocked/kOffPath/kCollision từng được bật.
|
||||
* @ref recovery_route_cursors_; chỉ ô của detector `on_exhausted: lock` từng được bật.
|
||||
*
|
||||
* `path_blocked`/`off_path` là DỰ BÁO, không phải báo hỏng: plan vẫn hợp lệ và controller vẫn ra
|
||||
* lệnh được. Hết đường vòng thì robot BÁM TIẾP plan cũ chứ không ABORT — lưới an toàn thật là
|
||||
@@ -566,7 +587,7 @@ private:
|
||||
* lại để monitor không bắn liên tục: mỗi lượt detour tốn vài trăm ms SBPL trên control thread.
|
||||
* Mở khoá khi robot đi được quá `oscillation_distance` — cùng mốc tiến độ đã reset cursor (Q1-C).
|
||||
*/
|
||||
std::array<bool, 6> monitor_trigger_suppressed_{{ false, false, false, false, false, false }};
|
||||
std::vector<char> monitor_trigger_suppressed_;
|
||||
|
||||
/**
|
||||
* Mốc của `recovery_reset_min_travel`, ghi khi recovery có path mới được nạp lại ngân sách. Xoá
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
#include <robot/time.h>
|
||||
|
||||
#include <move_base2/core/env_monitor.h>
|
||||
#include <env_monitor_core/env_monitor.h>
|
||||
#include <move_base2/ports/environment_port.h>
|
||||
|
||||
namespace move_base2
|
||||
@@ -57,7 +57,7 @@ public:
|
||||
}
|
||||
|
||||
/// @brief Một dòng JSON. @p geometry có thể null (tick nhẹ). @p state là tên state machine.
|
||||
void record(const robot::Time& now, const EnvSample& sample, const EnvVerdict& verdict,
|
||||
void record(const robot::Time& now, const env_monitor_core::EnvSample& sample, const env_monitor_core::EnvVerdict& verdict,
|
||||
const EnvGeometry* geometry, const char* state, std::uint64_t mission_id,
|
||||
bool used_local_plan);
|
||||
|
||||
|
||||
@@ -396,6 +396,8 @@ private:
|
||||
PlannerRunner planner_;
|
||||
ControllerRunner controller_;
|
||||
RecoveryRunner recovery_;
|
||||
/// Lõi EnvMonitor + detector plugin, nạp từ YAML ở @ref buildRunners. ControlLoop giữ con trỏ (non-owning).
|
||||
env_monitor_core::EnvMonitor env_monitor_;
|
||||
ActionRunner action_;
|
||||
MissionAdapterBridge mission_;
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
@@ -42,7 +44,10 @@ enum class RecoveryTrigger
|
||||
/// local planner, trong `collision_stop_distance`. Cùng họ dự báo với kPathBlocked nhưng là một
|
||||
/// ngăn riêng: nổ khi đã sát vật (0.2 m) chứ không phải 3 m trước, nên cách xử lý (lùi trước
|
||||
/// khi lập lại đường) và ngân sách route phải tách khỏi kPathBlocked.
|
||||
kCollision
|
||||
kCollision,
|
||||
/// Route của một detector EnvMonitor có tên route không thuộc bốn tên cũ ở trên (ví dụ `intrusion`). Detector dùng
|
||||
/// tên cũ (`oscillation`, `path_blocked`, `off_path`, `collision`) vẫn báo trigger cũ để log không đổi.
|
||||
kDetector
|
||||
};
|
||||
|
||||
const char* toString(RecoveryTrigger trigger);
|
||||
@@ -72,10 +77,19 @@ struct RecoveryRoutes
|
||||
/// Route của kCollision (Phép đo 3). Rỗng = guard va chạm KHÔNG được vũ trang (cùng quy ước).
|
||||
std::vector<std::size_t> collision;
|
||||
|
||||
/// Route khai thêm trong `recovery/routes` ngoài sáu tên trên (route theo detector, ví dụ `intrusion`).
|
||||
std::map<std::string, std::vector<std::size_t>> named;
|
||||
|
||||
const std::vector<std::size_t>& forTrigger(RecoveryTrigger trigger) const;
|
||||
|
||||
/// @brief Route theo tên: sáu tên cố định hoặc @ref named. nullptr = không có route tên đó.
|
||||
const std::vector<std::size_t>* find(const std::string& name) const;
|
||||
|
||||
/// @brief Ba route GỐC đều rỗng — dấu hiệu config dùng schema legacy (không có khoá `routes`).
|
||||
bool empty() const;
|
||||
|
||||
/// @brief Schema legacy (@ref empty): ba route gốc thử toàn bộ @p behavior_count behavior theo thứ tự registry.
|
||||
void fillLegacy(std::size_t behavior_count);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -86,6 +86,10 @@
|
||||
<build_depend>action_core</build_depend>
|
||||
<run_depend>action_core</run_depend>
|
||||
|
||||
<!-- Lõi EnvMonitor: ControlLoop gom feature, gọi lõi và nối verdict vào state machine. -->
|
||||
<build_depend>env_monitor_core</build_depend>
|
||||
<run_depend>env_monitor_core</run_depend>
|
||||
|
||||
<!-- Kho cảm biến THÔ dùng chung: action handler và local planner đọc qua cổng của gói này. -->
|
||||
<build_depend>robot_sensor_ports</build_depend>
|
||||
<run_depend>robot_sensor_ports</run_depend>
|
||||
|
||||
@@ -248,12 +248,11 @@ void readDebug(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
void readEnvMonitor(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
{
|
||||
robot::NodeHandle env_nh(nh, "env_monitor");
|
||||
EnvMonitorConfig& m = config.env_monitor;
|
||||
EnvSamplingConfig& s = config.env_sampling;
|
||||
|
||||
readBool(env_nh, "enabled", m.enabled);
|
||||
readDouble(env_nh, "grace_after_new_plan", m.grace_after_new_plan);
|
||||
readDouble(env_nh, "pose_jump_reject", m.pose_jump_reject);
|
||||
// Phần chung và từng detector (stall / unreachable / contact / replan_budget / detectors) do
|
||||
// env_monitor_core::EnvMonitor::initialize() đọc. Ở đây chỉ phần lấy mẫu của move_base2.
|
||||
readBool(env_nh, "enabled", config.env_monitor_enabled);
|
||||
readDouble(env_nh, "check_period", s.check_period);
|
||||
|
||||
robot::NodeHandle body_nh(env_nh, "body");
|
||||
@@ -274,62 +273,11 @@ void readEnvMonitor(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
readDouble(geo_nh, "exit_ahead", s.exit_ahead);
|
||||
readDouble(geo_nh, "target_snap", s.target_snap);
|
||||
|
||||
robot::NodeHandle stall_nh(env_nh, "stall");
|
||||
readBool(stall_nh, "enabled", m.stall.enabled);
|
||||
readString(stall_nh, "action", m.stall.action);
|
||||
readDouble(stall_nh, "window_s", m.stall.window_s);
|
||||
readDouble(stall_nh, "window_m", m.stall.window_m);
|
||||
readDouble(stall_nh, "min_commanded", m.stall.min_commanded);
|
||||
readDouble(stall_nh, "eff_on", m.stall.eff_on);
|
||||
readDouble(stall_nh, "eff_off", m.stall.eff_off);
|
||||
readDouble(stall_nh, "confirm", m.stall.confirm);
|
||||
readDouble(stall_nh, "goal_zone", m.stall.goal_zone);
|
||||
readDouble(stall_nh, "slip_on", m.stall.slip_on);
|
||||
readDouble(stall_nh, "slip_time", m.stall.slip_time);
|
||||
readDouble(stall_nh, "min_commanded_since_goal", m.stall.min_commanded_since_goal);
|
||||
readDouble(stall_nh, "retry_backoff", m.stall.retry_backoff);
|
||||
readDouble(stall_nh, "jump_reject", m.stall.jump_reject);
|
||||
readDouble(stall_nh, "disp_window_s", m.stall.disp_window_s);
|
||||
readDouble(stall_nh, "disp_min", m.stall.disp_min);
|
||||
readDouble(stall_nh, "disp_min_commanded", m.stall.disp_min_commanded);
|
||||
readDouble(stall_nh, "idle_window_s", m.stall.idle_window_s);
|
||||
readDouble(stall_nh, "confine_window_s", m.stall.confine_window_s);
|
||||
readDouble(stall_nh, "confine_radius", m.stall.confine_radius);
|
||||
readDouble(stall_nh, "confine_cmd_factor", m.stall.confine_cmd_factor);
|
||||
readBool(stall_nh, "progress_veto", m.stall.progress_veto);
|
||||
|
||||
robot::NodeHandle unreach_nh(env_nh, "unreachable");
|
||||
readBool(unreach_nh, "enabled", m.unreachable.enabled);
|
||||
readString(unreach_nh, "action", m.unreachable.action);
|
||||
readDouble(unreach_nh, "static_on", m.unreachable.static_on);
|
||||
readDouble(unreach_nh, "clean_start_margin", m.unreachable.clean_start_margin);
|
||||
readDouble(unreach_nh, "retry_backoff", m.unreachable.retry_backoff);
|
||||
|
||||
// Khối `contact` mang cả cách lấy quỹ đạo để sweep (của move_base2) lẫn tham số detector (của env_monitor_core).
|
||||
robot::NodeHandle contact_nh(env_nh, "contact");
|
||||
readBool(contact_nh, "enabled", m.contact.enabled);
|
||||
readString(contact_nh, "action", m.contact.action);
|
||||
readBool(contact_nh, "apply_command", m.contact.apply_command);
|
||||
readString(contact_nh, "use_local_plan", s.use_local_plan);
|
||||
readDouble(contact_nh, "local_plan_start_tol", s.local_plan_start_tol);
|
||||
readDouble(contact_nh, "lookahead", s.contact_lookahead);
|
||||
readInt(contact_nh, "confirm_cycles", m.contact.confirm_cycles);
|
||||
readDouble(contact_nh, "trigger_static_time", m.contact.trigger_static_time);
|
||||
readDouble(contact_nh, "clean_start_margin", m.contact.clean_start_margin);
|
||||
readDouble(contact_nh, "brake_decel", m.contact.brake_decel);
|
||||
readDouble(contact_nh, "min_speed", m.contact.min_speed);
|
||||
readDouble(contact_nh, "min_check_speed", m.contact.min_check_speed);
|
||||
readDouble(contact_nh, "release_hysteresis", m.contact.release_hysteresis);
|
||||
readInt(contact_nh, "release_confirm_cycles", m.contact.release_confirm_cycles);
|
||||
readDouble(contact_nh, "envelope_margin", m.contact.envelope_margin);
|
||||
readDouble(contact_nh, "standdown_min_travel", m.contact.standdown_min_travel);
|
||||
readDouble(contact_nh, "standdown_travel", m.contact.standdown_travel);
|
||||
readBool(contact_nh, "envelope", m.contact.envelope);
|
||||
|
||||
robot::NodeHandle budget_nh(env_nh, "replan_budget");
|
||||
readDouble(budget_nh, "min_travel", m.replan.min_travel);
|
||||
readDouble(budget_nh, "escalate_factor", m.replan.escalate_factor);
|
||||
readDouble(budget_nh, "escalate_window_m", m.replan.escalate_window_m);
|
||||
readDouble(budget_nh, "escalate_max", m.replan.escalate_max);
|
||||
|
||||
robot::NodeHandle logger_nh(env_nh, "logger");
|
||||
readBool(logger_nh, "enabled", config.env_logger.enabled);
|
||||
@@ -491,9 +439,9 @@ bool MoveBase2Config::validate(std::string& error) const
|
||||
return false;
|
||||
}
|
||||
|
||||
if (env_monitor.enabled)
|
||||
if (env_monitor_enabled)
|
||||
{
|
||||
if (!env_monitor.validate(error) || !env_sampling.validate(error) || !env_logger.validate(error))
|
||||
if (!env_sampling.validate(error) || !env_logger.validate(error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -755,7 +703,6 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
|
||||
config.go_straight = go_straight;
|
||||
config.rotate = rotate;
|
||||
config.backup_global_planner_name = backup_global_planner_name;
|
||||
config.env_monitor = env_monitor;
|
||||
config.env_sampling = env_sampling;
|
||||
config.env_logger = env_logger;
|
||||
config.debug_env = debug_env;
|
||||
|
||||
@@ -220,6 +220,64 @@ bool EnvSamplingConfig::validate(std::string& error) const
|
||||
// ControlLoop
|
||||
// ================================================================================================
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
/// Nhãn trigger cho log và recovery_core: tên route cũ giữ trigger cũ, route khác là kDetector.
|
||||
RecoveryTrigger triggerForRoute(const std::string& route)
|
||||
{
|
||||
if (route == "oscillation")
|
||||
{
|
||||
return RecoveryTrigger::kOscillation;
|
||||
}
|
||||
if (route == "path_blocked")
|
||||
{
|
||||
return RecoveryTrigger::kPathBlocked;
|
||||
}
|
||||
if (route == "off_path")
|
||||
{
|
||||
return RecoveryTrigger::kOffPath;
|
||||
}
|
||||
if (route == "collision")
|
||||
{
|
||||
return RecoveryTrigger::kCollision;
|
||||
}
|
||||
return RecoveryTrigger::kDetector;
|
||||
}
|
||||
|
||||
/// Một DetectorRoute cho mỗi detector đã nạp, đúng thứ tự (bit i của fired_mask). Detector trỏ tới route không có
|
||||
/// trong `recovery/routes` bị GỠ khỏi monitor (log LỖI): chốt 26/11, giống type sai.
|
||||
void resolveDetectorRoutes(env_monitor_core::EnvMonitor& monitor, StateMachineConfig& config)
|
||||
{
|
||||
if (config.recovery_routes.empty())
|
||||
{
|
||||
config.recovery_routes.fillLegacy(config.recovery_behavior_count);
|
||||
}
|
||||
config.detector_routes.clear();
|
||||
const std::vector<env_monitor_core::EnvDetectorInfo> detectors = monitor.detectors(); // copy: remove() sửa list
|
||||
for (const env_monitor_core::EnvDetectorInfo& d : detectors)
|
||||
{
|
||||
const std::vector<std::size_t>* route = config.recovery_routes.find(d.route.route);
|
||||
if (route == nullptr)
|
||||
{
|
||||
robot::log_error("[move_base2] EnvMonitor: detector '%s' points to route '%s', which is not in recovery/routes — "
|
||||
"the detector is REMOVED (no flag, no brake, no speed cap).\n",
|
||||
d.name.c_str(), d.route.route.c_str());
|
||||
monitor.remove(d.name);
|
||||
continue;
|
||||
}
|
||||
DetectorRoute r;
|
||||
r.name = d.name;
|
||||
r.route = *route;
|
||||
r.lock_on_exhausted = d.route.lock_on_exhausted;
|
||||
r.sequence = d.route.sequence;
|
||||
r.trigger = triggerForRoute(d.route.route);
|
||||
config.detector_routes.push_back(r);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDeps& deps,
|
||||
std::string& error)
|
||||
{
|
||||
@@ -235,7 +293,14 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!state_machine_.configure(config.state_machine, error))
|
||||
// Route theo detector: mỗi detector EnvMonitor trỏ tới một route theo tên (Test/docs/move_base2/
|
||||
// ENV_DETECTOR_PLUGINS_PROMPT.md §4). Chỉ khi monitor thật sự chạy — không có cổng môi trường thì không bit nào bật.
|
||||
StateMachineConfig state_machine_config = config.state_machine;
|
||||
if (deps.env_monitor != nullptr && deps.env_monitor->enabled() && deps.environment != nullptr)
|
||||
{
|
||||
resolveDetectorRoutes(*deps.env_monitor, state_machine_config);
|
||||
}
|
||||
if (!state_machine_.configure(state_machine_config, error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -245,6 +310,7 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
|
||||
}
|
||||
|
||||
config_ = config;
|
||||
config_.state_machine = state_machine_config;
|
||||
deps_ = deps;
|
||||
deps_.planner->setCostmapReadyTimeout(config_.costmap_ready_timeout);
|
||||
|
||||
@@ -252,7 +318,7 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
|
||||
// EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 (PathMonitor cũ đã
|
||||
// xoá). Không có cổng thì tắt, nhưng phải kêu nếu config bảo bật.
|
||||
env_logger_.reset();
|
||||
if (config_.env_monitor.enabled)
|
||||
if (deps_.env_monitor != nullptr && deps_.env_monitor->enabled())
|
||||
{
|
||||
if (deps_.environment == nullptr)
|
||||
{
|
||||
@@ -261,21 +327,19 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!config_.env_sampling.validate(error) || !env_monitor_.configure(config_.env_monitor, error))
|
||||
// Lõi đã initialize() từ YAML ở host (NavigationRuntime); ở đây chỉ kiểm phần lấy mẫu của chính vòng điều khiển.
|
||||
if (!config_.env_sampling.validate(error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
robot::log_info("[move_base2] %s\n sampling : check=%.2f s lethal>=%d padding=%.2f m horizon=%.1f m "
|
||||
"corridor_margin=%.2f m use_local_plan=%s lookahead=%.1f m body=%s\n",
|
||||
config_.env_monitor.describe().c_str(), config_.env_sampling.check_period,
|
||||
deps_.env_monitor->describe().c_str(), config_.env_sampling.check_period,
|
||||
config_.env_sampling.lethal_threshold, config_.env_sampling.padding,
|
||||
config_.env_sampling.horizon, config_.env_sampling.corridor_margin,
|
||||
config_.env_sampling.use_local_plan.c_str(), config_.env_sampling.contact_lookahead,
|
||||
config_.env_sampling.body_front > 0.0 ? "config" : "costmap footprint");
|
||||
const bool shadow = config_.env_monitor.stall.action != "recover" &&
|
||||
config_.env_monitor.unreachable.action != "recover" &&
|
||||
config_.env_monitor.contact.action != "recover" &&
|
||||
!config_.env_monitor.contact.apply_command;
|
||||
const bool shadow = !deps_.env_monitor->armed();
|
||||
robot::log_info("[move_base2] EnvMonitor mode: %s\n",
|
||||
shadow ? "SHADOW (log only; no flags, no braking, no speed cap)"
|
||||
: "ACTIVE on at least one verdict or on the command");
|
||||
@@ -320,6 +384,8 @@ void ControlLoop::reset()
|
||||
action_message_.clear();
|
||||
|
||||
latest_plan_.clear();
|
||||
chain_path_.clear();
|
||||
running_recovery_detector_ = -1;
|
||||
planner_running_ = false;
|
||||
backup_global_planner_active_ = false;
|
||||
|
||||
@@ -335,8 +401,11 @@ void ControlLoop::reset()
|
||||
last_plan_started_ = robot::Time();
|
||||
has_last_plan_applied_ = false;
|
||||
|
||||
env_monitor_.reset();
|
||||
env_verdict_ = EnvVerdict();
|
||||
if (deps_.env_monitor != nullptr)
|
||||
{
|
||||
deps_.env_monitor->reset();
|
||||
}
|
||||
env_verdict_ = env_monitor_core::EnvVerdict();
|
||||
env_geometry_ = EnvGeometry();
|
||||
has_last_env_heavy_ = false;
|
||||
has_last_env_debug_ = false;
|
||||
@@ -732,20 +801,52 @@ bool ControlLoop::robotStopped() const
|
||||
return arbiter_.stopped();
|
||||
}
|
||||
|
||||
bool ControlLoop::runningChain() const
|
||||
{
|
||||
const auto& routes = config_.state_machine.detector_routes;
|
||||
return running_recovery_detector_ >= 0 && static_cast<std::size_t>(running_recovery_detector_) < routes.size() &&
|
||||
routes[running_recovery_detector_].sequence;
|
||||
}
|
||||
|
||||
std::string ControlLoop::triggerLabel(const StateMachineOutput& output) const
|
||||
{
|
||||
const auto& routes = config_.state_machine.detector_routes;
|
||||
std::string label = toString(output.recovery_trigger);
|
||||
if (output.recovery_detector >= 0 && static_cast<std::size_t>(output.recovery_detector) < routes.size())
|
||||
{
|
||||
label += " (" + routes[output.recovery_detector].name + ")"; // detector nào: kDetector tự nó không nói
|
||||
}
|
||||
return label;
|
||||
}
|
||||
|
||||
void ControlLoop::envRecoveryFinished(const robot::Time& now, env_monitor_core::EnvRecoveryOutcome outcome)
|
||||
{
|
||||
if (deps_.env_monitor == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Báo tên detector có route vừa chạy: detector đó biết lượt recovery là của chính nó (contact: stand-down).
|
||||
const auto& routes = config_.state_machine.detector_routes;
|
||||
const bool by_detector =
|
||||
running_recovery_detector_ >= 0 && static_cast<std::size_t>(running_recovery_detector_) < routes.size();
|
||||
deps_.env_monitor->onRecoveryFinished(now, outcome,
|
||||
by_detector ? routes[running_recovery_detector_].name : std::string());
|
||||
}
|
||||
|
||||
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
|
||||
bool costmap_stale)
|
||||
{
|
||||
env_brake_ = false;
|
||||
if (!config_.env_monitor.enabled || deps_.environment == nullptr || !env_monitor_.configured())
|
||||
if (deps_.env_monitor == nullptr || !deps_.env_monitor->enabled() || deps_.environment == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!has_active_request_)
|
||||
{
|
||||
// Không có chặng: mọi ngân sách/mốc thuộc chặng cũ. Verdict rỗng.
|
||||
env_monitor_.reset();
|
||||
env_verdict_ = EnvVerdict();
|
||||
deps_.env_monitor->reset();
|
||||
env_verdict_ = env_monitor_core::EnvVerdict();
|
||||
env_geometry_ = EnvGeometry();
|
||||
has_last_env_heavy_ = false;
|
||||
env_plan_index_valid_ = false;
|
||||
@@ -756,7 +857,7 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||
const bool monitorable = state_machine_.state() == NavigationState::kControlling && pose_available &&
|
||||
!latest_plan_.empty() && sampling.monitors(active_request_.profile);
|
||||
|
||||
EnvSample s;
|
||||
env_monitor_core::EnvSample s;
|
||||
s.now = now;
|
||||
s.dt = dt;
|
||||
s.costmap_current = !costmap_stale;
|
||||
@@ -836,7 +937,7 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||
has_last_env_heavy_ = true;
|
||||
}
|
||||
|
||||
if (config_.env_monitor.contact.enabled)
|
||||
if (deps_.env_monitor->needs().sweep) // chỉ khi có detector cần quỹ đạo (contact)
|
||||
{
|
||||
EnvTrajectoryRequest treq;
|
||||
treq.robot_pose = robot_pose;
|
||||
@@ -864,8 +965,8 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||
}
|
||||
}
|
||||
|
||||
env_verdict_ = env_monitor_.update(s);
|
||||
env_brake_ = env_verdict_.brake && config_.env_monitor.contact.apply_command;
|
||||
env_verdict_ = deps_.env_monitor->update(s);
|
||||
env_brake_ = env_verdict_.brake_applied; // chỉ phanh của detector có apply_command
|
||||
if (env_verdict_.pose_jump)
|
||||
{
|
||||
// Bất thường (localization đặt lại pose / TF đứng rồi chạy lại), không phải đường đi bình thường: không công tắc.
|
||||
@@ -918,8 +1019,7 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||
env_verdict_.replan_budget_left, env_verdict_.net_disp,
|
||||
env_verdict_.wandering
|
||||
? " WANDERING"
|
||||
: (!env_verdict_.idle && env_verdict_.confined && env_verdict_.progress_proven &&
|
||||
config_.env_monitor.stall.progress_veto
|
||||
: (!env_verdict_.idle && env_verdict_.confined_vetoed
|
||||
? " CONFINED vetoed: progress proven"
|
||||
: (env_verdict_.idle ? " IDLE" : (env_verdict_.confined ? " CONFINED" : ""))));
|
||||
}
|
||||
@@ -1091,12 +1191,8 @@ bool ControlLoop::step()
|
||||
}
|
||||
}
|
||||
input.travelled_since_oscillation_reset = travelled;
|
||||
// Bốn cổng của state machine do EnvMonitor cấp (Test/docs/move_base2/ENV_MONITOR_PLAN.md): cờ chỉ khác false khi
|
||||
// verdict tương ứng có `action: recover`. `off_path` không còn nguồn nào (phép đo cũ đã bỏ 6/9/2026).
|
||||
input.path_blocked = env_verdict_.path_blocked;
|
||||
input.collision = env_verdict_.collision;
|
||||
input.off_path = false;
|
||||
input.no_progress = env_verdict_.no_progress;
|
||||
// Bit i = detector i đòi recovery (đã qua action/cổng/ngân sách), cùng thứ tự với detector_routes.
|
||||
input.detector_fired = env_verdict_.fired_mask;
|
||||
|
||||
// Cùng một chỉ số dùng cho cả cycle khởi động recovery lẫn các cycle tick: state machine chỉ tăng
|
||||
// chỉ số khi behavior kết thúc, nên `nextRecoveryIndex()` chính là behavior sắp chạy hoặc đang
|
||||
@@ -1163,7 +1259,10 @@ bool ControlLoop::step()
|
||||
latest_plan_.clear();
|
||||
order_plan_.clear();
|
||||
has_outcome_ = false;
|
||||
env_monitor_.onGoalAccepted(now);
|
||||
if (deps_.env_monitor != nullptr)
|
||||
{
|
||||
deps_.env_monitor->onGoalAccepted(now);
|
||||
}
|
||||
|
||||
// Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop.
|
||||
if (active_request_.has_goal)
|
||||
@@ -1206,6 +1305,20 @@ bool ControlLoop::step()
|
||||
planner_running_ = false;
|
||||
}
|
||||
|
||||
// Chuỗi `route_mode: sequence` vừa xong: path mới nhất của chuỗi (nếu có) là plan được áp ngay dưới, và EnvMonitor
|
||||
// nghe kết cục của CẢ chuỗi đúng một lần (chốt 26/11).
|
||||
if (output.recovery_chain_finished)
|
||||
{
|
||||
if (!chain_path_.empty())
|
||||
{
|
||||
latest_plan_ = chain_path_;
|
||||
}
|
||||
envRecoveryFinished(now, output.recovery_chain_has_path ? env_monitor_core::EnvRecoveryOutcome::kSucceededWithPath
|
||||
: output.recovery_chain_last_failed ? env_monitor_core::EnvRecoveryOutcome::kFailed
|
||||
: env_monitor_core::EnvRecoveryOutcome::kSucceeded);
|
||||
chain_path_.clear();
|
||||
}
|
||||
|
||||
if (output.apply_plan && !latest_plan_.empty())
|
||||
{
|
||||
if (!deps_.controller->setPlan(latest_plan_))
|
||||
@@ -1229,7 +1342,10 @@ bool ControlLoop::step()
|
||||
// plan vừa tới (rõ nhất lúc preempt/đổi chặng). Đo lệch tuyến ngay lúc đó là khai hoả oan.
|
||||
last_plan_applied_ = now;
|
||||
has_last_plan_applied_ = true;
|
||||
env_monitor_.onPlanApplied(now);
|
||||
if (deps_.env_monitor != nullptr)
|
||||
{
|
||||
deps_.env_monitor->onPlanApplied(now);
|
||||
}
|
||||
env_plan_index_valid_ = false;
|
||||
|
||||
if (config_.debug_plan)
|
||||
@@ -1263,7 +1379,7 @@ bool ControlLoop::step()
|
||||
"here the controller is the only safety net: it stops at the obstacle and "
|
||||
"controller_patience escalates to controlling_failed. This trigger stays "
|
||||
"muted until the robot travels %.2f m.\n",
|
||||
toString(output.recovery_trigger), config_.state_machine.oscillation_distance);
|
||||
triggerLabel(output).c_str(), config_.state_machine.oscillation_distance);
|
||||
}
|
||||
|
||||
// Recovery vừa nộp path mới nhưng robot chưa dịch chuyển kể từ path mới trước đó: state machine
|
||||
@@ -1275,7 +1391,7 @@ bool ControlLoop::step()
|
||||
"the previous one (%.2f m, need %.2f m) — counting it against the %s route "
|
||||
"budget instead of refilling it.\n",
|
||||
output.recovery_reset_travel, config_.state_machine.recovery_reset_min_travel,
|
||||
toString(output.recovery_trigger));
|
||||
triggerLabel(output).c_str());
|
||||
}
|
||||
|
||||
robot_geometry_msgs::Twist candidate;
|
||||
@@ -1283,13 +1399,20 @@ bool ControlLoop::step()
|
||||
|
||||
if (output.start_recovery)
|
||||
{
|
||||
running_recovery_trigger_ = output.recovery_trigger;
|
||||
running_recovery_detector_ = output.recovery_detector;
|
||||
if (!output.recovery_chain_continues)
|
||||
{
|
||||
chain_path_.clear(); // lượt mới: path của chuỗi trước (nếu bị huỷ giữa chừng) không còn giá trị
|
||||
}
|
||||
if (!deps_.recovery->start(output.recovery_index, output.recovery_trigger))
|
||||
{
|
||||
// Behavior từ chối khởi động (ví dụ đã va chạm ngay tại chỗ) — báo hỏng để state machine
|
||||
// chuyển sang behavior kế tiếp thay vì tick một behavior chưa start.
|
||||
recovery_feedback_ = RecoveryFeedback::kFailed;
|
||||
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
|
||||
if (!runningChain())
|
||||
{
|
||||
envRecoveryFinished(now, env_monitor_core::EnvRecoveryOutcome::kFailed);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (output.tick_recovery)
|
||||
@@ -1302,14 +1425,19 @@ bool ControlLoop::step()
|
||||
break;
|
||||
case RecoveryTick::Status::kSucceeded:
|
||||
recovery_feedback_ = RecoveryFeedback::kSucceeded;
|
||||
env_monitor_.onRecoveryFinished(now,
|
||||
tick.has_path && !tick.path.empty() ? EnvRecoveryOutcome::kSucceededWithPath
|
||||
: EnvRecoveryOutcome::kSucceeded,
|
||||
running_recovery_trigger_ == RecoveryTrigger::kCollision);
|
||||
if (!runningChain()) // chuỗi sequence: báo một lần khi cả chuỗi xong (recovery_chain_finished)
|
||||
{
|
||||
envRecoveryFinished(now, tick.has_path && !tick.path.empty()
|
||||
? env_monitor_core::EnvRecoveryOutcome::kSucceededWithPath
|
||||
: env_monitor_core::EnvRecoveryOutcome::kSucceeded);
|
||||
}
|
||||
break;
|
||||
case RecoveryTick::Status::kFailed:
|
||||
recovery_feedback_ = RecoveryFeedback::kFailed;
|
||||
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
|
||||
if (!runningChain())
|
||||
{
|
||||
envRecoveryFinished(now, env_monitor_core::EnvRecoveryOutcome::kFailed);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (tick.has_velocity)
|
||||
@@ -1320,6 +1448,10 @@ bool ControlLoop::step()
|
||||
{
|
||||
// Họ recovery sinh lại đường đi: coi kết quả như một plan mới, chờ state machine đẩy xuống.
|
||||
latest_plan_ = tick.path;
|
||||
if (runningChain())
|
||||
{
|
||||
chain_path_ = tick.path; // giữ path MỚI NHẤT của chuỗi tới khi cả chuỗi xong
|
||||
}
|
||||
planner_feedback_ = PlannerFeedback::kPlanReady;
|
||||
if (config_.debug_plan)
|
||||
{
|
||||
@@ -1455,9 +1587,9 @@ bool ControlLoop::step()
|
||||
// (P4); ở shadow chỉ có dòng log "would cap". Giữ omega/v để cung không đổi khi kẹp.
|
||||
if (std::isfinite(env_verdict_.v_cap) && std::fabs(candidate.linear.x) > env_verdict_.v_cap)
|
||||
{
|
||||
if (config_.env_monitor.contact.apply_command)
|
||||
if (std::isfinite(env_verdict_.v_cap_applied) && std::fabs(candidate.linear.x) > env_verdict_.v_cap_applied)
|
||||
{
|
||||
const double scale = env_verdict_.v_cap / std::fabs(candidate.linear.x);
|
||||
const double scale = env_verdict_.v_cap_applied / std::fabs(candidate.linear.x);
|
||||
candidate.linear.x *= scale;
|
||||
candidate.angular.z *= scale;
|
||||
}
|
||||
@@ -1613,7 +1745,7 @@ bool ControlLoop::step()
|
||||
robot::log_error("[move_base2] abort detail: recovery route exhausted "
|
||||
"(trigger=%s cursor=%zu size=%zu, planner_in=%s, controller_in=%s, "
|
||||
"recovery_in=%s, pose=%s, costmap_current=%s).\n",
|
||||
toString(output.recovery_trigger), output.recovery_route_cursor,
|
||||
triggerLabel(output).c_str(), output.recovery_route_cursor,
|
||||
output.recovery_route_size, toString(input.planner),
|
||||
toString(input.controller), toString(input.recovery),
|
||||
pose_available ? "yes" : "no", costmap_stale ? "no" : "yes");
|
||||
|
||||
@@ -1,927 +0,0 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — cài đặt lõi EnvMonitor (xem header).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/core/env_monitor.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
bool validAction(const std::string& action)
|
||||
{
|
||||
return action == "log" || action == "recover";
|
||||
}
|
||||
|
||||
bool finitePositive(double v)
|
||||
{
|
||||
return std::isfinite(v) && v > 0.0;
|
||||
}
|
||||
|
||||
bool finiteNonNegative(double v)
|
||||
{
|
||||
return std::isfinite(v) && v >= 0.0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ------------------------------------------------------------------------------------------ config
|
||||
|
||||
bool EnvMonitorConfig::validate(std::string& error) const
|
||||
{
|
||||
if (!finiteNonNegative(grace_after_new_plan))
|
||||
{
|
||||
error = "env_monitor/grace_after_new_plan must be >= 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(pose_jump_reject))
|
||||
{
|
||||
error = "env_monitor/pose_jump_reject must be >= 0 [m] (0 = off)";
|
||||
return false;
|
||||
}
|
||||
if (!validAction(stall.action) || !validAction(unreachable.action) || !validAction(contact.action))
|
||||
{
|
||||
error = "env_monitor/*/action must be \"log\" or \"recover\"";
|
||||
return false;
|
||||
}
|
||||
if (!finitePositive(stall.window_s) || !finitePositive(stall.window_m))
|
||||
{
|
||||
error = "env_monitor/stall/window_s and window_m must be > 0";
|
||||
return false;
|
||||
}
|
||||
if (!finitePositive(stall.min_commanded))
|
||||
{
|
||||
error = "env_monitor/stall/min_commanded must be > 0 [m] (0 would turn waiting into stalling)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(stall.eff_on) || !std::isfinite(stall.eff_off) || stall.eff_off <= stall.eff_on)
|
||||
{
|
||||
error = "env_monitor/stall/eff_off must be > eff_on (hysteresis)";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(stall.confirm) || !finiteNonNegative(stall.goal_zone) ||
|
||||
!finiteNonNegative(stall.slip_on) || !finiteNonNegative(stall.slip_time) ||
|
||||
!finiteNonNegative(stall.min_commanded_since_goal) || !finiteNonNegative(stall.retry_backoff) ||
|
||||
!finiteNonNegative(stall.jump_reject) || !finitePositive(stall.disp_window_s) ||
|
||||
!finiteNonNegative(stall.disp_min) || !finiteNonNegative(stall.disp_min_commanded) ||
|
||||
!finiteNonNegative(stall.idle_window_s) || !finiteNonNegative(stall.confine_radius) ||
|
||||
!finitePositive(stall.confine_window_s) || !std::isfinite(stall.confine_cmd_factor) ||
|
||||
stall.confine_cmd_factor < 1.0)
|
||||
{
|
||||
error = "env_monitor/stall: confirm, goal_zone, slip_on, slip_time, min_commanded_since_goal, "
|
||||
"retry_backoff must be >= 0";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(unreachable.static_on) || !finitePositive(unreachable.clean_start_margin) ||
|
||||
!finiteNonNegative(unreachable.retry_backoff))
|
||||
{
|
||||
error = "env_monitor/unreachable: static_on >= 0 [s], clean_start_margin > 0 [m], retry_backoff >= 0";
|
||||
return false;
|
||||
}
|
||||
if (contact.confirm_cycles < 1)
|
||||
{
|
||||
error = "env_monitor/contact/confirm_cycles must be >= 1";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(contact.trigger_static_time) || !finitePositive(contact.clean_start_margin) ||
|
||||
!finitePositive(contact.brake_decel) || !finiteNonNegative(contact.min_speed) ||
|
||||
!finiteNonNegative(contact.min_check_speed) || !finiteNonNegative(contact.release_hysteresis) ||
|
||||
contact.release_confirm_cycles < 1 || !finiteNonNegative(contact.envelope_margin) ||
|
||||
!finiteNonNegative(contact.standdown_min_travel) || !finiteNonNegative(contact.standdown_travel))
|
||||
{
|
||||
error = "env_monitor/contact: trigger_static_time >= 0, clean_start_margin > 0, brake_decel > 0, "
|
||||
"min_speed >= 0, min_check_speed >= 0, release_hysteresis >= 0, release_confirm_cycles >= 1, "
|
||||
"envelope_margin >= 0, standdown_min_travel >= 0, standdown_travel >= 0";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(replan.min_travel) || !std::isfinite(replan.escalate_factor) ||
|
||||
replan.escalate_factor < 1.0 || !finiteNonNegative(replan.escalate_window_m) ||
|
||||
!finiteNonNegative(replan.escalate_max) || (replan.escalate_max > 0.0 && replan.escalate_max < replan.min_travel))
|
||||
{
|
||||
error = "env_monitor/replan_budget: min_travel >= 0, escalate_factor >= 1, escalate_window_m >= 0, "
|
||||
"escalate_max = 0 or >= min_travel";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string EnvMonitorConfig::describe() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "env_monitor " << (enabled ? "ON" : "OFF") << " (grace " << grace_after_new_plan << " s, pose_jump>"
|
||||
<< pose_jump_reject << " m):\n";
|
||||
out << " stall : " << (stall.enabled ? "on" : "off") << " action=" << stall.action
|
||||
<< " window=" << stall.window_s << " s/" << stall.window_m << " m min_cmd=" << stall.min_commanded
|
||||
<< " m eff<" << stall.eff_on << " ket / >=" << stall.eff_off << " xoa confirm=" << stall.confirm
|
||||
<< " s goal_zone=" << stall.goal_zone << " m slip>=" << stall.slip_on << " m/s " << stall.slip_time
|
||||
<< " s cmd_since_goal>=" << stall.min_commanded_since_goal << " m backoff=" << stall.retry_backoff
|
||||
<< " s jump_reject=" << stall.jump_reject << " m disp_gate=" << stall.disp_min << " m/"
|
||||
<< stall.disp_window_s << " s (cmd>=" << stall.disp_min_commanded << " m) idle=" << stall.idle_window_s
|
||||
<< " s confine=" << stall.confine_radius << " m/" << stall.confine_window_s << " s x" << stall.confine_cmd_factor
|
||||
<< " progress_veto=" << (stall.progress_veto ? "on" : "off") << "\n";
|
||||
out << " unreachable : " << (unreachable.enabled ? "on" : "off") << " action=" << unreachable.action
|
||||
<< " static_on=" << unreachable.static_on << " s clean_margin=" << unreachable.clean_start_margin
|
||||
<< " m backoff=" << unreachable.retry_backoff << " s\n";
|
||||
out << " contact : " << (contact.enabled ? "on" : "off") << " action=" << contact.action
|
||||
<< " confirm=" << contact.confirm_cycles << " cycles trigger_static=" << contact.trigger_static_time
|
||||
<< " s clean_margin=" << contact.clean_start_margin << " m decel=" << contact.brake_decel
|
||||
<< " m/s^2 envelope=" << (contact.envelope ? "on" : "off") << " min_speed=" << contact.min_speed
|
||||
<< " m/s min_check_speed=" << contact.min_check_speed << " m/s release=" << contact.release_hysteresis
|
||||
<< " m/" << contact.release_confirm_cycles << " cycles envelope_margin=" << contact.envelope_margin
|
||||
<< " m standdown=" << contact.standdown_min_travel << "/" << contact.standdown_travel
|
||||
<< " m apply_command=" << (contact.apply_command ? "YES" : "no (shadow)") << "\n";
|
||||
out << " replan : min_travel=" << replan.min_travel << " m x" << replan.escalate_factor
|
||||
<< " within " << replan.escalate_window_m << " m, max " << replan.escalate_max << " m";
|
||||
return out.str();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- lifecycle
|
||||
|
||||
bool EnvMonitor::configure(const EnvMonitorConfig& config, std::string& error)
|
||||
{
|
||||
if (!config.validate(error))
|
||||
{
|
||||
configured_ = false;
|
||||
return false;
|
||||
}
|
||||
config_ = config;
|
||||
configured_ = true;
|
||||
reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
void EnvMonitor::reset()
|
||||
{
|
||||
cmd_accum_ = 0.0;
|
||||
travel_total_ = 0.0;
|
||||
jump_dist_total_ = 0.0;
|
||||
has_last_pose_ = false;
|
||||
v_gap_max_ = 0.0;
|
||||
has_pose_jump_restart_ = false;
|
||||
has_goal_ = false;
|
||||
cmd_at_goal_ = 0.0;
|
||||
has_plan_time_ = false;
|
||||
clearWindow();
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
slip_seen_ = false;
|
||||
has_stall_backoff_ = false;
|
||||
baseline_pending_ = true;
|
||||
baseline_unreachable_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
has_unreach_backoff_ = false;
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
has_prev_heavy_ = false;
|
||||
clearPosWindow();
|
||||
braking_ = false;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
detour_from_contact_ = false;
|
||||
detour_mark_travel_ = 0.0;
|
||||
standdown_ = false;
|
||||
standdown_mark_travel_ = 0.0;
|
||||
standdown_clean_streak_ = 0;
|
||||
has_replan_mark_ = false;
|
||||
replan_mark_travel_ = 0.0;
|
||||
budget_travel_ = config_.replan.min_travel;
|
||||
has_prev_replan_ = false;
|
||||
prev_replan_travel_ = 0.0;
|
||||
}
|
||||
|
||||
void EnvMonitor::onGoalAccepted(const robot::Time& now)
|
||||
{
|
||||
(void)now;
|
||||
const double cmd = cmd_accum_;
|
||||
const double travel = travel_total_;
|
||||
const double jump_dist = jump_dist_total_;
|
||||
const bool had_pose = has_last_pose_;
|
||||
const double lx = last_x_;
|
||||
const double ly = last_y_;
|
||||
const robot::Time pose_t = last_pose_t_;
|
||||
const double gap_v = v_gap_max_;
|
||||
reset();
|
||||
// Odometer và lệnh tích luỹ là đơn điệu, chỉ dùng qua hiệu số: giữ lại để mốc không nhảy.
|
||||
cmd_accum_ = cmd;
|
||||
travel_total_ = travel;
|
||||
jump_dist_total_ = jump_dist;
|
||||
has_last_pose_ = had_pose;
|
||||
last_x_ = lx;
|
||||
last_y_ = ly;
|
||||
last_pose_t_ = pose_t;
|
||||
v_gap_max_ = gap_v;
|
||||
has_goal_ = true;
|
||||
cmd_at_goal_ = cmd_accum_;
|
||||
}
|
||||
|
||||
void EnvMonitor::onPlanApplied(const robot::Time& now)
|
||||
{
|
||||
has_plan_time_ = true;
|
||||
plan_time_ = now;
|
||||
clearWindow();
|
||||
clearPosWindow(); // cửa sổ dịch chuyển bắt đầu lại: plan mới là một lượt thử mới
|
||||
has_prev_heavy_ = false;
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
// Plan mới có baseline riêng: chỉ nổ "mất liên thông" vì thứ xảy ra SAU khi plan được lập (R2).
|
||||
baseline_pending_ = true;
|
||||
baseline_unreachable_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
}
|
||||
|
||||
void EnvMonitor::onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome, bool from_contact)
|
||||
{
|
||||
switch (outcome)
|
||||
{
|
||||
case EnvRecoveryOutcome::kSucceededWithPath:
|
||||
{
|
||||
// Detour do chính cờ collision: nếu robot không rời chỗ mà lại "sắp chạm" thì lần sau đứng ra.
|
||||
detour_from_contact_ = from_contact;
|
||||
detour_mark_travel_ = travel_total_;
|
||||
// R3/R5: im tới khi đi đủ budget_travel_ kể từ đây; lặp trong escalate_window_m thì nhân lên.
|
||||
if (has_prev_replan_ && travel_total_ - prev_replan_travel_ < config_.replan.escalate_window_m)
|
||||
{
|
||||
budget_travel_ *= config_.replan.escalate_factor;
|
||||
if (config_.replan.escalate_max > 0.0)
|
||||
{
|
||||
budget_travel_ = std::min(budget_travel_, config_.replan.escalate_max);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
budget_travel_ = config_.replan.min_travel;
|
||||
}
|
||||
has_prev_replan_ = true;
|
||||
prev_replan_travel_ = travel_total_;
|
||||
has_replan_mark_ = true;
|
||||
replan_mark_travel_ = travel_total_;
|
||||
break;
|
||||
}
|
||||
case EnvRecoveryOutcome::kSucceeded:
|
||||
break;
|
||||
case EnvRecoveryOutcome::kFailed:
|
||||
has_stall_backoff_ = true;
|
||||
stall_backoff_until_ = now + robot::Duration(config_.stall.retry_backoff);
|
||||
has_unreach_backoff_ = true;
|
||||
unreach_backoff_until_ = now + robot::Duration(config_.unreachable.retry_backoff);
|
||||
break;
|
||||
}
|
||||
// Mọi kết cục đều kết thúc một pha dừng: chuỗi xác nhận cũ không còn giá trị.
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
braking_ = false;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------- window
|
||||
|
||||
void EnvMonitor::clearWindow()
|
||||
{
|
||||
ring_head_ = 0;
|
||||
ring_count_ = 0;
|
||||
}
|
||||
|
||||
void EnvMonitor::clearPosWindow()
|
||||
{
|
||||
pos_head_ = 0;
|
||||
pos_count_ = 0;
|
||||
wandering_ = false;
|
||||
idle_ = false;
|
||||
confined_ = false;
|
||||
region_radius_ = std::numeric_limits<double>::quiet_NaN();
|
||||
net_disp_ = std::numeric_limits<double>::quiet_NaN();
|
||||
has_eff_ok_ = false;
|
||||
has_eff_low_ = false;
|
||||
}
|
||||
|
||||
bool EnvMonitor::progressProven(const robot::Time& now) const
|
||||
{
|
||||
const EnvMonitorConfig::Stall& c = config_.stall;
|
||||
if (!has_eff_ok_ || (now - eff_ok_t_).toSec() > c.window_s)
|
||||
{
|
||||
return false; // không có bằng chứng tiến độ còn mới: cổng được nổ như cũ
|
||||
}
|
||||
return !has_eff_low_ || (now - eff_low_t_).toSec() > c.confine_window_s;
|
||||
}
|
||||
|
||||
bool EnvMonitor::oldestPos(const robot::Time& now, double window_s, PosSample& out) const
|
||||
{
|
||||
// Mẫu MỚI NHẤT đã đủ tuổi window_s — cùng lý do với oldestInWindow.
|
||||
for (std::size_t k = 1; k <= pos_count_; ++k)
|
||||
{
|
||||
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
|
||||
if ((now - p.t).toSec() >= window_s)
|
||||
{
|
||||
out = p;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool EnvMonitor::oldestInWindow(const robot::Time& now, HeavySample& out) const
|
||||
{
|
||||
// Mẫu MỚI NHẤT đã đủ tuổi window_s hoặc đủ xa window_m lệnh — cửa sổ sát ngưỡng nhất, không phải
|
||||
// mẫu cũ nhất trong ring (cửa sổ giãn ra làm eff mượt giả).
|
||||
for (std::size_t k = 1; k <= ring_count_; ++k)
|
||||
{
|
||||
const HeavySample& s = ring_[(ring_head_ + kRing - k) % kRing];
|
||||
const bool old_enough = (now - s.t).toSec() >= config_.stall.window_s;
|
||||
const bool far_enough = cmd_accum_ - s.cmd >= config_.stall.window_m;
|
||||
if (old_enough || far_enough)
|
||||
{
|
||||
out = s;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------- update
|
||||
|
||||
EnvVerdict EnvMonitor::update(const EnvSample& s)
|
||||
{
|
||||
EnvVerdict v;
|
||||
if (!configured_ || !config_.enabled)
|
||||
{
|
||||
return v;
|
||||
}
|
||||
|
||||
// Tích luỹ lệnh và quãng đường — mọi cửa sổ, cổng, ngân sách đều đo bằng hai con số này.
|
||||
if (s.dt > 0.0 && std::isfinite(s.v_cmd))
|
||||
{
|
||||
cmd_accum_ += std::fabs(s.v_cmd) * s.dt;
|
||||
}
|
||||
if (std::isfinite(s.v_cmd))
|
||||
{
|
||||
v_gap_max_ = std::max(v_gap_max_, std::fabs(s.v_cmd));
|
||||
}
|
||||
if (std::isfinite(s.v_meas))
|
||||
{
|
||||
v_gap_max_ = std::max(v_gap_max_, std::fabs(s.v_meas));
|
||||
}
|
||||
if (std::isfinite(s.robot_x) && std::isfinite(s.robot_y))
|
||||
{
|
||||
if (has_last_pose_)
|
||||
{
|
||||
const double step = std::hypot(s.robot_x - last_x_, s.robot_y - last_y_);
|
||||
// Khoảng giữa hai pose hợp lệ có thể gồm nhiều cycle thiếu pose.
|
||||
const double reach = v_gap_max_ * std::max(0.0, (s.now - last_pose_t_).toSec());
|
||||
if (config_.pose_jump_reject > 0.0 && step > config_.pose_jump_reject + reach)
|
||||
{
|
||||
v.pose_jump = true;
|
||||
v.pose_jump_dist = step;
|
||||
jump_dist_total_ += step;
|
||||
}
|
||||
else
|
||||
{
|
||||
travel_total_ += step;
|
||||
}
|
||||
}
|
||||
last_x_ = s.robot_x;
|
||||
last_y_ = s.robot_y;
|
||||
last_pose_t_ = s.now;
|
||||
v_gap_max_ = 0.0;
|
||||
has_last_pose_ = true;
|
||||
}
|
||||
const double restart_cooldown = std::max({ config_.stall.idle_window_s, config_.stall.confine_window_s,
|
||||
config_.stall.disp_window_s });
|
||||
if (v.pose_jump && (!has_pose_jump_restart_ || (s.now - pose_jump_restart_t_).toSec() >= restart_cooldown))
|
||||
{
|
||||
// Pose bị đặt lại (relocalization): mẫu vị trí và cost_to_go hai bên cú dời không cùng hệ quy chiếu. Giữ chúng
|
||||
// thì quỹ đạo gấp lên chính nó (giam vùng / đứng yên / dịch chuyển nổ oan) và eff âm giả (sim 6/11 20:34).
|
||||
// Đo lại từ đầu; kết luận kẹt cũ cũng không còn cơ sở — cùng cách xử lý với cú nhảy cost_to_go.
|
||||
clearWindow();
|
||||
clearPosWindow();
|
||||
has_prev_heavy_ = false;
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
has_pose_jump_restart_ = true;
|
||||
pose_jump_restart_t_ = s.now;
|
||||
v.pose_jump_restart = true;
|
||||
}
|
||||
if (has_replan_mark_)
|
||||
{
|
||||
v.replan_budget_left = std::max(0.0, budget_travel_ - (travel_total_ - replan_mark_travel_));
|
||||
}
|
||||
|
||||
updateContact(s, v);
|
||||
|
||||
if (!s.has_plan || !s.costmap_current)
|
||||
{
|
||||
// Không có gì để đo tiến độ; xoá chuỗi để không nối "đúng liên tục" qua quãng gián đoạn.
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
return v;
|
||||
}
|
||||
updateStall(s, v);
|
||||
updateUnreachable(s, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
void EnvMonitor::updateStall(const EnvSample& s, EnvVerdict& v)
|
||||
{
|
||||
const EnvMonitorConfig::Stall& c = config_.stall;
|
||||
if (!c.enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Cửa sổ dịch chuyển thực: lấy mẫu vị trí mỗi tick nặng, không phụ thuộc cost/plan/mặt nạ.
|
||||
if (s.geometry_valid && std::isfinite(s.robot_x) && std::isfinite(s.robot_y))
|
||||
{
|
||||
pos_ring_[pos_head_] = PosSample{ s.now, s.robot_x, s.robot_y, cmd_accum_ };
|
||||
pos_head_ = (pos_head_ + 1) % kPosRing;
|
||||
pos_count_ = std::min(pos_count_ + 1, kPosRing);
|
||||
PosSample old;
|
||||
if (oldestPos(s.now, c.disp_window_s, old))
|
||||
{
|
||||
net_disp_ = std::hypot(s.robot_x - old.x, s.robot_y - old.y);
|
||||
wandering_ = (cmd_accum_ - old.cmd >= c.disp_min_commanded) && net_disp_ < c.disp_min;
|
||||
}
|
||||
else
|
||||
{
|
||||
net_disp_ = std::numeric_limits<double>::quiet_NaN();
|
||||
wandering_ = false;
|
||||
}
|
||||
// Cổng đứng yên: không cần lệnh đủ — PRIEST bò 0,05 m/s tại chỗ 30 s cũng là kẹt.
|
||||
idle_ = false;
|
||||
PosSample older;
|
||||
if (c.idle_window_s > 0.0 && c.disp_min > 0.0 && oldestPos(s.now, c.idle_window_s, older))
|
||||
{
|
||||
idle_ = std::hypot(s.robot_x - older.x, s.robot_y - older.y) < c.disp_min;
|
||||
}
|
||||
// Cổng giam vùng: bán kính của tập vị trí trong confine_window_s quanh tâm của chúng, so với lệnh tích luỹ.
|
||||
confined_ = false;
|
||||
region_radius_ = std::numeric_limits<double>::quiet_NaN();
|
||||
if (c.confine_radius > 0.0 && c.disp_min > 0.0)
|
||||
{
|
||||
double sx = 0.0;
|
||||
double sy = 0.0;
|
||||
std::size_t n = 0;
|
||||
double oldest_cmd = cmd_accum_;
|
||||
double oldest_age = 0.0;
|
||||
for (std::size_t k = 1; k <= pos_count_; ++k)
|
||||
{
|
||||
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
|
||||
const double age = (s.now - p.t).toSec();
|
||||
if (age > c.confine_window_s)
|
||||
{
|
||||
break;
|
||||
}
|
||||
sx += p.x;
|
||||
sy += p.y;
|
||||
++n;
|
||||
oldest_cmd = p.cmd;
|
||||
oldest_age = age;
|
||||
}
|
||||
if (n >= 2 && oldest_age >= c.confine_window_s - 0.5)
|
||||
{
|
||||
const double cx = sx / static_cast<double>(n);
|
||||
const double cy = sy / static_cast<double>(n);
|
||||
double radius = 0.0;
|
||||
for (std::size_t k = 1; k <= n; ++k)
|
||||
{
|
||||
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
|
||||
radius = std::max(radius, std::hypot(p.x - cx, p.y - cy));
|
||||
}
|
||||
region_radius_ = radius;
|
||||
const double cmd = cmd_accum_ - oldest_cmd;
|
||||
confined_ = radius < c.confine_radius &&
|
||||
cmd >= c.confine_cmd_factor * std::max(2.0 * radius, c.disp_min);
|
||||
}
|
||||
}
|
||||
}
|
||||
v.net_disp = net_disp_;
|
||||
v.wandering = wandering_;
|
||||
v.idle = idle_;
|
||||
v.confined = confined_;
|
||||
v.region_radius = region_radius_;
|
||||
|
||||
// Mẫu nặng mới: ghi vào ring nếu có cost hữu hạn. +inf (mất liên thông tạm) không ghi — không kết
|
||||
// luận từ mẫu thiếu.
|
||||
if (s.geometry_valid && s.cost_conclusive && s.reachable && std::isfinite(s.cost_to_go))
|
||||
{
|
||||
// Lật liên thông: cost đổi nhiều hơn chuyển động và độ dời pose bị loại từ mẫu nặng trước. Cú nhảy pose lặp
|
||||
// không xoá cửa sổ, nên cost đi theo nó cũng không phải một cú nhảy do mặt nạ free; giữ lại để đo eff.
|
||||
if (c.jump_reject > 0.0 && has_prev_heavy_ &&
|
||||
std::fabs(s.cost_to_go - prev_heavy_cost_) > c.jump_reject + (travel_total_ - prev_heavy_travel_) +
|
||||
(jump_dist_total_ - prev_heavy_jump_dist_))
|
||||
{
|
||||
clearWindow();
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
has_eff_low_ = true;
|
||||
eff_low_t_ = s.now;
|
||||
v.cost_jump = true;
|
||||
}
|
||||
has_prev_heavy_ = true;
|
||||
prev_heavy_cost_ = s.cost_to_go;
|
||||
prev_heavy_travel_ = travel_total_;
|
||||
prev_heavy_jump_dist_ = jump_dist_total_;
|
||||
ring_[ring_head_] = HeavySample{ s.now, s.cost_to_go, cmd_accum_ };
|
||||
ring_head_ = (ring_head_ + 1) % kRing;
|
||||
ring_count_ = std::min(ring_count_ + 1, kRing);
|
||||
|
||||
HeavySample old;
|
||||
if (oldestInWindow(s.now, old))
|
||||
{
|
||||
const double cmd = cmd_accum_ - old.cmd;
|
||||
v.cmd_window = cmd;
|
||||
if (cmd >= c.min_commanded)
|
||||
{
|
||||
v.eff_geo = (old.cost - s.cost_to_go) / cmd;
|
||||
}
|
||||
}
|
||||
// Lịch sử cho progressProven(): chỉ eff đo được mới là bằng chứng, theo cả hai chiều.
|
||||
if (!std::isnan(v.eff_geo))
|
||||
{
|
||||
if (v.eff_geo >= c.eff_off)
|
||||
{
|
||||
has_eff_ok_ = true;
|
||||
eff_ok_t_ = s.now;
|
||||
}
|
||||
else
|
||||
{
|
||||
has_eff_low_ = true;
|
||||
eff_low_t_ = s.now;
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool progress_proven = progressProven(s.now);
|
||||
v.progress_proven = progress_proven;
|
||||
|
||||
// Trượt: lệnh đi mà bánh không quay (vật thấp, bumper). Chỉ khi có v_meas.
|
||||
bool slipping = false;
|
||||
if (c.slip_on > 0.0 && std::isfinite(s.v_meas))
|
||||
{
|
||||
const bool slip_now = std::fabs(s.v_cmd) - std::fabs(s.v_meas) >= c.slip_on;
|
||||
if (slip_now)
|
||||
{
|
||||
if (!slip_seen_)
|
||||
{
|
||||
slip_seen_ = true;
|
||||
slip_since_ = s.now;
|
||||
}
|
||||
slipping = (s.now - slip_since_).toSec() >= c.slip_time;
|
||||
}
|
||||
else
|
||||
{
|
||||
slip_seen_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
const bool grace = has_plan_time_ && (s.now - plan_time_).toSec() < config_.grace_after_new_plan;
|
||||
const bool near_goal = std::isfinite(s.d_goal) && s.d_goal < c.goal_zone;
|
||||
if (grace || near_goal)
|
||||
{
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const bool eff_known = !std::isnan(v.eff_geo);
|
||||
const bool stalled = (eff_known && v.eff_geo < c.eff_on) || slipping;
|
||||
const bool cleared = eff_known && v.eff_geo >= c.eff_off && !slipping;
|
||||
if (stalled)
|
||||
{
|
||||
if (!stall_seen_)
|
||||
{
|
||||
stall_seen_ = true;
|
||||
stall_since_ = s.now;
|
||||
}
|
||||
if (!stall_fired_ && (s.now - stall_since_).toSec() >= c.confirm)
|
||||
{
|
||||
stall_fired_ = true;
|
||||
v.event = slipping ? "stall: wheels slip against the command" : "stall: cost_to_go not decreasing";
|
||||
}
|
||||
}
|
||||
else if (cleared)
|
||||
{
|
||||
if (stall_fired_)
|
||||
{
|
||||
v.event = "stall cleared: progress resumed";
|
||||
}
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
}
|
||||
// Còn lại (không đo được, hoặc eff trong vùng chết): giữ trạng thái — không kết luận ≠ hết kẹt.
|
||||
// Đứng yên suốt idle_window_s, hoặc đi nhiều mà bị giam trong vùng nhỏ suốt confine_window_s, là kẹt kể cả
|
||||
// khi geodesic không đo được hoặc đang lật dấu. Chỉ cổng giam vùng bị phủ quyết khi có bằng chứng tiến độ;
|
||||
// cổng đứng yên vẫn hoạt động vì cost_to_go có thể đổi do hình học costmap.
|
||||
if ((idle_ || (confined_ && !(c.progress_veto && progress_proven))) && !stall_fired_)
|
||||
{
|
||||
stall_fired_ = true;
|
||||
stall_seen_ = true;
|
||||
stall_since_ = s.now;
|
||||
v.event = idle_ ? "stall: no net displacement for the idle window"
|
||||
: "stall: confined to a small region while commanded";
|
||||
}
|
||||
|
||||
v.stall_detected = stall_fired_;
|
||||
if (!stall_fired_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Cổng đầu chặng, ngân sách replan, backoff sau lượt hỏng.
|
||||
bool muted = false;
|
||||
if (has_goal_ && cmd_accum_ - cmd_at_goal_ < c.min_commanded_since_goal)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
if (c.disp_min > 0.0)
|
||||
{
|
||||
// Cổng dịch chuyển thực thay ngân sách replan: cửa sổ vị trí đã bắt đầu lại ở plan mới, nên "sau detour
|
||||
// vẫn quần tại chỗ disp_window_s" mới được nổ lại; né tự do (dịch chuyển >= disp_min) không bao giờ nổ.
|
||||
if (!wandering_ && !idle_ && !confined_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
}
|
||||
else if (has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
if (has_stall_backoff_ && s.now < stall_backoff_until_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
v.stall_muted = muted;
|
||||
v.no_progress = !muted && c.action == "recover";
|
||||
}
|
||||
|
||||
void EnvMonitor::updateUnreachable(const EnvSample& s, EnvVerdict& v)
|
||||
{
|
||||
const EnvMonitorConfig::Unreachable& c = config_.unreachable;
|
||||
if (!c.enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Trạng thái chỉ đổi ở tick nặng có kết luận; verdict thì phải ra MỖI cycle từ trạng thái, nếu
|
||||
// không cờ nhấp nháy giữa hai tick 5 Hz và state machine 20 Hz thấy cờ bật/tắt.
|
||||
if (s.geometry_valid && s.cost_conclusive)
|
||||
{
|
||||
// Baseline của plan: mẫu kết luận đầu tiên sau khi nhận plan. Plan đã không liên thông ngay từ
|
||||
// đầu thì đó là chuyện của SBPL/planner đã lập nó — monitor không cãi trên cùng snapshot (R2).
|
||||
if (baseline_pending_)
|
||||
{
|
||||
baseline_pending_ = false;
|
||||
baseline_unreachable_ = !s.reachable;
|
||||
}
|
||||
if (s.reachable)
|
||||
{
|
||||
if (unreach_fired_)
|
||||
{
|
||||
v.event = "unreachable cleared: the exit is connected again";
|
||||
}
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
baseline_unreachable_ = false; // từ đây mất liên thông là chuyện mới
|
||||
}
|
||||
else
|
||||
{
|
||||
const bool grace = has_plan_time_ && (s.now - plan_time_).toSec() < config_.grace_after_new_plan;
|
||||
const bool clean = std::isfinite(s.edt_body_min) && s.edt_body_min >= c.clean_start_margin;
|
||||
if (baseline_unreachable_ || grace || !clean)
|
||||
{
|
||||
// Không tích: chưa phải "xấu đi", hoặc robot đã lọt vành (SBPL không có chỗ bắt đầu — việc
|
||||
// của kContact + controller_patience).
|
||||
unreach_seen_ = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!unreach_seen_)
|
||||
{
|
||||
unreach_seen_ = true;
|
||||
unreach_since_ = s.now;
|
||||
}
|
||||
if (!unreach_fired_ && (s.now - unreach_since_).toSec() >= c.static_on)
|
||||
{
|
||||
unreach_fired_ = true;
|
||||
v.event = "unreachable: no path to the plan exit inside the window";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
v.unreachable_detected = unreach_fired_;
|
||||
if (!unreach_fired_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
bool muted = false;
|
||||
if (has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
if (has_unreach_backoff_ && s.now < unreach_backoff_until_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
v.unreachable_muted = muted;
|
||||
v.path_blocked = !muted && c.action == "recover";
|
||||
}
|
||||
|
||||
void EnvMonitor::updateContact(const EnvSample& s, EnvVerdict& v)
|
||||
{
|
||||
const EnvMonitorConfig::Contact& c = config_.contact;
|
||||
if (!c.enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
double v_ref = std::fabs(s.v_cmd);
|
||||
if (std::isfinite(s.v_meas))
|
||||
{
|
||||
v_ref = std::max(v_ref, std::fabs(s.v_meas));
|
||||
}
|
||||
v.brake_dist = v_ref * v_ref / (2.0 * c.brake_decel);
|
||||
|
||||
if (!s.contact_conclusive || !s.costmap_current)
|
||||
{
|
||||
// Không biết thì không dừng, cũng không xoá chuỗi (cùng hợp đồng với guard cũ).
|
||||
v.brake = braking_; // đang phanh thì giữ phanh tới khi có bằng chứng ngược lại
|
||||
return;
|
||||
}
|
||||
if (standdown_)
|
||||
{
|
||||
// Đang đứng ra: không phanh, không cờ, không bao. Chỉ theo dõi điều kiện vũ trang lại.
|
||||
v.contact_standdown = true;
|
||||
if (std::isfinite(s.traj_contact_dist))
|
||||
{
|
||||
standdown_clean_streak_ = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
++standdown_clean_streak_;
|
||||
}
|
||||
const bool travelled = travel_total_ - standdown_mark_travel_ >= c.standdown_travel;
|
||||
if (travelled || standdown_clean_streak_ >= c.release_confirm_cycles)
|
||||
{
|
||||
standdown_ = false;
|
||||
standdown_clean_streak_ = 0;
|
||||
v.contact_standdown = false;
|
||||
v.event = travelled ? "contact: re-armed after moving on" : "contact: re-armed, the trajectory is clear";
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!std::isfinite(s.traj_contact_dist))
|
||||
{
|
||||
contact_streak_ = 0;
|
||||
if (braking_ && ++release_streak_ < c.release_confirm_cycles)
|
||||
{
|
||||
// Một mẫu sạch chưa là sạch: local planner đổi quỹ đạo mỗi cycle, sạch 1 cycle rồi chạm lại là
|
||||
// chuyện thường (run 5/9 22:35: 4 lần nhả/phanh trong 3 s). Giữ phanh và cờ tới khi sạch liên tiếp.
|
||||
v.brake = true;
|
||||
v.collision = contact_fired_ && c.action == "recover";
|
||||
return;
|
||||
}
|
||||
if (braking_ || contact_fired_)
|
||||
{
|
||||
v.event = "contact cleared: the trajectory is free again";
|
||||
}
|
||||
braking_ = false;
|
||||
release_streak_ = 0;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Bao tốc độ: |v| <= sqrt(2 a (d - margin)) để luôn còn dừng được trên đất sạch.
|
||||
// Bao giữ thêm envelope_margin so với ngưỡng phanh: lệnh nằm trên bao thì quãng phanh còn dư đúng chừng
|
||||
// đó, nhiễu quỹ đạo vài cm không đẩy sang "sắp chạm". Trong margin thì 0; giữa margin và margin+dư thì bò
|
||||
// min_speed.
|
||||
if (c.envelope)
|
||||
{
|
||||
if (s.traj_contact_dist <= c.clean_start_margin)
|
||||
{
|
||||
v.v_cap = 0.0;
|
||||
}
|
||||
else
|
||||
{
|
||||
const double room = s.traj_contact_dist - c.clean_start_margin - c.envelope_margin;
|
||||
v.v_cap = std::max(c.min_speed, room > 0.0 ? std::sqrt(2.0 * c.brake_decel * room) : 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Xoay tại chỗ / bò mà monitor chưa phanh: quỹ đạo local planner lúc này là một cú xoay, góc thân
|
||||
// quét vào ô kề bên là chuyện của controller (nó tự kiểm footprint), không phải bài toán quãng phanh.
|
||||
// Phanh ở đây là chặn robot xoay ra khỏi vật đang kề mũi, rồi 1 s sau giơ cờ và gọi detour từ đúng
|
||||
// chỗ đứng — vòng churn đầu chặng của guard cũ (mission 5/6 shadow 5/9). Đã phanh rồi thì vẫn xét
|
||||
// tiếp để "kề mũi đứng yên" còn nổ được.
|
||||
double v_intent = v_ref;
|
||||
if (std::isfinite(s.v_controller))
|
||||
{
|
||||
v_intent = std::max(v_intent, std::fabs(s.v_controller));
|
||||
}
|
||||
if (v_intent < c.min_check_speed && !braking_)
|
||||
{
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Hai câu hỏi khác nhau:
|
||||
// - "sắp chạm" = còn dừng kịp không (theo quãng phanh) -> PHANH. Đứng lại rồi thì quãng phanh về 0
|
||||
// và câu này tự hết đúng, robot được bò tiếp dưới bao tốc độ.
|
||||
// - "đang kề vật" = tiếp xúc trong đúng clean_start_margin bất kể tốc độ -> nếu còn đó đủ
|
||||
// trigger_static_time thì vật đứng yên trước mũi, không phải người đi qua -> giơ CỜ.
|
||||
// Bao tốc độ đặt lệnh đúng lên biên v_cap = sqrt(2a(d - margin)), tức d - quãng phanh == margin: nếu
|
||||
// "sắp chạm" là <= thì mỗi lần bao kẹp xong là phanh, nhả, kẹp, phanh (chattering 4 cycle). Chỉ phanh
|
||||
// khi vượt bao quá 1 mm — lệnh nằm trên bao là đang giảm tốc đúng luật, không phải sắp chạm.
|
||||
// Trong margin thì bao đã là 0: đó là một cú dừng của monitor dù quãng phanh bằng 0 — phải được gọi
|
||||
// là phanh để có sự kiện, để giữ 0 tức thì qua trọng tài và để cổng xoay không nuốt nó.
|
||||
constexpr double kEnvelopeTol = 1e-3; // [m]
|
||||
// Đã kề thì còn kề tới margin + release_hysteresis: quỹ đạo nhảy 0,08 <-> 0,25 m quanh margin không
|
||||
// được reset đồng hồ giơ cờ, cũng không được nhả phanh.
|
||||
const double close_limit = c.clean_start_margin + (contact_close_ ? c.release_hysteresis : 0.0);
|
||||
const bool close = s.traj_contact_dist <= close_limit;
|
||||
const bool imminent = close || s.traj_contact_dist - v.brake_dist < c.clean_start_margin - kEnvelopeTol;
|
||||
v.contact_imminent = imminent;
|
||||
if (imminent)
|
||||
{
|
||||
release_streak_ = 0;
|
||||
++contact_streak_;
|
||||
if (!braking_ && contact_streak_ >= c.confirm_cycles)
|
||||
{
|
||||
if (c.standdown_min_travel > 0.0 && detour_from_contact_ &&
|
||||
travel_total_ - detour_mark_travel_ < c.standdown_min_travel)
|
||||
{
|
||||
// Vừa detour từ đúng chỗ này vì chính cú chạm này, robot chưa rời chỗ: phanh + cờ lần nữa chỉ lặp
|
||||
// lại churn (3 detour rồi ABORT). Nhường controller — nó là lưới an toàn duy nhất tới khi robot đi
|
||||
// được standdown_travel hoặc quỹ đạo sạch.
|
||||
standdown_ = true;
|
||||
standdown_mark_travel_ = travel_total_;
|
||||
standdown_clean_streak_ = 0;
|
||||
detour_from_contact_ = false;
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
v.contact_standdown = true;
|
||||
v.contact_imminent = false;
|
||||
v.v_cap = std::numeric_limits<double>::infinity();
|
||||
v.event = "contact: standing down — the detour from this spot did not move the robot, the controller "
|
||||
"is the only safety net until it travels on";
|
||||
return;
|
||||
}
|
||||
braking_ = true;
|
||||
v.event = "contact: braking to zero";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
contact_streak_ = 0;
|
||||
if (braking_ && ++release_streak_ >= c.release_confirm_cycles)
|
||||
{
|
||||
braking_ = false;
|
||||
release_streak_ = 0;
|
||||
v.event = "contact receded: releasing the brake";
|
||||
}
|
||||
}
|
||||
v.brake = braking_;
|
||||
|
||||
if (close)
|
||||
{
|
||||
if (!contact_close_)
|
||||
{
|
||||
contact_close_ = true;
|
||||
close_since_ = s.now;
|
||||
}
|
||||
if (!contact_fired_ && (s.now - close_since_).toSec() >= c.trigger_static_time)
|
||||
{
|
||||
contact_fired_ = true;
|
||||
v.event = "contact persists while stopped: asking for a replan";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (contact_fired_)
|
||||
{
|
||||
v.event = "contact cleared: the obstacle moved away";
|
||||
}
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
}
|
||||
v.collision = contact_fired_ && c.action == "recover";
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -121,7 +121,7 @@ bool EnvLogger::open(const EnvLoggerConfig& config, std::string& error)
|
||||
return true;
|
||||
}
|
||||
|
||||
void EnvLogger::record(const robot::Time& now, const EnvSample& s, const EnvVerdict& v,
|
||||
void EnvLogger::record(const robot::Time& now, const env_monitor_core::EnvSample& s, const env_monitor_core::EnvVerdict& v,
|
||||
const EnvGeometry* g, const char* state, std::uint64_t mission_id,
|
||||
bool used_local_plan)
|
||||
{
|
||||
|
||||
@@ -482,6 +482,17 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
||||
// Ràng buộc thứ tự khởi tạo — xem doc của lớp. Con số này KHÔNG đến từ YAML.
|
||||
config_.state_machine.recovery_behavior_count = recovery_.behaviorCount();
|
||||
|
||||
// --- 4b. EnvMonitor ----------------------------------------------------------------------------
|
||||
//
|
||||
// Lõi và các detector plugin tự đọc khối `env_monitor` dưới root_nh (gói env_monitor_core). Detector không nạp
|
||||
// được (thiếu library_path, lệch ABI) đã được log LỖI và bỏ qua bên trong; tham số sai thì từ chối khởi động,
|
||||
// như trước khi tách gói.
|
||||
if (!env_monitor_.initialize(root_nh, error))
|
||||
{
|
||||
error = "invalid env_monitor parameters: " + error;
|
||||
return false;
|
||||
}
|
||||
|
||||
// --- 5. Action ---------------------------------------------------------------------------------
|
||||
action_.setClock(&clock_);
|
||||
action_.setNamespace(config_.action_namespace);
|
||||
@@ -642,6 +653,7 @@ ControlLoopDeps NavigationRuntime::deps()
|
||||
deps.action = &action_;
|
||||
deps.costmap_status = &costmap_status_;
|
||||
deps.environment = &environment_;
|
||||
deps.env_monitor = &env_monitor_;
|
||||
deps.components = &components_;
|
||||
return deps;
|
||||
}
|
||||
|
||||
@@ -111,6 +111,8 @@ const char* toString(RecoveryTrigger trigger)
|
||||
return "off_path";
|
||||
case RecoveryTrigger::kCollision:
|
||||
return "collision";
|
||||
case RecoveryTrigger::kDetector:
|
||||
return "detector";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
@@ -131,8 +133,51 @@ const std::vector<std::size_t>& RecoveryRoutes::forTrigger(RecoveryTrigger trigg
|
||||
return off_path;
|
||||
case RecoveryTrigger::kCollision:
|
||||
return collision;
|
||||
case RecoveryTrigger::kDetector:
|
||||
break; // route của detector đi theo tên (find), không theo trigger
|
||||
}
|
||||
static const std::vector<std::size_t> kNone;
|
||||
return kNone;
|
||||
}
|
||||
|
||||
const std::vector<std::size_t>* RecoveryRoutes::find(const std::string& name) const
|
||||
{
|
||||
if (name == "planning_failed")
|
||||
{
|
||||
return &planning_failed;
|
||||
}
|
||||
if (name == "controlling_failed")
|
||||
{
|
||||
return &controlling_failed;
|
||||
}
|
||||
if (name == "oscillation")
|
||||
{
|
||||
return &oscillation;
|
||||
}
|
||||
if (name == "path_blocked")
|
||||
{
|
||||
return &path_blocked;
|
||||
}
|
||||
if (name == "off_path")
|
||||
{
|
||||
return &off_path;
|
||||
}
|
||||
if (name == "collision")
|
||||
{
|
||||
return &collision;
|
||||
}
|
||||
const auto it = named.find(name);
|
||||
return it == named.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
void RecoveryRoutes::fillLegacy(std::size_t behavior_count)
|
||||
{
|
||||
for (std::size_t index = 0; index < behavior_count; ++index)
|
||||
{
|
||||
planning_failed.push_back(index);
|
||||
controlling_failed.push_back(index);
|
||||
oscillation.push_back(index);
|
||||
}
|
||||
return planning_failed;
|
||||
}
|
||||
|
||||
bool RecoveryRoutes::empty() const
|
||||
|
||||
@@ -32,6 +32,9 @@ recovery_core::RecoveryTrigger toCoreTrigger(RecoveryTrigger trigger)
|
||||
return recovery_core::RecoveryTrigger::kPathBlocked;
|
||||
case RecoveryTrigger::kOffPath:
|
||||
return recovery_core::RecoveryTrigger::kOffPath;
|
||||
case RecoveryTrigger::kCollision:
|
||||
case RecoveryTrigger::kDetector:
|
||||
break; // recovery_core chưa có hai lý do này: kUnspecified (chỉ dùng để log)
|
||||
}
|
||||
return recovery_core::RecoveryTrigger::kUnspecified;
|
||||
}
|
||||
@@ -220,6 +223,7 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
return false;
|
||||
};
|
||||
|
||||
std::vector<std::string> named_keys;
|
||||
for (const auto& entry : configured_routes)
|
||||
{
|
||||
if (!entry.first.IsScalar())
|
||||
@@ -230,8 +234,7 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
const std::string key = entry.first.as<std::string>();
|
||||
if (!is_expected_key(key))
|
||||
{
|
||||
error = routes_key + " has unsupported trigger '" + key + "'";
|
||||
return false;
|
||||
named_keys.push_back(key); // route theo detector (ví dụ `intrusion`): detector trỏ tới theo tên
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,6 +253,8 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
return &routes_.off_path;
|
||||
case RecoveryTrigger::kCollision:
|
||||
return &routes_.collision;
|
||||
case RecoveryTrigger::kDetector:
|
||||
break;
|
||||
}
|
||||
return &routes_.planning_failed;
|
||||
};
|
||||
@@ -262,9 +267,8 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
// (2026-08-05): cursor chỉ reset khi robot đi được quá oscillation_distance, nhưng giữa hai lần
|
||||
// monitor bắn robot chỉ nhích được ~0.1-0.15 m, nên route không lặp thì cạn ngay sau một cặp
|
||||
// [detour, wait] dù vật cản sắp vào tầm. Route vẫn hữu hạn — bế tắc thật vẫn ABORT được.
|
||||
const auto resolve_route = [&](const char* trigger_name, RecoveryTrigger trigger,
|
||||
const auto resolve_route = [&](const char* trigger_name, std::vector<std::size_t>* resolved,
|
||||
const YAML::Node& route_node) {
|
||||
std::vector<std::size_t>* resolved = route_for(trigger);
|
||||
resolved->clear();
|
||||
|
||||
for (const YAML::Node& behavior_node : route_node)
|
||||
@@ -300,7 +304,7 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!resolve_route(expected.first, expected.second, route_node))
|
||||
if (!resolve_route(expected.first, route_for(expected.second), route_node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -328,7 +332,7 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!resolve_route(optional.first, optional.second, route_node))
|
||||
if (!resolve_route(optional.first, route_for(optional.second), route_node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -343,6 +347,22 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
}
|
||||
}
|
||||
|
||||
for (const std::string& key : named_keys)
|
||||
{
|
||||
const YAML::Node route_node = configured_routes[key];
|
||||
if (!route_node.IsSequence())
|
||||
{
|
||||
error = routes_key + "/" + key + " must be a YAML sequence";
|
||||
return false;
|
||||
}
|
||||
if (!resolve_route(key.c_str(), &routes_.named[key], route_node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
robot::log_info("[move_base2] RecoveryRunner: detector route '%s' resolved with %zu behavior(s).", key.c_str(),
|
||||
routes_.named[key].size());
|
||||
}
|
||||
|
||||
robot::log_info("[move_base2] RecoveryRunner: routes resolved: planning=%zu controlling=%zu "
|
||||
"oscillation=%zu path_blocked=%zu off_path=%zu collision=%zu.",
|
||||
routes_.planning_failed.size(), routes_.controlling_failed.size(),
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace
|
||||
{
|
||||
/// Ô cursor 0..2 = trigger riêng của state machine (planning_failed, controlling_failed, oscillation); 3 + i = detector i.
|
||||
constexpr std::size_t kOwnSlots = 3;
|
||||
} // namespace
|
||||
|
||||
// ================================================================================================
|
||||
// StateMachineConfig
|
||||
@@ -110,6 +115,20 @@ bool StateMachineConfig::validate(std::string& error) const
|
||||
return false;
|
||||
}
|
||||
|
||||
if (detector_routes.size() > 32)
|
||||
{
|
||||
error = "at most 32 detector routes (StateMachineInput::detector_fired is 32 bits)";
|
||||
return false;
|
||||
}
|
||||
for (const DetectorRoute& d : detector_routes)
|
||||
{
|
||||
if (d.name.empty() || !indices_valid(d.route))
|
||||
{
|
||||
error = "detector route '" + d.name + "' has no name or references a behavior that was not loaded";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -157,6 +176,11 @@ std::string StateMachineConfig::describe() const
|
||||
<< " off_path=" << recovery_routes.off_path.size()
|
||||
<< " collision=" << recovery_routes.collision.size() << '\n';
|
||||
}
|
||||
for (const DetectorRoute& d : detector_routes)
|
||||
{
|
||||
out << " detector " << d.name << " : route=" << toString(d.trigger) << " size=" << d.route.size()
|
||||
<< (d.sequence ? " sequence" : " step") << (d.lock_on_exhausted ? " lock" : " abort") << '\n';
|
||||
}
|
||||
return out.str();
|
||||
}
|
||||
|
||||
@@ -173,12 +197,7 @@ bool StateMachine::configure(const StateMachineConfig& config, std::string& erro
|
||||
// chỉ xử lý route đã resolve.
|
||||
if (config_.recovery_routes.empty())
|
||||
{
|
||||
for (std::size_t index = 0; index < config_.recovery_behavior_count; ++index)
|
||||
{
|
||||
config_.recovery_routes.planning_failed.push_back(index);
|
||||
config_.recovery_routes.controlling_failed.push_back(index);
|
||||
config_.recovery_routes.oscillation.push_back(index);
|
||||
}
|
||||
config_.recovery_routes.fillLegacy(config_.recovery_behavior_count);
|
||||
}
|
||||
|
||||
if (!config_.validate(error))
|
||||
@@ -187,6 +206,8 @@ bool StateMachine::configure(const StateMachineConfig& config, std::string& erro
|
||||
return false;
|
||||
}
|
||||
|
||||
recovery_route_cursors_.assign(kOwnSlots + config_.detector_routes.size(), 0);
|
||||
monitor_trigger_suppressed_.assign(kOwnSlots + config_.detector_routes.size(), 0);
|
||||
initialized_ = true;
|
||||
reset();
|
||||
return true;
|
||||
@@ -204,8 +225,10 @@ void StateMachine::reset()
|
||||
recovery_index_ = 0;
|
||||
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
state_before_recovery_ = NavigationState::kPlanning;
|
||||
recovery_route_cursors_.fill(0);
|
||||
monitor_trigger_suppressed_.fill(false);
|
||||
std::fill(recovery_route_cursors_.begin(), recovery_route_cursors_.end(), 0);
|
||||
std::fill(monitor_trigger_suppressed_.begin(), monitor_trigger_suppressed_.end(), 0);
|
||||
active_slot_ = 0;
|
||||
chain_active_ = false;
|
||||
has_path_reset_mark_ = false;
|
||||
travel_at_last_path_reset_ = 0.0;
|
||||
planning_retries_ = 0;
|
||||
@@ -242,6 +265,7 @@ void StateMachine::beginPlanningCycle(const robot::Time& now)
|
||||
namespace
|
||||
{
|
||||
/// @brief Chỉ số cursor của một trigger. `switch` đầy đủ để compiler bắt khi enum thêm giá trị.
|
||||
/// Ô cursor của trigger riêng của state machine. Detector i dùng ô kOwnSlots + i.
|
||||
std::size_t cursorSlot(RecoveryTrigger trigger)
|
||||
{
|
||||
switch (trigger)
|
||||
@@ -253,46 +277,63 @@ std::size_t cursorSlot(RecoveryTrigger trigger)
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return 2;
|
||||
case RecoveryTrigger::kPathBlocked:
|
||||
return 3;
|
||||
case RecoveryTrigger::kOffPath:
|
||||
return 4;
|
||||
case RecoveryTrigger::kCollision:
|
||||
return 5;
|
||||
case RecoveryTrigger::kDetector:
|
||||
break; // chỉ detector giơ các lý do này; chúng đi escalateDetector với ô riêng
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// Lý do chuyển state (chuỗi hằng, sống suốt chương trình) theo nhãn route của detector — giữ nguyên chữ cũ.
|
||||
const char* detectorReason(RecoveryTrigger trigger)
|
||||
{
|
||||
switch (trigger)
|
||||
{
|
||||
case RecoveryTrigger::kCollision:
|
||||
return "the body is about to hit an obstacle";
|
||||
case RecoveryTrigger::kPathBlocked:
|
||||
return "the path ahead is blocked";
|
||||
case RecoveryTrigger::kOffPath:
|
||||
return "the robot drifted off the plan";
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return "no progress along the plan";
|
||||
case RecoveryTrigger::kPlanningFailed:
|
||||
case RecoveryTrigger::kControllingFailed:
|
||||
case RecoveryTrigger::kDetector:
|
||||
break;
|
||||
}
|
||||
return "a detector asked for recovery";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger)
|
||||
const std::vector<std::size_t>& StateMachine::activeRoute() const
|
||||
{
|
||||
return recovery_route_cursors_[cursorSlot(trigger)];
|
||||
}
|
||||
|
||||
const std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger) const
|
||||
{
|
||||
return recovery_route_cursors_[cursorSlot(trigger)];
|
||||
}
|
||||
|
||||
bool StateMachine::isMonitorTrigger(RecoveryTrigger trigger)
|
||||
{
|
||||
return trigger == RecoveryTrigger::kPathBlocked || trigger == RecoveryTrigger::kOffPath ||
|
||||
trigger == RecoveryTrigger::kCollision;
|
||||
}
|
||||
|
||||
void StateMachine::suppressMonitorTrigger(RecoveryTrigger trigger, StateMachineOutput& out)
|
||||
{
|
||||
monitor_trigger_suppressed_[cursorSlot(trigger)] = true;
|
||||
out.recovery_trigger = trigger;
|
||||
out.monitor_trigger_suppressed = true;
|
||||
return active_slot_ >= kOwnSlots ? config_.detector_routes[active_slot_ - kOwnSlots].route
|
||||
: config_.recovery_routes.forTrigger(active_recovery_trigger_);
|
||||
}
|
||||
|
||||
void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time& now,
|
||||
const char* reason, StateMachineOutput& out)
|
||||
{
|
||||
const std::vector<std::size_t>& route = config_.recovery_routes.forTrigger(trigger);
|
||||
const std::size_t cursor = recoveryRouteCursor(trigger);
|
||||
escalate(cursorSlot(trigger), config_.recovery_routes.forTrigger(trigger), trigger, false, -1, now, reason, out);
|
||||
}
|
||||
|
||||
void StateMachine::escalateDetector(std::size_t index, const robot::Time& now, StateMachineOutput& out)
|
||||
{
|
||||
const DetectorRoute& d = config_.detector_routes[index];
|
||||
escalate(kOwnSlots + index, d.route, d.trigger, d.lock_on_exhausted, static_cast<int>(index), now,
|
||||
detectorReason(d.trigger), out);
|
||||
}
|
||||
|
||||
void StateMachine::escalate(std::size_t slot, const std::vector<std::size_t>& route, RecoveryTrigger trigger,
|
||||
bool lock, int detector, const robot::Time& now, const char* reason,
|
||||
StateMachineOutput& out)
|
||||
{
|
||||
const std::size_t cursor = recovery_route_cursors_[slot];
|
||||
|
||||
out.recovery_trigger = trigger;
|
||||
out.recovery_detector = detector;
|
||||
out.recovery_route_cursor = cursor;
|
||||
out.recovery_route_size = route.size();
|
||||
|
||||
@@ -307,9 +348,11 @@ void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time
|
||||
//
|
||||
// Khoá trigger lại cho tới khi có tiến độ thật: không khoá thì monitor bắn lại sau mỗi
|
||||
// confirm_time và mỗi lượt đốt vài trăm ms SBPL trên control thread mà không đổi được gì.
|
||||
if (isMonitorTrigger(trigger))
|
||||
// Từ 26/11 "dự báo" là thuộc tính của detector (`on_exhausted: lock`), không của tên trigger.
|
||||
if (lock)
|
||||
{
|
||||
suppressMonitorTrigger(trigger, out);
|
||||
monitor_trigger_suppressed_[slot] = 1;
|
||||
out.monitor_trigger_suppressed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -319,6 +362,10 @@ void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time
|
||||
}
|
||||
|
||||
active_recovery_trigger_ = trigger;
|
||||
active_slot_ = slot;
|
||||
chain_active_ = detector >= 0 && config_.detector_routes[static_cast<std::size_t>(detector)].sequence;
|
||||
chain_pos_ = cursor;
|
||||
chain_has_path_ = false;
|
||||
|
||||
// Nhớ state đã leo thang: nó quyết định đường quay về khi behavior kết thúc. Phải chụp TRƯỚC
|
||||
// enter() bên dưới — sau đó state_ đã là kRecovering.
|
||||
@@ -347,7 +394,8 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
|
||||
recovery_index_ = 0;
|
||||
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
state_before_recovery_ = NavigationState::kPlanning;
|
||||
recovery_route_cursors_.fill(0);
|
||||
std::fill(recovery_route_cursors_.begin(), recovery_route_cursors_.end(), 0);
|
||||
chain_active_ = false;
|
||||
request_has_goal_ = in.pending_request_has_goal;
|
||||
action_count_ = in.pending_request_action_count;
|
||||
action_index_ = 0;
|
||||
@@ -375,7 +423,7 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
|
||||
last_valid_control_ = in.now;
|
||||
last_oscillation_reset_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
monitor_trigger_suppressed_.fill(false);
|
||||
std::fill(monitor_trigger_suppressed_.begin(), monitor_trigger_suppressed_.end(), 0);
|
||||
has_path_reset_mark_ = false; // origin đo quãng đường đặt lại ngay dưới -> mốc cũ vô nghĩa
|
||||
travel_at_last_path_reset_ = 0.0;
|
||||
out.reset_oscillation_origin = true;
|
||||
@@ -632,7 +680,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
beginPlanningCycle(in.now);
|
||||
// Tuyến khác thì hình thế khác — trigger giám sát tuyến được thử lại ngay, không phải chờ
|
||||
// đủ oscillation_distance.
|
||||
monitor_trigger_suppressed_.fill(false);
|
||||
std::fill(monitor_trigger_suppressed_.begin(), monitor_trigger_suppressed_.end(), 0);
|
||||
}
|
||||
|
||||
// Đi đủ xa thì không còn bị coi là quẩn — đặt lại cả đồng hồ lẫn mốc đo quãng đường.
|
||||
@@ -646,12 +694,12 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// gặp hai sự cố cách nhau nửa giờ sẽ ABORT thẳng ở sự cố thứ hai vì route đã cạn từ sự cố
|
||||
// đầu. Mốc "đi được quá oscillation_distance" là thứ vòng lặp kẹt-recovery-nhích-kẹt không
|
||||
// làm giả được, nên tính hữu hạn của chuỗi recovery vẫn giữ nguyên.
|
||||
recovery_route_cursors_.fill(0);
|
||||
std::fill(recovery_route_cursors_.begin(), recovery_route_cursors_.end(), 0);
|
||||
|
||||
// Cùng mốc tiến độ mở khoá trigger giám sát tuyến (2026-08-05e): robot đã đi được nửa mét
|
||||
// nghĩa là hình thế đã khác, thử vòng lại là đáng. Đứng im vì bị chắn thì không bao giờ tới
|
||||
// đây — đúng ý đồ: không đốt SBPL vào một tình huống chưa đổi.
|
||||
monitor_trigger_suppressed_.fill(false);
|
||||
std::fill(monitor_trigger_suppressed_.begin(), monitor_trigger_suppressed_.end(), 0);
|
||||
|
||||
// Origin vừa đặt lại nên travelled_since_oscillation_reset sẽ về 0 ở cycle sau; mốc của
|
||||
// recovery_reset_min_travel phải đi theo, nếu không hiệu số âm sẽ khoá nạp lại vĩnh viễn.
|
||||
@@ -690,42 +738,54 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
//
|
||||
// Trigger đang bị KHOÁ (lượt trước đã hết đường vòng, robot chưa đi đủ oscillation_distance)
|
||||
// thì bỏ qua hẳn nhánh này: bám tiếp plan cũ, để controller_patience làm việc của nó.
|
||||
const bool collision_open =
|
||||
in.collision && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kCollision)];
|
||||
const bool blocked_open =
|
||||
in.path_blocked && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kPathBlocked)];
|
||||
const bool off_path_open =
|
||||
in.off_path && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kOffPath)];
|
||||
if (collision_open || blocked_open || off_path_open)
|
||||
// Từ 26/11: nhóm này là các detector `on_exhausted: lock`, xét theo thứ tự danh sách detector (mặc định
|
||||
// contact > unreachable — đúng collision > path_blocked ở trên). Chỉ detector mở đầu tiên được xét mỗi cycle.
|
||||
bool forecast_escalated = false;
|
||||
for (std::size_t i = 0; i < config_.detector_routes.size(); ++i)
|
||||
{
|
||||
const RecoveryTrigger trigger = collision_open ? RecoveryTrigger::kCollision
|
||||
: blocked_open ? RecoveryTrigger::kPathBlocked
|
||||
: RecoveryTrigger::kOffPath;
|
||||
const bool open = config_.detector_routes[i].lock_on_exhausted && ((in.detector_fired >> i) & 1u) != 0 &&
|
||||
!monitor_trigger_suppressed_[kOwnSlots + i];
|
||||
if (!open)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
out.stop_planner = true;
|
||||
escalateToRecovery(trigger, in.now,
|
||||
collision_open ? "the body is about to hit an obstacle"
|
||||
: blocked_open ? "the path ahead is blocked"
|
||||
: "the robot drifted off the plan",
|
||||
out);
|
||||
// Hết đường vòng: escalateToRecovery đã khoá trigger thay vì ABORT — không đổi state, chạy
|
||||
// tiếp xuống nhánh sinh lệnh của cycle này để robot không mất một nhịp điều khiển.
|
||||
if (!out.monitor_trigger_suppressed)
|
||||
escalateDetector(i, in.now, out);
|
||||
// Hết đường vòng: escalate đã khoá trigger thay vì ABORT — không đổi state, chạy tiếp xuống nhánh sinh
|
||||
// lệnh của cycle này để robot không mất một nhịp điều khiển.
|
||||
if (out.monitor_trigger_suppressed)
|
||||
{
|
||||
out.stop_planner = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
forecast_escalated = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
out.stop_planner = false;
|
||||
if (forecast_escalated)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (controller == ControllerFeedback::kCommandValid)
|
||||
{
|
||||
last_valid_control_ = in.now;
|
||||
|
||||
// kStall (EnvMonitor): controller vẫn ra lệnh hợp lệ nhưng robot không đi được đâu.
|
||||
if (in.no_progress)
|
||||
// kStall (EnvMonitor) và mọi detector `on_exhausted: abort`: controller vẫn ra lệnh hợp lệ nhưng robot
|
||||
// không đi được đâu. Theo thứ tự danh sách detector; cạn route là ABORT.
|
||||
bool escalated = false;
|
||||
for (std::size_t i = 0; i < config_.detector_routes.size() && !escalated; ++i)
|
||||
{
|
||||
if (!config_.detector_routes[i].lock_on_exhausted && ((in.detector_fired >> i) & 1u) != 0)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
escalateToRecovery(RecoveryTrigger::kOscillation, in.now, "no progress along the plan",
|
||||
out);
|
||||
escalateDetector(i, in.now, out);
|
||||
escalated = true;
|
||||
}
|
||||
}
|
||||
if (escalated)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -818,6 +878,32 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
|
||||
if (in.recovery == RecoveryFeedback::kSucceeded || in.recovery == RecoveryFeedback::kFailed)
|
||||
{
|
||||
// route_mode sequence (chốt 26/11): một lần nổ chạy HẾT route. Behavior hỏng hay nộp path giữa chừng thì
|
||||
// vẫn chạy tiếp behavior kế; path mới nhất được áp khi cả chuỗi xong (ControlLoop giữ nó tới lúc đó).
|
||||
if (chain_active_)
|
||||
{
|
||||
chain_has_path_ = chain_has_path_ || (in.recovery == RecoveryFeedback::kSucceeded &&
|
||||
in.planner == PlannerFeedback::kPlanReady);
|
||||
const std::vector<std::size_t>& chain_route = activeRoute();
|
||||
if (chain_pos_ + 1 < chain_route.size())
|
||||
{
|
||||
++chain_pos_;
|
||||
recovery_index_ = chain_route[chain_pos_];
|
||||
out.start_recovery = true;
|
||||
out.recovery_index = recovery_index_;
|
||||
out.recovery_trigger = active_recovery_trigger_;
|
||||
out.recovery_detector = static_cast<int>(active_slot_ - kOwnSlots);
|
||||
out.recovery_chain_continues = true;
|
||||
break;
|
||||
}
|
||||
out.recovery_chain_finished = true;
|
||||
out.recovery_chain_has_path = chain_has_path_;
|
||||
out.recovery_chain_last_failed = in.recovery == RecoveryFeedback::kFailed;
|
||||
}
|
||||
// Từ đây cả chuỗi tính như MỘT behavior vừa xong: một lượt cursor, cùng ngoại lệ nạp lại khi có path mới.
|
||||
const bool chain = chain_active_;
|
||||
chain_active_ = false;
|
||||
|
||||
// Behavior chạy xong. Lỗi kế tiếp sẽ dùng behavior kế tiếp trong route; hết behavior thì
|
||||
// ABORTED.
|
||||
//
|
||||
@@ -836,9 +922,10 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// đó không giải quyết sự cố gì, nên nó ăn vào ngân sách như một lần thất bại: route cạn ->
|
||||
// mute (05e) -> guard vẫn báo no_valid_command -> controller_patience -> controlling_failed
|
||||
// -> cạn -> ABORT có lý do. Có dịch chuyển thật (0.45 m của ca 08-05) thì vẫn nạp lại như cũ.
|
||||
const bool recovered_with_new_path = in.recovery == RecoveryFeedback::kSucceeded &&
|
||||
in.planner == PlannerFeedback::kPlanReady;
|
||||
std::size_t& cursor = recoveryRouteCursor(active_recovery_trigger_);
|
||||
const bool recovered_with_new_path =
|
||||
chain ? chain_has_path_
|
||||
: in.recovery == RecoveryFeedback::kSucceeded && in.planner == PlannerFeedback::kPlanReady;
|
||||
std::size_t& cursor = recovery_route_cursors_[active_slot_];
|
||||
bool refill = false;
|
||||
if (recovered_with_new_path)
|
||||
{
|
||||
@@ -855,18 +942,22 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
out.recovery_reset_denied = true;
|
||||
out.recovery_reset_travel = std::max(0.0, travelled);
|
||||
out.recovery_trigger = active_recovery_trigger_; // để bên gọi log đúng route bị trừ
|
||||
out.recovery_detector = active_slot_ >= kOwnSlots ? static_cast<int>(active_slot_ - kOwnSlots) : -1;
|
||||
}
|
||||
}
|
||||
const std::vector<std::size_t>& route = activeRoute();
|
||||
if (refill)
|
||||
{
|
||||
cursor = 0;
|
||||
}
|
||||
else if (chain)
|
||||
{
|
||||
cursor = route.size(); // cả chuỗi là một lượt: lần nổ sau coi như route đã cạn
|
||||
}
|
||||
else
|
||||
{
|
||||
++cursor;
|
||||
}
|
||||
const std::vector<std::size_t>& route =
|
||||
config_.recovery_routes.forTrigger(active_recovery_trigger_);
|
||||
recovery_index_ = cursor < route.size() ? route[cursor] : config_.recovery_behavior_count;
|
||||
|
||||
// Đường quay về (contract 2026-08-04b — tách replan khỏi recovery hoàn toàn):
|
||||
@@ -881,7 +972,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// việc riêng của replan nền theo `planner_frequency`.
|
||||
// Riêng khi leo thang từ kPlanning (mất pose lúc lập plan) thì chưa từng có plan —
|
||||
// quay về kPlanning như nhóm 2.
|
||||
const bool has_detour_path = in.planner == PlannerFeedback::kPlanReady;
|
||||
const bool has_detour_path = chain ? chain_has_path_ : in.planner == PlannerFeedback::kPlanReady;
|
||||
const bool old_plan_valid =
|
||||
active_recovery_trigger_ != RecoveryTrigger::kPlanningFailed &&
|
||||
state_before_recovery_ == NavigationState::kControlling;
|
||||
|
||||
@@ -207,6 +207,17 @@ BackUpRecovery:
|
||||
|
||||
# GhostRecovery cố ý KHÔNG khai library_path.
|
||||
|
||||
# --- Detector của EnvMonitor (gói env_monitor_core) -------------------------------------------
|
||||
# File này không có khối `env_monitor`: lõi dùng tham số mặc định và nạp 3 detector có sẵn, như trước khi tách gói.
|
||||
ContactDetector:
|
||||
library_path: libenv_monitor_core_contact_detector
|
||||
|
||||
StallDetector:
|
||||
library_path: libenv_monitor_core_stall_detector
|
||||
|
||||
UnreachableDetector:
|
||||
library_path: libenv_monitor_core_unreachable_detector
|
||||
|
||||
# --- Action handler cho action_runner_test -----------------------------------------------------
|
||||
actions:
|
||||
handlers:
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
#include <move_base2/control_loop.h>
|
||||
|
||||
#include "env_monitor_fixture.h"
|
||||
#include "fake_ports.h"
|
||||
|
||||
using move_base2::ControlLoop;
|
||||
@@ -99,8 +100,11 @@ public:
|
||||
deps_.action = &action_;
|
||||
deps_.costmap_status = &costmap_status_;
|
||||
deps_.environment = &environment_;
|
||||
deps_.env_monitor = &env_monitor_;
|
||||
|
||||
std::string error;
|
||||
EXPECT_TRUE(move_base2::testing::initEnvMonitor(env_monitor_, env_monitor_core::EnvMonitorConfig(), error))
|
||||
<< error;
|
||||
EXPECT_TRUE(loop_.configure(baseConfig(), deps_, error)) << error;
|
||||
}
|
||||
|
||||
@@ -145,6 +149,7 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
env_monitor_core::EnvMonitor env_monitor_; ///< trước loop_: loop_ giữ con trỏ tới nó
|
||||
ControlLoop loop_;
|
||||
ControlLoopDeps deps_;
|
||||
FakeClockPort clock_;
|
||||
|
||||
57
test/env_monitor_fixture.h
Normal file
57
test/env_monitor_fixture.h
Normal file
@@ -0,0 +1,57 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 tests — an EnvMonitor (env_monitor_core) built from an EnvMonitorConfig through the real YAML path:
|
||||
* the struct becomes the `env_monitor` block under a fresh namespace, the three built-in detectors are loaded as
|
||||
* .so from devel/lib, exactly as NavigationRuntime does.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef MOVE_BASE2_TEST_ENV_MONITOR_FIXTURE_H_
|
||||
#define MOVE_BASE2_TEST_ENV_MONITOR_FIXTURE_H_
|
||||
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
|
||||
#include <env_monitor_core/env_monitor.h>
|
||||
|
||||
#ifndef MOVE_BASE2_TEST_LIBRARY_DIR
|
||||
#error "MOVE_BASE2_TEST_LIBRARY_DIR must be defined by CMake"
|
||||
#endif
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace testing
|
||||
{
|
||||
|
||||
inline bool initEnvMonitor(env_monitor_core::EnvMonitor& monitor, const env_monitor_core::EnvMonitorConfig& config,
|
||||
std::string& error)
|
||||
{
|
||||
static int counter = 0;
|
||||
// devel/lib must win over a PNKX_NAV_CORE_LIBRARY_PATH left in the user's shell.
|
||||
setenv("PNKX_NAV_CORE_LIBRARY_PATH", MOVE_BASE2_TEST_LIBRARY_DIR, 1);
|
||||
robot::NodeHandle nh("move_base2_env_monitor_test_" + std::to_string(++counter));
|
||||
const char* const kLibraries[][2] = {
|
||||
{ "ContactDetector", "libenv_monitor_core_contact_detector" },
|
||||
{ "StallDetector", "libenv_monitor_core_stall_detector" },
|
||||
{ "UnreachableDetector", "libenv_monitor_core_unreachable_detector" },
|
||||
};
|
||||
for (const auto& lib : kLibraries)
|
||||
{
|
||||
YAML::Node node;
|
||||
node["library_path"] = lib[1];
|
||||
nh.setParam(lib[0], node);
|
||||
}
|
||||
nh.setParam("env_monitor", env_monitor_core::toYaml(config));
|
||||
return monitor.initialize(nh, error);
|
||||
}
|
||||
|
||||
} // namespace testing
|
||||
} // namespace move_base2
|
||||
|
||||
#endif // MOVE_BASE2_TEST_ENV_MONITOR_FIXTURE_H_
|
||||
File diff suppressed because it is too large
Load Diff
@@ -11,6 +11,8 @@
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <move_base2/core/state_machine.h>
|
||||
@@ -32,6 +34,38 @@ using move_base2::VelocitySource;
|
||||
namespace
|
||||
{
|
||||
|
||||
/// Bit của bốn detector mà các test dưới dùng, cùng nghĩa với bốn cờ cố định trước 26/11.
|
||||
enum LegacyDetector : std::uint32_t
|
||||
{
|
||||
kCollisionBit = 1u << 0, ///< contact -> route collision, khoá
|
||||
kBlockedBit = 1u << 1, ///< unreachable -> route path_blocked, khoá
|
||||
kOffPathBit = 1u << 2, ///< off_path -> route off_path, khoá
|
||||
kNoProgressBit = 1u << 3, ///< stall -> route oscillation, ABORT
|
||||
};
|
||||
|
||||
/// Bốn detector theo đúng thứ tự ưu tiên cũ (collision > path_blocked > off_path; stall riêng nhánh controller).
|
||||
void addLegacyDetectors(move_base2::StateMachineConfig& config)
|
||||
{
|
||||
if (config.recovery_routes.empty())
|
||||
{
|
||||
config.recovery_routes.fillLegacy(config.recovery_behavior_count);
|
||||
}
|
||||
const auto route = [](const char* name, const std::vector<std::size_t>& indices, bool lock, RecoveryTrigger trigger) {
|
||||
move_base2::DetectorRoute r;
|
||||
r.name = name;
|
||||
r.route = indices;
|
||||
r.lock_on_exhausted = lock;
|
||||
r.trigger = trigger;
|
||||
return r;
|
||||
};
|
||||
config.detector_routes = {
|
||||
route("contact", config.recovery_routes.collision, true, RecoveryTrigger::kCollision),
|
||||
route("unreachable", config.recovery_routes.path_blocked, true, RecoveryTrigger::kPathBlocked),
|
||||
route("off_path", config.recovery_routes.off_path, true, RecoveryTrigger::kOffPath),
|
||||
route("stall", config.recovery_routes.oscillation, false, RecoveryTrigger::kOscillation),
|
||||
};
|
||||
}
|
||||
|
||||
/// @brief Cấu hình cơ sở cho test: ngưỡng ngắn để không phải tua thời gian dài.
|
||||
StateMachineConfig baseConfig()
|
||||
{
|
||||
@@ -53,9 +87,13 @@ StateMachineConfig baseConfig()
|
||||
class Driver
|
||||
{
|
||||
public:
|
||||
explicit Driver(const StateMachineConfig& config = baseConfig())
|
||||
explicit Driver(StateMachineConfig config = baseConfig())
|
||||
{
|
||||
std::string error;
|
||||
if (config.detector_routes.empty())
|
||||
{
|
||||
addLegacyDetectors(config);
|
||||
}
|
||||
configured_ = machine_.configure(config, error);
|
||||
EXPECT_TRUE(configured_) << error;
|
||||
now_ = 1000.0;
|
||||
@@ -884,7 +922,7 @@ TEST(StateMachineControlling, NoProgressFlagEscalatesToOscillationRecovery)
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput input = controller(ControllerFeedback::kCommandValid);
|
||||
input.no_progress = true;
|
||||
input.detector_fired |= kNoProgressBit;
|
||||
const StateMachineOutput out = driver.tick(input);
|
||||
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
@@ -2197,7 +2235,7 @@ StateMachineInput collisionInput()
|
||||
{
|
||||
StateMachineInput input;
|
||||
input.controller = ControllerFeedback::kCommandValid;
|
||||
input.collision = true;
|
||||
input.detector_fired |= kCollisionBit;
|
||||
input.active_recovery_output = RecoveryOutputKind::kPath;
|
||||
return input;
|
||||
}
|
||||
@@ -2206,7 +2244,7 @@ StateMachineInput blockedInput()
|
||||
{
|
||||
StateMachineInput input;
|
||||
input.controller = ControllerFeedback::kCommandValid;
|
||||
input.path_blocked = true;
|
||||
input.detector_fired |= kBlockedBit;
|
||||
// Cả hai route giám sát tuyến đều trỏ vào detour, họ kPath: nó KHÔNG lái robot, chỉ trả đường đi
|
||||
// mới. Khai đúng họ ở đây để test kiểm được bất biến "robot đứng yên suốt lúc detour".
|
||||
input.active_recovery_output = RecoveryOutputKind::kPath;
|
||||
@@ -2217,7 +2255,7 @@ StateMachineInput offPathInput()
|
||||
{
|
||||
StateMachineInput input;
|
||||
input.controller = ControllerFeedback::kCommandValid;
|
||||
input.off_path = true;
|
||||
input.detector_fired |= kOffPathBit;
|
||||
input.active_recovery_output = RecoveryOutputKind::kPath;
|
||||
return input;
|
||||
}
|
||||
@@ -2260,8 +2298,8 @@ TEST(StateMachinePathMonitor, BlockedPathWinsWhenBothFire)
|
||||
|
||||
StateMachineInput both;
|
||||
both.controller = ControllerFeedback::kCommandValid;
|
||||
both.path_blocked = true;
|
||||
both.off_path = true;
|
||||
both.detector_fired |= kBlockedBit;
|
||||
both.detector_fired |= kOffPathBit;
|
||||
|
||||
EXPECT_EQ(driver.tick(both).recovery_trigger, RecoveryTrigger::kPathBlocked);
|
||||
}
|
||||
@@ -2303,8 +2341,8 @@ TEST(StateMachineCollisionTrigger, WinsOverPathBlockedAndOffPath)
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput all = collisionInput();
|
||||
all.path_blocked = true;
|
||||
all.off_path = true;
|
||||
all.detector_fired |= kBlockedBit;
|
||||
all.detector_fired |= kOffPathBit;
|
||||
const StateMachineOutput out = driver.tick(all);
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_EQ(out.recovery_trigger, RecoveryTrigger::kCollision);
|
||||
@@ -3038,6 +3076,134 @@ TEST(StateMachineEmergency, IsNotTerminalAndMustBeStopped)
|
||||
EXPECT_STREQ(move_base2::toString(NavigationState::kEmergency), "EMERGENCY");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
// route_mode: sequence (chốt 26/11, Test/docs/move_base2/ENV_DETECTOR_PLUGINS_PROMPT.md §4.5)
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
namespace
|
||||
{
|
||||
/// Một detector `contact` chạy route [0, 1, 2] kiểu sequence, cạn thì khoá.
|
||||
StateMachineConfig sequenceConfig()
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.recovery_behavior_count = 3;
|
||||
config.recovery_routes.planning_failed = { 0 };
|
||||
config.recovery_routes.controlling_failed = { 0 };
|
||||
config.recovery_routes.oscillation = { 0 };
|
||||
move_base2::DetectorRoute contact;
|
||||
contact.name = "contact";
|
||||
contact.route = { 0, 1, 2 };
|
||||
contact.lock_on_exhausted = true;
|
||||
contact.sequence = true;
|
||||
contact.trigger = RecoveryTrigger::kCollision;
|
||||
config.detector_routes = { contact };
|
||||
return config;
|
||||
}
|
||||
|
||||
StateMachineInput sequenceFire()
|
||||
{
|
||||
StateMachineInput input;
|
||||
input.controller = ControllerFeedback::kCommandValid;
|
||||
input.detector_fired = 1u;
|
||||
input.active_recovery_output = RecoveryOutputKind::kPath;
|
||||
return input;
|
||||
}
|
||||
|
||||
StateMachineInput behaviorDone(RecoveryFeedback result, bool with_path = false)
|
||||
{
|
||||
StateMachineInput input;
|
||||
input.recovery = result;
|
||||
input.planner = with_path ? PlannerFeedback::kPlanReady : PlannerFeedback::kIdle;
|
||||
input.active_recovery_output = RecoveryOutputKind::kPath;
|
||||
return input;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(StateMachineSequence, OneFiringRunsTheWholeRouteEvenWhenABehaviorFails)
|
||||
{
|
||||
Driver driver(sequenceConfig());
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineOutput out = driver.tick(sequenceFire());
|
||||
ASSERT_EQ(out.state, NavigationState::kRecovering);
|
||||
EXPECT_TRUE(out.start_recovery);
|
||||
EXPECT_EQ(out.recovery_index, 0u);
|
||||
EXPECT_FALSE(out.recovery_chain_continues);
|
||||
EXPECT_EQ(out.recovery_detector, 0);
|
||||
|
||||
out = driver.tick(behaviorDone(RecoveryFeedback::kFailed));
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering) << "a failed behavior does not end a sequence";
|
||||
EXPECT_TRUE(out.start_recovery);
|
||||
EXPECT_TRUE(out.recovery_chain_continues);
|
||||
EXPECT_EQ(out.recovery_index, 1u);
|
||||
|
||||
out = driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
|
||||
EXPECT_TRUE(out.recovery_chain_continues);
|
||||
EXPECT_EQ(out.recovery_index, 2u);
|
||||
|
||||
out = driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
|
||||
EXPECT_TRUE(out.recovery_chain_finished);
|
||||
EXPECT_FALSE(out.recovery_chain_has_path);
|
||||
EXPECT_FALSE(out.recovery_chain_last_failed);
|
||||
EXPECT_FALSE(out.apply_plan);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
|
||||
// Cả chuỗi là MỘT lượt: lần nổ sau route đã cạn -> khoá (lock), robot bám tiếp plan.
|
||||
out = driver.tick(sequenceFire());
|
||||
EXPECT_TRUE(out.monitor_trigger_suppressed);
|
||||
EXPECT_FALSE(out.start_recovery);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
}
|
||||
|
||||
TEST(StateMachineSequence, APathInTheMiddleIsHeldAppliedAtTheEndAndRefillsTheRoute)
|
||||
{
|
||||
Driver driver(sequenceConfig());
|
||||
driver.driveToControlling();
|
||||
driver.tick(sequenceFire());
|
||||
|
||||
StateMachineOutput out = driver.tick(behaviorDone(RecoveryFeedback::kSucceeded, true));
|
||||
EXPECT_TRUE(out.recovery_chain_continues) << "a new path does not end a sequence";
|
||||
EXPECT_FALSE(out.apply_plan) << "the path waits for the end of the chain";
|
||||
EXPECT_EQ(out.state, NavigationState::kRecovering);
|
||||
|
||||
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
|
||||
out = driver.tick(behaviorDone(RecoveryFeedback::kFailed));
|
||||
EXPECT_TRUE(out.recovery_chain_finished);
|
||||
EXPECT_TRUE(out.recovery_chain_has_path);
|
||||
EXPECT_TRUE(out.recovery_chain_last_failed);
|
||||
EXPECT_TRUE(out.apply_plan);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_STREQ(out.reason, "recovery produced a detour path");
|
||||
|
||||
// Chuỗi có path mới và đây là lần nạp đầu: route nạp lại, lần nổ sau chạy lại cả chuỗi.
|
||||
out = driver.tick(sequenceFire());
|
||||
EXPECT_FALSE(out.monitor_trigger_suppressed);
|
||||
EXPECT_TRUE(out.start_recovery);
|
||||
EXPECT_EQ(out.recovery_index, 0u);
|
||||
}
|
||||
|
||||
TEST(StateMachineSequence, ANewPathWithoutTravelDoesNotRefillTheRoute)
|
||||
{
|
||||
StateMachineConfig config = sequenceConfig();
|
||||
config.recovery_reset_min_travel = 0.10; // [m]
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
// Lượt 1: có path -> nạp lại (lần đầu luôn được), mốc quãng đường đặt ở 0.
|
||||
driver.tick(sequenceFire());
|
||||
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded, true));
|
||||
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
|
||||
ASSERT_TRUE(driver.tick(behaviorDone(RecoveryFeedback::kSucceeded)).recovery_chain_finished);
|
||||
|
||||
// Lượt 2: lại có path nhưng robot chưa đi được 0.10 m -> tính như một lượt, route cạn.
|
||||
driver.tick(sequenceFire());
|
||||
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded, true));
|
||||
driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
|
||||
const StateMachineOutput end = driver.tick(behaviorDone(RecoveryFeedback::kSucceeded));
|
||||
ASSERT_TRUE(end.recovery_chain_finished);
|
||||
EXPECT_TRUE(end.recovery_reset_denied);
|
||||
EXPECT_TRUE(driver.tick(sequenceFire()).monitor_trigger_suppressed);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
#include <move_base2/control_loop.h>
|
||||
|
||||
#include "env_monitor_fixture.h"
|
||||
#include "fake_ports.h"
|
||||
|
||||
using move_base2::ControlLoop;
|
||||
@@ -117,7 +118,9 @@ NavigationRequest makeActionOnlyRequest(std::size_t count, std::uint64_t sequenc
|
||||
class Fixture
|
||||
{
|
||||
public:
|
||||
explicit Fixture(const ControlLoopConfig& config = baseConfig()) : recovery_(2)
|
||||
explicit Fixture(const ControlLoopConfig& config = baseConfig(),
|
||||
const env_monitor_core::EnvMonitorConfig& env = env_monitor_core::EnvMonitorConfig())
|
||||
: recovery_(2)
|
||||
{
|
||||
pose_.setPosition(0.0, 0.0);
|
||||
|
||||
@@ -130,12 +133,14 @@ public:
|
||||
deps_.action = &action_;
|
||||
deps_.costmap_status = &costmap_status_;
|
||||
deps_.environment = &environment_;
|
||||
deps_.env_monitor = &env_monitor_;
|
||||
deps_.components = &components_;
|
||||
planner_.attachStatusBoard(&components_);
|
||||
recovery_.attachStatusBoard(&components_);
|
||||
action_.attachStatusBoard(&components_);
|
||||
|
||||
std::string error;
|
||||
EXPECT_TRUE(move_base2::testing::initEnvMonitor(env_monitor_, env, error)) << error;
|
||||
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
|
||||
}
|
||||
|
||||
@@ -173,6 +178,7 @@ public:
|
||||
return hit_limit_;
|
||||
}
|
||||
|
||||
env_monitor_core::EnvMonitor env_monitor_; ///< trước loop_: loop_ giữ con trỏ tới nó
|
||||
ControlLoop loop_;
|
||||
FakeClockPort clock_;
|
||||
FakePosePort pose_;
|
||||
@@ -2122,22 +2128,29 @@ ControlLoopConfig envContactConfig()
|
||||
config.state_machine.recovery_routes.oscillation = { 0 };
|
||||
config.state_machine.recovery_routes.path_blocked = { 1 };
|
||||
config.state_machine.recovery_routes.collision = { 1 };
|
||||
config.env_monitor.enabled = true;
|
||||
config.env_monitor.stall.action = "log";
|
||||
config.env_monitor.unreachable.action = "log";
|
||||
config.env_monitor.contact.action = "recover";
|
||||
config.env_monitor.contact.apply_command = true;
|
||||
config.env_monitor.contact.confirm_cycles = 2;
|
||||
config.env_monitor.contact.trigger_static_time = 0.3; // [s] = 6 cycle, đủ ngắn cho test
|
||||
config.env_monitor.contact.clean_start_margin = 0.2; // [m]
|
||||
config.env_sampling.check_period = 0.01; // [s] < chu kỳ 0.05 -> tick nặng mỗi cycle
|
||||
return config;
|
||||
}
|
||||
|
||||
/// Tham số lõi EnvMonitor của bộ test kContact (nạp qua YAML như runtime).
|
||||
env_monitor_core::EnvMonitorConfig envContactMonitor()
|
||||
{
|
||||
env_monitor_core::EnvMonitorConfig env;
|
||||
env.enabled = true;
|
||||
env.stall.action = "log";
|
||||
env.unreachable.action = "log";
|
||||
env.contact.action = "recover";
|
||||
env.contact.apply_command = true;
|
||||
env.contact.confirm_cycles = 2;
|
||||
env.contact.trigger_static_time = 0.3; // [s] = 6 cycle, đủ ngắn cho test
|
||||
env.contact.clean_start_margin = 0.2; // [m]
|
||||
return env;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(WalkingSkeletonEnvContact, BrakesAfterConfirmThenRaisesCollisionAfterStaticTime)
|
||||
{
|
||||
Fixture fixture(envContactConfig());
|
||||
Fixture fixture(envContactConfig(), envContactMonitor());
|
||||
driveToControlling(fixture);
|
||||
|
||||
// Tiếp xúc 0.10 m trên quỹ đạo, trong clean_start_margin: cycle 1 đếm, cycle 2 phanh -> lệnh 0.
|
||||
@@ -2166,7 +2179,7 @@ TEST(WalkingSkeletonEnvContact, HeldWithTheRouteSpentEscalatesToControllingFaile
|
||||
// Cùng chuỗi bắt buộc như guard cũ: cạn route collision -> khoá -> brake giữ 0 nhưng controller
|
||||
// phải bị báo no_valid_command -> controller_patience -> controlling_failed. Không có bước này
|
||||
// robot đứng chết vô hạn với controller "ổn".
|
||||
Fixture fixture(envContactConfig());
|
||||
Fixture fixture(envContactConfig(), envContactMonitor());
|
||||
driveToControlling(fixture);
|
||||
fixture.recovery_.setScript({ RecoveryScript::kFailed });
|
||||
|
||||
@@ -2207,7 +2220,7 @@ TEST(WalkingSkeletonEnvContact, DetourFromContactThatDidNotMoveTheRobotArmsTheSt
|
||||
// Run 6/9 16:30 (đám đông): người đứng 7 cm trước mũi -> cờ collision -> detour -> chạm lại ngay -> cờ -> detour ...
|
||||
// 4 lần rồi ABORT, vì stand-down không được vũ trang (trigger đọc ở cycle tick là mặc định). Chuỗi đúng: sau
|
||||
// detour do cờ collision mà robot không dịch, chạm lại thì kContact ĐỨNG RA — không phanh, không cờ thứ hai.
|
||||
Fixture fixture(envContactConfig());
|
||||
Fixture fixture(envContactConfig(), envContactMonitor());
|
||||
driveToControlling(fixture);
|
||||
std::vector<robot_geometry_msgs::PoseStamped> detour{ makeRequest(0.0).goal, makeRequest(3.0).goal };
|
||||
fixture.recovery_.setScript({ RecoveryScript::kSucceeded });
|
||||
@@ -2245,7 +2258,7 @@ TEST(WalkingSkeletonEnvContact, DetourFromContactThatDidNotMoveTheRobotArmsTheSt
|
||||
|
||||
TEST(WalkingSkeletonEnvContact, ContactBeyondTheStoppingDistanceCapsSpeedWithoutBraking)
|
||||
{
|
||||
Fixture fixture(envContactConfig());
|
||||
Fixture fixture(envContactConfig(), envContactMonitor());
|
||||
driveToControlling(fixture);
|
||||
const double v_free = fixture.loop_.lastCommand().linear.x;
|
||||
ASSERT_GT(v_free, 0.27);
|
||||
|
||||
Reference in New Issue
Block a user