Files
RC2027_BR_code/sim_ws/tools/check_slope_drive.py
T
Kevin ca61aa63b5 fix(sim): clean up interrupted runs and document usage and migration
Prevent ROS cleanup errors from skipping owned Gazebo process teardown.
Reject occupied master ports before launching nodes and stop the stack when
its GUI closes. Add --gui to the automatic LIO navigation checks.

Expand the root README and add a beginner guide covering manual goals,
automatic tests, restart troubleshooting, MID360 assumptions and staged
migration to real hardware. Preserve lifecycle and GUI validation evidence.

Validation: three navigation restart cycles, two busy-port rejection cases,
SIGINT/SIGHUP cleanup and a GUI straight-route check. Current source hashes,
Python syntax, documentation shell syntax and local links verified. Hardware
migration remains unverified; no push performed.
2026-11-08 22:44:02 +08:00

166 lines
8.4 KiB
Python

#!/usr/bin/python3
"""Validate force drive using independent Gazebo state, real contacts and lidar geometry."""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import sys
import time
import numpy as np
import rclpy
from gazebo_msgs.msg import ContactsState
from gazebo_msgs.srv import GetEntityState
from geometry_msgs.msg import WrenchStamped
from rclpy.qos import qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2
from check_omni_robot import BASE, Probe, Sim, reset_and_settle, sim_env, shutdown_probe
from check_sim_lidar import points, stamp
class SlopeProbe(Probe):
def __init__(self):
super().__init__()
self.contacts, self.wrenches, self.cloud_checks = [], [], []
self.raw = {}
self.create_subscription(ContactsState, '/sim/drive_contacts', self.on_contacts, 100)
self.create_subscription(WrenchStamped, '/sim/drive_wrench', self.on_force, 100)
self.create_subscription(PointCloud2, '/lidar/points', lambda m: self.raw.update({stamp(m):m}), qos_profile_sensor_data)
self.create_subscription(PointCloud2, '/cloud_registered', self.on_cloud, 5)
def on_contacts(self, m):
self.contacts.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
pairs=[(s.collision1_name,s.collision2_name) for s in m.states],
max_depth=max((d for s in m.states for d in s.depths),default=0.)))
def on_force(self, m):
self.wrenches.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
force=[m.wrench.force.x,m.wrench.force.y,m.wrench.force.z],
torque=[m.wrench.torque.x,m.wrench.torque.y,m.wrench.torque.z]))
def on_cloud(self, m):
raw = self.raw.pop(stamp(m), None)
if raw is None:
return
pr,pw = points(raw),points(m)
self_hit = (np.abs(pr[:,0])<=.42)&(np.abs(pr[:,1])<=.42)&(pr[:,2]>=-.47)&(pr[:,2]<=-.20)
roi = np.isfinite(pw).all(1)&(~self_hit)&(pw[:,0]>-.5)&(pw[:,0]<2.4)&(pw[:,1]>3.1)&(pw[:,1]<3.9)
pc=pw[roi]
if len(pc)>20:
errors=np.abs(.597*pc[:,0]+3.5*pc[:,2]-1.6119)/math.hypot(.597,3.5)
self.cloud_checks.append(dict(t=stamp(m)*1e-9,points=len(pc),max_plane_error_m=float(np.max(errors))))
for key in sorted(self.raw)[:-20]:self.raw.pop(key)
def get_state(self):
req=GetEntityState.Request(); req.name=BASE; req.reference_frame='world'
res=self._call(self.cli_get,req)
if res is None or not res.success:return None
st=res.state;q=st.pose.orientation
roll=math.atan2(2*(q.w*q.x+q.y*q.z),1-2*(q.x*q.x+q.y*q.y))
pitch=math.asin(max(-1.,min(1.,2*(q.w*q.y-q.z*q.x))))
yaw=math.atan2(2*(q.w*q.z+q.x*q.y),1-2*(q.y*q.y+q.z*q.z))
return dict(stamp=res.header.stamp.sec+res.header.stamp.nanosec*1e-9,
pos=[st.pose.position.x,st.pose.position.y,st.pose.position.z],yaw=yaw,
rpy=[roll,pitch,yaw],quaternion=[q.x,q.y,q.z,q.w],
twist_world=[st.twist.linear.x,st.twist.linear.y,st.twist.linear.z],
wz=st.twist.angular.z)
def hold(p, cmd, duration):
samples=[];nxt=p.now()
def sample():
nonlocal nxt
if p.now()<nxt:return
state=p.get_state()
if state is None:raise RuntimeError('independent truth unavailable')
samples.append(state);nxt=p.now()+.04
p.hold(*cmd,duration,sampler=sample)
return samples
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
ap.add_argument('--world');args=ap.parse_args()
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)
os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
sim,p=Sim(str(out/'sim')),None
report=dict(status='INVALID',phases={})
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
report['collector_sha256']=hashlib.sha256(source).hexdigest()
try:
ok,why=sim.start(lidar=True,drive='contact',world=args.world);report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=SlopeProbe()
if not p.wait_clock():raise RuntimeError('no clock')
p.pump(.5)
if not p.set_state(3.5,3.5,1.15,0.):raise RuntimeError('drop set failed')
t0=p.now()
drop=hold(p,(.2,0.,0.),.28)
t=np.array([s['stamp'] for s in drop]); z=np.array([s['pos'][2] for s in drop])
if len(np.unique(t))<5:raise RuntimeError('insufficient free-fall samples')
acc=float(2*np.polyfit(t-t[0],z,2)[0])
forces=[s for s in p.wrenches if t0+.04<s['t']<p.now()]
checks=dict(gravity=abs(acc+9.81)<.5,
no_air_drive=len(forces)>3 and max(np.linalg.norm(s['force']) for s in forces)<1e-6,
horizontal_drift=abs(drop[-1]['pos'][0]-drop[0]['pos'][0])<.01)
report['phases']['free_fall']=dict(checks=checks,acceleration_z_m_s2=acc,samples=drop)
ok,rec=reset_and_settle(p,3.5,3.5,.17,0.,str(out))
if not ok:raise RuntimeError('ramp start did not settle')
t0=p.now()
motions={}
for name,cmd,duration in (
('up_first',(-.25,0.,0.),10.),('stop',(0.,0.,0.),2.),
('up_second',(-.25,0.,0.),8.8),('upper_landing',(0.,0.,0.),1.5),
('down',(.25,0.,0.),18.8),('bottom',(0.,0.,0.),1.5)):
motions[name]=hold(p,cmd,duration)
(out/(name+'.json')).write_text(json.dumps(dict(samples=motions[name],
contacts=p.contacts,wrenches=p.wrenches),indent=2)+'\n')
print(name,motions[name][-1]['pos'],motions[name][-1]['rpy'],flush=True)
if name=='up_first' and motions[name][-1]['pos'][0]>2.:
report['phases']['ascent_entry']=dict(checks=dict(entered_ramp=False),samples=motions[name])
report['status']='FAIL'
return 30
up1,stop,up2,top,down,bottom=[motions[n] for n in (
'up_first','stop','up_second','upper_landing','down','bottom')]
states=up1+up2+down
mid=[s for s in states if -.35<s['pos'][0]<2.2]
if len(mid)<20:raise RuntimeError('insufficient ramp samples')
err=max(abs(s['pos'][2]-((1.6119-.597*s['pos'][0])/3.5+.15)) for s in mid)
theta=math.atan2(.597,3.5)
tilt=max(abs(s['rpy'][1]-theta) for s in mid)
late=stop[len(stop)//2:]
stop_speed=max(np.linalg.norm(s['twist_world']) for s in late)
stop_drift=max(np.linalg.norm(np.array(s['pos'])-late[0]['pos']) for s in late)
contacts=[s for s in p.contacts if s['t']>t0]
force=[s for s in p.wrenches if s['t']>t0]
clouds=[s for s in p.cloud_checks if s['t']>t0]
checks=dict(reached_upper_landing=top[-1]['pos'][0]<-.9 and abs(top[-1]['pos'][2]-.749)<.03,
returned_to_ground=bottom[-1]['pos'][0]>3. and abs(bottom[-1]['pos'][2]-.149)<.02,
followed_ramp=err<.03,physical_pitch=tilt<.05,
stayed_in_lane=max(abs(s['pos'][1]-3.5) for s in states)<.03,
hill_stop=stop_speed<.01 and stop_drift<.02,
ramp_contact=any('ramp_north' in n for s in contacts for pair in s['pairs'] for n in pair),
no_excess_penetration=bool(contacts) and max(s['max_depth'] for s in contacts)<.005,
no_vertical_or_tilt_actuator=bool(force) and all(s['force'][2]==0 and s['torque'][:2]==[0,0] for s in force),
tilted_cloud_geometry=len(clouds)>10 and max(s['max_plane_error_m'] for s in clouds)<.01)
report['phases']['round_trip']=dict(checks=checks,up_first=up1,stop=stop,up_second=up2,
upper_landing=top,down=down,bottom=bottom,max_height_error_m=err,max_pitch_error_rad=tilt,
hill_stop_speed_m_s=float(stop_speed),hill_stop_drift_m=float(stop_drift),
contacts=contacts,applied_wrenches=force,cloud_geometry=clouds)
for name,phase in report['phases'].items():print(name,phase['checks'],flush=True)
report['status']='PASS' if all(all(v['checks'].values()) for v in report['phases'].values()) else 'FAIL'
except Exception as exc:
report['error']=repr(exc);print(report['error'],flush=True)
finally:
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,
default=lambda v:v.item() if isinstance(v,np.generic) else str(v))+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
if __name__=='__main__':sys.exit(main())