Bộ giám sát mới trong ControlLoop (core/env_monitor, core/grid_analysis, ports/environment_port, io/env_logger), thay bốn phép đo của PathMonitor (code cũ còn, tắt bằng path_monitor/enabled: false): - kContact: dò tiếp xúc dọc quỹ đạo local planner (thay cung v/omega), bao tốc độ sqrt(2a(d - margin)) có dư, phanh chỉ khi vượt bao, cờ collision khi kề mũi tĩnh 1 s; cổng xoay tại chỗ theo lệnh controller muốn; hysteresis + xác nhận khi nhả; đứng ra sau detour không dịch robot (nhường controller); giữ phanh khi route khoá thì báo no valid command để controller_patience leo thang. - kStall: cost_to_go = geodesic tới điểm thoát 2 m dọc plan + phần plan còn lại, index plan bám cửa sổ, bộ lọc lật liên thông; cờ no_progress chỉ khi cổng dịch chuyển thực mở (robot không đi được đâu trong 12 s dù lệnh >= 1,5 m) — thay ngân sách replan cho stall. - kUnreachable: liên thông tới điểm thoát, đang ở action log. - EnvLogger ghi JSONL mỗi tick nặng; config/runtime/env_monitor_params.yaml đủ khoá, comment tiếng Việt; ControllerPort::measuredVelocity; FakeEnvironmentPort cho test. Sim 5–6/9: hết churn detour, khe 1,25 m đi qua 0,5 m/s, lượt 6/9 10:15 2 detour/142 s không oan. Test: grid_analysis 31, env_monitor 43, plan_inspector 37, walking_skeleton 87, các bộ khác pass. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017xXjFjr2DQ6rhmhHSW4fk4
2278 lines
84 KiB
C++
2278 lines
84 KiB
C++
/*********************************************************************
|
||
*
|
||
* Software License Agreement (BSD License)
|
||
*
|
||
* move_base2 — test bộ khung chạy end-to-end với thành phần giả.
|
||
*
|
||
* Đây là test chứng minh contract giữa các cổng đã khớp: nhận yêu cầu, đi qua đủ state, gọi đúng
|
||
* cổng, phát đúng lệnh vận tốc, và báo kết quả đúng một lần.
|
||
*
|
||
* Author: DuongTD
|
||
*********************************************************************/
|
||
#include <gtest/gtest.h>
|
||
|
||
#include <algorithm>
|
||
#include <string>
|
||
#include <vector>
|
||
|
||
#include <move_base2/control_loop.h>
|
||
|
||
#include "fake_ports.h"
|
||
|
||
using move_base2::ControlLoop;
|
||
using move_base2::ControlLoopConfig;
|
||
using move_base2::ControlLoopDeps;
|
||
using move_base2::MotionProfile;
|
||
using move_base2::NavigationRequest;
|
||
using move_base2::NavigationState;
|
||
using move_base2::RecoveryTrigger;
|
||
using move_base2::testing::ActionScript;
|
||
using move_base2::testing::ControllerScript;
|
||
using move_base2::testing::FakeActionPort;
|
||
using move_base2::testing::FakeClockPort;
|
||
using move_base2::testing::FakeControllerPort;
|
||
using move_base2::testing::FakeCostmapStatusPort;
|
||
using move_base2::testing::FakeMissionPort;
|
||
using move_base2::testing::FakeEnvironmentPort;
|
||
using move_base2::testing::FakePathCheckPort;
|
||
using move_base2::testing::FakePlannerPort;
|
||
using move_base2::testing::FakePosePort;
|
||
using move_base2::testing::FakeRecoveryPort;
|
||
using move_base2::testing::PlannerScript;
|
||
using move_base2::testing::RecoveryScript;
|
||
|
||
namespace
|
||
{
|
||
|
||
constexpr double kControlPeriod = 0.05; ///< [s]
|
||
|
||
ControlLoopConfig baseConfig()
|
||
{
|
||
ControlLoopConfig config;
|
||
|
||
config.state_machine.planner_patience = 0.5; // [s]
|
||
config.state_machine.controller_patience = 0.5; // [s]
|
||
config.state_machine.oscillation_timeout = 0.0; // tắt
|
||
config.state_machine.oscillation_distance = 0.5; // [m]
|
||
config.state_machine.max_planning_retries = -1;
|
||
config.state_machine.recovery_behavior_count = 2;
|
||
config.state_machine.recovery_enabled = true;
|
||
|
||
config.velocity.max_vel_x = 0.5; // [m/s]
|
||
config.velocity.min_vel_x = -0.2; // [m/s]
|
||
config.velocity.max_vel_theta = 1.0; // [rad/s]
|
||
config.velocity.max_accel_x = 100.0; // [m/s^2] lớn để test tập trung vào state, không vào ramp
|
||
config.velocity.max_accel_theta = 100.0; // [rad/s^2]
|
||
|
||
config.nominal_control_period = kControlPeriod;
|
||
|
||
config.position.global_planner_name = "FakeGlobalPlanner";
|
||
config.position.local_planner_name = "FakeLocalPlanner";
|
||
|
||
config.docking = config.position;
|
||
config.docking.local_planner_name = "FakeDockPlanner";
|
||
config.go_straight = config.position;
|
||
config.go_straight.local_planner_name = "FakeStraightPlanner";
|
||
config.rotate = config.position;
|
||
config.rotate.local_planner_name = "FakeRotatePlanner";
|
||
|
||
return config;
|
||
}
|
||
|
||
NavigationRequest makeRequest(double goal_x, std::uint64_t sequence_id = 0)
|
||
{
|
||
NavigationRequest request;
|
||
request.profile = MotionProfile::kPosition;
|
||
request.goal.header.frame_id = "map";
|
||
request.goal.pose.position.x = goal_x;
|
||
request.goal.pose.orientation.w = 1.0;
|
||
request.mission_sequence_id = sequence_id;
|
||
return request;
|
||
}
|
||
|
||
/// @brief Gắn @p count action tên "act_<i>" vào yêu cầu — kiểm được thứ tự tới ActionPort (D8).
|
||
NavigationRequest withActions(NavigationRequest request, std::size_t count)
|
||
{
|
||
for (std::size_t i = 0; i < count; ++i)
|
||
{
|
||
robot_protocol_msgs::Action action;
|
||
action.actionType = "act_" + std::to_string(i);
|
||
request.actions.push_back(action);
|
||
}
|
||
return request;
|
||
}
|
||
|
||
/// @brief Yêu cầu chỉ-có-action (D8): has_goal = false, goal để mặc định — không được validate.
|
||
NavigationRequest makeActionOnlyRequest(std::size_t count, std::uint64_t sequence_id = 0)
|
||
{
|
||
NavigationRequest request;
|
||
request.has_goal = false;
|
||
request.mission_sequence_id = sequence_id;
|
||
return withActions(request, count);
|
||
}
|
||
|
||
/**
|
||
* @class Fixture
|
||
* @brief Dựng sẵn control loop nối với toàn bộ cổng giả.
|
||
*/
|
||
class Fixture
|
||
{
|
||
public:
|
||
explicit Fixture(const ControlLoopConfig& config = baseConfig()) : recovery_(2)
|
||
{
|
||
pose_.setPosition(0.0, 0.0);
|
||
|
||
deps_.clock = &clock_;
|
||
deps_.pose = &pose_;
|
||
deps_.planner = &planner_;
|
||
deps_.controller = &controller_;
|
||
deps_.recovery = &recovery_;
|
||
deps_.mission = &mission_;
|
||
deps_.action = &action_;
|
||
deps_.costmap_status = &costmap_status_;
|
||
deps_.path_check = &path_check_;
|
||
deps_.environment = &environment_;
|
||
|
||
std::string error;
|
||
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
|
||
}
|
||
|
||
/// @brief Chạy tối đa @p max_cycles cycle, ghi lại chuỗi state (đã nén lặp liên tiếp).
|
||
void run(std::size_t max_cycles = 200)
|
||
{
|
||
for (std::size_t i = 0; i < max_cycles; ++i)
|
||
{
|
||
record();
|
||
if (!loop_.step())
|
||
{
|
||
record();
|
||
return;
|
||
}
|
||
clock_.advance(kControlPeriod);
|
||
}
|
||
hit_limit_ = true;
|
||
}
|
||
|
||
/// @brief Chạy đúng một cycle và ghi lại state sau cycle đó.
|
||
void stepOnce()
|
||
{
|
||
loop_.step();
|
||
clock_.advance(kControlPeriod);
|
||
record();
|
||
}
|
||
|
||
const std::vector<std::string>& states() const
|
||
{
|
||
return states_;
|
||
}
|
||
|
||
bool hitLimit() const
|
||
{
|
||
return hit_limit_;
|
||
}
|
||
|
||
ControlLoop loop_;
|
||
FakeClockPort clock_;
|
||
FakePosePort pose_;
|
||
FakePlannerPort planner_;
|
||
FakeControllerPort controller_;
|
||
FakeRecoveryPort recovery_;
|
||
FakeMissionPort mission_;
|
||
FakeActionPort action_;
|
||
FakeCostmapStatusPort costmap_status_;
|
||
FakePathCheckPort path_check_;
|
||
FakeEnvironmentPort environment_;
|
||
ControlLoopDeps deps_;
|
||
|
||
private:
|
||
void record()
|
||
{
|
||
const std::string name = move_base2::toString(loop_.state());
|
||
if (states_.empty() || states_.back() != name)
|
||
{
|
||
states_.push_back(name);
|
||
}
|
||
}
|
||
|
||
std::vector<std::string> states_;
|
||
bool hit_limit_ = false;
|
||
};
|
||
|
||
std::string join(const std::vector<std::string>& items)
|
||
{
|
||
std::string out = "[";
|
||
for (std::size_t i = 0; i < items.size(); ++i)
|
||
{
|
||
out += items[i];
|
||
if (i + 1 < items.size())
|
||
{
|
||
out += ", ";
|
||
}
|
||
}
|
||
return out + "]";
|
||
}
|
||
|
||
} // namespace
|
||
|
||
// ================================================================================================
|
||
// Cấu hình và cửa vào
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoop, RefusesToConfigureWithMissingPorts)
|
||
{
|
||
ControlLoop loop;
|
||
ControlLoopDeps deps; // toàn null
|
||
|
||
std::string error;
|
||
EXPECT_FALSE(loop.configure(baseConfig(), deps, error));
|
||
EXPECT_NE(error.find("port"), std::string::npos);
|
||
EXPECT_FALSE(loop.initialized());
|
||
}
|
||
|
||
TEST(ControlLoop, RefusesToConfigureWithInvalidVelocityLimits)
|
||
{
|
||
Fixture fixture;
|
||
ControlLoopConfig bad = baseConfig();
|
||
bad.velocity.max_vel_x = -1.0;
|
||
|
||
ControlLoop loop;
|
||
std::string error;
|
||
EXPECT_FALSE(loop.configure(bad, fixture.deps_, error));
|
||
}
|
||
|
||
TEST(ControlLoop, RefusesToConfigureWithoutPositionPlanner)
|
||
{
|
||
Fixture fixture;
|
||
ControlLoopConfig bad = baseConfig();
|
||
bad.position.local_planner_name.clear();
|
||
|
||
ControlLoop loop;
|
||
std::string error;
|
||
EXPECT_FALSE(loop.configure(bad, fixture.deps_, error));
|
||
EXPECT_NE(error.find("position"), std::string::npos);
|
||
}
|
||
|
||
TEST(ControlLoop, RejectsGoalWithInvalidQuaternion)
|
||
{
|
||
Fixture fixture;
|
||
NavigationRequest request = makeRequest(3.0);
|
||
request.goal.pose.orientation.w = 0.0; // norm = 0
|
||
|
||
std::string reason;
|
||
EXPECT_FALSE(fixture.loop_.submit(request, reason));
|
||
EXPECT_NE(reason.find("quaternion"), std::string::npos);
|
||
}
|
||
|
||
TEST(ControlLoop, RejectsGoalWithNonFiniteCoordinates)
|
||
{
|
||
Fixture fixture;
|
||
NavigationRequest request = makeRequest(3.0);
|
||
request.goal.pose.position.x = std::numeric_limits<double>::quiet_NaN();
|
||
|
||
std::string reason;
|
||
EXPECT_FALSE(fixture.loop_.submit(request, reason));
|
||
}
|
||
|
||
TEST(ControlLoop, RejectsRequestWhenLocalPlannerCannotBeLoaded)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setSwapSucceeds(false);
|
||
|
||
std::string reason;
|
||
EXPECT_FALSE(fixture.loop_.submit(makeRequest(3.0), reason));
|
||
EXPECT_NE(reason.find("local planner"), std::string::npos);
|
||
}
|
||
|
||
TEST(ControlLoop, RejectsRequestWhenGlobalPlannerCannotBeLoaded)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setSwapSucceeds(false);
|
||
|
||
std::string reason;
|
||
EXPECT_FALSE(fixture.loop_.submit(makeRequest(3.0), reason));
|
||
EXPECT_NE(reason.find("global planner"), std::string::npos);
|
||
}
|
||
|
||
TEST(ControlLoop, ProfileSelectsItsOwnLocalPlanner)
|
||
{
|
||
Fixture fixture;
|
||
|
||
NavigationRequest docking = makeRequest(1.0);
|
||
docking.profile = MotionProfile::kDocking;
|
||
docking.marker = "dock_a";
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(docking, reason)) << reason;
|
||
EXPECT_EQ(fixture.controller_.activeController(), "FakeDockPlanner");
|
||
// Marker phải tới port TRƯỚC khi swap — planner đọc maker_name trong initialize().
|
||
EXPECT_EQ(fixture.controller_.lastDockingMarker(), "dock_a");
|
||
|
||
NavigationRequest rotate = makeRequest(1.0);
|
||
rotate.profile = MotionProfile::kRotate;
|
||
ASSERT_TRUE(fixture.loop_.submit(rotate, reason)) << reason;
|
||
EXPECT_EQ(fixture.controller_.activeController(), "FakeRotatePlanner");
|
||
}
|
||
|
||
TEST(ControlLoop, DockingMarkerProfileOverridesBothPlannersAndFallsBackToDefault)
|
||
{
|
||
ControlLoopConfig config = baseConfig();
|
||
config.docking_marker_profiles["trolley"].global_planner_name = "FakeTrolleyGlobalPlanner";
|
||
config.docking_marker_profiles["trolley"].local_planner_name = "FakeTrolleyLocalPlanner";
|
||
Fixture fixture(config);
|
||
|
||
NavigationRequest trolley = makeRequest(1.0);
|
||
trolley.profile = MotionProfile::kDocking;
|
||
trolley.marker = "trolley";
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(trolley, reason)) << reason;
|
||
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeTrolleyGlobalPlanner");
|
||
EXPECT_EQ(fixture.controller_.activeController(), "FakeTrolleyLocalPlanner");
|
||
|
||
NavigationRequest unconfigured = makeRequest(1.0);
|
||
unconfigured.profile = MotionProfile::kDocking;
|
||
unconfigured.marker = "charger";
|
||
ASSERT_TRUE(fixture.loop_.submit(unconfigured, reason)) << reason;
|
||
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeGlobalPlanner");
|
||
EXPECT_EQ(fixture.controller_.activeController(), "FakeDockPlanner");
|
||
}
|
||
|
||
TEST(ControlLoop, RejectsDockingRequestWithoutMarker)
|
||
{
|
||
Fixture fixture;
|
||
|
||
NavigationRequest docking = makeRequest(1.0);
|
||
docking.profile = MotionProfile::kDocking;
|
||
// marker cố ý bỏ trống — bản cũ cũng chặn tại cửa dockTo.
|
||
|
||
std::string reason;
|
||
EXPECT_FALSE(fixture.loop_.submit(docking, reason));
|
||
EXPECT_NE(reason.find("marker"), std::string::npos) << reason;
|
||
}
|
||
|
||
TEST(ControlLoop, AllowsGoalFrameStyleDockingWithoutMarkerWhenConfigured)
|
||
{
|
||
ControlLoopConfig config = baseConfig();
|
||
config.docking_requires_marker = false;
|
||
Fixture fixture(config);
|
||
|
||
NavigationRequest docking = makeRequest(1.0);
|
||
docking.profile = MotionProfile::kDocking;
|
||
|
||
std::string reason;
|
||
EXPECT_TRUE(fixture.loop_.submit(docking, reason)) << reason;
|
||
EXPECT_TRUE(fixture.controller_.lastDockingMarker().empty());
|
||
}
|
||
|
||
TEST(ControlLoop, RejectsDockingRequestWhenMarkerIsUnknown)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setDockingMarkerSucceeds(false); // marker không có trong maker_sources
|
||
|
||
NavigationRequest docking = makeRequest(1.0);
|
||
docking.profile = MotionProfile::kDocking;
|
||
docking.marker = "tram_la";
|
||
|
||
std::string reason;
|
||
EXPECT_FALSE(fixture.loop_.submit(docking, reason));
|
||
EXPECT_NE(reason.find("tram_la"), std::string::npos) << reason;
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Đường đi thuận lợi
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoop, HappyPathReachesSucceededAndReportsOnce)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({PlannerScript::kOk});
|
||
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kOk,
|
||
ControllerScript::kOk, ControllerScript::kGoalReached});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 42), reason)) << reason;
|
||
|
||
fixture.run();
|
||
|
||
EXPECT_FALSE(fixture.hitLimit());
|
||
EXPECT_EQ(fixture.states(), (std::vector<std::string>{"IDLE", "PLANNING", "CONTROLLING",
|
||
"SUCCEEDED"}))
|
||
<< join(fixture.states());
|
||
EXPECT_STREQ(fixture.loop_.lastOutcome(), "SUCCEEDED");
|
||
EXPECT_EQ(fixture.loop_.outcomeReportCount(), 1u);
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(42), 1u)
|
||
<< "each leg may report its outcome exactly once";
|
||
}
|
||
|
||
TEST(ControlLoop, DirectGoalWithoutMissionIdDoesNotTouchMissionLayer)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 0), reason)) << reason;
|
||
fixture.run();
|
||
|
||
EXPECT_EQ(fixture.loop_.outcomeReportCount(), 1u);
|
||
EXPECT_TRUE(fixture.mission_.reports().empty())
|
||
<< "a direct goal belongs to no mission so nothing is reported to the mission layer";
|
||
}
|
||
|
||
TEST(ControlLoop, ControllerCommandIsPublishedWhileControlling)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setNominalSpeed(0.3);
|
||
fixture.controller_.setScript({ControllerScript::kOk});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
fixture.loop_.step(); // IDLE -> PLANNING (lập plan trong cycle này)
|
||
fixture.clock_.advance(kControlPeriod);
|
||
fixture.loop_.step(); // PLANNING -> CONTROLLING, chạy controller ngay
|
||
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.3, 1e-9);
|
||
}
|
||
|
||
TEST(ControlLoop, OrderIsForwardedToThePlanner)
|
||
{
|
||
Fixture fixture;
|
||
NavigationRequest request = makeRequest(3.0);
|
||
request.order = std::make_shared<robot_protocol_msgs::Order>();
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(request, reason)) << reason;
|
||
|
||
fixture.loop_.step();
|
||
EXPECT_TRUE(fixture.planner_.sawOrder());
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Bất biến an toàn
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoop, NoVelocityIsEmittedOutsideControllingAndRecovering)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kOk,
|
||
ControllerScript::kGoalReached});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
for (int i = 0; i < 50; ++i)
|
||
{
|
||
const bool running = fixture.loop_.step();
|
||
const NavigationState state = fixture.loop_.state();
|
||
|
||
if (move_base2::mustBeStopped(state))
|
||
{
|
||
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0)
|
||
<< "state " << move_base2::toString(state) << " at cycle " << i;
|
||
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 0.0)
|
||
<< "state " << move_base2::toString(state) << " at cycle " << i;
|
||
}
|
||
|
||
if (!running)
|
||
{
|
||
break;
|
||
}
|
||
fixture.clock_.advance(kControlPeriod);
|
||
}
|
||
}
|
||
|
||
TEST(ControlLoop, NaNFromControllerIsBlockedByArbiter)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setScript({ControllerScript::kNaN});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
fixture.loop_.step();
|
||
fixture.clock_.advance(kControlPeriod);
|
||
fixture.loop_.step(); // CONTROLLING, controller trả NaN
|
||
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
EXPECT_GT(fixture.loop_.arbiter().nonFiniteRejections(), 0u);
|
||
}
|
||
|
||
TEST(ControlLoop, OverspeedCommandIsClampedNotPassedThrough)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setScript({ControllerScript::kTooFast});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
fixture.loop_.step();
|
||
fixture.clock_.advance(kControlPeriod);
|
||
fixture.loop_.step();
|
||
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.5);
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 1.0);
|
||
EXPECT_GT(fixture.loop_.arbiter().velocityClamps(), 0u);
|
||
}
|
||
|
||
TEST(ControlLoop, EmptyPlanIsTreatedAsFailureNotAsAValidPlan)
|
||
{
|
||
// Fake cố ý vi phạm contract (trả true kèm plan rỗng) để kiểm guard của bên gọi: plan rỗng lọt
|
||
// xuống sẽ thành front()/back() trên vector rỗng ở tầng dưới.
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({PlannerScript::kEmpty});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
fixture.run();
|
||
|
||
EXPECT_EQ(fixture.controller_.setPlanCount(), 0u) << "an empty plan must not be pushed down to "
|
||
"the controller";
|
||
EXPECT_STREQ(fixture.loop_.lastOutcome(), "FAILED");
|
||
}
|
||
|
||
TEST(ControlLoop, LostPoseStopsTheRobotImmediately)
|
||
{
|
||
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_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
|
||
fixture.pose_.setAvailable(false);
|
||
fixture.clock_.advance(kControlPeriod);
|
||
fixture.loop_.step();
|
||
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0)
|
||
<< "losing TF must stop the robot immediately, not keep going on a stale pose";
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Recovery
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoop, PrimaryPlannerFailureUsesBackupBeforeRecovery)
|
||
{
|
||
ControlLoopConfig config = baseConfig();
|
||
config.backup_global_planner_name = "FakeBackupGlobalPlanner";
|
||
// 0 nghĩa là không retry planner hiện tại. Backup vẫn phải có đúng một lượt riêng trước recovery.
|
||
config.state_machine.max_planning_retries = 0;
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({PlannerScript::kFail, PlannerScript::kOk});
|
||
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
|
||
|
||
std::string reason;
|
||
NavigationRequest request = makeRequest(3.0, 71);
|
||
request.order = std::make_shared<robot_protocol_msgs::Order>();
|
||
ASSERT_TRUE(fixture.loop_.submit(request, reason)) << reason;
|
||
fixture.run();
|
||
|
||
EXPECT_FALSE(fixture.hitLimit());
|
||
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeBackupGlobalPlanner");
|
||
EXPECT_EQ(fixture.planner_.makePlanCount(), 2u);
|
||
EXPECT_EQ(fixture.planner_.orderHistory(), (std::vector<bool>{true, false}));
|
||
EXPECT_EQ(fixture.recovery_.startCount(), 0u);
|
||
EXPECT_EQ(fixture.states(),
|
||
(std::vector<std::string>{"IDLE", "PLANNING", "CONTROLLING", "SUCCEEDED"}))
|
||
<< join(fixture.states());
|
||
}
|
||
|
||
TEST(ControlLoop, BackupPlannerFailureEscalatesToRecovery)
|
||
{
|
||
ControlLoopConfig config = baseConfig();
|
||
config.backup_global_planner_name = "FakeBackupGlobalPlanner";
|
||
config.state_machine.max_planning_retries = 0;
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({PlannerScript::kFail, PlannerScript::kFail});
|
||
fixture.recovery_.setScript({RecoveryScript::kRunning});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 72), reason)) << reason;
|
||
|
||
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeBackupGlobalPlanner");
|
||
EXPECT_EQ(fixture.planner_.makePlanCount(), 2u);
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
EXPECT_EQ(fixture.recovery_.startCount(), 1u);
|
||
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed);
|
||
}
|
||
|
||
TEST(ControlLoop, PlannerFailureDrivesRecoveryThenSucceeds)
|
||
{
|
||
// Kịch bản thật: planner bế tắc cho tới khi recovery gỡ được thế, sau đó lập plan bình thường.
|
||
// Lật kịch bản planner ngay khi quan sát thấy RECOVERING, thay vì đếm trước số cycle — đếm trước
|
||
// làm test phụ thuộc vào đúng thời điểm hết kiên nhẫn, thứ không phải là thứ đang được kiểm.
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({PlannerScript::kFail});
|
||
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
|
||
fixture.recovery_.setScript({RecoveryScript::kRunning, RecoveryScript::kSucceeded});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 7), reason)) << reason;
|
||
|
||
bool planner_unblocked = false;
|
||
std::vector<std::string> states;
|
||
|
||
for (int i = 0; i < 200; ++i)
|
||
{
|
||
const std::string name = move_base2::toString(fixture.loop_.state());
|
||
if (states.empty() || states.back() != name)
|
||
{
|
||
states.push_back(name);
|
||
}
|
||
|
||
if (!planner_unblocked && fixture.loop_.state() == NavigationState::kRecovering)
|
||
{
|
||
fixture.planner_.setScript({PlannerScript::kOk});
|
||
planner_unblocked = true;
|
||
}
|
||
|
||
if (!fixture.loop_.step())
|
||
{
|
||
states.push_back(move_base2::toString(fixture.loop_.state()));
|
||
break;
|
||
}
|
||
fixture.clock_.advance(kControlPeriod);
|
||
}
|
||
|
||
EXPECT_TRUE(planner_unblocked) << "never entered recovery";
|
||
EXPECT_EQ(states, (std::vector<std::string>{"IDLE", "PLANNING", "RECOVERING", "PLANNING",
|
||
"CONTROLLING", "SUCCEEDED"}))
|
||
<< join(states);
|
||
EXPECT_EQ(fixture.recovery_.startCount(), 1u);
|
||
EXPECT_EQ(fixture.recovery_.lastStartIndex(), 0u);
|
||
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed);
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
|
||
}
|
||
|
||
TEST(ControlLoop, AllRecoveriesExhaustedEndsInAbortedWithSingleReport)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({PlannerScript::kFail}); // luôn hỏng
|
||
fixture.recovery_.setScript({RecoveryScript::kSucceeded});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 9), reason)) << reason;
|
||
fixture.run();
|
||
|
||
EXPECT_FALSE(fixture.hitLimit());
|
||
EXPECT_EQ(fixture.states(),
|
||
(std::vector<std::string>{"IDLE", "PLANNING", "RECOVERING", "PLANNING", "RECOVERING",
|
||
"PLANNING", "ABORTED"}))
|
||
<< join(fixture.states());
|
||
|
||
EXPECT_EQ(fixture.recovery_.startedIndices(), (std::vector<std::size_t>{0u, 1u}))
|
||
<< "behaviors must run one after another, the first one must not repeat";
|
||
EXPECT_STREQ(fixture.loop_.lastOutcome(), "FAILED");
|
||
EXPECT_EQ(fixture.loop_.outcomeReportCount(), 1u);
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(9), 1u);
|
||
}
|
||
|
||
TEST(ControlLoop, RecoveryRefusingToStartMovesOnToTheNextBehavior)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({PlannerScript::kFail});
|
||
fixture.recovery_.setStartSucceeds(false);
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
fixture.run();
|
||
|
||
EXPECT_EQ(fixture.recovery_.startedIndices(), (std::vector<std::size_t>{0u, 1u}));
|
||
EXPECT_EQ(fixture.recovery_.updateCount(), 0u)
|
||
<< "a behavior that never started successfully must not be ticked";
|
||
EXPECT_STREQ(fixture.loop_.lastOutcome(), "FAILED");
|
||
}
|
||
|
||
TEST(ControlLoop, RecoveryVelocityGoesThroughArbiterWithOneHandoverCycle)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({PlannerScript::kFail});
|
||
fixture.recovery_.setScript({RecoveryScript::kRunning, RecoveryScript::kRunning,
|
||
RecoveryScript::kSucceeded});
|
||
fixture.recovery_.setRecoveryVelocity(true, -0.15); // [m/s], âm = lùi
|
||
fixture.controller_.setScript({ControllerScript::kOk});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
bool saw_reverse = false;
|
||
for (int i = 0; i < 60; ++i)
|
||
{
|
||
const bool running = fixture.loop_.step();
|
||
if (fixture.loop_.state() == NavigationState::kRecovering &&
|
||
fixture.loop_.lastCommand().linear.x < -1e-6)
|
||
{
|
||
saw_reverse = true;
|
||
EXPECT_GE(fixture.loop_.lastCommand().linear.x, -0.2) << "the reverse command must stay "
|
||
"within the limit";
|
||
}
|
||
if (!running)
|
||
{
|
||
break;
|
||
}
|
||
fixture.clock_.advance(kControlPeriod);
|
||
}
|
||
|
||
EXPECT_TRUE(saw_reverse) << "recovery published a velocity but the command never reached the "
|
||
"output";
|
||
}
|
||
|
||
TEST(ControlLoop, RecoveryDisabledAbortsOnFirstFailure)
|
||
{
|
||
ControlLoopConfig config = baseConfig();
|
||
config.state_machine.recovery_enabled = false;
|
||
config.state_machine.recovery_behavior_count = 0;
|
||
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({PlannerScript::kFail});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
fixture.run();
|
||
|
||
EXPECT_EQ(fixture.recovery_.startCount(), 0u);
|
||
EXPECT_EQ(fixture.states(), (std::vector<std::string>{"IDLE", "PLANNING", "ABORTED"}))
|
||
<< join(fixture.states());
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Pause / cancel
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoop, CancelWhileControllingStopsAndReportsCancelled)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setScript({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_.requestCancel();
|
||
|
||
int cycles_to_zero = 0;
|
||
for (int i = 0; i < 10; ++i)
|
||
{
|
||
fixture.clock_.advance(kControlPeriod);
|
||
const bool running = fixture.loop_.step();
|
||
++cycles_to_zero;
|
||
if (!running)
|
||
{
|
||
break;
|
||
}
|
||
}
|
||
|
||
EXPECT_LE(cycles_to_zero, 2) << "cmd_vel must reach 0 within 2 cycles after a cancel";
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||
EXPECT_STREQ(fixture.loop_.lastOutcome(), "CANCELLED");
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(5), 1u);
|
||
}
|
||
|
||
TEST(ControlLoop, CancelDuringRecoveryStopsTheBehavior)
|
||
{
|
||
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), 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);
|
||
|
||
EXPECT_EQ(fixture.recovery_.cancelCount(), 1u);
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
|
||
fixture.loop_.step();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
|
||
}
|
||
|
||
TEST(ControlLoop, PauseAndResumeMidControlling)
|
||
{
|
||
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);
|
||
|
||
fixture.loop_.requestPause();
|
||
fixture.clock_.advance(kControlPeriod);
|
||
fixture.loop_.step();
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
|
||
// 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);
|
||
fixture.loop_.requestResume();
|
||
fixture.loop_.step();
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Nhiều chặng liên tiếp
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoop, ThreeSequentialMissionLegsEachReportedExactlyOnce)
|
||
{
|
||
Fixture fixture;
|
||
|
||
for (std::uint64_t leg = 1; leg <= 3; ++leg)
|
||
{
|
||
fixture.planner_.setScript({PlannerScript::kOk});
|
||
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(static_cast<double>(leg), leg), reason)) << reason;
|
||
|
||
for (int i = 0; i < 50; ++i)
|
||
{
|
||
const bool running = fixture.loop_.step();
|
||
fixture.clock_.advance(kControlPeriod);
|
||
if (!running)
|
||
{
|
||
break;
|
||
}
|
||
}
|
||
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kSucceeded) << "leg " << leg;
|
||
ASSERT_EQ(fixture.mission_.reportCountFor(leg), 1u) << "leg " << leg;
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.outcomeReportCount(), 3u);
|
||
EXPECT_EQ(fixture.mission_.reports().size(), 3u);
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Action của mission (D8)
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoopActions, ActionOnlyMissionNeverTouchesPlannerOrController)
|
||
{
|
||
Fixture fixture;
|
||
fixture.action_.setScript({ActionScript::kRunning, ActionScript::kSucceeded,
|
||
ActionScript::kRunning, ActionScript::kSucceeded});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(2, 7), reason)) << reason;
|
||
fixture.run();
|
||
|
||
ASSERT_FALSE(fixture.hitLimit()) << join(fixture.states());
|
||
EXPECT_EQ(fixture.states(),
|
||
(std::vector<std::string>{"IDLE", "EXECUTING_ACTIONS", "SUCCEEDED"}))
|
||
<< join(fixture.states());
|
||
|
||
// Không một lời gọi nào tới planner/controller — và vì thế không một lệnh vận tốc nào khác 0.
|
||
EXPECT_EQ(fixture.planner_.makePlanCount(), 0u);
|
||
EXPECT_EQ(fixture.controller_.computeCount(), 0u);
|
||
EXPECT_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
EXPECT_EQ(fixture.loop_.lastCommand().angular.z, 0.0);
|
||
|
||
// Hai action tới port nguyên vẹn, đúng thứ tự; kết quả báo đúng một lần sau action cuối.
|
||
EXPECT_EQ(fixture.action_.startedActionTypes(),
|
||
(std::vector<std::string>{"act_0", "act_1"}));
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
|
||
}
|
||
|
||
TEST(ControlLoopActions, MissionWithGoalRunsActionsAfterGoalReached)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({PlannerScript::kOk});
|
||
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
|
||
fixture.action_.setScript({ActionScript::kRunning, ActionScript::kSucceeded});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(withActions(makeRequest(2.0, 11), 1), reason)) << reason;
|
||
fixture.run();
|
||
|
||
ASSERT_FALSE(fixture.hitLimit()) << join(fixture.states());
|
||
EXPECT_EQ(fixture.states(),
|
||
(std::vector<std::string>{"IDLE", "PLANNING", "CONTROLLING", "EXECUTING_ACTIONS",
|
||
"SUCCEEDED"}))
|
||
<< join(fixture.states());
|
||
EXPECT_EQ(fixture.action_.startedActionTypes(), (std::vector<std::string>{"act_0"}));
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(11), 1u);
|
||
}
|
||
|
||
TEST(ControlLoopActions, ActionFailureAbortsAndReportsOnce)
|
||
{
|
||
Fixture fixture;
|
||
fixture.action_.setScript({ActionScript::kRunning, ActionScript::kFailed});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 13), reason)) << reason;
|
||
fixture.run();
|
||
|
||
ASSERT_FALSE(fixture.hitLimit()) << join(fixture.states());
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kAborted);
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(13), 1u);
|
||
EXPECT_EQ(fixture.recovery_.startCount(), 0u) << "a failed action must not drag recovery in";
|
||
}
|
||
|
||
TEST(ControlLoopActions, SubmitRejectsActionRequestWhenActionPortMissing)
|
||
{
|
||
Fixture fixture;
|
||
|
||
ControlLoop bare_loop;
|
||
ControlLoopDeps deps = fixture.deps_;
|
||
deps.action = nullptr;
|
||
|
||
std::string error;
|
||
ASSERT_TRUE(bare_loop.configure(baseConfig(), deps, error)) << error;
|
||
|
||
std::string reason;
|
||
EXPECT_FALSE(bare_loop.submit(makeActionOnlyRequest(1), reason));
|
||
EXPECT_NE(reason.find("action port"), std::string::npos) << reason;
|
||
|
||
// Không goal lẫn action thì bị từ chối bất kể có port hay không.
|
||
EXPECT_FALSE(fixture.loop_.submit(makeActionOnlyRequest(0), reason));
|
||
EXPECT_NE(reason.find("neither goal nor action"), std::string::npos) << reason;
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Lập plan bất đồng bộ (kBusy)
|
||
//
|
||
// Global planner nặng mất hàng trăm ms, control loop chạy 20 Hz và là thread duy nhất phát cmd_vel.
|
||
// Các test dưới đây khoá lại điều kiện để tách được hai nhịp đó mà state machine không phải đoán.
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoopAsyncPlanner, StaysInPlanningWhileThePlannerIsStillWorking)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setLatencyCycles(3);
|
||
fixture.controller_.setScript({ControllerScript::kOk});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
fixture.stepOnce(); // IDLE -> PLANNING, kick lượt lập plan
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||
|
||
for (int i = 0; i < 3; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning)
|
||
<< "left PLANNING while the planner was still computing, cycle " << i;
|
||
}
|
||
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(ControlLoopAsyncPlanner, DoesNotRestartAPlanThatIsAlreadyRunning)
|
||
{
|
||
// `start_planner` là tín hiệu MỨC, bật lại mỗi cycle chừng nào còn ở PLANNING. Kick lại một lượt
|
||
// đang chạy sẽ làm mất toàn bộ thời gian đã bỏ ra cho nó.
|
||
Fixture fixture;
|
||
fixture.planner_.setLatencyCycles(4);
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
for (int i = 0; i < 4; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.planner_.makePlanCount(), 1u)
|
||
<< "the planning attempt was restarted every cycle";
|
||
}
|
||
|
||
TEST(ControlLoopAsyncPlanner, PlannerPatienceStillFiresWhileThePlannerIsBusy)
|
||
{
|
||
// Đây là thứ DUY NHẤT phát hiện được thread planner treo. Ở chế độ đồng bộ, planner treo làm
|
||
// treo luôn control loop nên còn dễ thấy; ở chế độ bất đồng bộ nó im lặng hoàn toàn.
|
||
ControlLoopConfig config = baseConfig();
|
||
config.state_machine.planner_patience = 0.2; // [s] = 4 cycle
|
||
config.state_machine.max_planning_retries = -1;
|
||
|
||
Fixture fixture(config);
|
||
fixture.planner_.setLatencyCycles(1000); // không bao giờ xong
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
for (int i = 0; i < 20; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
// Planner treo vĩnh viễn thì đường đi đúng là: hết kiên nhẫn -> recovery -> thử lại -> hết
|
||
// recovery -> ABORTED. Điều phải khoá lại là nó KHÔNG đứng im ở PLANNING.
|
||
EXPECT_NE(std::find(fixture.states().begin(), fixture.states().end(), "RECOVERING"),
|
||
fixture.states().end())
|
||
<< "the planner hung and nobody escalated — the robot would sit in PLANNING forever: "
|
||
<< join(fixture.states());
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kAborted) << join(fixture.states());
|
||
}
|
||
|
||
TEST(ControlLoopAsyncPlanner, KeepsFollowingTheOldPlanWhileReplanningInBackground)
|
||
{
|
||
// Chính là lý do tồn tại của cả mô hình: lập lại plan không được làm gián đoạn việc bám plan cũ.
|
||
ControlLoopConfig config = baseConfig();
|
||
config.state_machine.controller_patience = 100.0; // [s] không cho controller hết kiên nhẫn
|
||
Fixture fixture(config);
|
||
|
||
fixture.controller_.setNominalSpeed(0.3); // [m/s]
|
||
fixture.controller_.setScript({ControllerScript::kOk});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
fixture.stepOnce(); // PLANNING
|
||
fixture.stepOnce(); // -> CONTROLLING
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
for (int i = 0; i < 5; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.3, 1e-9)
|
||
<< "cmd_vel was interrupted while replanning, cycle " << i;
|
||
}
|
||
}
|
||
|
||
TEST(ControlLoopAsyncPlanner, BackgroundReplanSwapsThePlanWithoutLeavingControlling)
|
||
{
|
||
// Contract 2026-08-04: `planner_frequency` là cơ chế thay plan duy nhất trong lúc chạy — plan
|
||
// mới được lập nền theo nhịp và thay ngay trong kControlling, không đổi state, không dừng robot.
|
||
ControlLoopConfig config = baseConfig();
|
||
config.planner_frequency = 2.0; // [Hz] -> chu kỳ 0.5 s = 10 cycle @ kControlPeriod 0.05 s
|
||
Fixture fx(config);
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fx.loop_.submit(makeRequest(5.0), reason)) << reason;
|
||
|
||
// 1.5 s: lượt plan đầu (kPlanning) + ít nhất 2 nhịp replan nền.
|
||
for (int i = 0; i < 30; ++i)
|
||
{
|
||
fx.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fx.loop_.state(), NavigationState::kControlling);
|
||
EXPECT_GE(fx.planner_.makePlanCount(), 3u); // 1 lượt đầu + >= 2 replan nền
|
||
EXPECT_GE(fx.controller_.setPlanCount(), 3u); // mỗi plan mới đều tới controller
|
||
EXPECT_EQ(join(fx.states()), "[PLANNING, CONTROLLING]") << "replan nền không được đổi state";
|
||
}
|
||
|
||
TEST(ControlLoopAsyncPlanner, BackgroundReplanFailureKeepsTheCurrentPlanAndSkipsBackup)
|
||
{
|
||
// Replan nền hỏng thì plan cũ vẫn hiệu lực: không recovery, và nhất là KHÔNG kích backup
|
||
// planner — một lượt replan hụt mà đổi hẳn sang SBPL là mất quỹ đạo Order cho phần còn lại.
|
||
ControlLoopConfig config = baseConfig();
|
||
config.planner_frequency = 2.0; // [Hz]
|
||
config.backup_global_planner_name = "FakeBackupPlanner";
|
||
Fixture fx(config);
|
||
|
||
// Lượt đầu thành công; mọi lượt sau (toàn replan nền) đều fail.
|
||
fx.planner_.setScript({PlannerScript::kOk, PlannerScript::kFail});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fx.loop_.submit(makeRequest(5.0), reason)) << reason;
|
||
|
||
for (int i = 0; i < 30; ++i)
|
||
{
|
||
fx.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fx.loop_.state(), NavigationState::kControlling);
|
||
EXPECT_GE(fx.planner_.makePlanCount(), 2u); // replan nền có chạy thật và có fail thật
|
||
EXPECT_EQ(fx.planner_.activePlanner(), "FakeGlobalPlanner");
|
||
EXPECT_EQ(fx.planner_.swapCount(), 1u) << "backup planner must not be engaged by a background "
|
||
"replan failure";
|
||
}
|
||
|
||
TEST(ControlLoopAsyncPlanner, CancelWhilePlanningCancelsTheRunningPlan)
|
||
{
|
||
// Không huỷ thì lượt đang bay vẫn về và chiếm chỗ hộp thư, rồi bị nhận nhầm cho yêu cầu kế tiếp.
|
||
Fixture fixture;
|
||
fixture.planner_.setLatencyCycles(100);
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||
|
||
fixture.loop_.requestCancel();
|
||
fixture.stepOnce();
|
||
|
||
EXPECT_GE(fixture.planner_.cancelCount(), 1u);
|
||
EXPECT_FALSE(fixture.planner_.isPlanning());
|
||
}
|
||
|
||
TEST(ControlLoopAsyncPlanner, AcceptingANewRequestCancelsAnInFlightPlan)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setLatencyCycles(100);
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
fixture.stepOnce();
|
||
ASSERT_TRUE(fixture.planner_.isPlanning());
|
||
|
||
const std::size_t before = fixture.planner_.cancelCount();
|
||
fixture.loop_.requestCancel();
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0), reason)) << reason;
|
||
fixture.stepOnce();
|
||
|
||
EXPECT_GT(fixture.planner_.cancelCount(), before)
|
||
<< "a new request did not cancel the planning attempt of the old goal";
|
||
}
|
||
|
||
TEST(ControlLoopAsyncPlanner, FailureToStartAPlanIsTreatedAsAFailedAttempt)
|
||
{
|
||
// Không khởi động được mà im lặng thì state machine đứng ở PLANNING vô hạn: không có kFailed để
|
||
// đếm lượt, không có kPlanReady để đi tiếp.
|
||
ControlLoopConfig config = baseConfig();
|
||
config.state_machine.max_planning_retries = 2;
|
||
Fixture fixture(config);
|
||
fixture.planner_.setSwapSucceeds(true);
|
||
fixture.planner_.setScript({PlannerScript::kFail});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
|
||
fixture.run();
|
||
|
||
EXPECT_FALSE(fixture.hitLimit()) << join(fixture.states());
|
||
EXPECT_NE(std::find(fixture.states().begin(), fixture.states().end(), "RECOVERING"),
|
||
fixture.states().end())
|
||
<< join(fixture.states());
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Preempt — goal mới thay goal cũ NGAY
|
||
//
|
||
// Bấm goal mới nghĩa là goal cũ không còn muốn nữa. Xếp hàng chờ robot đi hết chặng cũ là hành vi
|
||
// không ai mong đợi, và mission layer cũng đã chốt "preempt ngay" (Q1, Phase 2).
|
||
// ================================================================================================
|
||
|
||
TEST(ControlLoopPreempt, NewGoalWhileControllingReplansImmediately)
|
||
{
|
||
Fixture fixture;
|
||
fixture.controller_.setScript({ControllerScript::kOk});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
fixture.stepOnce(); // IDLE -> PLANNING
|
||
fixture.stepOnce(); // -> CONTROLLING
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
const std::size_t plans_before = fixture.planner_.makePlanCount();
|
||
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0), reason)) << reason;
|
||
fixture.stepOnce();
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning)
|
||
<< "the new goal was queued instead of replacing the old one right away";
|
||
EXPECT_GT(fixture.planner_.makePlanCount(), plans_before) << "did not replan for the new goal";
|
||
}
|
||
|
||
TEST(ControlLoopPreempt, NewGoalWhilePlanningReplansImmediately)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setLatencyCycles(50); // plan cũ còn lâu mới xong
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0), reason)) << reason;
|
||
fixture.stepOnce();
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||
EXPECT_GE(fixture.planner_.cancelCount(), 1u) << "the planning attempt for the old goal was not "
|
||
"cancelled";
|
||
}
|
||
|
||
TEST(ControlLoopPreempt, OldMissionIsReportedPreemptedExactlyOnceUnderItsOwnId)
|
||
{
|
||
// Bất biến quan trọng nhất: báo kết quả ĐÚNG MỘT LẦN và ĐÚNG ID. Preempt báo kết quả chặng cũ và
|
||
// nhận chặng mới trong cùng một cycle — dùng nhầm id thì mission layer mất dấu cả hai chặng.
|
||
Fixture fixture;
|
||
fixture.controller_.setScript({ControllerScript::kOk});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 11), reason)) << reason;
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0, 22), reason)) << reason;
|
||
fixture.stepOnce();
|
||
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(11), 1u) << "the preempted leg was not reported "
|
||
"exactly once";
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(22), 0u) << "the NEW leg got its outcome reported the "
|
||
"moment it was accepted";
|
||
}
|
||
|
||
TEST(ControlLoopPreempt, PreemptedGoalStillFinishesTheNewOne)
|
||
{
|
||
// Preempt không được để lại trạng thái nửa vời: chặng mới phải chạy tới cùng như bình thường.
|
||
Fixture fixture;
|
||
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kOk,
|
||
ControllerScript::kGoalReached});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 11), reason)) << reason;
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0, 22), reason)) << reason;
|
||
fixture.run();
|
||
|
||
EXPECT_FALSE(fixture.hitLimit()) << join(fixture.states());
|
||
EXPECT_STREQ(fixture.loop_.lastOutcome(), "SUCCEEDED");
|
||
EXPECT_EQ(fixture.mission_.reportCountFor(22), 1u);
|
||
}
|
||
|
||
TEST(ControlLoopPreempt, NewGoalDuringRecoveryCancelsTheRunningBehavior)
|
||
{
|
||
ControlLoopConfig config = baseConfig();
|
||
config.state_machine.planner_patience = 0.05; // [s] vào recovery nhanh
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({PlannerScript::kFail});
|
||
fixture.recovery_.setScript({RecoveryScript::kRunning});
|
||
|
||
std::string reason;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
|
||
for (int i = 0; i < 6 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering) << join(fixture.states());
|
||
|
||
fixture.planner_.setScript({PlannerScript::kOk});
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0), reason)) << reason;
|
||
fixture.stepOnce();
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
|
||
EXPECT_GE(fixture.recovery_.cancelCount(), 1u) << "the running behavior was not told to stop";
|
||
}
|
||
|
||
// ================================================================================================
|
||
// Guard "không đi mù" — dữ liệu quan sát của costmap quá hạn
|
||
// ================================================================================================
|
||
//
|
||
// move_base thế hệ 1 có đúng guard này (`move_base.cpp:2720`) và move_base2 trước đây KHÔNG có:
|
||
// costmap hết hạn nghĩa là robot đang tránh vật cản trên một bản đồ của quá khứ.
|
||
|
||
TEST(StaleCostmap, BlocksWheelsWhileControlling)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(50, ControllerScript::kOk));
|
||
|
||
std::string error;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(2.0), error)) << error;
|
||
|
||
// Chạy tới khi đang bám plan và thực sự có lệnh khác 0.
|
||
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kControlling; ++i)
|
||
{
|
||
fixture.loop_.step();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
fixture.loop_.step();
|
||
ASSERT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0) << "no command to block yet";
|
||
|
||
const std::size_t controller_calls_before = fixture.controller_.computeCount();
|
||
|
||
fixture.costmap_status_.setCurrent(false);
|
||
fixture.loop_.step();
|
||
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "sensor data is stale yet it kept "
|
||
"driving";
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 0.0);
|
||
EXPECT_EQ(fixture.controller_.computeCount(), controller_calls_before)
|
||
<< "the controller must not compute a command on stale data";
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling)
|
||
<< "the guard only blocks the wheels, it does not change state — exactly like the old "
|
||
"version";
|
||
}
|
||
|
||
TEST(StaleCostmap, ResumesWhenSensorDataBecomesCurrentAgain)
|
||
{
|
||
Fixture fixture;
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(50, ControllerScript::kOk));
|
||
|
||
std::string error;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(2.0), error)) << error;
|
||
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kControlling; ++i)
|
||
{
|
||
fixture.loop_.step();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
fixture.costmap_status_.setCurrent(false);
|
||
fixture.loop_.step();
|
||
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
|
||
fixture.costmap_status_.setCurrent(true);
|
||
fixture.loop_.step();
|
||
EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0)
|
||
<< "sensors are fresh again yet the robot stays still";
|
||
}
|
||
|
||
TEST(StaleCostmap, DisabledByConfigLetsTheRobotDrive)
|
||
{
|
||
ControlLoopConfig config = baseConfig();
|
||
config.require_current_costmap = false;
|
||
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(50, ControllerScript::kOk));
|
||
|
||
std::string error;
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(2.0), error)) << error;
|
||
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kControlling; ++i)
|
||
{
|
||
fixture.loop_.step();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
fixture.costmap_status_.setCurrent(false);
|
||
fixture.loop_.step();
|
||
|
||
EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0)
|
||
<< "the guard is disabled by config yet it still blocked";
|
||
}
|
||
|
||
TEST(StaleCostmap, NullPortMeansNoGuard)
|
||
{
|
||
// Đường đi của mọi test cổng-giả có sẵn: không ai bơm costmap_status thì lõi coi là còn hạn.
|
||
Fixture fixture;
|
||
fixture.deps_.costmap_status = nullptr;
|
||
std::string error;
|
||
ASSERT_TRUE(fixture.loop_.configure(baseConfig(), fixture.deps_, error)) << error;
|
||
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(50, ControllerScript::kOk));
|
||
ASSERT_TRUE(fixture.loop_.submit(makeRequest(2.0), error)) << error;
|
||
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kControlling; ++i)
|
||
{
|
||
fixture.loop_.step();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
fixture.costmap_status_.setCurrent(false); // không ai hỏi nó cả
|
||
fixture.loop_.step();
|
||
|
||
EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0);
|
||
EXPECT_EQ(fixture.costmap_status_.queryCount(), 0u) << "the port was detached yet the core still "
|
||
"asked it";
|
||
}
|
||
|
||
// ================================================================================================
|
||
// PathMonitor (contract 2026-08-04d)
|
||
// ================================================================================================
|
||
|
||
namespace
|
||
{
|
||
/// @brief Nộp yêu cầu và trả true nếu lõi nhận — gọn hơn việc mỗi ca tự khai biến `reason`.
|
||
bool submitOk(Fixture& fixture, const NavigationRequest& request)
|
||
{
|
||
std::string reason;
|
||
const bool accepted = fixture.loop_.submit(request, reason);
|
||
EXPECT_TRUE(accepted) << reason;
|
||
return accepted;
|
||
}
|
||
|
||
/// Config có giám sát tuyến BẬT, ngưỡng ngắn để test không phải tua thời gian dài.
|
||
ControlLoopConfig monitorConfig()
|
||
{
|
||
ControlLoopConfig config = baseConfig();
|
||
config.state_machine.recovery_routes.planning_failed = { 0 };
|
||
config.state_machine.recovery_routes.controlling_failed = { 0 };
|
||
config.state_machine.recovery_routes.oscillation = { 0 };
|
||
config.state_machine.recovery_routes.path_blocked = { 1 };
|
||
config.state_machine.recovery_routes.off_path = { 1 };
|
||
config.state_machine.recovery_routes.collision = { 1 };
|
||
|
||
config.path_monitor.enabled = true;
|
||
config.path_monitor.check_period = 0.0; // quét mỗi cycle: test điều khiển thời gian bằng advance
|
||
config.path_monitor.confirm_time = 0.2; // [s]
|
||
config.path_monitor.horizon = 3.0; // [m]
|
||
config.path_monitor.min_detour_distance = 0.5; // [m]
|
||
// Phép đo lệch tuyến TẮT ở config cơ sở: pose giả đứng yên tại gốc còn plan giả nằm ở goal, nên
|
||
// cross-track luôn lớn và sẽ át hết mọi ca về "tuyến bị chắn". Ca lệch tuyến có config riêng.
|
||
config.path_monitor.max_cross_track = 0.0; // [m]
|
||
config.path_monitor.grace_after_new_plan = 0.0; // tắt để test khai hoả được ngay
|
||
return config;
|
||
}
|
||
} // namespace
|
||
|
||
TEST(WalkingSkeletonPathMonitor, BlockedPathStopsTheRobotAfterConfirmTime)
|
||
{
|
||
Fixture fixture(monitorConfig());
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
// Recovery chạy dài để test quan sát được trạng thái DỪNG, thay vì thấy nó thoáng qua trong một
|
||
// cycle rồi quay lại kControlling.
|
||
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce(); // kPlanning
|
||
fixture.stepOnce(); // kControlling
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
fixture.path_check_.setBlocked(true, 1.5);
|
||
|
||
// Chưa đủ confirm_time: robot vẫn chạy.
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
for (int i = 0; i < 6; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.0, 1e-9);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, PathBlockedCanBeDisabledOnItsOwn)
|
||
{
|
||
// Công tắc riêng (2026-08-06): tắt phép đo "tuyến bị chắn" mà không phải đặt `horizon` về 0 —
|
||
// ngưỡng giữ nguyên để bật lại chỉ cần đổi một cờ, và đọc config thấy rõ ý định.
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.path_monitor.path_blocked_enabled = false;
|
||
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
fixture.path_check_.setBlocked(true, 1.5);
|
||
for (int i = 0; i < 10; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
}
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, FlickeringObstacleDoesNotStopTheRobot)
|
||
{
|
||
// Người đi ngang qua đúng một lượt quét không được làm robot dừng — đó là cả lý do có debounce.
|
||
Fixture fixture(monitorConfig());
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.path_check_.setBlocked(i % 2 == 0, 1.5);
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
}
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, ObstacleTooCloseIsLeftToTheControllerPath)
|
||
{
|
||
// Vật cản sát nách: detour hầu như không ra nghiệm, và ca đó đã có controller_patience lo.
|
||
Fixture fixture(monitorConfig());
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
fixture.path_check_.setBlocked(true, 0.2); // [m] < min_detour_distance
|
||
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, StaleCostmapSuppressesTheMonitor)
|
||
{
|
||
// Costmap quá hạn thì mọi kết luận về vật cản đều là quá khứ — không được khai hoả dựa vào nó.
|
||
Fixture fixture(monitorConfig());
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
|
||
fixture.path_check_.setBlocked(true, 1.5);
|
||
fixture.costmap_status_.setCurrent(false);
|
||
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, UnavailableCheckIsTreatedAsUnknown)
|
||
{
|
||
// Cổng trả false = "không kết luận được". Không được suy thành bẩn (robot dừng oan mỗi lần TF trễ).
|
||
Fixture fixture(monitorConfig());
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
|
||
fixture.path_check_.setBlocked(true, 1.5);
|
||
fixture.path_check_.setAvailable(false);
|
||
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, DockingLegIsNeverMonitored)
|
||
{
|
||
// Đường cong vào dock là một thể thống nhất; cắt ghép nó là phá chính hình học đó.
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.docking_requires_marker = false;
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
|
||
NavigationRequest request = makeRequest(3.0);
|
||
request.profile = MotionProfile::kDocking;
|
||
ASSERT_TRUE(submitOk(fixture, request));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
fixture.path_check_.setBlocked(true, 1.5);
|
||
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, DriftingOffThePlanStopsTheRobot)
|
||
{
|
||
// Local planner tự né vật cản nhỏ (tầng 0) có thể kéo robot ra xa tuyến mà plan vẫn "sạch" và
|
||
// controller vẫn ra lệnh — không trigger nào khác nhìn thấy tình huống này.
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.path_monitor.max_cross_track = 0.4; // [m]
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
// Plan giả chỉ có pose goal (3, 0); robot bám sát nó thì cross-track nhỏ.
|
||
fixture.pose_.setPosition(3.0, 0.1);
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
// Dạt sang bên quá ngưỡng: sau `confirm_time` thì dừng.
|
||
fixture.pose_.setPosition(3.0, 0.9);
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.0, 1e-9);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, OffPathCanBeDisabledOnItsOwn)
|
||
{
|
||
// Đối xứng với `PathBlockedCanBeDisabledOnItsOwn`: ngưỡng `max_cross_track` vẫn để nguyên 0.4 m,
|
||
// chỉ hạ cờ — cấu hình đã đo được giữ lại, bật lại là một dòng.
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.path_monitor.max_cross_track = 0.4; // [m] ngưỡng thật, giữ nguyên
|
||
config.path_monitor.off_path_enabled = false;
|
||
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
fixture.pose_.setPosition(3.0, 5.0); // lệch rất xa
|
||
for (int i = 0; i < 10; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
}
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, GracePeriodSuppressesTheOffPathCheck)
|
||
{
|
||
// Ngay sau khi đổi plan, pose robot có thể lệch nhất thời so với plan vừa tới (rõ nhất lúc
|
||
// preempt/đổi chặng). Đo lệch tuyến lúc đó là khai hoả oan.
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.path_monitor.max_cross_track = 0.4; // [m]
|
||
config.path_monitor.grace_after_new_plan = 5.0; // [s] dài hơn hẳn kịch bản
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
fixture.pose_.setPosition(3.0, 5.0); // lệch rất xa
|
||
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, EmptyRouteDisablesTheMonitorInsteadOfAborting)
|
||
{
|
||
// Route rỗng nghĩa là behavior detour không nạp được (hoặc chưa khai). Giám sát mà không có
|
||
// đường xử lý sẽ biến một cơ chế đang tắt thành ABORT ngay lần đầu thấy vật cản — đúng lỗi đã
|
||
// gặp trên sim 2026-08-05. Đúng: không khai hoả, để controller_patience lo như trước.
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.state_machine.recovery_routes.path_blocked.clear();
|
||
config.state_machine.recovery_routes.off_path.clear();
|
||
config.state_machine.recovery_routes.collision.clear();
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
fixture.path_check_.setBlocked(true, 1.5);
|
||
|
||
for (int i = 0; i < 10; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, OffPathRouteEmptyDisablesOnlyThatCheck)
|
||
{
|
||
// Hai phép đo độc lập: thiếu route của cái này không được làm câm cái kia.
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.path_monitor.max_cross_track = 0.4; // [m]
|
||
config.state_machine.recovery_routes.off_path.clear();
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
|
||
// Lệch rất xa nhưng route off_path rỗng -> không khai hoả.
|
||
fixture.pose_.setPosition(3.0, 5.0);
|
||
for (int i = 0; i < 6; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
// Còn path_blocked vẫn còn route thì vẫn phải chạy bình thường.
|
||
fixture.path_check_.setBlocked(true, 1.5);
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
}
|
||
|
||
TEST(WalkingSkeletonPathMonitor, BlockedFreshPlanDoesNotReplaceACleanOne)
|
||
{
|
||
// Luật "không thay plan sạch bằng plan bẩn": không có nó thì planner mù ghi đè đường vòng mỗi
|
||
// nhịp replan nền và robot dừng-detour-chạy-dừng liên tục.
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.planner_frequency = 1000.0; // ép replan nền nổ mỗi cycle
|
||
Fixture fixture(config);
|
||
fixture.planner_.setScript(std::vector<PlannerScript>(20, PlannerScript::kOk));
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(40, ControllerScript::kOk));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
const std::size_t accepted_before = fixture.controller_.setPlanCount();
|
||
|
||
// Plan mới về đều đặn nhưng đều bị chắn -> controller không được nhận thêm plan nào.
|
||
fixture.path_check_.setBlocked(true, 1.5);
|
||
for (int i = 0; i < 3; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
|
||
EXPECT_EQ(fixture.controller_.setPlanCount(), accepted_before);
|
||
}
|
||
|
||
int main(int argc, char** argv)
|
||
{
|
||
testing::InitGoogleTest(&argc, argv);
|
||
return RUN_ALL_TESTS();
|
||
}
|
||
|
||
// =================================================================================================
|
||
// PathMonitor — phép đo 3: thân sắp chạm vật cản thật trên cung lệnh (2026-09-03).
|
||
// =================================================================================================
|
||
namespace
|
||
{
|
||
ControlLoopConfig collisionConfig()
|
||
{
|
||
ControlLoopConfig config = monitorConfig();
|
||
// Chỉ phép đo 3 sống: hai phép đo cũ tắt để chứng minh nó tự giơ được cờ path_blocked một mình.
|
||
config.path_monitor.path_blocked_enabled = false;
|
||
config.path_monitor.off_path_enabled = false;
|
||
config.path_monitor.collision_enabled = true;
|
||
config.path_monitor.collision_lookahead = 0.8; // [m]
|
||
config.path_monitor.collision_stop_distance = 0.35; // [m]
|
||
config.path_monitor.collision_confirm_cycles = 2;
|
||
config.path_monitor.collision_front_offset = 0.58; // [m]
|
||
config.path_monitor.collision_rear_offset = 0.58; // [m]
|
||
config.path_monitor.collision_side_offset = 0.48; // [m]
|
||
config.path_monitor.collision_footprint_padding = 0.1; // [m]
|
||
config.path_monitor.collision_brake_decel = 0.0;
|
||
return config;
|
||
}
|
||
|
||
/// @brief Chỉ Phép đo 4 sống. Cửa sổ/confirm rút ngắn để test chạy vài chục cycle.
|
||
ControlLoopConfig progressConfig(const std::string& action = "recover")
|
||
{
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.path_monitor.path_blocked_enabled = false;
|
||
config.path_monitor.off_path_enabled = false;
|
||
config.path_monitor.collision_enabled = false;
|
||
config.path_monitor.progress_enabled = true;
|
||
config.path_monitor.progress_action = action;
|
||
config.path_monitor.progress_window = 1.0; // [s] = 20 cycle
|
||
config.path_monitor.progress_min_commanded = 0.05; // [m]
|
||
config.path_monitor.progress_min_efficiency = 0.30;
|
||
config.path_monitor.progress_clear_efficiency = 0.60;
|
||
config.path_monitor.progress_confirm_time = 0.3; // [s] = 6 cycle
|
||
config.path_monitor.progress_goal_zone = 0.6; // [m]
|
||
return config;
|
||
}
|
||
|
||
void driveToControlling(Fixture& fixture)
|
||
{
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(60, ControllerScript::kOk));
|
||
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce(); // qua ramp gia tốc của trọng tài để lệnh ổn định
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
}
|
||
} // namespace
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, BrakesImmediatelyThenReplansAfterConfirm)
|
||
{
|
||
Fixture fixture(collisionConfig());
|
||
driveToControlling(fixture);
|
||
|
||
// Chạm trong quãng dừng: lệnh ra bằng 0 NGAY cycle này — trước cả khi cờ được giơ.
|
||
fixture.path_check_.setMotionBlocked(true, 0.2);
|
||
fixture.stepOnce();
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 0.0);
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle 1: chưa đủ xác nhận";
|
||
|
||
// Cycle 2 xác nhận -> cờ path_blocked vào state machine ở cycle 3.
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, HeldByTheGuardAfterTheRouteIsSpentEscalatesToControllingFailed)
|
||
{
|
||
// Run 1 sim 2026-09-04: detour không ra nghiệm (start nằm trong vành 253), route path_blocked cạn,
|
||
// guard giữ lệnh 0 nhưng vẫn báo command_valid -> controller_patience không chạy -> robot đứng
|
||
// chết 20 s không một dòng log. Chuỗi bắt buộc: cạn route -> mute -> guard báo no_valid_command
|
||
// -> controller_patience -> controlling_failed. Guard giữ 0 suốt chuỗi.
|
||
Fixture fixture(collisionConfig());
|
||
driveToControlling(fixture);
|
||
fixture.recovery_.setScript({ RecoveryScript::kFailed });
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.2);
|
||
for (int i = 0; i < 3; ++i)
|
||
{
|
||
fixture.stepOnce(); // phanh, xác nhận, giơ cờ
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
ASSERT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
|
||
|
||
// Behavior tick ở cycle sau khi start, kết quả vào state machine ở cycle sau nữa.
|
||
for (int i = 0; i < 4 && fixture.loop_.state() == NavigationState::kRecovering; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling)
|
||
<< "detour thất bại phải quay về kControlling với route path_blocked đã cạn";
|
||
|
||
bool escalated = false;
|
||
for (int i = 0; i < 40 && !escalated; ++i) // controller_patience 0.5 s = 10 cycle, dư địa rộng
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i;
|
||
escalated = fixture.loop_.state() == NavigationState::kRecovering &&
|
||
fixture.recovery_.lastTrigger() == RecoveryTrigger::kControllingFailed;
|
||
}
|
||
EXPECT_TRUE(escalated) << "guard held the robot but nothing escalated";
|
||
}
|
||
|
||
namespace
|
||
{
|
||
/// @brief P4 (5/9): guard cũ tắt hẳn, kContact của EnvMonitor phanh thật và giơ cờ collision.
|
||
ControlLoopConfig envContactConfig()
|
||
{
|
||
ControlLoopConfig config = monitorConfig();
|
||
config.path_monitor.enabled = false; // guard cũ tắt hẳn: chỉ EnvMonitor phanh
|
||
config.env_monitor.enabled = true;
|
||
config.env_monitor.stall.action = "log";
|
||
config.env_monitor.unreachable.action = "log";
|
||
config.env_monitor.contact.action = "recover";
|
||
config.env_monitor.contact.apply_command = true;
|
||
config.env_monitor.contact.confirm_cycles = 2;
|
||
config.env_monitor.contact.trigger_static_time = 0.3; // [s] = 6 cycle, đủ ngắn cho test
|
||
config.env_monitor.contact.clean_start_margin = 0.2; // [m]
|
||
config.env_sampling.check_period = 0.01; // [s] < chu kỳ 0.05 -> tick nặng mỗi cycle
|
||
return config;
|
||
}
|
||
} // namespace
|
||
|
||
TEST(WalkingSkeletonEnvContact, BrakesAfterConfirmThenRaisesCollisionAfterStaticTime)
|
||
{
|
||
Fixture fixture(envContactConfig());
|
||
driveToControlling(fixture);
|
||
|
||
// Tiếp xúc 0.10 m trên quỹ đạo, trong clean_start_margin: cycle 1 đếm, cycle 2 phanh -> lệnh 0.
|
||
fixture.environment_.setContact(true, 0.10);
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 0.0);
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "phanh nhưng chưa giơ cờ";
|
||
|
||
// Kề mũi đứng yên đủ trigger_static_time -> cờ collision -> route collision.
|
||
int held = 0;
|
||
for (int i = 0; i < 12 && fixture.loop_.state() == NavigationState::kControlling; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i;
|
||
++held;
|
||
}
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
|
||
EXPECT_GE(held, 4) << "cờ phải chờ đủ trigger_static_time, không nổ cùng nhịp với phanh";
|
||
}
|
||
|
||
TEST(WalkingSkeletonEnvContact, HeldWithTheRouteSpentEscalatesToControllingFailed)
|
||
{
|
||
// Cùng chuỗi bắt buộc như guard cũ: cạn route collision -> khoá -> brake giữ 0 nhưng controller
|
||
// phải bị báo no_valid_command -> controller_patience -> controlling_failed. Không có bước này
|
||
// robot đứng chết vô hạn với controller "ổn".
|
||
Fixture fixture(envContactConfig());
|
||
driveToControlling(fixture);
|
||
fixture.recovery_.setScript({ RecoveryScript::kFailed });
|
||
|
||
fixture.environment_.setContact(true, 0.10);
|
||
for (int i = 0; i < 12 && fixture.loop_.state() == NavigationState::kControlling; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
ASSERT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
|
||
|
||
for (int i = 0; i < 4 && fixture.loop_.state() == NavigationState::kRecovering; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling)
|
||
<< "detour thất bại phải quay về kControlling với route collision đã cạn";
|
||
|
||
// onRecoveryFinished xoá chuỗi phanh: tối đa confirm_cycles cycle lệnh có thể khác 0 rồi phanh lại.
|
||
bool escalated = false;
|
||
int nonzero_after_settle = 0;
|
||
for (int i = 0; i < 60 && !escalated; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
if (i >= 3 && fixture.loop_.lastCommand().linear.x != 0.0)
|
||
{
|
||
++nonzero_after_settle;
|
||
}
|
||
escalated = fixture.loop_.state() == NavigationState::kRecovering &&
|
||
fixture.recovery_.lastTrigger() == RecoveryTrigger::kControllingFailed;
|
||
}
|
||
EXPECT_TRUE(escalated) << "EnvMonitor held the robot but nothing escalated";
|
||
EXPECT_EQ(nonzero_after_settle, 0) << "brake must hold once re-confirmed";
|
||
}
|
||
|
||
TEST(WalkingSkeletonEnvContact, ContactBeyondTheStoppingDistanceCapsSpeedWithoutBraking)
|
||
{
|
||
Fixture fixture(envContactConfig());
|
||
driveToControlling(fixture);
|
||
const double v_free = fixture.loop_.lastCommand().linear.x;
|
||
ASSERT_GT(v_free, 0.27);
|
||
|
||
// 2.0 m phía trước: bao sqrt(2·0.35·1.7) = 1.09 m/s > lệnh -> không đổi, không phanh.
|
||
fixture.environment_.setContact(true, 2.0);
|
||
for (int i = 0; i < 6; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, v_free);
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
// 0.40 m: bao sqrt(2·0.35·(0.40 − margin 0.2 − dư 0.1)) = 0.265 m/s. Lệnh bị kẹp xuống đúng bao và GIỮ ở đó:
|
||
// quãng phanh ở tốc độ đã kẹp = 0.10 m -> còn 0.30 m > margin -> không phải "sắp chạm", không phanh, không cờ.
|
||
fixture.environment_.setContact(true, 0.40);
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, std::sqrt(2.0 * 0.35 * 0.10), 1e-3) << "cycle " << i;
|
||
}
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, BodyComesFromTheCostmapFootprintWhenOffsetsAreZero)
|
||
{
|
||
// Ba offset = 0: thân lấy từ footprint costmap qua cổng. Có footprint -> guard dò và dừng như khai
|
||
// tay; hình thân đúng là việc của costmap, không phải của người chép số vào hai file.
|
||
ControlLoopConfig config = collisionConfig();
|
||
config.path_monitor.collision_front_offset = 0.0;
|
||
config.path_monitor.collision_rear_offset = 0.0;
|
||
config.path_monitor.collision_side_offset = 0.0;
|
||
Fixture fixture(config);
|
||
fixture.path_check_.setBodyExtents(0.58, 0.58, 0.48);
|
||
driveToControlling(fixture);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.2);
|
||
fixture.stepOnce();
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, NoBodyGeometryIsInconclusiveNotAStop)
|
||
{
|
||
// Offset = 0 mà cổng không có footprint: guard KHÔNG biết thân ở đâu thì không dừng, không giơ cờ,
|
||
// chỉ kêu lỗi — cùng contract với TF/costmap hỏng. Dừng mù là biến lỗi cấu hình thành robot chết.
|
||
ControlLoopConfig config = collisionConfig();
|
||
config.path_monitor.collision_front_offset = 0.0;
|
||
config.path_monitor.collision_rear_offset = 0.0;
|
||
config.path_monitor.collision_side_offset = 0.0;
|
||
Fixture fixture(config); // fake không setBodyExtents
|
||
driveToControlling(fixture);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.2);
|
||
for (int i = 0; i < 10; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i;
|
||
}
|
||
EXPECT_EQ(fixture.path_check_.motionQueryCount(), 0u); // chưa có thân thì không dò
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, SlowTurnFarFromContactIsCappedNotStopped)
|
||
{
|
||
// Run 16:26: xoay bò v 0.04 ω −0.5 (R 0.08 m), chạm ở 0.15 m cung = quay 1.9 rad, còn 3.8 s.
|
||
// Chưa "sắp" theo thời gian lẫn góc -> không dừng, không recovery, chỉ kẹp v <= (0.15−0.1)/1.0.
|
||
Fixture fixture(collisionConfig()); // padding 0.1, stop_time 1.0, stop_angle 0.35 mặc định
|
||
driveToControlling(fixture);
|
||
fixture.controller_.setNominalSpeed(0.04);
|
||
fixture.controller_.setNominalTurnRate(-0.5);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.15);
|
||
for (int i = 0; i < 10; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
}
|
||
EXPECT_EQ(fixture.recovery_.startCount(), 0u);
|
||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
EXPECT_LE(fixture.loop_.lastCommand().linear.x, 0.05 + 1e-9);
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, -0.5); // guard không đụng omega
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, SlowTurnCloseToContactStops)
|
||
{
|
||
// Cùng cú xoay nhưng chỉ còn 0.02 m cung = 0.25 rad <= stop_angle -> sắp chạm thật -> dừng.
|
||
Fixture fixture(collisionConfig());
|
||
driveToControlling(fixture);
|
||
fixture.controller_.setNominalSpeed(0.04);
|
||
fixture.controller_.setNominalTurnRate(0.5);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.02);
|
||
fixture.stepOnce();
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, StraightCreepStillStops)
|
||
{
|
||
// Bò thẳng 0.05 m/s, chạm ở 0.15 m: 3 s nữa nhưng góc = 0 -> "sắp" theo góc -> dừng như trước.
|
||
Fixture fixture(collisionConfig());
|
||
driveToControlling(fixture);
|
||
fixture.controller_.setNominalSpeed(0.05);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.15);
|
||
fixture.stepOnce();
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, FastCurvedApproachStillStops)
|
||
{
|
||
// Lần nổ 115.1 của run 16:26: v 0.36 ω −0.27, chạm ở 0.20 m = 0.55 s -> sắp theo thời gian.
|
||
Fixture fixture(collisionConfig());
|
||
driveToControlling(fixture);
|
||
fixture.controller_.setNominalSpeed(0.36);
|
||
fixture.controller_.setNominalTurnRate(-0.27);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.20);
|
||
fixture.stepOnce();
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
fixture.stepOnce();
|
||
fixture.stepOnce();
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, ContactBeyondStopDistanceDoesNotStop)
|
||
{
|
||
Fixture fixture(collisionConfig());
|
||
driveToControlling(fixture);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.7); // [m] > stop_distance 0.35
|
||
for (int i = 0; i < 10; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i;
|
||
}
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, CapsSpeedByRemainingDistanceWhenBrakeDecelIsSet)
|
||
{
|
||
ControlLoopConfig config = collisionConfig();
|
||
config.path_monitor.collision_brake_decel = 0.1; // [m/s^2] -> cap sqrt(2*0.1*0.35) = 0.26 m/s
|
||
Fixture fixture(config);
|
||
driveToControlling(fixture);
|
||
const double free_speed = fixture.loop_.lastCommand().linear.x;
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.7);
|
||
for (int i = 0; i < 10; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
const double cap = std::sqrt(2.0 * 0.1 * (0.7 - 0.35));
|
||
EXPECT_LE(fixture.loop_.lastCommand().linear.x, cap + 1e-9);
|
||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
EXPECT_LT(fixture.loop_.lastCommand().linear.x, free_speed);
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, OneCycleFlickerBrakesButDoesNotReplan)
|
||
{
|
||
// Một nhịp costmap nhấp nháy: lệnh 0 đúng một cycle (an toàn), nhưng không kéo recovery ra.
|
||
Fixture fixture(collisionConfig());
|
||
driveToControlling(fixture);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.2);
|
||
fixture.stepOnce();
|
||
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
fixture.path_check_.setMotionBlocked(false);
|
||
for (int i = 0; i < 6; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
}
|
||
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, DisabledFlagLeavesTheCommandAlone)
|
||
{
|
||
ControlLoopConfig config = collisionConfig();
|
||
config.path_monitor.collision_enabled = false;
|
||
Fixture fixture(config);
|
||
driveToControlling(fixture);
|
||
|
||
fixture.path_check_.setMotionBlocked(true, 0.2);
|
||
for (int i = 0; i < 6; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i;
|
||
}
|
||
EXPECT_EQ(fixture.path_check_.motionQueryCount(), 0u);
|
||
}
|
||
|
||
TEST(WalkingSkeletonCollisionGuard, UnknownVerdictNeitherStopsNorClearsTheStreak)
|
||
{
|
||
Fixture fixture(collisionConfig());
|
||
driveToControlling(fixture);
|
||
|
||
fixture.path_check_.setMotionAvailable(false); // thiếu TF/costmap: "không biết"
|
||
fixture.path_check_.setMotionBlocked(true, 0.2);
|
||
for (int i = 0; i < 6; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i;
|
||
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i;
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------------------------
|
||
// Phép đo 4 — "planner đòi đi mà robot không tiến"
|
||
// ---------------------------------------------------------------------------------------------
|
||
|
||
namespace
|
||
{
|
||
/// Pose giả đứng yên tại gốc trong khi controller kOk vẫn phát v > 0 — đúng định nghĩa kẹt.
|
||
void runStalled(Fixture& fixture, int max_cycles)
|
||
{
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(400, ControllerScript::kOk));
|
||
for (int i = 0; i < max_cycles && fixture.loop_.state() == NavigationState::kControlling; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
}
|
||
} // namespace
|
||
|
||
TEST(WalkingSkeletonProgressMonitor, StalledRobotEscalatesToOscillationRecovery)
|
||
{
|
||
Fixture fixture(progressConfig("recover"));
|
||
driveToControlling(fixture);
|
||
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "controller phải đang đòi đi";
|
||
|
||
// Cần: 1 mẫu đủ tuổi window (20 cycle) + confirm 6 cycle + 1 cycle để state machine thấy cờ.
|
||
runStalled(fixture, 60);
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
|
||
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kOscillation);
|
||
}
|
||
|
||
TEST(WalkingSkeletonProgressMonitor, LogModeNeverEscalates)
|
||
{
|
||
Fixture fixture(progressConfig("log"));
|
||
driveToControlling(fixture);
|
||
|
||
runStalled(fixture, 80);
|
||
|
||
// Cùng tình huống kẹt, mode "log" chỉ in cảnh báo: state machine không được thấy cờ.
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonProgressMonitor, NearTheGoalIsNotMeasured)
|
||
{
|
||
Fixture fixture(progressConfig("recover"));
|
||
fixture.planner_.setScript({ PlannerScript::kOk });
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(400, ControllerScript::kOk));
|
||
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
|
||
// Goal cách 0.3 m < progress_goal_zone 0.6 m: dừng chính xác / rot2goal có lệnh nhỏ mà không
|
||
// tiến là hợp lệ, không được coi là kẹt.
|
||
ASSERT_TRUE(submitOk(fixture, makeRequest(0.3)));
|
||
for (int i = 0; i < 8; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
|
||
runStalled(fixture, 80);
|
||
|
||
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
|
||
}
|
||
|
||
TEST(WalkingSkeletonProgressMonitor, ZeroCommandIsWaitingNotStalling)
|
||
{
|
||
Fixture fixture(progressConfig("recover"));
|
||
driveToControlling(fixture);
|
||
|
||
// Controller ngừng ra lệnh (hold chờ người): lệnh sau trọng tài về 0 -> cmd < min_commanded ->
|
||
// KHÔNG đo. Phép đo 4 không được nhầm "chờ" với "kẹt".
|
||
fixture.controller_.setScript(std::vector<ControllerScript>(400, ControllerScript::kFail));
|
||
for (int i = 0; i < 60 && fixture.loop_.state() == NavigationState::kControlling; ++i)
|
||
{
|
||
fixture.stepOnce();
|
||
}
|
||
// Có thể rời kControlling vì controller_patience (kFail) — nhưng KHÔNG phải vì kOscillation.
|
||
EXPECT_NE(fixture.recovery_.lastTrigger(), RecoveryTrigger::kOscillation);
|
||
}
|
||
|