diff --git a/config/move_base_common_params.yaml b/config/move_base_common_params.yaml index 2e0ed8e..f05b348 100755 --- a/config/move_base_common_params.yaml +++ b/config/move_base_common_params.yaml @@ -26,9 +26,33 @@ controller_frequency: 30.0 # [Hz] nhịp chạy vòng điều khiển controller_patience: 0.0 # [s] controller lỗi thì xoá vật cản rồi thử lại; quá ngưỡng này thì bỏ và lập plan mới. 0 = bỏ ngay planner_frequency: 0.0 # [Hz] nhịp lập plan lại khi đang bám path. 0 = KHÔNG lập lại, chỉ lập khi controller lỗi planner_patience: 2.0 # [s] lập plan lỗi thì thử lại trong bấy lâu rồi mới bỏ cuộc... -max_planning_retries: 0 # ... hoặc sau bấy nhiêu lần thử (điều kiện nào tới trước thì thắng). 0 = không giới hạn số lần +# Số lần lập plan HỎNG liên tiếp được phép trước khi leo thang recovery (điều kiện nào tới trước +# giữa khoá này và `planner_patience` thì thắng). CHÚ Ý: 0 = hỏng MỘT lượt là leo thang ngay, +# KHÔNG phải "không giới hạn"; muốn không giới hạn thì đặt -1 (chỉ an toàn khi planner_patience > 0). +max_planning_retries: 0 + +# [s] Trần chờ ở CANCELLING và PAUSING cho tới khi runtime IM HẲN rồi mới báo CANCELLED/PREEMPTED +# hoặc PAUSED ra host (lúc PAUSING host vẫn thấy tên state cũ + feed_back_str "pausing…"): +# lệnh = 0 và odom ≈ 0, thread global planner rảnh và recovery đã dừng (kể cả lượt makePlan đã huỷ mà plugin không cắt +# được), action đã trả terminal. Quá trần vẫn CANCELLED nhưng in LỖI "settle timeout". +# ► Chỉnh: TĂNG (5–10) nếu SBPL `allocated_time` lớn và chưa có preempt. 0 = TẮT (báo ngay khi +# lệnh = 0 như trước 11/9/2026 — host dễ gửi goal kế lúc planner còn bận, goal kế bị coi là hỏng). +settle_timeout: 2.0 + +# [m/s] Ngưỡng coi robot ĐÃ DỪNG theo odom (bánh xe còn giảm tốc sau khi lệnh = 0). Chỉ có tác dụng +# khi host đẩy odom vào; không có odom thì lùi về đo bằng lệnh. 0 = bỏ odom. +# ► Chỉnh: TĂNG (0.05) nếu odom nhiễu giữ CANCELLING tới tận settle_timeout dù robot đã đứng. +stopped_measured_linear_eps: 0.02 + +# [rad/s] Như trên cho trục quay. +stopped_measured_angular_eps: 0.02 oscillation_timeout: -1 # [s] robot dao động tại chỗ quá lâu thì bỏ controller và chạy recovery. -1 = tắt oscillation_distance: 0.5 +# [m] Recovery THÀNH CÔNG và nộp path mới chỉ được nạp lại ngân sách route khi robot đã đi được ít +# nhất quãng này kể từ lần nạp lại trước; chưa đi được thì tính như thất bại (chặn vòng "replan +# thành công -> bị chặn tại chỗ -> replan", sim 2026-09-04). 0 = nạp lại vô điều kiện (hành vi cũ). +# Phải <= oscillation_distance. +recovery_reset_min_travel: 0.10 ## recovery behaviors # # Recovery của move_base cũ đã dừng: bộ behavior gen-2 (tick-based) khai ở @@ -58,3 +82,38 @@ ClearCostmapRecovery: MoveBase: library_path: libmove_base + +# ================================================================================================= +# Watchdog thành phần (2026-09-11) — thread riêng đọc bảng trạng thái, kết luận "TREO" +# +# Mỗi thành phần (global planner, local planner, recovery, action, control loop) tự khai nó đang +# bận/dừng/rảnh và "nhích" mỗi nhịp. Watchdog chạy trên thread riêng — control thread treo thì +# không tự phát hiện được chính nó — và kết luận treo khi một hàng BẬN mà KHÔNG NHÍCH quá ngân sách. +# Treo → in LỖI một lần (không tắt được); control loop treo → host đọc navigation_state = LOST và +# phải tự đưa cmd_vel về 0. Đây là chẩn đoán, không phải điều khiển: state machine không đổi gì. +# ================================================================================================= + +# [s] Chu kỳ kiểm của watchdog. 0 = TẮT watchdog (không có thread, không phát hiện treo). +watchdog_period: 0.1 + +# [s] Trần MỘT lượt makePlan trên thread planner trước khi kết luận global planner TREO. Từ 11/9/2026 +# khoá này mới có tác dụng (trước đó đọc mà không dùng). PHẢI LỚN HƠN thời gian một lượt hợp lệ dài +# nhất: với SBPL là `allocated_time` trong sbpl_global_params.yaml (đã là trần chung cho cả 3 lượt +# replan nội bộ). ► Chỉnh: đặt ≈ allocated_time + 1. 0 = không giám sát hàng này. +planner_timeout: 5.0 + +# [s] Trần MỘT lời gọi computeVelocityCommands của local planner. Priest 30–48 ms, Hybrid < 10 ms; +# 0.5 s là "chắc chắn có gì đó hỏng" chứ không phải chậm. 0 = không giám sát. +local_planner_call_budget: 0.5 + +# [s] Recovery behavior bận mà không nhích (không tick, worker detour không về) quá đây = treo. +recovery_stall_budget: 5.0 + +# [s] Action handler bận mà không nhích quá đây = treo. 0 = TẮT (mặc định): handler tự timeout +# theo thiết bị của nó (tầng 1), `action_patience` là tầng 2 — không cần tầng thứ ba. +action_stall_budget: 0.0 + +# [s] Control thread không kết thúc được một cycle nào trong quãng này = TREO → host thấy LOST. +# 0.5 s = 15 cycle @ 30 Hz. GIẢM (0.2) nếu host cần phản ứng nhanh hơn; không đặt < 3 cycle vì +# một lượt detour/solve dài hợp lệ sẽ bị báo nhầm. +control_loop_stall_budget: 0.5 diff --git a/src/APIs/c_api/NAV_C_API_2_GUIDE.md b/src/APIs/c_api/NAV_C_API_2_GUIDE.md index 8248d16..870709e 100644 --- a/src/APIs/c_api/NAV_C_API_2_GUIDE.md +++ b/src/APIs/c_api/NAV_C_API_2_GUIDE.md @@ -460,6 +460,52 @@ theo dõi `navigation_get_twist`. Nếu C# có tầng an toàn giả định d `cancel` từ host huỷ **cả order** (gồm hàng đợi mission), khác với huỷ nội bộ do chính mission layer phát ra chỉ dừng chặng đang chạy. +**Cancel nói thật từ 2026-09-11.** Sau `navigation_cancel()`, `navigation_get_state()` báo +`PREEMPTING` cho tới khi lõi **im hẳn**, rồi mới `PREEMPTED` (và chốt lại tới yêu cầu kế). "Im hẳn" +là ba điều kiện cùng đúng: + +1. lệnh vận tốc = 0 **và** odom đọc ≈ 0 (bánh xe đã đứng, không chỉ lệnh); +2. thread global planner rảnh — một lượt `makePlan` đã huỷ mà plugin không cắt được (SBPL chạy tới + hết `allocated_time`) giữ thread bận nhiều giây, và `PREEMPTED` **không** được báo trong lúc đó; +3. action đang chạy (nếu có) đã trả terminal. + +Luật cho host: **không gửi goal kế khi state còn `PREEMPTING`.** + +```cpp +navigation_cancel(h); +NavigationState s; +do { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + navigation_get_state(h, &s); +} while (s == PREEMPTING); +// s == PREEMPTED (hoặc PENDING/… nếu đã có việc khác) → an toàn gửi goal kế +``` + +Gửi sớm không bị từ chối — goal kế đứng ở `PLANNING` tới khi thread rảnh — nhưng hàng đợi phía +host sẽ lệch nhịp với lõi. Trước 2026-09-11 lõi báo `PREEMPTED` sau đúng một cycle bất kể thread +planner; host tin, gửi goal kế, goal kế bị coi là hỏng và `ABORTED` sau ~3 s. Trần chờ là khoá +`settle_timeout` của `move_base2` (mặc định 2 s); quá trần lõi vẫn báo `PREEMPTED` và in lỗi. + +### 6.5b. Trạng thái từng thành phần và `LOST` (2026-09-11) + +| | Hàm | Đổi | +|---|---|---| +| + | `size_t navigation_get_component_status(NavigationHandle, NavComponentStatus* out, size_t max)` | mới | + +Lõi giữ một bảng "ai đang bận / đã được bảo dừng / đã treo" cho 7 thành phần (`global_planner`, +`local_planner`, `recovery`, `action`, `costmap_global`, `costmap_local`, `control_loop`). Hàm này +chép bảng ra cho host; chỉ đọc atomic nên gọi được từ thread bất kỳ — kể cả khi control thread +đang treo, là lúc cần nó nhất. `phase`: 0 idle, 1 busy, 2 stopping, 3 paused, 4 hung; `hung` là kết +luận của watchdog (bận quá ngân sách mà không nhích). Trả 0 với runtime cũ không có capability. + +**`LOST`:** control thread không kết thúc được cycle nào quá `control_loop_stall_budget` (mặc định +0.5 s) → `navigation_get_state()` báo `LOST` (ghi từ thread watchdog), `feed_back_str` nêu thời +gian. Host đọc `LOST` phải **tự đưa cmd_vel về 0** — twist từ `navigation_get_twist()` lúc đó là +giá trị cũ, stamp không tiến (mục 6). Hết treo, state thật quay lại. + +Dùng khi cancel/pause có vẻ lâu: gọi hàm này, hàng nào `phase = 2` (stopping) lâu là plugin không +tuân preempt; `hung = 1` là treo thật. + ### 6.6. Trần vận tốc | | Hàm | Đổi | diff --git a/src/APIs/c_api/include/nav_c_api_2.h b/src/APIs/c_api/include/nav_c_api_2.h index c55ed6c..399c95a 100644 --- a/src/APIs/c_api/include/nav_c_api_2.h +++ b/src/APIs/c_api/include/nav_c_api_2.h @@ -45,6 +45,17 @@ * the request; the control thread applies it on its next cycle. Returning from the call does * not mean the robot stopped — watch the state, or watch the twist. * + * Since 2026-09-11 the state tells the truth about a cancel: after navigation_cancel() the + * core reports PREEMPTING until it is quiescent — the issued command is zero AND odometry + * reads zero, the global-planner thread is idle (a cancelled makePlan() that the plugin + * cannot interrupt keeps that thread busy for seconds), and any running action has reported + * terminal. Only then does it report PREEMPTED, and that result is latched until the next + * request. Poll navigation_get_state() and do not submit the next goal while it is + * PREEMPTING. A goal submitted early is not rejected — it waits in PLANNING until the + * thread frees — but it is the caller's queue that ends up out of step. The wait is bounded + * by move_base2's `settle_timeout` (default 2 s); on expiry the core still reports + * PREEMPTED and logs an error. + * * 5. navigation_set_twist_linear() / _angular() set a velocity **ceiling**, and the sign of the * linear x component selects which direction the ceiling applies to. They now only reject * NaN/Inf; the old runtime also returned false while a cancel was in flight, and that signal no @@ -175,6 +186,38 @@ extern "C" */ char *navigation_get_status_text(NavigationHandle handle); + /** + * @brief One row of the runtime's component status board (added 2026-09-11). + * + * `phase`: 0 idle, 1 busy, 2 stopping (told to cancel, not yet returned), 3 paused, 4 hung. + * `hung`: the watchdog's verdict — busy longer than the component's budget with no progress. + * Rows, in order: global_planner, local_planner, recovery, action, costmap_global, costmap_local, + * control_loop. Use `name` rather than the index when displaying. + */ + typedef struct + { + char name[32]; + unsigned char phase; + unsigned char hung; + double seconds_in_phase; + double seconds_since_progress; + } NavComponentStatus; + + /** + * @brief Per-component liveness of the runtime: who is busy, who was told to stop, who is hung. + * + * Reads atomics only — safe from any thread and, critically, still answers while the control + * thread itself is stalled (navigation_get_state() then reports LOST). Poll it when a cancel or + * pause seems to take long, or after LOST, to see which component is stuck. + * + * @param handle Navigation handle. + * @param out Array of at least @p max entries; may be NULL with max = 0 to query the count. + * @param max Capacity of @p out. + * @return Number of rows the runtime has (may exceed @p max); 0 if the runtime does not offer + * the capability (older move_base2) or is not initialized. + */ + size_t navigation_get_component_status(NavigationHandle handle, NavComponentStatus *out, size_t max); + // ============================================================================================ // Sensor input // ============================================================================================ diff --git a/src/APIs/c_api/src/nav_c_api_2.cpp b/src/APIs/c_api/src/nav_c_api_2.cpp index baeafa6..e306c39 100644 --- a/src/APIs/c_api/src/nav_c_api_2.cpp +++ b/src/APIs/c_api/src/nav_c_api_2.cpp @@ -14,13 +14,19 @@ #include #include +#include #include #include #include +#include +#include + +#include #include #include +#include #include #include @@ -179,6 +185,65 @@ extern "C" bool navigation_get_state(NavigationHandle handle, NavigationState *o } } +extern "C" size_t navigation_get_component_status(NavigationHandle handle, NavComponentStatus *out, + size_t max) +{ + if (!handle) + { + return 0; + } + try + { + // Capability tra MỘT lần theo alias trong .so navigation đang nạp (cùng đường mà + // navigation_create() đã đi). Runtime cũ không export alias → 0, không phải lỗi. + using Probe = std::function; + static Probe probe; + static bool probed = false; + if (!probed) + { + probed = true; + try + { + robot::PluginLoaderHelper loader; + const std::string path = loader.findLibraryPath("MoveBase"); + probe = boost::dll::import_alias( + path, robot::move_base_core::kComponentStatusProbeAlias, + boost::dll::load_mode::append_decorations); + } + catch (const std::exception &e) + { + robot::log_warning("navigation_get_component_status: runtime offers no '%s' capability: %s", + robot::move_base_core::kComponentStatusProbeAlias, e.what()); + probe = nullptr; + } + } + if (!probe) + { + return 0; + } + + std::vector rows(max); + const std::size_t count = probe(as_navigation(handle), rows.empty() ? nullptr : rows.data(), max); + const std::size_t copied = count < max ? count : max; + for (std::size_t i = 0; i < copied && out != nullptr; ++i) + { + std::memcpy(out[i].name, rows[i].name, sizeof(out[i].name)); + out[i].phase = rows[i].phase; + out[i].hung = rows[i].hung; + out[i].seconds_in_phase = rows[i].seconds_in_phase; + out[i].seconds_since_progress = rows[i].seconds_since_progress; + } + return count; + } + catch (...) + { + return 0; + } +} + extern "C" char *navigation_get_status_text(NavigationHandle handle) { if (!handle) diff --git a/src/Navigations/Cores/move_base_core/include/move_base_core/component_status_probe.h b/src/Navigations/Cores/move_base_core/include/move_base_core/component_status_probe.h new file mode 100644 index 0000000..5bcd048 --- /dev/null +++ b/src/Navigations/Cores/move_base_core/include/move_base_core/component_status_probe.h @@ -0,0 +1,51 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * move_base_core — optional capability: per-component liveness of a navigation runtime. + * + * Author: DuongTD + *********************************************************************/ +#ifndef MOVE_BASE_CORE_COMPONENT_STATUS_PROBE_H +#define MOVE_BASE_CORE_COMPONENT_STATUS_PROBE_H + +#include + +namespace robot +{ +namespace move_base_core +{ + +class BaseNavigation; + +/** + * One row of the runtime's component status board, flattened for a C/.NET host. + * + * Deliberately NOT a virtual on BaseNavigation: that would change the vtable every host binary was + * built against. Instead the navigation plugin .so exports a free function under the Boost.DLL + * alias @ref kComponentStatusProbeAlias and a host that wants it dlsym()s it (nav_c_api_2: + * navigation_get_component_status). Runtimes without the alias simply do not offer it. + * + * `phase` values: 0 idle, 1 busy, 2 stopping, 3 paused, 4 hung (mirrors move_base2::ComponentPhase). + * `hung` is the watchdog's verdict — busy for longer than the component's budget without progress. + */ +struct ComponentStatusEntry +{ + char name[32]; + unsigned char phase; + unsigned char hung; + double seconds_in_phase; + double seconds_since_progress; +}; + +/// Fills up to @p max entries for @p navigation; returns how many rows the runtime has (may exceed max). +using ComponentStatusProbeFn = std::size_t (*)(BaseNavigation* navigation, ComponentStatusEntry* out, + std::size_t max); + +/// Boost.DLL alias name the navigation plugin exports the probe under (added 2026-09-11). +constexpr const char* kComponentStatusProbeAlias = "MoveBaseComponentStatus"; + +} // namespace move_base_core +} // namespace robot + +#endif // MOVE_BASE_CORE_COMPONENT_STATUS_PROBE_H diff --git a/src/Navigations/Cores/robot_nav_core/include/robot_nav_core/preemptable.h b/src/Navigations/Cores/robot_nav_core/include/robot_nav_core/preemptable.h new file mode 100644 index 0000000..513ce36 --- /dev/null +++ b/src/Navigations/Cores/robot_nav_core/include/robot_nav_core/preemptable.h @@ -0,0 +1,44 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_nav_core — optional mixin for plugins whose work can be interrupted from another thread. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_NAV_CORE_PREEMPTABLE_H +#define ROBOT_NAV_CORE_PREEMPTABLE_H + +namespace robot_nav_core { + +/** + * @class Preemptable + * @brief A plugin that can cut short a long-running call (makePlan, a recovery attempt) when asked. + * + * Deliberately a separate interface instead of a new virtual on BaseGlobalPlanner / + * BaseLocalPlanner: adding a slot to those vtables would force every already-built plugin .so to be + * rebuilt in lock-step, and a stale one would crash on load. A plugin opts in by inheriting this + * class as well; the runtime discovers support with `dynamic_cast` and falls back to + * "discard the result when it arrives" for plugins that do not. + * + * Contract for implementers: + * - preempt() is called from ANOTHER thread than the one inside the long call. It must be + * lock-free, allocation-free and return immediately — typically one atomic store. + * - The long call must poll the flag often (per expansion / per iteration) and return promptly, + * reporting failure; a partial result must not be handed back as a success. + * - Every new call must start with the flag cleared, so a preempt aimed at the previous call + * cannot kill the next one. + * + * Added 2026-09-11 for the move_base2 cancel/pause path (SBPLLatticePlanner, DetourPathRecovery). + */ +class Preemptable { +public: + virtual ~Preemptable() = default; + + /// Request that the call currently running on the plugin's worker returns as soon as possible. + virtual void preempt() = 0; +}; + +} // namespace robot_nav_core + +#endif // ROBOT_NAV_CORE_PREEMPTABLE_H