#!/usr/bin/env python3 """Record an isolated Gazebo mapping/evaluation run; truth is recorder-only. Source ROS first. Example: python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field_mapping.flmap python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map src/sentry_sim/maps/field_full.flmap """ import argparse import math 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 rclpy.qos import qos_profile_sensor_data from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from std_srvs.srv import Trigger from tf2_msgs.msg import TFMessage import project_env from _internal.arena_grid import ArenaGrid from _internal import arena_survey def yaw(q): return math.atan2(2 * (q.w*q.z + q.x*q.y), 1 - 2 * (q.y*q.y + q.z*q.z)) class Driver(Node): def __init__(self, profile): super().__init__('field_lio_evaluation_driver', parameter_overrides=[Parameter('use_sim_time', value=True)]) self.publisher = self.create_publisher(Twist, os.environ.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel'), 10) self.origin = None self.pose = None self.index = 0 self.tf_publishers = set() self.map_odom_messages = 0 self.forbidden_tf = 0 self.tf_subscription = self.create_subscription(TFMessage, '/tf', self.on_tf, 500) # Verified against the existing occupancy map with room for the body footprint. self.route = ([(-4.4, 3.0), (-4.4, 0.7), (-5.15, 0.7), (-5.15, 3.0), (-5.0, 3.0)] if profile == 'mapping' else [(-4.6, 2.8), (-4.6, 1.0), (-5.1, 1.0), (-5.1, 2.8), (-5.0, 3.0)]) self.subscription = self.create_subscription(Odometry, '/odom', self.on_odom, qos_profile_sensor_data) def on_tf(self, msg, info): for transform in msg.transforms: if transform.header.frame_id == 'map' and transform.child_frame_id == 'odom': gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid self.tf_publishers.add(json.dumps(gid, sort_keys=True, default=str) if isinstance(gid, dict) else str(gid)) self.map_odom_messages += 1 if transform.header.frame_id == 'map' and transform.child_frame_id == 'base_link': self.forbidden_tf += 1 def on_odom(self, msg): p = msg.pose.pose if self.origin is None: self.origin = (p.position.x, p.position.y, yaw(p.orientation)) x, y, angle = self.origin dx, dy = p.position.x-x, p.position.y-y self.pose = (-5 + math.cos(angle)*dx + math.sin(angle)*dy, 3 - math.sin(angle)*dx + math.cos(angle)*dy, yaw(p.orientation)-angle) def drive(self, elapsed): command = Twist() if elapsed >= 5 and self.pose and elapsed % 30 > 2: x, y, angle = self.pose tx, ty = self.route[self.index] distance = math.hypot(tx-x, ty-y) if distance < 0.08: self.index = (self.index+1) % len(self.route) else: error = math.atan2(math.sin(math.atan2(ty-y, tx-x)-angle), math.cos(math.atan2(ty-y, tx-x)-angle)) command.angular.z = max(-0.4, min(0.4, 1.5*error)) if abs(error) < 0.3: command.linear.x = min(0.20, 0.8*distance) self.publisher.publish(command) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--profile', choices=['mapping', 'evaluation'], required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--map', type=Path, required=True) parser.add_argument('--duration', type=float) parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC'), help='override the recorded LiDAR topic') parser.add_argument('--full-field', action='store_true', help='capture stationary scans at overlapping Gazebo survey stations (mapping only)') parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]') args = parser.parse_args() if args.full_field and args.profile != 'mapping': parser.error('--full-field requires --profile mapping') if args.duration is not None and (not math.isfinite(args.duration) or args.duration <= 0): parser.error('--duration must be positive and finite') if args.full_field and args.map.exists(): parser.error('full-field mapping requires a new output map path') if args.output.exists(): parser.error('output directory must not already exist') if args.profile == 'evaluation' and not args.map.is_file(): parser.error('evaluation requires an existing map') 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') survey = None default_duration = 120.0 if args.full_field: survey = arena_survey.stations(ArenaGrid(project_env.find_map_yaml())) default_duration = float(math.ceil(3 + len(survey) * (arena_survey.STATION_SECONDS + 0.7))) if args.duration is not None and args.duration < default_duration: parser.error(f'--duration must be at least {default_duration:.1f} simulated seconds for the survey') print(f'mapping survey: {len(survey)} stationary LiDAR stations', flush=True) if args.duration is None: args.duration = default_duration except (project_env.ProbeError, ValueError, OSError) as error: parser.exit(1, f'{parser.prog}: {error}\n') cloud_topic = args.lio_cloud_topic or '/scan/points_lio' args.output.mkdir(parents=True) args.map.parent.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), LIO_POINT_CLOUD_TOPIC=cloud_topic) 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'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1', FASTDDS_BUILTIN_TRANSPORTS='UDPv4', HEADLESS='1', NAV2='0', RVIZ='0', LOCALIZATION='lio', LIO_MODE='mapping' if args.profile == 'mapping' else 'localization', LIO_MAP=str(args.map.resolve()), LIO_EXPORT_MAP=str(args.map.resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve())) if survey is not None: # NAV2=0 and this branch starts neither AMCL nor LIO. The survey is offline. os.environ['LOCALIZATION'] = 'amcl' os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve())) os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve())) (args.output/'runtime.json').write_text(json.dumps({ 'ROS_DOMAIN_ID': os.environ['ROS_DOMAIN_ID'], 'GZ_PARTITION': os.environ['GZ_PARTITION'], 'duration_sec': args.duration, 'profile': args.profile, 'survey': survey, 'IMU_sensor_noise': 'zero', 'control_input': 'known stationary survey coordinates' if survey else 'wheel odometry', }, indent=2)) processes = [] log_handles = [] rclpy.init() driver = Driver(args.profile) surveyed = [] try: processes.append(subprocess.Popen(['bash', str(workspace/'scripts/sentry_up.sh')], start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace)) log = open(args.output/'record.log', 'w', encoding='utf8') log_handles.append(log) sim_share = Path(os.environ.get('SENTRY_SIM_SHARE') or workspace/'src/sentry_sim') recorder = subprocess.Popen([str(recorder_exe), '--ros-args', '--params-file', str(sim_share/'config/field_cloud.yaml'), '-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}', '-p', f'point_cloud_topic:={cloud_topic}'], stdout=log, stderr=subprocess.STDOUT, start_new_session=True) processes.append(recorder) deadline = time.monotonic() + max(600, args.duration*10) start = None last_print = 0 while time.monotonic() < deadline and recorder.poll() is None: if (args.output/'STOP').exists(): raise RuntimeError('capture stopped through STOP file') rclpy.spin_once(driver, timeout_sec=0.02) if processes[0].poll() is not None: raise RuntimeError('simulation stack exited; inspect stack.log') if (args.output/'config.txt').exists(): now = driver.get_clock().now().nanoseconds*1e-9 if start is None: start = now if survey is None: driver.drive(now-start) elif len(surveyed) < len(survey) and (not surveyed or now >= surveyed[-1]['command_time'] + arena_survey.STATION_SECONDS + 0.1): if not surveyed and (args.output/'scans.csv').stat().st_size == 0: if now-start > 5: raise RuntimeError(f'no LiDAR scans received on {cloud_topic}') continue point = survey[len(surveyed)] arena_survey.set_station(gz_exe, point, os.environ['GZ_PARTITION']) # Sample the newest received /clock after the synchronous service. for _ in range(10): rclpy.spin_once(driver, timeout_sec=0) surveyed.append({'goal': point, 'command_time': driver.get_clock().now().nanoseconds*1e-9}) print(f'survey station {len(surveyed)}/{len(survey)} {point}', flush=True) if survey is None and now-start > last_print+10: last_print = now-start print(f'{args.profile}: {last_print:.1f}/{args.duration:.1f} simulated seconds; odom pose={driver.pose}', flush=True) driver.publisher.publish(Twist()) if recorder.poll() is None: raise RuntimeError('capture deadline exceeded') if recorder.returncode or not (args.output/'complete.txt').exists(): raise RuntimeError('recorder failed; inspect record.log') if survey is not None: if len(surveyed) != len(survey): raise RuntimeError(f'survey reached only {len(surveyed)}/{len(survey)} stations') selection = list(arena_survey.selected_clouds(args.output, surveyed)) arena_survey.evaluate_stations(args.output, selection) point_count = arena_survey.build_map(args.output, selection, args.map) print(f'survey complete: {len(selection)} stations, {point_count} voxels; {args.map}', flush=True) return if args.profile == 'mapping': client = driver.create_client(Trigger, '/field_localization/save_map') if not client.wait_for_service(timeout_sec=5): raise RuntimeError('LIO save_map service unavailable') future = client.call_async(Trigger.Request()) rclpy.spin_until_future_complete(driver, future, timeout_sec=10) if not future.done() or not future.result().success: raise RuntimeError('LIO map export failed') tf_summary = {'map_to_odom_publishers': len(driver.tf_publishers), 'map_to_odom_messages': driver.map_odom_messages, 'map_to_base_link_messages': driver.forbidden_tf} (args.output/'tf_validation.json').write_text(json.dumps(tf_summary, indent=2)) if len(driver.tf_publishers) != 1 or driver.map_odom_messages == 0 or driver.forbidden_tf: raise RuntimeError(f'TF validation failed: {tf_summary}') print(f'capture complete: {args.output}; TF validation={tf_summary}', flush=True) finally: if survey is not None: (args.output/'survey_progress.json').write_text(json.dumps(surveyed, indent=2)) driver.publisher.publish(Twist()) for process in reversed(processes): if process.poll() is None: os.killpg(process.pid, signal.SIGINT) for process in reversed(processes): try: process.wait(timeout=15) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() for handle in log_handles: handle.close() driver.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()