feat(localization): integrate LIO ROS TF, replay and validated AMCL replacement

GCC 15.2 C++23 clean rebuild: zero warnings. All 11 xmake test suites pass. Independent 120 s Gazebo replay: ATE 0.005279 m / 0.191335 deg; 1 s RPE 0.005358 m / 0.099086 deg. Both startup entry points validate Nav2 activation, no AMCL, and a single map-to-odom publisher.
This commit is contained in:
mzx committed 2026-11-22 01:44:36 +08:00
1 parent 55e9456e4a
commit b833e6f658
30 files changed
+1314 -329

No files matched your search

+178
View File
@@ -0,0 +1,178 @@
#!/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.flmap
python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map generated/field.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
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, '/model/sentry/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, default=120)
args = parser.parse_args()
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')
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',
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))
processes = []
log_handles = []
rclpy.init()
driver = Driver(args.profile)
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}'],
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
driver.drive(now-start)
if 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 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:
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()
+15 -6
View File
@@ -37,7 +37,6 @@ from tf2_ros import Buffer, TransformListener
# 只报了 7 个节点的状态 —— 一眼看不出问题其实出在定位那一组。
EXPECTED_ACTIVE = [
'map_server',
'amcl',
'controller_server',
'planner_server',
'smoother_server',
@@ -164,9 +163,14 @@ def main():
return None, '调用超时'
return fut.result().current_state, None
# Give DDS discovery a chance before choosing the expected localization branch.
for _ in range(10):
rclpy.spin_once(node, timeout_sec=0.1)
names_now = set(node.get_node_names())
expected_active = EXPECTED_ACTIVE + (['amcl'] if 'amcl' in names_now else [])
# ---------- 1. 生命周期 ----------
print('=== 1. 生命周期状态 ===')
for name in EXPECTED_ACTIVE:
for name in expected_active:
st, err = active(name)
if st is None:
print(' %-20s ❌ %s' % (name, err))
@@ -177,6 +181,12 @@ def main():
print(' %-20s ⚠️ %s' % (name, st.label))
problems.append(f'{name} 是 {st.label},不是 ACTIVE')
names_now = set(node.get_node_names())
if 'field_localization' in names_now and 'amcl' in names_now:
problems.append('LIO 与 AMCL 同时运行;检查 map->odom 发布者互斥')
elif 'amcl' not in names_now and 'field_localization' not in names_now:
problems.append('LIO / AMCL 定位器均未发现')
# ---------- 1.5 节点总览:定位"卡在谁身上" ----------
# 光看生命周期状态不够 —— 如果某个节点**压根没起来**,
# 上面只会说"服务不存在",看不出是谁没被编排。这里把家底列出来。
@@ -193,14 +203,14 @@ def main():
else:
print(' 生命周期管理器: ❌ 一个都没有(Nav2 不会自己配置)')
problems.append('没有 lifecycle_manager 在跑')
missing = [n for n in EXPECTED_ACTIVE if n not in names]
missing = [n for n in expected_active if n not in names]
if missing:
print(f' ⚠️ 期望存在但没起: {", ".join(missing)}')
for n in missing:
problems.append(f'{n} 没在跑')
extra = [n for n in names
if any(k in n for k in ('amcl', 'server', 'navigator', 'manager'))
and n not in EXPECTED_ACTIVE and 'lifecycle_manager' not in n]
and n not in expected_active and 'lifecycle_manager' not in n]
if extra:
print(f' 其他相关节点: {", ".join(extra)}')
else:
@@ -295,8 +305,7 @@ def main():
print(' [TF] map -> base_link (%.3f, %.3f)' % tf_pos)
print(' [偏差] %.3f m %s' % (dev, flag))
if dev >= 0.05:
note = ('现在定位是"作弊"的(静态 map->odom + 轮速里程计),'
'偏差会随时间累积且不自愈')
note = '定位与 Gazebo 独立真值存在偏差;检查定位状态与传感器时间同步'
print(' %s' % note)
problems.append('TF 位置与 Gazebo 真值差 %.2f m' % dev)
+1 -1
View File
@@ -38,7 +38,7 @@ import sys
from pathlib import Path
# xmake 会产出的可执行文件,用来反推产物目录。
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf')
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'field_localization_node')
# 系统 gz 的常见安装位置(按优先级)。
_GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz')
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Live integration check: isolated Gazebo + LIO + Nav2, no motion commands."""
import argparse
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 lifecycle_msgs.srv import GetState
from tf2_msgs.msg import TFMessage
NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server',
'bt_navigator', 'behavior_server', 'waypoint_follower', 'velocity_smoother',
'collision_monitor']
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--map', type=Path, required=True)
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
if not args.map.is_file():
parser.error('map missing')
args.output.mkdir(parents=True, exist_ok=True)
session = uuid.uuid4().hex[:12]
os.environ.update(ROS_DOMAIN_ID=str(50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
FASTDDS_BUILTIN_TRANSPORTS='UDPv4', ROS2CLI_DISABLE_DAEMON='1',
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
LIO_MAP=str(args.map.resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
workspace = Path(__file__).resolve().parents[1]
log = None
if args.launcher == 'shell':
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
else:
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
log = open(args.output/'stack.log', 'w', encoding='utf8')
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
rclpy.init()
node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)])
publishers = set()
counts = {'map_to_odom': 0, 'map_to_base_link': 0}
def on_tf(msg, info):
for transform in msg.transforms:
if transform.header.frame_id != 'map':
continue
if transform.child_frame_id == 'odom':
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
publishers.add(json.dumps(gid, sort_keys=True, default=str))
counts['map_to_odom'] += 1
if transform.child_frame_id == 'base_link':
counts['map_to_base_link'] += 1
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
states = {}
try:
deadline = time.monotonic()+120
last_check = 0.0
stable_since = None
manager_completed = False
while time.monotonic() < deadline:
rclpy.spin_once(node, timeout_sec=0.1)
if process.poll() is not None:
raise RuntimeError('stack exited')
if time.monotonic()-last_check < 0.5:
continue
last_check = time.monotonic()
for name, client in clients.items():
if not client.service_is_ready():
continue
future = client.call_async(GetState.Request())
rclpy.spin_until_future_complete(node, future, timeout_sec=1)
if future.done() and future.result():
states[name] = future.result().current_state.id
log_path = args.output/'stack.log'
text = log_path.read_text(errors='replace') if log_path.exists() else ''
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
for line in text.splitlines())
if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed:
if stable_since is None:
stable_since = time.monotonic()
if time.monotonic()-stable_since >= 2:
break
else:
stable_since = None
names = sorted(set(node.get_node_names()))
result = {'launcher': args.launcher, 'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
result['passed'] = (manager_completed and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
and counts['map_to_base_link'] == 0)
(args.output/'result.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result, indent=2), flush=True)
if not result['passed']:
raise RuntimeError('stack integration validation failed')
finally:
_ = subscription
if process.poll() is None:
os.killpg(process.pid, signal.SIGINT)
try:
process.wait(timeout=20)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
if log:
log.close()
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
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())