feat: lifecycle contract — cancel/pause must reach true quiescence before reporting done
Root cause (from a C++ host log, 2026-09-11): cancel during PLANNING only set a discard flag on the planner thread, which ran to allocated_time before CANCELLED could be reported; a queued next mission landed on a still-busy planner and timed out too. Same class of bug existed for pause, recovery, and implicitly for a legitimate ABORTED read while a component was still unwinding. Full audit, decisions, and phased design in docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md; old-vs-new behaviour per state in docs/LIFECYCLE_BEHAVIOUR_MATRIX.md. Runtime quiescence, not just "command sent": - kPausing (new state) mirrors kCancelling: PAUSED/CANCELLED is only entered once planner and recovery are idle, the action reports terminal, and the robot is stopped per odometry (robot_stopped, stopped_measured_linear/ angular_eps) — not merely "the command we sent was zero". settle_timeout bounds the wait; exceeding it still finishes but logs an ungated error naming which component was still busy, so a plugin that doesn't honour cancel/pause is visible instead of silently swallowed. - PlannerRunner::running_planner_ (new): the instance the planner thread is actually inside makePlan() with, tracked separately from active_ — active_ can already point at a different instance after swapPlanner() while the old attempt is still running. cancelPlan(), swapPlanner() (when a job is running_ or only pending_ and not yet picked up), and the destructor all preempt through this pointer now; the old code preempted through active_ and could silently preempt the wrong (idle) instance after a profile swap. - ComponentStatusBoard + per-component ComponentPhase (idle/busy/stopping/ paused/hung), read by PlannerRunner, RecoveryRunner, ActionRunner and ControlLoop instead of ad hoc bools — this is what makes "did everything actually stop" answerable at all, and what the new Watchdog thread reads to flag a component busy-without-progress as hung (logged once at the edge) without the control loop needing to detect its own stall. - Resume: PLANNING replans from the current pose. CONTROLLING re-issues setPlan() with the plan already in hand (decided: setPlan again, not a fresh plan) — the local planner needs nothing else since it already runs once per control cycle; a fresh plan on resume was considered and rejected as unnecessary work for a plan that's still valid. - Command-to-zero on cancel/pause stays immediate (no deceleration ramp) — existing VelocityArbiter behaviour, left as is per a scoped decision. Depends on: Test/sbpl (bd89924), pnkx_nav_core (2b0993b, robot_nav_core:: Preemptable + component_status_probe.h), Test/sbpl_lattice_planner (7456e99), Test/recovery_core (254c7fc, onCancelRequested + ABI guard), Test/ sbpl_recovery (ea79686, worker-thread cancel), Test/action_core (669c3f7, pause/resume + kCancelled), Test/dock_pattern_action (cc1ea74). Verified: 13 gtest binaries / 528 tests, 0 failures. Runtime on the dev machine (Gazebo + real ROS host + VDA5050 over MQTT), 6 scenarios — cancel during PLANNING, pause/resume during PLANNING and CONTROLLING (incl. submit-while-still-winding-down), pause-then-cancel during PLANNING and CONTROLLING: no ABORTED/RECOVERING in any run, preempt lands within hundredths of a millisecond of entering CANCELLING/PAUSING, PAUSED/CANCELLED only reported once the robot is actually stopped per odometry. Full numbers in the plan doc section 6. Excluded from this commit (pre-existing, unrelated): config/runtime/recovery_behaviors_params.yaml (allocated_time 1.0->2.0, SBPLDetourPlanner tuning predating this work). Not yet done (see plan doc "Trạng thái"): config tuning (phase 0, pending per a scoping decision); runtime scenarios for cancel mid-detour and a 30 s pause mid-action; commit to rb_ws is a separate step, not done here. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
56
src/component_status.cpp
Normal file
56
src/component_status.cpp
Normal file
@@ -0,0 +1,56 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — tên hiển thị cho bảng trạng thái thành phần.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/core/component_status.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
const char* toString(Component component)
|
||||
{
|
||||
switch (component)
|
||||
{
|
||||
case Component::kGlobalPlanner:
|
||||
return "global_planner";
|
||||
case Component::kLocalPlanner:
|
||||
return "local_planner";
|
||||
case Component::kRecovery:
|
||||
return "recovery";
|
||||
case Component::kAction:
|
||||
return "action";
|
||||
case Component::kCostmapGlobal:
|
||||
return "costmap_global";
|
||||
case Component::kCostmapLocal:
|
||||
return "costmap_local";
|
||||
case Component::kControlLoop:
|
||||
return "control_loop";
|
||||
case Component::kCount:
|
||||
break;
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const char* toString(ComponentPhase phase)
|
||||
{
|
||||
switch (phase)
|
||||
{
|
||||
case ComponentPhase::kIdle:
|
||||
return "idle";
|
||||
case ComponentPhase::kBusy:
|
||||
return "busy";
|
||||
case ComponentPhase::kStopping:
|
||||
return "stopping";
|
||||
case ComponentPhase::kPaused:
|
||||
return "paused";
|
||||
case ComponentPhase::kHung:
|
||||
return "hung";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -147,6 +147,12 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
readDouble(nh, "planner_frequency", config.planner_frequency);
|
||||
readDouble(nh, "planner_timeout", config.planner_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);
|
||||
readDouble(nh, "recovery_stall_budget", config.watchdog.recovery_stall_budget);
|
||||
readDouble(nh, "action_stall_budget", config.watchdog.action_stall_budget);
|
||||
readDouble(nh, "control_loop_stall_budget", config.watchdog.control_loop_stall_budget);
|
||||
config.watchdog.planner_timeout = config.planner_timeout;
|
||||
|
||||
readDouble(nh, "planner_patience", config.state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", config.state_machine.controller_patience);
|
||||
@@ -157,6 +163,9 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
readDouble(nh, "action_patience", config.state_machine.action_patience);
|
||||
readInt(nh, "max_planning_retries", config.state_machine.max_planning_retries);
|
||||
readBool(nh, "recovery_behavior_enabled", config.state_machine.recovery_enabled);
|
||||
readDouble(nh, "settle_timeout", config.state_machine.settle_timeout);
|
||||
readDouble(nh, "stopped_measured_linear_eps", config.state_machine.stopped_measured_linear_eps);
|
||||
readDouble(nh, "stopped_measured_angular_eps", config.state_machine.stopped_measured_angular_eps);
|
||||
|
||||
// Nghĩa của Twist đi qua arbiter — quyết định đơn vị của cả cụm giới hạn bên dưới. "steering"
|
||||
// (linear.x = tốc độ bánh steer, angular.z = GÓC lái) là convention của robot lái một bánh
|
||||
@@ -426,6 +435,10 @@ bool MoveBase2Config::validate(std::string& error) const
|
||||
error = "planner_timeout is not finite [s]";
|
||||
return false;
|
||||
}
|
||||
if (!watchdog.validate(error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0)
|
||||
{
|
||||
@@ -525,6 +538,7 @@ std::string MoveBase2Config::describe() const
|
||||
out << " planner_timeout: " << planner_timeout << " s\n";
|
||||
out << " runtime_stats_period: " << runtime_stats_period << " s"
|
||||
<< (runtime_stats_period > 0.0 ? "\n" : " (off)\n");
|
||||
out << watchdog.describe();
|
||||
out << " frames: global='" << global_frame << "' base='" << robot_base_frame << "'\n";
|
||||
out << " require_current_costmap: " << (require_current_costmap ? "true" : "false") << "\n";
|
||||
out << " namespaces: recovery='" << recovery_namespace << "' actions='" << action_namespace
|
||||
@@ -571,6 +585,13 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
// 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);
|
||||
// Watchdog (2026-09-11) — không có trong schema gen-1; thiếu khoá thì default (bật, 0.1 s).
|
||||
readDouble(nh, "watchdog_period", watchdog.period);
|
||||
readDouble(nh, "local_planner_call_budget", watchdog.local_planner_call_budget);
|
||||
readDouble(nh, "recovery_stall_budget", watchdog.recovery_stall_budget);
|
||||
readDouble(nh, "action_stall_budget", watchdog.action_stall_budget);
|
||||
readDouble(nh, "control_loop_stall_budget", watchdog.control_loop_stall_budget);
|
||||
watchdog.planner_timeout = planner_timeout;
|
||||
readDouble(nh, "planner_patience", state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", state_machine.controller_patience);
|
||||
readDouble(nh, "sensor_patience", state_machine.sensor_patience);
|
||||
@@ -578,6 +599,11 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
readDouble(nh, "oscillation_distance", state_machine.oscillation_distance);
|
||||
readInt(nh, "max_planning_retries", state_machine.max_planning_retries);
|
||||
readBool(nh, "recovery_behavior_enabled", state_machine.recovery_enabled);
|
||||
// Không có trong schema gen-1 (bản cũ báo CANCELLED ngay khi lệnh về 0) — đọc để cây config cũ
|
||||
// vẫn bật được chờ quiescent; thiếu khoá thì dùng default (bật, 2 s).
|
||||
readDouble(nh, "settle_timeout", state_machine.settle_timeout);
|
||||
readDouble(nh, "stopped_measured_linear_eps", state_machine.stopped_measured_linear_eps);
|
||||
readDouble(nh, "stopped_measured_angular_eps", state_machine.stopped_measured_angular_eps);
|
||||
|
||||
readString(nh, "global_frame", global_frame);
|
||||
readString(nh, "robot_base_frame", robot_base_frame);
|
||||
|
||||
@@ -654,6 +654,23 @@ void ControlLoop::collectPlannerResult()
|
||||
planner_feedback_ = PlannerFeedback::kPlanReady;
|
||||
}
|
||||
|
||||
bool ControlLoop::robotStopped() const
|
||||
{
|
||||
const StateMachineConfig& sm = config_.state_machine;
|
||||
const bool use_measured = sm.stopped_measured_linear_eps > 0.0 || sm.stopped_measured_angular_eps > 0.0;
|
||||
|
||||
robot_geometry_msgs::Twist measured;
|
||||
if (use_measured && deps_.controller != nullptr && deps_.controller->measuredVelocity(measured))
|
||||
{
|
||||
// Odom đo được thì nó là sự thật về bánh xe; lệnh đã phát chỉ là ý định. NaN từ odom rơi vào
|
||||
// nhánh "chưa dừng" (so sánh với NaN luôn false) — an toàn: settle_timeout là trần.
|
||||
return std::fabs(measured.linear.x) <= sm.stopped_measured_linear_eps &&
|
||||
std::fabs(measured.linear.y) <= sm.stopped_measured_linear_eps &&
|
||||
std::fabs(measured.angular.z) <= sm.stopped_measured_angular_eps;
|
||||
}
|
||||
return arbiter_.stopped();
|
||||
}
|
||||
|
||||
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
|
||||
bool costmap_stale)
|
||||
@@ -841,6 +858,28 @@ void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
|
||||
{
|
||||
candidate = robot_geometry_msgs::Twist();
|
||||
|
||||
// Hàng local_planner của bảng trạng thái: bận trong suốt lượt gọi plugin (đồng bộ, cùng thread),
|
||||
// rảnh khi ra. Watchdog (pha 4) dùng nó để bắt local planner treo — control thread không tự bắt
|
||||
// được chính mình. RAII để mọi đường thoát (kể cả exception từ plugin) đều trả về idle.
|
||||
struct LocalPlannerBusyScope
|
||||
{
|
||||
explicit LocalPlannerBusyScope(ComponentStatusBoard* board) : board_(board)
|
||||
{
|
||||
if (board_ != nullptr)
|
||||
{
|
||||
board_->enter(Component::kLocalPlanner, ComponentPhase::kBusy);
|
||||
}
|
||||
}
|
||||
~LocalPlannerBusyScope()
|
||||
{
|
||||
if (board_ != nullptr)
|
||||
{
|
||||
board_->enter(Component::kLocalPlanner, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
ComponentStatusBoard* board_;
|
||||
} local_planner_busy(deps_.components);
|
||||
|
||||
// Giữ nguyên thứ tự của interface được bọc: hỏi đã tới đích trước, chỉ khi chưa mới tính lệnh.
|
||||
if (deps_.controller->isGoalReached())
|
||||
{
|
||||
@@ -948,7 +987,28 @@ bool ControlLoop::step()
|
||||
input.action_message = action_message_;
|
||||
input.pose_available = pose_available;
|
||||
input.costmap_current = !costmap_stale;
|
||||
input.robot_stopped = arbiter_.stopped();
|
||||
input.robot_stopped = robotStopped();
|
||||
// Điều kiện quiescent của kCancelling/kPausing (2026-09-11). `isPlanning()` là true cả khi lượt
|
||||
// đang chạy đã bị `cancelPlan()` — plugin không cắt được thì thread vẫn bận, và đó chính là thứ
|
||||
// host phải chờ. Bảng trạng thái thành phần (nếu có) bổ sung hàng recovery/action mà cổng không
|
||||
// hỏi được; hàng global_planner của bảng chỉ CỘNG thêm, cổng vẫn là câu hỏi gốc. Action: chưa có
|
||||
// handshake cancelling→cancelled ở cổng (pha 3) — không có bảng thì coi là terminal ngay.
|
||||
{
|
||||
const ComponentStatusBoard* board = deps_.components;
|
||||
input.planner_busy = deps_.planner->isPlanning() ||
|
||||
(board != nullptr && !board->isIdle(Component::kGlobalPlanner));
|
||||
input.recovery_busy = board != nullptr && !board->isIdle(Component::kRecovery);
|
||||
if (board != nullptr)
|
||||
{
|
||||
const ComponentPhase action_phase = board->phase(Component::kAction);
|
||||
input.action_terminal =
|
||||
action_phase == ComponentPhase::kIdle || action_phase == ComponentPhase::kPaused;
|
||||
}
|
||||
else
|
||||
{
|
||||
input.action_terminal = true;
|
||||
}
|
||||
}
|
||||
input.travelled_since_oscillation_reset = travelled;
|
||||
// Bốn cổng của state machine do EnvMonitor cấp (Test/ENV_MONITOR_PLAN.md): cờ chỉ khác false khi
|
||||
// verdict tương ứng có `action: recover`. `off_path` không còn nguồn nào (phép đo cũ đã bỏ 6/9/2026).
|
||||
@@ -980,6 +1040,21 @@ bool ControlLoop::step()
|
||||
}
|
||||
}
|
||||
|
||||
if (output.settle_timed_out)
|
||||
{
|
||||
// LỖI, không có khoá tắt: CANCELLED/PAUSED được báo ra mà runtime CHƯA im hẳn. Host sẽ tin và
|
||||
// gửi goal kế; goal kế chờ được nhờ kBusy, nhưng nguyên nhân gốc (plugin không cắt được
|
||||
// makePlan, odom không về 0, action không trả terminal) phải lộ ra ở đây, kèm thành phần nào.
|
||||
robot::log_error("[move_base2] settle timeout %.1f s while %s (mission %llu): finishing anyway — "
|
||||
"planner_busy=%s recovery_busy=%s action_terminal=%s robot_stopped=%s. A plugin "
|
||||
"is not honouring cancel/pause, or odometry never reads zero.\n",
|
||||
config_.state_machine.settle_timeout,
|
||||
output.state == NavigationState::kPaused ? "PAUSING" : "CANCELLING",
|
||||
static_cast<unsigned long long>(has_active_request_ ? active_request_.mission_sequence_id : 0),
|
||||
input.planner_busy ? "yes" : "no", input.recovery_busy ? "yes" : "no",
|
||||
input.action_terminal ? "yes" : "no", input.robot_stopped ? "yes" : "no");
|
||||
}
|
||||
|
||||
// Cờ một-lần đã được state machine tiêu thụ xong ở lời gọi trên.
|
||||
pause_requested_ = false;
|
||||
resume_requested_ = false;
|
||||
@@ -1182,6 +1257,14 @@ bool ControlLoop::step()
|
||||
{
|
||||
deps_.action->cancel();
|
||||
}
|
||||
if (output.pause_action && deps_.action != nullptr)
|
||||
{
|
||||
deps_.action->pause();
|
||||
}
|
||||
if (output.resume_action && deps_.action != nullptr)
|
||||
{
|
||||
deps_.action->resume();
|
||||
}
|
||||
|
||||
if (output.start_action)
|
||||
{
|
||||
@@ -1214,6 +1297,13 @@ bool ControlLoop::step()
|
||||
robot::log_info("[move_base2] %s\n", tick.message.c_str());
|
||||
}
|
||||
break;
|
||||
case ActionTick::Status::kCancelled:
|
||||
// Handler thiết bị đã về vị trí an toàn sau cancel (pha 3). Chỉ gặp trong CANCELLING/PAUSING;
|
||||
// hàng kAction về idle → quiescent. Một dòng info: đây là sườn kết thúc, không lặp.
|
||||
action_feedback_ = ActionFeedback::kCancelled;
|
||||
robot::log_info("[move_base2] action stopped safely after cancel%s%s\n",
|
||||
tick.message.empty() ? "" : ": ", tick.message.c_str());
|
||||
break;
|
||||
case ActionTick::Status::kFailed:
|
||||
action_feedback_ = ActionFeedback::kFailed;
|
||||
// Handler đã dựng sẵn lý do cụ thể ("thiếu mẫu", "tản quá", "không publish được"). Trước
|
||||
@@ -1365,10 +1455,27 @@ bool ControlLoop::step()
|
||||
}
|
||||
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. 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;
|
||||
// Không khởi động được. Hai nguyên nhân khác hẳn nhau, không được gộp (bài học log
|
||||
// 2026-09-11: cancel lúc SBPL đang chạy, goal kế bị coi là hỏng và ABORTED sau 3 s dù chưa
|
||||
// lập plan lần nào):
|
||||
// - thread planner còn chạy lượt CŨ đã bị cancelPlan() mà plugin không cắt được → BẬN,
|
||||
// cycle sau thử lại; planner_patience vẫn là trần nếu bận quá lâu;
|
||||
// - chưa có planner, pose hỏng... → HỎNG thật, đồng hồ kiên nhẫn/retry chạy như cũ.
|
||||
// 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.
|
||||
if (deps_.planner->isPlanning())
|
||||
{
|
||||
planner_feedback_ = PlannerFeedback::kBusy;
|
||||
robot::log_warning_throttle(5.0,
|
||||
"[move_base2] planner thread still busy with a cancelled attempt; "
|
||||
"waiting for it before planning mission %llu (planner_patience "
|
||||
"%.1f s is the ceiling).\n",
|
||||
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
||||
config_.state_machine.planner_patience);
|
||||
}
|
||||
else
|
||||
{
|
||||
planner_feedback_ = PlannerFeedback::kFailed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1452,6 +1559,14 @@ bool ControlLoop::step()
|
||||
cancel_requested_ = false;
|
||||
}
|
||||
|
||||
// Heartbeat của chính control thread — thứ duy nhất cho watchdog (thread khác) biết vòng điều
|
||||
// khiển còn quay. Đặt ở cuối step(): một cycle kẹt giữa chừng (detour SBPL, plugin treo) không
|
||||
// nhích được mốc này.
|
||||
if (deps_.components != nullptr)
|
||||
{
|
||||
deps_.components->progress(Component::kControlLoop);
|
||||
}
|
||||
|
||||
// false = "yêu cầu hiện tại vừa kết thúc, không còn gì để chạy". Preempt CŨNG báo kết quả (cho
|
||||
// chặng cũ) nhưng ngay lập tức nhận chặng mới — lúc đó runtime vẫn đang chạy, nên không được trả
|
||||
// false. Điều kiện đúng là "vào state terminal", không phải "có báo kết quả".
|
||||
|
||||
213
src/io/watchdog.cpp
Normal file
213
src/io/watchdog.cpp
Normal file
@@ -0,0 +1,213 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — watchdog thành phần treo.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/io/watchdog.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
|
||||
#include <robot/console.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
bool WatchdogConfig::validate(std::string& error) const
|
||||
{
|
||||
const double values[] = {period, planner_timeout, local_planner_call_budget,
|
||||
recovery_stall_budget, action_stall_budget, control_loop_stall_budget};
|
||||
for (double v : values)
|
||||
{
|
||||
if (!std::isfinite(v))
|
||||
{
|
||||
error = "watchdog budgets must be finite [s]";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (period < 0.0)
|
||||
{
|
||||
error = "watchdog_period must be >= 0 [s] (0 = watchdog off)";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string WatchdogConfig::describe() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "Watchdog:\n";
|
||||
out << " period : " << period << " s" << (period > 0.0 ? "" : " (off)") << '\n';
|
||||
const auto line = [&out](const char* name, double v) {
|
||||
out << " " << name << " : " << v << " s" << (v > 0.0 ? "" : " (not watched)") << '\n';
|
||||
};
|
||||
line("planner_timeout ", planner_timeout);
|
||||
line("local_planner_call_budget", local_planner_call_budget);
|
||||
line("recovery_stall_budget ", recovery_stall_budget);
|
||||
line("action_stall_budget ", action_stall_budget);
|
||||
line("control_loop_stall_budget", control_loop_stall_budget);
|
||||
return out.str();
|
||||
}
|
||||
|
||||
Watchdog::~Watchdog()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
bool Watchdog::start(const ComponentStatusBoard* board, const WatchdogConfig& config,
|
||||
std::string& error)
|
||||
{
|
||||
if (board == nullptr)
|
||||
{
|
||||
error = "watchdog needs a component status board";
|
||||
return false;
|
||||
}
|
||||
if (!config.validate(error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (running_.load())
|
||||
{
|
||||
error = "watchdog already running";
|
||||
return false;
|
||||
}
|
||||
board_ = board;
|
||||
config_ = config;
|
||||
for (auto& flag : hung_)
|
||||
{
|
||||
flag.store(false, std::memory_order_relaxed);
|
||||
}
|
||||
if (config_.period <= 0.0)
|
||||
{
|
||||
return true; // Tắt: không thread, checkOnce() vẫn dùng được nếu ai đó tự gọi.
|
||||
}
|
||||
running_.store(true);
|
||||
thread_ = std::thread(&Watchdog::threadBody, this);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Watchdog::stop()
|
||||
{
|
||||
running_.store(false);
|
||||
if (thread_.joinable())
|
||||
{
|
||||
thread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
bool Watchdog::anyHung() const
|
||||
{
|
||||
for (const auto& flag : hung_)
|
||||
{
|
||||
if (flag.load(std::memory_order_relaxed))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
double Watchdog::budgetFor(Component c) const
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case Component::kGlobalPlanner:
|
||||
return config_.planner_timeout;
|
||||
case Component::kLocalPlanner:
|
||||
return config_.local_planner_call_budget;
|
||||
case Component::kRecovery:
|
||||
return config_.recovery_stall_budget;
|
||||
case Component::kAction:
|
||||
return config_.action_stall_budget;
|
||||
case Component::kControlLoop:
|
||||
return config_.control_loop_stall_budget;
|
||||
case Component::kCostmapGlobal:
|
||||
case Component::kCostmapLocal:
|
||||
// Chưa có heartbeat từ map-update thread (cần móc vào gói costmap) — không giám sát ở pha này.
|
||||
return 0.0;
|
||||
case Component::kCount:
|
||||
break;
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
void Watchdog::checkOnce()
|
||||
{
|
||||
if (board_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||
{
|
||||
const Component c = static_cast<Component>(i);
|
||||
const double budget = budgetFor(c);
|
||||
if (budget <= 0.0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const ComponentPhase phase = board_->phase(c);
|
||||
// Hàng heartbeat-only (control loop) không có phase: luôn được coi là "đang chạy". Hàng khác chỉ
|
||||
// xét khi đang có việc — idle/paused không có gì để treo.
|
||||
const bool watched = c == Component::kControlLoop ||
|
||||
phase == ComponentPhase::kBusy || phase == ComponentPhase::kStopping;
|
||||
// Hàng chưa từng nhích (last_progress = 0): runtime mới lên, chưa có gì để so.
|
||||
const bool ever_progressed = board_->at(c).last_progress_ns.load(std::memory_order_relaxed) != 0;
|
||||
const double since = board_->secondsSinceProgress(c);
|
||||
const bool stalled = watched && ever_progressed && since > budget;
|
||||
|
||||
std::atomic<bool>& flag = hung_[i];
|
||||
const bool was_hung = flag.load(std::memory_order_relaxed);
|
||||
if (stalled && !was_hung)
|
||||
{
|
||||
flag.store(true, std::memory_order_relaxed);
|
||||
// LỖI, không có khoá tắt: đây là "một phần của runtime đã chết đứng". In một lần ở sườn.
|
||||
robot::log_error("[move_base2] watchdog: %s is HUNG — phase '%s', no progress for %.2f s "
|
||||
"(budget %.2f s). %s\n",
|
||||
toString(c), toString(phase), since, budget,
|
||||
c == Component::kControlLoop
|
||||
? "The control thread is not cycling: host must treat cmd_vel as stale."
|
||||
: "cancel/pause will hit settle_timeout; the plugin is not returning.");
|
||||
}
|
||||
else if (!stalled && was_hung)
|
||||
{
|
||||
flag.store(false, std::memory_order_relaxed);
|
||||
robot::log_warning("[move_base2] watchdog: %s recovered (phase '%s').\n", toString(c),
|
||||
toString(phase));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string Watchdog::report() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
bool any = false;
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows; ++i)
|
||||
{
|
||||
if (hung_[i].load(std::memory_order_relaxed))
|
||||
{
|
||||
const Component c = static_cast<Component>(i);
|
||||
out << (any ? ", " : "") << toString(c) << " hung for "
|
||||
<< (board_ != nullptr ? board_->secondsSinceProgress(c) : 0.0) << " s";
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
return out.str();
|
||||
}
|
||||
|
||||
void Watchdog::threadBody()
|
||||
{
|
||||
const auto period = std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
||||
std::chrono::duration<double>(config_.period));
|
||||
while (running_.load(std::memory_order_relaxed))
|
||||
{
|
||||
checkOnce();
|
||||
std::this_thread::sleep_for(period);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -6,10 +6,12 @@
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
|
||||
#include <move_base_core/component_status_probe.h>
|
||||
#include <move_base_core/navigation.h>
|
||||
|
||||
#include <move_base2/navigation_server.h>
|
||||
@@ -30,6 +32,39 @@ robot::move_base_core::BaseNavigation::Ptr createMoveBase2()
|
||||
return std::make_shared<NavigationServer>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Capability "MoveBaseComponentStatus" (2026-09-11): host dlsym alias này để đọc bảng trạng thái
|
||||
* thành phần + kết luận treo của watchdog, không cần thêm virtual vào BaseNavigation. Chỉ atomic
|
||||
* load — gọi được từ thread bất kỳ, kể cả khi control thread đang treo (đó chính là lúc cần nó).
|
||||
*/
|
||||
std::size_t componentStatusProbe(robot::move_base_core::BaseNavigation* navigation,
|
||||
robot::move_base_core::ComponentStatusEntry* out, std::size_t max)
|
||||
{
|
||||
auto* server = dynamic_cast<NavigationServer*>(navigation);
|
||||
if (server == nullptr)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
const ComponentStatusBoard* board = server->componentStatus();
|
||||
if (board == nullptr)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
const Watchdog& watchdog = server->watchdog();
|
||||
for (std::size_t i = 0; i < ComponentStatusBoard::kRows && i < max && out != nullptr; ++i)
|
||||
{
|
||||
const Component c = static_cast<Component>(i);
|
||||
robot::move_base_core::ComponentStatusEntry& e = out[i];
|
||||
std::strncpy(e.name, toString(c), sizeof(e.name) - 1);
|
||||
e.name[sizeof(e.name) - 1] = '\0';
|
||||
e.phase = static_cast<unsigned char>(board->phase(c));
|
||||
e.hung = watchdog.hung(c) ? 1 : 0;
|
||||
e.seconds_in_phase = board->secondsInPhase(c);
|
||||
e.seconds_since_progress = board->secondsSinceProgress(c);
|
||||
}
|
||||
return ComponentStatusBoard::kRows;
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
|
||||
BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase2)
|
||||
@@ -46,3 +81,6 @@ BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase2)
|
||||
* host. `MoveBase2` giữ lại cho host nào muốn nạp tường minh bản mới.
|
||||
*/
|
||||
BOOST_DLL_ALIAS(move_base2::createMoveBase2, MoveBase)
|
||||
|
||||
// Capability đọc trạng thái thành phần (xem move_base_core/component_status_probe.h).
|
||||
BOOST_DLL_ALIAS(move_base2::componentStatusProbe, MoveBaseComponentStatus)
|
||||
|
||||
@@ -420,6 +420,9 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
||||
// và chính thread đó tự đăng ký nhãn của mình khi bắt đầu chạy.
|
||||
planner_.attachStats(stats_.get());
|
||||
controller_.attachStats(stats_.get());
|
||||
planner_.attachStatusBoard(&components_);
|
||||
recovery_.attachStatusBoard(&components_);
|
||||
action_.attachStatusBoard(&components_);
|
||||
|
||||
// Trước configure(): planner nạp trong configure() và có thể muốn đọc cảm biến ngay trong
|
||||
// initialize() của nó.
|
||||
@@ -626,6 +629,7 @@ ControlLoopDeps NavigationRuntime::deps()
|
||||
deps.action = &action_;
|
||||
deps.costmap_status = &costmap_status_;
|
||||
deps.environment = &environment_;
|
||||
deps.components = &components_;
|
||||
return deps;
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ NavigationServer::~NavigationServer()
|
||||
|
||||
void NavigationServer::shutdown()
|
||||
{
|
||||
watchdog_.stop();
|
||||
stopControlThread();
|
||||
if (runtime_ != nullptr)
|
||||
{
|
||||
@@ -60,6 +61,11 @@ void NavigationServer::shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
const ComponentStatusBoard* NavigationServer::componentStatus() const
|
||||
{
|
||||
return runtime_ != nullptr ? &runtime_->components() : nullptr;
|
||||
}
|
||||
|
||||
bool NavigationServer::startControlThread(double frequency)
|
||||
{
|
||||
if (!loop_.initialized())
|
||||
@@ -284,6 +290,10 @@ robot::move_base_core::State NavigationServer::toHostState(NavigationState state
|
||||
// VDA5050 đang suy `driving = true` từ CONTROLLING (amr_vda_5050_client_api.cpp:1233), mà
|
||||
// robot lúc này đứng yên làm action; báo "đang chạy" cho fleet master là báo sai.
|
||||
return HostState::ACTIVE;
|
||||
case NavigationState::kPausing:
|
||||
// Không tới được từ refreshFeedback(): PAUSING được thay bằng state TRƯỚC pause ở đó (host chỉ
|
||||
// thấy PAUSED khi runtime đã im hẳn — 2026-09-11). Giữ case để switch đủ nhánh.
|
||||
return HostState::PAUSED;
|
||||
case NavigationState::kPaused:
|
||||
return HostState::PAUSED;
|
||||
case NavigationState::kCancelling:
|
||||
@@ -344,7 +354,16 @@ void NavigationServer::reportSensorStore()
|
||||
|
||||
void NavigationServer::refreshFeedback()
|
||||
{
|
||||
robot::move_base_core::State host_state = toHostState(loop_.state());
|
||||
// PAUSING nói thật (2026-09-11): pause đã nhận, lệnh = 0, nhưng thread planner/recovery/action
|
||||
// chưa im — host vẫn thấy tên state trước (PLANNING/CONTROLLING/CLEARING/ACTIVE) kèm
|
||||
// feed_back_str "pausing…"; PAUSED chỉ khi đã im hẳn. Host đọc PAUSED là "dừng rồi, làm gì cũng
|
||||
// được" — báo sớm là nói dối cùng kiểu với PREEMPTED cũ.
|
||||
NavigationState core_state = loop_.state();
|
||||
if (core_state == NavigationState::kPausing)
|
||||
{
|
||||
core_state = loop_.stateBeforePause();
|
||||
}
|
||||
robot::move_base_core::State host_state = toHostState(core_state);
|
||||
|
||||
// Một order nhiều chặng: lõi về SUCCEEDED sau MỖI chặng, còn order thì chưa xong. Host suy "order
|
||||
// hoàn thành" thẳng từ SUCCEEDED (amr_vda_5050_client_api.cpp:1062, 1092), nên báo nguyên trạng
|
||||
@@ -588,6 +607,16 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
|
||||
return;
|
||||
}
|
||||
|
||||
// Watchdog sau control thread: hàng control_loop chỉ có nghĩa khi thread đó đã quay. Watchdog
|
||||
// hỏng không phải lý do từ chối runtime — log rồi chạy tiếp không có nó.
|
||||
{
|
||||
std::string watchdog_error;
|
||||
if (!watchdog_.start(&runtime_->components(), runtime_->config().watchdog, watchdog_error))
|
||||
{
|
||||
robot::log_error("[move_base2] watchdog not started: %s\n", watchdog_error.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
nav_feedback_->is_ready = true;
|
||||
nav_feedback_->feed_back_str = "ready";
|
||||
refreshFeedback();
|
||||
@@ -1179,6 +1208,16 @@ robot_nav_2d_msgs::Twist2DStamped NavigationServer::getTwist()
|
||||
|
||||
robot::move_base_core::NavFeedback* NavigationServer::getFeedback()
|
||||
{
|
||||
// Control thread treo thì refreshFeedback() không chạy nữa và host sẽ đọc mãi state cuối cùng —
|
||||
// một CONTROLLING đóng băng trông y hệt một CONTROLLING đang chạy. Watchdog (thread riêng) là
|
||||
// nguồn duy nhất còn nói được; ghi đè ở đây, trên thread host. `LOST` là giá trị có sẵn trong
|
||||
// move_base_core::State, chưa ai dùng, nghĩa đúng: "lõi không còn theo dõi được goal".
|
||||
// Host đọc LOST phải tự zero cmd_vel (nav_c_api_2.h mục 6 đã bắt kiểm stamp của twist).
|
||||
if (watchdog_.controlLoopHung())
|
||||
{
|
||||
nav_feedback_->navigation_state = robot::move_base_core::State::LOST;
|
||||
nav_feedback_->feed_back_str = "control thread stalled: " + watchdog_.report();
|
||||
}
|
||||
return nav_feedback_.get();
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ const char* toString(NavigationState state)
|
||||
return "RECOVERING";
|
||||
case NavigationState::kExecutingActions:
|
||||
return "EXECUTING_ACTIONS";
|
||||
case NavigationState::kPausing:
|
||||
return "PAUSING";
|
||||
case NavigationState::kPaused:
|
||||
return "PAUSED";
|
||||
case NavigationState::kCancelling:
|
||||
|
||||
@@ -52,6 +52,9 @@ ActionTick ActionRunner::toTick(const action_core::ActionTick& tick)
|
||||
case action_core::ActionStatus::kSucceeded:
|
||||
out.status = ActionTick::Status::kSucceeded;
|
||||
break;
|
||||
case action_core::ActionStatus::kCancelled:
|
||||
out.status = ActionTick::Status::kCancelled;
|
||||
break;
|
||||
case action_core::ActionStatus::kFailed:
|
||||
out.status = ActionTick::Status::kFailed;
|
||||
break;
|
||||
@@ -131,6 +134,10 @@ bool ActionRunner::start(const robot_protocol_msgs::Action& action)
|
||||
|
||||
active_ = handler;
|
||||
active_action_id_ = action.actionId;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kBusy);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -151,17 +158,74 @@ ActionTick ActionRunner::update()
|
||||
if (tick.status != ActionTick::Status::kRunning)
|
||||
{
|
||||
active_ = nullptr;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
else if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->progress(Component::kAction);
|
||||
}
|
||||
|
||||
return tick;
|
||||
}
|
||||
|
||||
void ActionRunner::cancel()
|
||||
{
|
||||
if (active_ == nullptr)
|
||||
{
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
active_->cancel();
|
||||
|
||||
if (active_->cancelNeedsTicks())
|
||||
{
|
||||
// Handler thiết bị (2026-09-11): cancel() mới RA LỆNH dừng; giữ handler, tick tiếp trong
|
||||
// CANCELLING/PAUSING tới khi nó trả kCancelled/terminal. Hàng kAction = stopping cho tới lúc đó
|
||||
// — CANCELLED/PAUSED không được báo ra host trong lúc thiết bị còn đang về vị trí an toàn.
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kStopping);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handler perception/no-op: dừng xong ngay trong cancel(), quên nó, hàng về idle.
|
||||
active_ = nullptr;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
void ActionRunner::pause()
|
||||
{
|
||||
if (active_ != nullptr)
|
||||
{
|
||||
active_->cancel();
|
||||
active_ = nullptr;
|
||||
active_->pause(clock_->now());
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
// kPaused là "đã xác nhận tạm dừng": điều kiện quiescent của PAUSING chấp nhận nó.
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kPaused);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ActionRunner::resume()
|
||||
{
|
||||
if (active_ != nullptr)
|
||||
{
|
||||
active_->resume(clock_->now());
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kAction, ComponentPhase::kBusy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ PlannerRunner::~PlannerRunner()
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
shutdown_ = true;
|
||||
discard_ = true;
|
||||
preemptRunningLocked(); // shutdown không phải chờ hết allocated_time của lượt dở
|
||||
}
|
||||
cv_.notify_all();
|
||||
|
||||
@@ -102,6 +103,11 @@ PlannerRunner::~PlannerRunner()
|
||||
}
|
||||
}
|
||||
|
||||
void PlannerRunner::attachStatusBoard(ComponentStatusBoard* board)
|
||||
{
|
||||
status_board_ = board;
|
||||
}
|
||||
|
||||
void PlannerRunner::attachStats(RuntimeStats* stats)
|
||||
{
|
||||
stats_ = stats;
|
||||
@@ -366,11 +372,25 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
// Lượt đang chạy thuộc về planner cũ — kết quả của nó không còn nghĩa. Không cắt ngang được
|
||||
// phép tính, chỉ đánh dấu vứt kết quả. Con trỏ planner cũ vẫn hợp lệ vì cache không xoá entry.
|
||||
if (running_ || pending_)
|
||||
// Lượt đang chạy thuộc về planner cũ — kết quả của nó không còn nghĩa: đánh dấu vứt, và cắt
|
||||
// nếu plugin Preemptable. Con trỏ planner cũ vẫn hợp lệ vì cache không xoá entry.
|
||||
if (pending_ && !running_)
|
||||
{
|
||||
// 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;
|
||||
request_order_.reset();
|
||||
}
|
||||
else if (running_)
|
||||
{
|
||||
discard_ = true;
|
||||
// Lượt cũ vẫn chiếm thread; cắt nó ngay để yêu cầu kế (dùng planner mới) không phải chờ
|
||||
// planner_patience. Phải cắt TRƯỚC khi đổi active_ — sau dòng dưới active_ đã là instance mới.
|
||||
preemptRunningLocked();
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||
}
|
||||
}
|
||||
active_ = planner;
|
||||
}
|
||||
@@ -463,12 +483,49 @@ bool PlannerRunner::pollPlan(PlanResult& result)
|
||||
return true;
|
||||
}
|
||||
|
||||
void PlannerRunner::preemptRunningLocked()
|
||||
{
|
||||
// Gọi dưới mutex_. `running_planner_` là instance thread đang ở trong makePlan — KHÔNG phải
|
||||
// `active_`, vì swapPlanner có thể đã trỏ active_ sang instance khác trong lúc lượt cũ chưa về.
|
||||
// Instance cũ được cache/retired giữ sống nên con trỏ còn hợp lệ suốt lượt; preempt() là một
|
||||
// atomic store, gọi được từ control thread. Plugin không Preemptable: không có gì để làm.
|
||||
if (running_planner_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (auto* preemptable = dynamic_cast<robot_nav_core::Preemptable*>(running_planner_))
|
||||
{
|
||||
preemptable->preempt();
|
||||
}
|
||||
}
|
||||
|
||||
void PlannerRunner::cancelPlan()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (pending_ || running_)
|
||||
if (pending_ && !running_)
|
||||
{
|
||||
// Lượt đã được xếp nhưng thread chưa kịp nhận (cửa sổ giữa startPlan() và lúc thread thức dậy).
|
||||
// Rút nó ra khỏi hàng đợi là đủ — không có gì để preempt, và nếu chỉ đặt discard_ thì thread
|
||||
// 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;
|
||||
request_order_.reset();
|
||||
}
|
||||
else if (pending_ || running_)
|
||||
{
|
||||
discard_ = true;
|
||||
if (running_)
|
||||
{
|
||||
// Cắt thật (2026-09-11): plugin implement robot_nav_core::Preemptable thì lượt makePlan đang
|
||||
// chạy thoát trong vài ms thay vì đi tới hết allocated_time. Plugin cũ (không Preemptable)
|
||||
// thì chỉ còn discard_ như trước — kết quả về bị vứt, thread bận tới khi nó xong.
|
||||
preemptRunningLocked();
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
// Thread vẫn ở trong makePlan; từ giờ tới lúc nó trả về là "đang dừng", không phải "bận".
|
||||
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kStopping);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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;
|
||||
@@ -501,6 +558,7 @@ void PlannerRunner::threadBody()
|
||||
// Chụp lại yêu cầu rồi NHẢ MUTEX trước khi gọi plugin. Đây là điểm mấu chốt của cả mô hình:
|
||||
// control thread không bao giờ phải chờ một lượt lập plan.
|
||||
robot_nav_core::BaseGlobalPlanner* planner = active_;
|
||||
running_planner_ = planner;
|
||||
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_;
|
||||
@@ -508,6 +566,10 @@ void PlannerRunner::threadBody()
|
||||
|
||||
pending_ = false;
|
||||
running_ = true;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
|
||||
}
|
||||
|
||||
lock.unlock();
|
||||
|
||||
@@ -558,6 +620,11 @@ void PlannerRunner::threadBody()
|
||||
|
||||
lock.lock();
|
||||
running_ = false;
|
||||
running_planner_ = nullptr;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
|
||||
}
|
||||
|
||||
if (discard_)
|
||||
{
|
||||
|
||||
@@ -408,6 +408,10 @@ bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
|
||||
active_ = behavior;
|
||||
active_name_ = registry_.nameAt(index);
|
||||
active_trigger_ = trigger;
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
status_board_->enter(Component::kRecovery, ComponentPhase::kBusy);
|
||||
}
|
||||
|
||||
// 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Ừ
|
||||
@@ -434,6 +438,17 @@ RecoveryTick RecoveryRunner::update()
|
||||
|
||||
refreshContext();
|
||||
const RecoveryTick result = toTick(active_->update(deps_.clock->now()));
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
if (result.status == RecoveryTick::Status::kRunning)
|
||||
{
|
||||
status_board_->progress(Component::kRecovery);
|
||||
}
|
||||
else
|
||||
{
|
||||
status_board_->enter(Component::kRecovery, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
// 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).
|
||||
//
|
||||
@@ -465,6 +480,13 @@ void RecoveryRunner::cancel()
|
||||
{
|
||||
active_->cancel();
|
||||
}
|
||||
if (status_board_ != nullptr)
|
||||
{
|
||||
// Sau cancel() behavior không được tick nữa (CANCELLING ép tick_recovery=false): hàng phải về
|
||||
// idle ngay ở đây, không có tick nào sau để làm việc đó. Behavior có việc chạy dài (detour
|
||||
// worker) phải kết thúc việc đó bên trong cancel() của nó — xem RecoveryBehavior::onCancelRequested.
|
||||
status_board_->enter(Component::kRecovery, ComponentPhase::kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
RecoveryTick RecoveryRunner::toTick(const recovery_core::RecoveryResult& result) const
|
||||
|
||||
@@ -49,6 +49,18 @@ bool StateMachineConfig::validate(std::string& error) const
|
||||
"route cursor is refilled anyway, so a larger value can never take effect";
|
||||
return false;
|
||||
}
|
||||
if (settle_timeout < 0.0)
|
||||
{
|
||||
error = "settle_timeout must be >= 0 [s] (0 = finish CANCELLING/PAUSING as soon as the command "
|
||||
"is zero, without waiting for the planner thread)";
|
||||
return false;
|
||||
}
|
||||
if (stopped_measured_linear_eps < 0.0 || stopped_measured_angular_eps < 0.0)
|
||||
{
|
||||
error = "stopped_measured_linear_eps [m/s] and stopped_measured_angular_eps [rad/s] must be "
|
||||
">= 0 (0 = ignore odometry, judge 'stopped' from the issued command)";
|
||||
return false;
|
||||
}
|
||||
if (planner_patience <= 0.0 && max_planning_retries < 0)
|
||||
{
|
||||
// Từ khi lập plan chạy trên thread riêng, hai tham số này là thứ DUY NHẤT phát hiện được planner
|
||||
@@ -121,6 +133,15 @@ std::string StateMachineConfig::describe() const
|
||||
<< '\n';
|
||||
out << " max_planning_retries : " << max_planning_retries
|
||||
<< (max_planning_retries < 0 ? " (unlimited)" : "") << '\n';
|
||||
out << " settle_timeout : " << settle_timeout << " s"
|
||||
<< (settle_timeout > 0.0 ? "" : " (off — CANCELLED/PAUSED as soon as the command is zero)")
|
||||
<< '\n';
|
||||
out << " stopped_measured_eps : " << stopped_measured_linear_eps << " m/s, "
|
||||
<< stopped_measured_angular_eps << " rad/s"
|
||||
<< (stopped_measured_linear_eps > 0.0 || stopped_measured_angular_eps > 0.0
|
||||
? ""
|
||||
: " (off — 'stopped' judged from the issued command)")
|
||||
<< '\n';
|
||||
out << " recovery_enabled : " << (recovery_enabled ? "true" : "false") << '\n';
|
||||
out << " recovery_behavior_cnt : " << recovery_behavior_count << '\n';
|
||||
if (recovery_routes.empty())
|
||||
@@ -389,6 +410,45 @@ bool StateMachine::preemptIfRequested(const StateMachineInput& in, StateMachineO
|
||||
return true;
|
||||
}
|
||||
|
||||
void StateMachine::resumeFromPause(const StateMachineInput& in, StateMachineOutput& out)
|
||||
{
|
||||
// Đặt lại toàn bộ đồng hồ kiên nhẫn: một lần tạm dừng dài không được tính là "planner chậm"
|
||||
// hay "controller hỏng", nếu không thì resume xong là rơi thẳng vào recovery.
|
||||
beginPlanningCycle(in.now);
|
||||
last_valid_control_ = in.now;
|
||||
last_oscillation_reset_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
out.reset_oscillation_origin = true;
|
||||
travel_at_last_path_reset_ = 0.0; // origin đặt lại -> mốc recovery_reset_min_travel về 0
|
||||
|
||||
if (state_before_pause_ == NavigationState::kControlling)
|
||||
{
|
||||
// Nạp lại plan cho controller trước khi bám tiếp (2026-09-11). Local planner giữ trạng
|
||||
// thái nội bộ theo thời gian (warm-start trajectory, slew, latch) từ lúc robot còn chạy;
|
||||
// sau một quãng đứng yên trạng thái đó là của một robot khác. `setPlan` là đường reset
|
||||
// duy nhất mà interface LocalPlanner có — plugin reset warm-start theo pose hiện tại ở
|
||||
// đó. Bên gọi giữ nguyên plan mới nhất (`latest_plan_`) suốt lúc tạm dừng.
|
||||
out.apply_plan = true;
|
||||
out.run_controller = true;
|
||||
enter(NavigationState::kControlling, in.now, "resume following the plan", out);
|
||||
}
|
||||
else if (state_before_pause_ == NavigationState::kExecutingActions)
|
||||
{
|
||||
// Action không bị huỷ khi tạm dừng nên không start lại — tick tiếp đúng action dở dang.
|
||||
// Mốc action_patience được gieo lại: một quãng dừng dài không được tính vào trần thời
|
||||
// gian của action, nếu không resume xong là ABORTED oan ngay lập tức.
|
||||
action_started_at_ = in.now;
|
||||
out.resume_action = true; // Handler cộng quãng dừng vào mốc timeout của nó.
|
||||
out.tick_action = true;
|
||||
enter(NavigationState::kExecutingActions, in.now, "resume running the action", out);
|
||||
}
|
||||
else
|
||||
{
|
||||
out.start_planner = true;
|
||||
enter(NavigationState::kPlanning, in.now, "resume planning", out);
|
||||
}
|
||||
}
|
||||
|
||||
StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
StateMachineOutput out;
|
||||
@@ -442,7 +502,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
state_before_pause_ = NavigationState::kPlanning;
|
||||
enter(NavigationState::kPaused, in.now, "paused while planning", out);
|
||||
enter(NavigationState::kPausing, in.now, "pausing while planning", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -519,7 +579,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
state_before_pause_ = NavigationState::kControlling;
|
||||
enter(NavigationState::kPaused, in.now, "paused while following the plan", out);
|
||||
enter(NavigationState::kPausing, in.now, "pausing while following the plan", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -716,7 +776,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// dài là không an toàn (nó dead-reckon theo thời gian). Resume sẽ lập plan lại từ đầu.
|
||||
out.cancel_recovery = true;
|
||||
state_before_pause_ = NavigationState::kPlanning;
|
||||
enter(NavigationState::kPaused, in.now, "paused while recovering", out);
|
||||
enter(NavigationState::kPausing, in.now, "pausing while recovering", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -856,12 +916,14 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// dead-reckon, còn chạy lại một action thiết bị (nâng/hạ, sạc) từ đầu thì không chắc an
|
||||
// toàn — action không idempotent. Tạm dừng chỉ ngừng tick; resume tick tiếp đúng action đó.
|
||||
state_before_pause_ = NavigationState::kExecutingActions;
|
||||
enter(NavigationState::kPaused, in.now, "paused while running an action", out);
|
||||
out.pause_action = true; // Handler dịch mốc timeout của nó; không dừng thiết bị.
|
||||
enter(NavigationState::kPausing, in.now, "pausing while running an action", out);
|
||||
break;
|
||||
}
|
||||
|
||||
if (in.action == ActionFeedback::kFailed)
|
||||
if (in.action == ActionFeedback::kFailed || in.action == ActionFeedback::kCancelled)
|
||||
{
|
||||
// kCancelled ở đây là lỗi thứ tự gọi (không ai cancel trong EXECUTING_ACTIONS) — xử như hỏng.
|
||||
// Action hỏng không có đường recovery: recovery behavior là công cụ phục hồi NAVIGATION
|
||||
// (dọn costmap, lùi, xoay), không giúp gì được một thiết bị đang hỏng. Kết thúc tường minh
|
||||
// để mission layer quyết định làm gì với phần còn lại của order.
|
||||
@@ -909,6 +971,58 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
break;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------
|
||||
case NavigationState::kPausing:
|
||||
{
|
||||
// Đã nhận pause: stop_planner / cancel_recovery / pause_action đã phát ở cycle vào state,
|
||||
// arbiter đang phát 0. Ở đây chỉ chờ mọi thành phần IM rồi mới sang kPaused — host đọc
|
||||
// PAUSED là "đã dừng hẳn, làm gì cũng được" (2026-09-11). Cùng ba điều kiện quiescent với
|
||||
// kCancelling; `settle_timeout` là trần.
|
||||
if (preemptIfRequested(in, out))
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (in.cancel_requested)
|
||||
{
|
||||
enter(NavigationState::kCancelling, in.now, "cancelled while pausing", out);
|
||||
break;
|
||||
}
|
||||
if (in.resume_requested)
|
||||
{
|
||||
// Chưa kịp dừng hẳn đã được bảo chạy tiếp: đi đúng đường resume của kPaused.
|
||||
resumeFromPause(in, out);
|
||||
break;
|
||||
}
|
||||
|
||||
if (config_.settle_timeout <= 0.0)
|
||||
{
|
||||
if (in.robot_stopped)
|
||||
{
|
||||
enter(NavigationState::kPaused, in.now, "paused: robot stopped", out);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const bool quiescent = in.robot_stopped && !in.planner_busy && !in.recovery_busy && in.action_terminal;
|
||||
if (quiescent)
|
||||
{
|
||||
enter(NavigationState::kPaused, in.now, "paused: runtime quiescent", out);
|
||||
break;
|
||||
}
|
||||
if (secondsInState(in.now) > config_.settle_timeout)
|
||||
{
|
||||
out.settle_timed_out = true;
|
||||
enter(NavigationState::kPaused, in.now, "paused: settle timeout", out);
|
||||
break;
|
||||
}
|
||||
// Action đã được bảo tạm dừng ở cycle vào state; tick tiếp cho handler thiết bị xác nhận.
|
||||
if (!in.action_terminal)
|
||||
{
|
||||
out.tick_action = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------
|
||||
case NavigationState::kPaused:
|
||||
{
|
||||
@@ -926,34 +1040,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
}
|
||||
if (in.resume_requested)
|
||||
{
|
||||
// Đặt lại toàn bộ đồng hồ kiên nhẫn: một lần tạm dừng dài không được tính là "planner chậm"
|
||||
// hay "controller hỏng", nếu không thì resume xong là rơi thẳng vào recovery.
|
||||
beginPlanningCycle(in.now);
|
||||
last_valid_control_ = in.now;
|
||||
last_oscillation_reset_ = in.now;
|
||||
sensor_stale_active_ = false;
|
||||
out.reset_oscillation_origin = true;
|
||||
travel_at_last_path_reset_ = 0.0; // origin đặt lại -> mốc recovery_reset_min_travel về 0
|
||||
|
||||
if (state_before_pause_ == NavigationState::kControlling)
|
||||
{
|
||||
out.run_controller = true;
|
||||
enter(NavigationState::kControlling, in.now, "resume following the plan", out);
|
||||
}
|
||||
else if (state_before_pause_ == NavigationState::kExecutingActions)
|
||||
{
|
||||
// Action không bị huỷ khi tạm dừng nên không start lại — tick tiếp đúng action dở dang.
|
||||
// Mốc action_patience được gieo lại: một quãng dừng dài không được tính vào trần thời
|
||||
// gian của action, nếu không resume xong là ABORTED oan ngay lập tức.
|
||||
action_started_at_ = in.now;
|
||||
out.tick_action = true;
|
||||
enter(NavigationState::kExecutingActions, in.now, "resume running the action", out);
|
||||
}
|
||||
else
|
||||
{
|
||||
out.start_planner = true;
|
||||
enter(NavigationState::kPlanning, in.now, "resume planning", out);
|
||||
}
|
||||
resumeFromPause(in, out);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -962,12 +1049,44 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
case NavigationState::kCancelling:
|
||||
{
|
||||
// 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)
|
||||
// nguồn là kNone — xem VelocityArbiter::arbitrate). Lệnh 0 là điều kiện CẦN, chưa đủ để
|
||||
// báo CANCELLED (2026-09-11): host đọc CANCELLED/PREEMPTED là "đã xong, gửi goal kế được"
|
||||
// — mà goal kế bị `startPlan()` từ chối chừng nào thread planner còn chạy lượt cũ, và bị
|
||||
// tính là hỏng. Ba điều kiện quiescent: lệnh/odom về 0, thread planner rảnh, action đã trả
|
||||
// terminal. `settle_timeout` là trần: quá thì vẫn CANCELLED nhưng báo lỗi lên bên gọi.
|
||||
if (config_.settle_timeout <= 0.0)
|
||||
{
|
||||
// Tắt: hành vi trước 2026-09-11 — chỉ chờ lệnh về 0.
|
||||
if (in.robot_stopped)
|
||||
{
|
||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||
"robot came to a full stop", out);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const bool quiescent = in.robot_stopped && !in.planner_busy && !in.recovery_busy && in.action_terminal;
|
||||
if (quiescent)
|
||||
{
|
||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||
"robot came to a full stop", out);
|
||||
"robot stopped, planner and recovery idle, action terminal", out);
|
||||
break;
|
||||
}
|
||||
|
||||
if (secondsInState(in.now) > config_.settle_timeout)
|
||||
{
|
||||
out.settle_timed_out = true;
|
||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||
"cancel settle timeout", out);
|
||||
break;
|
||||
}
|
||||
|
||||
// Action đã bị bảo dừng ở cycle vào kCancelling; tick tiếp để handler thiết bị đưa thiết bị
|
||||
// về vị trí an toàn rồi báo terminal. Không cấp vận tốc — phần chốt bất biến cuối hàm ép
|
||||
// velocity_source về kNone cho mọi state phải dừng.
|
||||
if (!in.action_terminal)
|
||||
{
|
||||
out.tick_action = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user