feat: add the wall reflector detection action

Action handler that detects two flat reflective tape strips on a wall from a
raw LaserScan and publishes the stop-station target (and a marker frame) as
static TFs for the next move_to stage. Geometry comes from
dock_pattern_detector's ReflectorPairMatcher. The handler adds scan
freshness checks (stamp after settle, max age, strictly increasing stamps)
and a deadline for detections waiting on TF, derives lidar flip and tilt
from TF, and never reuses samples across pause/resume or runs.
This commit is contained in:
2026-11-12 11:16:38 +07:00
commit f115fd0efd
6 changed files with 1700 additions and 0 deletions

185
CMakeLists.txt Normal file
View File

@@ -0,0 +1,185 @@
cmake_minimum_required(VERSION 3.0.2)
project(wall_reflector_detection_action VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# ==================================================================================================
# Phát hiện chế độ build — theo mẫu dock_pattern_action, giữ cả hai:
# - catkin (`catkin_make` trong workspace phát triển)
# - standalone (root CMakeLists của pnkx_nav_core, không có catkin)
# ==================================================================================================
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
set(BUILDING_WITH_CATKIN TRUE)
message(STATUS "Building wall_reflector_detection_action with Catkin")
else()
set(BUILDING_WITH_CATKIN FALSE)
message(STATUS "Building wall_reflector_detection_action with Standalone CMake")
endif()
find_package(Boost REQUIRED)
find_package(Threads REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(Eigen3 REQUIRED)
# tf3 không được build bởi workspace này (cài sẵn ở /usr/local/lib/libtf3.so).
find_library(TF3_LIBRARY
NAMES tf3
PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu
)
if(NOT TF3_LIBRARY)
message(FATAL_ERROR "tf3 not found — install tf3 (/usr/local/lib/libtf3.so) before building")
endif()
if(BUILDING_WITH_CATKIN)
find_package(catkin REQUIRED COMPONENTS
action_core
dock_pattern_detector
robot_line_extraction
robot_sensor_ports
robot_cpp
robot_sensor_msgs
)
catkin_package(
CATKIN_DEPENDS
action_core
dock_pattern_detector
robot_line_extraction
robot_sensor_ports
robot_cpp
robot_sensor_msgs
)
else()
# Standalone cần root đăng ký các dependency trước package này; P2 chưa sửa root CMakeLists.
set(WALL_REFLECTOR_DETECTION_ACTION_STANDALONE_LIBRARIES
action_core
dock_pattern_detector
robot_line_extraction
robot_sensor_ports
robot_cpp
robot_sensor_msgs
)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
endif()
# Handler là plugin Boost.DLL, nạp theo khoá `library_path` trong YAML — KHÔNG link thẳng vào ai.
add_library(wall_reflector_detection_action_handler SHARED
plugins/wall_reflector_detection_action_handler.cpp
)
target_compile_options(wall_reflector_detection_action_handler PRIVATE -Wall -Wextra)
# Header của dependency vào dạng SYSTEM: robot_cpp sinh hàng trăm warning riêng của nó — để lẫn vào
# thì warning của chính gói này vô hình. Gắn vào TARGET, không `include_directories()` toàn thư mục.
target_include_directories(wall_reflector_detection_action_handler SYSTEM
PRIVATE
${Boost_INCLUDE_DIRS}
${EIGEN3_INCLUDE_DIRS}
)
if(BUILDING_WITH_CATKIN)
target_include_directories(wall_reflector_detection_action_handler SYSTEM
PRIVATE ${catkin_INCLUDE_DIRS})
add_dependencies(wall_reflector_detection_action_handler ${catkin_EXPORTED_TARGETS})
target_link_libraries(wall_reflector_detection_action_handler
PUBLIC
${catkin_LIBRARIES}
PRIVATE
Boost::boost
yaml-cpp
Threads::Threads
${CMAKE_DL_LIBS}
${TF3_LIBRARY}
)
install(TARGETS wall_reflector_detection_action_handler
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
)
else()
target_link_libraries(wall_reflector_detection_action_handler
PUBLIC
${WALL_REFLECTOR_DETECTION_ACTION_STANDALONE_LIBRARIES}
PRIVATE
Boost::boost
yaml-cpp
Threads::Threads
${CMAKE_DL_LIBS}
${TF3_LIBRARY}
)
# Plugin được nạp bằng boost::dll theo TÊN FILE, và `PluginLoaderHelper` tra trong thư mục build.
set_target_properties(wall_reflector_detection_action_handler PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
BUILD_RPATH "${CMAKE_BINARY_DIR}"
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
)
include(GNUInstallDirs)
install(TARGETS wall_reflector_detection_action_handler
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
endif()
# Test chạy qua `catkin_add_gtest` và cần `CATKIN_DEVEL_PREFIX` để biết plugin nằm ở đâu, nên chỉ
# có ở nhánh catkin. Ở standalone, plugin vẫn build — chỉ không có test.
if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN)
if(NOT COMMAND catkin_add_gtest)
message(FATAL_ERROR "catkin_add_gtest NOT FOUND")
endif()
catkin_add_gtest(wall_reflector_detection_action_test test/wall_reflector_detection_action_test.cpp)
if(TARGET wall_reflector_detection_action_test)
# catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make` thường.
set_target_properties(wall_reflector_detection_action_test PROPERTIES EXCLUDE_FROM_ALL FALSE)
target_compile_options(wall_reflector_detection_action_test PRIVATE -Wall -Wextra)
target_include_directories(wall_reflector_detection_action_test PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/../../../../Libraries/dock_pattern_detector/test")
target_include_directories(wall_reflector_detection_action_test SYSTEM
PRIVATE ${catkin_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIRS}
)
# Plugin KHÔNG được link thẳng: nó chỉ export alias Boost.DLL và được nạp qua ActionRegistry,
# đúng đường mà runtime đi.
target_link_libraries(wall_reflector_detection_action_test
${catkin_LIBRARIES}
${Boost_LIBRARIES}
yaml-cpp
pthread
${CMAKE_DL_LIBS}
${TF3_LIBRARY}
)
add_dependencies(wall_reflector_detection_action_test wall_reflector_detection_action_handler)
# ctest không mang theo PNKX_NAV_CORE_CONFIG_DIR hay LD_LIBRARY_PATH của shell.
target_compile_definitions(wall_reflector_detection_action_test PRIVATE
WALL_REFLECTOR_DETECTION_ACTION_TEST_CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/config"
WALL_REFLECTOR_DETECTION_ACTION_TEST_LIBRARY_DIR="${CATKIN_DEVEL_PREFIX}/lib"
)
endif()
endif()

82
README.md Normal file
View File

@@ -0,0 +1,82 @@
# `wall_reflector_detection_action`
Plugin Boost.DLL `WallReflectorDetectionActionHandler` đọc một `LaserScan` thô từ
`robot_sensor_ports::SensorReader`, gọi `ReflectorPairMatcher`, lọc marker theo nhiều scan và ghi TF
tĩnh cho trạm dừng. Gói không phát vận tốc. P2 chưa có cấu hình runtime, world hay chuỗi mission.
## Contract
- `scan_topic` phải được khai trong sensor store và đưa đủ `ranges`, `intensities`, frame và stamp
của cùng một scan. Ngưỡng cường độ và kích thước tape phải đo trên đúng LiDAR và tường thực.
- `prior_frame` là frame thân robot để khai ROI/prior. TF gắn lidar được tra để xác định flip,
hướng trước/sau và độ nghiêng; quá 0.0873 rad hoặc nhìn ngược `entry_direction` thì fail. Không
có khóa lật lidar. P1 trả marker trong `prior_frame`; plugin tra `global_frame <- prior_frame`
tại stamp scan, không thay bằng TF mới nhất.
- `marker_frame` mặc định `wall_reflector_frame`: gốc ở tâm cặp, +X hướng từ tường về sensor.
`output_frame` mặc định `wall_reflector_target`: `C + offset_x*n + offset_y*t`,
`yaw = marker_yaw + offset_yaw + (forward ? π : 0)`. Cả hai tính từ **cùng marker đã lọc**.
- Ghi marker trước, target sau và chỉ báo thành công khi cả hai phép ghi thành công. `marker_frame`
rỗng thì chỉ ghi target. Hai phép ghi TF không nguyên tử; nếu ghi target lỗi, marker có thể đã đổi.
TF tĩnh cũ vẫn tồn tại khi lượt sau fail/cancel: mission phải ràng buộc chặng `move_to` với thành
công của **lượt hiện tại**, không chỉ kiểm tra frame tồn tại. Không chạy đồng thời hai chủ ghi cùng
frame; ownership và chặn direct consumer cần kiểm chứng ở P3.
- Dữ liệu phải mới, sau settle, tăng stamp nghiêm ngặt và không lặp cursor. Pending TF giữ tối đa
`pending_tf_timeout` và `max_scan_age`; detection hợp lệ mới hơn thay pending cũ. Pause/resume,
cancel và nhảy đồng hồ về trước/quay ngược được xử lý trong vòng đời action; resume bắt đầu settle
lại. Clock scan và `now` phải cùng miền thời gian. Settling không tự chứng minh robot đứng yên.
Host `amr_control` đã dời stamp ROS (sim time khi `use_sim_time`) sang wall clock bằng
`toWallStamp` (`Controllers/Packages/amr_control/src/sensor_converter.cpp`), nên chạy được cả sim
lẫn robot. Host `Test/nav_ros_bridge` chép nguyên stamp: dưới Gazebo `use_sim_time` mọi scan sẽ bị
coi là `scan stale` và action luôn timeout — phải dời stamp như `amr_control` trước khi dùng host đó.
- `ambiguous` làm xóa cả mẫu đang lọc/pending. Timeout trả lý do cuối; cấu hình thiếu, TF mount sai,
profile lạ hoặc lỗi ghi TF báo lỗi. Các lý do P1 như `wall_support`, `width`, `spacing`,
`ambiguous`, `capacity_*` được chuyển vào thông điệp chờ/timeout.
## Khóa handler
Các khóa đặt dưới namespace của handler trong file test; đây là schema đề xuất cho P3:
| Khóa | Default | Miền / đơn vị |
|---|---|---|
| `action_types` | `[DetectWallReflectors]` | danh sách chuỗi không rỗng, không trùng |
| `scan_topic`, `default_profile` | bắt buộc | topic LaserScan trong store; profile tồn tại |
| `output_frame`, `marker_frame` | `wall_reflector_target`, `wall_reflector_frame` | marker rỗng để tắt; output bắt buộc, các frame không trùng nhau/global/base |
| `prior_frame`, `profile_param_key` | `base_link`, `reflector_profile` | chuỗi không rỗng |
| `entry_direction` | `forward` | `forward` hoặc `backward` |
| `min_range`, `max_range` | 0.1, 3.0 | [m] 0 ≤ min < max; giao với range limits trong scan |
| `zero_range_is_no_echo` | true | bool; P1 loại 0 ở cả hai chế độ |
| `max_candidates`, `max_pairs`, `max_scan_rays` | 16, 120, 4096 | nguyên lần lượt 2–128, 1–8128, 2–65536 |
| `settle_delay`, `timeout` | 0.4, 15 | [s] ≥0; timeout > settle + window + hold |
| `max_scan_age`, `max_future_skew`, `pending_tf_timeout` | 0.3, 0.05, 0.2 | [s] >0, ≥0, >0 và pending ≤ max age |
| `sample_window`, `min_samples` | 1.0, 5 | [s] >0; số mẫu ≥3 |
| `max_spread_xy`, `max_spread_yaw`, `hold_time` | 0.03, 0.05, 0 | [m], [rad], [s]; spread >0, yaw ≤π, hold ≥0 |
| `jump_threshold`, `cluster_recency` | 0, 0.3 | [m] 0 hoặc > spread xy; [s] >0 |
| `min_cluster_fraction`, `min_cluster_samples` | 0.6, 3 | (0.5,1]; 3..min_samples |
| `debug/state`, `debug/detect`, `debug/skip` | true | bool; log lỗi không tắt được |
Mỗi `profiles/<name>` nạp các khóa sau vào `ReflectorPairProfile`. Các giá trị **bắt buộc** không có
mặc định dùng được và được `validate()` kiểm lúc configure:
| Nhóm khóa | Default / kiểm tra |
|---|---|
| `tape_width`, `width_tolerance`, `tape_spacing`, `spacing_tolerance` | bắt buộc [m]; width >0, spacing > width, dung sai >0 và nhỏ hơn đại lượng tương ứng |
| `tape_min_intensity`, `tape_core_intensity` | bắt buộc [đơn vị driver]; ≥0 và core ≥ min |
| `tape_min_points` | 3 tia; ≥3 |
| `tape_bloom_max_angle`, `tape_plateau_min_fraction` | bắt buộc; [rad] [0,π), tỉ lệ (0,1] |
| `edge_bias_bound`, `max_edge_uncertainty`, `min_ray_wall_cos` | bắt buộc [m] ≥0, bắt buộc [m] >0, 0.35 trong (0,1] |
| `wall_min_points_each_side`, `wall_min_span` | 5 tia ≥3; span bắt buộc [m] > spacing |
| `wall_max_rms`, `wall_max_residual`, `wall_max_gap`, `wall_merge_distance` | bắt buộc [m]; RMS >0, max ≥ RMS, gap ≥ tape width, merge >0 |
| `wall_max_extrapolation` | 0 [m], ≥0 |
| `has_prior`, `prior_x`, `prior_y`, `prior_yaw` | false, 0, 0, 0; finite [m,m,rad] |
| `prior_position_tolerance`, `prior_yaw_tolerance` | bắt buộc khi `has_prior`; >0 [m], (0,π] [rad] |
| `search_center_yaw`, `search_fov` | 0, π [rad]; finite, FOV trong (0,π] |
| `offset_x`, `offset_y`, `offset_yaw` | bắt buộc >0 [m], 0 [m], 0 [rad]; finite |
`test/config/action_handlers_params.yaml` chỉ chứa số tổng hợp, không dùng làm profile robot. Test
include trực tiếp `dock_pattern_detector/test/wall_scan_sim.h`; package detector phải nằm cạnh package
này trong source tree khi build test. Không có khóa `filter_enabled`.
`PoseSampleFilter` hiện tự log tiến trình và có cấp phát nội bộ khi lưu diagnostics; các debug switch
của handler không điều khiển log của thư viện đó và P2 chưa chứng minh không cấp phát trong mọi tick.
Cần xem xét API/budget của `action_core` nếu đây là yêu cầu cứng. Hiệu chuẩn, nghiệm thu robot, xác nhận
đường sensor→bridge→store và chặng điều hướng thuộc các pha sau.

34
package.xml Normal file
View File

@@ -0,0 +1,34 @@
<package>
<name>wall_reflector_detection_action</name>
<version>0.1.0</version>
<description>Action plugin phát hiện hai dải phản quang trên tường bằng LiDAR 2D.</description>
<author>DuongTD</author>
<maintainer email="tdd@gmail.com">DuongTD</maintainer>
<license>BSD</license>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>action_core</build_depend>
<run_depend>action_core</run_depend>
<build_depend>dock_pattern_detector</build_depend>
<run_depend>dock_pattern_detector</run_depend>
<build_depend>robot_line_extraction</build_depend>
<run_depend>robot_line_extraction</run_depend>
<build_depend>robot_sensor_ports</build_depend>
<run_depend>robot_sensor_ports</run_depend>
<build_depend>robot_cpp</build_depend>
<run_depend>robot_cpp</run_depend>
<build_depend>robot_sensor_msgs</build_depend>
<run_depend>robot_sensor_msgs</run_depend>
<build_depend>tf3</build_depend>
<run_depend>tf3</run_depend>
<build_depend>yaml-cpp</build_depend>
<run_depend>yaml-cpp</run_depend>
</package>

View File

@@ -0,0 +1,734 @@
#include <action_core/action_handler.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <yaml-cpp/yaml.h>
#include <robot/robot.h>
#include <robot_sensor_msgs/LaserScan.h>
#include <tf3/buffer_core.h>
#include <action_core/action_abi.h>
#include <action_core/pose_sample_filter.h>
#include <dock_pattern_detector/reflector_pair_matcher.h>
#include <robot_sensor_ports/sensor_reader.h>
#include <robot_sensor_ports/sensor_types.h>
namespace action_core
{
namespace
{
constexpr double kPi = 3.14159265358979323846;
constexpr double kMaxTilt = 0.0873;
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 secondsBetween(const robot::Time& first, const robot::Time& second)
{
return static_cast<double>(static_cast<int64_t>(first.toNSec()) -
static_cast<int64_t>(second.toNSec())) * 1e-9;
}
double wrap(double angle)
{
return std::atan2(std::sin(angle), std::cos(angle));
}
template <typename T>
void load(robot::NodeHandle& nh, const char* key, T& value)
{
nh.param(key, value, value);
}
} // namespace
/**
* @brief Adapter scan → marker → hai TF tĩnh, không điều khiển vận tốc.
*
* Sensor và TF là cổng non-owning của context. Marker P1 nằm trong prior_frame; TF từ prior_frame
* sang global_frame được tra đúng timestamp scan trước khi đưa marker vào PoseSampleFilter.
*/
class WallReflectorDetectionActionHandler final : public ActionHandler
{
public:
static ActionHandler::Ptr create()
{
return std::make_shared<WallReflectorDetectionActionHandler>();
}
bool configure(const std::string& name, const ActionContext& context,
robot::NodeHandle& nh) override
{
initialized_ = false;
active_ = false;
paused_ = false;
name_ = name;
ctx_ = context;
if (!ctx_.tf || !ctx_.sensors || ctx_.global_frame.empty() || ctx_.robot_base_frame.empty())
{
robot::log_error("[wall_reflector] '%s': TF, sensor store and context frames are required.",
name_.c_str());
return false;
}
nh.param("action_types", action_types_, std::vector<std::string>{"DetectWallReflectors"});
nh.param("output_frame", output_frame_, std::string("wall_reflector_target"));
nh.param("marker_frame", marker_frame_, std::string("wall_reflector_frame"));
nh.param("scan_topic", scan_topic_, std::string());
nh.param("prior_frame", prior_frame_, std::string("base_link"));
nh.param("default_profile", default_profile_, std::string());
nh.param("profile_param_key", profile_param_key_, std::string("reflector_profile"));
nh.param("settle_delay", settle_delay_, 0.4);
nh.param("timeout", timeout_, 15.0);
nh.param("max_scan_age", max_scan_age_, 0.3);
nh.param("max_future_skew", max_future_skew_, 0.05);
nh.param("pending_tf_timeout", pending_tf_timeout_, 0.2);
load(nh, "min_range", limits_.min_range);
load(nh, "max_range", limits_.max_range);
load(nh, "zero_range_is_no_echo", limits_.zero_range_is_no_echo);
int max_candidates = 16;
int max_pairs = 120;
int max_scan_rays = 4096;
load(nh, "max_candidates", max_candidates);
load(nh, "max_pairs", max_pairs);
load(nh, "max_scan_rays", max_scan_rays);
std::string direction = "forward";
load(nh, "entry_direction", direction);
robot::NodeHandle debug(nh, "debug");
debug.param("state", debug_state_, true);
debug.param("detect", debug_detect_, true);
debug.param("skip", debug_skip_, true);
if (action_types_.empty() || std::any_of(action_types_.begin(), action_types_.end(),
[](const std::string& value) { return value.empty(); }))
return configError("action_types must contain nonempty unique types");
std::vector<std::string> sorted = action_types_;
std::sort(sorted.begin(), sorted.end());
if (std::adjacent_find(sorted.begin(), sorted.end()) != sorted.end())
return configError("action_types contains duplicates");
if (output_frame_.empty() || output_frame_ == ctx_.global_frame ||
output_frame_ == ctx_.robot_base_frame || output_frame_ == prior_frame_ ||
(!marker_frame_.empty() && (marker_frame_ == output_frame_ ||
marker_frame_ == ctx_.global_frame || marker_frame_ == ctx_.robot_base_frame ||
marker_frame_ == prior_frame_)))
return configError("output_frame/marker_frame conflict with each other or context frames");
if (scan_topic_.empty() || prior_frame_.empty() || default_profile_.empty() ||
profile_param_key_.empty())
return configError("scan_topic, prior_frame, default_profile and profile_param_key are required");
if (!robot_sensor_ports::has<robot_sensor_msgs::LaserScan>(*ctx_.sensors, scan_topic_))
return configError("scan_topic is not a LaserScan in sensor store");
if (direction != "forward" && direction != "backward")
return configError("entry_direction must be forward or backward");
forward_ = direction == "forward";
if (!std::isfinite(settle_delay_) || settle_delay_ < 0.0 || !std::isfinite(timeout_) ||
timeout_ <= 0.0 || !std::isfinite(max_scan_age_) || max_scan_age_ <= 0.0 ||
!std::isfinite(max_future_skew_) || max_future_skew_ < 0.0 ||
!std::isfinite(pending_tf_timeout_) || pending_tf_timeout_ <= 0.0 ||
pending_tf_timeout_ > max_scan_age_)
return configError("invalid settle_delay, timeout or freshness limits");
if (!std::isfinite(limits_.min_range) || !std::isfinite(limits_.max_range) ||
limits_.min_range < 0.0 || limits_.max_range <= limits_.min_range ||
max_candidates < 2 || max_candidates > 128 || max_pairs < 1 || max_pairs > 8128 ||
max_scan_rays < 2 || max_scan_rays > 65536)
return configError("invalid matcher range or capacity limits");
limits_.max_candidates = static_cast<std::size_t>(max_candidates);
limits_.max_pairs = static_cast<std::size_t>(max_pairs);
limits_.max_scan_rays = static_cast<std::size_t>(max_scan_rays);
if (!loadProfiles(nh) || !loadFilter(nh))
return false;
initialized_ = true;
robot::log_info("[wall_reflector] '%s': scan=%s prior=%s target=%s marker=%s direction=%s "
"profiles=%zu default=%s debug/state=%s debug/detect=%s debug/skip=%s",
name_.c_str(), scan_topic_.c_str(), prior_frame_.c_str(), output_frame_.c_str(),
marker_frame_.c_str(), direction.c_str(), profiles_.size(), default_profile_.c_str(),
debug_state_ ? "on" : "off", debug_detect_ ? "on" : "off",
debug_skip_ ? "on" : "off");
return true;
}
std::vector<std::string> supportedActionTypes() const override { return action_types_; }
bool start(const robot_protocol_msgs::Action& action, const robot::Time& now) override
{
active_ = false;
if (!initialized_)
return false;
clearRun(now);
started_at_ = now;
paused_ = false;
action_id_ = action.actionId;
std::string selected = default_profile_;
for (const auto& parameter : action.actionParameters)
if (parameter.key == profile_param_key_ && !parameter.value.empty())
selected = parameter.value;
const auto found = profiles_.find(selected);
if (found == profiles_.end())
{
robot::log_error("[wall_reflector] '%s': unknown profile '%s'.", name_.c_str(), selected.c_str());
return false;
}
std::string error;
if (!matcher_.configure(found->second, error))
{
robot::log_error("[wall_reflector] '%s': profile '%s': %s", name_.c_str(), selected.c_str(), error.c_str());
return false;
}
active_profile_ = found->second;
active_ = true;
if (debug_state_)
robot::log_info("[wall_reflector][debug] '%s': started profile '%s'.", name_.c_str(), selected.c_str());
return true;
}
ActionTick update(const robot::Time& now) override
{
ActionTick tick;
if (!initialized_ || !active_)
{
tick.status = ActionStatus::kFailed;
tick.message = "wall_reflector: not active";
return tick;
}
if (paused_)
return tick;
if (now < last_now_)
{
clearRun(now);
started_at_ = now;
noteReason("clock moved backwards; waiting for new scans");
}
last_now_ = now;
if (secondsBetween(now, started_at_) >= timeout_)
{
active_ = false;
tick.status = ActionStatus::kFailed;
tick.message = "wall_reflector timeout: " +
(last_reason_.empty() ? std::string("insufficient samples") : last_reason_);
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), tick.message.c_str());
return tick;
}
if (secondsBetween(now, settle_start_) >= settle_delay_)
processScan(now);
if (!mount_error_.empty())
{
active_ = false;
tick.status = ActionStatus::kFailed;
tick.message = mount_error_;
return tick;
}
if (filter_.pruneExpired(now))
filter_.evaluate(now);
if (have_sample_stamp_ && !fresh(last_sample_stamp_, now))
{
filter_.reset();
have_sample_stamp_ = false;
noteReason("latest filter scan stale");
}
if (have_sample_stamp_ && filter_.windowSize() > 0 && filter_.holdSatisfied(now))
{
active_ = false;
if (!publish(filter_.holdPose(), now))
{
tick.status = ActionStatus::kFailed;
tick.message = "wall_reflector: failed to publish output TF";
return tick;
}
tick.status = ActionStatus::kSucceeded;
tick.message = marker_frame_.empty() ? "wall_reflector: target published"
: "wall_reflector: marker and target published";
return tick;
}
if (reason_dirty_)
{
tick.message = last_reason_;
reason_dirty_ = false;
}
return tick;
}
void pause(const robot::Time& now) override
{
if (active_ && !paused_)
{
paused_ = true;
paused_at_ = now;
filter_.reset();
pending_valid_ = false;
have_sample_stamp_ = false;
if (debug_state_)
robot::log_info("[wall_reflector][debug] '%s': paused.", name_.c_str());
}
}
void resume(const robot::Time& now) override
{
if (active_ && paused_)
{
if (now >= paused_at_)
started_at_ += now - paused_at_;
else
started_at_ = now;
clearRun(now);
paused_ = false;
if (debug_state_)
robot::log_info("[wall_reflector][debug] '%s': resumed; settling again.", name_.c_str());
}
}
void cancel() override
{
active_ = false;
paused_ = false;
pending_valid_ = false;
have_sample_stamp_ = false;
filter_.reset();
if (debug_state_)
robot::log_info("[wall_reflector][debug] '%s': cancelled.", name_.c_str());
}
private:
bool configError(const char* message)
{
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), message);
return false;
}
bool loadProfiles(robot::NodeHandle& nh)
{
YAML::Node profiles;
if (!nh.getParam("profiles", profiles) || !profiles.IsMap() || profiles.size() == 0)
return configError("profiles must be a nonempty map");
profiles_.clear();
for (const auto& entry : profiles)
{
const std::string key = entry.first.as<std::string>();
robot::NodeHandle p(nh, "profiles/" + key);
dock_pattern_detector::ReflectorPairProfile profile;
load(p, "tape_width", profile.tape_width);
load(p, "width_tolerance", profile.width_tolerance);
load(p, "tape_spacing", profile.tape_spacing);
load(p, "spacing_tolerance", profile.spacing_tolerance);
load(p, "tape_min_intensity", profile.tape_min_intensity);
load(p, "tape_core_intensity", profile.tape_core_intensity);
load(p, "tape_bloom_max_angle", profile.tape_bloom_max_angle);
load(p, "tape_plateau_min_fraction", profile.tape_plateau_min_fraction);
load(p, "edge_bias_bound", profile.edge_bias_bound);
load(p, "max_edge_uncertainty", profile.max_edge_uncertainty);
load(p, "min_ray_wall_cos", profile.min_ray_wall_cos);
load(p, "wall_min_span", profile.wall_min_span);
load(p, "wall_max_rms", profile.wall_max_rms);
load(p, "wall_max_residual", profile.wall_max_residual);
load(p, "wall_max_gap", profile.wall_max_gap);
load(p, "wall_max_extrapolation", profile.wall_max_extrapolation);
load(p, "wall_merge_distance", profile.wall_merge_distance);
load(p, "has_prior", profile.has_prior);
load(p, "prior_x", profile.prior_x);
load(p, "prior_y", profile.prior_y);
load(p, "prior_yaw", profile.prior_yaw);
load(p, "prior_position_tolerance", profile.prior_position_tolerance);
load(p, "prior_yaw_tolerance", profile.prior_yaw_tolerance);
load(p, "search_center_yaw", profile.search_center_yaw);
load(p, "search_fov", profile.search_fov);
load(p, "offset_x", profile.offset_x);
load(p, "offset_y", profile.offset_y);
load(p, "offset_yaw", profile.offset_yaw);
int tape_points = static_cast<int>(profile.tape_min_points);
int wall_points = static_cast<int>(profile.wall_min_points_each_side);
load(p, "tape_min_points", tape_points);
load(p, "wall_min_points_each_side", wall_points);
profile.tape_min_points = static_cast<std::size_t>(std::max(0, tape_points));
profile.wall_min_points_each_side = static_cast<std::size_t>(std::max(0, wall_points));
std::string error;
if (!profile.validate(error))
{
robot::log_error("[wall_reflector] '%s': profile '%s': %s", name_.c_str(), key.c_str(), error.c_str());
return false;
}
profiles_[key] = profile;
}
if (profiles_.find(default_profile_) == profiles_.end())
return configError("default_profile does not exist");
return true;
}
bool loadFilter(robot::NodeHandle& nh)
{
PoseSampleFilterConfig config;
config.enabled = true;
nh.param("sample_window", config.sample_window, 1.0);
nh.param("min_samples", config.min_samples, 5);
nh.param("max_spread_xy", config.max_spread_xy, 0.03);
nh.param("max_spread_yaw", config.max_spread_yaw, 0.05);
nh.param("hold_time", config.hold_time, 0.0);
nh.param("jump_threshold", config.jump_threshold, 0.0);
nh.param("cluster_recency", config.cluster_recency, 0.3);
nh.param("min_cluster_fraction", config.min_cluster_fraction, 0.6);
nh.param("min_cluster_samples", config.min_cluster_samples, 3);
if (config.min_samples < 3 || config.max_spread_yaw > kPi ||
!std::isfinite(config.cluster_recency) || config.cluster_recency <= 0.0 ||
!std::isfinite(config.min_cluster_fraction) || config.min_cluster_fraction <= 0.5 ||
config.min_cluster_fraction > 1.0 || config.min_cluster_samples < 3 ||
config.min_cluster_samples > config.min_samples ||
timeout_ <= settle_delay_ + config.sample_window + config.hold_time)
return configError("invalid filter limits or timeout");
return filter_.configure(config, name_);
}
void clearRun(const robot::Time& now)
{
filter_.reset();
filter_.setLabels(scan_topic_, ctx_.global_frame);
settle_start_ = now;
last_now_ = now;
scan_cursor_ = 0;
pending_valid_ = false;
have_seen_stamp_ = false;
have_sample_stamp_ = false;
mount_valid_ = false;
mount_error_.clear();
last_reason_.clear();
reason_dirty_ = false;
have_skip_log_ = false;
}
void noteReason(const std::string& reason)
{
if (reason != last_reason_)
{
last_reason_ = reason;
reason_dirty_ = true;
if (debug_skip_ && (!have_skip_log_ || secondsBetween(last_now_, last_skip_log_) >= 1.0))
{
robot::log_info("[wall_reflector][debug] '%s': %s", name_.c_str(), reason.c_str());
last_skip_log_ = last_now_;
have_skip_log_ = true;
}
}
}
const char* freshnessError(const robot::Time& stamp, const robot::Time& now) const
{
if (stamp.isZero())
return "scan stamp is zero";
if (secondsBetween(stamp, settle_start_) < settle_delay_)
return "scan before settle";
const double age = secondsBetween(now, stamp);
if (!std::isfinite(age) || age < -max_future_skew_)
return "scan future beyond allowed skew";
if (age > max_scan_age_)
return "scan stale";
return nullptr;
}
bool fresh(const robot::Time& stamp, const robot::Time& now) const
{
return freshnessError(stamp, now) == nullptr;
}
bool ensureMount(const std::string& scan_frame)
{
if (mount_valid_ && scan_frame_ == scan_frame)
return true;
if (scan_frame.empty() || scan_frame == output_frame_ ||
(!marker_frame_.empty() && scan_frame == marker_frame_))
{
mount_error_ = "invalid scan frame or output frame conflict";
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), mount_error_.c_str());
return false;
}
tf3::TransformStampedMsg prior_tf;
tf3::TransformStampedMsg base_tf;
try
{
prior_tf = ctx_.tf->lookupTransform(prior_frame_, scan_frame, tf3::Time());
base_tf = ctx_.tf->lookupTransform(ctx_.robot_base_frame, scan_frame, tf3::Time());
}
catch (const std::exception&)
{
noteReason("missing mounting TF");
return false;
}
const auto& rotation = base_tf.transform.rotation;
const double norm = rotation.x * rotation.x + rotation.y * rotation.y +
rotation.z * rotation.z + rotation.w * rotation.w;
const auto& prior_rotation = prior_tf.transform.rotation;
const double prior_norm = prior_rotation.x * prior_rotation.x + prior_rotation.y * prior_rotation.y +
prior_rotation.z * prior_rotation.z + prior_rotation.w * prior_rotation.w;
if (!std::isfinite(norm) || std::abs(norm - 1.0) > 0.01 ||
!std::isfinite(prior_norm) || std::abs(prior_norm - 1.0) > 0.01 ||
!std::isfinite(prior_tf.transform.translation.x) ||
!std::isfinite(prior_tf.transform.translation.y))
{
mount_error_ = "invalid mounting TF";
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), mount_error_.c_str());
return false;
}
const double up_base = 1.0 - 2.0 * (rotation.x * rotation.x + rotation.y * rotation.y);
const double up_prior = 1.0 - 2.0 * (prior_rotation.x * prior_rotation.x + prior_rotation.y * prior_rotation.y);
const double tilt_base = std::acos(std::min(1.0, std::abs(up_base)));
const double tilt_prior = std::acos(std::min(1.0, std::abs(up_prior)));
if (tilt_base > kMaxTilt || tilt_prior > kMaxTilt || (up_base < 0.0) != (up_prior < 0.0))
mount_error_ = "scan plane tilt exceeds limit or prior frame is inverted";
else if ((std::cos(yawOf(rotation)) > 0.0) != forward_)
mount_error_ = "lidar faces opposite entry_direction";
if (!mount_error_.empty())
{
robot::log_error("[wall_reflector] '%s': %s", name_.c_str(), mount_error_.c_str());
return false;
}
scan_in_prior_.x = prior_tf.transform.translation.x;
scan_in_prior_.y = prior_tf.transform.translation.y;
scan_in_prior_.yaw = yawOf(prior_rotation);
flipped_ = up_prior < 0.0;
scan_frame_ = scan_frame;
mount_valid_ = true;
if (debug_detect_)
robot::log_info("[wall_reflector][debug] '%s': scan=%s prior=%s flip=%s tilt=%.4f",
name_.c_str(), scan_frame.c_str(), prior_frame_.c_str(),
flipped_ ? "yes" : "no", tilt_base);
return true;
}
void processScan(const robot::Time& now)
{
const auto scan = robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(
*ctx_.sensors, scan_topic_, scan_cursor_);
if (scan)
{
const robot::Time stamp(scan->header.stamp.sec, scan->header.stamp.nsec);
const char* freshness_error = freshnessError(stamp, now);
if (freshness_error != nullptr)
noteReason(freshness_error);
else if (have_seen_stamp_ && stamp <= last_seen_stamp_)
noteReason("scan stamp repeated or out of order");
else
{
last_seen_stamp_ = stamp;
have_seen_stamp_ = true;
if (ensureMount(scan->header.frame_id))
{
robot_line_extraction::ScanGeometry geometry;
const double sign = flipped_ ? -1.0 : 1.0;
geometry.angle_min = sign * scan->angle_min;
geometry.angle_increment = sign * scan->angle_increment;
geometry.size = scan->ranges.size();
if (geometry.size > limits_.max_scan_rays)
noteReason("capacity_scan_rays");
else
{
if (!std::isfinite(scan->range_min) || !std::isfinite(scan->range_max) ||
scan->range_min < 0.0 || scan->range_max <= scan->range_min)
{
noteReason("invalid sensor range limits");
}
else
{
auto effective_limits = limits_;
effective_limits.min_range = std::max(limits_.min_range, static_cast<double>(scan->range_min));
effective_limits.max_range = std::min(limits_.max_range, static_cast<double>(scan->range_max));
if (effective_limits.min_range >= effective_limits.max_range)
{
noteReason("sensor and configured ranges do not overlap");
}
else
{
ranges_.assign(scan->ranges.begin(), scan->ranges.end());
auto detection = matcher_.match(geometry, ranges_, scan->intensities,
effective_limits, scan_in_prior_);
if (!detection.valid)
{
if (detection.reason == "ambiguous")
{
filter_.reset();
pending_valid_ = false;
have_sample_stamp_ = false;
}
noteReason(detection.reason);
}
else
{
pending_marker_ = detection.marker;
pending_stamp_ = stamp;
pending_received_ = now;
pending_valid_ = true;
last_reason_.clear();
reason_dirty_ = false;
}
}
}
}
}
}
}
if (pending_valid_)
{
if (!fresh(pending_stamp_, now) || secondsBetween(now, pending_received_) > pending_tf_timeout_)
{
pending_valid_ = false;
noteReason("pending TF expired");
}
else
resolvePending(now);
}
}
void resolvePending(const robot::Time& now)
{
tf3::TransformStampedMsg transform;
try
{
transform = ctx_.tf->lookupTransform(ctx_.global_frame, prior_frame_,
tf3::Time(pending_stamp_.sec, pending_stamp_.nsec));
}
catch (const std::exception&)
{
noteReason("waiting for TF at scan stamp");
return;
}
const auto& rotation = transform.transform.rotation;
const double norm = rotation.x * rotation.x + rotation.y * rotation.y +
rotation.z * rotation.z + rotation.w * rotation.w;
const double up = 1.0 - 2.0 * (rotation.x * rotation.x + rotation.y * rotation.y);
if (!std::isfinite(norm) || std::abs(norm - 1.0) > 0.01 || !std::isfinite(up) ||
std::acos(std::min(1.0, up)) > kMaxTilt)
{
pending_valid_ = false;
noteReason("invalid or tilted global TF");
return;
}
const double angle = yawOf(rotation);
const double c = std::cos(angle);
const double s = std::sin(angle);
PoseSample sample;
sample.x = transform.transform.translation.x + c * pending_marker_.x - s * pending_marker_.y;
sample.y = transform.transform.translation.y + s * pending_marker_.x + c * pending_marker_.y;
sample.yaw = wrap(angle + pending_marker_.yaw);
sample.taken_at = now;
if (!std::isfinite(sample.x) || !std::isfinite(sample.y) || !std::isfinite(sample.yaw))
{
pending_valid_ = false;
noteReason("nonfinite transform or marker");
return;
}
filter_.addSample(sample);
filter_.pruneExpired(now);
filter_.evaluate(now);
last_sample_stamp_ = pending_stamp_;
have_sample_stamp_ = true;
pending_valid_ = false;
last_reason_.clear();
reason_dirty_ = false;
}
bool writeTransform(const std::string& child, double x, double y, double yaw,
const robot::Time& now)
{
tf3::TransformStampedMsg transform;
transform.header.stamp = tf3::Time(now.sec, now.nsec);
transform.header.frame_id = ctx_.global_frame;
transform.child_frame_id = child;
transform.transform.translation.x = x;
transform.transform.translation.y = y;
transform.transform.translation.z = 0.0;
transform.transform.rotation.x = 0.0;
transform.transform.rotation.y = 0.0;
transform.transform.rotation.z = std::sin(yaw / 2.0);
transform.transform.rotation.w = std::cos(yaw / 2.0);
try
{
if (!ctx_.tf->setTransform(transform, "wall_reflector/" + name_, true))
{
robot::log_error("[wall_reflector] '%s': setTransform failed for '%s'.",
name_.c_str(), child.c_str());
return false;
}
return true;
}
catch (const std::exception& ex)
{
robot::log_error("[wall_reflector] '%s': TF publish failed: %s", name_.c_str(), ex.what());
return false;
}
}
bool publish(const PoseSample& marker, const robot::Time& now)
{
const double c = std::cos(marker.yaw);
const double s = std::sin(marker.yaw);
const double x = marker.x + active_profile_.offset_x * c - active_profile_.offset_y * s;
const double y = marker.y + active_profile_.offset_x * s + active_profile_.offset_y * c;
const double yaw = wrap(marker.yaw + active_profile_.offset_yaw + (forward_ ? kPi : 0.0));
if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(yaw))
{
robot::log_error("[wall_reflector] '%s': nonfinite target pose.", name_.c_str());
return false;
}
if (!marker_frame_.empty() && !writeTransform(marker_frame_, marker.x, marker.y, marker.yaw, now))
return false;
if (!writeTransform(output_frame_, x, y, yaw, now))
return false;
if (debug_state_)
robot::log_info("[wall_reflector][debug] '%s': output TF published.", name_.c_str());
return true;
}
std::string name_;
ActionContext ctx_;
bool initialized_ = false;
bool active_ = false;
bool paused_ = false;
bool forward_ = true;
bool debug_state_ = true;
bool debug_detect_ = true;
bool debug_skip_ = true;
std::vector<std::string> action_types_;
std::string output_frame_;
std::string marker_frame_;
std::string scan_topic_;
std::string prior_frame_;
std::string default_profile_;
std::string profile_param_key_;
std::string action_id_;
double settle_delay_ = 0.4;
double timeout_ = 15.0;
double max_scan_age_ = 0.3;
double max_future_skew_ = 0.05;
double pending_tf_timeout_ = 0.2;
std::map<std::string, dock_pattern_detector::ReflectorPairProfile> profiles_;
dock_pattern_detector::ReflectorPairProfile active_profile_;
dock_pattern_detector::ReflectorPairLimits limits_;
dock_pattern_detector::ReflectorPairMatcher matcher_;
dock_pattern_detector::ReflectorPose2D scan_in_prior_;
dock_pattern_detector::ReflectorPose2D pending_marker_;
PoseSampleFilter filter_;
robot::Time started_at_;
robot::Time settle_start_;
robot::Time paused_at_;
robot::Time last_now_;
robot::Time last_skip_log_;
robot::Time last_seen_stamp_;
robot::Time last_sample_stamp_;
robot::Time pending_stamp_;
robot::Time pending_received_;
bool reason_dirty_ = false;
bool have_skip_log_ = false;
bool have_seen_stamp_ = false;
bool have_sample_stamp_ = false;
bool pending_valid_ = false;
bool mount_valid_ = false;
bool flipped_ = false;
std::string scan_frame_;
std::string mount_error_;
std::string last_reason_;
uint64_t scan_cursor_ = 0;
std::vector<double> ranges_;
};
} // namespace action_core
ACTION_CORE_EXPORT_HANDLER(action_core::WallReflectorDetectionActionHandler::create,
WallReflectorDetectionActionHandler)

View File

@@ -0,0 +1,167 @@
# Cấu hình CHỈ cho test tổng hợp; không phải số hiệu chuẩn robot.
actions_wall:
handlers:
- {name: forward, type: WallReflectorDetectionActionHandler}
- {name: backward, type: WallReflectorDetectionActionHandler}
- {name: wrong_direction, type: WallReflectorDetectionActionHandler}
forward:
action_types: [DetectWallReflectors]
scan_topic: /f_scan
entry_direction: forward
default_profile: standard
output_frame: wall_reflector_target
marker_frame: wall_reflector_frame
settle_delay: 0.2
timeout: 5.0
max_scan_age: 0.3
max_future_skew: 0.05
pending_tf_timeout: 0.2
min_samples: 3
sample_window: 1.0
profiles:
standard:
tape_width: 0.05
width_tolerance: 0.025
tape_spacing: 0.40
spacing_tolerance: 0.025
tape_min_intensity: 8000.0
tape_core_intensity: 15000.0
tape_min_points: 3
tape_bloom_max_angle: 0.0
tape_plateau_min_fraction: 0.5
edge_bias_bound: 0.0
max_edge_uncertainty: 0.04
wall_min_span: 0.65
wall_max_rms: 0.006
wall_max_residual: 0.02
wall_max_gap: 0.15
wall_merge_distance: 0.02
offset_x: 0.6
alternate:
tape_width: 0.05
width_tolerance: 0.025
tape_spacing: 0.40
spacing_tolerance: 0.025
tape_min_intensity: 8000.0
tape_core_intensity: 15000.0
tape_min_points: 3
tape_bloom_max_angle: 0.0
tape_plateau_min_fraction: 0.5
edge_bias_bound: 0.0
max_edge_uncertainty: 0.04
wall_min_span: 0.65
wall_max_rms: 0.006
wall_max_residual: 0.02
wall_max_gap: 0.15
wall_merge_distance: 0.02
offset_x: 0.8
offset_y: 0.1
offset_yaw: 0.2
backward:
action_types: [DetectWallReflectorsBackward]
scan_topic: /b_scan2
entry_direction: backward
default_profile: standard
output_frame: wall_reflector_target
marker_frame: wall_reflector_frame
settle_delay: 0.2
timeout: 5.0
max_scan_age: 0.3
max_future_skew: 0.05
pending_tf_timeout: 0.2
min_samples: 3
sample_window: 1.0
profiles:
standard:
tape_width: 0.05
width_tolerance: 0.025
tape_spacing: 0.40
spacing_tolerance: 0.025
tape_min_intensity: 8000.0
tape_core_intensity: 15000.0
tape_min_points: 3
tape_bloom_max_angle: 0.0
tape_plateau_min_fraction: 0.5
edge_bias_bound: 0.0
max_edge_uncertainty: 0.04
wall_min_span: 0.65
wall_max_rms: 0.006
wall_max_residual: 0.02
wall_max_gap: 0.15
wall_merge_distance: 0.02
offset_x: 0.6
alternate:
tape_width: 0.05
width_tolerance: 0.025
tape_spacing: 0.40
spacing_tolerance: 0.025
tape_min_intensity: 8000.0
tape_core_intensity: 15000.0
tape_min_points: 3
tape_bloom_max_angle: 0.0
tape_plateau_min_fraction: 0.5
edge_bias_bound: 0.0
max_edge_uncertainty: 0.04
wall_min_span: 0.65
wall_max_rms: 0.006
wall_max_residual: 0.02
wall_max_gap: 0.15
wall_merge_distance: 0.02
offset_x: 0.8
offset_y: 0.1
offset_yaw: 0.2
wrong_direction:
action_types: [DetectWallWrong]
scan_topic: /b_scan2
entry_direction: forward
default_profile: standard
output_frame: wall_reflector_target
marker_frame: wall_reflector_frame
settle_delay: 0.2
timeout: 5.0
max_scan_age: 0.3
max_future_skew: 0.05
pending_tf_timeout: 0.2
min_samples: 3
sample_window: 1.0
profiles:
standard:
tape_width: 0.05
width_tolerance: 0.025
tape_spacing: 0.40
spacing_tolerance: 0.025
tape_min_intensity: 8000.0
tape_core_intensity: 15000.0
tape_min_points: 3
tape_bloom_max_angle: 0.0
tape_plateau_min_fraction: 0.5
edge_bias_bound: 0.0
max_edge_uncertainty: 0.04
wall_min_span: 0.65
wall_max_rms: 0.006
wall_max_residual: 0.02
wall_max_gap: 0.15
wall_merge_distance: 0.02
offset_x: 0.6
alternate:
tape_width: 0.05
width_tolerance: 0.025
tape_spacing: 0.40
spacing_tolerance: 0.025
tape_min_intensity: 8000.0
tape_core_intensity: 15000.0
tape_min_points: 3
tape_bloom_max_angle: 0.0
tape_plateau_min_fraction: 0.5
edge_bias_bound: 0.0
max_edge_uncertainty: 0.04
wall_min_span: 0.65
wall_max_rms: 0.006
wall_max_residual: 0.02
wall_max_gap: 0.15
wall_merge_distance: 0.02
offset_x: 0.8
offset_y: 0.1
offset_yaw: 0.2
WallReflectorDetectionActionHandler:
library_path: libwall_reflector_detection_action_handler

View File

@@ -0,0 +1,498 @@
#include <gtest/gtest.h>
#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>
#include <robot_sensor_msgs/LaserScan.h>
#include <yaml-cpp/yaml.h>
#include "wall_scan_sim.h"
namespace
{
using action_core::ActionHandler;
using action_core::ActionRegistry;
using action_core::ActionStatus;
using action_core::ActionTick;
constexpr double kPi = 3.14159265358979323846;
constexpr const char* kNamespace = "actions_wall";
constexpr const char* kTarget = "wall_reflector_target";
constexpr const char* kMarker = "wall_reflector_frame";
robot_protocol_msgs::Action action(const std::string& type, const std::string& profile = "")
{
robot_protocol_msgs::Action value;
value.actionId = "test";
value.actionType = type;
if (!profile.empty())
{
robot_protocol_msgs::ActionParameter parameter;
parameter.key = "reflector_profile";
parameter.value = profile;
value.actionParameters.push_back(parameter);
}
return value;
}
robot_sensor_msgs::LaserScan makeScan(const char* frame, double stamp,
const wall_scan_sim::World& world = {})
{
const auto geometry = wall_scan_sim::geometry(0.003926990554);
const auto synthetic = wall_scan_sim::rayCast(world, geometry);
robot_sensor_msgs::LaserScan scan;
scan.header.frame_id = frame;
scan.header.stamp = robot::Time(stamp);
scan.angle_min = static_cast<float>(geometry.angle_min);
scan.angle_increment = static_cast<float>(geometry.angle_increment);
scan.angle_max = scan.angle_min + (geometry.size - 1) * scan.angle_increment;
scan.range_min = 0.05;
scan.range_max = 6.0;
scan.ranges.assign(synthetic.ranges.begin(), synthetic.ranges.end());
scan.intensities = synthetic.intensities;
return scan;
}
double yawOf(const tf3::TransformStampedMsg& transform)
{
const auto& q = transform.transform.rotation;
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 angleError(double first, double second)
{
return std::abs(std::atan2(std::sin(first - second), std::cos(first - second)));
}
class Rig
{
public:
Rig()
{
robot_sensor_ports::SensorStoreConfig config;
for (const char* topic : {"/f_scan", "/b_scan2"})
{
robot_sensor_ports::SensorEntryConfig sensor;
sensor.topic = topic;
sensor.data_type = "robot_sensor_msgs/LaserScan";
sensor.capacity = 1;
sensor.max_age = 0.5;
config.sensors.push_back(sensor);
}
std::string error;
store_ok = store.configure(config, error);
mount("front_laser", 0.0, 0.0, 0.0);
mount("rear_laser", kPi, 0.0, 0.0);
mount("flipped_laser", 0.0, kPi, 0.0);
mount("tilted_laser", 0.0, 0.0, 0.2);
context.tf = &tf;
context.sensors = &store;
context.global_frame = "map";
context.robot_base_frame = "base_link";
registry.setContext(context);
loaded = registry.loadFromConfig(nh, kNamespace);
}
void mount(const char* child, double yaw, double roll, double pitch)
{
const double cr = std::cos(roll / 2), sr = std::sin(roll / 2);
const double cp = std::cos(pitch / 2), sp = std::sin(pitch / 2);
const double cy = std::cos(yaw / 2), sy = std::sin(yaw / 2);
tf3::TransformStampedMsg transform;
transform.header.frame_id = "base_link";
transform.child_frame_id = child;
transform.transform.rotation.w = cr * cp * cy + sr * sp * sy;
transform.transform.rotation.x = sr * cp * cy - cr * sp * sy;
transform.transform.rotation.y = cr * sp * cy + sr * cp * sy;
transform.transform.rotation.z = cr * cp * sy - sr * sp * cy;
tf.setTransform(transform, "test", true);
}
void robotPose(double stamp, double x = 0.0)
{
const robot::Time time(stamp);
tf3::TransformStampedMsg transform;
transform.header.stamp = tf3::Time(time.sec, time.nsec);
transform.header.frame_id = "map";
transform.child_frame_id = "base_link";
transform.transform.translation.x = x;
transform.transform.rotation.w = 1.0;
tf.setTransform(transform, "test", false);
}
ActionTick feed(ActionHandler* handler, double now, double stamp, const char* frame = "front_laser",
const char* topic = "/f_scan", bool add_tf = true,
const wall_scan_sim::World& world = {})
{
if (add_tf)
robotPose(stamp);
auto scan = makeScan(frame, stamp, world);
robot_sensor_ports::put(store, topic, scan, robot::Time(stamp));
return handler->update(robot::Time(now));
}
ActionTick happy(ActionHandler* handler, double start = 10.0, const char* frame = "front_laser",
const char* topic = "/f_scan")
{
ActionTick result;
for (int index = 0; index < 5; ++index)
{
const double now = start + 0.3 + index * 0.1;
result = feed(handler, now, now, frame, topic);
if (result.status != ActionStatus::kRunning)
break;
}
return result;
}
bool hasOutput(const char* frame)
{
try
{
tf.lookupTransform("map", frame, tf3::Time());
return true;
}
catch (const std::exception&)
{
return false;
}
}
tf3::TransformStampedMsg output(const char* frame)
{
return tf.lookupTransform("map", frame, tf3::Time());
}
robot::NodeHandle nh;
tf3::BufferCore tf;
robot_sensor_ports::SensorStore store;
action_core::ActionContext context;
ActionRegistry registry;
bool store_ok = false;
bool loaded = false;
};
TEST(WallReflectorAction, PluginLoadAndForwardTarget)
{
Rig rig;
ASSERT_TRUE(rig.store_ok);
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
const auto result = rig.happy(handler);
ASSERT_EQ(result.status, ActionStatus::kSucceeded) << result.message;
EXPECT_NE(result.message.find("published"), std::string::npos);
const auto marker = rig.output(kMarker);
const auto target = rig.output(kTarget);
EXPECT_NEAR(marker.transform.translation.x, 1.0, 0.01);
EXPECT_NEAR(target.transform.translation.x, 0.4, 0.01);
EXPECT_LT(angleError(yawOf(marker), kPi), 0.01);
EXPECT_LT(angleError(yawOf(target), 0.0), 0.01);
}
TEST(WallReflectorAction, BackwardTargetAndProfileSelection)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectorsBackward");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectorsBackward", "alternate"), robot::Time(10.0)));
const auto result = rig.happy(handler, 10.0, "rear_laser", "/b_scan2");
ASSERT_EQ(result.status, ActionStatus::kSucceeded) << result.message;
const auto marker = rig.output(kMarker);
const auto target = rig.output(kTarget);
EXPECT_NEAR(marker.transform.translation.x, -1.0, 0.01);
EXPECT_NEAR(target.transform.translation.x, -0.2, 0.01);
EXPECT_NEAR(target.transform.translation.y, 0.1, 0.01);
EXPECT_LT(angleError(yawOf(marker), 0.0), 0.01);
EXPECT_LT(angleError(yawOf(target), 0.2), 0.01);
}
TEST(WallReflectorAction, EmptyMarkerFramePublishesTargetOnly)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
rig.nh.setParam("actions_wall/forward/marker_frame", "");
ActionRegistry target_only;
target_only.setContext(rig.context);
ASSERT_TRUE(target_only.loadFromConfig(rig.nh, kNamespace));
rig.nh.setParam("actions_wall/forward/marker_frame", kMarker);
auto* handler = target_only.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
const auto result = rig.happy(handler);
ASSERT_EQ(result.status, ActionStatus::kSucceeded) << result.message;
EXPECT_TRUE(rig.hasOutput(kTarget));
EXPECT_FALSE(rig.hasOutput(kMarker));
}
TEST(WallReflectorAction, UnknownProfileFailsStartWithReason)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
testing::internal::CaptureStdout();
EXPECT_FALSE(handler->start(action("DetectWallReflectors", "missing"), robot::Time(10.0)));
EXPECT_NE(testing::internal::GetCapturedStdout().find("unknown profile"), std::string::npos);
EXPECT_FALSE(rig.hasOutput(kTarget));
}
TEST(WallReflectorAction, InvalidConfigurationReportsReason)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
const std::string root = "actions_wall/forward/";
YAML::Node original;
ASSERT_TRUE(rig.nh.getParam(root + "profiles/standard", original));
YAML::Node missing = YAML::Clone(original);
missing.remove("tape_width");
rig.nh.setParam(root + "profiles/standard", missing);
ActionRegistry invalid_profile;
invalid_profile.setContext(rig.context);
testing::internal::CaptureStdout();
EXPECT_FALSE(invalid_profile.loadFromConfig(rig.nh, kNamespace));
EXPECT_NE(testing::internal::GetCapturedStdout().find("tape_width"), std::string::npos);
rig.nh.setParam(root + "profiles/standard", original);
rig.nh.setParam(root + "marker_frame", kTarget);
ActionRegistry invalid_frames;
invalid_frames.setContext(rig.context);
testing::internal::CaptureStdout();
EXPECT_FALSE(invalid_frames.loadFromConfig(rig.nh, kNamespace));
EXPECT_NE(testing::internal::GetCapturedStdout().find("frame"), std::string::npos);
rig.nh.setParam(root + "marker_frame", kMarker);
rig.nh.setParam(root + "default_profile", "missing");
ActionRegistry invalid_default;
invalid_default.setContext(rig.context);
testing::internal::CaptureStdout();
EXPECT_FALSE(invalid_default.loadFromConfig(rig.nh, kNamespace));
EXPECT_NE(testing::internal::GetCapturedStdout().find("default_profile"), std::string::npos);
rig.nh.setParam(root + "default_profile", "standard");
}
TEST(WallReflectorAction, TfLateUsesScanStampAndRetries)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
auto tick = rig.feed(handler, 10.3, 10.3, "front_laser", "/f_scan", false);
EXPECT_EQ(tick.status, ActionStatus::kRunning);
EXPECT_NE(tick.message.find("TF at scan stamp"), std::string::npos);
rig.robotPose(10.3, 0.5);
rig.robotPose(10.35, 3.0);
tick = handler->update(robot::Time(10.35));
EXPECT_EQ(tick.status, ActionStatus::kRunning);
rig.robotPose(10.4, 0.5);
tick = rig.feed(handler, 10.4, 10.4, "front_laser", "/f_scan", false);
EXPECT_EQ(tick.status, ActionStatus::kRunning);
rig.robotPose(10.5, 0.5);
tick = rig.feed(handler, 10.5, 10.5, "front_laser", "/f_scan", false);
ASSERT_EQ(tick.status, ActionStatus::kSucceeded) << tick.message;
EXPECT_NEAR(rig.output(kMarker).transform.translation.x, 1.5, 0.01);
}
TEST(WallReflectorAction, NewerPendingReplacesOlderDetection)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(handler, 10.3, 10.3, "front_laser", "/f_scan", false).status,
ActionStatus::kRunning);
EXPECT_EQ(rig.feed(handler, 10.4, 10.4, "front_laser", "/f_scan", false).status,
ActionStatus::kRunning);
rig.robotPose(10.3, 2.0);
auto tick = handler->update(robot::Time(10.41));
EXPECT_EQ(tick.status, ActionStatus::kRunning);
EXPECT_FALSE(rig.hasOutput(kTarget));
rig.robotPose(10.4, 0.5);
tick = handler->update(robot::Time(10.42));
EXPECT_EQ(tick.status, ActionStatus::kRunning);
rig.robotPose(10.5, 0.5);
EXPECT_EQ(rig.feed(handler, 10.5, 10.5, "front_laser", "/f_scan", false).status,
ActionStatus::kRunning);
rig.robotPose(10.6, 0.5);
tick = rig.feed(handler, 10.6, 10.6, "front_laser", "/f_scan", false);
ASSERT_EQ(tick.status, ActionStatus::kSucceeded) << tick.message;
EXPECT_NEAR(rig.output(kMarker).transform.translation.x, 1.5, 0.01);
}
TEST(WallReflectorAction, BackwardClockJumpClearsFilterAndWaits)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(handler, 10.3, 10.3).status, ActionStatus::kRunning);
EXPECT_EQ(rig.feed(handler, 10.4, 10.4).status, ActionStatus::kRunning);
const auto tick = handler->update(robot::Time(9.0));
EXPECT_EQ(tick.status, ActionStatus::kRunning);
EXPECT_NE(tick.message.find("clock moved backwards"), std::string::npos);
EXPECT_FALSE(rig.hasOutput(kTarget));
}
TEST(WallReflectorAction, TfNeverArrivesPendingExpiresAndTimeoutExplains)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(handler, 10.3, 10.3, "front_laser", "/f_scan", false).status,
ActionStatus::kRunning);
const auto expired = handler->update(robot::Time(10.6));
EXPECT_NE(expired.message.find("pending TF expired"), std::string::npos);
const auto result = handler->update(robot::Time(15.1));
EXPECT_EQ(result.status, ActionStatus::kFailed);
EXPECT_NE(result.message.find("pending TF expired"), std::string::npos);
EXPECT_FALSE(rig.hasOutput(kTarget));
}
TEST(WallReflectorAction, RejectsOldFutureRepeatedAndStaleScans)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
auto tick = rig.feed(handler, 10.3, 9.9);
EXPECT_NE(tick.message.find("before settle"), std::string::npos);
tick = rig.feed(handler, 10.31, 10.5);
EXPECT_NE(tick.message.find("future"), std::string::npos);
tick = rig.feed(handler, 10.7, 10.3);
EXPECT_NE(tick.message.find("stale"), std::string::npos);
tick = rig.feed(handler, 10.8, 10.8);
EXPECT_EQ(tick.status, ActionStatus::kRunning);
tick = rig.feed(handler, 10.81, 10.8);
EXPECT_NE(tick.message.find("repeated"), std::string::npos);
for (double now : {10.82, 10.83, 10.84})
EXPECT_EQ(handler->update(robot::Time(now)).status, ActionStatus::kRunning);
tick = handler->update(robot::Time(11.2));
EXPECT_NE(tick.message.find("stale"), std::string::npos);
EXPECT_FALSE(rig.hasOutput(kTarget));
}
TEST(WallReflectorAction, UpsideDownLidarDerivedFromTf)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
const auto result = rig.happy(handler, 10.0, "flipped_laser");
ASSERT_EQ(result.status, ActionStatus::kSucceeded) << result.message;
EXPECT_NEAR(rig.output(kTarget).transform.translation.x, 0.4, 0.01);
EXPECT_LT(angleError(yawOf(rig.output(kTarget)), 0.0), 0.01);
}
TEST(WallReflectorAction, TiltAndDirectionFailWithReason)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* front = rig.registry.find("DetectWallReflectors");
ASSERT_NE(front, nullptr);
ASSERT_TRUE(front->start(action("DetectWallReflectors"), robot::Time(10.0)));
auto tick = rig.feed(front, 10.3, 10.3, "tilted_laser");
EXPECT_EQ(tick.status, ActionStatus::kFailed);
EXPECT_NE(tick.message.find("tilt"), std::string::npos);
auto* wrong = rig.registry.find("DetectWallWrong");
ASSERT_NE(wrong, nullptr);
ASSERT_TRUE(wrong->start(action("DetectWallWrong"), robot::Time(10.0)));
tick = rig.feed(wrong, 10.4, 10.4, "rear_laser", "/b_scan2");
EXPECT_EQ(tick.status, ActionStatus::kFailed);
EXPECT_NE(tick.message.find("opposite"), std::string::npos);
EXPECT_FALSE(rig.hasOutput(kTarget));
}
TEST(WallReflectorAction, AmbiguousSceneNeverSucceeds)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
wall_scan_sim::World world;
world.tapes = {{-0.4, 0.05}, {0.0, 0.05}, {0.4, 0.05}};
auto tick = rig.feed(handler, 10.3, 10.3, "front_laser", "/f_scan", true, world);
EXPECT_EQ(tick.status, ActionStatus::kRunning);
EXPECT_NE(tick.message.find("ambiguous"), std::string::npos);
tick = handler->update(robot::Time(15.1));
EXPECT_EQ(tick.status, ActionStatus::kFailed);
EXPECT_NE(tick.message.find("ambiguous"), std::string::npos);
EXPECT_FALSE(rig.hasOutput(kTarget));
}
TEST(WallReflectorAction, CancelAndPauseResumeDiscardOldSamples)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
EXPECT_EQ(rig.feed(handler, 10.3, 10.3).status, ActionStatus::kRunning);
handler->cancel();
EXPECT_EQ(handler->update(robot::Time(10.4)).status, ActionStatus::kFailed);
EXPECT_FALSE(rig.hasOutput(kTarget));
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(20.0)));
EXPECT_EQ(rig.feed(handler, 20.3, 20.3).status, ActionStatus::kRunning);
EXPECT_EQ(rig.feed(handler, 20.4, 20.4).status, ActionStatus::kRunning);
handler->pause(robot::Time(20.45));
handler->resume(robot::Time(21.0));
auto tick = rig.feed(handler, 21.1, 21.1);
EXPECT_EQ(tick.status, ActionStatus::kRunning);
EXPECT_FALSE(rig.hasOutput(kTarget));
tick = rig.feed(handler, 21.3, 20.4);
EXPECT_NE(tick.message.find("before settle"), std::string::npos);
tick = rig.happy(handler, 21.0);
ASSERT_EQ(tick.status, ActionStatus::kSucceeded) << tick.message;
}
TEST(WallReflectorAction, FailedSecondRunDoesNotReplacePreviousTf)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
auto* handler = rig.registry.find("DetectWallReflectors");
ASSERT_NE(handler, nullptr);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(10.0)));
ASSERT_EQ(rig.happy(handler).status, ActionStatus::kSucceeded);
const auto original = rig.output(kTarget);
ASSERT_TRUE(handler->start(action("DetectWallReflectors"), robot::Time(20.0)));
wall_scan_sim::World empty;
empty.tapes.clear();
auto tick = rig.feed(handler, 20.3, 20.3, "front_laser", "/f_scan", true, empty);
EXPECT_NE(tick.message.find("insufficient_candidates"), std::string::npos);
tick = handler->update(robot::Time(25.1));
EXPECT_EQ(tick.status, ActionStatus::kFailed);
EXPECT_NE(tick.message.find("insufficient_candidates"), std::string::npos);
const auto retained = rig.output(kTarget);
EXPECT_DOUBLE_EQ(retained.transform.translation.x, original.transform.translation.x);
EXPECT_DOUBLE_EQ(retained.transform.translation.y, original.transform.translation.y);
}
} // namespace
int main(int argc, char** argv)
{
#ifdef WALL_REFLECTOR_DETECTION_ACTION_TEST_CONFIG_DIR
setenv("PNKX_NAV_CORE_CONFIG_DIR", WALL_REFLECTOR_DETECTION_ACTION_TEST_CONFIG_DIR, 1);
#endif
#ifdef WALL_REFLECTOR_DETECTION_ACTION_TEST_LIBRARY_DIR
setenv("PNKX_NAV_CORE_LIBRARY_PATH", WALL_REFLECTOR_DETECTION_ACTION_TEST_LIBRARY_DIR, 1);
#endif
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}