/********************************************************************* * * 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 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 kDefaultTimeout = 15.0; // [s] 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)); } /// @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. 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). */ 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 * * Độ tản vượt `max_spread_*` → `kFailed`. Dữ liệu tản nghĩa là **chưa nhìn rõ**, và trung bình của * dữ liệu rác vẫn là rác. 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. * * 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] thời lượng thu mẫu * - `min_samples` [int] ít hơn → kFailed * - `max_spread_xy` [m] tản hơn → kFailed * - `max_spread_yaw` [rad] * - `timeout` [s] lưới cuối tầng 1 * - `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("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 (timeout_ > 0.0 && timeout_ <= settle_delay_ + sample_window_) { // Timeout ngắn hơn thời gian thu mẫu thì action LUÔN hỏng — gần như chắc chắn gõ nhầm. robot::log_error("[action_core] '%s': timeout=%.3f s <= settle_delay+sample_window=%.3f s; " "the action would always fail.", name_.c_str(), timeout_, settle_delay_ + sample_window_); 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; samples_.clear(); have_last_stamp_ = false; 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] // Timeout TẦNG 1: frame thô không bao giờ xuất hiện thì phải thoát, không treo control loop. if (timeout_ > 0.0 && elapsed >= timeout_) { tick.status = ActionStatus::kFailed; tick.message = "action '" + action_id_ + "': frame '" + frame_ + "' did not appear in time"; return tick; } // 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_) { collectSample(); } if (elapsed < settle_delay_ + sample_window_) { tick.status = ActionStatus::kRunning; return tick; } if (static_cast(samples_.size()) < min_samples_) { tick.status = ActionStatus::kFailed; tick.message = "action '" + action_id_ + "': only " + std::to_string(samples_.size()) + " sample(s) of '" + frame_ + "', need " + std::to_string(min_samples_); return tick; } Sample filtered; double spread_xy = 0.0; double spread_yaw = 0.0; filter(filtered, spread_xy, spread_yaw); if (spread_xy > max_spread_xy_ || spread_yaw > max_spread_yaw_) { // Thấy, nhưng không đáng tin. 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ý. tick.status = ActionStatus::kFailed; tick.message = "action '" + action_id_ + "': detection unstable (spread xy=" + std::to_string(spread_xy) + " m, yaw=" + std::to_string(spread_yaw) + " rad)"; return tick; } if (!publish(filtered, 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)"; 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ũ. samples_.clear(); have_last_stamp_ = false; simulated_goal_published_ = false; } private: struct Sample { double x = 0.0; double y = 0.0; double yaw = 0.0; // [rad] }; 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 Đọc một mẫu MỚI của frame thô, quy về global frame. Mẫu trùng timestamp bị bỏ. void collectSample() { tf3::TransformStampedMsg tf; try { tf = ctx_.tf->lookupTransform(ctx_.global_frame, frame_, tf3::Time()); } catch (const std::exception&) { return; // 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; } 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); samples_.push_back(s); } void filter(Sample& out, double& spread_xy, double& spread_yaw) const { std::vector xs, ys; xs.reserve(samples_.size()); ys.reserve(samples_.size()); double sum_sin = 0.0; double sum_cos = 0.0; for (const Sample& s : samples_) { xs.push_back(s.x); ys.push_back(s.y); sum_sin += std::sin(s.yaw); sum_cos += std::cos(s.yaw); } out.x = median(xs); out.y = median(ys); // 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. std::vector dev_xy; std::vector dev_yaw; dev_xy.reserve(samples_.size()); dev_yaw.reserve(samples_.size()); for (const Sample& s : samples_) { 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. dev_yaw.push_back( std::fabs(std::atan2(std::sin(s.yaw - out.yaw), std::cos(s.yaw - out.yaw)))); } spread_xy = robustSpread(std::move(dev_xy)); spread_yaw = robustSpread(std::move(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 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_; std::vector samples_; tf3::Time last_stamp_; bool have_last_stamp_ = false; bool simulated_goal_published_ = false; }; } // namespace action_core BOOST_DLL_ALIAS(action_core::FrameSamplerActionHandler::create, FrameSamplerActionHandler)