Compare commits

...

4 Commits

Author SHA1 Message Date
a046ceff73 build: add BUILD_MISSION_ADAPTERS_TESTS option, off by default
Tests used to build whenever CATKIN_ENABLE_TESTING was on. They now also
need -DBUILD_MISSION_ADAPTERS_TESTS=ON, in both build modes.
2026-11-17 20:36:11 +07:00
ab0bed7248 feat(rotate): đọc angle_deg từ actionParameters, quy sang relative_yaw
- Mission: thêm relative_yaw [rad], NaN = không dùng, đi kèm được với
  relative_distance (khác cặp goal_frame/relative_distance vốn loại
  trừ nhau) — chặng quay tại chỗ là distance 0 + góc khác 0.

- Step: thêm turn_param (cùng vai trò move_to_param — bảng compound chỉ
  giữ cấu trúc, số đo tới từ actionParameters của order). Validate lúc
  boot: turn_param gắn vào profile khác rotate thì configure() từ chối.

- expandCompound(): parseTurnDegrees() đọc actionParameters theo
  turn_param, parse ĐỘ bằng std::stod (bắt hết ký tự đuôi rác kiểu
  "90abc"), validate biên [-180,180] — vượt biên thì TỪ CHỐI thay vì
  normalize âm thầm, vì goal là một pose chỉ diễn tả được hướng cuối,
  không diễn tả được chiều/số vòng quay. Quy sang rad, log cả hai đơn
  vị. Thiếu khoá/parse hỏng/ngoài biên đều bỏ CẢ message, đúng pattern
  move_to_param đã có.

- 7 test mới: chuyển đổi độ->rad, giữ dấu, thiếu tham số, tham số không
  phải số, vượt biên (cả hai đầu + đúng biên), compound khác không đụng
  relative_yaw, turn_param sai profile trượt lúc boot.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 10:46:31 +07:00
ec11dc42ed optimal 2026-08-10 22:26:10 +07:00
4a6b541773 fix file cmake 2026-08-10 11:37:07 +07:00
11 changed files with 959 additions and 15 deletions

View File

@@ -45,10 +45,18 @@ if(NOT BUILDING_WITH_CATKIN)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
# Test/<pkg> -> src/AMR_T800/pnkx_nav_core/src # Gói này build được ở hai vị trí:
# Test/<pkg> (dev, sibling của pnkx_nav_core) -> ../../pnkx_nav_core/src
# src/Libraries/<pkg> (in-tree trong pnkx_nav_core) -> ../.. chính là src
# Có thể ép qua -DPNKX_NAV_CORE_SRC_DIR khi layout khác chuẩn.
if(NOT DEFINED PNKX_NAV_CORE_SRC_DIR)
set(PNKX_NAV_CORE_SRC_DIR set(PNKX_NAV_CORE_SRC_DIR
"${CMAKE_CURRENT_SOURCE_DIR}/../../pnkx_nav_core/src" "${CMAKE_CURRENT_SOURCE_DIR}/../../pnkx_nav_core/src"
) )
if(NOT IS_DIRECTORY "${PNKX_NAV_CORE_SRC_DIR}")
set(PNKX_NAV_CORE_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../..")
endif()
endif()
# Test/<pkg> -> T800_ws/devel/lib # Test/<pkg> -> T800_ws/devel/lib
set(WORKSPACE_DEVEL_LIB_DIR set(WORKSPACE_DEVEL_LIB_DIR
@@ -64,6 +72,14 @@ if(NOT BUILDING_WITH_CATKIN)
${PNKX_NAV_CORE_SRC_DIR}/*/*/*/*/include ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/*/include
) )
# Glob rỗng nghĩa là PNKX_NAV_CORE_SRC_DIR trỏ trượt — fail ngay tại configure thay vì để
# compiler báo "No such file or directory" khó lần.
if(NOT STANDALONE_PACKAGE_INCLUDE_DIRS)
message(FATAL_ERROR
"mission_adapters: no package include dirs found under "
"'${PNKX_NAV_CORE_SRC_DIR}'. Set -DPNKX_NAV_CORE_SRC_DIR=<pnkx_nav_core>/src.")
endif()
set(STANDALONE_INCLUDE_DIRS set(STANDALONE_INCLUDE_DIRS
${STANDALONE_PACKAGE_INCLUDE_DIRS} ${STANDALONE_PACKAGE_INCLUDE_DIRS}
@@ -344,7 +360,10 @@ endif()
# EXCLUDE_FROM_ALL để binary có mặt sau `catkin_make` thường — chạy thẳng # EXCLUDE_FROM_ALL để binary có mặt sau `catkin_make` thường — chạy thẳng
# ./devel/lib/mission_adapters/<test> theo đúng quy trình verify của repo. # ./devel/lib/mission_adapters/<test> theo đúng quy trình verify của repo.
# ======================================================== # ========================================================
if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN) # Test mặc định OFF trong cả hai chế độ build; bật bằng -DBUILD_MISSION_ADAPTERS_TESTS=ON.
option(BUILD_MISSION_ADAPTERS_TESTS "Build the mission_adapters unit tests" OFF)
if(BUILD_MISSION_ADAPTERS_TESTS AND CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN)
if(NOT COMMAND catkin_add_gtest) if(NOT COMMAND catkin_add_gtest)
message(FATAL_ERROR "catkin_add_gtest NOT FOUND") message(FATAL_ERROR "catkin_add_gtest NOT FOUND")

View File

@@ -1,7 +1,7 @@
# mission_adapters # mission_adapters
Lớp mission độc lập ROS: nhận yêu cầu từ nguồn ngoài (goal đơn lẻ, VDA5050 Order), chuyển thành hàng Lớp mission độc lập ROS: nhận yêu cầu từ nguồn ngoài (goal đơn lẻ, VDA5050 Order, VDA5050
đợi mission, và giữ trạng thái của hàng đợi đó. instantActions), chuyển thành hàng đợi mission, và giữ trạng thái của hàng đợi đó.
Gói **không biết** navigation runtime nào đang chạy phía sau. Mission đi xuống qua cổng Gói **không biết** navigation runtime nào đang chạy phía sau. Mission đi xuống qua cổng
`NavigationClient`, kết quả quay về theo `MissionId`. Nhờ vậy cùng một lớp mission dùng lại được cho `NavigationClient`, kết quả quay về theo `MissionId`. Nhờ vậy cùng một lớp mission dùng lại được cho
@@ -10,11 +10,32 @@ runtime khác, và test được mà không cần robot.
Nguồn mission là plugin nạp bằng Boost.DLL theo khoá `library_path` trong YAML — xem Nguồn mission là plugin nạp bằng Boost.DLL theo khoá `library_path` trong YAML — xem
[docs/PLUGIN_GUIDE.md](docs/PLUGIN_GUIDE.md). [docs/PLUGIN_GUIDE.md](docs/PLUGIN_GUIDE.md).
## Ba nguồn có sẵn
| Instance | Schema | Plugin | Payload |
|---|---|---|---|
| `goal_src` | `geometry.pose_stamped` | `GoalSourceAdapter` | một `PoseStamped`, luôn profile `position` |
| `vda5050_src` | `vda5050.order` | `VDA5050SourceAdapter` | một Order, cắt chặng tại mỗi node có action |
| `instant_src` | `vda5050.instant_action` | `InstantActionSourceAdapter` | một message `instantActions` (0..n action) |
`InstantActionSourceAdapter` **kế thừa** `VDA5050SourceAdapter` và nằm cùng một `.so`
(`libmission_adapters_vda5050_source`, hai `BOOST_DLL_ALIAS`). Không phải quan hệ "là một" mà là
ràng buộc dữ liệu: bảng `compound_actions` phải có đúng **một** bản, nếu không `charge` gửi dạng
node action và `charge` gửi dạng instantAction sẽ nở ra hai chuỗi chặng khác nhau.
Vì `configure()` scope theo tên instance, `instant_src` đọc bảng của nguồn order qua param
`compound_actions_from` (mặc định `vda5050_src`). Khai bảng thứ hai dưới `instant_src` là quay lại
đúng vấn đề đó, chỉ khác là lệch trong YAML thay vì trong code.
**Message instantActions luôn `kReplace`.** `blockingType` không chọn cách vào hàng đợi: fleet gửi
message tiếp theo khi message trước còn chạy, và nghĩa của lệnh mới là thay lệnh cũ. Hệ quả phải
biết — một instantAction đến giữa lúc order đang chạy sẽ **huỷ order đó**.
## Luồng runtime ## Luồng runtime
```text ```text
host (MQTT / OPC-UA / REST / UI) host (MQTT / OPC-UA / REST / UI)
│ goalEvent / orderEvent / submitRequest(MissionRequest) │ goalEvent / orderEvent / instantActionsEvent / submitRequest(MissionRequest)
▼ ▼
┌──────────────────┐ tra schema ┌────────────────┐ ┌──────────────────┐ tra schema ┌────────────────┐
│ EventProcessor │ ──────────────► │ PluginRegistry │ (các .so nguồn mission) │ EventProcessor │ ──────────────► │ PluginRegistry │ (các .so nguồn mission)
@@ -127,6 +148,7 @@ Bản test: `test/config/mission_adapters_params.yaml`, chỉ được đọc kh
| Khoá | Đơn vị / mặc định | Ý nghĩa | | Khoá | Đơn vị / mặc định | Ý nghĩa |
|---|---|---| |---|---|---|
| `mission_adapters/mission_sources` | — | Danh sách nguồn mission `{name, type}` | | `mission_adapters/mission_sources` | — | Danh sách nguồn mission `{name, type}` |
| `<instant source>/compound_actions_from` | `vda5050_src` | Namespace của nguồn order để **dùng chung** bảng `compound_actions` |
| `mission_adapters/mission_timeout` | `[s]`, `0.0` | Trần thời gian cho một chặng; `0` = tắt. Quá hạn → chặng thất bại **và** navigation được bảo dừng | | `mission_adapters/mission_timeout` | `[s]`, `0.0` | Trần thời gian cho một chặng; `0` = tắt. Quá hạn → chặng thất bại **và** navigation được bảo dừng |
| `mission_adapters/clear_queue_on_failure` | `true` | Một chặng hỏng thì xoá sạch hàng đợi. Đặt `false` chỉ khi các mission độc lập với nhau | | `mission_adapters/clear_queue_on_failure` | `true` | Một chặng hỏng thì xoá sạch hàng đợi. Đặt `false` chỉ khi các mission độc lập với nhau |
| `<type>/library_path` | — | Tên `.so` của plugin — **thiếu khoá này là lỗi runtime phổ biến nhất** | | `<type>/library_path` | — | Tên `.so` của plugin — **thiếu khoá này là lỗi runtime phổ biến nhất** |
@@ -190,6 +212,10 @@ Chuyển đổi payload → mission chạy trên thread của `EventProcessor`,
## Chưa có ## Chưa có
- Mission persistence (mất điện giữa order thì hàng đợi mất). - Mission persistence (mất điện giữa order thì hàng đợi mất).
- VDA5050 instant actions. - Trạng thái theo TỪNG action gửi ngược lên fleet. Hiện consumer suy done/fail từ trạng thái
navigation, mà trạng thái đó là của **cả hàng đợi** — chỉ đúng khi message instantActions là việc
duy nhất trong hàng đợi.
- `blockingType: NONE` đúng nghĩa (chạy song song với di chuyển). Runtime không lái được trong lúc
chạy action nên nó bị thu hẹp thành "xếp hàng", có log.
- Mission priority queue — hàng đợi hiện là FIFO thuần. - Mission priority queue — hàng đợi hiện là FIFO thuần.
- Multi-robot fleet. - Multi-robot fleet.

View File

@@ -55,6 +55,14 @@ namespace mission_adapters
/// @brief Tiện ích cho nguồn VDA5050. /// @brief Tiện ích cho nguồn VDA5050.
void orderEvent(const robot_protocol_msgs::Order& order); void orderEvent(const robot_protocol_msgs::Order& order);
/**
* @brief Tiện ích cho nguồn instantAction: MỘT message, 0..n action.
*
* Cả message đi xuống như một lô. Tách ra gọi nhiều lần là mở lại đúng lỗ mà việc gộp sinh
* ra để bịt: action `HARD` sau preempt chặng của action trước trong cùng message.
*/
void instantActionsEvent(const std::vector<robot_protocol_msgs::Action>& actions);
void cancelEvent(); void cancelEvent();
void pauseEvent(); void pauseEvent();
void resumeEvent(); void resumeEvent();

View File

@@ -11,8 +11,10 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector>
#include <robot_geometry_msgs/PoseStamped.h> #include <robot_geometry_msgs/PoseStamped.h>
#include <robot_protocol_msgs/Action.h>
#include <robot_protocol_msgs/Order.h> #include <robot_protocol_msgs/Order.h>
namespace mission_adapters namespace mission_adapters
@@ -22,6 +24,18 @@ namespace mission_adapters
{ {
constexpr const char* kVda5050Order = "vda5050.order"; constexpr const char* kVda5050Order = "vda5050.order";
constexpr const char* kPoseStamped = "geometry.pose_stamped"; constexpr const char* kPoseStamped = "geometry.pose_stamped";
/**
* MỘT message `instantActions` của VDA5050 — tức một DANH SÁCH action, không phải một action.
*
* Giữ nguyên hình dạng của message là bắt buộc, không phải cho gọn: đẩy từng action xuống
* riêng lẻ thì action `HARD` thứ hai trong cùng message sẽ preempt và xoá sạch chặng của
* action thứ nhất — hai lệnh fleet gửi cùng lúc, một cái ăn thịt cái kia.
*
* Schema riêng chứ không nhét vào `kVda5050Order`: hai thứ khác nhau ở chỗ quyết định hành
* vi — order mới luôn thay hàng đợi, còn instantActions chỉ thay khi có action `HARD`.
*/
constexpr const char* kInstantAction = "vda5050.instant_action";
} // namespace schema } // namespace schema
/** /**
@@ -41,6 +55,8 @@ namespace mission_adapters
std::shared_ptr<robot_protocol_msgs::Order> order; std::shared_ptr<robot_protocol_msgs::Order> order;
std::shared_ptr<robot_geometry_msgs::PoseStamped> pose; std::shared_ptr<robot_geometry_msgs::PoseStamped> pose;
/// Danh sách action của MỘT message `instantActions`, giữ nguyên thứ tự fleet gửi.
std::shared_ptr<std::vector<robot_protocol_msgs::Action>> actions;
std::string raw_payload; std::string raw_payload;
@@ -62,6 +78,21 @@ namespace mission_adapters
return request; return request;
} }
/// @brief Dựng request từ một message `instantActions` (0..n action, giữ nguyên thứ tự).
static MissionRequest fromInstantActions(const std::vector<robot_protocol_msgs::Action>& actions)
{
MissionRequest request;
request.schema = schema::kInstantAction;
request.actions = std::make_shared<std::vector<robot_protocol_msgs::Action>>(actions);
return request;
}
/// @brief Tiện ích cho ca một action — vẫn đi đúng đường của cả lô.
static MissionRequest fromInstantAction(const robot_protocol_msgs::Action& action)
{
return fromInstantActions({action});
}
/// @brief Dựng request từ payload thô của một nguồn ngoài. /// @brief Dựng request từ payload thô của một nguồn ngoài.
static MissionRequest fromRaw(const std::string& schema_name, const std::string& payload) static MissionRequest fromRaw(const std::string& schema_name, const std::string& payload)
{ {

View File

@@ -137,6 +137,18 @@ namespace mission_adapters
/// Quãng đường tương đối [m] so với pose hiện tại; dương = tiến, âm = lùi. NaN = không dùng. /// Quãng đường tương đối [m] so với pose hiện tại; dương = tiến, âm = lùi. NaN = không dùng.
double relative_distance = std::numeric_limits<double>::quiet_NaN(); double relative_distance = std::numeric_limits<double>::quiet_NaN();
/**
* Góc quay tương đối [rad] so với hướng hiện tại; dương = ngược chiều kim đồng hồ (REP-103).
* NaN = không dùng.
*
* Đơn vị ở ĐÂY là radian, trong khi order của fleet mang ĐỘ: quy đổi xảy ra một lần duy
* nhất, tại adapter đọc payload. Mọi thứ từ đây trở vào lõi đều là radian.
*
* Đi kèm được với @ref relative_distance (chặng quay là distance 0 + góc khác 0), khác với
* cặp goal_frame/relative_distance vốn loại trừ nhau.
*/
double relative_yaw = std::numeric_limits<double>::quiet_NaN();
}; };
} // namespace mission_adapters } // namespace mission_adapters

View File

@@ -1,7 +1,9 @@
#include "vda5050_source_adapter.h" #include "vda5050_source_adapter.h"
#include <algorithm> #include <algorithm>
#include <cctype>
#include <cmath> #include <cmath>
#include <stdexcept>
#include <string> #include <string>
#include <utility> #include <utility>
@@ -21,6 +23,90 @@ bool isNavigationProfile(const std::string& profile)
profile == "go_straight" || profile == "rotate"; profile == "go_straight" || profile == "rotate";
} }
/// [deg] Biên của một chặng quay. Vượt biên là dấu hiệu order muốn thứ mà một pose không diễn tả
/// được — xem @ref parseTurnDegrees.
constexpr double kMaxTurnDegrees = 180.0;
/**
* @brief Đọc góc quay [deg] từ actionParameters và quy sang [rad].
*
* @param action Action gốc của order, nơi giữ tham số.
* @param key Tên khoá lấy từ `turn_param` của step.
* @param source Tên adapter, chỉ dùng cho log.
* @param radians Nơi ghi kết quả khi thành công.
* @return false nếu thiếu khoá, không parse được, hoặc ngoài biên — bên gọi phải bỏ CẢ message.
*
* Đơn vị vào là ĐỘ vì đó là thứ fleet và người vận hành gửi; ra là RADIAN vì đó là thứ mọi API bên
* trong dùng. Quy đổi nằm đúng ở đây, biên duy nhất chạm payload, và log in cả hai đơn vị để một
* lần lệch đơn vị lộ ra trong log thay vì phải suy ngược từ hành vi robot.
*
* Biên +/-180 độ KHÔNG phải để cho đẹp: đích của chặng là một POSE, mà pose chỉ nói hướng cuối chứ
* không nói quay bao nhiêu hay quay chiều nào. "Quay 270 độ ngược kim đồng hồ" quy về pose sẽ thành
* "quay 90 độ thuận kim đồng hồ" — robot làm đúng pose, sai ý định. Từ chối thẳng còn hơn quay
* ngược chiều người gửi mong đợi.
*/
bool parseTurnDegrees(const robot_protocol_msgs::Action& action, const std::string& key,
const std::string& source, double& radians)
{
const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(),
[&key](const robot_protocol_msgs::ActionParameter& p) {
return p.key == key;
});
if (it == action.actionParameters.end() || it->value.empty())
{
robot::log_error("VDA5050SourceAdapter[%s]: rotation action '%s' (actionId '%s') requires "
"parameter '%s' [deg] but it is missing",
source.c_str(), action.actionType.c_str(), action.actionId.c_str(),
key.c_str());
return false;
}
double degrees = 0.0;
try
{
std::size_t consumed = 0;
degrees = std::stod(it->value, &consumed);
// stod dừng ở ký tự lạ đầu tiên và vẫn trả về phần đọc được: "90abc" sẽ thành 90 nếu không
// kiểm phần đuôi. Chỉ chấp nhận khoảng trắng phía sau.
while (consumed < it->value.size() &&
std::isspace(static_cast<unsigned char>(it->value[consumed])))
{
++consumed;
}
if (consumed != it->value.size())
{
throw std::invalid_argument("trailing characters");
}
}
catch (const std::exception& ex)
{
robot::log_error("VDA5050SourceAdapter[%s]: rotation action '%s' (actionId '%s') has "
"parameter '%s' = '%s', which is not a number [deg]: %s",
source.c_str(), action.actionType.c_str(), action.actionId.c_str(),
key.c_str(), it->value.c_str(), ex.what());
return false;
}
if (!std::isfinite(degrees) || std::fabs(degrees) > kMaxTurnDegrees)
{
robot::log_error("VDA5050SourceAdapter[%s]: rotation action '%s' (actionId '%s') asks for "
"%.3f deg; only [-%.0f, %.0f] deg can be expressed as a goal pose. A "
"larger turn would silently become the short way round.",
source.c_str(), action.actionType.c_str(), action.actionId.c_str(),
degrees, kMaxTurnDegrees, kMaxTurnDegrees);
return false;
}
radians = degrees * M_PI / 180.0;
robot::log_info("VDA5050SourceAdapter[%s]: rotation action '%s' (actionId '%s'): %s=%.3f [deg] "
"-> relative_yaw=%.4f [rad]",
source.c_str(), action.actionType.c_str(), action.actionId.c_str(), key.c_str(),
degrees, radians);
return true;
}
using mission_adapters::Action; using mission_adapters::Action;
using mission_adapters::ActionType; using mission_adapters::ActionType;
using mission_adapters::ConversionResult; using mission_adapters::ConversionResult;
@@ -127,6 +213,7 @@ bool VDA5050SourceAdapter::loadCompoundActions(const std::string& name, robot::N
if (n["move"]) step.move = n["move"].as<double>(); if (n["move"]) step.move = n["move"].as<double>();
if (n["profile"]) step.motion_hint = n["profile"].as<std::string>(); if (n["profile"]) step.motion_hint = n["profile"].as<std::string>();
if (n["marker"]) step.marker = n["marker"].as<std::string>(); if (n["marker"]) step.marker = n["marker"].as<std::string>();
if (n["turn_param"]) step.turn_param = n["turn_param"].as<std::string>();
} }
catch (const YAML::Exception& ex) catch (const YAML::Exception& ex)
{ {
@@ -168,6 +255,17 @@ bool VDA5050SourceAdapter::loadCompoundActions(const std::string& name, robot::N
name.c_str(), action_type.c_str(), i); name.c_str(), action_type.c_str(), i);
return false; return false;
} }
if (!step.turn_param.empty() && step.motion_hint != "rotate")
{
// Góc quay chỉ có nghĩa với planner quay tại chỗ. Gắn vào profile khác thì hoặc là
// gõ nhầm, hoặc là mong đợi một hành vi không tồn tại — cả hai đều phải nổ ở boot
// chứ không phải bị bỏ qua lặng lẽ lúc order đầu tiên tới.
robot::log_error("VDA5050SourceAdapter[%s]: '%s' step %zu sets turn_param but its "
"profile is '%s'; turn_param is only valid with 'rotate'",
name.c_str(), action_type.c_str(), i,
step.motion_hint.empty() ? "position" : step.motion_hint.c_str());
return false;
}
steps.push_back(step); steps.push_back(step);
} }
@@ -427,6 +525,14 @@ bool VDA5050SourceAdapter::expandCompound(
{ {
sub->relative_distance = step.move; sub->relative_distance = step.move;
} }
// Góc quay đi kèm được với quãng tịnh tiến: chặng `rotate` là move 0 m + góc khác 0.
// Đặt sau khối trên để nó áp cho mọi dạng đích, không riêng dạng tương đối.
if (!step.turn_param.empty() &&
!parseTurnDegrees(entry.action, step.turn_param, name_, sub->relative_yaw))
{
return false;
}
} }
out.push_back(std::move(sub)); out.push_back(std::move(sub));
@@ -572,6 +678,176 @@ ConversionResult VDA5050SourceAdapter::convert(const mission_adapters::MissionRe
return result; return result;
} }
// ═════════════════════════════════════════════════════════════════════════════════════════════════
// InstantActionSourceAdapter
// ═════════════════════════════════════════════════════════════════════════════════════════════════
mission_adapters::MissionSourceAdapter::Ptr InstantActionSourceAdapter::create()
{
return std::make_shared<InstantActionSourceAdapter>();
}
std::string InstantActionSourceAdapter::schema() const
{
return mission_adapters::schema::kInstantAction;
}
bool InstantActionSourceAdapter::configure(const std::string& name, robot::NodeHandle& nh)
{
// Lớp cha gán name_/global_frame_ và nạp bảng compound theo namespace CỦA CHÍNH instance này —
// ở đó không có bảng nào, nên nó về rỗng. Đó là điều mong muốn: bảng thật được nạp lại ngay bên
// dưới từ namespace của nguồn order.
if (!VDA5050SourceAdapter::configure(name, nh))
return false;
nh.getParam(name + "/compound_actions_from", compound_source_, std::string("vda5050_src"));
if (compound_source_.empty())
{
robot::log_error("InstantActionSourceAdapter[%s]: compound_actions_from is empty — it must "
"name the mission source that owns the compound_actions table",
name.c_str());
return false;
}
if (!loadCompoundActions(compound_source_, nh))
return false;
robot::log_info("InstantActionSourceAdapter[%s]: sharing the compound_actions table of '%s'",
name.c_str(), compound_source_.c_str());
return true;
}
mission_adapters::SubmitMode
InstantActionSourceAdapter::toSubmitMode(const std::string& blocking_type)
{
// CỐ Ý bỏ qua `blocking_type`: một message instantActions LUÔN preempt.
//
// `kAppend` không còn ca dùng nào đúng. Fleet gửi message tiếp theo trong lúc message trước còn
// chạy, và ý nghĩa của lệnh mới là thay lệnh cũ — xếp nó sau chuỗi cũ thì lệnh "instant" chạy
// sau vài chục giây, và message cũ vẫn thao tác thiết bị dù đã bị lệnh mới thay thế.
//
// Tham số giữ lại vì nó là hợp đồng đọc được: chữ ký nói rằng đây là chỗ `blockingType` từng
// quyết định hàng đợi, và ai muốn khôi phục sự phân biệt đó thì sửa đúng một hàm này.
(void)blocking_type;
return SubmitMode::kReplace;
}
bool InstantActionSourceAdapter::validate(const mission_adapters::MissionRequest& request,
std::string& reason) const
{
if (!request.actions)
{
reason = "request is missing the instantActions payload";
return false;
}
if (request.actions->empty())
{
reason = "instantActions message carries no action";
return false;
}
// Một action hỏng làm hỏng CẢ message. VDA5050 chỉ đòi robot báo done/fail cho lượt gửi này, và
// fleet đang chặn mọi lệnh khác để đợi — chạy được ba trên bốn rồi báo "xong" là báo sai.
for (std::size_t i = 0; i < request.actions->size(); ++i)
{
const robot_protocol_msgs::Action& action = (*request.actions)[i];
if (action.actionType.empty())
{
reason = "action " + std::to_string(i) + " has an empty actionType";
return false;
}
// VDA5050 bắt buộc actionId. Ở đây nó còn là thứ host dùng để dựng `actionStates` trả về.
if (action.actionId.empty())
{
reason = "action '" + action.actionType + "' (index " + std::to_string(i) +
") has an empty actionId";
return false;
}
}
return true;
}
void InstantActionSourceAdapter::logBlockingTypeNarrowing(
const robot_protocol_msgs::Action& action) const
{
if (action.blockingType != robot_protocol_msgs::Action::NONE &&
action.blockingType != robot_protocol_msgs::Action::SOFT &&
action.blockingType != robot_protocol_msgs::Action::HARD)
{
robot::log_warning("InstantActionSourceAdapter[%s]: '%s' (id '%s') has blockingType '%s' — "
"not one of NONE/SOFT/HARD; treating it as HARD",
name_.c_str(), action.actionType.c_str(), action.actionId.c_str(),
action.blockingType.c_str());
return;
}
if (action.blockingType == robot_protocol_msgs::Action::NONE)
{
// Thu hẹp có chủ đích, xem doc của lớp. Log để người đọc log biết vì sao robot đứng chờ thay
// vì chạy song song như fleet mong đợi.
robot::log_warning("InstantActionSourceAdapter[%s]: '%s' (id '%s') asks for blockingType "
"NONE (parallel with movement) — this runtime cannot drive while an "
"action runs, so it is queued after the current leg instead",
name_.c_str(), action.actionType.c_str(), action.actionId.c_str());
}
}
mission_adapters::ConversionResult
InstantActionSourceAdapter::convert(const mission_adapters::MissionRequest& request)
{
ConversionResult result;
// Cả message preempt, không phụ thuộc `blockingType` — xem @ref toSubmitMode.
result.mode = SubmitMode::kReplace;
for (const robot_protocol_msgs::Action& action : *request.actions)
{
logBlockingTypeNarrowing(action);
// Chặng chỉ-action mang đúng action vừa nhận. Nếu nó là compound, `expandCompound` sẽ GỠ
// action khỏi đây và phát ra chuỗi chặng thay thế — lúc đó chặng này rỗng và bị bỏ bên dưới.
auto leg = std::make_shared<Mission>();
leg->type = MissionType::VDA5050_ORDER;
leg->has_goal = false;
Action carried;
carried.type = ActionType::NODE_ACTION;
carried.sequenceId = 0;
carried.action = action;
leg->actions.push_back(std::move(carried));
std::vector<std::shared_ptr<Mission>> expanded;
if (!expandCompound(leg, expanded))
{
// Thiếu tham số cấu trúc (ví dụ `move_to_param` không có trong actionParameters).
//
// Bỏ CẢ MESSAGE, kể cả những action đã dựng xong trước đó trong vòng lặp này. Fleet gửi
// một message và chờ một câu trả lời done/fail cho nó; chạy được ba action rồi tắc ở
// action thứ tư mà vẫn báo "xong" là báo sai — và những action đã chạy thì đã đụng vào
// thiết bị thật rồi. Trả rỗng: EventProcessor giữ nguyên hàng đợi đang chạy.
robot::log_error("InstantActionSourceAdapter[%s]: action '%s' (id '%s') could not be "
"expanded — dropping the whole instantActions message (%zu action(s))",
name_.c_str(), action.actionType.c_str(), action.actionId.c_str(),
request.actions->size());
return ConversionResult{};
}
// Sau khi nở, chặng gốc chỉ còn ý nghĩa khi action KHÔNG phải compound.
if (leg->has_goal || !leg->actions.empty())
result.missions.push_back(std::move(leg));
for (auto& sub : expanded)
result.missions.push_back(std::move(sub));
}
return result;
}
} // namespace mission_plugins } // namespace mission_plugins
BOOST_DLL_ALIAS(mission_plugins::VDA5050SourceAdapter::create, VDA5050SourceAdapter) BOOST_DLL_ALIAS(mission_plugins::VDA5050SourceAdapter::create, VDA5050SourceAdapter)
BOOST_DLL_ALIAS(mission_plugins::InstantActionSourceAdapter::create, InstantActionSourceAdapter)

View File

@@ -64,12 +64,17 @@ public:
mission_adapters::ConversionResult mission_adapters::ConversionResult
convert(const mission_adapters::MissionRequest& request) override; convert(const mission_adapters::MissionRequest& request) override;
private: // Phần dưới là `protected` chứ không `private` vì @ref InstantActionSourceAdapter kế thừa lớp
// này để dùng lại đúng một thứ: bộ nở compound action. Bảng `compound_actions` PHẢI là nguồn
// duy nhất — `charge` gửi dạng node action và `charge` gửi dạng instantAction bắt buộc nở ra
// cùng một chuỗi chặng, nếu không thì cùng một chữ lại có hai nghĩa tuỳ đường vào.
protected:
/** /**
* @struct Step * @struct Step
* @brief Một bước trong chuỗi mở rộng của compound action. * @brief Một bước trong chuỗi mở rộng của compound action.
* *
* Engine hiểu đúng bốn từ khoá và **không biết** `charge`, `dock_target` hay `LiftFork` nghĩa là * Engine hiểu đúng bốn từ khoá chính (cộng ba khoá tuỳ chọn) và **không biết** `charge`,
* `dock_target` hay `LiftFork` nghĩa là
* gì — đó là điều kiện để cùng một engine dùng lại cho model robot khác: thêm model = thêm YAML * gì — đó là điều kiện để cùng một engine dùng lại cho model robot khác: thêm model = thêm YAML
* + một `.so` handler, không sửa dòng nào ở đây. * + một `.so` handler, không sửa dòng nào ở đây.
* *
@@ -84,6 +89,15 @@ private:
std::string motion_hint; ///< `profile:` -> position | docking | go_straight | rotate std::string motion_hint; ///< `profile:` -> position | docking | go_straight | rotate
std::string marker; ///< `marker:` -> khoá override planner, chỉ hợp lệ với docking std::string marker; ///< `marker:` -> khoá override planner, chỉ hợp lệ với docking
/**
* `turn_param: <key>` -> góc quay lấy từ actionParameters[<key>] của chính order, tính bằng
* ĐỘ. Chỉ hợp lệ với `profile: rotate`; `configure()` từ chối lúc boot nếu gắn nhầm profile.
*
* Cùng vai trò với @ref move_to_param: bảng compound giữ CẤU TRÚC (khoá nào mang góc), còn
* số đo tới từ order. Nhờ vậy đổi góc quay không phải sửa file YAML nào.
*/
std::string turn_param;
}; };
/// @brief Chuỗi chặng thay cho một action. Bảng chỉ giữ CẤU TRÚC, dữ liệu tới từ order. /// @brief Chuỗi chặng thay cho một action. Bảng chỉ giữ CẤU TRÚC, dữ liệu tới từ order.
@@ -141,6 +155,94 @@ private:
size_t converted_node_count_ = 0; size_t converted_node_count_ = 0;
}; };
/**
* @class InstantActionSourceAdapter
* @brief Nguồn mission từ MỘT message `instantActions` của VDA5050 (schema "vda5050.instant_action").
*
* Kế thừa @ref VDA5050SourceAdapter **chỉ để dùng lại bộ nở compound action**, không phải vì quan hệ
* "là một". Lý do là ràng buộc dữ liệu: bảng `compound_actions` phải có đúng một bản, nếu không thì
* `charge` gửi dạng node action và `charge` gửi dạng instantAction sẽ nở ra hai chuỗi chặng khác
* nhau — chính cái bệnh mà lớp này sinh ra để chữa.
*
* Nằm cùng `.so` với lớp cha và export bằng alias thứ hai. Ranh giới `.so` không đổi: contract
* `MissionSourceAdapter` giữ nguyên từng chữ ký.
*
* ## Cả message là một lô
*
* Message mang 0..n action. Chúng được nở theo đúng thứ tự fleet gửi và nối thành MỘT
* `ConversionResult`, tức một lần vào hàng đợi. Đẩy từng action xuống riêng lẻ sẽ hỏng ngay ở
* message thứ hai có `HARD`: nó preempt và xoá sạch chặng của action đứng trước nó trong cùng
* message.
*
* Một action không nở được thì **bỏ cả message**, kể cả phần đã dựng xong. Fleet gửi một message và
* chờ một câu trả lời done/fail cho nó; chạy được ba action rồi tắc ở action thứ tư mà vẫn báo
* "xong" là báo sai — và ba action kia đã đụng vào thiết bị thật rồi.
*
* Dừng-ở-lỗi lúc CHẠY là việc của `clear_queue_on_failure` (mission_adapters_params.yaml): chặng
* nào hỏng thì phần còn lại của hàng đợi bị xoá, nên message tự động dừng tại action lỗi.
*
* ## Message mới LUÔN thay message cũ
*
* `SubmitMode` luôn là `kReplace`, không phụ thuộc `blockingType`. Fleet gửi message tiếp theo khi
* message trước còn đang chạy, và nghĩa của lệnh mới là thay lệnh cũ: xếp nó vào cuối hàng đợi thì
* một lệnh mang tên "instant" chạy sau vài chục giây, còn chuỗi cũ vẫn kịp thao tác thiết bị dù đã
* bị thay thế. Chuỗi cũ bị huỷ tường minh (`MissionManager::submit`), nên host thấy `PREEMPTED` và
* báo message cũ là FAILED — đúng thứ đã xảy ra.
*
* `blockingType` vì vậy KHÔNG còn chọn cách vào hàng đợi. Nó vẫn được đọc và log khi giá trị lạ
* hoặc khi `NONE` bị thu hẹp, để lệch từ vựng giữa fleet và robot vẫn lộ ra trong log.
*
* @warning Hệ quả: một instantAction đến giữa lúc order đang chạy sẽ **huỷ order đó**. Fleet master
* hiện tại không gửi trong tình huống này; `MissionLayer::submitInstantActions` cảnh báo
* khi giả định đó bị vi phạm. VDA5050 thì cho phép, nên đây là chỗ phải xem lại trước khi
* đổi sang fleet master khác.
*
*/
class InstantActionSourceAdapter : public VDA5050SourceAdapter
{
public:
/// @brief Factory được PluginRegistry nạp qua boost::dll::import_alias.
static mission_adapters::MissionSourceAdapter::Ptr create();
/**
* @brief Đọc param riêng của instance.
*
* Param (namespace `<name>`):
* - `compound_actions_from` [string, mặc định "vda5050_src"]: namespace của nguồn order để
* **dùng chung** bảng `compound_actions`. Khai bảng thứ hai dưới namespace của chính instance
* này là quay lại đúng vấn đề hai-bản-lệch-nhau, chỉ khác là lệch trong YAML thay vì trong
* code — nên adapter cố ý KHÔNG đọc bảng của chính nó.
*/
bool configure(const std::string& name, robot::NodeHandle& nh) override;
std::string schema() const override;
bool validate(const mission_adapters::MissionRequest& request,
std::string& reason) const override;
mission_adapters::ConversionResult
convert(const mission_adapters::MissionRequest& request) override;
/// @brief Namespace mà bảng compound được đọc từ đó. Cho test và log.
const std::string& compoundSource() const { return compound_source_; }
/**
* @brief Cách một message instantActions vào hàng đợi. Luôn `kReplace`.
*
* Tham số `blockingType` được giữ nguyên trong chữ ký dù không còn được đọc: nó đánh dấu đây là
* chỗ duy nhất quyết định điều đó, nên khôi phục sự phân biệt HARD/SOFT/NONE chỉ phải sửa ở đây.
*
* `static` và public để test được mà không phải dựng cả adapter — hàm thuần, không đụng state.
*/
static mission_adapters::SubmitMode toSubmitMode(const std::string& blocking_type);
private:
/// @brief Log khi `blockingType` bị hạ cấp hoặc không đọc được. Không đổi hành vi, chỉ để lại vết.
void logBlockingTypeNarrowing(const robot_protocol_msgs::Action& action) const;
std::string compound_source_ = "vda5050_src";
};
} // namespace mission_plugins } // namespace mission_plugins
#endif // MISSION_ADAPTERS_PLUGINS_VDA5050_SOURCE_ADAPTER_H_ #endif // MISSION_ADAPTERS_PLUGINS_VDA5050_SOURCE_ADAPTER_H_

View File

@@ -158,6 +158,11 @@ namespace mission_adapters
submitRequest(MissionRequest::fromPose(goal)); submitRequest(MissionRequest::fromPose(goal));
} }
void EventProcessor::instantActionsEvent(const std::vector<robot_protocol_msgs::Action>& actions)
{
submitRequest(MissionRequest::fromInstantActions(actions));
}
void EventProcessor::pauseEvent() void EventProcessor::pauseEvent()
{ {
Event event; Event event;

View File

@@ -514,6 +514,387 @@ TEST(CompoundConfig, RejectsInvalidOrActionOnlyProfiles)
EXPECT_FALSE(adapter.configure("vda5050_bad_profile", nh)); EXPECT_FALSE(adapter.configure("vda5050_bad_profile", nh));
} }
TEST(CompoundConfig, RejectsTurnParamOnANonRotationStep)
{
robot::NodeHandle nh;
VDA5050SourceAdapter adapter;
EXPECT_FALSE(adapter.configure("vda5050_bad_turn_param", nh))
<< "góc quay chỉ có nghĩa với profile rotate; gắn vào profile khác là mong đợi một hành vi "
"không tồn tại, phải nổ ở boot chứ không im lặng lúc order đầu tiên tới";
}
// ═════════════════════════════════════════════════════════════════════════════════════════════════
// InstantActionSourceAdapter
//
// Thứ phải khoá ở đây, theo mức nghiêm trọng:
// 1. instantAction dùng ĐÚNG bảng compound của nguồn order — nếu không thì `charge` có hai nghĩa
// tuỳ đường vào, và một trong hai nghĩa sẽ bỏ bước dò rồi lùi vào trạm bằng toạ độ cũ;
// 2. `blockingType` map ra đúng SubmitMode — sai hướng nghĩa là một `MutedOn` xoá cả order đang
// chạy, hoặc một lệnh HARD phải xếp hàng sau cả tuyến đường;
// 3. thiếu tham số cấu trúc thì BỎ HẲN, không chạy nửa chuỗi;
// 4. không bao giờ sinh ra mission không goal cũng không action (EventProcessor sẽ vứt cả lô).
// ═════════════════════════════════════════════════════════════════════════════════════════════════
namespace
{
using mission_plugins::InstantActionSourceAdapter;
/// @brief instantAction hợp lệ tối thiểu: có actionType, actionId và blockingType.
robot_protocol_msgs::Action makeInstant(const std::string& type,
const std::string& blocking = "HARD",
const std::string& param_key = "",
const std::string& param_value = "")
{
robot_protocol_msgs::Action action;
action.actionType = type;
action.actionId = type + "_instant_id";
action.blockingType = blocking;
if (!param_key.empty())
{
robot_protocol_msgs::ActionParameter p;
p.key = param_key;
p.value = param_value;
action.actionParameters.push_back(p);
}
return action;
}
class InstantActionAdapterTest : public ::testing::Test
{
protected:
void SetUp() override
{
robot::NodeHandle nh;
ASSERT_TRUE(adapter.configure("instant_src", nh));
}
ConversionResult convert(const robot_protocol_msgs::Action& action)
{
return adapter.convert(MissionRequest::fromInstantAction(action));
}
ConversionResult convertAll(const std::vector<robot_protocol_msgs::Action>& actions)
{
return adapter.convert(MissionRequest::fromInstantActions(actions));
}
InstantActionSourceAdapter adapter;
};
} // namespace
TEST_F(InstantActionAdapterTest, DeclaresItsOwnSchema)
{
EXPECT_EQ(adapter.schema(), std::string(mission_adapters::schema::kInstantAction));
EXPECT_NE(adapter.schema(), std::string(mission_adapters::schema::kVda5050Order))
<< "trùng schema với nguồn order thì registry chỉ giữ được một trong hai";
}
TEST_F(InstantActionAdapterTest, SharesTheCompoundTableOfTheOrderSource)
{
EXPECT_EQ(adapter.compoundSource(), "vda5050_src");
}
TEST(InstantActionConfig, DefaultsToTheOrderSourceWhenNotConfigured)
{
robot::NodeHandle nh;
InstantActionSourceAdapter adapter;
// `instant_src_no_table` không khai compound_actions_from... nhưng nó khai. Dùng một namespace
// hoàn toàn trống để kiểm mặc định.
ASSERT_TRUE(adapter.configure("registry_test_empty", nh));
EXPECT_EQ(adapter.compoundSource(), "vda5050_src") << "mặc định phải trỏ về nguồn order";
}
TEST(InstantActionConfig, AcceptsASourceWithNoCompoundTable)
{
robot::NodeHandle nh;
InstantActionSourceAdapter adapter;
ASSERT_TRUE(adapter.configure("instant_src_no_table", nh))
<< "không có bảng là hợp lệ: mọi action chạy thẳng như action thường";
const auto result = adapter.convert(MissionRequest::fromInstantAction(makeInstant("charge")));
ASSERT_EQ(result.missions.size(), 1u) << "không có bảng thì `charge` KHÔNG được nở";
EXPECT_EQ(result.missions[0]->actions.at(0).action.actionType, "charge");
}
TEST(InstantActionConfig, RejectsAnEmptyCompoundSource)
{
robot::NodeHandle nh;
InstantActionSourceAdapter adapter;
EXPECT_FALSE(adapter.configure("instant_src_empty_source", nh))
<< "chuỗi rỗng không trỏ tới nguồn nào — phải trượt lúc boot, không phải lúc action đầu tới";
}
TEST_F(InstantActionAdapterTest, RejectsAMissingPayload)
{
MissionRequest request;
request.schema = mission_adapters::schema::kInstantAction;
std::string reason;
EXPECT_FALSE(adapter.validate(request, reason));
EXPECT_FALSE(reason.empty());
}
TEST_F(InstantActionAdapterTest, RejectsAnEmptyMessage)
{
std::string reason;
EXPECT_FALSE(adapter.validate(MissionRequest::fromInstantActions({}), reason))
<< "message rỗng để host ngồi chờ một kết quả không bao giờ tới";
}
TEST_F(InstantActionAdapterTest, RejectsAnEmptyActionType)
{
auto action = makeInstant("PickUp");
action.actionType.clear();
std::string reason;
EXPECT_FALSE(adapter.validate(MissionRequest::fromInstantAction(action), reason));
}
TEST_F(InstantActionAdapterTest, RejectsAnEmptyActionId)
{
auto action = makeInstant("PickUp");
action.actionId.clear();
std::string reason;
EXPECT_FALSE(adapter.validate(MissionRequest::fromInstantAction(action), reason))
<< "thiếu actionId thì action chạy xong fleet cũng không ghép được kết quả về đâu";
}
TEST_F(InstantActionAdapterTest, AcceptsAWellFormedAction)
{
std::string reason;
EXPECT_TRUE(adapter.validate(MissionRequest::fromInstantAction(makeInstant("MutedOn")), reason));
EXPECT_TRUE(reason.empty());
}
TEST_F(InstantActionAdapterTest, APlainActionBecomesOneActionOnlyMission)
{
const auto result = convert(makeInstant("MutedOn"));
ASSERT_EQ(result.missions.size(), 1u);
EXPECT_FALSE(result.missions[0]->has_goal) << "action thường không có quãng đường nào để đi";
ASSERT_EQ(result.missions[0]->actions.size(), 1u);
EXPECT_EQ(result.missions[0]->actions[0].action.actionType, "MutedOn");
EXPECT_EQ(result.missions[0]->actions[0].action.actionId, "MutedOn_instant_id")
<< "actionId phải đi nguyên vẹn — host dùng nó để ghép trạng thái trả về";
EXPECT_TRUE(result.missions[0]->motion_hint.empty())
<< "mission chỉ-action để trống profile, nếu không sẽ bị hiểu là yêu cầu điều khiển";
}
TEST_F(InstantActionAdapterTest, ACompoundActionExpandsExactlyLikeANodeAction)
{
const auto result = convert(makeInstant("charge", "HARD", "goal_frame", "charger_07_goal"));
// DetectCharger | docking | startCharging — KHÔNG có chặng nav dẫn tới, vì instantAction không
// mang node nào.
ASSERT_EQ(result.missions.size(), 3u);
EXPECT_FALSE(result.missions[0]->has_goal);
ASSERT_EQ(result.missions[0]->actions.size(), 1u);
EXPECT_EQ(result.missions[0]->actions[0].action.actionType, "DetectCharger");
EXPECT_TRUE(result.missions[1]->has_goal);
EXPECT_EQ(result.missions[1]->motion_hint, "docking");
EXPECT_EQ(result.missions[1]->goal_frame, "charger_07_goal")
<< "frame phải lấy từ actionParameters của chính instantAction";
EXPECT_EQ(result.missions[1]->marker, "charger");
EXPECT_FALSE(result.missions[2]->has_goal);
ASSERT_EQ(result.missions[2]->actions.size(), 1u);
EXPECT_EQ(result.missions[2]->actions[0].action.actionType, "startCharging");
}
TEST_F(InstantActionAdapterTest, TheCarrierLegIsDroppedOnceTheActionIsExpanded)
{
const auto result = convert(makeInstant("charge", "HARD", "goal_frame", "charger_07_goal"));
// Bất biến D8, cũng là thứ EventProcessor kiểm và vứt CẢ LÔ nếu vi phạm: chặng mang action gốc
// trở thành rỗng sau khi nở, nên nó phải bị bỏ chứ không được đẩy xuống.
for (const auto& mission : result.missions)
{
EXPECT_TRUE(mission->has_goal || !mission->actions.empty())
<< "mission không goal cũng không action là mission không có việc gì để làm";
}
}
TEST_F(InstantActionAdapterTest, ARelativeMoveCompoundCarriesTheDistance)
{
const auto result = convert(makeInstant("UnDockFromStation", "HARD"));
ASSERT_EQ(result.missions.size(), 1u);
EXPECT_TRUE(result.missions[0]->has_goal);
EXPECT_EQ(result.missions[0]->motion_hint, "go_straight");
EXPECT_DOUBLE_EQ(result.missions[0]->relative_distance, -1.0) << "[m] âm = lùi ra khỏi trạm";
}
TEST_F(InstantActionAdapterTest, ARotationCompoundConvertsDegreesToRadians)
{
// Order của fleet mang ĐỘ; mọi thứ từ mission layer trở vào lõi là RADIAN. Quy đổi phải xảy ra
// đúng một lần, ở đây.
const auto result = convert(makeInstant("rotate", "HARD", "angle_deg", "90"));
ASSERT_EQ(result.missions.size(), 1u);
EXPECT_TRUE(result.missions[0]->has_goal);
EXPECT_EQ(result.missions[0]->motion_hint, "rotate");
EXPECT_DOUBLE_EQ(result.missions[0]->relative_distance, 0.0) << "[m] chặng quay không tịnh tiến";
EXPECT_NEAR(result.missions[0]->relative_yaw, M_PI / 2.0, 1e-9);
}
TEST_F(InstantActionAdapterTest, ARotationKeepsTheSignOfTheRequestedAngle)
{
const auto result = convert(makeInstant("rotate", "HARD", "angle_deg", "-45"));
ASSERT_EQ(result.missions.size(), 1u);
EXPECT_NEAR(result.missions[0]->relative_yaw, -M_PI / 4.0, 1e-9)
<< "âm = thuận chiều kim đồng hồ (REP-103)";
}
TEST_F(InstantActionAdapterTest, ARotationWithoutItsAngleDropsTheWholeAction)
{
// Không có góc thì không có chặng quay nào để chạy. Rơi về 0 độ nghĩa là robot nhận lệnh quay
// rồi đứng im, và fleet vẫn thấy action FINISHED.
EXPECT_TRUE(convert(makeInstant("rotate", "HARD")).missions.empty());
}
TEST_F(InstantActionAdapterTest, ARotationWithANonNumericAngleDropsTheWholeAction)
{
EXPECT_TRUE(convert(makeInstant("rotate", "HARD", "angle_deg", "quarter turn")).missions.empty());
// stod() dừng ở ký tự lạ và vẫn trả phần đọc được: "90abc" phải bị từ chối, không phải hiểu
// thành 90 độ.
EXPECT_TRUE(convert(makeInstant("rotate", "HARD", "angle_deg", "90abc")).missions.empty());
}
TEST_F(InstantActionAdapterTest, ARotationBeyondHalfATurnIsRefused)
{
// Đích của chặng là một POSE, mà pose chỉ nói hướng cuối chứ không nói quay bao nhiêu hay chiều
// nào. 270 độ ngược kim đồng hồ quy về pose sẽ thành 90 độ thuận kim đồng hồ — robot làm đúng
// pose, sai ý định. Từ chối còn hơn quay ngược chiều người gửi mong đợi.
EXPECT_TRUE(convert(makeInstant("rotate", "HARD", "angle_deg", "270")).missions.empty());
EXPECT_TRUE(convert(makeInstant("rotate", "HARD", "angle_deg", "-181")).missions.empty());
// Đúng biên thì vẫn nhận.
const auto edge = convert(makeInstant("rotate", "HARD", "angle_deg", "180"));
ASSERT_EQ(edge.missions.size(), 1u);
EXPECT_NEAR(edge.missions[0]->relative_yaw, M_PI, 1e-9);
}
TEST_F(InstantActionAdapterTest, ANonRotationCompoundLeavesTheYawUnset)
{
const auto result = convert(makeInstant("UnDockFromStation", "HARD"));
ASSERT_EQ(result.missions.size(), 1u);
EXPECT_TRUE(std::isnan(result.missions[0]->relative_yaw))
<< "NaN = không dùng; một giá trị 0 ở đây sẽ ép chặng go_straight phải giữ nguyên hướng";
}
TEST_F(InstantActionAdapterTest, AMissingCompoundParameterDropsTheWholeAction)
{
// `charge` cần `goal_frame` trong actionParameters; không có thì bước docking không biết lùi vào
// đâu. Chạy nửa chuỗi — dò xong rồi đóng relay sạc tại chỗ đang đứng — nguy hiểm hơn là không
// chạy.
const auto result = convert(makeInstant("charge", "HARD"));
EXPECT_TRUE(result.missions.empty());
}
TEST(InstantActionBlocking, EveryMessagePreemptsRegardlessOfBlockingType)
{
// Message instantActions mới LUÔN thay message cũ. `kAppend` không còn ca dùng nào đúng: xếp
// sau chuỗi cũ thì lệnh "instant" chạy sau vài chục giây, và chuỗi cũ vẫn kịp thao tác thiết bị
// dù đã bị lệnh mới thay thế.
EXPECT_EQ(InstantActionSourceAdapter::toSubmitMode("HARD"), SubmitMode::kReplace);
EXPECT_EQ(InstantActionSourceAdapter::toSubmitMode("SOFT"), SubmitMode::kReplace);
EXPECT_EQ(InstantActionSourceAdapter::toSubmitMode("NONE"), SubmitMode::kReplace);
EXPECT_EQ(InstantActionSourceAdapter::toSubmitMode(""), SubmitMode::kReplace);
EXPECT_EQ(InstantActionSourceAdapter::toSubmitMode("BLOCKING"), SubmitMode::kReplace);
}
TEST_F(InstantActionAdapterTest, TheConversionAlwaysAsksForPreemption)
{
EXPECT_EQ(convert(makeInstant("MutedOn", "HARD")).mode, SubmitMode::kReplace);
EXPECT_EQ(convert(makeInstant("MutedOn", "SOFT")).mode, SubmitMode::kReplace);
EXPECT_EQ(convert(makeInstant("MutedOn", "NONE")).mode, SubmitMode::kReplace);
}
TEST_F(InstantActionAdapterTest, TwoActionsInARowDoNotLeakStateIntoEachOther)
{
const auto first = convert(makeInstant("charge", "HARD", "goal_frame", "charger_01_goal"));
const auto second = convert(makeInstant("MutedOn", "SOFT"));
ASSERT_EQ(first.missions.size(), 3u);
ASSERT_EQ(second.missions.size(), 1u);
EXPECT_EQ(second.missions[0]->actions.at(0).action.actionType, "MutedOn");
EXPECT_EQ(second.mode, SubmitMode::kReplace)
<< "message sau không được thừa hưởng state của message trước";
}
// ── Nhiều action trong MỘT message ──────────────────────────────────────────────────────────────
//
// Đây là ca mà bản "một action một lần" hỏng: action `HARD` thứ hai preempt và xoá sạch chặng của
// action thứ nhất. Cả message phải thành MỘT lô, một lần vào hàng đợi.
TEST_F(InstantActionAdapterTest, EveryActionOfTheMessageIsConvertedInOrder)
{
const auto result = convertAll({ makeInstant("MutedOn", "SOFT"),
makeInstant("MutedOff", "SOFT") });
ASSERT_EQ(result.missions.size(), 2u);
EXPECT_EQ(result.missions[0]->actions.at(0).action.actionType, "MutedOn");
EXPECT_EQ(result.missions[1]->actions.at(0).action.actionType, "MutedOff");
}
TEST_F(InstantActionAdapterTest, CompoundAndPlainActionsMixInTheRightOrder)
{
// `[MutedOn, charge, MutedOff]` — chuỗi charge phải nằm GIỮA, không được gom hết lại: bật lại
// cảm biến an toàn trước khi robot lùi vào trạm là đảo ngược hợp đồng an toàn.
const auto result = convertAll({ makeInstant("MutedOn", "SOFT"),
makeInstant("charge", "SOFT", "goal_frame", "charger_09_goal"),
makeInstant("MutedOff", "SOFT") });
// MutedOn | DetectCharger | docking | startCharging | MutedOff
ASSERT_EQ(result.missions.size(), 5u);
EXPECT_EQ(result.missions[0]->actions.at(0).action.actionType, "MutedOn");
EXPECT_EQ(result.missions[1]->actions.at(0).action.actionType, "DetectCharger");
EXPECT_EQ(result.missions[2]->motion_hint, "docking");
EXPECT_EQ(result.missions[3]->actions.at(0).action.actionType, "startCharging");
EXPECT_EQ(result.missions[4]->actions.at(0).action.actionType, "MutedOff");
}
TEST_F(InstantActionAdapterTest, AMixedMessageStillPreemptsAsAWhole)
{
// Mode là của CẢ message, và luôn là preempt — kể cả message không có action `HARD` nào.
EXPECT_EQ(convertAll({ makeInstant("a", "SOFT"), makeInstant("b", "HARD") }).mode,
SubmitMode::kReplace);
EXPECT_EQ(convertAll({ makeInstant("a", "SOFT"), makeInstant("b", "NONE") }).mode,
SubmitMode::kReplace);
}
TEST_F(InstantActionAdapterTest, OneUnexpandableActionDropsTheWholeMessage)
{
// `charge` thiếu `goal_frame`. Những action đứng TRƯỚC nó đã dựng xong cũng phải bị bỏ: fleet
// chờ một câu trả lời done/fail cho cả message, mà `MutedOn` thì đã đụng vào thiết bị thật.
const auto result = convertAll({ makeInstant("MutedOn", "SOFT"),
makeInstant("charge", "SOFT"),
makeInstant("MutedOff", "SOFT") });
EXPECT_TRUE(result.missions.empty())
<< "chạy được nửa message rồi báo xong là báo sai";
}
TEST_F(InstantActionAdapterTest, ValidateRejectsTheMessageWhenAnyActionIsMalformed)
{
auto bad = makeInstant("PickUp");
bad.actionId.clear();
std::string reason;
EXPECT_FALSE(adapter.validate(
MissionRequest::fromInstantActions({ makeInstant("MutedOn"), bad }), reason))
<< "một action hỏng làm hỏng cả message — không chạy nửa vời";
EXPECT_NE(reason.find("PickUp"), std::string::npos) << "reason: " << reason;
}
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
// Bảng `compound_actions` nằm trong cây config test. `overwrite = 0` để shell vẫn override được // Bảng `compound_actions` nằm trong cây config test. `overwrite = 0` để shell vẫn override được

View File

@@ -8,6 +8,7 @@ mission_adapters:
mission_sources: mission_sources:
- {name: goal_src, type: GoalSourceAdapter} - {name: goal_src, type: GoalSourceAdapter}
- {name: vda5050_src, type: VDA5050SourceAdapter} - {name: vda5050_src, type: VDA5050SourceAdapter}
- {name: instant_src, type: InstantActionSourceAdapter}
mission_timeout: 0.0 # [s] 0 = tắt mission_timeout: 0.0 # [s] 0 = tắt
clear_queue_on_failure: false # false = chỉ bỏ chặng lỗi, giữ phần còn lại của order clear_queue_on_failure: false # false = chỉ bỏ chặng lỗi, giữ phần còn lại của order
@@ -20,6 +21,11 @@ GoalSourceAdapter:
VDA5050SourceAdapter: VDA5050SourceAdapter:
library_path: libmission_adapters_vda5050_source library_path: libmission_adapters_vda5050_source
# Cùng .so, alias thứ hai. plugin_registry_test khoá đúng điểm này: hai symbol khác nhau trong một
# thư viện phải nạp được thành hai adapter với hai schema khác nhau.
InstantActionSourceAdapter:
library_path: libmission_adapters_vda5050_source
# ── Các case lỗi mà plugin_registry_test cố ý dựng ra ──────────────────────────────────────────── # ── Các case lỗi mà plugin_registry_test cố ý dựng ra ────────────────────────────────────────────
# #
# Mỗi case là một namespace riêng để test gọi loadFromConfig(nh, "<namespace>") mà không phải sinh # Mỗi case là một namespace riêng để test gọi loadFromConfig(nh, "<namespace>") mà không phải sinh
@@ -82,6 +88,18 @@ vda5050_src:
steps: steps:
- {move_to: dock_target, profile: docking, marker: trolley} - {move_to: dock_target, profile: docking, marker: trolley}
# Quay tại chỗ: không tịnh tiến, góc [deg] lấy từ actionParameters['angle_deg'] của order.
rotate:
steps:
- {move: 0.0, profile: rotate, turn_param: angle_deg}
# turn_param gắn vào profile không phải rotate -> configure() phải từ chối lúc boot.
vda5050_bad_turn_param:
compound_actions:
Spin:
steps:
- {move: 1.0, profile: go_straight, turn_param: angle_deg}
# Step có hai từ khoá -> configure() phải từ chối lúc boot. # Step có hai từ khoá -> configure() phải từ chối lúc boot.
vda5050_bad_step: vda5050_bad_step:
compound_actions: compound_actions:
@@ -105,3 +123,18 @@ vda5050_bad_profile:
invalid_name: invalid_name:
steps: steps:
- {move: 0.5, profile: dock} - {move: 0.5, profile: dock}
# ── instant_src ───────────────────────────────────────────────────────────────────────────────────
#
# CỐ Ý không khai `compound_actions` ở đây: adapter phải đọc bảng của `vda5050_src`. Khai bảng thứ
# hai là đúng cái bệnh hai-bản-lệch-nhau mà việc dùng chung sinh ra để tránh.
instant_src:
compound_actions_from: vda5050_src
# Trỏ tới một nguồn không khai bảng nào: hợp lệ, adapter chạy không có compound action nào.
instant_src_no_table:
compound_actions_from: registry_test_empty
# compound_actions_from rỗng -> configure() phải trượt ngay lúc boot.
instant_src_empty_source:
compound_actions_from: ""

View File

@@ -79,19 +79,70 @@ protected:
// ── Đường nạp bình thường ──────────────────────────────────────────────────────────────────────── // ── Đường nạp bình thường ────────────────────────────────────────────────────────────────────────
TEST_F(PluginRegistryTest, LoadsBothSourcesFromConfig) TEST_F(PluginRegistryTest, LoadsEverySourceFromConfig)
{ {
PluginRegistry registry; PluginRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh)) ASSERT_TRUE(registry.loadFromConfig(nh))
<< "could not load the plugin — check PNKX_NAV_CORE_CONFIG_DIR and devel/lib"; << "could not load the plugin — check PNKX_NAV_CORE_CONFIG_DIR and devel/lib";
EXPECT_EQ(registry.size(), 2u); EXPECT_EQ(registry.size(), 3u);
EXPECT_NE(registry.find(schema::kPoseStamped), nullptr); EXPECT_NE(registry.find(schema::kPoseStamped), nullptr);
EXPECT_NE(registry.find(schema::kVda5050Order), nullptr); EXPECT_NE(registry.find(schema::kVda5050Order), nullptr);
EXPECT_NE(registry.find(schema::kInstantAction), nullptr);
EXPECT_EQ(registry.find("does.not.exist"), nullptr); EXPECT_EQ(registry.find("does.not.exist"), nullptr);
} }
TEST_F(PluginRegistryTest, TwoAliasesInOneLibraryLoadAsTwoAdapters)
{
// VDA5050SourceAdapter và InstantActionSourceAdapter là hai BOOST_DLL_ALIAS trong CÙNG một
// libmission_adapters_vda5050_source.so — cố ý, để hai adapter dùng chung một bản bộ nở compound
// action thay vì có hai bản trôi lệch nhau.
//
// Test này khoá chính cơ chế đó: `library_path` giống hệt nhau ở hai entry phải cho ra hai
// adapter riêng biệt với hai schema riêng biệt. Nếu loader gộp theo library thay vì theo symbol,
// một trong hai schema sẽ biến mất và đường vào tương ứng chết lặng.
PluginRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh));
auto* order_adapter = registry.find(schema::kVda5050Order);
auto* instant_adapter = registry.find(schema::kInstantAction);
ASSERT_NE(order_adapter, nullptr);
ASSERT_NE(instant_adapter, nullptr);
EXPECT_NE(order_adapter, instant_adapter) << "hai alias phải là hai instance, không phải một";
EXPECT_EQ(order_adapter->schema(), std::string(schema::kVda5050Order));
EXPECT_EQ(instant_adapter->schema(), std::string(schema::kInstantAction));
}
TEST_F(PluginRegistryTest, TheInstantAdapterLoadedFromDiskExpandsCompoundActions)
{
// Không chỉ nạp được: adapter nạp qua Boost.DLL phải thật sự thấy bảng compound của nguồn order.
// `compound_actions_from` được đọc trong configure(), và configure() chạy bên trong
// loadFromConfig() — nên đây là chỗ duy nhất kiểm được cả chuỗi nạp + cấu hình + dùng chung bảng.
PluginRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh));
auto* adapter = registry.find(schema::kInstantAction);
ASSERT_NE(adapter, nullptr);
robot_protocol_msgs::Action action;
action.actionType = "UnDockFromStation";
action.actionId = "undock_1";
action.blockingType = "HARD";
const auto request = MissionRequest::fromInstantAction(action);
std::string reason;
ASSERT_TRUE(adapter->validate(request, reason)) << reason;
const auto result = adapter->convert(request);
ASSERT_EQ(result.missions.size(), 1u);
EXPECT_EQ(result.missions.front()->motion_hint, "go_straight")
<< "nở được nghĩa là bảng compound của vda5050_src đã tới được adapter này";
EXPECT_DOUBLE_EQ(result.missions.front()->relative_distance, -1.0);
}
TEST_F(PluginRegistryTest, LoadedAdapterConvertsRealPayload) TEST_F(PluginRegistryTest, LoadedAdapterConvertsRealPayload)
{ {
PluginRegistry registry; PluginRegistry registry;