418 lines
16 KiB
C++
418 lines
16 KiB
C++
/*********************************************************************
|
|
*
|
|
* Software License Agreement (BSD License)
|
|
*
|
|
* move_base2 — cài đặt NavigationRuntime.
|
|
*
|
|
* Author: DuongTD
|
|
*********************************************************************/
|
|
#include <move_base2/navigation_runtime.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;
|
|
}
|
|
}
|
|
|
|
bool CostmapPathCheck::checkPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
|
std::size_t from_index, double horizon,
|
|
PlanBlockResult& out) const
|
|
{
|
|
if (costmap_ == nullptr || !tf_ || plan.empty() || from_index >= plan.size())
|
|
{
|
|
return false;
|
|
}
|
|
|
|
robot_costmap_2d::Costmap2D* grid = costmap_->getCostmap();
|
|
if (grid == nullptr)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
PlanarTransform plan_to_grid;
|
|
if (!planarTransform(*tf_, plan[from_index].header.frame_id, costmap_->getGlobalFrameID(),
|
|
plan_to_grid))
|
|
{
|
|
// Không quy đổi được frame thì mọi kết luận đều vô nghĩa. Trả false = "không biết".
|
|
return false;
|
|
}
|
|
|
|
// Cùng giao thức khoá với map-update thread và planner: lượt quét chỉ đọc vài chục ô nên giữ
|
|
// mutex trọn lượt là rẻ, còn đọc lưới trong lúc nó đang được ghi thì kết luận không đáng tin.
|
|
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()));
|
|
out = move_base2::checkPlan(plan, from_index, horizon, *grid, plan_to_grid);
|
|
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 ---------------------------------------------------------------------------------
|
|
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());
|
|
|
|
// PathMonitor quét tuyến trên chính costmap local — cùng lưới mà detour lập đường vòng trên đó.
|
|
path_check_.setCostmap(local_costmap_.get());
|
|
path_check_.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());
|
|
|
|
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;
|
|
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 --------------------------------------------------------------------------
|
|
//
|
|
// Không chặn: mission layer hỏng thì navigation vẫn phải chạy được. Nhưng phải LOG rõ, vì 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 duy nhất.
|
|
if (config_.mission_layer_enabled)
|
|
{
|
|
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());
|
|
}
|
|
}
|
|
else
|
|
{
|
|
robot::log_info("[move_base2] NavigationRuntime: mission layer disabled by config "
|
|
"(mission_layer_enabled: false) — orders go straight down as one goal.\n");
|
|
}
|
|
|
|
// --- 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.path_check = &path_check_;
|
|
return deps;
|
|
}
|
|
|
|
} // namespace move_base2
|