feat: run detour planning on a worker thread so cancel doesn't block the control loop

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>
This commit is contained in:
2026-09-12 22:06:50 +07:00
parent 8f9326be04
commit ea79686eef
4 changed files with 400 additions and 19 deletions

View File

@@ -21,12 +21,17 @@
*********************************************************************/
#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>
@@ -41,10 +46,12 @@
#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>
@@ -216,6 +223,40 @@ public:
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
{
@@ -233,6 +274,12 @@ protected:
// 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"));
@@ -444,12 +491,47 @@ protected:
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()
@@ -458,6 +540,7 @@ protected:
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;
@@ -467,25 +550,81 @@ protected:
}
robot_geometry_msgs::PoseStamped goal;
std::vector<robot_geometry_msgs::PoseStamped> detour;
bool planned = false;
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_)
{
// 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.
if (!buildMergedGrid())
{
return recovery_core::RecoveryResult::Failed()
.withMessage("could not rebuild the merged grid (TF/costmap unavailable)");
}
set_external_grid_(planner_.get(), &merged_grid_);
planned = planner_->makePlan(start, goal, detour);
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.
@@ -494,19 +633,83 @@ protected:
robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap();
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(
*(costmap->getCostmap()->getMutex()));
planned = planner_->makePlan(start, goal, detour);
planned = planner_->makePlan(worker_start_, worker_goal_, detour_out);
}
else
{
planned = planner_->makePlan(start, goal, detour);
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)
{
@@ -593,7 +796,6 @@ protected:
std::to_string(attempts_per_run_) + " failed");
}
private:
robot_costmap_2d::Costmap2DROBOT* chosenCostmap() const
{
return use_global_costmap_ ? ctx().global_costmap : ctx().local_costmap;
@@ -913,8 +1115,21 @@ private:
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
BOOST_DLL_ALIAS(sbpl_recovery::DetourPathRecovery::create, DetourPathRecovery)
RECOVERY_CORE_EXPORT_BEHAVIOR(sbpl_recovery::DetourPathRecovery::create, DetourPathRecovery)

View File

@@ -13,6 +13,8 @@ recovery:
- {name: detour_map, type: DetourPathRecovery}
- {name: detour_narrow, type: DetourPathRecovery}
- {name: detour_alias, type: DetourPathRecovery}
- {name: detour_async, type: DetourPathRecovery}
- {name: detour_slow, type: DetourPathRecovery}
detour:
planner_name: TestLinePlanner
@@ -21,6 +23,7 @@ recovery:
attempts_per_run: 3
lock_costmap: false
costmap_frame_override: odom
async_planning: false # planner giả tức thì — giữ đường đồng bộ để test đếm tick như cũ
detour_flaky:
planner_name: TestFlakyPlanner # hai ứng viên đầu bị "chắn", ứng viên ba mới thông
@@ -29,6 +32,7 @@ recovery:
attempts_per_run: 3
lock_costmap: false
costmap_frame_override: odom
async_planning: false # planner giả tức thì — giữ đường đồng bộ để test đếm tick như cũ
detour_dead:
planner_name: TestDeadPlanner # không ứng viên nào thông -> behavior phải kFailed
@@ -37,6 +41,7 @@ recovery:
attempts_per_run: 3
lock_costmap: false
costmap_frame_override: odom
async_planning: false # planner giả tức thì — giữ đường đồng bộ để test đếm tick như cũ
detour_map:
planner_name: TestLinePlanner # plan ở frame map, costmap ở odom -> ép đường quy đổi TF
@@ -45,6 +50,7 @@ recovery:
attempts_per_run: 3
lock_costmap: false
costmap_frame_override: odom
async_planning: false # planner giả tức thì — giữ đường đồng bộ để test đếm tick như cũ
# Tên instance KHÁC symbol: đọc param từ `DetourOnlyTuning`, nạp .so theo alias `TestLinePlanner`.
# Đây là đường mà cấu hình runtime dùng để cho detour một instance SBPL riêng (allocated_time
@@ -57,6 +63,25 @@ recovery:
attempts_per_run: 3
lock_costmap: false
costmap_frame_override: odom
async_planning: false # planner giả tức thì — giữ đường đồng bộ để test đếm tick như cũ
# Đường bất đồng bộ (mặc định production): planner giả ngủ 0.3 s, có Preemptable.
detour_async:
planner_name: TestSlowPlanner
planning_distance: 1.0
sample_step: 0.5
attempts_per_run: 3
lock_costmap: false
costmap_frame_override: odom
cancel_join_timeout: 0.5 # [s]
# Cùng planner; instance riêng để test cancel giữa chừng không dính bộ đếm của instance trên.
detour_slow:
planner_name: TestSlowPlanner
planning_distance: 1.0
sample_step: 0.5
attempts_per_run: 3
lock_costmap: false
costmap_frame_override: odom
cancel_join_timeout: 0.5 # [s]
detour_narrow:
planner_name: TestOffsetPlanner # planner giả luôn vẽ đường vòng lệch 1.0 m khỏi tuyến
@@ -66,6 +91,7 @@ recovery:
max_deviation: 0.2 # [m] chặt hơn độ lệch của planner -> mọi ứng viên bị loại
lock_costmap: false
costmap_frame_override: odom
async_planning: false # planner giả tức thì — giữ đường đồng bộ để test đếm tick như cũ
# Bảng symbol -> thư viện cho Boost.DLL. Ba symbol planner cùng một .so; param của planner đọc theo
# namespace mang tên symbol.
@@ -80,6 +106,10 @@ TestDeadPlanner:
library_path: libsbpl_recovery_test_line_planner
fail_first_attempts: 1000
TestSlowPlanner:
library_path: libsbpl_recovery_test_line_planner
plan_delay: 0.3 # [s] một lượt "search" giả
# Luôn vẽ đường vòng lệch 1.0 m khỏi đoạn thẳng start->goal: dùng để kiểm guard max_deviation.
TestOffsetPlanner:
library_path: libsbpl_recovery_test_line_planner

View File

@@ -12,10 +12,12 @@
#include <gtest/gtest.h>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <thread>
#include <vector>
#include <robot/node_handle.h>
@@ -226,7 +228,7 @@ protected:
robot::NodeHandle nh;
ASSERT_TRUE(registry_.loadFromConfig(nh, "recovery", ctx_));
ASSERT_EQ(registry_.size(), 6u);
ASSERT_EQ(registry_.size(), 8u); // +detour_async, detour_slow (2026-09-11)
}
FakePoseProvider pose_;
@@ -573,6 +575,107 @@ TEST(MergeGrids, OverlayTransformsLocalFrameIntoGridFrame)
EXPECT_EQ(merged.getCost(mx, my), LETHAL_OBSTACLE);
}
// ================================================================================================
// Đường bất đồng bộ (2026-09-11): makePlan trên worker thread, control thread chỉ poll; cancel()
// cắt được lượt đang chạy qua robot_nav_core::Preemptable.
// ================================================================================================
namespace
{
/// Poll update() tới khi status khác kRunning-"đang chạy", tối đa @p max_seconds.
RecoveryResult pumpUntilSettled(RecoveryBehavior* detour, const robot::Time& t0, double max_seconds,
int* ticks_out = nullptr)
{
const auto deadline = std::chrono::steady_clock::now() +
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::duration<double>(max_seconds));
int ticks = 0;
RecoveryResult result;
while (std::chrono::steady_clock::now() < deadline)
{
result = detour->update(t0);
++ticks;
if (result.status != RecoveryStatus::kRunning)
{
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
if (ticks_out != nullptr)
{
*ticks_out = ticks;
}
return result;
}
} // namespace
TEST_F(DetourPathRecoveryTest, AsyncUpdateNeverBlocksAndDeliversThePathLater)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour_async");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
// Tick đầu khởi động worker và trả về NGAY — planner giả ngủ 300 ms, tick phải < 50 ms.
const auto before = std::chrono::steady_clock::now();
const RecoveryResult first = detour->update(t0_);
const double first_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_EQ(first.status, RecoveryStatus::kRunning);
EXPECT_LT(first_ms, 50.0) << "update() blocked inside makePlan";
int ticks = 0;
const RecoveryResult result = pumpUntilSettled(detour, t0_, 3.0, &ticks);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
EXPECT_GE(ticks, 2) << "the path must arrive on a later tick, not the first";
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
ASSERT_EQ(path->poses.size(), 5u);
}
TEST_F(DetourPathRecoveryTest, CancelMidSearchReturnsQuicklyAndJoinsTheWorker)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour_slow");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
ASSERT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
std::this_thread::sleep_for(std::chrono::milliseconds(50)); // worker đang ở giữa 300 ms "search"
const auto before = std::chrono::steady_clock::now();
detour->cancel(); // → onCancelRequested(): preempt + join
const double cancel_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_LT(cancel_ms, 100.0) << "cancel must not wait for the fake 300 ms search to finish";
// Sau cancel behavior phải khởi động lại được ngay (worker cũ đã join), và lượt mới chạy bình thường.
ASSERT_TRUE(detour->start(controllingGoal(), t0_)) << "stale worker blocked a new run";
const RecoveryResult result = pumpUntilSettled(detour, t0_, 3.0);
EXPECT_EQ(result.status, RecoveryStatus::kSucceeded);
}
TEST_F(DetourPathRecoveryTest, CancelledSearchResultIsDiscarded)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour_slow");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
ASSERT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
detour->cancel();
// Tick sau cancel: base trả kCancelled (đường onCancel), không được là kSucceeded với path của
// lượt đã huỷ.
const RecoveryResult after = detour->update(t0_);
EXPECT_NE(after.status, RecoveryStatus::kSucceeded);
EXPECT_EQ(after.pathOut(), nullptr);
}
int main(int argc, char** argv)
{
#ifdef SBPL_RECOVERY_TEST_CONFIG_DIR

View File

@@ -14,8 +14,11 @@
* Author: DuongTD
*********************************************************************/
#include <atomic>
#include <chrono>
#include <cmath>
#include <memory>
#include <thread>
#include <string>
#include <vector>
@@ -23,11 +26,13 @@
#include <robot/node_handle.h>
#include <robot_nav_core/base_global_planner.h>
#include <robot_nav_core/preemptable.h>
namespace sbpl_recovery_test
{
class TestLinePlanner final : public robot_nav_core::BaseGlobalPlanner
class TestLinePlanner final : public robot_nav_core::BaseGlobalPlanner,
public robot_nav_core::Preemptable
{
public:
static robot_nav_core::BaseGlobalPlanner::Ptr create()
@@ -43,14 +48,38 @@ public:
nh.param("fail_first_attempts", fail_first_attempts_, 0);
nh.param("points", points_, 5);
nh.param("lateral_offset", lateral_offset_, 0.0);
// [s] Giả lập một lượt search dài: ngủ từng lát 5 ms và kiểm cờ preempt — mô hình đúng của
// ARA* với abort flag (poll mỗi expand). 0 = tức thì.
nh.param("plan_delay", plan_delay_, 0.0);
return true;
}
void preempt() override
{
preempt_.store(true, std::memory_order_relaxed);
}
bool makePlan(const robot_geometry_msgs::PoseStamped& start,
const robot_geometry_msgs::PoseStamped& goal,
std::vector<robot_geometry_msgs::PoseStamped>& plan) override
{
plan.clear();
preempt_.store(false, std::memory_order_relaxed);
if (plan_delay_ > 0.0)
{
const auto deadline = std::chrono::steady_clock::now() +
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::duration<double>(plan_delay_));
while (std::chrono::steady_clock::now() < deadline)
{
if (preempt_.load(std::memory_order_relaxed))
{
++preempted_calls_;
return false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
if (calls_made_++ < fail_first_attempts_)
{
return false;
@@ -83,7 +112,10 @@ private:
int fail_first_attempts_ = 0;
int points_ = 5;
double lateral_offset_ = 0.0; ///< [m] độ phình ngang lớn nhất so với đoạn start->goal.
double plan_delay_ = 0.0; ///< [s] thời gian giả lập một lượt search.
int calls_made_ = 0;
int preempted_calls_ = 0;
std::atomic<bool> preempt_{false};
};
} // namespace sbpl_recovery_test
@@ -92,3 +124,4 @@ BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestLinePlanner)
BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestFlakyPlanner)
BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestDeadPlanner)
BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestOffsetPlanner)
BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestSlowPlanner)