#!/usr/bin/env python3 """Shared environment discovery for the simulation launchers and tools.""" import argparse import math import os from pathlib import Path import re import shutil import signal import subprocess import sys import tempfile import time WORKSPACE = Path(__file__).resolve().parents[1] _KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'cmd_vel_relay', 'field_localization_node', 'field_localization_record', 'field_localization_replay') _GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz') _GZ_VERSION_TIMEOUT = 5 _FIELD_PACKAGE = Path('src/guodong_sentry_sim') class ProbeError(RuntimeError): """A required setting is missing or points to an unusable path.""" def require_file(path, name): path = Path(path).absolute() if not path.is_file(): raise ProbeError(f'{name} 必须指向普通文件: {path}') return path def require_directory(path, name): path = Path(path).absolute() if not path.is_dir(): raise ProbeError(f'{name} 必须指向目录: {path}') return path def is_executable(path): return Path(path).is_file() and os.access(path, os.X_OK) def require_executable(path, name): path = Path(path).absolute() if not is_executable(path): raise ProbeError(f'{name} 必须指向可执行的普通文件: {path}') return path def find_ros_setup(): """Return the ROS setup path, or None when ROS is already sourced.""" explicit = os.environ.get('ROS_SETUP') setup = require_file(explicit, 'ROS_SETUP') if explicit else None if os.environ.get('AMENT_PREFIX_PATH') and shutil.which('ros2'): return None if setup is not None: return setup root = os.environ.get('ROS_INSTALL_ROOT') if root: setup = Path(root) / 'setup.bash' if setup.is_file(): return setup.absolute() distro = os.environ.get('ROS_DISTRO') if distro: setup = Path('/opt/ros') / distro / 'setup.bash' if setup.is_file(): return setup candidates = sorted( (p for p in Path('/opt/ros').glob('*/setup.bash') if p.is_file()), key=lambda p: ([int(part) if i % 2 else part for i, part in enumerate(re.split(r'([0-9]+)', p.parent.name))], p.parent.name), ) if not candidates: raise ProbeError('找不到 ROS 2 setup.bash。请加载 ROS 环境或设置 ROS_SETUP。') if len(candidates) > 1: print(f'[env] 警告: 发现多个 ROS 安装,按目录名排序选择 {candidates[-1]}', file=sys.stderr) return candidates[-1] def find_bin_dir(ws=WORKSPACE): """Choose a single build directory without mixing targets from different builds.""" for name in ('SENTRY_BIN_DIR', 'NAV_BIN_DIR'): if override := os.environ.get(name): return require_directory(override, name) build = Path(ws).absolute() / 'build' unified = build / 'bin' if any(is_executable(unified / name) for name in _KNOWN_BINARIES): return unified for mode in ('release', 'debug'): for candidate in sorted(build.glob(f'*/*/{mode}')): if any(is_executable(candidate / name) for name in _KNOWN_BINARIES): return candidate return unified def find_gz_bin(): """Prefer system Gazebo, validating an explicit override before any fallback.""" if override := os.environ.get('GZ_BIN'): return require_executable(override, 'GZ_BIN') for path in _GZ_CANDIDATES: if is_executable(path): return Path(path) if path := shutil.which('gz'): return require_executable(path, 'gz') raise ProbeError('找不到 Gazebo 的 gz 可执行文件。请设置 GZ_BIN。') def run_gz(gz, *args, timeout, partition=None): """Run a Gazebo query in its own process group with a wall-clock deadline.""" env = os.environ.copy() env.pop('LD_LIBRARY_PATH', None) if partition is not None: env['GZ_PARTITION'] = partition command = [str(gz), *args] # Files let us read results after a timeout even if a descendant still holds # an output descriptor. Only the process group started here is signalled. with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr: process = subprocess.Popen(command, env=env, start_new_session=True, stdout=stdout, stderr=stderr) try: process.wait(timeout=timeout) except BaseException: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass process.wait() raise stdout.seek(0) stderr.seek(0) return subprocess.CompletedProcess(command, process.returncode, stdout.read().decode(errors='replace'), stderr.read().decode(errors='replace')) def gz_version_args(gz=None): """Return force-version arguments, or warn and let Gazebo choose its default.""" if gz is None: gz = find_gz_bin() if forced := os.environ.get('GZ_FORCE_VERSION'): return ['--force-version', forced] try: result = run_gz(gz, 'sim', '--version', timeout=_GZ_VERSION_TIMEOUT) if result.returncode: reason = f'退出码 {result.returncode}' else: version = re.match(r'^\s*([0-9]+)(?=\.|\s|$)', result.stdout.strip() or result.stderr.strip()) if version: return ['--force-version', version[1]] reason = '无法解析版本' except subprocess.TimeoutExpired: reason = f'超时({_GZ_VERSION_TIMEOUT:g} 秒)' except OSError as error: reason = str(error) print(f'[env] 警告: {gz} sim --version {reason},使用 Gazebo 默认版本。' '可通过 GZ_FORCE_VERSION 指定主版本。', file=sys.stderr) return [] def wait_gz_clock(gz, gazebo_pid=None): """Wait for the selected Gazebo transport to advertise /clock.""" raw_timeout = os.environ.get('BRIDGE_WAIT_TIMEOUT') or '120' try: timeout = float(raw_timeout) except ValueError: timeout = 0 if not math.isfinite(timeout) or timeout <= 0: raise ProbeError(f'BRIDGE_WAIT_TIMEOUT 必须为正数: {raw_timeout}') deadline = time.monotonic() + timeout while (remaining := deadline - time.monotonic()) > 0: if gazebo_pid is not None: try: os.kill(gazebo_pid, 0) except ProcessLookupError as error: raise ProbeError('Gazebo 启动失败,进程已退出') from error try: # Listing topics waits for a full discovery cycle (over two seconds on this host). result = run_gz(gz, 'topic', '-e', '-t', '/clock', '-n', '1', timeout=min(2, remaining)) if result.returncode == 0 and result.stdout.strip(): return except subprocess.TimeoutExpired: pass time.sleep(max(0, min(1, deadline - time.monotonic()))) raise ProbeError( f'等待 Gazebo /clock 超时({timeout:g} 秒),请检查 GZ_PARTITION=' f'{os.environ.get("GZ_PARTITION") or "sentry"}') def find_field_root(ws=WORKSPACE, *, explicit=None): if explicit: return require_directory(explicit, 'field_root') if override := os.environ.get('SENTRY_FIELD_ROOT'): return require_directory(override, 'SENTRY_FIELD_ROOT') for parent, pattern in ((Path(ws).absolute() / 'field', '*'), (Path.home() / 'Gazebo_projects', '*map_transfer*')): for candidate in sorted(parent.glob(pattern)): if (candidate / _FIELD_PACKAGE).is_dir(): return candidate raise ProbeError('找不到场地迁移包。请设置 SENTRY_FIELD_ROOT。') def find_map_yaml(field_root=None, *, explicit=None, ws=WORKSPACE): if explicit: return require_file(explicit, 'map') if override := os.environ.get('SENTRY_MAP_YAML'): return require_file(override, 'SENTRY_MAP_YAML') if field_root is None: field_root = find_field_root(ws) maps = Path(field_root) / _FIELD_PACKAGE / 'maps' preferred = maps / 'rmul_2027' / 'rmul_2027.yaml' if preferred.is_file(): return preferred candidates = sorted(p for p in maps.glob('*/*.yaml') if p.is_file()) for candidate in candidates: if candidate.name == 'rmul_2027.yaml': return candidate if candidates: return candidates[0] raise ProbeError(f'{maps} 下找不到栅格图 YAML。请设置 SENTRY_MAP_YAML。') def report(ws): setup = find_ros_setup() bin_dir = find_bin_dir(ws) field_root = find_field_root(ws) map_yaml = find_map_yaml(field_root) gz = find_gz_bin() versions = ' '.join(gz_version_args(gz)) print(f'仓库根: {ws}') print(f' ROS setup : {setup or "<已 source>"}') print(f' BIN_DIR : {bin_dir}') print(f' GZ_BIN : {gz}') print(f' gz 版本参数 : {versions or "<无>"}') print(f' FIELD_ROOT : {field_root}') print(f' MAP_YAML : {map_yaml}') def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('workspace', type=Path, nargs='?', default=WORKSPACE) queries = parser.add_mutually_exclusive_group() for query in ('bin-dir', 'field', 'map', 'gz', 'gz-version-args', 'ros-setup'): queries.add_argument(f'--{query}', dest='query', action='store_const', const=query) for query in ('gz-version-args-lines', 'wait-gz-clock'): queries.add_argument(f'--{query}', dest='query', action='store_const', const=query, help=argparse.SUPPRESS) parser.add_argument('--field-root', type=Path, help=argparse.SUPPRESS) parser.add_argument('--gazebo-pid', type=int, help=argparse.SUPPRESS) args = parser.parse_args(argv) if args.field_root is not None and args.query != 'map': parser.error('--field-root requires --map') if args.gazebo_pid is not None and (args.query != 'wait-gz-clock' or args.gazebo_pid <= 0): parser.error('--gazebo-pid requires --wait-gz-clock and a positive PID') try: ws = require_directory(args.workspace, 'workspace') match args.query: case 'bin-dir': print(find_bin_dir(ws)) case 'field': print(find_field_root(ws)) case 'map': print(find_map_yaml(args.field_root, ws=ws)) case 'gz': print(find_gz_bin()) case 'gz-version-args' | 'gz-version-args-lines': separator = '\n' if args.query == 'gz-version-args-lines' else ' ' versions = gz_version_args() if versions: print(separator.join(versions)) elif args.query == 'gz-version-args': print() case 'ros-setup': print(find_ros_setup() or '') case 'wait-gz-clock': wait_gz_clock(find_gz_bin(), args.gazebo_pid) case None: report(ws) except (ProbeError, OSError) as error: print(f'[env] {error}', file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())