fix(nav): stop on invalid localization and enforce final velocity path
This commit is contained in:
1 parent
b772174c1c
commit
28ac7c488e
24 files changed
+1236
-161
No files matched your search
@@ -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())
|
||||
Reference in new issue
Block a user