Root cause (from a C++ host log, 2026-09-11): cancel during PLANNING only set a discard flag on the planner thread, which ran to allocated_time before CANCELLED could be reported; a queued next mission landed on a still-busy planner and timed out too. Same class of bug existed for pause, recovery, and implicitly for a legitimate ABORTED read while a component was still unwinding. Full audit, decisions, and phased design in docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md; old-vs-new behaviour per state in docs/LIFECYCLE_BEHAVIOUR_MATRIX.md. Runtime quiescence, not just "command sent": - kPausing (new state) mirrors kCancelling: PAUSED/CANCELLED is only entered once planner and recovery are idle, the action reports terminal, and the robot is stopped per odometry (robot_stopped, stopped_measured_linear/ angular_eps) — not merely "the command we sent was zero". settle_timeout bounds the wait; exceeding it still finishes but logs an ungated error naming which component was still busy, so a plugin that doesn't honour cancel/pause is visible instead of silently swallowed. - PlannerRunner::running_planner_ (new): the instance the planner thread is actually inside makePlan() with, tracked separately from active_ — active_ can already point at a different instance after swapPlanner() while the old attempt is still running. cancelPlan(), swapPlanner() (when a job is running_ or only pending_ and not yet picked up), and the destructor all preempt through this pointer now; the old code preempted through active_ and could silently preempt the wrong (idle) instance after a profile swap. - ComponentStatusBoard + per-component ComponentPhase (idle/busy/stopping/ paused/hung), read by PlannerRunner, RecoveryRunner, ActionRunner and ControlLoop instead of ad hoc bools — this is what makes "did everything actually stop" answerable at all, and what the new Watchdog thread reads to flag a component busy-without-progress as hung (logged once at the edge) without the control loop needing to detect its own stall. - Resume: PLANNING replans from the current pose. CONTROLLING re-issues setPlan() with the plan already in hand (decided: setPlan again, not a fresh plan) — the local planner needs nothing else since it already runs once per control cycle; a fresh plan on resume was considered and rejected as unnecessary work for a plan that's still valid. - Command-to-zero on cancel/pause stays immediate (no deceleration ramp) — existing VelocityArbiter behaviour, left as is per a scoped decision. Depends on: Test/sbpl (bd89924), pnkx_nav_core (2b0993b, robot_nav_core:: Preemptable + component_status_probe.h), Test/sbpl_lattice_planner (7456e99), Test/recovery_core (254c7fc, onCancelRequested + ABI guard), Test/ sbpl_recovery (ea79686, worker-thread cancel), Test/action_core (669c3f7, pause/resume + kCancelled), Test/dock_pattern_action (cc1ea74). Verified: 13 gtest binaries / 528 tests, 0 failures. Runtime on the dev machine (Gazebo + real ROS host + VDA5050 over MQTT), 6 scenarios — cancel during PLANNING, pause/resume during PLANNING and CONTROLLING (incl. submit-while-still-winding-down), pause-then-cancel during PLANNING and CONTROLLING: no ABORTED/RECOVERING in any run, preempt lands within hundredths of a millisecond of entering CANCELLING/PAUSING, PAUSED/CANCELLED only reported once the robot is actually stopped per odometry. Full numbers in the plan doc section 6. Excluded from this commit (pre-existing, unrelated): config/runtime/recovery_behaviors_params.yaml (allocated_time 1.0->2.0, SBPLDetourPlanner tuning predating this work). Not yet done (see plan doc "Trạng thái"): config tuning (phase 0, pending per a scoping decision); runtime scenarios for cancel mid-detour and a 30 s pause mid-action; commit to rb_ws is a separate step, not done here. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
637 lines
23 KiB
C++
637 lines
23 KiB
C++
/*********************************************************************
|
|
*
|
|
* Software License Agreement (BSD License)
|
|
*
|
|
* move_base2 — cài đặt NavigationRuntime.
|
|
*
|
|
* Author: DuongTD
|
|
*********************************************************************/
|
|
#include <move_base2/navigation_runtime.h>
|
|
|
|
#include <algorithm>
|
|
|
|
#include <limits>
|
|
|
|
#include <cmath>
|
|
|
|
#include <move_base2/io/sensor_store_types.h>
|
|
|
|
#include <exception>
|
|
|
|
#include <boost/thread/locks.hpp>
|
|
|
|
#include <robot/node_handle.h>
|
|
#include <robot/robot.h>
|
|
#include <robot_costmap_2d/costmap_2d.h>
|
|
#include <robot_nav_2d_utils/conversions.h>
|
|
#include <tf3/buffer_core.h>
|
|
|
|
namespace move_base2
|
|
{
|
|
|
|
bool CostmapPosePort::lookupPose(const std::string& frame,
|
|
robot_geometry_msgs::PoseStamped& pose) const
|
|
{
|
|
if (!tf_ || costmap_ == nullptr || frame.empty())
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// Quy về global frame CỦA COSTMAP, không phải một frame cố định: planner làm việc trên đúng lưới
|
|
// đó. Trả pose ở hệ khác là planner nhận toạ độ vô nghĩa mà không tầng nào báo lỗi — đúng lỗi
|
|
// "pose start sai frame" đã xảy ra ngày 2026-07-29.
|
|
const std::string& target = costmap_->getGlobalFrameID();
|
|
|
|
try
|
|
{
|
|
const tf3::TransformStampedMsg tf = tf_->lookupTransform(target, frame, tf3::Time());
|
|
|
|
pose.header.stamp = robot::Time(tf.header.stamp.sec, tf.header.stamp.nsec);
|
|
pose.header.frame_id = target;
|
|
pose.pose.position.x = tf.transform.translation.x;
|
|
pose.pose.position.y = tf.transform.translation.y;
|
|
pose.pose.position.z = tf.transform.translation.z;
|
|
pose.pose.orientation.x = tf.transform.rotation.x;
|
|
pose.pose.orientation.y = tf.transform.rotation.y;
|
|
pose.pose.orientation.z = tf.transform.rotation.z;
|
|
pose.pose.orientation.w = tf.transform.rotation.w;
|
|
return true;
|
|
}
|
|
catch (const std::exception& ex)
|
|
{
|
|
robot::log_warning("[move_base2] cannot resolve frame '%s' in '%s': %s\n", frame.c_str(),
|
|
target.c_str(), ex.what());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// ================================================================================================
|
|
// CostmapEnvironment
|
|
// ================================================================================================
|
|
|
|
namespace
|
|
{
|
|
double yawOfPose(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));
|
|
}
|
|
} // namespace
|
|
|
|
robot_costmap_2d::Costmap2D* CostmapEnvironment::gridForRead(bool& live) const
|
|
{
|
|
live = true;
|
|
if (costmap_ == nullptr)
|
|
{
|
|
return nullptr;
|
|
}
|
|
robot_costmap_2d::Costmap2D* grid = costmap_->getCostmapForRead();
|
|
live = (grid == costmap_->getCostmap()); // snapshot tắt -> trả lưới sống -> phải khoá
|
|
return grid;
|
|
}
|
|
|
|
void CostmapEnvironment::refresh()
|
|
{
|
|
if (costmap_ != nullptr)
|
|
{
|
|
costmap_->refreshSnapshot(); // no-op khi snapshot tắt
|
|
}
|
|
}
|
|
|
|
bool CostmapEnvironment::sampleGeometry(const EnvGeometryRequest& r, EnvGeometry& out)
|
|
{
|
|
out = EnvGeometry();
|
|
if (costmap_ == nullptr || !tf_ || r.plan == nullptr || r.sampling == nullptr || r.plan->size() < 2 ||
|
|
r.from_index >= r.plan->size())
|
|
{
|
|
return false;
|
|
}
|
|
bool live = true;
|
|
robot_costmap_2d::Costmap2D* grid = gridForRead(live);
|
|
if (grid == nullptr)
|
|
{
|
|
return false;
|
|
}
|
|
const std::string& grid_frame = costmap_->getGlobalFrameID();
|
|
PlanarTransform plan_to_grid;
|
|
PlanarTransform pose_to_grid;
|
|
if (!planarTransform(*tf_, (*r.plan)[r.from_index].header.frame_id, grid_frame, plan_to_grid) ||
|
|
!planarTransform(*tf_, r.robot_pose.header.frame_id, grid_frame, pose_to_grid))
|
|
{
|
|
return false; // không quy đổi được frame: không biết, không đoán
|
|
}
|
|
double gx = 0.0;
|
|
double gy = 0.0;
|
|
pose_to_grid.apply(r.robot_pose.pose.position.x, r.robot_pose.pose.position.y, gx, gy);
|
|
const double gyaw = yawOfPose(r.robot_pose) + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw);
|
|
|
|
// Bán kính tâm = inscribed của thân, KHÔNG đệm: cùng biên với SBPL (luật R2).
|
|
const double free_radius = std::min(r.side, std::min(r.front, r.rear));
|
|
out.free_radius = free_radius;
|
|
|
|
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()), boost::defer_lock);
|
|
if (live)
|
|
{
|
|
lock.lock();
|
|
}
|
|
if (!analyzeGrid(*grid, static_cast<unsigned char>(r.sampling->lethal_threshold), free_radius, scratch_))
|
|
{
|
|
return false;
|
|
}
|
|
out.edt_body_min = bodyClearance(scratch_, gx, gy, gyaw, r.front, r.rear, r.side);
|
|
CostToGoParams cost_params;
|
|
cost_params.target_backoff = r.sampling->target_backoff;
|
|
cost_params.robot_snap = r.sampling->robot_snap;
|
|
cost_params.exit_ahead = r.sampling->exit_ahead;
|
|
cost_params.target_snap = r.sampling->target_snap;
|
|
out.cost = costToGo(*r.plan, r.from_index, gx, gy, cost_params, plan_to_grid, scratch_);
|
|
CorridorParams corridor_params;
|
|
corridor_params.horizon = r.sampling->horizon;
|
|
corridor_params.body_width = 2.0 * r.side;
|
|
corridor_params.margin = r.sampling->corridor_margin;
|
|
corridor_params.side_cap = r.sampling->corridor_cap;
|
|
out.corridor = scanCorridor(*r.plan, r.from_index, corridor_params, plan_to_grid, scratch_);
|
|
out.valid = true;
|
|
return true;
|
|
}
|
|
|
|
bool CostmapEnvironment::sweepTrajectory(const EnvTrajectoryRequest& r, SweepResult& out,
|
|
bool& used_local_plan)
|
|
{
|
|
out = SweepResult();
|
|
used_local_plan = false;
|
|
if (costmap_ == nullptr || !tf_ || r.sampling == nullptr)
|
|
{
|
|
return false;
|
|
}
|
|
bool live = true;
|
|
robot_costmap_2d::Costmap2D* grid = gridForRead(live);
|
|
if (grid == nullptr)
|
|
{
|
|
return false;
|
|
}
|
|
const std::string& grid_frame = costmap_->getGlobalFrameID();
|
|
PlanarTransform pose_to_grid;
|
|
if (!planarTransform(*tf_, r.robot_pose.header.frame_id, grid_frame, pose_to_grid))
|
|
{
|
|
return false;
|
|
}
|
|
double gx = 0.0;
|
|
double gy = 0.0;
|
|
pose_to_grid.apply(r.robot_pose.pose.position.x, r.robot_pose.pose.position.y, gx, gy);
|
|
const double gyaw = yawOfPose(r.robot_pose) + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw);
|
|
|
|
SweepParams params;
|
|
params.front = r.front;
|
|
params.rear = r.rear;
|
|
params.side = r.side;
|
|
params.padding = r.sampling->padding;
|
|
params.lookahead = r.sampling->contact_lookahead;
|
|
params.lethal_threshold = static_cast<unsigned char>(r.sampling->lethal_threshold);
|
|
|
|
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()), boost::defer_lock);
|
|
if (live)
|
|
{
|
|
lock.lock();
|
|
}
|
|
|
|
// 1) Quỹ đạo thật của local planner, quy về frame lưới.
|
|
if (r.sampling->use_local_plan != "false" && r.local_plan != nullptr && r.local_plan->poses.size() >= 2)
|
|
{
|
|
PlanarTransform traj_to_grid;
|
|
if (planarTransform(*tf_, r.local_plan->header.frame_id, grid_frame, traj_to_grid))
|
|
{
|
|
const double dyaw = std::atan2(traj_to_grid.sin_yaw, traj_to_grid.cos_yaw);
|
|
traj_scratch_.clear();
|
|
traj_scratch_.reserve(r.local_plan->poses.size());
|
|
for (const auto& p : r.local_plan->poses)
|
|
{
|
|
robot_geometry_msgs::PoseStamped ps;
|
|
traj_to_grid.apply(p.pose.x, p.pose.y, ps.pose.position.x, ps.pose.position.y);
|
|
const double yaw = p.pose.theta + dyaw;
|
|
ps.pose.orientation.z = std::sin(0.5 * yaw);
|
|
ps.pose.orientation.w = std::cos(0.5 * yaw);
|
|
traj_scratch_.push_back(ps);
|
|
}
|
|
out = move_base2::sweepTrajectory(traj_scratch_, gx, gy, gyaw, r.sampling->local_plan_start_tol,
|
|
params, *grid, scratch_);
|
|
if (out.conclusive)
|
|
{
|
|
used_local_plan = true;
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
if (r.sampling->use_local_plan == "true")
|
|
{
|
|
return false; // ép dùng quỹ đạo mà không có -> không kết luận
|
|
}
|
|
// 2) Cung (v, omega) không đổi — cùng hình học với guard cũ, nhưng cùng bộ dò với quỹ đạo thật.
|
|
if (std::fabs(r.v) < 1e-3)
|
|
{
|
|
out.conclusive = true; // đứng yên / xoay tại chỗ: không có chuyển động tịnh tiến để dò
|
|
return true;
|
|
}
|
|
const double res = grid->getResolution();
|
|
const double step = res > 0.0 ? res : 0.05;
|
|
const double direction = r.v < 0.0 ? -1.0 : 1.0;
|
|
const double kappa = r.omega / r.v;
|
|
traj_scratch_.clear();
|
|
const int n = static_cast<int>(std::ceil(r.sampling->contact_lookahead / step));
|
|
traj_scratch_.reserve(static_cast<std::size_t>(n) + 1);
|
|
for (int i = 0; i <= n; ++i)
|
|
{
|
|
const double s = direction * step * i;
|
|
robot_geometry_msgs::PoseStamped ps;
|
|
double yaw = gyaw;
|
|
if (std::fabs(kappa) < 1e-6)
|
|
{
|
|
ps.pose.position.x = gx + s * std::cos(gyaw);
|
|
ps.pose.position.y = gy + s * std::sin(gyaw);
|
|
}
|
|
else
|
|
{
|
|
yaw = gyaw + kappa * s;
|
|
ps.pose.position.x = gx + (std::sin(yaw) - std::sin(gyaw)) / kappa;
|
|
ps.pose.position.y = gy - (std::cos(yaw) - std::cos(gyaw)) / kappa;
|
|
}
|
|
ps.pose.orientation.z = std::sin(0.5 * yaw);
|
|
ps.pose.orientation.w = std::cos(0.5 * yaw);
|
|
traj_scratch_.push_back(ps);
|
|
}
|
|
out = move_base2::sweepTrajectory(traj_scratch_, gx, gy, gyaw, 1.0, params, *grid, scratch_);
|
|
return out.conclusive;
|
|
}
|
|
|
|
bool CostmapEnvironment::robotBodyExtents(double& front, double& rear, double& side) const
|
|
{
|
|
if (costmap_ == nullptr)
|
|
{
|
|
return false;
|
|
}
|
|
const std::vector<robot_geometry_msgs::Point>& fp = costmap_->getUnpaddedRobotFootprint();
|
|
if (fp.size() < 3)
|
|
{
|
|
return false;
|
|
}
|
|
double max_x = std::numeric_limits<double>::lowest();
|
|
double min_x = std::numeric_limits<double>::max();
|
|
double max_abs_y = 0.0;
|
|
for (const robot_geometry_msgs::Point& p : fp)
|
|
{
|
|
if (!std::isfinite(p.x) || !std::isfinite(p.y))
|
|
{
|
|
return false;
|
|
}
|
|
max_x = std::max(max_x, p.x);
|
|
min_x = std::min(min_x, p.x);
|
|
max_abs_y = std::max(max_abs_y, std::fabs(p.y));
|
|
}
|
|
if (!(max_x > 0.0) || !(min_x < 0.0) || !(max_abs_y > 0.0))
|
|
{
|
|
return false;
|
|
}
|
|
front = max_x;
|
|
rear = -min_x;
|
|
side = max_abs_y;
|
|
return true;
|
|
}
|
|
|
|
NavigationRuntime::NavigationRuntime() = default;
|
|
|
|
NavigationRuntime::~NavigationRuntime()
|
|
{
|
|
// Dừng thread cập nhật costmap trước khi bất kỳ thành viên nào bị huỷ: các runner giữ con trỏ tới
|
|
// costmap, và costmap giữ thread đang chạy qua chuỗi layer.
|
|
stop();
|
|
}
|
|
|
|
bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf,
|
|
std::string& error)
|
|
{
|
|
if (built_ || costmapsReady())
|
|
{
|
|
error = "NavigationRuntime::buildCostmaps() called twice";
|
|
return false;
|
|
}
|
|
|
|
if (!tf)
|
|
{
|
|
error = "NavigationRuntime needs a non-null TF buffer";
|
|
return false;
|
|
}
|
|
|
|
tf_ = tf;
|
|
|
|
// --- 1. Config ---------------------------------------------------------------------------------
|
|
//
|
|
// Đăng ký kiểu message riêng của gói này TRƯỚC khi đọc config: `data_type: OccupancyGrid` trong
|
|
// khối `sensor_store` sẽ bị từ chối là "unknown" nếu bảng tên chưa có nó.
|
|
registerSensorStoreTypes();
|
|
|
|
robot::NodeHandle root_nh("~");
|
|
config_ = MoveBase2Config::load(root_nh);
|
|
|
|
// --- 2. Costmap --------------------------------------------------------------------------------
|
|
//
|
|
// Dựng nhưng CHƯA start: thread cập nhật chạy trong lúc planner chưa nạp xong là cửa sổ để mọi
|
|
// thứ chạm vào nhau ở trạng thái nửa vời. start() nằm ở hàm riêng, gọi sau khi lắp xong.
|
|
// Telemetry dựng NGAY SAU config và TRƯỚC costmap: costmap tạo thread cập nhật ngay trong
|
|
// constructor của nó và không phơi tid ra, nên cách duy nhất gọi đúng tên thread đó mà không phải
|
|
// sửa gói costmap là chụp danh sách tid quanh lúc dựng.
|
|
stats_.reset(new RuntimeStats(config_.runtime_stats_period));
|
|
|
|
try
|
|
{
|
|
stats_->beginThreadCapture();
|
|
global_costmap_.reset(new robot_costmap_2d::Costmap2DROBOT("global_costmap", *tf_));
|
|
stats_->endThreadCapture("costmap/global");
|
|
|
|
stats_->beginThreadCapture();
|
|
local_costmap_.reset(new robot_costmap_2d::Costmap2DROBOT("local_costmap", *tf_));
|
|
stats_->endThreadCapture("costmap/local");
|
|
}
|
|
catch (const std::exception& ex)
|
|
{
|
|
error = std::string("could not build costmap: ") + ex.what();
|
|
global_costmap_.reset();
|
|
local_costmap_.reset();
|
|
return false;
|
|
}
|
|
|
|
global_costmap_->pause();
|
|
local_costmap_->pause();
|
|
|
|
// Thread update chưa chạy ở pha này, nên chụp footprint config ban đầu ở đây an toàn. Lưu riêng
|
|
// hai bản vì runtime phải rollback cả cặp nếu controller không nhận được footprint mới.
|
|
global_footprint_ = global_costmap_->getUnpaddedRobotFootprint();
|
|
local_footprint_ = local_costmap_->getUnpaddedRobotFootprint();
|
|
|
|
// Hai nguồn pose, khác frame — xem doc của thành viên. Bản cũ cũng vậy: `makePlan` lấy start từ
|
|
// `planner_costmap_robot_` (map), còn `LocalPlannerAdapter` lấy pose từ costmap local (odom).
|
|
global_pose_.setCostmap(global_costmap_.get());
|
|
local_pose_.setCostmap(local_costmap_.get());
|
|
|
|
// Chặng có `goal_frame` tra TF qua cổng pose. Chỉ cổng GLOBAL cần: goal của chặng luôn được quy
|
|
// về frame của costmap lập plan.
|
|
global_pose_.setTf(tf_);
|
|
|
|
// Costmap ĐIỀU KHIỂN (local) là nguồn của guard "không đi mù" — xem doc của CostmapStatusAdapter.
|
|
costmap_status_.setCostmap(local_costmap_.get());
|
|
|
|
// EnvMonitor đọc costmap local — cùng lưới mà detour lập đường vòng trên đó; TF để quy plan (map) và
|
|
// pose về frame lưới.
|
|
environment_.setCostmap(local_costmap_.get());
|
|
controller_.setSnapshotRefreshedByLoop(true); // ControlLoop làm mới snapshot một lần đầu cycle (P0b)
|
|
environment_.setTf(tf_);
|
|
|
|
// Gắn ngay: host có thể hỏi dữ liệu hiển thị bất cứ lúc nào sau initialize(), kể cả trước khi
|
|
// costmap có nội dung. Exporter tự trả về "chưa có gì" thay vì lưới rỗng.
|
|
global_exporter_.attach(global_costmap_.get(), config_.global_frame);
|
|
local_exporter_.attach(local_costmap_.get(), local_costmap_->getGlobalFrameID());
|
|
|
|
// Cả hai exporter dùng chung một tên đoạn công việc: bảng hiện TỔNG chi phí kết xuất cho rviz.
|
|
// Tách riêng global/local không nói thêm được gì — host gọi chúng từ các ros::Timer khác nhau và
|
|
// câu hỏi cần trả lời là "hiển thị tốn bao nhiêu", không phải "lưới nào tốn hơn".
|
|
global_exporter_.attachTelemetry(stats_.get());
|
|
local_exporter_.attachTelemetry(stats_.get());
|
|
|
|
return true;
|
|
}
|
|
|
|
bool NavigationRuntime::buildRunners(std::string& error)
|
|
{
|
|
if (built_)
|
|
{
|
|
error = "NavigationRuntime::buildRunners() called twice";
|
|
return false;
|
|
}
|
|
if (!costmapsReady())
|
|
{
|
|
error = "buildRunners() called before buildCostmaps()";
|
|
return false;
|
|
}
|
|
|
|
robot::NodeHandle root_nh("~");
|
|
|
|
// --- 3. Planner và controller ------------------------------------------------------------------
|
|
//
|
|
// Gắn telemetry TRƯỚC configure: PlannerRunner khởi động thread lập plan ngay trong configure(),
|
|
// và chính thread đó tự đăng ký nhãn của mình khi bắt đầu chạy.
|
|
planner_.attachStats(stats_.get());
|
|
controller_.attachStats(stats_.get());
|
|
planner_.attachStatusBoard(&components_);
|
|
recovery_.attachStatusBoard(&components_);
|
|
action_.attachStatusBoard(&components_);
|
|
|
|
// Trước configure(): planner nạp trong configure() và có thể muốn đọc cảm biến ngay trong
|
|
// initialize() của nó.
|
|
controller_.setSensorReader(sensors_);
|
|
|
|
if (!planner_.configure(root_nh, global_costmap_.get(), config_.position.global_planner_name,
|
|
error))
|
|
{
|
|
global_costmap_.reset();
|
|
local_costmap_.reset();
|
|
return false;
|
|
}
|
|
|
|
if (!controller_.configure(root_nh, tf_, local_costmap_.get(), &local_pose_,
|
|
config_.position.local_planner_name, error))
|
|
{
|
|
global_costmap_.reset();
|
|
local_costmap_.reset();
|
|
return false;
|
|
}
|
|
|
|
// --- 4. Recovery -------------------------------------------------------------------------------
|
|
RecoveryRunner::Deps recovery_deps;
|
|
recovery_deps.clock = &clock_;
|
|
recovery_deps.pose = &local_pose_;
|
|
recovery_deps.local_costmap = local_costmap_.get();
|
|
recovery_deps.global_costmap = global_costmap_.get();
|
|
// Behavior họ path (DetourPathRecovery) lập đường vòng trên local costmap (frame odom) trong khi
|
|
// plan ở frame map — cần TF để quy đổi hai chiều.
|
|
recovery_deps.tf = tf_.get();
|
|
recovery_.setDeps(recovery_deps);
|
|
recovery_.setNamespace(config_.recovery_namespace);
|
|
|
|
if (!recovery_.configure(root_nh))
|
|
{
|
|
// Không dừng lại: một behavior hỏng không nên xoá sạch các đường phục hồi còn lại.
|
|
// `behaviorCount()` bên dưới phản ánh số nạp được THẬT, và `validate()` sẽ chặn nếu con số đó
|
|
// bằng 0 trong khi recovery vẫn đang bật.
|
|
robot::log_warning("[move_base2] NavigationRuntime: a recovery behavior failed to load; "
|
|
"continuing with the remaining %zu behavior(s).\n",
|
|
recovery_.behaviorCount());
|
|
}
|
|
|
|
// `recovery_enabled: false` hợp lệ ngay cả khi registry rỗng. Khi đó để StateMachineConfig tự
|
|
// validate cặp enabled/count bên dưới; không được ép parse route của một subsystem đã tắt.
|
|
if (recovery_.behaviorCount() > 0)
|
|
{
|
|
std::string recovery_routes_error;
|
|
if (!recovery_.configureRoutes(root_nh, recovery_routes_error))
|
|
{
|
|
error = "invalid recovery routes: " + recovery_routes_error;
|
|
return false;
|
|
}
|
|
config_.state_machine.recovery_routes = recovery_.routes();
|
|
}
|
|
|
|
// Ràng buộc thứ tự khởi tạo — xem doc của lớp. Con số này KHÔNG đến từ YAML.
|
|
config_.state_machine.recovery_behavior_count = recovery_.behaviorCount();
|
|
|
|
// --- 5. Action ---------------------------------------------------------------------------------
|
|
action_.setClock(&clock_);
|
|
action_.setNamespace(config_.action_namespace);
|
|
|
|
// Handler dò cần TF để đọc frame thô và GHI lại frame đã lọc — xem action_core::ActionContext.
|
|
action_core::ActionContext action_ctx;
|
|
action_ctx.tf = tf_.get();
|
|
action_ctx.global_frame = global_costmap_->getGlobalFrameID();
|
|
action_ctx.robot_base_frame = config_.robot_base_frame;
|
|
// Null khi host không cấp kho — handler nào cần dữ liệu thô tự từ chối ở configure().
|
|
action_ctx.sensors = sensors_;
|
|
action_.setContext(action_ctx);
|
|
|
|
if (!action_.configure(root_nh))
|
|
{
|
|
robot::log_warning("[move_base2] NavigationRuntime: an action handler failed to load; "
|
|
"continuing with the remaining %zu handler(s).\n", action_.handlerCount());
|
|
}
|
|
|
|
// --- 6. Mission layer --------------------------------------------------------------------------
|
|
//
|
|
// Mission layer luôn được dựng (2026-09-06, bỏ khoá `mission_layer_enabled`). Không chặn boot:
|
|
// layer hỏng thì navigation vẫn phải chạy được, nhưng phải LOG rõ — hai trạng thái này cho hai
|
|
// hành vi khác hẳn nhau với cùng một order: cắt thành chặng, hay đi thẳng xuống như một goal.
|
|
std::string mission_error;
|
|
if (mission_layer_.configure(root_nh, config_.mission_namespace, mission_error))
|
|
{
|
|
mission_layer_.attach(mission_);
|
|
robot::log_info("[move_base2] NavigationRuntime: mission layer ready (%zu source(s)) — "
|
|
"VDA5050 orders are split into legs.\n", mission_layer_.sourceCount());
|
|
}
|
|
else
|
|
{
|
|
robot::log_warning("[move_base2] NavigationRuntime: mission layer NOT started — %s. Orders "
|
|
"fall back to the direct path (one goal per order, no leg queue, no "
|
|
"released/orderUpdateId handling).\n", mission_error.c_str());
|
|
}
|
|
|
|
// --- 7. Kiểm cấu hình sau cùng -----------------------------------------------------------------
|
|
if (!config_.validate(error))
|
|
{
|
|
global_costmap_.reset();
|
|
local_costmap_.reset();
|
|
return false;
|
|
}
|
|
|
|
robot::log_info("[move_base2] NavigationRuntime built:\n%s", config_.describe().c_str());
|
|
|
|
built_ = true;
|
|
return true;
|
|
}
|
|
|
|
void NavigationRuntime::start()
|
|
{
|
|
if (!built_)
|
|
{
|
|
return;
|
|
}
|
|
global_costmap_->start();
|
|
local_costmap_->start();
|
|
|
|
// Bridge trước layer: executor của layer có thể dispatch ngay ở lần đánh thức đầu tiên, và bridge
|
|
// TỪ CHỐI mission khi chưa start (có chủ đích — mission layer phải biết chặng không được nhận).
|
|
mission_.start();
|
|
mission_layer_.start();
|
|
}
|
|
|
|
void NavigationRuntime::stop()
|
|
{
|
|
// Ngược chiều dòng dữ liệu: dừng nguồn sinh chặng trước, rồi mới đóng bridge.
|
|
mission_layer_.stop();
|
|
mission_.stop();
|
|
if (local_costmap_)
|
|
{
|
|
local_costmap_->stop();
|
|
}
|
|
if (global_costmap_)
|
|
{
|
|
global_costmap_->stop();
|
|
}
|
|
}
|
|
|
|
bool NavigationRuntime::setRobotFootprint(
|
|
const std::vector<robot_geometry_msgs::Point>& footprint)
|
|
{
|
|
if (!costmapsReady())
|
|
{
|
|
robot::log_error("[move_base2] NavigationRuntime: cannot apply a footprint before both "
|
|
"costmaps exist.\n");
|
|
return false;
|
|
}
|
|
|
|
// Bản move_base cũ làm đúng hai lời gọi này. Không dùng getCostmap() chung vì mỗi wrapper sở hữu
|
|
// padded footprint và phát onFootprintChanged() xuống layer riêng của nó.
|
|
global_costmap_->setUnpaddedRobotFootprint(footprint);
|
|
local_costmap_->setUnpaddedRobotFootprint(footprint);
|
|
|
|
// Đây là pha costmap -> runner: chưa có local planner nào để refresh. Nhờ áp footprint tại đây,
|
|
// instance planner đầu tiên được dựng phía dưới sẽ snapshot đúng hình robot và không phải dựng
|
|
// lại ngay sau startup.
|
|
if (!built_)
|
|
{
|
|
global_footprint_ = footprint;
|
|
local_footprint_ = footprint;
|
|
robot::log_info("[move_base2] NavigationRuntime: applied initial footprint (%zu point(s)) "
|
|
"before planner initialization.\n", footprint.size());
|
|
return true;
|
|
}
|
|
|
|
// HybridController (và nhiều planner) snapshot footprint trong initialize(). Recreate instance
|
|
// giữ ABI robot_nav_core2 ổn định với plugin .so cũ, đồng thời nạp lại plan đang chạy.
|
|
if (!controller_.refreshActivePlanner())
|
|
{
|
|
// Controller cũ vẫn giữ footprint cũ trong cache. Khôi phục cả hai costmap trước khi trả lỗi
|
|
// để không tạo tình trạng global/local/controller dùng ba hình robot khác nhau.
|
|
global_costmap_->setUnpaddedRobotFootprint(global_footprint_);
|
|
local_costmap_->setUnpaddedRobotFootprint(local_footprint_);
|
|
robot::log_error("[move_base2] NavigationRuntime: local planner cache was not refreshed "
|
|
"after the footprint changed; both costmaps were rolled back.\n");
|
|
return false;
|
|
}
|
|
|
|
global_footprint_ = footprint;
|
|
local_footprint_ = footprint;
|
|
|
|
robot::log_info("[move_base2] NavigationRuntime: propagated footprint (%zu point(s)) to "
|
|
"global/local costmaps.\n", footprint.size());
|
|
return true;
|
|
}
|
|
|
|
ControlLoopDeps NavigationRuntime::deps()
|
|
{
|
|
ControlLoopDeps deps;
|
|
if (!built_)
|
|
{
|
|
return deps;
|
|
}
|
|
|
|
deps.clock = &clock_;
|
|
deps.pose = &global_pose_; // planner start + chống quẩn + pose báo về host: frame `map`
|
|
deps.planner = &planner_;
|
|
deps.controller = &controller_;
|
|
deps.recovery = &recovery_;
|
|
deps.mission = &mission_;
|
|
deps.action = &action_;
|
|
deps.costmap_status = &costmap_status_;
|
|
deps.environment = &environment_;
|
|
deps.components = &components_;
|
|
return deps;
|
|
}
|
|
|
|
} // namespace move_base2
|