#!/usr/bin/python3 """Existing SCAN reference-path controller + force physics: uphill, downhill, stair rejection.""" 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 nav_msgs.msg import Path as NavPath from geometry_msgs.msg import PoseStamped from rclpy.qos import QoSProfile,DurabilityPolicy from check_omni_robot import Sim,sim_env, shutdown_probe from check_scan_navigation import NavProbe from check_slope_drive import SlopeProbe from check_sim_lidar import points LANE_Y=3.5125 # Midpoint of the rail's outer face y=3.025 and ramp edge y=4. class TerrainProbe(NavProbe): get_state=SlopeProbe.get_state def __init__(self): super().__init__() self.path_pub=self.create_publisher(NavPath,'/initial_path', QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL)) self.contacts=[] self.create_subscription(ContactsState,'/sim/drive_contacts',self.contacts.append,100) def run_path(p, xs, blocked=False): old_id=p.status[-1].goal_id if p.status else 0 first_status,first_cmd,first_contacts=len(p.status),len(p.commands),len(p.contacts) first=p.get_state() if first is None:raise RuntimeError('missing starting truth') msg=NavPath();msg.header.frame_id='world';msg.header.stamp=p.get_clock().now().to_msg() for x in xs: z=0.15 if blocked and x<-1.8 else (0. if x>=2.7 else (.6 if x<=-.8 else (1.6119-.597*x)/3.5)) pose=PoseStamped();pose.header=msg.header;pose.pose.position.x=float(x) pose.pose.position.y=LANE_Y;pose.pose.position.z=z;pose.pose.orientation.w=1. msg.poses.append(pose) p.path_pub.publish(msg) t0,end=p.now(),time.monotonic()+360 states=[] while p.now()-t0<65 and time.monotonic()old_id and status.state in (status.SUCCEEDED,status.FAILED):break p.pump(1.) rest=[] for _ in range(10):p.pump(.1);rest.append(p.get_state()) if any(s is None for s in rest):raise RuntimeError('missing stop truth') status=p.status[-1] statuses=p.status[first_status:];commands=p.commands[first_cmd:] contacts=p.contacts[first_contacts:] err=math.hypot(rest[-1]['pos'][0]-xs[-1],rest[-1]['pos'][1]-LANE_Y) goal_z=msg.poses[-1].pose.position.z+.15 drift=max(math.dist(s['pos'],rest[0]['pos']) for s in rest) checks=dict(acknowledged=status.goal_id>old_id, state_as_expected=status.state==(status.FAILED if blocked else status.SUCCEEDED), perception_fresh=p.ready, stopped=drift<.02 and max(math.hypot(*s['twist_world'][:2]) for s in rest)<.01, original_goal_preserved=abs(status.goal.x-xs[-1])<1e-6 and abs(status.goal.y-LANE_Y)<1e-6) if blocked: checks.update(never_active=not any(s.state==s.ACTIVE for s in statuses), stationary=max(math.dist(s['pos'],first['pos']) for s in states)<.02, zero_commands=bool(commands) and all(max(abs(c[k]) for k in ('vx','vy','wz'))<1e-6 for c in commands)) else: mid=[s for s in states if -.350 else 'ramp_south') in pair for m in contacts for s in m.states for pair in (s.collision1_name,s.collision2_name)), penetration=bool(contacts) and max((d for m in contacts for s in m.states for d in s.depths),default=1)<.005) return dict(checks=checks,ok=all(checks.values()),duration_sim_s=p.now()-t0, goal=[xs[-1],LANE_Y,goal_z],position_error_m=err,stop_drift_m=drift, input_path=[[s.pose.position.x,s.pose.position.y,s.pose.position.z] for s in msg.poses], samples=states,stop_samples=rest,commands=commands, statuses=[dict(t=s.header.stamp.sec+s.header.stamp.nanosec*1e-9,state=s.state,reason=s.reason, goal=[s.goal.x,s.goal.y,s.goal.z],traj_id=s.traj_id) for s in statuses]) def main(): global LANE_Y ap=argparse.ArgumentParser();ap.add_argument('--out',required=True) ap.add_argument('--side',choices=('red','blue'),default='red') ap.add_argument('--case',choices=('round_trip','stairs_rejected'),default='round_trip') args=ap.parse_args() if args.side=='blue':LANE_Y=-LANE_Y 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') source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source) report=dict(status='INVALID',side=args.side,cases={},collector_sha256=hashlib.sha256(source).hexdigest()) sim,p=Sim(str(out/'sim')),None try: spawn=(1.5,LANE_Y,.5,0.) if args.case=='stairs_rejected' else (3.5,LANE_Y,.15,0.) ok,why=sim.start(navigation=True,terrain=True,spawn=spawn);report['startup']=why if not ok:raise RuntimeError(why) rclpy.init();p=TerrainProbe() if not p.wait_clock():raise RuntimeError('no clock') end=time.monotonic()+90 while time.monotonic()0:break else:raise RuntimeError('terrain pipeline not ready') p.pump(2.) # A distant goal outside the sliding map is allowed to approach before # re-evaluation. Test immediate rejection only with the goal observed. cases=([('stairs_rejected',[1.5,-2.5],True)] if args.case=='stairs_rejected' else [('uphill',[3.5,2.7,-.8,-1.2],False),('downhill',[-1.2,-.8,2.7,3.5],False)]) for name,xs,blocked in cases: result=run_path(p,xs,blocked) report['cases'][name]=result (out/(name+'.json')).write_text(json.dumps(result,indent=2)+'\n') np.savez_compressed(out/(name+'_map.npz'),**{t:points(m) for t,m in p.clouds.items()}) print(name,result['checks'],'error',result['position_error_m'],flush=True) if not result['ok']:break report['status']='PASS' if len(report['cases'])==len(cases) and all(c['ok'] for c in report['cases'].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)+'\n') return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']] if __name__=='__main__':sys.exit(main())