DetourPathRecovery was the one recovery behavior that mattered for the onCancelRequested() fix in recovery_core (commit 254c7fc): it calls SBPLDetourPlanner::makePlan() synchronously from update(), which runs on the control thread — cancel arriving mid-search had nothing to preempt it with, and the control loop itself would stall for the remainder of allocated_time. - Moves the search to a per-attempt worker thread (startWorker/workerBody/ planInto/finishAttempt/waitWorker/joinWorker/requestWorkerStop); update() only polls. - onCancelRequested() (new override): preempts via robot_nav_core::Preemptable if the inner planner supports it (see Test/sbpl_lattice_planner), then waits up to cancel_join_timeout (0.2 s) and joins — cancel now actually blocks until the worker is gone, not just until a flag is set. - onStart() joins a stale worker from a previous attempt before starting a new one; destructor joins too. - async_planning param (default true) so tests can force the old synchronous path when they need deterministic single-thread timing. - Uses RECOVERY_CORE_EXPORT_BEHAVIOR for the ABI version symbol. - test/plugins/test_line_planner.cpp: added plan_delay (simulate a slow search) and made it Preemptable, exported as TestSlowPlanner, to drive the new worker-thread cancel tests. Depends on recovery_core commit 254c7fc (onCancelRequested hook + ABI macro) and Test/sbpl_lattice_planner commit 7456e99 (Preemptable pattern this follows). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1136 lines
53 KiB
C++
1136 lines
53 KiB
C++
/*********************************************************************
|
||
*
|
||
* Software License Agreement (BSD License)
|
||
*
|
||
* sbpl_recovery — recovery họ path: lập đường vòng quanh vật cản rồi NỐI LẠI global plan hiện hành.
|
||
*
|
||
* Port từ `navigation_experimental/sbpl_recovery` (Eitan Marder-Eppstein, BSD) sang khuôn
|
||
* `recovery_core`. Hai khác biệt có chủ đích so với bản gốc:
|
||
*
|
||
* 1. Bản gốc TỰ LÁI: chạy pose_follower bên trong và publish thẳng cmd_vel — hai nguồn vận tốc
|
||
* song song với move_base. Ở đây behavior thuộc họ `kPath`: nó chỉ TRẢ VỀ đường vòng; runtime
|
||
* áp path đó và local planner đang active bám theo (một nguồn vận tốc duy nhất, đúng D8).
|
||
* 2. Bản gốc nhận plan qua topic; ở đây plan đến từ `RecoveryContext::plan` — chính plan mà
|
||
* control loop đang bám, không lệch phiên bản.
|
||
*
|
||
* Đường vòng được NỐI với phần còn lại của plan cũ (splice): contract 2026-08-04b không replan sau
|
||
* recovery, nên path trả về phải đi tới đích của CHẶNG, không phải chỉ tới điểm nối — nếu không
|
||
* robot sẽ báo "tới đích" ngay tại điểm nối giữa tuyến.
|
||
*
|
||
* Author: DuongTD
|
||
*********************************************************************/
|
||
|
||
#include <algorithm>
|
||
#include <atomic>
|
||
#include <chrono>
|
||
#include <cmath>
|
||
#include <condition_variable>
|
||
#include <cstddef>
|
||
#include <functional>
|
||
#include <limits>
|
||
#include <memory>
|
||
#include <mutex>
|
||
#include <string>
|
||
#include <thread>
|
||
#include <vector>
|
||
|
||
#include <boost/dll/alias.hpp>
|
||
#include <boost/dll/import.hpp>
|
||
#include <boost/system/system_error.hpp>
|
||
#include <boost/thread/locks.hpp>
|
||
|
||
#include <robot/node_handle.h>
|
||
#include <robot/plugin_loader_helper.h>
|
||
#include <robot/robot.h>
|
||
#include <robot_costmap_2d/cost_values.h>
|
||
#include <robot_costmap_2d/costmap_2d.h>
|
||
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||
#include <robot_nav_core/base_global_planner.h>
|
||
#include <robot_nav_core/preemptable.h>
|
||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||
#include <tf3/buffer_core.h>
|
||
|
||
#include <recovery_core/adapters/costmap_collision_checker.h>
|
||
#include <recovery_core/recovery_abi.h>
|
||
#include <recovery_core/recovery_behavior.h>
|
||
|
||
#include <sbpl_recovery/merge_grids.h>
|
||
|
||
namespace sbpl_recovery
|
||
{
|
||
namespace
|
||
{
|
||
constexpr int kDefaultAttemptsPerRun = 3;
|
||
|
||
/// [m] Gần đích hơn mức này thì không lập nữa: một đường tới chính chỗ đang đứng chỉ có một pose,
|
||
/// tầng trên nhận rồi báo hỏng ngay chu kỳ sau. Chọn nhỏ hơn `xy_goal_tolerance` của mọi profile
|
||
/// để behavior không bao giờ là thứ chặn robot hoàn tất chặng.
|
||
constexpr double kMinGoalDistance = 0.10;
|
||
constexpr double kSpacingEpsilon = 1e-6; // [m]
|
||
constexpr double kReferencePlanLogThrottle = 10.0; // [s]
|
||
|
||
double sqDistance(const robot_geometry_msgs::PoseStamped& a,
|
||
const robot_geometry_msgs::PoseStamped& b)
|
||
{
|
||
const double dx = a.pose.position.x - b.pose.position.x;
|
||
const double dy = a.pose.position.y - b.pose.position.y;
|
||
return dx * dx + dy * dy;
|
||
}
|
||
|
||
/// [m] Khoảng cách từ điểm tới đoạn thẳng.
|
||
double pointToSegment(double px, double py, double ax, double ay, double bx, double by)
|
||
{
|
||
const double dx = bx - ax;
|
||
const double dy = by - ay;
|
||
const double len_sq = dx * dx + dy * dy;
|
||
|
||
if (len_sq <= 1e-12)
|
||
{
|
||
return std::hypot(px - ax, py - ay);
|
||
}
|
||
|
||
double t = ((px - ax) * dx + (py - ay) * dy) / len_sq;
|
||
t = std::max(0.0, std::min(1.0, t));
|
||
return std::hypot(px - (ax + t * dx), py - (ay + t * dy));
|
||
}
|
||
|
||
/**
|
||
* @brief [m] Độ lệch lớn nhất của @p detour so với đoạn plan gốc `plan[0..rejoin]`.
|
||
*
|
||
* Đây là guard cho ràng buộc lệch tuyến của fleet: order chỉ định tuyến, robot chỉ được rời khỏi nó
|
||
* trong một hành lang cho phép. Đo so với **plan gốc** chứ không so với đường thẳng nối hai đầu —
|
||
* plan gốc mới là thứ fleet đã duyệt.
|
||
*/
|
||
double maxDeviation(const std::vector<robot_geometry_msgs::PoseStamped>& plan, std::size_t rejoin,
|
||
const std::vector<robot_geometry_msgs::PoseStamped>& detour)
|
||
{
|
||
if (plan.size() < 2 || detour.empty())
|
||
{
|
||
return 0.0;
|
||
}
|
||
|
||
const std::size_t last = std::min(rejoin, plan.size() - 1);
|
||
double worst = 0.0;
|
||
|
||
for (const robot_geometry_msgs::PoseStamped& pose : detour)
|
||
{
|
||
double best = std::numeric_limits<double>::max();
|
||
for (std::size_t i = 0; i < last; ++i)
|
||
{
|
||
best = std::min(best, pointToSegment(pose.pose.position.x, pose.pose.position.y,
|
||
plan[i].pose.position.x, plan[i].pose.position.y,
|
||
plan[i + 1].pose.position.x,
|
||
plan[i + 1].pose.position.y));
|
||
}
|
||
worst = std::max(worst, best);
|
||
}
|
||
|
||
return worst;
|
||
}
|
||
} // namespace
|
||
|
||
/**
|
||
* @class DetourPathRecovery
|
||
* @brief Lập LẠI CẢ ĐƯỜNG tới đích của chặng bằng một global planner plugin (mặc định SBPL).
|
||
*
|
||
* Thuật toán:
|
||
* 1. `onStart`: chụp tuyến của chặng (tham chiếu, rơi về plan đang bám), lấy pose CUỐI làm đích.
|
||
* 2. Mỗi `update()` chạy một lượt makePlan(pose hiện tại → đích chặng) trên costmap đã chọn.
|
||
* Thành công → trả NGUYÊN đường vừa lập, `kSucceeded`. Hết `attempts_per_run` → `kFailed`,
|
||
* state machine chuyển behavior kế tiếp của route.
|
||
*
|
||
* ## Vì sao không còn "đường vòng nối lại plan" (2026-09-02)
|
||
*
|
||
* Bản trước vá một đoạn vào tuyến đang chạy nên phải CHỌN điểm nối, và việc chọn đó là nguồn của
|
||
* lớp lỗi nặng nhất gói này từng có. Bộ chọn chỉ đo khoảng cách Euclid tới robot, không có khái
|
||
* niệm "phía trước": một pose 3 m sau lưng là ứng viên hợp lệ. Con trỏ quét còn tụt về đầu tuyến
|
||
* khi robot cách mọi pose hơn `planning_distance`, mà trigger `off_path` lại bắn ở ngưỡng LỚN HƠN
|
||
* mức đó — nên ca xấu nhất là ca chắc chắn xảy ra.
|
||
*
|
||
* Sim 28/8/2026 (mission 8): nối tại index 0/279 — quay về vạch xuất phát. SBPL nối bằng cung (bộ
|
||
* mprim phạt xoay tại chỗ ×20) nên ra một đường KHÉP KÍN: winding +272°, tự cắt 1 lần, hai đoạn
|
||
* cách nhau 6.8 m theo arc mà áp sát 0.10 m. Robot bám vòng đó 244 giây, con trỏ index nhảy lùi 32
|
||
* lần, không thoát. Chi tiết: `Test/SBPL_RECOVERY_AUDIT.md`.
|
||
*
|
||
* Lập một đường LIỀN thì không còn gì để chọn sai: một lượt A* là một đường đi trong đồ thị, mỗi
|
||
* state thăm một lần — không tự cắt, không tự vòng. Không mối nối cũng đồng nghĩa không đoạn đuôi
|
||
* phải ghép, tức mất luôn nguồn tự cắt thứ hai. Đo trên cùng log: 7 lượt plan đầy đủ đều cho
|
||
* `arc/chord = 1.01`, `self_cross = 0`; 11 lượt detour cho 1.05–1.98.
|
||
*
|
||
* ## Ba chế độ costmap (`costmap_source`)
|
||
*
|
||
* - `combined` (khuyến nghị, xem `DETOUR_MERGED_GRID_PLAN.md`): LƯỚI GỘP — snapshot global làm
|
||
* nền (tường/kệ tĩnh, phủ toàn bản đồ) rồi đè cửa sổ local lên (vật cản sensor tươi). Mutex hai
|
||
* costmap chỉ bị giữ trong lúc copy (~vài ms); SBPL search trên bản chụp KHÔNG giữ mutex nào —
|
||
* map update không bao giờ bị planner bỏ đói. Một frame (map), một nguồn sự thật. Cần planner
|
||
* export capability `<symbol>ExternalGrid` (sbpl_lattice_planner có sẵn).
|
||
* - `local`: chỉ cửa sổ lăn — cho hệ không có global costmap; điểm nối kẹt trong cửa sổ.
|
||
* - `global`: chỉ lưới tĩnh — cho hệ mà global có nạp obstacle. Đã đo trên sim 2026-08-05: global
|
||
* KHÔNG nạp sensor thì goal nào SBPL cũng vẽ xuyên đúng chỗ vật cản tươi — đừng dùng khi đó.
|
||
*
|
||
* ## Timing
|
||
*
|
||
* `onUpdate` chạy trên control thread. Một lượt makePlan trên cửa sổ local là lời gọi "nặng" so
|
||
* với khuyến cáo của hook, nhưng CHỦ ĐÍCH chấp nhận: trong RECOVERING họ path robot đứng yên
|
||
* (velocity source = kNone), một cycle giãn ra không làm sai lệnh nào — cùng ngân sách thời gian
|
||
* mà recovery blocking của move_base gen-1 vẫn dùng. Mỗi tick chỉ chạy một lượt planner, nên trần
|
||
* trên từng cycle là một lượt makePlan duy nhất.
|
||
*
|
||
* Param (namespace của instance):
|
||
* - `planner_name` [string, "SBPLLatticePlanner"] tên instance planner: vừa là namespace đọc
|
||
* param, vừa là tên truyền vào `initialize()`. Đổi nó = có một instance tuning
|
||
* riêng (vd `allocated_time` ngắn cho detour) mà không đụng bản dùng chung.
|
||
* - `planner_symbol` [string, = planner_name] alias Boost.DLL **có thật** trong `.so`, và cũng là
|
||
* khoá tra `<planner_symbol>/library_path`. Chỉ cần khai khi `planner_name`
|
||
* không phải một alias có thật — đúng trường hợp `SBPLLatticePlanner`, vốn chỉ
|
||
* export một symbol duy nhất (khác bộ local planner, nơi mỗi biến thể là một
|
||
* class riêng có alias riêng).
|
||
* - `use_global_costmap` [bool, false] legacy; `costmap_source` khai thì thắng.
|
||
* - `planning_distance` [m, 2.0] điểm nối cách robot tối thiểu chừng này.
|
||
* - `sample_step` [m, 0.5] khoảng cách dọc plan giữa hai ứng viên liên tiếp.
|
||
* - `rejoin_clearance` [m, 0.5] điểm nối phải cách pose bẩn gần nhất (CẢ HAI PHÍA dọc
|
||
* plan) ít nhất chừng này. Sát mép vật cản thì đường vòng
|
||
* gần như luôn đâm vào vùng đệm của chính nó.
|
||
* - `max_rejoin_distance` [m, 0 = không giới hạn] TRẦN quét dọc plan, thuần tuỳ chọn: quét luôn
|
||
* tự dừng ở rìa lưới (`kOutside`) hoặc cuối plan. Đừng đặt
|
||
* nhỏ: sim 2026-08-05 hai lần liền cap cắt quét ngay sau
|
||
* pose bẩn cuối và báo "không có chỗ sạch" dù chưa nhìn tiếp.
|
||
* - `attempts_per_run` [int, 3] số ứng viên tối đa một lượt.
|
||
* - `rejoin_on` [string, "reference"] tuyến để nối lại: `reference` = tuyến GỐC của chặng (plan
|
||
* do planner sinh — detour tự kéo robot về tuyến order, và
|
||
* `max_deviation` đo đúng hành lang fleet đã duyệt);
|
||
* `current` = plan đang bám (hành vi cũ, tuyến trôi dần qua
|
||
* từng lượt detour). Runtime không cấp tuyến tham chiếu thì
|
||
* tự quay về `current` kèm cảnh báo.
|
||
* - `timeout` [s] trần lượt, base cưỡng chế (0 = không giới hạn).
|
||
* - `lock_costmap` [bool, true] giữ mutex costmap quanh makePlan (giao thức với
|
||
* map-update thread). CHỈ unit test với costmap placeholder được tắt.
|
||
* - `costmap_frame_override` [string, ""] frame của costmap khi không dereference được costmap.
|
||
* CHỈ dành cho unit test với costmap placeholder.
|
||
*/
|
||
class DetourPathRecovery final : public recovery_core::RecoveryBehavior
|
||
{
|
||
public:
|
||
DetourPathRecovery() = default;
|
||
|
||
static recovery_core::RecoveryBehavior::RecoveryBehaviorPtr create()
|
||
{
|
||
return std::make_shared<DetourPathRecovery>();
|
||
}
|
||
|
||
recovery_core::RecoveryOutputType outputKind() const override
|
||
{
|
||
return recovery_core::RecoveryOutputType::kPath;
|
||
}
|
||
|
||
~DetourPathRecovery() override
|
||
{
|
||
// Worker có thể còn chạy nếu lượt bị huỷ mà planner không preempt được: cắt rồi join — huỷ
|
||
// object trong lúc worker còn đụng member là use-after-free.
|
||
requestWorkerStop();
|
||
joinWorker();
|
||
}
|
||
|
||
/**
|
||
* @brief Hook đồng bộ khi bị huỷ (recovery_core, 2026-09-11): cắt lượt makePlan đang chạy.
|
||
*
|
||
* Chạy trên control thread. `preempt()` trên planner (nếu nó là Preemptable) làm ARA* thoát trong
|
||
* vài ms; đợi worker tối đa `cancel_join_timeout` rồi join. Quá trần = planner không tuân preempt
|
||
* (libsbpl cũ, hoặc plugin khác) — log LỖI, không tắt được; worker được join ở onStart kế/dtor.
|
||
*/
|
||
void onCancelRequested() override
|
||
{
|
||
if (!workerRunning())
|
||
{
|
||
return;
|
||
}
|
||
requestWorkerStop();
|
||
if (!waitWorker(cancel_join_timeout_))
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': planner '%s' did not return %.2f s after preempt — "
|
||
"the cancelled search keeps running in the background (does the planner "
|
||
"implement robot_nav_core::Preemptable, and does libsbpl have the abort "
|
||
"flag?).",
|
||
name().c_str(), planner_name_.c_str(), cancel_join_timeout_);
|
||
return;
|
||
}
|
||
joinWorker();
|
||
}
|
||
|
||
protected:
|
||
bool onConfigure(robot::NodeHandle& nh) override
|
||
{
|
||
nh.param("planner_name", planner_name_, std::string("SBPLLatticePlanner"));
|
||
// Symbol Boost.DLL mặc định TRÙNG tên instance. Tách ra vì hai thứ này chỉ trùng nhau khi mỗi
|
||
// biến thể planner là một class riêng có alias riêng (như bộ local planner). `SBPLLatticePlanner`
|
||
// chỉ export ĐÚNG MỘT symbol, nên muốn một instance SBPL riêng cho detour (allocated_time ngắn
|
||
// để không treo control thread) thì phải nạp cùng symbol đó nhưng đọc param từ namespace khác.
|
||
nh.param("planner_symbol", planner_symbol_, planner_name_);
|
||
// "local" | "global" | "combined". Khai thì thắng `use_global_costmap` (giữ để tương thích).
|
||
nh.param("costmap_source", costmap_source_, std::string());
|
||
nh.param("use_global_costmap", use_global_costmap_, false);
|
||
// `planning_distance` / `sample_step` / `rejoin_clearance` / `max_rejoin_distance` đã bị GỠ
|
||
// 2026-09-02 cùng với mô hình detour: chúng chỉ phục vụ việc quét chọn điểm nối, mà behavior
|
||
// này không còn nối vào tuyến cũ nữa. Để nguyên trong YAML thì vô hại (không ai đọc), nhưng
|
||
// nên dọn để khỏi có người chỉnh rồi chờ hiệu ứng không bao giờ tới.
|
||
nh.param("attempts_per_run", attempts_per_run_, kDefaultAttemptsPerRun);
|
||
// [s] Trần đợi worker thoát khi bị cancel/pause. Với planner preempt được là vài ms; đặt đủ dư.
|
||
nh.param("cancel_join_timeout", cancel_join_timeout_, 0.2);
|
||
// true (mặc định): makePlan chạy trên worker thread, control thread không kẹt. false: chạy
|
||
// đồng bộ trong onUpdate như trước 2026-09-11 — chỉ cho planner giả tức thì trong unit test,
|
||
// hoặc đường lùi khi cần tái hiện hành vi cũ.
|
||
nh.param("async_planning", async_planning_, true);
|
||
nh.param("max_deviation", max_deviation_, 0.0);
|
||
// "reference" | "current". Xem @ref rejoin_on_ và RecoveryContext::reference_plan.
|
||
nh.param("rejoin_on", rejoin_on_, std::string("reference"));
|
||
nh.param("lock_costmap", lock_costmap_, true);
|
||
nh.param("costmap_frame_override", costmap_frame_override_, std::string());
|
||
|
||
if (rejoin_on_ != "reference" && rejoin_on_ != "current")
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': rejoin_on='%s' must be reference | current.",
|
||
name().c_str(), rejoin_on_.c_str());
|
||
return false;
|
||
}
|
||
|
||
if (planner_name_.empty() || planner_symbol_.empty())
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': planner_name/planner_symbol must not be empty.",
|
||
name().c_str());
|
||
return false;
|
||
}
|
||
|
||
if (costmap_source_.empty())
|
||
{
|
||
costmap_source_ = use_global_costmap_ ? "global" : "local";
|
||
}
|
||
if (costmap_source_ != "local" && costmap_source_ != "global" && costmap_source_ != "combined")
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': costmap_source='%s' must be local | global | "
|
||
"combined.", name().c_str(), costmap_source_.c_str());
|
||
return false;
|
||
}
|
||
// combined = LƯỚI GỘP (2026-08-05, vòng 3): global nền + local đè, SBPL initialize trên GLOBAL
|
||
// (env theo kích thước lưới gộp) và nhận bản chụp gộp qua capability ExternalGrid mỗi attempt.
|
||
// Nguyên lý không đổi: người LẬP đường phải nhìn thấy vật cản tươi — giờ nhìn qua lưới gộp.
|
||
use_global_costmap_ = costmap_source_ != "local";
|
||
if (attempts_per_run_ < 1)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': attempts_per_run=%d must be >= 1.", name().c_str(),
|
||
attempts_per_run_);
|
||
return false;
|
||
}
|
||
if (!std::isfinite(max_deviation_) || max_deviation_ < 0.0)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': max_deviation=%.3f m must be >= 0 (0 = no limit).",
|
||
name().c_str(), max_deviation_);
|
||
return false;
|
||
}
|
||
|
||
// Họ path không bị base bắt buộc có pose, nhưng behavior NÀY cần: điểm nối chọn theo khoảng
|
||
// cách tới robot. Chặn ở boot thay vì lượt chạy đầu tiên.
|
||
if (ctx().pose == nullptr)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': needs a PoseProvider to pick a rejoin point.",
|
||
name().c_str());
|
||
return false;
|
||
}
|
||
|
||
robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap();
|
||
if (costmap == nullptr)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': the %s costmap is missing from the context.",
|
||
name().c_str(), use_global_costmap_ ? "global" : "local");
|
||
return false;
|
||
}
|
||
if (costmap_source_ == "combined" && costmap_frame_override_.empty() &&
|
||
ctx().local_costmap == nullptr)
|
||
{
|
||
// Lưới gộp cần CẢ HAI nguồn — thiếu mắt tươi thì đây chỉ còn là mode "global", và mode đó
|
||
// đã được đo là mù vật cản sensor. Bắt lỗi cấu hình ở boot thay vì chạy sai âm thầm.
|
||
robot::log_error("[sbpl_recovery] '%s': costmap_source=combined needs BOTH costmaps but the "
|
||
"local costmap is missing from the context.", name().c_str());
|
||
return false;
|
||
}
|
||
|
||
return loadPlanner(costmap);
|
||
}
|
||
|
||
bool onStart(const recovery_core::RecoveryGoal& /*goal*/) override
|
||
{
|
||
robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap();
|
||
if (costmap == nullptr)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': costmap disappeared from the context.",
|
||
name().c_str());
|
||
return false;
|
||
}
|
||
|
||
// Con trỏ costmap là non-owning và CÓ THỂ bị thay giữa hai lượt (contract của RecoveryContext).
|
||
// Planner đã initialize() với con trỏ cũ thì phải dựng lại — dùng tiếp là đọc một costmap chết.
|
||
if (costmap != initialized_costmap_ && !loadPlanner(costmap))
|
||
{
|
||
return false;
|
||
}
|
||
|
||
// Costmap quá hạn = lưới đang mô tả một thế giới của quá khứ. Lập đường vòng trên nó là sinh
|
||
// ra một plan trông hợp lệ nhưng vô nghĩa (sim 2026-08-05: detour 22-31 pose trên map cũ ngay
|
||
// sau khi chính attempt SBPL trước đó bỏ đói map update). Từ chối kèm lý do; gate qua test seam
|
||
// vì costmap placeholder của unit test không dereference được.
|
||
if (costmap_frame_override_.empty())
|
||
{
|
||
const bool chosen_current = costmap->isCurrent();
|
||
const bool local_current = costmap_source_ != "combined" ||
|
||
ctx().local_costmap == nullptr ||
|
||
ctx().local_costmap->isCurrent();
|
||
if (!chosen_current || !local_current)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': refusing to start — the %s costmap is stale "
|
||
"(planning on a past world produces junk detours).",
|
||
name().c_str(), !chosen_current
|
||
? (use_global_costmap_ ? "global" : "local")
|
||
: "local");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// Tuyến để NỐI LẠI. Mặc định là tuyến THAM CHIẾU của chặng (plan do planner sinh), không phải
|
||
// plan đang bám (2026-08-05e): nối vào plan đang bám nghĩa là mỗi lượt detour lấy kết quả của
|
||
// lượt trước làm mốc — sim đo được tuyến bị ăn mòn dần (rejoin 106/305 -> 130/289 -> 132/273),
|
||
// robot không bao giờ quay về tuyến order, và `max_deviation` đo với một mốc đã trôi nên hành
|
||
// lang fleet mất ý nghĩa. Nối vào tuyến tham chiếu thì chính SBPL kéo robot trở lại tuyến đã
|
||
// duyệt, và đuôi splice cũng là đuôi tuyến gốc nên chặng luôn kết thúc đúng chỗ.
|
||
plan_.clear();
|
||
const bool want_reference = rejoin_on_ == "reference" && ctx().reference_plan != nullptr;
|
||
bool have_plan = want_reference && ctx().reference_plan->getGlobalPlan(plan_) && !plan_.empty();
|
||
if (!have_plan)
|
||
{
|
||
// Runtime không cấp tuyến tham chiếu (hoặc chưa có plan nào của planner): quay về plan đang
|
||
// bám. Mất khả năng tự về tuyến, nhưng vẫn vòng được — im lặng thì tệ hơn.
|
||
if (want_reference)
|
||
{
|
||
robot::log_warning_throttle(
|
||
kReferencePlanLogThrottle,
|
||
"[sbpl_recovery] '%s': no reference route available — rejoining the CURRENT plan "
|
||
"instead; detours will not pull the robot back to the order route.", name().c_str());
|
||
}
|
||
plan_.clear();
|
||
have_plan = ctx().plan != nullptr && ctx().plan->getGlobalPlan(plan_) && !plan_.empty();
|
||
}
|
||
if (!have_plan)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': no plan to rejoin — refusing to start.",
|
||
name().c_str());
|
||
return false;
|
||
}
|
||
|
||
plan_frame_ = plan_.front().header.frame_id;
|
||
costmap_frame_ = costmapFrame(costmap);
|
||
|
||
if (plan_frame_ != costmap_frame_ && ctx().tf == nullptr)
|
||
{
|
||
// Local costmap (odom) + plan (map) là ca mặc định — thiếu TF thì không quy đổi được.
|
||
robot::log_error("[sbpl_recovery] '%s': plan frame '%s' != costmap frame '%s' and the "
|
||
"context has no TF buffer.",
|
||
name().c_str(), plan_frame_.c_str(), costmap_frame_.c_str());
|
||
return false;
|
||
}
|
||
|
||
robot_geometry_msgs::PoseStamped robot_in_plan;
|
||
if (!robotPoseIn(plan_frame_, robot_in_plan))
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': robot pose unavailable — cannot pick a rejoin "
|
||
"point.", name().c_str());
|
||
return false;
|
||
}
|
||
|
||
// Lưới gộp cho lượt lập plan; mỗi attempt trong onUpdate sẽ chụp lại bản tươi hơn.
|
||
if (merged_active_ && !buildMergedGrid())
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': could not build the merged grid — refusing to "
|
||
"start.", name().c_str());
|
||
return false;
|
||
}
|
||
|
||
// ĐÍCH LÀ GOAL CHẶNG, không phải một điểm nối trên tuyến cũ (2026-09-02).
|
||
//
|
||
// Bản trước vá một đoạn vào tuyến đang chạy, nên nó phải CHỌN điểm nối — và việc chọn đó là
|
||
// nguồn của lớp lỗi nặng nhất gói này từng có. `buildCandidates` chỉ đo khoảng cách Euclid tới
|
||
// robot, không có khái niệm "phía trước": một pose 3 m SAU LƯNG là ứng viên hợp lệ, còn một
|
||
// pose 0.8 m trước mặt thì bị loại. Tệ hơn, con trỏ quét tụt về 0 khi robot cách MỌI pose của
|
||
// tuyến hơn `planning_distance`, mà trigger `off_path` lại bắn ở ngưỡng LỚN HƠN mức đó — nên
|
||
// ca xấu nhất là ca chắc chắn xảy ra. Sim 28/8 (mission 8, /tmp/crowd2.log): nối tại index
|
||
// 0/279, tức quay về vạch xuất phát; SBPL nối bằng cung nên ra một đường KHÉP KÍN (winding
|
||
// +272 độ, tự cắt 1 lần, hai đoạn cách nhau 6.8 m theo arc mà áp sát 0.10 m) và robot chạy
|
||
// vòng 244 giây không thoát.
|
||
//
|
||
// Lập một đường LIỀN từ pose hiện tại tới goal chặng thì không còn gì để chọn sai: một lượt A*
|
||
// là một đường đi trong đồ thị, mỗi state thăm một lần, không tự cắt và không tự vòng. Không
|
||
// có mối nối thì cũng không có đoạn đuôi phải ghép vào — mất luôn nguồn tự cắt thứ hai.
|
||
//
|
||
// Goal lấy từ pose CUỐI của tuyến (`rejoin_on: reference` -> tuyến tham chiếu của chặng, rơi
|
||
// về plan đang bám nếu chưa có): mọi plan của chặng đều kết thúc ở đích chặng.
|
||
goal_in_plan_ = plan_.back();
|
||
|
||
if (!std::isfinite(goal_in_plan_.pose.position.x) ||
|
||
!std::isfinite(goal_in_plan_.pose.position.y))
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': the leg goal (last pose of a %zu-pose plan) is not "
|
||
"finite — refusing to start.", name().c_str(), plan_.size());
|
||
return false;
|
||
}
|
||
|
||
// Đã ở đích thì không còn gì để lập: plan tới chính chỗ đang đứng cho ra path một pose, tầng
|
||
// trên nhận rồi báo hỏng ngay chu kỳ sau.
|
||
const double sq_to_goal = sqDistance(robot_in_plan, goal_in_plan_);
|
||
if (sq_to_goal < kMinGoalDistance * kMinGoalDistance)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': already %.2f m from the leg goal (minimum %.2f m) "
|
||
"— refusing to start; there is no path left to plan.",
|
||
name().c_str(), std::sqrt(sq_to_goal), kMinGoalDistance);
|
||
return false;
|
||
}
|
||
|
||
// Worker của lượt trước (bị huỷ mà planner không preempt được) phải xong trước khi lập lại:
|
||
// nó còn đụng merged_grid_/planner_. Join có trần; quá trần thì từ chối khởi động thay vì đua.
|
||
if (workerRunning())
|
||
{
|
||
requestWorkerStop();
|
||
if (!waitWorker(cancel_join_timeout_))
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': previous planning worker still running after "
|
||
"%.2f s — refusing to start a new run on top of it.",
|
||
name().c_str(), cancel_join_timeout_);
|
||
return false;
|
||
}
|
||
joinWorker();
|
||
}
|
||
|
||
attempt_ = 0;
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* @brief Một tick. Từ 2026-09-11 lượt makePlan chạy trên WORKER THREAD: control thread chỉ chuẩn
|
||
* bị (pose, đích, lưới gộp), khởi động, rồi mỗi tick poll — không bao giờ kẹt trong SBPL,
|
||
* nên cancel/pause của host tới được ngay cycle kế. Hợp lệ với THREADING.md: behavior họ
|
||
* kPath không phát vận tốc, bất biến "chỉ control thread phát cmd_vel" không bị chạm.
|
||
*/
|
||
recovery_core::RecoveryResult onUpdate(const robot::Time& now, double /*dt*/) override
|
||
{
|
||
// --- Worker đang chạy: poll --------------------------------------------------------------
|
||
if (workerRunning())
|
||
{
|
||
if (!workerDone())
|
||
{
|
||
return recovery_core::RecoveryResult::Running()
|
||
.withProgress(progressNow(), remainingNow())
|
||
.withMessage("planning attempt " + std::to_string(attempt_ + 1) + "/" +
|
||
std::to_string(attempts_per_run_) + " in progress");
|
||
}
|
||
joinWorker();
|
||
return finishAttempt(now);
|
||
}
|
||
|
||
if (attempt_ >= static_cast<std::size_t>(attempts_per_run_))
|
||
{
|
||
return recovery_core::RecoveryResult::Failed()
|
||
.withProgress(1.0, 0.0)
|
||
.withMessage("could not plan a path to the leg goal after " +
|
||
std::to_string(attempts_per_run_) + " attempt(s)");
|
||
}
|
||
|
||
// --- Chuẩn bị một attempt trên control thread ------------------------------------------
|
||
// Pose lấy TƯƠI mỗi lượt thử: behavior trước đó trong route (rotate/back_up) có thể đã dời
|
||
// robot; và mất pose giữa chừng phải kết thúc lượt, không dùng pose cũ.
|
||
robot_geometry_msgs::PoseStamped start;
|
||
if (!robotPoseIn(costmap_frame_, start))
|
||
{
|
||
return recovery_core::RecoveryResult::Failed().withMessage("robot pose became unavailable");
|
||
}
|
||
|
||
robot_geometry_msgs::PoseStamped goal;
|
||
try
|
||
{
|
||
goal = toFrame(goal_in_plan_, costmap_frame_);
|
||
}
|
||
catch (const std::exception& ex)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%d: goal frame conversion threw: %s",
|
||
name().c_str(), attempt_ + 1, attempts_per_run_, ex.what());
|
||
++attempt_;
|
||
return recovery_core::RecoveryResult::Running()
|
||
.withProgress(progressNow(), remainingNow())
|
||
.withMessage("goal could not be expressed in the costmap frame");
|
||
}
|
||
|
||
if (merged_active_)
|
||
{
|
||
// Lưới gộp: chụp lại bản TƯƠI trước từng attempt (mutex chỉ bị giữ trong lúc copy), rồi
|
||
// SBPL search trên bản chụp — KHÔNG giữ mutex costmap nào, map update không bị bỏ đói dù
|
||
// attempt thua đốt trọn allocated_time. Chụp trên control thread; worker chỉ đọc.
|
||
if (!buildMergedGrid())
|
||
{
|
||
return recovery_core::RecoveryResult::Failed()
|
||
.withMessage("could not rebuild the merged grid (TF/costmap unavailable)");
|
||
}
|
||
set_external_grid_(planner_.get(), &merged_grid_);
|
||
}
|
||
|
||
if (!async_planning_)
|
||
{
|
||
// Đường đồng bộ: cùng thân với worker nhưng chạy ngay trên thread này.
|
||
worker_start_ = start;
|
||
worker_goal_ = goal;
|
||
worker_detour_.clear();
|
||
worker_stop_.store(false, std::memory_order_relaxed);
|
||
planInto(worker_planned_, worker_detour_);
|
||
return finishAttempt(now);
|
||
}
|
||
|
||
startWorker(start, goal);
|
||
return recovery_core::RecoveryResult::Running()
|
||
.withProgress(progressNow(), remainingNow())
|
||
.withMessage("planning attempt " + std::to_string(attempt_ + 1) + "/" +
|
||
std::to_string(attempts_per_run_) + " started");
|
||
}
|
||
|
||
private:
|
||
// ================================================================================================
|
||
// Worker thread cho một attempt (2026-09-11)
|
||
// ================================================================================================
|
||
|
||
void startWorker(const robot_geometry_msgs::PoseStamped& start,
|
||
const robot_geometry_msgs::PoseStamped& goal)
|
||
{
|
||
worker_start_ = start;
|
||
worker_goal_ = goal;
|
||
worker_detour_.clear();
|
||
worker_planned_ = false;
|
||
worker_stop_.store(false, std::memory_order_relaxed);
|
||
{
|
||
std::lock_guard<std::mutex> lock(worker_mutex_);
|
||
worker_done_ = false;
|
||
}
|
||
worker_running_ = true;
|
||
worker_ = std::thread(&DetourPathRecovery::workerBody, this);
|
||
}
|
||
|
||
/// @brief Một lượt makePlan với đúng giao thức khoá cũ. Dùng chung cho worker và đường đồng bộ.
|
||
void planInto(bool& planned_out, std::vector<robot_geometry_msgs::PoseStamped>& detour_out)
|
||
{
|
||
bool planned = false;
|
||
try
|
||
{
|
||
if (merged_active_)
|
||
{
|
||
planned = planner_->makePlan(worker_start_, worker_goal_, detour_out);
|
||
}
|
||
// Cùng giao thức khoá với PlannerRunner/gen-1: map-update thread ghi lưới dưới mutex này,
|
||
// planner đọc lưới sống thì phải giữ nó. Chỉ unit test với costmap placeholder được tắt.
|
||
else if (lock_costmap_)
|
||
{
|
||
robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap();
|
||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(
|
||
*(costmap->getCostmap()->getMutex()));
|
||
planned = planner_->makePlan(worker_start_, worker_goal_, detour_out);
|
||
}
|
||
else
|
||
{
|
||
planned = planner_->makePlan(worker_start_, worker_goal_, detour_out);
|
||
}
|
||
}
|
||
catch (const std::exception& ex)
|
||
{
|
||
// Exception thoát khỏi thân thread là std::terminate — bắt ở đây, báo như một attempt hỏng.
|
||
robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%d threw: %s", name().c_str(),
|
||
attempt_ + 1, attempts_per_run_, ex.what());
|
||
planned = false;
|
||
}
|
||
catch (...)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%d threw an unknown exception",
|
||
name().c_str(), attempt_ + 1, attempts_per_run_);
|
||
planned = false;
|
||
}
|
||
// Lượt bị cắt thì kết quả (nếu có) không phải thứ ai yêu cầu.
|
||
planned_out = planned && !worker_stop_.load(std::memory_order_relaxed);
|
||
}
|
||
|
||
void workerBody()
|
||
{
|
||
planInto(worker_planned_, worker_detour_);
|
||
{
|
||
std::lock_guard<std::mutex> lock(worker_mutex_);
|
||
worker_done_ = true;
|
||
}
|
||
worker_cv_.notify_all();
|
||
}
|
||
|
||
bool workerRunning() const
|
||
{
|
||
return worker_running_;
|
||
}
|
||
|
||
bool workerDone()
|
||
{
|
||
std::lock_guard<std::mutex> lock(worker_mutex_);
|
||
return worker_done_;
|
||
}
|
||
|
||
/// @return true nếu worker đã xong trong @p seconds.
|
||
bool waitWorker(double seconds)
|
||
{
|
||
std::unique_lock<std::mutex> lock(worker_mutex_);
|
||
return worker_cv_.wait_for(lock, std::chrono::duration<double>(seconds),
|
||
[this] { return worker_done_; });
|
||
}
|
||
|
||
void joinWorker()
|
||
{
|
||
if (worker_.joinable())
|
||
{
|
||
worker_.join();
|
||
}
|
||
worker_running_ = false;
|
||
}
|
||
|
||
/// @brief Cắt lượt đang chạy: preempt planner (nếu hỗ trợ) + cờ vứt kết quả.
|
||
void requestWorkerStop()
|
||
{
|
||
worker_stop_.store(true, std::memory_order_relaxed);
|
||
if (auto* p = dynamic_cast<robot_nav_core::Preemptable*>(planner_.get()))
|
||
{
|
||
p->preempt();
|
||
}
|
||
}
|
||
|
||
/// @brief Phần sau makePlan (guard lệch tuyến, đổi frame, nộp path) — chạy trên control thread.
|
||
recovery_core::RecoveryResult finishAttempt(const robot::Time& now)
|
||
{
|
||
const bool planned = worker_planned_;
|
||
std::vector<robot_geometry_msgs::PoseStamped>& detour = worker_detour_;
|
||
|
||
if (planned && !detour.empty() && max_deviation_ > 0.0)
|
||
{
|
||
// Guard lệch tuyến: đường vòng phải nằm trong hành lang fleet cho phép quanh tuyến gốc.
|
||
// `plan_` ở frame plan còn `detour` vừa được planner sinh ra ở frame costmap, nên phải quy
|
||
// về cùng frame trước khi đo. TF đứt giữa chừng thì bỏ qua guard — nhánh splice bên dưới sẽ
|
||
// gặp lại đúng lỗi đó và xử lý một lần.
|
||
std::vector<robot_geometry_msgs::PoseStamped> detour_in_plan_frame;
|
||
detour_in_plan_frame.reserve(detour.size());
|
||
bool converted = true;
|
||
try
|
||
{
|
||
for (const robot_geometry_msgs::PoseStamped& pose : detour)
|
||
{
|
||
detour_in_plan_frame.push_back(toFrame(pose, plan_frame_));
|
||
}
|
||
}
|
||
catch (const std::exception&)
|
||
{
|
||
converted = false;
|
||
}
|
||
|
||
if (converted)
|
||
{
|
||
// Đo với TOÀN BỘ tuyến tham chiếu: đường mới chạy suốt tới goal chặng nên hành lang
|
||
// fleet cũng phải xét suốt tuyến, không phải tới một điểm nối.
|
||
const double deviation =
|
||
maxDeviation(plan_, plan_.size() - 1, detour_in_plan_frame); // [m]
|
||
if (deviation > max_deviation_)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%d strays %.2f m from the route "
|
||
"(limit %.2f m) — rejected.",
|
||
name().c_str(), attempt_ + 1, attempts_per_run_, deviation,
|
||
max_deviation_);
|
||
++attempt_;
|
||
return recovery_core::RecoveryResult::Running()
|
||
.withProgress(progressNow(), remainingNow())
|
||
.withMessage("replan rejected: deviates too far from the route");
|
||
}
|
||
}
|
||
}
|
||
|
||
if (planned && !detour.empty())
|
||
{
|
||
robot_nav_msgs::Path out;
|
||
out.header.frame_id = plan_frame_;
|
||
out.header.stamp = now;
|
||
out.poses.reserve(detour.size());
|
||
|
||
try
|
||
{
|
||
for (const robot_geometry_msgs::PoseStamped& pose : detour)
|
||
{
|
||
out.poses.push_back(toFrame(pose, plan_frame_));
|
||
}
|
||
}
|
||
catch (const std::exception& ex)
|
||
{
|
||
// TF đứt đúng giữa lúc quy đổi kết quả: đường vòng không dùng được, coi như lượt thử hỏng.
|
||
robot::log_warning("[sbpl_recovery] '%s': could not express the path in '%s': %s",
|
||
name().c_str(), plan_frame_.c_str(), ex.what());
|
||
++attempt_;
|
||
return recovery_core::RecoveryResult::Running()
|
||
.withProgress(progressNow(), remainingNow())
|
||
.withMessage("path found but its frame conversion failed");
|
||
}
|
||
|
||
// KHÔNG nối đuôi tuyến cũ. Đường vừa lập đã chạy tới goal chặng, nên contract 2026-08-04b
|
||
// ("không replan sau recovery — path phải tự đi tới đích của chặng") vẫn được giữ; chỉ là
|
||
// giữ bằng cách lập đủ, không phải bằng cách vá.
|
||
robot::log_info("[sbpl_recovery] '%s': planned %zu pose(s) from the robot to the leg goal "
|
||
"(attempt %zu/%d).",
|
||
name().c_str(), out.poses.size(), attempt_ + 1, attempts_per_run_);
|
||
|
||
return recovery_core::RecoveryResult::PathOut(out, recovery_core::RecoveryStatus::kSucceeded)
|
||
.withProgress(1.0, 0.0)
|
||
.withMessage("replanned a full path to the leg goal");
|
||
}
|
||
|
||
++attempt_;
|
||
return recovery_core::RecoveryResult::Running()
|
||
.withProgress(progressNow(), remainingNow())
|
||
.withMessage("replan attempt " + std::to_string(attempt_) + "/" +
|
||
std::to_string(attempts_per_run_) + " failed");
|
||
}
|
||
|
||
robot_costmap_2d::Costmap2DROBOT* chosenCostmap() const
|
||
{
|
||
return use_global_costmap_ ? ctx().global_costmap : ctx().local_costmap;
|
||
}
|
||
|
||
/// Frame của costmap đã chọn. Override chỉ dành cho unit test với costmap placeholder —
|
||
/// production để rỗng và đọc thẳng từ costmap.
|
||
std::string costmapFrame(robot_costmap_2d::Costmap2DROBOT* costmap) const
|
||
{
|
||
return costmap_frame_override_.empty() ? costmap->getGlobalFrameID() : costmap_frame_override_;
|
||
}
|
||
|
||
bool loadPlanner(robot_costmap_2d::Costmap2DROBOT* costmap)
|
||
{
|
||
// Tra library_path và đọc param của planner từ ROOT config (không phải namespace của instance
|
||
// recovery) — cùng chỗ với mọi planner khác, nên `SBPLLatticePlanner` dùng chung tuning với
|
||
// backup planner nếu trùng tên.
|
||
robot::NodeHandle root_nh;
|
||
robot::PluginLoaderHelper loader(root_nh);
|
||
const std::string library_path = loader.findLibraryPath(planner_symbol_);
|
||
if (library_path.empty())
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': no library found for planner symbol '%s' — check the "
|
||
"key '%s/library_path' in the YAML.",
|
||
name().c_str(), planner_symbol_.c_str(), planner_symbol_.c_str());
|
||
return false;
|
||
}
|
||
|
||
try
|
||
{
|
||
// factory_ giữ .so còn nạp — phải sống lâu hơn planner_ (factory_ khai TRƯỚC planner_ nên bị
|
||
// huỷ SAU).
|
||
planner_factory_ = boost::dll::import_alias<robot_nav_core::BaseGlobalPlanner::Ptr()>(
|
||
library_path, planner_symbol_, boost::dll::load_mode::append_decorations);
|
||
planner_ = planner_factory_();
|
||
}
|
||
catch (const boost::system::system_error& ex)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': could not load symbol '%s' from '%s': %s. Lưu ý: "
|
||
"`planner_symbol` phải là alias Boost.DLL CÓ THẬT trong .so; muốn một "
|
||
"instance tuning riêng thì đổi `planner_name` (namespace param), không phải "
|
||
"symbol.",
|
||
name().c_str(), planner_symbol_.c_str(), library_path.c_str(), ex.what());
|
||
return false;
|
||
}
|
||
catch (const std::exception& ex)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': error while loading planner '%s': %s", name().c_str(),
|
||
planner_symbol_.c_str(), ex.what());
|
||
return false;
|
||
}
|
||
|
||
if (!planner_)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': factory of '%s' returned null.", name().c_str(),
|
||
planner_symbol_.c_str());
|
||
return false;
|
||
}
|
||
|
||
try
|
||
{
|
||
// Boot-time là chỗ đúng cho initialize: SBPL dựng environment theo kích thước costmap và
|
||
// CHẶN tới khi costmap khác 0 — không được làm điều đó trong control loop.
|
||
if (!planner_->initialize(planner_name_, costmap))
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': planner '%s' reported an initialize() failure.",
|
||
name().c_str(), planner_name_.c_str());
|
||
planner_.reset();
|
||
return false;
|
||
}
|
||
}
|
||
catch (const std::exception& ex)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': initialize() of '%s' threw: %s", name().c_str(),
|
||
planner_name_.c_str(), ex.what());
|
||
planner_.reset();
|
||
return false;
|
||
}
|
||
|
||
initialized_costmap_ = costmap;
|
||
|
||
// `costmap_frame_override` là test seam với costmap placeholder — lúc đó không được dựng
|
||
// checker thật (nó sẽ dereference placeholder) và cũng không nạp capability lưới ngoài.
|
||
merged_active_ = false;
|
||
if (costmap_frame_override_.empty())
|
||
{
|
||
if (costmap_source_ == "global")
|
||
{
|
||
// Checker phải nhìn cùng lưới với planner (ctx().collision của runtime trỏ local).
|
||
own_checker_ = std::make_unique<recovery_core::CostmapCollisionChecker>(costmap);
|
||
}
|
||
else if (costmap_source_ == "combined")
|
||
{
|
||
// Lưới gộp cần planner nhận lưới NGOÀI (bản chụp global+local). Capability nằm ngoài
|
||
// interface BaseGlobalPlanner nên tra qua một alias Boost.DLL thứ hai trong CÙNG .so:
|
||
// "<planner_symbol>ExternalGrid". Thiếu nó = planner này không chạy được mode combined —
|
||
// báo lỗi cấu hình ở boot, không âm thầm rơi về hành vi khác.
|
||
try
|
||
{
|
||
// std::function giữ luôn tham chiếu .so bên trong callable của boost::dll — cùng cơ chế
|
||
// giữ-sống với planner_factory_.
|
||
set_external_grid_ =
|
||
boost::dll::import_alias<void(robot_nav_core::BaseGlobalPlanner*,
|
||
const robot_costmap_2d::Costmap2D*)>(
|
||
library_path, planner_symbol_ + "ExternalGrid",
|
||
boost::dll::load_mode::append_decorations);
|
||
}
|
||
catch (const std::exception& ex)
|
||
{
|
||
robot::log_error("[sbpl_recovery] '%s': costmap_source=combined but '%s' does not "
|
||
"export the '%sExternalGrid' capability: %s. Use a planner that "
|
||
"supports external grids, or switch costmap_source to local/global.",
|
||
name().c_str(), library_path.c_str(), planner_symbol_.c_str(),
|
||
ex.what());
|
||
planner_.reset();
|
||
return false;
|
||
}
|
||
merged_active_ = true;
|
||
}
|
||
}
|
||
|
||
robot::log_info("[sbpl_recovery] '%s': detour planner '%s' ready on the %s costmap.",
|
||
name().c_str(), planner_name_.c_str(),
|
||
costmap_source_ == "combined" ? "merged (global+local)"
|
||
: (use_global_costmap_ ? "global" : "local"));
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* @brief Chụp lưới gộp: global làm nền, cửa sổ local đè lên (xem merge_grids.h).
|
||
*
|
||
* Mutex mỗi costmap chỉ bị giữ trong lúc copy nguyên khối lưới của nó; phần overlay chạy trên
|
||
* hai BẢN CHỤP nên không đụng costmap sống. TF local->map tra MỘT lần cho cả lượt.
|
||
*/
|
||
bool buildMergedGrid()
|
||
{
|
||
robot_costmap_2d::Costmap2DROBOT* global = ctx().global_costmap;
|
||
robot_costmap_2d::Costmap2DROBOT* local = ctx().local_costmap;
|
||
if (global == nullptr || local == nullptr)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
PlanarTransform2D local_to_map; // Ghi lại làm member: pha quét ứng viên cần chiều ngược.
|
||
const std::string local_frame = local->getGlobalFrameID();
|
||
const std::string map_frame = global->getGlobalFrameID();
|
||
if (local_frame != map_frame)
|
||
{
|
||
if (ctx().tf == nullptr)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': merged grid needs TF '%s' -> '%s' but the "
|
||
"context has no TF buffer.",
|
||
name().c_str(), local_frame.c_str(), map_frame.c_str());
|
||
return false;
|
||
}
|
||
try
|
||
{
|
||
const tf3::TransformStampedMsg transform =
|
||
ctx().tf->lookupTransform(map_frame, local_frame, tf3::Time());
|
||
local_to_map.x = transform.transform.translation.x;
|
||
local_to_map.y = transform.transform.translation.y;
|
||
// Quaternion phẳng (robot 2D): yaw = 2*atan2(z, w) — cùng phép rút gọn với port SBPL.
|
||
const double yaw = 2.0 * std::atan2(transform.transform.rotation.z,
|
||
transform.transform.rotation.w);
|
||
local_to_map.cos_yaw = std::cos(yaw);
|
||
local_to_map.sin_yaw = std::sin(yaw);
|
||
}
|
||
catch (const std::exception& ex)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': TF '%s' -> '%s' unavailable for the merged "
|
||
"grid: %s",
|
||
name().c_str(), local_frame.c_str(), map_frame.c_str(), ex.what());
|
||
return false;
|
||
}
|
||
}
|
||
|
||
{
|
||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(
|
||
*(global->getCostmap()->getMutex()));
|
||
merged_grid_ = *global->getCostmap();
|
||
}
|
||
{
|
||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(
|
||
*(local->getCostmap()->getMutex()));
|
||
local_snapshot_ = *local->getCostmap();
|
||
}
|
||
overlayLocalGrid(local_snapshot_, local_to_map, merged_grid_);
|
||
local_to_map_ = local_to_map;
|
||
return true;
|
||
}
|
||
|
||
/// Pose robot trong @p frame. Trả false khi mất pose hoặc TF không quy đổi được.
|
||
bool robotPoseIn(const std::string& frame, robot_geometry_msgs::PoseStamped& out) const
|
||
{
|
||
robot_geometry_msgs::PoseStamped raw;
|
||
if (!ctx().pose->getRobotPose(raw))
|
||
{
|
||
return false;
|
||
}
|
||
|
||
try
|
||
{
|
||
out = toFrame(raw, frame);
|
||
}
|
||
catch (const std::exception& ex)
|
||
{
|
||
robot::log_warning("[sbpl_recovery] '%s': cannot express the robot pose in '%s': %s",
|
||
name().c_str(), frame.c_str(), ex.what());
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/// Quy @p in về @p target qua TF của context. Ném tf3 exception khi không quy đổi được.
|
||
robot_geometry_msgs::PoseStamped toFrame(const robot_geometry_msgs::PoseStamped& in,
|
||
const std::string& target) const
|
||
{
|
||
if (in.header.frame_id == target || in.header.frame_id.empty())
|
||
{
|
||
return in;
|
||
}
|
||
if (ctx().tf == nullptr)
|
||
{
|
||
throw std::runtime_error("frame '" + in.header.frame_id + "' != '" + target +
|
||
"' and no TF buffer is available");
|
||
}
|
||
|
||
const tf3::TransformStampedMsg transform =
|
||
ctx().tf->lookupTransform(target, in.header.frame_id, tf3::Time());
|
||
robot_geometry_msgs::PoseStamped out;
|
||
tf3::doTransform(in, out, transform);
|
||
out.header.frame_id = target;
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* @brief Đặt được robot tại pose này không (footprint thật, trên costmap đang dùng).
|
||
*
|
||
* Không có collision checker, hoặc không quy đổi được frame → coi là **đặt được**. "Không biết"
|
||
* không được biến thành "loại": loại nhầm hết ứng viên thì detour mất sạch đường ra, trong khi
|
||
* planner mới là bên phán quyết cuối cùng.
|
||
*/
|
||
/**
|
||
* @brief Collision checker khớp với costmap mà DETOUR đang lập plan trên đó.
|
||
*
|
||
* `ctx().collision` của runtime trỏ vào costmap LOCAL. Khi `use_global_costmap: true`, kiểm ứng
|
||
* viên bằng checker local là tự mâu thuẫn: pose ngoài cửa sổ lăn 8x8 m bị đọc thành "chắn" trong
|
||
* khi SBPL trên global costmap tới đó bình thường — đúng lỗi sim 2026-08-05 (footprint của pose ở
|
||
* ~3.5 m vươn quá rìa 4.0 m, `kOutsideMap`, cả đuôi tầm quét thành "vật cản"). Người quyết định
|
||
* và người kiểm phải nhìn cùng một lưới.
|
||
*/
|
||
const recovery_core::CollisionChecker* checker() const
|
||
{
|
||
if (use_global_costmap_ && own_checker_ != nullptr)
|
||
{
|
||
return own_checker_.get();
|
||
}
|
||
return ctx().collision;
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
double progressNow() const
|
||
{
|
||
return static_cast<double>(attempt_) / static_cast<double>(attempts_per_run_);
|
||
}
|
||
|
||
double remainingNow() const
|
||
{
|
||
const std::size_t budget = static_cast<std::size_t>(attempts_per_run_);
|
||
return static_cast<double>(budget - std::min(attempt_, budget));
|
||
}
|
||
|
||
// --- Param ---------------------------------------------------------------
|
||
std::string planner_name_ = "SBPLLatticePlanner"; ///< Namespace param + tên truyền vào initialize().
|
||
std::string planner_symbol_ = "SBPLLatticePlanner"; ///< Alias Boost.DLL thật trong .so.
|
||
bool use_global_costmap_ = false;
|
||
int attempts_per_run_ = kDefaultAttemptsPerRun;
|
||
double max_deviation_ = 0.0; ///< [m] 0 = không giới hạn.
|
||
/// "reference" = nối vào tuyến gốc của chặng (mặc định, tự về tuyến order); "current" = nối vào
|
||
/// plan đang bám (hành vi trước 2026-08-05e).
|
||
std::string rejoin_on_ = "reference";
|
||
bool lock_costmap_ = true;
|
||
std::string costmap_frame_override_; ///< Test seam — production để rỗng.
|
||
|
||
// --- Planner plugin (factory_ khai trước planner_: .so phải sống lâu hơn instance) -----------
|
||
std::function<robot_nav_core::BaseGlobalPlanner::Ptr()> planner_factory_;
|
||
robot_nav_core::BaseGlobalPlanner::Ptr planner_;
|
||
robot_costmap_2d::Costmap2DROBOT* initialized_costmap_ = nullptr; ///< non-owning.
|
||
|
||
/// Checker trên costmap ĐÃ CHỌN, chỉ dựng cho mode "global" (ctx().collision là local).
|
||
std::unique_ptr<recovery_core::CostmapCollisionChecker> own_checker_;
|
||
|
||
std::string costmap_source_; ///< "local" | "global" | "combined".
|
||
|
||
// --- Lưới gộp (mode combined) ---------------------------------------------------------------
|
||
/// Capability lưới ngoài của planner (alias "<symbol>ExternalGrid"); std::function giữ .so sống.
|
||
std::function<void(robot_nav_core::BaseGlobalPlanner*, const robot_costmap_2d::Costmap2D*)>
|
||
set_external_grid_;
|
||
robot_costmap_2d::Costmap2D merged_grid_; ///< Bản chụp gộp; buffer tái dùng giữa các lượt.
|
||
robot_costmap_2d::Costmap2D local_snapshot_; ///< Bản chụp cửa sổ local; tái dùng như trên.
|
||
/// Frame local -> frame lưới gộp, chụp cùng lúc với hai lưới.
|
||
PlanarTransform2D local_to_map_;
|
||
bool merged_active_ = false; ///< combined + đủ hai costmap + planner có capability.
|
||
|
||
// --- Trạng thái một lượt --------------------------------------------------
|
||
std::vector<robot_geometry_msgs::PoseStamped> plan_; ///< Bản chụp plan, frame plan_frame_.
|
||
|
||
/// Đích của chặng — pose CUỐI của @ref plan_, chụp một lần ở onStart và giữ nguyên suốt lượt.
|
||
/// Chụp một lần chứ không đọc lại mỗi attempt: tuyến tham chiếu có thể bị thay giữa chừng, và
|
||
/// đổi đích giữa các attempt của cùng một lượt recovery là đổi bài toán đang giải.
|
||
robot_geometry_msgs::PoseStamped goal_in_plan_;
|
||
std::string plan_frame_;
|
||
std::string costmap_frame_;
|
||
std::size_t attempt_ = 0;
|
||
|
||
// --- Worker thread của một attempt (2026-09-11) ---------------------------------------------
|
||
double cancel_join_timeout_ = 0.2; ///< [s] trần đợi worker thoát sau preempt.
|
||
bool async_planning_ = true; ///< false = makePlan đồng bộ trong onUpdate (test/đường lùi).
|
||
std::thread worker_;
|
||
bool worker_running_ = false; ///< chỉ control thread đọc/ghi.
|
||
std::mutex worker_mutex_;
|
||
std::condition_variable worker_cv_;
|
||
bool worker_done_ = false; ///< dưới worker_mutex_.
|
||
std::atomic<bool> worker_stop_{false};
|
||
robot_geometry_msgs::PoseStamped worker_start_;
|
||
robot_geometry_msgs::PoseStamped worker_goal_;
|
||
std::vector<robot_geometry_msgs::PoseStamped> worker_detour_; ///< worker ghi, control đọc sau join.
|
||
bool worker_planned_ = false; ///< như trên.
|
||
};
|
||
|
||
} // namespace sbpl_recovery
|
||
|
||
RECOVERY_CORE_EXPORT_BEHAVIOR(sbpl_recovery::DetourPathRecovery::create, DetourPathRecovery)
|