From 8e2a4182c59e11fcb54a4a6bdbe43abbcb1a6aba Mon Sep 17 00:00:00 2001 From: duongtd Date: Mon, 10 Aug 2026 10:52:16 +0700 Subject: [PATCH] first commit --- CMakeLists.txt | 416 ++++++++++++++++++ README.md | 94 +++++ docs/PLUGIN_GUIDE.md | 170 ++++++++ include/action_core/action_context.h | 52 +++ include/action_core/action_handler.h | 88 ++++ include/action_core/action_registry.h | 135 ++++++ include/action_core/action_types.h | 53 +++ package.xml | 48 +++ plugins/frame_sampler_action_handler.cpp | 515 +++++++++++++++++++++++ plugins/log_report_action_handler.cpp | 118 ++++++ plugins/noop_action_handler.cpp | 177 ++++++++ plugins/wait_action_handler.cpp | 195 +++++++++ src/action_registry.cpp | 225 ++++++++++ src/action_types.cpp | 28 ++ test/action_registry_test.cpp | 267 ++++++++++++ test/config/action_handlers_params.yaml | 128 ++++++ test/frame_sampler_test.cpp | 352 ++++++++++++++++ test/log_report_action_handler_test.cpp | 100 +++++ test/noop_action_handler_test.cpp | 116 +++++ test/wait_action_handler_test.cpp | 136 ++++++ 20 files changed, 3413 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 docs/PLUGIN_GUIDE.md create mode 100644 include/action_core/action_context.h create mode 100644 include/action_core/action_handler.h create mode 100644 include/action_core/action_registry.h create mode 100644 include/action_core/action_types.h create mode 100644 package.xml create mode 100644 plugins/frame_sampler_action_handler.cpp create mode 100644 plugins/log_report_action_handler.cpp create mode 100644 plugins/noop_action_handler.cpp create mode 100644 plugins/wait_action_handler.cpp create mode 100644 src/action_registry.cpp create mode 100644 src/action_types.cpp create mode 100644 test/action_registry_test.cpp create mode 100644 test/config/action_handlers_params.yaml create mode 100644 test/frame_sampler_test.cpp create mode 100644 test/log_report_action_handler_test.cpp create mode 100644 test/noop_action_handler_test.cpp create mode 100644 test/wait_action_handler_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..f26672e --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,416 @@ +cmake_minimum_required(VERSION 3.0.2) +project(action_core VERSION 0.1.0 LANGUAGES CXX) + +# ======================================================== +# Build mode detection +# ======================================================== +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building action_core with Catkin") +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building action_core with Standalone CMake") +endif() + + +# ======================================================== +# C++ Standard +# ======================================================== +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + + +# ======================================================== +# Common dependencies +# ======================================================== +find_package(Boost REQUIRED COMPONENTS + system + filesystem +) + +find_package(Threads REQUIRED) +find_package(yaml-cpp REQUIRED) + +# tf3 không được build bởi workspace này (cài sẵn ở /usr/local/lib/libtf3.so). Handler dò cần nó để +# đọc frame thô và GHI lại frame đã lọc — xem ActionContext. +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() + + +# ======================================================== +# Standalone configuration +# ======================================================== +if(NOT BUILDING_WITH_CATKIN) + + 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}") + + # Test/action_core -> Test -> AMR_T800. Cây nguồn của nav core nằm ngay dưới đó. + set(PNKX_NAV_CORE_SRC_DIR + "${CMAKE_CURRENT_SOURCE_DIR}/../../.." + ) + + set(WORKSPACE_DEVEL_LIB_DIR + "${CMAKE_CURRENT_SOURCE_DIR}/../../../../devel/lib" + ) + + file(GLOB STANDALONE_PACKAGE_INCLUDE_DIRS + LIST_DIRECTORIES true + + ${PNKX_NAV_CORE_SRC_DIR}/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/*/include + ) + + set(STANDALONE_INCLUDE_DIRS + ${STANDALONE_PACKAGE_INCLUDE_DIRS} + + /opt/ros/noetic/include + /usr/local/include + ) + + if(EXISTS ${WORKSPACE_DEVEL_LIB_DIR}) + link_directories(${WORKSPACE_DEVEL_LIB_DIR}) + endif() + + link_directories( + /usr/local/lib + ) + + # Gói này KHÔNG kéo costmap/tf3: action không chạm bản đồ và không phát vận tốc (D8), nên bốn + # thư viện dưới đây là toàn bộ phụ thuộc runtime của nó. + set(STANDALONE_LIBRARIES + robot_cpp + robot_time + robot_xmlrpcpp + robot_protocol_msgs + ) + + include_directories( + include + ) + + include_directories(SYSTEM + ${STANDALONE_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) + + +# ======================================================== +# Catkin configuration +# ======================================================== +else() + + find_package(catkin REQUIRED COMPONENTS + robot_cpp + robot_time + robot_protocol_msgs + robot_xmlrpcpp + ) + + catkin_package( + INCLUDE_DIRS + include + + LIBRARIES + action_core + action_core_frame_sampler_action_handler + action_core_wait_action_handler + action_core_log_report_action_handler + action_core_noop_action_handler + + CATKIN_DEPENDS + robot_cpp + robot_time + robot_protocol_msgs + robot_xmlrpcpp + + DEPENDS + Boost + ) + + include_directories( + include + ) + + # 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} + ) + +endif() + + +# ======================================================== +# Core library +# ======================================================== +add_library(action_core SHARED + src/action_types.cpp + src/action_registry.cpp +) + +target_compile_options(action_core PRIVATE -Wall -Wextra) + + +if(BUILDING_WITH_CATKIN) + + add_dependencies(action_core + ${${PROJECT_NAME}_EXPORTED_TARGETS} + ${catkin_EXPORTED_TARGETS} + ) + + target_include_directories(action_core + PUBLIC + $ + $ + + ${Boost_INCLUDE_DIRS} + ) + + target_link_libraries(action_core + PUBLIC + ${catkin_LIBRARIES} + + PRIVATE + Boost::boost + Boost::system + Boost::filesystem + + yaml-cpp + + Threads::Threads + + ${CMAKE_DL_LIBS} + + ${TF3_LIBRARY} + ) + +else() + + target_include_directories(action_core + PUBLIC + $ + $ + + SYSTEM PUBLIC + ${STANDALONE_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) + + target_link_libraries(action_core + PUBLIC + ${STANDALONE_LIBRARIES} + + PRIVATE + Boost::boost + Boost::system + Boost::filesystem + + yaml-cpp + + Threads::Threads + + ${CMAKE_DL_LIBS} + + ${TF3_LIBRARY} + ) + +endif() + + +# ======================================================== +# Action handler plugins +# ======================================================== +# +# Mỗi handler là một .so riêng, nạp qua Boost.DLL theo khoá `library_path` trong YAML — KHÔNG link +# thẳng vào ai. Thêm một loại action mới = thêm một dòng ở đây + một dòng YAML. +set(ACTION_CORE_PLUGIN_TARGETS) + +function(add_action_core_plugin target source) + + add_library(${target} SHARED ${source}) + + target_compile_options(${target} PRIVATE -Wall -Wextra) + + add_dependencies(${target} action_core) + + set_target_properties(${target} PROPERTIES POSITION_INDEPENDENT_CODE ON) + + if(BUILDING_WITH_CATKIN) + add_dependencies(${target} + ${${PROJECT_NAME}_EXPORTED_TARGETS} + ${catkin_EXPORTED_TARGETS} + ) + + target_include_directories(${target} + PUBLIC + $ + $ + ) + + target_link_libraries(${target} + PUBLIC + action_core + + PRIVATE + ${catkin_LIBRARIES} + Boost::boost + ${CMAKE_DL_LIBS} + ${TF3_LIBRARY} + ) + else() + target_include_directories(${target} + PUBLIC + $ + $ + + SYSTEM PUBLIC + ${STANDALONE_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) + + target_link_libraries(${target} + PUBLIC + action_core + + PRIVATE + ${STANDALONE_LIBRARIES} + Boost::boost + ${CMAKE_DL_LIBS} + ${TF3_LIBRARY} + ) + endif() + + set(ACTION_CORE_PLUGIN_TARGETS + ${ACTION_CORE_PLUGIN_TARGETS} ${target} + PARENT_SCOPE + ) + +endfunction() + + +# Bộ handler DEFAULT của gói. `wait` và `logReport` là hiện thực thật, chạy được trên robot thật — +# chúng không điều khiển thiết bị nào vì chính action đó không yêu cầu thiết bị nào. `noop` là stub +# mô phỏng, chỉ dành cho sim/dev. +add_action_core_plugin(action_core_frame_sampler_action_handler plugins/frame_sampler_action_handler.cpp) +add_action_core_plugin(action_core_wait_action_handler plugins/wait_action_handler.cpp) +add_action_core_plugin(action_core_log_report_action_handler plugins/log_report_action_handler.cpp) +add_action_core_plugin(action_core_noop_action_handler plugins/noop_action_handler.cpp) + + +# ======================================================== +# Install +# ======================================================== +if(BUILDING_WITH_CATKIN) + + install(TARGETS action_core ${ACTION_CORE_PLUGIN_TARGETS} + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + ) + +else() + + include(GNUInstallDirs) + + install(TARGETS action_core ${ACTION_CORE_PLUGIN_TARGETS} + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) + + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + ) + + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} + FILES_MATCHING PATTERN "*.h" + ) + +endif() + + +# ======================================================== +# Tests +# ======================================================== +if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN) + + if(NOT COMMAND catkin_add_gtest) + message(FATAL_ERROR "catkin_add_gtest NOT FOUND") + endif() + + set(ACTION_CORE_TESTS + action_registry_test + noop_action_handler_test + frame_sampler_test + wait_action_handler_test + log_report_action_handler_test + ) + + foreach(test_name ${ACTION_CORE_TESTS}) + catkin_add_gtest(${test_name} test/${test_name}.cpp) + + if(TARGET ${test_name}) + # catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make` + # thường, đúng quy trình verify của repo (chạy thẳng ./devel/lib//). + set_target_properties(${test_name} PROPERTIES EXCLUDE_FROM_ALL FALSE) + + target_compile_options(${test_name} PRIVATE -Wall -Wextra) + + target_include_directories(${test_name} + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/test + ) + + target_include_directories(${test_name} SYSTEM + PRIVATE + ${catkin_INCLUDE_DIRS} + ) + + # catkin_add_gtest dùng target_link_libraries dạng plain, nên phần bổ sung cũng phải plain. + # Plugin KHÔNG được link thẳng: chúng chỉ export alias Boost.DLL và được nạp qua + # ActionRegistry, đúng đường mà runtime đi. + target_link_libraries(${test_name} + action_core + ${catkin_LIBRARIES} + ${Boost_LIBRARIES} + yaml-cpp + pthread + ${CMAKE_DL_LIBS} + ${TF3_LIBRARY} + ) + + add_dependencies(${test_name} ${ACTION_CORE_PLUGIN_TARGETS}) + + # Đường tới cây config test và thư mục .so, để binary tự trỏ đúng chỗ khi chạy qua ctest + # (ctest không mang theo PNKX_NAV_CORE_CONFIG_DIR hay LD_LIBRARY_PATH của shell). + target_compile_definitions(${test_name} PRIVATE + ACTION_CORE_TEST_CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/config" + ACTION_CORE_TEST_LIBRARY_DIR="${CATKIN_DEVEL_PREFIX}/lib" + ) + endif() + endforeach() + +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..7229a65 --- /dev/null +++ b/README.md @@ -0,0 +1,94 @@ +# action_core + +Interface tick-based cho phần **thực thi action** của một mission, kèm bộ handler mặc định và +registry nạp plugin. + +Gói này không biết navigation là gì. Nó chỉ định nghĩa "một action được thực thi như thế nào" và cho +phép nạp thêm loại action mới bằng file `.so` — cùng khuôn với `recovery_core` cho recovery behavior. +Bên tiêu thụ hiện tại là `move_base2::ActionRunner`, nhưng contract không ràng buộc vào nó. + +## Contract + +```cpp +class ActionHandler +{ + virtual bool configure(const std::string& name, robot::NodeHandle& nh) = 0; + virtual std::vector supportedActionTypes() const = 0; + virtual bool start(const robot_protocol_msgs::Action& action, const robot::Time& now) = 0; + virtual ActionTick update(const robot::Time& now) = 0; // kRunning | kSucceeded | kFailed + virtual void cancel() = 0; +}; +``` + +Vòng đời: `configure` một lần khi nạp → `start` khi caller giao action → `update` mỗi control cycle +→ `cancel` nếu bị huỷ giữa chừng. + +Hai điều kiện bắt buộc, cả hai đều là ràng buộc an toàn chứ không phải khuyến nghị: + +1. **Không được block.** `update()` chạy trên control thread ở tần số điều khiển. Chờ thiết bị thì + giữ state nội bộ và trả `kRunning`; nhờ vậy cancel/pause/emergency luôn được phản hồi trong một + cycle. +2. **Phải tự timeout.** Đây là tầng 1 — tầng chính — trong contract 3 tầng, vì chỉ handler biết + ngưỡng đúng cho thiết bị của nó ("nâng kệ quá 20 s là bất thường" khác hẳn "sạc 30 phút là bình + thường"). Hai tầng còn lại thuộc về caller và cả hai đều là lưới cuối: `action_patience` của + state machine (mặc định tắt) và `mission_timeout` của mission layer. + +`ActionTick` cố ý **không mang vận tốc**: trong lúc chạy action không ai được phát `cmd_vel`. Action +cần chuyển động phải được mô hình hoá thành motion profile của navigation, không phải do handler tự +lái — hai nguồn vận tốc cùng lúc là lỗi đã tốn nhiều công để loại bỏ khỏi runtime này. + +## Bộ handler mặc định + +| Plugin | `actionType` mặc định | Chạy được trên robot thật? | +|---|---|---| +| `WaitActionHandler` | `wait` | **Có.** Chờ đúng khoảng thời gian lấy từ `actionParameters` của chính action (`duration`), có trần `max_duration`. Chờ chính là công việc, không giả vờ điều khiển gì | +| `LogReportActionHandler` | `logReport` | **Có.** Ghi nội dung action ra log rồi hoàn tất — đúng ngữ nghĩa mà VDA5050 định nghĩa cho action này | +| `NoopActionHandler` | `wait` (cấu hình được) | **Không — chỉ sim/dev.** Log rồi báo thành công sau `duration` giây. Một `PickUp` chạy qua đây nghĩa là robot báo "đã nâng kệ" trong khi càng nâng chưa nhúc nhích | + +`NoopActionHandler` vẫn có ba công dụng thật: cho `actionType` chưa có thiết bị chạy được, dựng +deployment end-to-end trước khi phần cứng sẵn sàng, và làm fault-injection (`hang: true`) cho test. + +## Cấu hình + +```yaml +actions: + handlers: + - {name: waiter, type: WaitActionHandler} + - {name: reporter, type: LogReportActionHandler} + + waiter: + action_types: [wait] + default_duration: 0.0 # [s] khi action không kèm tham số `duration` + max_duration: 600.0 # [s] trần cứng; vượt trần thì action THẤT BẠI, không bị cắt ngắn + + reporter: + action_types: [logReport] + +WaitActionHandler: + library_path: libaction_core_wait_action_handler +LogReportActionHandler: + library_path: libaction_core_log_report_action_handler +``` + +Danh sách `handlers` **được phép rỗng** — một hệ không có thiết bị nào thì mọi mission đều là +nav-only. Khi đó `ActionRegistry` chỉ cảnh báo, và bên tiêu thụ mới là chỗ từ chối action kèm lý do +nêu đích danh `actionType` không ai nhận. + +Thiếu khoá `library_path` là nguyên nhân phổ biến nhất của "plugin build xong nhưng runtime báo +không tìm thấy"; registry báo lỗi nêu đích danh khoá bị thiếu. + +## Build và test + +```bash +catkin_make --pkg action_core + +./devel/lib/action_core/action_registry_test +./devel/lib/action_core/wait_action_handler_test +./devel/lib/action_core/log_report_action_handler_test +./devel/lib/action_core/noop_action_handler_test +``` + +Test tự trỏ `PNKX_NAV_CORE_CONFIG_DIR` vào `test/config/` và `PNKX_NAV_CORE_LIBRARY_PATH` vào +`devel/lib` (`overwrite = 0`), nên chạy được thẳng qua `ctest` mà không cần source workspace. + +Viết handler mới: xem `docs/PLUGIN_GUIDE.md`. diff --git a/docs/PLUGIN_GUIDE.md b/docs/PLUGIN_GUIDE.md new file mode 100644 index 0000000..71a05ef --- /dev/null +++ b/docs/PLUGIN_GUIDE.md @@ -0,0 +1,170 @@ +# Viết một action handler mới + +Sáu bước. Không bước nào đụng vào `src/` của `action_core` hay của navigation — đó là mục tiêu của +kiến trúc plugin này. + +## 1. Viết plugin + +`plugins/lift_action_handler.cpp` (ví dụ: càng nâng nói chuyện qua PLC): + +```cpp +#include + +#include +#include + +namespace my_actions +{ + +class LiftActionHandler final : public action_core::ActionHandler +{ +public: + static action_core::ActionHandler::Ptr create() + { + return std::make_shared(); + } + + bool configure(const std::string& name, robot::NodeHandle& nh) override + { + name_ = name; + nh.param("action_types", action_types_, std::vector{ "PickUp", "DropDown" }); + nh.param("timeout", timeout_, 20.0); // [s] ngưỡng của CHÍNH thiết bị này + nh.param("device_address", address_, std::string("192.168.1.50")); + + // Cấu hình sai phải bị chặn ở đây, không phải lúc chạy: trả false thì registry không đăng ký + // handler và log nêu đích danh instance nào hỏng. + if (timeout_ <= 0.0) + { + robot::log_error("[my_actions] '%s': timeout must be > 0 s", name_.c_str()); + 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; + + // Đọc tham số của chính action — đây là chỗ fleet truyền thông tin cho từng lần chạy. + // Tham số hỏng thì TỪ CHỐI, đừng đoán: caller coi như action thất bại và fleet nhận được lý do. + if (!sendCommandToDevice(action)) + { + return false; + } + return true; + } + + action_core::ActionTick update(const robot::Time& now) override + { + action_core::ActionTick tick; + + // TẦNG 1 — bắt buộc. Không có nó, thiết bị câm lặng sẽ giữ robot đứng vĩnh viễn. + if ((now - started_at_).toSec() >= timeout_) + { + tick.status = action_core::ActionStatus::kFailed; + tick.message = "action '" + action_id_ + "': device did not answer in time"; + return tick; + } + + // KHÔNG block ở đây. Hỏi trạng thái không chờ, chưa xong thì trả kRunning. + if (deviceReportedDone()) + { + tick.status = action_core::ActionStatus::kSucceeded; + tick.message = "action '" + action_id_ + "' completed"; + return tick; + } + + tick.status = action_core::ActionStatus::kRunning; + return tick; + } + + void cancel() override + { + // Đưa thiết bị về trạng thái AN TOÀN, và không được treo: hàm này chạy trên control thread. + stopDevice(); + } + +private: + std::string name_, address_, action_id_; + std::vector action_types_; + double timeout_ = 20.0; // [s] + robot::Time started_at_; +}; + +} // namespace my_actions + +BOOST_DLL_ALIAS(my_actions::LiftActionHandler::create, LiftActionHandler) +``` + +## 2. Khai target trong CMake + +```cmake +add_action_core_plugin(my_actions_lift_action_handler plugins/lift_action_handler.cpp) +``` + +Nếu handler nằm ở gói khác thì gói đó tự `add_library(... SHARED)`, link `action_core`, và bật +`POSITION_INDEPENDENT_CODE`. + +## 3. Khai trong YAML + +```yaml +actions: + handlers: + - {name: lift, type: LiftActionHandler} + + lift: + action_types: [PickUp, DropDown] + timeout: 20.0 # [s] + device_address: "192.168.1.50" + +LiftActionHandler: + library_path: libmy_actions_lift_action_handler +``` + +Tên trong `type:` phải **khớp chính xác** tên trong `BOOST_DLL_ALIAS`. Khoá `library_path` là thứ +hay quên nhất. + +## 4. Kiểm `.so` đã ở đúng chỗ + +```bash +ls devel/lib | grep lift +nm -D --defined-only devel/lib/libmy_actions_lift_action_handler.so | grep LiftActionHandler +``` + +Boost.DLL là `dlsym` + `reinterpret_cast`, **không kiểm kiểu qua ranh giới `.so`**. Alias sai kiểu +vẫn nạp "thành công" rồi mọi lời gọi ảo trúng sai slot — lỗi chỉ hiện ra bằng một segfault ở cycle +đầu tiên. `nm -D` là cách duy nhất kiểm trước. + +## 5. Viết test + +Đăng ký thẳng vào registry, không cần `.so`: + +```cpp +action_core::ActionRegistry registry; +ASSERT_TRUE(registry.registerHandler(std::make_shared())); +``` + +Hoặc kiểm đúng đường runtime đi (`YAML → library_path → Boost.DLL → configure`) bằng +`registry.loadFromConfig(nh, "actions")` với một cây config test riêng — xem +`test/action_registry_test.cpp`. + +Bốn ca tối thiểu cho một handler thật: + +- thiết bị trả lời bình thường → `kSucceeded`; +- thiết bị câm lặng quá `timeout` → `kFailed` (**tầng 1 phải tự cắt**); +- tham số của action hỏng → `start()` trả false; +- `cancel()` giữa chừng → thiết bị về trạng thái an toàn, hàm không treo. + +## 6. Những lỗi hay gặp + +| Triệu chứng | Nguyên nhân | +|---|---| +| "no library found for 'X'" | thiếu khoá `X: {library_path: ...}` ở **root** của YAML | +| "could not load symbol 'X'" | tên trong `BOOST_DLL_ALIAS` khác tên trong `type:` | +| Nạp được nhưng segfault ở cycle đầu | alias export sai kiểu — kiểm bằng `nm -D` | +| "actionType 'Y' is already registered" | hai handler cùng nhận một type; registry từ chối thay vì ghi đè im lặng vì định tuyến khi đó phụ thuộc thứ tự dòng trong YAML | +| Handler không bao giờ được gọi | `actionType` fleet gửi khác `action_types` đã khai (chú ý hoa/thường: `PickUp` ≠ `pick`) | +| Robot đứng im vĩnh viễn ở một action | handler trả `kRunning` mãi và không tự timeout — vi phạm tầng 1 | diff --git a/include/action_core/action_context.h b/include/action_core/action_context.h new file mode 100644 index 0000000..56def00 --- /dev/null +++ b/include/action_core/action_context.h @@ -0,0 +1,52 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — cổng môi trường cấp cho handler một lần qua configure(). + * + * Author: DuongTD + *********************************************************************/ +#ifndef ACTION_CORE_ACTION_CONTEXT_H_ +#define ACTION_CORE_ACTION_CONTEXT_H_ + +#include + +namespace tf3 +{ +class BufferCore; +} + +namespace action_core +{ + +/** + * @struct ActionContext + * @brief Cổng môi trường cấp cho handler một lần qua `configure()`. + * + * Cùng vai trò với `recovery_core::RecoveryContext`: chỉ chứa **cổng**, không chứa dữ liệu động. + * Cổng nào bắt buộc là tuỳ handler — `configure()` của nó kiểm và trả false nếu thiếu, thay vì để + * phát hiện lúc chạy giữa ca. + * + * @note `tf` là con trỏ **không const** có chủ đích. Handler dò không chỉ *đọc* TF mà còn *ghi*: + * nó lấy mẫu pose thô, lọc, rồi `setTransform` kết quả đã ổn định vào cùng buffer để chặng + * sau tra. Đây là cách trả pose ra ngoài mà không phải thêm trường vào @ref ActionTick — + * tick chỉ mang trạng thái, không mang dữ liệu. + * + * @warning Con trỏ **non-owning**. Buffer thuộc navigation runtime và sống lâu hơn handler; handler + * không được giữ bản sao nào của dữ liệu bên trong nó qua các tick. + */ +struct ActionContext +{ + /// Buffer TF dùng chung với navigation. Có thể null — handler cần TF phải tự từ chối ở configure(). + tf3::BufferCore* tf = nullptr; + + /// Frame cố định để quy mọi pose về trước khi so sánh hay tích luỹ. Thường là `map`. + std::string global_frame = "map"; + + /// Frame gắn với thân robot. + std::string robot_base_frame = "base_link"; +}; + +} // namespace action_core + +#endif // ACTION_CORE_ACTION_CONTEXT_H_ diff --git a/include/action_core/action_handler.h b/include/action_core/action_handler.h new file mode 100644 index 0000000..d7bcceb --- /dev/null +++ b/include/action_core/action_handler.h @@ -0,0 +1,88 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — contract plugin thực thi một loại action. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ACTION_CORE_ACTION_HANDLER_H_ +#define ACTION_CORE_ACTION_HANDLER_H_ + +#include +#include +#include + +// robot_protocol_msgs/Action.h khai boost::shared_ptr nhưng không tự include — phải nạp trước nó, +// nếu không translation unit nào include Action.h đầu tiên sẽ hỏng. +#include + +#include +#include +#include + +#include +#include + +namespace action_core +{ + +/** + * @class ActionHandler + * @brief Thực thi một hoặc nhiều loại action (`actionType` của VDA5050). + * + * Đây là **interface duy nhất** của gói này và là ranh giới `.so`: đổi chữ ký thì phải đổi cả + * @ref ActionRegistry trong cùng một lần sửa, vì `boost::dll::import_alias` là `dlsym` + + * `reinterpret_cast` — không có kiểm kiểu nào bắt được sự lệch đó lúc biên dịch, và lỗi chỉ hiện ra + * bằng một lời gọi ảo trúng sai slot lúc chạy. + * + * Tick-based, cùng mô hình với recovery behavior và cùng lý do: handler được gọi từ **control + * thread** ở `controller_frequency`, nên nó **không được block**. Chờ thiết bị thì giữ state nội bộ + * và trả `kRunning`; nhờ vậy cancel/pause/emergency luôn được phản hồi trong một cycle. + * + * @warning **Handler phải tự timeout.** Đây là tầng 1 của contract 3 tầng và là tầng chính: chỉ + * handler biết ngưỡng đúng cho thiết bị của nó ("nâng kệ quá 20 s là bất thường" khác hẳn + * "sạc 30 phút là bình thường"). Hai tầng còn lại thuộc về caller: `action_patience` của + * state machine là lưới cuối và mặc định tắt, `mission_timeout` đo cả chặng. Một handler + * trả `kRunning` vĩnh viễn là handler viết sai contract. + * + * @note Trong lúc action chạy, **không ai được phát cmd_vel** (D8). Xem @ref ActionTick. + */ +class ActionHandler +{ +public: + using Ptr = std::shared_ptr; + + virtual ~ActionHandler() = default; + + /** + * @brief Cấu hình một lần. + * @param name Tên instance, dùng cho log. + * @param ctx Cổng môi trường (TF, frame). Handler cần cổng nào thì tự kiểm và trả false nếu + * thiếu — lỗi phải lộ lúc khởi động, không phải giữa ca. + * @param nh NodeHandle **đã được caller scope sẵn** vào namespace param của instance này. + * @return false nếu không chạy được với cấu hình này; registry sẽ không đăng ký handler. + */ + virtual bool configure(const std::string& name, const ActionContext& ctx, + robot::NodeHandle& nh) = 0; + + /// @brief Các `actionType` mà handler này nhận. Rỗng = không nhận gì (registry sẽ từ chối nạp). + virtual std::vector supportedActionTypes() const = 0; + + /** + * @brief Bắt đầu thực thi @p action. + * @param now Thời điểm hiện tại — mốc cho timeout của chính handler. + * @return false = từ chối khởi động; bên gọi coi như action thất bại và **không** tick tiếp. + */ + virtual bool start(const robot_protocol_msgs::Action& action, const robot::Time& now) = 0; + + /// @brief Một control cycle. Chỉ được gọi sau khi @ref start trả true. + virtual ActionTick update(const robot::Time& now) = 0; + + /// @brief Yêu cầu dừng an toàn. Handler phải đưa thiết bị về trạng thái an toàn, không treo. + virtual void cancel() = 0; +}; + +} // namespace action_core + +#endif // ACTION_CORE_ACTION_HANDLER_H_ diff --git a/include/action_core/action_registry.h b/include/action_core/action_registry.h new file mode 100644 index 0000000..d5e8151 --- /dev/null +++ b/include/action_core/action_registry.h @@ -0,0 +1,135 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — nạp và tra cứu ActionHandler theo actionType. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ACTION_CORE_ACTION_REGISTRY_H_ +#define ACTION_CORE_ACTION_REGISTRY_H_ + +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace action_core +{ + +/** + * @class ActionRegistry + * @brief Bảng tra `actionType` -> handler, nạp từ YAML bằng Boost.DLL. + * + * Khác `recovery_core::RecoveryRegistry` ở cấu trúc dữ liệu, và khác có lý do: recovery là **danh + * sách có thứ tự** (thử behavior 0 trước, hỏng thì sang 1), còn action được **định tuyến theo tên** + * — thứ tự khai trong YAML không mang ý nghĩa hành vi nào. Vì thế đây là bảng tra, không phải vector. + * + * Cấu hình mong đợi: + * + * @code{.yaml} + * actions: + * handlers: + * - {name: noop, type: NoopActionHandler} + * noop: + * action_types: [wait, pick, drop] + * duration: 2.0 # [s] + * timeout: 30.0 # [s] timeout tầng 1, của chính handler + * + * NoopActionHandler: + * library_path: libaction_core_noop_action_handler + * @endcode + * + * Khoá `library_path` là thứ hay quên nhất: thiếu nó thì plugin build xong vẫn báo "không tìm + * thấy" lúc chạy. Registry vì thế báo lỗi nêu **đích danh** khoá bị thiếu thay vì chỉ nói không nạp + * được. + * + * @note Không thread-safe. Nạp lúc khởi tạo, tra từ control thread. + */ +class ActionRegistry +{ +public: + ActionRegistry() = default; + ~ActionRegistry(); + + ActionRegistry(const ActionRegistry&) = delete; + ActionRegistry& operator=(const ActionRegistry&) = delete; + + /** + * @brief Cổng môi trường cấp cho mọi handler. Đặt TRƯỚC @ref loadFromConfig. + * + * Handler nhận context lúc `configure()`, tức một lần khi nạp — đặt sau đó là các handler đã nạp + * giữ context cũ. + */ + void setContext(const ActionContext& context); + + const ActionContext& context() const + { + return context_; + } + + /** + * @brief Nạp toàn bộ handler khai trong `/handlers`. + * @param nh NodeHandle gốc. + * @param ns Namespace chứa danh sách handler. + * @return false nếu có handler nào không nạp được. Các handler còn lại vẫn được đăng ký, và mỗi + * lỗi được log kèm lý do cụ thể. + * + * **Danh sách rỗng hoặc không có khoá `handlers` KHÔNG phải lỗi** — trả true kèm cảnh báo. Một hệ + * không có thiết bị nào thì mọi mission đều là nav-only; caller (`ActionRunner` của move_base2) + * mới là chỗ từ chối yêu cầu mang action, và nó từ chối ngay tại cửa với lý do rõ ràng. + */ + bool loadFromConfig(robot::NodeHandle& nh, const std::string& ns = "actions"); + + /** + * @brief Đăng ký một handler đã dựng sẵn (test, hoặc handler biên dịch thẳng vào host). + * @return false nếu handler null, không khai `actionType` nào, hoặc trùng type đã có chủ. + * + * Hai handler cùng nhận một `actionType` bị **từ chối** thay vì ghi đè im lặng: định tuyến khi đó + * phụ thuộc thứ tự nạp, tức phụ thuộc thứ tự dòng trong YAML — không ai đọc config mà đoán ra được + * điều đó. + */ + bool registerHandler(const ActionHandler::Ptr& handler); + + /// @brief Handler nhận @p action_type, hoặc nullptr. + ActionHandler* find(const std::string& action_type) const; + + /// @brief Số handler đã nạp (không phải số actionType). + std::size_t size() const + { + return handlers_.size(); + } + + /// @brief Mọi `actionType` đã có chủ. Dùng cho log và test. + std::vector actionTypes() const; + + void clear(); + +private: + /// Nạp một handler. Trả false kèm log lý do nếu hỏng ở bất kỳ bước nào. + bool loadOne(const std::string& name, const std::string& type, robot::NodeHandle& nh, + const std::string& ns); + + ActionContext context_; + + std::vector handlers_; + std::map by_type_; ///< non-owning, trỏ vào handlers_ + + /** + * Giữ factory của Boost.DLL sống đúng bằng vòng đời registry. + * + * Không phải biến thừa: factory nắm `shared_library` bên trong, thả nó ra là `.so` bị unload + * trong khi handler tạo từ nó vẫn còn sống — vtable trỏ vào vùng nhớ đã gỡ. + */ + std::vector> factories_; +}; + +} // namespace action_core + +#endif // ACTION_CORE_ACTION_REGISTRY_H_ diff --git a/include/action_core/action_types.h b/include/action_core/action_types.h new file mode 100644 index 0000000..990cd95 --- /dev/null +++ b/include/action_core/action_types.h @@ -0,0 +1,53 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — kiểu hợp đồng cho một lượt thực thi action. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ACTION_CORE_ACTION_TYPES_H_ +#define ACTION_CORE_ACTION_TYPES_H_ + +#include + +namespace action_core +{ + +/** + * @enum ActionStatus + * @brief Tiến trình của action đang chạy, trả về mỗi control cycle. + * + * Không có `kCancelled`: huỷ đi qua @ref ActionHandler::cancel và kết thúc lượt chạy ngay tại đó, + * caller không tick tiếp nên không có kết quả nào để mang trạng thái đó. Cùng lý do mà + * `recovery_core::RecoveryStatus::kCancelled` không bao giờ vượt ranh giới port. + */ +enum class ActionStatus +{ + kRunning, ///< Chưa xong, caller phải tiếp tục gọi update(). + kSucceeded, ///< Thiết bị đã hoàn tất thao tác. + kFailed ///< Không thực hiện được, hoặc quá thời gian của chính handler. +}; + +const char* toString(ActionStatus status); + +/** + * @struct ActionTick + * @brief Kết quả một control cycle. + * + * Khác tick của recovery, tick của action **không mang vận tốc lẫn path**: trong lúc chạy action + * không ai được phát cmd_vel (quyết định D8). Action cần chuyển động phải được mô hình hoá thành + * motion profile của navigation, không phải do handler tự lái. Đây là hàng rào an toàn — hai nguồn + * vận tốc cùng lúc là lỗi đã tốn nhiều công để loại bỏ khỏi runtime này — chứ không phải thiếu sót. + */ +struct ActionTick +{ + ActionStatus status = ActionStatus::kRunning; + + /// Mô tả người-đọc-được. Chỉ dùng để log khi trạng thái đổi, không để so sánh. + std::string message; +}; + +} // namespace action_core + +#endif // ACTION_CORE_ACTION_TYPES_H_ diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..55bbfa6 --- /dev/null +++ b/package.xml @@ -0,0 +1,48 @@ + + action_core + 0.1.0 + + Interface tick-based cho thực thi action của mission, kèm handler mặc định và registry nạp + plugin. + + Vòng đời: configure(name, nh) -> start(action, now) -> lặp update(now) -> [cancel()]. Handler + được tick từ control thread ở tần số điều khiển nên KHÔNG được block: chờ thiết bị thì giữ state + nội bộ và trả kRunning. Mỗi handler tự chịu trách nhiệm timeout theo thiết bị của nó — đó là + tầng chính trong contract 3 tầng, hai tầng còn lại (action_patience, mission_timeout) chỉ là + lưới cuối của caller. + + Tick của action cố ý KHÔNG mang vận tốc: trong lúc chạy action không ai được phát cmd_vel, chuyển + động phải là motion profile của navigation. Đây là hàng rào an toàn, không phải thiếu sót. + + Không chạy roscpp/ROS master; dùng lớp ROS-like robot_* (robot_cpp, robot_time, + robot_protocol_msgs). Handler build thành plugin Boost.DLL riêng, nạp qua ActionRegistry theo + khoá library_path trong YAML — thêm một loại action mới không phải sửa dòng nào của gói này. + + T800 Robotics + T800 Robotics + BSD + + catkin + + robot_cpp + robot_cpp + + robot_time + robot_time + + + robot_protocol_msgs + robot_protocol_msgs + + + tf3 + tf3 + + robot_xmlrpcpp + robot_xmlrpcpp + + yaml-cpp + yaml-cpp + + diff --git a/plugins/frame_sampler_action_handler.cpp b/plugins/frame_sampler_action_handler.cpp new file mode 100644 index 0000000..7fce3b6 --- /dev/null +++ b/plugins/frame_sampler_action_handler.cpp @@ -0,0 +1,515 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — handler dò: lấy mẫu một TF frame nhiễu, lọc, ghi ra một frame ổn định. + * + * Author: DuongTD + *********************************************************************/ + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace action_core +{ +namespace +{ +constexpr double kDefaultSettleDelay = 1.0; // [s] +constexpr double kDefaultSampleWindow = 2.0; // [s] +constexpr int kDefaultMinSamples = 20; +constexpr double kDefaultMaxSpreadXy = 0.03; // [m] +constexpr double kDefaultMaxSpreadYaw = 0.05; // [rad] +constexpr double kDefaultTimeout = 15.0; // [s] +constexpr const char* kFrameKey = "goal_frame"; + +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)); +} + +/// @brief Trung vị theo từng trục. Bền hơn trung bình trước outlier — LiDAR thỉnh thoảng bắt nhầm. +double median(std::vector v) +{ + const std::size_t mid = v.size() / 2; + std::nth_element(v.begin(), v.begin() + mid, v.end()); + const double hi = v[mid]; + if (v.size() % 2 != 0) + { + return hi; + } + std::nth_element(v.begin(), v.begin() + mid - 1, v.end()); + return 0.5 * (hi + v[mid - 1]); +} + +/** + * @brief Độ tản BỀN: 2 x phân vị 90 của độ lệch so với tâm. + * + * Không dùng `max - min`: một mẫu nhận nhầm duy nhất trong ba mươi mẫu sẽ thổi nó lên hàng mét và + * đánh hỏng cả lượt dò — mà đó đúng là tình huống trung vị sinh ra để chịu được. Cắt ở phân vị 90 + * cho phép tối đa 10% mẫu rác, đồng thời vẫn bắt được dữ liệu tản thật (khi ấy MỌI mẫu đều lệch, + * không chỉ vài mẫu). + */ +double robustSpread(std::vector deviations) +{ + if (deviations.empty()) + { + return 0.0; + } + const std::size_t idx = + std::min(deviations.size() - 1, static_cast(deviations.size() * 0.9)); + std::nth_element(deviations.begin(), deviations.begin() + idx, deviations.end()); + return 2.0 * deviations[idx]; +} +} // namespace + +/** + * @class FrameSamplerActionHandler + * @brief Dò: lấy mẫu một TF frame trong một cửa sổ thời gian, lọc nhiễu, ghi ra frame ổn định. + * + * Pose do LiDAR/camera sinh ra **dao động**. Bám thẳng vào nó là robot lắc theo nhiễu; chốt một mẫu + * bất kỳ là chốt cả sai số của đúng mẫu đó. Handler này đứng giữa: robot đứng yên (trong + * `EXECUTING_ACTIONS` không ai phát cmd_vel), thu mẫu trong `sample_window`, lọc, rồi ghi kết quả + * ra `output_frame`. Chặng kế tiếp trỏ `goal_frame` vào frame đó. + * + * ## Vì sao ghi ra TF thay vì trả pose qua tick + * + * @ref ActionTick cố ý chỉ mang **trạng thái**, không mang dữ liệu — thêm pose vào đó sẽ buộc mọi + * tầng ở giữa phải chở một trường mà chúng không hiểu. `tf3::BufferCore` ghi được, và navigation đã + * đọc chung buffer đó, nên kết quả đi tới nơi cần mà không đổi contract nào. + * + * ## Ba chỗ dễ sai khi lọc, đã xử lý + * + * 1. **Yaw không được lấy trung bình số học.** Mẫu quanh ±π cho ra ~0 — lệch 180°, robot vào trạm + * ngược đầu. Gộp bằng vector đơn vị: `atan2(mean(sin), mean(cos))`. + * 2. **x, y dùng trung vị**, không phải trung bình: một mẫu nhận nhầm chân kệ khác kéo trung bình đi + * vài cm. + * 3. **Gộp mẫu trong frame CỐ ĐỊNH** (`ctx.global_frame`), không phải `base_link`: robot còn nhúc + * nhích thì mẫu trong hệ thân xe không so sánh được với nhau. + * + * Thêm: **bỏ mẫu trùng timestamp**. TF cập nhật chậm hơn control loop, đọc mỗi cycle 30 Hz sẽ đếm + * cùng một pose thành 30 mẫu và `min_samples` mất hết ý nghĩa. + * + * ## Cổng chất lượng + * + * Độ tản vượt `max_spread_*` → `kFailed`. Dữ liệu tản nghĩa là **chưa nhìn rõ**, và trung bình của + * dữ liệu rác vẫn là rác. Hỏng ở đây thì `clear_queue_on_failure` xoá luôn chặng tiến-vào và chặng + * thao tác thiết bị phía sau — robot không lùi vào đâu cả. Đây là thứ mà một watchdog "không thấy + * gì" đơn thuần không bắt được: nó **thấy**, chỉ là không đáng tin. + * + * Param (namespace của instance): + * - `action_types` [list] actionType nội bộ, vd `[DetectCharger]` + * - `output_frame` [string] frame ghi ra; chặng sau trỏ vào đây + * - `input_frame` [string, ""] frame thô cố định; rỗng = lấy từ `actionParameters["goal_frame"]` + * - `settle_delay` [s] chờ robot đứng hẳn trước khi thu mẫu + * - `sample_window` [s] thời lượng thu mẫu + * - `min_samples` [int] ít hơn → kFailed + * - `max_spread_xy` [m] tản hơn → kFailed + * - `max_spread_yaw` [rad] + * - `timeout` [s] lưới cuối tầng 1 + * - `use_simulated_goal` [bool, false] chỉ dành cho Gazebo/dev: bỏ perception, chốt một pose + * tương đối với `simulated_parent_frame` thành `output_frame` tĩnh. Không bật trên robot thật. + * - `simulated_parent_frame` [string, "base_link"] parent của pose giả + * - `simulated_offset_x/y` [m], `simulated_offset_yaw` [rad] pose giả trong parent frame + */ +class FrameSamplerActionHandler final : public ActionHandler +{ +public: + FrameSamplerActionHandler() = 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) + { + // Không có TF thì handler này 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("[action_core] '%s': needs a TF buffer but the context has none.", + name_.c_str()); + return false; + } + + nh.param("action_types", action_types_, std::vector{}); + nh.param("output_frame", output_frame_, std::string()); + nh.param("input_frame", input_frame_, std::string()); + nh.param("settle_delay", settle_delay_, kDefaultSettleDelay); + nh.param("sample_window", sample_window_, kDefaultSampleWindow); + nh.param("min_samples", min_samples_, kDefaultMinSamples); + nh.param("max_spread_xy", max_spread_xy_, kDefaultMaxSpreadXy); + nh.param("max_spread_yaw", max_spread_yaw_, kDefaultMaxSpreadYaw); + nh.param("timeout", timeout_, kDefaultTimeout); + nh.param("use_simulated_goal", use_simulated_goal_, false); + nh.param("simulated_parent_frame", simulated_parent_frame_, std::string("base_link")); + nh.param("simulated_offset_x", simulated_offset_x_, 0.0); + nh.param("simulated_offset_y", simulated_offset_y_, 0.0); + nh.param("simulated_offset_yaw", simulated_offset_yaw_, 0.0); + + if (action_types_.empty()) + { + robot::log_error("[action_core] '%s': action_types is empty — never called.", name_.c_str()); + return false; + } + if (output_frame_.empty()) + { + robot::log_error("[action_core] '%s': output_frame is empty — the result would go nowhere.", + name_.c_str()); + return false; + } + if (output_frame_ == input_frame_) + { + // Ghi đè chính frame thô là tranh chấp với bên publish nó; giá trị lọc sẽ bị ghi lại ngay. + robot::log_error("[action_core] '%s': output_frame must differ from input_frame ('%s').", + name_.c_str(), input_frame_.c_str()); + return false; + } + if (!std::isfinite(settle_delay_) || settle_delay_ < 0.0 || + !std::isfinite(sample_window_) || sample_window_ <= 0.0) + { + robot::log_error("[action_core] '%s': settle_delay=%.3f / sample_window=%.3f invalid.", + name_.c_str(), settle_delay_, sample_window_); + return false; + } + if (min_samples_ < 1) + { + robot::log_error("[action_core] '%s': min_samples=%d must be >= 1.", name_.c_str(), + min_samples_); + return false; + } + if (!std::isfinite(max_spread_xy_) || max_spread_xy_ <= 0.0 || + !std::isfinite(max_spread_yaw_) || max_spread_yaw_ <= 0.0) + { + robot::log_error("[action_core] '%s': max_spread_xy/yaw must be > 0.", name_.c_str()); + return false; + } + if (timeout_ > 0.0 && timeout_ <= settle_delay_ + sample_window_) + { + // Timeout ngắn hơn thời gian thu mẫu thì action LUÔN hỏng — gần như chắc chắn gõ nhầm. + robot::log_error("[action_core] '%s': timeout=%.3f s <= settle_delay+sample_window=%.3f s; " + "the action would always fail.", + name_.c_str(), timeout_, settle_delay_ + sample_window_); + return false; + } + if (use_simulated_goal_) + { + if (simulated_parent_frame_.empty() || simulated_parent_frame_ == output_frame_) + { + robot::log_error("[action_core] '%s': simulated_parent_frame must be non-empty and differ " + "from output_frame.", + name_.c_str()); + return false; + } + if (!std::isfinite(simulated_offset_x_) || !std::isfinite(simulated_offset_y_) || + !std::isfinite(simulated_offset_yaw_)) + { + robot::log_error("[action_core] '%s': simulated goal offset is non-finite.", name_.c_str()); + 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; + samples_.clear(); + have_last_stamp_ = false; + simulated_goal_published_ = false; + + if (use_simulated_goal_) + { + if (!publishSimulatedGoal(now)) + { + return false; + } + simulated_goal_published_ = true; + robot::log_warning("[action_core] '%s': SIMULATION ONLY — published '%s' from fixed offset " + "(%.3f, %.3f, %.3f rad) in '%s'.", + name_.c_str(), output_frame_.c_str(), simulated_offset_x_, + simulated_offset_y_, simulated_offset_yaw_, + simulated_parent_frame_.c_str()); + return true; + } + + frame_ = input_frame_; + if (frame_.empty() && !readFrameParam(action, frame_)) + { + return false; + } + + robot::log_info("[action_core] '%s': sampling '%s' for %.2f s (settle %.2f s) -> '%s'.", + name_.c_str(), frame_.c_str(), sample_window_, settle_delay_, + output_frame_.c_str()); + return true; + } + + ActionTick update(const robot::Time& now) override + { + ActionTick tick; + if (simulated_goal_published_) + { + tick.status = ActionStatus::kSucceeded; + tick.message = "action '" + action_id_ + "': simulated static frame '" + output_frame_ + "'"; + return tick; + } + + const double elapsed = (now - started_at_).toSec(); // [s] + + // Timeout TẦNG 1: frame thô không bao giờ xuất hiện thì phải thoát, không treo control loop. + if (timeout_ > 0.0 && elapsed >= timeout_) + { + tick.status = ActionStatus::kFailed; + tick.message = "action '" + action_id_ + "': frame '" + frame_ + "' did not appear in time"; + return tick; + } + + // Robot vừa dừng vẫn còn dao động cơ khí; pose dò được lúc này mang theo dao động đó. + if (elapsed >= settle_delay_) + { + collectSample(); + } + + if (elapsed < settle_delay_ + sample_window_) + { + tick.status = ActionStatus::kRunning; + return tick; + } + + if (static_cast(samples_.size()) < min_samples_) + { + tick.status = ActionStatus::kFailed; + tick.message = "action '" + action_id_ + "': only " + std::to_string(samples_.size()) + + " sample(s) of '" + frame_ + "', need " + std::to_string(min_samples_); + return tick; + } + + Sample filtered; + double spread_xy = 0.0; + double spread_yaw = 0.0; + filter(filtered, spread_xy, spread_yaw); + + if (spread_xy > max_spread_xy_ || spread_yaw > max_spread_yaw_) + { + // Thấy, nhưng không đáng tin. Khác hẳn "không thấy gì" — và nguy hiểm hơn, vì trung bình của + // dữ liệu rác vẫn ra một con số trông hợp lý. + tick.status = ActionStatus::kFailed; + tick.message = "action '" + action_id_ + "': detection unstable (spread xy=" + + std::to_string(spread_xy) + " m, yaw=" + std::to_string(spread_yaw) + " rad)"; + return tick; + } + + if (!publish(filtered, 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(samples_.size()) + " sample(s)"; + return tick; + } + + void cancel() override + { + // Không có thiết bị nào để dừng; chỉ bỏ mẫu để lượt sau không thừa hưởng dữ liệu cũ. + samples_.clear(); + have_last_stamp_ = false; + simulated_goal_published_ = false; + } + +private: + struct Sample + { + double x = 0.0; + double y = 0.0; + double yaw = 0.0; // [rad] + }; + + bool readFrameParam(const robot_protocol_msgs::Action& action, std::string& frame) const + { + const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(), + [](const robot_protocol_msgs::ActionParameter& p) { + return p.key == kFrameKey; + }); + + if (it == action.actionParameters.end() || it->value.empty()) + { + robot::log_error("[action_core] '%s': action '%s' has no '%s' parameter and no input_frame " + "configured — nothing to detect.", + name_.c_str(), action.actionId.c_str(), kFrameKey); + return false; + } + + frame = it->value; + return true; + } + + /// @brief Đọc một mẫu MỚI của frame thô, quy về global frame. Mẫu trùng timestamp bị bỏ. + void collectSample() + { + tf3::TransformStampedMsg tf; + try + { + tf = ctx_.tf->lookupTransform(ctx_.global_frame, frame_, tf3::Time()); + } + catch (const std::exception&) + { + return; // Chưa dò ra. Không log ở đây: hàm này chạy mỗi control cycle. + } + + // TF cập nhật chậm hơn control loop; không lọc theo timestamp thì cùng một pose bị đếm nhiều + // lần và `min_samples` mất hết ý nghĩa. + if (have_last_stamp_ && tf.header.stamp == last_stamp_) + { + return; + } + last_stamp_ = tf.header.stamp; + have_last_stamp_ = true; + + Sample s; + s.x = tf.transform.translation.x; + s.y = tf.transform.translation.y; + s.yaw = yawOf(tf.transform.rotation); + samples_.push_back(s); + } + + void filter(Sample& out, double& spread_xy, double& spread_yaw) const + { + std::vector xs, ys; + xs.reserve(samples_.size()); + ys.reserve(samples_.size()); + + double sum_sin = 0.0; + double sum_cos = 0.0; + + for (const Sample& s : samples_) + { + xs.push_back(s.x); + ys.push_back(s.y); + sum_sin += std::sin(s.yaw); + sum_cos += std::cos(s.yaw); + } + + out.x = median(xs); + out.y = median(ys); + + // Gộp góc bằng vector đơn vị. Trung bình số học của các mẫu quanh ±π cho ra ~0 — lệch 180°. + out.yaw = std::atan2(sum_sin, sum_cos); + + // Độ tản đo quanh TÂM ĐÃ LỌC, không phải min-max thô: xem robustSpread. + std::vector dev_xy; + std::vector dev_yaw; + dev_xy.reserve(samples_.size()); + dev_yaw.reserve(samples_.size()); + + for (const Sample& s : samples_) + { + dev_xy.push_back(std::hypot(s.x - out.x, s.y - out.y)); + // Lệch góc phải quy về (-pi, pi], nếu không mẫu ở hai bên đường cắt bị tính thành ~2pi. + dev_yaw.push_back( + std::fabs(std::atan2(std::sin(s.yaw - out.yaw), std::cos(s.yaw - out.yaw)))); + } + + spread_xy = robustSpread(std::move(dev_xy)); + spread_yaw = robustSpread(std::move(dev_yaw)); + } + + bool publish(const Sample& 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, "action_core/" + name_, /*is_static=*/true); + } + + bool publishSimulatedGoal(const robot::Time& now) + { + tf3::TransformStampedMsg parent; + try + { + parent = ctx_.tf->lookupTransform(ctx_.global_frame, simulated_parent_frame_, tf3::Time()); + } + catch (const std::exception&) + { + robot::log_error("[action_core] '%s': simulation parent frame '%s' is unavailable.", + name_.c_str(), simulated_parent_frame_.c_str()); + return false; + } + + const double parent_yaw = yawOf(parent.transform.rotation); + Sample simulated; + simulated.x = parent.transform.translation.x + + std::cos(parent_yaw) * simulated_offset_x_ - + std::sin(parent_yaw) * simulated_offset_y_; + simulated.y = parent.transform.translation.y + + std::sin(parent_yaw) * simulated_offset_x_ + + std::cos(parent_yaw) * simulated_offset_y_; + simulated.yaw = parent_yaw + simulated_offset_yaw_; + return publish(simulated, now); + } + + std::string name_; + ActionContext ctx_; + + std::vector action_types_; + std::string output_frame_; + std::string input_frame_; + double settle_delay_ = kDefaultSettleDelay; + double sample_window_ = kDefaultSampleWindow; + int min_samples_ = kDefaultMinSamples; + double max_spread_xy_ = kDefaultMaxSpreadXy; + double max_spread_yaw_ = kDefaultMaxSpreadYaw; + double timeout_ = kDefaultTimeout; + bool use_simulated_goal_ = false; + std::string simulated_parent_frame_ = "base_link"; + double simulated_offset_x_ = 0.0; // [m] + double simulated_offset_y_ = 0.0; // [m] + double simulated_offset_yaw_ = 0.0; // [rad] + + robot::Time started_at_; + std::string action_id_; + std::string frame_; + std::vector samples_; + tf3::Time last_stamp_; + bool have_last_stamp_ = false; + bool simulated_goal_published_ = false; +}; + +} // namespace action_core + +BOOST_DLL_ALIAS(action_core::FrameSamplerActionHandler::create, FrameSamplerActionHandler) diff --git a/plugins/log_report_action_handler.cpp b/plugins/log_report_action_handler.cpp new file mode 100644 index 0000000..197b51f --- /dev/null +++ b/plugins/log_report_action_handler.cpp @@ -0,0 +1,118 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — handler mặc định cho action `logReport`: ghi nhật ký tại chỗ rồi hoàn tất. + * + * Author: DuongTD + *********************************************************************/ + +#include + +#include +#include +#include + +#include +#include + +namespace action_core +{ + +/** + * @class LogReportActionHandler + * @brief Ghi toàn bộ nội dung action ra log rồi báo hoàn tất ngay ở tick đầu. + * + * `logReport` là action tiêu chuẩn của VDA5050 với ngữ nghĩa "AGV ghi lại một mốc chẩn đoán tại + * điểm này" — không có thiết bị nào phải cử động, nên handler này là hiện thực **đầy đủ và đúng**, + * không phải stub. Đây là điểm khác biệt so với @ref NoopActionHandler: Noop giả vờ làm một việc mà + * nó không làm, còn lớp này làm đúng việc mà action yêu cầu. + * + * Nó cũng là ví dụ tham chiếu ngắn nhất cho contract: một handler hợp lệ tối thiểu cần đúng bốn hàm + * và không cần state nào ngoài `action_id_`. + * + * Param (namespace của instance): + * - `action_types` [list, mặc định `["logReport"]`] + */ +class LogReportActionHandler final : public ActionHandler +{ +public: + LogReportActionHandler() = default; + + static ActionHandler::Ptr create() + { + return std::make_shared(); + } + + bool configure(const std::string& name, const ActionContext& /*ctx*/, + robot::NodeHandle& nh) override + { + name_ = name; + nh.param("action_types", action_types_, std::vector{ "logReport" }); + + if (action_types_.empty()) + { + robot::log_error("[action_core] '%s': action_types is empty — this handler would never be " + "called.", name_.c_str()); + return false; + } + return true; + } + + std::vector supportedActionTypes() const override + { + return action_types_; + } + + bool start(const robot_protocol_msgs::Action& action, const robot::Time&) override + { + action_id_ = action.actionId; + + // In cả tham số: giá trị của một logReport nằm ở chỗ nó ghi được thứ fleet muốn ghi, và mất + // tham số nghĩa là mất chính nội dung đó. + std::string params; + for (const auto& parameter : action.actionParameters) + { + if (!params.empty()) + { + params += ", "; + } + params += parameter.key + "=" + parameter.value; + } + + robot::log_info("[action_core] '%s': logReport '%s'%s%s", name_.c_str(), action_id_.c_str(), + action.actionDescription.empty() ? "" : " — ", + action.actionDescription.empty() ? "" : action.actionDescription.c_str()); + + if (!params.empty()) + { + robot::log_info("[action_core] '%s': parameters: %s", name_.c_str(), params.c_str()); + } + + return true; + } + + ActionTick update(const robot::Time&) override + { + // Không có gì để chờ: việc đã xong ngay trong start(). Vẫn phải trả qua update() vì contract + // quy định kết quả chỉ đến từ tick — caller không suy kết quả từ giá trị trả về của start(). + ActionTick tick; + tick.status = ActionStatus::kSucceeded; + tick.message = "action '" + action_id_ + "' logged"; + return tick; + } + + void cancel() override + { + // Không có trạng thái nào để hoàn tác. + } + +private: + std::string name_; + std::vector action_types_{ "logReport" }; + std::string action_id_; +}; + +} // namespace action_core + +BOOST_DLL_ALIAS(action_core::LogReportActionHandler::create, LogReportActionHandler) diff --git a/plugins/noop_action_handler.cpp b/plugins/noop_action_handler.cpp new file mode 100644 index 0000000..519a80e --- /dev/null +++ b/plugins/noop_action_handler.cpp @@ -0,0 +1,177 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — handler mặc định: log rồi báo xong sau một khoảng thời gian. + * + * Author: DuongTD + *********************************************************************/ + +#include + +#include +#include +#include +#include + +#include +#include + +namespace action_core +{ +namespace +{ +constexpr double kDefaultDuration = 0.0; // [s] 0 = xong ngay ở tick đầu. +constexpr double kMaxDuration = 600.0; // [s] trần vệ sinh cho param cấu hình sai. +constexpr double kDefaultTimeout = 30.0; // [s] +} // namespace + +/** + * @class NoopActionHandler + * @brief Handler mặc định — không điều khiển thiết bị nào, chỉ log và đếm giờ. + * + * Có ba công dụng thật, không phải chỗ giữ chỗ: + * 1. cho `actionType` chưa có thiết bị tương ứng (`wait`, hoặc action chỉ mang ý nghĩa ghi nhật ký) + * chạy được mà không phải viết handler riêng; + * 2. dựng một deployment chạy end-to-end trước khi phần cứng sẵn sàng; + * 3. làm ví dụ tham chiếu cho contract — đặc biệt là **timeout tầng 1**. + * + * `duration = 0` nghĩa là xong ngay ở tick đầu. Đặt > 0 để mô phỏng một thiết bị chậm; đặt + * `hang: true` để mô phỏng thiết bị không bao giờ trả lời — khi đó chỉ `timeout` cắt được, đúng + * tình huống mà timeout tầng 1 sinh ra để xử lý. + * + * @warning Trên robot thật, một action `PickUp` chạy qua handler này nghĩa là robot báo "đã nâng kệ" + * trong khi càng nâng chưa hề nhúc nhích, và fleet master sẽ giao chặng tiếp theo với giả + * định hàng đã ở trên xe. Chỉ dùng cho sim/dev. + */ +class NoopActionHandler final : public ActionHandler +{ +public: + NoopActionHandler() = default; + + static ActionHandler::Ptr create() + { + return std::make_shared(); + } + + bool configure(const std::string& name, const ActionContext& /*ctx*/, + robot::NodeHandle& nh) override + { + name_ = name; + + nh.param("duration", duration_, kDefaultDuration); + nh.param("timeout", timeout_, kDefaultTimeout); + nh.param("hang", hang_, false); + nh.param("action_types", action_types_, std::vector{ "wait" }); + + if (!std::isfinite(duration_) || duration_ < 0.0 || duration_ > kMaxDuration) + { + robot::log_warning("[action_core] '%s': duration=%.3f s outside [0, %.0f]; using %.3f s.", + name_.c_str(), duration_, kMaxDuration, kDefaultDuration); + duration_ = kDefaultDuration; + } + + if (!std::isfinite(timeout_) || timeout_ < 0.0) + { + robot::log_warning("[action_core] '%s': timeout=%.3f s is invalid; using %.3f s.", + name_.c_str(), timeout_, kDefaultTimeout); + timeout_ = kDefaultTimeout; + } + + if (hang_ && timeout_ <= 0.0) + { + // Chế độ mô phỏng thiết bị treo mà lại tắt timeout thì action sẽ chạy vĩnh viễn — đúng thứ + // contract cấm. + robot::log_error("[action_core] '%s': hang=true but timeout=%.3f s; the handler would never " + "finish.", name_.c_str(), timeout_); + return false; + } + + if (!hang_ && timeout_ > 0.0 && duration_ > 0.0 && timeout_ <= duration_) + { + // Cấu hình này khiến action LUÔN hỏng vì timeout — gần như chắc chắn là gõ nhầm. + robot::log_error("[action_core] '%s': timeout=%.3f s <= duration=%.3f s; the action would " + "always fail.", name_.c_str(), timeout_, duration_); + return false; + } + + if (action_types_.empty()) + { + robot::log_error("[action_core] '%s': action_types is empty — this handler would never be " + "called.", name_.c_str()); + 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; + + robot::log_info("[action_core] '%s': starting action '%s' (id '%s'), duration %.3f s.", + name_.c_str(), action.actionType.c_str(), action.actionId.c_str(), duration_); + return true; + } + + ActionTick update(const robot::Time& now) override + { + ActionTick tick; + const double elapsed = (now - started_at_).toSec(); // [s] + + // Timeout TẦNG 1 — trách nhiệm của chính handler, không dựa vào action_patience của state + // machine (mặc định tắt). Ở đây ngưỡng là cấu hình vì handler này không nói chuyện với thiết bị + // nào; handler thật thì suy ngưỡng từ hiểu biết về thiết bị của nó. + if (timeout_ > 0.0 && elapsed >= timeout_) + { + tick.status = ActionStatus::kFailed; + tick.message = "action '" + action_id_ + "' exceeded its timeout"; + return tick; + } + + if (hang_) + { + // Mô phỏng thiết bị không bao giờ trả lời. Có để fault-injection trong test tích hợp: đây là + // đúng tình huống mà timeout tầng 1 sinh ra để xử lý. + tick.status = ActionStatus::kRunning; + return tick; + } + + if (elapsed >= duration_) + { + tick.status = ActionStatus::kSucceeded; + tick.message = "action '" + action_id_ + "' completed"; + return tick; + } + + tick.status = ActionStatus::kRunning; + return tick; + } + + void cancel() override + { + // Không có thiết bị nào để đưa về trạng thái an toàn. Handler thật phải làm việc đó ở đây. + robot::log_info("[action_core] '%s': action '%s' cancelled.", name_.c_str(), + action_id_.c_str()); + } + +private: + std::string name_; + std::vector action_types_{ "wait" }; + double duration_ = kDefaultDuration; ///< [s] + double timeout_ = kDefaultTimeout; ///< [s] 0 = không giới hạn + bool hang_ = false; ///< true = không bao giờ hoàn tất (fault injection) + + robot::Time started_at_; + std::string action_id_; +}; + +} // namespace action_core + +BOOST_DLL_ALIAS(action_core::NoopActionHandler::create, NoopActionHandler) diff --git a/plugins/wait_action_handler.cpp b/plugins/wait_action_handler.cpp new file mode 100644 index 0000000..9f34942 --- /dev/null +++ b/plugins/wait_action_handler.cpp @@ -0,0 +1,195 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — handler mặc định cho action `wait`: chờ đúng khoảng thời gian order yêu cầu. + * + * Author: DuongTD + *********************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace action_core +{ +namespace +{ +constexpr double kDefaultDuration = 0.0; // [s] khi order không kèm tham số nào. +constexpr double kDefaultMaxDuration = 600.0; // [s] trần vệ sinh cho tham số gõ nhầm. +constexpr const char* kDurationKey = "duration"; +} // namespace + +/** + * @class WaitActionHandler + * @brief Chờ một khoảng thời gian lấy từ **actionParameters của chính order**. + * + * Khác @ref NoopActionHandler ở điểm quyết định: `Noop` là stub — thời lượng nằm trong YAML và mọi + * lần chạy đều như nhau. `Wait` là handler **thật**: chờ chính là công việc, và thời lượng do fleet + * master quyết định cho từng action một qua `actionParameters: [{key: duration, value: "5.0"}]`. + * + * Đây là handler duy nhất trong bộ default có thể chạy trên robot thật mà không nói dối ai: nó + * không giả vờ điều khiển thiết bị nào, nó chỉ đếm giờ — và đó đúng là thứ action `wait` yêu cầu. + * + * Param (namespace của instance): + * - `action_types` [list, mặc định `["wait"]`] + * - `default_duration` [s, mặc định 0.0]: dùng khi action **không** kèm tham số `duration`. + * - `max_duration` [s, mặc định 600.0]: trần cứng. Vượt trần thì action **thất bại**, không phải + * bị cắt xuống — một order yêu cầu chờ 2 giờ gần như chắc chắn là gõ nhầm, và im lặng rút ngắn + * nó xuống 10 phút là giấu đi lỗi cấu hình của fleet. + */ +class WaitActionHandler final : public ActionHandler +{ +public: + WaitActionHandler() = default; + + static ActionHandler::Ptr create() + { + return std::make_shared(); + } + + bool configure(const std::string& name, const ActionContext& /*ctx*/, + robot::NodeHandle& nh) override + { + name_ = name; + + nh.param("action_types", action_types_, std::vector{ "wait" }); + nh.param("default_duration", default_duration_, kDefaultDuration); + nh.param("max_duration", max_duration_, kDefaultMaxDuration); + + if (action_types_.empty()) + { + robot::log_error("[action_core] '%s': action_types is empty — this handler would never be " + "called.", name_.c_str()); + return false; + } + + if (!std::isfinite(max_duration_) || max_duration_ <= 0.0) + { + robot::log_error("[action_core] '%s': max_duration=%.3f s must be > 0.", name_.c_str(), + max_duration_); + return false; + } + + if (!std::isfinite(default_duration_) || default_duration_ < 0.0 || + default_duration_ > max_duration_) + { + robot::log_error("[action_core] '%s': default_duration=%.3f s outside [0, %.3f].", + name_.c_str(), default_duration_, max_duration_); + 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 + { + action_id_ = action.actionId; + started_at_ = now; + + if (!readDuration(action, duration_)) + { + // Từ chối khởi động thay vì chờ một khoảng thời gian đoán bừa: caller coi như action hỏng và + // fleet nhận được lý do, thay vì robot đứng im một lúc không ai giải thích được. + return false; + } + + robot::log_info("[action_core] '%s': waiting %.3f s for action '%s' (id '%s').", name_.c_str(), + duration_, action.actionType.c_str(), action_id_.c_str()); + return true; + } + + ActionTick update(const robot::Time& now) override + { + ActionTick tick; + const double elapsed = (now - started_at_).toSec(); // [s] + + // Timeout tầng 1 chính là điều kiện hoàn tất: `duration_` đã bị chặn trên bởi `max_duration_` + // ngay tại start(), nên handler này không thể chạy vô hạn. + if (elapsed >= duration_) + { + tick.status = ActionStatus::kSucceeded; + tick.message = "action '" + action_id_ + "' waited " + std::to_string(duration_) + " s"; + return tick; + } + + tick.status = ActionStatus::kRunning; + return tick; + } + + void cancel() override + { + // Không có thiết bị nào để đưa về trạng thái an toàn — chờ thì dừng chờ là xong. + robot::log_info("[action_core] '%s': wait '%s' cancelled.", name_.c_str(), action_id_.c_str()); + } + +private: + /// @brief Đọc `duration` từ actionParameters. Trả false kèm log nếu giá trị không dùng được. + bool readDuration(const robot_protocol_msgs::Action& action, double& duration) const + { + const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(), + [](const robot_protocol_msgs::ActionParameter& p) { + return p.key == kDurationKey; + }); + + if (it == action.actionParameters.end()) + { + duration = default_duration_; + return true; + } + + try + { + duration = std::stod(it->value); + } + catch (const std::exception&) + { + robot::log_error("[action_core] '%s': action '%s' has duration='%s' which is not a number.", + name_.c_str(), action.actionId.c_str(), it->value.c_str()); + return false; + } + + if (!std::isfinite(duration) || duration < 0.0) + { + robot::log_error("[action_core] '%s': action '%s' has duration=%.3f s — must be >= 0.", + name_.c_str(), action.actionId.c_str(), duration); + return false; + } + + if (duration > max_duration_) + { + robot::log_error("[action_core] '%s': action '%s' asks for %.3f s but max_duration is " + "%.3f s — refusing instead of silently shortening it.", + name_.c_str(), action.actionId.c_str(), duration, max_duration_); + return false; + } + + return true; + } + + std::string name_; + std::vector action_types_{ "wait" }; + double default_duration_ = kDefaultDuration; ///< [s] + double max_duration_ = kDefaultMaxDuration; ///< [s] + + robot::Time started_at_; + double duration_ = 0.0; ///< [s] của action đang chạy + std::string action_id_; +}; + +} // namespace action_core + +BOOST_DLL_ALIAS(action_core::WaitActionHandler::create, WaitActionHandler) diff --git a/src/action_registry.cpp b/src/action_registry.cpp new file mode 100644 index 0000000..8972867 --- /dev/null +++ b/src/action_registry.cpp @@ -0,0 +1,225 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — cài đặt ActionRegistry. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include + +#include +#include +#include + +#include +#include + +namespace action_core +{ + +ActionRegistry::~ActionRegistry() +{ + clear(); +} + +void ActionRegistry::clear() +{ + // Thứ tự bắt buộc: handler phải chết TRƯỚC factory, vì factory là thứ giữ `.so` còn nạp. + by_type_.clear(); + handlers_.clear(); + factories_.clear(); +} + +void ActionRegistry::setContext(const ActionContext& context) +{ + context_ = context; +} + +bool ActionRegistry::registerHandler(const ActionHandler::Ptr& handler) +{ + if (!handler) + { + robot::log_error("[action_core] ActionRegistry: handler is null."); + return false; + } + + const std::vector types = handler->supportedActionTypes(); + if (types.empty()) + { + robot::log_error("[action_core] ActionRegistry: handler declares no actionType — it would never " + "be called."); + return false; + } + + // Kiểm TRƯỚC khi ghi bất cứ gì: một type trùng ở giữa danh sách không được để lại registry ở + // trạng thái nửa vời. + for (const std::string& type : types) + { + if (type.empty()) + { + robot::log_error("[action_core] ActionRegistry: handler declares an empty actionType."); + return false; + } + if (by_type_.find(type) != by_type_.end()) + { + robot::log_error("[action_core] ActionRegistry: actionType '%s' is already registered by " + "another handler.", + type.c_str()); + return false; + } + } + + handlers_.push_back(handler); + for (const std::string& type : types) + { + by_type_[type] = handler.get(); + } + return true; +} + +ActionHandler* ActionRegistry::find(const std::string& action_type) const +{ + const auto it = by_type_.find(action_type); + return it == by_type_.end() ? nullptr : it->second; +} + +std::vector ActionRegistry::actionTypes() const +{ + std::vector types; + types.reserve(by_type_.size()); + for (const auto& entry : by_type_) + { + types.push_back(entry.first); + } + return types; +} + +bool ActionRegistry::loadOne(const std::string& name, const std::string& type, + robot::NodeHandle& nh, const std::string& ns) +{ + robot::PluginLoaderHelper loader(nh); + const std::string library_path = loader.findLibraryPath(type); + + if (library_path.empty()) + { + robot::log_error("[action_core] ActionRegistry: no library found for '%s' — check the key " + "'%s/library_path' in the YAML and that the .so file exists.", + type.c_str(), type.c_str()); + return false; + } + + std::function factory; + try + { + factory = boost::dll::import_alias( + library_path, type, boost::dll::load_mode::append_decorations); + } + catch (const boost::system::system_error& ex) + { + robot::log_error("[action_core] ActionRegistry: could not load symbol '%s' from '%s': %s", + type.c_str(), library_path.c_str(), ex.what()); + return false; + } + catch (const std::exception& ex) + { + robot::log_error("[action_core] ActionRegistry: error while loading '%s': %s", type.c_str(), + ex.what()); + return false; + } + + ActionHandler::Ptr handler; + try + { + handler = factory(); + } + catch (const std::exception& ex) + { + robot::log_error("[action_core] ActionRegistry: factory of '%s' threw an exception: %s", + type.c_str(), ex.what()); + return false; + } + + if (!handler) + { + robot::log_error("[action_core] ActionRegistry: factory of '%s' returned null.", type.c_str()); + return false; + } + + const std::string param_ns = ns.empty() ? name : ns + "/" + name; + robot::NodeHandle handler_nh(nh, param_ns); + + if (!handler->configure(name, context_, handler_nh)) + { + robot::log_error("[action_core] ActionRegistry: '%s' (instance '%s') configure() failed.", + type.c_str(), name.c_str()); + return false; + } + + if (!registerHandler(handler)) + { + return false; + } + + // Chỉ giữ factory SAU khi đăng ký thành công: handler bị từ chối thì `.so` không có lý do ở lại. + factories_.push_back(std::move(factory)); + + robot::log_info("[action_core] ActionRegistry: loaded '%s' (instance '%s').", type.c_str(), + name.c_str()); + return true; +} + +bool ActionRegistry::loadFromConfig(robot::NodeHandle& nh, const std::string& ns) +{ + const std::string key = ns.empty() ? std::string("handlers") : ns + "/handlers"; + + YAML::Node list; + if (!nh.getParam(key, list) || !list.IsSequence()) + { + // Không có handler nào là hợp lệ — xem doc của hàm này. + robot::log_warning("[action_core] ActionRegistry: '%s' has no handler list; no action can be " + "executed.", key.c_str()); + return true; + } + + bool all_ok = true; + + for (std::size_t i = 0; i < list.size(); ++i) + { + const YAML::Node& entry = list[i]; + + if (!entry.IsMap() || !entry["type"]) + { + robot::log_error("[action_core] ActionRegistry: '%s[%zu]' is missing the 'type' key.", + key.c_str(), i); + all_ok = false; + continue; + } + + std::string type; + std::string name; + try + { + type = entry["type"].as(); + name = entry["name"] ? entry["name"].as() : type; + } + catch (const YAML::Exception& ex) + { + robot::log_error("[action_core] ActionRegistry: '%s[%zu]' could not be read: %s", key.c_str(), + i, ex.what()); + all_ok = false; + continue; + } + + if (!loadOne(name, type, nh, ns)) + { + all_ok = false; + } + } + + return all_ok; +} + +} // namespace action_core diff --git a/src/action_types.cpp b/src/action_types.cpp new file mode 100644 index 0000000..165b382 --- /dev/null +++ b/src/action_types.cpp @@ -0,0 +1,28 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * action_core — tên trạng thái cho log. + * + * Author: DuongTD + *********************************************************************/ +#include + +namespace action_core +{ + +const char* toString(ActionStatus status) +{ + switch (status) + { + case ActionStatus::kRunning: + return "RUNNING"; + case ActionStatus::kSucceeded: + return "SUCCEEDED"; + case ActionStatus::kFailed: + return "FAILED"; + } + return "UNKNOWN"; +} + +} // namespace action_core diff --git a/test/action_registry_test.cpp b/test/action_registry_test.cpp new file mode 100644 index 0000000..42d60bd --- /dev/null +++ b/test/action_registry_test.cpp @@ -0,0 +1,267 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm đường nạp plugin thật: YAML -> library_path -> Boost.DLL -> configure -> tra theo actionType. + * + * Đây là đường mà runtime đi, nên nó phải được kiểm bằng `.so` thật chứ không phải bằng handler + * dựng sẵn. Phần đăng ký trực tiếp (registerHandler) được kiểm riêng bên dưới bằng handler giả. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include +#include +#include + +#include + +#include + +namespace +{ +using action_core::ActionHandler; +using action_core::ActionRegistry; +using action_core::ActionStatus; +using action_core::ActionTick; + +/// @brief Handler giả, không qua Boost.DLL — dùng cho phần contract của registerHandler(). +class FakeHandler final : public ActionHandler +{ +public: + explicit FakeHandler(std::vector types) : types_(std::move(types)) + { + } + + bool configure(const std::string&, const action_core::ActionContext&, + robot::NodeHandle&) override + { + return true; + } + + std::vector supportedActionTypes() const override + { + return types_; + } + + bool start(const robot_protocol_msgs::Action&, const robot::Time&) override + { + return true; + } + + ActionTick update(const robot::Time&) override + { + ActionTick tick; + tick.status = ActionStatus::kSucceeded; + return tick; + } + + void cancel() override + { + } + +private: + std::vector types_; +}; + +robot_protocol_msgs::Action makeAction(const std::string& type) +{ + robot_protocol_msgs::Action action; + action.actionType = type; + action.actionId = type + "-1"; + return action; +} + +// ================================================================================================ +// Đường nạp thật +// ================================================================================================ + +TEST(ActionRegistry, LoadsDeclaredHandlersAndRoutesByActionType) +{ + robot::NodeHandle nh; + ActionRegistry registry; + + ASSERT_TRUE(registry.loadFromConfig(nh, "actions")); + EXPECT_EQ(registry.size(), 2u); + + // Định tuyến theo TÊN, không theo thứ tự khai — một handler nhận nhiều actionType. + ASSERT_NE(registry.find("wait"), nullptr); + ASSERT_NE(registry.find("pick"), nullptr); + ASSERT_NE(registry.find("charge"), nullptr); + EXPECT_EQ(registry.find("wait"), registry.find("pick")); + EXPECT_NE(registry.find("wait"), registry.find("charge")); + + EXPECT_EQ(registry.find("khong-ton-tai"), nullptr); +} + +TEST(ActionRegistry, LoadedHandlerActuallyRuns) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ASSERT_TRUE(registry.loadFromConfig(nh, "actions")); + + ActionHandler* handler = registry.find("wait"); + ASSERT_NE(handler, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(handler->start(makeAction("wait"), now)); + + // `quick` có duration 0 -> xong ngay ở tick đầu. + const ActionTick tick = handler->update(now); + EXPECT_EQ(tick.status, ActionStatus::kSucceeded); + EXPECT_FALSE(tick.message.empty()); +} + +TEST(ActionRegistry, SlowHandlerStaysRunningUntilItsDuration) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ASSERT_TRUE(registry.loadFromConfig(nh, "actions")); + + ActionHandler* handler = registry.find("charge"); + ASSERT_NE(handler, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(handler->start(makeAction("charge"), now)); + + EXPECT_EQ(handler->update(now).status, ActionStatus::kRunning); + EXPECT_EQ(handler->update(now + robot::Duration(0.5)).status, ActionStatus::kRunning); + EXPECT_EQ(handler->update(now + robot::Duration(1.0)).status, ActionStatus::kSucceeded); +} + +TEST(ActionRegistry, HandlerTimeoutIsTheHandlersOwnResponsibility) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ASSERT_TRUE(registry.loadFromConfig(nh, "actions")); + + ActionHandler* handler = registry.find("charge"); + ASSERT_NE(handler, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(handler->start(makeAction("charge"), now)); + + // Tầng 1 của contract 3 tầng: handler tự cắt, không chờ action_patience của state machine. + EXPECT_EQ(handler->update(now + robot::Duration(10.0)).status, ActionStatus::kFailed); +} + +// ================================================================================================ +// Đường lỗi — mỗi ca phải fail được, không được im lặng +// ================================================================================================ + +TEST(ActionRegistry, MissingHandlerListIsNotAnError) +{ + // Hệ không có thiết bị nào thì mọi mission đều nav-only. Caller mới là chỗ từ chối yêu cầu mang + // action, và nó từ chối kèm lý do rõ ràng. + robot::NodeHandle nh; + ActionRegistry registry; + + EXPECT_TRUE(registry.loadFromConfig(nh, "actions_empty")); + EXPECT_EQ(registry.size(), 0u); + EXPECT_EQ(registry.find("wait"), nullptr); +} + +TEST(ActionRegistry, RejectsSecondHandlerClaimingTheSameActionType) +{ + robot::NodeHandle nh; + ActionRegistry registry; + + // Định tuyến khi đó phụ thuộc thứ tự dòng trong YAML — không ai đọc config mà đoán ra được. + EXPECT_FALSE(registry.loadFromConfig(nh, "actions_duplicate_type")); + + // Handler đầu vẫn dùng được: một entry hỏng không xoá các entry còn lại. + EXPECT_EQ(registry.size(), 1u); + EXPECT_NE(registry.find("pick"), nullptr); +} + +TEST(ActionRegistry, RejectsHandlerThatCouldNeverFinish) +{ + robot::NodeHandle nh; + ActionRegistry registry; + + // hang=true + timeout=0 nghĩa là action chạy vĩnh viễn — đúng thứ contract cấm, và handler tự + // từ chối ở configure(). + EXPECT_FALSE(registry.loadFromConfig(nh, "actions_hang_forever")); + EXPECT_EQ(registry.size(), 0u); +} + +TEST(ActionRegistry, ReportsMissingLibraryPath) +{ + robot::NodeHandle nh; + ActionRegistry registry; + + // Thiếu `library_path` là nguyên nhân phổ biến nhất của "plugin build xong nhưng runtime báo + // không tìm thấy". + EXPECT_FALSE(registry.loadFromConfig(nh, "actions_missing_library")); + EXPECT_EQ(registry.size(), 0u); +} + +// ================================================================================================ +// Contract của registerHandler +// ================================================================================================ + +TEST(ActionRegistry, RejectsNullHandler) +{ + ActionRegistry registry; + EXPECT_FALSE(registry.registerHandler(nullptr)); +} + +TEST(ActionRegistry, RejectsHandlerWithNoActionType) +{ + ActionRegistry registry; + EXPECT_FALSE(registry.registerHandler(std::make_shared(std::vector{}))); +} + +TEST(ActionRegistry, RejectsEmptyActionTypeString) +{ + ActionRegistry registry; + EXPECT_FALSE(registry.registerHandler( + std::make_shared(std::vector{ "pick", "" }))); + + // Từ chối phải là NGUYÊN TỬ: 'pick' đứng trước chuỗi rỗng không được lọt vào bảng. + EXPECT_EQ(registry.size(), 0u); + EXPECT_EQ(registry.find("pick"), nullptr); +} + +TEST(ActionRegistry, ActionTypesListsEveryClaimedType) +{ + ActionRegistry registry; + ASSERT_TRUE(registry.registerHandler( + std::make_shared(std::vector{ "pick", "drop" }))); + ASSERT_TRUE( + registry.registerHandler(std::make_shared(std::vector{ "wait" }))); + + const std::vector types = registry.actionTypes(); + ASSERT_EQ(types.size(), 3u); + EXPECT_EQ(registry.size(), 2u); // size() đếm HANDLER, không đếm actionType +} + +TEST(ActionRegistry, ClearDropsEverything) +{ + ActionRegistry registry; + ASSERT_TRUE( + registry.registerHandler(std::make_shared(std::vector{ "pick" }))); + + registry.clear(); + EXPECT_EQ(registry.size(), 0u); + EXPECT_EQ(registry.find("pick"), nullptr); +} + +} // namespace + +int main(int argc, char** argv) +{ + // Trỏ vào cây config và thư mục .so của gói. `overwrite = 0` để shell vẫn override được khi cần + // chạy tay với cây khác — cùng cách `test_costmap` làm. +#ifdef ACTION_CORE_TEST_CONFIG_DIR + setenv("PNKX_NAV_CORE_CONFIG_DIR", ACTION_CORE_TEST_CONFIG_DIR, 0); +#endif +#ifdef ACTION_CORE_TEST_LIBRARY_DIR + setenv("PNKX_NAV_CORE_LIBRARY_PATH", ACTION_CORE_TEST_LIBRARY_DIR, 0); +#endif + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/config/action_handlers_params.yaml b/test/config/action_handlers_params.yaml new file mode 100644 index 0000000..83a34bc --- /dev/null +++ b/test/config/action_handlers_params.yaml @@ -0,0 +1,128 @@ +# Config CHỈ dùng cho test của gói. Bản runtime nằm trong cây config của nav core (C2) — sửa tham +# số vận hành thì sửa ở đó, đừng sửa bản này. +# +# Chạy test kèm: PNKX_NAV_CORE_CONFIG_DIR=src/AMR_T800/Test/action_core/test/config +# (binary test tự setenv qua ACTION_CORE_TEST_CONFIG_DIR nên chạy được thẳng qua ctest.) + +actions: + handlers: + - {name: quick, type: NoopActionHandler} + - {name: slow, type: NoopActionHandler} + + quick: + action_types: [wait, pick] + duration: 0.0 # [s] xong ngay ở tick đầu + timeout: 30.0 # [s] timeout tầng 1, của chính handler + + slow: + action_types: [charge] + duration: 1.0 # [s] + timeout: 10.0 # [s] + +# Hai handler cùng nhận một actionType: registry phải TỪ CHỐI cái thứ hai thay vì ghi đè im lặng. +actions_duplicate_type: + handlers: + - {name: first, type: NoopActionHandler} + - {name: second, type: NoopActionHandler} + + first: + action_types: [pick] + second: + action_types: [pick] + +# Handler treo vĩnh viễn mà lại tắt timeout — configure() phải từ chối. +actions_hang_forever: + handlers: + - {name: ghost, type: NoopActionHandler} + + ghost: + action_types: [wait] + hang: true + timeout: 0.0 + +# Type không khai library_path ở đâu cả. +actions_missing_library: + handlers: + - {name: nowhere, type: MissingActionHandler} + +# Không có khoá `handlers`: hợp lệ, chỉ nghĩa là hệ không có thiết bị nào. +actions_empty: + something_else: 1 + +# Bộ handler default, mỗi cái một namespace riêng để test nạp độc lập. +actions_wait: + handlers: + - {name: waiter, type: WaitActionHandler} + + waiter: + action_types: [wait] + default_duration: 0.0 # [s] khi order không kèm tham số `duration` + max_duration: 5.0 # [s] trần cứng; vượt trần thì action THẤT BẠI, không bị cắt ngắn + +actions_log: + handlers: + - {name: reporter, type: LogReportActionHandler} + + reporter: + action_types: [logReport] + +# Handler dò — lấy mẫu frame thô, lọc, ghi ra frame ổn định. +actions_detect: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + + detect: + action_types: [DetectCharger] + output_frame: dock_target + settle_delay: 0.2 # [s] + sample_window: 1.0 # [s] + min_samples: 10 + max_spread_xy: 0.03 # [m] + max_spread_yaw: 0.05 # [rad] + timeout: 5.0 # [s] + +# output_frame trùng input_frame -> configure() phải từ chối. +actions_detect_same_frame: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + detect: + action_types: [DetectCharger] + input_frame: charger_raw + output_frame: charger_raw + +# timeout ngắn hơn settle_delay + sample_window -> action LUÔN hỏng, phải chặn lúc boot. +actions_detect_bad_timeout: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + settle_delay: 1.0 + sample_window: 2.0 + timeout: 1.0 + +# Bypass perception có chủ đích cho test sim: pose giả là offset trong base_link nhưng output vẫn +# phải là frame tĩnh trong map, nếu không đích sẽ chạy theo robot và docking không thể hoàn tất. +actions_detect_simulated: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + detect: + action_types: [DetectPallet] + output_frame: dock_target + use_simulated_goal: true + simulated_parent_frame: base_link + simulated_offset_x: -1.5 + simulated_offset_y: 0.2 + simulated_offset_yaw: 0.0 + +NoopActionHandler: + library_path: libaction_core_noop_action_handler + +FrameSamplerActionHandler: + library_path: libaction_core_frame_sampler_action_handler + +WaitActionHandler: + library_path: libaction_core_wait_action_handler + +LogReportActionHandler: + library_path: libaction_core_log_report_action_handler diff --git a/test/frame_sampler_test.cpp b/test/frame_sampler_test.cpp new file mode 100644 index 0000000..34ad002 --- /dev/null +++ b/test/frame_sampler_test.cpp @@ -0,0 +1,352 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm handler dò: lấy mẫu TF nhiễu, lọc, ghi ra frame ổn định. + * + * Trọng tâm là ba thứ mà một bản lọc viết vội sẽ sai: gộp góc quanh ±π, chống outlier, và cổng chất + * lượng khi dữ liệu tản. Cả ba đều dẫn tới robot lùi vào sai chỗ mà không có lỗi nào được báo. + * + * Author: DuongTD + *********************************************************************/ +#include + +#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* kRawFrame = "charger_raw"; +constexpr const char* kOutFrame = "dock_target"; + +/// tf3::Time chỉ có ctor (sec, nsec) — không có ctor từ double như robot::Time. +tf3::Time toTf3Time(double t) +{ + const uint32_t sec = static_cast(t); + return tf3::Time(sec, static_cast((t - sec) * 1e9)); +} + +robot_protocol_msgs::Action makeAction(const std::string& frame = kRawFrame, + const std::string& action_type = "DetectCharger") +{ + robot_protocol_msgs::Action action; + action.actionType = action_type; + action.actionId = "detect-1"; + + if (!frame.empty()) + { + robot_protocol_msgs::ActionParameter p; + p.key = "goal_frame"; + p.value = frame; + action.actionParameters.push_back(p); + } + return action; +} + +/// @brief Rig: một buffer TF thật + handler nạp qua đúng đường Boost.DLL. +class Rig +{ +public: + explicit Rig(const std::string& ns = "actions_detect", + const std::string& action_type = "DetectCharger") + { + ctx.tf = &tf; + ctx.global_frame = kGlobalFrame; + registry.setContext(ctx); + loaded = registry.loadFromConfig(nh, ns); + handler = registry.find(action_type); + } + + /// @brief Bơm một mẫu thô vào buffer. `stamp` phải TĂNG, nếu không mẫu bị bỏ (đúng contract). + void pushSample(double x, double y, double yaw, double stamp_s) + { + tf3::TransformStampedMsg t; + t.header.stamp = toTf3Time(stamp_s); + t.header.frame_id = kGlobalFrame; + t.child_frame_id = kRawFrame; + t.transform.translation.x = x; + t.transform.translation.y = y; + t.transform.rotation.z = std::sin(yaw * 0.5); + t.transform.rotation.w = std::cos(yaw * 0.5); + tf.setTransform(t, "test", /*is_static=*/false); + } + + void pushTransform(const std::string& parent, const std::string& child, double x, double y, + double yaw, double stamp_s) + { + tf3::TransformStampedMsg t; + t.header.stamp = toTf3Time(stamp_s); + t.header.frame_id = parent; + t.child_frame_id = child; + t.transform.translation.x = x; + t.transform.translation.y = y; + t.transform.rotation.z = std::sin(yaw * 0.5); + t.transform.rotation.w = std::cos(yaw * 0.5); + tf.setTransform(t, "test", /*is_static=*/false); + } + + bool readOutput(double& x, double& y, double& yaw) + { + try + { + const auto t = tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time()); + x = t.transform.translation.x; + y = t.transform.translation.y; + const auto& q = t.transform.rotation; + yaw = std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)); + return true; + } + catch (const std::exception&) + { + return false; + } + } + + robot::NodeHandle nh; + tf3::BufferCore tf; + ActionContext ctx; + ActionRegistry registry; + ActionHandler* handler = nullptr; + bool loaded = false; +}; + +/// @brief Chạy handler qua trọn một lượt: bơm @p n mẫu quanh (x,y,yaw) với nhiễu @p noise. +ActionStatus runSampling(Rig& rig, int n, double x, double y, double yaw, double noise_xy, + double noise_yaw = 0.0) +{ + const robot::Time t0 = robot::Time(100.0); + EXPECT_TRUE(rig.handler->start(makeAction(), t0)); + + // settle_delay = 0.2, sample_window = 1.0 trong config test. + double stamp = 100.0; + ActionStatus last = ActionStatus::kRunning; + + for (int i = 0; i < n; ++i) + { + stamp += 0.01; + // Nhiễu răng cưa: đổi dấu mỗi mẫu — biên độ đúng bằng `noise`, không phụ thuộc bộ sinh ngẫu nhiên. + const double s = (i % 2 == 0) ? 1.0 : -1.0; + rig.pushSample(x + s * noise_xy, y - s * noise_xy, yaw + s * noise_yaw, stamp); + last = rig.handler->update(robot::Time(100.3 + i * 0.01)).status; + if (last != ActionStatus::kRunning) + { + return last; + } + } + + // Quá cửa sổ lấy mẫu -> handler chốt kết quả. + return rig.handler->update(robot::Time(101.5)).status; +} + +// ================================================================================================ +// Đường thành công +// ================================================================================================ + +TEST(FrameSampler, LoadsAndPublishesAStableFrame) +{ + Rig rig; + ASSERT_TRUE(rig.loaded); + ASSERT_NE(rig.handler, nullptr); + + EXPECT_EQ(runSampling(rig, 30, 2.0, 1.0, 0.5, 0.002), ActionStatus::kSucceeded); + + double x = 0.0, y = 0.0, yaw = 0.0; + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(x, 2.0, 0.005); + EXPECT_NEAR(y, 1.0, 0.005); + EXPECT_NEAR(yaw, 0.5, 0.01); +} + +TEST(FrameSampler, MedianRejectsAnOutlier) +{ + Rig rig; + ASSERT_NE(rig.handler, nullptr); + + const robot::Time t0 = robot::Time(100.0); + ASSERT_TRUE(rig.handler->start(makeAction(), t0)); + + double stamp = 100.0; + for (int i = 0; i < 30; ++i) + { + stamp += 0.01; + // Một mẫu nhận nhầm chân kệ khác, lệch 1 m. Trung bình sẽ bị kéo ~3 cm; trung vị thì không. + const double x = (i == 7) ? 3.0 : 2.0; + rig.pushSample(x, 1.0, 0.0, stamp); + rig.handler->update(robot::Time(100.3 + i * 0.01)); + } + ASSERT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kSucceeded); + + double x = 0.0, y = 0.0, yaw = 0.0; + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(x, 2.0, 0.001) << "trung vị phải loại được outlier"; +} + +TEST(FrameSampler, AveragesYawAcrossTheWrapAround) +{ + Rig rig; + ASSERT_NE(rig.handler, nullptr); + + const robot::Time t0 = robot::Time(100.0); + ASSERT_TRUE(rig.handler->start(makeAction(), t0)); + + // Mẫu nằm hai bên đường cắt ±π. Trung bình SỐ HỌC cho ra ~0 — lệch 180°, robot vào trạm ngược đầu. + double stamp = 100.0; + for (int i = 0; i < 30; ++i) + { + stamp += 0.01; + const double yaw = (i % 2 == 0) ? (M_PI - 0.01) : (-M_PI + 0.01); + rig.pushSample(2.0, 1.0, yaw, stamp); + rig.handler->update(robot::Time(100.3 + i * 0.01)); + } + ASSERT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kSucceeded); + + double x = 0.0, y = 0.0, yaw = 0.0; + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(std::fabs(yaw), M_PI, 0.02) << "gộp góc phải dùng vector đơn vị, không phải trung bình"; +} + +TEST(FrameSampler, SimulatedGoalIsFrozenInTheGlobalFrame) +{ + Rig rig("actions_detect_simulated", "DetectPallet"); + ASSERT_TRUE(rig.loaded); + ASSERT_NE(rig.handler, nullptr); + + rig.pushTransform(kGlobalFrame, "base_link", 10.0, 5.0, M_PI_2, 100.0); + EXPECT_TRUE(rig.handler->start(makeAction("", "DetectPallet"), robot::Time(100.0))); + EXPECT_EQ(rig.handler->update(robot::Time(100.0)).status, ActionStatus::kSucceeded); + + double x = 0.0, y = 0.0, yaw = 0.0; + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(x, 9.8, 1e-6); + EXPECT_NEAR(y, 3.5, 1e-6); + EXPECT_NEAR(yaw, M_PI_2, 1e-6); + + // Output là static trong map, không được chạy theo parent ở cycle sau. + rig.pushTransform(kGlobalFrame, "base_link", 20.0, 5.0, M_PI_2, 101.0); + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(x, 9.8, 1e-6); + EXPECT_NEAR(y, 3.5, 1e-6); +} + +// ================================================================================================ +// Đường lỗi — mỗi ca phải fail được +// ================================================================================================ + +TEST(FrameSampler, FailsWhenDetectionIsTooScattered) +{ + Rig rig; + ASSERT_NE(rig.handler, nullptr); + + // max_spread_xy = 0.03 trong config test; nhiễu ±0.05 cho độ tản 0.1 m. + EXPECT_EQ(runSampling(rig, 30, 2.0, 1.0, 0.0, 0.05), ActionStatus::kFailed); + + double x = 0.0, y = 0.0, yaw = 0.0; + EXPECT_FALSE(rig.readOutput(x, y, yaw)) << "dữ liệu tản thì KHÔNG được ghi frame nào"; +} + +TEST(FrameSampler, FailsWithTooFewSamples) +{ + Rig rig; + ASSERT_NE(rig.handler, nullptr); + + const robot::Time t0 = robot::Time(100.0); + ASSERT_TRUE(rig.handler->start(makeAction(), t0)); + + rig.pushSample(2.0, 1.0, 0.0, 100.5); + rig.handler->update(robot::Time(100.5)); + + // min_samples = 10 trong config test. + EXPECT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kFailed); +} + +TEST(FrameSampler, DuplicateTimestampsDoNotCountAsSamples) +{ + Rig rig; + ASSERT_NE(rig.handler, nullptr); + + const robot::Time t0 = robot::Time(100.0); + ASSERT_TRUE(rig.handler->start(makeAction(), t0)); + + // TF cập nhật chậm hơn control loop: cùng một pose bị đọc 30 lần. Không lọc theo timestamp thì + // min_samples mất hết ý nghĩa và một mẫu duy nhất trông như ba mươi mẫu. + rig.pushSample(2.0, 1.0, 0.0, 100.5); + for (int i = 0; i < 30; ++i) + { + rig.handler->update(robot::Time(100.3 + i * 0.01)); + } + + EXPECT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kFailed); +} + +TEST(FrameSampler, FailsWhenTheRawFrameNeverAppears) +{ + Rig rig; + ASSERT_NE(rig.handler, nullptr); + + const robot::Time t0 = robot::Time(100.0); + ASSERT_TRUE(rig.handler->start(makeAction(), t0)); + + EXPECT_EQ(rig.handler->update(robot::Time(100.5)).status, ActionStatus::kRunning); + // timeout = 5.0 trong config test. + EXPECT_EQ(rig.handler->update(robot::Time(105.1)).status, ActionStatus::kFailed); +} + +TEST(FrameSampler, RefusesToStartWithoutAFrameParameter) +{ + Rig rig; + ASSERT_NE(rig.handler, nullptr); + + // Không có `goal_frame` và config cũng không khai `input_frame` -> không biết dò cái gì. + EXPECT_FALSE(rig.handler->start(makeAction(""), robot::Time(100.0))); +} + +TEST(FrameSampler, RefusesToLoadWithoutATfBuffer) +{ + // Handler cần TF; thiếu thì phải từ chối lúc NẠP, không phải lúc order đầu tiên tới. + robot::NodeHandle nh; + ActionRegistry registry; // context mặc định: tf == nullptr + EXPECT_FALSE(registry.loadFromConfig(nh, "actions_detect")); + EXPECT_EQ(registry.size(), 0u); +} + +TEST(FrameSampler, RefusesOutputFrameEqualToInputFrame) +{ + Rig rig("actions_detect_same_frame"); + EXPECT_FALSE(rig.loaded) << "ghi đè chính frame thô là tranh chấp với bên publish nó"; + EXPECT_EQ(rig.registry.size(), 0u); +} + +TEST(FrameSampler, RefusesTimeoutShorterThanTheSamplingWindow) +{ + Rig rig("actions_detect_bad_timeout"); + EXPECT_FALSE(rig.loaded) << "action sẽ LUÔN hỏng — gần như chắc chắn gõ nhầm"; + EXPECT_EQ(rig.registry.size(), 0u); +} + +} // namespace + +int main(int argc, char** argv) +{ +#ifdef ACTION_CORE_TEST_CONFIG_DIR + setenv("PNKX_NAV_CORE_CONFIG_DIR", ACTION_CORE_TEST_CONFIG_DIR, 0); +#endif +#ifdef ACTION_CORE_TEST_LIBRARY_DIR + setenv("PNKX_NAV_CORE_LIBRARY_PATH", ACTION_CORE_TEST_LIBRARY_DIR, 0); +#endif + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/log_report_action_handler_test.cpp b/test/log_report_action_handler_test.cpp new file mode 100644 index 0000000..d5d5764 --- /dev/null +++ b/test/log_report_action_handler_test.cpp @@ -0,0 +1,100 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm handler `logReport` — hiện thực tối thiểu nhưng ĐẦY ĐỦ của contract. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include + +#include + +#include + +namespace +{ +using action_core::ActionHandler; +using action_core::ActionRegistry; +using action_core::ActionStatus; + +robot_protocol_msgs::Action makeReport() +{ + robot_protocol_msgs::Action action; + action.actionType = "logReport"; + action.actionId = "log-1"; + action.actionDescription = "checkpoint"; + + robot_protocol_msgs::ActionParameter parameter; + parameter.key = "reason"; + parameter.value = "shift-change"; + action.actionParameters.push_back(parameter); + + return action; +} + +TEST(LogReportActionHandler, FinishesOnTheFirstTick) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ASSERT_TRUE(registry.loadFromConfig(nh, "actions_log")); + + ActionHandler* handler = registry.find("logReport"); + ASSERT_NE(handler, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(handler->start(makeReport(), now)); + + // Việc đã xong trong start(), nhưng kết quả VẪN phải đi qua update(): caller không suy kết quả từ + // giá trị trả về của start(). + const auto tick = handler->update(now); + EXPECT_EQ(tick.status, ActionStatus::kSucceeded); + EXPECT_NE(tick.message.find("log-1"), std::string::npos) << tick.message; +} + +TEST(LogReportActionHandler, HandlesAnActionWithNoParameters) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ASSERT_TRUE(registry.loadFromConfig(nh, "actions_log")); + + ActionHandler* handler = registry.find("logReport"); + ASSERT_NE(handler, nullptr); + + robot_protocol_msgs::Action bare; + bare.actionType = "logReport"; + bare.actionId = "log-2"; + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(handler->start(bare, now)); + EXPECT_EQ(handler->update(now).status, ActionStatus::kSucceeded); +} + +TEST(LogReportActionHandler, CancelIsSafe) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ASSERT_TRUE(registry.loadFromConfig(nh, "actions_log")); + + ActionHandler* handler = registry.find("logReport"); + ASSERT_NE(handler, nullptr); + EXPECT_NO_THROW(handler->cancel()); +} + +} // namespace + +int main(int argc, char** argv) +{ +#ifdef ACTION_CORE_TEST_CONFIG_DIR + setenv("PNKX_NAV_CORE_CONFIG_DIR", ACTION_CORE_TEST_CONFIG_DIR, 0); +#endif +#ifdef ACTION_CORE_TEST_LIBRARY_DIR + setenv("PNKX_NAV_CORE_LIBRARY_PATH", ACTION_CORE_TEST_LIBRARY_DIR, 0); +#endif + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/noop_action_handler_test.cpp b/test/noop_action_handler_test.cpp new file mode 100644 index 0000000..da02d59 --- /dev/null +++ b/test/noop_action_handler_test.cpp @@ -0,0 +1,116 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm hành vi của handler mặc định qua đúng đường nạp plugin. + * + * `NoopActionHandler` là ví dụ tham chiếu cho contract, nên hành vi của nó phải được khoá lại — + * đặc biệt là các guard cấu hình, vì chúng là thứ ngăn một file YAML gõ nhầm biến thành action + * chạy vĩnh viễn trên robot. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include + +#include + +#include + +namespace +{ +using action_core::ActionHandler; +using action_core::ActionRegistry; +using action_core::ActionStatus; + +robot_protocol_msgs::Action makeAction(const std::string& type) +{ + robot_protocol_msgs::Action action; + action.actionType = type; + action.actionId = type + "-id"; + return action; +} + +ActionHandler* load(ActionRegistry& registry, robot::NodeHandle& nh, const std::string& type) +{ + if (!registry.loadFromConfig(nh, "actions")) + { + return nullptr; + } + return registry.find(type); +} + +TEST(NoopActionHandler, ZeroDurationFinishesOnTheFirstTick) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ActionHandler* handler = load(registry, nh, "wait"); + ASSERT_NE(handler, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(handler->start(makeAction("wait"), now)); + EXPECT_EQ(handler->update(now).status, ActionStatus::kSucceeded); +} + +TEST(NoopActionHandler, MessageNamesTheActionId) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ActionHandler* handler = load(registry, nh, "wait"); + ASSERT_NE(handler, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(handler->start(makeAction("wait"), now)); + + // Message chỉ để log, nhưng phải chỉ đúng action nào — log không truy được về action nào thì vô + // dụng khi một chặng có nhiều action. + const std::string message = handler->update(now).message; + EXPECT_NE(message.find("wait-id"), std::string::npos) << message; +} + +TEST(NoopActionHandler, CancelDoesNotThrowAndCanBeCalledWithoutStart) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ActionHandler* handler = load(registry, nh, "wait"); + ASSERT_NE(handler, nullptr); + + // Caller huỷ một action chưa kịp start là chuyện bình thường (cancel tới trong cùng cycle). + EXPECT_NO_THROW(handler->cancel()); +} + +TEST(NoopActionHandler, RestartResetsTheClock) +{ + robot::NodeHandle nh; + ActionRegistry registry; + ActionHandler* handler = load(registry, nh, "charge"); + ASSERT_NE(handler, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(handler->start(makeAction("charge"), now)); + EXPECT_EQ(handler->update(now + robot::Duration(10.0)).status, ActionStatus::kFailed); + + // Handler được dùng lại cho action sau: mốc thời gian phải được gieo lại, nếu không action thứ + // hai hỏng ngay lập tức vì thừa hưởng đồng hồ của action trước. + const robot::Time later = now + robot::Duration(20.0); + ASSERT_TRUE(handler->start(makeAction("charge"), later)); + EXPECT_EQ(handler->update(later).status, ActionStatus::kRunning); + EXPECT_EQ(handler->update(later + robot::Duration(1.0)).status, ActionStatus::kSucceeded); +} + +} // namespace + +int main(int argc, char** argv) +{ +#ifdef ACTION_CORE_TEST_CONFIG_DIR + setenv("PNKX_NAV_CORE_CONFIG_DIR", ACTION_CORE_TEST_CONFIG_DIR, 0); +#endif +#ifdef ACTION_CORE_TEST_LIBRARY_DIR + setenv("PNKX_NAV_CORE_LIBRARY_PATH", ACTION_CORE_TEST_LIBRARY_DIR, 0); +#endif + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/wait_action_handler_test.cpp b/test/wait_action_handler_test.cpp new file mode 100644 index 0000000..a31a1a0 --- /dev/null +++ b/test/wait_action_handler_test.cpp @@ -0,0 +1,136 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm handler `wait` — handler default duy nhất lấy tham số từ CHÍNH action, không từ YAML. + * + * Trọng tâm là các đường từ chối: một `duration` hỏng phải làm action thất bại có lý do, chứ không + * được biến thành một khoảng chờ đoán bừa mà không ai giải thích được vì sao robot đứng im. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include + +#include + +#include + +namespace +{ +using action_core::ActionHandler; +using action_core::ActionRegistry; +using action_core::ActionStatus; + +robot_protocol_msgs::Action makeWait(const std::string& duration_value) +{ + robot_protocol_msgs::Action action; + action.actionType = "wait"; + action.actionId = "wait-1"; + + if (!duration_value.empty()) + { + robot_protocol_msgs::ActionParameter parameter; + parameter.key = "duration"; + parameter.value = duration_value; + action.actionParameters.push_back(parameter); + } + return action; +} + +class WaitRig +{ +public: + WaitRig() + { + loaded_ = registry_.loadFromConfig(nh_, "actions_wait"); + handler_ = registry_.find("wait"); + } + + bool loaded_ = false; + robot::NodeHandle nh_; + ActionRegistry registry_; + ActionHandler* handler_ = nullptr; +}; + +TEST(WaitActionHandler, TakesDurationFromTheActionItself) +{ + WaitRig rig; + ASSERT_TRUE(rig.loaded_); + ASSERT_NE(rig.handler_, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(rig.handler_->start(makeWait("2.0"), now)); + + EXPECT_EQ(rig.handler_->update(now).status, ActionStatus::kRunning); + EXPECT_EQ(rig.handler_->update(now + robot::Duration(1.9)).status, ActionStatus::kRunning); + EXPECT_EQ(rig.handler_->update(now + robot::Duration(2.0)).status, ActionStatus::kSucceeded); +} + +TEST(WaitActionHandler, FallsBackToDefaultWhenTheActionCarriesNoDuration) +{ + WaitRig rig; + ASSERT_NE(rig.handler_, nullptr); + + // default_duration = 0 trong config test -> xong ngay ở tick đầu. + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(rig.handler_->start(makeWait(""), now)); + EXPECT_EQ(rig.handler_->update(now).status, ActionStatus::kSucceeded); +} + +TEST(WaitActionHandler, RefusesNonNumericDuration) +{ + WaitRig rig; + ASSERT_NE(rig.handler_, nullptr); + + // Từ chối tại start(): caller coi như action hỏng và fleet nhận được lý do. + EXPECT_FALSE(rig.handler_->start(makeWait("mot-luc-nua"), robot::Time::now())); +} + +TEST(WaitActionHandler, RefusesNegativeDuration) +{ + WaitRig rig; + ASSERT_NE(rig.handler_, nullptr); + EXPECT_FALSE(rig.handler_->start(makeWait("-1.0"), robot::Time::now())); +} + +TEST(WaitActionHandler, RefusesDurationAboveTheConfiguredCeiling) +{ + WaitRig rig; + ASSERT_NE(rig.handler_, nullptr); + + // max_duration = 5 s trong config test. Vượt trần phải là THẤT BẠI, không phải bị cắt xuống 5 s: + // im lặng rút ngắn là giấu đi một lỗi cấu hình của fleet. + EXPECT_FALSE(rig.handler_->start(makeWait("120.0"), robot::Time::now())); +} + +TEST(WaitActionHandler, RestartResetsTheClock) +{ + WaitRig rig; + ASSERT_NE(rig.handler_, nullptr); + + const robot::Time now = robot::Time::now(); + ASSERT_TRUE(rig.handler_->start(makeWait("1.0"), now)); + EXPECT_EQ(rig.handler_->update(now + robot::Duration(1.0)).status, ActionStatus::kSucceeded); + + const robot::Time later = now + robot::Duration(10.0); + ASSERT_TRUE(rig.handler_->start(makeWait("1.0"), later)); + EXPECT_EQ(rig.handler_->update(later).status, ActionStatus::kRunning); +} + +} // namespace + +int main(int argc, char** argv) +{ +#ifdef ACTION_CORE_TEST_CONFIG_DIR + setenv("PNKX_NAV_CORE_CONFIG_DIR", ACTION_CORE_TEST_CONFIG_DIR, 0); +#endif +#ifdef ACTION_CORE_TEST_LIBRARY_DIR + setenv("PNKX_NAV_CORE_LIBRARY_PATH", ACTION_CORE_TEST_LIBRARY_DIR, 0); +#endif + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}