#!/usr/bin/python3 """SCAN navigation using LIO only; independent physical arrival and fault-stop checks.""" import argparse import hashlib import json import math import os from pathlib import Path import signal import sys import time import rclpy from geometry_msgs.msg import PoseStamped from nav_msgs.msg import Odometry from sensor_msgs.msg import PointCloud2 from std_msgs.msg import String from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data from check_omni_robot import Sim,sim_env, shutdown_probe from check_scan_navigation import NavProbe,run_goal from check_slope_drive import SlopeProbe class LioNavProbe(NavProbe): get_state=SlopeProbe.get_state def __init__(self): super().__init__(map_diagnostics=False);self.navigation_status=[];self.nav_odom=[];self.lio_odom=[] # The route/fault checks do not need the full dense 3D visualization maps. # Avoid requesting tens of MB/s merely to save diagnostic point counts. self.create_subscription(String,'/sim/navigation/status',lambda m:self.navigation_status.append(json.loads(m.data)), QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL)) self.create_subscription(Odometry,'/sim/navigation/body_odom',lambda m:self.nav_odom.append(m),100) self.create_subscription(Odometry,'/sim/lio/aft_mapped_to_init',lambda m:self.lio_odom.append(m),100) for topic in ('/sim/navigation/planning_cloud','/sim/navigation/cloud_registered'): self.create_subscription(PointCloud2,topic,lambda m,topic=topic:self.clouds.update({topic:m}),qos_profile_sensor_data) def graph_evidence(out,probe,planning_topic='/sim/navigation/planning_cloud',extra_nodes=()): info={} for node in ('/lio_navigation_adapter','/sim/lio/point_lio_sim','/scan_planner_node','/closed_loop_controller')+tuple(extra_nodes): name=node.rsplit('/',1)[1];namespace=node.rsplit('/',1)[0] or '/' deadline=time.monotonic()+15 while time.monotonic()=(2 if node in extra_nodes else 3):break except RuntimeError:pass rclpy.spin_once(probe,timeout_sec=.05) else:raise RuntimeError('graph discovery incomplete: '+node) topics=[topic for topic,_ in subscribers] info[node]=dict(subscribers='\n'.join(topic+': '+','.join(types) for topic,types in subscribers), topics=topics,clients='\n'.join(topic for topic,_ in clients)) (out/(node.strip('/').replace('/','_')+'_node.json')).write_text(json.dumps(info[node],indent=2)+'\n') checks=dict(no_truth_input=all(all(t not in d['topics'] for t in ( '/odom','/body_odom','/aft_mapped_to_init','/tf','/tf_static','/gazebo/model_states','/gazebo/link_states')) and all(t not in d['clients'] for t in ('get_entity_state','get_model_state')) for d in info.values()), estimator_sensors_only=all(t in info['/sim/lio/point_lio_sim']['topics'] for t in ('/sim/mid360/lidar','/sim/mid360/imu')), adapter_lio_only=all(t in info['/lio_navigation_adapter']['topics'] for t in ('/sim/lio/aft_mapped_to_init','/sim/lio/cloud_registered_full_lidar')), controller_uses_estimate='/sim/navigation/body_odom' in info['/closed_loop_controller']['topics'], planner_uses_estimate=all(t in info['/scan_planner_node']['topics'] for t in ('/sim/navigation/body_odom','/sim/navigation/sensor_odom',planning_topic))) return dict(checks=checks,ok=all(checks.values()),nodes=info) def fault_stop(p,sim): goal=PoseStamped();goal.header.frame_id='world';goal.header.stamp=p.get_clock().now().to_msg() goal.pose.position.x=-3.6;goal.pose.position.y=4.5;goal.pose.position.z=.15;goal.pose.orientation.w=1. p.goal_pub.publish(goal);deadline=time.monotonic()+60 while time.monotonic().1:break else:raise RuntimeError('fault case never moved') candidates=[] for pid in sim.known: try: if b'/pointlio_mapping' in Path('/proc/%d/cmdline'%pid).read_bytes():candidates.append(pid) except FileNotFoundError:pass if len(candidates)!=1:raise RuntimeError('no single owned Point-LIO process: '+repr(candidates)) pid=candidates[0];samples=[];readiness=[];start_cmd=len(p.commands);t0=p.now() if not sim.owns(pid):raise RuntimeError('Point-LIO ownership marker changed') try: os.kill(pid,signal.SIGSTOP) while p.now()-t0<1.3: p.pump(.05);s=p.get_state() if s is None:raise RuntimeError('missing independent physical state') samples.append(s);readiness.append(dict(t=p.now(),ready=p.ready)) finally: last_nav_stamp=(p.nav_odom[-1].header.stamp.sec+p.nav_odom[-1].header.stamp.nanosec*1e-9) if p.nav_odom else None os.kill(pid,signal.SIGCONT) stop=next((s['stamp']-t0 for s in samples if math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02),None) late=[s for s in samples if s['stamp']-t0>.7] drift=max(math.dist(s['pos'],late[0]['pos']) for s in late) if late else None checks=dict(started_moving=True,readiness_revoked=any(not s['ready'] for s in readiness), stopped_in_time=stop is not None and 0<=stop<=.5, remained_stopped=bool(late) and drift<.02 and all(math.hypot(*s['twist_world'][:2])<.01 for s in late), no_truth_fallback=last_nav_stamp is not None and last_nav_stampt0 for s in p.navigation_status) checks['no_motion_after_resume']=all(math.hypot(*s['twist_world'][:2])<.01 for s in resumed) return dict(name='lio_loss_stop',checks=checks,ok=all(checks.values()),owned_lio_pid=pid, stop_latency_sim_s=stop,drift_m=drift,samples=samples,resumed_samples=resumed, last_nav_stamp_during_loss=last_nav_stamp,loss_start_stamp=t0,readiness=readiness,commands=p.commands[start_cmd:]) def near_goal_recovery(p,sim): candidates=[] for pid in sim.known: try: if b'/lio_navigation_adapter.py' in Path('/proc/%d/cmdline'%pid).read_bytes() and sim.owns(pid):candidates.append(pid) except FileNotFoundError:pass if len(candidates)!=1:raise RuntimeError('cannot identify one owned navigation adapter') event={};pid=candidates[0] def pause_near_goal(state): distance=math.hypot(state['pos'][0]+3.8,state['pos'][1]-4.5) if event or not (.12event['resumed'] and s['state']==1 and s['traj_id']>max(before) for s in result['statuses']) result['event']=event;result['ok']=all(checks.values());return result def main(): ap=argparse.ArgumentParser();ap.add_argument('--out',required=True) group=ap.add_mutually_exclusive_group();group.add_argument('--straight-only',action='store_true');group.add_argument('--fault-only',action='store_true');group.add_argument('--recovery-only',action='store_true') ap.add_argument('--laps',type=int,default=1) ap.add_argument('--sensor-profile',choices=('ideal','mild','stress'),default='ideal') ap.add_argument('--split',action='store_true') ap.add_argument('--gui',action='store_true',help='Show Gazebo while testing (default: headless)') args=ap.parse_args() if not 1<=args.laps<=5 or (args.laps>1 and (args.straight_only or args.fault_only or args.recovery_only)): ap.error('laps must be 1..5 and multi-lap mode requires complete navigation') 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',cases=[],sensor_profile=args.sensor_profile,laps=args.laps,split=args.split,gui=args.gui,collector_sha256=hashlib.sha256(source).hexdigest()) sim,p=Sim(str(out/'sim')),None try: ok,why=sim.start(lio_navigation=True,sensor_profile=args.sensor_profile,split=args.split,gui=args.gui);report['startup']=why if not ok:raise RuntimeError(why) rclpy.init();p=LioNavProbe() if not p.wait_clock():raise RuntimeError('missing clock') deadline=time.monotonic()+90 while time.monotonic()=2 and len(p.nav_odom)>20:break else:raise RuntimeError('LIO navigation never became ready') report['graph']=graph_evidence(out,p) if not report['graph']['ok']: report['status']='FAIL';return 30 p.pump(1.) if args.fault_only:report['cases'].append(fault_stop(p,sim)) elif args.recovery_only:report['cases'].append(near_goal_recovery(p,sim)) else: # Keep the whole 8 cm arrival-tolerance region and terminal-turn # envelope clear of the now-observed L1 corner. No margin is reduced. goals=[('straight',-3.8,4.5,0.),('lateral',-3.8,3.5,0.),('return_and_turn',-4.5,4.5,math.pi/2)] if args.straight_only:goals=goals[:1] fixture=False for lap in range(args.laps): lapdir=out if args.laps==1 else out/('lap_%d'%(lap+1));lapdir.mkdir(exist_ok=True) for name,x,y,yaw in goals: result=run_goal(p,name,x,y,yaw,goal_z=.15,settle_timeout=.2) result['lap']=lap+1;report['cases'].append(result) (lapdir/(name+'.json')).write_text(json.dumps(result,indent=2)+'\n') print('lap',lap+1,name,result['checks'],'error',result['position_error_m'],flush=True) if not result['ok']:break if not all(c['ok'] for c in report['cases']):break if not args.straight_only: if not fixture: (out/'test_obstacle.sdf').write_text(p.add_obstacle());fixture=True;p.pump(2.) result=run_goal(p,'detour',-4.5,1.5,math.pi/2,obstacle=True,goal_z=.15,settle_timeout=.2) result['lap']=lap+1;report['cases'].append(result) (lapdir/'detour.json').write_text(json.dumps(result,indent=2)+'\n') print('lap',lap+1,'detour',result['checks'],'error',result['position_error_m'],flush=True) if not result['ok']:break expected=1 if args.straight_only or args.fault_only or args.recovery_only else 4*args.laps report['status']='PASS' if len(report['cases'])==expected and all(c['ok'] for c in report['cases']) else 'FAIL' report['navigation_status']=p.navigation_status report['observed_tf_edges']=p.tf_pairs report['input_reference_frames']=sorted({(m.header.frame_id,m.child_frame_id) for m in p.nav_odom}) 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())