feat(sim): Gazebo wall model, detection sweep and evaluation scripts
- sim/models/wall_reflector_pair: wall with two 3 cm strips 9 cm apart (laser_retro 2000 on the strips, 0 on the wall), generated by gen_wall_models.py; spawn_wall_reflector.launch places it. - sim/eval_wall_reflector.py: compares the published marker/target with the Gazebo ground truth, read from the handler success log because the nav core TF never reaches ROS; --align-by-robot when map != Gazebo world. - sim/sweep_wall_detection.py: places the wall at several distances and angles behind the robot, sends DetectWallReflectors, writes a CSV and dumps the scan of every failed case. - Handler success log now prints marker, target and frame (debug/state). - Install sim/ in both catkin and standalone builds.
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -112,6 +112,8 @@ if(BUILDING_WITH_CATKIN)
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
install(DIRECTORY sim/ DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/sim)
|
||||
|
||||
else()
|
||||
|
||||
target_link_libraries(wall_reflector_detection_action_handler
|
||||
@@ -140,6 +142,8 @@ else()
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
)
|
||||
|
||||
install(DIRECTORY sim/ DESTINATION ${CMAKE_INSTALL_DATADIR}/${PROJECT_NAME}/sim)
|
||||
|
||||
|
||||
endif()
|
||||
|
||||
|
||||
118
README.md
118
README.md
@@ -2,7 +2,7 @@
|
||||
|
||||
Plugin Boost.DLL `WallReflectorDetectionActionHandler` đọc một `LaserScan` thô từ
|
||||
`robot_sensor_ports::SensorReader`, gọi `ReflectorPairMatcher`, lọc marker theo nhiều scan và ghi TF
|
||||
tĩnh cho trạm dừng. Gói không phát vận tốc. P2 chưa có cấu hình runtime, world hay chuỗi mission.
|
||||
tĩnh cho trạm dừng. Gói không phát vận tốc. Cấu hình và model P3 dưới đây chỉ dành cho mô phỏng.
|
||||
|
||||
## Contract
|
||||
|
||||
@@ -34,7 +34,7 @@ tĩnh cho trạm dừng. Gói không phát vận tốc. P2 chưa có cấu hình
|
||||
|
||||
## Khóa handler
|
||||
|
||||
Các khóa đặt dưới namespace của handler trong file test; đây là schema đề xuất cho P3:
|
||||
Các khóa đặt dưới namespace của handler; cấu hình runtime P3 dùng một profile SIM-ONLY:
|
||||
|
||||
| Khóa | Default | Miền / đơn vị |
|
||||
|---|---|---|
|
||||
@@ -80,3 +80,117 @@ này trong source tree khi build test. Không có khóa `filter_enabled`.
|
||||
của handler không điều khiển log của thư viện đó và P2 chưa chứng minh không cấp phát trong mọi tick.
|
||||
Cần xem xét API/budget của `action_core` nếu đây là yêu cầu cứng. Hiệu chuẩn, nghiệm thu robot, xác nhận
|
||||
đường sensor→bridge→store và chặng điều hướng thuộc các pha sau.
|
||||
|
||||
|
||||
## Mô phỏng Gazebo: chỉ số SIM-ONLY
|
||||
|
||||
Model `sim/models/wall_reflector_pair` có mặt tường tối `x=-0.050 m`, mặt tape nhô
|
||||
`x=-0.052 m`, tâm hai dải ở `y=±0.045 m`, rộng 0.03 m; dải cao 0.10–0.30 m, bao
|
||||
cao độ lidar sau 0.184 m. Tường `laser_retro=0`, tape `2000`, ngưỡng `1000`. Matcher
|
||||
chiếu mép lên **mặt tường**, nên marker ground truth ở `(-0.050,0)` trong frame model,
|
||||
pháp tuyến `-X`; không lấy mặt tape nhô làm tâm marker. Chạy lại generator khi cần:
|
||||
|
||||
```bash
|
||||
python3 /home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/src/Algorithms/Packages/actions/wall_reflector_detection_action/sim/gen_wall_models.py
|
||||
```
|
||||
|
||||
Model sinh hai dải rộng 0.03 m, tâm cách 0.09 m (số người dùng đang thử 12/11/2026). Vị trí spawn
|
||||
mặc định `(3.99,34.5,π)` đặt mặt dải cách lidar sau của robot khởi tạo tại `(5.5,34.5,0)` khoảng
|
||||
1.0 m (lidar ở base −0.454 m); dải 3 cm ở 2 m chỉ còn ~2.6 tia S300 sim, dưới `tape_min_points: 3`.
|
||||
Vị trí lấy từ đọc world; **chưa chạy Gazebo để kiểm chứng** vật cản/va chạm tại đó.
|
||||
Kiểm tra trong Gazebo trước khi gửi action. Chọn lại `x`, `y`, `yaw` nếu cần. Nếu model
|
||||
trùng tên đã tồn tại, xóa model cũ hoặc đổi `name` khi spawn.
|
||||
|
||||
Sau khi build workspace và `source /home/duongtd/T800_ws/devel/setup.bash` trong mỗi
|
||||
terminal, thứ tự tối thiểu như sau (5 terminal, dùng lại terminal spawn; chỉ sử dụng trong sim):
|
||||
|
||||
1. World và robot:
|
||||
|
||||
```bash
|
||||
roslaunch amr_startup sehc_world.launch robot_type:=hook_150
|
||||
```
|
||||
|
||||
2. Khi Gazebo sẵn sàng, spawn tường:
|
||||
|
||||
```bash
|
||||
roslaunch wall_reflector_detection_action spawn_wall_reflector.launch
|
||||
```
|
||||
|
||||
3. Cấp `/map` và `map→odom` bằng map/localization phù hợp với world. Ví dụ mở map
|
||||
`sehc_factory` sau khi xác nhận nó thực sự khớp world; AMCL cần pose khởi tạo đúng theo map
|
||||
và scan/TF hợp lệ, không mặc định map trùng Gazebo world:
|
||||
|
||||
```bash
|
||||
roslaunch amr_startup start_maps.launch map_file:=/home/duongtd/T800_ws/src/AMR_T800/Test/simulators/factory_ss_demo/maps/sehc_factory/sehc_factory.yaml with_virtual_walls:=false
|
||||
```
|
||||
|
||||
Ở terminal khác, sau khi biết pose ban đầu trong map, khởi chạy AMCL với các giá trị đó;
|
||||
ví dụ lệnh dưới chỉ đúng **nếu đã xác nhận** map trùng world:
|
||||
|
||||
```bash
|
||||
roslaunch /home/duongtd/T800_ws/src/AMR_T800/Controllers/Packages/amr_startup/launch/includes/amcl.launch scan_topic:=/b_scan initial_pose_x:=5.5 initial_pose_y:=34.5 initial_pose_a:=0.0
|
||||
```
|
||||
|
||||
Theo dõi localization hội tụ trước khi dò; số `(5.5,34.5,0)` là pose Gazebo, không tự chứng minh pose map.
|
||||
|
||||
4. Host dùng cây dev, sau khi topic/TF sẵn sàng:
|
||||
|
||||
```bash
|
||||
export PNKX_NAV_CORE_CONFIG_DIR=/home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/src/Navigations/Packages/move_base2/config/runtime
|
||||
roslaunch amr_startup amr_control.launch robot_type:=hook_150 with_virtual_walls:=false 2>&1 | tee /tmp/amr_control_wall.log
|
||||
```
|
||||
|
||||
`tee` giữ log để bước đánh giá đọc dòng kết quả của handler.
|
||||
|
||||
Host này đổi stamp sim về wall clock cho handler. Kiểm tra log boot đã nạp đúng handler/profile,
|
||||
sensor store và `/b_scan`; MQTT broker và định danh phải được cấu hình sẵn. Cây root `config/runtime`
|
||||
hiện comment `/b_scan` trong sensor store nên không dùng được cấu hình mới cho tới khi khai topic.
|
||||
|
||||
5. Chỉ dò, không di chuyển: gửi VDA5050 instant action bằng công cụ có sẵn. `--no-validate`
|
||||
bỏ kiểm schema phía script; phía nhận vẫn có thể từ chối. Xác nhận kết quả của **actionId hiện tại**
|
||||
trong state/log, không suy ra thành công từ TF cũ.
|
||||
|
||||
```bash
|
||||
python3 /home/duongtd/T800_ws/src/AMR_T800/Controllers/Packages/amr_comunication/scripts/vda5050_send.py /dev/stdin --kind instantActions --no-validate <<'JSON'
|
||||
{"actions":[{"actionType":"DetectWallReflectors","actionId":"wall-detect-1","blockingType":"HARD","actionParameters":[]}]}
|
||||
JSON
|
||||
```
|
||||
|
||||
Compound `GoToWallStation` chạy `DetectWallReflectors` rồi `move_to: wall_reflector_target`
|
||||
qua profile `docking`; nó **ra lệnh di chuyển lùi**, chỉ dùng sau khi xác nhận đường chạy, footprint,
|
||||
costmap và dừng an toàn trong sim. Profile docking hiện tắt tránh vật cản theo cấu hình hiện có;
|
||||
`clear_queue_on_failure` phải vẫn bật. Thử qua cùng lệnh instant action ở trên, thay actionType bằng
|
||||
`GoToWallStation` và actionId bằng một ID mới. Chưa xác nhận end-to-end routing/điều khiển cho scene này.
|
||||
|
||||
### Đánh giá pose
|
||||
|
||||
Handler ghi marker/target vào **tf3 nội bộ**; `amr_control` chỉ mirror ROS TF → tf3, không phát
|
||||
ngược lại, nên không đọc được hai frame kết quả bằng ROS TF. Khi thành công, handler log một dòng
|
||||
(nhóm `debug/state`, phải đang bật):
|
||||
|
||||
```text
|
||||
[wall_reflector][debug] 'detect_wall_reflector': output TF published: marker=(x, y, yaw) target=(x, y, yaw) frame=map
|
||||
```
|
||||
|
||||
Script đọc dòng **cuối** như vậy trong log và so với ground truth từ `/gazebo/model_states`
|
||||
(mặt tường tối của model, giữa hai dải; target = marker + offset của profile):
|
||||
|
||||
```bash
|
||||
python3 /home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/src/Algorithms/Packages/actions/wall_reflector_detection_action/sim/eval_wall_reflector.py --assume-map-equals-world --confirm-current-success --log /tmp/amr_control_wall.log
|
||||
```
|
||||
|
||||
Sau compound `GoToWallStation`, đo pose robot thật trong Gazebo so với target thật (gồm cả sai số
|
||||
localization và controller, không chỉ detector):
|
||||
|
||||
```bash
|
||||
python3 /home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/src/Algorithms/Packages/actions/wall_reflector_detection_action/sim/eval_wall_reflector.py --assume-map-equals-world --confirm-current-success --robot-final
|
||||
```
|
||||
|
||||
Có thể nhập tay số từ dòng log bằng `--marker X Y YAW --target X Y YAW` thay cho `--log`.
|
||||
Chỉ dùng cờ `--assume-map-equals-world` sau khi đã kiểm chứng hai frame trùng nhau; nếu không,
|
||||
thay bằng `--world-to-map X Y YAW` với ba số đo độc lập [m,m,rad], là pose world trong map.
|
||||
Nếu profile/model name thay đổi, truyền `--offset-x`, `--offset-y`, `--offset-yaw`,
|
||||
`--entry-direction`, `--wall-model`, `--robot-model` tương ứng. Sai số in theo hệ marker thật:
|
||||
lateral dọc tường, depth theo pháp tuyến, yaw. ModelStates không có stamp và log có thể chứa lượt cũ:
|
||||
xác nhận actionId hiện tại thành công trước khi đọc; phép đo không đồng bộ, không dùng làm chứng
|
||||
nhận độ chính xác robot thật.
|
||||
|
||||
@@ -672,8 +672,13 @@ private:
|
||||
return false;
|
||||
if (!writeTransform(output_frame_, x, y, yaw, now))
|
||||
return false;
|
||||
// TF chỉ nằm trong buffer tf3 nội bộ (host không phát lại sang ROS), nên dòng này là cách duy
|
||||
// nhất để đối chiếu kết quả từ ngoài: `sim/eval_wall_reflector.py --log` đọc đúng định dạng này.
|
||||
if (debug_state_)
|
||||
robot::log_info("[wall_reflector][debug] '%s': output TF published.", name_.c_str());
|
||||
robot::log_info("[wall_reflector][debug] '%s': output TF published: marker=(%.4f, %.4f, %.4f) "
|
||||
"target=(%.4f, %.4f, %.4f) frame=%s",
|
||||
name_.c_str(), marker.x, marker.y, marker.yaw, x, y, yaw,
|
||||
ctx_.global_frame.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
187
sim/eval_wall_reflector.py
Normal file
187
sim/eval_wall_reflector.py
Normal file
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/env python3
|
||||
"""SIM-ONLY: so kết quả DetectWallReflectors với ground truth từ Gazebo.
|
||||
|
||||
Handler ghi TF vào buffer tf3 nội bộ của nav core; host không phát lại sang ROS TF. Vì vậy script
|
||||
lấy kết quả từ dòng log thành công của handler (cần `debug/state: true`):
|
||||
|
||||
... output TF published: marker=(x, y, yaw) target=(x, y, yaw) frame=map
|
||||
|
||||
Ba chế độ lấy ước lượng:
|
||||
--log FILE đọc dòng thành công CUỐI trong file log của amr_control
|
||||
--marker X Y YAW --target X Y YAW nhập tay từ dòng log đó
|
||||
--robot-final pose base của robot trong Gazebo sau khi compound GoToWallStation xong
|
||||
(đo cả detector + localization + controller, không chỉ detector)
|
||||
|
||||
Ground truth: tâm marker nằm trên MẶT TƯỜNG tối (x model -0.05), giữa hai dải; pháp tuyến hướng ra
|
||||
phía robot. Sai số in trong hệ (t, n) của marker thật: lateral dọc tường, depth theo pháp tuyến.
|
||||
"""
|
||||
import argparse
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
|
||||
LOG_PATTERN = re.compile(
|
||||
r"output TF published: marker=\(([-+\d.eE]+), ([-+\d.eE]+), ([-+\d.eE]+)\) "
|
||||
r"target=\(([-+\d.eE]+), ([-+\d.eE]+), ([-+\d.eE]+)\) frame=(\S+)")
|
||||
|
||||
# Mặt tường tối trong frame model (gen_wall_models.py: WALL_FACE_X); tâm cặp dải ở y = 0.
|
||||
WALL_FACE_X = -0.05
|
||||
|
||||
|
||||
def wrap(angle):
|
||||
return math.atan2(math.sin(angle), math.cos(angle))
|
||||
|
||||
|
||||
def compose(parent, child):
|
||||
x, y, yaw = parent
|
||||
dx, dy, dyaw = child
|
||||
return (x + math.cos(yaw) * dx - math.sin(yaw) * dy,
|
||||
y + math.sin(yaw) * dx + math.cos(yaw) * dy,
|
||||
wrap(yaw + dyaw))
|
||||
|
||||
|
||||
def inverse(pose):
|
||||
x, y, yaw = pose
|
||||
c, s = math.cos(yaw), math.sin(yaw)
|
||||
return (-c * x - s * y, s * x - c * y, wrap(-yaw))
|
||||
|
||||
|
||||
def read_log(path):
|
||||
last = None
|
||||
with open(path, encoding='utf-8', errors='replace') as stream:
|
||||
for line in stream:
|
||||
match = LOG_PATTERN.search(line)
|
||||
if match:
|
||||
last = match
|
||||
if last is None:
|
||||
raise ValueError('không thấy dòng "output TF published: marker=..." trong ' + path +
|
||||
' (debug/state có đang bật không?)')
|
||||
values = [float(v) for v in last.groups()[:6]]
|
||||
return tuple(values[:3]), tuple(values[3:]), last.group(7)
|
||||
|
||||
|
||||
def report(label, estimate, truth, normal):
|
||||
nx, ny = normal
|
||||
ex, ey = estimate[0] - truth[0], estimate[1] - truth[1]
|
||||
depth = ex * nx + ey * ny
|
||||
lateral = -ex * ny + ey * nx
|
||||
print('{}: lateral={:+.4f} m, depth={:+.4f} m, yaw={:+.3f} deg'.format(
|
||||
label, lateral, depth, math.degrees(wrap(estimate[2] - truth[2]))))
|
||||
print(' estimate=({:.4f}, {:.4f}, {:.4f}) truth=({:.4f}, {:.4f}, {:.4f})'.format(
|
||||
*estimate, *truth))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
alignment = parser.add_mutually_exclusive_group(required=True)
|
||||
alignment.add_argument('--world-to-map', type=float, nargs=3, metavar=('X', 'Y', 'YAW'),
|
||||
help='Pose của Gazebo world trong map, đo độc lập [m, m, rad]')
|
||||
alignment.add_argument('--assume-map-equals-world', action='store_true',
|
||||
help='Chỉ dùng sau khi đã xác nhận map và world trùng nhau')
|
||||
alignment.add_argument('--align-by-robot', action='store_true',
|
||||
help='Suy world→map từ pose robot trong Gazebo và TF map→base_link hiện '
|
||||
'tại. Sai số khi đó là sai số detector so với chính robot (không gồm '
|
||||
'sai số localization). Robot phải đứng yên từ lúc dò tới lúc chạy.')
|
||||
source = parser.add_mutually_exclusive_group(required=True)
|
||||
source.add_argument('--log', metavar='FILE', help='File log chứa dòng thành công của handler')
|
||||
source.add_argument('--marker', type=float, nargs=3, metavar=('X', 'Y', 'YAW'))
|
||||
source.add_argument('--robot-final', action='store_true',
|
||||
help='So pose robot sau compound với target thật (end-to-end)')
|
||||
parser.add_argument('--target', type=float, nargs=3, metavar=('X', 'Y', 'YAW'),
|
||||
help='Đi kèm --marker')
|
||||
parser.add_argument('--confirm-current-success', action='store_true', required=True,
|
||||
help='Xác nhận thủ công lượt action hiện tại đã thành công; TF/log có thể cũ')
|
||||
parser.add_argument('--wall-model', default='wall_reflector_pair')
|
||||
parser.add_argument('--robot-model', default='robot')
|
||||
parser.add_argument('--global-frame', default='map')
|
||||
parser.add_argument('--base-frame', default='base_link')
|
||||
parser.add_argument('--offset-x', type=float, default=0.85)
|
||||
parser.add_argument('--offset-y', type=float, default=0.0)
|
||||
parser.add_argument('--offset-yaw', type=float, default=0.0)
|
||||
parser.add_argument('--entry-direction', choices=('forward', 'backward'), default='backward')
|
||||
parser.add_argument('--timeout', type=float, default=5.0)
|
||||
args = parser.parse_args()
|
||||
if args.marker is not None and args.target is None:
|
||||
parser.error('--marker cần đi kèm --target')
|
||||
alignment_pose = tuple(args.world_to_map or (0.0, 0.0, 0.0))
|
||||
if not all(math.isfinite(v) for v in (*alignment_pose, args.offset_x, args.offset_y,
|
||||
args.offset_yaw, args.timeout)) or args.timeout <= 0:
|
||||
parser.error('Alignment, offset phải hữu hạn và timeout phải dương')
|
||||
|
||||
marker = target = None
|
||||
frame = None
|
||||
if args.log:
|
||||
try:
|
||||
marker, target, frame = read_log(args.log)
|
||||
except (OSError, ValueError) as exc:
|
||||
print('Không đọc được kết quả:', exc, file=sys.stderr)
|
||||
return 1
|
||||
elif args.marker is not None:
|
||||
marker, target = tuple(args.marker), tuple(args.target)
|
||||
|
||||
import rospy
|
||||
from gazebo_msgs.msg import ModelStates
|
||||
from tf.transformations import euler_from_quaternion
|
||||
|
||||
def pose2d(pose, label):
|
||||
return pose2d_parts(pose.position, pose.orientation, label)
|
||||
|
||||
def pose2d_parts(position, orientation, label):
|
||||
values = (position.x, position.y, orientation.x, orientation.y, orientation.z,
|
||||
orientation.w)
|
||||
if not all(math.isfinite(value) for value in values):
|
||||
raise ValueError(label + ': pose không hữu hạn')
|
||||
roll, pitch, yaw = euler_from_quaternion(values[2:])
|
||||
if abs(roll) > 0.01 or abs(pitch) > 0.01:
|
||||
raise ValueError(label + ': phép đối chiếu 2D cần model gần thẳng đứng')
|
||||
return (position.x, position.y, yaw)
|
||||
|
||||
rospy.init_node('eval_wall_reflector', anonymous=True)
|
||||
try:
|
||||
states = rospy.wait_for_message('/gazebo/model_states', ModelStates, timeout=args.timeout)
|
||||
wall = states.pose[states.name.index(args.wall_model)]
|
||||
robot = states.pose[states.name.index(args.robot_model)]
|
||||
robot_in_world = pose2d(robot, 'robot')
|
||||
if args.align_by_robot:
|
||||
import tf2_ros
|
||||
buffer = tf2_ros.Buffer()
|
||||
listener = tf2_ros.TransformListener(buffer)
|
||||
stamped = buffer.lookup_transform(args.global_frame, args.base_frame, rospy.Time(0),
|
||||
rospy.Duration(args.timeout))
|
||||
transform = stamped.transform
|
||||
robot_in_global = pose2d_parts(transform.translation, transform.rotation,
|
||||
'TF ' + args.global_frame + '->' + args.base_frame)
|
||||
alignment_pose = compose(robot_in_global, inverse(robot_in_world))
|
||||
del listener
|
||||
wall_in_map = compose(alignment_pose, pose2d(wall, 'wall'))
|
||||
robot_in_map = compose(alignment_pose, robot_in_world)
|
||||
except Exception as exc: # rospy/tf2 lỗi đủ loại; script chỉ báo và thoát.
|
||||
print('Không thể đánh giá:', exc, file=sys.stderr)
|
||||
return 1
|
||||
|
||||
# Pháp tuyến mặt có dải là -x của model; quay π để +X marker hướng ra phía robot.
|
||||
marker_truth = compose(wall_in_map, (WALL_FACE_X, 0.0, math.pi))
|
||||
heading = args.offset_yaw + (math.pi if args.entry_direction == 'forward' else 0.0)
|
||||
target_truth = compose(marker_truth, (args.offset_x, args.offset_y, heading))
|
||||
normal = (math.cos(marker_truth[2]), math.sin(marker_truth[2]))
|
||||
if ((robot_in_map[0] - marker_truth[0]) * normal[0] +
|
||||
(robot_in_map[1] - marker_truth[1]) * normal[1]) <= 0:
|
||||
print('Robot không ở phía có dải của tường; ground truth pháp tuyến không áp dụng.',
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print('world→map: {}{}'.format(alignment_pose, '' if frame is None else ', frame log=' + frame))
|
||||
print('Cảnh báo: ModelStates không có stamp; dữ liệu không đồng bộ với lúc dò.')
|
||||
if args.robot_final:
|
||||
report('robot sau compound (detector + localization + controller)', robot_in_map,
|
||||
target_truth, normal)
|
||||
else:
|
||||
report('marker (detector)', marker, marker_truth, normal)
|
||||
report('target (detector + offset)', target, target_truth, normal)
|
||||
print('Robot hiện tại: ({:.4f}, {:.4f}, {:.4f})'.format(*robot_in_map))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
62
sim/gen_wall_models.py
Normal file
62
sim/gen_wall_models.py
Normal file
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sinh model SIM-ONLY; các tọa độ đều trong frame model."""
|
||||
from pathlib import Path
|
||||
|
||||
MODEL_DIR = Path(__file__).resolve().parent / 'models' / 'wall_reflector_pair'
|
||||
WALL_FACE_X = -0.050
|
||||
TAPE_FACE_X = -0.052
|
||||
# Dải rộng 0.03 m, tâm cách 0.09 m: kích thước người dùng đang thử ngày 12/11/2026.
|
||||
TAPE_WIDTH = 0.03
|
||||
TAPE_CENTRES_Y = (-0.045, 0.045)
|
||||
|
||||
|
||||
def main():
|
||||
MODEL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
config = '''<?xml version="1.0"?>
|
||||
<model><name>wall_reflector_pair</name><version>1.0</version>
|
||||
<sdf version="1.6">model.sdf</sdf>
|
||||
<description>SIM-ONLY: wall with two reflective tape strips.</description>
|
||||
</model>
|
||||
'''
|
||||
parts = []
|
||||
for index, centre_y in enumerate(TAPE_CENTRES_Y):
|
||||
parts.append(f''' <collision name="tape_{index}_collision">
|
||||
<pose>-0.051 {centre_y} 0.20 0 0 0</pose>
|
||||
<geometry><box><size>0.002 {TAPE_WIDTH} 0.20</size></box></geometry>
|
||||
<laser_retro>2000</laser_retro>
|
||||
</collision>
|
||||
<visual name="tape_{index}_visual">
|
||||
<pose>-0.051 {centre_y} 0.20 0 0 0</pose>
|
||||
<geometry><box><size>0.002 {TAPE_WIDTH} 0.20</size></box></geometry>
|
||||
<material><ambient>1 1 1 1</ambient><diffuse>1 1 1 1</diffuse></material>
|
||||
</visual>''')
|
||||
sdf = '''<?xml version="1.0"?>
|
||||
<sdf version="1.6">
|
||||
<model name="wall_reflector_pair">
|
||||
<static>true</static>
|
||||
<link name="wall">
|
||||
<collision name="wall_collision">
|
||||
<pose>0 0 0.30 0 0 0</pose>
|
||||
<geometry><box><size>0.10 2.0 0.60</size></box></geometry>
|
||||
<laser_retro>0</laser_retro>
|
||||
</collision>
|
||||
<visual name="wall_visual">
|
||||
<pose>0 0 0.30 0 0 0</pose>
|
||||
<geometry><box><size>0.10 2.0 0.60</size></box></geometry>
|
||||
<material><ambient>0.35 0.35 0.35 1</ambient><diffuse>0.35 0.35 0.35 1</diffuse></material>
|
||||
</visual>
|
||||
''' + '\n'.join(parts) + '''
|
||||
</link>
|
||||
</model>
|
||||
</sdf>
|
||||
'''
|
||||
(MODEL_DIR / 'model.config').write_text(config, encoding='utf-8')
|
||||
(MODEL_DIR / 'model.sdf').write_text(sdf, encoding='utf-8')
|
||||
print(f'Mặt tường dùng làm ground truth: x={WALL_FACE_X:.3f} m')
|
||||
print(f'Mặt tape: x={TAPE_FACE_X:.3f} m; tâm tape (x,y,z) [m]:')
|
||||
for centre_y in TAPE_CENTRES_Y:
|
||||
print(f' ({TAPE_FACE_X:.3f}, {centre_y:.3f}, 0.200)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
12
sim/launch/spawn_wall_reflector.launch
Normal file
12
sim/launch/spawn_wall_reflector.launch
Normal file
@@ -0,0 +1,12 @@
|
||||
<!-- SIM-ONLY. Vị trí mặc định chỉ là ứng viên qua đọc world; kiểm tra va chạm trong Gazebo. -->
|
||||
<launch>
|
||||
<arg name="name" default="wall_reflector_pair" />
|
||||
<!-- 3.99: mặt dải (x model -0.052, quay π → +0.052) nằm ở 4.042, cách lidar sau của hook_150
|
||||
(base 5.5 − 0.454 = 5.046) khoảng 1.0 m. Dải 3 cm ở 2 m chỉ còn ~2.6 tia S300 sim. -->
|
||||
<arg name="x" default="3.99" />
|
||||
<arg name="y" default="34.5" />
|
||||
<arg name="z" default="0.0" />
|
||||
<arg name="yaw" default="3.141592653589793" />
|
||||
<node name="spawn_$(arg name)" pkg="gazebo_ros" type="spawn_model" output="screen"
|
||||
args="-sdf -file $(find wall_reflector_detection_action)/sim/models/wall_reflector_pair/model.sdf -model $(arg name) -x $(arg x) -y $(arg y) -z $(arg z) -Y $(arg yaw)" />
|
||||
</launch>
|
||||
5
sim/models/wall_reflector_pair/model.config
Normal file
5
sim/models/wall_reflector_pair/model.config
Normal file
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0"?>
|
||||
<model><name>wall_reflector_pair</name><version>1.0</version>
|
||||
<sdf version="1.6">model.sdf</sdf>
|
||||
<description>SIM-ONLY: wall with two reflective tape strips.</description>
|
||||
</model>
|
||||
38
sim/models/wall_reflector_pair/model.sdf
Normal file
38
sim/models/wall_reflector_pair/model.sdf
Normal file
@@ -0,0 +1,38 @@
|
||||
<?xml version="1.0"?>
|
||||
<sdf version="1.6">
|
||||
<model name="wall_reflector_pair">
|
||||
<static>true</static>
|
||||
<link name="wall">
|
||||
<collision name="wall_collision">
|
||||
<pose>0 0 0.30 0 0 0</pose>
|
||||
<geometry><box><size>0.10 2.0 0.60</size></box></geometry>
|
||||
<laser_retro>0</laser_retro>
|
||||
</collision>
|
||||
<visual name="wall_visual">
|
||||
<pose>0 0 0.30 0 0 0</pose>
|
||||
<geometry><box><size>0.10 2.0 0.60</size></box></geometry>
|
||||
<material><ambient>0.35 0.35 0.35 1</ambient><diffuse>0.35 0.35 0.35 1</diffuse></material>
|
||||
</visual>
|
||||
<collision name="tape_0_collision">
|
||||
<pose>-0.051 -0.045 0.20 0 0 0</pose>
|
||||
<geometry><box><size>0.002 0.03 0.20</size></box></geometry>
|
||||
<laser_retro>2000</laser_retro>
|
||||
</collision>
|
||||
<visual name="tape_0_visual">
|
||||
<pose>-0.051 -0.045 0.20 0 0 0</pose>
|
||||
<geometry><box><size>0.002 0.03 0.20</size></box></geometry>
|
||||
<material><ambient>1 1 1 1</ambient><diffuse>1 1 1 1</diffuse></material>
|
||||
</visual>
|
||||
<collision name="tape_1_collision">
|
||||
<pose>-0.051 0.045 0.20 0 0 0</pose>
|
||||
<geometry><box><size>0.002 0.03 0.20</size></box></geometry>
|
||||
<laser_retro>2000</laser_retro>
|
||||
</collision>
|
||||
<visual name="tape_1_visual">
|
||||
<pose>-0.051 0.045 0.20 0 0 0</pose>
|
||||
<geometry><box><size>0.002 0.03 0.20</size></box></geometry>
|
||||
<material><ambient>1 1 1 1</ambient><diffuse>1 1 1 1</diffuse></material>
|
||||
</visual>
|
||||
</link>
|
||||
</model>
|
||||
</sdf>
|
||||
281
sim/sweep_wall_detection.py
Normal file
281
sim/sweep_wall_detection.py
Normal file
@@ -0,0 +1,281 @@
|
||||
#!/usr/bin/env python3
|
||||
"""SIM-ONLY: quét vùng làm việc của DetectWallReflectors trong Gazebo.
|
||||
|
||||
Với mỗi cặp (khoảng cách, góc), script:
|
||||
1. đọc pose robot trong Gazebo, đặt lại model tường sau lưng robot (lidar sau, `entry_direction:
|
||||
backward`): mặt dải cách lidar sau `distance` mét, tường xoay `angle` độ quanh tâm cặp dải;
|
||||
2. gửi instant action `DetectWallReflectors` qua `vda5050_send.py` (MQTT, cùng config với robot);
|
||||
3. đọc log của amr_control (phải ghi theo DÒNG — chạy launch qua `stdbuf -oL -eL`) tới khi có
|
||||
dòng thành công hoặc timeout của handler;
|
||||
4. nếu thành công, so marker/target với ground truth giống `eval_wall_reflector.py --align-by-robot`
|
||||
(world→map suy từ pose robot, nên sai số là của detector so với chính robot).
|
||||
|
||||
Robot phải đứng yên suốt quá trình quét. Kết quả in bảng và ghi CSV.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
MODEL_SDF = os.path.join(HERE, 'models', 'wall_reflector_pair', 'model.sdf')
|
||||
SEND_SCRIPT = os.path.normpath(os.path.join(
|
||||
HERE, '..', '..', '..', '..', '..', '..', '..', 'Controllers', 'Packages', 'amr_comunication',
|
||||
'scripts', 'vda5050_send.py'))
|
||||
|
||||
# Lidar sau của hook_150 nằm ở base −0.454 m (diff_hook_150.urdf.xacro: laser_dx); mặt dải ở x model
|
||||
# −0.052 (gen_wall_models.py: TAPE_FACE_X).
|
||||
REAR_LIDAR_OFFSET = 0.454
|
||||
TAPE_FACE_X = -0.052
|
||||
|
||||
FAIL_PATTERN = re.compile(r"\[wall_reflector\] '[^']+': (wall_reflector timeout: .*|"
|
||||
r"lidar faces opposite entry_direction|scan plane tilt.*|"
|
||||
r"wall_reflector: failed to publish.*|unknown profile.*)")
|
||||
DEBUG_REASON = re.compile(r"\[wall_reflector\]\[debug\] '[^']+': (.*)")
|
||||
|
||||
|
||||
def load_eval_module():
|
||||
spec = importlib.util.spec_from_file_location('eval_wall_reflector',
|
||||
os.path.join(HERE, 'eval_wall_reflector.py'))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def wall_pose_behind(robot, distance, angle, lateral):
|
||||
"""Pose model tường (world) để mặt dải cách lidar sau `distance`, xoay `angle` rad."""
|
||||
x, y, yaw = robot
|
||||
heading = (math.cos(yaw), math.sin(yaw))
|
||||
side = (-heading[1], heading[0])
|
||||
face_x = x - (REAR_LIDAR_OFFSET + distance) * heading[0] + lateral * side[0]
|
||||
face_y = y - (REAR_LIDAR_OFFSET + distance) * heading[1] + lateral * side[1]
|
||||
model_yaw = yaw + math.pi + angle
|
||||
# Mặt dải ở x model TAPE_FACE_X: gốc model = mặt − R(model_yaw)·(TAPE_FACE_X, 0).
|
||||
return (face_x - TAPE_FACE_X * math.cos(model_yaw),
|
||||
face_y - TAPE_FACE_X * math.sin(model_yaw),
|
||||
model_yaw)
|
||||
|
||||
|
||||
def wait_for_result(log_path, offset, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_reason = ''
|
||||
position = offset
|
||||
buffer = ''
|
||||
while time.monotonic() < deadline:
|
||||
with open(log_path, encoding='utf-8', errors='replace') as stream:
|
||||
stream.seek(position)
|
||||
chunk = stream.read()
|
||||
position = stream.tell()
|
||||
buffer += chunk
|
||||
lines = buffer.split('\n')
|
||||
buffer = lines.pop()
|
||||
for line in lines:
|
||||
reason = DEBUG_REASON.search(line)
|
||||
if reason and not reason.group(1).startswith(('started profile', 'scan=')):
|
||||
last_reason = reason.group(1)
|
||||
failure = FAIL_PATTERN.search(line)
|
||||
if failure:
|
||||
return 'fail', failure.group(1), None
|
||||
match = EVAL.LOG_PATTERN.search(line)
|
||||
if match:
|
||||
values = [float(v) for v in match.groups()[:6]]
|
||||
return 'ok', last_reason, (tuple(values[:3]), tuple(values[3:]))
|
||||
time.sleep(0.2)
|
||||
return 'no_result', last_reason or 'không thấy dòng kết quả (log có ghi theo dòng không?)', None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--log', required=True, help='Log amr_control đang được ghi (tee)')
|
||||
parser.add_argument('--distances', type=float, nargs='+', default=[0.6, 1.0, 1.4],
|
||||
help='Khoảng cách lidar sau → mặt dải [m]')
|
||||
parser.add_argument('--angles', type=float, nargs='+', default=[0.0, 20.0, -20.0, 30.0, -30.0],
|
||||
help='Góc xoay tường quanh tâm cặp dải [độ]')
|
||||
parser.add_argument('--lateral', type=float, default=0.0, help='Dịch tường dọc mặt [m]')
|
||||
parser.add_argument('--timeout', type=float, default=20.0, help='Chờ mỗi lượt [s]')
|
||||
parser.add_argument('--settle', type=float, default=1.0, help='Chờ sau khi đặt tường [s]')
|
||||
parser.add_argument('--offset-x', type=float, default=0.85)
|
||||
parser.add_argument('--wall-model', default='wall_reflector_pair')
|
||||
parser.add_argument('--robot-model', default='robot')
|
||||
parser.add_argument('--global-frame', default='map')
|
||||
parser.add_argument('--base-frame', default='base_link')
|
||||
parser.add_argument('--csv', default='/tmp/wall_sweep.csv')
|
||||
parser.add_argument('--scan-topic', default='/b_scan')
|
||||
parser.add_argument('--bright', type=float, default=1000.0,
|
||||
help='Ngưỡng intensity coi là tia sáng khi chẩn đoán (= tape_min_intensity)')
|
||||
args = parser.parse_args()
|
||||
|
||||
import rospy
|
||||
import tf2_ros
|
||||
from gazebo_msgs.msg import ModelStates
|
||||
from gazebo_msgs.srv import DeleteModel, SpawnModel
|
||||
from geometry_msgs.msg import Pose
|
||||
from sensor_msgs.msg import LaserScan
|
||||
|
||||
rospy.init_node('sweep_wall_detection', anonymous=True)
|
||||
rospy.wait_for_service('/gazebo/delete_model', timeout=10)
|
||||
rospy.wait_for_service('/gazebo/spawn_sdf_model', timeout=10)
|
||||
delete_model = rospy.ServiceProxy('/gazebo/delete_model', DeleteModel)
|
||||
spawn_model = rospy.ServiceProxy('/gazebo/spawn_sdf_model', SpawnModel)
|
||||
tf_buffer = tf2_ros.Buffer()
|
||||
tf_listener = tf2_ros.TransformListener(tf_buffer) # noqa: F841 — phải sống suốt vòng quét
|
||||
with open(MODEL_SDF, encoding='utf-8') as stream:
|
||||
sdf = stream.read()
|
||||
|
||||
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 model_pose(name):
|
||||
states = rospy.wait_for_message('/gazebo/model_states', ModelStates, timeout=5)
|
||||
pose = states.pose[states.name.index(name)]
|
||||
return (pose.position.x, pose.position.y, yaw_of(pose.orientation))
|
||||
|
||||
def model_present(name):
|
||||
states = rospy.wait_for_message('/gazebo/model_states', ModelStates, timeout=5)
|
||||
return name in states.name
|
||||
|
||||
def wait_until(predicate, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
def place_wall(wall):
|
||||
"""Xoá tường cũ, đợi nó biến mất, spawn ở `wall`, đợi đúng chỗ. Lỗi thì báo, không im lặng.
|
||||
|
||||
Xoá rồi spawn cùng tên ngay lập tức có thể bị Gazebo từ chối ("already exists") — lần quét
|
||||
12/11 mất 5/15 lượt vì không kiểm `success` của spawn.
|
||||
"""
|
||||
if model_present(args.wall_model):
|
||||
delete_model(args.wall_model)
|
||||
if not wait_until(lambda: not model_present(args.wall_model), 5.0):
|
||||
return 'không xoá được model tường cũ'
|
||||
pose = Pose()
|
||||
pose.position.x, pose.position.y = wall[0], wall[1]
|
||||
pose.orientation.z, pose.orientation.w = math.sin(wall[2] / 2), math.cos(wall[2] / 2)
|
||||
message = ''
|
||||
for _ in range(3):
|
||||
response = spawn_model(args.wall_model, sdf, '', pose, 'world')
|
||||
message = response.status_message
|
||||
if response.success:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
return 'spawn thất bại: ' + message
|
||||
|
||||
def at_requested_pose():
|
||||
if not model_present(args.wall_model):
|
||||
return False
|
||||
x, y, yaw = model_pose(args.wall_model)
|
||||
return (math.hypot(x - wall[0], y - wall[1]) < 0.01 and
|
||||
abs(EVAL.wrap(yaw - wall[2])) < 0.01)
|
||||
|
||||
if not wait_until(at_requested_pose, 5.0):
|
||||
return 'tường không xuất hiện đúng pose sau khi spawn'
|
||||
return ''
|
||||
|
||||
rows = []
|
||||
case = 0
|
||||
for distance in args.distances:
|
||||
for angle_degrees in args.angles:
|
||||
case += 1
|
||||
robot_world = model_pose(args.robot_model)
|
||||
wall = wall_pose_behind(robot_world, distance, math.radians(angle_degrees), args.lateral)
|
||||
placement_error = place_wall(wall)
|
||||
if placement_error:
|
||||
print('{:>4.2f} m {:>+6.1f}° lỗi đặt tường: {}'.format(
|
||||
distance, angle_degrees, placement_error), flush=True)
|
||||
rows.append({'distance_m': distance, 'angle_deg': angle_degrees,
|
||||
'status': 'wall_error', 'reason': placement_error,
|
||||
'marker_lateral_mm': '', 'marker_depth_mm': '', 'yaw_deg': '',
|
||||
'target_lateral_mm': '', 'target_depth_mm': ''})
|
||||
continue
|
||||
time.sleep(args.settle)
|
||||
|
||||
offset = os.path.getsize(args.log)
|
||||
action_id = 'wall-sweep-{}-{}'.format(case, int(time.time()))
|
||||
message = json.dumps({'actions': [{'actionType': 'DetectWallReflectors',
|
||||
'actionId': action_id, 'blockingType': 'HARD',
|
||||
'actionParameters': []}]})
|
||||
sent = subprocess.run([sys.executable, SEND_SCRIPT, '/dev/stdin', '--kind',
|
||||
'instantActions', '--no-validate'],
|
||||
input=message, text=True, capture_output=True)
|
||||
if sent.returncode != 0:
|
||||
print('Gửi action lỗi:', sent.stdout, sent.stderr, file=sys.stderr)
|
||||
return 1
|
||||
status, reason, result = wait_for_result(args.log, offset, args.timeout)
|
||||
|
||||
if status != 'ok':
|
||||
# Lưu một scan để biết vì sao không dò được: không có tia sáng nào (Gazebo không trả
|
||||
# laser_retro), chỉ một dải (bị che), hay đủ hai dải mà matcher vẫn loại.
|
||||
try:
|
||||
scan = rospy.wait_for_message(args.scan_topic, LaserScan, timeout=5)
|
||||
bright = [i for i, v in enumerate(scan.intensities) if v >= args.bright]
|
||||
runs = []
|
||||
for index in bright:
|
||||
if runs and index == runs[-1][1] + 1:
|
||||
runs[-1][1] = index
|
||||
else:
|
||||
runs.append([index, index])
|
||||
dump = '/tmp/wall_sweep_fail_{}.json'.format(case)
|
||||
with open(dump, 'w', encoding='utf-8') as stream:
|
||||
json.dump({'distance_m': distance, 'angle_deg': angle_degrees,
|
||||
'robot_world': robot_world, 'wall_world': wall,
|
||||
'angle_min': scan.angle_min,
|
||||
'angle_increment': scan.angle_increment,
|
||||
'ranges': list(scan.ranges),
|
||||
'intensities': list(scan.intensities),
|
||||
'bright_runs': runs}, stream)
|
||||
reason += ' | scan: {} tia sáng, run {}, max intensity {:.0f} → {}'.format(
|
||||
len(bright), runs[:6], max(scan.intensities, default=0.0), dump)
|
||||
except rospy.ROSException as exc:
|
||||
reason += ' | không lấy được scan: {}'.format(exc)
|
||||
row = {'distance_m': distance, 'angle_deg': angle_degrees, 'status': status,
|
||||
'reason': reason, 'marker_lateral_mm': '', 'marker_depth_mm': '',
|
||||
'yaw_deg': '', 'target_lateral_mm': '', 'target_depth_mm': ''}
|
||||
if result is not None:
|
||||
stamped = tf_buffer.lookup_transform(args.global_frame, args.base_frame,
|
||||
rospy.Time(0), rospy.Duration(5.0))
|
||||
t = stamped.transform
|
||||
robot_global = (t.translation.x, t.translation.y, yaw_of(t.rotation))
|
||||
alignment = EVAL.compose(robot_global, EVAL.inverse(robot_world))
|
||||
wall_global = EVAL.compose(alignment, model_pose(args.wall_model))
|
||||
marker_truth = EVAL.compose(wall_global, (EVAL.WALL_FACE_X, 0.0, math.pi))
|
||||
target_truth = EVAL.compose(marker_truth, (args.offset_x, 0.0, 0.0))
|
||||
nx, ny = math.cos(marker_truth[2]), math.sin(marker_truth[2])
|
||||
marker, target = result
|
||||
for label, estimate, truth in (('marker', marker, marker_truth),
|
||||
('target', target, target_truth)):
|
||||
ex, ey = estimate[0] - truth[0], estimate[1] - truth[1]
|
||||
row[label + '_lateral_mm'] = round(1000.0 * (-ex * ny + ey * nx), 2)
|
||||
row[label + '_depth_mm'] = round(1000.0 * (ex * nx + ey * ny), 2)
|
||||
row['yaw_deg'] = round(math.degrees(EVAL.wrap(marker[2] - marker_truth[2])), 3)
|
||||
rows.append(row)
|
||||
print('{:>4.2f} m {:>+6.1f}° {:<9} marker lat {:>7} mm depth {:>7} mm yaw {:>7}° '
|
||||
'target lat {:>7} mm {}'.format(
|
||||
distance, angle_degrees, status, row['marker_lateral_mm'],
|
||||
row['marker_depth_mm'], row['yaw_deg'], row['target_lateral_mm'],
|
||||
reason), flush=True)
|
||||
|
||||
with open(args.csv, 'w', newline='', encoding='utf-8') as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(rows[0].keys()))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
print('CSV:', args.csv)
|
||||
print('Cảnh báo: ModelStates không có stamp; sim không có bloom/bias của băng gương thật.')
|
||||
return 0
|
||||
|
||||
|
||||
EVAL = load_eval_module()
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user