This commit is contained in:
2026-08-10 21:50:42 +07:00
parent 65f8c7ce1c
commit a2a2ea2829
12 changed files with 713 additions and 74 deletions

View File

@@ -37,7 +37,7 @@ trước, sửa test, rồi mới sửa code.
```
host / mission layer
│ moveTo / dockTo / moveStraightTo / rotateTo
│ moveTo(goal) / moveTo(order) / executeInstantActions
▼
NavigationServer::submit() quy về một NavigationRequest
│ từ chối ngay tại cửa nếu goal hỏng hoặc không nạp được planner
@@ -84,14 +84,35 @@ và mission layer (`mission_adapters`) được dựng trong `NavigationRuntime`
thành từng chặng thay vì dồn thành một goal. Phần còn thiếu được liệt kê ở cuối
`docs/ARCHITECTURE.md`.
### Order VDA5050 đi đường nào
### Ba đường vào, tất cả qua mission layer
`NavigationServer::moveTo(Order, …)` thử `MissionLayer::submitOrder()` trước. Layer nhận thì order đi
qua `mission_adapters`: cắt chặng tại mỗi node có action, chỉ chạy phần `released`, `orderUpdateId`
nối tiếp thay vì chạy lại, `mission_timeout` làm lưới cuối. Layer từ chối (tắt bằng config, hoặc
không nạp được nguồn nào cho schema `vda5050.order`) thì order rơi xuống đường trực tiếp — một
`NavigationRequest` cho cả order, đúng hành vi gen-1.
| Entry point | Schema | Layer từ chối thì |
|---|---|---|
| `moveTo(goal, …)` | `geometry.pose_stamped` | rơi xuống `submit()` trực tiếp — goal đơn vẫn còn nguyên nghĩa |
| `moveTo(order, goal, …)` | `vda5050.order` | rơi xuống đường trực tiếp: một `NavigationRequest` cho cả order, hành vi gen-1 |
| `executeInstantActions(actions)` | `vda5050.instant_action` | **trả false** — không có fallback |
Sáu entry point còn lại (`moveTo(goal)`, `dockTo`, `moveStraightTo`, `rotateTo`) **không** đi qua
mission layer: chúng mang theo sai số hình học và motion profile riêng, mà mission layer không có
chỗ chứa hai thứ đó.
Order đi qua `mission_adapters`: cắt chặng tại mỗi node có action, chỉ chạy phần `released`,
`orderUpdateId` nối tiếp thay vì chạy lại, `mission_timeout` làm lưới cuối.
`executeInstantActions` không có fallback vì một instantAction chỉ có nghĩa **sau khi** được nở theo
bảng `compound_actions`: đẩy thẳng xuống lõi sẽ biến `PickUp` thành một chặng chỉ-action không có
bước dò và không có bước tiến vào — robot báo "đã nâng kệ" khi càng còn chưa tới gần kệ.
### Bốn entry point đã bị gỡ
`dockTo` ×2, `moveStraightTo`, `rotateTo` không còn trong contract host. Chúng submit thẳng vào lõi,
bỏ qua mission layer, nên một goal đến giữa chừng ghi đè chặng đang chạy mà hàng đợi không biết —
`MissionManager` vẫn giao chặng kế của một tuyến robot đã rời khỏi.
Bốn `MotionProfile` giữ nguyên. Docking / go-straight / rotate giờ là thuộc tính **của từng chặng**
trong order: khoá `profile:` (`position | docking | go_straight | rotate`) cộng `marker:` cho
docking, khai trong `config/runtime/compound_actions_params.yaml`.
### instantActions
Một message = một lô. Cả message xuống cùng lúc và **luôn preempt** những gì đang trong hàng đợi;
`blockingType` không còn chọn cách vào hàng đợi. Chi tiết và lý do: `docs/ARCHITECTURE.md`, cùng
doc của `mission_plugins::InstantActionSourceAdapter`.
Payload mẫu để thử tay: `Controllers/Packages/amr_comunication/scripts/samples/`.

View File

@@ -122,7 +122,15 @@ actions:
#
# ► Chỉnh: mỗi lần thêm một step `{action: X}` vào compound_actions_params.yaml thì PHẢI thêm X
# vào đây (hoặc vào handler thật tương ứng).
action_types: [LiftFork, startCharging, DropDown, Drop, MutedOn, MutedOff, pick, drop]
#
# ⚠ `Load` và `UnLoad` nằm ở đây vì instantAction giờ đi qua ActionRunner thay vì chạy IO trong
# host. Bản host cũ (`VDA5050ClientAPI::load` / `::unLoad`) có logic thiết bị THẬT — đếm
# count_ok/count_ng, bắt tay IO — mà stub này không có. Trên robot thật đây là hai action nguy
# hiểm nhất trong danh sách: robot báo "đã nhận hàng" mà không có gì trên xe.
# Phải thay bằng handler thật trước khi chạy hiện trường; xem TODO(port) trong
# amr_vda_5050_client_api.cpp.
action_types: [LiftFork, startCharging, DropDown, Drop, MutedOn, MutedOff, pick, drop,
Load, UnLoad]
# [s] Thời gian giả lập thiết bị làm việc.
# ► Chỉnh: đặt ~= thời gian thật của thiết bị để timing trên sim giống hiện trường.

View File

@@ -65,6 +65,31 @@ vda5050_src:
# ► Chỉnh: [m] âm = lùi. Đặt đủ dài để càng nâng ra hẳn khỏi khe kệ trước khi robot xoay;
# quá ngắn thì kệ quệt vào giá, quá dài thì tốn thời gian và có thể lùi vào lối đi chung.
- {move: -0.5, profile: go_straight}
dockTo:
steps:
- {action: DetectPallet}
- {move_to: dock_target, profile: docking, marker: trolley}
- {action: LiftFork}
# Lùi ra khỏi khe kệ. Quãng đường tương đối được quy ra pose tuyệt đối tại `submit`, từ pose
# LÚC ĐÓ — lúc adapter sinh chặng thì robot còn chưa tới nơi.
# ► Chỉnh: [m] âm = lùi. Đặt đủ dài để càng nâng ra hẳn khỏi khe kệ trước khi robot xoay;
# quá ngắn thì kệ quệt vào giá, quá dài thì tốn thời gian và có thể lùi vào lối đi chung.
- {move: -0.5, profile: go_straight}
# --- UnDockFromStation: lùi ra khỏi trạm --------------------------------------------------------
# Trước đây action này chạy phía host bằng `moveStraightTo`, một entry point đã bị gỡ vì nó đẩy
# goal thẳng vào lõi và cướp được chặng mà mission layer đang chạy. Ở đây nó là một chặng bình
# thường: cùng mission id, cùng lifecycle, cùng đường cancel.
#
# ⚠ Khác biệt so với bản host cũ: quãng lùi giờ là HẰNG SỐ CỦA CẤU HÌNH, không còn lấy từ
# `actionParameters.distance` của từng order — step `move:` chỉ nhận số, không có biến thể đọc
# param. Trạm nào cần quãng lùi khác thì phải khai một compound action riêng.
UnDockFromStation:
steps:
# ► Chỉnh: [m] âm = lùi. Đủ dài để robot ra hẳn khỏi trạm trước khi được phép xoay. Profile
# `go_straight` KHÔNG tránh vật cản — chỉ đúng khi phía sau trạm là vùng đã biết là trống.
- {move: -1.0, profile: go_straight}
# --- GoStraight / Rotate: hai lệnh chuyển động trần, dùng để kiểm thử và cho quy trình đơn giản
GoStraight:

View File

@@ -21,13 +21,19 @@ mission_adapters:
#
# goal_src : goal trần từ host (không có edge) — dùng khi test bằng RViz/sim.
# vda5050_src : Order VDA5050 đầy đủ (node + edge + action), đường chạy production.
# instant_src : một action lẻ ngoài order (VDA5050 `instantActions`).
#
# ► Chỉnh: bỏ bớt một nguồn = tắt đường vào tương ứng. Bỏ HẾT thì runtime tự quay về đường trực
# tiếp (như `mission_layer_enabled: false`) kèm log cảnh báo — thiếu plugin không được phép biến
# thành robot đứng im không rõ lý do.
#
# ⚠ Bỏ `instant_src` KHÔNG quay về hành vi cũ: `executeInstantAction` sẽ trả false và mọi
# instantAction (trừ cancelOrder/startPause/stopPause) bị báo FAILED `actionNotSupported`.
# Đường host tự chạy IO cho `PickUp`/`Load`/... đã bị gỡ, không còn chỗ nào nhận thay.
mission_sources:
- {name: goal_src, type: GoalSourceAdapter}
- {name: vda5050_src, type: VDA5050SourceAdapter}
- {name: instant_src, type: InstantActionSourceAdapter}
# [s] Trần thời gian cho MỘT chặng (navigation + action), tính từ lúc chặng được giao.
# 0 = tắt. Quá hạn thì chặng bị đánh dấu thất bại VÀ navigation được bảo dừng — lưới cuối cho
@@ -66,6 +72,21 @@ vda5050_src:
# `vda5050_src` và được `robot::NodeHandle` GỘP vào chung một cây. Tách file vì file này là
# symlink sang submodule `pnkx_nav_core`.
# --- instant_src: một action lẻ ngoài order (VDA5050 `instantActions`) ---------------------------
instant_src:
# Namespace của nguồn khác để DÙNG CHUNG bảng `compound_actions` của nó.
#
# Đây là lý do adapter này tồn tại như một class con thay vì một plugin riêng: `charge` gửi dạng
# node action và `charge` gửi dạng instantAction phải nở ra CÙNG một chuỗi chặng. Khai một bảng
# thứ hai dưới khoá `instant_src` sẽ chạy được ngay hôm nay rồi trôi lệch dần — và triệu chứng là
# robot lùi vào trạm bằng toạ độ cũ vì một trong hai bảng thiếu bước dò.
#
# ► Chỉnh: gần như không bao giờ. Chỉ đổi khi thật sự cần hai bộ quy trình khác nhau cho cùng một
# actionType — và lúc đó phải cân nhắc lại vì fleet chỉ gửi một tên.
# Giá trị mặc định (khi không khai khoá này) cũng là `vda5050_src`; khai rõ ở đây để người đọc
# config thấy được sự phụ thuộc thay vì phải đọc code mới biết.
compound_actions_from: vda5050_src
# Bảng symbol -> thư viện cho Boost.DLL. KHÔNG phải tham số tinh chỉnh.
#
# Thiếu khoá library_path là nguyên nhân phổ biến nhất của lỗi "plugin build xong nhưng runtime báo
@@ -76,3 +97,8 @@ GoalSourceAdapter:
VDA5050SourceAdapter:
library_path: libmission_adapters_vda5050_source
# Cùng .so với VDA5050SourceAdapter, alias thứ hai. Không phải nhầm: hai adapter dùng chung bộ nở
# compound action nên chúng phải ở chung một đơn vị biên dịch, tránh hai bản logic trôi lệch nhau.
InstantActionSourceAdapter:
library_path: libmission_adapters_vda5050_source

View File

@@ -79,13 +79,38 @@ Bảy port đều nhỏ và đều tồn tại vì một lý do vận hành cụ
## Quyết định thiết kế đáng ghi lại
**Sáu entry point gộp về một contract lõi.** `moveTo` ×2, `dockTo` ×2, `moveStraightTo`, `rotateTo`
của contract host chỉ khác nhau ở kiểu chuyển động. `moveTo(PoseStamped)` là direct **position**
goal nên trước tiên đi `MissionLayer::submitGoal()` → `GoalSourceAdapter` → `MissionManager`; nhờ đó
nó nhận mission ID và lifecycle/cancel giống VDA5050. Nếu mission layer bị tắt hoặc không nạp source
này mới fallback tương thích về `NavigationRequest` trực tiếp. Các API mang profile/marker riêng
(`dockTo`, `moveStraightTo`, `rotateTo`) dựng request trực tiếp, vì schema `geometry.pose_stamped`
chưa biểu diễn được marker/profile của chúng.
**Mọi entry point gộp về một contract lõi, và tất cả đi qua mission layer.** Contract host còn ba
đường vào công việc:
| Entry point | Schema | Nguồn | Layer từ chối thì |
|---|---|---|---|
| `moveTo(PoseStamped, …)` | `geometry.pose_stamped` | `GoalSourceAdapter` | fallback về `NavigationRequest` trực tiếp |
| `moveTo(Order, …)` | `vda5050.order` | `VDA5050SourceAdapter` | fallback: một request cho cả order |
| `executeInstantActions(vector<Action>)` | `vda5050.instant_action` | `InstantActionSourceAdapter` | **trả false**, không fallback |
Nhờ đi qua layer, cả ba nhận mission ID và lifecycle/cancel giống nhau.
`executeInstantActions` cố ý **không có fallback**. Hai đường kia fallback được vì payload của chúng
vẫn còn nguyên nghĩa khi bỏ qua layer — một pose vẫn là một pose. Một instantAction thì không: nghĩa
của nó nằm ở bảng `compound_actions`, nên đẩy thẳng xuống lõi biến `PickUp` thành một chặng
chỉ-action không có bước dò và không có bước tiến vào — robot báo "đã nâng kệ" khi càng chưa tới gần
kệ.
**Bốn entry point mang profile riêng đã bị gỡ.** `dockTo` ×2, `moveStraightTo`, `rotateTo` từng dựng
`NavigationRequest` thẳng, vì schema `geometry.pose_stamped` không biểu diễn được marker/profile của
chúng. Đó chính là lỗ: `ControlLoop::submit()` không có guard "mission đang chạy", nên một goal đến
giữa chừng ghi đè `pending_request_` và hàng đợi vẫn giao chặng kế của tuyến robot đã rời khỏi.
Bốn `MotionProfile` giữ nguyên. Marker và profile giờ là thuộc tính **của từng chặng** trong order
(`profile:`, `marker:` trong `compound_actions_params.yaml`) — tức chúng đi trong payload của
`vda5050.order` và `vda5050.instant_action`, hai schema có chỗ chứa chúng.
**instantActions: một message là một lô, và luôn preempt.** Cả message xuống cùng lúc, nở theo đúng
thứ tự fleet gửi, nối thành một `ConversionResult`. Đẩy từng action riêng lẻ thì action `HARD` thứ
hai preempt và xoá sạch chặng của action thứ nhất trong cùng message. `blockingType` **không** chọn
cách vào hàng đợi: message mới luôn thay message cũ, vì 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ả: một instantAction đến giữa lúc order
đang chạy sẽ huỷ order đó — `MissionLayer::submitInstantActions` cảnh báo khi điều đó xảy ra.
**Một đường vào duy nhất.** `ControlLoop::submit()` là chỗ duy nhất một goal lọt được vào lõi, và
`IDLE → PLANNING` là transition duy nhất bắt đầu một chặng. Nhờ đó việc chống hai nguồn goal tranh

View File

@@ -117,11 +117,31 @@ public:
*
* @note Đây là đường chuẩn của `NavigationServer::moveTo(PoseStamped)`: RViz, OPC-UA hay nguồn
* host nào gửi direct position goal đều phải đi qua `GoalSourceAdapter` để nhận cùng
* mission id/lifecycle với VDA5050. Các entry point mang profile riêng (`dockTo`,
* `moveStraightTo`, `rotateTo`) vẫn đi thẳng vì schema pose hiện không mang marker/profile.
* mission id/lifecycle với VDA5050.
*
* @note Schema pose chỉ mang pose, nên goal đi đường này luôn là profile `position`. Các entry
* point mang profile riêng (`dockTo` ×2, `moveStraightTo`, `rotateTo`) từng đi thẳng vòng
* qua layer này và đã bị gỡ khỏi contract host vì đúng lý do đó. Docking/go-straight/rotate
* giờ tới bằng `profile:` của từng chặng trong order — tức qua @ref submitOrder.
*/
bool submitGoal(const robot_geometry_msgs::PoseStamped& goal);
/**
* @brief Đẩy MỘT message `instantActions` (0..n action) vào mission layer.
* @return false nếu layer chưa chạy hoặc không có nguồn nào nhận schema `vda5050.instant_action`.
*
* Cùng hợp đồng với @ref submitOrder: true chỉ nghĩa là "đã nhận vào hàng đợi sự kiện". Action
* hỏng bị adapter từ chối sau đó trên thread sự kiện, hàng đợi đang chạy không bị đụng.
*
* @note Hàm này cảnh báo khi action tới lúc hàng đợi còn việc. Fleet master hiện tại chỉ gửi
* instantAction khi robot rảnh, và cả cách báo trạng thái action ngược lên fleet đang dựa
* vào giả định đó (host suy `actionStatus` từ `NavigationState`, mà state là của CẢ hàng
* đợi chứ không của riêng action). VDA5050 thì **cho phép** gửi giữa order — spec còn nêu
* pause/resume làm ví dụ. Nên đây là giả định vận hành, không phải bảo đảm giao thức: ngày
* nó vỡ, dòng log này là thứ chỉ thẳng ra vì sao trạng thái báo về sai.
*/
bool submitInstantActions(const std::vector<robot_protocol_msgs::Action>& actions);
/// @brief Huỷ chặng đang chạy và xoá sạch hàng đợi.
void cancel();

View File

@@ -26,9 +26,12 @@ namespace move_base2
* @enum MotionProfile
* @brief Kiểu chuyển động của một yêu cầu.
*
* Profile quyết định local planner nào được nạp và global planner nào được swap. Nó là thứ duy nhất
* thực sự khác nhau giữa sáu entry point của contract host cũ (moveTo ×2, dockTo ×2, moveStraightTo,
* rotateTo) — phần còn lại của sáu hàm đó giống hệt nhau.
* Profile quyết định local planner nào được nạp và global planner nào được swap.
*
* Contract host cũ có sáu entry point (`moveTo` ×2, `dockTo` ×2, `moveStraightTo`, `rotateTo`) mà
* khác nhau đúng ở chỗ này — phần còn lại giống hệt. Bốn cái mang profile riêng đã bị gỡ vì chúng
* submit thẳng vào lõi, bỏ qua mission layer. Enum thì giữ nguyên: profile giờ tới từ khoá
* `profile:` của từng chặng trong order (`position | docking | go_straight | rotate`).
*/
enum class MotionProfile
{

View File

@@ -195,14 +195,13 @@ public:
double yaw_goal_tolerance) override;
bool moveTo(const robot_protocol_msgs::Order& msg, const robot_geometry_msgs::PoseStamped& goal,
double xy_goal_tolerance, double yaw_goal_tolerance) override;
bool dockTo(const std::string& maker, const robot_geometry_msgs::PoseStamped& goal,
double xy_goal_tolerance, double yaw_goal_tolerance) override;
bool dockTo(const robot_protocol_msgs::Order& msg, const std::string& marker,
const robot_geometry_msgs::PoseStamped& goal, double xy_goal_tolerance,
double yaw_goal_tolerance) override;
bool moveStraightTo(const robot_geometry_msgs::PoseStamped& goal,
double xy_goal_tolerance) override;
bool rotateTo(const robot_geometry_msgs::PoseStamped& goal, double yaw_goal_tolerance) override;
// `dockTo`/`moveStraightTo`/`rotateTo` không còn: chúng submit thẳng vào lõi, bỏ qua mission
// layer, nên một goal đến giữa chừng ghi đè chặng đang chạy mà hàng đợi không biết. Bốn profile
// vẫn còn nguyên (@ref MotionProfile) và tới được qua `profile:`/`marker` của từng chặng trong
// order, tức cùng đường với mọi chặng khác — cùng mission id, cùng lifecycle, cùng cancel.
bool executeInstantActions(const std::vector<robot_protocol_msgs::Action>& actions) override;
void pause() override;
void resume() override;

View File

@@ -127,6 +127,42 @@ bool MissionLayer::submitGoal(const robot_geometry_msgs::PoseStamped& goal)
return true;
}
bool MissionLayer::submitInstantActions(const std::vector<robot_protocol_msgs::Action>& actions)
{
if (!started_ || !handles(mission_adapters::schema::kInstantAction))
{
return false;
}
if (actions.empty())
{
// Message rỗng không phải lệnh huỷ và cũng không phải lỗi hệ thống — nhưng nhận nó thì host sẽ
// ngồi chờ một kết quả không bao giờ tới, mà fleet lại đang chặn mọi lệnh khác để đợi.
robot::log_warning("[move_base2] MissionLayer: instantActions message carries no action.");
return false;
}
// Message instantActions LUÔN preempt, nên dòng này không phải "có thể có vấn đề" mà là "việc
// đang chạy SẼ bị huỷ". Với chuỗi instantActions trước đó thì đúng ý định. Với một order đang
// chạy thì đó là mất cả tuyến đường — fleet master hiện tại không gửi trong tình huống đó, và đây
// là dòng duy nhất chỉ ra ngày giả định ấy bị vi phạm.
//
// Throttle vì nếu giả định vỡ thì nó vỡ đều, và một dòng mỗi lần trong control loop sẽ nhấn chìm
// log.
if (manager_.hasMission())
{
robot::log_warning_throttle(5.0,
"[move_base2] MissionLayer: instantActions message (%zu action(s), "
"first '%s' id '%s') preempts the work already in the queue — if "
"that was a running order, the order is now cancelled",
actions.size(), actions.front().actionType.c_str(),
actions.front().actionId.c_str());
}
events_.instantActionsEvent(actions);
return true;
}
void MissionLayer::cancel()
{
if (started_)

View File

@@ -10,6 +10,7 @@
#include <cmath>
#include <mission_adapters/mission_request.h>
#include <robot_nav_2d_utils/conversions.h>
namespace move_base2
@@ -746,7 +747,11 @@ bool NavigationServer::removeAllData()
}
// ================================================================================================
// Sáu entry point di chuyển -> một NavigationRequest
// Hai entry point di chuyển -> một NavigationRequest
//
// Bốn entry point mang profile riêng (`dockTo` ×2, `moveStraightTo`, `rotateTo`) đã bị gỡ khỏi
// contract host: chúng submit thẳng vào lõi, bỏ qua mission layer. Docking/go-straight/rotate giờ
// đi qua `profile:` và `marker` của từng chặng trong order — xem MissionAdapterBridge::toProfile.
// ================================================================================================
bool NavigationServer::submit(const NavigationRequest& request)
@@ -814,51 +819,28 @@ bool NavigationServer::moveTo(const robot_protocol_msgs::Order& msg,
return submit(request);
}
bool NavigationServer::dockTo(const std::string& maker,
const robot_geometry_msgs::PoseStamped& goal,
double xy_goal_tolerance, double yaw_goal_tolerance)
bool NavigationServer::executeInstantActions(
const std::vector<robot_protocol_msgs::Action>& actions)
{
(void)xy_goal_tolerance;
(void)yaw_goal_tolerance;
NavigationRequest request;
request.profile = MotionProfile::kDocking;
request.goal = goal;
request.marker = maker;
return submit(request);
}
// KHÔNG có đường rơi xuống `submit()` như `moveTo`. Một instantAction chỉ có nghĩa khi mission
// layer nở nó theo bảng compound: đẩy thẳng xuống lõi sẽ biến `PickUp` thành một chặng chỉ-action
// không có bước dò và không có bước tiến vào, tức robot báo "đã nâng kệ" khi càng còn chưa tới
// gần kệ. Layer tắt thì phải từ chối để host báo FAILED ngay, thay vì chờ một kết quả không đến.
if (runtime_ == nullptr || !runtime_->missionLayer().submitInstantActions(actions))
{
const std::string first = actions.empty() ? std::string("<empty>") : actions.front().actionType;
bool NavigationServer::dockTo(const robot_protocol_msgs::Order& msg, const std::string& marker,
const robot_geometry_msgs::PoseStamped& goal,
double xy_goal_tolerance, double yaw_goal_tolerance)
{
(void)xy_goal_tolerance;
(void)yaw_goal_tolerance;
NavigationRequest request;
request.profile = MotionProfile::kDocking;
request.goal = goal;
request.marker = marker;
request.order = std::make_shared<robot_protocol_msgs::Order>(msg);
return submit(request);
}
last_reject_reason_ = "mission layer cannot accept instant actions";
nav_feedback_->feed_back_str =
"instant action '" + first + "' rejected: " + last_reject_reason_;
robot::log_error("[move_base2] instantActions message rejected (%zu action(s), first '%s') — "
"mission layer not running, empty message, or no source declares schema '%s'.",
actions.size(), first.c_str(), mission_adapters::schema::kInstantAction);
return false;
}
bool NavigationServer::moveStraightTo(const robot_geometry_msgs::PoseStamped& goal,
double xy_goal_tolerance)
{
(void)xy_goal_tolerance;
NavigationRequest request;
request.profile = MotionProfile::kGoStraight;
request.goal = goal;
return submit(request);
}
bool NavigationServer::rotateTo(const robot_geometry_msgs::PoseStamped& goal,
double yaw_goal_tolerance)
{
(void)yaw_goal_tolerance;
NavigationRequest request;
request.profile = MotionProfile::kRotate;
request.goal = goal;
return submit(request);
last_reject_reason_.clear();
return true;
}
// ================================================================================================

View File

@@ -359,6 +359,386 @@ TEST(MissionLayerTest, AppendModeDoesNotPreemptTheRunningLeg)
EXPECT_NE(running_id, fixture.received_.back().mission_sequence_id);
}
// ================================================================================================
// instantAction — đường vào thứ ba
//
// Thứ phải khoá: instantAction đi ĐÚNG cùng một hàng đợi với order. Nếu nó tìm được đường tắt nào
// xuống lõi thì mọi thứ lớp này bảo đảm — một mission id, một vòng đời, một đường cancel — mất
// hiệu lực đúng vào lúc fleet gửi lệnh khẩn.
// ================================================================================================
namespace
{
/// @brief Nguồn instantAction giả: nở một action thành @c legs chặng, giống compound action thật.
class FakeInstantAdapter : public MissionSourceAdapter
{
public:
explicit FakeInstantAdapter(std::size_t legs, SubmitMode mode = SubmitMode::kReplace)
: legs_(legs), mode_(mode)
{
}
bool configure(const std::string&, robot::NodeHandle&) override
{
return true;
}
std::string schema() const override
{
return mission_adapters::schema::kInstantAction;
}
bool validate(const MissionRequest& request, std::string& reason) const override
{
if (!request.actions || request.actions->empty())
{
reason = "request carries no action";
return false;
}
return true;
}
ConversionResult convert(const MissionRequest& request) override
{
ConversionResult result;
result.mode = mode_;
// Mỗi action nở thành `legs_` chặng, nối tiếp nhau theo đúng thứ tự fleet gửi — cùng hình dạng
// với compound action thật.
for (const robot_protocol_msgs::Action& action : *request.actions)
{
for (std::size_t i = 0; i < legs_; ++i)
{
auto mission = std::make_shared<Mission>();
mission->has_goal = false;
mission_adapters::Action carried;
carried.action = action;
// Đánh số để test phân biệt được chặng nào của chuỗi đang chạy.
carried.action.actionId = action.actionId + "-" + std::to_string(i);
mission->actions.push_back(carried);
result.missions.push_back(mission);
}
}
return result;
}
private:
std::size_t legs_;
SubmitMode mode_;
};
robot_protocol_msgs::Action makeInstantAction(const std::string& type = "PickUp")
{
robot_protocol_msgs::Action action;
action.actionType = type;
action.actionId = type + "_1";
action.blockingType = "HARD";
return action;
}
/// @brief Layer chỉ có nguồn instantAction, cộng chỗ nhận yêu cầu như control thread thật.
class InstantFixture
{
public:
explicit InstantFixture(std::size_t legs, SubmitMode mode = SubmitMode::kReplace)
{
EXPECT_TRUE(layer_.registry().registerAdapter(std::make_shared<FakeInstantAdapter>(legs, mode)));
layer_.markActiveForTesting();
layer_.attach(bridge_);
bridge_.setRequestCallback([this](const NavigationRequest& request) {
received_.push_back(request);
});
bridge_.setCancelCallback([this]() { ++cancel_calls_; });
bridge_.start();
layer_.start();
}
~InstantFixture()
{
layer_.stop();
bridge_.stop();
}
bool pumpUntilRequest()
{
const auto deadline = std::chrono::steady_clock::now() + kTimeout;
while (std::chrono::steady_clock::now() < deadline)
{
if (bridge_.pumpPendingRequest())
{
return true;
}
std::this_thread::sleep_for(kPollStep);
}
return false;
}
void finishLastLeg(NavigationOutcome outcome)
{
ASSERT_FALSE(received_.empty());
bridge_.reportOutcome(received_.back().mission_sequence_id, outcome);
}
bool waitForStateOnLayer(MissionState expected)
{
const auto deadline = std::chrono::steady_clock::now() + kTimeout;
while (std::chrono::steady_clock::now() < deadline)
{
if (layer_.state() == expected)
{
return true;
}
std::this_thread::sleep_for(kPollStep);
}
return false;
}
MissionLayer layer_;
MissionAdapterBridge bridge_;
std::vector<NavigationRequest> received_;
int cancel_calls_ = 0;
};
} // namespace
TEST(MissionLayerInstantAction, RejectsWhenNoSourceDeclaresTheSchema)
{
// Fixture thường chỉ có nguồn pose. Layer phải TỪ CHỐI, để `executeInstantAction` báo false và
// host báo FAILED ngay — nuốt rồi im lặng là fleet chờ tới hết giờ vì nó đang chặn mọi lệnh khác.
Fixture fixture(1);
EXPECT_FALSE(fixture.layer_.handles(mission_adapters::schema::kInstantAction));
EXPECT_FALSE(fixture.layer_.submitInstantActions({makeInstantAction()}));
}
TEST(MissionLayerInstantAction, RejectsBeforeStartAndAfterStop)
{
MissionLayer layer;
MissionAdapterBridge bridge;
ASSERT_TRUE(layer.registry().registerAdapter(std::make_shared<FakeInstantAdapter>(1)));
layer.markActiveForTesting();
layer.attach(bridge);
EXPECT_FALSE(layer.submitInstantActions({makeInstantAction()}));
bridge.start();
layer.start();
EXPECT_TRUE(layer.submitInstantActions({makeInstantAction()}));
layer.stop();
bridge.stop();
EXPECT_FALSE(layer.submitInstantActions({makeInstantAction()}));
}
TEST(MissionLayerInstantAction, AnExpandedActionReachesNavigationOneLegAtATime)
{
// `PickUp` nở thành ba chặng. Chúng phải đi tuần tự qua đúng hàng đợi của order, chứ không được
// bắn một lượt xuống lõi.
InstantFixture fixture(3);
ASSERT_TRUE(fixture.layer_.submitInstantActions({makeInstantAction()}));
ASSERT_TRUE(fixture.pumpUntilRequest());
ASSERT_EQ(1u, fixture.received_.size());
ASSERT_EQ(1u, fixture.received_[0].actions.size());
EXPECT_EQ("PickUp_1-0", fixture.received_[0].actions[0].actionId);
EXPECT_FALSE(fixture.received_[0].has_goal) << "chặng chỉ-action không có quãng đường nào";
EXPECT_NE(0u, fixture.received_[0].mission_sequence_id) << "phải có mission id như mọi chặng khác";
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
ASSERT_EQ(2u, fixture.received_.size());
EXPECT_EQ("PickUp_1-1", fixture.received_[1].actions.at(0).actionId);
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
ASSERT_EQ(3u, fixture.received_.size());
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
EXPECT_TRUE(fixture.waitForStateOnLayer(MissionState::COMPLETED));
}
TEST(MissionLayerInstantAction, TheQueueStaysPendingUntilTheLastLegOfTheChain)
{
// Đây là thứ gánh cả cách báo trạng thái về fleet: host suy `actionStatus` từ `NavigationState`,
// mà `refreshFeedback` che SUCCEEDED giữa các chặng thành ACTIVE chừng nào hàng đợi còn việc.
// Nếu hàng đợi báo cạn sớm ở chặng đầu, fleet nhận FINISHED khi càng nâng chưa nhúc nhích.
InstantFixture fixture(3);
ASSERT_TRUE(fixture.layer_.submitInstantActions({makeInstantAction()}));
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_TRUE(fixture.layer_.hasMission());
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_TRUE(fixture.layer_.hasMission()) << "mới xong chặng 1/3 — chưa được coi là xong";
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_TRUE(fixture.layer_.hasMission());
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
EXPECT_TRUE(fixture.waitForStateOnLayer(MissionState::COMPLETED));
EXPECT_FALSE(fixture.layer_.hasMission()) << "chỉ tới đây fleet mới được nghe FINISHED";
}
TEST(MissionLayerInstantAction, AFailedLegDropsTheRestOfTheChain)
{
// `clear_queue_on_failure`: dò hỏng thì KHÔNG được chạy tiếp bước nâng càng.
InstantFixture fixture(3);
ASSERT_TRUE(fixture.layer_.submitInstantActions({makeInstantAction()}));
ASSERT_TRUE(fixture.pumpUntilRequest());
fixture.finishLastLeg(NavigationOutcome::kFailed);
EXPECT_TRUE(fixture.waitForStateOnLayer(MissionState::FAILED));
EXPECT_FALSE(fixture.pumpUntilRequest()) << "không được giao chặng nào nữa sau khi chặng đầu hỏng";
EXPECT_EQ(1u, fixture.received_.size());
}
TEST(MissionLayerInstantAction, HardBlockingPreemptsTheRunningLeg)
{
// `blockingType: HARD` -> kReplace. Chặng đang chạy phải bị bảo dừng, không chỉ bị quên đi.
InstantFixture fixture(1, SubmitMode::kReplace);
ASSERT_TRUE(fixture.layer_.submitInstantActions({makeInstantAction("first")}));
ASSERT_TRUE(fixture.pumpUntilRequest());
const auto running_id = fixture.received_.back().mission_sequence_id;
ASSERT_TRUE(fixture.layer_.submitInstantActions({makeInstantAction("second")}));
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_NE(running_id, fixture.received_.back().mission_sequence_id);
EXPECT_GT(fixture.cancel_calls_, 0) << "preempt phải DỪNG chặng cũ, không chỉ bỏ nó khỏi hàng đợi";
}
TEST(MissionLayerInstantAction, ANewMessageClearsTheLegsOfThePreviousOne)
{
// Fleet gửi message tiếp theo khi message trước còn đang chạy. Chuỗi cũ phải bị XOÁ, không phải
// xếp message mới sau nó: lệnh "instant" mà chạy sau vài chục giây thì không còn là instant, và
// chuỗi cũ vẫn kịp thao tác thiết bị dù đã bị lệnh mới thay thế.
InstantFixture fixture(3, SubmitMode::kReplace);
ASSERT_TRUE(fixture.layer_.submitInstantActions({ makeInstantAction("old") }));
ASSERT_TRUE(fixture.pumpUntilRequest());
const auto old_id = fixture.received_.back().mission_sequence_id;
EXPECT_EQ("old_1-0", fixture.received_.back().actions.at(0).actionId);
// Message mới tới khi chuỗi cũ mới chạy được 1/3 chặng.
ASSERT_TRUE(fixture.layer_.submitInstantActions({ makeInstantAction("new") }));
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_EQ("new_1-0", fixture.received_.back().actions.at(0).actionId)
<< "chặng kế tiếp phải thuộc message MỚI, không phải chặng 2/3 của message cũ";
EXPECT_NE(old_id, fixture.received_.back().mission_sequence_id);
EXPECT_GT(fixture.cancel_calls_, 0)
<< "chặng cũ phải được BẢO DỪNG, không chỉ bị quên khỏi hàng đợi";
}
TEST(MissionLayerInstantAction, TheRemainingLegsOfTheOldMessageNeverRun)
{
// Không chỉ chặng đang chạy: hai chặng CÒN LẠI của message cũ cũng phải biến mất. Nếu chúng còn
// trong hàng đợi, robot sẽ chạy nốt bước nâng càng của một lệnh đã bị thay thế.
InstantFixture fixture(3, SubmitMode::kReplace);
ASSERT_TRUE(fixture.layer_.submitInstantActions({ makeInstantAction("old") }));
ASSERT_TRUE(fixture.pumpUntilRequest());
ASSERT_TRUE(fixture.layer_.submitInstantActions({ makeInstantAction("new") }));
ASSERT_TRUE(fixture.pumpUntilRequest());
// Message mới có 3 chặng: chạy hết chúng rồi hàng đợi phải cạn hẳn.
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
EXPECT_TRUE(fixture.waitForStateOnLayer(MissionState::COMPLETED));
EXPECT_FALSE(fixture.layer_.hasMission());
for (const auto& request : fixture.received_)
{
if (&request == &fixture.received_.front())
continue; // chặng 1/3 của message cũ đã chạy trước khi bị thay — hợp lệ
EXPECT_EQ(request.actions.at(0).actionId.rfind("new_1-", 0), 0u)
<< "chặng của message cũ vẫn được giao sau khi nó đã bị thay thế: "
<< request.actions.at(0).actionId;
}
}
TEST(MissionLayerInstantAction, AMultiActionMessageQueuesAsOneBatch)
{
// Ba action, mỗi cái nở một chặng. Chúng phải nằm CÙNG một lô trong hàng đợi và chạy tuần tự —
// không cái nào preempt cái nào. Đây đúng là ca mà bản gửi-từng-cái làm hỏng.
InstantFixture fixture(1);
ASSERT_TRUE(fixture.layer_.submitInstantActions({ makeInstantAction("MutedOn"),
makeInstantAction("PickUp"),
makeInstantAction("MutedOff") }));
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_EQ("MutedOn_1-0", fixture.received_.at(0).actions.at(0).actionId);
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_EQ("PickUp_1-0", fixture.received_.at(1).actions.at(0).actionId);
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_EQ("MutedOff_1-0", fixture.received_.at(2).actions.at(0).actionId);
EXPECT_EQ(0, fixture.cancel_calls_) << "không action nào được preempt action đứng trước nó";
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
EXPECT_TRUE(fixture.waitForStateOnLayer(MissionState::COMPLETED));
}
TEST(MissionLayerInstantAction, AFailureStopsTheRestOfTheMessage)
{
// Yêu cầu vận hành: action nào fail thì DỪNG luôn và báo fail. Chặng thứ hai của message hỏng thì
// action thứ ba không được chạy — nếu chạy, robot thao tác thiết bị sau một bước đã hỏng.
InstantFixture fixture(1);
ASSERT_TRUE(fixture.layer_.submitInstantActions({ makeInstantAction("first"),
makeInstantAction("second"),
makeInstantAction("third") }));
ASSERT_TRUE(fixture.pumpUntilRequest());
fixture.finishLastLeg(NavigationOutcome::kSucceeded);
ASSERT_TRUE(fixture.pumpUntilRequest());
EXPECT_EQ("second_1-0", fixture.received_.at(1).actions.at(0).actionId);
fixture.finishLastLeg(NavigationOutcome::kFailed);
EXPECT_TRUE(fixture.waitForStateOnLayer(MissionState::FAILED));
EXPECT_FALSE(fixture.pumpUntilRequest()) << "action thứ ba KHÔNG được chạy sau khi action hai hỏng";
EXPECT_EQ(2u, fixture.received_.size());
EXPECT_FALSE(fixture.layer_.hasMission()) << "hàng đợi phải sạch để host báo fail rồi kết thúc";
}
TEST(MissionLayerInstantAction, AnEmptyMessageIsRefused)
{
InstantFixture fixture(1);
EXPECT_FALSE(fixture.layer_.submitInstantActions({}));
}
TEST(MissionLayerInstantAction, CancelDropsAnInstantActionChainToo)
{
// Vòng đời của instantAction phải là vòng đời chung: `cancelOrder` tới giữa chuỗi `PickUp` phải
// dừng được nó. Đây là lý do instantAction bắt buộc đi qua lớp này thay vì xuống thẳng lõi.
InstantFixture fixture(3);
ASSERT_TRUE(fixture.layer_.submitInstantActions({makeInstantAction()}));
ASSERT_TRUE(fixture.pumpUntilRequest());
fixture.layer_.cancel();
EXPECT_TRUE(fixture.waitForStateOnLayer(MissionState::CANCELLED));
EXPECT_GT(fixture.cancel_calls_, 0);
EXPECT_FALSE(fixture.layer_.hasMission());
}
} // namespace
int main(int argc, char** argv)

View File

@@ -939,6 +939,120 @@ TEST(NavigationServerFeedback, NothingIsLatchedBeforeTheFirstRequest)
<< "a freshly booted runtime reports a terminal result although no goal has ever been sent";
}
// ================================================================================================
// executeInstantAction() — cửa duy nhất nhận một action lẻ
//
// Điểm cần khoá: hàm này KHÔNG có đường rơi xuống lõi như `moveTo(goal)` có. Một instantAction chỉ
// có nghĩa sau khi mission layer nở nó theo bảng compound — `PickUp` mà đi thẳng xuống lõi sẽ thành
// một chặng chỉ-action, tức robot báo "đã nâng kệ" trong khi càng còn chưa tới gần kệ.
//
// Fixture ở đây không dựng NavigationRuntime, nên nó mô phỏng đúng cấu hình có mission layer tắt.
// ================================================================================================
namespace
{
robot_protocol_msgs::Action makeInstantAction(const std::string& type = "PickUp")
{
robot_protocol_msgs::Action action;
action.actionType = type;
action.actionId = type + "_1";
action.blockingType = "HARD";
return action;
}
} // namespace
TEST(NavigationServerInstantAction, IsRefusedWhenThereIsNoMissionLayer)
{
Fixture fixture;
fixture.configure();
EXPECT_FALSE(fixture.server_.executeInstantActions({makeInstantAction()}))
<< "nhận rồi không làm gì là fleet chờ tới hết giờ — nó đang chặn mọi lệnh khác để đợi";
}
TEST(NavigationServerInstantAction, AnEmptyMessageIsRefused)
{
// Message rỗng không phải lệnh huỷ. Nhận nó thì host ngồi chờ một kết quả không bao giờ tới.
Fixture fixture;
fixture.configure();
EXPECT_FALSE(fixture.server_.executeInstantActions({}));
}
TEST(NavigationServerInstantAction, AMultiActionMessageGoesDownAsOneCall)
{
// Chữ ký nhận CẢ danh sách chính là thứ ngăn action `HARD` thứ hai preempt chặng của action thứ
// nhất trong cùng message. Test này khoá chữ ký đó lại: biên dịch được với nhiều action là đủ,
// cộng với việc nó vẫn bị từ chối gọn gàng khi không có mission layer.
Fixture fixture;
fixture.configure();
const std::vector<robot_protocol_msgs::Action> message = {
makeInstantAction("MutedOn"), makeInstantAction("PickUp"), makeInstantAction("MutedOff")
};
EXPECT_FALSE(fixture.server_.executeInstantActions(message));
EXPECT_EQ(0u, fixture.action_.startCount());
}
TEST(NavigationServerInstantAction, ARefusalSaysWhichActionAndWhy)
{
Fixture fixture;
fixture.configure();
ASSERT_FALSE(fixture.server_.executeInstantActions({makeInstantAction("charge")}));
// Host chép chuỗi này vào `resultDescription` gửi lên fleet. "rejected" trơ trọi không giúp được
// ai; phải nói được là action NÀO và vì SAO.
const std::string reason = fixture.server_.getFeedback()->feed_back_str;
EXPECT_NE(reason.find("charge"), std::string::npos) << "reason: " << reason;
EXPECT_NE(reason.find("instant action"), std::string::npos) << "reason: " << reason;
}
TEST(NavigationServerInstantAction, ARefusedActionNeverReachesTheCore)
{
// Bất biến quan trọng nhất của hàm này: KHÔNG có nhánh fallback. `moveTo(goal)` có — layer tắt thì
// nó submit thẳng, và đúng như vậy vì một goal đơn vẫn còn nguyên nghĩa. Một instantAction thì
// không: bỏ qua bước nở là bỏ qua bước dò và bước tiến vào.
Fixture fixture;
fixture.configure();
ASSERT_FALSE(fixture.server_.executeInstantActions({makeInstantAction()}));
fixture.spin(10);
EXPECT_EQ(0u, fixture.planner_.makePlanCount()) << "không được lập plan cho một action bị từ chối";
EXPECT_EQ(0u, fixture.action_.startCount()) << "và không được chạy action nào";
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state,
robot::move_base_core::State::PENDING)
<< "lõi phải đứng yên — báo ACTIVE ở đây là fleet tưởng robot đang làm việc";
}
TEST(NavigationServerInstantAction, RefusingDoesNotDisturbAGoalAlreadyRunning)
{
// Từ chối phải là no-op với việc đang chạy. Nếu nó đụng vào `pending_request_` hay cờ cancel thì
// một action lạ do fleet gửi nhầm sẽ dừng cả tuyến đường đang đi.
Fixture fixture;
fixture.configure();
NavigationRequest request;
request.profile = MotionProfile::kPosition;
request.goal.header.frame_id = "map";
request.goal.pose.position.x = 2.0; // [m]
request.goal.pose.orientation.w = 1.0;
ASSERT_TRUE(fixture.server_.moveTo(request.goal, 0.0, 0.0));
fixture.spin(5);
const auto state_before = fixture.server_.getFeedback()->navigation_state;
const std::size_t plans_before = fixture.planner_.makePlanCount();
EXPECT_FALSE(fixture.server_.executeInstantActions({makeInstantAction("NotSupported")}));
fixture.spin(5);
EXPECT_EQ(fixture.server_.getFeedback()->navigation_state, state_before)
<< "một action bị từ chối không được đổi trạng thái của goal đang chạy";
EXPECT_GE(fixture.planner_.makePlanCount(), plans_before);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);