Source code for reli.robot.sim

"""Kinematic differential-drive simulator (no ROS needed).

Physics advance inside ``_sleep``: each control period integrates the last velocity command exactly
along a unicycle arc and then waits ``dt / realtime_factor`` of wall time (no wait when the factor
is 0). Time is simulated, so runs are deterministic and can be faster than real time.
"""

from __future__ import annotations

import math
import threading
import time

from ..config import RobotConfig
from ..types import Pose2D, wrap_angle
from .base import Robot


[docs] class SimRobot(Robot): def __init__(self, cfg: RobotConfig): super().__init__(cfg.limits, cfg.control) s = cfg.sim.start_pose self._pose = Pose2D(s.x, s.y, math.radians(s.yaw_deg)) self._cmd = (0.0, 0.0) self._t = 0.0 self._factor = cfg.sim.realtime_factor self._lock = threading.Lock() def pose(self) -> Pose2D: with self._lock: return self._pose def set_pose(self, pose: Pose2D) -> None: with self._lock: self._pose = pose def _command(self, v: float, w: float) -> None: with self._lock: self._cmd = (v, w) def _now(self) -> float: with self._lock: return self._t def _sleep(self, dt: float) -> None: with self._lock: v, w = self._cmd p = self._pose if abs(w) < 1e-9: x = p.x + v * dt * math.cos(p.yaw) y = p.y + v * dt * math.sin(p.yaw) else: r = v / w x = p.x + r * (math.sin(p.yaw + w * dt) - math.sin(p.yaw)) y = p.y - r * (math.cos(p.yaw + w * dt) - math.cos(p.yaw)) self._pose = Pose2D(x, y, wrap_angle(p.yaw + w * dt)) self._t += dt if self._factor > 0: time.sleep(dt / self._factor)