feat: env_monitor_core package with detector plugins
EnvMonitor moves out of move_base2 into its own package. stall, unreachable and contact become boost::dll detector plugins loaded from env_monitor/detectors, each with its own recovery route (route, route_mode step|sequence, on_exhausted lock|abort). Golden test replays the pre-split verdicts bit for bit.
This commit is contained in:
264
CMakeLists.txt
Normal file
264
CMakeLists.txt
Normal file
@@ -0,0 +1,264 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(env_monitor_core VERSION 0.1.0 LANGUAGES CXX)
|
||||
|
||||
# Hai chế độ build như recovery_core / action_core: catkin (T800_ws) và CMake standalone (pnkx_nav_core).
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building env_monitor_core with Catkin")
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building env_monitor_core with Standalone CMake")
|
||||
endif()
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Boost REQUIRED COMPONENTS
|
||||
system
|
||||
filesystem
|
||||
)
|
||||
find_package(yaml-cpp REQUIRED)
|
||||
|
||||
if(NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
set(PNKX_NAV_CORE_SRC_DIR
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../.."
|
||||
)
|
||||
|
||||
file(GLOB STANDALONE_PACKAGE_INCLUDE_DIRS
|
||||
LIST_DIRECTORIES true
|
||||
${PNKX_NAV_CORE_SRC_DIR}/*/include
|
||||
${PNKX_NAV_CORE_SRC_DIR}/*/*/include
|
||||
${PNKX_NAV_CORE_SRC_DIR}/*/*/*/include
|
||||
${PNKX_NAV_CORE_SRC_DIR}/*/*/*/*/include
|
||||
)
|
||||
|
||||
set(STANDALONE_INCLUDE_DIRS
|
||||
${STANDALONE_PACKAGE_INCLUDE_DIRS}
|
||||
/usr/local/include
|
||||
)
|
||||
|
||||
# Khi cấu hình từ gốc pnkx_nav_core, các tên này là CMake target và mang theo include dir của chúng.
|
||||
set(PACKAGES_DIR
|
||||
robot_time
|
||||
robot_cpp
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
robot_time
|
||||
robot_cpp
|
||||
)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS
|
||||
include
|
||||
# Chỉ lõi: detector nạp động bằng boost::dll, gói phụ thuộc không được link thẳng vào chúng.
|
||||
LIBRARIES
|
||||
env_monitor_core
|
||||
CATKIN_DEPENDS
|
||||
robot_time
|
||||
robot_cpp
|
||||
DEPENDS
|
||||
Boost
|
||||
)
|
||||
|
||||
include_directories(SYSTEM
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# Link chung cho lõi và plugin, theo chế độ build.
|
||||
function(env_monitor_core_wire target)
|
||||
target_compile_options(${target} PRIVATE -Wall -Wextra)
|
||||
target_include_directories(${target}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
set_target_properties(${target} PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${target}
|
||||
${${PROJECT_NAME}_EXPORTED_TARGETS}
|
||||
${catkin_EXPORTED_TARGETS}
|
||||
)
|
||||
target_link_libraries(${target}
|
||||
PUBLIC
|
||||
${catkin_LIBRARIES}
|
||||
PRIVATE
|
||||
Boost::boost
|
||||
Boost::system
|
||||
Boost::filesystem
|
||||
yaml-cpp
|
||||
${CMAKE_DL_LIBS}
|
||||
)
|
||||
else()
|
||||
target_include_directories(${target}
|
||||
PRIVATE
|
||||
${STANDALONE_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
)
|
||||
target_link_libraries(${target}
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
Boost::boost
|
||||
Boost::system
|
||||
Boost::filesystem
|
||||
yaml-cpp
|
||||
${CMAKE_DL_LIBS}
|
||||
)
|
||||
set_target_properties(${target} PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY
|
||||
${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH
|
||||
"${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# ========================================================
|
||||
# Lõi: host EnvMonitor (phần chung, nạp + gộp detector) và đọc/kiểm tham số. Không chứa detector nào.
|
||||
# ========================================================
|
||||
add_library(env_monitor_core SHARED
|
||||
src/env_monitor.cpp
|
||||
src/env_monitor_config.cpp
|
||||
)
|
||||
env_monitor_core_wire(env_monitor_core)
|
||||
|
||||
# ========================================================
|
||||
# Detector có sẵn — mỗi cái một .so, nạp bằng boost::dll theo `<Type>/library_path` trong YAML.
|
||||
# Detector của gói khác làm y như vậy: depend env_monitor_core, include env_monitor_core/env_detector.h.
|
||||
# ========================================================
|
||||
set(ENV_MONITOR_CORE_PLUGIN_TARGETS
|
||||
env_monitor_core_contact_detector
|
||||
env_monitor_core_stall_detector
|
||||
env_monitor_core_unreachable_detector
|
||||
)
|
||||
foreach(plugin contact stall unreachable)
|
||||
set(target env_monitor_core_${plugin}_detector)
|
||||
add_library(${target} SHARED plugins/${plugin}_detector.cpp)
|
||||
env_monitor_core_wire(${target})
|
||||
target_link_libraries(${target} PUBLIC env_monitor_core)
|
||||
endforeach()
|
||||
|
||||
# ========================================================
|
||||
# Install
|
||||
# ========================================================
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
|
||||
install(
|
||||
TARGETS
|
||||
env_monitor_core
|
||||
${ENV_MONITOR_CORE_PLUGIN_TARGETS}
|
||||
ARCHIVE DESTINATION
|
||||
${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION
|
||||
${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION
|
||||
${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
install(
|
||||
DIRECTORY
|
||||
include/${PROJECT_NAME}/
|
||||
DESTINATION
|
||||
${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING
|
||||
PATTERN "*.h"
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
install(
|
||||
TARGETS
|
||||
env_monitor_core
|
||||
${ENV_MONITOR_CORE_PLUGIN_TARGETS}
|
||||
EXPORT
|
||||
${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION
|
||||
lib
|
||||
LIBRARY DESTINATION
|
||||
lib
|
||||
RUNTIME DESTINATION
|
||||
bin
|
||||
)
|
||||
|
||||
install(
|
||||
EXPORT
|
||||
${PROJECT_NAME}-targets
|
||||
FILE
|
||||
${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE
|
||||
${PROJECT_NAME}::
|
||||
DESTINATION
|
||||
lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
install(
|
||||
DIRECTORY
|
||||
include/${PROJECT_NAME}/
|
||||
DESTINATION
|
||||
include/${PROJECT_NAME}
|
||||
FILES_MATCHING
|
||||
PATTERN "*.h"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Tests — OFF mặc định; bật bằng -DBUILD_ENV_MONITOR_CORE_TESTS=ON (chỉ nhánh catkin).
|
||||
# ========================================================
|
||||
option(BUILD_ENV_MONITOR_CORE_TESTS "Build env_monitor_core tests" OFF)
|
||||
|
||||
if(BUILD_ENV_MONITOR_CORE_TESTS AND BUILDING_WITH_CATKIN AND CATKIN_ENABLE_TESTING)
|
||||
|
||||
if(NOT COMMAND catkin_add_gtest)
|
||||
message(FATAL_ERROR "catkin_add_gtest NOT FOUND")
|
||||
endif()
|
||||
|
||||
# Plugin chỉ cho test: ABI lệch cố ý, để kiểm EnvMonitor từ chối nạp nó.
|
||||
add_library(env_monitor_core_test_stale_abi_detector SHARED test/plugins/stale_abi_detector.cpp)
|
||||
env_monitor_core_wire(env_monitor_core_test_stale_abi_detector)
|
||||
target_link_libraries(env_monitor_core_test_stale_abi_detector PUBLIC env_monitor_core)
|
||||
|
||||
set(ENV_MONITOR_CORE_TESTS
|
||||
env_monitor_test
|
||||
env_monitor_golden_test
|
||||
env_monitor_loading_test
|
||||
)
|
||||
|
||||
foreach(test_name ${ENV_MONITOR_CORE_TESTS})
|
||||
catkin_add_gtest(${test_name} test/${test_name}.cpp)
|
||||
|
||||
if(TARGET ${test_name})
|
||||
# catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make` thường.
|
||||
set_target_properties(${test_name} PROPERTIES EXCLUDE_FROM_ALL FALSE)
|
||||
target_compile_options(${test_name} PRIVATE -Wall -Wextra)
|
||||
target_include_directories(${test_name} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/test)
|
||||
target_link_libraries(${test_name}
|
||||
env_monitor_core
|
||||
${catkin_LIBRARIES}
|
||||
yaml-cpp
|
||||
)
|
||||
# Detector được nạp qua boost::dll từ devel/lib, đúng đường runtime đi: phải build xong trước khi test chạy.
|
||||
add_dependencies(${test_name} ${ENV_MONITOR_CORE_PLUGIN_TARGETS} env_monitor_core_test_stale_abi_detector)
|
||||
target_compile_definitions(${test_name} PRIVATE
|
||||
ENV_MONITOR_CORE_TEST_LIBRARY_DIR="${CATKIN_DEVEL_PREFIX}/lib"
|
||||
ENV_MONITOR_CORE_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/data"
|
||||
)
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
endif()
|
||||
91
README.md
Normal file
91
README.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# env_monitor_core
|
||||
|
||||
Lõi giám sát môi trường khi robot bám plan. Mỗi control cycle host đưa vào một `EnvSample` (feature hình học đã
|
||||
tính sẵn: `cost_to_go`, `reachable`, `edt_body_min`, khoảng tiếp xúc dọc quỹ đạo), lõi trả một `EnvVerdict`: bit
|
||||
"detector nào đòi recovery", lệnh phanh, bao tốc độ, và số chẩn đoán cho log/JSONL.
|
||||
|
||||
Lõi thuần: không costmap, không TF, không log trong cycle. Host (hiện là `move_base2`) gom feature, gọi lõi, nối kết
|
||||
quả vào state machine và trọng tài vận tốc.
|
||||
|
||||
## Cấu trúc
|
||||
|
||||
```
|
||||
include/env_monitor_core/
|
||||
├── env_types.h # EnvSample, EnvVerdict, EnvRecoveryOutcome — dữ liệu một cycle
|
||||
├── env_detector.h # interface EnvDetector + EnvNeeds, EnvShared, EnvFrame, EnvDetectorOutput, EnvRouteSpec
|
||||
├── env_detector_abi.h # kEnvDetectorAbiVersion + ENV_MONITOR_CORE_EXPORT_DETECTOR
|
||||
├── env_monitor_config.h # tham số (phần chung + ba detector có sẵn), đọc/kiểm/mô tả, toYaml
|
||||
└── env_monitor.h # host EnvMonitor: phần chung, nạp và gộp detector
|
||||
src/ # host + config
|
||||
plugins/ # ba detector có sẵn, mỗi cái một .so
|
||||
test/ # env_monitor_test (66), env_monitor_golden_test, env_monitor_loading_test
|
||||
```
|
||||
|
||||
## Host và detector
|
||||
|
||||
`EnvMonitor` giữ phần chung cho mọi detector: odometer, lọc pose nhảy, grace sau plan mới, ngân sách replan. Mỗi
|
||||
verdict là một `EnvDetector` nạp bằng boost::dll:
|
||||
|
||||
| Detector | Phát hiện | Route mặc định | Cạn route |
|
||||
|---|---|---|---|
|
||||
| `ContactDetector` | thân sắp chạm trên quỹ đạo thật; phanh, bao tốc độ | `collision` | `lock` |
|
||||
| `StallDetector` | lệnh đi mà robot không dịch chuyển / không tới gần lối ra | `oscillation` | `abort` |
|
||||
| `UnreachableDetector` | không còn đường trong cửa sổ tới điểm thoát | `path_blocked` | `lock` |
|
||||
|
||||
Mỗi cycle host gọi mọi detector theo thứ tự `env_monitor/detectors`, rồi gộp: bit `fired_mask` theo từng detector,
|
||||
`brake` OR, `v_cap` min, `event` của detector sau ghi đè detector trước. `brake_applied` / `v_cap_applied` chỉ lấy
|
||||
từ detector có `apply_command`. Detector không gọi port nào: host chỉ lấy feature mà ít nhất một detector cần
|
||||
(`needs()`), mỗi cycle một lần.
|
||||
|
||||
## YAML
|
||||
|
||||
```yaml
|
||||
env_monitor:
|
||||
enabled: true
|
||||
detectors: # thiếu khoá = contact, stall, unreachable theo đúng thứ tự này
|
||||
- {name: contact, type: ContactDetector}
|
||||
- {name: stall, type: StallDetector}
|
||||
- {name: unreachable, type: UnreachableDetector}
|
||||
contact: # tham số của detector tên `contact`
|
||||
action: recover
|
||||
route: collision # tên route trong recovery/routes
|
||||
route_mode: step # step | sequence
|
||||
on_exhausted: lock # lock | abort
|
||||
...
|
||||
ContactDetector:
|
||||
library_path: libenv_monitor_core_contact_detector
|
||||
```
|
||||
|
||||
- Type sai, thiếu `library_path`, thiếu hoặc lệch ABI: log LỖI, bỏ detector đó, các detector khác vẫn chạy.
|
||||
- Tham số sai (của phần chung hoặc của một detector): `initialize()` trả lỗi, host từ chối khởi động.
|
||||
- Host trỏ route không tồn tại: host gỡ detector (`remove()`), log LỖI.
|
||||
|
||||
Comment đầy đủ từng khoá (tiếng Việt) nằm trong `env_monitor_params.yaml` của cây config đang chạy.
|
||||
|
||||
## Viết detector mới trong gói khác
|
||||
|
||||
1. `package.xml`/`CMakeLists.txt`: depend `env_monitor_core`, build một `SHARED` library link `env_monitor_core`.
|
||||
2. Hiện thực `env_monitor_core::EnvDetector` (`initialize`, `describe`, `armed`, `defaultRoute`, `needs`, `reset`,
|
||||
`update`; tuỳ chọn `appliesCommand`, `onPlanApplied`, `onRecoveryFinished`). Ghi vào `EnvDetectorOutput` phần được
|
||||
gộp, và chỉ các trường chẩn đoán của chính mình vào `EnvVerdict`.
|
||||
3. Export: `ENV_MONITOR_CORE_EXPORT_DETECTOR(MyDetector::create, MyDetector)` — sinh `MyDetector` và `MyDetector_abi`.
|
||||
4. YAML: thêm `{name: ..., type: MyDetector}` vào `detectors`, khối tham số cùng `name`, `MyDetector/library_path`, và
|
||||
route tương ứng trong `recovery/routes`.
|
||||
|
||||
Đổi chữ ký virtual hoặc layout các struct trong `env_detector.h` / `env_types.h` thì phải tăng `kEnvDetectorAbiVersion`.
|
||||
|
||||
## Build và test
|
||||
|
||||
```bash
|
||||
cd /home/duongtd/T800_ws
|
||||
catkin_make --pkg env_monitor_core -DBUILD_ENV_MONITOR_CORE_TESTS=ON
|
||||
env -u PNKX_NAV_CORE_CONFIG_DIR -u PNKX_NAV_CORE_LIBRARY_PATH ./devel/lib/env_monitor_core/env_monitor_golden_test
|
||||
env -u PNKX_NAV_CORE_CONFIG_DIR -u PNKX_NAV_CORE_LIBRARY_PATH ./devel/lib/env_monitor_core/env_monitor_test
|
||||
env -u PNKX_NAV_CORE_CONFIG_DIR -u PNKX_NAV_CORE_LIBRARY_PATH ./devel/lib/env_monitor_core/env_monitor_loading_test
|
||||
```
|
||||
|
||||
`env_monitor_golden_test` so verdict từng cycle của 24 kịch bản với `test/data/env_monitor_golden.txt`, ghi ngày
|
||||
26/11/2026 từ bản EnvMonitor một khối cũ (trong `move_base2`). Lệch ở đây là đổi hành vi: sửa code, đừng ghi lại file
|
||||
(`ENV_MONITOR_CORE_GOLDEN_RECORD=1`) để test xanh.
|
||||
|
||||
Nhánh standalone của `pnkx_nav_core` cần `add_subdirectory` gói này trong `CMakeLists.txt` gốc, trước `move_base2`.
|
||||
140
include/env_monitor_core/env_detector.h
Normal file
140
include/env_monitor_core/env_detector.h
Normal file
@@ -0,0 +1,140 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — contract of one detector inside EnvMonitor.
|
||||
*
|
||||
* A detector is pure: each control cycle it gets the sample the host already gathered (EnvFrame) and
|
||||
* answers through EnvDetectorOutput (flag, brake, speed cap, event) plus its own diagnostic fields of
|
||||
* EnvVerdict. It never calls a port, a costmap or TF: the host computes the features that at least one
|
||||
* detector asks for (needs()) once per cycle. That keeps every detector testable from a table of samples.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_ENV_DETECTOR_H_
|
||||
#define ENV_MONITOR_CORE_ENV_DETECTOR_H_
|
||||
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/time.h>
|
||||
|
||||
#include <env_monitor_core/env_types.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
/// Features a detector reads. The host samples each one only if some loaded detector needs it.
|
||||
struct EnvNeeds
|
||||
{
|
||||
bool geometry = false; ///< heavy features at check_period: cost_to_go, reachable, edt_body_min.
|
||||
bool sweep = false; ///< every cycle: traj_contact_dist along the real trajectory.
|
||||
/// [s] Longest window of robot positions the detector keeps. A relocalization restarts those windows at most once
|
||||
/// per the longest such window over all detectors (see EnvMonitorConfig::pose_jump_reject). 0 = keeps none.
|
||||
double position_window_s = 0.0;
|
||||
// TODO(intrusion): add `scans` — raw lidar points from sensor_store (NavigationServer::getLaserScan) moved to
|
||||
// base_link, plus the polygon footprint. IntrusionDetector needs them; without them it cannot see points
|
||||
// inside 100 mm of the body edge that the costmap inflates away. Host side samples them only when needed.
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Recovery route of a detector. The host reads `route`, `route_mode` and `on_exhausted` from the detector's block
|
||||
* (`env_monitor/<name>`); a missing key takes the value from EnvDetector::defaultRoute().
|
||||
*/
|
||||
struct EnvRouteSpec
|
||||
{
|
||||
std::string route; ///< name of a route in `recovery/routes`.
|
||||
bool sequence = false; ///< `route_mode: sequence` = one firing runs the whole route; false = `step`.
|
||||
bool lock_on_exhausted = true; ///< `on_exhausted: lock` (forecast: lock, keep the plan) / `abort` (end the leg).
|
||||
};
|
||||
|
||||
/// Read-only state the host owns and shares with every detector (odometer, goal and plan marks, budget).
|
||||
struct EnvShared
|
||||
{
|
||||
robot::Time now;
|
||||
double cmd_accum = 0.0; ///< [m] Σ|v_cmd|·dt since start (monotonic, use differences).
|
||||
double travel_total = 0.0; ///< [m] odometer from the pose, relocalization jumps excluded.
|
||||
double jump_dist_total = 0.0; ///< [m] sum of rejected pose jumps.
|
||||
bool has_goal = false;
|
||||
double cmd_at_goal = 0.0; ///< [m] cmd_accum when the current goal was accepted.
|
||||
bool in_grace = false; ///< within grace_after_new_plan of the last applied plan.
|
||||
bool replan_muted = false; ///< replan budget not yet travelled since the last detour with a new path.
|
||||
bool pose_jump_restart = false; ///< this cycle's pose jump restarts the position windows.
|
||||
bool measurable = false; ///< has a plan AND a current costmap: progress can be measured.
|
||||
};
|
||||
|
||||
/// Everything a detector sees in one cycle.
|
||||
struct EnvFrame
|
||||
{
|
||||
EnvSample sample;
|
||||
EnvShared shared;
|
||||
};
|
||||
|
||||
/// What the host merges over detectors: flags per detector, brake OR, v_cap min, event overwritten in list order.
|
||||
struct EnvDetectorOutput
|
||||
{
|
||||
bool fired = false; ///< asks for recovery this cycle (after action, gates, budget, backoff).
|
||||
bool brake = false; ///< the command must be 0 this cycle.
|
||||
double v_cap = std::numeric_limits<double>::infinity(); ///< [m/s] cap on |v|; +inf = none.
|
||||
const char* event = ""; ///< edge event of this cycle ("" = none); a later detector's event wins.
|
||||
};
|
||||
|
||||
/**
|
||||
* @class EnvDetector
|
||||
* @brief One verdict of EnvMonitor. Not thread-safe; only the control thread calls it, through the host.
|
||||
*/
|
||||
class EnvDetector
|
||||
{
|
||||
public:
|
||||
using Ptr = std::shared_ptr<EnvDetector>;
|
||||
|
||||
virtual ~EnvDetector() = default;
|
||||
|
||||
/// Read and validate the parameters. @p nh is scoped to `env_monitor/<name>`; missing keys keep the defaults
|
||||
/// (warned). Invalid values fail with @p error — the host then refuses to start, like the monolithic monitor.
|
||||
virtual bool initialize(const std::string& name, robot::NodeHandle& nh, std::string& error) = 0;
|
||||
|
||||
/// One boot-log line: what is on, the action, the thresholds.
|
||||
virtual std::string describe() const = 0;
|
||||
|
||||
/// Raises a flag (`action: recover`) or acts on the command. All detectors not armed = SHADOW mode.
|
||||
virtual bool armed() const = 0;
|
||||
|
||||
/// Route used when the YAML block has no `route` / `route_mode` / `on_exhausted`.
|
||||
virtual EnvRouteSpec defaultRoute() const = 0;
|
||||
|
||||
/// This detector's brake and speed cap act on the command (`apply_command`); otherwise they are only reported.
|
||||
virtual bool appliesCommand() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual EnvNeeds needs() const = 0;
|
||||
|
||||
/// Back to the initial state (new goal, leaving kControlling). Keeps the configuration.
|
||||
virtual void reset() = 0;
|
||||
|
||||
/// A new plan was applied (planner or detour).
|
||||
virtual void onPlanApplied(const EnvShared& shared)
|
||||
{
|
||||
(void)shared;
|
||||
}
|
||||
|
||||
/// A recovery just ended, before the new plan (if any) is applied.
|
||||
/// @param own_route the recovery was started by this detector's flag.
|
||||
virtual void onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route)
|
||||
{
|
||||
(void)shared;
|
||||
(void)outcome;
|
||||
(void)own_route;
|
||||
}
|
||||
|
||||
/// One cycle. Write the merged part to @p out and only this detector's diagnostic fields to @p verdict.
|
||||
virtual void update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& verdict) = 0;
|
||||
};
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
#endif // ENV_MONITOR_CORE_ENV_DETECTOR_H_
|
||||
48
include/env_monitor_core/env_detector_abi.h
Normal file
48
include/env_monitor_core/env_detector_abi.h
Normal file
@@ -0,0 +1,48 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — ABI version of EnvDetector plugins and the boost::dll export macro.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_ENV_DETECTOR_ABI_H_
|
||||
#define ENV_MONITOR_CORE_ENV_DETECTOR_ABI_H_
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief ABI of `EnvDetector` and the structs it exchanges (`EnvFrame`, `EnvShared`, `EnvSample`, `EnvVerdict`,
|
||||
* `EnvDetectorOutput`, `EnvNeeds`).
|
||||
*
|
||||
* BUMP it on every change of a virtual signature or of those structs' layout. A plugin built against old headers
|
||||
* and loaded into a new runtime calls into the wrong vtable slot or reads a shifted field — a runtime crash that
|
||||
* no compiler catches (boost::dll = dlsym + reinterpret_cast). EnvMonitor reads `<Type>_abi` BEFORE the factory
|
||||
* and refuses the plugin on mismatch.
|
||||
*
|
||||
* 1 — 2026-11-26: first plugin version (stall / unreachable / contact split out of EnvMonitor).
|
||||
*/
|
||||
constexpr int kEnvDetectorAbiVersion = 1;
|
||||
|
||||
/// Exported next to every plugin through @ref ENV_MONITOR_CORE_EXPORT_DETECTOR; returns @ref kEnvDetectorAbiVersion.
|
||||
inline int envDetectorAbiVersion()
|
||||
{
|
||||
return kEnvDetectorAbiVersion;
|
||||
}
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
/**
|
||||
* @brief Export a detector for boost::dll together with its ABI version.
|
||||
*
|
||||
* @param factory function returning `env_monitor_core::EnvDetector::Ptr`.
|
||||
* @param symbol name matching `type` in the YAML (`{name: stall, type: StallDetector}`).
|
||||
*/
|
||||
#define ENV_MONITOR_CORE_EXPORT_DETECTOR(factory, symbol) \
|
||||
BOOST_DLL_ALIAS(factory, symbol) \
|
||||
BOOST_DLL_ALIAS(env_monitor_core::envDetectorAbiVersion, symbol##_abi)
|
||||
|
||||
#endif // ENV_MONITOR_CORE_ENV_DETECTOR_ABI_H_
|
||||
177
include/env_monitor_core/env_monitor.h
Normal file
177
include/env_monitor_core/env_monitor.h
Normal file
@@ -0,0 +1,177 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — lõi quyết định của EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md §2.3, P2).
|
||||
*
|
||||
* Thuần: không costmap, không TF, không log trong cycle, không cấp phát sau `initialize`. Vào là một @ref EnvSample
|
||||
* mỗi control cycle (feature đã tính ở cổng bằng `grid_analysis`), ra là một @ref EnvVerdict: các cờ
|
||||
* cho state machine đúng như PathMonitor cũ (`no_progress`, `path_blocked`, `collision`), lệnh phanh và
|
||||
* bao tốc độ. Nhờ thuần nên kiểm được bằng bảng và replay được trên feature ghi lại.
|
||||
*
|
||||
* Triết lý (chốt 5/9/2026): local planner tự do né, recovery chỉ khi BẾ TẮC THẬT. Không có verdict
|
||||
* "plan bị chắn". Ba verdict:
|
||||
* - kStall — lệnh ≠ 0 mà `cost_to_go` (địa trắc tới điểm thoát + phần plan còn lại) không giảm.
|
||||
* - kUnreachable — không còn đường trong cửa sổ tới điểm thoát, tĩnh, và xấu hơn lúc nhận plan.
|
||||
* - kContact — thân sắp chạm trên quỹ đạo thật: phanh ngay, cờ chỉ khi tiếp xúc đứng yên.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_ENV_MONITOR_H_
|
||||
#define ENV_MONITOR_CORE_ENV_MONITOR_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/time.h>
|
||||
|
||||
#include <env_monitor_core/env_detector.h>
|
||||
#include <env_monitor_core/env_monitor_config.h>
|
||||
#include <env_monitor_core/env_types.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
/// One loaded detector, in `env_monitor/detectors` order (the index is the bit of EnvVerdict::fired_mask).
|
||||
struct EnvDetectorInfo
|
||||
{
|
||||
std::string name;
|
||||
std::string type;
|
||||
std::string library;
|
||||
EnvRouteSpec route;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class EnvMonitor
|
||||
* @brief Lõi thuần. Không thread-safe; chỉ control thread gọi.
|
||||
*/
|
||||
class EnvMonitor
|
||||
{
|
||||
public:
|
||||
EnvMonitor() = default;
|
||||
~EnvMonitor();
|
||||
EnvMonitor(const EnvMonitor&) = delete;
|
||||
EnvMonitor& operator=(const EnvMonitor&) = delete;
|
||||
|
||||
/**
|
||||
* @brief Đọc khối `env_monitor` dưới @p nh và nạp các detector.
|
||||
*
|
||||
* Danh sách `env_monitor/detectors: [{name, type}]`; thiếu khoá thì nạp contact, stall, unreachable (log info).
|
||||
* Mỗi type tra `<Type>/library_path` dưới @p nh (cùng cách action_core / recovery_core), kiểm `<Type>_abi`, rồi
|
||||
* `initialize(name, env_monitor/<name>)`. Không tìm thấy thư viện, thiếu/lệch ABI: log LỖI, bỏ detector đó, chạy
|
||||
* tiếp. Tham số sai (phần chung hoặc của một detector): trả false với @p error, như bản một khối từ chối config.
|
||||
* `enabled: false`: không nạp gì, không kiểm gì.
|
||||
*/
|
||||
bool initialize(robot::NodeHandle& nh, std::string& error);
|
||||
bool configured() const
|
||||
{
|
||||
return configured_;
|
||||
}
|
||||
bool enabled() const
|
||||
{
|
||||
return configured_ && config_.enabled;
|
||||
}
|
||||
|
||||
/// @brief Phần chung và một dòng cho mỗi detector đã nạp (tên, type, thư viện, tham số).
|
||||
std::string describe() const;
|
||||
/// @brief Có detector nào giơ cờ hoặc tác động lên lệnh không. Không có = SHADOW.
|
||||
bool armed() const;
|
||||
/// @brief Hợp các feature mà detector đã nạp cần.
|
||||
EnvNeeds needs() const;
|
||||
std::size_t detectorCount() const
|
||||
{
|
||||
return detectors_.size();
|
||||
}
|
||||
/// @brief Detector đã nạp, đúng thứ tự chạy; chỉ số i là bit i của EnvVerdict::fired_mask.
|
||||
const std::vector<EnvDetectorInfo>& detectors() const
|
||||
{
|
||||
return loaded_;
|
||||
}
|
||||
/// @brief Gỡ một detector đã nạp (ví dụ host không tìm thấy route của nó). @return false nếu không có tên đó.
|
||||
bool remove(const std::string& name);
|
||||
|
||||
/// @brief Về trạng thái ban đầu (rời kControlling, huỷ chặng). Giữ config.
|
||||
void reset();
|
||||
|
||||
/// @brief Chặng mới được nhận: đặt lại mọi ngân sách, mốc lệnh đầu chặng.
|
||||
void onGoalAccepted(const robot::Time& now);
|
||||
|
||||
/// @brief Plan mới được áp (planner hay detour): xoá cửa sổ, bắt đầu grace, chờ baseline liên thông.
|
||||
void onPlanApplied(const robot::Time& now);
|
||||
|
||||
/// @brief Một lượt recovery vừa kết thúc (trước khi plan mới, nếu có, được áp).
|
||||
/// @param source_detector tên detector có route vừa chạy ("" = trigger không phải của monitor).
|
||||
void onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome,
|
||||
const std::string& source_detector = std::string());
|
||||
|
||||
/// @brief Một cycle. Gọi SAU khi các feature của cycle đã có, TRƯỚC state machine.
|
||||
EnvVerdict update(const EnvSample& sample);
|
||||
|
||||
// --- soi trạng thái (test, log) ---
|
||||
double commandedTotal() const
|
||||
{
|
||||
return cmd_accum_;
|
||||
}
|
||||
double travelledTotal() const
|
||||
{
|
||||
return travel_total_;
|
||||
}
|
||||
double replanBudget() const
|
||||
{
|
||||
return budget_travel_;
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr std::size_t kMaxDetectors = 32; ///< bits of EnvVerdict::fired_mask
|
||||
|
||||
/// Read-only view of the host state for the detectors.
|
||||
EnvShared shared(const robot::Time& now) const;
|
||||
/// @return false and a non-empty @p error = invalid parameters (fatal); false and empty @p error = not loaded.
|
||||
bool load(const std::string& name, const std::string& type, robot::NodeHandle& nh, robot::NodeHandle& env_nh,
|
||||
std::string& error);
|
||||
void clear();
|
||||
|
||||
/// Chỉ phần chung (enabled, grace, pose_jump_reject, replan). Tham số detector nằm trong detector.
|
||||
EnvMonitorConfig config_;
|
||||
bool configured_ = false;
|
||||
/// Factory giữ thư viện .so còn nạp. Khai TRƯỚC detectors_: hủy ngược thứ tự khai báo, nên detector chết trước
|
||||
/// thư viện của nó (vtable không trỏ vào vùng đã unmap).
|
||||
std::vector<std::function<EnvDetector::Ptr()>> factories_;
|
||||
/// Chạy theo đúng thứ tự `env_monitor/detectors` mỗi cycle; detector sau ghi đè `event` của detector trước.
|
||||
std::vector<EnvDetector::Ptr> detectors_;
|
||||
std::vector<EnvDetectorInfo> loaded_;
|
||||
double restart_cooldown_ = 0.0; ///< [s] max position_window_s over detectors (EnvNeeds).
|
||||
|
||||
// Tích luỹ
|
||||
double cmd_accum_ = 0.0; ///< [m] Σ|v_cmd|·dt
|
||||
double travel_total_ = 0.0; ///< [m] odometer từ pose
|
||||
double jump_dist_total_ = 0.0; ///< [m] tổng độ dời pose bị loại, chỉ dùng cho bộ lọc cost jump.
|
||||
bool has_last_pose_ = false;
|
||||
double last_x_ = 0.0;
|
||||
double last_y_ = 0.0;
|
||||
robot::Time last_pose_t_;
|
||||
double v_gap_max_ = 0.0; ///< [m/s] tốc độ lớn nhất từ pose hữu hạn gần nhất.
|
||||
bool has_pose_jump_restart_ = false;
|
||||
robot::Time pose_jump_restart_t_;
|
||||
|
||||
// Mốc chặng / plan
|
||||
bool has_goal_ = false;
|
||||
double cmd_at_goal_ = 0.0;
|
||||
bool has_plan_time_ = false;
|
||||
robot::Time plan_time_;
|
||||
|
||||
// Ngân sách replan (R3/R5)
|
||||
bool has_replan_mark_ = false;
|
||||
double replan_mark_travel_ = 0.0; ///< odometer tại lần detour thành công gần nhất.
|
||||
double budget_travel_ = 0.0; ///< [m] ngân sách hiện hành (= min_travel, nhân factor khi lặp).
|
||||
bool has_prev_replan_ = false;
|
||||
double prev_replan_travel_ = 0.0;
|
||||
};
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
#endif // ENV_MONITOR_CORE_ENV_MONITOR_H_
|
||||
181
include/env_monitor_core/env_monitor_config.h
Normal file
181
include/env_monitor_core/env_monitor_config.h
Normal file
@@ -0,0 +1,181 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — tham số của EnvMonitor (host + ba detector có sẵn).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_ENV_MONITOR_CONFIG_H_
|
||||
#define ENV_MONITOR_CORE_ENV_MONITOR_CONFIG_H_
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
/**
|
||||
* @struct EnvMonitorConfig
|
||||
* @brief Tham số lõi. Đơn vị trong tên hoặc comment. Mọi ngưỡng số là GIÁ TRỊ KHỞI ĐIỂM rút từ hai bag
|
||||
* sim 5/9/2026 (Test/docs/move_base2/ENV_MONITOR_PLAN.md §4.4); chốt lại bằng shadow/replay, không bằng tay.
|
||||
*/
|
||||
struct EnvMonitorConfig
|
||||
{
|
||||
bool enabled = true;
|
||||
|
||||
/// [s] Sau khi nhận plan mới (planner hoặc detour) không kết luận gì: mẫu cũ thuộc plan cũ.
|
||||
double grace_after_new_plan = 1.0;
|
||||
|
||||
/// [m] Pose dời quá (đây + tốc độ lớn nhất trong khoảng mất pose nhân thời gian từ pose hợp lệ trước) = pose bị
|
||||
/// đặt lại. Cú dời không cộng vào odometer; cửa sổ kStall bắt đầu lại tối đa một lần mỗi cửa sổ vị trí dài nhất.
|
||||
/// Sim 6/11 20:34:34: AMCL "Setting pose" kéo pose lùi 1,2 m giữa lúc chạy thẳng 0,3 m/s -> quỹ đạo 20 s gấp đôi
|
||||
/// lên chính nó -> giam vùng nổ oan 8,65 s sau. 0 = tắt (cú dời được tính như quãng đi, như bản cũ).
|
||||
double pose_jump_reject = 0.5;
|
||||
|
||||
/**
|
||||
* kStall — "planner đòi đi mà cost_to_go không giảm". Đi cờ `no_progress` -> trigger oscillation
|
||||
* (trigger GỐC: cạn route là ABORT chặng), nên `action` mặc định "log" cho tới khi shadow đủ dài.
|
||||
*/
|
||||
struct Stall
|
||||
{
|
||||
bool enabled = true;
|
||||
std::string action = "log"; ///< "log" = chỉ báo trong verdict; "recover" = giơ cờ.
|
||||
double window_s = 4.0; ///< [s] cửa sổ đo eff.
|
||||
/// [m] Hai mẫu nặng liên tiếp mà cost_to_go đổi quá (đây + quãng robot dịch) = mặt nạ free đổi liên thông (ô
|
||||
/// nhấp nháy ở mép khe), không phải tiến/lùi: xoá cửa sổ đo, bắt đầu lại. Run 5/9 23:37: geo nhảy +3,2 m trong
|
||||
/// 0,2 s, eff −2,7, detour oan. 0 = tắt.
|
||||
double jump_reject = 1.0;
|
||||
/// Cổng DỊCH CHUYỂN THỰC (6/9): "bế tắc thật" = robot không đi được đâu, không phải "không tiến theo plan".
|
||||
/// Chỉ giơ cờ khi trong disp_window_s gần nhất robot dịch chuyển thực (khoảng cách đầu-cuối) < disp_min dù đã
|
||||
/// lệnh >= disp_min_commanded. Né tự do luôn dịch chuyển -> không nổ; quần trong hộp 0,9 m (run 5/9 00:05,
|
||||
/// 97 s) -> nổ sau ~window. Cửa sổ vị trí bắt đầu lại ở mỗi plan mới, thay cho ngân sách replan R3/R5 (đo
|
||||
/// theo quãng đường nên đi vòng đốt ngân sách rất chậm, câm cờ đúng 97 s). disp_min = 0 -> tắt cổng, dùng lại
|
||||
/// ngân sách replan như cũ.
|
||||
double disp_window_s = 12.0;
|
||||
double disp_min = 0.6; ///< [m]
|
||||
double disp_min_commanded = 1.5; ///< [m]
|
||||
/// [s] Cổng ĐỨNG YÊN: robot dịch chuyển thực < disp_min trong chừng này giây (không cần lệnh đủ) -> kẹt, kể cả
|
||||
/// khi geodesic không đo được. Run 6/9 10:59: PRIEST bò 0,03–0,15 m/s tại chỗ 30 s (blocked_ahead cost 253, res
|
||||
/// 1,6 chưa tới ngưỡng khai bất khả thi), lệnh tích luỹ 12 s chỉ 0,1–0,4 m nên cổng dịch chuyển câm; kUnreachable
|
||||
/// mới gỡ ở 75 s. Thử trên 7 lượt: bắt đúng 2 ca quần tại chỗ, 0 lần ở 3 lượt sạch. 0 = tắt.
|
||||
double idle_window_s = 25.0;
|
||||
/// Cổng GIAM VÙNG: trong confine_window_s mọi vị trí nằm trong vòng bán kính < confine_radius quanh tâm của chúng,
|
||||
/// và lệnh tích luỹ >= confine_cmd_factor x max(2 x bán kính đo được, disp_min) — đi nhiều mà không ra khỏi vùng
|
||||
/// nhỏ = loanh quanh trong local minimum. Cổng dịch chuyển đo đầu–cuối nên mù với vòng bán kính > 0,3 m; cổng
|
||||
/// đứng yên chỉ bắt gần như đứng. Replay 8 lượt 5–6/9: bắt 00:05 (101 s thay vì 206), 10:57 (27 s thay vì 75),
|
||||
/// 23:37; 0 lần ở 5 lượt sạch. Hệ số lệnh chặn ca bò thẳng chậm sau người (2 m/20 s: bán kính 1 m, lệnh 2 m
|
||||
/// < 1,5 x 2 m). confine_radius = 0 -> tắt. Chỉ hoạt động khi disp_min > 0.
|
||||
/// Cổng giam vùng KHÔNG nổ khi tiến độ đã được chứng minh: mọi eff đo được trong
|
||||
/// confine_window_s gần nhất đều >= eff_off, và eff gần nhất mới hơn window_s. Plan hợp lệ có vòng quay đầu (planner
|
||||
/// chỉ đi tiến) giữ robot trong vòng nhỏ mà cost_to_go vẫn giảm đều. Cổng đứng yên không bị phủ quyết.
|
||||
double confine_window_s = 20.0;
|
||||
double confine_radius = 1.2; ///< [m]
|
||||
double confine_cmd_factor = 1.5; ///< [-]
|
||||
/// Bật phủ quyết theo tiến độ cho cổng giam vùng (xem confine_window_s). false = giam vùng chỉ xét hình học.
|
||||
bool progress_veto = true;
|
||||
double window_m = 1.5; ///< [m] hoặc theo lệnh tích luỹ — cái tới trước.
|
||||
double min_commanded = 0.30; ///< [m] lệnh trong cửa sổ ít hơn = đang chờ, không đo.
|
||||
double eff_on = 0.20; ///< [-] eff dưới đây là kẹt.
|
||||
double eff_off = 0.50; ///< [-] trên đây mới xoá (hysteresis).
|
||||
double confirm = 1.0; ///< [s] kẹt liên tục chừng này mới nổ.
|
||||
double goal_zone = 0.6; ///< [m] gần goal hơn đây không đo.
|
||||
double slip_on = 0.15; ///< [m/s] |v_cmd| - |v_meas| liên tục = kẹt vật lý. 0 = tắt.
|
||||
double slip_time = 1.0; ///< [s]
|
||||
double min_commanded_since_goal = 1.0; ///< [m] cổng đầu chặng (cắt nổ sớm 13,0 / 145,6 bag 1).
|
||||
double retry_backoff = 3.0; ///< [s] sau một lượt recovery HỎNG không tích bằng chứng.
|
||||
} stall;
|
||||
|
||||
/// kUnreachable — cờ `path_blocked` -> route path_blocked (cạn route chỉ KHOÁ, an toàn để bật).
|
||||
struct Unreachable
|
||||
{
|
||||
bool enabled = true;
|
||||
std::string action = "recover";
|
||||
double static_on = 1.0; ///< [s] mất liên thông liên tục chừng này mới nổ.
|
||||
double clean_start_margin = 0.20; ///< [m] edt_body_min tối thiểu để còn gọi replan được.
|
||||
double retry_backoff = 2.0; ///< [s]
|
||||
} unreachable;
|
||||
|
||||
/// kContact — phanh theo quỹ đạo thật; cờ `collision` -> route collision.
|
||||
struct Contact
|
||||
{
|
||||
bool enabled = true;
|
||||
std::string action = "recover";
|
||||
int confirm_cycles = 2; ///< [cycle] chạm liên tục chừng này thì phanh.
|
||||
double trigger_static_time = 1.0; ///< [s] phanh mà tiếp xúc còn đó chừng này mới giơ cờ.
|
||||
double clean_start_margin = 0.20; ///< [m] dừng với thân còn cách vật ít nhất chừng này.
|
||||
double brake_decel = 0.35; ///< [m/s^2] decel dùng cho quãng phanh và bao tốc độ.
|
||||
double min_speed = 0.05; ///< [m/s] bao tốc độ không kẹp thấp hơn đây (thấp hơn = dừng).
|
||||
/// [m/s] |v_cmd| và |v_đo| đều dưới đây mà monitor CHƯA phanh = robot đang xoay tại chỗ hoặc bò: đó là
|
||||
/// chuyển động của controller, không phải bài toán quãng phanh -> không phanh, không cờ (cùng vai
|
||||
/// `path_monitor/collision_min_speed` cũ). Shadow 5/9: ba lần "braking to zero" ngay đầu chặng khi
|
||||
/// robot xoay ra khỏi vật kề mũi (v 0.00–0.07 m/s) đều là nổ oan kiểu này.
|
||||
double min_check_speed = 0.10;
|
||||
/// [m] Hysteresis cho "kề mũi": đã kề (d <= margin) thì còn kề tới khi d > margin + đây. Local planner
|
||||
/// đổi quỹ đạo mỗi cycle nên d nhảy 0,08 <-> 0,25 m quanh margin (run 5/9 22:35): không có nó thì phanh
|
||||
/// bật/nhả 4 lần/s và đồng hồ giơ cờ bị reset liên tục.
|
||||
double release_hysteresis = 0.10;
|
||||
/// [cycle] Nhả phanh (quỹ đạo sạch hoặc lùi xa) chỉ sau chừng này cycle liên tiếp không còn "sắp chạm".
|
||||
int release_confirm_cycles = 4;
|
||||
/// [m] Dư của bao tốc độ so với ngưỡng phanh: v_cap = sqrt(2a(d - margin - đây)), tối thiểu min_speed cho
|
||||
/// tới d <= margin (= 0). 0 = bao đặt đúng biên phanh -> cứ kẹp xong là chớm "sắp chạm" (rung tiếp cận run
|
||||
/// 5/9 22:58: 9/28 lần phanh < 0,3 s).
|
||||
double envelope_margin = 0.10;
|
||||
/// [m] Detour do CHÍNH cờ collision vừa xong mà robot dịch chưa tới đây và lại "sắp chạm" -> kContact ĐỨNG RA
|
||||
/// (không phanh, không cờ, không bao) tới khi đi được standdown_travel hoặc quỹ đạo sạch: detour từ trong khe
|
||||
/// là vô nghĩa, xoay là chạm (m1/m8 run 5/9 22:58 churn 3 detour rồi ABORT); mission 6 cùng lượt thoát được
|
||||
/// đúng lúc guard "nhường controller". 0 = tắt.
|
||||
double standdown_min_travel = 0.10;
|
||||
double standdown_travel = 0.30; ///< [m] đứng ra chừng này quãng đường rồi vũ trang lại.
|
||||
bool envelope = true; ///< bật bao tốc độ theo tiếp xúc trên quỹ đạo.
|
||||
/// false = SHADOW: `brake`/`v_cap` chỉ được báo trong verdict, ControlLoop không đụng lệnh.
|
||||
/// true = phanh và bao tốc độ tác động thật lên lệnh trước trọng tài. Lõi không dùng cờ này.
|
||||
bool apply_command = false;
|
||||
} contact;
|
||||
|
||||
/// Ngân sách replan theo quãng đường (R3 + R5) cho kStall và kUnreachable.
|
||||
struct ReplanBudget
|
||||
{
|
||||
double min_travel = 1.5; ///< [m] sau detour thành công, im tới khi đi chừng này.
|
||||
double escalate_factor = 2.0; ///< [-] replan lặp trong escalate_window_m thì nhân ngân sách.
|
||||
double escalate_window_m = 10.0; ///< [m] đi chừng này không replan thì về min_travel.
|
||||
/// [m] Trần của leo thang; 0 = không trần. Run 5/9 22:35: 4 detour PRIEST trong 10 m -> 1,5 -> 3 -> 6 -> 12 m,
|
||||
/// kStall câm gần hết chặng.
|
||||
double escalate_max = 6.0;
|
||||
} replan;
|
||||
|
||||
bool validate(std::string& error) const;
|
||||
std::string describe() const;
|
||||
};
|
||||
|
||||
// Từng phần dùng riêng: host đọc phần chung, mỗi detector đọc khối của mình (`env_monitor/<name>`).
|
||||
// Khoá thiếu giữ giá trị mặc định và log cảnh báo, như move_base2 đọc trước đây.
|
||||
|
||||
/// Phần chung của host: `enabled`, `grace_after_new_plan`, `pose_jump_reject`, khối `replan_budget`.
|
||||
/// @param env_nh NodeHandle trỏ vào khối `env_monitor`.
|
||||
void readHost(robot::NodeHandle& env_nh, EnvMonitorConfig& config);
|
||||
void readStall(robot::NodeHandle& nh, EnvMonitorConfig::Stall& stall);
|
||||
void readUnreachable(robot::NodeHandle& nh, EnvMonitorConfig::Unreachable& unreachable);
|
||||
void readContact(robot::NodeHandle& nh, EnvMonitorConfig::Contact& contact);
|
||||
|
||||
/// Ngược của read*: toàn bộ struct thành khối YAML `env_monitor` (số viết 17 chữ số, đọc lại ra đúng từng bit).
|
||||
/// Dùng cho test và công cụ dựng config; không có khoá `detectors` (= danh sách mặc định).
|
||||
YAML::Node toYaml(const EnvMonitorConfig& config);
|
||||
|
||||
bool validateHost(const EnvMonitorConfig& config, std::string& error);
|
||||
bool validateStall(const EnvMonitorConfig::Stall& stall, std::string& error);
|
||||
bool validateUnreachable(const EnvMonitorConfig::Unreachable& unreachable, std::string& error);
|
||||
bool validateContact(const EnvMonitorConfig::Contact& contact, std::string& error);
|
||||
|
||||
/// Nội dung một dòng log boot (sau nhãn tên), cùng chữ với bản một khối.
|
||||
std::string describeStall(const EnvMonitorConfig::Stall& stall);
|
||||
std::string describeUnreachable(const EnvMonitorConfig::Unreachable& unreachable);
|
||||
std::string describeContact(const EnvMonitorConfig::Contact& contact);
|
||||
std::string describeReplan(const EnvMonitorConfig::ReplanBudget& replan);
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
#endif // ENV_MONITOR_CORE_ENV_MONITOR_CONFIG_H_
|
||||
109
include/env_monitor_core/env_types.h
Normal file
109
include/env_monitor_core/env_types.h
Normal file
@@ -0,0 +1,109 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — dữ liệu vào/ra một cycle của EnvMonitor, dùng chung cho host và mọi detector.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_ENV_TYPES_H_
|
||||
#define ENV_MONITOR_CORE_ENV_TYPES_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
|
||||
#include <robot/time.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
/**
|
||||
* @struct EnvSample
|
||||
* @brief Dữ liệu vào của một cycle. Phần "nặng" chỉ có nghĩa khi @ref geometry_valid (nhịp 5 Hz).
|
||||
* NaN / +inf = không có; lõi không suy diễn từ giá trị thiếu.
|
||||
*/
|
||||
struct EnvSample
|
||||
{
|
||||
robot::Time now;
|
||||
double dt = 0.0; ///< [s] từ cycle trước; 0 ở cycle đầu.
|
||||
bool costmap_current = true; ///< costmap stale -> mọi kết luận hình học là quá khứ.
|
||||
bool has_plan = false;
|
||||
/// [m] pose robot, frame bất kỳ nhưng cố định (đo quãng đường). NaN = không có pose cycle này. Frame `map` nhảy
|
||||
/// khi localization đặt lại pose: lõi tự nhận ra cú nhảy (EnvMonitorConfig::pose_jump_reject).
|
||||
double robot_x = 0.0;
|
||||
double robot_y = 0.0;
|
||||
double v_cmd = 0.0; ///< [m/s] lệnh SAU trọng tài của cycle trước.
|
||||
double w_cmd = 0.0; ///< [rad/s]
|
||||
double v_meas = std::numeric_limits<double>::quiet_NaN(); ///< [m/s] đo được; NaN = không có.
|
||||
/// [m/s] lệnh controller MUỐN ở cycle trước, TRƯỚC bao tốc độ / phanh / trọng tài; NaN = không biết.
|
||||
/// Cần cho cổng xoay của kContact: bao kẹp lệnh về 0 trong margin làm v_cmd = 0 dù controller vẫn đòi
|
||||
/// đi — không có số này, cổng xoay coi đó là "đứng yên" và robot dừng câm không cờ.
|
||||
double v_controller = std::numeric_limits<double>::quiet_NaN();
|
||||
bool controller_valid = true; ///< controller cycle trước có ra lệnh không.
|
||||
double d_goal = std::numeric_limits<double>::infinity(); ///< [m] Euclid tới goal.
|
||||
|
||||
bool geometry_valid = false; ///< các trường dưới đây vừa được tính ở tick này.
|
||||
bool cost_conclusive = false; ///< costToGo kết luận được.
|
||||
bool reachable = false; ///< có đường địa trắc tới T.
|
||||
double cost_to_go = std::numeric_limits<double>::infinity(); ///< [m]
|
||||
double edt_body_min = std::numeric_limits<double>::quiet_NaN(); ///< [m]
|
||||
|
||||
bool contact_conclusive = false; ///< sweep quỹ đạo kết luận được (mỗi cycle).
|
||||
double traj_contact_dist = std::numeric_limits<double>::infinity(); ///< [m] dọc quỹ đạo.
|
||||
};
|
||||
|
||||
/// Kết quả một lượt recovery mà lõi cần biết (không include recovery_core: chỉ ba ý nghĩa).
|
||||
enum class EnvRecoveryOutcome
|
||||
{
|
||||
kSucceededWithPath, ///< detour_path nộp path mới -> ngân sách theo quãng đường.
|
||||
kSucceeded, ///< behavior khác thành công (không đổi plan).
|
||||
kFailed ///< hỏng -> retry_backoff.
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct EnvVerdict
|
||||
* @brief Kết quả một cycle. Cờ đầu là cái đưa vào `StateMachineInput` (đã qua action + cổng +
|
||||
* ngân sách); phần chẩn đoán là số thô để log / ghi JSONL.
|
||||
*/
|
||||
struct EnvVerdict
|
||||
{
|
||||
/// Bit i = detector thứ i (thứ tự `env_monitor/detectors`) đòi recovery cycle này. State machine đọc mask này;
|
||||
/// ba cờ dưới là chẩn đoán của ba detector có sẵn (log, JSONL).
|
||||
std::uint32_t fired_mask = 0;
|
||||
bool no_progress = false; ///< kStall hiệu lực.
|
||||
bool path_blocked = false; ///< kUnreachable hiệu lực.
|
||||
bool collision = false; ///< kContact hiệu lực (cờ, không phải phanh).
|
||||
bool brake = false; ///< Cycle này lệnh ra phải bằng 0.
|
||||
double v_cap = std::numeric_limits<double>::infinity(); ///< [m/s] trần |v| cycle này; +inf = không kẹp.
|
||||
/// Phần của brake / v_cap đến từ detector có `apply_command`: chỉ phần này tác động lên lệnh. Phần còn lại là shadow
|
||||
/// (chỉ log "would cap").
|
||||
bool brake_applied = false;
|
||||
double v_cap_applied = std::numeric_limits<double>::infinity(); ///< [m/s]
|
||||
|
||||
bool stall_detected = false; ///< điều kiện kẹt đã đủ confirm, chưa xét action/cổng.
|
||||
bool unreachable_detected = false;
|
||||
bool contact_imminent = false; ///< chạm trong quãng phanh ở cycle này.
|
||||
bool contact_standdown = false; ///< kContact đang đứng ra sau detour từ chính chỗ này (nhường controller).
|
||||
bool cost_jump = false; ///< tick này cost_to_go nhảy quá jump_reject: cửa sổ stall vừa bị xoá.
|
||||
bool pose_jump = false; ///< cycle này pose dời quá ngưỡng có tính đến quãng có thể đi.
|
||||
bool pose_jump_restart = false; ///< cú nhảy này thực sự xoá các cửa sổ stall.
|
||||
double pose_jump_dist = std::numeric_limits<double>::quiet_NaN(); ///< [m] độ dời của cú nhảy đó (NaN = không nhảy).
|
||||
bool progress_proven = false; ///< bằng chứng eff còn hiệu lực: có thể phủ quyết cổng giam vùng.
|
||||
bool stall_muted = false; ///< detected nhưng bị cổng/ngân sách/backoff/grace giữ lại.
|
||||
double net_disp = std::numeric_limits<double>::quiet_NaN(); ///< [m] dịch chuyển thực trong disp_window_s (NaN = chưa đủ mẫu).
|
||||
bool wandering = false; ///< cổng dịch chuyển đã mở: lệnh đủ mà không đi được đâu.
|
||||
bool idle = false; ///< cổng đứng yên đã mở: không dịch chuyển suốt idle_window_s.
|
||||
bool confined = false; ///< cổng giam vùng đã mở: đi nhiều mà ở trong vòng nhỏ suốt confine_window_s.
|
||||
bool confined_vetoed = false; ///< giam vùng nhưng bị phủ quyết vì tiến độ đã chứng minh (progress_veto).
|
||||
double region_radius = std::numeric_limits<double>::quiet_NaN(); ///< [m] bán kính vùng đã ở trong confine_window_s.
|
||||
bool unreachable_muted = false;
|
||||
double eff_geo = std::numeric_limits<double>::quiet_NaN(); ///< [-] eff của cửa sổ gần nhất.
|
||||
double cmd_window = 0.0; ///< [m] lệnh tích luỹ trong cửa sổ đó.
|
||||
double brake_dist = 0.0; ///< [m]
|
||||
double replan_budget_left = 0.0; ///< [m] còn phải đi bao xa mới hết mute sau replan (0 = không mute).
|
||||
const char* event = ""; ///< Sườn sự kiện của cycle này ("" = không có). Dùng để log một lần.
|
||||
};
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
#endif // ENV_MONITOR_CORE_ENV_TYPES_H_
|
||||
24
package.xml
Normal file
24
package.xml
Normal file
@@ -0,0 +1,24 @@
|
||||
<package>
|
||||
<name>env_monitor_core</name>
|
||||
<version>0.1.0</version>
|
||||
<description>
|
||||
Lõi giám sát môi trường khi bám plan: mỗi control cycle nhận một EnvSample (feature hình học
|
||||
đã tính sẵn ở host) và trả một EnvVerdict (cờ cho state machine, lệnh phanh, bao tốc độ).
|
||||
Thuần: không costmap, không TF, không I/O. Host (ví dụ move_base2) gom feature và nối kết quả
|
||||
vào state machine. Mỗi verdict là một detector plugin Boost.DLL (stall, unreachable, contact có
|
||||
sẵn), nạp theo danh sách env_monitor/detectors và khoá library_path trong YAML.
|
||||
</description>
|
||||
<author>DuongTD</author>
|
||||
<maintainer email="tdd@gmail.com">DuongTD</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
<build_depend>robot_time</build_depend>
|
||||
<run_depend>robot_time</run_depend>
|
||||
<!-- NodeHandle đọc YAML, PluginLoaderHelper tra library_path, log. -->
|
||||
<build_depend>robot_cpp</build_depend>
|
||||
<run_depend>robot_cpp</run_depend>
|
||||
<build_depend>yaml-cpp</build_depend>
|
||||
<run_depend>yaml-cpp</run_depend>
|
||||
</package>
|
||||
285
plugins/contact_detector.cpp
Normal file
285
plugins/contact_detector.cpp
Normal file
@@ -0,0 +1,285 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — kContact (xem contact_detector.h).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include "contact_detector.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
|
||||
#include <env_monitor_core/env_detector_abi.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
EnvDetector::Ptr ContactDetector::create()
|
||||
{
|
||||
return std::make_shared<ContactDetector>();
|
||||
}
|
||||
|
||||
bool ContactDetector::initialize(const std::string& name, robot::NodeHandle& nh, std::string& error)
|
||||
{
|
||||
(void)name;
|
||||
readContact(nh, config_);
|
||||
return validateContact(config_, error);
|
||||
}
|
||||
|
||||
std::string ContactDetector::describe() const
|
||||
{
|
||||
return describeContact(config_);
|
||||
}
|
||||
|
||||
EnvRouteSpec ContactDetector::defaultRoute() const
|
||||
{
|
||||
// Bản một khối: kContact đi route `collision`, cạn route là KHOÁ (dự báo; phanh vẫn giữ).
|
||||
EnvRouteSpec spec;
|
||||
spec.route = "collision";
|
||||
spec.lock_on_exhausted = true;
|
||||
return spec;
|
||||
}
|
||||
|
||||
bool ContactDetector::armed() const
|
||||
{
|
||||
return config_.action == "recover" || config_.apply_command;
|
||||
}
|
||||
|
||||
bool ContactDetector::appliesCommand() const
|
||||
{
|
||||
return config_.apply_command;
|
||||
}
|
||||
|
||||
EnvNeeds ContactDetector::needs() const
|
||||
{
|
||||
EnvNeeds n;
|
||||
n.sweep = config_.enabled;
|
||||
return n;
|
||||
}
|
||||
|
||||
void ContactDetector::reset()
|
||||
{
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
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;
|
||||
}
|
||||
|
||||
void ContactDetector::onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route)
|
||||
{
|
||||
if (outcome == 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_ = own_route;
|
||||
detour_mark_travel_ = shared.travel_total;
|
||||
}
|
||||
// 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ị.
|
||||
contact_streak_ = 0;
|
||||
release_streak_ = 0;
|
||||
braking_ = false;
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
}
|
||||
|
||||
void ContactDetector::update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v)
|
||||
{
|
||||
const EnvSample& s = frame.sample;
|
||||
const EnvShared& sh = frame.shared;
|
||||
const EnvMonitorConfig::Contact& c = config_;
|
||||
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ũ).
|
||||
out.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 = sh.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;
|
||||
out.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.
|
||||
out.brake = true;
|
||||
v.collision = contact_fired_ && c.action == "recover";
|
||||
out.fired = v.collision;
|
||||
return;
|
||||
}
|
||||
if (braking_ || contact_fired_)
|
||||
{
|
||||
out.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)
|
||||
{
|
||||
out.v_cap = 0.0;
|
||||
}
|
||||
else
|
||||
{
|
||||
const double room = s.traj_contact_dist - c.clean_start_margin - c.envelope_margin;
|
||||
out.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_ &&
|
||||
sh.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_ = sh.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;
|
||||
out.v_cap = std::numeric_limits<double>::infinity();
|
||||
out.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;
|
||||
out.event = "contact: braking to zero";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
contact_streak_ = 0;
|
||||
if (braking_ && ++release_streak_ >= c.release_confirm_cycles)
|
||||
{
|
||||
braking_ = false;
|
||||
release_streak_ = 0;
|
||||
out.event = "contact receded: releasing the brake";
|
||||
}
|
||||
}
|
||||
out.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;
|
||||
out.event = "contact persists while stopped: asking for a replan";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (contact_fired_)
|
||||
{
|
||||
out.event = "contact cleared: the obstacle moved away";
|
||||
}
|
||||
contact_close_ = false;
|
||||
contact_fired_ = false;
|
||||
}
|
||||
v.collision = contact_fired_ && c.action == "recover";
|
||||
out.fired = v.collision;
|
||||
}
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
ENV_MONITOR_CORE_EXPORT_DETECTOR(env_monitor_core::ContactDetector::create, ContactDetector)
|
||||
57
plugins/contact_detector.h
Normal file
57
plugins/contact_detector.h
Normal file
@@ -0,0 +1,57 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — kContact: thân sắp chạm trên quỹ đạo thật. Phanh + bao tốc độ; cờ `collision`.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_CONTACT_DETECTOR_H_
|
||||
#define ENV_MONITOR_CORE_CONTACT_DETECTOR_H_
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/time.h>
|
||||
|
||||
#include <env_monitor_core/env_detector.h>
|
||||
#include <env_monitor_core/env_monitor_config.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
class ContactDetector final : public EnvDetector
|
||||
{
|
||||
public:
|
||||
/// Factory exported to boost::dll (symbol `ContactDetector`).
|
||||
static EnvDetector::Ptr create();
|
||||
|
||||
bool initialize(const std::string& name, robot::NodeHandle& nh, std::string& error) override;
|
||||
std::string describe() const override;
|
||||
bool armed() const override;
|
||||
EnvRouteSpec defaultRoute() const override;
|
||||
bool appliesCommand() const override;
|
||||
EnvNeeds needs() const override;
|
||||
void reset() override;
|
||||
void onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route) override;
|
||||
void update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v) override;
|
||||
|
||||
private:
|
||||
EnvMonitorConfig::Contact config_;
|
||||
|
||||
int contact_streak_ = 0;
|
||||
int release_streak_ = 0; ///< cycle liên tiếp không "sắp chạm" trong khi đang phanh.
|
||||
bool braking_ = false;
|
||||
bool contact_close_ = false; ///< tiếp xúc trong clean_start_margin (bất kể tốc độ).
|
||||
robot::Time close_since_;
|
||||
bool contact_fired_ = false;
|
||||
bool detour_from_contact_ = false; ///< detour gần nhất là do cờ collision; mốc quãng đường ở dưới.
|
||||
double detour_mark_travel_ = 0.0; ///< [m]
|
||||
bool standdown_ = false; ///< đang đứng ra (xem Contact::standdown_min_travel).
|
||||
double standdown_mark_travel_ = 0.0; ///< [m]
|
||||
int standdown_clean_streak_ = 0; ///< cycle quỹ đạo sạch liên tiếp trong khi đứng ra.
|
||||
};
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
#endif // ENV_MONITOR_CORE_CONTACT_DETECTOR_H_
|
||||
410
plugins/stall_detector.cpp
Normal file
410
plugins/stall_detector.cpp
Normal file
@@ -0,0 +1,410 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — kStall (xem stall_detector.h).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include "stall_detector.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
|
||||
#include <env_monitor_core/env_detector_abi.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
EnvDetector::Ptr StallDetector::create()
|
||||
{
|
||||
return std::make_shared<StallDetector>();
|
||||
}
|
||||
|
||||
bool StallDetector::initialize(const std::string& name, robot::NodeHandle& nh, std::string& error)
|
||||
{
|
||||
(void)name;
|
||||
readStall(nh, config_);
|
||||
return validateStall(config_, error);
|
||||
}
|
||||
|
||||
std::string StallDetector::describe() const
|
||||
{
|
||||
return describeStall(config_);
|
||||
}
|
||||
|
||||
EnvRouteSpec StallDetector::defaultRoute() const
|
||||
{
|
||||
// Bản một khối: kStall đi route `oscillation`, cạn route là ABORT chặng (trigger gốc).
|
||||
EnvRouteSpec spec;
|
||||
spec.route = "oscillation";
|
||||
spec.lock_on_exhausted = false;
|
||||
return spec;
|
||||
}
|
||||
|
||||
bool StallDetector::armed() const
|
||||
{
|
||||
return config_.action == "recover";
|
||||
}
|
||||
|
||||
EnvNeeds StallDetector::needs() const
|
||||
{
|
||||
EnvNeeds n;
|
||||
n.geometry = config_.enabled;
|
||||
// Cửa sổ vị trí dài nhất: cú nhảy pose xoá cửa sổ tối đa một lần mỗi chừng này (kể cả khi stall tắt, như bản cũ).
|
||||
n.position_window_s = std::max({ config_.idle_window_s, config_.confine_window_s, config_.disp_window_s });
|
||||
return n;
|
||||
}
|
||||
|
||||
void StallDetector::reset()
|
||||
{
|
||||
clearWindow();
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
slip_seen_ = false;
|
||||
has_stall_backoff_ = false;
|
||||
has_prev_heavy_ = false;
|
||||
clearPosWindow();
|
||||
}
|
||||
|
||||
void StallDetector::onPlanApplied(const EnvShared& shared)
|
||||
{
|
||||
(void)shared;
|
||||
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;
|
||||
}
|
||||
|
||||
void StallDetector::onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route)
|
||||
{
|
||||
(void)own_route;
|
||||
if (outcome == EnvRecoveryOutcome::kFailed)
|
||||
{
|
||||
has_stall_backoff_ = true;
|
||||
stall_backoff_until_ = shared.now + robot::Duration(config_.retry_backoff);
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
|
||||
void StallDetector::clearWindow()
|
||||
{
|
||||
ring_head_ = 0;
|
||||
ring_count_ = 0;
|
||||
}
|
||||
|
||||
void StallDetector::clearPosWindow()
|
||||
{
|
||||
pos_head_ = 0;
|
||||
pos_count_ = 0;
|
||||
wandering_ = false;
|
||||
idle_ = false;
|
||||
confined_ = false;
|
||||
region_radius_ = std::numeric_limits<double>::quiet_NaN();
|
||||
net_disp_ = std::numeric_limits<double>::quiet_NaN();
|
||||
has_eff_ok_ = false;
|
||||
has_eff_low_ = false;
|
||||
}
|
||||
|
||||
bool StallDetector::progressProven(const robot::Time& now) const
|
||||
{
|
||||
const EnvMonitorConfig::Stall& c = config_;
|
||||
if (!has_eff_ok_ || (now - eff_ok_t_).toSec() > c.window_s)
|
||||
{
|
||||
return false; // không có bằng chứng tiến độ còn mới: cổng được nổ như cũ
|
||||
}
|
||||
return !has_eff_low_ || (now - eff_low_t_).toSec() > c.confine_window_s;
|
||||
}
|
||||
|
||||
bool StallDetector::oldestPos(const robot::Time& now, double window_s, PosSample& out) const
|
||||
{
|
||||
// Mẫu MỚI NHẤT đã đủ tuổi 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() >= window_s)
|
||||
{
|
||||
out = p;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool StallDetector::oldestInWindow(const robot::Time& now, double cmd_accum, 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_.window_s;
|
||||
const bool far_enough = cmd_accum - s.cmd >= config_.window_m;
|
||||
if (old_enough || far_enough)
|
||||
{
|
||||
out = s;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void StallDetector::update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v)
|
||||
{
|
||||
const EnvSample& s = frame.sample;
|
||||
const EnvShared& sh = frame.shared;
|
||||
if (sh.pose_jump_restart)
|
||||
{
|
||||
// Host vừa nhận ra pose bị đặt lại (xem EnvMonitor::update): mẫu vị trí và cost_to_go hai bên cú dời
|
||||
// không cùng hệ quy chiếu — đo lại từ đầu, kết luận kẹt cũ không còn cơ sở.
|
||||
clearWindow();
|
||||
clearPosWindow();
|
||||
has_prev_heavy_ = false;
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
}
|
||||
if (!sh.measurable)
|
||||
{
|
||||
// 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;
|
||||
return;
|
||||
}
|
||||
const EnvMonitorConfig::Stall& c = config_;
|
||||
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, sh.cmd_accum };
|
||||
pos_head_ = (pos_head_ + 1) % kPosRing;
|
||||
pos_count_ = std::min(pos_count_ + 1, kPosRing);
|
||||
PosSample old;
|
||||
if (oldestPos(s.now, c.disp_window_s, old))
|
||||
{
|
||||
net_disp_ = std::hypot(s.robot_x - old.x, s.robot_y - old.y);
|
||||
wandering_ = (sh.cmd_accum - old.cmd >= c.disp_min_commanded) && net_disp_ < c.disp_min;
|
||||
}
|
||||
else
|
||||
{
|
||||
net_disp_ = std::numeric_limits<double>::quiet_NaN();
|
||||
wandering_ = false;
|
||||
}
|
||||
// Cổng đứng yên: không cần lệnh đủ — PRIEST bò 0,05 m/s tại chỗ 30 s cũng là kẹt.
|
||||
idle_ = false;
|
||||
PosSample older;
|
||||
if (c.idle_window_s > 0.0 && c.disp_min > 0.0 && oldestPos(s.now, c.idle_window_s, older))
|
||||
{
|
||||
idle_ = std::hypot(s.robot_x - older.x, s.robot_y - older.y) < c.disp_min;
|
||||
}
|
||||
// Cổng giam vùng: bán kính của tập vị trí trong confine_window_s quanh tâm của chúng, so với lệnh tích luỹ.
|
||||
confined_ = false;
|
||||
region_radius_ = std::numeric_limits<double>::quiet_NaN();
|
||||
if (c.confine_radius > 0.0 && c.disp_min > 0.0)
|
||||
{
|
||||
double sx = 0.0;
|
||||
double sy = 0.0;
|
||||
std::size_t n = 0;
|
||||
double oldest_cmd = sh.cmd_accum;
|
||||
double oldest_age = 0.0;
|
||||
for (std::size_t k = 1; k <= pos_count_; ++k)
|
||||
{
|
||||
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
|
||||
const double age = (s.now - p.t).toSec();
|
||||
if (age > c.confine_window_s)
|
||||
{
|
||||
break;
|
||||
}
|
||||
sx += p.x;
|
||||
sy += p.y;
|
||||
++n;
|
||||
oldest_cmd = p.cmd;
|
||||
oldest_age = age;
|
||||
}
|
||||
if (n >= 2 && oldest_age >= c.confine_window_s - 0.5)
|
||||
{
|
||||
const double cx = sx / static_cast<double>(n);
|
||||
const double cy = sy / static_cast<double>(n);
|
||||
double radius = 0.0;
|
||||
for (std::size_t k = 1; k <= n; ++k)
|
||||
{
|
||||
const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing];
|
||||
radius = std::max(radius, std::hypot(p.x - cx, p.y - cy));
|
||||
}
|
||||
region_radius_ = radius;
|
||||
const double cmd = sh.cmd_accum - oldest_cmd;
|
||||
confined_ = radius < c.confine_radius &&
|
||||
cmd >= c.confine_cmd_factor * std::max(2.0 * radius, c.disp_min);
|
||||
}
|
||||
}
|
||||
}
|
||||
v.net_disp = net_disp_;
|
||||
v.wandering = wandering_;
|
||||
v.idle = idle_;
|
||||
v.confined = confined_;
|
||||
v.region_radius = region_radius_;
|
||||
|
||||
// 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 chuyển động và độ dời pose bị loại từ mẫu nặng trước. Cú nhảy pose lặp
|
||||
// không xoá cửa sổ, nên cost đi theo nó cũng không phải một cú nhảy do mặt nạ free; giữ lại để đo eff.
|
||||
if (c.jump_reject > 0.0 && has_prev_heavy_ &&
|
||||
std::fabs(s.cost_to_go - prev_heavy_cost_) > c.jump_reject + (sh.travel_total - prev_heavy_travel_) +
|
||||
(sh.jump_dist_total - prev_heavy_jump_dist_))
|
||||
{
|
||||
clearWindow();
|
||||
stall_seen_ = false;
|
||||
stall_fired_ = false;
|
||||
has_eff_low_ = true;
|
||||
eff_low_t_ = s.now;
|
||||
v.cost_jump = true;
|
||||
}
|
||||
has_prev_heavy_ = true;
|
||||
prev_heavy_cost_ = s.cost_to_go;
|
||||
prev_heavy_travel_ = sh.travel_total;
|
||||
prev_heavy_jump_dist_ = sh.jump_dist_total;
|
||||
ring_[ring_head_] = HeavySample{ s.now, s.cost_to_go, sh.cmd_accum };
|
||||
ring_head_ = (ring_head_ + 1) % kRing;
|
||||
ring_count_ = std::min(ring_count_ + 1, kRing);
|
||||
|
||||
HeavySample old;
|
||||
if (oldestInWindow(s.now, sh.cmd_accum, old))
|
||||
{
|
||||
const double cmd = sh.cmd_accum - old.cmd;
|
||||
v.cmd_window = cmd;
|
||||
if (cmd >= c.min_commanded)
|
||||
{
|
||||
v.eff_geo = (old.cost - s.cost_to_go) / cmd;
|
||||
}
|
||||
}
|
||||
// Lịch sử cho progressProven(): chỉ eff đo được mới là bằng chứng, theo cả hai chiều.
|
||||
if (!std::isnan(v.eff_geo))
|
||||
{
|
||||
if (v.eff_geo >= c.eff_off)
|
||||
{
|
||||
has_eff_ok_ = true;
|
||||
eff_ok_t_ = s.now;
|
||||
}
|
||||
else
|
||||
{
|
||||
has_eff_low_ = true;
|
||||
eff_low_t_ = s.now;
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool progress_proven = progressProven(s.now);
|
||||
v.progress_proven = progress_proven;
|
||||
v.confined_vetoed = confined_ && c.progress_veto && progress_proven;
|
||||
|
||||
// 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 = sh.in_grace;
|
||||
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;
|
||||
out.event = slipping ? "stall: wheels slip against the command" : "stall: cost_to_go not decreasing";
|
||||
}
|
||||
}
|
||||
else if (cleared)
|
||||
{
|
||||
if (stall_fired_)
|
||||
{
|
||||
out.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.
|
||||
// Đứng yên suốt idle_window_s, hoặc đi nhiều mà bị giam trong vùng nhỏ suốt confine_window_s, là kẹt kể cả
|
||||
// khi geodesic không đo được hoặc đang lật dấu. Chỉ cổng giam vùng bị phủ quyết khi có bằng chứng tiến độ;
|
||||
// cổng đứng yên vẫn hoạt động vì cost_to_go có thể đổi do hình học costmap.
|
||||
if ((idle_ || (confined_ && !(c.progress_veto && progress_proven))) && !stall_fired_)
|
||||
{
|
||||
stall_fired_ = true;
|
||||
stall_seen_ = true;
|
||||
stall_since_ = s.now;
|
||||
out.event = idle_ ? "stall: no net displacement for the idle window"
|
||||
: "stall: confined to a small region while commanded";
|
||||
}
|
||||
|
||||
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 (sh.has_goal && sh.cmd_accum - sh.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_ && !idle_ && !confined_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
}
|
||||
else if (sh.replan_muted)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
if (has_stall_backoff_ && s.now < stall_backoff_until_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
v.stall_muted = muted;
|
||||
v.no_progress = !muted && c.action == "recover";
|
||||
out.fired = v.no_progress;
|
||||
}
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
ENV_MONITOR_CORE_EXPORT_DETECTOR(env_monitor_core::StallDetector::create, StallDetector)
|
||||
107
plugins/stall_detector.h
Normal file
107
plugins/stall_detector.h
Normal file
@@ -0,0 +1,107 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — kStall: "planner đòi đi mà robot không tiến". Cờ `no_progress`.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_STALL_DETECTOR_H_
|
||||
#define ENV_MONITOR_CORE_STALL_DETECTOR_H_
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/time.h>
|
||||
|
||||
#include <env_monitor_core/env_detector.h>
|
||||
#include <env_monitor_core/env_monitor_config.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
class StallDetector final : public EnvDetector
|
||||
{
|
||||
public:
|
||||
/// Factory exported to boost::dll (symbol `StallDetector`).
|
||||
static EnvDetector::Ptr create();
|
||||
|
||||
bool initialize(const std::string& name, robot::NodeHandle& nh, std::string& error) override;
|
||||
std::string describe() const override;
|
||||
bool armed() const override;
|
||||
EnvRouteSpec defaultRoute() const override;
|
||||
EnvNeeds needs() const override;
|
||||
void reset() override;
|
||||
void onPlanApplied(const EnvShared& shared) override;
|
||||
void onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route) override;
|
||||
void update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v) override;
|
||||
|
||||
private:
|
||||
struct HeavySample
|
||||
{
|
||||
robot::Time t;
|
||||
double cost = 0.0; ///< [m]
|
||||
double cmd = 0.0; ///< [m] cmd_accum_ lúc lấy mẫu.
|
||||
};
|
||||
/// 64 mẫu x 0,2 s = 12,8 s lịch sử, dư cho window_s 4 s kể cả khi nhịp nặng chậm lại.
|
||||
static constexpr std::size_t kRing = 64;
|
||||
struct PosSample
|
||||
{
|
||||
robot::Time t;
|
||||
double x = 0.0;
|
||||
double y = 0.0;
|
||||
double cmd = 0.0; ///< [m] cmd_accum_ lúc lấy mẫu.
|
||||
};
|
||||
/// 128 mẫu x 0,2 s = 25,6 s, dư cho disp_window_s 12 s.
|
||||
static constexpr std::size_t kPosRing = 192; ///< 192 x 0,2 s = 38 s, đủ idle_window_s 25 s.
|
||||
bool oldestPos(const robot::Time& now, double window_s, PosSample& out) const;
|
||||
|
||||
void clearWindow();
|
||||
void clearPosWindow();
|
||||
bool oldestInWindow(const robot::Time& now, double cmd_accum, HeavySample& out) const;
|
||||
/// Tiến độ đã chứng minh: có eff >= eff_off trong window_s gần nhất và không có eff < eff_off nào trong
|
||||
/// confine_window_s gần nhất (xem Stall::confine_window_s).
|
||||
bool progressProven(const robot::Time& now) const;
|
||||
|
||||
EnvMonitorConfig::Stall config_;
|
||||
|
||||
// Cửa sổ mẫu nặng
|
||||
std::array<HeavySample, kRing> ring_{};
|
||||
std::size_t ring_head_ = 0;
|
||||
std::size_t ring_count_ = 0;
|
||||
std::array<PosSample, kPosRing> pos_ring_{};
|
||||
std::size_t pos_head_ = 0;
|
||||
std::size_t pos_count_ = 0;
|
||||
bool wandering_ = false;
|
||||
bool idle_ = false; ///< cổng đứng yên đang mở (xem Stall::idle_window_s).
|
||||
bool confined_ = false; ///< cổng giam vùng đang mở (xem Stall::confine_radius).
|
||||
double region_radius_ = std::numeric_limits<double>::quiet_NaN();
|
||||
double net_disp_ = std::numeric_limits<double>::quiet_NaN();
|
||||
// Lịch sử eff cho progressProven(): mốc thời gian của mẫu eff tốt/thấp gần nhất. Xoá cùng cửa sổ vị trí.
|
||||
bool has_eff_ok_ = false;
|
||||
robot::Time eff_ok_t_;
|
||||
bool has_eff_low_ = false;
|
||||
robot::Time eff_low_t_;
|
||||
|
||||
// kStall
|
||||
bool stall_seen_ = false;
|
||||
robot::Time stall_since_;
|
||||
bool stall_fired_ = false;
|
||||
bool slip_seen_ = false;
|
||||
robot::Time slip_since_;
|
||||
bool has_stall_backoff_ = false;
|
||||
robot::Time stall_backoff_until_;
|
||||
|
||||
bool has_prev_heavy_ = false; ///< mẫu nặng trước cho bộ lọc nhảy cost_to_go.
|
||||
double prev_heavy_cost_ = 0.0;
|
||||
double prev_heavy_travel_ = 0.0;
|
||||
double prev_heavy_jump_dist_ = 0.0;
|
||||
};
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
#endif // ENV_MONITOR_CORE_STALL_DETECTOR_H_
|
||||
172
plugins/unreachable_detector.cpp
Normal file
172
plugins/unreachable_detector.cpp
Normal file
@@ -0,0 +1,172 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — kUnreachable (xem unreachable_detector.h).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include "unreachable_detector.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
|
||||
#include <env_monitor_core/env_detector_abi.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
EnvDetector::Ptr UnreachableDetector::create()
|
||||
{
|
||||
return std::make_shared<UnreachableDetector>();
|
||||
}
|
||||
|
||||
bool UnreachableDetector::initialize(const std::string& name, robot::NodeHandle& nh, std::string& error)
|
||||
{
|
||||
(void)name;
|
||||
readUnreachable(nh, config_);
|
||||
return validateUnreachable(config_, error);
|
||||
}
|
||||
|
||||
std::string UnreachableDetector::describe() const
|
||||
{
|
||||
return describeUnreachable(config_);
|
||||
}
|
||||
|
||||
EnvRouteSpec UnreachableDetector::defaultRoute() const
|
||||
{
|
||||
// Bản một khối: kUnreachable đi route `path_blocked`, cạn route là KHOÁ (dự báo, plan vẫn hợp lệ).
|
||||
EnvRouteSpec spec;
|
||||
spec.route = "path_blocked";
|
||||
spec.lock_on_exhausted = true;
|
||||
return spec;
|
||||
}
|
||||
|
||||
bool UnreachableDetector::armed() const
|
||||
{
|
||||
return config_.action == "recover";
|
||||
}
|
||||
|
||||
EnvNeeds UnreachableDetector::needs() const
|
||||
{
|
||||
EnvNeeds n;
|
||||
n.geometry = config_.enabled;
|
||||
return n;
|
||||
}
|
||||
|
||||
void UnreachableDetector::reset()
|
||||
{
|
||||
baseline_pending_ = true;
|
||||
baseline_unreachable_ = false;
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
has_unreach_backoff_ = false;
|
||||
}
|
||||
|
||||
void UnreachableDetector::onPlanApplied(const EnvShared& shared)
|
||||
{
|
||||
(void)shared;
|
||||
// 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 UnreachableDetector::onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route)
|
||||
{
|
||||
(void)own_route;
|
||||
if (outcome == EnvRecoveryOutcome::kFailed)
|
||||
{
|
||||
has_unreach_backoff_ = true;
|
||||
unreach_backoff_until_ = shared.now + robot::Duration(config_.retry_backoff);
|
||||
}
|
||||
// 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ị.
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
}
|
||||
|
||||
void UnreachableDetector::update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v)
|
||||
{
|
||||
const EnvSample& s = frame.sample;
|
||||
const EnvShared& sh = frame.shared;
|
||||
if (!sh.measurable)
|
||||
{
|
||||
// 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.
|
||||
unreach_seen_ = false;
|
||||
unreach_fired_ = false;
|
||||
return;
|
||||
}
|
||||
const EnvMonitorConfig::Unreachable& c = config_;
|
||||
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_)
|
||||
{
|
||||
out.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 = sh.in_grace;
|
||||
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;
|
||||
out.event = "unreachable: no path to the plan exit inside the window";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
v.unreachable_detected = unreach_fired_;
|
||||
if (!unreach_fired_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
bool muted = false;
|
||||
if (sh.replan_muted)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
if (has_unreach_backoff_ && s.now < unreach_backoff_until_)
|
||||
{
|
||||
muted = true;
|
||||
}
|
||||
v.unreachable_muted = muted;
|
||||
v.path_blocked = !muted && c.action == "recover";
|
||||
out.fired = v.path_blocked;
|
||||
}
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
ENV_MONITOR_CORE_EXPORT_DETECTOR(env_monitor_core::UnreachableDetector::create, UnreachableDetector)
|
||||
53
plugins/unreachable_detector.h
Normal file
53
plugins/unreachable_detector.h
Normal file
@@ -0,0 +1,53 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — kUnreachable: không còn đường trong cửa sổ tới điểm thoát. Cờ `path_blocked`.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_UNREACHABLE_DETECTOR_H_
|
||||
#define ENV_MONITOR_CORE_UNREACHABLE_DETECTOR_H_
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/time.h>
|
||||
|
||||
#include <env_monitor_core/env_detector.h>
|
||||
#include <env_monitor_core/env_monitor_config.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
|
||||
class UnreachableDetector final : public EnvDetector
|
||||
{
|
||||
public:
|
||||
/// Factory exported to boost::dll (symbol `UnreachableDetector`).
|
||||
static EnvDetector::Ptr create();
|
||||
|
||||
bool initialize(const std::string& name, robot::NodeHandle& nh, std::string& error) override;
|
||||
std::string describe() const override;
|
||||
bool armed() const override;
|
||||
EnvRouteSpec defaultRoute() const override;
|
||||
EnvNeeds needs() const override;
|
||||
void reset() override;
|
||||
void onPlanApplied(const EnvShared& shared) override;
|
||||
void onRecoveryFinished(const EnvShared& shared, EnvRecoveryOutcome outcome, bool own_route) override;
|
||||
void update(const EnvFrame& frame, EnvDetectorOutput& out, EnvVerdict& v) override;
|
||||
|
||||
private:
|
||||
EnvMonitorConfig::Unreachable config_;
|
||||
|
||||
bool baseline_pending_ = true; ///< chưa có mẫu kết luận nào từ plan hiện tại.
|
||||
bool baseline_unreachable_ = false; ///< plan đã không liên thông ngay từ lúc nhận (R2: không cãi SBPL).
|
||||
bool unreach_seen_ = false;
|
||||
robot::Time unreach_since_;
|
||||
bool unreach_fired_ = false;
|
||||
bool has_unreach_backoff_ = false;
|
||||
robot::Time unreach_backoff_until_;
|
||||
};
|
||||
|
||||
} // namespace env_monitor_core
|
||||
|
||||
#endif // ENV_MONITOR_CORE_UNREACHABLE_DETECTOR_H_
|
||||
474
src/env_monitor.cpp
Normal file
474
src/env_monitor.cpp
Normal file
@@ -0,0 +1,474 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — cài đặt lõi EnvMonitor (xem header).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <env_monitor_core/env_monitor.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
#include <boost/dll/import.hpp>
|
||||
#include <boost/system/system_error.hpp>
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <robot/plugin_loader_helper.h>
|
||||
#include <robot/robot.h>
|
||||
|
||||
#include <env_monitor_core/env_detector_abi.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
/// Thiếu khoá `detectors`: đúng ba detector của bản một khối, đúng thứ tự chạy của nó (thứ tự ghi `event`).
|
||||
const std::vector<std::pair<std::string, std::string>> kDefaultDetectors = {
|
||||
{ "contact", "ContactDetector" },
|
||||
{ "stall", "StallDetector" },
|
||||
{ "unreachable", "UnreachableDetector" },
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// ----------------------------------------------------------------------------------------- lifecycle
|
||||
|
||||
EnvMonitor::~EnvMonitor()
|
||||
{
|
||||
clear();
|
||||
}
|
||||
|
||||
void EnvMonitor::clear()
|
||||
{
|
||||
// Detector phải chết TRƯỚC factory: factory giữ .so còn nạp.
|
||||
detectors_.clear();
|
||||
factories_.clear();
|
||||
loaded_.clear();
|
||||
}
|
||||
|
||||
bool EnvMonitor::initialize(robot::NodeHandle& nh, std::string& error)
|
||||
{
|
||||
error.clear();
|
||||
configured_ = false;
|
||||
clear();
|
||||
config_ = EnvMonitorConfig();
|
||||
robot::NodeHandle env_nh(nh, "env_monitor");
|
||||
readHost(env_nh, config_);
|
||||
restart_cooldown_ = 0.0;
|
||||
if (config_.enabled)
|
||||
{
|
||||
if (!validateHost(config_, error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
std::vector<std::pair<std::string, std::string>> list;
|
||||
if (!env_nh.hasParam("detectors"))
|
||||
{
|
||||
robot::log_info("[env_monitor_core] EnvMonitor: no 'env_monitor/detectors' list — loading the built-in "
|
||||
"contact, stall, unreachable.");
|
||||
list = kDefaultDetectors;
|
||||
}
|
||||
else
|
||||
{
|
||||
const YAML::Node entries = env_nh.getParamValue("detectors");
|
||||
if (!entries.IsSequence())
|
||||
{
|
||||
error = "env_monitor/detectors must be a list of {name, type}";
|
||||
return false;
|
||||
}
|
||||
for (std::size_t i = 0; i < entries.size(); ++i)
|
||||
{
|
||||
const YAML::Node& entry = entries[i];
|
||||
if (!entry.IsMap() || !entry["type"])
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: env_monitor/detectors[%zu] has no 'type' — skipped.", i);
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
const std::string type = entry["type"].as<std::string>();
|
||||
list.emplace_back(entry["name"] ? entry["name"].as<std::string>() : type, type);
|
||||
}
|
||||
catch (const YAML::Exception& ex)
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: env_monitor/detectors[%zu] could not be read: %s — "
|
||||
"skipped.", i, ex.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto& entry : list)
|
||||
{
|
||||
if (!load(entry.first, entry.second, nh, env_nh, error) && !error.empty())
|
||||
{
|
||||
clear();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (const auto& d : detectors_)
|
||||
{
|
||||
restart_cooldown_ = std::max(restart_cooldown_, d->needs().position_window_s);
|
||||
}
|
||||
}
|
||||
configured_ = true;
|
||||
reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EnvMonitor::load(const std::string& name, const std::string& type, robot::NodeHandle& nh,
|
||||
robot::NodeHandle& env_nh, std::string& error)
|
||||
{
|
||||
robot::PluginLoaderHelper loader(nh);
|
||||
const std::string library_path = loader.findLibraryPath(type);
|
||||
if (library_path.empty())
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: no library found for '%s' (detector '%s') — check the key "
|
||||
"'%s/library_path' in the YAML and that the .so file exists. Running WITHOUT this detector.",
|
||||
type.c_str(), name.c_str(), type.c_str());
|
||||
return false;
|
||||
}
|
||||
// ABI trước factory: plugin build với header cũ gọi nhầm slot vtable — crash lúc chạy, không compile error nào bắt.
|
||||
try
|
||||
{
|
||||
const auto abi = boost::dll::import_alias<int()>(library_path, type + "_abi",
|
||||
boost::dll::load_mode::append_decorations);
|
||||
const int plugin_abi = abi();
|
||||
if (plugin_abi != kEnvDetectorAbiVersion)
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: '%s' from '%s' was built for ABI %d but this runtime is ABI "
|
||||
"%d — refusing to load it. Rebuild the plugin against the current env_monitor_core headers.",
|
||||
type.c_str(), library_path.c_str(), plugin_abi, kEnvDetectorAbiVersion);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: '%s' from '%s' exports no '%s_abi' symbol (not built with "
|
||||
"ENV_MONITOR_CORE_EXPORT_DETECTOR) — refusing to load it: %s",
|
||||
type.c_str(), library_path.c_str(), type.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
std::function<EnvDetector::Ptr()> factory;
|
||||
try
|
||||
{
|
||||
factory = boost::dll::import_alias<EnvDetector::Ptr()>(library_path, type, boost::dll::load_mode::append_decorations);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: could not load symbol '%s' from '%s': %s", type.c_str(),
|
||||
library_path.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
EnvDetector::Ptr detector;
|
||||
try
|
||||
{
|
||||
detector = factory();
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: factory of '%s' threw: %s", type.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
if (!detector)
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: factory of '%s' returned null.", type.c_str());
|
||||
return false;
|
||||
}
|
||||
if (detectors_.size() >= kMaxDetectors)
|
||||
{
|
||||
robot::log_error("[env_monitor_core] EnvMonitor: more than %zu detectors — '%s' is NOT loaded (fired_mask is 32 bits).",
|
||||
kMaxDetectors, name.c_str());
|
||||
return false;
|
||||
}
|
||||
robot::NodeHandle detector_nh(env_nh, name);
|
||||
if (!detector->initialize(name, detector_nh, error))
|
||||
{
|
||||
if (error.empty())
|
||||
{
|
||||
error = "env_monitor/" + name + ": initialize() failed";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// Route: khoá chung của mọi detector, đọc ở host; thiếu khoá thì lấy mặc định của plugin (không cảnh báo).
|
||||
EnvRouteSpec route = detector->defaultRoute();
|
||||
std::string mode = route.sequence ? "sequence" : "step";
|
||||
std::string exhausted = route.lock_on_exhausted ? "lock" : "abort";
|
||||
detector_nh.param("route", route.route, route.route);
|
||||
detector_nh.param("route_mode", mode, mode);
|
||||
detector_nh.param("on_exhausted", exhausted, exhausted);
|
||||
if (route.route.empty() || (mode != "step" && mode != "sequence") || (exhausted != "lock" && exhausted != "abort"))
|
||||
{
|
||||
error = "env_monitor/" + name + ": route must be a route name, route_mode \"step\" or \"sequence\", on_exhausted "
|
||||
"\"lock\" or \"abort\"";
|
||||
return false;
|
||||
}
|
||||
route.sequence = mode == "sequence";
|
||||
route.lock_on_exhausted = exhausted == "lock";
|
||||
detectors_.push_back(std::move(detector));
|
||||
factories_.push_back(std::move(factory));
|
||||
loaded_.push_back(EnvDetectorInfo{ name, type, library_path, route });
|
||||
robot::log_info("[env_monitor_core] EnvMonitor: loaded detector '%s' (%s from %s).", name.c_str(), type.c_str(),
|
||||
library_path.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string EnvMonitor::describe() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "env_monitor " << (config_.enabled ? "ON" : "OFF") << " (grace " << config_.grace_after_new_plan
|
||||
<< " s, pose_jump>" << config_.pose_jump_reject << " m):\n";
|
||||
out << " detectors :";
|
||||
if (loaded_.empty())
|
||||
{
|
||||
out << " none";
|
||||
}
|
||||
for (const EnvDetectorInfo& l : loaded_)
|
||||
{
|
||||
out << " " << l.name << "=" << l.type << " (" << l.library << ")";
|
||||
}
|
||||
out << "\n";
|
||||
for (std::size_t i = 0; i < detectors_.size(); ++i)
|
||||
{
|
||||
const EnvRouteSpec& r = loaded_[i].route;
|
||||
out << " " << std::left << std::setw(12) << loaded_[i].name << ": " << detectors_[i]->describe() << " | route="
|
||||
<< r.route << " " << (r.sequence ? "sequence" : "step") << " on_exhausted="
|
||||
<< (r.lock_on_exhausted ? "lock" : "abort") << "\n";
|
||||
}
|
||||
out << " replan : " << describeReplan(config_.replan);
|
||||
return out.str();
|
||||
}
|
||||
|
||||
bool EnvMonitor::armed() const
|
||||
{
|
||||
return std::any_of(detectors_.begin(), detectors_.end(), [](const EnvDetector::Ptr& d) { return d->armed(); });
|
||||
}
|
||||
|
||||
EnvNeeds EnvMonitor::needs() const
|
||||
{
|
||||
EnvNeeds all;
|
||||
for (const auto& d : detectors_)
|
||||
{
|
||||
const EnvNeeds n = d->needs();
|
||||
all.geometry = all.geometry || n.geometry;
|
||||
all.sweep = all.sweep || n.sweep;
|
||||
all.position_window_s = std::max(all.position_window_s, n.position_window_s);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
void EnvMonitor::reset()
|
||||
{
|
||||
cmd_accum_ = 0.0;
|
||||
travel_total_ = 0.0;
|
||||
jump_dist_total_ = 0.0;
|
||||
has_last_pose_ = false;
|
||||
v_gap_max_ = 0.0;
|
||||
has_pose_jump_restart_ = false;
|
||||
has_goal_ = false;
|
||||
cmd_at_goal_ = 0.0;
|
||||
has_plan_time_ = false;
|
||||
has_replan_mark_ = false;
|
||||
replan_mark_travel_ = 0.0;
|
||||
budget_travel_ = config_.replan.min_travel;
|
||||
has_prev_replan_ = false;
|
||||
prev_replan_travel_ = 0.0;
|
||||
for (const auto& d : detectors_)
|
||||
{
|
||||
d->reset();
|
||||
}
|
||||
}
|
||||
|
||||
void EnvMonitor::onGoalAccepted(const robot::Time& now)
|
||||
{
|
||||
(void)now;
|
||||
const double cmd = cmd_accum_;
|
||||
const double travel = travel_total_;
|
||||
const double jump_dist = jump_dist_total_;
|
||||
const bool had_pose = has_last_pose_;
|
||||
const double lx = last_x_;
|
||||
const double ly = last_y_;
|
||||
const robot::Time pose_t = last_pose_t_;
|
||||
const double gap_v = v_gap_max_;
|
||||
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;
|
||||
jump_dist_total_ = jump_dist;
|
||||
has_last_pose_ = had_pose;
|
||||
last_x_ = lx;
|
||||
last_y_ = ly;
|
||||
last_pose_t_ = pose_t;
|
||||
v_gap_max_ = gap_v;
|
||||
has_goal_ = true;
|
||||
cmd_at_goal_ = cmd_accum_;
|
||||
}
|
||||
|
||||
void EnvMonitor::onPlanApplied(const robot::Time& now)
|
||||
{
|
||||
has_plan_time_ = true;
|
||||
plan_time_ = now;
|
||||
const EnvShared sh = shared(now);
|
||||
for (const auto& d : detectors_)
|
||||
{
|
||||
d->onPlanApplied(sh);
|
||||
}
|
||||
}
|
||||
|
||||
bool EnvMonitor::remove(const std::string& name)
|
||||
{
|
||||
for (std::size_t i = 0; i < loaded_.size(); ++i)
|
||||
{
|
||||
if (loaded_[i].name == name)
|
||||
{
|
||||
// Factory (thư viện) giữ lại: vô hại, và gỡ .so khi detector khác cùng thư viện còn sống là sai.
|
||||
detectors_.erase(detectors_.begin() + static_cast<std::ptrdiff_t>(i));
|
||||
loaded_.erase(loaded_.begin() + static_cast<std::ptrdiff_t>(i));
|
||||
restart_cooldown_ = needs().position_window_s;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void EnvMonitor::onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome,
|
||||
const std::string& source_detector)
|
||||
{
|
||||
if (outcome == EnvRecoveryOutcome::kSucceededWithPath)
|
||||
{
|
||||
// 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_;
|
||||
}
|
||||
const EnvShared sh = shared(now);
|
||||
for (std::size_t i = 0; i < detectors_.size(); ++i)
|
||||
{
|
||||
detectors_[i]->onRecoveryFinished(sh, outcome, !source_detector.empty() && loaded_[i].name == source_detector);
|
||||
}
|
||||
}
|
||||
|
||||
EnvShared EnvMonitor::shared(const robot::Time& now) const
|
||||
{
|
||||
EnvShared sh;
|
||||
sh.now = now;
|
||||
sh.cmd_accum = cmd_accum_;
|
||||
sh.travel_total = travel_total_;
|
||||
sh.jump_dist_total = jump_dist_total_;
|
||||
sh.has_goal = has_goal_;
|
||||
sh.cmd_at_goal = cmd_at_goal_;
|
||||
sh.in_grace = has_plan_time_ && (now - plan_time_).toSec() < config_.grace_after_new_plan;
|
||||
sh.replan_muted = has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_;
|
||||
return sh;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------- 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.v_cmd))
|
||||
{
|
||||
v_gap_max_ = std::max(v_gap_max_, std::fabs(s.v_cmd));
|
||||
}
|
||||
if (std::isfinite(s.v_meas))
|
||||
{
|
||||
v_gap_max_ = std::max(v_gap_max_, std::fabs(s.v_meas));
|
||||
}
|
||||
if (std::isfinite(s.robot_x) && std::isfinite(s.robot_y))
|
||||
{
|
||||
if (has_last_pose_)
|
||||
{
|
||||
const double step = std::hypot(s.robot_x - last_x_, s.robot_y - last_y_);
|
||||
// Khoảng giữa hai pose hợp lệ có thể gồm nhiều cycle thiếu pose.
|
||||
const double reach = v_gap_max_ * std::max(0.0, (s.now - last_pose_t_).toSec());
|
||||
if (config_.pose_jump_reject > 0.0 && step > config_.pose_jump_reject + reach)
|
||||
{
|
||||
v.pose_jump = true;
|
||||
v.pose_jump_dist = step;
|
||||
jump_dist_total_ += step;
|
||||
}
|
||||
else
|
||||
{
|
||||
travel_total_ += step;
|
||||
}
|
||||
}
|
||||
last_x_ = s.robot_x;
|
||||
last_y_ = s.robot_y;
|
||||
last_pose_t_ = s.now;
|
||||
v_gap_max_ = 0.0;
|
||||
has_last_pose_ = true;
|
||||
}
|
||||
const double restart_cooldown = restart_cooldown_;
|
||||
if (v.pose_jump && (!has_pose_jump_restart_ || (s.now - pose_jump_restart_t_).toSec() >= restart_cooldown))
|
||||
{
|
||||
// Pose bị đặt lại (relocalization): mẫu vị trí và cost_to_go hai bên cú dời không cùng hệ quy chiếu. Giữ chúng
|
||||
// thì quỹ đạo gấp lên chính nó (giam vùng / đứng yên / dịch chuyển nổ oan) và eff âm giả (sim 6/11 20:34).
|
||||
// Đo lại từ đầu; kết luận kẹt cũ cũng không còn cơ sở — cùng cách xử lý với cú nhảy cost_to_go.
|
||||
// Các detector giữ cửa sổ vị trí tự xoá chúng khi thấy EnvShared::pose_jump_restart.
|
||||
has_pose_jump_restart_ = true;
|
||||
pose_jump_restart_t_ = s.now;
|
||||
v.pose_jump_restart = true;
|
||||
}
|
||||
if (has_replan_mark_)
|
||||
{
|
||||
v.replan_budget_left = std::max(0.0, budget_travel_ - (travel_total_ - replan_mark_travel_));
|
||||
}
|
||||
|
||||
EnvFrame frame;
|
||||
frame.sample = s;
|
||||
frame.shared = shared(s.now);
|
||||
frame.shared.pose_jump_restart = v.pose_jump_restart;
|
||||
frame.shared.measurable = s.has_plan && s.costmap_current;
|
||||
for (std::size_t i = 0; i < detectors_.size(); ++i)
|
||||
{
|
||||
const EnvDetector::Ptr& d = detectors_[i];
|
||||
EnvDetectorOutput out;
|
||||
d->update(frame, out, v);
|
||||
if (out.fired)
|
||||
{
|
||||
v.fired_mask |= std::uint32_t{ 1 } << i;
|
||||
}
|
||||
v.brake = v.brake || out.brake;
|
||||
v.v_cap = std::min(v.v_cap, out.v_cap);
|
||||
if (d->appliesCommand())
|
||||
{
|
||||
v.brake_applied = v.brake_applied || out.brake;
|
||||
v.v_cap_applied = std::min(v.v_cap_applied, out.v_cap);
|
||||
}
|
||||
if (out.event[0] != '\0')
|
||||
{
|
||||
v.event = out.event; // thứ tự danh sách: detector sau ghi đè, như bản một khối
|
||||
}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
} // namespace env_monitor_core
|
||||
398
src/env_monitor_config.cpp
Normal file
398
src/env_monitor_config.cpp
Normal file
@@ -0,0 +1,398 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — đọc, kiểm tra và mô tả tham số EnvMonitor.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <env_monitor_core/env_monitor_config.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <sstream>
|
||||
|
||||
#include <robot/robot.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
// Khoá thiếu: giữ mặc định, cảnh báo một lần lúc boot (cùng hợp đồng với move_base2 trước khi tách gói).
|
||||
void readDouble(robot::NodeHandle& nh, const std::string& key, double& value)
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
robot::log_warning("[env_monitor_core] missing param '%s', using default %.4f", key.c_str(), value);
|
||||
return;
|
||||
}
|
||||
nh.param(key, value, value);
|
||||
}
|
||||
|
||||
void readInt(robot::NodeHandle& nh, const std::string& key, int& value)
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
robot::log_warning("[env_monitor_core] missing param '%s', using default %d", key.c_str(), value);
|
||||
return;
|
||||
}
|
||||
nh.param(key, value, value);
|
||||
}
|
||||
|
||||
void readBool(robot::NodeHandle& nh, const std::string& key, bool& value)
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
robot::log_warning("[env_monitor_core] missing param '%s', using default %s", key.c_str(),
|
||||
value ? "true" : "false");
|
||||
return;
|
||||
}
|
||||
nh.param(key, value, value);
|
||||
}
|
||||
|
||||
void readString(robot::NodeHandle& nh, const std::string& key, std::string& value)
|
||||
{
|
||||
if (!nh.hasParam(key))
|
||||
{
|
||||
robot::log_warning("[env_monitor_core] missing param '%s', using default '%s'", key.c_str(), value.c_str());
|
||||
return;
|
||||
}
|
||||
nh.param(key, value, value);
|
||||
}
|
||||
|
||||
/// Doubles as text with 17 digits: the value read back is bit-identical to the struct field.
|
||||
YAML::Node num(double d)
|
||||
{
|
||||
char buf[40];
|
||||
std::snprintf(buf, sizeof(buf), "%.17g", d);
|
||||
return YAML::Node(std::string(buf));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// --------------------------------------------------------------------------------------------- read
|
||||
|
||||
void readHost(robot::NodeHandle& env_nh, EnvMonitorConfig& m)
|
||||
{
|
||||
readBool(env_nh, "enabled", m.enabled);
|
||||
readDouble(env_nh, "grace_after_new_plan", m.grace_after_new_plan);
|
||||
readDouble(env_nh, "pose_jump_reject", m.pose_jump_reject);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
void readStall(robot::NodeHandle& stall_nh, EnvMonitorConfig::Stall& c)
|
||||
{
|
||||
readBool(stall_nh, "enabled", c.enabled);
|
||||
readString(stall_nh, "action", c.action);
|
||||
readDouble(stall_nh, "window_s", c.window_s);
|
||||
readDouble(stall_nh, "window_m", c.window_m);
|
||||
readDouble(stall_nh, "min_commanded", c.min_commanded);
|
||||
readDouble(stall_nh, "eff_on", c.eff_on);
|
||||
readDouble(stall_nh, "eff_off", c.eff_off);
|
||||
readDouble(stall_nh, "confirm", c.confirm);
|
||||
readDouble(stall_nh, "goal_zone", c.goal_zone);
|
||||
readDouble(stall_nh, "slip_on", c.slip_on);
|
||||
readDouble(stall_nh, "slip_time", c.slip_time);
|
||||
readDouble(stall_nh, "min_commanded_since_goal", c.min_commanded_since_goal);
|
||||
readDouble(stall_nh, "retry_backoff", c.retry_backoff);
|
||||
readDouble(stall_nh, "jump_reject", c.jump_reject);
|
||||
readDouble(stall_nh, "disp_window_s", c.disp_window_s);
|
||||
readDouble(stall_nh, "disp_min", c.disp_min);
|
||||
readDouble(stall_nh, "disp_min_commanded", c.disp_min_commanded);
|
||||
readDouble(stall_nh, "idle_window_s", c.idle_window_s);
|
||||
readDouble(stall_nh, "confine_window_s", c.confine_window_s);
|
||||
readDouble(stall_nh, "confine_radius", c.confine_radius);
|
||||
readDouble(stall_nh, "confine_cmd_factor", c.confine_cmd_factor);
|
||||
readBool(stall_nh, "progress_veto", c.progress_veto);
|
||||
}
|
||||
|
||||
void readUnreachable(robot::NodeHandle& unreach_nh, EnvMonitorConfig::Unreachable& c)
|
||||
{
|
||||
readBool(unreach_nh, "enabled", c.enabled);
|
||||
readString(unreach_nh, "action", c.action);
|
||||
readDouble(unreach_nh, "static_on", c.static_on);
|
||||
readDouble(unreach_nh, "clean_start_margin", c.clean_start_margin);
|
||||
readDouble(unreach_nh, "retry_backoff", c.retry_backoff);
|
||||
}
|
||||
|
||||
void readContact(robot::NodeHandle& contact_nh, EnvMonitorConfig::Contact& c)
|
||||
{
|
||||
// use_local_plan / local_plan_start_tol / lookahead cùng khối nhưng thuộc phần lấy mẫu của host (move_base2).
|
||||
readBool(contact_nh, "enabled", c.enabled);
|
||||
readString(contact_nh, "action", c.action);
|
||||
readBool(contact_nh, "apply_command", c.apply_command);
|
||||
readInt(contact_nh, "confirm_cycles", c.confirm_cycles);
|
||||
readDouble(contact_nh, "trigger_static_time", c.trigger_static_time);
|
||||
readDouble(contact_nh, "clean_start_margin", c.clean_start_margin);
|
||||
readDouble(contact_nh, "brake_decel", c.brake_decel);
|
||||
readDouble(contact_nh, "min_speed", c.min_speed);
|
||||
readDouble(contact_nh, "min_check_speed", c.min_check_speed);
|
||||
readDouble(contact_nh, "release_hysteresis", c.release_hysteresis);
|
||||
readInt(contact_nh, "release_confirm_cycles", c.release_confirm_cycles);
|
||||
readDouble(contact_nh, "envelope_margin", c.envelope_margin);
|
||||
readDouble(contact_nh, "standdown_min_travel", c.standdown_min_travel);
|
||||
readDouble(contact_nh, "standdown_travel", c.standdown_travel);
|
||||
readBool(contact_nh, "envelope", c.envelope);
|
||||
}
|
||||
|
||||
YAML::Node toYaml(const EnvMonitorConfig& m)
|
||||
{
|
||||
YAML::Node env;
|
||||
env["enabled"] = m.enabled;
|
||||
env["grace_after_new_plan"] = num(m.grace_after_new_plan);
|
||||
env["pose_jump_reject"] = num(m.pose_jump_reject);
|
||||
|
||||
YAML::Node s;
|
||||
s["enabled"] = m.stall.enabled;
|
||||
s["action"] = m.stall.action;
|
||||
s["window_s"] = num(m.stall.window_s);
|
||||
s["window_m"] = num(m.stall.window_m);
|
||||
s["min_commanded"] = num(m.stall.min_commanded);
|
||||
s["eff_on"] = num(m.stall.eff_on);
|
||||
s["eff_off"] = num(m.stall.eff_off);
|
||||
s["confirm"] = num(m.stall.confirm);
|
||||
s["goal_zone"] = num(m.stall.goal_zone);
|
||||
s["slip_on"] = num(m.stall.slip_on);
|
||||
s["slip_time"] = num(m.stall.slip_time);
|
||||
s["min_commanded_since_goal"] = num(m.stall.min_commanded_since_goal);
|
||||
s["retry_backoff"] = num(m.stall.retry_backoff);
|
||||
s["jump_reject"] = num(m.stall.jump_reject);
|
||||
s["disp_window_s"] = num(m.stall.disp_window_s);
|
||||
s["disp_min"] = num(m.stall.disp_min);
|
||||
s["disp_min_commanded"] = num(m.stall.disp_min_commanded);
|
||||
s["idle_window_s"] = num(m.stall.idle_window_s);
|
||||
s["confine_window_s"] = num(m.stall.confine_window_s);
|
||||
s["confine_radius"] = num(m.stall.confine_radius);
|
||||
s["confine_cmd_factor"] = num(m.stall.confine_cmd_factor);
|
||||
s["progress_veto"] = m.stall.progress_veto;
|
||||
env["stall"] = s;
|
||||
|
||||
YAML::Node u;
|
||||
u["enabled"] = m.unreachable.enabled;
|
||||
u["action"] = m.unreachable.action;
|
||||
u["static_on"] = num(m.unreachable.static_on);
|
||||
u["clean_start_margin"] = num(m.unreachable.clean_start_margin);
|
||||
u["retry_backoff"] = num(m.unreachable.retry_backoff);
|
||||
env["unreachable"] = u;
|
||||
|
||||
YAML::Node c;
|
||||
c["enabled"] = m.contact.enabled;
|
||||
c["action"] = m.contact.action;
|
||||
c["apply_command"] = m.contact.apply_command;
|
||||
c["confirm_cycles"] = m.contact.confirm_cycles;
|
||||
c["trigger_static_time"] = num(m.contact.trigger_static_time);
|
||||
c["clean_start_margin"] = num(m.contact.clean_start_margin);
|
||||
c["brake_decel"] = num(m.contact.brake_decel);
|
||||
c["min_speed"] = num(m.contact.min_speed);
|
||||
c["min_check_speed"] = num(m.contact.min_check_speed);
|
||||
c["release_hysteresis"] = num(m.contact.release_hysteresis);
|
||||
c["release_confirm_cycles"] = m.contact.release_confirm_cycles;
|
||||
c["envelope_margin"] = num(m.contact.envelope_margin);
|
||||
c["standdown_min_travel"] = num(m.contact.standdown_min_travel);
|
||||
c["standdown_travel"] = num(m.contact.standdown_travel);
|
||||
c["envelope"] = m.contact.envelope;
|
||||
env["contact"] = c;
|
||||
|
||||
YAML::Node r;
|
||||
r["min_travel"] = num(m.replan.min_travel);
|
||||
r["escalate_factor"] = num(m.replan.escalate_factor);
|
||||
r["escalate_window_m"] = num(m.replan.escalate_window_m);
|
||||
r["escalate_max"] = num(m.replan.escalate_max);
|
||||
env["replan_budget"] = r;
|
||||
return env;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- validate
|
||||
|
||||
bool validateHost(const EnvMonitorConfig& m, std::string& error)
|
||||
{
|
||||
if (!finiteNonNegative(m.grace_after_new_plan))
|
||||
{
|
||||
error = "env_monitor/grace_after_new_plan must be >= 0 [s]";
|
||||
return false;
|
||||
}
|
||||
if (!finiteNonNegative(m.pose_jump_reject))
|
||||
{
|
||||
error = "env_monitor/pose_jump_reject must be >= 0 [m] (0 = off)";
|
||||
return false;
|
||||
}
|
||||
const EnvMonitorConfig::ReplanBudget& replan = m.replan;
|
||||
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;
|
||||
}
|
||||
|
||||
bool validateStall(const EnvMonitorConfig::Stall& stall, std::string& error)
|
||||
{
|
||||
if (!validAction(stall.action))
|
||||
{
|
||||
error = "env_monitor/stall/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) ||
|
||||
!finiteNonNegative(stall.idle_window_s) || !finiteNonNegative(stall.confine_radius) ||
|
||||
!finitePositive(stall.confine_window_s) || !std::isfinite(stall.confine_cmd_factor) ||
|
||||
stall.confine_cmd_factor < 1.0)
|
||||
{
|
||||
error = "env_monitor/stall: confirm, goal_zone, slip_on, slip_time, min_commanded_since_goal, "
|
||||
"retry_backoff must be >= 0";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool validateUnreachable(const EnvMonitorConfig::Unreachable& unreachable, std::string& error)
|
||||
{
|
||||
if (!validAction(unreachable.action))
|
||||
{
|
||||
error = "env_monitor/unreachable/action must be \"log\" or \"recover\"";
|
||||
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;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool validateContact(const EnvMonitorConfig::Contact& contact, std::string& error)
|
||||
{
|
||||
if (!validAction(contact.action))
|
||||
{
|
||||
error = "env_monitor/contact/action must be \"log\" or \"recover\"";
|
||||
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;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EnvMonitorConfig::validate(std::string& error) const
|
||||
{
|
||||
return validateHost(*this, error) && validateStall(stall, error) && validateUnreachable(unreachable, error) &&
|
||||
validateContact(contact, error);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- describe
|
||||
|
||||
std::string describeStall(const EnvMonitorConfig::Stall& stall)
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << (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) idle=" << stall.idle_window_s
|
||||
<< " s confine=" << stall.confine_radius << " m/" << stall.confine_window_s << " s x" << stall.confine_cmd_factor
|
||||
<< " progress_veto=" << (stall.progress_veto ? "on" : "off");
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::string describeUnreachable(const EnvMonitorConfig::Unreachable& unreachable)
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << (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";
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::string describeContact(const EnvMonitorConfig::Contact& contact)
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << (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)");
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::string describeReplan(const EnvMonitorConfig::ReplanBudget& replan)
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "min_travel=" << replan.min_travel << " m x" << replan.escalate_factor << " within "
|
||||
<< replan.escalate_window_m << " m, max " << replan.escalate_max << " m";
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::string EnvMonitorConfig::describe() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "env_monitor " << (enabled ? "ON" : "OFF") << " (grace " << grace_after_new_plan << " s, pose_jump>"
|
||||
<< pose_jump_reject << " m):\n";
|
||||
out << " stall : " << describeStall(stall) << "\n";
|
||||
out << " unreachable : " << describeUnreachable(unreachable) << "\n";
|
||||
out << " contact : " << describeContact(contact) << "\n";
|
||||
out << " replan : " << describeReplan(replan);
|
||||
return out.str();
|
||||
}
|
||||
|
||||
} // namespace env_monitor_core
|
||||
5750
test/data/env_monitor_golden.txt
Normal file
5750
test/data/env_monitor_golden.txt
Normal file
File diff suppressed because it is too large
Load Diff
726
test/env_monitor_golden_test.cpp
Normal file
726
test/env_monitor_golden_test.cpp
Normal file
@@ -0,0 +1,726 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Golden test for EnvMonitor: drives the monitor through fixed scenarios and pins EVERY EnvVerdict field on
|
||||
* EVERY cycle against a recorded file. Written before EnvMonitor is moved to env_monitor_core and split into
|
||||
* detector plugins (Test/docs/move_base2/ENV_DETECTOR_PLUGINS_PROMPT.md, sections 6 and 8): the refactor must
|
||||
* reproduce this file bit for bit with the old configuration.
|
||||
*
|
||||
* Modes:
|
||||
* ENV_MONITOR_CORE_GOLDEN_RECORD=1 -> run every scenario and WRITE test/data/env_monitor_golden.txt
|
||||
* (unset) -> run every scenario and COMPARE with that file
|
||||
*
|
||||
* The committed golden file was recorded on 26/11/2026 from the monolithic EnvMonitor that still lived in
|
||||
* move_base2 (commit 605dbc8). Never re-record it to make a refactor pass: a diff here is a behaviour change.
|
||||
*
|
||||
* Only MonitorAdapter touches the EnvMonitor API. After the refactor, only that struct changes.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <env_monitor_core/env_monitor.h>
|
||||
|
||||
#include "env_monitor_test_config.h"
|
||||
|
||||
#ifndef ENV_MONITOR_CORE_TEST_DATA_DIR
|
||||
#error "ENV_MONITOR_CORE_TEST_DATA_DIR must be defined by CMake"
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using env_monitor_core::EnvSample;
|
||||
using env_monitor_core::EnvVerdict;
|
||||
|
||||
constexpr double kInf = std::numeric_limits<double>::infinity();
|
||||
constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
|
||||
|
||||
/// Config overrides as YAML paths under `env_monitor:` (e.g. "stall/action") -> value as text. Kept as text
|
||||
/// so that after the refactor the adapter can feed the same list to robot::NodeHandle.
|
||||
using Overrides = std::vector<std::pair<std::string, std::string>>;
|
||||
|
||||
/// Recovery outcome as the scenarios see it; the adapter maps it to the API of the day.
|
||||
enum class Outcome
|
||||
{
|
||||
kSucceededWithPath,
|
||||
kSucceeded,
|
||||
kFailed
|
||||
};
|
||||
|
||||
const char* toString(Outcome o)
|
||||
{
|
||||
switch (o)
|
||||
{
|
||||
case Outcome::kSucceededWithPath:
|
||||
return "succeeded_with_path";
|
||||
case Outcome::kSucceeded:
|
||||
return "succeeded";
|
||||
case Outcome::kFailed:
|
||||
return "failed";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ adapter
|
||||
|
||||
/// The ONLY place that calls EnvMonitor. Today: env_monitor_core::EnvMonitor built from YAML (detectors as .so).
|
||||
struct MonitorAdapter
|
||||
{
|
||||
bool init(const Overrides& overrides, std::string& error)
|
||||
{
|
||||
env_monitor_core::EnvMonitorConfig cfg;
|
||||
for (const auto& kv : overrides)
|
||||
{
|
||||
if (!apply(cfg, kv.first, kv.second))
|
||||
{
|
||||
error = "unknown override key '" + kv.first + "'";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return env_monitor_core_test::initializeFrom(monitor, cfg, error);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
monitor.reset();
|
||||
}
|
||||
|
||||
void goalAccepted(const robot::Time& now)
|
||||
{
|
||||
monitor.onGoalAccepted(now);
|
||||
}
|
||||
|
||||
void planApplied(const robot::Time& now)
|
||||
{
|
||||
monitor.onPlanApplied(now);
|
||||
}
|
||||
|
||||
/// @param own_route the finished route was started by the contact flag (today: `from_contact`).
|
||||
void recoveryFinished(const robot::Time& now, Outcome outcome, bool own_route)
|
||||
{
|
||||
env_monitor_core::EnvRecoveryOutcome o = env_monitor_core::EnvRecoveryOutcome::kFailed;
|
||||
switch (outcome)
|
||||
{
|
||||
case Outcome::kSucceededWithPath:
|
||||
o = env_monitor_core::EnvRecoveryOutcome::kSucceededWithPath;
|
||||
break;
|
||||
case Outcome::kSucceeded:
|
||||
o = env_monitor_core::EnvRecoveryOutcome::kSucceeded;
|
||||
break;
|
||||
case Outcome::kFailed:
|
||||
o = env_monitor_core::EnvRecoveryOutcome::kFailed;
|
||||
break;
|
||||
}
|
||||
// control_loop.cpp names the source detector only on success; failure passes none. "contact" is the built-in
|
||||
// detector name the scenarios mean by own_route.
|
||||
monitor.onRecoveryFinished(now, o, outcome != Outcome::kFailed && own_route ? "contact" : "");
|
||||
}
|
||||
|
||||
EnvVerdict update(const EnvSample& s)
|
||||
{
|
||||
return monitor.update(s);
|
||||
}
|
||||
|
||||
static bool apply(env_monitor_core::EnvMonitorConfig& c, const std::string& key, const std::string& value)
|
||||
{
|
||||
const auto num = [&value]() { return std::stod(value); };
|
||||
const auto flag = [&value]() { return value == "true"; };
|
||||
if (key == "enabled") c.enabled = flag();
|
||||
else if (key == "stall/enabled") c.stall.enabled = flag();
|
||||
else if (key == "stall/action") c.stall.action = value;
|
||||
else if (key == "stall/disp_min") c.stall.disp_min = num();
|
||||
else if (key == "stall/disp_window_s") c.stall.disp_window_s = num();
|
||||
else if (key == "stall/disp_min_commanded") c.stall.disp_min_commanded = num();
|
||||
else if (key == "stall/idle_window_s") c.stall.idle_window_s = num();
|
||||
else if (key == "stall/confine_window_s") c.stall.confine_window_s = num();
|
||||
else if (key == "stall/confine_radius") c.stall.confine_radius = num();
|
||||
else if (key == "stall/confine_cmd_factor") c.stall.confine_cmd_factor = num();
|
||||
else if (key == "stall/min_commanded_since_goal") c.stall.min_commanded_since_goal = num();
|
||||
else if (key == "unreachable/enabled") c.unreachable.enabled = flag();
|
||||
else if (key == "unreachable/action") c.unreachable.action = value;
|
||||
else if (key == "contact/enabled") c.contact.enabled = flag();
|
||||
else if (key == "contact/action") c.contact.action = value;
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
env_monitor_core::EnvMonitor monitor;
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------------------------- recording
|
||||
|
||||
std::string num(double d)
|
||||
{
|
||||
if (std::isnan(d))
|
||||
{
|
||||
return "nan"; // glibc may print "-nan"; the sign of a NaN carries no meaning here
|
||||
}
|
||||
if (std::isinf(d))
|
||||
{
|
||||
return d > 0.0 ? "inf" : "-inf";
|
||||
}
|
||||
char buf[40];
|
||||
std::snprintf(buf, sizeof(buf), "%.17g", d); // exact round trip
|
||||
return buf;
|
||||
}
|
||||
|
||||
std::string formatVerdict(const EnvVerdict& v)
|
||||
{
|
||||
std::ostringstream o;
|
||||
const auto b = [](bool x) { return x ? "1" : "0"; };
|
||||
o << "no_progress=" << b(v.no_progress) << " path_blocked=" << b(v.path_blocked) << " collision=" << b(v.collision)
|
||||
<< " brake=" << b(v.brake) << " v_cap=" << num(v.v_cap) << " stall_detected=" << b(v.stall_detected)
|
||||
<< " unreachable_detected=" << b(v.unreachable_detected) << " contact_imminent=" << b(v.contact_imminent)
|
||||
<< " contact_standdown=" << b(v.contact_standdown) << " cost_jump=" << b(v.cost_jump)
|
||||
<< " pose_jump=" << b(v.pose_jump) << " pose_jump_restart=" << b(v.pose_jump_restart)
|
||||
<< " pose_jump_dist=" << num(v.pose_jump_dist) << " progress_proven=" << b(v.progress_proven)
|
||||
<< " stall_muted=" << b(v.stall_muted) << " net_disp=" << num(v.net_disp) << " wandering=" << b(v.wandering)
|
||||
<< " idle=" << b(v.idle) << " confined=" << b(v.confined) << " region_radius=" << num(v.region_radius)
|
||||
<< " unreachable_muted=" << b(v.unreachable_muted) << " eff_geo=" << num(v.eff_geo)
|
||||
<< " cmd_window=" << num(v.cmd_window) << " brake_dist=" << num(v.brake_dist)
|
||||
<< " replan_budget_left=" << num(v.replan_budget_left) << " event=\"" << (v.event ? v.event : "") << "\"";
|
||||
return o.str();
|
||||
}
|
||||
|
||||
struct Recorder
|
||||
{
|
||||
bool enabled = true;
|
||||
std::vector<std::string> lines;
|
||||
|
||||
void verdict(const std::string& scenario, int cycle, const EnvVerdict& v)
|
||||
{
|
||||
if (enabled)
|
||||
{
|
||||
lines.push_back(scenario + " " + std::to_string(cycle) + " " + formatVerdict(v));
|
||||
}
|
||||
}
|
||||
|
||||
void mark(const std::string& scenario, int cycle, const std::string& what)
|
||||
{
|
||||
if (enabled)
|
||||
{
|
||||
lines.push_back(scenario + " " + std::to_string(cycle) + " # " + what);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------------------------- driver
|
||||
|
||||
/// Same motion model as the Harness in env_monitor_test.cpp: 20 Hz cycles, heavy tick every 4th cycle (5 Hz),
|
||||
/// robot along +x at v_cmd; `cost_rate` = d(cost_to_go)/dt (-v = full progress, 0 = no progress).
|
||||
class Drive
|
||||
{
|
||||
public:
|
||||
Drive(Recorder& rec, std::string name, const Overrides& overrides) : rec_(rec), name_(std::move(name))
|
||||
{
|
||||
std::string error;
|
||||
if (!adapter_.init(overrides, error))
|
||||
{
|
||||
ADD_FAILURE() << name_ << ": init failed: " << error;
|
||||
}
|
||||
goal();
|
||||
plan();
|
||||
}
|
||||
|
||||
robot::Time now() const
|
||||
{
|
||||
return robot::Time(t);
|
||||
}
|
||||
|
||||
void goal()
|
||||
{
|
||||
adapter_.goalAccepted(now());
|
||||
rec_.mark(name_, cycle, "goal_accepted");
|
||||
}
|
||||
|
||||
void plan()
|
||||
{
|
||||
adapter_.planApplied(now());
|
||||
rec_.mark(name_, cycle, "plan_applied");
|
||||
}
|
||||
|
||||
void recovery(Outcome outcome, bool own_route = false)
|
||||
{
|
||||
adapter_.recoveryFinished(now(), outcome, own_route);
|
||||
rec_.mark(name_, cycle, std::string("recovery_finished ") + toString(outcome) + (own_route ? " own" : ""));
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
adapter_.reset();
|
||||
rec_.mark(name_, cycle, "reset");
|
||||
}
|
||||
|
||||
const EnvVerdict& step(double v_cmd, double cost_rate, bool move = true)
|
||||
{
|
||||
t += dt;
|
||||
++cycle;
|
||||
if (orbit_radius > 0.0)
|
||||
{
|
||||
orbit_angle += v_cmd * dt / orbit_radius;
|
||||
x = orbit_x0 + orbit_radius * std::cos(orbit_angle);
|
||||
y = orbit_radius * std::sin(orbit_angle);
|
||||
}
|
||||
else if (wander_span > 0.0)
|
||||
{
|
||||
x = wander_x0 + wander_span * std::sin(2.0 * M_PI * (t - 100.0) / 4.0);
|
||||
}
|
||||
else if (move)
|
||||
{
|
||||
x += v_cmd * dt;
|
||||
}
|
||||
cost += cost_rate * dt;
|
||||
EnvSample s;
|
||||
s.now = now();
|
||||
s.dt = dt;
|
||||
s.costmap_current = costmap_current;
|
||||
s.has_plan = has_plan;
|
||||
s.robot_x = pose_unavailable ? kNaN : x;
|
||||
s.robot_y = pose_unavailable ? kNaN : y;
|
||||
s.v_cmd = v_cmd;
|
||||
s.v_meas = std::isnan(v_meas_override) ? (move ? v_cmd : 0.0) : v_meas_override;
|
||||
s.v_controller = v_controller_override;
|
||||
s.d_goal = d_goal;
|
||||
s.geometry_valid = (cycle % 4 == 0);
|
||||
s.cost_conclusive = conclusive;
|
||||
s.reachable = reachable;
|
||||
s.cost_to_go = reachable ? cost : kInf;
|
||||
s.edt_body_min = edt_body;
|
||||
s.contact_conclusive = contact_conclusive;
|
||||
s.traj_contact_dist = contact_dist;
|
||||
last = adapter_.update(s);
|
||||
rec_.verdict(name_, cycle, last);
|
||||
return last;
|
||||
}
|
||||
|
||||
void run(double seconds, double v_cmd, double cost_rate, bool move = true)
|
||||
{
|
||||
const int n = static_cast<int>(std::lround(seconds / dt));
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
step(v_cmd, cost_rate, move);
|
||||
}
|
||||
}
|
||||
|
||||
double t = 100.0;
|
||||
const double dt = 0.05;
|
||||
int cycle = 0;
|
||||
double x = 0.0;
|
||||
double y = 0.0;
|
||||
double cost = 12.0;
|
||||
double edt_body = 1.0;
|
||||
bool reachable = true;
|
||||
bool conclusive = true;
|
||||
bool has_plan = true;
|
||||
bool costmap_current = true;
|
||||
bool pose_unavailable = false;
|
||||
double d_goal = 12.0;
|
||||
double contact_dist = kInf;
|
||||
bool contact_conclusive = true;
|
||||
double v_meas_override = kNaN;
|
||||
double v_controller_override = kNaN;
|
||||
double wander_span = 0.0;
|
||||
double wander_x0 = 0.0;
|
||||
double orbit_radius = 0.0;
|
||||
double orbit_x0 = 0.0;
|
||||
double orbit_angle = 0.0;
|
||||
EnvVerdict last;
|
||||
|
||||
private:
|
||||
Recorder& rec_;
|
||||
std::string name_;
|
||||
MonitorAdapter adapter_;
|
||||
};
|
||||
|
||||
const Overrides kRecoverAll = {
|
||||
{ "stall/action", "recover" },
|
||||
{ "unreachable/action", "recover" },
|
||||
{ "contact/action", "recover" },
|
||||
{ "stall/disp_min", "0.0" },
|
||||
};
|
||||
|
||||
Overrides recoverWithDispGate(Overrides extra = {})
|
||||
{
|
||||
Overrides o = {
|
||||
{ "stall/action", "recover" }, { "unreachable/action", "recover" }, { "contact/action", "recover" },
|
||||
{ "stall/disp_min", "0.6" }, { "stall/disp_window_s", "6.0" }, { "stall/disp_min_commanded", "1.0" },
|
||||
{ "stall/idle_window_s", "10.0" }, { "stall/confine_window_s", "8.0" }, { "stall/confine_radius", "1.2" },
|
||||
{ "stall/confine_cmd_factor", "1.5" },
|
||||
};
|
||||
o.insert(o.end(), extra.begin(), extra.end());
|
||||
return o;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- scenarios
|
||||
|
||||
/// First cycle at which stall fires in the base "commanded without progress" run. Used to place a contact brake
|
||||
/// on the very same cycle, so the golden pins which detector's `event` wins.
|
||||
int firstStallCycle()
|
||||
{
|
||||
Recorder silent;
|
||||
silent.enabled = false;
|
||||
Drive d(silent, "probe", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
for (int i = 0; i < 200; ++i)
|
||||
{
|
||||
if (d.step(0.5, 0.0).stall_detected)
|
||||
{
|
||||
return d.cycle;
|
||||
}
|
||||
}
|
||||
ADD_FAILURE() << "probe: stall never fired";
|
||||
return -1;
|
||||
}
|
||||
|
||||
void runAllScenarios(Recorder& rec)
|
||||
{
|
||||
{
|
||||
Drive d(rec, "steady_progress", kRecoverAll);
|
||||
d.run(20.0, 0.5, -0.5);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_geodesic_and_hysteresis", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.run(6.0, 0.5, 0.0);
|
||||
d.run(4.0, 0.5, -0.175); // eff 0.35: dead band, holds
|
||||
d.run(4.0, 0.5, -0.4); // eff 0.8: clears
|
||||
d.run(10.0, 0.0, 0.0); // planner hold: waiting, not stalling
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_log_action", { { "stall/action", "log" }, { "stall/disp_min", "0.0" } });
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.run(6.0, 0.5, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_replan_budget_escalation", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.run(6.0, 0.5, 0.0);
|
||||
d.recovery(Outcome::kSucceededWithPath);
|
||||
d.plan();
|
||||
d.run(1.5, 0.5, 0.0);
|
||||
d.run(4.0, 0.5, 0.0);
|
||||
d.recovery(Outcome::kSucceededWithPath);
|
||||
d.plan();
|
||||
d.run(1.5, 0.5, 0.0);
|
||||
d.run(3.0, 0.5, 0.0);
|
||||
d.recovery(Outcome::kSucceeded); // non-path success: no budget change, chains reset
|
||||
d.run(3.0, 0.5, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_failed_recovery_backoff", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.run(6.0, 0.5, 0.0);
|
||||
d.recovery(Outcome::kFailed);
|
||||
d.run(2.9, 0.5, 0.0);
|
||||
d.run(2.0, 0.5, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_wheel_slip", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.conclusive = false;
|
||||
d.v_meas_override = 0.0;
|
||||
d.run(5.0, 0.4, 0.0, false);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_near_goal_not_measured", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.d_goal = 0.3;
|
||||
d.run(8.0, 0.3, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_idle_gate", recoverWithDispGate({ { "stall/min_commanded_since_goal", "0.1" } }));
|
||||
d.wander_span = 0.05;
|
||||
d.run(14.0, 0.05, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_confined_orbit", recoverWithDispGate({ { "stall/min_commanded_since_goal", "0.1" } }));
|
||||
d.orbit_radius = 0.6;
|
||||
d.run(14.0, 0.3, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_wandering_box_and_new_plan", recoverWithDispGate());
|
||||
d.wander_span = 0.25;
|
||||
d.run(12.0, 0.4, 0.0);
|
||||
d.recovery(Outcome::kSucceededWithPath);
|
||||
d.plan();
|
||||
d.run(10.0, 0.4, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "stall_displacement_gate_mutes", recoverWithDispGate());
|
||||
d.run(9.0, 0.5, 0.0); // cost flat but x advances
|
||||
}
|
||||
{
|
||||
Drive d(rec, "pose_jump_restart_and_cooldown", recoverWithDispGate());
|
||||
d.run(7.0, 0.3, -0.3);
|
||||
d.x -= 1.2; // relocalization
|
||||
d.step(0.3, -0.3);
|
||||
d.step(0.3, -0.3);
|
||||
d.x += 0.2; // ordinary localization correction, not a jump
|
||||
d.step(0.3, -0.3);
|
||||
d.run(3.0, 0.3, -0.3);
|
||||
d.x -= 1.0; // second jump inside the restart cooldown
|
||||
d.step(0.3, -0.3);
|
||||
d.pose_unavailable = true; // pose gap: the next valid pose may move by elapsed time x speed
|
||||
d.run(1.0, 0.3, -0.3);
|
||||
d.pose_unavailable = false;
|
||||
d.run(2.0, 0.3, -0.3);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "unreachable_fire_and_clear", kRecoverAll);
|
||||
d.run(2.0, 0.5, -0.5);
|
||||
d.reachable = false;
|
||||
d.run(3.0, 0.3, 0.0);
|
||||
d.reachable = true;
|
||||
d.run(0.4, 0.3, -0.3);
|
||||
d.reachable = false;
|
||||
d.edt_body = 0.1; // inside the band: no fire
|
||||
d.run(3.0, 0.3, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "unreachable_plan_born_unreachable", kRecoverAll);
|
||||
d.reachable = false;
|
||||
d.run(1.5, 0.3, 0.0);
|
||||
d.run(5.0, 0.3, 0.0);
|
||||
d.reachable = true;
|
||||
d.run(0.4, 0.3, -0.3);
|
||||
d.reachable = false;
|
||||
d.run(2.0, 0.3, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "unreachable_replan_budget_and_backoff", kRecoverAll);
|
||||
d.run(2.0, 0.5, -0.5);
|
||||
d.recovery(Outcome::kSucceededWithPath);
|
||||
d.plan();
|
||||
d.run(1.2, 0.3, -0.3);
|
||||
d.reachable = false;
|
||||
d.run(3.0, 0.3, 0.0);
|
||||
d.run(5.0, 0.3, 0.0); // budget used up: fires
|
||||
d.recovery(Outcome::kFailed);
|
||||
d.run(3.0, 0.3, 0.0); // backoff 2 s, then again
|
||||
}
|
||||
{
|
||||
Drive d(rec, "contact_brake_flag_release", kRecoverAll);
|
||||
d.contact_dist = 0.5;
|
||||
d.step(0.5, -0.5);
|
||||
d.step(0.5, -0.5);
|
||||
d.run(0.15, 0.0, 0.0, false);
|
||||
d.step(0.0, 0.0, false);
|
||||
d.contact_dist = 0.15;
|
||||
d.run(1.5, 0.3, 0.0, false);
|
||||
d.contact_dist = kInf;
|
||||
d.run(0.3, 0.0, 0.0, false);
|
||||
d.contact_dist = 0.3; // inconclusive sweep neither brakes nor releases
|
||||
d.run(0.2, 0.5, -0.5);
|
||||
d.contact_conclusive = false;
|
||||
d.run(0.2, 0.0, 0.0, false);
|
||||
d.contact_conclusive = true;
|
||||
d.contact_dist = 2.0; // far contact only caps speed
|
||||
d.run(1.0, 0.5, -0.5);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "contact_jitter_and_pivot", kRecoverAll);
|
||||
d.contact_dist = 0.08;
|
||||
d.run(2.0, 0.07, 0.0, false); // pivoting next to an obstacle: controller's business
|
||||
d.v_controller_override = 0.3;
|
||||
for (int i = 0; i < 40; ++i)
|
||||
{
|
||||
d.contact_dist = (i % 2 == 0) ? 0.08 : 0.25;
|
||||
d.step(0.0, 0.0, false);
|
||||
}
|
||||
d.contact_dist = kInf;
|
||||
d.run(0.5, 0.0, 0.0, false);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "contact_standdown_after_own_detour", kRecoverAll);
|
||||
d.contact_dist = 0.10;
|
||||
d.v_controller_override = 0.3;
|
||||
d.run(1.5, 0.0, 0.0, false);
|
||||
d.recovery(Outcome::kSucceededWithPath, true);
|
||||
d.step(0.0, 0.0, false);
|
||||
d.step(0.0, 0.0, false);
|
||||
d.contact_dist = 0.07;
|
||||
d.run(2.0, 0.0, 0.0, false);
|
||||
d.x += 0.35;
|
||||
d.step(0.2, 0.0, true);
|
||||
d.step(0.2, 0.0, true);
|
||||
d.step(0.2, 0.0, true);
|
||||
d.run(1.5, 0.0, 0.0, false);
|
||||
d.recovery(Outcome::kSucceededWithPath, true);
|
||||
d.step(0.0, 0.0, false);
|
||||
d.step(0.0, 0.0, false);
|
||||
d.contact_dist = kInf; // trajectory stays clear: re-arm
|
||||
d.run(0.3, 0.1, 0.0, false);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "contact_detour_from_other_trigger", kRecoverAll);
|
||||
d.recovery(Outcome::kSucceededWithPath, false);
|
||||
d.contact_dist = 0.10;
|
||||
d.v_controller_override = 0.3;
|
||||
d.run(1.5, 0.0, 0.0, false);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "gate_no_plan_or_stale_costmap", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.run(6.0, 0.5, 0.0);
|
||||
d.costmap_current = false;
|
||||
d.run(1.0, 0.5, 0.0);
|
||||
d.costmap_current = true;
|
||||
d.has_plan = false;
|
||||
d.contact_dist = 0.3; // contact still runs without a plan
|
||||
d.run(1.0, 0.5, 0.0);
|
||||
d.has_plan = true;
|
||||
d.contact_dist = kInf;
|
||||
d.run(6.0, 0.5, 0.0);
|
||||
}
|
||||
{
|
||||
// Contact starts braking on the very cycle stall fires: pins which `event` wins (today: stall, it runs later).
|
||||
const int fire = firstStallCycle();
|
||||
Drive d(rec, "event_overlap_contact_and_stall", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
while (d.cycle < fire + 20)
|
||||
{
|
||||
if (d.cycle == fire - 2)
|
||||
{
|
||||
d.contact_dist = 0.5; // imminent at fire-1, brake (confirm 2) at fire
|
||||
}
|
||||
d.step(0.5, 0.0);
|
||||
}
|
||||
}
|
||||
{
|
||||
Drive d(rec, "goal_plan_reset_midrun", kRecoverAll);
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.run(2.0, 0.5, 0.0);
|
||||
d.goal();
|
||||
d.run(2.0, 0.5, 0.0);
|
||||
d.plan();
|
||||
d.run(0.8, 0.5, 0.0); // inside grace
|
||||
d.run(5.0, 0.5, 0.0);
|
||||
d.reset();
|
||||
d.run(2.0, 0.5, -0.5);
|
||||
d.goal();
|
||||
d.plan();
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "disabled_monitor", { { "enabled", "false" }, { "stall/action", "recover" } });
|
||||
d.contact_dist = 0.1;
|
||||
d.reachable = false;
|
||||
d.run(3.0, 0.5, 0.0);
|
||||
}
|
||||
{
|
||||
Drive d(rec, "only_unreachable_enabled",
|
||||
{ { "stall/action", "recover" }, { "unreachable/action", "recover" }, { "contact/action", "recover" },
|
||||
{ "stall/disp_min", "0.0" }, { "stall/enabled", "false" }, { "contact/enabled", "false" } });
|
||||
d.run(3.0, 0.5, -0.5);
|
||||
d.contact_dist = 0.1;
|
||||
d.reachable = false;
|
||||
d.run(6.0, 0.5, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
std::string goldenPath()
|
||||
{
|
||||
return std::string(ENV_MONITOR_CORE_TEST_DATA_DIR) + "/env_monitor_golden.txt";
|
||||
}
|
||||
|
||||
/// First differing space-separated token, for a readable failure message.
|
||||
std::string firstDiff(const std::string& expected, const std::string& actual)
|
||||
{
|
||||
std::istringstream e(expected);
|
||||
std::istringstream a(actual);
|
||||
std::string te;
|
||||
std::string ta;
|
||||
while (true)
|
||||
{
|
||||
const bool he = static_cast<bool>(e >> te);
|
||||
const bool ha = static_cast<bool>(a >> ta);
|
||||
if (!he && !ha)
|
||||
{
|
||||
return "(lines differ only in spacing)";
|
||||
}
|
||||
if (!he || !ha || te != ta)
|
||||
{
|
||||
return "expected '" + (he ? te : std::string("<end>")) + "' got '" + (ha ? ta : std::string("<end>")) + "'";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(EnvMonitorGolden, ScenariosAreDeterministic)
|
||||
{
|
||||
Recorder a;
|
||||
Recorder b;
|
||||
runAllScenarios(a);
|
||||
runAllScenarios(b);
|
||||
ASSERT_EQ(a.lines.size(), b.lines.size());
|
||||
for (std::size_t i = 0; i < a.lines.size(); ++i)
|
||||
{
|
||||
ASSERT_EQ(a.lines[i], b.lines[i]) << "line " << i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(EnvMonitorGolden, MatchesTheRecordedVerdicts)
|
||||
{
|
||||
Recorder rec;
|
||||
runAllScenarios(rec);
|
||||
ASSERT_FALSE(rec.lines.empty());
|
||||
|
||||
const char* record = std::getenv("ENV_MONITOR_CORE_GOLDEN_RECORD");
|
||||
if (record != nullptr && std::string(record) == "1")
|
||||
{
|
||||
std::filesystem::create_directories(ENV_MONITOR_CORE_TEST_DATA_DIR);
|
||||
std::ofstream out(goldenPath(), std::ios::trunc);
|
||||
ASSERT_TRUE(out.good()) << "cannot write " << goldenPath();
|
||||
for (const auto& line : rec.lines)
|
||||
{
|
||||
out << line << '\n';
|
||||
}
|
||||
std::printf("[golden] recorded %zu lines to %s\n", rec.lines.size(), goldenPath().c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
std::ifstream in(goldenPath());
|
||||
ASSERT_TRUE(in.good()) << "golden file " << goldenPath()
|
||||
<< " is missing: run this test once with ENV_MONITOR_CORE_GOLDEN_RECORD=1 on the reference code";
|
||||
std::vector<std::string> expected;
|
||||
for (std::string line; std::getline(in, line);)
|
||||
{
|
||||
expected.push_back(line);
|
||||
}
|
||||
|
||||
int mismatches = 0;
|
||||
const std::size_t n = std::min(expected.size(), rec.lines.size());
|
||||
for (std::size_t i = 0; i < n && mismatches < 20; ++i)
|
||||
{
|
||||
if (expected[i] != rec.lines[i])
|
||||
{
|
||||
++mismatches;
|
||||
ADD_FAILURE() << "line " << i + 1 << ": " << firstDiff(expected[i], rec.lines[i]) << "\n expected: "
|
||||
<< expected[i] << "\n actual: " << rec.lines[i];
|
||||
}
|
||||
}
|
||||
EXPECT_EQ(expected.size(), rec.lines.size()) << "line count differs";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
379
test/env_monitor_loading_test.cpp
Normal file
379
test/env_monitor_loading_test.cpp
Normal file
@@ -0,0 +1,379 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core — loading detectors from YAML (Test/docs/move_base2/ENV_DETECTOR_PLUGINS_PROMPT.md §4, §6):
|
||||
* default list, YAML order, unknown type, stale / missing ABI, invalid parameters, merge of brake and v_cap.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <env_monitor_core/env_monitor.h>
|
||||
|
||||
#include "env_monitor_test_config.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using env_monitor_core::EnvMonitor;
|
||||
using env_monitor_core::EnvMonitorConfig;
|
||||
using env_monitor_core::EnvSample;
|
||||
using env_monitor_core::EnvVerdict;
|
||||
using env_monitor_core_test::freshNodeHandle;
|
||||
using env_monitor_core::toYaml;
|
||||
|
||||
constexpr double kInf = std::numeric_limits<double>::infinity();
|
||||
|
||||
EnvMonitorConfig recoverAll()
|
||||
{
|
||||
EnvMonitorConfig cfg;
|
||||
cfg.stall.action = "recover";
|
||||
cfg.unreachable.action = "recover";
|
||||
cfg.contact.action = "recover";
|
||||
cfg.stall.disp_min = 0.0;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
YAML::Node entry(const std::string& name, const std::string& type)
|
||||
{
|
||||
YAML::Node e;
|
||||
e["name"] = name;
|
||||
e["type"] = type;
|
||||
return e;
|
||||
}
|
||||
|
||||
/// @p env is the `env_monitor` block; @p list the `detectors` entries (empty = leave the key out).
|
||||
bool init(EnvMonitor& m, YAML::Node env, const std::vector<YAML::Node>& list, std::string& error)
|
||||
{
|
||||
robot::NodeHandle nh = freshNodeHandle();
|
||||
YAML::Node lib;
|
||||
lib["library_path"] = "libenv_monitor_core_test_stale_abi_detector";
|
||||
nh.setParam("StaleAbiDetector", lib);
|
||||
nh.setParam("NoAbiDetector", lib);
|
||||
if (!list.empty())
|
||||
{
|
||||
YAML::Node seq(YAML::NodeType::Sequence);
|
||||
for (const auto& e : list)
|
||||
{
|
||||
seq.push_back(e);
|
||||
}
|
||||
env["detectors"] = seq;
|
||||
}
|
||||
nh.setParam("env_monitor", env);
|
||||
return m.initialize(nh, error);
|
||||
}
|
||||
|
||||
/// Minimal cycle driver: 20 Hz, heavy tick every 4th cycle, robot along +x.
|
||||
struct Drive
|
||||
{
|
||||
explicit Drive(EnvMonitor& monitor) : m(monitor)
|
||||
{
|
||||
m.onGoalAccepted(robot::Time(t));
|
||||
m.onPlanApplied(robot::Time(t));
|
||||
}
|
||||
|
||||
const EnvVerdict& step(double v_cmd, double cost_rate)
|
||||
{
|
||||
t += 0.05;
|
||||
++cycle;
|
||||
x += v_cmd * 0.05;
|
||||
cost += cost_rate * 0.05;
|
||||
EnvSample s;
|
||||
s.now = robot::Time(t);
|
||||
s.dt = 0.05;
|
||||
s.has_plan = true;
|
||||
s.robot_x = x;
|
||||
s.v_cmd = v_cmd;
|
||||
s.v_meas = v_cmd;
|
||||
s.d_goal = 12.0;
|
||||
s.geometry_valid = (cycle % 4 == 0);
|
||||
s.cost_conclusive = true;
|
||||
s.reachable = true;
|
||||
s.cost_to_go = cost;
|
||||
s.edt_body_min = 1.0;
|
||||
s.contact_conclusive = true;
|
||||
s.traj_contact_dist = contact;
|
||||
last = m.update(s);
|
||||
return last;
|
||||
}
|
||||
|
||||
EnvMonitor& m;
|
||||
double t = 100.0;
|
||||
int cycle = 0;
|
||||
double x = 0.0;
|
||||
double cost = 12.0;
|
||||
double contact = kInf;
|
||||
EnvVerdict last;
|
||||
};
|
||||
|
||||
std::size_t at(const std::string& text, const std::string& needle)
|
||||
{
|
||||
return text.find(needle);
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, MissingDetectorsListLoadsTheThreeBuiltInsInTheMonolithOrder)
|
||||
{
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(recoverAll()), {}, error)) << error;
|
||||
EXPECT_EQ(3u, m.detectorCount());
|
||||
const std::string d = m.describe();
|
||||
ASSERT_NE(std::string::npos, at(d, "contact=ContactDetector")) << d;
|
||||
ASSERT_NE(std::string::npos, at(d, "stall=StallDetector")) << d;
|
||||
ASSERT_NE(std::string::npos, at(d, "unreachable=UnreachableDetector")) << d;
|
||||
EXPECT_LT(at(d, "contact=ContactDetector"), at(d, "stall=StallDetector"));
|
||||
EXPECT_LT(at(d, "stall=StallDetector"), at(d, "unreachable=UnreachableDetector"));
|
||||
EXPECT_TRUE(m.armed());
|
||||
EXPECT_TRUE(m.needs().geometry);
|
||||
EXPECT_TRUE(m.needs().sweep);
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, YamlListDecidesWhichDetectorsRunAndInWhatOrder)
|
||||
{
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(recoverAll()),
|
||||
{ entry("unreachable", "UnreachableDetector"), entry("contact", "ContactDetector") }, error))
|
||||
<< error;
|
||||
EXPECT_EQ(2u, m.detectorCount());
|
||||
const std::string d = m.describe();
|
||||
EXPECT_EQ(std::string::npos, at(d, "StallDetector")) << d;
|
||||
EXPECT_LT(at(d, "unreachable=UnreachableDetector"), at(d, "contact=ContactDetector")) << d;
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, UnknownTypeIsSkippedAndTheOthersStillRun)
|
||||
{
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(recoverAll()), { entry("ghost", "GhostDetector"), entry("contact", "ContactDetector") },
|
||||
error))
|
||||
<< error;
|
||||
EXPECT_TRUE(error.empty());
|
||||
EXPECT_EQ(1u, m.detectorCount());
|
||||
Drive d(m);
|
||||
d.contact = 0.10;
|
||||
d.step(0.5, -0.5);
|
||||
d.step(0.5, -0.5);
|
||||
EXPECT_TRUE(d.last.brake) << "the loaded contact detector must still brake";
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, StaleOrMissingAbiIsRefused)
|
||||
{
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(recoverAll()),
|
||||
{ entry("stale", "StaleAbiDetector"), entry("noabi", "NoAbiDetector"),
|
||||
entry("contact", "ContactDetector") },
|
||||
error))
|
||||
<< error;
|
||||
EXPECT_EQ(1u, m.detectorCount());
|
||||
EXPECT_EQ(std::string::npos, at(m.describe(), "Abi")) << m.describe();
|
||||
Drive d(m);
|
||||
d.step(0.0, 0.0);
|
||||
EXPECT_FALSE(d.last.brake) << "a refused plugin (it always brakes) must never run";
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, InvalidDetectorParametersFailTheWholeInitialize)
|
||||
{
|
||||
EnvMonitorConfig cfg = recoverAll();
|
||||
cfg.stall.eff_off = 0.1; // < eff_on 0.2
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
EXPECT_FALSE(init(m, toYaml(cfg), {}, error));
|
||||
EXPECT_NE(std::string::npos, error.find("env_monitor/stall")) << error;
|
||||
EXPECT_FALSE(m.configured());
|
||||
EXPECT_EQ(0u, m.detectorCount());
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, DisabledMonitorLoadsNothing)
|
||||
{
|
||||
EnvMonitorConfig cfg = recoverAll();
|
||||
cfg.enabled = false;
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(cfg), {}, error)) << error;
|
||||
EXPECT_FALSE(m.enabled());
|
||||
EXPECT_EQ(0u, m.detectorCount());
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, BrakeIsOredCapIsMinAndOnlyDetectorsWithAuthorityAct)
|
||||
{
|
||||
// Two contact instances: `far` keeps 0.2 m and is shadow, `near` keeps 0.1 m and acts on the command.
|
||||
YAML::Node env = toYaml(recoverAll());
|
||||
YAML::Node far = YAML::Clone(env["contact"]);
|
||||
far["clean_start_margin"] = "0.2";
|
||||
far["apply_command"] = false;
|
||||
YAML::Node near = YAML::Clone(env["contact"]);
|
||||
near["clean_start_margin"] = "0.1";
|
||||
near["apply_command"] = true;
|
||||
env["far"] = far;
|
||||
env["near"] = near;
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, env, { entry("far", "ContactDetector"), entry("near", "ContactDetector") }, error)) << error;
|
||||
ASSERT_EQ(2u, m.detectorCount());
|
||||
|
||||
Drive d(m);
|
||||
d.contact = 1.0;
|
||||
d.step(0.0, 0.0);
|
||||
const double far_cap = std::sqrt(2.0 * 0.35 * (1.0 - 0.2 - 0.1));
|
||||
const double near_cap = std::sqrt(2.0 * 0.35 * (1.0 - 0.1 - 0.1));
|
||||
EXPECT_NEAR(far_cap, d.last.v_cap, 1e-9) << "v_cap = min over detectors";
|
||||
EXPECT_NEAR(near_cap, d.last.v_cap_applied, 1e-9) << "only `near` acts on the command";
|
||||
EXPECT_FALSE(d.last.brake);
|
||||
|
||||
d.contact = 0.15; // inside both margins: both brake after confirm
|
||||
d.step(0.5, 0.0);
|
||||
d.step(0.5, 0.0);
|
||||
EXPECT_TRUE(d.last.brake);
|
||||
EXPECT_TRUE(d.last.brake_applied);
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, ShadowDetectorsReportTheBrakeButDoNotApplyIt)
|
||||
{
|
||||
EnvMonitorConfig cfg = recoverAll();
|
||||
cfg.contact.apply_command = false;
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(cfg), {}, error)) << error;
|
||||
Drive d(m);
|
||||
d.contact = 0.10;
|
||||
d.step(0.5, -0.5);
|
||||
d.step(0.5, -0.5);
|
||||
EXPECT_TRUE(d.last.brake);
|
||||
EXPECT_FALSE(d.last.brake_applied);
|
||||
EXPECT_TRUE(std::isinf(d.last.v_cap_applied));
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, ALaterDetectorInTheListWinsTheEventOfACycle)
|
||||
{
|
||||
// Find the cycle at which stall fires with the default order, then reverse the order and brake on that cycle.
|
||||
int fire = -1;
|
||||
{
|
||||
EnvMonitor probe;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(probe, toYaml(recoverAll()), {}, error)) << error;
|
||||
Drive d(probe);
|
||||
for (int i = 0; i < 60; ++i)
|
||||
{
|
||||
d.step(0.5, -0.5);
|
||||
}
|
||||
for (int i = 0; i < 200 && fire < 0; ++i)
|
||||
{
|
||||
if (d.step(0.5, 0.0).stall_detected)
|
||||
{
|
||||
fire = d.cycle;
|
||||
}
|
||||
}
|
||||
}
|
||||
ASSERT_GT(fire, 62);
|
||||
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(recoverAll()), { entry("stall", "StallDetector"), entry("contact", "ContactDetector") },
|
||||
error))
|
||||
<< error;
|
||||
Drive d(m);
|
||||
for (int i = 0; i < 60; ++i)
|
||||
{
|
||||
d.step(0.5, -0.5);
|
||||
}
|
||||
while (d.cycle < fire)
|
||||
{
|
||||
if (d.cycle == fire - 2)
|
||||
{
|
||||
d.contact = 0.5; // imminent at fire-1, brake at fire
|
||||
}
|
||||
d.step(0.5, 0.0);
|
||||
}
|
||||
ASSERT_TRUE(d.last.stall_detected);
|
||||
ASSERT_TRUE(d.last.brake);
|
||||
EXPECT_STREQ("contact: braking to zero", d.last.event) << "contact is listed after stall, so its event wins";
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, RouteDefaultsComeFromThePluginAndKeysOverrideThem)
|
||||
{
|
||||
YAML::Node env = toYaml(recoverAll());
|
||||
env["contact"]["route"] = "intrusion";
|
||||
env["contact"]["route_mode"] = "sequence";
|
||||
env["contact"]["on_exhausted"] = "abort";
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, env, {}, error)) << error;
|
||||
ASSERT_EQ(3u, m.detectors().size());
|
||||
const auto& contact = m.detectors()[0];
|
||||
EXPECT_EQ("contact", contact.name);
|
||||
EXPECT_EQ("intrusion", contact.route.route);
|
||||
EXPECT_TRUE(contact.route.sequence);
|
||||
EXPECT_FALSE(contact.route.lock_on_exhausted);
|
||||
// Defaults of the monolith: stall -> oscillation/abort, unreachable -> path_blocked/lock, both step.
|
||||
EXPECT_EQ("oscillation", m.detectors()[1].route.route);
|
||||
EXPECT_FALSE(m.detectors()[1].route.lock_on_exhausted);
|
||||
EXPECT_FALSE(m.detectors()[1].route.sequence);
|
||||
EXPECT_EQ("path_blocked", m.detectors()[2].route.route);
|
||||
EXPECT_TRUE(m.detectors()[2].route.lock_on_exhausted);
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, InvalidRouteModeOrOnExhaustedFailsTheInitialize)
|
||||
{
|
||||
for (const char* key : { "route_mode", "on_exhausted" })
|
||||
{
|
||||
YAML::Node env = toYaml(recoverAll());
|
||||
env["stall"][key] = "sometimes";
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
EXPECT_FALSE(init(m, env, {}, error)) << key;
|
||||
EXPECT_NE(std::string::npos, error.find("env_monitor/stall")) << error;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, FiredMaskHasOneBitPerDetectorInListOrder)
|
||||
{
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(recoverAll()), {}, error)) << error; // contact=bit0, stall=bit1, unreachable=bit2
|
||||
Drive d(m);
|
||||
d.contact = 0.10;
|
||||
d.step(0.0, 0.0);
|
||||
for (int i = 0; i < 30 && !d.last.collision; ++i)
|
||||
{
|
||||
d.step(0.5, 0.0);
|
||||
}
|
||||
ASSERT_TRUE(d.last.collision);
|
||||
EXPECT_EQ(1u, d.last.fired_mask & 1u);
|
||||
EXPECT_EQ(d.last.no_progress, (d.last.fired_mask & 2u) != 0);
|
||||
EXPECT_EQ(d.last.path_blocked, (d.last.fired_mask & 4u) != 0);
|
||||
}
|
||||
|
||||
TEST(EnvMonitorLoading, RemovedDetectorStopsRunningAndTheOthersShiftDown)
|
||||
{
|
||||
EnvMonitor m;
|
||||
std::string error;
|
||||
ASSERT_TRUE(init(m, toYaml(recoverAll()), {}, error)) << error;
|
||||
EXPECT_FALSE(m.remove("ghost"));
|
||||
ASSERT_TRUE(m.remove("contact"));
|
||||
ASSERT_EQ(2u, m.detectors().size());
|
||||
EXPECT_EQ("stall", m.detectors()[0].name);
|
||||
Drive d(m);
|
||||
d.contact = 0.10;
|
||||
d.step(0.5, -0.5);
|
||||
d.step(0.5, -0.5);
|
||||
EXPECT_FALSE(d.last.brake);
|
||||
EXPECT_FALSE(m.needs().sweep);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
1439
test/env_monitor_test.cpp
Normal file
1439
test/env_monitor_test.cpp
Normal file
File diff suppressed because it is too large
Load Diff
65
test/env_monitor_test_config.h
Normal file
65
test/env_monitor_test_config.h
Normal file
@@ -0,0 +1,65 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core tests — build an EnvMonitor from an EnvMonitorConfig through the real YAML path.
|
||||
*
|
||||
* The struct is written as YAML under a fresh namespace of the global robot::NodeHandle tree (the same keys
|
||||
* env_monitor_params.yaml uses), with `<Type>/library_path` for the three built-in detectors, then
|
||||
* EnvMonitor::initialize() loads the .so files from devel/lib exactly as the runtime does.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef ENV_MONITOR_CORE_TEST_ENV_MONITOR_TEST_CONFIG_H_
|
||||
#define ENV_MONITOR_CORE_TEST_ENV_MONITOR_TEST_CONFIG_H_
|
||||
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
|
||||
#include <env_monitor_core/env_monitor.h>
|
||||
|
||||
#ifndef ENV_MONITOR_CORE_TEST_LIBRARY_DIR
|
||||
#error "ENV_MONITOR_CORE_TEST_LIBRARY_DIR must be defined by CMake"
|
||||
#endif
|
||||
|
||||
namespace env_monitor_core_test
|
||||
{
|
||||
|
||||
/// Fresh namespace per call: the NodeHandle tree is global, two monitors must never share keys.
|
||||
inline robot::NodeHandle freshNodeHandle()
|
||||
{
|
||||
static int counter = 0;
|
||||
// The runtime and every test resolve `<Type>/library_path` against devel/lib; a value left in the user's shell
|
||||
// (see the scenario test 26/11) must not win.
|
||||
setenv("PNKX_NAV_CORE_LIBRARY_PATH", ENV_MONITOR_CORE_TEST_LIBRARY_DIR, 1);
|
||||
robot::NodeHandle nh("env_monitor_core_test_" + std::to_string(++counter));
|
||||
const char* const kLibraries[][2] = {
|
||||
{ "ContactDetector", "libenv_monitor_core_contact_detector" },
|
||||
{ "StallDetector", "libenv_monitor_core_stall_detector" },
|
||||
{ "UnreachableDetector", "libenv_monitor_core_unreachable_detector" },
|
||||
};
|
||||
for (const auto& lib : kLibraries)
|
||||
{
|
||||
YAML::Node node;
|
||||
node["library_path"] = lib[1];
|
||||
nh.setParam(lib[0], node);
|
||||
}
|
||||
return nh;
|
||||
}
|
||||
|
||||
/// EnvMonitor from @p config through YAML; the `detectors` list is left out, so the built-in default is used.
|
||||
inline bool initializeFrom(env_monitor_core::EnvMonitor& monitor, const env_monitor_core::EnvMonitorConfig& config,
|
||||
std::string& error)
|
||||
{
|
||||
robot::NodeHandle nh = freshNodeHandle();
|
||||
nh.setParam("env_monitor", env_monitor_core::toYaml(config));
|
||||
return monitor.initialize(nh, error);
|
||||
}
|
||||
|
||||
} // namespace env_monitor_core_test
|
||||
|
||||
#endif // ENV_MONITOR_CORE_TEST_ENV_MONITOR_TEST_CONFIG_H_
|
||||
74
test/plugins/stale_abi_detector.cpp
Normal file
74
test/plugins/stale_abi_detector.cpp
Normal file
@@ -0,0 +1,74 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* env_monitor_core tests — detectors that EnvMonitor must REFUSE to load:
|
||||
* - StaleAbiDetector : `_abi` returns a version the runtime does not match;
|
||||
* - NoAbiDetector : no `_abi` symbol at all (plain BOOST_DLL_ALIAS).
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
|
||||
#include <env_monitor_core/env_detector.h>
|
||||
#include <env_monitor_core/env_detector_abi.h>
|
||||
|
||||
namespace env_monitor_core
|
||||
{
|
||||
namespace testing
|
||||
{
|
||||
|
||||
class StaleAbiDetector final : public EnvDetector
|
||||
{
|
||||
public:
|
||||
static EnvDetector::Ptr create()
|
||||
{
|
||||
return std::make_shared<StaleAbiDetector>();
|
||||
}
|
||||
|
||||
bool initialize(const std::string& /*name*/, robot::NodeHandle& /*nh*/, std::string& /*error*/) override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
std::string describe() const override
|
||||
{
|
||||
return "stale";
|
||||
}
|
||||
bool armed() const override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
EnvRouteSpec defaultRoute() const override
|
||||
{
|
||||
EnvRouteSpec spec;
|
||||
spec.route = "stale";
|
||||
return spec;
|
||||
}
|
||||
EnvNeeds needs() const override
|
||||
{
|
||||
return EnvNeeds();
|
||||
}
|
||||
void reset() override
|
||||
{
|
||||
}
|
||||
void update(const EnvFrame& /*frame*/, EnvDetectorOutput& out, EnvVerdict& /*verdict*/) override
|
||||
{
|
||||
out.brake = true; // would be visible if the monitor ever ran it
|
||||
}
|
||||
};
|
||||
|
||||
/// ABI version "from the future": never equal to the runtime's.
|
||||
int staleAbiVersion()
|
||||
{
|
||||
return kEnvDetectorAbiVersion + 1;
|
||||
}
|
||||
|
||||
} // namespace testing
|
||||
} // namespace env_monitor_core
|
||||
|
||||
BOOST_DLL_ALIAS(env_monitor_core::testing::StaleAbiDetector::create, StaleAbiDetector)
|
||||
BOOST_DLL_ALIAS(env_monitor_core::testing::staleAbiVersion, StaleAbiDetector_abi)
|
||||
BOOST_DLL_ALIAS(env_monitor_core::testing::StaleAbiDetector::create, NoAbiDetector)
|
||||
Reference in New Issue
Block a user