Files
trolley_detection_action/plugins/trolley_detection_action_handler.cpp

945 lines
38 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* trolley_detection_action — handler dò xe hàng 4 chân từ LiDAR: scan thô -> tư thế xe -> frame
* đích ổn định cho robot chui gầm.
*
* Author: DuongTD
*********************************************************************/
#include <action_core/action_handler.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <action_core/action_abi.h>
#include <yaml-cpp/yaml.h>
#include <robot/robot.h>
#include <robot_sensor_msgs/LaserScan.h>
#include <tf3/buffer_core.h>
#include <action_core/pose_sample_filter.h>
#include <dock_pattern_detector/leg_pattern_matcher.h>
#include <robot_sensor_ports/sensor_reader.h>
#include <robot_sensor_ports/sensor_types.h>
// ================================================================================================
// NGUỒN GỐC: phần kiểm lúc boot, chọn profile, update/pause/resume/cancel, bộ lọc, đọc scan theo
// cursor, giữ phép dò chờ TF, noteReason/failOnTimeout/publish được CHÉP từ
// `dock_pattern_action/plugins/dock_pattern_action_handler.cpp` (commit 5bbcf37). Sửa lỗi ở phần
// chung bên nào thì xem lại bên kia — hai handler lệch nhau âm thầm là thứ khó bắt nhất.
// ================================================================================================
namespace action_core
{
namespace
{
constexpr double kDefaultSettleDelay = 0.4; // [s]
constexpr double kDefaultTimeout = 15.0; // [s]
constexpr double kDefaultMinRange = 0.10; // [m]
constexpr double kDefaultMaxRange = 3.0; // [m]
constexpr double kDefaultRangeSigma = 0.01; // [m]
/// Chu kỳ in lý do chưa dò ra / kết quả khớp. Control loop ~30 Hz; log mỗi cycle sẽ ngập log và làm
/// chậm chính vòng điều khiển. 1 Hz đủ để đọc xem đang hỏng ở cổng nào.
constexpr double kReasonLogPeriod = 1.0; // [s]
/// Mặt phẳng quét được nghiêng tối đa bao nhiêu so với mặt sàn của `prior_frame`. Bộ dò coi scan là
/// 2D: nghiêng t làm cự ly ngang sai r·(1 − cos t) — 5° ở 2.3 m là 9 mm, đã sát D6 (±1.5 cm). Quá
/// ngưỡng nghĩa là URDF sai hoặc lidar gắn lệch; dừng thay vì ghi một đích lệch.
constexpr double kMaxScanTilt = 0.0873; // [rad] 5°
/// @brief Hướng trục x của frame (atan2(R10, R00)). Đúng cả khi frame lộn ngược: lật quanh trục x
/// giữ nguyên trục x.
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));
}
/// @brief R22 của phép quay: trục z của frame chiếu lên trục z của frame cha. Âm = lộn ngược.
double upAxisZ(const tf3::QuaternionMsg& q)
{
return 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
}
double wrapAngle(double a)
{
return std::atan2(std::sin(a), std::cos(a));
}
/// @brief Robot chui gầm bằng đầu nào — quyết heading của goal.
enum class EntryDirection
{
kForward, ///< tiến vào: lidar trước dò, heading goal trỏ VÀO xe
kBackward ///< lùi vào: lidar sau dò, heading goal trỏ RA cạnh vào
};
const char* toString(EntryDirection d)
{
return d == EntryDirection::kForward ? "forward" : "backward";
}
} // namespace
/**
* @class TrolleyDetectionActionHandler
* @brief Dò xe hàng 4 chân trong scan LiDAR thô, lọc, ghi ra một frame đích ổn định.
*
* Cùng hợp đồng đầu ra với `DockPatternActionHandler` và `FrameSamplerActionHandler`: ghi một TF
* TĨNH vào `output_frame`, nên chặng `move_to` sau nó, `DockPlanner` và `mission_adapters` không
* đổi dòng nào. Khác ở bộ dò: `LegPatternMatcher` tìm 4 chân thay vì một biên dạng.
*
* ## Đích ghi ra
*
* Vị trí = tâm hình chữ nhật tâm chân + offset của profile. Heading theo `entry_direction`:
* - `forward`: pháp tuyến cạnh vào + π — trỏ VÀO xe, robot tiến thẳng vào.
* - `backward`: pháp tuyến cạnh vào — trỏ RA cạnh vào, robot lùi thẳng vào.
*
* Lidar của `scan_topic` phải nhìn đúng hướng với `entry_direction` (kiểm ở scan đầu mỗi lượt).
* Khai lệch hai khoá là goal ngược 180°, robot chui sai đầu xe — nên lệch thì `kFailed` ngay.
*
* ## Lidar gắn lộn ngược
*
* Tự suy từ TF `prior_frame` <- frame scan, không có khoá cấu hình: trục z của frame scan chỉ xuống
* (hook_150: roll π) thì tia ở góc θ trong frame lidar nằm ở góc −θ khi nhìn từ trên xuống. Handler
* đảo dấu `angle_min`/`angle_increment` trước khi dò, nên matcher làm việc trong frame "đứng thẳng"
* cùng gốc, cùng trục x với lidar. Driver không lật dữ liệu; nếu sau này driver lật thì URDF phải bỏ
* roll π — không thì costmap cũng sai — nên TF luôn là nguồn đúng. Mặt quét nghiêng quá
* `kMaxScanTilt` thì `kFailed`.
*
* ## Cấu hình
*
* - `action_types`, `output_frame`, `scan_topic`, `settle_delay`, `timeout`, `default_profile`,
* `profile_param_key` — cùng nghĩa với `dock_pattern`.
* - `prior_frame` [string] frame của `prior_*` và `search_fov` (mặc định `base_link`)
* - `entry_direction` [string] `forward` / `backward`
* - `min_range`, `max_range` [m], `range_sigma` [m]
* - `zero_range_is_no_echo` [bool] driver trả range 0 cho tia không phản hồi (mặc định false,
* xem @ref dock_pattern_detector::ScanLimits)
* - `debug/detect` [bool] log lý do chưa dò ra, kết quả khớp, tóm tắt lúc start
* - `profiles/<tên>/...` khoá của `LegProfile`
* - cộng toàn bộ khoá của @ref PoseSampleFilterConfig
*/
class TrolleyDetectionActionHandler final : public ActionHandler
{
public:
TrolleyDetectionActionHandler() = default;
static ActionHandler::Ptr create()
{
return std::make_shared<TrolleyDetectionActionHandler>();
}
bool configure(const std::string& name, const ActionContext& ctx,
robot::NodeHandle& nh) override
{
name_ = name;
ctx_ = ctx;
if (ctx_.tf == nullptr)
{
robot::log_error("[trolley_detection] '%s': needs a TF buffer but the context has none.",
name_.c_str());
return false;
}
if (ctx_.sensors == nullptr)
{
// Handler này đọc scan THÔ. Không có kho thì nó vô nghĩa — từ chối lúc nạp để lỗi lộ khi
// khởi động, không phải khi order đầu tiên tới giữa ca.
robot::log_error("[trolley_detection] '%s': needs the shared sensor store but the context "
"has none. Declare sensor_store/sensors in the runtime config.",
name_.c_str());
return false;
}
nh.param("action_types", action_types_, std::vector<std::string>{});
nh.param("output_frame", output_frame_, std::string());
nh.param("scan_topic", scan_topic_, std::string());
nh.param("settle_delay", settle_delay_, kDefaultSettleDelay);
nh.param("timeout", timeout_, kDefaultTimeout);
nh.param("default_profile", default_profile_, std::string());
nh.param("profile_param_key", profile_param_key_, std::string("trolley_profile"));
nh.param("prior_frame", prior_frame_, std::string("base_link"));
nh.param("min_range", limits_.min_range, kDefaultMinRange);
nh.param("max_range", limits_.max_range, kDefaultMaxRange);
nh.param("range_sigma", limits_.range_sigma, kDefaultRangeSigma);
nh.param("zero_range_is_no_echo", limits_.zero_range_is_no_echo, false);
std::string direction = "forward";
nh.param("entry_direction", direction, direction);
robot::NodeHandle debug_nh(nh, "debug");
debug_nh.param("detect", debug_detect_, true);
if (action_types_.empty())
{
robot::log_error("[trolley_detection] '%s': action_types is empty — never called.",
name_.c_str());
return false;
}
if (output_frame_.empty())
{
robot::log_error("[trolley_detection] '%s': output_frame is empty — the result would go "
"nowhere.",
name_.c_str());
return false;
}
if (scan_topic_.empty())
{
robot::log_error("[trolley_detection] '%s': scan_topic is empty.", name_.c_str());
return false;
}
if (prior_frame_.empty())
{
robot::log_error("[trolley_detection] '%s': prior_frame is empty.", name_.c_str());
return false;
}
if (direction == "forward")
{
entry_direction_ = EntryDirection::kForward;
}
else if (direction == "backward")
{
entry_direction_ = EntryDirection::kBackward;
}
else
{
robot::log_error("[trolley_detection] '%s': entry_direction '%s' is not 'forward' or "
"'backward'.",
name_.c_str(), direction.c_str());
return false;
}
// Gõ sai tên topic là lỗi phổ biến nhất, và triệu chứng của nó GIỐNG HỆT cảm biến chết: dò mãi
// không ra. Bắt lúc boot và in ra danh sách topic có thật.
if (!robot_sensor_ports::has<robot_sensor_msgs::LaserScan>(*ctx_.sensors, scan_topic_))
{
std::string known;
for (const robot_sensor_ports::SensorInfo& info : ctx_.sensors->inventory())
{
known += (known.empty() ? "" : ", ") + info.topic + " (" + info.data_type + ")";
}
robot::log_error("[trolley_detection] '%s': scan_topic '%s' is not a LaserScan in the "
"sensor store. Declared topics: %s",
name_.c_str(), scan_topic_.c_str(),
known.empty() ? "(none)" : known.c_str());
return false;
}
if (!std::isfinite(settle_delay_) || settle_delay_ < 0.0)
{
robot::log_error("[trolley_detection] '%s': settle_delay=%.3f must be finite and >= 0.",
name_.c_str(), settle_delay_);
return false;
}
if (!std::isfinite(limits_.min_range) || !std::isfinite(limits_.max_range) ||
limits_.min_range < 0.0 || limits_.max_range <= limits_.min_range)
{
robot::log_error("[trolley_detection] '%s': need 0 <= min_range < max_range [m] (got %.3f, "
"%.3f).",
name_.c_str(), limits_.min_range, limits_.max_range);
return false;
}
if (!std::isfinite(limits_.range_sigma) || limits_.range_sigma <= 0.0)
{
robot::log_error("[trolley_detection] '%s': range_sigma=%.4f must be finite and > 0 [m].",
name_.c_str(), limits_.range_sigma);
return false;
}
if (!loadProfiles(nh) || !loadFilter(nh))
{
return false;
}
// Dòng tóm tắt lúc boot: chỗ duy nhất xác nhận được giá trị đã nạp mà không mở YAML trên robot.
robot::log_info("[trolley_detection] '%s': %zu profile(s), default '%s', scan '%s', "
"entry_direction %s, prior_frame '%s', range [%.2f, %.2f] m, sigma %.3f m, "
"zero range %s, debug/detect %s.",
name_.c_str(), profiles_.size(), default_profile_.c_str(),
scan_topic_.c_str(), toString(entry_direction_), prior_frame_.c_str(),
limits_.min_range, limits_.max_range, limits_.range_sigma,
limits_.zero_range_is_no_echo ? "= no echo" : "= blocked",
debug_detect_ ? "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
{
started_at_ = now;
paused_ = false;
action_id_ = action.actionId;
scan_cursor_ = 0;
pending_valid_ = false;
last_reason_.clear();
have_reason_log_ = false;
have_match_log_ = false;
detections_ = 0;
tape_reported_ = false;
prior_tf_valid_ = false;
prior_tf_frame_.clear();
scan_flipped_ = false;
mount_error_.clear();
std::string profile_name = default_profile_;
const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(),
[this](const robot_protocol_msgs::ActionParameter& p) {
return p.key == profile_param_key_;
});
if (it != action.actionParameters.end() && !it->value.empty())
{
profile_name = it->value;
}
const auto found = profiles_.find(profile_name);
if (found == profiles_.end())
{
// KHÔNG âm thầm rơi về default: dùng nhầm hình học là chui vào sai chỗ.
std::string known;
for (const auto& entry : profiles_)
{
known += (known.empty() ? "" : ", ") + entry.first;
}
robot::log_error("[trolley_detection] '%s': action '%s' asked for profile '%s' which does "
"not exist. Known profiles: %s",
name_.c_str(), action.actionId.c_str(), profile_name.c_str(),
known.empty() ? "(none)" : known.c_str());
return false;
}
std::string error;
if (!matcher_.configure(found->second, error))
{
robot::log_error("[trolley_detection] '%s': profile '%s' is invalid: %s", name_.c_str(),
profile_name.c_str(), error.c_str());
return false;
}
profile_name_ = profile_name;
filter_.reset();
filter_.setLabels(scan_topic_, ctx_.global_frame);
if (debug_detect_)
{
const dock_pattern_detector::LegProfile& p = found->second;
robot::log_info("[trolley_detection][debug] '%s': detecting profile '%s' (cart %.3f x %.3f m, "
"leg %s %.3f m, min_legs %d, attached legs %s, tape %s/%s, bloom %.3f rad, "
"plateau %.3f, range bias sigma %.3f m, all max std %.3f m, offset_yaw %.3f, prior %s in '%s') on '%s', entry "
"%s -> '%s'.",
name_.c_str(), profile_name.c_str(), p.cart_opening, p.cart_depth,
dock_pattern_detector::toString(p.leg_shape), p.leg_width, p.min_legs,
p.accept_attached_legs ? "on" : "off",
p.tape_enabled ? "on" : "off", dock_pattern_detector::toString(p.tape_legs),
p.tape_bloom_max_angle, p.tape_plateau_min_fraction, p.tape_range_bias_sigma,
p.tape_range_bias_all_max_std, p.offset_yaw,
p.has_prior ? "on" : "off", prior_frame_.c_str(), scan_topic_.c_str(),
toString(entry_direction_), output_frame_.c_str());
}
return true;
}
ActionTick update(const robot::Time& now) override
{
ActionTick tick;
const double elapsed = (now - started_at_).toSec(); // [s]
// Robot vừa dừng vẫn còn dao động cơ khí; scan lúc này mang theo dao động đó.
if (elapsed >= settle_delay_)
{
processNewScan(now);
}
if (!mount_error_.empty())
{
tick.status = ActionStatus::kFailed;
tick.message = "action '" + action_id_ + "': " + mount_error_;
return tick;
}
if (filter_.holdSatisfied(now))
{
if (!publish(filter_.holdPose(), now))
{
tick.status = ActionStatus::kFailed;
tick.message = "action '" + action_id_ + "': could not publish '" + output_frame_ + "'";
return tick;
}
tick.status = ActionStatus::kSucceeded;
tick.message = "action '" + action_id_ + "': '" + output_frame_ + "' from " +
std::to_string(filter_.windowSize()) + " detection(s) of profile '" +
profile_name_ + "' after " + formatSeconds(elapsed) + " s";
return tick;
}
if (timeout_ > 0.0 && elapsed >= timeout_)
{
return failOnTimeout(elapsed);
}
tick.status = ActionStatus::kRunning;
return tick;
}
/// @brief Tạm dừng: ghi mốc để resume() dịch started_at_ — quãng đứng không tính vào timeout.
void pause(const robot::Time& now) override
{
if (!paused_)
{
paused_ = true;
paused_at_ = now;
}
}
void resume(const robot::Time& now) override
{
if (paused_)
{
started_at_ += (now - paused_at_);
paused_ = false;
}
}
void cancel() override
{
filter_.reset();
scan_cursor_ = 0;
pending_valid_ = false;
}
private:
// ==============================================================================================
// Nạp cấu hình
// ==============================================================================================
bool loadProfiles(robot::NodeHandle& nh)
{
YAML::Node node;
if (!nh.getParam("profiles", node) || !node.IsMap() || node.size() == 0)
{
robot::log_error("[trolley_detection] '%s': no 'profiles' map — nothing to detect.",
name_.c_str());
return false;
}
profiles_.clear();
for (const auto& entry : node)
{
const std::string profile_name = entry.first.as<std::string>();
robot::NodeHandle p_nh(nh, "profiles/" + profile_name);
dock_pattern_detector::LegProfile profile;
std::string error;
nh_param(p_nh, "cart_opening", profile.cart_opening);
nh_param(p_nh, "cart_depth", profile.cart_depth);
nh_param(p_nh, "cart_dim_tolerance", profile.cart_dim_tolerance);
std::string shape_name = dock_pattern_detector::toString(profile.leg_shape);
nh_param(p_nh, "leg_shape", shape_name);
if (!dock_pattern_detector::legShapeFromString(shape_name, profile.leg_shape, error))
{
robot::log_error("[trolley_detection] '%s': profile '%s': %s", name_.c_str(),
profile_name.c_str(), error.c_str());
return false;
}
nh_param(p_nh, "leg_width", profile.leg_width);
nh_param(p_nh, "leg_width_tolerance", profile.leg_width_tolerance);
nh_param(p_nh, "leg_depth", profile.leg_depth);
nh_param(p_nh, "leg_yaw_offset", profile.leg_yaw_offset);
int min_leg_points = static_cast<int>(profile.min_leg_points);
nh_param(p_nh, "min_leg_points", min_leg_points);
profile.min_leg_points = static_cast<std::size_t>(std::max(0, min_leg_points));
nh_param(p_nh, "shadow_min_angle", profile.shadow_min_angle);
nh_param(p_nh, "tape_bloom_max_angle", profile.tape_bloom_max_angle);
nh_param(p_nh, "tape_plateau_min_fraction", profile.tape_plateau_min_fraction);
nh_param(p_nh, "tape_range_bias_sigma", profile.tape_range_bias_sigma);
nh_param(p_nh, "tape_range_bias_all_max_std", profile.tape_range_bias_all_max_std);
nh_param(p_nh, "leg_cluster_gap", profile.leg_cluster_gap);
nh_param(p_nh, "leg_min_depth_gap", profile.leg_min_depth_gap);
nh_param(p_nh, "accept_attached_legs", profile.accept_attached_legs);
nh_param(p_nh, "min_legs", profile.min_legs);
nh_param(p_nh, "leg_assoc_radius", profile.leg_assoc_radius);
nh_param(p_nh, "max_interior_points", profile.max_interior_points);
nh_param(p_nh, "interior_margin", profile.interior_margin);
nh_param(p_nh, "ambiguity_margin", profile.ambiguity_margin);
nh_param(p_nh, "min_confidence", profile.min_confidence);
nh_param(p_nh, "tape_enabled", profile.tape_enabled);
std::string tape_legs_name = dock_pattern_detector::toString(profile.tape_legs);
nh_param(p_nh, "tape_legs", tape_legs_name);
if (!dock_pattern_detector::tapeLegsFromString(tape_legs_name, profile.tape_legs, error))
{
robot::log_error("[trolley_detection] '%s': profile '%s': %s", name_.c_str(),
profile_name.c_str(), error.c_str());
return false;
}
nh_param(p_nh, "tape_min_intensity", profile.tape_min_intensity);
int tape_min_points = static_cast<int>(profile.tape_min_points);
nh_param(p_nh, "tape_min_points", tape_min_points);
profile.tape_min_points = static_cast<std::size_t>(std::max(0, tape_min_points));
nh_param(p_nh, "has_prior", profile.has_prior);
nh_param(p_nh, "prior_x", profile.prior_x);
nh_param(p_nh, "prior_y", profile.prior_y);
nh_param(p_nh, "prior_yaw", profile.prior_yaw);
nh_param(p_nh, "prior_yaw_tolerance", profile.prior_yaw_tolerance);
nh_param(p_nh, "search_radius", profile.search_radius);
nh_param(p_nh, "search_fov", profile.search_fov);
nh_param(p_nh, "offset_x", profile.offset_x);
nh_param(p_nh, "offset_y", profile.offset_y);
nh_param(p_nh, "offset_yaw", profile.offset_yaw);
// Kiểm MỌI profile lúc boot, không chỉ profile mặc định. Gõ sai ở profile thứ năm mà bốn giờ
// chiều mới lộ là kiểu lỗi tệ nhất.
if (!profile.validate(error))
{
robot::log_error("[trolley_detection] '%s': profile '%s': %s", name_.c_str(),
profile_name.c_str(), error.c_str());
return false;
}
profiles_[profile_name] = profile;
}
if (default_profile_.empty())
{
default_profile_ = profiles_.begin()->first;
}
if (profiles_.find(default_profile_) == profiles_.end())
{
robot::log_error("[trolley_detection] '%s': default_profile '%s' is not among the declared "
"profiles.",
name_.c_str(), default_profile_.c_str());
return false;
}
return true;
}
bool loadFilter(robot::NodeHandle& nh)
{
PoseSampleFilterConfig config;
nh.param("filter_enabled", 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 (!filter_.configure(config, name_))
{
return false;
}
if (config.enabled && timeout_ > 0.0 &&
timeout_ <= settle_delay_ + config.sample_window + config.hold_time)
{
robot::log_error("[trolley_detection] '%s': timeout=%.3f s <= "
"settle_delay+sample_window+hold_time=%.3f s; the action would always fail.",
name_.c_str(), timeout_,
settle_delay_ + config.sample_window + config.hold_time);
return false;
}
return true;
}
/// @brief `robot::NodeHandle::param` nhưng không cần biến tạm ở chỗ gọi.
template <typename T>
static void nh_param(robot::NodeHandle& nh, const std::string& key, T& value)
{
nh.param(key, value, value);
}
// ==============================================================================================
// Vòng dò
// ==============================================================================================
/**
* @brief Pose 2D của frame scan trong `prior_frame`, tra một lần mỗi lượt rồi cache.
*
* Lidar gắn cứng vào thân robot nên phép biến đổi này không đổi trong một lượt; tra lại mỗi scan
* chỉ tốn công. Đồng thời suy lidar có lộn ngược không, kiểm mặt quét nằm ngang và hướng lidar
* khớp `entry_direction`.
*
* @return false nếu chưa có TF (thử lại scan sau) hoặc cách gắn lidar không dùng được (đã ghi
* `mount_error_`).
*/
bool ensurePriorTransform(const std::string& scan_frame, const robot::Time& now)
{
if (prior_tf_valid_ && prior_tf_frame_ == scan_frame)
{
return true;
}
tf3::TransformStampedMsg tf;
try
{
tf = ctx_.tf->lookupTransform(prior_frame_, scan_frame, tf3::Time());
}
catch (const std::exception& ex)
{
noteReason(now, "no transform '" + prior_frame_ + "' <- '" + scan_frame + "' yet: " +
ex.what());
return false;
}
// Yaw = hướng trục x của lidar, giống nhau ở frame lidar và frame "đứng thẳng" của nó, nên
// `scan_in_prior_` dùng được cho cả hai.
const double up = upAxisZ(tf.transform.rotation);
const double tilt = std::acos(std::min(1.0, std::fabs(up))); // [rad]
scan_in_prior_.x = tf.transform.translation.x;
scan_in_prior_.y = tf.transform.translation.y;
scan_in_prior_.yaw = yawOf(tf.transform.rotation);
scan_flipped_ = up < 0.0;
prior_tf_frame_ = scan_frame;
prior_tf_valid_ = true;
if (debug_detect_)
{
robot::log_info("[trolley_detection][debug] '%s': scan frame '%s' in '%s': (%.3f, %.3f) yaw "
"%.3f rad, tilt %.3f rad%s.",
name_.c_str(), scan_frame.c_str(), prior_frame_.c_str(), scan_in_prior_.x,
scan_in_prior_.y, scan_in_prior_.yaw, tilt,
scan_flipped_ ? ", mounted upside down: bearings mirrored" : "");
}
char buffer[256];
if (tilt > kMaxScanTilt)
{
std::snprintf(buffer, sizeof(buffer),
"scan plane of '%s' (frame '%s') is tilted %.3f rad from '%s' (limit %.3f); "
"the leg model is 2D, check the lidar mount in the URDF",
scan_topic_.c_str(), scan_frame.c_str(), tilt, prior_frame_.c_str(),
kMaxScanTilt);
mount_error_ = buffer;
robot::log_error("[trolley_detection] '%s': %s.", name_.c_str(), buffer);
return false;
}
// Lidar nhìn về trước (cos > 0) thì chỉ dò được xe phía trước: phải là `forward`, và ngược lại.
// Lidar góc của T800 (±π/4, ±3π/4) vẫn qua đúng phép kiểm này.
const bool looks_forward = std::cos(scan_in_prior_.yaw) > 0.0;
const bool wants_forward = entry_direction_ == EntryDirection::kForward;
if (looks_forward != wants_forward)
{
std::snprintf(buffer, sizeof(buffer),
"entry_direction %s but '%s' (frame '%s') faces %s in '%s' (yaw %.2f rad); "
"the goal heading would be reversed",
toString(entry_direction_), scan_topic_.c_str(), scan_frame.c_str(),
looks_forward ? "forward" : "backward", prior_frame_.c_str(),
scan_in_prior_.yaw);
mount_error_ = buffer;
robot::log_error("[trolley_detection] '%s': %s.", name_.c_str(), buffer);
return false;
}
return true;
}
/**
* @brief Lấy scan MỚI (nếu có), dò, quy sang global frame, đẩy vào bộ lọc.
*
* Chỉ chạy khi cursor cho biết có scan mới: dò lại trên đúng scan cũ là đốt CPU của vòng điều
* khiển và đếm hai lần cùng một phép đo.
*/
void processNewScan(const robot::Time& now)
{
// Trước hết giải quyết phép dò còn treo vì TF chưa kịp. Không dò lại: hình đã khớp rồi, chỉ
// thiếu phép quy đổi.
if (pending_valid_ && resolvePending(now))
{
pending_valid_ = false;
}
auto scan = robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(*ctx_.sensors, scan_topic_,
scan_cursor_);
if (!scan)
{
return;
}
if (!ensurePriorTransform(scan->header.frame_id, now))
{
return;
}
// Lidar lộn ngược: tia ở góc θ trong frame lidar nằm ở góc −θ trong frame đứng thẳng. Từ đây
// matcher và resolvePending() làm việc trong frame đứng thẳng đó; matcher nhận được bước góc âm.
const double bearing_sign = scan_flipped_ ? -1.0 : 1.0;
robot_line_extraction::ScanGeometry geometry;
geometry.angle_min = bearing_sign * scan->angle_min;
geometry.angle_increment = bearing_sign * scan->angle_increment;
geometry.size = scan->ranges.size();
// `ranges` là float trong message, double trong lõi. Đổi một lần ở đây, dùng lại buffer để
// không cấp phát mỗi scan. `intensities` đi thẳng: rỗng khi driver không gửi cường độ, và
// matcher tự nói ra điều đó nếu profile đang đòi dải.
ranges_.assign(scan->ranges.begin(), scan->ranges.end());
const dock_pattern_detector::LegDetection detection =
matcher_.match(geometry, ranges_, scan->intensities, limits_, scan_in_prior_);
if (!detection.valid)
{
noteReason(now, detection.reason);
return;
}
pending_ = detection;
pending_frame_ = scan->header.frame_id;
logMatch(now, detection); // sau khi gán pending_frame_: dòng log in tên frame đó
pending_stamp_ = tf3::Time(scan->header.stamp.sec, scan->header.stamp.nsec);
pending_valid_ = true;
last_reason_.clear();
if (resolvePending(now))
{
pending_valid_ = false;
}
}
/**
* @brief Quy phép dò đang treo sang global frame và đẩy vào bộ lọc.
*
* @return false nếu TF chưa có ở stamp đó — khi ấy phép dò **được giữ lại** để tick sau thử tiếp,
* và KHÔNG rơi về transform mới nhất (trộn hai thời điểm vào một phép đo).
*/
bool resolvePending(const robot::Time& now)
{
tf3::TransformStampedMsg sensor_to_global;
try
{
sensor_to_global =
ctx_.tf->lookupTransform(ctx_.global_frame, pending_frame_, pending_stamp_);
}
catch (const std::exception& ex)
{
noteReason(now, std::string("no transform at the scan stamp yet: ") + ex.what());
return false;
}
// `pending_` nằm trong frame đứng thẳng của lidar (xem processNewScan). Trục x của frame đó là
// trục x của lidar, nên yawOf() của TF lidar cũng là yaw của frame đứng thẳng — lật hay không.
const double base_yaw = yawOf(sensor_to_global.transform.rotation);
const double c = std::cos(base_yaw);
const double s = std::sin(base_yaw);
// Heading của goal theo cách robot chui: tiến vào thì trỏ VÀO xe (ngược pháp tuyến cạnh vào),
// lùi vào thì trỏ RA cạnh vào (đúng pháp tuyến).
const double heading =
pending_.yaw + (entry_direction_ == EntryDirection::kForward ? M_PI : 0.0);
PoseSample sample;
sample.x = sensor_to_global.transform.translation.x + c * pending_.x - s * pending_.y;
sample.y = sensor_to_global.transform.translation.y + s * pending_.x + c * pending_.y;
sample.yaw = wrapAngle(base_yaw + heading);
sample.taken_at = now;
++detections_;
last_reason_.clear();
filter_.addSample(sample);
filter_.pruneExpired(now);
filter_.evaluate(now);
return true;
}
/// @brief Ghi lại vì sao chưa dò ra, in tối đa một dòng mỗi `kReasonLogPeriod` giây.
void noteReason(const robot::Time& now, const std::string& reason)
{
last_reason_ = reason;
if (!debug_detect_ || (have_reason_log_ && (now - last_reason_log_).toSec() < kReasonLogPeriod))
{
return;
}
last_reason_log_ = now;
have_reason_log_ = true;
robot::log_info("[trolley_detection][debug] '%s': %s", name_.c_str(), reason.c_str());
}
/// @brief Kết quả khớp, tối đa 1 Hz. Kích thước đo lệch profile là dấu hiệu sớm của khai sai số.
void logMatch(const robot::Time& now, const dock_pattern_detector::LegDetection& d)
{
if (d.legs_seen > 0 && matcher_.profile().tape_enabled && !tape_reported_ && debug_detect_)
{
// Một dòng mỗi lượt: số người lắp xe cần để đặt ngưỡng cường độ.
tape_reported_ = true;
robot::log_info("[trolley_detection][debug] '%s': bright rays per leg (entry-left, "
"entry-right, far-left, far-right): %zu %zu %zu %zu (tape_min_intensity "
"%.0f).",
name_.c_str(), d.tape_bright_rays[0], d.tape_bright_rays[1],
d.tape_bright_rays[2], d.tape_bright_rays[3],
matcher_.profile().tape_min_intensity);
}
if (!debug_detect_ || (have_match_log_ && (now - last_match_log_).toSec() < kReasonLogPeriod))
{
return;
}
last_match_log_ = now;
have_match_log_ = true;
if (d.tape_range_bias_estimated)
{
robot::log_info("[trolley_detection][debug] '%s': cart at (%.3f, %.3f) yaw %.3f in '%s'%s, "
"legs seen %d (partial %d, attached %d, occluded %d, out of view %d), "
"measured %.3f x %.3f m, fit rms %.4f m, tape range bias %.3f m (std %.4f m; 0 = unavailable), confidence "
"%.2f.",
name_.c_str(), d.center_x, d.center_y, d.center_yaw, pending_frame_.c_str(),
scan_flipped_ ? " (upright view)" : "", d.legs_seen, d.legs_partial,
d.legs_attached, d.legs_occluded, d.legs_out_of_view, d.measured_opening,
d.measured_depth, d.fit_rms, d.tape_range_bias, d.tape_range_bias_std, d.confidence);
}
else
{
robot::log_info("[trolley_detection][debug] '%s': cart at (%.3f, %.3f) yaw %.3f in '%s'%s, "
"legs seen %d (partial %d, attached %d, occluded %d, out of view %d), "
"measured %.3f x %.3f m, fit rms %.4f m, bias off (std %.4f m; 0 = unavailable), confidence %.2f.",
name_.c_str(), d.center_x, d.center_y, d.center_yaw, pending_frame_.c_str(),
scan_flipped_ ? " (upright view)" : "", d.legs_seen, d.legs_partial,
d.legs_attached, d.legs_occluded, d.legs_out_of_view, d.measured_opening,
d.measured_depth, d.fit_rms, d.tape_range_bias_std, d.confidence);
}
}
ActionTick failOnTimeout(double elapsed)
{
ActionTick tick;
tick.status = ActionStatus::kFailed;
if (detections_ == 0)
{
// Chưa lần nào khớp được. `last_reason_` từ matcher nói rõ hỏng ở CỔNG NÀO.
tick.message = "action '" + action_id_ + "': no '" + profile_name_ + "' trolley on '" +
scan_topic_ + "' in " + formatSeconds(elapsed) + " s" +
(last_reason_.empty() ? "" : " — " + last_reason_);
return tick;
}
if (!filter_.hasBest())
{
// Có khớp, nhưng chưa cửa sổ nào đủ `min_samples`: dò được quá thưa so với `sample_window`.
tick.message = "action '" + action_id_ + "': detected the trolley only " +
std::to_string(detections_) + " time(s) in " + formatSeconds(elapsed) +
" s, need " + std::to_string(filter_.config().min_samples) + " within any " +
formatSeconds(filter_.config().sample_window) + " s window";
return tick;
}
robot::log_error("[trolley_detection] '%s': no window converged in %.2f s. Best window (%.0f%% "
"of the tolerance): %s\n",
name_.c_str(), elapsed, filter_.bestScore() * 100.0,
filter_.bestDescription().c_str());
tick.message = "action '" + action_id_ + "': detections unstable (best spread xy=" +
std::to_string(filter_.bestSpreadXy()) +
" m, yaw=" + std::to_string(filter_.bestSpreadYaw()) + " rad in " +
formatSeconds(elapsed) + " s)";
return tick;
}
static std::string formatSeconds(double seconds)
{
char buffer[32];
std::snprintf(buffer, sizeof(buffer), "%.2f", seconds);
return buffer;
}
bool publish(const PoseSample& s, const robot::Time& now)
{
tf3::TransformStampedMsg out;
out.header.stamp = tf3::Time(now.sec, now.nsec);
out.header.frame_id = ctx_.global_frame;
out.child_frame_id = output_frame_;
out.transform.translation.x = s.x;
out.transform.translation.y = s.y;
out.transform.translation.z = 0.0;
out.transform.rotation.x = 0.0;
out.transform.rotation.y = 0.0;
out.transform.rotation.z = std::sin(s.yaw * 0.5);
out.transform.rotation.w = std::cos(s.yaw * 0.5);
// static = true: kết quả đã chốt, không có hạn dùng. Chặng sau tra lúc nào cũng thấy, kể cả khi
// cảm biến đã mất dấu vì robot đã ở dưới gầm xe.
return ctx_.tf->setTransform(out, "trolley_detection/" + name_, /*is_static=*/true);
}
std::string name_;
ActionContext ctx_;
std::vector<std::string> action_types_;
std::string output_frame_;
std::string scan_topic_;
std::string prior_frame_ = "base_link";
EntryDirection entry_direction_ = EntryDirection::kForward;
double settle_delay_ = kDefaultSettleDelay;
double timeout_ = kDefaultTimeout;
dock_pattern_detector::ScanLimits limits_;
bool debug_detect_ = true;
std::string default_profile_;
std::string profile_param_key_ = "trolley_profile";
std::map<std::string, dock_pattern_detector::LegProfile> profiles_;
dock_pattern_detector::LegPatternMatcher matcher_;
PoseSampleFilter filter_;
robot::Time started_at_;
robot::Time paused_at_; ///< Mốc pause() gần nhất; chỉ có nghĩa khi paused_.
bool paused_ = false;
std::string action_id_;
std::string profile_name_;
/// Pose của frame scan trong prior_frame, cache cho cả lượt.
dock_pattern_detector::Pose2D scan_in_prior_;
std::string prior_tf_frame_;
bool prior_tf_valid_ = false;
/// Trục z của frame scan chỉ xuống: góc tia phải đảo dấu trước khi dò. Suy từ TF, cùng lúc với
/// scan_in_prior_.
bool scan_flipped_ = false;
/// Rỗng = ổn; khác rỗng = lidar nhìn ngược `entry_direction` hoặc mặt quét nghiêng, lượt này phải
/// fail.
std::string mount_error_;
/// Con trỏ đọc của kho cảm biến. Đây là thứ phân biệt "scan mới" với "cùng scan đọc lại".
uint64_t scan_cursor_ = 0;
/// Số lần khớp được cả lượt. Phân biệt "chưa lần nào khớp" với "khớp nhưng quá thưa".
std::size_t detections_ = 0;
/// Phép dò đã khớp nhưng chưa quy được sang global frame vì TF chưa tới stamp đó.
dock_pattern_detector::LegDetection pending_;
std::string pending_frame_;
tf3::Time pending_stamp_;
bool pending_valid_ = false;
bool tape_reported_ = false;
std::string last_reason_;
robot::Time last_reason_log_;
bool have_reason_log_ = false;
robot::Time last_match_log_;
bool have_match_log_ = false;
/// Buffer dùng lại: chạy mỗi khi có scan mới.
std::vector<double> ranges_;
};
} // namespace action_core
ACTION_CORE_EXPORT_HANDLER(action_core::TrolleyDetectionActionHandler::create,
TrolleyDetectionActionHandler)