对tools进行了整理,Xmake也改为相对路径,在线 LiDAR-IMU 定位器实现

This commit is contained in:
mzx committed 2026-11-23 14:32:42 +08:00
1 parent 0602144ac5
commit 4502296915
70 files changed
+2652 -1298

No files matched your search

+79 -14
View File
@@ -2,8 +2,8 @@
"""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.flmap
python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map generated/field.flmap
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
@@ -25,6 +25,8 @@ 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):
@@ -88,36 +90,75 @@ def main():
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, default=120)
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)
workspace = Path(__file__).resolve().parents[1]
binary = project_env.find_bin_dir(workspace)
session = uuid.uuid4().hex[:12]
os.environ.update(ROS_DOMAIN_ID=str(50 + int(session[:8], 16) % 50), GZ_PARTITION=f'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1',
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()))
(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, 'IMU_sensor_noise': 'zero', 'control_input': 'wheel odometry only'}, indent=2))
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)
recorder = subprocess.Popen([str(binary/'field_localization_record'), '--ros-args', '-p', 'use_sim_time:=true',
'-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}'],
recorder = subprocess.Popen([str(recorder_exe), '--ros-args', '-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)
@@ -133,8 +174,22 @@ def main():
now = driver.get_clock().now().nanoseconds*1e-9
if start is None:
start = now
driver.drive(now-start)
if now-start > last_print+10:
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())
@@ -142,6 +197,14 @@ def main():
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):
@@ -158,6 +221,8 @@ def main():
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: