Files
action_core/plugins/frame_sampler_action_handler.cpp
duongtd 669c3f7c06 feat: ActionHandler pause/resume + kCancelled status + ABI version guard
- ActionStatus::kCancelled (new, string "CANCELLED"): the missing "stopped
  on request" terminal status — previously a cancelled action only had
  Running/Succeeded/Failed to report through, so move_base2's state
  machine couldn't tell a cancelled action from a failed one.
- ActionHandler::cancelNeedsTicks() (default false), pause(now) and
  resume(now) (default no-ops): lets a handler opt into "I need more
  ticks to actually stop" (device handshake) instead of being torn down
  immediately, and gives handlers a real pause/resume contract instead of
  move_base2 having to freeze/unfreeze them from outside.
- action_abi.h (new) + ACTION_CORE_EXPORT_HANDLER macro, same pattern as
  recovery_core commit 254c7fc: exports a version symbol next to the
  factory alias; action_registry.cpp refuses a handler .so whose version
  doesn't match instead of dlsym+reinterpret_cast blindly onto a grown
  vtable.
- frame_sampler / wait / noop handlers implement pause/resume via
  paused_at_ / started_at_ += (now - paused_at_) so their own internal
  timers don't count paused time; paused_ is reset on start() so a reused
  handler instance can't come up already paused.
- test/plugins/stale_abi_action_handler.cpp (new) for the registry refusal
  test.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 22:07:00 +07:00

648 lines
30 KiB
C++
Raw Permalink 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)
*
* action_core — handler dò: lấy mẫu một TF frame nhiễu, lọc, ghi ra một frame ổn định.
*
* Author: DuongTD
*********************************************************************/
#include <action_core/action_handler.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
#include <action_core/action_abi.h>
#include <robot/robot.h>
#include <tf3/buffer_core.h>
#include <action_core/pose_sample_filter.h>
namespace action_core
{
namespace
{
constexpr double kDefaultSettleDelay = 1.0; // [s]
constexpr double kDefaultSampleWindow = 2.0; // [s]
constexpr int kDefaultMinSamples = 20;
constexpr double kDefaultMaxSpreadXy = 0.03; // [m]
constexpr double kDefaultMaxSpreadYaw = 0.05; // [rad]
constexpr double kDefaultHoldTime = 0.0; // [s]
constexpr double kDefaultTimeout = 15.0; // [s]
constexpr double kDefaultJumpThreshold = 0.0; // [m] 0 = tắt lọc cụm
constexpr double kDefaultClusterRecency = 0.3; // [s]
constexpr double kDefaultMinClusterFraction = 0.6;
constexpr int kDefaultMinClusterSamples = 5;
constexpr const char* kFrameKey = "goal_frame";
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 FrameSamplerActionHandler
* @brief Dò: lấy mẫu một TF frame trong một cửa sổ thời gian, lọc nhiễu, ghi ra frame ổn định.
*
* Pose do LiDAR/camera sinh ra **dao động**. Bám thẳng vào nó là robot lắc theo nhiễu; chốt một mẫu
* bất kỳ là chốt cả sai số của đúng mẫu đó. Handler này đứng giữa: robot đứng yên (trong
* `EXECUTING_ACTIONS` không ai phát cmd_vel), thu mẫu trong `sample_window`, lọc, rồi ghi kết quả
* ra `output_frame`. Chặng kế tiếp trỏ `goal_frame` vào frame đó.
*
* ## Vì sao ghi ra TF thay vì trả pose qua tick
*
* @ref ActionTick cố ý chỉ mang **trạng thái**, không mang dữ liệu — thêm pose vào đó sẽ buộc mọi
* tầng ở giữa phải chở một trường mà chúng không hiểu. `tf3::BufferCore` ghi được, và navigation đã
* đọc chung buffer đó, nên kết quả đi tới nơi cần mà không đổi contract nào.
*
* ## Ba chỗ dễ sai khi lọc, đã xử lý
*
* 1. **Yaw không được lấy trung bình số học.** Mẫu quanh ±π cho ra ~0 — lệch 180°, robot vào trạm
* ngược đầu. Gộp bằng vector đơn vị: `atan2(mean(sin), mean(cos))`.
* 2. **x, y dùng trung vị**, không phải trung bình: một mẫu nhận nhầm chân kệ khác kéo trung bình đi
* vài cm.
* 3. **Gộp mẫu trong frame CỐ ĐỊNH** (`ctx.global_frame`), không phải `base_link`: robot còn nhúc
* nhích thì mẫu trong hệ thân xe không so sánh được với nhau.
*
* Thêm: **bỏ mẫu trùng timestamp**. TF cập nhật chậm hơn control loop, đọc mỗi cycle 30 Hz sẽ đếm
* cùng một pose thành 30 mẫu và `min_samples` mất hết ý nghĩa.
*
* ## Cổng chất lượng: CỬA SỔ TRƯỢT, chờ hội tụ chứ không phán một lần
*
* Độ tản vượt `max_spread_*` nghĩa là **chưa nhìn rõ**, và trung bình của dữ liệu rác vẫn là rác —
* nhưng "chưa rõ *lúc này*" không đồng nghĩa "sẽ không bao giờ rõ". Perception thường cần vài giây
* để bám ổn định: mẫu đầu nhảy, rồi co dần về một chỗ. Phán ngay tại mốc
* `settle_delay + sample_window` là vứt bỏ toàn bộ thời gian còn lại của `timeout`.
*
* Nên `samples_` là **cửa sổ trượt** dài `sample_window`: mỗi tick thu mẫu mới, bỏ mẫu quá hạn, rồi
* đánh giá lại. Đạt ngưỡng → chốt; chưa đạt → chờ tiếp. Chỉ khi hết `timeout` mà **chưa cửa sổ nào**
* đạt mới `kFailed` — đúng nghĩa "dò suốt chừng ấy giây mà dữ liệu không chịu hội tụ".
*
* Cửa sổ phải TRƯỢT, không được tích luỹ: giữ cả mẫu từ giây đầu thì độ tản không bao giờ giảm
* được, perception có ổn định về sau cũng vẫn fail.
*
* Lần đánh giá đầu tiên vẫn đợi đủ `settle_delay + sample_window` — cửa sổ chưa đầy thời lượng thì
* mẫu nằm sát nhau về thời gian, trông chụm một cách giả tạo.
*
* Hỏng ở đây thì `clear_queue_on_failure` xoá luôn chặng tiến-vào và chặng thao tác thiết bị phía
* sau — robot không lùi vào đâu cả. Đây là thứ mà một watchdog "không thấy gì" đơn thuần không bắt
* được: nó **thấy**, chỉ là không đáng tin.
*
* ### `hold_time`: chặn cửa sổ "chụm nhưng sai"
*
* Thử lại liên tục mở ra một rủi ro mà bản phán-một-lần không có: một cửa sổ **tình cờ** chụm giữa
* lúc dò đang dao động cũng được chấp nhận. Nguy hơn nữa là nhận nhầm *ổn định* — LiDAR bám chắc
* vào chân kệ bên cạnh thì mẫu chụm thật, chỉ là chụm quanh sai chỗ. `hold_time` bắt điều kiện đạt
* phải **giữ được** liên tục ngần ấy giây mới chốt; tản trở lại một tick là đồng hồ reset.
*
* Mặc định `0.0` — chốt ngay cửa sổ đạt đầu tiên, đúng bằng lượng bằng chứng của phiên bản
* phán-một-lần trước đây (một cửa sổ đầy, đủ `min_samples`, độ tản trong ngưỡng). Đặt > 0 khi hiện
* trường có nhận nhầm.
*
* ## Lọc cụm chống TF nhảy (`jump_threshold` > 0)
*
* Localization sửa `map→odom` giữa lúc dò nghĩa là mẫu ĐÃ THU nhảy sang hệ toạ độ khác: cửa sổ
* chứa hai (hay nhiều) cụm cách nhau cả nửa mét, độ tản toàn cửa sổ vượt ngưỡng mãi dù từng cụm tự
* nó chụm hoàn hảo — lượt dò fail suốt `timeout` trong khi phép dò không có lỗi gì.
*
* Bật `jump_threshold` thì mỗi lần đánh giá, mẫu được gom cụm theo khoảng cách tới **TÂM** cụm
* (không phải tới mẫu gần nhất — mẫu bắt giữa lúc TF nội suy nằm lưng chừng hai cụm sẽ bắc cầu nối
* chúng nếu đo kiểu single-linkage). Cụm được phép chốt phải:
* - chiếm ≥ `min_cluster_fraction` tổng mẫu cửa sổ. Buộc > 0.5: quá bán thì tối đa MỘT cụm đạt —
* khỏi cần luật xử hoà riêng, và hai hệ toạ độ giằng co 50/50 thì không phe nào đủ, handler
* chờ. Không biết thì không đẩy goal ra — hai tâm cách 0.55 m mà chọn bừa là dock sai nửa mét.
* - có ≥ `min_cluster_samples` mẫu — dưới sàn này median/spread không còn nghĩa thống kê;
* - có mẫu trong `cluster_recency` giây chót — cụm "đa số nhưng NGUỘI" là toạ độ trước correction,
* chốt theo nó là dock vào hệ toạ độ localization đã vứt bỏ.
* Độ tản sau đó chỉ tính trên cụm được chọn; `max_spread_*` giữ nguyên vai trò cổng an toàn.
*
* `cluster_recency` đồng thời là chân trời quyết định: TF đổi hẳn trong vòng ngần ấy giây trước
* lúc chốt thì không phân biệt được với flicker, handler vẫn có thể chốt theo cụm cũ. Đặt dài hơn
* flicker điển hình nhưng ngắn hơn nhiều so với `sample_window`.
*
* ## `filter_enabled: false` — bỏ lọc có chủ đích
*
* Chốt ngay mẫu THỨ HAI nhận được, không cửa sổ, không độ tản. Lấy mẫu thứ hai chứ không phải thứ
* nhất: lookup đầu tiên sau khi action bắt đầu có thể trả về detection CŨ còn sót trong buffer từ
* trước khi robot dừng; mẫu thứ hai (stamp khác) chứng minh nguồn còn sống và dữ liệu là mới.
* `settle_delay` và `timeout` vẫn có hiệu lực; mọi param cửa sổ/độ tản/cụm bị bỏ qua. Dùng khi cần
* loại trừ chính tầng lọc lúc debug, hoặc khi perception đã tự lọc xong và publish pose chốt.
*
* ## Bộ lọc nằm ở đâu
*
* Toàn bộ phần cửa sổ trượt, lọc cụm, độ tản và giữ trạng thái nằm trong @ref PoseSampleFilter.
* Handler này chỉ là **nguồn mẫu**: nó tra TF, đẩy mẫu vào bộ lọc, rồi ghi kết quả ra TF. Bộ dò
* hình học từ LiDAR dùng đúng bộ lọc đó với đúng tập khoá YAML đó — người vận hành học một lần.
*
* ## Đọc tiến trình hội tụ
*
* Mỗi `kProgressLogPeriod` giây handler in một dòng: số mẫu trong cửa sổ, tâm, độ tản hiện tại và
* ngưỡng. Lúc `timeout` thì in **cửa sổ tốt nhất từng thấy** — biết dữ liệu đã co được tới đâu là
* biết nên nới ngưỡng, kéo dài `timeout`, hay sửa ở nguồn perception.
*
* Param (namespace của instance):
* - `action_types` [list] actionType nội bộ, vd `[DetectCharger]`
* - `output_frame` [string] frame ghi ra; chặng sau trỏ vào đây
* - `input_frame` [string, ""] frame thô cố định; rỗng = lấy từ `actionParameters["goal_frame"]`
* - `settle_delay` [s] chờ robot đứng hẳn trước khi thu mẫu
* - `sample_window` [s] độ dài CỬA SỔ TRƯỢT, cũng là thời điểm đánh giá lần đầu
* - `min_samples` [int] số mẫu tối thiểu TRONG CỬA SỔ để cửa sổ đó được đánh giá
* - `max_spread_xy` [m] cửa sổ tản hơn → chưa đạt, chờ tiếp
* - `max_spread_yaw` [rad]
* - `hold_time` [s, 0] phải giữ trạng thái đạt liên tục ngần này mới chốt
* - `timeout` [s] hết giờ mà chưa cửa sổ nào đạt → kFailed
* - `filter_enabled` [bool, true] false = chốt ngay mẫu thứ hai, bỏ toàn bộ cửa sổ/độ tản/cụm
* - `jump_threshold` [m, 0] 0 = tắt lọc cụm. Khoảng cách tới tâm cụm để mẫu được gom chung;
* đặt giữa độ tản dò thật (mm–cm) và biên độ TF nhảy (dm), bắt buộc > `max_spread_xy`
* - `cluster_recency` [s, 0.3] cụm không có mẫu mới hơn ngần này thì không được chốt
* - `min_cluster_fraction` [-, 0.6] tỉ lệ tổng mẫu cửa sổ mà cụm phải chiếm; bắt buộc > 0.5
* - `min_cluster_samples` [-, 5] sàn mẫu tuyệt đối của cụm; bắt buộc ≤ `min_samples`
* - `use_simulated_goal` [bool, false] chỉ dành cho Gazebo/dev: bỏ perception, chốt một pose
* tương đối với `simulated_parent_frame` thành `output_frame` tĩnh. Không bật trên robot thật.
* - `simulated_parent_frame` [string, "base_link"] parent của pose giả
* - `simulated_offset_x/y` [m], `simulated_offset_yaw` [rad] pose giả trong parent frame
*/
class FrameSamplerActionHandler final : public ActionHandler
{
public:
FrameSamplerActionHandler() = default;
static ActionHandler::Ptr create()
{
return std::make_shared<FrameSamplerActionHandler>();
}
bool configure(const std::string& name, const ActionContext& ctx,
robot::NodeHandle& nh) override
{
name_ = name;
ctx_ = ctx;
if (ctx_.tf == nullptr)
{
// Không có TF thì handler này 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("[action_core] '%s': needs a TF buffer but the context has none.",
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("input_frame", input_frame_, std::string());
nh.param("settle_delay", settle_delay_, kDefaultSettleDelay);
nh.param("timeout", timeout_, kDefaultTimeout);
nh.param("use_simulated_goal", use_simulated_goal_, false);
nh.param("simulated_parent_frame", simulated_parent_frame_, std::string("base_link"));
nh.param("simulated_offset_x", simulated_offset_x_, 0.0);
nh.param("simulated_offset_y", simulated_offset_y_, 0.0);
nh.param("simulated_offset_yaw", simulated_offset_yaw_, 0.0);
PoseSampleFilterConfig filter_config;
nh.param("filter_enabled", filter_config.enabled, true);
nh.param("sample_window", filter_config.sample_window, kDefaultSampleWindow);
nh.param("min_samples", filter_config.min_samples, kDefaultMinSamples);
nh.param("max_spread_xy", filter_config.max_spread_xy, kDefaultMaxSpreadXy);
nh.param("max_spread_yaw", filter_config.max_spread_yaw, kDefaultMaxSpreadYaw);
nh.param("hold_time", filter_config.hold_time, kDefaultHoldTime);
nh.param("jump_threshold", filter_config.jump_threshold, kDefaultJumpThreshold);
nh.param("cluster_recency", filter_config.cluster_recency, kDefaultClusterRecency);
nh.param("min_cluster_fraction", filter_config.min_cluster_fraction,
kDefaultMinClusterFraction);
nh.param("min_cluster_samples", filter_config.min_cluster_samples, kDefaultMinClusterSamples);
if (action_types_.empty())
{
robot::log_error("[action_core] '%s': action_types is empty — never called.", name_.c_str());
return false;
}
if (output_frame_.empty())
{
robot::log_error("[action_core] '%s': output_frame is empty — the result would go nowhere.",
name_.c_str());
return false;
}
if (output_frame_ == input_frame_)
{
// Ghi đè chính frame thô là tranh chấp với bên publish nó; giá trị lọc sẽ bị ghi lại ngay.
robot::log_error("[action_core] '%s': output_frame must differ from input_frame ('%s').",
name_.c_str(), input_frame_.c_str());
return false;
}
if (!std::isfinite(settle_delay_) || settle_delay_ < 0.0 ||
!std::isfinite(filter_config.sample_window) || filter_config.sample_window <= 0.0)
{
robot::log_error("[action_core] '%s': settle_delay=%.3f / sample_window=%.3f invalid.",
name_.c_str(), settle_delay_, filter_config.sample_window);
return false;
}
// Miền của nhóm khoá lọc thuộc về chính bộ lọc — cùng một luật cho mọi nguồn mẫu, không phải
// chép sang từng handler rồi để chúng trôi lệch nhau.
if (!filter_.configure(filter_config, name_))
{
return false;
}
if (filter_config.enabled && timeout_ > 0.0 &&
timeout_ <= settle_delay_ + filter_config.sample_window + filter_config.hold_time)
{
// Timeout ngắn hơn (thu mẫu + giữ trạng thái đạt) thì action LUÔN hỏng dù dò hoàn hảo — gần
// như chắc chắn gõ nhầm. `hold_time` nằm trong tổng này vì nó cộng thêm sau cửa sổ đầu tiên.
robot::log_error("[action_core] '%s': timeout=%.3f s <= "
"settle_delay+sample_window+hold_time=%.3f s; the action would always fail.",
name_.c_str(), timeout_,
settle_delay_ + filter_config.sample_window + filter_config.hold_time);
return false;
}
if (!filter_config.enabled && timeout_ > 0.0 && timeout_ <= settle_delay_)
{
// Đường bỏ lọc chỉ cần settle + 2 mẫu, nhưng timeout ngắn hơn cả settle thì vẫn LUÔN hỏng.
robot::log_error("[action_core] '%s': timeout=%.3f s <= settle_delay=%.3f s; the action "
"would always fail.",
name_.c_str(), timeout_, settle_delay_);
return false;
}
if (use_simulated_goal_)
{
if (simulated_parent_frame_.empty() || simulated_parent_frame_ == output_frame_)
{
robot::log_error("[action_core] '%s': simulated_parent_frame must be non-empty and differ "
"from output_frame.",
name_.c_str());
return false;
}
if (!std::isfinite(simulated_offset_x_) || !std::isfinite(simulated_offset_y_) ||
!std::isfinite(simulated_offset_yaw_))
{
robot::log_error("[action_core] '%s': simulated goal offset is non-finite.", name_.c_str());
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;
paused_ = false;
action_id_ = action.actionId;
resetRun();
simulated_goal_published_ = false;
if (use_simulated_goal_)
{
if (!publishSimulatedGoal(now))
{
return false;
}
simulated_goal_published_ = true;
robot::log_warning("[action_core] '%s': SIMULATION ONLY — published '%s' from fixed offset "
"(%.3f, %.3f, %.3f rad) in '%s'.",
name_.c_str(), output_frame_.c_str(), simulated_offset_x_,
simulated_offset_y_, simulated_offset_yaw_,
simulated_parent_frame_.c_str());
return true;
}
frame_ = input_frame_;
if (frame_.empty() && !readFrameParam(action, frame_))
{
return false;
}
filter_.setLabels(frame_, ctx_.global_frame);
robot::log_info("[action_core] '%s': sampling '%s' for %.2f s (settle %.2f s) -> '%s'.",
name_.c_str(), frame_.c_str(), filter_.config().sample_window, settle_delay_,
output_frame_.c_str());
return true;
}
ActionTick update(const robot::Time& now) override
{
ActionTick tick;
if (simulated_goal_published_)
{
tick.status = ActionStatus::kSucceeded;
tick.message = "action '" + action_id_ + "': simulated static frame '" + output_frame_ + "'";
return tick;
}
const double elapsed = (now - started_at_).toSec(); // [s]
// Robot vừa dừng vẫn còn dao động cơ khí; pose dò được lúc này mang theo dao động đó.
if (elapsed >= settle_delay_)
{
const bool grew = collectSample(now);
const bool shrank = filter_.pruneExpired(now);
window_changed_ = window_changed_ || grew || shrank;
}
// Bỏ lọc có chủ đích: chốt ngay mẫu THỨ HAI, không cửa sổ, không độ tản. Mẫu thứ nhất có thể
// là detection cũ còn sót trong buffer từ trước khi robot dừng; mẫu thứ hai (stamp khác) chứng
// minh nguồn còn sống và dữ liệu là mới.
if (!filter_.config().enabled)
{
if (filter_.totalSamples() >= 2)
{
if (!publish(filter_.newest(), 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 raw sample #2 (filter disabled) after " + formatSeconds(elapsed) +
" s";
return tick;
}
if (timeout_ > 0.0 && elapsed >= timeout_)
{
return failOnTimeout(elapsed);
}
tick.status = ActionStatus::kRunning;
return tick;
}
// Cửa sổ đầu tiên phải đủ THỜI LƯỢNG, không chỉ đủ số mẫu: mẫu thu trong 0.2 s đầu nằm sát nhau
// về thời gian nên trông chụm một cách giả tạo, chốt theo đó là chốt trước khi có bằng chứng.
if (elapsed >= settle_delay_ + filter_.config().sample_window && window_changed_)
{
window_changed_ = false;
filter_.evaluate(now);
}
// Thành công được xét TRƯỚC timeout: một cửa sổ đạt đúng vào tick cuối vẫn là dò thành công.
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()) + " sample(s) after " +
formatSeconds(elapsed) + " s";
return tick;
}
// Timeout TẦNG 1: hết giờ mà chưa cửa sổ nào đạt. Bao cả hai ca — frame thô không bao giờ xuất
// hiện, và frame có xuất hiện nhưng dữ liệu không chịu hội tụ.
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
{
// Không có thiết bị nào để dừng; chỉ bỏ mẫu để lượt sau không thừa hưởng dữ liệu cũ.
resetRun();
simulated_goal_published_ = false;
}
private:
bool readFrameParam(const robot_protocol_msgs::Action& action, std::string& frame) const
{
const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(),
[](const robot_protocol_msgs::ActionParameter& p) {
return p.key == kFrameKey;
});
if (it == action.actionParameters.end() || it->value.empty())
{
robot::log_error("[action_core] '%s': action '%s' has no '%s' parameter and no input_frame "
"configured — nothing to detect.",
name_.c_str(), action.actionId.c_str(), kFrameKey);
return false;
}
frame = it->value;
return true;
}
/// @brief Xoá trạng thái của một lượt dò. Gọi ở `start()` và `cancel()` để lượt sau không thừa
/// hưởng mẫu, cửa sổ tốt nhất hay đồng hồ giữ trạng thái của lượt trước.
void resetRun()
{
filter_.reset();
have_last_stamp_ = false;
window_changed_ = false;
}
/**
* @brief Đọc một mẫu MỚI của frame thô, quy về global frame. Mẫu trùng timestamp bị bỏ.
* @return true nếu cửa sổ có thêm mẫu.
*/
bool collectSample(const robot::Time& now)
{
tf3::TransformStampedMsg tf;
try
{
tf = ctx_.tf->lookupTransform(ctx_.global_frame, frame_, tf3::Time());
}
catch (const std::exception&)
{
return false; // Chưa dò ra. Không log ở đây: hàm này chạy mỗi control cycle.
}
// TF cập nhật chậm hơn control loop; không lọc theo timestamp thì cùng một pose bị đếm nhiều
// lần và `min_samples` mất hết ý nghĩa.
if (have_last_stamp_ && tf.header.stamp == last_stamp_)
{
return false;
}
last_stamp_ = tf.header.stamp;
have_last_stamp_ = true;
PoseSample s;
s.x = tf.transform.translation.x;
s.y = tf.transform.translation.y;
s.yaw = yawOf(tf.transform.rotation);
s.taken_at = now;
return filter_.addSample(s);
}
/// @brief Hết `timeout` mà chưa cửa sổ nào đạt. Ba nguyên nhân, ba thông điệp khác nhau.
ActionTick failOnTimeout(double elapsed)
{
ActionTick tick;
tick.status = ActionStatus::kFailed;
if (filter_.totalSamples() == 0)
{
// Không thấy gì cả: perception chưa chạy, sai tên frame, hoặc vật thể ngoài tầm.
tick.message = "action '" + action_id_ + "': frame '" + frame_ + "' did not appear in time";
return tick;
}
if (!filter_.config().enabled)
{
// Đường bỏ lọc mà vẫn timeout nghĩa là chỉ thấy đúng MỘT mẫu suốt lượt (>= 2 đã chốt từ lâu):
// không có mẫu thứ hai xác nhận, rất có thể là detection cũ đóng băng trong buffer.
tick.message = "action '" + action_id_ + "': '" + frame_ + "' produced only one sample in " +
formatSeconds(elapsed) + " s — need a second fresh sample (filter disabled)";
return tick;
}
if (!filter_.hasBest())
{
// Thấy, nhưng chưa cửa sổ nào đủ `min_samples`: nguồn publish quá thưa so với `sample_window`.
// Đây là lỗi CẤU HÌNH/tần số, không phải lỗi chất lượng dò — nới `max_spread_*` vô ích.
tick.message = "action '" + action_id_ + "': '" + frame_ + "' published too sparsely — " +
std::to_string(filter_.totalSamples()) + " sample(s) in " +
formatSeconds(elapsed) + " s, need " +
std::to_string(filter_.config().min_samples) + " within any " +
formatSeconds(filter_.config().sample_window) + " s window";
return tick;
}
// Thấy, đủ mẫu, nhưng không cửa sổ nào chụm đủ. Khác hẳn "không thấy gì" — và nguy hiểm hơn, vì
// trung bình của dữ liệu rác vẫn ra một con số trông hợp lý.
//
// Log hình dạng cửa sổ TỐT NHẤT, không chỉ một con số tổng hợp. Chỉ mình `spread` không phân
// biệt được hai nguyên nhân đòi hai cách xử lý trái ngược:
// - vài mẫu văng xa, phần còn lại chụm -> mẫu nhận nhầm, sửa ở nguồn publish frame;
// - mọi mẫu đều lệch -> dò thật sự không ổn định, phải dò lại/đứng gần hơn.
// Hộp bao cho biết các mẫu văng đi ĐÂU. Chạy đúng một lần mỗi lượt dò hỏng.
robot::log_error("[action_core] '%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_ + "': detection unstable (best spread xy=" +
std::to_string(filter_.bestSpreadXy()) +
" m, yaw=" + std::to_string(filter_.bestSpreadYaw()) + " rad in " +
formatSeconds(elapsed) + " s; limits " +
std::to_string(filter_.config().max_spread_xy) + " m / " +
std::to_string(filter_.config().max_spread_yaw) + " rad)";
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, "action_core/" + name_, /*is_static=*/true);
}
bool publishSimulatedGoal(const robot::Time& now)
{
tf3::TransformStampedMsg parent;
try
{
parent = ctx_.tf->lookupTransform(ctx_.global_frame, simulated_parent_frame_, tf3::Time());
}
catch (const std::exception&)
{
robot::log_error("[action_core] '%s': simulation parent frame '%s' is unavailable.",
name_.c_str(), simulated_parent_frame_.c_str());
return false;
}
const double parent_yaw = yawOf(parent.transform.rotation);
PoseSample simulated;
simulated.x = parent.transform.translation.x +
std::cos(parent_yaw) * simulated_offset_x_ -
std::sin(parent_yaw) * simulated_offset_y_;
simulated.y = parent.transform.translation.y +
std::sin(parent_yaw) * simulated_offset_x_ +
std::cos(parent_yaw) * simulated_offset_y_;
simulated.yaw = parent_yaw + simulated_offset_yaw_;
return publish(simulated, now);
}
std::string name_;
ActionContext ctx_;
std::vector<std::string> action_types_;
std::string output_frame_;
std::string input_frame_;
double settle_delay_ = kDefaultSettleDelay;
double timeout_ = kDefaultTimeout;
bool use_simulated_goal_ = false;
std::string simulated_parent_frame_ = "base_link";
double simulated_offset_x_ = 0.0; // [m]
double simulated_offset_y_ = 0.0; // [m]
double simulated_offset_yaw_ = 0.0; // [rad]
/// Cửa sổ trượt, lọc cụm, độ tản, giữ trạng thái và chẩn đoán — dùng chung với mọi nguồn mẫu.
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 frame_;
bool simulated_goal_published_ = false;
/// Stamp của TF đã lấy mẫu gần nhất; chống đếm hai lần cùng một pose. Thuộc về NGUỒN mẫu, không
/// phải bộ lọc — nguồn khác (một scan LiDAR) dedupe theo thứ khác.
tf3::Time last_stamp_;
bool have_last_stamp_ = false;
/// Cửa sổ đã đổi kể từ lần chấm điểm gần nhất. Không đổi thì độ tản cũng không đổi.
bool window_changed_ = false;
};
} // namespace action_core
ACTION_CORE_EXPORT_HANDLER(action_core::FrameSamplerActionHandler::create, FrameSamplerActionHandler)