refactor: xoá PathMonitor và PathCheckPort, EnvMonitor là bộ giám sát duy nhất; gộp refreshSnapshot

Xoá hạ tầng giám sát cũ đã tắt từ 5/9 (path_monitor/enabled: false), −2947 dòng:
- ControlLoop: PathMonitorConfig, updatePathMonitor / updateProgressMonitor / applyCollisionGuard /
  planIsBlocked / resetPathMonitor / rebuildPlanArcLength, toàn bộ member bốn phép đo, luật "plan
  mới bẩn thì giữ plan cũ" trong collectPlannerResult. Bốn cổng StateMachineInput giữ nguyên
  (off_path không còn nguồn, đặt false).
- ports/path_check_port.h, CostmapPathCheck trong NavigationRuntime.
- plan_inspector: bỏ checkPlan / checkMotion / PlanBlockResult / MotionCheckParams /
  MotionBlockResult; giữ planarTransform, nearestIndex, trackedNearestIndex, crossTrackError.
- Config: readPathMonitor, MoveBase2Config::path_monitor, validate; xoá
  config/runtime/path_monitor_params.yaml; comment YAML/state_machine đổi sang tên verdict EnvMonitor.
- Test: FakePathCheckPort, 30 test WalkingSkeletonPathMonitor/CollisionGuard, 13 test
  PlanInspectorCheck/Motion, 2 test validate thân guard.

P0(b): ControlLoop::step() gọi EnvironmentPort::refresh() một lần đầu cycle (không phụ thuộc
env_monitor/enabled); ControllerRunner::setSnapshotRefreshedByLoop(true) làm ba refreshSnapshot()
trong runner thành no-op — monitor và controller đọc cùng một lưới, một bản copy mỗi cycle.

Test: env_monitor 43, grid_analysis 33, plan_inspector 11, walking_skeleton 57, config_validation 32,
scenario 12, state_machine 100, navigation_server 56, controller_runner 28, velocity_arbiter 29,
planner_runner 31 — pass.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xXjFjr2DQ6rhmhHSW4fk4
This commit is contained in:
2026-09-06 10:55:15 +07:00
parent 62692838d6
commit c0a04b29ad
22 changed files with 85 additions and 3316 deletions

View File

@@ -140,94 +140,6 @@ void readDockingMarkerProfiles(robot::NodeHandle& nh, DockingMarkerProfiles& pro
}
}
/**
* @brief Đọc khối `path_monitor`.
*
* Khối vắng mặt = giám sát tuyến TẮT, hành vi y hệt trước 2026-08-04d. Đây là đường lùi thứ nhất
* (thứ hai là route `path_blocked`/`off_path` rỗng) — hai nút độc lập, cố ý.
*/
void readPathMonitor(robot::NodeHandle& nh, ControlLoopConfig::PathMonitorConfig& monitor)
{
robot::NodeHandle monitor_nh(nh, "path_monitor");
readBool(monitor_nh, "enabled", monitor.enabled);
readBool(monitor_nh, "path_blocked_enabled", monitor.path_blocked_enabled);
readBool(monitor_nh, "off_path_enabled", monitor.off_path_enabled);
readDouble(monitor_nh, "check_period", monitor.check_period);
readDouble(monitor_nh, "confirm_time", monitor.confirm_time);
readDouble(monitor_nh, "horizon", monitor.horizon);
readDouble(monitor_nh, "min_detour_distance", monitor.min_detour_distance);
readDouble(monitor_nh, "max_cross_track", monitor.max_cross_track);
readDouble(monitor_nh, "grace_after_new_plan", monitor.grace_after_new_plan);
// Phép đo 3 (2026-09-03): thân sắp chạm vật cản THẬT trên cung lệnh. Khoá riêng, không dùng chung
// tham số nào với hai phép đo trên.
readBool(monitor_nh, "collision_enabled", monitor.collision_enabled);
readDouble(monitor_nh, "collision_lookahead", monitor.collision_lookahead);
monitor_nh.param("collision_max_samples", monitor.collision_max_samples,
monitor.collision_max_samples);
readDouble(monitor_nh, "collision_stop_distance", monitor.collision_stop_distance);
monitor_nh.param("collision_confirm_cycles", monitor.collision_confirm_cycles,
monitor.collision_confirm_cycles);
monitor_nh.param("collision_cost_threshold", monitor.collision_cost_threshold,
monitor.collision_cost_threshold);
readDouble(monitor_nh, "collision_front_offset", monitor.collision_front_offset);
readDouble(monitor_nh, "collision_rear_offset", monitor.collision_rear_offset);
readDouble(monitor_nh, "collision_side_offset", monitor.collision_side_offset);
readDouble(monitor_nh, "collision_footprint_padding", monitor.collision_footprint_padding);
readBool(monitor_nh, "collision_exclude_baseline", monitor.collision_exclude_baseline);
readDouble(monitor_nh, "collision_min_speed", monitor.collision_min_speed);
readDouble(monitor_nh, "collision_stop_time", monitor.collision_stop_time);
readDouble(monitor_nh, "collision_stop_angle", monitor.collision_stop_angle);
readDouble(monitor_nh, "collision_lookahead_angle", monitor.collision_lookahead_angle);
readDouble(monitor_nh, "collision_brake_decel", monitor.collision_brake_decel);
// Phép đo 4 (2026-09-04): planner đòi đi mà robot không tiến.
readBool(monitor_nh, "progress_enabled", monitor.progress_enabled);
readString(monitor_nh, "progress_action", monitor.progress_action);
readDouble(monitor_nh, "progress_window", monitor.progress_window);
readDouble(monitor_nh, "progress_min_commanded", monitor.progress_min_commanded);
readDouble(monitor_nh, "progress_min_efficiency", monitor.progress_min_efficiency);
readDouble(monitor_nh, "progress_clear_efficiency", monitor.progress_clear_efficiency);
readDouble(monitor_nh, "progress_confirm_time", monitor.progress_confirm_time);
readDouble(monitor_nh, "progress_goal_zone", monitor.progress_goal_zone);
std::vector<std::string> names;
monitor_nh.param("profiles", names, std::vector<std::string>{});
if (names.empty())
{
return; // Giữ mặc định: chỉ profile position.
}
monitor.profiles.clear();
for (const std::string& name : names)
{
if (name == "position")
{
monitor.profiles.push_back(MotionProfile::kPosition);
}
else if (name == "docking")
{
monitor.profiles.push_back(MotionProfile::kDocking);
}
else if (name == "go_straight")
{
monitor.profiles.push_back(MotionProfile::kGoStraight);
}
else if (name == "rotate")
{
monitor.profiles.push_back(MotionProfile::kRotate);
}
else
{
// Không đoán: tên lạ mà im lặng bỏ qua thì người vận hành tưởng đã bật giám sát cho profile
// đó. Cảnh báo rồi bỏ — profile lạ không thể tự sinh ra hành vi nào.
robot::log_warning("[move_base2] path_monitor/profiles: unknown profile '%s', ignored.\n",
name.c_str());
}
}
}
/// Các tham số chung của move_base2, dùng chung cho schema namespace và schema root-profile.
void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
{
@@ -271,7 +183,6 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
readSensors(nh, config.sensors);
readSensorStore(nh, config);
readDebug(nh, config);
readPathMonitor(nh, config.path_monitor);
readEnvMonitor(nh, config);
readBool(nh, "docking_requires_marker", config.docking_requires_marker);
@@ -514,164 +425,6 @@ bool MoveBase2Config::validate(std::string& error) const
return false;
}
if (path_monitor.enabled)
{
// Chỉ kiểm khi BẬT: tham số vô nghĩa trong một khối đang tắt không có lý do gì để chặn boot.
if (!std::isfinite(path_monitor.check_period) || path_monitor.check_period <= 0.0)
{
error = "path_monitor/check_period must be > 0 [s]";
return false;
}
if (!std::isfinite(path_monitor.confirm_time) || path_monitor.confirm_time < 0.0)
{
error = "path_monitor/confirm_time must be >= 0 [s]";
return false;
}
if (!std::isfinite(path_monitor.horizon) || path_monitor.horizon < 0.0)
{
error = "path_monitor/horizon must be >= 0 [m] (0 = the blocked-path check is off)";
return false;
}
if (!std::isfinite(path_monitor.min_detour_distance) || path_monitor.min_detour_distance < 0.0)
{
error = "path_monitor/min_detour_distance must be >= 0 [m]";
return false;
}
if (!std::isfinite(path_monitor.max_cross_track) || path_monitor.max_cross_track < 0.0)
{
error = "path_monitor/max_cross_track must be >= 0 [m] (0 = the off-path check is off)";
return false;
}
if (!std::isfinite(path_monitor.grace_after_new_plan) ||
path_monitor.grace_after_new_plan < 0.0)
{
error = "path_monitor/grace_after_new_plan must be >= 0 [s]";
return false;
}
if (path_monitor.collision_enabled)
{
const auto bad = [](double v) { return !std::isfinite(v) || v < 0.0; };
if (!std::isfinite(path_monitor.collision_lookahead) || path_monitor.collision_lookahead <= 0.0)
{
error = "path_monitor/collision_lookahead must be > 0 [m]";
return false;
}
if (path_monitor.collision_max_samples < 1)
{
error = "path_monitor/collision_max_samples must be >= 1";
return false;
}
if (bad(path_monitor.collision_stop_distance) ||
path_monitor.collision_stop_distance > path_monitor.collision_lookahead)
{
error = "path_monitor/collision_stop_distance must be in [0, collision_lookahead] [m]";
return false;
}
if (path_monitor.collision_confirm_cycles < 1)
{
error = "path_monitor/collision_confirm_cycles must be >= 1";
return false;
}
if (path_monitor.collision_cost_threshold < 1 || path_monitor.collision_cost_threshold > 254)
{
error = "path_monitor/collision_cost_threshold must be in [1, 254] (254 = LETHAL only)";
return false;
}
if (bad(path_monitor.collision_front_offset) || bad(path_monitor.collision_rear_offset) ||
bad(path_monitor.collision_side_offset) || bad(path_monitor.collision_footprint_padding))
{
error = "path_monitor/collision_*_offset and collision_footprint_padding must be >= 0 [m]";
return false;
}
{
// Cả ba = 0: lấy thân từ footprint costmap lúc chạy. Khai tay thì phải đủ cả ba > 0 — mũi = 0
// là chỉ dò tâm (dừng khi tâm đã ở trong tường), hông = 0 là bỏ hai cạnh hông.
const int declared = (path_monitor.collision_front_offset > 0.0 ? 1 : 0) +
(path_monitor.collision_rear_offset > 0.0 ? 1 : 0) +
(path_monitor.collision_side_offset > 0.0 ? 1 : 0);
if (declared != 0 && declared != 3)
{
error = "path_monitor/collision_front_offset, collision_rear_offset and "
"collision_side_offset must either all be 0 (take the body from the costmap "
"footprint) or all be > 0 [m]";
return false;
}
}
if (!std::isfinite(path_monitor.collision_stop_time) || path_monitor.collision_stop_time <= 0.0)
{
error = "path_monitor/collision_stop_time must be > 0 [s]";
return false;
}
if (!std::isfinite(path_monitor.collision_stop_angle) || path_monitor.collision_stop_angle <= 0.0 ||
path_monitor.collision_stop_angle > M_PI)
{
error = "path_monitor/collision_stop_angle must be in (0, pi] [rad]";
return false;
}
if (!std::isfinite(path_monitor.collision_lookahead_angle) ||
path_monitor.collision_lookahead_angle < path_monitor.collision_stop_angle ||
path_monitor.collision_lookahead_angle > M_PI)
{
error = "path_monitor/collision_lookahead_angle must be in [collision_stop_angle, pi] [rad]";
return false;
}
if (bad(path_monitor.collision_min_speed) || bad(path_monitor.collision_brake_decel))
{
error = "path_monitor/collision_min_speed [m/s] and collision_brake_decel [m/s^2] must be >= 0";
return false;
}
}
if (path_monitor.progress_enabled)
{
if (path_monitor.progress_action != "log" && path_monitor.progress_action != "recover")
{
error = "path_monitor/progress_action must be 'log' or 'recover'";
return false;
}
if (!std::isfinite(path_monitor.progress_window) || path_monitor.progress_window <= 0.0)
{
error = "path_monitor/progress_window must be > 0 [s]";
return false;
}
if (!std::isfinite(path_monitor.progress_min_commanded) ||
path_monitor.progress_min_commanded <= 0.0)
{
// 0 là đo cả lúc đứng yên: cmd = 0, eff = 0/0 -> mọi lần chờ hợp lệ đều thành "kẹt".
error = "path_monitor/progress_min_commanded must be > 0 [m]";
return false;
}
if (!std::isfinite(path_monitor.progress_min_efficiency) ||
!std::isfinite(path_monitor.progress_clear_efficiency) ||
path_monitor.progress_min_efficiency < 0.0 ||
path_monitor.progress_clear_efficiency <= path_monitor.progress_min_efficiency)
{
// clear == min là cờ nhấp nháy quanh một ngưỡng: bật, xoá, bật... mỗi lượt quét.
error = "path_monitor/progress_clear_efficiency must be > progress_min_efficiency >= 0";
return false;
}
if (!std::isfinite(path_monitor.progress_confirm_time) ||
path_monitor.progress_confirm_time < 0.0 ||
!std::isfinite(path_monitor.progress_goal_zone) || path_monitor.progress_goal_zone < 0.0)
{
error = "path_monitor/progress_confirm_time [s] and progress_goal_zone [m] must be >= 0";
return false;
}
}
if (!(path_monitor.horizon > 0.0) && !(path_monitor.max_cross_track > 0.0) &&
!path_monitor.collision_enabled && !path_monitor.progress_enabled)
{
// Bật khối mà tắt cả bốn phép đo là mâu thuẫn: người khai tưởng giám sát đang chạy.
error = "path_monitor is enabled but all checks are off; set horizon > 0 [m], "
"max_cross_track > 0 [m], collision_enabled: true and/or progress_enabled: true, "
"or set enabled: false";
return false;
}
if (path_monitor.profiles.empty())
{
error = "path_monitor/profiles is empty; no leg would ever be monitored";
return false;
}
}
if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0)
{
error = "runtime_stats_period must be >= 0 [s] (0 = telemetry off)";
@@ -971,7 +724,6 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
config.rotate = rotate;
config.backup_global_planner_name = backup_global_planner_name;
config.docking_requires_marker = docking_requires_marker;
config.path_monitor = path_monitor;
config.env_monitor = env_monitor;
config.env_sampling = env_sampling;
config.env_logger = env_logger;

View File

@@ -152,11 +152,6 @@ std::string ControlLoopConfig::describe() const
return out.str();
}
bool ControlLoopConfig::PathMonitorConfig::monitors(MotionProfile profile) const
{
return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
}
bool EnvSamplingConfig::monitors(MotionProfile profile) const
{
return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
@@ -238,111 +233,9 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
config_ = config;
deps_ = deps;
// Bật giám sát mà không có đường xử lý nào là cấu hình vô nghĩa — và trước đây nó im lặng. Không
// chặn boot (navigation vẫn phải chạy), nhưng phải hét lên: người vận hành khai `enabled: true`
// thì tin rằng cơ chế đang chạy.
if (config_.path_monitor.enabled)
{
if (deps_.path_check == nullptr)
{
robot::log_error("[move_base2] path_monitor is enabled but no PathCheckPort is wired — path "
"monitoring stays OFF.\n");
}
else if (!config_.path_monitor.path_blocked_enabled && !config_.path_monitor.off_path_enabled &&
!config_.path_monitor.collision_enabled && !config_.path_monitor.progress_enabled)
{
robot::log_warning("[move_base2] path_monitor/enabled is true but ALL sub-monitors are off "
"(path_blocked_enabled=false, off_path_enabled=false, "
"collision_enabled=false, progress_enabled=false) — path monitoring does "
"nothing.\n");
}
else if (config_.state_machine.recovery_routes.path_blocked.empty() &&
config_.state_machine.recovery_routes.off_path.empty() &&
config_.state_machine.recovery_routes.collision.empty() &&
config_.state_machine.recovery_routes.oscillation.empty())
{
robot::log_error("[move_base2] path_monitor is enabled but the recovery routes "
"'path_blocked', 'off_path', 'collision' and 'oscillation' are all empty "
"(behaviors failed to load?) — path monitoring stays OFF.\n");
}
else
{
// In trạng thái THẬT của từng phép đo, đã gộp cả ba nút: đọc một dòng là biết cái nào sống.
const bool blocked_on = config_.path_monitor.path_blocked_enabled &&
config_.path_monitor.horizon > 0.0 &&
!config_.state_machine.recovery_routes.path_blocked.empty();
const bool off_path_on = config_.path_monitor.off_path_enabled &&
config_.path_monitor.max_cross_track > 0.0 &&
!config_.state_machine.recovery_routes.off_path.empty();
const bool collision_on = config_.path_monitor.collision_enabled &&
config_.path_monitor.collision_lookahead > 0.0 &&
!config_.state_machine.recovery_routes.collision.empty();
char body[64];
if (!(config_.path_monitor.collision_front_offset > 0.0) &&
!(config_.path_monitor.collision_rear_offset > 0.0) &&
!(config_.path_monitor.collision_side_offset > 0.0))
{
std::snprintf(body, sizeof(body), "costmap footprint");
}
else
{
std::snprintf(body, sizeof(body), "%.2f/%.2f/%.2f",
config_.path_monitor.collision_front_offset,
config_.path_monitor.collision_rear_offset,
config_.path_monitor.collision_side_offset);
}
robot::log_info("[move_base2] path monitor ON (confirm=%.2f s, check=%.2f s):\n"
" path_blocked: %s (flag=%s, horizon=%.2f m, route=%zu)\n"
" off_path : %s (flag=%s, max_cross_track=%.2f m, route=%zu)\n"
" collision : %s (flag=%s, lookahead=%.2f m, stop=%.2f m, confirm=%d "
"cycles, threshold=%d, body=%s+%.2f m, brake=%.2f m/s^2, "
"baseline=%s, stop_time=%.1f s, stop_angle=%.2f rad, lookahead_angle=%.2f "
"rad, route=collision %zu)\n",
config_.path_monitor.confirm_time, config_.path_monitor.check_period,
blocked_on ? "ON" : "OFF",
config_.path_monitor.path_blocked_enabled ? "on" : "off",
config_.path_monitor.horizon,
config_.state_machine.recovery_routes.path_blocked.size(),
off_path_on ? "ON" : "OFF",
config_.path_monitor.off_path_enabled ? "on" : "off",
config_.path_monitor.max_cross_track,
config_.state_machine.recovery_routes.off_path.size(),
collision_on ? "ON" : "OFF",
config_.path_monitor.collision_enabled ? "on" : "off",
config_.path_monitor.collision_lookahead,
config_.path_monitor.collision_stop_distance,
config_.path_monitor.collision_confirm_cycles,
config_.path_monitor.collision_cost_threshold,
body,
config_.path_monitor.collision_footprint_padding,
config_.path_monitor.collision_brake_decel,
config_.path_monitor.collision_exclude_baseline ? "on" : "off",
config_.path_monitor.collision_stop_time,
config_.path_monitor.collision_stop_angle,
config_.path_monitor.collision_lookahead_angle,
config_.state_machine.recovery_routes.collision.size());
const bool progress_on =
config_.path_monitor.progress_enabled &&
(config_.path_monitor.progress_action != "recover" ||
!config_.state_machine.recovery_routes.oscillation.empty());
robot::log_info(" progress : %s (flag=%s, action=%s, window=%.1f s, min_cmd=%.2f m, "
"eff<%.2f kẹt / >=%.2f xoá, confirm=%.1f s, goal_zone=%.2f m, "
"route=oscillation %zu)\n",
progress_on ? "ON" : "OFF",
config_.path_monitor.progress_enabled ? "on" : "off",
config_.path_monitor.progress_action.c_str(),
config_.path_monitor.progress_window,
config_.path_monitor.progress_min_commanded,
config_.path_monitor.progress_min_efficiency,
config_.path_monitor.progress_clear_efficiency,
config_.path_monitor.progress_confirm_time,
config_.path_monitor.progress_goal_zone,
config_.state_machine.recovery_routes.oscillation.size());
}
}
// EnvMonitor (Test/ENV_MONITOR_PLAN.md): chạy song song PathMonitor ở P3. Không có cổng thì tắt, nhưng
// phải kêu nếu config bảo bật.
// EnvMonitor (Test/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)
{
@@ -411,7 +304,6 @@ void ControlLoop::reset()
action_message_.clear();
latest_plan_.clear();
++plan_revision_;
planner_running_ = false;
backup_global_planner_active_ = false;
@@ -425,7 +317,6 @@ void ControlLoop::reset()
has_last_cycle_time_ = false;
has_oscillation_origin_ = false;
last_plan_started_ = robot::Time();
resetPathMonitor();
has_last_plan_applied_ = false;
env_monitor_.reset();
@@ -725,30 +616,8 @@ void ControlLoop::collectPlannerResult()
return;
}
// Luật "không thay plan sạch bằng plan bẩn" (contract 2026-08-04d).
//
// Không có luật này thì cơ chế detour tự phá chính nó: `CustomPlanner` mù costmap nên mỗi nhịp
// `planner_frequency` nó trả lại đúng đường thẳng xuyên vật cản, ghi đè đường vòng vừa lập, rồi
// PathMonitor lại khai hoả — robot dừng-detour-chạy-dừng mỗi giây và ngân sách route cạn rất
// nhanh.
//
// Chỉ áp ở kControlling, nơi ĐANG có một plan để giữ. Ở kPlanning vẫn nhận plan bẩn như cũ:
// PathMonitor sẽ khai hoả ngay khi vào kControlling, nên mọi tình huống tuyến-bị-chắn đi qua đúng
// MỘT đường xử lý thay vì hai.
//
// Hệ quả đẹp: khi robot đã đi qua vật cản, plan thẳng của planner chính hết bị chắn nên được nhận
// lại — robot tự quay về đúng tuyến/NURBS của order, không cần cơ chế nào để "kết thúc detour".
if (state_machine_.state() == NavigationState::kControlling && !latest_plan_.empty() &&
planIsBlocked(result.plan, 0))
{
robot::log_warning_throttle(5.0, "[move_base2] a fresh plan runs into an obstacle; keeping the "
"current plan.\n");
planner_feedback_ = PlannerFeedback::kFailed;
return;
}
latest_plan_.swap(result.plan);
++plan_revision_;
// Tuyến THAM CHIẾU của chặng = plan do PLANNER sinh, không phải plan đã bị recovery thay
// (contract 2026-08-05e). Detour nối lại vào nó nên robot tự quay về tuyến order thay vì trôi
// dần theo từng đường vòng, và `max_deviation` đo đúng hành lang mà fleet đã duyệt.
@@ -756,528 +625,6 @@ void ControlLoop::collectPlannerResult()
planner_feedback_ = PlannerFeedback::kPlanReady;
}
void ControlLoop::resetPathMonitor()
{
path_blocked_ = false;
off_path_ = false;
has_last_path_check_ = false;
blocked_seen_ = false;
off_path_seen_ = false;
collision_brake_ = false;
collision_blocked_ = false;
collision_streak_ = 0;
resetProgressMonitor();
}
void ControlLoop::resetProgressMonitor()
{
progress_head_ = 0;
progress_count_ = 0;
progress_cmd_accum_ = 0.0;
progress_stall_seen_ = false;
no_progress_ = false;
}
void ControlLoop::rebuildPlanArcLength()
{
plan_arclen_.clear();
plan_arclen_.reserve(latest_plan_.size());
double s = 0.0; // [m]
for (std::size_t i = 0; i < latest_plan_.size(); ++i)
{
if (i > 0)
{
const double dx = latest_plan_[i].pose.position.x - latest_plan_[i - 1].pose.position.x;
const double dy = latest_plan_[i].pose.position.y - latest_plan_[i - 1].pose.position.y;
s += std::hypot(dx, dy);
}
plan_arclen_.push_back(s);
}
plan_arclen_revision_ = plan_revision_;
// Mẫu trong ring đo trên plan CŨ: s_plan của chúng không so được với plan mới. Xoá ring, GIỮ
// cmd_accum (nó đơn điệu, chỉ dùng qua hiệu số giữa hai mẫu).
progress_head_ = 0;
progress_count_ = 0;
progress_stall_seen_ = false;
no_progress_ = false;
}
void ControlLoop::updateProgressMonitor(const robot::Time& now, std::size_t from_index,
const robot_geometry_msgs::PoseStamped& robot_pose)
{
const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor;
// Mode "recover" cần route oscillation; mode "log" thì không cần gì — chỉ in.
const bool route_ready = cfg.progress_action != "recover" ||
!config_.state_machine.recovery_routes.oscillation.empty();
const bool grace = has_last_plan_applied_ &&
(now - last_plan_applied_).toSec() < cfg.grace_after_new_plan;
if (!cfg.progress_enabled || !route_ready || latest_plan_.empty())
{
resetProgressMonitor();
return;
}
if (plan_arclen_revision_ != plan_revision_)
{
rebuildPlanArcLength();
}
const double dxg = latest_plan_.back().pose.position.x - robot_pose.pose.position.x;
const double dyg = latest_plan_.back().pose.position.y - robot_pose.pose.position.y;
const double d_goal = std::hypot(dxg, dyg); // [m]
const double s_plan =
from_index < plan_arclen_.size() ? plan_arclen_[from_index] : plan_arclen_.back(); // [m]
// Ghi mẫu TRƯỚC khi xét grace/goal_zone: chuỗi mẫu phải liên tục, chỉ có KẾT LUẬN là bị hoãn.
progress_ring_[progress_head_] = ProgressSample{ now, s_plan, d_goal, progress_cmd_accum_ };
progress_head_ = (progress_head_ + 1) % kProgressRing;
progress_count_ = std::min(progress_count_ + 1, kProgressRing);
if (grace || d_goal < cfg.progress_goal_zone)
{
progress_stall_seen_ = false;
no_progress_ = false;
return;
}
// Mẫu MỚI NHẤT mà đã đủ tuổi `progress_window` — cửa sổ đo sát W nhất, không phải mẫu cũ nhất
// trong ring (có thể già tới 6 s và làm cửa sổ giãn ra).
const ProgressSample* old = nullptr;
for (std::size_t k = 1; k <= progress_count_; ++k)
{
const ProgressSample& sample =
progress_ring_[(progress_head_ + kProgressRing - k) % kProgressRing];
if ((now - sample.t).toSec() >= cfg.progress_window)
{
old = &sample;
break;
}
}
if (old == nullptr)
{
return; // chưa đủ tuổi cửa sổ: chưa kết luận, giữ nguyên trạng thái
}
const double cmd = progress_cmd_accum_ - old->cmd; // [m] lệnh đã phát
const double prog = std::max(s_plan - old->s_plan, old->d_goal - d_goal); // [m] tiến được
const double eff = cmd > 1e-6 ? prog / cmd : 0.0; // [-]
const bool stalled = cmd >= cfg.progress_min_commanded && eff < cfg.progress_min_efficiency;
// Xoá cờ CHỈ khi tiến bộ thật. `cmd < min_commanded` là "chưa đo được" chứ không phải "hết kẹt":
// sim 4/9 mission 3 — robot kẹt 35 s, tốc độ lệnh lượn quanh đúng ngưỡng 0.1 m/s, cờ bật/tắt 5
// lần cho MỘT đợt kẹt. Kẹt xong chậm lại (hoặc planner hold) vẫn là kẹt cho tới khi đi được.
const bool cleared = cmd >= cfg.progress_min_commanded && eff >= cfg.progress_clear_efficiency;
if (stalled)
{
if (!progress_stall_seen_)
{
progress_stall_since_ = now;
progress_stall_seen_ = true;
}
if (!no_progress_ && (now - progress_stall_since_).toSec() >= cfg.progress_confirm_time)
{
no_progress_ = true;
// KHÔNG gắn thẻ [debug], KHÔNG cho tắt: đây là chẩn đoán "robot kẹt", in đúng một lần mỗi đợt.
robot::log_warning("[move_base2] PathMonitor: no progress — commanded %.2f m in %.1f s but "
"advanced %.2f m (eff %.2f), %.2f m to goal — %s.\n",
cmd, cfg.progress_window, prog, eff, d_goal,
cfg.progress_action == "recover" ? "escalating to recovery"
: "LOG ONLY (progress_action: log)");
}
}
else if (cleared)
{
if (no_progress_ && config_.debug_state)
{
robot::log_info("[move_base2][debug] PathMonitor: progress resumed (eff %.2f over %.2f m "
"commanded).\n", eff, cmd);
}
progress_stall_seen_ = false;
no_progress_ = false;
}
// Còn lại — cmd < min_commanded (chờ / lết), hoặc eff trong vùng chết min..clear — giữ nguyên
// trạng thái (hysteresis). Không kết luận ≠ hết kẹt.
}
bool ControlLoop::planIsBlocked(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
std::size_t from_index) const
{
if (deps_.path_check == nullptr || !(config_.path_monitor.horizon > 0.0) || plan.empty())
{
return false;
}
PlanBlockResult result;
if (!deps_.path_check->checkPlan(plan, from_index, config_.path_monitor.horizon, result))
{
// Không kết luận được (thiếu TF/costmap). "Không biết" KHÔNG được suy thành "bẩn": làm vậy là
// robot dừng mỗi lần TF trễ một nhịp.
return false;
}
if (result.blocked)
{
last_block_distance_ = result.distance; // [m] chỉ để log; không tham gia quyết định.
}
return result.blocked && result.distance >= config_.path_monitor.min_detour_distance;
}
void ControlLoop::updatePathMonitor(const robot::Time& now,
const robot_geometry_msgs::PoseStamped& robot_pose,
bool pose_available, bool costmap_stale)
{
const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor;
// Cổng vào: chỉ giám sát khi thực sự đang bám một plan của một profile được phép, với dữ liệu còn
// dùng được. Thiếu bất kỳ điều kiện nào thì XOÁ luôn trạng thái debounce — nếu chỉ bỏ qua, chuỗi
// "đúng liên tục" sẽ được nối lại qua một quãng gián đoạn và `confirm_time` mất ý nghĩa.
const bool monitorable = cfg.enabled && deps_.path_check != nullptr && has_active_request_ &&
pose_available && !costmap_stale && !latest_plan_.empty() &&
state_machine_.state() == NavigationState::kControlling &&
cfg.monitors(active_request_.profile);
if (!monitorable)
{
resetPathMonitor();
return;
}
// Route rỗng = KHÔNG có đường xử lý cho trigger đó. Khai hoả trong tình trạng này là biến một cơ
// chế đang tắt thành ABORT tức thì: state machine thấy cờ, gọi escalateToRecovery, route cạn ngay
// từ phần tử đầu, và chặng chết ngay lần đầu thấy vật cản. Giám sát cái mà không ai xử lý được
// thì thà đừng giám sát — để `controller_patience` lo như trước khi có cơ chế này.
//
// Ba nút độc lập cho mỗi phép đo, cố ý: cờ riêng (`path_blocked_enabled`/`off_path_enabled`,
// 2026-08-06 — nói thẳng ý định thay vì đặt ngưỡng về 0), ngưỡng của chính nó, và route.
const bool blocked_route_ready = cfg.path_blocked_enabled &&
!config_.state_machine.recovery_routes.path_blocked.empty();
const bool off_path_route_ready = cfg.off_path_enabled &&
!config_.state_machine.recovery_routes.off_path.empty();
// Nhịp quét riêng: đọc vài chục ô costmap mỗi control cycle 30 Hz là phí, mà vật cản cũng không
// xuất hiện nhanh hơn chu kỳ cập nhật costmap (6 Hz).
if (has_last_path_check_ && (now - last_path_check_).toSec() < cfg.check_period)
{
return;
}
last_path_check_ = now;
has_last_path_check_ = true;
const std::size_t from = nearestIndex(latest_plan_, robot_pose);
// --- Phép đo 1: tuyến phía trước có bị chắn không -------------------------------------------
const bool blocked_now = blocked_route_ready && planIsBlocked(latest_plan_, from);
if (blocked_now)
{
if (!blocked_seen_)
{
blocked_since_ = now;
blocked_seen_ = true;
}
if (!path_blocked_ && (now - blocked_since_).toSec() >= cfg.confirm_time)
{
path_blocked_ = true;
robot::log_warning("[move_base2] PathMonitor: the path ahead is blocked at %.2f m (horizon "
"%.2f m) — stopping to plan a detour.\n",
last_block_distance_, cfg.horizon);
}
}
else
{
blocked_seen_ = false;
path_blocked_ = false;
}
// --- Phép đo 2: robot đã lệch khỏi plan bao xa ----------------------------------------------
//
// Đo so với PLAN ĐANG CHẠY, không phải tuyến gốc của order: sau một lượt detour hợp lệ, plan đang
// chạy CHÍNH LÀ đường vòng và robot nằm trên nó, nên không khai hoả oan. Ràng buộc "lệch bao
// nhiêu so với tuyến fleet" là việc của `max_deviation` bên trong behavior detour.
const bool grace = has_last_plan_applied_ &&
(now - last_plan_applied_).toSec() < cfg.grace_after_new_plan;
if (off_path_route_ready && cfg.max_cross_track > 0.0 && !grace)
{
const double error = crossTrackError(latest_plan_, robot_pose); // [m]
if (error > cfg.max_cross_track)
{
if (!off_path_seen_)
{
off_path_since_ = now;
off_path_seen_ = true;
}
if (!off_path_ && (now - off_path_since_).toSec() >= cfg.confirm_time)
{
off_path_ = true;
robot::log_warning("[move_base2] PathMonitor: the robot is %.2f m off the plan (limit "
"%.2f m) — stopping.\n", error, cfg.max_cross_track);
}
}
else
{
off_path_seen_ = false;
off_path_ = false;
}
}
else
{
off_path_seen_ = false;
off_path_ = false;
}
// --- Phép đo 4: planner đòi đi mà robot không tiến ------------------------------------------
updateProgressMonitor(now, from, robot_pose);
}
namespace
{
/// @brief Liệt kê các ô baseline "(x, y) (x, y) ..." [m, frame base_link]; "-" khi rỗng.
void describeBaselineCells(const MotionBlockResult& result, char* out, std::size_t size)
{
std::size_t used = 0;
out[0] = '\0';
if (result.baseline_listed <= 0)
{
std::snprintf(out, size, "-");
return;
}
for (int i = 0; i < result.baseline_listed && used + 1 < size; ++i)
{
const int n = std::snprintf(out + used, size - used, "%s(%.2f, %.2f)", i > 0 ? " " : "",
result.baseline_xy[i][0], result.baseline_xy[i][1]);
if (n < 0)
{
break;
}
used += static_cast<std::size_t>(n);
}
if (result.baseline_cells > result.baseline_listed && used + 1 < size)
{
std::snprintf(out + used, size - used, " +%d more", result.baseline_cells - result.baseline_listed);
}
}
} // namespace
void ControlLoop::applyCollisionGuard(const robot_geometry_msgs::PoseStamped& robot_pose,
bool pose_available, robot_geometry_msgs::Twist& candidate)
{
const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor;
// Cùng cổng vào với hai phép đo kia, cùng lý do: chỉ đo khi thực sự đang bám plan của một profile
// được phép và có đường xử lý. Không có route thì dừng-mà-không-ai-xử là ABORT trá hình.
const bool armed = cfg.enabled && cfg.collision_enabled && deps_.path_check != nullptr &&
!config_.state_machine.recovery_routes.collision.empty() &&
has_active_request_ && pose_available &&
state_machine_.state() == NavigationState::kControlling &&
cfg.monitors(active_request_.profile);
if (!armed)
{
collision_brake_ = false;
collision_blocked_ = false;
collision_streak_ = 0;
return;
}
// Thân robot: khai tay đủ ba số, hoặc cả ba = 0 thì lấy từ footprint costmap mỗi cycle (rẻ: một
// vector 4 điểm). Không có cả hai nguồn thì đây là "không kết luận được" — không dừng, không xoá
// chuỗi xác nhận — nhưng phải kêu, vì guard đang mù mà cấu hình bảo là bật.
double front = cfg.collision_front_offset;
double rear = cfg.collision_rear_offset;
double side = cfg.collision_side_offset;
const bool body_from_costmap = !(front > 0.0) && !(rear > 0.0) && !(side > 0.0);
if (body_from_costmap)
{
if (!deps_.path_check->robotBodyExtents(front, rear, side))
{
robot::log_error_throttle(5.0,
"[move_base2] PathMonitor: collision guard has no body geometry — "
"the costmap footprint is unavailable and collision_*_offset are "
"not set; the commanded arc is NOT checked.\n");
collision_brake_ = false;
return;
}
if (!collision_body_logged_ || std::fabs(front - collision_body_front_) > 1e-3 ||
std::fabs(rear - collision_body_rear_) > 1e-3 || std::fabs(side - collision_body_side_) > 1e-3)
{
collision_body_logged_ = true;
collision_body_front_ = front;
collision_body_rear_ = rear;
collision_body_side_ = side;
robot::log_info("[move_base2] PathMonitor: collision body from the costmap footprint: "
"front=%.3f rear=%.3f side=%.3f m (+%.2f m padding).\n",
front, rear, side, cfg.collision_footprint_padding);
}
}
MotionCheckParams params;
params.lookahead = cfg.collision_lookahead;
params.max_samples = cfg.collision_max_samples;
params.front_offset = front;
params.rear_offset = rear;
params.side_offset = side;
params.padding = cfg.collision_footprint_padding;
params.cost_threshold = static_cast<unsigned char>(cfg.collision_cost_threshold);
params.min_speed = cfg.collision_min_speed;
params.exclude_baseline = cfg.collision_exclude_baseline;
params.lookahead_angle = cfg.collision_lookahead_angle;
MotionBlockResult result;
if (!deps_.path_check->checkMotion(robot_pose, candidate.linear.x, candidate.angular.z, params,
result))
{
// Không kết luận được (TF/costmap) — không biết thì không dừng, cũng không xoá chuỗi xác nhận.
collision_brake_ = false;
return;
}
if (result.scanned == 0)
{
// Xoay tại chỗ / v dưới min_speed: cung suy biến, không có bằng chứng mới.
collision_brake_ = false;
return;
}
if (!result.blocked)
{
collision_brake_ = false;
collision_streak_ = 0;
if (collision_blocked_)
{
collision_blocked_ = false;
robot::log_info("[move_base2] PathMonitor: the commanded arc is clear again.\n");
}
if (result.baseline_cells > 0 && config_.debug_state)
{
// Người vận hành thấy robot "đang chạm" mà vẫn đi: phải nói rõ vì sao được đi, và ô nào.
char cells[160];
describeBaselineCells(result, cells, sizeof(cells));
robot::log_info_throttle(2.0,
"[move_base2][debug] PathMonitor: body overlaps %d LETHAL cell(s) "
"but the commanded arc adds none — letting it move (v=%.2f m/s, "
"omega=%.2f rad/s); cells in base frame: %s\n",
result.baseline_cells, candidate.linear.x, candidate.angular.z,
cells);
}
return;
}
collision_hit_distance_ = result.distance;
if (result.distance > cfg.collision_stop_distance)
{
// Xa hơn quãng dừng: chưa phải dừng, nhưng không được lao vào ở tốc độ tối đa. Kẹp theo quãng
// còn lại — cùng công thức mọi tầng phanh khác trong stack.
collision_brake_ = false;
collision_streak_ = 0;
if (cfg.collision_brake_decel > 0.0)
{
const double room = result.distance - cfg.collision_stop_distance;
const double cap = std::sqrt(2.0 * cfg.collision_brake_decel * room);
if (std::fabs(candidate.linear.x) > cap)
{
// Kẹp có log (throttle): 4/9 không tách được cap của guard với head_slowdown của planner
// vì cap chạy im lặng.
robot::log_info_throttle(2.0,
"[move_base2] PathMonitor: contact %.2f m along the commanded arc "
"— v capped %.2f -> %.2f m/s.\n",
result.distance, candidate.linear.x, cap);
candidate.linear.x = candidate.linear.x < 0.0 ? -cap : cap;
}
}
return;
}
// Trong quãng dừng theo MÉT. Nhưng mét dọc cung chưa phải "sắp chạm" (2026-09-04, run 16:26,
// 11 lần nổ trong 15 s khi xoay gần tại chỗ ở góc trụ): cùng 0.15 m cung, đi thẳng 0.36 m/s là
// chạm sau 0.4 s, còn xoay bò v 0.04 ω −0.5 (R 0.08 m) là quay 107° và 3.8 s nữa — PRIEST đã
// thôi xoay sau 30–60° để thẳng hàng với path. Guard mô hình lệnh là cung không đổi nên không
// biết điều đó; thước đo phải là thời gian và góc. Chưa "sắp" thì không dừng, không đếm, không
// giơ cờ — chỉ kẹp v để luôn còn >= stop_time tới chạm; guard soi lại mỗi cycle, PRIEST cứ xoay
// tiếp thì `turn` tụt dần và tới ngưỡng là dừng thật.
const double speed = std::fabs(candidate.linear.x);
const double kappa = speed > 1e-6 ? candidate.angular.z / candidate.linear.x : 0.0;
const double time_to_contact = speed > 1e-6 ? result.distance / speed
: std::numeric_limits<double>::infinity();
const double turn_to_contact = std::fabs(kappa) * result.distance;
const double creep_cap =
std::max(0.0, result.distance - cfg.collision_footprint_padding) / cfg.collision_stop_time;
// Kẹp còn thấp hơn min_speed là "không cho đi" trá hình: coi là sắp chạm để đường leo thang
// (no_valid_command -> controller_patience) còn chạy, thay vì giữ 0 vô hạn mà không ai biết.
const bool imminent = time_to_contact <= cfg.collision_stop_time ||
turn_to_contact <= cfg.collision_stop_angle ||
creep_cap < cfg.collision_min_speed;
if (!imminent)
{
collision_brake_ = false;
collision_streak_ = 0;
if (collision_blocked_)
{
collision_blocked_ = false;
robot::log_info("[move_base2] PathMonitor: the commanded arc is clear again.\n");
}
if (speed > creep_cap)
{
candidate.linear.x = candidate.linear.x < 0.0 ? -creep_cap : creep_cap;
}
if (config_.debug_state)
{
robot::log_info_throttle(1.0,
"[move_base2][debug] PathMonitor: contact %.2f m along the arc but "
"%.1f s and %.2f rad away — turning, not stopping; v capped %.2f -> "
"%.2f m/s (omega %.2f rad/s).\n",
result.distance, time_to_contact, turn_to_contact, speed,
creep_cap, candidate.angular.z);
}
return;
}
// Sắp chạm thật: lệnh ra bằng 0 NGAY cycle này (trọng tài phát 0 tức thì), rồi đếm xác nhận.
collision_brake_ = true;
++collision_streak_;
// (A) Lệnh vừa bị huỷ thì với state machine nó KHÔNG hợp lệ. Trước đây guard ép lệnh về 0 nhưng
// để nguyên `command_valid` của controller: khi trigger path_blocked đã bị khoá (replan thất bại,
// 3/9 t=723 và 4/9 t=225) state machine thấy controller vẫn "ổn", controller_patience không bao
// giờ chạy, robot đứng chết vô hạn không một dòng log. Báo đúng sự thật thì: trigger còn mở ->
// replan như cũ; trigger đã khoá -> controller_patience -> route controlling_failed -> ABORT.
controller_feedback_ = ControllerFeedback::kNoValidCommand;
if (!collision_blocked_ && collision_streak_ >= cfg.collision_confirm_cycles)
{
collision_blocked_ = true;
robot::log_warning("[move_base2] PathMonitor: the body would hit a real obstacle %.2f m along "
"the commanded arc (v=%.2f m/s, omega=%.2f rad/s, stop=%.2f m; contact in "
"%.1f s / %.2f rad) — stopping to replan (ignoring %d LETHAL cell(s) already "
"under the body).\n",
result.distance, candidate.linear.x, candidate.angular.z,
cfg.collision_stop_distance, time_to_contact, turn_to_contact,
result.baseline_cells);
if (config_.debug_state)
{
// Hình học của cú chạm, frame base_link (x tới, y trái): cạnh nào chạm, ô chạm ở đâu, và
// những ô đã nằm dưới thân bị bỏ qua. Đây là thứ duy nhất cho phép phân biệt "góc thân quét
// tới" với "người bước tới" khi đọc log mà không có costmap.
static const char* const kEdge[4] = { "right", "nose", "left", "tail" };
char cells[160];
describeBaselineCells(result, cells, sizeof(cells));
robot::log_info("[move_base2][debug] PathMonitor: hit at sample %d: %s edge touches cell "
"(%.2f, %.2f) in base frame; baseline %d cell(s): %s\n",
result.sample,
result.hit_edge >= 0 && result.hit_edge < 4 ? kEdge[result.hit_edge] : "?",
result.hit_x, result.hit_y, result.baseline_cells, cells);
}
}
else if (collision_blocked_)
{
// (B) Phanh kéo dài không được im: người đọc log phải thấy robot đang bị GIỮ, vì sao, và ai
// sẽ leo thang.
robot::log_warning_throttle(2.0,
"[move_base2] PathMonitor: still braking (%d cycles, contact %.2f m, "
"controller wants v=%.2f) — reported as no valid command; if the "
"path_blocked trigger is locked, controller_patience escalates.\n",
collision_streak_, result.distance, candidate.linear.x);
}
}
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
bool costmap_stale)
@@ -1327,8 +674,6 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
if (monitorable)
{
deps_.environment->refresh();
double front = sampling.body_front;
double rear = sampling.body_rear;
double side = sampling.body_side;
@@ -1523,14 +868,18 @@ bool ControlLoop::step()
travelled = std::hypot(dx, dy);
}
// Costmap còn hạn không — hỏi ở ĐÂY chứ không ở mục 3.5 như trước: PathMonitor cần nó, mà monitor
// Costmap còn hạn không — hỏi ở ĐÂY chứ không ở mục 3.5 như trước: EnvMonitor cần nó, mà monitor
// phải chạy xong trước state machine. Vẫn là một lời gọi mỗi cycle, chỉ đổi vị trí.
const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr &&
!deps_.costmap_status->isCurrent();
// --- 1b. Giám sát tuyến ---------------------------------------------------------------------
// Chạy TRƯỚC state machine: hai cờ nó sinh ra là dữ liệu vào của state machine ngay cycle này.
updatePathMonitor(now, robot_pose, pose_available, costmap_stale);
// Một snapshot costmap cho CẢ cycle: monitor và controller đọc cùng một lưới (P0b). No-op khi tắt snapshot.
if (deps_.environment != nullptr)
{
deps_.environment->refresh();
}
updateEnvMonitor(now, dt, robot_pose, pose_available, costmap_stale);
// --- 2. State machine -----------------------------------------------------------------------
@@ -1551,14 +900,12 @@ bool ControlLoop::step()
input.costmap_current = !costmap_stale;
input.robot_stopped = arbiter_.stopped();
input.travelled_since_oscillation_reset = travelled;
// Phép đo 3 dùng chung route với phép đo 1: cả hai cùng một cách xử lý — lập lại đường.
// EnvMonitor OR vào cùng bốn cổng của PathMonitor: cờ của nó chỉ khác false khi `action: recover`.
input.path_blocked = path_blocked_ || env_verdict_.path_blocked;
input.collision = collision_blocked_ || env_verdict_.collision; // Phép đo 3 có trigger/route riêng (2026-09-04)
input.off_path = off_path_;
// Phép đo 4 chỉ được leo thang ở mode "recover"; mode "log" đã in cảnh báo và dừng ở đó.
input.no_progress = (no_progress_ && config_.path_monitor.progress_action == "recover") ||
env_verdict_.no_progress;
// Bốn cổng của state machine do EnvMonitor cấp (Test/ENV_MONITOR_PLAN.md): cờ chỉ khác false khi
// verdict tương ứng có `action: recover`. `off_path` không còn nguồn nào (phép đo cũ đã bỏ 6/9/2026).
input.path_blocked = env_verdict_.path_blocked;
input.collision = env_verdict_.collision;
input.off_path = false;
input.no_progress = env_verdict_.no_progress;
// 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
@@ -1608,7 +955,6 @@ bool ControlLoop::step()
has_active_request_ = true;
has_pending_request_ = false;
latest_plan_.clear();
++plan_revision_;
order_plan_.clear();
has_outcome_ = false;
env_monitor_.onGoalAccepted(now);
@@ -1722,7 +1068,6 @@ bool ControlLoop::step()
}
robot_geometry_msgs::Twist candidate;
collision_brake_ = false; // chỉ applyCollisionGuard của CYCLE NÀY được bật lại.
env_controller_v_ = 0.0; // controller không chạy cycle này = không đòi đi.
if (output.start_recovery)
@@ -1763,8 +1108,7 @@ 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;
++plan_revision_;
planner_feedback_ = PlannerFeedback::kPlanReady;
planner_feedback_ = PlannerFeedback::kPlanReady;
if (config_.debug_plan)
{
robot::log_info("[move_base2][debug] recovery produced path with %zu pose(s); "
@@ -1880,9 +1224,6 @@ bool ControlLoop::step()
if (controller_feedback_ == ControllerFeedback::kCommandValid)
{
env_controller_v_ = candidate.linear.x; // trước guard / bao / trọng tài: ý định thật của controller
// Phép đo 3 của PathMonitor: soi chính lệnh sắp phát, TRƯỚC trọng tài.
applyCollisionGuard(robot_pose, pose_available, candidate);
// EnvMonitor: bao tốc độ theo tiếp xúc trên quỹ đạo thật. Chỉ tác động khi `contact/apply_command`
// (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)
@@ -1983,15 +1324,8 @@ bool ControlLoop::step()
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
// Sắp chạm vật cản thật cũng là "không ai được phát": lệnh 0 tức thì, không giảm dần.
arbiter_.arbitrate((costmap_stale || collision_brake_ || env_brake_) ? VelocitySource::kNone
: output.velocity_source,
arbiter_.arbitrate((costmap_stale || env_brake_) ? VelocitySource::kNone : output.velocity_source,
candidate, dt);
// Phép đo 4 đo lệnh SAU trọng tài: hold của planner, phanh của Phép đo 3, costmap stale đều ra
// 0 ở đây — đó chính là cách nó phân biệt "đang chờ" với "đòi đi mà không tiến".
if (dt > 0.0)
{
progress_cmd_accum_ += std::fabs(arbiter_.lastCommand().linear.x) * dt; // [m]
}
// --- 5. Báo kết quả -------------------------------------------------------------------------
if (output.report_outcome)
@@ -2048,7 +1382,6 @@ bool ControlLoop::step()
{
has_active_request_ = false;
latest_plan_.clear();
++plan_revision_;
planner_running_ = false;
}
cancel_requested_ = false;

View File

@@ -65,107 +65,6 @@ bool CostmapPosePort::lookupPose(const std::string& frame,
}
}
bool CostmapPathCheck::checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
std::size_t from_index, double horizon,
PlanBlockResult& out) const
{
if (costmap_ == nullptr || !tf_ || plan.empty() || from_index >= plan.size())
{
return false;
}
robot_costmap_2d::Costmap2D* grid = costmap_->getCostmap();
if (grid == nullptr)
{
return false;
}
PlanarTransform plan_to_grid;
if (!planarTransform(*tf_, plan[from_index].header.frame_id, costmap_->getGlobalFrameID(),
plan_to_grid))
{
// Không quy đổi được frame thì mọi kết luận đều vô nghĩa. Trả false = "không biết".
return false;
}
// Cùng giao thức khoá với map-update thread và planner: lượt quét chỉ đọc vài chục ô nên giữ
// mutex trọn lượt là rẻ, còn đọc lưới trong lúc nó đang được ghi thì kết luận không đáng tin.
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()));
out = move_base2::checkPlan(plan, from_index, horizon, *grid, plan_to_grid);
return true;
}
bool CostmapPathCheck::checkMotion(const robot_geometry_msgs::PoseStamped& robot_pose, double v,
double omega, const MotionCheckParams& params,
MotionBlockResult& out) const
{
if (costmap_ == nullptr || !tf_)
{
return false;
}
robot_costmap_2d::Costmap2D* grid = costmap_->getCostmap();
if (grid == nullptr)
{
return false;
}
// Pose robot ở frame của cổng pose (thường `map`), lưới ở `odom`: quy đổi cả vị trí lẫn hướng
// rồi tích phân cung ngay trong frame lưới — mỗi mẫu không phải tra TF lần nữa.
PlanarTransform pose_to_grid;
if (!planarTransform(*tf_, robot_pose.header.frame_id, costmap_->getGlobalFrameID(),
pose_to_grid))
{
return false;
}
double gx = 0.0;
double gy = 0.0;
pose_to_grid.apply(robot_pose.pose.position.x, robot_pose.pose.position.y, gx, gy);
const auto& q = robot_pose.pose.orientation;
const double yaw_pose = std::atan2(2.0 * (q.w * q.z + q.x * q.y),
1.0 - 2.0 * (q.y * q.y + q.z * q.z));
const double yaw_grid = yaw_pose + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw);
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()));
out = move_base2::checkMotion(gx, gy, yaw_grid, v, omega, params, *grid, &baseline_scratch_);
return true;
}
bool CostmapPathCheck::robotBodyExtents(double& front, double& rear, double& side) const
{
if (costmap_ == nullptr)
{
return false;
}
// Footprint KHÔNG đệm: guard có collision_footprint_padding riêng, cộng đệm costmap vào nữa là
// đếm biên hai lần. Đây cũng là hình mà SBPL/PRIEST dùng, nên ba bên cùng một thân.
const std::vector<robot_geometry_msgs::Point>& fp = costmap_->getUnpaddedRobotFootprint();
if (fp.size() < 3)
{
return false;
}
double max_x = std::numeric_limits<double>::lowest();
double min_x = std::numeric_limits<double>::max();
double max_abs_y = 0.0;
for (const robot_geometry_msgs::Point& p : fp)
{
if (!std::isfinite(p.x) || !std::isfinite(p.y))
{
return false;
}
max_x = std::max(max_x, p.x);
min_x = std::min(min_x, p.x);
max_abs_y = std::max(max_abs_y, std::fabs(p.y));
}
if (!(max_x > 0.0) || !(min_x < 0.0) || !(max_abs_y > 0.0))
{
return false; // suy biến hoặc base_link nằm ngoài thân — không tin được
}
front = max_x;
rear = -min_x;
side = max_abs_y;
return true;
}
// ================================================================================================
// CostmapEnvironment
// ================================================================================================
@@ -480,12 +379,10 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf
// Costmap ĐIỀU KHIỂN (local) là nguồn của guard "không đi mù" — xem doc của CostmapStatusAdapter.
costmap_status_.setCostmap(local_costmap_.get());
// PathMonitor quét tuyến trên chính costmap local — cùng lưới mà detour lập đường vòng trên đó.
path_check_.setCostmap(local_costmap_.get());
path_check_.setTf(tf_);
// EnvMonitor đọc cùng costmap local (thay PathMonitor); TF để quy plan (map) và pose về frame lưới.
// EnvMonitor đọc costmap local — cùng lưới mà detour lập đường vòng trên đó; TF để quy plan (map) và
// pose về frame lưới.
environment_.setCostmap(local_costmap_.get());
controller_.setSnapshotRefreshedByLoop(true); // ControlLoop làm mới snapshot một lần đầu cycle (P0b)
environment_.setTf(tf_);
// Gắn ngay: host có thể hỏi dữ liệu hiển thị bất cứ lúc nào sau initialize(), kể cả trước khi
@@ -736,7 +633,6 @@ ControlLoopDeps NavigationRuntime::deps()
deps.mission = &mission_;
deps.action = &action_;
deps.costmap_status = &costmap_status_;
deps.path_check = &path_check_;
deps.environment = &environment_;
return deps;
}

View File

@@ -178,284 +178,4 @@ double crossTrackError(const std::vector<robot_geometry_msgs::PoseStamped>& plan
return best;
}
PlanBlockResult checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
std::size_t from_index, double horizon,
const robot_costmap_2d::Costmap2D& grid,
const PlanarTransform& plan_to_grid)
{
PlanBlockResult result;
if (plan.empty() || from_index >= plan.size() || !(horizon > 0.0))
{
return result;
}
double travelled = 0.0; // [m]
for (std::size_t i = from_index; i < plan.size(); ++i)
{
if (i > from_index)
{
travelled += std::hypot(plan[i].pose.position.x - plan[i - 1].pose.position.x,
plan[i].pose.position.y - plan[i - 1].pose.position.y);
if (travelled > horizon)
{
break;
}
}
double gx = 0.0;
double gy = 0.0;
plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, gx, gy);
unsigned int mx = 0;
unsigned int my = 0;
if (!grid.worldToMap(gx, gy, mx, my))
{
// Ra ngoài cửa sổ lưới: phần còn lại của tuyến cũng nằm ngoài (lưới lăn theo robot), nên
// dừng hẳn thay vì quét tiếp cho tới hết horizon.
break;
}
++result.scanned;
const unsigned char cost = grid.getCost(mx, my);
if (cost == robot_costmap_2d::NO_INFORMATION)
{
continue;
}
if (cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)
{
result.blocked = true;
result.index = i;
result.distance = travelled;
return result;
}
}
return result;
}
namespace
{
/// [m] Quãng đầu cung bị bỏ qua — chỗ robot đang đứng. Xem @ref checkMotion.
constexpr double kSkipOwnFootprintDist = 0.05;
/// Một điểm dò: ra ngoài lưới hay chưa có thông tin đều là KHÔNG chạm.
bool probeHits(const robot_costmap_2d::Costmap2D& grid, double x, double y,
unsigned char threshold, const std::vector<unsigned int>& baseline)
{
unsigned int mx = 0;
unsigned int my = 0;
if (!grid.worldToMap(x, y, mx, my))
{
return false;
}
const unsigned char cost = grid.getCost(mx, my);
if (cost == robot_costmap_2d::NO_INFORMATION || cost < threshold)
{
return false;
}
// Ô đã nằm dưới thân tại pose hiện tại: lệnh này không "đưa thêm" nó vào thân.
return baseline.empty() || !std::binary_search(baseline.begin(), baseline.end(), grid.getIndex(mx, my));
}
/**
* @brief Gom các ô >= @p threshold đang nằm dưới hình chữ nhật thân đệm tại pose hiện tại.
*
* Duyệt DIỆN TÍCH chứ không phải chu vi: ô nằm sâu trong thân mà chỉ lấy chu vi thì mẫu sau quét
* qua nó và tính oan là "mới". Ô được coi là dưới thân khi TÂM ô nằm trong hình chữ nhật nới thêm
* nửa ô — cùng độ rộng với những gì probe chu vi (bước nửa ô) có thể chạm tới ở s = 0. Kết quả
* được sort để probe tra bằng binary_search. ~600 ô ở lưới 0.05 m; kiểm cost trước khi quy đổi
* hình học nên phần lớn ô thoát sớm.
*/
void collectBaseline(const robot_costmap_2d::Costmap2D& grid, double x, double y, double yaw,
double front, double rear, double side, unsigned char threshold,
std::vector<unsigned int>& out, MotionBlockResult& result)
{
out.clear();
result.baseline_listed = 0;
const double c = std::cos(yaw);
const double sn = std::sin(yaw);
const double corners_x[4] = { front, front, -rear, -rear };
const double corners_y[4] = { side, -side, side, -side };
double min_wx = std::numeric_limits<double>::max();
double min_wy = std::numeric_limits<double>::max();
double max_wx = std::numeric_limits<double>::lowest();
double max_wy = std::numeric_limits<double>::lowest();
for (int i = 0; i < 4; ++i)
{
const double wx = x + corners_x[i] * c - corners_y[i] * sn;
const double wy = y + corners_x[i] * sn + corners_y[i] * c;
min_wx = std::min(min_wx, wx);
max_wx = std::max(max_wx, wx);
min_wy = std::min(min_wy, wy);
max_wy = std::max(max_wy, wy);
}
int mx0 = 0;
int my0 = 0;
int mx1 = 0;
int my1 = 0;
grid.worldToMapEnforceBounds(min_wx, min_wy, mx0, my0);
grid.worldToMapEnforceBounds(max_wx, max_wy, mx1, my1);
const double slack = 0.5 * grid.getResolution();
for (int my = my0; my <= my1; ++my)
{
for (int mx = mx0; mx <= mx1; ++mx)
{
const unsigned char cost = grid.getCost(static_cast<unsigned int>(mx), static_cast<unsigned int>(my));
if (cost == robot_costmap_2d::NO_INFORMATION || cost < threshold)
{
continue;
}
double wx = 0.0;
double wy = 0.0;
grid.mapToWorld(static_cast<unsigned int>(mx), static_cast<unsigned int>(my), wx, wy);
const double dx = wx - x;
const double dy = wy - y;
const double bx = dx * c + dy * sn;
const double by = -dx * sn + dy * c;
if (bx < -rear - slack || bx > front + slack || std::fabs(by) > side + slack)
{
continue;
}
out.push_back(grid.getIndex(static_cast<unsigned int>(mx), static_cast<unsigned int>(my)));
if (result.baseline_listed < MotionBlockResult::kMaxListedBaseline)
{
result.baseline_xy[result.baseline_listed][0] = bx;
result.baseline_xy[result.baseline_listed][1] = by;
++result.baseline_listed;
}
}
}
std::sort(out.begin(), out.end());
}
} // namespace
MotionBlockResult checkMotion(double x, double y, double yaw, double v, double omega,
const MotionCheckParams& params,
const robot_costmap_2d::Costmap2D& grid,
std::vector<unsigned int>* baseline_scratch)
{
MotionBlockResult result;
if (std::fabs(v) < params.min_speed || !(params.lookahead > 0.0) || params.max_samples < 1)
{
return result;
}
const double direction = v < 0.0 ? -1.0 : 1.0;
// Độ cong của cung: omega / v. Lùi thì cung lật chiều cùng với v — công thức giữ nguyên dấu.
const double kappa = omega / v;
// Bước dò không được lớn hơn một ô lưới: với bước 0.13 m mũi robot ở mẫu này còn cách tường
// mỏng 1 ô, mẫu sau đã ở BÊN KIA tường — cả hai đều sạch, robot đâm xuyên. max_samples chỉ là
// trần thưa; lưới mịn hơn thì dò dày hơn, tối đa lookahead/resolution mẫu (16 ở 0.8 m / 0.05).
double step = params.lookahead / params.max_samples;
const double resolution = grid.getResolution();
if (resolution > 0.0 && step > resolution)
{
step = resolution;
}
const int samples = static_cast<int>(std::ceil(params.lookahead / step - 1.0e-9));
const double front = params.front_offset + params.padding;
const double rear = params.rear_offset + params.padding;
const double side = params.side_offset + params.padding;
const double sin0 = std::sin(yaw);
const double cos0 = std::cos(yaw);
std::vector<unsigned int> local_baseline;
std::vector<unsigned int>& baseline = baseline_scratch != nullptr ? *baseline_scratch : local_baseline;
baseline.clear();
if (params.exclude_baseline)
{
collectBaseline(grid, x, y, yaw, front, rear, side, params.cost_threshold, baseline, result);
}
result.baseline_cells = static_cast<int>(baseline.size());
for (int i = 1; i <= samples; ++i)
{
const double walk = std::min(step * i, params.lookahead); // [m] dọc cung, luôn dương
if (walk < kSkipOwnFootprintDist)
{
continue;
}
if (std::fabs(kappa) * walk > params.lookahead_angle)
{
break; // quay quá góc này thì lệnh đã đổi — phần cung còn lại không phải tương lai thật
}
// Vị trí trên cung sau quãng `walk` theo chiều `direction`.
double px = 0.0;
double py = 0.0;
double pyaw = yaw;
const double s = direction * walk; // quãng có dấu
if (std::fabs(kappa) < 1.0e-6)
{
px = x + s * cos0;
py = y + s * sin0;
}
else
{
pyaw = yaw + kappa * s;
px = x + (std::sin(pyaw) - sin0) / kappa;
py = y - (std::cos(pyaw) - cos0) / kappa;
}
++result.scanned;
// Dò TOÀN BỘ CHU VI footprint đã đệm tại mẫu này, không phải 5 điểm rời. Năm điểm rời kéo dọc
// cung là năm đường quét, giữa chúng hở tới nửa bề rộng thân: hai trụ cách nhau 0.45 m nằm lọt
// giữa đường quét mũi (ngang 0) và đường quét hông (ngang ±0.53) — không đường nào chạm, robot
// ôm cả hai trụ mới dừng (đo 4/9: near=0.36 m @ +70° = góc trước-trái thân). Bỏ inflation thì
// trụ chỉ còn 2-3 ô, dò điểm rời chắc chắn lọt; "dò vật thật" bắt buộc đi kèm "dò kín thân".
// Chu vi lấy mẫu dày hơn một ô, và bước dọc cung không quá một ô, nên một ô vật cản muốn vào
// trong footprint bắt buộc phải cắt chu vi ở một mẫu nào đó — không còn khe hình học.
const double c = std::cos(pyaw);
const double sn = std::sin(pyaw);
const double spacing = resolution > 0.0 ? 0.5 * resolution : 0.025;
// Bốn đỉnh trong khung thân: x dọc heading, y sang trái.
const double x_min = -rear;
const double x_max = front;
const double y_max = side; // side đã gồm padding; side_offset = 0 -> dải rộng 2*padding
const double y_min = -side;
auto probe_body = [&](double bx, double by) {
const double wx = px + bx * c - by * sn;
const double wy = py + bx * sn + by * c;
if (!probeHits(grid, wx, wy, params.cost_threshold, baseline))
{
return false;
}
// Ghi ô chạm theo frame robot HIỆN TẠI (không phải thân đã dịch tới mẫu s) để log đọc được.
const double dx = wx - x;
const double dy = wy - y;
result.hit_x = dx * cos0 + dy * sin0;
result.hit_y = -dx * sin0 + dy * cos0;
return true;
};
auto probe_edge = [&](int edge, double x0, double y0, double x1, double y1) {
const double len = std::hypot(x1 - x0, y1 - y0);
const int n = std::max(1, static_cast<int>(std::ceil(len / spacing)));
for (int e = 0; e <= n; ++e)
{
const double t = static_cast<double>(e) / n;
if (probe_body(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t))
{
result.hit_edge = edge;
return true;
}
}
return false;
};
const bool hit = probe_edge(0, x_min, y_min, x_max, y_min) || // cạnh phải
probe_edge(1, x_max, y_min, x_max, y_max) || // cạnh mũi
probe_edge(2, x_max, y_max, x_min, y_max) || // cạnh trái
probe_edge(3, x_min, y_max, x_min, y_min); // cạnh đuôi
if (hit)
{
result.blocked = true;
result.sample = i;
result.distance = walk;
return result;
}
}
return result;
}
} // namespace move_base2

View File

@@ -366,7 +366,12 @@ bool ControllerRunner::setPlan(const std::vector<robot_geometry_msgs::PoseStampe
if (costmap_lock_enabled_)
{
if (costmap_->isSnapshotEnabled())
costmap_->refreshSnapshot();
{
if (!snapshot_refreshed_by_loop_)
{
costmap_->refreshSnapshot();
}
}
else
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
@@ -526,7 +531,12 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
if (costmap_lock_enabled_)
{
if (costmap_->isSnapshotEnabled())
costmap_->refreshSnapshot();
{
if (!snapshot_refreshed_by_loop_)
{
costmap_->refreshSnapshot();
}
}
else
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
@@ -585,7 +595,12 @@ bool ControllerRunner::isGoalReached()
if (costmap_lock_enabled_)
{
if (costmap_->isSnapshotEnabled())
costmap_->refreshSnapshot();
{
if (!snapshot_refreshed_by_loop_)
{
costmap_->refreshSnapshot();
}
}
else
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));

View File

@@ -624,7 +624,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
{
last_valid_control_ = in.now;
// Phép đo 4 (PathMonitor): controller vẫn ra lệnh hợp lệ nhưng robot không tiến.
// kStall (EnvMonitor): controller vẫn ra lệnh hợp lệ nhưng robot không đi được đâu.
if (in.no_progress)
{
out.stop_planner = true;