feat: env_monitor_core package with detector plugins

EnvMonitor moves out of move_base2 into its own package. stall, unreachable and
contact become boost::dll detector plugins loaded from env_monitor/detectors,
each with its own recovery route (route, route_mode step|sequence,
on_exhausted lock|abort). Golden test replays the pre-split verdicts bit for bit.
This commit is contained in:
2026-11-27 10:08:30 +07:00
commit 93d3996629
22 changed files with 11423 additions and 0 deletions

View File

@@ -0,0 +1,285 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* env_monitor_core — kContact (xem contact_detector.h).
*
* Author: DuongTD
*********************************************************************/
#include "contact_detector.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <memory>
#include <env_monitor_core/env_detector_abi.h>
namespace env_monitor_core
{
EnvDetector::Ptr ContactDetector::create()
{
return std::make_shared<ContactDetector>();
}
bool ContactDetector::initialize(const std::string& name, robot::NodeHandle& nh, std::string& error)
{
(void)name;
readContact(nh, config_);
return validateContact(config_, error);
}
std::string ContactDetector::describe() const
{
return describeContact(config_);
}
EnvRouteSpec ContactDetector::defaultRoute() const
{
// Bản một khối: kContact đi route `collision`, cạn route là KHOÁ (dự báo; phanh vẫn giữ).
EnvRouteSpec spec;
spec.route = "collision";
spec.lock_on_exhausted = true;
return spec;
}
bool ContactDetector::armed() const
{
return config_.action == "recover" || config_.apply_command;
}
bool ContactDetector::appliesCommand() const
{
return config_.apply_command;
}
EnvNeeds ContactDetector::needs() const
{
EnvNeeds n;
n.sweep = config_.enabled;
return n;
}
void ContactDetector::reset()
{
contact_streak_ = 0;
release_streak_ = 0;
braking_ = false;
contact_close_ = false;
contact_fired_ = false;
detour_from_contact_ = false;
detour_mark_travel_ = 0.0;
standdown_ = false;
standdown_mark_travel_ = 0.0;
standdown_clean_streak_ = 0;
}
void ContactDetector::onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route)
{
if (outcome == EnvRecoveryOutcome::kSucceededWithPath)
{
// Detour do chính cờ collision: nếu robot không rời chỗ mà lại "sắp chạm" thì lần sau đứng ra.
detour_from_contact_ = own_route;
detour_mark_travel_ = shared.travel_total;
}
// Mọi kết cục đều kết thúc một pha dừng: chuỗi xác nhận cũ không còn giá trị.
contact_streak_ = 0;
release_streak_ = 0;
braking_ = false;
contact_close_ = false;
contact_fired_ = false;
}
void ContactDetector::update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v)
{
const EnvSample& s = frame.sample;
const EnvShared& sh = frame.shared;
const EnvMonitorConfig::Contact& c = config_;
if (!c.enabled)
{
return;
}
double v_ref = std::fabs(s.v_cmd);
if (std::isfinite(s.v_meas))
{
v_ref = std::max(v_ref, std::fabs(s.v_meas));
}
v.brake_dist = v_ref * v_ref / (2.0 * c.brake_decel);
if (!s.contact_conclusive || !s.costmap_current)
{
// Không biết thì không dừng, cũng không xoá chuỗi (cùng hợp đồng với guard cũ).
out.brake = braking_; // đang phanh thì giữ phanh tới khi có bằng chứng ngược lại
return;
}
if (standdown_)
{
// Đang đứng ra: không phanh, không cờ, không bao. Chỉ theo dõi điều kiện vũ trang lại.
v.contact_standdown = true;
if (std::isfinite(s.traj_contact_dist))
{
standdown_clean_streak_ = 0;
}
else
{
++standdown_clean_streak_;
}
const bool travelled = sh.travel_total - standdown_mark_travel_ >= c.standdown_travel;
if (travelled || standdown_clean_streak_ >= c.release_confirm_cycles)
{
standdown_ = false;
standdown_clean_streak_ = 0;
v.contact_standdown = false;
out.event = travelled ? "contact: re-armed after moving on" : "contact: re-armed, the trajectory is clear";
}
return;
}
if (!std::isfinite(s.traj_contact_dist))
{
contact_streak_ = 0;
if (braking_ && ++release_streak_ < c.release_confirm_cycles)
{
// Một mẫu sạch chưa là sạch: local planner đổi quỹ đạo mỗi cycle, sạch 1 cycle rồi chạm lại là
// chuyện thường (run 5/9 22:35: 4 lần nhả/phanh trong 3 s). Giữ phanh và cờ tới khi sạch liên tiếp.
out.brake = true;
v.collision = contact_fired_ && c.action == "recover";
out.fired = v.collision;
return;
}
if (braking_ || contact_fired_)
{
out.event = "contact cleared: the trajectory is free again";
}
braking_ = false;
release_streak_ = 0;
contact_close_ = false;
contact_fired_ = false;
return;
}
// Bao tốc độ: |v| <= sqrt(2 a (d - margin)) để luôn còn dừng được trên đất sạch.
// Bao giữ thêm envelope_margin so với ngưỡng phanh: lệnh nằm trên bao thì quãng phanh còn dư đúng chừng
// đó, nhiễu quỹ đạo vài cm không đẩy sang "sắp chạm". Trong margin thì 0; giữa margin và margin+dư thì bò
// min_speed.
if (c.envelope)
{
if (s.traj_contact_dist <= c.clean_start_margin)
{
out.v_cap = 0.0;
}
else
{
const double room = s.traj_contact_dist - c.clean_start_margin - c.envelope_margin;
out.v_cap = std::max(c.min_speed, room > 0.0 ? std::sqrt(2.0 * c.brake_decel * room) : 0.0);
}
}
// Xoay tại chỗ / bò mà monitor chưa phanh: quỹ đạo local planner lúc này là một cú xoay, góc thân
// quét vào ô kề bên là chuyện của controller (nó tự kiểm footprint), không phải bài toán quãng phanh.
// Phanh ở đây là chặn robot xoay ra khỏi vật đang kề mũi, rồi 1 s sau giơ cờ và gọi detour từ đúng
// chỗ đứng — vòng churn đầu chặng của guard cũ (mission 5/6 shadow 5/9). Đã phanh rồi thì vẫn xét
// tiếp để "kề mũi đứng yên" còn nổ được.
double v_intent = v_ref;
if (std::isfinite(s.v_controller))
{
v_intent = std::max(v_intent, std::fabs(s.v_controller));
}
if (v_intent < c.min_check_speed && !braking_)
{
contact_streak_ = 0;
release_streak_ = 0;
contact_close_ = false;
contact_fired_ = false;
return;
}
// Hai câu hỏi khác nhau:
// - "sắp chạm" = còn dừng kịp không (theo quãng phanh) -> PHANH. Đứng lại rồi thì quãng phanh về 0
// và câu này tự hết đúng, robot được bò tiếp dưới bao tốc độ.
// - "đang kề vật" = tiếp xúc trong đúng clean_start_margin bất kể tốc độ -> nếu còn đó đủ
// trigger_static_time thì vật đứng yên trước mũi, không phải người đi qua -> giơ CỜ.
// Bao tốc độ đặt lệnh đúng lên biên v_cap = sqrt(2a(d - margin)), tức d - quãng phanh == margin: nếu
// "sắp chạm" là <= thì mỗi lần bao kẹp xong là phanh, nhả, kẹp, phanh (chattering 4 cycle). Chỉ phanh
// khi vượt bao quá 1 mm — lệnh nằm trên bao là đang giảm tốc đúng luật, không phải sắp chạm.
// Trong margin thì bao đã là 0: đó là một cú dừng của monitor dù quãng phanh bằng 0 — phải được gọi
// là phanh để có sự kiện, để giữ 0 tức thì qua trọng tài và để cổng xoay không nuốt nó.
constexpr double kEnvelopeTol = 1e-3; // [m]
// Đã kề thì còn kề tới margin + release_hysteresis: quỹ đạo nhảy 0,08 <-> 0,25 m quanh margin không
// được reset đồng hồ giơ cờ, cũng không được nhả phanh.
const double close_limit = c.clean_start_margin + (contact_close_ ? c.release_hysteresis : 0.0);
const bool close = s.traj_contact_dist <= close_limit;
const bool imminent = close || s.traj_contact_dist - v.brake_dist < c.clean_start_margin - kEnvelopeTol;
v.contact_imminent = imminent;
if (imminent)
{
release_streak_ = 0;
++contact_streak_;
if (!braking_ && contact_streak_ >= c.confirm_cycles)
{
if (c.standdown_min_travel > 0.0 && detour_from_contact_ &&
sh.travel_total - detour_mark_travel_ < c.standdown_min_travel)
{
// Vừa detour từ đúng chỗ này vì chính cú chạm này, robot chưa rời chỗ: phanh + cờ lần nữa chỉ lặp
// lại churn (3 detour rồi ABORT). Nhường controller — nó là lưới an toàn duy nhất tới khi robot đi
// được standdown_travel hoặc quỹ đạo sạch.
standdown_ = true;
standdown_mark_travel_ = sh.travel_total;
standdown_clean_streak_ = 0;
detour_from_contact_ = false;
contact_streak_ = 0;
release_streak_ = 0;
contact_close_ = false;
contact_fired_ = false;
v.contact_standdown = true;
v.contact_imminent = false;
out.v_cap = std::numeric_limits<double>::infinity();
out.event = "contact: standing down — the detour from this spot did not move the robot, the controller "
"is the only safety net until it travels on";
return;
}
braking_ = true;
out.event = "contact: braking to zero";
}
}
else
{
contact_streak_ = 0;
if (braking_ && ++release_streak_ >= c.release_confirm_cycles)
{
braking_ = false;
release_streak_ = 0;
out.event = "contact receded: releasing the brake";
}
}
out.brake = braking_;
if (close)
{
if (!contact_close_)
{
contact_close_ = true;
close_since_ = s.now;
}
if (!contact_fired_ && (s.now - close_since_).toSec() >= c.trigger_static_time)
{
contact_fired_ = true;
out.event = "contact persists while stopped: asking for a replan";
}
}
else
{
if (contact_fired_)
{
out.event = "contact cleared: the obstacle moved away";
}
contact_close_ = false;
contact_fired_ = false;
}
v.collision = contact_fired_ && c.action == "recover";
out.fired = v.collision;
}
} // namespace env_monitor_core
ENV_MONITOR_CORE_EXPORT_DETECTOR(env_monitor_core::ContactDetector::create, ContactDetector)

View File

@@ -0,0 +1,57 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* env_monitor_core — kContact: thân sắp chạm trên quỹ đạo thật. Phanh + bao tốc độ; cờ `collision`.
*
* Author: DuongTD
*********************************************************************/
#ifndef ENV_MONITOR_CORE_CONTACT_DETECTOR_H_
#define ENV_MONITOR_CORE_CONTACT_DETECTOR_H_
#include <string>
#include <robot/node_handle.h>
#include <robot/time.h>
#include <env_monitor_core/env_detector.h>
#include <env_monitor_core/env_monitor_config.h>
namespace env_monitor_core
{
class ContactDetector final : public EnvDetector
{
public:
/// Factory exported to boost::dll (symbol `ContactDetector`).
static EnvDetector::Ptr create();
bool initialize(const std::string& name, robot::NodeHandle& nh, std::string& error) override;
std::string describe() const override;
bool armed() const override;
EnvRouteSpec defaultRoute() const override;
bool appliesCommand() const override;
EnvNeeds needs() const override;
void reset() override;
void onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route) override;
void update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v) override;
private:
EnvMonitorConfig::Contact config_;
int contact_streak_ = 0;
int release_streak_ = 0; ///< cycle liên tiếp không "sắp chạm" trong khi đang phanh.
bool braking_ = false;
bool contact_close_ = false; ///< tiếp xúc trong clean_start_margin (bất kể tốc độ).
robot::Time close_since_;
bool contact_fired_ = false;
bool detour_from_contact_ = false; ///< detour gần nhất là do cờ collision; mốc quãng đường ở dưới.
double detour_mark_travel_ = 0.0; ///< [m]
bool standdown_ = false; ///< đang đứng ra (xem Contact::standdown_min_travel).
double standdown_mark_travel_ = 0.0; ///< [m]
int standdown_clean_streak_ = 0; ///< cycle quỹ đạo sạch liên tiếp trong khi đứng ra.
};
} // namespace env_monitor_core
#endif // ENV_MONITOR_CORE_CONTACT_DETECTOR_H_

410
plugins/stall_detector.cpp Normal file
View File

@@ -0,0 +1,410 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* env_monitor_core — kStall (xem stall_detector.h).
*
* Author: DuongTD
*********************************************************************/
#include "stall_detector.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <env_monitor_core/env_detector_abi.h>
namespace env_monitor_core
{
EnvDetector::Ptr StallDetector::create()
{
return std::make_shared<StallDetector>();
}
bool StallDetector::initialize(const std::string& name, robot::NodeHandle& nh, std::string& error)
{
(void)name;
readStall(nh, config_);
return validateStall(config_, error);
}
std::string StallDetector::describe() const
{
return describeStall(config_);
}
EnvRouteSpec StallDetector::defaultRoute() const
{
// Bản một khối: kStall đi route `oscillation`, cạn route là ABORT chặng (trigger gốc).
EnvRouteSpec spec;
spec.route = "oscillation";
spec.lock_on_exhausted = false;
return spec;
}
bool StallDetector::armed() const
{
return config_.action == "recover";
}
EnvNeeds StallDetector::needs() const
{
EnvNeeds n;
n.geometry = config_.enabled;
// Cửa sổ vị trí dài nhất: cú nhảy pose xoá cửa sổ tối đa một lần mỗi chừng này (kể cả khi stall tắt, như bản cũ).
n.position_window_s = std::max({ config_.idle_window_s, config_.confine_window_s, config_.disp_window_s });
return n;
}
void StallDetector::reset()
{
clearWindow();
stall_seen_ = false;
stall_fired_ = false;
slip_seen_ = false;
has_stall_backoff_ = false;
has_prev_heavy_ = false;
clearPosWindow();
}
void StallDetector::onPlanApplied(const EnvShared& shared)
{
(void)shared;
clearWindow();
clearPosWindow(); // cửa sổ dịch chuyển bắt đầu lại: plan mới là một lượt thử mới
has_prev_heavy_ = false;
stall_seen_ = false;
stall_fired_ = false;
}
void StallDetector::onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route)
{
(void)own_route;
if (outcome == EnvRecoveryOutcome::kFailed)
{
has_stall_backoff_ = true;
stall_backoff_until_ = shared.now + robot::Duration(config_.retry_backoff);
}
// Mọi kết cục đều kết thúc một pha dừng: chuỗi xác nhận cũ không còn giá trị.
stall_seen_ = false;
stall_fired_ = false;
}
void StallDetector::clearWindow()
{
ring_head_ = 0;
ring_count_ = 0;
}
void StallDetector::clearPosWindow()
{
pos_head_ = 0;
pos_count_ = 0;
wandering_ = false;
idle_ = false;
confined_ = false;
region_radius_ = std::numeric_limits<double>::quiet_NaN();
net_disp_ = std::numeric_limits<double>::quiet_NaN();
has_eff_ok_ = false;
has_eff_low_ = false;
}
bool StallDetector::progressProven(const robot::Time& now) const
{
const EnvMonitorConfig::Stall& c = config_;
if (!has_eff_ok_ || (now - eff_ok_t_).toSec() > c.window_s)
{
return false; // không có bằng chứng tiến độ còn mới: cổng được nổ như cũ
}
return !has_eff_low_ || (now - eff_low_t_).toSec() > c.confine_window_s;
}
bool StallDetector::oldestPos(const robot::Time& now, double window_s, PosSample& out) const
{
// Mẫu MỚI NHẤT đã đủ tuổi window_s — cùng lý do với oldestInWindow.
for (std::size_t k = 1; k <= pos_count_; ++k)
{
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
if ((now - p.t).toSec() >= window_s)
{
out = p;
return true;
}
}
return false;
}
bool StallDetector::oldestInWindow(const robot::Time& now, double cmd_accum, HeavySample& out) const
{
// Mẫu MỚI NHẤT đã đủ tuổi window_s hoặc đủ xa window_m lệnh — cửa sổ sát ngưỡng nhất, không phải
// mẫu cũ nhất trong ring (cửa sổ giãn ra làm eff mượt giả).
for (std::size_t k = 1; k <= ring_count_; ++k)
{
const HeavySample& s = ring_[(ring_head_ + kRing - k) % kRing];
const bool old_enough = (now - s.t).toSec() >= config_.window_s;
const bool far_enough = cmd_accum - s.cmd >= config_.window_m;
if (old_enough || far_enough)
{
out = s;
return true;
}
}
return false;
}
void StallDetector::update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v)
{
const EnvSample& s = frame.sample;
const EnvShared& sh = frame.shared;
if (sh.pose_jump_restart)
{
// Host vừa nhận ra pose bị đặt lại (xem EnvMonitor::update): mẫu vị trí và cost_to_go hai bên cú dời
// không cùng hệ quy chiếu — đo lại từ đầu, kết luận kẹt cũ không còn cơ sở.
clearWindow();
clearPosWindow();
has_prev_heavy_ = false;
stall_seen_ = false;
stall_fired_ = false;
}
if (!sh.measurable)
{
// Không có gì để đo tiến độ; xoá chuỗi để không nối "đúng liên tục" qua quãng gián đoạn.
stall_seen_ = false;
stall_fired_ = false;
return;
}
const EnvMonitorConfig::Stall& c = config_;
if (!c.enabled)
{
return;
}
// Cửa sổ dịch chuyển thực: lấy mẫu vị trí mỗi tick nặng, không phụ thuộc cost/plan/mặt nạ.
if (s.geometry_valid && std::isfinite(s.robot_x) && std::isfinite(s.robot_y))
{
pos_ring_[pos_head_] = PosSample{ s.now, s.robot_x, s.robot_y, sh.cmd_accum };
pos_head_ = (pos_head_ + 1) % kPosRing;
pos_count_ = std::min(pos_count_ + 1, kPosRing);
PosSample old;
if (oldestPos(s.now, c.disp_window_s, old))
{
net_disp_ = std::hypot(s.robot_x - old.x, s.robot_y - old.y);
wandering_ = (sh.cmd_accum - old.cmd >= c.disp_min_commanded) && net_disp_ < c.disp_min;
}
else
{
net_disp_ = std::numeric_limits<double>::quiet_NaN();
wandering_ = false;
}
// Cổng đứng yên: không cần lệnh đủ — PRIEST bò 0,05 m/s tại chỗ 30 s cũng là kẹt.
idle_ = false;
PosSample older;
if (c.idle_window_s > 0.0 && c.disp_min > 0.0 && oldestPos(s.now, c.idle_window_s, older))
{
idle_ = std::hypot(s.robot_x - older.x, s.robot_y - older.y) < c.disp_min;
}
// Cổng giam vùng: bán kính của tập vị trí trong confine_window_s quanh tâm của chúng, so với lệnh tích luỹ.
confined_ = false;
region_radius_ = std::numeric_limits<double>::quiet_NaN();
if (c.confine_radius > 0.0 && c.disp_min > 0.0)
{
double sx = 0.0;
double sy = 0.0;
std::size_t n = 0;
double oldest_cmd = sh.cmd_accum;
double oldest_age = 0.0;
for (std::size_t k = 1; k <= pos_count_; ++k)
{
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
const double age = (s.now - p.t).toSec();
if (age > c.confine_window_s)
{
break;
}
sx += p.x;
sy += p.y;
++n;
oldest_cmd = p.cmd;
oldest_age = age;
}
if (n >= 2 && oldest_age >= c.confine_window_s - 0.5)
{
const double cx = sx / static_cast<double>(n);
const double cy = sy / static_cast<double>(n);
double radius = 0.0;
for (std::size_t k = 1; k <= n; ++k)
{
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
radius = std::max(radius, std::hypot(p.x - cx, p.y - cy));
}
region_radius_ = radius;
const double cmd = sh.cmd_accum - oldest_cmd;
confined_ = radius < c.confine_radius &&
cmd >= c.confine_cmd_factor * std::max(2.0 * radius, c.disp_min);
}
}
}
v.net_disp = net_disp_;
v.wandering = wandering_;
v.idle = idle_;
v.confined = confined_;
v.region_radius = region_radius_;
// Mẫu nặng mới: ghi vào ring nếu có cost hữu hạn. +inf (mất liên thông tạm) không ghi — không kết
// luận từ mẫu thiếu.
if (s.geometry_valid && s.cost_conclusive && s.reachable && std::isfinite(s.cost_to_go))
{
// Lật liên thông: cost đổi nhiều hơn chuyển động và độ dời pose bị loại từ mẫu nặng trước. Cú nhảy pose lặp
// không xoá cửa sổ, nên cost đi theo nó cũng không phải một cú nhảy do mặt nạ free; giữ lại để đo eff.
if (c.jump_reject > 0.0 && has_prev_heavy_ &&
std::fabs(s.cost_to_go - prev_heavy_cost_) > c.jump_reject + (sh.travel_total - prev_heavy_travel_) +
(sh.jump_dist_total - prev_heavy_jump_dist_))
{
clearWindow();
stall_seen_ = false;
stall_fired_ = false;
has_eff_low_ = true;
eff_low_t_ = s.now;
v.cost_jump = true;
}
has_prev_heavy_ = true;
prev_heavy_cost_ = s.cost_to_go;
prev_heavy_travel_ = sh.travel_total;
prev_heavy_jump_dist_ = sh.jump_dist_total;
ring_[ring_head_] = HeavySample{ s.now, s.cost_to_go, sh.cmd_accum };
ring_head_ = (ring_head_ + 1) % kRing;
ring_count_ = std::min(ring_count_ + 1, kRing);
HeavySample old;
if (oldestInWindow(s.now, sh.cmd_accum, old))
{
const double cmd = sh.cmd_accum - old.cmd;
v.cmd_window = cmd;
if (cmd >= c.min_commanded)
{
v.eff_geo = (old.cost - s.cost_to_go) / cmd;
}
}
// Lịch sử cho progressProven(): chỉ eff đo được mới là bằng chứng, theo cả hai chiều.
if (!std::isnan(v.eff_geo))
{
if (v.eff_geo >= c.eff_off)
{
has_eff_ok_ = true;
eff_ok_t_ = s.now;
}
else
{
has_eff_low_ = true;
eff_low_t_ = s.now;
}
}
}
const bool progress_proven = progressProven(s.now);
v.progress_proven = progress_proven;
v.confined_vetoed = confined_ && c.progress_veto && progress_proven;
// Trượt: lệnh đi mà bánh không quay (vật thấp, bumper). Chỉ khi có v_meas.
bool slipping = false;
if (c.slip_on > 0.0 && std::isfinite(s.v_meas))
{
const bool slip_now = std::fabs(s.v_cmd) - std::fabs(s.v_meas) >= c.slip_on;
if (slip_now)
{
if (!slip_seen_)
{
slip_seen_ = true;
slip_since_ = s.now;
}
slipping = (s.now - slip_since_).toSec() >= c.slip_time;
}
else
{
slip_seen_ = false;
}
}
const bool grace = sh.in_grace;
const bool near_goal = std::isfinite(s.d_goal) && s.d_goal < c.goal_zone;
if (grace || near_goal)
{
stall_seen_ = false;
stall_fired_ = false;
return;
}
const bool eff_known = !std::isnan(v.eff_geo);
const bool stalled = (eff_known && v.eff_geo < c.eff_on) || slipping;
const bool cleared = eff_known && v.eff_geo >= c.eff_off && !slipping;
if (stalled)
{
if (!stall_seen_)
{
stall_seen_ = true;
stall_since_ = s.now;
}
if (!stall_fired_ && (s.now - stall_since_).toSec() >= c.confirm)
{
stall_fired_ = true;
out.event = slipping ? "stall: wheels slip against the command" : "stall: cost_to_go not decreasing";
}
}
else if (cleared)
{
if (stall_fired_)
{
out.event = "stall cleared: progress resumed";
}
stall_seen_ = false;
stall_fired_ = false;
}
// Còn lại (không đo được, hoặc eff trong vùng chết): giữ trạng thái — không kết luận ≠ hết kẹt.
// Đứng yên suốt idle_window_s, hoặc đi nhiều mà bị giam trong vùng nhỏ suốt confine_window_s, là kẹt kể cả
// khi geodesic không đo được hoặc đang lật dấu. Chỉ cổng giam vùng bị phủ quyết khi có bằng chứng tiến độ;
// cổng đứng yên vẫn hoạt động vì cost_to_go có thể đổi do hình học costmap.
if ((idle_ || (confined_ && !(c.progress_veto && progress_proven))) && !stall_fired_)
{
stall_fired_ = true;
stall_seen_ = true;
stall_since_ = s.now;
out.event = idle_ ? "stall: no net displacement for the idle window"
: "stall: confined to a small region while commanded";
}
v.stall_detected = stall_fired_;
if (!stall_fired_)
{
return;
}
// Cổng đầu chặng, ngân sách replan, backoff sau lượt hỏng.
bool muted = false;
if (sh.has_goal && sh.cmd_accum - sh.cmd_at_goal < c.min_commanded_since_goal)
{
muted = true;
}
if (c.disp_min > 0.0)
{
// Cổng dịch chuyển thực thay ngân sách replan: cửa sổ vị trí đã bắt đầu lại ở plan mới, nên "sau detour
// vẫn quần tại chỗ disp_window_s" mới được nổ lại; né tự do (dịch chuyển >= disp_min) không bao giờ nổ.
if (!wandering_ && !idle_ && !confined_)
{
muted = true;
}
}
else if (sh.replan_muted)
{
muted = true;
}
if (has_stall_backoff_ && s.now < stall_backoff_until_)
{
muted = true;
}
v.stall_muted = muted;
v.no_progress = !muted && c.action == "recover";
out.fired = v.no_progress;
}
} // namespace env_monitor_core
ENV_MONITOR_CORE_EXPORT_DETECTOR(env_monitor_core::StallDetector::create, StallDetector)

107
plugins/stall_detector.h Normal file
View File

@@ -0,0 +1,107 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* env_monitor_core — kStall: "planner đòi đi mà robot không tiến". Cờ `no_progress`.
*
* Author: DuongTD
*********************************************************************/
#ifndef ENV_MONITOR_CORE_STALL_DETECTOR_H_
#define ENV_MONITOR_CORE_STALL_DETECTOR_H_
#include <array>
#include <cstddef>
#include <limits>
#include <string>
#include <robot/node_handle.h>
#include <robot/time.h>
#include <env_monitor_core/env_detector.h>
#include <env_monitor_core/env_monitor_config.h>
namespace env_monitor_core
{
class StallDetector final : public EnvDetector
{
public:
/// Factory exported to boost::dll (symbol `StallDetector`).
static EnvDetector::Ptr create();
bool initialize(const std::string& name, robot::NodeHandle& nh, std::string& error) override;
std::string describe() const override;
bool armed() const override;
EnvRouteSpec defaultRoute() const override;
EnvNeeds needs() const override;
void reset() override;
void onPlanApplied(const EnvShared& shared) override;
void onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route) override;
void update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v) override;
private:
struct HeavySample
{
robot::Time t;
double cost = 0.0; ///< [m]
double cmd = 0.0; ///< [m] cmd_accum_ lúc lấy mẫu.
};
/// 64 mẫu x 0,2 s = 12,8 s lịch sử, dư cho window_s 4 s kể cả khi nhịp nặng chậm lại.
static constexpr std::size_t kRing = 64;
struct PosSample
{
robot::Time t;
double x = 0.0;
double y = 0.0;
double cmd = 0.0; ///< [m] cmd_accum_ lúc lấy mẫu.
};
/// 128 mẫu x 0,2 s = 25,6 s, dư cho disp_window_s 12 s.
static constexpr std::size_t kPosRing = 192; ///< 192 x 0,2 s = 38 s, đủ idle_window_s 25 s.
bool oldestPos(const robot::Time& now, double window_s, PosSample& out) const;
void clearWindow();
void clearPosWindow();
bool oldestInWindow(const robot::Time& now, double cmd_accum, HeavySample& out) const;
/// Tiến độ đã chứng minh: có eff >= eff_off trong window_s gần nhất và không có eff < eff_off nào trong
/// confine_window_s gần nhất (xem Stall::confine_window_s).
bool progressProven(const robot::Time& now) const;
EnvMonitorConfig::Stall config_;
// Cửa sổ mẫu nặng
std::array<HeavySample, kRing> ring_{};
std::size_t ring_head_ = 0;
std::size_t ring_count_ = 0;
std::array<PosSample, kPosRing> pos_ring_{};
std::size_t pos_head_ = 0;
std::size_t pos_count_ = 0;
bool wandering_ = false;
bool idle_ = false; ///< cổng đứng yên đang mở (xem Stall::idle_window_s).
bool confined_ = false; ///< cổng giam vùng đang mở (xem Stall::confine_radius).
double region_radius_ = std::numeric_limits<double>::quiet_NaN();
double net_disp_ = std::numeric_limits<double>::quiet_NaN();
// Lịch sử eff cho progressProven(): mốc thời gian của mẫu eff tốt/thấp gần nhất. Xoá cùng cửa sổ vị trí.
bool has_eff_ok_ = false;
robot::Time eff_ok_t_;
bool has_eff_low_ = false;
robot::Time eff_low_t_;
// kStall
bool stall_seen_ = false;
robot::Time stall_since_;
bool stall_fired_ = false;
bool slip_seen_ = false;
robot::Time slip_since_;
bool has_stall_backoff_ = false;
robot::Time stall_backoff_until_;
bool has_prev_heavy_ = false; ///< mẫu nặng trước cho bộ lọc nhảy cost_to_go.
double prev_heavy_cost_ = 0.0;
double prev_heavy_travel_ = 0.0;
double prev_heavy_jump_dist_ = 0.0;
};
} // namespace env_monitor_core
#endif // ENV_MONITOR_CORE_STALL_DETECTOR_H_

View File

@@ -0,0 +1,172 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* env_monitor_core — kUnreachable (xem unreachable_detector.h).
*
* Author: DuongTD
*********************************************************************/
#include "unreachable_detector.h"
#include <cmath>
#include <memory>
#include <env_monitor_core/env_detector_abi.h>
namespace env_monitor_core
{
EnvDetector::Ptr UnreachableDetector::create()
{
return std::make_shared<UnreachableDetector>();
}
bool UnreachableDetector::initialize(const std::string& name, robot::NodeHandle& nh, std::string& error)
{
(void)name;
readUnreachable(nh, config_);
return validateUnreachable(config_, error);
}
std::string UnreachableDetector::describe() const
{
return describeUnreachable(config_);
}
EnvRouteSpec UnreachableDetector::defaultRoute() const
{
// Bản một khối: kUnreachable đi route `path_blocked`, cạn route là KHOÁ (dự báo, plan vẫn hợp lệ).
EnvRouteSpec spec;
spec.route = "path_blocked";
spec.lock_on_exhausted = true;
return spec;
}
bool UnreachableDetector::armed() const
{
return config_.action == "recover";
}
EnvNeeds UnreachableDetector::needs() const
{
EnvNeeds n;
n.geometry = config_.enabled;
return n;
}
void UnreachableDetector::reset()
{
baseline_pending_ = true;
baseline_unreachable_ = false;
unreach_seen_ = false;
unreach_fired_ = false;
has_unreach_backoff_ = false;
}
void UnreachableDetector::onPlanApplied(const EnvShared& shared)
{
(void)shared;
// Plan mới có baseline riêng: chỉ nổ "mất liên thông" vì thứ xảy ra SAU khi plan được lập (R2).
baseline_pending_ = true;
baseline_unreachable_ = false;
unreach_seen_ = false;
unreach_fired_ = false;
}
void UnreachableDetector::onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route)
{
(void)own_route;
if (outcome == EnvRecoveryOutcome::kFailed)
{
has_unreach_backoff_ = true;
unreach_backoff_until_ = shared.now + robot::Duration(config_.retry_backoff);
}
// Mọi kết cục đều kết thúc một pha dừng: chuỗi xác nhận cũ không còn giá trị.
unreach_seen_ = false;
unreach_fired_ = false;
}
void UnreachableDetector::update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v)
{
const EnvSample& s = frame.sample;
const EnvShared& sh = frame.shared;
if (!sh.measurable)
{
// Không có gì để đo tiến độ; xoá chuỗi để không nối "đúng liên tục" qua quãng gián đoạn.
unreach_seen_ = false;
unreach_fired_ = false;
return;
}
const EnvMonitorConfig::Unreachable& c = config_;
if (!c.enabled)
{
return;
}
// Trạng thái chỉ đổi ở tick nặng có kết luận; verdict thì phải ra MỖI cycle từ trạng thái, nếu
// không cờ nhấp nháy giữa hai tick 5 Hz và state machine 20 Hz thấy cờ bật/tắt.
if (s.geometry_valid && s.cost_conclusive)
{
// Baseline của plan: mẫu kết luận đầu tiên sau khi nhận plan. Plan đã không liên thông ngay từ
// đầu thì đó là chuyện của SBPL/planner đã lập nó — monitor không cãi trên cùng snapshot (R2).
if (baseline_pending_)
{
baseline_pending_ = false;
baseline_unreachable_ = !s.reachable;
}
if (s.reachable)
{
if (unreach_fired_)
{
out.event = "unreachable cleared: the exit is connected again";
}
unreach_seen_ = false;
unreach_fired_ = false;
baseline_unreachable_ = false; // từ đây mất liên thông là chuyện mới
}
else
{
const bool grace = sh.in_grace;
const bool clean = std::isfinite(s.edt_body_min) && s.edt_body_min >= c.clean_start_margin;
if (baseline_unreachable_ || grace || !clean)
{
// Không tích: chưa phải "xấu đi", hoặc robot đã lọt vành (SBPL không có chỗ bắt đầu — việc
// của kContact + controller_patience).
unreach_seen_ = false;
}
else
{
if (!unreach_seen_)
{
unreach_seen_ = true;
unreach_since_ = s.now;
}
if (!unreach_fired_ && (s.now - unreach_since_).toSec() >= c.static_on)
{
unreach_fired_ = true;
out.event = "unreachable: no path to the plan exit inside the window";
}
}
}
}
v.unreachable_detected = unreach_fired_;
if (!unreach_fired_)
{
return;
}
bool muted = false;
if (sh.replan_muted)
{
muted = true;
}
if (has_unreach_backoff_ && s.now < unreach_backoff_until_)
{
muted = true;
}
v.unreachable_muted = muted;
v.path_blocked = !muted && c.action == "recover";
out.fired = v.path_blocked;
}
} // namespace env_monitor_core
ENV_MONITOR_CORE_EXPORT_DETECTOR(env_monitor_core::UnreachableDetector::create, UnreachableDetector)

View File

@@ -0,0 +1,53 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* env_monitor_core — kUnreachable: không còn đường trong cửa sổ tới điểm thoát. Cờ `path_blocked`.
*
* Author: DuongTD
*********************************************************************/
#ifndef ENV_MONITOR_CORE_UNREACHABLE_DETECTOR_H_
#define ENV_MONITOR_CORE_UNREACHABLE_DETECTOR_H_
#include <string>
#include <robot/node_handle.h>
#include <robot/time.h>
#include <env_monitor_core/env_detector.h>
#include <env_monitor_core/env_monitor_config.h>
namespace env_monitor_core
{
class UnreachableDetector final : public EnvDetector
{
public:
/// Factory exported to boost::dll (symbol `UnreachableDetector`).
static EnvDetector::Ptr create();
bool initialize(const std::string& name, robot::NodeHandle& nh, std::string& error) override;
std::string describe() const override;
bool armed() const override;
EnvRouteSpec defaultRoute() const override;
EnvNeeds needs() const override;
void reset() override;
void onPlanApplied(const EnvShared& shared) override;
void onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route) override;
void update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v) override;
private:
EnvMonitorConfig::Unreachable config_;
bool baseline_pending_ = true; ///< chưa có mẫu kết luận nào từ plan hiện tại.
bool baseline_unreachable_ = false; ///< plan đã không liên thông ngay từ lúc nhận (R2: không cãi SBPL).
bool unreach_seen_ = false;
robot::Time unreach_since_;
bool unreach_fired_ = false;
bool has_unreach_backoff_ = false;
robot::Time unreach_backoff_until_;
};
} // namespace env_monitor_core
#endif // ENV_MONITOR_CORE_UNREACHABLE_DETECTOR_H_