Run the dock detector as an action, from raw scan to goal frame
This is the layer that turns the geometry into something the robot actually runs. It pulls a raw scan from the shared store, extracts lines, matches the dock pattern, transforms into the global frame and writes the result as a static transform - the same output contract FrameSampler has, so the charge sequence keeps working and nothing in move_base2, dock_planner or mission_adapters changes. Swapping detectors is one word in the YAML. It is also the only place in the chain allowed to know about TF, actions and the sensor store. The three packages beneath it stay free of all that, which is what lets their tests build a world, cast rays and finish in a millisecond with no runtime around them. Three things only break once the pieces are joined, and no core test can see them: The scan cursor. A 30 Hz control loop reading a 29 Hz lidar ticks more often than scans arrive. Without the cursor the same scan counts as several samples, min_samples stops meaning anything, and the handler commits on one measurement. TF arriving after the scan. The two come from different sources, so TF running a few milliseconds behind is routine. The store's cursor has already moved past that scan, so dropping the sample loses a detection outright every time TF is late. The detection is now held and transformed on a later tick, without re-running the match - the shape was already found, only the transform was missing. The regression test fails without that, which is how it earned its place. Transforming at the scan's own stamp rather than at the latest. The pose just computed belongs to the moment the scan was taken; looking up at another moment mixes two instants into one measurement. The error from "latest" is small but nobody knows how small, and a stamp on the wrong clock shows up exactly here. Rejections happen at boot, not at detection time: no sensor store, a scan_topic the store does not carry (listing the ones it does - a mistyped topic looks exactly like a dead sensor), no profiles, a pattern that is not implemented, a default_profile that does not exist. Every profile is validated, not just the default one, because a typo in the fifth profile that only surfaces at four in the afternoon is the worst kind. An order asking for a profile that does not exist fails and says which ones do. It does not quietly fall back to the default: using the wrong geometry means docking in the wrong place, not being slightly slower. The timeout message says which gate failed. Nothing matched, matched too rarely, or matched but never settled need opposite responses, and one failure line cannot carry that.
This commit is contained in:
650
plugins/dock_pattern_action_handler.cpp
Normal file
650
plugins/dock_pattern_action_handler.cpp
Normal file
@@ -0,0 +1,650 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_action — handler dò dock từ LiDAR: scan thô -> biên dạng -> frame ổn định.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
|
||||
#include <action_core/action_handler.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
#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/v_pattern_matcher.h>
|
||||
#include <robot_line_extraction/line_extractor.h>
|
||||
#include <robot_sensor_ports/sensor_reader.h>
|
||||
#include <robot_sensor_ports/sensor_types.h>
|
||||
|
||||
namespace action_core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr double kDefaultSettleDelay = 0.4; // [s]
|
||||
constexpr double kDefaultTimeout = 15.0; // [s]
|
||||
|
||||
/// Chu kỳ in lý do chưa dò ra. 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]
|
||||
|
||||
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));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
/**
|
||||
* @class DockPatternActionHandler
|
||||
* @brief Dò biên dạng trạm dock trong scan LiDAR thô, lọc, ghi ra một frame ổn định.
|
||||
*
|
||||
* Cùng hợp đồng đầu ra với `FrameSamplerActionHandler`: ghi một TF tĩnh vào `output_frame`, nên
|
||||
* chuỗi `charge` chạy nguyên và không phải sửa dòng nào của navigation. Khác ở **nguồn**:
|
||||
* FrameSampler lấy pose perception đã tính sẵn qua TF, handler này **tự tính** từ mảng `ranges`.
|
||||
*
|
||||
* ## Vì sao tự tính lại tốt hơn
|
||||
*
|
||||
* FrameSampler chỉ có một tín hiệu để lọc: các mẫu có chụm không. Handler này biết nhiều hơn hẳn
|
||||
* ngay tại MỘT scan — số tia đỡ mỗi cánh, sai số khớp, góc kẹp lệch bao nhiêu, chiều dài cánh lệch
|
||||
* bao nhiêu. Nó **loại ứng viên sai tại nguồn** thay vì đợi thống kê, nên cổng chính chống nhầm
|
||||
* nằm ở matcher chứ không ở bộ lọc.
|
||||
*
|
||||
* Bộ lọc vẫn ở đây, cho thứ hạng hai: rung giữa các scan liên tiếp, và cú nhảy `map->odom` khi
|
||||
* localization sửa giữa lúc dò — robot đứng yên (D8) nên cú nhảy đó vẫn dịch pose đã publish.
|
||||
*
|
||||
* ## Bốn tầng, mỗi tầng một gói
|
||||
*
|
||||
* - `robot_sensor_ports` — scan THÔ. Costmap ở 0.05 m đã inflate và xoá thứ tự tia, không dựng
|
||||
* lại được; hai cánh 0.2 m trên lưới ấy là một cục.
|
||||
* - `robot_line_extraction` — `ranges` -> đoạn thẳng.
|
||||
* - `dock_pattern_detector` — đoạn + profile -> pose đích trong frame của scan.
|
||||
* - handler này — TF sang global, lọc, ghi ra TF.
|
||||
*
|
||||
* ## Cấu hình
|
||||
*
|
||||
* - `action_types` [list] actionType nào vào handler này
|
||||
* - `output_frame` [string] frame TF ghi ra, chặng sau trỏ `goal_frame` vào đây
|
||||
* - `scan_topic` [string] PHẢI khớp tên đã khai trong `sensor_store/sensors`
|
||||
* - `settle_delay` [s] chờ robot đứng hẳn trước khi lấy mẫu
|
||||
* - `timeout` [s] hết giờ mà chưa chốt -> kFailed
|
||||
* - `default_profile` [string] profile dùng khi order không mang khoá
|
||||
* - `profile_param_key` [string] tên khoá tra trong actionParameters
|
||||
* - `profiles/<tên>/...` hình học + offset của TỪNG cái sạc
|
||||
* - `line_extraction/...` tham số trích đoạn thẳng, theo CẢM BIẾN chứ không theo sạc
|
||||
* - cộng toàn bộ khoá của @ref PoseSampleFilterConfig, cùng tên như FrameSampler
|
||||
*/
|
||||
class DockPatternActionHandler final : public ActionHandler
|
||||
{
|
||||
public:
|
||||
DockPatternActionHandler() = default;
|
||||
|
||||
static ActionHandler::Ptr create()
|
||||
{
|
||||
return std::make_shared<DockPatternActionHandler>();
|
||||
}
|
||||
|
||||
bool configure(const std::string& name, const ActionContext& ctx,
|
||||
robot::NodeHandle& nh) override
|
||||
{
|
||||
name_ = name;
|
||||
ctx_ = ctx;
|
||||
|
||||
if (ctx_.tf == nullptr)
|
||||
{
|
||||
robot::log_error("[dock_pattern] '%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("[dock_pattern] '%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("dock_profile"));
|
||||
|
||||
if (action_types_.empty())
|
||||
{
|
||||
robot::log_error("[dock_pattern] '%s': action_types is empty — never called.", name_.c_str());
|
||||
return false;
|
||||
}
|
||||
if (output_frame_.empty())
|
||||
{
|
||||
robot::log_error("[dock_pattern] '%s': output_frame is empty — the result would go nowhere.",
|
||||
name_.c_str());
|
||||
return false;
|
||||
}
|
||||
if (scan_topic_.empty())
|
||||
{
|
||||
robot::log_error("[dock_pattern] '%s': scan_topic is empty.", name_.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("[dock_pattern] '%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("[dock_pattern] '%s': settle_delay=%.3f must be finite and >= 0.",
|
||||
name_.c_str(), settle_delay_);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!loadLineExtraction(nh) || !loadProfiles(nh) || !loadFilter(nh))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
action_id_ = action.actionId;
|
||||
scan_cursor_ = 0;
|
||||
pending_valid_ = false;
|
||||
last_reason_.clear();
|
||||
have_reason_log_ = false;
|
||||
detections_ = 0;
|
||||
|
||||
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à dock vào sai chỗ, không phải chậm hơn
|
||||
// một chút. Nói ra tên đã xin và tên có thật.
|
||||
std::string known;
|
||||
for (const auto& entry : profiles_)
|
||||
{
|
||||
known += (known.empty() ? "" : ", ") + entry.first;
|
||||
}
|
||||
robot::log_error("[dock_pattern] '%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("[dock_pattern] '%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);
|
||||
|
||||
robot::log_info("[dock_pattern] '%s': detecting pattern '%s' (profile '%s') on '%s' -> '%s'.",
|
||||
name_.c_str(), dock_pattern_detector::toString(found->second.pattern),
|
||||
profile_name.c_str(), scan_topic_.c_str(), 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 (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;
|
||||
}
|
||||
|
||||
void cancel() override
|
||||
{
|
||||
filter_.reset();
|
||||
scan_cursor_ = 0;
|
||||
pending_valid_ = false;
|
||||
}
|
||||
|
||||
private:
|
||||
// ==============================================================================================
|
||||
// Nạp cấu hình
|
||||
// ==============================================================================================
|
||||
|
||||
bool loadLineExtraction(robot::NodeHandle& nh)
|
||||
{
|
||||
robot::NodeHandle le_nh(nh, "line_extraction");
|
||||
robot_line_extraction::LineExtractionParams params;
|
||||
nh_param(le_nh, "bearing_var", params.bearing_var);
|
||||
nh_param(le_nh, "range_var", params.range_var);
|
||||
nh_param(le_nh, "least_sq_angle_thresh", params.least_sq_angle_thresh);
|
||||
nh_param(le_nh, "least_sq_radius_thresh", params.least_sq_radius_thresh);
|
||||
nh_param(le_nh, "max_line_gap", params.max_line_gap);
|
||||
nh_param(le_nh, "min_line_length", params.min_line_length);
|
||||
nh_param(le_nh, "min_range", params.min_range);
|
||||
nh_param(le_nh, "max_range", params.max_range);
|
||||
nh_param(le_nh, "min_split_dist", params.min_split_dist);
|
||||
nh_param(le_nh, "outlier_dist", params.outlier_dist);
|
||||
|
||||
int min_line_points = static_cast<int>(params.min_line_points);
|
||||
nh_param(le_nh, "min_line_points", min_line_points);
|
||||
params.min_line_points = static_cast<unsigned int>(std::max(0, min_line_points));
|
||||
|
||||
std::string error;
|
||||
if (!extractor_.configure(params, error))
|
||||
{
|
||||
robot::log_error("[dock_pattern] '%s': line_extraction: %s", name_.c_str(), error.c_str());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadProfiles(robot::NodeHandle& nh)
|
||||
{
|
||||
YAML::Node node;
|
||||
if (!nh.getParam("profiles", node) || !node.IsMap() || node.size() == 0)
|
||||
{
|
||||
robot::log_error("[dock_pattern] '%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::DockProfile profile;
|
||||
|
||||
std::string pattern_name = "v";
|
||||
nh_param(p_nh, "pattern", pattern_name);
|
||||
std::string error;
|
||||
if (!dock_pattern_detector::patternFromString(pattern_name, profile.pattern, error))
|
||||
{
|
||||
robot::log_error("[dock_pattern] '%s': profile '%s': %s", name_.c_str(),
|
||||
profile_name.c_str(), error.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
nh_param(p_nh, "vertex_angle", profile.vertex_angle);
|
||||
nh_param(p_nh, "wing_length", profile.wing_length);
|
||||
nh_param(p_nh, "angle_tolerance", profile.angle_tolerance);
|
||||
nh_param(p_nh, "length_tolerance", profile.length_tolerance);
|
||||
nh_param(p_nh, "vertex_gap", profile.vertex_gap);
|
||||
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);
|
||||
nh_param(p_nh, "min_confidence", profile.min_confidence);
|
||||
|
||||
int min_wing_points = static_cast<int>(profile.min_wing_points);
|
||||
nh_param(p_nh, "min_wing_points", min_wing_points);
|
||||
profile.min_wing_points = static_cast<std::size_t>(std::max(0, min_wing_points));
|
||||
|
||||
// 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("[dock_pattern] '%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("[dock_pattern] '%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("[dock_pattern] '%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 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. Control loop 30 Hz đọc lidar 29 Hz thì một phần các
|
||||
* tick không có gì 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;
|
||||
}
|
||||
|
||||
robot_line_extraction::ScanGeometry geometry;
|
||||
geometry.angle_min = scan->angle_min;
|
||||
geometry.angle_increment = 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.
|
||||
ranges_.assign(scan->ranges.begin(), scan->ranges.end());
|
||||
|
||||
std::string error;
|
||||
if (!extractor_.extract(geometry, ranges_, lines_, error))
|
||||
{
|
||||
noteReason(now, "scan unusable: " + error);
|
||||
return;
|
||||
}
|
||||
|
||||
const dock_pattern_detector::Detection detection = matcher_.match(lines_);
|
||||
if (!detection.valid)
|
||||
{
|
||||
noteReason(now, detection.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
// Hình đã khớp. Giữ lại kèm stamp và frame của scan; phép quy TF làm ở resolvePending() vì nó
|
||||
// có thể phải CHỜ.
|
||||
pending_ = detection;
|
||||
pending_frame_ = scan->header.frame_id;
|
||||
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ì sao giữ lại thay vì bỏ: TF và scan tới từ hai nguồn khác nhau, nên TF chậm hơn scan vài mili
|
||||
* giây là chuyện thường. Cursor của kho đã nhảy qua scan đó rồi, nên bỏ ở đây là **mất hẳn** một
|
||||
* phép dò mỗi lần TF trễ — trên robot thật là mất rất nhiều.
|
||||
*
|
||||
* Và vẫn KHÔNG rơi về transform mới nhất: pose vừa tính ứng với thời điểm scan được chụp, tra ở
|
||||
* thời điểm khác là trộn hai thời điểm vào một phép đo. Sai số của "mới nhất" nhỏ thật, nhưng
|
||||
* không ai biết nhỏ bao nhiêu — và stamp lệch hệ thời gian sẽ hiện ra đúng ở đây.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
const double base_yaw = yawOf(sensor_to_global.transform.rotation);
|
||||
const double c = std::cos(base_yaw);
|
||||
const double s = std::sin(base_yaw);
|
||||
|
||||
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 = std::atan2(std::sin(base_yaw + pending_.yaw), std::cos(base_yaw + pending_.yaw));
|
||||
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 (have_reason_log_ && (now - last_reason_log_).toSec() < kReasonLogPeriod)
|
||||
{
|
||||
return;
|
||||
}
|
||||
last_reason_log_ = now;
|
||||
have_reason_log_ = true;
|
||||
robot::log_info("[dock_pattern] '%s': %s", name_.c_str(), reason.c_str());
|
||||
}
|
||||
|
||||
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 — "không thấy gì"
|
||||
// và "thấy nhưng sai chiều dài cánh" đòi hai cách xử trí ngược nhau.
|
||||
tick.message = "action '" + action_id_ + "': no '" + profile_name_ + "' pattern 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`.
|
||||
// Lỗi CẤU HÌNH/tần số, không phải chất lượng dò — nới `max_spread_*` vô ích.
|
||||
tick.message = "action '" + action_id_ + "': detected the pattern 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("[dock_pattern] '%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 tới quá gần.
|
||||
return ctx_.tf->setTransform(out, "dock_pattern/" + name_, /*is_static=*/true);
|
||||
}
|
||||
|
||||
std::string name_;
|
||||
ActionContext ctx_;
|
||||
|
||||
std::vector<std::string> action_types_;
|
||||
std::string output_frame_;
|
||||
std::string scan_topic_;
|
||||
double settle_delay_ = kDefaultSettleDelay;
|
||||
double timeout_ = kDefaultTimeout;
|
||||
|
||||
std::string default_profile_;
|
||||
std::string profile_param_key_ = "dock_profile";
|
||||
std::map<std::string, dock_pattern_detector::DockProfile> profiles_;
|
||||
|
||||
robot_line_extraction::LineExtractor extractor_;
|
||||
dock_pattern_detector::VPatternMatcher matcher_;
|
||||
PoseSampleFilter filter_;
|
||||
|
||||
robot::Time started_at_;
|
||||
std::string action_id_;
|
||||
std::string profile_name_;
|
||||
|
||||
/// 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::Detection pending_;
|
||||
std::string pending_frame_;
|
||||
tf3::Time pending_stamp_;
|
||||
bool pending_valid_ = false;
|
||||
|
||||
std::string last_reason_;
|
||||
robot::Time last_reason_log_;
|
||||
bool have_reason_log_ = false;
|
||||
|
||||
/// Buffer dùng lại: hai hàm dưới chạy mỗi khi có scan mới, tức ~30 lần/giây.
|
||||
std::vector<double> ranges_;
|
||||
std::vector<robot_line_extraction::Line> lines_;
|
||||
};
|
||||
|
||||
} // namespace action_core
|
||||
|
||||
BOOST_DLL_ALIAS(action_core::DockPatternActionHandler::create, DockPatternActionHandler)
|
||||
Reference in New Issue
Block a user