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

@@ -166,6 +166,237 @@ bool CostmapPathCheck::robotBodyExtents(double& front, double& rear, double& sid
return true;
}
// ================================================================================================
// CostmapEnvironment
// ================================================================================================
namespace
{
double yawOfPose(const robot_geometry_msgs::PoseStamped& pose)
{
const auto& q = pose.pose.orientation;
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
}
} // namespace
robot_costmap_2d::Costmap2D* CostmapEnvironment::gridForRead(bool& live) const
{
live = true;
if (costmap_ == nullptr)
{
return nullptr;
}
robot_costmap_2d::Costmap2D* grid = costmap_->getCostmapForRead();
live = (grid == costmap_->getCostmap()); // snapshot tắt -> trả lưới sống -> phải khoá
return grid;
}
void CostmapEnvironment::refresh()
{
if (costmap_ != nullptr)
{
costmap_->refreshSnapshot(); // no-op khi snapshot tắt
}
}
bool CostmapEnvironment::sampleGeometry(const EnvGeometryRequest& r, EnvGeometry& out)
{
out = EnvGeometry();
if (costmap_ == nullptr || !tf_ || r.plan == nullptr || r.sampling == nullptr || r.plan->size() < 2 ||
r.from_index >= r.plan->size())
{
return false;
}
bool live = true;
robot_costmap_2d::Costmap2D* grid = gridForRead(live);
if (grid == nullptr)
{
return false;
}
const std::string& grid_frame = costmap_->getGlobalFrameID();
PlanarTransform plan_to_grid;
PlanarTransform pose_to_grid;
if (!planarTransform(*tf_, (*r.plan)[r.from_index].header.frame_id, grid_frame, plan_to_grid) ||
!planarTransform(*tf_, r.robot_pose.header.frame_id, grid_frame, pose_to_grid))
{
return false; // không quy đổi được frame: không biết, không đoán
}
double gx = 0.0;
double gy = 0.0;
pose_to_grid.apply(r.robot_pose.pose.position.x, r.robot_pose.pose.position.y, gx, gy);
const double gyaw = yawOfPose(r.robot_pose) + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw);
// Bán kính tâm = inscribed của thân, KHÔNG đệm: cùng biên với SBPL (luật R2).
const double free_radius = std::min(r.side, std::min(r.front, r.rear));
out.free_radius = free_radius;
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()), boost::defer_lock);
if (live)
{
lock.lock();
}
if (!analyzeGrid(*grid, static_cast<unsigned char>(r.sampling->lethal_threshold), free_radius, scratch_))
{
return false;
}
out.edt_body_min = bodyClearance(scratch_, gx, gy, gyaw, r.front, r.rear, r.side);
CostToGoParams cost_params;
cost_params.target_backoff = r.sampling->target_backoff;
cost_params.robot_snap = r.sampling->robot_snap;
cost_params.exit_ahead = r.sampling->exit_ahead;
out.cost = costToGo(*r.plan, r.from_index, gx, gy, cost_params, plan_to_grid, scratch_);
CorridorParams corridor_params;
corridor_params.horizon = r.sampling->horizon;
corridor_params.body_width = 2.0 * r.side;
corridor_params.margin = r.sampling->corridor_margin;
corridor_params.side_cap = r.sampling->corridor_cap;
out.corridor = scanCorridor(*r.plan, r.from_index, corridor_params, plan_to_grid, scratch_);
out.valid = true;
return true;
}
bool CostmapEnvironment::sweepTrajectory(const EnvTrajectoryRequest& r, SweepResult& out,
bool& used_local_plan)
{
out = SweepResult();
used_local_plan = false;
if (costmap_ == nullptr || !tf_ || r.sampling == nullptr)
{
return false;
}
bool live = true;
robot_costmap_2d::Costmap2D* grid = gridForRead(live);
if (grid == nullptr)
{
return false;
}
const std::string& grid_frame = costmap_->getGlobalFrameID();
PlanarTransform pose_to_grid;
if (!planarTransform(*tf_, r.robot_pose.header.frame_id, grid_frame, pose_to_grid))
{
return false;
}
double gx = 0.0;
double gy = 0.0;
pose_to_grid.apply(r.robot_pose.pose.position.x, r.robot_pose.pose.position.y, gx, gy);
const double gyaw = yawOfPose(r.robot_pose) + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw);
SweepParams params;
params.front = r.front;
params.rear = r.rear;
params.side = r.side;
params.padding = r.sampling->padding;
params.lookahead = r.sampling->contact_lookahead;
params.lethal_threshold = static_cast<unsigned char>(r.sampling->lethal_threshold);
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()), boost::defer_lock);
if (live)
{
lock.lock();
}
// 1) Quỹ đạo thật của local planner, quy về frame lưới.
if (r.sampling->use_local_plan != "false" && r.local_plan != nullptr && r.local_plan->poses.size() >= 2)
{
PlanarTransform traj_to_grid;
if (planarTransform(*tf_, r.local_plan->header.frame_id, grid_frame, traj_to_grid))
{
const double dyaw = std::atan2(traj_to_grid.sin_yaw, traj_to_grid.cos_yaw);
traj_scratch_.clear();
traj_scratch_.reserve(r.local_plan->poses.size());
for (const auto& p : r.local_plan->poses)
{
robot_geometry_msgs::PoseStamped ps;
traj_to_grid.apply(p.pose.x, p.pose.y, ps.pose.position.x, ps.pose.position.y);
const double yaw = p.pose.theta + dyaw;
ps.pose.orientation.z = std::sin(0.5 * yaw);
ps.pose.orientation.w = std::cos(0.5 * yaw);
traj_scratch_.push_back(ps);
}
out = move_base2::sweepTrajectory(traj_scratch_, gx, gy, gyaw, r.sampling->local_plan_start_tol,
params, *grid, scratch_);
if (out.conclusive)
{
used_local_plan = true;
return true;
}
}
}
if (r.sampling->use_local_plan == "true")
{
return false; // ép dùng quỹ đạo mà không có -> không kết luận
}
// 2) Cung (v, omega) không đổi — cùng hình học với guard cũ, nhưng cùng bộ dò với quỹ đạo thật.
if (std::fabs(r.v) < 1e-3)
{
out.conclusive = true; // đứng yên / xoay tại chỗ: không có chuyển động tịnh tiến để dò
return true;
}
const double res = grid->getResolution();
const double step = res > 0.0 ? res : 0.05;
const double direction = r.v < 0.0 ? -1.0 : 1.0;
const double kappa = r.omega / r.v;
traj_scratch_.clear();
const int n = static_cast<int>(std::ceil(r.sampling->contact_lookahead / step));
traj_scratch_.reserve(static_cast<std::size_t>(n) + 1);
for (int i = 0; i <= n; ++i)
{
const double s = direction * step * i;
robot_geometry_msgs::PoseStamped ps;
double yaw = gyaw;
if (std::fabs(kappa) < 1e-6)
{
ps.pose.position.x = gx + s * std::cos(gyaw);
ps.pose.position.y = gy + s * std::sin(gyaw);
}
else
{
yaw = gyaw + kappa * s;
ps.pose.position.x = gx + (std::sin(yaw) - std::sin(gyaw)) / kappa;
ps.pose.position.y = gy - (std::cos(yaw) - std::cos(gyaw)) / kappa;
}
ps.pose.orientation.z = std::sin(0.5 * yaw);
ps.pose.orientation.w = std::cos(0.5 * yaw);
traj_scratch_.push_back(ps);
}
out = move_base2::sweepTrajectory(traj_scratch_, gx, gy, gyaw, 1.0, params, *grid, scratch_);
return out.conclusive;
}
bool CostmapEnvironment::robotBodyExtents(double& front, double& rear, double& side) const
{
if (costmap_ == nullptr)
{
return false;
}
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;
}
front = max_x;
rear = -min_x;
side = max_abs_y;
return true;
}
NavigationRuntime::NavigationRuntime() = default;
NavigationRuntime::~NavigationRuntime()
@@ -252,6 +483,10 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf
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.
environment_.setCostmap(local_costmap_.get());
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
// costmap có nội dung. Exporter tự trả về "chưa có gì" thay vì lưới rỗng.
global_exporter_.attach(global_costmap_.get(), config_.global_frame);
@@ -501,6 +736,7 @@ ControlLoopDeps NavigationRuntime::deps()
deps.action = &action_;
deps.costmap_status = &costmap_status_;
deps.path_check = &path_check_;
deps.environment = &environment_;
return deps;
}