7 Commits

Author SHA1 Message Date
c6e70b7dc5 config(move_base_common): add costmap_ready_timeout
Sim tree copy of the key PlannerRunner reads: how long a goal waits for every enabled global layer to be current before planning (default 10 s, 0 = legacy behaviour).
2026-11-04 13:23:48 +07:00
6decd8db32 feat(move_base2): wait for a ready global costmap and replay maps in host order
- Replay static maps in arrival order instead of topic order, so a
  direction grid can no longer be replayed before its static map (F3).
- PlannerRunner checks every enabled global layer under the same lock as
  the snapshot; while not current it keeps the goal, reports
  waiting_for_costmap, logs the stale layers (throttled) and does not
  spend planner_patience or watchdog budget. After costmap_ready_timeout
  [s] (default 10, 0 = legacy behaviour) the attempt fails as before.
- Test fixture destroys the server before its fake ports; the control
  thread could call a destroyed port (race existed before this change).
2026-11-04 11:14:15 +07:00
7bfb3c362d fix(sensor_gateway): give static maps to the directional layer first
With a same-geometry map, StaticLayer could be written and report current
between the two dispatches while the old direction field was still READY,
so a plan could pair the new map with the old zones. The directional
layer only needs the map topic to go PENDING, and direction grids are
ignored by StaticLayer, so dispatching it first needs no lock.
2026-11-04 11:14:15 +07:00
f85d89ef8c feat(sensor_gateway): deliver static map grids to the directional layer
pushStaticMap now also dispatches to DIRECTIONAL_LAYER on the global costmap, after STATIC_LAYER so the master is already resized to the new map when the directional layer checks a direction grid against it. The layer filters by topic: map_topic resets it to PENDING, direction_topic carries the direction grid.
2026-11-03 16:57:01 +07:00
75af8ccf12 feat(planner_runner): bind dock_face_offset and dock_pivot_safety_margin per marker
Two new DockPlanner keys, valid only with dock_anchor: mating_edge, are copied from
docking_marker_profiles/<marker> into the planner namespace like footprint_dock and
dock_anchor.

Unlike those two, the new keys are optional. A marker that does not declare one would keep
the value bound by the previous marker, so the charger's smaller pivot margin could leak
into a later trolley docking. When the marker lacks a key that the planner namespace still
holds, the binder writes a YAML null, which DockPlanner reads as unset, and counts it as a
change so that the instance is rebuilt. footprint_dock and dock_anchor keep their old
behaviour.
2026-10-29 16:54:02 +07:00
c3c64919d3 feat(control_loop): reserve backup_global_planner for the position profile
A failed primary global planner on a docking, go_straight or rotate request no longer swaps to backup_global_planner. It goes straight to the planning_failed recovery route and aborts. Only the position profile may use the backup planner. Update STATE_MACHINE.md and add test NonPositionPlannerFailureSkipsBackup.
2026-10-27 13:09:30 +07:00
ea7f9659b8 feat(sensor_gateway): feed DepthCameraObstacleLayer through its own LayerType
robot_costmap_2d has LayerType::DEPTH_CAMERA_LAYER for
DepthCameraObstacleLayer. The gateway now pushes PointCloud2 to that type
as well as to VOXEL_LAYER, in both the local and the global costmap.
LaserScan, PointCloud and DepthCameraData stay VOXEL_LAYER only: the layer
marks and clears from the filtered camera cloud and does not use the depth
image.

Needs robot_costmap_2d main 64974d4 or later (the enum value).

Squashed from feature/depth-camera-layer-type (c280a0a..d3a9208).
2026-10-21 14:21:53 +07:00
25 changed files with 660 additions and 52 deletions

View File

@@ -125,6 +125,16 @@ sensor_patience: 2.0
# Chỉ bật (0.5–1.0) nếu sau này global planner vừa tránh được vật cản vừa đủ nhanh (~30 ms).
planner_frequency: 0.0
# [s] Thời gian tối đa giữ goal để chờ global costmap sẵn sàng trước khi lập plan. "Sẵn sàng" là
# mọi layer đang bật đều current: StaticLayer đã ghi map mới vào master, DirectionalLayer đã nhận
# grid hướng sau static map mới nhất. Trong lúc chờ, goal được giữ, không tính vào
# `planner_patience`, log ghi tên layer chưa sẵn sàng.
# ► Tăng: chờ được map/grid đến chậm (đổi map lớn, app gửi grid hướng muộn).
# ► Giảm: báo lỗi sớm hơn khi host quên gửi dữ liệu; quá thấp thì mission fail giả lúc đổi map.
# ► 0: tắt kiểm tra, quay về hành vi cũ — planner có thể lập plan trên map dở dang hoặc bị SBPL
# từ chối ngay khi direction còn PENDING.
costmap_ready_timeout: 10.0
# [s] Ở PLANNING quá lâu mà chưa có plan -> recovery. Mất pose ngay trong PLANNING dùng ngân sách
# `controlling_failed` (xem recovery_behaviors_params.yaml).
# ► Chỉnh: đặt > thời gian lập plan xấu nhất của global planner. SBPL `allocated_time: 10.0` ở

View File

@@ -11,7 +11,7 @@ Khi cần đổi hành vi: sửa tài liệu này trước, sửa test, rồi m
| State | Ai phát cmd_vel | Vào state khi | Ra khi |
|---|---|---|---|
| `IDLE` | không ai (0) | khởi động; cycle ngay sau một state terminal | có `NavigationRequest` đang chờ → `PLANNING`; yêu cầu chỉ-có-action (`has_goal == false`, D8) → `EXECUTING_ACTIONS`; yêu cầu không có goal lẫn action → `ABORTED` (tự vệ) |
| `PLANNING` | không ai (0) | nhận yêu cầu; recovery của `planning_failed` (hoặc lượt leo thang từ chính `PLANNING`) vừa chạy xong; tiếp tục sau tạm dừng | có plan hợp lệ → `CONTROLLING`; global planner chính fail/plan rỗng và có backup chưa dùng → đổi sang backup, lập plan lại; backup fail (hoặc không có backup) / quá `planner_patience` / quá `max_planning_retries` → còn pose thì `RECOVERING(planning_failed)`, **mất pose thì `RECOVERING(controlling_failed)`** — mất dữ liệu dùng ngân sách dữ liệu, không phải ngân sách "không tìm được đường" |
| `PLANNING` | không ai (0) | nhận yêu cầu; recovery của `planning_failed` (hoặc lượt leo thang từ chính `PLANNING`) vừa chạy xong; tiếp tục sau tạm dừng | có plan hợp lệ → `CONTROLLING`; global planner chính fail/plan rỗng, chặng là profile `position` và có backup chưa dùng → đổi sang backup, lập plan lại; backup fail (hoặc không có backup) / quá `planner_patience` / quá `max_planning_retries` → còn pose thì `RECOVERING(planning_failed)`, **mất pose thì `RECOVERING(controlling_failed)`** — mất dữ liệu dùng ngân sách dữ liệu, không phải ngân sách "không tìm được đường" |
| `CONTROLLING` | **local planner** | có plan hợp lệ; recovery leo thang từ `CONTROLLING` vừa xong (bám tiếp plan cũ, hoặc áp path detour); tiếp tục sau tạm dừng | `isGoalReached` → `SUCCEEDED` (hết action) hoặc `EXECUTING_ACTIONS` (còn action — D8); quá `controller_patience` → `RECOVERING(controlling_failed)`; quá `oscillation_timeout` → `RECOVERING(oscillation)`. **Không sinh được lệnh (kể cả mất pose) thì KHÔNG đổi state** (contract 2026-08-04): robot dừng tại chỗ, ở nguyên `CONTROLLING` chờ đồng hồ kiên nhẫn; plan mới trong lúc chạy đến từ replan nền theo `planner_frequency` và được thay tại chỗ |
| `RECOVERING` | **recovery behavior** | ba trigger ở trên | tick trả `succeeded`/`failed` → cursor của **route thuộc trigger đó** tăng 1, rồi (2026-08-04b): behavior nộp path detour (`kPath`) → `CONTROLLING` áp path đó; trigger `planning_failed` hoặc leo thang từ `PLANNING` → `PLANNING` lập plan lại; còn lại (controlling/oscillation từ `CONTROLLING`) → `CONTROLLING` bám tiếp plan cũ, KHÔNG replan; hết route khi định vào → `ABORTED` |
| `EXECUTING_ACTIONS` | không ai (0) — **D8** | tới goal mà yêu cầu còn action; nhận yêu cầu `has_goal == false` | action xong mà còn action kế → start action kế (ở nguyên state); action cuối `succeeded` → `SUCCEEDED`; một action `failed` → `ABORTED` (không qua recovery); quá `action_patience` (nếu bật) → cancel action + `ABORTED`; `cancel()` → `CANCELLING`; `pause()` → `PAUSING` → `PAUSED` (không huỷ action) |
@@ -103,7 +103,11 @@ Từ 2026-08-04, replan trong lúc chạy và recovery là **hai cơ chế tách
`backup_global_planner` là một alias tùy chọn ở root config. Khi global planner active trả `false`
hoặc plan rỗng, `ControlLoop` đổi sang alias này **một lần duy nhất cho mỗi request**, giữ nguyên
local planner và state `PLANNING`. Lượt backup thành công đi bình thường vào `CONTROLLING`; lượt
local planner và state `PLANNING`. **Chỉ áp cho profile `position`**: `docking`, `go_straight`,
`rotate` fail thì không đổi planner mà đi thẳng `PlannerFeedback::kFailed` (log WARN `backup '...'
is reserved for profile position`). Lý do (robot KIT 26/10): DockPlanner fail vì robot đứng quá gần
dock, SBPL dựng đường thẳng tới pose tiếp xúc và robot bám đường đó vào dock, bỏ qua cusp và đoạn
lùi thẳng. Lượt backup thành công đi bình thường vào `CONTROLLING`; lượt
backup fail mới được đưa vào `PlannerFeedback::kFailed`, nên state machine đi theo recovery hiện có.
Backup dùng overload `makePlan(start, goal, plan)` (không mang VDA5050 `Order`) để

View File

@@ -53,6 +53,9 @@ struct MoveBase2Config
*/
double planner_timeout = 5.0;
/// [s] Continuous global-costmap readiness wait; 0 disables the check (legacy behavior).
double costmap_ready_timeout = 10.0;
/**
* Watchdog (2026-09-11): thread riêng đọc bảng trạng thái thành phần, kết luận "treo" theo ngân
* sách từng hàng. `watchdog.planner_timeout` được chép từ @ref planner_timeout khi nạp.

View File

@@ -109,6 +109,9 @@ struct ControlLoopConfig
/// [s] Chu kỳ danh nghĩa, chỉ dùng cho dt của cycle ĐẦU TIÊN khi chưa có mốc thời gian trước đó.
double nominal_control_period = 0.05;
/// [s] Maximum continuous global-costmap wait; 0 disables the readiness check.
double costmap_ready_timeout = 10.0;
/// Công tắc log chẩn đoán. Xem `MoveBase2Config::debug_*` để biết từng nhóm in cái gì.
bool debug_state = true;
bool debug_plan = true;

View File

@@ -48,7 +48,8 @@ enum class ComponentPhase : std::uint8_t
kBusy, ///< Đang làm việc.
kStopping, ///< Đã được bảo dừng (preempt/cancel) nhưng chưa thoát.
kPaused, ///< Đã xác nhận tạm dừng (chỉ action, pha 3).
kHung ///< Watchdog kết luận: bận quá ngân sách mà không nhích (pha 4).
kHung, ///< Watchdog kết luận: bận quá ngân sách mà không nhích (pha 4).
kWaitingForCostmap ///< Retaining the request until global costmap data is ready.
};
const char* toString(Component component);

View File

@@ -28,6 +28,7 @@ enum class PlannerFeedback
{
kIdle, ///< Chưa có tin gì mới kể từ cycle trước.
kBusy, ///< Đang lập plan, chưa có kết quả.
kWaitingForCostmap, ///< Goal retained while the global costmap becomes current.
kPlanReady, ///< Có plan mới, không rỗng, sẵn sàng đẩy xuống controller.
kFailed ///< Lần lập plan gần nhất thất bại.
};
@@ -190,6 +191,7 @@ struct StateMachineInput
bool emergency = false;
PlannerFeedback planner = PlannerFeedback::kIdle;
bool planner_costmap_wait_finished = false;
ControllerFeedback controller = ControllerFeedback::kIdle;
RecoveryFeedback recovery = RecoveryFeedback::kIdle;
ActionFeedback action = ActionFeedback::kIdle;

View File

@@ -112,6 +112,9 @@ struct SensorGatewayStats
*
* ## Khác biệt có chủ đích so với `move_base` cũ
*
* - **`DEPTH_CAMERA_LAYER` chỉ nhận `PointCloud2`** (không nhận `LaserScan`, `PointCloud`,
* `DepthCameraData`), song song với `VOXEL_LAYER`: `DepthCameraObstacleLayer` có loại riêng và
* chỉ dùng cloud đã lọc của camera.
* - **Lọc layer chỉ theo `getType()`.** Bản cũ dùng `getType() == type || getName() == name`. Vế
* tên là code chết trong thực tế (tên layer là `obstacles`/`inflation`, tên sensor là
* `/b_scan`/`/map` — hai tập không giao nhau) nhưng lại là một cái bẫy: đặt tên một layer trùng

View File

@@ -10,6 +10,7 @@
#define MOVE_BASE2_NAVIGATION_SERVER_H_
#include <atomic>
#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
@@ -60,6 +61,8 @@ public:
/**
* @brief Nạp cấu hình và các cổng cho control loop.
* @warning Các cổng trong deps là non-owning: bên cấp phải giữ chúng sống tới khi control
* thread đã được dừng và join, kể cả khi dựa vào destructor của NavigationServer.
* @param[out] error Lý do không cấu hình được.
*/
bool configureLoop(const ControlLoopConfig& config, const ControlLoopDeps& deps,
@@ -423,6 +426,10 @@ private:
/// Bảo vệ dữ liệu sensor và footprint: host ghi từ thread của nó, control loop đọc.
mutable std::mutex data_mutex_;
/// Latest arrival order per stored static-map topic; guarded by data_mutex_.
std::map<std::string, std::uint64_t> static_map_sequences_;
std::uint64_t next_static_map_sequence_ = 0;
std::vector<robot_geometry_msgs::Point> footprint_;
bool footprint_pending_ = false;
std::map<std::string, robot_sensor_msgs::DepthCameraData::ConstPtr> depth_camera_data_;

View File

@@ -108,6 +108,12 @@ public:
/// @brief Có lượt lập plan nào đang chạy không.
virtual bool isPlanning() const = 0;
/// Configure the global readiness wait before accepting requests. Zero keeps legacy behavior.
virtual void setCostmapReadyTimeout(double /*seconds*/) {}
/// Atomically sample the wait and consume the completion event since the previous sample.
virtual bool costmapWaitState(bool& finished) { finished = false; return false; }
/**
* @brief Lấy kết quả nếu đã có. Không chặn.
*

View File

@@ -11,6 +11,7 @@
#define MOVE_BASE2_RUNNERS_PLANNER_RUNNER_H_
#include <condition_variable>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
@@ -38,6 +39,15 @@ class Costmap2DROBOT;
namespace move_base2
{
/// Decision for a continuous readiness wait. A zero timeout preserves legacy planning behavior.
enum class CostmapReadyDecision { kPlan, kWait, kTimeout };
inline CostmapReadyDecision costmapReadyDecision(bool ready, double elapsed, double timeout)
{
if (timeout == 0.0 || ready)
return CostmapReadyDecision::kPlan;
return elapsed >= timeout ? CostmapReadyDecision::kTimeout : CostmapReadyDecision::kWait;
}
/**
* @class PlannerRunner
* @brief Nạp và chạy global planner thế hệ 1 (`robot_nav_core::BaseGlobalPlanner`) qua Boost.DLL,
@@ -177,6 +187,8 @@ public:
const robot_protocol_msgs::Order* order, std::uint64_t tag) override;
bool isPlanning() const override;
void setCostmapReadyTimeout(double seconds) override;
bool costmapWaitState(bool& finished) override;
bool pollPlan(PlanResult& result) override;
@@ -268,6 +280,15 @@ private:
bool running_ = false; ///< Thread đang chạy plugin.
bool discard_ = false; ///< Lượt đang chạy đã bị huỷ — vứt kết quả khi nó về.
bool has_result_ = false;
double costmap_ready_timeout_ = 10.0; ///< [s], protected by mutex_.
bool waiting_for_costmap_ = false;
bool costmap_wait_finished_ = false;
// Written only by the planner thread; throttle a persistent outage across failed attempts.
bool costmap_wait_problem_active_ = false;
std::chrono::steady_clock::time_point last_costmap_wait_log_;
std::chrono::steady_clock::time_point last_costmap_timeout_log_;
std::string costmap_stale_names_;
bool costmap_stale_names_reserved_ = false;
robot_nav_core::BaseGlobalPlanner* active_ = nullptr; ///< Non-owning, trỏ vào @ref planners_.
/**

View File

@@ -49,6 +49,8 @@ const char* toString(ComponentPhase phase)
return "paused";
case ComponentPhase::kHung:
return "hung";
case ComponentPhase::kWaitingForCostmap:
return "waiting_for_costmap";
}
return "unknown";
}

View File

@@ -146,6 +146,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
readDouble(nh, "controller_frequency", config.controller_frequency);
readDouble(nh, "planner_frequency", config.planner_frequency);
readDouble(nh, "planner_timeout", config.planner_timeout);
readDouble(nh, "costmap_ready_timeout", config.costmap_ready_timeout);
readDouble(nh, "runtime_stats_period", config.runtime_stats_period);
readDouble(nh, "watchdog_period", config.watchdog.period);
readDouble(nh, "local_planner_call_budget", config.watchdog.local_planner_call_budget);
@@ -435,6 +436,11 @@ bool MoveBase2Config::validate(std::string& error) const
error = "planner_timeout is not finite [s]";
return false;
}
if (!std::isfinite(costmap_ready_timeout) || costmap_ready_timeout < 0.0)
{
error = "costmap_ready_timeout must be finite and >= 0 [s] (0 = legacy behavior)";
return false;
}
if (!watchdog.validate(error))
{
return false;
@@ -536,6 +542,8 @@ std::string MoveBase2Config::describe() const
out << " controller_frequency: " << controller_frequency << " Hz\n";
out << " planner_frequency: " << planner_frequency << " Hz\n";
out << " planner_timeout: " << planner_timeout << " s\n";
out << " costmap_ready_timeout: " << costmap_ready_timeout << " s"
<< (costmap_ready_timeout == 0.0 ? " (readiness check off)\n" : "\n");
out << " runtime_stats_period: " << runtime_stats_period << " s"
<< (runtime_stats_period > 0.0 ? "\n" : " (off)\n");
out << watchdog.describe();
@@ -582,6 +590,7 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
readDouble(nh, "controller_frequency", controller_frequency);
readDouble(nh, "planner_frequency", planner_frequency);
readDouble(nh, "costmap_ready_timeout", costmap_ready_timeout);
// Khoá này không có trong schema gen-1 — nó là công cụ chẩn đoán của move_base2. Vẫn đọc ở đây
// để bật được telemetry mà không phải chuyển cả cây config sang schema mới.
readDouble(nh, "runtime_stats_period", runtime_stats_period);
@@ -731,6 +740,7 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
config.debug_plan = debug_plan;
config.debug_skip = debug_skip;
config.state_machine = state_machine;
config.costmap_ready_timeout = costmap_ready_timeout;
config.velocity = velocity;
config.nominal_control_period =
controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s]

View File

@@ -48,6 +48,8 @@ const char* toString(PlannerFeedback feedback)
return "idle";
case PlannerFeedback::kBusy:
return "busy";
case PlannerFeedback::kWaitingForCostmap:
return "waiting_for_costmap";
case PlannerFeedback::kPlanReady:
return "plan_ready";
case PlannerFeedback::kFailed:
@@ -96,6 +98,11 @@ const char* toString(RecoveryFeedback feedback)
bool ControlLoopConfig::validate(std::string& error) const
{
if (!std::isfinite(costmap_ready_timeout) || costmap_ready_timeout < 0.0)
{
error = "costmap_ready_timeout must be finite and >= 0 [s]";
return false;
}
if (!state_machine.validate(error))
{
return false;
@@ -239,6 +246,7 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
config_ = config;
deps_ = deps;
deps_.planner->setCostmapReadyTimeout(config_.costmap_ready_timeout);
// EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 (PathMonitor cũ đã
@@ -655,10 +663,27 @@ void ControlLoop::collectPlannerResult()
// Fallback thuộc policy của control loop, không phải recovery: planner chính đã kết thúc nên
// worker rảnh để nạp/chạy SBPL ngay cycle này. Chỉ thử một lần cho cả request; backup fail thì
// giữ kFailed để state machine đi đúng đường recovery hiện có.
//
// Backup CHỈ dành cho profile position: goal trần không có edge làm CustomPlanner fail, và SBPL
// là đường lùi hợp lệ cho một chặng đi tới pose. Docking/go_straight/rotate thì SBPL không giữ
// được hình học của chặng — đo 26/10 trên robot KIT: DockPlanner fail vì robot đứng quá gần
// dock, SBPL dựng đường thẳng tới pose tiếp xúc, robot bám đường đó vào dock không qua cusp và
// đoạn lùi thẳng. Ba profile đó fail thì đi thẳng route planning_failed như khi không có backup.
if (!backup_global_planner_active_ && !config_.backup_global_planner_name.empty())
{
const std::string failed_planner = deps_.planner->activePlanner();
if (deps_.planner->swapPlanner(config_.backup_global_planner_name))
if (active_request_.profile != MotionProfile::kPosition)
{
// Không gắn [debug], không tắt được: đây là bằng chứng duy nhất trong log rằng lỗi planner
// của chặng này cố ý không được cứu bằng backup.
robot::log_warning("[move_base2] global planner '%s' failed for mission %llu (profile %s); "
"backup '%s' is reserved for profile position; starting recovery.\n",
failed_planner.c_str(),
static_cast<unsigned long long>(active_request_.mission_sequence_id),
toString(active_request_.profile),
config_.backup_global_planner_name.c_str());
}
else if (deps_.planner->swapPlanner(config_.backup_global_planner_name))
{
backup_global_planner_active_ = true;
planner_feedback_ = PlannerFeedback::kIdle;
@@ -669,11 +694,13 @@ void ControlLoop::collectPlannerResult()
config_.backup_global_planner_name.c_str());
return;
}
// Không có backup chạy được thì failure gốc vẫn phải đi recovery, không được để robot chờ.
robot::log_error("[move_base2] global planner '%s' failed and backup '%s' could not be "
"loaded; starting recovery.\n",
failed_planner.c_str(), config_.backup_global_planner_name.c_str());
else
{
// Không có backup chạy được thì failure gốc vẫn phải đi recovery, không được để robot chờ.
robot::log_error("[move_base2] global planner '%s' failed and backup '%s' could not be "
"loaded; starting recovery.\n",
failed_planner.c_str(), config_.backup_global_planner_name.c_str());
}
}
planner_feedback_ = PlannerFeedback::kFailed;
return;
@@ -1016,6 +1043,9 @@ bool ControlLoop::step()
input.cancel_requested = cancel_requested_;
input.emergency = emergency_;
input.planner = planner_feedback_;
const bool planner_waiting = deps_.planner->costmapWaitState(input.planner_costmap_wait_finished);
if (planner_running_ && planner_waiting && planner_feedback_ == PlannerFeedback::kBusy)
input.planner = PlannerFeedback::kWaitingForCostmap;
input.controller = controller_feedback_;
input.recovery = recovery_feedback_;
input.action = action_feedback_;

View File

@@ -44,6 +44,8 @@ const char* toString(robot_costmap_2d::LayerType type)
return "PreferredLayer";
case robot_costmap_2d::LayerType::UNPREFERRED_LAYER:
return "UnpreferredLayer";
case robot_costmap_2d::LayerType::DEPTH_CAMERA_LAYER:
return "DepthCameraObstacleLayer";
case robot_costmap_2d::LayerType::UNKNOWN:
break;
}
@@ -274,6 +276,12 @@ void SensorGateway::pushStaticMap(const std::string& name, const robot_nav_msgs:
}
ScopedSection timer(telemetry_, section_static_map_);
// DirectionalLayer TRƯỚC StaticLayer, có chủ đích. Layer tự lọc theo topic: map_topic chỉ đưa nó về
// PENDING (không cần geometry), direction_topic là grid hướng (StaticLayer bỏ qua, nên trong cùng
// lần gọi không có resize nào). Nếu StaticLayer nhận map trước, giữa hai lần dispatch updateMap có
// thể ghi xong map mới và StaticLayer báo current trong khi field hướng cũ vẫn READY — planner kiểm
// readiness đúng lúc đó sẽ plan theo map mới với zone cũ. Chỉ global costmap có layer này.
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::DIRECTIONAL_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::STATIC_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::PREFERRED_LAYER, name, stats_);
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::UNPREFERRED_LAYER, name, stats_);
@@ -331,6 +339,9 @@ void SensorGateway::pushPointCloud2(const std::string& name,
ScopedSection timer(telemetry_, section_cloud_);
dispatchTo(local_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
dispatchTo(global_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
// DepthCameraObstacleLayer has its own type and marks from the camera's PointCloud2.
dispatchTo(local_costmap_, cloud, robot_costmap_2d::LayerType::DEPTH_CAMERA_LAYER, name, stats_);
dispatchTo(global_costmap_, cloud, robot_costmap_2d::LayerType::DEPTH_CAMERA_LAYER, name, stats_);
}
void SensorGateway::pushDepthCameraData(const std::string& topic,

View File

@@ -11,6 +11,7 @@
#include <move_base2/io/sensor_store_types.h>
#include <robot_sensor_ports/sensor_writer.h>
#include <algorithm>
#include <cmath>
#include <mission_adapters/mission_request.h>
@@ -181,23 +182,41 @@ void NavigationServer::attachCostmaps(robot_costmap_2d::LayeredCostmap* global,
// Phát lại static map đã nhận trước khi costmap tồn tại. Chỉ static map, cố ý: một laser scan cũ
// phát lại vào costmap là dựng vật cản ở chỗ robot có thể đã rời khỏi từ lâu — im lặng và nguy
// hiểm hơn hẳn việc chờ mẫu kế tiếp, vốn chỉ cách vài chục ms.
std::map<std::string, robot_nav_msgs::OccupancyGrid> maps;
using ReplayEntry = std::pair<std::uint64_t,
std::pair<std::string, robot_nav_msgs::OccupancyGrid>>;
std::vector<ReplayEntry> maps;
std::pair<std::string, robot_nav_msgs::OccupancyGrid> legacy_map;
bool has_legacy_map = false;
{
std::lock_guard<std::mutex> lock(data_mutex_);
maps = static_maps_;
maps.reserve(static_maps_.size());
for (const auto& entry : static_maps_)
{
maps.push_back({ static_map_sequences_.at(entry.first), entry });
}
// `map_save_`/`map_name_save_` là cặp biến PUBLIC của BaseNavigation mà host tự gán (đường bù
// của bản cũ cho đúng vấn đề này). Tôn trọng nó để host không phải sửa gì, nhưng không để nó
// ghi đè bản đã đi qua addStaticMap.
if (!map_name_save_.empty() && maps.find(map_name_save_) == maps.end())
if (!map_name_save_.empty() && static_maps_.find(map_name_save_) == static_maps_.end())
{
maps[map_name_save_] = map_save_;
legacy_map = { map_name_save_, map_save_ };
has_legacy_map = true;
}
}
// The static map must precede its direction grid: the app must resend the direction grid
// immediately after every static map. Replaying by topic name would reverse that order.
std::sort(maps.begin(), maps.end(), [](const ReplayEntry& a, const ReplayEntry& b) {
return a.first < b.first;
});
if (has_legacy_map)
{
sensors_.pushStaticMap(legacy_map.first, legacy_map.second);
}
for (const auto& entry : maps)
{
sensors_.pushStaticMap(entry.first, entry.second);
sensors_.pushStaticMap(entry.second.first, entry.second.second);
}
}
@@ -693,6 +712,7 @@ void NavigationServer::addStaticMap(const std::string& topic, robot_nav_msgs::Oc
{
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_[topic] = map;
static_map_sequences_[topic] = ++next_static_map_sequence_;
}
sensors_.pushStaticMap(topic, map);
}
@@ -825,6 +845,7 @@ bool NavigationServer::removeStaticMap(const std::string& topic)
sensor_store_.clearTopic(topic);
std::lock_guard<std::mutex> lock(data_mutex_);
static_map_sequences_.erase(topic);
return static_maps_.erase(topic) > 0;
}
@@ -866,6 +887,7 @@ bool NavigationServer::removeAllStaticMaps()
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_.clear();
static_map_sequences_.clear();
return true;
}
@@ -906,6 +928,7 @@ bool NavigationServer::removeAllData()
{
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_.clear();
static_map_sequences_.clear();
laser_scans_.clear();
point_clouds_.clear();
point_cloud2s_.clear();

View File

@@ -8,7 +8,9 @@
*********************************************************************/
#include <move_base2/runners/planner_runner.h>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <exception>
#include <utility>
@@ -19,12 +21,51 @@
#include <robot/plugin_loader_helper.h>
#include <robot/robot.h>
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_costmap_2d/direction_field.h>
#include <robot_costmap_2d/layer.h>
#include <robot_costmap_2d/layered_costmap.h>
namespace move_base2
{
namespace
{
// Called with the master mutex held. Direction providers own a separate mutex, so their
// snapshot is the race-free equivalent of Layer::isCurrent() for those layers.
bool costmapReady(robot_costmap_2d::LayeredCostmap& costmap, std::string* stale_names)
{
const auto& layers = *costmap.getPlugins();
std::size_t providers = 0;
for (const auto& layer : layers)
if (layer && layer->isEnabled() &&
dynamic_cast<const robot_costmap_2d::DirectionFieldProvider*>(layer.get()))
++providers;
bool ready = true;
if (stale_names)
stale_names->clear();
for (const auto& layer : layers)
{
if (!layer || !layer->isEnabled())
continue;
const auto* provider = dynamic_cast<const robot_costmap_2d::DirectionFieldProvider*>(layer.get());
const bool current = provider
? providers == 1 && provider->directionSnapshot().state != robot_costmap_2d::DirectionFieldState::kPending
: layer->getType() != robot_costmap_2d::LayerType::DIRECTIONAL_LAYER && layer->isCurrent();
if (!current)
{
ready = false;
if (stale_names)
{
if (!stale_names->empty())
stale_names->append(", ");
stale_names->append(layer->getName());
}
}
}
return ready;
}
/// @brief Pose có dùng được để lập plan không — NaN/Inf lọt vào SBPL là hỏng ở tầng khó truy nhất.
bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose)
{
@@ -43,14 +84,22 @@ bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose)
/// hai công thức khác nhau, trùng tên là mời gọi đặt nhầm giá trị.
///
/// `dock_anchor` khai goal pose của marker nằm ở tâm footprint dock (`center`) hay ngay trên mặt
/// tiếp cận (`face`). `face` thì DockPlanner bỏ qua `footprint_dock` hoàn toàn.
/// tiếp cận (`face`). `mating_edge` dùng goal đã offset tới pose base_link lúc dock xong;
/// `face` và `mating_edge` khiến DockPlanner bỏ qua `footprint_dock` hoàn toàn.
/// `dock_face_offset` và `dock_pivot_safety_margin` là override DockPlanner chỉ có tác dụng với
/// `dock_anchor: mating_edge`; khai với `center` hoặc `face` khiến DockPlanner từ chối khởi tạo.
/// Nếu marker sau không khai, giá trị cũ được đặt YAML null để plugin trở về mặc định.
///
/// KHÔNG có `terminal_direction` ở đây, và cố ý như vậy: chiều chạy của đoạn thẳng cuối được SUY RA
/// từ phía robot đứng so với goal (`dock_calc.cpp`), vì tầng trên đã offset goal sao cho base_link
/// dừng đúng tại đó khi manơ hoàn tất. Một khoá cho phép marker ép chiều khác sẽ mâu thuẫn với
/// chính vị trí goal, nên khoá đó đã được gỡ thay vì hiện thực.
constexpr const char* kMarkerPlannerParams[] = {
"footprint_dock", "dock_anchor"
"footprint_dock", "dock_anchor", "dock_face_offset", "dock_pivot_safety_margin"
};
constexpr const char* kOptionalMarkerPlannerParams[] = {
"dock_face_offset", "dock_pivot_safety_margin"
};
/**
@@ -312,36 +361,54 @@ bool PlannerRunner::bindDockingMarker(const std::string& marker, const std::stri
}
const std::string profile_ns = "docking_marker_profiles/" + marker;
if (!nh_.hasParam(profile_ns))
{
// Marker hợp lệ nhưng không có profile riêng: cặp planner mặc định, không có gì để chép. Không
// phải lỗi — `maker_sources` mới là allow-list, bảng profile chỉ là override.
return true;
}
const bool has_profile = nh_.hasParam(profile_ns);
// Namespace phải được kiểm TRƯỚC khi dựng NodeHandle: `robot::NodeHandle` không báo lỗi khi
// namespace không resolve được mà lặng lẽ rơi về namespace cha. Bỏ qua bước này thì marker gõ sai
// sẽ đọc `footprint` ở ROOT — tức footprint ROBOT — rồi dùng nó làm kích thước trạm dock.
robot::NodeHandle marker_nh(nh_, profile_ns);
robot::NodeHandle planner_nh(nh_, planner_name);
if (marker_nh.getNamespace() == nh_.getNamespace() ||
planner_nh.getNamespace() == nh_.getNamespace())
const bool marker_namespace_invalid =
has_profile && marker_nh.getNamespace() == nh_.getNamespace();
const bool planner_namespace_invalid =
planner_nh.getNamespace() == nh_.getNamespace();
if (marker_namespace_invalid || (has_profile && planner_namespace_invalid))
{
robot::log_error("[move_base2] PlannerRunner: namespace '%s' or '%s' does not resolve in the "
"param tree; refusing to bind marker '%s'.\n",
profile_ns.c_str(), planner_name.c_str(), marker.c_str());
return false;
}
if (!has_profile && planner_namespace_invalid)
{
// Marker hợp lệ nhưng không có profile riêng: giữ nguyên hành vi cũ nếu planner namespace
// chưa tồn tại; không có nơi an toàn để xoá override per-marker.
return true;
}
bool copied = false;
for (const char* key : kMarkerPlannerParams)
if (has_profile)
{
copied = copyParamNode(marker_nh, planner_nh, key) || copied;
for (const char* key : kMarkerPlannerParams)
{
copied = copyParamNode(marker_nh, planner_nh, key) || copied;
}
}
for (const char* key : kOptionalMarkerPlannerParams)
{
if ((!has_profile || !marker_nh.hasParam(key)) && planner_nh.hasParam(key))
{
// Không để override rò sang marker trước: DockPlannerConfig đọc YAML null như chưa khai.
// footprint_dock và dock_anchor giữ nguyên cách xử lý cũ.
planner_nh.setParam(key, YAML::Node(YAML::NodeType::Null));
copied = true;
}
}
if (!copied)
{
return true; // Profile có tồn tại nhưng không khai khoá nào của planner — giữ nguyên cấu hình.
return true; // Không có khoá planner mới hoặc override tuỳ chọn nào cần xoá.
}
// Dựng lại instance CHỈ khi marker nối vào planner này thực sự đổi. Dock lại đúng marker cũ thì
@@ -404,6 +471,9 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
// Thread chưa nhận: rút yêu cầu ra, kẻo nó chạy yêu cầu của planner cũ trên instance mới rồi
// vứt — tốn một lượt makePlan vô ích.
pending_ = false;
waiting_for_costmap_ = false;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
request_order_.reset();
}
else if (running_)
@@ -419,6 +489,7 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
}
active_ = planner;
active_external_grid_ = external_grid ? &external_grid : nullptr;
cv_.notify_all();
}
active_name_ = planner_name;
@@ -484,6 +555,9 @@ bool PlannerRunner::startPlan(const robot_geometry_msgs::PoseStamped& start,
pending_ = true;
discard_ = false;
has_result_ = false;
waiting_for_costmap_ = costmap_lock_enabled_ && costmap_ready_timeout_ > 0.0;
if (waiting_for_costmap_ && status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kWaitingForCostmap);
cv_.notify_one();
return true;
@@ -495,6 +569,20 @@ bool PlannerRunner::isPlanning() const
return pending_ || running_;
}
void PlannerRunner::setCostmapReadyTimeout(double seconds)
{
std::lock_guard<std::mutex> lock(mutex_);
costmap_ready_timeout_ = seconds;
}
bool PlannerRunner::costmapWaitState(bool& finished)
{
std::lock_guard<std::mutex> lock(mutex_);
finished = costmap_wait_finished_;
costmap_wait_finished_ = false;
return waiting_for_costmap_;
}
bool PlannerRunner::pollPlan(PlanResult& result)
{
std::lock_guard<std::mutex> lock(mutex_);
@@ -541,6 +629,9 @@ void PlannerRunner::cancelPlan()
// sẽ nhận job này NGAY SAU cancel, chạy trọn allocated_time cho một plan không ai cần (bắt được
// bằng test CancelPreemptsAPreemptablePlannerWithinMilliseconds, 2026-09-11).
pending_ = false;
waiting_for_costmap_ = false;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
request_order_.reset();
}
else if (pending_ || running_)
@@ -562,6 +653,7 @@ void PlannerRunner::cancelPlan()
// Kết quả đã nằm sẵn trong hộp thư cũng bỏ luôn: bên gọi vừa nói nó không còn cần plan này.
has_result_ = false;
handoff_.clear();
cv_.notify_all();
}
// ================================================================================================
@@ -591,15 +683,16 @@ void PlannerRunner::threadBody()
// control thread không bao giờ phải chờ một lượt lập plan.
robot_nav_core::BaseGlobalPlanner* planner = active_;
const ExternalGridSetter* external_grid = active_external_grid_;
running_planner_ = planner;
running_planner_ = nullptr;
const robot_geometry_msgs::PoseStamped start = request_start_;
const robot_geometry_msgs::PoseStamped goal = request_goal_;
const std::shared_ptr<robot_protocol_msgs::Order> order = request_order_;
const std::uint64_t tag = request_tag_;
const double ready_timeout = costmap_ready_timeout_;
pending_ = false;
running_ = true;
if (status_board_ != nullptr)
if (status_board_ != nullptr && !waiting_for_costmap_)
{
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
}
@@ -608,10 +701,10 @@ void PlannerRunner::threadBody()
planning_.clear();
bool ok = false;
bool waited = false;
try
{
ScopedSection timer(stats_, section_make_plan_);
// Planner phải thấy một lưới ĐÔNG CỨNG suốt makePlan: LayeredCostmap::updateMap ghi lưới, và
// resizeMap REALLOC cả mảng, dưới Costmap2D::getMutex(). Hai cách đạt được điều đó:
//
@@ -624,32 +717,118 @@ void PlannerRunner::threadBody()
// đứng chờ hết lượt search; với SBPL cạn search trên map lớn là 6-14 s (đo 2026-09-17).
// Đây là đường rơi về khi tắt snapshot hoặc plugin không nhận lưới ngoài.
//
// Kiểm "costmap đã sẵn sàng" (P4, Test/docs/DIRECTION_ZONE_PLAN.md mục 7.3) chạy dưới CÙNG lần
// khoá đó, nên lưới planner đọc chính là lưới vừa được xác nhận current. Chưa current thì nhả
// khoá, chờ có hạn `costmap_ready_timeout` rồi kiểm lại; không gọi makePlan trên map dở dang.
//
// Lấy getCostmap() mỗi lượt, không cache — con trỏ đó có thể bị thay (bài học double-free của
// workspace). Với capability có mà snapshot TẮT, vẫn gọi setter với nullptr: xoá lưới ngoài
// còn sót từ cấu hình trước, để planner đọc lưới sống dưới khoá dài đúng như (b).
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
if (costmap_lock_enabled_)
using Clock = std::chrono::steady_clock;
Clock::time_point wait_started;
std::string& stale_names = costmap_stale_names_;
while (true)
{
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
const bool has_setter = external_grid != nullptr && static_cast<bool>(*external_grid);
if (has_setter && costmap_->isSnapshotEnabled())
const bool use_snapshot = costmap_lock_enabled_ && has_setter && costmap_->isSnapshotEnabled();
if (costmap_lock_enabled_)
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*costmap_->getCostmap()->getMutex());
// updateMap and StaticLayer callbacks use this same master mutex. For a snapshot, the
// recursive mutex remains held across both readiness and refreshSnapshot's copy. For a
// live grid it stays held through makePlan. Direction providers use their own snapshot lock.
if (costmap_lock_enabled_ && ready_timeout > 0.0 && !costmap_stale_names_reserved_)
{
std::size_t capacity = 0;
for (const auto& layer : *costmap_->getLayeredCostmap()->getPlugins())
if (layer) capacity += layer->getName().size() + 2;
stale_names.reserve(capacity);
costmap_stale_names_reserved_ = true;
}
const bool ready = !costmap_lock_enabled_ || ready_timeout == 0.0 ||
costmapReady(*costmap_->getLayeredCostmap(), &stale_names);
const auto now = Clock::now();
if (!ready && !waited)
{
waited = true;
wait_started = now;
if (!costmap_wait_problem_active_)
{
costmap_wait_problem_active_ = true;
last_costmap_wait_log_ = now;
robot::log_warning("[move_base2] PlannerRunner: waiting for global costmap; not current: %s\n",
stale_names.c_str());
}
}
const double elapsed = waited ? std::chrono::duration<double>(now - wait_started).count() : 0.0;
const CostmapReadyDecision decision = costmapReadyDecision(ready, elapsed, ready_timeout);
if (decision == CostmapReadyDecision::kTimeout)
{
if (last_costmap_timeout_log_ == Clock::time_point{} ||
std::chrono::duration<double>(now - last_costmap_timeout_log_).count() >= 5.0)
{
robot::log_error("[move_base2] PlannerRunner: global costmap readiness timed out after %.2f s; not current: %s\n",
elapsed, stale_names.c_str());
last_costmap_timeout_log_ = now;
}
break;
}
if (decision == CostmapReadyDecision::kWait)
{
if (std::chrono::duration<double>(now - last_costmap_wait_log_).count() >= 5.0)
{
robot::log_warning("[move_base2] PlannerRunner: still waiting for global costmap (%.2f s); not current: %s\n",
elapsed, stale_names.c_str());
last_costmap_wait_log_ = now;
}
costmap_lock.unlock();
lock.lock();
const double poll_seconds = std::min(0.05, ready_timeout - elapsed);
cv_.wait_for(lock, std::chrono::duration<double>(poll_seconds),
[this] { return shutdown_ || discard_; });
const bool cancelled = shutdown_ || discard_;
lock.unlock();
if (cancelled)
break;
continue;
}
if (use_snapshot)
{
costmap_->refreshSnapshot();
(*external_grid)(planner, costmap_->getCostmapForRead());
}
else
else if (costmap_lock_enabled_ && has_setter)
(*external_grid)(planner, nullptr);
lock.lock();
const bool cancelled = shutdown_ || discard_;
waiting_for_costmap_ = false;
costmap_wait_finished_ = costmap_wait_finished_ || waited;
if (!cancelled)
{
if (has_setter)
{
(*external_grid)(planner, nullptr);
}
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
running_planner_ = planner;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
}
lock.unlock();
if (cancelled)
break;
if (use_snapshot)
costmap_lock.unlock();
if (costmap_wait_problem_active_)
{
robot::log_info("[move_base2] PlannerRunner: global costmap is ready; planning resumes.\n");
costmap_wait_problem_active_ = false;
last_costmap_timeout_log_ = Clock::time_point{};
}
ScopedSection timer(stats_, section_make_plan_);
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
break;
}
// Hai overload của interface gốc gộp lại: "có Order hay không" là một nhánh, không phải hai
// contract. Plugin nào không hiểu Order thì overload mặc định của nó tự lo.
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
}
catch (const std::exception& ex)
{
@@ -675,6 +854,9 @@ void PlannerRunner::threadBody()
}
lock.lock();
if (waiting_for_costmap_ && waited)
costmap_wait_finished_ = true;
waiting_for_costmap_ = false;
running_ = false;
running_planner_ = nullptr;
if (status_board_ != nullptr)

View File

@@ -540,6 +540,13 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
break;
}
// Waiting for input is not planning time and must not consume the retry budget.
// The completion event also covers a wait which began and ended between control cycles.
if (in.planner_costmap_wait_finished || in.planner == PlannerFeedback::kWaitingForCostmap)
last_valid_plan_ = in.now;
if (in.planner == PlannerFeedback::kWaitingForCostmap)
break;
if (in.planner == PlannerFeedback::kPlanReady)
{
out.apply_plan = true;

View File

@@ -94,7 +94,8 @@ TEST(ComponentStatusBoard, EveryComponentAndPhaseHasAName)
EXPECT_NE(name, "unknown");
}
for (const ComponentPhase p : {ComponentPhase::kIdle, ComponentPhase::kBusy, ComponentPhase::kStopping,
ComponentPhase::kPaused, ComponentPhase::kHung})
ComponentPhase::kPaused, ComponentPhase::kHung,
ComponentPhase::kWaitingForCostmap})
{
const std::string name = move_base2::toString(p);
EXPECT_FALSE(name.empty());

View File

@@ -11,6 +11,7 @@
#include <gtest/gtest.h>
#include <cstdlib>
#include <limits>
#include <string>
#include <robot/node_handle.h>
@@ -55,6 +56,35 @@ TEST(MoveBase2Config, DefaultsAreValid)
EXPECT_TRUE(config.validate(error)) << error;
}
TEST(MoveBase2Config, CostmapReadyTimeoutValidation)
{
MoveBase2Config config = minimalValid();
std::string error;
EXPECT_DOUBLE_EQ(config.costmap_ready_timeout, 10.0);
EXPECT_DOUBLE_EQ(config.toControlLoopConfig().costmap_ready_timeout, 10.0);
EXPECT_NE(config.describe().find("costmap_ready_timeout"), std::string::npos);
config.costmap_ready_timeout = 0.0;
EXPECT_TRUE(config.validate(error));
for (double invalid : {-1.0, std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::quiet_NaN()})
{
config.costmap_ready_timeout = invalid;
EXPECT_FALSE(config.validate(error));
EXPECT_NE(error.find("costmap_ready_timeout"), std::string::npos);
}
}
TEST(MoveBase2Config, ReadsCostmapReadyTimeout)
{
robot::NodeHandle root;
robot::NodeHandle nh(root, "costmap_ready_timeout_test");
nh.setParam("costmap_ready_timeout", 3.5);
MoveBase2Config config;
config.fromNodeHandle(nh);
EXPECT_DOUBLE_EQ(config.costmap_ready_timeout, 3.5);
EXPECT_DOUBLE_EQ(config.toControlLoopConfig().costmap_ready_timeout, 3.5);
}
TEST(MoveBase2Config, CancelSettleKeysFallBackToDefaultsWhenAbsent)
{
// Cây config cũ (trước 2026-09-11) không có ba khoá này: phải giữ default BẬT (2 s, 0.02) chứ

View File

@@ -13,6 +13,7 @@
#include <chrono>
#include <cmath>
#include <cstddef>
#include <future>
#include <limits>
#include <string>
#include <thread>
@@ -195,7 +196,6 @@ public:
server_.attachCostmaps(&global_, &local_);
}
NavigationServer server_;
FakeClockPort clock_;
FakePosePort pose_;
FakePlannerPort planner_;
@@ -208,6 +208,10 @@ public:
robot_costmap_2d::LayeredCostmap global_;
robot_costmap_2d::LayeredCostmap local_;
// The server joins its control thread in its destructor. Declare it last so all borrowed
// ports, status data and costmaps outlive that join.
NavigationServer server_;
};
} // namespace
@@ -611,6 +615,74 @@ TEST(NavigationServerSensors, StaticMapReceivedBeforeAttachIsReplayed)
EXPECT_EQ(static_layer->records()[0].topic, "/map");
}
TEST(CostmapReadyDecision, ReadyWaitTimeoutAndLegacy)
{
using move_base2::CostmapReadyDecision;
using move_base2::costmapReadyDecision;
EXPECT_EQ(costmapReadyDecision(false, 0.0, 10.0), CostmapReadyDecision::kWait);
EXPECT_EQ(costmapReadyDecision(false, 9.99, 10.0), CostmapReadyDecision::kWait);
EXPECT_EQ(costmapReadyDecision(false, 10.0, 10.0), CostmapReadyDecision::kTimeout);
EXPECT_EQ(costmapReadyDecision(true, 3.0, 10.0), CostmapReadyDecision::kPlan);
EXPECT_EQ(costmapReadyDecision(false, 0.0, 0.0), CostmapReadyDecision::kPlan);
}
TEST(NavigationServerSensors, ReplayUsesLatestArrivalOrder)
{
Fixture fixture;
fixture.configure();
const robot_nav_msgs::OccupancyGrid grid;
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
SpyPtr layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "replay_spy");
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 2U);
EXPECT_EQ(layer->records()[0].topic, "/map");
EXPECT_EQ(layer->records()[1].topic, "/direction_map");
// The live pushes are followed by a second replay after both latest arrivals.
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 6U);
EXPECT_EQ(layer->records()[4].topic, "/map");
EXPECT_EQ(layer->records()[5].topic, "/direction_map");
}
TEST(NavigationServerSensors, ReplayForgetsErasedAndClearedSequences)
{
Fixture fixture;
fixture.configure();
const robot_nav_msgs::OccupancyGrid grid;
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
ASSERT_TRUE(fixture.server_.removeStaticMap("/map"));
fixture.server_.addStaticMap("/map", grid);
SpyPtr layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "replay_spy");
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 2U);
EXPECT_EQ(layer->records()[0].topic, "/direction_map");
EXPECT_EQ(layer->records()[1].topic, "/map");
ASSERT_TRUE(fixture.server_.removeAllStaticMaps());
fixture.server_.addStaticMap("/direction_map", grid);
const std::size_t before_clear_replay = layer->count();
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), before_clear_replay + 1U);
EXPECT_EQ(layer->records()[before_clear_replay].topic, "/direction_map");
ASSERT_TRUE(fixture.server_.removeAllData());
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
fixture.server_.map_name_save_ = "/legacy";
const std::size_t before_replay = layer->count();
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), before_replay + 3U);
EXPECT_EQ(layer->records()[before_replay].topic, "/legacy");
EXPECT_EQ(layer->records()[before_replay + 1].topic, "/map");
EXPECT_EQ(layer->records()[before_replay + 2].topic, "/direction_map");
}
TEST(NavigationServerSensors, LegacyMapSavePublicMemberIsAlsoReplayed)
{
// `map_save_`/`map_name_save_` là biến PUBLIC của BaseNavigation mà host tự gán
@@ -1203,12 +1275,33 @@ TEST(NavigationServerControlThread, SecondStartIsRefusedAndStopIsIdempotent)
TEST(NavigationServerControlThread, DestructorStopsTheThread)
{
// Thread chạm loop_, runtime_ và sensors_ mỗi cycle; huỷ chúng khi thread còn sống là hỏng ở chỗ
// không truy được.
Fixture fixture;
fixture.configure();
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
SUCCEED(); // destructor của fixture phải join, không treo
// Wait until a real cycle has begun; fixture destruction must join before its borrowed ports die.
class SignallingClock final : public move_base2::ClockPort
{
public:
explicit SignallingClock(std::promise<void>& started) : started_(started) {}
robot::Time now() const override
{
if (!signalled_.exchange(true))
started_.set_value();
return robot::Time(kClockStart);
}
private:
std::promise<void>& started_;
mutable std::atomic<bool> signalled_{false};
};
std::promise<void> started;
auto first_cycle = started.get_future();
SignallingClock clock(started);
{
Fixture fixture;
fixture.deps_.clock = &clock;
fixture.configure();
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
ASSERT_EQ(first_cycle.wait_for(std::chrono::seconds(2)), std::future_status::ready);
}
}
// ================================================================================================

View File

@@ -774,6 +774,51 @@ TEST(PlannerRunnerDockingMarker, ProfileWithoutFootprintDockIsAcceptedAndChanges
EXPECT_EQ(pluginInitializeCount(), before);
}
TEST(PlannerRunnerDockingMarker, CopiesAndClearsOptionalDockOverridesPerMarker)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
robot::NodeHandle nh;
// Create isolated profiles in the shared test parameter tree so this test does not alter the
// checked-in fixture or affect the existing dock_a/dock_b footprint tests.
nh.setParam("docking_marker_profiles/dock_override/dock_face_offset", 0.40);
nh.setParam("docking_marker_profiles/dock_override/dock_pivot_safety_margin", 0.10);
nh.setParam("docking_marker_profiles/dock_no_override/global_planner",
YAML::Node("TestPlannerOk"));
const std::size_t before = pluginInitializeCount();
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_override", "TestPlannerOk"));
YAML::Node copied_face_offset;
YAML::Node copied_margin;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_face_offset", copied_face_offset));
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_pivot_safety_margin", copied_margin));
EXPECT_DOUBLE_EQ(copied_face_offset.as<double>(), 0.40);
EXPECT_DOUBLE_EQ(copied_margin.as<double>(), 0.10);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 1);
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_no_override", "TestPlannerOk"));
YAML::Node cleared_face_offset;
YAML::Node cleared_margin;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_face_offset", cleared_face_offset));
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_pivot_safety_margin", cleared_margin));
EXPECT_TRUE(cleared_face_offset.IsNull());
EXPECT_TRUE(cleared_margin.IsNull());
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 2);
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_override", "TestPlannerOk"));
YAML::Node restored_face_offset;
YAML::Node restored_margin;
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_face_offset", restored_face_offset));
ASSERT_TRUE(nh.getParam("TestPlannerOk/dock_pivot_safety_margin", restored_margin));
EXPECT_DOUBLE_EQ(restored_face_offset.as<double>(), 0.40);
EXPECT_DOUBLE_EQ(restored_margin.as<double>(), 0.10);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before + 3);
}
TEST(PlannerRunnerDockingMarker, EmptyMarkerOrPlannerNameIsANoOp)
{
Fixture fixture;

View File

@@ -152,6 +152,27 @@ TEST(SensorGateway, StaticMapArrivesWithOccupancyGridType)
EXPECT_TRUE(*layer->records()[0].type == typeid(robot_nav_msgs::OccupancyGrid));
}
TEST(SensorGateway, DirectionalLayerSeesAStaticMapBeforeTheStaticLayer)
{
// A same-geometry map must invalidate the old direction field before StaticLayer can be written
// and report current; otherwise a plan could pair the new map with the old zones (DIRECTION_ZONE_PLAN 5.3).
Bench bench;
std::vector<std::string> order;
SpyPtr static_layer = bench.addGlobal(LayerType::STATIC_LAYER, "navigation_map");
SpyPtr directional = bench.addGlobal(LayerType::DIRECTIONAL_LAYER, "direction_zones");
static_layer->setObserver([&](const void*, const std::type_info&, const std::string&) {
order.push_back("static");
});
directional->setObserver([&](const void*, const std::type_info&, const std::string&) {
order.push_back("directional");
});
bench.attach();
bench.gateway().pushStaticMap("/map", robot_nav_msgs::OccupancyGrid());
EXPECT_EQ(order, (std::vector<std::string>{"directional", "static"}));
}
TEST(SensorGateway, PointCloudAndPointCloud2AreDistinctTypes)
{
Bench bench;
@@ -220,6 +241,27 @@ TEST(SensorGateway, ObstacleDataGoesOnlyToVoxelLayers)
EXPECT_EQ(inflation->count(), 0U);
}
TEST(SensorGateway, DepthCameraLayerGetsPointCloud2Only)
{
// DepthCameraObstacleLayer has its own LayerType: it must get the camera cloud, and neither the
// depth image (it does not use it) nor anything meant for the lidar layers.
Bench bench;
SpyPtr depth_layer = bench.addLocal(LayerType::DEPTH_CAMERA_LAYER, "depth_obstacles");
SpyPtr global_depth = bench.addGlobal(LayerType::DEPTH_CAMERA_LAYER, "depth_obstacles");
SpyPtr voxel = bench.addLocal(LayerType::VOXEL_LAYER, "lidar_obstacles");
bench.attach();
bench.gateway().pushLaserScan("/f_scan", makeScan());
bench.gateway().pushPointCloud("/pc", robot_sensor_msgs::PointCloud());
bench.gateway().pushPointCloud2("/camera/depth/points_proc", robot_sensor_msgs::PointCloud2());
bench.gateway().pushDepthCameraData("/camera/depth/data", makeDepth());
ASSERT_EQ(depth_layer->count(), 1U);
EXPECT_TRUE(*depth_layer->records()[0].type == typeid(robot_sensor_msgs::PointCloud2));
EXPECT_EQ(global_depth->count(), 1U);
EXPECT_EQ(voxel->count(), 4U); // the voxel layers keep getting everything, as before
}
TEST(SensorGateway, LayerNamedAfterATopicDoesNotReceiveTheSample)
{
// Hồi quy cho C5. Bản `move_base` cũ lọc bằng

View File

@@ -393,6 +393,31 @@ TEST(StateMachinePlanning, PlannerPatienceEscalatesToRecovery)
EXPECT_TRUE(out.stop_planner);
}
TEST(StateMachinePlanning, CostmapWaitDoesNotSpendPatienceOrRetries)
{
StateMachineConfig config = baseConfig();
config.max_planning_retries = 0;
Driver driver(config);
StateMachineInput request;
request.has_pending_request = true;
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
StateMachineInput waiting;
waiting.planner = PlannerFeedback::kWaitingForCostmap;
for (int i = 0; i < 20; ++i)
{
driver.advance(0.6);
EXPECT_EQ(driver.tick(waiting).state, NavigationState::kPlanning);
}
StateMachineInput busy;
busy.planner = PlannerFeedback::kBusy;
busy.planner_costmap_wait_finished = true;
driver.advance(0.6);
EXPECT_EQ(driver.tick(busy).state, NavigationState::kPlanning);
driver.advance(0.6);
EXPECT_EQ(driver.tick(StateMachineInput()).state, NavigationState::kPlanning);
EXPECT_EQ(driver.tick(plannerFailed()).state, NavigationState::kRecovering);
}
TEST(StateMachinePlanning, MaxRetriesEscalatesBeforePatienceExpires)
{
StateMachineConfig config = baseConfig();

View File

@@ -596,6 +596,39 @@ TEST(ControlLoop, BackupPlannerFailureEscalatesToRecovery)
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed);
}
// Backup chỉ dành cho position. Docking/go_straight/rotate fail thì đi thẳng recovery, planner chính
// giữ nguyên — robot KIT 26/10: SBPL thay DockPlanner dựng đường thẳng vào dock, bỏ qua cusp.
TEST(ControlLoop, NonPositionPlannerFailureSkipsBackup)
{
for (const MotionProfile profile :
{MotionProfile::kDocking, MotionProfile::kGoStraight, MotionProfile::kRotate})
{
SCOPED_TRACE(toString(profile));
ControlLoopConfig config = baseConfig();
config.backup_global_planner_name = "FakeBackupGlobalPlanner";
config.state_machine.max_planning_retries = 0;
Fixture fixture(config);
fixture.planner_.setScript({PlannerScript::kFail, PlannerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning});
std::string reason;
NavigationRequest request = makeRequest(3.0, 73);
request.profile = profile;
ASSERT_TRUE(fixture.loop_.submit(request, reason)) << reason;
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
{
fixture.stepOnce();
}
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeGlobalPlanner");
EXPECT_EQ(fixture.planner_.makePlanCount(), 1u);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
EXPECT_EQ(fixture.recovery_.startCount(), 1u);
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed);
}
}
TEST(ControlLoop, PlannerFailureDrivesRecoveryThenSucceeds)
{
// Kịch bản thật: planner bế tắc cho tới khi recovery gỡ được thế, sau đó lập plan bình thường.

View File

@@ -72,6 +72,20 @@ TEST(Watchdog, IdleRowsAreNeverHung)
EXPECT_FALSE(dog.anyHung()) << "idle for a long time is not 'hung'";
}
TEST(Watchdog, WaitingForCostmapDoesNotConsumePlannerBudget)
{
ComponentStatusBoard board;
Watchdog dog;
std::string error;
WatchdogConfig c = fastConfig();
c.period = 0.0;
ASSERT_TRUE(dog.start(&board, c, error)) << error;
board.enter(Component::kGlobalPlanner, ComponentPhase::kWaitingForCostmap);
sleepMs(80);
dog.checkOnce();
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner));
}
TEST(Watchdog, BusyWithoutProgressBecomesHungAndRecoversOnProgress)
{
ComponentStatusBoard board;