The gate used to fire at settle_delay + sample_window and abort, throwing away whatever remained of the timeout. Four field runs failed there with spreads between 1.3 m and 3.2 m while the detector reported the pallet to within a millimetre, and a retry seconds later at the same spot succeeded - the detection needed longer to settle than the window allowed, and the handler was not willing to wait. samples_ is now a sliding window of sample_window seconds: each tick adds the new sample and drops the expired ones. Once the window is full the spread is evaluated every tick, and a spread over the limit only means "not yet" - the handler keeps sampling until it converges or the timeout runs out. The timeout becomes the real deadline instead of the window. hold_time requires the spread to stay under the limit for that long before the result is published, so a momentarily quiet window cannot be mistaken for a settled one. 0 keeps the previous behaviour of publishing on the first good window. Convergence is logged once a second, not per tick, so it is possible to see whether the sample set is tightening without drowning a 30 Hz loop. median and robustSpread now take their buffer by reference and sort it in place, since they run on every tick rather than once per detection.
443 lines
16 KiB
C++
443 lines
16 KiB
C++
/*********************************************************************
|
|
*
|
|
* Software License Agreement (BSD License)
|
|
*
|
|
* Kiểm handler dò: lấy mẫu TF nhiễu, lọc, ghi ra frame ổn định.
|
|
*
|
|
* Trọng tâm là ba thứ mà một bản lọc viết vội sẽ sai: gộp góc quanh ±π, chống outlier, và cổng chất
|
|
* lượng khi dữ liệu tản. Cả ba đều dẫn tới robot lùi vào sai chỗ mà không có lỗi nào được báo.
|
|
*
|
|
* Author: DuongTD
|
|
*********************************************************************/
|
|
#include <gtest/gtest.h>
|
|
|
|
#include <cmath>
|
|
#include <cstdlib>
|
|
#include <memory>
|
|
#include <string>
|
|
|
|
#include <robot/node_handle.h>
|
|
#include <tf3/buffer_core.h>
|
|
|
|
#include <action_core/action_registry.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* kRawFrame = "charger_raw";
|
|
constexpr const char* kOutFrame = "dock_target";
|
|
|
|
/// tf3::Time chỉ có ctor (sec, nsec) — không có ctor từ double như robot::Time.
|
|
tf3::Time toTf3Time(double t)
|
|
{
|
|
const uint32_t sec = static_cast<uint32_t>(t);
|
|
return tf3::Time(sec, static_cast<uint32_t>((t - sec) * 1e9));
|
|
}
|
|
|
|
robot_protocol_msgs::Action makeAction(const std::string& frame = kRawFrame,
|
|
const std::string& action_type = "DetectCharger")
|
|
{
|
|
robot_protocol_msgs::Action action;
|
|
action.actionType = action_type;
|
|
action.actionId = "detect-1";
|
|
|
|
if (!frame.empty())
|
|
{
|
|
robot_protocol_msgs::ActionParameter p;
|
|
p.key = "goal_frame";
|
|
p.value = frame;
|
|
action.actionParameters.push_back(p);
|
|
}
|
|
return action;
|
|
}
|
|
|
|
/// @brief Rig: một buffer TF thật + handler nạp qua đúng đường Boost.DLL.
|
|
class Rig
|
|
{
|
|
public:
|
|
explicit Rig(const std::string& ns = "actions_detect",
|
|
const std::string& action_type = "DetectCharger")
|
|
{
|
|
ctx.tf = &tf;
|
|
ctx.global_frame = kGlobalFrame;
|
|
registry.setContext(ctx);
|
|
loaded = registry.loadFromConfig(nh, ns);
|
|
handler = registry.find(action_type);
|
|
}
|
|
|
|
/// @brief Bơm một mẫu thô vào buffer. `stamp` phải TĂNG, nếu không mẫu bị bỏ (đúng contract).
|
|
void pushSample(double x, double y, double yaw, double stamp_s)
|
|
{
|
|
tf3::TransformStampedMsg t;
|
|
t.header.stamp = toTf3Time(stamp_s);
|
|
t.header.frame_id = kGlobalFrame;
|
|
t.child_frame_id = kRawFrame;
|
|
t.transform.translation.x = x;
|
|
t.transform.translation.y = y;
|
|
t.transform.rotation.z = std::sin(yaw * 0.5);
|
|
t.transform.rotation.w = std::cos(yaw * 0.5);
|
|
tf.setTransform(t, "test", /*is_static=*/false);
|
|
}
|
|
|
|
void pushTransform(const std::string& parent, const std::string& child, double x, double y,
|
|
double yaw, double stamp_s)
|
|
{
|
|
tf3::TransformStampedMsg t;
|
|
t.header.stamp = toTf3Time(stamp_s);
|
|
t.header.frame_id = parent;
|
|
t.child_frame_id = child;
|
|
t.transform.translation.x = x;
|
|
t.transform.translation.y = y;
|
|
t.transform.rotation.z = std::sin(yaw * 0.5);
|
|
t.transform.rotation.w = std::cos(yaw * 0.5);
|
|
tf.setTransform(t, "test", /*is_static=*/false);
|
|
}
|
|
|
|
bool readOutput(double& x, double& y, double& yaw)
|
|
{
|
|
try
|
|
{
|
|
const auto t = tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
|
|
x = t.transform.translation.x;
|
|
y = t.transform.translation.y;
|
|
const auto& q = t.transform.rotation;
|
|
yaw = std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
|
|
return true;
|
|
}
|
|
catch (const std::exception&)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
robot::NodeHandle nh;
|
|
tf3::BufferCore tf;
|
|
ActionContext ctx;
|
|
ActionRegistry registry;
|
|
ActionHandler* handler = nullptr;
|
|
bool loaded = false;
|
|
};
|
|
|
|
// Config test: settle_delay = 0.2, sample_window = 1.0, min_samples = 10, timeout = 5.0.
|
|
// -> lượt dò bắt đầu tại t = 100.0; cửa sổ đầu tiên được chấm tại t = 101.2; timeout tại t = 105.0.
|
|
constexpr double kStart = 100.0;
|
|
constexpr double kTickPeriod = 0.01; // [s] ~100 Hz, dày hơn control loop thật cho chắc
|
|
constexpr double kFirstTick = 100.3; // [s] ngay sau settle_delay
|
|
constexpr double kFirstVerdict = 101.2; // [s] settle_delay + sample_window
|
|
constexpr double kTimeoutAt = 105.0; // [s]
|
|
|
|
/**
|
|
* @brief Chạy handler từ @p kFirstTick tới @p t_end, mỗi tick gọi @p make để bơm một mẫu.
|
|
*
|
|
* Dừng ngay khi handler ra khỏi kRunning và ghi thời điểm đó vào @p stopped_at — cửa sổ trượt khiến
|
|
* "chốt lúc nào" trở thành một phần của hành vi cần kiểm, không chỉ "chốt hay không".
|
|
*
|
|
* @param make void(Rig&, int tick_index, double now_s)
|
|
*/
|
|
template <typename MakeSample>
|
|
ActionStatus runTicks(Rig& rig, double t_end, MakeSample make, double* stopped_at = nullptr)
|
|
{
|
|
ActionStatus last = ActionStatus::kRunning;
|
|
int i = 0;
|
|
for (double t = kFirstTick; t <= t_end + 1e-9; t += kTickPeriod, ++i)
|
|
{
|
|
make(rig, i, t);
|
|
last = rig.handler->update(robot::Time(t)).status;
|
|
if (last != ActionStatus::kRunning)
|
|
{
|
|
if (stopped_at != nullptr)
|
|
{
|
|
*stopped_at = t;
|
|
}
|
|
return last;
|
|
}
|
|
}
|
|
return last;
|
|
}
|
|
|
|
/// @brief Lượt dò tiêu chuẩn: mẫu quanh (x, y, yaw) với nhiễu răng cưa biên độ @p noise_xy.
|
|
ActionStatus runSampling(Rig& rig, double x, double y, double yaw, double noise_xy,
|
|
double noise_yaw = 0.0, double t_end = 101.5,
|
|
double* stopped_at = nullptr)
|
|
{
|
|
EXPECT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart)));
|
|
|
|
return runTicks(
|
|
rig, t_end,
|
|
[&](Rig& r, int i, double t) {
|
|
// Nhiễu răng cưa: đổi dấu mỗi mẫu — biên độ đúng bằng `noise`, không phụ thuộc bộ sinh ngẫu
|
|
// nhiên. Stamp lấy luôn theo `t` nên luôn tăng, không mẫu nào bị coi là trùng.
|
|
const double s = (i % 2 == 0) ? 1.0 : -1.0;
|
|
r.pushSample(x + s * noise_xy, y - s * noise_xy, yaw + s * noise_yaw, t);
|
|
},
|
|
stopped_at);
|
|
}
|
|
|
|
// ================================================================================================
|
|
// Đường thành công
|
|
// ================================================================================================
|
|
|
|
TEST(FrameSampler, LoadsAndPublishesAStableFrame)
|
|
{
|
|
Rig rig;
|
|
ASSERT_TRUE(rig.loaded);
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
|
|
double stopped_at = 0.0;
|
|
EXPECT_EQ(runSampling(rig, 2.0, 1.0, 0.5, 0.002, 0.0, 101.5, &stopped_at),
|
|
ActionStatus::kSucceeded);
|
|
|
|
// Dò tốt ngay từ đầu thì chốt ở cửa sổ ĐẦU TIÊN — cửa sổ trượt không được làm chậm ca thuận lợi.
|
|
EXPECT_NEAR(stopped_at, kFirstVerdict, 0.03);
|
|
|
|
double x = 0.0, y = 0.0, yaw = 0.0;
|
|
ASSERT_TRUE(rig.readOutput(x, y, yaw));
|
|
EXPECT_NEAR(x, 2.0, 0.005);
|
|
EXPECT_NEAR(y, 1.0, 0.005);
|
|
EXPECT_NEAR(yaw, 0.5, 0.01);
|
|
}
|
|
|
|
TEST(FrameSampler, MedianRejectsAnOutlier)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
|
|
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart)));
|
|
|
|
// Outlier đặt ở GIỮA cửa sổ được chấm (t ~ 100.9), không phải ở đầu lượt: cửa sổ trượt chỉ dài
|
|
// 1 s nên mẫu của 0.3 s đầu đã bị cắt ra ngoài trước khi có phán quyết nào.
|
|
ASSERT_EQ(runTicks(rig, 101.5,
|
|
[](Rig& r, int, double t) {
|
|
// Một mẫu nhận nhầm chân kệ khác, lệch 1 m. Trung bình bị kéo ~1 cm; trung vị
|
|
// thì không.
|
|
const double x = (std::fabs(t - 100.9) < 0.005) ? 3.0 : 2.0;
|
|
r.pushSample(x, 1.0, 0.0, t);
|
|
}),
|
|
ActionStatus::kSucceeded);
|
|
|
|
double x = 0.0, y = 0.0, yaw = 0.0;
|
|
ASSERT_TRUE(rig.readOutput(x, y, yaw));
|
|
EXPECT_NEAR(x, 2.0, 0.001) << "trung vị phải loại được outlier";
|
|
}
|
|
|
|
TEST(FrameSampler, AveragesYawAcrossTheWrapAround)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
|
|
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart)));
|
|
|
|
// Mẫu nằm hai bên đường cắt ±π. Trung bình SỐ HỌC cho ra ~0 — lệch 180°, robot vào trạm ngược đầu.
|
|
ASSERT_EQ(runTicks(rig, 101.5,
|
|
[](Rig& r, int i, double t) {
|
|
const double yaw = (i % 2 == 0) ? (M_PI - 0.01) : (-M_PI + 0.01);
|
|
r.pushSample(2.0, 1.0, yaw, t);
|
|
}),
|
|
ActionStatus::kSucceeded);
|
|
|
|
double x = 0.0, y = 0.0, yaw = 0.0;
|
|
ASSERT_TRUE(rig.readOutput(x, y, yaw));
|
|
EXPECT_NEAR(std::fabs(yaw), M_PI, 0.02) << "gộp góc phải dùng vector đơn vị, không phải trung bình";
|
|
}
|
|
|
|
TEST(FrameSampler, SimulatedGoalIsFrozenInTheGlobalFrame)
|
|
{
|
|
Rig rig("actions_detect_simulated", "DetectPallet");
|
|
ASSERT_TRUE(rig.loaded);
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
|
|
rig.pushTransform(kGlobalFrame, "base_link", 10.0, 5.0, M_PI_2, 100.0);
|
|
EXPECT_TRUE(rig.handler->start(makeAction("", "DetectPallet"), robot::Time(100.0)));
|
|
EXPECT_EQ(rig.handler->update(robot::Time(100.0)).status, ActionStatus::kSucceeded);
|
|
|
|
double x = 0.0, y = 0.0, yaw = 0.0;
|
|
ASSERT_TRUE(rig.readOutput(x, y, yaw));
|
|
EXPECT_NEAR(x, 9.8, 1e-6);
|
|
EXPECT_NEAR(y, 3.5, 1e-6);
|
|
EXPECT_NEAR(yaw, M_PI_2, 1e-6);
|
|
|
|
// Output là static trong map, không được chạy theo parent ở cycle sau.
|
|
rig.pushTransform(kGlobalFrame, "base_link", 20.0, 5.0, M_PI_2, 101.0);
|
|
ASSERT_TRUE(rig.readOutput(x, y, yaw));
|
|
EXPECT_NEAR(x, 9.8, 1e-6);
|
|
EXPECT_NEAR(y, 3.5, 1e-6);
|
|
}
|
|
|
|
// ================================================================================================
|
|
// Cửa sổ trượt — chờ hội tụ thay vì phán một lần
|
|
// ================================================================================================
|
|
|
|
TEST(FrameSampler, RetriesUntilTheDetectionConverges)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart)));
|
|
|
|
// Perception bám nhầm trong 2 s đầu (±0.10 m) rồi ổn định. Bản phán-một-lần fail ngay tại
|
|
// t = 101.2; bản cửa sổ trượt phải chờ tới khi cửa sổ sạch mẫu xấu.
|
|
double stopped_at = 0.0;
|
|
EXPECT_EQ(runTicks(
|
|
rig, 105.2,
|
|
[](Rig& r, int i, double t) {
|
|
const double s = (i % 2 == 0) ? 1.0 : -1.0;
|
|
const double noise = (t < 102.0) ? 0.10 : 0.001;
|
|
r.pushSample(2.0 + s * noise, 1.0, 0.0, t);
|
|
},
|
|
&stopped_at),
|
|
ActionStatus::kSucceeded);
|
|
|
|
// Không được chốt trước khi cửa sổ hết mẫu xấu: chốt sớm nghĩa là chấp nhận chính dữ liệu tản.
|
|
EXPECT_GT(stopped_at, 102.0);
|
|
EXPECT_LT(stopped_at, kTimeoutAt);
|
|
|
|
double x = 0.0, y = 0.0, yaw = 0.0;
|
|
ASSERT_TRUE(rig.readOutput(x, y, yaw));
|
|
EXPECT_NEAR(x, 2.0, 0.005) << "phải chốt theo dữ liệu ĐÃ ổn định, không lẫn giai đoạn nhiễu";
|
|
EXPECT_NEAR(y, 1.0, 0.005);
|
|
}
|
|
|
|
TEST(FrameSampler, HoldTimeDelaysTheCommit)
|
|
{
|
|
// hold_time = 0.5 trong namespace này. Cùng dữ liệu tốt như LoadsAndPublishesAStableFrame, nhưng
|
|
// phải giữ trạng thái đạt thêm 0.5 s mới được chốt — chặn cửa sổ tình cờ chụm.
|
|
Rig rig("actions_detect_hold");
|
|
ASSERT_TRUE(rig.loaded);
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
|
|
double stopped_at = 0.0;
|
|
EXPECT_EQ(runSampling(rig, 2.0, 1.0, 0.0, 0.002, 0.0, 103.0, &stopped_at),
|
|
ActionStatus::kSucceeded);
|
|
EXPECT_GE(stopped_at, kFirstVerdict + 0.5 - 0.03) << "chốt trước hold_time là bỏ qua cổng giữ";
|
|
EXPECT_LE(stopped_at, kFirstVerdict + 0.5 + 0.05);
|
|
}
|
|
|
|
// ================================================================================================
|
|
// Đường lỗi — mỗi ca phải fail được
|
|
// ================================================================================================
|
|
|
|
TEST(FrameSampler, FailsWhenDetectionStaysScatteredUntilTheTimeout)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
|
|
// max_spread_xy = 0.03 trong config test; nhiễu ±0.05 cho độ tản 0.14 m. Tản suốt cả `timeout`
|
|
// nên KHÔNG cửa sổ nào đạt — đây mới là ca đáng fail.
|
|
double stopped_at = 0.0;
|
|
EXPECT_EQ(runSampling(rig, 2.0, 1.0, 0.0, 0.05, 0.0, 105.2, &stopped_at),
|
|
ActionStatus::kFailed);
|
|
EXPECT_GE(stopped_at, kTimeoutAt) << "phải dùng hết timeout để chờ hội tụ, không bỏ cuộc sớm";
|
|
|
|
double x = 0.0, y = 0.0, yaw = 0.0;
|
|
EXPECT_FALSE(rig.readOutput(x, y, yaw)) << "dữ liệu tản thì KHÔNG được ghi frame nào";
|
|
}
|
|
|
|
TEST(FrameSampler, FailsWhenTheFrameNeverStopsMoving)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart)));
|
|
|
|
// Mỗi mẫu chụm với mẫu kề nó, nhưng cả chuỗi trôi 0.5 m/s: cửa sổ 1 s trải 0.5 m. Đây là dạng
|
|
// hỏng mà "so mẫu này với mẫu trước" bỏ lọt còn độ tản cửa sổ thì bắt được.
|
|
EXPECT_EQ(runTicks(rig, 105.2,
|
|
[](Rig& r, int i, double t) {
|
|
r.pushSample(2.0 + i * 0.005, 1.0, 0.0, t);
|
|
}),
|
|
ActionStatus::kFailed);
|
|
|
|
double x = 0.0, y = 0.0, yaw = 0.0;
|
|
EXPECT_FALSE(rig.readOutput(x, y, yaw)) << "đích còn trôi thì KHÔNG được chốt";
|
|
}
|
|
|
|
TEST(FrameSampler, FailsWithTooFewSamples)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart)));
|
|
|
|
rig.pushSample(2.0, 1.0, 0.0, 100.5);
|
|
rig.handler->update(robot::Time(100.5));
|
|
|
|
// min_samples = 10 trong config test. Một mẫu duy nhất thì không cửa sổ nào chấm được, và tới
|
|
// timeout phải fail — không được im lặng chờ mãi.
|
|
EXPECT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kRunning);
|
|
EXPECT_EQ(rig.handler->update(robot::Time(105.1)).status, ActionStatus::kFailed);
|
|
}
|
|
|
|
TEST(FrameSampler, DuplicateTimestampsDoNotCountAsSamples)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart)));
|
|
|
|
// TF cập nhật chậm hơn control loop: cùng một pose bị đọc hàng trăm lần. Không lọc theo timestamp
|
|
// thì min_samples mất hết ý nghĩa và một mẫu duy nhất trông như một cửa sổ đầy.
|
|
rig.pushSample(2.0, 1.0, 0.0, 100.5);
|
|
EXPECT_EQ(runTicks(rig, 105.2, [](Rig&, int, double) {}), ActionStatus::kFailed);
|
|
}
|
|
|
|
TEST(FrameSampler, FailsWhenTheRawFrameNeverAppears)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
|
|
const robot::Time t0 = robot::Time(100.0);
|
|
ASSERT_TRUE(rig.handler->start(makeAction(), t0));
|
|
|
|
EXPECT_EQ(rig.handler->update(robot::Time(100.5)).status, ActionStatus::kRunning);
|
|
// timeout = 5.0 trong config test.
|
|
EXPECT_EQ(rig.handler->update(robot::Time(105.1)).status, ActionStatus::kFailed);
|
|
}
|
|
|
|
TEST(FrameSampler, RefusesToStartWithoutAFrameParameter)
|
|
{
|
|
Rig rig;
|
|
ASSERT_NE(rig.handler, nullptr);
|
|
|
|
// Không có `goal_frame` và config cũng không khai `input_frame` -> không biết dò cái gì.
|
|
EXPECT_FALSE(rig.handler->start(makeAction(""), robot::Time(100.0)));
|
|
}
|
|
|
|
TEST(FrameSampler, RefusesToLoadWithoutATfBuffer)
|
|
{
|
|
// Handler cần TF; thiếu thì phải từ chối lúc NẠP, không phải lúc order đầu tiên tới.
|
|
robot::NodeHandle nh;
|
|
ActionRegistry registry; // context mặc định: tf == nullptr
|
|
EXPECT_FALSE(registry.loadFromConfig(nh, "actions_detect"));
|
|
EXPECT_EQ(registry.size(), 0u);
|
|
}
|
|
|
|
TEST(FrameSampler, RefusesOutputFrameEqualToInputFrame)
|
|
{
|
|
Rig rig("actions_detect_same_frame");
|
|
EXPECT_FALSE(rig.loaded) << "ghi đè chính frame thô là tranh chấp với bên publish nó";
|
|
EXPECT_EQ(rig.registry.size(), 0u);
|
|
}
|
|
|
|
TEST(FrameSampler, RefusesTimeoutShorterThanTheSamplingWindow)
|
|
{
|
|
Rig rig("actions_detect_bad_timeout");
|
|
EXPECT_FALSE(rig.loaded) << "action sẽ LUÔN hỏng — gần như chắc chắn gõ nhầm";
|
|
EXPECT_EQ(rig.registry.size(), 0u);
|
|
}
|
|
|
|
} // namespace
|
|
|
|
int main(int argc, char** argv)
|
|
{
|
|
#ifdef ACTION_CORE_TEST_CONFIG_DIR
|
|
setenv("PNKX_NAV_CORE_CONFIG_DIR", ACTION_CORE_TEST_CONFIG_DIR, 0);
|
|
#endif
|
|
#ifdef ACTION_CORE_TEST_LIBRARY_DIR
|
|
setenv("PNKX_NAV_CORE_LIBRARY_PATH", ACTION_CORE_TEST_LIBRARY_DIR, 0);
|
|
#endif
|
|
|
|
testing::InitGoogleTest(&argc, argv);
|
|
return RUN_ALL_TESTS();
|
|
}
|