feat: IntrusionDetector plugin and EnvContext host services
- env_context.h: non-owning TF buffer, sensor reader and frame names; host calls setContext() after initialize() - IntrusionDetector reads raw LaserScan, looks up TF at the scan stamp and flags new points close to the unpadded footprint; a point counts only if the reference scan shows that spot was free - stall detector, env types, golden data and tests updated
This commit is contained in:
159
plugins/intrusion_core.h
Normal file
159
plugins/intrusion_core.h
Normal file
@@ -0,0 +1,159 @@
|
||||
#ifndef ENV_MONITOR_CORE_INTRUSION_CORE_H_
|
||||
#define ENV_MONITOR_CORE_INTRUSION_CORE_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <robot/time.h>
|
||||
#include <tf3/LinearMath/Transform.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
namespace intrusion
|
||||
{
|
||||
struct EnvScan
|
||||
{
|
||||
std::string topic;
|
||||
robot::Time stamp;
|
||||
double angle_min = 0.0, angle_increment = 0.0;
|
||||
double range_min = 0.0, range_max = 0.0;
|
||||
std::vector<float> ranges;
|
||||
tf3::Transform fixed_from_lidar = tf3::Transform::getIdentity();
|
||||
};
|
||||
|
||||
struct Config
|
||||
{
|
||||
bool enabled = true;
|
||||
std::string action = "log";
|
||||
std::vector<std::string> topics{ "/f_scan", "/b_scan" };
|
||||
double zone_distance = 0.10; ///< [m]
|
||||
double compare_age = 0.3; ///< [s]
|
||||
double free_margin = 0.05; ///< [m]
|
||||
int min_points = 3;
|
||||
int confirm_scans = 2;
|
||||
double history_max_age = 1.0; ///< [s]
|
||||
double max_scan_age = 0.3; ///< [s]
|
||||
double max_tf_gap = 0.1; ///< [s]
|
||||
/// [m/s] and [rad/s] motion limits for comparison between two scans.
|
||||
double max_check_speed = 0.15;
|
||||
double max_check_yaw_rate = 0.3;
|
||||
bool debug_events = true;
|
||||
};
|
||||
|
||||
struct Result
|
||||
{
|
||||
bool detected = false;
|
||||
bool rising = false;
|
||||
int points = 0;
|
||||
double min_distance = std::numeric_limits<double>::infinity();
|
||||
double centroid_x = 0.0, centroid_y = 0.0;
|
||||
};
|
||||
|
||||
/// Stateful scan history and geometry only; does not read sensors, TF or log.
|
||||
class Evaluator
|
||||
{
|
||||
public:
|
||||
void configure(const Config& config);
|
||||
void reset();
|
||||
bool isNew(const std::string& topic, const robot::Time& stamp) const;
|
||||
Result evaluate(const std::vector<EnvScan>& scans, const tf3::Transform& fixed_from_base,
|
||||
const std::vector<std::pair<double, double>>& footprint, const robot::Time& now);
|
||||
private:
|
||||
struct History
|
||||
{
|
||||
std::vector<EnvScan> slots;
|
||||
std::size_t first = 0, count = 0;
|
||||
int streak = 0;
|
||||
};
|
||||
Config config_;
|
||||
std::vector<History> history_;
|
||||
bool detected_ = false;
|
||||
};
|
||||
|
||||
using Point = std::pair<double, double>;
|
||||
|
||||
/// Distance to the polygon boundary; zero-length edges are allowed.
|
||||
inline double boundaryDistance(const std::vector<Point>& polygon, double x, double y)
|
||||
{
|
||||
double result = std::numeric_limits<double>::infinity();
|
||||
for (std::size_t i = 0; i < polygon.size(); ++i)
|
||||
{
|
||||
const auto& a = polygon[i];
|
||||
const auto& b = polygon[(i + 1) % polygon.size()];
|
||||
const double dx = b.first - a.first, dy = b.second - a.second;
|
||||
const double length2 = dx * dx + dy * dy;
|
||||
const double t = length2 > 0.0 ? std::clamp(((x - a.first) * dx + (y - a.second) * dy) / length2, 0.0, 1.0) : 0.0;
|
||||
result = std::min(result, std::hypot(x - a.first - t * dx, y - a.second - t * dy));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
inline bool inside(const std::vector<Point>& polygon, double x, double y)
|
||||
{
|
||||
bool result = false;
|
||||
for (std::size_t i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++)
|
||||
{
|
||||
const auto& a = polygon[i];
|
||||
const auto& b = polygon[j];
|
||||
if ((a.second > y) != (b.second > y) &&
|
||||
x < (b.first - a.first) * (y - a.second) / (b.second - a.second) + a.first)
|
||||
result = !result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// A rigid transform must have finite translation and a right-handed orthonormal basis.
|
||||
inline bool validTransform(const tf3::Transform& transform)
|
||||
{
|
||||
constexpr double kTolerance = 1e-3;
|
||||
const auto& origin = transform.getOrigin();
|
||||
const auto& basis = transform.getBasis();
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
if (!std::isfinite(origin[i])) return false;
|
||||
for (int j = 0; j < 3; ++j)
|
||||
if (!std::isfinite(basis[i][j])) return false;
|
||||
}
|
||||
for (int i = 0; i < 3; ++i)
|
||||
for (int j = i; j < 3; ++j)
|
||||
if (std::fabs(basis.getColumn(i).dot(basis.getColumn(j)) - (i == j ? 1.0 : 0.0)) > kTolerance)
|
||||
return false;
|
||||
return std::fabs(basis.determinant() - 1.0) <= kTolerance;
|
||||
}
|
||||
|
||||
/// True only when all three reference rays prove that the fixed-frame point was free.
|
||||
inline bool wasFree(const EnvScan& ref, const tf3::Transform& lidar_from_fixed,
|
||||
const tf3::Vector3& point_fixed, double margin)
|
||||
{
|
||||
const tf3::Vector3 local = lidar_from_fixed * point_fixed;
|
||||
const double theta = std::atan2(local.y(), local.x());
|
||||
if (!std::isfinite(theta) || !std::isfinite(ref.angle_min) || !std::isfinite(ref.angle_increment) ||
|
||||
ref.angle_increment == 0.0 || !std::isfinite(ref.range_min) || !std::isfinite(ref.range_max))
|
||||
return false;
|
||||
double offset = theta - ref.angle_min;
|
||||
if (ref.angle_increment > 0.0)
|
||||
{
|
||||
constexpr double kTwoPi = 6.28318530717958647692;
|
||||
offset = std::fmod(offset, kTwoPi);
|
||||
if (offset < 0.0) offset += kTwoPi;
|
||||
}
|
||||
const double index = offset / ref.angle_increment;
|
||||
if (!std::isfinite(index) || index < 0.5 || index >= static_cast<double>(ref.ranges.size()) - 1.5)
|
||||
return false;
|
||||
const auto i = static_cast<std::size_t>(std::round(index));
|
||||
double nearest = std::numeric_limits<double>::infinity();
|
||||
for (std::size_t j = i - 1; j <= i + 1; ++j)
|
||||
{
|
||||
const double range = ref.ranges[j];
|
||||
if (std::isnan(range) || range < ref.range_min) return false;
|
||||
if (range <= ref.range_max) nearest = std::min(nearest, range);
|
||||
}
|
||||
return nearest > std::hypot(local.x(), local.y()) + margin;
|
||||
}
|
||||
} // namespace intrusion
|
||||
} // namespace env_monitor_core
|
||||
#endif // ENV_MONITOR_CORE_INTRUSION_CORE_H_
|
||||
373
plugins/intrusion_detector.cpp
Normal file
373
plugins/intrusion_detector.cpp
Normal file
@@ -0,0 +1,373 @@
|
||||
#include "intrusion_detector.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <iomanip>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <robot_sensor_msgs/LaserScan.h>
|
||||
#include <robot_sensor_ports/sensor_reader.h>
|
||||
#include <robot_sensor_ports/sensor_types.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
#include <env_monitor_core/env_detector_abi.h>
|
||||
|
||||
#include "intrusion_core.h"
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
template <typename T>
|
||||
std::string defaultText(const T& value)
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << value;
|
||||
return out.str();
|
||||
}
|
||||
std::string defaultText(double value)
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << std::fixed << std::setprecision(4) << value;
|
||||
return out.str();
|
||||
}
|
||||
std::string defaultText(bool value) { return value ? "true" : "false"; }
|
||||
std::string defaultText(const std::string& value) { return "'" + value + "'"; }
|
||||
std::string defaultText(const std::vector<std::string>& values)
|
||||
{
|
||||
std::string text = "[";
|
||||
for (std::size_t i = 0; i < values.size(); ++i)
|
||||
{
|
||||
if (i) text += ",";
|
||||
text += values[i];
|
||||
}
|
||||
return text + "]";
|
||||
}
|
||||
template <typename T>
|
||||
void readParam(robot::NodeHandle& nh, const char* key, T& value)
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
const std::string fallback = defaultText(value);
|
||||
robot::log_warning("[env_monitor_core] missing param '%s', using default %s", key, fallback.c_str());
|
||||
return;
|
||||
}
|
||||
nh.param(key, value, value);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
EnvDetector::Ptr IntrusionDetector::create() { return std::make_shared<IntrusionDetector>(); }
|
||||
|
||||
bool IntrusionDetector::initialize(const std::string& name, robot::NodeHandle& nh, std::string& error)
|
||||
{
|
||||
readParam(nh, "enabled", config_.enabled);
|
||||
readParam(nh, "action", config_.action);
|
||||
readParam(nh, "topics", config_.topics);
|
||||
readParam(nh, "zone_distance", config_.zone_distance);
|
||||
readParam(nh, "compare_age", config_.compare_age);
|
||||
readParam(nh, "free_margin", config_.free_margin);
|
||||
readParam(nh, "min_points", config_.min_points);
|
||||
readParam(nh, "confirm_scans", config_.confirm_scans);
|
||||
readParam(nh, "history_max_age", config_.history_max_age);
|
||||
readParam(nh, "max_scan_age", config_.max_scan_age);
|
||||
readParam(nh, "max_tf_gap", config_.max_tf_gap);
|
||||
readParam(nh, "max_check_speed", config_.max_check_speed);
|
||||
readParam(nh, "max_check_yaw_rate", config_.max_check_yaw_rate);
|
||||
readParam(nh, "debug/events", config_.debug_events);
|
||||
error.clear();
|
||||
const auto positive = [](double v) { return std::isfinite(v) && v > 0.0; };
|
||||
const auto require = [&](bool ok, const char* key, const std::string& value, const char* rule) {
|
||||
if (!ok && error.empty()) error = "env_monitor/" + name + "/" + key + " = " + value + " " + rule;
|
||||
};
|
||||
require(config_.action == "log" || config_.action == "recover", "action", defaultText(config_.action),
|
||||
"must be log or recover");
|
||||
require(!config_.topics.empty() &&
|
||||
std::none_of(config_.topics.begin(), config_.topics.end(), [](const std::string& t) { return t.empty(); }),
|
||||
"topics", defaultText(config_.topics), "must be non-empty and contain no empty topic");
|
||||
require(positive(config_.zone_distance) && config_.zone_distance <= 0.5, "zone_distance",
|
||||
defaultText(config_.zone_distance), "must be in (0, 0.5] m");
|
||||
require(positive(config_.compare_age), "compare_age", defaultText(config_.compare_age), "must be > 0 s");
|
||||
require(std::isfinite(config_.free_margin) && config_.free_margin >= 0.0, "free_margin",
|
||||
defaultText(config_.free_margin), "must be >= 0 m");
|
||||
require(config_.min_points >= 1, "min_points", defaultText(config_.min_points), "must be >= 1");
|
||||
require(config_.confirm_scans >= 1, "confirm_scans", defaultText(config_.confirm_scans), "must be >= 1");
|
||||
require(positive(config_.history_max_age) && config_.history_max_age > config_.compare_age, "history_max_age",
|
||||
defaultText(config_.history_max_age), "must be > compare_age");
|
||||
require(positive(config_.max_scan_age), "max_scan_age", defaultText(config_.max_scan_age), "must be > 0 s");
|
||||
require(positive(config_.max_tf_gap), "max_tf_gap", defaultText(config_.max_tf_gap), "must be > 0 s");
|
||||
require(positive(config_.max_check_speed), "max_check_speed", defaultText(config_.max_check_speed),
|
||||
"must be > 0 m/s");
|
||||
require(positive(config_.max_check_yaw_rate), "max_check_yaw_rate", defaultText(config_.max_check_yaw_rate),
|
||||
"must be > 0 rad/s");
|
||||
if (!error.empty()) return false;
|
||||
evaluator_.configure(config_);
|
||||
scans_.resize(config_.topics.size());
|
||||
topic_state_.assign(config_.topics.size(), TopicState());
|
||||
reset();
|
||||
return true;
|
||||
}
|
||||
std::string IntrusionDetector::describe() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << (config_.enabled ? "on" : "off") << " action=" << config_.action << " zone=" << config_.zone_distance
|
||||
<< " m compare_age=" << config_.compare_age << " s free_margin=" << config_.free_margin
|
||||
<< " m min_points=" << config_.min_points << " confirm_scans=" << config_.confirm_scans
|
||||
<< " history_max_age=" << config_.history_max_age << " s max_scan_age=" << config_.max_scan_age
|
||||
<< " s max_tf_gap=" << config_.max_tf_gap << " s max_check_speed=" << config_.max_check_speed << " m/s max_check_yaw_rate="
|
||||
<< config_.max_check_yaw_rate << " rad/s debug/events=" << config_.debug_events;
|
||||
return out.str();
|
||||
}
|
||||
bool IntrusionDetector::armed() const { return config_.action == "recover"; }
|
||||
EnvRouteSpec IntrusionDetector::defaultRoute() const { EnvRouteSpec r; r.route = "intrusion"; return r; }
|
||||
EnvNeeds IntrusionDetector::needs() const
|
||||
{
|
||||
EnvNeeds n;
|
||||
n.footprint = config_.enabled;
|
||||
return n;
|
||||
}
|
||||
void IntrusionDetector::setContext(const EnvContext& context)
|
||||
{
|
||||
context_ = context;
|
||||
missing_context_logged_ = false;
|
||||
base_failed_ = false;
|
||||
std::fill(topic_state_.begin(), topic_state_.end(), TopicState());
|
||||
evaluator_.reset();
|
||||
}
|
||||
void IntrusionDetector::reset() { evaluator_.reset(); }
|
||||
void IntrusionDetector::onRecoveryFinished(const EnvShared&, EnvRecoveryOutcome, bool) { reset(); }
|
||||
|
||||
void intrusion::Evaluator::configure(const Config& config)
|
||||
{
|
||||
config_ = config;
|
||||
history_.clear();
|
||||
history_.resize(config_.topics.size());
|
||||
reset();
|
||||
}
|
||||
void intrusion::Evaluator::reset()
|
||||
{
|
||||
for (auto& h : history_) { h.first = 0; h.count = 0; h.streak = 0; }
|
||||
detected_ = false;
|
||||
}
|
||||
bool intrusion::Evaluator::isNew(const std::string& topic, const robot::Time& stamp) const
|
||||
{
|
||||
const auto it = std::find(config_.topics.begin(), config_.topics.end(), topic);
|
||||
if (it == config_.topics.end()) return false;
|
||||
const auto& h = history_[static_cast<std::size_t>(it - config_.topics.begin())];
|
||||
return !h.count || stamp > h.slots[(h.first + h.count - 1) % h.slots.size()].stamp;
|
||||
}
|
||||
|
||||
intrusion::Result intrusion::Evaluator::evaluate(const std::vector<EnvScan>& scans,
|
||||
const tf3::Transform& fixed_from_base, const std::vector<Point>& footprint, const robot::Time& now)
|
||||
{
|
||||
Result result;
|
||||
if (!config_.enabled || footprint.size() < 3 || !validTransform(fixed_from_base)) return result;
|
||||
for (const auto& p : footprint)
|
||||
if (!std::isfinite(p.first) || !std::isfinite(p.second)) return result;
|
||||
int event_points = 0;
|
||||
double event_distance = std::numeric_limits<double>::infinity(), event_x = 0.0, event_y = 0.0;
|
||||
const tf3::Transform base_from_fixed = fixed_from_base.inverse();
|
||||
for (const auto& scan : scans)
|
||||
{
|
||||
const auto topic = std::find(config_.topics.begin(), config_.topics.end(), scan.topic);
|
||||
if (topic == config_.topics.end()) continue;
|
||||
History& h = history_[static_cast<std::size_t>(topic - config_.topics.begin())];
|
||||
const double age = (now - scan.stamp).toSec();
|
||||
if (!std::isfinite(age) || std::fabs(age) > config_.max_scan_age ||
|
||||
!intrusion::validTransform(scan.fixed_from_lidar) ||
|
||||
!std::isfinite(scan.angle_min) || !std::isfinite(scan.angle_increment) || scan.angle_increment == 0.0 ||
|
||||
!std::isfinite(scan.range_min) || !std::isfinite(scan.range_max) || scan.range_min < 0.0 ||
|
||||
scan.range_max < scan.range_min) continue;
|
||||
if (h.count && !(scan.stamp > h.slots[(h.first + h.count - 1) % h.slots.size()].stamp)) continue;
|
||||
while (h.count && (scan.stamp - h.slots[h.first].stamp).toSec() > config_.history_max_age)
|
||||
{ h.first = (h.first + 1) % h.slots.size(); --h.count; }
|
||||
const EnvScan* ref = nullptr;
|
||||
for (std::size_t j = h.count; j > 0; --j)
|
||||
{
|
||||
const auto& candidate = h.slots[(h.first + j - 1) % h.slots.size()];
|
||||
if ((scan.stamp - candidate.stamp).toSec() >= config_.compare_age) { ref = &candidate; break; }
|
||||
}
|
||||
if (ref)
|
||||
{
|
||||
// Judge only while the robot itself is nearly still (like Athena's stop-and-recheck): a fast self-motion times
|
||||
// the stamp/TF error moves static surfaces by centimetres. The chain breaks — a fast pair is no evidence.
|
||||
const double dt = (scan.stamp - ref->stamp).toSec();
|
||||
const auto& origin = scan.fixed_from_lidar.getOrigin();
|
||||
const auto& ref_origin = ref->fixed_from_lidar.getOrigin();
|
||||
const auto axis = scan.fixed_from_lidar.getBasis().getColumn(0);
|
||||
const auto ref_axis = ref->fixed_from_lidar.getBasis().getColumn(0);
|
||||
const double moved = std::hypot(origin.x() - ref_origin.x(), origin.y() - ref_origin.y());
|
||||
const double turned = std::fabs(std::remainder(std::atan2(axis.y(), axis.x()) -
|
||||
std::atan2(ref_axis.y(), ref_axis.x()), 2.0 * M_PI));
|
||||
if (moved > config_.max_check_speed * dt || turned > config_.max_check_yaw_rate * dt)
|
||||
{
|
||||
h.streak = 0;
|
||||
ref = nullptr;
|
||||
}
|
||||
}
|
||||
if (ref)
|
||||
{
|
||||
const tf3::Transform ref_from_fixed = ref->fixed_from_lidar.inverse();
|
||||
int points = 0;
|
||||
double min_distance = std::numeric_limits<double>::infinity(), sum_x = 0.0, sum_y = 0.0;
|
||||
for (std::size_t i = 0; i < scan.ranges.size(); ++i)
|
||||
{
|
||||
const double r = scan.ranges[i];
|
||||
if (!std::isfinite(r) || r < scan.range_min || r > scan.range_max) continue;
|
||||
const double angle = scan.angle_min + i * scan.angle_increment;
|
||||
const tf3::Vector3 fixed = scan.fixed_from_lidar * tf3::Vector3(r * std::cos(angle), r * std::sin(angle), 0);
|
||||
const tf3::Vector3 body = base_from_fixed * fixed;
|
||||
const double bx = body.x(), by = body.y();
|
||||
const double distance = intrusion::boundaryDistance(footprint, bx, by);
|
||||
if (distance <= 1e-9 || distance > config_.zone_distance || intrusion::inside(footprint, bx, by) ||
|
||||
!intrusion::wasFree(*ref, ref_from_fixed, fixed, config_.free_margin)) continue;
|
||||
++points; sum_x += bx; sum_y += by; min_distance = std::min(min_distance, distance);
|
||||
}
|
||||
// shortcut: no cross-topic merge — an object seen by both lidars with < min_points each is missed; merge per time window if sim shows it
|
||||
if (points >= config_.min_points)
|
||||
{
|
||||
if (h.streak < config_.confirm_scans)
|
||||
{
|
||||
++h.streak;
|
||||
if (h.streak == config_.confirm_scans)
|
||||
{
|
||||
event_points = points; event_distance = min_distance; event_x = sum_x; event_y = sum_y;
|
||||
}
|
||||
}
|
||||
}
|
||||
else h.streak = 0;
|
||||
}
|
||||
if (h.count == h.slots.size())
|
||||
{
|
||||
// Preserve chronological order when the ring grows; warmed-up slots retain their range buffers.
|
||||
std::rotate(h.slots.begin(), h.slots.begin() + h.first, h.slots.end());
|
||||
h.first = 0;
|
||||
h.slots.emplace_back();
|
||||
}
|
||||
h.slots[(h.first + h.count) % h.slots.size()] = scan;
|
||||
++h.count;
|
||||
}
|
||||
// A lidar that went silent (or stale) after confirming must not hold the flag up until the next reset.
|
||||
for (auto& h : history_)
|
||||
if (h.count && (now - h.slots[(h.first + h.count - 1) % h.slots.size()].stamp).toSec() > config_.max_scan_age)
|
||||
h.streak = 0;
|
||||
const bool detected = std::any_of(history_.begin(), history_.end(),
|
||||
[&](const History& h) { return h.streak >= config_.confirm_scans; });
|
||||
result.detected = detected;
|
||||
result.rising = detected && !detected_;
|
||||
result.points = event_points;
|
||||
result.min_distance = event_distance;
|
||||
if (event_points > 0)
|
||||
{
|
||||
result.centroid_x = event_x / event_points;
|
||||
result.centroid_y = event_y / event_points;
|
||||
}
|
||||
detected_ = detected;
|
||||
return result;
|
||||
}
|
||||
|
||||
void IntrusionDetector::evaluate(const std::vector<intrusion::EnvScan>& scans,
|
||||
const tf3::Transform& fixed_from_base, const std::vector<intrusion::Point>& footprint,
|
||||
const robot::Time& now, EnvDetectorOutput& out, EnvVerdict& verdict)
|
||||
{
|
||||
const auto result = evaluator_.evaluate(scans, fixed_from_base, footprint, now);
|
||||
verdict.intrusion_detected = result.detected;
|
||||
out.fired = result.detected && armed();
|
||||
if (result.rising)
|
||||
{
|
||||
out.event = "intrusion";
|
||||
if (config_.debug_events)
|
||||
{
|
||||
const char* side = std::fabs(result.centroid_x) >= std::fabs(result.centroid_y) ?
|
||||
(result.centroid_x >= 0 ? "front" : "rear") : (result.centroid_y >= 0 ? "left" : "right");
|
||||
robot::log_info("[env_monitor_core][debug] intrusion points=%d min_distance=%.3f m side=%s action=%s",
|
||||
result.points, result.min_distance, side, config_.action.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IntrusionDetector::update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& verdict)
|
||||
{
|
||||
if (!config_.enabled) return;
|
||||
if (!context_.tf || !context_.sensors || context_.fixed_frame.empty() || context_.base_frame.empty())
|
||||
{
|
||||
if (!missing_context_logged_)
|
||||
{
|
||||
robot::log_error("[env_monitor_core] intrusion: TF, sensor reader or frame is missing in context");
|
||||
missing_context_logged_ = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!frame.sample.footprint_valid) return;
|
||||
const auto toTransform = [](const tf3::TransformStampedMsg& msg, tf3::Transform& result) {
|
||||
const auto& q = msg.transform.rotation;
|
||||
const auto& t = msg.transform.translation;
|
||||
const double norm = q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w;
|
||||
if (!std::isfinite(norm) || std::fabs(norm - 1.0) > 0.01 ||
|
||||
!std::isfinite(t.x) || !std::isfinite(t.y) || !std::isfinite(t.z)) return false;
|
||||
result = tf3::Transform(tf3::Quaternion(q.x, q.y, q.z, q.w), tf3::Vector3(t.x, t.y, t.z));
|
||||
return intrusion::validTransform(result);
|
||||
};
|
||||
tf3::Transform fixed_from_base = tf3::Transform::getIdentity();
|
||||
bool base_ok = false;
|
||||
try { base_ok = toTransform(context_.tf->lookupTransform(context_.fixed_frame, context_.base_frame, tf3::Time()),
|
||||
fixed_from_base); }
|
||||
catch (const std::exception&) {}
|
||||
if (!base_ok)
|
||||
{
|
||||
if (!base_failed_) robot::log_warning("[env_monitor_core] intrusion: base TF unavailable");
|
||||
base_failed_ = true;
|
||||
return;
|
||||
}
|
||||
if (base_failed_) robot::log_info("[env_monitor_core] intrusion: base TF restored");
|
||||
base_failed_ = false;
|
||||
for (std::size_t i = 0; i < config_.topics.size(); ++i)
|
||||
{
|
||||
auto& dest = scans_[i];
|
||||
dest.topic.clear();
|
||||
const auto& topic = config_.topics[i];
|
||||
uint64_t since = 0;
|
||||
const auto scan = robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(*context_.sensors, topic, since);
|
||||
bool ok = static_cast<bool>(scan);
|
||||
if (ok)
|
||||
{
|
||||
const double age = (frame.sample.now - scan->header.stamp).toSec();
|
||||
if (!std::isfinite(age) || std::fabs(age) > config_.max_scan_age ||
|
||||
!evaluator_.isNew(topic, scan->header.stamp)) continue;
|
||||
}
|
||||
if (ok)
|
||||
{
|
||||
tf3::TransformStampedMsg transform;
|
||||
try
|
||||
{
|
||||
try { transform = context_.tf->lookupTransform(context_.fixed_frame, scan->header.frame_id,
|
||||
tf3::Time(scan->header.stamp.sec, scan->header.stamp.nsec)); }
|
||||
catch (const std::exception&)
|
||||
{
|
||||
transform = context_.tf->lookupTransform(context_.fixed_frame, scan->header.frame_id, tf3::Time());
|
||||
const double gap = std::fabs(transform.header.stamp.toSec() - scan->header.stamp.toSec());
|
||||
if (!std::isfinite(gap) || gap > config_.max_tf_gap) ok = false;
|
||||
}
|
||||
if (ok) ok = toTransform(transform, dest.fixed_from_lidar);
|
||||
}
|
||||
catch (const std::exception&) { ok = false; }
|
||||
}
|
||||
auto& state = topic_state_[i];
|
||||
if (!ok && (!state.checked || !state.failed))
|
||||
robot::log_warning("[env_monitor_core] intrusion: scan or TF unavailable for '%s'", topic.c_str());
|
||||
if (ok && state.checked && state.failed)
|
||||
robot::log_info("[env_monitor_core] intrusion: scan and TF restored for '%s'", topic.c_str());
|
||||
state.checked = true; state.failed = !ok;
|
||||
if (!ok) continue;
|
||||
dest.topic = topic;
|
||||
dest.stamp = scan->header.stamp;
|
||||
dest.angle_min = scan->angle_min; dest.angle_increment = scan->angle_increment;
|
||||
dest.range_min = scan->range_min; dest.range_max = scan->range_max;
|
||||
dest.ranges = scan->ranges;
|
||||
}
|
||||
evaluate(scans_, fixed_from_base, frame.sample.footprint, frame.sample.now, out, verdict);
|
||||
}
|
||||
|
||||
} // namespace env_monitor_core
|
||||
ENV_MONITOR_CORE_EXPORT_DETECTOR(env_monitor_core::IntrusionDetector::create, IntrusionDetector)
|
||||
45
plugins/intrusion_detector.h
Normal file
45
plugins/intrusion_detector.h
Normal file
@@ -0,0 +1,45 @@
|
||||
#ifndef ENV_MONITOR_CORE_INTRUSION_DETECTOR_H_
|
||||
#define ENV_MONITOR_CORE_INTRUSION_DETECTOR_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <env_monitor_core/env_detector.h>
|
||||
|
||||
#include "intrusion_core.h"
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
/// Detects newly occupied space close to the unpadded body.
|
||||
class IntrusionDetector final : public EnvDetector
|
||||
{
|
||||
public:
|
||||
static EnvDetector::Ptr create();
|
||||
bool initialize(const std::string& name, robot::NodeHandle& nh, std::string& error) override;
|
||||
void setContext(const EnvContext& context) override;
|
||||
std::string describe() const override;
|
||||
bool armed() const override;
|
||||
EnvRouteSpec defaultRoute() const override;
|
||||
EnvNeeds needs() const override;
|
||||
void reset() override;
|
||||
void onRecoveryFinished(const EnvShared&, EnvRecoveryOutcome, bool) override;
|
||||
void update(const EnvFrame&, EnvDetectorOutput&, EnvVerdict&) override;
|
||||
|
||||
/// Geometry-only evaluation, also usable by synthetic scan tests.
|
||||
void evaluate(const std::vector<intrusion::EnvScan>& scans, const tf3::Transform& fixed_from_base,
|
||||
const std::vector<intrusion::Point>& footprint, const robot::Time& now,
|
||||
EnvDetectorOutput& out, EnvVerdict& verdict);
|
||||
|
||||
private:
|
||||
struct TopicState { bool checked = false; bool failed = false; };
|
||||
intrusion::Config config_;
|
||||
intrusion::Evaluator evaluator_;
|
||||
EnvContext context_;
|
||||
std::vector<intrusion::EnvScan> scans_;
|
||||
std::vector<TopicState> topic_state_;
|
||||
bool missing_context_logged_ = false;
|
||||
bool base_failed_ = false;
|
||||
|
||||
};
|
||||
} // namespace env_monitor_core
|
||||
#endif // ENV_MONITOR_CORE_INTRUSION_DETECTOR_H_
|
||||
@@ -89,6 +89,14 @@ void StallDetector::onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutco
|
||||
// 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;
|
||||
// Recovery thành công là một lượt thử mới như plan mới: quãng nó tự lùi/xoay không phải "lệnh đi mà không tiến"
|
||||
// (sim 27/11 12:17:22: evade lùi 2 lần 0.2 m, cửa sổ cũ cho eff -0.62 -> stall nổ oan). Hỏng thì giữ cửa sổ, backoff lo.
|
||||
if (outcome != EnvRecoveryOutcome::kFailed)
|
||||
{
|
||||
clearWindow();
|
||||
clearPosWindow();
|
||||
has_prev_heavy_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
void StallDetector::clearWindow()
|
||||
|
||||
Reference in New Issue
Block a user