/********************************************************************* * * 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 #include #include #include #include #include #include #include #include #include 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 const char* kFrameKey = "goal_frame"; /// Chu kỳ in tiến trình hội tụ. Control loop chạy ~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 tập mẫu đang co lại hay không. constexpr double kProgressLogPeriod = 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)); } /// @brief Trung vị theo từng trục. Bền hơn trung bình trước outlier — LiDAR thỉnh thoảng bắt nhầm. /// @note Nhận tham chiếu và SẮP XẾP LẠI @p v tại chỗ. Gọi trên buffer dùng lại được, không phải bản /// sao — hàm này chạy mỗi khi cửa sổ trượt đổi, tức gần như mỗi control cycle. double median(std::vector& v) { const std::size_t mid = v.size() / 2; std::nth_element(v.begin(), v.begin() + mid, v.end()); const double hi = v[mid]; if (v.size() % 2 != 0) { return hi; } std::nth_element(v.begin(), v.begin() + mid - 1, v.end()); return 0.5 * (hi + v[mid - 1]); } /** * @brief Độ tản BỀN: 2 x phân vị 90 của độ lệch so với tâm. * * Không dùng `max - min`: một mẫu nhận nhầm duy nhất trong ba mươi mẫu sẽ thổi nó lên hàng mét và * đánh hỏng cả lượt dò — mà đó đúng là tình huống trung vị sinh ra để chịu được. Cắt ở phân vị 90 * cho phép tối đa 10% mẫu rác, đồng thời vẫn bắt được dữ liệu tản thật (khi ấy MỌI mẫu đều lệch, * không chỉ vài mẫu). */ /// @note Như @ref median: nhận tham chiếu và sắp xếp lại tại chỗ, tránh cấp phát mỗi cycle. double robustSpread(std::vector& deviations) { if (deviations.empty()) { return 0.0; } const std::size_t idx = std::min(deviations.size() - 1, static_cast(deviations.size() * 0.9)); std::nth_element(deviations.begin(), deviations.begin() + idx, deviations.end()); return 2.0 * deviations[idx]; } } // 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. * * ## Đọ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 * - `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(); } 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{}); 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("sample_window", sample_window_, kDefaultSampleWindow); nh.param("min_samples", min_samples_, kDefaultMinSamples); nh.param("max_spread_xy", max_spread_xy_, kDefaultMaxSpreadXy); nh.param("max_spread_yaw", max_spread_yaw_, kDefaultMaxSpreadYaw); nh.param("hold_time", hold_time_, kDefaultHoldTime); 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); 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(sample_window_) || sample_window_ <= 0.0) { robot::log_error("[action_core] '%s': settle_delay=%.3f / sample_window=%.3f invalid.", name_.c_str(), settle_delay_, sample_window_); return false; } if (min_samples_ < 1) { robot::log_error("[action_core] '%s': min_samples=%d must be >= 1.", name_.c_str(), min_samples_); return false; } if (!std::isfinite(max_spread_xy_) || max_spread_xy_ <= 0.0 || !std::isfinite(max_spread_yaw_) || max_spread_yaw_ <= 0.0) { robot::log_error("[action_core] '%s': max_spread_xy/yaw must be > 0.", name_.c_str()); return false; } if (!std::isfinite(hold_time_) || hold_time_ < 0.0) { robot::log_error("[action_core] '%s': hold_time=%.3f must be finite and >= 0.", name_.c_str(), hold_time_); return false; } if (timeout_ > 0.0 && timeout_ <= settle_delay_ + sample_window_ + 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_ + sample_window_ + hold_time_); 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 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; 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; } robot::log_info("[action_core] '%s': sampling '%s' for %.2f s (settle %.2f s) -> '%s'.", name_.c_str(), frame_.c_str(), 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 = pruneExpired(now); window_changed_ = window_changed_ || grew || shrank; } // 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_ + sample_window_ && window_changed_) { window_changed_ = false; evaluateWindow(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 (converged_ && (now - converged_since_).toSec() >= hold_time_) { if (!publish(hold_pose_, 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(samples_.size()) + " 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; } 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: struct Sample { double x = 0.0; double y = 0.0; double yaw = 0.0; // [rad] /// Thời điểm TICK thu được mẫu, không phải stamp của TF. Cửa sổ trượt cắt theo trục thời gian /// của chính handler, cùng trục với `timeout` — stamp TF có thể lệch trục nếu nguồn publish /// dùng đồng hồ khác. robot::Time taken_at; }; 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() { samples_.clear(); total_samples_ = 0; have_last_stamp_ = false; window_changed_ = false; converged_ = false; best_valid_ = false; best_score_ = 0.0; best_spread_xy_ = 0.0; best_spread_yaw_ = 0.0; best_description_.clear(); have_progress_log_ = 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; Sample s; s.x = tf.transform.translation.x; s.y = tf.transform.translation.y; s.yaw = yawOf(tf.transform.rotation); s.taken_at = now; samples_.push_back(s); ++total_samples_; return true; } /** * @brief Bỏ mẫu già hơn `sample_window` khỏi đầu cửa sổ. * @return true nếu có mẫu bị bỏ. * * Đây là phần khiến cửa sổ TRƯỢT thay vì tích luỹ. Không có nó thì mẫu xấu của giây đầu ở lại mãi * và độ tản không bao giờ giảm được — perception ổn định về sau vẫn bị báo hỏng. */ bool pruneExpired(const robot::Time& now) { // Mẫu được push theo thứ tự thời gian nên chỉ cần cắt từ đầu; số phần tử bỏ mỗi tick là 0 hoặc // rất nhỏ, không phải quét lại toàn cửa sổ. std::size_t expired = 0; while (expired < samples_.size() && (now - samples_[expired].taken_at).toSec() > sample_window_) { ++expired; } if (expired == 0) { return false; } samples_.erase(samples_.begin(), samples_.begin() + expired); return true; } /** * @brief Chấm điểm cửa sổ hiện tại: cập nhật đồng hồ giữ trạng thái, cửa sổ tốt nhất, log tiến độ. * * Chỉ chạy khi cửa sổ ĐỔI (thêm mẫu mới hoặc bỏ mẫu quá hạn). Cửa sổ không đổi thì độ tản cũng * không đổi — lọc lại mỗi control cycle chỉ tốn CPU và cấp phát vô ích. */ void evaluateWindow(const robot::Time& now) { if (static_cast(samples_.size()) < min_samples_) { // Chưa đủ mẫu để nói được gì về độ tản. Đang đạt mà mất mẫu thì cũng coi như tuột — không // được chốt dựa trên một cửa sổ vừa mỏng đi. converged_ = false; logProgress(now, "%zu sample(s) in the %.2f s window, need %d — waiting", samples_.size(), sample_window_, min_samples_); return; } Sample centre; double spread_xy = 0.0; double spread_yaw = 0.0; filter(centre, spread_xy, spread_yaw); // Điểm = tỉ lệ so với ngưỡng, lấy trục tệ hơn. Cho biết cửa sổ còn thiếu bao nhiêu để đạt, và so // sánh được giữa hai trục có đơn vị khác nhau ([m] và [rad]). const double score = std::max(spread_xy / max_spread_xy_, spread_yaw / max_spread_yaw_); if (!best_valid_ || score < best_score_) { best_valid_ = true; best_score_ = score; best_spread_xy_ = spread_xy; best_spread_yaw_ = spread_yaw; // Chụp lại hình dạng cửa sổ NGAY LÚC NÀY: tới lúc timeout thì `samples_` đã là cửa sổ khác, // mô tả khi ấy sẽ không còn ứng với các con số tốt nhất. Chỉ chạy khi có cải thiện. best_description_ = describeSamples(centre); } if (spread_xy <= max_spread_xy_ && spread_yaw <= max_spread_yaw_) { if (!converged_) { converged_ = true; converged_since_ = now; } // Luôn chốt theo tâm MỚI NHẤT: mẫu càng gần thời điểm chốt càng ứng với hiện trạng. // // TODO(DuongTD): tâm có thể trôi chậm trong lúc giữ trạng thái (mỗi cửa sổ đều chụm nhưng cả // chuỗi cửa sổ đang bò đi) — cổng hiện tại không bắt được vì nó chỉ đo độ tản TRONG một cửa // sổ. Rủi ro: dock_target lệch dần theo drift của AMCL. Hướng xử lý: so `hold_pose_` lúc bắt // đầu giữ với lúc chốt, vượt `max_drift_xy` thì reset đồng hồ. Cần đo drift thật ở hiện // trường trước khi đặt ngưỡng. hold_pose_ = centre; } else { converged_ = false; } logProgress(now, "%zu sample(s): centre=(%.3f, %.3f) yaw=%.4f rad, spread xy=%.4f/%.3f m " "yaw=%.4f/%.3f rad%s", samples_.size(), centre.x, centre.y, centre.yaw, spread_xy, max_spread_xy_, spread_yaw, max_spread_yaw_, converged_ ? " — within tolerance, holding" : ""); } /// @brief In tiến độ hội tụ, tối đa một dòng mỗi `kProgressLogPeriod` giây. template void logProgress(const robot::Time& now, const char* format, Args... args) { if (have_progress_log_ && (now - last_progress_log_).toSec() < kProgressLogPeriod) { return; } last_progress_log_ = now; have_progress_log_ = true; char buffer[320]; std::snprintf(buffer, sizeof(buffer), format, args...); robot::log_info("[action_core] '%s': %s", name_.c_str(), buffer); } /// @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 (total_samples_ == 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 (!best_valid_) { // 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(total_samples_) + " sample(s) in " + formatSeconds(elapsed) + " s, need " + std::to_string(min_samples_) + " within any " + formatSeconds(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, best_score_ * 100.0, best_description_.c_str()); tick.message = "action '" + action_id_ + "': detection unstable (best spread xy=" + std::to_string(best_spread_xy_) + " m, yaw=" + std::to_string(best_spread_yaw_) + " rad in " + formatSeconds(elapsed) + " s; limits " + std::to_string(max_spread_xy_) + " m / " + std::to_string(max_spread_yaw_) + " rad)"; return tick; } static std::string formatSeconds(double seconds) { char buffer[32]; std::snprintf(buffer, sizeof(buffer), "%.2f", seconds); return buffer; } /** * @brief Mô tả hình dạng tập mẫu để chẩn đoán một lượt dò hỏng. * * Ba phân vị của độ lệch cộng hộp bao trong frame cố định. Đọc theo cặp: * - `p50` nhỏ mà `p90` lớn: đa số mẫu chụm, một nhúm văng ra — mẫu nhận nhầm ở nguồn. * - `p50` xấp xỉ `p90`: mọi mẫu đều lệch — phép dò thật sự không ổn định. * Hộp bao chỉ ra các mẫu văng nằm ở đâu, thứ mà không con số tổng hợp nào nói được. */ std::string describeSamples(const Sample& centre) const { if (samples_.empty()) { return "no sample to describe"; } std::vector dev; dev.reserve(samples_.size()); double min_x = samples_.front().x; double max_x = min_x; double min_y = samples_.front().y; double max_y = min_y; for (const Sample& s : samples_) { dev.push_back(std::hypot(s.x - centre.x, s.y - centre.y)); min_x = std::min(min_x, s.x); max_x = std::max(max_x, s.x); min_y = std::min(min_y, s.y); max_y = std::max(max_y, s.y); } std::sort(dev.begin(), dev.end()); const auto at = [&dev](double q) { const std::size_t i = std::min(dev.size() - 1, static_cast(dev.size() * q)); return dev[i]; }; char buffer[320]; std::snprintf(buffer, sizeof(buffer), "%zu sample(s) of '%s' in '%s': median=(%.3f, %.3f) yaw=%.4f rad, " "deviation p50=%.3f p90=%.3f max=%.3f m, bbox x=[%.3f, %.3f] y=[%.3f, %.3f]", samples_.size(), frame_.c_str(), ctx_.global_frame.c_str(), centre.x, centre.y, centre.yaw, at(0.5), at(0.9), dev.back(), min_x, max_x, min_y, max_y); return buffer; } /// @note Dùng buffer là member, không phải vector cục bộ: hàm này chạy mỗi khi cửa sổ đổi, tức /// gần như mỗi control cycle. `clear()` giữ nguyên capacity nên sau vài tick đầu là hết cấp /// phát. Vì vậy hàm không `const`. void filter(Sample& out, double& spread_xy, double& spread_yaw) { buf_x_.clear(); buf_y_.clear(); buf_x_.reserve(samples_.size()); buf_y_.reserve(samples_.size()); double sum_sin = 0.0; double sum_cos = 0.0; for (const Sample& s : samples_) { buf_x_.push_back(s.x); buf_y_.push_back(s.y); sum_sin += std::sin(s.yaw); sum_cos += std::cos(s.yaw); } out.x = median(buf_x_); out.y = median(buf_y_); // Gộp góc bằng vector đơn vị. Trung bình số học của các mẫu quanh ±π cho ra ~0 — lệch 180°. out.yaw = std::atan2(sum_sin, sum_cos); // Độ tản đo quanh TÂM ĐÃ LỌC, không phải min-max thô: xem robustSpread. buf_dev_xy_.clear(); buf_dev_yaw_.clear(); buf_dev_xy_.reserve(samples_.size()); buf_dev_yaw_.reserve(samples_.size()); for (const Sample& s : samples_) { buf_dev_xy_.push_back(std::hypot(s.x - out.x, s.y - out.y)); // Lệch góc phải quy về (-pi, pi], nếu không mẫu ở hai bên đường cắt bị tính thành ~2pi. buf_dev_yaw_.push_back( std::fabs(std::atan2(std::sin(s.yaw - out.yaw), std::cos(s.yaw - out.yaw)))); } spread_xy = robustSpread(buf_dev_xy_); spread_yaw = robustSpread(buf_dev_yaw_); } bool publish(const Sample& 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); Sample 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 action_types_; std::string output_frame_; std::string input_frame_; double settle_delay_ = kDefaultSettleDelay; double sample_window_ = kDefaultSampleWindow; int min_samples_ = kDefaultMinSamples; double max_spread_xy_ = kDefaultMaxSpreadXy; double max_spread_yaw_ = kDefaultMaxSpreadYaw; double hold_time_ = kDefaultHoldTime; // [s] 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] robot::Time started_at_; std::string action_id_; std::string frame_; bool simulated_goal_published_ = false; /// Cửa sổ trượt, mẫu cũ nhất ở đầu. Chỉ chứa mẫu trong `sample_window` giây gần nhất. std::vector samples_; /// Tổng mẫu thu được cả lượt. Phân biệt "không thấy gì" với "thấy nhưng publish quá thưa" lúc /// timeout — `samples_.size()` không nói được vì mẫu cũ đã bị cắt khỏi cửa sổ. std::size_t total_samples_ = 0; 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; /// Trạng thái giữ: cửa sổ đang đạt ngưỡng liên tục từ `converged_since_`. bool converged_ = false; robot::Time converged_since_; Sample hold_pose_; /// Cửa sổ tốt nhất từng thấy, chỉ để chẩn đoán lúc timeout — không bao giờ được publish. bool best_valid_ = false; double best_score_ = 0.0; // tỉ lệ so với ngưỡng; < 1.0 nghĩa là đã đạt double best_spread_xy_ = 0.0; // [m] double best_spread_yaw_ = 0.0; // [rad] std::string best_description_; robot::Time last_progress_log_; bool have_progress_log_ = false; /// Buffer dùng lại cho `filter()`: hàm đó chạy gần như mỗi control cycle. std::vector buf_x_; std::vector buf_y_; std::vector buf_dev_xy_; std::vector buf_dev_yaw_; }; } // namespace action_core BOOST_DLL_ALIAS(action_core::FrameSamplerActionHandler::create, FrameSamplerActionHandler)