Files
NODEDC_MISSION_CORE/simulation/ai-polygon/nav2/ros_navigation.py
T

342 lines
17 KiB
Python

"""ROS action/message boundary; upstream Nav2 owns paths and velocity proposals.
The caller spins this node and owns observation/command leases. Repeating TF
uses the original measurement stamp. FollowPath updates use Nav2's native
preemption within one caller-bound route context. A new motion task requires
fresh action feedback before command admission resumes.
"""
import math
import threading
import time
from collections import deque
from action_msgs.msg import GoalStatus
from builtin_interfaces.msg import Duration
from geometry_msgs.msg import TransformStamped, Twist
from lifecycle_msgs.msg import Transition
from lifecycle_msgs.srv import ChangeState
from nav2_msgs.action import BackUp, ComputePathToPose, FollowPath, Spin
from nav2_msgs.msg import Costmap
from nav_msgs.msg import Odometry
from rclpy.action import ActionClient
from rclpy.node import Node
from rclpy.parameter import Parameter
from rosgraph_msgs.msg import Clock
from rclpy.time import Time
from tf2_ros import TransformBroadcaster
def yaw_of(pose):
x, y, z, w = pose[3:]
return math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
class RosNavigation(Node):
def __init__(self, *, simulation_clock=False):
super().__init__('missioncore_nav2_adapter', parameter_overrides=[
Parameter('use_sim_time', value=simulation_clock)])
self.simulation_clock = simulation_clock
self.clock_publisher = self.create_publisher(Clock, '/clock', 1) if simulation_clock else None
self.condition = threading.Condition()
self.action_lock = threading.Lock()
self.pose = None
self.costmaps = {}
self.last_planner_diagnostic = None
for name in ("global_costmap", "local_costmap"):
self.create_subscription(Costmap, "/"+name+"/costmap_raw",
lambda value, owner=name: self.receive_costmap(owner, value), 1)
self.action_handle = self.terminal = self.latest_command = None
self.command_sequence = 0
self.action_sequence = 0
self.last_zero_sequence = 0
self.failed = False
self.pending_feedback = None
self.history = deque(maxlen=256)
self.tf = TransformBroadcaster(self)
self.odom = self.create_publisher(Odometry, '/odom', 5)
self.create_timer(.02, self.publish_pose)
self.active_source = None
for source in ('controller', 'behavior'):
self.create_subscription(Twist, '/nav2/'+source+'_cmd_vel',
lambda value, owner=source: self.on_command(value, owner), 20)
self.planner = ActionClient(self, ComputePathToPose, '/compute_path_to_pose')
self.controller = ActionClient(self, FollowPath, '/follow_path')
self.spin_client = ActionClient(self, Spin, '/spin')
self.backup_client = ActionClient(self, BackUp, '/backup')
def receive_costmap(self, name, message):
metadata = message.metadata
if metadata.size_x * metadata.size_y != len(message.data) or len(message.data) > 320*320:
return # Bounded read-only diagnostics; never a planning input.
receipt = dict(received_at=time.monotonic(), frame_id=message.header.frame_id,
stamp_ns=message.header.stamp.sec*1_000_000_000+message.header.stamp.nanosec,
resolution=metadata.resolution, width=metadata.size_x, height=metadata.size_y,
origin=[metadata.origin.position.x, metadata.origin.position.y],
data=list(message.data))
with self.condition:
self.costmaps[name] = receipt
def diagnostic(self):
with self.condition:
return dict(costmaps=dict(self.costmaps), last_planner=self.last_planner_diagnostic)
@staticmethod
def await_result(future, timeout):
done = threading.Event()
future.add_done_callback(lambda _: done.set())
if not done.wait(timeout):
raise TimeoutError('Nav2 response timeout')
return future.result()
def activate(self):
for name in ('planner_server', 'controller_server', 'behavior_server'):
client = self.create_client(ChangeState, '/' + name + '/change_state')
try:
if not client.wait_for_service(timeout_sec=8):
raise TimeoutError(name + ' unavailable')
for transition in (Transition.TRANSITION_CONFIGURE, Transition.TRANSITION_ACTIVATE):
request = ChangeState.Request()
request.transition.id = transition
if not self.await_result(client.call_async(request), 8).success:
raise RuntimeError(name + ' lifecycle transition failed')
finally:
self.destroy_client(client)
for client in (self.planner, self.controller, self.spin_client, self.backup_client):
if not client.wait_for_server(timeout_sec=2):
raise TimeoutError('Nav2 action unavailable')
def observe_pose(self, pose, age, twist=None, simulation_time_ns=None):
if (len(pose) != 7 or (twist is not None and len(twist) != 3)
or not all(math.isfinite(float(v)) for v in (*pose, *(twist or []), age))
or age < 0 or abs(sum(v*v for v in pose[3:])-1) > .02):
raise ValueError('Invalid measured odometry')
now = time.monotonic()
if self.simulation_clock:
if type(simulation_time_ns) is not int or not 0 <= simulation_time_ns < 2**63:
raise ValueError('Measured simulation time is required for odometry')
stamp = simulation_time_ns
else:
stamp = self.get_clock().now().nanoseconds-int(age*1e9)
if stamp < 0:
raise ValueError('Invalid odometry stamp')
with self.condition:
captured = now-age
if self.pose is not None and (captured < self.pose[0] or stamp < self.pose[3]):
return # Delayed delivery cannot rewind TF or the episode clock.
self.pose = (captured, tuple(pose), tuple(twist) if twist is not None else None, stamp)
if self.clock_publisher is not None:
# Physics owns time. Repeated measurements at pause never advance
# it; HTTP age and all transport/action waits remain wall time.
self.clock_publisher.publish(Clock(clock=Time(nanoseconds=stamp).to_msg()))
self.publish_pose()
def observation_stamp(self, seconds, wall_age):
if self.simulation_clock:
if not math.isfinite(seconds) or seconds < 0:
raise ValueError('Invalid observed simulation time')
return Time(nanoseconds=round(seconds*1e9)).to_msg()
return Time(nanoseconds=self.get_clock().now().nanoseconds-int(wall_age*1e9)).to_msg()
def publish_pose(self):
with self.condition:
measured = self.pose
if measured is None or time.monotonic()-measured[0] > .5:
return
_, pose, twist, stamp = measured
yaw = yaw_of(pose)
transform = TransformStamped()
transform.header.frame_id, transform.child_frame_id = 'map', 'base_link'
transform.header.stamp = Time(nanoseconds=stamp).to_msg()
transform.transform.translation.x, transform.transform.translation.y = map(float, pose[:2])
transform.transform.rotation.z, transform.transform.rotation.w = math.sin(yaw/2), math.cos(yaw/2)
self.tf.sendTransform(transform)
if twist is None:
return # A bootstrap pose is not a measured zero velocity.
odom = Odometry()
odom.header, odom.child_frame_id = transform.header, 'base_link'
odom.pose.pose.position.x, odom.pose.pose.position.y = map(float, pose[:2])
odom.pose.pose.orientation = transform.transform.rotation
odom.twist.twist.linear.x, odom.twist.twist.linear.y, odom.twist.twist.angular.z = map(float, twist)
self.odom.publish(odom)
def on_command(self, value, source):
command = (time.monotonic(), float(value.linear.x), float(value.angular.z))
with self.condition:
if source != self.active_source:
return
self.command_sequence += 1
self.history.append((self.command_sequence, *command))
if command[1:] == (0., 0.):
self.last_zero_sequence = self.command_sequence
if self.pending_feedback is None:
self.latest_command = command
self.condition.notify_all()
def plan(self, pose, goal, yaw):
request = ComputePathToPose.Goal()
request.planner_id, request.use_start = 'GridBased', True
for target, xy, heading in ((request.start, pose[:2], yaw_of(pose)),
(request.goal, goal[:2], yaw)):
target.header.frame_id, target.header.stamp = 'map', self.get_clock().now().to_msg()
target.pose.position.x, target.pose.position.y = map(float, xy)
target.pose.orientation.z, target.pose.orientation.w = math.sin(heading/2), math.cos(heading/2)
handle = self.accept(self.planner, request, .2)
if not handle.accepted:
raise RuntimeError('Nav2 planner rejected request')
try:
result = self.await_result(handle.get_result_async(), .65)
except TimeoutError:
# Do not leave work from a timed-out HTTP transaction as authority.
self.await_result(handle.cancel_goal_async(), .2)
raise
with self.condition:
self.last_planner_diagnostic = dict(completed_at=time.monotonic(),
start=list(pose), goal=list(goal), goal_yaw=yaw, status=result.status,
costmaps=dict(self.costmaps))
return (result.result.path if result.status == GoalStatus.STATUS_SUCCEEDED else None,
result.status)
def accept(self, client, request, timeout, feedback_callback=None):
if self.failed:
raise RuntimeError('Nav2 action boundary requires reset')
options = {} if feedback_callback is None else {'feedback_callback': feedback_callback}
future = client.send_goal_async(request, **options)
try:
return self.await_result(future, timeout)
except TimeoutError:
# A late action acceptance must not survive the failed transaction.
# The callback cannot block the ROS executor waiting for its reply.
with self.condition:
self.failed = True
self.active_source = self.latest_command = None
def cancel_late(done):
handle = done.result()
if handle is not None and handle.accepted:
handle.cancel_goal_async()
future.add_done_callback(cancel_late)
raise
def _stop(self):
if self.action_handle is None:
return
with self.condition:
self.pending_feedback = None
sequence = self.command_sequence
if not self.terminal.done():
self.await_result(self.action_handle.cancel_goal_async(), .25)
result = self.await_result(self.terminal, .4)
if result.status not in (GoalStatus.STATUS_CANCELED, GoalStatus.STATUS_SUCCEEDED,
GoalStatus.STATUS_ABORTED):
raise RuntimeError('Nav2 action did not terminate')
with self.condition:
if not self.condition.wait_for(lambda: self.last_zero_sequence > sequence, .25):
raise TimeoutError('Nav2 cancellation zero was not observed')
else:
with self.condition:
if not self.condition.wait_for(
lambda: self.last_zero_sequence > self.action_sequence, .25):
raise TimeoutError('Nav2 terminal zero was not observed')
self.action_handle = self.terminal = None
with self.condition:
self.active_source = None
self.latest_command = None
def stop(self):
with self.action_lock:
self._stop()
def _execute(self, client, request, source):
with self.action_lock:
self._stop()
with self.condition:
self.latest_command = None
self.active_source = source
sequence = self.command_sequence
self.action_sequence = sequence
self.action_handle = self.accept(client, request, .25)
if not self.action_handle.accepted:
self.action_handle = None
self.active_source = None
raise RuntimeError('Nav2 motion action rejected request')
self.terminal = self.action_handle.get_result_async()
with self.condition:
self.condition.wait_for(lambda: self.command_sequence > sequence
and self.latest_command is not None, .25)
return self.native_command()
def follow(self, path, *, continuing=False):
request = FollowPath.Goal()
request.path, request.controller_id, request.goal_checker_id = path, 'FollowPath', 'goal_checker'
with self.action_lock:
# The controller's updateGlobalPath accepts a pending FollowPath
# without zeroing velocity or resetting its progress checker.
# Spin/BackUp still require terminal cancellation and a zero.
if self.active_source != 'controller' or self.terminal is None or self.terminal.done():
self._stop()
continuing = False
token = object()
received = threading.Event()
with self.condition:
# Refining the path within the same caller-bound route context
# preserves its native stream. New tasks need fresh feedback.
self.pending_feedback = None if continuing else token
if not continuing:
self.latest_command = None
self.active_source = 'controller'
sequence = self.command_sequence
self.action_sequence = sequence
def feedback(_):
# Feedback is emitted only after updateGlobalPath and the
# new path's computeVelocityCommands in the pinned server.
with self.condition:
if continuing:
received.set()
elif self.pending_feedback is token:
self.pending_feedback = None
self.latest_command = None
received.set()
handle = self.accept(self.controller, request, .25, feedback)
if not handle.accepted:
with self.condition:
self.failed = True
self.active_source = self.latest_command = None
raise RuntimeError('Nav2 path update rejected')
self.action_handle, self.terminal = handle, handle.get_result_async()
if continuing:
# This continuing stream is already admitted during preemption.
# Waiting for its feedback only delays the next sensor frame;
# accept() still fences rejection and late action acceptance.
return self.native_command()
if not received.wait(.25):
# Do not bind a proposal to a path not yet used by Nav2.
# A later /control may use it once matching feedback arrives.
return self.native_command() if continuing else None
with self.condition:
self.condition.wait_for(lambda: self.command_sequence > sequence
and self.latest_command is not None, .25)
return self.native_command()
def spin(self, angle, duration):
if not math.isfinite(angle) or abs(angle) > math.pi or not math.isfinite(duration) or duration < 0:
raise ValueError('Invalid orientation goal')
request = Spin.Goal()
request.target_yaw = float(angle)
request.time_allowance = Duration(sec=int(duration), nanosec=int((duration%1)*1e9))
return self._execute(self.spin_client, request, 'behavior')
def backup(self, distance, speed, duration):
if (not all(math.isfinite(v) and v > 0 for v in (distance, speed))
or not math.isfinite(duration) or duration < 0):
raise ValueError('Invalid reverse goal')
request = BackUp.Goal()
request.target.x, request.speed = float(distance), float(speed)
request.time_allowance = Duration(sec=int(duration), nanosec=int((duration%1)*1e9))
return self._execute(self.backup_client, request, 'behavior')
def native_command(self):
with self.condition:
if (self.failed or self.pending_feedback is not None or self.action_handle is None
or self.terminal is None or self.terminal.done()):
return None
return self.latest_command