This commit is contained in:
2026-08-06 15:17:59 +07:00
parent 701d25f952
commit 5375a9da9e
33 changed files with 3199 additions and 137 deletions

View File

@@ -136,6 +136,62 @@ void readDockingMarkerProfiles(robot::NodeHandle& nh, DockingMarkerProfiles& pro
}
}
/**
* @brief Đọc khối `path_monitor`.
*
* Khối vắng mặt = giám sát tuyến TẮT, hành vi y hệt trước 2026-08-04d. Đây là đường lùi thứ nhất
* (thứ hai là route `path_blocked`/`off_path` rỗng) — hai nút độc lập, cố ý.
*/
void readPathMonitor(robot::NodeHandle& nh, ControlLoopConfig::PathMonitorConfig& monitor)
{
robot::NodeHandle monitor_nh(nh, "path_monitor");
readBool(monitor_nh, "enabled", monitor.enabled);
readBool(monitor_nh, "path_blocked_enabled", monitor.path_blocked_enabled);
readBool(monitor_nh, "off_path_enabled", monitor.off_path_enabled);
readDouble(monitor_nh, "check_period", monitor.check_period);
readDouble(monitor_nh, "confirm_time", monitor.confirm_time);
readDouble(monitor_nh, "horizon", monitor.horizon);
readDouble(monitor_nh, "min_detour_distance", monitor.min_detour_distance);
readDouble(monitor_nh, "max_cross_track", monitor.max_cross_track);
readDouble(monitor_nh, "grace_after_new_plan", monitor.grace_after_new_plan);
std::vector<std::string> names;
monitor_nh.param("profiles", names, std::vector<std::string>{});
if (names.empty())
{
return; // Giữ mặc định: chỉ profile position.
}
monitor.profiles.clear();
for (const std::string& name : names)
{
if (name == "position")
{
monitor.profiles.push_back(MotionProfile::kPosition);
}
else if (name == "docking")
{
monitor.profiles.push_back(MotionProfile::kDocking);
}
else if (name == "go_straight")
{
monitor.profiles.push_back(MotionProfile::kGoStraight);
}
else if (name == "rotate")
{
monitor.profiles.push_back(MotionProfile::kRotate);
}
else
{
// Không đoán: tên lạ mà im lặng bỏ qua thì người vận hành tưởng đã bật giám sát cho profile
// đó. Cảnh báo rồi bỏ — profile lạ không thể tự sinh ra hành vi nào.
robot::log_warning("[move_base2] path_monitor/profiles: unknown profile '%s', ignored.\n",
name.c_str());
}
}
}
/// Các tham số chung của move_base2, dùng chung cho schema namespace và schema root-profile.
void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
{
@@ -146,6 +202,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
readDouble(nh, "planner_patience", config.state_machine.planner_patience);
readDouble(nh, "controller_patience", config.state_machine.controller_patience);
readDouble(nh, "sensor_patience", config.state_machine.sensor_patience);
readDouble(nh, "oscillation_timeout", config.state_machine.oscillation_timeout);
readDouble(nh, "oscillation_distance", config.state_machine.oscillation_distance);
readDouble(nh, "action_patience", config.state_machine.action_patience);
@@ -159,6 +216,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
readDouble(nh, "acc_lim_theta", config.velocity.max_accel_theta);
readSensors(nh, config.sensors);
readPathMonitor(nh, config.path_monitor);
readBool(nh, "docking_requires_marker", config.docking_requires_marker);
readString(nh, "recovery_namespace", config.recovery_namespace);
@@ -253,6 +311,54 @@ bool MoveBase2Config::validate(std::string& error) const
error = "planner_timeout is not finite [s]";
return false;
}
if (path_monitor.enabled)
{
// Chỉ kiểm khi BẬT: tham số vô nghĩa trong một khối đang tắt không có lý do gì để chặn boot.
if (!std::isfinite(path_monitor.check_period) || path_monitor.check_period <= 0.0)
{
error = "path_monitor/check_period must be > 0 [s]";
return false;
}
if (!std::isfinite(path_monitor.confirm_time) || path_monitor.confirm_time < 0.0)
{
error = "path_monitor/confirm_time must be >= 0 [s]";
return false;
}
if (!std::isfinite(path_monitor.horizon) || path_monitor.horizon < 0.0)
{
error = "path_monitor/horizon must be >= 0 [m] (0 = the blocked-path check is off)";
return false;
}
if (!std::isfinite(path_monitor.min_detour_distance) || path_monitor.min_detour_distance < 0.0)
{
error = "path_monitor/min_detour_distance must be >= 0 [m]";
return false;
}
if (!std::isfinite(path_monitor.max_cross_track) || path_monitor.max_cross_track < 0.0)
{
error = "path_monitor/max_cross_track must be >= 0 [m] (0 = the off-path check is off)";
return false;
}
if (!std::isfinite(path_monitor.grace_after_new_plan) ||
path_monitor.grace_after_new_plan < 0.0)
{
error = "path_monitor/grace_after_new_plan must be >= 0 [s]";
return false;
}
if (!(path_monitor.horizon > 0.0) && !(path_monitor.max_cross_track > 0.0))
{
// Bật khối mà tắt cả hai phép đo là mâu thuẫn: người khai tưởng giám sát đang chạy.
error = "path_monitor is enabled but both checks are off; set horizon > 0 [m] and/or "
"max_cross_track > 0 [m], or set enabled: false";
return false;
}
if (path_monitor.profiles.empty())
{
error = "path_monitor/profiles is empty; no leg would ever be monitored";
return false;
}
}
if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0)
{
error = "runtime_stats_period must be >= 0 [s] (0 = telemetry off)";
@@ -370,6 +476,7 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
readDouble(nh, "runtime_stats_period", runtime_stats_period);
readDouble(nh, "planner_patience", state_machine.planner_patience);
readDouble(nh, "controller_patience", state_machine.controller_patience);
readDouble(nh, "sensor_patience", state_machine.sensor_patience);
readDouble(nh, "oscillation_timeout", state_machine.oscillation_timeout);
readDouble(nh, "oscillation_distance", state_machine.oscillation_distance);
readInt(nh, "max_planning_retries", state_machine.max_planning_retries);
@@ -505,6 +612,7 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
config.velocity = velocity;
config.nominal_control_period =
controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s]
config.planner_frequency = planner_frequency; // [Hz] replan nền khi kControlling
config.robot_base_frame = robot_base_frame;
config.require_current_costmap = require_current_costmap;
config.position = position;
@@ -514,6 +622,7 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
config.rotate = rotate;
config.backup_global_planner_name = backup_global_planner_name;
config.docking_requires_marker = docking_requires_marker;
config.path_monitor = path_monitor;
return config;
}

View File

@@ -8,7 +8,9 @@
*********************************************************************/
#include <move_base2/control_loop.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <sstream>
#include <robot/console.h>
@@ -25,6 +27,58 @@ constexpr double kQuaternionNormTolerance = 1e-2;
/// điều khiển — log mỗi cycle sẽ nhấn chìm mọi dòng khác.
constexpr double kStaleCostmapLogThrottle = 5.0;
/// [s] Log debug tạm phục vụ test đường recovery/controller. Ngắn hơn throttle runtime mặc định để
/// không bị mất dấu trong các fail diễn ra trong vài trăm ms sau detour.
constexpr double kDebugControlLogThrottle = 0.2;
const char* toString(PlannerFeedback feedback)
{
switch (feedback)
{
case PlannerFeedback::kIdle:
return "idle";
case PlannerFeedback::kBusy:
return "busy";
case PlannerFeedback::kPlanReady:
return "plan_ready";
case PlannerFeedback::kFailed:
return "failed";
}
return "unknown";
}
const char* toString(ControllerFeedback feedback)
{
switch (feedback)
{
case ControllerFeedback::kIdle:
return "idle";
case ControllerFeedback::kCommandValid:
return "command_valid";
case ControllerFeedback::kNoValidCommand:
return "no_valid_command";
case ControllerFeedback::kGoalReached:
return "goal_reached";
}
return "unknown";
}
const char* toString(RecoveryFeedback feedback)
{
switch (feedback)
{
case RecoveryFeedback::kIdle:
return "idle";
case RecoveryFeedback::kRunning:
return "running";
case RecoveryFeedback::kSucceeded:
return "succeeded";
case RecoveryFeedback::kFailed:
return "failed";
}
return "unknown";
}
} // namespace
// ================================================================================================
@@ -46,6 +100,11 @@ bool ControlLoopConfig::validate(std::string& error) const
error = "nominal_control_period must be > 0 [s]";
return false;
}
if (!std::isfinite(planner_frequency) || planner_frequency < 0.0)
{
error = "planner_frequency must be >= 0 [Hz] (0 = no background replanning)";
return false;
}
if (position.local_planner_name.empty())
{
error = "profile 'position' must have local_planner_name";
@@ -77,6 +136,8 @@ std::string ControlLoopConfig::describe() const
out << velocity.describe();
out << "ControlLoop:\n";
out << " nominal_control_period: " << nominal_control_period << " s\n";
out << " planner_frequency : " << planner_frequency << " Hz"
<< (planner_frequency > 0.0 ? "" : " (no background replanning)") << '\n';
out << " robot_base_frame : " << robot_base_frame << '\n';
out << " profile position : " << position.global_planner_name << " / "
<< position.local_planner_name << '\n';
@@ -89,6 +150,11 @@ std::string ControlLoopConfig::describe() const
return out.str();
}
bool ControlLoopConfig::PathMonitorConfig::monitors(MotionProfile profile) const
{
return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
}
// ================================================================================================
// ControlLoop
// ================================================================================================
@@ -119,6 +185,54 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
config_ = config;
deps_ = deps;
// Bật giám sát mà không có đường xử lý nào là cấu hình vô nghĩa — và trước đây nó im lặng. Không
// chặn boot (navigation vẫn phải chạy), nhưng phải hét lên: người vận hành khai `enabled: true`
// thì tin rằng cơ chế đang chạy.
if (config_.path_monitor.enabled)
{
if (deps_.path_check == nullptr)
{
robot::log_error("[move_base2] path_monitor is enabled but no PathCheckPort is wired — path "
"monitoring stays OFF.\n");
}
else if (!config_.path_monitor.path_blocked_enabled && !config_.path_monitor.off_path_enabled)
{
robot::log_warning("[move_base2] path_monitor/enabled is true but BOTH sub-monitors are off "
"(path_blocked_enabled=false, off_path_enabled=false) — path monitoring "
"does nothing.\n");
}
else if (config_.state_machine.recovery_routes.path_blocked.empty() &&
config_.state_machine.recovery_routes.off_path.empty())
{
robot::log_error("[move_base2] path_monitor is enabled but BOTH recovery routes "
"'path_blocked' and 'off_path' are empty (behaviors failed to load?) — path "
"monitoring stays OFF.\n");
}
else
{
// In trạng thái THẬT của từng phép đo, đã gộp cả ba nút: đọc một dòng là biết cái nào sống.
const bool blocked_on = config_.path_monitor.path_blocked_enabled &&
config_.path_monitor.horizon > 0.0 &&
!config_.state_machine.recovery_routes.path_blocked.empty();
const bool off_path_on = config_.path_monitor.off_path_enabled &&
config_.path_monitor.max_cross_track > 0.0 &&
!config_.state_machine.recovery_routes.off_path.empty();
robot::log_info("[move_base2] path monitor ON (confirm=%.2f s, check=%.2f s):\n"
" path_blocked: %s (flag=%s, horizon=%.2f m, route=%zu)\n"
" off_path : %s (flag=%s, max_cross_track=%.2f m, route=%zu)\n",
config_.path_monitor.confirm_time, config_.path_monitor.check_period,
blocked_on ? "ON" : "OFF",
config_.path_monitor.path_blocked_enabled ? "on" : "off",
config_.path_monitor.horizon,
config_.state_machine.recovery_routes.path_blocked.size(),
off_path_on ? "ON" : "OFF",
config_.path_monitor.off_path_enabled ? "on" : "off",
config_.path_monitor.max_cross_track,
config_.state_machine.recovery_routes.off_path.size());
}
}
initialized_ = true;
reset();
return true;
@@ -153,6 +267,9 @@ void ControlLoop::reset()
has_last_cycle_time_ = false;
has_oscillation_origin_ = false;
last_plan_started_ = robot::Time();
resetPathMonitor();
has_last_plan_applied_ = false;
has_outcome_ = false;
outcome_report_count_ = 0;
@@ -394,6 +511,18 @@ void ControlLoop::collectPlannerResult()
// rỗng lọt xuống sẽ thành front()/back() trên vector rỗng ở tầng dưới.
if (!result.succeeded || result.plan.empty())
{
// Replan NỀN hỏng (đang kControlling): bỏ qua, plan cũ vẫn hiệu lực và robot đang bám nó bình
// thường. Không kích backup planner ở đây — một lượt replan nền hụt (robot đi qua vùng hẹp,
// costmap tạm bít) mà đổi hẳn sang SBPL là mất quỹ đạo NURBS của order cho phần còn lại của
// chặng. Backup chỉ dành cho lúc THẬT SỰ cần plan mà không có (kPlanning).
if (state_machine_.state() == NavigationState::kControlling)
{
robot::log_warning_throttle(5.0, "[move_base2] background replan failed; keeping the "
"current plan.\n");
planner_feedback_ = PlannerFeedback::kFailed;
return;
}
// 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ó.
@@ -421,10 +550,172 @@ void ControlLoop::collectPlannerResult()
return;
}
// Luật "không thay plan sạch bằng plan bẩn" (contract 2026-08-04d).
//
// Không có luật này thì cơ chế detour tự phá chính nó: `CustomPlanner` mù costmap nên mỗi nhịp
// `planner_frequency` nó trả lại đúng đường thẳng xuyên vật cản, ghi đè đường vòng vừa lập, rồi
// PathMonitor lại khai hoả — robot dừng-detour-chạy-dừng mỗi giây và ngân sách route cạn rất
// nhanh.
//
// Chỉ áp ở kControlling, nơi ĐANG có một plan để giữ. Ở kPlanning vẫn nhận plan bẩn như cũ:
// PathMonitor sẽ khai hoả ngay khi vào kControlling, nên mọi tình huống tuyến-bị-chắn đi qua đúng
// MỘT đường xử lý thay vì hai.
//
// Hệ quả đẹp: khi robot đã đi qua vật cản, plan thẳng của planner chính hết bị chắn nên được nhận
// lại — robot tự quay về đúng tuyến/NURBS của order, không cần cơ chế nào để "kết thúc detour".
if (state_machine_.state() == NavigationState::kControlling && !latest_plan_.empty() &&
planIsBlocked(result.plan, 0))
{
robot::log_warning_throttle(5.0, "[move_base2] a fresh plan runs into an obstacle; keeping the "
"current plan.\n");
planner_feedback_ = PlannerFeedback::kFailed;
return;
}
latest_plan_.swap(result.plan);
// Tuyến THAM CHIẾU của chặng = plan do PLANNER sinh, không phải plan đã bị recovery thay
// (contract 2026-08-05e). Detour nối lại vào nó nên robot tự quay về tuyến order thay vì trôi
// dần theo từng đường vòng, và `max_deviation` đo đúng hành lang mà fleet đã duyệt.
order_plan_ = latest_plan_;
planner_feedback_ = PlannerFeedback::kPlanReady;
}
void ControlLoop::resetPathMonitor()
{
path_blocked_ = false;
off_path_ = false;
has_last_path_check_ = false;
blocked_seen_ = false;
off_path_seen_ = false;
}
bool ControlLoop::planIsBlocked(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
std::size_t from_index) const
{
if (deps_.path_check == nullptr || !(config_.path_monitor.horizon > 0.0) || plan.empty())
{
return false;
}
PlanBlockResult result;
if (!deps_.path_check->checkPlan(plan, from_index, config_.path_monitor.horizon, result))
{
// Không kết luận được (thiếu TF/costmap). "Không biết" KHÔNG được suy thành "bẩn": làm vậy là
// robot dừng mỗi lần TF trễ một nhịp.
return false;
}
if (result.blocked)
{
last_block_distance_ = result.distance; // [m] chỉ để log; không tham gia quyết định.
}
return result.blocked && result.distance >= config_.path_monitor.min_detour_distance;
}
void ControlLoop::updatePathMonitor(const robot::Time& now,
const robot_geometry_msgs::PoseStamped& robot_pose,
bool pose_available, bool costmap_stale)
{
const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor;
// Cổng vào: chỉ giám sát khi thực sự đang bám một plan của một profile được phép, với dữ liệu còn
// dùng được. Thiếu bất kỳ điều kiện nào thì XOÁ luôn trạng thái debounce — nếu chỉ bỏ qua, chuỗi
// "đúng liên tục" sẽ được nối lại qua một quãng gián đoạn và `confirm_time` mất ý nghĩa.
const bool monitorable = cfg.enabled && deps_.path_check != nullptr && has_active_request_ &&
pose_available && !costmap_stale && !latest_plan_.empty() &&
state_machine_.state() == NavigationState::kControlling &&
cfg.monitors(active_request_.profile);
if (!monitorable)
{
resetPathMonitor();
return;
}
// Route rỗng = KHÔNG có đường xử lý cho trigger đó. Khai hoả trong tình trạng này là biến một cơ
// chế đang tắt thành ABORT tức thì: state machine thấy cờ, gọi escalateToRecovery, route cạn ngay
// từ phần tử đầu, và chặng chết ngay lần đầu thấy vật cản. Giám sát cái mà không ai xử lý được
// thì thà đừng giám sát — để `controller_patience` lo như trước khi có cơ chế này.
//
// Ba nút độc lập cho mỗi phép đo, cố ý: cờ riêng (`path_blocked_enabled`/`off_path_enabled`,
// 2026-08-06 — nói thẳng ý định thay vì đặt ngưỡng về 0), ngưỡng của chính nó, và route.
const bool blocked_route_ready = cfg.path_blocked_enabled &&
!config_.state_machine.recovery_routes.path_blocked.empty();
const bool off_path_route_ready = cfg.off_path_enabled &&
!config_.state_machine.recovery_routes.off_path.empty();
// Nhịp quét riêng: đọc vài chục ô costmap mỗi control cycle 30 Hz là phí, mà vật cản cũng không
// xuất hiện nhanh hơn chu kỳ cập nhật costmap (6 Hz).
if (has_last_path_check_ && (now - last_path_check_).toSec() < cfg.check_period)
{
return;
}
last_path_check_ = now;
has_last_path_check_ = true;
const std::size_t from = nearestIndex(latest_plan_, robot_pose);
// --- Phép đo 1: tuyến phía trước có bị chắn không -------------------------------------------
const bool blocked_now = blocked_route_ready && planIsBlocked(latest_plan_, from);
if (blocked_now)
{
if (!blocked_seen_)
{
blocked_since_ = now;
blocked_seen_ = true;
}
if (!path_blocked_ && (now - blocked_since_).toSec() >= cfg.confirm_time)
{
path_blocked_ = true;
robot::log_warning("[move_base2] PathMonitor: the path ahead is blocked at %.2f m (horizon "
"%.2f m) — stopping to plan a detour.\n",
last_block_distance_, cfg.horizon);
}
}
else
{
blocked_seen_ = false;
path_blocked_ = false;
}
// --- Phép đo 2: robot đã lệch khỏi plan bao xa ----------------------------------------------
//
// Đo so với PLAN ĐANG CHẠY, không phải tuyến gốc của order: sau một lượt detour hợp lệ, plan đang
// chạy CHÍNH LÀ đường vòng và robot nằm trên nó, nên không khai hoả oan. Ràng buộc "lệch bao
// nhiêu so với tuyến fleet" là việc của `max_deviation` bên trong behavior detour.
const bool grace = has_last_plan_applied_ &&
(now - last_plan_applied_).toSec() < cfg.grace_after_new_plan;
if (off_path_route_ready && cfg.max_cross_track > 0.0 && !grace)
{
const double error = crossTrackError(latest_plan_, robot_pose); // [m]
if (error > cfg.max_cross_track)
{
if (!off_path_seen_)
{
off_path_since_ = now;
off_path_seen_ = true;
}
if (!off_path_ && (now - off_path_since_).toSec() >= cfg.confirm_time)
{
off_path_ = true;
robot::log_warning("[move_base2] PathMonitor: the robot is %.2f m off the plan (limit "
"%.2f m) — stopping.\n", error, cfg.max_cross_track);
}
}
else
{
off_path_seen_ = false;
off_path_ = false;
}
}
else
{
off_path_seen_ = false;
off_path_ = false;
}
}
void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
{
candidate = robot_geometry_msgs::Twist();
@@ -486,6 +777,15 @@ bool ControlLoop::step()
travelled = std::hypot(dx, dy);
}
// Costmap còn hạn không — hỏi ở ĐÂY chứ không ở mục 3.5 như trước: PathMonitor cần nó, mà monitor
// phải chạy xong trước state machine. Vẫn là một lời gọi mỗi cycle, chỉ đổi vị trí.
const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr &&
!deps_.costmap_status->isCurrent();
// --- 1b. Giám sát tuyến ---------------------------------------------------------------------
// Chạy TRƯỚC state machine: hai cờ nó sinh ra là dữ liệu vào của state machine ngay cycle này.
updatePathMonitor(now, robot_pose, pose_available, costmap_stale);
// --- 2. State machine -----------------------------------------------------------------------
StateMachineInput input;
input.now = now;
@@ -500,8 +800,11 @@ bool ControlLoop::step()
input.recovery = recovery_feedback_;
input.action = action_feedback_;
input.pose_available = pose_available;
input.costmap_current = !costmap_stale;
input.robot_stopped = arbiter_.stopped();
input.travelled_since_oscillation_reset = travelled;
input.path_blocked = path_blocked_;
input.off_path = off_path_;
// Cùng một chỉ số dùng cho cả cycle khởi động recovery lẫn các cycle tick: state machine chỉ tăng
// chỉ số khi behavior kết thúc, nên `nextRecoveryIndex()` chính là behavior sắp chạy hoặc đang
@@ -516,6 +819,11 @@ bool ControlLoop::step()
if (output.state_changed)
{
last_reason_ = output.reason;
robot::log_info("[move_base2][debug] state -> %s: %s "
"(planner=%s controller=%s recovery=%s pose=%s active_request=%s).\n",
toString(output.state), output.reason != nullptr ? output.reason : "",
toString(input.planner), toString(input.controller), toString(input.recovery),
pose_available ? "yes" : "no", has_active_request_ ? "yes" : "no");
}
// Cờ một-lần đã được state machine tiêu thụ xong ở lời gọi trên.
@@ -542,6 +850,7 @@ bool ControlLoop::step()
has_active_request_ = true;
has_pending_request_ = false;
latest_plan_.clear();
order_plan_.clear();
has_outcome_ = false;
// Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop.
@@ -563,6 +872,10 @@ bool ControlLoop::step()
++plan_tag_;
deps_.planner->cancelPlan();
planner_running_ = false;
// Nhịp replan nền đếm lại từ đầu chặng — lượt plan đầu tiên của chặng do state machine yêu
// cầu, replan nền chỉ bắt đầu sau đó một chu kỳ đầy đủ.
last_plan_started_ = now;
}
if (output.reset_oscillation_origin && pose_available)
@@ -585,6 +898,28 @@ bool ControlLoop::step()
{
// Controller từ chối plan: coi như lần lập plan này hỏng, để chu kỳ kiên nhẫn tiếp tục chạy.
planner_feedback_ = PlannerFeedback::kFailed;
robot::log_error("[move_base2][debug] controller rejected plan with %zu pose(s); "
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
latest_plan_.size(), latest_plan_.front().pose.position.x,
latest_plan_.front().pose.position.y,
latest_plan_.front().header.frame_id.c_str(),
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
latest_plan_.back().header.frame_id.c_str());
}
else
{
// Mốc cho `grace_after_new_plan`: ngay sau khi đổi plan, pose robot có thể còn lệch so với
// plan vừa tới (rõ nhất lúc preempt/đổi chặng). Đo lệch tuyến ngay lúc đó là khai hoả oan.
last_plan_applied_ = now;
has_last_plan_applied_ = true;
robot::log_info("[move_base2][debug] controller accepted plan with %zu pose(s); "
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
latest_plan_.size(), latest_plan_.front().pose.position.x,
latest_plan_.front().pose.position.y,
latest_plan_.front().header.frame_id.c_str(),
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
latest_plan_.back().header.frame_id.c_str());
}
}
@@ -593,6 +928,19 @@ bool ControlLoop::step()
deps_.recovery->cancel();
}
// Giám sát tuyến hết đường vòng (contract 2026-08-05e): KHÔNG kết thúc chặng — robot bám tiếp
// plan cũ và trigger bị khoá tới khi đi được quá `oscillation_distance`. Log đúng MỘT dòng ở
// sườn khoá, vì sau đó nhánh monitor im lặng hoàn toàn và người vận hành sẽ không hiểu vì sao
// robot vẫn tiến về phía vật cản.
if (output.monitor_trigger_suppressed)
{
robot::log_warning("[move_base2] %s: no detour left — continuing on the current plan. From "
"here the controller is the only safety net: it stops at the obstacle and "
"controller_patience escalates to controlling_failed. This trigger stays "
"muted until the robot travels %.2f m.\n",
toString(output.recovery_trigger), config_.state_machine.oscillation_distance);
}
robot_geometry_msgs::Twist candidate;
if (output.start_recovery)
@@ -628,6 +976,13 @@ bool ControlLoop::step()
// Họ recovery sinh lại đường đi: coi kết quả như một plan mới, chờ state machine đẩy xuống.
latest_plan_ = tick.path;
planner_feedback_ = PlannerFeedback::kPlanReady;
robot::log_info("[move_base2][debug] recovery produced path with %zu pose(s); "
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
latest_plan_.size(), latest_plan_.front().pose.position.x,
latest_plan_.front().pose.position.y,
latest_plan_.front().header.frame_id.c_str(),
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
latest_plan_.back().header.frame_id.c_str());
}
}
@@ -677,8 +1032,6 @@ bool ControlLoop::step()
// nó đi là bịt mất lối phục hồi duy nhất còn tác dụng. Behavior họ velocity không bị thiệt vì
// chúng đo tiến độ bằng POSE: robot không nhúc nhích thì chúng tự hết giờ và báo hỏng, chứ không
// báo thành công nhầm.
const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr &&
!deps_.costmap_status->isCurrent();
if (costmap_stale)
{
// Throttle: đây là vòng lặp điều khiển, và tình trạng này kéo dài hàng giây.
@@ -687,12 +1040,67 @@ bool ControlLoop::step()
"costmap is describing a past world).\n");
}
if (output.state == NavigationState::kControlling && !pose_available)
{
robot::log_warning_throttle(
kDebugControlLogThrottle,
"[move_base2][debug] controller skipped while CONTROLLING: pose unavailable "
"(reason=%s, controller_feedback_in=%s, recovery_cursor=%zu/%zu).\n",
output.reason != nullptr ? output.reason : "", toString(input.controller),
output.recovery_route_cursor, output.recovery_route_size);
}
if (output.run_controller && costmap_stale)
{
robot::log_warning_throttle(
kDebugControlLogThrottle,
"[move_base2][debug] controller skipped while CONTROLLING: costmap stale "
"(reason=%s, controller_feedback_in=%s, recovery_cursor=%zu/%zu).\n",
output.reason != nullptr ? output.reason : "", toString(input.controller),
output.recovery_route_cursor, output.recovery_route_size);
}
if (output.run_controller && !costmap_stale)
{
runController(candidate);
if (controller_feedback_ == ControllerFeedback::kNoValidCommand)
{
robot::log_warning_throttle(
kDebugControlLogThrottle,
"[move_base2][debug] controller returned no valid command "
"(reason=%s, planner_in=%s, controller_in=%s, recovery_in=%s, pose=%s, "
"recovery_cursor=%zu/%zu).\n",
output.reason != nullptr ? output.reason : "", toString(input.planner),
toString(input.controller), toString(input.recovery), pose_available ? "yes" : "no",
output.recovery_route_cursor, output.recovery_route_size);
}
// else if (controller_feedback_ == ControllerFeedback::kCommandValid)
// {
// robot::log_info_throttle(kDebugControlLogThrottle,
// "[move_base2][debug] controller command valid: v=%.3f wz=%.3f.\n",
// candidate.linear.x, candidate.angular.z);
// }
}
if (output.start_planner && pose_available && !planner_running_)
// Replan nền (contract 2026-08-04): đang bám plan và tới nhịp `planner_frequency` thì khởi động
// một lượt lập plan mới trên thread planner. Plan mới về được kControlling nhận ngay (apply_plan)
// mà KHÔNG đổi state — controller không dừng một cycle nào. Đây là cơ chế thay plan duy nhất
// trong lúc chạy, vì controller hỏng không còn kéo máy về kPlanning nữa.
//
// Nhịp đếm lại mỗi lần (TÁI) vào kControlling: sau recovery bám tiếp plan cũ — hoặc nhận path
// detour — plan đó phải sống được trọn một chu kỳ planner_frequency trước khi lượt replan nền
// đầu tiên có quyền thay nó. Không đếm lại thì đồng hồ vẫn mang cả quãng thời gian nằm trong
// recovery và replan nền nổ ngay cycle đầu sau khi quay lại, đè mất path detour vừa nộp.
if (output.state_changed && output.state == NavigationState::kControlling)
{
last_plan_started_ = now;
}
const bool periodic_replan_due =
config_.planner_frequency > 0.0 && output.state == NavigationState::kControlling &&
(now - last_plan_started_).toSec() >= 1.0 / config_.planner_frequency;
if ((output.start_planner || periodic_replan_due) && pose_available && !planner_running_)
{
// `start_planner` là tín hiệu MỨC ("hãy đang lập plan"), bật lại mỗi cycle chừng nào state
// machine còn ở kPlanning — không phải sườn. Kick lại một lượt đang chạy sẽ vừa bị cổng từ
@@ -702,10 +1110,15 @@ bool ControlLoop::step()
const robot_protocol_msgs::Order* order =
backup_global_planner_active_ ? nullptr : active_request_.order.get();
planner_running_ = deps_.planner->startPlan(robot_pose, active_request_.goal, order, plan_tag_);
if (!planner_running_)
if (planner_running_)
{
last_plan_started_ = now;
}
else if (output.start_planner)
{
// Không khởi động được (chưa có planner, pose hỏng...). Coi như một lượt hỏng để đồng hồ
// kiên nhẫn tiếp tục chạy, thay vì đứng im ở kPlanning vô hạn.
// kiên nhẫn tiếp tục chạy, thay vì đứng im ở kPlanning vô hạn. Riêng replan NỀN không khởi
// động được thì bỏ qua — plan cũ vẫn hiệu lực, nhịp sau thử lại.
planner_feedback_ = PlannerFeedback::kFailed;
}
}
@@ -737,6 +1150,17 @@ bool ControlLoop::step()
static_cast<unsigned long long>(outgoing_mission_id));
break;
case NavigationOutcome::kFailed:
if (output.reason != nullptr &&
std::strcmp(output.reason, "no recovery behavior left") == 0)
{
robot::log_error("[move_base2][debug] abort detail: recovery route exhausted "
"(trigger=%s cursor=%zu size=%zu, planner_in=%s, controller_in=%s, "
"recovery_in=%s, pose=%s, costmap_current=%s).\n",
toString(output.recovery_trigger), output.recovery_route_cursor,
output.recovery_route_size, toString(input.planner),
toString(input.controller), toString(input.recovery),
pose_available ? "yes" : "no", costmap_stale ? "no" : "yes");
}
robot::log_error("[move_base2] Navigation failed (mission %llu: ABORTED): %s\n",
static_cast<unsigned long long>(outgoing_mission_id),
last_reason_ != nullptr ? last_reason_ : "");

View File

@@ -10,8 +10,11 @@
#include <exception>
#include <boost/thread/locks.hpp>
#include <robot/node_handle.h>
#include <robot/robot.h>
#include <robot_costmap_2d/costmap_2d.h>
#include <robot_nav_2d_utils/conversions.h>
#include <tf3/buffer_core.h>
@@ -54,6 +57,36 @@ bool CostmapPosePort::lookupPose(const std::string& frame,
}
}
bool CostmapPathCheck::checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
std::size_t from_index, double horizon,
PlanBlockResult& out) const
{
if (costmap_ == nullptr || !tf_ || plan.empty() || from_index >= plan.size())
{
return false;
}
robot_costmap_2d::Costmap2D* grid = costmap_->getCostmap();
if (grid == nullptr)
{
return false;
}
PlanarTransform plan_to_grid;
if (!planarTransform(*tf_, plan[from_index].header.frame_id, costmap_->getGlobalFrameID(),
plan_to_grid))
{
// Không quy đổi được frame thì mọi kết luận đều vô nghĩa. Trả false = "không biết".
return false;
}
// Cùng giao thức khoá với map-update thread và planner: lượt quét chỉ đọc vài chục ô nên giữ
// mutex trọn lượt là rẻ, còn đọc lưới trong lúc nó đang được ghi thì kết luận không đáng tin.
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()));
out = move_base2::checkPlan(plan, from_index, horizon, *grid, plan_to_grid);
return true;
}
NavigationRuntime::NavigationRuntime() = default;
NavigationRuntime::~NavigationRuntime()
@@ -131,6 +164,10 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf
// Costmap ĐIỀU KHIỂN (local) là nguồn của guard "không đi mù" — xem doc của CostmapStatusAdapter.
costmap_status_.setCostmap(local_costmap_.get());
// PathMonitor quét tuyến trên chính costmap local — cùng lưới mà detour lập đường vòng trên đó.
path_check_.setCostmap(local_costmap_.get());
path_check_.setTf(tf_);
// Gắn ngay: host có thể hỏi dữ liệu hiển thị bất cứ lúc nào sau initialize(), kể cả trước khi
// costmap có nội dung. Exporter tự trả về "chưa có gì" thay vì lưới rỗng.
global_exporter_.attach(global_costmap_.get(), config_.global_frame);
@@ -189,6 +226,9 @@ bool NavigationRuntime::buildRunners(std::string& error)
recovery_deps.pose = &local_pose_;
recovery_deps.local_costmap = local_costmap_.get();
recovery_deps.global_costmap = global_costmap_.get();
// Behavior họ path (DetourPathRecovery) lập đường vòng trên local costmap (frame odom) trong khi
// plan ở frame map — cần TF để quy đổi hai chiều.
recovery_deps.tf = tf_.get();
recovery_.setDeps(recovery_deps);
recovery_.setNamespace(config_.recovery_namespace);
@@ -370,6 +410,7 @@ ControlLoopDeps NavigationRuntime::deps()
deps.mission = &mission_;
deps.action = &action_;
deps.costmap_status = &costmap_status_;
deps.path_check = &path_check_;
return deps;
}

View File

@@ -436,6 +436,34 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
// vòng ngược lên xoá hàng đợi của nó.
runtime_->mission().setCancelCallback([this]() { requestLoopCancel(); });
// Behavior recovery họ path (DetourPathRecovery) cần plan hiện hành để chọn điểm nối lại tuyến.
// Callback chạy trên CONTROL THREAD — recovery chỉ được start/tick từ đó — cùng thread với
// latestPlan(), nên không cần lock.
runtime_->recoveryRunner().setPlanSource(
[this](std::vector<robot_geometry_msgs::PoseStamped>& out) {
const std::vector<robot_geometry_msgs::PoseStamped>& plan = loop_.latestPlan();
if (plan.empty())
{
return false;
}
out = plan;
return true;
});
// Tuyến THAM CHIẾU: plan gần nhất do PLANNER sinh, recovery không thay được. Detour nối lại vào
// nó nên robot tự quay về tuyến order thay vì trôi dần theo từng đường vòng chồng lên nhau, và
// hành lang `max_deviation` được đo với đúng tuyến mà fleet đã duyệt (contract 2026-08-05e).
runtime_->recoveryRunner().setReferencePlanSource(
[this](std::vector<robot_geometry_msgs::PoseStamped>& out) {
const std::vector<robot_geometry_msgs::PoseStamped>& plan = loop_.orderPlan();
if (plan.empty())
{
return false;
}
out = plan;
return true;
});
// start() sau cùng: cho thread cập nhật costmap chạy khi mọi thứ khác đã lắp xong.
runtime_->start();

View File

@@ -100,6 +100,10 @@ const char* toString(RecoveryTrigger trigger)
return "controlling_failed";
case RecoveryTrigger::kOscillation:
return "oscillation";
case RecoveryTrigger::kPathBlocked:
return "path_blocked";
case RecoveryTrigger::kOffPath:
return "off_path";
}
return "unknown";
}
@@ -114,12 +118,19 @@ const std::vector<std::size_t>& RecoveryRoutes::forTrigger(RecoveryTrigger trigg
return controlling_failed;
case RecoveryTrigger::kOscillation:
return oscillation;
case RecoveryTrigger::kPathBlocked:
return path_blocked;
case RecoveryTrigger::kOffPath:
return off_path;
}
return planning_failed;
}
bool RecoveryRoutes::empty() const
{
// CHỈ xét ba route gốc: `empty()` là câu hỏi "config có dùng schema legacy không", và schema
// legacy không biết tới hai route giám sát tuyến. Hai route mới rỗng là trạng thái bình thường
// (cơ chế giám sát tắt), không phải dấu hiệu của legacy.
return planning_failed.empty() && controlling_failed.empty() && oscillation.empty();
}

194
src/plan_inspector.cpp Normal file
View File

@@ -0,0 +1,194 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — cài đặt plan_inspector.
*
* Author: DuongTD
*********************************************************************/
#include <move_base2/core/plan_inspector.h>
#include <algorithm>
#include <cmath>
#include <exception>
#include <robot_costmap_2d/costmap_2d.h>
#include <robot_costmap_2d/cost_values.h>
#include <tf3/buffer_core.h>
namespace move_base2
{
namespace
{
/// [m] Dưới ngưỡng này thì một đoạn plan coi như suy biến thành điểm.
constexpr double kDegenerateSegment = 1e-9;
/// @brief [m] Khoảng cách từ điểm (px,py) tới đoạn thẳng (ax,ay)-(bx,by).
double pointToSegment(double px, double py, double ax, double ay, double bx, double by)
{
const double dx = bx - ax;
const double dy = by - ay;
const double len_sq = dx * dx + dy * dy;
if (len_sq <= kDegenerateSegment)
{
return std::hypot(px - ax, py - ay);
}
double t = ((px - ax) * dx + (py - ay) * dy) / len_sq;
t = std::max(0.0, std::min(1.0, t));
return std::hypot(px - (ax + t * dx), py - (ay + t * dy));
}
} // namespace
bool planarTransform(const tf3::BufferCore& tf, const std::string& from, const std::string& to,
PlanarTransform& out)
{
out = PlanarTransform();
if (from.empty() || to.empty())
{
return false;
}
if (from == to)
{
return true; // Identity — không cần chạm tới TF.
}
try
{
const tf3::TransformStampedMsg tf_msg =
const_cast<tf3::BufferCore&>(tf).lookupTransform(to, from, tf3::Time());
const auto& q = tf_msg.transform.rotation;
const double yaw =
std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)); // [rad]
out.x = tf_msg.transform.translation.x;
out.y = tf_msg.transform.translation.y;
out.cos_yaw = std::cos(yaw);
out.sin_yaw = std::sin(yaw);
return true;
}
catch (const std::exception&)
{
// Không log ở đây: hàm này chạy theo nhịp monitor. Bên gọi quyết định có báo hay không.
return false;
}
}
std::size_t nearestIndex(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
const robot_geometry_msgs::PoseStamped& pose)
{
if (plan.size() < 2)
{
return 0;
}
const double px = pose.pose.position.x;
const double py = pose.pose.position.y;
std::size_t best = 0;
double best_distance = std::numeric_limits<double>::max();
for (std::size_t i = 0; i + 1 < plan.size(); ++i)
{
const double distance =
pointToSegment(px, py, plan[i].pose.position.x, plan[i].pose.position.y,
plan[i + 1].pose.position.x, plan[i + 1].pose.position.y);
if (distance < best_distance)
{
best_distance = distance;
best = i;
}
}
return best;
}
double crossTrackError(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
const robot_geometry_msgs::PoseStamped& pose)
{
if (plan.empty())
{
return 0.0;
}
const double px = pose.pose.position.x;
const double py = pose.pose.position.y;
if (plan.size() == 1)
{
return std::hypot(px - plan.front().pose.position.x, py - plan.front().pose.position.y);
}
double best = std::numeric_limits<double>::max();
for (std::size_t i = 0; i + 1 < plan.size(); ++i)
{
best = std::min(best, pointToSegment(px, py, plan[i].pose.position.x, plan[i].pose.position.y,
plan[i + 1].pose.position.x, plan[i + 1].pose.position.y));
}
return best;
}
PlanBlockResult checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
std::size_t from_index, double horizon,
const robot_costmap_2d::Costmap2D& grid,
const PlanarTransform& plan_to_grid)
{
PlanBlockResult result;
if (plan.empty() || from_index >= plan.size() || !(horizon > 0.0))
{
return result;
}
double travelled = 0.0; // [m]
for (std::size_t i = from_index; i < plan.size(); ++i)
{
if (i > from_index)
{
travelled += std::hypot(plan[i].pose.position.x - plan[i - 1].pose.position.x,
plan[i].pose.position.y - plan[i - 1].pose.position.y);
if (travelled > horizon)
{
break;
}
}
double gx = 0.0;
double gy = 0.0;
plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, gx, gy);
unsigned int mx = 0;
unsigned int my = 0;
if (!grid.worldToMap(gx, gy, mx, my))
{
// Ra ngoài cửa sổ lưới: phần còn lại của tuyến cũng nằm ngoài (lưới lăn theo robot), nên
// dừng hẳn thay vì quét tiếp cho tới hết horizon.
break;
}
++result.scanned;
const unsigned char cost = grid.getCost(mx, my);
if (cost == robot_costmap_2d::NO_INFORMATION)
{
continue;
}
if (cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)
{
result.blocked = true;
result.index = i;
result.distance = travelled;
return result;
}
}
return result;
}
} // namespace move_base2

View File

@@ -15,6 +15,7 @@
#include <boost/dll/import.hpp>
#include <boost/system/system_error.hpp>
#include <boost/thread/locks.hpp>
#include <robot/plugin_loader_helper.h>
#include <robot/robot.h>
@@ -331,6 +332,13 @@ bool ControllerRunner::setPlan(const std::vector<robot_geometry_msgs::PoseStampe
try
{
// Plugin có thể chiếu plan lên costmap ngay trong setPlan — khoá như hai đường gọi còn lại.
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
if (costmap_lock_enabled_)
{
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
}
// Gen-2 tách goal khỏi plan: `setGoalPose` phải gọi TRƯỚC `setPlan`, đúng như
// `LocalPlannerAdapter` làm. Goal là pose CUỐI của plan.
const robot_nav_2d_msgs::Path2D path = robot_nav_2d_utils::posesToPath2D(plan);
@@ -475,6 +483,15 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
// Đo đúng lời gọi vào plugin, không đo cả hàm: phần còn lại (tra pose, kiểm NaN) là chi phí của
// move_base2, còn đây mới là chi phí của local planner đang cấu hình.
ScopedSection timer(stats_, section_compute_);
// Khoá lưới local costmap trong lúc plugin tính lệnh — gen-1 giữ đúng lock này quanh mọi
// computeVelocityCommands (move_base.cpp:1078). Thread cập nhật costmap ghi lưới dưới cùng
// mutex; không khoá thì cost function đọc dữ liệu đang bị ghi dở.
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
if (costmap_lock_enabled_)
{
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
}
// Gen-2 trả THẲNG lệnh (không có cờ thành công/thất bại) và ném exception khi không tính được —
// ngược với gen-1. Vì vậy nhánh "không có lệnh hợp lệ" ở đây là nhánh catch.
const robot_nav_2d_msgs::Twist2DStamped cmd_2d =
@@ -524,6 +541,13 @@ bool ControllerRunner::isGoalReached()
try
{
// Cùng lý do với computeVelocityCommands: plugin có thể dò costmap khi kiểm đích.
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
if (costmap_lock_enabled_)
{
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
}
const bool reached =
active_->isGoalReached(pose, robot_nav_2d_utils::twist3Dto2D(measured_velocity_));
if (reached)

View File

@@ -14,9 +14,11 @@
#include <boost/dll/import.hpp>
#include <boost/system/system_error.hpp>
#include <boost/thread/locks.hpp>
#include <robot/plugin_loader_helper.h>
#include <robot/robot.h>
#include <robot_costmap_2d/costmap_2d_robot.h>
namespace move_base2
{
@@ -364,6 +366,17 @@ void PlannerRunner::threadBody()
try
{
ScopedSection timer(stats_, section_make_plan_);
// Khoá lưới costmap suốt makePlan — cùng giao thức với gen-1 (move_base.cpp:1921,1959):
// LayeredCostmap::updateMap ghi lưới, và resizeMap REALLOC cả mảng, dưới đúng mutex này.
// Không khoá thì planner đọc cost đang bị ghi dở, hoặc tệ hơn là đọc vào vùng nhớ vừa bị
// resize giải phóng khi static map được nhận lại. 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).
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
if (costmap_lock_enabled_)
{
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
}
// 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_)

View File

@@ -6,7 +6,6 @@
#include <move_base2/runners/recovery_runner.h>
#include <map>
#include <set>
#include <utility>
#include <robot/robot.h>
@@ -29,6 +28,10 @@ recovery_core::RecoveryTrigger toCoreTrigger(RecoveryTrigger trigger)
return recovery_core::RecoveryTrigger::kControllingFailed;
case RecoveryTrigger::kOscillation:
return recovery_core::RecoveryTrigger::kOscillation;
case RecoveryTrigger::kPathBlocked:
return recovery_core::RecoveryTrigger::kPathBlocked;
case RecoveryTrigger::kOffPath:
return recovery_core::RecoveryTrigger::kOffPath;
}
return recovery_core::RecoveryTrigger::kUnspecified;
}
@@ -69,6 +72,11 @@ void RecoveryRunner::setNamespace(const std::string& ns)
namespace_ = ns;
}
void RecoveryRunner::setReferencePlanSource(PlanSource source)
{
reference_plan_bridge_.setSource(std::move(source));
}
void RecoveryRunner::setPlanSource(PlanSource source)
{
plan_bridge_.setSource(std::move(source));
@@ -84,8 +92,10 @@ void RecoveryRunner::refreshContext()
ctx_.pose = &pose_bridge_;
ctx_.collision = &collision_;
ctx_.plan = &plan_bridge_;
ctx_.reference_plan = &reference_plan_bridge_;
ctx_.local_costmap = deps_.local_costmap;
ctx_.global_costmap = deps_.global_costmap;
ctx_.tf = deps_.tf;
}
bool RecoveryRunner::configure(robot::NodeHandle& nh)
@@ -178,13 +188,20 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
return false;
}
// Ba route GỐC bắt buộc phải có; hai route giám sát tuyến là TUỲ CHỌN — thiếu chúng nghĩa là
// cơ chế giám sát tắt, và mọi config đang chạy (viết trước 2026-08-04d) vẫn boot được.
const std::pair<const char*, RecoveryTrigger> expected_routes[] = {
{"planning_failed", RecoveryTrigger::kPlanningFailed},
{"controlling_failed", RecoveryTrigger::kControllingFailed},
{"oscillation", RecoveryTrigger::kOscillation},
};
const auto is_expected_key = [&expected_routes](const std::string& key) {
const std::pair<const char*, RecoveryTrigger> optional_routes[] = {
{"path_blocked", RecoveryTrigger::kPathBlocked},
{"off_path", RecoveryTrigger::kOffPath},
};
const auto is_expected_key = [&expected_routes, &optional_routes](const std::string& key) {
for (const auto& expected : expected_routes)
{
if (key == expected.first)
@@ -192,6 +209,13 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
return true;
}
}
for (const auto& optional : optional_routes)
{
if (key == optional.first)
{
return true;
}
}
return false;
};
@@ -210,32 +234,36 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
}
}
for (const auto& expected : expected_routes)
{
const std::string trigger_name(expected.first);
const YAML::Node route_node = configured_routes[trigger_name];
if (!route_node || !route_node.IsSequence())
{
error = routes_key + "/" + trigger_name + " must be a YAML sequence";
return false;
}
std::vector<std::size_t>* resolved = nullptr;
switch (expected.second)
const auto route_for = [this](RecoveryTrigger trigger) -> std::vector<std::size_t>* {
switch (trigger)
{
case RecoveryTrigger::kPlanningFailed:
resolved = &routes_.planning_failed;
break;
return &routes_.planning_failed;
case RecoveryTrigger::kControllingFailed:
resolved = &routes_.controlling_failed;
break;
return &routes_.controlling_failed;
case RecoveryTrigger::kOscillation:
resolved = &routes_.oscillation;
break;
return &routes_.oscillation;
case RecoveryTrigger::kPathBlocked:
return &routes_.path_blocked;
case RecoveryTrigger::kOffPath:
return &routes_.off_path;
}
return &routes_.planning_failed;
};
// Resolve tên instance -> index registry cho MỘT route. Trả false kèm `error` khi schema sai;
// tên không nạp được thì bỏ qua kèm cảnh báo (cho phép commit schema trước plugin).
//
// Một behavior ĐƯỢC PHÉP xuất hiện nhiều lần trong cùng route: mỗi lần xuất hiện là một lượt thử.
// Đây là cách duy nhất cấp ngân sách cho vòng "thử detour — chờ — nhích lại gần — thử lại"
// (2026-08-05): cursor chỉ reset khi robot đi được quá oscillation_distance, nhưng giữa hai lần
// monitor bắn robot chỉ nhích được ~0.1-0.15 m, nên route không lặp thì cạn ngay sau một cặp
// [detour, wait] dù vật cản sắp vào tầm. Route vẫn hữu hạn — bế tắc thật vẫn ABORT được.
const auto resolve_route = [&](const char* trigger_name, RecoveryTrigger trigger,
const YAML::Node& route_node) {
std::vector<std::size_t>* resolved = route_for(trigger);
resolved->clear();
std::set<std::size_t> seen;
for (const YAML::Node& behavior_node : route_node)
{
if (!behavior_node.IsScalar())
@@ -248,33 +276,75 @@ bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
const auto found = loaded.find(behavior_name);
if (found == loaded.end())
{
// Đây là điểm cho phép commit schema trước plugin. Không tạo index giả: StateMachine chỉ
// được thấy những index registry thực sự nạp được.
// Không tạo index giả: StateMachine chỉ được thấy index registry thực sự nạp được.
robot::log_warning("[move_base2] RecoveryRunner: route '%s' skips '%s' because that "
"behavior was not loaded.",
trigger_name.c_str(), behavior_name.c_str());
trigger_name, behavior_name.c_str());
continue;
}
if (!seen.insert(found->second).second)
{
error = routes_key + "/" + trigger_name + " repeats behavior '" + behavior_name + "'";
return false;
}
resolved->push_back(found->second);
}
return true;
};
if (resolved->empty())
for (const auto& expected : expected_routes)
{
const std::string trigger_name(expected.first);
const YAML::Node route_node = configured_routes[trigger_name];
if (!route_node || !route_node.IsSequence())
{
error = routes_key + "/" + trigger_name +
" has no behavior that was successfully loaded";
error = routes_key + "/" + trigger_name + " must be a YAML sequence";
return false;
}
if (!resolve_route(expected.first, expected.second, route_node))
{
return false;
}
if (route_for(expected.second)->empty())
{
error = routes_key + "/" + trigger_name + " has no behavior that was successfully loaded";
return false;
}
}
for (const auto& optional : optional_routes)
{
const std::string trigger_name(optional.first);
const YAML::Node route_node = configured_routes[trigger_name];
if (!route_node)
{
// Không khai = cơ chế giám sát tuyến tắt. Đây là mặc định và là đường lùi.
continue;
}
if (!route_node.IsSequence())
{
error = routes_key + "/" + trigger_name + " must be a YAML sequence";
return false;
}
if (!resolve_route(optional.first, optional.second, route_node))
{
return false;
}
if (route_for(optional.second)->empty())
{
// Khai route nhưng không behavior nào nạp được: KHÔNG chặn khởi động (navigation vẫn phải
// chạy), nhưng phải hét lên — im lặng ở đây là người vận hành tưởng giám sát đang bật.
robot::log_error("[move_base2] RecoveryRunner: route '%s' was configured but none of its "
"behaviors loaded — that monitor stays DISABLED.",
trigger_name.c_str());
}
}
robot::log_info("[move_base2] RecoveryRunner: routes resolved: planning=%zu controlling=%zu "
"oscillation=%zu.",
"oscillation=%zu path_blocked=%zu off_path=%zu.",
routes_.planning_failed.size(), routes_.controlling_failed.size(),
routes_.oscillation.size());
routes_.oscillation.size(), routes_.path_blocked.size(),
routes_.off_path.size());
return true;
}
@@ -333,6 +403,8 @@ bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
}
active_ = behavior;
active_name_ = registry_.nameAt(index);
active_trigger_ = trigger;
// Log tại SƯỜN (một dòng cho mỗi lượt khởi động, không nằm trên đường tick). Không có dòng này
// thì trên robot/sim không cách nào biết đang chạy behavior nào: các plugin chỉ log khi chúng TỪ
@@ -358,7 +430,30 @@ RecoveryTick RecoveryRunner::update()
}
refreshContext();
return toTick(active_->update(deps_.clock->now()));
const RecoveryTick result = toTick(active_->update(deps_.clock->now()));
// Log tại SƯỜN KẾT THÚC, một dòng cho mỗi lượt (không nằm trên đường tick: kRunning không log).
//
// Không có nó thì một behavior CHẠY RỒI HỎNG hoàn toàn im lặng: bên gọi chỉ thấy state machine
// ghi `recovery=failed` lẫn giữa dòng chuyển state, còn `message` mà behavior đặt sẵn (vd
// "no reachable rejoin point on the plan after 3 attempt(s)") thì không ai in ra. Sim 2026-08-05:
// detour hỏng cả 3 attempt -> route cạn -> ABORTED, và trong log không có chữ "fail" nào của
// recovery. Nhánh TỪ CHỐI KHỞI ĐỘNG đã có log riêng ở start().
if (result.status == RecoveryTick::Status::kFailed)
{
robot::log_warning("[move_base2] RecoveryRunner: behavior '%s' FAILED (trigger %s): %s",
active_name_.c_str(), toString(active_trigger_),
result.message.empty() ? "no reason given" : result.message.c_str());
}
else if (result.status == RecoveryTick::Status::kSucceeded)
{
robot::log_info("[move_base2] RecoveryRunner: behavior '%s' succeeded (trigger %s)%s: %s",
active_name_.c_str(), toString(active_trigger_),
result.has_path ? " with a new path" : "",
result.message.empty() ? "done" : result.message.c_str());
}
return result;
}
void RecoveryRunner::cancel()

View File

@@ -22,6 +22,11 @@ bool StateMachineConfig::validate(std::string& error) const
{
// Các ngưỡng thời gian được phép <= 0 với nghĩa "tắt", nên không kiểm dấu ở đây. Thứ phải chặn là
// giá trị vô nghĩa: khoảng cách chống quẩn âm, và bật chống quẩn mà không cho khoảng cách nào.
if (sensor_patience < 0.0)
{
error = "sensor_patience must be >= 0 [s] (0 = disabled)";
return false;
}
if (oscillation_distance < 0.0)
{
error = "oscillation_distance must be >= 0 [m]";
@@ -52,13 +57,15 @@ bool StateMachineConfig::validate(std::string& error) const
return false;
}
const auto indices_valid = [this](const std::vector<std::size_t>& route) {
return std::all_of(route.begin(), route.end(),
[this](std::size_t index) { return index < recovery_behavior_count; });
};
if (!recovery_routes.empty())
{
const auto valid_route = [this](const std::vector<std::size_t>& route) {
return !route.empty() &&
std::all_of(route.begin(), route.end(), [this](std::size_t index) {
return index < recovery_behavior_count;
});
const auto valid_route = [&indices_valid](const std::vector<std::size_t>& route) {
return !route.empty() && indices_valid(route);
};
if (!valid_route(recovery_routes.planning_failed) ||
@@ -69,6 +76,15 @@ bool StateMachineConfig::validate(std::string& error) const
return false;
}
}
// Hai route giám sát tuyến được phép RỖNG (= tắt cơ chế tương ứng), nhưng index đã khai thì phải
// trỏ vào behavior có thật: index giả sẽ thành `start()` vào một behavior không tồn tại lúc chạy.
if (!indices_valid(recovery_routes.path_blocked) || !indices_valid(recovery_routes.off_path))
{
error = "recovery route 'path_blocked'/'off_path' references a behavior that was not loaded";
return false;
}
return true;
}
@@ -80,6 +96,8 @@ std::string StateMachineConfig::describe() const
<< (planner_patience > 0.0 ? "" : " (off)") << '\n';
out << " controller_patience : " << controller_patience << " s"
<< (controller_patience > 0.0 ? "" : " (off)") << '\n';
out << " sensor_patience : " << sensor_patience << " s"
<< (sensor_patience > 0.0 ? "" : " (off)") << '\n';
out << " oscillation_timeout : " << oscillation_timeout << " s"
<< (oscillation_timeout > 0.0 ? "" : " (off)") << '\n';
out << " action_patience : " << action_patience << " s"
@@ -142,9 +160,12 @@ void StateMachine::reset()
last_valid_plan_ = robot::Time();
last_valid_control_ = robot::Time();
last_oscillation_reset_ = robot::Time();
sensor_stale_active_ = false;
recovery_index_ = 0;
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
state_before_recovery_ = NavigationState::kPlanning;
recovery_route_cursors_.fill(0);
monitor_trigger_suppressed_.fill(false);
planning_retries_ = 0;
request_has_goal_ = true;
action_count_ = 0;
@@ -176,32 +197,48 @@ void StateMachine::beginPlanningCycle(const robot::Time& now)
planning_retries_ = 0;
}
std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger)
namespace
{
/// @brief Chỉ số cursor của một trigger. `switch` đầy đủ để compiler bắt khi enum thêm giá trị.
std::size_t cursorSlot(RecoveryTrigger trigger)
{
switch (trigger)
{
case RecoveryTrigger::kPlanningFailed:
return recovery_route_cursors_[0];
return 0;
case RecoveryTrigger::kControllingFailed:
return recovery_route_cursors_[1];
return 1;
case RecoveryTrigger::kOscillation:
return recovery_route_cursors_[2];
return 2;
case RecoveryTrigger::kPathBlocked:
return 3;
case RecoveryTrigger::kOffPath:
return 4;
}
return recovery_route_cursors_[0];
return 0;
}
} // namespace
std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger)
{
return recovery_route_cursors_[cursorSlot(trigger)];
}
const std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger) const
{
switch (trigger)
{
case RecoveryTrigger::kPlanningFailed:
return recovery_route_cursors_[0];
case RecoveryTrigger::kControllingFailed:
return recovery_route_cursors_[1];
case RecoveryTrigger::kOscillation:
return recovery_route_cursors_[2];
}
return recovery_route_cursors_[0];
return recovery_route_cursors_[cursorSlot(trigger)];
}
bool StateMachine::isMonitorTrigger(RecoveryTrigger trigger)
{
return trigger == RecoveryTrigger::kPathBlocked || trigger == RecoveryTrigger::kOffPath;
}
void StateMachine::suppressMonitorTrigger(RecoveryTrigger trigger, StateMachineOutput& out)
{
monitor_trigger_suppressed_[cursorSlot(trigger)] = true;
out.recovery_trigger = trigger;
out.monitor_trigger_suppressed = true;
}
void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time& now,
@@ -210,18 +247,41 @@ void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time
const std::vector<std::size_t>& route = config_.recovery_routes.forTrigger(trigger);
const std::size_t cursor = recoveryRouteCursor(trigger);
out.recovery_trigger = trigger;
out.recovery_route_cursor = cursor;
out.recovery_route_size = route.size();
if (!config_.recovery_enabled || cursor >= route.size())
{
// Trigger giám sát tuyến là DỰ BÁO, không phải báo hỏng (contract 2026-08-05e): plan vẫn hợp
// lệ, controller vẫn ra lệnh được. Hết đường vòng thì bám tiếp plan cũ, KHÔNG kết thúc chặng —
// sim 2026-08-05 ABORT đúng lúc `controller=command_valid, costmap_current=yes`, tức vứt một
// chặng mà robot hoàn toàn khoẻ. Lưới an toàn thật vẫn nguyên: local planner + costmap không
// cho đâm, rồi controller_patience đưa vào controlling_failed với ngân sách riêng của nó — và
// ĐÓ mới là đường ABORT hợp lệ.
//
// Khoá trigger lại cho tới khi có tiến độ thật: không khoá thì monitor bắn lại sau mỗi
// confirm_time và mỗi lượt đốt vài trăm ms SBPL trên control thread mà không đổi được gì.
if (isMonitorTrigger(trigger))
{
suppressMonitorTrigger(trigger, out);
return;
}
finish(NavigationState::kAborted, NavigationOutcome::kFailed, now,
"no recovery behavior left", out);
return;
}
active_recovery_trigger_ = trigger;
// Nhớ state đã leo thang: nó quyết định đường quay về khi behavior kết thúc. Phải chụp TRƯỚC
// enter() bên dưới — sau đó state_ đã là kRecovering.
state_before_recovery_ = state_;
recovery_index_ = route[cursor];
out.start_recovery = true;
out.recovery_index = recovery_index_;
out.recovery_trigger = trigger;
enter(NavigationState::kRecovering, now, reason, out);
}
@@ -241,6 +301,7 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
out.accept_request = true;
recovery_index_ = 0;
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
state_before_recovery_ = NavigationState::kPlanning;
recovery_route_cursors_.fill(0);
request_has_goal_ = in.pending_request_has_goal;
action_count_ = in.pending_request_action_count;
@@ -268,6 +329,8 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
beginPlanningCycle(in.now);
last_valid_control_ = in.now;
last_oscillation_reset_ = in.now;
sensor_stale_active_ = false;
monitor_trigger_suppressed_.fill(false);
out.reset_oscillation_origin = true;
enter(NavigationState::kPlanning, in.now, "new request accepted", out);
}
@@ -392,6 +455,21 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
if (retries_exhausted || patience_exhausted)
{
out.stop_planner = true;
if (!in.pose_available)
{
// Hết kiên nhẫn mà nguyên nhân là KHÔNG CÓ POSE: planner còn chưa được khởi động (control
// loop chặn startPlan khi mất pose), nên đây là sự cố DỮ LIỆU chứ không phải "không tìm
// được đường". Leo thang bằng ngân sách controlling_failed — cùng ngân sách với mất
// pose lúc đang bám plan. Hệ quả với route `controlling_failed: [wait]`: mất pose →
// wait một lượt → quay lại đây kiểm tra; pose vẫn chưa về thì cursor đã cạn → ABORTED
// và robot dừng hẳn; pose về thì lập plan chạy tiếp. Route planning_failed nhờ vậy giữ
// đúng nghĩa "planner có dữ liệu nhưng không tìm được đường".
escalateToRecovery(RecoveryTrigger::kControllingFailed, in.now,
"pose unavailable, cannot plan", out);
break;
}
escalateToRecovery(RecoveryTrigger::kPlanningFailed, in.now,
retries_exhausted ? "planning retries exhausted" : "planning timed "
"out", out);
@@ -430,6 +508,9 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
{
out.apply_plan = true;
beginPlanningCycle(in.now);
// Tuyến khác thì hình thế khác — trigger giám sát tuyến được thử lại ngay, không phải chờ
// đủ oscillation_distance.
monitor_trigger_suppressed_.fill(false);
}
// Đi đủ xa thì không còn bị coi là quẩn — đặt lại cả đồng hồ lẫn mốc đo quãng đường.
@@ -438,6 +519,17 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
{
last_oscillation_reset_ = in.now;
out.reset_oscillation_origin = true;
// Tiến độ thật thì ngân sách recovery đầy lại (2026-08-04). Không reset thì một chặng dài
// gặp hai sự cố cách nhau nửa giờ sẽ ABORT thẳng ở sự cố thứ hai vì route đã cạn từ sự cố
// đầu. Mốc "đi được quá oscillation_distance" là thứ vòng lặp kẹt-recovery-nhích-kẹt không
// làm giả được, nên tính hữu hạn của chuỗi recovery vẫn giữ nguyên.
recovery_route_cursors_.fill(0);
// Cùng mốc tiến độ mở khoá trigger giám sát tuyến (2026-08-05e): robot đã đi được nửa mét
// nghĩa là hình thế đã khác, thử vòng lại là đáng. Đứng im vì bị chắn thì không bao giờ tới
// đây — đúng ý đồ: không đốt SBPL vào một tình huống chưa đổi.
monitor_trigger_suppressed_.fill(false);
}
if (controller == ControllerFeedback::kGoalReached)
@@ -459,6 +551,36 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
break;
}
// Giám sát tuyến (contract 2026-08-04d). Đặt SAU nhánh goal_reached — đã tới đích thì không
// vòng đi đâu nữa — và TRƯỚC nhánh sinh lệnh: đã biết tuyến tắc thì không chạy thêm một cycle
// nào về phía vật cản.
//
// `path_blocked` thắng `off_path` khi cả hai cùng đúng: tuyến bị chắn là NGUYÊN NHÂN, còn
// lệch tuyến thường là HỆ QUẢ của việc local planner tự né chính vật cản đó.
//
// Trigger đang bị KHOÁ (lượt trước đã hết đường vòng, robot chưa đi đủ oscillation_distance)
// thì bỏ qua hẳn nhánh này: bám tiếp plan cũ, để controller_patience làm việc của nó.
if ((in.path_blocked && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kPathBlocked)]) ||
(in.off_path && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kOffPath)]))
{
const bool use_blocked =
in.path_blocked && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kPathBlocked)];
const RecoveryTrigger trigger =
use_blocked ? RecoveryTrigger::kPathBlocked : RecoveryTrigger::kOffPath;
out.stop_planner = true;
escalateToRecovery(trigger, in.now,
use_blocked ? "the path ahead is blocked"
: "the robot drifted off the plan",
out);
// Hết đường vòng: escalateToRecovery đã khoá trigger thay vì ABORT — không đổi state, chạy
// tiếp xuống nhánh sinh lệnh của cycle này để robot không mất một nhịp điều khiển.
if (!out.monitor_trigger_suppressed)
{
break;
}
out.stop_planner = false;
}
if (controller == ControllerFeedback::kCommandValid)
{
last_valid_control_ = in.now;
@@ -476,7 +598,41 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
break;
}
// Còn lại: kIdle (cycle đầu sau khi vào state) hoặc kNoValidCommand.
// Còn lại: kIdle (cycle đầu sau khi vào state) hoặc kNoValidCommand — gồm cả mất pose.
//
// KHÔNG nhảy sang kPlanning ở đây (contract 2026-08-04, tách replan khỏi recovery): controller
// không ra lệnh thì robot DỪNG TẠI CHỖ và vẫn ở kControlling — candidate rỗng nên arbiter tự
// đưa lệnh về 0. Lập plan lại là việc của replan nền theo `planner_frequency`, không phải phản
// xạ của một cycle hỏng; nhờ vậy controller_patience đo đúng "mất lệnh liên tục bao lâu" thay
// vì bị vòng CONTROLLING→PLANNING→CONTROLLING chen vào trước khi đồng hồ kịp chạy. Hết kiên
// nhẫn thì vào recovery với đúng lý do controlling_failed.
// Costmap stale = DATA OUTAGE (2026-08-05): controller bị control loop SKIP chứ không phải
// bất lực, nên controller_patience bị ĐÓNG BĂNG (33 ms patience đo outage là đo sai thứ —
// sim: detour xong -> stale do chính SBPL giữ mutex -> controlling_failed sau MỘT cycle ->
// detour rác trên map cũ -> ABORT, trong khi costmap chỉ cần ~0.5 s để hồi). Chuỗi stale
// liên tục có trần riêng `sensor_patience`; quá trần mới là "mất dữ liệu" thật.
if (!in.costmap_current && config_.sensor_patience > 0.0)
{
if (!sensor_stale_active_)
{
sensor_stale_active_ = true;
sensor_stale_since_ = in.now;
}
last_valid_control_ = in.now; // đóng băng controller_patience trong lúc outage
if ((in.now - sensor_stale_since_).toSec() > config_.sensor_patience)
{
out.stop_planner = true;
escalateToRecovery(RecoveryTrigger::kControllingFailed, in.now,
"sensor data stayed stale for too long", out);
break;
}
out.run_controller = true; // control loop tự skip khi stale; giữ nguyên hợp đồng output
break;
}
sensor_stale_active_ = false;
if (config_.controller_patience > 0.0 &&
(in.now - last_valid_control_).toSec() > config_.controller_patience)
{
@@ -486,21 +642,6 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
break;
}
if (controller == ControllerFeedback::kNoValidCommand && in.pose_available)
{
// Chưa hết kiên nhẫn: quay lại lập plan. Cố ý KHÔNG reset last_valid_control_ ở đây, nếu
// không thì vòng lặp lập-plan-rồi-lại-hỏng sẽ không bao giờ chạm controller_patience.
out.start_planner = true;
beginPlanningCycle(in.now);
enter(NavigationState::kPlanning, in.now, "controller produced no command, replanning",
out);
break;
}
// Mất pose thì ở nguyên kControlling (vận tốc đã bị ép về 0 ở phần chốt bất biến) cho tới khi
// controller_patience hết hạn. Lập lại plan không giúp được gì khi vấn đề là định vị, và
// nhảy sang kPlanning chỉ làm lý do vào recovery bị ghi nhận sai thành "lập plan hỏng".
out.run_controller = true;
break;
}
@@ -533,16 +674,75 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
if (in.recovery == RecoveryFeedback::kSucceeded || in.recovery == RecoveryFeedback::kFailed)
{
// Behavior chạy xong (thành công hay không) thì thử lập plan lại. Lỗi kế tiếp sẽ dùng
// behavior kế tiếp; hết behavior thì ABORTED.
// Behavior chạy xong. Lỗi kế tiếp sẽ dùng behavior kế tiếp trong route; hết behavior thì
// ABORTED.
//
// NGOẠI LỆ (2026-08-05): behavior THÀNH CÔNG và NỘP PATH MỚI (detour) thì cursor của
// trigger đó reset NGAY — sự cố này đã được giải quyết bằng một đường đi mới, lần chắn
// kế tiếp là sự cố MỚI với ngân sách đầy. Không chờ mốc oscillation_distance: sim đo
// robot bám detour 1.1 s (~0.45 m) rồi gặp vật cản thứ hai và ABORT vì thiếu 5 cm.
// Chỉ reset cho ca "thành công + path mới": `wait` thành công trivially sau N giây, reset
// theo nó là route không bao giờ cạn — robot đứng chờ vô hạn thay vì ABORT báo fail.
const bool recovered_with_new_path = in.recovery == RecoveryFeedback::kSucceeded &&
in.planner == PlannerFeedback::kPlanReady;
std::size_t& cursor = recoveryRouteCursor(active_recovery_trigger_);
++cursor;
if (recovered_with_new_path)
{
cursor = 0;
}
else
{
++cursor;
}
const std::vector<std::size_t>& route =
config_.recovery_routes.forTrigger(active_recovery_trigger_);
recovery_index_ = cursor < route.size() ? route[cursor] : config_.recovery_behavior_count;
// Đường quay về (contract 2026-08-04b — tách replan khỏi recovery hoàn toàn):
//
// 1. Behavior họ detour vừa nộp một PATH MỚI (control loop đã cất vào latest_plan_ và báo
// kPlanReady): áp path đó và bám tiếp. Đây là đường thay plan DUY NHẤT mà recovery được
// phép thực hiện.
// 2. Trigger planning_failed — vào recovery vì KHÔNG lập được plan: không có plan nào để
// bám nên phải quay về kPlanning thử lập lại.
// 3. Trigger controlling/oscillation leo thang từ kControlling: global path cũ vẫn là
// đường hợp lệ — quay lại bám tiếp nó, KHÔNG lập plan lại. Thay plan trong lúc chạy là
// việc riêng của replan nền theo `planner_frequency`.
// Riêng khi leo thang từ kPlanning (mất pose lúc lập plan) thì chưa từng có plan —
// quay về kPlanning như nhóm 2.
const bool has_detour_path = in.planner == PlannerFeedback::kPlanReady;
const bool old_plan_valid =
active_recovery_trigger_ != RecoveryTrigger::kPlanningFailed &&
state_before_recovery_ == NavigationState::kControlling;
if (has_detour_path || old_plan_valid)
{
if (has_detour_path)
{
out.apply_plan = true;
beginPlanningCycle(in.now);
}
// Controller được trọn một cửa controller_patience để thử lại trên plan (cũ hoặc detour);
// vẫn bế tắc thì lượt leo thang kế tiếp dùng behavior tiếp theo của route. Đồng hồ stale
// cũng đo lại từ đầu — recovery (nhất là SBPL giữ mutex) có thể chính là thủ phạm làm
// costmap trễ, cho nó trọn một cửa sensor_patience để hồi.
last_valid_control_ = in.now;
sensor_stale_active_ = false;
last_oscillation_reset_ = in.now;
out.reset_oscillation_origin = true;
out.run_controller = true;
enter(NavigationState::kControlling, in.now,
has_detour_path ? "recovery produced a detour path"
: "recovery finished, resuming the current plan",
out);
break;
}
out.start_planner = true;
beginPlanningCycle(in.now);
last_valid_control_ = in.now;
sensor_stale_active_ = false;
enter(NavigationState::kPlanning, in.now,
in.recovery == RecoveryFeedback::kSucceeded ? "recovery finished, replanning"
: "recovery failed, replanning",
@@ -644,6 +844,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
beginPlanningCycle(in.now);
last_valid_control_ = in.now;
last_oscillation_reset_ = in.now;
sensor_stale_active_ = false;
out.reset_oscillation_origin = true;
if (state_before_pause_ == NavigationState::kControlling)
@@ -672,8 +873,9 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
// --------------------------------------------------------------------------------------
case NavigationState::kCancelling:
{
// Nguồn vận tốc đã là kNone nên bộ trọng tài đang giảm tốc về 0 theo trần gia tốc; trạng thái
// này vì vậy luôn kết thúc sau hữu hạn cycle, không cần thêm timeout.
// Nguồn vận tốc đã là kNone nên bộ trọng tài phát lệnh 0 NGAY (arbiter cố ý không ramp khi
// nguồn là kNone — xem VelocityArbiter::arbitrate); trạng thái này vì vậy kết thúc ngay cycle
// robot_stopped bật, không cần thêm timeout.
if (in.robot_stopped)
{
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,