Files
dock_pattern_action/test/dock_pattern_action_test.cpp
duongtd c125bd069c feat: add entry_direction and derive an upside-down lidar from TF
The charger goal heading always pointed out of the station, so only robots
that reverse onto the charger were supported. Front-charging robots now set
`entry_direction: forward` (goal yaw + pi, position unchanged) together with
a front `scan_topic`. The default stays `backward`, so existing configs keep
their behaviour.

Once per run the handler looks up base_link <- scan frame and:
- fails the action if the scan plane is tilted more than 5 deg;
- fails the action if the lidar faces the side opposite to entry_direction,
  instead of writing a reversed goal;
- mirrors the bearings when the lidar is mounted upside down (roll pi),
  as the trolley handler does. No config key is needed for that.

Tests: forward vs backward, direction mismatch, upside-down V / taped V /
arc, tilted scan plane, invalid entry_direction.
2026-11-10 15:06:00 +07:00

776 lines
30 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm handler dò dock từ LiDAR — chạy ĐÚNG chuỗi mà runtime chạy.
*
* Kho cảm biến thật + buffer tf3 thật + plugin nạp qua Boost.DLL. Chỉ scan là dựng sẵn: dựng hình
* trước, chiếu tia sau, nên đáp án biết trước và sai lệch đo được bằng số.
*
* Trọng tâm là những chỗ chỉ HỎNG KHI GHÉP, mà test lõi không thấy: cursor scan, quy TF tại đúng
* stamp, chọn profile từ actionParameters, và các đường từ chối lúc boot.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <string>
#include <vector>
#include <robot/node_handle.h>
#include <tf3/buffer_core.h>
#include <action_core/action_registry.h>
#include <robot_sensor_ports/sensor_store.h>
#include <robot_sensor_ports/sensor_types.h>
namespace
{
using action_core::ActionContext;
using action_core::ActionHandler;
using action_core::ActionRegistry;
using action_core::ActionStatus;
constexpr const char* kGlobalFrame = "map";
constexpr const char* kScanFrame = "front_laser";
constexpr const char* kScanTopic = "/f_scan";
constexpr const char* kOutFrame = "dock_target";
constexpr double kInf = std::numeric_limits<double>::infinity();
/// @brief Quy giây thành tf3::Time QUA robot::Time.
///
/// Không tự tính `(t - sec) * 1e9`: phép đó cắt cụt và lệch một nano giây so với
/// `robot::Time::fromSec`, đủ để lookup tại đúng stamp của scan báo "extrapolation into the
/// future" và mẫu bị bỏ. Đi qua cùng một hàm đổi thì hai stamp khớp từng bit.
tf3::Time toTf3Time(double t)
{
const robot::Time rt(t);
return tf3::Time(rt.sec, rt.nsec);
}
struct Segment
{
double ax, ay, bx, by; // [m]
};
/// @brief Hai cánh của tấm chữ V. Góc TRONG tại đỉnh = pi - 2*half_angle.
std::vector<Segment> vPlate(double apex_x, double half_angle, double wing)
{
const double tip_x = apex_x + wing * std::sin(half_angle);
const double tip_y = wing * std::cos(half_angle);
return { { apex_x, 0.0, tip_x, tip_y }, { apex_x, 0.0, tip_x, -tip_y } };
}
/// @brief Máng cong LÕM: tâm ở @p center_x trên trục x, mặt cong ở XA hơn tâm.
std::vector<Segment> concaveCradle(double center_x, double r, double span, int facets = 300)
{
std::vector<Segment> out;
for (int i = 0; i + 1 < facets; ++i)
{
const double t0 = -span / 2.0 + span * i / (facets - 1);
const double t1 = -span / 2.0 + span * (i + 1) / (facets - 1);
out.push_back({ center_x + r * std::cos(t0), r * std::sin(t0), center_x + r * std::cos(t1),
r * std::sin(t1) });
}
return out;
}
/// @brief [m] Cự ly từ điểm (@p px, @p py) tới đoạn @p s.
double distToSegment(double px, double py, const Segment& s)
{
const double ex = s.bx - s.ax;
const double ey = s.by - s.ay;
const double len2 = ex * ex + ey * ey;
double t = (len2 > 0.0) ? ((px - s.ax) * ex + (py - s.ay) * ey) / len2 : 0.0;
t = std::max(0.0, std::min(1.0, t));
return std::hypot(px - (s.ax + t * ex), py - (s.ay + t * ey));
}
/// @brief Hai dải phản quang dán giữa mỗi cánh của tấm dựng bởi @ref vPlate.
std::vector<Segment> vPlateTapes(double apex_x, double half_angle, double wing, double tape_width)
{
std::vector<Segment> tapes;
for (const Segment& w : vPlate(apex_x, half_angle, wing))
{
const double len = std::hypot(w.bx - w.ax, w.by - w.ay);
const double dx = (w.bx - w.ax) / len;
const double dy = (w.by - w.ay) / len;
const double mid_x = w.ax + dx * len / 2.0;
const double mid_y = w.ay + dy * len / 2.0;
tapes.push_back({ mid_x - dx * tape_width / 2.0, mid_y - dy * tape_width / 2.0,
mid_x + dx * tape_width / 2.0, mid_y + dy * tape_width / 2.0 });
}
return tapes;
}
robot_sensor_msgs::LaserScan makeScan(const std::vector<Segment>& world, double stamp_s,
std::size_t rays = 600,
const std::vector<Segment>& tapes = {})
{
robot_sensor_msgs::LaserScan scan;
scan.header.frame_id = kScanFrame;
scan.header.stamp = robot::Time(stamp_s);
scan.angle_min = -0.8f;
scan.angle_max = 0.8f;
scan.angle_increment = 1.6f / static_cast<float>(rays - 1);
scan.range_min = 0.05f;
scan.range_max = 20.0f;
scan.ranges.assign(rays, static_cast<float>(kInf));
for (std::size_t i = 0; i < rays; ++i)
{
const double bearing = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
const double dx = std::cos(bearing);
const double dy = std::sin(bearing);
for (const Segment& s : world)
{
const double ex = s.bx - s.ax;
const double ey = s.by - s.ay;
const double det = dx * (-ey) - dy * (-ex);
if (std::fabs(det) < 1e-12)
{
continue;
}
const double t = (s.ax * (-ey) - s.ay * (-ex)) / det;
const double u = (dx * s.ay - dy * s.ax) / det;
if (t > 0.0 && u >= 0.0 && u <= 1.0 && t < scan.ranges[i])
{
scan.ranges[i] = static_cast<float>(t);
}
}
}
// `intensities` để RỖNG khi không có dải nào — đúng như một driver không đo cường độ, và đó là
// ca mà handler phải nói ra thay vì im lặng dò không xong.
if (!tapes.empty())
{
scan.intensities.assign(rays, 0.0f);
for (std::size_t i = 0; i < rays; ++i)
{
if (!std::isfinite(scan.ranges[i]))
{
continue;
}
const double bearing = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
const double px = scan.ranges[i] * std::cos(bearing);
const double py = scan.ranges[i] * std::sin(bearing);
for (const Segment& tape : tapes)
{
if (distToSegment(px, py, tape) <= 1e-6)
{
scan.intensities[i] = 2000.0f; // đúng `laser_retro` của model dock_plate_v
break;
}
}
}
}
return scan;
}
robot_protocol_msgs::Action makeAction(const std::string& profile = std::string())
{
robot_protocol_msgs::Action action;
action.actionType = "DetectCharger";
action.actionId = "detect-1";
if (!profile.empty())
{
robot_protocol_msgs::ActionParameter p;
p.key = "dock_profile";
p.value = profile;
action.actionParameters.push_back(p);
}
return action;
}
/// @brief Rig: kho thật + tf3 thật + plugin nạp qua đúng đường Boost.DLL.
class Rig
{
public:
explicit Rig(const std::string& ns = "actions_dock",
const std::string& direction = "backward", double base_yaw = M_PI)
{
robot_sensor_ports::SensorStoreConfig store_config;
robot_sensor_ports::SensorEntryConfig entry;
entry.topic = kScanTopic;
entry.data_type = "robot_sensor_msgs/LaserScan";
entry.capacity = 1;
entry.max_age = 0.5; // [s]
store_config.sensors.push_back(entry);
std::string error;
store_ok_ = store.configure(store_config, error);
// Cảm biến gắn tại gốc robot, robot tại gốc map — giữ phép biến đổi tầm thường để lệch nào ở
// kết quả cũng là lệch của phép DÒ, không phải của phép quy đổi.
setSensorPose(0.0, 0.0, 0.0, 0.0);
// Keep the historic map <- scan test geometry and place the robot base so that the
// same lidar is rear-facing by default. This also leaves scan-time TF independent.
tf3::TransformStampedMsg base;
base.header.frame_id = kGlobalFrame;
base.child_frame_id = "base_link";
base.transform.rotation.z = std::sin(base_yaw / 2.0);
base.transform.rotation.w = std::cos(base_yaw / 2.0);
tf.setTransform(base, "test", /*is_static=*/true);
ctx.tf = &tf;
ctx.sensors = &store;
ctx.global_frame = kGlobalFrame;
registry.setContext(ctx);
if (ns == "actions_dock")
{
nh.setParam("actions_dock/detect/entry_direction", direction);
}
loaded = registry.loadFromConfig(nh, ns);
if (ns == "actions_dock")
{
nh.setParam("actions_dock/detect/entry_direction", std::string("backward"));
}
handler = registry.find("DetectCharger");
}
void setSensorPose(double x, double y, double yaw, double stamp_s,
double roll = 0.0, double pitch = 0.0)
{
tf3::TransformStampedMsg t;
t.header.stamp = toTf3Time(stamp_s);
t.header.frame_id = kGlobalFrame;
t.child_frame_id = kScanFrame;
t.transform.translation.x = x;
t.transform.translation.y = y;
t.transform.translation.z = 0.0;
const double cr = std::cos(roll * 0.5), sr = std::sin(roll * 0.5);
const double cp = std::cos(pitch * 0.5), sp = std::sin(pitch * 0.5);
const double cy = std::cos(yaw * 0.5), sy = std::sin(yaw * 0.5);
t.transform.rotation.x = sr * cp * cy - cr * sp * sy;
t.transform.rotation.y = cr * sp * cy + sr * cp * sy;
t.transform.rotation.z = cr * cp * sy - sr * sp * cy;
t.transform.rotation.w = cr * cp * cy + sr * sp * sy;
tf.setTransform(t, "test", /*is_static=*/false);
}
void push(const std::vector<Segment>& world, double stamp_s,
const std::vector<Segment>& tapes = {})
{
robot_sensor_ports::put(store, kScanTopic, makeScan(world, stamp_s, 600, tapes),
robot::Time(stamp_s));
}
/// @brief Như @ref feed nhưng scan mang thêm dải phản quang.
ActionStatus feedWithTape(const std::vector<Segment>& world, const std::vector<Segment>& tapes,
int count, double start_s = 10.0, double period = 0.1)
{
ActionStatus status = ActionStatus::kRunning;
for (int i = 0; i < count; ++i)
{
const double t = start_s + period * i;
setSensorPose(0.0, 0.0, 0.0, t);
push(world, t, tapes);
const action_core::ActionTick tick = handler->update(robot::Time(t));
status = tick.status;
last_message = tick.message;
++ticks;
if (status != ActionStatus::kRunning)
{
break;
}
}
return status;
}
/// @brief Bơm @p count scan rồi tick, đúng nhịp mà control loop chạy.
ActionStatus feed(const std::vector<Segment>& world, int count, double start_s = 10.0,
double period = 0.1)
{
ActionStatus status = ActionStatus::kRunning;
for (int i = 0; i < count; ++i)
{
const double t = start_s + period * i;
setSensorPose(0.0, 0.0, 0.0, t);
push(world, t);
const action_core::ActionTick tick = handler->update(robot::Time(t));
status = tick.status;
last_message = tick.message;
++ticks;
if (status != ActionStatus::kRunning)
{
break;
}
}
return status;
}
std::string last_message;
int ticks = 0;
bool store_ok_ = false;
bool loaded = false;
robot::NodeHandle nh;
tf3::BufferCore tf;
robot_sensor_ports::SensorStore store;
ActionContext ctx;
ActionRegistry registry;
ActionHandler* handler = nullptr;
};
double yawOf(const tf3::QuaternionMsg& q)
{
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
}
double angleDistance(double a, double b)
{
return std::fabs(std::atan2(std::sin(a - b), std::cos(a - b)));
}
// A mirrored physical scan keeps the original ray indices and mirrors their bearings;
// reverse both arrays to synthesize the same asymmetric scene with a roll-pi sensor.
ActionStatus feedMounted(Rig& rig, const std::vector<Segment>& scene,
const std::vector<Segment>& tapes, double roll, double pitch = 0.0,
double yaw = 0.0)
{
ActionStatus status = ActionStatus::kRunning;
for (int i = 0; i < 8 && status == ActionStatus::kRunning; ++i)
{
const double t = 10.0 + 0.1 * i;
rig.setSensorPose(0.0, 0.0, yaw, t, roll, pitch);
auto scan = makeScan(scene, t, 600, tapes);
if (std::fabs(roll) > 1.0)
{
std::reverse(scan.ranges.begin(), scan.ranges.end());
std::reverse(scan.intensities.begin(), scan.intensities.end());
}
robot_sensor_ports::put(rig.store, kScanTopic, scan, robot::Time(t));
const auto tick = rig.handler->update(robot::Time(t));
status = tick.status;
rig.last_message = tick.message;
}
return status;
}
void expectSameGoal(const tf3::TransformStampedMsg& a, const tf3::TransformStampedMsg& b)
{
EXPECT_NEAR(a.transform.translation.x, b.transform.translation.x, 0.001);
EXPECT_NEAR(a.transform.translation.y, b.transform.translation.y, 0.001);
EXPECT_LT(angleDistance(yawOf(a.transform.rotation), yawOf(b.transform.rotation)), 0.001);
}
// ================================================================================================
// 1. Đường chạy đủ
// ================================================================================================
TEST(DockPatternAction, DetectsAPlateAndWritesTheGoalFrame)
{
Rig rig;
ASSERT_TRUE(rig.store_ok_);
ASSERT_TRUE(rig.loaded);
ASSERT_NE(rig.handler, nullptr);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
EXPECT_EQ(rig.feed(vPlate(1.20, M_PI / 4.0, 0.30), 8), ActionStatus::kSucceeded);
// Đỉnh ở x=1.20 trong frame cảm biến, cảm biến trùng gốc map, profile lùi 0.60 m ra phía robot.
const tf3::TransformStampedMsg out = rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
EXPECT_NEAR(out.transform.translation.x, 0.60, 0.05);
EXPECT_NEAR(out.transform.translation.y, 0.00, 0.05);
}
TEST(DockPatternAction, TheGoalFollowsTheSensorPose)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
// Cảm biến dịch sang (2.0, 1.0) trong map. Kết quả phải ra theo — đây là chỗ phép quy TF sai sẽ
// lộ, mà test lõi hình học không bao giờ thấy vì lõi làm việc trong frame của scan.
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
ActionStatus status = ActionStatus::kRunning;
for (int i = 0; i < 8; ++i)
{
const double t = 10.0 + 0.1 * i;
rig.setSensorPose(2.0, 1.0, 0.0, t);
rig.push(vPlate(1.20, M_PI / 4.0, 0.30), t);
status = rig.handler->update(robot::Time(t)).status;
if (status != ActionStatus::kRunning)
{
break;
}
}
ASSERT_EQ(status, ActionStatus::kSucceeded);
const tf3::TransformStampedMsg out = rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
EXPECT_NEAR(out.transform.translation.x, 2.60, 0.05);
EXPECT_NEAR(out.transform.translation.y, 1.00, 0.05);
}
TEST(DockPatternAction, TheOrderPicksTheProfile)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
// `v_wide` chờ tấm 120 độ và lùi 0.50 m. Order chọn nó qua actionParameters — đường đã verify:
// chặng chỉ-action mang NGUYÊN actionParameters của action gốc.
ASSERT_TRUE(rig.handler->start(makeAction("v_wide"), robot::Time(10.0)));
ASSERT_EQ(rig.feed(vPlate(1.10, M_PI / 6.0, 0.25), 8), ActionStatus::kSucceeded);
const tf3::TransformStampedMsg out = rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
EXPECT_NEAR(out.transform.translation.x, 0.60, 0.06);
}
TEST(DockPatternAction, TheWrongProfileForTheShapeDoesNotDetect)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
// Tấm 90 độ nhưng order xin profile 120 độ. Phải TRƯỢT, không được nhận bừa.
ASSERT_TRUE(rig.handler->start(makeAction("v_wide"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(vPlate(1.20, M_PI / 4.0, 0.30), 12), ActionStatus::kRunning);
}
// ================================================================================================
// 2. Cursor scan — chỗ chỉ hỏng khi ghép
// ================================================================================================
TEST(DockPatternAction, TickingWithoutANewScanCountsNothing)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
rig.setSensorPose(0.0, 0.0, 0.0, 10.0);
rig.push(vPlate(1.20, M_PI / 4.0, 0.30), 10.0);
// MỘT scan, nhưng tick nhiều lần — đúng như control loop 30 Hz đọc lidar 29 Hz. Không có cursor
// thì cùng một scan bị đếm thành nhiều mẫu, `min_samples` mất hết ý nghĩa và handler chốt trên
// một phép đo duy nhất.
for (int i = 0; i < 20; ++i)
{
ASSERT_EQ(rig.handler->update(robot::Time(10.0 + 0.01 * i)).status, ActionStatus::kRunning);
}
}
TEST(DockPatternAction, EachNewScanCountsOnce)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
// min_samples là 3, nên 2 scan chưa được chốt và 4 scan thì phải chốt.
EXPECT_EQ(rig.feed(vPlate(1.20, M_PI / 4.0, 0.30), 2), ActionStatus::kRunning);
EXPECT_EQ(rig.feed(vPlate(1.20, M_PI / 4.0, 0.30), 4, 10.2), ActionStatus::kSucceeded)
<< "ticks=" << rig.ticks << " msg='" << rig.last_message << "'";
}
// ================================================================================================
// 3. Đường hỏng
// ================================================================================================
TEST(DockPatternAction, ADetectionSurvivesTfArrivingAfterTheScan)
{
// TF và scan tới từ hai nguồn khác nhau, nên TF chậm hơn scan vài mili giây là chuyện thường.
// Cursor của kho đã nhảy qua scan đó rồi, nên bỏ mẫu ở đây là MẤT HẲN một phép dò mỗi lần TF trễ.
// Phép dò phải được giữ lại và quy đổi ở tick sau.
Rig rig;
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
const std::vector<Segment> world = vPlate(1.20, M_PI / 4.0, 0.30);
ActionStatus status = ActionStatus::kRunning;
for (int i = 0; i < 6 && status == ActionStatus::kRunning; ++i)
{
const double t = 10.0 + 0.1 * i;
// Scan tới TRƯỚC, TF chưa có ở stamp đó -> lookup phải trượt.
rig.push(world, t);
status = rig.handler->update(robot::Time(t)).status;
if (status != ActionStatus::kRunning)
{
break;
}
// TF đuổi kịp. Tick sau KHÔNG có scan mới, nhưng phép dò treo phải được giải quyết.
rig.setSensorPose(0.0, 0.0, 0.0, t);
status = rig.handler->update(robot::Time(t + 0.01)).status;
}
EXPECT_EQ(status, ActionStatus::kSucceeded)
<< "phép dò bị vứt khi TF trễ — mỗi lần TF chậm là mất một scan";
}
TEST(DockPatternAction, AnEmptySceneTimesOutAndSaysWhy)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
rig.feed({}, 40, 10.0, 0.1);
const action_core::ActionTick tick = rig.handler->update(robot::Time(16.0));
EXPECT_EQ(tick.status, ActionStatus::kFailed);
// Thông điệp phải nói được HỎNG Ở CỔNG NÀO, không phải một dòng "detection failed".
EXPECT_NE(tick.message.find("no 'v_std' pattern"), std::string::npos) << tick.message;
}
TEST(DockPatternAction, APalletCornerNeverBecomesADock)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
// Góc pallet: ĐÚNG 90 độ, chỉ khác cạnh dài 0.8 m. Đây là dương tính giả điển hình trong kho.
rig.feed(vPlate(1.20, M_PI / 4.0, 0.80), 40, 10.0, 0.1);
const action_core::ActionTick tick = rig.handler->update(robot::Time(16.0));
EXPECT_EQ(tick.status, ActionStatus::kFailed);
EXPECT_NE(tick.message.find("wing length"), std::string::npos) << tick.message;
}
TEST(DockPatternAction, ARunIsNotContaminatedByThePreviousOne)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
ASSERT_EQ(rig.feed(vPlate(1.20, M_PI / 4.0, 0.30), 8), ActionStatus::kSucceeded);
// Lượt hai trên cảnh trống: nếu mẫu của lượt trước còn lại thì nó sẽ chốt ngay, tức dock vào chỗ
// đã rời đi từ lâu.
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(20.0)));
EXPECT_EQ(rig.feed({}, 8, 20.0), ActionStatus::kRunning);
}
// ================================================================================================
// 4. Từ chối LÚC BOOT
// ================================================================================================
TEST(DockPatternAction, RefusesAScanTopicTheStoreDoesNotHave)
{
// Gõ sai tên topic là lỗi phổ biến nhất, và triệu chứng của nó GIỐNG HỆT cảm biến chết. Bắt lúc
// boot, đừng để nó thành một lượt dò hết giờ.
Rig rig("actions_dock_bad_topic");
EXPECT_EQ(rig.handler, nullptr);
}
TEST(DockPatternAction, RefusesAConfigWithNoProfile)
{
Rig rig("actions_dock_no_profile");
EXPECT_EQ(rig.handler, nullptr);
}
TEST(DockPatternAction, RefusesAPatternThatIsNotImplementedYet)
{
// Nhận nó nghĩa là dựng một bộ dò không bao giờ tìm thấy gì — nhìn giống hệt trạm ngoài tầm.
Rig rig("actions_dock_unimplemented");
EXPECT_EQ(rig.handler, nullptr);
}
TEST(DockPatternAction, CarriesScanIntensitiesThroughToTheMatcher)
{
// Kiểm ĐƯỜNG DẪN DỮ LIỆU, không phải luật khớp — luật đã có test riêng bên
// dock_pattern_detector. Ở đây câu hỏi là: mảng `intensities` của scan có thật sự đi từ kho cảm
// biến tới matcher không, hay handler đang đưa vào một mảng rỗng.
Rig rig;
ASSERT_TRUE(rig.store_ok_);
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction("v_tape"), robot::Time(10.0)));
EXPECT_EQ(rig.feedWithTape(vPlate(1.20, M_PI / 4.0, 0.30),
vPlateTapes(1.20, M_PI / 4.0, 0.30, 0.12), 8),
ActionStatus::kSucceeded)
<< rig.last_message;
const tf3::TransformStampedMsg out = rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
EXPECT_NEAR(out.transform.translation.x, 0.60, 0.05);
EXPECT_NEAR(out.transform.translation.y, 0.00, 0.05);
}
TEST(DockPatternAction, ATapeProfileOnAScanWithoutIntensitiesSaysWhy)
{
// Cùng tấm, cùng profile, khác đúng một chuyện: scan không mang cường độ — như driver không đo
// được. Nếu handler đưa vào matcher một mảng bịa thay vì mảng của scan thì test này KHÔNG thấy
// được câu đó, nên nó chính là bằng chứng đường dẫn dữ liệu là thật.
Rig rig;
ASSERT_TRUE(rig.store_ok_);
ASSERT_TRUE(rig.loaded);
// Chạy quá `timeout` (5 s) để action kết thúc — lý do chỉ đi ra ngoài khi nó KẾT THÚC.
ASSERT_TRUE(rig.handler->start(makeAction("v_tape"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(vPlate(1.20, M_PI / 4.0, 0.30), 60), ActionStatus::kFailed);
EXPECT_NE(rig.last_message.find("no intensity data"), std::string::npos) << rig.last_message;
}
TEST(DockPatternAction, ATapeProfileRefusesAPlateThatCarriesNoTape)
{
// Tấm đúng hình hoàn hảo, scan CÓ mang cường độ, nhưng không dải nào sáng. Đây là ca ngoài kho:
// hai pallet kê vuông góc dựng ra đúng hình cái sạc.
Rig rig;
ASSERT_TRUE(rig.store_ok_);
ASSERT_TRUE(rig.loaded);
// Dải nằm ngoài tấm nên không tia nào trúng — scan vẫn có mảng `intensities`, toàn 0.
const std::vector<Segment> elsewhere = { { 5.0, 5.0, 5.1, 5.1 } };
ASSERT_TRUE(rig.handler->start(makeAction("v_tape"), robot::Time(10.0)));
EXPECT_EQ(rig.feedWithTape(vPlate(1.20, M_PI / 4.0, 0.30), elsewhere, 60), ActionStatus::kFailed);
EXPECT_NE(rig.last_message.find("reflective tape"), std::string::npos) << rig.last_message;
}
TEST(DockPatternAction, DispatchesToTheArcMatcherWhenTheProfileAsksForOne)
{
// Kiểm ĐƯỜNG ĐỊNH TUYẾN, không phải luật khớp — luật đã có test riêng bên dock_pattern_detector.
// Câu hỏi ở đây: profile khai `pattern: arc` có thật sự chạy qua ArcPatternMatcher không, hay
// handler vẫn đưa nó cho bộ khớp chữ V. Nếu đưa nhầm, bộ khớp chữ V nay TỪ CHỐI ngay lúc start,
// nên test này fail ở dòng start chứ không phải im lặng không dò ra gì.
Rig rig;
ASSERT_TRUE(rig.store_ok_);
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction("cradle"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(concaveCradle(1.20, 0.40, 2.0), 8), ActionStatus::kSucceeded)
<< rig.last_message;
// Tâm ở 1.20, bán kính 0.40 -> điểm sâu nhất ở 1.60; profile lùi 0.60 m ra phía robot.
const tf3::TransformStampedMsg out = rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
EXPECT_NEAR(out.transform.translation.x, 1.00, 0.05);
EXPECT_NEAR(out.transform.translation.y, 0.00, 0.05);
}
TEST(DockPatternAction, AnArcProfileRefusesAVPlate)
{
// Mặt kia: cùng handler, cùng profile arc, nhưng trong tầm là một tấm chữ V. Không có cặp này
// thì một lỗi làm hỏng hẳn phép dò cung cũng trông y hệt "cổng đang làm việc".
Rig rig;
ASSERT_TRUE(rig.store_ok_);
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction("cradle"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(vPlate(1.20, M_PI / 4.0, 0.30), 60), ActionStatus::kFailed);
}
TEST(DockPatternAction, RefusesADefaultProfileThatDoesNotExist)
{
Rig rig("actions_dock_bad_default");
EXPECT_EQ(rig.handler, nullptr);
}
TEST(DockPatternAction, RefusesToStartOnAProfileTheOrderInvented)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
// KHÔNG âm thầm rơi về default: dùng nhầm hình học là dock vào sai chỗ, không phải chậm hơn một
// chút.
EXPECT_FALSE(rig.handler->start(makeAction("khong_co_profile_nay"), robot::Time(10.0)));
}
TEST(DockPatternAction, RefusesToLoadWithoutASensorStore)
{
// Handler này đọc scan THÔ. Không có kho thì nó vô nghĩa, và phải nói ra lúc nạp.
robot::NodeHandle nh;
tf3::BufferCore tf;
ActionContext ctx;
ctx.tf = &tf;
ctx.sensors = nullptr;
ctx.global_frame = kGlobalFrame;
ActionRegistry registry;
registry.setContext(ctx);
registry.loadFromConfig(nh, "actions_dock");
EXPECT_EQ(registry.find("DetectCharger"), nullptr);
}
TEST(DockPatternAction, ForwardAndBackwardUseSamePositionAndOppositeHeadings)
{
Rig rear;
Rig front("actions_dock", "forward", 0.0);
ASSERT_TRUE(rear.loaded);
ASSERT_TRUE(front.loaded);
ASSERT_TRUE(rear.handler->start(makeAction(), robot::Time(10.0)));
ASSERT_TRUE(front.handler->start(makeAction(), robot::Time(10.0)));
const auto scene = vPlate(1.20, M_PI / 4.0, 0.30);
ASSERT_EQ(feedMounted(rear, scene, {}, 0.0), ActionStatus::kSucceeded) << rear.last_message;
ASSERT_EQ(feedMounted(front, scene, {}, 0.0), ActionStatus::kSucceeded) << front.last_message;
const auto a = rear.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
const auto b = front.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
EXPECT_NEAR(a.transform.translation.x, b.transform.translation.x, 0.001);
EXPECT_NEAR(a.transform.translation.y, b.transform.translation.y, 0.001);
EXPECT_NEAR(angleDistance(yawOf(a.transform.rotation), yawOf(b.transform.rotation)), M_PI, 0.001);
}
TEST(DockPatternAction, DirectionMismatchFailsWithoutGoal)
{
Rig rig("actions_dock", "backward", 0.0);
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
EXPECT_EQ(feedMounted(rig, vPlate(1.2, M_PI / 4.0, 0.30), {}, 0.0), ActionStatus::kFailed);
EXPECT_NE(rig.last_message.find("entry_direction backward"), std::string::npos);
EXPECT_NE(rig.last_message.find("faces forward"), std::string::npos);
EXPECT_ANY_THROW(rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time()));
}
TEST(DockPatternAction, UpsideDownScanMatchesUprightForVArcAndTape)
{
for (const std::string profile : {"v_std", "v_tape", "cradle"})
{
SCOPED_TRACE(profile);
Rig upright;
Rig flipped;
ASSERT_TRUE(upright.loaded);
ASSERT_TRUE(flipped.loaded);
ASSERT_TRUE(upright.handler->start(makeAction(profile), robot::Time(10.0)));
ASSERT_TRUE(flipped.handler->start(makeAction(profile), robot::Time(10.0)));
auto scene = profile == "cradle" ? concaveCradle(1.20, 0.40, 2.0)
: vPlate(1.20, M_PI / 4.0, 0.30);
auto tapes = profile == "v_tape" ? vPlateTapes(1.20, M_PI / 4.0, 0.30, 0.12)
: std::vector<Segment>{};
// Shift the scene sideways so a missing reflection cannot pass by symmetry.
for (auto& s : scene) { s.ay += 0.08; s.by += 0.08; }
for (auto& s : tapes) { s.ay += 0.08; s.by += 0.08; }
ASSERT_EQ(feedMounted(upright, scene, tapes, 0.0, 0.0, 0.4), ActionStatus::kSucceeded)
<< upright.last_message;
ASSERT_EQ(feedMounted(flipped, scene, tapes, M_PI, 0.0, 0.4), ActionStatus::kSucceeded)
<< flipped.last_message;
expectSameGoal(upright.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time()),
flipped.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time()));
}
}
TEST(DockPatternAction, TiltedScanPlaneFailsWithoutGoal)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0)));
EXPECT_EQ(feedMounted(rig, vPlate(1.2, M_PI / 4.0, 0.30), {}, 0.0, 0.11),
ActionStatus::kFailed);
EXPECT_NE(rig.last_message.find("tilted"), std::string::npos);
EXPECT_ANY_THROW(rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time()));
}
TEST(DockPatternAction, RefusesInvalidEntryDirection)
{
Rig rig("actions_dock", "sideways");
EXPECT_FALSE(rig.loaded);
EXPECT_EQ(rig.handler, nullptr);
}
} // namespace
int main(int argc, char** argv)
{
#ifdef DOCK_PATTERN_ACTION_TEST_CONFIG_DIR
setenv("PNKX_NAV_CORE_CONFIG_DIR", DOCK_PATTERN_ACTION_TEST_CONFIG_DIR, 0);
#endif
#ifdef DOCK_PATTERN_ACTION_TEST_LIBRARY_DIR
setenv("PNKX_NAV_CORE_LIBRARY_PATH", DOCK_PATTERN_ACTION_TEST_LIBRARY_DIR, 0);
#endif
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}