From 8269e205769da52af3fca0402d4985447ce1271d Mon Sep 17 00:00:00 2001 From: duongtd Date: Wed, 26 Aug 2026 13:03:22 +0700 Subject: [PATCH] Run the dock detector as an action, from raw scan to goal frame This is the layer that turns the geometry into something the robot actually runs. It pulls a raw scan from the shared store, extracts lines, matches the dock pattern, transforms into the global frame and writes the result as a static transform - the same output contract FrameSampler has, so the charge sequence keeps working and nothing in move_base2, dock_planner or mission_adapters changes. Swapping detectors is one word in the YAML. It is also the only place in the chain allowed to know about TF, actions and the sensor store. The three packages beneath it stay free of all that, which is what lets their tests build a world, cast rays and finish in a millisecond with no runtime around them. Three things only break once the pieces are joined, and no core test can see them: The scan cursor. A 30 Hz control loop reading a 29 Hz lidar ticks more often than scans arrive. Without the cursor the same scan counts as several samples, min_samples stops meaning anything, and the handler commits on one measurement. TF arriving after the scan. The two come from different sources, so TF running a few milliseconds behind is routine. The store's cursor has already moved past that scan, so dropping the sample loses a detection outright every time TF is late. The detection is now held and transformed on a later tick, without re-running the match - the shape was already found, only the transform was missing. The regression test fails without that, which is how it earned its place. Transforming at the scan's own stamp rather than at the latest. The pose just computed belongs to the moment the scan was taken; looking up at another moment mixes two instants into one measurement. The error from "latest" is small but nobody knows how small, and a stamp on the wrong clock shows up exactly here. Rejections happen at boot, not at detection time: no sensor store, a scan_topic the store does not carry (listing the ones it does - a mistyped topic looks exactly like a dead sensor), no profiles, a pattern that is not implemented, a default_profile that does not exist. Every profile is validated, not just the default one, because a typo in the fifth profile that only surfaces at four in the afternoon is the worst kind. An order asking for a profile that does not exist fails and says which ones do. It does not quietly fall back to the default: using the wrong geometry means docking in the wrong place, not being slightly slower. The timeout message says which gate failed. Nothing matched, matched too rarely, or matched but never settled need opposite responses, and one failure line cannot carry that. --- CMakeLists.txt | 111 ++++ README.md | 111 ++++ package.xml | 49 ++ plugins/dock_pattern_action_handler.cpp | 650 ++++++++++++++++++++++++ test/config/action_handlers_params.yaml | 100 ++++ test/dock_pattern_action_test.cpp | 461 +++++++++++++++++ 6 files changed, 1482 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 package.xml create mode 100644 plugins/dock_pattern_action_handler.cpp create mode 100644 test/config/action_handlers_params.yaml create mode 100644 test/dock_pattern_action_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c7e873c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,111 @@ +cmake_minimum_required(VERSION 3.0.2) +project(dock_pattern_action VERSION 0.1.0 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +find_package(Boost REQUIRED) +find_package(Threads REQUIRED) +find_package(yaml-cpp REQUIRED) +find_package(Eigen3 REQUIRED) + +find_package(catkin REQUIRED COMPONENTS + action_core + dock_pattern_detector + robot_line_extraction + robot_sensor_ports + robot_cpp + robot_sensor_msgs +) + +# 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() + +catkin_package( + CATKIN_DEPENDS + action_core + dock_pattern_detector + robot_line_extraction + robot_sensor_ports + robot_cpp + robot_sensor_msgs +) + +# Header của dependency vào dạng SYSTEM: gói này build với -Wall -Wextra, mà 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. +include_directories(SYSTEM + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ${EIGEN3_INCLUDE_DIRS} +) + +# Handler là plugin Boost.DLL, nạp theo khoá `library_path` trong YAML — KHÔNG link thẳng vào ai. +add_library(dock_pattern_action_handler SHARED + plugins/dock_pattern_action_handler.cpp +) + +target_compile_options(dock_pattern_action_handler PRIVATE -Wall -Wextra) + +add_dependencies(dock_pattern_action_handler ${catkin_EXPORTED_TARGETS}) + +target_link_libraries(dock_pattern_action_handler + PUBLIC + ${catkin_LIBRARIES} + PRIVATE + Boost::boost + yaml-cpp + Threads::Threads + ${CMAKE_DL_LIBS} + ${TF3_LIBRARY} +) + +install(TARGETS dock_pattern_action_handler + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} +) + +if(CATKIN_ENABLE_TESTING) + if(NOT COMMAND catkin_add_gtest) + message(FATAL_ERROR "catkin_add_gtest NOT FOUND") + endif() + + catkin_add_gtest(dock_pattern_action_test test/dock_pattern_action_test.cpp) + + if(TARGET dock_pattern_action_test) + # catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make` thường. + set_target_properties(dock_pattern_action_test PROPERTIES EXCLUDE_FROM_ALL FALSE) + target_compile_options(dock_pattern_action_test PRIVATE -Wall -Wextra) + + target_include_directories(dock_pattern_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(dock_pattern_action_test + ${catkin_LIBRARIES} + ${Boost_LIBRARIES} + yaml-cpp + pthread + ${CMAKE_DL_LIBS} + ${TF3_LIBRARY} + ) + + add_dependencies(dock_pattern_action_test dock_pattern_action_handler) + + # ctest không mang theo PNKX_NAV_CORE_CONFIG_DIR hay LD_LIBRARY_PATH của shell. + target_compile_definitions(dock_pattern_action_test PRIVATE + DOCK_PATTERN_ACTION_TEST_CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/config" + DOCK_PATTERN_ACTION_TEST_LIBRARY_DIR="${CATKIN_DEVEL_PREFIX}/lib" + ) + endif() +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..cbfb3ec --- /dev/null +++ b/README.md @@ -0,0 +1,111 @@ +# dock_pattern_action + +Handler dò trạm dock từ **scan LiDAR thô**, nạp qua Boost.DLL như mọi action handler khác. + +Đây là tầng **adapter**, và là chỗ duy nhất trong chuỗi dò được phép biết tới TF, action và kho cảm +biến. + +## Chuỗi bốn tầng + +``` +robot_sensor_ports scan THÔ (ranges + intensities), cursor theo sequence + v +robot_line_extraction ranges -> đoạn thẳng + v +dock_pattern_detector đoạn + profile -> pose đích trong FRAME CỦA SCAN + v +gói này TF sang global -> PoseSampleFilter -> ghi `dock_target` +``` + +Ba gói dưới **không biết** TF/action/kho là gì — nhờ vậy phần hình học test được bằng scan dựng +sẵn, chạy trong một mili giây, không cần dựng runtime. + +## Thay `FrameSampler` mà không sửa gì phía dưới + +Cùng hợp đồng đầu ra: ghi một TF **tĩnh** vào `output_frame`. Chuỗi `charge` chạy nguyên — không +phải sửa dòng nào của move_base2, dock_planner hay mission_adapters. Chỉ đổi `type:` trong +`action_handlers_params.yaml`: + +```yaml +handlers: + - {name: detect, type: DockPatternActionHandler} # thay FrameSamplerActionHandler +``` + +Khác ở **nguồn**: FrameSampler lấy pose perception đã tính sẵn qua TF; handler này **tự tính** từ +mảng `ranges`. + +## Vì sao tự tính lại chắc hơn + +FrameSampler chỉ có **một** tín hiệu để lọc: các mẫu có chụm không. Handler này biết nhiều hơn hẳn +ngay tại **một** scan — số tia đỡ mỗi cánh, sai số khớp, góc kẹp lệch bao nhiêu, chiều dài cánh lệch +bao nhiêu. Nó **loại ứng viên sai tại nguồn** thay vì đợi thống kê. + +Nên cổng chính chống nhầm nằm ở **matcher**, không ở bộ lọc. Bộ lọc vẫn ở đây cho thứ hạng hai: +rung giữa các scan, và cú nhảy `map->odom` khi localization sửa giữa lúc dò — robot đứng yên (D8) +nên cú nhảy đó vẫn dịch pose đã publish. + +## Ba chỗ chỉ hỏng khi GHÉP, không test lõi nào thấy + +**1. Cursor scan.** 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. + +**2. TF tới SAU scan.** 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 là **mất hẳn** một phép dò mỗi +lần TF trễ. Phép dò được **giữ lại** và quy đổi ở tick sau, không dò lại (hình đã khớp, chỉ thiếu +phép quy đổi). Có test canh: `ADetectionSurvivesTfArrivingAfterTheScan`. + +**3. Quy TF tại đúng stamp của scan**, không phải lúc mới nhất. Pose vừa tính ứng với thời điểm scan +được chụp; tra ở thời điểm khác là trộn hai thời điểm vào một phép đo. Sai số của "mới nhất" nhỏ +thật, nhưng không ai biết nhỏ bao nhiêu — và **stamp lệch hệ thời gian sẽ hiện ra đúng ở đây**. + +## Chọn profile lúc chạy + +Order mang `dock_profile` trong `actionParameters`; chặng chỉ-action nhận **nguyên** params của +action gốc (`vda5050_source_adapter.cpp:380`). + +Xin profile **không tồn tại** → `start()` trả false kèm danh sách tên có thật. **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. + +## Từ chối lúc BOOT + +Không đợi tới lúc dò: + +- `ctx.sensors == nullptr` — handler này đọc scan thô, không có kho thì vô nghĩa +- `scan_topic` không có trong `sensor_store` → in luôn **danh sách topic có thật**. 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 +- không khai `profiles` nào +- `pattern` chưa hiện thực (`cylinder`, `arc`) — nhận nó là dựng một bộ dò không bao giờ tìm thấy gì +- `default_profile` trỏ vào profile không tồn tại +- **mọi** profile được validate, không chỉ profile mặc định — gõ sai ở profile thứ năm mà bốn giờ + chiều mới lộ là kiểu lỗi tệ nhất + +## Khi hết giờ, thông điệp nói hỏng ở CỔNG NÀO + +Ba ca khác nhau, ba cách xử trí khác nhau: + +| thông điệp | nghĩa là | +|---|---| +| `no '' pattern on '' — ` | chưa lần nào khớp; lý do từ matcher chỉ ra cổng nào chặn | +| `detected the pattern only N time(s)` | có khớp nhưng quá thưa so với `sample_window` — lỗi **tần số/cấu hình**, nới `max_spread_*` vô ích | +| `detections unstable (best spread ...)` | khớp đủ nhưng không chụm; log kèm cửa sổ **tốt nhất** từng thấy | + +## Config + +Xem `test/config/action_handlers_params.yaml`. Nhóm khoá: + +- định tuyến: `action_types`, `output_frame`, `scan_topic` +- thời gian: `settle_delay`, `timeout` +- chọn profile: `default_profile`, `profile_param_key` +- `profiles//` — hình học + offset của **từng cái sạc** +- `line_extraction/` — theo **cảm biến**, không theo sạc +- toàn bộ khoá của `PoseSampleFilter`, **cùng tên** như FrameSampler + +## Build và test + +```bash +catkin_make --pkg dock_pattern_action +./devel/lib/dock_pattern_action/dock_pattern_action_test # 16 test +``` + +Test dùng **kho thật + buffer tf3 thật + plugin nạp qua Boost.DLL**; chỉ scan là dựng sẵn. Đó là +cách bắt được ba lỗi ghép nối ở trên — không test lõi nào thấy chúng. diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..c787c5a --- /dev/null +++ b/package.xml @@ -0,0 +1,49 @@ + + dock_pattern_action + 0.1.0 + + Handler dò trạm dock từ scan LiDAR THÔ, nạp qua Boost.DLL như mọi action handler khác. + + Đây là tầng ADAPTER, và là chỗ duy nhất trong chuỗi dò được phép biết tới TF, action và kho cảm + biến. Ba gói bên dưới (`robot_sensor_ports`, `robot_line_extraction`, `dock_pattern_detector`) + cố ý không biết gì về chúng — nhờ vậy phần hình học test được bằng scan dựng sẵn, chạy trong + một mili giây, không cần dựng runtime. + + Cùng hợp đồng đầu ra với `FrameSamplerActionHandler`: ghi một TF tĩnh vào `output_frame`. Nên + chuỗi `charge` chạy nguyên, không phải sửa dòng nào của move_base2, dock_planner hay + mission_adapters — chỉ đổi `type:` trong action_handlers_params.yaml. + + Khác ở NGUỒN: FrameSampler lấy pose perception đã tính sẵn qua TF; handler này tự tính từ mảng + `ranges`, nên nó loại được ứng viên sai ngay tại một scan (số tia đỡ, sai số khớp, góc kẹp, + chiều dài cánh) thay vì chỉ dựa vào thống kê nhiều mẫu. + + T800 Robotics + T800 Robotics + BSD + + catkin + + action_core + action_core + + dock_pattern_detector + dock_pattern_detector + + robot_line_extraction + robot_line_extraction + + robot_sensor_ports + robot_sensor_ports + + robot_cpp + robot_cpp + + robot_sensor_msgs + robot_sensor_msgs + + tf3 + tf3 + + yaml-cpp + yaml-cpp + diff --git a/plugins/dock_pattern_action_handler.cpp b/plugins/dock_pattern_action_handler.cpp new file mode 100644 index 0000000..4d43220 --- /dev/null +++ b/plugins/dock_pattern_action_handler.cpp @@ -0,0 +1,650 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * dock_pattern_action — handler dò dock từ LiDAR: scan thô -> biên dạng -> frame ổn định. + * + * Author: DuongTD + *********************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace action_core +{ +namespace +{ +constexpr double kDefaultSettleDelay = 0.4; // [s] +constexpr double kDefaultTimeout = 15.0; // [s] + +/// Chu kỳ in lý do chưa dò ra. Control loop ~30 Hz; log mỗi cycle sẽ ngập log và làm chậm chính +/// vòng điều khiển. 1 Hz đủ để đọc xem đang hỏng ở cổng nào. +constexpr double kReasonLogPeriod = 1.0; // [s] + +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)); +} +} // namespace + +/** + * @class DockPatternActionHandler + * @brief Dò biên dạng trạm dock trong scan LiDAR thô, lọc, ghi ra một frame ổn định. + * + * Cùng hợp đồng đầu ra với `FrameSamplerActionHandler`: ghi một TF tĩnh vào `output_frame`, nên + * chuỗi `charge` chạy nguyên và không phải sửa dòng nào của navigation. Khác ở **nguồn**: + * FrameSampler lấy pose perception đã tính sẵn qua TF, handler này **tự tính** từ mảng `ranges`. + * + * ## Vì sao tự tính lại tốt hơn + * + * FrameSampler chỉ có một tín hiệu để lọc: các mẫu có chụm không. Handler này biết nhiều hơn hẳn + * ngay tại MỘT scan — số tia đỡ mỗi cánh, sai số khớp, góc kẹp lệch bao nhiêu, chiều dài cánh lệch + * bao nhiêu. Nó **loại ứng viên sai tại nguồn** thay vì đợi thống kê, nên cổng chính chống nhầm + * nằm ở matcher chứ không ở bộ lọc. + * + * Bộ lọc vẫn ở đây, cho thứ hạng hai: rung giữa các scan liên tiếp, và cú nhảy `map->odom` khi + * localization sửa giữa lúc dò — robot đứng yên (D8) nên cú nhảy đó vẫn dịch pose đã publish. + * + * ## Bốn tầng, mỗi tầng một gói + * + * - `robot_sensor_ports` — scan THÔ. Costmap ở 0.05 m đã inflate và xoá thứ tự tia, không dựng + * lại được; hai cánh 0.2 m trên lưới ấy là một cục. + * - `robot_line_extraction` — `ranges` -> đoạn thẳng. + * - `dock_pattern_detector` — đoạn + profile -> pose đích trong frame của scan. + * - handler này — TF sang global, lọc, ghi ra TF. + * + * ## Cấu hình + * + * - `action_types` [list] actionType nào vào handler này + * - `output_frame` [string] frame TF ghi ra, chặng sau trỏ `goal_frame` vào đây + * - `scan_topic` [string] PHẢI khớp tên đã khai trong `sensor_store/sensors` + * - `settle_delay` [s] chờ robot đứng hẳn trước khi lấy mẫu + * - `timeout` [s] hết giờ mà chưa chốt -> kFailed + * - `default_profile` [string] profile dùng khi order không mang khoá + * - `profile_param_key` [string] tên khoá tra trong actionParameters + * - `profiles//...` hình học + offset của TỪNG cái sạc + * - `line_extraction/...` tham số trích đoạn thẳng, theo CẢM BIẾN chứ không theo sạc + * - cộng toàn bộ khoá của @ref PoseSampleFilterConfig, cùng tên như FrameSampler + */ +class DockPatternActionHandler final : public ActionHandler +{ +public: + DockPatternActionHandler() = default; + + static ActionHandler::Ptr create() + { + return std::make_shared(); + } + + bool configure(const std::string& name, const ActionContext& ctx, + robot::NodeHandle& nh) override + { + name_ = name; + ctx_ = ctx; + + if (ctx_.tf == nullptr) + { + robot::log_error("[dock_pattern] '%s': needs a TF buffer but the context has none.", + name_.c_str()); + return false; + } + if (ctx_.sensors == nullptr) + { + // Handler này đọc scan THÔ. Không có kho thì nó vô nghĩa — từ chối lúc nạp để lỗi lộ khi + // khởi động, không phải khi order đầu tiên tới giữa ca. + robot::log_error("[dock_pattern] '%s': needs the shared sensor store but the context has " + "none. Declare sensor_store/sensors in the runtime config.", + name_.c_str()); + return false; + } + + nh.param("action_types", action_types_, std::vector{}); + nh.param("output_frame", output_frame_, std::string()); + nh.param("scan_topic", scan_topic_, std::string()); + nh.param("settle_delay", settle_delay_, kDefaultSettleDelay); + nh.param("timeout", timeout_, kDefaultTimeout); + nh.param("default_profile", default_profile_, std::string()); + nh.param("profile_param_key", profile_param_key_, std::string("dock_profile")); + + if (action_types_.empty()) + { + robot::log_error("[dock_pattern] '%s': action_types is empty — never called.", name_.c_str()); + return false; + } + if (output_frame_.empty()) + { + robot::log_error("[dock_pattern] '%s': output_frame is empty — the result would go nowhere.", + name_.c_str()); + return false; + } + if (scan_topic_.empty()) + { + robot::log_error("[dock_pattern] '%s': scan_topic is empty.", name_.c_str()); + return false; + } + + // 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: dò mãi + // không ra. Bắt lúc boot và in ra danh sách topic có thật. + if (!robot_sensor_ports::has(*ctx_.sensors, scan_topic_)) + { + std::string known; + for (const robot_sensor_ports::SensorInfo& info : ctx_.sensors->inventory()) + { + known += (known.empty() ? "" : ", ") + info.topic + " (" + info.data_type + ")"; + } + robot::log_error("[dock_pattern] '%s': scan_topic '%s' is not a LaserScan in the sensor " + "store. Declared topics: %s", + name_.c_str(), scan_topic_.c_str(), + known.empty() ? "(none)" : known.c_str()); + return false; + } + + if (!std::isfinite(settle_delay_) || settle_delay_ < 0.0) + { + robot::log_error("[dock_pattern] '%s': settle_delay=%.3f must be finite and >= 0.", + name_.c_str(), settle_delay_); + return false; + } + + if (!loadLineExtraction(nh) || !loadProfiles(nh) || !loadFilter(nh)) + { + return false; + } + + return true; + } + + std::vector supportedActionTypes() const override + { + return action_types_; + } + + bool start(const robot_protocol_msgs::Action& action, const robot::Time& now) override + { + started_at_ = now; + action_id_ = action.actionId; + scan_cursor_ = 0; + pending_valid_ = false; + last_reason_.clear(); + have_reason_log_ = false; + detections_ = 0; + + std::string profile_name = default_profile_; + const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(), + [this](const robot_protocol_msgs::ActionParameter& p) { + return p.key == profile_param_key_; + }); + if (it != action.actionParameters.end() && !it->value.empty()) + { + profile_name = it->value; + } + + const auto found = profiles_.find(profile_name); + if (found == profiles_.end()) + { + // 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. Nói ra tên đã xin và tên có thật. + std::string known; + for (const auto& entry : profiles_) + { + known += (known.empty() ? "" : ", ") + entry.first; + } + robot::log_error("[dock_pattern] '%s': action '%s' asked for profile '%s' which does not " + "exist. Known profiles: %s", + name_.c_str(), action.actionId.c_str(), profile_name.c_str(), + known.empty() ? "(none)" : known.c_str()); + return false; + } + + std::string error; + if (!matcher_.configure(found->second, error)) + { + robot::log_error("[dock_pattern] '%s': profile '%s' is invalid: %s", name_.c_str(), + profile_name.c_str(), error.c_str()); + return false; + } + + profile_name_ = profile_name; + filter_.reset(); + filter_.setLabels(scan_topic_, ctx_.global_frame); + + robot::log_info("[dock_pattern] '%s': detecting pattern '%s' (profile '%s') on '%s' -> '%s'.", + name_.c_str(), dock_pattern_detector::toString(found->second.pattern), + profile_name.c_str(), scan_topic_.c_str(), output_frame_.c_str()); + return true; + } + + ActionTick update(const robot::Time& now) override + { + ActionTick tick; + const double elapsed = (now - started_at_).toSec(); // [s] + + // Robot vừa dừng vẫn còn dao động cơ khí; scan lúc này mang theo dao động đó. + if (elapsed >= settle_delay_) + { + processNewScan(now); + } + + if (filter_.holdSatisfied(now)) + { + if (!publish(filter_.holdPose(), now)) + { + tick.status = ActionStatus::kFailed; + tick.message = "action '" + action_id_ + "': could not publish '" + output_frame_ + "'"; + return tick; + } + tick.status = ActionStatus::kSucceeded; + tick.message = "action '" + action_id_ + "': '" + output_frame_ + "' from " + + std::to_string(filter_.windowSize()) + " detection(s) of profile '" + + profile_name_ + "' after " + formatSeconds(elapsed) + " s"; + return tick; + } + + if (timeout_ > 0.0 && elapsed >= timeout_) + { + return failOnTimeout(elapsed); + } + + tick.status = ActionStatus::kRunning; + return tick; + } + + void cancel() override + { + filter_.reset(); + scan_cursor_ = 0; + pending_valid_ = false; + } + +private: + // ============================================================================================== + // Nạp cấu hình + // ============================================================================================== + + bool loadLineExtraction(robot::NodeHandle& nh) + { + robot::NodeHandle le_nh(nh, "line_extraction"); + robot_line_extraction::LineExtractionParams params; + nh_param(le_nh, "bearing_var", params.bearing_var); + nh_param(le_nh, "range_var", params.range_var); + nh_param(le_nh, "least_sq_angle_thresh", params.least_sq_angle_thresh); + nh_param(le_nh, "least_sq_radius_thresh", params.least_sq_radius_thresh); + nh_param(le_nh, "max_line_gap", params.max_line_gap); + nh_param(le_nh, "min_line_length", params.min_line_length); + nh_param(le_nh, "min_range", params.min_range); + nh_param(le_nh, "max_range", params.max_range); + nh_param(le_nh, "min_split_dist", params.min_split_dist); + nh_param(le_nh, "outlier_dist", params.outlier_dist); + + int min_line_points = static_cast(params.min_line_points); + nh_param(le_nh, "min_line_points", min_line_points); + params.min_line_points = static_cast(std::max(0, min_line_points)); + + std::string error; + if (!extractor_.configure(params, error)) + { + robot::log_error("[dock_pattern] '%s': line_extraction: %s", name_.c_str(), error.c_str()); + return false; + } + return true; + } + + bool loadProfiles(robot::NodeHandle& nh) + { + YAML::Node node; + if (!nh.getParam("profiles", node) || !node.IsMap() || node.size() == 0) + { + robot::log_error("[dock_pattern] '%s': no 'profiles' map — nothing to detect.", + name_.c_str()); + return false; + } + + profiles_.clear(); + for (const auto& entry : node) + { + const std::string profile_name = entry.first.as(); + robot::NodeHandle p_nh(nh, "profiles/" + profile_name); + + dock_pattern_detector::DockProfile profile; + + std::string pattern_name = "v"; + nh_param(p_nh, "pattern", pattern_name); + std::string error; + if (!dock_pattern_detector::patternFromString(pattern_name, profile.pattern, error)) + { + robot::log_error("[dock_pattern] '%s': profile '%s': %s", name_.c_str(), + profile_name.c_str(), error.c_str()); + return false; + } + + nh_param(p_nh, "vertex_angle", profile.vertex_angle); + nh_param(p_nh, "wing_length", profile.wing_length); + nh_param(p_nh, "angle_tolerance", profile.angle_tolerance); + nh_param(p_nh, "length_tolerance", profile.length_tolerance); + nh_param(p_nh, "vertex_gap", profile.vertex_gap); + nh_param(p_nh, "search_radius", profile.search_radius); + nh_param(p_nh, "search_fov", profile.search_fov); + nh_param(p_nh, "offset_x", profile.offset_x); + nh_param(p_nh, "offset_y", profile.offset_y); + nh_param(p_nh, "offset_yaw", profile.offset_yaw); + nh_param(p_nh, "min_confidence", profile.min_confidence); + + int min_wing_points = static_cast(profile.min_wing_points); + nh_param(p_nh, "min_wing_points", min_wing_points); + profile.min_wing_points = static_cast(std::max(0, min_wing_points)); + + // Kiểm MỌI profile lúc boot, không chỉ profile mặc định. Gõ sai ở profile thứ năm mà bốn giờ + // chiều mới lộ là kiểu lỗi tệ nhất. + if (!profile.validate(error)) + { + robot::log_error("[dock_pattern] '%s': profile '%s': %s", name_.c_str(), + profile_name.c_str(), error.c_str()); + return false; + } + + profiles_[profile_name] = profile; + } + + if (default_profile_.empty()) + { + default_profile_ = profiles_.begin()->first; + } + if (profiles_.find(default_profile_) == profiles_.end()) + { + robot::log_error("[dock_pattern] '%s': default_profile '%s' is not among the declared " + "profiles.", + name_.c_str(), default_profile_.c_str()); + return false; + } + return true; + } + + bool loadFilter(robot::NodeHandle& nh) + { + PoseSampleFilterConfig config; + nh.param("filter_enabled", 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 (!filter_.configure(config, name_)) + { + return false; + } + + if (config.enabled && timeout_ > 0.0 && + timeout_ <= settle_delay_ + config.sample_window + config.hold_time) + { + robot::log_error("[dock_pattern] '%s': timeout=%.3f s <= " + "settle_delay+sample_window+hold_time=%.3f s; the action would always fail.", + name_.c_str(), timeout_, + settle_delay_ + config.sample_window + config.hold_time); + return false; + } + return true; + } + + /// @brief `robot::NodeHandle::param` nhưng không cần biến tạm ở chỗ gọi. + template + static void nh_param(robot::NodeHandle& nh, const std::string& key, T& value) + { + nh.param(key, value, value); + } + + // ============================================================================================== + // Vòng dò + // ============================================================================================== + + /** + * @brief Lấy scan MỚI (nếu có), dò, quy sang global frame, đẩy vào bộ lọc. + * + * Chỉ chạy khi cursor cho biết có scan mới. Control loop 30 Hz đọc lidar 29 Hz thì một phần các + * tick không có gì mới — dò lại trên đúng scan cũ là đốt CPU của vòng điều khiển và đếm hai lần + * cùng một phép đo. + */ + void processNewScan(const robot::Time& now) + { + // Trước hết giải quyết phép dò còn treo vì TF chưa kịp. Không dò lại: hình đã khớp rồi, chỉ + // thiếu phép quy đổi. + if (pending_valid_ && resolvePending(now)) + { + pending_valid_ = false; + } + + auto scan = robot_sensor_ports::latest(*ctx_.sensors, scan_topic_, + scan_cursor_); + if (!scan) + { + return; + } + + robot_line_extraction::ScanGeometry geometry; + geometry.angle_min = scan->angle_min; + geometry.angle_increment = scan->angle_increment; + geometry.size = scan->ranges.size(); + + // `ranges` là float trong message, double trong lõi. Đổi một lần ở đây, dùng lại buffer để + // không cấp phát mỗi scan. + ranges_.assign(scan->ranges.begin(), scan->ranges.end()); + + std::string error; + if (!extractor_.extract(geometry, ranges_, lines_, error)) + { + noteReason(now, "scan unusable: " + error); + return; + } + + const dock_pattern_detector::Detection detection = matcher_.match(lines_); + if (!detection.valid) + { + noteReason(now, detection.reason); + return; + } + + // Hình đã khớp. Giữ lại kèm stamp và frame của scan; phép quy TF làm ở resolvePending() vì nó + // có thể phải CHỜ. + pending_ = detection; + pending_frame_ = scan->header.frame_id; + pending_stamp_ = tf3::Time(scan->header.stamp.sec, scan->header.stamp.nsec); + pending_valid_ = true; + last_reason_.clear(); + + if (resolvePending(now)) + { + pending_valid_ = false; + } + } + + /** + * @brief Quy phép dò đang treo sang global frame và đẩy vào bộ lọc. + * + * @return false nếu TF chưa có ở stamp đó — khi ấy phép dò **được giữ lại** để tick sau thử tiếp. + * + * Vì sao giữ lại thay vì bỏ: 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ỏ ở đây là **mất hẳn** một + * phép dò mỗi lần TF trễ — trên robot thật là mất rất nhiều. + * + * Và vẫn KHÔNG rơi về transform mới nhất: pose vừa tính ứng với thời điểm scan được chụp, tra ở + * thời điểm khác là trộn hai thời điểm vào một phép đo. Sai số của "mới nhất" nhỏ thật, nhưng + * không ai biết nhỏ bao nhiêu — và stamp lệch hệ thời gian sẽ hiện ra đúng ở đây. + */ + bool resolvePending(const robot::Time& now) + { + tf3::TransformStampedMsg sensor_to_global; + try + { + sensor_to_global = + ctx_.tf->lookupTransform(ctx_.global_frame, pending_frame_, pending_stamp_); + } + catch (const std::exception& ex) + { + noteReason(now, std::string("no transform at the scan stamp yet: ") + ex.what()); + return false; + } + + const double base_yaw = yawOf(sensor_to_global.transform.rotation); + const double c = std::cos(base_yaw); + const double s = std::sin(base_yaw); + + PoseSample sample; + sample.x = sensor_to_global.transform.translation.x + c * pending_.x - s * pending_.y; + sample.y = sensor_to_global.transform.translation.y + s * pending_.x + c * pending_.y; + sample.yaw = std::atan2(std::sin(base_yaw + pending_.yaw), std::cos(base_yaw + pending_.yaw)); + sample.taken_at = now; + + ++detections_; + last_reason_.clear(); + + filter_.addSample(sample); + filter_.pruneExpired(now); + filter_.evaluate(now); + return true; + } + + /// @brief Ghi lại vì sao chưa dò ra, in tối đa một dòng mỗi `kReasonLogPeriod` giây. + void noteReason(const robot::Time& now, const std::string& reason) + { + last_reason_ = reason; + + if (have_reason_log_ && (now - last_reason_log_).toSec() < kReasonLogPeriod) + { + return; + } + last_reason_log_ = now; + have_reason_log_ = true; + robot::log_info("[dock_pattern] '%s': %s", name_.c_str(), reason.c_str()); + } + + ActionTick failOnTimeout(double elapsed) + { + ActionTick tick; + tick.status = ActionStatus::kFailed; + + if (detections_ == 0) + { + // Chưa lần nào khớp được. `last_reason_` từ matcher nói rõ hỏng ở CỔNG NÀO — "không thấy gì" + // và "thấy nhưng sai chiều dài cánh" đòi hai cách xử trí ngược nhau. + tick.message = "action '" + action_id_ + "': no '" + profile_name_ + "' pattern on '" + + scan_topic_ + "' in " + formatSeconds(elapsed) + " s" + + (last_reason_.empty() ? "" : " — " + last_reason_); + return tick; + } + + if (!filter_.hasBest()) + { + // Có khớp, nhưng chưa cửa sổ nào đủ `min_samples`: dò được quá thưa so với `sample_window`. + // Lỗi CẤU HÌNH/tần số, không phải chất lượng dò — nới `max_spread_*` vô ích. + tick.message = "action '" + action_id_ + "': detected the pattern only " + + std::to_string(detections_) + " time(s) in " + formatSeconds(elapsed) + + " s, need " + std::to_string(filter_.config().min_samples) + + " within any " + formatSeconds(filter_.config().sample_window) + " s window"; + return tick; + } + + robot::log_error("[dock_pattern] '%s': no window converged in %.2f s. Best window (%.0f%% of " + "the tolerance): %s\n", + name_.c_str(), elapsed, filter_.bestScore() * 100.0, + filter_.bestDescription().c_str()); + + tick.message = "action '" + action_id_ + "': detections unstable (best spread xy=" + + std::to_string(filter_.bestSpreadXy()) + + " m, yaw=" + std::to_string(filter_.bestSpreadYaw()) + " rad in " + + formatSeconds(elapsed) + " s)"; + return tick; + } + + static std::string formatSeconds(double seconds) + { + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "%.2f", seconds); + return buffer; + } + + bool publish(const PoseSample& s, const robot::Time& now) + { + tf3::TransformStampedMsg out; + out.header.stamp = tf3::Time(now.sec, now.nsec); + out.header.frame_id = ctx_.global_frame; + out.child_frame_id = output_frame_; + out.transform.translation.x = s.x; + out.transform.translation.y = s.y; + out.transform.translation.z = 0.0; + out.transform.rotation.x = 0.0; + out.transform.rotation.y = 0.0; + out.transform.rotation.z = std::sin(s.yaw * 0.5); + out.transform.rotation.w = std::cos(s.yaw * 0.5); + + // static = true: kết quả đã chốt, không có hạn dùng. Chặng sau tra lúc nào cũng thấy, kể cả khi + // cảm biến đã mất dấu vì robot tới quá gần. + return ctx_.tf->setTransform(out, "dock_pattern/" + name_, /*is_static=*/true); + } + + std::string name_; + ActionContext ctx_; + + std::vector action_types_; + std::string output_frame_; + std::string scan_topic_; + double settle_delay_ = kDefaultSettleDelay; + double timeout_ = kDefaultTimeout; + + std::string default_profile_; + std::string profile_param_key_ = "dock_profile"; + std::map profiles_; + + robot_line_extraction::LineExtractor extractor_; + dock_pattern_detector::VPatternMatcher matcher_; + PoseSampleFilter filter_; + + robot::Time started_at_; + std::string action_id_; + std::string profile_name_; + + /// Con trỏ đọc của kho cảm biến. Đây là thứ phân biệt "scan mới" với "cùng scan đọc lại". + uint64_t scan_cursor_ = 0; + /// Số lần khớp được cả lượt. Phân biệt "chưa lần nào khớp" với "khớp nhưng quá thưa". + std::size_t detections_ = 0; + /// Phép dò đã khớp nhưng chưa quy được sang global frame vì TF chưa tới stamp đó. + dock_pattern_detector::Detection pending_; + std::string pending_frame_; + tf3::Time pending_stamp_; + bool pending_valid_ = false; + + std::string last_reason_; + robot::Time last_reason_log_; + bool have_reason_log_ = false; + + /// Buffer dùng lại: hai hàm dưới chạy mỗi khi có scan mới, tức ~30 lần/giây. + std::vector ranges_; + std::vector lines_; +}; + +} // namespace action_core + +BOOST_DLL_ALIAS(action_core::DockPatternActionHandler::create, DockPatternActionHandler) diff --git a/test/config/action_handlers_params.yaml b/test/config/action_handlers_params.yaml new file mode 100644 index 0000000..faea415 --- /dev/null +++ b/test/config/action_handlers_params.yaml @@ -0,0 +1,100 @@ +# ================================================================================================= +# Cây config của test — KHÔNG phải bản chạy thật. Mỗi khối là một ca kiểm riêng. +# ================================================================================================= + +# Ca thường: một profile chữ V, bộ lọc nhẹ để test không phải bơm hàng chục scan. +actions_dock: + handlers: + - {name: detect, type: DockPatternActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + scan_topic: /f_scan + settle_delay: 0.0 # [s] test tự điều khiển đồng hồ + timeout: 5.0 # [s] + + default_profile: v_std + profile_param_key: dock_profile + + sample_window: 1.0 # [s] + min_samples: 3 + max_spread_xy: 0.05 # [m] + max_spread_yaw: 0.10 # [rad] + + line_extraction: + min_split_dist: 0.02 # [m] + max_line_gap: 0.08 # [m] + min_line_length: 0.05 # [m] + min_line_points: 5 + + profiles: + v_std: + pattern: v + vertex_angle: 1.5708 # [rad] tấm mở 90 độ + wing_length: 0.30 # [m] + angle_tolerance: 0.20 # [rad] + length_tolerance: 0.06 # [m] + vertex_gap: 0.05 # [m] + min_wing_points: 5 + min_confidence: 0.3 + offset_x: 0.60 # [m] lùi ra trước mặt sạc + + v_wide: + pattern: v + vertex_angle: 2.0944 # [rad] 120 độ + wing_length: 0.25 # [m] + angle_tolerance: 0.20 + length_tolerance: 0.06 + vertex_gap: 0.05 + min_wing_points: 5 + min_confidence: 0.3 + offset_x: 0.50 + +# scan_topic không có trong kho -> phải từ chối LÚC BOOT kèm danh sách topic có thật. +actions_dock_bad_topic: + handlers: + - {name: detect, type: DockPatternActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + scan_topic: /front_scan + default_profile: v_std + profiles: + v_std: {pattern: v, vertex_angle: 1.5708, wing_length: 0.30, vertex_gap: 0.05} + +# Không khai profile nào -> không có gì để dò. +actions_dock_no_profile: + handlers: + - {name: detect, type: DockPatternActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + scan_topic: /f_scan + +# pattern chưa hiện thực -> nói thẳng, đừng nhận rồi không bao giờ dò ra gì. +actions_dock_unimplemented: + handlers: + - {name: detect, type: DockPatternActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + scan_topic: /f_scan + default_profile: pillar + profiles: + pillar: {pattern: cylinder, vertex_angle: 1.5708, wing_length: 0.30, vertex_gap: 0.05} + +# default_profile trỏ vào profile không tồn tại. +actions_dock_bad_default: + handlers: + - {name: detect, type: DockPatternActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + scan_topic: /f_scan + default_profile: khong_co + profiles: + v_std: {pattern: v, vertex_angle: 1.5708, wing_length: 0.30, vertex_gap: 0.05} + +# Bảng symbol -> thư viện cho Boost.DLL. +DockPatternActionHandler: + library_path: libdock_pattern_action_handler diff --git a/test/dock_pattern_action_test.cpp b/test/dock_pattern_action_test.cpp new file mode 100644 index 0000000..c33c1d5 --- /dev/null +++ b/test/dock_pattern_action_test.cpp @@ -0,0 +1,461 @@ +/********************************************************************* + * + * 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 + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +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::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 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 } }; +} + +robot_sensor_msgs::LaserScan makeScan(const std::vector& world, double stamp_s, + std::size_t rays = 600) +{ + 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(rays - 1); + scan.range_min = 0.05f; + scan.range_max = 20.0f; + scan.ranges.assign(rays, static_cast(kInf)); + + for (std::size_t i = 0; i < rays; ++i) + { + const double bearing = scan.angle_min + static_cast(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(t); + } + } + } + + 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") + { + 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); + + ctx.tf = &tf; + ctx.sensors = &store; + ctx.global_frame = kGlobalFrame; + registry.setContext(ctx); + loaded = registry.loadFromConfig(nh, ns); + handler = registry.find("DetectCharger"); + } + + void setSensorPose(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 = kScanFrame; + t.transform.translation.x = x; + t.transform.translation.y = y; + t.transform.translation.z = 0.0; + t.transform.rotation.x = 0.0; + t.transform.rotation.y = 0.0; + 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 push(const std::vector& world, double stamp_s) + { + robot_sensor_ports::put(store, kScanTopic, makeScan(world, stamp_s), robot::Time(stamp_s)); + } + + /// @brief Bơm @p count scan rồi tick, đúng nhịp mà control loop chạy. + ActionStatus feed(const std::vector& 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; +}; + +// ================================================================================================ +// 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 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, 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); +} + +} // 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(); +}