完善双雷达仿真与自动上坡任务,更新使用文档

加入下置 MID360 前向补盲与双雷达融合,修复北侧走廊导航、坐标适配和数据时效处理。

实现接近坡脚、姿态辅助上坡与平台停车任务,增加独立快模式、命令仲裁及失效停车保护,保留测试与分阶段验收记录。

同步实车尺寸及雷达安装参数,调整 Gazebo 红方默认视角,完善根目录 README、仿真使用和实车迁移说明。
This commit is contained in:
2026-11-12 16:42:07 +08:00
parent cac93cae11
commit 6f1d837b46
95 changed files with 13667 additions and 244 deletions
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/python3
"""Independent mission evaluation: truth only for scoring, no drive injection."""
import argparse,hashlib,json,math,os,sys,time
from pathlib import Path
import numpy as np
import rclpy
from std_msgs.msg import String
from gazebo_msgs.srv import SpawnEntity
from std_srvs.srv import Trigger
from rcl_interfaces.srv import GetParameters
from geometry_msgs.msg import Twist
from rclpy.qos import QoSProfile,DurabilityPolicy,ReliabilityPolicy
from check_omni_robot import Sim,sim_env,shutdown_probe
from check_lio_terrain import TerrainProbe
from check_mid360 import interpolate,json_value
from check_lio_navigation import graph_evidence
def critical_cloud_reliability_ok(evidence):
"""Check discovery evidence; history depth is not exposed by this local RMW."""
for topic, producer, consumers in (
('/sim/navigation/fused_planning_cloud', 'dual_lidar_fusion', ('step_blocker', 'ramp_mission')),
('/sim/navigation/terrain_planning_cloud', 'step_blocker', ('lio_navigation_adapter', 'scan_planner_node'))):
for kind, names in (('publisher', (producer,)), ('subscription', consumers)):
for name in names:
matches = [row for row in evidence.get(topic, []) if row['kind'] == kind and row['node'] == name]
if len(matches) != 1 or matches[0]['reliability'] != str(ReliabilityPolicy.RELIABLE):
return False
return True
def bounds(s):
from check_mid360 import rotate
R=rotate(np.broadcast_to(np.array(s['quaternion']),(3,4)),np.eye(3)).T
c=np.asarray(s['pos'])+R@np.array([0.,0.,.055]);e=np.abs(R)@np.array([.4,.4,.205])
return c-e,c+e
def motion_metrics(truth,events,fast=False):
entry=next((e['stamp'] for e in events if e.get('to')=='ENTRY'),None)
nav_start=next((e['stamp'] for e in events if e.get('to')=='NAVIGATE'),None)
nav=[s for s in truth if nav_start is not None and s['stamp']>=nav_start and (entry is None or s['stamp']<entry)]
straight=[s for s in nav if -3.5<s['pos'][0]<2.5]
uphill=[s for s in truth if entry is not None and s['stamp']>=entry and .5<s['pos'][0]<1.8]
crest=[s for s in truth if entry is not None and s['stamp']>=entry and ((-1.15<s['pos'][0]<-1.02) if fast else (-.85<s['pos'][0]<-.35))]
speed=lambda s:float(np.linalg.norm(s['twist_world']))
longest=0.;since=None
for s in straight:
if speed(s)<.05:
if since is None:since=s['stamp']
longest=max(longest,s['stamp']-since)
else:since=None
return dict(straight_peak_mps=max(map(speed,straight),default=0.),
straight_longest_stop_s=longest,nav_yaw_peak_radps=max((abs(s['wz']) for s in nav),default=0.),
uphill_peak_mps=max(map(speed,uphill),default=0.),crest_peak_mps=max(map(speed,crest),default=0.),
crest_median_mps=float(np.median([speed(s) for s in crest])) if crest else None)
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
ap.add_argument('--profile',choices=('standard','fast'),default='standard')
ap.add_argument('--ramp-speed',type=float);ap.add_argument('--nav-speed',type=float)
ap.add_argument('--crest-speed',type=float,default=.2);ap.add_argument('--yaw-speed',type=float)
ap.add_argument('--gui',action='store_true');ap.add_argument('--sensor-profile',choices=('ideal','mild'),default='ideal')
ap.add_argument('--with-rviz',action='store_true',help='include RViz to reproduce the interactive launch load (requires --gui)')
ap.add_argument('--fault',choices=('none','lower_loss','mission_loss','mux_loss','obstacle'),default='none')
ap.add_argument('--aligned-start',action='store_true',help='fault diagnostics only, start physically at the staging pose; never count as a full-route pass')
args=ap.parse_args();out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)
if args.nav_speed is None:args.nav_speed=2.5 if args.profile=='fast' else .6
if args.ramp_speed is None:args.ramp_speed=1.1 if args.profile=='fast' else .7
if args.yaw_speed is None:args.yaw_speed=2.0 if args.profile=='fast' else .8
if args.aligned_start and args.fault=='none':ap.error('--aligned-start is only for explicitly scoped fault diagnostics')
if args.with_rviz and not args.gui:ap.error('--with-rviz requires --gui')
if (out/'result.json').exists():ap.error('use a fresh output directory')
os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
report=dict(status='INVALID',profile=args.profile,gui=args.gui,with_rviz=args.with_rviz,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,fault=args.fault,aligned_start=args.aligned_start,collector_sha256=hashlib.sha256(source).hexdigest())
root=Path(__file__).resolve().parents[2]
report['source_sha256']={str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in [
root/name for name in ('sim_ws/src/br_sim_bringup/scripts/ramp_mission.py','sim_ws/src/br_sim_bringup/scripts/mission_command_mux.py','sim_ws/src/br_sim_bringup/launch/ramp_mission.launch.py',
'sim_ws/src/r2027_robot_description/src/contact_drive.cpp','sim_ws/src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro',
'sim_ws/src/r2027_robot_description/launch/robocon_robot.launch.py','sim_ws/src/br_sim_bringup/launch/mid360_sim.launch.py',
'minco_ws/src/scan/plan_env/src/grid_map.cpp','minco_ws/src/scan/plan_env/include/plan_env/grid_map.h','minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp',
'minco_ws/src/scan/plan_manage/src/planner_manager.cpp','minco_ws/src/scan/plan_manage/src/closed_loop_controller.cpp','sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py',
'minco_ws/src/perception/Point-LIO/include/common_lib.h','minco_ws/src/perception/Point-LIO/include/sensor_timestamp.h',
'sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py','minco_ws/src/scan/step_blocker/step_blocker/step_blocker_node.py',
'minco_ws/src/perception/Point-LIO/include/sensor_time_rate_limiter.h','minco_ws/src/perception/Point-LIO/src/laserMapping.cpp','sim_ws/src/robocon_gazebo/worlds/robocon_robot.world')]}
for name in report['source_sha256']:(out/Path(name).name).write_bytes((root/name).read_bytes())
sim=Sim(str(out/'sim'));p=None;states=[];mission=[];mux=[];fault={};actuator=[]
try:
ok,why=sim.start(lio_navigation=True,dual_lidar=True,mission=True,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,gui=args.gui,sensor_profile=args.sensor_profile,
with_rviz=args.with_rviz,mission_profile=args.profile,
crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,
aligned_start=args.aligned_start,spawn=(3.7,3.5125,.15,math.pi) if args.aligned_start else None);report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=TerrainProbe(out,True)
for pub in (p.pub,p.goal_pub,p.path_pub):p.destroy_publisher(pub)
p.send=lambda *args:None
p.create_subscription(String,'/mission/status',lambda m:mission.append(json.loads(m.data)),QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
p.create_subscription(String,'/mission/mux_status',lambda m:mux.append(json.loads(m.data)),10)
p.create_subscription(Twist,'/sim/cmd_vel',lambda m:actuator.append(dict(stamp=p.now(),command=[m.linear.x,m.linear.y,m.angular.z])),100)
if not p.wait_clock():raise RuntimeError('missing clock')
deadline=time.monotonic()+700;start=p.now();last_query=-1.;graph=None
fixture=False
while time.monotonic()<deadline and p.now()-start<210:
p.pump(.03)
if p.now()-last_query>=.1:
s=p.get_state()
if s is None:raise RuntimeError('missing physical entity query')
states.append(s);last_query=p.now()
if not mission:continue
state=mission[-1]['state']
if args.fault=='obstacle' and not fixture and state in ('NAVIGATE','ENTRY'):
req=SpawnEntity.Request();req.name='mission_ramp_obstacle';req.reference_frame='world'
req.initial_pose.position.x=1.;req.initial_pose.position.y=3.5125;req.initial_pose.position.z=float((1.6119-.597)/3.5+.15);req.initial_pose.orientation.w=1.
req.xml='<sdf version="1.6"><model name="mission_ramp_obstacle"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 0.30</size></box></geometry></collision></link></model></sdf>'
res=p._call(p.spawn,req,15)
if res is None or not res.success:raise RuntimeError('fixture spawn failed')
fixture=True;fault=dict(kind='obstacle',spawn_stamp=p.now())
inject=args.fault in ('lower_loss','mission_loss','mux_loss') and not fault and state=='CLIMB' and states[-1]['pos'][0]<1.8
if inject:
fault=dict(kind=args.fault,start=p.now(),initial=states[-1])
if args.fault=='lower_loss':
raw=p.raw[1];raw_end=(int(raw.timebase)+max(point.offset_time for point in raw.points))*1e-9
fault.update(lower_last_source_end=raw_end,lower_source_age_at_injection_s=p.now()-raw_end)
fault.update(upper_before=int(p.raw[0].timebase),lower_before=int(p.raw[1].timebase))
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/disable')
response=p._call(cli,Trigger.Request(),5)
if response is None or not response.success:raise RuntimeError('lower disable failed')
else:
import signal
sim.refresh_owned()
executable=b'/ramp_mission.py' if args.fault=='mission_loss' else b'/mission_command_mux.py'
candidates=[pid for pid in sim.known if sim.owns(pid) and executable in Path('/proc/%d/cmdline'%pid).read_bytes()]
if len(candidates)!=1:raise RuntimeError('mission process ownership ambiguous')
fault['pid']=candidates[0];os.kill(fault['pid'],signal.SIGSTOP)
if state in ('FAILED','SUCCEEDED'):break
if args.fault in ('mission_loss','mux_loss') and fault and p.now()-fault['start']>1.4:break
else:raise RuntimeError('mission did not terminate in acceptance time')
if args.fault!='none' and not fault:raise RuntimeError('requested fault was not injected; the injection gate was not reached')
if args.fault=='lower_loss' and fault:
p.pump(1.1)
fault.update(upper_during_loss=int(p.raw[0].timebase),lower_during_loss=int(p.raw[1].timebase))
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/profile/'+args.sensor_profile)
response=p._call(cli,Trigger.Request(),5)
if response is None or not response.success:raise RuntimeError('lower restore failed')
fault['restore_stamp']=p.now()
p.pump(1.3);final=p.get_state()
if final is None:raise RuntimeError('missing final entity query')
states.append(final)
report['graph']=graph_evidence(out,p,'/sim/navigation/terrain_planning_cloud',extra_nodes=('/dual_lidar_fusion','/ramp_mission','/mission_command_mux'))
publishers=p.get_publishers_info_by_topic('/cmd_vel')
cli=p.create_client(GetParameters,'/sim/lio/point_lio_sim/get_parameters')
req=GetParameters.Request();req.names=['odometry.publish_scan_end']
scan_end_params=p._call(cli,req,5)
report['scan_end_odometry_enabled']=bool(scan_end_params and scan_end_params.values and scan_end_params.values[0].bool_value)
report['critical_cloud_qos']={}
for topic,producer,consumers in (
('/sim/navigation/fused_planning_cloud','dual_lidar_fusion',('step_blocker','ramp_mission')),
('/sim/navigation/terrain_planning_cloud','step_blocker',('lio_navigation_adapter','scan_planner_node'))):
rows=[]
for kind,infos,wanted in (('publisher',p.get_publishers_info_by_topic(topic),(producer,)),('subscription',p.get_subscriptions_info_by_topic(topic),consumers)):
for name in wanted:
matches=[i for i in infos if i.node_name==name]
rows.extend(dict(kind=kind,node=i.node_name,reliability=str(i.qos_profile.reliability),depth=i.qos_profile.depth) for i in matches)
report['critical_cloud_qos'][topic]=rows
report['qos_depth_evidence']='Configured depth 1 in archived source; discovery returned depth 0 locally and does not establish runtime history depth.'
report['cmd_vel_publishers']=[dict(node=i.node_name,namespace=i.node_namespace) for i in publishers]
truth=p.truth_poses
if len(truth)<100:raise RuntimeError('missing dense physical truth')
queries=[s for s in states if truth[0]['stamp']<=s['stamp']<=truth[-1]['stamp']]
tpos,tq=interpolate(truth,[s['stamp'] for s in queries])
error=np.linalg.norm(tpos-np.array([s['pos'] for s in queries]),axis=1)
angles=2*np.arccos(np.clip(abs(np.sum(tq*np.array([s['quaternion'] for s in queries]),axis=1)),0,1))
# Query service and update-end truth are asynchronous within the world's
# configured 1 ms physics step. Keep raw differences and bound the
# additional positional uncertainty by the measured query speed.
phase_bound=np.array([np.linalg.norm(s['twist_world'])*.001 for s in queries]) if args.profile=='fast' else np.zeros(len(queries))
report['truth_service_phase_bound']=dict(physics_step_s=.001,scope='fast only; 2 mm spatial residual plus one physics-step travel',maximum_bound_m=float(max(phase_bound)),maximum_residual_m=float(max(error-phase_bound)))
report['truth_service_agreement']=dict(samples=len(queries),max_position_error_m=float(max(error)),max_angle_error_rad=float(max(angles)),max_dense_gap_s=float(max(np.diff([s['stamp'] for s in truth]))))
tail=[s for s in truth if s['stamp']>=final['stamp']-1.]
checks=dict(no_truth_feedback=report['graph']['ok'],scan_end_odometry_enabled=report['scan_end_odometry_enabled'],critical_cloud_qos_reliable=critical_cloud_reliability_ok(report['critical_cloud_qos']),one_drive_owner=len(publishers)==1 and publishers[0].node_name=='mission_command_mux',
truth_crosschecked=bool(np.all(error<.002+phase_bound)) and max(angles)<.005 and report['truth_service_agreement']['max_dense_gap_s']<=.12,
stopped=bool(tail) and all(np.linalg.norm(s['twist_world'])<.01 and abs(s['wz'])<.02 for s in tail),
stopped_drift=bool(tail) and max(math.dist(s['pos'],tail[0]['pos']) for s in tail)<.02)
events=mission[-1]['events'];entry=next((e['stamp'] for e in events if e.get('to')=='ENTRY'),None)
ramp=[s for s in truth if entry is not None and s['stamp']>=entry and s['pos'][0]<3.1]
clearance=[min(bounds(s)[0][1]-3.025,4.-bounds(s)[1][1]) for s in ramp]
report['ramp_clearance_m']=min(clearance,default=None)
report['maximum_ramp_lateral_error_m']=max((abs(s['pos'][1]-3.5125) for s in ramp),default=None)
pairs=sorted({(c.collision1_name,c.collision2_name) for m in p.contacts for c in m.states})
report['contacts']=dict(pairs=pairs,maximum_depth_m=max((d for m in p.contacts for c in m.states for d in c.depths),default=None))
report['final']=final;report['events']=events;report['elapsed_sim_s']=mission[-1].get('elapsed_s')
starts=[e['stamp'] for e in events if e.get('to') in ('NAVIGATE','ENTRY')]
terminal=[e['stamp'] for e in events if e.get('to') in ('SUCCEEDED','FAILED')]
report['task_duration_sim_s']=terminal[-1]-starts[0] if terminal and starts else None
report['motion_metrics']=motion_metrics(truth,events,args.profile=='fast')
if args.fault=='none':
lo,hi=bounds(final)
north=[]
for a,b in zip(truth,truth[1:]):
if entry is None or b['stamp']>entry:continue
qa=np.array(a['quaternion']);qb=np.array(b['quaternion'])
angle=2*math.acos(np.clip(abs(float(qa@qb)),0,1));pad=(math.dist(a['pos'],b['pos'])+.62*angle)/2
for s in (a,b):
blo,bhi=bounds(s)
# The inner wall ends at x=2.7; the east staging area is open.
if bhi[0]+pad>=-3. and blo[0]-pad<=2.7:north.append(min(blo[1]-4.,5.5-bhi[1])-pad)
report['north_corridor_gap_bound_m']=min(north,default=None)
mm=report['motion_metrics']
if args.profile=='fast':checks['within_20_seconds']=mission[-1]['state']=='SUCCEEDED' and report['task_duration_sim_s'] is not None and report['task_duration_sim_s']<=20.
checks.update(mission_succeeded=mission[-1]['state']=='SUCCEEDED',
straight_without_intermediate_stop=mm['straight_longest_stop_s']<=.25,
requested_straight_speed_reached=mm['straight_peak_mps']>=.85*args.nav_speed,
requested_uphill_speed_reached=mm['uphill_peak_mps']>=.85*args.ramp_speed,
requested_turn_speed_reached=mm['nav_yaw_peak_radps']>=.85*args.yaw_speed,
crest_speed_respected=mm['crest_median_mps'] is not None and mm['crest_peak_mps']<=args.crest_speed+.03,
north_corridor_clearance=bool(north) and min(north)>.03,
no_wall_contacts=all(any(name.endswith(suffix) for suffix in ('::ground','::ramp_north','::Cube.005')) for pair in pairs for name in pair if not name.startswith('r2027_omni::')),
all_phases=all(any(e.get('to')==stage for e in events) for stage in ('NAVIGATE','ENTRY','CLIMB','CREST','PLATFORM','SETTLE','SUCCEEDED')),
started_at_default=math.dist(truth[0]['pos'],[-4.5,4.5,.15])<.03,
final_whole_body_on_platform=lo[0]>=-1.76 and hi[0]<=-.84 and lo[1]>=3.065 and hi[1]<=3.96,
platform_height=abs(final['pos'][2]-.75)<.03,
full_ramp_clearance=bool(clearance) and min(clearance)>.04,
ramp_lateral_error=bool(ramp) and report['maximum_ramp_lateral_error_m']<.03,
actual_ramp_contacts=any('ramp_north' in c.collision1_name or 'ramp_north' in c.collision2_name for m in p.contacts for c in m.states),
contact_penetration=max((d for m in p.contacts for c in m.states for d in c.depths),default=1)<.005)
else:
if args.fault=='obstacle':
checks.update(obstacle_detected=mission[-1]['state']=='FAILED' and mission[-1]['reason']=='obstacle_in_braking_corridor',
obstacle_not_contacted=not any('mission_ramp_obstacle' in c.collision1_name or 'mission_ramp_obstacle' in c.collision2_name for m in p.contacts for c in m.states))
else:
stop=next((s['stamp']-fault['start'] for s in truth if s['stamp']>=fault['start'] and np.linalg.norm(s['twist_world'])<.01 and abs(s['wz'])<.02),None)
fault['stop_latency_s']=stop;checks['fault_stop_latency']=stop is not None and 0<=stop<=.5
checks['fault_exercised']=bool(fault) and (args.fault in ('mission_loss','mux_loss') or mission[-1]['state']=='FAILED')
if args.fault=='mission_loss':checks['lease_expiry_exercised']=any(m['stamp']>fault['start']+.15 and m['reason']=='lease_stale' for m in mux)
if args.fault=='mux_loss':checks['actuator_watchdog_exercised']=any(m['stamp']>fault['start']+.15 and max(abs(v) for v in m['command'])<1e-8 for m in actuator)
if args.fault=='lower_loss':
fault.update(upper_after=int(p.raw[0].timebase),lower_after=int(p.raw[1].timebase))
checks['upper_continued']=fault['upper_during_loss']-fault['upper_before']>500000000
checks['lower_stopped']=fault['lower_during_loss']-fault['lower_before']<=100000000
checks['restored_data_without_motion']=p.ready and mission[-1]['state']=='FAILED' and fault['lower_after']>fault['lower_during_loss']
report['checks']=checks;report['status']='PASS' if all(checks.values()) else 'FAIL'
print(report['status'],checks,'task_duration',report['task_duration_sim_s'],'final',final['pos'],flush=True)
except Exception as exc:report['error']=repr(exc);print(report['error'],flush=True)
finally:
report.update(mission=mission,mux=mux,service_samples=states,fault_event=fault,actuator_commands=actuator)
if p is not None:
report['physical_poses']=p.truth_poses
report['navigation_status']=p.navigation_status
if args.fault in ('mission_loss','mux_loss') and 'pid' in fault and sim.owns(fault['pid']):
import signal
os.kill(fault['pid'],signal.SIGKILL);fault['cleanup']='owned stopped process killed after measurement; never resumed motion'
report['ros_cleanup_errors']=shutdown_probe(p);report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
if __name__=='__main__':sys.exit(main())