对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

+151
View File
@@ -0,0 +1,151 @@
"""Static arena clearance and deterministic routes for isolated simulation tests."""
from collections import deque
from functools import cache
import heapq
import math
from pathlib import Path
import numpy as np
import yaml
START = (-5.0, 3.0)
SURVEY_GOALS = ((-5., 0.), (-5., -3.), (0., -3.), (5., -3.), (5., 0.), (5., 3.),
(0., 3.), (0., 0.), (0., -3.), (-5., -3.), START)
# Revisit the reported east route in both directions before covering the perimeter.
ARENA_GOALS = ((0., 0.), (5., -3.), (0., 0.), (5., -3.), (5., 0.), (5., 3.),
(0., 3.), START, (-5., 0.), (-5., -3.), (0., -3.), (0., 0.), START)
class ArenaGrid:
def __init__(self, map_yaml):
path = Path(map_yaml)
config = yaml.safe_load(path.read_text())
self.resolution = float(config['resolution'])
self.origin = tuple(config['origin'][:2])
if config.get('mode', 'trinary') != 'trinary' or config['origin'][2] != 0:
raise ValueError('arena coverage expects an unrotated trinary occupancy map')
with (path.parent / config['image']).open('rb') as image:
def header():
line = image.readline().split(b'#', 1)[0].strip()
while not line:
raw = image.readline()
if not raw:
raise ValueError('truncated PGM header')
line = raw.split(b'#', 1)[0].strip()
return line
if header() != b'P5':
raise ValueError('expected binary PGM occupancy map')
width, height = map(int, header().split())
if header() != b'255':
raise ValueError('expected 8-bit PGM occupancy map')
pixels = np.frombuffer(image.read(), dtype=np.uint8).reshape(height, width)
self.size = (height, width)
probability = pixels / 255 if config.get('negate', 0) else 1 - pixels / 255
self.free = (probability < config['free_thresh'])[::-1]
def cell(self, point):
x, y = point
return (math.floor((y-self.origin[1])/self.resolution),
math.floor((x-self.origin[0])/self.resolution))
def point(self, cell):
y, x = cell
return (self.origin[0]+(x+0.5)*self.resolution,
self.origin[1]+(y+0.5)*self.resolution)
def neighbors(self, cell):
y, x = cell
h, w = self.size
for i, j in ((y-1,x),(y+1,x),(y,x-1),(y,x+1)):
if 0 <= i < h and 0 <= j < w:
yield i, j
@cache
def clear(self, clearance):
radius = math.ceil(clearance/self.resolution)
padded = np.pad(self.free, radius)
h, w = self.size
mask = self.free.copy()
for y in range(-radius, radius+1):
for x in range(-radius, radius+1):
if math.hypot(x, y)*self.resolution <= clearance + 1e-10:
mask &= padded[radius+y:radius+y+h, radius+x:radius+x+w]
return mask
def coverage(self):
# Largest radius of the existing 0.65 x 0.54 m rectangular footprint.
travel = self.clear(math.hypot(0.325, 0.270))
start = self.cell(START)
if not travel[start]:
raise ValueError('spawn pose fails the footprint clearance check')
connected = np.zeros(self.size, dtype=bool)
connected[start] = True
queue = deque([start])
while queue:
for cell in self.neighbors(queue.popleft()):
if travel[cell] and not connected[cell]:
connected[cell] = True
queue.append(cell)
targets = connected & self.clear(0.50)
wide = self.clear(0.65)
tiles = {}
for cell in zip(*np.nonzero(targets)):
point = self.point(cell)
grid = tuple(map(math.floor, point))
score = (not wide[cell], math.dist(point, (grid[0]+0.5, grid[1]+0.5)), point)
if grid not in tiles or score < tiles[grid]:
tiles[grid] = score
ys, xs = np.nonzero(connected)
return {'reachable_cells': int(connected.sum()), 'eligible_goal_cells': int(targets.sum()),
'reachable_area_m2': float(connected.sum() * self.resolution**2),
'center_coordinate_bounds_m': [self.point((min(ys), min(xs))),
self.point((max(ys), max(xs)))],
'disconnected_goal_cells': int((self.clear(0.50)&~connected).sum()),
'resolution_m': self.resolution,
'samples': [tiles[tile][2] for tile in sorted(tiles)]}
def route(self, anchors, clearance=0.55):
safe = self.clear(clearance)
points = [START]
for target in anchors:
start, end = self.cell(points[-1]), self.cell(target)
if not safe[start] or not safe[end]:
raise ValueError(f'unsafe survey anchor {points[-1]} -> {target}')
frontier = [(0, 0, start)]
distance = {start: 0}
previous = {}
while frontier:
_, cost, node = heapq.heappop(frontier)
if node == end:
break
if cost != distance[node]:
continue
for cell in self.neighbors(node):
if safe[cell] and cost+1 < distance.get(cell, math.inf):
distance[cell] = cost+1
previous[cell] = node
estimate = abs(cell[0]-end[0])+abs(cell[1]-end[1])
heapq.heappush(frontier, (cost+1+estimate, cost+1, cell))
else:
raise ValueError(f'no survey route from {points[-1]} to {target}')
cells = [end]
while cells[-1] != start:
cells.append(previous[cells[-1]])
candidates = [self.point(c) for c in reversed(cells[1:-1])] + [target]
index = 0
while index < len(candidates):
a = points[-1]
# Advance to the furthest visible waypoint along the grid path.
for last in range(len(candidates)-1, index-1, -1):
b = candidates[last]
count = max(1, math.ceil(2*math.dist(a,b)/self.resolution))
if all(safe[self.cell(tuple(x+(y-x)*i/count for x,y in zip(a,b)))]
for i in range(count+1)):
break
else:
raise ValueError(f'unable to simplify survey route near {a}')
points.append(b)
index = last+1
return points[1:]
+108
View File
@@ -0,0 +1,108 @@
"""Make a Gazebo-only map from stationary LiDAR scans at commanded survey stations."""
import csv
import json
import math
import os
import re
import struct
import tempfile
import numpy as np
import project_env
from _internal.arena_grid import START, SURVEY_GOALS
SETTLE_SECONDS = 0.8
STATION_SECONDS = 1.5
MAP_RESOLUTION = 0.10
def stations(grid):
result = [START]
route = grid.route(SURVEY_GOALS)
for a, b in zip([START] + route, route):
steps = max(1, math.ceil(math.dist(a, b) / 1.5))
for i in range(1, steps + 1):
point = tuple(round(x + (y - x) * i / steps, 4) for x, y in zip(a, b))
if point not in result:
result.append(point)
return result
def set_station(gz, point, partition):
x, y = point
request = f'name: "sentry" position: {{ x: {x} y: {y} z: 0 }} orientation: {{ w: 1 }}'
response = project_env.run_gz(
gz, 'service', '-s', '/world/rmul_arena/set_pose', '--reqtype', 'gz.msgs.Pose',
'--reptype', 'gz.msgs.Boolean', '--timeout', '2000', '--req', request,
timeout=3, partition=partition,
)
if response.returncode or not re.search(r'^data:\s*true\s*$', response.stdout, re.M):
raise RuntimeError(f'Gazebo did not acknowledge station {point}: {response.stdout} {response.stderr}')
def transform(points, pose):
translation, xyz, w = pose[:3], pose[3:6], pose[6]
twice = 2 * np.cross(xyz, points)
return points + w * twice + np.cross(xyz, twice) + translation
def selected_clouds(directory, survey):
with (directory / 'scans.csv').open() as stream:
scans = [(float(row['timestamp']), row['file']) for row in csv.DictReader(stream)]
for station in survey:
stamp = station['command_time']
candidates = [scan for scan in scans if stamp + SETTLE_SECONDS <= scan[0] < stamp + STATION_SECONDS]
if len(candidates) < 3:
raise RuntimeError(f'insufficient settled scans at {station["goal"]}')
yield station['goal'], candidates[len(candidates) // 2]
def build_map(directory, selected, output):
config = (directory / 'config.txt').read_text().splitlines()
extrinsics = [np.array(list(map(float, row.split()[1:]))) for row in config[2:4]]
if [line.split()[0] for line in config[2:4]] != ['base_from_imu', 'imu_from_lidar']:
raise ValueError('survey recorder configuration is missing LiDAR extrinsics')
clouds = []
for (x, y), (stamp, filename) in selected:
raw = (directory / filename).read_bytes()
magic, version, time, count = struct.unpack_from('<8sIdI', raw)
if magic != b'FLPC0001' or version != 1 or time != stamp or len(raw) != 24 + count * 24:
raise ValueError(f'invalid recorded scan {filename}')
rows = np.frombuffer(raw, dtype=[('time', '<f8'), ('point', '<f4', (4,))], offset=24)
points = rows['point'][:, :3].astype(np.float64)
points = points[np.isfinite(points).all(axis=1)]
if not len(points):
raise RuntimeError(f'no finite returns at station {(x, y)}')
base_from_imu, imu_from_lidar = extrinsics
clouds.append(transform(transform(points, imu_from_lidar), base_from_imu) + [x, y, 0])
points = np.concatenate(clouds)
# Average measured returns that occupy the same voxel across overlapping views.
grid = np.floor(points / MAP_RESOLUTION).astype(np.int64)
_, bins, counts = np.unique(grid, axis=0, return_inverse=True, return_counts=True)
centers = np.column_stack([np.bincount(bins, weights=axis) / counts for axis in points.T])
with tempfile.NamedTemporaryFile(dir=output.parent) as stream:
stream.write(struct.pack('<8sIdQ', b'FLMAP001', 1, MAP_RESOLUTION, len(centers)))
stream.write(centers.astype('<f8').tobytes())
stream.flush()
os.link(stream.name, output)
return len(centers)
def evaluate_stations(directory, selected):
# Independent truth is read only after all scan selections have been made.
truth = np.loadtxt(directory / 'truth.tum', ndmin=2)
report = []
for (x, y), (stamp, filename) in selected:
index = int(np.argmin(np.abs(truth[:, 0] - stamp)))
time, *pose = truth[index]
if abs(time - stamp) > 0.025:
raise RuntimeError(f'no independent truth for {filename} at {stamp:.3f}s')
error = math.dist(pose[:3], (x, y, 0))
rotation = math.degrees(2 * math.acos(min(1.0, abs(pose[6]))))
report.append({'station': [x, y], 'timestamp': stamp, 'scan': filename,
'position_error_m': error, 'rotation_error_deg': rotation})
(directory / 'survey_truth.json').write_text(json.dumps(report, indent=2))
if any(row['position_error_m'] > 0.02 or row['rotation_error_deg'] > 1 for row in report):
raise RuntimeError('commanded poses failed independent survey verification; see survey_truth.json')
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Shared DDS defaults for both launchers; explicit nonempty settings take precedence."""
import argparse
import json
import os
import shlex
KEYS = ('RMW_IMPLEMENTATION', 'ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS',
'FASTDDS_DEFAULT_PROFILES_FILE', 'FASTRTPS_DEFAULT_PROFILES_FILE',
'RMW_FASTRTPS_USE_QOS_FROM_XML', 'RMW_FASTRTPS_PUBLICATION_MODE',
'ROS_AUTOMATIC_DISCOVERY_RANGE', 'ROS_STATIC_PEERS', 'ROS_DISCOVERY_SERVER',
'ROS_LOCALHOST_ONLY')
def defaults(environment):
result = dict(environment)
for key, value in (('ROS_DOMAIN_ID', '0'), ('FASTDDS_BUILTIN_TRANSPORTS', 'UDPv4')):
if not result.get(key):
result[key] = value
return result
def describe(environment):
return json.dumps({key: environment.get(key, '<ROS default>') for key in KEYS},
ensure_ascii=False, sort_keys=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--shell', action='store_true')
args = parser.parse_args()
env = defaults(os.environ)
if args.shell:
for name in ('ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS'):
print(f'export {name}={shlex.quote(env[name])}')
else:
print('[DDS] '+describe(env), flush=True)
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
"""Nav2 domain preflight, discovery-gated startup and bounded readiness check."""
import argparse
import json
import os
import re
import time
from pathlib import Path
import rclpy
from geometry_msgs.msg import PoseStamped
from lifecycle_msgs.srv import GetState
from nav2_msgs.srv import IsPathValid, ManageLifecycleNodes
from rcl_interfaces.msg import Log
from rcl_interfaces.srv import GetParameters
from rclpy.utilities import get_rmw_implementation_identifier
from std_srvs.srv import Trigger
from dds_environment import defaults, describe
CONFLICT_SERVICES = {
'lifecycle_manager_nav2': '/lifecycle_manager_nav2/manage_nodes',
'planner_server': '/planner_server/get_state', 'bt_navigator': '/bt_navigator/get_state',
'controller_server': '/controller_server/get_state', 'map_server': '/map_server/get_state',
'amcl': '/amcl/get_state', 'field_localization': '/field_localization/save_map',
}
def path_probe_request():
# Read-only collision query at the map origin; is_valid need not be true.
request = IsPathValid.Request()
request.path.header.frame_id = 'map'
pose = PoseStamped()
pose.header.frame_id = 'map'
pose.pose.orientation.w = 1.0
request.path.poses = [pose]
return request
def ready(managed, states, manager_active, path_responded):
return (bool(managed) and all(states.get(name) == 3 for name in managed)
and manager_active and path_responded)
def failure_details(managed, states, path_discovered, path_responded, errors):
missing = sorted({match for error in errors for match in
re.findall(r'"([^"]+)" (?:action|service) server not available', error)})
return {'managed_node_list_received': bool(managed),
'missing_dependencies': missing,
'not_active': {name: states.get(name, 'response timeout / unavailable')
for name in managed if states.get(name) != 3},
'is_path_valid_discovered': path_discovered,
'is_path_valid_responded': path_responded, 'errors': errors[-8:]}
def preflight(node, duration):
deadline = time.monotonic()+duration
while rclpy.ok() and time.monotonic() < deadline:
rclpy.spin_once(node, timeout_sec=0.1)
# RViz lifecycle clients can share a manager's node name; only actual servers conflict.
conflicts = sorted(name for name, service in CONFLICT_SERVICES.items()
if node.get_servers_info_by_service(service))
if conflicts:
print('[Nav2] 启动拒绝:当前 ROS_DOMAIN_ID='+os.environ['ROS_DOMAIN_ID']+
' 已有导航/定位节点:'+', '.join(conflicts)+
'。请先正常退出旧启动入口,或为独立仿真显式选择其他 ROS_DOMAIN_ID;未终止任何进程。',
flush=True)
return 1
return 0
def complete_endpoint(info):
# Request/reply endpoints must belong to the same participant, not a stale mixed pair.
return (info.endpoint_count == 2 and len(info.endpoint_gids) == 2
and all(len(gid) >= 12 for gid in info.endpoint_gids)
and info.endpoint_gids[0][:12] == info.endpoint_gids[1][:12])
def lifecycle_discovery_gaps(node, managed):
gaps = []
for name in managed:
for service in ('get_state', 'change_state'):
topic = f'/{name}/{service}'
servers = node.get_servers_info_by_service(topic)
clients = node.get_clients_info_by_service(topic)
if not any(info.node_name == name and complete_endpoint(info) for info in servers):
gaps.append(topic+' server')
if not any(info.node_name == 'lifecycle_manager_nav2' and complete_endpoint(info)
for info in clients):
gaps.append(topic+' manager client')
return gaps
def wait_active(node, timeout, activate=False, result_path=None):
started = time.monotonic()
deadline = started+timeout
parameter = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
active = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
path = node.create_client(IsPathValid, '/is_path_valid')
control = node.create_client(ManageLifecycleNodes, '/lifecycle_manager_nav2/manage_nodes') if activate else None
startup_future = None
discovery_since = None
discovery_gaps = []
managed = []
states = {}
observed = {}
clients = {}
pending = {}
errors = []
manager_failed = False
failed_at = None
manager_active = False
path_responded = False
path_discovered = False
stable_since = None
last_poll = 0.0
def on_log(message):
nonlocal manager_failed, failed_at
if message.level >= Log.ERROR and ('bt_navigator' in message.name
or 'lifecycle_manager' in message.name):
errors.append(message.name+': '+message.msg)
del errors[:-8]
if 'Failed to bring up all requested nodes' in message.msg:
manager_failed = True
failed_at = time.monotonic()
subscription = node.create_subscription(Log, '/rosout', on_log, 100)
def submit(key, client, request):
if key not in pending and client.service_is_ready():
pending[key] = (client, client.call_async(request), time.monotonic())
def finish(code):
# Let already-sent queries complete before destroying the clients.
until = time.monotonic()+0.5
while (rclpy.ok() and time.monotonic() < until
and any(not future.done() for _, future, _ in pending.values())):
rclpy.spin_once(node, timeout_sec=0.02)
for client, future, _ in pending.values():
if not future.done():
client.remove_pending_request(future)
if result_path is not None:
result_path.write_text(json.dumps({
'passed': code == 0, 'states': states,
'retryable': (code != 0 and not manager_active
and states.get('bt_navigator') in (1, 2)
and time.monotonic()-observed.get('bt_navigator', 0.0) < 2.5),
**failure_details(managed, states, path_discovered, path_responded, errors)},
ensure_ascii=False, indent=2))
return code
print('[Nav2] 等待 Nav2 激活(全部受管节点 ACTIVE、管理器就绪、/is_path_valid 响应)', flush=True)
while rclpy.ok() and time.monotonic() < deadline:
rclpy.spin_once(node, timeout_sec=0.05)
now = time.monotonic()
for key, (client, future, stamp) in list(pending.items()):
if not future.done() and now-stamp < 2:
continue
response = future.result() if future.done() and not future.cancelled() else None
if not future.done():
client.remove_pending_request(future)
del pending[key]
observed[key] = now if response is not None else 0.0
if key == 'parameters':
if response and response.values:
managed = list(response.values[0].string_array_value)
for name in managed:
if name not in clients:
clients[name] = node.create_client(GetState, f'/{name}/get_state')
elif key == 'manager':
manager_active = bool(response and response.success)
elif key == 'path':
# Collision validity is distinct from request/response availability.
path_responded = response is not None
else:
states[key] = response.current_state.id if response else None
if now-last_poll >= 0.5:
last_poll = now
if not managed:
submit('parameters', parameter, GetParameters.Request(names=['node_names']))
submit('manager', active, Trigger.Request())
path_discovered = path.service_is_ready()
# The planner costmap does not run before activation.
if states.get('planner_server') == 3:
submit('path', path, path_probe_request())
for name, client in clients.items():
if not client.service_is_ready() or now-observed.get(name, 0.0) > 2.5:
states[name] = None
submit(name, client, GetState.Request())
if not active.service_is_ready() or now-observed.get('manager', 0.0) > 2.5:
manager_active = False
if not path_discovered or now-observed.get('path', 0.0) > 2.5:
path_responded = False
if activate and startup_future is None:
discovery_gaps = lifecycle_discovery_gaps(node, managed) if managed else ['manager node list']
warmed = (bool(managed) and not discovery_gaps and control.service_is_ready()
and observed.get('manager', 0.0) > 0
and all(states.get(name) == 1 for name in managed))
if warmed:
if discovery_since is None:
discovery_since = now
if now-discovery_since >= 1:
print('[Nav2] 状态服务已响应、管理器状态切换端点完整,发起 STARTUP', flush=True)
startup_future = control.call_async(ManageLifecycleNodes.Request(
command=ManageLifecycleNodes.Request.STARTUP))
else:
discovery_since = None
if startup_future is not None and startup_future.done():
response = startup_future.result()
if response is None or not response.success:
errors.append('lifecycle_manager_nav2: STARTUP returned failure')
manager_failed = True
if failed_at is None:
failed_at = now
if manager_failed:
# Obtain a fresh navigator state after its failed activation callback returns.
# Recovery is permitted only if the navigator is definitely not ACTIVE.
if observed.get('bt_navigator', 0.0) > failed_at or now-failed_at > 2.5:
break
continue
if ready(managed, states, manager_active, path_responded):
if stable_since is None:
stable_since = now
if now-stable_since >= 1:
print(f'[Nav2] Nav2 就绪:{len(managed)} 个受管节点 ACTIVE,'
f'/is_path_valid 已响应,耗时 {now-started:.2f}s', flush=True)
return finish(0)
else:
stable_since = None
_ = subscription
print('[Nav2] 激活失败:'+json.dumps(failure_details(
managed, states, path_discovered, path_responded, errors), ensure_ascii=False), flush=True)
if discovery_gaps and startup_future is None:
print('[Nav2] 尚未完成发现的生命周期端点:'+', '.join(discovery_gaps), flush=True)
return finish(1)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--preflight', action='store_true')
parser.add_argument('--activate', action='store_true',
help='call manager STARTUP once, after lifecycle discovery is ready (requires autostart=False)')
parser.add_argument('--result', type=Path)
parser.add_argument('--timeout', type=float, default=120)
parser.add_argument('--discovery-seconds', type=float, default=3)
args = parser.parse_args()
if args.timeout <= 0 or args.discovery_seconds <= 0:
parser.error('timeouts must be positive')
os.environ.update(defaults(os.environ))
print('[DDS] '+describe(os.environ), flush=True)
rclpy.init(args=[])
node = rclpy.create_node('sentry_nav2_preflight' if args.preflight else 'sentry_nav2_readiness')
print('[DDS] actual RMW='+get_rmw_implementation_identifier(), flush=True)
try:
return preflight(node, args.discovery_seconds) if args.preflight else wait_active(
node, args.timeout, args.activate, args.result)
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
raise SystemExit(main())
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Resolve ROS 2 package include directories through the ament index."""
import argparse
import os
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
def get_prefixes(explicit_prefix: str) -> list[Path]:
"""Build an ordered list of ROS installation prefixes."""
raw = [explicit_prefix]
raw.extend(os.environ.get("AMENT_PREFIX_PATH", "").split(os.pathsep))
prefixes = []
seen = set()
for item in raw:
if not item:
continue
path = Path(item).resolve()
if path.is_dir() and path not in seen:
prefixes.append(path)
seen.add(path)
return prefixes
def find_package(name: str, prefixes: list[Path]):
"""Find a package through the ament resource index."""
for prefix in prefixes:
marker = (
prefix
/ "share/ament_index/resource_index/packages"
/ name
)
manifest = prefix / "share" / name / "package.xml"
if marker.is_file():
if not manifest.is_file():
raise RuntimeError(
f"Package '{name}' is indexed but package.xml "
f"is missing: {manifest}"
)
return prefix, manifest
return None
def get_dependencies(manifest: Path) -> list[str]:
"""Read compile-relevant dependencies from package.xml."""
root = ET.parse(manifest).getroot()
dependency_tags = {
"depend",
"build_depend",
"build_export_depend",
"buildtool_export_depend",
}
dependencies = set()
for element in root:
tag = element.tag.split("}")[-1]
if tag not in dependency_tags:
continue
name = (element.text or "").strip()
if name:
dependencies.add(name)
return sorted(dependencies)
def resolve(roots: list[str], prefixes: list[Path]) -> list[Path]:
"""Recursively resolve packages and collect include directories."""
visited = set()
include_dirs = []
include_seen = set()
def add_include(path: Path):
path = path.resolve()
if path.is_dir() and path not in include_seen:
include_dirs.append(path)
include_seen.add(path)
def visit(name: str, is_root: bool = False):
if name in visited:
return
visited.add(name)
result = find_package(name, prefixes)
if result is None:
message = f"Package '{name}' not found in ament index"
if is_root:
raise RuntimeError(message)
print(f"[WARN] {message}", file=sys.stderr)
return
prefix, manifest = result
# Common ROS installation include directory.
add_include(prefix / "include")
# ROS packages commonly install headers under include/<package>.
add_include(prefix / "include" / name)
print(f"[ROS DEP] {name}", file=sys.stderr)
for dependency in get_dependencies(manifest):
visit(dependency)
for root in roots:
visit(root, is_root=True)
return include_dirs
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--prefix", required=True)
parser.add_argument("--roots", required=True)
args = parser.parse_args()
roots = [item for item in args.roots.split(",") if item]
prefixes = get_prefixes(args.prefix)
if not prefixes:
raise RuntimeError("No valid ROS installation prefixes found")
include_dirs = resolve(roots, prefixes)
for directory in include_dirs:
print(directory)
if __name__ == "__main__":
try:
main()
except Exception as error:
print(f"[ERROR] {error}", file=sys.stderr)
sys.exit(1)
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Supervise only our Nav2 process group; bounded recovery before navigation becomes active."""
import argparse
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
def stop_owned(process):
if process is None:
return
# Each child is started in a new session. No process-name matching or shared-memory cleanup.
for signum, timeout in ((signal.SIGINT, 8), (signal.SIGTERM, 2), (signal.SIGKILL, 1)):
try:
os.killpg(process.pid, signum)
except ProcessLookupError:
break
deadline = time.monotonic()+timeout
while time.monotonic() < deadline:
process.poll()
try:
os.killpg(process.pid, 0)
except ProcessLookupError:
return
time.sleep(0.05)
process.poll()
def supervise(command, checker, attempts, timeout):
navigation = None
observer = None
try:
with tempfile.TemporaryDirectory(prefix='sentry-nav2-') as directory:
for attempt in range(1, attempts+1):
result_path = Path(directory)/f'{attempt}.json'
print(f'[Nav2 supervisor] startup attempt {attempt}/{attempts}', flush=True)
navigation = subprocess.Popen(command, start_new_session=True)
observer = subprocess.Popen(
checker+['--activate', '--timeout', str(timeout), '--result', str(result_path)],
start_new_session=True)
while navigation.poll() is None and observer.poll() is None:
time.sleep(0.1)
if navigation.poll() is not None:
print('[Nav2 supervisor] Nav2 process exited before readiness; aborting', flush=True)
return 1
result = json.loads(result_path.read_text()) if result_path.is_file() else {}
if observer.returncode == 0 and result.get('passed'):
print(f'[Nav2 supervisor] ready on attempt {attempt}; startup recovery disabled', flush=True)
return navigation.wait()
stop_owned(observer)
observer = None
stop_owned(navigation)
navigation = None
if not result.get('retryable') or attempt == attempts:
print('[Nav2 supervisor] startup failed; no further retry (navigator active/unknown, '
'or attempt limit reached)', flush=True)
return 1
print('[Nav2 supervisor] navigator confirmed UNCONFIGURED/INACTIVE; '
'recreating only owned Nav2 processes. LIO/Gazebo continue running.', flush=True)
return 1
finally:
stop_owned(observer)
stop_owned(navigation)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--attempts', type=int, default=3)
parser.add_argument('--timeout', type=float, default=120)
parser.add_argument('launch_arguments', nargs=argparse.REMAINDER)
args = parser.parse_args()
if args.attempts < 1 or args.attempts > 3 or args.timeout <= 0:
parser.error('attempts must be 1..3; timeout must be positive')
arguments = args.launch_arguments
if arguments and arguments[0] == '--':
arguments = arguments[1:]
if not arguments:
parser.error('Nav2 bringup arguments required after --')
def interrupted(signum, frame):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
raise KeyboardInterrupt
signal.signal(signal.SIGINT, interrupted)
signal.signal(signal.SIGTERM, interrupted)
try:
return supervise(['ros2', 'launch', 'nav2_bringup', 'bringup_launch.py', *arguments],
[sys.executable, str(Path(__file__).with_name('nav2_startup.py'))],
args.attempts, args.timeout)
except KeyboardInterrupt:
return 130
if __name__ == '__main__':
raise SystemExit(main())
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Exit successfully only after simulation clock and basic robot TF are available."""
import time
import rclpy
from rclpy.node import Node
from rclpy.parameter import Parameter
from rclpy.time import Time
from tf2_ros import Buffer, TransformListener
def main():
rclpy.init()
node = Node('wait_navigation_ready', parameter_overrides=[Parameter('use_sim_time', value=True)])
buffer = Buffer(node=node)
listener = TransformListener(buffer, node)
result = 1
try:
deadline = time.monotonic()+180
while rclpy.ok() and time.monotonic() < deadline:
rclpy.spin_once(node, timeout_sec=0.1)
if (node.get_clock().now().nanoseconds > 0
and buffer.can_transform('odom', 'base_link', Time())
and buffer.can_transform('base_link', 'lidar_link', Time())):
print('simulation clock and odom/base/lidar TF ready', flush=True)
result = 0
break
if result:
print('simulation clock/TF readiness timeout', flush=True)
finally:
_ = listener
node.destroy_node()
rclpy.shutdown()
return result
if __name__ == '__main__':
raise SystemExit(main())