feat: EnvMonitor thay PathMonitor — giám sát môi trường bằng EDT/geodesic/quỹ đạo thật

Bộ giám sát mới trong ControlLoop (core/env_monitor, core/grid_analysis, ports/environment_port,
io/env_logger), thay bốn phép đo của PathMonitor (code cũ còn, tắt bằng path_monitor/enabled: false):

- kContact: dò tiếp xúc dọc quỹ đạo local planner (thay cung v/omega), bao tốc độ sqrt(2a(d - margin))
  có dư, phanh chỉ khi vượt bao, cờ collision khi kề mũi tĩnh 1 s; cổng xoay tại chỗ theo lệnh
  controller muốn; hysteresis + xác nhận khi nhả; đứng ra sau detour không dịch robot (nhường
  controller); giữ phanh khi route khoá thì báo no valid command để controller_patience leo thang.
- kStall: cost_to_go = geodesic tới điểm thoát 2 m dọc plan + phần plan còn lại, index plan bám cửa
  sổ, bộ lọc lật liên thông; cờ no_progress chỉ khi cổng dịch chuyển thực mở (robot không đi được
  đâu trong 12 s dù lệnh >= 1,5 m) — thay ngân sách replan cho stall.
- kUnreachable: liên thông tới điểm thoát, đang ở action log.
- EnvLogger ghi JSONL mỗi tick nặng; config/runtime/env_monitor_params.yaml đủ khoá, comment tiếng
  Việt; ControllerPort::measuredVelocity; FakeEnvironmentPort cho test.

Sim 5–6/9: hết churn detour, khe 1,25 m đi qua 0,5 m/s, lượt 6/9 10:15 2 detour/142 s không oan.
Test: grid_analysis 31, env_monitor 43, plan_inspector 37, walking_skeleton 87, các bộ khác 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:30:31 +07:00
parent f2097380e4
commit 261cc20ad4
26 changed files with 5589 additions and 7 deletions

View File

@@ -157,6 +157,56 @@ 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();
}
bool EnvSamplingConfig::validate(std::string& error) const
{
if (!std::isfinite(check_period) || check_period <= 0.0)
{
error = "env_monitor/check_period must be > 0 [s]";
return false;
}
if (lethal_threshold < 1 || lethal_threshold > 254)
{
error = "env_monitor/body/lethal_threshold must be in [1, 254]";
return false;
}
const bool any_body = body_front > 0.0 || body_rear > 0.0 || body_side > 0.0;
const bool all_body = body_front > 0.0 && body_rear > 0.0 && body_side > 0.0;
if (any_body && !all_body)
{
error = "env_monitor/body: front_offset, rear_offset and side_offset must all be > 0 [m] when any "
"is set (all 0 = use the costmap footprint)";
return false;
}
if (!std::isfinite(padding) || padding < 0.0 || !std::isfinite(horizon) || horizon <= 0.0 ||
!std::isfinite(corridor_margin) || corridor_margin < 0.0 || !std::isfinite(corridor_cap) ||
corridor_cap <= 0.0 || !std::isfinite(target_backoff) || target_backoff < 0.0 ||
!std::isfinite(track_back) || track_back < 0.0 || !std::isfinite(track_ahead) || track_ahead <= 0.0 ||
!std::isfinite(exit_ahead) || exit_ahead < 0.0 ||
!std::isfinite(robot_snap) || robot_snap < 0.0)
{
error = "env_monitor: padding/corridor_margin/target_backoff/robot_snap/track_back/exit_ahead >= 0, "
"horizon/corridor_cap/track_ahead > 0 [m]";
return false;
}
if (use_local_plan != "auto" && use_local_plan != "true" && use_local_plan != "false")
{
error = "env_monitor/contact/use_local_plan must be auto | true | false";
return false;
}
if (!std::isfinite(local_plan_start_tol) || local_plan_start_tol <= 0.0 ||
!std::isfinite(contact_lookahead) || contact_lookahead <= 0.0)
{
error = "env_monitor/contact: local_plan_start_tol and lookahead must be > 0 [m]";
return false;
}
return true;
}
// ================================================================================================
// ControlLoop
// ================================================================================================
@@ -291,6 +341,53 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
}
}
// 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.
env_logger_.reset();
if (config_.env_monitor.enabled)
{
if (deps_.environment == nullptr)
{
robot::log_error("[move_base2] env_monitor is enabled but no EnvironmentPort is wired — EnvMonitor "
"stays OFF.\n");
}
else
{
if (!config_.env_sampling.validate(error) || !env_monitor_.configure(config_.env_monitor, error))
{
return false;
}
robot::log_info("[move_base2] %s\n sampling : check=%.2f s lethal>=%d padding=%.2f m horizon=%.1f m "
"corridor_margin=%.2f m use_local_plan=%s lookahead=%.1f m body=%s\n",
config_.env_monitor.describe().c_str(), config_.env_sampling.check_period,
config_.env_sampling.lethal_threshold, config_.env_sampling.padding,
config_.env_sampling.horizon, config_.env_sampling.corridor_margin,
config_.env_sampling.use_local_plan.c_str(), config_.env_sampling.contact_lookahead,
config_.env_sampling.body_front > 0.0 ? "config" : "costmap footprint");
const bool shadow = config_.env_monitor.stall.action != "recover" &&
config_.env_monitor.unreachable.action != "recover" &&
config_.env_monitor.contact.action != "recover" &&
!config_.env_monitor.contact.apply_command;
robot::log_info("[move_base2] EnvMonitor mode: %s\n",
shadow ? "SHADOW (log only; no flags, no braking, no speed cap)"
: "ACTIVE on at least one verdict or on the command");
if (config_.env_logger.enabled)
{
env_logger_ = std::make_unique<EnvLogger>();
if (!env_logger_->open(config_.env_logger, error))
{
robot::log_error("[move_base2] %s — EnvMonitor runs without the JSONL logger.\n", error.c_str());
env_logger_.reset();
error.clear();
}
else
{
robot::log_info("[move_base2] EnvMonitor logger writing to %s\n", env_logger_->path().c_str());
}
}
}
}
initialized_ = true;
reset();
return true;
@@ -331,6 +428,14 @@ void ControlLoop::reset()
resetPathMonitor();
has_last_plan_applied_ = false;
env_monitor_.reset();
env_verdict_ = EnvVerdict();
env_geometry_ = EnvGeometry();
has_last_env_heavy_ = false;
has_last_env_debug_ = false;
env_brake_ = false;
env_used_local_plan_ = false;
has_outcome_ = false;
outcome_report_count_ = 0;
last_reason_ = "";
@@ -1173,6 +1278,190 @@ void ControlLoop::applyCollisionGuard(const robot_geometry_msgs::PoseStamped& ro
}
}
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
bool costmap_stale)
{
env_brake_ = false;
if (!config_.env_monitor.enabled || deps_.environment == nullptr || !env_monitor_.configured())
{
return;
}
if (!has_active_request_)
{
// Không có chặng: mọi ngân sách/mốc thuộc chặng cũ. Verdict rỗng.
env_monitor_.reset();
env_verdict_ = EnvVerdict();
env_geometry_ = EnvGeometry();
has_last_env_heavy_ = false;
env_plan_index_valid_ = false;
return;
}
const EnvSamplingConfig& sampling = config_.env_sampling;
const bool monitorable = state_machine_.state() == NavigationState::kControlling && pose_available &&
!latest_plan_.empty() && sampling.monitors(active_request_.profile);
EnvSample s;
s.now = now;
s.dt = dt;
s.costmap_current = !costmap_stale;
s.has_plan = monitorable;
s.robot_x = robot_pose.pose.position.x;
s.robot_y = robot_pose.pose.position.y;
const robot_geometry_msgs::Twist& last_cmd = arbiter_.lastCommand();
s.v_cmd = last_cmd.linear.x;
s.w_cmd = last_cmd.angular.z;
robot_geometry_msgs::Twist measured;
if (deps_.controller->measuredVelocity(measured))
{
s.v_meas = measured.linear.x;
}
s.controller_valid = controller_feedback_ != ControllerFeedback::kNoValidCommand;
s.v_controller = env_controller_v_;
if (!latest_plan_.empty() && pose_available)
{
s.d_goal = std::hypot(latest_plan_.back().pose.position.x - robot_pose.pose.position.x,
latest_plan_.back().pose.position.y - robot_pose.pose.position.y);
}
if (monitorable)
{
deps_.environment->refresh();
double front = sampling.body_front;
double rear = sampling.body_rear;
double side = sampling.body_side;
bool have_body = front > 0.0 && rear > 0.0 && side > 0.0;
if (!have_body)
{
have_body = deps_.environment->robotBodyExtents(front, rear, side);
if (!have_body)
{
robot::log_error_throttle(5.0, "[move_base2] EnvMonitor: no body geometry (costmap footprint "
"unavailable, body/*_offset not set) — geometry not sampled.\n");
}
}
if (have_body)
{
const bool heavy_due =
!has_last_env_heavy_ || (now - last_env_heavy_).toSec() >= sampling.check_period;
if (heavy_due)
{
// Bám index đơn điệu: detour uốn quanh trụ có đoạn sau đi sát robot, nearest toàn plan nhảy sang đó
// và điểm thoát T đổi (cost_to_go +8 m / 1 s, run 5/9 22:35). Plan mới thì tìm lại toàn plan một lần.
if (!env_plan_index_valid_ || env_plan_index_ + 1 >= latest_plan_.size())
{
env_plan_index_ = nearestIndex(latest_plan_, robot_pose);
env_plan_index_valid_ = true;
}
else
{
env_plan_index_ = trackedNearestIndex(latest_plan_, robot_pose, env_plan_index_, sampling.track_back,
sampling.track_ahead);
}
EnvGeometryRequest req;
req.plan = &latest_plan_;
req.from_index = env_plan_index_;
req.robot_pose = robot_pose;
req.sampling = &sampling;
req.front = front;
req.rear = rear;
req.side = side;
EnvGeometry geometry;
if (deps_.environment->sampleGeometry(req, geometry))
{
env_geometry_ = geometry;
s.geometry_valid = true;
s.cost_conclusive = geometry.cost.conclusive;
s.reachable = geometry.cost.reachable;
s.cost_to_go = geometry.cost.cost_to_go;
s.edt_body_min = geometry.edt_body_min;
}
last_env_heavy_ = now;
has_last_env_heavy_ = true;
}
if (config_.env_monitor.contact.enabled)
{
EnvTrajectoryRequest treq;
treq.robot_pose = robot_pose;
treq.v = s.v_cmd;
treq.omega = s.w_cmd;
treq.sampling = &sampling;
treq.front = front;
treq.rear = rear;
treq.side = side;
if (sampling.use_local_plan != "false")
{
deps_.controller->getLocalPlan(env_local_plan_);
treq.local_plan = &env_local_plan_;
}
SweepResult sweep;
bool used_local = false;
if (deps_.environment->sweepTrajectory(treq, sweep, used_local) && sweep.conclusive)
{
s.contact_conclusive = true;
s.traj_contact_dist = sweep.blocked ? sweep.distance : std::numeric_limits<double>::infinity();
env_used_local_plan_ = used_local;
env_contact_dist_ = s.traj_contact_dist;
}
}
}
}
env_verdict_ = env_monitor_.update(s);
env_brake_ = env_verdict_.brake && config_.env_monitor.contact.apply_command;
if (env_verdict_.cost_jump && config_.debug_env)
{
robot::log_info_throttle(1.0, "[move_base2][debug] EnvMonitor: cost_to_go jumped to %.2f m in one tick — free mask "
"changed connectivity, stall window restarted.\n",
s.cost_to_go);
}
// Sườn sự kiện: một dòng, không throttle, không khoá — đây là chẩn đoán "robot kẹt/sắp chạm".
if (env_verdict_.event[0] != '\0')
{
robot::log_warning("[move_base2] EnvMonitor: %s (eff_geo=%.2f cmd=%.2f m, cost_to_go=%.2f m, "
"edt_body=%.2f m, contact=%.2f m, budget_left=%.2f m, mission %llu%s).\n",
env_verdict_.event, env_verdict_.eff_geo, env_verdict_.cmd_window,
env_geometry_.valid ? env_geometry_.cost.cost_to_go : -1.0, s.edt_body_min,
s.traj_contact_dist, env_verdict_.replan_budget_left,
static_cast<unsigned long long>(active_request_.mission_sequence_id),
(env_verdict_.no_progress || env_verdict_.path_blocked || env_verdict_.collision)
? "; FLAG RAISED"
: "; shadow");
}
// Tóm tắt feature 1 Hz — nhóm debug/env, tắt được.
if (config_.debug_env && monitorable && s.geometry_valid &&
(!has_last_env_debug_ || (now - last_env_debug_).toSec() >= 1.0))
{
last_env_debug_ = now;
has_last_env_debug_ = true;
robot::log_info("[move_base2][debug] EnvMonitor: cost_to_go=%.2f (geo %.2f + arc %.2f, %s%s) eff=%.2f "
"cmd=%.2f m edt_body=%.2f m clear_ahead=%.2f m corridor=%.2f m contact=%.2f m (%s) "
"v_cap=%.2f stall=%d%s unreach=%d%s brake=%d standdown=%d budget_left=%.1f m disp=%.2f m%s\n",
env_geometry_.cost.cost_to_go, env_geometry_.cost.geo_to_exit, env_geometry_.cost.arc_rest,
env_geometry_.cost.reachable ? "reachable" : "UNREACHABLE",
env_geometry_.cost.robot_in_ring ? ", in ring" : "", env_verdict_.eff_geo,
env_verdict_.cmd_window, env_geometry_.edt_body_min, env_geometry_.corridor.plan_clear_ahead,
env_geometry_.corridor.min_width, s.traj_contact_dist,
env_used_local_plan_ ? "local plan" : "arc", env_verdict_.v_cap,
env_verdict_.stall_detected ? 1 : 0, env_verdict_.stall_muted ? "(muted)" : "",
env_verdict_.unreachable_detected ? 1 : 0, env_verdict_.unreachable_muted ? "(muted)" : "",
env_verdict_.brake ? 1 : 0, env_verdict_.contact_standdown ? 1 : 0,
env_verdict_.replan_budget_left, env_verdict_.net_disp,
env_verdict_.wandering ? " WANDERING" : "");
}
if (env_logger_ && (s.geometry_valid || env_verdict_.event[0] != '\0'))
{
env_logger_->record(now, s, env_verdict_, s.geometry_valid ? &env_geometry_ : nullptr,
toString(state_machine_.state()), active_request_.mission_sequence_id,
env_used_local_plan_);
}
}
void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
{
candidate = robot_geometry_msgs::Twist();
@@ -1242,6 +1531,7 @@ bool ControlLoop::step()
// --- 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);
updateEnvMonitor(now, dt, robot_pose, pose_available, costmap_stale);
// --- 2. State machine -----------------------------------------------------------------------
StateMachineInput input;
@@ -1262,11 +1552,13 @@ bool ControlLoop::step()
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.
input.path_blocked = path_blocked_;
input.collision = collision_blocked_; // Phép đo 3 có trigger/route riêng (2026-09-04)
// 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";
input.no_progress = (no_progress_ && config_.path_monitor.progress_action == "recover") ||
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
@@ -1319,6 +1611,7 @@ bool ControlLoop::step()
++plan_revision_;
order_plan_.clear();
has_outcome_ = false;
env_monitor_.onGoalAccepted(now);
// Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop.
if (active_request_.has_goal)
@@ -1382,6 +1675,8 @@ bool ControlLoop::step()
// plan vừa tới (rõ nhất lúc preempt/đổi chặng). Đo lệch tuyến ngay lúc đó là khai hoả oan.
last_plan_applied_ = now;
has_last_plan_applied_ = true;
env_monitor_.onPlanApplied(now);
env_plan_index_valid_ = false;
if (config_.debug_plan)
{
@@ -1428,6 +1723,7 @@ 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)
{
@@ -1436,6 +1732,7 @@ bool ControlLoop::step()
// Behavior từ chối khởi động (ví dụ đã va chạm ngay tại chỗ) — báo hỏng để state machine
// chuyển sang behavior kế tiếp thay vì tick một behavior chưa start.
recovery_feedback_ = RecoveryFeedback::kFailed;
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
}
}
else if (output.tick_recovery)
@@ -1448,9 +1745,14 @@ bool ControlLoop::step()
break;
case RecoveryTick::Status::kSucceeded:
recovery_feedback_ = RecoveryFeedback::kSucceeded;
env_monitor_.onRecoveryFinished(now,
tick.has_path && !tick.path.empty() ? EnvRecoveryOutcome::kSucceededWithPath
: EnvRecoveryOutcome::kSucceeded,
output.recovery_trigger == RecoveryTrigger::kCollision);
break;
case RecoveryTick::Status::kFailed:
recovery_feedback_ = RecoveryFeedback::kFailed;
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
break;
}
if (tick.has_velocity)
@@ -1577,8 +1879,44 @@ bool ControlLoop::step()
runController(candidate);
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)
{
if (config_.env_monitor.contact.apply_command)
{
const double scale = env_verdict_.v_cap / std::fabs(candidate.linear.x);
candidate.linear.x *= scale;
candidate.angular.z *= scale;
}
else if (config_.debug_env)
{
robot::log_info_throttle(2.0, "[move_base2][debug] EnvMonitor: would cap v %.2f -> %.2f m/s "
"(contact %.2f m along the %s; shadow, not applied).\n",
candidate.linear.x, env_verdict_.v_cap, env_contact_dist_,
env_used_local_plan_ ? "local plan" : "commanded arc");
}
}
// EnvMonitor giữ phanh MÀ cờ collision đã giơ và state machine vẫn để CONTROLLING (route
// collision cạn/khoá): lệnh vừa bị huỷ thì với state machine nó KHÔNG hợp lệ — cùng luật (A)
// của guard cũ. Báo đúng sự thật thì controller_patience chạy -> route controlling_failed ->
// ABORT có log, thay vì robot đứng chết vô hạn với controller "ổn". Trước khi cờ giơ (1 s kề
// mũi) controller vẫn hợp lệ: patience 0,5 s không được chạy đua với chính cờ collision.
if (env_brake_ && env_verdict_.collision)
{
controller_feedback_ = ControllerFeedback::kNoValidCommand;
robot::log_warning_throttle(2.0,
"[move_base2] EnvMonitor: holding the brake (contact %.2f m along the %s, "
"controller wants v=%.2f) — reported as no valid command; if the collision "
"trigger is locked, controller_patience escalates.\n",
env_contact_dist_, env_used_local_plan_ ? "local plan" : "commanded arc",
candidate.linear.x);
}
}
if (controller_feedback_ == ControllerFeedback::kNoValidCommand)
{
@@ -1645,8 +1983,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_) ? VelocitySource::kNone
: output.velocity_source,
arbiter_.arbitrate((costmap_stale || collision_brake_ || 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".