feat: add the wall reflector detection action
Action handler that detects two flat reflective tape strips on a wall from a raw LaserScan and publishes the stop-station target (and a marker frame) as static TFs for the next move_to stage. Geometry comes from dock_pattern_detector's ReflectorPairMatcher. The handler adds scan freshness checks (stamp after settle, max age, strictly increasing stamps) and a deadline for detections waiting on TF, derives lidar flip and tilt from TF, and never reuses samples across pause/resume or runs.
This commit is contained in:
734
plugins/wall_reflector_detection_action_handler.cpp
Normal file
734
plugins/wall_reflector_detection_action_handler.cpp
Normal file
@@ -0,0 +1,734 @@
|
||||
#include <action_core/action_handler.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
#include <robot/robot.h>
|
||||
#include <robot_sensor_msgs/LaserScan.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
#include <action_core/action_abi.h>
|
||||
#include <action_core/pose_sample_filter.h>
|
||||
#include <dock_pattern_detector/reflector_pair_matcher.h>
|
||||
#include <robot_sensor_ports/sensor_reader.h>
|
||||
#include <robot_sensor_ports/sensor_types.h>
|
||||
|
||||
namespace action_core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
constexpr double kMaxTilt = 0.0873;
|
||||
|
||||
double yawOf(const tf3::QuaternionMsg& q)
|
||||
{
|
||||
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));
|
||||
}
|
||||
|
||||
double secondsBetween(const robot::Time& first, const robot::Time& second)
|
||||
{
|
||||
return static_cast<double>(static_cast<int64_t>(first.toNSec()) -
|
||||
static_cast<int64_t>(second.toNSec())) * 1e-9;
|
||||
}
|
||||
|
||||
double wrap(double angle)
|
||||
{
|
||||
return std::atan2(std::sin(angle), std::cos(angle));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void load(robot::NodeHandle& nh, const char* key, T& value)
|
||||
{
|
||||
nh.param(key, value, value);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
/**
|
||||
* @brief Adapter scan → marker → hai TF tĩnh, không điều khiển vận tốc.
|
||||
*
|
||||
* Sensor và TF là cổng non-owning của context. Marker P1 nằm trong prior_frame; TF từ prior_frame
|
||||
* sang global_frame được tra đúng timestamp scan trước khi đưa marker vào PoseSampleFilter.
|
||||
*/
|
||||
class WallReflectorDetectionActionHandler final : public ActionHandler
|
||||
{
|
||||
public:
|
||||
static ActionHandler::Ptr create()
|
||||
{
|
||||
return std::make_shared<WallReflectorDetectionActionHandler>();
|
||||
}
|
||||
|
||||
bool configure(const std::string& name, const ActionContext& context,
|
||||
robot::NodeHandle& nh) override
|
||||
{
|
||||
initialized_ = false;
|
||||
active_ = false;
|
||||
paused_ = false;
|
||||
name_ = name;
|
||||
ctx_ = context;
|
||||
if (!ctx_.tf || !ctx_.sensors || ctx_.global_frame.empty() || ctx_.robot_base_frame.empty())
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': TF, sensor store and context frames are required.",
|
||||
name_.c_str());
|
||||
return false;
|
||||
}
|
||||
nh.param("action_types", action_types_, std::vector<std::string>{"DetectWallReflectors"});
|
||||
nh.param("output_frame", output_frame_, std::string("wall_reflector_target"));
|
||||
nh.param("marker_frame", marker_frame_, std::string("wall_reflector_frame"));
|
||||
nh.param("scan_topic", scan_topic_, std::string());
|
||||
nh.param("prior_frame", prior_frame_, std::string("base_link"));
|
||||
nh.param("default_profile", default_profile_, std::string());
|
||||
nh.param("profile_param_key", profile_param_key_, std::string("reflector_profile"));
|
||||
nh.param("settle_delay", settle_delay_, 0.4);
|
||||
nh.param("timeout", timeout_, 15.0);
|
||||
nh.param("max_scan_age", max_scan_age_, 0.3);
|
||||
nh.param("max_future_skew", max_future_skew_, 0.05);
|
||||
nh.param("pending_tf_timeout", pending_tf_timeout_, 0.2);
|
||||
load(nh, "min_range", limits_.min_range);
|
||||
load(nh, "max_range", limits_.max_range);
|
||||
load(nh, "zero_range_is_no_echo", limits_.zero_range_is_no_echo);
|
||||
int max_candidates = 16;
|
||||
int max_pairs = 120;
|
||||
int max_scan_rays = 4096;
|
||||
load(nh, "max_candidates", max_candidates);
|
||||
load(nh, "max_pairs", max_pairs);
|
||||
load(nh, "max_scan_rays", max_scan_rays);
|
||||
std::string direction = "forward";
|
||||
load(nh, "entry_direction", direction);
|
||||
robot::NodeHandle debug(nh, "debug");
|
||||
debug.param("state", debug_state_, true);
|
||||
debug.param("detect", debug_detect_, true);
|
||||
debug.param("skip", debug_skip_, true);
|
||||
|
||||
if (action_types_.empty() || std::any_of(action_types_.begin(), action_types_.end(),
|
||||
[](const std::string& value) { return value.empty(); }))
|
||||
return configError("action_types must contain nonempty unique types");
|
||||
std::vector<std::string> sorted = action_types_;
|
||||
std::sort(sorted.begin(), sorted.end());
|
||||
if (std::adjacent_find(sorted.begin(), sorted.end()) != sorted.end())
|
||||
return configError("action_types contains duplicates");
|
||||
if (output_frame_.empty() || output_frame_ == ctx_.global_frame ||
|
||||
output_frame_ == ctx_.robot_base_frame || output_frame_ == prior_frame_ ||
|
||||
(!marker_frame_.empty() && (marker_frame_ == output_frame_ ||
|
||||
marker_frame_ == ctx_.global_frame || marker_frame_ == ctx_.robot_base_frame ||
|
||||
marker_frame_ == prior_frame_)))
|
||||
return configError("output_frame/marker_frame conflict with each other or context frames");
|
||||
if (scan_topic_.empty() || prior_frame_.empty() || default_profile_.empty() ||
|
||||
profile_param_key_.empty())
|
||||
return configError("scan_topic, prior_frame, default_profile and profile_param_key are required");
|
||||
if (!robot_sensor_ports::has<robot_sensor_msgs::LaserScan>(*ctx_.sensors, scan_topic_))
|
||||
return configError("scan_topic is not a LaserScan in sensor store");
|
||||
if (direction != "forward" && direction != "backward")
|
||||
return configError("entry_direction must be forward or backward");
|
||||
forward_ = direction == "forward";
|
||||
if (!std::isfinite(settle_delay_) || settle_delay_ < 0.0 || !std::isfinite(timeout_) ||
|
||||
timeout_ <= 0.0 || !std::isfinite(max_scan_age_) || max_scan_age_ <= 0.0 ||
|
||||
!std::isfinite(max_future_skew_) || max_future_skew_ < 0.0 ||
|
||||
!std::isfinite(pending_tf_timeout_) || pending_tf_timeout_ <= 0.0 ||
|
||||
pending_tf_timeout_ > max_scan_age_)
|
||||
return configError("invalid settle_delay, timeout or freshness limits");
|
||||
if (!std::isfinite(limits_.min_range) || !std::isfinite(limits_.max_range) ||
|
||||
limits_.min_range < 0.0 || limits_.max_range <= limits_.min_range ||
|
||||
max_candidates < 2 || max_candidates > 128 || max_pairs < 1 || max_pairs > 8128 ||
|
||||
max_scan_rays < 2 || max_scan_rays > 65536)
|
||||
return configError("invalid matcher range or capacity limits");
|
||||
limits_.max_candidates = static_cast<std::size_t>(max_candidates);
|
||||
limits_.max_pairs = static_cast<std::size_t>(max_pairs);
|
||||
limits_.max_scan_rays = static_cast<std::size_t>(max_scan_rays);
|
||||
if (!loadProfiles(nh) || !loadFilter(nh))
|
||||
return false;
|
||||
initialized_ = true;
|
||||
robot::log_info("[wall_reflector] '%s': scan=%s prior=%s target=%s marker=%s direction=%s "
|
||||
"profiles=%zu default=%s debug/state=%s debug/detect=%s debug/skip=%s",
|
||||
name_.c_str(), scan_topic_.c_str(), prior_frame_.c_str(), output_frame_.c_str(),
|
||||
marker_frame_.c_str(), direction.c_str(), profiles_.size(), default_profile_.c_str(),
|
||||
debug_state_ ? "on" : "off", debug_detect_ ? "on" : "off",
|
||||
debug_skip_ ? "on" : "off");
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::string> supportedActionTypes() const override { return action_types_; }
|
||||
|
||||
bool start(const robot_protocol_msgs::Action& action, const robot::Time& now) override
|
||||
{
|
||||
active_ = false;
|
||||
if (!initialized_)
|
||||
return false;
|
||||
clearRun(now);
|
||||
started_at_ = now;
|
||||
paused_ = false;
|
||||
action_id_ = action.actionId;
|
||||
std::string selected = default_profile_;
|
||||
for (const auto& parameter : action.actionParameters)
|
||||
if (parameter.key == profile_param_key_ && !parameter.value.empty())
|
||||
selected = parameter.value;
|
||||
const auto found = profiles_.find(selected);
|
||||
if (found == profiles_.end())
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': unknown profile '%s'.", name_.c_str(), selected.c_str());
|
||||
return false;
|
||||
}
|
||||
std::string error;
|
||||
if (!matcher_.configure(found->second, error))
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': profile '%s': %s", name_.c_str(), selected.c_str(), error.c_str());
|
||||
return false;
|
||||
}
|
||||
active_profile_ = found->second;
|
||||
active_ = true;
|
||||
if (debug_state_)
|
||||
robot::log_info("[wall_reflector][debug] '%s': started profile '%s'.", name_.c_str(), selected.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
ActionTick update(const robot::Time& now) override
|
||||
{
|
||||
ActionTick tick;
|
||||
if (!initialized_ || !active_)
|
||||
{
|
||||
tick.status = ActionStatus::kFailed;
|
||||
tick.message = "wall_reflector: not active";
|
||||
return tick;
|
||||
}
|
||||
if (paused_)
|
||||
return tick;
|
||||
if (now < last_now_)
|
||||
{
|
||||
clearRun(now);
|
||||
started_at_ = now;
|
||||
noteReason("clock moved backwards; waiting for new scans");
|
||||
}
|
||||
last_now_ = now;
|
||||
if (secondsBetween(now, started_at_) >= timeout_)
|
||||
{
|
||||
active_ = false;
|
||||
tick.status = ActionStatus::kFailed;
|
||||
tick.message = "wall_reflector timeout: " +
|
||||
(last_reason_.empty() ? std::string("insufficient samples") : last_reason_);
|
||||
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), tick.message.c_str());
|
||||
return tick;
|
||||
}
|
||||
if (secondsBetween(now, settle_start_) >= settle_delay_)
|
||||
processScan(now);
|
||||
if (!mount_error_.empty())
|
||||
{
|
||||
active_ = false;
|
||||
tick.status = ActionStatus::kFailed;
|
||||
tick.message = mount_error_;
|
||||
return tick;
|
||||
}
|
||||
if (filter_.pruneExpired(now))
|
||||
filter_.evaluate(now);
|
||||
if (have_sample_stamp_ && !fresh(last_sample_stamp_, now))
|
||||
{
|
||||
filter_.reset();
|
||||
have_sample_stamp_ = false;
|
||||
noteReason("latest filter scan stale");
|
||||
}
|
||||
if (have_sample_stamp_ && filter_.windowSize() > 0 && filter_.holdSatisfied(now))
|
||||
{
|
||||
active_ = false;
|
||||
if (!publish(filter_.holdPose(), now))
|
||||
{
|
||||
tick.status = ActionStatus::kFailed;
|
||||
tick.message = "wall_reflector: failed to publish output TF";
|
||||
return tick;
|
||||
}
|
||||
tick.status = ActionStatus::kSucceeded;
|
||||
tick.message = marker_frame_.empty() ? "wall_reflector: target published"
|
||||
: "wall_reflector: marker and target published";
|
||||
return tick;
|
||||
}
|
||||
if (reason_dirty_)
|
||||
{
|
||||
tick.message = last_reason_;
|
||||
reason_dirty_ = false;
|
||||
}
|
||||
return tick;
|
||||
}
|
||||
|
||||
void pause(const robot::Time& now) override
|
||||
{
|
||||
if (active_ && !paused_)
|
||||
{
|
||||
paused_ = true;
|
||||
paused_at_ = now;
|
||||
filter_.reset();
|
||||
pending_valid_ = false;
|
||||
have_sample_stamp_ = false;
|
||||
if (debug_state_)
|
||||
robot::log_info("[wall_reflector][debug] '%s': paused.", name_.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void resume(const robot::Time& now) override
|
||||
{
|
||||
if (active_ && paused_)
|
||||
{
|
||||
if (now >= paused_at_)
|
||||
started_at_ += now - paused_at_;
|
||||
else
|
||||
started_at_ = now;
|
||||
clearRun(now);
|
||||
paused_ = false;
|
||||
if (debug_state_)
|
||||
robot::log_info("[wall_reflector][debug] '%s': resumed; settling again.", name_.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void cancel() override
|
||||
{
|
||||
active_ = false;
|
||||
paused_ = false;
|
||||
pending_valid_ = false;
|
||||
have_sample_stamp_ = false;
|
||||
filter_.reset();
|
||||
if (debug_state_)
|
||||
robot::log_info("[wall_reflector][debug] '%s': cancelled.", name_.c_str());
|
||||
}
|
||||
|
||||
private:
|
||||
bool configError(const char* message)
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), message);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool loadProfiles(robot::NodeHandle& nh)
|
||||
{
|
||||
YAML::Node profiles;
|
||||
if (!nh.getParam("profiles", profiles) || !profiles.IsMap() || profiles.size() == 0)
|
||||
return configError("profiles must be a nonempty map");
|
||||
profiles_.clear();
|
||||
for (const auto& entry : profiles)
|
||||
{
|
||||
const std::string key = entry.first.as<std::string>();
|
||||
robot::NodeHandle p(nh, "profiles/" + key);
|
||||
dock_pattern_detector::ReflectorPairProfile profile;
|
||||
load(p, "tape_width", profile.tape_width);
|
||||
load(p, "width_tolerance", profile.width_tolerance);
|
||||
load(p, "tape_spacing", profile.tape_spacing);
|
||||
load(p, "spacing_tolerance", profile.spacing_tolerance);
|
||||
load(p, "tape_min_intensity", profile.tape_min_intensity);
|
||||
load(p, "tape_core_intensity", profile.tape_core_intensity);
|
||||
load(p, "tape_bloom_max_angle", profile.tape_bloom_max_angle);
|
||||
load(p, "tape_plateau_min_fraction", profile.tape_plateau_min_fraction);
|
||||
load(p, "edge_bias_bound", profile.edge_bias_bound);
|
||||
load(p, "max_edge_uncertainty", profile.max_edge_uncertainty);
|
||||
load(p, "min_ray_wall_cos", profile.min_ray_wall_cos);
|
||||
load(p, "wall_min_span", profile.wall_min_span);
|
||||
load(p, "wall_max_rms", profile.wall_max_rms);
|
||||
load(p, "wall_max_residual", profile.wall_max_residual);
|
||||
load(p, "wall_max_gap", profile.wall_max_gap);
|
||||
load(p, "wall_max_extrapolation", profile.wall_max_extrapolation);
|
||||
load(p, "wall_merge_distance", profile.wall_merge_distance);
|
||||
load(p, "has_prior", profile.has_prior);
|
||||
load(p, "prior_x", profile.prior_x);
|
||||
load(p, "prior_y", profile.prior_y);
|
||||
load(p, "prior_yaw", profile.prior_yaw);
|
||||
load(p, "prior_position_tolerance", profile.prior_position_tolerance);
|
||||
load(p, "prior_yaw_tolerance", profile.prior_yaw_tolerance);
|
||||
load(p, "search_center_yaw", profile.search_center_yaw);
|
||||
load(p, "search_fov", profile.search_fov);
|
||||
load(p, "offset_x", profile.offset_x);
|
||||
load(p, "offset_y", profile.offset_y);
|
||||
load(p, "offset_yaw", profile.offset_yaw);
|
||||
int tape_points = static_cast<int>(profile.tape_min_points);
|
||||
int wall_points = static_cast<int>(profile.wall_min_points_each_side);
|
||||
load(p, "tape_min_points", tape_points);
|
||||
load(p, "wall_min_points_each_side", wall_points);
|
||||
profile.tape_min_points = static_cast<std::size_t>(std::max(0, tape_points));
|
||||
profile.wall_min_points_each_side = static_cast<std::size_t>(std::max(0, wall_points));
|
||||
std::string error;
|
||||
if (!profile.validate(error))
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': profile '%s': %s", name_.c_str(), key.c_str(), error.c_str());
|
||||
return false;
|
||||
}
|
||||
profiles_[key] = profile;
|
||||
}
|
||||
if (profiles_.find(default_profile_) == profiles_.end())
|
||||
return configError("default_profile does not exist");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadFilter(robot::NodeHandle& nh)
|
||||
{
|
||||
PoseSampleFilterConfig config;
|
||||
config.enabled = true;
|
||||
nh.param("sample_window", config.sample_window, 1.0);
|
||||
nh.param("min_samples", config.min_samples, 5);
|
||||
nh.param("max_spread_xy", config.max_spread_xy, 0.03);
|
||||
nh.param("max_spread_yaw", config.max_spread_yaw, 0.05);
|
||||
nh.param("hold_time", config.hold_time, 0.0);
|
||||
nh.param("jump_threshold", config.jump_threshold, 0.0);
|
||||
nh.param("cluster_recency", config.cluster_recency, 0.3);
|
||||
nh.param("min_cluster_fraction", config.min_cluster_fraction, 0.6);
|
||||
nh.param("min_cluster_samples", config.min_cluster_samples, 3);
|
||||
if (config.min_samples < 3 || config.max_spread_yaw > kPi ||
|
||||
!std::isfinite(config.cluster_recency) || config.cluster_recency <= 0.0 ||
|
||||
!std::isfinite(config.min_cluster_fraction) || config.min_cluster_fraction <= 0.5 ||
|
||||
config.min_cluster_fraction > 1.0 || config.min_cluster_samples < 3 ||
|
||||
config.min_cluster_samples > config.min_samples ||
|
||||
timeout_ <= settle_delay_ + config.sample_window + config.hold_time)
|
||||
return configError("invalid filter limits or timeout");
|
||||
return filter_.configure(config, name_);
|
||||
}
|
||||
|
||||
void clearRun(const robot::Time& now)
|
||||
{
|
||||
filter_.reset();
|
||||
filter_.setLabels(scan_topic_, ctx_.global_frame);
|
||||
settle_start_ = now;
|
||||
last_now_ = now;
|
||||
scan_cursor_ = 0;
|
||||
pending_valid_ = false;
|
||||
have_seen_stamp_ = false;
|
||||
have_sample_stamp_ = false;
|
||||
mount_valid_ = false;
|
||||
mount_error_.clear();
|
||||
last_reason_.clear();
|
||||
reason_dirty_ = false;
|
||||
have_skip_log_ = false;
|
||||
}
|
||||
|
||||
void noteReason(const std::string& reason)
|
||||
{
|
||||
if (reason != last_reason_)
|
||||
{
|
||||
last_reason_ = reason;
|
||||
reason_dirty_ = true;
|
||||
if (debug_skip_ && (!have_skip_log_ || secondsBetween(last_now_, last_skip_log_) >= 1.0))
|
||||
{
|
||||
robot::log_info("[wall_reflector][debug] '%s': %s", name_.c_str(), reason.c_str());
|
||||
last_skip_log_ = last_now_;
|
||||
have_skip_log_ = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const char* freshnessError(const robot::Time& stamp, const robot::Time& now) const
|
||||
{
|
||||
if (stamp.isZero())
|
||||
return "scan stamp is zero";
|
||||
if (secondsBetween(stamp, settle_start_) < settle_delay_)
|
||||
return "scan before settle";
|
||||
const double age = secondsBetween(now, stamp);
|
||||
if (!std::isfinite(age) || age < -max_future_skew_)
|
||||
return "scan future beyond allowed skew";
|
||||
if (age > max_scan_age_)
|
||||
return "scan stale";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool fresh(const robot::Time& stamp, const robot::Time& now) const
|
||||
{
|
||||
return freshnessError(stamp, now) == nullptr;
|
||||
}
|
||||
|
||||
bool ensureMount(const std::string& scan_frame)
|
||||
{
|
||||
if (mount_valid_ && scan_frame_ == scan_frame)
|
||||
return true;
|
||||
if (scan_frame.empty() || scan_frame == output_frame_ ||
|
||||
(!marker_frame_.empty() && scan_frame == marker_frame_))
|
||||
{
|
||||
mount_error_ = "invalid scan frame or output frame conflict";
|
||||
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), mount_error_.c_str());
|
||||
return false;
|
||||
}
|
||||
tf3::TransformStampedMsg prior_tf;
|
||||
tf3::TransformStampedMsg base_tf;
|
||||
try
|
||||
{
|
||||
prior_tf = ctx_.tf->lookupTransform(prior_frame_, scan_frame, tf3::Time());
|
||||
base_tf = ctx_.tf->lookupTransform(ctx_.robot_base_frame, scan_frame, tf3::Time());
|
||||
}
|
||||
catch (const std::exception&)
|
||||
{
|
||||
noteReason("missing mounting TF");
|
||||
return false;
|
||||
}
|
||||
const auto& rotation = base_tf.transform.rotation;
|
||||
const double norm = rotation.x * rotation.x + rotation.y * rotation.y +
|
||||
rotation.z * rotation.z + rotation.w * rotation.w;
|
||||
const auto& prior_rotation = prior_tf.transform.rotation;
|
||||
const double prior_norm = prior_rotation.x * prior_rotation.x + prior_rotation.y * prior_rotation.y +
|
||||
prior_rotation.z * prior_rotation.z + prior_rotation.w * prior_rotation.w;
|
||||
if (!std::isfinite(norm) || std::abs(norm - 1.0) > 0.01 ||
|
||||
!std::isfinite(prior_norm) || std::abs(prior_norm - 1.0) > 0.01 ||
|
||||
!std::isfinite(prior_tf.transform.translation.x) ||
|
||||
!std::isfinite(prior_tf.transform.translation.y))
|
||||
{
|
||||
mount_error_ = "invalid mounting TF";
|
||||
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), mount_error_.c_str());
|
||||
return false;
|
||||
}
|
||||
const double up_base = 1.0 - 2.0 * (rotation.x * rotation.x + rotation.y * rotation.y);
|
||||
const double up_prior = 1.0 - 2.0 * (prior_rotation.x * prior_rotation.x + prior_rotation.y * prior_rotation.y);
|
||||
const double tilt_base = std::acos(std::min(1.0, std::abs(up_base)));
|
||||
const double tilt_prior = std::acos(std::min(1.0, std::abs(up_prior)));
|
||||
if (tilt_base > kMaxTilt || tilt_prior > kMaxTilt || (up_base < 0.0) != (up_prior < 0.0))
|
||||
mount_error_ = "scan plane tilt exceeds limit or prior frame is inverted";
|
||||
else if ((std::cos(yawOf(rotation)) > 0.0) != forward_)
|
||||
mount_error_ = "lidar faces opposite entry_direction";
|
||||
if (!mount_error_.empty())
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), mount_error_.c_str());
|
||||
return false;
|
||||
}
|
||||
scan_in_prior_.x = prior_tf.transform.translation.x;
|
||||
scan_in_prior_.y = prior_tf.transform.translation.y;
|
||||
scan_in_prior_.yaw = yawOf(prior_rotation);
|
||||
flipped_ = up_prior < 0.0;
|
||||
scan_frame_ = scan_frame;
|
||||
mount_valid_ = true;
|
||||
if (debug_detect_)
|
||||
robot::log_info("[wall_reflector][debug] '%s': scan=%s prior=%s flip=%s tilt=%.4f",
|
||||
name_.c_str(), scan_frame.c_str(), prior_frame_.c_str(),
|
||||
flipped_ ? "yes" : "no", tilt_base);
|
||||
return true;
|
||||
}
|
||||
|
||||
void processScan(const robot::Time& now)
|
||||
{
|
||||
const auto scan = robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(
|
||||
*ctx_.sensors, scan_topic_, scan_cursor_);
|
||||
if (scan)
|
||||
{
|
||||
const robot::Time stamp(scan->header.stamp.sec, scan->header.stamp.nsec);
|
||||
const char* freshness_error = freshnessError(stamp, now);
|
||||
if (freshness_error != nullptr)
|
||||
noteReason(freshness_error);
|
||||
else if (have_seen_stamp_ && stamp <= last_seen_stamp_)
|
||||
noteReason("scan stamp repeated or out of order");
|
||||
else
|
||||
{
|
||||
last_seen_stamp_ = stamp;
|
||||
have_seen_stamp_ = true;
|
||||
if (ensureMount(scan->header.frame_id))
|
||||
{
|
||||
robot_line_extraction::ScanGeometry geometry;
|
||||
const double sign = flipped_ ? -1.0 : 1.0;
|
||||
geometry.angle_min = sign * scan->angle_min;
|
||||
geometry.angle_increment = sign * scan->angle_increment;
|
||||
geometry.size = scan->ranges.size();
|
||||
if (geometry.size > limits_.max_scan_rays)
|
||||
noteReason("capacity_scan_rays");
|
||||
else
|
||||
{
|
||||
if (!std::isfinite(scan->range_min) || !std::isfinite(scan->range_max) ||
|
||||
scan->range_min < 0.0 || scan->range_max <= scan->range_min)
|
||||
{
|
||||
noteReason("invalid sensor range limits");
|
||||
}
|
||||
else
|
||||
{
|
||||
auto effective_limits = limits_;
|
||||
effective_limits.min_range = std::max(limits_.min_range, static_cast<double>(scan->range_min));
|
||||
effective_limits.max_range = std::min(limits_.max_range, static_cast<double>(scan->range_max));
|
||||
if (effective_limits.min_range >= effective_limits.max_range)
|
||||
{
|
||||
noteReason("sensor and configured ranges do not overlap");
|
||||
}
|
||||
else
|
||||
{
|
||||
ranges_.assign(scan->ranges.begin(), scan->ranges.end());
|
||||
auto detection = matcher_.match(geometry, ranges_, scan->intensities,
|
||||
effective_limits, scan_in_prior_);
|
||||
if (!detection.valid)
|
||||
{
|
||||
if (detection.reason == "ambiguous")
|
||||
{
|
||||
filter_.reset();
|
||||
pending_valid_ = false;
|
||||
have_sample_stamp_ = false;
|
||||
}
|
||||
noteReason(detection.reason);
|
||||
}
|
||||
else
|
||||
{
|
||||
pending_marker_ = detection.marker;
|
||||
pending_stamp_ = stamp;
|
||||
pending_received_ = now;
|
||||
pending_valid_ = true;
|
||||
last_reason_.clear();
|
||||
reason_dirty_ = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pending_valid_)
|
||||
{
|
||||
if (!fresh(pending_stamp_, now) || secondsBetween(now, pending_received_) > pending_tf_timeout_)
|
||||
{
|
||||
pending_valid_ = false;
|
||||
noteReason("pending TF expired");
|
||||
}
|
||||
else
|
||||
resolvePending(now);
|
||||
}
|
||||
}
|
||||
|
||||
void resolvePending(const robot::Time& now)
|
||||
{
|
||||
tf3::TransformStampedMsg transform;
|
||||
try
|
||||
{
|
||||
transform = ctx_.tf->lookupTransform(ctx_.global_frame, prior_frame_,
|
||||
tf3::Time(pending_stamp_.sec, pending_stamp_.nsec));
|
||||
}
|
||||
catch (const std::exception&)
|
||||
{
|
||||
noteReason("waiting for TF at scan stamp");
|
||||
return;
|
||||
}
|
||||
const auto& rotation = transform.transform.rotation;
|
||||
const double norm = rotation.x * rotation.x + rotation.y * rotation.y +
|
||||
rotation.z * rotation.z + rotation.w * rotation.w;
|
||||
const double up = 1.0 - 2.0 * (rotation.x * rotation.x + rotation.y * rotation.y);
|
||||
if (!std::isfinite(norm) || std::abs(norm - 1.0) > 0.01 || !std::isfinite(up) ||
|
||||
std::acos(std::min(1.0, up)) > kMaxTilt)
|
||||
{
|
||||
pending_valid_ = false;
|
||||
noteReason("invalid or tilted global TF");
|
||||
return;
|
||||
}
|
||||
const double angle = yawOf(rotation);
|
||||
const double c = std::cos(angle);
|
||||
const double s = std::sin(angle);
|
||||
PoseSample sample;
|
||||
sample.x = transform.transform.translation.x + c * pending_marker_.x - s * pending_marker_.y;
|
||||
sample.y = transform.transform.translation.y + s * pending_marker_.x + c * pending_marker_.y;
|
||||
sample.yaw = wrap(angle + pending_marker_.yaw);
|
||||
sample.taken_at = now;
|
||||
if (!std::isfinite(sample.x) || !std::isfinite(sample.y) || !std::isfinite(sample.yaw))
|
||||
{
|
||||
pending_valid_ = false;
|
||||
noteReason("nonfinite transform or marker");
|
||||
return;
|
||||
}
|
||||
filter_.addSample(sample);
|
||||
filter_.pruneExpired(now);
|
||||
filter_.evaluate(now);
|
||||
last_sample_stamp_ = pending_stamp_;
|
||||
have_sample_stamp_ = true;
|
||||
pending_valid_ = false;
|
||||
last_reason_.clear();
|
||||
reason_dirty_ = false;
|
||||
}
|
||||
|
||||
bool writeTransform(const std::string& child, double x, double y, double yaw,
|
||||
const robot::Time& now)
|
||||
{
|
||||
tf3::TransformStampedMsg transform;
|
||||
transform.header.stamp = tf3::Time(now.sec, now.nsec);
|
||||
transform.header.frame_id = ctx_.global_frame;
|
||||
transform.child_frame_id = child;
|
||||
transform.transform.translation.x = x;
|
||||
transform.transform.translation.y = y;
|
||||
transform.transform.translation.z = 0.0;
|
||||
transform.transform.rotation.x = 0.0;
|
||||
transform.transform.rotation.y = 0.0;
|
||||
transform.transform.rotation.z = std::sin(yaw / 2.0);
|
||||
transform.transform.rotation.w = std::cos(yaw / 2.0);
|
||||
try
|
||||
{
|
||||
if (!ctx_.tf->setTransform(transform, "wall_reflector/" + name_, true))
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': setTransform failed for '%s'.",
|
||||
name_.c_str(), child.c_str());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': TF publish failed: %s", name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool publish(const PoseSample& marker, const robot::Time& now)
|
||||
{
|
||||
const double c = std::cos(marker.yaw);
|
||||
const double s = std::sin(marker.yaw);
|
||||
const double x = marker.x + active_profile_.offset_x * c - active_profile_.offset_y * s;
|
||||
const double y = marker.y + active_profile_.offset_x * s + active_profile_.offset_y * c;
|
||||
const double yaw = wrap(marker.yaw + active_profile_.offset_yaw + (forward_ ? kPi : 0.0));
|
||||
if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(yaw))
|
||||
{
|
||||
robot::log_error("[wall_reflector] '%s': nonfinite target pose.", name_.c_str());
|
||||
return false;
|
||||
}
|
||||
if (!marker_frame_.empty() && !writeTransform(marker_frame_, marker.x, marker.y, marker.yaw, now))
|
||||
return false;
|
||||
if (!writeTransform(output_frame_, x, y, yaw, now))
|
||||
return false;
|
||||
if (debug_state_)
|
||||
robot::log_info("[wall_reflector][debug] '%s': output TF published.", name_.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string name_;
|
||||
ActionContext ctx_;
|
||||
bool initialized_ = false;
|
||||
bool active_ = false;
|
||||
bool paused_ = false;
|
||||
bool forward_ = true;
|
||||
bool debug_state_ = true;
|
||||
bool debug_detect_ = true;
|
||||
bool debug_skip_ = true;
|
||||
std::vector<std::string> action_types_;
|
||||
std::string output_frame_;
|
||||
std::string marker_frame_;
|
||||
std::string scan_topic_;
|
||||
std::string prior_frame_;
|
||||
std::string default_profile_;
|
||||
std::string profile_param_key_;
|
||||
std::string action_id_;
|
||||
double settle_delay_ = 0.4;
|
||||
double timeout_ = 15.0;
|
||||
double max_scan_age_ = 0.3;
|
||||
double max_future_skew_ = 0.05;
|
||||
double pending_tf_timeout_ = 0.2;
|
||||
std::map<std::string, dock_pattern_detector::ReflectorPairProfile> profiles_;
|
||||
dock_pattern_detector::ReflectorPairProfile active_profile_;
|
||||
dock_pattern_detector::ReflectorPairLimits limits_;
|
||||
dock_pattern_detector::ReflectorPairMatcher matcher_;
|
||||
dock_pattern_detector::ReflectorPose2D scan_in_prior_;
|
||||
dock_pattern_detector::ReflectorPose2D pending_marker_;
|
||||
PoseSampleFilter filter_;
|
||||
robot::Time started_at_;
|
||||
robot::Time settle_start_;
|
||||
robot::Time paused_at_;
|
||||
robot::Time last_now_;
|
||||
robot::Time last_skip_log_;
|
||||
robot::Time last_seen_stamp_;
|
||||
robot::Time last_sample_stamp_;
|
||||
robot::Time pending_stamp_;
|
||||
robot::Time pending_received_;
|
||||
bool reason_dirty_ = false;
|
||||
bool have_skip_log_ = false;
|
||||
bool have_seen_stamp_ = false;
|
||||
bool have_sample_stamp_ = false;
|
||||
bool pending_valid_ = false;
|
||||
bool mount_valid_ = false;
|
||||
bool flipped_ = false;
|
||||
std::string scan_frame_;
|
||||
std::string mount_error_;
|
||||
std::string last_reason_;
|
||||
uint64_t scan_cursor_ = 0;
|
||||
std::vector<double> ranges_;
|
||||
};
|
||||
} // namespace action_core
|
||||
|
||||
ACTION_CORE_EXPORT_HANDLER(action_core::WallReflectorDetectionActionHandler::create,
|
||||
WallReflectorDetectionActionHandler)
|
||||
Reference in New Issue
Block a user