#!/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]+.015)<=.42)&(np.abs(pr[:,1])<=.42)&(pr[:,2]+.33>=-.17)&(pr[:,2]+.33<=.28) 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()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 -.35t0] 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())