diff --git a/README.md b/README.md index 8f22980..f2e6927 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # 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 -đợi mission, và giữ trạng thái của hàng đợi đó. +Lớp mission độc lập ROS: nhận yêu cầu từ nguồn ngoài (goal đơn lẻ, VDA5050 Order, VDA5050 +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 `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 [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 ```text host (MQTT / OPC-UA / REST / UI) - │ goalEvent / orderEvent / submitRequest(MissionRequest) + │ goalEvent / orderEvent / instantActionsEvent / submitRequest(MissionRequest) ▼ ┌──────────────────┐ tra schema ┌────────────────┐ │ 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 | |---|---|---| | `mission_adapters/mission_sources` | — | Danh sách nguồn mission `{name, type}` | +| `/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/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 | | `/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ó - 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. - Multi-robot fleet. diff --git a/include/mission_adapters/event_processor.h b/include/mission_adapters/event_processor.h index 53f63f5..8e5cecb 100644 --- a/include/mission_adapters/event_processor.h +++ b/include/mission_adapters/event_processor.h @@ -55,6 +55,14 @@ namespace mission_adapters /// @brief Tiện ích cho nguồn VDA5050. 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& actions); + void cancelEvent(); void pauseEvent(); void resumeEvent(); diff --git a/include/mission_adapters/mission_request.h b/include/mission_adapters/mission_request.h index aaf5205..f630a65 100644 --- a/include/mission_adapters/mission_request.h +++ b/include/mission_adapters/mission_request.h @@ -11,8 +11,10 @@ #include #include +#include #include +#include #include namespace mission_adapters @@ -20,8 +22,20 @@ namespace mission_adapters /// @brief Tên schema của các nguồn có sẵn. Nguồn mới tự khai schema riêng, không cần sửa ở đây. namespace schema { - constexpr const char* kVda5050Order = "vda5050.order"; - constexpr const char* kPoseStamped = "geometry.pose_stamped"; + constexpr const char* kVda5050Order = "vda5050.order"; + 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 /** @@ -41,6 +55,8 @@ namespace mission_adapters std::shared_ptr order; std::shared_ptr pose; + /// Danh sách action của MỘT message `instantActions`, giữ nguyên thứ tự fleet gửi. + std::shared_ptr> actions; std::string raw_payload; @@ -62,6 +78,21 @@ namespace mission_adapters 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& actions) + { + MissionRequest request; + request.schema = schema::kInstantAction; + request.actions = std::make_shared>(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. static MissionRequest fromRaw(const std::string& schema_name, const std::string& payload) { diff --git a/plugins/vda5050_source_adapter.cpp b/plugins/vda5050_source_adapter.cpp index 9c3a325..0a0abb5 100644 --- a/plugins/vda5050_source_adapter.cpp +++ b/plugins/vda5050_source_adapter.cpp @@ -572,6 +572,176 @@ ConversionResult VDA5050SourceAdapter::convert(const mission_adapters::MissionRe return result; } +// ═════════════════════════════════════════════════════════════════════════════════════════════════ +// InstantActionSourceAdapter +// ═════════════════════════════════════════════════════════════════════════════════════════════════ + +mission_adapters::MissionSourceAdapter::Ptr InstantActionSourceAdapter::create() +{ + return std::make_shared(); +} + +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(); + 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> 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 BOOST_DLL_ALIAS(mission_plugins::VDA5050SourceAdapter::create, VDA5050SourceAdapter) +BOOST_DLL_ALIAS(mission_plugins::InstantActionSourceAdapter::create, InstantActionSourceAdapter) diff --git a/plugins/vda5050_source_adapter.h b/plugins/vda5050_source_adapter.h index 6f0a8e9..cbecc0f 100644 --- a/plugins/vda5050_source_adapter.h +++ b/plugins/vda5050_source_adapter.h @@ -64,7 +64,11 @@ public: mission_adapters::ConversionResult 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 * @brief Một bước trong chuỗi mở rộng của compound action. @@ -141,6 +145,94 @@ private: 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 ``): + * - `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 #endif // MISSION_ADAPTERS_PLUGINS_VDA5050_SOURCE_ADAPTER_H_ diff --git a/src/event_processor.cpp b/src/event_processor.cpp index d8e9462..a0297ca 100644 --- a/src/event_processor.cpp +++ b/src/event_processor.cpp @@ -158,6 +158,11 @@ namespace mission_adapters submitRequest(MissionRequest::fromPose(goal)); } + void EventProcessor::instantActionsEvent(const std::vector& actions) + { + submitRequest(MissionRequest::fromInstantActions(actions)); + } + void EventProcessor::pauseEvent() { Event event; diff --git a/test/adapter_test.cpp b/test/adapter_test.cpp index cdc817e..50c614d 100644 --- a/test/adapter_test.cpp +++ b/test/adapter_test.cpp @@ -514,6 +514,317 @@ TEST(CompoundConfig, RejectsInvalidOrActionOnlyProfiles) EXPECT_FALSE(adapter.configure("vda5050_bad_profile", nh)); } +// ═════════════════════════════════════════════════════════════════════════════════════════════════ +// 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& 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, 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) { // Bảng `compound_actions` nằm trong cây config test. `overwrite = 0` để shell vẫn override được diff --git a/test/config/mission_adapters_params.yaml b/test/config/mission_adapters_params.yaml index 35c3180..f6c3c29 100644 --- a/test/config/mission_adapters_params.yaml +++ b/test/config/mission_adapters_params.yaml @@ -8,6 +8,7 @@ mission_adapters: mission_sources: - {name: goal_src, type: GoalSourceAdapter} - {name: vda5050_src, type: VDA5050SourceAdapter} + - {name: instant_src, type: InstantActionSourceAdapter} 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 @@ -20,6 +21,11 @@ GoalSourceAdapter: VDA5050SourceAdapter: 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 ──────────────────────────────────────────── # # Mỗi case là một namespace riêng để test gọi loadFromConfig(nh, "") mà không phải sinh @@ -105,3 +111,18 @@ vda5050_bad_profile: invalid_name: steps: - {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: "" diff --git a/test/plugin_registry_test.cpp b/test/plugin_registry_test.cpp index 3520f0f..46b129d 100644 --- a/test/plugin_registry_test.cpp +++ b/test/plugin_registry_test.cpp @@ -79,19 +79,70 @@ protected: // ── Đường nạp bình thường ──────────────────────────────────────────────────────────────────────── -TEST_F(PluginRegistryTest, LoadsBothSourcesFromConfig) +TEST_F(PluginRegistryTest, LoadsEverySourceFromConfig) { PluginRegistry registry; ASSERT_TRUE(registry.loadFromConfig(nh)) << "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::kVda5050Order), nullptr); + EXPECT_NE(registry.find(schema::kInstantAction), 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) { PluginRegistry registry;