feat: EnvMonitor thay PathMonitor — giám sát môi trường bằng EDT/geodesic/quỹ đạo thật
Bộ giám sát mới trong ControlLoop (core/env_monitor, core/grid_analysis, ports/environment_port, io/env_logger), thay bốn phép đo của PathMonitor (code cũ còn, tắt bằng path_monitor/enabled: false): - kContact: dò tiếp xúc dọc quỹ đạo local planner (thay cung v/omega), bao tốc độ sqrt(2a(d - margin)) có dư, phanh chỉ khi vượt bao, cờ collision khi kề mũi tĩnh 1 s; cổng xoay tại chỗ theo lệnh controller muốn; hysteresis + xác nhận khi nhả; đứng ra sau detour không dịch robot (nhường controller); giữ phanh khi route khoá thì báo no valid command để controller_patience leo thang. - kStall: cost_to_go = geodesic tới điểm thoát 2 m dọc plan + phần plan còn lại, index plan bám cửa sổ, bộ lọc lật liên thông; cờ no_progress chỉ khi cổng dịch chuyển thực mở (robot không đi được đâu trong 12 s dù lệnh >= 1,5 m) — thay ngân sách replan cho stall. - kUnreachable: liên thông tới điểm thoát, đang ở action log. - EnvLogger ghi JSONL mỗi tick nặng; config/runtime/env_monitor_params.yaml đủ khoá, comment tiếng Việt; ControllerPort::measuredVelocity; FakeEnvironmentPort cho test. Sim 5–6/9: hết churn detour, khe 1,25 m đi qua 0,5 m/s, lượt 6/9 10:15 2 detour/142 s không oan. Test: grid_analysis 31, env_monitor 43, plan_inspector 37, walking_skeleton 87, các bộ khác pass. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017xXjFjr2DQ6rhmhHSW4fk4
This commit is contained in:
@@ -69,6 +69,7 @@ void readBinding(robot::NodeHandle& nh, const std::string& ns, ProfileBinding& b
|
||||
|
||||
void readSensors(robot::NodeHandle& nh, SensorGatewayConfig& sensors);
|
||||
void readDebug(robot::NodeHandle& nh, MoveBase2Config& config);
|
||||
void readEnvMonitor(robot::NodeHandle& nh, MoveBase2Config& config);
|
||||
|
||||
void readSensorStore(robot::NodeHandle& nh, MoveBase2Config& config);
|
||||
|
||||
@@ -271,6 +272,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
readSensorStore(nh, config);
|
||||
readDebug(nh, config);
|
||||
readPathMonitor(nh, config.path_monitor);
|
||||
readEnvMonitor(nh, config);
|
||||
readBool(nh, "docking_requires_marker", config.docking_requires_marker);
|
||||
|
||||
readString(nh, "recovery_namespace", config.recovery_namespace);
|
||||
@@ -320,6 +322,124 @@ void readDebug(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
readBool(debug_nh, "state", config.debug_state);
|
||||
readBool(debug_nh, "plan", config.debug_plan);
|
||||
readBool(debug_nh, "skip", config.debug_skip);
|
||||
readBool(debug_nh, "env", config.debug_env);
|
||||
}
|
||||
|
||||
/// Đọc khối `env_monitor` (xem config/runtime/env_monitor_params.yaml).
|
||||
void readEnvMonitor(robot::NodeHandle& nh, MoveBase2Config& config)
|
||||
{
|
||||
robot::NodeHandle env_nh(nh, "env_monitor");
|
||||
EnvMonitorConfig& m = config.env_monitor;
|
||||
EnvSamplingConfig& s = config.env_sampling;
|
||||
|
||||
readBool(env_nh, "enabled", m.enabled);
|
||||
readDouble(env_nh, "grace_after_new_plan", m.grace_after_new_plan);
|
||||
readDouble(env_nh, "check_period", s.check_period);
|
||||
|
||||
robot::NodeHandle body_nh(env_nh, "body");
|
||||
readDouble(body_nh, "front_offset", s.body_front);
|
||||
readDouble(body_nh, "rear_offset", s.body_rear);
|
||||
readDouble(body_nh, "side_offset", s.body_side);
|
||||
readDouble(body_nh, "padding", s.padding);
|
||||
readInt(body_nh, "lethal_threshold", s.lethal_threshold);
|
||||
|
||||
robot::NodeHandle geo_nh(env_nh, "geometry");
|
||||
readDouble(geo_nh, "horizon", s.horizon);
|
||||
readDouble(geo_nh, "corridor_margin", s.corridor_margin);
|
||||
readDouble(geo_nh, "corridor_cap", s.corridor_cap);
|
||||
readDouble(geo_nh, "target_backoff", s.target_backoff);
|
||||
readDouble(geo_nh, "robot_snap", s.robot_snap);
|
||||
readDouble(geo_nh, "track_back", s.track_back);
|
||||
readDouble(geo_nh, "track_ahead", s.track_ahead);
|
||||
readDouble(geo_nh, "exit_ahead", s.exit_ahead);
|
||||
|
||||
robot::NodeHandle stall_nh(env_nh, "stall");
|
||||
readBool(stall_nh, "enabled", m.stall.enabled);
|
||||
readString(stall_nh, "action", m.stall.action);
|
||||
readDouble(stall_nh, "window_s", m.stall.window_s);
|
||||
readDouble(stall_nh, "window_m", m.stall.window_m);
|
||||
readDouble(stall_nh, "min_commanded", m.stall.min_commanded);
|
||||
readDouble(stall_nh, "eff_on", m.stall.eff_on);
|
||||
readDouble(stall_nh, "eff_off", m.stall.eff_off);
|
||||
readDouble(stall_nh, "confirm", m.stall.confirm);
|
||||
readDouble(stall_nh, "goal_zone", m.stall.goal_zone);
|
||||
readDouble(stall_nh, "slip_on", m.stall.slip_on);
|
||||
readDouble(stall_nh, "slip_time", m.stall.slip_time);
|
||||
readDouble(stall_nh, "min_commanded_since_goal", m.stall.min_commanded_since_goal);
|
||||
readDouble(stall_nh, "retry_backoff", m.stall.retry_backoff);
|
||||
readDouble(stall_nh, "jump_reject", m.stall.jump_reject);
|
||||
readDouble(stall_nh, "disp_window_s", m.stall.disp_window_s);
|
||||
readDouble(stall_nh, "disp_min", m.stall.disp_min);
|
||||
readDouble(stall_nh, "disp_min_commanded", m.stall.disp_min_commanded);
|
||||
|
||||
robot::NodeHandle unreach_nh(env_nh, "unreachable");
|
||||
readBool(unreach_nh, "enabled", m.unreachable.enabled);
|
||||
readString(unreach_nh, "action", m.unreachable.action);
|
||||
readDouble(unreach_nh, "static_on", m.unreachable.static_on);
|
||||
readDouble(unreach_nh, "clean_start_margin", m.unreachable.clean_start_margin);
|
||||
readDouble(unreach_nh, "retry_backoff", m.unreachable.retry_backoff);
|
||||
|
||||
robot::NodeHandle contact_nh(env_nh, "contact");
|
||||
readBool(contact_nh, "enabled", m.contact.enabled);
|
||||
readString(contact_nh, "action", m.contact.action);
|
||||
readBool(contact_nh, "apply_command", m.contact.apply_command);
|
||||
readString(contact_nh, "use_local_plan", s.use_local_plan);
|
||||
readDouble(contact_nh, "local_plan_start_tol", s.local_plan_start_tol);
|
||||
readDouble(contact_nh, "lookahead", s.contact_lookahead);
|
||||
readInt(contact_nh, "confirm_cycles", m.contact.confirm_cycles);
|
||||
readDouble(contact_nh, "trigger_static_time", m.contact.trigger_static_time);
|
||||
readDouble(contact_nh, "clean_start_margin", m.contact.clean_start_margin);
|
||||
readDouble(contact_nh, "brake_decel", m.contact.brake_decel);
|
||||
readDouble(contact_nh, "min_speed", m.contact.min_speed);
|
||||
readDouble(contact_nh, "min_check_speed", m.contact.min_check_speed);
|
||||
readDouble(contact_nh, "release_hysteresis", m.contact.release_hysteresis);
|
||||
readInt(contact_nh, "release_confirm_cycles", m.contact.release_confirm_cycles);
|
||||
readDouble(contact_nh, "envelope_margin", m.contact.envelope_margin);
|
||||
readDouble(contact_nh, "standdown_min_travel", m.contact.standdown_min_travel);
|
||||
readDouble(contact_nh, "standdown_travel", m.contact.standdown_travel);
|
||||
readBool(contact_nh, "envelope", m.contact.envelope);
|
||||
|
||||
robot::NodeHandle budget_nh(env_nh, "replan_budget");
|
||||
readDouble(budget_nh, "min_travel", m.replan.min_travel);
|
||||
readDouble(budget_nh, "escalate_factor", m.replan.escalate_factor);
|
||||
readDouble(budget_nh, "escalate_window_m", m.replan.escalate_window_m);
|
||||
readDouble(budget_nh, "escalate_max", m.replan.escalate_max);
|
||||
|
||||
robot::NodeHandle logger_nh(env_nh, "logger");
|
||||
readBool(logger_nh, "enabled", config.env_logger.enabled);
|
||||
readString(logger_nh, "log_dir", config.env_logger.log_dir);
|
||||
readDouble(logger_nh, "flush_period", config.env_logger.flush_period);
|
||||
|
||||
std::vector<std::string> names;
|
||||
env_nh.param("profiles", names, std::vector<std::string>{});
|
||||
if (!names.empty())
|
||||
{
|
||||
s.profiles.clear();
|
||||
for (const std::string& name : names)
|
||||
{
|
||||
if (name == "position")
|
||||
{
|
||||
s.profiles.push_back(MotionProfile::kPosition);
|
||||
}
|
||||
else if (name == "docking")
|
||||
{
|
||||
s.profiles.push_back(MotionProfile::kDocking);
|
||||
}
|
||||
else if (name == "go_straight")
|
||||
{
|
||||
s.profiles.push_back(MotionProfile::kGoStraight);
|
||||
}
|
||||
else if (name == "rotate")
|
||||
{
|
||||
s.profiles.push_back(MotionProfile::kRotate);
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_warning("[move_base2] env_monitor/profiles: unknown profile '%s', ignored.\n",
|
||||
name.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Đọc cấu hình đường vào cảm biến từ namespace con `sensors`.
|
||||
@@ -594,6 +714,14 @@ bool MoveBase2Config::validate(std::string& error) const
|
||||
return false;
|
||||
}
|
||||
|
||||
if (env_monitor.enabled)
|
||||
{
|
||||
if (!env_monitor.validate(error) || !env_sampling.validate(error) || !env_logger.validate(error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!velocity.validate(error))
|
||||
{
|
||||
return false;
|
||||
@@ -843,6 +971,10 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
|
||||
config.backup_global_planner_name = backup_global_planner_name;
|
||||
config.docking_requires_marker = docking_requires_marker;
|
||||
config.path_monitor = path_monitor;
|
||||
config.env_monitor = env_monitor;
|
||||
config.env_sampling = env_sampling;
|
||||
config.env_logger = env_logger;
|
||||
config.debug_env = debug_env;
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
@@ -157,6 +157,56 @@ bool ControlLoopConfig::PathMonitorConfig::monitors(MotionProfile profile) const
|
||||
return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
|
||||
}
|
||||
|
||||
bool EnvSamplingConfig::monitors(MotionProfile profile) const
|
||||
{
|
||||
return std::find(profiles.begin(), profiles.end(), profile) != profiles.end();
|
||||
}
|
||||
|
||||
bool EnvSamplingConfig::validate(std::string& error) const
|
||||
{
|
||||
if (!std::isfinite(check_period) || check_period <= 0.0)
|
||||
{
|
||||
error = "env_monitor/check_period must be > 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (lethal_threshold < 1 || lethal_threshold > 254)
|
||||
{
|
||||
error = "env_monitor/body/lethal_threshold must be in [1, 254]";
|
||||
return false;
|
||||
}
|
||||
const bool any_body = body_front > 0.0 || body_rear > 0.0 || body_side > 0.0;
|
||||
const bool all_body = body_front > 0.0 && body_rear > 0.0 && body_side > 0.0;
|
||||
if (any_body && !all_body)
|
||||
{
|
||||
error = "env_monitor/body: front_offset, rear_offset and side_offset must all be > 0 [m] when any "
|
||||
"is set (all 0 = use the costmap footprint)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(padding) || padding < 0.0 || !std::isfinite(horizon) || horizon <= 0.0 ||
|
||||
!std::isfinite(corridor_margin) || corridor_margin < 0.0 || !std::isfinite(corridor_cap) ||
|
||||
corridor_cap <= 0.0 || !std::isfinite(target_backoff) || target_backoff < 0.0 ||
|
||||
!std::isfinite(track_back) || track_back < 0.0 || !std::isfinite(track_ahead) || track_ahead <= 0.0 ||
|
||||
!std::isfinite(exit_ahead) || exit_ahead < 0.0 ||
|
||||
!std::isfinite(robot_snap) || robot_snap < 0.0)
|
||||
{
|
||||
error = "env_monitor: padding/corridor_margin/target_backoff/robot_snap/track_back/exit_ahead >= 0, "
|
||||
"horizon/corridor_cap/track_ahead > 0 [m]";
|
||||
return false;
|
||||
}
|
||||
if (use_local_plan != "auto" && use_local_plan != "true" && use_local_plan != "false")
|
||||
{
|
||||
error = "env_monitor/contact/use_local_plan must be auto | true | false";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(local_plan_start_tol) || local_plan_start_tol <= 0.0 ||
|
||||
!std::isfinite(contact_lookahead) || contact_lookahead <= 0.0)
|
||||
{
|
||||
error = "env_monitor/contact: local_plan_start_tol and lookahead must be > 0 [m]";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// ControlLoop
|
||||
// ================================================================================================
|
||||
@@ -291,6 +341,53 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
|
||||
}
|
||||
}
|
||||
|
||||
// EnvMonitor (Test/ENV_MONITOR_PLAN.md): chạy song song PathMonitor ở P3. Không có cổng thì tắt, nhưng
|
||||
// phải kêu nếu config bảo bật.
|
||||
env_logger_.reset();
|
||||
if (config_.env_monitor.enabled)
|
||||
{
|
||||
if (deps_.environment == nullptr)
|
||||
{
|
||||
robot::log_error("[move_base2] env_monitor is enabled but no EnvironmentPort is wired — EnvMonitor "
|
||||
"stays OFF.\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!config_.env_sampling.validate(error) || !env_monitor_.configure(config_.env_monitor, error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
robot::log_info("[move_base2] %s\n sampling : check=%.2f s lethal>=%d padding=%.2f m horizon=%.1f m "
|
||||
"corridor_margin=%.2f m use_local_plan=%s lookahead=%.1f m body=%s\n",
|
||||
config_.env_monitor.describe().c_str(), config_.env_sampling.check_period,
|
||||
config_.env_sampling.lethal_threshold, config_.env_sampling.padding,
|
||||
config_.env_sampling.horizon, config_.env_sampling.corridor_margin,
|
||||
config_.env_sampling.use_local_plan.c_str(), config_.env_sampling.contact_lookahead,
|
||||
config_.env_sampling.body_front > 0.0 ? "config" : "costmap footprint");
|
||||
const bool shadow = config_.env_monitor.stall.action != "recover" &&
|
||||
config_.env_monitor.unreachable.action != "recover" &&
|
||||
config_.env_monitor.contact.action != "recover" &&
|
||||
!config_.env_monitor.contact.apply_command;
|
||||
robot::log_info("[move_base2] EnvMonitor mode: %s\n",
|
||||
shadow ? "SHADOW (log only; no flags, no braking, no speed cap)"
|
||||
: "ACTIVE on at least one verdict or on the command");
|
||||
if (config_.env_logger.enabled)
|
||||
{
|
||||
env_logger_ = std::make_unique<EnvLogger>();
|
||||
if (!env_logger_->open(config_.env_logger, error))
|
||||
{
|
||||
robot::log_error("[move_base2] %s — EnvMonitor runs without the JSONL logger.\n", error.c_str());
|
||||
env_logger_.reset();
|
||||
error.clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_info("[move_base2] EnvMonitor logger writing to %s\n", env_logger_->path().c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
initialized_ = true;
|
||||
reset();
|
||||
return true;
|
||||
@@ -331,6 +428,14 @@ void ControlLoop::reset()
|
||||
resetPathMonitor();
|
||||
has_last_plan_applied_ = false;
|
||||
|
||||
env_monitor_.reset();
|
||||
env_verdict_ = EnvVerdict();
|
||||
env_geometry_ = EnvGeometry();
|
||||
has_last_env_heavy_ = false;
|
||||
has_last_env_debug_ = false;
|
||||
env_brake_ = false;
|
||||
env_used_local_plan_ = false;
|
||||
|
||||
has_outcome_ = false;
|
||||
outcome_report_count_ = 0;
|
||||
last_reason_ = "";
|
||||
@@ -1173,6 +1278,190 @@ void ControlLoop::applyCollisionGuard(const robot_geometry_msgs::PoseStamped& ro
|
||||
}
|
||||
}
|
||||
|
||||
void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt,
|
||||
const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available,
|
||||
bool costmap_stale)
|
||||
{
|
||||
env_brake_ = false;
|
||||
if (!config_.env_monitor.enabled || deps_.environment == nullptr || !env_monitor_.configured())
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!has_active_request_)
|
||||
{
|
||||
// Không có chặng: mọi ngân sách/mốc thuộc chặng cũ. Verdict rỗng.
|
||||
env_monitor_.reset();
|
||||
env_verdict_ = EnvVerdict();
|
||||
env_geometry_ = EnvGeometry();
|
||||
has_last_env_heavy_ = false;
|
||||
env_plan_index_valid_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const EnvSamplingConfig& sampling = config_.env_sampling;
|
||||
const bool monitorable = state_machine_.state() == NavigationState::kControlling && pose_available &&
|
||||
!latest_plan_.empty() && sampling.monitors(active_request_.profile);
|
||||
|
||||
EnvSample s;
|
||||
s.now = now;
|
||||
s.dt = dt;
|
||||
s.costmap_current = !costmap_stale;
|
||||
s.has_plan = monitorable;
|
||||
s.robot_x = robot_pose.pose.position.x;
|
||||
s.robot_y = robot_pose.pose.position.y;
|
||||
const robot_geometry_msgs::Twist& last_cmd = arbiter_.lastCommand();
|
||||
s.v_cmd = last_cmd.linear.x;
|
||||
s.w_cmd = last_cmd.angular.z;
|
||||
robot_geometry_msgs::Twist measured;
|
||||
if (deps_.controller->measuredVelocity(measured))
|
||||
{
|
||||
s.v_meas = measured.linear.x;
|
||||
}
|
||||
s.controller_valid = controller_feedback_ != ControllerFeedback::kNoValidCommand;
|
||||
s.v_controller = env_controller_v_;
|
||||
if (!latest_plan_.empty() && pose_available)
|
||||
{
|
||||
s.d_goal = std::hypot(latest_plan_.back().pose.position.x - robot_pose.pose.position.x,
|
||||
latest_plan_.back().pose.position.y - robot_pose.pose.position.y);
|
||||
}
|
||||
|
||||
if (monitorable)
|
||||
{
|
||||
deps_.environment->refresh();
|
||||
|
||||
double front = sampling.body_front;
|
||||
double rear = sampling.body_rear;
|
||||
double side = sampling.body_side;
|
||||
bool have_body = front > 0.0 && rear > 0.0 && side > 0.0;
|
||||
if (!have_body)
|
||||
{
|
||||
have_body = deps_.environment->robotBodyExtents(front, rear, side);
|
||||
if (!have_body)
|
||||
{
|
||||
robot::log_error_throttle(5.0, "[move_base2] EnvMonitor: no body geometry (costmap footprint "
|
||||
"unavailable, body/*_offset not set) — geometry not sampled.\n");
|
||||
}
|
||||
}
|
||||
|
||||
if (have_body)
|
||||
{
|
||||
const bool heavy_due =
|
||||
!has_last_env_heavy_ || (now - last_env_heavy_).toSec() >= sampling.check_period;
|
||||
if (heavy_due)
|
||||
{
|
||||
// Bám index đơn điệu: detour uốn quanh trụ có đoạn sau đi sát robot, nearest toàn plan nhảy sang đó
|
||||
// và điểm thoát T đổi (cost_to_go +8 m / 1 s, run 5/9 22:35). Plan mới thì tìm lại toàn plan một lần.
|
||||
if (!env_plan_index_valid_ || env_plan_index_ + 1 >= latest_plan_.size())
|
||||
{
|
||||
env_plan_index_ = nearestIndex(latest_plan_, robot_pose);
|
||||
env_plan_index_valid_ = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
env_plan_index_ = trackedNearestIndex(latest_plan_, robot_pose, env_plan_index_, sampling.track_back,
|
||||
sampling.track_ahead);
|
||||
}
|
||||
EnvGeometryRequest req;
|
||||
req.plan = &latest_plan_;
|
||||
req.from_index = env_plan_index_;
|
||||
req.robot_pose = robot_pose;
|
||||
req.sampling = &sampling;
|
||||
req.front = front;
|
||||
req.rear = rear;
|
||||
req.side = side;
|
||||
EnvGeometry geometry;
|
||||
if (deps_.environment->sampleGeometry(req, geometry))
|
||||
{
|
||||
env_geometry_ = geometry;
|
||||
s.geometry_valid = true;
|
||||
s.cost_conclusive = geometry.cost.conclusive;
|
||||
s.reachable = geometry.cost.reachable;
|
||||
s.cost_to_go = geometry.cost.cost_to_go;
|
||||
s.edt_body_min = geometry.edt_body_min;
|
||||
}
|
||||
last_env_heavy_ = now;
|
||||
has_last_env_heavy_ = true;
|
||||
}
|
||||
|
||||
if (config_.env_monitor.contact.enabled)
|
||||
{
|
||||
EnvTrajectoryRequest treq;
|
||||
treq.robot_pose = robot_pose;
|
||||
treq.v = s.v_cmd;
|
||||
treq.omega = s.w_cmd;
|
||||
treq.sampling = &sampling;
|
||||
treq.front = front;
|
||||
treq.rear = rear;
|
||||
treq.side = side;
|
||||
if (sampling.use_local_plan != "false")
|
||||
{
|
||||
deps_.controller->getLocalPlan(env_local_plan_);
|
||||
treq.local_plan = &env_local_plan_;
|
||||
}
|
||||
SweepResult sweep;
|
||||
bool used_local = false;
|
||||
if (deps_.environment->sweepTrajectory(treq, sweep, used_local) && sweep.conclusive)
|
||||
{
|
||||
s.contact_conclusive = true;
|
||||
s.traj_contact_dist = sweep.blocked ? sweep.distance : std::numeric_limits<double>::infinity();
|
||||
env_used_local_plan_ = used_local;
|
||||
env_contact_dist_ = s.traj_contact_dist;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
env_verdict_ = env_monitor_.update(s);
|
||||
env_brake_ = env_verdict_.brake && config_.env_monitor.contact.apply_command;
|
||||
if (env_verdict_.cost_jump && config_.debug_env)
|
||||
{
|
||||
robot::log_info_throttle(1.0, "[move_base2][debug] EnvMonitor: cost_to_go jumped to %.2f m in one tick — free mask "
|
||||
"changed connectivity, stall window restarted.\n",
|
||||
s.cost_to_go);
|
||||
}
|
||||
|
||||
// Sườn sự kiện: một dòng, không throttle, không khoá — đây là chẩn đoán "robot kẹt/sắp chạm".
|
||||
if (env_verdict_.event[0] != '\0')
|
||||
{
|
||||
robot::log_warning("[move_base2] EnvMonitor: %s (eff_geo=%.2f cmd=%.2f m, cost_to_go=%.2f m, "
|
||||
"edt_body=%.2f m, contact=%.2f m, budget_left=%.2f m, mission %llu%s).\n",
|
||||
env_verdict_.event, env_verdict_.eff_geo, env_verdict_.cmd_window,
|
||||
env_geometry_.valid ? env_geometry_.cost.cost_to_go : -1.0, s.edt_body_min,
|
||||
s.traj_contact_dist, env_verdict_.replan_budget_left,
|
||||
static_cast<unsigned long long>(active_request_.mission_sequence_id),
|
||||
(env_verdict_.no_progress || env_verdict_.path_blocked || env_verdict_.collision)
|
||||
? "; FLAG RAISED"
|
||||
: "; shadow");
|
||||
}
|
||||
// Tóm tắt feature 1 Hz — nhóm debug/env, tắt được.
|
||||
if (config_.debug_env && monitorable && s.geometry_valid &&
|
||||
(!has_last_env_debug_ || (now - last_env_debug_).toSec() >= 1.0))
|
||||
{
|
||||
last_env_debug_ = now;
|
||||
has_last_env_debug_ = true;
|
||||
robot::log_info("[move_base2][debug] EnvMonitor: cost_to_go=%.2f (geo %.2f + arc %.2f, %s%s) eff=%.2f "
|
||||
"cmd=%.2f m edt_body=%.2f m clear_ahead=%.2f m corridor=%.2f m contact=%.2f m (%s) "
|
||||
"v_cap=%.2f stall=%d%s unreach=%d%s brake=%d standdown=%d budget_left=%.1f m disp=%.2f m%s\n",
|
||||
env_geometry_.cost.cost_to_go, env_geometry_.cost.geo_to_exit, env_geometry_.cost.arc_rest,
|
||||
env_geometry_.cost.reachable ? "reachable" : "UNREACHABLE",
|
||||
env_geometry_.cost.robot_in_ring ? ", in ring" : "", env_verdict_.eff_geo,
|
||||
env_verdict_.cmd_window, env_geometry_.edt_body_min, env_geometry_.corridor.plan_clear_ahead,
|
||||
env_geometry_.corridor.min_width, s.traj_contact_dist,
|
||||
env_used_local_plan_ ? "local plan" : "arc", env_verdict_.v_cap,
|
||||
env_verdict_.stall_detected ? 1 : 0, env_verdict_.stall_muted ? "(muted)" : "",
|
||||
env_verdict_.unreachable_detected ? 1 : 0, env_verdict_.unreachable_muted ? "(muted)" : "",
|
||||
env_verdict_.brake ? 1 : 0, env_verdict_.contact_standdown ? 1 : 0,
|
||||
env_verdict_.replan_budget_left, env_verdict_.net_disp,
|
||||
env_verdict_.wandering ? " WANDERING" : "");
|
||||
}
|
||||
if (env_logger_ && (s.geometry_valid || env_verdict_.event[0] != '\0'))
|
||||
{
|
||||
env_logger_->record(now, s, env_verdict_, s.geometry_valid ? &env_geometry_ : nullptr,
|
||||
toString(state_machine_.state()), active_request_.mission_sequence_id,
|
||||
env_used_local_plan_);
|
||||
}
|
||||
}
|
||||
|
||||
void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
|
||||
{
|
||||
candidate = robot_geometry_msgs::Twist();
|
||||
@@ -1242,6 +1531,7 @@ bool ControlLoop::step()
|
||||
// --- 1b. Giám sát tuyến ---------------------------------------------------------------------
|
||||
// Chạy TRƯỚC state machine: hai cờ nó sinh ra là dữ liệu vào của state machine ngay cycle này.
|
||||
updatePathMonitor(now, robot_pose, pose_available, costmap_stale);
|
||||
updateEnvMonitor(now, dt, robot_pose, pose_available, costmap_stale);
|
||||
|
||||
// --- 2. State machine -----------------------------------------------------------------------
|
||||
StateMachineInput input;
|
||||
@@ -1262,11 +1552,13 @@ bool ControlLoop::step()
|
||||
input.robot_stopped = arbiter_.stopped();
|
||||
input.travelled_since_oscillation_reset = travelled;
|
||||
// Phép đo 3 dùng chung route với phép đo 1: cả hai cùng một cách xử lý — lập lại đường.
|
||||
input.path_blocked = path_blocked_;
|
||||
input.collision = collision_blocked_; // Phép đo 3 có trigger/route riêng (2026-09-04)
|
||||
// EnvMonitor OR vào cùng bốn cổng của PathMonitor: cờ của nó chỉ khác false khi `action: recover`.
|
||||
input.path_blocked = path_blocked_ || env_verdict_.path_blocked;
|
||||
input.collision = collision_blocked_ || env_verdict_.collision; // Phép đo 3 có trigger/route riêng (2026-09-04)
|
||||
input.off_path = off_path_;
|
||||
// Phép đo 4 chỉ được leo thang ở mode "recover"; mode "log" đã in cảnh báo và dừng ở đó.
|
||||
input.no_progress = no_progress_ && config_.path_monitor.progress_action == "recover";
|
||||
input.no_progress = (no_progress_ && config_.path_monitor.progress_action == "recover") ||
|
||||
env_verdict_.no_progress;
|
||||
|
||||
// Cùng một chỉ số dùng cho cả cycle khởi động recovery lẫn các cycle tick: state machine chỉ tăng
|
||||
// chỉ số khi behavior kết thúc, nên `nextRecoveryIndex()` chính là behavior sắp chạy hoặc đang
|
||||
@@ -1319,6 +1611,7 @@ bool ControlLoop::step()
|
||||
++plan_revision_;
|
||||
order_plan_.clear();
|
||||
has_outcome_ = false;
|
||||
env_monitor_.onGoalAccepted(now);
|
||||
|
||||
// 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)
|
||||
@@ -1382,6 +1675,8 @@ bool ControlLoop::step()
|
||||
// plan vừa tới (rõ nhất lúc preempt/đổi chặng). Đo lệch tuyến ngay lúc đó là khai hoả oan.
|
||||
last_plan_applied_ = now;
|
||||
has_last_plan_applied_ = true;
|
||||
env_monitor_.onPlanApplied(now);
|
||||
env_plan_index_valid_ = false;
|
||||
|
||||
if (config_.debug_plan)
|
||||
{
|
||||
@@ -1428,6 +1723,7 @@ bool ControlLoop::step()
|
||||
|
||||
robot_geometry_msgs::Twist candidate;
|
||||
collision_brake_ = false; // chỉ applyCollisionGuard của CYCLE NÀY được bật lại.
|
||||
env_controller_v_ = 0.0; // controller không chạy cycle này = không đòi đi.
|
||||
|
||||
if (output.start_recovery)
|
||||
{
|
||||
@@ -1436,6 +1732,7 @@ bool ControlLoop::step()
|
||||
// Behavior từ chối khởi động (ví dụ đã va chạm ngay tại chỗ) — báo hỏng để state machine
|
||||
// chuyển sang behavior kế tiếp thay vì tick một behavior chưa start.
|
||||
recovery_feedback_ = RecoveryFeedback::kFailed;
|
||||
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
|
||||
}
|
||||
}
|
||||
else if (output.tick_recovery)
|
||||
@@ -1448,9 +1745,14 @@ bool ControlLoop::step()
|
||||
break;
|
||||
case RecoveryTick::Status::kSucceeded:
|
||||
recovery_feedback_ = RecoveryFeedback::kSucceeded;
|
||||
env_monitor_.onRecoveryFinished(now,
|
||||
tick.has_path && !tick.path.empty() ? EnvRecoveryOutcome::kSucceededWithPath
|
||||
: EnvRecoveryOutcome::kSucceeded,
|
||||
output.recovery_trigger == RecoveryTrigger::kCollision);
|
||||
break;
|
||||
case RecoveryTick::Status::kFailed:
|
||||
recovery_feedback_ = RecoveryFeedback::kFailed;
|
||||
env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed);
|
||||
break;
|
||||
}
|
||||
if (tick.has_velocity)
|
||||
@@ -1577,8 +1879,44 @@ bool ControlLoop::step()
|
||||
runController(candidate);
|
||||
if (controller_feedback_ == ControllerFeedback::kCommandValid)
|
||||
{
|
||||
env_controller_v_ = candidate.linear.x; // trước guard / bao / trọng tài: ý định thật của controller
|
||||
// Phép đo 3 của PathMonitor: soi chính lệnh sắp phát, TRƯỚC trọng tài.
|
||||
applyCollisionGuard(robot_pose, pose_available, candidate);
|
||||
|
||||
// EnvMonitor: bao tốc độ theo tiếp xúc trên quỹ đạo thật. Chỉ tác động khi `contact/apply_command`
|
||||
// (P4); ở shadow chỉ có dòng log "would cap". Giữ omega/v để cung không đổi khi kẹp.
|
||||
if (std::isfinite(env_verdict_.v_cap) && std::fabs(candidate.linear.x) > env_verdict_.v_cap)
|
||||
{
|
||||
if (config_.env_monitor.contact.apply_command)
|
||||
{
|
||||
const double scale = env_verdict_.v_cap / std::fabs(candidate.linear.x);
|
||||
candidate.linear.x *= scale;
|
||||
candidate.angular.z *= scale;
|
||||
}
|
||||
else if (config_.debug_env)
|
||||
{
|
||||
robot::log_info_throttle(2.0, "[move_base2][debug] EnvMonitor: would cap v %.2f -> %.2f m/s "
|
||||
"(contact %.2f m along the %s; shadow, not applied).\n",
|
||||
candidate.linear.x, env_verdict_.v_cap, env_contact_dist_,
|
||||
env_used_local_plan_ ? "local plan" : "commanded arc");
|
||||
}
|
||||
}
|
||||
|
||||
// EnvMonitor giữ phanh MÀ cờ collision đã giơ và state machine vẫn để CONTROLLING (route
|
||||
// collision cạn/khoá): lệnh vừa bị huỷ thì với state machine nó KHÔNG hợp lệ — cùng luật (A)
|
||||
// của guard cũ. Báo đúng sự thật thì controller_patience chạy -> route controlling_failed ->
|
||||
// ABORT có log, thay vì robot đứng chết vô hạn với controller "ổn". Trước khi cờ giơ (1 s kề
|
||||
// mũi) controller vẫn hợp lệ: patience 0,5 s không được chạy đua với chính cờ collision.
|
||||
if (env_brake_ && env_verdict_.collision)
|
||||
{
|
||||
controller_feedback_ = ControllerFeedback::kNoValidCommand;
|
||||
robot::log_warning_throttle(2.0,
|
||||
"[move_base2] EnvMonitor: holding the brake (contact %.2f m along the %s, "
|
||||
"controller wants v=%.2f) — reported as no valid command; if the collision "
|
||||
"trigger is locked, controller_patience escalates.\n",
|
||||
env_contact_dist_, env_used_local_plan_ ? "local plan" : "commanded arc",
|
||||
candidate.linear.x);
|
||||
}
|
||||
}
|
||||
if (controller_feedback_ == ControllerFeedback::kNoValidCommand)
|
||||
{
|
||||
@@ -1645,8 +1983,8 @@ bool ControlLoop::step()
|
||||
|
||||
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
|
||||
// Sắp chạm vật cản thật cũng là "không ai được phát": lệnh 0 tức thì, không giảm dần.
|
||||
arbiter_.arbitrate((costmap_stale || collision_brake_) ? VelocitySource::kNone
|
||||
: output.velocity_source,
|
||||
arbiter_.arbitrate((costmap_stale || collision_brake_ || env_brake_) ? VelocitySource::kNone
|
||||
: output.velocity_source,
|
||||
candidate, dt);
|
||||
// Phép đo 4 đo lệnh SAU trọng tài: hold của planner, phanh của Phép đo 3, costmap stale đều ra
|
||||
// 0 ở đây — đó chính là cách nó phân biệt "đang chờ" với "đòi đi mà không tiến".
|
||||
|
||||
773
src/env_monitor.cpp
Normal file
773
src/env_monitor.cpp
Normal file
@@ -0,0 +1,773 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — cài đặt lõi EnvMonitor (xem header).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/core/env_monitor.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
bool validAction(const std::string& action)
|
||||
{
|
||||
return action == "log" || action == "recover";
|
||||
}
|
||||
|
||||
bool finitePositive(double v)
|
||||
{
|
||||
return std::isfinite(v) && v > 0.0;
|
||||
}
|
||||
|
||||
bool finiteNonNegative(double v)
|
||||
{
|
||||
return std::isfinite(v) && v >= 0.0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ------------------------------------------------------------------------------------------ config
|
||||
|
||||
bool EnvMonitorConfig::validate(std::string& error) const
|
||||
{
|
||||
if (!finiteNonNegative(grace_after_new_plan))
|
||||
{
|
||||
error = "env_monitor/grace_after_new_plan must be >= 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (!validAction(stall.action) || !validAction(unreachable.action) || !validAction(contact.action))
|
||||
{
|
||||
error = "env_monitor/*/action must be \"log\" or \"recover\"";
|
||||
return false;
|
||||
}
|
||||
if (!finitePositive(stall.window_s) || !finitePositive(stall.window_m))
|
||||
{
|
||||
error = "env_monitor/stall/window_s and window_m must be > 0";
|
||||
return false;
|
||||
}
|
||||
if (!finitePositive(stall.min_commanded))
|
||||
{
|
||||
error = "env_monitor/stall/min_commanded must be > 0 [m] (0 would turn waiting into stalling)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(stall.eff_on) || !std::isfinite(stall.eff_off) || stall.eff_off <= stall.eff_on)
|
||||
{
|
||||
error = "env_monitor/stall/eff_off must be > eff_on (hysteresis)";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(stall.confirm) || !finiteNonNegative(stall.goal_zone) ||
|
||||
!finiteNonNegative(stall.slip_on) || !finiteNonNegative(stall.slip_time) ||
|
||||
!finiteNonNegative(stall.min_commanded_since_goal) || !finiteNonNegative(stall.retry_backoff) ||
|
||||
!finiteNonNegative(stall.jump_reject) || !finitePositive(stall.disp_window_s) ||
|
||||
!finiteNonNegative(stall.disp_min) || !finiteNonNegative(stall.disp_min_commanded))
|
||||
{
|
||||
error = "env_monitor/stall: confirm, goal_zone, slip_on, slip_time, min_commanded_since_goal, "
|
||||
"retry_backoff must be >= 0";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(unreachable.static_on) || !finitePositive(unreachable.clean_start_margin) ||
|
||||
!finiteNonNegative(unreachable.retry_backoff))
|
||||
{
|
||||
error = "env_monitor/unreachable: static_on >= 0 [s], clean_start_margin > 0 [m], retry_backoff >= 0";
|
||||
return false;
|
||||
}
|
||||
if (contact.confirm_cycles < 1)
|
||||
{
|
||||
error = "env_monitor/contact/confirm_cycles must be >= 1";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(contact.trigger_static_time) || !finitePositive(contact.clean_start_margin) ||
|
||||
!finitePositive(contact.brake_decel) || !finiteNonNegative(contact.min_speed) ||
|
||||
!finiteNonNegative(contact.min_check_speed) || !finiteNonNegative(contact.release_hysteresis) ||
|
||||
contact.release_confirm_cycles < 1 || !finiteNonNegative(contact.envelope_margin) ||
|
||||
!finiteNonNegative(contact.standdown_min_travel) || !finiteNonNegative(contact.standdown_travel))
|
||||
{
|
||||
error = "env_monitor/contact: trigger_static_time >= 0, clean_start_margin > 0, brake_decel > 0, "
|
||||
"min_speed >= 0, min_check_speed >= 0, release_hysteresis >= 0, release_confirm_cycles >= 1, "
|
||||
"envelope_margin >= 0, standdown_min_travel >= 0, standdown_travel >= 0";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(replan.min_travel) || !std::isfinite(replan.escalate_factor) ||
|
||||
replan.escalate_factor < 1.0 || !finiteNonNegative(replan.escalate_window_m) ||
|
||||
!finiteNonNegative(replan.escalate_max) || (replan.escalate_max > 0.0 && replan.escalate_max < replan.min_travel))
|
||||
{
|
||||
error = "env_monitor/replan_budget: min_travel >= 0, escalate_factor >= 1, escalate_window_m >= 0, "
|
||||
"escalate_max = 0 or >= min_travel";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string EnvMonitorConfig::describe() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "env_monitor " << (enabled ? "ON" : "OFF") << " (grace " << grace_after_new_plan << " s):\n";
|
||||
out << " stall : " << (stall.enabled ? "on" : "off") << " action=" << stall.action
|
||||
<< " window=" << stall.window_s << " s/" << stall.window_m << " m min_cmd=" << stall.min_commanded
|
||||
<< " m eff<" << stall.eff_on << " ket / >=" << stall.eff_off << " xoa confirm=" << stall.confirm
|
||||
<< " s goal_zone=" << stall.goal_zone << " m slip>=" << stall.slip_on << " m/s " << stall.slip_time
|
||||
<< " s cmd_since_goal>=" << stall.min_commanded_since_goal << " m backoff=" << stall.retry_backoff
|
||||
<< " s jump_reject=" << stall.jump_reject << " m disp_gate=" << stall.disp_min << " m/"
|
||||
<< stall.disp_window_s << " s (cmd>=" << stall.disp_min_commanded << " m)\n";
|
||||
out << " unreachable : " << (unreachable.enabled ? "on" : "off") << " action=" << unreachable.action
|
||||
<< " static_on=" << unreachable.static_on << " s clean_margin=" << unreachable.clean_start_margin
|
||||
<< " m backoff=" << unreachable.retry_backoff << " s\n";
|
||||
out << " contact : " << (contact.enabled ? "on" : "off") << " action=" << contact.action
|
||||
<< " confirm=" << contact.confirm_cycles << " cycles trigger_static=" << contact.trigger_static_time
|
||||
<< " s clean_margin=" << contact.clean_start_margin << " m decel=" << contact.brake_decel
|
||||
<< " m/s^2 envelope=" << (contact.envelope ? "on" : "off") << " min_speed=" << contact.min_speed
|
||||
<< " m/s min_check_speed=" << contact.min_check_speed << " m/s release=" << contact.release_hysteresis
|
||||
<< " m/" << contact.release_confirm_cycles << " cycles envelope_margin=" << contact.envelope_margin
|
||||
<< " m standdown=" << contact.standdown_min_travel << "/" << contact.standdown_travel
|
||||
<< " m apply_command=" << (contact.apply_command ? "YES" : "no (shadow)") << "\n";
|
||||
out << " replan : min_travel=" << replan.min_travel << " m x" << replan.escalate_factor
|
||||
<< " within " << replan.escalate_window_m << " m, max " << replan.escalate_max << " m";
|
||||
return out.str();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- lifecycle
|
||||
|
||||
bool EnvMonitor::configure(const EnvMonitorConfig& config, std::string& error)
|
||||
{
|
||||
if (!config.validate(error))
|
||||
{
|
||||
configured_ = false;
|
||||
return false;
|
||||
}
|
||||
config_ = config;
|
||||
configured_ = true;
|
||||
reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
void EnvMonitor::reset()
|
||||
{
|
||||
cmd_accum_ = 0.0;
|
||||
travel_total_ = 0.0;
|
||||
has_last_pose_ = false;
|
||||
has_goal_ = false;
|
||||
cmd_at_goal_ = 0.0;
|
||||
has_plan_time_ = false;
|
||||
clearWindow();
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
slip_seen_ = false;
|
||||
has_stall_backoff_ = false;
|
||||
baseline_pending_ = true;
|
||||
baseline_unreachable_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
has_unreach_backoff_ = false;
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
has_prev_heavy_ = false;
|
||||
clearPosWindow();
|
||||
braking_ = false;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
detour_from_contact_ = false;
|
||||
detour_mark_travel_ = 0.0;
|
||||
standdown_ = false;
|
||||
standdown_mark_travel_ = 0.0;
|
||||
standdown_clean_streak_ = 0;
|
||||
has_replan_mark_ = false;
|
||||
replan_mark_travel_ = 0.0;
|
||||
budget_travel_ = config_.replan.min_travel;
|
||||
has_prev_replan_ = false;
|
||||
prev_replan_travel_ = 0.0;
|
||||
}
|
||||
|
||||
void EnvMonitor::onGoalAccepted(const robot::Time& now)
|
||||
{
|
||||
(void)now;
|
||||
const double cmd = cmd_accum_;
|
||||
const double travel = travel_total_;
|
||||
const bool had_pose = has_last_pose_;
|
||||
const double lx = last_x_;
|
||||
const double ly = last_y_;
|
||||
reset();
|
||||
// Odometer và lệnh tích luỹ là đơn điệu, chỉ dùng qua hiệu số: giữ lại để mốc không nhảy.
|
||||
cmd_accum_ = cmd;
|
||||
travel_total_ = travel;
|
||||
has_last_pose_ = had_pose;
|
||||
last_x_ = lx;
|
||||
last_y_ = ly;
|
||||
has_goal_ = true;
|
||||
cmd_at_goal_ = cmd_accum_;
|
||||
}
|
||||
|
||||
void EnvMonitor::onPlanApplied(const robot::Time& now)
|
||||
{
|
||||
has_plan_time_ = true;
|
||||
plan_time_ = now;
|
||||
clearWindow();
|
||||
clearPosWindow(); // cửa sổ dịch chuyển bắt đầu lại: plan mới là một lượt thử mới
|
||||
has_prev_heavy_ = false;
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
// Plan mới có baseline riêng: chỉ nổ "mất liên thông" vì thứ xảy ra SAU khi plan được lập (R2).
|
||||
baseline_pending_ = true;
|
||||
baseline_unreachable_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
}
|
||||
|
||||
void EnvMonitor::onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome, bool from_contact)
|
||||
{
|
||||
switch (outcome)
|
||||
{
|
||||
case EnvRecoveryOutcome::kSucceededWithPath:
|
||||
{
|
||||
// Detour do chính cờ collision: nếu robot không rời chỗ mà lại "sắp chạm" thì lần sau đứng ra.
|
||||
detour_from_contact_ = from_contact;
|
||||
detour_mark_travel_ = travel_total_;
|
||||
// R3/R5: im tới khi đi đủ budget_travel_ kể từ đây; lặp trong escalate_window_m thì nhân lên.
|
||||
if (has_prev_replan_ && travel_total_ - prev_replan_travel_ < config_.replan.escalate_window_m)
|
||||
{
|
||||
budget_travel_ *= config_.replan.escalate_factor;
|
||||
if (config_.replan.escalate_max > 0.0)
|
||||
{
|
||||
budget_travel_ = std::min(budget_travel_, config_.replan.escalate_max);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
budget_travel_ = config_.replan.min_travel;
|
||||
}
|
||||
has_prev_replan_ = true;
|
||||
prev_replan_travel_ = travel_total_;
|
||||
has_replan_mark_ = true;
|
||||
replan_mark_travel_ = travel_total_;
|
||||
break;
|
||||
}
|
||||
case EnvRecoveryOutcome::kSucceeded:
|
||||
break;
|
||||
case EnvRecoveryOutcome::kFailed:
|
||||
has_stall_backoff_ = true;
|
||||
stall_backoff_until_ = now + robot::Duration(config_.stall.retry_backoff);
|
||||
has_unreach_backoff_ = true;
|
||||
unreach_backoff_until_ = now + robot::Duration(config_.unreachable.retry_backoff);
|
||||
break;
|
||||
}
|
||||
// Mọi kết cục đều kết thúc một pha dừng: chuỗi xác nhận cũ không còn giá trị.
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
braking_ = false;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------- window
|
||||
|
||||
void EnvMonitor::clearWindow()
|
||||
{
|
||||
ring_head_ = 0;
|
||||
ring_count_ = 0;
|
||||
}
|
||||
|
||||
void EnvMonitor::clearPosWindow()
|
||||
{
|
||||
pos_head_ = 0;
|
||||
pos_count_ = 0;
|
||||
wandering_ = false;
|
||||
net_disp_ = std::numeric_limits<double>::quiet_NaN();
|
||||
}
|
||||
|
||||
bool EnvMonitor::oldestPos(const robot::Time& now, PosSample& out) const
|
||||
{
|
||||
// Mẫu MỚI NHẤT đã đủ tuổi disp_window_s — cùng lý do với oldestInWindow.
|
||||
for (std::size_t k = 1; k <= pos_count_; ++k)
|
||||
{
|
||||
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
|
||||
if ((now - p.t).toSec() >= config_.stall.disp_window_s)
|
||||
{
|
||||
out = p;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool EnvMonitor::oldestInWindow(const robot::Time& now, HeavySample& out) const
|
||||
{
|
||||
// Mẫu MỚI NHẤT đã đủ tuổi window_s hoặc đủ xa window_m lệnh — cửa sổ sát ngưỡng nhất, không phải
|
||||
// mẫu cũ nhất trong ring (cửa sổ giãn ra làm eff mượt giả).
|
||||
for (std::size_t k = 1; k <= ring_count_; ++k)
|
||||
{
|
||||
const HeavySample& s = ring_[(ring_head_ + kRing - k) % kRing];
|
||||
const bool old_enough = (now - s.t).toSec() >= config_.stall.window_s;
|
||||
const bool far_enough = cmd_accum_ - s.cmd >= config_.stall.window_m;
|
||||
if (old_enough || far_enough)
|
||||
{
|
||||
out = s;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------- update
|
||||
|
||||
EnvVerdict EnvMonitor::update(const EnvSample& s)
|
||||
{
|
||||
EnvVerdict v;
|
||||
if (!configured_ || !config_.enabled)
|
||||
{
|
||||
return v;
|
||||
}
|
||||
|
||||
// Tích luỹ lệnh và quãng đường — mọi cửa sổ, cổng, ngân sách đều đo bằng hai con số này.
|
||||
if (s.dt > 0.0 && std::isfinite(s.v_cmd))
|
||||
{
|
||||
cmd_accum_ += std::fabs(s.v_cmd) * s.dt;
|
||||
}
|
||||
if (std::isfinite(s.robot_x) && std::isfinite(s.robot_y))
|
||||
{
|
||||
if (has_last_pose_)
|
||||
{
|
||||
travel_total_ += std::hypot(s.robot_x - last_x_, s.robot_y - last_y_);
|
||||
}
|
||||
last_x_ = s.robot_x;
|
||||
last_y_ = s.robot_y;
|
||||
has_last_pose_ = true;
|
||||
}
|
||||
if (has_replan_mark_)
|
||||
{
|
||||
v.replan_budget_left = std::max(0.0, budget_travel_ - (travel_total_ - replan_mark_travel_));
|
||||
}
|
||||
|
||||
updateContact(s, v);
|
||||
|
||||
if (!s.has_plan || !s.costmap_current)
|
||||
{
|
||||
// Không có gì để đo tiến độ; xoá chuỗi để không nối "đúng liên tục" qua quãng gián đoạn.
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
return v;
|
||||
}
|
||||
updateStall(s, v);
|
||||
updateUnreachable(s, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
void EnvMonitor::updateStall(const EnvSample& s, EnvVerdict& v)
|
||||
{
|
||||
const EnvMonitorConfig::Stall& c = config_.stall;
|
||||
if (!c.enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Cửa sổ dịch chuyển thực: lấy mẫu vị trí mỗi tick nặng, không phụ thuộc cost/plan/mặt nạ.
|
||||
if (s.geometry_valid && std::isfinite(s.robot_x) && std::isfinite(s.robot_y))
|
||||
{
|
||||
pos_ring_[pos_head_] = PosSample{ s.now, s.robot_x, s.robot_y, cmd_accum_ };
|
||||
pos_head_ = (pos_head_ + 1) % kPosRing;
|
||||
pos_count_ = std::min(pos_count_ + 1, kPosRing);
|
||||
PosSample old;
|
||||
if (oldestPos(s.now, old))
|
||||
{
|
||||
net_disp_ = std::hypot(s.robot_x - old.x, s.robot_y - old.y);
|
||||
wandering_ = (cmd_accum_ - old.cmd >= c.disp_min_commanded) && net_disp_ < c.disp_min;
|
||||
}
|
||||
else
|
||||
{
|
||||
net_disp_ = std::numeric_limits<double>::quiet_NaN();
|
||||
wandering_ = false;
|
||||
}
|
||||
}
|
||||
v.net_disp = net_disp_;
|
||||
v.wandering = wandering_;
|
||||
|
||||
// Mẫu nặng mới: ghi vào ring nếu có cost hữu hạn. +inf (mất liên thông tạm) không ghi — không kết
|
||||
// luận từ mẫu thiếu.
|
||||
if (s.geometry_valid && s.cost_conclusive && s.reachable && std::isfinite(s.cost_to_go))
|
||||
{
|
||||
// Lật liên thông: cost đổi nhiều hơn robot có thể đã đi trong một tick -> mặt nạ free vừa đóng/mở một khe,
|
||||
// không phải tiến độ. Bắt đầu đo lại; kết luận kẹt cũ (nếu có) cũng không còn cơ sở.
|
||||
if (c.jump_reject > 0.0 && has_prev_heavy_ &&
|
||||
std::fabs(s.cost_to_go - prev_heavy_cost_) > c.jump_reject + (travel_total_ - prev_heavy_travel_))
|
||||
{
|
||||
clearWindow();
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
v.cost_jump = true;
|
||||
}
|
||||
has_prev_heavy_ = true;
|
||||
prev_heavy_cost_ = s.cost_to_go;
|
||||
prev_heavy_travel_ = travel_total_;
|
||||
ring_[ring_head_] = HeavySample{ s.now, s.cost_to_go, cmd_accum_ };
|
||||
ring_head_ = (ring_head_ + 1) % kRing;
|
||||
ring_count_ = std::min(ring_count_ + 1, kRing);
|
||||
|
||||
HeavySample old;
|
||||
if (oldestInWindow(s.now, old))
|
||||
{
|
||||
const double cmd = cmd_accum_ - old.cmd;
|
||||
v.cmd_window = cmd;
|
||||
if (cmd >= c.min_commanded)
|
||||
{
|
||||
v.eff_geo = (old.cost - s.cost_to_go) / cmd;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Trượt: lệnh đi mà bánh không quay (vật thấp, bumper). Chỉ khi có v_meas.
|
||||
bool slipping = false;
|
||||
if (c.slip_on > 0.0 && std::isfinite(s.v_meas))
|
||||
{
|
||||
const bool slip_now = std::fabs(s.v_cmd) - std::fabs(s.v_meas) >= c.slip_on;
|
||||
if (slip_now)
|
||||
{
|
||||
if (!slip_seen_)
|
||||
{
|
||||
slip_seen_ = true;
|
||||
slip_since_ = s.now;
|
||||
}
|
||||
slipping = (s.now - slip_since_).toSec() >= c.slip_time;
|
||||
}
|
||||
else
|
||||
{
|
||||
slip_seen_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
const bool grace = has_plan_time_ && (s.now - plan_time_).toSec() < config_.grace_after_new_plan;
|
||||
const bool near_goal = std::isfinite(s.d_goal) && s.d_goal < c.goal_zone;
|
||||
if (grace || near_goal)
|
||||
{
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const bool eff_known = !std::isnan(v.eff_geo);
|
||||
const bool stalled = (eff_known && v.eff_geo < c.eff_on) || slipping;
|
||||
const bool cleared = eff_known && v.eff_geo >= c.eff_off && !slipping;
|
||||
if (stalled)
|
||||
{
|
||||
if (!stall_seen_)
|
||||
{
|
||||
stall_seen_ = true;
|
||||
stall_since_ = s.now;
|
||||
}
|
||||
if (!stall_fired_ && (s.now - stall_since_).toSec() >= c.confirm)
|
||||
{
|
||||
stall_fired_ = true;
|
||||
v.event = slipping ? "stall: wheels slip against the command" : "stall: cost_to_go not decreasing";
|
||||
}
|
||||
}
|
||||
else if (cleared)
|
||||
{
|
||||
if (stall_fired_)
|
||||
{
|
||||
v.event = "stall cleared: progress resumed";
|
||||
}
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
}
|
||||
// Còn lại (không đo được, hoặc eff trong vùng chết): giữ trạng thái — không kết luận ≠ hết kẹt.
|
||||
|
||||
v.stall_detected = stall_fired_;
|
||||
if (!stall_fired_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Cổng đầu chặng, ngân sách replan, backoff sau lượt hỏng.
|
||||
bool muted = false;
|
||||
if (has_goal_ && cmd_accum_ - cmd_at_goal_ < c.min_commanded_since_goal)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
if (c.disp_min > 0.0)
|
||||
{
|
||||
// Cổng dịch chuyển thực thay ngân sách replan: cửa sổ vị trí đã bắt đầu lại ở plan mới, nên "sau detour
|
||||
// vẫn quần tại chỗ disp_window_s" mới được nổ lại; né tự do (dịch chuyển >= disp_min) không bao giờ nổ.
|
||||
if (!wandering_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
}
|
||||
else if (has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
if (has_stall_backoff_ && s.now < stall_backoff_until_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
v.stall_muted = muted;
|
||||
v.no_progress = !muted && c.action == "recover";
|
||||
}
|
||||
|
||||
void EnvMonitor::updateUnreachable(const EnvSample& s, EnvVerdict& v)
|
||||
{
|
||||
const EnvMonitorConfig::Unreachable& c = config_.unreachable;
|
||||
if (!c.enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Trạng thái chỉ đổi ở tick nặng có kết luận; verdict thì phải ra MỖI cycle từ trạng thái, nếu
|
||||
// không cờ nhấp nháy giữa hai tick 5 Hz và state machine 20 Hz thấy cờ bật/tắt.
|
||||
if (s.geometry_valid && s.cost_conclusive)
|
||||
{
|
||||
// Baseline của plan: mẫu kết luận đầu tiên sau khi nhận plan. Plan đã không liên thông ngay từ
|
||||
// đầu thì đó là chuyện của SBPL/planner đã lập nó — monitor không cãi trên cùng snapshot (R2).
|
||||
if (baseline_pending_)
|
||||
{
|
||||
baseline_pending_ = false;
|
||||
baseline_unreachable_ = !s.reachable;
|
||||
}
|
||||
if (s.reachable)
|
||||
{
|
||||
if (unreach_fired_)
|
||||
{
|
||||
v.event = "unreachable cleared: the exit is connected again";
|
||||
}
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
baseline_unreachable_ = false; // từ đây mất liên thông là chuyện mới
|
||||
}
|
||||
else
|
||||
{
|
||||
const bool grace = has_plan_time_ && (s.now - plan_time_).toSec() < config_.grace_after_new_plan;
|
||||
const bool clean = std::isfinite(s.edt_body_min) && s.edt_body_min >= c.clean_start_margin;
|
||||
if (baseline_unreachable_ || grace || !clean)
|
||||
{
|
||||
// Không tích: chưa phải "xấu đi", hoặc robot đã lọt vành (SBPL không có chỗ bắt đầu — việc
|
||||
// của kContact + controller_patience).
|
||||
unreach_seen_ = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!unreach_seen_)
|
||||
{
|
||||
unreach_seen_ = true;
|
||||
unreach_since_ = s.now;
|
||||
}
|
||||
if (!unreach_fired_ && (s.now - unreach_since_).toSec() >= c.static_on)
|
||||
{
|
||||
unreach_fired_ = true;
|
||||
v.event = "unreachable: no path to the plan exit inside the window";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
v.unreachable_detected = unreach_fired_;
|
||||
if (!unreach_fired_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
bool muted = false;
|
||||
if (has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
if (has_unreach_backoff_ && s.now < unreach_backoff_until_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
v.unreachable_muted = muted;
|
||||
v.path_blocked = !muted && c.action == "recover";
|
||||
}
|
||||
|
||||
void EnvMonitor::updateContact(const EnvSample& s, EnvVerdict& v)
|
||||
{
|
||||
const EnvMonitorConfig::Contact& c = config_.contact;
|
||||
if (!c.enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
double v_ref = std::fabs(s.v_cmd);
|
||||
if (std::isfinite(s.v_meas))
|
||||
{
|
||||
v_ref = std::max(v_ref, std::fabs(s.v_meas));
|
||||
}
|
||||
v.brake_dist = v_ref * v_ref / (2.0 * c.brake_decel);
|
||||
|
||||
if (!s.contact_conclusive || !s.costmap_current)
|
||||
{
|
||||
// Không biết thì không dừng, cũng không xoá chuỗi (cùng hợp đồng với guard cũ).
|
||||
v.brake = braking_; // đang phanh thì giữ phanh tới khi có bằng chứng ngược lại
|
||||
return;
|
||||
}
|
||||
if (standdown_)
|
||||
{
|
||||
// Đang đứng ra: không phanh, không cờ, không bao. Chỉ theo dõi điều kiện vũ trang lại.
|
||||
v.contact_standdown = true;
|
||||
if (std::isfinite(s.traj_contact_dist))
|
||||
{
|
||||
standdown_clean_streak_ = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
++standdown_clean_streak_;
|
||||
}
|
||||
const bool travelled = travel_total_ - standdown_mark_travel_ >= c.standdown_travel;
|
||||
if (travelled || standdown_clean_streak_ >= c.release_confirm_cycles)
|
||||
{
|
||||
standdown_ = false;
|
||||
standdown_clean_streak_ = 0;
|
||||
v.contact_standdown = false;
|
||||
v.event = travelled ? "contact: re-armed after moving on" : "contact: re-armed, the trajectory is clear";
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!std::isfinite(s.traj_contact_dist))
|
||||
{
|
||||
contact_streak_ = 0;
|
||||
if (braking_ && ++release_streak_ < c.release_confirm_cycles)
|
||||
{
|
||||
// Một mẫu sạch chưa là sạch: local planner đổi quỹ đạo mỗi cycle, sạch 1 cycle rồi chạm lại là
|
||||
// chuyện thường (run 5/9 22:35: 4 lần nhả/phanh trong 3 s). Giữ phanh và cờ tới khi sạch liên tiếp.
|
||||
v.brake = true;
|
||||
v.collision = contact_fired_ && c.action == "recover";
|
||||
return;
|
||||
}
|
||||
if (braking_ || contact_fired_)
|
||||
{
|
||||
v.event = "contact cleared: the trajectory is free again";
|
||||
}
|
||||
braking_ = false;
|
||||
release_streak_ = 0;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Bao tốc độ: |v| <= sqrt(2 a (d - margin)) để luôn còn dừng được trên đất sạch.
|
||||
// Bao giữ thêm envelope_margin so với ngưỡng phanh: lệnh nằm trên bao thì quãng phanh còn dư đúng chừng
|
||||
// đó, nhiễu quỹ đạo vài cm không đẩy sang "sắp chạm". Trong margin thì 0; giữa margin và margin+dư thì bò
|
||||
// min_speed.
|
||||
if (c.envelope)
|
||||
{
|
||||
if (s.traj_contact_dist <= c.clean_start_margin)
|
||||
{
|
||||
v.v_cap = 0.0;
|
||||
}
|
||||
else
|
||||
{
|
||||
const double room = s.traj_contact_dist - c.clean_start_margin - c.envelope_margin;
|
||||
v.v_cap = std::max(c.min_speed, room > 0.0 ? std::sqrt(2.0 * c.brake_decel * room) : 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Xoay tại chỗ / bò mà monitor chưa phanh: quỹ đạo local planner lúc này là một cú xoay, góc thân
|
||||
// quét vào ô kề bên là chuyện của controller (nó tự kiểm footprint), không phải bài toán quãng phanh.
|
||||
// Phanh ở đây là chặn robot xoay ra khỏi vật đang kề mũi, rồi 1 s sau giơ cờ và gọi detour từ đúng
|
||||
// chỗ đứng — vòng churn đầu chặng của guard cũ (mission 5/6 shadow 5/9). Đã phanh rồi thì vẫn xét
|
||||
// tiếp để "kề mũi đứng yên" còn nổ được.
|
||||
double v_intent = v_ref;
|
||||
if (std::isfinite(s.v_controller))
|
||||
{
|
||||
v_intent = std::max(v_intent, std::fabs(s.v_controller));
|
||||
}
|
||||
if (v_intent < c.min_check_speed && !braking_)
|
||||
{
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Hai câu hỏi khác nhau:
|
||||
// - "sắp chạm" = còn dừng kịp không (theo quãng phanh) -> PHANH. Đứng lại rồi thì quãng phanh về 0
|
||||
// và câu này tự hết đúng, robot được bò tiếp dưới bao tốc độ.
|
||||
// - "đang kề vật" = tiếp xúc trong đúng clean_start_margin bất kể tốc độ -> nếu còn đó đủ
|
||||
// trigger_static_time thì vật đứng yên trước mũi, không phải người đi qua -> giơ CỜ.
|
||||
// Bao tốc độ đặt lệnh đúng lên biên v_cap = sqrt(2a(d - margin)), tức d - quãng phanh == margin: nếu
|
||||
// "sắp chạm" là <= thì mỗi lần bao kẹp xong là phanh, nhả, kẹp, phanh (chattering 4 cycle). Chỉ phanh
|
||||
// khi vượt bao quá 1 mm — lệnh nằm trên bao là đang giảm tốc đúng luật, không phải sắp chạm.
|
||||
// Trong margin thì bao đã là 0: đó là một cú dừng của monitor dù quãng phanh bằng 0 — phải được gọi
|
||||
// là phanh để có sự kiện, để giữ 0 tức thì qua trọng tài và để cổng xoay không nuốt nó.
|
||||
constexpr double kEnvelopeTol = 1e-3; // [m]
|
||||
// Đã kề thì còn kề tới margin + release_hysteresis: quỹ đạo nhảy 0,08 <-> 0,25 m quanh margin không
|
||||
// được reset đồng hồ giơ cờ, cũng không được nhả phanh.
|
||||
const double close_limit = c.clean_start_margin + (contact_close_ ? c.release_hysteresis : 0.0);
|
||||
const bool close = s.traj_contact_dist <= close_limit;
|
||||
const bool imminent = close || s.traj_contact_dist - v.brake_dist < c.clean_start_margin - kEnvelopeTol;
|
||||
v.contact_imminent = imminent;
|
||||
if (imminent)
|
||||
{
|
||||
release_streak_ = 0;
|
||||
++contact_streak_;
|
||||
if (!braking_ && contact_streak_ >= c.confirm_cycles)
|
||||
{
|
||||
if (c.standdown_min_travel > 0.0 && detour_from_contact_ &&
|
||||
travel_total_ - detour_mark_travel_ < c.standdown_min_travel)
|
||||
{
|
||||
// Vừa detour từ đúng chỗ này vì chính cú chạm này, robot chưa rời chỗ: phanh + cờ lần nữa chỉ lặp
|
||||
// lại churn (3 detour rồi ABORT). Nhường controller — nó là lưới an toàn duy nhất tới khi robot đi
|
||||
// được standdown_travel hoặc quỹ đạo sạch.
|
||||
standdown_ = true;
|
||||
standdown_mark_travel_ = travel_total_;
|
||||
standdown_clean_streak_ = 0;
|
||||
detour_from_contact_ = false;
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
v.contact_standdown = true;
|
||||
v.contact_imminent = false;
|
||||
v.v_cap = std::numeric_limits<double>::infinity();
|
||||
v.event = "contact: standing down — the detour from this spot did not move the robot, the controller "
|
||||
"is the only safety net until it travels on";
|
||||
return;
|
||||
}
|
||||
braking_ = true;
|
||||
v.event = "contact: braking to zero";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
contact_streak_ = 0;
|
||||
if (braking_ && ++release_streak_ >= c.release_confirm_cycles)
|
||||
{
|
||||
braking_ = false;
|
||||
release_streak_ = 0;
|
||||
v.event = "contact receded: releasing the brake";
|
||||
}
|
||||
}
|
||||
v.brake = braking_;
|
||||
|
||||
if (close)
|
||||
{
|
||||
if (!contact_close_)
|
||||
{
|
||||
contact_close_ = true;
|
||||
close_since_ = s.now;
|
||||
}
|
||||
if (!contact_fired_ && (s.now - close_since_).toSec() >= c.trigger_static_time)
|
||||
{
|
||||
contact_fired_ = true;
|
||||
v.event = "contact persists while stopped: asking for a replan";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (contact_fired_)
|
||||
{
|
||||
v.event = "contact cleared: the obstacle moved away";
|
||||
}
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
}
|
||||
v.collision = contact_fired_ && c.action == "recover";
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
813
src/grid_analysis.cpp
Normal file
813
src/grid_analysis.cpp
Normal file
@@ -0,0 +1,813 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — cài đặt grid_analysis (xem header).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/core/grid_analysis.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
|
||||
#include <robot_costmap_2d/costmap_2d.h>
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
constexpr float kInf = std::numeric_limits<float>::infinity();
|
||||
/// Giá trị "vô cùng" hữu hạn cho EDT 1-D: bình phương khoảng cách theo ô tối đa là 160^2 = 25 600,
|
||||
/// 1e6 vẫn biểu diễn chính xác trong float và không sinh NaN khi trừ nhau như +inf.
|
||||
constexpr float kFarSq = 1.0e6f;
|
||||
/// [m] Bỏ quãng đầu quỹ đạo khi kéo footprint — cùng lý do với plan_inspector::kSkipOwnFootprintDist.
|
||||
constexpr double kSkipOwnFootprintDist = 0.05;
|
||||
/// Lượng tử hoá khoảng cách trong khoá heap: 0.1 mm, đủ cho 20 m trong 32 bit.
|
||||
constexpr double kHeapQuant = 10000.0;
|
||||
|
||||
double yawOf(const robot_geometry_msgs::PoseStamped& pose)
|
||||
{
|
||||
const auto& q = pose.pose.orientation;
|
||||
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Biến đổi khoảng cách bình phương 1-D (Felzenszwalb & Huttenlocher 2004) — parabola lower envelope.
|
||||
* @param f n giá trị vào (0 tại vật cản, kFarSq nơi khác; hoặc kết quả lượt trước).
|
||||
* @param d n giá trị ra.
|
||||
* @param v,z bộ đệm >= n và >= n+1.
|
||||
*/
|
||||
void distanceTransform1D(const float* f, int n, float* d, int* v, float* z)
|
||||
{
|
||||
int k = 0;
|
||||
v[0] = 0;
|
||||
z[0] = -kInf;
|
||||
z[1] = kInf;
|
||||
for (int q = 1; q < n; ++q)
|
||||
{
|
||||
float s = ((f[q] + static_cast<float>(q) * q) - (f[v[k]] + static_cast<float>(v[k]) * v[k])) /
|
||||
(2.0f * q - 2.0f * v[k]);
|
||||
while (s <= z[k])
|
||||
{
|
||||
--k;
|
||||
s = ((f[q] + static_cast<float>(q) * q) - (f[v[k]] + static_cast<float>(v[k]) * v[k])) /
|
||||
(2.0f * q - 2.0f * v[k]);
|
||||
}
|
||||
++k;
|
||||
v[k] = q;
|
||||
z[k] = s;
|
||||
z[k + 1] = kInf;
|
||||
}
|
||||
k = 0;
|
||||
for (int q = 0; q < n; ++q)
|
||||
{
|
||||
while (z[k + 1] < static_cast<float>(q))
|
||||
{
|
||||
++k;
|
||||
}
|
||||
const float dq = static_cast<float>(q - v[k]);
|
||||
d[q] = dq * dq + f[v[k]];
|
||||
}
|
||||
}
|
||||
|
||||
std::uint64_t heapKey(double dist, std::uint32_t idx)
|
||||
{
|
||||
const std::uint64_t q = static_cast<std::uint64_t>(std::llround(dist * kHeapQuant));
|
||||
return (q << 32) | idx;
|
||||
}
|
||||
|
||||
/// Dựng chu vi hình chữ nhật thân (frame thân) với bước @p spacing; mỗi điểm mang id cạnh.
|
||||
void buildPerimeter(double front, double rear, double side, double spacing, std::vector<double>& out)
|
||||
{
|
||||
out.clear();
|
||||
const double x0[4] = { -rear, front, front, -rear };
|
||||
const double y0[4] = { -side, -side, side, side };
|
||||
const double x1[4] = { front, front, -rear, -rear };
|
||||
const double y1[4] = { -side, side, side, -side };
|
||||
for (int e = 0; e < 4; ++e)
|
||||
{
|
||||
const double len = std::hypot(x1[e] - x0[e], y1[e] - y0[e]);
|
||||
const int n = std::max(1, static_cast<int>(std::ceil(len / spacing)));
|
||||
for (int i = 0; i <= n; ++i)
|
||||
{
|
||||
const double t = static_cast<double>(i) / n;
|
||||
out.push_back(x0[e] + (x1[e] - x0[e]) * t);
|
||||
out.push_back(y0[e] + (y1[e] - y0[e]) * t);
|
||||
out.push_back(static_cast<double>(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ------------------------------------------------------------------------------------------ scratch
|
||||
|
||||
bool GridScratch::ensure(const robot_costmap_2d::Costmap2D& grid)
|
||||
{
|
||||
const unsigned int w = grid.getSizeInCellsX();
|
||||
const unsigned int h = grid.getSizeInCellsY();
|
||||
resolution = grid.getResolution();
|
||||
origin_x = grid.getOriginX();
|
||||
origin_y = grid.getOriginY();
|
||||
if (w == 0 || h == 0 || !(resolution > 0.0))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (w != width || h != height)
|
||||
{
|
||||
width = w;
|
||||
height = h;
|
||||
const std::size_t n = static_cast<std::size_t>(w) * h;
|
||||
edt.assign(n, kInf);
|
||||
free.assign(n, 0);
|
||||
geo.assign(n, kInf);
|
||||
tmp_.assign(n, kFarSq);
|
||||
const std::size_t m = std::max(w, h) + 2;
|
||||
f_.assign(m, 0.0f);
|
||||
d_.assign(m, 0.0f);
|
||||
v_.assign(m, 0);
|
||||
z_.assign(m + 1, 0.0f);
|
||||
heap_.clear();
|
||||
heap_.reserve(n * 2);
|
||||
baseline.reserve(1024);
|
||||
perim_.reserve(3 * 512);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GridScratch::toCell(double x, double y, unsigned int& mx, unsigned int& my) const
|
||||
{
|
||||
if (width == 0 || height == 0 || !(resolution > 0.0))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const double fx = std::floor((x - origin_x) / resolution);
|
||||
const double fy = std::floor((y - origin_y) / resolution);
|
||||
if (fx < 0.0 || fy < 0.0 || fx >= static_cast<double>(width) || fy >= static_cast<double>(height))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
mx = static_cast<unsigned int>(fx);
|
||||
my = static_cast<unsigned int>(fy);
|
||||
return true;
|
||||
}
|
||||
|
||||
void GridScratch::cellCenter(unsigned int mx, unsigned int my, double& x, double& y) const
|
||||
{
|
||||
x = origin_x + (mx + 0.5) * resolution;
|
||||
y = origin_y + (my + 0.5) * resolution;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- EDT
|
||||
|
||||
bool analyzeGrid(const robot_costmap_2d::Costmap2D& grid, unsigned char lethal_threshold,
|
||||
double free_radius, GridScratch& s)
|
||||
{
|
||||
if (!s.ensure(grid))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const unsigned char* cost = grid.getCharMap();
|
||||
const std::size_t n = static_cast<std::size_t>(s.width) * s.height;
|
||||
bool any_lethal = false;
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
{
|
||||
// NO_INFORMATION (255) không phải vật cản — cùng quy ước với checkPlan và SBPL.
|
||||
const bool lethal = cost[i] >= lethal_threshold && cost[i] != robot_costmap_2d::NO_INFORMATION;
|
||||
s.tmp_[i] = lethal ? 0.0f : kFarSq;
|
||||
any_lethal |= lethal;
|
||||
}
|
||||
s.free_radius = free_radius;
|
||||
if (!any_lethal)
|
||||
{
|
||||
std::fill(s.edt.begin(), s.edt.end(), kInf);
|
||||
std::fill(s.free.begin(), s.free.end(), static_cast<std::uint8_t>(1));
|
||||
return true;
|
||||
}
|
||||
// Lượt 1: theo hàng (trục x).
|
||||
const int w = static_cast<int>(s.width);
|
||||
const int h = static_cast<int>(s.height);
|
||||
for (int y = 0; y < h; ++y)
|
||||
{
|
||||
float* row = &s.tmp_[static_cast<std::size_t>(y) * s.width];
|
||||
distanceTransform1D(row, w, s.d_.data(), s.v_.data(), s.z_.data());
|
||||
std::copy(s.d_.begin(), s.d_.begin() + w, row);
|
||||
}
|
||||
// Lượt 2: theo cột (trục y).
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
for (int y = 0; y < h; ++y)
|
||||
{
|
||||
s.f_[y] = s.tmp_[static_cast<std::size_t>(y) * s.width + x];
|
||||
}
|
||||
distanceTransform1D(s.f_.data(), h, s.d_.data(), s.v_.data(), s.z_.data());
|
||||
for (int y = 0; y < h; ++y)
|
||||
{
|
||||
const std::size_t i = static_cast<std::size_t>(y) * s.width + x;
|
||||
const float dist = std::sqrt(s.d_[y]) * static_cast<float>(s.resolution);
|
||||
s.edt[i] = dist;
|
||||
s.free[i] = dist >= static_cast<float>(free_radius) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
double distanceAt(const GridScratch& s, double x, double y)
|
||||
{
|
||||
unsigned int mx = 0;
|
||||
unsigned int my = 0;
|
||||
if (!s.toCell(x, y, mx, my) || s.edt.empty())
|
||||
{
|
||||
return std::numeric_limits<double>::quiet_NaN();
|
||||
}
|
||||
return s.edt[s.index(mx, my)];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------- geodesic
|
||||
|
||||
bool computeGeodesic(unsigned int tx, unsigned int ty, GridScratch& s, std::size_t* visited,
|
||||
std::size_t stop_index)
|
||||
{
|
||||
if (visited != nullptr)
|
||||
{
|
||||
*visited = 0;
|
||||
}
|
||||
if (s.width == 0 || tx >= s.width || ty >= s.height || s.free.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
std::fill(s.geo.begin(), s.geo.end(), kInf);
|
||||
const std::size_t t = s.index(tx, ty);
|
||||
if (!s.free[t])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const float res = static_cast<float>(s.resolution);
|
||||
const float diag = res * 1.41421356f;
|
||||
const int w = static_cast<int>(s.width);
|
||||
const int h = static_cast<int>(s.height);
|
||||
|
||||
s.heap_.clear();
|
||||
s.geo[t] = 0.0f;
|
||||
s.heap_.push_back(heapKey(0.0, static_cast<std::uint32_t>(t)));
|
||||
std::greater<std::uint64_t> cmp;
|
||||
|
||||
// 8 láng giềng: (dx, dy, chéo?)
|
||||
static const int kDx[8] = { 1, -1, 0, 0, 1, 1, -1, -1 };
|
||||
static const int kDy[8] = { 0, 0, 1, -1, 1, -1, 1, -1 };
|
||||
|
||||
std::size_t popped = 0;
|
||||
while (!s.heap_.empty())
|
||||
{
|
||||
std::pop_heap(s.heap_.begin(), s.heap_.end(), cmp);
|
||||
const std::uint64_t key = s.heap_.back();
|
||||
s.heap_.pop_back();
|
||||
const std::uint32_t idx = static_cast<std::uint32_t>(key & 0xffffffffu);
|
||||
const double qd = static_cast<double>(key >> 32) / kHeapQuant;
|
||||
if (qd > s.geo[idx] + 0.5 / kHeapQuant)
|
||||
{
|
||||
continue; // mục cũ, đã có đường ngắn hơn
|
||||
}
|
||||
++popped;
|
||||
if (idx == stop_index)
|
||||
{
|
||||
break; // ô cần hỏi đã có khoảng cách đúng (Dijkstra: pop = chốt); phần còn lại không cần
|
||||
}
|
||||
const int x = static_cast<int>(idx % s.width);
|
||||
const int y = static_cast<int>(idx / s.width);
|
||||
const float base = s.geo[idx];
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const int nx = x + kDx[k];
|
||||
const int ny = y + kDy[k];
|
||||
if (nx < 0 || ny < 0 || nx >= w || ny >= h)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const std::size_t ni = s.index(static_cast<unsigned int>(nx), static_cast<unsigned int>(ny));
|
||||
if (!s.free[ni])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
float step = res;
|
||||
if (k >= 4)
|
||||
{
|
||||
// Cấm cắt góc: hai ô trực giao trung gian phải free, không thì đường chui qua khe chéo.
|
||||
const std::size_t a = s.index(static_cast<unsigned int>(nx), static_cast<unsigned int>(y));
|
||||
const std::size_t b = s.index(static_cast<unsigned int>(x), static_cast<unsigned int>(ny));
|
||||
if (!s.free[a] || !s.free[b])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
step = diag;
|
||||
}
|
||||
const float nd = base + step;
|
||||
if (nd < s.geo[ni])
|
||||
{
|
||||
s.geo[ni] = nd;
|
||||
s.heap_.push_back(heapKey(nd, static_cast<std::uint32_t>(ni)));
|
||||
std::push_heap(s.heap_.begin(), s.heap_.end(), cmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (visited != nullptr)
|
||||
{
|
||||
*visited = popped;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool nearestFreeCell(const GridScratch& s, unsigned int mx, unsigned int my, double max_dist,
|
||||
unsigned int& fx, unsigned int& fy)
|
||||
{
|
||||
if (s.free.empty() || mx >= s.width || my >= s.height)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (s.free[s.index(mx, my)])
|
||||
{
|
||||
fx = mx;
|
||||
fy = my;
|
||||
return true;
|
||||
}
|
||||
const int r = static_cast<int>(std::ceil(max_dist / s.resolution));
|
||||
long best = -1;
|
||||
for (int dy = -r; dy <= r; ++dy)
|
||||
{
|
||||
for (int dx = -r; dx <= r; ++dx)
|
||||
{
|
||||
const int x = static_cast<int>(mx) + dx;
|
||||
const int y = static_cast<int>(my) + dy;
|
||||
if (!s.inBounds(x, y))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const long d2 = static_cast<long>(dx) * dx + static_cast<long>(dy) * dy;
|
||||
if (s.free[s.index(static_cast<unsigned int>(x), static_cast<unsigned int>(y))] &&
|
||||
(best < 0 || d2 < best))
|
||||
{
|
||||
best = d2;
|
||||
fx = static_cast<unsigned int>(x);
|
||||
fy = static_cast<unsigned int>(y);
|
||||
}
|
||||
}
|
||||
}
|
||||
return best >= 0 && std::sqrt(static_cast<double>(best)) * s.resolution <= max_dist;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------ body clearance
|
||||
|
||||
double bodyClearance(const GridScratch& s, double x, double y, double yaw, double front, double rear,
|
||||
double side)
|
||||
{
|
||||
if (s.edt.empty())
|
||||
{
|
||||
return std::numeric_limits<double>::quiet_NaN();
|
||||
}
|
||||
const double spacing = 0.5 * s.resolution;
|
||||
const double c = std::cos(yaw);
|
||||
const double sn = std::sin(yaw);
|
||||
double best = std::numeric_limits<double>::infinity();
|
||||
bool any = false;
|
||||
const double x0[4] = { -rear, front, front, -rear };
|
||||
const double y0[4] = { -side, -side, side, side };
|
||||
const double x1[4] = { front, front, -rear, -rear };
|
||||
const double y1[4] = { -side, side, side, -side };
|
||||
for (int e = 0; e < 4; ++e)
|
||||
{
|
||||
const double len = std::hypot(x1[e] - x0[e], y1[e] - y0[e]);
|
||||
const int n = std::max(1, static_cast<int>(std::ceil(len / spacing)));
|
||||
for (int i = 0; i <= n; ++i)
|
||||
{
|
||||
const double t = static_cast<double>(i) / n;
|
||||
const double bx = x0[e] + (x1[e] - x0[e]) * t;
|
||||
const double by = y0[e] + (y1[e] - y0[e]) * t;
|
||||
const double wx = x + bx * c - by * sn;
|
||||
const double wy = y + bx * sn + by * c;
|
||||
const double d = distanceAt(s, wx, wy);
|
||||
if (!std::isnan(d))
|
||||
{
|
||||
any = true;
|
||||
best = std::min(best, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
return any ? best : std::numeric_limits<double>::quiet_NaN();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------- cost to go
|
||||
|
||||
CostToGoResult costToGo(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index, double robot_x, double robot_y,
|
||||
const CostToGoParams& params, const PlanarTransform& plan_to_grid,
|
||||
GridScratch& s)
|
||||
{
|
||||
CostToGoResult r;
|
||||
if (plan.size() < 2 || from_index >= plan.size() || s.free.empty())
|
||||
{
|
||||
return r;
|
||||
}
|
||||
|
||||
// Độ dài cộng dồn từ from_index tới cuối, và pose plan cuối cùng còn trong lưới.
|
||||
// arc_at[i] chỉ cần cho các pose từ from_index; dùng hai con trỏ chạy để không cấp phát.
|
||||
double total = 0.0;
|
||||
{
|
||||
double px = 0.0;
|
||||
double py = 0.0;
|
||||
plan_to_grid.apply(plan[from_index].pose.position.x, plan[from_index].pose.position.y, px, py);
|
||||
for (std::size_t i = from_index + 1; i < plan.size(); ++i)
|
||||
{
|
||||
double qx = 0.0;
|
||||
double qy = 0.0;
|
||||
plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy);
|
||||
total += std::hypot(qx - px, qy - py);
|
||||
px = qx;
|
||||
py = qy;
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t ti = from_index;
|
||||
double arc_ti = 0.0; // độ dài từ from_index tới ti
|
||||
bool found = false;
|
||||
bool ahead = false;
|
||||
{
|
||||
double px = 0.0;
|
||||
double py = 0.0;
|
||||
double walk = 0.0;
|
||||
for (std::size_t i = from_index; i < plan.size(); ++i)
|
||||
{
|
||||
double qx = 0.0;
|
||||
double qy = 0.0;
|
||||
plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy);
|
||||
if (i > from_index)
|
||||
{
|
||||
walk += std::hypot(qx - px, qy - py);
|
||||
}
|
||||
px = qx;
|
||||
py = qy;
|
||||
unsigned int mx = 0;
|
||||
unsigned int my = 0;
|
||||
if (!s.toCell(qx, qy, mx, my))
|
||||
{
|
||||
break; // cửa sổ lăn theo robot: ra ngoài một lần là phần còn lại cũng ngoài
|
||||
}
|
||||
ti = i;
|
||||
arc_ti = walk;
|
||||
found = true;
|
||||
if (params.exit_ahead > 0.0 && walk >= params.exit_ahead)
|
||||
{
|
||||
ahead = true;
|
||||
break; // T ở quãng cố định dọc plan: chỉ tiến theo index, không lùi khi cửa sổ trôi
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
{
|
||||
return r; // pose plan gần robot nhất cũng ngoài lưới: robot xa plan, việc của off_path
|
||||
}
|
||||
r.target = (ti + 1 == plan.size()) ? CostToGoResult::Target::kGoal
|
||||
: ahead ? CostToGoResult::Target::kAhead
|
||||
: CostToGoResult::Target::kExit;
|
||||
|
||||
// T phải là ô free; không thì lùi dọc plan tối đa target_backoff.
|
||||
unsigned int tx = 0;
|
||||
unsigned int ty = 0;
|
||||
{
|
||||
double qx = 0.0;
|
||||
double qy = 0.0;
|
||||
plan_to_grid.apply(plan[ti].pose.position.x, plan[ti].pose.position.y, qx, qy);
|
||||
s.toCell(qx, qy, tx, ty);
|
||||
}
|
||||
if (!s.free[s.index(tx, ty)])
|
||||
{
|
||||
bool backed = false;
|
||||
double back = 0.0;
|
||||
double px = 0.0;
|
||||
double py = 0.0;
|
||||
plan_to_grid.apply(plan[ti].pose.position.x, plan[ti].pose.position.y, px, py);
|
||||
for (std::size_t j = ti; j > from_index; --j)
|
||||
{
|
||||
double qx = 0.0;
|
||||
double qy = 0.0;
|
||||
plan_to_grid.apply(plan[j - 1].pose.position.x, plan[j - 1].pose.position.y, qx, qy);
|
||||
back += std::hypot(qx - px, qy - py);
|
||||
px = qx;
|
||||
py = qy;
|
||||
if (back > params.target_backoff)
|
||||
{
|
||||
break;
|
||||
}
|
||||
unsigned int mx = 0;
|
||||
unsigned int my = 0;
|
||||
if (s.toCell(qx, qy, mx, my) && s.free[s.index(mx, my)])
|
||||
{
|
||||
ti = j - 1;
|
||||
arc_ti -= back;
|
||||
tx = mx;
|
||||
ty = my;
|
||||
backed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!backed)
|
||||
{
|
||||
r.conclusive = true;
|
||||
r.reachable = false;
|
||||
r.target = CostToGoResult::Target::kBlockedExit;
|
||||
r.target_index = ti;
|
||||
r.arc_rest = total - arc_ti;
|
||||
return r;
|
||||
}
|
||||
r.target = CostToGoResult::Target::kBackedOff;
|
||||
}
|
||||
r.target_index = ti;
|
||||
r.arc_rest = std::max(0.0, total - arc_ti);
|
||||
|
||||
// Ô robot; đang ôm sát vật thì snap sang ô free gần nhất.
|
||||
unsigned int rx = 0;
|
||||
unsigned int ry = 0;
|
||||
if (!s.toCell(robot_x, robot_y, rx, ry))
|
||||
{
|
||||
return r;
|
||||
}
|
||||
if (!s.free[s.index(rx, ry)])
|
||||
{
|
||||
r.robot_in_ring = true;
|
||||
unsigned int fx = 0;
|
||||
unsigned int fy = 0;
|
||||
if (!nearestFreeCell(s, rx, ry, params.robot_snap, fx, fy))
|
||||
{
|
||||
return r; // thân đã nằm sâu trong dải cấm: không kết luận
|
||||
}
|
||||
rx = fx;
|
||||
ry = fy;
|
||||
}
|
||||
|
||||
std::size_t visited = 0;
|
||||
computeGeodesic(tx, ty, s, &visited, s.index(rx, ry)); // dừng sớm tại ô robot
|
||||
r.cells_visited = visited;
|
||||
r.conclusive = true;
|
||||
const float g = s.geo[s.index(rx, ry)];
|
||||
r.reachable = std::isfinite(g);
|
||||
r.geo_to_exit = g;
|
||||
r.cost_to_go = r.reachable ? static_cast<double>(g) + r.arc_rest : std::numeric_limits<double>::infinity();
|
||||
return r;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------- corridor
|
||||
|
||||
CorridorResult scanCorridor(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
std::size_t from_index, const CorridorParams& params,
|
||||
const PlanarTransform& plan_to_grid, const GridScratch& s)
|
||||
{
|
||||
CorridorResult r;
|
||||
r.plan_clear_ahead = params.horizon;
|
||||
if (plan.size() < 2 || from_index >= plan.size() || s.edt.empty())
|
||||
{
|
||||
return r;
|
||||
}
|
||||
const double need = params.body_width + 2.0 * params.margin;
|
||||
double walk = 0.0;
|
||||
double px = 0.0;
|
||||
double py = 0.0;
|
||||
bool clear_set = false;
|
||||
for (std::size_t i = from_index; i < plan.size(); ++i)
|
||||
{
|
||||
double qx = 0.0;
|
||||
double qy = 0.0;
|
||||
plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy);
|
||||
if (i > from_index)
|
||||
{
|
||||
walk += std::hypot(qx - px, qy - py);
|
||||
}
|
||||
const double prev_x = px;
|
||||
const double prev_y = py;
|
||||
px = qx;
|
||||
py = qy;
|
||||
if (walk > params.horizon)
|
||||
{
|
||||
break;
|
||||
}
|
||||
unsigned int mx = 0;
|
||||
unsigned int my = 0;
|
||||
if (!s.toCell(qx, qy, mx, my))
|
||||
{
|
||||
break;
|
||||
}
|
||||
++r.scanned;
|
||||
if (!clear_set && s.edt[s.index(mx, my)] < static_cast<float>(s.free_radius))
|
||||
{
|
||||
r.plan_clear_ahead = walk;
|
||||
clear_set = true;
|
||||
}
|
||||
// Hướng tiếp tuyến: tới pose kế, hoặc từ pose trước nếu là pose cuối.
|
||||
double tx = 0.0;
|
||||
double ty = 0.0;
|
||||
if (i + 1 < plan.size())
|
||||
{
|
||||
double nx = 0.0;
|
||||
double ny = 0.0;
|
||||
plan_to_grid.apply(plan[i + 1].pose.position.x, plan[i + 1].pose.position.y, nx, ny);
|
||||
tx = nx - qx;
|
||||
ty = ny - qy;
|
||||
}
|
||||
else if (i > from_index)
|
||||
{
|
||||
tx = qx - prev_x;
|
||||
ty = qy - prev_y;
|
||||
}
|
||||
const double tn = std::hypot(tx, ty);
|
||||
if (tn < 1e-6)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const double nx = -ty / tn;
|
||||
const double ny = tx / tn;
|
||||
double width = 0.0;
|
||||
for (double sgn = 1.0; sgn >= -1.0; sgn -= 2.0)
|
||||
{
|
||||
double d = 0.0;
|
||||
while (d < params.side_cap)
|
||||
{
|
||||
d += s.resolution;
|
||||
unsigned int cx = 0;
|
||||
unsigned int cy = 0;
|
||||
if (!s.toCell(qx + sgn * nx * d, qy + sgn * ny * d, cx, cy))
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (s.edt[s.index(cx, cy)] <= 0.0f)
|
||||
{
|
||||
break; // ô lethal
|
||||
}
|
||||
}
|
||||
width += std::min(d, params.side_cap);
|
||||
}
|
||||
r.min_width = std::min(r.min_width, width);
|
||||
if (!std::isfinite(r.block_dist) && width < need)
|
||||
{
|
||||
r.block_dist = walk;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- sweep
|
||||
|
||||
SweepResult sweepTrajectory(const std::vector<robot_geometry_msgs::PoseStamped>& trajectory,
|
||||
double robot_x, double robot_y, double robot_yaw, double start_tol,
|
||||
const SweepParams& params, const robot_costmap_2d::Costmap2D& grid,
|
||||
GridScratch& s)
|
||||
{
|
||||
SweepResult r;
|
||||
if (trajectory.size() < 2 || !s.ensure(grid))
|
||||
{
|
||||
return r;
|
||||
}
|
||||
if (std::hypot(trajectory.front().pose.position.x - robot_x,
|
||||
trajectory.front().pose.position.y - robot_y) > start_tol)
|
||||
{
|
||||
return r; // quỹ đạo không bắt đầu ở robot: không phải chuyển động sắp xảy ra
|
||||
}
|
||||
const unsigned char* cost = grid.getCharMap();
|
||||
const double front = params.front + params.padding;
|
||||
const double rear = params.rear + params.padding;
|
||||
const double side = params.side + params.padding;
|
||||
auto lethal_at = [&](unsigned int mx, unsigned int my) {
|
||||
const unsigned char c = cost[s.index(mx, my)];
|
||||
return c >= params.lethal_threshold && c != robot_costmap_2d::NO_INFORMATION;
|
||||
};
|
||||
|
||||
// Baseline: ô lethal đang nằm dưới thân đệm tại pose hiện tại (duyệt diện tích, như checkMotion).
|
||||
s.baseline.clear();
|
||||
if (params.exclude_baseline)
|
||||
{
|
||||
const double c = std::cos(robot_yaw);
|
||||
const double sn = std::sin(robot_yaw);
|
||||
const double cx[4] = { front, front, -rear, -rear };
|
||||
const double cy[4] = { side, -side, side, -side };
|
||||
double min_x = std::numeric_limits<double>::max();
|
||||
double min_y = min_x;
|
||||
double max_x = std::numeric_limits<double>::lowest();
|
||||
double max_y = max_x;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
{
|
||||
const double wx = robot_x + cx[i] * c - cy[i] * sn;
|
||||
const double wy = robot_y + cx[i] * sn + cy[i] * c;
|
||||
min_x = std::min(min_x, wx);
|
||||
max_x = std::max(max_x, wx);
|
||||
min_y = std::min(min_y, wy);
|
||||
max_y = std::max(max_y, wy);
|
||||
}
|
||||
int mx0 = 0;
|
||||
int my0 = 0;
|
||||
int mx1 = 0;
|
||||
int my1 = 0;
|
||||
grid.worldToMapEnforceBounds(min_x, min_y, mx0, my0);
|
||||
grid.worldToMapEnforceBounds(max_x, max_y, mx1, my1);
|
||||
const double slack = 0.5 * s.resolution;
|
||||
for (int my = my0; my <= my1; ++my)
|
||||
{
|
||||
for (int mx = mx0; mx <= mx1; ++mx)
|
||||
{
|
||||
if (!lethal_at(static_cast<unsigned int>(mx), static_cast<unsigned int>(my)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
double wx = 0.0;
|
||||
double wy = 0.0;
|
||||
s.cellCenter(static_cast<unsigned int>(mx), static_cast<unsigned int>(my), wx, wy);
|
||||
const double dx = wx - robot_x;
|
||||
const double dy = wy - robot_y;
|
||||
const double bx = dx * c + dy * sn;
|
||||
const double by = -dx * sn + dy * c;
|
||||
if (bx < -rear - slack || bx > front + slack || std::fabs(by) > side + slack)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
s.baseline.push_back(static_cast<std::uint32_t>(s.index(static_cast<unsigned int>(mx),
|
||||
static_cast<unsigned int>(my))));
|
||||
}
|
||||
}
|
||||
std::sort(s.baseline.begin(), s.baseline.end());
|
||||
}
|
||||
r.baseline_cells = static_cast<int>(s.baseline.size());
|
||||
|
||||
buildPerimeter(front, rear, side, 0.5 * s.resolution, s.perim_);
|
||||
const std::size_t npts = s.perim_.size() / 3;
|
||||
|
||||
auto hit_at = [&](double px, double py, double yaw, int& edge) {
|
||||
const double c = std::cos(yaw);
|
||||
const double sn = std::sin(yaw);
|
||||
for (std::size_t k = 0; k < npts; ++k)
|
||||
{
|
||||
const double bx = s.perim_[3 * k];
|
||||
const double by = s.perim_[3 * k + 1];
|
||||
const double wx = px + bx * c - by * sn;
|
||||
const double wy = py + bx * sn + by * c;
|
||||
unsigned int mx = 0;
|
||||
unsigned int my = 0;
|
||||
if (!s.toCell(wx, wy, mx, my) || !lethal_at(mx, my))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const std::uint32_t idx = static_cast<std::uint32_t>(s.index(mx, my));
|
||||
if (!s.baseline.empty() && std::binary_search(s.baseline.begin(), s.baseline.end(), idx))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
edge = static_cast<int>(s.perim_[3 * k + 2]);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
double walk = 0.0;
|
||||
for (std::size_t i = 1; i < trajectory.size(); ++i)
|
||||
{
|
||||
const double ax = trajectory[i - 1].pose.position.x;
|
||||
const double ay = trajectory[i - 1].pose.position.y;
|
||||
const double bx = trajectory[i].pose.position.x;
|
||||
const double by = trajectory[i].pose.position.y;
|
||||
const double seg = std::hypot(bx - ax, by - ay);
|
||||
const double yaw = yawOf(trajectory[i]);
|
||||
// Chèn mẫu để bước dọc quỹ đạo không quá một ô: tường mỏng một ô không lọt giữa hai mẫu.
|
||||
const int nsub = std::max(1, static_cast<int>(std::ceil(seg / s.resolution)));
|
||||
for (int k = 1; k <= nsub; ++k)
|
||||
{
|
||||
const double t = static_cast<double>(k) / nsub;
|
||||
const double px = ax + (bx - ax) * t;
|
||||
const double py = ay + (by - ay) * t;
|
||||
const double w = walk + seg * t;
|
||||
if (w > params.lookahead)
|
||||
{
|
||||
r.conclusive = true;
|
||||
return r;
|
||||
}
|
||||
if (w < kSkipOwnFootprintDist)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
++r.scanned;
|
||||
int edge = -1;
|
||||
if (hit_at(px, py, yaw, edge))
|
||||
{
|
||||
r.conclusive = true;
|
||||
r.blocked = true;
|
||||
r.distance = w;
|
||||
r.sample = i;
|
||||
r.hit_edge = edge;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
walk += seg;
|
||||
}
|
||||
r.conclusive = r.scanned > 0;
|
||||
return r;
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
205
src/io/env_logger.cpp
Normal file
205
src/io/env_logger.cpp
Normal file
@@ -0,0 +1,205 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* move_base2 — cài đặt EnvLogger.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <move_base2/io/env_logger.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
namespace move_base2
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
/// JSON không có NaN/Inf: ghi null.
|
||||
void appendNumber(std::string& out, double v)
|
||||
{
|
||||
char buf[32];
|
||||
if (std::isfinite(v))
|
||||
{
|
||||
std::snprintf(buf, sizeof(buf), "%.4f", v);
|
||||
out += buf;
|
||||
}
|
||||
else
|
||||
{
|
||||
out += "null";
|
||||
}
|
||||
}
|
||||
|
||||
void appendField(std::string& out, const char* key, double v)
|
||||
{
|
||||
out += '"';
|
||||
out += key;
|
||||
out += "\":";
|
||||
appendNumber(out, v);
|
||||
out += ',';
|
||||
}
|
||||
|
||||
void appendField(std::string& out, const char* key, bool v)
|
||||
{
|
||||
out += '"';
|
||||
out += key;
|
||||
out += "\":";
|
||||
out += v ? "true" : "false";
|
||||
out += ',';
|
||||
}
|
||||
|
||||
void appendField(std::string& out, const char* key, const char* v)
|
||||
{
|
||||
out += '"';
|
||||
out += key;
|
||||
out += "\":\"";
|
||||
for (const char* p = v; *p != '\0'; ++p)
|
||||
{
|
||||
if (*p == '"' || *p == '\\')
|
||||
{
|
||||
out += '\\';
|
||||
}
|
||||
out += *p;
|
||||
}
|
||||
out += "\",";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool EnvLoggerConfig::validate(std::string& error) const
|
||||
{
|
||||
if (!enabled)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (log_dir.empty())
|
||||
{
|
||||
error = "env_monitor/logger/log_dir must not be empty when the logger is enabled";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(flush_period) || flush_period <= 0.0)
|
||||
{
|
||||
error = "env_monitor/logger/flush_period must be > 0 [s]";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
EnvLogger::~EnvLogger()
|
||||
{
|
||||
flush();
|
||||
}
|
||||
|
||||
bool EnvLogger::open(const EnvLoggerConfig& config, std::string& error)
|
||||
{
|
||||
config_ = config;
|
||||
if (!config.enabled)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (::mkdir(config.log_dir.c_str(), 0755) != 0 && errno != EEXIST)
|
||||
{
|
||||
error = "env_monitor/logger: cannot create log_dir '" + config.log_dir + "'";
|
||||
return false;
|
||||
}
|
||||
const auto epoch =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
path_ = config.log_dir + "/envmon_" + std::to_string(epoch) + ".jsonl";
|
||||
out_.open(path_, std::ios::out | std::ios::trunc);
|
||||
if (!out_.is_open())
|
||||
{
|
||||
error = "env_monitor/logger: cannot open '" + path_ + "' for writing";
|
||||
return false;
|
||||
}
|
||||
buffer_.reserve(64 * 1024);
|
||||
return true;
|
||||
}
|
||||
|
||||
void EnvLogger::record(const robot::Time& now, const EnvSample& s, const EnvVerdict& v,
|
||||
const EnvGeometry* g, const char* state, std::uint64_t mission_id,
|
||||
bool used_local_plan)
|
||||
{
|
||||
if (!out_.is_open())
|
||||
{
|
||||
return;
|
||||
}
|
||||
std::string& o = buffer_;
|
||||
o += "{\"v\":1,";
|
||||
appendField(o, "t", now.toSec());
|
||||
o += "\"mission\":" + std::to_string(mission_id) + ",";
|
||||
appendField(o, "state", state);
|
||||
appendField(o, "heavy", s.geometry_valid);
|
||||
appendField(o, "x", s.robot_x);
|
||||
appendField(o, "y", s.robot_y);
|
||||
appendField(o, "v_cmd", s.v_cmd);
|
||||
appendField(o, "w_cmd", s.w_cmd);
|
||||
appendField(o, "v_meas", s.v_meas);
|
||||
appendField(o, "v_controller", s.v_controller);
|
||||
appendField(o, "d_goal", s.d_goal);
|
||||
appendField(o, "costmap_current", s.costmap_current);
|
||||
appendField(o, "controller_valid", s.controller_valid);
|
||||
appendField(o, "cost_to_go", s.cost_conclusive && s.reachable ? s.cost_to_go : std::numeric_limits<double>::quiet_NaN());
|
||||
appendField(o, "cost_conclusive", s.cost_conclusive);
|
||||
appendField(o, "reachable", s.reachable);
|
||||
appendField(o, "edt_body_min", s.edt_body_min);
|
||||
appendField(o, "contact_conclusive", s.contact_conclusive);
|
||||
appendField(o, "traj_contact_dist", s.traj_contact_dist);
|
||||
appendField(o, "used_local_plan", used_local_plan);
|
||||
if (g != nullptr && g->valid)
|
||||
{
|
||||
appendField(o, "geo_to_exit", g->cost.geo_to_exit);
|
||||
appendField(o, "arc_rest", g->cost.arc_rest);
|
||||
appendField(o, "target_kind", static_cast<double>(static_cast<int>(g->cost.target)));
|
||||
appendField(o, "cells_visited", static_cast<double>(g->cost.cells_visited));
|
||||
appendField(o, "robot_in_ring", g->cost.robot_in_ring);
|
||||
appendField(o, "plan_clear_ahead", g->corridor.plan_clear_ahead);
|
||||
appendField(o, "corridor_min_width", g->corridor.min_width);
|
||||
appendField(o, "corridor_block_dist", g->corridor.block_dist);
|
||||
}
|
||||
appendField(o, "eff_geo", v.eff_geo);
|
||||
appendField(o, "cmd_window", v.cmd_window);
|
||||
appendField(o, "brake_dist", v.brake_dist);
|
||||
appendField(o, "v_cap", v.v_cap);
|
||||
appendField(o, "stall_detected", v.stall_detected);
|
||||
appendField(o, "stall_muted", v.stall_muted);
|
||||
appendField(o, "unreachable_detected", v.unreachable_detected);
|
||||
appendField(o, "unreachable_muted", v.unreachable_muted);
|
||||
appendField(o, "contact_imminent", v.contact_imminent);
|
||||
appendField(o, "brake", v.brake);
|
||||
appendField(o, "contact_standdown", v.contact_standdown);
|
||||
appendField(o, "cost_jump", v.cost_jump);
|
||||
appendField(o, "no_progress", v.no_progress);
|
||||
appendField(o, "path_blocked", v.path_blocked);
|
||||
appendField(o, "collision", v.collision);
|
||||
appendField(o, "replan_budget_left", v.replan_budget_left);
|
||||
appendField(o, "net_disp", v.net_disp);
|
||||
appendField(o, "wandering", v.wandering);
|
||||
appendField(o, "event", v.event);
|
||||
o.pop_back(); // dấu phẩy cuối
|
||||
o += "}\n";
|
||||
|
||||
if (!has_last_flush_ || (now - last_flush_).toSec() >= config_.flush_period || buffer_.size() > 48 * 1024)
|
||||
{
|
||||
flush();
|
||||
last_flush_ = now;
|
||||
has_last_flush_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
void EnvLogger::flush()
|
||||
{
|
||||
if (out_.is_open() && !buffer_.empty())
|
||||
{
|
||||
out_ << buffer_;
|
||||
out_.flush();
|
||||
buffer_.clear();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace move_base2
|
||||
@@ -166,6 +166,237 @@ bool CostmapPathCheck::robotBodyExtents(double& front, double& rear, double& sid
|
||||
return true;
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// CostmapEnvironment
|
||||
// ================================================================================================
|
||||
|
||||
namespace
|
||||
{
|
||||
double yawOfPose(const robot_geometry_msgs::PoseStamped& pose)
|
||||
{
|
||||
const auto& q = pose.pose.orientation;
|
||||
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
robot_costmap_2d::Costmap2D* CostmapEnvironment::gridForRead(bool& live) const
|
||||
{
|
||||
live = true;
|
||||
if (costmap_ == nullptr)
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
robot_costmap_2d::Costmap2D* grid = costmap_->getCostmapForRead();
|
||||
live = (grid == costmap_->getCostmap()); // snapshot tắt -> trả lưới sống -> phải khoá
|
||||
return grid;
|
||||
}
|
||||
|
||||
void CostmapEnvironment::refresh()
|
||||
{
|
||||
if (costmap_ != nullptr)
|
||||
{
|
||||
costmap_->refreshSnapshot(); // no-op khi snapshot tắt
|
||||
}
|
||||
}
|
||||
|
||||
bool CostmapEnvironment::sampleGeometry(const EnvGeometryRequest& r, EnvGeometry& out)
|
||||
{
|
||||
out = EnvGeometry();
|
||||
if (costmap_ == nullptr || !tf_ || r.plan == nullptr || r.sampling == nullptr || r.plan->size() < 2 ||
|
||||
r.from_index >= r.plan->size())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
bool live = true;
|
||||
robot_costmap_2d::Costmap2D* grid = gridForRead(live);
|
||||
if (grid == nullptr)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const std::string& grid_frame = costmap_->getGlobalFrameID();
|
||||
PlanarTransform plan_to_grid;
|
||||
PlanarTransform pose_to_grid;
|
||||
if (!planarTransform(*tf_, (*r.plan)[r.from_index].header.frame_id, grid_frame, plan_to_grid) ||
|
||||
!planarTransform(*tf_, r.robot_pose.header.frame_id, grid_frame, pose_to_grid))
|
||||
{
|
||||
return false; // không quy đổi được frame: không biết, không đoán
|
||||
}
|
||||
double gx = 0.0;
|
||||
double gy = 0.0;
|
||||
pose_to_grid.apply(r.robot_pose.pose.position.x, r.robot_pose.pose.position.y, gx, gy);
|
||||
const double gyaw = yawOfPose(r.robot_pose) + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw);
|
||||
|
||||
// Bán kính tâm = inscribed của thân, KHÔNG đệm: cùng biên với SBPL (luật R2).
|
||||
const double free_radius = std::min(r.side, std::min(r.front, r.rear));
|
||||
out.free_radius = free_radius;
|
||||
|
||||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()), boost::defer_lock);
|
||||
if (live)
|
||||
{
|
||||
lock.lock();
|
||||
}
|
||||
if (!analyzeGrid(*grid, static_cast<unsigned char>(r.sampling->lethal_threshold), free_radius, scratch_))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
out.edt_body_min = bodyClearance(scratch_, gx, gy, gyaw, r.front, r.rear, r.side);
|
||||
CostToGoParams cost_params;
|
||||
cost_params.target_backoff = r.sampling->target_backoff;
|
||||
cost_params.robot_snap = r.sampling->robot_snap;
|
||||
cost_params.exit_ahead = r.sampling->exit_ahead;
|
||||
out.cost = costToGo(*r.plan, r.from_index, gx, gy, cost_params, plan_to_grid, scratch_);
|
||||
CorridorParams corridor_params;
|
||||
corridor_params.horizon = r.sampling->horizon;
|
||||
corridor_params.body_width = 2.0 * r.side;
|
||||
corridor_params.margin = r.sampling->corridor_margin;
|
||||
corridor_params.side_cap = r.sampling->corridor_cap;
|
||||
out.corridor = scanCorridor(*r.plan, r.from_index, corridor_params, plan_to_grid, scratch_);
|
||||
out.valid = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CostmapEnvironment::sweepTrajectory(const EnvTrajectoryRequest& r, SweepResult& out,
|
||||
bool& used_local_plan)
|
||||
{
|
||||
out = SweepResult();
|
||||
used_local_plan = false;
|
||||
if (costmap_ == nullptr || !tf_ || r.sampling == nullptr)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
bool live = true;
|
||||
robot_costmap_2d::Costmap2D* grid = gridForRead(live);
|
||||
if (grid == nullptr)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const std::string& grid_frame = costmap_->getGlobalFrameID();
|
||||
PlanarTransform pose_to_grid;
|
||||
if (!planarTransform(*tf_, r.robot_pose.header.frame_id, grid_frame, pose_to_grid))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
double gx = 0.0;
|
||||
double gy = 0.0;
|
||||
pose_to_grid.apply(r.robot_pose.pose.position.x, r.robot_pose.pose.position.y, gx, gy);
|
||||
const double gyaw = yawOfPose(r.robot_pose) + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw);
|
||||
|
||||
SweepParams params;
|
||||
params.front = r.front;
|
||||
params.rear = r.rear;
|
||||
params.side = r.side;
|
||||
params.padding = r.sampling->padding;
|
||||
params.lookahead = r.sampling->contact_lookahead;
|
||||
params.lethal_threshold = static_cast<unsigned char>(r.sampling->lethal_threshold);
|
||||
|
||||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(grid->getMutex()), boost::defer_lock);
|
||||
if (live)
|
||||
{
|
||||
lock.lock();
|
||||
}
|
||||
|
||||
// 1) Quỹ đạo thật của local planner, quy về frame lưới.
|
||||
if (r.sampling->use_local_plan != "false" && r.local_plan != nullptr && r.local_plan->poses.size() >= 2)
|
||||
{
|
||||
PlanarTransform traj_to_grid;
|
||||
if (planarTransform(*tf_, r.local_plan->header.frame_id, grid_frame, traj_to_grid))
|
||||
{
|
||||
const double dyaw = std::atan2(traj_to_grid.sin_yaw, traj_to_grid.cos_yaw);
|
||||
traj_scratch_.clear();
|
||||
traj_scratch_.reserve(r.local_plan->poses.size());
|
||||
for (const auto& p : r.local_plan->poses)
|
||||
{
|
||||
robot_geometry_msgs::PoseStamped ps;
|
||||
traj_to_grid.apply(p.pose.x, p.pose.y, ps.pose.position.x, ps.pose.position.y);
|
||||
const double yaw = p.pose.theta + dyaw;
|
||||
ps.pose.orientation.z = std::sin(0.5 * yaw);
|
||||
ps.pose.orientation.w = std::cos(0.5 * yaw);
|
||||
traj_scratch_.push_back(ps);
|
||||
}
|
||||
out = move_base2::sweepTrajectory(traj_scratch_, gx, gy, gyaw, r.sampling->local_plan_start_tol,
|
||||
params, *grid, scratch_);
|
||||
if (out.conclusive)
|
||||
{
|
||||
used_local_plan = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (r.sampling->use_local_plan == "true")
|
||||
{
|
||||
return false; // ép dùng quỹ đạo mà không có -> không kết luận
|
||||
}
|
||||
// 2) Cung (v, omega) không đổi — cùng hình học với guard cũ, nhưng cùng bộ dò với quỹ đạo thật.
|
||||
if (std::fabs(r.v) < 1e-3)
|
||||
{
|
||||
out.conclusive = true; // đứng yên / xoay tại chỗ: không có chuyển động tịnh tiến để dò
|
||||
return true;
|
||||
}
|
||||
const double res = grid->getResolution();
|
||||
const double step = res > 0.0 ? res : 0.05;
|
||||
const double direction = r.v < 0.0 ? -1.0 : 1.0;
|
||||
const double kappa = r.omega / r.v;
|
||||
traj_scratch_.clear();
|
||||
const int n = static_cast<int>(std::ceil(r.sampling->contact_lookahead / step));
|
||||
traj_scratch_.reserve(static_cast<std::size_t>(n) + 1);
|
||||
for (int i = 0; i <= n; ++i)
|
||||
{
|
||||
const double s = direction * step * i;
|
||||
robot_geometry_msgs::PoseStamped ps;
|
||||
double yaw = gyaw;
|
||||
if (std::fabs(kappa) < 1e-6)
|
||||
{
|
||||
ps.pose.position.x = gx + s * std::cos(gyaw);
|
||||
ps.pose.position.y = gy + s * std::sin(gyaw);
|
||||
}
|
||||
else
|
||||
{
|
||||
yaw = gyaw + kappa * s;
|
||||
ps.pose.position.x = gx + (std::sin(yaw) - std::sin(gyaw)) / kappa;
|
||||
ps.pose.position.y = gy - (std::cos(yaw) - std::cos(gyaw)) / kappa;
|
||||
}
|
||||
ps.pose.orientation.z = std::sin(0.5 * yaw);
|
||||
ps.pose.orientation.w = std::cos(0.5 * yaw);
|
||||
traj_scratch_.push_back(ps);
|
||||
}
|
||||
out = move_base2::sweepTrajectory(traj_scratch_, gx, gy, gyaw, 1.0, params, *grid, scratch_);
|
||||
return out.conclusive;
|
||||
}
|
||||
|
||||
bool CostmapEnvironment::robotBodyExtents(double& front, double& rear, double& side) const
|
||||
{
|
||||
if (costmap_ == nullptr)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const std::vector<robot_geometry_msgs::Point>& fp = costmap_->getUnpaddedRobotFootprint();
|
||||
if (fp.size() < 3)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
double max_x = std::numeric_limits<double>::lowest();
|
||||
double min_x = std::numeric_limits<double>::max();
|
||||
double max_abs_y = 0.0;
|
||||
for (const robot_geometry_msgs::Point& p : fp)
|
||||
{
|
||||
if (!std::isfinite(p.x) || !std::isfinite(p.y))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
max_x = std::max(max_x, p.x);
|
||||
min_x = std::min(min_x, p.x);
|
||||
max_abs_y = std::max(max_abs_y, std::fabs(p.y));
|
||||
}
|
||||
if (!(max_x > 0.0) || !(min_x < 0.0) || !(max_abs_y > 0.0))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
front = max_x;
|
||||
rear = -min_x;
|
||||
side = max_abs_y;
|
||||
return true;
|
||||
}
|
||||
|
||||
NavigationRuntime::NavigationRuntime() = default;
|
||||
|
||||
NavigationRuntime::~NavigationRuntime()
|
||||
@@ -252,6 +483,10 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr<tf3::BufferCore>& tf
|
||||
path_check_.setCostmap(local_costmap_.get());
|
||||
path_check_.setTf(tf_);
|
||||
|
||||
// EnvMonitor đọc cùng costmap local (thay PathMonitor); TF để quy plan (map) và pose về frame lưới.
|
||||
environment_.setCostmap(local_costmap_.get());
|
||||
environment_.setTf(tf_);
|
||||
|
||||
// Gắn ngay: host có thể hỏi dữ liệu hiển thị bất cứ lúc nào sau initialize(), kể cả trước khi
|
||||
// costmap có nội dung. Exporter tự trả về "chưa có gì" thay vì lưới rỗng.
|
||||
global_exporter_.attach(global_costmap_.get(), config_.global_frame);
|
||||
@@ -501,6 +736,7 @@ ControlLoopDeps NavigationRuntime::deps()
|
||||
deps.action = &action_;
|
||||
deps.costmap_status = &costmap_status_;
|
||||
deps.path_check = &path_check_;
|
||||
deps.environment = &environment_;
|
||||
return deps;
|
||||
}
|
||||
|
||||
|
||||
@@ -80,6 +80,50 @@ bool planarTransform(const tf3::BufferCore& tf, const std::string& from, const s
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t trackedNearestIndex(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
const robot_geometry_msgs::PoseStamped& pose, std::size_t hint,
|
||||
double back_m, double ahead_m)
|
||||
{
|
||||
if (plan.size() < 2)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
const std::size_t last_seg = plan.size() - 2;
|
||||
hint = std::min(hint, last_seg);
|
||||
|
||||
auto seg_len = [&](std::size_t i) {
|
||||
return std::hypot(plan[i + 1].pose.position.x - plan[i].pose.position.x,
|
||||
plan[i + 1].pose.position.y - plan[i].pose.position.y);
|
||||
};
|
||||
std::size_t lo = hint;
|
||||
for (double walked = 0.0; lo > 0 && walked < back_m; --lo)
|
||||
{
|
||||
walked += seg_len(lo - 1);
|
||||
}
|
||||
std::size_t hi = hint;
|
||||
for (double walked = 0.0; hi < last_seg && walked < ahead_m; ++hi)
|
||||
{
|
||||
walked += seg_len(hi);
|
||||
}
|
||||
|
||||
const double px = pose.pose.position.x;
|
||||
const double py = pose.pose.position.y;
|
||||
std::size_t best = hint;
|
||||
double best_distance = std::numeric_limits<double>::max();
|
||||
for (std::size_t i = lo; i <= hi; ++i)
|
||||
{
|
||||
const double distance =
|
||||
pointToSegment(px, py, plan[i].pose.position.x, plan[i].pose.position.y,
|
||||
plan[i + 1].pose.position.x, plan[i + 1].pose.position.y);
|
||||
if (distance < best_distance)
|
||||
{
|
||||
best_distance = distance;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
std::size_t nearestIndex(const std::vector<robot_geometry_msgs::PoseStamped>& plan,
|
||||
const robot_geometry_msgs::PoseStamped& pose)
|
||||
{
|
||||
|
||||
@@ -647,6 +647,17 @@ void ControllerRunner::setMeasuredVelocity(const robot_geometry_msgs::Twist& vel
|
||||
return;
|
||||
}
|
||||
measured_velocity_ = velocity;
|
||||
has_measured_velocity_ = true;
|
||||
}
|
||||
|
||||
bool ControllerRunner::measuredVelocity(robot_geometry_msgs::Twist& out) const
|
||||
{
|
||||
if (!has_measured_velocity_)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
out = measured_velocity_;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ControllerRunner::setTwistLinear(const robot_geometry_msgs::Vector3& linear)
|
||||
|
||||
Reference in New Issue
Block a user