diff --git a/config/runtime/env_monitor_params.yaml b/config/runtime/env_monitor_params.yaml index 32ea6c5..10312fe 100644 --- a/config/runtime/env_monitor_params.yaml +++ b/config/runtime/env_monitor_params.yaml @@ -1,7 +1,7 @@ # ================================================================================================= # 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 5 (6/9 10:35) — CẢ BA VERDICT BẬT THẬT -# (unreachable bật lại cùng target_snap); PathMonitor cũ TẮT HẲN (path_monitor/enabled: false), EnvMonitor là bộ giám sát duy nhất. +# (unreachable bật lại cùng target_snap); PathMonitor cũ ĐÃ XOÁ (P5, 6/9), 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). @@ -121,7 +121,7 @@ env_monitor: 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. + # Chủ thể phanh duy nhất trong move_base2 (guard cũ đã xoá); cổng dừng trong PRIEST vẫn phải để tắt. # 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), @@ -149,7 +149,7 @@ env_monitor: 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 + # planner (cùng vai collision_min_speed của guard 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). diff --git a/config/runtime/move_base_common_params.yaml b/config/runtime/move_base_common_params.yaml index 66b66db..3e682ef 100644 --- a/config/runtime/move_base_common_params.yaml +++ b/config/runtime/move_base_common_params.yaml @@ -204,8 +204,8 @@ acc_lim_x: 1.0 acc_lim_theta: 1.20 # ================================================================================================= -# Giám sát tuyến (path_monitor) — ĐÃ TÁCH sang `path_monitor_params.yaml` (3/9/2026). -# Đừng khai lại `path_monitor:` ở đây: NodeHandle merge mọi file, hai bản sẽ đè nhau theo thứ tự +# Giám sát môi trường — xem `env_monitor_params.yaml` (EnvMonitor thay PathMonitor, 6/9/2026). +# Đừng khai lại `env_monitor:` ở đây: NodeHandle merge mọi file, hai bản sẽ đè nhau theo thứ tự # thư mục (không xác định) và người chỉnh sẽ thấy "sửa mãi không ăn". # ================================================================================================= diff --git a/config/runtime/path_monitor_params.yaml b/config/runtime/path_monitor_params.yaml deleted file mode 100644 index a1a9a54..0000000 --- a/config/runtime/path_monitor_params.yaml +++ /dev/null @@ -1,263 +0,0 @@ -# ================================================================================================= -# path_monitor_params.yaml — Giám sát tuyến của move_base2 (tách khỏi move_base_common_params.yaml -# ngày 3/9/2026; sắp xếp lại theo phép đo ngày 4/9/2026) -# -# Ai đọc: `move_base2` qua `robot::NodeHandle` (namespace `path_monitor`, hàm readPathMonitor trong -# src/config/move_base2_config.cpp). NodeHandle merge MỌI .yaml trong thư mục này vào một cây gốc, nên -# tên file không quan trọng — chỉ khoá top-level `path_monitor:` là quan trọng, và nó PHẢI xuất hiện ở -# đúng MỘT file. Khai lại ở file khác là hai bản merge chồng nhau theo thứ tự thư mục (không xác định). -# -# Ai KHÔNG đọc: PRIEST, SBPL, costmap. Các phép đo ở đây chỉ dùng dữ liệu move_base2 đang có (pose, -# plan đang bám, lệnh sau trọng tài, local costmap qua PathCheckPort) và chỉ ra QUYẾT ĐỊNH dừng / gọi -# recovery; chúng không sửa lệnh của local planner. -# -# Bốn phép đo, mỗi cái trả lời một câu khác nhau, không chồng nhau: -# 1 path_blocked plan phía trước chạm vành 253 trong `horizon` -> route path_blocked -# 2 off_path robot lệch plan đang bám quá `max_cross_track` -> route off_path -# 3 collision thân robot sắp chạm ô LETHAL trên CUNG LỆNH (v,omega) -> lệnh 0 + path_blocked -# 4 progress planner ĐÒI ĐI mà robot KHÔNG TIẾN (local minimum) -> route oscillation -# (5 liên thông cửa sổ local — xem Test/LOCAL_MINIMUM_PREDICT_PLAN.md, đang pending) -# -# Mỗi phép đo có BA nút độc lập và phải đủ CẢ BA mới sống: cờ riêng `*_enabled` (đứng đầu khối của -# nó), ngưỡng > 0, route tương ứng bên recovery_behaviors_params.yaml khác rỗng. Công tắc chung -# `enabled` tắt tất cả. -# -# Cấu trúc file: khối CHUNG (áp cho mọi phép đo), rồi mỗi phép đo một khối, khoá của phép đo nào nằm -# trọn trong khối đó, cờ bật/tắt là dòng đầu tiên của khối. -# ================================================================================================= -path_monitor: - # =============================================================================================== - # CHUNG - # =============================================================================================== - - # 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. - # ► 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 đó. - # ► Chỉnh: gần như luôn để `[position]`. Thêm profile khác chỉ khi profile đó dùng tuyến tự do. - profiles: [position] - - # [s] Nhịp quét costmap của phép đo 1, 2, 4. KHÔNG quét mỗi control cycle — quá phí. (Phép đo 3 - # chạy MỖI cycle, không theo nhịp này — xem khối của nó.) - # ► Chỉnh: đặt ~= chu kỳ cập nhật costmap local (5 Hz ⇒ 0.2 s). Nhỏ hơn thế là quét lại cùng một - # dữ liệu. TĂNG nếu CPU căng; đổi lại phản ứng chậm đi đúng chừng đó. - check_period: 0.2 - - # [s] Điều kiện của phép đo 1, 2 phải đúng LIÊN TỤC chừng này mới khai hoả (chống nhiễu một nhịp). - # ► Chỉnh: TĂNG (0.8–1.5) nếu người đi ngang qua làm robot dừng oan. GIẢM nếu robot phản ứng quá - # chậm với vật cản thật. Phải >= vài lần `check_period`, nếu không debounce vô nghĩa. - confirm_time: 0.5 - - # [s] Bỏ qua phép đo 2 và 4 ngay sau khi nhận plan mới — lúc preempt/đổi chặng pose robot có thể - # lệch nhất thời so với plan vừa tới, và mẫu tiến độ cũ thuộc plan cũ. - # ► Chỉnh: TĂNG nếu `off_path` / `no progress` khai hoả ngay sau mỗi lần đổi chặng hoặc detour. - grace_after_new_plan: 1.0 - - # =============================================================================================== - # PHÉP ĐO 1 — tuyến phía trước bị chắn (plan ∩ vành 253 trong `horizon`) -> route path_blocked - # =============================================================================================== - - # ► Chỉnh: hạ cờ để tắt mà VẪN GIỮ ngưỡng — bật lại chỉ sửa một dòng. Sim 4/9: plan tắc ở 2.09 m - # lúc robot còn sạch mà không ai phản ứng vì cờ này tắt; recovery giờ lập lại cả đường (không - # detour vòng tròn nữa) nên lý do tắt cũ hết hiệu lực — cân nhắc bật. - path_blocked_enabled: false - - # [m] Quãng tuyến phía trước cần quét. - # ► Chỉnh: phải <= nửa cửa sổ costmap local (8x8 m ⇒ ~4 m), ngoài đó không có dữ liệu. - # - TĂNG (tới ~3.5) để phát hiện sớm hơn, có nhiều chỗ hơn để lập đường vòng; - # - GIẢM (1.5–2.0) nếu robot dừng quá sớm trước vật cản mà local planner tự lách được. - horizon: 3.0 - - # [m] Vật cản gần hơn mức này thì KHÔNG khai hoả: lập lại đường từ sát nách hầu như không ra - # nghiệm (start trong vành 253), và ca đó đã có phép đo 3 + controller_patience lo. - # ► Chỉnh: đặt ~= bán kính ngoại tiếp footprint + dư địa (thân 1.166x0.96 ⇒ ngoại tiếp 0.75 m). - # TĂNG nếu thấy nhiều lượt `Solution not found` với vật cản rất gần. - min_detour_distance: 0.5 - - # =============================================================================================== - # PHÉP ĐO 2 — robot lệch khỏi plan đang bám quá `max_cross_track` -> route off_path - # =============================================================================================== - - # Tắt tường minh: max_cross_track chưa đo được nên chưa có ngưỡng thật. Bật thì đặt ngưỡng dưới. - off_path_enabled: false - - # [m] Lệch khỏi plan ĐANG CHẠY quá mức này thì khai hoả. Đo với plan đang chạy chứ không phải - # tuyến gốc — sau một lượt lập lại đường hợp lệ, plan đang chạy CHÍNH LÀ đường mới nên không báo - # oan. (Ràng buộc "lệch bao nhiêu so với tuyến fleet" là việc của `max_deviation` bên detour.) - # ► Chỉnh: cách đặt đúng: chạy sim/robot qua các khúc cua gắt nhất của tuyến, ghi cross-track - # đỉnh, rồi đặt ~1.5–2 lần giá trị đó. Đặt số mò là robot dừng oan giữa đường cong. PRIEST né - # người lệch tới 2–3 m (sim 3–4/9) nên 1.0 hiện là số giữ chỗ, không phải số đo. - max_cross_track: 1.0 - - # =============================================================================================== - # PHÉP ĐO 3 — thân robot sắp chạm vật cản THẬT trên cung lệnh (2026-09-03) -> lệnh 0 + path_blocked - # =============================================================================================== - # - # Đối tượng đo KHÁC HẲN hai phép đo trên: không phải global plan, mà là CUNG mà lệnh (v, omega) của - # local planner sắp vẽ ra từ pose hiện tại. Local planner lệch plan cả mét khi né, lúc đó quét - # plan bảo "sạch" trong khi thân đang lao hướng khác — mission 5 (29/8) húc vào khe 0.76 m như thế. - # - # Chạy MỖI control cycle, không theo check_period/confirm_time: 0.2 s + 0.5 s xác nhận ở 0.5 m/s - # là 0.35 m đi thêm — bằng cả quãng dừng. Hai bước khi chạm trong collision_stop_distance: - # (1) ngay cycle đó lệnh ra = 0 và controller bị coi là "không có lệnh" (controller_patience chạy); - # (2) sau collision_confirm_cycles cycle liên tiếp, giơ cờ path_blocked -> route lập lại đường. - # - # ► 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. - # ► 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ì ----------------------------------------------------------------------------- - - # [m] Quãng cung cần dò — tầm phanh, không hơn. Dò xa hơn là soi thứ solver còn chưa được thấy - # và báo fake ở đuôi (lý do gate toàn-quỹ-đạo cũ trong priest bị tắt). - collision_lookahead: 0.8 - - # Trần THƯA của số mẫu trên cung: bước = lookahead / samples nhưng không bao giờ lớn hơn một ô lưới - # (tường mỏng 1 ô lọt giữa hai mẫu là đâm xuyên). Lưới 0.05 m ⇒ thực tế 16 mẫu, mẫu đầu ở 0.05 m. - collision_max_samples: 6 - - # cost >= đây là chạm. 254 = chỉ ô vật cản THẬT (LETHAL). ĐỪNG hạ xuống 253: vành inflation là biên - # dành cho TÂM robot, đem áp lên mũi/hông là đếm biên hai lần — báo "chạm" khi tường còn cách nửa - # mét và robot kẹt vì một cái bóng (2/9: "body inside 24 obstacles" với tường cách 0.48+ m). - collision_cost_threshold: 254 - - # --- 3b. Thân robot ---------------------------------------------------------------------------- - - # [m] Hình chữ nhật thân tính từ base_link: mũi / đuôi / nửa bề rộng. - # CẢ BA = 0 (mặc định) = lấy từ footprint KHÔNG đệm của costmap mỗi cycle — cùng hình với SBPL và - # PRIEST, đổi footprint lúc chạy (setRobotFootprint) là guard đổi theo, không phải chép số vào hai - # file. Boot log in "collision body from the costmap footprint: front=.. rear=.. side=..". - # ► Chỉnh: chỉ khai tay khi cố ý muốn guard dùng thân KHÁC costmap (ví dụ chở hàng nhô ra) — khi - # đó phải khai đủ CẢ BA > 0, khai lửng là config sai (runtime từ chối). - collision_front_offset: 0.0 - collision_rear_offset: 0.0 - collision_side_offset: 0.0 - - # [m] Biên an toàn TƯỜNG MINH cộng vào mọi cạnh — đây là thứ thay cho inflation ở phép đo này. - # ► Chỉnh: ~ sai số định vị + sai số footprint. 0.05 = dừng khi thân còn cách vật 5 cm. LƯU Ý: - # SBPL lập đường với footprint KHÔNG đệm, nên khe hẹp hơn thân+2·đệm mà rộng hơn thân thật là - # chỗ planner bảo đi được còn guard bảo không — muốn qua khe đó thì hạ về 0.0. - collision_footprint_padding: 0.05 - - # Loại trừ baseline (2026-09-04): ô LETHAL đang nằm DƯỚI thân đệm ngay tại chỗ đứng KHÔNG được - # tính là chạm ở các mẫu sau. Guard đổi câu hỏi từ "thân có đè LETHAL không" thành "lệnh này có - # đưa THÊM ô LETHAL vào thân không": trượt song song / rời xa người đang kề hông thì đi được, - # lấn sâu thêm (rẽ vào họ) thì vẫn chặn. Sim 4/9: người kề hông phải ở 0.46 m ngang (thân 0.48 + - # đệm 0.05) làm mẫu đầu tiên báo "0.05 m" mãi dù PRIEST lệnh đi thẳng; SBPL (không đệm) bảo đi - # được; robot đứng chết. Baseline tính lại MỖI cycle: người bước vào robot đang đứng yên cũng - # thành baseline — chấp nhận, vì robot không phải bên khép khoảng cách. - # ► Chỉnh: false = hành vi cũ (mọi ô dưới thân đệm đều là "sắp chạm"). - # Debug (khoá `debug/state` trong move_base_common_params.yaml, mặc định bật): - # - "body overlaps N LETHAL cell(s) ... letting it move; cells in base frame: (x, y) ..." — đang - # cho đi vì cung không thêm ô, kèm toạ độ ô dưới thân (frame base_link, x tới, y trái). - # - "hit at sample K: edge touches cell (x, y) ...; baseline N cell(s): ..." - # — mỗi lần guard nổ: cạnh nào chạm, ô chạm ở đâu, ô nào đã bị bỏ qua. Ô chạm ở góc trái-sau - # khi đang rẽ phải = thân quét tới; ô chạm ở mũi khi đi thẳng mà cycle trước còn sạch = người - # bước tới. - collision_exclude_baseline: true - - # --- 3c. Phản ứng khi chạm --------------------------------------------------------------------- - - # [m] Chạm gần hơn đây (VÀ "sắp" theo stop_time/stop_angle ở dưới): lệnh 0 ngay + đếm xác nhận. - # Xa hơn: chỉ kẹp tốc độ (xem brake_decel). - # ► Chỉnh: >= quãng phanh ở tốc độ hành trình với decel thật của base (0.5 m/s, 0.35 m/s^2 ⇒ - # 0.36 m). GIẢM để đi sát vật cản hơn — chỉ khi đã đo decel thật trên robot. - collision_stop_distance: 0.2 - - # [cycle] chạm liên tiếp chừng này mới giơ cờ replan. Lệnh 0 vẫn phát từ cycle đầu — cái này chỉ - # chống một nhịp costmap nhấp nháy kéo cả recovery ra. 2 cycle @20 Hz = 0.1 s. - collision_confirm_cycles: 2 - - # [m/s^2] Chạm XA hơn stop_distance thì kẹp v <= sqrt(2 a (d - stop)) trước khi phát, để không - # lao vào ở tốc độ tối đa rồi phanh gấp ở stop_distance. 0 = không kẹp. Đặt = decel thoải mái của - # base. Vật cản ở HÔNG không có pha kẹp này (guard chỉ thấy nó khi mép hông phủ lên) — đó là việc - # của baseline ở trên. - collision_brake_decel: 0.35 - - # [m/s] |v| dưới đây không dò: cung suy biến, xoay tại chỗ có phép kiểm riêng bên planner. - collision_min_speed: 0.02 - - # "Sắp chạm" theo THỜI GIAN và GÓC (2026-09-04, run 16:26). Trong stop_distance, mét dọc cung - # chưa nói lên gì với cung xoay gần tại chỗ: cùng 0.15 m cung, đi thẳng 0.36 m/s là chạm sau - # 0.4 s; xoay bò v 0.04 ω −0.5 (R 0.08 m) là quay 107° và còn 3.8 s — PRIEST đã thôi xoay sau - # 30–60° để thẳng hàng với path. Guard mô hình lệnh là cung không đổi nên phải đo bằng thời gian - # và góc: dừng khi còn <= stop_time HOẶC còn <= stop_angle; chưa tới thì KHÔNG dừng, không replan, - # chỉ kẹp v <= (walk − padding)/stop_time. Đi thẳng (góc ≈ 0) luôn "sắp" -> y như trước. - # Hôm đó: 11 lần nổ trong 15 s tại góc trụ, xoay 0.9 rad mất 12 s thay vì 2 s -> với luật này 1 lần. - # ► Chỉnh stop_time: TĂNG (1.5) nếu base phanh chậm; GIẢM (0.6) chỉ khi đã đo decel thật. - # ► Chỉnh stop_angle: là biên còn lại khi xoay sát vật; 0.35 rad ≈ 0.27 m quãng góc thân. GIẢM - # (0.2) nếu robot hay bị dừng oan giữa cú xoay; TĂNG nếu đã thấy góc thân chạm. - collision_stop_time: 1.0 - collision_stop_angle: 0.35 - - # [rad] Cung không dò quá góc quay này. R = 0.1 m thì 0.8 m lookahead là quay 8 rad (hơn một - # vòng) — soi thứ không xảy ra và làm "would hit"/"clear again" lật mỗi vài cycle. Đi thẳng không - # bị cắt. Phải >= collision_stop_angle. - collision_lookahead_angle: 1.0 - - # =============================================================================================== - # PHÉP ĐO 4 — tiến độ so với lệnh (2026-09-04) -> route oscillation - # =============================================================================================== - # - # "Planner ĐÒI ĐI mà robot KHÔNG TIẾN" — định nghĩa vận hành của local minimum, không cần biết vì - # sao kẹt. Mỗi cycle cộng |v| ĐÃ PHÁT sau trọng tài; mỗi nhịp check_period lấy mẫu (tiến dọc plan, - # khoảng cách tới goal). So mẫu bây giờ với mẫu cách đây `progress_window`: - # cmd = tổng lệnh trong cửa sổ [m] - # prog = max(tiến dọc plan, giảm khoảng cách tới goal) [m] - # eff = prog / cmd - # Kẹt khi cmd >= min_commanded VÀ eff < min_efficiency, liên tục đủ progress_confirm_time. - # - # Số đo trên sim 3/9: chạy bình thường eff 0.65-0.85, kể cả đoạn né lệch plan 1.9 m; hai ca kẹt - # thật eff -0.14..0.27; nổ 12–54 s TRƯỚC khi hệ cũ vào RECOVERING, lúc robot còn cách vành 253 - # tới 0.84-1.42 m — đứng trên đất sạch, SBPL có chỗ bắt đầu. - # - # KHÔNG nổ khi: planner hold chờ người (twist 0 -> cmd = 0), phép đo 3 phanh (lệnh sau trọng tài - # = 0), xoay tại chỗ đầu chặng (v = 0), sát goal (goal_zone), vừa nhận plan (grace_after_new_plan). - # KHÔNG bắt được: robot lao THẲNG về goal vào vật cản (khoảng cách goal vẫn giảm) — đó là việc của - # phép đo 1 và 3. Lỗ đã biết: robot LẾT chậm (< min_commanded / window) không được đo — cố ý, để - # không nhầm với chờ. - progress_enabled: true - - # "log" = chỉ in cảnh báo, KHÔNG leo thang. Giai đoạn quan sát: chạy vài ca, đọc dòng - # "PathMonitor: no progress" xem có nổ oan không rồi mới chuyển. - # "recover" = leo thang kOscillation -> route `oscillation` bên recovery_behaviors_params.yaml. - # kOscillation là trigger GỐC: cạn route = ABORT chặng, báo fleet. Nổ oan là MẤT CHẶNG. - # ► Ngưỡng bên dưới rút từ ĐÚNG HAI ca kẹt trong một log sim — chưa có plan vòng gắt, chưa có - # robot thật (bánh trượt, odom nhiễu). - progress_action: recover - - # [s] Cửa sổ đo. Mission 2 trong log: khoảng cách tới goal đứng đúng 3 s trước khi planner hold. - # ► Chỉnh: TĂNG (5.0) nếu nổ oan ở chỗ robot lết chậm hợp lệ (cửa hẹp có người); GIẢM = nhạy hơn - # nhưng dễ nổ vì một nhịp odom. - progress_window: 3.0 - - # [m] Lệnh tích luỹ trong cửa sổ ít hơn đây = robot đang chờ / xoay, KHÔNG đo. 0.30 m / 3 s = - # 0.1 m/s trung bình. ► TĂNG (0.5) để bỏ qua lệnh rất nhỏ; ĐỪNG đặt 0 (chờ hợp lệ thành "kẹt"). - progress_min_commanded: 0.30 - - # [-] prog/cmd DƯỚI đây là kẹt. Log: kẹt <= 0.27, bình thường >= 0.65 — biên rộng hơn gấp đôi. - # ► GIẢM (0.20) nếu nổ oan trên plan vòng gắt (tiến dọc plan thật nhưng khoảng cách goal tăng). - progress_min_efficiency: 0.30 - - # [-] prog/cmd TRÊN đây mới xoá chuỗi kẹt. Phải > min_efficiency: vùng 0.30-0.60 là vùng chết - # (giữ trạng thái) — bằng nhau là cờ nhấp nháy quanh một ngưỡng mỗi lượt quét. - # Chỉ tiến bộ THẬT mới xoá cờ; cmd tụt dưới min_commanded (chậm lại, hold) thì GIỮ NGUYÊN — sim 4/9 - # cho thấy robot kẹt hay lượn quanh đúng ngưỡng tốc độ và làm cờ bật/tắt 5 lần cho một đợt. - progress_clear_efficiency: 0.60 - - # [s] Kẹt liên tục chừng này mới khai hoả (= 5 lượt check_period 0.2). Lọc một nhịp dist nhiễu. - progress_confirm_time: 1.0 - - # [m] Gần goal hơn đây không đo: rot2goal / dừng chính xác có lệnh nhỏ mà không tiến — hợp lệ. - # ► Đặt >= xy_goal_tolerance của profile + 0.3. - progress_goal_zone: 0.6 diff --git a/config/runtime/priest_local_planner_params.yaml b/config/runtime/priest_local_planner_params.yaml index 7b6f8b9..e9f96ce 100644 --- a/config/runtime/priest_local_planner_params.yaml +++ b/config/runtime/priest_local_planner_params.yaml @@ -54,7 +54,7 @@ PriestLocalPlanner: # sự dài thì khoảng hụt kéo dài qua ngưỡng này và horizon vẫn bung. # 0 = bung ngay (hành vi cũ) # --- Solver tự khai bất khả thi (2026-09-04) --- - # Mọi cổng va chạm của planner này đã chuyển sang path_monitor/collision của move_base2 (LETHAL + + # Mọi cổng va chạm của planner này đã chuyển sang env_monitor/contact (guard cũ path_monitor/collision đã xoá 6/9/2026) của move_base2 (LETHAL + # chu vi footprint đệm); planner không còn tự dò costmap để dừng. Thứ duy nhất nó còn giữ là tín # hiệu không ai khác có: best_res_norm — chuẩn vi phạm ràng buộc của CẢ batch. Thang đo thực tế: # bám đường sạch 0–0.3, né bình thường 1–2, mọi ca ngõ cụt đã đọc 4–7. Đo 4/9: res treo 4.5–7.0 @@ -309,7 +309,7 @@ PriestLocalPlanner: # ================= Hình học thân cho các probe còn lại ================= # Cổng va chạm của planner này (dò quỹ đạo / dò cung lệnh / chốt thân-trong-vành) đã CHUYỂN sang - # path_monitor/collision của move_base2 (2026-09-03): LETHAL + chu vi footprint đệm, planner-agnostic. + # env_monitor/contact (guard cũ path_monitor/collision đã xoá 6/9/2026) của move_base2 (2026-09-03): LETHAL + chu vi footprint đệm, planner-agnostic. # Planner không còn tự dừng vì va chạm. Bốn khoá dưới đây chỉ còn là HÌNH HỌC THÂN cho ba phép dò # mềm còn lại: head_slowdown, quét pivot trước khi xoay tại chỗ, đĩa kiểm goal bị đè. Giữ tên khoá # để không đổi schema. diff --git a/config/runtime/recovery_behaviors_params.yaml b/config/runtime/recovery_behaviors_params.yaml index ac07d4e..32b3b3a 100644 --- a/config/runtime/recovery_behaviors_params.yaml +++ b/config/runtime/recovery_behaviors_params.yaml @@ -1,6 +1,6 @@ # ================================================================================================= # recovery_behaviors_params.yaml — bộ recovery behavior (recovery_core, gen-2 tick-based) và tham số -# vận hành. Sắp xếp lại theo bốn phép đo của PathMonitor ngày 4/9/2026. +# vận hành. Sắp xếp lại theo bốn phép đo của PathMonitor ngày 4/9/2026; từ 6/9/2026 các cờ do EnvMonitor cấp (env_monitor_params.yaml). # # Quy ước comment: dòng mô tả = LÀ GÌ / vì sao; `► Chỉnh:` = tăng giảm theo triệu chứng nào. # @@ -50,8 +50,8 @@ recovery: # 2. ROUTES — trigger nào chạy chuỗi behavior nào # =============================================================================================== # - # Sáu trigger, chia hai nhóm theo HẬU QUẢ KHI CẠN ROUTE. Bốn phép đo của PathMonitor - # (`path_monitor_params.yaml`) đổ vào bốn trigger, mỗi phép đo có ngân sách và khoá RIÊNG: + # Sáu trigger, chia hai nhóm theo HẬU QUẢ KHI CẠN ROUTE. Ba verdict của EnvMonitor + # (`env_monitor_params.yaml`: kUnreachable -> path_blocked, kContact -> collision, kStall -> oscillation; off_path không còn nguồn) đổ vào bốn trigger, mỗi phép đo có ngân sách và khoá RIÊNG: # # Phép đo Trigger Cạn route thì... # ------------------ ------------------ ------------------------------------------------- @@ -82,7 +82,7 @@ recovery: # hết ra lệnh quá `controller_patience`), `planning_failed`, hoặc `oscillation`. # # ► Chỉnh route (áp cho cả sáu): - # - route RỖNG = TẮT HẲN trigger đó. Bốn route của PathMonitor được phép rỗng; hai route + # - route RỖNG = TẮT HẲN trigger đó. Bốn route giám sát (path_blocked/off_path/collision/oscillation) được phép rỗng; hai route # `planning_failed`/`controlling_failed` bắt buộc có ít nhất một behavior (validate chặn). # - route được phép LẶP behavior: mỗi lần xuất hiện là một lượt thử (`[detour, wait, detour]`). # - route dài hơn = kiên nhẫn hơn nhưng chậm báo lỗi lên fleet hơn. @@ -114,11 +114,12 @@ recovery: # trước lượt lập đường sau; đổi lại chậm báo lỗi lên fleet. oscillation: [detour_path] - # --- Nhóm B: DỰ BÁO của PathMonitor — cạn route là KHOÁ, robot đi tiếp ------------------------ + # --- Nhóm B: DỰ BÁO của EnvMonitor (kUnreachable, kContact) — cạn route là KHOÁ, robot đi tiếp ----- # PHÉP ĐO 1: plan phía trước chạm vành 253 trong `horizon` (3 m). Cảnh báo SỚM nhất, robot còn # cách vật cản cả mét — lập lại đường là đủ, không cần lùi. - # ► Chỉnh: phép đo này đang TẮT ở `path_monitor_params.yaml` (`path_blocked_enabled: false`). + # ► Chỉnh: cờ này do kUnreachable của `env_monitor_params.yaml` cấp (`unreachable/action: recover`); phép đo 1 + # "plan ∩ 253" của PathMonitor cũ đã xoá 6/9/2026. # Route vẫn khai sẵn để bật lại chỉ bằng một dòng bên đó. path_blocked: [detour_path] diff --git a/include/move_base2/config/move_base2_config.h b/include/move_base2/config/move_base2_config.h index 037016c..dc438c1 100644 --- a/include/move_base2/config/move_base2_config.h +++ b/include/move_base2/config/move_base2_config.h @@ -148,12 +148,7 @@ struct MoveBase2Config /// Giữ marker cho docking planner legacy; false cho profile docking dựa hoàn toàn vào goal_frame. bool docking_requires_marker = true; - // --- Giám sát tuyến --------------------------------------------------------------------------- - - /// Đọ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` ------- + // --- EnvMonitor (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. diff --git a/include/move_base2/control_loop.h b/include/move_base2/control_loop.h index aab3674..d902caf 100644 --- a/include/move_base2/control_loop.h +++ b/include/move_base2/control_loop.h @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -65,12 +64,6 @@ struct ControlLoopDeps CostmapStatusPort* costmap_status = nullptr; ActionPort* action = nullptr; ///< Có thể null (D8) — null thì yêu cầu có action bị từ chối. - /** - * Nguồn trả lời "tuyến này còn đi được không". **Có thể null** — null thì `PathMonitor` và luật - * lọc plan bẩn đều tắt, hành vi y hệt trước 2026-08-04d. Mọi bộ test dùng cổng giả rơi vào nhánh - * 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 @@ -163,128 +156,8 @@ struct ControlLoopConfig */ bool docking_requires_marker = true; - /** - * @struct PathMonitorConfig - * @brief Giám sát tuyến trong lúc bám plan (contract 2026-08-04d). - * - * Hai phép đo độc lập, cùng một kết cục: robot **dừng** rồi chạy recovery của trigger tương ứng. - * - tuyến phía trước bị chắn → `path_blocked` - * - robot đã lệch khỏi plan → `off_path` - * - * Mỗi phép đo tắt riêng được, và route rỗng cũng là tắt — có hai nút để đảm bảo đường lùi. - */ - struct PathMonitorConfig - { - bool enabled = false; ///< Công tắc CHUNG. Tắt mặc định: bật bằng config, không bật ngầm. - /** - * Công tắc RIÊNG cho từng phép đo, nằm dưới @ref enabled (tắt cái chung là tắt cả hai). - * - * Trước 2026-08-06 chỉ tắt được bằng cách đặt `horizon`/`max_cross_track` về 0 — một giá trị - * ma, đọc config không thấy ý định, và lẫn với "quên khai". Hai cờ này nói thẳng. Ngưỡng 0 vẫn - * còn tác dụng tắt để config cũ không đổi hành vi. - */ - bool path_blocked_enabled = true; - bool off_path_enabled = true; - - double check_period = 0.2; ///< [s] nhịp quét. KHÔNG quét mỗi control cycle — quá phí. - double confirm_time = 0.5; ///< [s] điều kiện phải đúng liên tục chừng này mới khai hoả. - - /// [m] Quãng tuyến phía trước cần quét. Phải <= nửa cửa sổ costmap local, ngoài đó không có dữ - /// liệu. 0 = tắt phép đo "tuyến bị chắn" (cách cũ; ưu tiên @ref path_blocked_enabled). - double horizon = 3.0; - - /// [m] Vật cản gần hơn mức này thì KHÔNG khai hoả: detour từ sát nách vật cản hầu như không ra - /// nghiệm, và tình huống đó đã có `controller_patience` lo. - double min_detour_distance = 0.5; - - /// [m] Lệch khỏi plan quá mức này thì khai hoả. 0 = tắt phép đo "lệch tuyến" (cách cũ; ưu tiên - /// @ref off_path_enabled). Để 0 nghĩa là bật cờ thôi vẫn chưa đủ — phải cho một ngưỡng thật. - double max_cross_track = 0.0; - - /// [s] Bỏ qua phép đo lệch tuyến ngay sau khi nhận plan mới — lúc preempt/đổi chặng pose robot - /// có thể lệch nhất thời so với plan vừa tới. - double grace_after_new_plan = 1.0; - - /** - * -- Phép đo 3: thân robot sắp chạm vật cản THẬT (2026-09-03) --------------------------------- - * - * Độc lập với hai phép đo trên — không dùng chung nhịp, ngưỡng hay công tắc nào của chúng. - * Đối tượng đo là cung mà lệnh `(v, omega)` của controller sắp vẽ ra từ pose hiện tại, dò - * bằng footprint đã đệm, ngưỡng LETHAL. Chạy MỖI control cycle (không theo `check_period`): - * 0.2 s + 0.5 s xác nhận ở 0.5 m/s là 0.35 m — bằng cả quãng dừng. - * - * Hai bước khi chạm trong `collision_stop_distance`: (1) ngay cycle đó lệnh ra bằng 0 — trọng - * tài phát 0 tức thì như costmap stale; (2) sau `collision_confirm_cycles` cycle liên tiếp, - * giơ cờ `collision` để state machine chạy route `collision` (tách khỏi phép đo 1 ngày 4/9: nổ - * ở 0.2 m thì lùi trước khi lập lại đường có nghĩa, ở 3 m thì không). - */ - bool collision_enabled = false; - double collision_lookahead = 0.8; ///< [m] quãng cung cần dò — tầm phanh. - int collision_max_samples = 6; ///< số mẫu trên cung. - double collision_stop_distance = 0.35; ///< [m] chạm gần hơn đây: lệnh 0 ngay + đếm xác nhận. - int collision_confirm_cycles = 2; ///< [cycle] chạm liên tiếp chừng này mới giơ cờ. - int collision_cost_threshold = 254; ///< cost >= đây là chạm. 254 = chỉ LETHAL, không inflation. - /** - * [m] Hình chữ nhật thân tính từ base_link: mũi / đuôi / nửa bề rộng. CẢ BA bằng 0 (mặc định) - * = lấy từ footprint không đệm của costmap qua PathCheckPort::robotBodyExtents() mỗi cycle — cùng - * hình với SBPL và PRIEST, đổi footprint lúc chạy là guard đổi theo. Khai tay thì phải khai đủ - * cả ba > 0; khai lửng là config sai. Không có cả hai nguồn thì guard báo lỗi và KHÔNG kết luận - * (không dừng) ở cycle đó. - */ - double collision_front_offset = 0.0; - double collision_rear_offset = 0.0; - double collision_side_offset = 0.0; - double collision_footprint_padding = 0.1;///< [m] biên an toàn tường minh, thay cho inflation. - /// Loại trừ ô LETHAL đang nằm dưới thân đệm tại pose hiện tại (xem MotionCheckParams). - bool collision_exclude_baseline = true; - double collision_min_speed = 0.02; ///< [m/s] |v| dưới đây không dò (xoay tại chỗ). - /** - * Tiêu chí "sắp chạm" theo THỜI GIAN và GÓC (2026-09-04, run 16:26). Trong stop_distance, - * "walk mét dọc cung" không nói lên gì với cung xoay gần tại chỗ: 0.15 m ở R = 0.08 m là quay - * 107° và còn 3.8 s, còn PRIEST sẽ thôi xoay sau 30–60° để thẳng hàng. Chỉ dừng khi - * `walk/|v| <= collision_stop_time` HOẶC `|omega/v|·walk <= collision_stop_angle`; ngoài đó chỉ - * kẹp v <= (walk − padding)/stop_time. Đi thẳng (turn ≈ 0) luôn "sắp" -> y như trước. - */ - double collision_stop_time = 1.0; ///< [s] - double collision_stop_angle = 0.35; ///< [rad] ~20° - double collision_lookahead_angle = 1.0; ///< [rad] cung không dò quá góc này (xem MotionCheckParams). - /// [m/s^2] Chạm XA hơn stop_distance thì kẹp `v <= sqrt(2 a (d - stop))` trước khi phát; - /// 0 = không kẹp, chỉ dừng khi đã vào stop_distance. - double collision_brake_decel = 0.0; - - // --- Phép đo 4: tiến độ so với lệnh (2026-09-04) ------------------------------------------ - // - // "Planner ĐÒI ĐI mà robot KHÔNG TIẾN" — định nghĩa vận hành của local minimum. Không cần biết - // vì sao kẹt: trong cửa sổ `progress_window`, cộng tổng |v| ĐÃ PHÁT (sau trọng tài) và so với - // quãng tiến được (max của tiến dọc plan và giảm khoảng cách tới goal). Lệnh nhiều mà tiến ít - // là kẹt. Đo trên sim 3/9: bình thường eff 0.65-0.85 kể cả khi né lệch plan 1.9 m; hai ca kẹt - // thật eff -0.14..0.27, nổ 12 s trước khi hệ cũ vào RECOVERING. - // - // KHÔNG nổ khi: PRIEST hold chờ người (twist 0 -> cmd = 0), Phép đo 3 phanh (lệnh sau trọng - // tài = 0), rot2path (v = 0), sát goal (`progress_goal_zone`), vừa nhận plan (grace). - bool progress_enabled = false; - /// "log" = chỉ in cảnh báo (giai đoạn quan sát); "recover" = leo thang kOscillation. - /// Mặc định log: ngưỡng rút từ hai ca kẹt trong một log sim, và kOscillation là trigger GỐC — - /// cạn route là ABORT chặng, nổ oan là mất chặng chứ không chỉ mất vài giây. - std::string progress_action = "log"; - double progress_window = 3.0; ///< [s] cửa sổ đo. - double progress_min_commanded = 0.30; ///< [m] lệnh tích luỹ ít hơn = đang chờ, không đo. - double progress_min_efficiency = 0.30; ///< [-] prog/cmd dưới đây là kẹt. - double progress_clear_efficiency = 0.60; ///< [-] prog/cmd trên đây mới xoá chuỗi kẹt (hysteresis). - double progress_confirm_time = 1.0; ///< [s] kẹt liên tục chừng này mới khai hoả. - double progress_goal_zone = 0.6; ///< [m] gần goal hơn đây không đo (rot2goal, dừng chính xác). - - /// Profile được giám sát. Docking/go_straight/rotate KHÔNG bao giờ nên có mặt: đườ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 đó. - std::vector profiles{ MotionProfile::kPosition }; - - bool monitors(MotionProfile profile) const; - }; - - PathMonitorConfig path_monitor; - - // --- EnvMonitor (P3: chạy song song PathMonitor, shadow qua `action: log`) --------------------- + // --- EnvMonitor (Test/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 ---------- EnvMonitorConfig env_monitor; EnvSamplingConfig env_sampling; EnvLoggerConfig env_logger; @@ -477,50 +350,12 @@ private: /// @brief Gọi controller và lấy lệnh ứng viên. void runController(robot_geometry_msgs::Twist& candidate); - /** - * @brief Chạy PathMonitor và cập nhật hai cờ khai hoả. - * - * Gọi ở đầu cycle, TRƯỚC state machine — hai cờ là dữ liệu vào của nó. - * - * @param now Thời điểm cycle này. - * @param robot_pose Pose robot; chỉ dùng khi @p pose_available. - * @param pose_available Mất pose thì không đo được gì cả. - * @param costmap_stale Costmap quá hạn thì mọi kết luận về vật cản đều là quá khứ. - */ - void updatePathMonitor(const robot::Time& now, const robot_geometry_msgs::PoseStamped& robot_pose, - bool pose_available, bool costmap_stale); - - /// @brief Đặt lại toàn bộ trạng thái debounce của monitor (đổi chặng, rời kControlling, tắt). - void resetPathMonitor(); - - /// @brief Phép đo 4: "planner đòi đi mà không tiến". Gọi từ updatePathMonitor theo nhịp quét. - 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. + * verdict cho state machine và trọng tài của CYCLE NÀY. Gọi trước state machine. */ 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(); - - /** - * @brief Phép đo 3 của PathMonitor: dò cung lệnh @p candidate, ghi đè lệnh nếu sắp chạm. - * - * Gọi NGAY SAU controller, TRƯỚC trọng tài, mỗi cycle. Đặt @ref collision_brake_ (lệnh ra = 0 - * cycle này) và, sau đủ cycle xác nhận, @ref collision_blocked_ (cờ vào state machine cycle - * sau, gộp với `path_blocked`). - */ - void applyCollisionGuard(const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available, - robot_geometry_msgs::Twist& candidate); - - /// @brief Plan này có bị chắn không. false = không kết luận được (thiếu cổng/TF/costmap). - bool planIsBlocked(const std::vector& plan, - std::size_t from_index) const; - /// @brief Quaternion có chuẩn hoá được không — goal hỏng phải bị từ chối ngay tại cửa. static bool isQuaternionValid(const robot_geometry_msgs::PoseStamped& pose); @@ -574,56 +409,6 @@ private: /// (@ref ControlLoopConfig::planner_frequency). Đặt lại khi nhận yêu cầu mới. robot::Time last_plan_started_; - // --- PathMonitor ----------------------------------------------------------------------------- - // - // Hai cờ này là KẾT QUẢ ĐÃ DEBOUNCE, không phải phép đo thô: chúng chỉ bật sau khi điều kiện đúng - // liên tục đủ `confirm_time`. Người/xe đi ngang qua đúng một lượt quét không được làm robot dừng. - bool path_blocked_ = false; - bool off_path_ = false; - /// [m] Chỗ chắn gần nhất đo được. `mutable` vì nó chỉ phục vụ log — `planIsBlocked` vẫn là phép - /// hỏi thuần, không đổi quyết định nào của loop. - mutable double last_block_distance_ = 0.0; - - robot::Time last_path_check_; ///< Mốc nhịp quét. - bool has_last_path_check_ = false; - - robot::Time blocked_since_; ///< Lần đầu thấy tuyến bẩn trong chuỗi hiện tại. - bool blocked_seen_ = false; - robot::Time off_path_since_; ///< Lần đầu thấy lệch quá ngưỡng trong chuỗi hiện tại. - bool off_path_seen_ = false; - - // Phép đo 3 — trạng thái riêng, không dính nhịp `last_path_check_`. - /// Thân đang dùng khi lấy từ costmap, chỉ để log khi thay đổi (footprint đổi lúc chạy). - bool collision_body_logged_ = false; - double collision_body_front_ = 0.0; ///< [m] - double collision_body_rear_ = 0.0; ///< [m] - double collision_body_side_ = 0.0; ///< [m] - bool collision_brake_ = false; ///< Cycle này lệnh ra phải bằng 0 (chạm trong stop_distance). - bool collision_blocked_ = false; ///< Đã xác nhận đủ cycle — giơ cờ collision (trigger riêng). - int collision_streak_ = 0; ///< Số cycle liên tiếp chạm trong stop_distance. - double collision_hit_distance_ = 0.0; ///< [m] chỉ để log. - - // Phép đo 4 — tiến độ so với lệnh. Ring mẫu theo nhịp `check_period`; 32 mẫu x 0.2 s = 6.4 s - // lịch sử, đủ cho `progress_window` 3 s và còn dư. - struct ProgressSample - { - robot::Time t; - double s_plan = 0.0; ///< [m] độ dài plan tính tới pose gần robot nhất. - double d_goal = 0.0; ///< [m] khoảng cách chim bay tới goal. - double cmd = 0.0; ///< [m] tổng |v| đã phát tính tới lúc lấy mẫu. - }; - static constexpr std::size_t kProgressRing = 32; - std::array progress_ring_{}; - std::size_t progress_head_ = 0; ///< Vị trí ghi kế tiếp. - std::size_t progress_count_ = 0; ///< Số mẫu hợp lệ (<= kProgressRing). - double progress_cmd_accum_ = 0.0; ///< [m] tổng |v| đã phát, cộng mỗi cycle SAU trọng tài. - robot::Time progress_stall_since_; - bool progress_stall_seen_ = false; - bool no_progress_ = false; ///< Kết quả đã debounce; chỉ vào state machine ở mode "recover". - std::vector plan_arclen_; ///< [m] độ dài cộng dồn của latest_plan_, dựng khi plan đổi. - std::uint64_t plan_revision_ = 0; ///< Tăng mỗi lần latest_plan_ đổi. - std::uint64_t plan_arclen_revision_ = ~0ull; ///< Revision mà plan_arclen_ và ring đang khớp. - /// Mốc nhận plan mới — dùng cho `grace_after_new_plan`. robot::Time last_plan_applied_; bool has_last_plan_applied_ = false; diff --git a/include/move_base2/core/plan_inspector.h b/include/move_base2/core/plan_inspector.h index 45fcd5e..ed0294c 100644 --- a/include/move_base2/core/plan_inspector.h +++ b/include/move_base2/core/plan_inspector.h @@ -2,10 +2,12 @@ * * Software License Agreement (BSD License) * - * move_base2 — đo đạc trên global plan: tuyến phía trước có sạch không, robot cách plan bao xa. + * move_base2 — hình học trên global plan: quy đổi frame, index gần robot (toàn plan / bám cửa sổ), + * khoảng cách lệch tuyến. * - * Hàm thuần, không giữ trạng thái, không quyết định gì. Người dùng duy nhất là `PathMonitor` của - * `ControlLoop` (và luật lọc plan trong `collectPlannerResult`). + * Hàm thuần, không giữ trạng thái, không quyết định gì. Người dùng: `ControlLoop` (index bám cho + * EnvMonitor) và `CostmapEnvironment` (quy đổi plan về frame lưới). Các hàm quét tuyến/cung của + * PathMonitor cũ (`checkPlan`, `checkMotion`) đã xoá 6/9/2026 — thay bằng `core/grid_analysis`. * * Author: DuongTD *********************************************************************/ @@ -25,18 +27,6 @@ namespace tf3 { class BufferCore; } namespace move_base2 { -/** - * @struct PlanBlockResult - * @brief Kết quả quét tuyến phía trước. - */ -struct PlanBlockResult -{ - bool blocked = false; ///< Có ô nào trên tuyến không đặt được robot vào không. - std::size_t index = 0; ///< Index pose bẩn đầu tiên. Chỉ có nghĩa khi @ref blocked. - double distance = 0.0; ///< [m] Quãng đường dọc plan từ pose bắt đầu tới đó. - std::size_t scanned = 0; ///< Số pose đã quét — 0 nghĩa là không kết luận được gì. -}; - /** * @struct PlanarTransform * @brief Phép biến đổi 2D phẳng: `p_out = R(yaw) * p_in + t`. @@ -96,109 +86,6 @@ std::size_t trackedNearestIndex(const std::vector& plan, const robot_geometry_msgs::PoseStamped& pose); -/** - * @brief Quét tuyến phía trước xem có ô nào không đặt được robot vào không. - * - * @param plan Tuyến cần quét, trong frame của plan. - * @param from_index Bắt đầu quét từ đây (thường là @ref nearestIndex của pose robot). - * @param horizon [m] Quãng đường dọc plan tối đa cần quét. - * @param grid Lưới cost. Bên gọi phải giữ mutex của nó. - * @param plan_to_grid Phép quy đổi frame plan → frame lưới. - * - * Ngữ nghĩa cost, cả ba đều cố ý: - * - `>= INSCRIBED_INFLATED_OBSTACLE` = **bị chắn**: đặt tâm robot ở đây thì footprint đã đệm chạm - * vật cản. - * - `NO_INFORMATION` = **KHÔNG** bị chắn. Vùng chưa quét mà tính là chắn thì robot dừng suốt ở mọi - * tuyến đi vào chỗ chưa thấy. - * - Pose ra ngoài lưới = **dừng quét**, không phải bị chắn. Cửa sổ costmap lăn theo robot nên phần - * xa luôn nằm ngoài; coi đó là bị chắn thì mọi plan đều bẩn. - */ -PlanBlockResult checkPlan(const std::vector& plan, - std::size_t from_index, double horizon, - const robot_costmap_2d::Costmap2D& grid, - const PlanarTransform& plan_to_grid); - -/** - * @struct MotionCheckParams - * @brief Hình học và ngưỡng cho phép đo "thân robot có sắp chạm không" (@ref checkMotion). - * - * Khác hẳn @ref checkPlan: đối tượng đo là CHUYỂN ĐỘNG SẮP XẢY RA (cung cong không đổi vẽ bởi lệnh - * `(v, omega)` từ pose hiện tại), không phải global plan — local planner lệch plan cả mét khi né, - * quét plan lúc đó bảo "sạch" trong khi thân đang đi hướng khác (đo 29/8, mission 5: cte 0.97 m, - * robot húc vào khe 0.76 m). Ngưỡng mặc định là LETHAL: chỉ ô vật cản THẬT, không đếm vành - * inflation — inflation là biên cho tâm robot, đem áp lên mũi/hông là đếm biên hai lần và báo - * chạm giả khi tường còn cách nửa mét. Biên an toàn thay bằng @ref padding tường minh. - */ -struct MotionCheckParams -{ - double lookahead = 0.8; ///< [m] quãng cung cần dò — tầm phanh, không hơn. - /// Trần THƯA của số mẫu: bước = lookahead / max_samples nhưng không bao giờ lớn hơn một ô lưới - /// (tường mỏng 1 ô lọt giữa hai mẫu là đâm xuyên). Ở lưới 0.05 m, 0.8 m dò 16 mẫu. - int max_samples = 6; - double front_offset = 0.0; ///< [m] mũi robot tính từ base_link, dọc heading. - double rear_offset = 0.0; ///< [m] đuôi robot tính từ base_link, ngược heading. - double side_offset = 0.0; ///< [m] nửa bề rộng thân (chu vi dò cả bốn cạnh). - double padding = 0.0; ///< [m] nới thêm mọi offset — biên an toàn tường minh. - unsigned char cost_threshold = 254; ///< cost >= đây là chạm. 254 = chỉ LETHAL. - double min_speed = 0.02; ///< [m/s] |v| dưới đây cung suy biến, không dò (xoay tại chỗ). - /** - * [rad] Không dò cung quá góc quay này: |omega/v|·walk > lookahead_angle thì dừng vẽ. Với cung - * R = 0.1 m, 0.8 m lookahead là quay 8 rad — hơn một vòng tròn — soi thứ không bao giờ xảy ra vì - * lệnh đã đổi từ lâu, và là nguồn của "would hit"/"clear again" lật mỗi vài cycle khi omega/v đổi - * chút ở đuôi cung. Mặc định pi = không cắt (nguyên thuỷ giữ hành vi cũ; policy đặt ở config). - */ - double lookahead_angle = 3.14159265358979323846; - /** - * Loại trừ baseline (2026-09-04): ô >= cost_threshold đang nằm DƯỚI thân đệm tại pose hiện tại - * không được tính là chạm ở các mẫu sau. Câu hỏi đổi từ "thân có đè LETHAL không" thành "lệnh - * này có đưa THÊM ô LETHAL vào thân không": trượt song song / rời xa vật đang kề hông thì đi - * được, lấn sâu thêm thì vẫn chặn. Sim 4/9: người kề hông ở 0.46 m ngang (thân 0.48 + đệm 0.05) - * làm mẫu đầu tiên báo 0.05 m mãi dù lệnh là đi thẳng. false = hành vi cũ. - */ - bool exclude_baseline = true; -}; - -/** - * @struct MotionBlockResult - * @brief Kết quả dò cung lệnh. - */ -struct MotionBlockResult -{ - bool blocked = false; ///< Có điểm dò nào chạm ngưỡng không. - int sample = -1; ///< Chỉ số mẫu chạm đầu tiên (1-based theo bước). Chỉ có nghĩa khi blocked. - double distance = 0.0; ///< [m] quãng dọc cung từ robot tới mẫu chạm. - int scanned = 0; ///< Số mẫu đã dò — 0 nghĩa là không dò được gì (v quá nhỏ). - int baseline_cells = 0; ///< Số ô >= ngưỡng đang nằm dưới thân đệm và đã được loại trừ. Chỉ để log. - - /// Chi tiết để debug hiện trường (không ảnh hưởng quyết định). Toạ độ trong frame robot HIỆN TẠI - /// (x tới, y trái), không phải frame lưới, để người đọc log biết ngay "ô người ở trái-sau". - static constexpr int kMaxListedBaseline = 8; - int hit_edge = -1; ///< Cạnh chạm: 0 phải, 1 mũi, 2 trái, 3 đuôi. -1 = không chạm. - double hit_x = 0.0; ///< [m] ô chạm, frame robot hiện tại. - double hit_y = 0.0; ///< [m] - int baseline_listed = 0; ///< Số ô baseline được liệt kê (<= kMaxListedBaseline). - std::array, kMaxListedBaseline> baseline_xy{}; ///< [m] frame robot hiện tại. -}; - -/** - * @brief Dò cung cong không đổi mà lệnh `(v, omega)` vẽ ra từ pose `(x, y, yaw)` — tất cả trong - * frame của @p grid. - * - * @param baseline_scratch Bộ đệm cho tập ô baseline (xem @ref MotionCheckParams::exclude_baseline), - * để caller gọi 20 Hz không cấp phát heap mỗi cycle; nullptr = dùng vector cục bộ. - * - * Mỗi mẫu dò TOÀN BỘ CHU VI hình chữ nhật footprint đã cộng @ref MotionCheckParams::padding, - * lấy mẫu dày hơn một ô lưới. Năm điểm rời (bản đầu) để hở nửa bề rộng thân giữa các đường quét — - * trụ mảnh đứng ở góc trước lọt qua mà không probe nào thấy (đo 4/9). Bỏ 0.05 m đầu: đất robot đang đứng không phải bằng chứng về tương - * lai, và phán nó là "chạm" biến robot đứng cạnh vật cản thành đứng vĩnh viễn. `NO_INFORMATION` - * và điểm ra ngoài lưới = KHÔNG chạm (cùng lý do với @ref checkPlan). v < 0 (lùi) dò theo chiều - * lùi với cùng hình học. - */ -MotionBlockResult checkMotion(double x, double y, double yaw, double v, double omega, - const MotionCheckParams& params, - const robot_costmap_2d::Costmap2D& grid, - std::vector* baseline_scratch = nullptr); - } // namespace move_base2 #endif // MOVE_BASE2_CORE_PLAN_INSPECTOR_H_ diff --git a/include/move_base2/core/state_machine.h b/include/move_base2/core/state_machine.h index 76f0ddb..d1b92a5 100644 --- a/include/move_base2/core/state_machine.h +++ b/include/move_base2/core/state_machine.h @@ -197,7 +197,8 @@ struct StateMachineInput bool robot_stopped = true; /** - * Tuyến phía trước bị chắn (PathMonitor của control loop đã xác nhận đủ `confirm_time`). + * Tuyến phía trước bị chắn (EnvMonitor kUnreachable: không còn đường trong cửa sổ tới điểm thoát, đã + * tĩnh đủ `static_on`). * * Khác mọi cờ khác trong struct này: nó là **dự báo**, không phải báo hỏng. Controller vẫn ra * lệnh bình thường, plan vẫn hợp lệ — chỉ là đi tiếp thì sẽ tắc. Bên gọi chịu trách nhiệm mọi @@ -205,15 +206,16 @@ struct StateMachineInput */ bool path_blocked = false; - /// Robot đã lệch khỏi plan đang chạy quá ngưỡng. Cùng quy ước với @ref path_blocked. + /// Robot đã lệch khỏi plan đang chạy quá ngưỡng. Cùng quy ước với @ref path_blocked. Từ 6/9/2026 không + /// còn nguồn cấp (phép đo 2 của PathMonitor cũ đã xoá); giữ cổng cho hợp đồng route/khoá và test. bool off_path = false; - /// Phép đo 3 của PathMonitor: thân sắp chạm vật cản thật trên cung lệnh, đã đủ cycle xác nhận. + /// EnvMonitor kContact: thân sắp chạm vật cản thật trên quỹ đạo local planner, kề mũi tĩnh đủ lâu. /// Cùng quy ước với @ref path_blocked (dự báo, route riêng `collision`, cạn route thì khoá). /// Thắng cả path_blocked lẫn off_path khi cùng đúng: gần nhất thì xử lý trước. bool collision = false; - /// Phép đo 4 của PathMonitor: planner đòi đi mà robot không tiến (local minimum đã bắt đầu). + /// EnvMonitor kStall: planner đòi đi mà robot không đi được đâu (cổng dịch chuyển thực mở). /// Đi đường kOscillation — trigger GỐC — nên cạn route là ABORT hợp lệ, không rơi vào bẫy trigger /// giám sát bị khoá rồi đứng im. Bên gọi chịu debounce/route/mode; state machine chỉ tin cờ. bool no_progress = false; diff --git a/include/move_base2/navigation_runtime.h b/include/move_base2/navigation_runtime.h index 99bf3c2..2d73669 100644 --- a/include/move_base2/navigation_runtime.h +++ b/include/move_base2/navigation_runtime.h @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -88,51 +87,6 @@ private: std::shared_ptr tf_; }; -/** - * @class CostmapPathCheck - * @brief Hiện thực @ref PathCheckPort trên costmap ĐIỀU KHIỂN (local). - * - * Local chứ không global, hai lý do và cả hai đều quan trọng: - * - **Độ tươi**: local chạy ở `update_frequency: 6.0` Hz, global chỉ `1.0` Hz. Vật cản vừa xuất - * hiện có mặt ở local trước. - * - **Đồng thuận với detour**: `DetourPathRecovery` lập đường vòng trên chính local costmap. - * Monitor báo "bẩn" trên một lưới mà planner detour lại thấy "sạch" là vòng lặp vô nghĩa. - * - * Plan ở frame global (`map`) còn lưới ở `odom`, nên phải quy đổi — tra TF **một lần** cho cả lượt - * quét (xem @ref PlanarTransform), không phải mỗi pose. - * - * @note Con trỏ costmap **non-owning và có thể bị thay** — lấy lại mỗi lần dùng, không cache - * `Costmap2D*` bên trong. - */ -class CostmapPathCheck final : public PathCheckPort -{ -public: - void setCostmap(robot_costmap_2d::Costmap2DROBOT* costmap) - { - costmap_ = costmap; - } - - void setTf(const std::shared_ptr& tf) - { - tf_ = tf; - } - - bool checkPlan(const std::vector& plan, - std::size_t from_index, double horizon, PlanBlockResult& out) const override; - - bool checkMotion(const robot_geometry_msgs::PoseStamped& robot_pose, double v, double omega, - const MotionCheckParams& params, MotionBlockResult& out) const override; - - bool robotBodyExtents(double& front, double& rear, double& side) const override; - -private: - robot_costmap_2d::Costmap2DROBOT* costmap_ = nullptr; - std::shared_ptr tf_; - /// Bộ đệm baseline của checkMotion — tránh cấp phát heap mỗi cycle. Cổng này chỉ được gọi từ - /// control thread (một consumer), nên `mutable` không tạo race. - 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. @@ -391,7 +345,7 @@ 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. + /// Nguồn dữ liệu của EnvMonitor: costmap local, cùng lưới với detour. CostmapEnvironment environment_; std::unique_ptr global_costmap_; @@ -419,7 +373,6 @@ private: */ CostmapPosePort global_pose_; ///< frame `map` — planner, chống quẩn, pose báo về host. CostmapPosePort local_pose_; ///< frame `odom` — controller và recovery. - CostmapPathCheck path_check_; ///< quét tuyến trên costmap local (PathMonitor + lọc plan). CostmapExporter global_exporter_; CostmapExporter local_exporter_; diff --git a/include/move_base2/ports/path_check_port.h b/include/move_base2/ports/path_check_port.h deleted file mode 100644 index e34fef4..0000000 --- a/include/move_base2/ports/path_check_port.h +++ /dev/null @@ -1,88 +0,0 @@ -/********************************************************************* - * - * Software License Agreement (BSD License) - * - * move_base2 — cổng kiểm tra tuyến trên costmap. - * - * Author: DuongTD - *********************************************************************/ -#ifndef MOVE_BASE2_PORTS_PATH_CHECK_PORT_H_ -#define MOVE_BASE2_PORTS_PATH_CHECK_PORT_H_ - -#include -#include - -#include - -#include - -namespace move_base2 -{ - -/** - * @class PathCheckPort - * @brief "Tuyến này có đi được không" — lõi hỏi, hạ tầng trả lời. - * - * Tách thành cổng vì phép kiểm cần **costmap + TF**, hai thứ `ControlLoop` cố ý không giữ. Nhờ vậy - * lõi vẫn kiểm được bằng cổng giả, còn hiện thực thật (`CostmapPathCheck`) sống cạnh costmap trong - * `NavigationRuntime`. - * - * @note Chỉ control thread được gọi: hiện thực thật giữ mutex costmap trong lúc quét. - */ -class PathCheckPort -{ -public: - virtual ~PathCheckPort() = default; - - /** - * @brief Quét @p plan từ @p from_index về phía trước tối đa @p horizon [m]. - * - * @param[out] out Kết quả; chỉ được ghi khi hàm trả true. - * @return false = **không kết luận được** (thiếu TF, chưa có costmap). Bên gọi phải coi đó là - * "không biết" và KHÔNG khai hoả — không được suy thành "sạch" hay "bẩn". - */ - virtual bool checkPlan(const std::vector& plan, - std::size_t from_index, double horizon, PlanBlockResult& out) const = 0; - - /** - * @brief Dò cung mà lệnh `(v, omega)` sắp vẽ ra từ @p robot_pose — thân robot có chạm không. - * - * Mặc định = "không kết luận được": cổng giả và hiện thực cũ không cần biết phép đo này; chỉ - * `CostmapPathCheck` hiện thực thật. Cùng quy ước với @ref checkPlan: false = KHÔNG BIẾT, bên gọi - * không được khai hoả. - */ - virtual bool checkMotion(const robot_geometry_msgs::PoseStamped& robot_pose, double v, - double omega, const MotionCheckParams& params, - MotionBlockResult& out) const - { - (void)robot_pose; - (void)v; - (void)omega; - (void)params; - (void)out; - return false; - } - - /** - * @brief Kích thước thân robot từ footprint mà costmap đang dùng (KHÔNG đệm), trong frame base. - * - * @param[out] front [m] mũi tính từ base_link (max x), @p rear [m] đuôi (-min x), - * @p side [m] nửa bề rộng (max |y|). Chỉ ghi khi trả true. - * @return false nếu cổng không có footprint (test giả, costmap chưa dựng) hoặc footprint suy biến — - * caller phải dùng số khai tay hoặc báo không kết luận được. - * - * Collision guard dùng hình chữ nhật bao của footprint; footprint đa giác lồi khác chữ nhật thì bao - * hơi rộng hơn, an toàn về phía dừng sớm. - */ - 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_PATH_CHECK_PORT_H_ diff --git a/include/move_base2/runners/controller_runner.h b/include/move_base2/runners/controller_runner.h index 3d2948a..a323124 100644 --- a/include/move_base2/runners/controller_runner.h +++ b/include/move_base2/runners/controller_runner.h @@ -182,6 +182,13 @@ public: return controllers_.size(); } + /// @brief ControlLoop đã làm mới snapshot costmap đầu cycle (qua EnvironmentPort::refresh) thì runner + /// không làm lại trước computeVelocityCommands/isGoalReached/setPlan — một lưới cho cả cycle (P0b). + void setSnapshotRefreshedByLoop(bool refreshed) + { + snapshot_refreshed_by_loop_ = refreshed; + } + private: /// @brief Một plugin đã nạp: factory phải sống cùng instance — vứt factory là để `.so` unload. struct Loaded @@ -223,6 +230,8 @@ private: /// Khoá costmap mutex quanh lời gọi plugin. Chỉ unit test với costmap placeholder mới được tắt. bool costmap_lock_enabled_ = true; + /// true = ControlLoop đã refreshSnapshot() một lần đầu cycle qua EnvironmentPort; runner không làm lại. + bool snapshot_refreshed_by_loop_ = false; /// Telemetry non-owning, null = tắt đo. Chỉ đọc sau khi @ref attachStats. RuntimeStats* stats_ = nullptr; diff --git a/src/config/move_base2_config.cpp b/src/config/move_base2_config.cpp index b67fd96..d2fe4a0 100644 --- a/src/config/move_base2_config.cpp +++ b/src/config/move_base2_config.cpp @@ -140,94 +140,6 @@ void readDockingMarkerProfiles(robot::NodeHandle& nh, DockingMarkerProfiles& pro } } -/** - * @brief Đọc khối `path_monitor`. - * - * Khối vắng mặt = giám sát tuyến TẮT, hành vi y hệt trước 2026-08-04d. Đây là đường lùi thứ nhất - * (thứ hai là route `path_blocked`/`off_path` rỗng) — hai nút độc lập, cố ý. - */ -void readPathMonitor(robot::NodeHandle& nh, ControlLoopConfig::PathMonitorConfig& monitor) -{ - robot::NodeHandle monitor_nh(nh, "path_monitor"); - - readBool(monitor_nh, "enabled", monitor.enabled); - readBool(monitor_nh, "path_blocked_enabled", monitor.path_blocked_enabled); - readBool(monitor_nh, "off_path_enabled", monitor.off_path_enabled); - readDouble(monitor_nh, "check_period", monitor.check_period); - readDouble(monitor_nh, "confirm_time", monitor.confirm_time); - readDouble(monitor_nh, "horizon", monitor.horizon); - readDouble(monitor_nh, "min_detour_distance", monitor.min_detour_distance); - readDouble(monitor_nh, "max_cross_track", monitor.max_cross_track); - readDouble(monitor_nh, "grace_after_new_plan", monitor.grace_after_new_plan); - - // Phép đo 3 (2026-09-03): thân sắp chạm vật cản THẬT trên cung lệnh. Khoá riêng, không dùng chung - // tham số nào với hai phép đo trên. - readBool(monitor_nh, "collision_enabled", monitor.collision_enabled); - readDouble(monitor_nh, "collision_lookahead", monitor.collision_lookahead); - monitor_nh.param("collision_max_samples", monitor.collision_max_samples, - monitor.collision_max_samples); - readDouble(monitor_nh, "collision_stop_distance", monitor.collision_stop_distance); - monitor_nh.param("collision_confirm_cycles", monitor.collision_confirm_cycles, - monitor.collision_confirm_cycles); - monitor_nh.param("collision_cost_threshold", monitor.collision_cost_threshold, - monitor.collision_cost_threshold); - readDouble(monitor_nh, "collision_front_offset", monitor.collision_front_offset); - readDouble(monitor_nh, "collision_rear_offset", monitor.collision_rear_offset); - readDouble(monitor_nh, "collision_side_offset", monitor.collision_side_offset); - readDouble(monitor_nh, "collision_footprint_padding", monitor.collision_footprint_padding); - readBool(monitor_nh, "collision_exclude_baseline", monitor.collision_exclude_baseline); - readDouble(monitor_nh, "collision_min_speed", monitor.collision_min_speed); - readDouble(monitor_nh, "collision_stop_time", monitor.collision_stop_time); - readDouble(monitor_nh, "collision_stop_angle", monitor.collision_stop_angle); - readDouble(monitor_nh, "collision_lookahead_angle", monitor.collision_lookahead_angle); - readDouble(monitor_nh, "collision_brake_decel", monitor.collision_brake_decel); - - // Phép đo 4 (2026-09-04): planner đòi đi mà robot không tiến. - readBool(monitor_nh, "progress_enabled", monitor.progress_enabled); - readString(monitor_nh, "progress_action", monitor.progress_action); - readDouble(monitor_nh, "progress_window", monitor.progress_window); - readDouble(monitor_nh, "progress_min_commanded", monitor.progress_min_commanded); - readDouble(monitor_nh, "progress_min_efficiency", monitor.progress_min_efficiency); - readDouble(monitor_nh, "progress_clear_efficiency", monitor.progress_clear_efficiency); - readDouble(monitor_nh, "progress_confirm_time", monitor.progress_confirm_time); - readDouble(monitor_nh, "progress_goal_zone", monitor.progress_goal_zone); - - std::vector names; - monitor_nh.param("profiles", names, std::vector{}); - if (names.empty()) - { - return; // Giữ mặc định: chỉ profile position. - } - - monitor.profiles.clear(); - for (const std::string& name : names) - { - if (name == "position") - { - monitor.profiles.push_back(MotionProfile::kPosition); - } - else if (name == "docking") - { - monitor.profiles.push_back(MotionProfile::kDocking); - } - else if (name == "go_straight") - { - monitor.profiles.push_back(MotionProfile::kGoStraight); - } - else if (name == "rotate") - { - monitor.profiles.push_back(MotionProfile::kRotate); - } - else - { - // Không đoán: tên lạ mà im lặng bỏ qua thì người vận hành tưởng đã bật giám sát cho profile - // đó. Cảnh báo rồi bỏ — profile lạ không thể tự sinh ra hành vi nào. - robot::log_warning("[move_base2] path_monitor/profiles: unknown profile '%s', ignored.\n", - name.c_str()); - } - } -} - /// Các tham số chung của move_base2, dùng chung cho schema namespace và schema root-profile. void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config) { @@ -271,7 +183,6 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config) readSensors(nh, config.sensors); readSensorStore(nh, config); readDebug(nh, config); - readPathMonitor(nh, config.path_monitor); readEnvMonitor(nh, config); readBool(nh, "docking_requires_marker", config.docking_requires_marker); @@ -514,164 +425,6 @@ bool MoveBase2Config::validate(std::string& error) const return false; } - if (path_monitor.enabled) - { - // Chỉ kiểm khi BẬT: tham số vô nghĩa trong một khối đang tắt không có lý do gì để chặn boot. - if (!std::isfinite(path_monitor.check_period) || path_monitor.check_period <= 0.0) - { - error = "path_monitor/check_period must be > 0 [s]"; - return false; - } - if (!std::isfinite(path_monitor.confirm_time) || path_monitor.confirm_time < 0.0) - { - error = "path_monitor/confirm_time must be >= 0 [s]"; - return false; - } - if (!std::isfinite(path_monitor.horizon) || path_monitor.horizon < 0.0) - { - error = "path_monitor/horizon must be >= 0 [m] (0 = the blocked-path check is off)"; - return false; - } - if (!std::isfinite(path_monitor.min_detour_distance) || path_monitor.min_detour_distance < 0.0) - { - error = "path_monitor/min_detour_distance must be >= 0 [m]"; - return false; - } - if (!std::isfinite(path_monitor.max_cross_track) || path_monitor.max_cross_track < 0.0) - { - error = "path_monitor/max_cross_track must be >= 0 [m] (0 = the off-path check is off)"; - return false; - } - if (!std::isfinite(path_monitor.grace_after_new_plan) || - path_monitor.grace_after_new_plan < 0.0) - { - error = "path_monitor/grace_after_new_plan must be >= 0 [s]"; - return false; - } - if (path_monitor.collision_enabled) - { - const auto bad = [](double v) { return !std::isfinite(v) || v < 0.0; }; - if (!std::isfinite(path_monitor.collision_lookahead) || path_monitor.collision_lookahead <= 0.0) - { - error = "path_monitor/collision_lookahead must be > 0 [m]"; - return false; - } - if (path_monitor.collision_max_samples < 1) - { - error = "path_monitor/collision_max_samples must be >= 1"; - return false; - } - if (bad(path_monitor.collision_stop_distance) || - path_monitor.collision_stop_distance > path_monitor.collision_lookahead) - { - error = "path_monitor/collision_stop_distance must be in [0, collision_lookahead] [m]"; - return false; - } - if (path_monitor.collision_confirm_cycles < 1) - { - error = "path_monitor/collision_confirm_cycles must be >= 1"; - return false; - } - if (path_monitor.collision_cost_threshold < 1 || path_monitor.collision_cost_threshold > 254) - { - error = "path_monitor/collision_cost_threshold must be in [1, 254] (254 = LETHAL only)"; - return false; - } - if (bad(path_monitor.collision_front_offset) || bad(path_monitor.collision_rear_offset) || - bad(path_monitor.collision_side_offset) || bad(path_monitor.collision_footprint_padding)) - { - error = "path_monitor/collision_*_offset and collision_footprint_padding must be >= 0 [m]"; - return false; - } - { - // Cả ba = 0: lấy thân từ footprint costmap lúc chạy. Khai tay thì phải đủ cả ba > 0 — mũi = 0 - // là chỉ dò tâm (dừng khi tâm đã ở trong tường), hông = 0 là bỏ hai cạnh hông. - const int declared = (path_monitor.collision_front_offset > 0.0 ? 1 : 0) + - (path_monitor.collision_rear_offset > 0.0 ? 1 : 0) + - (path_monitor.collision_side_offset > 0.0 ? 1 : 0); - if (declared != 0 && declared != 3) - { - error = "path_monitor/collision_front_offset, collision_rear_offset and " - "collision_side_offset must either all be 0 (take the body from the costmap " - "footprint) or all be > 0 [m]"; - return false; - } - } - if (!std::isfinite(path_monitor.collision_stop_time) || path_monitor.collision_stop_time <= 0.0) - { - error = "path_monitor/collision_stop_time must be > 0 [s]"; - return false; - } - if (!std::isfinite(path_monitor.collision_stop_angle) || path_monitor.collision_stop_angle <= 0.0 || - path_monitor.collision_stop_angle > M_PI) - { - error = "path_monitor/collision_stop_angle must be in (0, pi] [rad]"; - return false; - } - if (!std::isfinite(path_monitor.collision_lookahead_angle) || - path_monitor.collision_lookahead_angle < path_monitor.collision_stop_angle || - path_monitor.collision_lookahead_angle > M_PI) - { - error = "path_monitor/collision_lookahead_angle must be in [collision_stop_angle, pi] [rad]"; - return false; - } - if (bad(path_monitor.collision_min_speed) || bad(path_monitor.collision_brake_decel)) - { - error = "path_monitor/collision_min_speed [m/s] and collision_brake_decel [m/s^2] must be >= 0"; - return false; - } - } - if (path_monitor.progress_enabled) - { - if (path_monitor.progress_action != "log" && path_monitor.progress_action != "recover") - { - error = "path_monitor/progress_action must be 'log' or 'recover'"; - return false; - } - if (!std::isfinite(path_monitor.progress_window) || path_monitor.progress_window <= 0.0) - { - error = "path_monitor/progress_window must be > 0 [s]"; - return false; - } - if (!std::isfinite(path_monitor.progress_min_commanded) || - path_monitor.progress_min_commanded <= 0.0) - { - // 0 là đo cả lúc đứng yên: cmd = 0, eff = 0/0 -> mọi lần chờ hợp lệ đều thành "kẹt". - error = "path_monitor/progress_min_commanded must be > 0 [m]"; - return false; - } - if (!std::isfinite(path_monitor.progress_min_efficiency) || - !std::isfinite(path_monitor.progress_clear_efficiency) || - path_monitor.progress_min_efficiency < 0.0 || - path_monitor.progress_clear_efficiency <= path_monitor.progress_min_efficiency) - { - // clear == min là cờ nhấp nháy quanh một ngưỡng: bật, xoá, bật... mỗi lượt quét. - error = "path_monitor/progress_clear_efficiency must be > progress_min_efficiency >= 0"; - return false; - } - if (!std::isfinite(path_monitor.progress_confirm_time) || - path_monitor.progress_confirm_time < 0.0 || - !std::isfinite(path_monitor.progress_goal_zone) || path_monitor.progress_goal_zone < 0.0) - { - error = "path_monitor/progress_confirm_time [s] and progress_goal_zone [m] must be >= 0"; - return false; - } - } - if (!(path_monitor.horizon > 0.0) && !(path_monitor.max_cross_track > 0.0) && - !path_monitor.collision_enabled && !path_monitor.progress_enabled) - { - // Bật khối mà tắt cả bốn phép đo là mâu thuẫn: người khai tưởng giám sát đang chạy. - error = "path_monitor is enabled but all checks are off; set horizon > 0 [m], " - "max_cross_track > 0 [m], collision_enabled: true and/or progress_enabled: true, " - "or set enabled: false"; - return false; - } - if (path_monitor.profiles.empty()) - { - error = "path_monitor/profiles is empty; no leg would ever be monitored"; - return false; - } - } if (!std::isfinite(runtime_stats_period) || runtime_stats_period < 0.0) { error = "runtime_stats_period must be >= 0 [s] (0 = telemetry off)"; @@ -971,7 +724,6 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const config.rotate = rotate; 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; diff --git a/src/control_loop.cpp b/src/control_loop.cpp index 2cce735..ecb5968 100644 --- a/src/control_loop.cpp +++ b/src/control_loop.cpp @@ -152,11 +152,6 @@ std::string ControlLoopConfig::describe() const return out.str(); } -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(); @@ -238,111 +233,9 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe config_ = config; deps_ = deps; - // Bật giám sát mà không có đường xử lý nào là cấu hình vô nghĩa — và trước đây nó im lặng. Không - // chặn boot (navigation vẫn phải chạy), nhưng phải hét lên: người vận hành khai `enabled: true` - // thì tin rằng cơ chế đang chạy. - if (config_.path_monitor.enabled) - { - if (deps_.path_check == nullptr) - { - robot::log_error("[move_base2] path_monitor is enabled but no PathCheckPort is wired — path " - "monitoring stays OFF.\n"); - } - else if (!config_.path_monitor.path_blocked_enabled && !config_.path_monitor.off_path_enabled && - !config_.path_monitor.collision_enabled && !config_.path_monitor.progress_enabled) - { - robot::log_warning("[move_base2] path_monitor/enabled is true but ALL sub-monitors are off " - "(path_blocked_enabled=false, off_path_enabled=false, " - "collision_enabled=false, progress_enabled=false) — path monitoring does " - "nothing.\n"); - } - else if (config_.state_machine.recovery_routes.path_blocked.empty() && - config_.state_machine.recovery_routes.off_path.empty() && - config_.state_machine.recovery_routes.collision.empty() && - config_.state_machine.recovery_routes.oscillation.empty()) - { - robot::log_error("[move_base2] path_monitor is enabled but the recovery routes " - "'path_blocked', 'off_path', 'collision' and 'oscillation' are all empty " - "(behaviors failed to load?) — path monitoring stays OFF.\n"); - } - else - { - // In trạng thái THẬT của từng phép đo, đã gộp cả ba nút: đọc một dòng là biết cái nào sống. - const bool blocked_on = config_.path_monitor.path_blocked_enabled && - config_.path_monitor.horizon > 0.0 && - !config_.state_machine.recovery_routes.path_blocked.empty(); - const bool off_path_on = config_.path_monitor.off_path_enabled && - config_.path_monitor.max_cross_track > 0.0 && - !config_.state_machine.recovery_routes.off_path.empty(); - const bool collision_on = config_.path_monitor.collision_enabled && - config_.path_monitor.collision_lookahead > 0.0 && - !config_.state_machine.recovery_routes.collision.empty(); - char body[64]; - if (!(config_.path_monitor.collision_front_offset > 0.0) && - !(config_.path_monitor.collision_rear_offset > 0.0) && - !(config_.path_monitor.collision_side_offset > 0.0)) - { - std::snprintf(body, sizeof(body), "costmap footprint"); - } - else - { - std::snprintf(body, sizeof(body), "%.2f/%.2f/%.2f", - config_.path_monitor.collision_front_offset, - config_.path_monitor.collision_rear_offset, - config_.path_monitor.collision_side_offset); - } - robot::log_info("[move_base2] path monitor ON (confirm=%.2f s, check=%.2f s):\n" - " path_blocked: %s (flag=%s, horizon=%.2f m, route=%zu)\n" - " off_path : %s (flag=%s, max_cross_track=%.2f m, route=%zu)\n" - " collision : %s (flag=%s, lookahead=%.2f m, stop=%.2f m, confirm=%d " - "cycles, threshold=%d, body=%s+%.2f m, brake=%.2f m/s^2, " - "baseline=%s, stop_time=%.1f s, stop_angle=%.2f rad, lookahead_angle=%.2f " - "rad, route=collision %zu)\n", - config_.path_monitor.confirm_time, config_.path_monitor.check_period, - blocked_on ? "ON" : "OFF", - config_.path_monitor.path_blocked_enabled ? "on" : "off", - config_.path_monitor.horizon, - config_.state_machine.recovery_routes.path_blocked.size(), - off_path_on ? "ON" : "OFF", - config_.path_monitor.off_path_enabled ? "on" : "off", - config_.path_monitor.max_cross_track, - config_.state_machine.recovery_routes.off_path.size(), - collision_on ? "ON" : "OFF", - config_.path_monitor.collision_enabled ? "on" : "off", - config_.path_monitor.collision_lookahead, - config_.path_monitor.collision_stop_distance, - config_.path_monitor.collision_confirm_cycles, - config_.path_monitor.collision_cost_threshold, - body, - config_.path_monitor.collision_footprint_padding, - config_.path_monitor.collision_brake_decel, - config_.path_monitor.collision_exclude_baseline ? "on" : "off", - config_.path_monitor.collision_stop_time, - config_.path_monitor.collision_stop_angle, - config_.path_monitor.collision_lookahead_angle, - config_.state_machine.recovery_routes.collision.size()); - const bool progress_on = - config_.path_monitor.progress_enabled && - (config_.path_monitor.progress_action != "recover" || - !config_.state_machine.recovery_routes.oscillation.empty()); - robot::log_info(" progress : %s (flag=%s, action=%s, window=%.1f s, min_cmd=%.2f m, " - "eff<%.2f kẹt / >=%.2f xoá, confirm=%.1f s, goal_zone=%.2f m, " - "route=oscillation %zu)\n", - progress_on ? "ON" : "OFF", - config_.path_monitor.progress_enabled ? "on" : "off", - config_.path_monitor.progress_action.c_str(), - config_.path_monitor.progress_window, - config_.path_monitor.progress_min_commanded, - config_.path_monitor.progress_min_efficiency, - config_.path_monitor.progress_clear_efficiency, - config_.path_monitor.progress_confirm_time, - config_.path_monitor.progress_goal_zone, - config_.state_machine.recovery_routes.oscillation.size()); - } - } - // 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. + // EnvMonitor (Test/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 (PathMonitor cũ đã + // xoá). 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) { @@ -411,7 +304,6 @@ void ControlLoop::reset() action_message_.clear(); latest_plan_.clear(); - ++plan_revision_; planner_running_ = false; backup_global_planner_active_ = false; @@ -425,7 +317,6 @@ void ControlLoop::reset() has_last_cycle_time_ = false; has_oscillation_origin_ = false; last_plan_started_ = robot::Time(); - resetPathMonitor(); has_last_plan_applied_ = false; env_monitor_.reset(); @@ -725,30 +616,8 @@ void ControlLoop::collectPlannerResult() return; } - // Luật "không thay plan sạch bằng plan bẩn" (contract 2026-08-04d). - // - // Không có luật này thì cơ chế detour tự phá chính nó: `CustomPlanner` mù costmap nên mỗi nhịp - // `planner_frequency` nó trả lại đúng đường thẳng xuyên vật cản, ghi đè đường vòng vừa lập, rồi - // PathMonitor lại khai hoả — robot dừng-detour-chạy-dừng mỗi giây và ngân sách route cạn rất - // nhanh. - // - // Chỉ áp ở kControlling, nơi ĐANG có một plan để giữ. Ở kPlanning vẫn nhận plan bẩn như cũ: - // PathMonitor sẽ khai hoả ngay khi vào kControlling, nên mọi tình huống tuyến-bị-chắn đi qua đúng - // MỘT đường xử lý thay vì hai. - // - // Hệ quả đẹp: khi robot đã đi qua vật cản, plan thẳng của planner chính hết bị chắn nên được nhận - // lại — robot tự quay về đúng tuyến/NURBS của order, không cần cơ chế nào để "kết thúc detour". - if (state_machine_.state() == NavigationState::kControlling && !latest_plan_.empty() && - planIsBlocked(result.plan, 0)) - { - robot::log_warning_throttle(5.0, "[move_base2] a fresh plan runs into an obstacle; keeping the " - "current plan.\n"); - planner_feedback_ = PlannerFeedback::kFailed; - return; - } latest_plan_.swap(result.plan); - ++plan_revision_; // Tuyến THAM CHIẾU của chặng = plan do PLANNER sinh, không phải plan đã bị recovery thay // (contract 2026-08-05e). Detour nối lại vào nó nên robot tự quay về tuyến order thay vì trôi // dần theo từng đường vòng, và `max_deviation` đo đúng hành lang mà fleet đã duyệt. @@ -756,528 +625,6 @@ void ControlLoop::collectPlannerResult() planner_feedback_ = PlannerFeedback::kPlanReady; } -void ControlLoop::resetPathMonitor() -{ - path_blocked_ = false; - off_path_ = false; - has_last_path_check_ = false; - blocked_seen_ = false; - off_path_seen_ = false; - collision_brake_ = false; - collision_blocked_ = false; - collision_streak_ = 0; - resetProgressMonitor(); -} - -void ControlLoop::resetProgressMonitor() -{ - progress_head_ = 0; - progress_count_ = 0; - progress_cmd_accum_ = 0.0; - progress_stall_seen_ = false; - no_progress_ = false; -} - -void ControlLoop::rebuildPlanArcLength() -{ - plan_arclen_.clear(); - plan_arclen_.reserve(latest_plan_.size()); - double s = 0.0; // [m] - for (std::size_t i = 0; i < latest_plan_.size(); ++i) - { - if (i > 0) - { - const double dx = latest_plan_[i].pose.position.x - latest_plan_[i - 1].pose.position.x; - const double dy = latest_plan_[i].pose.position.y - latest_plan_[i - 1].pose.position.y; - s += std::hypot(dx, dy); - } - plan_arclen_.push_back(s); - } - plan_arclen_revision_ = plan_revision_; - // Mẫu trong ring đo trên plan CŨ: s_plan của chúng không so được với plan mới. Xoá ring, GIỮ - // cmd_accum (nó đơn điệu, chỉ dùng qua hiệu số giữa hai mẫu). - progress_head_ = 0; - progress_count_ = 0; - progress_stall_seen_ = false; - no_progress_ = false; -} - -void ControlLoop::updateProgressMonitor(const robot::Time& now, std::size_t from_index, - const robot_geometry_msgs::PoseStamped& robot_pose) -{ - const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor; - - // Mode "recover" cần route oscillation; mode "log" thì không cần gì — chỉ in. - const bool route_ready = cfg.progress_action != "recover" || - !config_.state_machine.recovery_routes.oscillation.empty(); - const bool grace = has_last_plan_applied_ && - (now - last_plan_applied_).toSec() < cfg.grace_after_new_plan; - if (!cfg.progress_enabled || !route_ready || latest_plan_.empty()) - { - resetProgressMonitor(); - return; - } - if (plan_arclen_revision_ != plan_revision_) - { - rebuildPlanArcLength(); - } - - const double dxg = latest_plan_.back().pose.position.x - robot_pose.pose.position.x; - const double dyg = latest_plan_.back().pose.position.y - robot_pose.pose.position.y; - const double d_goal = std::hypot(dxg, dyg); // [m] - const double s_plan = - from_index < plan_arclen_.size() ? plan_arclen_[from_index] : plan_arclen_.back(); // [m] - - // Ghi mẫu TRƯỚC khi xét grace/goal_zone: chuỗi mẫu phải liên tục, chỉ có KẾT LUẬN là bị hoãn. - progress_ring_[progress_head_] = ProgressSample{ now, s_plan, d_goal, progress_cmd_accum_ }; - progress_head_ = (progress_head_ + 1) % kProgressRing; - progress_count_ = std::min(progress_count_ + 1, kProgressRing); - - if (grace || d_goal < cfg.progress_goal_zone) - { - progress_stall_seen_ = false; - no_progress_ = false; - return; - } - - // Mẫu MỚI NHẤT mà đã đủ tuổi `progress_window` — cửa sổ đo sát W nhất, không phải mẫu cũ nhất - // trong ring (có thể già tới 6 s và làm cửa sổ giãn ra). - const ProgressSample* old = nullptr; - for (std::size_t k = 1; k <= progress_count_; ++k) - { - const ProgressSample& sample = - progress_ring_[(progress_head_ + kProgressRing - k) % kProgressRing]; - if ((now - sample.t).toSec() >= cfg.progress_window) - { - old = &sample; - break; - } - } - if (old == nullptr) - { - return; // chưa đủ tuổi cửa sổ: chưa kết luận, giữ nguyên trạng thái - } - - const double cmd = progress_cmd_accum_ - old->cmd; // [m] lệnh đã phát - const double prog = std::max(s_plan - old->s_plan, old->d_goal - d_goal); // [m] tiến được - const double eff = cmd > 1e-6 ? prog / cmd : 0.0; // [-] - - const bool stalled = cmd >= cfg.progress_min_commanded && eff < cfg.progress_min_efficiency; - // Xoá cờ CHỈ khi tiến bộ thật. `cmd < min_commanded` là "chưa đo được" chứ không phải "hết kẹt": - // sim 4/9 mission 3 — robot kẹt 35 s, tốc độ lệnh lượn quanh đúng ngưỡng 0.1 m/s, cờ bật/tắt 5 - // lần cho MỘT đợt kẹt. Kẹt xong chậm lại (hoặc planner hold) vẫn là kẹt cho tới khi đi được. - const bool cleared = cmd >= cfg.progress_min_commanded && eff >= cfg.progress_clear_efficiency; - - if (stalled) - { - if (!progress_stall_seen_) - { - progress_stall_since_ = now; - progress_stall_seen_ = true; - } - if (!no_progress_ && (now - progress_stall_since_).toSec() >= cfg.progress_confirm_time) - { - no_progress_ = true; - // KHÔNG gắn thẻ [debug], KHÔNG cho tắt: đây là chẩn đoán "robot kẹt", in đúng một lần mỗi đợt. - robot::log_warning("[move_base2] PathMonitor: no progress — commanded %.2f m in %.1f s but " - "advanced %.2f m (eff %.2f), %.2f m to goal — %s.\n", - cmd, cfg.progress_window, prog, eff, d_goal, - cfg.progress_action == "recover" ? "escalating to recovery" - : "LOG ONLY (progress_action: log)"); - } - } - else if (cleared) - { - if (no_progress_ && config_.debug_state) - { - robot::log_info("[move_base2][debug] PathMonitor: progress resumed (eff %.2f over %.2f m " - "commanded).\n", eff, cmd); - } - progress_stall_seen_ = false; - no_progress_ = false; - } - // Còn lại — cmd < min_commanded (chờ / lết), hoặc eff trong vùng chết min..clear — giữ nguyên - // trạng thái (hysteresis). Không kết luận ≠ hết kẹt. -} - -bool ControlLoop::planIsBlocked(const std::vector& plan, - std::size_t from_index) const -{ - if (deps_.path_check == nullptr || !(config_.path_monitor.horizon > 0.0) || plan.empty()) - { - return false; - } - - PlanBlockResult result; - if (!deps_.path_check->checkPlan(plan, from_index, config_.path_monitor.horizon, result)) - { - // Không kết luận được (thiếu TF/costmap). "Không biết" KHÔNG được suy thành "bẩn": làm vậy là - // robot dừng mỗi lần TF trễ một nhịp. - return false; - } - - if (result.blocked) - { - last_block_distance_ = result.distance; // [m] chỉ để log; không tham gia quyết định. - } - return result.blocked && result.distance >= config_.path_monitor.min_detour_distance; -} - -void ControlLoop::updatePathMonitor(const robot::Time& now, - const robot_geometry_msgs::PoseStamped& robot_pose, - bool pose_available, bool costmap_stale) -{ - const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor; - - // Cổng vào: chỉ giám sát khi thực sự đang bám một plan của một profile được phép, với dữ liệu còn - // dùng được. Thiếu bất kỳ điều kiện nào thì XOÁ luôn trạng thái debounce — nếu chỉ bỏ qua, chuỗi - // "đúng liên tục" sẽ được nối lại qua một quãng gián đoạn và `confirm_time` mất ý nghĩa. - const bool monitorable = cfg.enabled && deps_.path_check != nullptr && has_active_request_ && - pose_available && !costmap_stale && !latest_plan_.empty() && - state_machine_.state() == NavigationState::kControlling && - cfg.monitors(active_request_.profile); - - if (!monitorable) - { - resetPathMonitor(); - return; - } - - // Route rỗng = KHÔNG có đường xử lý cho trigger đó. Khai hoả trong tình trạng này là biến một cơ - // chế đang tắt thành ABORT tức thì: state machine thấy cờ, gọi escalateToRecovery, route cạn ngay - // từ phần tử đầu, và chặng chết ngay lần đầu thấy vật cản. Giám sát cái mà không ai xử lý được - // thì thà đừng giám sát — để `controller_patience` lo như trước khi có cơ chế này. - // - // Ba nút độc lập cho mỗi phép đo, cố ý: cờ riêng (`path_blocked_enabled`/`off_path_enabled`, - // 2026-08-06 — nói thẳng ý định thay vì đặt ngưỡng về 0), ngưỡng của chính nó, và route. - const bool blocked_route_ready = cfg.path_blocked_enabled && - !config_.state_machine.recovery_routes.path_blocked.empty(); - const bool off_path_route_ready = cfg.off_path_enabled && - !config_.state_machine.recovery_routes.off_path.empty(); - - // Nhịp quét riêng: đọc vài chục ô costmap mỗi control cycle 30 Hz là phí, mà vật cản cũng không - // xuất hiện nhanh hơn chu kỳ cập nhật costmap (6 Hz). - if (has_last_path_check_ && (now - last_path_check_).toSec() < cfg.check_period) - { - return; - } - last_path_check_ = now; - has_last_path_check_ = true; - - const std::size_t from = nearestIndex(latest_plan_, robot_pose); - - // --- Phép đo 1: tuyến phía trước có bị chắn không ------------------------------------------- - const bool blocked_now = blocked_route_ready && planIsBlocked(latest_plan_, from); - if (blocked_now) - { - if (!blocked_seen_) - { - blocked_since_ = now; - blocked_seen_ = true; - } - if (!path_blocked_ && (now - blocked_since_).toSec() >= cfg.confirm_time) - { - path_blocked_ = true; - robot::log_warning("[move_base2] PathMonitor: the path ahead is blocked at %.2f m (horizon " - "%.2f m) — stopping to plan a detour.\n", - last_block_distance_, cfg.horizon); - } - } - else - { - blocked_seen_ = false; - path_blocked_ = false; - } - - // --- Phép đo 2: robot đã lệch khỏi plan bao xa ---------------------------------------------- - // - // Đo so với PLAN ĐANG CHẠY, không phải tuyến gốc của order: sau một lượt detour hợp lệ, plan đang - // chạy CHÍNH LÀ đường vòng và robot nằm trên nó, nên không khai hoả oan. Ràng buộc "lệch bao - // nhiêu so với tuyến fleet" là việc của `max_deviation` bên trong behavior detour. - const bool grace = has_last_plan_applied_ && - (now - last_plan_applied_).toSec() < cfg.grace_after_new_plan; - - if (off_path_route_ready && cfg.max_cross_track > 0.0 && !grace) - { - const double error = crossTrackError(latest_plan_, robot_pose); // [m] - if (error > cfg.max_cross_track) - { - if (!off_path_seen_) - { - off_path_since_ = now; - off_path_seen_ = true; - } - if (!off_path_ && (now - off_path_since_).toSec() >= cfg.confirm_time) - { - off_path_ = true; - robot::log_warning("[move_base2] PathMonitor: the robot is %.2f m off the plan (limit " - "%.2f m) — stopping.\n", error, cfg.max_cross_track); - } - } - else - { - off_path_seen_ = false; - off_path_ = false; - } - } - else - { - off_path_seen_ = false; - off_path_ = false; - } - - // --- Phép đo 4: planner đòi đi mà robot không tiến ------------------------------------------ - updateProgressMonitor(now, from, robot_pose); -} - -namespace -{ -/// @brief Liệt kê các ô baseline "(x, y) (x, y) ..." [m, frame base_link]; "-" khi rỗng. -void describeBaselineCells(const MotionBlockResult& result, char* out, std::size_t size) -{ - std::size_t used = 0; - out[0] = '\0'; - if (result.baseline_listed <= 0) - { - std::snprintf(out, size, "-"); - return; - } - for (int i = 0; i < result.baseline_listed && used + 1 < size; ++i) - { - const int n = std::snprintf(out + used, size - used, "%s(%.2f, %.2f)", i > 0 ? " " : "", - result.baseline_xy[i][0], result.baseline_xy[i][1]); - if (n < 0) - { - break; - } - used += static_cast(n); - } - if (result.baseline_cells > result.baseline_listed && used + 1 < size) - { - std::snprintf(out + used, size - used, " +%d more", result.baseline_cells - result.baseline_listed); - } -} -} // namespace - -void ControlLoop::applyCollisionGuard(const robot_geometry_msgs::PoseStamped& robot_pose, - bool pose_available, robot_geometry_msgs::Twist& candidate) -{ - const ControlLoopConfig::PathMonitorConfig& cfg = config_.path_monitor; - - // Cùng cổng vào với hai phép đo kia, cùng lý do: chỉ đo khi thực sự đang bám plan của một profile - // được phép và có đường xử lý. Không có route thì dừng-mà-không-ai-xử là ABORT trá hình. - const bool armed = cfg.enabled && cfg.collision_enabled && deps_.path_check != nullptr && - !config_.state_machine.recovery_routes.collision.empty() && - has_active_request_ && pose_available && - state_machine_.state() == NavigationState::kControlling && - cfg.monitors(active_request_.profile); - if (!armed) - { - collision_brake_ = false; - collision_blocked_ = false; - collision_streak_ = 0; - return; - } - - // Thân robot: khai tay đủ ba số, hoặc cả ba = 0 thì lấy từ footprint costmap mỗi cycle (rẻ: một - // vector 4 điểm). Không có cả hai nguồn thì đây là "không kết luận được" — không dừng, không xoá - // chuỗi xác nhận — nhưng phải kêu, vì guard đang mù mà cấu hình bảo là bật. - double front = cfg.collision_front_offset; - double rear = cfg.collision_rear_offset; - double side = cfg.collision_side_offset; - const bool body_from_costmap = !(front > 0.0) && !(rear > 0.0) && !(side > 0.0); - if (body_from_costmap) - { - if (!deps_.path_check->robotBodyExtents(front, rear, side)) - { - robot::log_error_throttle(5.0, - "[move_base2] PathMonitor: collision guard has no body geometry — " - "the costmap footprint is unavailable and collision_*_offset are " - "not set; the commanded arc is NOT checked.\n"); - collision_brake_ = false; - return; - } - if (!collision_body_logged_ || std::fabs(front - collision_body_front_) > 1e-3 || - std::fabs(rear - collision_body_rear_) > 1e-3 || std::fabs(side - collision_body_side_) > 1e-3) - { - collision_body_logged_ = true; - collision_body_front_ = front; - collision_body_rear_ = rear; - collision_body_side_ = side; - robot::log_info("[move_base2] PathMonitor: collision body from the costmap footprint: " - "front=%.3f rear=%.3f side=%.3f m (+%.2f m padding).\n", - front, rear, side, cfg.collision_footprint_padding); - } - } - - MotionCheckParams params; - params.lookahead = cfg.collision_lookahead; - params.max_samples = cfg.collision_max_samples; - params.front_offset = front; - params.rear_offset = rear; - params.side_offset = side; - params.padding = cfg.collision_footprint_padding; - params.cost_threshold = static_cast(cfg.collision_cost_threshold); - params.min_speed = cfg.collision_min_speed; - params.exclude_baseline = cfg.collision_exclude_baseline; - params.lookahead_angle = cfg.collision_lookahead_angle; - - MotionBlockResult result; - if (!deps_.path_check->checkMotion(robot_pose, candidate.linear.x, candidate.angular.z, params, - result)) - { - // Không kết luận được (TF/costmap) — không biết thì không dừng, cũng không xoá chuỗi xác nhận. - collision_brake_ = false; - return; - } - if (result.scanned == 0) - { - // Xoay tại chỗ / v dưới min_speed: cung suy biến, không có bằng chứng mới. - collision_brake_ = false; - return; - } - - if (!result.blocked) - { - collision_brake_ = false; - collision_streak_ = 0; - if (collision_blocked_) - { - collision_blocked_ = false; - robot::log_info("[move_base2] PathMonitor: the commanded arc is clear again.\n"); - } - if (result.baseline_cells > 0 && config_.debug_state) - { - // Người vận hành thấy robot "đang chạm" mà vẫn đi: phải nói rõ vì sao được đi, và ô nào. - char cells[160]; - describeBaselineCells(result, cells, sizeof(cells)); - robot::log_info_throttle(2.0, - "[move_base2][debug] PathMonitor: body overlaps %d LETHAL cell(s) " - "but the commanded arc adds none — letting it move (v=%.2f m/s, " - "omega=%.2f rad/s); cells in base frame: %s\n", - result.baseline_cells, candidate.linear.x, candidate.angular.z, - cells); - } - return; - } - - collision_hit_distance_ = result.distance; - if (result.distance > cfg.collision_stop_distance) - { - // Xa hơn quãng dừng: chưa phải dừng, nhưng không được lao vào ở tốc độ tối đa. Kẹp theo quãng - // còn lại — cùng công thức mọi tầng phanh khác trong stack. - collision_brake_ = false; - collision_streak_ = 0; - if (cfg.collision_brake_decel > 0.0) - { - const double room = result.distance - cfg.collision_stop_distance; - const double cap = std::sqrt(2.0 * cfg.collision_brake_decel * room); - if (std::fabs(candidate.linear.x) > cap) - { - // Kẹp có log (throttle): 4/9 không tách được cap của guard với head_slowdown của planner - // vì cap chạy im lặng. - robot::log_info_throttle(2.0, - "[move_base2] PathMonitor: contact %.2f m along the commanded arc " - "— v capped %.2f -> %.2f m/s.\n", - result.distance, candidate.linear.x, cap); - candidate.linear.x = candidate.linear.x < 0.0 ? -cap : cap; - } - } - return; - } - - // Trong quãng dừng theo MÉT. Nhưng mét dọc cung chưa phải "sắp chạm" (2026-09-04, run 16:26, - // 11 lần nổ trong 15 s khi xoay gần tại chỗ ở góc trụ): cùng 0.15 m cung, đi thẳng 0.36 m/s là - // chạm sau 0.4 s, còn xoay bò v 0.04 ω −0.5 (R 0.08 m) là quay 107° và 3.8 s nữa — PRIEST đã - // thôi xoay sau 30–60° để thẳng hàng với path. Guard mô hình lệnh là cung không đổi nên không - // biết điều đó; thước đo phải là thời gian và góc. Chưa "sắp" thì không dừng, không đếm, không - // giơ cờ — chỉ kẹp v để luôn còn >= stop_time tới chạm; guard soi lại mỗi cycle, PRIEST cứ xoay - // tiếp thì `turn` tụt dần và tới ngưỡng là dừng thật. - const double speed = std::fabs(candidate.linear.x); - const double kappa = speed > 1e-6 ? candidate.angular.z / candidate.linear.x : 0.0; - const double time_to_contact = speed > 1e-6 ? result.distance / speed - : std::numeric_limits::infinity(); - const double turn_to_contact = std::fabs(kappa) * result.distance; - const double creep_cap = - std::max(0.0, result.distance - cfg.collision_footprint_padding) / cfg.collision_stop_time; - // Kẹp còn thấp hơn min_speed là "không cho đi" trá hình: coi là sắp chạm để đường leo thang - // (no_valid_command -> controller_patience) còn chạy, thay vì giữ 0 vô hạn mà không ai biết. - const bool imminent = time_to_contact <= cfg.collision_stop_time || - turn_to_contact <= cfg.collision_stop_angle || - creep_cap < cfg.collision_min_speed; - if (!imminent) - { - collision_brake_ = false; - collision_streak_ = 0; - if (collision_blocked_) - { - collision_blocked_ = false; - robot::log_info("[move_base2] PathMonitor: the commanded arc is clear again.\n"); - } - if (speed > creep_cap) - { - candidate.linear.x = candidate.linear.x < 0.0 ? -creep_cap : creep_cap; - } - if (config_.debug_state) - { - robot::log_info_throttle(1.0, - "[move_base2][debug] PathMonitor: contact %.2f m along the arc but " - "%.1f s and %.2f rad away — turning, not stopping; v capped %.2f -> " - "%.2f m/s (omega %.2f rad/s).\n", - result.distance, time_to_contact, turn_to_contact, speed, - creep_cap, candidate.angular.z); - } - return; - } - - // Sắp chạm thật: lệnh ra bằng 0 NGAY cycle này (trọng tài phát 0 tức thì), rồi đếm xác nhận. - collision_brake_ = true; - ++collision_streak_; - - // (A) Lệnh vừa bị huỷ thì với state machine nó KHÔNG hợp lệ. Trước đây guard ép lệnh về 0 nhưng - // để nguyên `command_valid` của controller: khi trigger path_blocked đã bị khoá (replan thất bại, - // 3/9 t=723 và 4/9 t=225) state machine thấy controller vẫn "ổn", controller_patience không bao - // giờ chạy, robot đứng chết vô hạn không một dòng log. Báo đúng sự thật thì: trigger còn mở -> - // replan như cũ; trigger đã khoá -> controller_patience -> route controlling_failed -> ABORT. - controller_feedback_ = ControllerFeedback::kNoValidCommand; - - if (!collision_blocked_ && collision_streak_ >= cfg.collision_confirm_cycles) - { - collision_blocked_ = true; - robot::log_warning("[move_base2] PathMonitor: the body would hit a real obstacle %.2f m along " - "the commanded arc (v=%.2f m/s, omega=%.2f rad/s, stop=%.2f m; contact in " - "%.1f s / %.2f rad) — stopping to replan (ignoring %d LETHAL cell(s) already " - "under the body).\n", - result.distance, candidate.linear.x, candidate.angular.z, - cfg.collision_stop_distance, time_to_contact, turn_to_contact, - result.baseline_cells); - if (config_.debug_state) - { - // Hình học của cú chạm, frame base_link (x tới, y trái): cạnh nào chạm, ô chạm ở đâu, và - // những ô đã nằm dưới thân bị bỏ qua. Đây là thứ duy nhất cho phép phân biệt "góc thân quét - // tới" với "người bước tới" khi đọc log mà không có costmap. - static const char* const kEdge[4] = { "right", "nose", "left", "tail" }; - char cells[160]; - describeBaselineCells(result, cells, sizeof(cells)); - robot::log_info("[move_base2][debug] PathMonitor: hit at sample %d: %s edge touches cell " - "(%.2f, %.2f) in base frame; baseline %d cell(s): %s\n", - result.sample, - result.hit_edge >= 0 && result.hit_edge < 4 ? kEdge[result.hit_edge] : "?", - result.hit_x, result.hit_y, result.baseline_cells, cells); - } - } - else if (collision_blocked_) - { - // (B) Phanh kéo dài không được im: người đọc log phải thấy robot đang bị GIỮ, vì sao, và ai - // sẽ leo thang. - robot::log_warning_throttle(2.0, - "[move_base2] PathMonitor: still braking (%d cycles, contact %.2f m, " - "controller wants v=%.2f) — reported as no valid command; if the " - "path_blocked trigger is locked, controller_patience escalates.\n", - collision_streak_, result.distance, candidate.linear.x); - } -} - void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt, const robot_geometry_msgs::PoseStamped& robot_pose, bool pose_available, bool costmap_stale) @@ -1327,8 +674,6 @@ void ControlLoop::updateEnvMonitor(const robot::Time& now, double dt, if (monitorable) { - deps_.environment->refresh(); - double front = sampling.body_front; double rear = sampling.body_rear; double side = sampling.body_side; @@ -1523,14 +868,18 @@ bool ControlLoop::step() travelled = std::hypot(dx, dy); } - // Costmap còn hạn không — hỏi ở ĐÂY chứ không ở mục 3.5 như trước: PathMonitor cần nó, mà monitor + // Costmap còn hạn không — hỏi ở ĐÂY chứ không ở mục 3.5 như trước: EnvMonitor cần nó, mà monitor // phải chạy xong trước state machine. Vẫn là một lời gọi mỗi cycle, chỉ đổi vị trí. const bool costmap_stale = config_.require_current_costmap && deps_.costmap_status != nullptr && !deps_.costmap_status->isCurrent(); // --- 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); + // Một snapshot costmap cho CẢ cycle: monitor và controller đọc cùng một lưới (P0b). No-op khi tắt snapshot. + if (deps_.environment != nullptr) + { + deps_.environment->refresh(); + } updateEnvMonitor(now, dt, robot_pose, pose_available, costmap_stale); // --- 2. State machine ----------------------------------------------------------------------- @@ -1551,14 +900,12 @@ bool ControlLoop::step() input.costmap_current = !costmap_stale; 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. - // 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") || - env_verdict_.no_progress; + // Bốn cổng của state machine do EnvMonitor cấp (Test/ENV_MONITOR_PLAN.md): cờ chỉ khác false khi + // verdict tương ứng có `action: recover`. `off_path` không còn nguồn nào (phép đo cũ đã bỏ 6/9/2026). + input.path_blocked = env_verdict_.path_blocked; + input.collision = env_verdict_.collision; + input.off_path = false; + input.no_progress = 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 @@ -1608,7 +955,6 @@ bool ControlLoop::step() has_active_request_ = true; has_pending_request_ = false; latest_plan_.clear(); - ++plan_revision_; order_plan_.clear(); has_outcome_ = false; env_monitor_.onGoalAccepted(now); @@ -1722,7 +1068,6 @@ 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) @@ -1763,8 +1108,7 @@ bool ControlLoop::step() { // Họ recovery sinh lại đường đi: coi kết quả như một plan mới, chờ state machine đẩy xuống. latest_plan_ = tick.path; - ++plan_revision_; - planner_feedback_ = PlannerFeedback::kPlanReady; + planner_feedback_ = PlannerFeedback::kPlanReady; if (config_.debug_plan) { robot::log_info("[move_base2][debug] recovery produced path with %zu pose(s); " @@ -1880,9 +1224,6 @@ bool ControlLoop::step() 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) @@ -1983,15 +1324,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_ || env_brake_) ? VelocitySource::kNone - : output.velocity_source, + arbiter_.arbitrate((costmap_stale || 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". - if (dt > 0.0) - { - progress_cmd_accum_ += std::fabs(arbiter_.lastCommand().linear.x) * dt; // [m] - } // --- 5. Báo kết quả ------------------------------------------------------------------------- if (output.report_outcome) @@ -2048,7 +1382,6 @@ bool ControlLoop::step() { has_active_request_ = false; latest_plan_.clear(); - ++plan_revision_; planner_running_ = false; } cancel_requested_ = false; diff --git a/src/navigation_runtime.cpp b/src/navigation_runtime.cpp index 268c379..31e4939 100644 --- a/src/navigation_runtime.cpp +++ b/src/navigation_runtime.cpp @@ -65,107 +65,6 @@ bool CostmapPosePort::lookupPose(const std::string& frame, } } -bool CostmapPathCheck::checkPlan(const std::vector& plan, - std::size_t from_index, double horizon, - PlanBlockResult& out) const -{ - if (costmap_ == nullptr || !tf_ || plan.empty() || from_index >= plan.size()) - { - return false; - } - - robot_costmap_2d::Costmap2D* grid = costmap_->getCostmap(); - if (grid == nullptr) - { - return false; - } - - PlanarTransform plan_to_grid; - if (!planarTransform(*tf_, plan[from_index].header.frame_id, costmap_->getGlobalFrameID(), - plan_to_grid)) - { - // Không quy đổi được frame thì mọi kết luận đều vô nghĩa. Trả false = "không biết". - return false; - } - - // Cùng giao thức khoá với map-update thread và planner: lượt quét chỉ đọc vài chục ô nên giữ - // mutex trọn lượt là rẻ, còn đọc lưới trong lúc nó đang được ghi thì kết luận không đáng tin. - boost::unique_lock lock(*(grid->getMutex())); - out = move_base2::checkPlan(plan, from_index, horizon, *grid, plan_to_grid); - return true; -} - -bool CostmapPathCheck::checkMotion(const robot_geometry_msgs::PoseStamped& robot_pose, double v, - double omega, const MotionCheckParams& params, - MotionBlockResult& out) const -{ - if (costmap_ == nullptr || !tf_) - { - return false; - } - robot_costmap_2d::Costmap2D* grid = costmap_->getCostmap(); - if (grid == nullptr) - { - return false; - } - - // Pose robot ở frame của cổng pose (thường `map`), lưới ở `odom`: quy đổi cả vị trí lẫn hướng - // rồi tích phân cung ngay trong frame lưới — mỗi mẫu không phải tra TF lần nữa. - PlanarTransform pose_to_grid; - if (!planarTransform(*tf_, robot_pose.header.frame_id, costmap_->getGlobalFrameID(), - pose_to_grid)) - { - return false; - } - double gx = 0.0; - double gy = 0.0; - pose_to_grid.apply(robot_pose.pose.position.x, robot_pose.pose.position.y, gx, gy); - const auto& q = robot_pose.pose.orientation; - const double yaw_pose = std::atan2(2.0 * (q.w * q.z + q.x * q.y), - 1.0 - 2.0 * (q.y * q.y + q.z * q.z)); - const double yaw_grid = yaw_pose + std::atan2(pose_to_grid.sin_yaw, pose_to_grid.cos_yaw); - - boost::unique_lock lock(*(grid->getMutex())); - out = move_base2::checkMotion(gx, gy, yaw_grid, v, omega, params, *grid, &baseline_scratch_); - return true; -} - -bool CostmapPathCheck::robotBodyExtents(double& front, double& rear, double& side) const -{ - if (costmap_ == nullptr) - { - return false; - } - // Footprint KHÔNG đệm: guard có collision_footprint_padding riêng, cộng đệm costmap vào nữa là - // đếm biên hai lần. Đây cũng là hình mà SBPL/PRIEST dùng, nên ba bên cùng một thân. - 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; // suy biến hoặc base_link nằm ngoài thân — không tin được - } - front = max_x; - rear = -min_x; - side = max_abs_y; - return true; -} - // ================================================================================================ // CostmapEnvironment // ================================================================================================ @@ -480,12 +379,10 @@ bool NavigationRuntime::buildCostmaps(const std::shared_ptr& tf // Costmap ĐIỀU KHIỂN (local) là nguồn của guard "không đi mù" — xem doc của CostmapStatusAdapter. costmap_status_.setCostmap(local_costmap_.get()); - // PathMonitor quét tuyến trên chính costmap local — cùng lưới mà detour lập đường vòng trên đó. - 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. + // EnvMonitor đọc costmap local — cùng lưới mà detour lập đường vòng trên đó; TF để quy plan (map) và + // pose về frame lưới. environment_.setCostmap(local_costmap_.get()); + controller_.setSnapshotRefreshedByLoop(true); // ControlLoop làm mới snapshot một lần đầu cycle (P0b) 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 @@ -736,7 +633,6 @@ ControlLoopDeps NavigationRuntime::deps() deps.mission = &mission_; 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 4b970da..ba63c9f 100644 --- a/src/plan_inspector.cpp +++ b/src/plan_inspector.cpp @@ -178,284 +178,4 @@ double crossTrackError(const std::vector& plan return best; } -PlanBlockResult checkPlan(const std::vector& plan, - std::size_t from_index, double horizon, - const robot_costmap_2d::Costmap2D& grid, - const PlanarTransform& plan_to_grid) -{ - PlanBlockResult result; - - if (plan.empty() || from_index >= plan.size() || !(horizon > 0.0)) - { - return result; - } - - double travelled = 0.0; // [m] - - for (std::size_t i = from_index; i < plan.size(); ++i) - { - if (i > from_index) - { - travelled += std::hypot(plan[i].pose.position.x - plan[i - 1].pose.position.x, - plan[i].pose.position.y - plan[i - 1].pose.position.y); - if (travelled > horizon) - { - break; - } - } - - double gx = 0.0; - double gy = 0.0; - plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, gx, gy); - - unsigned int mx = 0; - unsigned int my = 0; - if (!grid.worldToMap(gx, gy, mx, my)) - { - // Ra ngoài cửa sổ lưới: phần còn lại của tuyến cũng nằm ngoài (lưới lăn theo robot), nên - // dừng hẳn thay vì quét tiếp cho tới hết horizon. - break; - } - - ++result.scanned; - - const unsigned char cost = grid.getCost(mx, my); - if (cost == robot_costmap_2d::NO_INFORMATION) - { - continue; - } - if (cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) - { - result.blocked = true; - result.index = i; - result.distance = travelled; - return result; - } - } - - return result; -} - -namespace -{ -/// [m] Quãng đầu cung bị bỏ qua — chỗ robot đang đứng. Xem @ref checkMotion. -constexpr double kSkipOwnFootprintDist = 0.05; - -/// Một điểm dò: ra ngoài lưới hay chưa có thông tin đều là KHÔNG chạm. -bool probeHits(const robot_costmap_2d::Costmap2D& grid, double x, double y, - unsigned char threshold, const std::vector& baseline) -{ - unsigned int mx = 0; - unsigned int my = 0; - if (!grid.worldToMap(x, y, mx, my)) - { - return false; - } - const unsigned char cost = grid.getCost(mx, my); - if (cost == robot_costmap_2d::NO_INFORMATION || cost < threshold) - { - return false; - } - // Ô đã nằm dưới thân tại pose hiện tại: lệnh này không "đưa thêm" nó vào thân. - return baseline.empty() || !std::binary_search(baseline.begin(), baseline.end(), grid.getIndex(mx, my)); -} - -/** - * @brief Gom các ô >= @p threshold đang nằm dưới hình chữ nhật thân đệm tại pose hiện tại. - * - * Duyệt DIỆN TÍCH chứ không phải chu vi: ô nằm sâu trong thân mà chỉ lấy chu vi thì mẫu sau quét - * qua nó và tính oan là "mới". Ô được coi là dưới thân khi TÂM ô nằm trong hình chữ nhật nới thêm - * nửa ô — cùng độ rộng với những gì probe chu vi (bước nửa ô) có thể chạm tới ở s = 0. Kết quả - * được sort để probe tra bằng binary_search. ~600 ô ở lưới 0.05 m; kiểm cost trước khi quy đổi - * hình học nên phần lớn ô thoát sớm. - */ -void collectBaseline(const robot_costmap_2d::Costmap2D& grid, double x, double y, double yaw, - double front, double rear, double side, unsigned char threshold, - std::vector& out, MotionBlockResult& result) -{ - out.clear(); - result.baseline_listed = 0; - const double c = std::cos(yaw); - const double sn = std::sin(yaw); - const double corners_x[4] = { front, front, -rear, -rear }; - const double corners_y[4] = { side, -side, side, -side }; - double min_wx = std::numeric_limits::max(); - double min_wy = std::numeric_limits::max(); - double max_wx = std::numeric_limits::lowest(); - double max_wy = std::numeric_limits::lowest(); - for (int i = 0; i < 4; ++i) - { - const double wx = x + corners_x[i] * c - corners_y[i] * sn; - const double wy = y + corners_x[i] * sn + corners_y[i] * c; - min_wx = std::min(min_wx, wx); - max_wx = std::max(max_wx, wx); - min_wy = std::min(min_wy, wy); - max_wy = std::max(max_wy, wy); - } - int mx0 = 0; - int my0 = 0; - int mx1 = 0; - int my1 = 0; - grid.worldToMapEnforceBounds(min_wx, min_wy, mx0, my0); - grid.worldToMapEnforceBounds(max_wx, max_wy, mx1, my1); - const double slack = 0.5 * grid.getResolution(); - for (int my = my0; my <= my1; ++my) - { - for (int mx = mx0; mx <= mx1; ++mx) - { - const unsigned char cost = grid.getCost(static_cast(mx), static_cast(my)); - if (cost == robot_costmap_2d::NO_INFORMATION || cost < threshold) - { - continue; - } - double wx = 0.0; - double wy = 0.0; - grid.mapToWorld(static_cast(mx), static_cast(my), wx, wy); - const double dx = wx - x; - const double dy = wy - 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; - } - out.push_back(grid.getIndex(static_cast(mx), static_cast(my))); - if (result.baseline_listed < MotionBlockResult::kMaxListedBaseline) - { - result.baseline_xy[result.baseline_listed][0] = bx; - result.baseline_xy[result.baseline_listed][1] = by; - ++result.baseline_listed; - } - } - } - std::sort(out.begin(), out.end()); -} -} // namespace - -MotionBlockResult checkMotion(double x, double y, double yaw, double v, double omega, - const MotionCheckParams& params, - const robot_costmap_2d::Costmap2D& grid, - std::vector* baseline_scratch) -{ - MotionBlockResult result; - if (std::fabs(v) < params.min_speed || !(params.lookahead > 0.0) || params.max_samples < 1) - { - return result; - } - - const double direction = v < 0.0 ? -1.0 : 1.0; - // Độ cong của cung: omega / v. Lùi thì cung lật chiều cùng với v — công thức giữ nguyên dấu. - const double kappa = omega / v; - // Bước dò không được lớn hơn một ô lưới: với bước 0.13 m mũi robot ở mẫu này còn cách tường - // mỏng 1 ô, mẫu sau đã ở BÊN KIA tường — cả hai đều sạch, robot đâm xuyên. max_samples chỉ là - // trần thưa; lưới mịn hơn thì dò dày hơn, tối đa lookahead/resolution mẫu (16 ở 0.8 m / 0.05). - double step = params.lookahead / params.max_samples; - const double resolution = grid.getResolution(); - if (resolution > 0.0 && step > resolution) - { - step = resolution; - } - const int samples = static_cast(std::ceil(params.lookahead / step - 1.0e-9)); - const double front = params.front_offset + params.padding; - const double rear = params.rear_offset + params.padding; - const double side = params.side_offset + params.padding; - const double sin0 = std::sin(yaw); - const double cos0 = std::cos(yaw); - - std::vector local_baseline; - std::vector& baseline = baseline_scratch != nullptr ? *baseline_scratch : local_baseline; - baseline.clear(); - if (params.exclude_baseline) - { - collectBaseline(grid, x, y, yaw, front, rear, side, params.cost_threshold, baseline, result); - } - result.baseline_cells = static_cast(baseline.size()); - - for (int i = 1; i <= samples; ++i) - { - const double walk = std::min(step * i, params.lookahead); // [m] dọc cung, luôn dương - if (walk < kSkipOwnFootprintDist) - { - continue; - } - if (std::fabs(kappa) * walk > params.lookahead_angle) - { - break; // quay quá góc này thì lệnh đã đổi — phần cung còn lại không phải tương lai thật - } - // Vị trí trên cung sau quãng `walk` theo chiều `direction`. - double px = 0.0; - double py = 0.0; - double pyaw = yaw; - const double s = direction * walk; // quãng có dấu - if (std::fabs(kappa) < 1.0e-6) - { - px = x + s * cos0; - py = y + s * sin0; - } - else - { - pyaw = yaw + kappa * s; - px = x + (std::sin(pyaw) - sin0) / kappa; - py = y - (std::cos(pyaw) - cos0) / kappa; - } - ++result.scanned; - - // Dò TOÀN BỘ CHU VI footprint đã đệm tại mẫu này, không phải 5 điểm rời. Năm điểm rời kéo dọc - // cung là năm đường quét, giữa chúng hở tới nửa bề rộng thân: hai trụ cách nhau 0.45 m nằm lọt - // giữa đường quét mũi (ngang 0) và đường quét hông (ngang ±0.53) — không đường nào chạm, robot - // ôm cả hai trụ mới dừng (đo 4/9: near=0.36 m @ +70° = góc trước-trái thân). Bỏ inflation thì - // trụ chỉ còn 2-3 ô, dò điểm rời chắc chắn lọt; "dò vật thật" bắt buộc đi kèm "dò kín thân". - // Chu vi lấy mẫu dày hơn một ô, và bước dọc cung không quá một ô, nên một ô vật cản muốn vào - // trong footprint bắt buộc phải cắt chu vi ở một mẫu nào đó — không còn khe hình học. - const double c = std::cos(pyaw); - const double sn = std::sin(pyaw); - const double spacing = resolution > 0.0 ? 0.5 * resolution : 0.025; - // Bốn đỉnh trong khung thân: x dọc heading, y sang trái. - const double x_min = -rear; - const double x_max = front; - const double y_max = side; // side đã gồm padding; side_offset = 0 -> dải rộng 2*padding - const double y_min = -side; - auto probe_body = [&](double bx, double by) { - const double wx = px + bx * c - by * sn; - const double wy = py + bx * sn + by * c; - if (!probeHits(grid, wx, wy, params.cost_threshold, baseline)) - { - return false; - } - // Ghi ô chạm theo frame robot HIỆN TẠI (không phải thân đã dịch tới mẫu s) để log đọc được. - const double dx = wx - x; - const double dy = wy - y; - result.hit_x = dx * cos0 + dy * sin0; - result.hit_y = -dx * sin0 + dy * cos0; - return true; - }; - auto probe_edge = [&](int edge, 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 / spacing))); - for (int e = 0; e <= n; ++e) - { - const double t = static_cast(e) / n; - if (probe_body(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t)) - { - result.hit_edge = edge; - return true; - } - } - return false; - }; - const bool hit = probe_edge(0, x_min, y_min, x_max, y_min) || // cạnh phải - probe_edge(1, x_max, y_min, x_max, y_max) || // cạnh mũi - probe_edge(2, x_max, y_max, x_min, y_max) || // cạnh trái - probe_edge(3, x_min, y_max, x_min, y_min); // cạnh đuôi - if (hit) - { - result.blocked = true; - result.sample = i; - result.distance = walk; - return result; - } - } - return result; -} - } // namespace move_base2 diff --git a/src/runners/controller_runner.cpp b/src/runners/controller_runner.cpp index 5fb098a..ed52120 100644 --- a/src/runners/controller_runner.cpp +++ b/src/runners/controller_runner.cpp @@ -366,7 +366,12 @@ bool ControllerRunner::setPlan(const std::vectorisSnapshotEnabled()) - costmap_->refreshSnapshot(); + { + if (!snapshot_refreshed_by_loop_) + { + costmap_->refreshSnapshot(); + } + } else costmap_lock = boost::unique_lock( *(costmap_->getCostmap()->getMutex())); @@ -526,7 +531,12 @@ bool ControllerRunner::computeVelocityCommands(robot_geometry_msgs::Twist& cmd) if (costmap_lock_enabled_) { if (costmap_->isSnapshotEnabled()) - costmap_->refreshSnapshot(); + { + if (!snapshot_refreshed_by_loop_) + { + costmap_->refreshSnapshot(); + } + } else costmap_lock = boost::unique_lock( *(costmap_->getCostmap()->getMutex())); @@ -585,7 +595,12 @@ bool ControllerRunner::isGoalReached() if (costmap_lock_enabled_) { if (costmap_->isSnapshotEnabled()) - costmap_->refreshSnapshot(); + { + if (!snapshot_refreshed_by_loop_) + { + costmap_->refreshSnapshot(); + } + } else costmap_lock = boost::unique_lock( *(costmap_->getCostmap()->getMutex())); diff --git a/src/state_machine.cpp b/src/state_machine.cpp index 5876924..c115c69 100644 --- a/src/state_machine.cpp +++ b/src/state_machine.cpp @@ -624,7 +624,7 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in) { last_valid_control_ = in.now; - // Phép đo 4 (PathMonitor): controller vẫn ra lệnh hợp lệ nhưng robot không tiến. + // kStall (EnvMonitor): controller vẫn ra lệnh hợp lệ nhưng robot không đi được đâu. if (in.no_progress) { out.stop_planner = true; diff --git a/test/config_validation_test.cpp b/test/config_validation_test.cpp index a18ca1e..ff92a1f 100644 --- a/test/config_validation_test.cpp +++ b/test/config_validation_test.cpp @@ -55,33 +55,6 @@ TEST(MoveBase2Config, DefaultsAreValid) EXPECT_TRUE(config.validate(error)) << error; } -TEST(MoveBase2Config, RejectsAPartiallyDeclaredCollisionBody) -{ - // Thân guard: cả ba offset = 0 (lấy từ footprint costmap) hoặc cả ba > 0. Khai hai bỏ một là mũi - // dò tâm hoặc hông không dò — config sai, không phải "mặc định". - MoveBase2Config config = minimalValid(); - config.path_monitor.enabled = true; - config.path_monitor.collision_enabled = true; - config.path_monitor.collision_front_offset = 0.58; // [m] - config.path_monitor.collision_rear_offset = 0.58; // [m] - config.path_monitor.collision_side_offset = 0.0; - std::string error; - EXPECT_FALSE(config.validate(error)); - EXPECT_NE(error.find("collision_side_offset"), std::string::npos) << error; -} - -TEST(MoveBase2Config, AcceptsACollisionBodyTakenFromTheCostmapFootprint) -{ - MoveBase2Config config = minimalValid(); - config.path_monitor.enabled = true; - config.path_monitor.collision_enabled = true; - config.path_monitor.collision_front_offset = 0.0; - config.path_monitor.collision_rear_offset = 0.0; - config.path_monitor.collision_side_offset = 0.0; - std::string error; - EXPECT_TRUE(config.validate(error)) << error; -} - TEST(MoveBase2Config, RejectsRecoveryEnabledWithNoBehaviorLoaded) { // Ràng buộc thứ tự khởi tạo: RecoveryRunner không nạp được behavior nào mà diff --git a/test/fake_ports.h b/test/fake_ports.h index b8360b7..e0c3834 100644 --- a/test/fake_ports.h +++ b/test/fake_ports.h @@ -31,7 +31,6 @@ #include #include #include -#include #include #include #include @@ -864,125 +863,6 @@ private: mutable std::size_t query_count_ = 0; }; -/** - * @class FakePathCheckPort - * @brief Cổng kiểm tuyến giả: kịch bản quyết định tuyến sạch hay bẩn, không cần costmap thật. - * - * `available_ = false` mô phỏng "không kết luận được" (thiếu TF/costmap) — bên gọi phải coi đó là - * không biết, KHÔNG được suy thành sạch hay bẩn. - */ -class FakePathCheckPort final : public PathCheckPort -{ -public: - bool checkPlan(const std::vector& plan, - std::size_t from_index, double horizon, PlanBlockResult& out) const override - { - (void)from_index; - (void)horizon; - ++query_count_; - - if (!available_) - { - return false; - } - - out = PlanBlockResult(); - out.blocked = blocked_; - out.distance = distance_; - out.scanned = plan.size(); - return true; - } - - /// @param distance [m] khoảng cách tới vật cản — bên gọi so với `min_detour_distance`. - void setBlocked(bool blocked, double distance = 1.5) - { - blocked_ = blocked; - distance_ = distance; - } - - /// Phép đo 3 (cung lệnh): kịch bản riêng, không dính `setBlocked` của phép đo 1. - bool checkMotion(const robot_geometry_msgs::PoseStamped& robot_pose, double v, double omega, - const MotionCheckParams& params, MotionBlockResult& out) const override - { - (void)robot_pose; - (void)omega; - (void)params; - ++motion_query_count_; - if (!motion_available_) - { - return false; - } - out = MotionBlockResult(); - out.scanned = std::fabs(v) >= params.min_speed ? 1 : 0; - out.blocked = out.scanned > 0 && motion_blocked_; - out.sample = out.blocked ? 1 : -1; - out.distance = out.blocked ? motion_distance_ : 0.0; - return true; - } - - /// @param distance [m] quãng dọc cung tới điểm chạm — bên gọi so với `collision_stop_distance`. - void setMotionBlocked(bool blocked, double distance = 0.2) - { - motion_blocked_ = blocked; - motion_distance_ = distance; - } - - 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; - } - - /// @brief Giả lập footprint costmap; mặc định KHÔNG có (như PathCheckPort gốc). - void setBodyExtents(double front, double rear, double side) - { - body_available_ = true; - body_front_ = front; - body_rear_ = rear; - body_side_ = side; - } - - void setMotionAvailable(bool available) - { - motion_available_ = available; - } - - std::size_t motionQueryCount() const - { - return motion_query_count_; - } - - void setAvailable(bool available) - { - available_ = available; - } - - std::size_t queryCount() const - { - return query_count_; - } - -private: - bool blocked_ = false; - bool available_ = true; - double distance_ = 1.5; // [m] - mutable std::size_t query_count_ = 0; - bool motion_blocked_ = false; - bool body_available_ = false; - double body_front_ = 0.0; - double body_rear_ = 0.0; - double body_side_ = 0.0; - bool motion_available_ = true; - double motion_distance_ = 0.2; // [m] - 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. diff --git a/test/plan_inspector_test.cpp b/test/plan_inspector_test.cpp index 23be321..eb47577 100644 --- a/test/plan_inspector_test.cpp +++ b/test/plan_inspector_test.cpp @@ -25,12 +25,10 @@ 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; robot_geometry_msgs::PoseStamped makePose(double x, double y, const std::string& frame = "map") @@ -61,128 +59,6 @@ nav_test_harness::FakeCostmap makeGrid() return nav_test_harness::FakeCostmap::centered(10.0, 0.05); } -TEST(PlanInspectorCheck, CleanPlanIsNotBlocked) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); - const auto plan = linePlan(0.0, 3.0, 0.1); - - const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()); - - EXPECT_FALSE(result.blocked); - EXPECT_GT(result.scanned, 0u); -} - -TEST(PlanInspectorCheck, FreeSpaceValueIsNotBlocked) -{ - // Bẫy của fork này: FREE_SPACE = 60, không phải 0. Đặt tường minh giá trị đó lên tuyến để khoá - // lại bất biến "so sánh phải dùng hằng số có tên". - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setCostAt(1.0, 0.0, robot_costmap_2d::FREE_SPACE)); - - const auto plan = linePlan(0.0, 3.0, 0.1); - const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()); - - EXPECT_FALSE(result.blocked); -} - -TEST(PlanInspectorCheck, LethalCellOnThePlanBlocks) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setLethalAt(1.5, 0.0)); - - const auto plan = linePlan(0.0, 3.0, 0.1); - const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()); - - ASSERT_TRUE(result.blocked); - EXPECT_NEAR(plan[result.index].pose.position.x, 1.5, 0.06); - EXPECT_NEAR(result.distance, 1.5, 0.06); -} - -TEST(PlanInspectorCheck, InscribedInflatedCountsAsBlocked) -{ - // Ngưỡng là INSCRIBED_INFLATED_OBSTACLE chứ không phải LETHAL: ở đó tâm robot đặt vào là footprint - // đã đệm chạm vật cản. - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setCostAt(1.0, 0.0, robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)); - - const auto plan = linePlan(0.0, 3.0, 0.1); - const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()); - - EXPECT_TRUE(result.blocked); -} - -TEST(PlanInspectorCheck, UnknownCellIsNotBlocked) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setCostAt(1.0, 0.0, robot_costmap_2d::NO_INFORMATION)); - - const auto plan = linePlan(0.0, 3.0, 0.1); - const PlanBlockResult result = checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()); - - // Vùng chưa quét mà tính là chắn thì robot dừng ở mọi tuyến đi vào chỗ chưa thấy. - EXPECT_FALSE(result.blocked); -} - -TEST(PlanInspectorCheck, HorizonCutsTheScanShort) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setLethalAt(2.5, 0.0)); - - const auto plan = linePlan(0.0, 3.0, 0.1); - - EXPECT_FALSE(checkPlan(plan, 0, 1.0, *grid.costmap(), PlanarTransform()).blocked); - EXPECT_TRUE(checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()).blocked); -} - -TEST(PlanInspectorCheck, ScanStartsAtFromIndex) -{ - // Vật cản NẰM SAU lưng (phần plan đã đi qua) không được tính. - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setLethalAt(0.5, 0.0)); - - const auto plan = linePlan(0.0, 3.0, 0.1); - - EXPECT_TRUE(checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()).blocked); - EXPECT_FALSE(checkPlan(plan, 15, 3.0, *grid.costmap(), PlanarTransform()).blocked); -} - -TEST(PlanInspectorCheck, OutOfGridStopsTheScanInsteadOfBlocking) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); // ±5 m - const auto plan = linePlan(0.0, 20.0, 0.5); - - const PlanBlockResult result = checkPlan(plan, 0, 20.0, *grid.costmap(), PlanarTransform()); - - EXPECT_FALSE(result.blocked); - EXPECT_LT(result.scanned, plan.size()); // dừng ở rìa lưới, không quét hết -} - -TEST(PlanInspectorCheck, EmptyPlanAndBadArgumentsAreSafe) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); - const auto plan = linePlan(0.0, 3.0, 0.1); - - EXPECT_FALSE(checkPlan({}, 0, 3.0, *grid.costmap(), PlanarTransform()).blocked); - EXPECT_FALSE(checkPlan(plan, 999, 3.0, *grid.costmap(), PlanarTransform()).blocked); - EXPECT_FALSE(checkPlan(plan, 0, 0.0, *grid.costmap(), PlanarTransform()).blocked); -} - -TEST(PlanInspectorCheck, TransformIsAppliedToEveryPose) -{ - // Plan ở "map", lưới ở "odom" lệch (2, 1): vật cản đặt theo toạ độ LƯỚI. - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setLethalAt(-0.5, -1.0)); // = map (1.5, 0.0) sau khi trừ offset - - PlanarTransform to_grid; - to_grid.x = -2.0; - to_grid.y = -1.0; - - const auto plan = linePlan(0.0, 3.0, 0.1); - - EXPECT_TRUE(checkPlan(plan, 0, 3.0, *grid.costmap(), to_grid).blocked); - EXPECT_FALSE(checkPlan(plan, 0, 3.0, *grid.costmap(), PlanarTransform()).blocked); -} - TEST(PlanInspectorNearest, ProjectsOntoSegmentsNotVertices) { const auto plan = linePlan(0.0, 3.0, 1.0); // pose tại x = 0,1,2,3 @@ -305,263 +181,3 @@ int main(int argc, char** argv) ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } - -// ================================================================================================= -// Phép đo 3: cung lệnh — thân robot có sắp chạm vật cản THẬT không (2026-09-03). -// ================================================================================================= -namespace -{ -using move_base2::checkMotion; -using move_base2::MotionBlockResult; -using move_base2::MotionCheckParams; - -MotionCheckParams bodyParams() -{ - MotionCheckParams p; - p.lookahead = 0.8; - p.max_samples = 6; - p.front_offset = 0.58; - p.rear_offset = 0.58; - p.side_offset = 0.48; - p.padding = 0.05; - p.cost_threshold = robot_costmap_2d::LETHAL_OBSTACLE; - return p; -} - -TEST(MotionCheck, ClearArcIsNotBlocked) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - EXPECT_FALSE(r.blocked); - // Bước dò bị kẹp về một ô lưới (0.05 m) nên 0.8 m là 16 mẫu, không phải max_samples = 6. - EXPECT_EQ(r.scanned, 16); -} - -TEST(MotionCheck, ThinWallBetweenCoarseSamplesIsStillCaught) -{ - // Tường dày đúng MỘT ô tại x=1.30. Với bước thưa 0.8/6 = 0.133 m, mũi (0.63 m trước tâm) ở - // mẫu 5 là 1.297 (chưa tới), mẫu 6 là 1.43 (đã qua) — cả hai sạch, robot đâm xuyên. Kẹp bước - // về một ô lưới thì không mẫu nào nhảy qua được. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double y = -0.6; y <= 0.6; y += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(1.30, y)); - } - MotionCheckParams p = bodyParams(); - p.max_samples = 6; - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, p, *grid.costmap()); - ASSERT_TRUE(r.blocked); - EXPECT_NEAR(r.distance, 1.30 - 0.63, 0.06); -} - -TEST(MotionCheck, LethalAheadOfTheNoseBlocksWithDistance) -{ - // Tường tại x=1.2. Mũi robot vươn 0.58+0.05 = 0.63 m trước tâm, nên tâm chỉ cần đi ~0.57 m là - // mũi chạm — phải báo ở mẫu ~0.53–0.67 m, KHÔNG phải khi tâm tới 1.2 m. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double y = -0.6; y <= 0.6; y += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(1.2, y)); - } - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - ASSERT_TRUE(r.blocked); - EXPECT_GT(r.distance, 0.4); - EXPECT_LT(r.distance, 0.8); -} - -TEST(MotionCheck, InflationOnlyIsNotBlocked) -{ - // Đây là toàn bộ lý do phép đo này tồn tại: ô INSCRIBED (253) là biên cho TÂM robot, đặt lên mũi - // là đếm biên hai lần. Phủ 253 kín đường đi — robot vẫn phải được chạy. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double x = 0.0; x <= 2.0; x += 0.05) - { - for (double y = -0.7; y <= 0.7; y += 0.05) - { - ASSERT_TRUE(grid.setCostAt(x, y, robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)); - } - } - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - EXPECT_FALSE(r.blocked); -} - -TEST(MotionCheck, LethalUnderTheBodyDoesNotBlockParallelMotion) -{ - // Người kề hông trái: hàng ô LETHAL ở y=0.51 (ngoài thân 0.48, trong thân đệm 0.53), dọc x từ - // -0.2 tới 0.3 — đúng ca sim 4/9 làm guard báo 0.05 m mãi. Đi thẳng thì mép trái chỉ quét lại - // đúng những ô đã nằm dưới thân -> không có ô mới -> phải cho đi. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double x = -0.2; x <= 0.3; x += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(x, 0.51)); - } - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - EXPECT_FALSE(r.blocked) << "blocked at " << r.distance << " m"; - EXPECT_GE(r.baseline_cells, 1); -} - -TEST(MotionCheck, LethalUnderTheBodyStillBlocksWhenTheArcAddsNewCells) -{ - // Khối 3 hàng x 9 cột ở hông trái-sau (y=0.51/0.56/0.61, x từ -0.6 tới -0.2). Hàng trong cùng là - // baseline; rẽ phải làm góc trái-sau văng ra ngoài lên hai hàng còn lại -> ô MỚI -> vẫn chặn, và - // ở khoảng cách thật (> mẫu đầu 0.05 m) chứ không phải "0.05 m" máy móc. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double x = -0.6; x <= -0.2; x += 0.05) - { - for (double y = 0.51; y <= 0.62; y += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(x, y)); - } - } - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, -0.1, bodyParams(), *grid.costmap()); - ASSERT_TRUE(r.blocked); - EXPECT_GT(r.distance, 0.05); - EXPECT_LT(r.distance, 0.5); - EXPECT_GE(r.baseline_cells, 1); - // Chi tiết debug: chạm bằng cạnh TRÁI, ô chạm nằm bên trái phía sau tâm, baseline liệt kê ô bên trái. - EXPECT_EQ(r.hit_edge, 2); - EXPECT_GT(r.hit_y, 0.4); - EXPECT_LT(r.hit_x, 0.0); - ASSERT_GE(r.baseline_listed, 1); - EXPECT_GT(r.baseline_xy[0][1], 0.4); -} - -TEST(MotionCheck, LethalAheadOfTheNoseIsUnaffectedByBaseline) -{ - // Có người kề hông (baseline) VÀ tường trước mũi: tường là ô mới, phải chặn y như không có baseline. - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setLethalAt(0.0, 0.51)); - for (double y = -0.6; y <= 0.6; y += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(1.2, y)); - } - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - ASSERT_TRUE(r.blocked); - EXPECT_GT(r.distance, 0.4); - EXPECT_LT(r.distance, 0.8); - EXPECT_GE(r.baseline_cells, 1); -} - -TEST(MotionCheck, LookaheadAngleTruncatesTheArc) -{ - // R = v/omega = 0.1 m: 0.8 m cung là quay 8 rad. Cắt ở 1.0 rad -> chỉ còn 0.1 m cung = 2 mẫu; - // không cắt (pi) -> 0.31 m = 6 mẫu. Không có vật cản: chỉ đo số mẫu. - nav_test_harness::FakeCostmap grid = makeGrid(); - MotionCheckParams p = bodyParams(); - p.lookahead_angle = 1.0; - const MotionBlockResult cut = checkMotion(0.0, 0.0, 0.0, 0.4, 4.0, p, *grid.costmap()); - EXPECT_FALSE(cut.blocked); - EXPECT_EQ(cut.scanned, 2); - p.lookahead_angle = M_PI; - const MotionBlockResult full = checkMotion(0.0, 0.0, 0.0, 0.4, 4.0, p, *grid.costmap()); - EXPECT_FALSE(full.blocked); - EXPECT_GE(full.scanned, 6); -} - -TEST(MotionCheck, BaselineDisabledKeepsTheOldVerdict) -{ - // Đường lùi: tắt cờ thì ca "người kề hông + đi thẳng" lại bị chặn ngay mẫu đầu như trước 4/9. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double x = -0.2; x <= 0.3; x += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(x, 0.51)); - } - MotionCheckParams p = bodyParams(); - p.exclude_baseline = false; - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, p, *grid.costmap()); - ASSERT_TRUE(r.blocked); - EXPECT_LE(r.distance, 0.1); - EXPECT_EQ(r.baseline_cells, 0); -} - -TEST(MotionCheck, ArcCurvingAwayFromTheWallIsClear) -{ - // Tường ngay trước mặt tại x=1.0 nhưng lệnh rẽ gắt trái (kappa = 1.5/0.3 = 5 1/m, R=0.2 m): - // cung quay đi trước khi mũi tới tường. Gate quỹ đạo giấy cũng nói vậy — và đó là hành vi ĐÚNG - // của phép đo này: nó đo lệnh thật, không đoán. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double y = -0.3; y <= 0.3; y += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(1.0, y)); - } - MotionCheckParams p = bodyParams(); - p.side_offset = 0.0; // chỉ tâm/mũi/đuôi để test hình học cung, không dính probe hông - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.3, 1.5, p, *grid.costmap()); - EXPECT_FALSE(r.blocked); -} - -TEST(MotionCheck, ThinPillarAtTheFrontCornerIsCaught) -{ - // Trụ mảnh (một ô) tại x=1.0, y=+0.30: nằm giữa đường quét mũi (ngang 0) và đường quét hông - // (ngang 0.53) của bản 5 điểm — bản đó không probe nào chạm, robot ôm trụ bằng góc trước-trái - // (đo 4/9: near=0.36 m @ +70°). Chu vi bắt được ở mẫu mà cạnh mũi đi qua trụ. - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setLethalAt(1.0, 0.30)); - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - ASSERT_TRUE(r.blocked); - // Cạnh mũi ở 0.58 + 0.05 = 0.63 trước tâm -> chạm khi tâm đi được ~0.37 m. - EXPECT_NEAR(r.distance, 1.0 - 0.63, 0.06); -} - -TEST(MotionCheck, PillarBetweenTwoWheelsIsCaughtByTheFrontEdge) -{ - // Hai trụ cách nhau 0.45 m, robot chui giữa: bản 5 điểm để lọt cả hai; chu vi mũi chạm ngay. - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setLethalAt(1.2, 0.225)); - ASSERT_TRUE(grid.setLethalAt(1.2, -0.225)); - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - EXPECT_TRUE(r.blocked); -} - -TEST(MotionCheck, SideProbeCatchesAWallBesideTheArc) -{ - // Tường dọc bên trái tại y=+0.50, robot đi thẳng: chu vi với nửa rộng 0.48 + 0.05 = 0.53 chạm; - // thu side_offset về 0 (dải rộng 2 x padding) thì không. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double x = 0.0; x <= 1.5; x += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(x, 0.50)); - } - MotionCheckParams p = bodyParams(); - const MotionBlockResult with_side = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, p, *grid.costmap()); - EXPECT_TRUE(with_side.blocked); - p.side_offset = 0.0; - const MotionBlockResult no_side = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, p, *grid.costmap()); - EXPECT_FALSE(no_side.blocked); -} - -TEST(MotionCheck, StandingStillScansNothing) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); - ASSERT_TRUE(grid.setLethalAt(0.3, 0.0)); - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.0, 0.5, bodyParams(), *grid.costmap()); - EXPECT_FALSE(r.blocked); - EXPECT_EQ(r.scanned, 0); -} - -TEST(MotionCheck, ReverseMotionProbesBehind) -{ - // Tường SAU lưng tại x=-1.2, lệnh lùi: đuôi (0.58+0.05) chạm trước khi tâm tới. - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double y = -0.6; y <= 0.6; y += 0.05) - { - ASSERT_TRUE(grid.setLethalAt(-1.2, y)); - } - const MotionBlockResult fwd = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - EXPECT_FALSE(fwd.blocked); - const MotionBlockResult rev = checkMotion(0.0, 0.0, 0.0, -0.4, 0.0, bodyParams(), *grid.costmap()); - ASSERT_TRUE(rev.blocked); - EXPECT_LT(rev.distance, 0.8); -} - -TEST(MotionCheck, UnknownCellsAreNotBlocked) -{ - nav_test_harness::FakeCostmap grid = makeGrid(); - for (double x = 0.0; x <= 2.0; x += 0.05) - { - ASSERT_TRUE(grid.setCostAt(x, 0.0, robot_costmap_2d::NO_INFORMATION)); - } - const MotionBlockResult r = checkMotion(0.0, 0.0, 0.0, 0.4, 0.0, bodyParams(), *grid.costmap()); - EXPECT_FALSE(r.blocked); -} -} // namespace diff --git a/test/walking_skeleton_test.cpp b/test/walking_skeleton_test.cpp index 61e1df5..cd992fb 100644 --- a/test/walking_skeleton_test.cpp +++ b/test/walking_skeleton_test.cpp @@ -34,7 +34,6 @@ 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; using move_base2::testing::FakeRecoveryPort; @@ -130,7 +129,6 @@ public: deps_.mission = &mission_; deps_.action = &action_; deps_.costmap_status = &costmap_status_; - deps_.path_check = &path_check_; deps_.environment = &environment_; std::string error; @@ -180,7 +178,6 @@ public: FakeMissionPort mission_; FakeActionPort action_; FakeCostmapStatusPort costmap_status_; - FakePathCheckPort path_check_; FakeEnvironmentPort environment_; ControlLoopDeps deps_; @@ -1403,7 +1400,7 @@ TEST(StaleCostmap, NullPortMeansNoGuard) } // ================================================================================================ -// PathMonitor (contract 2026-08-04d) +// Trợ giúp chung cho các ca có mission (submit + kiểm nhận). // ================================================================================================ namespace @@ -1417,359 +1414,8 @@ bool submitOk(Fixture& fixture, const NavigationRequest& request) return accepted; } -/// Config có giám sát tuyến BẬT, ngưỡng ngắn để test không phải tua thời gian dài. -ControlLoopConfig monitorConfig() -{ - ControlLoopConfig config = baseConfig(); - config.state_machine.recovery_routes.planning_failed = { 0 }; - config.state_machine.recovery_routes.controlling_failed = { 0 }; - config.state_machine.recovery_routes.oscillation = { 0 }; - config.state_machine.recovery_routes.path_blocked = { 1 }; - config.state_machine.recovery_routes.off_path = { 1 }; - config.state_machine.recovery_routes.collision = { 1 }; - - config.path_monitor.enabled = true; - config.path_monitor.check_period = 0.0; // quét mỗi cycle: test điều khiển thời gian bằng advance - config.path_monitor.confirm_time = 0.2; // [s] - config.path_monitor.horizon = 3.0; // [m] - config.path_monitor.min_detour_distance = 0.5; // [m] - // Phép đo lệch tuyến TẮT ở config cơ sở: pose giả đứng yên tại gốc còn plan giả nằm ở goal, nên - // cross-track luôn lớn và sẽ át hết mọi ca về "tuyến bị chắn". Ca lệch tuyến có config riêng. - config.path_monitor.max_cross_track = 0.0; // [m] - config.path_monitor.grace_after_new_plan = 0.0; // tắt để test khai hoả được ngay - return config; -} } // namespace -TEST(WalkingSkeletonPathMonitor, BlockedPathStopsTheRobotAfterConfirmTime) -{ - Fixture fixture(monitorConfig()); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - // Recovery chạy dài để test quan sát được trạng thái DỪNG, thay vì thấy nó thoáng qua trong một - // cycle rồi quay lại kControlling. - fixture.recovery_.setScript(std::vector(20, RecoveryScript::kRunning)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); // kPlanning - fixture.stepOnce(); // kControlling - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - fixture.path_check_.setBlocked(true, 1.5); - - // Chưa đủ confirm_time: robot vẫn chạy. - fixture.stepOnce(); - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - for (int i = 0; i < 6; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); - EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.0, 1e-9); -} - -TEST(WalkingSkeletonPathMonitor, PathBlockedCanBeDisabledOnItsOwn) -{ - // Công tắc riêng (2026-08-06): tắt phép đo "tuyến bị chắn" mà không phải đặt `horizon` về 0 — - // ngưỡng giữ nguyên để bật lại chỉ cần đổi một cờ, và đọc config thấy rõ ý định. - ControlLoopConfig config = monitorConfig(); - config.path_monitor.path_blocked_enabled = false; - - Fixture fixture(config); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - fixture.path_check_.setBlocked(true, 1.5); - for (int i = 0; i < 10; ++i) - { - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - } -} - -TEST(WalkingSkeletonPathMonitor, FlickeringObstacleDoesNotStopTheRobot) -{ - // Người đi ngang qua đúng một lượt quét không được làm robot dừng — đó là cả lý do có debounce. - Fixture fixture(monitorConfig()); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - for (int i = 0; i < 8; ++i) - { - fixture.path_check_.setBlocked(i % 2 == 0, 1.5); - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - } -} - -TEST(WalkingSkeletonPathMonitor, ObstacleTooCloseIsLeftToTheControllerPath) -{ - // Vật cản sát nách: detour hầu như không ra nghiệm, và ca đó đã có controller_patience lo. - Fixture fixture(monitorConfig()); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - fixture.path_check_.setBlocked(true, 0.2); // [m] < min_detour_distance - - for (int i = 0; i < 8; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); -} - -TEST(WalkingSkeletonPathMonitor, StaleCostmapSuppressesTheMonitor) -{ - // Costmap quá hạn thì mọi kết luận về vật cản đều là quá khứ — không được khai hoả dựa vào nó. - Fixture fixture(monitorConfig()); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - - fixture.path_check_.setBlocked(true, 1.5); - fixture.costmap_status_.setCurrent(false); - - for (int i = 0; i < 8; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); -} - -TEST(WalkingSkeletonPathMonitor, UnavailableCheckIsTreatedAsUnknown) -{ - // Cổng trả false = "không kết luận được". Không được suy thành bẩn (robot dừng oan mỗi lần TF trễ). - Fixture fixture(monitorConfig()); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - - fixture.path_check_.setBlocked(true, 1.5); - fixture.path_check_.setAvailable(false); - - for (int i = 0; i < 8; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); -} - -TEST(WalkingSkeletonPathMonitor, DockingLegIsNeverMonitored) -{ - // Đườ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 đó. - ControlLoopConfig config = monitorConfig(); - config.docking_requires_marker = false; - Fixture fixture(config); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - - NavigationRequest request = makeRequest(3.0); - request.profile = MotionProfile::kDocking; - ASSERT_TRUE(submitOk(fixture, request)); - - fixture.stepOnce(); - fixture.stepOnce(); - fixture.path_check_.setBlocked(true, 1.5); - - for (int i = 0; i < 8; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); -} - -TEST(WalkingSkeletonPathMonitor, DriftingOffThePlanStopsTheRobot) -{ - // Local planner tự né vật cản nhỏ (tầng 0) có thể kéo robot ra xa tuyến mà plan vẫn "sạch" và - // controller vẫn ra lệnh — không trigger nào khác nhìn thấy tình huống này. - ControlLoopConfig config = monitorConfig(); - config.path_monitor.max_cross_track = 0.4; // [m] - Fixture fixture(config); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - fixture.recovery_.setScript(std::vector(20, RecoveryScript::kRunning)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - // Plan giả chỉ có pose goal (3, 0); robot bám sát nó thì cross-track nhỏ. - fixture.pose_.setPosition(3.0, 0.1); - fixture.stepOnce(); - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - // Dạt sang bên quá ngưỡng: sau `confirm_time` thì dừng. - fixture.pose_.setPosition(3.0, 0.9); - for (int i = 0; i < 8; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); - EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.0, 1e-9); -} - -TEST(WalkingSkeletonPathMonitor, OffPathCanBeDisabledOnItsOwn) -{ - // Đối xứng với `PathBlockedCanBeDisabledOnItsOwn`: ngưỡng `max_cross_track` vẫn để nguyên 0.4 m, - // chỉ hạ cờ — cấu hình đã đo được giữ lại, bật lại là một dòng. - ControlLoopConfig config = monitorConfig(); - config.path_monitor.max_cross_track = 0.4; // [m] ngưỡng thật, giữ nguyên - config.path_monitor.off_path_enabled = false; - - Fixture fixture(config); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - fixture.pose_.setPosition(3.0, 5.0); // lệch rất xa - for (int i = 0; i < 10; ++i) - { - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - } -} - -TEST(WalkingSkeletonPathMonitor, GracePeriodSuppressesTheOffPathCheck) -{ - // Ngay sau khi đổi plan, pose robot có thể lệch nhất thời so với plan vừa tới (rõ nhất lúc - // preempt/đổi chặng). Đo lệch tuyến lúc đó là khai hoả oan. - ControlLoopConfig config = monitorConfig(); - config.path_monitor.max_cross_track = 0.4; // [m] - config.path_monitor.grace_after_new_plan = 5.0; // [s] dài hơn hẳn kịch bản - Fixture fixture(config); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - fixture.pose_.setPosition(3.0, 5.0); // lệch rất xa - - for (int i = 0; i < 8; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); -} - -TEST(WalkingSkeletonPathMonitor, EmptyRouteDisablesTheMonitorInsteadOfAborting) -{ - // Route rỗng nghĩa là behavior detour không nạp được (hoặc chưa khai). Giám sát mà không có - // đường xử lý sẽ biến một cơ chế đang tắt thành ABORT ngay lần đầu thấy vật cản — đúng lỗi đã - // gặp trên sim 2026-08-05. Đúng: không khai hoả, để controller_patience lo như trước. - ControlLoopConfig config = monitorConfig(); - config.state_machine.recovery_routes.path_blocked.clear(); - config.state_machine.recovery_routes.off_path.clear(); - config.state_machine.recovery_routes.collision.clear(); - Fixture fixture(config); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - fixture.path_check_.setBlocked(true, 1.5); - - for (int i = 0; i < 10; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); - EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0); -} - -TEST(WalkingSkeletonPathMonitor, OffPathRouteEmptyDisablesOnlyThatCheck) -{ - // Hai phép đo độc lập: thiếu route của cái này không được làm câm cái kia. - ControlLoopConfig config = monitorConfig(); - config.path_monitor.max_cross_track = 0.4; // [m] - config.state_machine.recovery_routes.off_path.clear(); - Fixture fixture(config); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - fixture.recovery_.setScript(std::vector(20, RecoveryScript::kRunning)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - - // Lệch rất xa nhưng route off_path rỗng -> không khai hoả. - fixture.pose_.setPosition(3.0, 5.0); - for (int i = 0; i < 6; ++i) - { - fixture.stepOnce(); - } - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - // Còn path_blocked vẫn còn route thì vẫn phải chạy bình thường. - fixture.path_check_.setBlocked(true, 1.5); - for (int i = 0; i < 8; ++i) - { - fixture.stepOnce(); - } - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); -} - -TEST(WalkingSkeletonPathMonitor, BlockedFreshPlanDoesNotReplaceACleanOne) -{ - // Luật "không thay plan sạch bằng plan bẩn": không có nó thì planner mù ghi đè đường vòng mỗi - // nhịp replan nền và robot dừng-detour-chạy-dừng liên tục. - ControlLoopConfig config = monitorConfig(); - config.planner_frequency = 1000.0; // ép replan nền nổ mỗi cycle - Fixture fixture(config); - fixture.planner_.setScript(std::vector(20, PlannerScript::kOk)); - fixture.controller_.setScript(std::vector(40, ControllerScript::kOk)); - ASSERT_TRUE(submitOk(fixture, makeRequest(3.0))); - - fixture.stepOnce(); - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - const std::size_t accepted_before = fixture.controller_.setPlanCount(); - - // Plan mới về đều đặn nhưng đều bị chắn -> controller không được nhận thêm plan nào. - fixture.path_check_.setBlocked(true, 1.5); - for (int i = 0; i < 3; ++i) - { - fixture.stepOnce(); - } - - EXPECT_EQ(fixture.controller_.setPlanCount(), accepted_before); -} - int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); @@ -1777,46 +1423,11 @@ int main(int argc, char** argv) } // ================================================================================================= -// PathMonitor — phép đo 3: thân sắp chạm vật cản thật trên cung lệnh (2026-09-03). +// EnvMonitor kContact — phanh theo quỹ đạo thật, cờ collision, leo thang khi route khoá (P4, 2026-09-05). +// PathMonitor cũ (4 phép đo, PathCheckPort) đã xoá 6/9/2026 — xem Test/ENV_MONITOR_PLAN.md §4.19. // ================================================================================================= namespace { -ControlLoopConfig collisionConfig() -{ - ControlLoopConfig config = monitorConfig(); - // Chỉ phép đo 3 sống: hai phép đo cũ tắt để chứng minh nó tự giơ được cờ path_blocked một mình. - config.path_monitor.path_blocked_enabled = false; - config.path_monitor.off_path_enabled = false; - config.path_monitor.collision_enabled = true; - config.path_monitor.collision_lookahead = 0.8; // [m] - config.path_monitor.collision_stop_distance = 0.35; // [m] - config.path_monitor.collision_confirm_cycles = 2; - config.path_monitor.collision_front_offset = 0.58; // [m] - config.path_monitor.collision_rear_offset = 0.58; // [m] - config.path_monitor.collision_side_offset = 0.48; // [m] - config.path_monitor.collision_footprint_padding = 0.1; // [m] - config.path_monitor.collision_brake_decel = 0.0; - return config; -} - -/// @brief Chỉ Phép đo 4 sống. Cửa sổ/confirm rút ngắn để test chạy vài chục cycle. -ControlLoopConfig progressConfig(const std::string& action = "recover") -{ - ControlLoopConfig config = monitorConfig(); - config.path_monitor.path_blocked_enabled = false; - config.path_monitor.off_path_enabled = false; - config.path_monitor.collision_enabled = false; - config.path_monitor.progress_enabled = true; - config.path_monitor.progress_action = action; - config.path_monitor.progress_window = 1.0; // [s] = 20 cycle - config.path_monitor.progress_min_commanded = 0.05; // [m] - config.path_monitor.progress_min_efficiency = 0.30; - config.path_monitor.progress_clear_efficiency = 0.60; - config.path_monitor.progress_confirm_time = 0.3; // [s] = 6 cycle - config.path_monitor.progress_goal_zone = 0.6; // [m] - return config; -} - void driveToControlling(Fixture& fixture) { fixture.planner_.setScript({ PlannerScript::kOk }); @@ -1832,70 +1443,17 @@ void driveToControlling(Fixture& fixture) } } // namespace -TEST(WalkingSkeletonCollisionGuard, BrakesImmediatelyThenReplansAfterConfirm) -{ - Fixture fixture(collisionConfig()); - driveToControlling(fixture); - - // Chạm trong quãng dừng: lệnh ra bằng 0 NGAY cycle này — trước cả khi cờ được giơ. - fixture.path_check_.setMotionBlocked(true, 0.2); - 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) << "cycle 1: chưa đủ xác nhận"; - - // Cycle 2 xác nhận -> cờ path_blocked vào state machine ở cycle 3. - fixture.stepOnce(); - fixture.stepOnce(); - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); - EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision); - EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0); -} - -TEST(WalkingSkeletonCollisionGuard, HeldByTheGuardAfterTheRouteIsSpentEscalatesToControllingFailed) -{ - // Run 1 sim 2026-09-04: detour không ra nghiệm (start nằm trong vành 253), route path_blocked cạn, - // guard giữ lệnh 0 nhưng vẫn báo command_valid -> controller_patience không chạy -> robot đứng - // chết 20 s không một dòng log. Chuỗi bắt buộc: cạn route -> mute -> guard báo no_valid_command - // -> controller_patience -> controlling_failed. Guard giữ 0 suốt chuỗi. - Fixture fixture(collisionConfig()); - driveToControlling(fixture); - fixture.recovery_.setScript({ RecoveryScript::kFailed }); - - fixture.path_check_.setMotionBlocked(true, 0.2); - for (int i = 0; i < 3; ++i) - { - fixture.stepOnce(); // phanh, xác nhận, giơ cờ - } - ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering); - ASSERT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision); - - // Behavior tick ở cycle sau khi start, kết quả vào state machine ở cycle sau nữa. - 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 path_blocked đã cạn"; - - bool escalated = false; - for (int i = 0; i < 40 && !escalated; ++i) // controller_patience 0.5 s = 10 cycle, dư địa rộng - { - fixture.stepOnce(); - ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i; - escalated = fixture.loop_.state() == NavigationState::kRecovering && - fixture.recovery_.lastTrigger() == RecoveryTrigger::kControllingFailed; - } - 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 + ControlLoopConfig config = baseConfig(); + config.state_machine.recovery_routes.planning_failed = { 0 }; + config.state_machine.recovery_routes.controlling_failed = { 0 }; + config.state_machine.recovery_routes.oscillation = { 0 }; + config.state_machine.recovery_routes.path_blocked = { 1 }; + config.state_machine.recovery_routes.collision = { 1 }; config.env_monitor.enabled = true; config.env_monitor.stall.action = "log"; config.env_monitor.unreachable.action = "log"; @@ -2003,201 +1561,6 @@ TEST(WalkingSkeletonEnvContact, ContactBeyondTheStoppingDistanceCapsSpeedWithout 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 - // tay; hình thân đúng là việc của costmap, không phải của người chép số vào hai file. - ControlLoopConfig config = collisionConfig(); - config.path_monitor.collision_front_offset = 0.0; - config.path_monitor.collision_rear_offset = 0.0; - config.path_monitor.collision_side_offset = 0.0; - Fixture fixture(config); - fixture.path_check_.setBodyExtents(0.58, 0.58, 0.48); - driveToControlling(fixture); - - fixture.path_check_.setMotionBlocked(true, 0.2); - fixture.stepOnce(); - EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0); - fixture.stepOnce(); - fixture.stepOnce(); - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); - EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision); -} - -TEST(WalkingSkeletonCollisionGuard, NoBodyGeometryIsInconclusiveNotAStop) -{ - // Offset = 0 mà cổng không có footprint: guard KHÔNG biết thân ở đâu thì không dừng, không giơ cờ, - // chỉ kêu lỗi — cùng contract với TF/costmap hỏng. Dừng mù là biến lỗi cấu hình thành robot chết. - ControlLoopConfig config = collisionConfig(); - config.path_monitor.collision_front_offset = 0.0; - config.path_monitor.collision_rear_offset = 0.0; - config.path_monitor.collision_side_offset = 0.0; - Fixture fixture(config); // fake không setBodyExtents - driveToControlling(fixture); - - fixture.path_check_.setMotionBlocked(true, 0.2); - for (int i = 0; i < 10; ++i) - { - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i; - } - EXPECT_EQ(fixture.path_check_.motionQueryCount(), 0u); // chưa có thân thì không dò -} - -TEST(WalkingSkeletonCollisionGuard, SlowTurnFarFromContactIsCappedNotStopped) -{ - // Run 16:26: xoay bò v 0.04 ω −0.5 (R 0.08 m), chạm ở 0.15 m cung = quay 1.9 rad, còn 3.8 s. - // Chưa "sắp" theo thời gian lẫn góc -> không dừng, không recovery, chỉ kẹp v <= (0.15−0.1)/1.0. - Fixture fixture(collisionConfig()); // padding 0.1, stop_time 1.0, stop_angle 0.35 mặc định - driveToControlling(fixture); - fixture.controller_.setNominalSpeed(0.04); - fixture.controller_.setNominalTurnRate(-0.5); - - fixture.path_check_.setMotionBlocked(true, 0.15); - for (int i = 0; i < 10; ++i) - { - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - } - EXPECT_EQ(fixture.recovery_.startCount(), 0u); - EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0); - EXPECT_LE(fixture.loop_.lastCommand().linear.x, 0.05 + 1e-9); - EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, -0.5); // guard không đụng omega -} - -TEST(WalkingSkeletonCollisionGuard, SlowTurnCloseToContactStops) -{ - // Cùng cú xoay nhưng chỉ còn 0.02 m cung = 0.25 rad <= stop_angle -> sắp chạm thật -> dừng. - Fixture fixture(collisionConfig()); - driveToControlling(fixture); - fixture.controller_.setNominalSpeed(0.04); - fixture.controller_.setNominalTurnRate(0.5); - - fixture.path_check_.setMotionBlocked(true, 0.02); - fixture.stepOnce(); - EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0); - fixture.stepOnce(); - fixture.stepOnce(); - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); - EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision); -} - -TEST(WalkingSkeletonCollisionGuard, StraightCreepStillStops) -{ - // Bò thẳng 0.05 m/s, chạm ở 0.15 m: 3 s nữa nhưng góc = 0 -> "sắp" theo góc -> dừng như trước. - Fixture fixture(collisionConfig()); - driveToControlling(fixture); - fixture.controller_.setNominalSpeed(0.05); - - fixture.path_check_.setMotionBlocked(true, 0.15); - fixture.stepOnce(); - EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0); - fixture.stepOnce(); - fixture.stepOnce(); - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); -} - -TEST(WalkingSkeletonCollisionGuard, FastCurvedApproachStillStops) -{ - // Lần nổ 115.1 của run 16:26: v 0.36 ω −0.27, chạm ở 0.20 m = 0.55 s -> sắp theo thời gian. - Fixture fixture(collisionConfig()); - driveToControlling(fixture); - fixture.controller_.setNominalSpeed(0.36); - fixture.controller_.setNominalTurnRate(-0.27); - - fixture.path_check_.setMotionBlocked(true, 0.20); - fixture.stepOnce(); - EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0); - fixture.stepOnce(); - fixture.stepOnce(); - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); -} - -TEST(WalkingSkeletonCollisionGuard, ContactBeyondStopDistanceDoesNotStop) -{ - Fixture fixture(collisionConfig()); - driveToControlling(fixture); - - fixture.path_check_.setMotionBlocked(true, 0.7); // [m] > stop_distance 0.35 - for (int i = 0; i < 10; ++i) - { - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i; - } -} - -TEST(WalkingSkeletonCollisionGuard, CapsSpeedByRemainingDistanceWhenBrakeDecelIsSet) -{ - ControlLoopConfig config = collisionConfig(); - config.path_monitor.collision_brake_decel = 0.1; // [m/s^2] -> cap sqrt(2*0.1*0.35) = 0.26 m/s - Fixture fixture(config); - driveToControlling(fixture); - const double free_speed = fixture.loop_.lastCommand().linear.x; - - fixture.path_check_.setMotionBlocked(true, 0.7); - for (int i = 0; i < 10; ++i) - { - fixture.stepOnce(); - } - const double cap = std::sqrt(2.0 * 0.1 * (0.7 - 0.35)); - EXPECT_LE(fixture.loop_.lastCommand().linear.x, cap + 1e-9); - EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0); - EXPECT_LT(fixture.loop_.lastCommand().linear.x, free_speed); - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); -} - -TEST(WalkingSkeletonCollisionGuard, OneCycleFlickerBrakesButDoesNotReplan) -{ - // Một nhịp costmap nhấp nháy: lệnh 0 đúng một cycle (an toàn), nhưng không kéo recovery ra. - Fixture fixture(collisionConfig()); - driveToControlling(fixture); - - fixture.path_check_.setMotionBlocked(true, 0.2); - fixture.stepOnce(); - EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0); - fixture.path_check_.setMotionBlocked(false); - for (int i = 0; i < 6; ++i) - { - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - } - EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0); -} - -TEST(WalkingSkeletonCollisionGuard, DisabledFlagLeavesTheCommandAlone) -{ - ControlLoopConfig config = collisionConfig(); - config.path_monitor.collision_enabled = false; - Fixture fixture(config); - driveToControlling(fixture); - - fixture.path_check_.setMotionBlocked(true, 0.2); - for (int i = 0; i < 6; ++i) - { - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i; - } - EXPECT_EQ(fixture.path_check_.motionQueryCount(), 0u); -} - -TEST(WalkingSkeletonCollisionGuard, UnknownVerdictNeitherStopsNorClearsTheStreak) -{ - Fixture fixture(collisionConfig()); - driveToControlling(fixture); - - fixture.path_check_.setMotionAvailable(false); // thiếu TF/costmap: "không biết" - fixture.path_check_.setMotionBlocked(true, 0.2); - for (int i = 0; i < 6; ++i) - { - fixture.stepOnce(); - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "cycle " << i; - ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i; - } -} - // --------------------------------------------------------------------------------------------- // Phép đo 4 — "planner đòi đi mà robot không tiến" // --------------------------------------------------------------------------------------------- @@ -2215,63 +1578,3 @@ void runStalled(Fixture& fixture, int max_cycles) } } // namespace -TEST(WalkingSkeletonProgressMonitor, StalledRobotEscalatesToOscillationRecovery) -{ - Fixture fixture(progressConfig("recover")); - driveToControlling(fixture); - ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0) << "controller phải đang đòi đi"; - - // Cần: 1 mẫu đủ tuổi window (20 cycle) + confirm 6 cycle + 1 cycle để state machine thấy cờ. - runStalled(fixture, 60); - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering); - EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kOscillation); -} - -TEST(WalkingSkeletonProgressMonitor, LogModeNeverEscalates) -{ - Fixture fixture(progressConfig("log")); - driveToControlling(fixture); - - runStalled(fixture, 80); - - // Cùng tình huống kẹt, mode "log" chỉ in cảnh báo: state machine không được thấy cờ. - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); -} - -TEST(WalkingSkeletonProgressMonitor, NearTheGoalIsNotMeasured) -{ - Fixture fixture(progressConfig("recover")); - fixture.planner_.setScript({ PlannerScript::kOk }); - fixture.controller_.setScript(std::vector(400, ControllerScript::kOk)); - fixture.recovery_.setScript(std::vector(20, RecoveryScript::kRunning)); - // Goal cách 0.3 m < progress_goal_zone 0.6 m: dừng chính xác / rot2goal có lệnh nhỏ mà không - // tiến là hợp lệ, không được coi là kẹt. - ASSERT_TRUE(submitOk(fixture, makeRequest(0.3))); - for (int i = 0; i < 8; ++i) - { - fixture.stepOnce(); - } - ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling); - - runStalled(fixture, 80); - - EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling); -} - -TEST(WalkingSkeletonProgressMonitor, ZeroCommandIsWaitingNotStalling) -{ - Fixture fixture(progressConfig("recover")); - driveToControlling(fixture); - - // Controller ngừng ra lệnh (hold chờ người): lệnh sau trọng tài về 0 -> cmd < min_commanded -> - // KHÔNG đo. Phép đo 4 không được nhầm "chờ" với "kẹt". - fixture.controller_.setScript(std::vector(400, ControllerScript::kFail)); - for (int i = 0; i < 60 && fixture.loop_.state() == NavigationState::kControlling; ++i) - { - fixture.stepOnce(); - } - // Có thể rời kControlling vì controller_patience (kFail) — nhưng KHÔNG phải vì kOscillation. - EXPECT_NE(fixture.recovery_.lastTrigger(), RecoveryTrigger::kOscillation); -} -