"""Robot abstraction and closed-loop motion primitives.
A concrete robot only provides pose feedback and a velocity command (``_command(v, w)``); navigation
to map goals can additionally be delegated to a navigation stack. The primitives here turn the
action parameters into velocity profiles Lambda: (A_n(phi_n), V_s) -> {(v(t), w(t))}, closing the
loop on odometry so that distances and angles are reached regardless of latency or wheel slip, with
trapezoidal acceleration limits and timeouts. All primitives are interruptible.
"""
from __future__ import annotations
import logging
import math
import threading
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass
from ..config import ControlSettings, MotionLimits
from ..types import Pose2D, wrap_angle
log = logging.getLogger(__name__)
[docs]
@dataclass
class MotionResult:
success: bool
reason: str = ""
reported: bool = False # the user was already told about a failure
CANCELLED = MotionResult(False, "cancelled")
[docs]
class Robot(ABC):
"""Base class. Subclasses implement ``pose``, ``_command`` and optionally ``odometry``,
``_sleep``, ``navigate_to`` and ``close``."""
has_navigation_stack: bool = False
def __init__(self, limits: MotionLimits, control: ControlSettings):
self.limits = limits
self.control = control
self._halt = threading.Event()
# ------------------------------------------------------------ interface
[docs]
@abstractmethod
def pose(self) -> Pose2D:
"""Pose in the map frame (used for reporting and global goals)."""
[docs]
def odometry(self) -> Pose2D:
"""Smooth, locally consistent pose used to close motion loops."""
return self.pose()
@abstractmethod
def _command(self, v: float, w: float) -> None:
"""Send a body velocity: v in m/s (forward), w in rad/s (counter-clockwise)."""
def _sleep(self, dt: float) -> None:
"""Wait one control period (the simulator advances its physics here)."""
time.sleep(dt)
def _now(self) -> float:
"""Clock used for timeouts (the simulator uses simulated time)."""
return time.monotonic()
[docs]
def close(self) -> None: # noqa: B027 - optional hook
"""Release connections."""
# --------------------------------------------------------------- control
[docs]
def stop(self) -> None:
"""Emergency stop: interrupts any running primitive and zeroes velocity."""
self._halt.set()
self._command(0.0, 0.0)
def _cancelled(self, cancel: threading.Event | None) -> bool:
return self._halt.is_set() or bool(cancel and cancel.is_set())
def _begin(self) -> None:
self._halt.clear()
@property
def _dt(self) -> float:
return 1.0 / self.control.rate_hz
# ------------------------------------------------------------ primitives
[docs]
def move(
self, distance: float, speed: float, cancel: threading.Event | None = None
) -> MotionResult:
"""Drive ``distance`` metres along the current heading (negative = backward)."""
self._begin()
speed = abs(speed)
start = self.odometry()
heading = (math.cos(start.yaw), math.sin(start.yaw))
target = abs(distance)
sign = 1.0 if distance >= 0 else -1.0
deadline = self._deadline(target / speed + speed / self.limits.linear_accel)
v = 0.0
while True:
if self._cancelled(cancel):
self._command(0.0, 0.0)
return CANCELLED
p = self.odometry()
travelled = sign * ((p.x - start.x) * heading[0] + (p.y - start.y) * heading[1])
remaining = target - travelled
if remaining <= v * self._dt / 2: # the next period would overshoot
break
if self._now() > deadline:
self._command(0.0, 0.0)
return MotionResult(False, f"timeout after {travelled:.2f} of {target:.2f} m")
v = _trapezoid(
v,
speed,
remaining,
self.limits.linear_accel,
self._dt,
floor=min(self.limits.linear_speed_min, speed),
)
# Hold the initial heading while driving straight.
w = self.control.heading_gain * wrap_angle(start.yaw - p.yaw)
self._command(sign * v, w)
self._sleep(self._dt)
self._command(0.0, 0.0)
return MotionResult(True)
[docs]
def turn(
self, angle: float, angular_speed: float, cancel: threading.Event | None = None
) -> MotionResult:
"""Rotate in place by ``angle`` radians (positive = counter-clockwise)."""
self._begin()
w_max = abs(angular_speed)
accel = math.radians(self.limits.angular_accel_deg)
target = abs(angle)
sign = 1.0 if angle >= 0 else -1.0
deadline = self._deadline(target / w_max + w_max / accel)
last = self.odometry().yaw
turned = 0.0
w = 0.0
while True:
if self._cancelled(cancel):
self._command(0.0, 0.0)
return CANCELLED
yaw = self.odometry().yaw
turned += sign * wrap_angle(yaw - last) # unwrapped, supports > 360 deg
last = yaw
remaining = target - turned
if remaining <= w * self._dt / 2:
break
if self._now() > deadline:
self._command(0.0, 0.0)
return MotionResult(False, "timeout while turning")
w = _trapezoid(
w,
w_max,
remaining,
accel,
self._dt,
floor=min(math.radians(self.control.min_angular_speed_deg), w_max),
)
self._command(0.0, sign * w)
self._sleep(self._dt)
self._command(0.0, 0.0)
return MotionResult(True)
[docs]
def arc(
self,
radius: float,
angle: float,
speed: float,
left: bool,
cancel: threading.Event | None = None,
) -> MotionResult:
"""Drive along a circle of ``radius`` m sweeping ``angle`` rad."""
self._begin()
speed = abs(speed)
sign = 1.0 if left else -1.0
target = abs(angle)
deadline = self._deadline(radius * target / speed + speed / self.limits.linear_accel)
last = self.odometry().yaw
swept = 0.0
v = 0.0
while True:
if self._cancelled(cancel):
self._command(0.0, 0.0)
return CANCELLED
yaw = self.odometry().yaw
swept += sign * wrap_angle(yaw - last)
last = yaw
remaining = target - swept
if remaining * radius <= v * self._dt / 2:
break
if self._now() > deadline:
self._command(0.0, 0.0)
return MotionResult(False, "timeout while driving the arc")
v = _trapezoid(
v,
speed,
remaining * radius,
self.limits.linear_accel,
self._dt,
floor=min(self.limits.linear_speed_min, speed),
)
self._command(v, sign * v / radius)
self._sleep(self._dt)
self._command(0.0, 0.0)
return MotionResult(True)
def wait(self, seconds: float, cancel: threading.Event | None = None) -> MotionResult:
self._begin()
self._command(0.0, 0.0)
end = self._now() + seconds
while self._now() < end:
if self._cancelled(cancel):
return CANCELLED
self._sleep(min(self._dt, max(0.0, end - self._now())))
return MotionResult(True)
[docs]
def face(
self, x: float, y: float, angular_speed: float, cancel: threading.Event | None = None
) -> MotionResult:
"""Turn towards a map point."""
delta = self.pose().bearing_to(x, y)
return self.turn(delta, angular_speed, cancel)
[docs]
def navigate_to(
self,
x: float,
y: float,
yaw: float | None,
speed: float,
cancel: threading.Event | None = None,
) -> MotionResult:
"""Reach a map goal. Default: face the goal, drive with heading correction, then align to
``yaw``. Robots with a navigation stack override this to get global planning and obstacle
avoidance."""
self._begin()
tol = self.control.goal_tolerance_m / 2.0
w_max = math.radians(self.limits.angular_speed_max_deg)
deadline = self._now() + self.control.navigation_timeout_s
p = self.pose()
if p.distance_to(x, y) > tol:
res = self.turn(p.bearing_to(x, y), w_max, cancel)
if not res.success:
return res
v = 0.0
while True:
if self._cancelled(cancel):
self._command(0.0, 0.0)
return CANCELLED
p = self.pose()
dist = p.distance_to(x, y)
if dist <= tol:
break
if self._now() > deadline:
self._command(0.0, 0.0)
return MotionResult(False, "navigation timeout")
err = p.bearing_to(x, y)
v = _trapezoid(
v,
speed,
dist,
self.limits.linear_accel,
self._dt,
floor=min(self.limits.linear_speed_min, speed),
)
v *= max(0.0, math.cos(err)) # slow down while the heading is off
w = max(-w_max, min(w_max, self.control.heading_gain * err))
self._command(v, w)
self._sleep(self._dt)
self._command(0.0, 0.0)
if yaw is not None:
res = self.turn(wrap_angle(yaw - self.pose().yaw), w_max, cancel)
if not res.success:
return res
return MotionResult(True)
# --------------------------------------------------------------- helpers
def _deadline(self, nominal_s: float) -> float:
return self._now() + self.control.timeout_factor * nominal_s + 2.0
def _trapezoid(
current: float, v_max: float, remaining: float, accel: float, dt: float, floor: float
) -> float:
"""Next speed of a trapezoidal profile: accelerate, cruise, then brake so that
the robot stops at the target (v^2 = 2 a s)."""
braking = math.sqrt(max(0.0, 2.0 * accel * remaining))
return max(floor, min(v_max, current + accel * dt, braking))