first commit

This commit is contained in:
2026-07-29 15:45:16 +07:00
commit 4762a3032c
56 changed files with 15310 additions and 0 deletions

View File

@@ -0,0 +1,302 @@
/*********************************************************************
* move_base2 — hiện thực ActionPort bằng các ActionHandler plugin.
*
* Author: DuongTD
*********************************************************************/
#include <move_base2/runners/action_runner.h>
#include <utility>
#include <boost/dll/import.hpp>
#include <boost/system/system_error.hpp>
#include <yaml-cpp/yaml.h>
#include <robot/robot.h>
namespace move_base2
{
ActionRunner::~ActionRunner()
{
// Handler phải chết TRƯỚC factory: factory là thứ giữ .so còn nạp.
active_ = nullptr;
by_type_.clear();
handlers_.clear();
factories_.clear();
}
void ActionRunner::setClock(ClockPort* clock)
{
clock_ = clock;
}
void ActionRunner::setNamespace(const std::string& ns)
{
namespace_ = ns;
}
bool ActionRunner::registerHandler(const ActionHandler::Ptr& handler)
{
if (!handler)
{
robot::log_error("[move_base2] ActionRunner: handler null.");
return false;
}
const std::vector<std::string> types = handler->supportedActionTypes();
if (types.empty())
{
robot::log_error("[move_base2] ActionRunner: handler không khai actionType nào — sẽ không bao "
"giờ được gọi.");
return false;
}
for (const std::string& type : types)
{
if (type.empty())
{
robot::log_error("[move_base2] ActionRunner: handler khai một actionType rỗng.");
return false;
}
if (by_type_.find(type) != by_type_.end())
{
// Hai handler cùng nhận một type thì việc định tuyến phụ thuộc thứ tự nạp — từ chối thay vì
// im lặng ghi đè.
robot::log_error("[move_base2] ActionRunner: actionType '%s' đã có handler khác đăng ký.",
type.c_str());
return false;
}
}
handlers_.push_back(handler);
for (const std::string& type : types)
{
by_type_[type] = handler.get();
}
return true;
}
ActionHandler* ActionRunner::find(const std::string& action_type) const
{
const auto it = by_type_.find(action_type);
return it == by_type_.end() ? nullptr : it->second;
}
std::vector<std::string> ActionRunner::supportedActionTypes() const
{
std::vector<std::string> types;
types.reserve(by_type_.size());
for (const auto& entry : by_type_)
{
types.push_back(entry.first);
}
return types;
}
bool ActionRunner::loadOne(const std::string& name, const std::string& type,
robot::NodeHandle& nh, const std::string& ns)
{
robot::PluginLoaderHelper loader(nh);
const std::string library_path = loader.findLibraryPath(type);
if (library_path.empty())
{
robot::log_error("[move_base2] ActionRunner: không tìm được thư viện cho '%s' — kiểm khoá "
"'%s/library_path' trong YAML và sự tồn tại của file .so.",
type.c_str(), type.c_str());
return false;
}
std::function<ActionHandler::Ptr()> factory;
try
{
factory = boost::dll::import_alias<ActionHandler::Ptr()>(
library_path, type, boost::dll::load_mode::append_decorations);
}
catch (const boost::system::system_error& ex)
{
robot::log_error("[move_base2] ActionRunner: không nạp được symbol '%s' từ '%s': %s",
type.c_str(), library_path.c_str(), ex.what());
return false;
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] ActionRunner: lỗi khi nạp '%s': %s", type.c_str(), ex.what());
return false;
}
ActionHandler::Ptr handler;
try
{
handler = factory();
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] ActionRunner: factory của '%s' ném exception: %s", type.c_str(),
ex.what());
return false;
}
if (!handler)
{
robot::log_error("[move_base2] ActionRunner: factory của '%s' trả về null.", type.c_str());
return false;
}
const std::string param_ns = ns.empty() ? name : ns + "/" + name;
robot::NodeHandle handler_nh(nh, param_ns);
if (!handler->configure(name, handler_nh))
{
robot::log_error("[move_base2] ActionRunner: '%s' (instance '%s') configure() thất bại.",
type.c_str(), name.c_str());
return false;
}
if (!registerHandler(handler))
{
return false;
}
factories_.push_back(std::move(factory));
robot::log_info("[move_base2] ActionRunner: nạp '%s' (instance '%s').", type.c_str(),
name.c_str());
return true;
}
bool ActionRunner::configure(robot::NodeHandle& nh)
{
if (configured_)
{
robot::log_error("[move_base2] ActionRunner: configure() gọi lần thứ hai.");
return false;
}
if (clock_ == nullptr)
{
robot::log_error("[move_base2] ActionRunner: thiếu ClockPort — handler không có mốc timeout.");
return false;
}
const std::string key = namespace_.empty() ? std::string("handlers") : namespace_ + "/handlers";
YAML::Node list;
if (!nh.getParam(key, list) || !list.IsSequence())
{
// Không có handler nào là hợp lệ: hệ không có thiết bị thì mọi mission đều nav-only, và
// ControlLoop::submit đã từ chối yêu cầu mang action ngay tại cửa.
robot::log_warning("[move_base2] ActionRunner: '%s' không có danh sách handler — runtime sẽ "
"từ chối mọi yêu cầu mang action.", key.c_str());
configured_ = true;
return true;
}
bool all_ok = true;
for (std::size_t i = 0; i < list.size(); ++i)
{
const YAML::Node& entry = list[i];
if (!entry.IsMap() || !entry["type"])
{
robot::log_error("[move_base2] ActionRunner: '%s[%zu]' thiếu khoá 'type'.", key.c_str(), i);
all_ok = false;
continue;
}
std::string type;
std::string name;
try
{
type = entry["type"].as<std::string>();
name = entry["name"] ? entry["name"].as<std::string>() : type;
}
catch (const YAML::Exception& ex)
{
robot::log_error("[move_base2] ActionRunner: '%s[%zu]' không đọc được: %s", key.c_str(), i,
ex.what());
all_ok = false;
continue;
}
if (!loadOne(name, type, nh, namespace_))
{
all_ok = false;
}
}
configured_ = true;
return all_ok;
}
bool ActionRunner::start(const robot_protocol_msgs::Action& action)
{
active_ = nullptr;
active_action_id_.clear();
if (!configured_)
{
robot::log_error("[move_base2] ActionRunner: start() trước configure().");
return false;
}
if (action.actionType.empty())
{
robot::log_error("[move_base2] ActionRunner: action không có actionType.");
return false;
}
ActionHandler* handler = find(action.actionType);
if (handler == nullptr)
{
robot::log_error("[move_base2] ActionRunner: không handler nào nhận actionType '%s' (id '%s').",
action.actionType.c_str(), action.actionId.c_str());
return false;
}
if (!handler->start(action, clock_->now()))
{
robot::log_warning("[move_base2] ActionRunner: handler từ chối khởi động action '%s' (id '%s').",
action.actionType.c_str(), action.actionId.c_str());
return false;
}
active_ = handler;
active_action_id_ = action.actionId;
return true;
}
ActionTick ActionRunner::update()
{
ActionTick tick;
if (active_ == nullptr)
{
// Contract nói update() chỉ được gọi sau start() trả true. Vẫn guard: lỗi thứ tự gọi phải thành
// "action này hỏng" chứ không phải dereference null.
tick.status = ActionTick::Status::kFailed;
tick.message = "update() khi không có action nào đang chạy";
return tick;
}
tick = active_->update(clock_->now());
if (tick.status != ActionTick::Status::kRunning)
{
active_ = nullptr;
}
return tick;
}
void ActionRunner::cancel()
{
if (active_ != nullptr)
{
active_->cancel();
active_ = nullptr;
}
}
} // namespace move_base2

View File

@@ -0,0 +1,408 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — cài đặt ControllerRunner.
*
* Author: DuongTD
*********************************************************************/
#include <move_base2/runners/controller_runner.h>
#include <cmath>
#include <exception>
#include <utility>
#include <boost/dll/import.hpp>
#include <boost/system/system_error.hpp>
#include <robot/plugin_loader_helper.h>
#include <robot/robot.h>
namespace move_base2
{
namespace
{
/// [s] Giãn cách log cho cảnh báo phát sinh trong đường nóng — nhịp control loop, không được spam.
constexpr double kHotPathLogThrottle = 5.0;
bool isFiniteTwist(const robot_geometry_msgs::Twist& twist)
{
return std::isfinite(twist.linear.x) && std::isfinite(twist.linear.y) &&
std::isfinite(twist.angular.z);
}
} // namespace
ControllerRunner::ControllerRunner() = default;
ControllerRunner::~ControllerRunner() = default;
bool ControllerRunner::configure(const robot::NodeHandle& nh, tf3::BufferCore* tf,
robot_costmap_2d::Costmap2DROBOT* costmap,
const std::string& initial_controller, std::string& error)
{
if (configured_)
{
error = "ControllerRunner::configure() gọi lần thứ hai";
return false;
}
if (costmap == nullptr)
{
error = "ControllerRunner cần costmap local khác null";
return false;
}
nh_ = nh;
tf_ = tf;
costmap_ = costmap;
configured_ = true;
if (!initial_controller.empty() && !swapPlanner(initial_controller))
{
error = "không nạp được local planner khởi đầu '" + initial_controller + "'";
configured_ = false;
return false;
}
return true;
}
robot_nav_core::BaseLocalPlanner* ControllerRunner::acquire(const std::string& name)
{
const auto cached = controllers_.find(name);
if (cached != controllers_.end())
{
return cached->second.instance.get();
}
robot::PluginLoaderHelper loader(nh_);
const std::string library_path = loader.findLibraryPath(name);
if (library_path.empty())
{
robot::log_error("[move_base2] ControllerRunner: không tìm được thư viện cho '%s' — kiểm khoá "
"'%s/library_path' trong YAML và sự tồn tại của file .so trong devel/lib.\n",
name.c_str(), name.c_str());
return nullptr;
}
Loaded loaded;
try
{
loaded.factory = boost::dll::import_alias<robot_nav_core::BaseLocalPlanner::Ptr()>(
library_path, name, boost::dll::load_mode::append_decorations);
}
catch (const boost::system::system_error& ex)
{
robot::log_error("[move_base2] ControllerRunner: không nạp được symbol '%s' từ '%s': %s\n",
name.c_str(), library_path.c_str(), ex.what());
return nullptr;
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] ControllerRunner: lỗi khi nạp '%s': %s\n", name.c_str(),
ex.what());
return nullptr;
}
try
{
loaded.instance = loaded.factory();
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] ControllerRunner: factory của '%s' ném exception: %s\n",
name.c_str(), ex.what());
return nullptr;
}
if (!loaded.instance)
{
robot::log_error("[move_base2] ControllerRunner: factory của '%s' trả nullptr.\n", name.c_str());
return nullptr;
}
try
{
// Khác BaseGlobalPlanner: initialize ở đây trả void, nên không có cách nào biết plugin tự thấy
// mình hỏng. Chỉ chặn được exception.
loaded.instance->initialize(name, tf_, costmap_);
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] ControllerRunner: initialize() của '%s' ném exception: %s\n",
name.c_str(), ex.what());
return nullptr;
}
const auto inserted = controllers_.emplace(name, std::move(loaded));
return inserted.first->second.instance.get();
}
void ControllerRunner::applyPendingLimits(robot_nav_core::BaseLocalPlanner* controller)
{
if (controller == nullptr)
{
return;
}
// Trần vận tốc thuộc về YÊU CẦU, không thuộc về instance planner. Instance mới nạp không biết gì
// về các trần host đã đặt trước đó — không áp lại là robot lặng lẽ chạy nhanh hơn mức tầng an
// toàn cho phép, và không có dấu hiệu nào cả.
try
{
if (has_limit_linear_forward_)
{
controller->setTwistLinear(limit_linear_forward_);
}
if (has_limit_linear_backward_)
{
controller->setTwistLinear(limit_linear_backward_);
}
if (has_limit_angular_)
{
controller->setTwistAngular(limit_angular_);
}
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] ControllerRunner: lỗi khi áp lại trần vận tốc: %s\n", ex.what());
}
}
bool ControllerRunner::swapPlanner(const std::string& planner_name)
{
if (!configured_)
{
robot::log_error("[move_base2] ControllerRunner: swapPlanner() trước configure().\n");
return false;
}
if (planner_name.empty())
{
robot::log_error("[move_base2] ControllerRunner: tên controller rỗng.\n");
return false;
}
if (planner_name == active_name_ && active_ != nullptr)
{
return true; // Đã đúng controller; không log để khỏi spam ở cửa vào mỗi yêu cầu.
}
robot_nav_core::BaseLocalPlanner* controller = acquire(planner_name);
if (controller == nullptr)
{
// Giữ nguyên controller đang chạy: bên gọi từ chối yêu cầu dựa vào giá trị trả về.
return false;
}
active_ = controller;
active_name_ = planner_name;
applyPendingLimits(active_);
robot::log_info("[move_base2] ControllerRunner: local planner đang dùng là '%s'.\n",
planner_name.c_str());
return true;
}
void ControllerRunner::setTolerance(double xy_m, double yaw_rad)
{
if (!configured_)
{
return;
}
// Interface gen-1 không có hàm đặt sai số; bản cũ ghi vào param rồi để planner tự đọc lại. Kênh
// gián tiếp này được giữ nguyên để không đổi hành vi của các planner đang chạy — nhưng planner
// nào chỉ đọc param lúc initialize sẽ KHÔNG thấy giá trị mới. Xem doc của lớp.
nh_.setParam("xy_goal_tolerance", xy_m);
nh_.setParam("yaw_goal_tolerance", yaw_rad);
}
bool ControllerRunner::setPlan(const std::vector<robot_geometry_msgs::PoseStamped>& plan)
{
if (!configured_ || active_ == nullptr)
{
robot::log_error_throttle(kHotPathLogThrottle,
"[move_base2] ControllerRunner: setPlan() khi chưa có controller.\n");
return false;
}
if (plan.empty())
{
// Plan rỗng lọt xuống sẽ thành front()/back() trên vector rỗng bên trong planner.
robot::log_error_throttle(kHotPathLogThrottle,
"[move_base2] ControllerRunner: từ chối plan rỗng.\n");
return false;
}
try
{
return active_->setPlan(plan);
}
catch (const std::exception& ex)
{
robot::log_error_throttle(kHotPathLogThrottle,
"[move_base2] ControllerRunner: '%s' ném exception trong setPlan: "
"%s\n", active_name_.c_str(), ex.what());
return false;
}
}
bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
{
cmd = robot_geometry_msgs::Twist();
if (!configured_ || active_ == nullptr)
{
robot::log_error_throttle(kHotPathLogThrottle,
"[move_base2] ControllerRunner: computeVelocityCommands() khi chưa "
"có controller.\n");
return false;
}
robot_geometry_msgs::Twist result;
bool ok = false;
try
{
ok = active_->computeVelocityCommands(measured_velocity_, result);
}
catch (const std::exception& ex)
{
robot::log_error_throttle(kHotPathLogThrottle,
"[move_base2] ControllerRunner: '%s' ném exception khi tính lệnh: "
"%s\n", active_name_.c_str(), ex.what());
return false;
}
if (!ok)
{
return false;
}
if (!isFiniteTwist(result))
{
// VelocityArbiter cũng chặn NaN/Inf, nhưng chặn ngay tại nguồn cho biết ĐÚNG plugin nào đang
// trả dữ liệu hỏng — arbiter chỉ thấy một con số vô nghĩa không rõ từ đâu.
robot::log_error_throttle(kHotPathLogThrottle,
"[move_base2] ControllerRunner: '%s' trả lệnh chứa NaN/Inf.\n",
active_name_.c_str());
return false;
}
cmd = result;
return true;
}
bool ControllerRunner::isGoalReached()
{
if (!configured_ || active_ == nullptr)
{
return false;
}
try
{
return active_->isGoalReached();
}
catch (const std::exception& ex)
{
// Trả false: "chưa tới đích" là phía an toàn — báo nhầm đã tới sẽ kết thúc chặng đường sớm và
// robot dừng ở chỗ không phải đích.
robot::log_error_throttle(kHotPathLogThrottle,
"[move_base2] ControllerRunner: '%s' ném exception trong "
"isGoalReached: %s\n", active_name_.c_str(), ex.what());
return false;
}
}
void ControllerRunner::setMeasuredVelocity(const robot_geometry_msgs::Twist& velocity)
{
if (!isFiniteTwist(velocity))
{
// Giữ giá trị cũ thay vì đưa NaN vào hàm tính lệnh — nhiều local planner dùng nó làm mốc giới
// hạn gia tốc, và NaN ở đó lan ra toàn bộ cost function.
robot::log_error_throttle(kHotPathLogThrottle,
"[move_base2] ControllerRunner: bỏ vận tốc đo được chứa NaN/Inf.\n");
return;
}
measured_velocity_ = velocity;
}
bool ControllerRunner::setTwistLinear(const robot_geometry_msgs::Vector3& linear)
{
if (!std::isfinite(linear.x) || !std::isfinite(linear.y) || !std::isfinite(linear.z))
{
robot::log_error("[move_base2] ControllerRunner: trần vận tốc thẳng chứa NaN/Inf, bỏ qua.\n");
return false;
}
// Dấu chọn chiều — xem doc của ControllerPort::setTwistLinear. Nhớ cả hai chiều riêng để
// swapPlanner còn áp lại được lên instance mới.
if (linear.x < 0.0)
{
limit_linear_backward_ = linear;
has_limit_linear_backward_ = true;
}
else
{
limit_linear_forward_ = linear;
has_limit_linear_forward_ = true;
}
if (active_ == nullptr)
{
// Host đặt trần trước khi controller được nạp là chuyện bình thường: thứ tự khởi tạo không do
// move_base2 quyết. Đã nhớ lại, sẽ áp khi có controller.
return true;
}
try
{
return active_->setTwistLinear(linear);
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] ControllerRunner: '%s' ném exception trong setTwistLinear: %s\n",
active_name_.c_str(), ex.what());
return false;
}
}
bool ControllerRunner::setTwistAngular(const robot_geometry_msgs::Vector3& angular)
{
if (!std::isfinite(angular.x) || !std::isfinite(angular.y) || !std::isfinite(angular.z))
{
robot::log_error("[move_base2] ControllerRunner: trần vận tốc góc chứa NaN/Inf, bỏ qua.\n");
return false;
}
limit_angular_ = angular;
has_limit_angular_ = true;
if (active_ == nullptr)
{
return true;
}
try
{
return active_->setTwistAngular(angular);
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] ControllerRunner: '%s' ném exception trong setTwistAngular: %s\n",
active_name_.c_str(), ex.what());
return false;
}
}
std::string ControllerRunner::activeController() const
{
return active_ != nullptr ? active_name_ : std::string();
}
} // namespace move_base2

View File

@@ -0,0 +1,395 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — cài đặt PlannerRunner.
*
* Author: DuongTD
*********************************************************************/
#include <move_base2/runners/planner_runner.h>
#include <cmath>
#include <exception>
#include <utility>
#include <boost/dll/import.hpp>
#include <boost/system/system_error.hpp>
#include <robot/plugin_loader_helper.h>
#include <robot/robot.h>
namespace move_base2
{
namespace
{
/// @brief Pose có dùng được để lập plan không — NaN/Inf lọt vào SBPL là hỏng ở tầng khó truy nhất.
bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose)
{
return std::isfinite(pose.pose.position.x) && std::isfinite(pose.pose.position.y) &&
std::isfinite(pose.pose.orientation.z) && std::isfinite(pose.pose.orientation.w);
}
} // namespace
PlannerRunner::PlannerRunner() = default;
PlannerRunner::~PlannerRunner()
{
{
std::lock_guard<std::mutex> lock(mutex_);
shutdown_ = true;
discard_ = true;
}
cv_.notify_all();
if (thread_.joinable())
{
// Chờ có chủ đích: plugin là hộp đen nạp lúc chạy, không có đường cắt ngang một phép tính đang
// chạy. Detach thay vì join sẽ để thread chạm vào `planning_`/`handoff_` sau khi chúng đã bị
// huỷ — hỏng ở chỗ không thể truy được.
thread_.join();
}
}
bool PlannerRunner::configure(const robot::NodeHandle& nh,
robot_costmap_2d::Costmap2DROBOT* costmap,
const std::string& initial_planner, std::string& error)
{
if (configured_)
{
error = "PlannerRunner::configure() gọi lần thứ hai";
return false;
}
if (costmap == nullptr)
{
// Không có costmap thì `BaseGlobalPlanner::initialize` nhận nullptr và mọi plugin tự quyết định
// làm gì với nó — thường là sập. Chặn ở đây, nơi còn nói được lý do.
error = "PlannerRunner cần costmap global khác null";
return false;
}
nh_ = nh;
costmap_ = costmap;
configured_ = true;
if (!initial_planner.empty() && !swapPlanner(initial_planner))
{
error = "không nạp được global planner khởi đầu '" + initial_planner + "'";
configured_ = false;
return false;
}
thread_ = std::thread(&PlannerRunner::threadBody, this);
return true;
}
// ================================================================================================
// Nạp plugin — chỉ control thread chạm
// ================================================================================================
robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& name)
{
const auto cached = planners_.find(name);
if (cached != planners_.end())
{
return cached->second.instance.get();
}
robot::PluginLoaderHelper loader(nh_);
const std::string library_path = loader.findLibraryPath(name);
if (library_path.empty())
{
robot::log_error("[move_base2] PlannerRunner: không tìm được thư viện cho '%s' — kiểm khoá "
"'%s/library_path' trong YAML và sự tồn tại của file .so trong devel/lib.\n",
name.c_str(), name.c_str());
return nullptr;
}
Loaded loaded;
try
{
loaded.factory = boost::dll::import_alias<robot_nav_core::BaseGlobalPlanner::Ptr()>(
library_path, name, boost::dll::load_mode::append_decorations);
}
catch (const boost::system::system_error& ex)
{
robot::log_error("[move_base2] PlannerRunner: không nạp được symbol '%s' từ '%s': %s\n",
name.c_str(), library_path.c_str(), ex.what());
return nullptr;
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] PlannerRunner: lỗi khi nạp '%s': %s\n", name.c_str(), ex.what());
return nullptr;
}
try
{
loaded.instance = loaded.factory();
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] PlannerRunner: factory của '%s' ném exception: %s\n",
name.c_str(), ex.what());
return nullptr;
}
if (!loaded.instance)
{
robot::log_error("[move_base2] PlannerRunner: factory của '%s' trả nullptr.\n", name.c_str());
return nullptr;
}
bool initialized = false;
try
{
initialized = loaded.instance->initialize(name, costmap_);
}
catch (const std::exception& ex)
{
robot::log_error("[move_base2] PlannerRunner: initialize() của '%s' ném exception: %s\n",
name.c_str(), ex.what());
return nullptr;
}
if (!initialized)
{
// Bản cũ chỉ log rồi đi tiếp với một planner chưa khởi tạo. Ở đây coi là thất bại: một planner
// báo "tôi chưa sẵn sàng" mà vẫn được gọi makePlan là đường dẫn tới hành vi không xác định.
robot::log_error("[move_base2] PlannerRunner: '%s' báo initialize() thất bại.\n", name.c_str());
return nullptr;
}
// Chỉ đưa vào cache khi đã khởi tạo xong — cache một instance hỏng nghĩa là mọi lần thử lại sau
// đều nhận lại đúng cái hỏng đó mà không báo gì.
const auto inserted = planners_.emplace(name, std::move(loaded));
return inserted.first->second.instance.get();
}
bool PlannerRunner::swapPlanner(const std::string& planner_name)
{
if (!configured_)
{
robot::log_error("[move_base2] PlannerRunner: swapPlanner() trước configure().\n");
return false;
}
if (planner_name.empty())
{
robot::log_error("[move_base2] PlannerRunner: tên planner rỗng.\n");
return false;
}
if (planner_name == active_name_)
{
std::lock_guard<std::mutex> lock(mutex_);
if (active_ != nullptr)
{
return true; // Đã đúng planner; không log để khỏi spam ở cửa vào mỗi yêu cầu.
}
}
robot_nav_core::BaseGlobalPlanner* planner = acquire(planner_name);
if (planner == nullptr)
{
// Giữ nguyên planner đang chạy. Bên gọi từ chối yêu cầu dựa vào giá trị trả về; chuyển sang
// trạng thái "không có planner" ở đây sẽ làm hỏng luôn cả yêu cầu đang chạy dở.
return false;
}
{
std::lock_guard<std::mutex> lock(mutex_);
// Lượt đang chạy thuộc về planner cũ — kết quả của nó không còn nghĩa. Không cắt ngang được
// phép tính, chỉ đánh dấu vứt kết quả. Con trỏ planner cũ vẫn hợp lệ vì cache không xoá entry.
if (running_ || pending_)
{
discard_ = true;
}
active_ = planner;
}
active_name_ = planner_name;
robot::log_info("[move_base2] PlannerRunner: global planner đang dùng là '%s'.\n",
planner_name.c_str());
return true;
}
std::string PlannerRunner::activePlanner() const
{
std::lock_guard<std::mutex> lock(mutex_);
return active_ != nullptr ? active_name_ : std::string();
}
// ================================================================================================
// Vòng đời một lượt lập plan
// ================================================================================================
bool PlannerRunner::startPlan(const robot_geometry_msgs::PoseStamped& start,
const robot_geometry_msgs::PoseStamped& goal,
const robot_protocol_msgs::Order* order, std::uint64_t tag)
{
if (!configured_)
{
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: startPlan() trước configure().\n");
return false;
}
if (!isFinitePose(start) || !isFinitePose(goal))
{
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: start hoặc goal chứa NaN/Inf, "
"không khởi động lượt lập plan.\n");
return false;
}
std::lock_guard<std::mutex> lock(mutex_);
if (active_ == nullptr)
{
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: startPlan() khi chưa có planner.\n");
return false;
}
if (pending_ || running_)
{
return false; // Đã có lượt đang chạy; bên gọi phải chờ hoặc huỷ trước.
}
request_start_ = start;
request_goal_ = goal;
// Sao chép Order: con trỏ chỉ hợp lệ trong lời gọi này, còn lượt lập plan sống lâu hơn thế.
request_order_ = (order != nullptr) ? std::make_shared<robot_protocol_msgs::Order>(*order)
: nullptr;
request_tag_ = tag;
pending_ = true;
discard_ = false;
has_result_ = false;
cv_.notify_one();
return true;
}
bool PlannerRunner::isPlanning() const
{
std::lock_guard<std::mutex> lock(mutex_);
return pending_ || running_;
}
bool PlannerRunner::pollPlan(PlanResult& result)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!has_result_)
{
return false;
}
has_result_ = false;
result.tag = result_tag_;
result.succeeded = result_ok_;
// Hoán vị chứ không copy: vector cũ của bên gọi quay lại làm hộp thư và giữ nguyên capacity, nên
// ở trạng thái ổn định không có lần cấp phát nào cho việc bàn giao plan.
result.plan.swap(handoff_);
handoff_.clear();
return true;
}
void PlannerRunner::cancelPlan()
{
std::lock_guard<std::mutex> lock(mutex_);
if (pending_ || running_)
{
discard_ = true;
}
// Kết quả đã nằm sẵn trong hộp thư cũng bỏ luôn: bên gọi vừa nói nó không còn cần plan này.
has_result_ = false;
handoff_.clear();
}
// ================================================================================================
// Thread planner
// ================================================================================================
void PlannerRunner::threadBody()
{
std::unique_lock<std::mutex> lock(mutex_);
while (true)
{
cv_.wait(lock, [this] { return shutdown_ || pending_; });
if (shutdown_)
{
return;
}
// Chụp lại yêu cầu rồi NHẢ MUTEX trước khi gọi plugin. Đây là điểm mấu chốt của cả mô hình:
// control thread không bao giờ phải chờ một lượt lập plan.
robot_nav_core::BaseGlobalPlanner* planner = active_;
const robot_geometry_msgs::PoseStamped start = request_start_;
const robot_geometry_msgs::PoseStamped goal = request_goal_;
const std::shared_ptr<robot_protocol_msgs::Order> order = request_order_;
const std::uint64_t tag = request_tag_;
pending_ = false;
running_ = true;
lock.unlock();
planning_.clear();
bool ok = false;
try
{
// Hai overload của interface gốc gộp lại: "có Order hay không" là một nhánh, không phải hai
// contract. Plugin nào không hiểu Order thì overload mặc định của nó tự lo.
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
}
catch (const std::exception& ex)
{
// Plugin bên thứ ba ném ra thì đây là biên duy nhất chặn được — exception thoát khỏi thân
// thread là std::terminate, tức mất cả tiến trình navigation vì một lượt lập plan hỏng.
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: plugin ném exception khi lập "
"plan: %s\n", ex.what());
ok = false;
}
catch (...)
{
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: plugin ném exception lạ khi lập "
"plan.\n");
ok = false;
}
if (!ok || planning_.empty())
{
// Contract của PlannerPort: thành công nghĩa là plan KHÔNG rỗng. Một số plugin trả true kèm
// vector rỗng; quy về thất bại ngay tại đây để tầng trên không gọi front()/back() trên nó.
planning_.clear();
ok = false;
}
lock.lock();
running_ = false;
if (discard_)
{
// Lượt này đã bị huỷ hoặc planner đã bị đổi giữa chừng. Vứt lặng lẽ — không phải lỗi.
discard_ = false;
planning_.clear();
continue;
}
planning_.swap(handoff_);
result_tag_ = tag;
result_ok_ = ok;
has_result_ = true;
}
}
} // namespace move_base2

View File

@@ -0,0 +1,253 @@
/*********************************************************************
* move_base2 — hiện thực RecoveryPort bằng recovery_core.
*
* Author: DuongTD
*********************************************************************/
#include <move_base2/runners/recovery_runner.h>
#include <utility>
#include <robot/robot.h>
namespace move_base2
{
namespace
{
/// Dịch lý do vào recovery sang enum của recovery_core. `switch` đầy đủ để compiler bắt được ngay
/// khi một bên thêm giá trị mới — đó là toàn bộ lý do không dùng cast số.
recovery_core::RecoveryTrigger toCoreTrigger(RecoveryTrigger trigger)
{
switch (trigger)
{
case RecoveryTrigger::kPlanningFailed:
return recovery_core::RecoveryTrigger::kPlanningFailed;
case RecoveryTrigger::kControllingFailed:
return recovery_core::RecoveryTrigger::kControllingFailed;
case RecoveryTrigger::kOscillation:
return recovery_core::RecoveryTrigger::kOscillation;
}
return recovery_core::RecoveryTrigger::kUnspecified;
}
RecoveryOutputKind toPortKind(recovery_core::RecoveryOutputType kind)
{
switch (kind)
{
case recovery_core::RecoveryOutputType::kNone:
return RecoveryOutputKind::kNone;
case recovery_core::RecoveryOutputType::kVelocity:
return RecoveryOutputKind::kVelocity;
case recovery_core::RecoveryOutputType::kPath:
return RecoveryOutputKind::kPath;
}
return RecoveryOutputKind::kNone;
}
} // namespace
void RecoveryRunner::setDeps(const Deps& deps)
{
deps_ = deps;
pose_bridge_.setPort(deps_.pose);
collision_.setCostmap(deps_.local_costmap);
}
void RecoveryRunner::setCostmaps(robot_costmap_2d::Costmap2DROBOT* local,
robot_costmap_2d::Costmap2DROBOT* global)
{
deps_.local_costmap = local;
deps_.global_costmap = global;
collision_.setCostmap(local);
}
void RecoveryRunner::setNamespace(const std::string& ns)
{
namespace_ = ns;
}
void RecoveryRunner::setPlanSource(PlanSource source)
{
plan_bridge_.setSource(std::move(source));
}
void RecoveryRunner::refreshContext()
{
// Trỏ lại mỗi lượt thay vì tin bản cache từ configure(): con trỏ costmap là non-owning và có thể
// bị thay khi runtime dựng lại costmap. Cache nó chính là nguyên nhân lỗi double-free đã ghi nhận
// trong workspace.
collision_.setCostmap(deps_.local_costmap);
ctx_.pose = &pose_bridge_;
ctx_.collision = &collision_;
ctx_.plan = &plan_bridge_;
ctx_.local_costmap = deps_.local_costmap;
ctx_.global_costmap = deps_.global_costmap;
}
bool RecoveryRunner::configure(robot::NodeHandle& nh)
{
if (configured_)
{
robot::log_error("[move_base2] RecoveryRunner: configure() gọi lần thứ hai.");
return false;
}
if (deps_.clock == nullptr || deps_.pose == nullptr)
{
robot::log_error("[move_base2] RecoveryRunner: thiếu ClockPort hoặc PosePort.");
return false;
}
refreshContext();
const bool all_ok = registry_.loadFromConfig(nh, namespace_, ctx_);
if (registry_.size() == 0)
{
robot::log_error("[move_base2] RecoveryRunner: không nạp được behavior nào từ namespace '%s' — "
"runtime sẽ không có đường phục hồi.", namespace_.c_str());
return false;
}
configured_ = true;
if (!all_ok)
{
// Một số behavior hỏng nhưng phần còn lại dùng được: giữ chúng lại và báo false để bên gọi
// quyết định (chạy tiếp với ít đường phục hồi hơn, hay dừng khởi động).
robot::log_warning("[move_base2] RecoveryRunner: nạp được %zu behavior, một số entry bị bỏ.",
registry_.size());
return false;
}
robot::log_info("[move_base2] RecoveryRunner: nạp %zu recovery behavior từ '%s'.",
registry_.size(), namespace_.c_str());
return true;
}
std::size_t RecoveryRunner::behaviorCount() const
{
return registry_.size();
}
RecoveryOutputKind RecoveryRunner::outputKind(std::size_t index) const
{
const recovery_core::RecoveryBehavior* behavior = registry_.at(index);
// Index sai -> kNone: không cấp quyền phát vận tốc cho thứ không biết là gì.
return behavior == nullptr ? RecoveryOutputKind::kNone : toPortKind(behavior->outputKind());
}
std::string RecoveryRunner::behaviorName(std::size_t index) const
{
return registry_.nameAt(index);
}
bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
{
active_ = nullptr;
if (!configured_)
{
robot::log_error("[move_base2] RecoveryRunner: start() trước configure().");
return false;
}
recovery_core::RecoveryBehavior* behavior = registry_.at(index);
if (behavior == nullptr)
{
robot::log_error("[move_base2] RecoveryRunner: index %zu ngoài dải (%zu behavior).", index,
registry_.size());
return false;
}
refreshContext();
recovery_core::RecoveryGoal goal;
goal.trigger = toCoreTrigger(trigger);
// Không đặt angle/distance: để behavior dùng default đã cấu hình của nó. Lõi chưa có nguồn thông
// tin nào để chọn góc/quãng tốt hơn config; khi có (ví dụ hình học vật cản), đặt vào đây.
if (!behavior->start(goal, deps_.clock->now()))
{
robot::log_warning("[move_base2] RecoveryRunner: behavior '%s' từ chối khởi động (%s).",
registry_.nameAt(index).c_str(), toString(trigger));
return false;
}
active_ = behavior;
return true;
}
RecoveryTick RecoveryRunner::update()
{
RecoveryTick tick;
if (active_ == nullptr)
{
// Contract nói update() chỉ được gọi sau start() trả true. Vẫn guard: state machine hỏng thì
// phải thành "recovery này thất bại" chứ không phải dereference null.
tick.status = RecoveryTick::Status::kFailed;
tick.message = "update() khi không có behavior nào đang chạy";
return tick;
}
refreshContext();
return toTick(active_->update(deps_.clock->now()));
}
void RecoveryRunner::cancel()
{
if (active_ != nullptr)
{
active_->cancel();
}
}
RecoveryTick RecoveryRunner::toTick(const recovery_core::RecoveryResult& result) const
{
RecoveryTick tick;
switch (result.status)
{
case recovery_core::RecoveryStatus::kRunning:
tick.status = RecoveryTick::Status::kRunning;
break;
case recovery_core::RecoveryStatus::kSucceeded:
tick.status = RecoveryTick::Status::kSucceeded;
break;
case recovery_core::RecoveryStatus::kIdle:
// Behavior chưa start mà đã bị tick — lỗi thứ tự gọi, không phải trạng thái bình thường.
tick.status = RecoveryTick::Status::kFailed;
break;
case recovery_core::RecoveryStatus::kCancelled:
// Nhánh này KHÔNG đạt tới được với state machine hiện tại: sau cancel() nó chuyển sang
// CANCELLING, nơi tick_recovery bị ép false. Giữ nhánh lại làm hàng rào nếu sau này ai đó nới
// điều kiện tick — bỏ đi thì kCancelled sẽ rơi vào default và im lặng thành kRunning.
tick.status = RecoveryTick::Status::kFailed;
break;
case recovery_core::RecoveryStatus::kFailed:
tick.status = RecoveryTick::Status::kFailed;
break;
}
if (const robot_geometry_msgs::Twist* cmd = result.velocity())
{
tick.has_velocity = true;
tick.cmd = *cmd;
}
if (const robot_nav_msgs::Path* path = result.pathOut())
{
if (!path->poses.empty())
{
tick.has_path = true;
tick.path = path->poses;
}
}
tick.message = result.message;
return tick;
}
} // namespace move_base2