- SensorGateway::pushStaticMap also dispatches to DIRECTIONAL_LAYER on the global costmap, before STATIC_LAYER: with a same-geometry map the directional layer goes PENDING before StaticLayer can report current, so a plan cannot pair the new map with the old zones. - Static maps are replayed in arrival order instead of topic order, so a direction grid is never replayed before its static map. - PlannerRunner checks every enabled global layer under the same lock as the snapshot. While a layer is not current it keeps the goal, reports waiting_for_costmap, logs the stale layers (throttled) and spends no planner_patience or watchdog budget. After costmap_ready_timeout [s] (default 10, 0 = legacy behaviour) the attempt fails as before. The key is added to config/runtime/move_base_common_params.yaml. - Test fixture destroys the server before its fake ports (the control thread could call a destroyed port). Full history: branch feature/direction-zone.
1221 lines
53 KiB
C++
1221 lines
53 KiB
C++
/*********************************************************************
|
|
*
|
|
* Software License Agreement (BSD License)
|
|
*
|
|
* move_base2 — cài đặt state machine. Bảng chuyển đầy đủ, không I/O, không logging.
|
|
*
|
|
* Author: DuongTD
|
|
*********************************************************************/
|
|
#include <move_base2/core/state_machine.h>
|
|
|
|
#include <algorithm>
|
|
#include <sstream>
|
|
|
|
namespace move_base2
|
|
{
|
|
|
|
// ================================================================================================
|
|
// StateMachineConfig
|
|
// ================================================================================================
|
|
|
|
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]";
|
|
return false;
|
|
}
|
|
if (oscillation_timeout > 0.0 && oscillation_distance <= 0.0)
|
|
{
|
|
error = "oscillation_timeout is enabled so oscillation_distance must be > 0 [m], otherwise "
|
|
"every cycle counts as oscillating";
|
|
return false;
|
|
}
|
|
if (recovery_reset_min_travel < 0.0)
|
|
{
|
|
error = "recovery_reset_min_travel must be >= 0 [m] (0 = a new path always refills the route)";
|
|
return false;
|
|
}
|
|
if (oscillation_distance > 0.0 && recovery_reset_min_travel > oscillation_distance)
|
|
{
|
|
error = "recovery_reset_min_travel must be <= oscillation_distance [m]: past that distance every "
|
|
"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
|
|
// treo. Tắt cả hai nghĩa là một plugin không bao giờ trả lời sẽ giữ robot ở PLANNING vĩnh viễn,
|
|
// im lặng, và state machine tin rằng mọi thứ bình thường. Ở chế độ đồng bộ trước đây điều này
|
|
// vô hại hơn nhiều vì planner treo làm treo luôn control loop — hỏng thì thấy ngay.
|
|
error = "planner_patience <= 0 [s] and max_planning_retries < 0 at the same time: nothing can "
|
|
"detect a hung planner; set at least one of them";
|
|
return false;
|
|
}
|
|
if (recovery_enabled && recovery_behavior_count == 0)
|
|
{
|
|
// Không phải lỗi cấu hình chết người, nhưng để im lặng thì lúc chạy sẽ ABORTED ngay ở lỗi đầu
|
|
// tiên mà không ai hiểu vì sao. Bắt buộc khai báo tường minh recovery_enabled = false.
|
|
error = "recovery_enabled = true but recovery_behavior_count = 0; set recovery_enabled = false "
|
|
"if you really do not want recovery";
|
|
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 = [&indices_valid](const std::vector<std::size_t>& route) {
|
|
return !route.empty() && indices_valid(route);
|
|
};
|
|
|
|
if (!valid_route(recovery_routes.planning_failed) ||
|
|
!valid_route(recovery_routes.controlling_failed) ||
|
|
!valid_route(recovery_routes.oscillation))
|
|
{
|
|
error = "every configured recovery route must be non-empty and reference a loaded behavior";
|
|
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) ||
|
|
!indices_valid(recovery_routes.collision))
|
|
{
|
|
error = "recovery route 'path_blocked'/'off_path'/'collision' references a behavior that was "
|
|
"not loaded";
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
std::string StateMachineConfig::describe() const
|
|
{
|
|
std::ostringstream out;
|
|
out << "StateMachineConfig:\n";
|
|
out << " planner_patience : " << planner_patience << " s"
|
|
<< (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"
|
|
<< (action_patience > 0.0 ? "" : " (off — handler times out on its own)") << '\n';
|
|
out << " oscillation_distance : " << oscillation_distance << " m\n";
|
|
out << " recovery_reset_min_travel : " << recovery_reset_min_travel << " m"
|
|
<< (recovery_reset_min_travel > 0.0 ? "" : " (off — a new path always refills the route)")
|
|
<< '\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())
|
|
{
|
|
out << " recovery_routes : legacy shared list\n";
|
|
}
|
|
else
|
|
{
|
|
out << " recovery_routes : planning=" << recovery_routes.planning_failed.size()
|
|
<< " controlling=" << recovery_routes.controlling_failed.size()
|
|
<< " oscillation=" << recovery_routes.oscillation.size()
|
|
<< " path_blocked=" << recovery_routes.path_blocked.size()
|
|
<< " off_path=" << recovery_routes.off_path.size()
|
|
<< " collision=" << recovery_routes.collision.size() << '\n';
|
|
}
|
|
return out.str();
|
|
}
|
|
|
|
// ================================================================================================
|
|
// StateMachine
|
|
// ================================================================================================
|
|
|
|
bool StateMachine::configure(const StateMachineConfig& config, std::string& error)
|
|
{
|
|
config_ = config;
|
|
|
|
// Schema cũ không có `recovery/routes`: giữ nguyên một list chung cho mọi trigger. Normalise ở
|
|
// đây, sau khi RecoveryRunner đã báo số plugin nạp được thật, để phần còn lại của state machine
|
|
// chỉ xử lý route đã resolve.
|
|
if (config_.recovery_routes.empty())
|
|
{
|
|
for (std::size_t index = 0; index < config_.recovery_behavior_count; ++index)
|
|
{
|
|
config_.recovery_routes.planning_failed.push_back(index);
|
|
config_.recovery_routes.controlling_failed.push_back(index);
|
|
config_.recovery_routes.oscillation.push_back(index);
|
|
}
|
|
}
|
|
|
|
if (!config_.validate(error))
|
|
{
|
|
initialized_ = false;
|
|
return false;
|
|
}
|
|
|
|
initialized_ = true;
|
|
reset();
|
|
return true;
|
|
}
|
|
|
|
void StateMachine::reset()
|
|
{
|
|
state_ = NavigationState::kIdle;
|
|
state_before_pause_ = NavigationState::kIdle;
|
|
state_entered_at_ = robot::Time();
|
|
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);
|
|
has_path_reset_mark_ = false;
|
|
travel_at_last_path_reset_ = 0.0;
|
|
planning_retries_ = 0;
|
|
request_has_goal_ = true;
|
|
action_count_ = 0;
|
|
action_index_ = 0;
|
|
action_started_at_ = robot::Time();
|
|
}
|
|
|
|
double StateMachine::secondsInState(const robot::Time& now) const
|
|
{
|
|
return (now - state_entered_at_).toSec();
|
|
}
|
|
|
|
void StateMachine::enter(NavigationState next, const robot::Time& now, const char* reason,
|
|
StateMachineOutput& out)
|
|
{
|
|
if (next != state_)
|
|
{
|
|
state_ = next;
|
|
state_entered_at_ = now;
|
|
out.state_changed = true;
|
|
}
|
|
out.state = state_;
|
|
out.reason = reason;
|
|
}
|
|
|
|
void StateMachine::beginPlanningCycle(const robot::Time& now)
|
|
{
|
|
last_valid_plan_ = now;
|
|
planning_retries_ = 0;
|
|
}
|
|
|
|
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 0;
|
|
case RecoveryTrigger::kControllingFailed:
|
|
return 1;
|
|
case RecoveryTrigger::kOscillation:
|
|
return 2;
|
|
case RecoveryTrigger::kPathBlocked:
|
|
return 3;
|
|
case RecoveryTrigger::kOffPath:
|
|
return 4;
|
|
case RecoveryTrigger::kCollision:
|
|
return 5;
|
|
}
|
|
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
|
|
{
|
|
return recovery_route_cursors_[cursorSlot(trigger)];
|
|
}
|
|
|
|
bool StateMachine::isMonitorTrigger(RecoveryTrigger trigger)
|
|
{
|
|
return trigger == RecoveryTrigger::kPathBlocked || trigger == RecoveryTrigger::kOffPath ||
|
|
trigger == RecoveryTrigger::kCollision;
|
|
}
|
|
|
|
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,
|
|
const char* reason, StateMachineOutput& out)
|
|
{
|
|
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_;
|
|
enter(NavigationState::kRecovering, now, reason, out);
|
|
}
|
|
|
|
void StateMachine::finish(NavigationState terminal, NavigationOutcome outcome,
|
|
const robot::Time& now, const char* reason, StateMachineOutput& out)
|
|
{
|
|
// Cờ này bật đúng tại cycle bước vào state terminal, và state terminal chỉ tồn tại một cycle
|
|
// (cycle sau đã về kIdle). Đó là toàn bộ cơ chế giữ bất biến "báo kết quả đúng một lần".
|
|
out.report_outcome = true;
|
|
out.outcome = outcome;
|
|
out.stop_planner = true;
|
|
enter(terminal, now, reason, out);
|
|
}
|
|
|
|
void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachineOutput& out)
|
|
{
|
|
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;
|
|
action_index_ = 0;
|
|
|
|
if (!request_has_goal_)
|
|
{
|
|
// D8: yêu cầu chỉ-có-action — không có gì để lập plan, vào thẳng thực thi action.
|
|
if (action_count_ == 0)
|
|
{
|
|
// Không goal lẫn action là vi phạm contract; mission layer đã validate nhưng lõi vẫn phải tự
|
|
// vệ: kết thúc tường minh thay vì treo ở một state không có đường ra.
|
|
finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now,
|
|
"request has neither goal nor action", out);
|
|
return;
|
|
}
|
|
out.start_action = true;
|
|
out.action_index = 0;
|
|
action_started_at_ = in.now;
|
|
enter(NavigationState::kExecutingActions, in.now, "action-only request", out);
|
|
return;
|
|
}
|
|
|
|
out.start_planner = true;
|
|
beginPlanningCycle(in.now);
|
|
last_valid_control_ = in.now;
|
|
last_oscillation_reset_ = in.now;
|
|
sensor_stale_active_ = false;
|
|
monitor_trigger_suppressed_.fill(false);
|
|
has_path_reset_mark_ = false; // origin đo quãng đường đặt lại ngay dưới -> mốc cũ vô nghĩa
|
|
travel_at_last_path_reset_ = 0.0;
|
|
out.reset_oscillation_origin = true;
|
|
enter(NavigationState::kPlanning, in.now, "new request accepted", out);
|
|
}
|
|
|
|
bool StateMachine::preemptIfRequested(const StateMachineInput& in, StateMachineOutput& out)
|
|
{
|
|
if (!in.has_pending_request)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// Dọn sạch yêu cầu cũ TRƯỚC khi nhận yêu cầu mới: planner đang chạy phải bị huỷ (kết quả của nó
|
|
// thuộc goal cũ), recovery và action đang chạy phải được bảo dừng an toàn.
|
|
out.stop_planner = true;
|
|
if (state_ == NavigationState::kRecovering)
|
|
{
|
|
out.cancel_recovery = true;
|
|
}
|
|
if (state_ == NavigationState::kExecutingActions)
|
|
{
|
|
out.cancel_action = true;
|
|
}
|
|
|
|
// Báo kết quả cho chặng cũ ĐÚNG MỘT LẦN, ngay tại đây. Không báo thì mission layer chờ vĩnh viễn
|
|
// một chặng đã bị thay.
|
|
out.report_outcome = true;
|
|
out.outcome = NavigationOutcome::kPreempted;
|
|
|
|
acceptPendingRequest(in, out);
|
|
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;
|
|
out.state = state_;
|
|
out.recovery_index = recovery_index_;
|
|
|
|
if (!initialized_)
|
|
{
|
|
// Guard bắt buộc: không bao giờ quyết định điều khiển khi chưa configure.
|
|
out.state = NavigationState::kIdle;
|
|
out.velocity_source = VelocitySource::kNone;
|
|
out.reason = "not configured";
|
|
return out;
|
|
}
|
|
|
|
// State terminal chỉ sống một cycle. Về kIdle ngay đầu cycle kế tiếp để yêu cầu mới được nhận
|
|
// không phải chờ thêm một vòng.
|
|
if (isTerminal(state_))
|
|
{
|
|
enter(NavigationState::kIdle, in.now, "request finished", out);
|
|
}
|
|
|
|
// Dừng khẩn xét TRƯỚC mọi thứ, kể cả cancel (2026-09-14). Là mức chứ không phải xung: chừng nào
|
|
// host còn giữ thì không nhánh nào của switch bên dưới được chạy — pause/resume/cancel/goal chờ
|
|
// đều bị bỏ qua, và cả kIdle có goal chờ cũng không được nhận. Chỉ khi host gỡ chốt mới về kIdle.
|
|
if (in.emergency)
|
|
{
|
|
if (state_ != NavigationState::kEmergency)
|
|
{
|
|
enterEmergency(in, out);
|
|
}
|
|
else if (!in.action_terminal)
|
|
{
|
|
// Cùng lý do với kCancelling: handler thiết bị cần tick để đư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 kNone cho mọi state phải dừng.
|
|
out.tick_action = true;
|
|
}
|
|
applyInvariants(in, out);
|
|
return out;
|
|
}
|
|
if (state_ == NavigationState::kEmergency)
|
|
{
|
|
// Cố ý KHÔNG nhận goal trong cùng cycle: ControlLoop đã vứt yêu cầu chờ lúc vào dừng khẩn và
|
|
// NavigationServer từ chối submit khi còn chốt, nên không có gì hợp lệ để nhận ở đây. Cycle kế
|
|
// kIdle nhận bình thường — host phải gửi goal mới, robot không tự chạy lại.
|
|
enter(NavigationState::kIdle, in.now, "emergency cleared", out);
|
|
applyInvariants(in, out);
|
|
return out;
|
|
}
|
|
|
|
// Mất pose nghĩa là không biết robot ở đâu. Khi đó controller không được chạy, và không nguồn nào
|
|
// được phát vận tốc — kể cả recovery. Recovery vẫn được tick để nó tự báo lỗi theo contract của
|
|
// nó, nhưng lệnh nó sinh ra bị chặn ở phần chốt bất biến cuối hàm.
|
|
const ControllerFeedback controller =
|
|
in.pose_available ? in.controller : ControllerFeedback::kNoValidCommand;
|
|
|
|
switch (state_)
|
|
{
|
|
// --------------------------------------------------------------------------------------
|
|
case NavigationState::kIdle:
|
|
{
|
|
if (in.has_pending_request)
|
|
{
|
|
acceptPendingRequest(in, out);
|
|
}
|
|
break;
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
case NavigationState::kPlanning:
|
|
{
|
|
if (in.cancel_requested)
|
|
{
|
|
out.stop_planner = true;
|
|
enter(NavigationState::kCancelling, in.now, "cancelled while planning", out);
|
|
break;
|
|
}
|
|
if (in.pause_requested)
|
|
{
|
|
out.stop_planner = true;
|
|
state_before_pause_ = NavigationState::kPlanning;
|
|
enter(NavigationState::kPausing, in.now, "pausing while planning", out);
|
|
break;
|
|
}
|
|
|
|
// Goal mới chen ngang: thay ngay, không xếp hàng.
|
|
if (preemptIfRequested(in, out))
|
|
{
|
|
break;
|
|
}
|
|
|
|
// Waiting for input is not planning time and must not consume the retry budget.
|
|
// The completion event also covers a wait which began and ended between control cycles.
|
|
if (in.planner_costmap_wait_finished || in.planner == PlannerFeedback::kWaitingForCostmap)
|
|
last_valid_plan_ = in.now;
|
|
if (in.planner == PlannerFeedback::kWaitingForCostmap)
|
|
break;
|
|
|
|
if (in.planner == PlannerFeedback::kPlanReady)
|
|
{
|
|
out.apply_plan = true;
|
|
out.run_controller = true; // Chạy controller ngay trong cycle này, không phí một vòng.
|
|
beginPlanningCycle(in.now);
|
|
|
|
// Cố ý KHÔNG làm mới last_valid_control_ và last_oscillation_reset_ ở đây. Có plan mới
|
|
// không chứng minh được gì về controller: nếu reset thì vòng lặp
|
|
// CONTROLLING -> PLANNING -> CONTROLLING sẽ làm mới đồng hồ mỗi vòng, và một controller
|
|
// hỏng vĩnh viễn sẽ không bao giờ chạm controller_patience. Hai đồng hồ đó chỉ được đặt lại
|
|
// ở ba chỗ: nhận yêu cầu mới, tiếp tục sau tạm dừng, và sau khi recovery chạy xong.
|
|
enter(NavigationState::kControlling, in.now, "valid plan available", out);
|
|
break;
|
|
}
|
|
|
|
if (in.planner == PlannerFeedback::kFailed)
|
|
{
|
|
++planning_retries_;
|
|
}
|
|
|
|
const bool retries_exhausted = config_.max_planning_retries >= 0 &&
|
|
planning_retries_ > config_.max_planning_retries;
|
|
const bool patience_exhausted =
|
|
config_.planner_patience > 0.0 &&
|
|
(in.now - last_valid_plan_).toSec() > config_.planner_patience;
|
|
|
|
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);
|
|
break;
|
|
}
|
|
|
|
out.start_planner = true; // Giữ planner chạy tiếp.
|
|
break;
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
case NavigationState::kControlling:
|
|
{
|
|
if (in.cancel_requested)
|
|
{
|
|
out.stop_planner = true;
|
|
enter(NavigationState::kCancelling, in.now, "cancelled while following the plan", out);
|
|
break;
|
|
}
|
|
if (in.pause_requested)
|
|
{
|
|
out.stop_planner = true;
|
|
state_before_pause_ = NavigationState::kControlling;
|
|
enter(NavigationState::kPausing, in.now, "pausing while following the plan", out);
|
|
break;
|
|
}
|
|
|
|
// Goal mới chen ngang: thay ngay, không xếp hàng.
|
|
if (preemptIfRequested(in, out))
|
|
{
|
|
break;
|
|
}
|
|
|
|
// Plan mới tới giữa lúc đang bám plan cũ: nhận ngay, vẫn ở kControlling.
|
|
if (in.planner == PlannerFeedback::kPlanReady)
|
|
{
|
|
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.
|
|
if (config_.oscillation_distance > 0.0 &&
|
|
in.travelled_since_oscillation_reset >= config_.oscillation_distance)
|
|
{
|
|
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);
|
|
|
|
// Origin vừa đặt lại nên travelled_since_oscillation_reset sẽ về 0 ở cycle sau; mốc của
|
|
// recovery_reset_min_travel phải đi theo, nếu không hiệu số âm sẽ khoá nạp lại vĩnh viễn.
|
|
has_path_reset_mark_ = false;
|
|
travel_at_last_path_reset_ = 0.0;
|
|
}
|
|
|
|
if (controller == ControllerFeedback::kGoalReached)
|
|
{
|
|
if (action_count_ > 0)
|
|
{
|
|
// D8: tới goal chưa phải là xong — mission còn action phải chạy tại chỗ. Kết quả chỉ
|
|
// được báo sau action cuối, để mission layer thấy trọn một chặng nav + action.
|
|
out.stop_planner = true;
|
|
out.start_action = true;
|
|
out.action_index = action_index_;
|
|
action_started_at_ = in.now;
|
|
enter(NavigationState::kExecutingActions, in.now, "goal reached, actions still to run",
|
|
out);
|
|
break;
|
|
}
|
|
finish(NavigationState::kSucceeded, NavigationOutcome::kSucceeded, in.now, "goal reached",
|
|
out);
|
|
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.
|
|
//
|
|
// Thứ tự ưu tiên khi nhiều cờ cùng đúng: `collision` (2026-09-04, Phép đo 3 — thân sắp chạm
|
|
// trong 0.2 m) > `path_blocked` (tuyến tắc, 3 m trước) > `off_path`. Gần nhất xử lý trước;
|
|
// 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 đó. Mỗi trigger có route, cursor và khoá riêng — Phép đo 3 cạn route
|
|
// không làm Phép đo 1 mất lượt.
|
|
//
|
|
// 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ó.
|
|
const bool collision_open =
|
|
in.collision && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kCollision)];
|
|
const bool blocked_open =
|
|
in.path_blocked && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kPathBlocked)];
|
|
const bool off_path_open =
|
|
in.off_path && !monitor_trigger_suppressed_[cursorSlot(RecoveryTrigger::kOffPath)];
|
|
if (collision_open || blocked_open || off_path_open)
|
|
{
|
|
const RecoveryTrigger trigger = collision_open ? RecoveryTrigger::kCollision
|
|
: blocked_open ? RecoveryTrigger::kPathBlocked
|
|
: RecoveryTrigger::kOffPath;
|
|
out.stop_planner = true;
|
|
escalateToRecovery(trigger, in.now,
|
|
collision_open ? "the body is about to hit an obstacle"
|
|
: blocked_open ? "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;
|
|
|
|
// kStall (EnvMonitor): controller vẫn ra lệnh hợp lệ nhưng robot không đi được đâu.
|
|
if (in.no_progress)
|
|
{
|
|
out.stop_planner = true;
|
|
escalateToRecovery(RecoveryTrigger::kOscillation, in.now, "no progress along the plan",
|
|
out);
|
|
break;
|
|
}
|
|
|
|
if (config_.oscillation_timeout > 0.0 &&
|
|
(in.now - last_oscillation_reset_).toSec() > config_.oscillation_timeout)
|
|
{
|
|
out.stop_planner = true;
|
|
escalateToRecovery(RecoveryTrigger::kOscillation, in.now, "oscillating in place too long",
|
|
out);
|
|
break;
|
|
}
|
|
|
|
out.run_controller = true;
|
|
break;
|
|
}
|
|
|
|
// 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)
|
|
{
|
|
out.stop_planner = true;
|
|
escalateToRecovery(RecoveryTrigger::kControllingFailed, in.now,
|
|
"velocity command generation timed out", out);
|
|
break;
|
|
}
|
|
|
|
out.run_controller = true;
|
|
break;
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
case NavigationState::kRecovering:
|
|
{
|
|
// Goal mới chen ngang: thay ngay, không xếp hàng. Đặt TRƯỚC mọi xử lý khác của state này —
|
|
// yêu cầu cũ đã bị thay thì mọi quyết định dựa trên nó đều vô nghĩa.
|
|
if (preemptIfRequested(in, out))
|
|
{
|
|
break;
|
|
}
|
|
|
|
if (in.cancel_requested)
|
|
{
|
|
out.cancel_recovery = true;
|
|
enter(NavigationState::kCancelling, in.now, "cancelled while recovering", out);
|
|
break;
|
|
}
|
|
if (in.pause_requested)
|
|
{
|
|
// Recovery bị huỷ khi tạm dừng: giữ một behavior ở trạng thái dở dang qua một quãng dừng
|
|
// 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::kPausing, in.now, "pausing while recovering", out);
|
|
break;
|
|
}
|
|
|
|
if (in.recovery == RecoveryFeedback::kSucceeded || in.recovery == RecoveryFeedback::kFailed)
|
|
{
|
|
// 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.
|
|
//
|
|
// ĐIỀU KIỆN THÊM (2026-09-04): "path mới" chỉ nạp lại ngân sách khi robot ĐÃ DỊCH CHUYỂN ít
|
|
// nhất recovery_reset_min_travel kể từ lần nạp lại trước. Sim 4/9: collision guard chặn tại
|
|
// chỗ -> detour lập lại đúng đường cũ (cost y hệt, 0 ms) -> cursor về 0 -> chặn lại sau 2
|
|
// cycle -> 249 vòng trong 52 s, robot bất động, controller_patience không bao giờ tích đủ vì
|
|
// path_blocked chen trước mỗi 0.2 s. Một path mới mà robot không đi được một bước nào trên
|
|
// đó không giải quyết sự cố gì, nên nó ăn vào ngân sách như một lần thất bại: route cạn ->
|
|
// mute (05e) -> guard vẫn báo no_valid_command -> controller_patience -> controlling_failed
|
|
// -> cạn -> ABORT có lý do. Có dịch chuyển thật (0.45 m của ca 08-05) thì vẫn nạp lại như cũ.
|
|
const bool recovered_with_new_path = in.recovery == RecoveryFeedback::kSucceeded &&
|
|
in.planner == PlannerFeedback::kPlanReady;
|
|
std::size_t& cursor = recoveryRouteCursor(active_recovery_trigger_);
|
|
bool refill = false;
|
|
if (recovered_with_new_path)
|
|
{
|
|
const double travelled = in.travelled_since_oscillation_reset - travel_at_last_path_reset_;
|
|
refill = !has_path_reset_mark_ || config_.recovery_reset_min_travel <= 0.0 ||
|
|
travelled >= config_.recovery_reset_min_travel;
|
|
if (refill)
|
|
{
|
|
has_path_reset_mark_ = true;
|
|
travel_at_last_path_reset_ = in.travelled_since_oscillation_reset;
|
|
}
|
|
else
|
|
{
|
|
out.recovery_reset_denied = true;
|
|
out.recovery_reset_travel = std::max(0.0, travelled);
|
|
out.recovery_trigger = active_recovery_trigger_; // để bên gọi log đúng route bị trừ
|
|
}
|
|
}
|
|
if (refill)
|
|
{
|
|
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;
|
|
// Origin đo quãng đường đặt lại ngay tại đây, nên từ cycle sau travelled đếm từ 0 kể từ
|
|
// đúng lúc path mới được áp — chính là quãng mà recovery_reset_min_travel muốn đo. Mốc phải
|
|
// về 0 theo (GIỮ has_path_reset_mark_): sim 4/9 mission 3 robot đi 0.18 m sau path mới mà
|
|
// vẫn bị tính "0.00 m" vì mốc còn giữ giá trị của origin cũ.
|
|
travel_at_last_path_reset_ = 0.0;
|
|
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",
|
|
out);
|
|
break;
|
|
}
|
|
|
|
out.tick_recovery = true;
|
|
break;
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
case NavigationState::kExecutingActions:
|
|
{
|
|
// Goal mới chen ngang: thay ngay, không xếp hàng. Đặt TRƯỚC mọi xử lý khác của state này —
|
|
// yêu cầu cũ đã bị thay thì mọi quyết định dựa trên nó đều vô nghĩa.
|
|
if (preemptIfRequested(in, out))
|
|
{
|
|
break;
|
|
}
|
|
|
|
if (in.cancel_requested)
|
|
{
|
|
out.cancel_action = true;
|
|
enter(NavigationState::kCancelling, in.now, "cancelled while running an action", out);
|
|
break;
|
|
}
|
|
if (in.pause_requested)
|
|
{
|
|
// Khác recovery, action KHÔNG bị huỷ khi tạm dừng: robot đang đứng yên nên không có rủi ro
|
|
// 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;
|
|
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 || 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.
|
|
//
|
|
// Mang theo lý do của handler: nó đi tiếp ra host qua feedback, nên đây là chỗ duy nhất
|
|
// người vận hành thấy được action nào hỏng vì cái gì.
|
|
// Giữ trong member: `out.reason` chỉ lưu con trỏ (xem @ref action_failure_reason_).
|
|
action_failure_reason_ = in.action_message.empty()
|
|
? std::string("action failed")
|
|
: "action failed: " + in.action_message;
|
|
finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now,
|
|
action_failure_reason_.c_str(), out);
|
|
break;
|
|
}
|
|
|
|
if (in.action == ActionFeedback::kSucceeded)
|
|
{
|
|
++action_index_;
|
|
if (action_index_ < action_count_)
|
|
{
|
|
out.start_action = true;
|
|
out.action_index = action_index_;
|
|
action_started_at_ = in.now; // Trần thời gian tính cho TỪNG action, không cho cả chuỗi.
|
|
break; // Vẫn ở kExecutingActions, chuyển sang action kế tiếp.
|
|
}
|
|
finish(NavigationState::kSucceeded, NavigationOutcome::kSucceeded, in.now,
|
|
"last action finished", out);
|
|
break;
|
|
}
|
|
|
|
// Lưới an toàn cuối cùng cho action treo (handler hỏng, thiết bị câm lặng vĩnh viễn).
|
|
// Cơ chế timeout CHÍNH là của từng ActionHandler; lưới này mặc định tắt.
|
|
if (config_.action_patience > 0.0 &&
|
|
(in.now - action_started_at_).toSec() > config_.action_patience)
|
|
{
|
|
out.cancel_action = true; // Bảo port dừng thiết bị an toàn trước khi kết thúc chặng.
|
|
finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now,
|
|
"action exceeded action_patience", out);
|
|
break;
|
|
}
|
|
|
|
// Mất pose KHÔNG chặn tick action: robot đứng yên, thao tác thiết bị không cần định vị.
|
|
// Vận tốc vẫn bị ép về 0 ở phần chốt bất biến cuối hàm như mọi state phải dừng khác.
|
|
out.tick_action = true;
|
|
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:
|
|
{
|
|
// Goal mới chen ngang: thay ngay, không xếp hàng. Đặt TRƯỚC mọi xử lý khác của state này —
|
|
// yêu cầu cũ đã bị thay thì mọi quyết định dựa trên nó đều vô nghĩa.
|
|
if (preemptIfRequested(in, out))
|
|
{
|
|
break;
|
|
}
|
|
|
|
if (in.cancel_requested)
|
|
{
|
|
enter(NavigationState::kCancelling, in.now, "cancelled while paused", out);
|
|
break;
|
|
}
|
|
if (in.resume_requested)
|
|
{
|
|
resumeFromPause(in, out);
|
|
}
|
|
break;
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
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). 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 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;
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
case NavigationState::kSucceeded:
|
|
case NavigationState::kAborted:
|
|
case NavigationState::kCancelled:
|
|
// Không tới được: đã chuyển về kIdle ở đầu hàm.
|
|
break;
|
|
}
|
|
|
|
applyInvariants(in, out);
|
|
return out;
|
|
}
|
|
|
|
void StateMachine::applyInvariants(const StateMachineInput& in, StateMachineOutput& out)
|
|
{
|
|
// ------------------------------------------------------------------------------------------
|
|
// Chốt bất biến trước khi trả ra. Đây là hàng rào an toàn cuối cùng của lõi — MỌI đường ra của
|
|
// update() đều phải qua đây, kể cả hai đường về sớm của dừng khẩn.
|
|
// ------------------------------------------------------------------------------------------
|
|
out.state = state_;
|
|
|
|
if (state_ == NavigationState::kControlling)
|
|
{
|
|
out.velocity_source = VelocitySource::kController;
|
|
}
|
|
else if (state_ == NavigationState::kRecovering)
|
|
{
|
|
// Chỉ behavior thật sự lái robot mới được cấp quyền phát vận tốc. Behavior one-shot (đợi, xoá
|
|
// costmap) giữ nguồn ở kNone, nên arbiter không phải đổi nguồn hai lần cho một lượt không có
|
|
// vận tốc nào — mỗi lần đổi nguồn tốn một cycle zero (mục 1.6).
|
|
out.velocity_source = in.active_recovery_output == RecoveryOutputKind::kVelocity
|
|
? VelocitySource::kRecovery
|
|
: VelocitySource::kNone;
|
|
}
|
|
else
|
|
{
|
|
out.velocity_source = VelocitySource::kNone;
|
|
}
|
|
|
|
if (!in.pose_available)
|
|
{
|
|
out.velocity_source = VelocitySource::kNone;
|
|
out.run_controller = false;
|
|
}
|
|
|
|
if (mustBeStopped(state_))
|
|
{
|
|
out.velocity_source = VelocitySource::kNone;
|
|
out.run_controller = false;
|
|
out.tick_recovery = false;
|
|
}
|
|
}
|
|
|
|
bool StateMachine::actionInFlight() const
|
|
{
|
|
if (state_ == NavigationState::kExecutingActions)
|
|
{
|
|
return true;
|
|
}
|
|
// Tạm dừng KHÔNG huỷ action (xem kExecutingActions): handler vẫn đang giữ thiết bị dở dang.
|
|
return (state_ == NavigationState::kPausing || state_ == NavigationState::kPaused) &&
|
|
state_before_pause_ == NavigationState::kExecutingActions;
|
|
}
|
|
|
|
void StateMachine::enterEmergency(const StateMachineInput& in, StateMachineOutput& out)
|
|
{
|
|
// Dọn như preempt + cancel gộp: mọi thứ đang chạy đều bị bảo dừng. Từng cờ theo state để test
|
|
// khẳng định được "chỉ dừng cái đang chạy" — runner tự no-op khi rảnh, nhưng output phải nói thật.
|
|
out.stop_planner = true;
|
|
if (state_ == NavigationState::kRecovering)
|
|
{
|
|
out.cancel_recovery = true;
|
|
}
|
|
// kCancelling đã phát cancel_action ở cycle vào nó — không phát lần hai.
|
|
if (actionInFlight())
|
|
{
|
|
out.cancel_action = true;
|
|
}
|
|
|
|
// Chặng đang chạy được báo CANCELLED đúng một lần, ngay tại đây (state ≠ kIdle ⇔ có yêu cầu đang
|
|
// chạy). kCancelling chưa báo (nó báo lúc vào kCancelled) nên vẫn phải báo. Không có state terminal
|
|
// xen giữa — kEmergency là nơi ở lại, và ControlLoop xoá yêu cầu hiện hành như với mọi outcome.
|
|
if (state_ != NavigationState::kIdle)
|
|
{
|
|
out.report_outcome = true;
|
|
out.outcome = NavigationOutcome::kCancelled;
|
|
}
|
|
|
|
state_before_pause_ = NavigationState::kIdle; // Không còn gì để quay về; dọn cho refreshFeedback.
|
|
enter(NavigationState::kEmergency, in.now, "emergency stop", out);
|
|
}
|
|
|
|
} // namespace move_base2
|