optimal & fix file cmake
This commit is contained in:
@@ -15,6 +15,33 @@
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace
|
||||
{
|
||||
/// @brief Dịch gợi ý chuỗi của mission layer sang profile của navigation.
|
||||
MotionProfile toProfile(const std::string& hint)
|
||||
{
|
||||
if (hint.empty() || hint == "position")
|
||||
{
|
||||
return MotionProfile::kPosition;
|
||||
}
|
||||
if (hint == "docking")
|
||||
{
|
||||
return MotionProfile::kDocking;
|
||||
}
|
||||
if (hint == "go_straight")
|
||||
{
|
||||
return MotionProfile::kGoStraight;
|
||||
}
|
||||
if (hint == "rotate")
|
||||
{
|
||||
return MotionProfile::kRotate;
|
||||
}
|
||||
|
||||
robot::log_warning("[move_base2] MissionAdapterBridge: unknown motion_hint '%s' — running the leg "
|
||||
"as a plain position goal.\n", hint.c_str());
|
||||
return MotionProfile::kPosition;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
MissionAdapterBridge::MissionAdapterBridge() = default;
|
||||
MissionAdapterBridge::~MissionAdapterBridge() = default;
|
||||
@@ -49,10 +76,6 @@ NavigationRequest MissionAdapterBridge::toRequest(const mission_adapters::Missio
|
||||
request.has_goal = mission.has_goal;
|
||||
request.goal = mission.goal;
|
||||
|
||||
// Sai số để mặc định: quy ước của NavigationRequest là giá trị <= 0 nghĩa "dùng default của
|
||||
// profile trong config". Mission layer không biết gì về sai số hình học nên không được đặt.
|
||||
request.tolerance = GoalTolerance();
|
||||
|
||||
// Mission layer KHÔNG diễn giải actionType và không lọc gì (D8) — action đi qua nguyên vẹn, đúng
|
||||
// thứ tự đã sắp theo sequenceId.
|
||||
request.actions.reserve(mission.actions.size());
|
||||
@@ -61,10 +84,39 @@ NavigationRequest MissionAdapterBridge::toRequest(const mission_adapters::Missio
|
||||
request.actions.push_back(action.action);
|
||||
}
|
||||
|
||||
// Mọi mission đều chạy profile position. `MissionType` chỉ nói mission đến TỪ ĐÂU (goal đơn hay
|
||||
// order VDA5050), không nói robot phải di chuyển KIỂU gì — docking/go-straight/rotate là lựa chọn
|
||||
// của người vận hành qua sáu entry point của contract host, không phải của mission layer.
|
||||
request.profile = MotionProfile::kPosition;
|
||||
// Mission layer chở `motion_hint` dưới dạng CHUỖI và không diễn giải nó; đây là biên duy nhất
|
||||
// dịch sang khái niệm của navigation. Mission nav mới luôn đặt profile hiệu lực; chuỗi rỗng vẫn
|
||||
// được coi là position để tương thích nguồn mission cũ.
|
||||
request.profile = toProfile(mission.motion_hint);
|
||||
request.marker = mission.marker;
|
||||
|
||||
// Đích đến muộn đi qua nguyên vẹn; `ControlLoop::submit` mới là chỗ quy về pose tuyệt đối.
|
||||
request.goal_frame = mission.goal_frame;
|
||||
request.relative_distance = mission.relative_distance;
|
||||
|
||||
// Chặng của order PHẢI mang theo phần order của nó. Global planner cấu hình cho profile position
|
||||
// là `CustomPlanner`, mà lớp này chỉ hiện thực nhánh `makePlan(Order, start, goal, plan)`; nhánh
|
||||
// ba tham số là stub in "This function is not available!" rồi trả false
|
||||
// (`custom_planner.h:86-91`). Chặng không có order vì thế fail ngay lượt lập plan đầu tiên và đi
|
||||
// thẳng vào recovery cho tới `ABORTED` — không có dấu hiệu nào chỉ ra thiếu dữ liệu.
|
||||
//
|
||||
// Order dựng lại từ CHẶNG chứ không phải order gốc: planner tra edge theo `startNodeId`/
|
||||
// `endNodeId` trong tập node nó nhận được, nên đưa cả order gốc xuống là mọi chặng đều lập plan
|
||||
// cho toàn tuyến. Quỹ đạo NURBS của edge đi theo nguyên vẹn vì đây là bản sao của chính các edge
|
||||
// trong order.
|
||||
//
|
||||
// CHỈ chặng position mới mang order. `DockPlanner` và `TwoPointsPlanner` — global planner của các
|
||||
// profile còn lại — chỉ hiện thực nhánh `makePlan` ba tham số; mang order xuống thì `PlannerRunner`
|
||||
// gọi biến thể `Order`, base trả false, và chặng fail ngay lượt lập plan đầu. Đúng lỗi đã xảy ra
|
||||
// với `CustomPlanner` ngày 2026-07-31, soi gương lại.
|
||||
if (mission.type == mission_adapters::MissionType::VDA5050_ORDER && mission.has_goal &&
|
||||
request.profile == MotionProfile::kPosition)
|
||||
{
|
||||
auto order = std::make_shared<robot_protocol_msgs::Order>();
|
||||
order->nodes = mission.nodes;
|
||||
order->edges = mission.edges;
|
||||
request.order = std::move(order);
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
@@ -87,8 +139,8 @@ bool MissionAdapterBridge::dispatch(const std::shared_ptr<const mission_adapters
|
||||
{
|
||||
// Chưa start hoặc đã stop. Từ chối thay vì cất lại: mission layer phải biết chặng của nó không
|
||||
// được nhận, chứ không phải chờ một kết quả sẽ không bao giờ tới.
|
||||
robot::log_warning("[move_base2] MissionAdapterBridge: từ chối mission %llu — bridge chưa "
|
||||
"start.\n", static_cast<unsigned long long>(mission->id));
|
||||
robot::log_warning("[move_base2] MissionAdapterBridge: rejecting mission %llu — the bridge did "
|
||||
"not start.\n", static_cast<unsigned long long>(mission->id));
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -97,8 +149,8 @@ bool MissionAdapterBridge::dispatch(const std::shared_ptr<const mission_adapters
|
||||
// Không nên xảy ra: MissionManager chỉ giao chặng mới sau khi chặng cũ kết thúc. Đếm lại thay
|
||||
// vì im lặng — một chặng biến mất trong khi fleet master vẫn chờ nó là lỗi rất khó truy.
|
||||
++dropped_requests_;
|
||||
robot::log_warning("[move_base2] MissionAdapterBridge: mission %llu đè mission %llu chưa kịp "
|
||||
"đẩy xuống.\n", static_cast<unsigned long long>(mission->id),
|
||||
robot::log_warning("[move_base2] MissionAdapterBridge: mission %llu overwrites mission %llu "
|
||||
"before it was pushed down.\n", static_cast<unsigned long long>(mission->id),
|
||||
static_cast<unsigned long long>(pending_->id));
|
||||
}
|
||||
|
||||
|
||||
190
src/bridges/mission_layer.cpp
Normal file
190
src/bridges/mission_layer.cpp
Normal file
@@ -0,0 +1,190 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — cài đặt MissionLayer.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/bridges/mission_layer.h>
|
||||
|
||||
#include <mission_adapters/mission_request.h>
|
||||
#include <robot/robot.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
|
||||
MissionLayer::MissionLayer() : events_(manager_, registry_), executor_(manager_)
|
||||
{
|
||||
}
|
||||
|
||||
MissionLayer::~MissionLayer()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
bool MissionLayer::configure(robot::NodeHandle& nh, const std::string& ns, std::string& error)
|
||||
{
|
||||
if (active_)
|
||||
{
|
||||
error = "MissionLayer::configure() called twice";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ns.empty())
|
||||
{
|
||||
error = "mission_namespace is empty";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!config_.loadFromParams(nh, ns))
|
||||
{
|
||||
error = "invalid mission parameters in namespace '" + ns + "'";
|
||||
return false;
|
||||
}
|
||||
manager_.setConfig(config_);
|
||||
|
||||
// Nạp hụt một nguồn không xoá các nguồn còn lại: registry đã log đích danh nguồn hỏng và lý do.
|
||||
if (!registry_.loadFromConfig(nh, ns))
|
||||
{
|
||||
robot::log_warning("[move_base2] MissionLayer: some mission sources failed to load; "
|
||||
"continuing with the remaining %zu source(s).\n", registry_.size());
|
||||
}
|
||||
|
||||
if (registry_.size() == 0)
|
||||
{
|
||||
error = "no mission source could be loaded from namespace '" + ns +
|
||||
"' — check `mission_sources` and the `library_path` key of each type";
|
||||
return false;
|
||||
}
|
||||
|
||||
active_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void MissionLayer::attach(MissionAdapterBridge& bridge)
|
||||
{
|
||||
// Hai chiều, cả hai đều non-owning: bridge báo outcome lên manager, executor đẩy chặng qua bridge.
|
||||
bridge.attach(&manager_);
|
||||
executor_.setNavigationClient(&bridge);
|
||||
}
|
||||
|
||||
void MissionLayer::start()
|
||||
{
|
||||
if (!active_ || started_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Event thread trước executor: nguồn sinh việc phải sẵn sàng trước nơi tiêu thụ việc. Ngược lại
|
||||
// thì executor chạy một vòng rỗng rồi ngủ, vô hại nhưng không có lý do gì để làm vậy.
|
||||
events_.start();
|
||||
executor_.start();
|
||||
started_ = true;
|
||||
|
||||
robot::log_info("[move_base2] MissionLayer started with %zu mission source(s).\n",
|
||||
registry_.size());
|
||||
}
|
||||
|
||||
void MissionLayer::stop()
|
||||
{
|
||||
if (!started_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ngược chiều dòng dữ liệu: chặn nguồn sự kiện trước, rồi mới dừng nơi phát lệnh xuống navigation.
|
||||
// Dừng executor trước thì event thread vẫn nạp thêm mission vào hàng đợi của một hệ đang tắt.
|
||||
events_.stop();
|
||||
executor_.stop();
|
||||
started_ = false;
|
||||
}
|
||||
|
||||
bool MissionLayer::handles(const std::string& schema) const
|
||||
{
|
||||
return registry_.find(schema) != nullptr;
|
||||
}
|
||||
|
||||
bool MissionLayer::submitOrder(const robot_protocol_msgs::Order& order)
|
||||
{
|
||||
if (!started_ || !handles(mission_adapters::schema::kVda5050Order))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
events_.orderEvent(order);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MissionLayer::submitGoal(const robot_geometry_msgs::PoseStamped& goal)
|
||||
{
|
||||
if (!started_ || !handles(mission_adapters::schema::kPoseStamped))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
events_.goalEvent(goal);
|
||||
return true;
|
||||
}
|
||||
|
||||
void MissionLayer::cancel()
|
||||
{
|
||||
if (started_)
|
||||
{
|
||||
events_.cancelEvent();
|
||||
}
|
||||
}
|
||||
|
||||
void MissionLayer::pause()
|
||||
{
|
||||
if (started_)
|
||||
{
|
||||
events_.pauseEvent();
|
||||
}
|
||||
}
|
||||
|
||||
void MissionLayer::resume()
|
||||
{
|
||||
if (started_)
|
||||
{
|
||||
events_.resumeEvent();
|
||||
}
|
||||
}
|
||||
|
||||
void MissionLayer::emergency()
|
||||
{
|
||||
if (started_)
|
||||
{
|
||||
events_.emergencyEvent();
|
||||
}
|
||||
}
|
||||
|
||||
void MissionLayer::clearEmergency()
|
||||
{
|
||||
if (started_)
|
||||
{
|
||||
events_.clearEmergencyEvent();
|
||||
}
|
||||
}
|
||||
|
||||
bool MissionLayer::hasMission() const
|
||||
{
|
||||
return manager_.hasMission();
|
||||
}
|
||||
|
||||
mission_adapters::MissionState MissionLayer::state() const
|
||||
{
|
||||
return manager_.state();
|
||||
}
|
||||
|
||||
std::size_t MissionLayer::sourceCount() const
|
||||
{
|
||||
return registry_.size();
|
||||
}
|
||||
|
||||
void MissionLayer::markActiveForTesting()
|
||||
{
|
||||
active_ = registry_.size() > 0;
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
@@ -20,7 +21,7 @@ void readDouble(robot::NodeHandle& nh, const std::string& key, double& value)
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
robot::log_warning("[move_base2] thiếu param '%s', dùng default %.4f", key.c_str(), value);
|
||||
robot::log_warning("[move_base2] missing param '%s', using default %.4f", key.c_str(), value);
|
||||
return;
|
||||
}
|
||||
nh.param(key, value, value);
|
||||
@@ -30,7 +31,7 @@ void readInt(robot::NodeHandle& nh, const std::string& key, int& value)
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
robot::log_warning("[move_base2] thiếu param '%s', dùng default %d", key.c_str(), value);
|
||||
robot::log_warning("[move_base2] missing param '%s', using default %d", key.c_str(), value);
|
||||
return;
|
||||
}
|
||||
nh.param(key, value, value);
|
||||
@@ -40,7 +41,7 @@ void readBool(robot::NodeHandle& nh, const std::string& key, bool& value)
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
robot::log_warning("[move_base2] thiếu param '%s', dùng default %s", key.c_str(),
|
||||
robot::log_warning("[move_base2] missing param '%s', using default %s", key.c_str(),
|
||||
value ? "true" : "false");
|
||||
return;
|
||||
}
|
||||
@@ -51,7 +52,7 @@ void readString(robot::NodeHandle& nh, const std::string& key, std::string& valu
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
robot::log_warning("[move_base2] thiếu param '%s', dùng default '%s'", key.c_str(),
|
||||
robot::log_warning("[move_base2] missing param '%s', using default '%s'", key.c_str(),
|
||||
value.c_str());
|
||||
return;
|
||||
}
|
||||
@@ -64,28 +65,121 @@ void readBinding(robot::NodeHandle& nh, const std::string& ns, ProfileBinding& b
|
||||
robot::NodeHandle profile_nh(nh, ns);
|
||||
readString(profile_nh, "base_global_planner", binding.global_planner_name);
|
||||
readString(profile_nh, "base_local_planner", binding.local_planner_name);
|
||||
readDouble(profile_nh, "xy_goal_tolerance", binding.default_xy_tolerance);
|
||||
readDouble(profile_nh, "yaw_goal_tolerance", binding.default_yaw_tolerance);
|
||||
}
|
||||
|
||||
void readSensors(robot::NodeHandle& nh, SensorGatewayConfig& sensors);
|
||||
|
||||
/// Đọc cặp planner runtime trực tiếp, không có adapter gen-1 ở giữa.
|
||||
void readRootProfileBinding(robot::NodeHandle& nh, const std::string& ns, ProfileBinding& binding)
|
||||
{
|
||||
robot::NodeHandle profile_nh(nh, ns);
|
||||
readString(profile_nh, "global_planner", binding.global_planner_name);
|
||||
readString(profile_nh, "local_planner", binding.local_planner_name);
|
||||
}
|
||||
|
||||
void readDockingMarkerProfiles(robot::NodeHandle& nh, DockingMarkerProfiles& profiles,
|
||||
std::string& error)
|
||||
{
|
||||
profiles.clear();
|
||||
error.clear();
|
||||
|
||||
if (!nh.hasParam("docking_marker_profiles"))
|
||||
{
|
||||
return; // Optional: the default docking binding remains authoritative.
|
||||
}
|
||||
const YAML::Node table = nh.getParamValue("docking_marker_profiles");
|
||||
if (!table || !table.IsDefined())
|
||||
{
|
||||
error = "docking_marker_profiles is declared but cannot be read";
|
||||
return;
|
||||
}
|
||||
if (!table.IsMap())
|
||||
{
|
||||
error = "docking_marker_profiles must be a map of marker names";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
for (auto entry = table.begin(); entry != table.end(); ++entry)
|
||||
{
|
||||
const std::string marker = entry->first.as<std::string>();
|
||||
const YAML::Node value = entry->second;
|
||||
if (marker.empty() || !value.IsMap())
|
||||
{
|
||||
error = "docking_marker_profiles has an empty marker name or a non-map entry";
|
||||
return;
|
||||
}
|
||||
if (!value["global_planner"] || !value["local_planner"] ||
|
||||
!value["global_planner"].IsScalar() || !value["local_planner"].IsScalar())
|
||||
{
|
||||
error = "docking_marker_profiles/'" + marker +
|
||||
"' must set scalar global_planner and local_planner";
|
||||
return;
|
||||
}
|
||||
|
||||
ProfileBinding binding;
|
||||
binding.global_planner_name = value["global_planner"].as<std::string>();
|
||||
binding.local_planner_name = value["local_planner"].as<std::string>();
|
||||
if (binding.global_planner_name.empty() || binding.local_planner_name.empty())
|
||||
{
|
||||
error = "docking_marker_profiles/'" + marker +
|
||||
"' has an empty global_planner or local_planner";
|
||||
return;
|
||||
}
|
||||
profiles.emplace(marker, std::move(binding));
|
||||
}
|
||||
}
|
||||
catch (const YAML::Exception& ex)
|
||||
{
|
||||
error = std::string("docking_marker_profiles is malformed: ") + ex.what();
|
||||
}
|
||||
}
|
||||
|
||||
/// Các tham số chung của move_base2, dùng chung cho schema namespace và schema root-profile.
|
||||
void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
{
|
||||
readDouble(nh, "controller_frequency", config.controller_frequency);
|
||||
readDouble(nh, "planner_frequency", config.planner_frequency);
|
||||
readDouble(nh, "planner_timeout", config.planner_timeout);
|
||||
readDouble(nh, "runtime_stats_period", config.runtime_stats_period);
|
||||
|
||||
readDouble(nh, "planner_patience", config.state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", config.state_machine.controller_patience);
|
||||
readDouble(nh, "oscillation_timeout", config.state_machine.oscillation_timeout);
|
||||
readDouble(nh, "oscillation_distance", config.state_machine.oscillation_distance);
|
||||
readDouble(nh, "action_patience", config.state_machine.action_patience);
|
||||
readInt(nh, "max_planning_retries", config.state_machine.max_planning_retries);
|
||||
readBool(nh, "recovery_behavior_enabled", config.state_machine.recovery_enabled);
|
||||
|
||||
readDouble(nh, "max_vel_x", config.velocity.max_vel_x);
|
||||
readDouble(nh, "min_vel_x", config.velocity.min_vel_x);
|
||||
readDouble(nh, "max_vel_theta", config.velocity.max_vel_theta);
|
||||
readDouble(nh, "acc_lim_x", config.velocity.max_accel_x);
|
||||
readDouble(nh, "acc_lim_theta", config.velocity.max_accel_theta);
|
||||
|
||||
readSensors(nh, config.sensors);
|
||||
readBool(nh, "docking_requires_marker", config.docking_requires_marker);
|
||||
|
||||
readString(nh, "recovery_namespace", config.recovery_namespace);
|
||||
readString(nh, "action_namespace", config.action_namespace);
|
||||
readString(nh, "mission_namespace", config.mission_namespace);
|
||||
readBool(nh, "mission_layer_enabled", config.mission_layer_enabled);
|
||||
readString(nh, "backup_global_planner", config.backup_global_planner_name);
|
||||
readString(nh, "global_frame", config.global_frame);
|
||||
readString(nh, "robot_base_frame", config.robot_base_frame);
|
||||
readBool(nh, "require_current_costmap", config.require_current_costmap);
|
||||
}
|
||||
|
||||
bool validateBinding(const ProfileBinding& binding, const char* name, std::string& error)
|
||||
{
|
||||
(void)name;
|
||||
(void)error;
|
||||
if (binding.local_planner_name.empty())
|
||||
{
|
||||
// Không đặt là hợp lệ: deployment có thể không dùng profile đó. Nhưng nếu đã đặt planner thì
|
||||
// sai số phải hợp lệ, vì chúng đi thẳng vào điều kiện dừng.
|
||||
// Không đặt là hợp lệ: deployment có thể không dùng profile đó.
|
||||
return true;
|
||||
}
|
||||
if (!std::isfinite(binding.default_xy_tolerance) || binding.default_xy_tolerance <= 0.0)
|
||||
{
|
||||
error = std::string(name) + ".xy_goal_tolerance phải > 0 [m]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(binding.default_yaw_tolerance) || binding.default_yaw_tolerance <= 0.0)
|
||||
{
|
||||
error = std::string(name) + ".yaw_goal_tolerance phải > 0 [rad]";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -101,134 +195,89 @@ void readSensors(robot::NodeHandle& nh, SensorGatewayConfig& sensors)
|
||||
void describeBinding(std::ostringstream& out, const char* name, const ProfileBinding& binding)
|
||||
{
|
||||
out << " " << name << ": global='" << binding.global_planner_name << "' local='"
|
||||
<< binding.local_planner_name << "' xy=" << binding.default_xy_tolerance
|
||||
<< " m yaw=" << binding.default_yaw_tolerance << " rad\n";
|
||||
}
|
||||
|
||||
/// Dịch patience gen-1 sang gen-2. Gen-1: mốc + patience luôn ở quá khứ khi patience <= 0, tức là
|
||||
/// "fail -> recovery NGAY". Gen-2: <= 0 nghĩa là TẮT đồng hồ — ngược nghĩa hoàn toàn. Giữ hành vi
|
||||
/// cũ bằng cách dịch thành đúng một chu kỳ điều khiển (gen-1 cũng chỉ phản ứng theo cycle).
|
||||
double legacyPatience(double value, double control_period_s, const char* key)
|
||||
{
|
||||
if (value > 0.0)
|
||||
{
|
||||
return value;
|
||||
}
|
||||
robot::log_warning(
|
||||
"[move_base2] legacy %s = %.3f: gen-1 hiểu là 'fail -> recovery ngay', gen-2 hiểu là 'tắt "
|
||||
"đồng hồ'. Dịch thành một chu kỳ điều khiển (%.4f s) để giữ hành vi cũ.",
|
||||
key, value, control_period_s);
|
||||
return control_period_s;
|
||||
}
|
||||
|
||||
/// Đọc binding của một profile theo schema gen-1: tên local planner ở khoá `<profile>_planner_name`
|
||||
/// tại root, global planner ở section con mang TÊN planner đó (thiếu thì dùng global mặc định).
|
||||
void readLegacyBinding(robot::NodeHandle& nh, const std::string& name_key,
|
||||
const std::string& default_global, double xy_tolerance,
|
||||
double yaw_tolerance, ProfileBinding& binding)
|
||||
{
|
||||
binding.default_xy_tolerance = xy_tolerance;
|
||||
binding.default_yaw_tolerance = yaw_tolerance;
|
||||
binding.global_planner_name = default_global;
|
||||
|
||||
// Default để RỖNG chứ không lấy default gen-1 ("mkt_algorithm/..."): các plugin đó không tồn tại
|
||||
// trong workspace, và profile không khai coi như không dùng — validate sẽ chặn nếu cả bốn rỗng.
|
||||
std::string local_name;
|
||||
nh.param(name_key, local_name, std::string(""));
|
||||
if (local_name.empty())
|
||||
{
|
||||
robot::log_warning("[move_base2] legacy: thiếu '%s' — profile này bị tắt", name_key.c_str());
|
||||
return;
|
||||
}
|
||||
binding.local_planner_name = local_name;
|
||||
|
||||
robot::NodeHandle planner_nh(nh, local_name);
|
||||
if (planner_nh.hasParam("base_global_planner"))
|
||||
{
|
||||
planner_nh.param("base_global_planner", binding.global_planner_name,
|
||||
binding.global_planner_name);
|
||||
}
|
||||
robot::log_info("[move_base2] legacy: %s='%s' -> local='%s' global='%s'", name_key.c_str(),
|
||||
local_name.c_str(), binding.local_planner_name.c_str(),
|
||||
binding.global_planner_name.c_str());
|
||||
<< binding.local_planner_name << "'\n";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void MoveBase2Config::fromNodeHandle(robot::NodeHandle& nh)
|
||||
{
|
||||
readDouble(nh, "controller_frequency", controller_frequency);
|
||||
readDouble(nh, "planner_frequency", planner_frequency);
|
||||
readDouble(nh, "planner_timeout", planner_timeout);
|
||||
|
||||
readDouble(nh, "planner_patience", state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", state_machine.controller_patience);
|
||||
readDouble(nh, "oscillation_timeout", state_machine.oscillation_timeout);
|
||||
readDouble(nh, "oscillation_distance", state_machine.oscillation_distance);
|
||||
readDouble(nh, "action_patience", state_machine.action_patience);
|
||||
readInt(nh, "max_planning_retries", state_machine.max_planning_retries);
|
||||
readBool(nh, "recovery_behavior_enabled", state_machine.recovery_enabled);
|
||||
|
||||
readDouble(nh, "max_vel_x", velocity.max_vel_x);
|
||||
readDouble(nh, "min_vel_x", velocity.min_vel_x);
|
||||
readDouble(nh, "max_vel_theta", velocity.max_vel_theta);
|
||||
readDouble(nh, "acc_lim_x", velocity.max_accel_x);
|
||||
readDouble(nh, "acc_lim_theta", velocity.max_accel_theta);
|
||||
|
||||
readSensors(nh, sensors);
|
||||
readMoveBase2Fields(nh, *this);
|
||||
|
||||
readBinding(nh, "position", position);
|
||||
readBinding(nh, "docking", docking);
|
||||
readBinding(nh, "go_straight", go_straight);
|
||||
readBinding(nh, "rotate", rotate);
|
||||
|
||||
readString(nh, "recovery_namespace", recovery_namespace);
|
||||
readString(nh, "action_namespace", action_namespace);
|
||||
readString(nh, "mission_namespace", mission_namespace);
|
||||
readString(nh, "global_frame", global_frame);
|
||||
readString(nh, "robot_base_frame", robot_base_frame);
|
||||
readDockingMarkerProfiles(nh, docking_marker_profiles, docking_marker_profiles_error);
|
||||
|
||||
// recovery_behavior_count KHÔNG đọc từ YAML: nó là số behavior thực sự nạp được, do
|
||||
// RecoveryRunner báo lại sau khi configure. Đọc từ config thì một behavior hỏng sẽ khiến state
|
||||
// machine tin là vẫn còn đường phục hồi.
|
||||
}
|
||||
|
||||
void MoveBase2Config::fromRootProfileNodeHandle(robot::NodeHandle& nh)
|
||||
{
|
||||
readMoveBase2Fields(nh, *this);
|
||||
readRootProfileBinding(nh, "position", position);
|
||||
readRootProfileBinding(nh, "docking", docking);
|
||||
readRootProfileBinding(nh, "go_straight", go_straight);
|
||||
readRootProfileBinding(nh, "rotate", rotate);
|
||||
readDockingMarkerProfiles(nh, docking_marker_profiles, docking_marker_profiles_error);
|
||||
}
|
||||
|
||||
bool MoveBase2Config::validate(std::string& error) const
|
||||
{
|
||||
if (!docking_marker_profiles_error.empty())
|
||||
{
|
||||
error = docking_marker_profiles_error;
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(controller_frequency) || controller_frequency <= 0.0)
|
||||
{
|
||||
error = "controller_frequency phải > 0 [Hz]";
|
||||
error = "controller_frequency must be > 0 [Hz]";
|
||||
return false;
|
||||
}
|
||||
if (controller_frequency > 200.0)
|
||||
{
|
||||
error = "controller_frequency > 200 Hz — nhịp này không thực tế cho một control loop có costmap";
|
||||
error = "controller_frequency > 200 Hz — unrealistic rate for a control loop that owns a "
|
||||
"costmap";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(planner_frequency) || planner_frequency < 0.0)
|
||||
{
|
||||
error = "planner_frequency phải >= 0 [Hz] (0 = chỉ lập plan khi cần)";
|
||||
error = "planner_frequency must be >= 0 [Hz] (0 = plan only when needed)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(planner_timeout))
|
||||
{
|
||||
error = "planner_timeout không hữu hạn [s]";
|
||||
error = "planner_timeout is not finite [s]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0)
|
||||
{
|
||||
error = "runtime_stats_period must be >= 0 [s] (0 = telemetry off)";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (recovery_namespace.empty())
|
||||
{
|
||||
error = "recovery_namespace rỗng";
|
||||
error = "recovery_namespace is empty";
|
||||
return false;
|
||||
}
|
||||
if (mission_layer_enabled && mission_namespace.empty())
|
||||
{
|
||||
error = "mission_layer_enabled is true but mission_namespace is empty — there would be no "
|
||||
"namespace to read `mission_sources` from";
|
||||
return false;
|
||||
}
|
||||
if (global_frame.empty() || robot_base_frame.empty())
|
||||
{
|
||||
error = "global_frame và robot_base_frame không được rỗng";
|
||||
error = "global_frame and robot_base_frame must not be empty";
|
||||
return false;
|
||||
}
|
||||
if (global_frame == robot_base_frame)
|
||||
{
|
||||
error = "global_frame trùng robot_base_frame — pose robot sẽ luôn là gốc toạ độ";
|
||||
error = "global_frame equals robot_base_frame — the robot pose would always be the origin";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -243,7 +292,7 @@ bool MoveBase2Config::validate(std::string& error) const
|
||||
if (position.local_planner_name.empty() && docking.local_planner_name.empty() &&
|
||||
go_straight.local_planner_name.empty() && rotate.local_planner_name.empty())
|
||||
{
|
||||
error = "không profile nào có base_local_planner — runtime sẽ từ chối mọi yêu cầu";
|
||||
error = "no profile has base_local_planner — the runtime would reject every request";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -278,13 +327,26 @@ std::string MoveBase2Config::describe() const
|
||||
out << " controller_frequency: " << controller_frequency << " Hz\n";
|
||||
out << " planner_frequency: " << planner_frequency << " Hz\n";
|
||||
out << " planner_timeout: " << planner_timeout << " s\n";
|
||||
out << " runtime_stats_period: " << runtime_stats_period << " s"
|
||||
<< (runtime_stats_period > 0.0 ? "\n" : " (off)\n");
|
||||
out << " frames: global='" << global_frame << "' base='" << robot_base_frame << "'\n";
|
||||
out << " require_current_costmap: " << (require_current_costmap ? "true" : "false") << "\n";
|
||||
out << " namespaces: recovery='" << recovery_namespace << "' actions='" << action_namespace
|
||||
<< "' mission='" << mission_namespace << "'\n";
|
||||
out << " mission_layer_enabled: " << (mission_layer_enabled ? "true" : "false")
|
||||
<< (mission_layer_enabled ? " (orders are split into legs)\n"
|
||||
: " (orders go straight down as one goal)\n");
|
||||
describeBinding(out, "position", position);
|
||||
describeBinding(out, "docking", docking);
|
||||
for (const auto& entry : docking_marker_profiles)
|
||||
{
|
||||
describeBinding(out, ("docking marker '" + entry.first + "'").c_str(), entry.second);
|
||||
}
|
||||
out << " docking_requires_marker: " << (docking_requires_marker ? "true" : "false") << '\n';
|
||||
describeBinding(out, "go_straight", go_straight);
|
||||
describeBinding(out, "rotate", rotate);
|
||||
out << " backup_global_planner: '" << backup_global_planner_name << "'"
|
||||
<< (backup_global_planner_name.empty() ? " (off)\n" : "\n");
|
||||
out << state_machine.describe();
|
||||
out << velocity.describe();
|
||||
out << sensors.describe();
|
||||
@@ -298,14 +360,14 @@ std::string MoveBase2Config::describe() const
|
||||
|
||||
void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
{
|
||||
// Default của gen-1 khác gen-2 ở hai chỗ; chế độ legacy giữ default gen-1 để không đổi hành vi
|
||||
// của một hệ đang chạy chỉ vì đổi runtime.
|
||||
// Schema gen-1 dùng base_footprint; giữ frame cũ để không đổi hành vi của hệ đang chạy.
|
||||
robot_base_frame = "base_footprint";
|
||||
position.default_xy_tolerance = 0.2; // [m]
|
||||
position.default_yaw_tolerance = 0.2; // [rad]
|
||||
|
||||
readDouble(nh, "controller_frequency", controller_frequency);
|
||||
readDouble(nh, "planner_frequency", planner_frequency);
|
||||
// Khoá này không có trong schema gen-1 — nó là công cụ chẩn đoán của move_base2. Vẫn đọc ở đây
|
||||
// để bật được telemetry mà không phải chuyển cả cây config sang schema mới.
|
||||
readDouble(nh, "runtime_stats_period", runtime_stats_period);
|
||||
readDouble(nh, "planner_patience", state_machine.planner_patience);
|
||||
readDouble(nh, "controller_patience", state_machine.controller_patience);
|
||||
readDouble(nh, "oscillation_timeout", state_machine.oscillation_timeout);
|
||||
@@ -315,12 +377,16 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
|
||||
readString(nh, "global_frame", global_frame);
|
||||
readString(nh, "robot_base_frame", robot_base_frame);
|
||||
// Không có trong schema gen-1 (bản cũ hard-code guard này, không cho tắt) — đọc để có đường tắt
|
||||
// khi observation buffer bị cấu hình sai, mặc định vẫn là bật.
|
||||
readBool(nh, "require_current_costmap", require_current_costmap);
|
||||
|
||||
// Sai số ở root là default chung cho cả bốn profile.
|
||||
double xy = position.default_xy_tolerance;
|
||||
double yaw = position.default_yaw_tolerance;
|
||||
readDouble(nh, "xy_goal_tolerance", xy);
|
||||
readDouble(nh, "yaw_goal_tolerance", yaw);
|
||||
// Cũng không có trong schema gen-1: gen-1 không có mission layer nên không có khoá tương ứng để
|
||||
// dịch. Đọc ở đây để tắt/bật được ngay trên cây config đang chạy mà không phải chuyển schema —
|
||||
// đây là đường lùi khi mission layer gây vấn đề trên hiện trường.
|
||||
readBool(nh, "mission_layer_enabled", mission_layer_enabled);
|
||||
readString(nh, "mission_namespace", mission_namespace);
|
||||
readBool(nh, "docking_requires_marker", docking_requires_marker);
|
||||
|
||||
std::string root_global_planner;
|
||||
readString(nh, "base_global_planner", root_global_planner);
|
||||
@@ -332,8 +398,9 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
// `LocalPlannerAdapter` là cầu nhúng planner gen-2 vào move_base gen-1. move_base2 gọi thẳng
|
||||
// interface gen-2 qua ControllerPort nên không cần cầu đó — bỏ qua CÓ LOG, để không ai tưởng
|
||||
// khoá này vẫn đang có hiệu lực.
|
||||
robot::log_warning("[move_base2] schema gen-1: bỏ qua base_local_planner='%s' — move_base2 gọi "
|
||||
"thẳng local planner, không qua adapter.", adapter.c_str());
|
||||
robot::log_warning("[move_base2] schema gen-1: ignoring base_local_planner='%s' — move_base2 "
|
||||
"calls the local planner directly, not through an adapter.",
|
||||
adapter.c_str());
|
||||
}
|
||||
|
||||
struct LegacyProfile
|
||||
@@ -350,12 +417,10 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
|
||||
for (const LegacyProfile& profile : profiles)
|
||||
{
|
||||
profile.binding->default_xy_tolerance = xy;
|
||||
profile.binding->default_yaw_tolerance = yaw;
|
||||
|
||||
if (!nh.hasParam(profile.key))
|
||||
{
|
||||
robot::log_warning("[move_base2] schema gen-1: thiếu '%s', profile này sẽ từ chối mọi yêu cầu",
|
||||
robot::log_warning("[move_base2] schema gen-1: missing '%s', this profile will reject every "
|
||||
"request",
|
||||
profile.key);
|
||||
continue;
|
||||
}
|
||||
@@ -385,14 +450,14 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
|
||||
const double one_cycle = controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s]
|
||||
if (state_machine.planner_patience <= 0.0)
|
||||
{
|
||||
robot::log_warning("[move_base2] schema gen-1: planner_patience <= 0 được dịch thành %.3f s "
|
||||
"(một chu kỳ điều khiển), không phải 'tắt'.", one_cycle);
|
||||
robot::log_warning("[move_base2] schema gen-1: planner_patience <= 0 is translated into %.3f s "
|
||||
"(one control cycle), not into 'off'.", one_cycle);
|
||||
state_machine.planner_patience = one_cycle;
|
||||
}
|
||||
if (state_machine.controller_patience <= 0.0)
|
||||
{
|
||||
robot::log_warning("[move_base2] schema gen-1: controller_patience <= 0 được dịch thành %.3f s "
|
||||
"(một chu kỳ điều khiển), không phải 'tắt'.", one_cycle);
|
||||
robot::log_warning("[move_base2] schema gen-1: controller_patience <= 0 is translated into "
|
||||
"%.3f s (one control cycle), not into 'off'.", one_cycle);
|
||||
state_machine.controller_patience = one_cycle;
|
||||
}
|
||||
}
|
||||
@@ -407,21 +472,29 @@ MoveBase2Config MoveBase2Config::load(robot::NodeHandle& root_nh)
|
||||
robot::NodeHandle modern_nh(root_nh, "move_base2");
|
||||
if (modern_nh.hasParam("controller_frequency"))
|
||||
{
|
||||
robot::log_info("[move_base2] dùng schema mới (namespace 'move_base2').");
|
||||
robot::log_info("[move_base2] using the new schema (namespace 'move_base2').");
|
||||
config.fromNodeHandle(modern_nh);
|
||||
return config;
|
||||
}
|
||||
|
||||
robot::NodeHandle position_nh(root_nh, "position");
|
||||
if (position_nh.hasParam("local_planner"))
|
||||
{
|
||||
robot::log_info("[move_base2] using the root profile schema.");
|
||||
config.fromRootProfileNodeHandle(root_nh);
|
||||
return config;
|
||||
}
|
||||
|
||||
if (root_nh.hasParam("controller_frequency") || root_nh.hasParam("base_global_planner"))
|
||||
{
|
||||
robot::log_warning("[move_base2] không thấy namespace 'move_base2'; đọc theo schema gen-1 của "
|
||||
robot::log_warning("[move_base2] namespace 'move_base2' not found; reading the gen-1 schema of "
|
||||
"move_base_common_params.yaml.");
|
||||
config.fromLegacyNodeHandle(root_nh);
|
||||
return config;
|
||||
}
|
||||
|
||||
robot::log_error("[move_base2] không tìm thấy cấu hình nào — chạy với toàn bộ giá trị mặc định. "
|
||||
"Kiểm PNKX_NAV_CORE_CONFIG_DIR và sự tồn tại của file config.");
|
||||
robot::log_error("[move_base2] no configuration found — running with all default values. Check "
|
||||
"PNKX_NAV_CORE_CONFIG_DIR and that the config file exists.");
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -433,10 +506,14 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
|
||||
config.nominal_control_period =
|
||||
controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s]
|
||||
config.robot_base_frame = robot_base_frame;
|
||||
config.require_current_costmap = require_current_costmap;
|
||||
config.position = position;
|
||||
config.docking = docking;
|
||||
config.docking_marker_profiles = docking_marker_profiles;
|
||||
config.go_straight = go_straight;
|
||||
config.rotate = rotate;
|
||||
config.backup_global_planner_name = backup_global_planner_name;
|
||||
config.docking_requires_marker = docking_requires_marker;
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,10 @@ 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;
|
||||
|
||||
} // namespace
|
||||
|
||||
// ================================================================================================
|
||||
@@ -39,19 +43,28 @@ bool ControlLoopConfig::validate(std::string& error) const
|
||||
}
|
||||
if (!(nominal_control_period > 0.0))
|
||||
{
|
||||
error = "nominal_control_period phải > 0 [s]";
|
||||
error = "nominal_control_period must be > 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (position.local_planner_name.empty())
|
||||
{
|
||||
error = "profile 'position' bắt buộc phải có local_planner_name";
|
||||
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 không được rỗng";
|
||||
error = "robot_base_frame must not be empty";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -88,7 +101,7 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
|
||||
if (deps.clock == nullptr || deps.pose == nullptr || deps.planner == nullptr ||
|
||||
deps.controller == nullptr || deps.recovery == nullptr)
|
||||
{
|
||||
error = "thiếu cổng bắt buộc (clock/pose/planner/controller/recovery)";
|
||||
error = "missing a required port (clock/pose/planner/controller/recovery)";
|
||||
return false;
|
||||
}
|
||||
if (!config.validate(error))
|
||||
@@ -129,6 +142,7 @@ void ControlLoop::reset()
|
||||
|
||||
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_;
|
||||
@@ -145,14 +159,21 @@ void ControlLoop::reset()
|
||||
last_reason_ = "";
|
||||
}
|
||||
|
||||
const ProfileBinding* ControlLoop::bindingFor(MotionProfile profile) const
|
||||
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:
|
||||
@@ -172,18 +193,71 @@ bool ControlLoop::isQuaternionValid(const robot_geometry_msgs::PoseStamped& pose
|
||||
return std::abs(std::sqrt(norm_sq) - 1.0) <= kQuaternionNormTolerance;
|
||||
}
|
||||
|
||||
bool ControlLoop::submit(const NavigationRequest& request, std::string& reason)
|
||||
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 chưa khởi tạo";
|
||||
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 = "yêu cầu có action nhưng runtime không có action port";
|
||||
reason = "request carries actions but the runtime has no action port";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -192,53 +266,83 @@ bool ControlLoop::submit(const NavigationRequest& request, std::string& reason)
|
||||
// D8: yêu cầu chỉ-có-action — không có goal để validate, không có planner để swap.
|
||||
if (request.actions.empty())
|
||||
{
|
||||
reason = "yêu cầu không có goal lẫn action";
|
||||
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 có toạ độ không hữu hạn";
|
||||
reason = "goal has non-finite coordinates";
|
||||
return false;
|
||||
}
|
||||
if (!isQuaternionValid(request.goal))
|
||||
{
|
||||
reason = "goal có quaternion không hợp lệ";
|
||||
reason = "goal has an invalid quaternion";
|
||||
return false;
|
||||
}
|
||||
|
||||
const ProfileBinding* binding = bindingFor(request.profile);
|
||||
const ProfileBinding* binding = bindingFor(request.profile, request.marker);
|
||||
if (binding == nullptr || binding->local_planner_name.empty())
|
||||
{
|
||||
reason = std::string("chưa cấu hình planner cho profile '") + toString(request.profile) + "'";
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// Đổ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 = "không nạp được global planner '" + 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 = "không nạp được local planner '" + binding->local_planner_name + "'";
|
||||
reason = "could not load local planner '" + binding->local_planner_name + "'";
|
||||
return false;
|
||||
}
|
||||
|
||||
deps_.controller->setTolerance(
|
||||
request.tolerance.hasXy() ? request.tolerance.xy : binding->default_xy_tolerance,
|
||||
request.tolerance.hasYaw() ? request.tolerance.yaw : binding->default_yaw_tolerance);
|
||||
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;
|
||||
@@ -290,6 +394,29 @@ void ControlLoop::collectPlannerResult()
|
||||
// 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())
|
||||
{
|
||||
// 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;
|
||||
}
|
||||
@@ -420,14 +547,14 @@ bool ControlLoop::step()
|
||||
// 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] Nhận goal (mission %llu): x=%.3f y=%.3f frame=%s.\n",
|
||||
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] Nhận yêu cầu chỉ-action (mission %llu), %zu action.\n",
|
||||
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());
|
||||
}
|
||||
@@ -540,7 +667,27 @@ bool ControlLoop::step()
|
||||
}
|
||||
}
|
||||
|
||||
if (output.run_controller)
|
||||
// --- 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.
|
||||
const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr &&
|
||||
!deps_.costmap_status->isCurrent();
|
||||
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.run_controller && !costmap_stale)
|
||||
{
|
||||
runController(candidate);
|
||||
}
|
||||
@@ -550,8 +697,11 @@ bool ControlLoop::step()
|
||||
// `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.
|
||||
planner_running_ = deps_.planner->startPlan(robot_pose, active_request_.goal,
|
||||
active_request_.order.get(), plan_tag_);
|
||||
// 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_)
|
||||
{
|
||||
// Không khởi động được (chưa có planner, pose hỏng...). Coi như một lượt hỏng để đồng hồ
|
||||
@@ -561,7 +711,7 @@ bool ControlLoop::step()
|
||||
}
|
||||
|
||||
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
|
||||
arbiter_.arbitrate(output.velocity_source, candidate, dt);
|
||||
arbiter_.arbitrate(costmap_stale ? VelocitySource::kNone : output.velocity_source, candidate, dt);
|
||||
|
||||
// --- 5. Báo kết quả -------------------------------------------------------------------------
|
||||
if (output.report_outcome)
|
||||
@@ -579,15 +729,15 @@ bool ControlLoop::step()
|
||||
static_cast<unsigned long long>(outgoing_mission_id));
|
||||
break;
|
||||
case NavigationOutcome::kPreempted:
|
||||
robot::log_info("[move_base2] Goal bị thay bởi goal mới (mission %llu: PREEMPTED).\n",
|
||||
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 bị huỷ (mission %llu: CANCELLED).\n",
|
||||
robot::log_info("[move_base2] Goal cancelled (mission %llu: CANCELLED).\n",
|
||||
static_cast<unsigned long long>(outgoing_mission_id));
|
||||
break;
|
||||
case NavigationOutcome::kFailed:
|
||||
robot::log_error("[move_base2] Navigation thất bại (mission %llu: ABORTED): %s\n",
|
||||
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;
|
||||
|
||||
@@ -107,12 +107,21 @@ void CostmapExporter::prepareGridLocked()
|
||||
}
|
||||
}
|
||||
|
||||
void CostmapExporter::attachTelemetry(RuntimeStats* telemetry)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
telemetry_ = telemetry;
|
||||
section_fill_ = (telemetry_ != nullptr) ? telemetry_->section("costmap.export")
|
||||
: RuntimeStats::kInvalidSection;
|
||||
}
|
||||
|
||||
void CostmapExporter::fill(robot_nav_msgs::OccupancyGrid& grid,
|
||||
robot_map_msgs::OccupancyGridUpdate& /*update*/, bool& is_updated)
|
||||
{
|
||||
is_updated = false;
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
ScopedSection timer(telemetry_, section_fill_);
|
||||
if (costmap_ == nullptr)
|
||||
{
|
||||
return;
|
||||
|
||||
425
src/io/runtime_stats.cpp
Normal file
425
src/io/runtime_stats.cpp
Normal file
@@ -0,0 +1,425 @@
|
||||
/**
|
||||
* @file runtime_stats.cpp
|
||||
* @brief Hiện thực @ref move_base2::RuntimeStats.
|
||||
*/
|
||||
#include <move_base2/io/runtime_stats.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
#ifdef __linux__
|
||||
#include <dirent.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <robot/robot.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
/// Bề rộng cột nhãn của bảng — đủ cho `costmap/global_costmap` mà không xuống dòng.
|
||||
constexpr int kLabelWidth = 26;
|
||||
|
||||
/// Tên hiển thị cho phần CPU không thuộc thread nào đã đăng ký (host ROS, ROS internals, plugin).
|
||||
constexpr const char* kUnregisteredLabel = "(unregistered)";
|
||||
|
||||
/**
|
||||
* @brief Đệm khoảng trắng bên phải cho đủ @p width **ký tự hiển thị**.
|
||||
*
|
||||
* `printf("%-*s")` đếm BYTE, mà nhãn ở đây có dấu tiếng Việt (UTF-8, 2 byte/ký tự) — dùng thẳng
|
||||
* printf thì bảng lệch cột đúng bằng số dấu. Byte nối tiếp của UTF-8 luôn có dạng 10xxxxxx nên đếm
|
||||
* byte KHÔNG phải continuation là ra số ký tự.
|
||||
*/
|
||||
std::string padRight(const std::string& text, int width)
|
||||
{
|
||||
int visible = 0;
|
||||
for (const char ch : text)
|
||||
{
|
||||
if ((static_cast<unsigned char>(ch) & 0xC0) != 0x80)
|
||||
{
|
||||
++visible;
|
||||
}
|
||||
}
|
||||
std::string padded = text;
|
||||
for (int i = visible; i < width; ++i)
|
||||
{
|
||||
padded += ' ';
|
||||
}
|
||||
return padded;
|
||||
}
|
||||
|
||||
double ticksPerSecond()
|
||||
{
|
||||
#ifdef __linux__
|
||||
const long hz = sysconf(_SC_CLK_TCK);
|
||||
return hz > 0 ? static_cast<double>(hz) : 100.0;
|
||||
#else
|
||||
return 100.0;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Lấy utime+stime từ một dòng `/proc/.../stat`.
|
||||
*
|
||||
* Không tách theo khoảng trắng từ đầu dòng được: trường thứ hai là tên tiến trình, nằm trong ngoặc
|
||||
* đơn và **có thể chứa cả khoảng trắng lẫn ngoặc**. Mốc đáng tin duy nhất là dấu `)` cuối cùng.
|
||||
*/
|
||||
std::uint64_t parseCpuTicks(const std::string& stat_line)
|
||||
{
|
||||
const std::size_t close = stat_line.rfind(')');
|
||||
if (close == std::string::npos)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::istringstream iss(stat_line.substr(close + 1));
|
||||
std::string field;
|
||||
// Sau dấu ')' , trường đầu tiên là state; utime là trường thứ 12, stime thứ 13.
|
||||
std::uint64_t utime = 0;
|
||||
std::uint64_t stime = 0;
|
||||
for (int index = 1; index <= 13; ++index)
|
||||
{
|
||||
if (!(iss >> field))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
if (index == 12)
|
||||
{
|
||||
utime = std::strtoull(field.c_str(), nullptr, 10);
|
||||
}
|
||||
else if (index == 13)
|
||||
{
|
||||
stime = std::strtoull(field.c_str(), nullptr, 10);
|
||||
}
|
||||
}
|
||||
return utime + stime;
|
||||
}
|
||||
|
||||
std::uint64_t readCpuTicksFrom(const std::string& path)
|
||||
{
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open())
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
std::string line;
|
||||
std::getline(file, line);
|
||||
return parseCpuTicks(line);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
RuntimeStats::RuntimeStats(double period_seconds)
|
||||
: period_seconds_(period_seconds)
|
||||
, ticks_per_second_(ticksPerSecond())
|
||||
, window_start_(std::chrono::steady_clock::now())
|
||||
{
|
||||
if (!enabled())
|
||||
{
|
||||
return;
|
||||
}
|
||||
last_process_cpu_ticks_ = readProcessCpuTicks();
|
||||
last_rss_bytes_ = readProcessRssBytes();
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// Đọc /proc
|
||||
// ================================================================================================
|
||||
|
||||
std::uint64_t RuntimeStats::readThreadCpuTicks(long tid)
|
||||
{
|
||||
#ifdef __linux__
|
||||
return readCpuTicksFrom("/proc/self/task/" + std::to_string(tid) + "/stat");
|
||||
#else
|
||||
(void)tid;
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::uint64_t RuntimeStats::readProcessCpuTicks()
|
||||
{
|
||||
#ifdef __linux__
|
||||
return readCpuTicksFrom("/proc/self/stat");
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::uint64_t RuntimeStats::readProcessRssBytes()
|
||||
{
|
||||
#ifdef __linux__
|
||||
std::ifstream file("/proc/self/statm");
|
||||
if (!file.is_open())
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
std::uint64_t total_pages = 0;
|
||||
std::uint64_t resident_pages = 0;
|
||||
file >> total_pages >> resident_pages;
|
||||
const long page_size = sysconf(_SC_PAGESIZE);
|
||||
return resident_pages * static_cast<std::uint64_t>(page_size > 0 ? page_size : 4096);
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::vector<long> RuntimeStats::listThreadIds()
|
||||
{
|
||||
std::vector<long> tids;
|
||||
#ifdef __linux__
|
||||
DIR* dir = opendir("/proc/self/task");
|
||||
if (dir == nullptr)
|
||||
{
|
||||
return tids;
|
||||
}
|
||||
while (const dirent* entry = readdir(dir))
|
||||
{
|
||||
if (entry->d_name[0] == '.')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
tids.push_back(std::strtol(entry->d_name, nullptr, 10));
|
||||
}
|
||||
closedir(dir);
|
||||
std::sort(tids.begin(), tids.end());
|
||||
#endif
|
||||
return tids;
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// Đăng ký
|
||||
// ================================================================================================
|
||||
|
||||
RuntimeStats::SectionId RuntimeStats::section(const std::string& name)
|
||||
{
|
||||
if (!enabled())
|
||||
{
|
||||
return kInvalidSection;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (SectionId id = 0; id < sections_.size(); ++id)
|
||||
{
|
||||
if (sections_[id].name == name)
|
||||
{
|
||||
return id;
|
||||
}
|
||||
}
|
||||
sections_.push_back(Section{ name, 0, 0, 0 });
|
||||
return sections_.size() - 1;
|
||||
}
|
||||
|
||||
void RuntimeStats::record(SectionId id, std::int64_t nanoseconds)
|
||||
{
|
||||
if (!enabled() || id == kInvalidSection)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (id >= sections_.size())
|
||||
{
|
||||
return;
|
||||
}
|
||||
Section& section = sections_[id];
|
||||
++section.calls;
|
||||
section.total_ns += nanoseconds;
|
||||
section.max_ns = std::max(section.max_ns, nanoseconds);
|
||||
}
|
||||
|
||||
void RuntimeStats::registerCurrentThread(const std::string& label)
|
||||
{
|
||||
if (!enabled())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
// syscall trực tiếp thay cho gettid(): wrapper của glibc chỉ có từ 2.30, gọi thẳng thì không phụ
|
||||
// thuộc phiên bản libc của máy build.
|
||||
const long tid = static_cast<long>(syscall(SYS_gettid));
|
||||
#else
|
||||
const long tid = 0;
|
||||
#endif
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (Thread& thread : threads_)
|
||||
{
|
||||
if (thread.tid == tid)
|
||||
{
|
||||
thread.label = label;
|
||||
return;
|
||||
}
|
||||
}
|
||||
threads_.push_back(Thread{ tid, label, readThreadCpuTicks(tid) });
|
||||
}
|
||||
|
||||
void RuntimeStats::beginThreadCapture()
|
||||
{
|
||||
if (!enabled())
|
||||
{
|
||||
return;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
capture_before_ = listThreadIds();
|
||||
capturing_ = true;
|
||||
}
|
||||
|
||||
void RuntimeStats::endThreadCapture(const std::string& label)
|
||||
{
|
||||
if (!enabled())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!capturing_)
|
||||
{
|
||||
robot::log_warning("[move_base2] RuntimeStats::endThreadCapture('%s') without an open capture "
|
||||
"window.\n",
|
||||
label.c_str());
|
||||
return;
|
||||
}
|
||||
capturing_ = false;
|
||||
|
||||
const std::vector<long> after = listThreadIds();
|
||||
int labelled = 0;
|
||||
for (const long tid : after)
|
||||
{
|
||||
if (std::binary_search(capture_before_.begin(), capture_before_.end(), tid))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
threads_.push_back(Thread{ tid, label, readThreadCpuTicks(tid) });
|
||||
++labelled;
|
||||
}
|
||||
|
||||
if (labelled == 0)
|
||||
{
|
||||
// Không phải lỗi chết người, nhưng phải nói ra: im lặng ở đây nghĩa là bảng thiếu hẳn một
|
||||
// thành phần và người đọc lại tưởng thành phần đó không tốn gì.
|
||||
robot::log_warning("[move_base2] RuntimeStats: '%s' created no thread — its CPU column will "
|
||||
"not appear.\n",
|
||||
label.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// In bảng
|
||||
// ================================================================================================
|
||||
|
||||
bool RuntimeStats::tick()
|
||||
{
|
||||
if (!enabled())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const double elapsed = std::chrono::duration<double>(now - window_start_).count();
|
||||
if (elapsed < period_seconds_)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string table = render();
|
||||
robot::log_info("%s", table.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string RuntimeStats::render()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const double window = std::chrono::duration<double>(now - window_start_).count();
|
||||
const double safe_window = window > 1e-6 ? window : 1e-6;
|
||||
|
||||
const std::uint64_t process_ticks = readProcessCpuTicks();
|
||||
const std::uint64_t rss_bytes = readProcessRssBytes();
|
||||
const double process_cpu =
|
||||
100.0 * static_cast<double>(process_ticks - last_process_cpu_ticks_) / ticks_per_second_ / safe_window;
|
||||
const double rss_mb = static_cast<double>(rss_bytes) / (1024.0 * 1024.0);
|
||||
const double rss_delta_mb = (static_cast<double>(rss_bytes) - static_cast<double>(last_rss_bytes_)) / (1024.0 * 1024.0);
|
||||
|
||||
const std::vector<long> all_tids = listThreadIds();
|
||||
|
||||
char line[256];
|
||||
std::ostringstream out;
|
||||
out << "\n";
|
||||
std::snprintf(line, sizeof(line), "[move_base2] ===== runtime stats — window %.2f s =====\n",
|
||||
window);
|
||||
out << line;
|
||||
std::snprintf(line, sizeof(line),
|
||||
" process: RSS %.1f MB (%+.1f MB in window, %+.1f MB/min) CPU %.1f%% thread %zu\n",
|
||||
rss_mb, rss_delta_mb, rss_delta_mb * 60.0 / safe_window, process_cpu, all_tids.size());
|
||||
out << line;
|
||||
|
||||
// --- CPU theo thread ---------------------------------------------------------------------------
|
||||
out << " " << padRight("thread", kLabelWidth) << " CPU%\n";
|
||||
|
||||
double registered_cpu = 0.0;
|
||||
std::size_t registered_alive = 0;
|
||||
for (Thread& thread : threads_)
|
||||
{
|
||||
const bool alive = std::binary_search(all_tids.begin(), all_tids.end(), thread.tid);
|
||||
const std::uint64_t ticks = alive ? readThreadCpuTicks(thread.tid) : thread.last_cpu_ticks;
|
||||
const double cpu =
|
||||
100.0 * static_cast<double>(ticks - thread.last_cpu_ticks) / ticks_per_second_ / safe_window;
|
||||
thread.last_cpu_ticks = ticks;
|
||||
|
||||
if (alive)
|
||||
{
|
||||
registered_cpu += cpu;
|
||||
++registered_alive;
|
||||
}
|
||||
|
||||
std::snprintf(line, sizeof(line), " %8.1f%s\n", cpu, alive ? "" : " (finished)");
|
||||
out << " " << padRight(thread.label, kLabelWidth - 2) << line;
|
||||
}
|
||||
|
||||
// Phần còn lại của tiến trình. Đây là con số quan trọng nhất khi đi tìm thủ phạm CPU: nếu nó lớn
|
||||
// hơn hẳn tổng các thread đã đăng ký thì vấn đề KHÔNG nằm trong navigation stack.
|
||||
const double other_cpu = process_cpu - registered_cpu;
|
||||
std::snprintf(line, sizeof(line), " %8.1f (%zu thread)\n", other_cpu,
|
||||
all_tids.size() > registered_alive ? all_tids.size() - registered_alive : 0);
|
||||
out << " " << padRight(kUnregisteredLabel, kLabelWidth - 2) << line;
|
||||
|
||||
// --- Chi phí theo đoạn công việc ----------------------------------------------------------------
|
||||
std::snprintf(line, sizeof(line), " %8s %10s %10s %8s\n", "calls/s", "avg [ms]", "peak [ms]",
|
||||
"CPU%");
|
||||
out << " " << padRight("work section", kLabelWidth) << line;
|
||||
|
||||
for (Section& section : sections_)
|
||||
{
|
||||
const double calls_per_second = static_cast<double>(section.calls) / safe_window;
|
||||
const double avg_ms =
|
||||
section.calls > 0 ? static_cast<double>(section.total_ns) / static_cast<double>(section.calls) / 1e6 : 0.0;
|
||||
const double max_ms = static_cast<double>(section.max_ns) / 1e6;
|
||||
// Tỷ lệ chiếm dụng: tổng thời gian đoạn này chạy so với chiều dài cửa sổ, quy ra %/1 core —
|
||||
// cùng đơn vị với cột CPU% ở trên nên so sánh trực tiếp được.
|
||||
const double share = 100.0 * static_cast<double>(section.total_ns) / 1e9 / safe_window;
|
||||
|
||||
std::snprintf(line, sizeof(line), " %8.1f %10.2f %10.2f %8.1f\n", calls_per_second, avg_ms, max_ms,
|
||||
share);
|
||||
out << " " << padRight(section.name, kLabelWidth - 2) << line;
|
||||
|
||||
section.calls = 0;
|
||||
section.total_ns = 0;
|
||||
section.max_ns = 0;
|
||||
}
|
||||
|
||||
window_start_ = now;
|
||||
last_process_cpu_ticks_ = process_ticks;
|
||||
last_rss_bytes_ = rss_bytes;
|
||||
|
||||
return out.str();
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -66,12 +66,12 @@ bool SensorGatewayConfig::validate(std::string& error) const
|
||||
|
||||
if (laser_sor_mean_k < 2)
|
||||
{
|
||||
error = "laser_sor_mean_k phải >= 2 [điểm] khi laser_sor_enabled = true";
|
||||
error = "laser_sor_mean_k must be >= 2 [points] when laser_sor_enabled = true";
|
||||
return false;
|
||||
}
|
||||
if (!(laser_sor_stddev_mul > 0.0))
|
||||
{
|
||||
error = "laser_sor_stddev_mul phải > 0 khi laser_sor_enabled = true";
|
||||
error = "laser_sor_stddev_mul must be > 0 when laser_sor_enabled = true";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -84,7 +84,7 @@ std::string SensorGatewayConfig::describe() const
|
||||
out << " laser_sor_enabled : " << (laser_sor_enabled ? "true" : "false") << '\n';
|
||||
if (laser_sor_enabled)
|
||||
{
|
||||
out << " laser_sor_mean_k : " << laser_sor_mean_k << " điểm\n";
|
||||
out << " laser_sor_mean_k : " << laser_sor_mean_k << " points\n";
|
||||
out << " laser_sor_stddev_mul : " << laser_sor_stddev_mul << '\n';
|
||||
}
|
||||
return out.str();
|
||||
@@ -125,6 +125,19 @@ bool SensorGateway::configure(const SensorGatewayConfig& config, std::string& er
|
||||
return true;
|
||||
}
|
||||
|
||||
void SensorGateway::attachTelemetry(RuntimeStats* telemetry)
|
||||
{
|
||||
telemetry_ = telemetry;
|
||||
if (telemetry_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
section_static_map_ = telemetry_->section("sensors.staticMap");
|
||||
section_laser_ = telemetry_->section("sensors.laserScan");
|
||||
section_cloud_ = telemetry_->section("sensors.pointCloud");
|
||||
section_depth_ = telemetry_->section("sensors.depthCamera");
|
||||
}
|
||||
|
||||
void SensorGateway::attach(robot_costmap_2d::LayeredCostmap* global,
|
||||
robot_costmap_2d::LayeredCostmap* local)
|
||||
{
|
||||
@@ -167,9 +180,9 @@ void SensorGateway::warnAboutUnreachableLayers(robot_costmap_2d::LayeredCostmap*
|
||||
if (layer->getType() == robot_costmap_2d::LayerType::OBSTACLE_LAYER)
|
||||
{
|
||||
robot::log_warning(
|
||||
"[SensorGateway] costmap %s: layer '%s' kiểu ObstacleLayer sẽ KHÔNG nhận dữ liệu cảm "
|
||||
"biến — cổng này đẩy vật cản theo LayerType::VOXEL_LAYER. Đổi sang 'type: VoxelLayer' "
|
||||
"trong danh sách plugins nếu layer đó cần dữ liệu.\n",
|
||||
"[SensorGateway] costmap %s: layer '%s' of type ObstacleLayer will NOT receive sensor "
|
||||
"data — this gateway pushes obstacles as LayerType::VOXEL_LAYER. Switch it to 'type: "
|
||||
"VoxelLayer' in the plugins list if that layer needs data.\n",
|
||||
which, layer->getName().c_str());
|
||||
}
|
||||
}
|
||||
@@ -241,7 +254,7 @@ void dispatchTo(robot_costmap_2d::LayeredCostmap* costmap, const T& value,
|
||||
++stats.layer_exceptions;
|
||||
robot::log_error_throttle(
|
||||
kHotPathLogThrottle,
|
||||
"[SensorGateway] layer '%s' (%s) ném exception khi nhận '%s': %s\n",
|
||||
"[SensorGateway] layer '%s' (%s) threw an exception while taking '%s': %s\n",
|
||||
layer->getName().c_str(), toString(type), name.c_str(), ex.what());
|
||||
}
|
||||
}
|
||||
@@ -255,11 +268,12 @@ void SensorGateway::pushStaticMap(const std::string& name, const robot_nav_msgs:
|
||||
{
|
||||
++stats_.dropped_no_costmap;
|
||||
robot::log_warning_throttle(kHotPathLogThrottle,
|
||||
"[SensorGateway] bỏ static map '%s': chưa gắn costmap nào\n",
|
||||
"[SensorGateway] dropping static map '%s': no costmap attached\n",
|
||||
name.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
ScopedSection timer(telemetry_, section_static_map_);
|
||||
dispatchTo(global_costmap_, map, robot_costmap_2d::LayerType::STATIC_LAYER, name, stats_);
|
||||
dispatchTo(local_costmap_, map, robot_costmap_2d::LayerType::STATIC_LAYER, name, stats_);
|
||||
}
|
||||
@@ -270,11 +284,12 @@ void SensorGateway::pushLaserScan(const std::string& name, const robot_sensor_ms
|
||||
{
|
||||
++stats_.dropped_no_costmap;
|
||||
robot::log_warning_throttle(kHotPathLogThrottle,
|
||||
"[SensorGateway] bỏ laser scan '%s': chưa gắn costmap nào\n",
|
||||
"[SensorGateway] dropping laser scan '%s': no costmap attached\n",
|
||||
name.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
ScopedSection timer(telemetry_, section_laser_);
|
||||
dispatchTo(local_costmap_, scan, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
|
||||
dispatchTo(global_costmap_, scan, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
|
||||
}
|
||||
@@ -286,11 +301,12 @@ void SensorGateway::pushPointCloud(const std::string& name,
|
||||
{
|
||||
++stats_.dropped_no_costmap;
|
||||
robot::log_warning_throttle(kHotPathLogThrottle,
|
||||
"[SensorGateway] bỏ point cloud '%s': chưa gắn costmap nào\n",
|
||||
"[SensorGateway] dropping point cloud '%s': no costmap attached\n",
|
||||
name.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
ScopedSection timer(telemetry_, section_cloud_);
|
||||
dispatchTo(local_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
|
||||
dispatchTo(global_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
|
||||
}
|
||||
@@ -302,11 +318,12 @@ void SensorGateway::pushPointCloud2(const std::string& name,
|
||||
{
|
||||
++stats_.dropped_no_costmap;
|
||||
robot::log_warning_throttle(kHotPathLogThrottle,
|
||||
"[SensorGateway] bỏ point cloud2 '%s': chưa gắn costmap nào\n",
|
||||
"[SensorGateway] dropping point cloud2 '%s': no costmap attached\n",
|
||||
name.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
ScopedSection timer(telemetry_, section_cloud_);
|
||||
dispatchTo(local_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
|
||||
dispatchTo(global_costmap_, cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, name, stats_);
|
||||
}
|
||||
@@ -323,11 +340,13 @@ void SensorGateway::pushDepthCameraData(const std::string& topic,
|
||||
{
|
||||
++stats_.dropped_no_costmap;
|
||||
robot::log_warning_throttle(kHotPathLogThrottle,
|
||||
"[SensorGateway] bỏ depth camera '%s': chưa gắn costmap nào\n",
|
||||
"[SensorGateway] dropping depth camera '%s': no costmap attached\n",
|
||||
topic.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
ScopedSection timer(telemetry_, section_depth_);
|
||||
|
||||
// Phải giữ nguyên dạng ConstPtr: layer so `typeid(DepthCameraData::ConstPtr)`. Truyền giá trị sẽ
|
||||
// rơi im lặng qua mọi nhánh của handleImpl.
|
||||
dispatchTo(local_costmap_, data, robot_costmap_2d::LayerType::VOXEL_LAYER, topic, stats_);
|
||||
|
||||
@@ -12,11 +12,48 @@
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/robot.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;
|
||||
}
|
||||
}
|
||||
|
||||
NavigationRuntime::NavigationRuntime() = default;
|
||||
|
||||
NavigationRuntime::~NavigationRuntime()
|
||||
@@ -31,13 +68,13 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf
|
||||
{
|
||||
if (built_ || costmapsReady())
|
||||
{
|
||||
error = "NavigationRuntime::buildCostmaps() gọi lần thứ hai";
|
||||
error = "NavigationRuntime::buildCostmaps() called twice";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!tf)
|
||||
{
|
||||
error = "NavigationRuntime cần TF buffer khác null";
|
||||
error = "NavigationRuntime needs a non-null TF buffer";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -51,14 +88,24 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf
|
||||
//
|
||||
// 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("không dựng được costmap: ") + ex.what();
|
||||
error = std::string("could not build costmap: ") + ex.what();
|
||||
global_costmap_.reset();
|
||||
local_costmap_.reset();
|
||||
return false;
|
||||
@@ -67,16 +114,34 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf
|
||||
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());
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -84,18 +149,24 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
||||
{
|
||||
if (built_)
|
||||
{
|
||||
error = "NavigationRuntime::buildRunners() gọi lần thứ hai";
|
||||
error = "NavigationRuntime::buildRunners() called twice";
|
||||
return false;
|
||||
}
|
||||
if (!costmapsReady())
|
||||
{
|
||||
error = "buildRunners() gọi trước buildCostmaps()";
|
||||
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))
|
||||
{
|
||||
@@ -126,8 +197,22 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
||||
// 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: có behavior recovery nạp hỏng; chạy tiếp "
|
||||
"với %zu behavior còn lại.\n", recovery_.behaviorCount());
|
||||
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.
|
||||
@@ -137,13 +222,47 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
||||
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: có action handler nạp hỏng; chạy tiếp với "
|
||||
"%zu handler còn lại.\n", action_.handlerCount());
|
||||
robot::log_warning("[move_base2] NavigationRuntime: an action handler failed to load; "
|
||||
"continuing with the remaining %zu handler(s).\n", action_.handlerCount());
|
||||
}
|
||||
|
||||
// --- 6. Kiểm cấu hình sau cùng -----------------------------------------------------------------
|
||||
// --- 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();
|
||||
@@ -151,7 +270,7 @@ bool NavigationRuntime::buildRunners(std::string& error)
|
||||
return false;
|
||||
}
|
||||
|
||||
robot::log_info("[move_base2] NavigationRuntime dựng xong:\n%s", config_.describe().c_str());
|
||||
robot::log_info("[move_base2] NavigationRuntime built:\n%s", config_.describe().c_str());
|
||||
|
||||
built_ = true;
|
||||
return true;
|
||||
@@ -165,11 +284,17 @@ void NavigationRuntime::start()
|
||||
}
|
||||
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_)
|
||||
{
|
||||
@@ -181,6 +306,54 @@ void NavigationRuntime::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;
|
||||
@@ -196,6 +369,7 @@ ControlLoopDeps NavigationRuntime::deps()
|
||||
deps.recovery = &recovery_;
|
||||
deps.mission = &mission_;
|
||||
deps.action = &action_;
|
||||
deps.costmap_status = &costmap_status_;
|
||||
return deps;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ NavigationServer::NavigationServer()
|
||||
// ngay từ lúc dựng — trước cả initialize().
|
||||
nav_feedback_ = std::make_shared<robot::move_base_core::NavFeedback>();
|
||||
nav_feedback_->navigation_state = robot::move_base_core::State::PENDING;
|
||||
nav_feedback_->feed_back_str = "chưa khởi tạo";
|
||||
nav_feedback_->feed_back_str = "not initialized";
|
||||
nav_feedback_->goal_checked = false;
|
||||
nav_feedback_->is_ready = false;
|
||||
}
|
||||
@@ -60,7 +60,7 @@ bool NavigationServer::startControlThread(double frequency)
|
||||
{
|
||||
if (!loop_.initialized())
|
||||
{
|
||||
robot::log_error("[move_base2] startControlThread() trước khi control loop được cấu hình.\n");
|
||||
robot::log_error("[move_base2] startControlThread() before the control loop was configured.\n");
|
||||
return false;
|
||||
}
|
||||
if (control_thread_running_.load())
|
||||
@@ -69,23 +69,36 @@ bool NavigationServer::startControlThread(double frequency)
|
||||
}
|
||||
if (!(frequency > 0.0))
|
||||
{
|
||||
robot::log_error("[move_base2] controller_frequency phải > 0 [Hz], nhận %.3f.\n", frequency);
|
||||
robot::log_error("[move_base2] controller_frequency must be > 0 [Hz], got %.3f.\n", frequency);
|
||||
return false;
|
||||
}
|
||||
|
||||
control_thread_running_.store(true);
|
||||
control_thread_ = std::thread([this, frequency]() {
|
||||
if (stats_ != nullptr)
|
||||
{
|
||||
stats_->registerCurrentThread("move_base2/control");
|
||||
}
|
||||
|
||||
robot::Rate rate(frequency);
|
||||
while (control_thread_running_.load())
|
||||
{
|
||||
// Bỏ qua giá trị trả về: false chỉ nghĩa là yêu cầu hiện tại vừa kết thúc, không phải lý do
|
||||
// dừng vòng lặp — thread phải sống để nhận goal kế tiếp.
|
||||
spinOnce();
|
||||
|
||||
// In bảng thống kê nằm NGOÀI phần đo của cycle: chi phí của chính công cụ đo không được tính
|
||||
// vào chi phí của runtime, nếu không mỗi lần in lại thành một đỉnh giả trong cột "đỉnh [ms]".
|
||||
if (stats_ != nullptr)
|
||||
{
|
||||
stats_->tick();
|
||||
}
|
||||
|
||||
rate.sleep();
|
||||
}
|
||||
});
|
||||
|
||||
robot::log_info("[move_base2] control thread chạy ở %.2f Hz.\n", frequency);
|
||||
robot::log_info("[move_base2] control thread running at %.2f Hz.\n", frequency);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -108,7 +121,7 @@ bool NavigationServer::configureLoop(const ControlLoopConfig& config, const Cont
|
||||
if (!loop_.configure(config, deps, error))
|
||||
{
|
||||
nav_feedback_->is_ready = false;
|
||||
nav_feedback_->feed_back_str = "cấu hình lỗi: " + error;
|
||||
nav_feedback_->feed_back_str = "config error: " + error;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -116,7 +129,7 @@ bool NavigationServer::configureLoop(const ControlLoopConfig& config, const Cont
|
||||
|
||||
|
||||
nav_feedback_->is_ready = true;
|
||||
nav_feedback_->feed_back_str = "sẵn sàng";
|
||||
nav_feedback_->feed_back_str = "ready";
|
||||
refreshFeedback();
|
||||
return true;
|
||||
}
|
||||
@@ -156,9 +169,14 @@ void NavigationServer::attachCostmaps(robot_costmap_2d::LayeredCostmap* global,
|
||||
|
||||
bool NavigationServer::spinOnce()
|
||||
{
|
||||
// Bao trọn thân hàm: đây là chi phí một cycle điều khiển, đối chiếu trực tiếp được với
|
||||
// controller_frequency để biết control loop còn giữ được nhịp hay không.
|
||||
ScopedSection cycle_timer(stats_, section_cycle_);
|
||||
|
||||
// Trước khi tính lệnh: đẩy xuống controller những gì host đã đặt từ thread của nó. Đặt ở đây chứ
|
||||
// không ở cuối cycle để trần vận tốc có hiệu lực ngay trong chính cycle này — chậm một cycle
|
||||
// nghĩa là một chu kỳ nữa chạy quá tốc độ mà tầng an toàn vừa yêu cầu hạ.
|
||||
applyPendingFootprint();
|
||||
pushHostInputsToController();
|
||||
drainLifecycleRequests();
|
||||
|
||||
@@ -169,9 +187,16 @@ bool NavigationServer::spinOnce()
|
||||
runtime_->mission().pumpPendingRequest();
|
||||
}
|
||||
|
||||
const bool running = loop_.step();
|
||||
bool running = false;
|
||||
{
|
||||
ScopedSection step_timer(stats_, section_step_);
|
||||
running = loop_.step();
|
||||
}
|
||||
publishCommand();
|
||||
cachePlans();
|
||||
{
|
||||
ScopedSection cache_timer(stats_, section_cache_plans_);
|
||||
cachePlans();
|
||||
}
|
||||
refreshFeedback();
|
||||
return running;
|
||||
}
|
||||
@@ -253,9 +278,31 @@ robot::move_base_core::State NavigationServer::toHostState(NavigationState state
|
||||
return HostState::LOST;
|
||||
}
|
||||
|
||||
bool NavigationServer::missionHasPendingWork() const
|
||||
{
|
||||
return runtime_ != nullptr && runtime_->missionLayer().started() &&
|
||||
runtime_->mission().hasActiveMission();
|
||||
}
|
||||
|
||||
void NavigationServer::refreshFeedback()
|
||||
{
|
||||
nav_feedback_->navigation_state = toHostState(loop_.state());
|
||||
robot::move_base_core::State host_state = toHostState(loop_.state());
|
||||
|
||||
// Một order nhiều chặng: lõi về SUCCEEDED sau MỖI chặng, còn order thì chưa xong. Host suy "order
|
||||
// hoàn thành" thẳng từ SUCCEEDED (amr_vda_5050_client_api.cpp:1062, 1092), nên báo nguyên trạng
|
||||
// là báo cho fleet master rằng robot đã tới node cuối trong khi nó mới đi được nửa tuyến.
|
||||
//
|
||||
// ACTIVE là ánh xạ đúng cho khoảng giữa hai chặng: "yêu cầu đang được xử lý, chưa xong" — và
|
||||
// KHÔNG phải CONTROLLING, vì robot lúc này đứng yên chờ chặng kế tiếp (host suy `driving` từ
|
||||
// CONTROLLING, :1233). PENDING cũng phải che: lõi rơi về IDLE trong đúng cycle trước khi chặng
|
||||
// sau được đẩy xuống.
|
||||
if (missionHasPendingWork() && (host_state == robot::move_base_core::State::SUCCEEDED ||
|
||||
host_state == robot::move_base_core::State::PENDING))
|
||||
{
|
||||
host_state = robot::move_base_core::State::ACTIVE;
|
||||
}
|
||||
|
||||
nav_feedback_->navigation_state = host_state;
|
||||
|
||||
const char* reason = loop_.lastReason();
|
||||
if (reason != nullptr && reason[0] != '\0')
|
||||
@@ -293,17 +340,35 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
|
||||
if (!runtime_->buildCostmaps(tf_, error))
|
||||
{
|
||||
runtime_.reset();
|
||||
stats_ = nullptr;
|
||||
nav_feedback_->is_ready = false;
|
||||
nav_feedback_->feed_back_str = "không dựng được costmap: " + error;
|
||||
robot::log_error("[move_base2] initialize() thất bại: %s\n", error.c_str());
|
||||
nav_feedback_->feed_back_str = "could not build costmap: " + error;
|
||||
robot::log_error("[move_base2] initialize() failed: %s\n", error.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
// Telemetry đã tồn tại từ buildCostmaps (nó phải có mặt trước costmap để chụp được thread của
|
||||
// costmap). Mượn con trỏ và đăng ký các đoạn công việc của chính server ở đây, một lần.
|
||||
stats_ = runtime_->stats();
|
||||
if (stats_ != nullptr && stats_->enabled())
|
||||
{
|
||||
section_cycle_ = stats_->section("control.cycle");
|
||||
section_step_ = stats_->section("control.step");
|
||||
section_cache_plans_ = stats_->section("control.cachePlans");
|
||||
robot::log_info("[move_base2] telemetry ON — printing stats every %.2f s.\n",
|
||||
runtime_->config().runtime_stats_period);
|
||||
}
|
||||
|
||||
// Đường nạp cảm biến chạy trên thread callback của host; đo bằng đoạn công việc mới tách được nó
|
||||
// ra khỏi phần "(không đăng ký)".
|
||||
sensors_.attachTelemetry(stats_);
|
||||
|
||||
if (!configureSensors(runtime_->config().sensors, error))
|
||||
{
|
||||
runtime_.reset();
|
||||
stats_ = nullptr;
|
||||
nav_feedback_->is_ready = false;
|
||||
nav_feedback_->feed_back_str = "cấu hình cảm biến lỗi: " + error;
|
||||
nav_feedback_->feed_back_str = "sensor config error: " + error;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -324,20 +389,27 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
|
||||
attachCostmaps(runtime_->globalCostmap()->getLayeredCostmap(),
|
||||
runtime_->localCostmap()->getLayeredCostmap());
|
||||
|
||||
// Host có thể đã đặt footprint ngay sau khi tạo BaseNavigation nhưng trước initialize(). Áp nó
|
||||
// vào cả hai costmap TRƯỚC khi dựng runner để local planner đầu tiên snapshot đúng hình robot,
|
||||
// thay vì khởi tạo với footprint YAML rồi lập tức phải recreate trong cycle đầu tiên.
|
||||
applyPendingFootprint();
|
||||
|
||||
// --- Pha 2: nạp planner, controller, recovery, action ----------------------------------------
|
||||
if (!runtime_->buildRunners(error))
|
||||
{
|
||||
runtime_.reset();
|
||||
stats_ = nullptr;
|
||||
nav_feedback_->is_ready = false;
|
||||
nav_feedback_->feed_back_str = "không nạp được runtime: " + error;
|
||||
robot::log_error("[move_base2] initialize() thất bại: %s\n", error.c_str());
|
||||
nav_feedback_->feed_back_str = "could not load runtime: " + error;
|
||||
robot::log_error("[move_base2] initialize() failed: %s\n", error.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!configureLoop(runtime_->config().toControlLoopConfig(), runtime_->deps(), error))
|
||||
{
|
||||
runtime_.reset();
|
||||
robot::log_error("[move_base2] initialize() không cấu hình được control loop: %s\n",
|
||||
stats_ = nullptr;
|
||||
robot::log_error("[move_base2] initialize() could not configure the control loop: %s\n",
|
||||
error.c_str());
|
||||
return;
|
||||
}
|
||||
@@ -349,12 +421,20 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
|
||||
if (!loop_.submit(request, reason))
|
||||
{
|
||||
last_reject_reason_ = reason;
|
||||
robot::log_error("[move_base2] từ chối chặng mission %llu: %s\n",
|
||||
robot::log_error("[move_base2] rejecting mission leg %llu: %s\n",
|
||||
static_cast<unsigned long long>(request.mission_sequence_id),
|
||||
reason.c_str());
|
||||
|
||||
// Bắt buộc báo ngược: chặng bị lõi từ chối sẽ không bao giờ sinh ra outcome theo đường bình
|
||||
// thường, mà mission layer đã chuyển sang RUNNING lúc giao nó. Im lặng ở đây là cả order treo
|
||||
// vĩnh viễn ở chặng đó — fleet master chờ một node không bao giờ tới.
|
||||
runtime_->mission().reportOutcome(request.mission_sequence_id, NavigationOutcome::kFailed);
|
||||
}
|
||||
});
|
||||
runtime_->mission().setCancelCallback([this]() { cancel(); });
|
||||
|
||||
// CHỈ huỷ chặng đang chạy: yêu cầu này vừa đi ra từ chính mission layer, gọi cancel() đầy đủ sẽ
|
||||
// vòng ngược lên xoá hàng đợi của nó.
|
||||
runtime_->mission().setCancelCallback([this]() { requestLoopCancel(); });
|
||||
|
||||
// start() sau cùng: cho thread cập nhật costmap chạy khi mọi thứ khác đã lắp xong.
|
||||
runtime_->start();
|
||||
@@ -364,13 +444,14 @@ void NavigationServer::initialize(robot::TFListenerPtr tf)
|
||||
if (!startControlThread(runtime_->config().controller_frequency))
|
||||
{
|
||||
runtime_.reset();
|
||||
stats_ = nullptr;
|
||||
nav_feedback_->is_ready = false;
|
||||
nav_feedback_->feed_back_str = "không khởi động được control thread";
|
||||
nav_feedback_->feed_back_str = "could not start the control thread";
|
||||
return;
|
||||
}
|
||||
|
||||
nav_feedback_->is_ready = true;
|
||||
nav_feedback_->feed_back_str = "sẵn sàng";
|
||||
nav_feedback_->feed_back_str = "ready";
|
||||
refreshFeedback();
|
||||
}
|
||||
|
||||
@@ -382,6 +463,7 @@ void NavigationServer::setRobotFootprint(const std::vector<robot_geometry_msgs::
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
footprint_ = fprt;
|
||||
footprint_pending_ = true;
|
||||
}
|
||||
|
||||
std::vector<robot_geometry_msgs::Point> NavigationServer::getRobotFootprint()
|
||||
@@ -390,6 +472,31 @@ std::vector<robot_geometry_msgs::Point> NavigationServer::getRobotFootprint()
|
||||
return footprint_;
|
||||
}
|
||||
|
||||
void NavigationServer::applyPendingFootprint()
|
||||
{
|
||||
if (runtime_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<robot_geometry_msgs::Point> footprint;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
if (!footprint_pending_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
footprint = footprint_;
|
||||
footprint_pending_ = false;
|
||||
}
|
||||
|
||||
if (!runtime_->setRobotFootprint(footprint))
|
||||
{
|
||||
robot::log_error("[move_base2] NavigationServer: footprint update was not fully applied to "
|
||||
"the navigation runtime.\n");
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// Nhận dữ liệu sensor
|
||||
// ================================================================================================
|
||||
@@ -595,18 +702,33 @@ bool NavigationServer::submit(const NavigationRequest& request)
|
||||
}
|
||||
|
||||
last_reject_reason_ = reason;
|
||||
nav_feedback_->feed_back_str = "từ chối yêu cầu: " + reason;
|
||||
nav_feedback_->feed_back_str = "request rejected: " + reason;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool NavigationServer::moveTo(const robot_geometry_msgs::PoseStamped& goal,
|
||||
double xy_goal_tolerance, double yaw_goal_tolerance)
|
||||
{
|
||||
(void)xy_goal_tolerance;
|
||||
(void)yaw_goal_tolerance;
|
||||
|
||||
// Goal đơn lẻ từ host (RViz /move_base_simple/goal, OPC-UA, ...) cũng là một nguồn mission.
|
||||
// Nếu bỏ qua GoalSourceAdapter thì request vào ControlLoop có mission_sequence_id == 0 và mất
|
||||
// lifecycle/cancel thống nhất với VDA5050. GoalSourceAdapter chịu trách nhiệm validate pose, tạo
|
||||
// SIMPLE_GOAL và gán profile `position`; MissionManager cấp mission id khác 0 trước khi bridge
|
||||
// giao chặng xuống đây.
|
||||
//
|
||||
// Fallback trực tiếp chỉ dành cho cấu hình tương thích cũ: mission layer bị tắt, chưa khởi động,
|
||||
// hoặc không nạp GoalSourceAdapter. Không được coi false là goal đã được layer nhận.
|
||||
if (runtime_ != nullptr && runtime_->missionLayer().submitGoal(goal))
|
||||
{
|
||||
last_reject_reason_.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
NavigationRequest request;
|
||||
request.profile = MotionProfile::kPosition;
|
||||
request.goal = goal;
|
||||
request.tolerance.xy = xy_goal_tolerance;
|
||||
request.tolerance.yaw = yaw_goal_tolerance;
|
||||
return submit(request);
|
||||
}
|
||||
|
||||
@@ -614,11 +736,23 @@ bool NavigationServer::moveTo(const robot_protocol_msgs::Order& msg,
|
||||
const robot_geometry_msgs::PoseStamped& goal,
|
||||
double xy_goal_tolerance, double yaw_goal_tolerance)
|
||||
{
|
||||
(void)xy_goal_tolerance;
|
||||
(void)yaw_goal_tolerance;
|
||||
// Order đi qua mission layer khi layer đang chạy: chỉ ở đó order mới được cắt thành từng chặng
|
||||
// tại node có action, lọc theo `released`, và nối tiếp được khi fleet master release thêm horizon.
|
||||
// Đẩy thẳng xuống lõi là dồn cả order thành MỘT goal — action ở node giữa đường không có chỗ chạy.
|
||||
//
|
||||
// `submitOrder` trả false khi layer tắt hoặc không có nguồn nhận schema `vda5050.order`; lúc đó
|
||||
// rơi xuống đường trực tiếp bên dưới, đúng hành vi đã chạy được trên sim.
|
||||
if (runtime_ != nullptr && runtime_->missionLayer().submitOrder(msg))
|
||||
{
|
||||
last_reject_reason_.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
NavigationRequest request;
|
||||
request.profile = MotionProfile::kPosition;
|
||||
request.goal = goal;
|
||||
request.tolerance.xy = xy_goal_tolerance;
|
||||
request.tolerance.yaw = yaw_goal_tolerance;
|
||||
request.order = std::make_shared<robot_protocol_msgs::Order>(msg);
|
||||
return submit(request);
|
||||
}
|
||||
@@ -627,11 +761,11 @@ bool NavigationServer::dockTo(const std::string& maker,
|
||||
const robot_geometry_msgs::PoseStamped& goal,
|
||||
double xy_goal_tolerance, double yaw_goal_tolerance)
|
||||
{
|
||||
(void)xy_goal_tolerance;
|
||||
(void)yaw_goal_tolerance;
|
||||
NavigationRequest request;
|
||||
request.profile = MotionProfile::kDocking;
|
||||
request.goal = goal;
|
||||
request.tolerance.xy = xy_goal_tolerance;
|
||||
request.tolerance.yaw = yaw_goal_tolerance;
|
||||
request.marker = maker;
|
||||
return submit(request);
|
||||
}
|
||||
@@ -640,11 +774,11 @@ bool NavigationServer::dockTo(const robot_protocol_msgs::Order& msg, const std::
|
||||
const robot_geometry_msgs::PoseStamped& goal,
|
||||
double xy_goal_tolerance, double yaw_goal_tolerance)
|
||||
{
|
||||
(void)xy_goal_tolerance;
|
||||
(void)yaw_goal_tolerance;
|
||||
NavigationRequest request;
|
||||
request.profile = MotionProfile::kDocking;
|
||||
request.goal = goal;
|
||||
request.tolerance.xy = xy_goal_tolerance;
|
||||
request.tolerance.yaw = yaw_goal_tolerance;
|
||||
request.marker = marker;
|
||||
request.order = std::make_shared<robot_protocol_msgs::Order>(msg);
|
||||
return submit(request);
|
||||
@@ -653,20 +787,20 @@ bool NavigationServer::dockTo(const robot_protocol_msgs::Order& msg, const std::
|
||||
bool NavigationServer::moveStraightTo(const robot_geometry_msgs::PoseStamped& goal,
|
||||
double xy_goal_tolerance)
|
||||
{
|
||||
(void)xy_goal_tolerance;
|
||||
NavigationRequest request;
|
||||
request.profile = MotionProfile::kGoStraight;
|
||||
request.goal = goal;
|
||||
request.tolerance.xy = xy_goal_tolerance;
|
||||
return submit(request);
|
||||
}
|
||||
|
||||
bool NavigationServer::rotateTo(const robot_geometry_msgs::PoseStamped& goal,
|
||||
double yaw_goal_tolerance)
|
||||
{
|
||||
(void)yaw_goal_tolerance;
|
||||
NavigationRequest request;
|
||||
request.profile = MotionProfile::kRotate;
|
||||
request.goal = goal;
|
||||
request.tolerance.yaw = yaw_goal_tolerance;
|
||||
return submit(request);
|
||||
}
|
||||
|
||||
@@ -694,6 +828,16 @@ void NavigationServer::resume()
|
||||
}
|
||||
|
||||
void NavigationServer::cancel()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
cancel_requested_ = true;
|
||||
|
||||
// Huỷ từ host là "bỏ cả order", không chỉ chặng đang chạy: không xoá hàng đợi thì mission layer
|
||||
// giao chặng kế tiếp ngay sau khi chặng này dừng, và robot chạy tiếp một tuyến vừa bị huỷ.
|
||||
mission_cancel_requested_ = true;
|
||||
}
|
||||
|
||||
void NavigationServer::requestLoopCancel()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
cancel_requested_ = true;
|
||||
@@ -704,15 +848,18 @@ void NavigationServer::drainLifecycleRequests()
|
||||
bool pause = false;
|
||||
bool resume = false;
|
||||
bool cancel = false;
|
||||
bool mission_cancel = false;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
pause = pause_requested_;
|
||||
resume = resume_requested_;
|
||||
cancel = cancel_requested_;
|
||||
mission_cancel = mission_cancel_requested_;
|
||||
pause_requested_ = false;
|
||||
resume_requested_ = false;
|
||||
cancel_requested_ = false;
|
||||
mission_cancel_requested_ = false;
|
||||
}
|
||||
|
||||
// Huỷ trước: nó thắng mọi thứ khác. Tạm dừng rồi huỷ và huỷ rồi tạm dừng phải cho cùng kết quả.
|
||||
@@ -728,6 +875,19 @@ void NavigationServer::drainLifecycleRequests()
|
||||
{
|
||||
loop_.requestResume();
|
||||
}
|
||||
|
||||
// Huỷ lan tới cả hàng đợi mission. Đi sau lời gọi xuống lõi vì đây là đường bất đồng bộ (xếp vào
|
||||
// event bus, xử lý trên thread sự kiện) — lõi phải phản ứng trước, hàng đợi theo sau.
|
||||
if (mission_cancel && runtime_ != nullptr)
|
||||
{
|
||||
runtime_->missionLayer().cancel();
|
||||
}
|
||||
|
||||
// `pause`/`resume` CỐ Ý không lan xuống mission layer. Chặng đang chạy đã bị chính control loop
|
||||
// giữ lại, nên hàng đợi không giao chặng mới trong lúc tạm dừng dù manager không biết gì.
|
||||
// Ngược lại, đẩy manager sang PAUSED mở ra một đường hỏng thật: `onNavigationDone` chỉ được nhận
|
||||
// khi manager đang RUNNING, nên một chặng kết thúc đúng lúc lệnh pause tới sẽ bị **bỏ mất
|
||||
// outcome** — resume xong cả order treo vĩnh viễn ở chặng đó, không lỗi, không log.
|
||||
}
|
||||
|
||||
bool NavigationServer::setTwistLinear(const robot_geometry_msgs::Vector3& linear)
|
||||
|
||||
@@ -104,6 +104,25 @@ const char* toString(RecoveryTrigger trigger)
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const std::vector<std::size_t>& RecoveryRoutes::forTrigger(RecoveryTrigger trigger) const
|
||||
{
|
||||
switch (trigger)
|
||||
{
|
||||
case RecoveryTrigger::kPlanningFailed:
|
||||
return planning_failed;
|
||||
case RecoveryTrigger::kControllingFailed:
|
||||
return controlling_failed;
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return oscillation;
|
||||
}
|
||||
return planning_failed;
|
||||
}
|
||||
|
||||
bool RecoveryRoutes::empty() const
|
||||
{
|
||||
return planning_failed.empty() && controlling_failed.empty() && oscillation.empty();
|
||||
}
|
||||
|
||||
const char* toString(RecoveryOutputKind kind)
|
||||
{
|
||||
switch (kind)
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
/*********************************************************************
|
||||
* move_base2 — hiện thực ActionPort bằng các ActionHandler plugin.
|
||||
* move_base2 — hiện thực ActionPort bằng framework action_core.
|
||||
*
|
||||
* 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 <string>
|
||||
|
||||
#include <robot/robot.h>
|
||||
|
||||
@@ -18,11 +14,9 @@ namespace move_base2
|
||||
|
||||
ActionRunner::~ActionRunner()
|
||||
{
|
||||
// Handler phải chết TRƯỚC factory: factory là thứ giữ .so còn nạp.
|
||||
// Con trỏ này trỏ vào handler thuộc registry_. Bỏ nó trước khi registry_ bị huỷ để không ai còn
|
||||
// đường chạm vào một handler đã chết.
|
||||
active_ = nullptr;
|
||||
by_type_.clear();
|
||||
handlers_.clear();
|
||||
factories_.clear();
|
||||
}
|
||||
|
||||
void ActionRunner::setClock(ClockPort* clock)
|
||||
@@ -35,199 +29,59 @@ void ActionRunner::setNamespace(const std::string& ns)
|
||||
namespace_ = ns;
|
||||
}
|
||||
|
||||
bool ActionRunner::registerHandler(const ActionHandler::Ptr& handler)
|
||||
void ActionRunner::setContext(const action_core::ActionContext& context)
|
||||
{
|
||||
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;
|
||||
context_ = context;
|
||||
}
|
||||
|
||||
ActionHandler* ActionRunner::find(const std::string& action_type) const
|
||||
bool ActionRunner::registerHandler(const action_core::ActionHandler::Ptr& handler)
|
||||
{
|
||||
const auto it = by_type_.find(action_type);
|
||||
return it == by_type_.end() ? nullptr : it->second;
|
||||
return registry_.registerHandler(handler);
|
||||
}
|
||||
|
||||
std::vector<std::string> ActionRunner::supportedActionTypes() const
|
||||
ActionTick ActionRunner::toTick(const action_core::ActionTick& tick)
|
||||
{
|
||||
std::vector<std::string> types;
|
||||
types.reserve(by_type_.size());
|
||||
for (const auto& entry : by_type_)
|
||||
{
|
||||
types.push_back(entry.first);
|
||||
}
|
||||
return types;
|
||||
}
|
||||
ActionTick out;
|
||||
out.message = tick.message;
|
||||
|
||||
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())
|
||||
switch (tick.status)
|
||||
{
|
||||
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;
|
||||
case action_core::ActionStatus::kRunning:
|
||||
out.status = ActionTick::Status::kRunning;
|
||||
break;
|
||||
case action_core::ActionStatus::kSucceeded:
|
||||
out.status = ActionTick::Status::kSucceeded;
|
||||
break;
|
||||
case action_core::ActionStatus::kFailed:
|
||||
out.status = ActionTick::Status::kFailed;
|
||||
break;
|
||||
}
|
||||
|
||||
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;
|
||||
return out;
|
||||
}
|
||||
|
||||
bool ActionRunner::configure(robot::NodeHandle& nh)
|
||||
{
|
||||
if (configured_)
|
||||
{
|
||||
robot::log_error("[move_base2] ActionRunner: configure() gọi lần thứ hai.");
|
||||
robot::log_error("[move_base2] ActionRunner: configure() called twice.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (clock_ == nullptr)
|
||||
{
|
||||
robot::log_error("[move_base2] ActionRunner: thiếu ClockPort — handler không có mốc timeout.");
|
||||
// Registry không biết thời gian; handler thì cần mốc để tự timeout. Thiếu đồng hồ là mọi
|
||||
// handler mất tầng timeout chính của contract.
|
||||
robot::log_error("[move_base2] ActionRunner: missing ClockPort — handlers would have no "
|
||||
"timeout reference.");
|
||||
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;
|
||||
}
|
||||
}
|
||||
registry_.setContext(context_);
|
||||
|
||||
const bool ok = registry_.loadFromConfig(nh, namespace_);
|
||||
configured_ = true;
|
||||
return all_ok;
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool ActionRunner::start(const robot_protocol_msgs::Action& action)
|
||||
@@ -237,27 +91,40 @@ bool ActionRunner::start(const robot_protocol_msgs::Action& action)
|
||||
|
||||
if (!configured_)
|
||||
{
|
||||
robot::log_error("[move_base2] ActionRunner: start() trước configure().");
|
||||
robot::log_error("[move_base2] ActionRunner: start() before configure().");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (action.actionType.empty())
|
||||
{
|
||||
robot::log_error("[move_base2] ActionRunner: action không có actionType.");
|
||||
robot::log_error("[move_base2] ActionRunner: action has no actionType.");
|
||||
return false;
|
||||
}
|
||||
|
||||
ActionHandler* handler = find(action.actionType);
|
||||
action_core::ActionHandler* handler = registry_.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());
|
||||
// Liệt kê luôn những gì ĐƯỢC nhận. Không có nó, người đọc log mở config ra thấy đúng chữ mình
|
||||
// vừa gửi (tên instance) và tưởng đã khai rồi — trong khi khoá định tuyến là `action_types`,
|
||||
// một tên khác nằm ngay bên dưới.
|
||||
std::string accepted;
|
||||
for (const std::string& type : registry_.actionTypes())
|
||||
{
|
||||
accepted += accepted.empty() ? "" : ", ";
|
||||
accepted += type;
|
||||
}
|
||||
|
||||
robot::log_error("[move_base2] ActionRunner: no handler accepts actionType '%s' (id '%s'). "
|
||||
"Accepted actionTypes: [%s]. Lưu ý: khoá định tuyến là `action_types`, không "
|
||||
"phải tên instance trong `handlers`.",
|
||||
action.actionType.c_str(), action.actionId.c_str(),
|
||||
accepted.empty() ? "<none>" : accepted.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').",
|
||||
robot::log_warning("[move_base2] ActionRunner: handler refused to start action '%s' (id '%s').",
|
||||
action.actionType.c_str(), action.actionId.c_str());
|
||||
return false;
|
||||
}
|
||||
@@ -269,18 +136,17 @@ bool ActionRunner::start(const robot_protocol_msgs::Action& action)
|
||||
|
||||
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.
|
||||
ActionTick tick;
|
||||
tick.status = ActionTick::Status::kFailed;
|
||||
tick.message = "update() khi không có action nào đang chạy";
|
||||
tick.message = "update() with no action running";
|
||||
return tick;
|
||||
}
|
||||
|
||||
tick = active_->update(clock_->now());
|
||||
const ActionTick tick = toTick(active_->update(clock_->now()));
|
||||
|
||||
if (tick.status != ActionTick::Status::kRunning)
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
#include <boost/dll/import.hpp>
|
||||
@@ -39,6 +40,17 @@ bool isFiniteTwist(const robot_geometry_msgs::Twist& twist)
|
||||
ControllerRunner::ControllerRunner() = default;
|
||||
ControllerRunner::~ControllerRunner() = default;
|
||||
|
||||
void ControllerRunner::attachStats(RuntimeStats* stats)
|
||||
{
|
||||
stats_ = stats;
|
||||
if (stats_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
section_compute_ = stats_->section("controller.compute");
|
||||
section_local_plan_ = stats_->section("controller.getLocalPlan");
|
||||
}
|
||||
|
||||
bool ControllerRunner::configure(const robot::NodeHandle& nh,
|
||||
const std::shared_ptr<tf3::BufferCore>& tf,
|
||||
robot_costmap_2d::Costmap2DROBOT* costmap, const PosePort* pose,
|
||||
@@ -46,13 +58,13 @@ bool ControllerRunner::configure(const robot::NodeHandle& nh,
|
||||
{
|
||||
if (configured_)
|
||||
{
|
||||
error = "ControllerRunner::configure() gọi lần thứ hai";
|
||||
error = "ControllerRunner::configure() called twice";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (costmap == nullptr)
|
||||
{
|
||||
error = "ControllerRunner cần costmap local khác null";
|
||||
error = "ControllerRunner needs a non-null local costmap";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -60,7 +72,7 @@ bool ControllerRunner::configure(const robot::NodeHandle& nh,
|
||||
{
|
||||
// Gen-2 nhận pose làm THAM SỐ của computeVelocityCommands/isGoalReached; không có nguồn pose
|
||||
// thì không gọi được hàm nào trong hai hàm đó.
|
||||
error = "ControllerRunner cần PosePort khác null";
|
||||
error = "ControllerRunner needs a non-null PosePort";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -72,7 +84,7 @@ bool ControllerRunner::configure(const robot::NodeHandle& nh,
|
||||
|
||||
if (!initial_controller.empty() && !swapPlanner(initial_controller))
|
||||
{
|
||||
error = "không nạp được local planner khởi đầu '" + initial_controller + "'";
|
||||
error = "could not load the initial local planner '" + initial_controller + "'";
|
||||
configured_ = false;
|
||||
return false;
|
||||
}
|
||||
@@ -85,6 +97,35 @@ robot_nav_core2::LocalPlanner* ControllerRunner::acquire(const std::string& name
|
||||
const auto cached = controllers_.find(name);
|
||||
if (cached != controllers_.end())
|
||||
{
|
||||
if (!marker_dirty_)
|
||||
{
|
||||
return cached->second.instance.get();
|
||||
}
|
||||
|
||||
// Marker vừa đổi: instance này có thể đã đọc `maker_name` trong initialize() và không bao giờ
|
||||
// đọc lại. Dựng lại từ factory sẵn có (không dlopen lại); instance mới thay chỗ instance cũ
|
||||
// CHỈ khi initialize() thành công — thất bại thì giữ nguyên cache và trả lỗi để bên gọi từ
|
||||
// chối yêu cầu, không để lại trạng thái nửa vời.
|
||||
try
|
||||
{
|
||||
robot_nav_core2::LocalPlanner::Ptr fresh = cached->second.factory();
|
||||
if (!fresh)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: factory of '%s' returned nullptr while "
|
||||
"rebuilding for the new marker.\n", name.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
fresh->initialize(nh_, name, tf_, costmap_);
|
||||
cached->second.instance = std::move(fresh);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: rebuilding '%s' for the new marker failed: "
|
||||
"%s\n",
|
||||
name.c_str(), ex.what());
|
||||
return nullptr;
|
||||
}
|
||||
marker_dirty_ = false;
|
||||
return cached->second.instance.get();
|
||||
}
|
||||
|
||||
@@ -93,8 +134,8 @@ robot_nav_core2::LocalPlanner* ControllerRunner::acquire(const std::string& 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",
|
||||
robot::log_error("[move_base2] ControllerRunner: no library found for '%s' — check the key "
|
||||
"'%s/library_path' in the YAML and that the .so file exists in devel/lib.\n",
|
||||
name.c_str(), name.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
@@ -108,13 +149,13 @@ robot_nav_core2::LocalPlanner* ControllerRunner::acquire(const std::string& name
|
||||
}
|
||||
catch (const boost::system::system_error& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: không nạp được symbol '%s' từ '%s': %s\n",
|
||||
robot::log_error("[move_base2] ControllerRunner: could not load symbol '%s' from '%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(),
|
||||
robot::log_error("[move_base2] ControllerRunner: error while loading '%s': %s\n", name.c_str(),
|
||||
ex.what());
|
||||
return nullptr;
|
||||
}
|
||||
@@ -125,14 +166,15 @@ robot_nav_core2::LocalPlanner* ControllerRunner::acquire(const std::string& name
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: factory của '%s' ném exception: %s\n",
|
||||
robot::log_error("[move_base2] ControllerRunner: factory of '%s' threw an 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());
|
||||
robot::log_error("[move_base2] ControllerRunner: factory of '%s' returned nullptr.\n",
|
||||
name.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -144,15 +186,59 @@ robot_nav_core2::LocalPlanner* ControllerRunner::acquire(const std::string& name
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: initialize() của '%s' ném exception: %s\n",
|
||||
robot::log_error("[move_base2] ControllerRunner: initialize() of '%s' threw an exception: %s\n",
|
||||
name.c_str(), ex.what());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const auto inserted = controllers_.emplace(name, std::move(loaded));
|
||||
// Instance mới vừa initialize() với `maker_name` hiện hành — marker không còn "chưa được đọc".
|
||||
marker_dirty_ = false;
|
||||
return inserted.first->second.instance.get();
|
||||
}
|
||||
|
||||
bool ControllerRunner::setDockingMarker(const std::string& marker)
|
||||
{
|
||||
if (!configured_)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: setDockingMarker() before configure().\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validate với danh sách `maker_sources` (chuỗi cách nhau bằng space, maker_sources.yaml) —
|
||||
// đúng phép kiểm bản cũ làm ở cửa dockTo (move_base.cpp:1161-1173). Marker lạ phải bị chặn ở
|
||||
// đây: để lọt xuống thì getMaker() của docking planner âm thầm không match source nào và robot
|
||||
// đứng im không lý do.
|
||||
std::string sources;
|
||||
nh_.param("maker_sources", sources, std::string(""));
|
||||
std::stringstream ss(sources);
|
||||
std::string source;
|
||||
bool known = false;
|
||||
while (ss >> source)
|
||||
{
|
||||
if (source == marker)
|
||||
{
|
||||
known = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!known)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: marker '%s' is not listed in maker_sources "
|
||||
"('%s').\n", marker.c_str(), sources.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string current;
|
||||
nh_.param("maker_name", current, std::string(""));
|
||||
if (current != marker)
|
||||
{
|
||||
nh_.setParam("maker_name", marker);
|
||||
marker_dirty_ = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ControllerRunner::applyPendingLimits(robot_nav_core2::LocalPlanner* controller)
|
||||
{
|
||||
if (controller == nullptr)
|
||||
@@ -180,7 +266,8 @@ void ControllerRunner::applyPendingLimits(robot_nav_core2::LocalPlanner* control
|
||||
}
|
||||
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());
|
||||
robot::log_error("[move_base2] ControllerRunner: error while re-applying the velocity limits: "
|
||||
"%s\n", ex.what());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,19 +275,22 @@ bool ControllerRunner::swapPlanner(const std::string& planner_name)
|
||||
{
|
||||
if (!configured_)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: swapPlanner() trước configure().\n");
|
||||
robot::log_error("[move_base2] ControllerRunner: swapPlanner() before configure().\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (planner_name.empty())
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: tên controller rỗng.\n");
|
||||
robot::log_error("[move_base2] ControllerRunner: empty controller name.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (planner_name == active_name_ && active_ != nullptr)
|
||||
if (planner_name == active_name_ && active_ != nullptr && !marker_dirty_)
|
||||
{
|
||||
return true; // Đã đúng controller; không log để khỏi spam ở cửa vào mỗi yêu cầu.
|
||||
// Đã đúng controller; không log để khỏi spam ở cửa vào mỗi yêu cầu. Riêng khi marker vừa đổi
|
||||
// thì KHÔNG được đi tắt: dock lại cùng planner với marker khác phải rơi xuống acquire() để
|
||||
// instance được dựng lại và initialize() đọc `maker_name` mới.
|
||||
return true;
|
||||
}
|
||||
|
||||
robot_nav_core2::LocalPlanner* controller = acquire(planner_name);
|
||||
@@ -213,33 +303,21 @@ bool ControllerRunner::swapPlanner(const std::string& planner_name)
|
||||
active_ = controller;
|
||||
active_name_ = planner_name;
|
||||
has_active_goal_ = false; // Instance mới chưa biết goal nào.
|
||||
active_plan_.clear();
|
||||
applyPendingLimits(active_);
|
||||
|
||||
robot::log_info("[move_base2] ControllerRunner: local planner đang dùng là '%s'.\n",
|
||||
robot::log_info("[move_base2] ControllerRunner: active local planner is '%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");
|
||||
"[move_base2] ControllerRunner: setPlan() with no controller "
|
||||
"loaded.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -247,7 +325,7 @@ bool ControllerRunner::setPlan(const std::vector<robot_geometry_msgs::PoseStampe
|
||||
{
|
||||
// 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");
|
||||
"[move_base2] ControllerRunner: rejecting an empty plan.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -259,7 +337,8 @@ bool ControllerRunner::setPlan(const std::vector<robot_geometry_msgs::PoseStampe
|
||||
if (path.poses.empty())
|
||||
{
|
||||
robot::log_error_throttle(kHotPathLogThrottle,
|
||||
"[move_base2] ControllerRunner: plan chuyển sang Path2D bị rỗng.\n");
|
||||
"[move_base2] ControllerRunner: plan converted to Path2D came out "
|
||||
"empty.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -269,17 +348,84 @@ bool ControllerRunner::setPlan(const std::vector<robot_geometry_msgs::PoseStampe
|
||||
active_->setGoalPose(goal_pose);
|
||||
active_->setPlan(path);
|
||||
has_active_goal_ = true;
|
||||
active_plan_ = plan;
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error_throttle(kHotPathLogThrottle,
|
||||
"[move_base2] ControllerRunner: '%s' ném exception trong setPlan: "
|
||||
"[move_base2] ControllerRunner: '%s' threw an exception in setPlan: "
|
||||
"%s\n", active_name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool ControllerRunner::refreshActivePlanner()
|
||||
{
|
||||
if (!configured_ || active_ == nullptr)
|
||||
{
|
||||
// Chưa có controller active thì không có cache nào cần refresh. Hành vi này giúp footprint có
|
||||
// thể được host đặt trước goal đầu tiên mà không biến thành lỗi khởi tạo.
|
||||
return true;
|
||||
}
|
||||
|
||||
const auto loaded = controllers_.find(active_name_);
|
||||
if (loaded == controllers_.end())
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: active local planner '%s' is absent from "
|
||||
"the plugin cache.\n", active_name_.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool had_active_goal = has_active_goal_;
|
||||
const std::vector<robot_geometry_msgs::PoseStamped> saved_plan = active_plan_;
|
||||
if (had_active_goal && saved_plan.empty())
|
||||
{
|
||||
// Không thay instance cũ nếu không thể khôi phục goal đang chạy. Giữ controller hiện tại vẫn
|
||||
// an toàn hơn việc âm thầm biến navigation thành controller không có plan.
|
||||
robot::log_error("[move_base2] ControllerRunner: active planner '%s' has a goal but no "
|
||||
"cached plan to restore after a footprint change.\n", active_name_.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
robot_nav_core2::LocalPlanner::Ptr fresh;
|
||||
try
|
||||
{
|
||||
fresh = loaded->second.factory();
|
||||
if (!fresh)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: factory of '%s' returned nullptr while "
|
||||
"refreshing its footprint cache.\n", active_name_.c_str());
|
||||
return false;
|
||||
}
|
||||
fresh->initialize(nh_, active_name_, tf_, costmap_);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
// Chỉ thay cache SAU initialize thành công, nên lỗi này không làm mất controller cũ.
|
||||
robot::log_error("[move_base2] ControllerRunner: refreshing '%s' after a footprint change "
|
||||
"failed: %s\n", active_name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
|
||||
loaded->second.instance = std::move(fresh);
|
||||
active_ = loaded->second.instance.get();
|
||||
has_active_goal_ = false;
|
||||
active_plan_.clear();
|
||||
applyPendingLimits(active_);
|
||||
|
||||
if (had_active_goal && !setPlan(saved_plan))
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: could not restore the active plan after "
|
||||
"refreshing '%s' for a footprint change.\n", active_name_.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
robot::log_info("[move_base2] ControllerRunner: refreshed '%s' after the local costmap "
|
||||
"footprint changed.\n", active_name_.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ControllerRunner::currentPose(robot_nav_2d_msgs::Pose2DStamped& pose) const
|
||||
{
|
||||
if (pose_ == nullptr)
|
||||
@@ -302,8 +448,8 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
|
||||
if (!configured_ || active_ == nullptr)
|
||||
{
|
||||
robot::log_error_throttle(kHotPathLogThrottle,
|
||||
"[move_base2] ControllerRunner: computeVelocityCommands() khi chưa "
|
||||
"có controller.\n");
|
||||
"[move_base2] ControllerRunner: computeVelocityCommands() with no "
|
||||
"controller loaded.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -317,7 +463,8 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
|
||||
if (!currentPose(pose))
|
||||
{
|
||||
robot::log_error_throttle(kHotPathLogThrottle,
|
||||
"[move_base2] ControllerRunner: mất pose, không tính lệnh.\n");
|
||||
"[move_base2] ControllerRunner: pose lost, not computing a "
|
||||
"command.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -325,6 +472,9 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
|
||||
|
||||
try
|
||||
{
|
||||
// Đo đúng lời gọi vào plugin, không đo cả hàm: phần còn lại (tra pose, kiểm NaN) là chi phí của
|
||||
// move_base2, còn đây mới là chi phí của local planner đang cấu hình.
|
||||
ScopedSection timer(stats_, section_compute_);
|
||||
// Gen-2 trả THẲNG lệnh (không có cờ thành công/thất bại) và ném exception khi không tính được —
|
||||
// ngược với gen-1. Vì vậy nhánh "không có lệnh hợp lệ" ở đây là nhánh catch.
|
||||
const robot_nav_2d_msgs::Twist2DStamped cmd_2d =
|
||||
@@ -334,7 +484,7 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error_throttle(kHotPathLogThrottle,
|
||||
"[move_base2] ControllerRunner: '%s' không sinh được lệnh: %s\n",
|
||||
"[move_base2] ControllerRunner: '%s' produced no command: %s\n",
|
||||
active_name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
@@ -344,7 +494,8 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd)
|
||||
// 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",
|
||||
"[move_base2] ControllerRunner: '%s' returned a command containing "
|
||||
"NaN/Inf.\n",
|
||||
active_name_.c_str());
|
||||
return false;
|
||||
}
|
||||
@@ -378,6 +529,7 @@ bool ControllerRunner::isGoalReached()
|
||||
if (reached)
|
||||
{
|
||||
has_active_goal_ = false;
|
||||
active_plan_.clear();
|
||||
}
|
||||
return reached;
|
||||
}
|
||||
@@ -386,7 +538,7 @@ bool ControllerRunner::isGoalReached()
|
||||
// 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 "
|
||||
"[move_base2] ControllerRunner: '%s' threw an exception in "
|
||||
"isGoalReached: %s\n", active_name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
@@ -403,6 +555,7 @@ void ControllerRunner::getLocalPlan(robot_nav_2d_msgs::Path2D& plan)
|
||||
|
||||
try
|
||||
{
|
||||
ScopedSection timer(stats_, section_local_plan_);
|
||||
active_->getPlan(plan);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
@@ -410,8 +563,8 @@ void ControllerRunner::getLocalPlan(robot_nav_2d_msgs::Path2D& plan)
|
||||
// Không phải mọi planner đều hỗ trợ; gen-2 cho phép ném. Đây chỉ là dữ liệu hiển thị nên nuốt
|
||||
// exception là đúng — nhưng vẫn log để không ai tưởng rviz đang hiện quỹ đạo thật.
|
||||
robot::log_error_throttle(kHotPathLogThrottle,
|
||||
"[move_base2] ControllerRunner: '%s' không trả được quỹ đạo cục bộ: "
|
||||
"%s\n", active_name_.c_str(), ex.what());
|
||||
"[move_base2] ControllerRunner: '%s' could not return a local "
|
||||
"trajectory: %s\n", active_name_.c_str(), ex.what());
|
||||
plan = robot_nav_2d_msgs::Path2D();
|
||||
}
|
||||
}
|
||||
@@ -423,7 +576,8 @@ void ControllerRunner::setMeasuredVelocity(const robot_geometry_msgs::Twist& vel
|
||||
// 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");
|
||||
"[move_base2] ControllerRunner: dropping a measured velocity "
|
||||
"containing NaN/Inf.\n");
|
||||
return;
|
||||
}
|
||||
measured_velocity_ = velocity;
|
||||
@@ -433,7 +587,8 @@ 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");
|
||||
robot::log_error("[move_base2] ControllerRunner: linear velocity limit contains NaN/Inf, "
|
||||
"ignored.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -463,7 +618,8 @@ bool ControllerRunner::setTwistLinear(const robot_geometry_msgs::Vector3& linear
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: '%s' ném exception trong setTwistLinear: %s\n",
|
||||
robot::log_error("[move_base2] ControllerRunner: '%s' threw an exception in setTwistLinear: "
|
||||
"%s\n",
|
||||
active_name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
@@ -473,7 +629,8 @@ bool ControllerRunner::setTwistAngular(const robot_geometry_msgs::Vector3& angul
|
||||
{
|
||||
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");
|
||||
robot::log_error("[move_base2] ControllerRunner: angular velocity limit contains NaN/Inf, "
|
||||
"ignored.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -491,7 +648,8 @@ bool ControllerRunner::setTwistAngular(const robot_geometry_msgs::Vector3& angul
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] ControllerRunner: '%s' ném exception trong setTwistAngular: %s\n",
|
||||
robot::log_error("[move_base2] ControllerRunner: '%s' threw an exception in setTwistAngular: "
|
||||
"%s\n",
|
||||
active_name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -52,13 +52,20 @@ PlannerRunner::~PlannerRunner()
|
||||
}
|
||||
}
|
||||
|
||||
void PlannerRunner::attachStats(RuntimeStats* stats)
|
||||
{
|
||||
stats_ = stats;
|
||||
section_make_plan_ = (stats_ != nullptr) ? stats_->section("planner.makePlan")
|
||||
: RuntimeStats::kInvalidSection;
|
||||
}
|
||||
|
||||
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";
|
||||
error = "PlannerRunner::configure() called twice";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -66,7 +73,7 @@ bool PlannerRunner::configure(const robot::NodeHandle& nh,
|
||||
{
|
||||
// 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";
|
||||
error = "PlannerRunner needs a non-null global costmap";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -76,7 +83,7 @@ bool PlannerRunner::configure(const robot::NodeHandle& nh,
|
||||
|
||||
if (!initial_planner.empty() && !swapPlanner(initial_planner))
|
||||
{
|
||||
error = "không nạp được global planner khởi đầu '" + initial_planner + "'";
|
||||
error = "could not load the initial global planner '" + initial_planner + "'";
|
||||
configured_ = false;
|
||||
return false;
|
||||
}
|
||||
@@ -102,8 +109,8 @@ robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& nam
|
||||
|
||||
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",
|
||||
robot::log_error("[move_base2] PlannerRunner: no library found for '%s' — check the key "
|
||||
"'%s/library_path' in the YAML and that the .so file exists in devel/lib.\n",
|
||||
name.c_str(), name.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
@@ -117,13 +124,14 @@ robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& nam
|
||||
}
|
||||
catch (const boost::system::system_error& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] PlannerRunner: không nạp được symbol '%s' từ '%s': %s\n",
|
||||
robot::log_error("[move_base2] PlannerRunner: could not load symbol '%s' from '%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());
|
||||
robot::log_error("[move_base2] PlannerRunner: error while loading '%s': %s\n",
|
||||
name.c_str(), ex.what());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -133,14 +141,15 @@ robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& nam
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] PlannerRunner: factory của '%s' ném exception: %s\n",
|
||||
robot::log_error("[move_base2] PlannerRunner: factory of '%s' threw an 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());
|
||||
robot::log_error("[move_base2] PlannerRunner: factory of '%s' returned nullptr.\n",
|
||||
name.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -151,7 +160,7 @@ robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& nam
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[move_base2] PlannerRunner: initialize() của '%s' ném exception: %s\n",
|
||||
robot::log_error("[move_base2] PlannerRunner: initialize() of '%s' threw an exception: %s\n",
|
||||
name.c_str(), ex.what());
|
||||
return nullptr;
|
||||
}
|
||||
@@ -160,7 +169,8 @@ robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& nam
|
||||
{
|
||||
// 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());
|
||||
robot::log_error("[move_base2] PlannerRunner: '%s' reported an initialize() failure.\n",
|
||||
name.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -174,13 +184,13 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
|
||||
{
|
||||
if (!configured_)
|
||||
{
|
||||
robot::log_error("[move_base2] PlannerRunner: swapPlanner() trước configure().\n");
|
||||
robot::log_error("[move_base2] PlannerRunner: swapPlanner() before configure().\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (planner_name.empty())
|
||||
{
|
||||
robot::log_error("[move_base2] PlannerRunner: tên planner rỗng.\n");
|
||||
robot::log_error("[move_base2] PlannerRunner: empty planner name.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -213,7 +223,7 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
|
||||
}
|
||||
|
||||
active_name_ = planner_name;
|
||||
robot::log_info("[move_base2] PlannerRunner: global planner đang dùng là '%s'.\n",
|
||||
robot::log_info("[move_base2] PlannerRunner: active global planner is '%s'.\n",
|
||||
planner_name.c_str());
|
||||
return true;
|
||||
}
|
||||
@@ -234,14 +244,14 @@ bool PlannerRunner::startPlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
{
|
||||
if (!configured_)
|
||||
{
|
||||
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: startPlan() trước configure().\n");
|
||||
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: startPlan() before 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");
|
||||
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: start or goal contains NaN/Inf, "
|
||||
"not starting a planning attempt.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -249,7 +259,8 @@ bool PlannerRunner::startPlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
|
||||
if (active_ == nullptr)
|
||||
{
|
||||
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: startPlan() khi chưa có planner.\n");
|
||||
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: startPlan() with no planner "
|
||||
"loaded.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -317,6 +328,12 @@ void PlannerRunner::cancelPlan()
|
||||
|
||||
void PlannerRunner::threadBody()
|
||||
{
|
||||
if (stats_ != nullptr)
|
||||
{
|
||||
// Phải đăng ký TỪ chính thread này: nhãn được gắn theo tid của thread đang chạy.
|
||||
stats_->registerCurrentThread("move_base2/planner");
|
||||
}
|
||||
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
|
||||
while (true)
|
||||
@@ -346,6 +363,7 @@ void PlannerRunner::threadBody()
|
||||
|
||||
try
|
||||
{
|
||||
ScopedSection timer(stats_, section_make_plan_);
|
||||
// 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_)
|
||||
@@ -355,14 +373,14 @@ void PlannerRunner::threadBody()
|
||||
{
|
||||
// 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());
|
||||
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: plugin threw an exception while "
|
||||
"making a 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");
|
||||
robot::log_error_throttle(5.0, "[move_base2] PlannerRunner: plugin threw an unknown "
|
||||
"exception while making a plan.\n");
|
||||
ok = false;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,12 @@
|
||||
*********************************************************************/
|
||||
#include <move_base2/runners/recovery_runner.h>
|
||||
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
@@ -89,13 +92,13 @@ bool RecoveryRunner::configure(robot::NodeHandle& nh)
|
||||
{
|
||||
if (configured_)
|
||||
{
|
||||
robot::log_error("[move_base2] RecoveryRunner: configure() gọi lần thứ hai.");
|
||||
robot::log_error("[move_base2] RecoveryRunner: configure() called twice.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (deps_.clock == nullptr || deps_.pose == nullptr)
|
||||
{
|
||||
robot::log_error("[move_base2] RecoveryRunner: thiếu ClockPort hoặc PosePort.");
|
||||
robot::log_error("[move_base2] RecoveryRunner: missing ClockPort or PosePort.");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -105,8 +108,8 @@ bool RecoveryRunner::configure(robot::NodeHandle& nh)
|
||||
|
||||
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());
|
||||
robot::log_error("[move_base2] RecoveryRunner: could not load any behavior from namespace '%s' "
|
||||
"— the runtime will have no recovery path.", namespace_.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -116,16 +119,170 @@ bool RecoveryRunner::configure(robot::NodeHandle& nh)
|
||||
{
|
||||
// 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ỏ.",
|
||||
robot::log_warning("[move_base2] RecoveryRunner: loaded %zu behavior(s), some entries were "
|
||||
"dropped.",
|
||||
registry_.size());
|
||||
return false;
|
||||
}
|
||||
|
||||
robot::log_info("[move_base2] RecoveryRunner: nạp %zu recovery behavior từ '%s'.",
|
||||
robot::log_info("[move_base2] RecoveryRunner: loaded %zu recovery behavior(s) from '%s'.",
|
||||
registry_.size(), namespace_.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RecoveryRunner::configureRoutes(robot::NodeHandle& nh, std::string& error)
|
||||
{
|
||||
error.clear();
|
||||
if (!configured_)
|
||||
{
|
||||
error = "configureRoutes() called before a usable recovery registry was configured";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Luôn dựng fallback trước: schema legacy không có `routes` có nghĩa từng trigger thử toàn bộ
|
||||
// behavior đã nạp theo đúng thứ tự registry cũ.
|
||||
routes_ = RecoveryRoutes{};
|
||||
std::map<std::string, std::size_t> loaded;
|
||||
for (std::size_t index = 0; index < registry_.size(); ++index)
|
||||
{
|
||||
const std::string name = registry_.nameAt(index);
|
||||
loaded.emplace(name, index);
|
||||
routes_.planning_failed.push_back(index);
|
||||
routes_.controlling_failed.push_back(index);
|
||||
routes_.oscillation.push_back(index);
|
||||
}
|
||||
|
||||
const std::string routes_key = namespace_ + "/routes";
|
||||
if (!nh.hasParam(routes_key))
|
||||
{
|
||||
robot::log_info("[move_base2] RecoveryRunner: '%s' absent; using legacy shared recovery "
|
||||
"route with %zu behavior(s).",
|
||||
routes_key.c_str(), registry_.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
YAML::Node configured_routes;
|
||||
try
|
||||
{
|
||||
configured_routes = nh.getParamValue(routes_key);
|
||||
}
|
||||
catch (const YAML::Exception& exception)
|
||||
{
|
||||
error = "could not read " + routes_key + ": " + exception.what();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!configured_routes.IsMap())
|
||||
{
|
||||
error = routes_key + " must be a YAML map";
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::pair<const char*, RecoveryTrigger> expected_routes[] = {
|
||||
{"planning_failed", RecoveryTrigger::kPlanningFailed},
|
||||
{"controlling_failed", RecoveryTrigger::kControllingFailed},
|
||||
{"oscillation", RecoveryTrigger::kOscillation},
|
||||
};
|
||||
|
||||
const auto is_expected_key = [&expected_routes](const std::string& key) {
|
||||
for (const auto& expected : expected_routes)
|
||||
{
|
||||
if (key == expected.first)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
for (const auto& entry : configured_routes)
|
||||
{
|
||||
if (!entry.first.IsScalar())
|
||||
{
|
||||
error = routes_key + " contains a non-scalar route name";
|
||||
return false;
|
||||
}
|
||||
const std::string key = entry.first.as<std::string>();
|
||||
if (!is_expected_key(key))
|
||||
{
|
||||
error = routes_key + " has unsupported trigger '" + key + "'";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& expected : expected_routes)
|
||||
{
|
||||
const std::string trigger_name(expected.first);
|
||||
const YAML::Node route_node = configured_routes[trigger_name];
|
||||
if (!route_node || !route_node.IsSequence())
|
||||
{
|
||||
error = routes_key + "/" + trigger_name + " must be a YAML sequence";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::size_t>* resolved = nullptr;
|
||||
switch (expected.second)
|
||||
{
|
||||
case RecoveryTrigger::kPlanningFailed:
|
||||
resolved = &routes_.planning_failed;
|
||||
break;
|
||||
case RecoveryTrigger::kControllingFailed:
|
||||
resolved = &routes_.controlling_failed;
|
||||
break;
|
||||
case RecoveryTrigger::kOscillation:
|
||||
resolved = &routes_.oscillation;
|
||||
break;
|
||||
}
|
||||
resolved->clear();
|
||||
|
||||
std::set<std::size_t> seen;
|
||||
for (const YAML::Node& behavior_node : route_node)
|
||||
{
|
||||
if (!behavior_node.IsScalar())
|
||||
{
|
||||
error = routes_key + "/" + trigger_name + " must contain only behavior names";
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string behavior_name = behavior_node.as<std::string>();
|
||||
const auto found = loaded.find(behavior_name);
|
||||
if (found == loaded.end())
|
||||
{
|
||||
// Đây là điểm cho phép commit schema trước plugin. Không tạo index giả: StateMachine chỉ
|
||||
// được thấy những index registry thực sự nạp được.
|
||||
robot::log_warning("[move_base2] RecoveryRunner: route '%s' skips '%s' because that "
|
||||
"behavior was not loaded.",
|
||||
trigger_name.c_str(), behavior_name.c_str());
|
||||
continue;
|
||||
}
|
||||
if (!seen.insert(found->second).second)
|
||||
{
|
||||
error = routes_key + "/" + trigger_name + " repeats behavior '" + behavior_name + "'";
|
||||
return false;
|
||||
}
|
||||
resolved->push_back(found->second);
|
||||
}
|
||||
|
||||
if (resolved->empty())
|
||||
{
|
||||
error = routes_key + "/" + trigger_name +
|
||||
" has no behavior that was successfully loaded";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
robot::log_info("[move_base2] RecoveryRunner: routes resolved: planning=%zu controlling=%zu "
|
||||
"oscillation=%zu.",
|
||||
routes_.planning_failed.size(), routes_.controlling_failed.size(),
|
||||
routes_.oscillation.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
const RecoveryRoutes& RecoveryRunner::routes() const
|
||||
{
|
||||
return routes_;
|
||||
}
|
||||
|
||||
std::size_t RecoveryRunner::behaviorCount() const
|
||||
{
|
||||
return registry_.size();
|
||||
@@ -149,15 +306,15 @@ bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
|
||||
|
||||
if (!configured_)
|
||||
{
|
||||
robot::log_error("[move_base2] RecoveryRunner: start() trước configure().");
|
||||
robot::log_error("[move_base2] RecoveryRunner: start() before 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());
|
||||
robot::log_error("[move_base2] RecoveryRunner: index %zu out of range (%zu behavior(s)).",
|
||||
index, registry_.size());
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -170,12 +327,20 @@ bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
|
||||
|
||||
if (!behavior->start(goal, deps_.clock->now()))
|
||||
{
|
||||
robot::log_warning("[move_base2] RecoveryRunner: behavior '%s' từ chối khởi động (%s).",
|
||||
robot::log_warning("[move_base2] RecoveryRunner: behavior '%s' refused to start (%s).",
|
||||
registry_.nameAt(index).c_str(), toString(trigger));
|
||||
return false;
|
||||
}
|
||||
|
||||
active_ = behavior;
|
||||
|
||||
// Log tại SƯỜN (một dòng cho mỗi lượt khởi động, không nằm trên đường tick). Không có dòng này
|
||||
// thì trên robot/sim không cách nào biết đang chạy behavior nào: các plugin chỉ log khi chúng TỪ
|
||||
// CHỐI, nên một chuỗi recovery chạy trơn tru sẽ hoàn toàn im lặng và người vận hành chỉ thấy robot
|
||||
// tự nhiên quay hoặc lùi.
|
||||
robot::log_info("[move_base2] recovery: running '%s' (registry index %zu/%zu, trigger %s).",
|
||||
registry_.nameAt(index).c_str(), index + 1, registry_.size(), toString(trigger));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -188,7 +353,7 @@ RecoveryTick RecoveryRunner::update()
|
||||
// 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";
|
||||
tick.message = "update() with no behavior running";
|
||||
return tick;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*********************************************************************/
|
||||
#include <move_base2/core/state_machine.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
|
||||
namespace move_base2
|
||||
@@ -23,13 +24,13 @@ bool StateMachineConfig::validate(std::string& error) const
|
||||
// giá trị vô nghĩa: khoảng cách chống quẩn âm, và bật chống quẩn mà không cho khoảng cách nào.
|
||||
if (oscillation_distance < 0.0)
|
||||
{
|
||||
error = "oscillation_distance phải >= 0 [m]";
|
||||
error = "oscillation_distance must be >= 0 [m]";
|
||||
return false;
|
||||
}
|
||||
if (oscillation_timeout > 0.0 && oscillation_distance <= 0.0)
|
||||
{
|
||||
error = "bật oscillation_timeout thì oscillation_distance phải > 0 [m], nếu không mọi cycle "
|
||||
"đều bị coi là quẩn";
|
||||
error = "oscillation_timeout is enabled so oscillation_distance must be > 0 [m], otherwise "
|
||||
"every cycle counts as oscillating";
|
||||
return false;
|
||||
}
|
||||
if (planner_patience <= 0.0 && max_planning_retries < 0)
|
||||
@@ -38,18 +39,36 @@ bool StateMachineConfig::validate(std::string& error) const
|
||||
// treo. Tắt cả hai nghĩa là một plugin không bao giờ trả lời sẽ giữ robot ở PLANNING vĩnh viễn,
|
||||
// im lặng, và state machine tin rằng mọi thứ bình thường. Ở chế độ đồng bộ trước đây điều này
|
||||
// vô hại hơn nhiều vì planner treo làm treo luôn control loop — hỏng thì thấy ngay.
|
||||
error = "planner_patience <= 0 [s] và max_planning_retries < 0 cùng lúc: không có gì phát hiện "
|
||||
"được planner treo; đặt ít nhất một trong hai";
|
||||
error = "planner_patience <= 0 [s] and max_planning_retries < 0 at the same time: nothing can "
|
||||
"detect a hung planner; set at least one of them";
|
||||
return false;
|
||||
}
|
||||
if (recovery_enabled && recovery_behavior_count == 0)
|
||||
{
|
||||
// Không phải lỗi cấu hình chết người, nhưng để im lặng thì lúc chạy sẽ ABORTED ngay ở lỗi đầu
|
||||
// tiên mà không ai hiểu vì sao. Bắt buộc khai báo tường minh recovery_enabled = false.
|
||||
error = "recovery_enabled = true nhưng recovery_behavior_count = 0; đặt recovery_enabled = "
|
||||
"false nếu thực sự không muốn có recovery";
|
||||
error = "recovery_enabled = true but recovery_behavior_count = 0; set recovery_enabled = false "
|
||||
"if you really do not want recovery";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!recovery_routes.empty())
|
||||
{
|
||||
const auto valid_route = [this](const std::vector<std::size_t>& route) {
|
||||
return !route.empty() &&
|
||||
std::all_of(route.begin(), route.end(), [this](std::size_t index) {
|
||||
return index < recovery_behavior_count;
|
||||
});
|
||||
};
|
||||
|
||||
if (!valid_route(recovery_routes.planning_failed) ||
|
||||
!valid_route(recovery_routes.controlling_failed) ||
|
||||
!valid_route(recovery_routes.oscillation))
|
||||
{
|
||||
error = "every configured recovery route must be non-empty and reference a loaded behavior";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -58,18 +77,28 @@ std::string StateMachineConfig::describe() const
|
||||
std::ostringstream out;
|
||||
out << "StateMachineConfig:\n";
|
||||
out << " planner_patience : " << planner_patience << " s"
|
||||
<< (planner_patience > 0.0 ? "" : " (tắt)") << '\n';
|
||||
<< (planner_patience > 0.0 ? "" : " (off)") << '\n';
|
||||
out << " controller_patience : " << controller_patience << " s"
|
||||
<< (controller_patience > 0.0 ? "" : " (tắt)") << '\n';
|
||||
<< (controller_patience > 0.0 ? "" : " (off)") << '\n';
|
||||
out << " oscillation_timeout : " << oscillation_timeout << " s"
|
||||
<< (oscillation_timeout > 0.0 ? "" : " (tắt)") << '\n';
|
||||
<< (oscillation_timeout > 0.0 ? "" : " (off)") << '\n';
|
||||
out << " action_patience : " << action_patience << " s"
|
||||
<< (action_patience > 0.0 ? "" : " (tắt — handler tự timeout)") << '\n';
|
||||
<< (action_patience > 0.0 ? "" : " (off — handler times out on its own)") << '\n';
|
||||
out << " oscillation_distance : " << oscillation_distance << " m\n";
|
||||
out << " max_planning_retries : " << max_planning_retries
|
||||
<< (max_planning_retries < 0 ? " (không giới hạn)" : "") << '\n';
|
||||
<< (max_planning_retries < 0 ? " (unlimited)" : "") << '\n';
|
||||
out << " recovery_enabled : " << (recovery_enabled ? "true" : "false") << '\n';
|
||||
out << " recovery_behavior_cnt : " << recovery_behavior_count << '\n';
|
||||
if (recovery_routes.empty())
|
||||
{
|
||||
out << " recovery_routes : legacy shared list\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
out << " recovery_routes : planning=" << recovery_routes.planning_failed.size()
|
||||
<< " controlling=" << recovery_routes.controlling_failed.size()
|
||||
<< " oscillation=" << recovery_routes.oscillation.size() << '\n';
|
||||
}
|
||||
return out.str();
|
||||
}
|
||||
|
||||
@@ -79,13 +108,27 @@ std::string StateMachineConfig::describe() const
|
||||
|
||||
bool StateMachine::configure(const StateMachineConfig& config, std::string& error)
|
||||
{
|
||||
if (!config.validate(error))
|
||||
config_ = config;
|
||||
|
||||
// Schema cũ không có `recovery/routes`: giữ nguyên một list chung cho mọi trigger. Normalise ở
|
||||
// đây, sau khi RecoveryRunner đã báo số plugin nạp được thật, để phần còn lại của state machine
|
||||
// chỉ xử lý route đã resolve.
|
||||
if (config_.recovery_routes.empty())
|
||||
{
|
||||
for (std::size_t index = 0; index < config_.recovery_behavior_count; ++index)
|
||||
{
|
||||
config_.recovery_routes.planning_failed.push_back(index);
|
||||
config_.recovery_routes.controlling_failed.push_back(index);
|
||||
config_.recovery_routes.oscillation.push_back(index);
|
||||
}
|
||||
}
|
||||
|
||||
if (!config_.validate(error))
|
||||
{
|
||||
initialized_ = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
config_ = config;
|
||||
initialized_ = true;
|
||||
reset();
|
||||
return true;
|
||||
@@ -100,6 +143,8 @@ void StateMachine::reset()
|
||||
last_valid_control_ = robot::Time();
|
||||
last_oscillation_reset_ = robot::Time();
|
||||
recovery_index_ = 0;
|
||||
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
recovery_route_cursors_.fill(0);
|
||||
planning_retries_ = 0;
|
||||
request_has_goal_ = true;
|
||||
action_count_ = 0;
|
||||
@@ -131,16 +176,49 @@ void StateMachine::beginPlanningCycle(const robot::Time& now)
|
||||
planning_retries_ = 0;
|
||||
}
|
||||
|
||||
std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger)
|
||||
{
|
||||
switch (trigger)
|
||||
{
|
||||
case RecoveryTrigger::kPlanningFailed:
|
||||
return recovery_route_cursors_[0];
|
||||
case RecoveryTrigger::kControllingFailed:
|
||||
return recovery_route_cursors_[1];
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return recovery_route_cursors_[2];
|
||||
}
|
||||
return recovery_route_cursors_[0];
|
||||
}
|
||||
|
||||
const std::size_t& StateMachine::recoveryRouteCursor(RecoveryTrigger trigger) const
|
||||
{
|
||||
switch (trigger)
|
||||
{
|
||||
case RecoveryTrigger::kPlanningFailed:
|
||||
return recovery_route_cursors_[0];
|
||||
case RecoveryTrigger::kControllingFailed:
|
||||
return recovery_route_cursors_[1];
|
||||
case RecoveryTrigger::kOscillation:
|
||||
return recovery_route_cursors_[2];
|
||||
}
|
||||
return recovery_route_cursors_[0];
|
||||
}
|
||||
|
||||
void StateMachine::escalateToRecovery(RecoveryTrigger trigger, const robot::Time& now,
|
||||
const char* reason, StateMachineOutput& out)
|
||||
{
|
||||
if (!config_.recovery_enabled || recovery_index_ >= config_.recovery_behavior_count)
|
||||
const std::vector<std::size_t>& route = config_.recovery_routes.forTrigger(trigger);
|
||||
const std::size_t cursor = recoveryRouteCursor(trigger);
|
||||
|
||||
if (!config_.recovery_enabled || cursor >= route.size())
|
||||
{
|
||||
finish(NavigationState::kAborted, NavigationOutcome::kFailed, now,
|
||||
"hết recovery behavior khả dụng", out);
|
||||
"no recovery behavior left", out);
|
||||
return;
|
||||
}
|
||||
|
||||
active_recovery_trigger_ = trigger;
|
||||
recovery_index_ = route[cursor];
|
||||
out.start_recovery = true;
|
||||
out.recovery_index = recovery_index_;
|
||||
out.recovery_trigger = trigger;
|
||||
@@ -162,6 +240,8 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
|
||||
{
|
||||
out.accept_request = true;
|
||||
recovery_index_ = 0;
|
||||
active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed;
|
||||
recovery_route_cursors_.fill(0);
|
||||
request_has_goal_ = in.pending_request_has_goal;
|
||||
action_count_ = in.pending_request_action_count;
|
||||
action_index_ = 0;
|
||||
@@ -174,13 +254,13 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
|
||||
// Không goal lẫn action là vi phạm contract; mission layer đã validate nhưng lõi vẫn phải tự
|
||||
// vệ: kết thúc tường minh thay vì treo ở một state không có đường ra.
|
||||
finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now,
|
||||
"yêu cầu không có goal lẫn action", out);
|
||||
"request has neither goal nor action", out);
|
||||
return;
|
||||
}
|
||||
out.start_action = true;
|
||||
out.action_index = 0;
|
||||
action_started_at_ = in.now;
|
||||
enter(NavigationState::kExecutingActions, in.now, "yêu cầu chỉ có action", out);
|
||||
enter(NavigationState::kExecutingActions, in.now, "action-only request", out);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -189,7 +269,7 @@ void StateMachine::acceptPendingRequest(const StateMachineInput& in, StateMachin
|
||||
last_valid_control_ = in.now;
|
||||
last_oscillation_reset_ = in.now;
|
||||
out.reset_oscillation_origin = true;
|
||||
enter(NavigationState::kPlanning, in.now, "nhận yêu cầu mới", out);
|
||||
enter(NavigationState::kPlanning, in.now, "new request accepted", out);
|
||||
}
|
||||
|
||||
bool StateMachine::preemptIfRequested(const StateMachineInput& in, StateMachineOutput& out)
|
||||
@@ -231,7 +311,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// Guard bắt buộc: không bao giờ quyết định điều khiển khi chưa configure.
|
||||
out.state = NavigationState::kIdle;
|
||||
out.velocity_source = VelocitySource::kNone;
|
||||
out.reason = "chưa configure";
|
||||
out.reason = "not configured";
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -239,7 +319,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// không phải chờ thêm một vòng.
|
||||
if (isTerminal(state_))
|
||||
{
|
||||
enter(NavigationState::kIdle, in.now, "yêu cầu đã kết thúc", out);
|
||||
enter(NavigationState::kIdle, in.now, "request finished", out);
|
||||
}
|
||||
|
||||
// Mất pose nghĩa là không biết robot ở đâu. Khi đó controller không được chạy, và không nguồn nào
|
||||
@@ -266,14 +346,14 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
if (in.cancel_requested)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
enter(NavigationState::kCancelling, in.now, "huỷ khi đang lập plan", out);
|
||||
enter(NavigationState::kCancelling, in.now, "cancelled while planning", out);
|
||||
break;
|
||||
}
|
||||
if (in.pause_requested)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
state_before_pause_ = NavigationState::kPlanning;
|
||||
enter(NavigationState::kPaused, in.now, "tạm dừng khi đang lập plan", out);
|
||||
enter(NavigationState::kPaused, in.now, "paused while planning", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -294,7 +374,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// CONTROLLING -> PLANNING -> CONTROLLING sẽ làm mới đồng hồ mỗi vòng, và một controller
|
||||
// hỏng vĩnh viễn sẽ không bao giờ chạm controller_patience. Hai đồng hồ đó chỉ được đặt lại
|
||||
// ở ba chỗ: nhận yêu cầu mới, tiếp tục sau tạm dừng, và sau khi recovery chạy xong.
|
||||
enter(NavigationState::kControlling, in.now, "có plan hợp lệ", out);
|
||||
enter(NavigationState::kControlling, in.now, "valid plan available", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -313,7 +393,8 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
escalateToRecovery(RecoveryTrigger::kPlanningFailed, in.now,
|
||||
retries_exhausted ? "hết lượt lập plan" : "quá hạn lập plan", out);
|
||||
retries_exhausted ? "planning retries exhausted" : "planning timed "
|
||||
"out", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -327,14 +408,14 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
if (in.cancel_requested)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
enter(NavigationState::kCancelling, in.now, "huỷ khi đang bám plan", out);
|
||||
enter(NavigationState::kCancelling, in.now, "cancelled while following the plan", out);
|
||||
break;
|
||||
}
|
||||
if (in.pause_requested)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
state_before_pause_ = NavigationState::kControlling;
|
||||
enter(NavigationState::kPaused, in.now, "tạm dừng khi đang bám plan", out);
|
||||
enter(NavigationState::kPaused, in.now, "paused while following the plan", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -369,10 +450,12 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
out.start_action = true;
|
||||
out.action_index = action_index_;
|
||||
action_started_at_ = in.now;
|
||||
enter(NavigationState::kExecutingActions, in.now, "đạt goal, còn action phải chạy", out);
|
||||
enter(NavigationState::kExecutingActions, in.now, "goal reached, actions still to run",
|
||||
out);
|
||||
break;
|
||||
}
|
||||
finish(NavigationState::kSucceeded, NavigationOutcome::kSucceeded, in.now, "đạt goal", out);
|
||||
finish(NavigationState::kSucceeded, NavigationOutcome::kSucceeded, in.now, "goal reached",
|
||||
out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -384,7 +467,8 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
(in.now - last_oscillation_reset_).toSec() > config_.oscillation_timeout)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
escalateToRecovery(RecoveryTrigger::kOscillation, in.now, "quẩn tại chỗ quá lâu", out);
|
||||
escalateToRecovery(RecoveryTrigger::kOscillation, in.now, "oscillating in place too long",
|
||||
out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -398,7 +482,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
out.stop_planner = true;
|
||||
escalateToRecovery(RecoveryTrigger::kControllingFailed, in.now,
|
||||
"quá hạn sinh lệnh vận tốc", out);
|
||||
"velocity command generation timed out", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -408,7 +492,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// không thì vòng lặp lập-plan-rồi-lại-hỏng sẽ không bao giờ chạm controller_patience.
|
||||
out.start_planner = true;
|
||||
beginPlanningCycle(in.now);
|
||||
enter(NavigationState::kPlanning, in.now, "controller không sinh được lệnh, lập lại plan",
|
||||
enter(NavigationState::kPlanning, in.now, "controller produced no command, replanning",
|
||||
out);
|
||||
break;
|
||||
}
|
||||
@@ -434,7 +518,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
if (in.cancel_requested)
|
||||
{
|
||||
out.cancel_recovery = true;
|
||||
enter(NavigationState::kCancelling, in.now, "huỷ khi đang recovery", out);
|
||||
enter(NavigationState::kCancelling, in.now, "cancelled while recovering", out);
|
||||
break;
|
||||
}
|
||||
if (in.pause_requested)
|
||||
@@ -443,7 +527,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// dài là không an toàn (nó dead-reckon theo thời gian). Resume sẽ lập plan lại từ đầu.
|
||||
out.cancel_recovery = true;
|
||||
state_before_pause_ = NavigationState::kPlanning;
|
||||
enter(NavigationState::kPaused, in.now, "tạm dừng khi đang recovery", out);
|
||||
enter(NavigationState::kPaused, in.now, "paused while recovering", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -451,13 +535,17 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
// Behavior chạy xong (thành công hay không) thì thử lập plan lại. Lỗi kế tiếp sẽ dùng
|
||||
// behavior kế tiếp; hết behavior thì ABORTED.
|
||||
++recovery_index_;
|
||||
std::size_t& cursor = recoveryRouteCursor(active_recovery_trigger_);
|
||||
++cursor;
|
||||
const std::vector<std::size_t>& route =
|
||||
config_.recovery_routes.forTrigger(active_recovery_trigger_);
|
||||
recovery_index_ = cursor < route.size() ? route[cursor] : config_.recovery_behavior_count;
|
||||
out.start_planner = true;
|
||||
beginPlanningCycle(in.now);
|
||||
last_valid_control_ = in.now;
|
||||
enter(NavigationState::kPlanning, in.now,
|
||||
in.recovery == RecoveryFeedback::kSucceeded ? "recovery xong, lập plan lại"
|
||||
: "recovery thất bại, lập plan lại",
|
||||
in.recovery == RecoveryFeedback::kSucceeded ? "recovery finished, replanning"
|
||||
: "recovery failed, replanning",
|
||||
out);
|
||||
break;
|
||||
}
|
||||
@@ -479,7 +567,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
if (in.cancel_requested)
|
||||
{
|
||||
out.cancel_action = true;
|
||||
enter(NavigationState::kCancelling, in.now, "huỷ khi đang chạy action", out);
|
||||
enter(NavigationState::kCancelling, in.now, "cancelled while running an action", out);
|
||||
break;
|
||||
}
|
||||
if (in.pause_requested)
|
||||
@@ -488,7 +576,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// dead-reckon, còn chạy lại một action thiết bị (nâng/hạ, sạc) từ đầu thì không chắc an
|
||||
// toàn — action không idempotent. Tạm dừng chỉ ngừng tick; resume tick tiếp đúng action đó.
|
||||
state_before_pause_ = NavigationState::kExecutingActions;
|
||||
enter(NavigationState::kPaused, in.now, "tạm dừng khi đang chạy action", out);
|
||||
enter(NavigationState::kPaused, in.now, "paused while running an action", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -497,7 +585,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// Action hỏng không có đường recovery: recovery behavior là công cụ phục hồi NAVIGATION
|
||||
// (dọn costmap, lùi, xoay), không giúp gì được một thiết bị đang hỏng. Kết thúc tường minh
|
||||
// để mission layer quyết định làm gì với phần còn lại của order.
|
||||
finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now, "action thất bại",
|
||||
finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now, "action failed",
|
||||
out);
|
||||
break;
|
||||
}
|
||||
@@ -513,7 +601,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
break; // Vẫn ở kExecutingActions, chuyển sang action kế tiếp.
|
||||
}
|
||||
finish(NavigationState::kSucceeded, NavigationOutcome::kSucceeded, in.now,
|
||||
"action cuối đã xong", out);
|
||||
"last action finished", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -524,7 +612,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
{
|
||||
out.cancel_action = true; // Bảo port dừng thiết bị an toàn trước khi kết thúc chặng.
|
||||
finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now,
|
||||
"action quá hạn action_patience", out);
|
||||
"action exceeded action_patience", out);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -546,7 +634,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
|
||||
if (in.cancel_requested)
|
||||
{
|
||||
enter(NavigationState::kCancelling, in.now, "huỷ khi đang tạm dừng", out);
|
||||
enter(NavigationState::kCancelling, in.now, "cancelled while paused", out);
|
||||
break;
|
||||
}
|
||||
if (in.resume_requested)
|
||||
@@ -561,7 +649,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
if (state_before_pause_ == NavigationState::kControlling)
|
||||
{
|
||||
out.run_controller = true;
|
||||
enter(NavigationState::kControlling, in.now, "tiếp tục bám plan", out);
|
||||
enter(NavigationState::kControlling, in.now, "resume following the plan", out);
|
||||
}
|
||||
else if (state_before_pause_ == NavigationState::kExecutingActions)
|
||||
{
|
||||
@@ -570,12 +658,12 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
// gian của action, nếu không resume xong là ABORTED oan ngay lập tức.
|
||||
action_started_at_ = in.now;
|
||||
out.tick_action = true;
|
||||
enter(NavigationState::kExecutingActions, in.now, "tiếp tục chạy action", out);
|
||||
enter(NavigationState::kExecutingActions, in.now, "resume running the action", out);
|
||||
}
|
||||
else
|
||||
{
|
||||
out.start_planner = true;
|
||||
enter(NavigationState::kPlanning, in.now, "tiếp tục lập plan", out);
|
||||
enter(NavigationState::kPlanning, in.now, "resume planning", out);
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -589,7 +677,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
|
||||
if (in.robot_stopped)
|
||||
{
|
||||
finish(NavigationState::kCancelled, NavigationOutcome::kCancelled, in.now,
|
||||
"robot đã dừng hẳn", out);
|
||||
"robot came to a full stop", out);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -49,32 +49,33 @@ bool VelocityLimits::validate(std::string& error) const
|
||||
{
|
||||
if (!(max_vel_x > 0.0))
|
||||
{
|
||||
error = "max_vel_x phải > 0 [m/s]";
|
||||
error = "max_vel_x must be > 0 [m/s]";
|
||||
return false;
|
||||
}
|
||||
if (min_vel_x > 0.0)
|
||||
{
|
||||
error = "min_vel_x là trần tốc độ LÙI nên phải <= 0 [m/s]; đặt 0 nếu cấm lùi";
|
||||
error = "min_vel_x is the REVERSE speed limit so it must be <= 0 [m/s]; set 0 to forbid "
|
||||
"reversing";
|
||||
return false;
|
||||
}
|
||||
if (!(max_vel_theta > 0.0))
|
||||
{
|
||||
error = "max_vel_theta phải > 0 [rad/s]";
|
||||
error = "max_vel_theta must be > 0 [rad/s]";
|
||||
return false;
|
||||
}
|
||||
if (!(max_accel_x > 0.0))
|
||||
{
|
||||
error = "max_accel_x phải > 0 [m/s^2]";
|
||||
error = "max_accel_x must be > 0 [m/s^2]";
|
||||
return false;
|
||||
}
|
||||
if (!(max_accel_theta > 0.0))
|
||||
{
|
||||
error = "max_accel_theta phải > 0 [rad/s^2]";
|
||||
error = "max_accel_theta must be > 0 [rad/s^2]";
|
||||
return false;
|
||||
}
|
||||
if (zero_velocity_epsilon < 0.0)
|
||||
{
|
||||
error = "zero_velocity_epsilon phải >= 0";
|
||||
error = "zero_velocity_epsilon must be >= 0";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -84,9 +85,9 @@ std::string VelocityLimits::describe() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "VelocityLimits:\n";
|
||||
out << " max_vel_x : " << max_vel_x << " m/s (tiến)\n";
|
||||
out << " min_vel_x : " << min_vel_x << " m/s (lùi"
|
||||
<< (min_vel_x == 0.0 ? ", đang cấm lùi" : "") << ")\n";
|
||||
out << " max_vel_x : " << max_vel_x << " m/s (forward)\n";
|
||||
out << " min_vel_x : " << min_vel_x << " m/s (reverse"
|
||||
<< (min_vel_x == 0.0 ? ", reversing forbidden" : "") << ")\n";
|
||||
out << " max_vel_theta : " << max_vel_theta << " rad/s\n";
|
||||
out << " max_accel_x : " << max_accel_x << " m/s^2\n";
|
||||
out << " max_accel_theta : " << max_accel_theta << " rad/s^2\n";
|
||||
|
||||
Reference in New Issue
Block a user