feat: EvadeRecovery plugin (back up or turn to the free side)
- plugins/evade_core.h: pure geometry (polygon footprint, reverse sweep, rotation-arc sweep, free-side choice), tested with point lists - plugins/evade_recovery.cpp: reads raw scans through RecoveryContext::sensors; holds on a short view loss, never drives on stale data - RecoveryContext / behavior ABI additions for the sensor reader
This commit is contained in:
@@ -134,6 +134,8 @@ else()
|
|||||||
robot_geometry_msgs
|
robot_geometry_msgs
|
||||||
robot_nav_msgs
|
robot_nav_msgs
|
||||||
robot_xmlrpcpp
|
robot_xmlrpcpp
|
||||||
|
robot_sensor_msgs
|
||||||
|
robot_sensor_ports
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -157,6 +159,7 @@ else()
|
|||||||
recovery_core_clear_costmap_recovery
|
recovery_core_clear_costmap_recovery
|
||||||
recovery_core_rotate_recovery
|
recovery_core_rotate_recovery
|
||||||
recovery_core_back_up_recovery
|
recovery_core_back_up_recovery
|
||||||
|
recovery_core_evade_recovery
|
||||||
|
|
||||||
CATKIN_DEPENDS
|
CATKIN_DEPENDS
|
||||||
robot_costmap_2d
|
robot_costmap_2d
|
||||||
@@ -165,6 +168,8 @@ else()
|
|||||||
robot_geometry_msgs
|
robot_geometry_msgs
|
||||||
robot_nav_msgs
|
robot_nav_msgs
|
||||||
robot_xmlrpcpp
|
robot_xmlrpcpp
|
||||||
|
robot_sensor_msgs
|
||||||
|
robot_sensor_ports
|
||||||
|
|
||||||
DEPENDS
|
DEPENDS
|
||||||
Boost
|
Boost
|
||||||
@@ -456,6 +461,13 @@ add_recovery_core_plugin(
|
|||||||
plugins/back_up_recovery.cpp
|
plugins/back_up_recovery.cpp
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Phản xạ né (lùi hoặc xoay về phía trống). Đọc scan thô qua RecoveryContext::sensors; chỉ dùng
|
||||||
|
# header của robot_sensor_ports/robot_sensor_msgs (template + message), nên không link thêm gì.
|
||||||
|
add_recovery_core_plugin(
|
||||||
|
recovery_core_evade_recovery
|
||||||
|
plugins/evade_recovery.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# ========================================================
|
# ========================================================
|
||||||
# Install - Catkin
|
# Install - Catkin
|
||||||
@@ -560,6 +572,7 @@ else()
|
|||||||
message(STATUS " recovery_core_clear_costmap_recovery")
|
message(STATUS " recovery_core_clear_costmap_recovery")
|
||||||
message(STATUS " recovery_core_rotate_recovery")
|
message(STATUS " recovery_core_rotate_recovery")
|
||||||
message(STATUS " recovery_core_back_up_recovery")
|
message(STATUS " recovery_core_back_up_recovery")
|
||||||
|
message(STATUS " recovery_core_evade_recovery")
|
||||||
message(STATUS "Dependencies:")
|
message(STATUS "Dependencies:")
|
||||||
message(STATUS " robot_costmap_2d")
|
message(STATUS " robot_costmap_2d")
|
||||||
message(STATUS " robot_cpp")
|
message(STATUS " robot_cpp")
|
||||||
@@ -567,6 +580,8 @@ else()
|
|||||||
message(STATUS " robot_geometry_msgs")
|
message(STATUS " robot_geometry_msgs")
|
||||||
message(STATUS " robot_nav_msgs")
|
message(STATUS " robot_nav_msgs")
|
||||||
message(STATUS " robot_xmlrpcpp")
|
message(STATUS " robot_xmlrpcpp")
|
||||||
|
message(STATUS " robot_sensor_msgs (headers)")
|
||||||
|
message(STATUS " robot_sensor_ports (headers)")
|
||||||
message(STATUS " tf3")
|
message(STATUS " tf3")
|
||||||
message(STATUS " Boost")
|
message(STATUS " Boost")
|
||||||
message(STATUS " yaml-cpp")
|
message(STATUS " yaml-cpp")
|
||||||
@@ -606,6 +621,7 @@ if(BUILD_RECOVERY_CORE_TESTS AND CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN)
|
|||||||
pose_progress_test
|
pose_progress_test
|
||||||
rotate_safety_test
|
rotate_safety_test
|
||||||
registry_test
|
registry_test
|
||||||
|
evade_recovery_test
|
||||||
)
|
)
|
||||||
|
|
||||||
foreach(test_name ${RECOVERY_CORE_TESTS})
|
foreach(test_name ${RECOVERY_CORE_TESTS})
|
||||||
|
|||||||
13
README.md
13
README.md
@@ -52,7 +52,7 @@ caller route theo `output_type` được mà không cần tin lời hứa trong
|
|||||||
| Họ | Behavior mặc định | Output | Cổng bắt buộc trong context |
|
| Họ | Behavior mặc định | Output | Cổng bắt buộc trong context |
|
||||||
|----|-------------------|--------|------------------------------|
|
|----|-------------------|--------|------------------------------|
|
||||||
| `kNone` | `WaitRecovery`, `ClearCostmapRecovery` | không | — (clear costmap cần con trỏ costmap) |
|
| `kNone` | `WaitRecovery`, `ClearCostmapRecovery` | không | — (clear costmap cần con trỏ costmap) |
|
||||||
| `kVelocity` | `RotateRecovery`, `BackUpRecovery` | `robot_geometry_msgs::Twist` mỗi cycle | `PoseProvider` + `CollisionChecker` |
|
| `kVelocity` | `RotateRecovery`, `BackUpRecovery`, `EvadeRecovery` | `robot_geometry_msgs::Twist` mỗi cycle | `PoseProvider` + `CollisionChecker`; `EvadeRecovery` cần thêm `local_costmap`, `sensors`, `tf` (thiếu thì từ chối start) |
|
||||||
| `kPath` | (chưa có) | `robot_nav_msgs::Path` | `PlanProvider` |
|
| `kPath` | (chưa có) | `robot_nav_msgs::Path` | `PlanProvider` |
|
||||||
|
|
||||||
Đọc dữ liệu qua `result.velocity()` / `result.pathOut()` — trả `nullptr` nếu họ không khớp, nên
|
Đọc dữ liệu qua `result.velocity()` / `result.pathOut()` — trả `nullptr` nếu họ không khớp, nên
|
||||||
@@ -71,6 +71,12 @@ hỏng thì sang cái kế tiếp. Sắp từ nhẹ tới nặng.
|
|||||||
| 3 | `aggressive_reset` | `ClearCostmapRecovery` | Ngược lại: giữ vùng gần, xoá tất cả phần còn lại |
|
| 3 | `aggressive_reset` | `ClearCostmapRecovery` | Ngược lại: giữ vùng gần, xoá tất cả phần còn lại |
|
||||||
| 4 | `back_up` | `BackUpRecovery` | Lùi `backup_distance` mét. Xếp **cuối** vì lùi là hướng robot thường không có sensor |
|
| 4 | `back_up` | `BackUpRecovery` | Lùi `backup_distance` mét. Xếp **cuối** vì lùi là hướng robot thường không có sensor |
|
||||||
|
|
||||||
|
Ngoài bộ mặc định (không nằm trong route nào cho tới khi có `IntrusionDetector`):
|
||||||
|
|
||||||
|
| Instance | Plugin | Làm gì |
|
||||||
|
|----------|--------|--------|
|
||||||
|
| `evade` | `EvadeRecovery` | Phản xạ né vật sát thân: lùi thẳng `backup_distance` (0.2 m); phía sau không đủ chỗ thì xoay tại chỗ tới hướng trống nhất (d lớn nhất, hoà thì xoay ít nhất); không động tác nào khả thi thì từ chối start. Vật cản = điểm lidar thô (`RecoveryContext::sensors`, TF tại stamp scan) + ô LETHAL của local costmap, kiểm bằng footprint không padding — không dùng `CostmapCollisionChecker` (nó coi ô 253 là chắn nên kẹt trong khe 3 cm). Kiểm lại phần chuyển động còn lại mỗi tick với scan mới nhất. Lõi hình học thuần ở `plugins/evade_core.h` |
|
||||||
|
|
||||||
Không có behavior "chỉ xin lập plan lại": state machine của `move_base2` đã tự lập plan lại sau mọi
|
Không có behavior "chỉ xin lập plan lại": state machine của `move_base2` đã tự lập plan lại sau mọi
|
||||||
lượt recovery kết thúc, nên một behavior như vậy chỉ chiếm chỗ mà không làm gì.
|
lượt recovery kết thúc, nên một behavior như vậy chỉ chiếm chỗ mà không làm gì.
|
||||||
|
|
||||||
@@ -97,8 +103,9 @@ include/recovery_core/ recovery_context.h, recovery_types.h, recovery_behavior
|
|||||||
recovery_registry.h, recovery_math.h, adapters/
|
recovery_registry.h, recovery_math.h, adapters/
|
||||||
src/ base lifecycle + types + registry
|
src/ base lifecycle + types + registry
|
||||||
adapters/ CostmapPoseProvider, CostmapCollisionChecker (nối vào costmap thật)
|
adapters/ CostmapPoseProvider, CostmapCollisionChecker (nối vào costmap thật)
|
||||||
plugins/ wait, clear_costmap, rotate, back_up — bộ mặc định, mỗi cái một .so
|
plugins/ wait, clear_costmap, rotate, back_up — bộ mặc định, mỗi cái một .so;
|
||||||
test/ 9 bộ test GTest + cây config riêng
|
evade (+ evade_core.h: hình học thuần, test không cần costmap)
|
||||||
|
test/ 10 bộ test GTest + cây config riêng
|
||||||
docs/ ARCHITECTURE.md, SAFETY.md, PLUGIN_GUIDE.md
|
docs/ ARCHITECTURE.md, SAFETY.md, PLUGIN_GUIDE.md
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -24,8 +24,9 @@ namespace recovery_core
|
|||||||
*
|
*
|
||||||
* 1 — trước 2026-09-11 (không có symbol; registry coi là "không khai").
|
* 1 — trước 2026-09-11 (không có symbol; registry coi là "không khai").
|
||||||
* 2 — 2026-09-11: thêm virtual `onCancelRequested()`.
|
* 2 — 2026-09-11: thêm virtual `onCancelRequested()`.
|
||||||
|
* 3 — 2026-11-26: thêm `RecoveryContext::sensors` (EvadeRecovery đọc scan lidar) — đổi layout struct.
|
||||||
*/
|
*/
|
||||||
constexpr int kRecoveryAbiVersion = 2;
|
constexpr int kRecoveryAbiVersion = 3;
|
||||||
|
|
||||||
/// Hàm được export kèm mỗi plugin qua @ref RECOVERY_CORE_EXPORT_BEHAVIOR; trả @ref kRecoveryAbiVersion.
|
/// Hàm được export kèm mỗi plugin qua @ref RECOVERY_CORE_EXPORT_BEHAVIOR; trả @ref kRecoveryAbiVersion.
|
||||||
inline int recoveryAbiVersion()
|
inline int recoveryAbiVersion()
|
||||||
|
|||||||
@@ -197,6 +197,13 @@ protected:
|
|||||||
return cancel_requested_;
|
return cancel_requested_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @brief Mốc `now` của `start()` — đã đặt TRƯỚC khi gọi @ref onStart, để plugin đo tuổi dữ liệu
|
||||||
|
/// theo cùng đồng hồ của caller thay vì tự gọi `robot::Time::now()` (sim time ≠ wall time).
|
||||||
|
const robot::Time& startTime() const
|
||||||
|
{
|
||||||
|
return start_time_;
|
||||||
|
}
|
||||||
|
|
||||||
/// @brief Stop output đúng họ của behavior này, kèm @p status.
|
/// @brief Stop output đúng họ của behavior này, kèm @p status.
|
||||||
RecoveryResult stopResult(RecoveryStatus status) const;
|
RecoveryResult stopResult(RecoveryStatus status) const;
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ namespace robot_costmap_2d { class Costmap2DROBOT; }
|
|||||||
|
|
||||||
// Forward declare: chỉ plugin nào thật sự đổi frame mới include tf3; recovery_core không link tf3.
|
// Forward declare: chỉ plugin nào thật sự đổi frame mới include tf3; recovery_core không link tf3.
|
||||||
namespace tf3 { class BufferCore; }
|
namespace tf3 { class BufferCore; }
|
||||||
|
namespace robot_sensor_ports { class SensorReader; }
|
||||||
|
|
||||||
namespace recovery_core
|
namespace recovery_core
|
||||||
{
|
{
|
||||||
@@ -187,6 +188,9 @@ struct RecoveryContext
|
|||||||
* `action_core::ActionContext::tf`.
|
* `action_core::ActionContext::tf`.
|
||||||
*/
|
*/
|
||||||
tf3::BufferCore* tf = nullptr;
|
tf3::BufferCore* tf = nullptr;
|
||||||
|
|
||||||
|
/// Kho sensor của host (non-owning). nullptr = host không cấp sensors; plugin cần scan phải từ chối start.
|
||||||
|
const robot_sensor_ports::SensorReader* sensors = nullptr;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace recovery_core
|
} // namespace recovery_core
|
||||||
|
|||||||
@@ -44,6 +44,14 @@
|
|||||||
<build_depend>yaml-cpp</build_depend>
|
<build_depend>yaml-cpp</build_depend>
|
||||||
<run_depend>yaml-cpp</run_depend>
|
<run_depend>yaml-cpp</run_depend>
|
||||||
|
|
||||||
|
<!-- Kho cảm biến thô dùng chung (RecoveryContext::sensors). Contract chỉ khai báo trước
|
||||||
|
SensorReader; EvadeRecovery đọc LaserScan qua template header-only, không link thêm. -->
|
||||||
|
<build_depend>robot_sensor_msgs</build_depend>
|
||||||
|
<run_depend>robot_sensor_msgs</run_depend>
|
||||||
|
|
||||||
|
<build_depend>robot_sensor_ports</build_depend>
|
||||||
|
<run_depend>robot_sensor_ports</run_depend>
|
||||||
|
|
||||||
<!-- Chỉ dùng cho test: fake clock/costmap/pose/collision. Gói chỉ có trên máy dev, nên chỉ là
|
<!-- Chỉ dùng cho test: fake clock/costmap/pose/collision. Gói chỉ có trên máy dev, nên chỉ là
|
||||||
test_depend; CMake chỉ find_package nó khi bật BUILD_RECOVERY_CORE_TESTS. -->
|
test_depend; CMake chỉ find_package nó khi bật BUILD_RECOVERY_CORE_TESTS. -->
|
||||||
<test_depend>nav_test_harness</test_depend>
|
<test_depend>nav_test_harness</test_depend>
|
||||||
|
|||||||
564
plugins/evade_core.h
Normal file
564
plugins/evade_core.h
Normal file
@@ -0,0 +1,564 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* recovery_core — hình học thuần của EvadeRecovery: footprint đa giác, quét lùi, quét cung xoay,
|
||||||
|
* chọn hướng trống. Không phụ thuộc costmap, TF hay sensor store, nên test thẳng bằng danh sách
|
||||||
|
* điểm (test/evade_recovery_test.cpp).
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#ifndef RECOVERY_CORE_PLUGINS_EVADE_CORE_H_
|
||||||
|
#define RECOVERY_CORE_PLUGINS_EVADE_CORE_H_
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace recovery_plugins
|
||||||
|
{
|
||||||
|
namespace evade
|
||||||
|
{
|
||||||
|
|
||||||
|
constexpr double kPi = 3.14159265358979323846;
|
||||||
|
|
||||||
|
/// [m] bước lấy mẫu dọc quãng lùi (mục 6.2 bước 5 của plan).
|
||||||
|
constexpr double kLinearSampleStep = 0.02;
|
||||||
|
/// [m] bước đẩy footprint tới trước khi đo quãng trống d(ψ).
|
||||||
|
constexpr double kProbeStep = 0.05;
|
||||||
|
/// [m] cung tối đa mà góc thân xa nhất đi được giữa hai mẫu góc khi quét xoay.
|
||||||
|
constexpr double kArcSampleAtCorner = 0.02;
|
||||||
|
/// [m] hai hướng có d chênh nhau không quá mức này thì coi là hoà, chọn hướng xoay ít hơn.
|
||||||
|
constexpr double kTieDistance = 0.05;
|
||||||
|
/// [rad] hướng thắng lệch hướng đang quay mặt ít hơn mức này thì coi là đã quay ra phía trống (4a).
|
||||||
|
constexpr double kFacingTolerance = 10.0 * kPi / 180.0;
|
||||||
|
|
||||||
|
struct Point2
|
||||||
|
{
|
||||||
|
double x = 0.0; ///< [m]
|
||||||
|
double y = 0.0; ///< [m]
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Pose2
|
||||||
|
{
|
||||||
|
double x = 0.0; ///< [m]
|
||||||
|
double y = 0.0; ///< [m]
|
||||||
|
double yaw = 0.0; ///< [rad]
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Footprint trong frame thân robot (base), không padding. Thứ tự đỉnh tuỳ ý (CW hay CCW đều được).
|
||||||
|
using Polygon = std::vector<Point2>;
|
||||||
|
|
||||||
|
/// Tham số quyết định, đã validate ở onConfigure().
|
||||||
|
struct Params
|
||||||
|
{
|
||||||
|
double backup_distance = 0.20; ///< [m] quãng lùi
|
||||||
|
double motion_margin = 0.05; ///< [m] biên chỉ cộng theo chiều chuyển động
|
||||||
|
double min_free_distance = 0.30; ///< [m] d(ψ) tối thiểu để một hướng được coi là trống
|
||||||
|
double max_probe_distance = 1.0; ///< [m] trần khi đo d(ψ)
|
||||||
|
double heading_step = 10.0 * kPi / 180.0; ///< [rad] bước lấy mẫu hướng ứng viên
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class Motion
|
||||||
|
{
|
||||||
|
kNone, ///< Không động tác nào khả thi.
|
||||||
|
kBackUp, ///< Lùi thẳng backup_distance.
|
||||||
|
kRotate, ///< Xoay tại chỗ một góc có dấu.
|
||||||
|
kAlreadyFacing ///< Hướng thắng chính là hướng đang quay mặt: không cần chuyển động (4a).
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Decision
|
||||||
|
{
|
||||||
|
Motion motion = Motion::kNone;
|
||||||
|
double rotation = 0.0; ///< [rad] có dấu, + = ngược chiều kim đồng hồ. Chỉ cho kRotate.
|
||||||
|
double heading = 0.0; ///< [rad] hướng thắng ψ trong frame của pose
|
||||||
|
double free_distance = 0.0; ///< [m] d(ψ) của hướng thắng
|
||||||
|
double backup_blocked_at = -1.0; ///< [m] s đầu tiên bị chắn khi lùi; < 0 = lùi trống
|
||||||
|
int feasible_headings = 0; ///< số hướng khả thi (cung trống và d >= min_free_distance)
|
||||||
|
};
|
||||||
|
|
||||||
|
inline double normalizeAngle(double angle)
|
||||||
|
{
|
||||||
|
return std::atan2(std::sin(angle), std::cos(angle));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ray casting chẵn-lẻ. Điểm đúng trên cạnh rơi vào bên nào cũng được: motion_margin phủ phần đó.
|
||||||
|
inline bool insidePolygon(const Polygon& polygon, double x, double y)
|
||||||
|
{
|
||||||
|
if (polygon.size() < 3)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
bool inside = false;
|
||||||
|
for (std::size_t i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++)
|
||||||
|
{
|
||||||
|
const Point2& a = polygon[i];
|
||||||
|
const Point2& b = polygon[j];
|
||||||
|
if ((a.y > y) != (b.y > y) && x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x)
|
||||||
|
{
|
||||||
|
inside = !inside;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return inside;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [m] khoảng cách từ tâm thân tới đỉnh xa nhất (bán kính đường tròn ngoại tiếp quanh base).
|
||||||
|
inline double circumradius(const Polygon& polygon)
|
||||||
|
{
|
||||||
|
double r2 = 0.0;
|
||||||
|
for (const Point2& p : polygon)
|
||||||
|
{
|
||||||
|
r2 = std::max(r2, p.x * p.x + p.y * p.y);
|
||||||
|
}
|
||||||
|
return std::sqrt(r2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @return true nếu có điểm nào của @p obstacles (cùng frame với @p pose) nằm trong footprint đặt tại @p pose.
|
||||||
|
inline bool footprintHits(const Polygon& footprint, double r_max, const Pose2& pose,
|
||||||
|
const std::vector<Point2>& obstacles)
|
||||||
|
{
|
||||||
|
const double c = std::cos(pose.yaw);
|
||||||
|
const double s = std::sin(pose.yaw);
|
||||||
|
const double r2 = r_max * r_max;
|
||||||
|
for (const Point2& p : obstacles)
|
||||||
|
{
|
||||||
|
const double dx = p.x - pose.x;
|
||||||
|
const double dy = p.y - pose.y;
|
||||||
|
if (dx * dx + dy * dy > r2)
|
||||||
|
{
|
||||||
|
continue; // ngoài đường tròn ngoại tiếp thì không thể nằm trong đa giác
|
||||||
|
}
|
||||||
|
if (insidePolygon(footprint, c * dx + s * dy, -s * dx + c * dy))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Giữ các điểm cách tâm @p pose không quá @p radius và nằm NGOÀI footprint tại @p pose.
|
||||||
|
*
|
||||||
|
* Điểm trong footprint tại pose hiện tại là nhiễu hoặc phản xạ từ chính thân robot: robot đang đứng
|
||||||
|
* đó nên không thể có vật thật ở đó. Giữ chúng lại thì mọi động tác đều bị coi là chắn ngay mẫu đầu.
|
||||||
|
*/
|
||||||
|
inline std::vector<Point2> keepOutsideFootprint(const Polygon& footprint, const Pose2& pose,
|
||||||
|
double radius, const std::vector<Point2>& points)
|
||||||
|
{
|
||||||
|
std::vector<Point2> kept;
|
||||||
|
kept.reserve(points.size());
|
||||||
|
const double c = std::cos(pose.yaw);
|
||||||
|
const double s = std::sin(pose.yaw);
|
||||||
|
const double r2 = radius * radius;
|
||||||
|
for (const Point2& p : points)
|
||||||
|
{
|
||||||
|
const double dx = p.x - pose.x;
|
||||||
|
const double dy = p.y - pose.y;
|
||||||
|
if (dx * dx + dy * dy > r2)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!insidePolygon(footprint, c * dx + s * dy, -s * dx + c * dy))
|
||||||
|
{
|
||||||
|
kept.push_back(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return kept;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Quét lùi thẳng (ngược hướng @p from.yaw) quãng @p distance, bước <= kLinearSampleStep.
|
||||||
|
* @return s [m] của mẫu đầu tiên bị chắn, hoặc -1 nếu cả quãng trống.
|
||||||
|
*/
|
||||||
|
inline double backupBlockedAt(const Polygon& footprint, double r_max, const Pose2& from,
|
||||||
|
double distance, const std::vector<Point2>& obstacles)
|
||||||
|
{
|
||||||
|
const int samples = std::max(1, static_cast<int>(std::ceil(distance / kLinearSampleStep)));
|
||||||
|
const double c = std::cos(from.yaw);
|
||||||
|
const double s = std::sin(from.yaw);
|
||||||
|
for (int i = 0; i <= samples; ++i)
|
||||||
|
{
|
||||||
|
const double travel = distance * static_cast<double>(i) / samples;
|
||||||
|
const Pose2 pose{from.x - c * travel, from.y - s * travel, from.yaw};
|
||||||
|
if (footprintHits(footprint, r_max, pose, obstacles))
|
||||||
|
{
|
||||||
|
return travel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Quét cung xoay tại chỗ từ @p from theo góc có dấu @p angle, cộng thêm @p overshoot [rad].
|
||||||
|
* @return true nếu footprint ở mọi mẫu góc đều không chứa vật cản.
|
||||||
|
*/
|
||||||
|
inline bool arcClear(const Polygon& footprint, double r_max, const Pose2& from, double angle,
|
||||||
|
double overshoot, const std::vector<Point2>& obstacles)
|
||||||
|
{
|
||||||
|
const double sweep = std::abs(angle) + overshoot;
|
||||||
|
const double direction = angle >= 0.0 ? 1.0 : -1.0;
|
||||||
|
const double step = kArcSampleAtCorner / std::max(r_max, 1e-3);
|
||||||
|
const int samples = std::max(1, static_cast<int>(std::ceil(sweep / step)));
|
||||||
|
for (int i = 0; i <= samples; ++i)
|
||||||
|
{
|
||||||
|
const Pose2 pose{from.x, from.y, from.yaw + direction * sweep * static_cast<double>(i) / samples};
|
||||||
|
if (footprintHits(footprint, r_max, pose, obstacles))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Quãng trống d(ψ): đẩy footprint thẳng tới trước theo @p heading từng bước kProbeStep.
|
||||||
|
* @return [m] quãng xa nhất còn trống, tối đa @p max_probe.
|
||||||
|
*/
|
||||||
|
inline double freeDistance(const Polygon& footprint, double r_max, const Pose2& from,
|
||||||
|
double heading, double max_probe, const std::vector<Point2>& obstacles)
|
||||||
|
{
|
||||||
|
const int steps = static_cast<int>(std::floor(max_probe / kProbeStep + 1e-9));
|
||||||
|
const double c = std::cos(heading);
|
||||||
|
const double s = std::sin(heading);
|
||||||
|
for (int i = 1; i <= steps; ++i)
|
||||||
|
{
|
||||||
|
const double travel = kProbeStep * i;
|
||||||
|
const Pose2 pose{from.x + c * travel, from.y + s * travel, heading};
|
||||||
|
if (footprintHits(footprint, r_max, pose, obstacles))
|
||||||
|
{
|
||||||
|
return kProbeStep * (i - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return max_probe;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Chọn động tác né từ pose @p start, với tập vật cản @p obstacles đã bỏ điểm trong footprint.
|
||||||
|
*
|
||||||
|
* Bước 1: lùi thẳng nếu cả quãng `backup_distance + motion_margin` trống. Bước 2: xét các hướng
|
||||||
|
* ψ_k = yaw + k·heading_step; hướng khả thi khi cung xoay tới đó (thử chiều ngắn trước, chiều dài
|
||||||
|
* sau, vượt đích motion_margin / r_max) trống và d(ψ) >= min_free_distance. Thắng = d lớn nhất; các
|
||||||
|
* hướng có d trong kTieDistance của d lớn nhất thì chọn hướng xoay ít nhất.
|
||||||
|
*/
|
||||||
|
inline Decision decide(const Polygon& footprint, const Pose2& start, const Params& params,
|
||||||
|
const std::vector<Point2>& obstacles)
|
||||||
|
{
|
||||||
|
Decision decision;
|
||||||
|
const double r_max = circumradius(footprint);
|
||||||
|
|
||||||
|
decision.backup_blocked_at = backupBlockedAt(footprint, r_max, start,
|
||||||
|
params.backup_distance + params.motion_margin,
|
||||||
|
obstacles);
|
||||||
|
if (decision.backup_blocked_at < 0.0)
|
||||||
|
{
|
||||||
|
decision.motion = Motion::kBackUp;
|
||||||
|
decision.heading = start.yaw;
|
||||||
|
return decision;
|
||||||
|
}
|
||||||
|
|
||||||
|
const double overshoot = params.motion_margin / std::max(r_max, 1e-3);
|
||||||
|
const int count = std::max(1, static_cast<int>(std::floor(2.0 * kPi / params.heading_step + 1e-9)));
|
||||||
|
|
||||||
|
struct Candidate
|
||||||
|
{
|
||||||
|
double rotation;
|
||||||
|
double heading;
|
||||||
|
double free_distance;
|
||||||
|
};
|
||||||
|
std::vector<Candidate> feasible;
|
||||||
|
feasible.reserve(static_cast<std::size_t>(count));
|
||||||
|
|
||||||
|
for (int k = 0; k < count; ++k)
|
||||||
|
{
|
||||||
|
const double short_turn = normalizeAngle(k * params.heading_step);
|
||||||
|
const double heading = start.yaw + short_turn;
|
||||||
|
const double d = freeDistance(footprint, r_max, start, heading, params.max_probe_distance,
|
||||||
|
obstacles);
|
||||||
|
if (d < params.min_free_distance)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
double rotation = 0.0;
|
||||||
|
bool reachable = (k == 0); // hướng hiện tại: không xoay, không cần cung
|
||||||
|
if (!reachable)
|
||||||
|
{
|
||||||
|
if (arcClear(footprint, r_max, start, short_turn, overshoot, obstacles))
|
||||||
|
{
|
||||||
|
rotation = short_turn;
|
||||||
|
reachable = true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
const double long_turn = short_turn - std::copysign(2.0 * kPi, short_turn);
|
||||||
|
if (arcClear(footprint, r_max, start, long_turn, overshoot, obstacles))
|
||||||
|
{
|
||||||
|
rotation = long_turn;
|
||||||
|
reachable = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (reachable)
|
||||||
|
{
|
||||||
|
feasible.push_back({rotation, heading, d});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
decision.feasible_headings = static_cast<int>(feasible.size());
|
||||||
|
if (feasible.empty())
|
||||||
|
{
|
||||||
|
return decision;
|
||||||
|
}
|
||||||
|
|
||||||
|
double best_distance = 0.0;
|
||||||
|
for (const Candidate& c : feasible)
|
||||||
|
{
|
||||||
|
best_distance = std::max(best_distance, c.free_distance);
|
||||||
|
}
|
||||||
|
const Candidate* winner = nullptr;
|
||||||
|
for (const Candidate& c : feasible)
|
||||||
|
{
|
||||||
|
if (c.free_distance + kTieDistance + 1e-9 < best_distance)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (winner == nullptr || std::abs(c.rotation) < std::abs(winner->rotation))
|
||||||
|
{
|
||||||
|
winner = &c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
decision.rotation = winner->rotation;
|
||||||
|
decision.heading = normalizeAngle(winner->heading);
|
||||||
|
decision.free_distance = winner->free_distance;
|
||||||
|
decision.motion = std::abs(winner->rotation) < kFacingTolerance ? Motion::kAlreadyFacing
|
||||||
|
: Motion::kRotate;
|
||||||
|
return decision;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Giới hạn chuyển động của một lượt né (độ lớn, đã validate > 0).
|
||||||
|
struct MotionLimits
|
||||||
|
{
|
||||||
|
double backup_speed = 0.15; ///< [m/s]
|
||||||
|
double rotate_speed = 0.5; ///< [rad/s]
|
||||||
|
double acc_lim_x = 0.3; ///< [m/s^2]
|
||||||
|
double acc_lim_theta = 0.8; ///< [rad/s^2]
|
||||||
|
};
|
||||||
|
|
||||||
|
/// [m] dung sai đích khi lùi.
|
||||||
|
constexpr double kBackupTolerance = 0.01;
|
||||||
|
/// [rad] dung sai đích khi xoay.
|
||||||
|
constexpr double kRotateTolerance = 0.035;
|
||||||
|
|
||||||
|
enum class TickStatus
|
||||||
|
{
|
||||||
|
kRunning,
|
||||||
|
kSucceeded,
|
||||||
|
kFailed ///< phải phát lệnh 0: pose hỏng hoặc phần chuyển động còn lại bị chắn
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Tick
|
||||||
|
{
|
||||||
|
TickStatus status = TickStatus::kFailed;
|
||||||
|
double vx = 0.0; ///< [m/s] âm = lùi
|
||||||
|
double wz = 0.0; ///< [rad/s] + = ngược chiều kim đồng hồ
|
||||||
|
double progress = 0.0; ///< [0, 1]
|
||||||
|
double remaining = 0.0; ///< [m] hoặc [rad]
|
||||||
|
const char* message = "";
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class Executor
|
||||||
|
* @brief Chạy động tác đã chọn, mỗi tick: đo tiến độ bằng pose thật, kiểm lại phần CÒN LẠI với tập
|
||||||
|
* vật cản mới nhất, rồi sinh lệnh có ramp. Thuần, không I/O.
|
||||||
|
*
|
||||||
|
* Lùi: quãng đo dọc trục thân lúc bắt đầu; lệnh chỉ có vx < 0. Xoay: góc cộng dồn có dấu theo chiều
|
||||||
|
* xoay (unwrap); lệnh chỉ có wz. Vận tốc không vượt độ lớn cấu hình, không tăng quá acc_lim·dt mỗi
|
||||||
|
* tick, và không vượt phần còn lại / dt (giảm tốc khi gần đích, như BackUpRecovery/RotateRecovery).
|
||||||
|
*/
|
||||||
|
class Executor
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
void start(const Polygon& footprint, const Pose2& start, const Decision& decision,
|
||||||
|
const Params& params, const MotionLimits& limits)
|
||||||
|
{
|
||||||
|
footprint_ = footprint;
|
||||||
|
r_max_ = circumradius(footprint);
|
||||||
|
start_ = start;
|
||||||
|
decision_ = decision;
|
||||||
|
params_ = params;
|
||||||
|
limits_ = limits;
|
||||||
|
last_yaw_ = start.yaw;
|
||||||
|
rotated_ = 0.0;
|
||||||
|
current_speed_ = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @param obstacles Vật cản cùng frame với @p current, ĐÃ bỏ điểm trong footprint tại @p current.
|
||||||
|
Tick tick(const Pose2& current, const std::vector<Point2>& obstacles, double dt)
|
||||||
|
{
|
||||||
|
if (decision_.motion == Motion::kAlreadyFacing)
|
||||||
|
{
|
||||||
|
return finish(TickStatus::kSucceeded, "evade: already facing the free side");
|
||||||
|
}
|
||||||
|
if (decision_.motion == Motion::kNone)
|
||||||
|
{
|
||||||
|
return finish(TickStatus::kFailed, "evade: no feasible motion");
|
||||||
|
}
|
||||||
|
if (!std::isfinite(current.x) || !std::isfinite(current.y) || !std::isfinite(current.yaw))
|
||||||
|
{
|
||||||
|
return finish(TickStatus::kFailed, "robot pose is NaN/Inf — stopping the evade");
|
||||||
|
}
|
||||||
|
if (!std::isfinite(dt) || dt < 0.0)
|
||||||
|
{
|
||||||
|
dt = 0.0;
|
||||||
|
}
|
||||||
|
return decision_.motion == Motion::kBackUp ? tickBackUp(current, obstacles, dt)
|
||||||
|
: tickRotate(current, obstacles, dt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The caller published 0 this tick (obstacle view lost): restart the ramp from 0 when motion resumes.
|
||||||
|
void hold()
|
||||||
|
{
|
||||||
|
current_speed_ = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
Tick finish(TickStatus status, const char* message)
|
||||||
|
{
|
||||||
|
current_speed_ = 0.0;
|
||||||
|
Tick t;
|
||||||
|
t.status = status;
|
||||||
|
t.progress = status == TickStatus::kSucceeded ? 1.0 : 0.0;
|
||||||
|
t.message = message;
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
double nextSpeed(double target, double acc_lim, double remaining, double dt) const
|
||||||
|
{
|
||||||
|
if (dt <= 0.0)
|
||||||
|
{
|
||||||
|
return current_speed_; // tick cùng mốc với start: chưa có thời gian để tăng tốc
|
||||||
|
}
|
||||||
|
const double step = acc_lim * dt;
|
||||||
|
double speed = target > current_speed_ ? std::min(target, current_speed_ + step)
|
||||||
|
: std::max(target, current_speed_ - step);
|
||||||
|
speed = std::min(speed, remaining / dt);
|
||||||
|
return std::max(speed, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Tick tickBackUp(const Pose2& current, const std::vector<Point2>& obstacles, double dt)
|
||||||
|
{
|
||||||
|
const double traveled = -((current.x - start_.x) * std::cos(start_.yaw) +
|
||||||
|
(current.y - start_.y) * std::sin(start_.yaw));
|
||||||
|
const double remaining = params_.backup_distance - traveled;
|
||||||
|
if (remaining <= kBackupTolerance)
|
||||||
|
{
|
||||||
|
return finish(TickStatus::kSucceeded, "evade back-up complete");
|
||||||
|
}
|
||||||
|
if (backupBlockedAt(footprint_, r_max_, current, remaining + params_.motion_margin,
|
||||||
|
obstacles) >= 0.0)
|
||||||
|
{
|
||||||
|
return finish(TickStatus::kFailed, "obstacle entered the back-up path — stopping the evade");
|
||||||
|
}
|
||||||
|
current_speed_ = nextSpeed(limits_.backup_speed, limits_.acc_lim_x, remaining, dt);
|
||||||
|
Tick t;
|
||||||
|
t.status = TickStatus::kRunning;
|
||||||
|
t.vx = -current_speed_;
|
||||||
|
t.progress = traveled / params_.backup_distance;
|
||||||
|
t.remaining = remaining;
|
||||||
|
t.message = "evade: backing up";
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
Tick tickRotate(const Pose2& current, const std::vector<Point2>& obstacles, double dt)
|
||||||
|
{
|
||||||
|
const double direction = decision_.rotation >= 0.0 ? 1.0 : -1.0;
|
||||||
|
// Có dấu: quay ngược chiều (trượt) không bị tính là tiến; cộng dồn từng bước nên vượt π vẫn đúng.
|
||||||
|
rotated_ += direction * normalizeAngle(current.yaw - last_yaw_);
|
||||||
|
last_yaw_ = current.yaw;
|
||||||
|
|
||||||
|
const double target = std::abs(decision_.rotation);
|
||||||
|
const double remaining = target - rotated_;
|
||||||
|
if (remaining <= kRotateTolerance)
|
||||||
|
{
|
||||||
|
return finish(TickStatus::kSucceeded, "evade rotation complete");
|
||||||
|
}
|
||||||
|
const double overshoot = params_.motion_margin / std::max(r_max_, 1e-3);
|
||||||
|
if (!arcClear(footprint_, r_max_, current, direction * remaining, overshoot, obstacles))
|
||||||
|
{
|
||||||
|
return finish(TickStatus::kFailed, "obstacle entered the rotation arc — stopping the evade");
|
||||||
|
}
|
||||||
|
current_speed_ = nextSpeed(limits_.rotate_speed, limits_.acc_lim_theta, remaining, dt);
|
||||||
|
Tick t;
|
||||||
|
t.status = TickStatus::kRunning;
|
||||||
|
t.wz = direction * current_speed_;
|
||||||
|
t.progress = rotated_ / target;
|
||||||
|
t.remaining = remaining;
|
||||||
|
t.message = "evade: rotating";
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
Polygon footprint_;
|
||||||
|
double r_max_ = 0.0; ///< [m]
|
||||||
|
Pose2 start_;
|
||||||
|
Decision decision_;
|
||||||
|
Params params_;
|
||||||
|
MotionLimits limits_;
|
||||||
|
double last_yaw_ = 0.0; ///< [rad]
|
||||||
|
double rotated_ = 0.0; ///< [rad] tiến độ có dấu theo chiều xoay
|
||||||
|
double current_speed_ = 0.0; ///< [m/s] hoặc [rad/s] đang phát, để ramp
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class ViewGuard
|
||||||
|
* @brief Tolerates a short loss of the obstacle view (stale scan, TF a little late): hold still while it lasts,
|
||||||
|
* give up once it has lasted `timeout` [s]. Never lets the robot move on old data — it only decides
|
||||||
|
* between "wait" and "fail". Sim 27/11: single late scans (0.53 s) or TF gaps (0.13 s) killed a back-up.
|
||||||
|
*/
|
||||||
|
class ViewGuard
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
enum class State
|
||||||
|
{
|
||||||
|
kSeeing, ///< fresh view this tick
|
||||||
|
kHolding, ///< lost, still within the timeout: publish 0 and wait
|
||||||
|
kExpired ///< lost for >= timeout: fail
|
||||||
|
};
|
||||||
|
|
||||||
|
void reset()
|
||||||
|
{
|
||||||
|
lost_ = false;
|
||||||
|
since_ = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @param now [s] same clock on every call. @param timeout [s] 0 = fail on the first loss.
|
||||||
|
State update(bool seeing, double now, double timeout)
|
||||||
|
{
|
||||||
|
if (seeing)
|
||||||
|
{
|
||||||
|
lost_ = false;
|
||||||
|
return State::kSeeing;
|
||||||
|
}
|
||||||
|
if (!lost_)
|
||||||
|
{
|
||||||
|
lost_ = true;
|
||||||
|
since_ = now;
|
||||||
|
}
|
||||||
|
return now - since_ >= timeout ? State::kExpired : State::kHolding;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool lost() const
|
||||||
|
{
|
||||||
|
return lost_;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
bool lost_ = false;
|
||||||
|
double since_ = 0.0; ///< [s] when the current loss began
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace evade
|
||||||
|
} // namespace recovery_plugins
|
||||||
|
|
||||||
|
#endif // RECOVERY_CORE_PLUGINS_EVADE_CORE_H_
|
||||||
587
plugins/evade_recovery.cpp
Normal file
587
plugins/evade_recovery.cpp
Normal file
@@ -0,0 +1,587 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Software License Agreement (BSD License)
|
||||||
|
*
|
||||||
|
* recovery_core — phản xạ né khi có vật sát thân: lùi thẳng một đoạn ngắn, không lùi được thì xoay
|
||||||
|
* tại chỗ cho đầu hướng ra phía trống. Vật cản lấy từ điểm lidar thô + ô LETHAL của local costmap,
|
||||||
|
* kiểm bằng footprint thật (không padding), không qua CostmapCollisionChecker.
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
|
||||||
|
#include <recovery_core/recovery_behavior.h>
|
||||||
|
#include <recovery_core/recovery_math.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <exception>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include <robot/robot.h>
|
||||||
|
#include <robot_costmap_2d/cost_values.h>
|
||||||
|
#include <robot_costmap_2d/costmap_2d.h>
|
||||||
|
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||||||
|
#include <robot_sensor_msgs/LaserScan.h>
|
||||||
|
#include <robot_sensor_ports/sensor_reader.h>
|
||||||
|
#include <robot_sensor_ports/sensor_types.h>
|
||||||
|
#include <tf3/buffer_core.h>
|
||||||
|
|
||||||
|
#include <recovery_core/recovery_abi.h>
|
||||||
|
|
||||||
|
#include "evade_core.h"
|
||||||
|
|
||||||
|
namespace recovery_plugins
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
constexpr double kDefaultMaxScanAge = 0.3; // [s]
|
||||||
|
constexpr double kDefaultBackupDistance = 0.20; // [m]
|
||||||
|
constexpr double kDefaultBackupSpeed = 0.15; // [m/s] độ lớn (4b)
|
||||||
|
constexpr double kDefaultRotateSpeed = 0.5; // [rad/s] độ lớn (4b)
|
||||||
|
constexpr double kDefaultAccLimX = 0.3; // [m/s^2]
|
||||||
|
constexpr double kDefaultAccLimTheta = 0.8; // [rad/s^2]
|
||||||
|
constexpr double kDefaultHeadingStepDeg = 10.0; // [deg]
|
||||||
|
constexpr double kDefaultMotionMargin = 0.05; // [m] (4c)
|
||||||
|
constexpr double kDefaultMinFreeDistance = 0.30; // [m] (4c)
|
||||||
|
constexpr double kDefaultMaxProbeDistance = 1.0; // [m]
|
||||||
|
|
||||||
|
constexpr double kMaxLinearSpeed = 1.0; // [m/s] trần vệ sinh cho param sai
|
||||||
|
constexpr double kMaxAngularSpeed = 2.0; // [rad/s] trần vệ sinh cho param sai
|
||||||
|
|
||||||
|
/// [s] TF tại đúng stamp scan chưa có (TF odom->base hay tới sau scan vài ms) thì nhận TF mới nhất
|
||||||
|
/// nếu nó cách stamp không quá mức này. 0.1 s ở 0.15 m/s = 1.5 cm sai lệch vị trí điểm.
|
||||||
|
constexpr double kDefaultMaxTfGap = 0.1;
|
||||||
|
/// [s] Mất dữ liệu ngắn (scan trễ một nhịp, TF lệch) thì đứng yên chờ chừng này rồi mới bỏ cuộc.
|
||||||
|
constexpr double kDefaultViewLossTimeout = 1.0;
|
||||||
|
|
||||||
|
const std::vector<std::string> kDefaultScanTopics{"/f_scan", "/b_scan"};
|
||||||
|
|
||||||
|
/// Quay vector (x, y, 0) bằng quaternion đơn vị, lấy phần x, y. Lidar lắp ngược (roll = π) vẫn đúng.
|
||||||
|
void rotateXY(const tf3::QuaternionMsg& q, double x, double y, double& out_x, double& out_y)
|
||||||
|
{
|
||||||
|
// v' = v + w·t + u×t với t = 2·(u×v), u = (qx, qy, qz), v = (x, y, 0).
|
||||||
|
const double tx = -2.0 * q.z * y;
|
||||||
|
const double ty = 2.0 * q.z * x;
|
||||||
|
const double tz = 2.0 * (q.x * y - q.y * x);
|
||||||
|
out_x = x + q.w * tx + (q.y * tz - q.z * ty);
|
||||||
|
out_y = y + q.w * ty + (q.z * tx - q.x * tz);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool finitePose(const evade::Pose2& pose)
|
||||||
|
{
|
||||||
|
return std::isfinite(pose.x) && std::isfinite(pose.y) && std::isfinite(pose.yaw);
|
||||||
|
}
|
||||||
|
|
||||||
|
evade::Pose2 toPose2(const robot_geometry_msgs::PoseStamped& pose)
|
||||||
|
{
|
||||||
|
return {pose.pose.position.x, pose.pose.position.y, recovery_core::yawOf(pose)};
|
||||||
|
}
|
||||||
|
|
||||||
|
double toDeg(double rad)
|
||||||
|
{
|
||||||
|
return rad * 180.0 / evade::kPi;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class EvadeRecovery
|
||||||
|
* @brief Né vật xâm nhập sát thân: lùi `backup_distance`, hoặc xoay tại chỗ tới hướng trống nhất.
|
||||||
|
*
|
||||||
|
* Một plugin gói cả hai động tác (không ghép back_up + rotate) vì mỗi lần detector nổ, route chỉ chạy
|
||||||
|
* một behavior. Quyết định chốt ở `onStart()` (hàm `evade::decide`) — hoặc ở tick đầu tiên có dữ liệu
|
||||||
|
* mới nếu lúc start scan/TF còn trễ — không có động tác nào thì từ chối/hỏng, không làm thêm việc khác.
|
||||||
|
*
|
||||||
|
* Vì sao không dùng `CostmapCollisionChecker`: nó coi ô INSCRIBED (253) là chắn và chỉ quét biên
|
||||||
|
* footprint, nên trong khe hở 3 cm robot bị coi là "chắn" ngay tại chỗ. Ở đây vật cản là điểm lidar
|
||||||
|
* thô (TF tại stamp scan) cộng tâm ô LETHAL (254), kiểm bằng đa giác footprint không padding; biên
|
||||||
|
* `motion_margin` chỉ cộng theo chiều chuyển động.
|
||||||
|
*
|
||||||
|
* An toàn mỗi tick: lấy scan mới nhất, kiểm phần chuyển động CÒN LẠI; bị chắn hay mất pose thì phát
|
||||||
|
* Twist 0 và trả kFailed. Scan quá tuổi / TF lệch thì phát Twist 0 và CHỜ tối đa `view_loss_timeout`
|
||||||
|
* rồi mới kFailed (sim chạy chậm hay trễ một nhịp). Không bao giờ chạy theo dữ liệu cũ.
|
||||||
|
*
|
||||||
|
* Robot differential: lệnh chỉ có `linear.x` (lùi, âm) hoặc `angular.z` (xoay), không bao giờ cả hai,
|
||||||
|
* không `linear.y`. `goal.distance` / `goal.angle` bị bỏ qua: evade tự chọn động tác từ dữ liệu.
|
||||||
|
*/
|
||||||
|
class EvadeRecovery final : public recovery_core::RecoveryBehavior
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
EvadeRecovery() = default;
|
||||||
|
|
||||||
|
static recovery_core::RecoveryBehavior::RecoveryBehaviorPtr create()
|
||||||
|
{
|
||||||
|
return std::make_shared<EvadeRecovery>();
|
||||||
|
}
|
||||||
|
|
||||||
|
recovery_core::RecoveryOutputType outputKind() const override
|
||||||
|
{
|
||||||
|
return recovery_core::RecoveryOutputType::kVelocity;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
bool onConfigure(robot::NodeHandle& nh) override
|
||||||
|
{
|
||||||
|
double heading_step_deg = kDefaultHeadingStepDeg;
|
||||||
|
nh.param("scan_topics", scan_topics_, kDefaultScanTopics);
|
||||||
|
nh.param("max_scan_age", max_scan_age_, kDefaultMaxScanAge);
|
||||||
|
nh.param("backup_distance", params_.backup_distance, kDefaultBackupDistance);
|
||||||
|
nh.param("backup_speed", limits_.backup_speed, kDefaultBackupSpeed);
|
||||||
|
nh.param("rotate_speed", limits_.rotate_speed, kDefaultRotateSpeed);
|
||||||
|
nh.param("acc_lim_x", limits_.acc_lim_x, kDefaultAccLimX);
|
||||||
|
nh.param("acc_lim_theta", limits_.acc_lim_theta, kDefaultAccLimTheta);
|
||||||
|
nh.param("heading_step_deg", heading_step_deg, kDefaultHeadingStepDeg);
|
||||||
|
nh.param("motion_margin", params_.motion_margin, kDefaultMotionMargin);
|
||||||
|
nh.param("min_free_distance", params_.min_free_distance, kDefaultMinFreeDistance);
|
||||||
|
nh.param("max_probe_distance", params_.max_probe_distance, kDefaultMaxProbeDistance);
|
||||||
|
nh.param("max_tf_gap", max_tf_gap_, kDefaultMaxTfGap);
|
||||||
|
nh.param("view_loss_timeout", view_loss_timeout_, kDefaultViewLossTimeout);
|
||||||
|
nh.param("debug/decision", debug_decision_, true);
|
||||||
|
|
||||||
|
// Param sai thì từ chối configure (fail loud lúc boot), không âm thầm dùng default: behavior này
|
||||||
|
// lái robot sát vật cản.
|
||||||
|
const auto positive = [](double v) { return std::isfinite(v) && v > 0.0; };
|
||||||
|
const char* error = nullptr;
|
||||||
|
const auto require = [&error](bool ok, const char* message) {
|
||||||
|
if (!ok && error == nullptr)
|
||||||
|
{
|
||||||
|
error = message;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
require(!scan_topics_.empty(), "scan_topics is empty");
|
||||||
|
require(std::none_of(scan_topics_.begin(), scan_topics_.end(),
|
||||||
|
[](const std::string& topic) { return topic.empty(); }),
|
||||||
|
"scan_topics has an empty entry");
|
||||||
|
require(positive(max_scan_age_), "max_scan_age must be > 0 s");
|
||||||
|
require(positive(max_tf_gap_), "max_tf_gap must be > 0 s");
|
||||||
|
require(std::isfinite(view_loss_timeout_) && view_loss_timeout_ >= 0.0 &&
|
||||||
|
(timeout() <= 0.0 || view_loss_timeout_ < timeout()),
|
||||||
|
"view_loss_timeout must be in [0, timeout) s");
|
||||||
|
require(positive(params_.backup_distance), "backup_distance must be > 0 m");
|
||||||
|
require(positive(limits_.backup_speed) && limits_.backup_speed <= kMaxLinearSpeed,
|
||||||
|
"backup_speed must be in (0, 1.0] m/s");
|
||||||
|
require(positive(limits_.rotate_speed) && limits_.rotate_speed <= kMaxAngularSpeed,
|
||||||
|
"rotate_speed must be in (0, 2.0] rad/s");
|
||||||
|
require(positive(limits_.acc_lim_x), "acc_lim_x must be > 0 m/s^2");
|
||||||
|
require(positive(limits_.acc_lim_theta), "acc_lim_theta must be > 0 rad/s^2");
|
||||||
|
require(positive(heading_step_deg) && heading_step_deg <= 90.0,
|
||||||
|
"heading_step_deg must be in (0, 90]");
|
||||||
|
require(positive(params_.motion_margin), "motion_margin must be > 0 m");
|
||||||
|
require(positive(params_.min_free_distance), "min_free_distance must be > 0 m");
|
||||||
|
require(positive(params_.max_probe_distance), "max_probe_distance must be > 0 m");
|
||||||
|
require(params_.min_free_distance <= params_.max_probe_distance,
|
||||||
|
"min_free_distance must be <= max_probe_distance");
|
||||||
|
if (error != nullptr)
|
||||||
|
{
|
||||||
|
robot::log_error("[recovery_core] '%s': invalid evade parameters: %s.", name().c_str(), error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
params_.heading_step = heading_step_deg * evade::kPi / 180.0;
|
||||||
|
|
||||||
|
std::string topics;
|
||||||
|
for (const std::string& topic : scan_topics_)
|
||||||
|
{
|
||||||
|
topics += (topics.empty() ? "" : ",") + topic;
|
||||||
|
}
|
||||||
|
robot::log_info("[recovery_core] '%s': evade scans=[%s] max_scan_age=%.2f s max_tf_gap=%.2f s "
|
||||||
|
"view_loss_timeout=%.2f s backup=%.2f m @ "
|
||||||
|
"%.2f m/s rotate=%.2f rad/s acc=%.2f m/s^2 / %.2f rad/s^2 heading_step=%.1f deg "
|
||||||
|
"margin=%.2f m min_free=%.2f m max_probe=%.2f m timeout=%.1f s "
|
||||||
|
"debug/decision=%s",
|
||||||
|
name().c_str(), topics.c_str(), max_scan_age_, max_tf_gap_, view_loss_timeout_,
|
||||||
|
params_.backup_distance,
|
||||||
|
limits_.backup_speed, limits_.rotate_speed, limits_.acc_lim_x, limits_.acc_lim_theta, heading_step_deg,
|
||||||
|
params_.motion_margin, params_.min_free_distance, params_.max_probe_distance,
|
||||||
|
timeout(), debug_decision_ ? "on" : "off");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool onStart(const recovery_core::RecoveryGoal& /*goal*/) override
|
||||||
|
{
|
||||||
|
decision_ = evade::Decision();
|
||||||
|
|
||||||
|
const char* missing = ctx().local_costmap == nullptr ? "a local costmap"
|
||||||
|
: ctx().sensors == nullptr ? "a sensor store (RecoveryContext::sensors)"
|
||||||
|
: ctx().tf == nullptr ? "a TF buffer"
|
||||||
|
: nullptr;
|
||||||
|
if (missing != nullptr)
|
||||||
|
{
|
||||||
|
robot::log_error("[recovery_core] '%s': evade requires %s; refusing to start.",
|
||||||
|
name().c_str(), missing);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
robot_geometry_msgs::PoseStamped start_pose;
|
||||||
|
if (!ctx().pose->getRobotPose(start_pose))
|
||||||
|
{
|
||||||
|
robot::log_warning("[recovery_core] '%s': could not get a pose at start-up (TF stale?).",
|
||||||
|
name().c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
start_ = toPose2(start_pose);
|
||||||
|
if (!finitePose(start_))
|
||||||
|
{
|
||||||
|
robot::log_error("[recovery_core] '%s': robot pose is NaN/Inf; refusing to evade.",
|
||||||
|
name().c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!loadFootprint(start_pose.header.frame_id))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
pending_ = false;
|
||||||
|
view_guard_.reset();
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
std::string reason;
|
||||||
|
if (!collectObstacles(startTime(), start_, obstacles, reason))
|
||||||
|
{
|
||||||
|
// Scan trễ một nhịp / TF lệch chút: nhận việc, đứng yên chờ dữ liệu mới (quyết định ở onUpdate). Không di chuyển
|
||||||
|
// theo dữ liệu cũ. view_loss_timeout = 0 giữ hành vi cũ: từ chối ngay.
|
||||||
|
if (view_loss_timeout_ <= 0.0)
|
||||||
|
{
|
||||||
|
robot::log_warning("[recovery_core] '%s': cannot evade without a fresh view: %s.",
|
||||||
|
name().c_str(), reason.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
robot::log_warning("[recovery_core] '%s': no fresh view at start (%s); holding still up to %.2f s.",
|
||||||
|
name().c_str(), reason.c_str(), view_loss_timeout_);
|
||||||
|
view_guard_.update(false, startTime().toSec(), view_loss_timeout_);
|
||||||
|
pending_ = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return commit(start_, obstacles);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Chốt động tác từ @p from với @p obstacles và khởi động Executor. false = không động tác nào khả thi (đã log).
|
||||||
|
bool commit(const evade::Pose2& from, const std::vector<evade::Point2>& obstacles)
|
||||||
|
{
|
||||||
|
start_ = from;
|
||||||
|
decision_ = evade::decide(footprint_, start_, params_, obstacles);
|
||||||
|
executor_.start(footprint_, start_, decision_, params_, limits_);
|
||||||
|
|
||||||
|
const int headings =
|
||||||
|
static_cast<int>(std::floor(2.0 * evade::kPi / params_.heading_step + 1e-9));
|
||||||
|
switch (decision_.motion)
|
||||||
|
{
|
||||||
|
case evade::Motion::kNone:
|
||||||
|
// Lý do từ chối là lỗi vận hành cần thấy, không phải log đường đi bình thường: luôn in.
|
||||||
|
robot::log_warning("[recovery_core] '%s': no evade motion is feasible: back-up blocked at "
|
||||||
|
"s=%.2f m, 0 of %d headings reachable with free distance >= %.2f m "
|
||||||
|
"(%zu obstacle points).",
|
||||||
|
name().c_str(), decision_.backup_blocked_at, headings,
|
||||||
|
params_.min_free_distance, obstacles.size());
|
||||||
|
return false;
|
||||||
|
case evade::Motion::kBackUp:
|
||||||
|
if (debug_decision_)
|
||||||
|
{
|
||||||
|
robot::log_info("[recovery_core] [debug] '%s': evade -> back up %.2f m (rear clear, %zu "
|
||||||
|
"obstacle points).",
|
||||||
|
name().c_str(), params_.backup_distance, obstacles.size());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case evade::Motion::kRotate:
|
||||||
|
if (debug_decision_)
|
||||||
|
{
|
||||||
|
robot::log_info("[recovery_core] [debug] '%s': evade -> rotate %+.1f deg to heading "
|
||||||
|
"%.1f deg, free %.2f m (back-up blocked at s=%.2f m, %d/%d headings "
|
||||||
|
"feasible).",
|
||||||
|
name().c_str(), toDeg(decision_.rotation), toDeg(decision_.heading),
|
||||||
|
decision_.free_distance, decision_.backup_blocked_at,
|
||||||
|
decision_.feasible_headings, headings);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case evade::Motion::kAlreadyFacing:
|
||||||
|
if (debug_decision_)
|
||||||
|
{
|
||||||
|
robot::log_info("[recovery_core] [debug] '%s': evade -> already facing the free side "
|
||||||
|
"(free %.2f m, back-up blocked at s=%.2f m); no motion.",
|
||||||
|
name().c_str(), decision_.free_distance, decision_.backup_blocked_at);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
recovery_core::RecoveryResult onUpdate(const robot::Time& now, double dt) override
|
||||||
|
{
|
||||||
|
robot_geometry_msgs::PoseStamped pose;
|
||||||
|
if (!ctx().pose->getRobotPose(pose))
|
||||||
|
{
|
||||||
|
return stopResult(recovery_core::RecoveryStatus::kFailed)
|
||||||
|
.withMessage("robot pose lost (TF stale?) — stopping the evade");
|
||||||
|
}
|
||||||
|
const evade::Pose2 current = toPose2(pose);
|
||||||
|
|
||||||
|
if (pending_ && !finitePose(current))
|
||||||
|
{
|
||||||
|
return stopResult(recovery_core::RecoveryStatus::kFailed)
|
||||||
|
.withMessage("robot pose is NaN/Inf — stopping the evade");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kiểm lại mỗi tick với scan mới nhất; điểm trong footprint TẠI POSE HIỆN TẠI bị bỏ (cùng luật
|
||||||
|
// lúc start). Pose NaN thì không gom (cửa sổ costmap sẽ vô nghĩa) — Executor tự dừng.
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
std::string reason;
|
||||||
|
if ((pending_ || decision_.motion != evade::Motion::kAlreadyFacing) && finitePose(current))
|
||||||
|
{
|
||||||
|
const bool seeing = collectObstacles(now, current, obstacles, reason);
|
||||||
|
const bool was_lost = view_guard_.lost();
|
||||||
|
switch (view_guard_.update(seeing, now.toSec(), view_loss_timeout_))
|
||||||
|
{
|
||||||
|
case evade::ViewGuard::State::kExpired:
|
||||||
|
return stopResult(recovery_core::RecoveryStatus::kFailed)
|
||||||
|
.withMessage("lost the obstacle view (" + reason + ") — stopping the evade");
|
||||||
|
case evade::ViewGuard::State::kHolding:
|
||||||
|
if (!was_lost)
|
||||||
|
{
|
||||||
|
robot::log_warning("[recovery_core] '%s': obstacle view lost (%s); holding still up to %.2f s.",
|
||||||
|
name().c_str(), reason.c_str(), view_loss_timeout_);
|
||||||
|
}
|
||||||
|
executor_.hold();
|
||||||
|
return recovery_core::RecoveryResult::Velocity(robot_geometry_msgs::Twist(),
|
||||||
|
recovery_core::RecoveryStatus::kRunning)
|
||||||
|
.withMessage("waiting for a fresh obstacle view (" + reason + ")");
|
||||||
|
case evade::ViewGuard::State::kSeeing:
|
||||||
|
if (was_lost && debug_decision_)
|
||||||
|
{
|
||||||
|
robot::log_info("[recovery_core] [debug] '%s': obstacle view is back; evade continues.", name().c_str());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pending_)
|
||||||
|
{
|
||||||
|
pending_ = false;
|
||||||
|
if (!commit(current, obstacles))
|
||||||
|
{
|
||||||
|
return stopResult(recovery_core::RecoveryStatus::kFailed).withMessage("no evade motion is feasible");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const evade::Tick tick = executor_.tick(current, obstacles, dt);
|
||||||
|
if (tick.status == evade::TickStatus::kSucceeded)
|
||||||
|
{
|
||||||
|
return stopResult(recovery_core::RecoveryStatus::kSucceeded)
|
||||||
|
.withProgress(1.0, 0.0)
|
||||||
|
.withMessage(tick.message);
|
||||||
|
}
|
||||||
|
if (tick.status == evade::TickStatus::kFailed)
|
||||||
|
{
|
||||||
|
return stopResult(recovery_core::RecoveryStatus::kFailed).withMessage(tick.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
robot_geometry_msgs::Twist command;
|
||||||
|
command.linear.x = tick.vx; // [m/s], âm = lùi
|
||||||
|
command.angular.z = tick.wz; // [rad/s], + = ngược chiều kim đồng hồ
|
||||||
|
return recovery_core::RecoveryResult::Velocity(command, recovery_core::RecoveryStatus::kRunning)
|
||||||
|
.withProgress(tick.progress, tick.remaining)
|
||||||
|
.withMessage(tick.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
recovery_core::RecoveryResult onCancel() override
|
||||||
|
{
|
||||||
|
return stopResult(recovery_core::RecoveryStatus::kCancelled).withMessage("evade cancelled");
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
/// Chụp footprint không padding lúc start (dữ liệu, không giữ con trỏ costmap qua các tick).
|
||||||
|
bool loadFootprint(const std::string& pose_frame)
|
||||||
|
{
|
||||||
|
const robot_costmap_2d::Costmap2DROBOT* costmap = ctx().local_costmap;
|
||||||
|
if (!pose_frame.empty() && pose_frame != costmap->getGlobalFrameID())
|
||||||
|
{
|
||||||
|
robot::log_error("[recovery_core] '%s': robot pose is in '%s' but the local costmap is in "
|
||||||
|
"'%s'; refusing to evade.",
|
||||||
|
name().c_str(), pose_frame.c_str(), costmap->getGlobalFrameID().c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
footprint_.clear();
|
||||||
|
for (const robot_geometry_msgs::Point& p : costmap->getUnpaddedRobotFootprint())
|
||||||
|
{
|
||||||
|
if (!std::isfinite(p.x) || !std::isfinite(p.y))
|
||||||
|
{
|
||||||
|
robot::log_error("[recovery_core] '%s': footprint has a NaN/Inf vertex; refusing to evade.",
|
||||||
|
name().c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
footprint_.push_back({p.x, p.y});
|
||||||
|
}
|
||||||
|
if (footprint_.size() < 3)
|
||||||
|
{
|
||||||
|
robot::log_error("[recovery_core] '%s': unpadded footprint has %zu vertices (need >= 3); "
|
||||||
|
"refusing to evade.",
|
||||||
|
name().c_str(), footprint_.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
r_max_ = evade::circumradius(footprint_);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [m] chỉ vật cản trong bán kính này mới ảnh hưởng tới lùi, cung xoay và d(ψ).
|
||||||
|
double collectRadius() const
|
||||||
|
{
|
||||||
|
return r_max_ + params_.max_probe_distance + params_.motion_margin;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Gom vật cản quanh @p around (frame global của local costmap): điểm lidar của mọi topic
|
||||||
|
* trong `scan_topics` + tâm ô LETHAL. Điểm trong footprint tại @p around bị bỏ.
|
||||||
|
* @return false (kèm @p reason) khi thiếu scan, scan quá tuổi so với @p now, hoặc thiếu TF.
|
||||||
|
*/
|
||||||
|
bool collectObstacles(const robot::Time& now, const evade::Pose2& around,
|
||||||
|
std::vector<evade::Point2>& out, std::string& reason) const
|
||||||
|
{
|
||||||
|
robot_costmap_2d::Costmap2DROBOT* costmap = ctx().local_costmap;
|
||||||
|
if (costmap == nullptr || ctx().sensors == nullptr || ctx().tf == nullptr)
|
||||||
|
{
|
||||||
|
reason = "local costmap, sensor store or TF buffer is gone";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const std::string& frame = costmap->getGlobalFrameID();
|
||||||
|
const double radius = collectRadius();
|
||||||
|
std::vector<evade::Point2> points;
|
||||||
|
|
||||||
|
for (const std::string& topic : scan_topics_)
|
||||||
|
{
|
||||||
|
uint64_t since = 0; // luôn lấy scan mới nhất; tuổi kiểm bằng stamp bên dưới
|
||||||
|
const auto scan =
|
||||||
|
robot_sensor_ports::latest<robot_sensor_msgs::LaserScan>(*ctx().sensors, topic, since);
|
||||||
|
if (!scan)
|
||||||
|
{
|
||||||
|
reason = "no LaserScan on " + topic;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const robot::Time stamp = scan->header.stamp;
|
||||||
|
const double age = (now - stamp).toSec();
|
||||||
|
if (!std::isfinite(age) || std::abs(age) > max_scan_age_)
|
||||||
|
{
|
||||||
|
reason = topic + " is stale (age " + std::to_string(age) + " s, max_scan_age " +
|
||||||
|
std::to_string(max_scan_age_) + " s)";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
tf3::TransformStampedMsg transform;
|
||||||
|
if (!lookup(frame, scan->header.frame_id, stamp, transform, reason))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const tf3::QuaternionMsg& q = transform.transform.rotation;
|
||||||
|
const tf3::Vector3Msg& t = transform.transform.translation;
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < scan->ranges.size(); ++i)
|
||||||
|
{
|
||||||
|
const double r = scan->ranges[i];
|
||||||
|
if (!std::isfinite(r) || r < scan->range_min || r > scan->range_max)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const double angle = scan->angle_min + static_cast<double>(i) * scan->angle_increment;
|
||||||
|
double x = 0.0;
|
||||||
|
double y = 0.0;
|
||||||
|
rotateXY(q, r * std::cos(angle), r * std::sin(angle), x, y);
|
||||||
|
points.push_back({x + t.x, y + t.y});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
robot_costmap_2d::Costmap2D* grid = costmap->getCostmap();
|
||||||
|
if (grid == nullptr)
|
||||||
|
{
|
||||||
|
reason = "local costmap has no grid";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard<robot_costmap_2d::Costmap2D::mutex_t> lock(*grid->getMutex());
|
||||||
|
int x0 = 0;
|
||||||
|
int y0 = 0;
|
||||||
|
int x1 = 0;
|
||||||
|
int y1 = 0;
|
||||||
|
grid->worldToMapEnforceBounds(around.x - radius, around.y - radius, x0, y0);
|
||||||
|
grid->worldToMapEnforceBounds(around.x + radius, around.y + radius, x1, y1);
|
||||||
|
for (int my = y0; my <= y1; ++my)
|
||||||
|
{
|
||||||
|
for (int mx = x0; mx <= x1; ++mx)
|
||||||
|
{
|
||||||
|
// Chỉ LETHAL: ô 253 (inscribed) là vùng thổi phồng, không phải vật — tính nó vào thì khe
|
||||||
|
// hở 3 cm thành "chắn". Unknown cũng không phải vật.
|
||||||
|
if (grid->getCost(mx, my) != robot_costmap_2d::LETHAL_OBSTACLE)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
double wx = 0.0;
|
||||||
|
double wy = 0.0;
|
||||||
|
grid->mapToWorld(mx, my, wx, wy);
|
||||||
|
points.push_back({wx, wy});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out = evade::keepOutsideFootprint(footprint_, around, radius, points);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// TF @p target <- @p source tại stamp scan; chưa có thì TF mới nhất nếu cách stamp <= max_tf_gap.
|
||||||
|
bool lookup(const std::string& target, const std::string& source, const robot::Time& stamp,
|
||||||
|
tf3::TransformStampedMsg& out, std::string& reason) const
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
out = ctx().tf->lookupTransform(target, source, tf3::Time(stamp.sec, stamp.nsec));
|
||||||
|
}
|
||||||
|
catch (const std::exception&)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
out = ctx().tf->lookupTransform(target, source, tf3::Time());
|
||||||
|
}
|
||||||
|
catch (const std::exception& e)
|
||||||
|
{
|
||||||
|
reason = "no TF " + target + " <- " + source + " (" + e.what() + ")";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const double gap = std::abs(out.header.stamp.toSec() - stamp.toSec());
|
||||||
|
if (!std::isfinite(gap) || gap > max_tf_gap_)
|
||||||
|
{
|
||||||
|
reason = "TF " + target + " <- " + source + " is " + std::to_string(gap) +
|
||||||
|
" s away from the scan stamp";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const tf3::QuaternionMsg& q = out.transform.rotation;
|
||||||
|
const double norm = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
|
||||||
|
if (!std::isfinite(norm) || std::abs(norm - 1.0) > 0.01 ||
|
||||||
|
!std::isfinite(out.transform.translation.x) || !std::isfinite(out.transform.translation.y))
|
||||||
|
{
|
||||||
|
reason = "invalid TF " + target + " <- " + source;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config
|
||||||
|
std::vector<std::string> scan_topics_ = kDefaultScanTopics;
|
||||||
|
double max_scan_age_ = kDefaultMaxScanAge; ///< [s]
|
||||||
|
double max_tf_gap_ = kDefaultMaxTfGap; ///< [s]
|
||||||
|
double view_loss_timeout_ = kDefaultViewLossTimeout; ///< [s] 0 = bỏ cuộc ngay khi mất dữ liệu
|
||||||
|
evade::Params params_;
|
||||||
|
evade::MotionLimits limits_{kDefaultBackupSpeed, kDefaultRotateSpeed, kDefaultAccLimX,
|
||||||
|
kDefaultAccLimTheta};
|
||||||
|
bool debug_decision_ = true;
|
||||||
|
|
||||||
|
// Trạng thái lượt hiện tại
|
||||||
|
evade::Polygon footprint_; ///< frame base, không padding
|
||||||
|
double r_max_ = 0.0; ///< [m]
|
||||||
|
evade::Pose2 start_;
|
||||||
|
evade::Decision decision_;
|
||||||
|
evade::Executor executor_;
|
||||||
|
evade::ViewGuard view_guard_;
|
||||||
|
bool pending_ = false; ///< nhận việc nhưng chưa có dữ liệu mới để chốt động tác
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace recovery_plugins
|
||||||
|
|
||||||
|
RECOVERY_CORE_EXPORT_BEHAVIOR(recovery_plugins::EvadeRecovery::create, EvadeRecovery)
|
||||||
@@ -60,6 +60,35 @@ recovery_partial:
|
|||||||
wait:
|
wait:
|
||||||
wait_duration: 1.0 # [s]
|
wait_duration: 1.0 # [s]
|
||||||
|
|
||||||
|
# EvadeRecovery: nạp qua library_path + ABI. Fake của nav_test_harness không có local costmap,
|
||||||
|
# sensor store hay TF, nên test chỉ kiểm configure + từ chối start; lõi hình học test riêng.
|
||||||
|
recovery_evade:
|
||||||
|
behaviors:
|
||||||
|
- {name: evade, type: EvadeRecovery}
|
||||||
|
evade:
|
||||||
|
scan_topics: [/f_scan, /b_scan]
|
||||||
|
max_scan_age: 0.3 # [s]
|
||||||
|
backup_distance: 0.20 # [m]
|
||||||
|
backup_speed: 0.15 # [m/s] độ lớn
|
||||||
|
rotate_speed: 0.5 # [rad/s] độ lớn
|
||||||
|
acc_lim_x: 0.3 # [m/s^2]
|
||||||
|
acc_lim_theta: 0.8 # [rad/s^2]
|
||||||
|
heading_step_deg: 10.0 # [deg]
|
||||||
|
motion_margin: 0.05 # [m]
|
||||||
|
min_free_distance: 0.30 # [m]
|
||||||
|
max_probe_distance: 1.0 # [m]
|
||||||
|
timeout: 15.0 # [s]
|
||||||
|
debug:
|
||||||
|
decision: true
|
||||||
|
|
||||||
|
# Đường lỗi: min_free_distance > max_probe_distance -> configure phải từ chối, không dùng default.
|
||||||
|
recovery_evade_bad:
|
||||||
|
behaviors:
|
||||||
|
- {name: evade, type: EvadeRecovery}
|
||||||
|
evade:
|
||||||
|
min_free_distance: 1.5 # [m]
|
||||||
|
max_probe_distance: 1.0 # [m]
|
||||||
|
|
||||||
# Bảng symbol -> thư viện cho Boost.DLL. Thiếu khoá library_path là nguyên nhân phổ biến nhất của
|
# Bảng symbol -> thư viện cho Boost.DLL. Thiếu khoá library_path là nguyên nhân phổ biến nhất của
|
||||||
# lỗi "plugin build xong nhưng runtime báo không tìm thấy".
|
# lỗi "plugin build xong nhưng runtime báo không tìm thấy".
|
||||||
WaitRecovery:
|
WaitRecovery:
|
||||||
@@ -75,6 +104,9 @@ RotateRecovery:
|
|||||||
BackUpRecovery:
|
BackUpRecovery:
|
||||||
library_path: librecovery_core_back_up_recovery
|
library_path: librecovery_core_back_up_recovery
|
||||||
|
|
||||||
|
EvadeRecovery:
|
||||||
|
library_path: librecovery_core_evade_recovery
|
||||||
|
|
||||||
ClearCostmapRecovery:
|
ClearCostmapRecovery:
|
||||||
library_path: librecovery_core_clear_costmap_recovery
|
library_path: librecovery_core_clear_costmap_recovery
|
||||||
|
|
||||||
|
|||||||
444
test/evade_recovery_test.cpp
Normal file
444
test/evade_recovery_test.cpp
Normal file
@@ -0,0 +1,444 @@
|
|||||||
|
/*********************************************************************
|
||||||
|
*
|
||||||
|
* Kiểm EvadeRecovery: lõi hình học (chọn lùi / xoay / không làm gì), Executor (lệnh vận tốc, ramp,
|
||||||
|
* dừng khi bị chắn giữa chừng, pose NaN), và đường nạp plugin qua library_path + ABI.
|
||||||
|
*
|
||||||
|
* Phần adapter đọc scan/TF/ô LETHAL cần `Costmap2DROBOT` thật nên không test ở đây (chưa test nào
|
||||||
|
* trong workspace dựng được nó); phần đó kiểm bằng sim.
|
||||||
|
*
|
||||||
|
* Footprint mặc định = robot KIT 1.022 x 0.392 m, base ở tâm: r_max = 0.547 m.
|
||||||
|
*
|
||||||
|
* Author: DuongTD
|
||||||
|
*********************************************************************/
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include <robot/node_handle.h>
|
||||||
|
|
||||||
|
#include <recovery_core/recovery_registry.h>
|
||||||
|
|
||||||
|
#include "../plugins/evade_core.h"
|
||||||
|
#include "recovery_test_utils.h"
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
namespace evade = recovery_plugins::evade;
|
||||||
|
|
||||||
|
constexpr double kDeg = evade::kPi / 180.0;
|
||||||
|
|
||||||
|
evade::Polygon rectangle(double x_min, double x_max, double half_width)
|
||||||
|
{
|
||||||
|
return {{x_max, half_width}, {x_min, half_width}, {x_min, -half_width}, {x_max, -half_width}};
|
||||||
|
}
|
||||||
|
|
||||||
|
evade::Polygon kitFootprint()
|
||||||
|
{
|
||||||
|
return rectangle(-0.511, 0.511, 0.196);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Điểm dày đặc (bước 0.02 m) trên đoạn a-b, như một bức tường quét bằng lidar.
|
||||||
|
void addWall(std::vector<evade::Point2>& out, evade::Point2 a, evade::Point2 b)
|
||||||
|
{
|
||||||
|
const double length = std::hypot(b.x - a.x, b.y - a.y);
|
||||||
|
const int n = std::max(1, static_cast<int>(std::ceil(length / 0.02)));
|
||||||
|
for (int i = 0; i <= n; ++i)
|
||||||
|
{
|
||||||
|
const double t = static_cast<double>(i) / n;
|
||||||
|
out.push_back({a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
evade::Params defaultParams()
|
||||||
|
{
|
||||||
|
return evade::Params(); // 0.20 m, margin 0.05 m, min_free 0.30 m, probe 1.0 m, step 10 deg
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Lùi
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
TEST(EvadeDecide, BacksUpWhenTheRearIsClear)
|
||||||
|
{
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
addWall(obstacles, {0.55, -1.0}, {0.55, 1.0}); // vật sát mũi, phía sau trống
|
||||||
|
|
||||||
|
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
|
||||||
|
|
||||||
|
EXPECT_EQ(d.motion, evade::Motion::kBackUp);
|
||||||
|
EXPECT_LT(d.backup_blocked_at, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeDecide, ObstacleWithinBackUpReachSwitchesToRotation)
|
||||||
|
{
|
||||||
|
// Đuôi ở x = -0.511; tường ở -0.60 nằm trong 0.20 + 0.05 m phía sau nhưng ngoài r_max (0.547 m)
|
||||||
|
// nên không chắn cung xoay. Mũi cũng bị chắn để hướng hiện tại không thắng.
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
addWall(obstacles, {-0.60, -2.0}, {-0.60, 2.0});
|
||||||
|
addWall(obstacles, {0.60, -2.0}, {0.60, 2.0});
|
||||||
|
|
||||||
|
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
|
||||||
|
|
||||||
|
EXPECT_GE(d.backup_blocked_at, 0.0);
|
||||||
|
EXPECT_LE(d.backup_blocked_at, 0.25);
|
||||||
|
EXPECT_EQ(d.motion, evade::Motion::kRotate);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeDecide, ThreeCentimetreSideGapStillBacksUp)
|
||||||
|
{
|
||||||
|
// Hai tường song song cách hông 0.03 m: CostmapCollisionChecker (253 = chắn) sẽ từ chối ngay tại
|
||||||
|
// chỗ. Ở đây footprint thật, không nở ngang, nên vẫn lùi được.
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
addWall(obstacles, {-2.0, 0.226}, {2.0, 0.226});
|
||||||
|
addWall(obstacles, {-2.0, -0.226}, {2.0, -0.226});
|
||||||
|
addWall(obstacles, {0.55, -0.226}, {0.55, 0.226});
|
||||||
|
|
||||||
|
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
|
||||||
|
|
||||||
|
EXPECT_EQ(d.motion, evade::Motion::kBackUp);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeDecide, PointsInsideTheStartFootprintAreIgnored)
|
||||||
|
{
|
||||||
|
const evade::Polygon footprint = kitFootprint();
|
||||||
|
const evade::Pose2 start{0.0, 0.0, 0.0};
|
||||||
|
const std::vector<evade::Point2> raw{{0.0, 0.0}, {0.4, 0.1}, {-0.5, -0.15}, {0.6, 0.0}};
|
||||||
|
|
||||||
|
// Không lọc thì điểm phản xạ từ chính thân robot chắn ngay mẫu s = 0.
|
||||||
|
EXPECT_DOUBLE_EQ(evade::backupBlockedAt(footprint, evade::circumradius(footprint), start, 0.25, raw),
|
||||||
|
0.0);
|
||||||
|
|
||||||
|
const std::vector<evade::Point2> kept = evade::keepOutsideFootprint(footprint, start, 5.0, raw);
|
||||||
|
ASSERT_EQ(kept.size(), 1u);
|
||||||
|
EXPECT_DOUBLE_EQ(kept[0].x, 0.6);
|
||||||
|
EXPECT_EQ(evade::decide(footprint, start, defaultParams(), kept).motion, evade::Motion::kBackUp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Xoay
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
TEST(EvadeDecide, RotatesTowardTheWiderSide)
|
||||||
|
{
|
||||||
|
// Trước/sau chắn sát. Bên trái (+y) tường cách mũi ~0.4 m, bên phải (-y) trống > 1 m. Phía rộng
|
||||||
|
// cố ý đặt bên -y: khi hoà, thứ tự quét đi +y trước, nên đáp án âm chứng tỏ d thật sự được so.
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
addWall(obstacles, {-0.60, -2.0}, {-0.60, 2.0});
|
||||||
|
addWall(obstacles, {0.60, -2.0}, {0.60, 2.0});
|
||||||
|
addWall(obstacles, {-2.0, 0.911}, {2.0, 0.911});
|
||||||
|
|
||||||
|
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
|
||||||
|
|
||||||
|
ASSERT_EQ(d.motion, evade::Motion::kRotate);
|
||||||
|
EXPECT_LT(d.rotation, -60.0 * kDeg) << "must turn toward -y (the 1 m side)";
|
||||||
|
EXPECT_GT(d.rotation, -100.0 * kDeg);
|
||||||
|
EXPECT_GE(d.free_distance, 0.95);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeDecide, TiedHeadingsPickTheSmallestRotation)
|
||||||
|
{
|
||||||
|
// Đối xứng: 80, 90, 100 deg (và đối xứng âm) đều có d = 1.0 m (trần). 70 deg chỉ ~0.7 m.
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
addWall(obstacles, {-0.60, -2.0}, {-0.60, 2.0});
|
||||||
|
addWall(obstacles, {0.60, -2.0}, {0.60, 2.0});
|
||||||
|
|
||||||
|
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
|
||||||
|
|
||||||
|
ASSERT_EQ(d.motion, evade::Motion::kRotate);
|
||||||
|
EXPECT_NEAR(std::abs(d.rotation), 80.0 * kDeg, 1e-6);
|
||||||
|
EXPECT_DOUBLE_EQ(d.free_distance, 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeDecide, BlockedShortArcFallsBackToTheLongWay)
|
||||||
|
{
|
||||||
|
// Footprint lệch tâm (base ở mũi, đuôi dài 0.8 m) — với thân đối xứng, cung dài (>= pi) luôn phủ
|
||||||
|
// cung ngắn nên ca này không tồn tại. Vật B ở hướng 225 deg, r = 0.7 m: đuôi quét qua nó khi xoay
|
||||||
|
// CCW 0 -> 90 deg, nhưng không khi xoay CW 0 -> -270 deg.
|
||||||
|
const evade::Polygon footprint = rectangle(-0.8, 0.2, 0.2);
|
||||||
|
evade::Params params = defaultParams();
|
||||||
|
params.heading_step = 90.0 * kDeg;
|
||||||
|
params.min_free_distance = 0.8;
|
||||||
|
|
||||||
|
const std::vector<evade::Point2> obstacles{
|
||||||
|
{0.91, 0.0}, // mũi: d(0) = 0.70 < 0.8, ngoài r_max (0.825)
|
||||||
|
{-0.90, 0.0}, // sau đuôi: chắn lùi, ngoài r_max; d(180) = 0.70
|
||||||
|
{0.0, -0.92}, // phía -y: d(-90) = 0.70, ngoài r_max
|
||||||
|
{-0.495, -0.495}, // B
|
||||||
|
};
|
||||||
|
|
||||||
|
const evade::Decision d = evade::decide(footprint, {0.0, 0.0, 0.0}, params, obstacles);
|
||||||
|
|
||||||
|
ASSERT_EQ(d.motion, evade::Motion::kRotate);
|
||||||
|
EXPECT_NEAR(d.rotation, -270.0 * kDeg, 1e-6);
|
||||||
|
EXPECT_NEAR(d.heading, 90.0 * kDeg, 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeDecide, AlreadyFacingTheFreeSideNeedsNoMotion)
|
||||||
|
{
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
addWall(obstacles, {-0.60, -2.0}, {-0.60, 2.0}); // chỉ phía sau bị chắn
|
||||||
|
|
||||||
|
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
|
||||||
|
ASSERT_EQ(d.motion, evade::Motion::kAlreadyFacing);
|
||||||
|
|
||||||
|
evade::Executor executor;
|
||||||
|
executor.start(kitFootprint(), {0.0, 0.0, 0.0}, d, defaultParams(), evade::MotionLimits());
|
||||||
|
const evade::Tick tick = executor.tick({0.0, 0.0, 0.0}, obstacles, 0.05);
|
||||||
|
EXPECT_EQ(tick.status, evade::TickStatus::kSucceeded);
|
||||||
|
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
|
||||||
|
EXPECT_DOUBLE_EQ(tick.wz, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Thất bại
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
TEST(EvadeDecide, NothingFeasibleIsReported)
|
||||||
|
{
|
||||||
|
// Hộp kín, mọi tường cách tâm 0.60 m: xoay được (r_max 0.547) nhưng không hướng nào đạt 0.30 m.
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
addWall(obstacles, {-0.60, -0.60}, {-0.60, 0.60});
|
||||||
|
addWall(obstacles, {0.60, -0.60}, {0.60, 0.60});
|
||||||
|
addWall(obstacles, {-0.60, 0.60}, {0.60, 0.60});
|
||||||
|
addWall(obstacles, {-0.60, -0.60}, {0.60, -0.60});
|
||||||
|
|
||||||
|
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
|
||||||
|
|
||||||
|
EXPECT_EQ(d.motion, evade::Motion::kNone);
|
||||||
|
EXPECT_EQ(d.feasible_headings, 0);
|
||||||
|
EXPECT_GE(d.backup_blocked_at, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Executor: lệnh vận tốc
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
struct Sim
|
||||||
|
{
|
||||||
|
evade::Pose2 pose{1.0, 2.0, 0.3}; // không ở gốc, có yaw: bắt lỗi quên đổi frame
|
||||||
|
void apply(const evade::Tick& tick, double dt)
|
||||||
|
{
|
||||||
|
pose.x += tick.vx * std::cos(pose.yaw) * dt;
|
||||||
|
pose.y += tick.vx * std::sin(pose.yaw) * dt;
|
||||||
|
pose.yaw += tick.wz * dt;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
TEST(EvadeExecutor, BackUpCommandsStayWithinLimitsAndStopAtTheDistance)
|
||||||
|
{
|
||||||
|
Sim sim;
|
||||||
|
const evade::Pose2 start = sim.pose;
|
||||||
|
evade::Decision decision;
|
||||||
|
decision.motion = evade::Motion::kBackUp;
|
||||||
|
const evade::MotionLimits limits; // 0.15 m/s, 0.3 m/s^2
|
||||||
|
evade::Executor executor;
|
||||||
|
executor.start(kitFootprint(), start, decision, defaultParams(), limits);
|
||||||
|
|
||||||
|
const double dt = 0.05;
|
||||||
|
double previous_vx = 0.0;
|
||||||
|
evade::Tick tick;
|
||||||
|
int ticks = 0;
|
||||||
|
for (; ticks < 200; ++ticks)
|
||||||
|
{
|
||||||
|
tick = executor.tick(sim.pose, {}, dt);
|
||||||
|
if (tick.status != evade::TickStatus::kRunning)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
EXPECT_LE(tick.vx, 0.0);
|
||||||
|
EXPECT_DOUBLE_EQ(tick.wz, 0.0);
|
||||||
|
EXPECT_LE(std::abs(tick.vx), limits.backup_speed + 1e-9);
|
||||||
|
EXPECT_LE(std::abs(tick.vx - previous_vx), limits.acc_lim_x * dt + 1e-9);
|
||||||
|
previous_vx = tick.vx;
|
||||||
|
sim.apply(tick, dt);
|
||||||
|
}
|
||||||
|
|
||||||
|
ASSERT_EQ(tick.status, evade::TickStatus::kSucceeded);
|
||||||
|
const double traveled = -((sim.pose.x - start.x) * std::cos(start.yaw) +
|
||||||
|
(sim.pose.y - start.y) * std::sin(start.yaw));
|
||||||
|
EXPECT_NEAR(traveled, 0.20, evade::kBackupTolerance + 1e-6);
|
||||||
|
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeExecutor, RotationCommandsHaveNoLinearPartAndStopAtTheAngle)
|
||||||
|
{
|
||||||
|
Sim sim;
|
||||||
|
evade::Decision decision;
|
||||||
|
decision.motion = evade::Motion::kRotate;
|
||||||
|
decision.rotation = -100.0 * kDeg; // CW: dấu lệnh phải âm
|
||||||
|
const evade::MotionLimits limits; // 0.5 rad/s, 0.8 rad/s^2
|
||||||
|
evade::Executor executor;
|
||||||
|
executor.start(kitFootprint(), sim.pose, decision, defaultParams(), limits);
|
||||||
|
|
||||||
|
const double start_yaw = sim.pose.yaw;
|
||||||
|
const double dt = 0.05;
|
||||||
|
double previous_wz = 0.0;
|
||||||
|
evade::Tick tick;
|
||||||
|
for (int i = 0; i < 400; ++i)
|
||||||
|
{
|
||||||
|
tick = executor.tick(sim.pose, {}, dt);
|
||||||
|
if (tick.status != evade::TickStatus::kRunning)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
|
||||||
|
EXPECT_LE(tick.wz, 0.0);
|
||||||
|
EXPECT_LE(std::abs(tick.wz), limits.rotate_speed + 1e-9);
|
||||||
|
EXPECT_LE(std::abs(tick.wz - previous_wz), limits.acc_lim_theta * dt + 1e-9);
|
||||||
|
previous_wz = tick.wz;
|
||||||
|
sim.apply(tick, dt);
|
||||||
|
}
|
||||||
|
|
||||||
|
ASSERT_EQ(tick.status, evade::TickStatus::kSucceeded);
|
||||||
|
EXPECT_NEAR(sim.pose.yaw - start_yaw, -100.0 * kDeg, evade::kRotateTolerance + 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeExecutor, FirstTickAtTheStartStampDoesNotJumpToFullSpeed)
|
||||||
|
{
|
||||||
|
evade::Decision decision;
|
||||||
|
decision.motion = evade::Motion::kBackUp;
|
||||||
|
evade::Executor executor;
|
||||||
|
executor.start(kitFootprint(), {0.0, 0.0, 0.0}, decision, defaultParams(), evade::MotionLimits());
|
||||||
|
|
||||||
|
const evade::Tick tick = executor.tick({0.0, 0.0, 0.0}, {}, 0.0);
|
||||||
|
EXPECT_EQ(tick.status, evade::TickStatus::kRunning);
|
||||||
|
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeExecutor, HoldRestartsTheRampFromZero)
|
||||||
|
{
|
||||||
|
// Sim 27/11: the plugin publishes 0 while the view is lost; resuming must ramp again, not jump to the old speed.
|
||||||
|
Sim sim;
|
||||||
|
sim.pose = {0.0, 0.0, 0.0};
|
||||||
|
evade::Decision decision;
|
||||||
|
decision.motion = evade::Motion::kBackUp;
|
||||||
|
const evade::MotionLimits limits;
|
||||||
|
evade::Executor executor;
|
||||||
|
executor.start(kitFootprint(), sim.pose, decision, defaultParams(), limits);
|
||||||
|
for (int i = 0; i < 10; ++i)
|
||||||
|
{
|
||||||
|
const evade::Tick tick = executor.tick(sim.pose, {}, 0.05);
|
||||||
|
ASSERT_EQ(tick.status, evade::TickStatus::kRunning);
|
||||||
|
sim.apply(tick, 0.05);
|
||||||
|
}
|
||||||
|
executor.hold();
|
||||||
|
const evade::Tick resumed = executor.tick(sim.pose, {}, 0.05);
|
||||||
|
EXPECT_EQ(resumed.status, evade::TickStatus::kRunning);
|
||||||
|
EXPECT_LE(std::abs(resumed.vx), limits.acc_lim_x * 0.05 + 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeViewGuard, HoldsUntilTheTimeoutThenExpires)
|
||||||
|
{
|
||||||
|
evade::ViewGuard guard;
|
||||||
|
EXPECT_EQ(guard.update(true, 10.0, 1.0), evade::ViewGuard::State::kSeeing);
|
||||||
|
EXPECT_EQ(guard.update(false, 10.1, 1.0), evade::ViewGuard::State::kHolding);
|
||||||
|
EXPECT_EQ(guard.update(false, 10.9, 1.0), evade::ViewGuard::State::kHolding);
|
||||||
|
EXPECT_EQ(guard.update(true, 11.0, 1.0), evade::ViewGuard::State::kSeeing) << "a fresh view ends the loss";
|
||||||
|
EXPECT_EQ(guard.update(false, 11.5, 1.0), evade::ViewGuard::State::kHolding) << "a new loss starts a new clock";
|
||||||
|
EXPECT_EQ(guard.update(false, 12.5, 1.0), evade::ViewGuard::State::kExpired);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeViewGuard, ZeroTimeoutFailsOnTheFirstLoss)
|
||||||
|
{
|
||||||
|
evade::ViewGuard guard;
|
||||||
|
EXPECT_EQ(guard.update(false, 10.0, 0.0), evade::ViewGuard::State::kExpired);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeExecutor, ObstacleAppearingMidRunStopsWithZeroCommand)
|
||||||
|
{
|
||||||
|
Sim sim;
|
||||||
|
sim.pose = {0.0, 0.0, 0.0};
|
||||||
|
evade::Decision decision;
|
||||||
|
decision.motion = evade::Motion::kBackUp;
|
||||||
|
evade::Executor executor;
|
||||||
|
executor.start(kitFootprint(), sim.pose, decision, defaultParams(), evade::MotionLimits());
|
||||||
|
|
||||||
|
for (int i = 0; i < 5; ++i)
|
||||||
|
{
|
||||||
|
const evade::Tick tick = executor.tick(sim.pose, {}, 0.05);
|
||||||
|
ASSERT_EQ(tick.status, evade::TickStatus::kRunning);
|
||||||
|
sim.apply(tick, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Có người bước vào ngay sau đuôi (trong phần lùi còn lại).
|
||||||
|
std::vector<evade::Point2> obstacles;
|
||||||
|
addWall(obstacles, {sim.pose.x - 0.60, -0.3}, {sim.pose.x - 0.60, 0.3});
|
||||||
|
const evade::Tick blocked = executor.tick(sim.pose, obstacles, 0.05);
|
||||||
|
|
||||||
|
EXPECT_EQ(blocked.status, evade::TickStatus::kFailed);
|
||||||
|
EXPECT_DOUBLE_EQ(blocked.vx, 0.0);
|
||||||
|
EXPECT_DOUBLE_EQ(blocked.wz, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadeExecutor, NanPoseStopsWithZeroCommand)
|
||||||
|
{
|
||||||
|
evade::Decision decision;
|
||||||
|
decision.motion = evade::Motion::kRotate;
|
||||||
|
decision.rotation = 90.0 * kDeg;
|
||||||
|
evade::Executor executor;
|
||||||
|
executor.start(kitFootprint(), {0.0, 0.0, 0.0}, decision, defaultParams(), evade::MotionLimits());
|
||||||
|
|
||||||
|
const evade::Tick tick = executor.tick({0.0, std::nan(""), 0.0}, {}, 0.05);
|
||||||
|
EXPECT_EQ(tick.status, evade::TickStatus::kFailed);
|
||||||
|
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
|
||||||
|
EXPECT_DOUBLE_EQ(tick.wz, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Plugin qua registry (library_path + ABI)
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
TEST(EvadePlugin, LoadsThroughLibraryPathWithTheCurrentAbi)
|
||||||
|
{
|
||||||
|
recovery_test::VelocityRig rig;
|
||||||
|
robot::NodeHandle nh;
|
||||||
|
recovery_core::RecoveryRegistry registry;
|
||||||
|
|
||||||
|
EXPECT_TRUE(registry.loadFromConfig(nh, "recovery_evade", rig.ctx));
|
||||||
|
EXPECT_NE(recovery_test::findBehavior(registry, "evade"), nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadePlugin, RefusesToStartWithoutCostmapSensorsOrTf)
|
||||||
|
{
|
||||||
|
recovery_test::VelocityRig rig; // có pose + collision, KHÔNG có local_costmap/sensors/tf
|
||||||
|
rig.pose.setPose(0.0, 0.0, 0.0);
|
||||||
|
robot::NodeHandle nh;
|
||||||
|
recovery_core::RecoveryRegistry registry;
|
||||||
|
ASSERT_TRUE(registry.loadFromConfig(nh, "recovery_evade", rig.ctx));
|
||||||
|
recovery_core::RecoveryBehavior* evade_behavior = recovery_test::findBehavior(registry, "evade");
|
||||||
|
ASSERT_NE(evade_behavior, nullptr);
|
||||||
|
|
||||||
|
EXPECT_FALSE(evade_behavior->start(recovery_core::RecoveryGoal(), robot::Time(1000.0)));
|
||||||
|
const auto result = evade_behavior->update(robot::Time(1000.1));
|
||||||
|
EXPECT_EQ(result.status, recovery_core::RecoveryStatus::kFailed);
|
||||||
|
ASSERT_NE(result.velocity(), nullptr);
|
||||||
|
EXPECT_DOUBLE_EQ(result.velocity()->linear.x, 0.0);
|
||||||
|
EXPECT_DOUBLE_EQ(result.velocity()->angular.z, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EvadePlugin, RejectsInvalidParameters)
|
||||||
|
{
|
||||||
|
recovery_test::VelocityRig rig;
|
||||||
|
robot::NodeHandle nh;
|
||||||
|
recovery_core::RecoveryRegistry registry;
|
||||||
|
|
||||||
|
EXPECT_FALSE(registry.loadFromConfig(nh, "recovery_evade_bad", rig.ctx));
|
||||||
|
EXPECT_EQ(recovery_test::findBehavior(registry, "evade"), nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main(int argc, char** argv)
|
||||||
|
{
|
||||||
|
#ifdef RECOVERY_CORE_TEST_CONFIG_DIR
|
||||||
|
setenv("PNKX_NAV_CORE_CONFIG_DIR", RECOVERY_CORE_TEST_CONFIG_DIR, 0);
|
||||||
|
#endif
|
||||||
|
#ifdef RECOVERY_CORE_TEST_LIBRARY_DIR
|
||||||
|
setenv("PNKX_NAV_CORE_LIBRARY_PATH", RECOVERY_CORE_TEST_LIBRARY_DIR, 0);
|
||||||
|
#endif
|
||||||
|
testing::InitGoogleTest(&argc, argv);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user