feat: lifecycle contract — cancel/pause must reach true quiescence before reporting done
Root cause (from a C++ host log, 2026-09-11): cancel during PLANNING only set a discard flag on the planner thread, which ran to allocated_time before CANCELLED could be reported; a queued next mission landed on a still-busy planner and timed out too. Same class of bug existed for pause, recovery, and implicitly for a legitimate ABORTED read while a component was still unwinding. Full audit, decisions, and phased design in docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md; old-vs-new behaviour per state in docs/LIFECYCLE_BEHAVIOUR_MATRIX.md. Runtime quiescence, not just "command sent": - kPausing (new state) mirrors kCancelling: PAUSED/CANCELLED is only entered once planner and recovery are idle, the action reports terminal, and the robot is stopped per odometry (robot_stopped, stopped_measured_linear/ angular_eps) — not merely "the command we sent was zero". settle_timeout bounds the wait; exceeding it still finishes but logs an ungated error naming which component was still busy, so a plugin that doesn't honour cancel/pause is visible instead of silently swallowed. - PlannerRunner::running_planner_ (new): the instance the planner thread is actually inside makePlan() with, tracked separately from active_ — active_ can already point at a different instance after swapPlanner() while the old attempt is still running. cancelPlan(), swapPlanner() (when a job is running_ or only pending_ and not yet picked up), and the destructor all preempt through this pointer now; the old code preempted through active_ and could silently preempt the wrong (idle) instance after a profile swap. - ComponentStatusBoard + per-component ComponentPhase (idle/busy/stopping/ paused/hung), read by PlannerRunner, RecoveryRunner, ActionRunner and ControlLoop instead of ad hoc bools — this is what makes "did everything actually stop" answerable at all, and what the new Watchdog thread reads to flag a component busy-without-progress as hung (logged once at the edge) without the control loop needing to detect its own stall. - Resume: PLANNING replans from the current pose. CONTROLLING re-issues setPlan() with the plan already in hand (decided: setPlan again, not a fresh plan) — the local planner needs nothing else since it already runs once per control cycle; a fresh plan on resume was considered and rejected as unnecessary work for a plan that's still valid. - Command-to-zero on cancel/pause stays immediate (no deceleration ramp) — existing VelocityArbiter behaviour, left as is per a scoped decision. Depends on: Test/sbpl (bd89924), pnkx_nav_core (2b0993b, robot_nav_core:: Preemptable + component_status_probe.h), Test/sbpl_lattice_planner (7456e99), Test/recovery_core (254c7fc, onCancelRequested + ABI guard), Test/ sbpl_recovery (ea79686, worker-thread cancel), Test/action_core (669c3f7, pause/resume + kCancelled), Test/dock_pattern_action (cc1ea74). Verified: 13 gtest binaries / 528 tests, 0 failures. Runtime on the dev machine (Gazebo + real ROS host + VDA5050 over MQTT), 6 scenarios — cancel during PLANNING, pause/resume during PLANNING and CONTROLLING (incl. submit-while-still-winding-down), pause-then-cancel during PLANNING and CONTROLLING: no ABORTED/RECOVERING in any run, preempt lands within hundredths of a millisecond of entering CANCELLING/PAUSING, PAUSED/CANCELLED only reported once the robot is actually stopped per odometry. Full numbers in the plan doc section 6. Excluded from this commit (pre-existing, unrelated): config/runtime/recovery_behaviors_params.yaml (allocated_time 1.0->2.0, SBPLDetourPlanner tuning predating this work). Not yet done (see plan doc "Trạng thái"): config tuning (phase 0, pending per a scoping decision); runtime scenarios for cancel mid-detour and a 30 s pause mid-action; commit to rb_ws is a separate step, not done here. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -14,6 +14,7 @@
|
||||
#include <robot/node_handle.h>
|
||||
|
||||
#include <action_core/action_handler.h>
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/runners/action_runner.h>
|
||||
|
||||
#include "fake_ports.h"
|
||||
@@ -69,6 +70,17 @@ public:
|
||||
{
|
||||
++update_count;
|
||||
action_core::ActionTick tick;
|
||||
if (ticks_after_cancel_left >= 0)
|
||||
{
|
||||
if (ticks_after_cancel_left-- > 0)
|
||||
{
|
||||
tick.status = action_core::ActionStatus::kRunning;
|
||||
return tick;
|
||||
}
|
||||
tick.status = action_core::ActionStatus::kCancelled;
|
||||
tick.message = "device safe";
|
||||
return tick;
|
||||
}
|
||||
tick.status = next_status;
|
||||
return tick;
|
||||
}
|
||||
@@ -76,15 +88,46 @@ public:
|
||||
void cancel() override
|
||||
{
|
||||
++cancel_count;
|
||||
if (cancel_needs_ticks)
|
||||
{
|
||||
ticks_after_cancel_left = cancel_ticks;
|
||||
next_status = action_core::ActionStatus::kRunning;
|
||||
}
|
||||
}
|
||||
|
||||
bool cancelNeedsTicks() const override
|
||||
{
|
||||
return cancel_needs_ticks;
|
||||
}
|
||||
|
||||
void pause(const robot::Time& now) override
|
||||
{
|
||||
++pause_count;
|
||||
last_pause_at = now;
|
||||
}
|
||||
|
||||
void resume(const robot::Time& now) override
|
||||
{
|
||||
++resume_count;
|
||||
last_resume_at = now;
|
||||
}
|
||||
|
||||
bool configure_ok = true;
|
||||
bool start_ok = true;
|
||||
action_core::ActionStatus next_status = action_core::ActionStatus::kRunning;
|
||||
|
||||
/// Mô hình handler thiết bị: sau cancel() còn `cancel_ticks` lượt update() rồi mới kCancelled.
|
||||
bool cancel_needs_ticks = false;
|
||||
int cancel_ticks = 2;
|
||||
int ticks_after_cancel_left = -1;
|
||||
|
||||
int start_count = 0;
|
||||
int update_count = 0;
|
||||
int cancel_count = 0;
|
||||
int pause_count = 0;
|
||||
int resume_count = 0;
|
||||
robot::Time last_pause_at;
|
||||
robot::Time last_resume_at;
|
||||
std::string last_action_id;
|
||||
|
||||
private:
|
||||
@@ -248,6 +291,100 @@ TEST(ActionRunner, CancelReachesHandlerAndClearsActive)
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed);
|
||||
}
|
||||
|
||||
TEST(ActionRunner, DeviceHandlerKeepsBeingTickedAfterCancelUntilItReportsCancelled)
|
||||
{
|
||||
// Pha 3 (2026-09-11): handler khai cancelNeedsTicks → runner GIỮ nó sau cancel(), tick tiếp tới
|
||||
// khi trả kCancelled; hàng kAction = stopping trong lúc đó, idle khi xong.
|
||||
Rig rig;
|
||||
move_base2::ComponentStatusBoard board;
|
||||
rig.runner.attachStatusBoard(&board);
|
||||
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"lift"});
|
||||
handler->cancel_needs_ticks = true;
|
||||
handler->cancel_ticks = 2;
|
||||
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||
ASSERT_TRUE(rig.load("actions_empty"));
|
||||
ASSERT_TRUE(rig.runner.start(makeAction("lift")));
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kBusy);
|
||||
|
||||
rig.runner.cancel();
|
||||
EXPECT_EQ(handler->cancel_count, 1);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kStopping);
|
||||
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kStopping);
|
||||
const ActionTick done = rig.runner.update();
|
||||
EXPECT_EQ(done.status, ActionTick::Status::kCancelled);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kIdle);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed) << "handler was released";
|
||||
}
|
||||
|
||||
TEST(ActionRunner, PerceptionHandlerIsReleasedRightAwayOnCancel)
|
||||
{
|
||||
Rig rig;
|
||||
move_base2::ComponentStatusBoard board;
|
||||
rig.runner.attachStatusBoard(&board);
|
||||
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"detect"});
|
||||
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||
ASSERT_TRUE(rig.load("actions_empty"));
|
||||
ASSERT_TRUE(rig.runner.start(makeAction("detect")));
|
||||
|
||||
rig.runner.cancel();
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kIdle);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed) << "no handler active";
|
||||
}
|
||||
|
||||
TEST(ActionRunner, PauseAndResumeReachTheHandlerWithTheClockTime)
|
||||
{
|
||||
Rig rig;
|
||||
move_base2::ComponentStatusBoard board;
|
||||
rig.runner.attachStatusBoard(&board);
|
||||
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"});
|
||||
ASSERT_TRUE(rig.runner.registerHandler(handler));
|
||||
ASSERT_TRUE(rig.load("actions_empty"));
|
||||
ASSERT_TRUE(rig.runner.start(makeAction("pick")));
|
||||
|
||||
rig.clock.advance(1.0);
|
||||
rig.runner.pause();
|
||||
EXPECT_EQ(handler->pause_count, 1);
|
||||
EXPECT_DOUBLE_EQ(handler->last_pause_at.toSec(), 1001.0);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kPaused);
|
||||
|
||||
rig.clock.advance(30.0);
|
||||
rig.runner.resume();
|
||||
EXPECT_EQ(handler->resume_count, 1);
|
||||
EXPECT_DOUBLE_EQ(handler->last_resume_at.toSec(), 1031.0);
|
||||
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kBusy);
|
||||
|
||||
// Không có action đang chạy thì pause/resume không tới handler nào.
|
||||
rig.runner.cancel();
|
||||
rig.runner.pause();
|
||||
rig.runner.resume();
|
||||
EXPECT_EQ(handler->pause_count, 1);
|
||||
EXPECT_EQ(handler->resume_count, 1);
|
||||
}
|
||||
|
||||
TEST(ActionRunner, LoadedNoopHandlerDoesNotCountPausedTimeTowardsItsDuration)
|
||||
{
|
||||
// Handler thật (noop, duration 2 s): pause 30 s giữa chừng, resume, phải còn chạy tiếp đúng phần
|
||||
// thời gian còn lại — không kết thúc sớm, không timeout oan.
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.load("actions"));
|
||||
ASSERT_TRUE(rig.runner.start(makeAction("wait", "w1"))); // duration: 2.0 s, timeout 10 s
|
||||
|
||||
rig.clock.advance(1.0);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
|
||||
|
||||
rig.runner.pause();
|
||||
rig.clock.advance(30.0); // đứng chờ lâu hơn cả timeout 10 s
|
||||
rig.runner.resume();
|
||||
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning)
|
||||
<< "the 30 s pause must not count: 1 s of 2 s elapsed, and the 10 s timeout must not fire";
|
||||
rig.clock.advance(1.0);
|
||||
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kSucceeded);
|
||||
}
|
||||
|
||||
TEST(ActionRunner, CancelWithoutActiveActionIsSafe)
|
||||
{
|
||||
Rig rig;
|
||||
|
||||
143
test/component_status_test.cpp
Normal file
143
test/component_status_test.cpp
Normal file
@@ -0,0 +1,143 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — test bảng trạng thái thành phần: nguồn sự thật cho quiescence và watchdog.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
|
||||
using move_base2::Component;
|
||||
using move_base2::ComponentPhase;
|
||||
using move_base2::ComponentStatusBoard;
|
||||
|
||||
TEST(ComponentStatusBoard, StartsIdleEverywhere)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||
{
|
||||
const Component c = static_cast<Component>(i);
|
||||
EXPECT_TRUE(board.isIdle(c)) << move_base2::toString(c);
|
||||
EXPECT_EQ(board.at(c).progress_ticks.load(), 0u);
|
||||
}
|
||||
EXPECT_FALSE(board.anyHung());
|
||||
EXPECT_TRUE(board.allIdle({Component::kGlobalPlanner, Component::kRecovery, Component::kAction}));
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, EnterChangesPhaseAndCountsAsProgress)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||
EXPECT_EQ(board.phase(Component::kGlobalPlanner), ComponentPhase::kBusy);
|
||||
EXPECT_FALSE(board.isIdle(Component::kGlobalPlanner));
|
||||
EXPECT_FALSE(board.allIdle({Component::kGlobalPlanner, Component::kRecovery}));
|
||||
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 1u);
|
||||
EXPECT_GT(board.at(Component::kGlobalPlanner).phase_since_ns.load(), 0);
|
||||
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||
EXPECT_EQ(board.phase(Component::kGlobalPlanner), ComponentPhase::kStopping);
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||
EXPECT_TRUE(board.isIdle(Component::kGlobalPlanner));
|
||||
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 3u);
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, ProgressDoesNotChangePhase)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
board.enter(Component::kRecovery, ComponentPhase::kBusy);
|
||||
const std::int64_t since = board.at(Component::kRecovery).phase_since_ns.load();
|
||||
board.progress(Component::kRecovery);
|
||||
board.progress(Component::kRecovery);
|
||||
EXPECT_EQ(board.phase(Component::kRecovery), ComponentPhase::kBusy);
|
||||
EXPECT_EQ(board.at(Component::kRecovery).phase_since_ns.load(), since)
|
||||
<< "progress must not restart the phase clock";
|
||||
EXPECT_EQ(board.at(Component::kRecovery).progress_ticks.load(), 3u);
|
||||
EXPECT_GE(board.at(Component::kRecovery).last_progress_ns.load(), since);
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, SecondsInPhaseAndSinceProgressGrowWithWallTime)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
board.enter(Component::kControlLoop, ComponentPhase::kBusy);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
EXPECT_GE(board.secondsInPhase(Component::kControlLoop), 0.015);
|
||||
EXPECT_GE(board.secondsSinceProgress(Component::kControlLoop), 0.015);
|
||||
board.progress(Component::kControlLoop);
|
||||
EXPECT_LT(board.secondsSinceProgress(Component::kControlLoop), 0.015);
|
||||
EXPECT_GE(board.secondsInPhase(Component::kControlLoop), 0.015) << "phase clock untouched";
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, AnyHungSeesASingleHungRow)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
board.enter(Component::kCostmapLocal, ComponentPhase::kHung);
|
||||
EXPECT_TRUE(board.anyHung());
|
||||
board.enter(Component::kCostmapLocal, ComponentPhase::kIdle);
|
||||
EXPECT_FALSE(board.anyHung());
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, EveryComponentAndPhaseHasAName)
|
||||
{
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||
{
|
||||
const std::string name = move_base2::toString(static_cast<Component>(i));
|
||||
EXPECT_FALSE(name.empty());
|
||||
EXPECT_NE(name, "unknown");
|
||||
}
|
||||
for (const ComponentPhase p : {ComponentPhase::kIdle, ComponentPhase::kBusy, ComponentPhase::kStopping,
|
||||
ComponentPhase::kPaused, ComponentPhase::kHung})
|
||||
{
|
||||
const std::string name = move_base2::toString(p);
|
||||
EXPECT_FALSE(name.empty());
|
||||
EXPECT_NE(name, "unknown");
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ComponentStatusBoard, ConcurrentWriterAndReaderDoNotTearOrCrash)
|
||||
{
|
||||
// Mô hình thật: thread planner ghi hàng của nó, control thread và watchdog đọc. Không lock — mọi
|
||||
// field atomic, đọc phải luôn thấy một phase hợp lệ.
|
||||
ComponentStatusBoard board;
|
||||
std::atomic<bool> stop{false};
|
||||
std::atomic<std::uint64_t> bad_reads{0};
|
||||
|
||||
std::thread writer([&] {
|
||||
for (int i = 0; i < 200000; ++i)
|
||||
{
|
||||
board.enter(Component::kGlobalPlanner, (i & 1) ? ComponentPhase::kBusy : ComponentPhase::kIdle);
|
||||
board.progress(Component::kGlobalPlanner);
|
||||
}
|
||||
stop = true;
|
||||
});
|
||||
std::thread reader([&] {
|
||||
while (!stop)
|
||||
{
|
||||
const ComponentPhase p = board.phase(Component::kGlobalPlanner);
|
||||
if (p != ComponentPhase::kBusy && p != ComponentPhase::kIdle)
|
||||
{
|
||||
++bad_reads;
|
||||
}
|
||||
(void)board.secondsInPhase(Component::kGlobalPlanner);
|
||||
(void)board.allIdle({Component::kGlobalPlanner, Component::kRecovery});
|
||||
}
|
||||
});
|
||||
writer.join();
|
||||
reader.join();
|
||||
EXPECT_EQ(bad_reads.load(), 0u);
|
||||
EXPECT_EQ(board.at(Component::kGlobalPlanner).progress_ticks.load(), 400000u);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -16,6 +16,14 @@ move_base2:
|
||||
action_patience: 0.0 # [s] 0 = tắt; lưới cuối, không phải cơ chế timeout chính
|
||||
max_planning_retries: -1 # < 0 = không giới hạn
|
||||
recovery_behavior_enabled: true
|
||||
settle_timeout: 3.5 # [s] chờ quiescent ở CANCELLING; 0 = tắt
|
||||
stopped_measured_linear_eps: 0.03 # [m/s] "đã dừng" theo odom; 0 = bỏ odom
|
||||
stopped_measured_angular_eps: 0.04 # [rad/s]
|
||||
watchdog_period: 0.25 # [s]
|
||||
local_planner_call_budget: 0.7 # [s]
|
||||
recovery_stall_budget: 6.0 # [s]
|
||||
action_stall_budget: 1.5 # [s]
|
||||
control_loop_stall_budget: 0.9 # [s]
|
||||
|
||||
max_vel_x: 0.5 # [m/s] tiến
|
||||
min_vel_x: -0.2 # [m/s] lùi, ÂM
|
||||
@@ -276,6 +284,10 @@ TestPlannerThrowing:
|
||||
library_path: libmove_base2_test_global_planner
|
||||
TestPlannerInitFails:
|
||||
library_path: libmove_base2_test_global_planner
|
||||
TestPlannerSlowPreemptable: # search 2 s, thoát khi preempt() — mô hình SBPL + abort flag
|
||||
library_path: libmove_base2_test_global_planner
|
||||
TestPlannerSlowStubborn: # search 0.4 s, KHÔNG nhìn preempt — mô hình plugin cũ
|
||||
library_path: libmove_base2_test_global_planner
|
||||
|
||||
# TestPlannerMissingLibrary cố ý KHÔNG khai library_path.
|
||||
|
||||
|
||||
@@ -55,6 +55,42 @@ TEST(MoveBase2Config, DefaultsAreValid)
|
||||
EXPECT_TRUE(config.validate(error)) << error;
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, CancelSettleKeysFallBackToDefaultsWhenAbsent)
|
||||
{
|
||||
// Cây config cũ (trước 2026-09-11) không có ba khoá này: phải giữ default BẬT (2 s, 0.02) chứ
|
||||
// không im lặng rơi về hành vi cũ "CANCELLED ngay khi lệnh = 0".
|
||||
const MoveBase2Config config = loadFrom("move_base2_no_planner");
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.settle_timeout, 2.0);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_linear_eps, 0.02);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_angular_eps, 0.02);
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, WatchdogKeysFallBackToDefaultsWhenAbsent)
|
||||
{
|
||||
const MoveBase2Config config = loadFrom("move_base2_no_planner");
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.period, 0.1);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.control_loop_stall_budget, 0.5);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.action_stall_budget, 0.0);
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, RejectsNegativeWatchdogPeriod)
|
||||
{
|
||||
MoveBase2Config config = minimalValid();
|
||||
config.watchdog.period = -1.0;
|
||||
std::string error;
|
||||
EXPECT_FALSE(config.validate(error));
|
||||
EXPECT_NE(error.find("watchdog_period"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, RejectsNegativeCancelSettleTimeout)
|
||||
{
|
||||
MoveBase2Config config = minimalValid();
|
||||
config.state_machine.settle_timeout = -0.5;
|
||||
std::string error;
|
||||
EXPECT_FALSE(config.validate(error));
|
||||
EXPECT_NE(error.find("settle_timeout"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(MoveBase2Config, RejectsRecoveryEnabledWithNoBehaviorLoaded)
|
||||
{
|
||||
// Ràng buộc thứ tự khởi tạo: RecoveryRunner không nạp được behavior nào mà
|
||||
@@ -153,6 +189,16 @@ TEST(MoveBase2Config, ReadsEveryGroupFromYaml)
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.controller_patience, 15.0);
|
||||
EXPECT_EQ(config.state_machine.max_planning_retries, -1);
|
||||
EXPECT_TRUE(config.state_machine.recovery_enabled);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.settle_timeout, 3.5);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_linear_eps, 0.03);
|
||||
EXPECT_DOUBLE_EQ(config.state_machine.stopped_measured_angular_eps, 0.04);
|
||||
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.period, 0.25);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.planner_timeout, 5.0) << "copied from planner_timeout";
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.local_planner_call_budget, 0.7);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.recovery_stall_budget, 6.0);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.action_stall_budget, 1.5);
|
||||
EXPECT_DOUBLE_EQ(config.watchdog.control_loop_stall_budget, 0.9);
|
||||
|
||||
EXPECT_DOUBLE_EQ(config.velocity.max_vel_x, 0.5);
|
||||
EXPECT_DOUBLE_EQ(config.velocity.min_vel_x, -0.2);
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
|
||||
#include <robot/time.h>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/ports/action_port.h>
|
||||
#include <move_base2/ports/clock_port.h>
|
||||
#include <move_base2/ports/controller_port.h>
|
||||
@@ -221,6 +222,7 @@ public:
|
||||
pending_goal_ = goal;
|
||||
cycles_left_ = latency_cycles_;
|
||||
pending_action_ = nextAction();
|
||||
report(ComponentPhase::kBusy);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -248,6 +250,14 @@ public:
|
||||
}
|
||||
|
||||
in_flight_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
if (discarded_)
|
||||
{
|
||||
// Lượt đã bị huỷ giữa chừng nhưng plugin không cắt được (SBPL thật): kết quả về thì vứt lặng
|
||||
// lẽ, đúng như PlannerRunner với discard_. Bên gọi chỉ thấy isPlanning() chuyển về false.
|
||||
discarded_ = false;
|
||||
return false;
|
||||
}
|
||||
result.tag = pending_tag_;
|
||||
result.plan.clear();
|
||||
|
||||
@@ -272,8 +282,23 @@ public:
|
||||
|
||||
void cancelPlan() override
|
||||
{
|
||||
in_flight_ = false;
|
||||
++cancel_count_;
|
||||
if (cancel_keeps_busy_ && in_flight_)
|
||||
{
|
||||
// Mô phỏng plugin KHÔNG preempt được: thread vẫn bận cho tới hết latency đã đặt, kết quả
|
||||
// về bị vứt. Đây là hành vi của PlannerRunner + SBPL trước pha 2.
|
||||
discarded_ = true;
|
||||
report(ComponentPhase::kStopping);
|
||||
return;
|
||||
}
|
||||
in_flight_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
/// @brief Ghi hàng `kGlobalPlanner` như PlannerRunner thật. Null = không khai.
|
||||
void attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
std::string activePlanner() const override
|
||||
@@ -281,6 +306,18 @@ public:
|
||||
return active_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sau cancelPlan(), lượt đang chạy vẫn chiếm thread cho tới hết latency (mặc định false:
|
||||
* cancel cắt ngay, như plugin có preempt).
|
||||
*
|
||||
* Bật để tái hiện log 2026-09-11: cancel lúc SBPL đang chạy, goal kế bị `startPlan()` từ chối
|
||||
* suốt mấy giây.
|
||||
*/
|
||||
void setCancelKeepsBusy(bool keeps_busy)
|
||||
{
|
||||
cancel_keeps_busy_ = keeps_busy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Số cycle mà một lượt lập plan "mất" trước khi có kết quả.
|
||||
*
|
||||
@@ -356,6 +393,17 @@ private:
|
||||
std::size_t latency_cycles_ = 0;
|
||||
std::size_t cycles_left_ = 0;
|
||||
std::size_t cancel_count_ = 0;
|
||||
bool cancel_keeps_busy_ = false;
|
||||
bool discarded_ = false;
|
||||
ComponentStatusBoard* status_board_ = nullptr;
|
||||
|
||||
void report(ComponentPhase phase)
|
||||
{
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kGlobalPlanner, phase);
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t make_plan_count_ = 0;
|
||||
std::size_t swap_count_ = 0;
|
||||
@@ -438,6 +486,28 @@ public:
|
||||
void setMeasuredVelocity(const robot_geometry_msgs::Twist& velocity) override
|
||||
{
|
||||
measured_velocity_ = velocity;
|
||||
has_measured_velocity_ = true;
|
||||
}
|
||||
|
||||
/// Cổng thật (ControllerRunner) trả false cho tới khi host đẩy odom vào; fake giữ đúng nghĩa đó
|
||||
/// để mọi test không đẩy odom vẫn đi đường "đo bằng lệnh đã phát" như trước.
|
||||
bool measuredVelocity(robot_geometry_msgs::Twist& out) const override
|
||||
{
|
||||
if (!has_measured_velocity_)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
out = measured_velocity_;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @brief Giả lập odom: robot đang lăn với @p linear_x [m/s], @p angular_z [rad/s].
|
||||
void setOdometry(double linear_x, double angular_z = 0.0)
|
||||
{
|
||||
robot_geometry_msgs::Twist twist;
|
||||
twist.linear.x = linear_x;
|
||||
twist.angular.z = angular_z;
|
||||
setMeasuredVelocity(twist);
|
||||
}
|
||||
|
||||
void getLocalPlan(robot_nav_2d_msgs::Path2D& plan) override
|
||||
@@ -546,6 +616,7 @@ public:
|
||||
private:
|
||||
robot_nav_2d_msgs::Path2D local_plan_;
|
||||
robot_geometry_msgs::Twist measured_velocity_;
|
||||
bool has_measured_velocity_ = false;
|
||||
double limit_forward_ = 0.0; ///< [m/s]
|
||||
double limit_backward_ = 0.0; ///< [m/s], âm
|
||||
double limit_angular_ = 0.0; ///< [rad/s]
|
||||
@@ -633,6 +704,7 @@ public:
|
||||
return false;
|
||||
}
|
||||
active_ = true;
|
||||
report(ComponentPhase::kBusy);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -647,6 +719,10 @@ public:
|
||||
tick.status = RecoveryTick::Status::kRunning;
|
||||
tick.has_velocity = emits_velocity_;
|
||||
tick.cmd.linear.x = recovery_speed_;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->progress(Component::kRecovery);
|
||||
}
|
||||
break;
|
||||
case RecoveryScript::kSucceeded:
|
||||
tick.status = RecoveryTick::Status::kSucceeded;
|
||||
@@ -656,15 +732,44 @@ public:
|
||||
tick.path = success_path_;
|
||||
}
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
break;
|
||||
case RecoveryScript::kFailed:
|
||||
tick.status = RecoveryTick::Status::kFailed;
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
break;
|
||||
}
|
||||
return tick;
|
||||
}
|
||||
|
||||
/// @brief Ghi hàng `kRecovery` như RecoveryRunner thật. Null = không khai.
|
||||
void attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sau cancel(), behavior vẫn "bận" thêm @p cycles tick — mô phỏng detour worker chưa thoát.
|
||||
* Hàng kRecovery giữ kStopping; test gọi @ref settleCancel để nhả.
|
||||
*/
|
||||
void setCancelKeepsBusy(bool keeps_busy)
|
||||
{
|
||||
cancel_keeps_busy_ = keeps_busy;
|
||||
}
|
||||
|
||||
/// @brief Worker giả đã thoát: hàng về idle.
|
||||
void settleCancel()
|
||||
{
|
||||
stopping_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
bool stopping() const
|
||||
{
|
||||
return stopping_;
|
||||
}
|
||||
|
||||
/// @brief Thành công thì kèm một detour path (như 'detour_path' thật) — cần cho stand-down của kContact.
|
||||
void setSucceedWithPath(std::vector<robot_geometry_msgs::PoseStamped> path)
|
||||
{
|
||||
@@ -675,7 +780,17 @@ public:
|
||||
void cancel() override
|
||||
{
|
||||
++cancel_count_;
|
||||
const bool was_active = active_;
|
||||
active_ = false;
|
||||
if (was_active && cancel_keeps_busy_)
|
||||
{
|
||||
stopping_ = true;
|
||||
report(ComponentPhase::kStopping);
|
||||
}
|
||||
else
|
||||
{
|
||||
report(ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
std::string behaviorName(std::size_t index) const override
|
||||
@@ -772,6 +887,18 @@ private:
|
||||
std::size_t last_start_index_ = 0;
|
||||
RecoveryTrigger last_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
std::vector<std::size_t> started_indices_;
|
||||
|
||||
bool cancel_keeps_busy_ = false;
|
||||
bool stopping_ = false;
|
||||
ComponentStatusBoard* status_board_ = nullptr;
|
||||
|
||||
void report(ComponentPhase phase)
|
||||
{
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kRecovery, phase);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
@@ -793,6 +920,7 @@ public:
|
||||
return false;
|
||||
}
|
||||
active_ = true;
|
||||
report(ComponentPhase::kBusy);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -801,19 +929,45 @@ public:
|
||||
++update_count_;
|
||||
|
||||
ActionTick tick;
|
||||
if (stopping_)
|
||||
{
|
||||
if (cancel_ticks_left_ > 0)
|
||||
{
|
||||
--cancel_ticks_left_;
|
||||
tick.status = ActionTick::Status::kRunning;
|
||||
tick.message = "moving the device to a safe position";
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->progress(Component::kAction);
|
||||
}
|
||||
return tick;
|
||||
}
|
||||
stopping_ = false;
|
||||
active_ = false;
|
||||
tick.status = ActionTick::Status::kCancelled;
|
||||
tick.message = "device safe";
|
||||
report(ComponentPhase::kIdle);
|
||||
return tick;
|
||||
}
|
||||
switch (nextAction())
|
||||
{
|
||||
case ActionScript::kRunning:
|
||||
tick.status = ActionTick::Status::kRunning;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->progress(Component::kAction);
|
||||
}
|
||||
break;
|
||||
case ActionScript::kSucceeded:
|
||||
tick.status = ActionTick::Status::kSucceeded;
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
break;
|
||||
case ActionScript::kFailed:
|
||||
tick.status = ActionTick::Status::kFailed;
|
||||
tick.message = "fake action failed";
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
break;
|
||||
}
|
||||
return tick;
|
||||
@@ -822,7 +976,56 @@ public:
|
||||
void cancel() override
|
||||
{
|
||||
++cancel_count_;
|
||||
if (active_ && cancel_ticks_needed_ > 0)
|
||||
{
|
||||
// Handler thiết bị (pha 3): giữ "đang dừng" thêm N tick rồi trả kCancelled.
|
||||
cancel_ticks_left_ = cancel_ticks_needed_;
|
||||
stopping_ = true;
|
||||
report(ComponentPhase::kStopping);
|
||||
return;
|
||||
}
|
||||
active_ = false;
|
||||
report(ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
void pause() override
|
||||
{
|
||||
++pause_count_;
|
||||
if (active_)
|
||||
{
|
||||
report(ComponentPhase::kPaused);
|
||||
}
|
||||
}
|
||||
|
||||
void resume() override
|
||||
{
|
||||
++resume_count_;
|
||||
if (active_)
|
||||
{
|
||||
report(ComponentPhase::kBusy);
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief Sau cancel() handler cần @p ticks lượt update() nữa mới trả kCancelled (0 = dừng ngay).
|
||||
void setCancelNeedsTicks(std::size_t ticks)
|
||||
{
|
||||
cancel_ticks_needed_ = ticks;
|
||||
}
|
||||
|
||||
std::size_t pauseCount() const
|
||||
{
|
||||
return pause_count_;
|
||||
}
|
||||
|
||||
std::size_t resumeCount() const
|
||||
{
|
||||
return resume_count_;
|
||||
}
|
||||
|
||||
/// @brief Ghi hàng `kAction` như ActionRunner thật. Null = không khai.
|
||||
void attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
void setScript(std::vector<ActionScript> script)
|
||||
@@ -885,7 +1088,21 @@ private:
|
||||
std::size_t start_count_ = 0;
|
||||
std::size_t update_count_ = 0;
|
||||
std::size_t cancel_count_ = 0;
|
||||
std::size_t pause_count_ = 0;
|
||||
std::size_t resume_count_ = 0;
|
||||
std::size_t cancel_ticks_needed_ = 0;
|
||||
std::size_t cancel_ticks_left_ = 0;
|
||||
bool stopping_ = false;
|
||||
std::vector<std::string> started_action_types_;
|
||||
ComponentStatusBoard* status_board_ = nullptr;
|
||||
|
||||
void report(ComponentPhase phase)
|
||||
{
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, phase);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -147,6 +147,10 @@ public:
|
||||
deps_.recovery = &recovery_;
|
||||
deps_.mission = &mission_;
|
||||
deps_.action = &action_;
|
||||
deps_.components = &components_;
|
||||
planner_.attachStatusBoard(&components_);
|
||||
recovery_.attachStatusBoard(&components_);
|
||||
action_.attachStatusBoard(&components_);
|
||||
}
|
||||
|
||||
void configure(const ControlLoopConfig& config = baseConfig())
|
||||
@@ -199,6 +203,7 @@ public:
|
||||
FakeRecoveryPort recovery_;
|
||||
FakeMissionPort mission_;
|
||||
FakeActionPort action_;
|
||||
move_base2::ComponentStatusBoard components_;
|
||||
ControlLoopDeps deps_;
|
||||
|
||||
robot_costmap_2d::LayeredCostmap global_;
|
||||
@@ -842,7 +847,11 @@ TEST(NavigationServerLifecycle, PauseTakesEffectOnTheNextCycleNotImmediately)
|
||||
<< "pause() goes straight into the core from the host thread";
|
||||
|
||||
fixture.spin(1);
|
||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPausing)
|
||||
<< "pause is taken in one cycle: command zero, waiting for the runtime to settle";
|
||||
fixture.spin(1);
|
||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused)
|
||||
<< "nothing is busy in this fixture, so PAUSED follows one cycle later";
|
||||
}
|
||||
|
||||
TEST(NavigationServerLifecycle, ResumeAfterPauseReturnsToControlling)
|
||||
@@ -856,7 +865,7 @@ TEST(NavigationServerLifecycle, ResumeAfterPauseReturnsToControlling)
|
||||
fixture.spin(2);
|
||||
|
||||
fixture.server_.pause();
|
||||
fixture.spin(1);
|
||||
fixture.spin(2);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
|
||||
fixture.server_.resume();
|
||||
@@ -901,6 +910,7 @@ TEST(NavigationServerLifecycle, CancelWinsOverAPauseRequestedInTheSameCycle)
|
||||
fixture.spin(1);
|
||||
|
||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused) << "pause won over cancel";
|
||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing) << "pause won over cancel";
|
||||
}
|
||||
|
||||
TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
|
||||
@@ -914,13 +924,14 @@ TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
|
||||
fixture.spin(2);
|
||||
|
||||
fixture.server_.pause();
|
||||
fixture.spin(1);
|
||||
fixture.spin(2);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
|
||||
// Không có lệnh mới: cờ đã bị tiêu thụ, các cycle sau không được tự tạm dừng lại lần nữa.
|
||||
fixture.server_.resume();
|
||||
fixture.spin(3);
|
||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
@@ -1149,6 +1160,169 @@ TEST(NavigationServerFeedback, NothingIsLatchedBeforeTheFirstRequest)
|
||||
<< "a freshly booted runtime reports a terminal result although no goal has ever been sent";
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// PREEMPTING phải nói thật (2026-09-11): host đọc PREEMPTED là "xong rồi, gửi goal kế được". Cancel
|
||||
// lúc SBPL đang chạy mà báo PREEMPTED sau 33 ms thì host gửi goal kế vào một runtime còn bận —
|
||||
// đúng chuỗi sự kiện trong log robot_app.log dẫn tới ABORTED oan.
|
||||
// ================================================================================================
|
||||
|
||||
TEST(NavigationServerFeedback, PreemptingIsHeldUntilTheCancelledPlannerAttemptReallyEnds)
|
||||
{
|
||||
Fixture fixture;
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.planner_patience = 5.0; // [s]
|
||||
config.state_machine.settle_timeout = 2.0; // [s]
|
||||
fixture.configure(config);
|
||||
fixture.planner_.setLatencyCycles(10);
|
||||
fixture.planner_.setCancelKeepsBusy(true); // SBPL trước pha 2: cancelPlan() không cắt được
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
fixture.spin(2);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPlanning);
|
||||
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||
|
||||
fixture.server_.cancel();
|
||||
fixture.spin(1);
|
||||
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::PREEMPTING);
|
||||
|
||||
// Host poll 100 ms một lần = 2 cycle @ 20 Hz: mỗi lần poll trong lúc thread còn bận phải vẫn
|
||||
// thấy PREEMPTING, không phải PREEMPTED.
|
||||
std::size_t polls_while_busy = 0;
|
||||
for (int i = 0; i < 20 && fixture.planner_.isPlanning(); ++i)
|
||||
{
|
||||
fixture.spin(2);
|
||||
if (fixture.planner_.isPlanning())
|
||||
{
|
||||
++polls_while_busy;
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::PREEMPTING)
|
||||
<< "poll " << i << ": PREEMPTED reported while the planner thread is still busy";
|
||||
}
|
||||
}
|
||||
EXPECT_GE(polls_while_busy, 2u);
|
||||
|
||||
fixture.spin(2);
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::PREEMPTED)
|
||||
<< "once the thread is idle the cancel must be reported (and latched) as PREEMPTED";
|
||||
}
|
||||
|
||||
TEST(NavigationServerFeedback, GoalSentWhilePreemptingIsAcceptedAndRunsOnceThePlannerIsFree)
|
||||
{
|
||||
// Host cũ không đợi PREEMPTED. Vẫn phải chạy đúng: goal kế xếp sau, không bị coi là hỏng.
|
||||
Fixture fixture;
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.planner_patience = 5.0; // [s]
|
||||
config.state_machine.max_planning_retries = 0; // như máy chạy log
|
||||
fixture.configure(config);
|
||||
fixture.planner_.setLatencyCycles(10);
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
fixture.controller_.setScript({ ControllerScript::kOk });
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
fixture.spin(2);
|
||||
fixture.server_.cancel();
|
||||
fixture.spin(1);
|
||||
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::PREEMPTING);
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(5.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
|
||||
bool saw_clearing_or_aborted = false;
|
||||
bool reached_controlling = false;
|
||||
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||
{
|
||||
fixture.spin(1);
|
||||
const auto host = fixture.server_.getFeedback()->navigation_state;
|
||||
saw_clearing_or_aborted = saw_clearing_or_aborted ||
|
||||
host == robot::move_base_core::State::CLEARING ||
|
||||
host == robot::move_base_core::State::ABORTED;
|
||||
reached_controlling = host == robot::move_base_core::State::CONTROLLING;
|
||||
}
|
||||
EXPECT_FALSE(saw_clearing_or_aborted) << "the second goal went through recovery/abort";
|
||||
EXPECT_TRUE(reached_controlling);
|
||||
}
|
||||
|
||||
TEST(NavigationServerFeedback, PausedIsReportedOnlyOnceTheRuntimeIsQuiescent)
|
||||
{
|
||||
// PAUSING nói thật (2026-09-11): pause lúc SBPL còn chạy → host vẫn thấy PLANNING (+ feed_back_str
|
||||
// "pausing…"), KHÔNG phải PAUSED; PAUSED chỉ khi thread planner đã nhả.
|
||||
Fixture fixture;
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.planner_patience = 5.0; // [s]
|
||||
fixture.configure(config);
|
||||
fixture.planner_.setLatencyCycles(10);
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
fixture.spin(2);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPlanning);
|
||||
|
||||
fixture.server_.pause();
|
||||
fixture.spin(1);
|
||||
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPausing);
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PLANNING)
|
||||
<< "while pausing the host must keep seeing the state that is still winding down";
|
||||
EXPECT_NE(fixture.server_.getFeedback()->feed_back_str.find("pausing"), std::string::npos);
|
||||
|
||||
std::size_t polls_while_busy = 0;
|
||||
for (int i = 0; i < 20 && fixture.planner_.isPlanning(); ++i)
|
||||
{
|
||||
fixture.spin(2);
|
||||
if (fixture.planner_.isPlanning())
|
||||
{
|
||||
++polls_while_busy;
|
||||
EXPECT_NE(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PAUSED)
|
||||
<< "poll " << i << ": PAUSED reported while the planner thread is still busy";
|
||||
}
|
||||
}
|
||||
EXPECT_GE(polls_while_busy, 2u);
|
||||
|
||||
fixture.spin(2);
|
||||
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PAUSED);
|
||||
}
|
||||
|
||||
TEST(NavigationServerFeedback, StalledControlThreadIsReportedAsLostByTheWatchdog)
|
||||
{
|
||||
// Pha 4 (2026-09-11): control thread treo thì refreshFeedback() không chạy nữa, host đọc mãi
|
||||
// state cuối. Watchdog (thread riêng) phải ghi đè thành LOST trong getFeedback() — trên thread host.
|
||||
Fixture fixture;
|
||||
fixture.configure();
|
||||
fixture.controller_.setScript({ ControllerScript::kOk });
|
||||
|
||||
move_base2::WatchdogConfig dog;
|
||||
dog.period = 0.01; // [s]
|
||||
dog.control_loop_stall_budget = 0.05; // [s]
|
||||
std::string error;
|
||||
ASSERT_TRUE(fixture.server_.startWatchdog(&fixture.components_, dog, error)) << error;
|
||||
|
||||
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
||||
<< fixture.server_.lastRejectReason();
|
||||
fixture.spin(3); // mỗi spinOnce() là một heartbeat của "control thread"
|
||||
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::CONTROLLING);
|
||||
|
||||
// Control thread "treo": không spinOnce nữa. Watchdog phải tự thấy sau ngân sách.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(150));
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::LOST)
|
||||
<< "a frozen CONTROLLING must not look like a running one";
|
||||
EXPECT_NE(fixture.server_.getFeedback()->feed_back_str.find("control thread stalled"),
|
||||
std::string::npos);
|
||||
|
||||
// Thread quay lại → hết LOST, state thật quay về.
|
||||
fixture.spin(2);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(30));
|
||||
fixture.spin(1);
|
||||
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
||||
robot::move_base_core::State::CONTROLLING);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// executeInstantAction() — cửa duy nhất nhận một action lẻ
|
||||
//
|
||||
|
||||
@@ -385,6 +385,181 @@ TEST(PlannerRunner, CancelledPlanProducesNoResult)
|
||||
"nobody asks for anymore";
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, CancelPreemptsAPreemptablePlannerWithinMilliseconds)
|
||||
{
|
||||
// 2026-09-11: plugin implement robot_nav_core::Preemptable thì cancelPlan() cắt lượt đang chạy —
|
||||
// thread rảnh trong vài ms thay vì 2 s. Đây là thứ làm CANCELLED/PAUSED nói thật mà không phải chờ.
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||
|
||||
const auto before = std::chrono::steady_clock::now();
|
||||
fixture.runner_.cancelPlan();
|
||||
int waited_ms = 0;
|
||||
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
++waited_ms;
|
||||
}
|
||||
const double elapsed_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
EXPECT_LT(elapsed_ms, 200.0) << "preempt did not reach the planner; the thread ran to the end";
|
||||
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "a preempted attempt must not deliver a plan";
|
||||
|
||||
// Lượt kế phải khởi động được ngay và chạy bình thường (cờ preempt không dính sang lượt sau).
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
|
||||
EXPECT_TRUE(fixture.runner_.isPlanning());
|
||||
fixture.runner_.cancelPlan();
|
||||
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, SwapWhileAPreemptablePlannerIsRunningCutsTheOldAttempt)
|
||||
{
|
||||
// Đổi profile (mission kế dùng planner khác) trong lúc lượt cũ chưa về: swapPlanner phải cắt
|
||||
// instance ĐANG chạy, không chỉ đánh dấu vứt. Không cắt thì yêu cầu kế đứng ở kBusy tới hết
|
||||
// allocated_time của lượt cũ (2 s ở đây, 10-30 s với SBPL thật).
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||
|
||||
const auto before = std::chrono::steady_clock::now();
|
||||
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
|
||||
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
const double elapsed_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
EXPECT_LT(elapsed_ms, 200.0) << "swapPlanner did not preempt the running instance";
|
||||
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "the old planner's attempt must be discarded";
|
||||
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
|
||||
|
||||
// Planner mới chạy bình thường ngay sau đó.
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
|
||||
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
ASSERT_TRUE(fixture.runner_.pollPlan(result));
|
||||
EXPECT_TRUE(result.succeeded);
|
||||
EXPECT_EQ(result.tag, 2U);
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, CancelAfterSwapPreemptsTheInstanceThatIsActuallyRunning)
|
||||
{
|
||||
// Thứ tự thật trong log 2026-09-11 (mission 2 đổi profile TRƯỚC khi accept_request gọi
|
||||
// cancelPlan): active_ đã trỏ sang planner mới, nhưng thread vẫn ở trong makePlan của planner cũ.
|
||||
// cancelPlan phải cắt đúng instance đang chạy, không phải active_.
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||
|
||||
// Đổi sang planner "ngoan" (stubborn — không Preemptable) để chứng minh cancel không nhìn active_:
|
||||
// nếu cancel dynamic_cast trên active_ thì ra null và lượt Preemptable đang chạy KHÔNG bị cắt.
|
||||
// Lưu ý: swapPlanner nay cũng preempt; để tách bạch, test này chỉ khẳng định tổng thể thread rảnh
|
||||
// trong vài ms sau cặp swap+cancel, đúng như ControlLoop làm khi nhận goal mới.
|
||||
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowStubborn"));
|
||||
fixture.runner_.cancelPlan();
|
||||
int waited_ms = 0;
|
||||
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
++waited_ms;
|
||||
}
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
EXPECT_LT(waited_ms, 200) << "the running Preemptable instance was not the one preempted";
|
||||
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, SwapWhileTheJobIsQueuedButNotStartedDropsIt)
|
||||
{
|
||||
// Yêu cầu vừa được đặt, thread chưa kịp nhận: đổi planner phải rút yêu cầu đó ra, không để thread
|
||||
// chạy yêu cầu của planner cũ trên instance mới rồi vứt.
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
bool dropped_before_start = false;
|
||||
for (int attempt = 0; attempt < 50 && !dropped_before_start; ++attempt)
|
||||
{
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
|
||||
// Cả hai nhánh (rút trước khi thread nhận / cắt sau khi nó nhận) đều phải rảnh trong vài ms.
|
||||
int waited_ms = 0;
|
||||
while (fixture.runner_.isPlanning() && waited_ms < 1000)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
++waited_ms;
|
||||
}
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
EXPECT_LT(waited_ms, 200);
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||
dropped_before_start = (waited_ms == 0);
|
||||
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowPreemptable"));
|
||||
}
|
||||
// Không ép nhánh "rút trước khi nhận" phải xảy ra (phụ thuộc scheduler), chỉ cần cả hai nhánh
|
||||
// đều đúng.
|
||||
SUCCEED();
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, DestructorPreemptsARunningPreemptablePlanner)
|
||||
{
|
||||
// Shutdown giữa một lượt search dài: destructor phải cắt lượt đó thay vì chờ hết allocated_time.
|
||||
const auto before = std::chrono::steady_clock::now();
|
||||
{
|
||||
Fixture fixture("TestPlannerSlowPreemptable");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
ASSERT_TRUE(fixture.runner_.isPlanning());
|
||||
}
|
||||
const double elapsed_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
|
||||
EXPECT_LT(elapsed_ms, 500.0) << "destructor waited for the whole 2 s search";
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, CancelOnAStubbornPlannerFallsBackToDiscardingTheResult)
|
||||
{
|
||||
// Plugin cũ (không Preemptable): hành vi trước 2026-09-11 giữ nguyên — thread bận tới hết lượt,
|
||||
// kết quả về bị vứt. isPlanning() phải nói thật suốt quãng đó.
|
||||
Fixture fixture("TestPlannerSlowStubborn");
|
||||
ASSERT_TRUE(fixture.ok()) << fixture.error();
|
||||
|
||||
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
fixture.runner_.cancelPlan();
|
||||
EXPECT_TRUE(fixture.runner_.isPlanning()) << "a stubborn planner cannot be cut short";
|
||||
|
||||
for (int i = 0; i < 2000 && fixture.runner_.isPlanning(); ++i)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
EXPECT_FALSE(fixture.runner_.isPlanning());
|
||||
move_base2::PlanResult result;
|
||||
EXPECT_FALSE(fixture.runner_.pollPlan(result));
|
||||
}
|
||||
|
||||
TEST(PlannerRunner, ResultCarriesBackTheTagItWasStartedWith)
|
||||
{
|
||||
Fixture fixture;
|
||||
|
||||
@@ -17,7 +17,10 @@
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <thread>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -29,6 +32,7 @@
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot_nav_core/base_global_planner.h>
|
||||
#include <robot_nav_core/preemptable.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
@@ -129,6 +133,85 @@ private:
|
||||
bool saw_order_ = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class TestSlowPlanner
|
||||
* @brief Planner giả "search dài": ngủ từng lát 5 ms trong @p seconds. Bản Preemptable thoát khi
|
||||
* thấy cờ (mô hình ARA* + abort flag); bản "stubborn" không nhìn cờ (mô hình plugin cũ).
|
||||
*/
|
||||
class TestSlowPlannerBase : public robot_nav_core::BaseGlobalPlanner
|
||||
{
|
||||
public:
|
||||
explicit TestSlowPlannerBase(double seconds, bool honours_preempt)
|
||||
: seconds_(seconds), honours_preempt_(honours_preempt)
|
||||
{
|
||||
}
|
||||
|
||||
bool initialize(std::string /*name*/, robot_costmap_2d::Costmap2DROBOT* /*costmap_robot*/) override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool makePlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
const robot_geometry_msgs::PoseStamped& goal,
|
||||
std::vector<robot_geometry_msgs::PoseStamped>& plan) override
|
||||
{
|
||||
preempt_.store(false, std::memory_order_relaxed);
|
||||
const auto deadline = std::chrono::steady_clock::now() +
|
||||
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
||||
std::chrono::duration<double>(seconds_));
|
||||
while (std::chrono::steady_clock::now() < deadline)
|
||||
{
|
||||
if (honours_preempt_ && preempt_.load(std::memory_order_relaxed))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
}
|
||||
plan.clear();
|
||||
plan.push_back(start);
|
||||
plan.push_back(goal);
|
||||
return true;
|
||||
}
|
||||
|
||||
protected:
|
||||
std::atomic<bool> preempt_{false};
|
||||
|
||||
private:
|
||||
double seconds_;
|
||||
bool honours_preempt_;
|
||||
};
|
||||
|
||||
class TestSlowPreemptablePlanner final : public TestSlowPlannerBase,
|
||||
public robot_nav_core::Preemptable
|
||||
{
|
||||
public:
|
||||
TestSlowPreemptablePlanner() : TestSlowPlannerBase(2.0, true)
|
||||
{
|
||||
}
|
||||
void preempt() override
|
||||
{
|
||||
preempt_.store(true, std::memory_order_relaxed);
|
||||
}
|
||||
};
|
||||
|
||||
class TestSlowStubbornPlanner final : public TestSlowPlannerBase
|
||||
{
|
||||
public:
|
||||
TestSlowStubbornPlanner() : TestSlowPlannerBase(0.4, false)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr createSlowPreemptable()
|
||||
{
|
||||
return std::make_shared<TestSlowPreemptablePlanner>();
|
||||
}
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr createSlowStubborn()
|
||||
{
|
||||
return std::make_shared<TestSlowStubbornPlanner>();
|
||||
}
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr createOk()
|
||||
{
|
||||
return std::make_shared<TestGlobalPlanner>(TestGlobalPlanner::Behavior::kOk);
|
||||
@@ -168,5 +251,7 @@ BOOST_DLL_ALIAS(move_base2::testing::createOk, TestPlannerOk)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createEmptyPlan, TestPlannerEmptyPlan)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createThrowing, TestPlannerThrowing)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createInitFailing, TestPlannerInitFails)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createSlowPreemptable, TestPlannerSlowPreemptable)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::createSlowStubborn, TestPlannerSlowStubborn)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::initializeCount, TestPlannerInitializeCount)
|
||||
BOOST_DLL_ALIAS(move_base2::testing::lastFootprintDock, TestPlannerLastFootprintDock)
|
||||
|
||||
@@ -240,6 +240,39 @@ TEST(StateMachineConfig, RejectsResolvedRouteWithAnOutOfRangeBehavior)
|
||||
EXPECT_NE(error.find("loaded behavior"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(StateMachineConfig, RejectsNegativeCancelSettleTimeout)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = -1.0;
|
||||
std::string error;
|
||||
EXPECT_FALSE(config.validate(error));
|
||||
EXPECT_NE(error.find("settle_timeout"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(StateMachineConfig, RejectsNegativeStoppedMeasuredEps)
|
||||
{
|
||||
StateMachineConfig linear = baseConfig();
|
||||
linear.stopped_measured_linear_eps = -0.01;
|
||||
std::string error;
|
||||
EXPECT_FALSE(linear.validate(error));
|
||||
EXPECT_NE(error.find("stopped_measured_linear_eps"), std::string::npos);
|
||||
|
||||
StateMachineConfig angular = baseConfig();
|
||||
angular.stopped_measured_angular_eps = -0.01;
|
||||
EXPECT_FALSE(angular.validate(error));
|
||||
EXPECT_NE(error.find("stopped_measured_angular_eps"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(StateMachineConfig, ZeroCancelSettleTimeoutAndZeroEpsAreValidOffSwitches)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.0;
|
||||
config.stopped_measured_linear_eps = 0.0;
|
||||
config.stopped_measured_angular_eps = 0.0;
|
||||
std::string error;
|
||||
EXPECT_TRUE(config.validate(error)) << error;
|
||||
}
|
||||
|
||||
TEST(StateMachineConfig, DescribeMentionsEveryParameter)
|
||||
{
|
||||
const std::string text = baseConfig().describe();
|
||||
@@ -249,6 +282,8 @@ TEST(StateMachineConfig, DescribeMentionsEveryParameter)
|
||||
EXPECT_NE(text.find("action_patience"), std::string::npos);
|
||||
EXPECT_NE(text.find("max_planning_retries"), std::string::npos);
|
||||
EXPECT_NE(text.find("recovery_reset_min_travel"), std::string::npos);
|
||||
EXPECT_NE(text.find("settle_timeout"), std::string::npos);
|
||||
EXPECT_NE(text.find("stopped_measured_eps"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(StateMachine, RefusesToRunBeforeConfigure)
|
||||
@@ -444,7 +479,7 @@ TEST(StateMachinePlanning, PauseMovesToPausedAndResumeComesBack)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
@@ -903,7 +938,7 @@ TEST(StateMachineControlling, PauseThenResumeReturnsToControlling)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
EXPECT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
@@ -921,7 +956,7 @@ TEST(StateMachineControlling, LongPauseDoesNotBlowControllerPatience)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
driver.advance(60.0);
|
||||
|
||||
@@ -1108,7 +1143,7 @@ TEST(StateMachineRecovering, PauseMidRecoveryCancelsBehaviorAndResumesToPlanning
|
||||
pause.pause_requested = true;
|
||||
const StateMachineOutput paused = driver.tick(pause);
|
||||
|
||||
EXPECT_EQ(paused.state, NavigationState::kPaused);
|
||||
EXPECT_EQ(paused.state, NavigationState::kPausing);
|
||||
EXPECT_TRUE(paused.cancel_recovery)
|
||||
<< "keeping a behavior half-finished across a long pause is unsafe";
|
||||
|
||||
@@ -1147,7 +1182,7 @@ TEST(StateMachinePaused, CancelFromPausedGoesToCancelling)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
@@ -1161,7 +1196,9 @@ TEST(StateMachinePaused, StaysPausedIndefinitelyWithoutResume)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
// Cycle kế: mọi thành phần im (input mặc định) → PAUSED thật.
|
||||
ASSERT_EQ(driver.idleTick().state, NavigationState::kPaused);
|
||||
|
||||
for (int i = 0; i < 50; ++i)
|
||||
{
|
||||
@@ -1194,6 +1231,430 @@ TEST(StateMachineCancelling, WaitsForRobotToStopBeforeCancelled)
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// kCancelling chờ QUIESCENT (2026-09-11): lệnh về 0 là điều kiện cần, chưa đủ. Host đọc
|
||||
// CANCELLED/PREEMPTED là "xong rồi, gửi goal kế được" — báo trong lúc thread planner còn chạy lượt
|
||||
// cũ thì goal kế bị startPlan() từ chối và bị coi là hỏng (log 2026-09-11: ABORTED sau 3 s).
|
||||
// ================================================================================================
|
||||
|
||||
TEST(StateMachineCancelling, HoldsWhilePlannerThreadIsStillBusy)
|
||||
{
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
cancel.planner_busy = true; // SBPL đang chạy, cancelPlan() không cắt được
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput still_busy;
|
||||
still_busy.robot_stopped = true;
|
||||
still_busy.planner_busy = true;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
{
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(still_busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelling) << "left CANCELLING at cycle " << i;
|
||||
EXPECT_FALSE(out.report_outcome);
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||
EXPECT_FALSE(out.start_planner);
|
||||
}
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
idle.planner_busy = false;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(idle);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||
EXPECT_FALSE(out.settle_timed_out);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, GivesUpAfterSettleTimeoutAndFlagsIt)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.5; // [s]
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
|
||||
// 0.45 s: chưa quá trần.
|
||||
driver.advance(0.45);
|
||||
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||
EXPECT_FALSE(driver.last().settle_timed_out);
|
||||
|
||||
// 0.55 s: quá trần → CANCELLED nhưng cờ lỗi bật đúng cycle báo kết quả.
|
||||
driver.advance(0.10);
|
||||
const StateMachineOutput out = driver.tick(busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
|
||||
EXPECT_TRUE(out.settle_timed_out);
|
||||
|
||||
// Cờ chỉ sống một cycle: cycle kế về kIdle không mang nó theo.
|
||||
EXPECT_FALSE(driver.idleTick().settle_timed_out);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, HoldsWhileOdometrySaysTheRobotIsStillMoving)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
// Lệnh đã về 0 (bên gọi tính vào robot_stopped) nhưng odom vẫn đọc 0.3 m/s → chưa xong.
|
||||
StateMachineInput rolling;
|
||||
rolling.robot_stopped = false;
|
||||
rolling.planner_busy = false;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(rolling).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput stopped;
|
||||
stopped.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(stopped).state, NavigationState::kCancelled);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, KeepsTickingTheActionUntilItReportsTerminal)
|
||||
{
|
||||
// Handler thiết bị cần vài tick sau cancel() để đưa thiết bị về vị trí an toàn. Trong lúc đó
|
||||
// state machine tick tiếp nhưng KHÔNG cấp vận tốc — bất biến 3 giữ nguyên.
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
request.pending_request_has_goal = false;
|
||||
request.pending_request_action_count = 1;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kExecutingActions);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
cancel.action_terminal = false;
|
||||
const StateMachineOutput entering = driver.tick(cancel);
|
||||
ASSERT_EQ(entering.state, NavigationState::kCancelling);
|
||||
EXPECT_TRUE(entering.cancel_action);
|
||||
|
||||
StateMachineInput settling;
|
||||
settling.robot_stopped = true;
|
||||
settling.planner_busy = false;
|
||||
settling.action_terminal = false;
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(settling);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelling);
|
||||
EXPECT_TRUE(out.tick_action) << "cycle " << i;
|
||||
EXPECT_FALSE(out.run_controller);
|
||||
EXPECT_FALSE(out.tick_recovery);
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||
}
|
||||
|
||||
StateMachineInput terminal = settling;
|
||||
terminal.action_terminal = true;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(terminal);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||
EXPECT_FALSE(out.tick_action);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, ZeroSettleTimeoutKeepsTheLegacyBehaviour)
|
||||
{
|
||||
// Tắt = hành vi trước 2026-09-11: chỉ chờ lệnh về 0, mặc kệ planner còn bận.
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.0;
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput stopped_but_busy;
|
||||
stopped_but_busy.robot_stopped = true;
|
||||
stopped_but_busy.planner_busy = true;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(stopped_but_busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kCancelled);
|
||||
EXPECT_FALSE(out.settle_timed_out);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, CancelFromPausedAlsoWaitsForThePlannerThread)
|
||||
{
|
||||
// Pause lúc PLANNING đã cancelPlan() nhưng thread có thể còn bận; cancel từ PAUSED phải chờ nốt.
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
cancel.planner_busy = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput idle = busy;
|
||||
idle.planner_busy = false;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||
}
|
||||
|
||||
TEST(StateMachinePaused, ResumeFromControllingReappliesThePlanToTheController)
|
||||
{
|
||||
// Local planner giữ warm-start/slew theo thời gian; sau một quãng đứng yên phải nạp lại plan để
|
||||
// plugin reset theo pose hiện tại. Resume từ CONTROLLING vì vậy mang apply_plan (2026-09-11).
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
driver.advance(30.0);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
const StateMachineOutput out = driver.tick(resume);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.apply_plan);
|
||||
EXPECT_TRUE(out.run_controller);
|
||||
}
|
||||
|
||||
TEST(StateMachinePaused, ResumeFromPlanningDoesNotReapplyAnyPlan)
|
||||
{
|
||||
// Chưa từng có plan nào → không có gì để nạp lại; resume chỉ khởi động lại planner.
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
const StateMachineOutput out = driver.tick(resume);
|
||||
EXPECT_EQ(out.state, NavigationState::kPlanning);
|
||||
EXPECT_FALSE(out.apply_plan);
|
||||
EXPECT_TRUE(out.start_planner);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// kPausing (2026-09-11): pause nhận xong là lệnh 0 ngay, nhưng PAUSED chỉ khi mọi thành phần im —
|
||||
// cùng ba điều kiện quiescent với kCancelling. Host đọc PAUSED là "dừng rồi, làm gì cũng được".
|
||||
// ================================================================================================
|
||||
|
||||
TEST(StateMachinePausing, HoldsWhilePlannerThreadIsStillBusyThenSettles)
|
||||
{
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
pause.planner_busy = true;
|
||||
const StateMachineOutput entering = driver.tick(pause);
|
||||
ASSERT_EQ(entering.state, NavigationState::kPausing);
|
||||
EXPECT_TRUE(entering.stop_planner);
|
||||
EXPECT_EQ(entering.velocity_source, VelocitySource::kNone);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
{
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kPausing) << "cycle " << i;
|
||||
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
|
||||
EXPECT_FALSE(out.start_planner);
|
||||
EXPECT_FALSE(out.settle_timed_out);
|
||||
}
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput out = driver.tick(idle);
|
||||
EXPECT_EQ(out.state, NavigationState::kPaused);
|
||||
EXPECT_FALSE(out.settle_timed_out);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, HoldsWhileRecoveryIsStillStopping)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput recovering;
|
||||
recovering.robot_stopped = true;
|
||||
recovering.recovery_busy = true; // detour worker chưa thoát
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(recovering).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(idle).state, NavigationState::kPaused);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, GivesUpAfterSettleTimeoutAndFlagsIt)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.5; // [s]
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
driver.advance(0.45);
|
||||
EXPECT_EQ(driver.tick(busy).state, NavigationState::kPausing);
|
||||
driver.advance(0.10);
|
||||
const StateMachineOutput out = driver.tick(busy);
|
||||
EXPECT_EQ(out.state, NavigationState::kPaused);
|
||||
EXPECT_TRUE(out.settle_timed_out);
|
||||
EXPECT_FALSE(driver.idleTick().settle_timed_out) << "one-cycle flag";
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, ResumeBeforeSettledReturnsToThePreviousState)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
resume.planner_busy = true; // chưa im mà đã được bảo chạy tiếp — không phải chờ
|
||||
const StateMachineOutput out = driver.tick(resume);
|
||||
EXPECT_EQ(out.state, NavigationState::kControlling);
|
||||
EXPECT_TRUE(out.apply_plan);
|
||||
EXPECT_TRUE(out.run_controller);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, CancelBeforeSettledGoesToCancellingAndKeepsWaiting)
|
||||
{
|
||||
Driver driver;
|
||||
|
||||
StateMachineInput request;
|
||||
request.has_pending_request = true;
|
||||
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
pause.planner_busy = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
cancel.planner_busy = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput busy;
|
||||
busy.robot_stopped = true;
|
||||
busy.planner_busy = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(busy).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, NewGoalWhilePausingPreemptsLikePaused)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput new_goal;
|
||||
new_goal.has_pending_request = true;
|
||||
const StateMachineOutput out = driver.tick(new_goal);
|
||||
EXPECT_EQ(out.state, NavigationState::kPlanning);
|
||||
EXPECT_TRUE(out.report_outcome);
|
||||
EXPECT_EQ(out.outcome, NavigationOutcome::kPreempted);
|
||||
EXPECT_TRUE(out.accept_request);
|
||||
}
|
||||
|
||||
TEST(StateMachinePausing, ZeroSettleTimeoutSettlesOnRobotStoppedOnly)
|
||||
{
|
||||
StateMachineConfig config = baseConfig();
|
||||
config.settle_timeout = 0.0;
|
||||
Driver driver(config);
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput stopped_but_busy;
|
||||
stopped_but_busy.robot_stopped = true;
|
||||
stopped_but_busy.planner_busy = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(stopped_but_busy).state, NavigationState::kPaused);
|
||||
}
|
||||
|
||||
TEST(StateMachineCancelling, HoldsWhileRecoveryIsStillStopping)
|
||||
{
|
||||
Driver driver;
|
||||
driver.driveToControlling();
|
||||
|
||||
StateMachineInput cancel;
|
||||
cancel.cancel_requested = true;
|
||||
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput recovering;
|
||||
recovering.robot_stopped = true;
|
||||
recovering.recovery_busy = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(recovering).state, NavigationState::kCancelling);
|
||||
|
||||
StateMachineInput idle;
|
||||
idle.robot_stopped = true;
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(idle).state, NavigationState::kCancelled);
|
||||
}
|
||||
|
||||
TEST(StateMachineTerminal, OutcomeIsReportedExactlyOnce)
|
||||
{
|
||||
Driver driver;
|
||||
@@ -1393,18 +1854,57 @@ TEST(StateMachineActions, PauseDuringActionFreezesWithoutCancelling)
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
const StateMachineOutput paused = driver.tick(pause);
|
||||
EXPECT_EQ(paused.state, NavigationState::kPaused);
|
||||
EXPECT_EQ(paused.state, NavigationState::kPausing);
|
||||
EXPECT_FALSE(paused.cancel_action) << "the action is not idempotent — pausing must not cancel it";
|
||||
EXPECT_FALSE(paused.tick_action);
|
||||
EXPECT_TRUE(paused.pause_action) << "the handler must be told, so its own timeout clock stops";
|
||||
|
||||
StateMachineInput resume;
|
||||
resume.resume_requested = true;
|
||||
const StateMachineOutput resumed = driver.tick(resume);
|
||||
EXPECT_EQ(resumed.state, NavigationState::kExecutingActions);
|
||||
EXPECT_TRUE(resumed.tick_action) << "resume keeps ticking the unfinished action";
|
||||
EXPECT_TRUE(resumed.resume_action) << "the handler must be told the pause is over";
|
||||
EXPECT_FALSE(resumed.start_action) << "an action already in progress must not be started again";
|
||||
}
|
||||
|
||||
TEST(StateMachineActions, PausingWithAnActionWaitsForTheHandlerToAcknowledge)
|
||||
{
|
||||
// Handler chưa xác nhận pause (action_terminal=false) → PAUSING tick tiếp; xác nhận → PAUSED.
|
||||
Driver driver;
|
||||
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||
NavigationState::kExecutingActions);
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
pause.action_terminal = false;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
StateMachineInput not_yet;
|
||||
not_yet.robot_stopped = true;
|
||||
not_yet.action_terminal = false;
|
||||
driver.advance(0.05);
|
||||
const StateMachineOutput held = driver.tick(not_yet);
|
||||
EXPECT_EQ(held.state, NavigationState::kPausing);
|
||||
EXPECT_TRUE(held.tick_action);
|
||||
EXPECT_EQ(held.velocity_source, VelocitySource::kNone);
|
||||
|
||||
StateMachineInput acked = not_yet;
|
||||
acked.action_terminal = true; // hàng kAction = paused
|
||||
driver.advance(0.05);
|
||||
EXPECT_EQ(driver.tick(acked).state, NavigationState::kPaused);
|
||||
}
|
||||
|
||||
TEST(StateMachineActions, CancelledFeedbackInsideExecutingActionsIsTreatedAsFailure)
|
||||
{
|
||||
// Lỗi thứ tự gọi (không ai cancel trong EXECUTING_ACTIONS) — không được im lặng chạy tiếp.
|
||||
Driver driver;
|
||||
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
|
||||
NavigationState::kExecutingActions);
|
||||
const StateMachineOutput out = driver.tick(actionFb(ActionFeedback::kCancelled));
|
||||
EXPECT_EQ(out.state, NavigationState::kAborted);
|
||||
}
|
||||
|
||||
TEST(StateMachineActions, ActionPatienceIsDisabledByDefault)
|
||||
{
|
||||
Driver driver;
|
||||
@@ -1451,7 +1951,7 @@ TEST(StateMachineActions, PauseRearmsActionPatienceClock)
|
||||
|
||||
StateMachineInput pause;
|
||||
pause.pause_requested = true;
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPaused);
|
||||
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
|
||||
|
||||
// Dừng lâu hơn hẳn action_patience rồi mới resume — quãng dừng không được tính vào trần.
|
||||
driver.advance(30.0);
|
||||
@@ -1556,8 +2056,8 @@ TEST(StateMachineInvariants, EveryStateHasANonEmptyName)
|
||||
{
|
||||
const NavigationState states[] = {
|
||||
NavigationState::kIdle, NavigationState::kPlanning, NavigationState::kControlling,
|
||||
NavigationState::kRecovering, NavigationState::kExecutingActions, NavigationState::kPaused,
|
||||
NavigationState::kCancelling, NavigationState::kSucceeded, NavigationState::kAborted,
|
||||
NavigationState::kRecovering, NavigationState::kExecutingActions, NavigationState::kPausing,
|
||||
NavigationState::kPaused, NavigationState::kCancelling, NavigationState::kSucceeded, NavigationState::kAborted,
|
||||
NavigationState::kCancelled,
|
||||
};
|
||||
|
||||
|
||||
@@ -130,6 +130,10 @@ public:
|
||||
deps_.action = &action_;
|
||||
deps_.costmap_status = &costmap_status_;
|
||||
deps_.environment = &environment_;
|
||||
deps_.components = &components_;
|
||||
planner_.attachStatusBoard(&components_);
|
||||
recovery_.attachStatusBoard(&components_);
|
||||
action_.attachStatusBoard(&components_);
|
||||
|
||||
std::string error;
|
||||
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
|
||||
@@ -179,6 +183,7 @@ public:
|
||||
FakeActionPort action_;
|
||||
FakeCostmapStatusPort costmap_status_;
|
||||
FakeEnvironmentPort environment_;
|
||||
move_base2::ComponentStatusBoard components_;
|
||||
ControlLoopDeps deps_;
|
||||
|
||||
private:
|
||||
@@ -814,8 +819,11 @@ TEST(ControlLoop, PauseAndResumeMidControlling)
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPausing);
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
|
||||
// Dừng lâu rồi tiếp tục: không được vì thế mà rơi vào recovery.
|
||||
fixture.clock_.advance(30.0);
|
||||
@@ -826,6 +834,433 @@ TEST(ControlLoop, PauseAndResumeMidControlling)
|
||||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, ResumeMidControllingReappliesThePlanToTheController)
|
||||
{
|
||||
// Local planner giữ warm-start/slew theo thời gian; sau 30 s đứng yên phải nạp lại plan để
|
||||
// plugin reset theo pose hiện tại (2026-09-11).
|
||||
Fixture fixture;
|
||||
fixture.controller_.setScript({ControllerScript::kOk});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||||
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
const std::size_t set_plan_before = fixture.controller_.setPlanCount();
|
||||
ASSERT_EQ(set_plan_before, 1u);
|
||||
|
||||
fixture.loop_.requestPause();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.controller_.setPlanCount(), set_plan_before) << "pause must not touch the plan";
|
||||
|
||||
fixture.clock_.advance(30.0);
|
||||
fixture.loop_.requestResume();
|
||||
fixture.loop_.step();
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
EXPECT_EQ(fixture.controller_.setPlanCount(), set_plan_before + 1)
|
||||
<< "resume from CONTROLLING must call setPlan() again so the plugin resets its warm start";
|
||||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// Cancel phải dừng THẬT (2026-09-11): CANCELLED chỉ khi thread planner rảnh và odom về 0.
|
||||
// Tái hiện log: cancel lúc SBPL đang chạy → host thấy CANCELLED sau 33 ms → gửi goal kế →
|
||||
// startPlan() bị từ chối vì thread còn bận → bị coi là hỏng → recovery → ABORTED.
|
||||
// ================================================================================================
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
/// Fixture với planner "chậm" (10 cycle) và KHÔNG preempt được — đúng SBPL trước pha 2.
|
||||
ControlLoopConfig busyPlannerConfig()
|
||||
{
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.planner_patience = 5.0; // [s] đủ dài để kBusy không bị patience cắt
|
||||
config.state_machine.max_planning_retries = 0; // như config trên máy chạy log
|
||||
config.state_machine.settle_timeout = 2.0; // [s]
|
||||
return config;
|
||||
}
|
||||
|
||||
constexpr std::size_t kSlowPlannerCycles = 10;
|
||||
|
||||
/// Đưa fixture tới PLANNING với một lượt lập plan đang bay, chưa có kết quả.
|
||||
void driveToPlanningInFlight(Fixture& fixture, std::uint64_t mission_id)
|
||||
{
|
||||
fixture.planner_.setLatencyCycles(kSlowPlannerCycles);
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, mission_id), reason)) << reason;
|
||||
|
||||
fixture.loop_.step(); // accept → PLANNING, startPlan()
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step(); // pollPlan: chưa có
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||||
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(ControlLoop, CancelWhilePlannerStaysBusyHoldsCancellingUntilTheThreadIsIdle)
|
||||
{
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 7);
|
||||
// reset() lúc configure và accept_request đều gọi cancelPlan() (dọn lượt cũ) — đếm tương đối.
|
||||
const std::size_t cancels_before = fixture.planner_.cancelCount();
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
EXPECT_EQ(fixture.planner_.cancelCount(), cancels_before + 1);
|
||||
EXPECT_TRUE(fixture.planner_.isPlanning()) << "the fake models a planner that cannot be preempted";
|
||||
|
||||
// Chừng nào thread còn bận: giữ CANCELLING, lệnh = 0, KHÔNG báo kết quả. Cycle mà thread rảnh
|
||||
// (pollPlan thấy lượt cũ xong) cũng chính là cycle CANCELLED — không chậm thêm vòng nào.
|
||||
std::size_t cycles_held = 0;
|
||||
for (; cycles_held < 50; ++cycles_held)
|
||||
{
|
||||
const bool busy_before = fixture.planner_.isPlanning();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
if (fixture.loop_.state() == NavigationState::kCancelled)
|
||||
{
|
||||
EXPECT_TRUE(busy_before) << "must not finish before the very cycle the thread frees";
|
||||
EXPECT_FALSE(fixture.planner_.isPlanning());
|
||||
break;
|
||||
}
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << cycles_held;
|
||||
EXPECT_TRUE(fixture.planner_.isPlanning()) << "held CANCELLING although the thread is idle";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(7), 0u) << "CANCELLED reported while planner busy";
|
||||
}
|
||||
EXPECT_GE(cycles_held, 3u) << "the fake planner should have stayed busy for several cycles";
|
||||
EXPECT_LT(cycles_held, 50u) << "never reached CANCELLED";
|
||||
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_STREQ(fixture.loop_.lastOutcome(), "CANCELLED");
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, GoalSentRightAfterCancelWaitsForTheBusyPlannerInsteadOfFailing)
|
||||
{
|
||||
// Đúng chuỗi sự kiện trong log: cancel mission 3, mission 4 tới 0.2 s sau. Không được có
|
||||
// RECOVERING/ABORTED; mission 4 phải tới CONTROLLING sau khi thread rảnh.
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 3);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
|
||||
// Host không đợi PREEMPTED (hành vi cũ của khung chương trình): gửi goal kế ngay.
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 4), reason)) << reason;
|
||||
|
||||
const std::size_t make_plan_before = fixture.planner_.makePlanCount();
|
||||
bool saw_recovering = false;
|
||||
bool saw_aborted = false;
|
||||
bool reached_controlling = false;
|
||||
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
const NavigationState s = fixture.loop_.state();
|
||||
saw_recovering = saw_recovering || s == NavigationState::kRecovering;
|
||||
saw_aborted = saw_aborted || s == NavigationState::kAborted;
|
||||
reached_controlling = s == NavigationState::kControlling;
|
||||
}
|
||||
|
||||
EXPECT_FALSE(saw_recovering) << "a busy planner thread was treated as a failed planning attempt";
|
||||
EXPECT_FALSE(saw_aborted);
|
||||
EXPECT_TRUE(reached_controlling);
|
||||
EXPECT_EQ(fixture.planner_.makePlanCount(), make_plan_before + 1)
|
||||
<< "exactly one new planning attempt once the thread was free";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(3), 1u) << "mission 3 reported once (CANCELLED)";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(4), 0u) << "mission 4 is still running";
|
||||
}
|
||||
|
||||
TEST(ControlLoop, PauseWhilePlanningThenResumeWaitsForTheBusyPlanner)
|
||||
{
|
||||
// pause lúc PLANNING đi cùng đường cancelPlan(); resume → PLANNING → startPlan() bị từ chối →
|
||||
// phải là kBusy, không phải kFailed.
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 8);
|
||||
|
||||
fixture.loop_.requestPause();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPausing)
|
||||
<< "planner thread still busy: PAUSED must not be reported yet";
|
||||
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||||
|
||||
fixture.loop_.requestResume();
|
||||
bool saw_recovering = false;
|
||||
bool reached_controlling = false;
|
||||
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
saw_recovering = saw_recovering || fixture.loop_.state() == NavigationState::kRecovering;
|
||||
reached_controlling = fixture.loop_.state() == NavigationState::kControlling;
|
||||
}
|
||||
EXPECT_FALSE(saw_recovering);
|
||||
EXPECT_TRUE(reached_controlling);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(8), 0u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, NewGoalPreemptingABusyPlannerWaitsInsteadOfFailing)
|
||||
{
|
||||
// MissionManager::submit() tự huỷ mission đang chạy — không cần cancel vẫn dính cùng đường.
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 11);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(6.0, 12), reason)) << reason;
|
||||
|
||||
bool saw_recovering = false;
|
||||
bool reached_controlling = false;
|
||||
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
saw_recovering = saw_recovering || fixture.loop_.state() == NavigationState::kRecovering;
|
||||
reached_controlling = fixture.loop_.state() == NavigationState::kControlling;
|
||||
}
|
||||
EXPECT_FALSE(saw_recovering);
|
||||
EXPECT_TRUE(reached_controlling);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(11), 1u) << "mission 11 reported once (PREEMPTED)";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(12), 0u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, BusyPlannerStillCountsAgainstPlannerPatience)
|
||||
{
|
||||
// kBusy không phải vé miễn phí: plugin treo thật thì planner_patience vẫn phải leo thang.
|
||||
ControlLoopConfig config = busyPlannerConfig();
|
||||
config.state_machine.planner_patience = 0.2; // [s] = 4 cycle
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setLatencyCycles(100); // treo "vĩnh viễn" so với patience
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 20), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
|
||||
// Goal kế chen ngang (preempt) trong lúc thread treo: chờ bằng kBusy tối đa planner_patience rồi
|
||||
// mới recovery. Dùng preempt thay vì cancel để không phải đợi settle_timeout ở đây.
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 21), reason)) << reason;
|
||||
bool saw_recovering = false;
|
||||
for (int i = 0; i < 30 && !saw_recovering; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
saw_recovering = fixture.loop_.state() == NavigationState::kRecovering;
|
||||
}
|
||||
EXPECT_TRUE(saw_recovering) << "a planner that never returns must still hit planner_patience";
|
||||
}
|
||||
|
||||
TEST(ControlLoop, CancelSettleTimeoutFinishesCancelledEvenIfThePlannerNeverFrees)
|
||||
{
|
||||
ControlLoopConfig config = busyPlannerConfig();
|
||||
config.state_machine.settle_timeout = 0.2; // [s] = 4 cycle
|
||||
Fixture fixture(config);
|
||||
fixture.planner_.setLatencyCycles(1000);
|
||||
fixture.planner_.setCancelKeepsBusy(true);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 30), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
std::size_t cycles = 0;
|
||||
bool running = true;
|
||||
while (running && cycles < 20)
|
||||
{
|
||||
running = fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
++cycles;
|
||||
}
|
||||
|
||||
EXPECT_FALSE(running);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_TRUE(fixture.planner_.isPlanning()) << "the thread is still busy — settle timeout fired";
|
||||
EXPECT_GE(cycles, 4u);
|
||||
EXPECT_LE(cycles, 7u) << "CANCELLED must arrive right after settle_timeout";
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(30), 1u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, CancellingWaitsForMeasuredVelocityToReadZero)
|
||||
{
|
||||
// Lệnh về 0 ngay cycle đầu, nhưng odom còn 0.3 m/s (driver đang giảm tốc) → chưa CANCELLED.
|
||||
Fixture fixture;
|
||||
fixture.controller_.setScript({ControllerScript::kOk});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 40), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
fixture.controller_.setOdometry(0.3);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << i;
|
||||
}
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(40), 0u);
|
||||
|
||||
fixture.controller_.setOdometry(0.0);
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(40), 1u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, PauseWhilePlannerBusyHoldsPausingUntilTheThreadIsIdle)
|
||||
{
|
||||
// PAUSED nói thật (2026-09-11): pause nhận trong 1 cycle (lệnh 0), nhưng PAUSED chỉ khi thread
|
||||
// planner đã nhả — cùng cơ chế với CANCELLING.
|
||||
Fixture fixture(busyPlannerConfig());
|
||||
driveToPlanningInFlight(fixture, 50);
|
||||
|
||||
fixture.loop_.requestPause();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPausing);
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kGlobalPlanner),
|
||||
move_base2::ComponentPhase::kStopping)
|
||||
<< "the fake planner reports 'stopping' after a cancel it cannot honour";
|
||||
|
||||
std::size_t held = 0;
|
||||
for (; held < 50; ++held)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
if (fixture.loop_.state() == NavigationState::kPaused)
|
||||
{
|
||||
break;
|
||||
}
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPausing) << "cycle " << held;
|
||||
EXPECT_TRUE(fixture.planner_.isPlanning());
|
||||
}
|
||||
EXPECT_GE(held, 3u);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
EXPECT_FALSE(fixture.planner_.isPlanning());
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kGlobalPlanner),
|
||||
move_base2::ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, CancellingWaitsForARecoveryWorkerReportedThroughTheStatusBoard)
|
||||
{
|
||||
// Recovery có worker thread (detour, pha 2): cancel() không kết thúc được ngay → hàng kRecovery
|
||||
// giữ 'stopping' → CANCELLING phải chờ, dù cổng planner đã rảnh và lệnh đã 0.
|
||||
Fixture fixture;
|
||||
fixture.planner_.setScript({PlannerScript::kFail});
|
||||
fixture.recovery_.setScript({RecoveryScript::kRunning});
|
||||
fixture.recovery_.setCancelKeepsBusy(true);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 60), reason)) << reason;
|
||||
for (int i = 0; i < 40 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
}
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
ASSERT_TRUE(fixture.recovery_.stopping());
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << i;
|
||||
}
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(60), 0u);
|
||||
|
||||
fixture.recovery_.settleCancel(); // worker giả đã thoát
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(60), 1u);
|
||||
}
|
||||
|
||||
TEST(ControlLoop, StatusBoardTracksLocalPlannerAndControlLoopHeartbeat)
|
||||
{
|
||||
Fixture fixture;
|
||||
fixture.controller_.setScript({ControllerScript::kOk});
|
||||
|
||||
const std::uint64_t before =
|
||||
fixture.components_.at(move_base2::Component::kControlLoop).progress_ticks.load();
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
|
||||
// Heartbeat nhích mỗi step(); local planner về idle sau mỗi lượt gọi (không để "bận" treo).
|
||||
EXPECT_GE(fixture.components_.at(move_base2::Component::kControlLoop).progress_ticks.load(),
|
||||
before + 2);
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kLocalPlanner),
|
||||
move_base2::ComponentPhase::kIdle);
|
||||
EXPECT_GT(fixture.components_.at(move_base2::Component::kLocalPlanner).progress_ticks.load(), 0u)
|
||||
<< "computeVelocityCommands must have been bracketed busy/idle at least once";
|
||||
}
|
||||
|
||||
TEST(ControlLoop, MeasuredVelocityIsIgnoredWhenTheEpsSwitchesAreZero)
|
||||
{
|
||||
ControlLoopConfig config = baseConfig();
|
||||
config.state_machine.stopped_measured_linear_eps = 0.0;
|
||||
config.state_machine.stopped_measured_angular_eps = 0.0;
|
||||
Fixture fixture(config);
|
||||
fixture.controller_.setScript({ControllerScript::kOk});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 41), reason)) << reason;
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||||
fixture.controller_.setOdometry(0.3); // odom nói còn chạy — nhưng công tắc tắt
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
fixture.clock_.advance(kControlPeriod);
|
||||
fixture.loop_.step();
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled)
|
||||
<< "with eps = 0 'stopped' is judged from the issued command, as before 2026-09-11";
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// Nhiều chặng liên tiếp
|
||||
// ================================================================================================
|
||||
@@ -926,6 +1361,77 @@ TEST(ControlLoopActions, ActionFailureAbortsAndReportsOnce)
|
||||
EXPECT_EQ(fixture.recovery_.startCount(), 0u) << "a failed action must not drag recovery in";
|
||||
}
|
||||
|
||||
TEST(ControlLoopActions, PauseAndResumeAreForwardedToTheActionPort)
|
||||
{
|
||||
// Pha 3 (2026-09-11): handler có timeout riêng phải biết pause để dịch mốc; không báo thì 20 s
|
||||
// đứng chờ bị tính vào timeout dò 15 s → kFailed → ABORTED oan ngay sau resume.
|
||||
Fixture fixture;
|
||||
fixture.action_.setScript({ActionScript::kRunning});
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 14), reason)) << reason;
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||
const std::size_t updates_before_pause = fixture.action_.updateCount();
|
||||
|
||||
fixture.loop_.requestPause();
|
||||
fixture.stepOnce();
|
||||
EXPECT_EQ(fixture.action_.pauseCount(), 1u);
|
||||
EXPECT_EQ(fixture.action_.cancelCount(), 0u) << "pause must not cancel the action";
|
||||
fixture.stepOnce(); // hàng kAction = paused → quiescent
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||||
EXPECT_EQ(fixture.action_.updateCount(), updates_before_pause) << "no ticks while paused";
|
||||
|
||||
fixture.clock_.advance(30.0);
|
||||
fixture.loop_.requestResume();
|
||||
fixture.stepOnce();
|
||||
EXPECT_EQ(fixture.action_.resumeCount(), 1u);
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||
EXPECT_GT(fixture.action_.updateCount(), updates_before_pause) << "ticking resumed";
|
||||
EXPECT_EQ(fixture.action_.startCount(), 1u) << "the action must not be restarted";
|
||||
}
|
||||
|
||||
TEST(ControlLoopActions, CancelWaitsForADeviceHandlerToReportCancelled)
|
||||
{
|
||||
// Handler thiết bị cần 3 tick sau cancel() để về vị trí an toàn: CANCELLING tick tiếp, không
|
||||
// cấp vận tốc, và CANCELLED chỉ được báo sau tick kCancelled.
|
||||
Fixture fixture;
|
||||
fixture.action_.setScript({ActionScript::kRunning});
|
||||
fixture.action_.setCancelNeedsTicks(3);
|
||||
|
||||
std::string reason;
|
||||
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 15), reason)) << reason;
|
||||
fixture.stepOnce();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
|
||||
|
||||
fixture.loop_.requestCancel();
|
||||
fixture.stepOnce();
|
||||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
|
||||
EXPECT_EQ(fixture.action_.cancelCount(), 1u);
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kAction),
|
||||
move_base2::ComponentPhase::kStopping);
|
||||
|
||||
std::size_t held = 0;
|
||||
for (; held < 10; ++held)
|
||||
{
|
||||
if (fixture.loop_.state() == NavigationState::kCancelled)
|
||||
{
|
||||
break;
|
||||
}
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << held;
|
||||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(15), 0u) << "CANCELLED reported before the device was safe";
|
||||
fixture.stepOnce();
|
||||
}
|
||||
EXPECT_GE(held, 3u) << "the handler asked for 3 ticks after cancel";
|
||||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||||
EXPECT_EQ(fixture.mission_.reportCountFor(15), 1u);
|
||||
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kAction),
|
||||
move_base2::ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
TEST(ControlLoopActions, SubmitRejectsActionRequestWhenActionPortMissing)
|
||||
{
|
||||
Fixture fixture;
|
||||
|
||||
195
test/watchdog_test.cpp
Normal file
195
test/watchdog_test.cpp
Normal file
@@ -0,0 +1,195 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — test watchdog: kết luận treo từ bảng trạng thái, trên thread riêng.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include <move_base2/core/component_status.h>
|
||||
#include <move_base2/io/watchdog.h>
|
||||
|
||||
using move_base2::Component;
|
||||
using move_base2::ComponentPhase;
|
||||
using move_base2::ComponentStatusBoard;
|
||||
using move_base2::Watchdog;
|
||||
using move_base2::WatchdogConfig;
|
||||
|
||||
namespace
|
||||
{
|
||||
WatchdogConfig fastConfig()
|
||||
{
|
||||
WatchdogConfig c;
|
||||
c.period = 0.01; // [s]
|
||||
c.planner_timeout = 0.05; // [s]
|
||||
c.local_planner_call_budget = 0.05;
|
||||
c.recovery_stall_budget = 0.05;
|
||||
c.action_stall_budget = 0.05;
|
||||
c.control_loop_stall_budget = 0.05;
|
||||
return c;
|
||||
}
|
||||
|
||||
void sleepMs(int ms)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(WatchdogConfig, RejectsNegativePeriodAndNonFiniteBudgets)
|
||||
{
|
||||
WatchdogConfig c;
|
||||
std::string error;
|
||||
c.period = -0.1;
|
||||
EXPECT_FALSE(c.validate(error));
|
||||
c = WatchdogConfig();
|
||||
c.planner_timeout = std::numeric_limits<double>::infinity();
|
||||
EXPECT_FALSE(c.validate(error));
|
||||
c = WatchdogConfig();
|
||||
c.period = 0.0; // tắt = hợp lệ
|
||||
EXPECT_TRUE(c.validate(error)) << error;
|
||||
EXPECT_NE(c.describe().find("planner_timeout"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(Watchdog, IdleRowsAreNeverHung)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0; // không thread — checkOnce() tay
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||
sleepMs(80);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.anyHung()) << "idle for a long time is not 'hung'";
|
||||
}
|
||||
|
||||
TEST(Watchdog, BusyWithoutProgressBecomesHungAndRecoversOnProgress)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0;
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
|
||||
board.enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "just started";
|
||||
|
||||
sleepMs(30);
|
||||
board.progress(Component::kGlobalPlanner); // vẫn nhích → không treo dù bận lâu
|
||||
sleepMs(30);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "busy but progressing";
|
||||
|
||||
sleepMs(80); // > 0.05 s không nhích
|
||||
dog.checkOnce();
|
||||
EXPECT_TRUE(dog.hung(Component::kGlobalPlanner));
|
||||
EXPECT_TRUE(dog.anyHung());
|
||||
EXPECT_NE(dog.report().find("global_planner"), std::string::npos);
|
||||
|
||||
board.progress(Component::kGlobalPlanner);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner)) << "recovered";
|
||||
}
|
||||
|
||||
TEST(Watchdog, StoppingCountsAsWatchedButPausedDoesNot)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0;
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
|
||||
board.enter(Component::kRecovery, ComponentPhase::kStopping);
|
||||
board.enter(Component::kAction, ComponentPhase::kPaused);
|
||||
sleepMs(80);
|
||||
dog.checkOnce();
|
||||
EXPECT_TRUE(dog.hung(Component::kRecovery)) << "told to stop and never returned = hung";
|
||||
EXPECT_FALSE(dog.hung(Component::kAction)) << "a paused handler is not expected to progress";
|
||||
}
|
||||
|
||||
TEST(Watchdog, ZeroBudgetDisablesThatRow)
|
||||
{
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0;
|
||||
c.action_stall_budget = 0.0;
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
|
||||
board.enter(Component::kAction, ComponentPhase::kBusy);
|
||||
sleepMs(80);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.hung(Component::kAction));
|
||||
}
|
||||
|
||||
TEST(Watchdog, ControlLoopHeartbeatStallIsDetectedFromTheWatchdogThread)
|
||||
{
|
||||
// Mô hình thật: control thread heartbeat cuối mỗi step(); ngừng heartbeat = treo. Watchdog chạy
|
||||
// thread riêng và phải tự thấy — đây là thứ control thread không tự làm được.
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
ASSERT_TRUE(dog.start(&board, fastConfig(), error)) << error;
|
||||
ASSERT_TRUE(dog.running());
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
board.progress(Component::kControlLoop);
|
||||
sleepMs(10);
|
||||
}
|
||||
EXPECT_FALSE(dog.controlLoopHung());
|
||||
|
||||
sleepMs(120); // không heartbeat
|
||||
EXPECT_TRUE(dog.controlLoopHung());
|
||||
|
||||
board.progress(Component::kControlLoop);
|
||||
sleepMs(40);
|
||||
EXPECT_FALSE(dog.controlLoopHung());
|
||||
|
||||
dog.stop();
|
||||
EXPECT_FALSE(dog.running());
|
||||
}
|
||||
|
||||
TEST(Watchdog, RowThatNeverProgressedIsNotHung)
|
||||
{
|
||||
// Runtime mới lên: control loop chưa chạy cycle nào, last_progress = 0 — không được báo treo ngay.
|
||||
ComponentStatusBoard board;
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
WatchdogConfig c = fastConfig();
|
||||
c.period = 0.0;
|
||||
ASSERT_TRUE(dog.start(&board, c, error)) << error;
|
||||
sleepMs(80);
|
||||
dog.checkOnce();
|
||||
EXPECT_FALSE(dog.controlLoopHung());
|
||||
}
|
||||
|
||||
TEST(Watchdog, StartRequiresABoardAndRefusesDoubleStart)
|
||||
{
|
||||
Watchdog dog;
|
||||
std::string error;
|
||||
EXPECT_FALSE(dog.start(nullptr, fastConfig(), error));
|
||||
ComponentStatusBoard board;
|
||||
ASSERT_TRUE(dog.start(&board, fastConfig(), error)) << error;
|
||||
EXPECT_FALSE(dog.start(&board, fastConfig(), error)) << "already running";
|
||||
dog.stop();
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
Reference in New Issue
Block a user