#!/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 time import uuid import rclpy from rclpy.node import Node from rclpy.parameter import Parameter from lifecycle_msgs.srv import GetState from tf2_msgs.msg import TFMessage NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server', 'bt_navigator', 'behavior_server', 'waypoint_follower', 'velocity_smoother', 'collision_monitor'] 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) args = parser.parse_args() if not args.map.is_file(): parser.error('map missing') args.output.mkdir(parents=True, exist_ok=True) session = uuid.uuid4().hex[:12] os.environ.update(ROS_DOMAIN_ID=str(50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}', FASTDDS_BUILTIN_TRANSPORTS='UDPv4', 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())) workspace = Path(__file__).resolve().parents[1] 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') 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} states = {} try: deadline = time.monotonic()+120 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() for name, client in clients.items(): if not client.service_is_ready(): continue future = client.call_async(GetState.Request()) rclpy.spin_until_future_complete(node, future, timeout_sec=1) if future.done() and future.result(): states[name] = future.result().current_state.id 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 names = sorted(set(node.get_node_names())) result = {'launcher': args.launcher, '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 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)) print(json.dumps(result, indent=2), flush=True) if not result['passed']: raise RuntimeError('stack integration validation failed') 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 log: log.close() node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()