From 261cc20ad4f3e3978d0ca4301590c8b5f1247e75 Mon Sep 17 00:00:00 2001 From: duongtd Date: Sun, 6 Sep 2026 10:30:31 +0700 Subject: [PATCH] =?UTF-8?q?feat:=20EnvMonitor=20thay=20PathMonitor=20?= =?UTF-8?q?=E2=80=94=20gi=C3=A1m=20s=C3=A1t=20m=C3=B4i=20tr=C6=B0=E1=BB=9D?= =?UTF-8?q?ng=20b=E1=BA=B1ng=20EDT/geodesic/qu=E1=BB=B9=20=C4=91=E1=BA=A1o?= =?UTF-8?q?=20th=E1=BA=ADt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bộ giám sát mới trong ControlLoop (core/env_monitor, core/grid_analysis, ports/environment_port, io/env_logger), thay bốn phép đo của PathMonitor (code cũ còn, tắt bằng path_monitor/enabled: false): - kContact: dò tiếp xúc dọc quỹ đạo local planner (thay cung v/omega), bao tốc độ sqrt(2a(d - margin)) có dư, phanh chỉ khi vượt bao, cờ collision khi kề mũi tĩnh 1 s; cổng xoay tại chỗ theo lệnh controller muốn; hysteresis + xác nhận khi nhả; đứng ra sau detour không dịch robot (nhường controller); giữ phanh khi route khoá thì báo no valid command để controller_patience leo thang. - kStall: cost_to_go = geodesic tới điểm thoát 2 m dọc plan + phần plan còn lại, index plan bám cửa sổ, bộ lọc lật liên thông; cờ no_progress chỉ khi cổng dịch chuyển thực mở (robot không đi được đâu trong 12 s dù lệnh >= 1,5 m) — thay ngân sách replan cho stall. - kUnreachable: liên thông tới điểm thoát, đang ở action log. - EnvLogger ghi JSONL mỗi tick nặng; config/runtime/env_monitor_params.yaml đủ khoá, comment tiếng Việt; ControllerPort::measuredVelocity; FakeEnvironmentPort cho test. Sim 5–6/9: hết churn detour, khe 1,25 m đi qua 0,5 m/s, lượt 6/9 10:15 2 detour/142 s không oan. Test: grid_analysis 31, env_monitor 43, plan_inspector 37, walking_skeleton 87, các bộ khác pass. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_017xXjFjr2DQ6rhmhHSW4fk4 --- CMakeLists.txt | 5 + config/runtime/env_monitor_params.yaml | 166 ++++ config/runtime/path_monitor_params.yaml | 11 +- include/move_base2/config/move_base2_config.h | 7 + include/move_base2/control_loop.h | 41 + include/move_base2/core/env_monitor.h | 357 +++++++ include/move_base2/core/grid_analysis.h | 278 ++++++ include/move_base2/core/plan_inspector.h | 13 + include/move_base2/io/env_logger.h | 77 ++ include/move_base2/navigation_runtime.h | 39 + include/move_base2/ports/controller_port.h | 11 + include/move_base2/ports/environment_port.h | 145 +++ .../move_base2/runners/controller_runner.h | 2 + src/config/move_base2_config.cpp | 132 +++ src/control_loop.cpp | 348 ++++++- src/env_monitor.cpp | 773 +++++++++++++++ src/grid_analysis.cpp | 813 +++++++++++++++ src/io/env_logger.cpp | 205 ++++ src/navigation_runtime.cpp | 236 +++++ src/plan_inspector.cpp | 44 + src/runners/controller_runner.cpp | 11 + test/env_monitor_test.cpp | 933 ++++++++++++++++++ test/fake_ports.h | 124 +++ test/grid_analysis_test.cpp | 683 +++++++++++++ test/plan_inspector_test.cpp | 25 + test/walking_skeleton_test.cpp | 117 +++ 26 files changed, 5589 insertions(+), 7 deletions(-) create mode 100644 config/runtime/env_monitor_params.yaml create mode 100644 include/move_base2/core/env_monitor.h create mode 100644 include/move_base2/core/grid_analysis.h create mode 100644 include/move_base2/io/env_logger.h create mode 100644 include/move_base2/ports/environment_port.h create mode 100644 src/env_monitor.cpp create mode 100644 src/grid_analysis.cpp create mode 100644 src/io/env_logger.cpp create mode 100644 test/env_monitor_test.cpp create mode 100644 test/grid_analysis_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index a18f293..0c9261a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -233,6 +233,8 @@ add_library(move_base2_core SHARED src/state_machine.cpp src/velocity_arbiter.cpp src/plan_inspector.cpp + src/grid_analysis.cpp + src/env_monitor.cpp src/control_loop.cpp src/config/move_base2_config.cpp src/runners/recovery_runner.cpp @@ -243,6 +245,7 @@ add_library(move_base2_core SHARED src/io/sensor_gateway.cpp src/io/sensor_store_types.cpp src/io/costmap_exporter.cpp + src/io/env_logger.cpp src/bridges/mission_adapter_bridge.cpp src/bridges/mission_layer.cpp src/navigation_runtime.cpp @@ -450,6 +453,8 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN) state_machine_test velocity_arbiter_test plan_inspector_test + grid_analysis_test + env_monitor_test walking_skeleton_test config_validation_test action_runner_test diff --git a/config/runtime/env_monitor_params.yaml b/config/runtime/env_monitor_params.yaml new file mode 100644 index 0000000..9fcb001 --- /dev/null +++ b/config/runtime/env_monitor_params.yaml @@ -0,0 +1,166 @@ +# ================================================================================================= +# env_monitor_params.yaml — EnvMonitor: giám sát môi trường quanh robot để gọi recovery (thay PathMonitor) +# Ngày lập: 2026-09-05 (Test/ENV_MONITOR_PLAN.md). Giai đoạn hiện tại: P4 BƯỚC 4 (6/9 00:20) — stall + contact bật thật, +# unreachable về log; PathMonitor cũ TẮT HẲN (path_monitor/enabled: false), EnvMonitor là bộ giám sát duy nhất. +# stall cổng dịch chuyển thực (disp_*) là định nghĩa "bế tắc thật"; geodesic là điều kiện thứ hai + để ghi. +# contact action recover + apply_command true: bao tốc độ, phanh chỉ khi vượt bao, cờ collision, đứng ra sau detour +# vô ích. Run 23:32: khe 1,25 m đi qua 0,5 m/s, 0 phanh, 0 ABORT (plan §4.12). +# unreachable action recover: chưa nổ lần nào qua 5 lượt sim. +# stall action recover (bật 23:45): shadow 4 lượt — 20:20 4/6 đúng sớm 1–5,5 s + 1 oan/330 s; 23:32 2/2 đúng sớm +# 4,8–6,8 s trên đất sạch, 0 oan. Cờ no_progress -> route oscillation (trigger GỐC: cạn route = ABORT chặng). +# Đổi `action` / `contact/apply_command` là đổi hành vi thật, không cần build lại. +# +# Ai đọc: `move_base2` qua `robot::NodeHandle` (namespace `env_monitor`, hàm readEnvMonitor trong +# src/config/move_base2_config.cpp). NodeHandle merge MỌI .yaml trong thư mục này, nên khoá top-level +# `env_monitor:` phải xuất hiện ở đúng MỘT file. +# +# Triết lý (chốt 5/9): local planner được TỰ DO NÉ; recovery chỉ chạy khi BẾ TẮC THẬT. Không có phép đo +# "plan phía trước bị chắn" ở đây — đó là thứ làm bản cũ nổ oan và phải tắt. Ba verdict: +# stall lệnh đi mà cost_to_go (đường vòng tới điểm thoát + phần plan còn lại) không giảm -> no_progress +# unreachable không còn đường trong cửa sổ tới điểm thoát, vật đứng yên, xấu hơn lúc nhận plan -> path_blocked +# contact thân sắp chạm trên QUỸ ĐẠO THẬT của local planner: phanh; vật kề mũi đứng yên 1 s -> collision +# Cờ đi vào đúng bốn cổng của state machine như cũ; route bên recovery_behaviors_params.yaml không đổi. +# +# Mọi ngưỡng là GIÁ TRỊ KHỞI ĐIỂM rút từ hai bag sim 5/9 (plan §4.4). Chốt bằng shadow/replay, không mò tay. +# ================================================================================================= +env_monitor: + # Công tắc chung. false = không lấy mẫu, không in, không ghi — hành vi y như không có EnvMonitor. + enabled: true + + # Profile được giám sát. docking / go_straight / rotate KHÔNG: đường cong vào dock là một thể thống nhất. + profiles: [position] + + # [s] Nhịp phần NẶNG (EDT + Dijkstra + hành lang, ~0.6 ms trên máy dev). Phần tiếp xúc chạy mỗi cycle. + # ► Chỉnh: ≈ chu kỳ cập nhật costmap local (10 Hz -> 0.1..0.2). TĂNG nếu CPU căng, phản ứng chậm đi đúng chừng đó. + check_period: 0.2 + + # [s] Sau khi nhận plan mới (planner hay detour) không kết luận gì: mẫu cũ thuộc plan cũ. + grace_after_new_plan: 1.0 + + # --- Thân robot và ngữ nghĩa vật cản -------------------------------------------------------------- + body: + # [m] mũi / đuôi / nửa bề rộng từ base_link. CẢ BA = 0 = lấy footprint KHÔNG đệm của costmap mỗi lượt + # (cùng hình với SBPL và PRIEST). Khai tay thì khai đủ cả ba > 0. + front_offset: 0.0 + rear_offset: 0.0 + side_offset: 0.0 + # [m] Đệm CHỈ cho dò tiếp xúc (phanh). Liên thông / hành lang dùng đúng biên SBPL (không đệm) — monitor + # khắt khe hơn planner vừa lập path là tự cãi nhau với chính path đó (vòng lặp 4/9). + padding: 0.0 # 5/9 23:20: về 0 — thân dò = footprint thật. Với 0.05 + ô 5 cm, khe 1.25 m (thân 0.96) vẫn bị coi + # là "sắp chạm" khi PRIEST đi lệch 11 cm một bên -> phanh -> detour từ trong khe -> ABORT (m1/m8 run + # 22:58). PRIEST tự giữ khoảng cách theo model của nó; monitor chỉ chặn footprint thật vào ô lethal. + # Robot thật: sai số localization 3–5 cm là cạ — đo trên robot rồi mới quyết 0.02–0.05. + # cost >= đây là vật cản THẬT. ĐỪNG hạ xuống 253: vành inflation của cây sim (0.3 m) nhỏ hơn inscribed + # (0.48 m) nên đã bị cắt cụt; mọi biên ở đây tính lại từ khoảng cách tới ô lethal + bán kính thân. + lethal_threshold: 254 + + # --- Hình học dọc plan (chỉ để ghi, giải thích, bao tốc độ; KHÔNG tự nổ) --------------------------- + geometry: + horizon: 3.0 # [m] quãng plan quét hành lang. <= nửa cửa sổ local. + corridor_margin: 0.0 # [m] mỗi bên, cộng vào bề rộng thân khi xét khe. 0 = đúng biên SBPL. + corridor_cap: 1.5 # [m] trần quãng trống đo về mỗi bên. + target_backoff: 0.5 # [m] điểm thoát T nằm trong vật cản thì lùi dọc plan tối đa chừng này. + robot_snap: 0.35 # [m] ô robot không đặt được (đang ôm sát vật) thì lấy ô free gần nhất trong đây. + track_back: 1.0 # [m] bám index plan qua các tick: chỉ tìm lùi tối đa chừng này dọc plan so với tick trước. + exit_ahead: 2.0 # [m] điểm thoát T của cost_to_go = pose plan ở quãng này dọc plan kể từ index đang bám (kẹp trong cửa + # sổ). 0 = T là điểm plan rời cửa sổ (bản cũ). Run 23:37: plan detour vòng chữ U, robot đi theo về tây, + # phần plan quay về đông rời cửa sổ sớm hơn -> T LÙI, arc_rest tăng bù geo giảm, tiến độ thật đo = 0, + # stall oan lúc robot đang chạy 0.5 m/s. T ở quãng cố định chỉ tiến theo index; geodesic 2 m ít bị lật + # liên thông hơn 6–9 m. GIẢM (1.5) nếu còn thấy arc_rest tăng khi robot đi đúng plan. + track_ahead: 3.0 # [m] ... và tiến tối đa chừng này. Detour uốn quanh trụ có đoạn sau đi sát robot: tìm toàn plan + # nhảy sang đoạn đó, điểm thoát T đổi, cost_to_go nhảy +8 m/1 s (run 22:35) -> stall giả. + # Plan mới thì tìm lại toàn plan một lần. TĂNG track_ahead nếu robot cắt cua xa plan. + + # --- stall: "planner đòi đi mà không tới gần lối ra" -> cờ no_progress -> route oscillation ---------- + # oscillation là trigger GỐC: cạn route = ABORT chặng, nổ oan là MẤT CHẶNG -> bật "recover" SAU CÙNG. + stall: + enabled: true + action: recover # "recover" = giơ cờ no_progress (bật 5/9 23:45); "log" = chỉ ghi/in (shadow). + window_s: 4.0 # [s] cửa sổ đo eff_geo = (cost_to_go giảm) / (lệnh tích luỹ) + window_m: 1.5 # [m] hoặc theo lệnh tích luỹ — cái tới trước. Bag 5/9: né đúng eff 0.7–1.0, kẹt ≈ 0 hoặc âm. + jump_reject: 1.0 # [m] hai mẫu nặng liên tiếp (0.2 s) 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, bỏ kết luận kẹt cũ. + # Run 23:37: geo nhảy +3.2 m / 0.2 s -> eff −2.7 -> detour oan. 0 = tắt. Robot 0.5 m/s đi được 0.1 m/tick + # nên 1.0 là rộng gấp 10 — HẠ (0.5) nếu còn thấy eff âm sâu bất thường mà không có sự kiện. + min_commanded: 0.30 # [m] lệnh trong cửa sổ ít hơn = đang chờ/xoay, KHÔNG đo. ĐỪNG đặt 0. + eff_on: 0.20 # [-] eff dưới đây là kẹt. + eff_off: 0.50 # [-] trên đây mới xoá (hysteresis). Phải > eff_on. + confirm: 1.0 # [s] kẹt liên tục chừng này mới nổ. + goal_zone: 0.6 # [m] gần goal hơn đây không đo (rot2goal, dừng chính xác). >= xy_goal_tolerance + 0.3. + slip_on: 0.15 # [m/s] |v_cmd| - |v_đo| liên tục = kẹt vật lý (vật thấp, bumper). 0 = tắt. + slip_time: 1.0 # [s] + min_commanded_since_goal: 1.0 # [m] cổng đầu chặng — cắt hai lần nổ sớm ở bag 5/9 (rel 13.0, 145.6). + # --- Cổng DỊCH CHUYỂN THỰC (6/9 00:20) — định nghĩa vận hành của "bế tắc thật" --------------------------------- + # Cờ chỉ được giơ 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ổ (run 00:05 cờ 95 s: robot chạy 0.5 m/s mà nổ vì lệch plan). + # Quần trong hộp 0.9 x 0.5 m (run 00:05: 97 s, dịch 0.13–0.62 m mỗi 20 s) -> nổ sau ~window. Cửa sổ bắt đầu lại ở mỗi + # plan mới, THAY ngân sách replan_budget cho stall (ngân sách đo theo quãng đường, đi vòng 6.6 m mới đốt hết -> câm 97 s). + disp_window_s: 12.0 # [s] cửa sổ đo dịch chuyển. GIẢM (8) nếu muốn nổ sớm hơn, TĂNG (20) nếu còn nổ khi né chậm trong đám đông. + disp_min: 0.6 # [m] dịch chuyển thực dưới đây = không đi được đâu. 0 = TẮT cổng, dùng lại ngân sách replan như cũ. + disp_min_commanded: 1.5 # [m] lệnh tích luỹ trong cửa sổ phải >= đây mới xét (đứng chờ không phải kẹt). + retry_backoff: 3.0 # [s] sau một lượt recovery HỎNG không tích bằng chứng (thay cho behavior wait). + + # --- unreachable: không còn đường trong cửa sổ tới điểm thoát -> cờ path_blocked -> route path_blocked -- + # Cạn route chỉ KHOÁ trigger (contract 05e), an toàn để bật trước stall. Bag 5/9: 0/3278 khung — hiếm. + unreachable: + enabled: true + action: log # 6/9 00:20: về LOG. Với exit_ahead 2 m, "không có đường tới T" = plan bị chắn trong 2 m = phép đo 1 cũ mà chủ + # dự án đã tắt; run 00:05 nổ oan 4 lần khi robot đứng giữa đất trống (edt 1.12) và SBPL vẽ lại cùng đường. + # Bật lại chỉ khi mặt nạ free khớp footprint có hướng (chưa có). + static_on: 1.0 # [s] mất liên thông liên tục chừng này mới nổ (người đi ngang < 1 s). + clean_start_margin: 0.20 # [m] thân còn cách vật ít nhất chừng này mới gọi replan (SBPL cần chỗ bắt đầu). + retry_backoff: 2.0 # [s] + + # --- contact: thân sắp chạm trên quỹ đạo thật -> phanh; kề mũi đứng yên -> cờ collision ----------- + contact: + enabled: true + action: recover # cờ collision (route collision). P4 bước 1: bật thật. + apply_command: true # true = phanh + bao tốc độ thật (P4). false = SHADOW: chỉ ghi "sẽ phanh/kẹp bao nhiêu", KHÔNG đụng lệnh. + # Khi true PHẢI tắt path_monitor/collision_enabled: hai chủ thể cùng phanh là deadlock 2/9 quay lại. + # Phanh mà cờ collision đã giơ nhưng route khoá -> controller bị báo "không có lệnh" -> controller_patience + # -> controlling_failed (cùng luật guard cũ), robot không đứng chết im lặng. + use_local_plan: auto # auto = dùng quỹ đạo local planner khi qua kiểm hợp lệ (pose đầu cách robot <= local_plan_start_tol), + # không thì cung (v, omega); true = ép dùng; false = luôn cung (như guard cũ). + local_plan_start_tol: 0.15 # [m] + lookahead: 1.5 # [m] quãng quỹ đạo cần dò. + confirm_cycles: 2 # [cycle] chạm trong quãng phanh liên tục chừng này thì phanh (0.1 s @ 20 Hz). + trigger_static_time: 1.0 # [s] tiếp xúc trong clean_start_margin còn đó chừng này (bất kể tốc độ) mới giơ cờ. + 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. + brake_decel: 0.35 # [m/s^2] decel dùng cho quãng phanh v^2/2a và bao tốc độ sqrt(2a(d - margin)). Đặt = decel thật của base. + release_hysteresis: 0.10 # [m] đã kề mũi (d <= clean_start_margin) thì còn kề tới khi d > margin + đây. Run 5/9 22:35: PRIEST đổi + # quỹ đạo mỗi cycle, d nhảy 0.08 <-> 0.25 quanh margin -> phanh bật/nhả 4 lần/s, đồng hồ giơ cờ reset + # liên tục nên không bao giờ nổ. TĂNG nếu còn thấy "receded" rồi "braking" trong < 0.5 s. + release_confirm_cycles: 4 # [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 "sắp chạm" + # (0.2 s @ 20 Hz). Người đi ngang thì chậm 0.2 s là chấp nhận; 1 = nhả ngay như bản 22:35. + envelope_margin: 0.10 # [m] bao tốc độ giữ dư chừng này so với ngưỡng phanh: v_cap = sqrt(2a(d - margin - dư)), bò min_speed + # cho tới d <= margin. 0 = bao đặt đúng biên phanh -> kẹp xong là chớm "sắp chạm", phanh/nhả liên tục + # khi tiếp cận (run 22:58: 9/28 lần phanh < 0.3 s). TĂNG nếu còn rung; robot dừng xa vật hơn đúng chừng đó. + standdown_min_travel: 0.10 # [m] detour do chính cờ collision vừa xong mà robot dịch chưa tới đây rồi lại "sắp chạm" -> kContact + # ĐỨNG RA: không phanh, không cờ, không bao — nhường local planner (lưới an toàn duy nhất). Detour từ + # trong khe là vô nghĩa: xoay là góc thân chạm (run 22:58: 3 detour trong 4 s rồi ABORT ở m1 và m8; + # mission 6 thoát được đúng lúc guard cạn route và nhường). 0 = tắt, hành vi như 22:58. + standdown_travel: 0.30 # [m] đứng ra cho tới khi robot đi được chừng này (hoặc quỹ đạo sạch release_confirm_cycles cycle) rồi + # vũ trang lại. TĂNG nếu thấy "re-armed" rồi "braking" lại ngay trong cùng khe. + min_speed: 0.05 # [m/s] bao tốc độ không kẹp thấp hơn đây; thấp hơn là dừng hẳn. + min_check_speed: 0.10 # [m/s] |v_cmd|, |v_đo| VÀ |v controller muốn| (trước bao/phanh) đều dưới đây mà chưa phanh = đang + # xoay tại chỗ / bò: KHÔNG phanh, KHÔNG cờ — góc thân quét vào ô kề bên khi xoay là việc của local + # planner (cùng vai path_monitor/collision_min_speed cũ). Tính cả "lệnh controller muốn" vì bao tốc + # độ kẹp lệnh về 0 trong margin: nếu chỉ nhìn lệnh đã kẹp thì robot dừng câm không cờ. Shadow 5/9: + # 3 lần "braking to zero" ngay đầu chặng (v 0.00–0.07) là nổ oan kiểu này; mọi tiếp xúc thật đều ở + # v >= 0.25. HẠ xuống 0 = dò cả khi xoay -> robot đứng cạnh vật bị ghim rồi gọi detour từ đó (churn). + envelope: true # bao tốc độ theo tiếp xúc (chỉ có tác dụng khi apply_command: true). + + # --- Ngân sách replan theo quãng đường (chống "đi một đoạn lại nổ" trong đám đông) ------------------- + replan_budget: + min_travel: 1.5 # [m] sau detour thành công, stall/unreachable im tới khi robot đi chừng này trên plan mới. + escalate_factor: 2.0 # [-] replan lặp trong escalate_window_m thì nhân ngân sách: 1.5 -> 3 -> 6 m. + escalate_window_m: 10.0 # [m] đi chừng này không replan thì về min_travel. + escalate_max: 6.0 # [m] trần leo thang; 0 = không trần. Run 22:35: 4 detour PRIEST trong 10 m -> 1.5 -> 3 -> 6 -> 12 m, + # kStall câm gần hết chặng. Phải >= min_travel. + + # --- Ghi JSONL cho replay / ML ------------------------------------------------------------------------ + logger: + enabled: true # true = ghi mỗi tick nặng + mỗi sườn sự kiện vào log_dir/envmon_.jsonl (bật 5/9 22:50 để + # đọc profile phanh/bao tốc độ; tắt khi lên robot nếu không cần replay). + log_dir: /tmp/env_monitor + flush_period: 1.0 # [s] diff --git a/config/runtime/path_monitor_params.yaml b/config/runtime/path_monitor_params.yaml index f091883..a1a9a54 100644 --- a/config/runtime/path_monitor_params.yaml +++ b/config/runtime/path_monitor_params.yaml @@ -33,7 +33,10 @@ path_monitor: # Công tắc CHUNG; tắt cái này là tắt cả bốn phép đo. # ► Chỉnh: false = đưa hành vi về đúng như trước 2026-08-04d (chỉ còn controller_patience lo). # Dùng làm đường lùi nhanh khi nghi cơ chế giám sát gây vấn đề ngoài hiện trường. - enabled: true + # ► P4 bước 3 (5/9 23:45): TẮT HẲN — env_monitor_params.yaml (EnvMonitor) thay cả bốn phép đo: kContact thay 3, + # kStall thay 4, kUnreachable thay 1; phép đo 2 (off_path) không có bản thay, chủ dự án đã bỏ từ trước. + # Bật lại chỉ khi env_monitor/enabled: false (hai bộ cùng giơ cờ là hai lần detour cho một sự kiện). + enabled: false # Profile được giám sát. docking/go_straight/rotate KHÔNG được detour: đường cong vào dock là một # thể thống nhất, cắt ghép nó là phá chính hình học đó. @@ -107,7 +110,11 @@ path_monitor: # # ► Khi bật cái này, TẮT các cổng dừng trong priest (collision_check_enabled, start_violation_ # stop_count) — hai chủ thể cùng ra lệnh dừng là deadlock 2/9 quay lại. - collision_enabled: true + # ► P4 5/9: TẮT — kContact của env_monitor_params.yaml thay (dò trên quỹ đạo THẬT của local planner + # thay cho cung (v, omega), quãng phanh theo decel, cổng xoay tại chỗ). Shadow 5/9: guard này thấy + # tiếp xúc 0.05 m ở v 0.50 nơi kContact thấy 0.36 m, và nổ oan khi robot xoay ra khỏi trụ kề mũi + # (churn giết mission 5). Bật lại CHỈ khi env_monitor/contact/apply_command: false. + collision_enabled: false # --- 3a. Dò cái gì ----------------------------------------------------------------------------- diff --git a/include/move_base2/config/move_base2_config.h b/include/move_base2/config/move_base2_config.h index b38d8ac..037016c 100644 --- a/include/move_base2/config/move_base2_config.h +++ b/include/move_base2/config/move_base2_config.h @@ -153,6 +153,13 @@ struct MoveBase2Config /// Đọc từ namespace con `path_monitor`. Tắt mặc định — bật bằng config, không bật ngầm. ControlLoopConfig::PathMonitorConfig path_monitor; + // --- EnvMonitor (thay PathMonitor; Test/ENV_MONITOR_PLAN.md) — namespace con `env_monitor` ------- + EnvMonitorConfig env_monitor; ///< lõi quyết định (stall / unreachable / contact / ngân sách). + EnvSamplingConfig env_sampling; ///< lấy mẫu ở cổng (nhịp, thân, hình học, quỹ đạo). + EnvLoggerConfig env_logger; ///< ghi JSONL cho replay/ML. Tắt mặc định. + /// Nhóm log `debug/env`: một dòng tóm tắt feature mỗi giây khi đang giám sát. Mặc định bật. + bool debug_env = true; + // --- Namespace cho các thành phần nạp plugin --------------------------------------------------- /// Namespace chứa danh sách recovery behavior (`/behaviors`) trong YAML. diff --git a/include/move_base2/control_loop.h b/include/move_base2/control_loop.h index d563959..aab3674 100644 --- a/include/move_base2/control_loop.h +++ b/include/move_base2/control_loop.h @@ -12,7 +12,9 @@ #include #include #include +#include #include +#include #include #include @@ -22,11 +24,14 @@ #include #include #include +#include +#include #include #include #include #include #include +#include #include #include #include @@ -66,6 +71,12 @@ struct ControlLoopDeps * này. */ PathCheckPort* path_check = nullptr; + + /** + * Nguồn dữ liệu của EnvMonitor (Test/ENV_MONITOR_PLAN.md). **Có thể null** — null thì EnvMonitor tắt + * hoàn toàn, mọi bộ test dùng cổng giả rơi vào nhánh này. + */ + EnvironmentPort* environment = nullptr; }; /** @@ -273,6 +284,12 @@ struct ControlLoopConfig PathMonitorConfig path_monitor; + // --- EnvMonitor (P3: chạy song song PathMonitor, shadow qua `action: log`) --------------------- + EnvMonitorConfig env_monitor; + EnvSamplingConfig env_sampling; + EnvLoggerConfig env_logger; + bool debug_env = true; ///< nhóm log `debug/env`: một dòng tóm tắt feature mỗi giây khi đang giám sát. + bool validate(std::string& error) const; std::string describe() const; }; @@ -480,6 +497,13 @@ private: void updateProgressMonitor(const robot::Time& now, std::size_t from_index, const robot_geometry_msgs::PoseStamped& robot_pose); void resetProgressMonitor(); + + /** + * @brief EnvMonitor: lấy mẫu môi trường (nặng theo `check_period`, quỹ đạo mỗi cycle), chạy lõi, giữ + * verdict cho state machine và trọng tài của CYCLE NÀY. Gọi ngay sau updatePathMonitor. + */ + void updateEnvMonitor(const robot::Time& now, double dt, const robot_geometry_msgs::PoseStamped& robot_pose, + bool pose_available, bool costmap_stale); /// @brief Dựng lại cache độ dài cộng dồn của latest_plan_ và xoá ring (mẫu cũ thuộc plan cũ). void rebuildPlanArcLength(); @@ -604,6 +628,23 @@ private: robot::Time last_plan_applied_; bool has_last_plan_applied_ = false; + // --- EnvMonitor ------------------------------------------------------------------------------- + EnvMonitor env_monitor_; + EnvVerdict env_verdict_; ///< verdict của cycle này (vào state machine + trọng tài). + EnvGeometry env_geometry_; ///< mẫu nặng gần nhất (giữ giữa hai tick 5 Hz để log/ghi). + robot::Time last_env_heavy_; + bool has_last_env_heavy_ = false; + robot::Time last_env_debug_; + bool has_last_env_debug_ = false; + bool env_brake_ = false; ///< cycle này EnvMonitor đòi lệnh 0 (chỉ khi apply_command). + bool env_used_local_plan_ = false; + double env_contact_dist_ = std::numeric_limits::quiet_NaN(); ///< [m] tiếp xúc gần nhất (inf = trống) cho log. + double env_controller_v_ = 0.0; ///< [m/s] lệnh controller muốn ở cycle trước, trước bao/phanh/trọng tài. + std::size_t env_plan_index_ = 0; ///< index plan đang bám cho EnvMonitor (trackedNearestIndex). + bool env_plan_index_valid_ = false; ///< false = plan mới, tick nặng kế tìm lại toàn plan. + robot_nav_2d_msgs::Path2D env_local_plan_; ///< bộ đệm quỹ đạo local planner, tránh cấp phát mỗi cycle. + std::unique_ptr env_logger_; + robot_geometry_msgs::PoseStamped oscillation_origin_; bool has_oscillation_origin_ = false; diff --git a/include/move_base2/core/env_monitor.h b/include/move_base2/core/env_monitor.h new file mode 100644 index 0000000..dc4496b --- /dev/null +++ b/include/move_base2/core/env_monitor.h @@ -0,0 +1,357 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * move_base2 — lõi quyết định của EnvMonitor (Test/ENV_MONITOR_PLAN.md §2.3, P2). + * + * Thuần: không costmap, không TF, không log, không cấp phát sau `configure`. 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 MOVE_BASE2_CORE_ENV_MONITOR_H_ +#define MOVE_BASE2_CORE_ENV_MONITOR_H_ + +#include +#include +#include +#include + +#include + +namespace move_base2 +{ + +/** + * @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 (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; + + /** + * 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] + 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; +}; + +/** + * @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; + double robot_x = 0.0; ///< [m] pose robot, frame bất kỳ nhưng cố định (đo quãng đường). + 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::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::quiet_NaN(); + bool controller_valid = true; ///< controller cycle trước có ra lệnh không. + double d_goal = std::numeric_limits::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::infinity(); ///< [m] + double edt_body_min = std::numeric_limits::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::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 +{ + 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::infinity(); ///< [m/s] trần |v| cycle này; +inf = không kẹp. + + 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 stall_muted = false; ///< detected nhưng bị cổng/ngân sách/backoff/grace giữ lại. + double net_disp = std::numeric_limits::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 unreachable_muted = false; + double eff_geo = std::numeric_limits::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. +}; + +/** + * @class EnvMonitor + * @brief Lõi thuần. Không thread-safe; chỉ control thread gọi. + */ +class EnvMonitor +{ +public: + EnvMonitor() = default; + + bool configure(const EnvMonitorConfig& config, std::string& error); + bool configured() const + { + return configured_; + } + const EnvMonitorConfig& config() const + { + return config_; + } + + /// @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 from_contact recovery này do cờ collision của chính monitor gọi (trigger kCollision). + void onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome, bool from_contact = false); + + /// @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: + 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 = 128; + bool oldestPos(const robot::Time& now, PosSample& out) const; + + void clearWindow(); + void clearPosWindow(); + bool oldestInWindow(const robot::Time& now, HeavySample& out) const; + void updateStall(const EnvSample& s, EnvVerdict& v); + void updateUnreachable(const EnvSample& s, EnvVerdict& v); + void updateContact(const EnvSample& s, EnvVerdict& v); + + EnvMonitorConfig config_; + bool configured_ = false; + + // Tích luỹ + double cmd_accum_ = 0.0; ///< [m] Σ|v_cmd|·dt + double travel_total_ = 0.0; ///< [m] odometer từ pose + bool has_last_pose_ = false; + double last_x_ = 0.0; + double last_y_ = 0.0; + + // Mốc chặng / plan + bool has_goal_ = false; + double cmd_at_goal_ = 0.0; + bool has_plan_time_ = false; + robot::Time plan_time_; + + // Cửa sổ mẫu nặng + std::array ring_{}; + std::size_t ring_head_ = 0; + std::size_t ring_count_ = 0; + std::array pos_ring_{}; + std::size_t pos_head_ = 0; + std::size_t pos_count_ = 0; + bool wandering_ = false; + double net_disp_ = std::numeric_limits::quiet_NaN(); + + // 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_; + + // kUnreachable + 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_; + + // kContact + int contact_streak_ = 0; + int release_streak_ = 0; ///< cycle liên tiếp không "sắp chạm" trong khi đang phanh. + 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; + 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. + + // 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 move_base2 + +#endif // MOVE_BASE2_CORE_ENV_MONITOR_H_ diff --git a/include/move_base2/core/grid_analysis.h b/include/move_base2/core/grid_analysis.h new file mode 100644 index 0000000..76c6647 --- /dev/null +++ b/include/move_base2/core/grid_analysis.h @@ -0,0 +1,278 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * move_base2 — phân tích hình học trên local costmap cho EnvMonitor (Test/ENV_MONITOR_PLAN.md, P1). + * + * Hàm thuần trên `robot_costmap_2d::Costmap2D`, không giữ trạng thái ngoài @ref GridScratch (bộ đệm + * tái dùng để không cấp phát trong control loop). Không log, không TF, không quyết định gì — người + * dùng là `EnvMonitor` và bộ phân tích offline `Test/env_monitor_tools/envmon_offline.py`, hai bên + * phải ra cùng số trên cùng lưới. + * + * Ngữ nghĩa cost, cố ý và khác `plan_inspector::checkPlan`: + * - Vật cản là ô có cost >= `lethal_threshold` (mặc định 254 = LETHAL). Vành inflation 253 KHÔNG + * được dùng ở đây: `inflation_radius` của cây sim (0.3 m) nhỏ hơn inscribed (0.48 m) nên vành đó + * bị cắt cụt; mọi biên an toàn được tính lại từ EDT tới ô lethal cộng bán kính thân. + * - `NO_INFORMATION` KHÔNG phải vật cản, cùng quy ước với SBPL (`unknown_is_free`). + * - Ra ngoài lưới = không có dữ liệu, không phải bị chắn. + * + * Author: DuongTD + *********************************************************************/ +#ifndef MOVE_BASE2_CORE_GRID_ANALYSIS_H_ +#define MOVE_BASE2_CORE_GRID_ANALYSIS_H_ + +#include +#include +#include +#include + +#include + +#include + +namespace robot_costmap_2d { class Costmap2D; } + +namespace move_base2 +{ + +/** + * @struct GridScratch + * @brief Bộ đệm của một lượt phân tích: EDT, mặt nạ tự do, trường địa trắc, hàng đợi. + * + * Gọi @ref analyzeGrid mỗi tick (5 Hz) rồi đưa cùng một scratch cho mọi hàm bên dưới. Kích thước + * chỉ đổi khi costmap đổi kích thước (`ensure`), sau đó không cấp phát heap nữa. + */ +struct GridScratch +{ + unsigned int width = 0; + unsigned int height = 0; + double resolution = 0.0; ///< [m/ô] + double origin_x = 0.0; ///< [m] toạ độ góc dưới-trái của ô (0,0), frame của lưới + double origin_y = 0.0; ///< [m] + double free_radius = 0.0; ///< [m] bán kính đã dùng cho @ref free + + std::vector edt; ///< [m] khoảng cách tâm ô -> ô lethal gần nhất; 0 tại ô lethal + std::vector free; ///< 1 = tâm robot đặt được (edt >= free_radius) + std::vector geo; ///< [m] trường địa trắc của lượt @ref computeGeodesic gần nhất + std::vector baseline; ///< index ô lethal đang nằm dưới thân đệm (sorted), cho sweep + + // Bộ đệm nội bộ của EDT (Felzenszwalb), Dijkstra và dò chu vi — không đọc từ ngoài. + std::vector f_; + std::vector d_; + std::vector v_; + std::vector z_; + std::vector tmp_; + std::vector heap_; + std::vector perim_; ///< (bx, by, edge) x N — chu vi footprint đệm trong frame thân. + + /// @brief Đổi kích thước theo lưới; giữ nguyên nếu đã khớp. Trả false nếu lưới rỗng. + bool ensure(const robot_costmap_2d::Costmap2D& grid); + + bool inBounds(int mx, int my) const + { + return mx >= 0 && my >= 0 && static_cast(mx) < width && + static_cast(my) < height; + } + std::size_t index(unsigned int mx, unsigned int my) const + { + return static_cast(my) * width + mx; + } + /// @brief Ô chứa điểm (x, y) frame lưới. Trả false nếu ra ngoài. + bool toCell(double x, double y, unsigned int& mx, unsigned int& my) const; + /// @brief Tâm ô (mx, my) [m]. + void cellCenter(unsigned int mx, unsigned int my, double& x, double& y) const; +}; + +/** + * @brief Bước 1 của mỗi tick: EDT tới ô >= @p lethal_threshold và mặt nạ tự do `edt >= free_radius`. + * + * EDT chính xác (Euclid), hai lượt 1-D theo Felzenszwalb–Huttenlocher, O(số ô). Lưới 160x160 ~ 0.3 ms. + * Lưới không có ô lethal nào -> edt = +inf mọi nơi, mọi ô đều free. + * + * @param free_radius [m] bán kính mà tâm robot phải cách vật cản để coi ô là đặt được — inscribed + * radius KHÔNG đệm (cùng biên với SBPL, luật R2 của plan: monitor không được khắt khe hơn + * planner vừa lập path). + * @return false nếu lưới rỗng. + */ +bool analyzeGrid(const robot_costmap_2d::Costmap2D& grid, unsigned char lethal_threshold, + double free_radius, GridScratch& scratch); + +/// @brief [m] EDT tại điểm (x, y) frame lưới; NaN nếu ra ngoài lưới hoặc chưa @ref analyzeGrid. +double distanceAt(const GridScratch& scratch, double x, double y); + +/** + * @brief Trường địa trắc từ ô (tx, ty) trên mặt nạ tự do: Dijkstra 8 láng giềng, cấm cắt góc. + * + * Cắt góc bị cấm: bước chéo chỉ hợp lệ khi CẢ HAI ô trực giao trung gian cũng free — không thì + * đường "chui" qua hai ô chéo mà thân không lọt. Trọng số `res` và `res*sqrt(2)`. Kết quả ở + * `scratch.geo`, +inf = không tới được. + * + * @param[out] visited số ô đã lấy ra khỏi hàng đợi — để log chi phí. + * @param stop_index dừng sớm ngay khi ô này được lấy ra (giá trị của nó đã đúng); các ô còn lại giữ + * +inf nên KHÔNG đọc trường ở chỗ khác sau khi dừng sớm. Mặc định = chạy trọn thành phần liên + * thông (cần khi muốn biết một ô có tới được không). + * @return false nếu (tx, ty) ngoài lưới hoặc không free (không tính gì). + */ +bool computeGeodesic(unsigned int tx, unsigned int ty, GridScratch& scratch, + std::size_t* visited = nullptr, + std::size_t stop_index = static_cast(-1)); + +/** + * @brief Ô free gần (mx, my) nhất trong bán kính @p max_dist [m]; chính nó nếu đã free. + * @return false nếu không có ô free nào trong bán kính. + */ +bool nearestFreeCell(const GridScratch& scratch, unsigned int mx, unsigned int my, double max_dist, + unsigned int& fx, unsigned int& fy); + +/** + * @brief [m] Khoảng trống của thân: min EDT trên chu vi hình chữ nhật thân (KHÔNG đệm) tại pose. + * + * Đây là `edt_body_min` của plan — điều kiện "còn đất sạch để SBPL bắt đầu". Thân: mũi @p front, + * đuôi @p rear (số dương), nửa rộng @p side, tính từ base_link, frame lưới. Điểm chu vi nằm ngoài + * lưới bị bỏ qua; NaN nếu không điểm nào trong lưới. + */ +double bodyClearance(const GridScratch& scratch, double x, double y, double yaw, double front, + double rear, double side); + +/** + * @struct CostToGoParams + * @brief Tham số của @ref costToGo. Đơn vị mét. + */ +struct CostToGoParams +{ + double target_backoff = 0.5; ///< [m] T bị bẩn thì lùi dọc plan tối đa chừng này để tìm T free. + double robot_snap = 0.35; ///< [m] ô robot không free (đang ôm sát vật) thì lấy ô free gần nhất trong bán kính này. + /// [m] T = pose plan ở quãng này dọc plan kể từ from_index (vẫn kẹp trong cửa sổ). 0 = T là điểm plan rời cửa sổ + /// (bản cũ). Lý do (run 5/9 23:37): plan vòng chữ U trong tầm cửa sổ — robot đi theo plan về tây, phần plan quay + /// về đông rời cửa sổ sớm hơn, T LÙI dọc plan, arc_rest tăng bù đúng phần geo giảm, tiến độ thật đo thành 0 + /// -> stall oan. T ở quãng cố định chỉ tiến theo index, và geodesic 2 m ít bị lật liên thông hơn 6–9 m. + double exit_ahead = 0.0; +}; + +/** + * @struct CostToGoResult + * @brief Kết quả @ref costToGo — thước đo tiến độ địa trắc (v1 trong ENV_MONITOR_PLAN.md §4.4). + */ +struct CostToGoResult +{ + enum class Target + { + kExit, ///< T = pose plan xa nhất còn trong cửa sổ (plan rời cửa sổ). + kGoal, ///< T = pose cuối plan (goal nằm trong cửa sổ). + kBackedOff, ///< T đã lùi dọc plan vì pose gốc không free. + kBlockedExit, ///< Không tìm được T free trong `target_backoff` — "đích bị bịt". + kAhead ///< T = pose plan ở quãng `exit_ahead` dọc plan (chưa tới goal, chưa rời cửa sổ). + }; + + bool conclusive = false; ///< false = không kết luận được (plan rỗng, robot ngoài lưới, robot trong vật cản). + bool reachable = false; ///< Có đường địa trắc từ robot tới T không. Chỉ có nghĩa khi conclusive. + bool robot_in_ring = false; ///< Ô robot không free, đã snap sang ô free gần nhất. + Target target = Target::kExit; + std::size_t target_index = 0; ///< Index của T trên plan. + double geo_to_exit = std::numeric_limits::infinity(); ///< [m] geo(robot -> T). + double arc_rest = 0.0; ///< [m] độ dài plan từ T tới cuối. + double cost_to_go = std::numeric_limits::infinity(); ///< [m] geo_to_exit + arc_rest. + std::size_t cells_visited = 0; ///< Chi phí Dijkstra, để log. +}; + +/** + * @brief `cost_to_go = geo(robot -> T) + arc(T -> goal)`, T = điểm plan rời cửa sổ. + * + * Vì sao tham chiếu là PLAN chứ không phải bản đồ tĩnh: plan đang bám đã chứa detour SBPL, còn bản + * đồ tĩnh không chứa vật cản chưa vẽ (bãi trụ trong sim, kệ tạm ngoài đời) — đo trên bag 5/9 cho + * thấy phương án bản đồ tĩnh nổ oan khi robot đi đúng detour. Vì sao geo chứ không phải Euclid: + * chui vào túi mở về phía goal thì Euclid vẫn giảm, geo thì tăng (mission 2 và mission 8 ngày 5/9). + * + * Yêu cầu @ref analyzeGrid đã chạy trên scratch ở tick này. @p plan_to_grid quy plan về frame lưới. + * @p robot_x/@p robot_y là pose robot trong frame lưới. + */ +CostToGoResult costToGo(const std::vector& plan, + std::size_t from_index, double robot_x, double robot_y, + const CostToGoParams& params, const PlanarTransform& plan_to_grid, + GridScratch& scratch); + +/** + * @struct CorridorParams + * @brief Tham số quét hành lang dọc plan (@ref scanCorridor). + */ +struct CorridorParams +{ + double horizon = 3.0; ///< [m] quãng plan cần quét. + double body_width = 0.96; ///< [m] bề rộng thân. + double margin = 0.0; ///< [m] cộng mỗi bên vào bề rộng thân. 0 = đúng biên SBPL (luật R2). + double side_cap = 1.5; ///< [m] trần quãng trống đo về mỗi bên. +}; + +/** + * @struct CorridorResult + * @brief Kết quả @ref scanCorridor. Hai đại lượng độc lập, cùng đo dọc plan từ `from_index`. + */ +struct CorridorResult +{ + std::size_t scanned = 0; ///< Số pose plan đã quét trong lưới. 0 = không kết luận gì. + /// [m] Quãng dọc plan tới pose đầu tiên có EDT(tâm) < free_radius; = horizon nếu không có. + double plan_clear_ahead = 0.0; + /// [m] Bề rộng trống nhỏ nhất vuông góc với plan (trái + phải, mỗi bên trần side_cap). + double min_width = std::numeric_limits::infinity(); + /// [m] Quãng dọc plan tới mẫu đầu tiên có bề rộng < body_width + 2*margin; +inf nếu không có. + double block_dist = std::numeric_limits::infinity(); +}; + +/** + * @brief Quét hành lang: plan còn sạch bao xa, và chỗ hẹp đầu tiên thân không lọt cách bao xa. + * + * Bề rộng đo VUÔNG GÓC với plan tại từng pose: đi theo pháp tuyến hai phía cho tới ô lethal hoặc ra + * lưới, mỗi phía trần `side_cap`. KHÔNG dùng 2*EDT(tâm): plan sượt tường một bên mà bên kia trống + * vẫn là hành lang rộng (mission 1 ngày 5/9). + */ +CorridorResult scanCorridor(const std::vector& plan, + std::size_t from_index, const CorridorParams& params, + const PlanarTransform& plan_to_grid, const GridScratch& scratch); + +/** + * @struct SweepParams + * @brief Hình học và ngưỡng của @ref sweepTrajectory. + */ +struct SweepParams +{ + double front = 0.583; ///< [m] mũi tính từ base_link. + double rear = 0.583; ///< [m] đuôi. + double side = 0.48; ///< [m] nửa bề rộng. + double padding = 0.05; ///< [m] biên an toàn tường minh cộng mọi cạnh (chỉ cho phanh). + double lookahead = 1.5; ///< [m] quãng quỹ đạo cần dò. + unsigned char lethal_threshold = 254; + bool exclude_baseline = true; ///< Bỏ ô lethal đang nằm dưới thân đệm tại pose hiện tại. +}; + +/** + * @struct SweepResult + * @brief Kết quả @ref sweepTrajectory. + */ +struct SweepResult +{ + bool conclusive = false; ///< false = quỹ đạo rỗng hoặc không bắt đầu gần robot. + bool blocked = false; + double distance = std::numeric_limits::infinity(); ///< [m] quãng dọc quỹ đạo tới mẫu chạm. + std::size_t sample = 0; ///< Index pose quỹ đạo chạm. + int hit_edge = -1; ///< 0 phải, 1 mũi, 2 trái, 3 đuôi. + int baseline_cells = 0; + std::size_t scanned = 0; +}; + +/** + * @brief Kéo footprint đệm dọc QUỸ ĐẠO THẬT của local planner, dò chu vi ở từng pose. + * + * Thay cho cung (v, omega) không đổi của `checkMotion` khi planner có quỹ đạo (`getLocalPlan()`). + * Quỹ đạo trong frame lưới, pose đầu phải cách robot <= @p start_tol (không thì trả không kết luận + * — bên gọi rơi về cung). Bước giữa hai pose lớn hơn một ô thì chèn thêm mẫu để tường mỏng không lọt. + * Baseline: ô lethal đang nằm dưới thân đệm tại (robot_x, robot_y, robot_yaw) không được tính là + * chạm — cùng luật với checkMotion (2026-09-04). + */ +SweepResult sweepTrajectory(const std::vector& trajectory, + double robot_x, double robot_y, double robot_yaw, double start_tol, + const SweepParams& params, const robot_costmap_2d::Costmap2D& grid, + GridScratch& scratch); + +} // namespace move_base2 + +#endif // MOVE_BASE2_CORE_GRID_ANALYSIS_H_ diff --git a/include/move_base2/core/plan_inspector.h b/include/move_base2/core/plan_inspector.h index dcffc1c..45fcd5e 100644 --- a/include/move_base2/core/plan_inspector.h +++ b/include/move_base2/core/plan_inspector.h @@ -74,6 +74,19 @@ bool planarTransform(const tf3::BufferCore& tf, const std::string& from, const s std::size_t nearestIndex(const std::vector& plan, const robot_geometry_msgs::PoseStamped& pose); +/** + * @brief Như @ref nearestIndex nhưng chỉ tìm quanh @p hint: lùi tối đa @p back_m và tiến tối đa + * @p ahead_m dọc plan (theo chiều dài cung). + * + * Detour SBPL uốn quanh trụ có đoạn sau đi sát chỗ robot đang đứng: `nearestIndex` toàn plan nhảy + * sang đoạn đó, điểm thoát T của EnvMonitor đổi và `cost_to_go` nhảy +8 m trong 1 s (run 5/9 22:35, + * eff_geo −4,96 giả). Bên gọi giữ index qua các cycle và reset về `nearestIndex` khi có plan mới. + * @p hint vượt cỡ plan thì được kẹp; plan < 2 pose → 0. + */ +std::size_t trackedNearestIndex(const std::vector& plan, + const robot_geometry_msgs::PoseStamped& pose, std::size_t hint, + double back_m, double ahead_m); + /** * @brief [m] Khoảng cách vuông góc từ @p pose tới polyline của @p plan. * diff --git a/include/move_base2/io/env_logger.h b/include/move_base2/io/env_logger.h new file mode 100644 index 0000000..0682f17 --- /dev/null +++ b/include/move_base2/io/env_logger.h @@ -0,0 +1,77 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * move_base2 — ghi feature + verdict của EnvMonitor ra JSONL (Test/ENV_MONITOR_PLAN.md §2.6). + * + * Mục đích: replay offline để chỉnh ngưỡng không cần sim, và là dữ liệu huấn luyện ML sau này. Mỗi + * dòng là một tick nặng (5 Hz) hoặc một sườn sự kiện. Tắt mặc định; khi tắt không cấp phát, không mở + * file. + * + * Ghi trên control thread: dòng ~400 byte, gom vào buffer và flush mỗi `flush_period` — một lần + * `write()` vài kB mỗi giây. Nếu đo thấy ảnh hưởng chu kỳ thì chuyển sang thread riêng. + * + * Author: DuongTD + *********************************************************************/ +#ifndef MOVE_BASE2_IO_ENV_LOGGER_H_ +#define MOVE_BASE2_IO_ENV_LOGGER_H_ + +#include +#include +#include + +#include + +#include +#include + +namespace move_base2 +{ + +struct EnvLoggerConfig +{ + bool enabled = false; + std::string log_dir = "/tmp/env_monitor"; ///< tạo nếu chưa có; file `envmon_.jsonl`. + double flush_period = 1.0; ///< [s] + + bool validate(std::string& error) const; +}; + +class EnvLogger +{ +public: + EnvLogger() = default; + ~EnvLogger(); + EnvLogger(const EnvLogger&) = delete; + EnvLogger& operator=(const EnvLogger&) = delete; + + /// @return false kèm lý do nếu không mở được file. Không mở gì khi `config.enabled == false`. + bool open(const EnvLoggerConfig& config, std::string& error); + bool isOpen() const + { + return out_.is_open(); + } + const std::string& path() const + { + return path_; + } + + /// @brief Một dòng JSON. @p geometry có thể null (tick nhẹ). @p state là tên state machine. + void record(const robot::Time& now, const EnvSample& sample, const EnvVerdict& verdict, + const EnvGeometry* geometry, const char* state, std::uint64_t mission_id, + bool used_local_plan); + + void flush(); + +private: + EnvLoggerConfig config_; + std::ofstream out_; + std::string path_; + std::string buffer_; + robot::Time last_flush_; + bool has_last_flush_ = false; +}; + +} // namespace move_base2 + +#endif // MOVE_BASE2_IO_ENV_LOGGER_H_ diff --git a/include/move_base2/navigation_runtime.h b/include/move_base2/navigation_runtime.h index 13a86ef..99bf3c2 100644 --- a/include/move_base2/navigation_runtime.h +++ b/include/move_base2/navigation_runtime.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -132,6 +133,41 @@ private: mutable std::vector baseline_scratch_ = std::vector(64); }; +/** + * @class CostmapEnvironment + * @brief Hiện thực @ref EnvironmentPort trên costmap ĐIỀU KHIỂN (local) — nguồn dữ liệu của EnvMonitor. + * + * Đọc snapshot (`snapshot_for_readers`) qua `getCostmapForRead()` sau `refresh()`; không có snapshot thì + * giữ mutex trong lúc phân tích (~1 ms). Toán nằm ở `core/grid_analysis`; ở đây chỉ TF + lưới + thân. + */ +class CostmapEnvironment final : public EnvironmentPort +{ +public: + void setCostmap(robot_costmap_2d::Costmap2DROBOT* costmap) + { + costmap_ = costmap; + } + void setTf(const std::shared_ptr& tf) + { + tf_ = tf; + } + + void refresh() override; + bool sampleGeometry(const EnvGeometryRequest& request, EnvGeometry& out) override; + bool sweepTrajectory(const EnvTrajectoryRequest& request, SweepResult& out, + bool& used_local_plan) override; + bool robotBodyExtents(double& front, double& rear, double& side) const override; + +private: + /// Lưới để đọc + có phải lưới sống (cần khoá) không. nullptr = chưa có costmap. + robot_costmap_2d::Costmap2D* gridForRead(bool& live) const; + + robot_costmap_2d::Costmap2DROBOT* costmap_ = nullptr; + std::shared_ptr tf_; + GridScratch scratch_; ///< chỉ control thread dùng + std::vector traj_scratch_; ///< quỹ đạo đã quy về frame lưới +}; + /** * @class CostmapStatusAdapter * @brief Cổng "costmap còn hạn không" lấy từ costmap thật. @@ -355,6 +391,9 @@ private: /// Guard "không đi mù": hỏi costmap điều khiển xem observation buffer còn hạn không. CostmapStatusAdapter costmap_status_; + /// Nguồn dữ liệu của EnvMonitor: cùng costmap local với PathMonitor cũ và detour. + CostmapEnvironment environment_; + std::unique_ptr global_costmap_; std::unique_ptr local_costmap_; diff --git a/include/move_base2/ports/controller_port.h b/include/move_base2/ports/controller_port.h index b785333..f26ad8c 100644 --- a/include/move_base2/ports/controller_port.h +++ b/include/move_base2/ports/controller_port.h @@ -97,6 +97,17 @@ public: */ virtual void setMeasuredVelocity(const robot_geometry_msgs::Twist& velocity) = 0; + /** + * @brief Vận tốc đo được gần nhất đã nhận qua @ref setMeasuredVelocity (EnvMonitor dùng để tính quãng + * phanh và phát hiện trượt). Mặc định "chưa có" để cổng giả/hiện thực cũ không đổi. + * @return false nếu chưa từng nhận giá trị nào. + */ + virtual bool measuredVelocity(robot_geometry_msgs::Twist& out) const + { + (void)out; + return false; + } + /** * @brief Đặt trần vận tốc thẳng. **Dấu chọn chiều**: dương = tiến, âm = lùi. * diff --git a/include/move_base2/ports/environment_port.h b/include/move_base2/ports/environment_port.h new file mode 100644 index 0000000..d70fe6f --- /dev/null +++ b/include/move_base2/ports/environment_port.h @@ -0,0 +1,145 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * move_base2 — cổng môi trường cho EnvMonitor: "quanh robot lúc này trông thế nào". + * + * Kế thừa vai trò của `PathCheckPort` (Test/ENV_MONITOR_PLAN.md §2.5): lõi hỏi, hạ tầng trả lời. + * Cổng lo costmap + TF; toán nằm ở `core/grid_analysis`; quyết định nằm ở `core/env_monitor`. Nhờ vậy + * `ControlLoop` kiểm được bằng cổng giả (mặc định = "không kết luận được"). + * + * @note Chỉ control thread được gọi. Hiện thực thật đọc snapshot costmap (`snapshot_for_readers`) hoặc + * giữ mutex khi không có snapshot. + * + * Author: DuongTD + *********************************************************************/ +#ifndef MOVE_BASE2_PORTS_ENVIRONMENT_PORT_H_ +#define MOVE_BASE2_PORTS_ENVIRONMENT_PORT_H_ + +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace move_base2 +{ + +/** + * @struct EnvSamplingConfig + * @brief Tham số LẤY MẪU của EnvMonitor (phần chạy ở cổng / ControlLoop, không phải lõi quyết định). + */ +struct EnvSamplingConfig +{ + double check_period = 0.2; ///< [s] nhịp phần nặng (EDT + Dijkstra + hành lang). + int lethal_threshold = 254; ///< cost >= đây là vật cản thật. KHÔNG hạ xuống 253. + /// [m] thân robot tính từ base_link; cả ba = 0 -> lấy footprint không đệm của costmap mỗi lượt. + double body_front = 0.0; + double body_rear = 0.0; + double body_side = 0.0; + double padding = 0.05; ///< [m] đệm chỉ cho dò tiếp xúc; liên thông dùng biên SBPL (0). + double horizon = 3.0; ///< [m] quãng plan quét hành lang. + double corridor_margin = 0.0; ///< [m] mỗi bên, cộng vào bề rộng thân khi xét khe. 0 = biên SBPL. + double corridor_cap = 1.5; ///< [m] trần quãng trống mỗi bên. + double target_backoff = 0.5; ///< [m] T bẩn thì lùi dọc plan tối đa chừng này. + double robot_snap = 0.35; ///< [m] ô robot không free thì snap sang ô free gần nhất trong đây. + /// [m] Cửa sổ bám index plan qua các tick: lùi tối đa track_back, tiến tối đa track_ahead dọc plan kể từ + /// index tick trước (xem trackedNearestIndex). Plan mới -> tìm lại toàn plan một lần. + double track_back = 1.0; + double track_ahead = 3.0; + /// [m] Điểm thoát T của cost_to_go ở quãng này dọc plan kể từ index đang bám (kẹp trong cửa sổ); 0 = T là điểm + /// plan rời cửa sổ (bản cũ, lùi được khi cửa sổ trôi -> stall oan trên plan chữ U, run 5/9 23:37). + double exit_ahead = 2.0; + std::string use_local_plan = "auto"; ///< auto | true | false — quỹ đạo local planner cho dò tiếp xúc. + double local_plan_start_tol = 0.15; ///< [m] pose đầu quỹ đạo phải cách robot dưới đây mới tin. + double contact_lookahead = 1.5; ///< [m] quãng quỹ đạo cần dò. + std::vector profiles{ MotionProfile::kPosition }; + + bool monitors(MotionProfile profile) const; + bool validate(std::string& error) const; +}; + +/// @brief Yêu cầu lấy mẫu hình học nặng (5 Hz). +struct EnvGeometryRequest +{ + const std::vector* plan = nullptr; ///< frame map, KHÔNG null. + std::size_t from_index = 0; + robot_geometry_msgs::PoseStamped robot_pose; ///< frame của cổng pose. + const EnvSamplingConfig* sampling = nullptr; + double front = 0.0; ///< [m] thân đã chốt (config hoặc footprint). + double rear = 0.0; + double side = 0.0; +}; + +/// @brief Kết quả lấy mẫu hình học. +struct EnvGeometry +{ + bool valid = false; + double free_radius = 0.0; ///< [m] bán kính tâm đã dùng (inscribed). + CostToGoResult cost; + double edt_body_min = std::numeric_limits::quiet_NaN(); + CorridorResult corridor; +}; + +/// @brief Yêu cầu dò tiếp xúc dọc quỹ đạo (mỗi cycle). +struct EnvTrajectoryRequest +{ + robot_geometry_msgs::PoseStamped robot_pose; + const robot_nav_2d_msgs::Path2D* local_plan = nullptr; ///< quỹ đạo local planner; null = không có. + double v = 0.0; ///< [m/s] lệnh gần nhất — cho cung (v, omega) khi không dùng được quỹ đạo. + double omega = 0.0; ///< [rad/s] + const EnvSamplingConfig* sampling = nullptr; + double front = 0.0; + double rear = 0.0; + double side = 0.0; +}; + +class EnvironmentPort +{ +public: + virtual ~EnvironmentPort() = default; + + /// @brief Một lần đầu cycle: làm mới snapshot costmap (nếu bật) để cả lượt đọc cùng một lưới. + virtual void refresh() + { + } + + /// @return false = KHÔNG kết luận được (thiếu costmap/TF). Bên gọi không được suy thành gì cả. + virtual bool sampleGeometry(const EnvGeometryRequest& request, EnvGeometry& out) + { + (void)request; + (void)out; + return false; + } + + /** + * @brief Kéo footprint đệm dọc quỹ đạo local planner; không dùng được thì dọc cung (v, omega). + * @param[out] used_local_plan quỹ đạo thật đã được dùng (false = đã rơi về cung). + */ + virtual bool sweepTrajectory(const EnvTrajectoryRequest& request, SweepResult& out, + bool& used_local_plan) + { + (void)request; + (void)out; + used_local_plan = false; + return false; + } + + /// @brief Thân robot từ footprint KHÔNG đệm của costmap. false = không có. + virtual bool robotBodyExtents(double& front, double& rear, double& side) const + { + (void)front; + (void)rear; + (void)side; + return false; + } +}; + +} // namespace move_base2 + +#endif // MOVE_BASE2_PORTS_ENVIRONMENT_PORT_H_ diff --git a/include/move_base2/runners/controller_runner.h b/include/move_base2/runners/controller_runner.h index 53ff4f1..3d2948a 100644 --- a/include/move_base2/runners/controller_runner.h +++ b/include/move_base2/runners/controller_runner.h @@ -171,6 +171,7 @@ public: bool isGoalReached() override; void getLocalPlan(robot_nav_2d_msgs::Path2D& plan) override; void setMeasuredVelocity(const robot_geometry_msgs::Twist& velocity) override; + bool measuredVelocity(robot_geometry_msgs::Twist& out) const override; bool setTwistLinear(const robot_geometry_msgs::Vector3& linear) override; bool setTwistAngular(const robot_geometry_msgs::Vector3& angular) override; std::string activeController() const override; @@ -266,6 +267,7 @@ private: bool has_limit_angular_ = false; robot_geometry_msgs::Twist measured_velocity_; + bool has_measured_velocity_ = false; }; } // namespace move_base2 diff --git a/src/config/move_base2_config.cpp b/src/config/move_base2_config.cpp index d04f240..7df4c90 100644 --- a/src/config/move_base2_config.cpp +++ b/src/config/move_base2_config.cpp @@ -69,6 +69,7 @@ void readBinding(robot::NodeHandle& nh, const std::string& ns, ProfileBinding& b void readSensors(robot::NodeHandle& nh, SensorGatewayConfig& sensors); void readDebug(robot::NodeHandle& nh, MoveBase2Config& config); +void readEnvMonitor(robot::NodeHandle& nh, MoveBase2Config& config); void readSensorStore(robot::NodeHandle& nh, MoveBase2Config& config); @@ -271,6 +272,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config) readSensorStore(nh, config); readDebug(nh, config); readPathMonitor(nh, config.path_monitor); + readEnvMonitor(nh, config); readBool(nh, "docking_requires_marker", config.docking_requires_marker); readString(nh, "recovery_namespace", config.recovery_namespace); @@ -320,6 +322,124 @@ void readDebug(robot::NodeHandle& nh, MoveBase2Config& config) readBool(debug_nh, "state", config.debug_state); readBool(debug_nh, "plan", config.debug_plan); readBool(debug_nh, "skip", config.debug_skip); + readBool(debug_nh, "env", config.debug_env); +} + +/// Đọc khối `env_monitor` (xem config/runtime/env_monitor_params.yaml). +void readEnvMonitor(robot::NodeHandle& nh, MoveBase2Config& config) +{ + robot::NodeHandle env_nh(nh, "env_monitor"); + EnvMonitorConfig& m = config.env_monitor; + EnvSamplingConfig& s = config.env_sampling; + + readBool(env_nh, "enabled", m.enabled); + readDouble(env_nh, "grace_after_new_plan", m.grace_after_new_plan); + readDouble(env_nh, "check_period", s.check_period); + + robot::NodeHandle body_nh(env_nh, "body"); + readDouble(body_nh, "front_offset", s.body_front); + readDouble(body_nh, "rear_offset", s.body_rear); + readDouble(body_nh, "side_offset", s.body_side); + readDouble(body_nh, "padding", s.padding); + readInt(body_nh, "lethal_threshold", s.lethal_threshold); + + robot::NodeHandle geo_nh(env_nh, "geometry"); + readDouble(geo_nh, "horizon", s.horizon); + readDouble(geo_nh, "corridor_margin", s.corridor_margin); + readDouble(geo_nh, "corridor_cap", s.corridor_cap); + readDouble(geo_nh, "target_backoff", s.target_backoff); + readDouble(geo_nh, "robot_snap", s.robot_snap); + readDouble(geo_nh, "track_back", s.track_back); + readDouble(geo_nh, "track_ahead", s.track_ahead); + readDouble(geo_nh, "exit_ahead", s.exit_ahead); + + robot::NodeHandle stall_nh(env_nh, "stall"); + readBool(stall_nh, "enabled", m.stall.enabled); + readString(stall_nh, "action", m.stall.action); + readDouble(stall_nh, "window_s", m.stall.window_s); + readDouble(stall_nh, "window_m", m.stall.window_m); + readDouble(stall_nh, "min_commanded", m.stall.min_commanded); + readDouble(stall_nh, "eff_on", m.stall.eff_on); + readDouble(stall_nh, "eff_off", m.stall.eff_off); + readDouble(stall_nh, "confirm", m.stall.confirm); + readDouble(stall_nh, "goal_zone", m.stall.goal_zone); + readDouble(stall_nh, "slip_on", m.stall.slip_on); + readDouble(stall_nh, "slip_time", m.stall.slip_time); + readDouble(stall_nh, "min_commanded_since_goal", m.stall.min_commanded_since_goal); + readDouble(stall_nh, "retry_backoff", m.stall.retry_backoff); + readDouble(stall_nh, "jump_reject", m.stall.jump_reject); + readDouble(stall_nh, "disp_window_s", m.stall.disp_window_s); + readDouble(stall_nh, "disp_min", m.stall.disp_min); + readDouble(stall_nh, "disp_min_commanded", m.stall.disp_min_commanded); + + robot::NodeHandle unreach_nh(env_nh, "unreachable"); + readBool(unreach_nh, "enabled", m.unreachable.enabled); + readString(unreach_nh, "action", m.unreachable.action); + readDouble(unreach_nh, "static_on", m.unreachable.static_on); + readDouble(unreach_nh, "clean_start_margin", m.unreachable.clean_start_margin); + readDouble(unreach_nh, "retry_backoff", m.unreachable.retry_backoff); + + robot::NodeHandle contact_nh(env_nh, "contact"); + readBool(contact_nh, "enabled", m.contact.enabled); + readString(contact_nh, "action", m.contact.action); + readBool(contact_nh, "apply_command", m.contact.apply_command); + readString(contact_nh, "use_local_plan", s.use_local_plan); + readDouble(contact_nh, "local_plan_start_tol", s.local_plan_start_tol); + readDouble(contact_nh, "lookahead", s.contact_lookahead); + readInt(contact_nh, "confirm_cycles", m.contact.confirm_cycles); + readDouble(contact_nh, "trigger_static_time", m.contact.trigger_static_time); + readDouble(contact_nh, "clean_start_margin", m.contact.clean_start_margin); + readDouble(contact_nh, "brake_decel", m.contact.brake_decel); + readDouble(contact_nh, "min_speed", m.contact.min_speed); + readDouble(contact_nh, "min_check_speed", m.contact.min_check_speed); + readDouble(contact_nh, "release_hysteresis", m.contact.release_hysteresis); + readInt(contact_nh, "release_confirm_cycles", m.contact.release_confirm_cycles); + readDouble(contact_nh, "envelope_margin", m.contact.envelope_margin); + readDouble(contact_nh, "standdown_min_travel", m.contact.standdown_min_travel); + readDouble(contact_nh, "standdown_travel", m.contact.standdown_travel); + readBool(contact_nh, "envelope", m.contact.envelope); + + robot::NodeHandle budget_nh(env_nh, "replan_budget"); + readDouble(budget_nh, "min_travel", m.replan.min_travel); + readDouble(budget_nh, "escalate_factor", m.replan.escalate_factor); + readDouble(budget_nh, "escalate_window_m", m.replan.escalate_window_m); + readDouble(budget_nh, "escalate_max", m.replan.escalate_max); + + robot::NodeHandle logger_nh(env_nh, "logger"); + readBool(logger_nh, "enabled", config.env_logger.enabled); + readString(logger_nh, "log_dir", config.env_logger.log_dir); + readDouble(logger_nh, "flush_period", config.env_logger.flush_period); + + std::vector names; + env_nh.param("profiles", names, std::vector{}); + if (!names.empty()) + { + s.profiles.clear(); + for (const std::string& name : names) + { + if (name == "position") + { + s.profiles.push_back(MotionProfile::kPosition); + } + else if (name == "docking") + { + s.profiles.push_back(MotionProfile::kDocking); + } + else if (name == "go_straight") + { + s.profiles.push_back(MotionProfile::kGoStraight); + } + else if (name == "rotate") + { + s.profiles.push_back(MotionProfile::kRotate); + } + else + { + robot::log_warning("[move_base2] env_monitor/profiles: unknown profile '%s', ignored.\n", + name.c_str()); + } + } + } } /// Đọc cấu hình đường vào cảm biến từ namespace con `sensors`. @@ -594,6 +714,14 @@ bool MoveBase2Config::validate(std::string& error) const return false; } + if (env_monitor.enabled) + { + if (!env_monitor.validate(error) || !env_sampling.validate(error) || !env_logger.validate(error)) + { + return false; + } + } + if (!velocity.validate(error)) { return false; @@ -843,6 +971,10 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const config.backup_global_planner_name = backup_global_planner_name; config.docking_requires_marker = docking_requires_marker; config.path_monitor = path_monitor; + config.env_monitor = env_monitor; + config.env_sampling = env_sampling; + config.env_logger = env_logger; + config.debug_env = debug_env; return config; } diff --git a/src/control_loop.cpp b/src/control_loop.cpp index 2437c58..6c7d75a 100644 --- a/src/control_loop.cpp +++ b/src/control_loop.cpp @@ -157,6 +157,56 @@ bool ControlLoopConfig::PathMonitorConfig::monitors(MotionProfile profile) const return std::find(profiles.begin(), profiles.end(), profile) != profiles.end(); } +bool EnvSamplingConfig::monitors(MotionProfile profile) const +{ + return std::find(profiles.begin(), profiles.end(), profile) != profiles.end(); +} + +bool EnvSamplingConfig::validate(std::string& error) const +{ + if (!std::isfinite(check_period) || check_period <= 0.0) + { + error = "env_monitor/check_period must be > 0 [s]"; + return false; + } + if (lethal_threshold < 1 || lethal_threshold > 254) + { + error = "env_monitor/body/lethal_threshold must be in [1, 254]"; + return false; + } + const bool any_body = body_front > 0.0 || body_rear > 0.0 || body_side > 0.0; + const bool all_body = body_front > 0.0 && body_rear > 0.0 && body_side > 0.0; + if (any_body && !all_body) + { + error = "env_monitor/body: front_offset, rear_offset and side_offset must all be > 0 [m] when any " + "is set (all 0 = use the costmap footprint)"; + return false; + } + if (!std::isfinite(padding) || padding < 0.0 || !std::isfinite(horizon) || horizon <= 0.0 || + !std::isfinite(corridor_margin) || corridor_margin < 0.0 || !std::isfinite(corridor_cap) || + corridor_cap <= 0.0 || !std::isfinite(target_backoff) || target_backoff < 0.0 || + !std::isfinite(track_back) || track_back < 0.0 || !std::isfinite(track_ahead) || track_ahead <= 0.0 || + !std::isfinite(exit_ahead) || exit_ahead < 0.0 || + !std::isfinite(robot_snap) || robot_snap < 0.0) + { + error = "env_monitor: padding/corridor_margin/target_backoff/robot_snap/track_back/exit_ahead >= 0, " + "horizon/corridor_cap/track_ahead > 0 [m]"; + return false; + } + if (use_local_plan != "auto" && use_local_plan != "true" && use_local_plan != "false") + { + error = "env_monitor/contact/use_local_plan must be auto | true | false"; + return false; + } + if (!std::isfinite(local_plan_start_tol) || local_plan_start_tol <= 0.0 || + !std::isfinite(contact_lookahead) || contact_lookahead <= 0.0) + { + error = "env_monitor/contact: local_plan_start_tol and lookahead must be > 0 [m]"; + return false; + } + return true; +} + // ================================================================================================ // ControlLoop // ================================================================================================ @@ -291,6 +341,53 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe } } + // EnvMonitor (Test/ENV_MONITOR_PLAN.md): chạy song song PathMonitor ở P3. Không có cổng thì tắt, nhưng + // phải kêu nếu config bảo bật. + env_logger_.reset(); + if (config_.env_monitor.enabled) + { + if (deps_.environment == nullptr) + { + robot::log_error("[move_base2] env_monitor is enabled but no EnvironmentPort is wired — EnvMonitor " + "stays OFF.\n"); + } + else + { + if (!config_.env_sampling.validate(error) || !env_monitor_.configure(config_.env_monitor, error)) + { + return false; + } + robot::log_info("[move_base2] %s\n sampling : check=%.2f s lethal>=%d padding=%.2f m horizon=%.1f m " + "corridor_margin=%.2f m use_local_plan=%s lookahead=%.1f m body=%s\n", + config_.env_monitor.describe().c_str(), config_.env_sampling.check_period, + config_.env_sampling.lethal_threshold, config_.env_sampling.padding, + config_.env_sampling.horizon, config_.env_sampling.corridor_margin, + config_.env_sampling.use_local_plan.c_str(), config_.env_sampling.contact_lookahead, + config_.env_sampling.body_front > 0.0 ? "config" : "costmap footprint"); + const bool shadow = config_.env_monitor.stall.action != "recover" && + config_.env_monitor.unreachable.action != "recover" && + config_.env_monitor.contact.action != "recover" && + !config_.env_monitor.contact.apply_command; + robot::log_info("[move_base2] EnvMonitor mode: %s\n", + shadow ? "SHADOW (log only; no flags, no braking, no speed cap)" + : "ACTIVE on at least one verdict or on the command"); + if (config_.env_logger.enabled) + { + env_logger_ = std::make_unique(); + if (!env_logger_->open(config_.env_logger, error)) + { + robot::log_error("[move_base2] %s — EnvMonitor runs without the JSONL logger.\n", error.c_str()); + env_logger_.reset(); + error.clear(); + } + else + { + robot::log_info("[move_base2] EnvMonitor logger writing to %s\n", env_logger_->path().c_str()); + } + } + } + } + initialized_ = true; reset(); return true; @@ -331,6 +428,14 @@ void ControlLoop::reset() resetPathMonitor(); has_last_plan_applied_ = false; + env_monitor_.reset(); + env_verdict_ = EnvVerdict(); + env_geometry_ = EnvGeometry(); + has_last_env_heavy_ = false; + has_last_env_debug_ = false; + env_brake_ = false; + env_used_local_plan_ = false; + has_outcome_ = false; outcome_report_count_ = 0; last_reason_ = ""; @@ -1173,6 +1278,190 @@ void ControlLoop::applyCollisionGuard(const robot_geometry_msgs::PoseStamped& ro } } +void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt, + const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available, + bool costmap_stale) +{ + env_brake_ = false; + if (!config_.env_monitor.enabled || deps_.environment == nullptr || !env_monitor_.configured()) + { + return; + } + if (!has_active_request_) + { + // Không có chặng: mọi ngân sách/mốc thuộc chặng cũ. Verdict rỗng. + env_monitor_.reset(); + env_verdict_ = EnvVerdict(); + env_geometry_ = EnvGeometry(); + has_last_env_heavy_ = false; + env_plan_index_valid_ = false; + return; + } + + const EnvSamplingConfig& sampling = config_.env_sampling; + const bool monitorable = state_machine_.state() == NavigationState::kControlling && pose_available && + !latest_plan_.empty() && sampling.monitors(active_request_.profile); + + EnvSample s; + s.now = now; + s.dt = dt; + s.costmap_current = !costmap_stale; + s.has_plan = monitorable; + s.robot_x = robot_pose.pose.position.x; + s.robot_y = robot_pose.pose.position.y; + const robot_geometry_msgs::Twist& last_cmd = arbiter_.lastCommand(); + s.v_cmd = last_cmd.linear.x; + s.w_cmd = last_cmd.angular.z; + robot_geometry_msgs::Twist measured; + if (deps_.controller->measuredVelocity(measured)) + { + s.v_meas = measured.linear.x; + } + s.controller_valid = controller_feedback_ != ControllerFeedback::kNoValidCommand; + s.v_controller = env_controller_v_; + if (!latest_plan_.empty() && pose_available) + { + s.d_goal = std::hypot(latest_plan_.back().pose.position.x - robot_pose.pose.position.x, + latest_plan_.back().pose.position.y - robot_pose.pose.position.y); + } + + if (monitorable) + { + deps_.environment->refresh(); + + double front = sampling.body_front; + double rear = sampling.body_rear; + double side = sampling.body_side; + bool have_body = front > 0.0 && rear > 0.0 && side > 0.0; + if (!have_body) + { + have_body = deps_.environment->robotBodyExtents(front, rear, side); + if (!have_body) + { + robot::log_error_throttle(5.0, "[move_base2] EnvMonitor: no body geometry (costmap footprint " + "unavailable, body/*_offset not set) — geometry not sampled.\n"); + } + } + + if (have_body) + { + const bool heavy_due = + !has_last_env_heavy_ || (now - last_env_heavy_).toSec() >= sampling.check_period; + if (heavy_due) + { + // Bám index đơn điệu: detour uốn quanh trụ có đoạn sau đi sát robot, nearest toàn plan nhảy sang đó + // và điểm thoát T đổi (cost_to_go +8 m / 1 s, run 5/9 22:35). Plan mới thì tìm lại toàn plan một lần. + if (!env_plan_index_valid_ || env_plan_index_ + 1 >= latest_plan_.size()) + { + env_plan_index_ = nearestIndex(latest_plan_, robot_pose); + env_plan_index_valid_ = true; + } + else + { + env_plan_index_ = trackedNearestIndex(latest_plan_, robot_pose, env_plan_index_, sampling.track_back, + sampling.track_ahead); + } + EnvGeometryRequest req; + req.plan = &latest_plan_; + req.from_index = env_plan_index_; + req.robot_pose = robot_pose; + req.sampling = &sampling; + req.front = front; + req.rear = rear; + req.side = side; + EnvGeometry geometry; + if (deps_.environment->sampleGeometry(req, geometry)) + { + env_geometry_ = geometry; + s.geometry_valid = true; + s.cost_conclusive = geometry.cost.conclusive; + s.reachable = geometry.cost.reachable; + s.cost_to_go = geometry.cost.cost_to_go; + s.edt_body_min = geometry.edt_body_min; + } + last_env_heavy_ = now; + has_last_env_heavy_ = true; + } + + if (config_.env_monitor.contact.enabled) + { + EnvTrajectoryRequest treq; + treq.robot_pose = robot_pose; + treq.v = s.v_cmd; + treq.omega = s.w_cmd; + treq.sampling = &sampling; + treq.front = front; + treq.rear = rear; + treq.side = side; + if (sampling.use_local_plan != "false") + { + deps_.controller->getLocalPlan(env_local_plan_); + treq.local_plan = &env_local_plan_; + } + SweepResult sweep; + bool used_local = false; + if (deps_.environment->sweepTrajectory(treq, sweep, used_local) && sweep.conclusive) + { + s.contact_conclusive = true; + s.traj_contact_dist = sweep.blocked ? sweep.distance : std::numeric_limits::infinity(); + env_used_local_plan_ = used_local; + env_contact_dist_ = s.traj_contact_dist; + } + } + } + } + + env_verdict_ = env_monitor_.update(s); + env_brake_ = env_verdict_.brake && config_.env_monitor.contact.apply_command; + if (env_verdict_.cost_jump && config_.debug_env) + { + robot::log_info_throttle(1.0, "[move_base2][debug] EnvMonitor: cost_to_go jumped to %.2f m in one tick — free mask " + "changed connectivity, stall window restarted.\n", + s.cost_to_go); + } + + // Sườn sự kiện: một dòng, không throttle, không khoá — đây là chẩn đoán "robot kẹt/sắp chạm". + if (env_verdict_.event[0] != '\0') + { + robot::log_warning("[move_base2] EnvMonitor: %s (eff_geo=%.2f cmd=%.2f m, cost_to_go=%.2f m, " + "edt_body=%.2f m, contact=%.2f m, budget_left=%.2f m, mission %llu%s).\n", + env_verdict_.event, env_verdict_.eff_geo, env_verdict_.cmd_window, + env_geometry_.valid ? env_geometry_.cost.cost_to_go : -1.0, s.edt_body_min, + s.traj_contact_dist, env_verdict_.replan_budget_left, + static_cast(active_request_.mission_sequence_id), + (env_verdict_.no_progress || env_verdict_.path_blocked || env_verdict_.collision) + ? "; FLAG RAISED" + : "; shadow"); + } + // Tóm tắt feature 1 Hz — nhóm debug/env, tắt được. + if (config_.debug_env && monitorable && s.geometry_valid && + (!has_last_env_debug_ || (now - last_env_debug_).toSec() >= 1.0)) + { + last_env_debug_ = now; + has_last_env_debug_ = true; + robot::log_info("[move_base2][debug] EnvMonitor: cost_to_go=%.2f (geo %.2f + arc %.2f, %s%s) eff=%.2f " + "cmd=%.2f m edt_body=%.2f m clear_ahead=%.2f m corridor=%.2f m contact=%.2f m (%s) " + "v_cap=%.2f stall=%d%s unreach=%d%s brake=%d standdown=%d budget_left=%.1f m disp=%.2f m%s\n", + env_geometry_.cost.cost_to_go, env_geometry_.cost.geo_to_exit, env_geometry_.cost.arc_rest, + env_geometry_.cost.reachable ? "reachable" : "UNREACHABLE", + env_geometry_.cost.robot_in_ring ? ", in ring" : "", env_verdict_.eff_geo, + env_verdict_.cmd_window, env_geometry_.edt_body_min, env_geometry_.corridor.plan_clear_ahead, + env_geometry_.corridor.min_width, s.traj_contact_dist, + env_used_local_plan_ ? "local plan" : "arc", env_verdict_.v_cap, + env_verdict_.stall_detected ? 1 : 0, env_verdict_.stall_muted ? "(muted)" : "", + env_verdict_.unreachable_detected ? 1 : 0, env_verdict_.unreachable_muted ? "(muted)" : "", + env_verdict_.brake ? 1 : 0, env_verdict_.contact_standdown ? 1 : 0, + env_verdict_.replan_budget_left, env_verdict_.net_disp, + env_verdict_.wandering ? " WANDERING" : ""); + } + if (env_logger_ && (s.geometry_valid || env_verdict_.event[0] != '\0')) + { + env_logger_->record(now, s, env_verdict_, s.geometry_valid ? &env_geometry_ : nullptr, + toString(state_machine_.state()), active_request_.mission_sequence_id, + env_used_local_plan_); + } +} + void ControlLoop::runController(robot_geometry_msgs::Twist& candidate) { candidate = robot_geometry_msgs::Twist(); @@ -1242,6 +1531,7 @@ bool ControlLoop::step() // --- 1b. Giám sát tuyến --------------------------------------------------------------------- // Chạy TRƯỚC state machine: hai cờ nó sinh ra là dữ liệu vào của state machine ngay cycle này. updatePathMonitor(now, robot_pose, pose_available, costmap_stale); + updateEnvMonitor(now, dt, robot_pose, pose_available, costmap_stale); // --- 2. State machine ----------------------------------------------------------------------- StateMachineInput input; @@ -1262,11 +1552,13 @@ bool ControlLoop::step() input.robot_stopped = arbiter_.stopped(); input.travelled_since_oscillation_reset = travelled; // Phép đo 3 dùng chung route với phép đo 1: cả hai cùng một cách xử lý — lập lại đường. - input.path_blocked = path_blocked_; - input.collision = collision_blocked_; // Phép đo 3 có trigger/route riêng (2026-09-04) + // EnvMonitor OR vào cùng bốn cổng của PathMonitor: cờ của nó chỉ khác false khi `action: recover`. + input.path_blocked = path_blocked_ || env_verdict_.path_blocked; + input.collision = collision_blocked_ || env_verdict_.collision; // Phép đo 3 có trigger/route riêng (2026-09-04) input.off_path = off_path_; // Phép đo 4 chỉ được leo thang ở mode "recover"; mode "log" đã in cảnh báo và dừng ở đó. - input.no_progress = no_progress_ && config_.path_monitor.progress_action == "recover"; + input.no_progress = (no_progress_ && config_.path_monitor.progress_action == "recover") || + env_verdict_.no_progress; // Cùng một chỉ số dùng cho cả cycle khởi động recovery lẫn các cycle tick: state machine chỉ tăng // chỉ số khi behavior kết thúc, nên `nextRecoveryIndex()` chính là behavior sắp chạy hoặc đang @@ -1319,6 +1611,7 @@ bool ControlLoop::step() ++plan_revision_; order_plan_.clear(); has_outcome_ = false; + env_monitor_.onGoalAccepted(now); // Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop. if (active_request_.has_goal) @@ -1382,6 +1675,8 @@ bool ControlLoop::step() // plan vừa tới (rõ nhất lúc preempt/đổi chặng). Đo lệch tuyến ngay lúc đó là khai hoả oan. last_plan_applied_ = now; has_last_plan_applied_ = true; + env_monitor_.onPlanApplied(now); + env_plan_index_valid_ = false; if (config_.debug_plan) { @@ -1428,6 +1723,7 @@ bool ControlLoop::step() robot_geometry_msgs::Twist candidate; collision_brake_ = false; // chỉ applyCollisionGuard của CYCLE NÀY được bật lại. + env_controller_v_ = 0.0; // controller không chạy cycle này = không đòi đi. if (output.start_recovery) { @@ -1436,6 +1732,7 @@ bool ControlLoop::step() // Behavior từ chối khởi động (ví dụ đã va chạm ngay tại chỗ) — báo hỏng để state machine // chuyển sang behavior kế tiếp thay vì tick một behavior chưa start. recovery_feedback_ = RecoveryFeedback::kFailed; + env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed); } } else if (output.tick_recovery) @@ -1448,9 +1745,14 @@ bool ControlLoop::step() break; case RecoveryTick::Status::kSucceeded: recovery_feedback_ = RecoveryFeedback::kSucceeded; + env_monitor_.onRecoveryFinished(now, + tick.has_path && !tick.path.empty() ? EnvRecoveryOutcome::kSucceededWithPath + : EnvRecoveryOutcome::kSucceeded, + output.recovery_trigger == RecoveryTrigger::kCollision); break; case RecoveryTick::Status::kFailed: recovery_feedback_ = RecoveryFeedback::kFailed; + env_monitor_.onRecoveryFinished(now, EnvRecoveryOutcome::kFailed); break; } if (tick.has_velocity) @@ -1577,8 +1879,44 @@ bool ControlLoop::step() runController(candidate); if (controller_feedback_ == ControllerFeedback::kCommandValid) { + env_controller_v_ = candidate.linear.x; // trước guard / bao / trọng tài: ý định thật của controller // Phép đo 3 của PathMonitor: soi chính lệnh sắp phát, TRƯỚC trọng tài. applyCollisionGuard(robot_pose, pose_available, candidate); + + // EnvMonitor: bao tốc độ theo tiếp xúc trên quỹ đạo thật. Chỉ tác động khi `contact/apply_command` + // (P4); ở shadow chỉ có dòng log "would cap". Giữ omega/v để cung không đổi khi kẹp. + if (std::isfinite(env_verdict_.v_cap) && std::fabs(candidate.linear.x) > env_verdict_.v_cap) + { + if (config_.env_monitor.contact.apply_command) + { + const double scale = env_verdict_.v_cap / std::fabs(candidate.linear.x); + candidate.linear.x *= scale; + candidate.angular.z *= scale; + } + else if (config_.debug_env) + { + robot::log_info_throttle(2.0, "[move_base2][debug] EnvMonitor: would cap v %.2f -> %.2f m/s " + "(contact %.2f m along the %s; shadow, not applied).\n", + candidate.linear.x, env_verdict_.v_cap, env_contact_dist_, + env_used_local_plan_ ? "local plan" : "commanded arc"); + } + } + + // EnvMonitor giữ phanh MÀ cờ collision đã giơ và state machine vẫn để CONTROLLING (route + // collision cạn/khoá): lệnh vừa bị huỷ thì với state machine nó KHÔNG hợp lệ — cùng luật (A) + // của guard cũ. Báo đúng sự thật thì controller_patience chạy -> route controlling_failed -> + // ABORT có log, thay vì robot đứng chết vô hạn với controller "ổn". Trước khi cờ giơ (1 s kề + // mũi) controller vẫn hợp lệ: patience 0,5 s không được chạy đua với chính cờ collision. + if (env_brake_ && env_verdict_.collision) + { + controller_feedback_ = ControllerFeedback::kNoValidCommand; + robot::log_warning_throttle(2.0, + "[move_base2] EnvMonitor: holding the brake (contact %.2f m along the %s, " + "controller wants v=%.2f) — reported as no valid command; if the collision " + "trigger is locked, controller_patience escalates.\n", + env_contact_dist_, env_used_local_plan_ ? "local plan" : "commanded arc", + candidate.linear.x); + } } if (controller_feedback_ == ControllerFeedback::kNoValidCommand) { @@ -1645,8 +1983,8 @@ bool ControlLoop::step() // --- 4. Lệnh vận tốc ------------------------------------------------------------------------ // Sắp chạm vật cản thật cũng là "không ai được phát": lệnh 0 tức thì, không giảm dần. - arbiter_.arbitrate((costmap_stale || collision_brake_) ? VelocitySource::kNone - : output.velocity_source, + arbiter_.arbitrate((costmap_stale || collision_brake_ || env_brake_) ? VelocitySource::kNone + : output.velocity_source, candidate, dt); // Phép đo 4 đo lệnh SAU trọng tài: hold của planner, phanh của Phép đo 3, costmap stale đều ra // 0 ở đây — đó chính là cách nó phân biệt "đang chờ" với "đòi đi mà không tiến". diff --git a/src/env_monitor.cpp b/src/env_monitor.cpp new file mode 100644 index 0000000..58d95c4 --- /dev/null +++ b/src/env_monitor.cpp @@ -0,0 +1,773 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * move_base2 — cài đặt lõi EnvMonitor (xem header). + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include +#include + +namespace move_base2 +{ +namespace +{ + +bool validAction(const std::string& action) +{ + return action == "log" || action == "recover"; +} + +bool finitePositive(double v) +{ + return std::isfinite(v) && v > 0.0; +} + +bool finiteNonNegative(double v) +{ + return std::isfinite(v) && v >= 0.0; +} + +} // namespace + +// ------------------------------------------------------------------------------------------ config + +bool EnvMonitorConfig::validate(std::string& error) const +{ + if (!finiteNonNegative(grace_after_new_plan)) + { + error = "env_monitor/grace_after_new_plan must be >= 0 [s]"; + return false; + } + if (!validAction(stall.action) || !validAction(unreachable.action) || !validAction(contact.action)) + { + error = "env_monitor/*/action must be \"log\" or \"recover\""; + return false; + } + if (!finitePositive(stall.window_s) || !finitePositive(stall.window_m)) + { + error = "env_monitor/stall/window_s and window_m must be > 0"; + return false; + } + if (!finitePositive(stall.min_commanded)) + { + error = "env_monitor/stall/min_commanded must be > 0 [m] (0 would turn waiting into stalling)"; + return false; + } + if (!std::isfinite(stall.eff_on) || !std::isfinite(stall.eff_off) || stall.eff_off <= stall.eff_on) + { + error = "env_monitor/stall/eff_off must be > eff_on (hysteresis)"; + return false; + } + if (!finiteNonNegative(stall.confirm) || !finiteNonNegative(stall.goal_zone) || + !finiteNonNegative(stall.slip_on) || !finiteNonNegative(stall.slip_time) || + !finiteNonNegative(stall.min_commanded_since_goal) || !finiteNonNegative(stall.retry_backoff) || + !finiteNonNegative(stall.jump_reject) || !finitePositive(stall.disp_window_s) || + !finiteNonNegative(stall.disp_min) || !finiteNonNegative(stall.disp_min_commanded)) + { + error = "env_monitor/stall: confirm, goal_zone, slip_on, slip_time, min_commanded_since_goal, " + "retry_backoff must be >= 0"; + return false; + } + if (!finiteNonNegative(unreachable.static_on) || !finitePositive(unreachable.clean_start_margin) || + !finiteNonNegative(unreachable.retry_backoff)) + { + error = "env_monitor/unreachable: static_on >= 0 [s], clean_start_margin > 0 [m], retry_backoff >= 0"; + return false; + } + if (contact.confirm_cycles < 1) + { + error = "env_monitor/contact/confirm_cycles must be >= 1"; + return false; + } + if (!finiteNonNegative(contact.trigger_static_time) || !finitePositive(contact.clean_start_margin) || + !finitePositive(contact.brake_decel) || !finiteNonNegative(contact.min_speed) || + !finiteNonNegative(contact.min_check_speed) || !finiteNonNegative(contact.release_hysteresis) || + contact.release_confirm_cycles < 1 || !finiteNonNegative(contact.envelope_margin) || + !finiteNonNegative(contact.standdown_min_travel) || !finiteNonNegative(contact.standdown_travel)) + { + error = "env_monitor/contact: trigger_static_time >= 0, clean_start_margin > 0, brake_decel > 0, " + "min_speed >= 0, min_check_speed >= 0, release_hysteresis >= 0, release_confirm_cycles >= 1, " + "envelope_margin >= 0, standdown_min_travel >= 0, standdown_travel >= 0"; + return false; + } + if (!finiteNonNegative(replan.min_travel) || !std::isfinite(replan.escalate_factor) || + replan.escalate_factor < 1.0 || !finiteNonNegative(replan.escalate_window_m) || + !finiteNonNegative(replan.escalate_max) || (replan.escalate_max > 0.0 && replan.escalate_max < replan.min_travel)) + { + error = "env_monitor/replan_budget: min_travel >= 0, escalate_factor >= 1, escalate_window_m >= 0, " + "escalate_max = 0 or >= min_travel"; + return false; + } + return true; +} + +std::string EnvMonitorConfig::describe() const +{ + std::ostringstream out; + out << "env_monitor " << (enabled ? "ON" : "OFF") << " (grace " << grace_after_new_plan << " s):\n"; + out << " stall : " << (stall.enabled ? "on" : "off") << " action=" << stall.action + << " window=" << stall.window_s << " s/" << stall.window_m << " m min_cmd=" << stall.min_commanded + << " m eff<" << stall.eff_on << " ket / >=" << stall.eff_off << " xoa confirm=" << stall.confirm + << " s goal_zone=" << stall.goal_zone << " m slip>=" << stall.slip_on << " m/s " << stall.slip_time + << " s cmd_since_goal>=" << stall.min_commanded_since_goal << " m backoff=" << stall.retry_backoff + << " s jump_reject=" << stall.jump_reject << " m disp_gate=" << stall.disp_min << " m/" + << stall.disp_window_s << " s (cmd>=" << stall.disp_min_commanded << " m)\n"; + out << " unreachable : " << (unreachable.enabled ? "on" : "off") << " action=" << unreachable.action + << " static_on=" << unreachable.static_on << " s clean_margin=" << unreachable.clean_start_margin + << " m backoff=" << unreachable.retry_backoff << " s\n"; + out << " contact : " << (contact.enabled ? "on" : "off") << " action=" << contact.action + << " confirm=" << contact.confirm_cycles << " cycles trigger_static=" << contact.trigger_static_time + << " s clean_margin=" << contact.clean_start_margin << " m decel=" << contact.brake_decel + << " m/s^2 envelope=" << (contact.envelope ? "on" : "off") << " min_speed=" << contact.min_speed + << " m/s min_check_speed=" << contact.min_check_speed << " m/s release=" << contact.release_hysteresis + << " m/" << contact.release_confirm_cycles << " cycles envelope_margin=" << contact.envelope_margin + << " m standdown=" << contact.standdown_min_travel << "/" << contact.standdown_travel + << " m apply_command=" << (contact.apply_command ? "YES" : "no (shadow)") << "\n"; + out << " replan : min_travel=" << replan.min_travel << " m x" << replan.escalate_factor + << " within " << replan.escalate_window_m << " m, max " << replan.escalate_max << " m"; + return out.str(); +} + +// ----------------------------------------------------------------------------------------- lifecycle + +bool EnvMonitor::configure(const EnvMonitorConfig& config, std::string& error) +{ + if (!config.validate(error)) + { + configured_ = false; + return false; + } + config_ = config; + configured_ = true; + reset(); + return true; +} + +void EnvMonitor::reset() +{ + cmd_accum_ = 0.0; + travel_total_ = 0.0; + has_last_pose_ = false; + has_goal_ = false; + cmd_at_goal_ = 0.0; + has_plan_time_ = false; + clearWindow(); + stall_seen_ = false; + stall_fired_ = false; + slip_seen_ = false; + has_stall_backoff_ = false; + baseline_pending_ = true; + baseline_unreachable_ = false; + unreach_seen_ = false; + unreach_fired_ = false; + has_unreach_backoff_ = false; + contact_streak_ = 0; + release_streak_ = 0; + has_prev_heavy_ = false; + clearPosWindow(); + braking_ = false; + contact_close_ = false; + contact_fired_ = false; + detour_from_contact_ = false; + detour_mark_travel_ = 0.0; + standdown_ = false; + standdown_mark_travel_ = 0.0; + standdown_clean_streak_ = 0; + has_replan_mark_ = false; + replan_mark_travel_ = 0.0; + budget_travel_ = config_.replan.min_travel; + has_prev_replan_ = false; + prev_replan_travel_ = 0.0; +} + +void EnvMonitor::onGoalAccepted(const robot::Time& now) +{ + (void)now; + const double cmd = cmd_accum_; + const double travel = travel_total_; + const bool had_pose = has_last_pose_; + const double lx = last_x_; + const double ly = last_y_; + reset(); + // Odometer và lệnh tích luỹ là đơn điệu, chỉ dùng qua hiệu số: giữ lại để mốc không nhảy. + cmd_accum_ = cmd; + travel_total_ = travel; + has_last_pose_ = had_pose; + last_x_ = lx; + last_y_ = ly; + has_goal_ = true; + cmd_at_goal_ = cmd_accum_; +} + +void EnvMonitor::onPlanApplied(const robot::Time& now) +{ + has_plan_time_ = true; + plan_time_ = now; + clearWindow(); + clearPosWindow(); // cửa sổ dịch chuyển bắt đầu lại: plan mới là một lượt thử mới + has_prev_heavy_ = false; + stall_seen_ = false; + stall_fired_ = false; + // Plan mới có baseline riêng: chỉ nổ "mất liên thông" vì thứ xảy ra SAU khi plan được lập (R2). + baseline_pending_ = true; + baseline_unreachable_ = false; + unreach_seen_ = false; + unreach_fired_ = false; +} + +void EnvMonitor::onRecoveryFinished(const robot::Time& now, EnvRecoveryOutcome outcome, bool from_contact) +{ + switch (outcome) + { + case EnvRecoveryOutcome::kSucceededWithPath: + { + // Detour do chính cờ collision: nếu robot không rời chỗ mà lại "sắp chạm" thì lần sau đứng ra. + detour_from_contact_ = from_contact; + detour_mark_travel_ = travel_total_; + // R3/R5: im tới khi đi đủ budget_travel_ kể từ đây; lặp trong escalate_window_m thì nhân lên. + if (has_prev_replan_ && travel_total_ - prev_replan_travel_ < config_.replan.escalate_window_m) + { + budget_travel_ *= config_.replan.escalate_factor; + if (config_.replan.escalate_max > 0.0) + { + budget_travel_ = std::min(budget_travel_, config_.replan.escalate_max); + } + } + else + { + budget_travel_ = config_.replan.min_travel; + } + has_prev_replan_ = true; + prev_replan_travel_ = travel_total_; + has_replan_mark_ = true; + replan_mark_travel_ = travel_total_; + break; + } + case EnvRecoveryOutcome::kSucceeded: + break; + case EnvRecoveryOutcome::kFailed: + has_stall_backoff_ = true; + stall_backoff_until_ = now + robot::Duration(config_.stall.retry_backoff); + has_unreach_backoff_ = true; + unreach_backoff_until_ = now + robot::Duration(config_.unreachable.retry_backoff); + break; + } + // Mọi kết cục đều kết thúc một pha dừng: chuỗi xác nhận cũ không còn giá trị. + stall_seen_ = false; + stall_fired_ = false; + unreach_seen_ = false; + unreach_fired_ = false; + contact_streak_ = 0; + release_streak_ = 0; + braking_ = false; + contact_close_ = false; + contact_fired_ = false; +} + +// -------------------------------------------------------------------------------------------- window + +void EnvMonitor::clearWindow() +{ + ring_head_ = 0; + ring_count_ = 0; +} + +void EnvMonitor::clearPosWindow() +{ + pos_head_ = 0; + pos_count_ = 0; + wandering_ = false; + net_disp_ = std::numeric_limits::quiet_NaN(); +} + +bool EnvMonitor::oldestPos(const robot::Time& now, PosSample& out) const +{ + // Mẫu MỚI NHẤT đã đủ tuổi disp_window_s — cùng lý do với oldestInWindow. + for (std::size_t k = 1; k <= pos_count_; ++k) + { + const PosSample& p = pos_ring_[(pos_head_ + kPosRing - k) % kPosRing]; + if ((now - p.t).toSec() >= config_.stall.disp_window_s) + { + out = p; + return true; + } + } + return false; +} + +bool EnvMonitor::oldestInWindow(const robot::Time& now, HeavySample& out) const +{ + // Mẫu MỚI NHẤT đã đủ tuổi window_s hoặc đủ xa window_m lệnh — cửa sổ sát ngưỡng nhất, không phải + // mẫu cũ nhất trong ring (cửa sổ giãn ra làm eff mượt giả). + for (std::size_t k = 1; k <= ring_count_; ++k) + { + const HeavySample& s = ring_[(ring_head_ + kRing - k) % kRing]; + const bool old_enough = (now - s.t).toSec() >= config_.stall.window_s; + const bool far_enough = cmd_accum_ - s.cmd >= config_.stall.window_m; + if (old_enough || far_enough) + { + out = s; + return true; + } + } + return false; +} + +// -------------------------------------------------------------------------------------------- update + +EnvVerdict EnvMonitor::update(const EnvSample& s) +{ + EnvVerdict v; + if (!configured_ || !config_.enabled) + { + return v; + } + + // Tích luỹ lệnh và quãng đường — mọi cửa sổ, cổng, ngân sách đều đo bằng hai con số này. + if (s.dt > 0.0 && std::isfinite(s.v_cmd)) + { + cmd_accum_ += std::fabs(s.v_cmd) * s.dt; + } + if (std::isfinite(s.robot_x) && std::isfinite(s.robot_y)) + { + if (has_last_pose_) + { + travel_total_ += std::hypot(s.robot_x - last_x_, s.robot_y - last_y_); + } + last_x_ = s.robot_x; + last_y_ = s.robot_y; + has_last_pose_ = true; + } + if (has_replan_mark_) + { + v.replan_budget_left = std::max(0.0, budget_travel_ - (travel_total_ - replan_mark_travel_)); + } + + updateContact(s, v); + + if (!s.has_plan || !s.costmap_current) + { + // Không có gì để đo tiến độ; xoá chuỗi để không nối "đúng liên tục" qua quãng gián đoạn. + stall_seen_ = false; + stall_fired_ = false; + unreach_seen_ = false; + unreach_fired_ = false; + return v; + } + updateStall(s, v); + updateUnreachable(s, v); + return v; +} + +void EnvMonitor::updateStall(const EnvSample& s, EnvVerdict& v) +{ + const EnvMonitorConfig::Stall& c = config_.stall; + if (!c.enabled) + { + return; + } + + // Cửa sổ dịch chuyển thực: lấy mẫu vị trí mỗi tick nặng, không phụ thuộc cost/plan/mặt nạ. + if (s.geometry_valid && std::isfinite(s.robot_x) && std::isfinite(s.robot_y)) + { + pos_ring_[pos_head_] = PosSample{ s.now, s.robot_x, s.robot_y, cmd_accum_ }; + pos_head_ = (pos_head_ + 1) % kPosRing; + pos_count_ = std::min(pos_count_ + 1, kPosRing); + PosSample old; + if (oldestPos(s.now, old)) + { + net_disp_ = std::hypot(s.robot_x - old.x, s.robot_y - old.y); + wandering_ = (cmd_accum_ - old.cmd >= c.disp_min_commanded) && net_disp_ < c.disp_min; + } + else + { + net_disp_ = std::numeric_limits::quiet_NaN(); + wandering_ = false; + } + } + v.net_disp = net_disp_; + v.wandering = wandering_; + + // Mẫu nặng mới: ghi vào ring nếu có cost hữu hạn. +inf (mất liên thông tạm) không ghi — không kết + // luận từ mẫu thiếu. + if (s.geometry_valid && s.cost_conclusive && s.reachable && std::isfinite(s.cost_to_go)) + { + // Lật liên thông: cost đổi nhiều hơn robot có thể đã đi trong một tick -> mặt nạ free vừa đóng/mở một khe, + // không phải tiến độ. Bắt đầu đo lại; kết luận kẹt cũ (nếu có) cũng không còn cơ sở. + if (c.jump_reject > 0.0 && has_prev_heavy_ && + std::fabs(s.cost_to_go - prev_heavy_cost_) > c.jump_reject + (travel_total_ - prev_heavy_travel_)) + { + clearWindow(); + stall_seen_ = false; + stall_fired_ = false; + v.cost_jump = true; + } + has_prev_heavy_ = true; + prev_heavy_cost_ = s.cost_to_go; + prev_heavy_travel_ = travel_total_; + ring_[ring_head_] = HeavySample{ s.now, s.cost_to_go, cmd_accum_ }; + ring_head_ = (ring_head_ + 1) % kRing; + ring_count_ = std::min(ring_count_ + 1, kRing); + + HeavySample old; + if (oldestInWindow(s.now, old)) + { + const double cmd = cmd_accum_ - old.cmd; + v.cmd_window = cmd; + if (cmd >= c.min_commanded) + { + v.eff_geo = (old.cost - s.cost_to_go) / cmd; + } + } + } + + // Trượt: lệnh đi mà bánh không quay (vật thấp, bumper). Chỉ khi có v_meas. + bool slipping = false; + if (c.slip_on > 0.0 && std::isfinite(s.v_meas)) + { + const bool slip_now = std::fabs(s.v_cmd) - std::fabs(s.v_meas) >= c.slip_on; + if (slip_now) + { + if (!slip_seen_) + { + slip_seen_ = true; + slip_since_ = s.now; + } + slipping = (s.now - slip_since_).toSec() >= c.slip_time; + } + else + { + slip_seen_ = false; + } + } + + const bool grace = has_plan_time_ && (s.now - plan_time_).toSec() < config_.grace_after_new_plan; + const bool near_goal = std::isfinite(s.d_goal) && s.d_goal < c.goal_zone; + if (grace || near_goal) + { + stall_seen_ = false; + stall_fired_ = false; + return; + } + + const bool eff_known = !std::isnan(v.eff_geo); + const bool stalled = (eff_known && v.eff_geo < c.eff_on) || slipping; + const bool cleared = eff_known && v.eff_geo >= c.eff_off && !slipping; + if (stalled) + { + if (!stall_seen_) + { + stall_seen_ = true; + stall_since_ = s.now; + } + if (!stall_fired_ && (s.now - stall_since_).toSec() >= c.confirm) + { + stall_fired_ = true; + v.event = slipping ? "stall: wheels slip against the command" : "stall: cost_to_go not decreasing"; + } + } + else if (cleared) + { + if (stall_fired_) + { + v.event = "stall cleared: progress resumed"; + } + stall_seen_ = false; + stall_fired_ = false; + } + // Còn lại (không đo được, hoặc eff trong vùng chết): giữ trạng thái — không kết luận ≠ hết kẹt. + + v.stall_detected = stall_fired_; + if (!stall_fired_) + { + return; + } + // Cổng đầu chặng, ngân sách replan, backoff sau lượt hỏng. + bool muted = false; + if (has_goal_ && cmd_accum_ - cmd_at_goal_ < c.min_commanded_since_goal) + { + muted = true; + } + if (c.disp_min > 0.0) + { + // Cổng dịch chuyển thực thay ngân sách replan: cửa sổ vị trí đã bắt đầu lại ở plan mới, nên "sau detour + // vẫn quần tại chỗ disp_window_s" mới được nổ lại; né tự do (dịch chuyển >= disp_min) không bao giờ nổ. + if (!wandering_) + { + muted = true; + } + } + else if (has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_) + { + muted = true; + } + if (has_stall_backoff_ && s.now < stall_backoff_until_) + { + muted = true; + } + v.stall_muted = muted; + v.no_progress = !muted && c.action == "recover"; +} + +void EnvMonitor::updateUnreachable(const EnvSample& s, EnvVerdict& v) +{ + const EnvMonitorConfig::Unreachable& c = config_.unreachable; + if (!c.enabled) + { + return; + } + // Trạng thái chỉ đổi ở tick nặng có kết luận; verdict thì phải ra MỖI cycle từ trạng thái, nếu + // không cờ nhấp nháy giữa hai tick 5 Hz và state machine 20 Hz thấy cờ bật/tắt. + if (s.geometry_valid && s.cost_conclusive) + { + // Baseline của plan: mẫu kết luận đầu tiên sau khi nhận plan. Plan đã không liên thông ngay từ + // đầu thì đó là chuyện của SBPL/planner đã lập nó — monitor không cãi trên cùng snapshot (R2). + if (baseline_pending_) + { + baseline_pending_ = false; + baseline_unreachable_ = !s.reachable; + } + if (s.reachable) + { + if (unreach_fired_) + { + v.event = "unreachable cleared: the exit is connected again"; + } + unreach_seen_ = false; + unreach_fired_ = false; + baseline_unreachable_ = false; // từ đây mất liên thông là chuyện mới + } + else + { + const bool grace = has_plan_time_ && (s.now - plan_time_).toSec() < config_.grace_after_new_plan; + const bool clean = std::isfinite(s.edt_body_min) && s.edt_body_min >= c.clean_start_margin; + if (baseline_unreachable_ || grace || !clean) + { + // Không tích: chưa phải "xấu đi", hoặc robot đã lọt vành (SBPL không có chỗ bắt đầu — việc + // của kContact + controller_patience). + unreach_seen_ = false; + } + else + { + if (!unreach_seen_) + { + unreach_seen_ = true; + unreach_since_ = s.now; + } + if (!unreach_fired_ && (s.now - unreach_since_).toSec() >= c.static_on) + { + unreach_fired_ = true; + v.event = "unreachable: no path to the plan exit inside the window"; + } + } + } + } + v.unreachable_detected = unreach_fired_; + if (!unreach_fired_) + { + return; + } + bool muted = false; + if (has_replan_mark_ && travel_total_ - replan_mark_travel_ < budget_travel_) + { + muted = true; + } + if (has_unreach_backoff_ && s.now < unreach_backoff_until_) + { + muted = true; + } + v.unreachable_muted = muted; + v.path_blocked = !muted && c.action == "recover"; +} + +void EnvMonitor::updateContact(const EnvSample& s, EnvVerdict& v) +{ + const EnvMonitorConfig::Contact& c = config_.contact; + if (!c.enabled) + { + return; + } + double v_ref = std::fabs(s.v_cmd); + if (std::isfinite(s.v_meas)) + { + v_ref = std::max(v_ref, std::fabs(s.v_meas)); + } + v.brake_dist = v_ref * v_ref / (2.0 * c.brake_decel); + + if (!s.contact_conclusive || !s.costmap_current) + { + // Không biết thì không dừng, cũng không xoá chuỗi (cùng hợp đồng với guard cũ). + v.brake = braking_; // đang phanh thì giữ phanh tới khi có bằng chứng ngược lại + return; + } + if (standdown_) + { + // Đang đứng ra: không phanh, không cờ, không bao. Chỉ theo dõi điều kiện vũ trang lại. + v.contact_standdown = true; + if (std::isfinite(s.traj_contact_dist)) + { + standdown_clean_streak_ = 0; + } + else + { + ++standdown_clean_streak_; + } + const bool travelled = travel_total_ - standdown_mark_travel_ >= c.standdown_travel; + if (travelled || standdown_clean_streak_ >= c.release_confirm_cycles) + { + standdown_ = false; + standdown_clean_streak_ = 0; + v.contact_standdown = false; + v.event = travelled ? "contact: re-armed after moving on" : "contact: re-armed, the trajectory is clear"; + } + return; + } + if (!std::isfinite(s.traj_contact_dist)) + { + contact_streak_ = 0; + if (braking_ && ++release_streak_ < c.release_confirm_cycles) + { + // Một mẫu sạch chưa là sạch: local planner đổi quỹ đạo mỗi cycle, sạch 1 cycle rồi chạm lại là + // chuyện thường (run 5/9 22:35: 4 lần nhả/phanh trong 3 s). Giữ phanh và cờ tới khi sạch liên tiếp. + v.brake = true; + v.collision = contact_fired_ && c.action == "recover"; + return; + } + if (braking_ || contact_fired_) + { + v.event = "contact cleared: the trajectory is free again"; + } + braking_ = false; + release_streak_ = 0; + contact_close_ = false; + contact_fired_ = false; + return; + } + + // Bao tốc độ: |v| <= sqrt(2 a (d - margin)) để luôn còn dừng được trên đất sạch. + // Bao giữ thêm envelope_margin so với ngưỡng phanh: lệnh nằm trên bao thì quãng phanh còn dư đúng chừng + // đó, nhiễu quỹ đạo vài cm không đẩy sang "sắp chạm". Trong margin thì 0; giữa margin và margin+dư thì bò + // min_speed. + if (c.envelope) + { + if (s.traj_contact_dist <= c.clean_start_margin) + { + v.v_cap = 0.0; + } + else + { + const double room = s.traj_contact_dist - c.clean_start_margin - c.envelope_margin; + v.v_cap = std::max(c.min_speed, room > 0.0 ? std::sqrt(2.0 * c.brake_decel * room) : 0.0); + } + } + + // Xoay tại chỗ / bò mà monitor chưa phanh: quỹ đạo local planner lúc này là một cú xoay, góc thân + // quét vào ô kề bên là chuyện của controller (nó tự kiểm footprint), không phải bài toán quãng phanh. + // Phanh ở đây là chặn robot xoay ra khỏi vật đang kề mũi, rồi 1 s sau giơ cờ và gọi detour từ đúng + // chỗ đứng — vòng churn đầu chặng của guard cũ (mission 5/6 shadow 5/9). Đã phanh rồi thì vẫn xét + // tiếp để "kề mũi đứng yên" còn nổ được. + double v_intent = v_ref; + if (std::isfinite(s.v_controller)) + { + v_intent = std::max(v_intent, std::fabs(s.v_controller)); + } + if (v_intent < c.min_check_speed && !braking_) + { + contact_streak_ = 0; + release_streak_ = 0; + contact_close_ = false; + contact_fired_ = false; + return; + } + + // Hai câu hỏi khác nhau: + // - "sắp chạm" = còn dừng kịp không (theo quãng phanh) -> PHANH. Đứng lại rồi thì quãng phanh về 0 + // và câu này tự hết đúng, robot được bò tiếp dưới bao tốc độ. + // - "đang kề vật" = tiếp xúc trong đúng clean_start_margin bất kể tốc độ -> nếu còn đó đủ + // trigger_static_time thì vật đứng yên trước mũi, không phải người đi qua -> giơ CỜ. + // Bao tốc độ đặt lệnh đúng lên biên v_cap = sqrt(2a(d - margin)), tức d - quãng phanh == margin: nếu + // "sắp chạm" là <= thì mỗi lần bao kẹp xong là phanh, nhả, kẹp, phanh (chattering 4 cycle). Chỉ phanh + // khi vượt bao quá 1 mm — lệnh nằm trên bao là đang giảm tốc đúng luật, không phải sắp chạm. + // Trong margin thì bao đã là 0: đó là một cú dừng của monitor dù quãng phanh bằng 0 — phải được gọi + // là phanh để có sự kiện, để giữ 0 tức thì qua trọng tài và để cổng xoay không nuốt nó. + constexpr double kEnvelopeTol = 1e-3; // [m] + // Đã kề thì còn kề tới margin + release_hysteresis: quỹ đạo nhảy 0,08 <-> 0,25 m quanh margin không + // được reset đồng hồ giơ cờ, cũng không được nhả phanh. + const double close_limit = c.clean_start_margin + (contact_close_ ? c.release_hysteresis : 0.0); + const bool close = s.traj_contact_dist <= close_limit; + const bool imminent = close || s.traj_contact_dist - v.brake_dist < c.clean_start_margin - kEnvelopeTol; + v.contact_imminent = imminent; + if (imminent) + { + release_streak_ = 0; + ++contact_streak_; + if (!braking_ && contact_streak_ >= c.confirm_cycles) + { + if (c.standdown_min_travel > 0.0 && detour_from_contact_ && + travel_total_ - detour_mark_travel_ < c.standdown_min_travel) + { + // Vừa detour từ đúng chỗ này vì chính cú chạm này, robot chưa rời chỗ: phanh + cờ lần nữa chỉ lặp + // lại churn (3 detour rồi ABORT). Nhường controller — nó là lưới an toàn duy nhất tới khi robot đi + // được standdown_travel hoặc quỹ đạo sạch. + standdown_ = true; + standdown_mark_travel_ = travel_total_; + standdown_clean_streak_ = 0; + detour_from_contact_ = false; + contact_streak_ = 0; + release_streak_ = 0; + contact_close_ = false; + contact_fired_ = false; + v.contact_standdown = true; + v.contact_imminent = false; + v.v_cap = std::numeric_limits::infinity(); + v.event = "contact: standing down — the detour from this spot did not move the robot, the controller " + "is the only safety net until it travels on"; + return; + } + braking_ = true; + v.event = "contact: braking to zero"; + } + } + else + { + contact_streak_ = 0; + if (braking_ && ++release_streak_ >= c.release_confirm_cycles) + { + braking_ = false; + release_streak_ = 0; + v.event = "contact receded: releasing the brake"; + } + } + v.brake = braking_; + + if (close) + { + if (!contact_close_) + { + contact_close_ = true; + close_since_ = s.now; + } + if (!contact_fired_ && (s.now - close_since_).toSec() >= c.trigger_static_time) + { + contact_fired_ = true; + v.event = "contact persists while stopped: asking for a replan"; + } + } + else + { + if (contact_fired_) + { + v.event = "contact cleared: the obstacle moved away"; + } + contact_close_ = false; + contact_fired_ = false; + } + v.collision = contact_fired_ && c.action == "recover"; +} + +} // namespace move_base2 diff --git a/src/grid_analysis.cpp b/src/grid_analysis.cpp new file mode 100644 index 0000000..94829e6 --- /dev/null +++ b/src/grid_analysis.cpp @@ -0,0 +1,813 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * move_base2 — cài đặt grid_analysis (xem header). + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include +#include + +#include +#include + +namespace move_base2 +{ +namespace +{ + +constexpr float kInf = std::numeric_limits::infinity(); +/// Giá trị "vô cùng" hữu hạn cho EDT 1-D: bình phương khoảng cách theo ô tối đa là 160^2 = 25 600, +/// 1e6 vẫn biểu diễn chính xác trong float và không sinh NaN khi trừ nhau như +inf. +constexpr float kFarSq = 1.0e6f; +/// [m] Bỏ quãng đầu quỹ đạo khi kéo footprint — cùng lý do với plan_inspector::kSkipOwnFootprintDist. +constexpr double kSkipOwnFootprintDist = 0.05; +/// Lượng tử hoá khoảng cách trong khoá heap: 0.1 mm, đủ cho 20 m trong 32 bit. +constexpr double kHeapQuant = 10000.0; + +double yawOf(const robot_geometry_msgs::PoseStamped& pose) +{ + const auto& q = pose.pose.orientation; + return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)); +} + +/** + * @brief Biến đổi khoảng cách bình phương 1-D (Felzenszwalb & Huttenlocher 2004) — parabola lower envelope. + * @param f n giá trị vào (0 tại vật cản, kFarSq nơi khác; hoặc kết quả lượt trước). + * @param d n giá trị ra. + * @param v,z bộ đệm >= n và >= n+1. + */ +void distanceTransform1D(const float* f, int n, float* d, int* v, float* z) +{ + int k = 0; + v[0] = 0; + z[0] = -kInf; + z[1] = kInf; + for (int q = 1; q < n; ++q) + { + float s = ((f[q] + static_cast(q) * q) - (f[v[k]] + static_cast(v[k]) * v[k])) / + (2.0f * q - 2.0f * v[k]); + while (s <= z[k]) + { + --k; + s = ((f[q] + static_cast(q) * q) - (f[v[k]] + static_cast(v[k]) * v[k])) / + (2.0f * q - 2.0f * v[k]); + } + ++k; + v[k] = q; + z[k] = s; + z[k + 1] = kInf; + } + k = 0; + for (int q = 0; q < n; ++q) + { + while (z[k + 1] < static_cast(q)) + { + ++k; + } + const float dq = static_cast(q - v[k]); + d[q] = dq * dq + f[v[k]]; + } +} + +std::uint64_t heapKey(double dist, std::uint32_t idx) +{ + const std::uint64_t q = static_cast(std::llround(dist * kHeapQuant)); + return (q << 32) | idx; +} + +/// Dựng chu vi hình chữ nhật thân (frame thân) với bước @p spacing; mỗi điểm mang id cạnh. +void buildPerimeter(double front, double rear, double side, double spacing, std::vector& out) +{ + out.clear(); + const double x0[4] = { -rear, front, front, -rear }; + const double y0[4] = { -side, -side, side, side }; + const double x1[4] = { front, front, -rear, -rear }; + const double y1[4] = { -side, side, side, -side }; + for (int e = 0; e < 4; ++e) + { + const double len = std::hypot(x1[e] - x0[e], y1[e] - y0[e]); + const int n = std::max(1, static_cast(std::ceil(len / spacing))); + for (int i = 0; i <= n; ++i) + { + const double t = static_cast(i) / n; + out.push_back(x0[e] + (x1[e] - x0[e]) * t); + out.push_back(y0[e] + (y1[e] - y0[e]) * t); + out.push_back(static_cast(e)); + } + } +} + +} // namespace + +// ------------------------------------------------------------------------------------------ scratch + +bool GridScratch::ensure(const robot_costmap_2d::Costmap2D& grid) +{ + const unsigned int w = grid.getSizeInCellsX(); + const unsigned int h = grid.getSizeInCellsY(); + resolution = grid.getResolution(); + origin_x = grid.getOriginX(); + origin_y = grid.getOriginY(); + if (w == 0 || h == 0 || !(resolution > 0.0)) + { + return false; + } + if (w != width || h != height) + { + width = w; + height = h; + const std::size_t n = static_cast(w) * h; + edt.assign(n, kInf); + free.assign(n, 0); + geo.assign(n, kInf); + tmp_.assign(n, kFarSq); + const std::size_t m = std::max(w, h) + 2; + f_.assign(m, 0.0f); + d_.assign(m, 0.0f); + v_.assign(m, 0); + z_.assign(m + 1, 0.0f); + heap_.clear(); + heap_.reserve(n * 2); + baseline.reserve(1024); + perim_.reserve(3 * 512); + } + return true; +} + +bool GridScratch::toCell(double x, double y, unsigned int& mx, unsigned int& my) const +{ + if (width == 0 || height == 0 || !(resolution > 0.0)) + { + return false; + } + const double fx = std::floor((x - origin_x) / resolution); + const double fy = std::floor((y - origin_y) / resolution); + if (fx < 0.0 || fy < 0.0 || fx >= static_cast(width) || fy >= static_cast(height)) + { + return false; + } + mx = static_cast(fx); + my = static_cast(fy); + return true; +} + +void GridScratch::cellCenter(unsigned int mx, unsigned int my, double& x, double& y) const +{ + x = origin_x + (mx + 0.5) * resolution; + y = origin_y + (my + 0.5) * resolution; +} + +// --------------------------------------------------------------------------------------------- EDT + +bool analyzeGrid(const robot_costmap_2d::Costmap2D& grid, unsigned char lethal_threshold, + double free_radius, GridScratch& s) +{ + if (!s.ensure(grid)) + { + return false; + } + const unsigned char* cost = grid.getCharMap(); + const std::size_t n = static_cast(s.width) * s.height; + bool any_lethal = false; + for (std::size_t i = 0; i < n; ++i) + { + // NO_INFORMATION (255) không phải vật cản — cùng quy ước với checkPlan và SBPL. + const bool lethal = cost[i] >= lethal_threshold && cost[i] != robot_costmap_2d::NO_INFORMATION; + s.tmp_[i] = lethal ? 0.0f : kFarSq; + any_lethal |= lethal; + } + s.free_radius = free_radius; + if (!any_lethal) + { + std::fill(s.edt.begin(), s.edt.end(), kInf); + std::fill(s.free.begin(), s.free.end(), static_cast(1)); + return true; + } + // Lượt 1: theo hàng (trục x). + const int w = static_cast(s.width); + const int h = static_cast(s.height); + for (int y = 0; y < h; ++y) + { + float* row = &s.tmp_[static_cast(y) * s.width]; + distanceTransform1D(row, w, s.d_.data(), s.v_.data(), s.z_.data()); + std::copy(s.d_.begin(), s.d_.begin() + w, row); + } + // Lượt 2: theo cột (trục y). + for (int x = 0; x < w; ++x) + { + for (int y = 0; y < h; ++y) + { + s.f_[y] = s.tmp_[static_cast(y) * s.width + x]; + } + distanceTransform1D(s.f_.data(), h, s.d_.data(), s.v_.data(), s.z_.data()); + for (int y = 0; y < h; ++y) + { + const std::size_t i = static_cast(y) * s.width + x; + const float dist = std::sqrt(s.d_[y]) * static_cast(s.resolution); + s.edt[i] = dist; + s.free[i] = dist >= static_cast(free_radius) ? 1 : 0; + } + } + return true; +} + +double distanceAt(const GridScratch& s, double x, double y) +{ + unsigned int mx = 0; + unsigned int my = 0; + if (!s.toCell(x, y, mx, my) || s.edt.empty()) + { + return std::numeric_limits::quiet_NaN(); + } + return s.edt[s.index(mx, my)]; +} + +// ---------------------------------------------------------------------------------------- geodesic + +bool computeGeodesic(unsigned int tx, unsigned int ty, GridScratch& s, std::size_t* visited, + std::size_t stop_index) +{ + if (visited != nullptr) + { + *visited = 0; + } + if (s.width == 0 || tx >= s.width || ty >= s.height || s.free.empty()) + { + return false; + } + std::fill(s.geo.begin(), s.geo.end(), kInf); + const std::size_t t = s.index(tx, ty); + if (!s.free[t]) + { + return false; + } + const float res = static_cast(s.resolution); + const float diag = res * 1.41421356f; + const int w = static_cast(s.width); + const int h = static_cast(s.height); + + s.heap_.clear(); + s.geo[t] = 0.0f; + s.heap_.push_back(heapKey(0.0, static_cast(t))); + std::greater cmp; + + // 8 láng giềng: (dx, dy, chéo?) + static const int kDx[8] = { 1, -1, 0, 0, 1, 1, -1, -1 }; + static const int kDy[8] = { 0, 0, 1, -1, 1, -1, 1, -1 }; + + std::size_t popped = 0; + while (!s.heap_.empty()) + { + std::pop_heap(s.heap_.begin(), s.heap_.end(), cmp); + const std::uint64_t key = s.heap_.back(); + s.heap_.pop_back(); + const std::uint32_t idx = static_cast(key & 0xffffffffu); + const double qd = static_cast(key >> 32) / kHeapQuant; + if (qd > s.geo[idx] + 0.5 / kHeapQuant) + { + continue; // mục cũ, đã có đường ngắn hơn + } + ++popped; + if (idx == stop_index) + { + break; // ô cần hỏi đã có khoảng cách đúng (Dijkstra: pop = chốt); phần còn lại không cần + } + const int x = static_cast(idx % s.width); + const int y = static_cast(idx / s.width); + const float base = s.geo[idx]; + for (int k = 0; k < 8; ++k) + { + const int nx = x + kDx[k]; + const int ny = y + kDy[k]; + if (nx < 0 || ny < 0 || nx >= w || ny >= h) + { + continue; + } + const std::size_t ni = s.index(static_cast(nx), static_cast(ny)); + if (!s.free[ni]) + { + continue; + } + float step = res; + if (k >= 4) + { + // Cấm cắt góc: hai ô trực giao trung gian phải free, không thì đường chui qua khe chéo. + const std::size_t a = s.index(static_cast(nx), static_cast(y)); + const std::size_t b = s.index(static_cast(x), static_cast(ny)); + if (!s.free[a] || !s.free[b]) + { + continue; + } + step = diag; + } + const float nd = base + step; + if (nd < s.geo[ni]) + { + s.geo[ni] = nd; + s.heap_.push_back(heapKey(nd, static_cast(ni))); + std::push_heap(s.heap_.begin(), s.heap_.end(), cmp); + } + } + } + if (visited != nullptr) + { + *visited = popped; + } + return true; +} + +bool nearestFreeCell(const GridScratch& s, unsigned int mx, unsigned int my, double max_dist, + unsigned int& fx, unsigned int& fy) +{ + if (s.free.empty() || mx >= s.width || my >= s.height) + { + return false; + } + if (s.free[s.index(mx, my)]) + { + fx = mx; + fy = my; + return true; + } + const int r = static_cast(std::ceil(max_dist / s.resolution)); + long best = -1; + for (int dy = -r; dy <= r; ++dy) + { + for (int dx = -r; dx <= r; ++dx) + { + const int x = static_cast(mx) + dx; + const int y = static_cast(my) + dy; + if (!s.inBounds(x, y)) + { + continue; + } + const long d2 = static_cast(dx) * dx + static_cast(dy) * dy; + if (s.free[s.index(static_cast(x), static_cast(y))] && + (best < 0 || d2 < best)) + { + best = d2; + fx = static_cast(x); + fy = static_cast(y); + } + } + } + return best >= 0 && std::sqrt(static_cast(best)) * s.resolution <= max_dist; +} + +// ------------------------------------------------------------------------------------ body clearance + +double bodyClearance(const GridScratch& s, double x, double y, double yaw, double front, double rear, + double side) +{ + if (s.edt.empty()) + { + return std::numeric_limits::quiet_NaN(); + } + const double spacing = 0.5 * s.resolution; + const double c = std::cos(yaw); + const double sn = std::sin(yaw); + double best = std::numeric_limits::infinity(); + bool any = false; + const double x0[4] = { -rear, front, front, -rear }; + const double y0[4] = { -side, -side, side, side }; + const double x1[4] = { front, front, -rear, -rear }; + const double y1[4] = { -side, side, side, -side }; + for (int e = 0; e < 4; ++e) + { + const double len = std::hypot(x1[e] - x0[e], y1[e] - y0[e]); + const int n = std::max(1, static_cast(std::ceil(len / spacing))); + for (int i = 0; i <= n; ++i) + { + const double t = static_cast(i) / n; + const double bx = x0[e] + (x1[e] - x0[e]) * t; + const double by = y0[e] + (y1[e] - y0[e]) * t; + const double wx = x + bx * c - by * sn; + const double wy = y + bx * sn + by * c; + const double d = distanceAt(s, wx, wy); + if (!std::isnan(d)) + { + any = true; + best = std::min(best, d); + } + } + } + return any ? best : std::numeric_limits::quiet_NaN(); +} + +// ------------------------------------------------------------------------------------- cost to go + +CostToGoResult costToGo(const std::vector& plan, + std::size_t from_index, double robot_x, double robot_y, + const CostToGoParams& params, const PlanarTransform& plan_to_grid, + GridScratch& s) +{ + CostToGoResult r; + if (plan.size() < 2 || from_index >= plan.size() || s.free.empty()) + { + return r; + } + + // Độ dài cộng dồn từ from_index tới cuối, và pose plan cuối cùng còn trong lưới. + // arc_at[i] chỉ cần cho các pose từ from_index; dùng hai con trỏ chạy để không cấp phát. + double total = 0.0; + { + double px = 0.0; + double py = 0.0; + plan_to_grid.apply(plan[from_index].pose.position.x, plan[from_index].pose.position.y, px, py); + for (std::size_t i = from_index + 1; i < plan.size(); ++i) + { + double qx = 0.0; + double qy = 0.0; + plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy); + total += std::hypot(qx - px, qy - py); + px = qx; + py = qy; + } + } + + std::size_t ti = from_index; + double arc_ti = 0.0; // độ dài từ from_index tới ti + bool found = false; + bool ahead = false; + { + double px = 0.0; + double py = 0.0; + double walk = 0.0; + for (std::size_t i = from_index; i < plan.size(); ++i) + { + double qx = 0.0; + double qy = 0.0; + plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy); + if (i > from_index) + { + walk += std::hypot(qx - px, qy - py); + } + px = qx; + py = qy; + unsigned int mx = 0; + unsigned int my = 0; + if (!s.toCell(qx, qy, mx, my)) + { + break; // cửa sổ lăn theo robot: ra ngoài một lần là phần còn lại cũng ngoài + } + ti = i; + arc_ti = walk; + found = true; + if (params.exit_ahead > 0.0 && walk >= params.exit_ahead) + { + ahead = true; + break; // T ở quãng cố định dọc plan: chỉ tiến theo index, không lùi khi cửa sổ trôi + } + } + } + if (!found) + { + return r; // pose plan gần robot nhất cũng ngoài lưới: robot xa plan, việc của off_path + } + r.target = (ti + 1 == plan.size()) ? CostToGoResult::Target::kGoal + : ahead ? CostToGoResult::Target::kAhead + : CostToGoResult::Target::kExit; + + // T phải là ô free; không thì lùi dọc plan tối đa target_backoff. + unsigned int tx = 0; + unsigned int ty = 0; + { + double qx = 0.0; + double qy = 0.0; + plan_to_grid.apply(plan[ti].pose.position.x, plan[ti].pose.position.y, qx, qy); + s.toCell(qx, qy, tx, ty); + } + if (!s.free[s.index(tx, ty)]) + { + bool backed = false; + double back = 0.0; + double px = 0.0; + double py = 0.0; + plan_to_grid.apply(plan[ti].pose.position.x, plan[ti].pose.position.y, px, py); + for (std::size_t j = ti; j > from_index; --j) + { + double qx = 0.0; + double qy = 0.0; + plan_to_grid.apply(plan[j - 1].pose.position.x, plan[j - 1].pose.position.y, qx, qy); + back += std::hypot(qx - px, qy - py); + px = qx; + py = qy; + if (back > params.target_backoff) + { + break; + } + unsigned int mx = 0; + unsigned int my = 0; + if (s.toCell(qx, qy, mx, my) && s.free[s.index(mx, my)]) + { + ti = j - 1; + arc_ti -= back; + tx = mx; + ty = my; + backed = true; + break; + } + } + if (!backed) + { + r.conclusive = true; + r.reachable = false; + r.target = CostToGoResult::Target::kBlockedExit; + r.target_index = ti; + r.arc_rest = total - arc_ti; + return r; + } + r.target = CostToGoResult::Target::kBackedOff; + } + r.target_index = ti; + r.arc_rest = std::max(0.0, total - arc_ti); + + // Ô robot; đang ôm sát vật thì snap sang ô free gần nhất. + unsigned int rx = 0; + unsigned int ry = 0; + if (!s.toCell(robot_x, robot_y, rx, ry)) + { + return r; + } + if (!s.free[s.index(rx, ry)]) + { + r.robot_in_ring = true; + unsigned int fx = 0; + unsigned int fy = 0; + if (!nearestFreeCell(s, rx, ry, params.robot_snap, fx, fy)) + { + return r; // thân đã nằm sâu trong dải cấm: không kết luận + } + rx = fx; + ry = fy; + } + + std::size_t visited = 0; + computeGeodesic(tx, ty, s, &visited, s.index(rx, ry)); // dừng sớm tại ô robot + r.cells_visited = visited; + r.conclusive = true; + const float g = s.geo[s.index(rx, ry)]; + r.reachable = std::isfinite(g); + r.geo_to_exit = g; + r.cost_to_go = r.reachable ? static_cast(g) + r.arc_rest : std::numeric_limits::infinity(); + return r; +} + +// ---------------------------------------------------------------------------------------- corridor + +CorridorResult scanCorridor(const std::vector& plan, + std::size_t from_index, const CorridorParams& params, + const PlanarTransform& plan_to_grid, const GridScratch& s) +{ + CorridorResult r; + r.plan_clear_ahead = params.horizon; + if (plan.size() < 2 || from_index >= plan.size() || s.edt.empty()) + { + return r; + } + const double need = params.body_width + 2.0 * params.margin; + double walk = 0.0; + double px = 0.0; + double py = 0.0; + bool clear_set = false; + for (std::size_t i = from_index; i < plan.size(); ++i) + { + double qx = 0.0; + double qy = 0.0; + plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy); + if (i > from_index) + { + walk += std::hypot(qx - px, qy - py); + } + const double prev_x = px; + const double prev_y = py; + px = qx; + py = qy; + if (walk > params.horizon) + { + break; + } + unsigned int mx = 0; + unsigned int my = 0; + if (!s.toCell(qx, qy, mx, my)) + { + break; + } + ++r.scanned; + if (!clear_set && s.edt[s.index(mx, my)] < static_cast(s.free_radius)) + { + r.plan_clear_ahead = walk; + clear_set = true; + } + // Hướng tiếp tuyến: tới pose kế, hoặc từ pose trước nếu là pose cuối. + double tx = 0.0; + double ty = 0.0; + if (i + 1 < plan.size()) + { + double nx = 0.0; + double ny = 0.0; + plan_to_grid.apply(plan[i + 1].pose.position.x, plan[i + 1].pose.position.y, nx, ny); + tx = nx - qx; + ty = ny - qy; + } + else if (i > from_index) + { + tx = qx - prev_x; + ty = qy - prev_y; + } + const double tn = std::hypot(tx, ty); + if (tn < 1e-6) + { + continue; + } + const double nx = -ty / tn; + const double ny = tx / tn; + double width = 0.0; + for (double sgn = 1.0; sgn >= -1.0; sgn -= 2.0) + { + double d = 0.0; + while (d < params.side_cap) + { + d += s.resolution; + unsigned int cx = 0; + unsigned int cy = 0; + if (!s.toCell(qx + sgn * nx * d, qy + sgn * ny * d, cx, cy)) + { + break; + } + if (s.edt[s.index(cx, cy)] <= 0.0f) + { + break; // ô lethal + } + } + width += std::min(d, params.side_cap); + } + r.min_width = std::min(r.min_width, width); + if (!std::isfinite(r.block_dist) && width < need) + { + r.block_dist = walk; + } + } + return r; +} + +// ------------------------------------------------------------------------------------------- sweep + +SweepResult sweepTrajectory(const std::vector& trajectory, + double robot_x, double robot_y, double robot_yaw, double start_tol, + const SweepParams& params, const robot_costmap_2d::Costmap2D& grid, + GridScratch& s) +{ + SweepResult r; + if (trajectory.size() < 2 || !s.ensure(grid)) + { + return r; + } + if (std::hypot(trajectory.front().pose.position.x - robot_x, + trajectory.front().pose.position.y - robot_y) > start_tol) + { + return r; // quỹ đạo không bắt đầu ở robot: không phải chuyển động sắp xảy ra + } + const unsigned char* cost = grid.getCharMap(); + const double front = params.front + params.padding; + const double rear = params.rear + params.padding; + const double side = params.side + params.padding; + auto lethal_at = [&](unsigned int mx, unsigned int my) { + const unsigned char c = cost[s.index(mx, my)]; + return c >= params.lethal_threshold && c != robot_costmap_2d::NO_INFORMATION; + }; + + // Baseline: ô lethal đang nằm dưới thân đệm tại pose hiện tại (duyệt diện tích, như checkMotion). + s.baseline.clear(); + if (params.exclude_baseline) + { + const double c = std::cos(robot_yaw); + const double sn = std::sin(robot_yaw); + const double cx[4] = { front, front, -rear, -rear }; + const double cy[4] = { side, -side, side, -side }; + double min_x = std::numeric_limits::max(); + double min_y = min_x; + double max_x = std::numeric_limits::lowest(); + double max_y = max_x; + for (int i = 0; i < 4; ++i) + { + const double wx = robot_x + cx[i] * c - cy[i] * sn; + const double wy = robot_y + cx[i] * sn + cy[i] * c; + min_x = std::min(min_x, wx); + max_x = std::max(max_x, wx); + min_y = std::min(min_y, wy); + max_y = std::max(max_y, wy); + } + int mx0 = 0; + int my0 = 0; + int mx1 = 0; + int my1 = 0; + grid.worldToMapEnforceBounds(min_x, min_y, mx0, my0); + grid.worldToMapEnforceBounds(max_x, max_y, mx1, my1); + const double slack = 0.5 * s.resolution; + for (int my = my0; my <= my1; ++my) + { + for (int mx = mx0; mx <= mx1; ++mx) + { + if (!lethal_at(static_cast(mx), static_cast(my))) + { + continue; + } + double wx = 0.0; + double wy = 0.0; + s.cellCenter(static_cast(mx), static_cast(my), wx, wy); + const double dx = wx - robot_x; + const double dy = wy - robot_y; + const double bx = dx * c + dy * sn; + const double by = -dx * sn + dy * c; + if (bx < -rear - slack || bx > front + slack || std::fabs(by) > side + slack) + { + continue; + } + s.baseline.push_back(static_cast(s.index(static_cast(mx), + static_cast(my)))); + } + } + std::sort(s.baseline.begin(), s.baseline.end()); + } + r.baseline_cells = static_cast(s.baseline.size()); + + buildPerimeter(front, rear, side, 0.5 * s.resolution, s.perim_); + const std::size_t npts = s.perim_.size() / 3; + + auto hit_at = [&](double px, double py, double yaw, int& edge) { + const double c = std::cos(yaw); + const double sn = std::sin(yaw); + for (std::size_t k = 0; k < npts; ++k) + { + const double bx = s.perim_[3 * k]; + const double by = s.perim_[3 * k + 1]; + const double wx = px + bx * c - by * sn; + const double wy = py + bx * sn + by * c; + unsigned int mx = 0; + unsigned int my = 0; + if (!s.toCell(wx, wy, mx, my) || !lethal_at(mx, my)) + { + continue; + } + const std::uint32_t idx = static_cast(s.index(mx, my)); + if (!s.baseline.empty() && std::binary_search(s.baseline.begin(), s.baseline.end(), idx)) + { + continue; + } + edge = static_cast(s.perim_[3 * k + 2]); + return true; + } + return false; + }; + + double walk = 0.0; + for (std::size_t i = 1; i < trajectory.size(); ++i) + { + const double ax = trajectory[i - 1].pose.position.x; + const double ay = trajectory[i - 1].pose.position.y; + const double bx = trajectory[i].pose.position.x; + const double by = trajectory[i].pose.position.y; + const double seg = std::hypot(bx - ax, by - ay); + const double yaw = yawOf(trajectory[i]); + // Chèn mẫu để bước dọc quỹ đạo không quá một ô: tường mỏng một ô không lọt giữa hai mẫu. + const int nsub = std::max(1, static_cast(std::ceil(seg / s.resolution))); + for (int k = 1; k <= nsub; ++k) + { + const double t = static_cast(k) / nsub; + const double px = ax + (bx - ax) * t; + const double py = ay + (by - ay) * t; + const double w = walk + seg * t; + if (w > params.lookahead) + { + r.conclusive = true; + return r; + } + if (w < kSkipOwnFootprintDist) + { + continue; + } + ++r.scanned; + int edge = -1; + if (hit_at(px, py, yaw, edge)) + { + r.conclusive = true; + r.blocked = true; + r.distance = w; + r.sample = i; + r.hit_edge = edge; + return r; + } + } + walk += seg; + } + r.conclusive = r.scanned > 0; + return r; +} + +} // namespace move_base2 diff --git a/src/io/env_logger.cpp b/src/io/env_logger.cpp new file mode 100644 index 0000000..18b238b --- /dev/null +++ b/src/io/env_logger.cpp @@ -0,0 +1,205 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * move_base2 — cài đặt EnvLogger. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include +#include +#include + +#include + +namespace move_base2 +{ +namespace +{ + +/// JSON không có NaN/Inf: ghi null. +void appendNumber(std::string& out, double v) +{ + char buf[32]; + if (std::isfinite(v)) + { + std::snprintf(buf, sizeof(buf), "%.4f", v); + out += buf; + } + else + { + out += "null"; + } +} + +void appendField(std::string& out, const char* key, double v) +{ + out += '"'; + out += key; + out += "\":"; + appendNumber(out, v); + out += ','; +} + +void appendField(std::string& out, const char* key, bool v) +{ + out += '"'; + out += key; + out += "\":"; + out += v ? "true" : "false"; + out += ','; +} + +void appendField(std::string& out, const char* key, const char* v) +{ + out += '"'; + out += key; + out += "\":\""; + for (const char* p = v; *p != '\0'; ++p) + { + if (*p == '"' || *p == '\\') + { + out += '\\'; + } + out += *p; + } + out += "\","; +} + +} // namespace + +bool EnvLoggerConfig::validate(std::string& error) const +{ + if (!enabled) + { + return true; + } + if (log_dir.empty()) + { + error = "env_monitor/logger/log_dir must not be empty when the logger is enabled"; + return false; + } + if (!std::isfinite(flush_period) || flush_period <= 0.0) + { + error = "env_monitor/logger/flush_period must be > 0 [s]"; + return false; + } + return true; +} + +EnvLogger::~EnvLogger() +{ + flush(); +} + +bool EnvLogger::open(const EnvLoggerConfig& config, std::string& error) +{ + config_ = config; + if (!config.enabled) + { + return true; + } + if (::mkdir(config.log_dir.c_str(), 0755) != 0 && errno != EEXIST) + { + error = "env_monitor/logger: cannot create log_dir '" + config.log_dir + "'"; + return false; + } + const auto epoch = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + path_ = config.log_dir + "/envmon_" + std::to_string(epoch) + ".jsonl"; + out_.open(path_, std::ios::out | std::ios::trunc); + if (!out_.is_open()) + { + error = "env_monitor/logger: cannot open '" + path_ + "' for writing"; + return false; + } + buffer_.reserve(64 * 1024); + return true; +} + +void EnvLogger::record(const robot::Time& now, const EnvSample& s, const EnvVerdict& v, + const EnvGeometry* g, const char* state, std::uint64_t mission_id, + bool used_local_plan) +{ + if (!out_.is_open()) + { + return; + } + std::string& o = buffer_; + o += "{\"v\":1,"; + appendField(o, "t", now.toSec()); + o += "\"mission\":" + std::to_string(mission_id) + ","; + appendField(o, "state", state); + appendField(o, "heavy", s.geometry_valid); + appendField(o, "x", s.robot_x); + appendField(o, "y", s.robot_y); + appendField(o, "v_cmd", s.v_cmd); + appendField(o, "w_cmd", s.w_cmd); + appendField(o, "v_meas", s.v_meas); + appendField(o, "v_controller", s.v_controller); + appendField(o, "d_goal", s.d_goal); + appendField(o, "costmap_current", s.costmap_current); + appendField(o, "controller_valid", s.controller_valid); + appendField(o, "cost_to_go", s.cost_conclusive && s.reachable ? s.cost_to_go : std::numeric_limits::quiet_NaN()); + appendField(o, "cost_conclusive", s.cost_conclusive); + appendField(o, "reachable", s.reachable); + appendField(o, "edt_body_min", s.edt_body_min); + appendField(o, "contact_conclusive", s.contact_conclusive); + appendField(o, "traj_contact_dist", s.traj_contact_dist); + appendField(o, "used_local_plan", used_local_plan); + if (g != nullptr && g->valid) + { + appendField(o, "geo_to_exit", g->cost.geo_to_exit); + appendField(o, "arc_rest", g->cost.arc_rest); + appendField(o, "target_kind", static_cast(static_cast(g->cost.target))); + appendField(o, "cells_visited", static_cast(g->cost.cells_visited)); + appendField(o, "robot_in_ring", g->cost.robot_in_ring); + appendField(o, "plan_clear_ahead", g->corridor.plan_clear_ahead); + appendField(o, "corridor_min_width", g->corridor.min_width); + appendField(o, "corridor_block_dist", g->corridor.block_dist); + } + appendField(o, "eff_geo", v.eff_geo); + appendField(o, "cmd_window", v.cmd_window); + appendField(o, "brake_dist", v.brake_dist); + appendField(o, "v_cap", v.v_cap); + appendField(o, "stall_detected", v.stall_detected); + appendField(o, "stall_muted", v.stall_muted); + appendField(o, "unreachable_detected", v.unreachable_detected); + appendField(o, "unreachable_muted", v.unreachable_muted); + appendField(o, "contact_imminent", v.contact_imminent); + appendField(o, "brake", v.brake); + appendField(o, "contact_standdown", v.contact_standdown); + appendField(o, "cost_jump", v.cost_jump); + appendField(o, "no_progress", v.no_progress); + appendField(o, "path_blocked", v.path_blocked); + appendField(o, "collision", v.collision); + appendField(o, "replan_budget_left", v.replan_budget_left); + appendField(o, "net_disp", v.net_disp); + appendField(o, "wandering", v.wandering); + appendField(o, "event", v.event); + o.pop_back(); // dấu phẩy cuối + o += "}\n"; + + if (!has_last_flush_ || (now - last_flush_).toSec() >= config_.flush_period || buffer_.size() > 48 * 1024) + { + flush(); + last_flush_ = now; + has_last_flush_ = true; + } +} + +void EnvLogger::flush() +{ + if (out_.is_open() && !buffer_.empty()) + { + out_ << buffer_; + out_.flush(); + buffer_.clear(); + } +} + +} // namespace move_base2 diff --git a/src/navigation_runtime.cpp b/src/navigation_runtime.cpp index bf8e85f..fdf7d58 100644 --- a/src/navigation_runtime.cpp +++ b/src/navigation_runtime.cpp @@ -166,6 +166,237 @@ bool CostmapPathCheck::robotBodyExtents(double& front, double& rear, double& sid return true; } +// ================================================================================================ +// CostmapEnvironment +// ================================================================================================ + +namespace +{ +double yawOfPose(const robot_geometry_msgs::PoseStamped& pose) +{ + const auto& q = pose.pose.orientation; + return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)); +} +} // namespace + +robot_costmap_2d::Costmap2D* CostmapEnvironment::gridForRead(bool& live) const +{ + live = true; + if (costmap_ == nullptr) + { + return nullptr; + } + robot_costmap_2d::Costmap2D* grid = costmap_->getCostmapForRead(); + live = (grid == costmap_->getCostmap()); // snapshot tắt -> trả lưới sống -> phải khoá + return grid; +} + +void CostmapEnvironment::refresh() +{ + if (costmap_ != nullptr) + { + costmap_->refreshSnapshot(); // no-op khi snapshot tắt + } +} + +bool CostmapEnvironment::sampleGeometry(const EnvGeometryRequest& r, EnvGeometry& out) +{ + out = EnvGeometry(); + if (costmap_ == nullptr || !tf_ || r.plan == nullptr || r.sampling == nullptr || r.plan->size() < 2 || + r.from_index >= r.plan->size()) + { + return false; + } + bool live = true; + robot_costmap_2d::Costmap2D* grid = gridForRead(live); + if (grid == nullptr) + { + return false; + } + const std::string& grid_frame = costmap_->getGlobalFrameID(); + PlanarTransform plan_to_grid; + PlanarTransform pose_to_grid; + if (!planarTransform(*tf_, (*r.plan)[r.from_index].header.frame_id, grid_frame, plan_to_grid) || + !planarTransform(*tf_, r.robot_pose.header.frame_id, grid_frame, pose_to_grid)) + { + return false; // không quy đổi được frame: không biết, không đoán + } + double gx = 0.0; + double gy = 0.0; + pose_to_grid.apply(r.robot_pose.pose.position.x, r.robot_pose.pose.position.y, gx, gy); + const double gyaw = yawOfPose(r.robot_pose) + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw); + + // Bán kính tâm = inscribed của thân, KHÔNG đệm: cùng biên với SBPL (luật R2). + const double free_radius = std::min(r.side, std::min(r.front, r.rear)); + out.free_radius = free_radius; + + boost::unique_lock lock(*(grid->getMutex()), boost::defer_lock); + if (live) + { + lock.lock(); + } + if (!analyzeGrid(*grid, static_cast(r.sampling->lethal_threshold), free_radius, scratch_)) + { + return false; + } + out.edt_body_min = bodyClearance(scratch_, gx, gy, gyaw, r.front, r.rear, r.side); + CostToGoParams cost_params; + cost_params.target_backoff = r.sampling->target_backoff; + cost_params.robot_snap = r.sampling->robot_snap; + cost_params.exit_ahead = r.sampling->exit_ahead; + out.cost = costToGo(*r.plan, r.from_index, gx, gy, cost_params, plan_to_grid, scratch_); + CorridorParams corridor_params; + corridor_params.horizon = r.sampling->horizon; + corridor_params.body_width = 2.0 * r.side; + corridor_params.margin = r.sampling->corridor_margin; + corridor_params.side_cap = r.sampling->corridor_cap; + out.corridor = scanCorridor(*r.plan, r.from_index, corridor_params, plan_to_grid, scratch_); + out.valid = true; + return true; +} + +bool CostmapEnvironment::sweepTrajectory(const EnvTrajectoryRequest& r, SweepResult& out, + bool& used_local_plan) +{ + out = SweepResult(); + used_local_plan = false; + if (costmap_ == nullptr || !tf_ || r.sampling == nullptr) + { + return false; + } + bool live = true; + robot_costmap_2d::Costmap2D* grid = gridForRead(live); + if (grid == nullptr) + { + return false; + } + const std::string& grid_frame = costmap_->getGlobalFrameID(); + PlanarTransform pose_to_grid; + if (!planarTransform(*tf_, r.robot_pose.header.frame_id, grid_frame, pose_to_grid)) + { + return false; + } + double gx = 0.0; + double gy = 0.0; + pose_to_grid.apply(r.robot_pose.pose.position.x, r.robot_pose.pose.position.y, gx, gy); + const double gyaw = yawOfPose(r.robot_pose) + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw); + + SweepParams params; + params.front = r.front; + params.rear = r.rear; + params.side = r.side; + params.padding = r.sampling->padding; + params.lookahead = r.sampling->contact_lookahead; + params.lethal_threshold = static_cast(r.sampling->lethal_threshold); + + boost::unique_lock lock(*(grid->getMutex()), boost::defer_lock); + if (live) + { + lock.lock(); + } + + // 1) Quỹ đạo thật của local planner, quy về frame lưới. + if (r.sampling->use_local_plan != "false" && r.local_plan != nullptr && r.local_plan->poses.size() >= 2) + { + PlanarTransform traj_to_grid; + if (planarTransform(*tf_, r.local_plan->header.frame_id, grid_frame, traj_to_grid)) + { + const double dyaw = std::atan2(traj_to_grid.sin_yaw, traj_to_grid.cos_yaw); + traj_scratch_.clear(); + traj_scratch_.reserve(r.local_plan->poses.size()); + for (const auto& p : r.local_plan->poses) + { + robot_geometry_msgs::PoseStamped ps; + traj_to_grid.apply(p.pose.x, p.pose.y, ps.pose.position.x, ps.pose.position.y); + const double yaw = p.pose.theta + dyaw; + ps.pose.orientation.z = std::sin(0.5 * yaw); + ps.pose.orientation.w = std::cos(0.5 * yaw); + traj_scratch_.push_back(ps); + } + out = move_base2::sweepTrajectory(traj_scratch_, gx, gy, gyaw, r.sampling->local_plan_start_tol, + params, *grid, scratch_); + if (out.conclusive) + { + used_local_plan = true; + return true; + } + } + } + if (r.sampling->use_local_plan == "true") + { + return false; // ép dùng quỹ đạo mà không có -> không kết luận + } + // 2) Cung (v, omega) không đổi — cùng hình học với guard cũ, nhưng cùng bộ dò với quỹ đạo thật. + if (std::fabs(r.v) < 1e-3) + { + out.conclusive = true; // đứng yên / xoay tại chỗ: không có chuyển động tịnh tiến để dò + return true; + } + const double res = grid->getResolution(); + const double step = res > 0.0 ? res : 0.05; + const double direction = r.v < 0.0 ? -1.0 : 1.0; + const double kappa = r.omega / r.v; + traj_scratch_.clear(); + const int n = static_cast(std::ceil(r.sampling->contact_lookahead / step)); + traj_scratch_.reserve(static_cast(n) + 1); + for (int i = 0; i <= n; ++i) + { + const double s = direction * step * i; + robot_geometry_msgs::PoseStamped ps; + double yaw = gyaw; + if (std::fabs(kappa) < 1e-6) + { + ps.pose.position.x = gx + s * std::cos(gyaw); + ps.pose.position.y = gy + s * std::sin(gyaw); + } + else + { + yaw = gyaw + kappa * s; + ps.pose.position.x = gx + (std::sin(yaw) - std::sin(gyaw)) / kappa; + ps.pose.position.y = gy - (std::cos(yaw) - std::cos(gyaw)) / kappa; + } + ps.pose.orientation.z = std::sin(0.5 * yaw); + ps.pose.orientation.w = std::cos(0.5 * yaw); + traj_scratch_.push_back(ps); + } + out = move_base2::sweepTrajectory(traj_scratch_, gx, gy, gyaw, 1.0, params, *grid, scratch_); + return out.conclusive; +} + +bool CostmapEnvironment::robotBodyExtents(double& front, double& rear, double& side) const +{ + if (costmap_ == nullptr) + { + return false; + } + const std::vector& fp = costmap_->getUnpaddedRobotFootprint(); + if (fp.size() < 3) + { + return false; + } + double max_x = std::numeric_limits::lowest(); + double min_x = std::numeric_limits::max(); + double max_abs_y = 0.0; + for (const robot_geometry_msgs::Point& p : fp) + { + if (!std::isfinite(p.x) || !std::isfinite(p.y)) + { + return false; + } + max_x = std::max(max_x, p.x); + min_x = std::min(min_x, p.x); + max_abs_y = std::max(max_abs_y, std::fabs(p.y)); + } + if (!(max_x > 0.0) || !(min_x < 0.0) || !(max_abs_y > 0.0)) + { + return false; + } + front = max_x; + rear = -min_x; + side = max_abs_y; + return true; +} + NavigationRuntime::NavigationRuntime() = default; NavigationRuntime::~NavigationRuntime() @@ -252,6 +483,10 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr& tf path_check_.setCostmap(local_costmap_.get()); path_check_.setTf(tf_); + // EnvMonitor đọc cùng costmap local (thay PathMonitor); TF để quy plan (map) và pose về frame lưới. + environment_.setCostmap(local_costmap_.get()); + environment_.setTf(tf_); + // Gắn ngay: host có thể hỏi dữ liệu hiển thị bất cứ lúc nào sau initialize(), kể cả trước khi // costmap có nội dung. Exporter tự trả về "chưa có gì" thay vì lưới rỗng. global_exporter_.attach(global_costmap_.get(), config_.global_frame); @@ -501,6 +736,7 @@ ControlLoopDeps NavigationRuntime::deps() deps.action = &action_; deps.costmap_status = &costmap_status_; deps.path_check = &path_check_; + deps.environment = &environment_; return deps; } diff --git a/src/plan_inspector.cpp b/src/plan_inspector.cpp index 8cb6a6e..4b970da 100644 --- a/src/plan_inspector.cpp +++ b/src/plan_inspector.cpp @@ -80,6 +80,50 @@ bool planarTransform(const tf3::BufferCore& tf, const std::string& from, const s } } +std::size_t trackedNearestIndex(const std::vector& plan, + const robot_geometry_msgs::PoseStamped& pose, std::size_t hint, + double back_m, double ahead_m) +{ + if (plan.size() < 2) + { + return 0; + } + const std::size_t last_seg = plan.size() - 2; + hint = std::min(hint, last_seg); + + auto seg_len = [&](std::size_t i) { + return std::hypot(plan[i + 1].pose.position.x - plan[i].pose.position.x, + plan[i + 1].pose.position.y - plan[i].pose.position.y); + }; + std::size_t lo = hint; + for (double walked = 0.0; lo > 0 && walked < back_m; --lo) + { + walked += seg_len(lo - 1); + } + std::size_t hi = hint; + for (double walked = 0.0; hi < last_seg && walked < ahead_m; ++hi) + { + walked += seg_len(hi); + } + + const double px = pose.pose.position.x; + const double py = pose.pose.position.y; + std::size_t best = hint; + double best_distance = std::numeric_limits::max(); + for (std::size_t i = lo; i <= hi; ++i) + { + const double distance = + pointToSegment(px, py, plan[i].pose.position.x, plan[i].pose.position.y, + plan[i + 1].pose.position.x, plan[i + 1].pose.position.y); + if (distance < best_distance) + { + best_distance = distance; + best = i; + } + } + return best; +} + std::size_t nearestIndex(const std::vector& plan, const robot_geometry_msgs::PoseStamped& pose) { diff --git a/src/runners/controller_runner.cpp b/src/runners/controller_runner.cpp index fd55ced..5fb098a 100644 --- a/src/runners/controller_runner.cpp +++ b/src/runners/controller_runner.cpp @@ -647,6 +647,17 @@ void ControllerRunner::setMeasuredVelocity(const robot_geometry_msgs::Twist& vel return; } measured_velocity_ = velocity; + has_measured_velocity_ = true; +} + +bool ControllerRunner::measuredVelocity(robot_geometry_msgs::Twist& out) const +{ + if (!has_measured_velocity_) + { + return false; + } + out = measured_velocity_; + return true; } bool ControllerRunner::setTwistLinear(const robot_geometry_msgs::Vector3& linear) diff --git a/test/env_monitor_test.cpp b/test/env_monitor_test.cpp new file mode 100644 index 0000000..892167c --- /dev/null +++ b/test/env_monitor_test.cpp @@ -0,0 +1,933 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm lõi EnvMonitor bằng bảng: chuỗi EnvSample giả ở 20 Hz (tick nặng mỗi 4 cycle = 5 Hz), đo + * verdict. Không costmap, không TF — đúng như lõi được thiết kế để kiểm. + * + * Quy ước harness: robot đi dọc x với v_cmd; `cost_rate` là đạo hàm của cost_to_go theo thời gian + * (−v = tiến đúng, eff 1.0; 0 = lệnh mà không tiến, eff 0). + * + * Author: DuongTD + *********************************************************************/ + +#include + +#include +#include +#include +#include + +#include + +namespace +{ + +using move_base2::EnvMonitor; +using move_base2::EnvMonitorConfig; +using move_base2::EnvRecoveryOutcome; +using move_base2::EnvSample; +using move_base2::EnvVerdict; + +constexpr double kInf = std::numeric_limits::infinity(); +constexpr double kNaN = std::numeric_limits::quiet_NaN(); + +class Harness +{ +public: + explicit Harness(EnvMonitorConfig cfg = EnvMonitorConfig()) + { + std::string error; + ok = monitor.configure(cfg, error); + if (!ok) + { + ADD_FAILURE() << "configure failed: " << error; + } + monitor.onGoalAccepted(now()); + monitor.onPlanApplied(now()); + } + + robot::Time now() const + { + return robot::Time(t); + } + + EnvVerdict step(double v_cmd, double cost_rate, bool move = true) + { + t += dt; + ++cycle; + if (wander_span > 0.0) + { + x = wander_x0 + wander_span * std::sin(2.0 * M_PI * (t - 100.0) / 4.0); // đi vòng trong hộp, bánh vẫn lăn + } + 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 = x; + s.robot_y = 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 = monitor.update(s); + if (last.event[0] != '\0') + { + events += std::string(last.event) + "\n"; + } + return last; + } + + void run(double seconds, double v_cmd, double cost_rate, bool move = true) + { + const int n = static_cast(std::lround(seconds / dt)); + for (int i = 0; i < n; ++i) + { + step(v_cmd, cost_rate, move); + } + } + + /// Chạy tới khi verdict thoả @p pred hoặc hết @p max_seconds; trả thời gian đã chạy (âm = không thoả). + template + double runUntil(double max_seconds, double v_cmd, double cost_rate, Pred pred, bool move = true) + { + const int n = static_cast(std::lround(max_seconds / dt)); + for (int i = 0; i < n; ++i) + { + step(v_cmd, cost_rate, move); + if (pred(last)) + { + return (i + 1) * dt; + } + } + return -1.0; + } + + bool ok = false; + EnvMonitor monitor; + 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; + 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; ///< [m] > 0: x dao động quanh wander_x0 với biên này (quần tại chỗ, không trượt bánh). + double wander_x0 = 0.0; + EnvVerdict last; + std::string events; +}; + +EnvMonitorConfig recoverAll() +{ + EnvMonitorConfig cfg; + cfg.stall.action = "recover"; + cfg.unreachable.action = "recover"; + cfg.contact.action = "recover"; + cfg.stall.disp_min = 0.0; // các test geodesic/ngân sách cũ chạy không cổng dịch chuyển; cổng có test riêng + return cfg; +} + +/// Cổng dịch chuyển bật với cửa sổ ngắn để test chạy nhanh. +EnvMonitorConfig recoverWithDispGate() +{ + EnvMonitorConfig cfg = recoverAll(); + cfg.stall.disp_min = 0.6; // [m] + cfg.stall.disp_window_s = 6.0; // [s] + cfg.stall.disp_min_commanded = 1.0; // [m] + return cfg; +} + +// ------------------------------------------------------------------------------------------ config + +TEST(EnvMonitorConfig, DefaultsValidateAndDescribe) +{ + EnvMonitorConfig cfg; + std::string error; + EXPECT_TRUE(cfg.validate(error)) << error; + EXPECT_NE(std::string::npos, cfg.describe().find("stall")); +} + +TEST(EnvMonitorConfig, RejectsHysteresisInversionActionTypoAndZeroMinCommanded) +{ + std::string error; + EnvMonitorConfig cfg; + cfg.stall.eff_off = cfg.stall.eff_on; + EXPECT_FALSE(cfg.validate(error)); + cfg = EnvMonitorConfig(); + cfg.unreachable.action = "recovery"; + EXPECT_FALSE(cfg.validate(error)); + cfg = EnvMonitorConfig(); + cfg.stall.min_commanded = 0.0; + EXPECT_FALSE(cfg.validate(error)); + cfg = EnvMonitorConfig(); + cfg.contact.brake_decel = 0.0; + EXPECT_FALSE(cfg.validate(error)); + cfg = EnvMonitorConfig(); + cfg.contact.min_check_speed = -0.1; + EXPECT_FALSE(cfg.validate(error)); + cfg = EnvMonitorConfig(); + cfg.replan.escalate_factor = 0.5; + EXPECT_FALSE(cfg.validate(error)); +} + +TEST(EnvMonitorConfig, InvalidConfigLeavesTheMonitorUnconfiguredAndSilent) +{ + EnvMonitorConfig cfg; + cfg.stall.eff_off = 0.1; + EnvMonitor m; + std::string error; + EXPECT_FALSE(m.configure(cfg, error)); + EXPECT_FALSE(m.configured()); + EnvSample s; + s.now = robot::Time(1.0); + const EnvVerdict v = m.update(s); + EXPECT_FALSE(v.no_progress); + EXPECT_FALSE(v.brake); +} + +// ------------------------------------------------------------------------------------------- stall + +TEST(EnvMonitorStall, SteadyProgressNeverStalls) +{ + Harness h(recoverAll()); + h.run(20.0, 0.5, -0.5); // eff = 1.0 suốt + EXPECT_FALSE(h.last.stall_detected); + EXPECT_FALSE(h.last.no_progress); + EXPECT_NEAR(1.0, h.last.eff_geo, 0.05); +} + +TEST(EnvMonitorStall, CommandedWithoutProgressFiresAfterWindowAndConfirm) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); // 1.5 m lệnh: qua cổng đầu chặng, cửa sổ có dữ liệu + // Từ đây lệnh 0.5 m/s nhưng cost đứng: cửa sổ 1.5 m lệnh (= 3 s) + confirm 1 s. + const double took = h.runUntil(10.0, 0.5, 0.0, [](const EnvVerdict& v) { return v.stall_detected; }); + EXPECT_GT(took, 3.0); + EXPECT_LT(took, 5.0); + EXPECT_TRUE(h.last.no_progress); + EXPECT_LT(h.last.eff_geo, 0.2); + EXPECT_NE(std::string::npos, h.events.find("stall: cost_to_go not decreasing")); +} + +TEST(EnvMonitorStall, LogActionReportsButDoesNotRaiseTheFlag) +{ + EnvMonitorConfig cfg = recoverAll(); + cfg.stall.action = "log"; + Harness h(cfg); + h.run(3.0, 0.5, -0.5); + h.run(6.0, 0.5, 0.0); + EXPECT_TRUE(h.last.stall_detected); + EXPECT_FALSE(h.last.no_progress); + EXPECT_FALSE(h.last.stall_muted); +} + +TEST(EnvMonitorStall, HoldingStillIsWaitingNotStalling) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.run(10.0, 0.0, 0.0); // planner hold: lệnh 0 + EXPECT_FALSE(h.last.stall_detected); +} + +TEST(EnvMonitorStall, HysteresisHoldsInTheDeadBandAndClearsAboveEffOff) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.run(6.0, 0.5, 0.0); + ASSERT_TRUE(h.last.stall_detected); + // eff 0.35: trong vùng chết 0.2–0.5 -> giữ kẹt. + h.run(4.0, 0.5, -0.175); + EXPECT_TRUE(h.last.stall_detected); + // eff 0.8 -> xoá. + h.run(4.0, 0.5, -0.4); + EXPECT_FALSE(h.last.stall_detected); + EXPECT_NE(std::string::npos, h.events.find("stall cleared")); +} + +TEST(EnvMonitorStall, GraceAfterANewPlanResetsTheWindow) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.run(6.0, 0.5, 0.0); + ASSERT_TRUE(h.last.stall_detected); + h.monitor.onPlanApplied(h.now()); + h.run(0.8, 0.5, 0.0); + EXPECT_FALSE(h.last.stall_detected); // trong grace + EXPECT_TRUE(std::isnan(h.last.eff_geo)); // cửa sổ đã xoá, chưa đủ mẫu + // Vẫn kẹt trên plan mới: nổ lại sau cửa sổ + confirm. + const double took = h.runUntil(10.0, 0.5, 0.0, [](const EnvVerdict& v) { return v.stall_detected; }); + EXPECT_GT(took, 2.5); + EXPECT_LT(took, 5.0); +} + +TEST(EnvMonitorStall, MinCommandedSinceGoalMutesEarlyFires) +{ + EnvMonitorConfig cfg = recoverAll(); + cfg.stall.window_m = 0.3; // cửa sổ ngắn để kẹt đo được trước khi qua cổng 1.0 m + cfg.stall.window_s = 1.0; + Harness h(cfg); + h.run(2.6, 0.3, 0.0); // 0.78 m lệnh (grace 1 s + cửa sổ 1 s + confirm 1 s), chưa qua cổng 1.0 m + EXPECT_TRUE(h.last.stall_detected); + EXPECT_TRUE(h.last.stall_muted); + EXPECT_FALSE(h.last.no_progress); + h.run(2.0, 0.3, 0.0); // tổng 1.2 m lệnh + EXPECT_TRUE(h.last.stall_detected); + EXPECT_FALSE(h.last.stall_muted); + EXPECT_TRUE(h.last.no_progress); +} + +TEST(EnvMonitorStall, ReplanBudgetMutesUntilTheRobotTravelsAndEscalatesWhenRepeated) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.run(6.0, 0.5, 0.0); + ASSERT_TRUE(h.last.no_progress); + + // Detour thành công -> im tới khi đi 1.5 m. + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath); + h.monitor.onPlanApplied(h.now()); + EXPECT_NEAR(1.5, h.monitor.replanBudget(), 1e-9); + h.run(1.5, 0.5, 0.0); // grace 1 s + kẹt tiếp; đi 0.75 m + h.run(4.0, 0.5, 0.0); // đi thêm 2 m (tổng 2.75 m sau detour) -> hết mute + EXPECT_TRUE(h.last.stall_detected); + EXPECT_FALSE(h.last.stall_muted); + + // Detour thứ hai chỉ 2.75 m sau lần trước (< 10 m): ngân sách nhân đôi. + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath); + h.monitor.onPlanApplied(h.now()); + EXPECT_NEAR(3.0, h.monitor.replanBudget(), 1e-9); + h.run(1.5, 0.5, 0.0); + h.run(3.0, 0.5, 0.0); // đi 2.25 m < 3.0 -> vẫn mute + EXPECT_TRUE(h.last.stall_detected); + EXPECT_TRUE(h.last.stall_muted); + EXPECT_GT(h.last.replan_budget_left, 0.0); +} + +TEST(EnvMonitorStall, ReplanBudgetEscalationIsCapped) +{ + EnvMonitorConfig cfg = recoverAll(); + cfg.replan.escalate_max = 6.0; + Harness h(cfg); + for (int i = 0; i < 4; ++i) + { + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath); + h.monitor.onPlanApplied(h.now()); + h.run(0.5, 0.5, 0.0); // 0.25 m giữa hai detour: trong escalate_window + } + EXPECT_NEAR(6.0, h.monitor.replanBudget(), 1e-9); // 1.5 -> 3 -> 6 -> 6, không lên 12 + EnvMonitorConfig uncapped = recoverAll(); + uncapped.replan.escalate_max = 0.0; + Harness h2(uncapped); + for (int i = 0; i < 4; ++i) + { + h2.monitor.onRecoveryFinished(h2.now(), EnvRecoveryOutcome::kSucceededWithPath); + h2.monitor.onPlanApplied(h2.now()); + h2.run(0.5, 0.5, 0.0); + } + EXPECT_NEAR(12.0, h2.monitor.replanBudget(), 1e-9); + std::string error; + EnvMonitorConfig bad = recoverAll(); + bad.replan.escalate_max = 1.0; // < min_travel 1.5 + EXPECT_FALSE(bad.validate(error)); +} + +TEST(EnvMonitorStall, FailedRecoveryBacksOff) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.run(6.0, 0.5, 0.0); + ASSERT_TRUE(h.last.no_progress); + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kFailed); + h.run(2.0, 0.5, 0.0); // chưa đủ cửa sổ lại (chuỗi xoá) -> có thể chưa detected; chạy tiếp + h.run(3.0, 0.5, 0.0); + // Trong 3 s backoff sau lượt hỏng: kể cả detected cũng bị mute. + EXPECT_FALSE(h.events.find("stall: cost_to_go") == std::string::npos); + Harness h2(recoverAll()); + h2.run(3.0, 0.5, -0.5); + h2.run(6.0, 0.5, 0.0); + h2.monitor.onRecoveryFinished(h2.now(), EnvRecoveryOutcome::kFailed); + bool muted_seen = false; + for (int i = 0; i < 58; ++i) // 2.9 s: nằm trọn trong backoff 3 s + { + h2.step(0.5, 0.0); + if (h2.last.stall_detected) + { + EXPECT_TRUE(h2.last.stall_muted); + muted_seen = true; + } + } + EXPECT_TRUE(muted_seen); + h2.run(2.0, 0.5, 0.0); + EXPECT_TRUE(h2.last.stall_detected); + EXPECT_FALSE(h2.last.stall_muted); +} + +TEST(EnvMonitorStall, WheelSlipIsAStallEvenWhenCostCannotBeMeasured) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.conclusive = false; // hình học không kết luận được + h.v_meas_override = 0.0; // bánh đứng + const double took = h.runUntil(5.0, 0.4, 0.0, [](const EnvVerdict& v) { return v.stall_detected; }, false); + EXPECT_GT(took, 1.9); // slip_time 1 s + confirm 1 s + EXPECT_LT(took, 3.0); + EXPECT_NE(std::string::npos, h.events.find("wheels slip")); +} + +TEST(EnvMonitorStall, NearTheGoalIsNotMeasured) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.d_goal = 0.3; + h.run(8.0, 0.3, 0.0); + EXPECT_FALSE(h.last.stall_detected); +} + +TEST(EnvMonitorStall, TransientUnreachableSamplesAreSkippedNotCounted) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + // Một tick nặng mất liên thông giữa chuỗi tiến đều: không ghi vào cửa sổ, eff không nhảy. + h.reachable = false; + h.run(0.2, 0.5, -0.5); + h.reachable = true; + h.run(2.0, 0.5, -0.5); + EXPECT_FALSE(h.last.stall_detected); + EXPECT_FALSE(h.last.unreachable_detected); + EXPECT_GT(h.last.eff_geo, 0.5); +} + +TEST(EnvMonitorStall, DisplacementGateMutesAGeodesicStallWhileTheRobotMovesOn) +{ + // Run 6/9 00:05 (95 s): robot chạy 0.5 m/s lệch plan để né, geodesic bảo kẹt -> cờ oan. Cổng dịch chuyển: robot đã + // đi 0.5 m/s x 6 s = 3 m -> không phải bế tắc. + Harness h(recoverWithDispGate()); + h.run(9.0, 0.5, 0.0); // cost đứng nhưng x tiến đều + EXPECT_TRUE(h.last.stall_detected); + EXPECT_TRUE(h.last.stall_muted); + EXPECT_FALSE(h.last.no_progress); + EXPECT_FALSE(h.last.wandering); + EXPECT_GT(h.last.net_disp, 2.0); +} + +TEST(EnvMonitorStall, WanderingInABoxPassesTheGateAfterTheWindow) +{ + // Run 6/9 00:05 (109–206 s): hộp 0.9 x 0.5 m, lệnh 6 m, 97 s mới nổ vì ngân sách đo theo quãng đường. + Harness h(recoverWithDispGate()); + h.wander_span = 0.25; // hộp 0.5 m + h.run(3.0, 0.4, 0.0); + EXPECT_FALSE(h.last.no_progress) << "cửa sổ dịch chuyển chưa đủ 6 s"; + const double took = h.runUntil(10.0, 0.4, 0.0, [](const EnvVerdict& v) { return v.no_progress; }); + EXPECT_GT(took, 0.0); + EXPECT_LT(took + 3.0, 7.5); // ~window 6 s (+ grace 1 s đầu) + EXPECT_TRUE(h.last.wandering); + EXPECT_LT(h.last.net_disp, 0.6); +} + +TEST(EnvMonitorStall, NewPlanRestartsTheDisplacementWindowAndReplacesTheBudget) +{ + Harness h(recoverWithDispGate()); + h.wander_span = 0.25; + ASSERT_GT(h.runUntil(12.0, 0.4, 0.0, [](const EnvVerdict& v) { return v.no_progress; }), 0.0); + // Detour thành công -> plan mới: cửa sổ vị trí bắt đầu lại, ngân sách replan KHÔNG câm (cổng thay nó). + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath); + h.monitor.onPlanApplied(h.now()); + h.run(3.0, 0.4, 0.0); + EXPECT_FALSE(h.last.no_progress) << "vừa có plan mới, chưa đủ cửa sổ dịch chuyển"; + const double took = h.runUntil(10.0, 0.4, 0.0, [](const EnvVerdict& v) { return v.no_progress; }); + EXPECT_GT(took, 0.0); + EXPECT_LT(took + 3.0, 7.5); // nổ lại sau ~window, không phải sau 1.5 m quãng đường x leo thang +} + +TEST(EnvMonitorStall, CostJumpRestartsTheWindowInsteadOfStalling) +{ + // Run 5/9 23:37: geo_to_exit nhảy +3.2 m trong một tick (mặt nạ free đổi liên thông) khi robot vẫn đi tốt + // -> eff −2.7 -> detour oan. Với jump_reject 1.0: xoá cửa sổ, không stall; đo lại từ đầu. + Harness h(recoverAll()); + h.run(4.5, 0.5, -0.5); // grace 1 s + cửa sổ 4 s/1.5 m đầy + for (int i = 0; i < 4 && std::isnan(h.last.eff_geo); ++i) + { + h.step(0.5, -0.5); // eff chỉ có ở tick nặng (mỗi 4 cycle) + } + EXPECT_GT(h.last.eff_geo, 0.8); + h.cost += 3.0; // nhảy + h.step(0.5, -0.5); + bool jumped = false; + for (int i = 0; i < 4 && !jumped; ++i) + { + jumped = h.last.cost_jump; + if (!jumped) + { + h.step(0.5, -0.5); + } + } + EXPECT_TRUE(jumped); + h.run(2.0, 0.5, -0.5); // tiếp tục đi tốt sau cú nhảy + EXPECT_FALSE(h.last.stall_detected); + EXPECT_FALSE(h.last.no_progress); + // Không có bộ lọc: cùng kịch bản là stall. + EnvMonitorConfig cfg = recoverAll(); + cfg.stall.jump_reject = 0.0; + Harness h2(cfg); + h2.run(3.0, 0.5, -0.5); + h2.cost += 3.0; + h2.run(2.0, 0.5, -0.5); + EXPECT_TRUE(h2.last.stall_detected); +} + +TEST(EnvMonitorStall, RealStallAfterAJumpIsStillDetected) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.cost += 3.0; + h.step(0.5, -0.5); + // Sau cú nhảy robot đòi đi mà cost đứng: cửa sổ mới cần window_s 4 s + confirm 1 s. + const double took = h.runUntil(8.0, 0.5, 0.0, [](const EnvVerdict& v) { return v.stall_detected; }); + EXPECT_GT(took, 4.0); + EXPECT_LT(took, 6.0); +} + +TEST(EnvMonitorStall, NoPlanOrStaleCostmapClearsTheChain) +{ + Harness h(recoverAll()); + h.run(3.0, 0.5, -0.5); + h.run(6.0, 0.5, 0.0); + ASSERT_TRUE(h.last.stall_detected); + h.costmap_current = false; + h.step(0.5, 0.0); + EXPECT_FALSE(h.last.stall_detected); + EXPECT_FALSE(h.last.no_progress); +} + +// ------------------------------------------------------------------------------------- unreachable + +TEST(EnvMonitorUnreachable, FiresAfterStaticTimeOnCleanGround) +{ + Harness h(recoverAll()); + h.run(2.0, 0.5, -0.5); // baseline: liên thông + h.reachable = false; + const double took = h.runUntil(5.0, 0.3, 0.0, [](const EnvVerdict& v) { return v.path_blocked; }); + EXPECT_GT(took, 0.9); + EXPECT_LT(took, 1.5); + EXPECT_TRUE(h.last.unreachable_detected); + h.reachable = true; + h.run(0.4, 0.3, -0.3); + EXPECT_FALSE(h.last.unreachable_detected); + EXPECT_NE(std::string::npos, h.events.find("unreachable cleared")); +} + +TEST(EnvMonitorUnreachable, RobotAlreadyInsideTheBandDoesNotFire) +{ + Harness h(recoverAll()); + h.run(2.0, 0.5, -0.5); + h.reachable = false; + h.edt_body = 0.1; // < clean_start_margin: SBPL không có chỗ bắt đầu + h.run(4.0, 0.3, 0.0); + EXPECT_FALSE(h.last.unreachable_detected); + EXPECT_FALSE(h.last.path_blocked); +} + +TEST(EnvMonitorUnreachable, PlanBornUnreachableIsNotArguedWith) +{ + // R2: plan vừa nhận đã không liên thông -> SBPL/planner đã lập trên cùng dữ liệu, monitor im. + Harness h(recoverAll()); + h.reachable = false; + h.run(1.5, 0.3, 0.0); // qua grace, baseline = không liên thông + h.run(5.0, 0.3, 0.0); + EXPECT_FALSE(h.last.unreachable_detected); + // Liên thông trở lại rồi mất lần nữa: đó là chuyện MỚI -> nổ. + h.reachable = true; + h.run(0.4, 0.3, -0.3); + h.reachable = false; + h.run(2.0, 0.3, 0.0); + EXPECT_TRUE(h.last.unreachable_detected); +} + +TEST(EnvMonitorUnreachable, LogActionDoesNotRaiseTheFlag) +{ + EnvMonitorConfig cfg = recoverAll(); + cfg.unreachable.action = "log"; + Harness h(cfg); + h.run(2.0, 0.5, -0.5); + h.reachable = false; + h.run(3.0, 0.3, 0.0); + EXPECT_TRUE(h.last.unreachable_detected); + EXPECT_FALSE(h.last.path_blocked); +} + +TEST(EnvMonitorUnreachable, ReplanBudgetAppliesToo) +{ + Harness h(recoverAll()); + h.run(2.0, 0.5, -0.5); + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath); + h.monitor.onPlanApplied(h.now()); + h.run(1.2, 0.3, -0.3); // baseline liên thông sau grace + h.reachable = false; + h.run(3.0, 0.3, 0.0); // đi 0.9 m < 1.5 m ngân sách + EXPECT_TRUE(h.last.unreachable_detected); + EXPECT_TRUE(h.last.unreachable_muted); + EXPECT_FALSE(h.last.path_blocked); +} + +// ---------------------------------------------------------------------------------------- contact + +TEST(EnvMonitorContact, BrakesWhenContactIsWithinTheStoppingDistanceAndFlagsWhenItPersists) +{ + Harness h(recoverAll()); + h.contact_dist = 0.5; // v 0.5 -> quãng phanh 0.357; 0.5 - 0.357 = 0.143 <= margin 0.2 -> sắp chạm + h.step(0.5, -0.5); + EXPECT_TRUE(h.last.contact_imminent); + EXPECT_FALSE(h.last.brake); // confirm 2 cycle + h.step(0.5, -0.5); + EXPECT_TRUE(h.last.brake); + EXPECT_FALSE(h.last.collision); + EXPECT_NEAR(std::sqrt(2.0 * 0.35 * 0.2), h.last.v_cap, 1e-6); // dư bao 0.1: room = 0.5 - 0.2 - 0.1 + // Đứng lại (v = 0) với vật còn cách 0.5 m: quãng phanh về 0 -> KHÔNG còn "sắp chạm". Nhả phanh sau + // release_confirm_cycles (4) cycle liên tiếp, rồi robot được bò dưới bao tốc độ; không có cờ vì vật chưa kề mũi. + h.run(0.15, 0.0, 0.0, false); // 3 cycle: vẫn giữ + EXPECT_TRUE(h.last.brake); + h.step(0.0, 0.0, false); // cycle 4: nhả + EXPECT_FALSE(h.last.brake); + EXPECT_FALSE(h.last.collision); + EXPECT_NE(std::string::npos, h.events.find("contact receded")); + EXPECT_NEAR(std::sqrt(2.0 * 0.35 * 0.2), h.last.v_cap, 1e-6); // dư bao 0.1: room = 0.5 - 0.2 - 0.1 + // Vật bước tới sát mũi (0.15 m <= margin 0.2) và đứng đó. Robot đang đứng (v = 0, chưa phanh) thì monitor + // không xét (min_check_speed) — controller tự lo; controller muốn tiến 0.3 m/s là phanh lại ngay, và + // sau 1 s kề mũi giơ cờ collision. + h.contact_dist = 0.15; + const double took = h.runUntil(3.0, 0.3, 0.0, [](const EnvVerdict& v) { return v.collision; }, false); + EXPECT_GT(took, 0.9); + EXPECT_LT(took, 1.2); + EXPECT_TRUE(h.last.brake); + EXPECT_NEAR(0.0, h.last.v_cap, 1e-9); + // Vật đi rồi: phanh và cờ cùng giữ thêm release_confirm_cycles (4) cycle sạch liên tiếp rồi mới hạ — + // một mẫu sạch chưa là sạch khi local planner đổi quỹ đạo mỗi cycle. + h.contact_dist = kInf; + h.run(0.15, 0.0, 0.0, false); + EXPECT_TRUE(h.last.brake); + EXPECT_TRUE(h.last.collision); + h.step(0.0, 0.0, false); + EXPECT_FALSE(h.last.brake); + EXPECT_FALSE(h.last.collision); + EXPECT_NE(std::string::npos, h.events.find("contact cleared")); +} + +TEST(EnvMonitorContact, PivotingOrCreepingNextToAnObstacleIsTheControllersBusiness) +{ + // Robot vừa nhận goal, đứng cách vật 8 cm, xoay tại chỗ / bò ra (v 0.07 < min_check_speed 0.10): quỹ đạo + // local planner có góc thân quét vào ô kề bên. Guard cũ ghim robot ở đây rồi gọi detour từ chính chỗ + // đó (churn mission 5/6 shadow 5/9). Monitor mới: không phanh, không cờ, không sự kiện. + Harness h(recoverAll()); + h.contact_dist = 0.08; + h.run(2.0, 0.07, 0.0, false); + EXPECT_FALSE(h.last.brake); + EXPECT_FALSE(h.last.collision); + EXPECT_FALSE(h.last.contact_imminent); + EXPECT_TRUE(h.events.empty()) << h.events; + EXPECT_NEAR(0.0, h.last.v_cap, 1e-9); // bao tốc độ vẫn tính: vật trong margin -> muốn tiến là 0 + // Bắt đầu tiến thật (0.4 m/s) vào vật: phanh sau confirm 2 cycle, và vì đã phanh nên đứng lại (v = 0) + // vẫn xét tiếp -> 1 s kề mũi -> cờ collision. Cổng tốc độ không che được tiếp xúc thật. + h.step(0.4, 0.0, false); + h.step(0.4, 0.0, false); + EXPECT_TRUE(h.last.brake); + const double took = h.runUntil(3.0, 0.0, 0.0, [](const EnvVerdict& v) { return v.collision; }, false); + EXPECT_GT(took, 0.0); + EXPECT_LT(took, 1.2); + EXPECT_TRUE(h.last.brake); +} + +TEST(EnvMonitorContact, CommandCappedToZeroWhileTheControllerStillPushesIsABrakeNotAPivot) +{ + // Bao tốc độ đã kẹp lệnh về 0 trong margin (v_cmd = 0, v_đo = 0) nhưng controller vẫn đòi 0.3 m/s: + // KHÔNG phải xoay tại chỗ — phải phanh có sự kiện rồi giơ cờ, không dừng câm. + Harness h(recoverAll()); + h.contact_dist = 0.10; + h.v_controller_override = 0.3; + h.step(0.0, 0.0, false); + h.step(0.0, 0.0, false); + EXPECT_TRUE(h.last.brake); + EXPECT_NE(std::string::npos, h.events.find("braking to zero")); + const double took = h.runUntil(3.0, 0.0, 0.0, [](const EnvVerdict& v) { return v.collision; }, false); + EXPECT_GT(took, 0.0); + EXPECT_LT(took, 1.2); + // Controller thôi đòi đi (xoay tại chỗ) NHƯNG monitor đã phanh: vẫn giữ tới khi quỹ đạo sạch đủ lâu. + h.v_controller_override = 0.0; + h.step(0.0, 0.0, false); + EXPECT_TRUE(h.last.brake); + h.contact_dist = kInf; + h.run(0.2, 0.0, 0.0, false); + EXPECT_FALSE(h.last.brake); + EXPECT_FALSE(h.last.collision); +} + +TEST(EnvMonitorContact, TrajectoryJitterAroundTheMarginHoldsTheBrakeAndStillRaisesTheFlag) +{ + // Run 5/9 22:35 (mission 1, 70–71 s): PRIEST đổi quỹ đạo mỗi cycle, d nhảy 0.08 <-> 0.25 m quanh margin + // 0.2 -> phanh/nhả 6 lần trong 1.2 s, đồng hồ kề mũi reset liên tục, cờ không bao giờ nổ. Với hysteresis + // 0.1 m: đã kề thì 0.25 vẫn là kề -> phanh giữ, cờ nổ sau 1 s, đúng một sự kiện phanh và một sự kiện cờ. + Harness h(recoverAll()); + h.v_controller_override = 0.3; + double fired_at = -1.0; + for (int i = 0; i < 40; ++i) + { + h.contact_dist = (i % 2 == 0) ? 0.08 : 0.25; + h.step(0.0, 0.0, false); + if (h.last.collision && fired_at < 0.0) + { + fired_at = (i + 1) * h.dt; + } + if (i >= 2) + { + EXPECT_TRUE(h.last.brake) << "cycle " << i; + } + } + EXPECT_GT(fired_at, 0.9); + EXPECT_LT(fired_at, 1.3); + auto count = [&](const char* needle) { + int n = 0; + for (std::size_t pos = h.events.find(needle); pos != std::string::npos; pos = h.events.find(needle, pos + 1)) + { + ++n; + } + return n; + }; + EXPECT_EQ(1, count("braking to zero")) << h.events; + EXPECT_EQ(1, count("persists")) << h.events; + EXPECT_EQ(0, count("receded")) << h.events; + EXPECT_EQ(0, count("cleared")) << h.events; +} + +TEST(EnvMonitorContact, RidingTheEnvelopeIsNotImminent) +{ + // Lệnh đúng bằng bao: quãng phanh = d - margin - dư -> còn dư 0.1 m so với ngưỡng phanh -> không phanh. + Harness h(recoverAll()); + h.contact_dist = 0.5; + const double v_cap = std::sqrt(2.0 * 0.35 * 0.2); + h.run(0.5, v_cap, 0.0, false); + EXPECT_FALSE(h.last.contact_imminent); + EXPECT_FALSE(h.last.brake); + EXPECT_NEAR(v_cap, h.last.v_cap, 1e-6); + // Giữa margin và margin + dư: bò min_speed, chưa phanh khi đang bò. + h.contact_dist = 0.25; + h.run(0.5, 0.05, 0.0, false); + EXPECT_NEAR(0.05, h.last.v_cap, 1e-9); + EXPECT_FALSE(h.last.brake); +} + +TEST(EnvMonitorContact, StandsDownWhenTheDetourFromThisSpotDidNotMoveTheRobot) +{ + // m1/m8 run 5/9 22:58: cờ -> detour -> robot không rời chỗ -> chạm lại -> cờ -> detour ... 3 lần rồi ABORT. + Harness h(recoverAll()); + h.contact_dist = 0.10; + h.v_controller_override = 0.3; + const double took = h.runUntil(3.0, 0.0, 0.0, [](const EnvVerdict& v) { return v.collision; }, false); + ASSERT_GT(took, 0.0); + // Detour do cờ collision thành công, robot vẫn đứng nguyên. + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath, true); + h.events.clear(); + h.step(0.0, 0.0, false); + h.step(0.0, 0.0, false); // confirm 2 cycle -> thay vì phanh: đứng ra + EXPECT_TRUE(h.last.contact_standdown); + EXPECT_FALSE(h.last.brake); + EXPECT_FALSE(h.last.collision); + EXPECT_TRUE(std::isinf(h.last.v_cap)); + EXPECT_NE(std::string::npos, h.events.find("standing down")) << h.events; + // Đứng ra suốt 2 s dù chạm 0.07 m liên tục: không phanh, không cờ, không sự kiện mới. (v_cmd 0 + v_controller + // 0.3 để không kích slip của kStall — harness không mô phỏng bánh lăn.) + h.events.clear(); + h.contact_dist = 0.07; + h.run(2.0, 0.0, 0.0, false); + EXPECT_TRUE(h.last.contact_standdown); + EXPECT_FALSE(h.last.brake); + EXPECT_FALSE(h.last.collision); + EXPECT_TRUE(h.events.empty()) << h.events; + // Robot đi được 0.35 m: vũ trang lại, chạm 0.07 m ở 0.2 m/s -> phanh như thường. + h.x += 0.35; + h.step(0.2, 0.0, true); + EXPECT_FALSE(h.last.contact_standdown); + EXPECT_NE(std::string::npos, h.events.find("re-armed after moving on")) << h.events; + h.step(0.2, 0.0, true); + h.step(0.2, 0.0, true); + EXPECT_TRUE(h.last.brake); +} + +TEST(EnvMonitorContact, StandDownEndsWhenTheTrajectoryStaysClear) +{ + Harness h(recoverAll()); + h.contact_dist = 0.10; + h.v_controller_override = 0.3; + ASSERT_GT(h.runUntil(3.0, 0.0, 0.0, [](const EnvVerdict& v) { return v.collision; }, false), 0.0); + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath, true); + h.step(0.0, 0.0, false); + h.step(0.0, 0.0, false); + ASSERT_TRUE(h.last.contact_standdown); + h.contact_dist = kInf; + h.run(0.15, 0.1, 0.0, false); // 3 cycle sạch: chưa + EXPECT_TRUE(h.last.contact_standdown); + h.step(0.1, 0.0, false); // cycle 4: vũ trang lại + EXPECT_FALSE(h.last.contact_standdown); + EXPECT_NE(std::string::npos, h.events.find("re-armed, the trajectory is clear")) << h.events; +} + +TEST(EnvMonitorContact, DetourThatMovedTheRobotDoesNotDisarmTheNextContact) +{ + Harness h(recoverAll()); + h.contact_dist = 0.10; + h.v_controller_override = 0.3; + ASSERT_GT(h.runUntil(3.0, 0.0, 0.0, [](const EnvVerdict& v) { return v.collision; }, false), 0.0); + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath, true); + h.contact_dist = kInf; + h.run(1.0, 0.3, 0.0, true); // đi 0.3 m trên đường mới, sạch + h.contact_dist = 0.10; // chạm mới ở chỗ khác -> phanh bình thường, không đứng ra + h.step(0.3, 0.0, false); + h.step(0.3, 0.0, false); + EXPECT_TRUE(h.last.brake); + EXPECT_FALSE(h.last.contact_standdown); +} + +TEST(EnvMonitorContact, DetourFromAnotherTriggerDoesNotArmTheStandDown) +{ + // controlling_failed / PRIEST tự khai: detour không phải do cờ collision -> chạm sau đó vẫn phanh + cờ. + Harness h(recoverAll()); + h.monitor.onRecoveryFinished(h.now(), EnvRecoveryOutcome::kSucceededWithPath, false); + h.contact_dist = 0.10; + h.v_controller_override = 0.3; + h.step(0.0, 0.0, false); + h.step(0.0, 0.0, false); + EXPECT_TRUE(h.last.brake); + EXPECT_FALSE(h.last.contact_standdown); +} + +TEST(EnvMonitorContact, OneCleanSampleDoesNotReleaseTheBrake) +{ + Harness h(recoverAll()); + h.contact_dist = 0.10; + h.step(0.5, 0.0, false); + h.step(0.5, 0.0, false); + ASSERT_TRUE(h.last.brake); + // Sạch 3 cycle rồi chạm lại: vẫn phanh, không có sự kiện nhả. + h.contact_dist = kInf; + h.run(0.15, 0.0, 0.0, false); + EXPECT_TRUE(h.last.brake); + h.contact_dist = 0.10; + h.step(0.0, 0.0, false); + EXPECT_TRUE(h.last.brake); + EXPECT_EQ(std::string::npos, h.events.find("cleared")) << h.events; + // Sạch 4 cycle liên tiếp: nhả. + h.contact_dist = kInf; + h.run(0.2, 0.0, 0.0, false); + EXPECT_FALSE(h.last.brake); + EXPECT_NE(std::string::npos, h.events.find("cleared")); +} + +TEST(EnvMonitorContact, MinCheckSpeedZeroRestoresTheOldGuardBehaviour) +{ + EnvMonitorConfig cfg = recoverAll(); + cfg.contact.min_check_speed = 0.0; + Harness h(cfg); + h.contact_dist = 0.08; + h.step(0.07, 0.0, false); + h.step(0.07, 0.0, false); + EXPECT_TRUE(h.last.brake); +} + +TEST(EnvMonitorContact, FarContactOnlyCapsSpeed) +{ + Harness h(recoverAll()); + h.contact_dist = 2.0; + h.run(1.0, 0.5, -0.5); + EXPECT_FALSE(h.last.contact_imminent); + EXPECT_FALSE(h.last.brake); + EXPECT_NEAR(std::sqrt(2.0 * 0.35 * 1.7), h.last.v_cap, 1e-6); // room = 2.0 - margin 0.2 - dư 0.1 + h.contact_dist = kInf; + h.step(0.5, -0.5); + EXPECT_TRUE(std::isinf(h.last.v_cap)); +} + +TEST(EnvMonitorContact, InconclusiveSweepNeitherBrakesNorReleases) +{ + Harness h(recoverAll()); + h.contact_dist = 0.3; + h.run(0.2, 0.5, -0.5); + ASSERT_TRUE(h.last.brake); + h.contact_conclusive = false; + h.step(0.0, 0.0, false); + EXPECT_TRUE(h.last.brake); // không biết thì giữ nguyên, không nhả + Harness h2(recoverAll()); + h2.contact_conclusive = false; + h2.contact_dist = 0.1; + h2.run(1.0, 0.5, -0.5); + EXPECT_FALSE(h2.last.brake); // không biết thì cũng không dừng +} + +TEST(EnvMonitorContact, MeasuredSpeedExtendsTheStoppingDistance) +{ + Harness h(recoverAll()); + h.contact_dist = 0.6; + h.v_meas_override = 0.6; // lệnh 0.2 nhưng đo 0.6 -> quãng phanh theo 0.6 = 0.514 -> sắp chạm + h.run(0.2, 0.2, -0.2); + EXPECT_TRUE(h.last.contact_imminent); + EXPECT_NEAR(0.6 * 0.6 / (2.0 * 0.35), h.last.brake_dist, 1e-9); +} + +// ---------------------------------------------------------------------------------------- disabled + +TEST(EnvMonitorSwitches, DisabledMonitorIsSilent) +{ + EnvMonitorConfig cfg = recoverAll(); + cfg.enabled = false; + Harness h(cfg); + h.contact_dist = 0.1; + h.reachable = false; + h.run(8.0, 0.5, 0.0); + EXPECT_FALSE(h.last.brake); + EXPECT_FALSE(h.last.no_progress); + EXPECT_FALSE(h.last.path_blocked); + EXPECT_TRUE(std::isinf(h.last.v_cap)); +} + +TEST(EnvMonitorSwitches, EachVerdictCanBeDisabledAlone) +{ + EnvMonitorConfig cfg = recoverAll(); + cfg.stall.enabled = false; + cfg.contact.enabled = false; + Harness h(cfg); + h.run(3.0, 0.5, -0.5); + h.contact_dist = 0.1; + h.reachable = false; + h.run(6.0, 0.5, 0.0); + EXPECT_FALSE(h.last.stall_detected); + EXPECT_FALSE(h.last.brake); + EXPECT_TRUE(h.last.path_blocked); +} + +} // namespace + +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/fake_ports.h b/test/fake_ports.h index 3db62f7..b8360b7 100644 --- a/test/fake_ports.h +++ b/test/fake_ports.h @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -982,6 +983,129 @@ private: mutable std::size_t motion_query_count_ = 0; }; +/** + * @class FakeEnvironmentPort + * @brief Cổng môi trường giả cho EnvMonitor: kịch bản quyết định cost_to_go / tiếp xúc, không cần costmap. + * + * Mặc định "không kết luận được" cho hình học và quỹ đạo (như cổng gốc thiếu costmap/TF) nhưng CÓ thân + * (footprint) — để các test cũ chạy với EnvMonitor bật mà không sinh verdict nào. + */ +class FakeEnvironmentPort final : public EnvironmentPort +{ +public: + bool sampleGeometry(const EnvGeometryRequest& request, EnvGeometry& out) override + { + (void)request; + ++geometry_query_count_; + if (!geometry_available_) + { + return false; + } + out = EnvGeometry(); + out.valid = true; + out.free_radius = body_side_; + out.cost.conclusive = true; + out.cost.reachable = reachable_; + out.cost.cost_to_go = reachable_ ? cost_to_go_ : std::numeric_limits::infinity(); + out.edt_body_min = edt_body_min_; + return true; + } + + bool sweepTrajectory(const EnvTrajectoryRequest& request, SweepResult& out, bool& used_local_plan) override + { + (void)request; + ++sweep_query_count_; + used_local_plan = false; + if (!sweep_available_) + { + return false; + } + out = SweepResult(); + out.conclusive = true; + out.scanned = 1; + out.blocked = contact_blocked_; + out.distance = contact_blocked_ ? contact_distance_ : 0.0; + return true; + } + + bool robotBodyExtents(double& front, double& rear, double& side) const override + { + if (!body_available_) + { + return false; + } + front = body_front_; + rear = body_rear_; + side = body_side_; + return true; + } + + /// @param distance [m] quãng dọc quỹ đạo tới điểm chạm. + void setContact(bool blocked, double distance = 0.1) + { + sweep_available_ = true; + contact_blocked_ = blocked; + contact_distance_ = distance; + } + + void setSweepAvailable(bool available) + { + sweep_available_ = available; + } + + /// @param cost_to_go [m] chi phí còn lại; @p edt_body_min [m] khoảng trống thân. + void setGeometry(bool reachable, double cost_to_go, double edt_body_min = 1.0) + { + geometry_available_ = true; + reachable_ = reachable; + cost_to_go_ = cost_to_go; + edt_body_min_ = edt_body_min; + } + + void setGeometryAvailable(bool available) + { + geometry_available_ = available; + } + + void setBodyExtents(double front, double rear, double side) + { + body_available_ = true; + body_front_ = front; + body_rear_ = rear; + body_side_ = side; + } + + void setBodyAvailable(bool available) + { + body_available_ = available; + } + + std::size_t sweepQueryCount() const + { + return sweep_query_count_; + } + + std::size_t geometryQueryCount() const + { + return geometry_query_count_; + } + +private: + bool geometry_available_ = false; + bool reachable_ = true; + double cost_to_go_ = 10.0; // [m] + double edt_body_min_ = 1.0; // [m] + bool sweep_available_ = false; + bool contact_blocked_ = false; + double contact_distance_ = 0.1; // [m] + bool body_available_ = true; + double body_front_ = 0.58; // [m] + double body_rear_ = 0.58; // [m] + double body_side_ = 0.48; // [m] + std::size_t geometry_query_count_ = 0; + std::size_t sweep_query_count_ = 0; +}; + class FakeMissionPort final : public MissionPort { public: diff --git a/test/grid_analysis_test.cpp b/test/grid_analysis_test.cpp new file mode 100644 index 0000000..c72950d --- /dev/null +++ b/test/grid_analysis_test.cpp @@ -0,0 +1,683 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm grid_analysis: EDT, mặt nạ tự do, trường địa trắc (cấm cắt góc), cost_to_go theo plan, hành + * lang vuông góc với plan, khoảng trống thân, kéo footprint dọc quỹ đạo. + * + * Lưới 10 x 10 m, ô 0.05 m — cùng resolution với local costmap runtime. Thân 1.166 x 0.96 m như + * footprint sim (front = rear = 0.583, side = 0.48), inscribed 0.48. + * + * Author: DuongTD + *********************************************************************/ + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include + +namespace +{ + +using move_base2::analyzeGrid; +using move_base2::bodyClearance; +using move_base2::computeGeodesic; +using move_base2::CorridorParams; +using move_base2::CorridorResult; +using move_base2::costToGo; +using move_base2::CostToGoParams; +using move_base2::CostToGoResult; +using move_base2::distanceAt; +using move_base2::GridScratch; +using move_base2::PlanarTransform; +using move_base2::scanCorridor; +using move_base2::SweepParams; +using move_base2::SweepResult; +using move_base2::sweepTrajectory; + +constexpr double kRes = 0.05; +constexpr double kInscribed = 0.48; +constexpr unsigned char kLethal = robot_costmap_2d::LETHAL_OBSTACLE; +constexpr double kInf = std::numeric_limits::infinity(); + +robot_geometry_msgs::PoseStamped makePose(double x, double y, double yaw = 0.0) +{ + robot_geometry_msgs::PoseStamped pose; + pose.header.frame_id = "odom"; + pose.pose.position.x = x; + pose.pose.position.y = y; + pose.pose.orientation.z = std::sin(0.5 * yaw); + pose.pose.orientation.w = std::cos(0.5 * yaw); + return pose; +} + +std::vector linePlan(double from_x, double to_x, double step, + double y = 0.0) +{ + std::vector plan; + for (double x = from_x; x <= to_x + 1e-9; x += step) + { + plan.push_back(makePose(x, y)); + } + return plan; +} + +nav_test_harness::FakeCostmap makeGrid() +{ + return nav_test_harness::FakeCostmap::centered(10.0, kRes); +} + +/// Vạch ô lethal thẳng từ (x0,y0) tới (x1,y1), bước nửa ô. +void lethalLine(nav_test_harness::FakeCostmap& grid, double x0, double y0, double x1, double y1) +{ + const double len = std::hypot(x1 - x0, y1 - y0); + const int n = std::max(1, static_cast(std::ceil(len / (0.5 * kRes)))); + for (int i = 0; i <= n; ++i) + { + const double t = static_cast(i) / n; + grid.setLethalAt(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t); + } +} + +bool cellOf(const GridScratch& s, double x, double y, unsigned int& mx, unsigned int& my) +{ + return s.toCell(x, y, mx, my); +} + +double geoAt(const GridScratch& s, double x, double y) +{ + unsigned int mx = 0; + unsigned int my = 0; + if (!cellOf(s, x, y, mx, my)) + { + return std::numeric_limits::quiet_NaN(); + } + return s.geo[s.index(mx, my)]; +} + +// ------------------------------------------------------------------------------------------ EDT + +TEST(GridAnalysisEdt, EmptyGridIsAllFreeAndInfinitelyFar) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + EXPECT_TRUE(std::isinf(distanceAt(s, 0.0, 0.0))); + unsigned int mx = 0; + unsigned int my = 0; + ASSERT_TRUE(cellOf(s, 2.0, -3.0, mx, my)); + EXPECT_EQ(1, s.free[s.index(mx, my)]); +} + +TEST(GridAnalysisEdt, DistanceToASingleLethalCellIsEuclidean) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalAt(0.0, 0.0); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + + EXPECT_NEAR(0.0, distanceAt(s, 0.0, 0.0), 1e-6); + EXPECT_NEAR(1.0, distanceAt(s, 1.0, 0.0), 1.5 * kRes); + EXPECT_NEAR(std::hypot(0.5, 0.5), distanceAt(s, 0.5, 0.5), 1.5 * kRes); + EXPECT_NEAR(3.0, distanceAt(s, -3.0, 0.0), 1.5 * kRes); + + // Mặt nạ tự do theo inscribed: 0.3 m thì tâm không đặt được, 0.6 m thì được. + unsigned int mx = 0; + unsigned int my = 0; + ASSERT_TRUE(cellOf(s, 0.3, 0.0, mx, my)); + EXPECT_EQ(0, s.free[s.index(mx, my)]); + ASSERT_TRUE(cellOf(s, 0.6, 0.0, mx, my)); + EXPECT_EQ(1, s.free[s.index(mx, my)]); +} + +TEST(GridAnalysisEdt, UnknownAndInflationAreNotObstacles) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setCostAt(0.0, 0.0, robot_costmap_2d::NO_INFORMATION); + grid.setCostAt(1.0, 1.0, robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + EXPECT_TRUE(std::isinf(distanceAt(s, 0.0, 0.0))); + EXPECT_TRUE(std::isinf(distanceAt(s, 1.0, 1.0))); +} + +TEST(GridAnalysisEdt, OutsideTheGridIsNaN) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + EXPECT_TRUE(std::isnan(distanceAt(s, 7.0, 0.0))); +} + +// ------------------------------------------------------------------------------------- geodesic + +TEST(GridAnalysisGeodesic, OpenFieldMatchesOctileDistance) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + unsigned int tx = 0; + unsigned int ty = 0; + ASSERT_TRUE(cellOf(s, 0.0, 0.0, tx, ty)); + std::size_t visited = 0; + ASSERT_TRUE(computeGeodesic(tx, ty, s, &visited)); + EXPECT_GT(visited, 0u); + + EXPECT_NEAR(0.0, geoAt(s, 0.0, 0.0), 1e-6); + EXPECT_NEAR(2.0, geoAt(s, 2.0, 0.0), 2.0 * kRes); + EXPECT_NEAR(2.0 * std::sqrt(2.0), geoAt(s, 2.0, 2.0), 2.0 * kRes); +} + +TEST(GridAnalysisGeodesic, WallForcesTheWayAround) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + lethalLine(grid, 1.0, -1.5, 1.0, 1.5); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + unsigned int tx = 0; + unsigned int ty = 0; + ASSERT_TRUE(cellOf(s, 0.0, 0.0, tx, ty)); + ASSERT_TRUE(computeGeodesic(tx, ty, s)); + + const double behind = geoAt(s, 2.0, 0.0); + EXPECT_TRUE(std::isfinite(behind)); + // Thẳng là 2.0 m; phải vòng qua đầu tường (1.5 m + inscribed) nên dài hơn hẳn. + EXPECT_GT(behind, 3.5); + // Ô ngay trong dải cấm quanh tường không có đường (không free). + EXPECT_TRUE(std::isinf(geoAt(s, 1.0, 0.0))); +} + +TEST(GridAnalysisGeodesic, SealedRoomIsUnreachable) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + lethalLine(grid, -1.5, -1.5, 1.5, -1.5); + lethalLine(grid, 1.5, -1.5, 1.5, 1.5); + lethalLine(grid, 1.5, 1.5, -1.5, 1.5); + lethalLine(grid, -1.5, 1.5, -1.5, -1.5); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + unsigned int tx = 0; + unsigned int ty = 0; + ASSERT_TRUE(cellOf(s, 0.0, 0.0, tx, ty)); + ASSERT_TRUE(computeGeodesic(tx, ty, s)); + EXPECT_TRUE(std::isfinite(geoAt(s, 0.5, 0.5))); + EXPECT_TRUE(std::isinf(geoAt(s, 3.0, 3.0))); +} + +TEST(GridAnalysisGeodesic, DiagonalWallOfSingleCellsIsNotLeaked) +{ + // Bán kính free ~0 để mặt nạ = "không lethal": tường chéo gồm các ô (i, i) chỉ chạm nhau ở góc. + nav_test_harness::FakeCostmap grid = makeGrid(); + for (int i = -100; i < 100; ++i) // trọn đường chéo của lưới 200 ô, không để hở hai đầu + { + grid.setLethalAt(i * kRes + 0.5 * kRes, i * kRes + 0.5 * kRes); + } + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, 0.01, s)); + unsigned int tx = 0; + unsigned int ty = 0; + ASSERT_TRUE(cellOf(s, 1.0, -1.0, tx, ty)); + ASSERT_TRUE(computeGeodesic(tx, ty, s)); + // Không cắt góc: bên kia tường chéo phải là +inf, cùng bên thì tới được. + EXPECT_TRUE(std::isinf(geoAt(s, -1.0, 1.0))); + EXPECT_TRUE(std::isfinite(geoAt(s, 2.0, -2.0))); +} + +TEST(GridAnalysisGeodesic, TargetInsideTheForbiddenBandIsRejected) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalAt(0.0, 0.0); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + unsigned int tx = 0; + unsigned int ty = 0; + ASSERT_TRUE(cellOf(s, 0.2, 0.0, tx, ty)); + EXPECT_FALSE(computeGeodesic(tx, ty, s)); +} + +// ----------------------------------------------------------------------------------- cost to go + +TEST(GridAnalysisCostToGo, StraightPlanInTheWindowEqualsRemainingLength) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(-3.0, 3.0, 0.1); + + CostToGoResult r = costToGo(plan, 0, -3.0, 0.0, CostToGoParams(), PlanarTransform(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_TRUE(r.reachable); + EXPECT_EQ(CostToGoResult::Target::kGoal, r.target); + EXPECT_NEAR(6.0, r.cost_to_go, 0.15); + EXPECT_NEAR(0.0, r.arc_rest, 1e-9); + + // Robot giữa plan: còn 3 m. + r = costToGo(plan, 30, 0.0, 0.0, CostToGoParams(), PlanarTransform(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_NEAR(3.0, r.cost_to_go, 0.15); +} + +TEST(GridAnalysisCostToGo, LateralDeviationCostsTheOctileDetour) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(-3.0, 3.0, 0.1); + // Robot lệch 1.5 m ngang tại x = 0: đường 8-liên-thông tới (3, 0) dài 1.5*sqrt2 + 1.5 = 3.62 m. + const CostToGoResult r = costToGo(plan, 30, 0.0, 1.5, CostToGoParams(), PlanarTransform(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_TRUE(r.reachable); + EXPECT_NEAR(3.62, r.cost_to_go, 0.2); +} + +TEST(GridAnalysisCostToGo, PlanLeavingTheWindowUsesTheExitPointPlusRemainingArc) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(0.0, 8.0, 0.1); // rời lưới ở x = 5 + const CostToGoResult r = costToGo(plan, 0, 0.0, 0.0, CostToGoParams(), PlanarTransform(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_TRUE(r.reachable); + EXPECT_EQ(CostToGoResult::Target::kExit, r.target); + EXPECT_GT(r.arc_rest, 2.9); + EXPECT_LT(r.arc_rest, 3.2); + EXPECT_NEAR(8.0, r.cost_to_go, 0.2); +} + +TEST(GridAnalysisCostToGo, ExitAheadPinsTheTargetAtAFixedArcLength) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(0.0, 8.0, 0.1); // rời lưới ở x = 5 + CostToGoParams params; + params.exit_ahead = 2.0; + const CostToGoResult r = costToGo(plan, 0, 0.0, 0.0, params, PlanarTransform(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_TRUE(r.reachable); + EXPECT_EQ(CostToGoResult::Target::kAhead, r.target); + EXPECT_EQ(20u, r.target_index); // pose ở x = 2.0 + EXPECT_NEAR(6.0, r.arc_rest, 0.05); // 8 − 2 + EXPECT_NEAR(8.0, r.cost_to_go, 0.2); // geo 2 + arc 6: cùng tổng với bản cũ khi đi thẳng + // Cửa sổ trôi không kéo T lùi: robot tiến 1 m -> from_index 10 -> T tiến theo (x = 3.0), arc_rest giảm đúng 1 m. + const CostToGoResult r2 = costToGo(plan, 10, 1.0, 0.0, params, PlanarTransform(), s); + EXPECT_EQ(30u, r2.target_index); + EXPECT_NEAR(5.0, r2.arc_rest, 0.05); + // Quãng cố định vượt cửa sổ thì vẫn kẹp ở điểm rời cửa sổ (kExit). + params.exit_ahead = 7.0; + const CostToGoResult r3 = costToGo(plan, 0, 0.0, 0.0, params, PlanarTransform(), s); + EXPECT_EQ(CostToGoResult::Target::kExit, r3.target); + // Goal trong quãng thì T = goal. + params.exit_ahead = 2.0; + const CostToGoResult r4 = costToGo(linePlan(0.0, 1.0, 0.1), 0, 0.0, 0.0, params, PlanarTransform(), s); + EXPECT_EQ(CostToGoResult::Target::kGoal, r4.target); +} + +TEST(GridAnalysisCostToGo, BlockedExitBacksOffAlongThePlanOrReportsBlocked) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalCircle(3.0, 0.0, 0.3); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(0.0, 3.0, 0.1); + + // T = (3, 0) nằm trong vật cản; ô free gần nhất dọc plan cách ~0.78 m > backoff 0.5 -> đích bị bịt. + CostToGoParams params; + params.target_backoff = 0.5; + CostToGoResult r = costToGo(plan, 0, 0.0, 0.0, params, PlanarTransform(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_FALSE(r.reachable); + EXPECT_EQ(CostToGoResult::Target::kBlockedExit, r.target); + + // Cho lùi 1.0 m thì tìm được T free và có đường. + params.target_backoff = 1.0; + r = costToGo(plan, 0, 0.0, 0.0, params, PlanarTransform(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_TRUE(r.reachable); + EXPECT_EQ(CostToGoResult::Target::kBackedOff, r.target); + EXPECT_GT(r.arc_rest, 0.7); + EXPECT_NEAR(3.0, r.cost_to_go, 0.2); +} + +TEST(GridAnalysisCostToGo, RobotHuggingAnObstacleSnapsToTheNearestFreeCell) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + lethalLine(grid, -3.0, 0.4, 3.0, 0.4); // tường sát bên trái tuyến + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(-3.0, 3.0, 0.1, -0.6); + // Robot tại (0, 0.1): cách tường 0.3 < inscribed -> ô không free, snap trong 0.35 m. + const CostToGoResult r = costToGo(plan, 30, 0.0, 0.1, CostToGoParams(), PlanarTransform(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_TRUE(r.robot_in_ring); + EXPECT_TRUE(r.reachable); +} + +TEST(GridAnalysisCostToGo, EmptyPlanOrRobotOutsideIsInconclusive) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + std::vector empty; + EXPECT_FALSE(costToGo(empty, 0, 0.0, 0.0, CostToGoParams(), PlanarTransform(), s).conclusive); + const auto plan = linePlan(0.0, 3.0, 0.1); + EXPECT_FALSE(costToGo(plan, 0, 7.0, 0.0, CostToGoParams(), PlanarTransform(), s).conclusive); +} + +TEST(GridAnalysisCostToGo, TransformIsAppliedToThePlan) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + // Plan trong frame "map" = lưới dịch +10 m: (10..13, 0) map -> (0..3, 0) lưới. + const auto plan = linePlan(10.0, 13.0, 0.1); + PlanarTransform map_to_grid; + map_to_grid.x = -10.0; + const CostToGoResult r = costToGo(plan, 0, 0.0, 0.0, CostToGoParams(), map_to_grid, s); + ASSERT_TRUE(r.conclusive); + EXPECT_NEAR(3.0, r.cost_to_go, 0.15); +} + +// ------------------------------------------------------------------------------------- corridor + +TEST(GridAnalysisCorridor, GapNarrowerThanTheBodyIsABlock) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalCircle(1.0, 0.6, 0.2); // mép trong ở y = +0.4 + grid.setLethalCircle(1.0, -0.6, 0.2); // mép trong ở y = -0.4 -> khe 0.8 m < thân 0.96 + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(-2.0, 3.0, 0.1); + const CorridorResult r = scanCorridor(plan, 0, CorridorParams(), PlanarTransform(), s); + EXPECT_GT(r.scanned, 0u); + EXPECT_NEAR(0.8, r.min_width, 0.12); + EXPECT_NEAR(3.0, r.block_dist, 0.25); + // Tâm robot không đặt được ở khe (0.4 < 0.48): plan hết sạch trước chỗ khe. + EXPECT_LT(r.plan_clear_ahead, 3.0); +} + +TEST(GridAnalysisCorridor, GapWiderThanTheBodyIsNotABlock) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalCircle(1.0, 0.8, 0.2); // mép trong ở y = +0.6 -> khe 1.2 m + grid.setLethalCircle(1.0, -0.8, 0.2); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(-2.0, 3.0, 0.1); + const CorridorResult r = scanCorridor(plan, 0, CorridorParams(), PlanarTransform(), s); + EXPECT_TRUE(std::isinf(r.block_dist)); + EXPECT_NEAR(1.2, r.min_width, 0.12); +} + +TEST(GridAnalysisCorridor, WallOnOneSideWithRoomOnTheOtherIsNotABlock) +{ + // Ca mission 1 ngày 5/9: plan sượt tường nhưng bên kia trống -> hành lang vẫn rộng. + nav_test_harness::FakeCostmap grid = makeGrid(); + lethalLine(grid, 0.0, 0.3, 2.0, 0.3); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(-2.0, 3.0, 0.1); + const CorridorResult r = scanCorridor(plan, 0, CorridorParams(), PlanarTransform(), s); + EXPECT_TRUE(std::isinf(r.block_dist)); + EXPECT_NEAR(0.3 + 1.5, r.min_width, 0.12); // trái 0.3 + phải chạm trần 1.5 + // Tâm cách đầu tường (0, 0.3) đúng 0.48 m tại x = -sqrt(0.48^2 - 0.3^2) = -0.375 -> 1.625 m từ x = -2. + EXPECT_NEAR(1.625, r.plan_clear_ahead, 0.15); +} + +TEST(GridAnalysisCorridor, HorizonLimitsTheScan) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalCircle(2.5, 0.6, 0.2); + grid.setLethalCircle(2.5, -0.6, 0.2); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const auto plan = linePlan(-2.0, 3.0, 0.1); + CorridorParams params; + params.horizon = 3.0; // khe ở 4.5 m dọc plan: ngoài tầm + const CorridorResult r = scanCorridor(plan, 0, params, PlanarTransform(), s); + EXPECT_TRUE(std::isinf(r.block_dist)); + EXPECT_NEAR(3.0, r.plan_clear_ahead, 1e-9); +} + +// --------------------------------------------------------------------------------- body clearance + +TEST(GridAnalysisBody, ClearanceBesideAWall) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + lethalLine(grid, -2.0, 0.7, 2.0, 0.7); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + // Cạnh trái thân ở y = 0.48, tường ở 0.7 -> 0.22 m. + EXPECT_NEAR(0.22, bodyClearance(s, 0.0, 0.0, 0.0, 0.583, 0.583, 0.48), 1.5 * kRes); + // Quay 90 độ: mũi (0.583) hướng về tường -> 0.117 m. + EXPECT_NEAR(0.117, bodyClearance(s, 0.0, 0.0, M_PI / 2.0, 0.583, 0.583, 0.48), 1.5 * kRes); +} + +TEST(GridAnalysisBody, EmptyGridClearanceIsInfinite) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + EXPECT_TRUE(std::isinf(bodyClearance(s, 0.0, 0.0, 0.3, 0.583, 0.583, 0.48))); +} + +// ---------------------------------------------------------------------------------------- sweep + +std::vector straightTrajectory(double length, double step) +{ + std::vector traj; + for (double x = 0.0; x <= length + 1e-9; x += step) + { + traj.push_back(makePose(x, 0.0, 0.0)); + } + return traj; +} + +TEST(GridAnalysisSweep, StraightTrajectoryIntoAWallReportsTheNoseContact) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalAt(1.5, 0.0); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const SweepResult r = sweepTrajectory(straightTrajectory(2.0, 0.1), 0.0, 0.0, 0.0, 0.3, + SweepParams(), *grid.costmap(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_TRUE(r.blocked); + EXPECT_EQ(1, r.hit_edge); // mũi + // Mũi đệm 0.633 m chạm ô tại 1.5 m (mép ô ~1.475): còn ~0.84 m đường đi. + EXPECT_NEAR(0.84, r.distance, 0.1); +} + +TEST(GridAnalysisSweep, ClearTrajectoryIsNotBlocked) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalAt(1.5, 1.5); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const SweepResult r = sweepTrajectory(straightTrajectory(1.4, 0.1), 0.0, 0.0, 0.0, 0.3, + SweepParams(), *grid.costmap(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_FALSE(r.blocked); + EXPECT_GT(r.scanned, 0u); +} + +TEST(GridAnalysisSweep, TrajectoryNotStartingAtTheRobotIsInconclusive) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + // Quỹ đạo bắt đầu ở (0,0) nhưng robot ở (1.0, 0): đây là global plan, không phải chuyển động sắp xảy ra. + const SweepResult r = sweepTrajectory(straightTrajectory(2.0, 0.1), 1.0, 0.0, 0.0, 0.3, + SweepParams(), *grid.costmap(), s); + EXPECT_FALSE(r.conclusive); +} + +TEST(GridAnalysisSweep, LethalCellUnderTheBodyIsExcludedByTheBaseline) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalAt(0.3, 0.50); // kề hông trái, trong thân đệm (0.53) + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + const SweepResult r = sweepTrajectory(straightTrajectory(2.0, 0.1), 0.0, 0.0, 0.0, 0.3, + SweepParams(), *grid.costmap(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_GE(r.baseline_cells, 1); + EXPECT_FALSE(r.blocked); // đi thẳng: ô đó trượt ra sau, không "thêm" ô mới vào thân + + SweepParams no_baseline; + no_baseline.exclude_baseline = false; + const SweepResult r2 = sweepTrajectory(straightTrajectory(2.0, 0.1), 0.0, 0.0, 0.0, 0.3, + no_baseline, *grid.costmap(), s); + EXPECT_TRUE(r2.blocked); +} + +TEST(GridAnalysisSweep, TrajectoryCurvingAwayFromAWallIsClear) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + // Tường cách 1.3 m: đi thẳng thì mũi đệm (0.633) chạm sau ~0.65 m; cung R 0.4 quay 90 độ có góc + // mũi-phải quét xa nhất sqrt(0.633^2 + 0.93^2) = 1.13 m < 1.3 -> không chạm. + lethalLine(grid, 1.3, -2.0, 1.3, 2.0); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + // Quỹ đạo quay gắt sang trái: cung R = 0.4 m, 90 độ, kết thúc song song tường ở x ~ 0.4. + std::vector traj; + for (int i = 0; i <= 20; ++i) + { + const double a = (M_PI / 2.0) * i / 20.0; + traj.push_back(makePose(0.4 * std::sin(a), 0.4 * (1.0 - std::cos(a)), a)); + } + SweepParams params; + params.lookahead = 1.0; + const SweepResult straight = sweepTrajectory(straightTrajectory(1.5, 0.1), 0.0, 0.0, 0.0, 0.3, + params, *grid.costmap(), s); + const SweepResult curve = sweepTrajectory(traj, 0.0, 0.0, 0.0, 0.3, params, *grid.costmap(), s); + ASSERT_TRUE(straight.conclusive); + EXPECT_TRUE(straight.blocked); + ASSERT_TRUE(curve.conclusive); + EXPECT_FALSE(curve.blocked); +} + +TEST(GridAnalysisSweep, LookaheadStopsTheSweep) +{ + nav_test_harness::FakeCostmap grid = makeGrid(); + grid.setLethalAt(3.0, 0.0); + GridScratch s; + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); + SweepParams params; + params.lookahead = 1.5; + const SweepResult r = sweepTrajectory(straightTrajectory(4.0, 0.1), 0.0, 0.0, 0.0, 0.3, params, + *grid.costmap(), s); + ASSERT_TRUE(r.conclusive); + EXPECT_FALSE(r.blocked); +} + +// ---------------------------------------------------------------------------------- scratch reuse + +TEST(GridAnalysisScratch, ReusedAcrossGridsWithoutStaleState) +{ + GridScratch s; + nav_test_harness::FakeCostmap a = makeGrid(); + a.setLethalAt(0.0, 0.0); + ASSERT_TRUE(analyzeGrid(*a.costmap(), kLethal, kInscribed, s)); + EXPECT_NEAR(0.0, distanceAt(s, 0.0, 0.0), 1e-6); + + nav_test_harness::FakeCostmap b = makeGrid(); // trống + ASSERT_TRUE(analyzeGrid(*b.costmap(), kLethal, kInscribed, s)); + EXPECT_TRUE(std::isinf(distanceAt(s, 0.0, 0.0))); + + nav_test_harness::FakeCostmap c(100, 60, kRes, -2.5, -1.5); // kích thước khác + c.setLethalAt(1.0, 0.0); + ASSERT_TRUE(analyzeGrid(*c.costmap(), kLethal, kInscribed, s)); + EXPECT_EQ(100u, s.width); + EXPECT_EQ(60u, s.height); + EXPECT_NEAR(1.0, distanceAt(s, 0.0, 0.0), 1.5 * kRes); +} + +// ------------------------------------------------------------------------------------- chi phí + +TEST(GridAnalysisBench, ReportCostOnRuntimeSizedGrid) +{ + // 160 x 160 @ 0.05 m như local costmap runtime, bãi 30 trụ rải ngẫu nhiên. Chỉ in số, không phán + // pass/fail: chi phí tuyệt đối phụ thuộc máy; plan (§2.5) dự tính EDT ~0.3 ms + Dijkstra <= 0.4 ms. + nav_test_harness::FakeCostmap grid = nav_test_harness::FakeCostmap::centered(8.0, kRes); + unsigned int seed = 12345u; + for (int i = 0; i < 30; ++i) + { + seed = seed * 1103515245u + 12345u; + const double x = -3.5 + 7.0 * ((seed >> 8) % 1000) / 1000.0; + seed = seed * 1103515245u + 12345u; + const double y = -3.5 + 7.0 * ((seed >> 8) % 1000) / 1000.0; + grid.setLethalCircle(x, y, 0.25); + } + // Dọn một hành lang trống dọc plan để T và ô robot luôn free -> Dijkstra chạy thật (thăm toàn bộ + // thành phần liên thông chứa T = trường hợp xấu nhất về chi phí). + // Lấy mẫu tại TÂM ô: bước đúng một ô nhưng đặt trên biên ô thì sai số float bỏ sót ô. + for (double x = -0.6 + 0.5 * kRes; x < 4.0; x += kRes) + { + for (double y = -0.8 + 0.5 * kRes; y < 0.8; y += kRes) + { + grid.setCostAt(x, y, robot_costmap_2d::FREE_SPACE); + } + } + GridScratch s; + const auto plan = linePlan(0.0, 3.9, 0.1); + ASSERT_TRUE(analyzeGrid(*grid.costmap(), kLethal, kInscribed, s)); // ensure() cấp phát một lần + + constexpr int kIters = 200; + auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < kIters; ++i) + { + analyzeGrid(*grid.costmap(), kLethal, kInscribed, s); + } + auto t1 = std::chrono::steady_clock::now(); + CostToGoResult last; + for (int i = 0; i < kIters; ++i) + { + last = costToGo(plan, 0, 0.0, 0.0, CostToGoParams(), PlanarTransform(), s); + } + auto t2 = std::chrono::steady_clock::now(); + CorridorResult corr; + for (int i = 0; i < kIters; ++i) + { + corr = scanCorridor(plan, 0, CorridorParams(), PlanarTransform(), s); + } + auto t3 = std::chrono::steady_clock::now(); + SweepResult sw; + const auto traj = straightTrajectory(1.5, 0.1); + for (int i = 0; i < kIters; ++i) + { + sw = sweepTrajectory(traj, 0.0, 0.0, 0.0, 0.3, SweepParams(), *grid.costmap(), s); + } + auto t4 = std::chrono::steady_clock::now(); + const auto us = [](auto a, auto b) { + return std::chrono::duration_cast(b - a).count() / static_cast(kIters); + }; + std::printf("[bench] 160x160: analyzeGrid %.0f us | costToGo %.0f us (visited %zu, reachable %d, " + "conclusive %d, in_ring %d, target %d, edt_robot %.2f, edt_T %.2f, cost %.2f) | " + "scanCorridor %.0f us (scanned %zu) | sweepTrajectory %.0f us\n", + us(t0, t1), us(t1, t2), last.cells_visited, last.reachable ? 1 : 0, + last.conclusive ? 1 : 0, last.robot_in_ring ? 1 : 0, static_cast(last.target), + distanceAt(s, 0.0, 0.0), distanceAt(s, 3.9, 0.0), last.cost_to_go, us(t2, t3), + corr.scanned, us(t3, t4)); + EXPECT_TRUE(last.conclusive); + EXPECT_TRUE(last.reachable); + EXPECT_GT(last.cells_visited, 1000u); + EXPECT_TRUE(sw.conclusive); +} + +} // namespace + +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/plan_inspector_test.cpp b/test/plan_inspector_test.cpp index 760e996..23be321 100644 --- a/test/plan_inspector_test.cpp +++ b/test/plan_inspector_test.cpp @@ -28,6 +28,7 @@ namespace using move_base2::checkPlan; using move_base2::crossTrackError; using move_base2::nearestIndex; +using move_base2::trackedNearestIndex; using move_base2::PlanarTransform; using move_base2::PlanBlockResult; using move_base2::planarTransform; @@ -202,6 +203,30 @@ TEST(PlanInspectorNearest, PlanFoldingBackOnItselfPicksTheNearerLeg) EXPECT_EQ(nearestIndex(plan, makePose(1.0, 0.95)), 2u); } +TEST(PlanInspectorNearest, TrackedIndexStaysOnTheCurrentLegOfAFoldedPlan) +{ + // Plan ra 4 m rồi vòng lại song song cách 0.6 m: robot đứng giữa hai đoạn (0.35 m tới đoạn đầu, 0.25 m tới + // đoạn về). nearestIndex toàn plan nhảy sang đoạn về (index 2); bám từ hint 0 với cửa sổ 1 m lùi / 3 m tiến + // thì đoạn về nằm ngoài 3 m dọc plan -> giữ đoạn đầu. + std::vector plan{ makePose(0.0, 0.0), makePose(4.0, 0.0), makePose(4.0, 0.6), + makePose(0.0, 0.6) }; + const auto robot = makePose(1.0, 0.35); + EXPECT_EQ(nearestIndex(plan, robot), 2u); + EXPECT_EQ(trackedNearestIndex(plan, robot, 0, 1.0, 3.0), 0u); + // Cửa sổ đủ dài thì bằng nearest toàn plan. + EXPECT_EQ(trackedNearestIndex(plan, robot, 0, 1.0, 20.0), 2u); +} + +TEST(PlanInspectorNearest, TrackedIndexAdvancesAndClampsTheHint) +{ + const auto plan = linePlan(0.0, 5.0, 0.5); // 11 pose, 10 đoạn + EXPECT_EQ(trackedNearestIndex(plan, makePose(2.3, 0.1), 2, 1.0, 3.0), 4u); // tiến + EXPECT_EQ(trackedNearestIndex(plan, makePose(1.2, 0.0), 4, 1.0, 3.0), 2u); // lùi trong 1 m + EXPECT_EQ(trackedNearestIndex(plan, makePose(0.1, 0.0), 8, 1.0, 3.0), 6u); // lùi bị chặn ở 1 m: đoạn 6 + EXPECT_EQ(trackedNearestIndex(plan, makePose(4.9, 0.0), 99, 1.0, 3.0), 9u); // hint vượt cỡ -> kẹp + EXPECT_EQ(trackedNearestIndex({}, makePose(0.0, 0.0), 3, 1.0, 3.0), 0u); +} + TEST(PlanInspectorNearest, ShortPlansAreSafe) { EXPECT_EQ(nearestIndex({}, makePose(0.0, 0.0)), 0u); diff --git a/test/walking_skeleton_test.cpp b/test/walking_skeleton_test.cpp index 13541e7..61e1df5 100644 --- a/test/walking_skeleton_test.cpp +++ b/test/walking_skeleton_test.cpp @@ -33,6 +33,7 @@ using move_base2::testing::FakeClockPort; using move_base2::testing::FakeControllerPort; using move_base2::testing::FakeCostmapStatusPort; using move_base2::testing::FakeMissionPort; +using move_base2::testing::FakeEnvironmentPort; using move_base2::testing::FakePathCheckPort; using move_base2::testing::FakePlannerPort; using move_base2::testing::FakePosePort; @@ -130,6 +131,7 @@ public: deps_.action = &action_; deps_.costmap_status = &costmap_status_; deps_.path_check = &path_check_; + deps_.environment = &environment_; std::string error; EXPECT_TRUE(loop_.configure(config, deps_, error)) << error; @@ -179,6 +181,7 @@ public: FakeActionPort action_; FakeCostmapStatusPort costmap_status_; FakePathCheckPort path_check_; + FakeEnvironmentPort environment_; ControlLoopDeps deps_; private: @@ -1886,6 +1889,120 @@ TEST(WalkingSkeletonCollisionGuard, HeldByTheGuardAfterTheRouteIsSpentEscalatesT EXPECT_TRUE(escalated) << "guard held the robot but nothing escalated"; } +namespace +{ +/// @brief P4 (5/9): guard cũ tắt hẳn, kContact của EnvMonitor phanh thật và giơ cờ collision. +ControlLoopConfig envContactConfig() +{ + ControlLoopConfig config = monitorConfig(); + config.path_monitor.enabled = false; // guard cũ tắt hẳn: chỉ EnvMonitor phanh + config.env_monitor.enabled = true; + config.env_monitor.stall.action = "log"; + config.env_monitor.unreachable.action = "log"; + config.env_monitor.contact.action = "recover"; + config.env_monitor.contact.apply_command = true; + config.env_monitor.contact.confirm_cycles = 2; + config.env_monitor.contact.trigger_static_time = 0.3; // [s] = 6 cycle, đủ ngắn cho test + config.env_monitor.contact.clean_start_margin = 0.2; // [m] + config.env_sampling.check_period = 0.01; // [s] < chu kỳ 0.05 -> tick nặng mỗi cycle + return config; +} +} // namespace + +TEST(WalkingSkeletonEnvContact, BrakesAfterConfirmThenRaisesCollisionAfterStaticTime) +{ + Fixture fixture(envContactConfig()); + driveToControlling(fixture); + + // Tiếp xúc 0.10 m trên quỹ đạo, trong clean_start_margin: cycle 1 đếm, cycle 2 phanh -> lệnh 0. + fixture.environment_.setContact(true, 0.10); + fixture.stepOnce(); + fixture.stepOnce(); + EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0); + EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 0.0); + EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "phanh nhưng chưa giơ cờ"; + + // Kề mũi đứng yên đủ trigger_static_time -> cờ collision -> route collision. + int held = 0; + for (int i = 0; i < 12 && fixture.loop_.state() == NavigationState::kControlling; ++i) + { + fixture.stepOnce(); + EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i; + ++held; + } + EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); + EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision); + EXPECT_GE(held, 4) << "cờ phải chờ đủ trigger_static_time, không nổ cùng nhịp với phanh"; +} + +TEST(WalkingSkeletonEnvContact, HeldWithTheRouteSpentEscalatesToControllingFailed) +{ + // Cùng chuỗi bắt buộc như guard cũ: cạn route collision -> khoá -> brake giữ 0 nhưng controller + // phải bị báo no_valid_command -> controller_patience -> controlling_failed. Không có bước này + // robot đứng chết vô hạn với controller "ổn". + Fixture fixture(envContactConfig()); + driveToControlling(fixture); + fixture.recovery_.setScript({ RecoveryScript::kFailed }); + + fixture.environment_.setContact(true, 0.10); + for (int i = 0; i < 12 && fixture.loop_.state() == NavigationState::kControlling; ++i) + { + fixture.stepOnce(); + } + ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering); + ASSERT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision); + + for (int i = 0; i < 4 && fixture.loop_.state() == NavigationState::kRecovering; ++i) + { + fixture.stepOnce(); + } + ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) + << "detour thất bại phải quay về kControlling với route collision đã cạn"; + + // onRecoveryFinished xoá chuỗi phanh: tối đa confirm_cycles cycle lệnh có thể khác 0 rồi phanh lại. + bool escalated = false; + int nonzero_after_settle = 0; + for (int i = 0; i < 60 && !escalated; ++i) + { + fixture.stepOnce(); + if (i >= 3 && fixture.loop_.lastCommand().linear.x != 0.0) + { + ++nonzero_after_settle; + } + escalated = fixture.loop_.state() == NavigationState::kRecovering && + fixture.recovery_.lastTrigger() == RecoveryTrigger::kControllingFailed; + } + EXPECT_TRUE(escalated) << "EnvMonitor held the robot but nothing escalated"; + EXPECT_EQ(nonzero_after_settle, 0) << "brake must hold once re-confirmed"; +} + +TEST(WalkingSkeletonEnvContact, ContactBeyondTheStoppingDistanceCapsSpeedWithoutBraking) +{ + Fixture fixture(envContactConfig()); + driveToControlling(fixture); + const double v_free = fixture.loop_.lastCommand().linear.x; + ASSERT_GT(v_free, 0.27); + + // 2.0 m phía trước: bao sqrt(2·0.35·1.7) = 1.09 m/s > lệnh -> không đổi, không phanh. + fixture.environment_.setContact(true, 2.0); + for (int i = 0; i < 6; ++i) + { + fixture.stepOnce(); + } + EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, v_free); + EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); + + // 0.40 m: bao sqrt(2·0.35·(0.40 − margin 0.2 − dư 0.1)) = 0.265 m/s. Lệnh bị kẹp xuống đúng bao và GIỮ ở đó: + // quãng phanh ở tốc độ đã kẹp = 0.10 m -> còn 0.30 m > margin -> không phải "sắp chạm", không phanh, không cờ. + fixture.environment_.setContact(true, 0.40); + for (int i = 0; i < 8; ++i) + { + fixture.stepOnce(); + EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, std::sqrt(2.0 * 0.35 * 0.10), 1e-3) << "cycle " << i; + } + EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); +} + TEST(WalkingSkeletonCollisionGuard, BodyComesFromTheCostmapFootprintWhenOffsetsAreZero) { // Ba offset = 0: thân lấy từ footprint costmap qua cổng. Có footprint -> guard dò và dừng như khai