/********************************************************************* * * Software License Agreement (BSD License) * * recovery_core — phản xạ né khi có vật sát thân: lùi thẳng một đoạn ngắn, không lùi được thì xoay * tại chỗ cho đầu hướng ra phía trống. Vật cản lấy từ điểm lidar thô + ô LETHAL của local costmap, * kiểm bằng footprint thật (không padding), không qua CostmapCollisionChecker. * * Author: DuongTD *********************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "evade_core.h" namespace recovery_plugins { namespace { constexpr double kDefaultMaxScanAge = 0.3; // [s] constexpr double kDefaultBackupDistance = 0.20; // [m] constexpr double kDefaultBackupSpeed = 0.15; // [m/s] độ lớn (4b) constexpr double kDefaultRotateSpeed = 0.5; // [rad/s] độ lớn (4b) constexpr double kDefaultAccLimX = 0.3; // [m/s^2] constexpr double kDefaultAccLimTheta = 0.8; // [rad/s^2] constexpr double kDefaultHeadingStepDeg = 10.0; // [deg] constexpr double kDefaultMotionMargin = 0.05; // [m] (4c) constexpr double kDefaultMinFreeDistance = 0.30; // [m] (4c) constexpr double kDefaultMaxProbeDistance = 1.0; // [m] constexpr double kMaxLinearSpeed = 1.0; // [m/s] trần vệ sinh cho param sai constexpr double kMaxAngularSpeed = 2.0; // [rad/s] trần vệ sinh cho param sai /// [s] TF tại đúng stamp scan chưa có (TF odom->base hay tới sau scan vài ms) thì nhận TF mới nhất /// nếu nó cách stamp không quá mức này. 0.1 s ở 0.15 m/s = 1.5 cm sai lệch vị trí điểm. constexpr double kDefaultMaxTfGap = 0.1; /// [s] Mất dữ liệu ngắn (scan trễ một nhịp, TF lệch) thì đứng yên chờ chừng này rồi mới bỏ cuộc. constexpr double kDefaultViewLossTimeout = 1.0; const std::vector kDefaultScanTopics{"/f_scan", "/b_scan"}; /// Quay vector (x, y, 0) bằng quaternion đơn vị, lấy phần x, y. Lidar lắp ngược (roll = π) vẫn đúng. void rotateXY(const tf3::QuaternionMsg& q, double x, double y, double& out_x, double& out_y) { // v' = v + w·t + u×t với t = 2·(u×v), u = (qx, qy, qz), v = (x, y, 0). const double tx = -2.0 * q.z * y; const double ty = 2.0 * q.z * x; const double tz = 2.0 * (q.x * y - q.y * x); out_x = x + q.w * tx + (q.y * tz - q.z * ty); out_y = y + q.w * ty + (q.z * tx - q.x * tz); } bool finitePose(const evade::Pose2& pose) { return std::isfinite(pose.x) && std::isfinite(pose.y) && std::isfinite(pose.yaw); } evade::Pose2 toPose2(const robot_geometry_msgs::PoseStamped& pose) { return {pose.pose.position.x, pose.pose.position.y, recovery_core::yawOf(pose)}; } double toDeg(double rad) { return rad * 180.0 / evade::kPi; } } // namespace /** * @class EvadeRecovery * @brief Né vật xâm nhập sát thân: lùi `backup_distance`, hoặc xoay tại chỗ tới hướng trống nhất. * * Một plugin gói cả hai động tác (không ghép back_up + rotate) vì mỗi lần detector nổ, route chỉ chạy * một behavior. Quyết định chốt ở `onStart()` (hàm `evade::decide`) — hoặc ở tick đầu tiên có dữ liệu * mới nếu lúc start scan/TF còn trễ — không có động tác nào thì từ chối/hỏng, không làm thêm việc khác. * * Vì sao không dùng `CostmapCollisionChecker`: nó coi ô INSCRIBED (253) là chắn và chỉ quét biên * footprint, nên trong khe hở 3 cm robot bị coi là "chắn" ngay tại chỗ. Ở đây vật cản là điểm lidar * thô (TF tại stamp scan) cộng tâm ô LETHAL (254), kiểm bằng đa giác footprint không padding; biên * `motion_margin` chỉ cộng theo chiều chuyển động. * * An toàn mỗi tick: lấy scan mới nhất, kiểm phần chuyển động CÒN LẠI; bị chắn hay mất pose thì phát * Twist 0 và trả kFailed. Scan quá tuổi / TF lệch thì phát Twist 0 và CHỜ tối đa `view_loss_timeout` * rồi mới kFailed (sim chạy chậm hay trễ một nhịp). Không bao giờ chạy theo dữ liệu cũ. * * Robot differential: lệnh chỉ có `linear.x` (lùi, âm) hoặc `angular.z` (xoay), không bao giờ cả hai, * không `linear.y`. `goal.distance` / `goal.angle` bị bỏ qua: evade tự chọn động tác từ dữ liệu. */ class EvadeRecovery final : public recovery_core::RecoveryBehavior { public: EvadeRecovery() = default; static recovery_core::RecoveryBehavior::RecoveryBehaviorPtr create() { return std::make_shared(); } recovery_core::RecoveryOutputType outputKind() const override { return recovery_core::RecoveryOutputType::kVelocity; } protected: bool onConfigure(robot::NodeHandle& nh) override { double heading_step_deg = kDefaultHeadingStepDeg; nh.param("scan_topics", scan_topics_, kDefaultScanTopics); nh.param("max_scan_age", max_scan_age_, kDefaultMaxScanAge); nh.param("backup_distance", params_.backup_distance, kDefaultBackupDistance); nh.param("backup_speed", limits_.backup_speed, kDefaultBackupSpeed); nh.param("rotate_speed", limits_.rotate_speed, kDefaultRotateSpeed); nh.param("acc_lim_x", limits_.acc_lim_x, kDefaultAccLimX); nh.param("acc_lim_theta", limits_.acc_lim_theta, kDefaultAccLimTheta); nh.param("heading_step_deg", heading_step_deg, kDefaultHeadingStepDeg); nh.param("motion_margin", params_.motion_margin, kDefaultMotionMargin); nh.param("min_free_distance", params_.min_free_distance, kDefaultMinFreeDistance); nh.param("max_probe_distance", params_.max_probe_distance, kDefaultMaxProbeDistance); nh.param("max_tf_gap", max_tf_gap_, kDefaultMaxTfGap); nh.param("view_loss_timeout", view_loss_timeout_, kDefaultViewLossTimeout); nh.param("debug/decision", debug_decision_, true); // Param sai thì từ chối configure (fail loud lúc boot), không âm thầm dùng default: behavior này // lái robot sát vật cản. const auto positive = [](double v) { return std::isfinite(v) && v > 0.0; }; const char* error = nullptr; const auto require = [&error](bool ok, const char* message) { if (!ok && error == nullptr) { error = message; } }; require(!scan_topics_.empty(), "scan_topics is empty"); require(std::none_of(scan_topics_.begin(), scan_topics_.end(), [](const std::string& topic) { return topic.empty(); }), "scan_topics has an empty entry"); require(positive(max_scan_age_), "max_scan_age must be > 0 s"); require(positive(max_tf_gap_), "max_tf_gap must be > 0 s"); require(std::isfinite(view_loss_timeout_) && view_loss_timeout_ >= 0.0 && (timeout() <= 0.0 || view_loss_timeout_ < timeout()), "view_loss_timeout must be in [0, timeout) s"); require(positive(params_.backup_distance), "backup_distance must be > 0 m"); require(positive(limits_.backup_speed) && limits_.backup_speed <= kMaxLinearSpeed, "backup_speed must be in (0, 1.0] m/s"); require(positive(limits_.rotate_speed) && limits_.rotate_speed <= kMaxAngularSpeed, "rotate_speed must be in (0, 2.0] rad/s"); require(positive(limits_.acc_lim_x), "acc_lim_x must be > 0 m/s^2"); require(positive(limits_.acc_lim_theta), "acc_lim_theta must be > 0 rad/s^2"); require(positive(heading_step_deg) && heading_step_deg <= 90.0, "heading_step_deg must be in (0, 90]"); require(positive(params_.motion_margin), "motion_margin must be > 0 m"); require(positive(params_.min_free_distance), "min_free_distance must be > 0 m"); require(positive(params_.max_probe_distance), "max_probe_distance must be > 0 m"); require(params_.min_free_distance <= params_.max_probe_distance, "min_free_distance must be <= max_probe_distance"); if (error != nullptr) { robot::log_error("[recovery_core] '%s': invalid evade parameters: %s.", name().c_str(), error); return false; } params_.heading_step = heading_step_deg * evade::kPi / 180.0; std::string topics; for (const std::string& topic : scan_topics_) { topics += (topics.empty() ? "" : ",") + topic; } robot::log_info("[recovery_core] '%s': evade scans=[%s] max_scan_age=%.2f s max_tf_gap=%.2f s " "view_loss_timeout=%.2f s backup=%.2f m @ " "%.2f m/s rotate=%.2f rad/s acc=%.2f m/s^2 / %.2f rad/s^2 heading_step=%.1f deg " "margin=%.2f m min_free=%.2f m max_probe=%.2f m timeout=%.1f s " "debug/decision=%s", name().c_str(), topics.c_str(), max_scan_age_, max_tf_gap_, view_loss_timeout_, params_.backup_distance, limits_.backup_speed, limits_.rotate_speed, limits_.acc_lim_x, limits_.acc_lim_theta, heading_step_deg, params_.motion_margin, params_.min_free_distance, params_.max_probe_distance, timeout(), debug_decision_ ? "on" : "off"); return true; } bool onStart(const recovery_core::RecoveryGoal& /*goal*/) override { decision_ = evade::Decision(); const char* missing = ctx().local_costmap == nullptr ? "a local costmap" : ctx().sensors == nullptr ? "a sensor store (RecoveryContext::sensors)" : ctx().tf == nullptr ? "a TF buffer" : nullptr; if (missing != nullptr) { robot::log_error("[recovery_core] '%s': evade requires %s; refusing to start.", name().c_str(), missing); return false; } robot_geometry_msgs::PoseStamped start_pose; if (!ctx().pose->getRobotPose(start_pose)) { robot::log_warning("[recovery_core] '%s': could not get a pose at start-up (TF stale?).", name().c_str()); return false; } start_ = toPose2(start_pose); if (!finitePose(start_)) { robot::log_error("[recovery_core] '%s': robot pose is NaN/Inf; refusing to evade.", name().c_str()); return false; } if (!loadFootprint(start_pose.header.frame_id)) { return false; } pending_ = false; view_guard_.reset(); std::vector obstacles; std::string reason; if (!collectObstacles(startTime(), start_, obstacles, reason)) { // Scan trễ một nhịp / TF lệch chút: nhận việc, đứng yên chờ dữ liệu mới (quyết định ở onUpdate). Không di chuyển // theo dữ liệu cũ. view_loss_timeout = 0 giữ hành vi cũ: từ chối ngay. if (view_loss_timeout_ <= 0.0) { robot::log_warning("[recovery_core] '%s': cannot evade without a fresh view: %s.", name().c_str(), reason.c_str()); return false; } robot::log_warning("[recovery_core] '%s': no fresh view at start (%s); holding still up to %.2f s.", name().c_str(), reason.c_str(), view_loss_timeout_); view_guard_.update(false, startTime().toSec(), view_loss_timeout_); pending_ = true; return true; } return commit(start_, obstacles); } /// Chốt động tác từ @p from với @p obstacles và khởi động Executor. false = không động tác nào khả thi (đã log). bool commit(const evade::Pose2& from, const std::vector& obstacles) { start_ = from; decision_ = evade::decide(footprint_, start_, params_, obstacles); executor_.start(footprint_, start_, decision_, params_, limits_); const int headings = static_cast(std::floor(2.0 * evade::kPi / params_.heading_step + 1e-9)); switch (decision_.motion) { case evade::Motion::kNone: // Lý do từ chối là lỗi vận hành cần thấy, không phải log đường đi bình thường: luôn in. robot::log_warning("[recovery_core] '%s': no evade motion is feasible: back-up blocked at " "s=%.2f m, 0 of %d headings reachable with free distance >= %.2f m " "(%zu obstacle points).", name().c_str(), decision_.backup_blocked_at, headings, params_.min_free_distance, obstacles.size()); return false; case evade::Motion::kBackUp: if (debug_decision_) { robot::log_info("[recovery_core] [debug] '%s': evade -> back up %.2f m (rear clear, %zu " "obstacle points).", name().c_str(), params_.backup_distance, obstacles.size()); } break; case evade::Motion::kRotate: if (debug_decision_) { robot::log_info("[recovery_core] [debug] '%s': evade -> rotate %+.1f deg to heading " "%.1f deg, free %.2f m (back-up blocked at s=%.2f m, %d/%d headings " "feasible).", name().c_str(), toDeg(decision_.rotation), toDeg(decision_.heading), decision_.free_distance, decision_.backup_blocked_at, decision_.feasible_headings, headings); } break; case evade::Motion::kAlreadyFacing: if (debug_decision_) { robot::log_info("[recovery_core] [debug] '%s': evade -> already facing the free side " "(free %.2f m, back-up blocked at s=%.2f m); no motion.", name().c_str(), decision_.free_distance, decision_.backup_blocked_at); } break; } return true; } recovery_core::RecoveryResult onUpdate(const robot::Time& now, double dt) override { robot_geometry_msgs::PoseStamped pose; if (!ctx().pose->getRobotPose(pose)) { return stopResult(recovery_core::RecoveryStatus::kFailed) .withMessage("robot pose lost (TF stale?) — stopping the evade"); } const evade::Pose2 current = toPose2(pose); if (pending_ && !finitePose(current)) { return stopResult(recovery_core::RecoveryStatus::kFailed) .withMessage("robot pose is NaN/Inf — stopping the evade"); } // Kiểm lại mỗi tick với scan mới nhất; điểm trong footprint TẠI POSE HIỆN TẠI bị bỏ (cùng luật // lúc start). Pose NaN thì không gom (cửa sổ costmap sẽ vô nghĩa) — Executor tự dừng. std::vector obstacles; std::string reason; if ((pending_ || decision_.motion != evade::Motion::kAlreadyFacing) && finitePose(current)) { const bool seeing = collectObstacles(now, current, obstacles, reason); const bool was_lost = view_guard_.lost(); switch (view_guard_.update(seeing, now.toSec(), view_loss_timeout_)) { case evade::ViewGuard::State::kExpired: return stopResult(recovery_core::RecoveryStatus::kFailed) .withMessage("lost the obstacle view (" + reason + ") — stopping the evade"); case evade::ViewGuard::State::kHolding: if (!was_lost) { robot::log_warning("[recovery_core] '%s': obstacle view lost (%s); holding still up to %.2f s.", name().c_str(), reason.c_str(), view_loss_timeout_); } executor_.hold(); return recovery_core::RecoveryResult::Velocity(robot_geometry_msgs::Twist(), recovery_core::RecoveryStatus::kRunning) .withMessage("waiting for a fresh obstacle view (" + reason + ")"); case evade::ViewGuard::State::kSeeing: if (was_lost && debug_decision_) { robot::log_info("[recovery_core] [debug] '%s': obstacle view is back; evade continues.", name().c_str()); } break; } } if (pending_) { pending_ = false; if (!commit(current, obstacles)) { return stopResult(recovery_core::RecoveryStatus::kFailed).withMessage("no evade motion is feasible"); } } const evade::Tick tick = executor_.tick(current, obstacles, dt); if (tick.status == evade::TickStatus::kSucceeded) { return stopResult(recovery_core::RecoveryStatus::kSucceeded) .withProgress(1.0, 0.0) .withMessage(tick.message); } if (tick.status == evade::TickStatus::kFailed) { return stopResult(recovery_core::RecoveryStatus::kFailed).withMessage(tick.message); } robot_geometry_msgs::Twist command; command.linear.x = tick.vx; // [m/s], âm = lùi command.angular.z = tick.wz; // [rad/s], + = ngược chiều kim đồng hồ return recovery_core::RecoveryResult::Velocity(command, recovery_core::RecoveryStatus::kRunning) .withProgress(tick.progress, tick.remaining) .withMessage(tick.message); } recovery_core::RecoveryResult onCancel() override { return stopResult(recovery_core::RecoveryStatus::kCancelled).withMessage("evade cancelled"); } private: /// Chụp footprint không padding lúc start (dữ liệu, không giữ con trỏ costmap qua các tick). bool loadFootprint(const std::string& pose_frame) { const robot_costmap_2d::Costmap2DROBOT* costmap = ctx().local_costmap; if (!pose_frame.empty() && pose_frame != costmap->getGlobalFrameID()) { robot::log_error("[recovery_core] '%s': robot pose is in '%s' but the local costmap is in " "'%s'; refusing to evade.", name().c_str(), pose_frame.c_str(), costmap->getGlobalFrameID().c_str()); return false; } footprint_.clear(); for (const robot_geometry_msgs::Point& p : costmap->getUnpaddedRobotFootprint()) { if (!std::isfinite(p.x) || !std::isfinite(p.y)) { robot::log_error("[recovery_core] '%s': footprint has a NaN/Inf vertex; refusing to evade.", name().c_str()); return false; } footprint_.push_back({p.x, p.y}); } if (footprint_.size() < 3) { robot::log_error("[recovery_core] '%s': unpadded footprint has %zu vertices (need >= 3); " "refusing to evade.", name().c_str(), footprint_.size()); return false; } r_max_ = evade::circumradius(footprint_); return true; } /// [m] chỉ vật cản trong bán kính này mới ảnh hưởng tới lùi, cung xoay và d(ψ). double collectRadius() const { return r_max_ + params_.max_probe_distance + params_.motion_margin; } /** * @brief Gom vật cản quanh @p around (frame global của local costmap): điểm lidar của mọi topic * trong `scan_topics` + tâm ô LETHAL. Điểm trong footprint tại @p around bị bỏ. * @return false (kèm @p reason) khi thiếu scan, scan quá tuổi so với @p now, hoặc thiếu TF. */ bool collectObstacles(const robot::Time& now, const evade::Pose2& around, std::vector& out, std::string& reason) const { robot_costmap_2d::Costmap2DROBOT* costmap = ctx().local_costmap; if (costmap == nullptr || ctx().sensors == nullptr || ctx().tf == nullptr) { reason = "local costmap, sensor store or TF buffer is gone"; return false; } const std::string& frame = costmap->getGlobalFrameID(); const double radius = collectRadius(); std::vector points; for (const std::string& topic : scan_topics_) { uint64_t since = 0; // luôn lấy scan mới nhất; tuổi kiểm bằng stamp bên dưới const auto scan = robot_sensor_ports::latest(*ctx().sensors, topic, since); if (!scan) { reason = "no LaserScan on " + topic; return false; } const robot::Time stamp = scan->header.stamp; const double age = (now - stamp).toSec(); if (!std::isfinite(age) || std::abs(age) > max_scan_age_) { reason = topic + " is stale (age " + std::to_string(age) + " s, max_scan_age " + std::to_string(max_scan_age_) + " s)"; return false; } tf3::TransformStampedMsg transform; if (!lookup(frame, scan->header.frame_id, stamp, transform, reason)) { return false; } const tf3::QuaternionMsg& q = transform.transform.rotation; const tf3::Vector3Msg& t = transform.transform.translation; for (std::size_t i = 0; i < scan->ranges.size(); ++i) { const double r = scan->ranges[i]; if (!std::isfinite(r) || r < scan->range_min || r > scan->range_max) { continue; } const double angle = scan->angle_min + static_cast(i) * scan->angle_increment; double x = 0.0; double y = 0.0; rotateXY(q, r * std::cos(angle), r * std::sin(angle), x, y); points.push_back({x + t.x, y + t.y}); } } robot_costmap_2d::Costmap2D* grid = costmap->getCostmap(); if (grid == nullptr) { reason = "local costmap has no grid"; return false; } { std::lock_guard lock(*grid->getMutex()); int x0 = 0; int y0 = 0; int x1 = 0; int y1 = 0; grid->worldToMapEnforceBounds(around.x - radius, around.y - radius, x0, y0); grid->worldToMapEnforceBounds(around.x + radius, around.y + radius, x1, y1); for (int my = y0; my <= y1; ++my) { for (int mx = x0; mx <= x1; ++mx) { // Chỉ LETHAL: ô 253 (inscribed) là vùng thổi phồng, không phải vật — tính nó vào thì khe // hở 3 cm thành "chắn". Unknown cũng không phải vật. if (grid->getCost(mx, my) != robot_costmap_2d::LETHAL_OBSTACLE) { continue; } double wx = 0.0; double wy = 0.0; grid->mapToWorld(mx, my, wx, wy); points.push_back({wx, wy}); } } } out = evade::keepOutsideFootprint(footprint_, around, radius, points); return true; } /// TF @p target <- @p source tại stamp scan; chưa có thì TF mới nhất nếu cách stamp <= max_tf_gap. bool lookup(const std::string& target, const std::string& source, const robot::Time& stamp, tf3::TransformStampedMsg& out, std::string& reason) const { try { out = ctx().tf->lookupTransform(target, source, tf3::Time(stamp.sec, stamp.nsec)); } catch (const std::exception&) { try { out = ctx().tf->lookupTransform(target, source, tf3::Time()); } catch (const std::exception& e) { reason = "no TF " + target + " <- " + source + " (" + e.what() + ")"; return false; } const double gap = std::abs(out.header.stamp.toSec() - stamp.toSec()); if (!std::isfinite(gap) || gap > max_tf_gap_) { reason = "TF " + target + " <- " + source + " is " + std::to_string(gap) + " s away from the scan stamp"; return false; } } const tf3::QuaternionMsg& q = out.transform.rotation; const double norm = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w; if (!std::isfinite(norm) || std::abs(norm - 1.0) > 0.01 || !std::isfinite(out.transform.translation.x) || !std::isfinite(out.transform.translation.y)) { reason = "invalid TF " + target + " <- " + source; return false; } return true; } // Config std::vector scan_topics_ = kDefaultScanTopics; double max_scan_age_ = kDefaultMaxScanAge; ///< [s] double max_tf_gap_ = kDefaultMaxTfGap; ///< [s] double view_loss_timeout_ = kDefaultViewLossTimeout; ///< [s] 0 = bỏ cuộc ngay khi mất dữ liệu evade::Params params_; evade::MotionLimits limits_{kDefaultBackupSpeed, kDefaultRotateSpeed, kDefaultAccLimX, kDefaultAccLimTheta}; bool debug_decision_ = true; // Trạng thái lượt hiện tại evade::Polygon footprint_; ///< frame base, không padding double r_max_ = 0.0; ///< [m] evade::Pose2 start_; evade::Decision decision_; evade::Executor executor_; evade::ViewGuard view_guard_; bool pending_ = false; ///< nhận việc nhưng chưa có dữ liệu mới để chốt động tác }; } // namespace recovery_plugins RECOVERY_CORE_EXPORT_BEHAVIOR(recovery_plugins::EvadeRecovery::create, EvadeRecovery)