Seven [move_base2][debug] lines printed unconditionally on every cycle. On a
robot running a full shift that is noise: they describe the normal path, and
constant noise buries the one line that is actually abnormal.
Three switches, grouped by what they answer, all defaulting to on so turning
them off is a deliberate act rather than something that changes behind whoever
is relying on the log:
debug/state state machine transitions, printed on change, not per cycle
debug/plan controller accepting or rejecting a plan, recovery paths
debug/skip why the controller was skipped while CONTROLLING
The abort-detail line stays unconditional and loses its [debug] tag. It is the
reason a mission failed and prints once per abort; a config that can silence it
is a config in which the robot fails silently.
The read path runs YAML debug/{state,plan,skip} into MoveBase2Config, which
carries it to ControlLoopConfig. describe() prints the resulting state at boot
so nobody has to guess why a log went quiet.
Nothing computes differently: stripping every log statement from the old and
new control_loop.cpp leaves a three-line difference, and all three are comments.
The gated arguments are pure reads.
1251 lines
51 KiB
C++
1251 lines
51 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 <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;
|
|
|
|
/// [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 ControlLoopConfig::PathMonitorConfig::monitors(MotionProfile profile) const
|
|
{
|
|
return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
|
|
}
|
|
|
|
// ================================================================================================
|
|
// 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;
|
|
|
|
// Bật giám sát mà không có đường xử lý nào là cấu hình vô nghĩa — và trước đây nó im lặng. Không
|
|
// chặn boot (navigation vẫn phải chạy), nhưng phải hét lên: người vận hành khai `enabled: true`
|
|
// thì tin rằng cơ chế đang chạy.
|
|
if (config_.path_monitor.enabled)
|
|
{
|
|
if (deps_.path_check == nullptr)
|
|
{
|
|
robot::log_error("[move_base2] path_monitor is enabled but no PathCheckPort is wired — path "
|
|
"monitoring stays OFF.\n");
|
|
}
|
|
else if (!config_.path_monitor.path_blocked_enabled && !config_.path_monitor.off_path_enabled)
|
|
{
|
|
robot::log_warning("[move_base2] path_monitor/enabled is true but BOTH sub-monitors are off "
|
|
"(path_blocked_enabled=false, off_path_enabled=false) — path monitoring "
|
|
"does nothing.\n");
|
|
}
|
|
else if (config_.state_machine.recovery_routes.path_blocked.empty() &&
|
|
config_.state_machine.recovery_routes.off_path.empty())
|
|
{
|
|
robot::log_error("[move_base2] path_monitor is enabled but BOTH recovery routes "
|
|
"'path_blocked' and 'off_path' are empty (behaviors failed to load?) — path "
|
|
"monitoring stays OFF.\n");
|
|
}
|
|
else
|
|
{
|
|
// In trạng thái THẬT của từng phép đo, đã gộp cả ba nút: đọc một dòng là biết cái nào sống.
|
|
const bool blocked_on = config_.path_monitor.path_blocked_enabled &&
|
|
config_.path_monitor.horizon > 0.0 &&
|
|
!config_.state_machine.recovery_routes.path_blocked.empty();
|
|
const bool off_path_on = config_.path_monitor.off_path_enabled &&
|
|
config_.path_monitor.max_cross_track > 0.0 &&
|
|
!config_.state_machine.recovery_routes.off_path.empty();
|
|
robot::log_info("[move_base2] path monitor ON (confirm=%.2f s, check=%.2f s):\n"
|
|
" path_blocked: %s (flag=%s, horizon=%.2f m, route=%zu)\n"
|
|
" off_path : %s (flag=%s, max_cross_track=%.2f m, route=%zu)\n",
|
|
config_.path_monitor.confirm_time, config_.path_monitor.check_period,
|
|
blocked_on ? "ON" : "OFF",
|
|
config_.path_monitor.path_blocked_enabled ? "on" : "off",
|
|
config_.path_monitor.horizon,
|
|
config_.state_machine.recovery_routes.path_blocked.size(),
|
|
off_path_on ? "ON" : "OFF",
|
|
config_.path_monitor.off_path_enabled ? "on" : "off",
|
|
config_.path_monitor.max_cross_track,
|
|
config_.state_machine.recovery_routes.off_path.size());
|
|
}
|
|
}
|
|
|
|
initialized_ = true;
|
|
reset();
|
|
return true;
|
|
}
|
|
|
|
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;
|
|
|
|
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();
|
|
resetPathMonitor();
|
|
has_last_plan_applied_ = 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);
|
|
|
|
if (!has_frame && !has_distance)
|
|
{
|
|
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;
|
|
}
|
|
|
|
if (has_frame)
|
|
{
|
|
if (!deps_.pose->lookupPose(request.goal_frame, request.goal))
|
|
{
|
|
reason = "cannot resolve goal_frame '" + request.goal_frame + "'";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
robot_geometry_msgs::PoseStamped robot_pose;
|
|
if (!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 = "relative_distance needs the robot pose, which is not available";
|
|
return false;
|
|
}
|
|
|
|
const auto& q = robot_pose.pose.orientation;
|
|
const double yaw = std::atan2(2.0 * (q.w * q.z + q.x * q.y),
|
|
1.0 - 2.0 * (q.y * q.y + q.z * q.z)); // [rad]
|
|
request.goal = robot_pose;
|
|
request.goal.pose.position.x += request.relative_distance * std::cos(yaw);
|
|
request.goal.pose.position.y += request.relative_distance * std::sin(yaw);
|
|
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;
|
|
}
|
|
|
|
// 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 phải được chọn TRƯỚC khi swap sang docking planner: planner legacy đọc `maker_name`
|
|
// trong initialize() (một lần), nên thứ tự ngược lại là dock vào marker của chặng trước.
|
|
// Compound action dùng goal_frame đã quy về pose tuyệt đối và HybridLocalPlanner không đọc
|
|
// maker_name, vì thế profile đó tắt requirement qua config thay vì bịa một marker.
|
|
if (request.profile == MotionProfile::kDocking)
|
|
{
|
|
if (request.marker.empty() && config_.docking_requires_marker)
|
|
{
|
|
reason = "docking request has no marker";
|
|
return false;
|
|
}
|
|
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::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ó.
|
|
if (!backup_global_planner_active_ && !config_.backup_global_planner_name.empty())
|
|
{
|
|
const std::string failed_planner = deps_.planner->activePlanner();
|
|
if (deps_.planner->swapPlanner(config_.backup_global_planner_name))
|
|
{
|
|
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;
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
// Luật "không thay plan sạch bằng plan bẩn" (contract 2026-08-04d).
|
|
//
|
|
// Không có luật này thì cơ chế detour tự phá chính nó: `CustomPlanner` mù costmap nên mỗi nhịp
|
|
// `planner_frequency` nó trả lại đúng đường thẳng xuyên vật cản, ghi đè đường vòng vừa lập, rồi
|
|
// PathMonitor lại khai hoả — robot dừng-detour-chạy-dừng mỗi giây và ngân sách route cạn rất
|
|
// nhanh.
|
|
//
|
|
// Chỉ áp ở kControlling, nơi ĐANG có một plan để giữ. Ở kPlanning vẫn nhận plan bẩn như cũ:
|
|
// PathMonitor sẽ khai hoả ngay khi vào kControlling, nên mọi tình huống tuyến-bị-chắn đi qua đúng
|
|
// MỘT đường xử lý thay vì hai.
|
|
//
|
|
// Hệ quả đẹp: khi robot đã đi qua vật cản, plan thẳng của planner chính hết bị chắn nên được nhận
|
|
// lại — robot tự quay về đúng tuyến/NURBS của order, không cần cơ chế nào để "kết thúc detour".
|
|
if (state_machine_.state() == NavigationState::kControlling && !latest_plan_.empty() &&
|
|
planIsBlocked(result.plan, 0))
|
|
{
|
|
robot::log_warning_throttle(5.0, "[move_base2] a fresh plan runs into an obstacle; keeping the "
|
|
"current plan.\n");
|
|
planner_feedback_ = PlannerFeedback::kFailed;
|
|
return;
|
|
}
|
|
|
|
latest_plan_.swap(result.plan);
|
|
// Tuyến THAM CHIẾU của chặng = plan do PLANNER sinh, không phải plan đã bị recovery thay
|
|
// (contract 2026-08-05e). Detour nối lại vào nó nên robot tự quay về tuyến order thay vì trôi
|
|
// dần theo từng đường vòng, và `max_deviation` đo đúng hành lang mà fleet đã duyệt.
|
|
order_plan_ = latest_plan_;
|
|
planner_feedback_ = PlannerFeedback::kPlanReady;
|
|
}
|
|
|
|
void ControlLoop::resetPathMonitor()
|
|
{
|
|
path_blocked_ = false;
|
|
off_path_ = false;
|
|
has_last_path_check_ = false;
|
|
blocked_seen_ = false;
|
|
off_path_seen_ = false;
|
|
}
|
|
|
|
bool ControlLoop::planIsBlocked(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
|
std::size_t from_index) const
|
|
{
|
|
if (deps_.path_check == nullptr || !(config_.path_monitor.horizon > 0.0) || plan.empty())
|
|
{
|
|
return false;
|
|
}
|
|
|
|
PlanBlockResult result;
|
|
if (!deps_.path_check->checkPlan(plan, from_index, config_.path_monitor.horizon, result))
|
|
{
|
|
// Không kết luận được (thiếu TF/costmap). "Không biết" KHÔNG được suy thành "bẩn": làm vậy là
|
|
// robot dừng mỗi lần TF trễ một nhịp.
|
|
return false;
|
|
}
|
|
|
|
if (result.blocked)
|
|
{
|
|
last_block_distance_ = result.distance; // [m] chỉ để log; không tham gia quyết định.
|
|
}
|
|
return result.blocked && result.distance >= config_.path_monitor.min_detour_distance;
|
|
}
|
|
|
|
void ControlLoop::updatePathMonitor(const robot::Time& now,
|
|
const robot_geometry_msgs::PoseStamped& robot_pose,
|
|
bool pose_available, bool costmap_stale)
|
|
{
|
|
const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor;
|
|
|
|
// Cổng vào: chỉ giám sát khi thực sự đang bám một plan của một profile được phép, với dữ liệu còn
|
|
// dùng được. Thiếu bất kỳ điều kiện nào thì XOÁ luôn trạng thái debounce — nếu chỉ bỏ qua, chuỗi
|
|
// "đúng liên tục" sẽ được nối lại qua một quãng gián đoạn và `confirm_time` mất ý nghĩa.
|
|
const bool monitorable = cfg.enabled && deps_.path_check != nullptr && has_active_request_ &&
|
|
pose_available && !costmap_stale && !latest_plan_.empty() &&
|
|
state_machine_.state() == NavigationState::kControlling &&
|
|
cfg.monitors(active_request_.profile);
|
|
|
|
if (!monitorable)
|
|
{
|
|
resetPathMonitor();
|
|
return;
|
|
}
|
|
|
|
// Route rỗng = KHÔNG có đường xử lý cho trigger đó. Khai hoả trong tình trạng này là biến một cơ
|
|
// chế đang tắt thành ABORT tức thì: state machine thấy cờ, gọi escalateToRecovery, route cạn ngay
|
|
// từ phần tử đầu, và chặng chết ngay lần đầu thấy vật cản. Giám sát cái mà không ai xử lý được
|
|
// thì thà đừng giám sát — để `controller_patience` lo như trước khi có cơ chế này.
|
|
//
|
|
// Ba nút độc lập cho mỗi phép đo, cố ý: cờ riêng (`path_blocked_enabled`/`off_path_enabled`,
|
|
// 2026-08-06 — nói thẳng ý định thay vì đặt ngưỡng về 0), ngưỡng của chính nó, và route.
|
|
const bool blocked_route_ready = cfg.path_blocked_enabled &&
|
|
!config_.state_machine.recovery_routes.path_blocked.empty();
|
|
const bool off_path_route_ready = cfg.off_path_enabled &&
|
|
!config_.state_machine.recovery_routes.off_path.empty();
|
|
|
|
// Nhịp quét riêng: đọc vài chục ô costmap mỗi control cycle 30 Hz là phí, mà vật cản cũng không
|
|
// xuất hiện nhanh hơn chu kỳ cập nhật costmap (6 Hz).
|
|
if (has_last_path_check_ && (now - last_path_check_).toSec() < cfg.check_period)
|
|
{
|
|
return;
|
|
}
|
|
last_path_check_ = now;
|
|
has_last_path_check_ = true;
|
|
|
|
const std::size_t from = nearestIndex(latest_plan_, robot_pose);
|
|
|
|
// --- Phép đo 1: tuyến phía trước có bị chắn không -------------------------------------------
|
|
const bool blocked_now = blocked_route_ready && planIsBlocked(latest_plan_, from);
|
|
if (blocked_now)
|
|
{
|
|
if (!blocked_seen_)
|
|
{
|
|
blocked_since_ = now;
|
|
blocked_seen_ = true;
|
|
}
|
|
if (!path_blocked_ && (now - blocked_since_).toSec() >= cfg.confirm_time)
|
|
{
|
|
path_blocked_ = true;
|
|
robot::log_warning("[move_base2] PathMonitor: the path ahead is blocked at %.2f m (horizon "
|
|
"%.2f m) — stopping to plan a detour.\n",
|
|
last_block_distance_, cfg.horizon);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
blocked_seen_ = false;
|
|
path_blocked_ = false;
|
|
}
|
|
|
|
// --- Phép đo 2: robot đã lệch khỏi plan bao xa ----------------------------------------------
|
|
//
|
|
// Đo so với PLAN ĐANG CHẠY, không phải tuyến gốc của order: sau một lượt detour hợp lệ, plan đang
|
|
// chạy CHÍNH LÀ đường vòng và robot nằm trên nó, nên không khai hoả oan. Ràng buộc "lệch bao
|
|
// nhiêu so với tuyến fleet" là việc của `max_deviation` bên trong behavior detour.
|
|
const bool grace = has_last_plan_applied_ &&
|
|
(now - last_plan_applied_).toSec() < cfg.grace_after_new_plan;
|
|
|
|
if (off_path_route_ready && cfg.max_cross_track > 0.0 && !grace)
|
|
{
|
|
const double error = crossTrackError(latest_plan_, robot_pose); // [m]
|
|
if (error > cfg.max_cross_track)
|
|
{
|
|
if (!off_path_seen_)
|
|
{
|
|
off_path_since_ = now;
|
|
off_path_seen_ = true;
|
|
}
|
|
if (!off_path_ && (now - off_path_since_).toSec() >= cfg.confirm_time)
|
|
{
|
|
off_path_ = true;
|
|
robot::log_warning("[move_base2] PathMonitor: the robot is %.2f m off the plan (limit "
|
|
"%.2f m) — stopping.\n", error, cfg.max_cross_track);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
off_path_seen_ = false;
|
|
off_path_ = false;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
off_path_seen_ = false;
|
|
off_path_ = false;
|
|
}
|
|
}
|
|
|
|
void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
|
|
{
|
|
candidate = robot_geometry_msgs::Twist();
|
|
|
|
// 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;
|
|
return;
|
|
}
|
|
|
|
robot_geometry_msgs::Twist cmd;
|
|
if (deps_.controller->computeVelocityCommands(cmd))
|
|
{
|
|
controller_feedback_ = ControllerFeedback::kCommandValid;
|
|
candidate = cmd;
|
|
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: PathMonitor cần nó, mà monitor
|
|
// phải chạy xong trước state machine. Vẫn là một lời gọi mỗi cycle, chỉ đổi vị trí.
|
|
const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr &&
|
|
!deps_.costmap_status->isCurrent();
|
|
|
|
// --- 1b. Giám sát tuyến ---------------------------------------------------------------------
|
|
// Chạy TRƯỚC state machine: hai cờ nó sinh ra là dữ liệu vào của state machine ngay cycle này.
|
|
updatePathMonitor(now, robot_pose, pose_available, costmap_stale);
|
|
|
|
// --- 2. State machine -----------------------------------------------------------------------
|
|
StateMachineInput input;
|
|
input.now = now;
|
|
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.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 = arbiter_.stopped();
|
|
input.travelled_since_oscillation_reset = travelled;
|
|
input.path_blocked = path_blocked_;
|
|
input.off_path = off_path_;
|
|
|
|
// Cùng một chỉ số dùng cho cả cycle khởi động recovery lẫn các cycle tick: state machine chỉ tăng
|
|
// chỉ số khi behavior kết thúc, nên `nextRecoveryIndex()` chính là behavior sắp chạy hoặc đang
|
|
// 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");
|
|
}
|
|
}
|
|
|
|
// 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;
|
|
|
|
// 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)
|
|
{
|
|
robot::log_info("[move_base2] Goal received (mission %llu): x=%.3f y=%.3f 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,
|
|
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;
|
|
|
|
if (config_.debug_plan)
|
|
{
|
|
robot::log_info("[move_base2][debug] controller accepted plan with %zu pose(s); "
|
|
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
|
|
latest_plan_.size(), latest_plan_.front().pose.position.x,
|
|
latest_plan_.front().pose.position.y,
|
|
latest_plan_.front().header.frame_id.c_str(),
|
|
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
|
|
latest_plan_.back().header.frame_id.c_str());
|
|
}
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
robot_geometry_msgs::Twist candidate;
|
|
|
|
if (output.start_recovery)
|
|
{
|
|
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;
|
|
}
|
|
}
|
|
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;
|
|
break;
|
|
case RecoveryTick::Status::kFailed:
|
|
recovery_feedback_ = RecoveryFeedback::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.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::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::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);
|
|
}
|
|
}
|
|
// else if (controller_feedback_ == ControllerFeedback::kCommandValid)
|
|
// {
|
|
// robot::log_info_throttle(kDebugControlLogThrottle,
|
|
// "[move_base2][debug] controller command valid: v=%.3f wz=%.3f.\n",
|
|
// candidate.linear.x, candidate.angular.z);
|
|
// }
|
|
}
|
|
|
|
// 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 (chưa có planner, pose hỏng...). Coi như một lượt hỏng để đồng hồ
|
|
// kiên nhẫn tiếp tục chạy, thay vì đứng im ở kPlanning vô hạn. Riêng replan NỀN không khởi
|
|
// động được thì bỏ qua — plan cũ vẫn hiệu lực, nhịp sau thử lại.
|
|
planner_feedback_ = PlannerFeedback::kFailed;
|
|
}
|
|
}
|
|
|
|
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
|
|
arbiter_.arbitrate(costmap_stale ? VelocitySource::kNone : output.velocity_source, candidate, dt);
|
|
|
|
// --- 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;
|
|
}
|
|
|
|
// 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
|