- SensorGateway::pushStaticMap also dispatches to DIRECTIONAL_LAYER on the global costmap, before STATIC_LAYER: with a same-geometry map the directional layer goes PENDING before StaticLayer can report current, so a plan cannot pair the new map with the old zones. - Static maps are replayed in arrival order instead of topic order, so a direction grid is never replayed before its static map. - PlannerRunner checks every enabled global layer under the same lock as the snapshot. While a layer is not current it keeps the goal, reports waiting_for_costmap, logs the stale layers (throttled) and spends no planner_patience or watchdog budget. After costmap_ready_timeout [s] (default 10, 0 = legacy behaviour) the attempt fails as before. The key is added to config/runtime/move_base_common_params.yaml. - Test fixture destroys the server before its fake ports (the control thread could call a destroyed port). Full history: branch feature/direction-zone.
1743 lines
68 KiB
C++
1743 lines
68 KiB
C++
/*********************************************************************
|
|
*
|
|
* Software License Agreement (BSD License)
|
|
*
|
|
* move_base2 — test facade `NavigationServer`: đường lệnh vận tốc ra host, và đường dữ liệu cảm
|
|
* biến từ host vào costmap.
|
|
*
|
|
* Author: DuongTD
|
|
*********************************************************************/
|
|
#include <gtest/gtest.h>
|
|
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
#include <cstddef>
|
|
#include <future>
|
|
#include <limits>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
#include <robot_costmap_2d/layered_costmap.h>
|
|
|
|
#include <move_base2/io/sensor_store_types.h>
|
|
#include <move_base2/navigation_server.h>
|
|
#include <robot_sensor_ports/sensor_reader.h>
|
|
|
|
#include "fake_ports.h"
|
|
#include "spy_layer.h"
|
|
|
|
using move_base2::ControlLoopConfig;
|
|
using move_base2::ControlLoopDeps;
|
|
using move_base2::MotionProfile;
|
|
using move_base2::NavigationRequest;
|
|
using move_base2::NavigationServer;
|
|
using move_base2::NavigationState;
|
|
using move_base2::SensorGatewayConfig;
|
|
using move_base2::testing::attachSpy;
|
|
using move_base2::testing::ControllerScript;
|
|
using move_base2::testing::FakeActionPort;
|
|
using move_base2::testing::FakeClockPort;
|
|
using move_base2::testing::FakeControllerPort;
|
|
using move_base2::testing::FakeMissionPort;
|
|
using move_base2::testing::FakePlannerPort;
|
|
using move_base2::testing::FakePosePort;
|
|
using move_base2::testing::FakeRecoveryPort;
|
|
using move_base2::testing::PlannerScript;
|
|
using move_base2::testing::SpyPtr;
|
|
using robot_costmap_2d::LayerType;
|
|
|
|
namespace
|
|
{
|
|
|
|
constexpr double kControlPeriod = 0.05; ///< [s]
|
|
constexpr double kClockStart = 1000.0; ///< [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 không vướng ramp
|
|
config.velocity.max_accel_theta = 100.0; // [rad/s^2]
|
|
|
|
config.nominal_control_period = kControlPeriod;
|
|
config.robot_base_frame = "base_link";
|
|
|
|
config.position.global_planner_name = "FakeGlobalPlanner";
|
|
config.position.local_planner_name = "FakeLocalPlanner";
|
|
|
|
config.docking = config.position;
|
|
config.go_straight = config.position;
|
|
config.rotate = config.position;
|
|
|
|
return config;
|
|
}
|
|
|
|
NavigationRequest makeRequest(double goal_x)
|
|
{
|
|
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;
|
|
return request;
|
|
}
|
|
|
|
robot_geometry_msgs::Vector3 makeVector(double x, double y = 0.0, double z = 0.0)
|
|
{
|
|
robot_geometry_msgs::Vector3 v;
|
|
v.x = x;
|
|
v.y = y;
|
|
v.z = z;
|
|
return v;
|
|
}
|
|
|
|
robot_nav_msgs::Odometry makeOdometry(double vx, double wz)
|
|
{
|
|
robot_nav_msgs::Odometry odom;
|
|
odom.header.frame_id = "odom";
|
|
odom.twist.twist.linear.x = vx; // [m/s]
|
|
odom.twist.twist.angular.z = wz; // [rad/s]
|
|
return odom;
|
|
}
|
|
|
|
robot_sensor_msgs::LaserScan makeScan(std::size_t rays = 40, float range = 1.0F)
|
|
{
|
|
robot_sensor_msgs::LaserScan scan;
|
|
scan.header.frame_id = "laser";
|
|
scan.angle_min = -1.5F; // [rad]
|
|
scan.angle_max = 1.5F; // [rad]
|
|
scan.angle_increment = 3.0F / static_cast<float>(rays); // [rad]
|
|
scan.range_min = 0.05F; // [m]
|
|
scan.range_max = 10.0F; // [m]
|
|
scan.ranges.assign(rays, range);
|
|
return scan;
|
|
}
|
|
|
|
/**
|
|
* @class Fixture
|
|
* @brief `NavigationServer` nối đủ cổng giả, cộng hai costmap thật để kiểm đường cảm biến.
|
|
*/
|
|
class Fixture
|
|
{
|
|
public:
|
|
Fixture()
|
|
: clock_(kClockStart)
|
|
, recovery_(2)
|
|
, global_("map", false, true)
|
|
, local_("odom", true, false)
|
|
{
|
|
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_.components = &components_;
|
|
planner_.attachStatusBoard(&components_);
|
|
recovery_.attachStatusBoard(&components_);
|
|
action_.attachStatusBoard(&components_);
|
|
}
|
|
|
|
void configure(const ControlLoopConfig& config = baseConfig())
|
|
{
|
|
std::string error;
|
|
ASSERT_TRUE(server_.configureLoop(config, deps_, error)) << error;
|
|
}
|
|
|
|
void configureSensors(const SensorGatewayConfig& config)
|
|
{
|
|
std::string error;
|
|
ASSERT_TRUE(server_.configureSensors(config, error)) << error;
|
|
}
|
|
|
|
/// @brief Khai một topic laser trong kho cảm biến thô.
|
|
void configureSensorStore(const std::string& topic = "/b_scan", std::size_t capacity = 1)
|
|
{
|
|
robot_sensor_ports::SensorStoreConfig config;
|
|
robot_sensor_ports::SensorEntryConfig entry;
|
|
entry.topic = topic;
|
|
entry.data_type = "robot_sensor_msgs/LaserScan";
|
|
entry.capacity = capacity;
|
|
entry.max_age = 0.5; // [s]
|
|
config.sensors.push_back(entry);
|
|
|
|
std::string error;
|
|
ASSERT_TRUE(server_.configureSensorStore(config, error)) << error;
|
|
}
|
|
|
|
/// @brief Chạy @p cycles control cycle, mỗi cycle nhích đồng hồ giả một chu kỳ.
|
|
void spin(std::size_t cycles)
|
|
{
|
|
for (std::size_t i = 0; i < cycles; ++i)
|
|
{
|
|
server_.spinOnce();
|
|
clock_.advance(kControlPeriod);
|
|
}
|
|
}
|
|
|
|
void attachCostmaps()
|
|
{
|
|
server_.attachCostmaps(&global_, &local_);
|
|
}
|
|
|
|
FakeClockPort clock_;
|
|
FakePosePort pose_;
|
|
FakePlannerPort planner_;
|
|
FakeControllerPort controller_;
|
|
FakeRecoveryPort recovery_;
|
|
FakeMissionPort mission_;
|
|
FakeActionPort action_;
|
|
move_base2::ComponentStatusBoard components_;
|
|
ControlLoopDeps deps_;
|
|
|
|
robot_costmap_2d::LayeredCostmap global_;
|
|
robot_costmap_2d::LayeredCostmap local_;
|
|
|
|
// The server joins its control thread in its destructor. Declare it last so all borrowed
|
|
// ports, status data and costmaps outlive that join.
|
|
NavigationServer server_;
|
|
};
|
|
|
|
} // namespace
|
|
|
|
// ================================================================================================
|
|
// getTwist() — LỆNH vận tốc, không phải vận tốc đo được
|
|
//
|
|
// Host lấy getTwist() rồi publish thẳng ra /cmd_vel. Nếu giá trị đó đến từ odometry thì có một vòng
|
|
// lặp dương: robot chạy 0.5 m/s -> đọc odom 0.5 -> phát lệnh 0.5 -> mãi mãi. VelocityArbiter — toàn
|
|
// bộ hàng rào an toàn của gói — cũng bị bỏ qua hoàn toàn. Các test dưới đây khoá lại điều đó.
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerTwist, ReturnsArbiterCommandNotOdometryVelocity)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setNominalSpeed(0.3); // [m/s]
|
|
fixture.controller_.setScript({ ControllerScript::kOk, ControllerScript::kOk });
|
|
|
|
// Odometry báo robot đang chạy nhanh hơn hẳn lệnh mà controller muốn phát.
|
|
fixture.server_.addOdometry("/odom", makeOdometry(1.7, 0.9));
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
|
|
fixture.spin(2); // IDLE -> PLANNING -> CONTROLLING (controller chạy ngay ở cycle này)
|
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kControlling);
|
|
|
|
const robot_nav_2d_msgs::Twist2DStamped twist = fixture.server_.getTwist();
|
|
EXPECT_NEAR(twist.velocity.x, 0.3, 1e-9) << "getTwist returned the measured velocity instead of "
|
|
"the command that was published";
|
|
EXPECT_NEAR(twist.velocity.theta, 0.0, 1e-9);
|
|
}
|
|
|
|
TEST(NavigationServerTwist, OdometryAloneNeverProducesACommand)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.server_.addOdometry("/odom", makeOdometry(1.7, 0.9));
|
|
fixture.spin(1); // IDLE, không có yêu cầu nào
|
|
|
|
const robot_nav_2d_msgs::Twist2DStamped twist = fixture.server_.getTwist();
|
|
EXPECT_NEAR(twist.velocity.x, 0.0, 1e-9);
|
|
EXPECT_NEAR(twist.velocity.y, 0.0, 1e-9);
|
|
EXPECT_NEAR(twist.velocity.theta, 0.0, 1e-9);
|
|
}
|
|
|
|
TEST(NavigationServerTwist, StampComesFromTheControlLoopClockNotWallClock)
|
|
{
|
|
// Host loại lệnh quá hạn theo dấu này. Lấy giờ hệ thống lúc host hỏi sẽ làm một control loop đã
|
|
// treo vẫn trông như đang phát lệnh tươi — đúng thứ dấu thời gian sinh ra để ngăn.
|
|
// Stamp chỉ tiến khi đang có yêu cầu (xem test StampFreezesWhenIdle...), nên phải có goal chạy.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setNominalSpeed(0.3); // [m/s]
|
|
fixture.controller_.setScript({ ControllerScript::kOk, ControllerScript::kOk });
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
|
|
fixture.spin(1);
|
|
EXPECT_NEAR(fixture.server_.getTwist().header.stamp.toSec(), kClockStart, 1e-9);
|
|
|
|
fixture.clock_.setTime(kClockStart + 12.0);
|
|
fixture.spin(1);
|
|
EXPECT_NEAR(fixture.server_.getTwist().header.stamp.toSec(), kClockStart + 12.0, 1e-9);
|
|
}
|
|
|
|
TEST(NavigationServerTwist, StampFreezesWhenIdleSoTeleopOwnsCmdVel)
|
|
{
|
|
// Không có yêu cầu nào thì stamp phải ĐỨNG YÊN dù control loop vẫn chạy: host publish /cmd_vel
|
|
// qua cửa tươi 0.05 s (amr_publiser.cpp:361), stamp tươi mỗi cycle nghĩa là amr_node phát 0 ở
|
|
// 20 Hz vĩnh viễn và đè chết teleop/joystick (rqt_robot_steering 10 Hz — robot chỉ nhích rồi
|
|
// đứng im). Bản cũ chỉ đóng dấu trong executeCycle; đây là regression đã gặp trên sim.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.spin(3);
|
|
EXPECT_TRUE(fixture.server_.getTwist().header.stamp.isZero())
|
|
<< "no request has ever arrived yet the stamp is fresh — the host would publish 0 over "
|
|
"teleop";
|
|
}
|
|
|
|
TEST(NavigationServerTwist, StampKeepsFreshBrieflyAfterGoalEndsThenFreezes)
|
|
{
|
|
// Lệnh 0 cuối cùng phải qua được cửa 0.05 s của host — kết thúc mà đóng băng stamp ngay thì
|
|
// robot giữ nguyên vận tốc chót. Cửa ân hạn 0.5 s; hết ân hạn stamp phải đứng yên trả /cmd_vel
|
|
// cho teleop.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setNominalSpeed(0.3); // [m/s]
|
|
fixture.controller_.setScript({ ControllerScript::kOk, ControllerScript::kGoalReached });
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
|
|
fixture.spin(4); // IDLE -> PLANNING -> CONTROLLING -> tới đích (terminal)
|
|
ASSERT_FALSE(fixture.server_.loop().hasActiveRequest());
|
|
|
|
// Ngay sau khi kết thúc: còn trong ân hạn, stamp vẫn tiến để host phát lệnh dừng.
|
|
const double stamp_in_grace = fixture.server_.getTwist().header.stamp.toSec();
|
|
fixture.spin(1);
|
|
EXPECT_GT(fixture.server_.getTwist().header.stamp.toSec(), stamp_in_grace)
|
|
<< "the stamp freezes as soon as the leg ends — the final stop command would never be "
|
|
"published";
|
|
|
|
// Chạy qua hết cửa ân hạn (0.5 s = 10 cycle) rồi thêm vài cycle: stamp phải đứng yên.
|
|
fixture.spin(12);
|
|
const double stamp_frozen = fixture.server_.getTwist().header.stamp.toSec();
|
|
fixture.spin(3);
|
|
EXPECT_NEAR(fixture.server_.getTwist().header.stamp.toSec(), stamp_frozen, 1e-9)
|
|
<< "the grace period is over yet the stamp is still fresh — teleop would never get /cmd_vel "
|
|
"back";
|
|
}
|
|
|
|
TEST(NavigationServerTwist, StampStaysStillWhenTheControlLoopStopsRunning)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.spin(1);
|
|
const double stamp_after_first = fixture.server_.getTwist().header.stamp.toSec();
|
|
|
|
// Đồng hồ chạy tiếp nhưng KHÔNG có cycle nào — mô phỏng control thread treo.
|
|
fixture.clock_.setTime(kClockStart + 30.0);
|
|
fixture.server_.addOdometry("/odom", makeOdometry(1.7, 0.0));
|
|
|
|
EXPECT_NEAR(fixture.server_.getTwist().header.stamp.toSec(), stamp_after_first, 1e-9)
|
|
<< "the timestamp refreshes itself although the control loop is not running — the host would "
|
|
"think the command is still valid";
|
|
}
|
|
|
|
TEST(NavigationServerTwist, IsStampedWithTheConfiguredRobotBaseFrame)
|
|
{
|
|
ControlLoopConfig config = baseConfig();
|
|
config.robot_base_frame = "base_footprint";
|
|
|
|
Fixture fixture;
|
|
fixture.configure(config);
|
|
fixture.spin(1);
|
|
|
|
EXPECT_EQ(fixture.server_.getTwist().header.frame_id, "base_footprint");
|
|
}
|
|
|
|
TEST(NavigationServerTwist, ConfigureIsRefusedWhenRobotBaseFrameIsEmpty)
|
|
{
|
|
ControlLoopConfig config = baseConfig();
|
|
config.robot_base_frame.clear();
|
|
|
|
Fixture fixture;
|
|
std::string error;
|
|
EXPECT_FALSE(fixture.server_.configureLoop(config, fixture.deps_, error));
|
|
EXPECT_FALSE(error.empty());
|
|
}
|
|
|
|
// ================================================================================================
|
|
// Đường dữ liệu cảm biến từ host vào costmap
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerSensors, SamplesReachTheCostmapLayersOnceAttached)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
SpyPtr static_layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "navigation_map");
|
|
SpyPtr local_voxel = attachSpy(fixture.local_, LayerType::VOXEL_LAYER, "obstacles");
|
|
fixture.attachCostmaps();
|
|
|
|
fixture.server_.addStaticMap("/map", robot_nav_msgs::OccupancyGrid());
|
|
fixture.server_.addLaserScan("/b_scan", makeScan());
|
|
fixture.server_.addPointCloud2("/camera/depth/points_proc", robot_sensor_msgs::PointCloud2());
|
|
|
|
EXPECT_EQ(static_layer->count(), 1U);
|
|
EXPECT_EQ(local_voxel->count(), 2U) << "laser + pointcloud2 must both reach the VoxelLayer";
|
|
EXPECT_EQ(local_voxel->records()[0].topic, "/b_scan");
|
|
EXPECT_EQ(local_voxel->records()[1].topic, "/camera/depth/points_proc");
|
|
}
|
|
|
|
TEST(NavigationServerSensors, StoringStillWorksWhenNoCostmapIsAttachedYet)
|
|
{
|
|
// Trạng thái bình thường lúc khởi động: host đã bắt đầu bơm dữ liệu trước khi costmap được dựng.
|
|
// Dữ liệu vẫn phải đọc lại được qua getter của contract host, và số mẫu mất phải đếm được.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.server_.addLaserScan("/b_scan", makeScan());
|
|
|
|
EXPECT_EQ(fixture.server_.getLaserScan("/b_scan").ranges.size(), 40U);
|
|
EXPECT_EQ(fixture.server_.sensors().stats().dropped_no_costmap, 1U);
|
|
EXPECT_EQ(fixture.server_.sensors().stats().delivered, 0U);
|
|
}
|
|
|
|
// ================================================================================================
|
|
// Đường dữ liệu cảm biến THÔ từ host vào kho dùng chung
|
|
//
|
|
// Kho là đường thứ hai, song song với costmap: bộ dò dock và local planner học tăng cường cần đúng
|
|
// mảng `ranges` theo thứ tự tia, thứ mà costmap ở 0.05 m đã inflate và xoá mất.
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerSensorStore, ADeclaredTopicReachesTheStore)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensorStore();
|
|
|
|
fixture.server_.addLaserScan("/b_scan", makeScan(40, 1.0F));
|
|
|
|
uint64_t cursor = 0;
|
|
auto scan = robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(fixture.server_.sensorStore(),
|
|
"/b_scan", cursor);
|
|
ASSERT_TRUE(scan);
|
|
EXPECT_EQ(scan->ranges.size(), 40U);
|
|
EXPECT_FLOAT_EQ(scan->ranges[0], 1.0F);
|
|
|
|
// Cursor đã nhích: lần đọc kế tiếp phải nói "chưa có gì mới", không đưa lại đúng scan đó.
|
|
EXPECT_FALSE(robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(fixture.server_.sensorStore(),
|
|
"/b_scan", cursor));
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, TheStoreGetsTheRawScanWhileTheCostmapGetsTheFilteredOne)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
// SOR bật: bản vào costmap có outlier bị đặt NaN, bản vào kho thì không.
|
|
SensorGatewayConfig sensors;
|
|
sensors.laser_sor_enabled = true;
|
|
sensors.laser_sor_mean_k = 4;
|
|
sensors.laser_sor_stddev_mul = 0.5;
|
|
fixture.configureSensors(sensors);
|
|
fixture.configureSensorStore();
|
|
|
|
// Một tia lạc hẳn ra giữa một bức tường phẳng — đúng thứ SOR sinh ra để loại.
|
|
robot_sensor_msgs::LaserScan scan = makeScan(40, 1.0F);
|
|
scan.ranges[20] = 8.0F;
|
|
fixture.server_.addLaserScan("/b_scan", scan);
|
|
|
|
uint64_t cursor = 0;
|
|
auto stored = robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(
|
|
fixture.server_.sensorStore(), "/b_scan", cursor);
|
|
ASSERT_TRUE(stored);
|
|
|
|
// Kho giữ đúng thứ laser đã thấy. Đây là điều kiện sống của bộ dò hình dạng: fit đường thẳng trên
|
|
// dữ liệu đã bị lọc là fit trên một hình khác.
|
|
EXPECT_FLOAT_EQ(stored->ranges[20], 8.0F);
|
|
|
|
// Còn bản costmap nhìn thấy thì đã bị lọc. Hai bản khác nhau là CÓ CHỦ ĐÍCH.
|
|
const robot_sensor_msgs::LaserScan filtered = fixture.server_.getLaserScan("/b_scan");
|
|
ASSERT_EQ(filtered.ranges.size(), 40U);
|
|
EXPECT_TRUE(std::isnan(filtered.ranges[20]))
|
|
<< "SOR phải loại tia lạc; nếu không, test này không còn phân biệt được hai đường";
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, AnUndeclaredTopicIsDroppedInsteadOfGrowingTheStore)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensorStore("/b_scan");
|
|
|
|
fixture.server_.addLaserScan("/f_scan", makeScan());
|
|
|
|
// Không tự thêm slot: một depth cloud không ai khai sẽ ngốn hàng MB mỗi frame.
|
|
EXPECT_FALSE(robot_sensor_ports::has<robot_sensor_msgs::LaserScan>(fixture.server_.sensorStore(),
|
|
"/f_scan"));
|
|
// Nhưng đường cũ vẫn nhận, không đổi hành vi host đang có.
|
|
EXPECT_EQ(fixture.server_.getLaserScan("/f_scan").ranges.size(), 40U);
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, RemovingATopicMakesTheStoreForgetItToo)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensorStore();
|
|
|
|
fixture.server_.addLaserScan("/b_scan", makeScan());
|
|
ASSERT_TRUE(fixture.server_.removeLaserScan("/b_scan"));
|
|
|
|
// Host đã bỏ dữ liệu đó; kho còn phát bản cũ là hai nguồn nói hai chuyện khác nhau về thứ robot
|
|
// đang nhìn thấy.
|
|
uint64_t cursor = 0;
|
|
EXPECT_FALSE(robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(fixture.server_.sensorStore(),
|
|
"/b_scan", cursor));
|
|
|
|
// Khai báo thì vẫn còn — bỏ dữ liệu không phải bỏ cấu hình.
|
|
EXPECT_TRUE(robot_sensor_ports::has<robot_sensor_msgs::LaserScan>(fixture.server_.sensorStore(),
|
|
"/b_scan"));
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, RemoveAllLaserScansClearsEveryLaserTopic)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensorStore();
|
|
|
|
fixture.server_.addLaserScan("/b_scan", makeScan());
|
|
ASSERT_TRUE(fixture.server_.removeAllLaserScans());
|
|
|
|
uint64_t cursor = 0;
|
|
EXPECT_FALSE(robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(fixture.server_.sensorStore(),
|
|
"/b_scan", cursor));
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, KeepsAFrameStackWhenCapacityAllowsIt)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensorStore("/b_scan", 3);
|
|
|
|
for (int i = 1; i <= 4; ++i)
|
|
{
|
|
fixture.server_.addLaserScan("/b_scan", makeScan(40, static_cast<float>(i)));
|
|
}
|
|
|
|
const auto frames = robot_sensor_ports::history<robot_sensor_msgs::LaserScan>(
|
|
fixture.server_.sensorStore(), "/b_scan", 3);
|
|
ASSERT_EQ(frames.size(), 3U);
|
|
// Cũ trước, mới sau.
|
|
EXPECT_FLOAT_EQ(frames[0]->ranges[0], 2.0F);
|
|
EXPECT_FLOAT_EQ(frames[2]->ranges[0], 4.0F);
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, TheReportIsOffUntilAskedFor)
|
|
{
|
|
// Mặc định tắt: đây là công cụ chẩn đoán, không phải thứ in trên robot sản xuất. Chỉ kiểm là
|
|
// spinOnce() không nổ khi chưa bật và khi chưa có đồng hồ.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensorStore();
|
|
|
|
fixture.server_.addLaserScan("/b_scan", makeScan());
|
|
fixture.spin(3);
|
|
SUCCEED();
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, TheReportSurvivesATopicThatNeverReceivedAnything)
|
|
{
|
|
// Ca đáng nói nhất khi chưa có consumer nào: gõ sai `topic` và cảm biến chết cho CÙNG một triệu
|
|
// chứng. Báo cáo phải chạy được qua topic rỗng thay vì bỏ qua vì "không có gì để in".
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensorStore();
|
|
fixture.server_.setSensorStoreReportPeriod(0.01); // [s]
|
|
|
|
fixture.spin(5);
|
|
|
|
robot_sensor_ports::SensorInfo info;
|
|
ASSERT_TRUE(fixture.server_.sensorStore().describe("/b_scan", info));
|
|
EXPECT_EQ(info.sequence, 0U);
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, TheReportMeasuresRateAndAgeOfWhatArrived)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensorStore();
|
|
fixture.server_.setSensorStoreReportPeriod(0.01); // [s]
|
|
|
|
// 10 Hz theo stamp, độc lập với đồng hồ control loop.
|
|
for (int i = 0; i < 6; ++i)
|
|
{
|
|
robot_sensor_msgs::LaserScan scan = makeScan();
|
|
scan.header.stamp = robot::Time(100.0 + 0.1 * i);
|
|
fixture.server_.addLaserScan("/b_scan", scan);
|
|
}
|
|
fixture.spin(3);
|
|
|
|
robot_sensor_ports::SensorInfo info;
|
|
ASSERT_TRUE(fixture.server_.sensorStore().describe("/b_scan", info));
|
|
EXPECT_EQ(info.sequence, 6U);
|
|
EXPECT_NEAR(info.rate_hz, 10.0, 1.0);
|
|
EXPECT_DOUBLE_EQ(info.stamp.toSec(), 100.5);
|
|
}
|
|
|
|
TEST(NavigationServerSensorStore, RegisteringTheRuntimeOwnTypeMakesItNameableInYaml)
|
|
{
|
|
// OccupancyGrid thuộc robot_nav_msgs, không nằm trong danh sách sẵn có của robot_sensor_ports.
|
|
// Đây chính là đường mở rộng: một dòng REGISTER_TYPE + một lời gọi add(), không đổi interface.
|
|
move_base2::registerSensorStoreTypes();
|
|
|
|
std::string full;
|
|
std::string error;
|
|
ASSERT_TRUE(robot_sensor_ports::TypeNames::resolve("OccupancyGrid", full, error)) << error;
|
|
EXPECT_EQ(full, "robot_nav_msgs/OccupancyGrid");
|
|
}
|
|
|
|
TEST(NavigationServerSensors, StaticMapReceivedBeforeAttachIsReplayed)
|
|
{
|
|
// Không có phần phát lại này thì thứ tự "map tới trước, costmap dựng sau" — thứ tự thường gặp
|
|
// nhất khi khởi động — để global costmap trắng vĩnh viễn: /map là topic latched, host không gửi
|
|
// lại. Bản cũ bù bằng cặp biến public map_save_/map_name_save_.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.server_.addStaticMap("/map", robot_nav_msgs::OccupancyGrid());
|
|
ASSERT_EQ(fixture.server_.sensors().stats().dropped_no_costmap, 1U);
|
|
|
|
SpyPtr static_layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "navigation_map");
|
|
fixture.attachCostmaps();
|
|
|
|
ASSERT_EQ(static_layer->count(), 1U) << "a static map received before a costmap was attached "
|
|
"must not be replayed";
|
|
EXPECT_EQ(static_layer->records()[0].topic, "/map");
|
|
}
|
|
|
|
TEST(CostmapReadyDecision, ReadyWaitTimeoutAndLegacy)
|
|
{
|
|
using move_base2::CostmapReadyDecision;
|
|
using move_base2::costmapReadyDecision;
|
|
EXPECT_EQ(costmapReadyDecision(false, 0.0, 10.0), CostmapReadyDecision::kWait);
|
|
EXPECT_EQ(costmapReadyDecision(false, 9.99, 10.0), CostmapReadyDecision::kWait);
|
|
EXPECT_EQ(costmapReadyDecision(false, 10.0, 10.0), CostmapReadyDecision::kTimeout);
|
|
EXPECT_EQ(costmapReadyDecision(true, 3.0, 10.0), CostmapReadyDecision::kPlan);
|
|
EXPECT_EQ(costmapReadyDecision(false, 0.0, 0.0), CostmapReadyDecision::kPlan);
|
|
}
|
|
|
|
TEST(NavigationServerSensors, ReplayUsesLatestArrivalOrder)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
const robot_nav_msgs::OccupancyGrid grid;
|
|
fixture.server_.addStaticMap("/map", grid);
|
|
fixture.server_.addStaticMap("/direction_map", grid);
|
|
|
|
SpyPtr layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "replay_spy");
|
|
fixture.attachCostmaps();
|
|
ASSERT_EQ(layer->count(), 2U);
|
|
EXPECT_EQ(layer->records()[0].topic, "/map");
|
|
EXPECT_EQ(layer->records()[1].topic, "/direction_map");
|
|
|
|
// The live pushes are followed by a second replay after both latest arrivals.
|
|
fixture.server_.addStaticMap("/map", grid);
|
|
fixture.server_.addStaticMap("/direction_map", grid);
|
|
fixture.attachCostmaps();
|
|
ASSERT_EQ(layer->count(), 6U);
|
|
EXPECT_EQ(layer->records()[4].topic, "/map");
|
|
EXPECT_EQ(layer->records()[5].topic, "/direction_map");
|
|
}
|
|
|
|
TEST(NavigationServerSensors, ReplayForgetsErasedAndClearedSequences)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
const robot_nav_msgs::OccupancyGrid grid;
|
|
fixture.server_.addStaticMap("/map", grid);
|
|
fixture.server_.addStaticMap("/direction_map", grid);
|
|
ASSERT_TRUE(fixture.server_.removeStaticMap("/map"));
|
|
fixture.server_.addStaticMap("/map", grid);
|
|
SpyPtr layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "replay_spy");
|
|
fixture.attachCostmaps();
|
|
ASSERT_EQ(layer->count(), 2U);
|
|
EXPECT_EQ(layer->records()[0].topic, "/direction_map");
|
|
EXPECT_EQ(layer->records()[1].topic, "/map");
|
|
|
|
ASSERT_TRUE(fixture.server_.removeAllStaticMaps());
|
|
fixture.server_.addStaticMap("/direction_map", grid);
|
|
const std::size_t before_clear_replay = layer->count();
|
|
fixture.attachCostmaps();
|
|
ASSERT_EQ(layer->count(), before_clear_replay + 1U);
|
|
EXPECT_EQ(layer->records()[before_clear_replay].topic, "/direction_map");
|
|
ASSERT_TRUE(fixture.server_.removeAllData());
|
|
fixture.server_.addStaticMap("/map", grid);
|
|
fixture.server_.addStaticMap("/direction_map", grid);
|
|
fixture.server_.map_name_save_ = "/legacy";
|
|
|
|
const std::size_t before_replay = layer->count();
|
|
fixture.attachCostmaps();
|
|
ASSERT_EQ(layer->count(), before_replay + 3U);
|
|
EXPECT_EQ(layer->records()[before_replay].topic, "/legacy");
|
|
EXPECT_EQ(layer->records()[before_replay + 1].topic, "/map");
|
|
EXPECT_EQ(layer->records()[before_replay + 2].topic, "/direction_map");
|
|
}
|
|
|
|
TEST(NavigationServerSensors, LegacyMapSavePublicMemberIsAlsoReplayed)
|
|
{
|
|
// `map_save_`/`map_name_save_` là biến PUBLIC của BaseNavigation mà host tự gán
|
|
// (sensor_converter.cpp). Giữ đường này để host không phải sửa gì khi đổi sang move_base2.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.server_.map_name_save_ = "/map";
|
|
fixture.server_.map_save_ = robot_nav_msgs::OccupancyGrid();
|
|
|
|
SpyPtr static_layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "navigation_map");
|
|
fixture.attachCostmaps();
|
|
|
|
EXPECT_EQ(static_layer->count(), 1U);
|
|
EXPECT_EQ(static_layer->records()[0].topic, "/map");
|
|
}
|
|
|
|
TEST(NavigationServerSensors, ReplayDoesNotDuplicateAMapAlreadyReceivedThroughTheApi)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.server_.addStaticMap("/map", robot_nav_msgs::OccupancyGrid());
|
|
fixture.server_.map_name_save_ = "/map"; // host gán cả hai đường, như bản cũ đang làm
|
|
fixture.server_.map_save_ = robot_nav_msgs::OccupancyGrid();
|
|
|
|
SpyPtr static_layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "navigation_map");
|
|
fixture.attachCostmaps();
|
|
|
|
EXPECT_EQ(static_layer->count(), 1U) << "the same map was replayed twice";
|
|
}
|
|
|
|
TEST(NavigationServerSensors, StaleLaserScansAreNotReplayedOnAttach)
|
|
{
|
|
// Cố ý: phát lại một scan cũ là dựng vật cản ở chỗ robot có thể đã rời khỏi từ lâu. Mẫu kế tiếp
|
|
// chỉ cách vài chục ms — chờ nó an toàn hơn hẳn.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.server_.addLaserScan("/b_scan", makeScan());
|
|
|
|
SpyPtr voxel = attachSpy(fixture.local_, LayerType::VOXEL_LAYER, "obstacles");
|
|
fixture.attachCostmaps();
|
|
|
|
EXPECT_EQ(voxel->count(), 0U);
|
|
}
|
|
|
|
TEST(NavigationServerSensors, StoredLaserScanIsTheSameOneHandedToTheCostmap)
|
|
{
|
|
// Bản cũ cất bản ĐÃ LỌC. Nếu getter trả bản thô còn costmap thấy bản lọc thì hai nguồn sự thật
|
|
// lệch nhau, và mọi chẩn đoán dựa trên getter sẽ nói dối về thứ costmap thật sự dùng.
|
|
SensorGatewayConfig sensors;
|
|
sensors.laser_sor_enabled = true;
|
|
sensors.laser_sor_mean_k = 5;
|
|
sensors.laser_sor_stddev_mul = 1.0;
|
|
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.configureSensors(sensors);
|
|
|
|
std::vector<float> seen_by_layer;
|
|
SpyPtr voxel = attachSpy(fixture.local_, LayerType::VOXEL_LAYER, "obstacles");
|
|
voxel->setObserver([&seen_by_layer](const void* data, const std::type_info& type,
|
|
const std::string&) {
|
|
if (type == typeid(robot_sensor_msgs::LaserScan))
|
|
{
|
|
seen_by_layer = static_cast<const robot_sensor_msgs::LaserScan*>(data)->ranges;
|
|
}
|
|
});
|
|
fixture.attachCostmaps();
|
|
|
|
fixture.server_.addLaserScan("/b_scan", makeScan());
|
|
|
|
const std::vector<float> stored = fixture.server_.getLaserScan("/b_scan").ranges;
|
|
ASSERT_FALSE(seen_by_layer.empty());
|
|
ASSERT_EQ(stored.size(), seen_by_layer.size());
|
|
|
|
// So từng phần tử chứ không so cả vector: bộ lọc biến outlier thành NaN để giữ nguyên cấu trúc
|
|
// scan, mà NaN != NaN nên operator== của vector sẽ báo khác nhau dù nội dung giống hệt.
|
|
for (std::size_t i = 0; i < stored.size(); ++i)
|
|
{
|
|
if (std::isnan(stored[i]))
|
|
{
|
|
EXPECT_TRUE(std::isnan(seen_by_layer[i])) << "mismatch at ray " << i;
|
|
}
|
|
else
|
|
{
|
|
EXPECT_FLOAT_EQ(stored[i], seen_by_layer[i]) << "mismatch at ray " << i;
|
|
}
|
|
}
|
|
}
|
|
|
|
TEST(NavigationServerSensors, DepthCameraDataIsStoredAndForwardedAsConstPtr)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
SpyPtr voxel = attachSpy(fixture.local_, LayerType::VOXEL_LAYER, "obstacles");
|
|
fixture.attachCostmaps();
|
|
|
|
robot_sensor_msgs::DepthCameraData::Ptr data =
|
|
boost::make_shared<robot_sensor_msgs::DepthCameraData>();
|
|
data->header.frame_id = "camera_optical";
|
|
fixture.server_.addDepthCameraData("/camera/depth/data", data);
|
|
|
|
ASSERT_EQ(voxel->count(), 1U);
|
|
EXPECT_TRUE(*voxel->records()[0].type == typeid(robot_sensor_msgs::DepthCameraData::ConstPtr));
|
|
EXPECT_EQ(voxel->records()[0].topic, "/camera/depth/data");
|
|
}
|
|
|
|
TEST(NavigationServerSensors, NullDepthPointerIsRejectedAtTheDoor)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
SpyPtr voxel = attachSpy(fixture.local_, LayerType::VOXEL_LAYER, "obstacles");
|
|
fixture.attachCostmaps();
|
|
|
|
fixture.server_.addDepthCameraData("/camera/depth/data",
|
|
robot_sensor_msgs::DepthCameraData::ConstPtr());
|
|
|
|
EXPECT_EQ(voxel->count(), 0U);
|
|
EXPECT_EQ(fixture.server_.sensors().stats().dropped_no_costmap, 0U);
|
|
}
|
|
|
|
// ================================================================================================
|
|
// Trần vận tốc (bước 12) — đường tầng an toàn hạ tốc độ robot
|
|
//
|
|
// `setTwistLinear` không phải lệnh jog dù tên nghe như vậy: host gọi nó theo cặp +v/-v để đặt trần
|
|
// cho hai chiều, và giá trị truyền xuống mang theo tốc độ đã bị tầng an toàn hạ
|
|
// (amr_control.cpp:561, 671-680). Trước đây `NavigationServer` trả false và không làm gì.
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerLimits, ForwardAndBackwardLimitsReachTheController)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
EXPECT_TRUE(fixture.server_.setTwistLinear(makeVector(0.30))); // [m/s] trần tiến
|
|
EXPECT_TRUE(fixture.server_.setTwistLinear(makeVector(-0.15))); // [m/s] trần lùi, ÂM
|
|
|
|
fixture.spin(1);
|
|
|
|
EXPECT_NEAR(fixture.controller_.limitForward(), 0.30, 1e-9);
|
|
EXPECT_NEAR(fixture.controller_.limitBackward(), -0.15, 1e-9);
|
|
}
|
|
|
|
TEST(NavigationServerLimits, AngularLimitReachesTheController)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
EXPECT_TRUE(fixture.server_.setTwistAngular(makeVector(0.0, 0.0, 0.45))); // [rad/s]
|
|
fixture.spin(1);
|
|
|
|
EXPECT_NEAR(fixture.controller_.limitAngular(), 0.45, 1e-9);
|
|
}
|
|
|
|
TEST(NavigationServerLimits, LimitTakesEffectInTheSameCycleItIsPushed)
|
|
{
|
|
// Chậm một cycle nghĩa là một chu kỳ nữa robot chạy quá tốc độ mà tầng an toàn vừa yêu cầu hạ.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
ASSERT_TRUE(fixture.server_.setTwistLinear(makeVector(0.12)));
|
|
fixture.spin(1);
|
|
EXPECT_NEAR(fixture.controller_.limitForward(), 0.12, 1e-9);
|
|
}
|
|
|
|
TEST(NavigationServerLimits, NonFiniteLimitIsRejectedAtTheDoor)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
const double nan = std::numeric_limits<double>::quiet_NaN();
|
|
EXPECT_FALSE(fixture.server_.setTwistLinear(makeVector(nan)));
|
|
EXPECT_FALSE(fixture.server_.setTwistAngular(makeVector(0.0, 0.0, nan)));
|
|
|
|
fixture.spin(1);
|
|
EXPECT_NEAR(fixture.controller_.limitForward(), 0.0, 1e-9);
|
|
}
|
|
|
|
TEST(NavigationServerLimits, LatestLimitWinsWhenSetSeveralTimesWithinOneCycle)
|
|
{
|
|
// Host gọi từ thread của nó với nhịp riêng; nhiều lời gọi giữa hai cycle là bình thường. Thứ phải
|
|
// có hiệu lực là giá trị MỚI NHẤT, không phải giá trị đầu tiên.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
ASSERT_TRUE(fixture.server_.setTwistLinear(makeVector(0.40)));
|
|
ASSERT_TRUE(fixture.server_.setTwistLinear(makeVector(0.10))); // tầng an toàn vừa hạ tiếp
|
|
fixture.spin(1);
|
|
|
|
EXPECT_NEAR(fixture.controller_.limitForward(), 0.10, 1e-9);
|
|
}
|
|
|
|
TEST(NavigationServerLimits, OdometryReachesTheControllerAsMeasuredVelocity)
|
|
{
|
|
// Bản cũ đưa vận tốc đo được vào controller bằng con trỏ tới bộ nhớ host ghi
|
|
// (`tc_->setOdom(&odometry_)`) — data race không có gì bảo vệ. Ở đây truyền theo giá trị, qua
|
|
// control thread.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.server_.addOdometry("/odom", makeOdometry(0.42, -0.17));
|
|
fixture.spin(1);
|
|
|
|
EXPECT_NEAR(fixture.controller_.measuredVelocity().linear.x, 0.42, 1e-9);
|
|
EXPECT_NEAR(fixture.controller_.measuredVelocity().angular.z, -0.17, 1e-9);
|
|
}
|
|
|
|
// ================================================================================================
|
|
// pause / resume / cancel — host gọi từ thread khác
|
|
//
|
|
// OPC-UA và VDA5050 chạy thread riêng (amr_control.cpp:159, 184) và gọi thẳng ba hàm này.
|
|
// `ControlLoop` tự khai là không thread-safe, và `requestPause()` còn ghi HAI cờ không nguyên tử —
|
|
// xen kẽ với `requestResume()` có thể để lại cả hai cùng false. Nên chúng chỉ được ghi nhận ở đây,
|
|
// rồi chuyển xuống lõi trên control thread.
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerLifecycle, PauseTakesEffectOnTheNextCycleNotImmediately)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setScript({ 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);
|
|
|
|
fixture.server_.pause();
|
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kControlling)
|
|
<< "pause() goes straight into the core from the host thread";
|
|
|
|
fixture.spin(1);
|
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPausing)
|
|
<< "pause is taken in one cycle: command zero, waiting for the runtime to settle";
|
|
fixture.spin(1);
|
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused)
|
|
<< "nothing is busy in this fixture, so PAUSED follows one cycle later";
|
|
}
|
|
|
|
TEST(NavigationServerLifecycle, ResumeAfterPauseReturnsToControlling)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
fixture.spin(2);
|
|
|
|
fixture.server_.pause();
|
|
fixture.spin(2);
|
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
|
|
|
fixture.server_.resume();
|
|
fixture.spin(1);
|
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kControlling);
|
|
}
|
|
|
|
TEST(NavigationServerLifecycle, PauseThenResumeWithinOneCycleEndsResumed)
|
|
{
|
|
// Hai cờ đối nghịch được đặt dưới cùng một lock, nên lệnh sau luôn thắng lệnh trước — không có
|
|
// trạng thái "cả hai cùng false" như bản ghi hai cờ rời rạc.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setScript({ 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);
|
|
|
|
fixture.server_.pause();
|
|
fixture.server_.resume();
|
|
fixture.spin(1);
|
|
|
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kControlling);
|
|
}
|
|
|
|
TEST(NavigationServerLifecycle, CancelWinsOverAPauseRequestedInTheSameCycle)
|
|
{
|
|
// "Tạm dừng rồi huỷ" và "huỷ rồi tạm dừng" phải cho cùng kết quả: huỷ thắng.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setScript({ 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);
|
|
|
|
fixture.server_.pause();
|
|
fixture.server_.cancel();
|
|
fixture.spin(1);
|
|
|
|
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused) << "pause won over cancel";
|
|
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing) << "pause won over cancel";
|
|
}
|
|
|
|
TEST(NavigationServerLifecycle, LifecycleRequestIsConsumedExactlyOnce)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
fixture.spin(2);
|
|
|
|
fixture.server_.pause();
|
|
fixture.spin(2);
|
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
|
|
|
// Không có lệnh mới: cờ đã bị tiêu thụ, các cycle sau không được tự tạm dừng lại lần nữa.
|
|
fixture.server_.resume();
|
|
fixture.spin(3);
|
|
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPaused);
|
|
EXPECT_NE(fixture.server_.loop().state(), NavigationState::kPausing);
|
|
}
|
|
|
|
// ================================================================================================
|
|
// 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
|
|
//
|
|
// Contract `BaseNavigation` KHÔNG có hàm spin nào: host nạp plugin, gọi initialize(), rồi chỉ tương
|
|
// tác qua moveTo/getTwist/getFeedback. Runtime vì thế phải TỰ LÁI mình, đúng như bản cũ (thread
|
|
// planner + action server). Thiếu control thread thì goal nằm im trong chỗ chờ vĩnh viễn — không
|
|
// cycle nào chạy, không state nào đổi, và không log gì cả. Đó là lỗi đã thật sự xảy ra trên sim.
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerControlThread, RunsCyclesWithoutAnyoneCallingSpinOnce)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
|
|
// Ở đây KHÔNG gọi spin() của fixture: chính control thread phải đẩy state đi.
|
|
ASSERT_TRUE(fixture.server_.startControlThread(200.0)); // [Hz]
|
|
|
|
bool left_idle = false;
|
|
for (int i = 0; i < 500 && !left_idle; ++i)
|
|
{
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
|
left_idle = fixture.server_.loop().state() != NavigationState::kIdle;
|
|
}
|
|
fixture.server_.stopControlThread();
|
|
|
|
EXPECT_TRUE(left_idle) << "the goal was accepted but no cycle ran — the control thread is "
|
|
"missing";
|
|
}
|
|
|
|
TEST(NavigationServerControlThread, RefusesToStartBeforeTheLoopIsConfigured)
|
|
{
|
|
NavigationServer server;
|
|
EXPECT_FALSE(server.startControlThread(20.0));
|
|
EXPECT_FALSE(server.controlThreadRunning());
|
|
}
|
|
|
|
TEST(NavigationServerControlThread, RefusesNonPositiveFrequency)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
EXPECT_FALSE(fixture.server_.startControlThread(0.0));
|
|
EXPECT_FALSE(fixture.server_.startControlThread(-5.0));
|
|
}
|
|
|
|
TEST(NavigationServerControlThread, SecondStartIsRefusedAndStopIsIdempotent)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
|
|
EXPECT_FALSE(fixture.server_.startControlThread(100.0)) << "started a second thread";
|
|
|
|
fixture.server_.stopControlThread();
|
|
fixture.server_.stopControlThread(); // không được treo hay sập
|
|
EXPECT_FALSE(fixture.server_.controlThreadRunning());
|
|
}
|
|
|
|
TEST(NavigationServerControlThread, DestructorStopsTheThread)
|
|
{
|
|
// Wait until a real cycle has begun; fixture destruction must join before its borrowed ports die.
|
|
class SignallingClock final : public move_base2::ClockPort
|
|
{
|
|
public:
|
|
explicit SignallingClock(std::promise<void>& started) : started_(started) {}
|
|
robot::Time now() const override
|
|
{
|
|
if (!signalled_.exchange(true))
|
|
started_.set_value();
|
|
return robot::Time(kClockStart);
|
|
}
|
|
|
|
private:
|
|
std::promise<void>& started_;
|
|
mutable std::atomic<bool> signalled_{false};
|
|
};
|
|
|
|
std::promise<void> started;
|
|
auto first_cycle = started.get_future();
|
|
SignallingClock clock(started);
|
|
{
|
|
Fixture fixture;
|
|
fixture.deps_.clock = &clock;
|
|
fixture.configure();
|
|
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
|
|
ASSERT_EQ(first_cycle.wait_for(std::chrono::seconds(2)), std::future_status::ready);
|
|
}
|
|
}
|
|
|
|
// ================================================================================================
|
|
// Dữ liệu hiển thị — host gọi từ BỐN ros::Timer khác nhau
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerPlannerData, GettersDoNotShareMutableState)
|
|
{
|
|
// `getGlobalData` và `getLocalData` mỗi cái được gọi từ HAI timer (costmap và plan). Ghi vào
|
|
// `global_data_`/`local_data_` dùng chung đã gây `std::bad_alloc` rồi hỏng heap và giết tiến trình.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.spin(1);
|
|
|
|
robot::move_base_core::PlannerDataOutput a = fixture.server_.getGlobalData();
|
|
robot::move_base_core::PlannerDataOutput b = fixture.server_.getGlobalData();
|
|
|
|
a.plan.poses.clear();
|
|
EXPECT_TRUE(b.plan.poses.empty() || !a.plan.poses.empty())
|
|
<< "two calls returned the same memory";
|
|
EXPECT_NO_THROW({ (void)fixture.server_.getLocalData(); });
|
|
}
|
|
|
|
TEST(NavigationServerPlannerData, ConcurrentGettersDoNotCorruptEachOther)
|
|
{
|
|
// Không chứng minh được không có race (cần ThreadSanitizer), nhưng chạy đúng hình dạng lời gọi
|
|
// của host: bốn thread cùng đọc trong khi control thread cùng ghi bộ đệm.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
ASSERT_TRUE(fixture.server_.startControlThread(200.0));
|
|
|
|
std::atomic<bool> stop{ false };
|
|
std::vector<std::thread> readers;
|
|
for (int i = 0; i < 4; ++i)
|
|
{
|
|
readers.emplace_back([&fixture, &stop, i]() {
|
|
while (!stop.load())
|
|
{
|
|
if (i % 2 == 0)
|
|
{
|
|
(void)fixture.server_.getGlobalData();
|
|
}
|
|
else
|
|
{
|
|
(void)fixture.server_.getLocalData();
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(150));
|
|
stop.store(true);
|
|
for (auto& t : readers)
|
|
{
|
|
t.join();
|
|
}
|
|
fixture.server_.stopControlThread();
|
|
|
|
SUCCEED();
|
|
}
|
|
|
|
TEST(NavigationServerPlannerData, PlanIsStampedWithTheControlLoopClock)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.clock_.setTime(kClockStart + 7.0);
|
|
fixture.spin(1);
|
|
|
|
EXPECT_NEAR(fixture.server_.getGlobalData().plan.header.stamp.toSec(), kClockStart + 7.0, 1e-9)
|
|
<< "the plan carries a timestamp from another clock than the control loop — the host would "
|
|
"treat it as stale and drop it";
|
|
}
|
|
|
|
// ================================================================================================
|
|
// getFeedback() — kết quả của một goal là SỰ KIỆN, không phải mức
|
|
//
|
|
// Lõi chỉ đứng ở state kết thúc đúng MỘT cycle (33 ms @ 30 Hz) rồi về kIdle. Host đọc getFeedback()
|
|
// theo chu kỳ riêng — đo được 100 ms trên robot thật — nên báo theo mức làm mất kết quả 2/3 số lần:
|
|
// host thấy CONTROLLING, lần đọc sau đã là PENDING, không có sự kiện hoàn thành nào, và người vận
|
|
// hành phải bấm cancel một order đã tới đích. Các test dưới đây khoá lại điều đó.
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerFeedback, SucceededSurvivesLongerThanOneCycleSoASlowHostStillSeesIt)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setNominalSpeed(0.3); // [m/s]
|
|
fixture.controller_.setScript({ ControllerScript::kOk, ControllerScript::kGoalReached });
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
|
|
fixture.spin(4); // IDLE -> PLANNING -> CONTROLLING -> tới đích (terminal)
|
|
ASSERT_FALSE(fixture.server_.loop().hasActiveRequest());
|
|
|
|
// 20 cycle = 0.67 s, gấp 6 lần chu kỳ đọc 100 ms của host thật.
|
|
fixture.spin(20);
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::SUCCEEDED)
|
|
<< "the result vanished once the core returned to idle — a host polling slower than one "
|
|
"control cycle would never learn the goal finished";
|
|
}
|
|
|
|
TEST(NavigationServerFeedback, AbortedIsLatchedTheSameWaySoFailuresAreNotLostEither)
|
|
{
|
|
Fixture fixture;
|
|
ControlLoopConfig config = baseConfig();
|
|
config.state_machine.recovery_enabled = false; // hỏng là ABORT thẳng, không đi qua recovery
|
|
fixture.configure(config);
|
|
fixture.controller_.setScript({ ControllerScript::kFail });
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
|
|
fixture.spin(30);
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::ABORTED)
|
|
<< "a failed goal reports PENDING once the core idles — the fleet would wait forever for a "
|
|
"result that already exists";
|
|
}
|
|
|
|
TEST(NavigationServerFeedback, ANewRequestClearsTheLatchedResult)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setNominalSpeed(0.3); // [m/s]
|
|
fixture.controller_.setScript({ ControllerScript::kOk, ControllerScript::kGoalReached });
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
fixture.spin(6);
|
|
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::SUCCEEDED);
|
|
|
|
// Goal thứ hai: chốt cũ phải biến mất ngay, nếu không host đọc "đã xong" cho một goal vừa bắt đầu.
|
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
fixture.spin(3);
|
|
|
|
EXPECT_NE(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::SUCCEEDED)
|
|
<< "the previous result is still being reported while a new goal is running — the host would "
|
|
"mark the new order complete before the robot moved";
|
|
}
|
|
|
|
TEST(NavigationServerFeedback, NothingIsLatchedBeforeTheFirstRequest)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
fixture.spin(5);
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PENDING)
|
|
<< "a freshly booted runtime reports a terminal result although no goal has ever been sent";
|
|
}
|
|
|
|
// ================================================================================================
|
|
// PREEMPTING phải nói thật (2026-09-11): host đọc PREEMPTED là "xong rồi, gửi goal kế được". Cancel
|
|
// lúc SBPL đang chạy mà báo PREEMPTED sau 33 ms thì host gửi goal kế vào một runtime còn bận —
|
|
// đúng chuỗi sự kiện trong log robot_app.log dẫn tới ABORTED oan.
|
|
// ================================================================================================
|
|
|
|
TEST(NavigationServerFeedback, PreemptingIsHeldUntilTheCancelledPlannerAttemptReallyEnds)
|
|
{
|
|
Fixture fixture;
|
|
ControlLoopConfig config = baseConfig();
|
|
config.state_machine.planner_patience = 5.0; // [s]
|
|
config.state_machine.settle_timeout = 2.0; // [s]
|
|
fixture.configure(config);
|
|
fixture.planner_.setLatencyCycles(10);
|
|
fixture.planner_.setCancelKeepsBusy(true); // SBPL trước pha 2: cancelPlan() không cắt được
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
fixture.spin(2);
|
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPlanning);
|
|
ASSERT_TRUE(fixture.planner_.isPlanning());
|
|
|
|
fixture.server_.cancel();
|
|
fixture.spin(1);
|
|
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::PREEMPTING);
|
|
|
|
// Host poll 100 ms một lần = 2 cycle @ 20 Hz: mỗi lần poll trong lúc thread còn bận phải vẫn
|
|
// thấy PREEMPTING, không phải PREEMPTED.
|
|
std::size_t polls_while_busy = 0;
|
|
for (int i = 0; i < 20 && fixture.planner_.isPlanning(); ++i)
|
|
{
|
|
fixture.spin(2);
|
|
if (fixture.planner_.isPlanning())
|
|
{
|
|
++polls_while_busy;
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::PREEMPTING)
|
|
<< "poll " << i << ": PREEMPTED reported while the planner thread is still busy";
|
|
}
|
|
}
|
|
EXPECT_GE(polls_while_busy, 2u);
|
|
|
|
fixture.spin(2);
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::PREEMPTED)
|
|
<< "once the thread is idle the cancel must be reported (and latched) as PREEMPTED";
|
|
}
|
|
|
|
TEST(NavigationServerFeedback, GoalSentWhilePreemptingIsAcceptedAndRunsOnceThePlannerIsFree)
|
|
{
|
|
// Host cũ không đợi PREEMPTED. Vẫn phải chạy đúng: goal kế xếp sau, không bị coi là hỏng.
|
|
Fixture fixture;
|
|
ControlLoopConfig config = baseConfig();
|
|
config.state_machine.planner_patience = 5.0; // [s]
|
|
config.state_machine.max_planning_retries = 0; // như máy chạy log
|
|
fixture.configure(config);
|
|
fixture.planner_.setLatencyCycles(10);
|
|
fixture.planner_.setCancelKeepsBusy(true);
|
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
fixture.spin(2);
|
|
fixture.server_.cancel();
|
|
fixture.spin(1);
|
|
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::PREEMPTING);
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(5.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
|
|
bool saw_clearing_or_aborted = false;
|
|
bool reached_controlling = false;
|
|
for (int i = 0; i < 60 && !reached_controlling; ++i)
|
|
{
|
|
fixture.spin(1);
|
|
const auto host = fixture.server_.getFeedback()->navigation_state;
|
|
saw_clearing_or_aborted = saw_clearing_or_aborted ||
|
|
host == robot::move_base_core::State::CLEARING ||
|
|
host == robot::move_base_core::State::ABORTED;
|
|
reached_controlling = host == robot::move_base_core::State::CONTROLLING;
|
|
}
|
|
EXPECT_FALSE(saw_clearing_or_aborted) << "the second goal went through recovery/abort";
|
|
EXPECT_TRUE(reached_controlling);
|
|
}
|
|
|
|
TEST(NavigationServerFeedback, PausedIsReportedOnlyOnceTheRuntimeIsQuiescent)
|
|
{
|
|
// PAUSING nói thật (2026-09-11): pause lúc SBPL còn chạy → host vẫn thấy PLANNING (+ feed_back_str
|
|
// "pausing…"), KHÔNG phải PAUSED; PAUSED chỉ khi thread planner đã nhả.
|
|
Fixture fixture;
|
|
ControlLoopConfig config = baseConfig();
|
|
config.state_machine.planner_patience = 5.0; // [s]
|
|
fixture.configure(config);
|
|
fixture.planner_.setLatencyCycles(10);
|
|
fixture.planner_.setCancelKeepsBusy(true);
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
fixture.spin(2);
|
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPlanning);
|
|
|
|
fixture.server_.pause();
|
|
fixture.spin(1);
|
|
ASSERT_EQ(fixture.server_.loop().state(), NavigationState::kPausing);
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PLANNING)
|
|
<< "while pausing the host must keep seeing the state that is still winding down";
|
|
EXPECT_NE(fixture.server_.getFeedback()->feed_back_str.find("pausing"), std::string::npos);
|
|
|
|
std::size_t polls_while_busy = 0;
|
|
for (int i = 0; i < 20 && fixture.planner_.isPlanning(); ++i)
|
|
{
|
|
fixture.spin(2);
|
|
if (fixture.planner_.isPlanning())
|
|
{
|
|
++polls_while_busy;
|
|
EXPECT_NE(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PAUSED)
|
|
<< "poll " << i << ": PAUSED reported while the planner thread is still busy";
|
|
}
|
|
}
|
|
EXPECT_GE(polls_while_busy, 2u);
|
|
|
|
fixture.spin(2);
|
|
EXPECT_EQ(fixture.server_.loop().state(), NavigationState::kPaused);
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::PAUSED);
|
|
}
|
|
|
|
TEST(NavigationServerFeedback, StalledControlThreadIsReportedAsLostByTheWatchdog)
|
|
{
|
|
// Pha 4 (2026-09-11): control thread treo thì refreshFeedback() không chạy nữa, host đọc mãi
|
|
// state cuối. Watchdog (thread riêng) phải ghi đè thành LOST trong getFeedback() — trên thread host.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
fixture.controller_.setScript({ ControllerScript::kOk });
|
|
|
|
move_base2::WatchdogConfig dog;
|
|
dog.period = 0.01; // [s]
|
|
dog.control_loop_stall_budget = 0.05; // [s]
|
|
std::string error;
|
|
ASSERT_TRUE(fixture.server_.startWatchdog(&fixture.components_, dog, error)) << error;
|
|
|
|
ASSERT_TRUE(fixture.server_.moveTo(makeRequest(3.0).goal, 0.15, 0.10))
|
|
<< fixture.server_.lastRejectReason();
|
|
fixture.spin(3); // mỗi spinOnce() là một heartbeat của "control thread"
|
|
ASSERT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::CONTROLLING);
|
|
|
|
// Control thread "treo": không spinOnce nữa. Watchdog phải tự thấy sau ngân sách.
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(150));
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, robot::move_base_core::State::LOST)
|
|
<< "a frozen CONTROLLING must not look like a running one";
|
|
EXPECT_NE(fixture.server_.getFeedback()->feed_back_str.find("control thread stalled"),
|
|
std::string::npos);
|
|
|
|
// Thread quay lại → hết LOST, state thật quay về.
|
|
fixture.spin(2);
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(30));
|
|
fixture.spin(1);
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::CONTROLLING);
|
|
}
|
|
|
|
// ================================================================================================
|
|
// executeInstantAction() — cửa duy nhất nhận một action lẻ
|
|
//
|
|
// Điểm cần khoá: hàm này KHÔNG có đường rơi xuống lõi như `moveTo(goal)` có. Một instantAction chỉ
|
|
// có nghĩa sau khi mission layer nở nó theo bảng compound — `PickUp` mà đi thẳng xuống lõi sẽ thành
|
|
// một chặng chỉ-action, tức robot báo "đã nâng kệ" trong khi càng còn chưa tới gần kệ.
|
|
//
|
|
// Fixture ở đây không dựng NavigationRuntime, nên nó mô phỏng đúng cấu hình có mission layer tắt.
|
|
// ================================================================================================
|
|
|
|
namespace
|
|
{
|
|
robot_protocol_msgs::Action makeInstantAction(const std::string& type = "PickUp")
|
|
{
|
|
robot_protocol_msgs::Action action;
|
|
action.actionType = type;
|
|
action.actionId = type + "_1";
|
|
action.blockingType = "HARD";
|
|
return action;
|
|
}
|
|
} // namespace
|
|
|
|
TEST(NavigationServerInstantAction, IsRefusedWhenThereIsNoMissionLayer)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
EXPECT_FALSE(fixture.server_.executeInstantActions({makeInstantAction()}))
|
|
<< "nhận rồi không làm gì là fleet chờ tới hết giờ — nó đang chặn mọi lệnh khác để đợi";
|
|
}
|
|
|
|
TEST(NavigationServerInstantAction, AnEmptyMessageIsRefused)
|
|
{
|
|
// Message rỗng không phải lệnh huỷ. Nhận nó thì host ngồi chờ một kết quả không bao giờ tới.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
EXPECT_FALSE(fixture.server_.executeInstantActions({}));
|
|
}
|
|
|
|
TEST(NavigationServerInstantAction, AMultiActionMessageGoesDownAsOneCall)
|
|
{
|
|
// Chữ ký nhận CẢ danh sách chính là thứ ngăn action `HARD` thứ hai preempt chặng của action thứ
|
|
// nhất trong cùng message. Test này khoá chữ ký đó lại: biên dịch được với nhiều action là đủ,
|
|
// cộng với việc nó vẫn bị từ chối gọn gàng khi không có mission layer.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
const std::vector<robot_protocol_msgs::Action> message = {
|
|
makeInstantAction("MutedOn"), makeInstantAction("PickUp"), makeInstantAction("MutedOff")
|
|
};
|
|
|
|
EXPECT_FALSE(fixture.server_.executeInstantActions(message));
|
|
EXPECT_EQ(0u, fixture.action_.startCount());
|
|
}
|
|
|
|
TEST(NavigationServerInstantAction, ARefusalSaysWhichActionAndWhy)
|
|
{
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
ASSERT_FALSE(fixture.server_.executeInstantActions({makeInstantAction("charge")}));
|
|
|
|
// Host chép chuỗi này vào `resultDescription` gửi lên fleet. "rejected" trơ trọi không giúp được
|
|
// ai; phải nói được là action NÀO và vì SAO.
|
|
const std::string reason = fixture.server_.getFeedback()->feed_back_str;
|
|
EXPECT_NE(reason.find("charge"), std::string::npos) << "reason: " << reason;
|
|
EXPECT_NE(reason.find("instant action"), std::string::npos) << "reason: " << reason;
|
|
}
|
|
|
|
TEST(NavigationServerInstantAction, ARefusedActionNeverReachesTheCore)
|
|
{
|
|
// Bất biến quan trọng nhất của hàm này: KHÔNG có nhánh fallback. `moveTo(goal)` có — layer tắt thì
|
|
// nó submit thẳng, và đúng như vậy vì một goal đơn vẫn còn nguyên nghĩa. Một instantAction thì
|
|
// không: bỏ qua bước nở là bỏ qua bước dò và bước tiến vào.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
ASSERT_FALSE(fixture.server_.executeInstantActions({makeInstantAction()}));
|
|
fixture.spin(10);
|
|
|
|
EXPECT_EQ(0u, fixture.planner_.makePlanCount()) << "không được lập plan cho một action bị từ chối";
|
|
EXPECT_EQ(0u, fixture.action_.startCount()) << "và không được chạy action nào";
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
|
|
robot::move_base_core::State::PENDING)
|
|
<< "lõi phải đứng yên — báo ACTIVE ở đây là fleet tưởng robot đang làm việc";
|
|
}
|
|
|
|
TEST(NavigationServerInstantAction, RefusingDoesNotDisturbAGoalAlreadyRunning)
|
|
{
|
|
// Từ chối phải là no-op với việc đang chạy. Nếu nó đụng vào `pending_request_` hay cờ cancel thì
|
|
// một action lạ do fleet gửi nhầm sẽ dừng cả tuyến đường đang đi.
|
|
Fixture fixture;
|
|
fixture.configure();
|
|
|
|
NavigationRequest request;
|
|
request.profile = MotionProfile::kPosition;
|
|
request.goal.header.frame_id = "map";
|
|
request.goal.pose.position.x = 2.0; // [m]
|
|
request.goal.pose.orientation.w = 1.0;
|
|
ASSERT_TRUE(fixture.server_.moveTo(request.goal, 0.0, 0.0));
|
|
|
|
fixture.spin(5);
|
|
const auto state_before = fixture.server_.getFeedback()->navigation_state;
|
|
const std::size_t plans_before = fixture.planner_.makePlanCount();
|
|
|
|
EXPECT_FALSE(fixture.server_.executeInstantActions({makeInstantAction("NotSupported")}));
|
|
fixture.spin(5);
|
|
|
|
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, state_before)
|
|
<< "một action bị từ chối không được đổi trạng thái của goal đang chạy";
|
|
EXPECT_GE(fixture.planner_.makePlanCount(), plans_before);
|
|
}
|
|
|
|
int main(int argc, char** argv)
|
|
{
|
|
::testing::InitGoogleTest(&argc, argv);
|
|
return RUN_ALL_TESTS();
|
|
}
|