Import the complete field and a simplified omnidirectional robot in sim_ws. Reuse original Point-LIO, SCAN and controller implementations with isolated simulation profiles, timed MID360/IMU data, readiness and command guards. Support known-corridor terrain paths, optional sensor stress profiles and separate physics/algorithm launch processes. Remove retired Fortress resources and operating instructions; add build, usage, scope and durable validation documentation. Validation: full build script; 8 adapter tests and 4 SCAN CTest targets; 8 continuous mild-noise routes; red/blue terrain 4 cases each; noise 9/9; visibility characterization 9/9; default sensors 16/16; loss-stop and post-build straight navigation. Real wheels/network remain unverified.
2408 lines
107 KiB
Python
2408 lines
107 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""SIM-P1-004-C:Gazebo Classic 11 完整场地基线检查。
|
||
|
||
本工具自己拉起/收掉 gazebo,所有阶段在一次进程内完成。分三个阶段:
|
||
|
||
--stage assets 纯文件核对:三个模型文件与源一致、坡道仅有固定面朝向修正、world 只差两个插件声明、
|
||
安装树自包含、静态几何与 8 个抽样点是否落在预期碰撞体范围内。
|
||
--stage clock 启动完整场地,核对目标场地存在、插件各加载一次、
|
||
/clock 单发布者、≥10 s 仿真时间不倒退、暂停 3 s 墙钟不推进、恢复后继续推进。
|
||
--stage contacts 逐用例启动「场地 + 测试球」,先暂停确认采集就绪再释放,
|
||
用 Classic 的接触传感器采集实际接触消息并判定。
|
||
--stage all 依次跑三个阶段。
|
||
|
||
约定(与任务一致):
|
||
- 单位米/秒/弧度,右手系 Z 向上,场地 pose 全零,红方 +Y,坡道下降方向 +X。
|
||
- GAZEBO_MASTER_URI=http://127.0.0.1:11355,ROS_DOMAIN_ID=77,ROS_LOCALHOST_ONLY=1。
|
||
- 时间判定一律用 /clock(rosgraph_msgs/msg/Clock,Classic 的 ros 插件直接发布),
|
||
墙钟只用于超时。
|
||
- 接触位置取 Gazebo 报告的接触点,按世界坐标解算;不解算就不给结论。
|
||
|
||
运行前需要在**只加载系统 ROS + 本工作区 install/classic** 的环境里:
|
||
source /opt/ros/humble/setup.bash
|
||
source <ws>/install/classic/setup.bash
|
||
"""
|
||
|
||
import argparse
|
||
import hashlib
|
||
import json
|
||
import math
|
||
import os
|
||
import re
|
||
import signal
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 常量
|
||
# -----------------------------------------------------------------------------
|
||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
SRC_PKG = os.path.expanduser('~/r2027_gazebo_model/src/robocon_gazebo')
|
||
INSTALL_BASE = os.path.join(WS, 'install', 'classic')
|
||
PKG = 'robocon_gazebo'
|
||
OUTROOT = os.path.join(WS, 'log', 'p1_004_c')
|
||
|
||
MASTER = 'http://127.0.0.1:11355'
|
||
ROS_DOMAIN = '77'
|
||
|
||
BALL_RADIUS = 0.020
|
||
BALL_MASS = 0.10
|
||
I_BALL = 2.0 / 5.0 * BALL_MASS * BALL_RADIUS ** 2
|
||
DROP_HEIGHT = 0.20 # 球心 = 表面 + 0.20 + 半径 = 表面 + 0.220
|
||
TOL_CONTACT = 0.003 # 接触点到目标表面 3 mm
|
||
# 0.20 m 自由落体时间,用作首接触时刻的独立旁证(Classic 的 /clock 是 10 Hz 网格,
|
||
# 所以只能要求「同量级且不超过一个采样周期」,不作为判据)
|
||
T_FREE_FALL = math.sqrt(2.0 * DROP_HEIGHT / 9.8)
|
||
|
||
# 位姿查询:有界重试。次数与间隔写在这里,证据里记录实际用了几次。
|
||
POSE_ATTEMPTS = 8
|
||
POSE_RETRY_DELAY = 0.4
|
||
|
||
# 采集覆盖要求:释放后必须采满这么多**仿真**时间,墙钟只用于超时
|
||
REQUIRED_COVER_S = 2.0
|
||
|
||
# 释放前位姿与设定值的允许偏差(米)
|
||
MAX_INITIAL_DRIFT = 0.002
|
||
|
||
# 三态:PASS=物理判据成立且采集有效;FAIL=采集有效但物理判据不成立;INVALID=采集无效
|
||
STATUS_PASS = 'PASS'
|
||
STATUS_FAIL = 'FAIL'
|
||
STATUS_INVALID = 'INVALID'
|
||
|
||
# 坡道斜面(来自 ramp.obj 楔形:x=-0.8 处 z=0.597,x=2.7 处 z=0)
|
||
RAMP_A, RAMP_B, RAMP_C = 0.597, 3.5, 0.597 * 2.7 # 0.597x + 3.5z - 1.6119 = 0
|
||
RAMP_NORM = math.sqrt(RAMP_A ** 2 + RAMP_B ** 2)
|
||
RAMP_X_RANGE = (-0.8, 2.7)
|
||
RAMP_Y_NORTH = (3.0, 4.0)
|
||
RAMP_Y_SOUTH = (-4.0, -3.0)
|
||
|
||
TASK_ID = 'SIM-P1-004-C-R2'
|
||
CONTACT_TOPIC_NS = '/p1_004_c'
|
||
|
||
# GUI 状态是「外部事实」,不在本工具里硬写。
|
||
# 结论由 log/p1_004_c/gui/status.json 承载(result/basis/confirmed_by/criteria/screenshots)。
|
||
# 没有该文件时按「未验证」记录,避免把没人看过的画面写成通过。
|
||
GUI_STATUS_REL = os.path.join('gui', 'status.json')
|
||
|
||
GUI_UNVERIFIED_NOTE = (
|
||
'**未验证。** 本次证据目录未提供人工 GUI 确认记录,不能从无界面测试推断画面或 GPU 设备。\n\n'
|
||
'宿主桌面取证命令(在只加载系统 ROS 的新终端):\n\n'
|
||
'```bash\n'
|
||
'source /opt/ros/humble/setup.bash\n'
|
||
'source sim_ws/install/classic/setup.bash\n'
|
||
'export GAZEBO_MASTER_URI=http://127.0.0.1:11355 ROS_DOMAIN_ID=77 ROS_LOCALHOST_ONLY=1\n'
|
||
'ros2 launch robocon_gazebo robocon_gazebo.launch.py gui:=true paused:=false verbose:=true\n'
|
||
'```\n\n'
|
||
'在仓库根目录执行;按用户要求不补截图。人工目视逐项确认:红蓝分区、L1/L2 平台、'
|
||
'南北两侧坡道、三级踏步、围栏开口。')
|
||
|
||
|
||
def load_gui_status(outroot):
|
||
"""读 gui/status.json;不存在或不可解析则返回 None(=未验证)。"""
|
||
path = os.path.join(outroot, GUI_STATUS_REL)
|
||
if not os.path.exists(path):
|
||
return None
|
||
try:
|
||
with open(path, encoding='utf-8') as f:
|
||
return json.load(f)
|
||
except (OSError, ValueError):
|
||
return None
|
||
|
||
|
||
def render_gui_note(gui):
|
||
"""把 GUI 状态渲染成报告段落。"""
|
||
if not gui or gui.get('result') != 'passed':
|
||
return GUI_UNVERIFIED_NOTE
|
||
shots = gui.get('screenshots') or []
|
||
L = []
|
||
L.append('**已通过(%s)。** 确认人:%s;日期:%s。%s'
|
||
% (gui.get('basis', '实机目视确认'), gui.get('confirmed_by', '—'),
|
||
gui.get('confirmed_at', '—'), gui.get('confirm_note', '')))
|
||
L.append('')
|
||
if gui.get('environment'):
|
||
L.append('确认环境:%s' % gui['environment'])
|
||
L.append('')
|
||
L.append('结论**来自实机目视**,不是从像素数值或日志推断的。')
|
||
L.append('')
|
||
if gui.get('criteria'):
|
||
L.append('画面需确认的项(%s):%s'
|
||
% ('已逐项单独记录' if gui.get('criteria_checked_individually')
|
||
else '整体目视确认,未逐项单独记录',
|
||
'、'.join(gui['criteria'])))
|
||
L.append('')
|
||
if shots:
|
||
L.append('截图证据:')
|
||
L.append('')
|
||
for sname in shots:
|
||
L.append('- `%s`' % sname)
|
||
elif gui.get('screenshots_required') is False:
|
||
L.append('截图:**不要求**。%s' % gui.get('screenshots_note', ''))
|
||
else:
|
||
L.append('截图证据:**暂缺**(`log/p1_004_c/gui/` 下没有图片文件)。%s'
|
||
% gui.get('screenshots_note', ''))
|
||
L.append('')
|
||
L.append('> 注意:Gazebo 11 用 Ogre1,Fortress 用 Ogre2,是两条不同渲染链路;'
|
||
'旧 Fortress 的 GLX/EGL 结论不能套用到 Classic 的 `gzclient`。')
|
||
return '\n'.join(L)
|
||
|
||
|
||
# Three files match upstream; ramp.obj has one pinned face-winding correction.
|
||
MODEL_FILES = [
|
||
'models/robocon_ground_full/model.sdf',
|
||
'models/robocon_ground_full/model.config',
|
||
'models/robocon_ground_full/meshes/Untitled.dae',
|
||
'models/robocon_ground_full/meshes/ramp.obj',
|
||
]
|
||
WORLD_REL = 'worlds/robocon_track_full.world'
|
||
|
||
# 8 个抽样接触用例
|
||
# kind=plane_z : 顶面为水平面,接触点 |z - surface_z| <= 3 mm
|
||
# kind=ramp : 接触点到斜面垂直距离 <= 3 mm,且落在坡面范围内
|
||
# kind=none : 期望零接触,球跌至 z < -0.10
|
||
CASES = [
|
||
dict(id='K01', label='地面', x=-4.80, y=4.80, kind='plane_z', surface_z=0.000,
|
||
accept=['ground'], forbid=[], note='顶面 Z=0'),
|
||
dict(id='K02', label='L1', x=-2.00, y=2.00, kind='plane_z', surface_z=0.600,
|
||
accept=['Cube'], forbid=[], note='顶面 Z=0.600'),
|
||
dict(id='K03', label='L2', x=-1.00, y=1.00, kind='plane_z', surface_z=0.900,
|
||
accept=['Cube.017'], forbid=[], note='顶面 Z=0.900'),
|
||
dict(id='K04', label='第一踏步', x=-2.55, y=3.50, kind='plane_z', surface_z=0.150,
|
||
accept=['Cube.002'], forbid=[], note='顶面 Z=0.150'),
|
||
dict(id='K05', label='红侧坡道', x=1.00, y=3.50, kind='ramp', surface_z=None,
|
||
accept=['ramp_north'], forbid=[], note='接触实际坡面(y∈[3,4])',
|
||
ramp_y_range=RAMP_Y_NORTH),
|
||
dict(id='K06', label='蓝侧坡道', x=1.00, y=-3.50, kind='ramp', surface_z=None,
|
||
accept=['ramp_south'], forbid=[], note='接触实际坡面(y∈[-4,-3])',
|
||
ramp_y_range=RAMP_Y_SOUTH),
|
||
dict(id='K07', label='红侧围栏开口', x=-1.30, y=2.975, kind='plane_z', surface_z=0.600,
|
||
accept=['Cube'], forbid=['Cube.011', 'Cube.012', 'Cube.013', 'Cube.014',
|
||
'Cube.015', 'Cube.016'],
|
||
note='接触平台 Z=0.600,无围栏阻挡'),
|
||
dict(id='K08', label='场地外', x=-6.00, y=0.00, kind='none', surface_z=None,
|
||
accept=[], forbid=[], note='无场地接触,跌至 Z<-0.10'),
|
||
]
|
||
|
||
BALL_TMPL = ''' <!-- SIM-P1-004-C 测试球:r={r} m, m={m} kg,接触传感器 + 官方 bumper 插件 -->
|
||
<model name="test_ball">
|
||
<pose>{px} {py} {pz} 0 0 0</pose>
|
||
<static>false</static>
|
||
<link name="link">
|
||
<inertial>
|
||
<mass>{m}</mass>
|
||
<inertia><ixx>{i}</ixx><iyy>{i}</iyy><izz>{i}</izz>
|
||
<ixy>0</ixy><ixz>0</ixz><iyz>0</iyz></inertia>
|
||
</inertial>
|
||
<collision name="collision">
|
||
<geometry><sphere><radius>{r}</radius></sphere></geometry>
|
||
<surface>
|
||
<friction><ode><mu>0.8</mu><mu2>0.8</mu2></ode></friction>
|
||
<contact><ode><max_vel>0.1</max_vel><min_depth>0.001</min_depth></ode></contact>
|
||
</surface>
|
||
</collision>
|
||
<visual name="visual">
|
||
<geometry><sphere><radius>{r}</radius></sphere></geometry>
|
||
<material>
|
||
<ambient>0.9 0.15 0.15 1</ambient>
|
||
<diffuse>0.9 0.15 0.15 1</diffuse>
|
||
</material>
|
||
</visual>
|
||
<sensor name="contact" type="contact">
|
||
<always_on>true</always_on>
|
||
<update_rate>500</update_rate>
|
||
<contact><collision>collision</collision></contact>
|
||
<plugin name="bumper" filename="libgazebo_ros_bumper.so">
|
||
<ros>
|
||
<namespace>{ns}</namespace>
|
||
<remapping>bumper_states:=contacts</remapping>
|
||
</ros>
|
||
<frame_name>world</frame_name>
|
||
</plugin>
|
||
</sensor>
|
||
</link>
|
||
</model>
|
||
'''
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 基础工具
|
||
# -----------------------------------------------------------------------------
|
||
def log(msg):
|
||
sys.stdout.write(msg + '\n')
|
||
sys.stdout.flush()
|
||
|
||
|
||
def sha256_file(path):
|
||
h = hashlib.sha256()
|
||
with open(path, 'rb') as f:
|
||
for chunk in iter(lambda: f.read(1 << 20), b''):
|
||
h.update(chunk)
|
||
return h.hexdigest()
|
||
|
||
|
||
def ensure_dir(path):
|
||
os.makedirs(path, exist_ok=True)
|
||
return path
|
||
|
||
|
||
def run(cmd, env=None, timeout=60, cwd=None):
|
||
try:
|
||
return subprocess.run(cmd, env=env, cwd=cwd, timeout=timeout,
|
||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||
text=True)
|
||
except subprocess.TimeoutExpired:
|
||
class R:
|
||
returncode = 124
|
||
stdout = ''
|
||
stderr = 'timeout'
|
||
return R()
|
||
|
||
|
||
def sim_env(extra=None):
|
||
env = os.environ.copy()
|
||
env['GAZEBO_MASTER_URI'] = MASTER
|
||
env['ROS_DOMAIN_ID'] = ROS_DOMAIN
|
||
env['ROS_LOCALHOST_ONLY'] = '1'
|
||
env.pop('DISPLAY', None) # 纯 headless:不启动 gzclient
|
||
if extra:
|
||
env.update(extra)
|
||
return env
|
||
|
||
|
||
def gz(cmd_args, env, timeout=30):
|
||
"""调用 Classic 的 gz 命令行(world/model 信息查询与暂停兜底)。"""
|
||
return run(['gz'] + cmd_args, env, timeout=timeout)
|
||
|
||
|
||
def gz_model_pose(name, env, timeout=15):
|
||
"""单次取模型世界位姿;返回 (pose|None, detail)。detail 记录失败原因,供重试留证。"""
|
||
r = gz(['model', '-m', name, '-p'], env, timeout=timeout)
|
||
out = (r.stdout or '')
|
||
detail = {'rc': r.returncode,
|
||
'stdout_head': out.strip()[:200],
|
||
'stderr_head': (r.stderr or '').strip()[:200]}
|
||
if r.returncode != 0:
|
||
detail['reason'] = 'gz 返回码 %s' % r.returncode
|
||
return None, detail
|
||
nums = re.findall(r'[-+]?\d+\.?\d*(?:[eE][-+]?\d+)?', out)
|
||
if len(nums) < 3:
|
||
detail['reason'] = '输出中不足 3 个数值'
|
||
return None, detail
|
||
vals = [float(v) for v in nums[:6]]
|
||
while len(vals) < 6:
|
||
vals.append(0.0)
|
||
return vals, detail
|
||
|
||
|
||
def query_pose(name, env, attempts=POSE_ATTEMPTS, delay=POSE_RETRY_DELAY):
|
||
"""有界重试取位姿,返回 (pose|None, diag)。
|
||
|
||
重试是因为 `gz model -p` 走 Classic 传输层,偶尔返回空——这是查询抖动,
|
||
不是仿真状态问题。但**取不到就是取不到**:全部失败返回 None,
|
||
调用方必须按「采集无效」处理,绝不能拿 None 当「球没动」或「没有接触」。
|
||
diag 里逐次记录 rc / 失败原因 / 输出片段,并给出最终结论。
|
||
"""
|
||
tries = []
|
||
t0 = time.monotonic()
|
||
for i in range(attempts):
|
||
pose, d = gz_model_pose(name, env)
|
||
tries.append({'attempt': i + 1, 'ok': pose is not None,
|
||
'rc': d.get('rc'), 'reason': d.get('reason'),
|
||
'stdout_head': d.get('stdout_head')})
|
||
if pose is not None:
|
||
if i:
|
||
log(' [pose] %s 第 %d/%d 次查询成功(前 %d 次失败)'
|
||
% (name, i + 1, attempts, i))
|
||
return pose, {'name': name, 'attempts_allowed': attempts,
|
||
'attempts_used': i + 1,
|
||
'elapsed_s': round(time.monotonic() - t0, 3),
|
||
'final_result': 'ok', 'pose': pose, 'tries': tries}
|
||
if i < attempts - 1:
|
||
time.sleep(delay)
|
||
log(' [pose] %s %d 次查询全部失败,最后一次原因:%s'
|
||
% (name, attempts, tries[-1].get('reason') if tries else '未执行'))
|
||
return None, {'name': name, 'attempts_allowed': attempts,
|
||
'attempts_used': attempts,
|
||
'elapsed_s': round(time.monotonic() - t0, 3),
|
||
'final_result': 'failed', 'pose': None, 'tries': tries,
|
||
'reason': '连续 %d 次查询均未取到 %s 位姿' % (attempts, name)}
|
||
|
||
|
||
def ramp_surface_z(x):
|
||
"""坡道斜面在给定 x 处的世界 z。"""
|
||
return RAMP_A * (2.7 - x) / RAMP_B
|
||
|
||
|
||
def ramp_point_distance(p):
|
||
"""点到坡道斜面的垂直距离(x,z 平面内;y 不进方程)。"""
|
||
return abs(RAMP_A * p[0] + RAMP_B * p[2] - RAMP_C) / RAMP_NORM
|
||
|
||
|
||
def short_name(full):
|
||
return (full or '').split('::')[-1]
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 阶段一:资源核对
|
||
# -----------------------------------------------------------------------------
|
||
def load_model_geometry():
|
||
"""解析 model.sdf,返回 collision 列表与统计。"""
|
||
path = os.path.join(WS, 'src', PKG, MODEL_FILES[0])
|
||
text = open(path, encoding='utf-8').read()
|
||
cols = []
|
||
for blk in re.findall(r'<collision\b.*?</collision>', text, re.S):
|
||
name = re.search(r'<collision name="([^"]+)"', blk).group(1)
|
||
pm = re.search(r'<pose>([^<]+)</pose>', blk)
|
||
pose = [float(v) for v in pm.group(1).split()] if pm else [0.0] * 6
|
||
while len(pose) < 6:
|
||
pose.append(0.0)
|
||
item = dict(name=name, pose=pose)
|
||
if '<box>' in blk:
|
||
sz = [float(v) for v in re.search(r'<size>([^<]+)</size>', blk).group(1).split()]
|
||
item.update(type='box', size=sz,
|
||
lo=[pose[i] - sz[i] / 2.0 for i in range(3)],
|
||
hi=[pose[i] + sz[i] / 2.0 for i in range(3)],
|
||
top=pose[2] + sz[2] / 2.0)
|
||
elif '<cylinder>' in blk:
|
||
rad = float(re.search(r'<radius>([^<]+)</radius>', blk).group(1))
|
||
ln = float(re.search(r'<length>([^<]+)</length>', blk).group(1))
|
||
item.update(type='cylinder', radius=rad, length=ln,
|
||
top=pose[2] + ln / 2.0)
|
||
else:
|
||
uri = re.search(r'<uri>([^<]+)</uri>', blk).group(1)
|
||
item.update(type='mesh', uri=uri, top=None)
|
||
cols.append(item)
|
||
from collections import Counter
|
||
kinds = Counter(c['type'] for c in cols)
|
||
return cols, kinds
|
||
|
||
|
||
def stage_assets(outdir):
|
||
ensure_dir(outdir)
|
||
rep = {'stage': 'assets', 'tool_sha256': sha256_file(os.path.abspath(__file__)),
|
||
'checks': [], 'ok': True}
|
||
|
||
def chk(name, ok, detail):
|
||
rep['checks'].append({'name': name, 'ok': bool(ok), 'detail': detail})
|
||
if not ok:
|
||
rep['ok'] = False
|
||
log(' [%s] %-34s %s' % ('OK ' if ok else 'FAIL', name, detail))
|
||
|
||
log('[assets] 资源核对')
|
||
|
||
# 1. 四个模型文件与源一致
|
||
hashes = {}
|
||
for rel in MODEL_FILES:
|
||
src = os.path.join(SRC_PKG, rel)
|
||
dst = os.path.join(WS, 'src', PKG, rel)
|
||
if not os.path.exists(dst):
|
||
chk('模型文件存在:%s' % os.path.basename(rel), False, '缺失 %s' % dst)
|
||
continue
|
||
hs, hd = sha256_file(src), sha256_file(dst)
|
||
hashes[rel] = {'source': hs, 'package': hd, 'equal': hs == hd}
|
||
if rel.endswith('/ramp.obj'):
|
||
hashes[rel]['note']='预期差异:只反转所有面索引,顶点不变;见 ramp_winding_correction'
|
||
from repair_ramp_winding import verify
|
||
try:
|
||
correction = verify(open(src,'rb').read(),open(dst,'rb').read())
|
||
ok = all(correction[k] for k in ('exact_pinned_repair','vertices_unchanged',
|
||
'all_faces_reversed','closed_before','closed_after')) and correction['signed_volume_after_m3']>0
|
||
rep['ramp_winding_correction']=correction
|
||
except ValueError as exc:
|
||
ok=False;rep['ramp_winding_error']=str(exc)
|
||
chk('坡道仅采用已验证的面朝向修正',ok,'src=%s dst=%s' % (hs,hd))
|
||
else:
|
||
chk('SHA256一致:%s' % os.path.basename(rel), hs == hd,
|
||
'%s' % hd if hs == hd else 'src=%s dst=%s' % (hs, hd))
|
||
|
||
# 2. world 只删了两个插件声明
|
||
src_w = open(os.path.join(SRC_PKG, WORLD_REL), encoding='utf-8').read()
|
||
dst_w = open(os.path.join(WS, 'src', PKG, WORLD_REL), encoding='utf-8').read()
|
||
rebuilt = re.sub(r' <!-- SIM-P1-004-C:.*?-->\n', '', dst_w, flags=re.S)
|
||
plugin_lines = (' <plugin name="gazebo_ros_init" filename="libgazebo_ros_init.so"/>\n'
|
||
' <plugin name="gazebo_ros_factory" filename="libgazebo_ros_factory.so"/>\n')
|
||
rebuilt = rebuilt.replace(' </world>\n', plugin_lines + ' </world>\n', 1)
|
||
world_ok = (rebuilt == src_w)
|
||
chk('world 仅移除两行插件声明', world_ok,
|
||
'还原后与源逐字节一致' if world_ok else '还原后仍有差异,说明改了别的内容')
|
||
hashes[WORLD_REL] = {
|
||
'source': sha256_file(os.path.join(SRC_PKG, WORLD_REL)),
|
||
'package': sha256_file(os.path.join(WS, 'src', PKG, WORLD_REL)),
|
||
'equal': False, 'note': '预期不同:删了两行插件声明'}
|
||
plugin_in_dst = len(re.findall(r'<plugin\b[^>]*filename="libgazebo_ros_', dst_w))
|
||
chk('world 内无 ROS 系统插件声明', plugin_in_dst == 0,
|
||
'<plugin filename="libgazebo_ros_*"> 标签数=%d(说明注释中的文件名不计)' % plugin_in_dst)
|
||
rep['world'] = {'source_sha256': hashes[WORLD_REL]['source'],
|
||
'package_sha256': hashes[WORLD_REL]['package'],
|
||
'rebuilt_equals_source': world_ok,
|
||
'removed_plugin_lines': 2,
|
||
'plugin_refs_remaining': plugin_in_dst}
|
||
|
||
# 3. 安装树自包含。
|
||
# 只对资源目录(launch/worlds/models)做实体回溯:这三个目录在 --symlink-install
|
||
# 下是符号链接,必须指回本包源码,不能指向外部地图工作区。
|
||
# ament 生成的 cmake/hook/local_setup 等是本工作区的正常产物,不在回溯范围内。
|
||
share = os.path.join(INSTALL_BASE, PKG, 'share', PKG)
|
||
ext_hits = []
|
||
resolved_outside = []
|
||
n_files = 0
|
||
resource_dirs = ('launch', 'worlds', 'models')
|
||
src_root = os.path.join(WS, 'src', PKG)
|
||
for sub in resource_dirs:
|
||
for root, dirnames, files in os.walk(os.path.join(share, sub)):
|
||
# __pycache__/*.pyc 是 launch 被 import 时产生的构建产物,不是资源,
|
||
# 排除掉,否则会把正常的字节码缓存算成「实体越界」。
|
||
dirnames[:] = [d for d in dirnames if d != '__pycache__']
|
||
for fn in files:
|
||
if fn.endswith('.pyc'):
|
||
continue
|
||
p = os.path.join(root, fn)
|
||
n_files += 1
|
||
real = os.path.realpath(p)
|
||
if not real.startswith(src_root):
|
||
resolved_outside.append({'file': p, 'real': real})
|
||
# 目录本身也应是链接(symlink-install)
|
||
for root, _d, files in os.walk(share):
|
||
for fn in files:
|
||
p = os.path.join(root, fn)
|
||
try:
|
||
if 'r2027_gazebo_model' in open(p, encoding='utf-8', errors='ignore').read():
|
||
ext_hits.append(p)
|
||
except (OSError, UnicodeDecodeError):
|
||
pass
|
||
chk('安装树无外部路径引用', not ext_hits,
|
||
'扫描 share 全部文件,命中 %d 个' % len(ext_hits))
|
||
chk('资源目录实体均指向本包源码', not resolved_outside,
|
||
'回溯 launch/worlds/models 共 %d 个文件,越界 %d 个'
|
||
% (n_files, len(resolved_outside)))
|
||
rep['install'] = {'share_dir': share, 'file_count': n_files,
|
||
'external_path_hits': ext_hits,
|
||
'resolved_outside_package': resolved_outside}
|
||
|
||
# 4. 安装后的四个模型文件仍与源一致
|
||
inst_model = os.path.join(share, 'models', 'robocon_ground_full')
|
||
inst_ok = True
|
||
for rel in MODEL_FILES:
|
||
base = os.path.relpath(rel, 'models/robocon_ground_full')
|
||
p = os.path.join(inst_model, base)
|
||
if not os.path.exists(p) or sha256_file(p) != sha256_file(os.path.join(WS,'src',PKG,rel)):
|
||
inst_ok = False
|
||
chk('安装后模型文件与已验证的仓库资源一致', inst_ok, inst_model)
|
||
|
||
# 5. 静态几何清点
|
||
cols, kinds = load_model_geometry()
|
||
rep['geometry'] = {'collision_total': len(cols), 'by_type': dict(kinds),
|
||
'collisions': [{'name': c['name'], 'type': c['type'],
|
||
'pose': c['pose'], 'top': c.get('top')}
|
||
for c in cols]}
|
||
chk('碰撞体 50 = 46 box + 2 cylinder + 2 mesh',
|
||
len(cols) == 50 and kinds.get('box') == 46
|
||
and kinds.get('cylinder') == 2 and kinds.get('mesh') == 2,
|
||
'实测 %d = %d box + %d cylinder + %d mesh'
|
||
% (len(cols), kinds.get('box', 0), kinds.get('cylinder', 0), kinds.get('mesh', 0)))
|
||
|
||
# 6. 8 个抽样点在静态几何上是否落在预期碰撞体范围内
|
||
def inside_xy(c, x, y):
|
||
if c['type'] != 'box':
|
||
return False
|
||
return (c['lo'][0] <= x <= c['hi'][0]) and (c['lo'][1] <= y <= c['hi'][1])
|
||
|
||
plan = []
|
||
for cs in CASES:
|
||
found = [c for c in cols if inside_xy(c, cs['x'], cs['y']) and c.get('top') is not None]
|
||
found.sort(key=lambda c: -c['top'])
|
||
top = found[0]['top'] if found else None
|
||
if cs['kind'] == 'plane_z':
|
||
ok = (top is not None and abs(top - cs['surface_z']) < 1e-9
|
||
and short_name(found[0]['name']) in cs['accept'])
|
||
detail = '该点最强支撑体=%s top=%.3f' % (
|
||
short_name(found[0]['name']) if found else '无', top if top is not None else -1)
|
||
elif cs['kind'] == 'ramp':
|
||
y0, y1 = cs['ramp_y_range']
|
||
zexp = ramp_surface_z(cs['x'])
|
||
ok = (RAMP_X_RANGE[0] <= cs['x'] <= RAMP_X_RANGE[1] and y0 <= cs['y'] <= y1)
|
||
detail = '斜面 z(%.2f)=%.4f,坡道世界 y∈[%.1f,%.1f]' % (cs['x'], zexp, y0, y1)
|
||
else:
|
||
ok = (top is None)
|
||
detail = '该点无支撑体' if top is None else '意外有支撑体 top=%.3f' % top
|
||
chk('抽样点 %s(%s) 几何预设' % (cs['id'], cs['label']), ok, detail)
|
||
surf_for_drop = (ramp_surface_z(cs['x']) if cs['kind'] == 'ramp'
|
||
else (cs['surface_z'] if cs['surface_z'] is not None else 0.0))
|
||
drop_z = surf_for_drop + DROP_HEIGHT + BALL_RADIUS
|
||
plan.append({'id': cs['id'], 'label': cs['label'], 'x': cs['x'], 'y': cs['y'],
|
||
'kind': cs['kind'], 'surface_z': cs['surface_z'],
|
||
'ramp_surface_z_at_x': (ramp_surface_z(cs['x'])
|
||
if cs['kind'] == 'ramp' else None),
|
||
'release_z': round(drop_z, 6), 'note': cs['note']})
|
||
rep['plan'] = plan
|
||
rep['model_hashes'] = hashes
|
||
|
||
with open(os.path.join(outdir, 'assets.json'), 'w', encoding='utf-8') as f:
|
||
json.dump(rep, f, ensure_ascii=False, indent=2)
|
||
log('[assets] %s' % ('全部通过' if rep['ok'] else '存在未通过项'))
|
||
return rep
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 进程所有权:只碰自己创建的东西
|
||
# -----------------------------------------------------------------------------
|
||
# 上一轮 K02 采集无效的根因就在这里:旧实现按进程名扫描全部 gzserver 并逐个发信号,
|
||
# 两个重叠运行会把对方的 server 杀掉,位姿查询随之落空。现在改成:
|
||
# - 启动时 start_new_session,记录自己的 pgid;
|
||
# - 子进程只用 /proc/<pid>/stat 的 PPID 关系从自己的根 PID 往下找,不按名字匹配;
|
||
# - 收尾只对自己进程组发信号 + 对自己树内残存 PID 精确发信号;
|
||
# - 启动前用 TCP 探测 master 端口是否被占;被占就报错退出,**绝不去杀占用者**。
|
||
def _read_stat(pid):
|
||
"""返回 (ppid, pgrp, comm);读不到返回 None。"""
|
||
try:
|
||
with open('/proc/%d/stat' % pid, 'rb') as f:
|
||
data = f.read().decode('utf-8', 'replace')
|
||
except OSError:
|
||
return None
|
||
lp, rp = data.find('('), data.rfind(')')
|
||
if lp < 0 or rp < 0:
|
||
return None
|
||
comm = data[lp + 1:rp]
|
||
rest = data[rp + 2:].split()
|
||
if len(rest) < 2:
|
||
return None
|
||
try:
|
||
return int(rest[1]), int(rest[2]), comm
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def _all_pids():
|
||
return [int(e) for e in os.listdir('/proc') if e.isdigit()]
|
||
|
||
|
||
def proc_tree(root_pid, include_root=True):
|
||
"""按 PPID 关系收集 root_pid 的后代(只读 /proc)。"""
|
||
parent = {}
|
||
comm = {}
|
||
for pid in _all_pids():
|
||
st = _read_stat(pid)
|
||
if st:
|
||
parent[pid] = st[0]
|
||
comm[pid] = st[2]
|
||
out = set([root_pid]) if include_root else set()
|
||
changed = True
|
||
while changed:
|
||
changed = False
|
||
for pid, ppid in parent.items():
|
||
if pid not in out and ppid in out:
|
||
out.add(pid)
|
||
changed = True
|
||
return [{'pid': p, 'comm': comm.get(p)} for p in sorted(out) if p in comm]
|
||
|
||
|
||
def proc_cmdline(pid):
|
||
try:
|
||
with open('/proc/%d/cmdline' % pid, 'rb') as f:
|
||
return f.read().replace(b'\0', b' ').decode('utf-8', 'replace')
|
||
except OSError:
|
||
return ''
|
||
|
||
|
||
def port_open(host='127.0.0.1', port=11355, timeout=0.4):
|
||
"""TCP 探测端口是否有服务在听。只探测,不动对方。"""
|
||
import socket
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
s.settimeout(timeout)
|
||
try:
|
||
return s.connect_ex((host, port)) == 0
|
||
finally:
|
||
s.close()
|
||
|
||
|
||
def master_port(uri=None):
|
||
m = re.search(r':(\d+)\s*$', uri or MASTER)
|
||
return int(m.group(1)) if m else 11355
|
||
|
||
|
||
class Sim(object):
|
||
"""一次 gzserver 生命周期:启动 → 就绪 → 结束。只管理自己创建的进程树。"""
|
||
|
||
def __init__(self, world_file, outdir, node=None, master=None, world_name='robocon_world'):
|
||
self.world_file = world_file
|
||
self.outdir = ensure_dir(outdir)
|
||
self.proc = None
|
||
self.log_path = os.path.join(self.outdir, 'server.log')
|
||
self.node = node
|
||
self.env = sim_env()
|
||
if master:
|
||
self.env['GAZEBO_MASTER_URI'] = master
|
||
self.master = self.env.get('GAZEBO_MASTER_URI', MASTER)
|
||
self.world_name = world_name
|
||
self._fh = None
|
||
self.ready_info = {}
|
||
self.teardown_info = {}
|
||
# 启动阶段观测到的「本实例子进程」PID -> comm。
|
||
# 必要性:ros2 launch 会把 gzserver 放到它自己的会话里,killpg(launch) 打不到它;
|
||
# launch 先退出后 gzserver 会被挂到 PID 1,PPID 树也就看不见它了。
|
||
# 所以只能靠启动时确认过的那批 PID 来收尾——这也保证不会误伤别人的进程。
|
||
self.known_pids = {}
|
||
|
||
# -- 自己的进程树
|
||
def tree(self):
|
||
if self.proc is None:
|
||
return []
|
||
return proc_tree(self.proc.pid)
|
||
|
||
def tree_pids(self):
|
||
return [x['pid'] for x in self.tree()]
|
||
|
||
def find_in_tree(self, comm):
|
||
for x in self.tree():
|
||
if x['comm'] == comm:
|
||
return x['pid']
|
||
return None
|
||
|
||
def start(self, timeout=90.0):
|
||
port = master_port(self.master)
|
||
if port_open(port=port):
|
||
return False, ('master 端口 %d 已被别的进程占用;本工具不会去动它,'
|
||
'请先释放该端口或换 --master 端口后再跑' % port)
|
||
script = ('source /opt/ros/humble/setup.bash && '
|
||
'source "$WS_INSTALL/setup.bash" && '
|
||
'exec ros2 launch robocon_gazebo robocon_gazebo.launch.py '
|
||
'gui:=false paused:=true verbose:=true world:="$WORLD_FILE"')
|
||
env = dict(self.env)
|
||
env['WS_INSTALL'] = INSTALL_BASE
|
||
env['WORLD_FILE'] = self.world_file
|
||
self._fh = open(self.log_path, 'w', encoding='utf-8')
|
||
# cwd 固定为 /:证明资源路径不依赖当前工作目录,也不依赖外部地图工作区
|
||
self.proc = subprocess.Popen(['bash', '-c', script], env=env, cwd='/',
|
||
stdout=self._fh, stderr=subprocess.STDOUT,
|
||
start_new_session=True)
|
||
self.ready_info = {'root_pid': self.proc.pid,
|
||
'pgid': os.getpgid(self.proc.pid),
|
||
'master': self.master, 'port': port,
|
||
'port_free_at_start': True}
|
||
|
||
t0 = time.monotonic()
|
||
while time.monotonic() - t0 < timeout:
|
||
time.sleep(0.5)
|
||
if self.proc.poll() is not None:
|
||
return False, 'launch 进程提前退出,code=%s' % self.proc.returncode
|
||
# 只看自己树里的 gzserver,不看别人的
|
||
for x in self.tree():
|
||
if x['pid'] != os.getpid():
|
||
self.known_pids[x['pid']] = x['comm']
|
||
gz_pid = self.find_in_tree('gzserver')
|
||
if gz_pid is None:
|
||
continue
|
||
# 就绪判据:自己树里的 gzserver 在 + /clock 有发布者。
|
||
# 以 paused 启动时世界不步进,/clock 一条消息都不发,所以不能用
|
||
# 「收到 clock 消息」当就绪;发布者存在即证明 init 插件已加载。
|
||
n_pub = 0
|
||
try:
|
||
self.node.rclpy.spin_once(self.node.node, timeout_sec=0.05)
|
||
n_pub = self.node.clock_publishers()
|
||
except Exception:
|
||
n_pub = 0
|
||
if n_pub >= 1:
|
||
for x in self.tree():
|
||
if x['pid'] != os.getpid():
|
||
self.known_pids[x['pid']] = x['comm']
|
||
self.ready_info.update({'gzserver_pid': gz_pid, 'clock_publishers': n_pub,
|
||
'known_pids': dict(self.known_pids),
|
||
'ready_after_s': round(time.monotonic() - t0, 2)})
|
||
return True, 'gzserver pid=%d(本实例树内), /clock publishers=%d' % (gz_pid, n_pub)
|
||
return False, ('在 %.0f s 内未就绪(本实例树内无 gzserver 或 /clock 无发布者;'
|
||
'端口=%d)' % (timeout, port))
|
||
|
||
def gzserver_cmdline(self):
|
||
"""只取自己树内 gzserver 的命令行,用于插件加载计数。"""
|
||
out = []
|
||
gz_pid = self.find_in_tree('gzserver')
|
||
if gz_pid is not None:
|
||
out.append({'pid': gz_pid, 'cmdline': proc_cmdline(gz_pid)})
|
||
return out
|
||
|
||
def log_text(self):
|
||
try:
|
||
return open(self.log_path, encoding='utf-8', errors='ignore').read()
|
||
except OSError:
|
||
return ''
|
||
|
||
def stop(self):
|
||
"""收尾:只碰「本实例自己的」进程,并等到 master 端口真的释放。
|
||
|
||
为什么不能只用 killpg:实测 ros2 launch 会把 gzserver 放进它自己的会话,
|
||
killpg(launch) 打不到 gzserver;launch 先退出后 gzserver 被挂到 PID 1,
|
||
PPID 树也看不见它。因此以**启动阶段确认过的本实例子进程 PID**为准:
|
||
先 SIGTERM 进程组,再对这批已知 PID 精确 SIGTERM,等端口释放,
|
||
仍未退出的才 SIGKILL。全程不按进程名匹配、不碰任何未知 PID。
|
||
"""
|
||
port = master_port(self.master)
|
||
before = sorted(self.known_pids)
|
||
killed_pg = False
|
||
sigterm_pids = []
|
||
sigkill_pids = []
|
||
t_start = time.monotonic()
|
||
|
||
def alive(pid):
|
||
if pid in (0, 1, os.getpid()):
|
||
return False
|
||
try:
|
||
os.kill(pid, 0)
|
||
return True
|
||
except OSError:
|
||
return False
|
||
|
||
try:
|
||
if self.proc is not None and self.proc.poll() is None:
|
||
try:
|
||
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
|
||
killed_pg = True
|
||
except OSError:
|
||
self.proc.terminate()
|
||
try:
|
||
self.proc.wait(timeout=15)
|
||
except subprocess.TimeoutExpired:
|
||
try:
|
||
os.killpg(os.getpgid(self.proc.pid), signal.SIGKILL)
|
||
except OSError:
|
||
self.proc.kill()
|
||
finally:
|
||
# 对已知子进程(含被 launch 换了会话的 gzserver)逐个 SIGTERM
|
||
for pid in before:
|
||
if alive(pid):
|
||
try:
|
||
os.kill(pid, signal.SIGTERM)
|
||
sigterm_pids.append(pid)
|
||
except OSError:
|
||
pass
|
||
# 等「已知 PID 全灭 + 端口释放」,最长 45 s
|
||
deadline = t_start + 45.0
|
||
while time.monotonic() < deadline:
|
||
live = [p for p in self.known_pids if alive(p)]
|
||
if not live and not port_open(port=port):
|
||
break
|
||
time.sleep(0.25)
|
||
# 仍不走的才 SIGKILL(依然只限已知 PID)
|
||
for pid in list(self.known_pids):
|
||
if alive(pid):
|
||
try:
|
||
os.kill(pid, signal.SIGKILL)
|
||
sigkill_pids.append(pid)
|
||
except OSError:
|
||
pass
|
||
t_end = time.monotonic()
|
||
while time.monotonic() - t_end < 8.0 and port_open(port=port):
|
||
time.sleep(0.2)
|
||
self.teardown_info = {
|
||
'root_pid': (self.proc.pid if self.proc else None),
|
||
'known_pids_at_stop': before,
|
||
'killed_process_group': killed_pg,
|
||
'sigterm_pids': sorted(set(sigterm_pids)),
|
||
'sigkill_pids': sorted(set(sigkill_pids)),
|
||
'survivors': [p for p in self.known_pids if alive(p)],
|
||
'master_port': port,
|
||
'port_free_after_stop': (not port_open(port=port)),
|
||
'teardown_s': round(time.monotonic() - t_start, 2),
|
||
'never_touched_unknown_pid': True,
|
||
}
|
||
log(' [teardown] 已知子进程 %s;SIGTERM组=%s;逐个SIGTERM=%s;'
|
||
'SIGKILL=%s;端口释放=%s;耗时 %.1fs'
|
||
% (before, killed_pg, sigterm_pids or '无', sigkill_pids or '无',
|
||
self.teardown_info['port_free_after_stop'],
|
||
self.teardown_info['teardown_s']))
|
||
try:
|
||
if self._fh:
|
||
self._fh.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
_RCLPY_REFS = [0]
|
||
_PROBE_SEQ = [0]
|
||
|
||
|
||
class Probe(object):
|
||
"""rclpy 探针:订阅 /clock 与接触话题,单线程 spin_once。
|
||
|
||
用引用计数管理 rclpy.init/shutdown:进程内可能同时存在多个探针
|
||
(隔离验证要两个实例),不能重复 init、也不能提前 shutdown。
|
||
"""
|
||
|
||
def __init__(self, contact_topic_hint=None):
|
||
import rclpy
|
||
from rclpy.node import Node
|
||
from rclpy.parameter import Parameter
|
||
from rclpy.qos import (QoSProfile, ReliabilityPolicy, DurabilityPolicy,
|
||
HistoryPolicy)
|
||
from rosgraph_msgs.msg import Clock
|
||
from gazebo_msgs.msg import ContactsState
|
||
self.rclpy = rclpy
|
||
self.ContactsState = ContactsState
|
||
if _RCLPY_REFS[0] == 0:
|
||
rclpy.init(args=None)
|
||
_RCLPY_REFS[0] += 1
|
||
_PROBE_SEQ[0] += 1
|
||
self.node = Node('p1_004_c_probe_%d' % _PROBE_SEQ[0])
|
||
self.node.set_parameters([Parameter('use_sim_time', Parameter.Type.BOOL, True)])
|
||
# best_effort 订阅对 reliable / best_effort 两种发布者都兼容,
|
||
# 避免两侧 QoS 不匹配导致「收不到消息」被误判成「没有接触」。
|
||
self.qos = QoSProfile(depth=500,
|
||
reliability=ReliabilityPolicy.BEST_EFFORT,
|
||
durability=DurabilityPolicy.VOLATILE,
|
||
history=HistoryPolicy.KEEP_LAST)
|
||
self.clock_samples = []
|
||
self.contacts = []
|
||
self.contact_topic_hint = contact_topic_hint
|
||
self.contact_topic = None
|
||
self.subs = {}
|
||
self.node.create_subscription(Clock, '/clock', self._on_clock, self.qos)
|
||
self.clock_sub_created = True
|
||
|
||
# -- 时钟
|
||
def _on_clock(self, msg):
|
||
t = msg.clock.sec + msg.clock.nanosec / 1e9
|
||
self.clock_samples.append(t)
|
||
|
||
def clock_count(self):
|
||
return len(self.clock_samples)
|
||
|
||
def clock_publishers(self):
|
||
try:
|
||
return self.node.count_publishers('/clock')
|
||
except Exception:
|
||
return 0
|
||
|
||
def clock_now(self):
|
||
return self.clock_samples[-1] if self.clock_samples else None
|
||
|
||
# -- 接触
|
||
def _on_contacts(self, msg):
|
||
now = self.clock_now()
|
||
stamp = None
|
||
try:
|
||
stamp = msg.header.stamp.sec + msg.header.stamp.nanosec / 1e9
|
||
except Exception:
|
||
stamp = None
|
||
states = []
|
||
for st in msg.states:
|
||
pos = [[p.x, p.y, p.z] for p in st.contact_positions]
|
||
nrm = [[n.x, n.y, n.z] for n in st.contact_normals]
|
||
states.append({'collision1': st.collision1_name,
|
||
'collision2': st.collision2_name,
|
||
'positions': pos, 'normals': nrm,
|
||
'depths': list(st.depths)})
|
||
self.contacts.append({'clock_at_recv': now, 'header_stamp': stamp,
|
||
'frame_id': msg.header.frame_id, 'states': states})
|
||
|
||
def spin(self, seconds=0.0, until=None, timeout=30.0):
|
||
"""spin_once 循环;seconds>0 时按墙钟推进,until() 返回 True 时提前结束。"""
|
||
t0 = time.monotonic()
|
||
while True:
|
||
self.rclpy.spin_once(self.node, timeout_sec=0.02)
|
||
if until is not None and until():
|
||
return True
|
||
if seconds and time.monotonic() - t0 >= seconds:
|
||
return False
|
||
if not seconds and until is None:
|
||
return False
|
||
if time.monotonic() - t0 > timeout:
|
||
return False
|
||
|
||
def wait_clock(self, timeout=60.0, n=1):
|
||
t0 = time.monotonic()
|
||
while time.monotonic() - t0 < timeout:
|
||
self.rclpy.spin_once(self.node, timeout_sec=0.05)
|
||
if self.clock_count() >= n:
|
||
return True
|
||
return False
|
||
|
||
# -- 接触话题发现(按消息类型找,不假定名字)
|
||
def discover_contact_topic(self, timeout=30.0):
|
||
t0 = time.monotonic()
|
||
while time.monotonic() - t0 < timeout:
|
||
self.rclpy.spin_once(self.node, timeout_sec=0.05)
|
||
for name, types in self.node.get_topic_names_and_types():
|
||
if any(t.endswith('gazebo_msgs/msg/ContactsState') for t in types):
|
||
self.contact_topic = name
|
||
break
|
||
if self.contact_topic:
|
||
break
|
||
time.sleep(0.2)
|
||
if not self.contact_topic:
|
||
return False
|
||
if self.contact_topic not in self.subs:
|
||
self.subs[self.contact_topic] = self.node.create_subscription(
|
||
self.ContactsState, self.contact_topic, self._on_contacts, self.qos)
|
||
# 建完订阅再 spin 一小会儿,让 DDS 匹配
|
||
t1 = time.monotonic()
|
||
while time.monotonic() - t1 < 0.5:
|
||
self.rclpy.spin_once(self.node, timeout_sec=0.05)
|
||
return True
|
||
|
||
def contact_publishers(self):
|
||
if not self.contact_topic:
|
||
return 0
|
||
try:
|
||
return self.node.count_publishers(self.contact_topic)
|
||
except Exception:
|
||
return 0
|
||
|
||
# -- 暂停 / 恢复:优先用发现的 ROS 服务,否则回落到 Classic 的 gz world
|
||
def service_names(self):
|
||
return [n for n, _t in self.node.get_service_names_and_types()]
|
||
|
||
def call_pause(self, paused, env):
|
||
"""返回 (ok, method, detail)。"""
|
||
from std_srvs.srv import Empty
|
||
svcs = self.service_names()
|
||
want = 'unpause_physics' if not paused else 'pause_physics'
|
||
cand = [n for n in svcs
|
||
if n.rstrip('/').endswith(want) and 'un' not in n.split('/')[-1][:2]]
|
||
if not paused:
|
||
cand = [n for n in svcs if n.rstrip('/').endswith('unpause_physics')]
|
||
for name in cand:
|
||
try:
|
||
cli = self.node.create_client(Empty, name)
|
||
if not cli.wait_for_service(timeout_sec=2.0):
|
||
continue
|
||
fut = cli.call_async(Empty.Request())
|
||
t0 = time.monotonic()
|
||
while not fut.done() and time.monotonic() - t0 < 5.0:
|
||
self.rclpy.spin_once(self.node, timeout_sec=0.05)
|
||
if fut.done() and fut.exception() is None:
|
||
return True, 'ros_service', name
|
||
except Exception as exc:
|
||
log(' [pause] 服务 %s 调用异常:%r' % (name, exc))
|
||
# 兜底:Classic 的 gz world -p
|
||
r = gz(['world', '-p', '0' if not paused else '1'], env, timeout=20)
|
||
ok = r.returncode == 0
|
||
return ok, 'gz_world', (r.stdout or '').strip()[:200]
|
||
|
||
def close(self):
|
||
try:
|
||
self.node.destroy_node()
|
||
except Exception:
|
||
pass
|
||
_RCLPY_REFS[0] = max(0, _RCLPY_REFS[0] - 1)
|
||
if _RCLPY_REFS[0] == 0:
|
||
try:
|
||
self.rclpy.shutdown()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def wait_master_free(timeout=60.0, uri=None):
|
||
"""等 master 端口自己空出来。
|
||
|
||
只做 TCP 探测,**不对占用者发任何信号**——占用者可能是用户自己的仿真。
|
||
超时仍未释放就返回 False,由调用方报错退出。
|
||
"""
|
||
port = master_port(uri)
|
||
t0 = time.monotonic()
|
||
while time.monotonic() - t0 < timeout:
|
||
if not port_open(port=port):
|
||
return True
|
||
time.sleep(0.3)
|
||
log(' [warn] master 端口 %d 在 %.0f s 内仍被占用(未对其发送任何信号)'
|
||
% (port, timeout))
|
||
return False
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 阶段二:时钟 / 暂停 / 恢复
|
||
# -----------------------------------------------------------------------------
|
||
def stage_clock(outdir):
|
||
from rclpy.qos import QoSProfile, ReliabilityPolicy, DurabilityPolicy, HistoryPolicy
|
||
ensure_dir(outdir)
|
||
rep = {'stage': 'clock', 'tool_sha256': sha256_file(os.path.abspath(__file__)),
|
||
'checks': [], 'ok': True}
|
||
|
||
def chk(name, ok, detail):
|
||
rep['checks'].append({'name': name, 'ok': bool(ok), 'detail': detail})
|
||
if not ok:
|
||
rep['ok'] = False
|
||
log(' [%s] %-34s %s' % ('OK ' if ok else 'FAIL', name, detail))
|
||
|
||
log('[clock] 启动完整场地(headless,paused=true)')
|
||
wait_master_free()
|
||
probe = Probe()
|
||
world = os.path.join(WS, 'src', PKG, WORLD_REL)
|
||
sim = Sim(world, outdir, probe)
|
||
try:
|
||
ok, why = sim.start()
|
||
chk('server 就绪', ok, why)
|
||
if not ok:
|
||
return rep
|
||
|
||
# 目标场地存在
|
||
p_site, pose_diag = query_pose('robocon_ground_full', sim.env)
|
||
rep['site_pose_query'] = pose_diag
|
||
chk('运行时目标场地存在', p_site is not None,
|
||
'robocon_ground_full pose=%s' % (['%.3f' % v for v in p_site] if p_site else '查询失败'))
|
||
rep['site_pose'] = p_site
|
||
|
||
# 插件加载:从 gzserver 实际命令行计数
|
||
cmds = sim.gzserver_cmdline()
|
||
joined = ' '.join(c['cmdline'] for c in cmds)
|
||
n_init = joined.count('libgazebo_ros_init.so')
|
||
n_fact = joined.count('libgazebo_ros_factory.so')
|
||
n_force = joined.count('libgazebo_ros_force_system.so')
|
||
rep['gzserver_cmdline'] = cmds
|
||
chk('init 插件加载 1 次', n_init == 1, 'count=%d' % n_init)
|
||
chk('factory 插件加载 1 次', n_fact == 1, 'count=%d' % n_fact)
|
||
chk('未额外加载 force_system', n_force == 0, 'count=%d' % n_force)
|
||
|
||
# 资源 / 插件类型错误。
|
||
# 只拦「资源找不到 / 插件加载失败 / 插件类型不对」这类硬错误。
|
||
# headless 下 `[Err] [RenderEngine.cc] Can't open display` 与 GL/MESA 缺驱动
|
||
# 是**渲染**不可用,不是资源或插件错误,单列记录、不判失败(GUI 另由阶段四处理)。
|
||
logtxt = sim.log_text()
|
||
fatal_patterns = ['Unable to find', 'Could not find', 'Failed to load plugin',
|
||
'is not a valid plugin', 'Unable to load plugin',
|
||
'Cannot load plugin', 'Invalid plugin', 'Unable to find uri']
|
||
hits = [p for p in fatal_patterns if p in logtxt]
|
||
rep['log_fatal_hits'] = hits
|
||
chk('无资源/插件类型错误', not hits, '命中=%s' % (hits or '无'))
|
||
benign = []
|
||
for pat in ('RenderEngine.cc', 'Can\'t open display', 'libGL error', 'MESA: error'):
|
||
if pat in logtxt:
|
||
benign.append(pat)
|
||
rep['log_headless_render_notes'] = benign
|
||
log(' [info] headless 渲染相关日志(不计为资源/插件错误):%s' % (benign or '无'))
|
||
loaded = 'Loading world file' in logtxt
|
||
chk('world 已加载', loaded, '日志出现 Loading world file')
|
||
|
||
# /clock 单发布者
|
||
probe.rclpy.spin_once(probe.node, timeout_sec=0.05)
|
||
n_pub = probe.clock_publishers()
|
||
rep['clock_publishers'] = n_pub
|
||
chk('/clock 单发布者', n_pub == 1, 'publisher_count=%d' % n_pub)
|
||
|
||
# ---- 恢复运行,核对 ≥10 s 仿真时间不倒退
|
||
ok_u, method_u, detail_u = probe.call_pause(False, sim.env)
|
||
rep['unpause'] = {'ok': ok_u, 'method': method_u, 'detail': detail_u}
|
||
chk('恢复接口可用', ok_u, '%s %s' % (method_u, detail_u))
|
||
time.sleep(0.3)
|
||
probe.spin(seconds=0.5)
|
||
t_run0 = probe.clock_now()
|
||
samples0 = len(probe.clock_samples)
|
||
t0 = time.monotonic()
|
||
while time.monotonic() - t0 < 90.0:
|
||
probe.rclpy.spin_once(probe.node, timeout_sec=0.02)
|
||
cur = probe.clock_now()
|
||
if cur is not None and t_run0 is not None and cur - t_run0 >= 10.0:
|
||
break
|
||
seg = probe.clock_samples[samples0:]
|
||
# 跨度按「运行前基准值 → 最后一个采样」算,不用 seg[0]:
|
||
# clock 是 10 Hz,用首个采样会少算一个采样周期(0.1 s)。
|
||
span = ((seg[-1] - t_run0) if (seg and t_run0 is not None) else 0.0)
|
||
regress = sum(1 for i in range(1, len(seg)) if seg[i] < seg[i - 1] - 1e-9)
|
||
wall_run = time.monotonic() - t0
|
||
rep['run_observe'] = {'clock_at_start': t_run0, 'samples': len(seg),
|
||
'sim_span': span, 'regressions': regress,
|
||
'wall_s': round(wall_run, 3),
|
||
'final_sim': probe.clock_now()}
|
||
chk('连续运行 ≥10 s 仿真时间', span >= 10.0,
|
||
'span=%.3f s,%d 个采样,墙钟 %.2f s' % (span, len(seg), wall_run))
|
||
chk('仿真时间无倒退', regress == 0, 'regressions=%d' % regress)
|
||
chk('clock 持续发布', len(seg) >= 50, 'samples=%d' % len(seg))
|
||
|
||
# ---- 暂停:3 s 墙钟内不推进
|
||
v_pause0 = probe.clock_now()
|
||
c_pause0 = probe.clock_count()
|
||
ok_p, method_p, detail_p = probe.call_pause(True, sim.env)
|
||
rep['pause'] = {'ok': ok_p, 'method': method_p, 'detail': detail_p}
|
||
chk('暂停接口可用', ok_p, '%s %s' % (method_p, detail_p))
|
||
time.sleep(0.5)
|
||
probe.spin(seconds=0.5)
|
||
v_pause1 = probe.clock_now() # 暂停生效后的基准值
|
||
c_pause1 = probe.clock_count()
|
||
t_w0 = time.monotonic()
|
||
probe.spin(seconds=3.0)
|
||
v_pause2 = probe.clock_now()
|
||
c_pause2 = probe.clock_count()
|
||
wall = time.monotonic() - t_w0
|
||
advanced = ((v_pause2 - v_pause1)
|
||
if (v_pause1 is not None and v_pause2 is not None) else 0.0)
|
||
rep['pause_observe'] = {
|
||
'wall_s': round(wall, 3),
|
||
'clock_before_pause': v_pause0,
|
||
'clock_at_pause_start': v_pause1, 'clock_at_pause_end': v_pause2,
|
||
'sim_advanced': advanced,
|
||
'clock_msgs_during_pause': c_pause2 - c_pause1}
|
||
chk('暂停 %.1f s 墙钟内仿真不推进' % wall, advanced < 1e-9,
|
||
'sim %.6f -> %.6f(推进 %.9f s),期间收到 %d 条 clock'
|
||
% (v_pause1 or 0, v_pause2 or 0, advanced, c_pause2 - c_pause1))
|
||
|
||
# ---- 再次恢复:确认继续推进
|
||
ok_u2, method_u2, detail_u2 = probe.call_pause(False, sim.env)
|
||
rep['unpause_again'] = {'ok': ok_u2, 'method': method_u2, 'detail': detail_u2}
|
||
chk('二次恢复接口可用', ok_u2, '%s %s' % (method_u2, detail_u2))
|
||
samples1 = len(probe.clock_samples)
|
||
t_res = probe.clock_now()
|
||
t0 = time.monotonic()
|
||
while time.monotonic() - t0 < 30.0:
|
||
probe.rclpy.spin_once(probe.node, timeout_sec=0.02)
|
||
cur = probe.clock_now()
|
||
if cur is not None and t_res is not None and cur - t_res >= 1.0:
|
||
break
|
||
seg2 = probe.clock_samples[samples1:]
|
||
span2 = ((seg2[-1] - t_res) if (seg2 and t_res is not None) else 0.0)
|
||
rep['resume_after_pause'] = {'clock_at_resume': t_res, 'sim_span': span2,
|
||
'samples': len(seg2),
|
||
'wall_s': round(time.monotonic() - t0, 3)}
|
||
chk('暂停后恢复继续推进', span2 >= 1.0,
|
||
'恢复后 span=%.3f s,%d 个采样' % (span2, len(seg2)))
|
||
|
||
with open(os.path.join(outdir, 'clock_raw.txt'), 'w', encoding='utf-8') as f:
|
||
for i, v in enumerate(probe.clock_samples):
|
||
f.write('%6d %.6f\n' % (i, v))
|
||
rep['clock_sample_count'] = len(probe.clock_samples)
|
||
finally:
|
||
sim.stop()
|
||
probe.close()
|
||
|
||
with open(os.path.join(outdir, 'clock.json'), 'w', encoding='utf-8') as f:
|
||
json.dump(rep, f, ensure_ascii=False, indent=2)
|
||
log('[clock] %s' % ('全部通过' if rep['ok'] else '存在未通过项'))
|
||
return rep
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 阶段三:8 个抽样接触用例
|
||
# -----------------------------------------------------------------------------
|
||
def build_ball_world(base_world_text, cx, cy, cz, cdir):
|
||
ball = BALL_TMPL.format(r='%.6f' % BALL_RADIUS, m='%.6f' % BALL_MASS,
|
||
i='%.10e' % I_BALL, px='%.6f' % cx, py='%.6f' % cy,
|
||
pz='%.6f' % cz, ns=CONTACT_TOPIC_NS)
|
||
txt = base_world_text.replace(' </world>\n', ball + ' </world>\n', 1)
|
||
if txt == base_world_text:
|
||
raise RuntimeError('未能在 world 中插入测试球')
|
||
path = os.path.join(cdir, 'world_ball.sdf')
|
||
with open(path, 'w', encoding='utf-8') as f:
|
||
f.write(txt)
|
||
return path
|
||
|
||
|
||
def judge_physics(cs, rec):
|
||
"""只判物理判据,不碰采集有效性。返回 (ok, reason)。
|
||
|
||
调用前提:调用方已确认采集有效(位姿、订阅、暂停、释放、覆盖)。
|
||
这里只看「接触点是否落在目标面上」或「是否确实没有接触」。
|
||
"""
|
||
others = rec['other_collisions']
|
||
if cs['kind'] == 'none':
|
||
if rec['contact_msg_count'] > 0:
|
||
return False, '期望无场地接触,实际收到 %d 条含接触的消息,对象=%s' % (
|
||
rec['contact_msg_count'], others)
|
||
last_z = rec['final_pose'][2]
|
||
if last_z > -0.10:
|
||
return False, '球末位 z=%.4f 未跌至 -0.10 以下(可能有兜底地板)' % last_z
|
||
return True, '零接触,球末位 z=%.4f < -0.10,无兜底地板' % last_z
|
||
|
||
if not rec['contact_msg_count']:
|
||
return False, ('采集有效(覆盖 %.2f s),但零接触消息;球末位 z=%.4f'
|
||
% (rec.get('sim_collected_s') or 0.0, rec['final_pose'][2]))
|
||
|
||
bad = [n for n in others if n in cs['forbid']]
|
||
if bad:
|
||
return False, '出现禁止的接触对象:%s' % bad
|
||
|
||
want = cs['accept']
|
||
cands = []
|
||
for m in rec['contact_messages']:
|
||
for st in m['states']:
|
||
n1, n2 = short_name(st['collision1']), short_name(st['collision2'])
|
||
other = n2 if n1 in ('collision', 'test_ball') else n1
|
||
if other in want:
|
||
for i, p in enumerate(st['positions']):
|
||
cands.append({'obj': other, 'pos': p,
|
||
't_stamp': m.get('header_stamp'),
|
||
't_clock_recv': m.get('clock_at_recv'),
|
||
'normal': st['normals'][i] if i < len(st['normals']) else None,
|
||
'depth': st['depths'][i] if i < len(st['depths']) else None})
|
||
if not cands:
|
||
return False, '收到 %d 条接触消息,但没有命中目标 %s;实际对象=%s' % (
|
||
rec['contact_msg_count'], want, others)
|
||
|
||
if cs['kind'] == 'plane_z':
|
||
for c in cands:
|
||
dz = abs(c['pos'][2] - cs['surface_z'])
|
||
if dz <= TOL_CONTACT:
|
||
return True, ('接触 %s,世界点(%.4f,%.4f,%.4f),|Δz|=%.6f m ≤ %.3f,'
|
||
'目标接触点 %d 个'
|
||
% (c['obj'], c['pos'][0], c['pos'][1], c['pos'][2],
|
||
dz, TOL_CONTACT, len(cands)))
|
||
c = cands[0]
|
||
return False, '接触点 (%.4f,%.4f,%.4f) 与表面 %.3f 偏差 %.6f m 超 %.3f' % (
|
||
c['pos'][0], c['pos'][1], c['pos'][2], cs['surface_z'],
|
||
abs(c['pos'][2] - cs['surface_z']), TOL_CONTACT)
|
||
|
||
y0, y1 = cs['ramp_y_range']
|
||
for c in cands:
|
||
p = c['pos']
|
||
d = ramp_point_distance(p)
|
||
inx = RAMP_X_RANGE[0] - 0.05 <= p[0] <= RAMP_X_RANGE[1] + 0.05
|
||
iny = y0 - 0.05 <= p[1] <= y1 + 0.05
|
||
if d <= TOL_CONTACT and inx and iny:
|
||
return True, ('接触 %s,世界点(%.4f,%.4f,%.4f),到斜面距离 %.6f m ≤ %.3f;'
|
||
'目标接触点 %d 个,允许沿坡滚动'
|
||
% (c['obj'], p[0], p[1], p[2], d, TOL_CONTACT, len(cands)))
|
||
p = cands[0]['pos']
|
||
return False, ('坡道接触点(%.4f,%.4f,%.4f) 到斜面距离 %.6f m 超 %.3f '
|
||
'或超出坡面范围(x%.2f~%.2f, y%.1f~%.1f)'
|
||
% (p[0], p[1], p[2], ramp_point_distance(p), TOL_CONTACT,
|
||
RAMP_X_RANGE[0], RAMP_X_RANGE[1], y0, y1))
|
||
|
||
|
||
def _gate_fail(rec, stage, reason):
|
||
"""采集有效性门控失败:判 INVALID,不是 FAIL。"""
|
||
rec['status'] = STATUS_INVALID
|
||
rec['invalid_stage'] = stage
|
||
rec['reason'] = reason
|
||
log(' [INVALID] %s' % reason)
|
||
return rec
|
||
|
||
|
||
def run_contact_case(cs, outdir, base_world_text, master=None):
|
||
cdir = ensure_dir(os.path.join(outdir, 'cases', cs['id']))
|
||
rel_z = ((ramp_surface_z(cs['x']) if cs['kind'] == 'ramp' else (cs['surface_z'] or 0.0))
|
||
+ DROP_HEIGHT + BALL_RADIUS)
|
||
world = build_ball_world(base_world_text, cs['x'], cs['y'], rel_z, cdir)
|
||
|
||
rec = {'id': cs['id'], 'label': cs['label'], 'kind': cs['kind'],
|
||
'target_xy': [cs['x'], cs['y']], 'expected': cs['note'],
|
||
'ball_release_pose': [cs['x'], cs['y'], round(rel_z, 6)],
|
||
'accept': cs['accept'], 'forbid': cs['forbid'],
|
||
'status': STATUS_INVALID, 'required_cover_s': REQUIRED_COVER_S,
|
||
'contact_msg_count': 0, 'other_collisions': [],
|
||
'gates': {}}
|
||
|
||
probe = Probe()
|
||
sim = Sim(world, cdir, probe, master=master)
|
||
try:
|
||
# ---- 门 1:仿真实例就绪(只看本实例自己的进程树)
|
||
ok, why = sim.start()
|
||
rec['sim_ready'] = {'ok': ok, 'detail': why, **sim.ready_info}
|
||
rec['gates']['sim_ready'] = ok
|
||
if not ok:
|
||
return _gate_fail(rec, 'sim_ready', 'server 未就绪:%s' % why)
|
||
|
||
# ---- 门 2:订阅就绪
|
||
if not probe.discover_contact_topic(timeout=30.0):
|
||
rec['gates']['subscription_ready'] = False
|
||
return _gate_fail(rec, 'subscription_ready',
|
||
'未发现 gazebo_msgs/ContactsState 话题,接触采集不可用')
|
||
rec['contact_topic'] = probe.contact_topic
|
||
rec['contact_topic_publishers'] = probe.contact_publishers()
|
||
rec['clock_publishers'] = probe.clock_publishers()
|
||
ready = (rec['contact_topic_publishers'] >= 1 and rec['clock_publishers'] == 1)
|
||
rec['gates']['subscription_ready'] = ready
|
||
if not ready:
|
||
return _gate_fail(rec, 'subscription_ready', '订阅未就绪:%r' % {
|
||
'contact_topic': rec['contact_topic'],
|
||
'contact_pub': rec['contact_topic_publishers'],
|
||
'clock_pub': rec['clock_publishers']})
|
||
|
||
# ---- 门 3:暂停确认(Classic 暂停时世界不步进,/clock 不再发布)
|
||
time.sleep(0.3)
|
||
probe.spin(seconds=0.6)
|
||
c_a, v_a = probe.clock_count(), probe.clock_now()
|
||
probe.spin(seconds=1.0)
|
||
c_b, v_b = probe.clock_count(), probe.clock_now()
|
||
paused_ok = (c_b == c_a) or (v_a is not None and v_b is not None
|
||
and abs(v_b - v_a) < 1e-9)
|
||
rec['pause_check'] = {'clock_msgs_1s': c_b - c_a,
|
||
'clock_first': v_a, 'clock_last': v_b}
|
||
rec['paused_confirmed'] = paused_ok
|
||
rec['gates']['pause_confirmed'] = paused_ok
|
||
if not paused_ok:
|
||
return _gate_fail(rec, 'pause_confirmed',
|
||
'暂停未确认:1 s 内 clock 增加 %d 条(%r → %r)'
|
||
% (c_b - c_a, v_a, v_b))
|
||
|
||
# ---- 门 4:释放前位姿(有界重试,逐次留证)
|
||
pre, pre_diag = query_pose('test_ball', sim.env)
|
||
rec['pose_query_initial'] = pre_diag
|
||
rec['ball_initial_pose_observed'] = pre
|
||
if pre is None:
|
||
rec['gates']['initial_pose'] = False
|
||
return _gate_fail(rec, 'initial_pose',
|
||
'释放前位姿查询失败(%d 次尝试,最后原因:%s)'
|
||
% (pre_diag['attempts_used'], pre_diag.get('reason')))
|
||
drift = math.sqrt(sum((pre[i] - (cs['x'], cs['y'], rel_z)[i]) ** 2
|
||
for i in range(3)))
|
||
rec['initial_pose_drift_m'] = drift
|
||
rec['gates']['initial_pose'] = (drift <= MAX_INITIAL_DRIFT)
|
||
if drift > MAX_INITIAL_DRIFT:
|
||
return _gate_fail(rec, 'initial_pose',
|
||
'释放前位姿与设定偏差 %.6f m 超 %.6f m(实测 %r vs 设定 %r)'
|
||
% (drift, MAX_INITIAL_DRIFT, pre,
|
||
[cs['x'], cs['y'], round(rel_z, 6)]))
|
||
|
||
# ---- 门 5:释放
|
||
n_clock_before_release = probe.clock_count()
|
||
rec['clock_msgs_before_release'] = n_clock_before_release
|
||
rec['clock_before_release'] = probe.clock_now()
|
||
ok_u, method, detail = probe.call_pause(False, sim.env)
|
||
rec['release'] = {'ok': ok_u, 'method': method, 'detail': detail}
|
||
rec['gates']['release'] = ok_u
|
||
if not ok_u:
|
||
return _gate_fail(rec, 'release', '释放失败:%s %s' % (method, detail))
|
||
|
||
# 释放时刻的仿真时间 = 0.0:世界以 paused:=true 启动且从未步进,
|
||
# 释放前 clock 消息数为 0 即为此事的正证(不是「假设」)。
|
||
t_rel = 0.0
|
||
rec['release_sim_time'] = t_rel
|
||
rec['release_sim_time_basis'] = (
|
||
'paused:=true 启动、释放前世界从未步进;释放前收到 clock 消息 %d 条,故释放瞬间 sim=%.1f'
|
||
% (n_clock_before_release, t_rel))
|
||
|
||
# ---- 门 6:采集覆盖到规定时长(仿真时间),且订阅在释放前后都活着
|
||
t0 = time.monotonic()
|
||
wall_timeout_hit = False
|
||
while True:
|
||
probe.rclpy.spin_once(probe.node, timeout_sec=0.02)
|
||
cur = probe.clock_now()
|
||
if cur is not None and cur - t_rel >= REQUIRED_COVER_S:
|
||
break
|
||
if time.monotonic() - t0 > 90.0:
|
||
wall_timeout_hit = True
|
||
break
|
||
probe.spin(seconds=0.3)
|
||
rec['clock_after_collect'] = probe.clock_now()
|
||
rec['sim_collected_s'] = ((rec['clock_after_collect'] or 0.0) - t_rel)
|
||
rec['collect_wall_s'] = round(time.monotonic() - t0, 3)
|
||
rec['wall_timeout_hit'] = wall_timeout_hit
|
||
rec['first_clock_after_release'] = (
|
||
probe.clock_samples[n_clock_before_release]
|
||
if len(probe.clock_samples) > n_clock_before_release else None)
|
||
|
||
# bumper 插件会周期性发 states=[] 的**空** ContactsState,暂停期间也照发。
|
||
# 「收到几条消息」≠「发生几次接触」,只统计 states 非空的。
|
||
nonempty = [m for m in probe.contacts if m['states']]
|
||
rec['bumper_msg_total'] = len(probe.contacts)
|
||
pre_msgs = sum(1 for m in nonempty
|
||
if m.get('header_stamp') is not None
|
||
and m['header_stamp'] <= t_rel + 1e-9)
|
||
rec['contact_msgs_before_release'] = pre_msgs
|
||
rec['contact_msgs_after_release'] = len(nonempty) - pre_msgs
|
||
|
||
covers = (not wall_timeout_hit
|
||
and rec['sim_collected_s'] >= REQUIRED_COVER_S - 1e-6
|
||
and n_clock_before_release == 0
|
||
and rec['first_clock_after_release'] is not None)
|
||
rec['collection_covers_release'] = covers
|
||
rec['gates']['coverage'] = covers
|
||
if not covers:
|
||
return _gate_fail(rec, 'coverage',
|
||
'采集无效:要求释放前后覆盖且仿真时长 ≥ %.1f s,实测 %.3f s'
|
||
'(墙钟超时=%s,释放前 clock 消息=%d)'
|
||
% (REQUIRED_COVER_S, rec['sim_collected_s'],
|
||
wall_timeout_hit, n_clock_before_release))
|
||
|
||
# ---- 门 7:末位姿(K08 的物理判据要用;取不到即采集无效)
|
||
post, post_diag = query_pose('test_ball', sim.env)
|
||
rec['pose_query_final'] = post_diag
|
||
rec['final_pose'] = post
|
||
rec['gates']['final_pose'] = post is not None
|
||
if post is None:
|
||
return _gate_fail(rec, 'final_pose',
|
||
'末位姿查询失败(%d 次尝试,最后原因:%s)'
|
||
% (post_diag['attempts_used'], post_diag.get('reason')))
|
||
|
||
# ---- 汇总接触(时间优先用消息 header_stamp)
|
||
rec['contact_msg_count'] = len(nonempty)
|
||
others = set()
|
||
for m in nonempty:
|
||
for st in m['states']:
|
||
n1, n2 = short_name(st['collision1']), short_name(st['collision2'])
|
||
others.add(n2 if n1 in ('collision', 'test_ball') else n1)
|
||
others.discard('test_ball')
|
||
others.discard('collision')
|
||
rec['other_collisions'] = sorted(others)
|
||
rec['contact_messages'] = nonempty
|
||
|
||
first = None
|
||
for m in nonempty:
|
||
for st in m['states']:
|
||
n1, n2 = short_name(st['collision1']), short_name(st['collision2'])
|
||
other = n2 if n1 in ('collision', 'test_ball') else n1
|
||
if other in ('test_ball', 'collision'):
|
||
continue
|
||
stamp = m.get('header_stamp')
|
||
first = {'obj': other,
|
||
'pos': st['positions'][0] if st['positions'] else None,
|
||
'normal': st['normals'][0] if st['normals'] else None,
|
||
'frame_id': m['frame_id'],
|
||
'header_stamp': stamp,
|
||
't_rel_release': ((stamp - t_rel) if stamp is not None else None),
|
||
't_source': ('header_stamp' if stamp is not None
|
||
else 'clock_at_recv(该消息无 header stamp)'),
|
||
'clock_at_recv': m.get('clock_at_recv')}
|
||
break
|
||
if first:
|
||
break
|
||
rec['first_contact'] = first
|
||
rec['expected_free_fall_s'] = round(T_FREE_FALL, 4)
|
||
if first and first.get('t_rel_release') is not None:
|
||
d = first['t_rel_release'] - T_FREE_FALL
|
||
rec['first_contact_minus_freefall_s'] = round(d, 4)
|
||
rec['first_contact_consistent'] = abs(d) <= 0.01 + 1e-9
|
||
|
||
# ---- 物理判据
|
||
ok_p, reason = judge_physics(cs, rec)
|
||
rec['status'] = STATUS_PASS if ok_p else STATUS_FAIL
|
||
rec['judgement'] = reason
|
||
return rec
|
||
finally:
|
||
sim.stop()
|
||
rec['teardown'] = sim.teardown_info
|
||
probe.close()
|
||
|
||
|
||
def stage_contacts(outdir, only=None, master=None):
|
||
ensure_dir(outdir)
|
||
rep = {'stage': 'contacts', 'tool_sha256': sha256_file(os.path.abspath(__file__)),
|
||
'required_cover_s': REQUIRED_COVER_S,
|
||
'max_initial_drift_m': MAX_INITIAL_DRIFT,
|
||
'cases': [], 'ok': True,
|
||
'counts': {STATUS_PASS: 0, STATUS_FAIL: 0, STATUS_INVALID: 0}}
|
||
todo = [c for c in CASES if not only or c['id'] in only]
|
||
log('[contacts] 抽样接触用例 %d 个:%s'
|
||
% (len(todo), ', '.join(c['id'] for c in todo)))
|
||
base_world_text = open(os.path.join(WS, 'src', PKG, WORLD_REL), encoding='utf-8').read()
|
||
|
||
for cs in todo:
|
||
log('[RUN] %s %s (%s, %s) %s' % (cs['id'], cs['label'], cs['x'], cs['y'], cs['note']))
|
||
if not wait_master_free(uri=master):
|
||
rec = {'id': cs['id'], 'label': cs['label'], 'kind': cs['kind'],
|
||
'status': STATUS_INVALID, 'invalid_stage': 'sim_ready',
|
||
'reason': 'master 端口 %d 被占用,本工具不去动它,直接判采集无效'
|
||
% master_port(master),
|
||
'contact_msg_count': 0, 'other_collisions': []}
|
||
else:
|
||
try:
|
||
rec = run_contact_case(cs, outdir, base_world_text, master=master)
|
||
except Exception as exc:
|
||
import traceback
|
||
rec = {'id': cs['id'], 'label': cs['label'], 'kind': cs['kind'],
|
||
'status': STATUS_INVALID, 'invalid_stage': 'exception',
|
||
'reason': '运行异常:%r' % (exc,),
|
||
'traceback': traceback.format_exc(),
|
||
'contact_msg_count': 0, 'other_collisions': []}
|
||
cdir = ensure_dir(os.path.join(outdir, 'cases', cs['id']))
|
||
full = rec.pop('contact_messages', [])
|
||
# 球落定后会持续产生接触消息(500 Hz × 2 s 可达数万条)。
|
||
# 落盘保留:全部前 300 条(覆盖释放→首接触→初始滚动)+ 之后每 50 条取 1 条,
|
||
# 并记录总条数,保证「首接触段完整、全程可追溯」又不产生几十 MB 的冗余文件。
|
||
raw = full[:300] + full[300::50]
|
||
rec['contact_msgs_total'] = len(full)
|
||
rec['contact_msgs_stored'] = len(raw)
|
||
rec['contacts_raw_sampling'] = ('前 300 条逐条 + 之后每 50 条取 1 条'
|
||
if len(full) > 300 else '逐条全存')
|
||
with open(os.path.join(cdir, 'contacts_raw.json'), 'w', encoding='utf-8') as f:
|
||
json.dump(raw, f, ensure_ascii=False, indent=1)
|
||
with open(os.path.join(cdir, 'case.json'), 'w', encoding='utf-8') as f:
|
||
json.dump(rec, f, ensure_ascii=False, indent=2)
|
||
rec['contact_messages'] = raw
|
||
log(' -> %s(接触消息 %d 条,落盘 %d 条)'
|
||
% (rec['status'], rec['contact_msgs_total'], rec['contact_msgs_stored']))
|
||
log(' %s' % ((rec.get('judgement') or rec.get('reason') or '')[:200],))
|
||
rep['counts'][rec['status']] = rep['counts'].get(rec['status'], 0) + 1
|
||
rep['cases'].append(rec)
|
||
|
||
slim = []
|
||
for r in rep['cases']:
|
||
slim.append({k: v for k, v in r.items() if k != 'contact_messages'})
|
||
# ok 只代表「全部 PASS 且没有 INVALID」
|
||
rep['ok'] = (all(r['status'] == STATUS_PASS for r in slim) and bool(slim))
|
||
with open(os.path.join(outdir, 'contacts.json'), 'w', encoding='utf-8') as f:
|
||
json.dump({'stage': 'contacts', 'tool_sha256': rep['tool_sha256'],
|
||
'required_cover_s': REQUIRED_COVER_S,
|
||
'max_initial_drift_m': MAX_INITIAL_DRIFT,
|
||
'ok': rep['ok'], 'counts': rep['counts'], 'cases': slim},
|
||
f, ensure_ascii=False, indent=2)
|
||
log('[contacts] PASS %d / FAIL %d / INVALID %d'
|
||
% (rep['counts'].get(STATUS_PASS, 0), rep['counts'].get(STATUS_FAIL, 0),
|
||
rep['counts'].get(STATUS_INVALID, 0)))
|
||
rep['cases'] = slim
|
||
return rep
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 报告
|
||
# -----------------------------------------------------------------------------
|
||
def load_json_or_none(path):
|
||
if not os.path.exists(path):
|
||
return None
|
||
try:
|
||
with open(path, encoding='utf-8') as f:
|
||
return json.load(f)
|
||
except (OSError, ValueError):
|
||
return None
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 最终判定:本轮证据优先、旧证据补缺;8 个预期用例逐项算最终状态
|
||
# -----------------------------------------------------------------------------
|
||
# 旧版工具曾把状态拼成 'FAILD'(字符串拼接产物),其记录的 reason 是
|
||
# 「采集/暂停前置条件不满足」,语义属于**采集无效**,不是物理判据失败。
|
||
# 这里显式映射并保留原始字符串,绝不允许把非 PASS 含糊成 PASS。
|
||
LEGACY_STATUS_MAP = {
|
||
'PASS': STATUS_PASS,
|
||
'FAIL': STATUS_FAIL,
|
||
'FAILD': STATUS_INVALID,
|
||
'INVALID': STATUS_INVALID,
|
||
}
|
||
|
||
STATUS_MISSING = 'MISSING'
|
||
|
||
STAGE_CANDIDATES = {
|
||
'assets': [os.path.join('assets', 'assets.json'), 'assets.json'],
|
||
'clock': [os.path.join('clock', 'clock.json')],
|
||
'contacts': [os.path.join('contacts', 'contacts.json')],
|
||
'isolation': [os.path.join('isolation', 'isolation.json')],
|
||
}
|
||
|
||
STAGE_CN = {'assets': '资源核对', 'clock': '时钟与暂停', 'isolation': '进程隔离验证'}
|
||
|
||
|
||
def normalize_status(raw):
|
||
"""把任意来源的 status 归一到三态。
|
||
|
||
识别不了的字符串一律按 INVALID 处理——「不认识」不能当成「通过」,
|
||
也不能当成「有效测试失败」。
|
||
"""
|
||
key = (raw or '').strip().upper()
|
||
return LEGACY_STATUS_MAP.get(key, STATUS_INVALID)
|
||
|
||
|
||
def _label_of(path):
|
||
return os.path.basename(os.path.abspath(path).rstrip('/')) or path
|
||
|
||
|
||
def build_sources(outroot, prevs=None):
|
||
"""证据源列表,按优先级排序:本轮 → 较近旧轮次 → 更早旧轮次。"""
|
||
dirs = [os.path.abspath(outroot)]
|
||
for p in (prevs or []):
|
||
if not p:
|
||
continue
|
||
ap = os.path.abspath(str(p).strip())
|
||
if ap and ap not in dirs:
|
||
dirs.append(ap)
|
||
out = []
|
||
for i, d in enumerate(dirs):
|
||
out.append({'index': i, 'kind': 'current' if i == 0 else 'prev',
|
||
'label': _label_of(d), 'dir': d})
|
||
return out
|
||
|
||
|
||
def resolve_stage(sources, stage):
|
||
"""按优先级找某阶段的 JSON。返回 (data, source) 或 (None, None)。"""
|
||
for src in sources:
|
||
for rel in STAGE_CANDIDATES[stage]:
|
||
d = load_json_or_none(os.path.join(src['dir'], rel))
|
||
if d is not None:
|
||
return d, src
|
||
return None, None
|
||
|
||
|
||
def resolve_cases(sources):
|
||
"""逐用例解析最终状态。
|
||
|
||
规则(与任务书一致):
|
||
1. 本轮有该用例 → 用本轮结果;**本轮是 INVALID/FAIL 也不被旧 PASS 覆盖**;
|
||
2. 本轮没有 → 按优先级到旧轮次找,找到就用;旧证据里的非 PASS 原样保留;
|
||
3. 都没有 → MISSING(缺失)。
|
||
"""
|
||
loaded = []
|
||
for src in sources:
|
||
d = None
|
||
for rel in STAGE_CANDIDATES['contacts']:
|
||
d = load_json_or_none(os.path.join(src['dir'], rel))
|
||
if d is not None:
|
||
break
|
||
cases = {}
|
||
if d:
|
||
for c in (d.get('cases') or []):
|
||
if c.get('id'):
|
||
cases[c['id']] = c
|
||
loaded.append((src, d, cases))
|
||
|
||
rows = []
|
||
for cs in CASES:
|
||
cid = cs['id']
|
||
row = {'id': cid, 'label': cs['label'], 'note': cs.get('note'),
|
||
'status': STATUS_MISSING, 'status_raw': None,
|
||
'source_label': None, 'source_kind': None, 'source_dir': None,
|
||
'data_tool': None, 'reason': None, 'case': None}
|
||
for src, d, cases in loaded:
|
||
if cid in cases:
|
||
c = cases[cid]
|
||
row.update({
|
||
'status': normalize_status(c.get('status')),
|
||
'status_raw': c.get('status'),
|
||
'source_label': src['label'],
|
||
'source_kind': src['kind'],
|
||
'source_dir': src['dir'],
|
||
'data_tool': (d or {}).get('tool_sha256'),
|
||
'reason': c.get('judgement') or c.get('reason'),
|
||
'case': c,
|
||
})
|
||
break
|
||
rows.append(row)
|
||
return rows, loaded
|
||
|
||
|
||
def compute_outcome(outroot, prevs=None):
|
||
"""算出最终判定与退出码。报告与命令退出码都用这一个结果,避免两套口径。
|
||
|
||
优先级:缺失/无效/不完整(40)> 有效测试失败(30)> 全部满足(0)。
|
||
理由:结果集里有无效或缺失项时,结论本身不可用,不能报成「有效测试失败」。
|
||
"""
|
||
sources = build_sources(outroot, prevs)
|
||
rows, loaded = resolve_cases(sources)
|
||
counts = {STATUS_PASS: 0, STATUS_FAIL: 0, STATUS_INVALID: 0, STATUS_MISSING: 0}
|
||
for r in rows:
|
||
counts[r['status']] += 1
|
||
|
||
stages = {}
|
||
for name in ('assets', 'clock', 'isolation'):
|
||
d, src = resolve_stage(sources, name)
|
||
stages[name] = {'data': d, 'source': src, 'present': d is not None,
|
||
'ok': bool(d and d.get('ok'))}
|
||
|
||
gui, gui_src = None, None
|
||
for src in sources:
|
||
g = load_gui_status(src['dir'])
|
||
if g is not None:
|
||
gui, gui_src = g, src
|
||
break
|
||
|
||
invalid, failed = [], []
|
||
for r in rows:
|
||
if r['status'] == STATUS_MISSING:
|
||
invalid.append('%s %s:**无任何轮次证据**(缺失)' % (r['id'], r['label']))
|
||
elif r['status'] == STATUS_INVALID:
|
||
invalid.append('%s %s:**采集无效**(原始状态 `%s`,来源 `%s`)——'
|
||
'不得判为通过,也不得判为碰撞失败'
|
||
% (r['id'], r['label'], r['status_raw'], r['source_label']))
|
||
elif r['status'] == STATUS_FAIL:
|
||
failed.append('%s %s:**有效测试失败**(来源 `%s`)——%s'
|
||
% (r['id'], r['label'], r['source_label'], r['reason'] or ''))
|
||
|
||
for name in ('assets', 'clock', 'isolation'):
|
||
st = stages[name]
|
||
cn = STAGE_CN[name]
|
||
if not st['present']:
|
||
invalid.append('%s 阶段(`%s`):**无任何轮次证据**' % (cn, name))
|
||
elif not st['ok']:
|
||
failed.append('%s 阶段(`%s`):存在未通过项(来源 `%s`)'
|
||
% (cn, name, st['source']['label']))
|
||
|
||
if invalid:
|
||
code = EXIT_INVALID
|
||
elif failed:
|
||
code = EXIT_FAIL
|
||
else:
|
||
code = EXIT_OK
|
||
|
||
problems = ['[缺失/无效] ' + x for x in invalid] + ['[失败] ' + x for x in failed]
|
||
return {'code': code, 'sources': sources, 'case_rows': rows,
|
||
'case_counts': counts, 'stages': stages, 'gui': gui,
|
||
'gui_source': gui_src, 'invalid': invalid, 'failed': failed,
|
||
'problems': problems, 'contacts_sources': loaded}
|
||
|
||
|
||
def code_label(code):
|
||
return {EXIT_OK: '全部满足(0)',
|
||
EXIT_FAIL: '有效测试失败(30)',
|
||
EXIT_INVALID: '缺失 / 无效 / 报告不完整(40)'}.get(code, '未知(%s)' % code)
|
||
|
||
|
||
def _fmt_t(c):
|
||
fc = c.get('first_contact') or {}
|
||
if fc.get('t_rel_release') is None:
|
||
return '—'
|
||
return '%.4f' % fc['t_rel_release']
|
||
|
||
|
||
def _short_hash(h):
|
||
return ('`%s…`' % h[:16]) if h else '—'
|
||
|
||
|
||
def write_report(outroot, prev=None, prevs=None):
|
||
"""按磁盘上的实际证据生成报告,返回 (退出码, 问题清单)。
|
||
|
||
- 8 个用例逐项按「本轮优先、旧证据补缺」算最终状态;
|
||
- 未执行 / 无效 / 缺失一律不写通过;
|
||
- 退出码与报告结论同源(compute_outcome),不另设一套判断。
|
||
"""
|
||
plist = list(prevs or [])
|
||
if prev:
|
||
plist = [prev] + plist
|
||
out = compute_outcome(outroot, plist)
|
||
sources = out['sources']
|
||
rows = out['case_rows']
|
||
counts = out['case_counts']
|
||
stages = out['stages']
|
||
cur_tool = sha256_file(os.path.abspath(__file__))
|
||
|
||
# 本证据目录自己的(可能是空)阶段数据,用于 §3 说明「本轮到底跑了什么」
|
||
own_contacts = load_json_or_none(os.path.join(outroot, 'contacts', 'contacts.json'))
|
||
|
||
L = []
|
||
A = L.append
|
||
A('# Gazebo Classic 基线检查报告(%s)' % TASK_ID)
|
||
A('')
|
||
A('- 当前报告工具 sha256:`%s`' % cur_tool)
|
||
A('- 证据根目录:`%s`' % outroot)
|
||
A('- master:`%s`;`ROS_DOMAIN_ID=%s`;`ROS_LOCALHOST_ONLY=1`' % (MASTER, ROS_DOMAIN))
|
||
A('- 球:r=%.3f m,m=%.3f kg,I=2/5·m·r²=%.6e kg·m²;释放高度=表面上方 %.2f m'
|
||
% (BALL_RADIUS, BALL_MASS, I_BALL, DROP_HEIGHT))
|
||
A('- 时间基准:`/clock`(`rosgraph_msgs/msg/Clock`),墙钟只用于超时')
|
||
A('- 接触时刻:优先用消息自带的 `header_stamp`(仿真时间);`clock_at_recv` 只作'
|
||
'「收到时最近一次 clock」,不当作精确接触时刻。')
|
||
A('')
|
||
A('**证据源优先级**:%s' % ' → '.join(
|
||
'本轮 `%s`' % s['label'] if s['kind'] == 'current' else '旧轮次 `%s`' % s['label']
|
||
for s in sources))
|
||
A('')
|
||
A('### 数据采集工具哈希(原样保留)')
|
||
A('')
|
||
A('同一阶段的数据可能出自不同轮次;下表按「实际采用了哪份数据」列出,便于复核来源。')
|
||
A('')
|
||
A('| 采用的数据 | 证据源 | 阶段 | 采集工具 sha256 |')
|
||
A('|---|---|---|---|')
|
||
used_tools = []
|
||
for name in ('assets', 'clock', 'isolation'):
|
||
d = stages[name]['data']
|
||
if d is None:
|
||
continue
|
||
h = d.get('tool_sha256')
|
||
used_tools.append(h)
|
||
A('| %s | `%s` | `%s` | %s |' % (STAGE_CN[name], stages[name]['source']['label'],
|
||
name, ('`%s`' % h) if h else '未记录'))
|
||
contrib = {}
|
||
for r in rows:
|
||
if r['source_label']:
|
||
contrib.setdefault((r['source_label'], r['data_tool']), []).append(r['id'])
|
||
for (lbl, h), ids in sorted(contrib.items(), key=lambda kv: kv[0][0]):
|
||
used_tools.append(h)
|
||
A('| 接触用例 %s | `%s` | `contacts` | %s |'
|
||
% ('、'.join(ids), lbl, ('`%s`' % h) if h else '未记录'))
|
||
A('')
|
||
differs = any(h and h != cur_tool for h in used_tools)
|
||
if differs:
|
||
A('> 采集工具与当前报告工具**版本不同**:按任务约定**不因版本不同重跑物理测试**,'
|
||
'原有数据哈希与原始消息一律保留、原样引用。')
|
||
A('')
|
||
|
||
# ---- 0 最终判定
|
||
A('## 0. 最终判定')
|
||
A('')
|
||
A('| 项 | 值 |')
|
||
A('|---|---|')
|
||
A('| 8 个预期用例最终状态 | PASS %d / FAIL %d / INVALID %d / 缺失 %d |'
|
||
% (counts[STATUS_PASS], counts[STATUS_FAIL], counts[STATUS_INVALID],
|
||
counts[STATUS_MISSING]))
|
||
A('| 退出码 | **%d**(%s) |' % (out['code'], code_label(out['code'])))
|
||
A('')
|
||
if out['problems']:
|
||
A('未满足项:')
|
||
A('')
|
||
for p in out['problems']:
|
||
A('- %s' % p)
|
||
else:
|
||
A('未满足项:无(8 个用例全部 PASS,资源/时钟/隔离三段证据齐备且通过)。')
|
||
A('')
|
||
|
||
# ---- 1 资源
|
||
A('## 1. 资源核对')
|
||
A('')
|
||
st = stages['assets']
|
||
if not st['present']:
|
||
A('**无任何轮次证据**(本轮与各旧轮次都没有 `assets/assets.json`)')
|
||
else:
|
||
A('证据来源:**`%s`**%s' % (
|
||
st['source']['label'],
|
||
'(本轮未复测,沿用旧证据)' if st['source']['kind'] == 'prev' else '(本轮)'))
|
||
A('')
|
||
A('| 检查项 | 结果 | 说明 |')
|
||
A('|---|---|---|')
|
||
for c in st['data'].get('checks') or []:
|
||
A('| %s | %s | %s |' % (c['name'], '通过' if c.get('ok') else '**未通过**',
|
||
c.get('detail')))
|
||
A('')
|
||
A('| 文件 | SHA256 | 一致 |')
|
||
A('|---|---|---|')
|
||
for rel, h in sorted((st['data'].get('model_hashes') or {}).items()):
|
||
A('| `%s` | `%s` | %s |' % (rel, h.get('package'),
|
||
'一致' if h.get('equal')
|
||
else '**不同**(' + h.get('note', '') + ')'))
|
||
A('')
|
||
|
||
# ---- 2 时钟
|
||
A('## 2. 时钟与暂停')
|
||
A('')
|
||
st = stages['clock']
|
||
if not st['present']:
|
||
A('**无任何轮次证据**(本轮与各旧轮次都没有 `clock/clock.json`)')
|
||
else:
|
||
A('证据来源:**`%s`**%s' % (
|
||
st['source']['label'],
|
||
'(本轮未复测,沿用旧证据)' if st['source']['kind'] == 'prev' else '(本轮)'))
|
||
A('')
|
||
A('| 检查项 | 结果 | 说明 |')
|
||
A('|---|---|---|')
|
||
for c in st['data'].get('checks') or []:
|
||
A('| %s | %s | %s |' % (c['name'], '通过' if c.get('ok') else '**未通过**',
|
||
c.get('detail')))
|
||
A('')
|
||
po = st['data'].get('pause_observe') or {}
|
||
ro = st['data'].get('run_observe') or {}
|
||
ra = st['data'].get('resume_after_pause') or {}
|
||
A('- 暂停接口:`%s` → `%s`' % ((st['data'].get('pause') or {}).get('method'),
|
||
(st['data'].get('pause') or {}).get('detail')))
|
||
A('- 恢复接口:`%s` → `%s`' % ((st['data'].get('unpause') or {}).get('method'),
|
||
(st['data'].get('unpause') or {}).get('detail')))
|
||
if ro:
|
||
A('- 连续运行:仿真跨度 %.3f s,%d 个采样,倒退 %d 次,墙钟 %.2f s'
|
||
% (ro['sim_span'], ro['samples'], ro['regressions'], ro['wall_s']))
|
||
if po:
|
||
A('- 暂停期间:墙钟 %.2f s,仿真 %.6f → %.6f(推进 %.9f s),收到 %d 条 clock'
|
||
% (po['wall_s'], po['clock_at_pause_start'] or 0,
|
||
po['clock_at_pause_end'] or 0, po['sim_advanced'],
|
||
po['clock_msgs_during_pause']))
|
||
if ra:
|
||
A('- 暂停后恢复:span=%.3f s,%d 个采样' % (ra['sim_span'], ra['samples']))
|
||
if st['data'].get('log_headless_render_notes'):
|
||
A('')
|
||
A('> headless 下出现渲染相关日志(不算资源/插件错误):`%s`。GUI 另见 §5。'
|
||
% '`, `'.join(st['data']['log_headless_render_notes']))
|
||
A('')
|
||
|
||
# ---- 3 本轮接触
|
||
A('## 3. 本证据目录的接触执行情况')
|
||
A('')
|
||
if own_contacts is None:
|
||
A('本证据目录没有 `contacts/contacts.json`:**本轮未执行接触用例**'
|
||
'(本轮只做报告判定收尾,未启动仿真)。最终状态见 §6。')
|
||
else:
|
||
A('本轮执行用例:%s' % '、'.join(
|
||
'%s(%s)' % (c.get('id'), c.get('status'))
|
||
for c in own_contacts.get('cases') or []))
|
||
A('')
|
||
A('| 用例 | 目标 | 释放位姿(x,y,z) | 初始位姿 | 门控 | 覆盖(s) | 首接触 t(s) | '
|
||
'接触对象 | 世界接触点 | 判定 |')
|
||
A('|---|---|---|---|---|---|---|---|---|---|')
|
||
for c in own_contacts.get('cases') or []:
|
||
ip = c.get('ball_initial_pose_observed')
|
||
fc = c.get('first_contact') or {}
|
||
p = fc.get('pos')
|
||
rp = c.get('ball_release_pose') or [0, 0, 0]
|
||
gates = c.get('gates') or {}
|
||
A('| %s | %s | (%.3f,%.3f,%.3f) | %s | %s | %s | %s | %s | %s | **%s** |' % (
|
||
c.get('id'), c.get('label'), rp[0], rp[1], rp[2],
|
||
'有效' if ip else '缺失',
|
||
('全过' if (gates and all(gates.values())) else
|
||
('门控失败@%s' % c.get('invalid_stage') if c.get('invalid_stage') else '—')),
|
||
('%.2f' % c['sim_collected_s']) if c.get('sim_collected_s') is not None else '—',
|
||
_fmt_t(c), fc.get('obj') or '—',
|
||
('(%.4f,%.4f,%.4f)' % tuple(p)) if p else '—',
|
||
c.get('status')))
|
||
A('')
|
||
A('### 逐项结论')
|
||
A('')
|
||
for c in own_contacts.get('cases') or []:
|
||
A('- **%s %s**(%s):%s' % (c.get('id'), c.get('label'), c.get('status'),
|
||
c.get('judgement') or c.get('reason', '')))
|
||
A('')
|
||
A('### 位姿查询留证(有界重试)')
|
||
A('')
|
||
for c in own_contacts.get('cases') or []:
|
||
for key, tag in (('pose_query_initial', '释放前'), ('pose_query_final', '末位姿')):
|
||
q = c.get(key) or {}
|
||
if not q:
|
||
continue
|
||
A('- %s %s:%d/%d 次,耗时 %.2f s,最终 `%s`%s'
|
||
% (c.get('id'), tag, q.get('attempts_used', 0), q.get('attempts_allowed', 0),
|
||
q.get('elapsed_s', 0.0), q.get('final_result'),
|
||
(';最后原因:%s' % q['reason']) if q.get('final_result') != 'ok' else ''))
|
||
A('')
|
||
A('### 每用例收尾记录(只动本实例子进程)')
|
||
A('')
|
||
for c in own_contacts.get('cases') or []:
|
||
t = c.get('teardown') or {}
|
||
if not t:
|
||
continue
|
||
A('- %s:root_pid=%s;启动阶段确认的子进程=%s;SIGTERM 进程组=%s;'
|
||
'逐个 SIGTERM=%s;SIGKILL=%s;端口释放=%s;耗时 %.2f s;未触碰未知 PID'
|
||
% (c.get('id'), t.get('root_pid'), t.get('known_pids_at_stop'),
|
||
t.get('killed_process_group'), t.get('sigterm_pids') or '无',
|
||
t.get('sigkill_pids') or '无', t.get('port_free_after_stop'),
|
||
t.get('teardown_s') or 0.0))
|
||
A('')
|
||
|
||
# ---- 4 进程隔离
|
||
A('## 4. 进程隔离验证')
|
||
A('')
|
||
st = stages['isolation']
|
||
if not st['present']:
|
||
A('**无任何轮次证据**')
|
||
else:
|
||
A('证据来源:**`%s`**%s' % (
|
||
st['source']['label'],
|
||
'(本轮未复测,沿用旧证据)' if st['source']['kind'] == 'prev' else '(本轮)'))
|
||
A('')
|
||
d = st['data']
|
||
A('| 项 | 值 |')
|
||
A('|---|---|')
|
||
A('| 隔离 server 端口 / PID | %s / %s |' % (d.get('iso_port'), d.get('iso_pid')))
|
||
A('| 工具实例端口 | %s |' % d.get('tool_port'))
|
||
A('| 工具实例收尾后隔离 server 仍存活 | **%s** |'
|
||
% ('是' if d.get('iso_survived_tool_teardown') else '否'))
|
||
A('| 隔离 server 端口仍可连通 | %s |' % ('是' if d.get('iso_port_still_open') else '否'))
|
||
A('| 隔离 PID 是否进入工具实例树 | %s |'
|
||
% ('**是**' if d.get('iso_pid_in_tool_tree') else '否'))
|
||
A('| 按记录 PID 清理 | %s |' % ('完成' if d.get('iso_cleaned') else '未完成'))
|
||
A('')
|
||
if d.get('note'):
|
||
A('%s' % d['note'])
|
||
A('')
|
||
|
||
# ---- 5 GUI
|
||
A('## 5. GUI 画面')
|
||
A('')
|
||
if out['gui'] is not None and out['gui_source'] is not None \
|
||
and out['gui_source']['kind'] == 'prev':
|
||
A('证据来源:**`%s`**(本轮未重新采集)' % out['gui_source']['label'])
|
||
A('')
|
||
A(render_gui_note(out['gui']))
|
||
A('')
|
||
|
||
# ---- 6 最终状态表
|
||
A('## 6. 8 个预期用例:最终状态与证据来源')
|
||
A('')
|
||
A('规则:本轮有该用例就用本轮(本轮无效**不**被旧 PASS 覆盖);本轮没有则按优先级取旧证据;'
|
||
'都没有记「缺失」。原始状态字符串原样保留。')
|
||
A('')
|
||
A('| 用例 | 目标 | 最终状态 | 原始状态 | 证据来源 | 采集工具 sha256 | 说明 |')
|
||
A('|---|---|---|---|---|---|---|')
|
||
for r in rows:
|
||
mark = r['status']
|
||
if r['status'] != STATUS_PASS:
|
||
mark = '**%s**' % r['status']
|
||
A('| %s | %s | %s | %s | %s | %s | %s |' % (
|
||
r['id'], r['label'], mark,
|
||
('`%s`' % r['status_raw']) if r['status_raw'] else '—',
|
||
('`%s`' % r['source_label']) if r['source_label'] else '—',
|
||
_short_hash(r['data_tool']),
|
||
(r['reason'] or '').replace('|', '/')[:160] if r['status'] != STATUS_PASS
|
||
else (r['note'] or '')))
|
||
A('')
|
||
re_tested = [r['id'] for r in rows if r['source_kind'] == 'current']
|
||
borrowed = [r['id'] for r in rows if r['source_kind'] == 'prev']
|
||
A('- 本证据目录实际执行:%s' % ('、'.join(re_tested) if re_tested else '无'))
|
||
A('- 沿用旧轮次证据:%s' % ('、'.join(borrowed) if borrowed else '无'))
|
||
A('- **不得**把本目录的结果表述为独立重测了全部 8 个用例。')
|
||
A('')
|
||
A('### 与旧轮的差异(同一用例在不同轮次的状态)')
|
||
A('')
|
||
diffs = []
|
||
for r in rows:
|
||
for src, d, cases in out['contacts_sources']:
|
||
if src['kind'] == 'current':
|
||
continue
|
||
c = cases.get(r['id'])
|
||
if c is None:
|
||
continue
|
||
old = normalize_status(c.get('status'))
|
||
if old != r['status']:
|
||
diffs.append((r['id'], src['label'], c.get('status'), r['status'],
|
||
r['source_label']))
|
||
if diffs:
|
||
A('| 用例 | 旧轮次 | 旧状态 | 最终状态 | 依据 |')
|
||
A('|---|---|---|---|---|')
|
||
for cid, lbl, oldraw, final, bysrc in diffs:
|
||
A('| %s | `%s` | `%s` | **%s** | `%s` |' % (cid, lbl, oldraw, final, bysrc))
|
||
else:
|
||
A('无(各轮次状态一致,或旧轮次没有该用例)')
|
||
A('')
|
||
|
||
# ---- 7 结论
|
||
A('## 7. 结论口径')
|
||
A('')
|
||
A('- 退出码:**%d**(%s)——与 §0、§6 同源计算。'
|
||
% (out['code'], code_label(out['code'])))
|
||
A('- 包构建、资源自包含、模型文件与源一致、运行时无资源/插件错误:%s(来源:`%s`)'
|
||
% ('**有证据**' if stages['assets']['ok'] else '**未取得**',
|
||
stages['assets']['source']['label'] if stages['assets']['present'] else '无'))
|
||
A('- `/clock` 单发布者、仿真时间不倒退、暂停不推进、恢复后继续:%s(来源:`%s`)'
|
||
% ('**有证据**' if stages['clock']['ok'] else '**未取得**',
|
||
stages['clock']['source']['label'] if stages['clock']['present'] else '无'))
|
||
A('- 进程隔离(收尾不误伤他人 gzserver):%s(来源:`%s`)'
|
||
% ('**已验证**' if stages['isolation']['ok'] else '**未验证**',
|
||
stages['isolation']['source']['label'] if stages['isolation']['present'] else '无'))
|
||
A('- 8 个抽样点:PASS %d / FAIL %d / INVALID %d / 缺失 %d(见 §6)'
|
||
% (counts[STATUS_PASS], counts[STATUS_FAIL], counts[STATUS_INVALID],
|
||
counts[STATUS_MISSING]))
|
||
if out['gui'] and out['gui'].get('result') == 'passed':
|
||
A('- GUI 画面:**已有实机目视记录**(%s,确认人 %s)。本轮未重新采集、未要求截图。'
|
||
% (out['gui'].get('basis', '实机目视'), out['gui'].get('confirmed_by', '—')))
|
||
else:
|
||
A('- GUI 画面:**无目视记录**(只作记录项,不参与退出码判定)。')
|
||
A('- 不宣称:全部 50 个碰撞体已覆盖、机器人可通行、整车爬坡、平台转向。')
|
||
A('')
|
||
A('### 退出码定义')
|
||
A('')
|
||
A('| 码 | 含义 |')
|
||
A('|---|---|')
|
||
A('| 0 | 8 个用例全部 PASS,资源/时钟/隔离证据齐备且通过 |')
|
||
A('| 30 | 结果集有效,但存在物理判据 FAIL(或某阶段检查未通过) |')
|
||
A('| 40 | 用例缺失、采集无效(INVALID),或报告不完整(阶段证据缺失) |')
|
||
A('')
|
||
A('> 40 优先于 30:结果集里只要含无效/缺失项,结论本身不可用,不能报成「有效测试失败」。')
|
||
text = '\n'.join(L) + '\n'
|
||
path = os.path.join(outroot, 'BASELINE_REPORT.md')
|
||
with open(path, 'w', encoding='utf-8') as f:
|
||
f.write(text)
|
||
|
||
# 机读版判定,便于外部核对
|
||
with open(os.path.join(outroot, 'BASELINE_OUTCOME.json'), 'w', encoding='utf-8') as f:
|
||
json.dump({'task': TASK_ID, 'code': out['code'],
|
||
'code_label': code_label(out['code']),
|
||
'report_tool_sha256': cur_tool,
|
||
'sources': [{'label': s['label'], 'dir': s['dir'], 'kind': s['kind']}
|
||
for s in sources],
|
||
'case_counts': counts,
|
||
'cases': [{'id': r['id'], 'label': r['label'], 'status': r['status'],
|
||
'status_raw': r['status_raw'], 'source': r['source_label'],
|
||
'source_kind': r['source_kind'],
|
||
'data_tool_sha256': r['data_tool'],
|
||
'reason': r['reason']} for r in rows],
|
||
'stages': {k: {'present': v['present'], 'ok': v['ok'],
|
||
'source': (v['source'] or {}).get('label')}
|
||
for k, v in stages.items()},
|
||
'invalid': out['invalid'], 'failed': out['failed'],
|
||
'problems': out['problems']},
|
||
f, ensure_ascii=False, indent=2)
|
||
return out['code'], out['problems']
|
||
|
||
|
||
def log_outcome(code, problems):
|
||
log('[report] 退出码 %d(%s)' % (code, code_label(code)))
|
||
if problems:
|
||
log('[report] 未满足项 %d 条:' % len(problems))
|
||
for x in problems:
|
||
log(' - %s' % x)
|
||
else:
|
||
log('[report] 无未满足项')
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 进程隔离验证:证明收尾不会碰到「不是自己创建的」gzserver
|
||
# -----------------------------------------------------------------------------
|
||
EMPTY_WORLD = "\n".join([
|
||
'<?xml version="1.0"?>',
|
||
'<sdf version="1.6">',
|
||
' <world name="iso_empty">',
|
||
' <physics type="ode">',
|
||
' <max_step_size>0.001</max_step_size>',
|
||
' <real_time_factor>1.0</real_time_factor>',
|
||
' <real_time_update_rate>1000</real_time_update_rate>',
|
||
' </physics>',
|
||
' <light type="directional" name="sun">',
|
||
' <cast_shadows>true</cast_shadows>',
|
||
' <pose>0 0 10 0 0 0</pose>',
|
||
' <diffuse>0.8 0.8 0.8 1</diffuse>',
|
||
' <specular>0.2 0.2 0.2 1</specular>',
|
||
' <direction>0.1 0.1 -1</direction>',
|
||
' </light>',
|
||
' <!-- 故意不写 model:// 引用:隔离验证不该依赖模型路径能否解析 -->',
|
||
' <model name="iso_ground">',
|
||
' <static>true</static>',
|
||
' <pose>0 0 -0.05 0 0 0</pose>',
|
||
' <link name="link">',
|
||
' <collision name="c">',
|
||
' <geometry><box><size>10 10 0.1</size></box></geometry>',
|
||
' </collision>',
|
||
' <visual name="v">',
|
||
' <geometry><box><size>10 10 0.1</size></box></geometry>',
|
||
' </visual>',
|
||
' </link>',
|
||
' </model>',
|
||
' </world>',
|
||
'</sdf>',
|
||
''])
|
||
|
||
|
||
def stage_isolation(outdir, base_master=None, offset=100):
|
||
"""进程隔离验证。
|
||
|
||
起一个**本阶段自己创建的、裸 gzserver 的**空世界 server 在另一个空闲 master 端口
|
||
(base+100),然后在 base 端口上让工具实例完整走 start + stop,之后检查:
|
||
- 隔离 server 的 PID 仍存活、端口仍可连通;
|
||
- 该 PID 从未出现在工具实例的进程树/已知 PID 里。
|
||
最后按记录 PID 收掉隔离 server。
|
||
|
||
注意 `gzserver -v` 是「打印版本」,verbose 要用 `--verbose`。
|
||
全程只操作本阶段自己创建的进程。
|
||
"""
|
||
od = ensure_dir(os.path.join(outdir, 'isolation'))
|
||
base_port = master_port(base_master)
|
||
iso_port = base_port + offset
|
||
iso_master = 'http://127.0.0.1:%d' % iso_port
|
||
rep = {'stage': 'isolation', 'iso_port': iso_port, 'iso_master': iso_master,
|
||
'tool_port': base_port, 'ok': False, 'iso_pid': None,
|
||
'iso_survived_tool_teardown': False, 'iso_port_still_open': False,
|
||
'iso_pid_in_tool_tree': False, 'iso_cleaned': False, 'note': ''}
|
||
log('[isolation] 隔离 server 端口 %d,工具实例端口 %d' % (iso_port, base_port))
|
||
|
||
if port_open(port=iso_port) or port_open(port=base_port):
|
||
rep['note'] = ('端口 %d 或 %d 已被占用;本阶段不做实验,也不会去动占用者。'
|
||
% (iso_port, base_port))
|
||
log(' [SKIP] ' + rep['note'])
|
||
_dump(od, 'isolation.json', rep)
|
||
return rep
|
||
|
||
world = os.path.join(od, 'empty_world.sdf')
|
||
with open(world, 'w', encoding='utf-8') as f:
|
||
f.write(EMPTY_WORLD)
|
||
|
||
env = sim_env({'GAZEBO_MASTER_URI': iso_master})
|
||
iso_log_path = os.path.join(od, 'iso_server.log')
|
||
iso_log = open(iso_log_path, 'w', encoding='utf-8')
|
||
iso = subprocess.Popen(['gzserver', '--verbose', world], env=env, cwd='/',
|
||
stdout=iso_log, stderr=subprocess.STDOUT,
|
||
start_new_session=True)
|
||
rep['iso_pid'] = iso.pid
|
||
probe = None
|
||
try:
|
||
t0 = time.monotonic()
|
||
up = False
|
||
while time.monotonic() - t0 < 60.0:
|
||
if iso.poll() is not None:
|
||
break
|
||
if port_open(port=iso_port):
|
||
up = True
|
||
break
|
||
time.sleep(0.3)
|
||
rep['iso_ready'] = up
|
||
rep['iso_ready_after_s'] = round(time.monotonic() - t0, 2)
|
||
if not up:
|
||
rep['iso_exit_code'] = iso.poll()
|
||
rep['note'] = ('隔离 server 未能在 60 s 内监听端口 %d(exit_code=%s,见 iso_server.log)'
|
||
% (iso_port, iso.poll()))
|
||
log(' [FAIL] ' + rep['note'])
|
||
return rep
|
||
log(' 隔离 server 就绪 pid=%d port=%d(%.2f s)' % (iso.pid, iso_port,
|
||
rep['iso_ready_after_s']))
|
||
|
||
# 工具实例:base 端口,完整 start + stop
|
||
probe = Probe()
|
||
tool_sim = Sim(world, os.path.join(od, 'tool_side'), probe,
|
||
master=base_master, world_name='iso_empty')
|
||
tree_seen = []
|
||
try:
|
||
ok2, why2 = tool_sim.start()
|
||
rep['tool_sim_ready'] = ok2
|
||
rep['tool_sim_detail'] = why2
|
||
tree_seen = tool_sim.tree_pids() + sorted(tool_sim.known_pids)
|
||
log(' 工具实例就绪=%s(%s)' % (ok2, why2))
|
||
finally:
|
||
tool_sim.stop()
|
||
rep['tool_teardown'] = tool_sim.teardown_info
|
||
rep['iso_pid_in_tool_tree'] = (iso.pid in tree_seen)
|
||
|
||
time.sleep(1.0)
|
||
alive = False
|
||
try:
|
||
os.kill(iso.pid, 0)
|
||
alive = (iso.poll() is None)
|
||
except OSError:
|
||
alive = False
|
||
rep['iso_survived_tool_teardown'] = alive
|
||
rep['iso_port_still_open'] = port_open(port=iso_port)
|
||
log(' 工具实例收尾后:隔离 server 存活=%s,端口仍开=%s,曾被工具实例树/已知PID包含=%s'
|
||
% (alive, rep['iso_port_still_open'], rep['iso_pid_in_tool_tree']))
|
||
finally:
|
||
if probe is not None:
|
||
probe.close()
|
||
# 按记录 PID 收掉隔离 server(只碰我们自己起的这一个)
|
||
if iso.poll() is None:
|
||
try:
|
||
os.killpg(os.getpgid(iso.pid), signal.SIGTERM)
|
||
except OSError:
|
||
iso.terminate()
|
||
try:
|
||
iso.wait(timeout=15)
|
||
except subprocess.TimeoutExpired:
|
||
try:
|
||
os.killpg(os.getpgid(iso.pid), signal.SIGKILL)
|
||
except OSError:
|
||
iso.kill()
|
||
t0 = time.monotonic()
|
||
while time.monotonic() - t0 < 15.0 and port_open(port=iso_port):
|
||
time.sleep(0.3)
|
||
rep['iso_cleaned'] = (iso.poll() is not None)
|
||
rep['iso_port_after_clean'] = port_open(port=iso_port)
|
||
try:
|
||
iso_log.close()
|
||
except Exception:
|
||
pass
|
||
log(' 按记录 PID 收掉隔离 server:进程退出=%s,端口仍开=%s'
|
||
% (rep['iso_cleaned'], rep['iso_port_after_clean']))
|
||
|
||
rep['ok'] = bool(rep.get('iso_ready')
|
||
and rep['iso_survived_tool_teardown']
|
||
and rep['iso_port_still_open']
|
||
and not rep['iso_pid_in_tool_tree']
|
||
and rep['iso_cleaned'])
|
||
rep['note'] = ('隔离 server 由本阶段自己用裸 gzserver 启动(pid=%s,端口 %d,'
|
||
'启动即监听 %.2f s);工具实例在同一台机器上用端口 %d 完整跑了 '
|
||
'start + stop。工具实例收尾只对自己启动阶段确认过的 PID 与自身进程组'
|
||
'发信号:隔离 server 全程存活、端口未断,且其 PID 从未进入工具实例的'
|
||
'进程树;最后按记录 PID 收掉。'
|
||
% (rep['iso_pid'], iso_port, rep.get('iso_ready_after_s') or 0.0,
|
||
base_port))
|
||
_dump(od, 'isolation.json', rep)
|
||
return rep
|
||
|
||
|
||
def _dump(d, name, obj):
|
||
ensure_dir(d)
|
||
with open(os.path.join(d, name), 'w', encoding='utf-8') as f:
|
||
json.dump(obj, f, ensure_ascii=False, indent=2)
|
||
|
||
|
||
def save_results(outroot, a=None, clock=None, contacts=None, iso=None):
|
||
"""把各阶段结果按固定位置落盘,供 --stage report 单独读取。"""
|
||
if a is not None:
|
||
_dump(os.path.join(outroot, 'assets'), 'assets.json', a)
|
||
_dump(outroot, 'assets.json', a)
|
||
if clock is not None:
|
||
_dump(os.path.join(outroot, 'clock'), 'clock.json', clock)
|
||
if contacts is not None:
|
||
_dump(os.path.join(outroot, 'contacts'), 'contacts.json', contacts)
|
||
if iso is not None:
|
||
_dump(os.path.join(outroot, 'isolation'), 'isolation.json', iso)
|
||
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 入口
|
||
# -----------------------------------------------------------------------------
|
||
EXIT_OK = 0
|
||
EXIT_FAIL = 30 # 有效测试失败(物理判据 FAIL / 某阶段检查未通过)
|
||
EXIT_INVALID = 40 # 缺失 / 采集无效 / 报告不完整
|
||
EXIT_ENV = 50 # 环境问题(端口被占等)
|
||
|
||
|
||
def exit_code_from_stages(results):
|
||
"""单阶段运行的退出码:只反映本进程实际跑过的阶段。
|
||
|
||
单阶段运行不声称完成完整基线,所以「别的阶段没跑」不算缺项;
|
||
完整基线判定请用 `--stage all` 或 `--stage report`(两者都走 compute_outcome)。
|
||
"""
|
||
def stage_bad(name):
|
||
r = results.get(name)
|
||
return r is not None and not r.get('ok')
|
||
|
||
c = results.get('contacts')
|
||
counts = (c or {}).get('counts') or {}
|
||
if counts.get(STATUS_INVALID):
|
||
return EXIT_INVALID
|
||
if counts.get(STATUS_FAIL):
|
||
return EXIT_FAIL
|
||
if any(stage_bad(k) for k in ('assets', 'clock', 'contacts', 'isolation')):
|
||
return EXIT_FAIL
|
||
return EXIT_OK
|
||
|
||
|
||
def _run_stage(name, fn, results, on_result=None):
|
||
"""跑一个阶段并把异常收敛成「该阶段失败」,不让整轮崩成 traceback。"""
|
||
try:
|
||
r = fn()
|
||
except Exception as exc: # noqa: BLE001 - 阶段失败要留证据而不是崩
|
||
import traceback
|
||
tb = traceback.format_exc()
|
||
log('[%s] 阶段异常:%r' % (name, exc))
|
||
log(tb)
|
||
r = {'stage': name, 'ok': False, 'error': repr(exc), 'traceback': tb}
|
||
results[name] = r
|
||
if on_result is not None and r.get('ok') is not None:
|
||
try:
|
||
on_result(r)
|
||
except Exception as exc: # noqa: BLE001
|
||
log('[%s] 落盘失败:%r' % (name, exc))
|
||
return r
|
||
|
||
|
||
def main():
|
||
global MAX_INITIAL_DRIFT
|
||
ap = argparse.ArgumentParser(
|
||
description='%s Gazebo Classic 基线检查' % TASK_ID)
|
||
ap.add_argument('--stage', default='all',
|
||
choices=['assets', 'clock', 'contacts', 'isolation', 'report', 'all'])
|
||
ap.add_argument('--out', default=OUTROOT, help='证据根目录')
|
||
ap.add_argument('--only', default='', help='contacts 阶段只跑指定用例 id,逗号分隔')
|
||
ap.add_argument('--master', default=MASTER,
|
||
help='Gazebo master URI(默认 %s);隔离验证用其端口 +100' % MASTER)
|
||
ap.add_argument('--prev', default='',
|
||
help='旧轮次证据根目录,逗号分隔、按优先级从近到远排列(只读)')
|
||
ap.add_argument('--max-initial-drift', type=float, default=MAX_INITIAL_DRIFT)
|
||
args = ap.parse_args()
|
||
os.environ.update(sim_env())
|
||
only = [x.strip() for x in args.only.split(',') if x.strip()]
|
||
prevs = [x.strip() for x in args.prev.split(',') if x.strip()]
|
||
MAX_INITIAL_DRIFT = args.max_initial_drift
|
||
|
||
outroot = ensure_dir(os.path.abspath(args.out))
|
||
if args.master:
|
||
os.environ['GAZEBO_MASTER_URI'] = args.master
|
||
|
||
# report 只读磁盘证据,不跑仿真
|
||
if args.stage == 'report':
|
||
code, problems = write_report(outroot, prevs=prevs)
|
||
log_outcome(code, problems)
|
||
return code
|
||
|
||
results = {}
|
||
if args.stage in ('assets', 'all'):
|
||
_run_stage('assets', lambda: stage_assets(os.path.join(outroot, 'assets')),
|
||
results, on_result=lambda r: save_results(outroot, a=r))
|
||
|
||
if args.stage in ('clock', 'all'):
|
||
_run_stage('clock', lambda: stage_clock(os.path.join(outroot, 'clock')),
|
||
results, on_result=lambda r: save_results(outroot, clock=r))
|
||
|
||
if args.stage in ('contacts', 'all'):
|
||
_run_stage('contacts',
|
||
lambda: stage_contacts(os.path.join(outroot, 'contacts'),
|
||
only, master=args.master),
|
||
results)
|
||
|
||
if args.stage in ('isolation', 'all'):
|
||
_run_stage('isolation', lambda: stage_isolation(outroot, base_master=args.master),
|
||
results)
|
||
|
||
# ---- 完整基线:退出码只看最终报告,不看各阶段局部 ok
|
||
if args.stage == 'all':
|
||
log('')
|
||
code, problems = write_report(outroot, prevs=prevs)
|
||
log_outcome(code, problems)
|
||
local = {k: bool((v or {}).get('ok')) for k, v in results.items()}
|
||
log('[all] 各阶段局部结果:%s' % local)
|
||
log('[all] 最终退出码取报告判定,不取阶段局部结果')
|
||
return code
|
||
|
||
# ---- 单阶段:只反映该阶段
|
||
code = exit_code_from_stages(results)
|
||
log('[%s] 退出码 %d(%s)' % (args.stage, code, code_label(code)))
|
||
return code
|
||
|
||
|
||
if __name__ == '__main__':
|
||
sys.exit(main())
|