feat: lan truyen BaseNavigation::emergency()/clearEmergency() len tren

NavigationServer::emergency() phan anh ngay tren thread goi (getTwist
tra 0, getFeedback bao EMERGENCY) truoc khi ham tra ve, du control
thread dang block trong plugin nao; don dep that (planner/recovery/
action/mission layer) chay o chu ky ke cua control thread. State
NavigationState::kEmergency la state GIU, khong terminal: pause/resume/
cancel/goal moi deu bi bo qua, chi clearEmergency() moi thoat, ve
kIdle.

MissionLayer: emergency() -> drain hang doi, goi cancel toi navigation
dung 1 lan, chuyen MissionState::EMERGENCY; clearEmergency() ve
CLEAR_EMERGENCY, khong tu chay lai gi, cho order ke tiep.

Test moi cho ca 2 lop (navigation_server_test, mission_layer_test,
state_machine_test, walking_skeleton_test) phu: force-zero-truoc-cycle,
tu choi moveTo/instantActions khi dang chot, huy goal con pending, mo
chot roi nhan goal moi.
This commit is contained in:
2026-09-15 15:08:09 +07:00
parent ac307b0358
commit f42cff3510
16 changed files with 1058 additions and 11 deletions

View File

@@ -270,6 +270,42 @@ TEST(MissionLayerTest, CancelStopsNavigationAndDropsTheQueue)
EXPECT_EQ(1u, fixture.received_.size());
}
TEST(MissionLayerTest, EmergencyStopsNavigationWipesTheQueueAndBlocksSubmitUntilCleared)
{
// Đường 2026-09-14: NavigationServer::emergency() → drain → MissionLayer::emergency(). Layer đã có
// sẵn hàm này; test khoá ba tính chất host dựa vào: robot được bảo dừng, hàng đợi trống, và không
// order nào được nhận cho tới khi gỡ chốt.
Fixture fixture(3);
ASSERT_TRUE(fixture.layer_.submitGoal(makeGoal()));
ASSERT_TRUE(fixture.pumpUntilRequest());
fixture.layer_.emergency();
EXPECT_TRUE(fixture.waitForState(MissionState::EMERGENCY));
const auto deadline = std::chrono::steady_clock::now() + kTimeout;
while (fixture.cancel_calls_ == 0 && std::chrono::steady_clock::now() < deadline)
{
std::this_thread::sleep_for(kPollStep);
}
EXPECT_GE(fixture.cancel_calls_, 1) << "emergency must ask navigation to stop, not just forget the queue";
EXPECT_FALSE(fixture.layer_.hasMission()) << "the remaining legs are gone";
// Chốt: order mới bị manager gạt (trên thread sự kiện) — không có chặng nào xuống, state giữ nguyên.
ASSERT_TRUE(fixture.layer_.submitGoal(makeGoal())) << "submitGoal only means 'queued on the event bus'";
EXPECT_FALSE(fixture.pumpUntilRequest());
EXPECT_EQ(fixture.layer_.state(), MissionState::EMERGENCY);
EXPECT_EQ(1u, fixture.received_.size());
// Gỡ chốt: về CLEAR_EMERGENCY, KHÔNG tự chạy lại gì; order kế mới được nhận.
fixture.layer_.clearEmergency();
EXPECT_TRUE(fixture.waitForState(MissionState::CLEAR_EMERGENCY));
EXPECT_FALSE(fixture.pumpUntilRequest());
ASSERT_TRUE(fixture.layer_.submitGoal(makeGoal()));
EXPECT_TRUE(fixture.pumpUntilRequest());
EXPECT_EQ(2u, fixture.received_.size());
}
TEST(MissionLayerTest, PausedLayerHoldsTheQueueUntilResume)
{
Fixture fixture(2);

View File

@@ -934,6 +934,211 @@ TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing);
}
// ================================================================================================
// EMERGENCY (2026-09-14) — phản ứng trên thread host trước, control thread dọn sau
// ================================================================================================
namespace
{
/// @brief Đưa fixture tới CONTROLLING với lệnh khác 0 đang phát.
void driveToControllingWithSpeed(Fixture& fixture, double speed)
{
fixture.configure();
fixture.controller_.setNominalSpeed(speed);
fixture.controller_.setScript({ ControllerScript::kOk, ControllerScript::kOk, ControllerScript::kOk,
ControllerScript::kOk, ControllerScript::kOk });
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::kControlling);
ASSERT_NEAR(fixture.server_.getTwist().velocity.x, speed, 1e-9);
}
} // namespace
TEST(NavigationServerEmergency, ForcesZeroTwistAndEmergencyStateBeforeTheNextCycle)
{
Fixture fixture;
driveToControllingWithSpeed(fixture, 0.3);
const robot::Time before = fixture.server_.getTwist().header.stamp;
fixture.server_.emergency();
// KHÔNG spin: đây là điều khác biệt với pause/cancel — host phải thấy 0 ngay trong lời gọi kế.
const robot_nav_2d_msgs::Twist2DStamped twist = fixture.server_.getTwist();
EXPECT_NEAR(twist.velocity.x, 0.0, 1e-9) << "the last command must not leak past emergency()";
EXPECT_NEAR(twist.velocity.theta, 0.0, 1e-9);
EXPECT_GE(twist.header.stamp.toSec(), before.toSec()) << "the zero must be fresh so the host publishes it";
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::EMERGENCY);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kControlling)
<< "the core itself only learns about it on the next cycle";
}
TEST(NavigationServerEmergency, EntersTheCoreStateOnTheNextCycleAndReportsTheLegCancelled)
{
Fixture fixture;
driveToControllingWithSpeed(fixture, 0.3);
fixture.server_.emergency();
fixture.spin(1);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::EMERGENCY);
EXPECT_NEAR(fixture.server_.getTwist().velocity.x, 0.0, 1e-9);
ASSERT_EQ(fixture.server_.loop().outcomeReportCount(), 1u) << "the interrupted leg is reported exactly once";
EXPECT_STREQ(fixture.server_.loop().lastOutcome(), "CANCELLED");
fixture.spin(5);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency) << "it is a latch, not a state that expires";
EXPECT_EQ(fixture.server_.loop().outcomeReportCount(), 1u);
}
TEST(NavigationServerEmergency, MoveToAndInstantActionsAreRejectedWhileLatched)
{
Fixture fixture;
fixture.configure();
fixture.server_.emergency();
fixture.spin(1);
EXPECT_FALSE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10));
EXPECT_NE(fixture.server_.lastRejectReason().find("emergency"), std::string::npos)
<< fixture.server_.lastRejectReason();
robot_protocol_msgs::Action action;
action.actionType = "PickUp";
action.actionId = "PickUp_1";
action.blockingType = "HARD";
EXPECT_FALSE(fixture.server_.executeInstantActions({ action }));
fixture.spin(3);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
}
TEST(NavigationServerEmergency, DropsAGoalThatWasStillPending)
{
Fixture fixture;
fixture.configure();
fixture.controller_.setScript({ ControllerScript::kOk });
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10));
// Goal đã vào ControlLoop (pending) nhưng chưa qua cycle nào — dừng khẩn tới trước.
fixture.server_.emergency();
fixture.spin(3);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
EXPECT_EQ(fixture.server_.loop().outcomeReportCount(), 0u) << "a leg that never started has no outcome";
// Gỡ chốt: goal cũ KHÔNG được tự chạy.
fixture.server_.clearEmergency();
fixture.spin(3);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kIdle);
}
TEST(NavigationServerEmergency, ClearReportsPendingAndAcceptsANewGoal)
{
Fixture fixture;
driveToControllingWithSpeed(fixture, 0.3);
fixture.server_.emergency();
fixture.spin(1);
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
fixture.server_.clearEmergency();
fixture.spin(1);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kIdle);
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PENDING)
<< "a clean slate, not a latched PREEMPTED: the host must send a new goal";
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
<< fixture.server_.lastRejectReason();
fixture.spin(2);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kControlling);
}
TEST(NavigationServerEmergency, WinsOverPauseAndCancelRequestedInTheSameDrain)
{
Fixture fixture;
driveToControllingWithSpeed(fixture, 0.3);
fixture.server_.pause();
fixture.server_.cancel();
fixture.server_.emergency();
fixture.spin(1);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
// Và ngược lại: dừng khẩn rồi mới pause/cancel cũng không đổi gì.
fixture.server_.pause();
fixture.server_.cancel();
fixture.server_.resume();
fixture.spin(2);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
}
TEST(NavigationServerEmergency, ClearThenEmergencyInTheSameDrainStaysLatched)
{
// Hai cờ đối nghịch dưới một lock: lệnh gọi SAU thắng, như pause/resume.
Fixture fixture;
fixture.configure();
fixture.server_.emergency();
fixture.spin(1);
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
fixture.server_.clearEmergency();
fixture.server_.emergency();
fixture.spin(2);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::EMERGENCY);
}
TEST(NavigationServerEmergency, TwistStampFreezesAfterTheGraceWindowWhileStillLatched)
{
Fixture fixture;
driveToControllingWithSpeed(fixture, 0.3);
fixture.server_.emergency();
const robot::Time fresh = fixture.server_.getTwist().header.stamp;
EXPECT_NEAR(fresh.toSec(), fixture.clock_.now().toSec(), 1e-9);
// Trong cửa ân hạn: stamp tiến theo đồng hồ (host publish 0 tường minh).
fixture.clock_.advance(0.2);
EXPECT_NEAR(fixture.server_.getTwist().header.stamp.toSec(), fixture.clock_.now().toSec(), 1e-9);
// Hết cửa: stamp đứng — host thấy lệnh quá hạn, nhường /cmd_vel; vận tốc vẫn 0.
fixture.clock_.advance(1.0);
const robot_nav_2d_msgs::Twist2DStamped late = fixture.server_.getTwist();
EXPECT_LT(late.header.stamp.toSec(), fixture.clock_.now().toSec() - 0.5);
EXPECT_NEAR(late.velocity.x, 0.0, 1e-9);
}
TEST(NavigationServerEmergency, OverridesTwistEvenWhenTheControlThreadNeverSpins)
{
// Mô phỏng control thread kẹt: không spin sau emergency(). Lệnh 0.3 m/s cuối cùng còn nằm
// trong twist_ của control loop — host không được thấy nó.
Fixture fixture;
driveToControllingWithSpeed(fixture, 0.3);
fixture.server_.emergency();
for (int i = 0; i < 5; ++i)
{
fixture.clock_.advance(0.01);
EXPECT_NEAR(fixture.server_.getTwist().velocity.x, 0.0, 1e-9) << "read " << i;
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::EMERGENCY);
}
}
TEST(NavigationServerEmergency, IsIdempotentAndClearWithoutLatchIsANoOp)
{
Fixture fixture;
fixture.configure();
fixture.server_.clearEmergency(); // chưa chốt gì — không được đổi state
fixture.spin(1);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kIdle);
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PENDING);
fixture.server_.emergency();
fixture.server_.emergency();
fixture.spin(2);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kEmergency);
fixture.server_.clearEmergency();
fixture.server_.clearEmergency();
fixture.spin(2);
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kIdle);
}
// ================================================================================================
// Control thread
//

View File

@@ -2057,8 +2057,8 @@ TEST(StateMachineInvariants, EveryStateHasANonEmptyName)
const NavigationState states[] = {
NavigationState::kIdle, NavigationState::kPlanning, NavigationState::kControlling,
NavigationState::kRecovering, NavigationState::kExecutingActions, NavigationState::kPausing,
NavigationState::kPaused, NavigationState::kCancelling, NavigationState::kSucceeded, NavigationState::kAborted,
NavigationState::kCancelled,
NavigationState::kPaused, NavigationState::kCancelling, NavigationState::kEmergency,
NavigationState::kSucceeded, NavigationState::kAborted, NavigationState::kCancelled,
};
for (const auto state : states)
@@ -2657,6 +2657,248 @@ TEST(StateMachineConfigValidation, MonitorRoutesMayBeEmptyButIndicesMustExist)
EXPECT_NE(error.find("path_blocked"), std::string::npos) << error;
}
// ================================================================================================
// EMERGENCY (2026-09-14) — mức, không phải xung; thắng mọi thứ; chỉ ra khi host gỡ chốt
// ================================================================================================
namespace
{
StateMachineInput emergencyInput()
{
StateMachineInput input;
input.emergency = true;
return input;
}
/// @brief Các cách đưa máy vào từng state đang chạy, để một test quét được hết bảng.
void driveTo(Driver& driver, NavigationState target)
{
switch (target)
{
case NavigationState::kPlanning:
ASSERT_EQ(driver.tick(requestWithActions(0)).state, NavigationState::kPlanning);
return;
case NavigationState::kControlling:
driver.driveToControlling();
return;
case NavigationState::kRecovering:
ASSERT_EQ(driver.tick(requestWithActions(0)).state, NavigationState::kPlanning);
driver.advance(2.0);
ASSERT_EQ(driver.tick(plannerFailed()).state, NavigationState::kRecovering);
return;
case NavigationState::kExecutingActions:
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
NavigationState::kExecutingActions);
return;
case NavigationState::kPausing:
{
driver.driveToControlling();
StateMachineInput pause;
pause.pause_requested = true;
pause.planner_busy = true; // giữ ở PAUSING
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
return;
}
case NavigationState::kPaused:
{
driver.driveToControlling();
StateMachineInput pause;
pause.pause_requested = true;
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
StateMachineInput stopped;
stopped.robot_stopped = true;
ASSERT_EQ(driver.tick(stopped).state, NavigationState::kPaused);
return;
}
case NavigationState::kCancelling:
{
driver.driveToControlling();
StateMachineInput cancel;
cancel.cancel_requested = true;
cancel.planner_busy = true; // giữ ở CANCELLING
ASSERT_EQ(driver.tick(cancel).state, NavigationState::kCancelling);
return;
}
default:
FAIL() << "driveTo has no recipe for " << move_base2::toString(target);
}
}
} // namespace
TEST(StateMachineEmergency, FromEveryRunningStateStopsEverythingAndReportsCancelled)
{
const NavigationState running[] = {
NavigationState::kPlanning, NavigationState::kControlling, NavigationState::kRecovering,
NavigationState::kExecutingActions, NavigationState::kPausing, NavigationState::kPaused,
NavigationState::kCancelling,
};
for (const NavigationState from : running)
{
SCOPED_TRACE(move_base2::toString(from));
Driver driver;
driveTo(driver, from);
const StateMachineOutput out = driver.tick(emergencyInput());
EXPECT_EQ(out.state, NavigationState::kEmergency);
EXPECT_TRUE(out.state_changed);
EXPECT_STREQ(out.reason, "emergency stop");
EXPECT_TRUE(out.stop_planner);
EXPECT_EQ(out.cancel_recovery, from == NavigationState::kRecovering)
<< "only a running behavior is told to stop";
EXPECT_EQ(out.cancel_action, from == NavigationState::kExecutingActions)
<< "only a running action is told to stop (pause from CONTROLLING has no action)";
EXPECT_TRUE(out.report_outcome) << "the interrupted leg must be reported exactly once";
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled);
EXPECT_EQ(out.velocity_source, VelocitySource::kNone);
EXPECT_FALSE(out.run_controller);
EXPECT_FALSE(out.tick_recovery);
EXPECT_FALSE(out.accept_request);
EXPECT_FALSE(out.start_planner);
}
}
TEST(StateMachineEmergency, FromPausedActionCancelsTheActionThePauseKeptAlive)
{
// Tạm dừng KHÔNG huỷ action (handler vẫn giữ thiết bị dở dang) — dừng khẩn thì phải huỷ nó.
Driver driver;
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
NavigationState::kExecutingActions);
StateMachineInput pause;
pause.pause_requested = true;
ASSERT_EQ(driver.tick(pause).state, NavigationState::kPausing);
const StateMachineOutput out = driver.tick(emergencyInput());
EXPECT_EQ(out.state, NavigationState::kEmergency);
EXPECT_TRUE(out.cancel_action);
}
TEST(StateMachineEmergency, FromIdleDoesNotReportAnOutcomeAndRefusesThePendingGoal)
{
Driver driver;
StateMachineInput input = emergencyInput();
input.has_pending_request = true;
const StateMachineOutput out = driver.tick(input);
EXPECT_EQ(out.state, NavigationState::kEmergency);
EXPECT_FALSE(out.report_outcome) << "nothing was running, there is no leg to report";
EXPECT_FALSE(out.accept_request) << "a goal waiting at IDLE must not start under emergency";
EXPECT_FALSE(out.start_planner);
}
TEST(StateMachineEmergency, WinsOverCancelPauseAndANewGoalInTheSameCycle)
{
Driver driver;
driver.driveToControlling();
StateMachineInput everything = emergencyInput();
everything.cancel_requested = true;
everything.pause_requested = true;
everything.has_pending_request = true;
everything.planner = PlannerFeedback::kPlanReady;
const StateMachineOutput out = driver.tick(everything);
EXPECT_EQ(out.state, NavigationState::kEmergency);
EXPECT_EQ(out.outcome, NavigationOutcome::kCancelled) << "not PREEMPTED: the goal is dropped, not replaced";
EXPECT_FALSE(out.accept_request);
EXPECT_FALSE(out.apply_plan);
}
TEST(StateMachineEmergency, IgnoresEveryLifecycleRequestWhileLatched)
{
Driver driver;
driver.driveToControlling();
ASSERT_EQ(driver.tick(emergencyInput()).state, NavigationState::kEmergency);
StateMachineInput noise = emergencyInput();
noise.pause_requested = true;
noise.resume_requested = true;
noise.cancel_requested = true;
noise.has_pending_request = true;
noise.planner = PlannerFeedback::kPlanReady;
noise.controller = ControllerFeedback::kGoalReached;
noise.robot_stopped = true;
for (int cycle = 0; cycle < 10; ++cycle)
{
driver.advance(0.5);
const StateMachineOutput out = driver.tick(noise);
ASSERT_EQ(out.state, NavigationState::kEmergency) << "cycle " << cycle;
ASSERT_FALSE(out.state_changed);
ASSERT_FALSE(out.report_outcome) << "cycle " << cycle << ": outcome must be reported once, at entry";
ASSERT_FALSE(out.accept_request);
ASSERT_FALSE(out.start_planner);
ASSERT_FALSE(out.apply_plan);
ASSERT_FALSE(out.run_controller);
ASSERT_EQ(out.velocity_source, VelocitySource::kNone);
}
}
TEST(StateMachineEmergency, KeepsTickingTheActionUntilItReportsTerminal)
{
Driver driver;
ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state,
NavigationState::kExecutingActions);
StateMachineInput enter = emergencyInput();
enter.action_terminal = false;
const StateMachineOutput entered = driver.tick(enter);
ASSERT_EQ(entered.state, NavigationState::kEmergency);
EXPECT_TRUE(entered.cancel_action);
StateMachineInput still_stopping = emergencyInput();
still_stopping.action_terminal = false;
const StateMachineOutput ticking = driver.tick(still_stopping);
EXPECT_TRUE(ticking.tick_action) << "the device handler needs ticks to reach its safe stop";
EXPECT_EQ(ticking.velocity_source, VelocitySource::kNone);
const StateMachineOutput done = driver.tick(emergencyInput()); // action_terminal mặc định true
EXPECT_FALSE(done.tick_action);
EXPECT_EQ(done.state, NavigationState::kEmergency) << "terminal action does not end the emergency";
}
TEST(StateMachineEmergency, ClearReturnsToIdleAndOnlyTheNextCycleAcceptsAGoal)
{
Driver driver;
driver.driveToControlling();
ASSERT_EQ(driver.tick(emergencyInput()).state, NavigationState::kEmergency);
// Gỡ chốt đúng lúc có goal chờ: cycle này KHÔNG nhận — ControlLoop đã vứt yêu cầu chờ lúc vào
// dừng khẩn, thứ nằm ở đây không thể là yêu cầu hợp lệ.
StateMachineInput cleared;
cleared.has_pending_request = true;
const StateMachineOutput idle = driver.tick(cleared);
EXPECT_EQ(idle.state, NavigationState::kIdle);
EXPECT_STREQ(idle.reason, "emergency cleared");
EXPECT_FALSE(idle.accept_request);
EXPECT_FALSE(idle.report_outcome);
// Cycle kế: kIdle nhận goal như bình thường.
const StateMachineOutput planning = driver.tick(requestWithActions(0));
EXPECT_EQ(planning.state, NavigationState::kPlanning);
EXPECT_TRUE(planning.accept_request);
}
TEST(StateMachineEmergency, ClearWithoutAnythingPendingStaysIdle)
{
Driver driver;
ASSERT_EQ(driver.tick(emergencyInput()).state, NavigationState::kEmergency);
EXPECT_EQ(driver.idleTick().state, NavigationState::kIdle);
EXPECT_EQ(driver.idleTick().state, NavigationState::kIdle);
}
TEST(StateMachineEmergency, IsNotTerminalAndMustBeStopped)
{
EXPECT_FALSE(move_base2::isTerminal(NavigationState::kEmergency));
EXPECT_TRUE(move_base2::mustBeStopped(NavigationState::kEmergency));
EXPECT_STREQ(move_base2::toString(NavigationState::kEmergency), "EMERGENCY");
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);

View File

@@ -989,6 +989,147 @@ TEST(ControlLoop, GoalSentRightAfterCancelWaitsForTheBusyPlannerInsteadOfFailing
EXPECT_EQ(fixture.mission_.reportCountFor(4), 0u) << "mission 4 is still running";
}
TEST(ControlLoop, EmergencyWhileControllingZeroesTheCommandAndLatches)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kOk, ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 5), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
fixture.loop_.requestEmergency();
fixture.clock_.advance(kControlPeriod);
EXPECT_TRUE(fixture.loop_.step()) << "EMERGENCY is not terminal: the loop keeps running";
EXPECT_EQ(fixture.loop_.state(), NavigationState::kEmergency);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "zero in the very cycle, no ramp";
EXPECT_STREQ(fixture.loop_.lastOutcome(), "CANCELLED");
EXPECT_EQ(fixture.mission_.reportCountFor(5), 1u);
EXPECT_FALSE(fixture.loop_.hasActiveRequest());
// Chốt: goal mới bị từ chối tại cửa, pause/resume/cancel không đổi gì, lệnh vẫn 0.
EXPECT_FALSE(fixture.loop_.submit(makeRequest(5.0, 6), reason));
EXPECT_NE(reason.find("emergency"), std::string::npos) << reason;
fixture.loop_.requestPause();
fixture.loop_.requestResume();
fixture.loop_.requestCancel();
for (int i = 0; i < 5; ++i)
{
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kEmergency) << "cycle " << i;
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
}
EXPECT_EQ(fixture.mission_.reportCountFor(5), 1u) << "reported exactly once";
// Gỡ chốt: IDLE, không tự chạy; goal kế được nhận bình thường.
fixture.loop_.requestClearEmergency();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kIdle);
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kIdle);
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 6), reason)) << reason;
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
}
TEST(ControlLoop, EmergencyWhilePlannerIsBusyPreemptsItAndTheNextGoalWaitsInsteadOfFailing)
{
Fixture fixture(busyPlannerConfig());
driveToPlanningInFlight(fixture, 7);
const std::size_t cancels_before = fixture.planner_.cancelCount();
fixture.loop_.requestEmergency();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kEmergency)
<< "EMERGENCY is reported at once — it is a latch, not 'done'; nothing waits for quiescence";
EXPECT_EQ(fixture.planner_.cancelCount(), cancels_before + 1) << "the running makePlan is cut";
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
// Gỡ chốt trong lúc thread planner vẫn còn bận lượt đã huỷ, rồi gửi goal kế ngay: phải chờ
// (kBusy) chứ không được coi là hỏng.
fixture.loop_.requestClearEmergency();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kIdle);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 8), reason)) << reason;
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);
EXPECT_FALSE(saw_aborted);
EXPECT_TRUE(reached_controlling);
EXPECT_EQ(fixture.mission_.reportCountFor(8), 0u);
}
TEST(ControlLoop, EmergencyDropsAPendingRequestSoNothingRunsAfterClear)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 9), reason)) << reason;
ASSERT_EQ(fixture.loop_.state(), NavigationState::kIdle) << "still pending, no cycle ran";
fixture.loop_.requestEmergency();
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kEmergency);
EXPECT_EQ(fixture.mission_.reportCountFor(9), 0u) << "never accepted, nothing to report";
fixture.loop_.requestClearEmergency();
for (int i = 0; i < 3; ++i)
{
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
}
EXPECT_EQ(fixture.loop_.state(), NavigationState::kIdle) << "the dropped goal must not start by itself";
}
TEST(ControlLoop, EmergencyDuringRecoveryStopsTheBehavior)
{
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning});
fixture.recovery_.setRecoveryVelocity(true, -0.15);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 10), 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_.requestEmergency();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kEmergency);
EXPECT_EQ(fixture.recovery_.cancelCount(), 1u);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "the behavior's -0.15 m/s must not survive";
EXPECT_EQ(fixture.mission_.reportCountFor(10), 1u);
}
TEST(ControlLoop, PauseWhilePlanningThenResumeWaitsForTheBusyPlanner)
{
// pause lúc PLANNING đi cùng đường cancelPlan(); resume → PLANNING → startPlan() bị từ chối →