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

@@ -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;