#!/usr/bin/env python3 """Bounded driver-only raw recording for stationary installation diagnostics.""" import argparse import hashlib import json import os from pathlib import Path import re import shutil import signal import subprocess import time import rclpy from rclpy.node import Node from rclpy.qos import qos_profile_sensor_data import rosbag2_py import yaml from livox_ros_driver2.msg import CustomMsg from sensor_msgs.msg import Imu from br_vehicle_mission.deployment import load_driver from br_vehicle_mission.livox_scan import read_scan def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--site', required=True) parser.add_argument('--out', required=True) parser.add_argument('--duration', type=float, default=20.) parser.add_argument('--discovery-interface', default='') parser.add_argument('--discovery-host', default='') args = parser.parse_args() if not 2 <= args.duration <= 120: parser.error('duration must be 2..120 seconds') if bool(args.discovery_interface) != bool(args.discovery_host): parser.error('discovery interface and host must be supplied together') site_path = Path(args.site).resolve() site = yaml.safe_load(site_path.read_text()) driver_path = Path(site['driver_params_file']) driver = load_driver(driver_path) root = Path(args.out).resolve() root.mkdir(parents=True, exist_ok=False) for name, path in [('site.yaml', site_path), ('driver.yaml', driver_path), ('dual_mid360.json', Path(driver['user_config_path']))]: shutil.copyfile(path, root / name) sensors = site['sensors'] topics = {'upper': (sensors['upper_lidar_topic'], CustomMsg, 'livox_ros_driver2/msg/CustomMsg'), 'lower': (sensors['lower_lidar_topic'], CustomMsg, 'livox_ros_driver2/msg/CustomMsg'), 'upper_imu': (sensors['upper_imu_topic'], Imu, 'sensor_msgs/msg/Imu'), 'lower_imu': (sensors['lower_lidar_topic'].replace('/lidar_', '/imu_'), Imu, 'sensor_msgs/msg/Imu')} command = ['ros2', 'launch', 'br_vehicle_mission', 'dual_mid360_driver.launch.py', 'driver_params_file:=' + str(driver_path)] if args.discovery_interface: command += ['driver_discovery_interface:=' + args.discovery_interface, 'driver_discovery_host_ip:=' + args.discovery_host] report = {'scope': 'Raw stationary geometry recording; driver only; no LIO, TF, planner or chassis', 'command': command, 'start_ns': time.time_ns(), 'ros_domain_id': os.environ.get('ROS_DOMAIN_ID'), 'script_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'samples': {key: [] for key in topics}, 'errors': []} process = None writer = None rclpy.init() node = Node('dual_geometry_recorder') def receive(key, raw): receive_ns = node.get_clock().now().nanoseconds topic, _, _ = topics[key] writer.write(topic, raw, receive_ns) row = {'receive_ns': receive_ns} if key in ('upper', 'lower'): scan = read_scan(raw) offsets = scan.offsets if not len(offsets) or scan.timebase != scan.stamp_ns: raise ValueError('empty scan or inconsistent timebase') if (offsets[1:] < offsets[:-1]).any() or int(offsets.max()) >= 100000000: raise ValueError('invalid point offsets') row.update(stamp_ns=scan.stamp_ns, points=scan.point_num, frame=scan.frame, lidar_id=scan.lidar_id, end_ns=scan.timebase + int(offsets.max())) report['samples'][key].append(row) try: with (root / 'driver.log').open('w') as log: process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) try: end = time.monotonic() + 6 while time.monotonic() < end: if process.poll() is not None: raise RuntimeError('driver exited during warmup') rclpy.spin_once(node, timeout_sec=.05) writer = rosbag2_py.SequentialWriter() writer.open(rosbag2_py.StorageOptions(uri=str(root / 'raw_bag'), storage_id='sqlite3'), rosbag2_py.ConverterOptions('', '')) for key, (topic, cls, type_name) in topics.items(): writer.create_topic(rosbag2_py.TopicMetadata(name=topic, type=type_name, serialization_format='cdr')) node.create_subscription(cls, topic, lambda raw, k=key: receive(k, raw), qos_profile_sensor_data, raw=True) report['sample_start_ns'] = time.time_ns() end = time.monotonic() + args.duration while time.monotonic() < end: if process.poll() is not None: raise RuntimeError('driver exited during recording') rclpy.spin_once(node, timeout_sec=.05) report['sample_end_ns'] = time.time_ns() finally: if process.poll() is None: process.send_signal(signal.SIGINT) try: process.wait(timeout=10) except subprocess.TimeoutExpired: report['forced_sigterm'] = True os.killpg(process.pid, signal.SIGTERM) process.wait(timeout=5) report['driver_launcher_exit'] = process.returncode except Exception as exc: report['errors'].append(repr(exc)) finally: node.destroy_node() rclpy.shutdown() writer = None report['end_ns'] = time.time_ns() report['counts'] = {key: len(rows) for key, rows in report['samples'].items()} log_path = root / 'driver.log' report['container_clean_shutdown'] = bool(log_path.exists() and re.search( r'\[component_container_mt-\d+\]: process has finished cleanly', log_path.read_text())) report['status'] = 'PASS' if (not report['errors'] and not report.get('forced_sigterm') and report.get('driver_launcher_exit') == 0 and report['container_clean_shutdown'] and min(report['counts'].values()) >= 20) else 'FAIL' (root / 'capture.json').write_text(json.dumps(report, indent=2) + '\n') print(json.dumps({key: value for key, value in report.items() if key != 'samples'}, indent=2)) return 0 if report['status'] == 'PASS' else 1 if __name__ == '__main__': raise SystemExit(main())