对tools进行了整理,Xmake也改为相对路径,在线 LiDAR-IMU 定位器实现
This commit is contained in:
1 parent
0602144ac5
commit
4502296915
70 files changed
+2652
-1298
No files matched your search
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Replay the same recorded southeast scans against two maps."""
|
||||
|
||||
import argparse
|
||||
from bisect import bisect_left
|
||||
import csv
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import project_env
|
||||
|
||||
|
||||
def rotation(quaternion):
|
||||
x, y, z, w = np.asarray(quaternion)/np.linalg.norm(quaternion)
|
||||
return np.array(((1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)),
|
||||
(2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)),
|
||||
(2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y))))
|
||||
|
||||
|
||||
def east_scans(dataset):
|
||||
rows = [list(map(float, l.split())) for l in (dataset/'truth.tum').read_text().splitlines()]
|
||||
if not rows:
|
||||
raise ValueError('southeast evaluation requires recorded ground truth')
|
||||
times = [r[0] for r in rows]
|
||||
mask = set()
|
||||
with (dataset/'scans.csv').open() as scans:
|
||||
for entry in csv.DictReader(scans):
|
||||
stamp = float(entry['timestamp'])
|
||||
index = bisect_left(times, stamp)
|
||||
if index == len(times) or (index > 0 and stamp-times[index-1] < times[index]-stamp):
|
||||
index -= 1
|
||||
time, x, y = rows[index][:3]
|
||||
if abs(time-stamp) <= 0.05 and x >= 4 and y <= -1.5:
|
||||
mask.add(stamp)
|
||||
return mask
|
||||
|
||||
|
||||
def compare_trace(path, stamps, imu_from_base):
|
||||
inliers, horizontal, horizontal_prior = [], [], []
|
||||
degenerate = x_weak = full = 0
|
||||
x, y, z = imu_from_base
|
||||
skew = np.array(((0, -z, y), (z, 0, -x), (-y, x, 0)))
|
||||
with path.open() as trace:
|
||||
for row in csv.DictReader(trace):
|
||||
phase = row['phase']
|
||||
stamp = float(row['scan_time'])
|
||||
if stamp not in stamps or phase == 'candidate':
|
||||
continue
|
||||
p = np.array([[float(row[f'P{i}_{j}']) for j in range(18)] for i in range(18)])
|
||||
j = np.zeros((2, 18))
|
||||
j[0, 0] = j[1, 1] = 1
|
||||
j[:, 6:9] = -(rotation([float(row[k]) for k in ('qx','qy','qz','qw')])@skew)[:2, :]
|
||||
sigma = 3*float(np.sqrt(max(0, np.linalg.eigvalsh(j@p@j.T)[-1])))
|
||||
if phase == 'prediction':
|
||||
if row['registration_stage'] != 'NOT_RUN':
|
||||
horizontal_prior.append(sigma)
|
||||
continue
|
||||
horizontal.append(sigma)
|
||||
inliers.append(int(row['inliers']))
|
||||
full += row['mode'] == 'FULL'
|
||||
dims = int(row['degenerate'])
|
||||
if dims:
|
||||
h = np.array([[float(row[f'H{i}_{j}']) for j in range(6)] for i in range(6)])
|
||||
if np.any(h):
|
||||
vt = np.linalg.svd(h)[2]
|
||||
x_weak += int(np.linalg.norm(vt[-dims:, 0]) >= 0.8)
|
||||
degenerate += 1
|
||||
if not inliers:
|
||||
raise RuntimeError('replay did not include the recorded southeast scans')
|
||||
return {'east_scans': len(inliers), 'accepted': full,
|
||||
'median_inliers': statistics.median(inliers), 'degenerate_scans': degenerate,
|
||||
'x_weak_scans': x_weak, 'maximum_horizontal_3sigma_m': max(horizontal),
|
||||
'maximum_prior_horizontal_3sigma_m': max(horizontal_prior, default=None)}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ('dataset', 'baseline', 'candidate', 'output'):
|
||||
parser.add_argument(f'--{name}', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
stamps = east_scans(args.dataset)
|
||||
if len(stamps) < 10:
|
||||
parser.error('verification dataset must contain at least ten scans in x >= 4, y <= -1.5')
|
||||
transform = next(line for line in (args.dataset/'config.txt').read_text().splitlines()
|
||||
if line.startswith('base_from_imu ')).split()[1:]
|
||||
extrinsic = list(map(float, transform))
|
||||
imu_from_base = -rotation(extrinsic[3:]).T @ extrinsic[:3]
|
||||
exe = project_env.require_executable(project_env.find_bin_dir()/'field_localization_replay',
|
||||
'field_localization_replay')
|
||||
args.output.mkdir(parents=True)
|
||||
reports = {}
|
||||
for name, world_map in (('baseline', args.baseline), ('candidate', args.candidate)):
|
||||
directory = args.output/name
|
||||
subprocess.run([str(exe), '--dataset', str(args.dataset), '--mode', 'localization',
|
||||
'--map', str(world_map), '--output', str(directory)], check=True)
|
||||
reports[name] = compare_trace(directory/'filter_trace.csv', stamps, imu_from_base)
|
||||
content = json.dumps(reports, indent=2)
|
||||
(args.output/'southeast.json').write_text(content+'\n')
|
||||
print(content)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Independent-frame trajectory metrics; no alignment or ground-truth feedback."""
|
||||
import bisect
|
||||
import math
|
||||
|
||||
|
||||
def conjugate(q):
|
||||
return [-q[0],-q[1],-q[2],q[3]]
|
||||
|
||||
|
||||
def multiply(a,b):
|
||||
x,y,z,w=a;X,Y,Z,W=b
|
||||
return [w*X+x*W+y*Z-z*Y,w*Y-x*Z+y*W+z*X,w*Z+x*Y-y*X+z*W,w*W-x*X-y*Y-z*Z]
|
||||
|
||||
|
||||
def rotate(q,p):
|
||||
return multiply(multiply(q,[*p,0]),conjugate(q))[:3]
|
||||
|
||||
|
||||
def angle(q):
|
||||
return 2*math.acos(min(1,abs(q[3])/math.sqrt(sum(x*x for x in q))))
|
||||
|
||||
|
||||
def interpolate(rows,t,gap=0.05):
|
||||
i=bisect.bisect_left(rows,[t])
|
||||
if i<len(rows) and abs(rows[i][0]-t)<1e-8:return rows[i][1:]
|
||||
if i==0 or i==len(rows) or rows[i][0]-rows[i-1][0]>gap:return None
|
||||
a,b=rows[i-1],rows[i];u=(t-a[0])/(b[0]-a[0])
|
||||
p=[(1-u)*a[j]+u*b[j] for j in range(1,4)]
|
||||
sign=1 if sum(a[j]*b[j] for j in range(4,8))>=0 else -1
|
||||
q=[(1-u)*a[j]+u*sign*b[j] for j in range(4,8)];norm=math.sqrt(sum(x*x for x in q))
|
||||
return p+[x/norm for x in q]
|
||||
|
||||
|
||||
def metrics(estimate,truth):
|
||||
# A single pose per stamp; ordering changes never create false zero-duration RPE.
|
||||
estimate=sorted({row[0]:row for row in estimate}.values())
|
||||
truth=sorted({row[0]:row for row in truth}.values())
|
||||
translation=[];rotation=[];relative_t=[];relative_r=[]
|
||||
for row in estimate:
|
||||
t=row[0];e=row[1:];g=interpolate(truth,t)
|
||||
if g is None:continue
|
||||
translation.append(sum((e[j]-g[j])**2 for j in range(3)))
|
||||
rotation.append(angle(multiply(conjugate(g[3:]),e[3:]))**2)
|
||||
en=interpolate(estimate,t+1);gn=interpolate(truth,t+1)
|
||||
if en is None or gn is None:continue
|
||||
ep=rotate(conjugate(e[3:]),[en[j]-e[j] for j in range(3)])
|
||||
gp=rotate(conjugate(g[3:]),[gn[j]-g[j] for j in range(3)])
|
||||
relative_t.append(sum((ep[j]-gp[j])**2 for j in range(3)))
|
||||
eq=multiply(conjugate(e[3:]),en[3:]);gq=multiply(conjugate(g[3:]),gn[3:])
|
||||
relative_r.append(angle(multiply(conjugate(gq),eq))**2)
|
||||
def rmse(values):return math.sqrt(sum(values)/len(values)) if values else None
|
||||
return {'matched':len(translation),'total':len(estimate),'rpe_pairs':len(relative_t),
|
||||
'ate_translation_m':rmse(translation),'ate_rotation_deg':None if not rotation else math.degrees(rmse(rotation)),
|
||||
'rpe_1s_translation_m':rmse(relative_t),'rpe_1s_rotation_deg':None if not relative_r else math.degrees(rmse(relative_r)),
|
||||
'maximum_position_error_m':math.sqrt(max(translation)) if translation else None}
|
||||
|
||||
|
||||
def cylinder_clearance(row,x,y,radius):
|
||||
q=row[4:];yaw=math.atan2(2*(q[3]*q[2]+q[0]*q[1]),1-2*(q[1]*q[1]+q[2]*q[2]))
|
||||
dx,dy=x-row[1],y-row[2]
|
||||
bx=math.cos(yaw)*dx+math.sin(yaw)*dy;by=-math.sin(yaw)*dx+math.cos(yaw)*dy
|
||||
# Union of the actual SDF chassis and gimbal collision boxes.
|
||||
chassis=math.hypot(max(0,abs(bx)-0.289),max(0,abs(by)-0.2605))
|
||||
gimbal=math.hypot(max(0,abs(bx-0.12)-0.20),max(0,abs(by)-0.15))
|
||||
return min(chassis,gimbal)-radius
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run three cold starts per route/launcher, plus a blocked-goal check."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--launcher',choices=['shell','python'],required=True)
|
||||
parser.add_argument('--output',type=Path,required=True)
|
||||
parser.add_argument('--map',type=Path,required=True)
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]')
|
||||
parser.add_argument('--scenario', action='append', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'])
|
||||
parser.add_argument('--repeats', type=int)
|
||||
args=parser.parse_args()
|
||||
if args.repeats is not None and args.repeats < 1:
|
||||
parser.error('repeats must be positive')
|
||||
if args.output.exists():parser.error('output must be new')
|
||||
args.output.mkdir(parents=True)
|
||||
script_dir = Path(__file__).resolve().parent
|
||||
root = script_dir.parents[1]
|
||||
results=[]
|
||||
for scenario in args.scenario or ['clear', 'cylinder', 'blocked']:
|
||||
count = args.repeats if args.repeats is not None else (3 if scenario in ('clear', 'cylinder') else 1)
|
||||
for index in range(1, count+1):
|
||||
name=f'{scenario}_{index}';folder=args.output/name
|
||||
with open(args.output/(name+'.log'),'w') as log:
|
||||
command=[sys.executable,str(script_dir/'validate_lio_navigation.py'),
|
||||
'--launcher',args.launcher,'--map',str(args.map.resolve()),'--output',str(folder.resolve()),
|
||||
'--scenario',scenario,'--goal','0','0']
|
||||
if args.domain is not None:
|
||||
command.extend(['--domain', str(args.domain)])
|
||||
child=subprocess.Popen(command,cwd=root,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
|
||||
try:code=child.wait()
|
||||
except KeyboardInterrupt:
|
||||
child.send_signal(signal.SIGINT)
|
||||
child.wait(timeout=30)
|
||||
raise
|
||||
file=folder/'result.json'
|
||||
result=json.loads(file.read_text()) if file.exists() else {'passed':False,'error':'no result'}
|
||||
results.append({'name':name,'exit_code':code,**result})
|
||||
(args.output/'summary.json').write_text(json.dumps(results,indent=2))
|
||||
print(f'{args.launcher} {name}: passed={result.get("passed")} goal={result.get("goal_succeeded")} metrics={result.get("trajectory_metrics")}',flush=True)
|
||||
return 0 if all(r['passed'] and r['exit_code']==0 for r in results) else 1
|
||||
|
||||
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
@@ -0,0 +1,532 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run an isolated Gazebo navigation scenario and score it using simulator truth."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.action import ActionClient
|
||||
from action_msgs.msg import GoalStatus
|
||||
from rclpy.parameter import Parameter
|
||||
from lifecycle_msgs.srv import GetState
|
||||
from tf2_msgs.msg import TFMessage
|
||||
from nav2_msgs.srv import IsPathValid
|
||||
from nav2_msgs.action import ComputePathToPose, FollowPath
|
||||
from nav_msgs.msg import Odometry
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from std_msgs.msg import Bool
|
||||
from rcl_interfaces.srv import GetParameters
|
||||
from std_srvs.srv import Trigger
|
||||
from rclpy.utilities import get_rmw_implementation_identifier
|
||||
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'),
|
||||
str(Path(__file__).resolve().parents[1])]
|
||||
import project_env
|
||||
from arena_grid import ARENA_GOALS, START, ArenaGrid
|
||||
from nav2_startup import path_probe_request
|
||||
|
||||
from dds_environment import defaults as dds_defaults
|
||||
from lio_metrics import cylinder_clearance, metrics
|
||||
from verify_lio_stack import NODES, process_environment
|
||||
|
||||
|
||||
ROUND_TRIP = ((0.0, 0.0), (-5.0, 3.0), (0.0, 0.0), (-5.0, 3.0), (0.0, 0.0))
|
||||
ROUND_TRIP_PAUSES = (0, 24, 10, 35, 16)
|
||||
|
||||
|
||||
def check_field_coverage(node, grid):
|
||||
coverage = grid.coverage()
|
||||
client = ActionClient(node, ComputePathToPose, '/compute_path_to_pose')
|
||||
try:
|
||||
if not client.wait_for_server(timeout_sec=8):
|
||||
raise RuntimeError('compute_path_to_pose unavailable for field coverage')
|
||||
|
||||
def pose(point):
|
||||
message = PoseStamped()
|
||||
message.header.frame_id = 'map'
|
||||
message.pose.position.x, message.pose.position.y = point
|
||||
message.pose.orientation.w = 1.0
|
||||
return message
|
||||
|
||||
checks = []
|
||||
for point in coverage.pop('samples'):
|
||||
request = ComputePathToPose.Goal()
|
||||
request.start = pose(START)
|
||||
request.goal = pose(point)
|
||||
request.use_start = True
|
||||
future = client.send_goal_async(request)
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=5)
|
||||
handle = future.result() if future.done() else None
|
||||
check = {'target': point, 'passed': False}
|
||||
if handle is None or not handle.accepted:
|
||||
check['error'] = 'goal rejected or acceptance timed out'
|
||||
else:
|
||||
future = handle.get_result_async()
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=5)
|
||||
wrapped = future.result() if future.done() else None
|
||||
if wrapped is None:
|
||||
cancel = handle.cancel_goal_async()
|
||||
rclpy.spin_until_future_complete(node, cancel, timeout_sec=1)
|
||||
check['error'] = 'planner response timed out'
|
||||
else:
|
||||
outcome = wrapped.result
|
||||
check.update(error_code=outcome.error_code, error=outcome.error_msg)
|
||||
if wrapped.status == GoalStatus.STATUS_SUCCEEDED and outcome.path.poses:
|
||||
endpoint = outcome.path.poses[-1].pose.position
|
||||
check['endpoint_error_m'] = math.hypot(endpoint.x-point[0], endpoint.y-point[1])
|
||||
check['passed'] = outcome.error_code == 0 and check['endpoint_error_m'] <= 0.30
|
||||
checks.append(check)
|
||||
finally:
|
||||
client.destroy()
|
||||
coverage.update(planned=sum(c['passed'] for c in checks), sample_count=len(checks), checks=checks)
|
||||
return coverage
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--map', type=Path, required=True)
|
||||
parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC') or '/scan/points_lio')
|
||||
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
goals = parser.add_mutually_exclusive_group()
|
||||
goals.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
|
||||
goals.add_argument('--full-field', action='store_true',
|
||||
help='check reachability in 1 m tiles and navigate the whole-field route')
|
||||
goals.add_argument('--round-trip-regression', action='store_true',
|
||||
help='run the five recorded goals without restarting the stack')
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]',
|
||||
help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests')
|
||||
parser.add_argument('--timeout', type=float, default=420.0,
|
||||
help='whole-stack validation deadline, including up to three startup attempts')
|
||||
parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear')
|
||||
parser.add_argument('--obstacle-x',type=float,default=-4.0)
|
||||
parser.add_argument('--obstacle-y',type=float,default=-1.5)
|
||||
parser.add_argument('--obstacle-radius',type=float,default=0.22)
|
||||
parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load')
|
||||
args = parser.parse_args()
|
||||
if args.round_trip_regression and args.scenario not in ('clear', 'cylinder'):
|
||||
parser.error('--round-trip-regression requires clear or cylinder')
|
||||
if args.full_field and args.scenario != 'clear':
|
||||
parser.error('--full-field starts the clear-field coverage route')
|
||||
multileg = args.round_trip_regression or args.full_field
|
||||
route = ARENA_GOALS if args.full_field else ROUND_TRIP if args.round_trip_regression else ((args.goal,) if args.goal else ())
|
||||
pauses = ROUND_TRIP_PAUSES if args.round_trip_regression else (0,)*len(route)
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
if args.output.exists():
|
||||
parser.error('output must be a new directory')
|
||||
workspace = project_env.WORKSPACE
|
||||
try:
|
||||
gz_exe = project_env.find_gz_bin()
|
||||
bin_dir = project_env.find_bin_dir(workspace)
|
||||
recorder_exe = project_env.require_executable(bin_dir/'field_localization_record',
|
||||
'field_localization_record')
|
||||
grid = ArenaGrid(project_env.find_map_yaml()) if args.full_field else None
|
||||
if route:
|
||||
nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client')
|
||||
except (project_env.ProbeError, ValueError, OSError) as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
args.output.mkdir(parents=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
ROS2CLI_DISABLE_DAEMON='1',
|
||||
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
|
||||
LIO_MAP=str(args.map.resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()),
|
||||
LIO_TRACE_PATH=str((args.output/'filter_trace.csv').resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir), LIO_POINT_CLOUD_TOPIC=args.lio_cloud_topic)
|
||||
os.environ.update(dds_defaults(os.environ))
|
||||
os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve()))
|
||||
os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve()))
|
||||
params_file = workspace/'src/sentry_sim/config/nav2_params.yaml'
|
||||
runtime = {
|
||||
'domain': os.environ['ROS_DOMAIN_ID'],
|
||||
'partition': os.environ['GZ_PARTITION'],
|
||||
'scenario': args.scenario,
|
||||
'obstacle': [args.obstacle_x, args.obstacle_y, args.obstacle_radius],
|
||||
'goals': route,
|
||||
'pauses_wall_sec': pauses,
|
||||
'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(),
|
||||
'lio_map_sha256': hashlib.sha256(args.map.read_bytes()).hexdigest(),
|
||||
'point_cloud_topic': args.lio_cloud_topic,
|
||||
}
|
||||
(args.output/'runtime.json').write_text(json.dumps(runtime, indent=2))
|
||||
log = None
|
||||
record_duration = 3600.0 if args.full_field else 1200.0 if multileg else 600.0
|
||||
record_log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
recorder = subprocess.Popen([str(recorder_exe), '--ros-args',
|
||||
'-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset',
|
||||
'-p', f'duration_sec:={record_duration}', '-p', f'point_cloud_topic:={args.lio_cloud_topic}'],
|
||||
stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
if args.launcher == 'shell':
|
||||
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
||||
else:
|
||||
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
|
||||
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
|
||||
log = open(args.output/'stack.log', 'w', encoding='utf8')
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
|
||||
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
rclpy.init()
|
||||
node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
publishers = set()
|
||||
samples = {'truth': [], 'estimate': []}
|
||||
health_events = []
|
||||
health_transitions = []
|
||||
actuator = []
|
||||
last_map_tf_wall = None
|
||||
|
||||
def on_health(msg):
|
||||
stamp = time.monotonic()
|
||||
if not health_events or msg.data != health_events[-1][1]:
|
||||
health_transitions.append({'wall': stamp, 'sim': sim_now(), 'valid': msg.data})
|
||||
health_events.append((stamp, msg.data))
|
||||
|
||||
def sim_now():
|
||||
return node.get_clock().now().nanoseconds * 1e-9
|
||||
|
||||
def spin_for(seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited during navigation')
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
subscription_actuator=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda msg:actuator.append((time.monotonic(),msg.linear.x,msg.linear.y,msg.angular.z)),100)
|
||||
subscriptions_health=node.create_subscription(Bool,'/field_localization/navigation_valid',
|
||||
on_health, 10)
|
||||
subscriptions = []
|
||||
def sample(message, name):
|
||||
p = message.pose.pose if name == 'estimate' else message.pose
|
||||
samples[name].append([message.header.stamp.sec+1e-9*message.header.stamp.nanosec,
|
||||
p.position.x,p.position.y,p.position.z,p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w])
|
||||
subscriptions.append(node.create_subscription(PoseStamped, '/evaluation/ground_truth',
|
||||
lambda msg: sample(msg, 'truth'), qos_profile_sensor_data))
|
||||
subscriptions.append(node.create_subscription(Odometry, '/field_localization/odometry',
|
||||
lambda msg: sample(msg, 'estimate'), qos_profile_sensor_data))
|
||||
counts = {'map_to_odom': 0, 'map_to_base_link': 0}
|
||||
|
||||
def on_tf(msg, info):
|
||||
nonlocal last_map_tf_wall
|
||||
for transform in msg.transforms:
|
||||
if transform.header.frame_id != 'map':
|
||||
continue
|
||||
if transform.child_frame_id == 'odom':
|
||||
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
|
||||
publishers.add(json.dumps(gid, sort_keys=True, default=str))
|
||||
counts['map_to_odom'] += 1
|
||||
last_map_tf_wall = time.monotonic()
|
||||
if transform.child_frame_id == 'base_link':
|
||||
counts['map_to_base_link'] += 1
|
||||
|
||||
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
|
||||
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
|
||||
path_client = node.create_client(IsPathValid, '/is_path_valid')
|
||||
active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
|
||||
parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
|
||||
states = {}
|
||||
processes = []
|
||||
rviz = None
|
||||
goal = None
|
||||
reached_readiness = False
|
||||
result = {}
|
||||
try:
|
||||
if args.rviz:
|
||||
rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d',
|
||||
str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true'],
|
||||
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'},
|
||||
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
deadline = time.monotonic()+args.timeout
|
||||
last_check = 0.0
|
||||
stable_since = None
|
||||
manager_completed = False
|
||||
while time.monotonic() < deadline:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited')
|
||||
if time.monotonic()-last_check < 0.5:
|
||||
continue
|
||||
last_check = time.monotonic()
|
||||
if not processes and time.monotonic()-started > 8:
|
||||
processes = process_environment(process.pid)
|
||||
states = {}
|
||||
pending = {}
|
||||
for name, client in clients.items():
|
||||
if not client.service_is_ready():
|
||||
continue
|
||||
pending[name] = client.call_async(GetState.Request())
|
||||
poll_end = time.monotonic()+1
|
||||
while time.monotonic() < poll_end and any(not f.done() for f in pending.values()):
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
for name, future in pending.items():
|
||||
if future.done() and future.result():
|
||||
states[name] = future.result().current_state.id
|
||||
else:
|
||||
clients[name].remove_pending_request(future)
|
||||
log_path = args.output/'stack.log'
|
||||
text = log_path.read_text(errors='replace') if log_path.exists() else ''
|
||||
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
|
||||
for line in text.splitlines())
|
||||
if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed and health_events and health_events[-1][1]:
|
||||
if stable_since is None:
|
||||
stable_since = time.monotonic()
|
||||
if time.monotonic()-stable_since >= 2:
|
||||
reached_readiness = True
|
||||
break
|
||||
else:
|
||||
stable_since = None
|
||||
processes = process_environment(process.pid)
|
||||
names = sorted(set(node.get_node_names()))
|
||||
path_ready = path_client.wait_for_service(timeout_sec=2)
|
||||
path_response = None
|
||||
if path_ready:
|
||||
future = path_client.call_async(path_probe_request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=3)
|
||||
if future.done() and future.result() is not None:
|
||||
path_response = str(future.result())
|
||||
manager_active = False
|
||||
if active_client.wait_for_service(timeout_sec=1):
|
||||
future = active_client.call_async(Trigger.Request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
manager_active = bool(future.done() and future.result() and future.result().success)
|
||||
managed_nodes = []
|
||||
if parameter_client.wait_for_service(timeout_sec=1):
|
||||
future = parameter_client.call_async(GetParameters.Request(names=['node_names']))
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
if future.done() and future.result() and future.result().values:
|
||||
managed_nodes = list(future.result().values[0].string_array_value)
|
||||
result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started,
|
||||
'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()),
|
||||
'rmw': get_rmw_implementation_identifier(), 'processes': processes,
|
||||
'node_counts': dict(Counter(node.get_node_names())),
|
||||
'services': dict(node.get_service_names_and_types()),
|
||||
'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))),
|
||||
'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))},
|
||||
'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response,
|
||||
'topic_qos': {
|
||||
topic: [{'node': p.node_name, 'reliability': str(p.qos_profile.reliability)}
|
||||
for p in node.get_publishers_info_by_topic(topic)]
|
||||
for topic in dict.fromkeys(('/scan/points', '/scan/points_filtered', args.lio_cloud_topic, '/imu'))
|
||||
},
|
||||
'manager_active': manager_active, 'managed_nodes': managed_nodes,
|
||||
'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
|
||||
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
|
||||
result['passed'] = (reached_readiness and manager_completed and manager_active and path_response is not None
|
||||
and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes)
|
||||
and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
|
||||
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
|
||||
and counts['map_to_base_link'] == 0)
|
||||
if grid is not None and result['passed']:
|
||||
coverage = check_field_coverage(node, grid)
|
||||
result['field_coverage'] = coverage
|
||||
print(f'field coverage: {coverage["planned"]}/{coverage["sample_count"]} representative goals planned', flush=True)
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
if args.scenario in ('cylinder','blocked') and result['passed']:
|
||||
# Obstacle lies on the initial straight corridor; a route around the cylinder exists.
|
||||
shape = f'<cylinder><radius>{args.obstacle_radius}</radius><length>0.8</length></cylinder>'
|
||||
pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0'
|
||||
if args.scenario == 'blocked':
|
||||
shape = '<box><size>1.6 1.6 0.8</size></box>'
|
||||
pose = '0 0 0.4 0 0 0'
|
||||
sdf = f'<sdf version="1.9"><model name="validation_obstacle"><static>true</static><pose>{pose}</pose><link name="body"><collision name="collision"><geometry>{shape}</geometry></collision><visual name="visual"><geometry>{shape}</geometry></visual></link></model></sdf>'
|
||||
gz = project_env.run_gz(gz_exe, 'service', '-s', '/world/rmul_arena/create',
|
||||
'--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000',
|
||||
'--req', 'sdf: '+json.dumps(sdf), timeout=10)
|
||||
(args.output/'obstacle.log').write_text(gz.stdout+gz.stderr)
|
||||
if gz.returncode or 'data: true' not in gz.stdout:
|
||||
raise RuntimeError('obstacle insertion failed')
|
||||
until=time.monotonic()+2
|
||||
while time.monotonic()<until:
|
||||
rclpy.spin_once(node,timeout_sec=0.02)
|
||||
if route and result['passed']:
|
||||
legs = []
|
||||
start_sim = None
|
||||
start_wall = None
|
||||
for index, target in enumerate(route):
|
||||
spin_for(pauses[index])
|
||||
goal_start_sim, goal_start_wall = sim_now(), time.monotonic()
|
||||
if start_sim is None:
|
||||
start_sim, start_wall = goal_start_sim, goal_start_wall
|
||||
goal_log = args.output/(f'goal_{index+1}.log' if multileg else 'goal.log')
|
||||
command = [str(nav_client), *map(str, target), '0']
|
||||
with goal_log.open('w') as stream:
|
||||
goal = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
|
||||
text=True, start_new_session=True)
|
||||
until = time.monotonic() + (240 if args.scenario == 'blocked' else 180)
|
||||
fault_time = None
|
||||
while goal.poll() is None and time.monotonic() < until:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited during navigation')
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
if (args.scenario == 'lidar_loss' and fault_time is None
|
||||
and time.monotonic()-goal_start_wall >= 5 and actuator
|
||||
and sum(abs(v) for v in actuator[-1][1:]) > 0.1):
|
||||
owned = process_environment(process.pid)
|
||||
sensors = [p['pid'] for p in owned if p['executable']
|
||||
and Path(p['executable'][0]).name == 'self_filter']
|
||||
if len(sensors) != 1:
|
||||
raise RuntimeError('cannot identify the owned self_filter for fault injection')
|
||||
fault_time = time.monotonic()
|
||||
os.kill(sensors[0], signal.SIGTERM)
|
||||
timed_out = goal.poll() is None
|
||||
if timed_out:
|
||||
os.killpg(goal.pid, signal.SIGINT)
|
||||
goal.wait(timeout=5)
|
||||
goal_end_wall = time.monotonic()
|
||||
spin_for(0.3)
|
||||
goal_end_sim = sim_now()
|
||||
output = goal_log.read_text()
|
||||
truth_goal = [row for row in samples['truth'] if goal_start_sim <= row[0] <= goal_end_sim]
|
||||
estimate_goal = [row for row in samples['estimate'] if goal_start_sim <= row[0] <= goal_end_sim]
|
||||
leg = {
|
||||
'goal': target, 'goal_exit_code': goal.returncode,
|
||||
'goal_succeeded': not timed_out and goal.returncode == 0 and '结果: ✅ SUCCEEDED' in output,
|
||||
'goal_elapsed_wall_sec': goal_end_wall-goal_start_wall,
|
||||
'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out,
|
||||
'trajectory_metrics': metrics(estimate_goal, truth_goal),
|
||||
'truth_goal_error_m': math.hypot(truth_goal[-1][1]-target[0], truth_goal[-1][2]-target[1]) if truth_goal else None,
|
||||
'minimum_cylinder_clearance_m': min(cylinder_clearance(row, args.obstacle_x, args.obstacle_y, args.obstacle_radius) for row in truth_goal)
|
||||
if truth_goal and args.scenario == 'cylinder' else None,
|
||||
'health_failures_during_goal': sum(not value for stamp, value in health_events
|
||||
if goal_start_wall <= stamp <= goal_end_wall),
|
||||
}
|
||||
if args.scenario == 'blocked':
|
||||
stopped = bool(actuator and actuator[-1][0] > goal_end_wall and actuator[-1][1:] == (0, 0, 0))
|
||||
result['blocked_zero_output'] = stopped
|
||||
leg['passed'] = (not timed_out and '结果: ❌ ABORTED' in output and stopped
|
||||
and leg['health_failures_during_goal'] == 0
|
||||
and leg['truth_goal_error_m'] is not None
|
||||
and leg['truth_goal_error_m'] > 0.30)
|
||||
elif args.scenario == 'lidar_loss':
|
||||
spin_for(0.7)
|
||||
stops = [t for t, x, y, z in actuator if fault_time is not None and t >= fault_time and x == y == z == 0]
|
||||
delay = min(stops)-fault_time if stops else None
|
||||
lost = next((event for event in health_transitions if fault_time is not None
|
||||
and event['wall'] >= fault_time and not event['valid']), None)
|
||||
canceled = '结果: ❌ CANCELED' in output
|
||||
# Once TF stops, FollowPath can complete with TF_ERROR before the relay's
|
||||
# cancel request returns. Both outcomes terminate the in-flight goal.
|
||||
tf_abort = ('结果: ❌ ABORTED' in output
|
||||
and f'Nav2 error_code={FollowPath.Result.TF_ERROR} ' in output)
|
||||
terminated = bool(lost and lost['wall'] <= goal_end_wall and (canceled or tf_abort))
|
||||
result.update(fault_goal_canceled=canceled,
|
||||
fault_goal_tf_aborted=tf_abort,
|
||||
fault_goal_terminated=terminated,
|
||||
fault_stop_delay_sec=delay,
|
||||
fault_tf_halted=bool(lost and last_map_tf_wall is not None
|
||||
and last_map_tf_wall <= lost['wall']+0.1))
|
||||
if lost:
|
||||
retry_log = args.output/'retry_invalid_localization.log'
|
||||
with retry_log.open('w') as stream:
|
||||
retry = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, timeout=20)
|
||||
retry_text = retry_log.read_text()
|
||||
result['invalid_retry_blocked'] = (retry.returncode != 0 and '定位不可用' in retry_text
|
||||
and '目标已接受' not in retry_text)
|
||||
else:
|
||||
result['invalid_retry_blocked'] = False
|
||||
leg['passed'] = (terminated and not timed_out and delay is not None and delay < 0.5
|
||||
and result['fault_tf_halted'] and result['invalid_retry_blocked'])
|
||||
else:
|
||||
leg['passed'] = (leg['goal_succeeded'] and leg['truth_goal_error_m'] is not None
|
||||
and leg['truth_goal_error_m'] <= 0.30
|
||||
and (leg['minimum_cylinder_clearance_m'] is None
|
||||
or leg['minimum_cylinder_clearance_m'] > 0))
|
||||
quality = leg['trajectory_metrics']
|
||||
leg['passed'] = (leg['passed'] and quality['matched'] > 100 and quality['rpe_pairs'] > 0
|
||||
and quality['maximum_position_error_m'] < 0.25 and quality['ate_translation_m'] < 0.1)
|
||||
legs.append(leg)
|
||||
result.update(leg)
|
||||
result['legs'] = legs
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(f'leg {index+1}/{len(route)} {tuple(target)}: passed={leg["passed"]} '
|
||||
f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True)
|
||||
if multileg and not leg['goal_succeeded']:
|
||||
spin_for(8)
|
||||
break
|
||||
result.update(counts)
|
||||
result['map_to_odom_publishers'] = len(publishers)
|
||||
result['amcl_present'] = 'amcl' in node.get_node_names()
|
||||
# Include drift during the pauses, but keep each goal's outcome independent.
|
||||
if multileg:
|
||||
end_sim = legs[-1]['end_sim']
|
||||
quality = metrics(*([row for row in samples[name] if start_sim <= row[0] <= end_sim]
|
||||
for name in ('estimate', 'truth')))
|
||||
result['trajectory_metrics'] = quality
|
||||
result['first_localization_loss'] = next(
|
||||
(event for event in health_transitions if event['wall'] >= start_wall and not event['valid']), None)
|
||||
clearances = [leg['minimum_cylinder_clearance_m'] for leg in legs
|
||||
if leg['minimum_cylinder_clearance_m'] is not None]
|
||||
result['minimum_cylinder_clearance_m'] = min(clearances) if clearances else None
|
||||
result['passed'] = (quality['maximum_position_error_m'] is not None
|
||||
and quality['maximum_position_error_m'] < 0.25
|
||||
and quality['ate_translation_m'] < 0.1
|
||||
and result['first_localization_loss'] is None)
|
||||
if grid is not None:
|
||||
result['passed'] = (result['passed'] and coverage['sample_count'] > 0
|
||||
and coverage['planned'] == coverage['sample_count'])
|
||||
result['passed'] = (result['passed'] and len(legs) == len(route) and all(leg['passed'] for leg in legs)
|
||||
and len(publishers) == 1 and counts['map_to_base_link'] == 0
|
||||
and not result['amcl_present'])
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps({k: v for k, v in result.items() if k not in
|
||||
('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True)
|
||||
if not result['passed']:
|
||||
raise RuntimeError('stack integration validation failed')
|
||||
except Exception as error:
|
||||
result.update(passed=False, error=str(error))
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
raise
|
||||
finally:
|
||||
_ = subscription, subscriptions, subscriptions_health, subscription_actuator
|
||||
(args.output/'health_events.json').write_text(json.dumps(health_events))
|
||||
(args.output/'health_transitions.json').write_text(json.dumps(health_transitions, indent=2))
|
||||
for name, rows in samples.items():
|
||||
with open(args.output/(name+'.tum'),'w') as output:
|
||||
for row in rows:
|
||||
output.write(' '.join(map(str,row))+'\n')
|
||||
if goal is not None and goal.poll() is None:
|
||||
os.killpg(goal.pid, signal.SIGINT)
|
||||
try:
|
||||
goal.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(goal.pid, signal.SIGKILL)
|
||||
goal.wait()
|
||||
if recorder.poll() is None:
|
||||
os.killpg(recorder.pid, signal.SIGINT)
|
||||
try:
|
||||
recorder.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(recorder.pid, signal.SIGKILL)
|
||||
recorder.wait()
|
||||
record_log.close()
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
try:
|
||||
process.wait(timeout=20)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
if rviz is not None:
|
||||
os.killpg(rviz.pid, signal.SIGINT)
|
||||
try:
|
||||
rviz.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(rviz.pid, signal.SIGKILL)
|
||||
rviz.wait()
|
||||
if log:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,255 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Live integration check: isolated Gazebo + LIO + Nav2, no motion commands."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from lifecycle_msgs.srv import GetState
|
||||
from tf2_msgs.msg import TFMessage
|
||||
from nav2_msgs.srv import IsPathValid
|
||||
from rcl_interfaces.srv import GetParameters
|
||||
from std_srvs.srv import Trigger
|
||||
from rclpy.utilities import get_rmw_implementation_identifier
|
||||
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'),
|
||||
str(Path(__file__).resolve().parents[1])]
|
||||
import project_env
|
||||
from nav2_startup import path_probe_request
|
||||
|
||||
NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server',
|
||||
'bt_navigator', 'behavior_server', 'waypoint_follower', 'velocity_smoother',
|
||||
'collision_monitor', 'route_server', 'docking_server', 'following_server']
|
||||
|
||||
ENV_KEYS = ['RMW_IMPLEMENTATION', 'ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS',
|
||||
'FASTDDS_DEFAULT_PROFILES_FILE', 'FASTRTPS_DEFAULT_PROFILES_FILE',
|
||||
'RMW_FASTRTPS_USE_QOS_FROM_XML', 'ROS_LOCALHOST_ONLY',
|
||||
'ROS_AUTOMATIC_DISCOVERY_RANGE', 'ROS_STATIC_PEERS', 'ROS_DISCOVERY_SERVER']
|
||||
|
||||
|
||||
def process_environment(root_pid):
|
||||
"""Only inspect this launch's descendants, and only middleware environment keys."""
|
||||
parents = {}
|
||||
for path in Path('/proc').glob('[0-9]*/status'):
|
||||
try:
|
||||
parent = next(line.split()[1] for line in path.read_text().splitlines()
|
||||
if line.startswith('PPid:'))
|
||||
parents[int(path.parent.name)] = int(parent)
|
||||
except (OSError, StopIteration, ValueError):
|
||||
continue
|
||||
owned = {root_pid}
|
||||
while True:
|
||||
expanded = owned | {pid for pid, parent in parents.items() if parent in owned}
|
||||
if expanded == owned:
|
||||
break
|
||||
owned = expanded
|
||||
result = []
|
||||
for pid in sorted(owned):
|
||||
try:
|
||||
base = Path('/proc')/str(pid)
|
||||
env = dict(item.split('=', 1) for item in
|
||||
(base/'environ').read_bytes().decode(errors='replace').split('\0') if '=' in item)
|
||||
command = (base/'cmdline').read_bytes().decode(errors='replace').split('\0')
|
||||
# Do not record full robot descriptions or unrelated environment variables.
|
||||
result.append({'pid': pid, 'executable': command[:2],
|
||||
'rmw_libraries': sorted({line.rsplit('/', 1)[-1] for line in
|
||||
(base/'maps').read_text().splitlines()
|
||||
if '/librmw_' in line and '.so' in line}),
|
||||
'environment': {key: env.get(key) for key in ENV_KEYS}})
|
||||
except OSError:
|
||||
continue
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--map', type=Path, required=True)
|
||||
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
|
||||
parser.add_argument('--timeout', type=float, default=420.0,
|
||||
help='whole-stack validation deadline, including up to three startup attempts')
|
||||
parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load')
|
||||
args = parser.parse_args()
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
workspace = project_env.WORKSPACE
|
||||
try:
|
||||
gz_exe = project_env.find_gz_bin()
|
||||
bin_dir = project_env.find_bin_dir(workspace)
|
||||
if args.goal is not None:
|
||||
nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client')
|
||||
except project_env.ProbeError as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir))
|
||||
os.environ.update(ROS_DOMAIN_ID=str(50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
ROS2CLI_DISABLE_DAEMON='1',
|
||||
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
|
||||
LIO_MAP=str(args.map.resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
log = None
|
||||
if args.launcher == 'shell':
|
||||
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
||||
else:
|
||||
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
|
||||
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
|
||||
log = open(args.output/'stack.log', 'w', encoding='utf8')
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
|
||||
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
rclpy.init()
|
||||
node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
publishers = set()
|
||||
counts = {'map_to_odom': 0, 'map_to_base_link': 0}
|
||||
|
||||
def on_tf(msg, info):
|
||||
for transform in msg.transforms:
|
||||
if transform.header.frame_id != 'map':
|
||||
continue
|
||||
if transform.child_frame_id == 'odom':
|
||||
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
|
||||
publishers.add(json.dumps(gid, sort_keys=True, default=str))
|
||||
counts['map_to_odom'] += 1
|
||||
if transform.child_frame_id == 'base_link':
|
||||
counts['map_to_base_link'] += 1
|
||||
|
||||
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
|
||||
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
|
||||
path_client = node.create_client(IsPathValid, '/is_path_valid')
|
||||
active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
|
||||
parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
|
||||
states = {}
|
||||
processes = []
|
||||
rviz = None
|
||||
result = {}
|
||||
try:
|
||||
if args.rviz:
|
||||
rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d',
|
||||
str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true'],
|
||||
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'},
|
||||
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
deadline = time.monotonic()+args.timeout
|
||||
last_check = 0.0
|
||||
stable_since = None
|
||||
manager_completed = False
|
||||
while time.monotonic() < deadline:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited')
|
||||
if time.monotonic()-last_check < 0.5:
|
||||
continue
|
||||
last_check = time.monotonic()
|
||||
if not processes and time.monotonic()-started > 8:
|
||||
processes = process_environment(process.pid)
|
||||
states = {}
|
||||
pending = {}
|
||||
for name, client in clients.items():
|
||||
if not client.service_is_ready():
|
||||
continue
|
||||
pending[name] = client.call_async(GetState.Request())
|
||||
poll_end = time.monotonic()+1
|
||||
while time.monotonic() < poll_end and any(not f.done() for f in pending.values()):
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
for name, future in pending.items():
|
||||
if future.done() and future.result():
|
||||
states[name] = future.result().current_state.id
|
||||
else:
|
||||
clients[name].remove_pending_request(future)
|
||||
log_path = args.output/'stack.log'
|
||||
text = log_path.read_text(errors='replace') if log_path.exists() else ''
|
||||
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
|
||||
for line in text.splitlines())
|
||||
if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed:
|
||||
if stable_since is None:
|
||||
stable_since = time.monotonic()
|
||||
if time.monotonic()-stable_since >= 2:
|
||||
break
|
||||
else:
|
||||
stable_since = None
|
||||
processes = process_environment(process.pid)
|
||||
names = sorted(set(node.get_node_names()))
|
||||
path_ready = path_client.wait_for_service(timeout_sec=2)
|
||||
path_response = None
|
||||
if path_ready:
|
||||
future = path_client.call_async(path_probe_request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=3)
|
||||
if future.done() and future.result() is not None:
|
||||
path_response = str(future.result())
|
||||
manager_active = False
|
||||
if active_client.wait_for_service(timeout_sec=1):
|
||||
future = active_client.call_async(Trigger.Request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
manager_active = bool(future.done() and future.result() and future.result().success)
|
||||
managed_nodes = []
|
||||
if parameter_client.wait_for_service(timeout_sec=1):
|
||||
future = parameter_client.call_async(GetParameters.Request(names=['node_names']))
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
if future.done() and future.result() and future.result().values:
|
||||
managed_nodes = list(future.result().values[0].string_array_value)
|
||||
result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started,
|
||||
'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()),
|
||||
'rmw': get_rmw_implementation_identifier(), 'processes': processes,
|
||||
'node_counts': dict(Counter(node.get_node_names())),
|
||||
'services': dict(node.get_service_names_and_types()),
|
||||
'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))),
|
||||
'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))},
|
||||
'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response,
|
||||
'manager_active': manager_active, 'managed_nodes': managed_nodes,
|
||||
'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
|
||||
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
|
||||
result['passed'] = (manager_completed and manager_active and path_response is not None
|
||||
and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes)
|
||||
and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
|
||||
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
|
||||
and counts['map_to_base_link'] == 0)
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
if args.goal and result['passed']:
|
||||
goal = subprocess.run([str(nav_client), *map(str, args.goal), '0'],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=200)
|
||||
(args.output/'goal.log').write_text(goal.stdout)
|
||||
result['goal_exit_code'] = goal.returncode
|
||||
result['goal_succeeded'] = '结果: ✅ SUCCEEDED' in goal.stdout
|
||||
result['passed'] = result['passed'] and goal.returncode == 0 and result['goal_succeeded']
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps({k: v for k, v in result.items() if k not in
|
||||
('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True)
|
||||
if not result['passed']:
|
||||
raise RuntimeError('stack integration validation failed')
|
||||
except Exception as error:
|
||||
result.update(passed=False, error=str(error))
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
raise
|
||||
finally:
|
||||
_ = subscription
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
try:
|
||||
process.wait(timeout=20)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
if rviz is not None:
|
||||
os.killpg(rviz.pid, signal.SIGINT)
|
||||
try:
|
||||
rviz.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(rviz.pid, signal.SIGKILL)
|
||||
rviz.wait()
|
||||
if log:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user