A failed primary global planner on a docking, go_straight or rotate request no longer swaps to backup_global_planner. It goes straight to the planning_failed recovery route and aborts. Only the position profile may use the backup planner. Update STATE_MACHINE.md and add test NonPositionPlannerFailureSkipsBackup.
1636 lines
71 KiB
C++
1636 lines
71 KiB
C++
/*********************************************************************
|
|
*
|
|
* Software License Agreement (BSD License)
|
|
*
|
|
* move_base2 — cài đặt control loop.
|
|
*
|
|
* Author: DuongTD
|
|
*********************************************************************/
|
|
#include <move_base2/control_loop.h>
|
|
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
#include <cstdio>
|
|
#include <limits>
|
|
#include <cstring>
|
|
#include <sstream>
|
|
|
|
#include <robot/console.h>
|
|
|
|
namespace move_base2
|
|
{
|
|
namespace
|
|
{
|
|
|
|
/// [-] Sai lệch chuẩn quaternion còn chấp nhận được trước khi coi goal là hỏng.
|
|
constexpr double kQuaternionNormTolerance = 1e-2;
|
|
|
|
/// @brief Yaw [rad] của một pose. Robot chạy trên mặt phẳng nên chỉ z-w của quaternion có nghĩa.
|
|
double yawOf(const robot_geometry_msgs::PoseStamped& pose)
|
|
{
|
|
const auto& q = pose.pose.orientation;
|
|
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
|
|
}
|
|
|
|
/// [s] Giãn cách log cho guard "không đi mù". Tình trạng này kéo dài hàng giây, và đây là vòng lặp
|
|
/// điều khiển — log mỗi cycle sẽ nhấn chìm mọi dòng khác.
|
|
constexpr double kStaleCostmapLogThrottle = 5.0;
|
|
|
|
/// [s] Log debug tạm phục vụ test đường recovery/controller. Ngắn hơn throttle runtime mặc định để
|
|
/// không bị mất dấu trong các fail diễn ra trong vài trăm ms sau detour.
|
|
constexpr double kDebugControlLogThrottle = 0.2;
|
|
|
|
const char* toString(PlannerFeedback feedback)
|
|
{
|
|
switch (feedback)
|
|
{
|
|
case PlannerFeedback::kIdle:
|
|
return "idle";
|
|
case PlannerFeedback::kBusy:
|
|
return "busy";
|
|
case PlannerFeedback::kPlanReady:
|
|
return "plan_ready";
|
|
case PlannerFeedback::kFailed:
|
|
return "failed";
|
|
}
|
|
return "unknown";
|
|
}
|
|
|
|
const char* toString(ControllerFeedback feedback)
|
|
{
|
|
switch (feedback)
|
|
{
|
|
case ControllerFeedback::kIdle:
|
|
return "idle";
|
|
case ControllerFeedback::kCommandValid:
|
|
return "command_valid";
|
|
case ControllerFeedback::kNoValidCommand:
|
|
return "no_valid_command";
|
|
case ControllerFeedback::kGoalReached:
|
|
return "goal_reached";
|
|
}
|
|
return "unknown";
|
|
}
|
|
|
|
const char* toString(RecoveryFeedback feedback)
|
|
{
|
|
switch (feedback)
|
|
{
|
|
case RecoveryFeedback::kIdle:
|
|
return "idle";
|
|
case RecoveryFeedback::kRunning:
|
|
return "running";
|
|
case RecoveryFeedback::kSucceeded:
|
|
return "succeeded";
|
|
case RecoveryFeedback::kFailed:
|
|
return "failed";
|
|
}
|
|
return "unknown";
|
|
}
|
|
|
|
} // namespace
|
|
|
|
// ================================================================================================
|
|
// ControlLoopConfig
|
|
// ================================================================================================
|
|
|
|
bool ControlLoopConfig::validate(std::string& error) const
|
|
{
|
|
if (!state_machine.validate(error))
|
|
{
|
|
return false;
|
|
}
|
|
if (!velocity.validate(error))
|
|
{
|
|
return false;
|
|
}
|
|
if (!(nominal_control_period > 0.0))
|
|
{
|
|
error = "nominal_control_period must be > 0 [s]";
|
|
return false;
|
|
}
|
|
if (!std::isfinite(planner_frequency) || planner_frequency < 0.0)
|
|
{
|
|
error = "planner_frequency must be >= 0 [Hz] (0 = no background replanning)";
|
|
return false;
|
|
}
|
|
if (position.local_planner_name.empty())
|
|
{
|
|
error = "profile 'position' must have local_planner_name";
|
|
return false;
|
|
}
|
|
for (const auto& entry : docking_marker_profiles)
|
|
{
|
|
if (entry.first.empty() || entry.second.global_planner_name.empty() ||
|
|
entry.second.local_planner_name.empty())
|
|
{
|
|
error = "every docking marker profile must have a name, global_planner, and local_planner";
|
|
return false;
|
|
}
|
|
}
|
|
if (robot_base_frame.empty())
|
|
{
|
|
// Frame rỗng đi thẳng vào header của lệnh vận tốc gửi host. Chặn ở đây thay vì để host nhận một
|
|
// lệnh không biết thuộc hệ toạ độ nào.
|
|
error = "robot_base_frame must not be empty";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::string ControlLoopConfig::describe() const
|
|
{
|
|
std::ostringstream out;
|
|
out << state_machine.describe();
|
|
out << velocity.describe();
|
|
out << "ControlLoop:\n";
|
|
out << " nominal_control_period: " << nominal_control_period << " s\n";
|
|
out << " planner_frequency : " << planner_frequency << " Hz"
|
|
<< (planner_frequency > 0.0 ? "" : " (no background replanning)") << '\n';
|
|
out << " robot_base_frame : " << robot_base_frame << '\n';
|
|
out << " profile position : " << position.global_planner_name << " / "
|
|
<< position.local_planner_name << '\n';
|
|
out << " profile docking : " << docking.global_planner_name << " / "
|
|
<< docking.local_planner_name << '\n';
|
|
out << " profile go_straight: " << go_straight.global_planner_name << " / "
|
|
<< go_straight.local_planner_name << '\n';
|
|
out << " profile rotate : " << rotate.global_planner_name << " / "
|
|
<< rotate.local_planner_name << '\n';
|
|
return out.str();
|
|
}
|
|
|
|
bool EnvSamplingConfig::monitors(MotionProfile profile) const
|
|
{
|
|
return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
|
|
}
|
|
|
|
bool EnvSamplingConfig::validate(std::string& error) const
|
|
{
|
|
if (!std::isfinite(check_period) || check_period <= 0.0)
|
|
{
|
|
error = "env_monitor/check_period must be > 0 [s]";
|
|
return false;
|
|
}
|
|
if (lethal_threshold < 1 || lethal_threshold > 254)
|
|
{
|
|
error = "env_monitor/body/lethal_threshold must be in [1, 254]";
|
|
return false;
|
|
}
|
|
const bool any_body = body_front > 0.0 || body_rear > 0.0 || body_side > 0.0;
|
|
const bool all_body = body_front > 0.0 && body_rear > 0.0 && body_side > 0.0;
|
|
if (any_body && !all_body)
|
|
{
|
|
error = "env_monitor/body: front_offset, rear_offset and side_offset must all be > 0 [m] when any "
|
|
"is set (all 0 = use the costmap footprint)";
|
|
return false;
|
|
}
|
|
if (!std::isfinite(padding) || padding < 0.0 || !std::isfinite(horizon) || horizon <= 0.0 ||
|
|
!std::isfinite(corridor_margin) || corridor_margin < 0.0 || !std::isfinite(corridor_cap) ||
|
|
corridor_cap <= 0.0 || !std::isfinite(target_backoff) || target_backoff < 0.0 ||
|
|
!std::isfinite(track_back) || track_back < 0.0 || !std::isfinite(track_ahead) || track_ahead <= 0.0 ||
|
|
!std::isfinite(exit_ahead) || exit_ahead < 0.0 || !std::isfinite(target_snap) || target_snap < 0.0 ||
|
|
!std::isfinite(robot_snap) || robot_snap < 0.0)
|
|
{
|
|
error = "env_monitor: padding/corridor_margin/target_backoff/robot_snap/track_back/exit_ahead/target_snap >= 0, "
|
|
"horizon/corridor_cap/track_ahead > 0 [m]";
|
|
return false;
|
|
}
|
|
if (use_local_plan != "auto" && use_local_plan != "true" && use_local_plan != "false")
|
|
{
|
|
error = "env_monitor/contact/use_local_plan must be auto | true | false";
|
|
return false;
|
|
}
|
|
if (!std::isfinite(local_plan_start_tol) || local_plan_start_tol <= 0.0 ||
|
|
!std::isfinite(contact_lookahead) || contact_lookahead <= 0.0)
|
|
{
|
|
error = "env_monitor/contact: local_plan_start_tol and lookahead must be > 0 [m]";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// ================================================================================================
|
|
// ControlLoop
|
|
// ================================================================================================
|
|
|
|
bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDeps& deps,
|
|
std::string& error)
|
|
{
|
|
initialized_ = false;
|
|
|
|
if (deps.clock == nullptr || deps.pose == nullptr || deps.planner == nullptr ||
|
|
deps.controller == nullptr || deps.recovery == nullptr)
|
|
{
|
|
error = "missing a required port (clock/pose/planner/controller/recovery)";
|
|
return false;
|
|
}
|
|
if (!config.validate(error))
|
|
{
|
|
return false;
|
|
}
|
|
if (!state_machine_.configure(config.state_machine, error))
|
|
{
|
|
return false;
|
|
}
|
|
if (!arbiter_.configure(config.velocity, error))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
config_ = config;
|
|
deps_ = deps;
|
|
|
|
|
|
// EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 (PathMonitor cũ đã
|
|
// xoá). Không có cổng thì tắt, nhưng phải kêu nếu config bảo bật.
|
|
env_logger_.reset();
|
|
if (config_.env_monitor.enabled)
|
|
{
|
|
if (deps_.environment == nullptr)
|
|
{
|
|
robot::log_error("[move_base2] env_monitor is enabled but no EnvironmentPort is wired — EnvMonitor "
|
|
"stays OFF.\n");
|
|
}
|
|
else
|
|
{
|
|
if (!config_.env_sampling.validate(error) || !env_monitor_.configure(config_.env_monitor, error))
|
|
{
|
|
return false;
|
|
}
|
|
robot::log_info("[move_base2] %s\n sampling : check=%.2f s lethal>=%d padding=%.2f m horizon=%.1f m "
|
|
"corridor_margin=%.2f m use_local_plan=%s lookahead=%.1f m body=%s\n",
|
|
config_.env_monitor.describe().c_str(), config_.env_sampling.check_period,
|
|
config_.env_sampling.lethal_threshold, config_.env_sampling.padding,
|
|
config_.env_sampling.horizon, config_.env_sampling.corridor_margin,
|
|
config_.env_sampling.use_local_plan.c_str(), config_.env_sampling.contact_lookahead,
|
|
config_.env_sampling.body_front > 0.0 ? "config" : "costmap footprint");
|
|
const bool shadow = config_.env_monitor.stall.action != "recover" &&
|
|
config_.env_monitor.unreachable.action != "recover" &&
|
|
config_.env_monitor.contact.action != "recover" &&
|
|
!config_.env_monitor.contact.apply_command;
|
|
robot::log_info("[move_base2] EnvMonitor mode: %s\n",
|
|
shadow ? "SHADOW (log only; no flags, no braking, no speed cap)"
|
|
: "ACTIVE on at least one verdict or on the command");
|
|
if (config_.env_logger.enabled)
|
|
{
|
|
env_logger_ = std::make_unique<EnvLogger>();
|
|
if (!env_logger_->open(config_.env_logger, error))
|
|
{
|
|
robot::log_error("[move_base2] %s — EnvMonitor runs without the JSONL logger.\n", error.c_str());
|
|
env_logger_.reset();
|
|
error.clear();
|
|
}
|
|
else
|
|
{
|
|
robot::log_info("[move_base2] EnvMonitor logger writing to %s\n", env_logger_->path().c_str());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
initialized_ = true;
|
|
reset();
|
|
return true;
|
|
}
|
|
|
|
void ControlLoop::reset()
|
|
{
|
|
state_machine_.reset();
|
|
arbiter_.reset();
|
|
|
|
has_pending_request_ = false;
|
|
has_active_request_ = false;
|
|
pause_requested_ = false;
|
|
resume_requested_ = false;
|
|
cancel_requested_ = false;
|
|
emergency_ = false;
|
|
|
|
planner_feedback_ = PlannerFeedback::kIdle;
|
|
controller_feedback_ = ControllerFeedback::kIdle;
|
|
recovery_feedback_ = RecoveryFeedback::kIdle;
|
|
action_feedback_ = ActionFeedback::kIdle;
|
|
action_message_.clear();
|
|
|
|
latest_plan_.clear();
|
|
planner_running_ = false;
|
|
backup_global_planner_active_ = false;
|
|
|
|
// Nhãn mới + huỷ: lượt đang bay thuộc về vòng đời trước, kết quả của nó không được nhận nhầm.
|
|
++plan_tag_;
|
|
if (deps_.planner != nullptr)
|
|
{
|
|
deps_.planner->cancelPlan();
|
|
}
|
|
|
|
has_last_cycle_time_ = false;
|
|
has_oscillation_origin_ = false;
|
|
last_plan_started_ = robot::Time();
|
|
has_last_plan_applied_ = false;
|
|
|
|
env_monitor_.reset();
|
|
env_verdict_ = EnvVerdict();
|
|
env_geometry_ = EnvGeometry();
|
|
has_last_env_heavy_ = false;
|
|
has_last_env_debug_ = false;
|
|
env_brake_ = false;
|
|
env_used_local_plan_ = false;
|
|
|
|
has_outcome_ = false;
|
|
outcome_report_count_ = 0;
|
|
last_reason_ = "";
|
|
}
|
|
|
|
const ProfileBinding* ControlLoop::bindingFor(MotionProfile profile, const std::string& marker) const
|
|
{
|
|
switch (profile)
|
|
{
|
|
case MotionProfile::kPosition:
|
|
return &config_.position;
|
|
case MotionProfile::kDocking:
|
|
{
|
|
const auto it = config_.docking_marker_profiles.find(marker);
|
|
if (!marker.empty() && it != config_.docking_marker_profiles.end())
|
|
{
|
|
return &it->second;
|
|
}
|
|
return &config_.docking;
|
|
}
|
|
case MotionProfile::kGoStraight:
|
|
return &config_.go_straight;
|
|
case MotionProfile::kRotate:
|
|
return &config_.rotate;
|
|
}
|
|
return nullptr;
|
|
}
|
|
|
|
bool ControlLoop::isQuaternionValid(const robot_geometry_msgs::PoseStamped& pose)
|
|
{
|
|
const auto& q = pose.pose.orientation;
|
|
if (!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w))
|
|
{
|
|
return false;
|
|
}
|
|
const double norm_sq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
|
|
return std::abs(std::sqrt(norm_sq) - 1.0) <= kQuaternionNormTolerance;
|
|
}
|
|
|
|
bool ControlLoop::resolveDeferredGoal(NavigationRequest& request, std::string& reason) const
|
|
{
|
|
const bool has_frame = !request.goal_frame.empty();
|
|
const bool has_distance = std::isfinite(request.relative_distance);
|
|
// Góc quay ĐI KÈM được với hai nguồn đích kia, không loại trừ: chặng quay tại chỗ là
|
|
// relative_distance = 0 cộng một góc khác 0.
|
|
const bool has_yaw = std::isfinite(request.relative_yaw);
|
|
|
|
if (!has_frame && !has_distance && !has_yaw)
|
|
{
|
|
return true; // Goal tuyệt đối, không có gì phải quy.
|
|
}
|
|
|
|
if (has_frame && has_distance)
|
|
{
|
|
// Hai nguồn đích cùng lúc thì không có thứ tự nào là hiển nhiên đúng. Từ chối thay vì chọn bừa.
|
|
reason = "request sets both goal_frame and relative_distance";
|
|
return false;
|
|
}
|
|
|
|
if (deps_.pose == nullptr)
|
|
{
|
|
reason = "deferred goal needs a pose port";
|
|
return false;
|
|
}
|
|
|
|
// Pose hiện tại: cần cho quãng tương đối, và cần cho góc tương đối kể cả khi vị trí đích tới từ
|
|
// một TF frame — góc luôn tính so với hướng robot đang quay về LÚC chặng được nhận.
|
|
robot_geometry_msgs::PoseStamped robot_pose;
|
|
const bool needs_robot_pose = has_distance || has_yaw;
|
|
if (needs_robot_pose && !deps_.pose->getRobotPose(robot_pose))
|
|
{
|
|
// Mất định vị thì không quy được quãng đường tương đối. Đoán ở đây là robot đi mù một đoạn.
|
|
reason = "a relative goal needs the robot pose, which is not available";
|
|
return false;
|
|
}
|
|
|
|
const double robot_yaw = needs_robot_pose ? yawOf(robot_pose) : 0.0;
|
|
|
|
if (has_frame)
|
|
{
|
|
if (!deps_.pose->lookupPose(request.goal_frame, request.goal))
|
|
{
|
|
reason = "cannot resolve goal_frame '" + request.goal_frame + "'";
|
|
return false;
|
|
}
|
|
}
|
|
else if (has_distance)
|
|
{
|
|
request.goal = robot_pose;
|
|
request.goal.pose.position.x += request.relative_distance * std::cos(robot_yaw);
|
|
request.goal.pose.position.y += request.relative_distance * std::sin(robot_yaw);
|
|
}
|
|
else
|
|
{
|
|
// Chỉ có góc: đích là chính chỗ robot đang đứng, chỉ khác hướng.
|
|
request.goal = robot_pose;
|
|
}
|
|
|
|
if (has_yaw)
|
|
{
|
|
// Hướng đích = hướng HIỆN TẠI cộng góc yêu cầu. Ghi đè orientation của goal chứ không cộng dồn
|
|
// vào orientation vừa lấy ở trên: với has_frame, orientation của frame đích là hướng của trạm
|
|
// chứ không phải hướng robot, và chặng quay nói về robot.
|
|
//
|
|
// Không normalize góc tổng: mission layer đã chặn ở [-pi, pi], và quaternion tự bọc.
|
|
const double goal_yaw = robot_yaw + request.relative_yaw;
|
|
const double half = 0.5 * goal_yaw;
|
|
request.goal.pose.orientation.x = 0.0;
|
|
request.goal.pose.orientation.y = 0.0;
|
|
request.goal.pose.orientation.z = std::sin(half);
|
|
request.goal.pose.orientation.w = std::cos(half);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool ControlLoop::submit(const NavigationRequest& incoming, std::string& reason)
|
|
{
|
|
// Bản sao: quy đổi goal đến muộn ghi vào chính request, mà bên gọi truyền const ref.
|
|
NavigationRequest request = incoming;
|
|
|
|
if (!initialized_)
|
|
{
|
|
reason = "runtime not initialized";
|
|
return false;
|
|
}
|
|
|
|
// Hàng rào thứ hai (hàng rào một ở NavigationServer, trước cả mission layer): đang giữ dừng khẩn
|
|
// thì không có goal nào được xếp chờ — xếp chờ là sau khi gỡ chốt robot tự chạy mà không ai gửi.
|
|
if (emergency_)
|
|
{
|
|
reason = "emergency stop latched";
|
|
return false;
|
|
}
|
|
|
|
// D8: yêu cầu mang action cần có ActionPort; từ chối tại cửa thay vì kẹt sau khi tới goal.
|
|
if (!request.actions.empty() && deps_.action == nullptr)
|
|
{
|
|
reason = "request carries actions but the runtime has no action port";
|
|
return false;
|
|
}
|
|
|
|
if (!request.has_goal)
|
|
{
|
|
// D8: yêu cầu chỉ-có-action — không có goal để validate, không có planner để swap.
|
|
if (request.actions.empty())
|
|
{
|
|
reason = "request has neither goal nor action";
|
|
return false;
|
|
}
|
|
pending_request_ = request;
|
|
has_pending_request_ = true;
|
|
backup_global_planner_active_ = false;
|
|
cancel_requested_ = false;
|
|
return true;
|
|
}
|
|
|
|
// Đích đến muộn: quy về pose tuyệt đối NGAY TẠI ĐÂY, trước mọi phép kiểm bên dưới. Đây là nơi duy
|
|
// nhất vừa biết chặng vừa được kích hoạt, vừa có cổng pose — mission layer sinh chặng lúc robot
|
|
// còn chưa tới nơi nên không thể quy sớm hơn.
|
|
if (!resolveDeferredGoal(request, reason))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (!std::isfinite(request.goal.pose.position.x) || !std::isfinite(request.goal.pose.position.y))
|
|
{
|
|
reason = "goal has non-finite coordinates";
|
|
return false;
|
|
}
|
|
if (!isQuaternionValid(request.goal))
|
|
{
|
|
reason = "goal has an invalid quaternion";
|
|
return false;
|
|
}
|
|
|
|
const ProfileBinding* binding = bindingFor(request.profile, request.marker);
|
|
if (binding == nullptr || binding->local_planner_name.empty())
|
|
{
|
|
reason = std::string("no planner configured for profile '") + toString(request.profile) + "'";
|
|
return false;
|
|
}
|
|
|
|
// Marker là TUỲ CHỌN (2026-09-06): docking hiện chạy bằng goal_frame đã quy về pose tuyệt đối và
|
|
// local planner không đọc `maker_name`, nên request không có marker vẫn hợp lệ. Khi caller CÓ gửi
|
|
// marker thì nó vẫn phải được chọn TRƯỚC khi swap sang docking planner — planner đọc tên marker
|
|
// trong initialize() (một lần), thứ tự ngược lại là dock vào marker của chặng trước.
|
|
if (request.profile == MotionProfile::kDocking)
|
|
{
|
|
if (!request.marker.empty() && !deps_.controller->setDockingMarker(request.marker))
|
|
{
|
|
reason = "marker '" + request.marker + "' is invalid (not listed in maker_sources?)";
|
|
return false;
|
|
}
|
|
|
|
// Global planner nhận marker qua param tree, không qua chữ ký hàm: chép
|
|
// `docking_marker_profiles/<marker>/footprint` sang namespace của planner TRƯỚC khi swap, vì
|
|
// swap là chỗ instance được dựng và đọc param. Đảo thứ tự = dock bằng hình học của chặng trước.
|
|
if (!request.marker.empty() &&
|
|
!deps_.planner->bindDockingMarker(request.marker, binding->global_planner_name))
|
|
{
|
|
reason = "marker '" + request.marker + "' has a malformed docking_marker_profiles entry";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Đổi planner NGAY tại cửa vào, trước khi nhận yêu cầu: nếu không nạp được thì từ chối luôn, chứ
|
|
// không để state machine bắt đầu một chặng rồi mới phát hiện không có planner nào chạy được.
|
|
if (!binding->global_planner_name.empty() &&
|
|
!deps_.planner->swapPlanner(binding->global_planner_name))
|
|
{
|
|
reason = "could not load global planner '" + binding->global_planner_name + "'";
|
|
return false;
|
|
}
|
|
if (!deps_.controller->swapPlanner(binding->local_planner_name))
|
|
{
|
|
reason = "could not load local planner '" + binding->local_planner_name + "'";
|
|
return false;
|
|
}
|
|
|
|
robot::log_info("[move_base2] Mission %llu: profile=%s, marker='%s', global='%s', local='%s'.\n",
|
|
static_cast<unsigned long long>(request.mission_sequence_id),
|
|
toString(request.profile), request.marker.empty() ? "<default>" : request.marker.c_str(),
|
|
binding->global_planner_name.c_str(),
|
|
binding->local_planner_name.c_str());
|
|
|
|
pending_request_ = request;
|
|
has_pending_request_ = true;
|
|
backup_global_planner_active_ = false;
|
|
|
|
// Yêu cầu mới thay thế yêu cầu đang chờ, không xếp hàng: xếp hàng là việc của mission layer.
|
|
cancel_requested_ = false;
|
|
return true;
|
|
}
|
|
|
|
void ControlLoop::requestPause()
|
|
{
|
|
pause_requested_ = true;
|
|
resume_requested_ = false;
|
|
}
|
|
|
|
void ControlLoop::requestResume()
|
|
{
|
|
resume_requested_ = true;
|
|
pause_requested_ = false;
|
|
}
|
|
|
|
void ControlLoop::requestCancel()
|
|
{
|
|
cancel_requested_ = true;
|
|
}
|
|
|
|
void ControlLoop::requestEmergency()
|
|
{
|
|
if (!emergency_)
|
|
{
|
|
// Sườn lên: LỖI mức vận hành, không gắn [debug], không có khoá tắt — dòng này là bằng chứng
|
|
// duy nhất trong log rằng robot dừng vì lệnh khẩn chứ không phải vì hỏng.
|
|
robot::log_warning("[move_base2] EMERGENCY STOP latched (mission %llu%s): command zero, planner/"
|
|
"recovery/action cancelled, mission queue wiped. Goals are rejected until "
|
|
"clearEmergency().\n",
|
|
static_cast<unsigned long long>(has_active_request_ ? active_request_.mission_sequence_id : 0),
|
|
has_pending_request_ ? ", pending request dropped" : "");
|
|
}
|
|
emergency_ = true;
|
|
has_pending_request_ = false;
|
|
}
|
|
|
|
void ControlLoop::requestClearEmergency()
|
|
{
|
|
if (emergency_)
|
|
{
|
|
robot::log_info("[move_base2] emergency cleared: back to IDLE, waiting for a new goal.\n");
|
|
}
|
|
emergency_ = false;
|
|
}
|
|
|
|
void ControlLoop::collectPlannerResult()
|
|
{
|
|
PlanResult result;
|
|
if (!deps_.planner->pollPlan(result))
|
|
{
|
|
// Chưa có kết quả. Chỉ báo "đang lập" khi thật sự có lượt đang chạy VÀ chưa có phản hồi nào
|
|
// khác — `apply_plan` ở cycle trước có thể đã đặt kFailed khi controller từ chối plan, và đó
|
|
// là tin quan trọng hơn.
|
|
if (planner_running_ && planner_feedback_ == PlannerFeedback::kIdle)
|
|
{
|
|
planner_feedback_ = PlannerFeedback::kBusy;
|
|
}
|
|
return;
|
|
}
|
|
|
|
planner_running_ = false;
|
|
|
|
if (result.tag != plan_tag_)
|
|
{
|
|
// Kết quả của một yêu cầu đã bị thay hoặc huỷ. Vứt lặng lẽ: bám theo nó nghĩa là robot đi tới
|
|
// goal không còn ai yêu cầu. Không phải lỗi, nên cũng không đặt kFailed.
|
|
return;
|
|
}
|
|
|
|
// Contract của PlannerPort là "succeeded nghĩa là plan không rỗng". Vẫn kiểm lại ở đây vì plan
|
|
// rỗng lọt xuống sẽ thành front()/back() trên vector rỗng ở tầng dưới.
|
|
if (!result.succeeded || result.plan.empty())
|
|
{
|
|
// Replan NỀN hỏng (đang kControlling): bỏ qua, plan cũ vẫn hiệu lực và robot đang bám nó bình
|
|
// thường. Không kích backup planner ở đây — một lượt replan nền hụt (robot đi qua vùng hẹp,
|
|
// costmap tạm bít) mà đổi hẳn sang SBPL là mất quỹ đạo NURBS của order cho phần còn lại của
|
|
// chặng. Backup chỉ dành cho lúc THẬT SỰ cần plan mà không có (kPlanning).
|
|
if (state_machine_.state() == NavigationState::kControlling)
|
|
{
|
|
robot::log_warning_throttle(5.0, "[move_base2] background replan failed; keeping the "
|
|
"current plan.\n");
|
|
planner_feedback_ = PlannerFeedback::kFailed;
|
|
return;
|
|
}
|
|
|
|
// Fallback thuộc policy của control loop, không phải recovery: planner chính đã kết thúc nên
|
|
// worker rảnh để nạp/chạy SBPL ngay cycle này. Chỉ thử một lần cho cả request; backup fail thì
|
|
// giữ kFailed để state machine đi đúng đường recovery hiện có.
|
|
//
|
|
// Backup CHỈ dành cho profile position: goal trần không có edge làm CustomPlanner fail, và SBPL
|
|
// là đường lùi hợp lệ cho một chặng đi tới pose. Docking/go_straight/rotate thì SBPL không giữ
|
|
// được hình học của chặng — đo 26/10 trên robot KIT: DockPlanner fail vì robot đứng quá gần
|
|
// dock, SBPL dựng đường thẳng tới pose tiếp xúc, robot bám đường đó vào dock không qua cusp và
|
|
// đoạn lùi thẳng. Ba profile đó fail thì đi thẳng route planning_failed như khi không có backup.
|
|
if (!backup_global_planner_active_ && !config_.backup_global_planner_name.empty())
|
|
{
|
|
const std::string failed_planner = deps_.planner->activePlanner();
|
|
if (active_request_.profile != MotionProfile::kPosition)
|
|
{
|
|
// Không gắn [debug], không tắt được: đây là bằng chứng duy nhất trong log rằng lỗi planner
|
|
// của chặng này cố ý không được cứu bằng backup.
|
|
robot::log_warning("[move_base2] global planner '%s' failed for mission %llu (profile %s); "
|
|
"backup '%s' is reserved for profile position; starting recovery.\n",
|
|
failed_planner.c_str(),
|
|
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
|
toString(active_request_.profile),
|
|
config_.backup_global_planner_name.c_str());
|
|
}
|
|
else if (deps_.planner->swapPlanner(config_.backup_global_planner_name))
|
|
{
|
|
backup_global_planner_active_ = true;
|
|
planner_feedback_ = PlannerFeedback::kIdle;
|
|
robot::log_warning("[move_base2] global planner '%s' failed for mission %llu; switching "
|
|
"once to backup '%s'.\n",
|
|
failed_planner.c_str(),
|
|
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
|
config_.backup_global_planner_name.c_str());
|
|
return;
|
|
}
|
|
else
|
|
{
|
|
// Không có backup chạy được thì failure gốc vẫn phải đi recovery, không được để robot chờ.
|
|
robot::log_error("[move_base2] global planner '%s' failed and backup '%s' could not be "
|
|
"loaded; starting recovery.\n",
|
|
failed_planner.c_str(), config_.backup_global_planner_name.c_str());
|
|
}
|
|
}
|
|
planner_feedback_ = PlannerFeedback::kFailed;
|
|
return;
|
|
}
|
|
|
|
|
|
latest_plan_.swap(result.plan);
|
|
// Tuyến THAM CHIẾU của chặng = plan do PLANNER sinh, không phải plan đã bị recovery thay
|
|
// (contract 2026-08-05e). Detour nối lại vào nó nên robot tự quay về tuyến order thay vì trôi
|
|
// dần theo từng đường vòng, và `max_deviation` đo đúng hành lang mà fleet đã duyệt.
|
|
order_plan_ = latest_plan_;
|
|
planner_feedback_ = PlannerFeedback::kPlanReady;
|
|
}
|
|
|
|
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)
|
|
{
|
|
env_brake_ = false;
|
|
if (!config_.env_monitor.enabled || deps_.environment == nullptr || !env_monitor_.configured())
|
|
{
|
|
return;
|
|
}
|
|
if (!has_active_request_)
|
|
{
|
|
// Không có chặng: mọi ngân sách/mốc thuộc chặng cũ. Verdict rỗng.
|
|
env_monitor_.reset();
|
|
env_verdict_ = EnvVerdict();
|
|
env_geometry_ = EnvGeometry();
|
|
has_last_env_heavy_ = false;
|
|
env_plan_index_valid_ = false;
|
|
return;
|
|
}
|
|
|
|
const EnvSamplingConfig& sampling = config_.env_sampling;
|
|
const bool monitorable = state_machine_.state() == NavigationState::kControlling && pose_available &&
|
|
!latest_plan_.empty() && sampling.monitors(active_request_.profile);
|
|
|
|
EnvSample s;
|
|
s.now = now;
|
|
s.dt = dt;
|
|
s.costmap_current = !costmap_stale;
|
|
s.has_plan = monitorable;
|
|
s.robot_x = robot_pose.pose.position.x;
|
|
s.robot_y = robot_pose.pose.position.y;
|
|
const robot_geometry_msgs::Twist& last_cmd = arbiter_.lastCommand();
|
|
s.v_cmd = last_cmd.linear.x;
|
|
s.w_cmd = last_cmd.angular.z;
|
|
robot_geometry_msgs::Twist measured;
|
|
if (deps_.controller->measuredVelocity(measured))
|
|
{
|
|
s.v_meas = measured.linear.x;
|
|
}
|
|
s.controller_valid = controller_feedback_ != ControllerFeedback::kNoValidCommand;
|
|
s.v_controller = env_controller_v_;
|
|
if (!latest_plan_.empty() && pose_available)
|
|
{
|
|
s.d_goal = std::hypot(latest_plan_.back().pose.position.x - robot_pose.pose.position.x,
|
|
latest_plan_.back().pose.position.y - robot_pose.pose.position.y);
|
|
}
|
|
|
|
if (monitorable)
|
|
{
|
|
double front = sampling.body_front;
|
|
double rear = sampling.body_rear;
|
|
double side = sampling.body_side;
|
|
bool have_body = front > 0.0 && rear > 0.0 && side > 0.0;
|
|
if (!have_body)
|
|
{
|
|
have_body = deps_.environment->robotBodyExtents(front, rear, side);
|
|
if (!have_body)
|
|
{
|
|
robot::log_error_throttle(5.0, "[move_base2] EnvMonitor: no body geometry (costmap footprint "
|
|
"unavailable, body/*_offset not set) — geometry not sampled.\n");
|
|
}
|
|
}
|
|
|
|
if (have_body)
|
|
{
|
|
const bool heavy_due =
|
|
!has_last_env_heavy_ || (now - last_env_heavy_).toSec() >= sampling.check_period;
|
|
if (heavy_due)
|
|
{
|
|
// Bám index đơn điệu: detour uốn quanh trụ có đoạn sau đi sát robot, nearest toàn plan nhảy sang đó
|
|
// và điểm thoát T đổi (cost_to_go +8 m / 1 s, run 5/9 22:35). Plan mới thì tìm lại toàn plan một lần.
|
|
if (!env_plan_index_valid_ || env_plan_index_ + 1 >= latest_plan_.size())
|
|
{
|
|
env_plan_index_ = nearestIndex(latest_plan_, robot_pose);
|
|
env_plan_index_valid_ = true;
|
|
}
|
|
else
|
|
{
|
|
env_plan_index_ = trackedNearestIndex(latest_plan_, robot_pose, env_plan_index_, sampling.track_back,
|
|
sampling.track_ahead);
|
|
}
|
|
EnvGeometryRequest req;
|
|
req.plan = &latest_plan_;
|
|
req.from_index = env_plan_index_;
|
|
req.robot_pose = robot_pose;
|
|
req.sampling = &sampling;
|
|
req.front = front;
|
|
req.rear = rear;
|
|
req.side = side;
|
|
EnvGeometry geometry;
|
|
if (deps_.environment->sampleGeometry(req, geometry))
|
|
{
|
|
env_geometry_ = geometry;
|
|
s.geometry_valid = true;
|
|
s.cost_conclusive = geometry.cost.conclusive;
|
|
s.reachable = geometry.cost.reachable;
|
|
s.cost_to_go = geometry.cost.cost_to_go;
|
|
s.edt_body_min = geometry.edt_body_min;
|
|
}
|
|
last_env_heavy_ = now;
|
|
has_last_env_heavy_ = true;
|
|
}
|
|
|
|
if (config_.env_monitor.contact.enabled)
|
|
{
|
|
EnvTrajectoryRequest treq;
|
|
treq.robot_pose = robot_pose;
|
|
treq.v = s.v_cmd;
|
|
treq.omega = s.w_cmd;
|
|
treq.sampling = &sampling;
|
|
treq.front = front;
|
|
treq.rear = rear;
|
|
treq.side = side;
|
|
if (sampling.use_local_plan != "false")
|
|
{
|
|
deps_.controller->getLocalPlan(env_local_plan_);
|
|
treq.local_plan = &env_local_plan_;
|
|
}
|
|
SweepResult sweep;
|
|
bool used_local = false;
|
|
if (deps_.environment->sweepTrajectory(treq, sweep, used_local) && sweep.conclusive)
|
|
{
|
|
s.contact_conclusive = true;
|
|
s.traj_contact_dist = sweep.blocked ? sweep.distance : std::numeric_limits<double>::infinity();
|
|
env_used_local_plan_ = used_local;
|
|
env_contact_dist_ = s.traj_contact_dist;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
env_verdict_ = env_monitor_.update(s);
|
|
env_brake_ = env_verdict_.brake && config_.env_monitor.contact.apply_command;
|
|
if (env_verdict_.cost_jump && config_.debug_env)
|
|
{
|
|
robot::log_info_throttle(1.0, "[move_base2][debug] EnvMonitor: cost_to_go jumped to %.2f m in one tick — free mask "
|
|
"changed connectivity, stall window restarted.\n",
|
|
s.cost_to_go);
|
|
}
|
|
|
|
// Sườn sự kiện: một dòng, không throttle, không khoá — đây là chẩn đoán "robot kẹt/sắp chạm".
|
|
if (env_verdict_.event[0] != '\0')
|
|
{
|
|
robot::log_warning("[move_base2] EnvMonitor: %s (eff_geo=%.2f cmd=%.2f m, cost_to_go=%.2f m, "
|
|
"edt_body=%.2f m, contact=%.2f m, budget_left=%.2f m, mission %llu%s).\n",
|
|
env_verdict_.event, env_verdict_.eff_geo, env_verdict_.cmd_window,
|
|
env_geometry_.valid ? env_geometry_.cost.cost_to_go : -1.0, s.edt_body_min,
|
|
s.traj_contact_dist, env_verdict_.replan_budget_left,
|
|
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
|
(env_verdict_.no_progress || env_verdict_.path_blocked || env_verdict_.collision)
|
|
? "; FLAG RAISED"
|
|
: "; shadow");
|
|
}
|
|
// Tóm tắt feature 1 Hz — nhóm debug/env, tắt được.
|
|
if (config_.debug_env && monitorable && s.geometry_valid &&
|
|
(!has_last_env_debug_ || (now - last_env_debug_).toSec() >= 1.0))
|
|
{
|
|
last_env_debug_ = now;
|
|
has_last_env_debug_ = true;
|
|
robot::log_info("[move_base2][debug] EnvMonitor: cost_to_go=%.2f (geo %.2f + arc %.2f, %s%s) eff=%.2f "
|
|
"cmd=%.2f m edt_body=%.2f m clear_ahead=%.2f m corridor=%.2f m contact=%.2f m (%s) "
|
|
"v_cap=%.2f stall=%d%s unreach=%d%s brake=%d standdown=%d budget_left=%.1f m disp=%.2f m%s\n",
|
|
env_geometry_.cost.cost_to_go, env_geometry_.cost.geo_to_exit, env_geometry_.cost.arc_rest,
|
|
env_geometry_.cost.reachable ? "reachable" : "UNREACHABLE",
|
|
env_geometry_.cost.robot_in_ring ? ", in ring" : "", env_verdict_.eff_geo,
|
|
env_verdict_.cmd_window, env_geometry_.edt_body_min, env_geometry_.corridor.plan_clear_ahead,
|
|
env_geometry_.corridor.min_width, s.traj_contact_dist,
|
|
env_used_local_plan_ ? "local plan" : "arc", env_verdict_.v_cap,
|
|
env_verdict_.stall_detected ? 1 : 0, env_verdict_.stall_muted ? "(muted)" : "",
|
|
env_verdict_.unreachable_detected ? 1 : 0, env_verdict_.unreachable_muted ? "(muted)" : "",
|
|
env_verdict_.brake ? 1 : 0, env_verdict_.contact_standdown ? 1 : 0,
|
|
env_verdict_.replan_budget_left, env_verdict_.net_disp,
|
|
env_verdict_.wandering ? " WANDERING"
|
|
: (env_verdict_.idle ? " IDLE" : (env_verdict_.confined ? " CONFINED" : "")));
|
|
}
|
|
if (env_logger_ && (s.geometry_valid || env_verdict_.event[0] != '\0'))
|
|
{
|
|
env_logger_->record(now, s, env_verdict_, s.geometry_valid ? &env_geometry_ : nullptr,
|
|
toString(state_machine_.state()), active_request_.mission_sequence_id,
|
|
env_used_local_plan_);
|
|
}
|
|
}
|
|
|
|
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())
|
|
{
|
|
controller_feedback_ = ControllerFeedback::kGoalReached;
|
|
if (config_.debug_plan)
|
|
{
|
|
// Nhánh này trả candidate RỖNG — không có lệnh nào được tính ở cycle này. Một planner báo
|
|
// "đã tới" ngay từ cycle đầu (trước khi computeVelocityCommands từng chạy lần nào) là triệu
|
|
// chứng ĐÚNG của "robot đứng im, không phát lệnh": không phải lệnh bị chặn, mà chưa bao giờ
|
|
// có lệnh nào được tính.
|
|
robot::log_info_throttle(kDebugControlLogThrottle,
|
|
"[move_base2][debug] runController: isGoalReached() = true -- "
|
|
"không tính lệnh cycle này (candidate = 0).\n");
|
|
}
|
|
return;
|
|
}
|
|
|
|
robot_geometry_msgs::Twist cmd;
|
|
if (deps_.controller->computeVelocityCommands(cmd))
|
|
{
|
|
controller_feedback_ = ControllerFeedback::kCommandValid;
|
|
candidate = cmd;
|
|
if (config_.debug_plan)
|
|
{
|
|
// v/omega TRƯỚC VelocityArbiter — phân biệt "planner không phát lệnh" (giá trị ở đây đã là
|
|
// 0 hoặc gần 0) với "lệnh phát ra nhưng bị guard/arbiter cắt về 0 phía sau" (giá trị ở đây
|
|
// khác 0 nhưng /cmd_vel lại là 0 — xem log EnvMonitor / VelocityArbiter cho cycle này).
|
|
robot::log_info_throttle(kDebugControlLogThrottle,
|
|
"[move_base2][debug] runController: command_valid v=%.3f m/s "
|
|
"omega=%.4f rad/s (trước arbiter).\n",
|
|
cmd.linear.x, cmd.angular.z);
|
|
}
|
|
return;
|
|
}
|
|
|
|
controller_feedback_ = ControllerFeedback::kNoValidCommand;
|
|
}
|
|
|
|
bool ControlLoop::step()
|
|
{
|
|
if (!initialized_)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// --- 1. Thời gian và pose -------------------------------------------------------------------
|
|
const robot::Time now = deps_.clock->now();
|
|
|
|
double dt = config_.nominal_control_period;
|
|
if (has_last_cycle_time_)
|
|
{
|
|
dt = (now - last_cycle_time_).toSec();
|
|
if (dt < 0.0)
|
|
{
|
|
// Đồng hồ lùi (thường do đổi nguồn time). Không có dt tin được thì bỏ giới hạn gia tốc ở
|
|
// cycle này thay vì tính ra một giá trị bịa.
|
|
dt = 0.0;
|
|
}
|
|
}
|
|
last_cycle_time_ = now;
|
|
has_last_cycle_time_ = true;
|
|
|
|
// Thu kết quả lập plan TRƯỚC khi dựng dữ liệu vào: state machine quyết định dựa trên phản hồi,
|
|
// nên phản hồi phải có mặt trước lúc nó chạy.
|
|
collectPlannerResult();
|
|
|
|
robot_geometry_msgs::PoseStamped robot_pose;
|
|
const bool pose_available = deps_.pose->getRobotPose(robot_pose);
|
|
|
|
double travelled = 0.0;
|
|
if (pose_available && has_oscillation_origin_)
|
|
{
|
|
const double dx = robot_pose.pose.position.x - oscillation_origin_.pose.position.x;
|
|
const double dy = robot_pose.pose.position.y - oscillation_origin_.pose.position.y;
|
|
travelled = std::hypot(dx, dy);
|
|
}
|
|
|
|
// Costmap còn hạn không — hỏi ở ĐÂY chứ không ở mục 3.5 như trước: EnvMonitor cần nó, mà monitor
|
|
// phải chạy xong trước state machine. Vẫn là một lời gọi mỗi cycle, chỉ đổi vị trí.
|
|
const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr &&
|
|
!deps_.costmap_status->isCurrent();
|
|
|
|
// --- 1b. Giám sát tuyến ---------------------------------------------------------------------
|
|
// Chạy TRƯỚC state machine: hai cờ nó sinh ra là dữ liệu vào của state machine ngay cycle này.
|
|
// Một snapshot costmap cho CẢ cycle: monitor và controller đọc cùng một lưới (P0b). No-op khi tắt snapshot.
|
|
if (deps_.environment != nullptr)
|
|
{
|
|
deps_.environment->refresh();
|
|
}
|
|
updateEnvMonitor(now, dt, robot_pose, pose_available, costmap_stale);
|
|
|
|
// --- 2. State machine -----------------------------------------------------------------------
|
|
StateMachineInput input;
|
|
input.now = now;
|
|
input.has_pending_request = has_pending_request_;
|
|
input.pending_request_has_goal = pending_request_.has_goal;
|
|
input.pending_request_action_count = pending_request_.actions.size();
|
|
input.pause_requested = pause_requested_;
|
|
input.resume_requested = resume_requested_;
|
|
input.cancel_requested = cancel_requested_;
|
|
input.emergency = emergency_;
|
|
input.planner = planner_feedback_;
|
|
input.controller = controller_feedback_;
|
|
input.recovery = recovery_feedback_;
|
|
input.action = action_feedback_;
|
|
input.action_message = action_message_;
|
|
input.pose_available = pose_available;
|
|
input.costmap_current = !costmap_stale;
|
|
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/docs/move_base2/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).
|
|
input.path_blocked = env_verdict_.path_blocked;
|
|
input.collision = env_verdict_.collision;
|
|
input.off_path = false;
|
|
input.no_progress = env_verdict_.no_progress;
|
|
|
|
// Cùng một chỉ số dùng cho cả cycle khởi động recovery lẫn các cycle tick: state machine chỉ tăng
|
|
// chỉ số khi behavior kết thúc, nên `nextRecoveryIndex()` chính là behavior sắp chạy hoặc đang
|
|
// chạy. Hỏi trước khi state machine quyết định để nó biết có nên trao quyền phát vận tốc không.
|
|
input.active_recovery_output =
|
|
deps_.recovery != nullptr
|
|
? deps_.recovery->outputKind(state_machine_.nextRecoveryIndex())
|
|
: RecoveryOutputKind::kNone;
|
|
|
|
const StateMachineOutput output = state_machine_.update(input);
|
|
|
|
if (output.state_changed)
|
|
{
|
|
last_reason_ = output.reason;
|
|
if (config_.debug_state)
|
|
{
|
|
robot::log_info("[move_base2][debug] state -> %s: %s "
|
|
"(planner=%s controller=%s recovery=%s pose=%s active_request=%s).\n",
|
|
toString(output.state), output.reason != nullptr ? output.reason : "",
|
|
toString(input.planner), toString(input.controller), toString(input.recovery),
|
|
pose_available ? "yes" : "no", has_active_request_ ? "yes" : "no");
|
|
}
|
|
}
|
|
|
|
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;
|
|
|
|
// Phản hồi của cycle trước đã dùng xong; đặt lại để cycle này tự sinh phản hồi mới.
|
|
planner_feedback_ = PlannerFeedback::kIdle;
|
|
controller_feedback_ = ControllerFeedback::kIdle;
|
|
recovery_feedback_ = RecoveryFeedback::kIdle;
|
|
action_feedback_ = ActionFeedback::kIdle;
|
|
action_message_.clear();
|
|
|
|
// --- 3. Thi hành output ---------------------------------------------------------------------
|
|
// Nhãn của yêu cầu SẮP bị thay. Preempt bật cả `report_outcome` lẫn `accept_request` trong cùng
|
|
// một cycle, mà phần báo kết quả nằm sau phần nhận yêu cầu — không giữ lại id cũ ở đây thì kết
|
|
// quả của chặng cũ sẽ được báo dưới id của chặng MỚI, và mission layer mất dấu cả hai.
|
|
const std::uint64_t outgoing_mission_id =
|
|
has_active_request_ ? active_request_.mission_sequence_id : 0;
|
|
const bool had_active_request = has_active_request_;
|
|
|
|
if (output.accept_request)
|
|
{
|
|
active_request_ = pending_request_;
|
|
has_active_request_ = true;
|
|
has_pending_request_ = false;
|
|
latest_plan_.clear();
|
|
order_plan_.clear();
|
|
has_outcome_ = false;
|
|
env_monitor_.onGoalAccepted(now);
|
|
|
|
// Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop.
|
|
if (active_request_.has_goal)
|
|
{
|
|
// yaw có mặt ở đây vì một chặng quay tại chỗ KHÁC chặng thường đúng ở con số này: x, y giữ
|
|
// nguyên và chỉ hướng đổi. Thiếu nó thì một chặng quay hỏng trông y hệt một chặng quay đúng.
|
|
robot::log_info("[move_base2] Goal received (mission %llu): x=%.3f y=%.3f yaw=%.4f frame=%s.\n",
|
|
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
|
active_request_.goal.pose.position.x, active_request_.goal.pose.position.y,
|
|
yawOf(active_request_.goal), active_request_.goal.header.frame_id.c_str());
|
|
}
|
|
else
|
|
{
|
|
robot::log_info("[move_base2] Action-only request received (mission %llu), %zu action(s).\n",
|
|
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
|
active_request_.actions.size());
|
|
}
|
|
|
|
// Nhãn mới: mọi lượt lập plan đang bay thuộc về goal cũ và phải bị vứt khi về.
|
|
++plan_tag_;
|
|
deps_.planner->cancelPlan();
|
|
planner_running_ = false;
|
|
|
|
// Nhịp replan nền đếm lại từ đầu chặng — lượt plan đầu tiên của chặng do state machine yêu
|
|
// cầu, replan nền chỉ bắt đầu sau đó một chu kỳ đầy đủ.
|
|
last_plan_started_ = now;
|
|
}
|
|
|
|
if (output.reset_oscillation_origin && pose_available)
|
|
{
|
|
oscillation_origin_ = robot_pose;
|
|
has_oscillation_origin_ = true;
|
|
}
|
|
|
|
if (output.stop_planner)
|
|
{
|
|
// Huỷ thật, không chỉ quên đi: nếu chỉ hạ cờ thì lượt đang chạy vẫn về và chiếm chỗ hộp thư,
|
|
// rồi bị nhận nhầm cho lượt kế tiếp mang cùng nhãn.
|
|
deps_.planner->cancelPlan();
|
|
planner_running_ = false;
|
|
}
|
|
|
|
if (output.apply_plan && !latest_plan_.empty())
|
|
{
|
|
if (!deps_.controller->setPlan(latest_plan_))
|
|
{
|
|
// Controller từ chối plan: coi như lần lập plan này hỏng, để chu kỳ kiên nhẫn tiếp tục chạy.
|
|
planner_feedback_ = PlannerFeedback::kFailed;
|
|
if (config_.debug_plan)
|
|
{
|
|
robot::log_error("[move_base2][debug] controller rejected plan with %zu pose(s); "
|
|
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
|
|
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
|
latest_plan_.front().pose.position.y,
|
|
latest_plan_.front().header.frame_id.c_str(),
|
|
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
|
latest_plan_.back().header.frame_id.c_str());
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// Mốc cho `grace_after_new_plan`: ngay sau khi đổi plan, pose robot có thể còn lệch so với
|
|
// plan vừa tới (rõ nhất lúc preempt/đổi chặng). Đo lệch tuyến ngay lúc đó là khai hoả oan.
|
|
last_plan_applied_ = now;
|
|
has_last_plan_applied_ = true;
|
|
env_monitor_.onPlanApplied(now);
|
|
env_plan_index_valid_ = false;
|
|
|
|
if (config_.debug_plan)
|
|
{
|
|
// yaw của pose CUỐI: đây là thứ setGoalPose() thực sự trao cho local planner. Chặng quay
|
|
// tại chỗ có first/last CÙNG vị trí — không có yaw ở đây thì log không phân biệt được
|
|
// "goal đúng nhưng chưa quay tới" với "goal sai ngay từ khi lập plan".
|
|
robot::log_info("[move_base2][debug] controller accepted plan with %zu pose(s); "
|
|
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, yaw=%.4f, frame=%s).\n",
|
|
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
|
latest_plan_.front().pose.position.y,
|
|
latest_plan_.front().header.frame_id.c_str(),
|
|
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
|
yawOf(latest_plan_.back()), latest_plan_.back().header.frame_id.c_str());
|
|
}
|
|
}
|
|
}
|
|
|
|
if (output.cancel_recovery)
|
|
{
|
|
deps_.recovery->cancel();
|
|
}
|
|
|
|
// Giám sát tuyến hết đường vòng (contract 2026-08-05e): KHÔNG kết thúc chặng — robot bám tiếp
|
|
// plan cũ và trigger bị khoá tới khi đi được quá `oscillation_distance`. Log đúng MỘT dòng ở
|
|
// sườn khoá, vì sau đó nhánh monitor im lặng hoàn toàn và người vận hành sẽ không hiểu vì sao
|
|
// robot vẫn tiến về phía vật cản.
|
|
if (output.monitor_trigger_suppressed)
|
|
{
|
|
robot::log_warning("[move_base2] %s: no detour left — continuing on the current plan. From "
|
|
"here the controller is the only safety net: it stops at the obstacle and "
|
|
"controller_patience escalates to controlling_failed. This trigger stays "
|
|
"muted until the robot travels %.2f m.\n",
|
|
toString(output.recovery_trigger), config_.state_machine.oscillation_distance);
|
|
}
|
|
|
|
// Recovery vừa nộp path mới nhưng robot chưa dịch chuyển kể từ path mới trước đó: state machine
|
|
// tính lần đó vào ngân sách route thay vì nạp lại (2026-09-04). Không gate: đây là dấu hiệu robot
|
|
// đang kẹt tại chỗ và mỗi lượt như vậy tiến gần ABORT thêm một nấc — người vận hành phải thấy.
|
|
if (output.recovery_reset_denied)
|
|
{
|
|
robot::log_warning("[move_base2] recovery produced a new path but the robot has not moved since "
|
|
"the previous one (%.2f m, need %.2f m) — counting it against the %s route "
|
|
"budget instead of refilling it.\n",
|
|
output.recovery_reset_travel, config_.state_machine.recovery_reset_min_travel,
|
|
toString(output.recovery_trigger));
|
|
}
|
|
|
|
robot_geometry_msgs::Twist candidate;
|
|
env_controller_v_ = 0.0; // controller không chạy cycle này = không đòi đi.
|
|
|
|
if (output.start_recovery)
|
|
{
|
|
running_recovery_trigger_ = output.recovery_trigger;
|
|
if (!deps_.recovery->start(output.recovery_index, output.recovery_trigger))
|
|
{
|
|
// Behavior từ chối khởi động (ví dụ đã va chạm ngay tại chỗ) — báo hỏng để state machine
|
|
// chuyển sang behavior kế tiếp thay vì tick một behavior chưa start.
|
|
recovery_feedback_ = RecoveryFeedback::kFailed;
|
|
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
|
|
}
|
|
}
|
|
else if (output.tick_recovery)
|
|
{
|
|
const RecoveryTick tick = deps_.recovery->update();
|
|
switch (tick.status)
|
|
{
|
|
case RecoveryTick::Status::kRunning:
|
|
recovery_feedback_ = RecoveryFeedback::kRunning;
|
|
break;
|
|
case RecoveryTick::Status::kSucceeded:
|
|
recovery_feedback_ = RecoveryFeedback::kSucceeded;
|
|
env_monitor_.onRecoveryFinished(now,
|
|
tick.has_path && !tick.path.empty() ? EnvRecoveryOutcome::kSucceededWithPath
|
|
: EnvRecoveryOutcome::kSucceeded,
|
|
running_recovery_trigger_ == RecoveryTrigger::kCollision);
|
|
break;
|
|
case RecoveryTick::Status::kFailed:
|
|
recovery_feedback_ = RecoveryFeedback::kFailed;
|
|
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
|
|
break;
|
|
}
|
|
if (tick.has_velocity)
|
|
{
|
|
candidate = tick.cmd;
|
|
}
|
|
if (tick.has_path && !tick.path.empty())
|
|
{
|
|
// Họ recovery sinh lại đường đi: coi kết quả như một plan mới, chờ state machine đẩy xuống.
|
|
latest_plan_ = tick.path;
|
|
planner_feedback_ = PlannerFeedback::kPlanReady;
|
|
if (config_.debug_plan)
|
|
{
|
|
robot::log_info("[move_base2][debug] recovery produced path with %zu pose(s); "
|
|
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
|
|
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
|
latest_plan_.front().pose.position.y,
|
|
latest_plan_.front().header.frame_id.c_str(),
|
|
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
|
latest_plan_.back().header.frame_id.c_str());
|
|
}
|
|
}
|
|
}
|
|
|
|
if (output.cancel_action && deps_.action != nullptr)
|
|
{
|
|
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)
|
|
{
|
|
// Cửa submit đã chặn yêu cầu có action mà không có port, nhưng vẫn guard: kẹt ở đây nghĩa là
|
|
// contract bị phá từ một đường khác — báo action hỏng để state machine kết thúc tường minh.
|
|
if (deps_.action == nullptr || output.action_index >= active_request_.actions.size())
|
|
{
|
|
action_feedback_ = ActionFeedback::kFailed;
|
|
}
|
|
else if (!deps_.action->start(active_request_.actions[output.action_index]))
|
|
{
|
|
// Không có handler cho actionType này hoặc handler từ chối — action coi như thất bại.
|
|
action_feedback_ = ActionFeedback::kFailed;
|
|
}
|
|
}
|
|
else if (output.tick_action && deps_.action != nullptr)
|
|
{
|
|
const ActionTick tick = deps_.action->update();
|
|
switch (tick.status)
|
|
{
|
|
case ActionTick::Status::kRunning:
|
|
action_feedback_ = ActionFeedback::kRunning;
|
|
break;
|
|
case ActionTick::Status::kSucceeded:
|
|
action_feedback_ = ActionFeedback::kSucceeded;
|
|
// Log ở mức info: một action chạy xong là sự kiện hiếm, và câu này mang theo số mẫu / frame
|
|
// đã ghi — thứ cần đối chiếu khi lần sau nó hỏng.
|
|
if (!tick.message.empty())
|
|
{
|
|
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
|
|
// đây chuỗi đó dừng ngay tại đây và ra ngoài chỉ còn "action failed" — ba lần chạy hiện
|
|
// trường liên tiếp không truy được nguyên nhân chính vì thế.
|
|
if (!tick.message.empty())
|
|
{
|
|
robot::log_error("[move_base2] %s\n", tick.message.c_str());
|
|
}
|
|
break;
|
|
}
|
|
// Giữ lại cho lần dựng StateMachineInput ngay sau đó; xoá khi status khác kFailed để lý do cũ
|
|
// không bám sang một action khác.
|
|
action_message_ = (tick.status == ActionTick::Status::kFailed) ? tick.message : std::string();
|
|
}
|
|
|
|
// --- 3.5 Guard "không đi mù" -----------------------------------------------------------------
|
|
//
|
|
// Dữ liệu quan sát hết hạn nghĩa là costmap đang mô tả một thế giới của quá khứ. move_base thế hệ
|
|
// 1 chặn nguyên cycle tại đây (`move_base.cpp:2720`) và phát vận tốc 0; giữ nguyên ngữ nghĩa đó.
|
|
//
|
|
// Chỉ chặn hai thứ THỰC SỰ làm robot chạy: lời gọi controller và quyền phát vận tốc. Recovery vẫn
|
|
// được tick, có chủ đích — `ClearCostmapRecovery` chính là đường thoát đúng khi costmap hỏng, chặn
|
|
// nó đi là bịt mất lối phục hồi duy nhất còn tác dụng. Behavior họ velocity không bị thiệt vì
|
|
// chúng đo tiến độ bằng POSE: robot không nhúc nhích thì chúng tự hết giờ và báo hỏng, chứ không
|
|
// báo thành công nhầm.
|
|
if (costmap_stale)
|
|
{
|
|
// Throttle: đây là vòng lặp điều khiển, và tình trạng này kéo dài hàng giây.
|
|
robot::log_warning_throttle(kStaleCostmapLogThrottle,
|
|
"[move_base2] Sensor data is stale — wheel commands blocked (the "
|
|
"costmap is describing a past world).\n");
|
|
}
|
|
|
|
if (output.state == NavigationState::kControlling && !pose_available)
|
|
{
|
|
if (config_.debug_skip)
|
|
{
|
|
robot::log_warning_throttle(
|
|
kDebugControlLogThrottle,
|
|
"[move_base2][debug] controller skipped while CONTROLLING: pose unavailable "
|
|
"(reason=%s, controller_feedback_in=%s, recovery_cursor=%zu/%zu).\n",
|
|
output.reason != nullptr ? output.reason : "", toString(input.controller),
|
|
output.recovery_route_cursor, output.recovery_route_size);
|
|
}
|
|
}
|
|
|
|
if (output.run_controller && costmap_stale)
|
|
{
|
|
if (config_.debug_skip)
|
|
{
|
|
robot::log_warning_throttle(
|
|
kDebugControlLogThrottle,
|
|
"[move_base2][debug] controller skipped while CONTROLLING: costmap stale "
|
|
"(reason=%s, controller_feedback_in=%s, recovery_cursor=%zu/%zu).\n",
|
|
output.reason != nullptr ? output.reason : "", toString(input.controller),
|
|
output.recovery_route_cursor, output.recovery_route_size);
|
|
}
|
|
}
|
|
|
|
if (output.run_controller && !costmap_stale)
|
|
{
|
|
runController(candidate);
|
|
if (controller_feedback_ == ControllerFeedback::kCommandValid)
|
|
{
|
|
env_controller_v_ = candidate.linear.x; // trước guard / bao / trọng tài: ý định thật của controller
|
|
// EnvMonitor: bao tốc độ theo tiếp xúc trên quỹ đạo thật. Chỉ tác động khi `contact/apply_command`
|
|
// (P4); ở shadow chỉ có dòng log "would cap". Giữ omega/v để cung không đổi khi kẹp.
|
|
if (std::isfinite(env_verdict_.v_cap) && std::fabs(candidate.linear.x) > env_verdict_.v_cap)
|
|
{
|
|
if (config_.env_monitor.contact.apply_command)
|
|
{
|
|
const double scale = env_verdict_.v_cap / std::fabs(candidate.linear.x);
|
|
candidate.linear.x *= scale;
|
|
candidate.angular.z *= scale;
|
|
}
|
|
else if (config_.debug_env)
|
|
{
|
|
robot::log_info_throttle(2.0, "[move_base2][debug] EnvMonitor: would cap v %.2f -> %.2f m/s "
|
|
"(contact %.2f m along the %s; shadow, not applied).\n",
|
|
candidate.linear.x, env_verdict_.v_cap, env_contact_dist_,
|
|
env_used_local_plan_ ? "local plan" : "commanded arc");
|
|
}
|
|
}
|
|
|
|
// EnvMonitor giữ phanh MÀ cờ collision đã giơ và state machine vẫn để CONTROLLING (route
|
|
// collision cạn/khoá): lệnh vừa bị huỷ thì với state machine nó KHÔNG hợp lệ — cùng luật (A)
|
|
// của guard cũ. Báo đúng sự thật thì controller_patience chạy -> route controlling_failed ->
|
|
// ABORT có log, thay vì robot đứng chết vô hạn với controller "ổn". Trước khi cờ giơ (1 s kề
|
|
// mũi) controller vẫn hợp lệ: patience 0,5 s không được chạy đua với chính cờ collision.
|
|
if (env_brake_ && env_verdict_.collision)
|
|
{
|
|
controller_feedback_ = ControllerFeedback::kNoValidCommand;
|
|
robot::log_warning_throttle(2.0,
|
|
"[move_base2] EnvMonitor: holding the brake (contact %.2f m along the %s, "
|
|
"controller wants v=%.2f) — reported as no valid command; if the collision "
|
|
"trigger is locked, controller_patience escalates.\n",
|
|
env_contact_dist_, env_used_local_plan_ ? "local plan" : "commanded arc",
|
|
candidate.linear.x);
|
|
}
|
|
}
|
|
if (controller_feedback_ == ControllerFeedback::kNoValidCommand)
|
|
{
|
|
if (config_.debug_skip)
|
|
{
|
|
robot::log_warning_throttle(
|
|
kDebugControlLogThrottle,
|
|
"[move_base2][debug] controller returned no valid command "
|
|
"(reason=%s, planner_in=%s, controller_in=%s, recovery_in=%s, pose=%s, "
|
|
"recovery_cursor=%zu/%zu).\n",
|
|
output.reason != nullptr ? output.reason : "", toString(input.planner),
|
|
toString(input.controller), toString(input.recovery), pose_available ? "yes" : "no",
|
|
output.recovery_route_cursor, output.recovery_route_size);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Replan nền (contract 2026-08-04): đang bám plan và tới nhịp `planner_frequency` thì khởi động
|
|
// một lượt lập plan mới trên thread planner. Plan mới về được kControlling nhận ngay (apply_plan)
|
|
// mà KHÔNG đổi state — controller không dừng một cycle nào. Đây là cơ chế thay plan duy nhất
|
|
// trong lúc chạy, vì controller hỏng không còn kéo máy về kPlanning nữa.
|
|
//
|
|
// Nhịp đếm lại mỗi lần (TÁI) vào kControlling: sau recovery bám tiếp plan cũ — hoặc nhận path
|
|
// detour — plan đó phải sống được trọn một chu kỳ planner_frequency trước khi lượt replan nền
|
|
// đầu tiên có quyền thay nó. Không đếm lại thì đồng hồ vẫn mang cả quãng thời gian nằm trong
|
|
// recovery và replan nền nổ ngay cycle đầu sau khi quay lại, đè mất path detour vừa nộp.
|
|
if (output.state_changed && output.state == NavigationState::kControlling)
|
|
{
|
|
last_plan_started_ = now;
|
|
}
|
|
|
|
const bool periodic_replan_due =
|
|
config_.planner_frequency > 0.0 && output.state == NavigationState::kControlling &&
|
|
(now - last_plan_started_).toSec() >= 1.0 / config_.planner_frequency;
|
|
|
|
if ((output.start_planner || periodic_replan_due) && pose_available && !planner_running_)
|
|
{
|
|
// `start_planner` là tín hiệu MỨC ("hãy đang lập plan"), bật lại mỗi cycle chừng nào state
|
|
// machine còn ở kPlanning — không phải sườn. Kick lại một lượt đang chạy sẽ vừa bị cổng từ
|
|
// chối, vừa làm mất thời gian đã bỏ ra.
|
|
// SBPLLatticePlanner và nhiều planner tổng quát chỉ hiện thực overload ba tham số. Backup vì
|
|
// thế chủ đích không nhận Order; planner chính vẫn nhận Order đầy đủ (CustomPlanner).
|
|
const robot_protocol_msgs::Order* order =
|
|
backup_global_planner_active_ ? nullptr : active_request_.order.get();
|
|
planner_running_ = deps_.planner->startPlan(robot_pose, active_request_.goal, order, plan_tag_);
|
|
if (planner_running_)
|
|
{
|
|
last_plan_started_ = now;
|
|
}
|
|
else if (output.start_planner)
|
|
{
|
|
// 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;
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
|
|
// Sắp chạm vật cản thật cũng là "không ai được phát": lệnh 0 tức thì, không giảm dần.
|
|
arbiter_.arbitrate((costmap_stale || env_brake_) ? VelocitySource::kNone : output.velocity_source,
|
|
candidate, dt);
|
|
|
|
if (config_.debug_plan && output.run_controller)
|
|
{
|
|
// Sau arbiter — thứ AmrPublisher thật sự lấy để phát /cmd_vel. Đối chiếu với dòng
|
|
// "runController: command_valid v=... omega=... (trước arbiter)" ở trên: hai dòng khác
|
|
// nhau nghĩa là VelocityArbiter (kẹp trần/gia tốc) hoặc EnvMonitor brake đã sửa lệnh; hai
|
|
// dòng giống hệt mà /cmd_vel vẫn đo được 0 thì lỗi nằm ngoài move_base2 (AmrPublisher, driver
|
|
// bánh xe, hoặc sim).
|
|
const robot_geometry_msgs::Twist& published = arbiter_.lastCommand();
|
|
robot::log_info_throttle(kDebugControlLogThrottle,
|
|
"[move_base2][debug] runController: sau arbiter v=%.3f m/s "
|
|
"omega=%.4f rad/s (nguồn=%s, source_in=%s).\n",
|
|
published.linear.x, published.angular.z,
|
|
toString(controller_feedback_), toString(output.velocity_source));
|
|
}
|
|
|
|
// --- 5. Báo kết quả -------------------------------------------------------------------------
|
|
if (output.report_outcome)
|
|
{
|
|
last_outcome_ = output.outcome;
|
|
has_outcome_ = true;
|
|
++outcome_report_count_;
|
|
|
|
// Log kết cục ra terminal — bản cũ báo "Goal reached!" tại đây, host và người vận hành đều
|
|
// dựa vào dòng này để biết chặng kết thúc ra sao. Chỉ chạy đúng một lần mỗi chặng.
|
|
switch (output.outcome)
|
|
{
|
|
case NavigationOutcome::kSucceeded:
|
|
robot::log_success("[move_base2] Goal reached (mission %llu).\n",
|
|
static_cast<unsigned long long>(outgoing_mission_id));
|
|
break;
|
|
case NavigationOutcome::kPreempted:
|
|
robot::log_info("[move_base2] Goal replaced by a new goal (mission %llu: PREEMPTED).\n",
|
|
static_cast<unsigned long long>(outgoing_mission_id));
|
|
break;
|
|
case NavigationOutcome::kCancelled:
|
|
robot::log_info("[move_base2] Goal cancelled (mission %llu: CANCELLED).\n",
|
|
static_cast<unsigned long long>(outgoing_mission_id));
|
|
break;
|
|
case NavigationOutcome::kFailed:
|
|
if (output.reason != nullptr &&
|
|
std::strcmp(output.reason, "no recovery behavior left") == 0)
|
|
{
|
|
// KHÔNG gắn thẻ [debug] và KHÔNG cho tắt: đây là LÝ DO mission hỏng, in đúng một lần
|
|
// mỗi lần abort. Công tắc `debug/*` dành cho log mô tả đường đi bình thường; tắt được
|
|
// một dòng lỗi nghĩa là có cấu hình khiến robot hỏng trong im lặng.
|
|
robot::log_error("[move_base2] abort detail: recovery route exhausted "
|
|
"(trigger=%s cursor=%zu size=%zu, planner_in=%s, controller_in=%s, "
|
|
"recovery_in=%s, pose=%s, costmap_current=%s).\n",
|
|
toString(output.recovery_trigger), output.recovery_route_cursor,
|
|
output.recovery_route_size, toString(input.planner),
|
|
toString(input.controller), toString(input.recovery),
|
|
pose_available ? "yes" : "no", costmap_stale ? "no" : "yes");
|
|
}
|
|
robot::log_error("[move_base2] Navigation failed (mission %llu: ABORTED): %s\n",
|
|
static_cast<unsigned long long>(outgoing_mission_id),
|
|
last_reason_ != nullptr ? last_reason_ : "");
|
|
break;
|
|
}
|
|
|
|
if (deps_.mission != nullptr && had_active_request && outgoing_mission_id != 0)
|
|
{
|
|
deps_.mission->reportOutcome(outgoing_mission_id, output.outcome);
|
|
}
|
|
|
|
// Preempt vừa báo kết quả chặng cũ VỪA nhận chặng mới trong cùng cycle. Chỉ xoá yêu cầu đang
|
|
// chạy khi thực sự không có chặng mới nào thay thế.
|
|
if (!output.accept_request)
|
|
{
|
|
has_active_request_ = false;
|
|
latest_plan_.clear();
|
|
planner_running_ = false;
|
|
}
|
|
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ả".
|
|
return !isTerminal(output.state);
|
|
}
|
|
|
|
const char* ControlLoop::lastOutcome() const
|
|
{
|
|
return has_outcome_ ? toString(last_outcome_) : "";
|
|
}
|
|
|
|
} // namespace move_base2
|