upload auto relocalization

This commit is contained in:
trung09122002
2026-09-14 16:56:37 +07:00
parent f9a1873753
commit a5f6460fad
19 changed files with 1311 additions and 37 deletions

229
README.md
View File

@@ -21,13 +21,18 @@ sudo apt install -y \
ros-noetic-robot-localization \
ros-noetic-octomap-server ros-noetic-octomap-ros \
ros-noetic-depth-image-proc \
ros-noetic-rtabmap-ros \
python3-serial python3-numpy
```
Để sau (giai đoạn baseline / phần cứng thật):
`localization_ops` có node C++ (`reloc_gicp_node`) link thẳng vào `librtabmap_core`
và PCL. `ros-noetic-rtabmap-ros` kéo theo đủ header ở
`/opt/ros/noetic/include/rtabmap-0.21`.
Để sau (phần cứng thật):
```bash
sudo apt install -y ros-noetic-rtabmap-ros ros-noetic-cartographer-ros ros-noetic-apriltag-ros
sudo apt install -y ros-noetic-cartographer-ros ros-noetic-apriltag-ros
pip3 install evo pyrealsense2
```
@@ -43,6 +48,43 @@ catkin build
source setup_env.sh # KHÔNG phải devel/setup.bash — xem bên dưới
```
Build một package khi sửa cục bộ:
```bash
catkin build localization_ops 2>&1 | tee /tmp/build.log
```
### ⚠️ Đừng tin chữ `succeeded` — kiểm bằng artefact
`catkin build` báo xanh vẫn có thể **không** cài lại thứ bạn vừa sửa — với node
C++ thì `succeeded` không đồng nghĩa binary đã mới. Đã mất nhiều vòng đo vì chạy
nhầm bản cũ mà không ai biết.
Hai loại node hành xử **ngược nhau**, đừng lẫn:
| | cần build lại? | kiểm thế nào |
|---|---|---|
| node C++ | **có**, mỗi lần sửa | binary phải mới hơn nguồn |
| script Python | **không** — `devel` chỉ có stub exec thẳng `src/` | chỉ cần stub tồn tại; grep nội dung thì grep `src/` |
```bash
# binary phải MỚI HƠN nguồn
stat -c '%y %n' src/localization_ops/src/reloc_gicp_node.cpp \
devel/.private/localization_ops/lib/localization_ops/reloc_gicp_node
# Script Python: devel chỉ chứa STUB ~600 byte exec thẳng file trong src/.
# => sửa src/ là có tác dụng NGAY, không cần build.
# Build chỉ cần khi THÊM script mới, để sinh stub. Kiểm stub có chưa:
ls -l devel/lib/localization_ops/reloc_exec.py
# ⚠️ ĐỪNG grep nội dung trên file trong devel/ — đó là stub, luôn không khớp.
# Muốn kiểm nội dung thì grep thẳng src/.
grep -c "warning:" /tmp/build.log # nên ra 0
```
Với C++ thì kiểm ký hiệu thật thay vì đoán:
`nm -DC devel/.../reloc_gicp_node | grep -c IterativeClosestPoint`
### ⚠️ Dùng `setup_env.sh`, không dùng `devel/setup.bash`
SDK camera Hikvision **MVS** (`/opt/MVS`) tự prepend một bản `libusb` **cũ** vào
@@ -86,6 +128,10 @@ bằng hiệu chuẩn UMBmark ở GĐ2** trên robot thật.
Chuyển sang phần cứng thật: thêm `use_sim:=false`. **Mọi thứ từ L2 trở lên không
đổi một dòng nào** — đó là kết quả của nguyên tắc parity sim↔real.
> Bảy lớp này là **bring-up**: robot biết mình ở đâu ngay từ đầu. Trường hợp bị
> bê đi chỗ khác hoặc khởi động không từ dock nằm ở mục
> [Relocalization](#relocalization).
### World mô phỏng
```bash
@@ -120,6 +166,173 @@ roslaunch robot_bringup localization.launch # vận hành, map tĩnh đã duy
Tách hai chế độ loại bỏ phần lớn độ phức tạp: không cần lifelong SLAM, không sợ
false loop closure phá map giữa ca phục vụ. Xem `mapping.launch` để biết lý do.
### Quét map
```bash
# T1 — Gazebo + RTAB-Map ghi vào database
cd ~/projects/vSLAM_ws && source setup_env.sh
roslaunch robot_bringup mapping.launch \
world:=hospital \
database_path:=$HOME/projects/vSLAM_ws/maps/map_hospital.db
# T2 — lái bằng joystick ảo
roslaunch robot_bringup teleop_joystick.launch
```
World có sẵn: `restaurant`, `hotel_corridor`, `house`, `hospital`,
`hospital_two_floors`, `hospital_three_floors`, `cliff_test`.
Quét xong: **Ctrl-C ở T1**. RTAB-Map tự ghi và tối ưu đồ thị lúc thoát — giết
bằng `kill -9` là mất `opt_poses`.
Tuỳ chọn hay dùng:
| arg | mặc định | dùng khi |
|---|---|---|
| `visual_loop` | `false` | bật loop closure bằng túi từ. Trên D410 (IR, không RGB) **đo được 0/43 loop closure qua nổi** — xem phần Relocalization |
| `continue_map` | `false` | quét tiếp vào database đã có |
| `rtabmap_gui` | `false` | mở `rtabmap_viz`; nên `rviz:=false` kèm theo cho đỡ tốn CPU |
| `linear_update` | `0.1` | khoảng cách tối thiểu giữa hai node |
⚠️ `Grid/RangeMax` đang là **12.0 m** trong khi LiDAR với tới 40 m — bản đồ
lưới bị cắt ở 12 m. Mở lên 30 m làm 76.6% node đặc thù hơn nhưng **phải quét
lại toàn bộ**, và 4 node tệ nhất không đổi. Đòn bẩy nhỏ, chưa làm.
### Xem map đã quét
```bash
# Tóm tắt: số node, số loop closure, kích thước
rtabmap-info maps/map_hospital.db
# Giao diện đầy đủ: đồ thị, từng node, lưới chiếm dụng, ràng buộc
rtabmap-databaseViewer maps/map_hospital.db
# Xuất mây điểm 3D rồi xem
rtabmap-export --cloud --output maps/hospital_cloud maps/map_hospital.db
pcl_viewer maps/hospital_cloud.pcd
```
Lưới chiếm dụng 2D nằm sẵn trong database ở `Admin.opt_map` (nén zlib, `int8`,
`-1`/`0`/`100`), kèm `opt_map_x_min`, `opt_map_y_min`, `opt_map_resolution`.
Kích thước `rows/cols/type` nằm ở **12 byte cuối** khối nén — RTAB-Map nhét vào
đó trong `compressData()`, không có cột riêng.
⚠️ **`Node.pose` KHÔNG phải pose tối ưu.** Đo trên `map_hospital.db`:
`|opt − Node.pose|` trung vị 0.386 m, p90 5.23 m, 39.4% lệch > 1 m. Muốn pose
đúng thì đọc `Admin.opt_poses` (hoặc `DBDriver::loadOptimizedPoses()` trong C++).
---
## Relocalization
Robot bị bê đi chỗ khác giữa ca, hoặc khởi động không từ dock: phải tự tìm lại
mình ở đâu trên map tĩnh.
### Bốn lớp, bật dần
| arg | làm gì | mặc định |
|---|---|---|
| `enable_global_init` | khớp scan LiDAR với **toàn** lưới chiếm dụng (tương quan FFT + tinh chỉnh). Publish `/initialpose` khi một giả thuyết áp đảo | `false` |
| `enable_active_reloc` | khi nhập nhằng, tính **chuyển động nào tách các giả thuyết nhanh nhất** và nói ra. Không publish `/initialpose` | `false` |
| `enable_gicp` | tinh chỉnh giả thuyết bằng ICP-2D trên mây depth. Không publish `/initialpose` | `false` |
| `enable_reloc_exec` | ⚠️ robot **tự xoay và tự đi** theo đề xuất, lặp đến khi chốt | `false` |
Ba lớp sau chỉ có tác dụng khi `enable_global_init:=true`.
```bash
roslaunch robot_bringup localization.launch \
world:=hospital \
database_path:=$HOME/projects/vSLAM_ws/maps/map_hospital.db \
start_at_origin:=false enable_dock_init:=false \
x:=5.71 y:=-11.46 yaw:=0.0 \
enable_global_init:=true enable_active_reloc:=true
```
### Đo bằng `reloc_hosp.sh`
```bash
./reloc_hosp.sh X Y [YAW] [Icp/MaxTranslation] [Vis/MinInliers] \
[global_init] [active_reloc] [gicp] [reloc_exec]
./reloc_hosp.sh 5.71 -11.46 0.0 0.3 20 true true # đo thủ công
./reloc_hosp.sh 5.71 -11.46 0.0 0.3 20 true true false true # tự lái
```
Script **chép bản đồ sạch trước mỗi lần chạy**. Thiếu bước đó thì
`opt_last_localization` của lần trước làm phép đo vô nghĩa — đã dính hai lần.
Chấm điểm ở terminal khác:
```bash
PYTHONUNBUFFERED=1 rosrun slam_eval check_initpose.py --map-origin 4.0 14.0 0.0
```
In sai số vị trí **và hướng** tại đúng khoảnh khắc publish, kèm **số lần di
chuyển** tới khi chốt. `PYTHONUNBUFFERED=1` bắt buộc — thiếu là log rỗng khi
qua ống dẫn.
⚠️ **Chưa dùng được trên phần cứng thật** — đã đo được một lần chốt sai 22.5 m,
lệch 180°, mà vẫn qua cả hai cổng tỉ lệ. Nâng ngưỡng không cứu được.
⚠️ Để `enable_gicp:=false` — đo ra depth không giúp chọn đúng chỗ.
### ⚠️ `enable_reloc_exec` — robot tự lái khi chưa biết mình ở đâu
Vòng lặp: `SWEEP` (xoay gom scan) → `WAIT` → `ROTATE` → `DRIVE` → lặp.
#### Chạy
```bash
# T1 — KHÔNG mở teleop (xem cảnh báo bên dưới)
pkill -f gzserver; pkill -f gzclient; pkill -f roslaunch; pkill -f rosmaster; sleep 3
cd ~/projects/vSLAM_ws && source setup_env.sh
./reloc_hosp.sh 5.71 -11.46 0.0 0.3 20 true true false true 2>&1 \
| tee /tmp/r_auto.log | grep -v "observation buffer"
# T2 — chấm điểm
cd ~/projects/vSLAM_ws && source setup_env.sh
PYTHONUNBUFFERED=1 rosrun slam_eval check_initpose.py --map-origin 4.0 14.0 0.0 \
2>&1 | tee /tmp/r_t2.log
```
Không phải lái gì. Node tự chạy cho tới khi chốt hoặc chạm trần.
Dòng đầu tiên phải thấy — **không có nó là node chưa chạy**, đừng ngồi chờ robot
nhúc nhích:
```
reloc_exec: BAT | tran 6 vong / 12.0 m | 0.12 m/s
```
Các dòng `reloc_exec:` khác cho biết đang ở pha nào: `vong N - XOAY TAI CHO`,
`THUC HIEN quay ... roi di ...`, `di xong X.XX m`, `DA CHOT POSE`, `DUNG HAN`.
`grep -v "observation buffer"` chỉ lọc màn hình; log đầy đủ vẫn nằm trong file
nhờ `tee` đặt trước.
Các chặn, **không được gỡ**:
- mặc định **TẮT**, phải bật có ý
- bơm `/cmd_vel` chứ **không** phải `/cmd_vel_safe` → vẫn đi qua `safety_monitor`
- **người luôn thắng**: `/cmd_vel` không phải của nó → dừng ngay + tự khoá 5 s
- xoay cho phép khi `OK/NO_CMD/CLIFF_STOP/US_BLOCKED`; tiến chỉ khi `OK/NO_CMD`
- trần cứng **6 vòng / 12 m** cho một lần định vị, hết thì dừng hẳn gọi người
- 0.12 m/s, 0.4 rad/s; dừng ngay khi có `/initialpose`
```bash
rosservice call /reloc_exec/enable "data: false" # dừng khẩn
rostopic echo /reloc/exec_state # SWEEP/WAIT/ROTATE/DRIVE/HALTED
```
⚠️ **Đừng mở teleop khi thử tự lái** — joystick ảo phát `Twist` đều đặn, node sẽ
coi là người đang lái và nhường quyền, robot không bao giờ tự chạy.
⚠️ **Thử trên sim trước.** Tuyệt đối không bật lần đầu trên phần cứng thật.
⚠️ **`cliff_detect` đang báo nhầm 4–8 lần mỗi lần chạy** và chặn pha `DRIVE`.
Pha xoay miễn nhiễm (lệnh xoay thuần không chạm nhánh cliff). Phải sửa cliff
trước khi dùng tự lái trên phần cứng thật.
---
## Đánh giá
@@ -149,7 +362,8 @@ src/
├── robot_safety/ ⚠️ process ĐỘC LẬP: bumper, siêu âm, e-stop
├── perception_3d/ nodelet zero-copy: lọc cloud + bù nghiêng
├── slam_core/ factor graph 2.5D (đang passthrough, GTSAM ở GĐ5)
├── localization_ops/ dock init, phát hiện tầng, đa bản đồ
├── localization_ops/ dock init, relocalization toàn cục + chủ động + tự lái,
│ phát hiện tầng, đa bản đồ
├── slam_eval/ ATE/RPE, repeatability, profile tài nguyên
├── experimental/ ⚠️ CATKIN_IGNORE — vùng cách ly GPL
└── third_party/ .rosinstall + vcstool
@@ -178,10 +392,13 @@ Hình học robot có ở **hai nơi** và phải khớp nhau:
| Đã có | Chưa có |
|---|---|
| ✅ Mô phỏng Gazebo + ground truth | ❌ Factor graph GTSAM (GĐ5) |
| ✅ Odometry + slip detection | ❌ Scan matching, loop closure |
| ✅ Perception 3D (nodelet, bù nghiêng) | ❌ Baseline Cartographer / RTAB-Map |
| ✅ Odometry + slip detection | ❌ Baseline Cartographer (so sánh) |
| ✅ Perception 3D (nodelet, bù nghiêng) | ❌ Hiệu chuẩn thật (allan_variance, UMBmark, extrinsic) |
| ✅ RTAB-Map: quét map + loop closure LiDAR | ❌ Chặn dương tính giả của relocalization |
| ✅ Relocalization toàn cục + định vị chủ động | ❌ `cliff_detect` báo nhầm |
| ✅ Tự lái `reloc_exec` (sim) | ❌ `reloc_exec` trên phần cứng thật |
| ✅ Lớp an toàn | ❌ Phần cứng thật (IMU, barometer, bumper, siêu âm chưa mua) |
| ✅ Bộ đo ATE/repeatability | ❌ Hiệu chuẩn (allan_variance, UMBmark, extrinsic) |
| ✅ Bộ đo ATE/repeatability/relocalization | ❌ ATE chưa chạy lại sau commit 5 |
| ✅ Khung đa tầng | ❌ Xử lý xung đột librealsense |
Lộ trình đầy đủ: [`docs/ROADMAP.md`](docs/ROADMAP.md)

View File

@@ -22,6 +22,8 @@
# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true # bat global_scan_init
# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true true # + dinh vi CHU DONG
# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true true true # + GICP tren depth
# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true true false true # + TU LAI
# ⚠️ Tham so 9 cho robot TU XOAY va TU DI. Thu tren SIM truoc.
#
# Tham so 4 = Icp/MaxTranslation. Noi len de proximity hoi phuc duoc sau va cham.
# Tham so 5 = Vis/MinInliers. Ha xuong de de nhan ra cho hon.
@@ -69,6 +71,7 @@ X="$1"; Y="$2"; YAW="${3:-3.14}"; ICPT="${4:-0.3}"; MININL="${5:-20}"
GLOBAL="${6:-false}"
ACTIVE="${7:-false}"
GICP="${8:-false}"
EXEC="${9:-false}"
[ -f "$SRC" ] || { echo "KHONG THAY ban do goc: $SRC"; exit 1; }
@@ -94,4 +97,5 @@ exec roslaunch robot_bringup localization.launch world:=hospital \
x:="$X" y:="$Y" yaw:="$YAW" icp_max_translation:="$ICPT" \
vis_min_inliers:="$MININL" enable_global_init:="$GLOBAL" \
enable_active_reloc:="$ACTIVE" \
enable_gicp:="$GICP"
enable_gicp:="$GICP" \
enable_reloc_exec:="$EXEC"

View File

@@ -25,6 +25,7 @@ catkin_install_python(PROGRAMS
scripts/dock_init.py
scripts/global_scan_init.py
scripts/reloc_active.py
scripts/reloc_exec.py
scripts/floor_detector.py
scripts/multi_map_manager.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}

View File

@@ -43,6 +43,14 @@
<arg name="enable_gicp" default="false"/>
<arg name="database_path" default=""/>
<!-- ============ TU LAI: xoay + di, lap den khi chot ============
⚠️ Node DUY NHAT tu lai robot khi CHUA biet minh o dau. Mac dinh TAT.
Bom /cmd_vel nen van di qua safety_monitor - cliff/bumper/vat can van
chan duoc. Nguoi cham joystick la no nhuong quyen ngay va tu khoa.
Tran cung 6 vong / 12 m roi dung han goi nguoi.
Chi co tac dung khi enable_global_init:=true va enable_active_reloc:=true. -->
<arg name="enable_reloc_exec" default="false"/>
<rosparam file="$(find localization_ops)/config/floors.yaml" command="load"/>
<node if="$(arg enable_dock_init)"
@@ -73,6 +81,13 @@
<param name="database_path" value="$(arg database_path)"/>
</node>
<node if="$(arg enable_reloc_exec)"
name="reloc_exec" pkg="localization_ops" type="reloc_exec.py"
output="screen">
<param name="enabled" value="true"/>
<env name="PYTHONUNBUFFERED" value="1"/>
</node>
<group if="$(arg enable_multifloor)">
<node name="floor_detector" pkg="localization_ops" type="floor_detector.py"
output="screen"/>

View File

@@ -69,9 +69,11 @@ import threading
import numpy as np
import rospy
import tf2_ros
from geometry_msgs.msg import Pose, PoseArray, PoseWithCovarianceStamped
from geometry_msgs.msg import (Pose, PoseArray, PoseWithCovarianceStamped,
Vector3Stamped)
from nav_msgs.msg import OccupancyGrid, Odometry
from sensor_msgs.msg import LaserScan
from std_msgs.msg import Bool
from std_srvs.srv import Trigger, TriggerResponse
try:
@@ -240,6 +242,58 @@ class GlobalScanInit(object):
# thay doi hanh vi dinh vi, chi cong bo thu dang co.
self.hyp_pub = rospy.Publisher('/reloc/hypotheses', PoseArray,
queue_size=1, latch=True)
# Bao cho reloc_exec biet DANG gom scan -> no xoay dung cua so nay,
# thay vi xoay lech pha roi gom truot.
self.collect_pub = rospy.Publisher('/reloc/collecting', Bool,
queue_size=1, latch=True)
# ---- KET HOP CAMERA + LIDAR ----
# LiDAR truy hoi (270 do, khop tuong quan toan ban do), depth XAC MINH
# (khop hinh hoc 3D that). Depth KHONG phu quyet - no NANG NGUONG.
#
# Da do 2 ca: pose dung -> depth fitness 0.0716; pose sai 22.5 m ->
# 0.1147. Nguong 0.10 nam giua. ⚠️ Moi 2 mau, moi ben 1 - day la tham
# so, chinh lai khi co them du lieu.
#
# ⚠️ MAC DINH TAT - nguong 0.10 da bi BAC BO.
# Lay tu 2 mau (dung 0.0716, sai 0.1147) roi noi thanh cong. Mau thu ba
# lat nguoc: pose SAI 22.4 m duoc depth cham 0.0392, TOT HON ca pose
# DUNG. Ly do co cau truc: reloc_gicp khop may depth voi may ban do
# QUANH CHINH GIA THUYET, nen o hanh lang doi xung trong 3D no khop tot
# that. Xac minh CUC BO khong bat duoc nham lan TOAN CUC.
#
# Giu lai de GHI SO (xem log 'depth khop'), khong de chan. Bat lai chi
# khi co bang chung tu >= 6 diem tha rang mot nguong nao do tach duoc.
self.use_depth_check = rospy.get_param('~use_depth_check', False)
self.depth_wait = rospy.get_param('~depth_wait', 1.5)
self.depth_max_fitness = rospy.get_param('~depth_max_fitness', 0.10)
self.min_ratio_depth_bad = rospy.get_param('~min_ratio_depth_bad', 1.80)
self.depth_chk = None # (stamp, fitness, valid)
# ---- TICH LUY DA VONG ----
# Tren nguong nay thi chot ngay (duong nhanh). Duoi thi phai co bang
# chung qua nhieu vong. 1.60 chon tu du lieu: 7 ca DUNG trai 1.315-1.581,
# 3 ca SAI deu 1.31-1.39 -> vung nguy hiem la DAI HEP quanh nguong, khong
# phai toan mien. Cac ca chac chan (>= 1.60) khong bi lam cham.
self.min_ratio_fast = rospy.get_param('~min_ratio_fast', 1.60)
self.min_cycles = rospy.get_param('~min_cycles', 2)
self.assoc_radius = rospy.get_param('~assoc_radius', 0.8)
self.acc_timeout = rospy.get_param('~acc_timeout', 120.0)
# ⚠️ Chi tinh mot vong vao streak khi robot DA DICH CHUYEN. Ly le cua
# co che nay la "gia thuyet sai do doi xung CUC BO se vo khi doi goc
# nhin" - ly le do CHI dung khi giua hai vong co di chuyen.
# Do o hl3: robot dung yen, global_scan_init tu retry_period quet lai
# cung mot cho 20 lan, streak len 19 - nhung do chi la "bo khop lap lai
# duoc", ma ban sao doi xung 180 do cung lap lai y het nhu vay.
self.acc_min_move = rospy.get_param('~acc_min_move', 0.20) # m
self.acc = [] # [x, y, th, streak, t_last] trong he map
self.acc_odom = None # pose odom->base luc tich luy gan nhat
self.acc_time = 0.0
rospy.Subscriber('/reloc/depth_check', Vector3Stamped,
self.on_depth_check, queue_size=5)
rospy.Subscriber('map', OccupancyGrid, self.on_map, queue_size=1)
rospy.Subscriber('scan', LaserScan, self.on_scan, queue_size=5)
self.srv = rospy.Service('~relocalize', Trigger, self.on_trigger)
@@ -284,6 +338,9 @@ class GlobalScanInit(object):
# ---------------- gom scan ----------------
def on_depth_check(self, m):
self.depth_chk = (m.header.stamp, m.vector.x, m.vector.y > 0.5)
def on_odom(self, msg):
self.omega = msg.twist.twist.angular.z
@@ -339,6 +396,7 @@ class GlobalScanInit(object):
# ---------------- khop ----------------
def finish(self, timed_out):
self.collect_pub.publish(Bool(data=False))
with self.lock:
self.active = False
pts = np.concatenate(self.pts) if self.pts else None
@@ -371,7 +429,12 @@ class GlobalScanInit(object):
# Cong bo TRUOC moi cong kiem: du bi tu choi, tap gia thuyet van co gia
# tri cho lop dinh vi chu dong o tren.
self.publish_hypotheses(hyps)
hyp_stamp = self.publish_hypotheses(hyps)
# ⚠️ Tich luy TRUOC moi cong kiem: vong bi tu choi van la bang chung.
# O diem8 ty le chi 1.13-1.27 suot nhieu vong nen khong vong nao qua
# cong - nhung chung van noi len giai thuyet nao xuat hien lai.
self.accumulate(hyps)
ratio = s1 / max(s2, 1e-6)
# ⚠️ Cong kiem thu hai: doi thu CUNG vi tri, KHAC huong.
@@ -398,6 +461,60 @@ class GlobalScanInit(object):
self.arm_retry()
return
# ---- DAI BIEN: doi bang chung qua NHIEU VONG ----
# Ty le mot lan khop KHONG tach duoc dung/sai: da do 1.315 (dung) va
# 1.31/1.31/1.39 (SAI 22.5 m, lat 180 do) - chong nhau hoan toan.
# Nhung gia thuyet sai sinh ra tu doi xung CUC BO thuong chi manh o mot
# goc nhin; doi cho 0.5 m la doi xung vo va no bien mat. Gia thuyet
# dung thi xuat hien lai o MOI goc nhin.
#
# Nen: tren min_ratio_fast thi chot ngay nhu cu (diem6 1.581,
# hanhlang1 1.536 khong cham); trong dai bien thi phai dung dau LIEN
# TIEP min_cycles vong moi duoc chot. Cong nay chi lam he THAN TRONG
# HON, khong bao gio mo them duong chot moi.
if ratio < self.min_ratio_fast:
streak = self.acc_streak(x, y)
if streak < self.min_cycles:
rospy.logwarn(
'global_scan_init: DAI BIEN - ty le %.2f < %.2f, gia thuyet '
'nay moi dung dau %d/%d vong lien tiep. KHONG publish, cho '
'them bang chung.', ratio, self.min_ratio_fast,
streak, self.min_cycles)
self.arm_retry()
return
rospy.loginfo('global_scan_init: ty le %.2f o dai bien nhung da '
'dung dau %d vong lien tiep - chot.', ratio, streak)
# ---- DEPTH: GHI SO truoc, chan sau ----
# Cho phan quyet cua reloc_gicp cho dung lo gia thuyet nay, roi IN RA
# cap (ty le LiDAR, depth fitness). Day la du lieu de sau nay biet co
# nguong nao tach duoc dung/sai hay khong - hien tai CHUA biet.
if hyp_stamp is not None:
t0 = rospy.Time.now().to_sec()
r = rospy.Rate(20)
while (not rospy.is_shutdown()
and rospy.Time.now().to_sec() - t0 < self.depth_wait
and (self.depth_chk is None
or self.depth_chk[0] != hyp_stamp)):
r.sleep()
chk = self.depth_chk
if chk is not None and chk[0] == hyp_stamp and chk[2]:
# ⚠️ Dong nay la DU LIEU. Gom lai bang gather_reloc_stats.py.
rospy.logwarn('global_scan_init: DOSO ty_le=%.3f depth_khop='
'%.4f', ratio, chk[1])
if self.use_depth_check and chk[1] > self.depth_max_fitness \
and ratio < self.min_ratio_depth_bad:
rospy.logwarn(
'global_scan_init: DEPTH KHONG DONG Y - khop %.4f > '
'%.4f, ma ty le LiDAR chi %.2f < %.2f. KHONG publish.',
chk[1], self.depth_max_fitness, ratio,
self.min_ratio_depth_bad)
self.arm_retry()
return
else:
rospy.logwarn('global_scan_init: DOSO ty_le=%.3f depth_khop='
'khong-co', ratio)
# ⚠️ Cho robot cham lai roi COMPOSE LAI. Xem settle_omega o onInit.
if abs(self.omega) > self.settle_omega:
rospy.loginfo('global_scan_init: dang quay %.1f do/s - cho dung roi '
@@ -620,6 +737,90 @@ class GlobalScanInit(object):
return None
return (bs, bx, by, bth)
# ---------------- tich luy bang chung qua nhieu vong ----------------
def odom_pose(self):
"""Pose odom->base hien tai, (x, y, th). None neu chua co TF."""
try:
tr = self.buf.lookup_transform(self.odom_frame, self.base_frame,
rospy.Time(0), rospy.Duration(0.3))
except Exception:
return None
return (tr.transform.translation.x, tr.transform.translation.y,
yaw_of(tr.transform.rotation))
def accumulate(self, hyps):
"""Ghep tap gia thuyet vong nay voi cac vong truoc, qua odom.
⚠️ Truyen bang ODOM chu khong bang pose toan cuc - dung luc nay pose
toan cuc chua biet. Odom cuc bo dang tin: da do 0.1 do troi tren 1086
do xoay, va moi buoc chi 0.5-1 m nen troi khong dang ke.
"""
now = rospy.Time.now().to_sec()
od = self.odom_pose()
if od is None or not hyps:
return
if self.acc and (now - self.acc_time) > self.acc_timeout:
self.acc = [] # qua cu, bo het
if not self.acc or self.acc_odom is None:
self.acc_odom, self.acc_time = od, now
self.acc = [[hx, hy, hth, 0, now] for hx, hy, hth, _s in hyps]
self.acc[0][3] = 1 # hyps[0] la nguoi thang vong nay
return
# delta odom giua hai vong, trong he base cua vong truoc
px, py, pth = self.acc_odom
dx, dy = od[0] - px, od[1] - py
c, s = math.cos(-pth), math.sin(-pth)
lx, ly = c * dx - s * dy, s * dx + c * dy
dth = math.atan2(math.sin(od[2] - pth), math.cos(od[2] - pth))
# Cung cho dung -> streak KHONG duoc cong. Xem acc_min_move o onInit.
if math.hypot(lx, ly) < self.acc_min_move:
for e in self.acc:
e[4] = now
self.acc_odom, self.acc_time = od, now
return
# truyen tung gia thuyet cu toi bang delta do
for e in self.acc:
ct, st = math.cos(e[2]), math.sin(e[2])
e[0] += ct * lx - st * ly
e[1] += st * lx + ct * ly
e[2] = math.atan2(math.sin(e[2] + dth), math.cos(e[2] + dth))
win = hyps[0]
r2 = self.assoc_radius * self.assoc_radius
for i, (hx, hy, hth, _s) in enumerate(hyps):
best, bd = None, r2
for e in self.acc:
d = (e[0] - hx) ** 2 + (e[1] - hy) ** 2
if d < bd:
best, bd = e, d
if best is None:
self.acc.append([hx, hy, hth, 1 if i == 0 else 0, now])
continue
best[0], best[1], best[2] = hx, hy, hth # bam theo do do moi nhat
best[4] = now
# streak = so vong LIEN TIEP dung dau
best[3] = best[3] + 1 if i == 0 else 0
# bo cac gia thuyet khong xuat hien lai o vong nay
self.acc = [e for e in self.acc if e[4] >= now - 1e-6]
self.acc_odom, self.acc_time = od, now
rospy.loginfo('global_scan_init: tich luy %d gia thuyet, nguoi thang '
'dung dau %d vong lien tiep.',
len(self.acc), self.acc_streak(win[0], win[1]))
def acc_streak(self, x, y):
"""So vong LIEN TIEP ma gia thuyet gan (x, y) nhat da dung dau."""
best, bd = 0, self.assoc_radius * self.assoc_radius
for e in self.acc:
d = (e[0] - x) ** 2 + (e[1] - y) ** 2
if d < bd:
best, bd = e[3], d
return best
def compose(self, tx, ty, th):
"""T_map_odom vua tim duoc, ghep voi odom->base HIEN TAI.
@@ -652,7 +853,8 @@ class GlobalScanInit(object):
if not hyps:
return
msg = PoseArray()
msg.header.stamp = rospy.Time.now()
stamp = rospy.Time.now()
msg.header.stamp = stamp
msg.header.frame_id = self.map_frame
for hx, hy, hth, _score in hyps:
p = Pose()
@@ -665,8 +867,14 @@ class GlobalScanInit(object):
if len(hyps) > 1:
rospy.loginfo('global_scan_init: %d gia thuyet -> /reloc/hypotheses '
'(cach nhau >= %.1f m)', len(hyps), self.reject_radius)
return stamp
def publish(self, x, y, th, ratio):
# Da chot -> bang chung tich luy het nhiem vu. Lan dinh vi sau bat dau
# lai tu dau, khong keo theo lich su cua lan truoc.
self.acc = []
self.acc_odom = None
m = PoseWithCovarianceStamped()
# Dong dau bang moc TF that su da dung, khong phai now():
# noi that ve thoi diem pose nay co gia tri.
@@ -700,6 +908,7 @@ class GlobalScanInit(object):
rospy.loginfo('global_scan_init: bat dau gom scan. '
'XOAY ROBOT TAI CHO %.0f do.',
math.degrees(self.yaw_sweep))
self.collect_pub.publish(Bool(data=True))
return True, 'dang gom scan, xoay robot tai cho'
def on_timer(self, _evt):

View File

@@ -101,6 +101,14 @@ class ActiveReloc(object):
# vi de xuat bua mot chuyen dong vo ich.
self.min_gain = rospy.get_param('~min_gain', 0.05)
# ⚠️ Im lang = KET CUNG khi reloc_exec dang lai. Do o diem4: hai vong
# cuoi node nay noi "can di XA hon 3 m" roi khong publish gi, robot
# dung yen cho den khi cham tran. Khi be tac, van canh bao nhu cu nhung
# PHAI dua ra mot chuyen dong - lay quang XA nhat con an toan - de vong
# lap con chay. Co nguoi lai thi ho doc canh bao; khong co ai thi robot
# it ra con doi duoc goc nhin.
self.explore_when_stuck = rospy.get_param('~explore_when_stuck', True)
self.grid = None
self.pub = rospy.Publisher('/reloc/suggested_motion', PoseStamped,
queue_size=1, latch=True)
@@ -210,9 +218,9 @@ class ActiveReloc(object):
# tha de xuat mot chuyen dong an toan o vai gia thuyet DAU BANG con hon
# im lang bat nguoi van hanh mo. Lop an toan vat ly (safety_monitor +
# costmap) van la chan cuoi.
best, used = None, 0
best, far, used = None, None, 0
for need in range(len(hyps), 0, -1):
best = self.search(hyps[:need])
best, far = self.search(hyps[:need])
if best is not None:
used = need
break
@@ -235,6 +243,14 @@ class ActiveReloc(object):
'day khong giup gi, cac cho nay giong nhau tren ca vung '
'lan can. Can di XA hon %.1f m.',
n_all, 100 * gain, 100 * self.min_gain, max(self.dists))
if not (self.explore_when_stuck and far is not None):
return
g2, t2, d2, s2 = far
self.publish(t2, d2)
rospy.logwarn('reloc_active: THAM DO - %s. Khong hua tach duoc '
'(loi ich %+.0f%%), chi de doi goc nhin. Day la '
'quang XA nhat con an toan.',
self.describe(t2, d2), 100 * g2)
return
self.publish(turn, dist)
@@ -271,11 +287,17 @@ class ActiveReloc(object):
Da do: chon dung 0.5 m (quang ngan nhat) ca ba lan lien tiep.
Tru di muc tach khi DUNG YEN thi moi do duoc chuyen dong dong gop gi.
Tra ve (best, far):
best = loi ich lon nhat
far = di duoc XA nhat (uu tien quang duong, roi moi den loi ich).
Dung khi be tac: xem explore_when_stuck o on_hyps.
"""
if len(hyps) < 2:
return None
return None, None
base = self.separation(hyps, 0.0, 0.0)
best = None
far = None
for turn in self.turns:
for dist in self.dists:
if not all(self.path_clear(hx, hy, hth, turn, dist)
@@ -288,7 +310,10 @@ class ActiveReloc(object):
gain = sep - base
if best is None or gain > best[0]:
best = (gain, turn, dist, sep)
return best
if far is None or dist > far[2] or (dist == far[2]
and gain > far[0]):
far = (gain, turn, dist, sep)
return best, far
@staticmethod
def describe(turn, dist):

View File

@@ -0,0 +1,326 @@
#!/usr/bin/env python3
"""
reloc_exec - Dinh vi lai HOAN TOAN TU DONG: tu xoay, tu di, lap den khi chot.
Vong lap:
SWEEP xoay tai cho trong dung cua so global_scan_init dang gom scan
WAIT cho ket qua: /initialpose -> XONG | de xuat -> di chuyen
ROTATE quay tai cho theo de xuat
DRIVE tien theo de xuat
-> ve IDLE, global_scan_init tu arm lai sau retry_period -> SWEEP tiep
⚠️⚠️ NODE DUY NHAT TU LAI ROBOT KHI CHUA BIET MINH O DAU. Cac chan duoi la CO Y.
1. MAC DINH TAT (~enabled). Phai bat co y.
2. Bom /cmd_vel chu KHONG phai /cmd_vel_safe -> van qua safety_monitor.
Bom thang cmd_vel_safe la VO HIEU HOA lop an toan. Tuyet doi khong.
3. NGUOI LUON THANG: /cmd_vel la khong phai cua minh -> dung + khoa.
4. Quyen theo trang thai an toan - xem ROT_OK / DRIVE_OK ngay duoi.
Da doc safety_monitor_node.cpp:291 - CLIFF_STOP chi zero linear.x, giu
angular.z, va chi kich hoat khi last_cmd_.linear.x > 0. Nen lenh xoay
thuan khong bao gio cham toi cliff - ke ca khi cliff dang bao nham.
⚠️ Khong tin danh sach trang thai la du: bo bat ket (~stall_timeout) chan
theo TIEN DO THAT cua odom, dung duoc ca voi trang thai chua tung biet.
5. Tran cung: ~max_total_dist met cho MOT lan dinh vi (tai nguyen THAT), va
~max_idle_cycles vong lien tiep khong di duoc met nao thi goi nguoi.
~max_cycles chi la chan chong lap vo han. Het thi dung han.
6. Toc do thap, het gio moi pha, dung ngay khi co /initialpose.
⚠️ /reloc/suggested_motion latch=True -> vua ket noi la nhan de xuat CU.
Khong kiem tuoi thi robot chay theo lenh loi thoi ngay luc khoi dong.
⚠️ Bam vong kin bang ODOM, khong phai pose toan cuc - dung luc nay pose toan
cuc chua biet. Odom cuc bo dang tin: da do 0.1 do troi tren 1086 do xoay.
"""
import math
import rospy
from geometry_msgs.msg import PoseStamped, PoseWithCovarianceStamped, Twist
from nav_msgs.msg import Odometry
from std_msgs.msg import Bool, String
from std_srvs.srv import SetBool, SetBoolResponse
# Doc safety_monitor_node.cpp:339 - nhanh scan chi xet khi out.linear.x > 0,
# nen moi trang thai duoi day KHONG anh huong lenh xoay thuan.
# SCAN_SLOW : chi nhan linear.x voi slow_factor_ - VAN DI DUOC, khong phai chan
# SCAN_STOP : linear.x = 0 - chan that
# CLIFF_STOP: linear.x = 0, giu angular.z
ROT_OK = ('OK', 'NO_CMD', 'SCAN_SLOW', 'SCAN_STOP', 'CLIFF_STOP', 'US_BLOCKED')
DRIVE_OK = ('OK', 'NO_CMD', 'SCAN_SLOW')
def yaw_of(q):
return math.atan2(2.0 * (q.w * q.z + q.x * q.y),
1.0 - 2.0 * (q.y * q.y + q.z * q.z))
def wrap(a):
return math.atan2(math.sin(a), math.cos(a))
def clamp(v, lo, hi):
return max(lo, min(hi, v))
class RelocExec(object):
def __init__(self):
self.enabled = rospy.get_param('~enabled', False)
self.max_lin = rospy.get_param('~max_lin', 0.12)
self.max_ang = rospy.get_param('~max_ang', 0.40)
self.sweep_omega = rospy.get_param('~sweep_omega', 0.40)
self.k_lin = rospy.get_param('~k_lin', 0.6)
self.k_ang = rospy.get_param('~k_ang', 1.0)
self.yaw_tol = math.radians(rospy.get_param('~yaw_tol_deg', 2.0))
self.dist_tol = rospy.get_param('~dist_tol', 0.05)
self.max_dist = rospy.get_param('~max_dist', 3.0)
self.max_total_dist = rospy.get_param('~max_total_dist', 12.0)
# ⚠️ Dem VONG la sai don vi. Do o diem4: cham tran 6 vong khi moi di
# 0.90 m / 12 m ngan sach, vi o cho kho moi buoc chi 0.45 m. Tai nguyen
# that la QUANG DUONG (max_total_dist). Vong chi con la chan chong lap.
self.max_cycles = rospy.get_param('~max_cycles', 20)
# Goi nguoi khi N vong LIEN TIEP khong sinh duoc chuyen dong nao - do
# moi la dau hieu be tac that, khac han "moi di duoc it".
self.max_idle_cycles = rospy.get_param('~max_idle_cycles', 3)
self.phase_timeout = rospy.get_param('~phase_timeout', 40.0)
self.wait_result = rospy.get_param('~wait_result', 8.0)
self.max_age = rospy.get_param('~max_age', 5.0)
self.override_hold = rospy.get_param('~override_hold', 5.0)
# ⚠️ Chan theo TIEN DO THAT, khong theo chuoi trang thai. Da liet ke
# thieu SCAN_SLOW mot lan va node bo cuoc oan ca hai lan DRIVE. Do
# odom co nhuc nhich khong thi dung cho moi truong hop, ke ca trang
# thai chua tung biet.
self.stall_timeout = rospy.get_param('~stall_timeout', 6.0)
self.stall_eps = rospy.get_param('~stall_eps', 0.02) # m
self.state = 'IDLE'
self.odom = self.safety = None
self.collecting = False
self.done_stamp = None
self.lock_until = rospy.Time(0)
self.sent = (0.0, 0.0, rospy.Time(0))
self.t0 = rospy.Time.now()
self.start = None
self.turn = self.dist = 0.0
self.cycles = 0
self.idle_cycles = 0 # so vong LIEN TIEP khong di duoc met nao
self.total = 0.0
self.halted = False # da dung han, cho nguoi
self.mark = None # (quang duong, thoi diem) - bat ket
self.last_pos = None # de cong quang duong LIEN TUC khi DRIVE
self.pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
self.state_pub = rospy.Publisher('/reloc/exec_state', String,
queue_size=1, latch=True)
rospy.Subscriber('/odometry/filtered', Odometry, self.on_odom,
queue_size=5)
rospy.Subscriber('/reloc/collecting', Bool, self.on_collect,
queue_size=1)
rospy.Subscriber('/reloc/suggested_motion', PoseStamped, self.on_sug,
queue_size=1)
rospy.Subscriber('/safety/status', String, self.on_safety, queue_size=1)
rospy.Subscriber('/initialpose', PoseWithCovarianceStamped,
self.on_fixed, queue_size=1)
# ⚠️ Nghe chinh /cmd_vel de phat hien NGUOI dang lai.
rospy.Subscriber('/cmd_vel', Twist, self.on_cmd, queue_size=5)
rospy.Service('~enable', SetBool, self.on_enable)
rospy.on_shutdown(self.halt)
rospy.Timer(rospy.Duration(0.05), self.tick)
rospy.logwarn('reloc_exec: %s | tran %.1f m / %d vong ket lien tiep / '
'%d vong | %.2f m/s',
'BAT' if self.enabled else 'TAT (~enabled)',
self.max_total_dist, self.max_idle_cycles,
self.max_cycles, self.max_lin)
# ---------------- dau vao ----------------
def on_odom(self, m):
self.odom = (m.pose.pose.position.x, m.pose.pose.position.y,
yaw_of(m.pose.pose.orientation))
def on_safety(self, m):
self.safety = m.data
if self.state in ('SWEEP', 'ROTATE') and m.data not in ROT_OK:
self.abort('safety = %s (xoay khong duoc phep)' % m.data)
elif self.state == 'DRIVE' and m.data not in DRIVE_OK:
self.abort('safety = %s (tien khong duoc phep)' % m.data)
def on_collect(self, m):
self.collecting = bool(m.data)
if self.collecting and self.enabled and not self.halted \
and self.state == 'IDLE' \
and rospy.Time.now() >= self.lock_until:
self.cycles += 1
self.idle_cycles += 1 # reset ve 0 khi DRIVE di duoc
if self.idle_cycles > self.max_idle_cycles:
self.stop_for_human(
'%d vong lien tiep khong di duoc met nao - be tac that'
% self.max_idle_cycles)
return
if self.cycles > self.max_cycles:
self.stop_for_human('da %d vong ma chua chot (da di %.2f m)'
% (self.max_cycles, self.total))
return
self.start = self.odom
self.go('SWEEP')
rospy.logwarn('reloc_exec: vong %d - XOAY TAI CHO de gom scan',
self.cycles)
elif not self.collecting and self.state == 'SWEEP':
self.halt()
self.go('WAIT')
def on_fixed(self, _m):
self.halt()
self.state = 'IDLE'
self.state_pub.publish(String(data='DONE'))
rospy.logwarn('reloc_exec: DA CHOT POSE sau %d vong, %.2f m. Dung lai.',
self.cycles, self.total)
self.cycles, self.total, self.idle_cycles = 0, 0.0, 0
def on_cmd(self, m):
"""Phan biet lenh cua CHINH MINH voi lenh cua nguoi."""
lin, ang, t = self.sent
if (abs(m.linear.x - lin) < 1e-3 and abs(m.angular.z - ang) < 1e-3
and (rospy.Time.now() - t).to_sec() < 0.3):
return
self.lock_until = rospy.Time.now() + rospy.Duration(self.override_hold)
if self.state != 'IDLE':
self.abort('NGUOI dang lai - nhuong quyen')
def on_enable(self, req):
self.enabled = req.data
self.halted = False
if not req.data:
self.abort('tat qua dich vu')
else:
self.cycles, self.total, self.idle_cycles = 0, 0.0, 0
return SetBoolResponse(True, 'reloc_exec: %s'
% ('BAT' if req.data else 'TAT'))
def on_sug(self, m):
if self.state != 'WAIT' or not self.enabled or self.halted:
return
if (rospy.Time.now() - m.header.stamp).to_sec() > self.max_age:
return # de xuat cu do latch
if m.header.stamp == self.done_stamp:
return
dist = math.hypot(m.pose.position.x, m.pose.position.y)
if dist > self.max_dist:
self.stop_for_human('de xuat %.2f m > tran %.2f m'
% (dist, self.max_dist))
return
if self.total + dist > self.max_total_dist:
self.stop_for_human('vuot tran tong %.1f m' % self.max_total_dist)
return
if self.safety not in ROT_OK:
return
self.turn, self.dist = yaw_of(m.pose.orientation), dist
self.done_stamp = m.header.stamp
self.start = self.odom
self.go('ROTATE')
rospy.logwarn('reloc_exec: THUC HIEN quay %+.0f do roi di %.2f m',
math.degrees(self.turn), dist)
# ---------------- dieu khien ----------------
def go(self, s):
self.state = s
self.t0 = rospy.Time.now()
self.state_pub.publish(String(data=s))
def send(self, lin, ang):
t = Twist()
t.linear.x, t.angular.z = lin, ang
self.sent = (lin, ang, rospy.Time.now())
self.pub.publish(t)
def halt(self):
self.send(0.0, 0.0)
def abort(self, why):
rospy.logwarn('reloc_exec: DUNG - %s', why)
self.halt()
self.state = 'IDLE'
self.state_pub.publish(String(data='IDLE'))
def stop_for_human(self, why):
rospy.logerr('reloc_exec: DUNG HAN - %s. Can nguoi lai. '
'Bat lai: rosservice call /reloc_exec/enable "data: true"',
why)
self.halt()
self.halted = True
self.state = 'IDLE'
self.state_pub.publish(String(data='HALTED'))
def tick(self, _evt):
if self.state == 'IDLE' or self.odom is None:
return
if (rospy.Time.now() - self.t0).to_sec() > self.phase_timeout:
self.abort('het gio pha %s' % self.state)
return
x, y, th = self.odom
sx, sy, sth = self.start
if self.state == 'SWEEP':
self.send(0.0, self.sweep_omega) # xoay thuan -> mien cliff
elif self.state == 'WAIT':
self.halt()
if (rospy.Time.now() - self.t0).to_sec() > self.wait_result:
self.state = 'IDLE' # cho global_scan_init arm lai
self.state_pub.publish(String(data='IDLE'))
elif self.state == 'ROTATE':
err = wrap(sth + self.turn - th)
if abs(err) < self.yaw_tol:
self.halt()
self.start = self.odom
self.mark = None
self.last_pos = self.odom[:2] # dem quang duong LIEN TUC
self.go('DRIVE')
return
w = clamp(self.k_ang * err, -self.max_ang, self.max_ang)
if 0.0 < abs(w) < 0.15:
w = math.copysign(0.15, w) # thang ma sat tinh
self.send(0.0, w)
elif self.state == 'DRIVE':
gone = math.hypot(x - sx, y - sy)
# ⚠️ Cong DAN theo tung tick, khong doi den khi di tron. Da do o
# diem4c: ca 3 chuyen bi CLIFF_STOP cat giua chung nen total ghi
# 0.00 m trong khi robot da di that 1.35 m -> tran 12 m vo hieu.
if self.last_pos is not None:
self.total += math.hypot(x - self.last_pos[0],
y - self.last_pos[1])
self.last_pos = (x, y)
if self.total > self.max_total_dist:
self.stop_for_human('da di %.2f m > tran %.1f m'
% (self.total, self.max_total_dist))
return
# tien do co nhuc nhich khong
if self.mark is None or gone > self.mark[0] + self.stall_eps:
self.mark = (gone, rospy.Time.now())
elif (rospy.Time.now() - self.mark[1]).to_sec() > self.stall_timeout:
self.abort('KET - %.1f s khong nhuc nhich (safety=%s)'
% (self.stall_timeout, self.safety))
return
if self.dist - gone < self.dist_tol:
self.halt()
self.idle_cycles = 0 # co tien do -> khong phai be tac
rospy.logwarn('reloc_exec: di xong %.2f m (tong %.2f m / %.1f m)',
gone, self.total, self.max_total_dist)
self.state = 'IDLE'
self.state_pub.publish(String(data='IDLE'))
return
self.send(clamp(self.k_lin * (self.dist - gone), 0.05,
self.max_lin), 0.0)
if __name__ == '__main__':
rospy.init_node('reloc_exec')
try:
RelocExec()
rospy.spin()
except rospy.ROSInterruptException:
pass

View File

@@ -39,6 +39,7 @@
#include <ros/ros.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <geometry_msgs/Vector3Stamped.h>
#include <sensor_msgs/PointCloud2.h>
#include <tf2_ros/buffer.h>
#include <tf2_ros/transform_listener.h>
@@ -131,6 +132,12 @@ public:
pub_pose_ = nh.advertise<geometry_msgs::PoseWithCovarianceStamped>(
"/reloc/gicp_pose", 1, true);
// Phan quyet cho gia thuyet [0] - nguoi thang cua LiDAR. Publish LUON, ke
// ca khi no truot cong kiem cua node nay: global_scan_init can biet depth
// khop duoc toi muc nao, khong can biet node nay co chot hay khong.
// x = fitness cua gia thuyet [0] y = 1 neu do duoc z = keo bao xa
pub_check_ = nh.advertise<geometry_msgs::Vector3Stamped>(
"/reloc/depth_check", 1);
if (publish_initialpose_)
{
ROS_WARN("reloc_gicp: ~publish_initialpose=true - node NAY se ghi de "
@@ -267,6 +274,7 @@ private:
// ---- tinh chinh tung gia thuyet ----
struct Res { double fit; double x, y, yaw; int idx; };
std::vector<Res> ok;
double fit0 = -1.0, corr0 = -1.0; // rieng cho gia thuyet [0]
const int n = std::min((int)msg->poses.size(), max_hyps_);
for (int i = 0; i < n; ++i)
{
@@ -306,6 +314,16 @@ private:
const Eigen::Matrix4f T = icp.getFinalTransformation();
// ⚠️ Ghi lai gia thuyet [0] TRUOC moi cong kiem. global_scan_init can
// biet depth khop duoc toi muc nao voi NGUOI THANG CUA LIDAR, ke ca khi
// gia thuyet do bi node nay loai.
if (i == 0)
{
fit0 = icp.getFitnessScore(max_corr_dist_);
corr0 = std::sqrt((T(0, 3) - guess(0, 3)) * (T(0, 3) - guess(0, 3)) +
(T(1, 3) - guess(1, 3)) * (T(1, 3) - guess(1, 3)));
}
// Phan lech NGOAI mat phang = phep kiem mien phi. Robot chay tren san,
// may da can bang trong luc; GICP doi day len 30 cm nghia la no khop
// nham tang/vat the khac, khong phai tinh chinh.
@@ -339,6 +357,15 @@ private:
"khop %.4f", i, r.x, r.y, r.yaw * 180.0 / M_PI, corr, r.fit);
}
geometry_msgs::Vector3Stamped chk;
chk.header.stamp = msg->header.stamp; // khop dung lo gia thuyet nay
chk.vector.x = fit0;
chk.vector.y = (fit0 >= 0.0) ? 1.0 : 0.0;
chk.vector.z = corr0;
pub_check_.publish(chk);
ROS_INFO("reloc_gicp: phan quyet cho gt0 - khop %.4f, keo %.3f m",
fit0, corr0);
if (ok.empty())
{
ROS_WARN("reloc_gicp: khong gia thuyet nao qua duoc cong kiem");
@@ -385,7 +412,7 @@ private:
tf2_ros::Buffer tf_buffer_;
tf2_ros::TransformListener tf_listener_;
ros::Subscriber sub_cloud_, sub_hyps_;
ros::Publisher pub_pose_, pub_init_;
ros::Publisher pub_pose_, pub_init_, pub_check_;
sensor_msgs::PointCloud2::ConstPtr last_cloud_;
rtabmap::DBDriver * db_ = 0;

View File

@@ -10,6 +10,7 @@ find_package(catkin REQUIRED COMPONENTS
sensor_msgs
std_msgs
geometry_msgs
nav_msgs
tf2
tf2_ros
pcl_ros

View File

@@ -103,7 +103,27 @@ cliff_detect:
#
# An toan vi level_gate da loai vuc that (z ~ -1m) khoi phep khop, nen khop
# tren toan cua so khong nuot mat chinh cai dang can tim.
# 0.20 ~ 11.3 do - lon hon sai so pitch da do, du chan phep khop bi keo lech.
# ⚠️ RAMP LA THU ROBOT PHUC VU PHAI DI DUOC. Phan biet ramp voi vuc KHONG
# phai bang DO DOC, ma bang TINH LIEN TUC:
# ramp -> mat lien tuc, khop mot duong nghieng cho PHAN DU NHO (MAD thap)
# vuc -> gian doan, diem lech HAN khoi mat khop, du doc bao nhieu
# Nen max_level_residual ben duoi moi la cong phan biet that; cai nay chi de
# chan phep khop vo nghia.
#
# 0.20 cu duoc co theo nhieu pitch +-8.5 do - nguon nhieu do DA BI KHU
# (sua gravity_align 2026-09-14: bien do 11.23 -> 1.32 do), nen tran chat
# nhu vay khong con ly do ton tai.
#
# Da do o sanh thang may hospital: ramp_01 cach 2.84 m lam phep khop doi doc
# >= 0.20 suot 69 khung lien tiep, MAD chi 0.037 (tuc khop RAT tot) -> bi loai
# oan -> robot khong the di xuong ramp.
# 0.30 ~ 16.7 do, doc hon moi ramp xe lan hop chuan (8.3%).
#
# ⚠️ DA THU 0.30 de robot di duoc xuong ramp o sanh thang may - KHONG DAT,
# robot van bi chan. Noi long mot cong AN TOAN ma khong thu duoc gi la danh
# doi sai, nen tra ve 0.20.
# Dong cliff_detect[dbg] gio in `doc_tho` (doc TRUOC khi kep). Do con so do
# tren mot ramp that roi hay chinh lai - dung doan nhu lan truoc.
max_level_slope: 0.20
# ⚠️ Duong khop co THUC SU ta duoc mat san khong? Do bang do lech tuyet doi

View File

@@ -19,6 +19,7 @@
<depend>sensor_msgs</depend>
<depend>std_msgs</depend>
<depend>geometry_msgs</depend>
<depend>nav_msgs</depend>
<depend>tf2</depend>
<depend>tf2_ros</depend>
<depend>pcl_ros</depend>

View File

@@ -84,6 +84,7 @@
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <limits>
#include <string>
#include <vector>
@@ -190,6 +191,33 @@ private:
pnh_.param("max_level_residual", max_level_residual_, 0.05);
// Tat han de A/B test hoac khi chua hieu chuan.
// ⚠️ tz la chieu cao camera doc tu TF, danh dinh co dinh tren robot nay.
// Da do luc robot KET TREN BAC THANG: tz = 0.642 thay vi 0.803, tuc chui
// mui 16 cm - va DUNG luc do bo tu can bang khop lai mat san theo TANG
// DUOI (z0 = -0.138, MAD 0.0005 "rat dep") roi bao KHONG CO VUC.
// Phep khop tu danh lua: no khop tu chinh cac diem quan sat duoc, ma khi
// robot da nhoai qua mep thi thu quan sat duoc CHINH LA tang duoi.
pnh_.param("nominal_tz", nominal_tz_, 0.803);
pnh_.param("max_tz_dev", max_tz_dev_, 0.08);
// ⚠️ FAIL-CLOSED. Truoc day moi nhanh "khong biet" deu publish FALSE roi
// BO QUA frame - tuc im lang, tuc CHO PHEP DI. Da tra gia: robot di thang
// vao bac thang va ket. Cam bien vuc hong theo kieu MO thi nguy hiem hon
// la khong co, vi no tao cam giac an toan gia.
// Doi lai: robot se dung nhieu hon, ke ca dung oan. Do la danh doi dung
// cho mot cam bien vuc.
pnh_.param("fail_safe", fail_safe_, true);
// ⚠️ Phan biet hai loai "khong biet", vi chung khac nhau ve ban chat:
// - tz lech danh dinh: robot dang nghieng/nhoai len vat -> BAO NGUY NGAY
// - khop san truot MOT khung: nhieu nhat thoi -> bo qua
// - khop san truot LIEN TUC qua fail_safe_after giay -> BAO NGUY
// Da tra gia cho ca hai huong: fail-open lam robot di thang vao bac thang
// va ket; fail-closed tho lam robot dung han (74 su kien mot lan chay,
// trong khi cac khung TOT co MAD 0.0007 va doc 0.0006 - hinh hoc dang rat
// chuan sau khi sua gravity_align).
pnh_.param("fail_safe_after", fail_safe_after_, 1.0);
pnh_.param("enabled", enabled_, true);
// In thong ke tung chang moi 2s. Bat khi detector im lang ma khong ro vi sao:
@@ -298,9 +326,7 @@ private:
// Publish False va di tiep, thay vi bao vuc gia.
if (require_accel_ok_ && rp_fresh && !accel_ok_)
{
std_msgs::Bool f; f.data = false; flag_pub_.publish(f);
NODELET_WARN_THROTTLE(5.0, "cliff_detect: accel bi gate (robot dang tang/giam toc) "
"-> pitch khong dang tin, BO QUA frame.");
bail("accel bi gate (robot dang tang/giam toc) -> pitch khong dang tin", false);
return;
}
@@ -326,7 +352,24 @@ private:
// Tia chi co the cham san khi no chuc XUONG trong base_footprint.
// Va camera phai o TREN san.
if (tz <= 0.0)
{
bail("tz <= 0 - hinh hoc vo nghia", true);
return;
}
// ⚠️ Camera lech khoi chieu cao danh dinh => robot dang nghieng/da nhoai
// len vat gi do. Dung luc do phep khop mat san bam theo TANG DUOI va bao
// "khong co vuc". Xem nominal_tz o onInit.
if (std::fabs(tz - nominal_tz_) > max_tz_dev_)
{
char why[160];
snprintf(why, sizeof(why),
"tz %.3f lech %.3f m khoi danh dinh %.3f - robot khong bang "
"phang, khong tin duoc phep khop san",
tz, std::fabs(tz - nominal_tz_), nominal_tz_);
bail(why, true);
return;
}
// ⚠️ KHONG duoc doc thang info->K.
//
@@ -441,7 +484,11 @@ private:
if (r2 - r1 > 0.15) // du duong day de uoc luong doc
{
double sl = (z2 - z1) / (r2 - r1);
lvl_slope_raw_ = sl; // giu doc TRUOC khi kep, de in ra hieu chuan
// Doc vuot tran = dau hieu phep khop hong, KHONG phai san doc that.
// ⚠️ Ramp la san doc THAT va robot phai di duoc - xem max_level_slope
// trong depth_filter.yaml. Cong phan biet ramp/vuc la MAD, khong phai
// do lon cua doc.
if (std::fabs(sl) > max_level_slope_)
{
slope_clamped = true;
@@ -468,12 +515,12 @@ private:
// Khung nhin khong phai mot mat phang san -> khong co goc quy chieu
// dang tin -> KHONG phan xet. Im lang an toan hon bao gia: bao gia se
// chan duong robot giua nha hang va nguoi van hanh se tat han node di.
std_msgs::Bool f; f.data = false; flag_pub_.publish(f);
NODELET_WARN_THROTTLE(5.0,
"cliff_detect: khop mat san KHONG dat (%s, MAD %.3f m > %.3f) -> "
"BO QUA frame.",
slope_clamped ? "doc cham tran" : "phan du lon",
lvl_mad, max_level_residual_);
char why[160];
snprintf(why, sizeof(why),
"khop mat san KHONG dat (%s, MAD %.3f m > %.3f)",
slope_clamped ? "doc cham tran" : "phan du lon",
lvl_mad, max_level_residual_);
bail(why, false);
return;
}
leveled = true;
@@ -482,11 +529,12 @@ private:
{
// Khong du mau -> khong biet san o dau -> KHONG phan xet.
// Im lang con hon bao gia, vi bao gia se chan duong robot giua nha hang.
std_msgs::Bool f; f.data = false; flag_pub_.publish(f);
NODELET_WARN_THROTTLE(5.0,
"cliff_detect: chi %zu mau san hop le trong [%.2f, %.2f] m (can >= %d) -> "
"khong khop duoc mat san, BO QUA frame.",
rz.size(), min_dist_, max_dist_, min_level_samples_);
char why[180];
snprintf(why, sizeof(why),
"chi %zu mau san hop le trong [%.2f, %.2f] m (can >= %d), "
"khong khop duoc mat san",
rz.size(), min_dist_, max_dist_, min_level_samples_);
bail(why, false);
return;
}
}
@@ -617,12 +665,13 @@ private:
"cliff_detect[dbg] anh %dx%d enc=%s | mau %ld: tia-len %ld, z<=0 %ld, "
"ngoai-dai %ld, TRONG-DAI %ld | lo %ld, sut %ld | sau-cum %d | "
"r_floor [%.2f, %.2f] m | z thap nhat %.3f m | "
"san: z0 %.4f doc %.4f MAD %.4f (%s) | "
"san: z0 %.4f doc %.4f (doc_tho %.4f) MAD %.4f (%s) | "
"accel_ok %d | tz %.3f fx %.1f cy %.1f",
W, H, img->encoding.c_str(), n_total, n_up, n_zneg, n_range, n_inwin,
n_hole, n_drop, n_cliff,
(r_min > 1e8 ? 0.0 : r_min), (r_max < -1e8 ? 0.0 : r_max),
(z_lowest > 1e8 ? 0.0 : z_lowest), lvl_z0, lvl_slope, lvl_mad,
(z_lowest > 1e8 ? 0.0 : z_lowest), lvl_z0, lvl_slope, lvl_slope_raw_,
lvl_mad,
leveled ? "khop duoc" : "mac dinh",
accel_ok_ ? 1 : 0, tz, fx, cy);
}
@@ -636,6 +685,9 @@ private:
cloud_pub_.publish(msg_out);
}
// Den day nghia la da phan xet duoc -> chuoi "khong biet" ket thuc.
bail_since_ = ros::Time();
std_msgs::Bool flag;
flag.data = detected;
flag_pub_.publish(flag);
@@ -678,6 +730,49 @@ private:
double level_gate_ = 0.25;
double max_level_slope_ = 0.20;
double max_level_residual_ = 0.05;
double nominal_tz_ = 0.803, max_tz_dev_ = 0.08;
double lvl_slope_raw_ = 0.0; // doc TRUOC khi kep - de hieu chuan max_level_slope
double fail_safe_after_ = 1.0;
bool fail_safe_ = true;
ros::Time bail_since_; // bat dau chuoi khung "khong biet" hien tai
/** "Khong biet san o dau" -> bao gi?
*
* ⚠️ Da tra gia cho CA HAI cuc doan:
* - luon FALSE (im lang): robot di thang vao bac thang va ket. Luc ket
* tz = 0.642 va phep khop bam theo TANG DUOI, MAD 0.0005, bao "khong
* co vuc" - tu danh lua hoan toan.
* - luon TRUE: 74 su kien mot lan chay, robot dung han, khong dinh vi
* duoc - trong khi cac khung TOT co MAD 0.0007 va doc 0.0006.
*
* Nen phan biet theo THOI GIAN:
* immediate = true -> bao nguy ngay (trang thai bat thuong that su:
* robot dang nghieng / nhoai len vat)
* immediate = false -> mot khung xau la nhieu nhat thoi, bo qua; nhung
* mu LIEN TUC qua fail_safe_after giay thi bao nguy. */
void bail(const char* why, bool immediate)
{
const ros::Time now = ros::Time::now();
if (bail_since_.isZero())
bail_since_ = now;
const double held = (now - bail_since_).toSec();
const bool danger =
fail_safe_ && (immediate || held > fail_safe_after_);
std_msgs::Bool f;
f.data = danger;
flag_pub_.publish(f);
if (danger)
NODELET_WARN_THROTTLE(2.0,
"cliff_detect: %s -> BAO NGUY (fail-safe%s).", why,
immediate ? "" : ", mu lien tuc");
else
NODELET_WARN_THROTTLE(5.0,
"cliff_detect: %s -> bo qua frame (mu %.1f/%.1f s).",
why, held, fail_safe_after_);
}
double roll_ = 0.0, pitch_ = 0.0;
bool have_rp_ = false, accel_ok_ = true;

View File

@@ -41,6 +41,7 @@
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_msgs/Float64MultiArray.h>
#include <nav_msgs/Odometry.h>
#include <tf2_ros/buffer.h>
#include <tf2_ros/transform_listener.h>
@@ -141,7 +142,30 @@ private:
cloud_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("cloud_aligned", 5);
rp_pub_ = nh_.advertise<std_msgs::Float64MultiArray>("gravity_align/roll_pitch", 10);
// ⚠️ Gia toc ke KHONG phan biet duoc "nghieng" voi "dang tang toc".
// Da do bang check_gravity_align.py, 7996 mau, so voi ground truth:
// pitch: trung vi -0.07 do (khong lech chuan) nhung BIEN DO 11.23 do
// accel_ok = 0 o 0/7996 mau -> cong theo do lon CHUA TUNG chan gi
// Vi sao cong vo dung: tang toc thang 1 m/s^2 lam |a| = sqrt(9.81^2+1^2)
// = 9.86, chi lech 0.05 so voi g - gan nhu mu voi gia toc NGANG, ma do
// moi la thu lam nghieng uoc luong. atan(1/9.81) = 5.8 do ~ nua bien do.
//
// Hau qua do duoc o cliff_detect: tz nhay 0.775-0.817 (le ra co dinh
// 0.800), doc mat san khop ra -0.163 ~ tan(9.3 do) -> 101 diem san that
// bi coi la sut -> bao vuc gia -> chan pha DRIVE cua reloc_exec.
//
// Cach sua: robot BIET no dang tang toc bao nhieu (odometry banh xe).
// Tru phan gia toc cua chinh minh ra khoi so doc gia toc ke, phan con lai
// moi la trong luc.
pnh_.param("use_odom_accel", use_odom_accel_, true);
pnh_.param<std::string>("odom_topic", odom_topic_, "/odometry/filtered");
pnh_.param("odom_timeout", odom_timeout_, 0.2);
pnh_.param("odom_accel_alpha", odom_accel_alpha_, 0.3);
imu_sub_ = nh_.subscribe("imu/data_raw", 200, &GravityAlignNodelet::onImu, this);
if (use_odom_accel_)
odom_sub_ = nh_.subscribe(odom_topic_, 50,
&GravityAlignNodelet::onOdom, this);
cloud_sub_ = nh_.subscribe("cloud_in", 5, &GravityAlignNodelet::onCloud, this);
NODELET_INFO("gravity_align: output_frame=%s, alpha=%.3f, chieu cao [%.2f, %.2f] m",
@@ -150,6 +174,26 @@ private:
"Xem docs/ARCHITECTURE.md muc 2.5D.");
}
void onOdom(const nav_msgs::Odometry::ConstPtr& msg)
{
const ros::Time now = msg->header.stamp;
const double v = msg->twist.twist.linear.x;
if (have_odom_)
{
const double dt = (now - last_odom_time_).toSec();
if (dt > 1e-3 && dt < 1.0)
{
// Vi phan van toc thi on - loc thong thap truoc khi dung.
const double a = odom_accel_alpha_;
a_lin_ = a * ((v - v_prev_) / dt) + (1.0 - a) * a_lin_;
}
}
v_prev_ = v;
w_ = msg->twist.twist.angular.z;
last_odom_time_ = now;
have_odom_ = true;
}
void onImu(const sensor_msgs::Imu::ConstPtr& msg)
{
const ros::Time now = msg->header.stamp;
@@ -196,12 +240,25 @@ private:
// --- Hieu chinh bang accel (chi khi dang gan trang thai tinh) ---
const double ax = ax_f_, ay = ay_f_, az = az_f_;
const double norm = std::sqrt(ax * ax + ay * ay + az * az);
// Tru gia toc cua CHINH ROBOT truoc khi coi phan con lai la trong luc.
// axc: gia toc tinh tien (dv/dt)
// ayc: gia toc huong tam khi quay (v * omega)
double axc = ax, ayc = ay;
const bool odom_fresh =
have_odom_ && (now - last_odom_time_).toSec() < odom_timeout_;
if (use_odom_accel_ && odom_fresh)
{
axc = ax - a_lin_;
ayc = ay - v_prev_ * w_;
}
const double norm = std::sqrt(axc * axc + ayc * ayc + az * az);
if (std::fabs(norm - 9.80665) < accel_gate_ && norm > 1e-3)
{
const double roll_acc = std::atan2(ay, az);
const double pitch_acc = std::atan2(-ax, std::sqrt(ay * ay + az * az));
const double roll_acc = std::atan2(ayc, az);
const double pitch_acc = std::atan2(-axc, std::sqrt(ayc * ayc + az * az));
roll_ = alpha_ * roll_ + (1.0 - alpha_) * roll_acc;
pitch_ = alpha_ * pitch_ + (1.0 - alpha_) * pitch_acc;
@@ -368,6 +425,13 @@ private:
double ax_f_ = 0.0, ay_f_ = 0.0, az_f_ = 9.80665;
bool accel_lpf_init_ = false;
bool have_imu_ = false, imu_init_ = false, accel_ok_ = false;
ros::Subscriber odom_sub_;
std::string odom_topic_;
bool use_odom_accel_ = true, have_odom_ = false;
double odom_timeout_ = 0.2, odom_accel_alpha_ = 0.3;
double a_lin_ = 0.0, v_prev_ = 0.0, w_ = 0.0;
ros::Time last_odom_time_;
ros::Time last_imu_time_;
};

View File

@@ -103,6 +103,10 @@
Mac dinh KHONG publish /initialpose nen bat len khong lam xau do chinh xac. -->
<arg name="enable_gicp" default="false"/>
<!-- ⚠️ TU LAI robot khi chua biet minh o dau. Mac dinh TAT.
Xem khoi canh bao trong localization_ops.launch truoc khi bat. -->
<arg name="enable_reloc_exec" default="false"/>
<!-- Gioi han ICP keo pose bao xa moi lan hieu chinh. Xem rtabmap.launch.
Noi len de proximity hoi phuc duoc sau va cham; doi lai mot ket qua ICP
sai cung duoc phep day xa hon. -->
@@ -171,6 +175,7 @@
<arg name="enable_active_reloc" value="$(arg enable_active_reloc)"/>
<arg name="enable_gicp" value="$(arg enable_gicp)"/>
<arg name="database_path" value="$(arg database_path)"/>
<arg name="enable_reloc_exec" value="$(arg enable_reloc_exec)"/>
<arg name="enable_multifloor" value="$(arg enable_multifloor)"/>
</include>

View File

@@ -68,6 +68,15 @@ safety_monitor:
enable_cliff_stop: true
cliff_timeout: 1.0 # s - khong co tin hieu moi thi coi nhu khong biet
# ⚠️ Giu chan TIEN them bao lau sau lan bao vuc CUOI CUNG.
# Da tra gia: robot di thang vao bac thang va ket. cliff_detect bao 38 lan
# trong lan chay do nhung chi chan duoc 1 - vi CLIFF_STOP chi kich hoat khi
# linear.x > 0 DUNG khoanh khac do, con robot thi xoay roi tien tung dot
# ngan. Va vuc bien mat khoi tam nhin khi lai gan hon 1.10 m (node mu duoi
# nguong do). Khoang trong giua "thay tu xa" va "da qua gan de thay" chinh
# la cho robot lot qua.
cliff_hold: 3.0
# ============ CAM BIEN VUC PHAN CUNG - CHUA MUA ============
# 2-3 ToF/IR chuc xuong o mep truoc (~$3/con). Day la thu DUY NHAT phu duoc
# vung mu 0-1.1m cua camera. Xem docs/HARDWARE.md muc 3.

View File

@@ -87,6 +87,7 @@ public:
// xem `cliff_topics` trong safety.yaml.
pnh.param("enable_cliff_stop", enable_cliff_stop_, true);
pnh.param("cliff_timeout", cliff_timeout_, 1.0);
pnh.param("cliff_hold", cliff_hold_, 3.0);
pnh.param("sensor_timeout", sensor_timeout_, 1.0);
pnh.param("cmd_timeout", cmd_timeout_, 0.5);
@@ -198,6 +199,8 @@ private:
{
cliff_ = msg->data;
last_cliff_time_ = ros::Time::now();
if (cliff_)
last_cliff_true_ = last_cliff_time_; // moc de giu chan, xem cliff_hold_
have_cliff_ = true;
}
@@ -289,8 +292,19 @@ private:
// se lam robot ket cung truoc mep ma khong ai cuu.
//
// Chi chan TIEN, cho phep LUI va XOAY - do la duong thoat duy nhat.
if (enable_cliff_stop_ && have_cliff_ && cliff_ &&
(now - last_cliff_time_).toSec() <= cliff_timeout_ &&
// ⚠️ Giu chan them cliff_hold_ giay sau lan bao vuc CUOI, khong chi khi co
// dang bat. Vuc bien mat khoi tam nhin cua camera khi lai gan hon 1.10 m,
// va CLIFF_STOP chi kich hoat dung khoanh khac co lenh tien - robot xoay
// roi tien tung dot ngan nen lot qua duoc khe do. Da tra gia bang mot lan
// di thang vao bac thang.
const bool cliff_recent =
have_cliff_ &&
(now - last_cliff_true_).toSec() <= cliff_hold_ &&
(now - last_cliff_time_).toSec() <= cliff_timeout_ + cliff_hold_;
if (enable_cliff_stop_ && (cliff_recent ||
(have_cliff_ && cliff_ &&
(now - last_cliff_time_).toSec() <= cliff_timeout_)) &&
last_cmd_.linear.x > 0.0)
{
out = last_cmd_;
@@ -372,6 +386,8 @@ private:
geometry_msgs::Twist last_cmd_;
ros::Time last_cmd_time_, last_scan_time_, last_bumper_time_, last_us_time_;
ros::Time last_cliff_time_;
ros::Time last_cliff_true_;
double cliff_hold_ = 3.0;
bool have_cmd_ = false, have_scan_ = false, have_bumper_ = false;
bool have_cliff_ = false, cliff_ = false;

View File

@@ -17,6 +17,8 @@ catkin_install_python(PROGRAMS
scripts/check_scan.py
scripts/check_yaw_drift.py
scripts/check_initpose.py
scripts/gather_reloc_stats.py
scripts/check_gravity_align.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

View File

@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""
check_gravity_align - So roll/pitch do tu IMU voi ground truth Gazebo.
============ VI SAO CAN ============
cliff_detect bao vuc gia 4-12 lan moi lan chay, va no chan pha DRIVE cua
reloc_exec. Da do o diem4: bat cliff -> 13 vong / 4.61 m that bai; tat cliff ->
1 lan di chuyen la chot.
Truy nguoc trong log cliff_detect[dbg]:
tz 0.775-0.817 (le ra co dinh 0.800) -> pitch dao dong +-8.5 do
doc mat san nhay giua 0.0000 va -0.1631 giua hai khung LIEN TIEP
tan(8.5 do) = 0.149, rat gan 0.163. Nen doc "bia" do CHINH LA pitch dao dong
dang bi bo khop hap thu - dung viec no sinh ra de lam.
=> Nghi thu pham that la roll/pitch tu gravity_align, khong phai cliff_detect.
Bo nay kiem dieu do. Neu pitch that (Gazebo) phang ma /gravity_align bao
+-8.5 do thi sua phai nam o gravity_align; moi tinh chinh trong cliff_detect
chi la va trieu chung.
⚠️ /ground_truth/odom CHI de danh gia. Khong uoc luong nao duoc subscribe no.
============ CACH DUNG ============
PYTHONUNBUFFERED=1 rosrun slam_eval check_gravity_align.py --duration 40
Chay roi LAI ROBOT toi lui vai met - loi chi lo ra khi tang/giam toc.
"""
import argparse
import math
import sys
import rospy
from nav_msgs.msg import Odometry
from std_msgs.msg import Float64MultiArray
def rp_of(q):
"""roll, pitch tu quaternion."""
sinr = 2.0 * (q.w * q.x + q.y * q.z)
cosr = 1.0 - 2.0 * (q.x * q.x + q.y * q.y)
roll = math.atan2(sinr, cosr)
sinp = 2.0 * (q.w * q.y - q.z * q.x)
sinp = max(-1.0, min(1.0, sinp))
return roll, math.asin(sinp)
class Checker(object):
def __init__(self):
self.gt = None # (roll, pitch) that, radian
self.v = 0.0
self.roll_e, self.pitch_e = [], []
self.n_bad_accel = 0
self.n = 0
rospy.Subscriber('/ground_truth/odom', Odometry, self.on_gt,
queue_size=50)
rospy.Subscriber('/gravity_align/roll_pitch', Float64MultiArray,
self.on_rp, queue_size=50)
def on_gt(self, m):
self.gt = rp_of(m.pose.pose.orientation)
self.v = math.hypot(m.twist.twist.linear.x, m.twist.twist.linear.y)
def on_rp(self, m):
if self.gt is None or len(m.data) < 2:
return
self.n += 1
if len(m.data) > 2 and m.data[2] < 0.5:
self.n_bad_accel += 1
self.roll_e.append(math.degrees(m.data[0] - self.gt[0]))
self.pitch_e.append(math.degrees(m.data[1] - self.gt[1]))
def report(self):
if not self.pitch_e:
print('khong nhan duoc du lieu - kiem /gravity_align/roll_pitch '
'va /ground_truth/odom co chay khong')
return
def stat(a, ten):
a = sorted(a)
n = len(a)
p = lambda q: a[min(n - 1, int(q * n))]
print(' %-6s: trung vi %+6.2f p5 %+6.2f p95 %+6.2f '
'bien do %.2f do' % (ten, p(0.5), p(0.05), p(0.95),
a[-1] - a[0]))
print('')
print('SAI SO roll/pitch so voi ground truth (%d mau):' % self.n)
stat(self.roll_e, 'roll')
stat(self.pitch_e, 'pitch')
print(' accel_ok = 0 o %d/%d mau (%.0f%%)'
% (self.n_bad_accel, self.n, 100.0 * self.n_bad_accel / self.n))
print('')
amp = max(self.pitch_e) - min(self.pitch_e)
if amp > 4.0:
print('=> PITCH DAO DONG %.1f do. Day la thu pham.' % amp)
print(' cliff_detect chi dang chiu hau qua: doc mat san no khop')
print(' ra tuong ung tan(%.1f do) = %.3f, du de day diem san that'
% (amp / 2.0, math.tan(math.radians(amp / 2.0))))
print(' xuong duoi nguong -> bao vuc gia.')
print(' SUA O gravity_align, khong phai cliff_detect.')
else:
print('=> pitch on dinh (bien do %.1f do). gravity_align KHONG phai'
% amp)
print(' thu pham - tim tiep trong cliff_detect.')
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--duration', type=float, default=40.0)
args, _ = ap.parse_known_args()
rospy.init_node('check_gravity_align', anonymous=True)
c = Checker()
print('check_gravity_align: dang do %.0fs - HAY LAI ROBOT TOI LUI vai met.'
% args.duration)
print('(loi chi lo ra khi tang/giam toc)')
rospy.sleep(args.duration)
c.report()
return 0
if __name__ == '__main__':
try:
sys.exit(main())
except rospy.ROSInterruptException:
pass

View File

@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""
gather_reloc_stats - Gom (ty le LiDAR, depth fitness, sai so THAT) tu cac log.
============ VI SAO CAN ============
Da hai lan rut ket luan tu 2 mau roi mau thu ba lat nguoc:
- nguong depth 0.10: dung 0.0716 / sai 0.1147 -> mau 3: SAI duoc 0.0392
- nguong ty le 1.40: dung >= 1.41 / sai <= 1.39 -> bien do 0.02, va ca 3 ca
sai deu o CUNG mot diem, cung mot kieu lat 180 do = MOT kieu hong lap lai
ba lan, khong phai ba mau doc lap
Bo nay khong ket luan gi. No chi GOM SO tu nhieu lan chay o NHIEU diem tha
khac nhau, roi in ra de nhin. Co tach duoc hay khong thi nhin bang mat.
============ CACH DUNG ============
Chay nhieu diem tha, moi lan mot cap log rieng (DUNG trung ten file, log cu
bi ghi de - da mat het du lieu mot lan vi chuyen nay):
./reloc_hosp.sh X Y 0.0 0.3 20 true true true true 2>&1 | tee /tmp/reloc_<ten>_t1.log
PYTHONUNBUFFERED=1 rosrun slam_eval check_initpose.py --map-origin 4.0 14.0 0.0 \
2>&1 | tee /tmp/reloc_<ten>_t2.log
Roi:
rosrun slam_eval gather_reloc_stats.py /tmp/reloc_*_t1.log
Bo tu tim file _t2 tuong ung theo ten.
"""
import argparse
import glob
import os
import re
import sys
RE_DOSO = re.compile(r'DOSO ty_le=([0-9.]+) depth_khop=([0-9.]+|khong-co)')
RE_SAI = re.compile(r'SAI\s+: vi tri ([0-9.]+) m\s+\|\s+HUONG ([+-][0-9.]+) do')
def main():
ap = argparse.ArgumentParser()
ap.add_argument('logs', nargs='+', help='cac file log T1 (_t1.log)')
ap.add_argument('--err-ok', type=float, default=1.0,
help='sai so duoi nguong nay coi la DUNG (m)')
args = ap.parse_args()
paths = []
for pat in args.logs:
paths.extend(sorted(glob.glob(pat)))
if not paths:
print('khong tim thay log nao')
return 1
rows = []
for t1 in paths:
t2 = t1.replace('_t1.log', '_t2.log')
if not os.path.exists(t2):
print(' (bo %s - khong co %s)' % (os.path.basename(t1),
os.path.basename(t2)))
continue
doso = RE_DOSO.findall(open(t1, errors='ignore').read())
sai = RE_SAI.findall(open(t2, errors='ignore').read())
if not doso or not sai:
print(' (bo %s - thieu DOSO hoac SAI)' % os.path.basename(t1))
continue
# DOSO cuoi cung truoc khi chot ghep voi lan publish dau tien
ty_le, khop = doso[-1]
e_pos, e_yaw = sai[0]
rows.append((os.path.basename(t1).replace('_t1.log', ''),
float(ty_le), khop, float(e_pos), float(e_yaw)))
if not rows:
print('khong gom duoc cap nao')
return 1
print('')
print('%-16s %8s %10s %10s %9s %s'
% ('diem tha', 'ty_le', 'depth', 'sai_vi_tri', 'sai_goc', 'ket luan'))
print('-' * 74)
for name, ty_le, khop, e_pos, e_yaw in sorted(rows, key=lambda r: r[3]):
ok = e_pos < args.err_ok
print('%-16s %8.3f %10s %9.3f m %8.2f %s'
% (name, ty_le, khop, e_pos, e_yaw, 'DUNG' if ok else '*** SAI'))
dung = [r for r in rows if r[3] < args.err_ok]
sai_ = [r for r in rows if r[3] >= args.err_ok]
print('')
print('%d DUNG, %d SAI' % (len(dung), len(sai_)))
if dung and sai_:
lo = min(r[1] for r in dung)
hi = max(r[1] for r in sai_)
print('ty le LiDAR : thap nhat khi DUNG %.3f | cao nhat khi SAI %.3f'
% (lo, hi))
print(' -> %s' % ('TACH DUOC, bien do %.3f' % (lo - hi) if lo > hi
else 'CHONG NHAU - khong nguong nao tach duoc'))
d = [float(r[2]) for r in dung if r[2] != 'khong-co']
s = [float(r[2]) for r in sai_ if r[2] != 'khong-co']
if d and s:
print('depth khop : cao nhat khi DUNG %.4f | thap nhat khi SAI %.4f'
% (max(d), min(s)))
print(' -> %s' % ('TACH DUOC' if max(d) < min(s)
else 'CHONG NHAU - khong nguong nao tach duoc'))
else:
print('⚠️ chi co mot loai ket qua - chua ket luan duoc gi')
return 0
if __name__ == '__main__':
sys.exit(main())