Files
move_base2/src/runners/recovery_runner.cpp
duongtd ab9ed67f97 feat: resume driving during a stationary recovery; host intrusion detector
- recovery_resume: while an allowed stationary behavior (detour_path)
  runs, probe the local planner; its command never reaches the arbiter;
  after N moving cycles cancel the recovery and resume the current plan,
  capped per leg
- host the env_monitor_core IntrusionDetector (EnvContext, footprint)
- runtime config: recovery_resume keys, priest_fallback keys, evade
  max_tf_gap / view_loss_timeout, SBPL detour options, env_monitor tuning
2026-11-27 22:06:59 +07:00

561 lines
19 KiB
C++

/*********************************************************************
* move_base2 — hiện thực RecoveryPort bằng recovery_core.
*
* Author: DuongTD
*********************************************************************/
#include <move_base2/runners/recovery_runner.h>
#include <map>
#include <utility>
#include <robot/robot.h>
#include <yaml-cpp/yaml.h>
namespace move_base2
{
namespace
{
/// Dịch lý do vào recovery sang enum của recovery_core. `switch` đầy đủ để compiler bắt được ngay
/// khi một bên thêm giá trị mới — đó là toàn bộ lý do không dùng cast số.
recovery_core::RecoveryTrigger toCoreTrigger(RecoveryTrigger trigger)
{
switch (trigger)
{
case RecoveryTrigger::kPlanningFailed:
return recovery_core::RecoveryTrigger::kPlanningFailed;
case RecoveryTrigger::kControllingFailed:
return recovery_core::RecoveryTrigger::kControllingFailed;
case RecoveryTrigger::kOscillation:
return recovery_core::RecoveryTrigger::kOscillation;
case RecoveryTrigger::kPathBlocked:
return recovery_core::RecoveryTrigger::kPathBlocked;
case RecoveryTrigger::kOffPath:
return recovery_core::RecoveryTrigger::kOffPath;
case RecoveryTrigger::kCollision:
case RecoveryTrigger::kDetector:
break; // recovery_core chưa có hai lý do này: kUnspecified (chỉ dùng để log)
}
return recovery_core::RecoveryTrigger::kUnspecified;
}
RecoveryOutputKind toPortKind(recovery_core::RecoveryOutputType kind)
{
switch (kind)
{
case recovery_core::RecoveryOutputType::kNone:
return RecoveryOutputKind::kNone;
case recovery_core::RecoveryOutputType::kVelocity:
return RecoveryOutputKind::kVelocity;
case recovery_core::RecoveryOutputType::kPath:
return RecoveryOutputKind::kPath;
}
return RecoveryOutputKind::kNone;
}
} // namespace
void RecoveryRunner::setDeps(const Deps& deps)
{
deps_ = deps;
pose_bridge_.setPort(deps_.pose);
collision_.setCostmap(deps_.local_costmap);
}
void RecoveryRunner::setCostmaps(robot_costmap_2d::Costmap2DROBOT* local,
robot_costmap_2d::Costmap2DROBOT* global)
{
deps_.local_costmap = local;
deps_.global_costmap = global;
collision_.setCostmap(local);
}
void RecoveryRunner::setNamespace(const std::string& ns)
{
namespace_ = ns;
}
void RecoveryRunner::setReferencePlanSource(PlanSource source)
{
reference_plan_bridge_.setSource(std::move(source));
}
void RecoveryRunner::setPlanSource(PlanSource source)
{
plan_bridge_.setSource(std::move(source));
}
void RecoveryRunner::refreshContext()
{
// Trỏ lại mỗi lượt thay vì tin bản cache từ configure(): con trỏ costmap là non-owning và có thể
// bị thay khi runtime dựng lại costmap. Cache nó chính là nguyên nhân lỗi double-free đã ghi nhận
// trong workspace.
collision_.setCostmap(deps_.local_costmap);
ctx_.pose = &pose_bridge_;
ctx_.collision = &collision_;
ctx_.plan = &plan_bridge_;
ctx_.reference_plan = &reference_plan_bridge_;
ctx_.local_costmap = deps_.local_costmap;
ctx_.global_costmap = deps_.global_costmap;
ctx_.tf = deps_.tf;
ctx_.sensors = deps_.sensors;
}
bool RecoveryRunner::configure(robot::NodeHandle& nh)
{
if (configured_)
{
robot::log_error("[move_base2] RecoveryRunner: configure() called twice.");
return false;
}
if (deps_.clock == nullptr || deps_.pose == nullptr)
{
robot::log_error("[move_base2] RecoveryRunner: missing ClockPort or PosePort.");
return false;
}
refreshContext();
const bool all_ok = registry_.loadFromConfig(nh, namespace_, ctx_);
if (registry_.size() == 0)
{
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;
}
configured_ = true;
if (!all_ok)
{
// Một số behavior hỏng nhưng phần còn lại dùng được: giữ chúng lại và báo false để bên gọi
// quyết định (chạy tiếp với ít đường phục hồi hơn, hay dừng khởi động).
robot::log_warning("[move_base2] RecoveryRunner: loaded %zu behavior(s), some entries were "
"dropped.",
registry_.size());
return false;
}
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;
}
// Ba route GỐC bắt buộc phải có; hai route giám sát tuyến là TUỲ CHỌN — thiếu chúng nghĩa là
// cơ chế giám sát tắt, và mọi config đang chạy (viết trước 2026-08-04d) vẫn boot được.
const std::pair<const char*, RecoveryTrigger> expected_routes[] = {
{"planning_failed", RecoveryTrigger::kPlanningFailed},
{"controlling_failed", RecoveryTrigger::kControllingFailed},
{"oscillation", RecoveryTrigger::kOscillation},
};
const std::pair<const char*, RecoveryTrigger> optional_routes[] = {
{"path_blocked", RecoveryTrigger::kPathBlocked},
{"off_path", RecoveryTrigger::kOffPath},
{"collision", RecoveryTrigger::kCollision},
};
const auto is_expected_key = [&expected_routes, &optional_routes](const std::string& key) {
for (const auto& expected : expected_routes)
{
if (key == expected.first)
{
return true;
}
}
for (const auto& optional : optional_routes)
{
if (key == optional.first)
{
return true;
}
}
return false;
};
std::vector<std::string> named_keys;
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))
{
named_keys.push_back(key); // route theo detector (ví dụ `intrusion`): detector trỏ tới theo tên
}
}
const auto route_for = [this](RecoveryTrigger trigger) -> std::vector<std::size_t>* {
switch (trigger)
{
case RecoveryTrigger::kPlanningFailed:
return &routes_.planning_failed;
case RecoveryTrigger::kControllingFailed:
return &routes_.controlling_failed;
case RecoveryTrigger::kOscillation:
return &routes_.oscillation;
case RecoveryTrigger::kPathBlocked:
return &routes_.path_blocked;
case RecoveryTrigger::kOffPath:
return &routes_.off_path;
case RecoveryTrigger::kCollision:
return &routes_.collision;
case RecoveryTrigger::kDetector:
break;
}
return &routes_.planning_failed;
};
// Resolve tên instance -> index registry cho MỘT route. Trả false kèm `error` khi schema sai;
// tên không nạp được thì bỏ qua kèm cảnh báo (cho phép commit schema trước plugin).
//
// Một behavior ĐƯỢC PHÉP xuất hiện nhiều lần trong cùng route: mỗi lần xuất hiện là một lượt thử.
// Đây là cách duy nhất cấp ngân sách cho vòng "thử detour — chờ — nhích lại gần — thử lại"
// (2026-08-05): cursor chỉ reset khi robot đi được quá oscillation_distance, nhưng giữa hai lần
// monitor bắn robot chỉ nhích được ~0.1-0.15 m, nên route không lặp thì cạn ngay sau một cặp
// [detour, wait] dù vật cản sắp vào tầm. Route vẫn hữu hạn — bế tắc thật vẫn ABORT được.
const auto resolve_route = [&](const char* trigger_name, std::vector<std::size_t>* resolved,
const YAML::Node& route_node) {
resolved->clear();
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())
{
// Không tạo index giả: StateMachine chỉ được thấy 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, behavior_name.c_str());
continue;
}
resolved->push_back(found->second);
}
return true;
};
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;
}
if (!resolve_route(expected.first, route_for(expected.second), route_node))
{
return false;
}
if (route_for(expected.second)->empty())
{
error = routes_key + "/" + trigger_name + " has no behavior that was successfully loaded";
return false;
}
}
for (const auto& optional : optional_routes)
{
const std::string trigger_name(optional.first);
const YAML::Node route_node = configured_routes[trigger_name];
if (!route_node)
{
// Không khai = cơ chế giám sát tuyến tắt. Đây là mặc định và là đường lùi.
continue;
}
if (!route_node.IsSequence())
{
error = routes_key + "/" + trigger_name + " must be a YAML sequence";
return false;
}
if (!resolve_route(optional.first, route_for(optional.second), route_node))
{
return false;
}
if (route_for(optional.second)->empty())
{
// Khai route nhưng không behavior nào nạp được: KHÔNG chặn khởi động (navigation vẫn phải
// chạy), nhưng phải hét lên — im lặng ở đây là người vận hành tưởng giám sát đang bật.
robot::log_error("[move_base2] RecoveryRunner: route '%s' was configured but none of its "
"behaviors loaded — that monitor stays DISABLED.",
trigger_name.c_str());
}
}
for (const std::string& key : named_keys)
{
const YAML::Node route_node = configured_routes[key];
if (!route_node.IsSequence())
{
error = routes_key + "/" + key + " must be a YAML sequence";
return false;
}
if (!resolve_route(key.c_str(), &routes_.named[key], route_node))
{
return false;
}
robot::log_info("[move_base2] RecoveryRunner: detector route '%s' resolved with %zu behavior(s).", key.c_str(),
routes_.named[key].size());
}
robot::log_info("[move_base2] RecoveryRunner: routes resolved: planning=%zu controlling=%zu "
"oscillation=%zu path_blocked=%zu off_path=%zu collision=%zu.",
routes_.planning_failed.size(), routes_.controlling_failed.size(),
routes_.oscillation.size(), routes_.path_blocked.size(),
routes_.off_path.size(), routes_.collision.size());
return true;
}
const RecoveryRoutes& RecoveryRunner::routes() const
{
return routes_;
}
std::size_t RecoveryRunner::behaviorCount() const
{
return registry_.size();
}
RecoveryOutputKind RecoveryRunner::outputKind(std::size_t index) const
{
const recovery_core::RecoveryBehavior* behavior = registry_.at(index);
// Index sai -> kNone: không cấp quyền phát vận tốc cho thứ không biết là gì.
return behavior == nullptr ? RecoveryOutputKind::kNone : toPortKind(behavior->outputKind());
}
std::string RecoveryRunner::behaviorName(std::size_t index) const
{
return registry_.nameAt(index);
}
bool RecoveryRunner::start(std::size_t index, RecoveryTrigger trigger)
{
active_ = nullptr;
if (!configured_)
{
robot::log_error("[move_base2] RecoveryRunner: start() before configure().");
return false;
}
recovery_core::RecoveryBehavior* behavior = registry_.at(index);
if (behavior == nullptr)
{
robot::log_error("[move_base2] RecoveryRunner: index %zu out of range (%zu behavior(s)).",
index, registry_.size());
return false;
}
refreshContext();
recovery_core::RecoveryGoal goal;
goal.trigger = toCoreTrigger(trigger);
// Không đặt angle/distance: để behavior dùng default đã cấu hình của nó. Lõi chưa có nguồn thông
// tin nào để chọn góc/quãng tốt hơn config; khi có (ví dụ hình học vật cản), đặt vào đây.
if (!behavior->start(goal, deps_.clock->now()))
{
robot::log_warning("[move_base2] RecoveryRunner: behavior '%s' refused to start (%s).",
registry_.nameAt(index).c_str(), toString(trigger));
return false;
}
active_ = behavior;
active_name_ = registry_.nameAt(index);
active_trigger_ = trigger;
if (status_board_ != nullptr)
{
status_board_->enter(Component::kRecovery, ComponentPhase::kBusy);
}
// 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;
}
RecoveryTick RecoveryRunner::update()
{
RecoveryTick tick;
if (active_ == nullptr)
{
// Contract nói update() chỉ được gọi sau start() trả true. Vẫn guard: state machine hỏng thì
// phải thành "recovery này thất bại" chứ không phải dereference null.
tick.status = RecoveryTick::Status::kFailed;
tick.message = "update() with no behavior running";
return tick;
}
refreshContext();
const RecoveryTick result = toTick(active_->update(deps_.clock->now()));
if (status_board_ != nullptr)
{
if (result.status == RecoveryTick::Status::kRunning)
{
status_board_->progress(Component::kRecovery);
}
else
{
status_board_->enter(Component::kRecovery, ComponentPhase::kIdle);
}
}
// Log tại SƯỜN KẾT THÚC, một dòng cho mỗi lượt (không nằm trên đường tick: kRunning không log).
//
// Không có nó thì một behavior CHẠY RỒI HỎNG hoàn toàn im lặng: bên gọi chỉ thấy state machine
// ghi `recovery=failed` lẫn giữa dòng chuyển state, còn `message` mà behavior đặt sẵn (vd
// "no reachable rejoin point on the plan after 3 attempt(s)") thì không ai in ra. Sim 2026-08-05:
// detour hỏng cả 3 attempt -> route cạn -> ABORTED, và trong log không có chữ "fail" nào của
// recovery. Nhánh TỪ CHỐI KHỞI ĐỘNG đã có log riêng ở start().
if (result.status == RecoveryTick::Status::kFailed)
{
robot::log_warning("[move_base2] RecoveryRunner: behavior '%s' FAILED (trigger %s): %s",
active_name_.c_str(), toString(active_trigger_),
result.message.empty() ? "no reason given" : result.message.c_str());
}
else if (result.status == RecoveryTick::Status::kSucceeded)
{
robot::log_info("[move_base2] RecoveryRunner: behavior '%s' succeeded (trigger %s)%s: %s",
active_name_.c_str(), toString(active_trigger_),
result.has_path ? " with a new path" : "",
result.message.empty() ? "done" : result.message.c_str());
}
return result;
}
void RecoveryRunner::cancel()
{
if (active_ != nullptr)
{
active_->cancel();
}
if (status_board_ != nullptr)
{
// Sau cancel() behavior không được tick nữa (CANCELLING ép tick_recovery=false): hàng phải về
// idle ngay ở đây, không có tick nào sau để làm việc đó. Behavior có việc chạy dài (detour
// worker) phải kết thúc việc đó bên trong cancel() của nó — xem RecoveryBehavior::onCancelRequested.
status_board_->enter(Component::kRecovery, ComponentPhase::kIdle);
}
}
RecoveryTick RecoveryRunner::toTick(const recovery_core::RecoveryResult& result) const
{
RecoveryTick tick;
switch (result.status)
{
case recovery_core::RecoveryStatus::kRunning:
tick.status = RecoveryTick::Status::kRunning;
break;
case recovery_core::RecoveryStatus::kSucceeded:
tick.status = RecoveryTick::Status::kSucceeded;
break;
case recovery_core::RecoveryStatus::kIdle:
// Behavior chưa start mà đã bị tick — lỗi thứ tự gọi, không phải trạng thái bình thường.
tick.status = RecoveryTick::Status::kFailed;
break;
case recovery_core::RecoveryStatus::kCancelled:
// Nhánh này KHÔNG đạt tới được với state machine hiện tại: sau cancel() nó chuyển sang
// CANCELLING, nơi tick_recovery bị ép false. Giữ nhánh lại làm hàng rào nếu sau này ai đó nới
// điều kiện tick — bỏ đi thì kCancelled sẽ rơi vào default và im lặng thành kRunning.
// Recovery resume chuyển sang CONTROLLING cũng không tick lại behavior đã huỷ.
tick.status = RecoveryTick::Status::kFailed;
break;
case recovery_core::RecoveryStatus::kFailed:
tick.status = RecoveryTick::Status::kFailed;
break;
}
if (const robot_geometry_msgs::Twist* cmd = result.velocity())
{
tick.has_velocity = true;
tick.cmd = *cmd;
}
if (const robot_nav_msgs::Path* path = result.pathOut())
{
if (!path->poses.empty())
{
tick.has_path = true;
tick.path = path->poses;
}
}
tick.message = result.message;
return tick;
}
} // namespace move_base2